diff --git a/.gitignore b/.gitignore index 26ab3c8d09..80f7631497 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,9 @@ +/*.ys /Cache/ /Meta/ /rosettacode.log +/entry +/pick +/random-clojure-task +/.clj-kondo/ +/.lsp/ diff --git a/Conf/lang.yaml b/Conf/lang.yaml index 298e845387..72c972e3d8 100644 --- a/Conf/lang.yaml +++ b/Conf/lang.yaml @@ -4,6 +4,7 @@ 360 Assembly: '.360' 4D: .4d 4DOS Batch: .4dos +4ME: .4me 6502 Assembly: '.6502' 68000 Assembly: '.68000' 6800 Assembly: '.6800' @@ -22,17 +23,19 @@ Acornsoft Lisp: .lisp Action!: .action ActionScript: .as Acurity Architect: .acurity -Ada: .ada -Agda: .agda +Ada: .adb +Adina: .adina Agda2: .agda2 +Agda: .agda Agena: .agena AHDL: .ahdl +AIDED NATURAL LANGUAGE: .aided Aikido: .aikido Aime: .aime Algae: .algae -ALGOL: .alg ALGOL 60: .alg ALGOL 68: .alg +ALGOL: .alg ALGOL-M: .alg ALGOL W: .alg Alice ML: .alice @@ -50,6 +53,7 @@ Anyways: .anyways Apex: .apex APL: .apl App Inventor: .app +Apple: .apple AppleScript: .applescript Applesoft BASIC: .basic Application Master: .app @@ -59,6 +63,8 @@ Arbre: .arbre Arc: .arc Arendelle: .arendelle Argile: .argile +Aria: .aria +ArkScript: .ark ARM Assembly: .arm ArnoldC: .arnoldc Arturo: .arturo @@ -68,7 +74,7 @@ ASP: .asp AspectC++: .acpp AspectJ: .aspectj ASP.Net: .asp -Assembly: .as +Assembly: .asm AssemblyScript: .asmscript Astro: .astro Asymptote: .asymptote @@ -77,15 +83,14 @@ ATS: .ats AutoHotkey: .ahk Autohotkey V2: .ahk AutoHotKey V2: .ahk -AutoIt: .autoit -AutoLISP: .l +AutoIt: .au3 +AutoLISP: .lsp Avail: .avail AWK: .awk Axe: .axe Axiom: .axiom Axum: .axum Ayrch: .ayrch -B: .b B4J: .b4j B4X: .b4x Babel: .pb @@ -94,12 +99,13 @@ BaCon: .bacon Bait: .bait Ballerina: .ballerina Bas: .bas -BASIC: .basic Basic09: .basic BASIC256: .basic +BASIC: .basic Batari Basic: .basic Batch File: .bat Battlestar: .battlestar +B: .b BBC BASIC: .basic Bc: .bc BCPL: .bcpl @@ -107,6 +113,7 @@ Beads: .beads Beef: .beef Beeswax: .beeswax Befunge: .bf +Berkeley Logo: .logo Beta: .beta Biferno: .biferno Binary Lambda Calculus: .blc @@ -130,23 +137,26 @@ Brat: .brat Brlcad: .brlcad Bruijn: .bruijn Burlesque: .blq -C++: .cpp -C: .c C0H: .c0h C1R: .c1r C2: .c2 C3: .c3 CafeOBJ: .cafeobj +Calc: .calc +Calcscript: .calc Caml: .caml Casio BASIC: .basic Cat: .cat CB80: .cb80 +CBASIC: .basic +C: .c C++/CLI: .cpp +C++: .cpp Cduce: .cduce Cecil: .cecil Ceylon: .ceylon CFEngine: .cfengine -Chapel: .chapel +Chapel: .chpl Chef: .chef Cherrycake: .cherrycake Chipmunk Basic: .basic @@ -155,6 +165,7 @@ ChucK: .chuck Cilk++: .cilk++ Cilk: .cilk Cind: .cind +CJam: .cjam Clarion: .clarion Clay: .clay Clean: .clean @@ -165,7 +176,7 @@ CLIPS: .clips Clojure: .clj CLU: .clu CMake: .cmake -COBOL: .cobol +COBOL: .cob Cobra: .cobra Coco: .coco Coconut: .coconut @@ -178,19 +189,19 @@ Common Lisp: .lisp Component Pascal: .pas Computer/zero Assembly: .0asm ContextFree: .cf +Convex: .convex Coq: .coq Corescript: .core Cowgol: .cowgol Crack: .crack Craft Basic: .basic Creative Basic: .basic -Curto: .curto -Crystal: .crystal +Crystal: .cr C sharp: .cs C Shell: .csh Cubescript: .cube Curry: .curry -D: .d +Curto: .curto Dafny: .dafny Dao: .dao Dart: .dart @@ -199,8 +210,9 @@ DataWeave: .dw DBL: .dbl Dc: .dc DCL: .dcl +D: .d DDNC: .ddnc -Delphi: .delphi +Delphi: .pas Deluge: .deluge DeviousYarn: .dy DIBOL-11: .dibol-11 @@ -212,20 +224,23 @@ DMS: .dms Dodo0: .dodo0 Draco: .draco Dragon: .dragon +Dragonstone: .dragonstone DreamBerd: .dreamberd Dt: .dt +DuckDB: .duckdb DUP: .dup DWScript: .dw Dyalect: .dyalect Dylan: .dylan Dylan.NET: .dylan -E: .e EasyLang: .easy EC: .ec EchoLisp: .l ECL: .ecl Ecstasy: .ecstasy +Ed: .ed EDSAC order code: .edsac +E: .e Eero: .eero Efene: .efene Egel: .egel @@ -238,10 +253,10 @@ Elan: .elan ElastiC: .elastic Elena: .elena Elisa: .elisa -Elixir: .elixir +Elixir: .ex ELLA: .ella Elm: .elm -Emacs Lisp: .l +Emacs Lisp: .el EMal: .emal Emojicode: .emojicode Enguage: .enguage @@ -252,28 +267,29 @@ ERRE: .erre Es: .es ESQL: .esql Euler: .euler -Euphoria: .euphoria +Euphoria: .eu Evaldraw: .evaldraw Excel: .excel Explore: .explore Extended BrainF***: .ebf +Extended Color BASIC: .basic Ezhil: .ezhil -F: .f Factor: .factor Falcon: .falcon 'FALSE': .false -Fan: .fan Fancy: .fancy +Fan: .fan Fantom: .fantom FAUST: .faust FBSL: .fbsl -Fe: .fe FeatureC++: .cpp +Fe: .fe Felix: .felix Fennel: .fennel Ferite: .ferite Fermat: .fermat Fexl: .fexl +F: .f Fhidwfe: .fhidwfe Fish: .fish FLORA-2: .flora2 @@ -294,6 +310,7 @@ Frink: .frink FRISC Assembly: .frisc F Sharp: .fs FTCBASIC: .basic +FuncSug: .funcsug FunL: .funl Furor: .furor FurryScript: .furryscript @@ -323,9 +340,10 @@ GlovePIE: .glovepie GLSL: .glsl GML: .gml Gnuplot: .gnuplot +Goaldi: .goaldi +Goboscript: .gobo Go!: .go Go: .go -Goaldi: .goaldi Golfscript: .golf Golo: .golo Goo: .goo @@ -342,7 +360,7 @@ Halon: .halon Harbour: .harbour Hare: .hare Haskell: .hs -Haxe: .haxe +Haxe: .hx Heron: .heron Hexiscript: .hexi HicEst: .hicest @@ -356,10 +374,11 @@ HQ9+: .hq9+ Huginn: .huginn Hy: .hy HyperTalk: .ht -I: .i Icon: .icon IDL: .idl Idris: .idris +I: .i +Imp77: .imp77 Inform 6: '.inf' Inform 7: '.inf' Informix 4GL: .4gl @@ -374,18 +393,19 @@ Iptscrae: .iptscrae Isabelle: .isabelle IS-BASIC: .basic IWBASIC: .basic -J: .j Jabaco: .jabaco Jack: .jack Jacquard Loom: .jacquard +Jactl: .jactl Jakt: .jakt JAMES II/Rule-based Cellular Automata: .james Janet: .janet -Java: .java JavaFX Script: .javafx +Java: .java JavaScript: .js JCL: .jcl Jinja: .jinja +J: .j JoCaml: .jocaml JOVIAL: .jovial Joy: .joy @@ -394,31 +414,34 @@ JScript.NET: .jscript JSE: .jse Jsish: .jsish JudoScript: .judo -Julia: .julia -K: .k +Julia: .jl Kabap: .kabap Kamailio Script: .kamailio +Kantalo: .kantalo KAP: .kap Kaya: .kaya Keg: .keg KeyList Databasing: .keylist Kite: .kite Kitten: .kitten +K: .k KL1: .kl1 Klingphix: .klingphix Klong: .klong Koka: .koka +Komodo: .komodo KonsolScript: .konsol -Kotlin: .kotlin +Kotlin: .kts KQL: .kql Ksh: .ksh -L++: .l++ LabVIEW: .labview +Labyrinth: .labyrinth Lambda Prolog: .pro Lambdatalk: .lambdatalk -Lang: .lang Lang5: .lang5 +Lang: .lang Langur: .langur +Lapyst: .lapyst Lasso: .lasso LAST: .last LaTeX: .tex @@ -444,6 +467,7 @@ Little: .little Little Man Computer: .lmc LiveCode: .livecode LiveScript: .live +L++: .l++ LLP: .llp LLVM: .llvm Lobster: .lobster @@ -456,8 +480,8 @@ Lolli: .lolli Lotus 123 Macro Scripting: .lotus123 LotusScript: .lotus Lout: .lout -LSE: .lse LSE64: .lse64 +LSE: .lse LSL: .lsl LSTS: .lsts Lua: .lua @@ -478,6 +502,8 @@ Malbolge: .malbolge MANOOL: .manool Maple: .maple MAPPER: .mapper +MariaDB: .sql +Mastermind: .mastermind Mathcad: .mathcad MathCortex: .mathcortex Mathematica: .math @@ -497,20 +523,21 @@ Metapost: .metapost MGS: .mgs Mia: .mia Microsoft Small Basic: .basic -Min: .min MINIL: .minil Minimal BASIC: .basic MiniScript: .mini MiniZinc: .minizinc +Min: .min MIPS Assembly: .mips Mirah: .mirah Miranda: .miranda MIRC Scripting Language: .mirc Mirelle: .mirelle -ML: .ml ML/I: .mli MLite: .mlite +ML: .ml MMIX: .mmix +Mn: .mn Modula-2: .mod2 Modula-3: .mod3 Mojo: .mojo @@ -520,6 +547,8 @@ Monkey: .monkey Monte: .monte MontiLang: .monti MOO: .moo +MoonBit: .moonbit +MoonRock: .moonrock MoonScript: .moon Morfa: .morfa Mosaic: .mosaic @@ -558,6 +587,7 @@ Nit: .nit Niue: .niue Nix: .nix NLP++: .nlp++ +Nom: .num NOWUT: .nowut NQP: .nqp NS-HUBASIC: .basic @@ -566,24 +596,27 @@ N/t/roff: .ntroff Nu: .nu Nutt: .nutt Nyquist: .nyquist -OASYS: .oasys OASYS Assembler: .oasys +OASYS: .oasys +Oberon-07: .oberon Oberon: .oberon Objeck: .objeck ObjectIcon: .oi Objective-C: .m +Object Pascal Implementations: .pas Object Pascal: .pas -OCaml: .ocaml +OCaml: .ml Occam: .occam Octave: .octave Odin: .odin Oforth: .fth Ol: .ol Omega: .omega +OmniMark: .xom Onyx: .onyx Onyx (wasm): .onyx -OOC: .ooc OOCalc: .oocalc +OOC: .ooc OoRexx: .rexx Opa: .opa OpenC++: .openc++ @@ -602,8 +635,9 @@ Panoramic: .panoramic ParaCL: .paracl Pare: .pare PARI/GP: .parigp -Pascal: .pas PascalABC.NET: .pas +Pascal: .pas +Pascal-P: .pas PASM: .pasm PDP-11 Assembly: .pdp11 Pebble: .pebble @@ -612,15 +646,16 @@ Pentium Assembly: .pentium PeopleCode: .peoplecode PepsiScript: .pepsi Peri: .peri -Perl: .pl Perl5i: .p5i Perl 6: .pl6 +Perl: .pl Peylang: .peylang -Phix: .phix Phixmonti: .phixmonti +Phix: .phix PHL: .phl PHP: .php Picat: .picat +Pico-8: .pico8 PicoLisp: .l Pict: .pict Piet: .piet @@ -633,12 +668,13 @@ Plain English: .plain PlainTeX: .tex Plan: .plan PL/B: .plb -PL/I: .pli PL/I-80: .pli +PL/I: .pli PL/M: .plm PL/pgSQL: .sql PL/SQL: .sql PLUS: .plus +Pluto: .pluto PLZ/SYS: .plz Pointless: .pointless Polyglot: .polyglot @@ -651,56 +687,58 @@ POV-Ray: .povray PowerBASIC: .basic Powerbuilder: .powerbuilder PowerPC Assembly: .ppc -PowerShell: .psh +PowerShell: .ps1 PPL: .ppl Processing: .processing Processing Python mode: .processing-py Processing.R: .processing-r ProDOS: .dos Prog8: .prog8 +ProgressBASIC: .basic Prolog: .pro PROMAL: .promal PSQL: .psql -Pure: .pure PureBasic: .basic Pure Data: .puredata +Pure: .pure Purity: .purity -Pyret: .pyret +Pyret: .arr Python: .py -Q: .q QB64: .qb64 QBasic: .basic Qi: .qi .QL: .ql QL SuperBASIC: .basic Qore: .qore +Q: .q Quackery: .quackery QuakeC: .c QuickBASIC: .basic Quill: .quill Quite BASIC: .basic Quorum: .quorum -R: .r -Ra: .ra Racket: .rkt Raku: .raku RapidQ: .rapidq Rapira: .rapira +Ra: .ra Rascal: .rascal RASEL: .rasel RATFOR: .ratfor Raven: .raven REALbasic: .basic -Reason: .reason +Reason: .re +Rebol: .rebol REBOL: .rebol Red: .red Reduce: .reduce Refal: .refal Relation: .relation -ReScript: .re +ReScript: .res Retro: .retro Revolution: .rev REXX: .rexx +Rhombus: .rhombus Rhope: .rhope Rhovas: .rhovas Ring: .ring @@ -708,28 +746,31 @@ RISC-V Assembly: .asm RLaB: .rlab RLSL: .rlsl Robotic: .robotic -Roc: .roc Rockstar: .rockstar -RPG: .rpg +Rocq: .rocq +Roc: .roc RPGIV: .rpgiv -RPL: .rpl +RPG: .rpg RPL/2: .rpl2 +RPL: .rpl +R: .r RTL/2: .rtl2 RTSL: .rtsl Rubylog: .rubylog Ruby: .rb Run BASIC: .basic -Rust: .rust -S++: .s++ +Rust: .rs +Rye: .rye Sage: .sage Salmon: .salmon -SAS: .sas +SapbotVM: .sapbot SASL: .sasl +SAS: .sas Sass/SCSS: .sass Sather: .sa S-BASIC: .basic Scala: .scala -Scheme: .ss +Scheme: .scm Scilab: .scilab Scratch: .scratch ScratchScript: .scratch @@ -741,14 +782,15 @@ Seed7: .seed7 Self: .self SenseTalk: .sensetalk SequenceL: .sequencel -SETL: .setl Setl4: .setl4 Set lang: .set +SETL: .setl Shale: .shale SheerPower 4GL: .4gl Shen: .shen Shiny: .shiny Sidef: .sidef +SIL: .sil SimpleCode: .simplecode SimpleLang: .simple SIMPOL: .simpol @@ -765,8 +807,8 @@ Smalltalk: .st Smart BASIC: .basic SMEQL: .smeql SmileBASIC: .basic -Snobol: .sno SNOBOL4: .sno +Snobol: .sno SNUSP: .snusp Soar: .soar Soda: .soda @@ -774,14 +816,15 @@ SoneKing Assembly: .soneking SPAD: .spad SPARC Assembly: .sparc SparForte: .sparforte -SPARK: .spark Sparkling: .sparkling +SPARK: .spark Spin: .spin SPL: .spl SPSS: .spss -SQL: .sql SQL PL: .sql +SQL: .sql Squirrel: .nut +S++: .s++ SSEM: .ssem Standard ML: .ml Star: .star @@ -802,22 +845,23 @@ SystemVerilog: .v TailDot: .taildot Tailspin: .tailspin TAL: .tal +TAV: .tav Tbas: .tbas Tcl: .tcl TechBASIC: .basic Teco: .teco TeLa: .tela Tern: .tern -Terra: .terra Terraform: .terraform +Terra: .terra TestML: .tml Thistle: .thistle Thyrd: .thyrd -TI BASIC: .basic TI-57: .ti57 TI-83 BASIC: .basic TI-83 Hex Assembly: .asm TI-89 BASIC: .basic +TI BASIC: .basic Tiny BASIC: .basic Tiny Craft Basic: .basic TIS-100: .tis100 @@ -850,31 +894,30 @@ Uiua: .uiua Ultimate++: .ultimate++ Unicon: .unicon Uniface: .uniface -Unison: .unison +Unison: .u UnixPipes: .up UNIX Shell: .sh Unlambda: .unlambda -Ursa: .ursa -Ursala: .ursala Ursalang: .ursa +Ursala: .ursala +Ursa: .ursa UScript: .u UserRPL: .rpl UTFool: .utfool Uxntal: .uxnatl -V: .v Vala: .vala Vale: .vale VAX Assembly: .vax VB6: .vb6 VBA: .vba -VBScript: .vb +VBScript: .vbs Vedit macro language: .vedit Verbexx: .verbexx Verilog: .v -VHDL: .vhdl +VHDL: .vhd Vim Script: .vim -Visual Basic: .vb Visual Basic .NET: .vb +Visual Basic: .vb Visual FoxPro: .fvp Visual Objects: .vobj Visual Prolog: .pro @@ -883,7 +926,10 @@ Vorpal: .vorpal Vox: .vox VRML: .vrml VTL-2: .vtl-2 +V: .v V (Vlang): .v +Vyxal: .vyxal +Waduzitdo: .waduzitdo Wart: .wart WDTE: .wdte WebAssembly: .wasm @@ -905,31 +951,32 @@ XBase: .xbase XBasic: .basic XBS: .xbs XEec: .xeec -XL: .xl XLISP: .l +XL: .xl Xojo: .xojo XPath 2.0: .xpath XPL0: .xpl0 XProc: .xproc XProfan: .xprofan XQuery: .xquery -XS: .xs -XSLT: .xslt +X-script: .x XSLT 1.0: .xslt XSLT 2.0: .xslt +XSLT: .xslt +XS: .xs XTalk: .xtalk XUL: .xul -Ya: .ya Yabasic: .basic Yacas: .yacas YAMLScript: .ys +Ya: .ya Yorick: .yorick Z80 Assembly: .z80 ZED: .zed Zig: .zig Zkl: .zkl -Zoea: .zoea Zoea Visual: .zoea +Zoea: .zoea Zonnon: .zonnon Zoomscript: .zoom ZPL: .zpl diff --git a/Lang/11l/Bioinformatics-base-count b/Lang/11l/Bioinformatics-base-count deleted file mode 120000 index d8c9e2572d..0000000000 --- a/Lang/11l/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/11l \ No newline at end of file diff --git a/Lang/11l/Meissel-Mertens-constant b/Lang/11l/Meissel-Mertens-constant deleted file mode 120000 index 908ef16ca2..0000000000 --- a/Lang/11l/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/11l \ No newline at end of file diff --git a/Lang/11l/Miller-Rabin-primality-test b/Lang/11l/Miller-Rabin-primality-test deleted file mode 120000 index cec9772a16..0000000000 --- a/Lang/11l/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/11l \ No newline at end of file diff --git a/Lang/11l/Sorting-Algorithms-Circle-Sort b/Lang/11l/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 38059f4dea..0000000000 --- a/Lang/11l/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/11l \ No newline at end of file diff --git a/Lang/4D/00-LANG.txt b/Lang/4D/00-LANG.txt index d591e6be7f..8c8b507919 100644 --- a/Lang/4D/00-LANG.txt +++ b/Lang/4D/00-LANG.txt @@ -1,3 +1,6 @@ -{{stub}}{{language|4D}}{{IDE}}'''4D''' (or '''4th Dimension''') is a database management system and [[:Category:Integrated Development Environments|integrated development environment]] authored by Laurent Ribardière in 1984. +{{stub}} +{{language|4D +|site=https://us.4d.com/ +}}{{IDE}}'''4D''' (or '''4th Dimension''') is a database management system and [[:Category:Integrated Development Environments|integrated development environment]] authored by Laurent Ribardière in 1984. ==Citations== *[[wp:4th_Dimension_%28Software%29|Wikipedia:4th Dimension (Software)]] \ No newline at end of file diff --git a/Lang/4ME/00-LANG.txt b/Lang/4ME/00-LANG.txt new file mode 100644 index 0000000000..d297ba9483 --- /dev/null +++ b/Lang/4ME/00-LANG.txt @@ -0,0 +1,7 @@ +{{language|4ME +|site=https://thevitebsk.github.io/4ME.by/}} +4ME is a programing language created by [[User:Gaham]] implemented in 04.07.2024 MSK +==See Also== +* [https://esolangs.org/wiki/4ME 4ME in Esolangs.org] +* [https://github.com/Thevitebsk/4me/ Github repo] +[[Category:Programming paradigm/Concatenative]] \ No newline at end of file diff --git a/Lang/4ME/00-META.yaml b/Lang/4ME/00-META.yaml new file mode 100644 index 0000000000..f0031de2c3 --- /dev/null +++ b/Lang/4ME/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:4ME diff --git a/Lang/6502-Assembly/00-LANG.txt b/Lang/6502-Assembly/00-LANG.txt index a7fa28ad34..1273acfa02 100644 --- a/Lang/6502-Assembly/00-LANG.txt +++ b/Lang/6502-Assembly/00-LANG.txt @@ -131,6 +131,29 @@ This flag is set if the BRK command was executed. The BRK basically * Set with: BRK * Cleared with: RTI * There are no branches associated with this command. + +This flag is used only for differentiating a BRK from an hardware IRQ +IRQ: + STA saveAccumulator ; save accumulator + PLA ; get flags + STA saveFlags ; save flags + AND #$10 ; check "break" flag + BNE IRQ_fromBreak ; if(break flag set){ goto IRQ_fromBreak; } + JMP IRQ_fromHardware ; else{ goto IRQ_fromInterrupt; } +IRQ_fromBreak: + LDA saveFlags ; load flags from temp address + PHA ; restore flags to stack + LDA saveAccumulator ; restore accumulator + ;... + RTI ; return from interrupt + +IRQ_fromInterrupt: + LDA saveFlags ; load flags from temp address + PHA ; restore flags to stack + LDA saveAccumulator ; restore accumulator + ;... + RTI ; return from interrupt +

===Decimal=== diff --git a/Lang/68000-Assembly/00-LANG.txt b/Lang/68000-Assembly/00-LANG.txt index cfd37d0eae..245cbaaea5 100644 --- a/Lang/68000-Assembly/00-LANG.txt +++ b/Lang/68000-Assembly/00-LANG.txt @@ -3,31 +3,36 @@ {{language}} 68000 assembly is the assembly language used for the Motorola 68000, or commonly known as the 68K. It should not be confused with the 6800 (which predates it). The Motorola 68000 is a big-endian processor with full 32-bit capabilities (despite most systems that use it being considered 16-bit.) It was used in many computers such as the Amiga or the Canon Cat, as well as game consoles such as the Sega Genesis and Neo Geo. - ==Architecture Overview== ===Big-Endian=== The 68000, unlike most processors of its era, is big-endian. This means that bytes are stored from left to right. The example below illustrates this concept: -MOVE.L #$12345678,$100000 ;store the hexadecimal numeral #$12345678 at memory address $100000 + +MOVE.L #$12345678,$100000 ;store the hexadecimal numeral #$12345678 at memory address $100000 + +
 ;hexdump of $100000:
 ;$100000 = $12
 ;$100001 = $34
 ;$100002 = $56
-;$100003 = $78
+;$100003 = $78
+
On a little-endian processor such as in [[x86 Assembly]], the order of the bytes would be reversed, i.e.: -;hexdump of $100000 +
+;hexdump of $100000
 ;$100000 = $78
 ;$100001 = $56
 ;$100002 = $34
-;$100003 = $12
+;$100003 = $12
+
-This difference isn't usually relevant in the majority of situations, so don't concern yourself too much. It's much more important when doing [[6502 Assembly]] where registers are smaller than the address space. +The main difference is that if you wanted to access this value as a byte or word it would be at a different address, whereas with a little endian architecture it is at the same address. ===Notation Conventions=== How you write the source code depends on your assembler and the syntax it uses. This page is written using Motorola syntax but there is also Milo syntax which has different conventions. -How you go about defining numbers or text in your code varies wildly between assemblers. I'm using VASM and these are the rules I have to follow, but your assembler may be different. +How you go about defining numbers or text in your code varies wildly between assemblers. * A number with a # in front represents a constant, literal value. For example, the 3 in MOVE.B #3,D0 represents the number 3. @@ -45,72 +50,88 @@ How you go about defining numbers or text in your code varies wildly between ass * The operand before the comma is the "source", and the operand after is the "destination." For example, MOVE.L D3,D2 takes the value in D3 and stores it into D2, not the other way around. This is the opposite of x86 and ARM, which have the source on the right and the destination on the left. - -Data blocks, on the other hand, begin with DC.B, DC.W, or DC.L and each represents a constant numeric value. Strangely, you do NOT prefix these with # to signify them as constants (doing so will cause an error on most assemblers). However, you can use the $ or % modifiers to denote hexadecimal or binary. +Data blocks, on the other hand, begin with DC.B, DC.W, or DC.L and each represents a constant numeric value. You do NOT prefix these with # to signify them as constants (doing so will cause an error on most assemblers). However, you can use the $ or % modifiers to denote hexadecimal or binary. Keep in mind that there is no requirement to use hexadecimal, decimal, or binary in your source code. It all gets converted to binary anyway. However, it is recommended to use the notation that is appropriate for how your data is meant to be interpreted, for readability purposes. ===Data Registers=== There are eight 32-bit data registers on the 68000, numbered D0-D7. As the name implies, these are designed to hold data. Much like in [[ARM Assembly]], each one is identical in terms of which commands it can use. A command that can be used for D0 can be used for any other D-register. -MOVE.B #$FF,D0 ;move the hexadecimal value 0xFF into the bottom byte of D0. -ADD.W #$8000,D4 ;add hexadecimal 0x8000 to the value stored in D4. + +MOVE.B #$FF,D0 ;move the hexadecimal value 0xFF into the bottom byte of D0. +ADD.W #$8000,D4 ;add hexadecimal 0x8000 to the value stored in D4. + ===Address Registers=== There are eight of these as well, numbered A0-A7. A7 is reserved as the stack pointer, and is commonly referenced as SP in assemblers. The others are free to use for any purpose. Although these registers are 32-bit, the 68000's address space is 24-bit (ranges from 0x000000 to 0xFFFFFF), so the leftmost byte is ignored. You can do simple math involving these registers but more complicated commands like multiply or divide can only be used with data registers. Address registers are used to contain addresses and extract the values stored within. ====Loading From Memory==== -MOVEA.L #$200000,A2 ;usually these are loaded from a label. + +MOVEA.L #$200000,A2 ;usually these are loaded from a label. ;The hex dump of address $200000: 44 55 66 77 MOVE.L #$00000000,D0 MOVE.B (A2),D0 ;load the byte stored at $200000 into D0. D0 = #$00000044 MOVE.W (A2),D0 ;load the word stored at $200000 into D0. D0 = #$00004455 MOVE.L (A2),D0 ;load the long stored at $200000 into D0. D0 = #$44556677 -MOVE.L D2,(A5) ;store the contents of D2 into the memory address pointed to by A5. - +MOVE.L D2,(A5) ;store the contents of D2 into the memory address pointed to by A5. + Note that it's also possible to transfer values to/from memory directly, without involving address registers at all. For constant memory locations, this is fine. However, the real strength of the address registers is in their pre-decrement and post-increment modes, which constant memory locations cannot use. -MOVE.L ($00FF0000),D0 + +MOVE.L ($00FF0000),D0 MOVE.W D1,($00FFFFFE) -MOVE.W ($00FF0000),($00FF1000) +MOVE.W ($00FF0000),($00FF1000) + The use of parentheses is not required on most assemblers, but can be used as a reminder to someone reading your code that these represent the values stored at the specified memory locations rather than literal numbers. ====Post-Increment==== The post-increment mode is specified by adding a + to the end of parentheses. This means that after the command is done, the address stored in the address register (not the value stored at that address) is increased by the byte length of the command (1 for .B, 2 for .W, 4 for .L). -MOVEA.L #$00240000,A4 ;load the address $240000 into A4 + +MOVEA.L #$00240000,A4 ;load the address $240000 into A4 MOVE.W (A4)+,D0 ;move the word stored at $240000 into D0, then increment to #$240002 MOVE.L (A4)+,D1 ;move the long stored at $240000 into D1, then increment to #$240006 -MOVE.L (SP)+,D3 ;pop the top value of the stack into D3 +MOVE.L (SP)+,D3 ;pop the top value of the stack into D3 + ====Pre-Decrement==== The pre-decrement mode is specified by typing a - before the parentheses. This means that before the command is done, the address stored in the address register is decreased by the byte length of the command. -MOVEA.L #$0024000A,A4 ;load the address $24000A into A4 +MOVEA.L #$0024000A,A4 ;load the address $24000A into A4 MOVE.W -(A4),D0 ;move the word stored at $240008 into D0 MOVE.L -(A4),D1 ;move the long stored at $240004 into D1 -MOVE.L D2,-(SP) ;push the contents of D2 onto the stack +MOVE.L D2,-(SP) ;push the contents of D2 onto the stack ====Address Offsets==== A memory address can be offset by a data register, an immediate value, or both. If a data register is used, only the bottom 2 bytes are considered. In either case, the contents of the data register and/or the immediate value are added to the value stored in the address register, and the value is read from that address at the specified length. The offsets are applied during the calculation only; the actual contents in the address register after the move are unchanged. Using a post-increment or pre-decrement with this addressing mode will only update the address by the specified length, not by the offsets. -MOVE.B (4,A0,D0),D1 ;The byte at A0+D0+4 is loaded into D1. + +MOVE.B (4,A0,D0),D1 ;The byte at A0+D0+4 is loaded into D1. + + It's possible to use the same data register as the offset and the destination. This does not cause any problems whatsoever, as the data register offset is "locked in" before the move, and is only updated after the command fully executes. Using the same command again immediately afterwards will offset based on the new value of that register. -MOVE.W (6,A0,D0),D0 ;The word at A0+D0+6 is read, then loaded into D0. + +MOVE.W (6,A0,D0),D0 ;The word at A0+D0+6 is read, then loaded into D0. + + A very important note is that when using this method with words and longs, the resulting address must be even! Otherwise the CPU will crash. For MOVE.B it doesn't matter. ====Effective Address==== A calculated offset can be saved to an address register with the LEA command, which stands for "Load Effective Address." [[x86 Assembly]] also has this command, and it serves the same purpose. The syntax for it can be a bit misleading depending on your assembler. -LEA myData,A0 ;load the effective address of myData into A0 + +LEA myData,A0 ;load the effective address of myData into A0 LEA (4,A0),A1 ;load into A1 the effective address A0+4. This looks like a dereference operation but it is not! -MOVE.W (A1),D1 ;dereference A1, loading the value it points to into D1. +MOVE.W (A1),D1 ;dereference A1, loading the value it points to into D1. + This can get confusing, especially if you have tables of pointers. Just remember that LEA cannot dereference an address. If you don't want to store the effective address in an address register, you can use PEA (push effective address) to put it onto the stack instead. -LEA myData,A0 ;load the effective address of myData into A0 -PEA (4,A0) ;store the effective address of A0+4 onto the stack. + +LEA myData,A0 ;load the effective address of myData into A0 +PEA (4,A0) ;store the effective address of A0+4 onto the stack. + ====The Stack==== The 68000's stack is commonly referred to as SP but it is also address register A7. This register is handled differently than the other address registers when pushing bytes onto the stack. A byte value pushed onto the stack will be padded to the right. The stack needs to pad byte-length data so that it can stay word-aligned at all times. Otherwise the CPU would crash as soon as you tried to use the stack for anything other than a byte! @@ -124,48 +145,48 @@ The 68000 can work with 8-bit, 16-bit, or 32-bit values. Some commands only work If you don't specify a length with your command, it usually defaults to word length, but ultimately it depends on the command you are using. (Some commands cannot be used at word length.) Bytes and words moved into a register are always stored on the right-hand side. For example: -MOVE.L #$FFFFFFFF,D7 + +MOVE.L #$FFFFFFFF,D7 MOVE.B #$00,D7 ;D7 contains #$FFFFFF00 -MOVE.W #$2222,D7 ;D7 contains #$FFFF2222 +MOVE.W #$2222,D7 ;D7 contains #$FFFF2222 + As you can see, the rest of the register is unchanged. (On the ARM, it would turn to zeroes.) This is very important to remember. If your code is doing something unexpected it might be due to the "old" value of the register corrupting another function. If the given constant is smaller than the length provided, the value is padded to the left with zeroes. -MOVE.W #$FF,D3 ;D3 = #$xxxx00FF, where x is the previous value of D3. -MOVE.L #0,D3 ;D3 = #$00000000 + +MOVE.W #$FF,D3 ;D3 = #$xxxx00FF, where x is the previous value of D3. +MOVE.L #0,D3 ;D3 = #$00000000 + Loading immediate values into address registers is different. You can only move words or longer into address registers, and if you move a word, the value is sign-extended. This means that if the top nibble of the word is 8 or greater, the value gets padded to the left with Fs, and is padded with zeroes if the top nibble is 7 or less. If you're adding a constant value less than 7FFF to an address, it's usually safe to use the word length operation, which takes less bytes to encode than the long length version. -MOVEA.W #$8000,A4 ;A4 = #$FFFF8000. Remember the top byte is ignored so this is the same as #$00FF8000. -MOVEA.W #$7FFF,A3 ;A3 = #$00007FFF + +MOVEA.W #$8000,A4 ;A4 = #$FFFF8000. Remember the top byte is ignored so this is the same as #$00FF8000. +MOVEA.W #$7FFF,A3 ;A3 = #$00007FFF + ==The Flags== The flags are stored in the Condition Code Register, also known as the CCR. The 68000 has no built-in commands like CLC for clearing/setting individual flags. Rather, you can alter them directly with MOVE,AND,OR, and EOR. Unfortunately, this means you'll have to remember which bits represent which flags. Or, if your assembler supports macros, you can define a macro that handles this for you. The flags update automatically after most operations, and take into consideration the operand sizes when doing so. Check out this example: - + MOVE.L #$12FF,D0 ADD.B #1,D0 - + Since we used ADD.B, D0 now contains $1200, and the extend, carry, and zero flags are all set. Had we done ADD.W, we would get $1300 in D0 with none of those flags set. The flags are based on what the actual instruction "sees", not the entire register at all times. * X: The eXtend flag is bit 4 of the CCR, and is similar to the carry flag. It gets set and cleared often for the same reasons and is used with the ADDX, SUBX, NEGX, ROXL, and ROXR commands. Why the 68000 has both this and the carry flag, I still don't know. - * N: The negative flag is bit 3 of the CCR, and is set when the last operation resulted in a "negative" value. What constitutes a negative value depends on the size of the last operation - for .B instructions, $80-$FF. For .W instructions, $8000-$FFFF, and for .L instructions, $80000000-$FFFFFFFF. - * Z: The zero flag is bit 2 of the CCR and works like you would expect - it's set whenever an operation results in zero. Unlike x86 Assembly, this also includes moving 0 directly into a register, clearing a register or memory with CLR, etc. - * V: The overflow flag is bit 1 of the CCR. It is set whenever a math operation results in a value crossing the $7F-$80 boundary. (Wraparound from 00 to FF doesn't count as overflow, but it does set the carry flag.) - * C: The carry flag is bit 0 of the CCR. It is set when a math operation results in a carry or borrow. Rolling over from FF to 00, or a 1 getting "pushed out" via a bit shift or rotate, set the carry flag. When using CMP, the carry flag determines the unsigned magnitude comparison. Carry set is less than, carry clear is greater than or equal. - - In truth, the flags are a 16-bit register, of which the CCR is just the "low half". The SR (status register) is the full 16-bit register. There are a few additional flags in the upper half, which are used by the operating system. You can read these but for the most part you won't need to write to them. @@ -189,13 +210,15 @@ The 68000 supports 7 different interrupts, often called IRQs or Interrupt Reques ==Alignment== The 68000 can only read or write words and longs at even addresses. Doing so at an odd address will result in the CPU crashing. (Note that reading byte data will not cause a crash regardless of whether it's located at an odd or even address.) This isn't usually a problem, but it can be if the programmer is not careful with the way their data is organized. Consider the following example: -TestData: + +TestData: DC.B $02 DC.W $0345 LEA TestData,A0 ;load effective address of TestData into A0. MOVE.B (A0)+,D0 ;load $02 into D0, increment A0 by 1 -MOVE.W (A0)+,D1 ;this crashes the CPU since A0 is now odd +MOVE.W (A0)+,D1 ;this crashes the CPU since A0 is now odd + How was it known that the address was odd at the second instruction? Simple. All instructions take an even number of bytes to encode. So there are only a few ways improper alignment can occur: * An odd value is loaded into an address register. @@ -205,18 +228,23 @@ How was it known that the address was odd at the second instruction? Simple. All If the programmer is smart with the way they encode byte-length data they can avoid this problem entirely with little effort. One way is to separate byte-length data into its own table. -ByteData: + +ByteData: DC.B $20,$40,$60,$80 WordData: -DC.W $1000,$2000,$3000,$4000 +DC.W $1000,$2000,$3000,$4000 + Another way is to pad the data with an extra byte, so that there is an even number of entries in the table. This becomes impractical with large data tables, so the EVEN directive can be placed after a series of bytes. If the byte count is odd, EVEN will pad the data with an extra byte. If it's already even, the EVEN command is ignored. This saves you the trouble of having to count a long series of bytes without worrying about wasting space. -MyString: DC.B "HELLO WORLD 12345678900000",0 -EVEN ;some assemblers require this to be on its own line + +MyString: DC.B "HELLO WORLD 12345678900000",0 +EVEN ;some assemblers require this to be on its own line + A third way is to perform a "dummy read." This is when a value is read from an address using pre-decrement or post-increment, with the sole purpose of moving the pointer, and the value being read is of zero interest. This method lets you work with mixed data types in the same table, but it requires the programmer to know in advance where the byte-length data begins and ends. -TestData: + +TestData: DC.B $02,$03,$04 DC.W $0345 @@ -227,7 +255,8 @@ MOVE.B (A0)+,(A1)+ ;copy $04 to a new memory location ;if we did MOVE.W (A0)+,(A1)+ now we'd crash. First we need to adjust the pointers. MOVE.B (A0)+,D7 ;dummy read to D7. Now A0 is word aligned. MOVE.B (A1)+,D7 ;dummy read to D7. Now A1 is word aligned. -MOVE.W (A0)+,(A1)+ ;copy $0345 to a new memory location +MOVE.W (A0)+,(A1)+ ;copy $0345 to a new memory location + Using ADDA.L #1,A0 and ADDA.L #1,A1 would have worked also, instead of the dummy read. The 68000 gives the programmer a lot of different ways to do a task. diff --git a/Lang/68000-Assembly/Musical-scale b/Lang/68000-Assembly/Musical-scale new file mode 120000 index 0000000000..0a23b13b4e --- /dev/null +++ b/Lang/68000-Assembly/Musical-scale @@ -0,0 +1 @@ +../../Task/Musical-scale/68000-Assembly \ No newline at end of file diff --git a/Lang/8080-Assembly/Align-columns b/Lang/8080-Assembly/Align-columns new file mode 120000 index 0000000000..d9134cb487 --- /dev/null +++ b/Lang/8080-Assembly/Align-columns @@ -0,0 +1 @@ +../../Task/Align-columns/8080-Assembly \ No newline at end of file diff --git a/Lang/8080-Assembly/Display-a-linear-combination b/Lang/8080-Assembly/Display-a-linear-combination new file mode 120000 index 0000000000..5e499be357 --- /dev/null +++ b/Lang/8080-Assembly/Display-a-linear-combination @@ -0,0 +1 @@ +../../Task/Display-a-linear-combination/8080-Assembly \ No newline at end of file diff --git a/Lang/8080-Assembly/Integer-comparison b/Lang/8080-Assembly/Integer-comparison new file mode 120000 index 0000000000..e48c1e8ea4 --- /dev/null +++ b/Lang/8080-Assembly/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/8080-Assembly \ No newline at end of file diff --git a/Lang/8080-Assembly/Loops-Infinite b/Lang/8080-Assembly/Loops-Infinite new file mode 120000 index 0000000000..f6336ebca0 --- /dev/null +++ b/Lang/8080-Assembly/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/8080-Assembly \ No newline at end of file diff --git a/Lang/8080-Assembly/Ordered-words b/Lang/8080-Assembly/Ordered-words new file mode 120000 index 0000000000..eee238f68d --- /dev/null +++ b/Lang/8080-Assembly/Ordered-words @@ -0,0 +1 @@ +../../Task/Ordered-words/8080-Assembly \ No newline at end of file diff --git a/Lang/8080-Assembly/Run-length-encoding b/Lang/8080-Assembly/Run-length-encoding new file mode 120000 index 0000000000..bc3ed9076c --- /dev/null +++ b/Lang/8080-Assembly/Run-length-encoding @@ -0,0 +1 @@ +../../Task/Run-length-encoding/8080-Assembly \ No newline at end of file diff --git a/Lang/8080-Assembly/Sieve-of-Eratosthenes b/Lang/8080-Assembly/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..ddc8441b98 --- /dev/null +++ b/Lang/8080-Assembly/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/8080-Assembly \ No newline at end of file diff --git a/Lang/8080-Assembly/Square-but-not-cube b/Lang/8080-Assembly/Square-but-not-cube new file mode 120000 index 0000000000..e8de867485 --- /dev/null +++ b/Lang/8080-Assembly/Square-but-not-cube @@ -0,0 +1 @@ +../../Task/Square-but-not-cube/8080-Assembly \ No newline at end of file diff --git a/Lang/8080-Assembly/Twos-complement b/Lang/8080-Assembly/Twos-complement new file mode 120000 index 0000000000..86928fcdc9 --- /dev/null +++ b/Lang/8080-Assembly/Twos-complement @@ -0,0 +1 @@ +../../Task/Twos-complement/8080-Assembly \ No newline at end of file diff --git a/Lang/8080-Assembly/Zeckendorf-number-representation b/Lang/8080-Assembly/Zeckendorf-number-representation new file mode 120000 index 0000000000..b0569b898c --- /dev/null +++ b/Lang/8080-Assembly/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/8080-Assembly \ No newline at end of file diff --git a/Lang/8086-Assembly/00-LANG.txt b/Lang/8086-Assembly/00-LANG.txt index 7cf10761fa..9120d12d87 100644 --- a/Lang/8086-Assembly/00-LANG.txt +++ b/Lang/8086-Assembly/00-LANG.txt @@ -4,13 +4,13 @@ ===Segmented Memory=== The 8086 uses a segmented memory model, similar to the Super Nintendo Entertainment System. Unlike banked memory models used in the Commodore 64 and late NES games, segment addresses are held in segment registers. These segment registers are 16 bit and get left-shifted by 4 and added to the pointer register of interest to determine the memory address to look up. The 8086 has four in total, but only the DS and ES registers can be used by the programmer. (The other two work with the stack pointer and instruction pointer, and are loaded for you.) On the 8086, you can only load segment registers with the value in a data register, or with the POP command. So first you must load a segment into a data register, THEN into a segment register. -;This is NOT valid code! +;This is NOT valid code! mov ds, @data ;you're trying to move the data segment location directly into DS. You can't! ;This is the proper way: mov ax, @data ;I chose AX but I could have used BX, CX, or DX. -mov ds, ax ;load DS with the data segment. +mov ds, ax ;load DS with the data segment. It's important to remember the subtle distinction between a ''segment'' and a ''segment register.'' Your program might have labeled ''segments'' such as .data and .code, but in order to properly read from/write to these sections you'll need to load their memory locations into ''segment registers.'' @@ -18,17 +18,17 @@ It's important to remember the subtle distinction between a ''segment'' and a '' There are four data registers: AX, BX, CX, and DX. While most commands can use any of them, some only work with particular data registers. System calls in particular are very specific about which registers can be used for what. On [[MS-DOS]], the AX register is used for selecting the desired interrupt to use with the INT command. Each data register is 16-bit, but has two eight bit halves ending in H or L, e.g. AH, AL. Instructions can be executed using the whole register or just half of it. -mov ax, 1000h ;move 1000h into AX, or equivalently, move 10h into AH and 00h into AL. +mov ax, 1000h ;move 1000h into AX, or equivalently, move 10h into AH and 00h into AL. Moving a value smaller than 16 bits into ?X is the same as moving it into ?L, and moving 0 into ?H. (? represents the data register of your choice. They are all the same in this regard.) -mov ax,0030h +mov ax,0030h ;is the same as: mov al, 30h -mov ah, 0h +mov ah, 0h Commands that alter the contents of a single register will not affect the other half. -mov ax,00FFh -inc al +mov ax,00FFh +inc al If we had executed INC AX, then AX would have been incremented to 0x100. Since we only incremented AL, only AL was incremented in this case, and AH '''still equals 0x00!''' Generally speaking, the 8086's registers serve the following purposes: @@ -42,24 +42,24 @@ When writing to or reading from consecutive sections of memory, it is helpful to The syntax for offsetting an index register will vary depending on your assembler. Many assemblers will often accept multiple different ways of writing it, and it comes down to personal preference. -mov si, offset MyArray +mov si, offset MyArray mov bx,2 mov al,[bx+si] ;loads decimal 30 into AL MyArray: -byte 10,20,30,40,50 +byte 10,20,30,40,50 ===The Stack=== As with [[Z80 Assembly]], you can't push 8-bit registers onto the stack. For data registers, you have to push/pop both halves. -;This is valid code. +;This is valid code. push ax push bx pop bx pop ax -;This is NOT valid code. +;This is NOT valid code. push ah push al push bh @@ -69,14 +69,14 @@ push bl pop bl pop bh pop al -pop ah +pop ah As with all processors that use a stack, if you push one or more registers and want to restore the backed-up values correctly, you must pop them in the reverse order. You can pop them out of order on purpose to swap registers around. In fact, this is a quick way to move the segment from DS into ES, or vice-versa: -push DS -pop ES ;you can't do "mov es, ds" but you can do this! +push DS +pop ES ;you can't do "mov es, ds" but you can do this! The proper way to use the stack to preserve registers: - + call foo mov ax,4C00h @@ -91,7 +91,7 @@ push cx pop cx pop bx pop ax -ret +ret If one of the push/pop commands in the routine above were missing, the RET instruction would not properly return to where it came from. As long as you pop at the end the same number of registers you pushed at the start, the stack is "balanced" and your return instruction will return correctly. This is because RET is actually POP IP (IP being the instruction pointer, which you can think of as what "line" of code the CPU is on.) The CPU assumes the top of the stack is the correct place to return to, but has no way of actually verifying it. If the function you just wrote causes the CPU to crash or jump to a completely different part of the code, there's a good chance you might have forgotten to balance the stack properly. @@ -107,40 +107,40 @@ One other caveat to mention: On early IBM PCs and compatibles, the 8087 was not ===Looping Constructs=== The 8086 has a lot more of these than most CPUs. The most obvious one is LOOP, which will subtract 1 from CX, then jump back to a specified label if CX is nonzero after the subtraction. If CX becomes zero after subtracting 1, then no jump will occur and the instruction pointer simply moves to the next instruction. -mov cx,0100h ;set the loop counter's starting value. This must be outside the loop, otherwise you'll loop forever! +mov cx,0100h ;set the loop counter's starting value. This must be outside the loop, otherwise you'll loop forever! foo: ;; your code that you want to loop goes here -loop foo +loop foo It's important not to alter CX inside the loop. It's easy to make a mistake like this if you're in a hurry: -foobar: +foobar: mov cx,1000h ;your code goes here -loop foobar +loop foobar It may not be obvious at first but the above loop will never end. CX decrements to 0x0FFF with the LOOP instruction but the mov cx,1000h was mistakenly placed ''inside'' the loop, resetting the loop counter back to 0x1000, which means no progress is really being made. The correct way to do this is to set the starting loop counter '''outside''' the loop, like so: -mov cx,1000h +mov cx,1000h foobar: ;your code goes here -loop foobar +loop foobar Sometimes you'll have to change CX during a loop, like if you want to do bit shifts with a shift amount other than 1, for example. There's a simple fix - use the stack to stash and retrieve the loop counter. -mov cx,0100h +mov cx,0100h foo: push cx mov cl,2 ror ax,cl ;starting with the 80186 you don't need CL for bit shifting. pop cx -loop foo +loop foo By using PUSH CX and POP CX, you can temporarily use CX for something else, as long as you restore it before the LOOP instruction. You can use other registers as loop counters as well, but not with the LOOP instruction - it's hardcoded to only work with CX. But you can do this: -mov dx,0100h +mov dx,0100h baz: ;your code goes here dec dx @@ -148,7 +148,7 @@ jnz baz ; A minor note for advanced programmers: ; If you're expecting the flags to be in a particular state based on the loop body, tough luck! ; They'll only reflect the decrement of DX from 1 to 0 at this point in the code. -; LOOP doesn't change the flags, which makes it more useful for loops meant to compare things. +; LOOP doesn't change the flags, which makes it more useful for loops meant to compare things. Another frequently used looping construct is REP. REP can be combined with certain instructions to repeat that instruction until CX equals zero. However, unlike LOOP, which can be used to repeat a block of instructions, REP can only repeat one. It doesn't work on all instructions, only the "string" instructions which operate on a block of memory. Typically these include MOVSB, LODSB, STOSB, CMPSB, and SCASB (each has a variant that ends in W instead of B, for 16-bit data.) There are also REPZ and REPNZ, which stand for "Repeat if Zero" and "Repeat if Nonzero" respectively. These two only work properly with CMPSB and SCASB, as MOVSB, LODSB, STOSB do not affect the flags. (The CPU doesn't detect whether CX equals zero using the flags, as the flags never reflect this equality to zero like you would expect.) diff --git a/Lang/8th/Angle-difference-between-two-bearings b/Lang/8th/Angle-difference-between-two-bearings new file mode 120000 index 0000000000..9cc882831f --- /dev/null +++ b/Lang/8th/Angle-difference-between-two-bearings @@ -0,0 +1 @@ +../../Task/Angle-difference-between-two-bearings/8th \ No newline at end of file diff --git a/Lang/8th/Environment-variables b/Lang/8th/Environment-variables new file mode 120000 index 0000000000..f15e7e1793 --- /dev/null +++ b/Lang/8th/Environment-variables @@ -0,0 +1 @@ +../../Task/Environment-variables/8th \ No newline at end of file diff --git a/Lang/8th/Factorial b/Lang/8th/Factorial new file mode 120000 index 0000000000..dde7e52e98 --- /dev/null +++ b/Lang/8th/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/8th \ No newline at end of file diff --git a/Lang/AArch64-Assembly/Bifid-cipher b/Lang/AArch64-Assembly/Bifid-cipher new file mode 120000 index 0000000000..57b7c95a81 --- /dev/null +++ b/Lang/AArch64-Assembly/Bifid-cipher @@ -0,0 +1 @@ +../../Task/Bifid-cipher/AArch64-Assembly \ No newline at end of file diff --git a/Lang/AArch64-Assembly/Binary-strings b/Lang/AArch64-Assembly/Binary-strings new file mode 120000 index 0000000000..09d5581057 --- /dev/null +++ b/Lang/AArch64-Assembly/Binary-strings @@ -0,0 +1 @@ +../../Task/Binary-strings/AArch64-Assembly \ No newline at end of file diff --git a/Lang/AArch64-Assembly/Bioinformatics-base-count b/Lang/AArch64-Assembly/Bioinformatics-base-count deleted file mode 120000 index 77532b44f2..0000000000 --- a/Lang/AArch64-Assembly/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/AArch64-Assembly \ No newline at end of file diff --git a/Lang/AArch64-Assembly/Calculating-the-value-of-e b/Lang/AArch64-Assembly/Calculating-the-value-of-e new file mode 120000 index 0000000000..6be0e9e4dd --- /dev/null +++ b/Lang/AArch64-Assembly/Calculating-the-value-of-e @@ -0,0 +1 @@ +../../Task/Calculating-the-value-of-e/AArch64-Assembly \ No newline at end of file diff --git a/Lang/AArch64-Assembly/Comma-quibbling b/Lang/AArch64-Assembly/Comma-quibbling new file mode 120000 index 0000000000..09eae1e29d --- /dev/null +++ b/Lang/AArch64-Assembly/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/AArch64-Assembly \ No newline at end of file diff --git a/Lang/AArch64-Assembly/Compound-data-type b/Lang/AArch64-Assembly/Compound-data-type new file mode 120000 index 0000000000..5e69c433e8 --- /dev/null +++ b/Lang/AArch64-Assembly/Compound-data-type @@ -0,0 +1 @@ +../../Task/Compound-data-type/AArch64-Assembly \ No newline at end of file diff --git a/Lang/AArch64-Assembly/Conways-Game-of-Life b/Lang/AArch64-Assembly/Conways-Game-of-Life new file mode 120000 index 0000000000..048d5e56cd --- /dev/null +++ b/Lang/AArch64-Assembly/Conways-Game-of-Life @@ -0,0 +1 @@ +../../Task/Conways-Game-of-Life/AArch64-Assembly \ No newline at end of file diff --git a/Lang/AArch64-Assembly/Create-an-HTML-table b/Lang/AArch64-Assembly/Create-an-HTML-table new file mode 120000 index 0000000000..53d9451773 --- /dev/null +++ b/Lang/AArch64-Assembly/Create-an-HTML-table @@ -0,0 +1 @@ +../../Task/Create-an-HTML-table/AArch64-Assembly \ No newline at end of file diff --git a/Lang/AArch64-Assembly/Determine-sentence-type b/Lang/AArch64-Assembly/Determine-sentence-type new file mode 120000 index 0000000000..9e5de0c792 --- /dev/null +++ b/Lang/AArch64-Assembly/Determine-sentence-type @@ -0,0 +1 @@ +../../Task/Determine-sentence-type/AArch64-Assembly \ No newline at end of file diff --git a/Lang/AArch64-Assembly/Environment-variables b/Lang/AArch64-Assembly/Environment-variables new file mode 120000 index 0000000000..bf37f1b011 --- /dev/null +++ b/Lang/AArch64-Assembly/Environment-variables @@ -0,0 +1 @@ +../../Task/Environment-variables/AArch64-Assembly \ No newline at end of file diff --git a/Lang/AArch64-Assembly/Fibonacci-n-step-number-sequences b/Lang/AArch64-Assembly/Fibonacci-n-step-number-sequences new file mode 120000 index 0000000000..27c6d5155d --- /dev/null +++ b/Lang/AArch64-Assembly/Fibonacci-n-step-number-sequences @@ -0,0 +1 @@ +../../Task/Fibonacci-n-step-number-sequences/AArch64-Assembly \ No newline at end of file diff --git a/Lang/AArch64-Assembly/Fibonacci-sequence b/Lang/AArch64-Assembly/Fibonacci-sequence new file mode 120000 index 0000000000..1b2a811917 --- /dev/null +++ b/Lang/AArch64-Assembly/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/AArch64-Assembly \ No newline at end of file diff --git a/Lang/AArch64-Assembly/Halt-and-catch-fire b/Lang/AArch64-Assembly/Halt-and-catch-fire new file mode 120000 index 0000000000..fcd91d9797 --- /dev/null +++ b/Lang/AArch64-Assembly/Halt-and-catch-fire @@ -0,0 +1 @@ +../../Task/Halt-and-catch-fire/AArch64-Assembly \ No newline at end of file diff --git a/Lang/AArch64-Assembly/Hash-from-two-arrays b/Lang/AArch64-Assembly/Hash-from-two-arrays new file mode 120000 index 0000000000..8f4af92c06 --- /dev/null +++ b/Lang/AArch64-Assembly/Hash-from-two-arrays @@ -0,0 +1 @@ +../../Task/Hash-from-two-arrays/AArch64-Assembly \ No newline at end of file diff --git a/Lang/AArch64-Assembly/Hofstadter-Q-sequence b/Lang/AArch64-Assembly/Hofstadter-Q-sequence new file mode 120000 index 0000000000..249eb0836e --- /dev/null +++ b/Lang/AArch64-Assembly/Hofstadter-Q-sequence @@ -0,0 +1 @@ +../../Task/Hofstadter-Q-sequence/AArch64-Assembly \ No newline at end of file diff --git a/Lang/AArch64-Assembly/Keyboard-input-Obtain-a-Y-or-N-response b/Lang/AArch64-Assembly/Keyboard-input-Obtain-a-Y-or-N-response new file mode 120000 index 0000000000..ea8bafc85e --- /dev/null +++ b/Lang/AArch64-Assembly/Keyboard-input-Obtain-a-Y-or-N-response @@ -0,0 +1 @@ +../../Task/Keyboard-input-Obtain-a-Y-or-N-response/AArch64-Assembly \ No newline at end of file diff --git a/Lang/AArch64-Assembly/Leonardo-numbers b/Lang/AArch64-Assembly/Leonardo-numbers new file mode 120000 index 0000000000..c954cc6b34 --- /dev/null +++ b/Lang/AArch64-Assembly/Leonardo-numbers @@ -0,0 +1 @@ +../../Task/Leonardo-numbers/AArch64-Assembly \ No newline at end of file diff --git a/Lang/AArch64-Assembly/Logical-operations b/Lang/AArch64-Assembly/Logical-operations new file mode 120000 index 0000000000..c765c862aa --- /dev/null +++ b/Lang/AArch64-Assembly/Logical-operations @@ -0,0 +1 @@ +../../Task/Logical-operations/AArch64-Assembly \ No newline at end of file diff --git a/Lang/AArch64-Assembly/Machine-code b/Lang/AArch64-Assembly/Machine-code new file mode 120000 index 0000000000..0510df24d2 --- /dev/null +++ b/Lang/AArch64-Assembly/Machine-code @@ -0,0 +1 @@ +../../Task/Machine-code/AArch64-Assembly \ No newline at end of file diff --git a/Lang/AArch64-Assembly/Magic-8-ball b/Lang/AArch64-Assembly/Magic-8-ball new file mode 120000 index 0000000000..1c232e0832 --- /dev/null +++ b/Lang/AArch64-Assembly/Magic-8-ball @@ -0,0 +1 @@ +../../Task/Magic-8-ball/AArch64-Assembly \ No newline at end of file diff --git a/Lang/AArch64-Assembly/Mandelbrot-set b/Lang/AArch64-Assembly/Mandelbrot-set new file mode 120000 index 0000000000..8e4411d4d0 --- /dev/null +++ b/Lang/AArch64-Assembly/Mandelbrot-set @@ -0,0 +1 @@ +../../Task/Mandelbrot-set/AArch64-Assembly \ No newline at end of file diff --git a/Lang/AArch64-Assembly/Menu b/Lang/AArch64-Assembly/Menu new file mode 120000 index 0000000000..5b0688a2c5 --- /dev/null +++ b/Lang/AArch64-Assembly/Menu @@ -0,0 +1 @@ +../../Task/Menu/AArch64-Assembly \ No newline at end of file diff --git a/Lang/AArch64-Assembly/Miller-Rabin-primality-test b/Lang/AArch64-Assembly/Miller-Rabin-primality-test deleted file mode 120000 index f452839a71..0000000000 --- a/Lang/AArch64-Assembly/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/AArch64-Assembly \ No newline at end of file diff --git a/Lang/AArch64-Assembly/Phrase-reversals b/Lang/AArch64-Assembly/Phrase-reversals new file mode 120000 index 0000000000..65751e913c --- /dev/null +++ b/Lang/AArch64-Assembly/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/AArch64-Assembly \ No newline at end of file diff --git a/Lang/AArch64-Assembly/Pi b/Lang/AArch64-Assembly/Pi new file mode 120000 index 0000000000..34be149f2d --- /dev/null +++ b/Lang/AArch64-Assembly/Pi @@ -0,0 +1 @@ +../../Task/Pi/AArch64-Assembly \ No newline at end of file diff --git a/Lang/AArch64-Assembly/Read-a-configuration-file b/Lang/AArch64-Assembly/Read-a-configuration-file new file mode 120000 index 0000000000..869fc1989f --- /dev/null +++ b/Lang/AArch64-Assembly/Read-a-configuration-file @@ -0,0 +1 @@ +../../Task/Read-a-configuration-file/AArch64-Assembly \ No newline at end of file diff --git a/Lang/AArch64-Assembly/Repeat-a-string b/Lang/AArch64-Assembly/Repeat-a-string new file mode 120000 index 0000000000..c83eefd8df --- /dev/null +++ b/Lang/AArch64-Assembly/Repeat-a-string @@ -0,0 +1 @@ +../../Task/Repeat-a-string/AArch64-Assembly \ No newline at end of file diff --git a/Lang/AArch64-Assembly/Reverse-words-in-a-string b/Lang/AArch64-Assembly/Reverse-words-in-a-string new file mode 120000 index 0000000000..2f40f86595 --- /dev/null +++ b/Lang/AArch64-Assembly/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/AArch64-Assembly \ No newline at end of file diff --git a/Lang/AArch64-Assembly/Sorting-Algorithms-Circle-Sort b/Lang/AArch64-Assembly/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 6922a69550..0000000000 --- a/Lang/AArch64-Assembly/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/AArch64-Assembly \ No newline at end of file diff --git a/Lang/AArch64-Assembly/Strip-block-comments b/Lang/AArch64-Assembly/Strip-block-comments new file mode 120000 index 0000000000..4a2741cf35 --- /dev/null +++ b/Lang/AArch64-Assembly/Strip-block-comments @@ -0,0 +1 @@ +../../Task/Strip-block-comments/AArch64-Assembly \ No newline at end of file diff --git a/Lang/AArch64-Assembly/Strip-comments-from-a-string b/Lang/AArch64-Assembly/Strip-comments-from-a-string new file mode 120000 index 0000000000..1e7fb59c48 --- /dev/null +++ b/Lang/AArch64-Assembly/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/AArch64-Assembly \ No newline at end of file diff --git a/Lang/AArch64-Assembly/Strip-whitespace-from-a-string-Top-and-tail b/Lang/AArch64-Assembly/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..115198d3ea --- /dev/null +++ b/Lang/AArch64-Assembly/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/AArch64-Assembly \ No newline at end of file diff --git a/Lang/AArch64-Assembly/Twos-complement b/Lang/AArch64-Assembly/Twos-complement new file mode 120000 index 0000000000..92454eff57 --- /dev/null +++ b/Lang/AArch64-Assembly/Twos-complement @@ -0,0 +1 @@ +../../Task/Twos-complement/AArch64-Assembly \ No newline at end of file diff --git a/Lang/AArch64-Assembly/Update-a-configuration-file b/Lang/AArch64-Assembly/Update-a-configuration-file new file mode 120000 index 0000000000..c28afd01b6 --- /dev/null +++ b/Lang/AArch64-Assembly/Update-a-configuration-file @@ -0,0 +1 @@ +../../Task/Update-a-configuration-file/AArch64-Assembly \ No newline at end of file diff --git a/Lang/AArch64-Assembly/Vigen-re-cipher b/Lang/AArch64-Assembly/Vigen-re-cipher new file mode 120000 index 0000000000..02254d1d9a --- /dev/null +++ b/Lang/AArch64-Assembly/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/AArch64-Assembly \ No newline at end of file diff --git a/Lang/AArch64-Assembly/Vigen-re-cipher-Cryptanalysis b/Lang/AArch64-Assembly/Vigen-re-cipher-Cryptanalysis new file mode 120000 index 0000000000..cc7f7e2227 --- /dev/null +++ b/Lang/AArch64-Assembly/Vigen-re-cipher-Cryptanalysis @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher-Cryptanalysis/AArch64-Assembly \ No newline at end of file diff --git a/Lang/AArch64-Assembly/Visualize-a-tree b/Lang/AArch64-Assembly/Visualize-a-tree new file mode 120000 index 0000000000..a3e4c5223f --- /dev/null +++ b/Lang/AArch64-Assembly/Visualize-a-tree @@ -0,0 +1 @@ +../../Task/Visualize-a-tree/AArch64-Assembly \ No newline at end of file diff --git a/Lang/ABAP/00-LANG.txt b/Lang/ABAP/00-LANG.txt index 446b44c265..819bd4cbc5 100644 --- a/Lang/ABAP/00-LANG.txt +++ b/Lang/ABAP/00-LANG.txt @@ -1,2 +1,14 @@ -{{stub}}{{language|site=http://www.sdn.sap.com/irj/sdn/abap}} -ABAP (Advanced Business Application Programming) is a programming language developed by the german software vendor SAP. It is mainly used to build high performance business applications. \ No newline at end of file +{{stub}}{{language +|site=http://www.sdn.sap.com/irj/sdn/abap +|safety=safe +|strength=strong +|compat=nominative +|checking=static +|tags=abap}} +ABAP (Advanced Business Application Programming) is a programming language developed by the german software vendor SAP. It is mainly used to build high performance business applications. + +==Citation== +*[https://en.wikipedia.org/wiki/ABAP] + +[[Category:Programming paradigm/Object-oriented]] +[[Category:Programming paradigm/Imperative]] \ No newline at end of file diff --git a/Lang/ABC/Arithmetic-derivative b/Lang/ABC/Arithmetic-derivative new file mode 120000 index 0000000000..4225078056 --- /dev/null +++ b/Lang/ABC/Arithmetic-derivative @@ -0,0 +1 @@ +../../Task/Arithmetic-derivative/ABC \ No newline at end of file diff --git a/Lang/ABC/Look-and-say-sequence b/Lang/ABC/Look-and-say-sequence new file mode 120000 index 0000000000..68b9661932 --- /dev/null +++ b/Lang/ABC/Look-and-say-sequence @@ -0,0 +1 @@ +../../Task/Look-and-say-sequence/ABC \ No newline at end of file diff --git a/Lang/ABC/Population-count b/Lang/ABC/Population-count new file mode 120000 index 0000000000..6bd44c7e1e --- /dev/null +++ b/Lang/ABC/Population-count @@ -0,0 +1 @@ +../../Task/Population-count/ABC \ No newline at end of file diff --git a/Lang/ABC/Square-but-not-cube b/Lang/ABC/Square-but-not-cube new file mode 120000 index 0000000000..23a046e711 --- /dev/null +++ b/Lang/ABC/Square-but-not-cube @@ -0,0 +1 @@ +../../Task/Square-but-not-cube/ABC \ No newline at end of file diff --git a/Lang/ABC/Zeckendorf-number-representation b/Lang/ABC/Zeckendorf-number-representation new file mode 120000 index 0000000000..8384d29a12 --- /dev/null +++ b/Lang/ABC/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/ABC \ No newline at end of file diff --git a/Lang/AIDED-NATURAL-LANGUAGE/00-LANG.txt b/Lang/AIDED-NATURAL-LANGUAGE/00-LANG.txt new file mode 100644 index 0000000000..c25a056976 --- /dev/null +++ b/Lang/AIDED-NATURAL-LANGUAGE/00-LANG.txt @@ -0,0 +1 @@ +{{stub}}{{language|Ayrch}} \ No newline at end of file diff --git a/Lang/AIDED-NATURAL-LANGUAGE/00-META.yaml b/Lang/AIDED-NATURAL-LANGUAGE/00-META.yaml new file mode 100644 index 0000000000..8395003e03 --- /dev/null +++ b/Lang/AIDED-NATURAL-LANGUAGE/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:AIDED_NATURAL_LANGUAGE diff --git a/Lang/ALGOL-60/00-LANG.txt b/Lang/ALGOL-60/00-LANG.txt index 725689b57a..2f04de0a7d 100644 --- a/Lang/ALGOL-60/00-LANG.txt +++ b/Lang/ALGOL-60/00-LANG.txt @@ -16,4 +16,9 @@ gcc hello.c -lalgol -lm -o hello *[[wp:ALGOL 60|ALGOL 60 on Wikipedia]] *[[ALGOL 68]] *[[ALGOL W]] -*[[Simula]] \ No newline at end of file +*[[Simula]] + +==External links== +* [http://algol60.org algol60.org] +* [https://softwarepreservation.computerhistory.org/ALGOL/ History of ALGOL] Includes links to documentation (e.g. reports) +* [https://www.masswerk.at/algol60/report.htm Revised Report on the Algorithmic Language Algol 60] (HTML) \ No newline at end of file diff --git a/Lang/ALGOL-60/Additive-primes b/Lang/ALGOL-60/Additive-primes new file mode 120000 index 0000000000..360a570784 --- /dev/null +++ b/Lang/ALGOL-60/Additive-primes @@ -0,0 +1 @@ +../../Task/Additive-primes/ALGOL-60 \ No newline at end of file diff --git a/Lang/ALGOL-60/Anti-primes b/Lang/ALGOL-60/Anti-primes new file mode 120000 index 0000000000..6d19745d0e --- /dev/null +++ b/Lang/ALGOL-60/Anti-primes @@ -0,0 +1 @@ +../../Task/Anti-primes/ALGOL-60 \ No newline at end of file diff --git a/Lang/ALGOL-60/Even-or-odd b/Lang/ALGOL-60/Even-or-odd new file mode 120000 index 0000000000..13baeccf6c --- /dev/null +++ b/Lang/ALGOL-60/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/ALGOL-60 \ No newline at end of file diff --git a/Lang/ALGOL-60/Factorial b/Lang/ALGOL-60/Factorial deleted file mode 120000 index 67b243e1d0..0000000000 --- a/Lang/ALGOL-60/Factorial +++ /dev/null @@ -1 +0,0 @@ -../../Task/Factorial/ALGOL-60 \ No newline at end of file diff --git a/Lang/ALGOL-60/Harmonic-series b/Lang/ALGOL-60/Harmonic-series new file mode 120000 index 0000000000..a1eefb4086 --- /dev/null +++ b/Lang/ALGOL-60/Harmonic-series @@ -0,0 +1 @@ +../../Task/Harmonic-series/ALGOL-60 \ No newline at end of file diff --git a/Lang/ALGOL-60/Horners-rule-for-polynomial-evaluation b/Lang/ALGOL-60/Horners-rule-for-polynomial-evaluation new file mode 120000 index 0000000000..2a520e0e7c --- /dev/null +++ b/Lang/ALGOL-60/Horners-rule-for-polynomial-evaluation @@ -0,0 +1 @@ +../../Task/Horners-rule-for-polynomial-evaluation/ALGOL-60 \ No newline at end of file diff --git a/Lang/ALGOL-60/Integer-comparison b/Lang/ALGOL-60/Integer-comparison new file mode 120000 index 0000000000..54a6736fa3 --- /dev/null +++ b/Lang/ALGOL-60/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/ALGOL-60 \ No newline at end of file diff --git a/Lang/ALGOL-60/Largest-proper-divisor-of-n b/Lang/ALGOL-60/Largest-proper-divisor-of-n new file mode 120000 index 0000000000..bd5f1adbca --- /dev/null +++ b/Lang/ALGOL-60/Largest-proper-divisor-of-n @@ -0,0 +1 @@ +../../Task/Largest-proper-divisor-of-n/ALGOL-60 \ No newline at end of file diff --git a/Lang/ALGOL-60/Loops-Increment-loop-index-within-loop-body b/Lang/ALGOL-60/Loops-Increment-loop-index-within-loop-body new file mode 120000 index 0000000000..b6ef8c8c0c --- /dev/null +++ b/Lang/ALGOL-60/Loops-Increment-loop-index-within-loop-body @@ -0,0 +1 @@ +../../Task/Loops-Increment-loop-index-within-loop-body/ALGOL-60 \ No newline at end of file diff --git a/Lang/ALGOL-60/Nth-root b/Lang/ALGOL-60/Nth-root new file mode 120000 index 0000000000..3032f52453 --- /dev/null +++ b/Lang/ALGOL-60/Nth-root @@ -0,0 +1 @@ +../../Task/Nth-root/ALGOL-60 \ No newline at end of file diff --git a/Lang/ALGOL-60/Prime-decomposition b/Lang/ALGOL-60/Prime-decomposition new file mode 120000 index 0000000000..cd5f625ac0 --- /dev/null +++ b/Lang/ALGOL-60/Prime-decomposition @@ -0,0 +1 @@ +../../Task/Prime-decomposition/ALGOL-60 \ No newline at end of file diff --git a/Lang/ALGOL-60/Proper-divisors b/Lang/ALGOL-60/Proper-divisors new file mode 120000 index 0000000000..7bb12e66dd --- /dev/null +++ b/Lang/ALGOL-60/Proper-divisors @@ -0,0 +1 @@ +../../Task/Proper-divisors/ALGOL-60 \ No newline at end of file diff --git a/Lang/ALGOL-60/Semiprime b/Lang/ALGOL-60/Semiprime new file mode 120000 index 0000000000..0981557b93 --- /dev/null +++ b/Lang/ALGOL-60/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/ALGOL-60 \ No newline at end of file diff --git a/Lang/ALGOL-60/Sequence-of-primes-by-trial-division b/Lang/ALGOL-60/Sequence-of-primes-by-trial-division new file mode 120000 index 0000000000..b95a2ebdcc --- /dev/null +++ b/Lang/ALGOL-60/Sequence-of-primes-by-trial-division @@ -0,0 +1 @@ +../../Task/Sequence-of-primes-by-trial-division/ALGOL-60 \ No newline at end of file diff --git a/Lang/ALGOL-60/Square-free-integers b/Lang/ALGOL-60/Square-free-integers new file mode 120000 index 0000000000..caff91a536 --- /dev/null +++ b/Lang/ALGOL-60/Square-free-integers @@ -0,0 +1 @@ +../../Task/Square-free-integers/ALGOL-60 \ No newline at end of file diff --git a/Lang/ALGOL-60/Sum-of-a-series b/Lang/ALGOL-60/Sum-of-a-series new file mode 120000 index 0000000000..48b6d3380c --- /dev/null +++ b/Lang/ALGOL-60/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/ALGOL-60 \ No newline at end of file diff --git a/Lang/ALGOL-60/Tau-function b/Lang/ALGOL-60/Tau-function new file mode 120000 index 0000000000..5e48edf00f --- /dev/null +++ b/Lang/ALGOL-60/Tau-function @@ -0,0 +1 @@ +../../Task/Tau-function/ALGOL-60 \ No newline at end of file diff --git a/Lang/ALGOL-60/Tau-number b/Lang/ALGOL-60/Tau-number new file mode 120000 index 0000000000..a054d3d6bb --- /dev/null +++ b/Lang/ALGOL-60/Tau-number @@ -0,0 +1 @@ +../../Task/Tau-number/ALGOL-60 \ No newline at end of file diff --git a/Lang/ALGOL-68/00-LANG.txt b/Lang/ALGOL-68/00-LANG.txt index c77464279f..0415892136 100644 --- a/Lang/ALGOL-68/00-LANG.txt +++ b/Lang/ALGOL-68/00-LANG.txt @@ -41,7 +41,7 @@ A syntax chart is available [http://www.softwarepreservation.org/projects/ALGOL/ * [http://www.linkedin.com/groups/Algol68-2333923 Algol68 group at linkedin] - includes various famous compiler composers.
'''Books available online''': -* [http://jmvdveer.home.xs4all.nl/en.algol-68-genie.html Algol 68G Manual - By Marcel van der Veer] Includes the Revised Report +* [https://algol68genie.nl/ Algol 68G Manual - By Marcel van der Veer] Includes the Revised Report * [http://www.softwarepreservation.org/projects/ALGOL/book/pame.2008.a4.pdf/view Programming Algol 68 Made Easy - by Sian Mountbatten (on softwarepreservation.org)] * [http://www.softwarepreservation.org/projects/ALGOL/book/Lindsey_van_der_Meulen-IItA68-Revised.pdf/view Informal Introduction to Algol 68 - by C. H. Lindsey & S. V. Van der Meulen (on softwarepreservation.org)] - if you prefer (and find) a hardcopy, be sure to get the 1977 edition. Highly recomended! @@ -59,7 +59,7 @@ A syntax chart is available [http://www.softwarepreservation.org/projects/ALGOL/ ** AND 50th Birthday '''ALGOL 58'''. * 23rd August 2009 - [http://sourceforge.net/projects/algol68/files/ algol68g-1.18.0-9h] released * 20th December 2009 - Happy 51st/41st Birthdays with [[Hamming_numbers#ALGOL_68|Hamming numbers]] - the 200th '''ALGOL 68''' code contribution on rosettacode.org! -** This time code was by [[User:Algol68g|Marcel van der Veer]], author of [http://www.xs4all.nl/~jmvdveer/algol.html Algol 68 Genie] +** This time code was by [[User:Algol68g|Marcel van der Veer]], author of [https://algol68genie.nl Algol 68 Genie] * 25th October 2011 - [[User:Jejones3141|Jejones3141]] added [[Soundex#ALGOL_68|Soundex]] - the 300th '''ALGOL 68''' code specimen. == Revisions == @@ -67,203 +67,12 @@ A syntax chart is available [http://www.softwarepreservation.org/projects/ALGOL/ *Oct. 1968: Penultimate Draft Report on the Algorithmic Language ALGOL 68 - Chapters 1-9 - Edited by: A. van Wijngaarden, B.J. Mailloux, J.E.L. Peck and C.H.A. Koster. *Dec. 1968: Report on the Algorithmic Language ALGOL 68 - Offprint from Numerische Mathematik, 14, 79-218 (1969); Springer-Verlag. - Edited by: A. van Wijngaarden, B.J. Mailloux, J.E.L. Peck and C.H.A. Koster. *Sep 1973: Revised Report on the Algorithmic Language Algol 68 - Springer-Verlag 1976 - Edited by: A. van Wijngaarden, B.J. Mailloux, J.E.L. Peck, C.H.A. Koster, M. Sintzoff, C.H. Lindsey, L.G.L.T. Meertens and R.G. Fisker. -==Coding style of samples== -Click "Expand" for more details. -
-
- -Many of the code samples provided here have a leading main:( and a matching ) at the end. These are not actually required in the language, but are included so as to highlight the main routine. - -On some compilers, it may be necessary to include appropriate "job cards" -or preludes in order for the programs to compile successfully. Hopefully -not too much else is required. Examples: -{|border="1" style="border-collapse: collapse; border: 5px double grey;" align="center" -|| Brief Algol68 -|| Algol68 as in rosettacode -|| Actual ELLA Algol 68RS code -|- -|| - print(("Hello, world!",new line)) -|| - main:( - print(("Hello, world!",new line)) - ) -|| - PROGRAM helloworld CONTEXT VOID - USE standard - BEGIN - print(("Hello, world!", new line)) - END - FINISH -|} -

'''Examples of different program representations''' -

-At the time when ALGOL 68 was defined some predominant computers had -24 or 36 bit words, with 6 bit character sets. Hence it was desirable that -ALGOL 68 should be able to run on machines with only uppercase. -The official spec provided for different representations of the same -program. Quote stropping (enclosing the bold words in single quotes) -and Point stropping (preceeding the bold words with a dot) -were used. A variant of Point stropping called RES stropping was also defined. -In RES stropping some language-defined bold words are not preceded by a dot. -A pragmatic comment may have been required to indicate which -stropping convention was to be used, as in some of the examples below. -Upper stropping (representing the bold words by upper case and -non-bold words in lower case) was introduced by Algol 68R. Upper stropping -is used by Algol 68RS and is one of the options for Algol 68G. -Rutgers ALGOL 68 uses quote stropping. Most of the samples -on Rosetta Code use Upper stropping. -Examples (pragmatic comments to set the stropping regime not shown): -{|border="1" style="border-collapse: collapse; border: 2px double grey;" align="left" -|| Algol68 as typically published - '''mode''' '''xint''' = '''int'''; - '''xint''' sum sq:=0; - '''for''' i '''while''' - sum sq≠70×70 - '''do''' - sum sq+:=i↑2 - '''od''' -|| QUOTE stropping (similar to wiki) - 'mode' 'xint' = 'int'; - 'xint' sum sq:=0; - 'for' i 'while' - sum sq≠70×70 - 'do' - sum sq+:=i↑2 - 'od' -|| POINT stropping - .MODE .XINT = .INT; - .XINT SUM SQ:=0; - .FOR I .WHILE - SUM SQ .NE 70*70 - .DO - SUM SQ .PLUSAB I .UP 2 - .OD -|| RES stropping - mode .xint = int; - .xint sum sq:=0; - for i while - sum sq≠70×70 - do - sum sq+:=i↑2 - od -|| Upper stropping - MODE XINT = INT; - XINT sum sq:=0; - FOR i WHILE - sum sq /= 70*70 - DO - sum sq PLUSAB i UP 2 - OD -|} - -
+==Coding style of samples, alphabets and stropping== +See [[ALGOL 68 Representation]]. == Coercion (casting) == -ALGOL 68 has a hierarchy of contexts which determine which kind of coercions are available at a particular point in the program. -
-Click "Expand" for more details. -
-
- -These contexts are: -{|class="wikitable" -!rowspan=2| N
-a
-m
-e -!rowspan=2| Context location -!colspan=5| Coercions available in this context -!rowspan=2| Coercion examples -|- -|bgcolor=aaaaff|Soft -|bgcolor=aaeeaa|Weak -|bgcolor=ffee99|Meek -|bgcolor=ffcc99|Firm -|bgcolor=ffcccc|Strong -|- -!S
-t
-r
-o
-n
-g -||Right hand side of: -* Identity-declarations, as "~" in: REAL x = ~ -* Initialisations, as "~" in: REAL x := ~ -Also: -* Actual-parameters of calls, as "~" in:PROC: sin(~) -* Enclosed clauses of casts, as "~" in: REAL(~) -* Units of routine-texts -* Statements yielding VOID -* All parts (but one) of a balanced clause -* One side of an identity relation, as "~" in: ~ IS ~ -|bgcolor=aaaaff rowspan=4 width="50px"| deproc- eduring -|bgcolor=aaeeaa rowspan=3 width="50px"| all '''soft''' then weak deref- erencing -|bgcolor=ffee99 rowspan=2 width="50px"| all '''weak''' then deref- erencing -|bgcolor=ffcc99 rowspan=1 width="50px"| all '''meek''' then uniting -|bgcolor=ffcccc width="50px"| all '''firm''' then widening, rowing and voiding -|colspan=1 bgcolor=ffcccc| -Widening occurs if there is no loss of precision. For example: An INT will be coerced to a REAL, and a REAL will be coerced to a LONG REAL. But not vice-versa. Examples: -INT to LONG INT -INT to REAL -REAL to COMPL -BITS to []BOOL -BYTES to STRING -A variable can also be coerced (rowed) to an array of length 1. - -For example: -INT to [1]INT -REAL to [1]REAL etc -|- -!F
-i
-r
-m -|| -*Operands of formulas as "~" in:OP: ~ * ~ -*Parameters of transput calls -|colspan=3 bgcolor=ffcc99| Example: -UNION(INT,REAL) var := 1 -|- -!M
-e
-e
-k -|| -* Trimscripts (yielding INT) -* Enquiries: e.g. as "~" in the following -IF ~ THEN ... FI and -FROM ~ BY ~ TO ~ WHILE ~ DO ... OD etc -* Primaries of calls (e.g. sin in sin(x)) -|colspan=4 bgcolor=ffee99|Examples: -REF REF BOOL to BOOL -REF REF REF INT to INT -|- -!W
-e
-a
-k -|| -* Primaries of slices, as in "~" in: ~[1:99] -* Secondaries of selections, as "~" in: value OF ~ -|colspan=5 bgcolor=aaeeaa|Examples: -REF BOOL to REF BOOL -REF REF INT to REF INT -REF REF REF REAL to REF REAL -REF REF REF REF STRUCT to REF STRUCT -|- -!S
-o
-f
-t -|| The LHS of assignments, as "~" in: ~ := ... -|colspan=6 bgcolor=aaaaff| Example: -* deproceduring of: PROC REAL random: e.g. random -|} -For more details about Primaries and Secondaries refer to [[Operator_precedence#ALGOL_68|Operator precedence]]. - -
+ALGOL 68 has a hierarchy of contexts which determine which kind of coercions are available at a particular point in the program.
+See [[:Category:ALGOL_68_Coercions|ALGOL 68 Coercions]] for more details. ==See also== *[[Web 68]] @@ -273,13 +82,22 @@ For more details about Primaries and Secondaries refer to [[Operator_precedence# * [[Action!]] * [[Agena]] * [[Draco]] +* [[RTL/2]] * [https://en.wikipedia.org/wiki/S3_(programming_language) S3 for ICL 2900] == Library code used in Rosetta Code samples == -[https://rosettacode.org/wiki/ALGOL_68/prelude Various (including the standard prelude)]
-[https://rosettacode.org/wiki/Category:ALGOL_68-primes Prime related]
-[https://rosettacode.org/wiki/Category:ALGOL_68-rows Row (array) related]
-[https://rosettacode.org/wiki/Category:ALGOL_68-l-system L-System related] +* [[ALGOL_68/prelude|Various (including the standard prelude)]] +* +* [[:Category:ALGOL_68-bits|bit-manipulation related]] +* [[:Category:ALGOL_68-files|File related]] +* [[:Category:ALGOL_68-l-system|L-System related]] +* [[:Category:ALGOL_68-primes|Prime related]] +* [[:Category:ALGOL_68-rows|Row (array) related]] +* [[:Category:ALGOL_68-sort|Sorting related]] + +== Tools == +[[Syntax_highlighting_using_Mediawiki_formatting#ALGOL 68|Format an upper-stropped Algol 68 source with Mediawiki markup]]
+[[Compiler/Simple_file_inclusion_pre_processor#ALGOL 68|Implement ''read'' and ''include'' pragmatic-comments for compilers that don't support file inclusion]] {{language programming paradigm|Concurrent}} {{language programming paradigm|Imperative}} \ No newline at end of file diff --git a/Lang/ALGOL-68/100-prisoners b/Lang/ALGOL-68/100-prisoners new file mode 120000 index 0000000000..f6c4da597a --- /dev/null +++ b/Lang/ALGOL-68/100-prisoners @@ -0,0 +1 @@ +../../Task/100-prisoners/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/21-game b/Lang/ALGOL-68/21-game new file mode 120000 index 0000000000..76ba9066d7 --- /dev/null +++ b/Lang/ALGOL-68/21-game @@ -0,0 +1 @@ +../../Task/21-game/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/9-billion-names-of-God-the-integer b/Lang/ALGOL-68/9-billion-names-of-God-the-integer new file mode 120000 index 0000000000..01c632e0dd --- /dev/null +++ b/Lang/ALGOL-68/9-billion-names-of-God-the-integer @@ -0,0 +1 @@ +../../Task/9-billion-names-of-God-the-integer/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Archimedean-spiral b/Lang/ALGOL-68/Archimedean-spiral new file mode 120000 index 0000000000..64c4988ade --- /dev/null +++ b/Lang/ALGOL-68/Archimedean-spiral @@ -0,0 +1 @@ +../../Task/Archimedean-spiral/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Arithmetic-geometric-mean-Calculate-Pi b/Lang/ALGOL-68/Arithmetic-geometric-mean-Calculate-Pi new file mode 120000 index 0000000000..1c8bcda555 --- /dev/null +++ b/Lang/ALGOL-68/Arithmetic-geometric-mean-Calculate-Pi @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean-Calculate-Pi/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Bifid-cipher b/Lang/ALGOL-68/Bifid-cipher new file mode 120000 index 0000000000..5e9da259ac --- /dev/null +++ b/Lang/ALGOL-68/Bifid-cipher @@ -0,0 +1 @@ +../../Task/Bifid-cipher/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Bioinformatics-base-count b/Lang/ALGOL-68/Bioinformatics-base-count deleted file mode 120000 index cb9d66b55c..0000000000 --- a/Lang/ALGOL-68/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Biorhythms b/Lang/ALGOL-68/Biorhythms new file mode 120000 index 0000000000..b15056dfc9 --- /dev/null +++ b/Lang/ALGOL-68/Biorhythms @@ -0,0 +1 @@ +../../Task/Biorhythms/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Bitmap-B-zier-curves-Quadratic b/Lang/ALGOL-68/Bitmap-B-zier-curves-Quadratic new file mode 120000 index 0000000000..30ab56c310 --- /dev/null +++ b/Lang/ALGOL-68/Bitmap-B-zier-curves-Quadratic @@ -0,0 +1 @@ +../../Task/Bitmap-B-zier-curves-Quadratic/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Burrows-Wheeler-transform b/Lang/ALGOL-68/Burrows-Wheeler-transform new file mode 120000 index 0000000000..203e0e501f --- /dev/null +++ b/Lang/ALGOL-68/Burrows-Wheeler-transform @@ -0,0 +1 @@ +../../Task/Burrows-Wheeler-transform/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Chaocipher b/Lang/ALGOL-68/Chaocipher new file mode 120000 index 0000000000..1d4c0173db --- /dev/null +++ b/Lang/ALGOL-68/Chaocipher @@ -0,0 +1 @@ +../../Task/Chaocipher/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Chernicks-Carmichael-numbers b/Lang/ALGOL-68/Chernicks-Carmichael-numbers new file mode 120000 index 0000000000..ebdbb0354b --- /dev/null +++ b/Lang/ALGOL-68/Chernicks-Carmichael-numbers @@ -0,0 +1 @@ +../../Task/Chernicks-Carmichael-numbers/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Convex-hull b/Lang/ALGOL-68/Convex-hull new file mode 120000 index 0000000000..6ded12cc5d --- /dev/null +++ b/Lang/ALGOL-68/Convex-hull @@ -0,0 +1 @@ +../../Task/Convex-hull/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Date-manipulation b/Lang/ALGOL-68/Date-manipulation new file mode 120000 index 0000000000..700d602cf1 --- /dev/null +++ b/Lang/ALGOL-68/Date-manipulation @@ -0,0 +1 @@ +../../Task/Date-manipulation/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/De-Bruijn-sequences b/Lang/ALGOL-68/De-Bruijn-sequences new file mode 120000 index 0000000000..1c1a7f459e --- /dev/null +++ b/Lang/ALGOL-68/De-Bruijn-sequences @@ -0,0 +1 @@ +../../Task/De-Bruijn-sequences/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Demings-funnel b/Lang/ALGOL-68/Demings-funnel new file mode 120000 index 0000000000..c30e5a173e --- /dev/null +++ b/Lang/ALGOL-68/Demings-funnel @@ -0,0 +1 @@ +../../Task/Demings-funnel/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Determinant-and-permanent b/Lang/ALGOL-68/Determinant-and-permanent new file mode 120000 index 0000000000..e8a753594d --- /dev/null +++ b/Lang/ALGOL-68/Determinant-and-permanent @@ -0,0 +1 @@ +../../Task/Determinant-and-permanent/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Dice-game-probabilities b/Lang/ALGOL-68/Dice-game-probabilities new file mode 120000 index 0000000000..9b1e59ee7b --- /dev/null +++ b/Lang/ALGOL-68/Dice-game-probabilities @@ -0,0 +1 @@ +../../Task/Dice-game-probabilities/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Display-an-outline-as-a-nested-table b/Lang/ALGOL-68/Display-an-outline-as-a-nested-table new file mode 120000 index 0000000000..41ea472cc8 --- /dev/null +++ b/Lang/ALGOL-68/Display-an-outline-as-a-nested-table @@ -0,0 +1 @@ +../../Task/Display-an-outline-as-a-nested-table/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Distribution-of-0-digits-in-factorial-series b/Lang/ALGOL-68/Distribution-of-0-digits-in-factorial-series new file mode 120000 index 0000000000..242e3aeb60 --- /dev/null +++ b/Lang/ALGOL-68/Distribution-of-0-digits-in-factorial-series @@ -0,0 +1 @@ +../../Task/Distribution-of-0-digits-in-factorial-series/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Draw-a-cuboid b/Lang/ALGOL-68/Draw-a-cuboid new file mode 120000 index 0000000000..3102af7fc7 --- /dev/null +++ b/Lang/ALGOL-68/Draw-a-cuboid @@ -0,0 +1 @@ +../../Task/Draw-a-cuboid/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Elementary-cellular-automaton-Random-number-generator b/Lang/ALGOL-68/Elementary-cellular-automaton-Random-number-generator new file mode 120000 index 0000000000..a4aed0fa0e --- /dev/null +++ b/Lang/ALGOL-68/Elementary-cellular-automaton-Random-number-generator @@ -0,0 +1 @@ +../../Task/Elementary-cellular-automaton-Random-number-generator/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Elliptic-curve-arithmetic b/Lang/ALGOL-68/Elliptic-curve-arithmetic new file mode 120000 index 0000000000..88681d69e9 --- /dev/null +++ b/Lang/ALGOL-68/Elliptic-curve-arithmetic @@ -0,0 +1 @@ +../../Task/Elliptic-curve-arithmetic/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Factorial b/Lang/ALGOL-68/Factorial deleted file mode 120000 index b406800839..0000000000 --- a/Lang/ALGOL-68/Factorial +++ /dev/null @@ -1 +0,0 @@ -../../Task/Factorial/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Factorial-base-numbers-indexing-permutations-of-a-collection b/Lang/ALGOL-68/Factorial-base-numbers-indexing-permutations-of-a-collection new file mode 120000 index 0000000000..ab36c72f12 --- /dev/null +++ b/Lang/ALGOL-68/Factorial-base-numbers-indexing-permutations-of-a-collection @@ -0,0 +1 @@ +../../Task/Factorial-base-numbers-indexing-permutations-of-a-collection/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Four-is-magic b/Lang/ALGOL-68/Four-is-magic new file mode 120000 index 0000000000..007db868ed --- /dev/null +++ b/Lang/ALGOL-68/Four-is-magic @@ -0,0 +1 @@ +../../Task/Four-is-magic/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/IBAN b/Lang/ALGOL-68/IBAN new file mode 120000 index 0000000000..08ea01a928 --- /dev/null +++ b/Lang/ALGOL-68/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Jaro-similarity b/Lang/ALGOL-68/Jaro-similarity new file mode 120000 index 0000000000..0255b5f0fa --- /dev/null +++ b/Lang/ALGOL-68/Jaro-similarity @@ -0,0 +1 @@ +../../Task/Jaro-similarity/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Jordan-P-lya-numbers b/Lang/ALGOL-68/Jordan-P-lya-numbers new file mode 120000 index 0000000000..6750737d48 --- /dev/null +++ b/Lang/ALGOL-68/Jordan-P-lya-numbers @@ -0,0 +1 @@ +../../Task/Jordan-P-lya-numbers/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Juggler-sequence b/Lang/ALGOL-68/Juggler-sequence new file mode 120000 index 0000000000..2c24c77bfb --- /dev/null +++ b/Lang/ALGOL-68/Juggler-sequence @@ -0,0 +1 @@ +../../Task/Juggler-sequence/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Knapsack-problem-0-1 b/Lang/ALGOL-68/Knapsack-problem-0-1 new file mode 120000 index 0000000000..38cd6f2ecb --- /dev/null +++ b/Lang/ALGOL-68/Knapsack-problem-0-1 @@ -0,0 +1 @@ +../../Task/Knapsack-problem-0-1/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Knapsack-problem-Continuous b/Lang/ALGOL-68/Knapsack-problem-Continuous new file mode 120000 index 0000000000..f49865cc46 --- /dev/null +++ b/Lang/ALGOL-68/Knapsack-problem-Continuous @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Continuous/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/LU-decomposition b/Lang/ALGOL-68/LU-decomposition new file mode 120000 index 0000000000..3453e9548a --- /dev/null +++ b/Lang/ALGOL-68/LU-decomposition @@ -0,0 +1 @@ +../../Task/LU-decomposition/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Legendre-prime-counting-function b/Lang/ALGOL-68/Legendre-prime-counting-function new file mode 120000 index 0000000000..f71f764e65 --- /dev/null +++ b/Lang/ALGOL-68/Legendre-prime-counting-function @@ -0,0 +1 @@ +../../Task/Legendre-prime-counting-function/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Logistic-curve-fitting-in-epidemiology b/Lang/ALGOL-68/Logistic-curve-fitting-in-epidemiology new file mode 120000 index 0000000000..508ef46a64 --- /dev/null +++ b/Lang/ALGOL-68/Logistic-curve-fitting-in-epidemiology @@ -0,0 +1 @@ +../../Task/Logistic-curve-fitting-in-epidemiology/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Longest-increasing-subsequence b/Lang/ALGOL-68/Longest-increasing-subsequence new file mode 120000 index 0000000000..a09c83eed3 --- /dev/null +++ b/Lang/ALGOL-68/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Mayan-numerals b/Lang/ALGOL-68/Mayan-numerals new file mode 120000 index 0000000000..901b0eac41 --- /dev/null +++ b/Lang/ALGOL-68/Mayan-numerals @@ -0,0 +1 @@ +../../Task/Mayan-numerals/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Meissel-Mertens-constant b/Lang/ALGOL-68/Meissel-Mertens-constant deleted file mode 120000 index e7b400c689..0000000000 --- a/Lang/ALGOL-68/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Miller-Rabin-primality-test b/Lang/ALGOL-68/Miller-Rabin-primality-test deleted file mode 120000 index c0a1c115c4..0000000000 --- a/Lang/ALGOL-68/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Partition-function-P b/Lang/ALGOL-68/Partition-function-P new file mode 120000 index 0000000000..98f6538801 --- /dev/null +++ b/Lang/ALGOL-68/Partition-function-P @@ -0,0 +1 @@ +../../Task/Partition-function-P/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Pentagram b/Lang/ALGOL-68/Pentagram new file mode 120000 index 0000000000..7ab101a89e --- /dev/null +++ b/Lang/ALGOL-68/Pentagram @@ -0,0 +1 @@ +../../Task/Pentagram/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Perlin-noise b/Lang/ALGOL-68/Perlin-noise new file mode 120000 index 0000000000..8bd6981103 --- /dev/null +++ b/Lang/ALGOL-68/Perlin-noise @@ -0,0 +1 @@ +../../Task/Perlin-noise/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Permutation-test b/Lang/ALGOL-68/Permutation-test new file mode 120000 index 0000000000..1a8b7f20df --- /dev/null +++ b/Lang/ALGOL-68/Permutation-test @@ -0,0 +1 @@ +../../Task/Permutation-test/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Primes---allocate-descendants-to-their-ancestors b/Lang/ALGOL-68/Primes---allocate-descendants-to-their-ancestors new file mode 120000 index 0000000000..9bf6ed3e36 --- /dev/null +++ b/Lang/ALGOL-68/Primes---allocate-descendants-to-their-ancestors @@ -0,0 +1 @@ +../../Task/Primes---allocate-descendants-to-their-ancestors/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Pythagoras-tree b/Lang/ALGOL-68/Pythagoras-tree new file mode 120000 index 0000000000..8c304d8b68 --- /dev/null +++ b/Lang/ALGOL-68/Pythagoras-tree @@ -0,0 +1 @@ +../../Task/Pythagoras-tree/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Quaternion-type b/Lang/ALGOL-68/Quaternion-type deleted file mode 120000 index 9934ee409f..0000000000 --- a/Lang/ALGOL-68/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Quoting-constructs b/Lang/ALGOL-68/Quoting-constructs new file mode 120000 index 0000000000..7f6defd772 --- /dev/null +++ b/Lang/ALGOL-68/Quoting-constructs @@ -0,0 +1 @@ +../../Task/Quoting-constructs/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Ramanujans-constant b/Lang/ALGOL-68/Ramanujans-constant new file mode 120000 index 0000000000..7fce932657 --- /dev/null +++ b/Lang/ALGOL-68/Ramanujans-constant @@ -0,0 +1 @@ +../../Task/Ramanujans-constant/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Sailors-coconuts-and-a-monkey-problem b/Lang/ALGOL-68/Sailors-coconuts-and-a-monkey-problem new file mode 120000 index 0000000000..c84573878e --- /dev/null +++ b/Lang/ALGOL-68/Sailors-coconuts-and-a-monkey-problem @@ -0,0 +1 @@ +../../Task/Sailors-coconuts-and-a-monkey-problem/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Sleeping-Beauty-problem b/Lang/ALGOL-68/Sleeping-Beauty-problem new file mode 120000 index 0000000000..b5873d4f8d --- /dev/null +++ b/Lang/ALGOL-68/Sleeping-Beauty-problem @@ -0,0 +1 @@ +../../Task/Sleeping-Beauty-problem/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Solve-a-Hidato-puzzle b/Lang/ALGOL-68/Solve-a-Hidato-puzzle new file mode 120000 index 0000000000..228ccf6bb3 --- /dev/null +++ b/Lang/ALGOL-68/Solve-a-Hidato-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hidato-puzzle/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Solve-a-Numbrix-puzzle b/Lang/ALGOL-68/Solve-a-Numbrix-puzzle new file mode 120000 index 0000000000..14e9e80e97 --- /dev/null +++ b/Lang/ALGOL-68/Solve-a-Numbrix-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Numbrix-puzzle/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Solve-the-no-connection-puzzle b/Lang/ALGOL-68/Solve-the-no-connection-puzzle new file mode 120000 index 0000000000..0ffda5f1f9 --- /dev/null +++ b/Lang/ALGOL-68/Solve-the-no-connection-puzzle @@ -0,0 +1 @@ +../../Task/Solve-the-no-connection-puzzle/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Sort-disjoint-sublist b/Lang/ALGOL-68/Sort-disjoint-sublist new file mode 120000 index 0000000000..be15a7cde3 --- /dev/null +++ b/Lang/ALGOL-68/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Subtractive-generator b/Lang/ALGOL-68/Subtractive-generator new file mode 120000 index 0000000000..f90071e31a --- /dev/null +++ b/Lang/ALGOL-68/Subtractive-generator @@ -0,0 +1 @@ +../../Task/Subtractive-generator/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Super-d-numbers b/Lang/ALGOL-68/Super-d-numbers new file mode 120000 index 0000000000..f050b2afa7 --- /dev/null +++ b/Lang/ALGOL-68/Super-d-numbers @@ -0,0 +1 @@ +../../Task/Super-d-numbers/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Take-notes-on-the-command-line b/Lang/ALGOL-68/Take-notes-on-the-command-line new file mode 120000 index 0000000000..f0f896e58b --- /dev/null +++ b/Lang/ALGOL-68/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Text-processing-2 b/Lang/ALGOL-68/Text-processing-2 new file mode 120000 index 0000000000..124fe3bf6c --- /dev/null +++ b/Lang/ALGOL-68/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Verhoeff-algorithm b/Lang/ALGOL-68/Verhoeff-algorithm new file mode 120000 index 0000000000..7cabb86204 --- /dev/null +++ b/Lang/ALGOL-68/Verhoeff-algorithm @@ -0,0 +1 @@ +../../Task/Verhoeff-algorithm/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Vogels-approximation-method b/Lang/ALGOL-68/Vogels-approximation-method new file mode 120000 index 0000000000..9c09f3c2a5 --- /dev/null +++ b/Lang/ALGOL-68/Vogels-approximation-method @@ -0,0 +1 @@ +../../Task/Vogels-approximation-method/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Wasteful-equidigital-and-frugal-numbers b/Lang/ALGOL-68/Wasteful-equidigital-and-frugal-numbers new file mode 120000 index 0000000000..6de9ddaea1 --- /dev/null +++ b/Lang/ALGOL-68/Wasteful-equidigital-and-frugal-numbers @@ -0,0 +1 @@ +../../Task/Wasteful-equidigital-and-frugal-numbers/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Word-wheel b/Lang/ALGOL-68/Word-wheel new file mode 120000 index 0000000000..ab6aaa99f7 --- /dev/null +++ b/Lang/ALGOL-68/Word-wheel @@ -0,0 +1 @@ +../../Task/Word-wheel/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-M/Additive-primes b/Lang/ALGOL-M/Additive-primes new file mode 120000 index 0000000000..974f9484e7 --- /dev/null +++ b/Lang/ALGOL-M/Additive-primes @@ -0,0 +1 @@ +../../Task/Additive-primes/ALGOL-M \ No newline at end of file diff --git a/Lang/ALGOL-M/Case-sensitivity-of-identifiers b/Lang/ALGOL-M/Case-sensitivity-of-identifiers new file mode 120000 index 0000000000..3e61bd6e7f --- /dev/null +++ b/Lang/ALGOL-M/Case-sensitivity-of-identifiers @@ -0,0 +1 @@ +../../Task/Case-sensitivity-of-identifiers/ALGOL-M \ No newline at end of file diff --git a/Lang/ALGOL-M/Integer-comparison b/Lang/ALGOL-M/Integer-comparison new file mode 120000 index 0000000000..1066ff383c --- /dev/null +++ b/Lang/ALGOL-M/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/ALGOL-M \ No newline at end of file diff --git a/Lang/ALGOL-M/Integer-overflow b/Lang/ALGOL-M/Integer-overflow new file mode 120000 index 0000000000..a7f3c63fee --- /dev/null +++ b/Lang/ALGOL-M/Integer-overflow @@ -0,0 +1 @@ +../../Task/Integer-overflow/ALGOL-M \ No newline at end of file diff --git a/Lang/ALGOL-M/Semiprime b/Lang/ALGOL-M/Semiprime new file mode 120000 index 0000000000..9bc2a5e1b8 --- /dev/null +++ b/Lang/ALGOL-M/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/ALGOL-M \ No newline at end of file diff --git a/Lang/ALGOL-W/00-LANG.txt b/Lang/ALGOL-W/00-LANG.txt index eed21ba5cf..f0f11b51d0 100644 --- a/Lang/ALGOL-W/00-LANG.txt +++ b/Lang/ALGOL-W/00-LANG.txt @@ -7,27 +7,15 @@ |checking=both |tags=algolw |LCT=yes}} -Algol W is a successor to [[wp:Algol 60|Algol 60]] closely based on A +Algol W was designed as a successor to [[wp:Algol 60|Algol 60]], closely based on A Contribution to the Development of ALGOL by [[wp:Niklaus Wirth|Niklaus Wirth]] and [[wp:C.A.R. Hoare|C. A. R. Hoare]]. It includes dynamically allocated records, string handling, complex numbers and a standard I/O -system. A copy of the Algol W Language Description can be found on Karl -Kleine's [http://www.fh-jena.de/~kleine/history/history.html Historic Documents in Computer Science] +system. A description of the Algol W Language as at 1972 can be found at [https://bitsavers.org/pdf/stanford/cs_techReports/STAN-CS-71-230_Algol_W_Reference_Manual_Feb72.pdf Algol W Reference Manual 1972 on bitsavers.org] page. [http://everything2.com/title/Algol%2520W Dabcanboulet's Algol W @ Everything2] page contains an excellent history and tutorial. -[http://tiddly-pom.com/~glyn/ Awe] is a new compiler for the Algol W -language. It is a complete implementation of the language described in -the [https://tiddly-pom.com/~glyn/algolw.pdf Algol W Language Description, June 1972]. Awe should be able to -compile code intended for the [[wp:OS/360|OS/360]] Algol W compilers -with little or no modification. See the Awe manual for more details. - -Awe correctly compiles Tony Marsland's computer [[wp:chess|chess]] player -[http://webdocs.cs.ualberta.ca/~tony/Public/Awit-Wita-ComputerChess/ Awit] -and Hendrik Boom's [http://mtn-host.prjek.net/projects/a68h/ A68H] -[[Algol 68]] compiler. - ==To do== [[Tasks not implemented in ALGOL W]] diff --git a/Lang/ALGOL-W/Arithmetic-Integer b/Lang/ALGOL-W/Arithmetic-Integer deleted file mode 120000 index de259d015a..0000000000 --- a/Lang/ALGOL-W/Arithmetic-Integer +++ /dev/null @@ -1 +0,0 @@ -../../Task/Arithmetic-Integer/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Arithmetic-geometric-mean-Calculate-Pi b/Lang/ALGOL-W/Arithmetic-geometric-mean-Calculate-Pi new file mode 120000 index 0000000000..0fd6c8a97f --- /dev/null +++ b/Lang/ALGOL-W/Arithmetic-geometric-mean-Calculate-Pi @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean-Calculate-Pi/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Calculating-the-value-of-e b/Lang/ALGOL-W/Calculating-the-value-of-e new file mode 120000 index 0000000000..0bccb15458 --- /dev/null +++ b/Lang/ALGOL-W/Calculating-the-value-of-e @@ -0,0 +1 @@ +../../Task/Calculating-the-value-of-e/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Copy-a-string b/Lang/ALGOL-W/Copy-a-string deleted file mode 120000 index 4a449ab936..0000000000 --- a/Lang/ALGOL-W/Copy-a-string +++ /dev/null @@ -1 +0,0 @@ -../../Task/Copy-a-string/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Equal-prime-and-composite-sums b/Lang/ALGOL-W/Equal-prime-and-composite-sums new file mode 120000 index 0000000000..54c76175f4 --- /dev/null +++ b/Lang/ALGOL-W/Equal-prime-and-composite-sums @@ -0,0 +1 @@ +../../Task/Equal-prime-and-composite-sums/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Eulers-constant-0.5772... b/Lang/ALGOL-W/Eulers-constant-0.5772... new file mode 120000 index 0000000000..809de9e1fd --- /dev/null +++ b/Lang/ALGOL-W/Eulers-constant-0.5772... @@ -0,0 +1 @@ +../../Task/Eulers-constant-0.5772.../ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Eulers-identity b/Lang/ALGOL-W/Eulers-identity new file mode 120000 index 0000000000..cda4a96c63 --- /dev/null +++ b/Lang/ALGOL-W/Eulers-identity @@ -0,0 +1 @@ +../../Task/Eulers-identity/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Factorial b/Lang/ALGOL-W/Factorial deleted file mode 120000 index 01c77fb141..0000000000 --- a/Lang/ALGOL-W/Factorial +++ /dev/null @@ -1 +0,0 @@ -../../Task/Factorial/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Factorial-primes b/Lang/ALGOL-W/Factorial-primes new file mode 120000 index 0000000000..d855b375f0 --- /dev/null +++ b/Lang/ALGOL-W/Factorial-primes @@ -0,0 +1 @@ +../../Task/Factorial-primes/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Find-the-intersection-of-two-lines b/Lang/ALGOL-W/Find-the-intersection-of-two-lines new file mode 120000 index 0000000000..0514984ef6 --- /dev/null +++ b/Lang/ALGOL-W/Find-the-intersection-of-two-lines @@ -0,0 +1 @@ +../../Task/Find-the-intersection-of-two-lines/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Integer-comparison b/Lang/ALGOL-W/Integer-comparison deleted file mode 120000 index b056aab0f7..0000000000 --- a/Lang/ALGOL-W/Integer-comparison +++ /dev/null @@ -1 +0,0 @@ -../../Task/Integer-comparison/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Jordan-P-lya-numbers b/Lang/ALGOL-W/Jordan-P-lya-numbers new file mode 120000 index 0000000000..6e24b686d2 --- /dev/null +++ b/Lang/ALGOL-W/Jordan-P-lya-numbers @@ -0,0 +1 @@ +../../Task/Jordan-P-lya-numbers/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Knapsack-problem-Continuous b/Lang/ALGOL-W/Knapsack-problem-Continuous new file mode 120000 index 0000000000..fba28c1695 --- /dev/null +++ b/Lang/ALGOL-W/Knapsack-problem-Continuous @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Continuous/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/McNuggets-problem b/Lang/ALGOL-W/McNuggets-problem new file mode 120000 index 0000000000..74213b63b7 --- /dev/null +++ b/Lang/ALGOL-W/McNuggets-problem @@ -0,0 +1 @@ +../../Task/McNuggets-problem/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Mian-Chowla-sequence b/Lang/ALGOL-W/Mian-Chowla-sequence new file mode 120000 index 0000000000..ef2068107d --- /dev/null +++ b/Lang/ALGOL-W/Mian-Chowla-sequence @@ -0,0 +1 @@ +../../Task/Mian-Chowla-sequence/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Numbers-with-equal-rises-and-falls b/Lang/ALGOL-W/Numbers-with-equal-rises-and-falls new file mode 120000 index 0000000000..da06043b47 --- /dev/null +++ b/Lang/ALGOL-W/Numbers-with-equal-rises-and-falls @@ -0,0 +1 @@ +../../Task/Numbers-with-equal-rises-and-falls/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Pseudo-random-numbers-Middle-square-method b/Lang/ALGOL-W/Pseudo-random-numbers-Middle-square-method new file mode 120000 index 0000000000..e6f0e36a5b --- /dev/null +++ b/Lang/ALGOL-W/Pseudo-random-numbers-Middle-square-method @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-Middle-square-method/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Quaternion-type b/Lang/ALGOL-W/Quaternion-type deleted file mode 120000 index 9f1593930d..0000000000 --- a/Lang/ALGOL-W/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Sleeping-Beauty-problem b/Lang/ALGOL-W/Sleeping-Beauty-problem new file mode 120000 index 0000000000..2a0e8b6707 --- /dev/null +++ b/Lang/ALGOL-W/Sleeping-Beauty-problem @@ -0,0 +1 @@ +../../Task/Sleeping-Beauty-problem/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Square-but-not-cube b/Lang/ALGOL-W/Square-but-not-cube new file mode 120000 index 0000000000..4f2dc4fb68 --- /dev/null +++ b/Lang/ALGOL-W/Square-but-not-cube @@ -0,0 +1 @@ +../../Task/Square-but-not-cube/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Square-free-integers b/Lang/ALGOL-W/Square-free-integers new file mode 120000 index 0000000000..c98b8e474a --- /dev/null +++ b/Lang/ALGOL-W/Square-free-integers @@ -0,0 +1 @@ +../../Task/Square-free-integers/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Tau-number b/Lang/ALGOL-W/Tau-number new file mode 120000 index 0000000000..8bde57a739 --- /dev/null +++ b/Lang/ALGOL-W/Tau-number @@ -0,0 +1 @@ +../../Task/Tau-number/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/The-sieve-of-Sundaram b/Lang/ALGOL-W/The-sieve-of-Sundaram new file mode 120000 index 0000000000..f0d3b0894c --- /dev/null +++ b/Lang/ALGOL-W/The-sieve-of-Sundaram @@ -0,0 +1 @@ +../../Task/The-sieve-of-Sundaram/ALGOL-W \ No newline at end of file diff --git a/Lang/ANSI-BASIC/100-doors b/Lang/ANSI-BASIC/100-doors new file mode 120000 index 0000000000..bd1164e9d1 --- /dev/null +++ b/Lang/ANSI-BASIC/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/AKS-test-for-primes b/Lang/ANSI-BASIC/AKS-test-for-primes new file mode 120000 index 0000000000..4668d2783c --- /dev/null +++ b/Lang/ANSI-BASIC/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Abundant-deficient-and-perfect-number-classifications b/Lang/ANSI-BASIC/Abundant-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..c6e6a91dca --- /dev/null +++ b/Lang/ANSI-BASIC/Abundant-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant-deficient-and-perfect-number-classifications/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Abundant-odd-numbers b/Lang/ANSI-BASIC/Abundant-odd-numbers new file mode 120000 index 0000000000..655c1f21d6 --- /dev/null +++ b/Lang/ANSI-BASIC/Abundant-odd-numbers @@ -0,0 +1 @@ +../../Task/Abundant-odd-numbers/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Angle-difference-between-two-bearings b/Lang/ANSI-BASIC/Angle-difference-between-two-bearings new file mode 120000 index 0000000000..de48f860b4 --- /dev/null +++ b/Lang/ANSI-BASIC/Angle-difference-between-two-bearings @@ -0,0 +1 @@ +../../Task/Angle-difference-between-two-bearings/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Arithmetic-numbers b/Lang/ANSI-BASIC/Arithmetic-numbers new file mode 120000 index 0000000000..db92ceb262 --- /dev/null +++ b/Lang/ANSI-BASIC/Arithmetic-numbers @@ -0,0 +1 @@ +../../Task/Arithmetic-numbers/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Babbage-problem b/Lang/ANSI-BASIC/Babbage-problem new file mode 120000 index 0000000000..8ef3bfe458 --- /dev/null +++ b/Lang/ANSI-BASIC/Babbage-problem @@ -0,0 +1 @@ +../../Task/Babbage-problem/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/CUSIP b/Lang/ANSI-BASIC/CUSIP new file mode 120000 index 0000000000..fc24eb8330 --- /dev/null +++ b/Lang/ANSI-BASIC/CUSIP @@ -0,0 +1 @@ +../../Task/CUSIP/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Catalan-numbers b/Lang/ANSI-BASIC/Catalan-numbers new file mode 120000 index 0000000000..9c5cfe1b71 --- /dev/null +++ b/Lang/ANSI-BASIC/Catalan-numbers @@ -0,0 +1 @@ +../../Task/Catalan-numbers/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Cumulative-standard-deviation b/Lang/ANSI-BASIC/Cumulative-standard-deviation new file mode 120000 index 0000000000..1d8fe68648 --- /dev/null +++ b/Lang/ANSI-BASIC/Cumulative-standard-deviation @@ -0,0 +1 @@ +../../Task/Cumulative-standard-deviation/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Damm-algorithm b/Lang/ANSI-BASIC/Damm-algorithm new file mode 120000 index 0000000000..e4b39fdaa1 --- /dev/null +++ b/Lang/ANSI-BASIC/Damm-algorithm @@ -0,0 +1 @@ +../../Task/Damm-algorithm/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Day-of-the-week b/Lang/ANSI-BASIC/Day-of-the-week new file mode 120000 index 0000000000..8ccffe667c --- /dev/null +++ b/Lang/ANSI-BASIC/Day-of-the-week @@ -0,0 +1 @@ +../../Task/Day-of-the-week/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Department-numbers b/Lang/ANSI-BASIC/Department-numbers new file mode 120000 index 0000000000..44a9633eba --- /dev/null +++ b/Lang/ANSI-BASIC/Department-numbers @@ -0,0 +1 @@ +../../Task/Department-numbers/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Determine-if-a-string-is-collapsible b/Lang/ANSI-BASIC/Determine-if-a-string-is-collapsible new file mode 120000 index 0000000000..47a87c627a --- /dev/null +++ b/Lang/ANSI-BASIC/Determine-if-a-string-is-collapsible @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-collapsible/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Dot-product b/Lang/ANSI-BASIC/Dot-product new file mode 120000 index 0000000000..22c1437095 --- /dev/null +++ b/Lang/ANSI-BASIC/Dot-product @@ -0,0 +1 @@ +../../Task/Dot-product/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Dutch-national-flag-problem b/Lang/ANSI-BASIC/Dutch-national-flag-problem new file mode 120000 index 0000000000..96adf147fe --- /dev/null +++ b/Lang/ANSI-BASIC/Dutch-national-flag-problem @@ -0,0 +1 @@ +../../Task/Dutch-national-flag-problem/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Equilibrium-index b/Lang/ANSI-BASIC/Equilibrium-index new file mode 120000 index 0000000000..4273670f14 --- /dev/null +++ b/Lang/ANSI-BASIC/Equilibrium-index @@ -0,0 +1 @@ +../../Task/Equilibrium-index/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Ethiopian-multiplication b/Lang/ANSI-BASIC/Ethiopian-multiplication new file mode 120000 index 0000000000..0687e83f8a --- /dev/null +++ b/Lang/ANSI-BASIC/Ethiopian-multiplication @@ -0,0 +1 @@ +../../Task/Ethiopian-multiplication/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Factors-of-an-integer b/Lang/ANSI-BASIC/Factors-of-an-integer new file mode 120000 index 0000000000..187d81b94b --- /dev/null +++ b/Lang/ANSI-BASIC/Factors-of-an-integer @@ -0,0 +1 @@ +../../Task/Factors-of-an-integer/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Fibonacci-sequence b/Lang/ANSI-BASIC/Fibonacci-sequence new file mode 120000 index 0000000000..7c7a1193ff --- /dev/null +++ b/Lang/ANSI-BASIC/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Formatted-numeric-output b/Lang/ANSI-BASIC/Formatted-numeric-output new file mode 120000 index 0000000000..e876b7e939 --- /dev/null +++ b/Lang/ANSI-BASIC/Formatted-numeric-output @@ -0,0 +1 @@ +../../Task/Formatted-numeric-output/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Function-definition b/Lang/ANSI-BASIC/Function-definition new file mode 120000 index 0000000000..c45352eba7 --- /dev/null +++ b/Lang/ANSI-BASIC/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Generate-lower-case-ASCII-alphabet b/Lang/ANSI-BASIC/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..26bc617302 --- /dev/null +++ b/Lang/ANSI-BASIC/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Horners-rule-for-polynomial-evaluation b/Lang/ANSI-BASIC/Horners-rule-for-polynomial-evaluation new file mode 120000 index 0000000000..4c6423e8e1 --- /dev/null +++ b/Lang/ANSI-BASIC/Horners-rule-for-polynomial-evaluation @@ -0,0 +1 @@ +../../Task/Horners-rule-for-polynomial-evaluation/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Langtons-ant b/Lang/ANSI-BASIC/Langtons-ant new file mode 120000 index 0000000000..c0944407d4 --- /dev/null +++ b/Lang/ANSI-BASIC/Langtons-ant @@ -0,0 +1 @@ +../../Task/Langtons-ant/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Leap-year b/Lang/ANSI-BASIC/Leap-year new file mode 120000 index 0000000000..d8f2cec2bd --- /dev/null +++ b/Lang/ANSI-BASIC/Leap-year @@ -0,0 +1 @@ +../../Task/Leap-year/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Leonardo-numbers b/Lang/ANSI-BASIC/Leonardo-numbers new file mode 120000 index 0000000000..eeb51e71aa --- /dev/null +++ b/Lang/ANSI-BASIC/Leonardo-numbers @@ -0,0 +1 @@ +../../Task/Leonardo-numbers/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Levenshtein-distance b/Lang/ANSI-BASIC/Levenshtein-distance new file mode 120000 index 0000000000..92b553d536 --- /dev/null +++ b/Lang/ANSI-BASIC/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Long-year b/Lang/ANSI-BASIC/Long-year new file mode 120000 index 0000000000..ca5898e1c7 --- /dev/null +++ b/Lang/ANSI-BASIC/Long-year @@ -0,0 +1 @@ +../../Task/Long-year/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Loops-Do-while b/Lang/ANSI-BASIC/Loops-Do-while new file mode 120000 index 0000000000..998c0b9f8a --- /dev/null +++ b/Lang/ANSI-BASIC/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Luhn-test-of-credit-card-numbers b/Lang/ANSI-BASIC/Luhn-test-of-credit-card-numbers new file mode 120000 index 0000000000..5e8c5fe6dd --- /dev/null +++ b/Lang/ANSI-BASIC/Luhn-test-of-credit-card-numbers @@ -0,0 +1 @@ +../../Task/Luhn-test-of-credit-card-numbers/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/M-bius-function b/Lang/ANSI-BASIC/M-bius-function new file mode 120000 index 0000000000..f786d2b99e --- /dev/null +++ b/Lang/ANSI-BASIC/M-bius-function @@ -0,0 +1 @@ +../../Task/M-bius-function/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Magic-constant b/Lang/ANSI-BASIC/Magic-constant new file mode 120000 index 0000000000..7d2184182c --- /dev/null +++ b/Lang/ANSI-BASIC/Magic-constant @@ -0,0 +1 @@ +../../Task/Magic-constant/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Map-range b/Lang/ANSI-BASIC/Map-range new file mode 120000 index 0000000000..829dfc3a26 --- /dev/null +++ b/Lang/ANSI-BASIC/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Mayan-numerals b/Lang/ANSI-BASIC/Mayan-numerals new file mode 120000 index 0000000000..daef520f79 --- /dev/null +++ b/Lang/ANSI-BASIC/Mayan-numerals @@ -0,0 +1 @@ +../../Task/Mayan-numerals/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Monty-Hall-problem b/Lang/ANSI-BASIC/Monty-Hall-problem new file mode 120000 index 0000000000..8f9a29cbcc --- /dev/null +++ b/Lang/ANSI-BASIC/Monty-Hall-problem @@ -0,0 +1 @@ +../../Task/Monty-Hall-problem/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Nth-root b/Lang/ANSI-BASIC/Nth-root new file mode 120000 index 0000000000..089f4d872e --- /dev/null +++ b/Lang/ANSI-BASIC/Nth-root @@ -0,0 +1 @@ +../../Task/Nth-root/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Old-Russian-measure-of-length b/Lang/ANSI-BASIC/Old-Russian-measure-of-length new file mode 120000 index 0000000000..81f64cd54c --- /dev/null +++ b/Lang/ANSI-BASIC/Old-Russian-measure-of-length @@ -0,0 +1 @@ +../../Task/Old-Russian-measure-of-length/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Periodic-table b/Lang/ANSI-BASIC/Periodic-table new file mode 120000 index 0000000000..b9e95e6595 --- /dev/null +++ b/Lang/ANSI-BASIC/Periodic-table @@ -0,0 +1 @@ +../../Task/Periodic-table/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Random-numbers b/Lang/ANSI-BASIC/Random-numbers new file mode 120000 index 0000000000..1de5221db0 --- /dev/null +++ b/Lang/ANSI-BASIC/Random-numbers @@ -0,0 +1 @@ +../../Task/Random-numbers/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Real-constants-and-functions b/Lang/ANSI-BASIC/Real-constants-and-functions new file mode 120000 index 0000000000..02cced5726 --- /dev/null +++ b/Lang/ANSI-BASIC/Real-constants-and-functions @@ -0,0 +1 @@ +../../Task/Real-constants-and-functions/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Repeat-a-string b/Lang/ANSI-BASIC/Repeat-a-string new file mode 120000 index 0000000000..018a40d1b5 --- /dev/null +++ b/Lang/ANSI-BASIC/Repeat-a-string @@ -0,0 +1 @@ +../../Task/Repeat-a-string/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Rot-13 b/Lang/ANSI-BASIC/Rot-13 new file mode 120000 index 0000000000..6dadbcd391 --- /dev/null +++ b/Lang/ANSI-BASIC/Rot-13 @@ -0,0 +1 @@ +../../Task/Rot-13/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Semiprime b/Lang/ANSI-BASIC/Semiprime new file mode 120000 index 0000000000..e0427579b2 --- /dev/null +++ b/Lang/ANSI-BASIC/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Shoelace-formula-for-polygonal-area b/Lang/ANSI-BASIC/Shoelace-formula-for-polygonal-area new file mode 120000 index 0000000000..63de3b564e --- /dev/null +++ b/Lang/ANSI-BASIC/Shoelace-formula-for-polygonal-area @@ -0,0 +1 @@ +../../Task/Shoelace-formula-for-polygonal-area/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Sorting-algorithms-Quicksort b/Lang/ANSI-BASIC/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..acf4c89afe --- /dev/null +++ b/Lang/ANSI-BASIC/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Square-free-integers b/Lang/ANSI-BASIC/Square-free-integers new file mode 120000 index 0000000000..90f8c4cba3 --- /dev/null +++ b/Lang/ANSI-BASIC/Square-free-integers @@ -0,0 +1 @@ +../../Task/Square-free-integers/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Statistics-Basic b/Lang/ANSI-BASIC/Statistics-Basic new file mode 120000 index 0000000000..11c8fbb1d2 --- /dev/null +++ b/Lang/ANSI-BASIC/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Statistics-Normal-distribution b/Lang/ANSI-BASIC/Statistics-Normal-distribution new file mode 120000 index 0000000000..674b0ba86f --- /dev/null +++ b/Lang/ANSI-BASIC/Statistics-Normal-distribution @@ -0,0 +1 @@ +../../Task/Statistics-Normal-distribution/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Tau-number b/Lang/ANSI-BASIC/Tau-number new file mode 120000 index 0000000000..bfebf263eb --- /dev/null +++ b/Lang/ANSI-BASIC/Tau-number @@ -0,0 +1 @@ +../../Task/Tau-number/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Temperature-conversion b/Lang/ANSI-BASIC/Temperature-conversion new file mode 120000 index 0000000000..af167d778a --- /dev/null +++ b/Lang/ANSI-BASIC/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/ANSI-BASIC \ No newline at end of file diff --git a/Lang/APL/ADFGVX-cipher b/Lang/APL/ADFGVX-cipher new file mode 120000 index 0000000000..ab764adced --- /dev/null +++ b/Lang/APL/ADFGVX-cipher @@ -0,0 +1 @@ +../../Task/ADFGVX-cipher/APL \ No newline at end of file diff --git a/Lang/APL/Abelian-sandpile-model b/Lang/APL/Abelian-sandpile-model new file mode 120000 index 0000000000..346a055fbc --- /dev/null +++ b/Lang/APL/Abelian-sandpile-model @@ -0,0 +1 @@ +../../Task/Abelian-sandpile-model/APL \ No newline at end of file diff --git a/Lang/APL/Arithmetic-derivative b/Lang/APL/Arithmetic-derivative new file mode 120000 index 0000000000..c5dd2fd89b --- /dev/null +++ b/Lang/APL/Arithmetic-derivative @@ -0,0 +1 @@ +../../Task/Arithmetic-derivative/APL \ No newline at end of file diff --git a/Lang/APL/Bioinformatics-base-count b/Lang/APL/Bioinformatics-base-count deleted file mode 120000 index f9e2de8949..0000000000 --- a/Lang/APL/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/APL \ No newline at end of file diff --git a/Lang/APL/Combinations b/Lang/APL/Combinations new file mode 120000 index 0000000000..b1574b8996 --- /dev/null +++ b/Lang/APL/Combinations @@ -0,0 +1 @@ +../../Task/Combinations/APL \ No newline at end of file diff --git a/Lang/APL/Display-a-linear-combination b/Lang/APL/Display-a-linear-combination new file mode 120000 index 0000000000..0e1867473a --- /dev/null +++ b/Lang/APL/Display-a-linear-combination @@ -0,0 +1 @@ +../../Task/Display-a-linear-combination/APL \ No newline at end of file diff --git a/Lang/APL/Loops-Infinite b/Lang/APL/Loops-Infinite new file mode 120000 index 0000000000..0f3ec957d2 --- /dev/null +++ b/Lang/APL/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/APL \ No newline at end of file diff --git a/Lang/APL/Monte-Carlo-methods b/Lang/APL/Monte-Carlo-methods new file mode 120000 index 0000000000..2cf831a11c --- /dev/null +++ b/Lang/APL/Monte-Carlo-methods @@ -0,0 +1 @@ +../../Task/Monte-Carlo-methods/APL \ No newline at end of file diff --git a/Lang/APL/Move-to-front-algorithm b/Lang/APL/Move-to-front-algorithm new file mode 120000 index 0000000000..bce8e1d67b --- /dev/null +++ b/Lang/APL/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/APL \ No newline at end of file diff --git a/Lang/APL/Pisano-period b/Lang/APL/Pisano-period new file mode 120000 index 0000000000..d81ff37307 --- /dev/null +++ b/Lang/APL/Pisano-period @@ -0,0 +1 @@ +../../Task/Pisano-period/APL \ No newline at end of file diff --git a/Lang/APL/Sort-a-list-of-object-identifiers b/Lang/APL/Sort-a-list-of-object-identifiers new file mode 120000 index 0000000000..400cb9fc60 --- /dev/null +++ b/Lang/APL/Sort-a-list-of-object-identifiers @@ -0,0 +1 @@ +../../Task/Sort-a-list-of-object-identifiers/APL \ No newline at end of file diff --git a/Lang/APL/Strip-comments-from-a-string b/Lang/APL/Strip-comments-from-a-string new file mode 120000 index 0000000000..ff78e120aa --- /dev/null +++ b/Lang/APL/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/APL \ No newline at end of file diff --git a/Lang/APL/Tic-tac-toe b/Lang/APL/Tic-tac-toe new file mode 120000 index 0000000000..58bb681d1c --- /dev/null +++ b/Lang/APL/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/APL \ No newline at end of file diff --git a/Lang/APL/Word-ladder b/Lang/APL/Word-ladder new file mode 120000 index 0000000000..6de9f38d51 --- /dev/null +++ b/Lang/APL/Word-ladder @@ -0,0 +1 @@ +../../Task/Word-ladder/APL \ No newline at end of file diff --git a/Lang/APL/Zeckendorf-number-representation b/Lang/APL/Zeckendorf-number-representation new file mode 120000 index 0000000000..e25cdfa21a --- /dev/null +++ b/Lang/APL/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/APL \ No newline at end of file diff --git a/Lang/ARM-Assembly/00-LANG.txt b/Lang/ARM-Assembly/00-LANG.txt index 4c41d124d7..273ed5e757 100644 --- a/Lang/ARM-Assembly/00-LANG.txt +++ b/Lang/ARM-Assembly/00-LANG.txt @@ -4,9 +4,9 @@ The ARM architecture is widely used on mobile phones and tablets. It falls under ===Instruction Size=== Every instruction that the ARM can execute is 32 bits. While other processors can have variable length instructions, the ARM does not. This means that the ARM doesn't need to parse where an instruction begins and ends, which makes it run very fast. What you might not expect is that this 32-bit instruction size includes both the actual instruction and the operands! Let's take a look at a [[Z80 Assembly]] instruction and compare it to an ARM instruction. -LD HL,&8040 ;bytecode is 0x21 0x40 0x80 +LD HL,&8040 ;bytecode is 0x21 0x40 0x80 -mov r4,#0x04000000 ;bytecode is 0xE3A04301 +mov r4,#0x04000000 ;bytecode is 0xE3A04301 So where did the 0x04000000 go? It's actually been compressed and fit within those 4 bytes you saw earlier. The ARM is very good at decompressing it, since it's been shrunk to an 8-bit number that can be rotated by an even number of bits. Unfortunately, this compression method is a double-edged sword - some 32-bit numbers can't be compressed this way, and thus many instructions can't work with them! @@ -18,72 +18,73 @@ Registers are much more flexible than immediate operands. Unlike immediate opera Getting an address in a register can be achieved with the MOV command, but there are limitations to that which will be explained in detail later. It's more reliable to use ADR which loads a nearby address into a register. This address has to be within a certain distance from the current program counter or it can't be loaded, so it's not a reliable way to load from the heap on many machines. It's mostly intended for loading from nearby read-only data, such as text strings or stored immediates (more on that later). When you type ADR R0,LABEL, the assembler will convert this to MOV R0,PC,#N, where N is the difference between the current program counter value and the label you specified. LDR can be used in a similar fashion to ADR but there is a subtle distinction between the two. Assume that the section below is assembled starting at memory address 0x04000000: -DataBlock: +DataBlock: .long 0xDEADBEEF ;VASM uses .long for 32-bit data and .word for 16-bit data. Your assembler will probably use .word for 32 bit and .long 0xFFFFFFFF ; .hword for 16-bit. MyCode: adr r0, DataBlock ;loads the value 0x04000000 into R0 - ldr r1, DataBlock ;loads the value 0xDEADBEEF into R1 - adr r2, DataBlock+4 ;loads the value 0x04000004 into R2 - -ldr r3, DataBlock+4 ;loads the value 0xFFFFFFFF into R3 +ldr r3, DataBlock+4 ;loads the value 0xFFFFFFFF into R3 + As you can see, ADR only gives you the memory location of a value in memory, where LDR loads ''from'' that memory location. - ===Data Addressing using LDR and STR=== Unlike its "cousin," the Motorola 68000 (which isn't really related but has a somewhat similar design), the ARM cannot directly write immediate values to memory. Those values must be contained in registers first. Unlike the 68000, the ARM has no "address registers." Rather, enclosing a register name in square brackets turns its value into a reference to a memory location. You'll need to load that memory location's numeric "value" as a constant first. Then you can read from it with LDR and write to it with STR. Not only can you read from a given address, you can also adjust how you read from it, and what you do before or after the read. -RAM_ADDRESS: +RAM_ADDRESS: .long 0 ;for simplicity we'll assume that this can actually be written to. Represents a placeholder for 32-bit data. ;Your assembler's syntax may be different. - .long 0 ;another placeholder for 32-bit data MyCode: adr R2,RAM_Address ;get the address of a nearby place to store values. MOV R0,#0x12345678 ;the value to store. -STR R0,[R2] ;store 0x12345678 into the first 32-bit slot. +STR R0,[R2] ;store 0x12345678 into the first 32-bit slot. + This is the basic way to store into memory, but there are other options, such as offsetting and post-increment. -RAM_ADDRESS: +RAM_ADDRESS: .long 0 .long 0 ;we'll store here this time. MyCode: adr R2,RAM_Address ;point R2 to the first storage slot MOV R0,#0x12345678 -STR R0,[R2,#4] ;store into the SECOND slot. R2 still points to the first slot - the #4 is added to R2 only temporarily. +STR R0,[R2,#4] ;store into the SECOND slot. R2 still points to the first slot - the #4 is added to R2 only temporarily. + There's a limit on the size of an immediate value used to offset when loading/storing. You can also use a register as an offset, whose value will be added to the address. -RAM_AREA: +RAM_AREA: .space 64,0 ;64 bytes of ram ;assume that R2 contains the address of "RAM_AREA" MyCode: MOV R0,#0x12345678 MOV R1,#20 -STR R0,[R2,R1] ;equivalent of "STR R0,[R2,#20]" +STR R0,[R2,R1] ;equivalent of "STR R0,[R2,#20]" + Now let's say you wanted to actually alter the pointer to R2, so that it remains pointing to where you offset it to after the store or load. That's an option you have - all you have to do is type "!" after the brackets. This is called "pre-increment" or "pre-indexing." -RAM_ADDRESS: +RAM_ADDRESS: .long 0 .long 0 ;we'll store here this time, and we want R2 to still be pointing here after we write to it. MyCode: adr R2,RAM_Address ;point R2 to the first storage slot MOV R0,#0x12345678 -STR R0,[R2,#4]! ;store into the SECOND slot. R2 also points to the second slot now, even after this instruction has concluded. +STR R0,[R2,#4]! ;store into the SECOND slot. R2 also points to the second slot now, even after this instruction has concluded. + Here, the offset is performed ''before'' the storage operation. What if you want to offset afterwards? That would be useful for reading in a data stream. Good news - you can do that simply by having the offset value or register '''outside''' the brackets. This is called "post-increment" or "post-indexing." Unlike pre-indexing, these changes to the pointer are not temporary. -LDR R0,[R1],#4 ;load the 32-bit value stored at memory location R1 into R0, THEN add 4 to R1. This offset remains even after this - ; instruction is finished. +LDR R0,[R1],#4 ;load the 32-bit value stored at memory location R1 into R0, THEN add 4 to R1. This offset remains even after this + ; instruction is finished. + ===Barrel Shifter=== The ARM can add a bit shift or rotate to one of its operands at no additional cost to execution time or bytecode. If the operand being shifted is a register, the value of that register is not actually changed. The shift or rotate only applies during that instruction. diff --git a/Lang/ARM-Assembly/Bifid-cipher b/Lang/ARM-Assembly/Bifid-cipher new file mode 120000 index 0000000000..456e328d85 --- /dev/null +++ b/Lang/ARM-Assembly/Bifid-cipher @@ -0,0 +1 @@ +../../Task/Bifid-cipher/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Binary-strings b/Lang/ARM-Assembly/Binary-strings new file mode 120000 index 0000000000..a7b6ed7647 --- /dev/null +++ b/Lang/ARM-Assembly/Binary-strings @@ -0,0 +1 @@ +../../Task/Binary-strings/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Bioinformatics-base-count b/Lang/ARM-Assembly/Bioinformatics-base-count deleted file mode 120000 index baff8c16a9..0000000000 --- a/Lang/ARM-Assembly/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Comma-quibbling b/Lang/ARM-Assembly/Comma-quibbling new file mode 120000 index 0000000000..3d3d7812f0 --- /dev/null +++ b/Lang/ARM-Assembly/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Create-an-HTML-table b/Lang/ARM-Assembly/Create-an-HTML-table new file mode 120000 index 0000000000..72c300d67a --- /dev/null +++ b/Lang/ARM-Assembly/Create-an-HTML-table @@ -0,0 +1 @@ +../../Task/Create-an-HTML-table/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Determine-sentence-type b/Lang/ARM-Assembly/Determine-sentence-type new file mode 120000 index 0000000000..5e77711ab2 --- /dev/null +++ b/Lang/ARM-Assembly/Determine-sentence-type @@ -0,0 +1 @@ +../../Task/Determine-sentence-type/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Environment-variables b/Lang/ARM-Assembly/Environment-variables new file mode 120000 index 0000000000..11f3baa342 --- /dev/null +++ b/Lang/ARM-Assembly/Environment-variables @@ -0,0 +1 @@ +../../Task/Environment-variables/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Fibonacci-n-step-number-sequences b/Lang/ARM-Assembly/Fibonacci-n-step-number-sequences new file mode 120000 index 0000000000..6e51a1f11e --- /dev/null +++ b/Lang/ARM-Assembly/Fibonacci-n-step-number-sequences @@ -0,0 +1 @@ +../../Task/Fibonacci-n-step-number-sequences/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Guess-the-number b/Lang/ARM-Assembly/Guess-the-number new file mode 120000 index 0000000000..f4c41a9cec --- /dev/null +++ b/Lang/ARM-Assembly/Guess-the-number @@ -0,0 +1 @@ +../../Task/Guess-the-number/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Halt-and-catch-fire b/Lang/ARM-Assembly/Halt-and-catch-fire new file mode 120000 index 0000000000..56faf31b66 --- /dev/null +++ b/Lang/ARM-Assembly/Halt-and-catch-fire @@ -0,0 +1 @@ +../../Task/Halt-and-catch-fire/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Hash-from-two-arrays b/Lang/ARM-Assembly/Hash-from-two-arrays new file mode 120000 index 0000000000..2a1c9147a6 --- /dev/null +++ b/Lang/ARM-Assembly/Hash-from-two-arrays @@ -0,0 +1 @@ +../../Task/Hash-from-two-arrays/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Keyboard-input-Obtain-a-Y-or-N-response b/Lang/ARM-Assembly/Keyboard-input-Obtain-a-Y-or-N-response new file mode 120000 index 0000000000..dc21bae989 --- /dev/null +++ b/Lang/ARM-Assembly/Keyboard-input-Obtain-a-Y-or-N-response @@ -0,0 +1 @@ +../../Task/Keyboard-input-Obtain-a-Y-or-N-response/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Leonardo-numbers b/Lang/ARM-Assembly/Leonardo-numbers new file mode 120000 index 0000000000..6639dbc2f4 --- /dev/null +++ b/Lang/ARM-Assembly/Leonardo-numbers @@ -0,0 +1 @@ +../../Task/Leonardo-numbers/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Machine-code b/Lang/ARM-Assembly/Machine-code new file mode 120000 index 0000000000..e48d9e81b2 --- /dev/null +++ b/Lang/ARM-Assembly/Machine-code @@ -0,0 +1 @@ +../../Task/Machine-code/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Menu b/Lang/ARM-Assembly/Menu new file mode 120000 index 0000000000..73a332d6f3 --- /dev/null +++ b/Lang/ARM-Assembly/Menu @@ -0,0 +1 @@ +../../Task/Menu/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Miller-Rabin-primality-test b/Lang/ARM-Assembly/Miller-Rabin-primality-test deleted file mode 120000 index 195623d60d..0000000000 --- a/Lang/ARM-Assembly/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Pancake-numbers b/Lang/ARM-Assembly/Pancake-numbers new file mode 120000 index 0000000000..7bcfc9ff51 --- /dev/null +++ b/Lang/ARM-Assembly/Pancake-numbers @@ -0,0 +1 @@ +../../Task/Pancake-numbers/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Phrase-reversals b/Lang/ARM-Assembly/Phrase-reversals new file mode 120000 index 0000000000..011ca34c42 --- /dev/null +++ b/Lang/ARM-Assembly/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Pi b/Lang/ARM-Assembly/Pi new file mode 120000 index 0000000000..97b44cbcc1 --- /dev/null +++ b/Lang/ARM-Assembly/Pi @@ -0,0 +1 @@ +../../Task/Pi/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Read-a-configuration-file b/Lang/ARM-Assembly/Read-a-configuration-file new file mode 120000 index 0000000000..76094b38c7 --- /dev/null +++ b/Lang/ARM-Assembly/Read-a-configuration-file @@ -0,0 +1 @@ +../../Task/Read-a-configuration-file/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Repeat-a-string b/Lang/ARM-Assembly/Repeat-a-string new file mode 120000 index 0000000000..69591f65b7 --- /dev/null +++ b/Lang/ARM-Assembly/Repeat-a-string @@ -0,0 +1 @@ +../../Task/Repeat-a-string/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Reverse-words-in-a-string b/Lang/ARM-Assembly/Reverse-words-in-a-string new file mode 120000 index 0000000000..10d177c9f9 --- /dev/null +++ b/Lang/ARM-Assembly/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Sorting-Algorithms-Circle-Sort b/Lang/ARM-Assembly/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 21eb603d7e..0000000000 --- a/Lang/ARM-Assembly/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/String-prepend b/Lang/ARM-Assembly/String-prepend new file mode 120000 index 0000000000..ab543c682f --- /dev/null +++ b/Lang/ARM-Assembly/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Strip-block-comments b/Lang/ARM-Assembly/Strip-block-comments new file mode 120000 index 0000000000..6a5702298a --- /dev/null +++ b/Lang/ARM-Assembly/Strip-block-comments @@ -0,0 +1 @@ +../../Task/Strip-block-comments/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Strip-comments-from-a-string b/Lang/ARM-Assembly/Strip-comments-from-a-string new file mode 120000 index 0000000000..b01acc2585 --- /dev/null +++ b/Lang/ARM-Assembly/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Strip-whitespace-from-a-string-Top-and-tail b/Lang/ARM-Assembly/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..ba0f5a585c --- /dev/null +++ b/Lang/ARM-Assembly/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Update-a-configuration-file b/Lang/ARM-Assembly/Update-a-configuration-file new file mode 120000 index 0000000000..9dd67115c0 --- /dev/null +++ b/Lang/ARM-Assembly/Update-a-configuration-file @@ -0,0 +1 @@ +../../Task/Update-a-configuration-file/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Vigen-re-cipher b/Lang/ARM-Assembly/Vigen-re-cipher new file mode 120000 index 0000000000..caeb031a4b --- /dev/null +++ b/Lang/ARM-Assembly/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Vigen-re-cipher-Cryptanalysis b/Lang/ARM-Assembly/Vigen-re-cipher-Cryptanalysis new file mode 120000 index 0000000000..ecfd7ae59c --- /dev/null +++ b/Lang/ARM-Assembly/Vigen-re-cipher-Cryptanalysis @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher-Cryptanalysis/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Visualize-a-tree b/Lang/ARM-Assembly/Visualize-a-tree new file mode 120000 index 0000000000..58626c23da --- /dev/null +++ b/Lang/ARM-Assembly/Visualize-a-tree @@ -0,0 +1 @@ +../../Task/Visualize-a-tree/ARM-Assembly \ No newline at end of file diff --git a/Lang/ASIC/Dragon-curve b/Lang/ASIC/Dragon-curve new file mode 120000 index 0000000000..7538c55bbc --- /dev/null +++ b/Lang/ASIC/Dragon-curve @@ -0,0 +1 @@ +../../Task/Dragon-curve/ASIC \ No newline at end of file diff --git a/Lang/ASIC/Generate-lower-case-ASCII-alphabet b/Lang/ASIC/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..af19876ed5 --- /dev/null +++ b/Lang/ASIC/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/ASIC \ No newline at end of file diff --git a/Lang/ASIC/Luhn-test-of-credit-card-numbers b/Lang/ASIC/Luhn-test-of-credit-card-numbers new file mode 120000 index 0000000000..30c2c72edb --- /dev/null +++ b/Lang/ASIC/Luhn-test-of-credit-card-numbers @@ -0,0 +1 @@ +../../Task/Luhn-test-of-credit-card-numbers/ASIC \ No newline at end of file diff --git a/Lang/ASIC/M-bius-function b/Lang/ASIC/M-bius-function new file mode 120000 index 0000000000..7848f34d54 --- /dev/null +++ b/Lang/ASIC/M-bius-function @@ -0,0 +1 @@ +../../Task/M-bius-function/ASIC \ No newline at end of file diff --git a/Lang/ASIC/Old-Russian-measure-of-length b/Lang/ASIC/Old-Russian-measure-of-length new file mode 120000 index 0000000000..e5e809a47d --- /dev/null +++ b/Lang/ASIC/Old-Russian-measure-of-length @@ -0,0 +1 @@ +../../Task/Old-Russian-measure-of-length/ASIC \ No newline at end of file diff --git a/Lang/ASIC/Temperature-conversion b/Lang/ASIC/Temperature-conversion new file mode 120000 index 0000000000..312278bfcd --- /dev/null +++ b/Lang/ASIC/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/ASIC \ No newline at end of file diff --git a/Lang/ATS/Quaternion-type b/Lang/ATS/Quaternion-type deleted file mode 120000 index 95bd8641ec..0000000000 --- a/Lang/ATS/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/ATS \ No newline at end of file diff --git a/Lang/AWK/00-LANG.txt b/Lang/AWK/00-LANG.txt index 8c5a32efdd..4d384747d7 100644 --- a/Lang/AWK/00-LANG.txt +++ b/Lang/AWK/00-LANG.txt @@ -8,13 +8,13 @@ Each AWK program consists of pattern-action statements. The program reads each input line, checks lines against patterns, and runs matching actions. For programs that never read input lines, the entire program can be one BEGIN { ... } block. -* ''List users who have /bin/ksh as a shell.''$ awk -F: '$7 == "/bin/ksh" { print $1 }' /etc/passwd +* ''List users who have /bin/ksh as a shell.''$ awk -F: '$7 == "/bin/ksh" { print $1 }' /etc/passwd AWK has only three types of variables: they are strings, floating-point numbers, and associative arrays (where every array index is a string). Conversion between strings and numbers is automatic. AWK also has regular expressions, which appear in many AWK programs. There are a few built-in functions, like cos() and sprintf(). -* ''Find average line length.''$ awk '{ cnt += length($0) } END { print cnt / NR }' /etc/rc +* ''Find average line length.''$ awk '{ cnt += length($0) } END { print cnt / NR }' /etc/rc The name "AWK" comes from the initials of Alfred Aho, Peter Weinberger and Brian Kernighan: they invented AWK during the 1970s. A few decades later, Kernighan continues to maintain the [[nawk|reference implementation]] of AWK. diff --git a/Lang/AWK/100-doors b/Lang/AWK/100-doors deleted file mode 120000 index 99c9a19f16..0000000000 --- a/Lang/AWK/100-doors +++ /dev/null @@ -1 +0,0 @@ -../../Task/100-doors/AWK \ No newline at end of file diff --git a/Lang/AWK/Arithmetic-derivative b/Lang/AWK/Arithmetic-derivative new file mode 120000 index 0000000000..5f269aa501 --- /dev/null +++ b/Lang/AWK/Arithmetic-derivative @@ -0,0 +1 @@ +../../Task/Arithmetic-derivative/AWK \ No newline at end of file diff --git a/Lang/AWK/Bell-numbers b/Lang/AWK/Bell-numbers new file mode 120000 index 0000000000..ba62e9e87d --- /dev/null +++ b/Lang/AWK/Bell-numbers @@ -0,0 +1 @@ +../../Task/Bell-numbers/AWK \ No newline at end of file diff --git a/Lang/AWK/Bioinformatics-base-count b/Lang/AWK/Bioinformatics-base-count deleted file mode 120000 index 0d26eb27e1..0000000000 --- a/Lang/AWK/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/AWK \ No newline at end of file diff --git a/Lang/AWK/Blum-integer b/Lang/AWK/Blum-integer new file mode 120000 index 0000000000..3a37b18d0c --- /dev/null +++ b/Lang/AWK/Blum-integer @@ -0,0 +1 @@ +../../Task/Blum-integer/AWK \ No newline at end of file diff --git a/Lang/AWK/Brilliant-numbers b/Lang/AWK/Brilliant-numbers new file mode 120000 index 0000000000..75aada11ac --- /dev/null +++ b/Lang/AWK/Brilliant-numbers @@ -0,0 +1 @@ +../../Task/Brilliant-numbers/AWK \ No newline at end of file diff --git a/Lang/AWK/Cuban-primes b/Lang/AWK/Cuban-primes new file mode 120000 index 0000000000..e24a72c78b --- /dev/null +++ b/Lang/AWK/Cuban-primes @@ -0,0 +1 @@ +../../Task/Cuban-primes/AWK \ No newline at end of file diff --git a/Lang/AWK/Documentation b/Lang/AWK/Documentation new file mode 120000 index 0000000000..203588c43d --- /dev/null +++ b/Lang/AWK/Documentation @@ -0,0 +1 @@ +../../Task/Documentation/AWK \ No newline at end of file diff --git a/Lang/AWK/Egyptian-division b/Lang/AWK/Egyptian-division new file mode 120000 index 0000000000..b3edb7cd3b --- /dev/null +++ b/Lang/AWK/Egyptian-division @@ -0,0 +1 @@ +../../Task/Egyptian-division/AWK \ No newline at end of file diff --git a/Lang/AWK/Equal-prime-and-composite-sums b/Lang/AWK/Equal-prime-and-composite-sums new file mode 120000 index 0000000000..ff748db68b --- /dev/null +++ b/Lang/AWK/Equal-prime-and-composite-sums @@ -0,0 +1 @@ +../../Task/Equal-prime-and-composite-sums/AWK \ No newline at end of file diff --git a/Lang/AWK/Eulers-constant-0.5772... b/Lang/AWK/Eulers-constant-0.5772... new file mode 120000 index 0000000000..f2365557d6 --- /dev/null +++ b/Lang/AWK/Eulers-constant-0.5772... @@ -0,0 +1 @@ +../../Task/Eulers-constant-0.5772.../AWK \ No newline at end of file diff --git a/Lang/AWK/Factorial-primes b/Lang/AWK/Factorial-primes new file mode 120000 index 0000000000..7344ad75fd --- /dev/null +++ b/Lang/AWK/Factorial-primes @@ -0,0 +1 @@ +../../Task/Factorial-primes/AWK \ No newline at end of file diff --git a/Lang/AWK/Interactive-programming-repl- b/Lang/AWK/Interactive-programming-repl- new file mode 120000 index 0000000000..958761b6b1 --- /dev/null +++ b/Lang/AWK/Interactive-programming-repl- @@ -0,0 +1 @@ +../../Task/Interactive-programming-repl-/AWK \ No newline at end of file diff --git a/Lang/AWK/Isqrt-integer-square-root-of-X b/Lang/AWK/Isqrt-integer-square-root-of-X new file mode 120000 index 0000000000..04e9a1d13c --- /dev/null +++ b/Lang/AWK/Isqrt-integer-square-root-of-X @@ -0,0 +1 @@ +../../Task/Isqrt-integer-square-root-of-X/AWK \ No newline at end of file diff --git a/Lang/AWK/MAC-vendor-lookup b/Lang/AWK/MAC-vendor-lookup new file mode 120000 index 0000000000..3bffc2dd1c --- /dev/null +++ b/Lang/AWK/MAC-vendor-lookup @@ -0,0 +1 @@ +../../Task/MAC-vendor-lookup/AWK \ No newline at end of file diff --git a/Lang/AWK/Own-digits-power-sum b/Lang/AWK/Own-digits-power-sum new file mode 120000 index 0000000000..f78f510ce9 --- /dev/null +++ b/Lang/AWK/Own-digits-power-sum @@ -0,0 +1 @@ +../../Task/Own-digits-power-sum/AWK \ No newline at end of file diff --git a/Lang/AWK/Padovan-n-step-number-sequences b/Lang/AWK/Padovan-n-step-number-sequences new file mode 120000 index 0000000000..6bc3dbde1f --- /dev/null +++ b/Lang/AWK/Padovan-n-step-number-sequences @@ -0,0 +1 @@ +../../Task/Padovan-n-step-number-sequences/AWK \ No newline at end of file diff --git a/Lang/AWK/Pierpont-primes b/Lang/AWK/Pierpont-primes new file mode 120000 index 0000000000..f41d86837f --- /dev/null +++ b/Lang/AWK/Pierpont-primes @@ -0,0 +1 @@ +../../Task/Pierpont-primes/AWK \ No newline at end of file diff --git a/Lang/AWK/Scope-modifiers b/Lang/AWK/Scope-modifiers new file mode 120000 index 0000000000..635bec03ae --- /dev/null +++ b/Lang/AWK/Scope-modifiers @@ -0,0 +1 @@ +../../Task/Scope-modifiers/AWK \ No newline at end of file diff --git a/Lang/AWK/Search-a-list-of-records b/Lang/AWK/Search-a-list-of-records new file mode 120000 index 0000000000..6172b78f81 --- /dev/null +++ b/Lang/AWK/Search-a-list-of-records @@ -0,0 +1 @@ +../../Task/Search-a-list-of-records/AWK \ No newline at end of file diff --git a/Lang/AWK/Selectively-replace-multiple-instances-of-a-character-within-a-string b/Lang/AWK/Selectively-replace-multiple-instances-of-a-character-within-a-string new file mode 120000 index 0000000000..248fe6e3f2 --- /dev/null +++ b/Lang/AWK/Selectively-replace-multiple-instances-of-a-character-within-a-string @@ -0,0 +1 @@ +../../Task/Selectively-replace-multiple-instances-of-a-character-within-a-string/AWK \ No newline at end of file diff --git a/Lang/AWK/Sequence-of-primorial-primes b/Lang/AWK/Sequence-of-primorial-primes new file mode 120000 index 0000000000..0448804b7b --- /dev/null +++ b/Lang/AWK/Sequence-of-primorial-primes @@ -0,0 +1 @@ +../../Task/Sequence-of-primorial-primes/AWK \ No newline at end of file diff --git a/Lang/AWK/Soloways-recurring-rainfall b/Lang/AWK/Soloways-recurring-rainfall new file mode 120000 index 0000000000..1f850c19b0 --- /dev/null +++ b/Lang/AWK/Soloways-recurring-rainfall @@ -0,0 +1 @@ +../../Task/Soloways-recurring-rainfall/AWK \ No newline at end of file diff --git a/Lang/AWK/Time-a-function b/Lang/AWK/Time-a-function new file mode 120000 index 0000000000..d78f55d9f9 --- /dev/null +++ b/Lang/AWK/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/AWK \ No newline at end of file diff --git a/Lang/AWK/Vampire-number b/Lang/AWK/Vampire-number new file mode 120000 index 0000000000..3b7709e53a --- /dev/null +++ b/Lang/AWK/Vampire-number @@ -0,0 +1 @@ +../../Task/Vampire-number/AWK \ No newline at end of file diff --git a/Lang/AWK/Wagstaff-primes b/Lang/AWK/Wagstaff-primes new file mode 120000 index 0000000000..955871e83e --- /dev/null +++ b/Lang/AWK/Wagstaff-primes @@ -0,0 +1 @@ +../../Task/Wagstaff-primes/AWK \ No newline at end of file diff --git a/Lang/AWK/Wilson-primes-of-order-n b/Lang/AWK/Wilson-primes-of-order-n new file mode 120000 index 0000000000..840b045a17 --- /dev/null +++ b/Lang/AWK/Wilson-primes-of-order-n @@ -0,0 +1 @@ +../../Task/Wilson-primes-of-order-n/AWK \ No newline at end of file diff --git a/Lang/Action-/00-LANG.txt b/Lang/Action-/00-LANG.txt index b37eb47c8f..3811c3c636 100644 --- a/Lang/Action-/00-LANG.txt +++ b/Lang/Action-/00-LANG.txt @@ -4,7 +4,7 @@ }} Action! is a language written by Clinton Parker and published by Optimized Sytems Software (OSS) for the Atari 8-bit line of home computers. It is related to ALGOL and optimized for single-pass compilation to 6502 code. - +A manual for the language is available at https://seriouscomputerist.atariverse.com/media/pdf/manual/OSS%20OS-A+%20-%20Manual%20(1983).pdf ==See Also== * [[wp:Action!_(programming_language)|Action! on Wikipedia]] * [[ALGOL 68]] diff --git a/Lang/Action-/Arithmetic-derivative b/Lang/Action-/Arithmetic-derivative new file mode 120000 index 0000000000..8206b6a192 --- /dev/null +++ b/Lang/Action-/Arithmetic-derivative @@ -0,0 +1 @@ +../../Task/Arithmetic-derivative/Action- \ No newline at end of file diff --git a/Lang/Action-/Bioinformatics-base-count b/Lang/Action-/Bioinformatics-base-count deleted file mode 120000 index 2a7e093367..0000000000 --- a/Lang/Action-/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Action- \ No newline at end of file diff --git a/Lang/Action-/Quaternion-type b/Lang/Action-/Quaternion-type deleted file mode 120000 index 0cfb07db30..0000000000 --- a/Lang/Action-/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Action- \ No newline at end of file diff --git a/Lang/Action-/Sorting-Algorithms-Circle-Sort b/Lang/Action-/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index a9db72f0ce..0000000000 --- a/Lang/Action-/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Action- \ No newline at end of file diff --git a/Lang/ActionScript/00-LANG.txt b/Lang/ActionScript/00-LANG.txt index 14a7dc41bf..4fe99ed760 100644 --- a/Lang/ActionScript/00-LANG.txt +++ b/Lang/ActionScript/00-LANG.txt @@ -4,7 +4,8 @@ |strength=strong |safety=safe |checking=static -|LCT=yes}} +|LCT=yes +|tags=actionscript, as}} {{Language programming paradigm|Distributed}} {{Language programming paradigm|Imperative}} diff --git a/Lang/Ada/00-LANG.txt b/Lang/Ada/00-LANG.txt index 85a16e96c0..e9eb8d687d 100644 --- a/Lang/Ada/00-LANG.txt +++ b/Lang/Ada/00-LANG.txt @@ -8,7 +8,7 @@ |strength=strong |safety=safe |LCT=yes -|bnf=http://www.adaic.org/standards/1zrm/html/RM-P.html}}'''Ada''' is a structured, statically typed [[imperative programming|imperative]] computer programming language. Ada was initially standardized by [[ANSI]] in 1983 and by [[ISO]] in 1987. This version of the language is commonly known as [[Ada 83]]. The next version was standardized by ISO in 1995 (ISO/IEC 8652:1995) and is commonly known as [[Ada 95]]. Following that ISO published ISO/IEC 8652:1995/Amd 1:2007 in 2007, which is commonly known as [[Ada 2005]]. Most recently ISO published [http://www.ada-auth.org/standards/12rm/html/RM-TTL.html ISO/IEC 8652:2012(E)], commonly known as [[Ada 2012]]. Formally only the most recent version of the language is known as '''Ada'''. +|bnf=http://www.ada-auth.org/standards/22rm/html/RM-P-1.html}}'''Ada''' is a structured, statically typed [[imperative programming|imperative]] computer programming language. Ada was initially standardized by [[ANSI]] in 1983 and by [[ISO]] in 1987. This version of the language is commonly known as [[Ada 83]]. The next version was standardized by ISO in 1995 (ISO/IEC 8652:1995) and is commonly known as [[Ada 95]]. Following that ISO published ISO/IEC 8652:1995/Amd 1:2007 in 2007, which is commonly known as [[Ada 2005]]. Afterwards they published ISO/IEC 8652:2012(E), also known as [[Ada 2012]]. Most recently ISO published [http://www.ada-auth.org/standards/22rm/html/RM-TTL.html ISO/IEC 8652:2023], commonly known as [[Ada 2022]]. Formally only the most recent version of the language is known as '''Ada'''. The language is named after [[wp:Ada_Lovelace|Augusta Ada King, Countess of Lovelace]] thought to be the first ever programmer. Initially it was designed for [http://www.defense.gov U.S. Department of Defense]. The language is used for large and mission-critical systems. See [[wp:Ada_(programming_language)|also]]. ==Grammar== @@ -17,4 +17,6 @@ The language is named after [[wp:Ada_Lovelace|Augusta Ada King, Countess of Love {{Language programming paradigm|Distributed}} {{Language programming paradigm|Generic}} {{Language programming paradigm|Imperative}} -{{Language programming paradigm|Object-oriented}} \ No newline at end of file +{{Language programming paradigm|Object-oriented}} +==Todo== +* [[Tasks not implemented in Ada]] \ No newline at end of file diff --git a/Lang/Ada/24-game-Solve b/Lang/Ada/24-game-Solve new file mode 120000 index 0000000000..245a9225c6 --- /dev/null +++ b/Lang/Ada/24-game-Solve @@ -0,0 +1 @@ +../../Task/24-game-Solve/Ada \ No newline at end of file diff --git a/Lang/Ada/Abelian-sandpile-model b/Lang/Ada/Abelian-sandpile-model new file mode 120000 index 0000000000..adfb5aa625 --- /dev/null +++ b/Lang/Ada/Abelian-sandpile-model @@ -0,0 +1 @@ +../../Task/Abelian-sandpile-model/Ada \ No newline at end of file diff --git a/Lang/Ada/Achilles-numbers b/Lang/Ada/Achilles-numbers new file mode 120000 index 0000000000..8a02102d36 --- /dev/null +++ b/Lang/Ada/Achilles-numbers @@ -0,0 +1 @@ +../../Task/Achilles-numbers/Ada \ No newline at end of file diff --git a/Lang/Ada/Almkvist-Giullera-formula-for-pi b/Lang/Ada/Almkvist-Giullera-formula-for-pi new file mode 120000 index 0000000000..66015473cd --- /dev/null +++ b/Lang/Ada/Almkvist-Giullera-formula-for-pi @@ -0,0 +1 @@ +../../Task/Almkvist-Giullera-formula-for-pi/Ada \ No newline at end of file diff --git a/Lang/Ada/Angles-geometric-normalization-and-conversion b/Lang/Ada/Angles-geometric-normalization-and-conversion new file mode 120000 index 0000000000..d4d2487c81 --- /dev/null +++ b/Lang/Ada/Angles-geometric-normalization-and-conversion @@ -0,0 +1 @@ +../../Task/Angles-geometric-normalization-and-conversion/Ada \ No newline at end of file diff --git a/Lang/Ada/Arithmetic-derivative b/Lang/Ada/Arithmetic-derivative new file mode 120000 index 0000000000..87dd4d6940 --- /dev/null +++ b/Lang/Ada/Arithmetic-derivative @@ -0,0 +1 @@ +../../Task/Arithmetic-derivative/Ada \ No newline at end of file diff --git a/Lang/Ada/Arithmetic-geometric-mean-Calculate-Pi b/Lang/Ada/Arithmetic-geometric-mean-Calculate-Pi new file mode 120000 index 0000000000..14bdbe4c3d --- /dev/null +++ b/Lang/Ada/Arithmetic-geometric-mean-Calculate-Pi @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean-Calculate-Pi/Ada \ No newline at end of file diff --git a/Lang/Ada/Ascending-primes b/Lang/Ada/Ascending-primes new file mode 120000 index 0000000000..cee2b86585 --- /dev/null +++ b/Lang/Ada/Ascending-primes @@ -0,0 +1 @@ +../../Task/Ascending-primes/Ada \ No newline at end of file diff --git a/Lang/Ada/Babylonian-spiral b/Lang/Ada/Babylonian-spiral new file mode 120000 index 0000000000..fd4ac4c6ad --- /dev/null +++ b/Lang/Ada/Babylonian-spiral @@ -0,0 +1 @@ +../../Task/Babylonian-spiral/Ada \ No newline at end of file diff --git a/Lang/Ada/Bioinformatics-base-count b/Lang/Ada/Bioinformatics-base-count deleted file mode 120000 index 59c9c9dde5..0000000000 --- a/Lang/Ada/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Ada \ No newline at end of file diff --git a/Lang/Ada/Biorhythms b/Lang/Ada/Biorhythms new file mode 120000 index 0000000000..0d82777906 --- /dev/null +++ b/Lang/Ada/Biorhythms @@ -0,0 +1 @@ +../../Task/Biorhythms/Ada \ No newline at end of file diff --git a/Lang/Ada/Blum-integer b/Lang/Ada/Blum-integer new file mode 120000 index 0000000000..48b2715109 --- /dev/null +++ b/Lang/Ada/Blum-integer @@ -0,0 +1 @@ +../../Task/Blum-integer/Ada \ No newline at end of file diff --git a/Lang/Ada/Boyer-Moore-string-search b/Lang/Ada/Boyer-Moore-string-search new file mode 120000 index 0000000000..114c2a5fea --- /dev/null +++ b/Lang/Ada/Boyer-Moore-string-search @@ -0,0 +1 @@ +../../Task/Boyer-Moore-string-search/Ada \ No newline at end of file diff --git a/Lang/Ada/Brace-expansion b/Lang/Ada/Brace-expansion new file mode 120000 index 0000000000..b881365fa7 --- /dev/null +++ b/Lang/Ada/Brace-expansion @@ -0,0 +1 @@ +../../Task/Brace-expansion/Ada \ No newline at end of file diff --git a/Lang/Ada/Brilliant-numbers b/Lang/Ada/Brilliant-numbers new file mode 120000 index 0000000000..80af4238ae --- /dev/null +++ b/Lang/Ada/Brilliant-numbers @@ -0,0 +1 @@ +../../Task/Brilliant-numbers/Ada \ No newline at end of file diff --git a/Lang/Ada/Calkin-Wilf-sequence b/Lang/Ada/Calkin-Wilf-sequence new file mode 120000 index 0000000000..9e4b8cd779 --- /dev/null +++ b/Lang/Ada/Calkin-Wilf-sequence @@ -0,0 +1 @@ +../../Task/Calkin-Wilf-sequence/Ada \ No newline at end of file diff --git a/Lang/Ada/Camel-case-and-snake-case b/Lang/Ada/Camel-case-and-snake-case new file mode 120000 index 0000000000..1d95b38233 --- /dev/null +++ b/Lang/Ada/Camel-case-and-snake-case @@ -0,0 +1 @@ +../../Task/Camel-case-and-snake-case/Ada \ No newline at end of file diff --git a/Lang/Ada/Canonicalize-CIDR b/Lang/Ada/Canonicalize-CIDR new file mode 120000 index 0000000000..c0c0b338b8 --- /dev/null +++ b/Lang/Ada/Canonicalize-CIDR @@ -0,0 +1 @@ +../../Task/Canonicalize-CIDR/Ada \ No newline at end of file diff --git a/Lang/Ada/Chaos-game b/Lang/Ada/Chaos-game new file mode 120000 index 0000000000..456fd72f97 --- /dev/null +++ b/Lang/Ada/Chaos-game @@ -0,0 +1 @@ +../../Task/Chaos-game/Ada \ No newline at end of file diff --git a/Lang/Ada/Cistercian-numerals b/Lang/Ada/Cistercian-numerals new file mode 120000 index 0000000000..a03109c188 --- /dev/null +++ b/Lang/Ada/Cistercian-numerals @@ -0,0 +1 @@ +../../Task/Cistercian-numerals/Ada \ No newline at end of file diff --git a/Lang/Ada/Color-wheel b/Lang/Ada/Color-wheel new file mode 120000 index 0000000000..3d78384078 --- /dev/null +++ b/Lang/Ada/Color-wheel @@ -0,0 +1 @@ +../../Task/Color-wheel/Ada \ No newline at end of file diff --git a/Lang/Ada/Combinations-and-permutations b/Lang/Ada/Combinations-and-permutations new file mode 120000 index 0000000000..3f163f203e --- /dev/null +++ b/Lang/Ada/Combinations-and-permutations @@ -0,0 +1 @@ +../../Task/Combinations-and-permutations/Ada \ No newline at end of file diff --git a/Lang/Ada/Cuban-primes b/Lang/Ada/Cuban-primes new file mode 120000 index 0000000000..a7270c8ac4 --- /dev/null +++ b/Lang/Ada/Cuban-primes @@ -0,0 +1 @@ +../../Task/Cuban-primes/Ada \ No newline at end of file diff --git a/Lang/Ada/Curzon-numbers b/Lang/Ada/Curzon-numbers new file mode 120000 index 0000000000..4a77e1da8a --- /dev/null +++ b/Lang/Ada/Curzon-numbers @@ -0,0 +1 @@ +../../Task/Curzon-numbers/Ada \ No newline at end of file diff --git a/Lang/Ada/Deepcopy b/Lang/Ada/Deepcopy new file mode 120000 index 0000000000..4b1e30735d --- /dev/null +++ b/Lang/Ada/Deepcopy @@ -0,0 +1 @@ +../../Task/Deepcopy/Ada \ No newline at end of file diff --git a/Lang/Ada/Descending-primes b/Lang/Ada/Descending-primes new file mode 120000 index 0000000000..3c6c36447c --- /dev/null +++ b/Lang/Ada/Descending-primes @@ -0,0 +1 @@ +../../Task/Descending-primes/Ada \ No newline at end of file diff --git a/Lang/Ada/Determine-sentence-type b/Lang/Ada/Determine-sentence-type new file mode 120000 index 0000000000..df39412f47 --- /dev/null +++ b/Lang/Ada/Determine-sentence-type @@ -0,0 +1 @@ +../../Task/Determine-sentence-type/Ada \ No newline at end of file diff --git a/Lang/Ada/Eban-numbers b/Lang/Ada/Eban-numbers new file mode 120000 index 0000000000..8c7c83bfc9 --- /dev/null +++ b/Lang/Ada/Eban-numbers @@ -0,0 +1 @@ +../../Task/Eban-numbers/Ada \ No newline at end of file diff --git a/Lang/Ada/Equal-prime-and-composite-sums b/Lang/Ada/Equal-prime-and-composite-sums new file mode 120000 index 0000000000..b1a2555466 --- /dev/null +++ b/Lang/Ada/Equal-prime-and-composite-sums @@ -0,0 +1 @@ +../../Task/Equal-prime-and-composite-sums/Ada \ No newline at end of file diff --git a/Lang/Ada/Eulers-constant-0.5772... b/Lang/Ada/Eulers-constant-0.5772... new file mode 120000 index 0000000000..b0e75cb33e --- /dev/null +++ b/Lang/Ada/Eulers-constant-0.5772... @@ -0,0 +1 @@ +../../Task/Eulers-constant-0.5772.../Ada \ No newline at end of file diff --git a/Lang/Ada/FTP b/Lang/Ada/FTP new file mode 120000 index 0000000000..1d406ce7cd --- /dev/null +++ b/Lang/Ada/FTP @@ -0,0 +1 @@ +../../Task/FTP/Ada \ No newline at end of file diff --git a/Lang/Ada/Factorial-primes b/Lang/Ada/Factorial-primes new file mode 120000 index 0000000000..fdff310065 --- /dev/null +++ b/Lang/Ada/Factorial-primes @@ -0,0 +1 @@ +../../Task/Factorial-primes/Ada \ No newline at end of file diff --git a/Lang/Ada/Factorions b/Lang/Ada/Factorions new file mode 120000 index 0000000000..d9b74415a9 --- /dev/null +++ b/Lang/Ada/Factorions @@ -0,0 +1 @@ +../../Task/Factorions/Ada \ No newline at end of file diff --git a/Lang/Ada/Fermat-numbers b/Lang/Ada/Fermat-numbers new file mode 120000 index 0000000000..c9d81fb3a1 --- /dev/null +++ b/Lang/Ada/Fermat-numbers @@ -0,0 +1 @@ +../../Task/Fermat-numbers/Ada \ No newline at end of file diff --git a/Lang/Ada/Find-duplicate-files b/Lang/Ada/Find-duplicate-files new file mode 120000 index 0000000000..f7ad1ff6fd --- /dev/null +++ b/Lang/Ada/Find-duplicate-files @@ -0,0 +1 @@ +../../Task/Find-duplicate-files/Ada \ No newline at end of file diff --git a/Lang/Ada/Giuga-numbers b/Lang/Ada/Giuga-numbers new file mode 120000 index 0000000000..24ab180f54 --- /dev/null +++ b/Lang/Ada/Giuga-numbers @@ -0,0 +1 @@ +../../Task/Giuga-numbers/Ada \ No newline at end of file diff --git a/Lang/Ada/Harmonic-series b/Lang/Ada/Harmonic-series new file mode 120000 index 0000000000..97492bcb66 --- /dev/null +++ b/Lang/Ada/Harmonic-series @@ -0,0 +1 @@ +../../Task/Harmonic-series/Ada \ No newline at end of file diff --git a/Lang/Ada/Hex-words b/Lang/Ada/Hex-words new file mode 120000 index 0000000000..da49cf2b4d --- /dev/null +++ b/Lang/Ada/Hex-words @@ -0,0 +1 @@ +../../Task/Hex-words/Ada \ No newline at end of file diff --git a/Lang/Ada/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols b/Lang/Ada/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols new file mode 120000 index 0000000000..29e378f3f1 --- /dev/null +++ b/Lang/Ada/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols @@ -0,0 +1 @@ +../../Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/Ada \ No newline at end of file diff --git a/Lang/Ada/Jacobi-symbol b/Lang/Ada/Jacobi-symbol new file mode 120000 index 0000000000..1c52eec7ce --- /dev/null +++ b/Lang/Ada/Jacobi-symbol @@ -0,0 +1 @@ +../../Task/Jacobi-symbol/Ada \ No newline at end of file diff --git a/Lang/Ada/Jacobsthal-numbers b/Lang/Ada/Jacobsthal-numbers new file mode 120000 index 0000000000..630504cad4 --- /dev/null +++ b/Lang/Ada/Jacobsthal-numbers @@ -0,0 +1 @@ +../../Task/Jacobsthal-numbers/Ada \ No newline at end of file diff --git a/Lang/Ada/Knapsack-problem-Bounded b/Lang/Ada/Knapsack-problem-Bounded new file mode 120000 index 0000000000..1cfbda0d29 --- /dev/null +++ b/Lang/Ada/Knapsack-problem-Bounded @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Bounded/Ada \ No newline at end of file diff --git a/Lang/Ada/Kosaraju b/Lang/Ada/Kosaraju new file mode 120000 index 0000000000..0b7b72cfb6 --- /dev/null +++ b/Lang/Ada/Kosaraju @@ -0,0 +1 @@ +../../Task/Kosaraju/Ada \ No newline at end of file diff --git a/Lang/Ada/Lah-numbers b/Lang/Ada/Lah-numbers new file mode 120000 index 0000000000..e4f08d947d --- /dev/null +++ b/Lang/Ada/Lah-numbers @@ -0,0 +1 @@ +../../Task/Lah-numbers/Ada \ No newline at end of file diff --git a/Lang/Ada/Largest-number-divisible-by-its-digits b/Lang/Ada/Largest-number-divisible-by-its-digits new file mode 120000 index 0000000000..d61b3cb8be --- /dev/null +++ b/Lang/Ada/Largest-number-divisible-by-its-digits @@ -0,0 +1 @@ +../../Task/Largest-number-divisible-by-its-digits/Ada \ No newline at end of file diff --git a/Lang/Ada/Left-factorials b/Lang/Ada/Left-factorials new file mode 120000 index 0000000000..8c62b38a57 --- /dev/null +++ b/Lang/Ada/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/Ada \ No newline at end of file diff --git a/Lang/Ada/Levenshtein-distance-Alignment b/Lang/Ada/Levenshtein-distance-Alignment new file mode 120000 index 0000000000..1c6a7ca906 --- /dev/null +++ b/Lang/Ada/Levenshtein-distance-Alignment @@ -0,0 +1 @@ +../../Task/Levenshtein-distance-Alignment/Ada \ No newline at end of file diff --git a/Lang/Ada/Long-literals-with-continuations b/Lang/Ada/Long-literals-with-continuations new file mode 120000 index 0000000000..9d6be6cfc8 --- /dev/null +++ b/Lang/Ada/Long-literals-with-continuations @@ -0,0 +1 @@ +../../Task/Long-literals-with-continuations/Ada \ No newline at end of file diff --git a/Lang/Ada/Longest-increasing-subsequence b/Lang/Ada/Longest-increasing-subsequence new file mode 120000 index 0000000000..dd360a694d --- /dev/null +++ b/Lang/Ada/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/Ada \ No newline at end of file diff --git a/Lang/Ada/M-bius-function b/Lang/Ada/M-bius-function new file mode 120000 index 0000000000..cb59f2e52a --- /dev/null +++ b/Lang/Ada/M-bius-function @@ -0,0 +1 @@ +../../Task/M-bius-function/Ada \ No newline at end of file diff --git a/Lang/Ada/Machine-code b/Lang/Ada/Machine-code new file mode 120000 index 0000000000..52ae4edc91 --- /dev/null +++ b/Lang/Ada/Machine-code @@ -0,0 +1 @@ +../../Task/Machine-code/Ada \ No newline at end of file diff --git a/Lang/Ada/Magic-constant b/Lang/Ada/Magic-constant new file mode 120000 index 0000000000..bd59423b8e --- /dev/null +++ b/Lang/Ada/Magic-constant @@ -0,0 +1 @@ +../../Task/Magic-constant/Ada \ No newline at end of file diff --git a/Lang/Ada/Metallic-ratios b/Lang/Ada/Metallic-ratios new file mode 120000 index 0000000000..f41030172b --- /dev/null +++ b/Lang/Ada/Metallic-ratios @@ -0,0 +1 @@ +../../Task/Metallic-ratios/Ada \ No newline at end of file diff --git a/Lang/Ada/Miller-Rabin-primality-test b/Lang/Ada/Miller-Rabin-primality-test deleted file mode 120000 index 79bf6fd437..0000000000 --- a/Lang/Ada/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Ada \ No newline at end of file diff --git a/Lang/Ada/Mind-boggling-card-trick b/Lang/Ada/Mind-boggling-card-trick new file mode 120000 index 0000000000..11ae4366fc --- /dev/null +++ b/Lang/Ada/Mind-boggling-card-trick @@ -0,0 +1 @@ +../../Task/Mind-boggling-card-trick/Ada \ No newline at end of file diff --git a/Lang/Ada/Minimal-steps-down-to-1 b/Lang/Ada/Minimal-steps-down-to-1 new file mode 120000 index 0000000000..44f17e189f --- /dev/null +++ b/Lang/Ada/Minimal-steps-down-to-1 @@ -0,0 +1 @@ +../../Task/Minimal-steps-down-to-1/Ada \ No newline at end of file diff --git a/Lang/Ada/Musical-scale b/Lang/Ada/Musical-scale new file mode 120000 index 0000000000..a792f4144a --- /dev/null +++ b/Lang/Ada/Musical-scale @@ -0,0 +1 @@ +../../Task/Musical-scale/Ada \ No newline at end of file diff --git a/Lang/Ada/Naming-conventions b/Lang/Ada/Naming-conventions new file mode 120000 index 0000000000..44f00f1ff1 --- /dev/null +++ b/Lang/Ada/Naming-conventions @@ -0,0 +1 @@ +../../Task/Naming-conventions/Ada \ No newline at end of file diff --git a/Lang/Ada/Nautical-bell b/Lang/Ada/Nautical-bell new file mode 120000 index 0000000000..61069c35a0 --- /dev/null +++ b/Lang/Ada/Nautical-bell @@ -0,0 +1 @@ +../../Task/Nautical-bell/Ada \ No newline at end of file diff --git a/Lang/Ada/Next-highest-int-from-digits b/Lang/Ada/Next-highest-int-from-digits new file mode 120000 index 0000000000..e996a777e6 --- /dev/null +++ b/Lang/Ada/Next-highest-int-from-digits @@ -0,0 +1 @@ +../../Task/Next-highest-int-from-digits/Ada \ No newline at end of file diff --git a/Lang/Ada/Numbers-which-are-the-cube-roots-of-the-product-of-their-proper-divisors b/Lang/Ada/Numbers-which-are-the-cube-roots-of-the-product-of-their-proper-divisors new file mode 120000 index 0000000000..58dcaaaaee --- /dev/null +++ b/Lang/Ada/Numbers-which-are-the-cube-roots-of-the-product-of-their-proper-divisors @@ -0,0 +1 @@ +../../Task/Numbers-which-are-the-cube-roots-of-the-product-of-their-proper-divisors/Ada \ No newline at end of file diff --git a/Lang/Ada/Old-Russian-measure-of-length b/Lang/Ada/Old-Russian-measure-of-length new file mode 120000 index 0000000000..1d4422be24 --- /dev/null +++ b/Lang/Ada/Old-Russian-measure-of-length @@ -0,0 +1 @@ +../../Task/Old-Russian-measure-of-length/Ada \ No newline at end of file diff --git a/Lang/Ada/Penneys-game b/Lang/Ada/Penneys-game new file mode 120000 index 0000000000..00a5e1d496 --- /dev/null +++ b/Lang/Ada/Penneys-game @@ -0,0 +1 @@ +../../Task/Penneys-game/Ada \ No newline at end of file diff --git a/Lang/Ada/Permutations-by-swapping b/Lang/Ada/Permutations-by-swapping new file mode 120000 index 0000000000..9140cf7f43 --- /dev/null +++ b/Lang/Ada/Permutations-by-swapping @@ -0,0 +1 @@ +../../Task/Permutations-by-swapping/Ada \ No newline at end of file diff --git a/Lang/Ada/Play-recorded-sounds b/Lang/Ada/Play-recorded-sounds new file mode 120000 index 0000000000..2365ca211b --- /dev/null +++ b/Lang/Ada/Play-recorded-sounds @@ -0,0 +1 @@ +../../Task/Play-recorded-sounds/Ada \ No newline at end of file diff --git a/Lang/Ada/Poker-hand-analyser b/Lang/Ada/Poker-hand-analyser new file mode 120000 index 0000000000..fc5a66b995 --- /dev/null +++ b/Lang/Ada/Poker-hand-analyser @@ -0,0 +1 @@ +../../Task/Poker-hand-analyser/Ada \ No newline at end of file diff --git a/Lang/Ada/Prime-conspiracy b/Lang/Ada/Prime-conspiracy new file mode 120000 index 0000000000..49f0dd3152 --- /dev/null +++ b/Lang/Ada/Prime-conspiracy @@ -0,0 +1 @@ +../../Task/Prime-conspiracy/Ada \ No newline at end of file diff --git a/Lang/Ada/Quaternion-type b/Lang/Ada/Quaternion-type deleted file mode 120000 index 9dc0eab94d..0000000000 --- a/Lang/Ada/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Ada \ No newline at end of file diff --git a/Lang/Ada/Random-sentence-from-book b/Lang/Ada/Random-sentence-from-book new file mode 120000 index 0000000000..f08e942e14 --- /dev/null +++ b/Lang/Ada/Random-sentence-from-book @@ -0,0 +1 @@ +../../Task/Random-sentence-from-book/Ada \ No newline at end of file diff --git a/Lang/Ada/Read-a-file-character-by-character-UTF8 b/Lang/Ada/Read-a-file-character-by-character-UTF8 new file mode 120000 index 0000000000..71f788273b --- /dev/null +++ b/Lang/Ada/Read-a-file-character-by-character-UTF8 @@ -0,0 +1 @@ +../../Task/Read-a-file-character-by-character-UTF8/Ada \ No newline at end of file diff --git a/Lang/Ada/Record-sound b/Lang/Ada/Record-sound new file mode 120000 index 0000000000..af45b7783f --- /dev/null +++ b/Lang/Ada/Record-sound @@ -0,0 +1 @@ +../../Task/Record-sound/Ada \ No newline at end of file diff --git a/Lang/Ada/Safe-primes-and-unsafe-primes b/Lang/Ada/Safe-primes-and-unsafe-primes new file mode 120000 index 0000000000..97b204f4de --- /dev/null +++ b/Lang/Ada/Safe-primes-and-unsafe-primes @@ -0,0 +1 @@ +../../Task/Safe-primes-and-unsafe-primes/Ada \ No newline at end of file diff --git a/Lang/Ada/Selectively-replace-multiple-instances-of-a-character-within-a-string b/Lang/Ada/Selectively-replace-multiple-instances-of-a-character-within-a-string new file mode 120000 index 0000000000..5077dd9033 --- /dev/null +++ b/Lang/Ada/Selectively-replace-multiple-instances-of-a-character-within-a-string @@ -0,0 +1 @@ +../../Task/Selectively-replace-multiple-instances-of-a-character-within-a-string/Ada \ No newline at end of file diff --git a/Lang/Ada/Sexy-primes b/Lang/Ada/Sexy-primes new file mode 120000 index 0000000000..ec070f062f --- /dev/null +++ b/Lang/Ada/Sexy-primes @@ -0,0 +1 @@ +../../Task/Sexy-primes/Ada \ No newline at end of file diff --git a/Lang/Ada/Sierpinski-pentagon b/Lang/Ada/Sierpinski-pentagon new file mode 120000 index 0000000000..d3c2f495a7 --- /dev/null +++ b/Lang/Ada/Sierpinski-pentagon @@ -0,0 +1 @@ +../../Task/Sierpinski-pentagon/Ada \ No newline at end of file diff --git a/Lang/Ada/Sierpinski-square-curve b/Lang/Ada/Sierpinski-square-curve new file mode 120000 index 0000000000..32cee5f712 --- /dev/null +++ b/Lang/Ada/Sierpinski-square-curve @@ -0,0 +1 @@ +../../Task/Sierpinski-square-curve/Ada \ No newline at end of file diff --git a/Lang/Ada/Sierpinski-triangle-Graphical b/Lang/Ada/Sierpinski-triangle-Graphical new file mode 120000 index 0000000000..c5fb35984b --- /dev/null +++ b/Lang/Ada/Sierpinski-triangle-Graphical @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle-Graphical/Ada \ No newline at end of file diff --git a/Lang/Ada/Sleeping-Beauty-problem b/Lang/Ada/Sleeping-Beauty-problem new file mode 120000 index 0000000000..1c2ef27d37 --- /dev/null +++ b/Lang/Ada/Sleeping-Beauty-problem @@ -0,0 +1 @@ +../../Task/Sleeping-Beauty-problem/Ada \ No newline at end of file diff --git a/Lang/Ada/Smallest-number-k-such-that-k+2^m-is-composite-for-all-m-less-than-k b/Lang/Ada/Smallest-number-k-such-that-k+2^m-is-composite-for-all-m-less-than-k new file mode 120000 index 0000000000..acb5a83713 --- /dev/null +++ b/Lang/Ada/Smallest-number-k-such-that-k+2^m-is-composite-for-all-m-less-than-k @@ -0,0 +1 @@ +../../Task/Smallest-number-k-such-that-k+2^m-is-composite-for-all-m-less-than-k/Ada \ No newline at end of file diff --git a/Lang/Ada/Sorting-algorithms-Cocktail-sort-with-shifting-bounds b/Lang/Ada/Sorting-algorithms-Cocktail-sort-with-shifting-bounds new file mode 120000 index 0000000000..484d3d768d --- /dev/null +++ b/Lang/Ada/Sorting-algorithms-Cocktail-sort-with-shifting-bounds @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort-with-shifting-bounds/Ada \ No newline at end of file diff --git a/Lang/Ada/Sorting-algorithms-Permutation-sort b/Lang/Ada/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..0f333c5ec8 --- /dev/null +++ b/Lang/Ada/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/Ada \ No newline at end of file diff --git a/Lang/Ada/Test-integerness b/Lang/Ada/Test-integerness new file mode 120000 index 0000000000..8a5462dcb5 --- /dev/null +++ b/Lang/Ada/Test-integerness @@ -0,0 +1 @@ +../../Task/Test-integerness/Ada \ No newline at end of file diff --git a/Lang/Ada/Total-circles-area b/Lang/Ada/Total-circles-area new file mode 120000 index 0000000000..781e585826 --- /dev/null +++ b/Lang/Ada/Total-circles-area @@ -0,0 +1 @@ +../../Task/Total-circles-area/Ada \ No newline at end of file diff --git a/Lang/Ada/Twin-primes b/Lang/Ada/Twin-primes new file mode 120000 index 0000000000..f368573f47 --- /dev/null +++ b/Lang/Ada/Twin-primes @@ -0,0 +1 @@ +../../Task/Twin-primes/Ada \ No newline at end of file diff --git a/Lang/Ada/Twos-complement b/Lang/Ada/Twos-complement new file mode 120000 index 0000000000..396d1a76f2 --- /dev/null +++ b/Lang/Ada/Twos-complement @@ -0,0 +1 @@ +../../Task/Twos-complement/Ada \ No newline at end of file diff --git a/Lang/Ada/UPC b/Lang/Ada/UPC new file mode 120000 index 0000000000..374da7b0aa --- /dev/null +++ b/Lang/Ada/UPC @@ -0,0 +1 @@ +../../Task/UPC/Ada \ No newline at end of file diff --git a/Lang/Ada/Ultra-useful-primes b/Lang/Ada/Ultra-useful-primes new file mode 120000 index 0000000000..c89f1426c4 --- /dev/null +++ b/Lang/Ada/Ultra-useful-primes @@ -0,0 +1 @@ +../../Task/Ultra-useful-primes/Ada \ No newline at end of file diff --git a/Lang/Ada/Vector b/Lang/Ada/Vector new file mode 120000 index 0000000000..4cc7975e2f --- /dev/null +++ b/Lang/Ada/Vector @@ -0,0 +1 @@ +../../Task/Vector/Ada \ No newline at end of file diff --git a/Lang/Ada/Wagstaff-primes b/Lang/Ada/Wagstaff-primes new file mode 120000 index 0000000000..3b705137b1 --- /dev/null +++ b/Lang/Ada/Wagstaff-primes @@ -0,0 +1 @@ +../../Task/Wagstaff-primes/Ada \ No newline at end of file diff --git a/Lang/Ada/War-card-game b/Lang/Ada/War-card-game new file mode 120000 index 0000000000..dd4f92afee --- /dev/null +++ b/Lang/Ada/War-card-game @@ -0,0 +1 @@ +../../Task/War-card-game/Ada \ No newline at end of file diff --git a/Lang/Ada/Weird-numbers b/Lang/Ada/Weird-numbers new file mode 120000 index 0000000000..98491ade1a --- /dev/null +++ b/Lang/Ada/Weird-numbers @@ -0,0 +1 @@ +../../Task/Weird-numbers/Ada \ No newline at end of file diff --git a/Lang/Ada/Wilson-primes-of-order-n b/Lang/Ada/Wilson-primes-of-order-n new file mode 120000 index 0000000000..95a6ebc6d1 --- /dev/null +++ b/Lang/Ada/Wilson-primes-of-order-n @@ -0,0 +1 @@ +../../Task/Wilson-primes-of-order-n/Ada \ No newline at end of file diff --git a/Lang/Ada/Word-ladder b/Lang/Ada/Word-ladder new file mode 120000 index 0000000000..495c24dbcd --- /dev/null +++ b/Lang/Ada/Word-ladder @@ -0,0 +1 @@ +../../Task/Word-ladder/Ada \ No newline at end of file diff --git a/Lang/Ada/Word-search b/Lang/Ada/Word-search new file mode 120000 index 0000000000..32f00f4762 --- /dev/null +++ b/Lang/Ada/Word-search @@ -0,0 +1 @@ +../../Task/Word-search/Ada \ No newline at end of file diff --git a/Lang/Ada/Word-wheel b/Lang/Ada/Word-wheel new file mode 120000 index 0000000000..47f67698e0 --- /dev/null +++ b/Lang/Ada/Word-wheel @@ -0,0 +1 @@ +../../Task/Word-wheel/Ada \ No newline at end of file diff --git a/Lang/Adina/00-LANG.txt b/Lang/Adina/00-LANG.txt new file mode 100644 index 0000000000..e796807867 --- /dev/null +++ b/Lang/Adina/00-LANG.txt @@ -0,0 +1,13 @@ +{{language|Adina}} +Adina is a programming language, based on Racket and russian language. Unlike Racket it uses indent and operators precedence to describe program syntax. It may be used in english, because all Racket libraries are accessible. One should add "english()" in first string to use standard racket libraries. + +Адина, это язык программирования, основанный на Racket и русском языке. В отличие от Racket вместо скобок для синтаксической +структуры используются отступы и бинарные операторы. Также сделан доступ через квадратные скобки к элементам коллекции и через фигурные к методам объектов. + +Документация по адресу: https://docs.racket-lang.org/russian-lang/ + +==See Also== +* [[Racket]] + +==TODO== +[[Tasks not implemented in Adina]] \ No newline at end of file diff --git a/Lang/Adina/00-META.yaml b/Lang/Adina/00-META.yaml new file mode 100644 index 0000000000..e1ca8650ca --- /dev/null +++ b/Lang/Adina/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Adina diff --git a/Lang/Adina/100-doors b/Lang/Adina/100-doors new file mode 120000 index 0000000000..c96d2d65fc --- /dev/null +++ b/Lang/Adina/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/Adina \ No newline at end of file diff --git a/Lang/Adina/Even-or-odd b/Lang/Adina/Even-or-odd new file mode 120000 index 0000000000..1718b42d76 --- /dev/null +++ b/Lang/Adina/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/Adina \ No newline at end of file diff --git a/Lang/Adina/Hello-world-Text b/Lang/Adina/Hello-world-Text new file mode 120000 index 0000000000..f886a7cc4f --- /dev/null +++ b/Lang/Adina/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Adina \ No newline at end of file diff --git a/Lang/Adina/Loops-For b/Lang/Adina/Loops-For new file mode 120000 index 0000000000..c4d6bee093 --- /dev/null +++ b/Lang/Adina/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/Adina \ No newline at end of file diff --git a/Lang/Adina/Tree-traversal b/Lang/Adina/Tree-traversal new file mode 120000 index 0000000000..fd3896d623 --- /dev/null +++ b/Lang/Adina/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/Adina \ No newline at end of file diff --git a/Lang/Agena/00-LANG.txt b/Lang/Agena/00-LANG.txt index c2930ac7a2..5398f01156 100644 --- a/Lang/Agena/00-LANG.txt +++ b/Lang/Agena/00-LANG.txt @@ -20,5 +20,10 @@ The syntax looks like very simplified [[ALGOL 68]] with elements taken from [[Lu == How has it been implemented ? == Agena is based on the [[ANSI]] [[C]] source code of [[Lua]], a popular and widely used Open Source programming language. +== Todo == +[[Tasks not implemented in Agena]] + == See Also == -[[ALGOL 68]] \ No newline at end of file +[[ALGOL 68]]
+[[Lua]]
+[[SQL]] \ No newline at end of file diff --git a/Lang/Agena/100-doors b/Lang/Agena/100-doors deleted file mode 120000 index 3a9139bb1c..0000000000 --- a/Lang/Agena/100-doors +++ /dev/null @@ -1 +0,0 @@ -../../Task/100-doors/Agena \ No newline at end of file diff --git a/Lang/Agena/AKS-test-for-primes b/Lang/Agena/AKS-test-for-primes new file mode 120000 index 0000000000..ab27a842c8 --- /dev/null +++ b/Lang/Agena/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/Agena \ No newline at end of file diff --git a/Lang/Agena/Abundant-deficient-and-perfect-number-classifications b/Lang/Agena/Abundant-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..89450cb83c --- /dev/null +++ b/Lang/Agena/Abundant-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant-deficient-and-perfect-number-classifications/Agena \ No newline at end of file diff --git a/Lang/Agena/Abundant-odd-numbers b/Lang/Agena/Abundant-odd-numbers new file mode 120000 index 0000000000..a18ccbb662 --- /dev/null +++ b/Lang/Agena/Abundant-odd-numbers @@ -0,0 +1 @@ +../../Task/Abundant-odd-numbers/Agena \ No newline at end of file diff --git a/Lang/Agena/Ackermann-function b/Lang/Agena/Ackermann-function new file mode 120000 index 0000000000..fb262b01a7 --- /dev/null +++ b/Lang/Agena/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/Agena \ No newline at end of file diff --git a/Lang/Agena/Almost-prime b/Lang/Agena/Almost-prime new file mode 120000 index 0000000000..62b34f9616 --- /dev/null +++ b/Lang/Agena/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/Agena \ No newline at end of file diff --git a/Lang/Agena/Angle-difference-between-two-bearings b/Lang/Agena/Angle-difference-between-two-bearings new file mode 120000 index 0000000000..62a719bb70 --- /dev/null +++ b/Lang/Agena/Angle-difference-between-two-bearings @@ -0,0 +1 @@ +../../Task/Angle-difference-between-two-bearings/Agena \ No newline at end of file diff --git a/Lang/Agena/Anti-primes b/Lang/Agena/Anti-primes new file mode 120000 index 0000000000..f98d65a6cf --- /dev/null +++ b/Lang/Agena/Anti-primes @@ -0,0 +1 @@ +../../Task/Anti-primes/Agena \ No newline at end of file diff --git a/Lang/Agena/Arbitrary-precision-integers-included- b/Lang/Agena/Arbitrary-precision-integers-included- new file mode 120000 index 0000000000..347104998a --- /dev/null +++ b/Lang/Agena/Arbitrary-precision-integers-included- @@ -0,0 +1 @@ +../../Task/Arbitrary-precision-integers-included-/Agena \ No newline at end of file diff --git a/Lang/Agena/Ascending-primes b/Lang/Agena/Ascending-primes new file mode 120000 index 0000000000..9c8c50d2ae --- /dev/null +++ b/Lang/Agena/Ascending-primes @@ -0,0 +1 @@ +../../Task/Ascending-primes/Agena \ No newline at end of file diff --git a/Lang/Agena/Associative-array-Iteration b/Lang/Agena/Associative-array-Iteration new file mode 120000 index 0000000000..55b1a0c7a6 --- /dev/null +++ b/Lang/Agena/Associative-array-Iteration @@ -0,0 +1 @@ +../../Task/Associative-array-Iteration/Agena \ No newline at end of file diff --git a/Lang/Agena/Attractive-numbers b/Lang/Agena/Attractive-numbers new file mode 120000 index 0000000000..bc968b5d21 --- /dev/null +++ b/Lang/Agena/Attractive-numbers @@ -0,0 +1 @@ +../../Task/Attractive-numbers/Agena \ No newline at end of file diff --git a/Lang/Agena/Brazilian-numbers b/Lang/Agena/Brazilian-numbers new file mode 120000 index 0000000000..7312d4ef84 --- /dev/null +++ b/Lang/Agena/Brazilian-numbers @@ -0,0 +1 @@ +../../Task/Brazilian-numbers/Agena \ No newline at end of file diff --git a/Lang/Agena/Calkin-Wilf-sequence b/Lang/Agena/Calkin-Wilf-sequence new file mode 120000 index 0000000000..eaff2085aa --- /dev/null +++ b/Lang/Agena/Calkin-Wilf-sequence @@ -0,0 +1 @@ +../../Task/Calkin-Wilf-sequence/Agena \ No newline at end of file diff --git a/Lang/Agena/Catalan-numbers b/Lang/Agena/Catalan-numbers new file mode 120000 index 0000000000..926ef43918 --- /dev/null +++ b/Lang/Agena/Catalan-numbers @@ -0,0 +1 @@ +../../Task/Catalan-numbers/Agena \ No newline at end of file diff --git a/Lang/Agena/Character-codes b/Lang/Agena/Character-codes new file mode 120000 index 0000000000..39121b3568 --- /dev/null +++ b/Lang/Agena/Character-codes @@ -0,0 +1 @@ +../../Task/Character-codes/Agena \ No newline at end of file diff --git a/Lang/Agena/Chowla-numbers b/Lang/Agena/Chowla-numbers new file mode 120000 index 0000000000..d4c2806c20 --- /dev/null +++ b/Lang/Agena/Chowla-numbers @@ -0,0 +1 @@ +../../Task/Chowla-numbers/Agena \ No newline at end of file diff --git a/Lang/Agena/Damm-algorithm b/Lang/Agena/Damm-algorithm new file mode 120000 index 0000000000..d753c9e99f --- /dev/null +++ b/Lang/Agena/Damm-algorithm @@ -0,0 +1 @@ +../../Task/Damm-algorithm/Agena \ No newline at end of file diff --git a/Lang/Agena/Day-of-the-week b/Lang/Agena/Day-of-the-week new file mode 120000 index 0000000000..e4733798aa --- /dev/null +++ b/Lang/Agena/Day-of-the-week @@ -0,0 +1 @@ +../../Task/Day-of-the-week/Agena \ No newline at end of file diff --git a/Lang/Agena/Department-numbers b/Lang/Agena/Department-numbers new file mode 120000 index 0000000000..fdeaca8fd3 --- /dev/null +++ b/Lang/Agena/Department-numbers @@ -0,0 +1 @@ +../../Task/Department-numbers/Agena \ No newline at end of file diff --git a/Lang/Agena/Descending-primes b/Lang/Agena/Descending-primes new file mode 120000 index 0000000000..483dfe03f7 --- /dev/null +++ b/Lang/Agena/Descending-primes @@ -0,0 +1 @@ +../../Task/Descending-primes/Agena \ No newline at end of file diff --git a/Lang/Agena/Disarium-numbers b/Lang/Agena/Disarium-numbers new file mode 120000 index 0000000000..2bace62b71 --- /dev/null +++ b/Lang/Agena/Disarium-numbers @@ -0,0 +1 @@ +../../Task/Disarium-numbers/Agena \ No newline at end of file diff --git a/Lang/Agena/Entropy b/Lang/Agena/Entropy new file mode 120000 index 0000000000..f0f66caa04 --- /dev/null +++ b/Lang/Agena/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/Agena \ No newline at end of file diff --git a/Lang/Agena/Equal-prime-and-composite-sums b/Lang/Agena/Equal-prime-and-composite-sums new file mode 120000 index 0000000000..376401ddea --- /dev/null +++ b/Lang/Agena/Equal-prime-and-composite-sums @@ -0,0 +1 @@ +../../Task/Equal-prime-and-composite-sums/Agena \ No newline at end of file diff --git a/Lang/Agena/Factorial b/Lang/Agena/Factorial new file mode 120000 index 0000000000..21cbc1e46b --- /dev/null +++ b/Lang/Agena/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Agena \ No newline at end of file diff --git a/Lang/Agena/Factorial-primes b/Lang/Agena/Factorial-primes new file mode 120000 index 0000000000..68796e7224 --- /dev/null +++ b/Lang/Agena/Factorial-primes @@ -0,0 +1 @@ +../../Task/Factorial-primes/Agena \ No newline at end of file diff --git a/Lang/Agena/Gamma-function b/Lang/Agena/Gamma-function new file mode 120000 index 0000000000..c0b0340467 --- /dev/null +++ b/Lang/Agena/Gamma-function @@ -0,0 +1 @@ +../../Task/Gamma-function/Agena \ No newline at end of file diff --git a/Lang/Agena/Gauss-Jordan-matrix-inversion b/Lang/Agena/Gauss-Jordan-matrix-inversion new file mode 120000 index 0000000000..a1bc51eaa3 --- /dev/null +++ b/Lang/Agena/Gauss-Jordan-matrix-inversion @@ -0,0 +1 @@ +../../Task/Gauss-Jordan-matrix-inversion/Agena \ No newline at end of file diff --git a/Lang/Agena/Generate-lower-case-ASCII-alphabet b/Lang/Agena/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..ace5f93bb5 --- /dev/null +++ b/Lang/Agena/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Agena \ No newline at end of file diff --git a/Lang/Agena/Giuga-numbers b/Lang/Agena/Giuga-numbers new file mode 120000 index 0000000000..273fdf8c7c --- /dev/null +++ b/Lang/Agena/Giuga-numbers @@ -0,0 +1 @@ +../../Task/Giuga-numbers/Agena \ No newline at end of file diff --git a/Lang/Agena/Goldbachs-comet b/Lang/Agena/Goldbachs-comet new file mode 120000 index 0000000000..26b052a294 --- /dev/null +++ b/Lang/Agena/Goldbachs-comet @@ -0,0 +1 @@ +../../Task/Goldbachs-comet/Agena \ No newline at end of file diff --git a/Lang/Agena/Haversine-formula b/Lang/Agena/Haversine-formula new file mode 120000 index 0000000000..45e20df974 --- /dev/null +++ b/Lang/Agena/Haversine-formula @@ -0,0 +1 @@ +../../Task/Haversine-formula/Agena \ No newline at end of file diff --git a/Lang/Agena/Horners-rule-for-polynomial-evaluation b/Lang/Agena/Horners-rule-for-polynomial-evaluation new file mode 120000 index 0000000000..cffe37e87c --- /dev/null +++ b/Lang/Agena/Horners-rule-for-polynomial-evaluation @@ -0,0 +1 @@ +../../Task/Horners-rule-for-polynomial-evaluation/Agena \ No newline at end of file diff --git a/Lang/Agena/Humble-numbers b/Lang/Agena/Humble-numbers new file mode 120000 index 0000000000..bdce77fd35 --- /dev/null +++ b/Lang/Agena/Humble-numbers @@ -0,0 +1 @@ +../../Task/Humble-numbers/Agena \ No newline at end of file diff --git a/Lang/Agena/JSON b/Lang/Agena/JSON new file mode 120000 index 0000000000..9c20f7b68f --- /dev/null +++ b/Lang/Agena/JSON @@ -0,0 +1 @@ +../../Task/JSON/Agena \ No newline at end of file diff --git a/Lang/Agena/Jacobsthal-numbers b/Lang/Agena/Jacobsthal-numbers new file mode 120000 index 0000000000..740d21ef1a --- /dev/null +++ b/Lang/Agena/Jacobsthal-numbers @@ -0,0 +1 @@ +../../Task/Jacobsthal-numbers/Agena \ No newline at end of file diff --git a/Lang/Agena/Jewels-and-stones b/Lang/Agena/Jewels-and-stones new file mode 120000 index 0000000000..7c03f8ec8f --- /dev/null +++ b/Lang/Agena/Jewels-and-stones @@ -0,0 +1 @@ +../../Task/Jewels-and-stones/Agena \ No newline at end of file diff --git a/Lang/Agena/Jordan-P-lya-numbers b/Lang/Agena/Jordan-P-lya-numbers new file mode 120000 index 0000000000..4e2d64a6e1 --- /dev/null +++ b/Lang/Agena/Jordan-P-lya-numbers @@ -0,0 +1 @@ +../../Task/Jordan-P-lya-numbers/Agena \ No newline at end of file diff --git a/Lang/Agena/Juggler-sequence b/Lang/Agena/Juggler-sequence new file mode 120000 index 0000000000..e5817b72b7 --- /dev/null +++ b/Lang/Agena/Juggler-sequence @@ -0,0 +1 @@ +../../Task/Juggler-sequence/Agena \ No newline at end of file diff --git a/Lang/Agena/Kaprekar-numbers b/Lang/Agena/Kaprekar-numbers new file mode 120000 index 0000000000..d665f2f5f5 --- /dev/null +++ b/Lang/Agena/Kaprekar-numbers @@ -0,0 +1 @@ +../../Task/Kaprekar-numbers/Agena \ No newline at end of file diff --git a/Lang/Agena/Legendre-prime-counting-function b/Lang/Agena/Legendre-prime-counting-function new file mode 120000 index 0000000000..07d7bc7083 --- /dev/null +++ b/Lang/Agena/Legendre-prime-counting-function @@ -0,0 +1 @@ +../../Task/Legendre-prime-counting-function/Agena \ No newline at end of file diff --git a/Lang/Agena/Leonardo-numbers b/Lang/Agena/Leonardo-numbers new file mode 120000 index 0000000000..d6d819f05a --- /dev/null +++ b/Lang/Agena/Leonardo-numbers @@ -0,0 +1 @@ +../../Task/Leonardo-numbers/Agena \ No newline at end of file diff --git a/Lang/Agena/Levenshtein-distance b/Lang/Agena/Levenshtein-distance new file mode 120000 index 0000000000..ec3426b464 --- /dev/null +++ b/Lang/Agena/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/Agena \ No newline at end of file diff --git a/Lang/Agena/Mayan-numerals b/Lang/Agena/Mayan-numerals new file mode 120000 index 0000000000..671a85a6c0 --- /dev/null +++ b/Lang/Agena/Mayan-numerals @@ -0,0 +1 @@ +../../Task/Mayan-numerals/Agena \ No newline at end of file diff --git a/Lang/Agena/McNuggets-problem b/Lang/Agena/McNuggets-problem new file mode 120000 index 0000000000..b2417f0142 --- /dev/null +++ b/Lang/Agena/McNuggets-problem @@ -0,0 +1 @@ +../../Task/McNuggets-problem/Agena \ No newline at end of file diff --git a/Lang/Agena/Mian-Chowla-sequence b/Lang/Agena/Mian-Chowla-sequence new file mode 120000 index 0000000000..a6489175a6 --- /dev/null +++ b/Lang/Agena/Mian-Chowla-sequence @@ -0,0 +1 @@ +../../Task/Mian-Chowla-sequence/Agena \ No newline at end of file diff --git a/Lang/Agena/Monty-Hall-problem b/Lang/Agena/Monty-Hall-problem new file mode 120000 index 0000000000..d1c4ae980e --- /dev/null +++ b/Lang/Agena/Monty-Hall-problem @@ -0,0 +1 @@ +../../Task/Monty-Hall-problem/Agena \ No newline at end of file diff --git a/Lang/Agena/Numbers-with-equal-rises-and-falls b/Lang/Agena/Numbers-with-equal-rises-and-falls new file mode 120000 index 0000000000..08787d85d6 --- /dev/null +++ b/Lang/Agena/Numbers-with-equal-rises-and-falls @@ -0,0 +1 @@ +../../Task/Numbers-with-equal-rises-and-falls/Agena \ No newline at end of file diff --git a/Lang/Agena/Ordered-words b/Lang/Agena/Ordered-words new file mode 120000 index 0000000000..3503a492c8 --- /dev/null +++ b/Lang/Agena/Ordered-words @@ -0,0 +1 @@ +../../Task/Ordered-words/Agena \ No newline at end of file diff --git a/Lang/Agena/Periodic-table b/Lang/Agena/Periodic-table new file mode 120000 index 0000000000..cb70080867 --- /dev/null +++ b/Lang/Agena/Periodic-table @@ -0,0 +1 @@ +../../Task/Periodic-table/Agena \ No newline at end of file diff --git a/Lang/Agena/Pernicious-numbers b/Lang/Agena/Pernicious-numbers new file mode 120000 index 0000000000..454ce5b94d --- /dev/null +++ b/Lang/Agena/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/Agena \ No newline at end of file diff --git a/Lang/Agena/Pisano-period b/Lang/Agena/Pisano-period new file mode 120000 index 0000000000..afaae8dce9 --- /dev/null +++ b/Lang/Agena/Pisano-period @@ -0,0 +1 @@ +../../Task/Pisano-period/Agena \ No newline at end of file diff --git a/Lang/Agena/Primality-by-trial-division b/Lang/Agena/Primality-by-trial-division new file mode 120000 index 0000000000..621c0609eb --- /dev/null +++ b/Lang/Agena/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/Agena \ No newline at end of file diff --git a/Lang/Agena/Program-name b/Lang/Agena/Program-name new file mode 120000 index 0000000000..bf43276155 --- /dev/null +++ b/Lang/Agena/Program-name @@ -0,0 +1 @@ +../../Task/Program-name/Agena \ No newline at end of file diff --git a/Lang/Agena/Quoting-constructs b/Lang/Agena/Quoting-constructs new file mode 120000 index 0000000000..f6fed80313 --- /dev/null +++ b/Lang/Agena/Quoting-constructs @@ -0,0 +1 @@ +../../Task/Quoting-constructs/Agena \ No newline at end of file diff --git a/Lang/Agena/Read-a-file-line-by-line b/Lang/Agena/Read-a-file-line-by-line new file mode 120000 index 0000000000..a4d8ef354b --- /dev/null +++ b/Lang/Agena/Read-a-file-line-by-line @@ -0,0 +1 @@ +../../Task/Read-a-file-line-by-line/Agena \ No newline at end of file diff --git a/Lang/Agena/Reverse-a-string b/Lang/Agena/Reverse-a-string new file mode 120000 index 0000000000..db79d68725 --- /dev/null +++ b/Lang/Agena/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/Agena \ No newline at end of file diff --git a/Lang/Agena/Sequence-of-primes-by-trial-division b/Lang/Agena/Sequence-of-primes-by-trial-division new file mode 120000 index 0000000000..d7958a31a1 --- /dev/null +++ b/Lang/Agena/Sequence-of-primes-by-trial-division @@ -0,0 +1 @@ +../../Task/Sequence-of-primes-by-trial-division/Agena \ No newline at end of file diff --git a/Lang/Agena/Sleeping-Beauty-problem b/Lang/Agena/Sleeping-Beauty-problem new file mode 120000 index 0000000000..2cf02e5792 --- /dev/null +++ b/Lang/Agena/Sleeping-Beauty-problem @@ -0,0 +1 @@ +../../Task/Sleeping-Beauty-problem/Agena \ No newline at end of file diff --git a/Lang/Agena/Smarandache-prime-digital-sequence b/Lang/Agena/Smarandache-prime-digital-sequence new file mode 120000 index 0000000000..3a1f0e0805 --- /dev/null +++ b/Lang/Agena/Smarandache-prime-digital-sequence @@ -0,0 +1 @@ +../../Task/Smarandache-prime-digital-sequence/Agena \ No newline at end of file diff --git a/Lang/Agena/Soloways-recurring-rainfall b/Lang/Agena/Soloways-recurring-rainfall new file mode 120000 index 0000000000..b391a79582 --- /dev/null +++ b/Lang/Agena/Soloways-recurring-rainfall @@ -0,0 +1 @@ +../../Task/Soloways-recurring-rainfall/Agena \ No newline at end of file diff --git a/Lang/Agena/Square-but-not-cube b/Lang/Agena/Square-but-not-cube new file mode 120000 index 0000000000..951bd25edd --- /dev/null +++ b/Lang/Agena/Square-but-not-cube @@ -0,0 +1 @@ +../../Task/Square-but-not-cube/Agena \ No newline at end of file diff --git a/Lang/Agena/Sum-of-elements-below-main-diagonal-of-matrix b/Lang/Agena/Sum-of-elements-below-main-diagonal-of-matrix new file mode 120000 index 0000000000..6bd7256f3a --- /dev/null +++ b/Lang/Agena/Sum-of-elements-below-main-diagonal-of-matrix @@ -0,0 +1 @@ +../../Task/Sum-of-elements-below-main-diagonal-of-matrix/Agena \ No newline at end of file diff --git a/Lang/Agena/Super-d-numbers b/Lang/Agena/Super-d-numbers new file mode 120000 index 0000000000..1da0548626 --- /dev/null +++ b/Lang/Agena/Super-d-numbers @@ -0,0 +1 @@ +../../Task/Super-d-numbers/Agena \ No newline at end of file diff --git a/Lang/Agena/Sylvesters-sequence b/Lang/Agena/Sylvesters-sequence new file mode 120000 index 0000000000..9a5d51563f --- /dev/null +++ b/Lang/Agena/Sylvesters-sequence @@ -0,0 +1 @@ +../../Task/Sylvesters-sequence/Agena \ No newline at end of file diff --git a/Lang/Agena/Tau-function b/Lang/Agena/Tau-function new file mode 120000 index 0000000000..579307a681 --- /dev/null +++ b/Lang/Agena/Tau-function @@ -0,0 +1 @@ +../../Task/Tau-function/Agena \ No newline at end of file diff --git a/Lang/Agena/Tau-number b/Lang/Agena/Tau-number new file mode 120000 index 0000000000..543c34a5b4 --- /dev/null +++ b/Lang/Agena/Tau-number @@ -0,0 +1 @@ +../../Task/Tau-number/Agena \ No newline at end of file diff --git a/Lang/Agena/The-sieve-of-Sundaram b/Lang/Agena/The-sieve-of-Sundaram new file mode 120000 index 0000000000..5ab3c6c849 --- /dev/null +++ b/Lang/Agena/The-sieve-of-Sundaram @@ -0,0 +1 @@ +../../Task/The-sieve-of-Sundaram/Agena \ No newline at end of file diff --git a/Lang/Agena/Thue-Morse b/Lang/Agena/Thue-Morse new file mode 120000 index 0000000000..f3225165e3 --- /dev/null +++ b/Lang/Agena/Thue-Morse @@ -0,0 +1 @@ +../../Task/Thue-Morse/Agena \ No newline at end of file diff --git a/Lang/Agena/Time-a-function b/Lang/Agena/Time-a-function new file mode 120000 index 0000000000..e5746c4dff --- /dev/null +++ b/Lang/Agena/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Agena \ No newline at end of file diff --git a/Lang/Agena/Totient-function b/Lang/Agena/Totient-function new file mode 120000 index 0000000000..d74f15771c --- /dev/null +++ b/Lang/Agena/Totient-function @@ -0,0 +1 @@ +../../Task/Totient-function/Agena \ No newline at end of file diff --git a/Lang/Agena/Unprimeable-numbers b/Lang/Agena/Unprimeable-numbers new file mode 120000 index 0000000000..fc3b30fec4 --- /dev/null +++ b/Lang/Agena/Unprimeable-numbers @@ -0,0 +1 @@ +../../Task/Unprimeable-numbers/Agena \ No newline at end of file diff --git a/Lang/Agena/Van-Eck-sequence b/Lang/Agena/Van-Eck-sequence new file mode 120000 index 0000000000..1714aa1507 --- /dev/null +++ b/Lang/Agena/Van-Eck-sequence @@ -0,0 +1 @@ +../../Task/Van-Eck-sequence/Agena \ No newline at end of file diff --git a/Lang/Agena/Van-der-Corput-sequence b/Lang/Agena/Van-der-Corput-sequence new file mode 120000 index 0000000000..92bec950df --- /dev/null +++ b/Lang/Agena/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/Agena \ No newline at end of file diff --git a/Lang/Agena/Wagstaff-primes b/Lang/Agena/Wagstaff-primes new file mode 120000 index 0000000000..b63d3369fa --- /dev/null +++ b/Lang/Agena/Wagstaff-primes @@ -0,0 +1 @@ +../../Task/Wagstaff-primes/Agena \ No newline at end of file diff --git a/Lang/Agena/Wieferich-primes b/Lang/Agena/Wieferich-primes new file mode 120000 index 0000000000..34597fbb1d --- /dev/null +++ b/Lang/Agena/Wieferich-primes @@ -0,0 +1 @@ +../../Task/Wieferich-primes/Agena \ No newline at end of file diff --git a/Lang/Agena/Wilson-primes-of-order-n b/Lang/Agena/Wilson-primes-of-order-n new file mode 120000 index 0000000000..6b8ae43468 --- /dev/null +++ b/Lang/Agena/Wilson-primes-of-order-n @@ -0,0 +1 @@ +../../Task/Wilson-primes-of-order-n/Agena \ No newline at end of file diff --git a/Lang/Agena/Yellowstone-sequence b/Lang/Agena/Yellowstone-sequence new file mode 120000 index 0000000000..4464a6e815 --- /dev/null +++ b/Lang/Agena/Yellowstone-sequence @@ -0,0 +1 @@ +../../Task/Yellowstone-sequence/Agena \ No newline at end of file diff --git a/Lang/Aikido/00-LANG.txt b/Lang/Aikido/00-LANG.txt index 4126891ffb..19bd4a47ab 100644 --- a/Lang/Aikido/00-LANG.txt +++ b/Lang/Aikido/00-LANG.txt @@ -12,4 +12,4 @@ It was developed at [[Sun Microsystems|Sun Microsystems Laboratories]] by David In some respects it is similar in functionality to [[Python]], [[Perl]], [[JavaScript]] and [[Java]]. Syntactically it is very similar to [[C++]] and Java. -Aikido is available for Linux, Mac OS X and Solaris. The interpreter can be obtained from http://sourceforge.net/projects/aikido. Documentation (in PDF) is at http://downloads.sourceforge.net/aikido/aikido_prm.pdf \ No newline at end of file +Aikido is available for Linux, Mac OS X and Solaris. The interpreter can be obtained from http://sourceforge.net/projects/aikido. Documentation (in PDF) is at https://sourceforge.net/projects/aikido/files/aikido/1.40/aikidoref140.pdf/download \ No newline at end of file diff --git a/Lang/Amazing-Hopper/Digital-root b/Lang/Amazing-Hopper/Digital-root new file mode 120000 index 0000000000..22bf453215 --- /dev/null +++ b/Lang/Amazing-Hopper/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/Amazing-Hopper \ No newline at end of file diff --git a/Lang/Amazing-Hopper/Sum-of-a-series b/Lang/Amazing-Hopper/Sum-of-a-series new file mode 120000 index 0000000000..03635804ee --- /dev/null +++ b/Lang/Amazing-Hopper/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Amazing-Hopper \ No newline at end of file diff --git a/Lang/AmigaBASIC/00-LANG.txt b/Lang/AmigaBASIC/00-LANG.txt index 94b3e71ee7..c2e6f48854 100644 --- a/Lang/AmigaBASIC/00-LANG.txt +++ b/Lang/AmigaBASIC/00-LANG.txt @@ -11,5 +11,7 @@ Execution speed however was not a particular strength of AmigaBASIC. Some 8-bit AmigaBASIC was superseded by [[wp:ARexx|ARexx]], a REXX-style scripting language, from AmigaOS version 2.0 onwards. The 1.x AmigaBASIC binary also works on AmigaOS 2, but not on AmigaOS 3. +Microsoft [[QuickBASIC]] (1985) and QBasic (1991) look very similar to AmigaBASIC, so their syntax highlighting rules mostly also work for AmigaBASIC code. + ==See Also== *[https://archive.org/search.php?query=amiga%20basic Scanned AmigaBASIC books at archive.org] \ No newline at end of file diff --git a/Lang/AmigaBASIC/Animate-a-pendulum b/Lang/AmigaBASIC/Animate-a-pendulum new file mode 120000 index 0000000000..010529e570 --- /dev/null +++ b/Lang/AmigaBASIC/Animate-a-pendulum @@ -0,0 +1 @@ +../../Task/Animate-a-pendulum/AmigaBASIC \ No newline at end of file diff --git a/Lang/AmigaBASIC/Chaos-game b/Lang/AmigaBASIC/Chaos-game new file mode 120000 index 0000000000..06fb31b581 --- /dev/null +++ b/Lang/AmigaBASIC/Chaos-game @@ -0,0 +1 @@ +../../Task/Chaos-game/AmigaBASIC \ No newline at end of file diff --git a/Lang/Apple/00-LANG.txt b/Lang/Apple/00-LANG.txt new file mode 100644 index 0000000000..e4e452b143 --- /dev/null +++ b/Lang/Apple/00-LANG.txt @@ -0,0 +1,12 @@ +{{language|Apple +|exec=Compiled +|safety=safe +|checking=static +|strength=strong +|site=https://github.com/vmchale/apple}} + +{{language programming paradigm|functional}} + +The Apple Array System is a JIT-compiler for a statically typed functional language specialized on arrays. + +It is expression-oriented (it has no imports); it is meant to be called from other languages. \ No newline at end of file diff --git a/Lang/Apple/00-META.yaml b/Lang/Apple/00-META.yaml new file mode 100644 index 0000000000..fcdeec5d5c --- /dev/null +++ b/Lang/Apple/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Apple diff --git a/Lang/Apple/Averages-Arithmetic-mean b/Lang/Apple/Averages-Arithmetic-mean new file mode 120000 index 0000000000..b4236a6909 --- /dev/null +++ b/Lang/Apple/Averages-Arithmetic-mean @@ -0,0 +1 @@ +../../Task/Averages-Arithmetic-mean/Apple \ No newline at end of file diff --git a/Lang/Apple/Averages-Pythagorean-means b/Lang/Apple/Averages-Pythagorean-means new file mode 120000 index 0000000000..50c70e6c0b --- /dev/null +++ b/Lang/Apple/Averages-Pythagorean-means @@ -0,0 +1 @@ +../../Task/Averages-Pythagorean-means/Apple \ No newline at end of file diff --git a/Lang/Apple/Catamorphism b/Lang/Apple/Catamorphism new file mode 120000 index 0000000000..5d06cbf18d --- /dev/null +++ b/Lang/Apple/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/Apple \ No newline at end of file diff --git a/Lang/Apple/Dot-product b/Lang/Apple/Dot-product new file mode 120000 index 0000000000..084fc21920 --- /dev/null +++ b/Lang/Apple/Dot-product @@ -0,0 +1 @@ +../../Task/Dot-product/Apple \ No newline at end of file diff --git a/Lang/Apple/Factorial b/Lang/Apple/Factorial new file mode 120000 index 0000000000..8d659daa6f --- /dev/null +++ b/Lang/Apple/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Apple \ No newline at end of file diff --git a/Lang/Apple/Factors-of-an-integer b/Lang/Apple/Factors-of-an-integer new file mode 120000 index 0000000000..a965a5d4bd --- /dev/null +++ b/Lang/Apple/Factors-of-an-integer @@ -0,0 +1 @@ +../../Task/Factors-of-an-integer/Apple \ No newline at end of file diff --git a/Lang/Apple/Filter b/Lang/Apple/Filter new file mode 120000 index 0000000000..5dfbcaf92d --- /dev/null +++ b/Lang/Apple/Filter @@ -0,0 +1 @@ +../../Task/Filter/Apple \ No newline at end of file diff --git a/Lang/Apple/ISBN13-check-digit b/Lang/Apple/ISBN13-check-digit new file mode 120000 index 0000000000..b9d843e9fc --- /dev/null +++ b/Lang/Apple/ISBN13-check-digit @@ -0,0 +1 @@ +../../Task/ISBN13-check-digit/Apple \ No newline at end of file diff --git a/Lang/AppleScript/21-game b/Lang/AppleScript/21-game new file mode 120000 index 0000000000..8108f8c3fc --- /dev/null +++ b/Lang/AppleScript/21-game @@ -0,0 +1 @@ +../../Task/21-game/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Angle-difference-between-two-bearings b/Lang/AppleScript/Angle-difference-between-two-bearings new file mode 120000 index 0000000000..cb1c37c369 --- /dev/null +++ b/Lang/AppleScript/Angle-difference-between-two-bearings @@ -0,0 +1 @@ +../../Task/Angle-difference-between-two-bearings/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Associative-array-Creation b/Lang/AppleScript/Associative-array-Creation new file mode 120000 index 0000000000..8dba66b7c2 --- /dev/null +++ b/Lang/AppleScript/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Bin-given-limits b/Lang/AppleScript/Bin-given-limits new file mode 120000 index 0000000000..955dc82ffb --- /dev/null +++ b/Lang/AppleScript/Bin-given-limits @@ -0,0 +1 @@ +../../Task/Bin-given-limits/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Call-a-foreign-language-function b/Lang/AppleScript/Call-a-foreign-language-function new file mode 120000 index 0000000000..29365d0ac9 --- /dev/null +++ b/Lang/AppleScript/Call-a-foreign-language-function @@ -0,0 +1 @@ +../../Task/Call-a-foreign-language-function/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Catalan-numbers b/Lang/AppleScript/Catalan-numbers new file mode 120000 index 0000000000..0299ff88b4 --- /dev/null +++ b/Lang/AppleScript/Catalan-numbers @@ -0,0 +1 @@ +../../Task/Catalan-numbers/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Create-an-HTML-table b/Lang/AppleScript/Create-an-HTML-table new file mode 120000 index 0000000000..c5386274dd --- /dev/null +++ b/Lang/AppleScript/Create-an-HTML-table @@ -0,0 +1 @@ +../../Task/Create-an-HTML-table/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Formatted-numeric-output b/Lang/AppleScript/Formatted-numeric-output new file mode 120000 index 0000000000..de125c08d5 --- /dev/null +++ b/Lang/AppleScript/Formatted-numeric-output @@ -0,0 +1 @@ +../../Task/Formatted-numeric-output/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Hello-world-Newbie b/Lang/AppleScript/Hello-world-Newbie new file mode 120000 index 0000000000..251b56564d --- /dev/null +++ b/Lang/AppleScript/Hello-world-Newbie @@ -0,0 +1 @@ +../../Task/Hello-world-Newbie/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Horners-rule-for-polynomial-evaluation b/Lang/AppleScript/Horners-rule-for-polynomial-evaluation new file mode 120000 index 0000000000..b014f0231a --- /dev/null +++ b/Lang/AppleScript/Horners-rule-for-polynomial-evaluation @@ -0,0 +1 @@ +../../Task/Horners-rule-for-polynomial-evaluation/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Logical-operations b/Lang/AppleScript/Logical-operations new file mode 120000 index 0000000000..f381ea6d80 --- /dev/null +++ b/Lang/AppleScript/Logical-operations @@ -0,0 +1 @@ +../../Task/Logical-operations/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Loops-N-plus-one-half b/Lang/AppleScript/Loops-N-plus-one-half new file mode 120000 index 0000000000..c9ebbc6d6f --- /dev/null +++ b/Lang/AppleScript/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Loops-Wrong-ranges b/Lang/AppleScript/Loops-Wrong-ranges new file mode 120000 index 0000000000..30ead650a7 --- /dev/null +++ b/Lang/AppleScript/Loops-Wrong-ranges @@ -0,0 +1 @@ +../../Task/Loops-Wrong-ranges/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Magic-constant b/Lang/AppleScript/Magic-constant new file mode 120000 index 0000000000..103e56a841 --- /dev/null +++ b/Lang/AppleScript/Magic-constant @@ -0,0 +1 @@ +../../Task/Magic-constant/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Monte-Carlo-methods b/Lang/AppleScript/Monte-Carlo-methods new file mode 120000 index 0000000000..a3fd9d8a00 --- /dev/null +++ b/Lang/AppleScript/Monte-Carlo-methods @@ -0,0 +1 @@ +../../Task/Monte-Carlo-methods/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Naming-conventions b/Lang/AppleScript/Naming-conventions new file mode 120000 index 0000000000..bd6fd7dc7b --- /dev/null +++ b/Lang/AppleScript/Naming-conventions @@ -0,0 +1 @@ +../../Task/Naming-conventions/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Nim-game b/Lang/AppleScript/Nim-game new file mode 120000 index 0000000000..f67182813f --- /dev/null +++ b/Lang/AppleScript/Nim-game @@ -0,0 +1 @@ +../../Task/Nim-game/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Nth-root b/Lang/AppleScript/Nth-root new file mode 120000 index 0000000000..24be4fbbed --- /dev/null +++ b/Lang/AppleScript/Nth-root @@ -0,0 +1 @@ +../../Task/Nth-root/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Numerical-integration b/Lang/AppleScript/Numerical-integration new file mode 120000 index 0000000000..2cd0b2ae37 --- /dev/null +++ b/Lang/AppleScript/Numerical-integration @@ -0,0 +1 @@ +../../Task/Numerical-integration/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Penneys-game b/Lang/AppleScript/Penneys-game new file mode 120000 index 0000000000..8e49dba4f9 --- /dev/null +++ b/Lang/AppleScript/Penneys-game @@ -0,0 +1 @@ +../../Task/Penneys-game/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Pig-the-dice-game b/Lang/AppleScript/Pig-the-dice-game new file mode 120000 index 0000000000..db35af118f --- /dev/null +++ b/Lang/AppleScript/Pig-the-dice-game @@ -0,0 +1 @@ +../../Task/Pig-the-dice-game/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Program-name b/Lang/AppleScript/Program-name new file mode 120000 index 0000000000..08ec2ad4f8 --- /dev/null +++ b/Lang/AppleScript/Program-name @@ -0,0 +1 @@ +../../Task/Program-name/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Real-constants-and-functions b/Lang/AppleScript/Real-constants-and-functions new file mode 120000 index 0000000000..4a6c0f5db0 --- /dev/null +++ b/Lang/AppleScript/Real-constants-and-functions @@ -0,0 +1 @@ +../../Task/Real-constants-and-functions/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Return-multiple-values b/Lang/AppleScript/Return-multiple-values new file mode 120000 index 0000000000..f507a094fb --- /dev/null +++ b/Lang/AppleScript/Return-multiple-values @@ -0,0 +1 @@ +../../Task/Return-multiple-values/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Send-email b/Lang/AppleScript/Send-email new file mode 120000 index 0000000000..4ba0780be8 --- /dev/null +++ b/Lang/AppleScript/Send-email @@ -0,0 +1 @@ +../../Task/Send-email/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Sorting-algorithms-Stooge-sort b/Lang/AppleScript/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..56b9196ffc --- /dev/null +++ b/Lang/AppleScript/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Variable-declaration-reset b/Lang/AppleScript/Variable-declaration-reset new file mode 120000 index 0000000000..3059dd090c --- /dev/null +++ b/Lang/AppleScript/Variable-declaration-reset @@ -0,0 +1 @@ +../../Task/Variable-declaration-reset/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Write-entire-file b/Lang/AppleScript/Write-entire-file new file mode 120000 index 0000000000..5be6a2da0d --- /dev/null +++ b/Lang/AppleScript/Write-entire-file @@ -0,0 +1 @@ +../../Task/Write-entire-file/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Write-float-arrays-to-a-text-file b/Lang/AppleScript/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..d7524dd990 --- /dev/null +++ b/Lang/AppleScript/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/AppleScript \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/00-LANG.txt b/Lang/Applesoft-BASIC/00-LANG.txt index b47ab777d1..854387033b 100644 --- a/Lang/Applesoft-BASIC/00-LANG.txt +++ b/Lang/Applesoft-BASIC/00-LANG.txt @@ -7,4 +7,5 @@ * [[wp:Applesoft BASIC|Wikipedia: Applesoft BASIC]] * [http://www.landsnail.com/a2ref.htm Apple II Programmer's Reference] from ][ In a Mac, via [http://www.landsnail.com/ Landsnail.com] * [http://www.hoist-point.com/applesoft_basic_tutorial.htm AppleSoft BASIC tutorial for absolute beginners] +* [https://www.calormen.com/jsbasic/ Applesoft BASIC in Javascript] On-line interpreter * ''[[Tasks not implemented in Applesoft BASIC|Tasks not implemented in Applesoft BASIC]]'' \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Check-output-device-is-a-terminal b/Lang/Applesoft-BASIC/Check-output-device-is-a-terminal new file mode 120000 index 0000000000..e21d34eceb --- /dev/null +++ b/Lang/Applesoft-BASIC/Check-output-device-is-a-terminal @@ -0,0 +1 @@ +../../Task/Check-output-device-is-a-terminal/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Church-numerals b/Lang/Applesoft-BASIC/Church-numerals new file mode 120000 index 0000000000..a114e6a3f9 --- /dev/null +++ b/Lang/Applesoft-BASIC/Church-numerals @@ -0,0 +1 @@ +../../Task/Church-numerals/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Cistercian-numerals b/Lang/Applesoft-BASIC/Cistercian-numerals new file mode 120000 index 0000000000..2c5e6c52c1 --- /dev/null +++ b/Lang/Applesoft-BASIC/Cistercian-numerals @@ -0,0 +1 @@ +../../Task/Cistercian-numerals/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Compare-a-list-of-strings b/Lang/Applesoft-BASIC/Compare-a-list-of-strings new file mode 120000 index 0000000000..7eafe8f723 --- /dev/null +++ b/Lang/Applesoft-BASIC/Compare-a-list-of-strings @@ -0,0 +1 @@ +../../Task/Compare-a-list-of-strings/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Determine-if-a-string-is-collapsible b/Lang/Applesoft-BASIC/Determine-if-a-string-is-collapsible new file mode 120000 index 0000000000..02f9d8d440 --- /dev/null +++ b/Lang/Applesoft-BASIC/Determine-if-a-string-is-collapsible @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-collapsible/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Determine-if-a-string-is-squeezable b/Lang/Applesoft-BASIC/Determine-if-a-string-is-squeezable new file mode 120000 index 0000000000..b18de01c9a --- /dev/null +++ b/Lang/Applesoft-BASIC/Determine-if-a-string-is-squeezable @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-squeezable/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Display-a-linear-combination b/Lang/Applesoft-BASIC/Display-a-linear-combination new file mode 120000 index 0000000000..d72f6d3a78 --- /dev/null +++ b/Lang/Applesoft-BASIC/Display-a-linear-combination @@ -0,0 +1 @@ +../../Task/Display-a-linear-combination/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Dragon-curve b/Lang/Applesoft-BASIC/Dragon-curve new file mode 120000 index 0000000000..89a81bf5e7 --- /dev/null +++ b/Lang/Applesoft-BASIC/Dragon-curve @@ -0,0 +1 @@ +../../Task/Dragon-curve/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Enumerations b/Lang/Applesoft-BASIC/Enumerations new file mode 120000 index 0000000000..aa327448dc --- /dev/null +++ b/Lang/Applesoft-BASIC/Enumerations @@ -0,0 +1 @@ +../../Task/Enumerations/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Eulers-sum-of-powers-conjecture b/Lang/Applesoft-BASIC/Eulers-sum-of-powers-conjecture new file mode 120000 index 0000000000..814a94e748 --- /dev/null +++ b/Lang/Applesoft-BASIC/Eulers-sum-of-powers-conjecture @@ -0,0 +1 @@ +../../Task/Eulers-sum-of-powers-conjecture/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Fibonacci-sequence b/Lang/Applesoft-BASIC/Fibonacci-sequence new file mode 120000 index 0000000000..f95390f3d5 --- /dev/null +++ b/Lang/Applesoft-BASIC/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Formatted-numeric-output b/Lang/Applesoft-BASIC/Formatted-numeric-output new file mode 120000 index 0000000000..52c4ceb520 --- /dev/null +++ b/Lang/Applesoft-BASIC/Formatted-numeric-output @@ -0,0 +1 @@ +../../Task/Formatted-numeric-output/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Levenshtein-distance b/Lang/Applesoft-BASIC/Levenshtein-distance new file mode 120000 index 0000000000..890eb3e044 --- /dev/null +++ b/Lang/Applesoft-BASIC/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Modular-inverse b/Lang/Applesoft-BASIC/Modular-inverse new file mode 120000 index 0000000000..d8b60109c6 --- /dev/null +++ b/Lang/Applesoft-BASIC/Modular-inverse @@ -0,0 +1 @@ +../../Task/Modular-inverse/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Monty-Hall-problem b/Lang/Applesoft-BASIC/Monty-Hall-problem new file mode 120000 index 0000000000..6e0ff7bcb9 --- /dev/null +++ b/Lang/Applesoft-BASIC/Monty-Hall-problem @@ -0,0 +1 @@ +../../Task/Monty-Hall-problem/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Multi-dimensional-array b/Lang/Applesoft-BASIC/Multi-dimensional-array new file mode 120000 index 0000000000..c47a96b8ff --- /dev/null +++ b/Lang/Applesoft-BASIC/Multi-dimensional-array @@ -0,0 +1 @@ +../../Task/Multi-dimensional-array/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Rep-string b/Lang/Applesoft-BASIC/Rep-string new file mode 120000 index 0000000000..ba7d92f8da --- /dev/null +++ b/Lang/Applesoft-BASIC/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Repeat b/Lang/Applesoft-BASIC/Repeat new file mode 120000 index 0000000000..eb0c08d923 --- /dev/null +++ b/Lang/Applesoft-BASIC/Repeat @@ -0,0 +1 @@ +../../Task/Repeat/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Sorting-algorithms-Gnome-sort b/Lang/Applesoft-BASIC/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..4b7c42e62c --- /dev/null +++ b/Lang/Applesoft-BASIC/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Towers-of-Hanoi b/Lang/Applesoft-BASIC/Towers-of-Hanoi new file mode 120000 index 0000000000..7e7bc24b30 --- /dev/null +++ b/Lang/Applesoft-BASIC/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Aquarius-BASIC/00-LANG.txt b/Lang/Aquarius-BASIC/00-LANG.txt index 787837afb3..1314ae0882 100644 --- a/Lang/Aquarius-BASIC/00-LANG.txt +++ b/Lang/Aquarius-BASIC/00-LANG.txt @@ -2,4 +2,37 @@ |exec=interpreted |tags=basic,aquariusbasic }} -{{Implementation|BASIC}}'''Aquarius BASIC''' refers to the more or less stripped-down releases of Microsoft BASIC for the Mattel/Radofin Aquarius. The built-in ROM BASIC was seriously restricted since the system only included 4K of RAM and 8K of ROM by default. Minus the RAM used for video and system management, only about 1.7K or RAM were usable by default; the optionally available Extended Microsoft BASIC that came on ROM cartridge was somewhat more generous, and RAM expansion cartridges were available. \ No newline at end of file +{{Implementation|BASIC}}'''Aquarius BASIC''' refers to the more or less stripped-down releases of Microsoft BASIC for the Mattel/Radofin Aquarius, a home computer released in 1983. + +The built-in ROM BASIC was seriously restricted since the system only included 4K of RAM and 8K of ROM by default. Minus the RAM used for video and system management, only about 1.7K of RAM were usable by default; the optionally available Extended Microsoft BASIC that came on ROM cartridge was somewhat more generous, and RAM expansion cartridges were available. + +BASIC lines can be a maximum of 72 characters long. Only the first two characters of a variable name are significant, so e.g. ABC and ABBA will contain the same value: + +10 ABC=3 +20 ABBA=5 +30 PRINT ABC;ABBA +RUN + 5 5 + +The Aquarius features a text-mode screen of 40x25 characters with 16 colors. BASIC only uses 38x24 characters, i.e. the row at the top and the two outermost columns on each side are not accessible when editing, PRINTing, or LISTing. However, all 40x25 characters can be modified via POKEs from BASIC to screen memory. + +Screen character memory starts at 0x3000 (12288); color RAM (with high nibble = foreground color; low nibble = background color) starts at 0x3400 (12288 + 1024 = 13312). Border color can be set by POKEing to the top left character, e.g. POKE 13312,7 will turn the border color to white. BASIC programs start at 0x3901.[https://www.vdsteenoven.com/aquarius/malloc.html] + +BASIC can set and unset 80x72-resolution pixels on the Aquarius with the PSET and PRESET commands (each text character consists of 2x3 pixels). This program for instance draws an ellipsis: +10 PRINT CHR$(11); +20 PI=3.141593 : R=30 +30 FOR I=0 TO 360 +40 X=R*SIN(I*PI/180) +50 Y=R*COS(I*PI/180) +60 PSET(39+X,35+Y) +70 NEXT + +The Aquarius character set cannot be redefined. + +By default, the total space for string variables is only 50 bytes! This can be increased with CLEAR, e.g. CLEAR 200 will reserve 200 bytes for strings. You can check with PRINT FRE("a") how much unused string space is still available. + +Emulators of the Mattel Aquarius include MAME and [https://aquarius.je/aqualite/ AquaLite]. + +==See Also== +* [[wp:Mattel Aquarius|Mattel Aquarius]] at Wikipedia +* [https://archive.org/search?query=mattel+aquarius Aquarius manuals at the Internet Archive] \ No newline at end of file diff --git a/Lang/Aquarius-BASIC/Archimedean-spiral b/Lang/Aquarius-BASIC/Archimedean-spiral new file mode 120000 index 0000000000..a52a300e36 --- /dev/null +++ b/Lang/Aquarius-BASIC/Archimedean-spiral @@ -0,0 +1 @@ +../../Task/Archimedean-spiral/Aquarius-BASIC \ No newline at end of file diff --git a/Lang/Aquarius-BASIC/Colour-bars-Display b/Lang/Aquarius-BASIC/Colour-bars-Display new file mode 120000 index 0000000000..5113e0e205 --- /dev/null +++ b/Lang/Aquarius-BASIC/Colour-bars-Display @@ -0,0 +1 @@ +../../Task/Colour-bars-Display/Aquarius-BASIC \ No newline at end of file diff --git a/Lang/Aquarius-BASIC/Mandelbrot-set b/Lang/Aquarius-BASIC/Mandelbrot-set new file mode 120000 index 0000000000..e078ca10a9 --- /dev/null +++ b/Lang/Aquarius-BASIC/Mandelbrot-set @@ -0,0 +1 @@ +../../Task/Mandelbrot-set/Aquarius-BASIC \ No newline at end of file diff --git a/Lang/Aquarius-BASIC/Matrix-digital-rain b/Lang/Aquarius-BASIC/Matrix-digital-rain new file mode 120000 index 0000000000..227ab761a1 --- /dev/null +++ b/Lang/Aquarius-BASIC/Matrix-digital-rain @@ -0,0 +1 @@ +../../Task/Matrix-digital-rain/Aquarius-BASIC \ No newline at end of file diff --git a/Lang/Aquarius-BASIC/Musical-scale b/Lang/Aquarius-BASIC/Musical-scale new file mode 120000 index 0000000000..16fb0326f5 --- /dev/null +++ b/Lang/Aquarius-BASIC/Musical-scale @@ -0,0 +1 @@ +../../Task/Musical-scale/Aquarius-BASIC \ No newline at end of file diff --git a/Lang/Aquarius-BASIC/Terminal-control-Display-an-extended-character b/Lang/Aquarius-BASIC/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..908e3614b8 --- /dev/null +++ b/Lang/Aquarius-BASIC/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/Aquarius-BASIC \ No newline at end of file diff --git a/Lang/Aria/00-LANG.txt b/Lang/Aria/00-LANG.txt new file mode 100644 index 0000000000..f3d1668eba --- /dev/null +++ b/Lang/Aria/00-LANG.txt @@ -0,0 +1,15 @@ +{{language +|exec=interpreted +|site=https://egranata.github.io/aria/ +}} + +Aria is a modern, dynamic scripting language. It is meant to be a “sweet spot” language, easy to pick-up and enjoyable to use. + +It provides a familiar C-style syntax, with a feature set inspired by well-beloved languages such as Python and Rust. It comes with little ceremony and a focus on getting stuff done. + +Aria programs are written as .aria files and passed to the Aria virtual machine, which compiles them down to bytecode and executes them. + +The Aria interpreter is written in Rust, 2024 edition. + +==Todo== +[[Tasks_not_implemented_in_Aria]] \ No newline at end of file diff --git a/Lang/Aria/00-META.yaml b/Lang/Aria/00-META.yaml new file mode 100644 index 0000000000..35ebadd91a --- /dev/null +++ b/Lang/Aria/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Aria diff --git a/Lang/Aria/99-bottles-of-beer b/Lang/Aria/99-bottles-of-beer new file mode 120000 index 0000000000..c2f486227d --- /dev/null +++ b/Lang/Aria/99-bottles-of-beer @@ -0,0 +1 @@ +../../Task/99-bottles-of-beer/Aria \ No newline at end of file diff --git a/Lang/Aria/Hello-world-Text b/Lang/Aria/Hello-world-Text new file mode 120000 index 0000000000..bb8e1db7a7 --- /dev/null +++ b/Lang/Aria/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Aria \ No newline at end of file diff --git a/Lang/ArkScript/00-LANG.txt b/Lang/ArkScript/00-LANG.txt new file mode 100644 index 0000000000..11fc16bd5b --- /dev/null +++ b/Lang/ArkScript/00-LANG.txt @@ -0,0 +1,43 @@ +{{language|ArkScript +|exec=bytecode +|site=https://arkscript-lang.dev +|gc=no +|parampass=value +|strength=strong +|checking=dynamic +|tags=arkscript}} +ArkScript is a small, fast, functional and scripting language for C++ projects, inspired by [[Lua]], [[Lisp]], and [[Python]]. + +The language has been designed to be concise, with only 9 keywords, and two rules to parse it: +# the first node after an opening paren ( is a "function", the following nodes are arguments +# the only exception to the previous rule is when defining the argument list of a function + + +(let foo 5) +(let bar "hello world!") + +(let egg (fun (a b c) + (+ a (* b c)))) + +(print (egg 1 foo bar)) + + +The language is also +* small: the core fit under 8000 lines of code ; also small in terms of keywords (only 9) +* a scripting language: very easy to embed it in your projects. Registering your own functions in the language is made easy +* portable: a unique bytecode which can be run everywhere the virtual machine is +* a functional language: every parameter is passed by value, everything is immutable unless specified +* powerful: provides closures and explicit capture +* promoting functionalities before performances: expressiveness often brings more productivity, though performances aren't left behind +* a Lisp inspired language, with fewer parentheses: [...] is expanded to (list ...) and {} to (begin ...) +* extensible: supports C++ module to use it in the language, adding functionalities + + +===Implementation=== +The compiler and VM are implemented in [[C++]] 20. For more details, see [https://github.com/ArkScript-lang/Ark ArkScript GitHub]. + +===License=== +ArkScript is released under the Mozilla Public License 2.0. + +===Todo=== +[[Tasks not implemented in ArkScript]] \ No newline at end of file diff --git a/Lang/ArkScript/00-META.yaml b/Lang/ArkScript/00-META.yaml new file mode 100644 index 0000000000..0a989734f8 --- /dev/null +++ b/Lang/ArkScript/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:ArkScript diff --git a/Lang/ArkScript/100-doors b/Lang/ArkScript/100-doors new file mode 120000 index 0000000000..733c5ecdec --- /dev/null +++ b/Lang/ArkScript/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/99-bottles-of-beer b/Lang/ArkScript/99-bottles-of-beer new file mode 120000 index 0000000000..44d94215f1 --- /dev/null +++ b/Lang/ArkScript/99-bottles-of-beer @@ -0,0 +1 @@ +../../Task/99-bottles-of-beer/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/A+B b/Lang/ArkScript/A+B new file mode 120000 index 0000000000..482decfa5a --- /dev/null +++ b/Lang/ArkScript/A+B @@ -0,0 +1 @@ +../../Task/A+B/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Abbreviations-easy b/Lang/ArkScript/Abbreviations-easy new file mode 120000 index 0000000000..03457b23d1 --- /dev/null +++ b/Lang/ArkScript/Abbreviations-easy @@ -0,0 +1 @@ +../../Task/Abbreviations-easy/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Ackermann-function b/Lang/ArkScript/Ackermann-function new file mode 120000 index 0000000000..f1f525fde6 --- /dev/null +++ b/Lang/ArkScript/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Anonymous-recursion b/Lang/ArkScript/Anonymous-recursion new file mode 120000 index 0000000000..c2db291cc2 --- /dev/null +++ b/Lang/ArkScript/Anonymous-recursion @@ -0,0 +1 @@ +../../Task/Anonymous-recursion/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Apply-a-callback-to-an-array b/Lang/ArkScript/Apply-a-callback-to-an-array new file mode 120000 index 0000000000..da474aa4d7 --- /dev/null +++ b/Lang/ArkScript/Apply-a-callback-to-an-array @@ -0,0 +1 @@ +../../Task/Apply-a-callback-to-an-array/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Arithmetic-Complex b/Lang/ArkScript/Arithmetic-Complex new file mode 120000 index 0000000000..c21a1d5bf8 --- /dev/null +++ b/Lang/ArkScript/Arithmetic-Complex @@ -0,0 +1 @@ +../../Task/Arithmetic-Complex/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Arithmetic-Integer b/Lang/ArkScript/Arithmetic-Integer new file mode 120000 index 0000000000..0023796f90 --- /dev/null +++ b/Lang/ArkScript/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Array-concatenation b/Lang/ArkScript/Array-concatenation new file mode 120000 index 0000000000..250e35894f --- /dev/null +++ b/Lang/ArkScript/Array-concatenation @@ -0,0 +1 @@ +../../Task/Array-concatenation/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Array-length b/Lang/ArkScript/Array-length new file mode 120000 index 0000000000..f70d67437b --- /dev/null +++ b/Lang/ArkScript/Array-length @@ -0,0 +1 @@ +../../Task/Array-length/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Ascending-primes b/Lang/ArkScript/Ascending-primes new file mode 120000 index 0000000000..9fc34de6f6 --- /dev/null +++ b/Lang/ArkScript/Ascending-primes @@ -0,0 +1 @@ +../../Task/Ascending-primes/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Associative-array-Creation b/Lang/ArkScript/Associative-array-Creation new file mode 120000 index 0000000000..2a5f3a1e53 --- /dev/null +++ b/Lang/ArkScript/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Associative-array-Iteration b/Lang/ArkScript/Associative-array-Iteration new file mode 120000 index 0000000000..f11b39f9bb --- /dev/null +++ b/Lang/ArkScript/Associative-array-Iteration @@ -0,0 +1 @@ +../../Task/Associative-array-Iteration/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Associative-array-Merging b/Lang/ArkScript/Associative-array-Merging new file mode 120000 index 0000000000..03affb97ec --- /dev/null +++ b/Lang/ArkScript/Associative-array-Merging @@ -0,0 +1 @@ +../../Task/Associative-array-Merging/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Balanced-brackets b/Lang/ArkScript/Balanced-brackets new file mode 120000 index 0000000000..7380d4a234 --- /dev/null +++ b/Lang/ArkScript/Balanced-brackets @@ -0,0 +1 @@ +../../Task/Balanced-brackets/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Boolean-values b/Lang/ArkScript/Boolean-values new file mode 120000 index 0000000000..5efbe13431 --- /dev/null +++ b/Lang/ArkScript/Boolean-values @@ -0,0 +1 @@ +../../Task/Boolean-values/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Calculating-the-value-of-e b/Lang/ArkScript/Calculating-the-value-of-e new file mode 120000 index 0000000000..0a0116531f --- /dev/null +++ b/Lang/ArkScript/Calculating-the-value-of-e @@ -0,0 +1 @@ +../../Task/Calculating-the-value-of-e/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Call-a-function b/Lang/ArkScript/Call-a-function new file mode 120000 index 0000000000..4d2870d9cb --- /dev/null +++ b/Lang/ArkScript/Call-a-function @@ -0,0 +1 @@ +../../Task/Call-a-function/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Call-an-object-method b/Lang/ArkScript/Call-an-object-method new file mode 120000 index 0000000000..9b53aa0595 --- /dev/null +++ b/Lang/ArkScript/Call-an-object-method @@ -0,0 +1 @@ +../../Task/Call-an-object-method/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Catamorphism b/Lang/ArkScript/Catamorphism new file mode 120000 index 0000000000..f6210b0ec4 --- /dev/null +++ b/Lang/ArkScript/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Character-codes b/Lang/ArkScript/Character-codes new file mode 120000 index 0000000000..fcf79b3e9a --- /dev/null +++ b/Lang/ArkScript/Character-codes @@ -0,0 +1 @@ +../../Task/Character-codes/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Check-that-file-exists b/Lang/ArkScript/Check-that-file-exists new file mode 120000 index 0000000000..7e3651c090 --- /dev/null +++ b/Lang/ArkScript/Check-that-file-exists @@ -0,0 +1 @@ +../../Task/Check-that-file-exists/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Closures-Value-capture b/Lang/ArkScript/Closures-Value-capture new file mode 120000 index 0000000000..6b30a8d976 --- /dev/null +++ b/Lang/ArkScript/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Command-line-arguments b/Lang/ArkScript/Command-line-arguments new file mode 120000 index 0000000000..216020915c --- /dev/null +++ b/Lang/ArkScript/Command-line-arguments @@ -0,0 +1 @@ +../../Task/Command-line-arguments/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Comments b/Lang/ArkScript/Comments new file mode 120000 index 0000000000..360a2acb05 --- /dev/null +++ b/Lang/ArkScript/Comments @@ -0,0 +1 @@ +../../Task/Comments/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Compound-data-type b/Lang/ArkScript/Compound-data-type new file mode 120000 index 0000000000..a901531424 --- /dev/null +++ b/Lang/ArkScript/Compound-data-type @@ -0,0 +1 @@ +../../Task/Compound-data-type/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Concurrent-computing b/Lang/ArkScript/Concurrent-computing new file mode 120000 index 0000000000..13a2e9c874 --- /dev/null +++ b/Lang/ArkScript/Concurrent-computing @@ -0,0 +1 @@ +../../Task/Concurrent-computing/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Conditional-structures b/Lang/ArkScript/Conditional-structures new file mode 120000 index 0000000000..10a922af53 --- /dev/null +++ b/Lang/ArkScript/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Conways-Game-of-Life b/Lang/ArkScript/Conways-Game-of-Life new file mode 120000 index 0000000000..2d495d7699 --- /dev/null +++ b/Lang/ArkScript/Conways-Game-of-Life @@ -0,0 +1 @@ +../../Task/Conways-Game-of-Life/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Copy-a-string b/Lang/ArkScript/Copy-a-string new file mode 120000 index 0000000000..88194e46fb --- /dev/null +++ b/Lang/ArkScript/Copy-a-string @@ -0,0 +1 @@ +../../Task/Copy-a-string/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Count-occurrences-of-a-substring b/Lang/ArkScript/Count-occurrences-of-a-substring new file mode 120000 index 0000000000..da5c9db0d2 --- /dev/null +++ b/Lang/ArkScript/Count-occurrences-of-a-substring @@ -0,0 +1 @@ +../../Task/Count-occurrences-of-a-substring/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Currying b/Lang/ArkScript/Currying new file mode 120000 index 0000000000..68a7b93b42 --- /dev/null +++ b/Lang/ArkScript/Currying @@ -0,0 +1 @@ +../../Task/Currying/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Delete-a-file b/Lang/ArkScript/Delete-a-file new file mode 120000 index 0000000000..d6dbc3ecd5 --- /dev/null +++ b/Lang/ArkScript/Delete-a-file @@ -0,0 +1 @@ +../../Task/Delete-a-file/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Dot-product b/Lang/ArkScript/Dot-product new file mode 120000 index 0000000000..0ee74f8b5a --- /dev/null +++ b/Lang/ArkScript/Dot-product @@ -0,0 +1 @@ +../../Task/Dot-product/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Empty-directory b/Lang/ArkScript/Empty-directory new file mode 120000 index 0000000000..5ade8a3b8b --- /dev/null +++ b/Lang/ArkScript/Empty-directory @@ -0,0 +1 @@ +../../Task/Empty-directory/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Empty-program b/Lang/ArkScript/Empty-program new file mode 120000 index 0000000000..d33db3e33c --- /dev/null +++ b/Lang/ArkScript/Empty-program @@ -0,0 +1 @@ +../../Task/Empty-program/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Empty-string b/Lang/ArkScript/Empty-string new file mode 120000 index 0000000000..aa29f38546 --- /dev/null +++ b/Lang/ArkScript/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Enforced-immutability b/Lang/ArkScript/Enforced-immutability new file mode 120000 index 0000000000..c12069d86c --- /dev/null +++ b/Lang/ArkScript/Enforced-immutability @@ -0,0 +1 @@ +../../Task/Enforced-immutability/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Even-or-odd b/Lang/ArkScript/Even-or-odd new file mode 120000 index 0000000000..7aee966d84 --- /dev/null +++ b/Lang/ArkScript/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Execute-a-system-command b/Lang/ArkScript/Execute-a-system-command new file mode 120000 index 0000000000..ab936f59d4 --- /dev/null +++ b/Lang/ArkScript/Execute-a-system-command @@ -0,0 +1 @@ +../../Task/Execute-a-system-command/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Extend-your-language b/Lang/ArkScript/Extend-your-language new file mode 120000 index 0000000000..08fabf671d --- /dev/null +++ b/Lang/ArkScript/Extend-your-language @@ -0,0 +1 @@ +../../Task/Extend-your-language/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Factorial b/Lang/ArkScript/Factorial new file mode 120000 index 0000000000..270de2c6be --- /dev/null +++ b/Lang/ArkScript/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Fibonacci-sequence b/Lang/ArkScript/Fibonacci-sequence new file mode 120000 index 0000000000..46f2bbba10 --- /dev/null +++ b/Lang/ArkScript/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/File-input-output b/Lang/ArkScript/File-input-output new file mode 120000 index 0000000000..f2e1e6b1be --- /dev/null +++ b/Lang/ArkScript/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Filter b/Lang/ArkScript/Filter new file mode 120000 index 0000000000..51c30a5235 --- /dev/null +++ b/Lang/ArkScript/Filter @@ -0,0 +1 @@ +../../Task/Filter/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/FizzBuzz b/Lang/ArkScript/FizzBuzz new file mode 120000 index 0000000000..2464c5dcce --- /dev/null +++ b/Lang/ArkScript/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Flatten-a-list b/Lang/ArkScript/Flatten-a-list new file mode 120000 index 0000000000..8540eceb42 --- /dev/null +++ b/Lang/ArkScript/Flatten-a-list @@ -0,0 +1 @@ +../../Task/Flatten-a-list/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Function-definition b/Lang/ArkScript/Function-definition new file mode 120000 index 0000000000..e750f72eaf --- /dev/null +++ b/Lang/ArkScript/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Generate-lower-case-ASCII-alphabet b/Lang/ArkScript/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..9cae72db7e --- /dev/null +++ b/Lang/ArkScript/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Greatest-element-of-a-list b/Lang/ArkScript/Greatest-element-of-a-list new file mode 120000 index 0000000000..d8bc7be88e --- /dev/null +++ b/Lang/ArkScript/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Hello-world-Line-printer b/Lang/ArkScript/Hello-world-Line-printer new file mode 120000 index 0000000000..205cc44ef5 --- /dev/null +++ b/Lang/ArkScript/Hello-world-Line-printer @@ -0,0 +1 @@ +../../Task/Hello-world-Line-printer/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Hello-world-Newline-omission b/Lang/ArkScript/Hello-world-Newline-omission new file mode 120000 index 0000000000..e70990b485 --- /dev/null +++ b/Lang/ArkScript/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Hello-world-Text b/Lang/ArkScript/Hello-world-Text new file mode 120000 index 0000000000..efe7845aa7 --- /dev/null +++ b/Lang/ArkScript/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Include-a-file b/Lang/ArkScript/Include-a-file new file mode 120000 index 0000000000..ebb4a807d7 --- /dev/null +++ b/Lang/ArkScript/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Infinity b/Lang/ArkScript/Infinity new file mode 120000 index 0000000000..e2ef2bf985 --- /dev/null +++ b/Lang/ArkScript/Infinity @@ -0,0 +1 @@ +../../Task/Infinity/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Integer-comparison b/Lang/ArkScript/Integer-comparison new file mode 120000 index 0000000000..6396856212 --- /dev/null +++ b/Lang/ArkScript/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Integer-sequence b/Lang/ArkScript/Integer-sequence new file mode 120000 index 0000000000..386017d017 --- /dev/null +++ b/Lang/ArkScript/Integer-sequence @@ -0,0 +1 @@ +../../Task/Integer-sequence/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Letter-frequency b/Lang/ArkScript/Letter-frequency new file mode 120000 index 0000000000..5c5906f290 --- /dev/null +++ b/Lang/ArkScript/Letter-frequency @@ -0,0 +1 @@ +../../Task/Letter-frequency/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Literals-Floating-point b/Lang/ArkScript/Literals-Floating-point new file mode 120000 index 0000000000..5bc172fabe --- /dev/null +++ b/Lang/ArkScript/Literals-Floating-point @@ -0,0 +1 @@ +../../Task/Literals-Floating-point/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Literals-Integer b/Lang/ArkScript/Literals-Integer new file mode 120000 index 0000000000..b313b7f803 --- /dev/null +++ b/Lang/ArkScript/Literals-Integer @@ -0,0 +1 @@ +../../Task/Literals-Integer/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Literals-String b/Lang/ArkScript/Literals-String new file mode 120000 index 0000000000..ec507deee1 --- /dev/null +++ b/Lang/ArkScript/Literals-String @@ -0,0 +1 @@ +../../Task/Literals-String/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Logical-operations b/Lang/ArkScript/Logical-operations new file mode 120000 index 0000000000..aaefe48457 --- /dev/null +++ b/Lang/ArkScript/Logical-operations @@ -0,0 +1 @@ +../../Task/Logical-operations/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Loops-While b/Lang/ArkScript/Loops-While new file mode 120000 index 0000000000..5f0c886bc8 --- /dev/null +++ b/Lang/ArkScript/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Middle-three-digits b/Lang/ArkScript/Middle-three-digits new file mode 120000 index 0000000000..71c7fc7a98 --- /dev/null +++ b/Lang/ArkScript/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Munchausen-numbers b/Lang/ArkScript/Munchausen-numbers new file mode 120000 index 0000000000..c351968c20 --- /dev/null +++ b/Lang/ArkScript/Munchausen-numbers @@ -0,0 +1 @@ +../../Task/Munchausen-numbers/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/N-queens-problem b/Lang/ArkScript/N-queens-problem new file mode 120000 index 0000000000..e917f9e593 --- /dev/null +++ b/Lang/ArkScript/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Nested-function b/Lang/ArkScript/Nested-function new file mode 120000 index 0000000000..85ce060fae --- /dev/null +++ b/Lang/ArkScript/Nested-function @@ -0,0 +1 @@ +../../Task/Nested-function/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Null-object b/Lang/ArkScript/Null-object new file mode 120000 index 0000000000..a698a2ff71 --- /dev/null +++ b/Lang/ArkScript/Null-object @@ -0,0 +1 @@ +../../Task/Null-object/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Pangram-checker b/Lang/ArkScript/Pangram-checker new file mode 120000 index 0000000000..db321bb4cb --- /dev/null +++ b/Lang/ArkScript/Pangram-checker @@ -0,0 +1 @@ +../../Task/Pangram-checker/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Pick-random-element b/Lang/ArkScript/Pick-random-element new file mode 120000 index 0000000000..be2e5037b3 --- /dev/null +++ b/Lang/ArkScript/Pick-random-element @@ -0,0 +1 @@ +../../Task/Pick-random-element/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Program-name b/Lang/ArkScript/Program-name new file mode 120000 index 0000000000..c48917f3b8 --- /dev/null +++ b/Lang/ArkScript/Program-name @@ -0,0 +1 @@ +../../Task/Program-name/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Program-termination b/Lang/ArkScript/Program-termination new file mode 120000 index 0000000000..19d9d120f6 --- /dev/null +++ b/Lang/ArkScript/Program-termination @@ -0,0 +1 @@ +../../Task/Program-termination/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Read-entire-file b/Lang/ArkScript/Read-entire-file new file mode 120000 index 0000000000..e3a1c22530 --- /dev/null +++ b/Lang/ArkScript/Read-entire-file @@ -0,0 +1 @@ +../../Task/Read-entire-file/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Repeat-a-string b/Lang/ArkScript/Repeat-a-string new file mode 120000 index 0000000000..ed7c4e98d3 --- /dev/null +++ b/Lang/ArkScript/Repeat-a-string @@ -0,0 +1 @@ +../../Task/Repeat-a-string/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Reverse-a-string b/Lang/ArkScript/Reverse-a-string new file mode 120000 index 0000000000..a3a2ea0c27 --- /dev/null +++ b/Lang/ArkScript/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Semordnilap b/Lang/ArkScript/Semordnilap new file mode 120000 index 0000000000..25df93d2d3 --- /dev/null +++ b/Lang/ArkScript/Semordnilap @@ -0,0 +1 @@ +../../Task/Semordnilap/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Shell-one-liner b/Lang/ArkScript/Shell-one-liner new file mode 120000 index 0000000000..889b436427 --- /dev/null +++ b/Lang/ArkScript/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Short-circuit-evaluation b/Lang/ArkScript/Short-circuit-evaluation new file mode 120000 index 0000000000..dcd4ac26ee --- /dev/null +++ b/Lang/ArkScript/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Show-ASCII-table b/Lang/ArkScript/Show-ASCII-table new file mode 120000 index 0000000000..65d6365487 --- /dev/null +++ b/Lang/ArkScript/Show-ASCII-table @@ -0,0 +1 @@ +../../Task/Show-ASCII-table/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Sleep b/Lang/ArkScript/Sleep new file mode 120000 index 0000000000..cd07cddf41 --- /dev/null +++ b/Lang/ArkScript/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Sorting-algorithms-Quicksort b/Lang/ArkScript/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..003f3fb633 --- /dev/null +++ b/Lang/ArkScript/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Stack b/Lang/ArkScript/Stack new file mode 120000 index 0000000000..f0aa9a05ea --- /dev/null +++ b/Lang/ArkScript/Stack @@ -0,0 +1 @@ +../../Task/Stack/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/String-append b/Lang/ArkScript/String-append new file mode 120000 index 0000000000..ade5a20d23 --- /dev/null +++ b/Lang/ArkScript/String-append @@ -0,0 +1 @@ +../../Task/String-append/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/String-case b/Lang/ArkScript/String-case new file mode 120000 index 0000000000..25e27a4618 --- /dev/null +++ b/Lang/ArkScript/String-case @@ -0,0 +1 @@ +../../Task/String-case/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/String-concatenation b/Lang/ArkScript/String-concatenation new file mode 120000 index 0000000000..999b5605f7 --- /dev/null +++ b/Lang/ArkScript/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/String-interpolation-included- b/Lang/ArkScript/String-interpolation-included- new file mode 120000 index 0000000000..33fa86b906 --- /dev/null +++ b/Lang/ArkScript/String-interpolation-included- @@ -0,0 +1 @@ +../../Task/String-interpolation-included-/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/String-length b/Lang/ArkScript/String-length new file mode 120000 index 0000000000..df129dcc11 --- /dev/null +++ b/Lang/ArkScript/String-length @@ -0,0 +1 @@ +../../Task/String-length/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/String-matching b/Lang/ArkScript/String-matching new file mode 120000 index 0000000000..7558bd042a --- /dev/null +++ b/Lang/ArkScript/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/String-prepend b/Lang/ArkScript/String-prepend new file mode 120000 index 0000000000..083b99bbf0 --- /dev/null +++ b/Lang/ArkScript/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Sum-and-product-of-an-array b/Lang/ArkScript/Sum-and-product-of-an-array new file mode 120000 index 0000000000..4c22ecff5f --- /dev/null +++ b/Lang/ArkScript/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Sum-digits-of-an-integer b/Lang/ArkScript/Sum-digits-of-an-integer new file mode 120000 index 0000000000..29e7afd56c --- /dev/null +++ b/Lang/ArkScript/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Sum-of-a-series b/Lang/ArkScript/Sum-of-a-series new file mode 120000 index 0000000000..f009df3580 --- /dev/null +++ b/Lang/ArkScript/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Sum-of-squares b/Lang/ArkScript/Sum-of-squares new file mode 120000 index 0000000000..85176ac4bb --- /dev/null +++ b/Lang/ArkScript/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Time-a-function b/Lang/ArkScript/Time-a-function new file mode 120000 index 0000000000..e2c1f55e22 --- /dev/null +++ b/Lang/ArkScript/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/User-input-Text b/Lang/ArkScript/User-input-Text new file mode 120000 index 0000000000..f0daf24108 --- /dev/null +++ b/Lang/ArkScript/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Variables b/Lang/ArkScript/Variables new file mode 120000 index 0000000000..f47b9d33ee --- /dev/null +++ b/Lang/ArkScript/Variables @@ -0,0 +1 @@ +../../Task/Variables/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Write-entire-file b/Lang/ArkScript/Write-entire-file new file mode 120000 index 0000000000..978c98fba7 --- /dev/null +++ b/Lang/ArkScript/Write-entire-file @@ -0,0 +1 @@ +../../Task/Write-entire-file/ArkScript \ No newline at end of file diff --git a/Lang/Arturo/00-LANG.txt b/Lang/Arturo/00-LANG.txt index e01d1ab72c..7424af10da 100644 --- a/Lang/Arturo/00-LANG.txt +++ b/Lang/Arturo/00-LANG.txt @@ -16,8 +16,8 @@ The language has been designed following some very simple and straightforward pr factorial: function [n][ - if? n > 0 -> n * factorial n-1 - else -> 1 + switch n > 0 -> n * factorial n-1 + -> 1 ] loop 1..19 [x]-> diff --git a/Lang/Arturo/Abstract-type b/Lang/Arturo/Abstract-type new file mode 120000 index 0000000000..d0cab7a251 --- /dev/null +++ b/Lang/Arturo/Abstract-type @@ -0,0 +1 @@ +../../Task/Abstract-type/Arturo \ No newline at end of file diff --git a/Lang/Arturo/Achilles-numbers b/Lang/Arturo/Achilles-numbers new file mode 120000 index 0000000000..14eecef378 --- /dev/null +++ b/Lang/Arturo/Achilles-numbers @@ -0,0 +1 @@ +../../Task/Achilles-numbers/Arturo \ No newline at end of file diff --git a/Lang/Arturo/Arithmetic-derivative b/Lang/Arturo/Arithmetic-derivative new file mode 120000 index 0000000000..d1b6630a6c --- /dev/null +++ b/Lang/Arturo/Arithmetic-derivative @@ -0,0 +1 @@ +../../Task/Arithmetic-derivative/Arturo \ No newline at end of file diff --git a/Lang/Arturo/Bioinformatics-base-count b/Lang/Arturo/Bioinformatics-base-count deleted file mode 120000 index 6562f48c25..0000000000 --- a/Lang/Arturo/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Arturo \ No newline at end of file diff --git a/Lang/Arturo/Bitmap-Bresenhams-line-algorithm b/Lang/Arturo/Bitmap-Bresenhams-line-algorithm new file mode 120000 index 0000000000..903f7d1b02 --- /dev/null +++ b/Lang/Arturo/Bitmap-Bresenhams-line-algorithm @@ -0,0 +1 @@ +../../Task/Bitmap-Bresenhams-line-algorithm/Arturo \ No newline at end of file diff --git a/Lang/Arturo/Blum-integer b/Lang/Arturo/Blum-integer new file mode 120000 index 0000000000..025a5231e2 --- /dev/null +++ b/Lang/Arturo/Blum-integer @@ -0,0 +1 @@ +../../Task/Blum-integer/Arturo \ No newline at end of file diff --git a/Lang/Arturo/Dice-game-probabilities b/Lang/Arturo/Dice-game-probabilities new file mode 120000 index 0000000000..963933dbf3 --- /dev/null +++ b/Lang/Arturo/Dice-game-probabilities @@ -0,0 +1 @@ +../../Task/Dice-game-probabilities/Arturo \ No newline at end of file diff --git a/Lang/Arturo/EKG-sequence-convergence b/Lang/Arturo/EKG-sequence-convergence new file mode 120000 index 0000000000..0753ff65e6 --- /dev/null +++ b/Lang/Arturo/EKG-sequence-convergence @@ -0,0 +1 @@ +../../Task/EKG-sequence-convergence/Arturo \ No newline at end of file diff --git a/Lang/Arturo/Element-wise-operations b/Lang/Arturo/Element-wise-operations new file mode 120000 index 0000000000..da54867937 --- /dev/null +++ b/Lang/Arturo/Element-wise-operations @@ -0,0 +1 @@ +../../Task/Element-wise-operations/Arturo \ No newline at end of file diff --git a/Lang/Arturo/Entropy-Narcissist b/Lang/Arturo/Entropy-Narcissist new file mode 120000 index 0000000000..a5a91d666a --- /dev/null +++ b/Lang/Arturo/Entropy-Narcissist @@ -0,0 +1 @@ +../../Task/Entropy-Narcissist/Arturo \ No newline at end of file diff --git a/Lang/Arturo/Inheritance-Single b/Lang/Arturo/Inheritance-Single new file mode 120000 index 0000000000..9ea196311d --- /dev/null +++ b/Lang/Arturo/Inheritance-Single @@ -0,0 +1 @@ +../../Task/Inheritance-Single/Arturo \ No newline at end of file diff --git a/Lang/Arturo/Magnanimous-numbers b/Lang/Arturo/Magnanimous-numbers new file mode 120000 index 0000000000..c058d4081f --- /dev/null +++ b/Lang/Arturo/Magnanimous-numbers @@ -0,0 +1 @@ +../../Task/Magnanimous-numbers/Arturo \ No newline at end of file diff --git a/Lang/Arturo/Meissel-Mertens-constant b/Lang/Arturo/Meissel-Mertens-constant deleted file mode 120000 index a360b321e1..0000000000 --- a/Lang/Arturo/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/Arturo \ No newline at end of file diff --git a/Lang/Arturo/Munching-squares b/Lang/Arturo/Munching-squares new file mode 120000 index 0000000000..3d1757b680 --- /dev/null +++ b/Lang/Arturo/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/Arturo \ No newline at end of file diff --git a/Lang/Arturo/Number-names b/Lang/Arturo/Number-names new file mode 120000 index 0000000000..0265b7a150 --- /dev/null +++ b/Lang/Arturo/Number-names @@ -0,0 +1 @@ +../../Task/Number-names/Arturo \ No newline at end of file diff --git a/Lang/Arturo/Palindromic-gapful-numbers b/Lang/Arturo/Palindromic-gapful-numbers new file mode 120000 index 0000000000..bb7c640247 --- /dev/null +++ b/Lang/Arturo/Palindromic-gapful-numbers @@ -0,0 +1 @@ +../../Task/Palindromic-gapful-numbers/Arturo \ No newline at end of file diff --git a/Lang/Arturo/Quaternion-type b/Lang/Arturo/Quaternion-type deleted file mode 120000 index b96cba3183..0000000000 --- a/Lang/Arturo/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Arturo \ No newline at end of file diff --git a/Lang/Arturo/Radical-of-an-integer b/Lang/Arturo/Radical-of-an-integer new file mode 120000 index 0000000000..0b80f4a924 --- /dev/null +++ b/Lang/Arturo/Radical-of-an-integer @@ -0,0 +1 @@ +../../Task/Radical-of-an-integer/Arturo \ No newline at end of file diff --git a/Lang/Arturo/Reflection-List-methods b/Lang/Arturo/Reflection-List-methods new file mode 120000 index 0000000000..b2c29c2e7a --- /dev/null +++ b/Lang/Arturo/Reflection-List-methods @@ -0,0 +1 @@ +../../Task/Reflection-List-methods/Arturo \ No newline at end of file diff --git a/Lang/Arturo/Rosetta-Code-Find-unimplemented-tasks b/Lang/Arturo/Rosetta-Code-Find-unimplemented-tasks new file mode 120000 index 0000000000..6c58da52bd --- /dev/null +++ b/Lang/Arturo/Rosetta-Code-Find-unimplemented-tasks @@ -0,0 +1 @@ +../../Task/Rosetta-Code-Find-unimplemented-tasks/Arturo \ No newline at end of file diff --git a/Lang/Arturo/Sorting-Algorithms-Circle-Sort b/Lang/Arturo/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index fc98e0e878..0000000000 --- a/Lang/Arturo/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Arturo \ No newline at end of file diff --git a/Lang/Arturo/Spelling-of-ordinal-numbers b/Lang/Arturo/Spelling-of-ordinal-numbers new file mode 120000 index 0000000000..0d47ac2434 --- /dev/null +++ b/Lang/Arturo/Spelling-of-ordinal-numbers @@ -0,0 +1 @@ +../../Task/Spelling-of-ordinal-numbers/Arturo \ No newline at end of file diff --git a/Lang/Arturo/Super-d-numbers b/Lang/Arturo/Super-d-numbers new file mode 120000 index 0000000000..9c8b511c5d --- /dev/null +++ b/Lang/Arturo/Super-d-numbers @@ -0,0 +1 @@ +../../Task/Super-d-numbers/Arturo \ No newline at end of file diff --git a/Lang/Arturo/Taxicab-numbers b/Lang/Arturo/Taxicab-numbers new file mode 120000 index 0000000000..9c84413e59 --- /dev/null +++ b/Lang/Arturo/Taxicab-numbers @@ -0,0 +1 @@ +../../Task/Taxicab-numbers/Arturo \ No newline at end of file diff --git a/Lang/Arturo/Weird-numbers b/Lang/Arturo/Weird-numbers new file mode 120000 index 0000000000..2f062bea69 --- /dev/null +++ b/Lang/Arturo/Weird-numbers @@ -0,0 +1 @@ +../../Task/Weird-numbers/Arturo \ No newline at end of file diff --git a/Lang/Arturo/Zumkeller-numbers b/Lang/Arturo/Zumkeller-numbers new file mode 120000 index 0000000000..b956d7f399 --- /dev/null +++ b/Lang/Arturo/Zumkeller-numbers @@ -0,0 +1 @@ +../../Task/Zumkeller-numbers/Arturo \ No newline at end of file diff --git a/Lang/AsciiDots/Quine b/Lang/AsciiDots/Quine new file mode 120000 index 0000000000..c2090631eb --- /dev/null +++ b/Lang/AsciiDots/Quine @@ -0,0 +1 @@ +../../Task/Quine/AsciiDots \ No newline at end of file diff --git a/Lang/AsciiDots/Write-language-name-in-3D-ASCII b/Lang/AsciiDots/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..81b3e17bd1 --- /dev/null +++ b/Lang/AsciiDots/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/AsciiDots \ No newline at end of file diff --git a/Lang/Asymptote/Array-length b/Lang/Asymptote/Array-length new file mode 120000 index 0000000000..017bab2099 --- /dev/null +++ b/Lang/Asymptote/Array-length @@ -0,0 +1 @@ +../../Task/Array-length/Asymptote \ No newline at end of file diff --git a/Lang/Asymptote/Day-of-the-week b/Lang/Asymptote/Day-of-the-week new file mode 120000 index 0000000000..f31fd61474 --- /dev/null +++ b/Lang/Asymptote/Day-of-the-week @@ -0,0 +1 @@ +../../Task/Day-of-the-week/Asymptote \ No newline at end of file diff --git a/Lang/Asymptote/Determine-sentence-type b/Lang/Asymptote/Determine-sentence-type new file mode 120000 index 0000000000..250fb5d120 --- /dev/null +++ b/Lang/Asymptote/Determine-sentence-type @@ -0,0 +1 @@ +../../Task/Determine-sentence-type/Asymptote \ No newline at end of file diff --git a/Lang/Asymptote/Diversity-prediction-theorem b/Lang/Asymptote/Diversity-prediction-theorem new file mode 120000 index 0000000000..4b9f736bd3 --- /dev/null +++ b/Lang/Asymptote/Diversity-prediction-theorem @@ -0,0 +1 @@ +../../Task/Diversity-prediction-theorem/Asymptote \ No newline at end of file diff --git a/Lang/Asymptote/Empty-program b/Lang/Asymptote/Empty-program deleted file mode 120000 index 5636b8fc49..0000000000 --- a/Lang/Asymptote/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Asymptote \ No newline at end of file diff --git a/Lang/Asymptote/Evaluate-binomial-coefficients b/Lang/Asymptote/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..8408c303d7 --- /dev/null +++ b/Lang/Asymptote/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/Asymptote \ No newline at end of file diff --git a/Lang/Asymptote/Hello-world-Newline-omission b/Lang/Asymptote/Hello-world-Newline-omission new file mode 120000 index 0000000000..1f04f08bd4 --- /dev/null +++ b/Lang/Asymptote/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/Asymptote \ No newline at end of file diff --git a/Lang/Asymptote/Jensens-Device b/Lang/Asymptote/Jensens-Device new file mode 120000 index 0000000000..621c474cd7 --- /dev/null +++ b/Lang/Asymptote/Jensens-Device @@ -0,0 +1 @@ +../../Task/Jensens-Device/Asymptote \ No newline at end of file diff --git a/Lang/Asymptote/Leonardo-numbers b/Lang/Asymptote/Leonardo-numbers new file mode 120000 index 0000000000..53f9861f22 --- /dev/null +++ b/Lang/Asymptote/Leonardo-numbers @@ -0,0 +1 @@ +../../Task/Leonardo-numbers/Asymptote \ No newline at end of file diff --git a/Lang/Asymptote/Loops-Infinite b/Lang/Asymptote/Loops-Infinite new file mode 120000 index 0000000000..0aa1840fd7 --- /dev/null +++ b/Lang/Asymptote/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/Asymptote \ No newline at end of file diff --git a/Lang/Asymptote/Map-range b/Lang/Asymptote/Map-range new file mode 120000 index 0000000000..249d69a043 --- /dev/null +++ b/Lang/Asymptote/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/Asymptote \ No newline at end of file diff --git a/Lang/Asymptote/Pancake-numbers b/Lang/Asymptote/Pancake-numbers new file mode 120000 index 0000000000..de9f5cf18c --- /dev/null +++ b/Lang/Asymptote/Pancake-numbers @@ -0,0 +1 @@ +../../Task/Pancake-numbers/Asymptote \ No newline at end of file diff --git a/Lang/Asymptote/Primality-by-trial-division b/Lang/Asymptote/Primality-by-trial-division new file mode 120000 index 0000000000..0cfaa74cf3 --- /dev/null +++ b/Lang/Asymptote/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/Asymptote \ No newline at end of file diff --git a/Lang/Asymptote/Repeat b/Lang/Asymptote/Repeat new file mode 120000 index 0000000000..03b0740c45 --- /dev/null +++ b/Lang/Asymptote/Repeat @@ -0,0 +1 @@ +../../Task/Repeat/Asymptote \ No newline at end of file diff --git a/Lang/Asymptote/Sudan-function b/Lang/Asymptote/Sudan-function new file mode 120000 index 0000000000..97eca50473 --- /dev/null +++ b/Lang/Asymptote/Sudan-function @@ -0,0 +1 @@ +../../Task/Sudan-function/Asymptote \ No newline at end of file diff --git a/Lang/Asymptote/Towers-of-Hanoi b/Lang/Asymptote/Towers-of-Hanoi new file mode 120000 index 0000000000..62a6e4d923 --- /dev/null +++ b/Lang/Asymptote/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Asymptote \ No newline at end of file diff --git a/Lang/Asymptote/Twos-complement b/Lang/Asymptote/Twos-complement new file mode 120000 index 0000000000..a487252d4a --- /dev/null +++ b/Lang/Asymptote/Twos-complement @@ -0,0 +1 @@ +../../Task/Twos-complement/Asymptote \ No newline at end of file diff --git a/Lang/Atari-BASIC/00-LANG.txt b/Lang/Atari-BASIC/00-LANG.txt index 233d214413..f0ee8029ec 100644 --- a/Lang/Atari-BASIC/00-LANG.txt +++ b/Lang/Atari-BASIC/00-LANG.txt @@ -3,6 +3,23 @@ |tags=basic,ataribasic }} {{Implementation|BASIC}} -'''Atari BASIC''' refers to the BASIC that shipped with Atari 8-bit micros. +'''Atari BASIC''' refers to the BASIC that shipped with Atari 8-bit micros. Revision A was released on cartridge for early models like the Atari 400 and 800 (1979), while revision B was included in ROM on later models such as the 800XL (1983). (Revision A is considered superior because revision B has more bugs!) Revision C was released on cartridge to address the bugs introduced in revision B. It was also in ROM on later 800XL computers and the XE range. -See Wikipedia: https://en.wikipedia.org/wiki/Atari_BASIC \ No newline at end of file +Emulators for Atari 8-bit computers include: +*[https://atari800.github.io/ Atari800] (Windows, Mac, Linux, etc.) +*[https://www.virtualdub.org/altirra.html Altirra] (Windows) + +Downloading the original Atari ROMs is not necessary for Atari800 or Altirra because they include the open source Altirra ROMs, which also feature Altirra BASIC, a fully compatible replacement for Atari BASIC. Altirra BASIC and OS are also better optimized than the original Atari ROMs; especially FOR loops and floating point functions are much quicker. + +To start Atari800 in BASIC mode, run it as atari800 -basic. Some important keys in Atari800 are F1=Settings, F5=Reset, F7=Break, F9=Quit, F10=Screenshot; see [https://github.com/atari800/atari800/blob/master/DOC/USAGE DOC/USAGE] for more. Lowercase characters in strings can be entered by first pressing Caps Lock in Atari800. + +In Atari800, folders on the host computer can be mounted in ''Emulator Configuration ⇨ Host Device Settings'', so then you can e.g. use LOAD "H1:MYPROG.BAS" to load a program from local disk. By default, folders are mounted read-only. + +BASIC programs in tokenized form are loaded and saved with LOAD and SAVE; in ASCII/ATASCII format you load them with ENTER and save them with LIST, e.g. LIST “H1:PROGRAM.LST”. + +After 9 minutes of inactivity, a screen saver (called attract mode by Atari) will activate and cycle colors. This can be stopped by an occasional POKE 77,0 to reset the timer. + +Like in Palo Alto Tiny BASIC, commands can be abbreviated by their first (unique) letters and a period, e.g. L. for LIST or GR. for GRAPHICS. + +==See Also== +*[https://en.wikipedia.org/wiki/Atari_BASIC Atari BASIC] in Wikipedia \ No newline at end of file diff --git a/Lang/Atari-BASIC/Archimedean-spiral b/Lang/Atari-BASIC/Archimedean-spiral new file mode 120000 index 0000000000..3e75563330 --- /dev/null +++ b/Lang/Atari-BASIC/Archimedean-spiral @@ -0,0 +1 @@ +../../Task/Archimedean-spiral/Atari-BASIC \ No newline at end of file diff --git a/Lang/Atari-BASIC/Chaos-game b/Lang/Atari-BASIC/Chaos-game new file mode 120000 index 0000000000..f88e0f8ada --- /dev/null +++ b/Lang/Atari-BASIC/Chaos-game @@ -0,0 +1 @@ +../../Task/Chaos-game/Atari-BASIC \ No newline at end of file diff --git a/Lang/Atari-BASIC/Color-of-a-screen-pixel b/Lang/Atari-BASIC/Color-of-a-screen-pixel new file mode 120000 index 0000000000..b097621245 --- /dev/null +++ b/Lang/Atari-BASIC/Color-of-a-screen-pixel @@ -0,0 +1 @@ +../../Task/Color-of-a-screen-pixel/Atari-BASIC \ No newline at end of file diff --git a/Lang/Atari-BASIC/Colour-bars-Display b/Lang/Atari-BASIC/Colour-bars-Display new file mode 120000 index 0000000000..03db8dce96 --- /dev/null +++ b/Lang/Atari-BASIC/Colour-bars-Display @@ -0,0 +1 @@ +../../Task/Colour-bars-Display/Atari-BASIC \ No newline at end of file diff --git a/Lang/Atari-BASIC/Draw-a-clock b/Lang/Atari-BASIC/Draw-a-clock new file mode 120000 index 0000000000..f8dd467da4 --- /dev/null +++ b/Lang/Atari-BASIC/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/Atari-BASIC \ No newline at end of file diff --git a/Lang/Atari-BASIC/Mandelbrot-set b/Lang/Atari-BASIC/Mandelbrot-set new file mode 120000 index 0000000000..45e66ccff0 --- /dev/null +++ b/Lang/Atari-BASIC/Mandelbrot-set @@ -0,0 +1 @@ +../../Task/Mandelbrot-set/Atari-BASIC \ No newline at end of file diff --git a/Lang/Atari-BASIC/Musical-scale b/Lang/Atari-BASIC/Musical-scale new file mode 120000 index 0000000000..b870e25059 --- /dev/null +++ b/Lang/Atari-BASIC/Musical-scale @@ -0,0 +1 @@ +../../Task/Musical-scale/Atari-BASIC \ No newline at end of file diff --git a/Lang/Atari-BASIC/Pi b/Lang/Atari-BASIC/Pi new file mode 120000 index 0000000000..b081cc7024 --- /dev/null +++ b/Lang/Atari-BASIC/Pi @@ -0,0 +1 @@ +../../Task/Pi/Atari-BASIC \ No newline at end of file diff --git a/Lang/Atari-BASIC/Random-number-generator-device- b/Lang/Atari-BASIC/Random-number-generator-device- new file mode 120000 index 0000000000..bc35b665ee --- /dev/null +++ b/Lang/Atari-BASIC/Random-number-generator-device- @@ -0,0 +1 @@ +../../Task/Random-number-generator-device-/Atari-BASIC \ No newline at end of file diff --git a/Lang/Atari-BASIC/Reverse-a-string b/Lang/Atari-BASIC/Reverse-a-string new file mode 120000 index 0000000000..c2ff7e214b --- /dev/null +++ b/Lang/Atari-BASIC/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/Atari-BASIC \ No newline at end of file diff --git a/Lang/Atari-BASIC/System-time b/Lang/Atari-BASIC/System-time new file mode 120000 index 0000000000..c4df1e6a39 --- /dev/null +++ b/Lang/Atari-BASIC/System-time @@ -0,0 +1 @@ +../../Task/System-time/Atari-BASIC \ No newline at end of file diff --git a/Lang/Atari-BASIC/Terminal-control-Hiding-the-cursor b/Lang/Atari-BASIC/Terminal-control-Hiding-the-cursor new file mode 120000 index 0000000000..78972a34b6 --- /dev/null +++ b/Lang/Atari-BASIC/Terminal-control-Hiding-the-cursor @@ -0,0 +1 @@ +../../Task/Terminal-control-Hiding-the-cursor/Atari-BASIC \ No newline at end of file diff --git a/Lang/Atari-BASIC/Terminal-control-Inverse-video b/Lang/Atari-BASIC/Terminal-control-Inverse-video new file mode 120000 index 0000000000..8c57f75946 --- /dev/null +++ b/Lang/Atari-BASIC/Terminal-control-Inverse-video @@ -0,0 +1 @@ +../../Task/Terminal-control-Inverse-video/Atari-BASIC \ No newline at end of file diff --git a/Lang/Atari-BASIC/Terminal-control-Positional-read b/Lang/Atari-BASIC/Terminal-control-Positional-read new file mode 120000 index 0000000000..a0575b2278 --- /dev/null +++ b/Lang/Atari-BASIC/Terminal-control-Positional-read @@ -0,0 +1 @@ +../../Task/Terminal-control-Positional-read/Atari-BASIC \ No newline at end of file diff --git a/Lang/Atari-BASIC/Terminal-control-Ringing-the-terminal-bell b/Lang/Atari-BASIC/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..3666cabb9e --- /dev/null +++ b/Lang/Atari-BASIC/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/Atari-BASIC \ No newline at end of file diff --git a/Lang/AutoHotkey/Miller-Rabin-primality-test b/Lang/AutoHotkey/Miller-Rabin-primality-test deleted file mode 120000 index 518dd6b131..0000000000 --- a/Lang/AutoHotkey/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Quaternion-type b/Lang/AutoHotkey/Quaternion-type deleted file mode 120000 index 00a1a5a068..0000000000 --- a/Lang/AutoHotkey/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Sorting-Algorithms-Circle-Sort b/Lang/AutoHotkey/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 975740b1fa..0000000000 --- a/Lang/AutoHotkey/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoLISP/100-doors b/Lang/AutoLISP/100-doors new file mode 120000 index 0000000000..4d97a8a5d6 --- /dev/null +++ b/Lang/AutoLISP/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/AutoLISP \ No newline at end of file diff --git a/Lang/AutoLISP/Babbage-problem b/Lang/AutoLISP/Babbage-problem new file mode 120000 index 0000000000..0ae3941c82 --- /dev/null +++ b/Lang/AutoLISP/Babbage-problem @@ -0,0 +1 @@ +../../Task/Babbage-problem/AutoLISP \ No newline at end of file diff --git a/Lang/AutoLISP/Balanced-brackets b/Lang/AutoLISP/Balanced-brackets new file mode 120000 index 0000000000..b752cfc1d6 --- /dev/null +++ b/Lang/AutoLISP/Balanced-brackets @@ -0,0 +1 @@ +../../Task/Balanced-brackets/AutoLISP \ No newline at end of file diff --git a/Lang/AutoLISP/Entropy b/Lang/AutoLISP/Entropy new file mode 120000 index 0000000000..bc1dec235f --- /dev/null +++ b/Lang/AutoLISP/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/AutoLISP \ No newline at end of file diff --git a/Lang/AutoLISP/Entropy-Narcissist b/Lang/AutoLISP/Entropy-Narcissist new file mode 120000 index 0000000000..0a143c87ce --- /dev/null +++ b/Lang/AutoLISP/Entropy-Narcissist @@ -0,0 +1 @@ +../../Task/Entropy-Narcissist/AutoLISP \ No newline at end of file diff --git a/Lang/AutoLISP/Environment-variables b/Lang/AutoLISP/Environment-variables new file mode 120000 index 0000000000..cc9ceec1ff --- /dev/null +++ b/Lang/AutoLISP/Environment-variables @@ -0,0 +1 @@ +../../Task/Environment-variables/AutoLISP \ No newline at end of file diff --git a/Lang/AutoLISP/Largest-proper-divisor-of-n b/Lang/AutoLISP/Largest-proper-divisor-of-n new file mode 120000 index 0000000000..48c08fae1a --- /dev/null +++ b/Lang/AutoLISP/Largest-proper-divisor-of-n @@ -0,0 +1 @@ +../../Task/Largest-proper-divisor-of-n/AutoLISP \ No newline at end of file diff --git a/Lang/AutoLISP/The-Twelve-Days-of-Christmas b/Lang/AutoLISP/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..3dd7563b0d --- /dev/null +++ b/Lang/AutoLISP/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/AutoLISP \ No newline at end of file diff --git a/Lang/Axiom/Quaternion-type b/Lang/Axiom/Quaternion-type deleted file mode 120000 index 483576377a..0000000000 --- a/Lang/Axiom/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Axiom \ No newline at end of file diff --git a/Lang/BASIC/00-LANG.txt b/Lang/BASIC/00-LANG.txt index 8f4f969193..ddee550d0d 100644 --- a/Lang/BASIC/00-LANG.txt +++ b/Lang/BASIC/00-LANG.txt @@ -12,25 +12,56 @@ BASIC became popular, with many different implementations for various computers. ==Links== *[[wp:BASIC|Wikipedia:BASIC]] +**[[wp:ASIC]] +**[[wp:Atari BASIC]] **[[wp:BASIC-PLUS]] +**[[wp:Basic-256]] +**[[wp:Batari BASIC]] +**[[wp:BBC BASIC]] **[[wp:Benton Harbor BASIC]] +**[[wp:Beta BASIC]] **[[wp:CBASIC]] **[[wp:Chipmunk Basic]] +**[[wp:DarkBASIC]] **[[wp:Dartmouth BASIC]] +**[[wp:FreeBASIC]] +**[[wp:FutureBASIC]] +**[[wp:GFA BASIC]] +**[[wp:GLBasic]] +**[[wp:Integer BASIC]] +**[[wp:Liberty BASIC]] +**[[wp:Locomotive BASIC]] **[[wp:Microsoft BASIC]] ***[[wp:Altair BASIC]] ***[[wp:Amiga BASIC]] ***[[wp:Applesoft BASIC]] ***[[wp:Atari Microsoft BASIC]] ***[[wp:Commodore BASIC]] +***[[wp:Extended Color BASIC]] ***[[wp:IBM BASIC]] -***[[wp:TRS-80 Level II BASIC ]] +***[[wp:MS BASIC for Macintosh]] +***[[wp:MSX BASIC]] +***[[wp:Small Basic]] +***[[wp:QBasic]] +***[[wp:QuickBASIC]]‎ +***[[wp:TRS-80 Level II BASIC]] +***[[wp:Visual Basic‎]] **[[wp:PowerBASIC]] **[[wp:PureBasic]] +**[[wp:QB64‎]] +**[[wp:Quite BASIC]]‎ +**[[wp:RapidQ]] +**[[wp:Realbasic]] **[[wp:Rocky Mountain BASIC]] +**[[wp:Run BASIC]] **[[wp:S-BASIC]] +**[[wp:ScriptBasic]] **[[wp:Sinclair BASIC]] +**[[wp:SmileBASIC‎]] **[[wp:SuperBASIC]] **[[wp:TI BASIC (TI 99/4A)]] +**[[wp:Tiny BASIC‎]] **[[wp:True BASIC]] +**[[wp:UBASIC]] +**[[wp:Yabasic]] {{language programming paradigm|Procedural}} \ No newline at end of file diff --git a/Lang/BASIC/Abundant-deficient-and-perfect-number-classifications b/Lang/BASIC/Abundant-deficient-and-perfect-number-classifications deleted file mode 120000 index 732a066bdf..0000000000 --- a/Lang/BASIC/Abundant-deficient-and-perfect-number-classifications +++ /dev/null @@ -1 +0,0 @@ -../../Task/Abundant-deficient-and-perfect-number-classifications/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Arithmetic-derivative b/Lang/BASIC/Arithmetic-derivative new file mode 120000 index 0000000000..25cf9a8b6a --- /dev/null +++ b/Lang/BASIC/Arithmetic-derivative @@ -0,0 +1 @@ +../../Task/Arithmetic-derivative/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Damm-algorithm b/Lang/BASIC/Damm-algorithm deleted file mode 120000 index 41ee6d1c36..0000000000 --- a/Lang/BASIC/Damm-algorithm +++ /dev/null @@ -1 +0,0 @@ -../../Task/Damm-algorithm/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Determine-if-a-string-is-collapsible b/Lang/BASIC/Determine-if-a-string-is-collapsible deleted file mode 120000 index 87084a2029..0000000000 --- a/Lang/BASIC/Determine-if-a-string-is-collapsible +++ /dev/null @@ -1 +0,0 @@ -../../Task/Determine-if-a-string-is-collapsible/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Ethiopian-multiplication b/Lang/BASIC/Ethiopian-multiplication deleted file mode 120000 index 94be458bb2..0000000000 --- a/Lang/BASIC/Ethiopian-multiplication +++ /dev/null @@ -1 +0,0 @@ -../../Task/Ethiopian-multiplication/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Function-definition b/Lang/BASIC/Function-definition deleted file mode 120000 index a052c63292..0000000000 --- a/Lang/BASIC/Function-definition +++ /dev/null @@ -1 +0,0 @@ -../../Task/Function-definition/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Gray-code b/Lang/BASIC/Gray-code deleted file mode 120000 index f0bc6f352f..0000000000 --- a/Lang/BASIC/Gray-code +++ /dev/null @@ -1 +0,0 @@ -../../Task/Gray-code/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Mayan-numerals b/Lang/BASIC/Mayan-numerals deleted file mode 120000 index ae24d05061..0000000000 --- a/Lang/BASIC/Mayan-numerals +++ /dev/null @@ -1 +0,0 @@ -../../Task/Mayan-numerals/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Monty-Hall-problem b/Lang/BASIC/Monty-Hall-problem deleted file mode 120000 index ba5a5a279d..0000000000 --- a/Lang/BASIC/Monty-Hall-problem +++ /dev/null @@ -1 +0,0 @@ -../../Task/Monty-Hall-problem/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Move-to-front-algorithm b/Lang/BASIC/Move-to-front-algorithm new file mode 120000 index 0000000000..a9f8d4df7e --- /dev/null +++ b/Lang/BASIC/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Ordered-words b/Lang/BASIC/Ordered-words new file mode 120000 index 0000000000..dd2f98d4e6 --- /dev/null +++ b/Lang/BASIC/Ordered-words @@ -0,0 +1 @@ +../../Task/Ordered-words/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Partition-an-integer-x-into-n-primes b/Lang/BASIC/Partition-an-integer-x-into-n-primes new file mode 120000 index 0000000000..8db316776d --- /dev/null +++ b/Lang/BASIC/Partition-an-integer-x-into-n-primes @@ -0,0 +1 @@ +../../Task/Partition-an-integer-x-into-n-primes/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Rot-13 b/Lang/BASIC/Rot-13 deleted file mode 120000 index 37a240fe69..0000000000 --- a/Lang/BASIC/Rot-13 +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rot-13/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Sorting-algorithms-Quicksort b/Lang/BASIC/Sorting-algorithms-Quicksort deleted file mode 120000 index f7976ecb9f..0000000000 --- a/Lang/BASIC/Sorting-algorithms-Quicksort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-algorithms-Quicksort/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Temperature-conversion b/Lang/BASIC/Temperature-conversion deleted file mode 120000 index 21182b0539..0000000000 --- a/Lang/BASIC/Temperature-conversion +++ /dev/null @@ -1 +0,0 @@ -../../Task/Temperature-conversion/BASIC \ No newline at end of file diff --git a/Lang/BASIC256/Associative-array-Merging b/Lang/BASIC256/Associative-array-Merging new file mode 120000 index 0000000000..20bef5368f --- /dev/null +++ b/Lang/BASIC256/Associative-array-Merging @@ -0,0 +1 @@ +../../Task/Associative-array-Merging/BASIC256 \ No newline at end of file diff --git a/Lang/BASIC256/Determine-if-a-string-has-all-the-same-characters b/Lang/BASIC256/Determine-if-a-string-has-all-the-same-characters new file mode 120000 index 0000000000..0fc88a3804 --- /dev/null +++ b/Lang/BASIC256/Determine-if-a-string-has-all-the-same-characters @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-has-all-the-same-characters/BASIC256 \ No newline at end of file diff --git a/Lang/BASIC256/Determine-sentence-type b/Lang/BASIC256/Determine-sentence-type new file mode 120000 index 0000000000..6be21d3753 --- /dev/null +++ b/Lang/BASIC256/Determine-sentence-type @@ -0,0 +1 @@ +../../Task/Determine-sentence-type/BASIC256 \ No newline at end of file diff --git a/Lang/BASIC256/Eban-numbers b/Lang/BASIC256/Eban-numbers new file mode 120000 index 0000000000..cc54b44b18 --- /dev/null +++ b/Lang/BASIC256/Eban-numbers @@ -0,0 +1 @@ +../../Task/Eban-numbers/BASIC256 \ No newline at end of file diff --git a/Lang/BASIC256/Empty-program b/Lang/BASIC256/Empty-program deleted file mode 120000 index 163b273495..0000000000 --- a/Lang/BASIC256/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/BASIC256 \ No newline at end of file diff --git a/Lang/BASIC256/Evaluate-binomial-coefficients b/Lang/BASIC256/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..415fd5e54e --- /dev/null +++ b/Lang/BASIC256/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/BASIC256 \ No newline at end of file diff --git a/Lang/BASIC256/Kronecker-product b/Lang/BASIC256/Kronecker-product new file mode 120000 index 0000000000..dd258524fe --- /dev/null +++ b/Lang/BASIC256/Kronecker-product @@ -0,0 +1 @@ +../../Task/Kronecker-product/BASIC256 \ No newline at end of file diff --git a/Lang/BASIC256/Meissel-Mertens-constant b/Lang/BASIC256/Meissel-Mertens-constant deleted file mode 120000 index 6ff8d02267..0000000000 --- a/Lang/BASIC256/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/BASIC256 \ No newline at end of file diff --git a/Lang/BASIC256/Multiple-regression b/Lang/BASIC256/Multiple-regression new file mode 120000 index 0000000000..4d8b79e98b --- /dev/null +++ b/Lang/BASIC256/Multiple-regression @@ -0,0 +1 @@ +../../Task/Multiple-regression/BASIC256 \ No newline at end of file diff --git a/Lang/BASIC256/Nested-templated-data b/Lang/BASIC256/Nested-templated-data new file mode 120000 index 0000000000..f5ddb43f39 --- /dev/null +++ b/Lang/BASIC256/Nested-templated-data @@ -0,0 +1 @@ +../../Task/Nested-templated-data/BASIC256 \ No newline at end of file diff --git a/Lang/BASIC256/Phrase-reversals b/Lang/BASIC256/Phrase-reversals new file mode 120000 index 0000000000..7bce29f023 --- /dev/null +++ b/Lang/BASIC256/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/BASIC256 \ No newline at end of file diff --git a/Lang/BASIC256/Pythagorean-triples b/Lang/BASIC256/Pythagorean-triples new file mode 120000 index 0000000000..0ded5bc54d --- /dev/null +++ b/Lang/BASIC256/Pythagorean-triples @@ -0,0 +1 @@ +../../Task/Pythagorean-triples/BASIC256 \ No newline at end of file diff --git a/Lang/BASIC256/Quaternion-type b/Lang/BASIC256/Quaternion-type deleted file mode 120000 index ecfff3f315..0000000000 --- a/Lang/BASIC256/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/BASIC256 \ No newline at end of file diff --git a/Lang/BASIC256/Ramer-Douglas-Peucker-line-simplification b/Lang/BASIC256/Ramer-Douglas-Peucker-line-simplification new file mode 120000 index 0000000000..9a890661d4 --- /dev/null +++ b/Lang/BASIC256/Ramer-Douglas-Peucker-line-simplification @@ -0,0 +1 @@ +../../Task/Ramer-Douglas-Peucker-line-simplification/BASIC256 \ No newline at end of file diff --git a/Lang/BASIC256/Sailors-coconuts-and-a-monkey-problem b/Lang/BASIC256/Sailors-coconuts-and-a-monkey-problem new file mode 120000 index 0000000000..3cfdfb5740 --- /dev/null +++ b/Lang/BASIC256/Sailors-coconuts-and-a-monkey-problem @@ -0,0 +1 @@ +../../Task/Sailors-coconuts-and-a-monkey-problem/BASIC256 \ No newline at end of file diff --git a/Lang/BASIC256/Sexy-primes b/Lang/BASIC256/Sexy-primes new file mode 120000 index 0000000000..86fc0a12b9 --- /dev/null +++ b/Lang/BASIC256/Sexy-primes @@ -0,0 +1 @@ +../../Task/Sexy-primes/BASIC256 \ No newline at end of file diff --git a/Lang/BASIC256/Sort-disjoint-sublist b/Lang/BASIC256/Sort-disjoint-sublist new file mode 120000 index 0000000000..4422d7b840 --- /dev/null +++ b/Lang/BASIC256/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/BASIC256 \ No newline at end of file diff --git a/Lang/BASIC256/Twos-complement b/Lang/BASIC256/Twos-complement new file mode 120000 index 0000000000..8b3d33db0a --- /dev/null +++ b/Lang/BASIC256/Twos-complement @@ -0,0 +1 @@ +../../Task/Twos-complement/BASIC256 \ No newline at end of file diff --git a/Lang/BBC-BASIC/Arbitrary-precision-integers-included- b/Lang/BBC-BASIC/Arbitrary-precision-integers-included- new file mode 120000 index 0000000000..ca18adffdc --- /dev/null +++ b/Lang/BBC-BASIC/Arbitrary-precision-integers-included- @@ -0,0 +1 @@ +../../Task/Arbitrary-precision-integers-included-/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Bioinformatics-base-count b/Lang/BBC-BASIC/Bioinformatics-base-count deleted file mode 120000 index 109612c5db..0000000000 --- a/Lang/BBC-BASIC/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Multi-dimensional-array b/Lang/BBC-BASIC/Multi-dimensional-array new file mode 120000 index 0000000000..4bc7c4a17c --- /dev/null +++ b/Lang/BBC-BASIC/Multi-dimensional-array @@ -0,0 +1 @@ +../../Task/Multi-dimensional-array/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Quaternion-type b/Lang/BBC-BASIC/Quaternion-type deleted file mode 120000 index 018816057d..0000000000 --- a/Lang/BBC-BASIC/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/BBC-BASIC \ No newline at end of file diff --git a/Lang/BCPL/Move-to-front-algorithm b/Lang/BCPL/Move-to-front-algorithm new file mode 120000 index 0000000000..27c5309df1 --- /dev/null +++ b/Lang/BCPL/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/BCPL \ No newline at end of file diff --git a/Lang/BCPL/Zeckendorf-number-representation b/Lang/BCPL/Zeckendorf-number-representation new file mode 120000 index 0000000000..6723808a9f --- /dev/null +++ b/Lang/BCPL/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/BCPL \ No newline at end of file diff --git a/Lang/BQN/Abundant-odd-numbers b/Lang/BQN/Abundant-odd-numbers new file mode 120000 index 0000000000..fdb56e6ed6 --- /dev/null +++ b/Lang/BQN/Abundant-odd-numbers @@ -0,0 +1 @@ +../../Task/Abundant-odd-numbers/BQN \ No newline at end of file diff --git a/Lang/BQN/Base64-decode-data b/Lang/BQN/Base64-decode-data new file mode 120000 index 0000000000..2272b7f2a1 --- /dev/null +++ b/Lang/BQN/Base64-decode-data @@ -0,0 +1 @@ +../../Task/Base64-decode-data/BQN \ No newline at end of file diff --git a/Lang/BQN/Bell-numbers b/Lang/BQN/Bell-numbers new file mode 120000 index 0000000000..2c520a34e3 --- /dev/null +++ b/Lang/BQN/Bell-numbers @@ -0,0 +1 @@ +../../Task/Bell-numbers/BQN \ No newline at end of file diff --git a/Lang/BQN/CUSIP b/Lang/BQN/CUSIP new file mode 120000 index 0000000000..b7ca66ab5f --- /dev/null +++ b/Lang/BQN/CUSIP @@ -0,0 +1 @@ +../../Task/CUSIP/BQN \ No newline at end of file diff --git a/Lang/BQN/Call-an-object-method b/Lang/BQN/Call-an-object-method new file mode 120000 index 0000000000..eb9e8d9920 --- /dev/null +++ b/Lang/BQN/Call-an-object-method @@ -0,0 +1 @@ +../../Task/Call-an-object-method/BQN \ No newline at end of file diff --git a/Lang/BQN/Cartesian-product-of-two-or-more-lists b/Lang/BQN/Cartesian-product-of-two-or-more-lists new file mode 120000 index 0000000000..9eca0c70e0 --- /dev/null +++ b/Lang/BQN/Cartesian-product-of-two-or-more-lists @@ -0,0 +1 @@ +../../Task/Cartesian-product-of-two-or-more-lists/BQN \ No newline at end of file diff --git a/Lang/BQN/Determine-if-a-string-is-squeezable b/Lang/BQN/Determine-if-a-string-is-squeezable new file mode 120000 index 0000000000..604c0583b1 --- /dev/null +++ b/Lang/BQN/Determine-if-a-string-is-squeezable @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-squeezable/BQN \ No newline at end of file diff --git a/Lang/BQN/Dutch-national-flag-problem b/Lang/BQN/Dutch-national-flag-problem new file mode 120000 index 0000000000..c24e10da06 --- /dev/null +++ b/Lang/BQN/Dutch-national-flag-problem @@ -0,0 +1 @@ +../../Task/Dutch-national-flag-problem/BQN \ No newline at end of file diff --git a/Lang/BQN/Find-common-directory-path b/Lang/BQN/Find-common-directory-path new file mode 120000 index 0000000000..d4456eaa79 --- /dev/null +++ b/Lang/BQN/Find-common-directory-path @@ -0,0 +1 @@ +../../Task/Find-common-directory-path/BQN \ No newline at end of file diff --git a/Lang/BQN/Globally-replace-text-in-several-files b/Lang/BQN/Globally-replace-text-in-several-files new file mode 120000 index 0000000000..b13db5355b --- /dev/null +++ b/Lang/BQN/Globally-replace-text-in-several-files @@ -0,0 +1 @@ +../../Task/Globally-replace-text-in-several-files/BQN \ No newline at end of file diff --git a/Lang/BQN/Harmonic-series b/Lang/BQN/Harmonic-series new file mode 120000 index 0000000000..6efb347667 --- /dev/null +++ b/Lang/BQN/Harmonic-series @@ -0,0 +1 @@ +../../Task/Harmonic-series/BQN \ No newline at end of file diff --git a/Lang/BQN/I-before-E-except-after-C b/Lang/BQN/I-before-E-except-after-C new file mode 120000 index 0000000000..5fd82fbd92 --- /dev/null +++ b/Lang/BQN/I-before-E-except-after-C @@ -0,0 +1 @@ +../../Task/I-before-E-except-after-C/BQN \ No newline at end of file diff --git a/Lang/BQN/IBAN b/Lang/BQN/IBAN new file mode 120000 index 0000000000..501e54d38b --- /dev/null +++ b/Lang/BQN/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/BQN \ No newline at end of file diff --git a/Lang/BQN/ISBN13-check-digit b/Lang/BQN/ISBN13-check-digit new file mode 120000 index 0000000000..70feb3a0c6 --- /dev/null +++ b/Lang/BQN/ISBN13-check-digit @@ -0,0 +1 @@ +../../Task/ISBN13-check-digit/BQN \ No newline at end of file diff --git a/Lang/BQN/Miller-Rabin-primality-test b/Lang/BQN/Miller-Rabin-primality-test deleted file mode 120000 index 88fd3a622d..0000000000 --- a/Lang/BQN/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/BQN \ No newline at end of file diff --git a/Lang/BQN/Phrase-reversals b/Lang/BQN/Phrase-reversals new file mode 120000 index 0000000000..a35381900f --- /dev/null +++ b/Lang/BQN/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/BQN \ No newline at end of file diff --git a/Lang/BQN/Self-describing-numbers b/Lang/BQN/Self-describing-numbers new file mode 120000 index 0000000000..394307e5cb --- /dev/null +++ b/Lang/BQN/Self-describing-numbers @@ -0,0 +1 @@ +../../Task/Self-describing-numbers/BQN \ No newline at end of file diff --git a/Lang/BQN/Sort-disjoint-sublist b/Lang/BQN/Sort-disjoint-sublist new file mode 120000 index 0000000000..b6e62b246c --- /dev/null +++ b/Lang/BQN/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/BQN \ No newline at end of file diff --git a/Lang/BQN/Tau-number b/Lang/BQN/Tau-number new file mode 120000 index 0000000000..0d0f120696 --- /dev/null +++ b/Lang/BQN/Tau-number @@ -0,0 +1 @@ +../../Task/Tau-number/BQN \ No newline at end of file diff --git a/Lang/BQN/Water-collected-between-towers b/Lang/BQN/Water-collected-between-towers new file mode 120000 index 0000000000..905f66c364 --- /dev/null +++ b/Lang/BQN/Water-collected-between-towers @@ -0,0 +1 @@ +../../Task/Water-collected-between-towers/BQN \ No newline at end of file diff --git a/Lang/BaCon/Copy-a-string b/Lang/BaCon/Copy-a-string deleted file mode 120000 index a2df7bcd98..0000000000 --- a/Lang/BaCon/Copy-a-string +++ /dev/null @@ -1 +0,0 @@ -../../Task/Copy-a-string/BaCon \ No newline at end of file diff --git a/Lang/Bait/Array-length b/Lang/Bait/Array-length new file mode 120000 index 0000000000..986225a090 --- /dev/null +++ b/Lang/Bait/Array-length @@ -0,0 +1 @@ +../../Task/Array-length/Bait \ No newline at end of file diff --git a/Lang/Bait/Empty-string b/Lang/Bait/Empty-string new file mode 120000 index 0000000000..b1bbee2da3 --- /dev/null +++ b/Lang/Bait/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/Bait \ No newline at end of file diff --git a/Lang/Bait/Loops-Continue b/Lang/Bait/Loops-Continue new file mode 120000 index 0000000000..6e3768fbb1 --- /dev/null +++ b/Lang/Bait/Loops-Continue @@ -0,0 +1 @@ +../../Task/Loops-Continue/Bait \ No newline at end of file diff --git a/Lang/Ballerina/00-LANG.txt b/Lang/Ballerina/00-LANG.txt index af215acfd5..211ba0fe40 100644 --- a/Lang/Ballerina/00-LANG.txt +++ b/Lang/Ballerina/00-LANG.txt @@ -1 +1,20 @@ -{{stub}}{{language|Ballerina}} \ No newline at end of file +{{language|Ballerina +|exec=bytecode +|strength=strong +|safety=safe +|express=explicit +|checking=static +|gc=yes +|hopl=no +|site=https://ballerina.io +}} +'''[https://en.wikipedia.org/wiki/Ballerina_(programming_language) Ballerina]''' is an open source general-purpose programming language designed and supported by [https://wso2.com/ WSO2] for cloud-era application programmers. + +It is under development on [https://github.com/ballerina-platform/ballerina-lang GitHub] and is fully documented [https://ballerina.io here]. + +Ballerina was first publicly announced in 2017 and version 1.0 was released on September 10, 2019. However, a major overhaul took place in 2022 when [https://blog.ballerina.io/posts/2022-02-01-announcing-ballerina-2201.0.0-swan-lake/ Ballerina 2201.0.0 (Swan Lake)] was released. + +The current version (2201.12.3) has distributions available for Windows, Linux and macOS and can be downloaded [https://ballerina.io/downloads/ here]. + +== See Also == +* [https://ballerina.io/learn/by-example/ Ballerina by Example] \ No newline at end of file diff --git a/Lang/Ballerina/100-doors b/Lang/Ballerina/100-doors new file mode 120000 index 0000000000..833a0fc189 --- /dev/null +++ b/Lang/Ballerina/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/99-bottles-of-beer b/Lang/Ballerina/99-bottles-of-beer new file mode 120000 index 0000000000..b3bd8e29e3 --- /dev/null +++ b/Lang/Ballerina/99-bottles-of-beer @@ -0,0 +1 @@ +../../Task/99-bottles-of-beer/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/A+B b/Lang/Ballerina/A+B new file mode 120000 index 0000000000..e9aab74a73 --- /dev/null +++ b/Lang/Ballerina/A+B @@ -0,0 +1 @@ +../../Task/A+B/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/ABC-problem b/Lang/Ballerina/ABC-problem new file mode 120000 index 0000000000..49ca7ac9ad --- /dev/null +++ b/Lang/Ballerina/ABC-problem @@ -0,0 +1 @@ +../../Task/ABC-problem/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/AKS-test-for-primes b/Lang/Ballerina/AKS-test-for-primes new file mode 120000 index 0000000000..9b19f08d80 --- /dev/null +++ b/Lang/Ballerina/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Abundant-deficient-and-perfect-number-classifications b/Lang/Ballerina/Abundant-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..b5353658a4 --- /dev/null +++ b/Lang/Ballerina/Abundant-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant-deficient-and-perfect-number-classifications/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Abundant-odd-numbers b/Lang/Ballerina/Abundant-odd-numbers new file mode 120000 index 0000000000..0b3a97c4a1 --- /dev/null +++ b/Lang/Ballerina/Abundant-odd-numbers @@ -0,0 +1 @@ +../../Task/Abundant-odd-numbers/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Accumulator-factory b/Lang/Ballerina/Accumulator-factory new file mode 120000 index 0000000000..837dbbe6a0 --- /dev/null +++ b/Lang/Ballerina/Accumulator-factory @@ -0,0 +1 @@ +../../Task/Accumulator-factory/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Achilles-numbers b/Lang/Ballerina/Achilles-numbers new file mode 120000 index 0000000000..3336ab1c37 --- /dev/null +++ b/Lang/Ballerina/Achilles-numbers @@ -0,0 +1 @@ +../../Task/Achilles-numbers/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Ackermann-function b/Lang/Ballerina/Ackermann-function new file mode 120000 index 0000000000..b9748d884d --- /dev/null +++ b/Lang/Ballerina/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Add-a-variable-to-a-class-instance-at-runtime b/Lang/Ballerina/Add-a-variable-to-a-class-instance-at-runtime new file mode 120000 index 0000000000..12efd91bd6 --- /dev/null +++ b/Lang/Ballerina/Add-a-variable-to-a-class-instance-at-runtime @@ -0,0 +1 @@ +../../Task/Add-a-variable-to-a-class-instance-at-runtime/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Additive-primes b/Lang/Ballerina/Additive-primes new file mode 120000 index 0000000000..a504210ea7 --- /dev/null +++ b/Lang/Ballerina/Additive-primes @@ -0,0 +1 @@ +../../Task/Additive-primes/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Address-of-a-variable b/Lang/Ballerina/Address-of-a-variable new file mode 120000 index 0000000000..6428e75ce3 --- /dev/null +++ b/Lang/Ballerina/Address-of-a-variable @@ -0,0 +1 @@ +../../Task/Address-of-a-variable/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Almost-prime b/Lang/Ballerina/Almost-prime new file mode 120000 index 0000000000..33d501af1e --- /dev/null +++ b/Lang/Ballerina/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Amb b/Lang/Ballerina/Amb new file mode 120000 index 0000000000..7acc58d7c4 --- /dev/null +++ b/Lang/Ballerina/Amb @@ -0,0 +1 @@ +../../Task/Amb/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Angle-difference-between-two-bearings b/Lang/Ballerina/Angle-difference-between-two-bearings new file mode 120000 index 0000000000..04ff00d986 --- /dev/null +++ b/Lang/Ballerina/Angle-difference-between-two-bearings @@ -0,0 +1 @@ +../../Task/Angle-difference-between-two-bearings/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Anti-primes b/Lang/Ballerina/Anti-primes new file mode 120000 index 0000000000..9911fc0bcb --- /dev/null +++ b/Lang/Ballerina/Anti-primes @@ -0,0 +1 @@ +../../Task/Anti-primes/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Apply-a-callback-to-an-array b/Lang/Ballerina/Apply-a-callback-to-an-array new file mode 120000 index 0000000000..9911480671 --- /dev/null +++ b/Lang/Ballerina/Apply-a-callback-to-an-array @@ -0,0 +1 @@ +../../Task/Apply-a-callback-to-an-array/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Approximate-equality b/Lang/Ballerina/Approximate-equality new file mode 120000 index 0000000000..0ea6692d0d --- /dev/null +++ b/Lang/Ballerina/Approximate-equality @@ -0,0 +1 @@ +../../Task/Approximate-equality/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Arithmetic-Complex b/Lang/Ballerina/Arithmetic-Complex new file mode 120000 index 0000000000..f87fd15204 --- /dev/null +++ b/Lang/Ballerina/Arithmetic-Complex @@ -0,0 +1 @@ +../../Task/Arithmetic-Complex/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Arithmetic-Integer b/Lang/Ballerina/Arithmetic-Integer new file mode 120000 index 0000000000..a4c8cf5206 --- /dev/null +++ b/Lang/Ballerina/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Arithmetic-Rational b/Lang/Ballerina/Arithmetic-Rational new file mode 120000 index 0000000000..422af5f88b --- /dev/null +++ b/Lang/Ballerina/Arithmetic-Rational @@ -0,0 +1 @@ +../../Task/Arithmetic-Rational/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Arithmetic-numbers b/Lang/Ballerina/Arithmetic-numbers new file mode 120000 index 0000000000..38541780a0 --- /dev/null +++ b/Lang/Ballerina/Arithmetic-numbers @@ -0,0 +1 @@ +../../Task/Arithmetic-numbers/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Array-concatenation b/Lang/Ballerina/Array-concatenation new file mode 120000 index 0000000000..41c2603b74 --- /dev/null +++ b/Lang/Ballerina/Array-concatenation @@ -0,0 +1 @@ +../../Task/Array-concatenation/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Array-length b/Lang/Ballerina/Array-length new file mode 120000 index 0000000000..25020148f9 --- /dev/null +++ b/Lang/Ballerina/Array-length @@ -0,0 +1 @@ +../../Task/Array-length/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Arrays b/Lang/Ballerina/Arrays new file mode 120000 index 0000000000..ec5c5a266e --- /dev/null +++ b/Lang/Ballerina/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Ascending-primes b/Lang/Ballerina/Ascending-primes new file mode 120000 index 0000000000..51444ceb96 --- /dev/null +++ b/Lang/Ballerina/Ascending-primes @@ -0,0 +1 @@ +../../Task/Ascending-primes/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Associative-array-Creation b/Lang/Ballerina/Associative-array-Creation new file mode 120000 index 0000000000..2639b285f3 --- /dev/null +++ b/Lang/Ballerina/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Associative-array-Iteration b/Lang/Ballerina/Associative-array-Iteration new file mode 120000 index 0000000000..d3e31d2374 --- /dev/null +++ b/Lang/Ballerina/Associative-array-Iteration @@ -0,0 +1 @@ +../../Task/Associative-array-Iteration/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Associative-array-Merging b/Lang/Ballerina/Associative-array-Merging new file mode 120000 index 0000000000..cd38137d75 --- /dev/null +++ b/Lang/Ballerina/Associative-array-Merging @@ -0,0 +1 @@ +../../Task/Associative-array-Merging/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Averages-Arithmetic-mean b/Lang/Ballerina/Averages-Arithmetic-mean new file mode 120000 index 0000000000..039d1f0de8 --- /dev/null +++ b/Lang/Ballerina/Averages-Arithmetic-mean @@ -0,0 +1 @@ +../../Task/Averages-Arithmetic-mean/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Averages-Mean-angle b/Lang/Ballerina/Averages-Mean-angle new file mode 120000 index 0000000000..adf77693ce --- /dev/null +++ b/Lang/Ballerina/Averages-Mean-angle @@ -0,0 +1 @@ +../../Task/Averages-Mean-angle/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Averages-Mean-time-of-day b/Lang/Ballerina/Averages-Mean-time-of-day new file mode 120000 index 0000000000..c969ed84e4 --- /dev/null +++ b/Lang/Ballerina/Averages-Mean-time-of-day @@ -0,0 +1 @@ +../../Task/Averages-Mean-time-of-day/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Averages-Median b/Lang/Ballerina/Averages-Median new file mode 120000 index 0000000000..5bbd39cecb --- /dev/null +++ b/Lang/Ballerina/Averages-Median @@ -0,0 +1 @@ +../../Task/Averages-Median/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Averages-Mode b/Lang/Ballerina/Averages-Mode new file mode 120000 index 0000000000..72d0e02dae --- /dev/null +++ b/Lang/Ballerina/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Averages-Pythagorean-means b/Lang/Ballerina/Averages-Pythagorean-means new file mode 120000 index 0000000000..fd607a9ee8 --- /dev/null +++ b/Lang/Ballerina/Averages-Pythagorean-means @@ -0,0 +1 @@ +../../Task/Averages-Pythagorean-means/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Averages-Root-mean-square b/Lang/Ballerina/Averages-Root-mean-square new file mode 120000 index 0000000000..48056410d9 --- /dev/null +++ b/Lang/Ballerina/Averages-Root-mean-square @@ -0,0 +1 @@ +../../Task/Averages-Root-mean-square/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Averages-Simple-moving-average b/Lang/Ballerina/Averages-Simple-moving-average new file mode 120000 index 0000000000..7e2849cced --- /dev/null +++ b/Lang/Ballerina/Averages-Simple-moving-average @@ -0,0 +1 @@ +../../Task/Averages-Simple-moving-average/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Balanced-brackets b/Lang/Ballerina/Balanced-brackets new file mode 120000 index 0000000000..3d78b77dd3 --- /dev/null +++ b/Lang/Ballerina/Balanced-brackets @@ -0,0 +1 @@ +../../Task/Balanced-brackets/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Binary-digits b/Lang/Ballerina/Binary-digits new file mode 120000 index 0000000000..47999ed558 --- /dev/null +++ b/Lang/Ballerina/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Boolean-values b/Lang/Ballerina/Boolean-values new file mode 120000 index 0000000000..c01657f16a --- /dev/null +++ b/Lang/Ballerina/Boolean-values @@ -0,0 +1 @@ +../../Task/Boolean-values/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Caesar-cipher b/Lang/Ballerina/Caesar-cipher new file mode 120000 index 0000000000..8e1a6603e9 --- /dev/null +++ b/Lang/Ballerina/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Calculating-the-value-of-e b/Lang/Ballerina/Calculating-the-value-of-e new file mode 120000 index 0000000000..af3085b824 --- /dev/null +++ b/Lang/Ballerina/Calculating-the-value-of-e @@ -0,0 +1 @@ +../../Task/Calculating-the-value-of-e/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Case-sensitivity-of-identifiers b/Lang/Ballerina/Case-sensitivity-of-identifiers new file mode 120000 index 0000000000..42725d41da --- /dev/null +++ b/Lang/Ballerina/Case-sensitivity-of-identifiers @@ -0,0 +1 @@ +../../Task/Case-sensitivity-of-identifiers/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Character-codes b/Lang/Ballerina/Character-codes new file mode 120000 index 0000000000..6abede048f --- /dev/null +++ b/Lang/Ballerina/Character-codes @@ -0,0 +1 @@ +../../Task/Character-codes/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Classes b/Lang/Ballerina/Classes new file mode 120000 index 0000000000..0c8bd2434d --- /dev/null +++ b/Lang/Ballerina/Classes @@ -0,0 +1 @@ +../../Task/Classes/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Commatizing-numbers b/Lang/Ballerina/Commatizing-numbers new file mode 120000 index 0000000000..a644eda1b6 --- /dev/null +++ b/Lang/Ballerina/Commatizing-numbers @@ -0,0 +1 @@ +../../Task/Commatizing-numbers/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Comments b/Lang/Ballerina/Comments new file mode 120000 index 0000000000..6b5d53ddee --- /dev/null +++ b/Lang/Ballerina/Comments @@ -0,0 +1 @@ +../../Task/Comments/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Copy-a-string b/Lang/Ballerina/Copy-a-string new file mode 120000 index 0000000000..ce5773b181 --- /dev/null +++ b/Lang/Ballerina/Copy-a-string @@ -0,0 +1 @@ +../../Task/Copy-a-string/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Count-in-octal b/Lang/Ballerina/Count-in-octal new file mode 120000 index 0000000000..7e70a67830 --- /dev/null +++ b/Lang/Ballerina/Count-in-octal @@ -0,0 +1 @@ +../../Task/Count-in-octal/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Currency b/Lang/Ballerina/Currency new file mode 120000 index 0000000000..2b278dfa20 --- /dev/null +++ b/Lang/Ballerina/Currency @@ -0,0 +1 @@ +../../Task/Currency/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Currying b/Lang/Ballerina/Currying new file mode 120000 index 0000000000..7e465c7834 --- /dev/null +++ b/Lang/Ballerina/Currying @@ -0,0 +1 @@ +../../Task/Currying/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Dot-product b/Lang/Ballerina/Dot-product new file mode 120000 index 0000000000..327f9d0969 --- /dev/null +++ b/Lang/Ballerina/Dot-product @@ -0,0 +1 @@ +../../Task/Dot-product/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Dynamic-variable-names b/Lang/Ballerina/Dynamic-variable-names new file mode 120000 index 0000000000..5c549728ae --- /dev/null +++ b/Lang/Ballerina/Dynamic-variable-names @@ -0,0 +1 @@ +../../Task/Dynamic-variable-names/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Empty-string b/Lang/Ballerina/Empty-string new file mode 120000 index 0000000000..a86a0ffc9d --- /dev/null +++ b/Lang/Ballerina/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Even-or-odd b/Lang/Ballerina/Even-or-odd new file mode 120000 index 0000000000..2d8b1b90ab --- /dev/null +++ b/Lang/Ballerina/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Extreme-floating-point-values b/Lang/Ballerina/Extreme-floating-point-values new file mode 120000 index 0000000000..7f91d37268 --- /dev/null +++ b/Lang/Ballerina/Extreme-floating-point-values @@ -0,0 +1 @@ +../../Task/Extreme-floating-point-values/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Factors-of-an-integer b/Lang/Ballerina/Factors-of-an-integer new file mode 120000 index 0000000000..ac634eef84 --- /dev/null +++ b/Lang/Ballerina/Factors-of-an-integer @@ -0,0 +1 @@ +../../Task/Factors-of-an-integer/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Farey-sequence b/Lang/Ballerina/Farey-sequence new file mode 120000 index 0000000000..d542459c5f --- /dev/null +++ b/Lang/Ballerina/Farey-sequence @@ -0,0 +1 @@ +../../Task/Farey-sequence/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Fibonacci-sequence b/Lang/Ballerina/Fibonacci-sequence new file mode 120000 index 0000000000..96031e7d01 --- /dev/null +++ b/Lang/Ballerina/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Filter b/Lang/Ballerina/Filter new file mode 120000 index 0000000000..b57b5e74be --- /dev/null +++ b/Lang/Ballerina/Filter @@ -0,0 +1 @@ +../../Task/Filter/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Find-limit-of-recursion b/Lang/Ballerina/Find-limit-of-recursion new file mode 120000 index 0000000000..0c9c45aca0 --- /dev/null +++ b/Lang/Ballerina/Find-limit-of-recursion @@ -0,0 +1 @@ +../../Task/Find-limit-of-recursion/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Fivenum b/Lang/Ballerina/Fivenum new file mode 120000 index 0000000000..0df90aeb78 --- /dev/null +++ b/Lang/Ballerina/Fivenum @@ -0,0 +1 @@ +../../Task/Fivenum/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/FizzBuzz b/Lang/Ballerina/FizzBuzz new file mode 120000 index 0000000000..e7f3aa8019 --- /dev/null +++ b/Lang/Ballerina/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Floyds-triangle b/Lang/Ballerina/Floyds-triangle new file mode 120000 index 0000000000..524ef8d9d5 --- /dev/null +++ b/Lang/Ballerina/Floyds-triangle @@ -0,0 +1 @@ +../../Task/Floyds-triangle/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Four-bit-adder b/Lang/Ballerina/Four-bit-adder new file mode 120000 index 0000000000..da1ccb0292 --- /dev/null +++ b/Lang/Ballerina/Four-bit-adder @@ -0,0 +1 @@ +../../Task/Four-bit-adder/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Function-definition b/Lang/Ballerina/Function-definition new file mode 120000 index 0000000000..aad5e07c0c --- /dev/null +++ b/Lang/Ballerina/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Gapful-numbers b/Lang/Ballerina/Gapful-numbers new file mode 120000 index 0000000000..16bb3670f6 --- /dev/null +++ b/Lang/Ballerina/Gapful-numbers @@ -0,0 +1 @@ +../../Task/Gapful-numbers/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Greatest-common-divisor b/Lang/Ballerina/Greatest-common-divisor new file mode 120000 index 0000000000..0f657f13a6 --- /dev/null +++ b/Lang/Ballerina/Greatest-common-divisor @@ -0,0 +1 @@ +../../Task/Greatest-common-divisor/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Greatest-element-of-a-list b/Lang/Ballerina/Greatest-element-of-a-list new file mode 120000 index 0000000000..579d0c3022 --- /dev/null +++ b/Lang/Ballerina/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Greatest-subsequential-sum b/Lang/Ballerina/Greatest-subsequential-sum new file mode 120000 index 0000000000..edc1a686d7 --- /dev/null +++ b/Lang/Ballerina/Greatest-subsequential-sum @@ -0,0 +1 @@ +../../Task/Greatest-subsequential-sum/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Hailstone-sequence b/Lang/Ballerina/Hailstone-sequence new file mode 120000 index 0000000000..41dfb14066 --- /dev/null +++ b/Lang/Ballerina/Hailstone-sequence @@ -0,0 +1 @@ +../../Task/Hailstone-sequence/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Hello-world-Graphical b/Lang/Ballerina/Hello-world-Graphical new file mode 120000 index 0000000000..4e2e7e9224 --- /dev/null +++ b/Lang/Ballerina/Hello-world-Graphical @@ -0,0 +1 @@ +../../Task/Hello-world-Graphical/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Hello-world-Newbie b/Lang/Ballerina/Hello-world-Newbie new file mode 120000 index 0000000000..b59c1b36e9 --- /dev/null +++ b/Lang/Ballerina/Hello-world-Newbie @@ -0,0 +1 @@ +../../Task/Hello-world-Newbie/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Hello-world-Newline-omission b/Lang/Ballerina/Hello-world-Newline-omission new file mode 120000 index 0000000000..1016c5553e --- /dev/null +++ b/Lang/Ballerina/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Hello-world-Standard-error b/Lang/Ballerina/Hello-world-Standard-error new file mode 120000 index 0000000000..c4921dce1f --- /dev/null +++ b/Lang/Ballerina/Hello-world-Standard-error @@ -0,0 +1 @@ +../../Task/Hello-world-Standard-error/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Increment-a-numerical-string b/Lang/Ballerina/Increment-a-numerical-string new file mode 120000 index 0000000000..712faa77bf --- /dev/null +++ b/Lang/Ballerina/Increment-a-numerical-string @@ -0,0 +1 @@ +../../Task/Increment-a-numerical-string/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Integer-comparison b/Lang/Ballerina/Integer-comparison new file mode 120000 index 0000000000..8563637dab --- /dev/null +++ b/Lang/Ballerina/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Integer-sequence b/Lang/Ballerina/Integer-sequence new file mode 120000 index 0000000000..06b95f33f5 --- /dev/null +++ b/Lang/Ballerina/Integer-sequence @@ -0,0 +1 @@ +../../Task/Integer-sequence/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Levenshtein-distance b/Lang/Ballerina/Levenshtein-distance new file mode 120000 index 0000000000..4824e03354 --- /dev/null +++ b/Lang/Ballerina/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Logical-operations b/Lang/Ballerina/Logical-operations new file mode 120000 index 0000000000..06b4043fcb --- /dev/null +++ b/Lang/Ballerina/Logical-operations @@ -0,0 +1 @@ +../../Task/Logical-operations/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Loop-over-multiple-arrays-simultaneously b/Lang/Ballerina/Loop-over-multiple-arrays-simultaneously new file mode 120000 index 0000000000..9b68d094d5 --- /dev/null +++ b/Lang/Ballerina/Loop-over-multiple-arrays-simultaneously @@ -0,0 +1 @@ +../../Task/Loop-over-multiple-arrays-simultaneously/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Loops-Break b/Lang/Ballerina/Loops-Break new file mode 120000 index 0000000000..6ab612b087 --- /dev/null +++ b/Lang/Ballerina/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Loops-Continue b/Lang/Ballerina/Loops-Continue new file mode 120000 index 0000000000..175be123b9 --- /dev/null +++ b/Lang/Ballerina/Loops-Continue @@ -0,0 +1 @@ +../../Task/Loops-Continue/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Loops-Do-while b/Lang/Ballerina/Loops-Do-while new file mode 120000 index 0000000000..b90c6b3171 --- /dev/null +++ b/Lang/Ballerina/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Loops-Downward-for b/Lang/Ballerina/Loops-Downward-for new file mode 120000 index 0000000000..e977389f54 --- /dev/null +++ b/Lang/Ballerina/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Loops-For b/Lang/Ballerina/Loops-For new file mode 120000 index 0000000000..8ad2b8fd0c --- /dev/null +++ b/Lang/Ballerina/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Loops-For-with-a-specified-step b/Lang/Ballerina/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..cc892dc7f2 --- /dev/null +++ b/Lang/Ballerina/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Loops-Foreach b/Lang/Ballerina/Loops-Foreach new file mode 120000 index 0000000000..f819fadabe --- /dev/null +++ b/Lang/Ballerina/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Loops-Increment-loop-index-within-loop-body b/Lang/Ballerina/Loops-Increment-loop-index-within-loop-body new file mode 120000 index 0000000000..1c9b81a58a --- /dev/null +++ b/Lang/Ballerina/Loops-Increment-loop-index-within-loop-body @@ -0,0 +1 @@ +../../Task/Loops-Increment-loop-index-within-loop-body/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Loops-Infinite b/Lang/Ballerina/Loops-Infinite new file mode 120000 index 0000000000..312369ce48 --- /dev/null +++ b/Lang/Ballerina/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Loops-N-plus-one-half b/Lang/Ballerina/Loops-N-plus-one-half new file mode 120000 index 0000000000..220ecbad7f --- /dev/null +++ b/Lang/Ballerina/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Loops-Nested b/Lang/Ballerina/Loops-Nested new file mode 120000 index 0000000000..f32c9a3c17 --- /dev/null +++ b/Lang/Ballerina/Loops-Nested @@ -0,0 +1 @@ +../../Task/Loops-Nested/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Loops-With-multiple-ranges b/Lang/Ballerina/Loops-With-multiple-ranges new file mode 120000 index 0000000000..2fad29a9f9 --- /dev/null +++ b/Lang/Ballerina/Loops-With-multiple-ranges @@ -0,0 +1 @@ +../../Task/Loops-With-multiple-ranges/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Loops-Wrong-ranges b/Lang/Ballerina/Loops-Wrong-ranges new file mode 120000 index 0000000000..6c8ada2aa7 --- /dev/null +++ b/Lang/Ballerina/Loops-Wrong-ranges @@ -0,0 +1 @@ +../../Task/Loops-Wrong-ranges/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Palindrome-detection b/Lang/Ballerina/Palindrome-detection new file mode 120000 index 0000000000..981d11f5cd --- /dev/null +++ b/Lang/Ballerina/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Repeat-a-string b/Lang/Ballerina/Repeat-a-string new file mode 120000 index 0000000000..83134ceac0 --- /dev/null +++ b/Lang/Ballerina/Repeat-a-string @@ -0,0 +1 @@ +../../Task/Repeat-a-string/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Reverse-a-string b/Lang/Ballerina/Reverse-a-string new file mode 120000 index 0000000000..f4e8e73220 --- /dev/null +++ b/Lang/Ballerina/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Rot-13 b/Lang/Ballerina/Rot-13 new file mode 120000 index 0000000000..d33ecacc03 --- /dev/null +++ b/Lang/Ballerina/Rot-13 @@ -0,0 +1 @@ +../../Task/Rot-13/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Sieve-of-Eratosthenes b/Lang/Ballerina/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..4cae2a9d5e --- /dev/null +++ b/Lang/Ballerina/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Stack b/Lang/Ballerina/Stack new file mode 120000 index 0000000000..e073045735 --- /dev/null +++ b/Lang/Ballerina/Stack @@ -0,0 +1 @@ +../../Task/Stack/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Statistics-Basic b/Lang/Ballerina/Statistics-Basic new file mode 120000 index 0000000000..7ef892b782 --- /dev/null +++ b/Lang/Ballerina/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/String-case b/Lang/Ballerina/String-case new file mode 120000 index 0000000000..091d633ac8 --- /dev/null +++ b/Lang/Ballerina/String-case @@ -0,0 +1 @@ +../../Task/String-case/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/String-concatenation b/Lang/Ballerina/String-concatenation new file mode 120000 index 0000000000..a5a366085e --- /dev/null +++ b/Lang/Ballerina/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/String-length b/Lang/Ballerina/String-length new file mode 120000 index 0000000000..0cdb126aa0 --- /dev/null +++ b/Lang/Ballerina/String-length @@ -0,0 +1 @@ +../../Task/String-length/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Sum-and-product-of-an-array b/Lang/Ballerina/Sum-and-product-of-an-array new file mode 120000 index 0000000000..a5ba732cde --- /dev/null +++ b/Lang/Ballerina/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Sum-of-a-series b/Lang/Ballerina/Sum-of-a-series new file mode 120000 index 0000000000..27da1c4b06 --- /dev/null +++ b/Lang/Ballerina/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Sum-of-squares b/Lang/Ballerina/Sum-of-squares new file mode 120000 index 0000000000..9f1e366796 --- /dev/null +++ b/Lang/Ballerina/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Tokenize-a-string b/Lang/Ballerina/Tokenize-a-string new file mode 120000 index 0000000000..d9a64c3a3e --- /dev/null +++ b/Lang/Ballerina/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Towers-of-Hanoi b/Lang/Ballerina/Towers-of-Hanoi new file mode 120000 index 0000000000..81bf7985bd --- /dev/null +++ b/Lang/Ballerina/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Truncatable-primes b/Lang/Ballerina/Truncatable-primes new file mode 120000 index 0000000000..044dcb5d58 --- /dev/null +++ b/Lang/Ballerina/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Unicode-variable-names b/Lang/Ballerina/Unicode-variable-names new file mode 120000 index 0000000000..7f61255815 --- /dev/null +++ b/Lang/Ballerina/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/Ballerina \ No newline at end of file diff --git a/Lang/Basic09/00-LANG.txt b/Lang/Basic09/00-LANG.txt index 16853881ce..fa600ca16b 100644 --- a/Lang/Basic09/00-LANG.txt +++ b/Lang/Basic09/00-LANG.txt @@ -1 +1,3 @@ -{{language|Basic09}}Basic09 is a dialect of BASIC created by Microware Systems Corporation in 1978 for use on the OS-9 operating system designed for the Motorola 6809 microporcessor. There is a version for OS-9/68000, "Microware BASIC", identical save that the INTEGER type is a four-byte signed integer instead of two-byte and REAL is IEEE 754 double precision rather than the five-byte format in the original version. \ No newline at end of file +{{language|Basic09}} +{{implementation|BASIC}} +Basic09 is a dialect of BASIC created by Microware Systems Corporation in 1978 for use on the OS-9 operating system designed for the Motorola 6809 microporcessor. There is a version for OS-9/68000, "Microware BASIC", identical save that the INTEGER type is a four-byte signed integer instead of two-byte and REAL is IEEE 754 double precision rather than the five-byte format in the original version. \ No newline at end of file diff --git a/Lang/Batch-File/00-LANG.txt b/Lang/Batch-File/00-LANG.txt index 1bcc82760d..06b0c85598 100644 --- a/Lang/Batch-File/00-LANG.txt +++ b/Lang/Batch-File/00-LANG.txt @@ -1,3 +1,3 @@ -{{language|Batch File}}'''Batch files''' are the scripting languages for [[Microsoft]] command line shells, such as [[MS-DOS]], COMMAND.EXE, and CMD.EXE. They typically have either the .BAT or .CMD extension. +{{language|Batch File}}'''Batch file''', sometimes just called Batch, is the common name for the scripting language for [[Microsoft]] command line shells, such as COMMAND.COM (in [[MS-DOS]]), and CMD.EXE (in Windows). They typically have either the .BAT or .CMD extension. Due to the association of batch files with MS-DOS in the public consciousness, sometimes this language is called the MS-DOS programming language even when used on modern versions of Windows, though this usage of the term is not technically correct. The "batch files" written in the Batch File language are not to be confused with the "bash scripts" written in the [[bash | bash programming language]] for the [[UNIX Shell]]. \ No newline at end of file diff --git a/Lang/Batch-File/Base64-decode-data b/Lang/Batch-File/Base64-decode-data new file mode 120000 index 0000000000..ec2f53b5db --- /dev/null +++ b/Lang/Batch-File/Base64-decode-data @@ -0,0 +1 @@ +../../Task/Base64-decode-data/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Call-a-foreign-language-function b/Lang/Batch-File/Call-a-foreign-language-function new file mode 120000 index 0000000000..82bd97e4ca --- /dev/null +++ b/Lang/Batch-File/Call-a-foreign-language-function @@ -0,0 +1 @@ +../../Task/Call-a-foreign-language-function/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Check-input-device-is-a-terminal b/Lang/Batch-File/Check-input-device-is-a-terminal new file mode 120000 index 0000000000..e3cbbd272b --- /dev/null +++ b/Lang/Batch-File/Check-input-device-is-a-terminal @@ -0,0 +1 @@ +../../Task/Check-input-device-is-a-terminal/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Check-output-device-is-a-terminal b/Lang/Batch-File/Check-output-device-is-a-terminal new file mode 120000 index 0000000000..3d54ec8254 --- /dev/null +++ b/Lang/Batch-File/Check-output-device-is-a-terminal @@ -0,0 +1 @@ +../../Task/Check-output-device-is-a-terminal/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Chinese-zodiac b/Lang/Batch-File/Chinese-zodiac new file mode 120000 index 0000000000..c2c7ae27f9 --- /dev/null +++ b/Lang/Batch-File/Chinese-zodiac @@ -0,0 +1 @@ +../../Task/Chinese-zodiac/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Copy-stdin-to-stdout b/Lang/Batch-File/Copy-stdin-to-stdout new file mode 120000 index 0000000000..ec25d70662 --- /dev/null +++ b/Lang/Batch-File/Copy-stdin-to-stdout @@ -0,0 +1 @@ +../../Task/Copy-stdin-to-stdout/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Exponentiation-operator b/Lang/Batch-File/Exponentiation-operator new file mode 120000 index 0000000000..93dda3ab18 --- /dev/null +++ b/Lang/Batch-File/Exponentiation-operator @@ -0,0 +1 @@ +../../Task/Exponentiation-operator/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Flatten-a-list b/Lang/Batch-File/Flatten-a-list new file mode 120000 index 0000000000..bdac6d0d38 --- /dev/null +++ b/Lang/Batch-File/Flatten-a-list @@ -0,0 +1 @@ +../../Task/Flatten-a-list/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Handle-a-signal b/Lang/Batch-File/Handle-a-signal new file mode 120000 index 0000000000..5dfc7c6a7d --- /dev/null +++ b/Lang/Batch-File/Handle-a-signal @@ -0,0 +1 @@ +../../Task/Handle-a-signal/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Hello-world-Web-server b/Lang/Batch-File/Hello-world-Web-server new file mode 120000 index 0000000000..ef5c7e0f66 --- /dev/null +++ b/Lang/Batch-File/Hello-world-Web-server @@ -0,0 +1 @@ +../../Task/Hello-world-Web-server/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Input-loop b/Lang/Batch-File/Input-loop deleted file mode 120000 index a2a4a9b473..0000000000 --- a/Lang/Batch-File/Input-loop +++ /dev/null @@ -1 +0,0 @@ -../../Task/Input-loop/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Keyboard-input-Keypress-check b/Lang/Batch-File/Keyboard-input-Keypress-check new file mode 120000 index 0000000000..5711a16a1c --- /dev/null +++ b/Lang/Batch-File/Keyboard-input-Keypress-check @@ -0,0 +1 @@ +../../Task/Keyboard-input-Keypress-check/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Long-year b/Lang/Batch-File/Long-year new file mode 120000 index 0000000000..2a90ddff12 --- /dev/null +++ b/Lang/Batch-File/Long-year @@ -0,0 +1 @@ +../../Task/Long-year/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Make-directory-path b/Lang/Batch-File/Make-directory-path new file mode 120000 index 0000000000..057c573752 --- /dev/null +++ b/Lang/Batch-File/Make-directory-path @@ -0,0 +1 @@ +../../Task/Make-directory-path/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Primality-by-trial-division b/Lang/Batch-File/Primality-by-trial-division new file mode 120000 index 0000000000..5a253da7c4 --- /dev/null +++ b/Lang/Batch-File/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Read-a-configuration-file b/Lang/Batch-File/Read-a-configuration-file new file mode 120000 index 0000000000..163a19758c --- /dev/null +++ b/Lang/Batch-File/Read-a-configuration-file @@ -0,0 +1 @@ +../../Task/Read-a-configuration-file/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Read-entire-file b/Lang/Batch-File/Read-entire-file new file mode 120000 index 0000000000..a4d22dbb49 --- /dev/null +++ b/Lang/Batch-File/Read-entire-file @@ -0,0 +1 @@ +../../Task/Read-entire-file/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/SHA-1 b/Lang/Batch-File/SHA-1 new file mode 120000 index 0000000000..7b80d0565c --- /dev/null +++ b/Lang/Batch-File/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/SHA-256 b/Lang/Batch-File/SHA-256 new file mode 120000 index 0000000000..88132ba441 --- /dev/null +++ b/Lang/Batch-File/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Simple-windowed-application b/Lang/Batch-File/Simple-windowed-application new file mode 120000 index 0000000000..98ffbccd11 --- /dev/null +++ b/Lang/Batch-File/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Sort-an-integer-array b/Lang/Batch-File/Sort-an-integer-array new file mode 120000 index 0000000000..9e7fd40b38 --- /dev/null +++ b/Lang/Batch-File/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Strip-a-set-of-characters-from-a-string b/Lang/Batch-File/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..bb3a4f27fc --- /dev/null +++ b/Lang/Batch-File/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Temperature-conversion b/Lang/Batch-File/Temperature-conversion new file mode 120000 index 0000000000..a928fb35a8 --- /dev/null +++ b/Lang/Batch-File/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Terminal-control-Hiding-the-cursor b/Lang/Batch-File/Terminal-control-Hiding-the-cursor new file mode 120000 index 0000000000..55e8dcde29 --- /dev/null +++ b/Lang/Batch-File/Terminal-control-Hiding-the-cursor @@ -0,0 +1 @@ +../../Task/Terminal-control-Hiding-the-cursor/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Terminal-control-Preserve-screen b/Lang/Batch-File/Terminal-control-Preserve-screen new file mode 120000 index 0000000000..8bc69bb473 --- /dev/null +++ b/Lang/Batch-File/Terminal-control-Preserve-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Preserve-screen/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Terminal-control-Unicode-output b/Lang/Batch-File/Terminal-control-Unicode-output new file mode 120000 index 0000000000..d9cf45a55e --- /dev/null +++ b/Lang/Batch-File/Terminal-control-Unicode-output @@ -0,0 +1 @@ +../../Task/Terminal-control-Unicode-output/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Truncate-a-file b/Lang/Batch-File/Truncate-a-file new file mode 120000 index 0000000000..18bcf16da0 --- /dev/null +++ b/Lang/Batch-File/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/URL-decoding b/Lang/Batch-File/URL-decoding new file mode 120000 index 0000000000..4081a1f375 --- /dev/null +++ b/Lang/Batch-File/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/URL-encoding b/Lang/Batch-File/URL-encoding new file mode 120000 index 0000000000..5609bac01d --- /dev/null +++ b/Lang/Batch-File/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Unicode-variable-names b/Lang/Batch-File/Unicode-variable-names new file mode 120000 index 0000000000..04bbb2a08c --- /dev/null +++ b/Lang/Batch-File/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Unix-ls b/Lang/Batch-File/Unix-ls new file mode 120000 index 0000000000..d789240aba --- /dev/null +++ b/Lang/Batch-File/Unix-ls @@ -0,0 +1 @@ +../../Task/Unix-ls/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Window-creation b/Lang/Batch-File/Window-creation new file mode 120000 index 0000000000..733ac1868e --- /dev/null +++ b/Lang/Batch-File/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Write-entire-file b/Lang/Batch-File/Write-entire-file new file mode 120000 index 0000000000..ace14aef52 --- /dev/null +++ b/Lang/Batch-File/Write-entire-file @@ -0,0 +1 @@ +../../Task/Write-entire-file/Batch-File \ No newline at end of file diff --git a/Lang/Bc/Anti-primes b/Lang/Bc/Anti-primes new file mode 120000 index 0000000000..3d900bc4e9 --- /dev/null +++ b/Lang/Bc/Anti-primes @@ -0,0 +1 @@ +../../Task/Anti-primes/Bc \ No newline at end of file diff --git a/Lang/Bc/Arithmetic-derivative b/Lang/Bc/Arithmetic-derivative new file mode 120000 index 0000000000..3ff888839e --- /dev/null +++ b/Lang/Bc/Arithmetic-derivative @@ -0,0 +1 @@ +../../Task/Arithmetic-derivative/Bc \ No newline at end of file diff --git a/Lang/Bc/Department-numbers b/Lang/Bc/Department-numbers new file mode 120000 index 0000000000..0e2c9bd91f --- /dev/null +++ b/Lang/Bc/Department-numbers @@ -0,0 +1 @@ +../../Task/Department-numbers/Bc \ No newline at end of file diff --git a/Lang/Bc/Fairshare-between-two-and-more b/Lang/Bc/Fairshare-between-two-and-more new file mode 120000 index 0000000000..f5c1a3523e --- /dev/null +++ b/Lang/Bc/Fairshare-between-two-and-more @@ -0,0 +1 @@ +../../Task/Fairshare-between-two-and-more/Bc \ No newline at end of file diff --git a/Lang/Bc/Miller-Rabin-primality-test b/Lang/Bc/Miller-Rabin-primality-test deleted file mode 120000 index 1ae2fd8406..0000000000 --- a/Lang/Bc/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Bc \ No newline at end of file diff --git a/Lang/Bc/Sieve-of-Eratosthenes b/Lang/Bc/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..de34a684a4 --- /dev/null +++ b/Lang/Bc/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Bc \ No newline at end of file diff --git a/Lang/Bc/Variables b/Lang/Bc/Variables new file mode 120000 index 0000000000..03f47bea63 --- /dev/null +++ b/Lang/Bc/Variables @@ -0,0 +1 @@ +../../Task/Variables/Bc \ No newline at end of file diff --git a/Lang/Beeswax/00-LANG.txt b/Lang/Beeswax/00-LANG.txt index bea56d7b6b..c131bf7731 100644 --- a/Lang/Beeswax/00-LANG.txt +++ b/Lang/Beeswax/00-LANG.txt @@ -25,7 +25,7 @@ All data in the local and global stacks are unsigned 64-bit integers, output as == More information == -* [[eso:Beeswax|Esoteric languages wiki entry]] +* [http://esolangs.org/wiki/beeswax Esoteric languages wiki entry] == Reference implementation, example programs and complete language specification == diff --git a/Lang/Berkeley-Logo/00-LANG.txt b/Lang/Berkeley-Logo/00-LANG.txt new file mode 100644 index 0000000000..06b91b5045 --- /dev/null +++ b/Lang/Berkeley-Logo/00-LANG.txt @@ -0,0 +1,8 @@ +{{language|Berkeley Logo}} +{{language programming paradigm|Procedural}} +{{implementation|Logo}} +'''Berkeley Logo''' (or '''UCBLogo''') is a portable implementation of the Logo language, maintained by Brian Harvey. He has also written a series of university textbooks using this language, ''Computer Science Logo Style''. + +==External links== +* [http://www.cs.berkeley.edu/~bh/logo.html Home page] +* [https://github.com/jrincayc/ucblogo-code further UCBLogo development] \ No newline at end of file diff --git a/Lang/Berkeley-Logo/00-META.yaml b/Lang/Berkeley-Logo/00-META.yaml new file mode 100644 index 0000000000..9eabccce73 --- /dev/null +++ b/Lang/Berkeley-Logo/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Berkeley_Logo diff --git a/Lang/Berkeley-Logo/Abundant-deficient-and-perfect-number-classifications b/Lang/Berkeley-Logo/Abundant-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..04fb2b777b --- /dev/null +++ b/Lang/Berkeley-Logo/Abundant-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant-deficient-and-perfect-number-classifications/Berkeley-Logo \ No newline at end of file diff --git a/Lang/Berkeley-Logo/Associative-array-Creation b/Lang/Berkeley-Logo/Associative-array-Creation new file mode 120000 index 0000000000..4d2050642e --- /dev/null +++ b/Lang/Berkeley-Logo/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/Berkeley-Logo \ No newline at end of file diff --git a/Lang/Berkeley-Logo/Babbage-problem b/Lang/Berkeley-Logo/Babbage-problem new file mode 120000 index 0000000000..aa1e4e41aa --- /dev/null +++ b/Lang/Berkeley-Logo/Babbage-problem @@ -0,0 +1 @@ +../../Task/Babbage-problem/Berkeley-Logo \ No newline at end of file diff --git a/Lang/Berkeley-Logo/Bell-numbers b/Lang/Berkeley-Logo/Bell-numbers new file mode 120000 index 0000000000..77a9bcb26c --- /dev/null +++ b/Lang/Berkeley-Logo/Bell-numbers @@ -0,0 +1 @@ +../../Task/Bell-numbers/Berkeley-Logo \ No newline at end of file diff --git a/Lang/Berkeley-Logo/Formatted-numeric-output b/Lang/Berkeley-Logo/Formatted-numeric-output new file mode 120000 index 0000000000..85a340c7e0 --- /dev/null +++ b/Lang/Berkeley-Logo/Formatted-numeric-output @@ -0,0 +1 @@ +../../Task/Formatted-numeric-output/Berkeley-Logo \ 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 3f502204f1..694f9a9437 100644 --- a/Lang/Binary-Lambda-Calculus/00-LANG.txt +++ b/Lang/Binary-Lambda-Calculus/00-LANG.txt @@ -5,7 +5,16 @@ }} {{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== * 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 +* https://gist.github.com/tromp/86b3184f852f65bfb814e3ab0987d861 + +Some implementations of BLC: +* [https://www.ioccc.org/2012/tromp/hint.html original tromp's implementation] for IOCCC, in pure ANSI C +* [https://github.com/tromp/AIT tromp's AIT], a project utilizing BLC for Information Theory research. Also includes a Haskell->BLC compiler and several other implementations +* [https://codeberg.org/aartaka/cl-blc aartaka's cl-blc], implementing BLC in Lisp + +==To do== +[[Tasks not implemented in Binary Lambda Calculus]] \ No newline at end of file diff --git a/Lang/Binary-Lambda-Calculus/A+B b/Lang/Binary-Lambda-Calculus/A+B new file mode 120000 index 0000000000..1a7c10c298 --- /dev/null +++ b/Lang/Binary-Lambda-Calculus/A+B @@ -0,0 +1 @@ +../../Task/A+B/Binary-Lambda-Calculus \ No newline at end of file diff --git a/Lang/Binary-Lambda-Calculus/Binary-digits b/Lang/Binary-Lambda-Calculus/Binary-digits new file mode 120000 index 0000000000..f74ad898bd --- /dev/null +++ b/Lang/Binary-Lambda-Calculus/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/Binary-Lambda-Calculus \ No newline at end of file diff --git a/Lang/Binary-Lambda-Calculus/Church-numerals b/Lang/Binary-Lambda-Calculus/Church-numerals new file mode 120000 index 0000000000..45f7ab14bd --- /dev/null +++ b/Lang/Binary-Lambda-Calculus/Church-numerals @@ -0,0 +1 @@ +../../Task/Church-numerals/Binary-Lambda-Calculus \ No newline at end of file diff --git a/Lang/Binary-Lambda-Calculus/Ethiopian-multiplication b/Lang/Binary-Lambda-Calculus/Ethiopian-multiplication new file mode 120000 index 0000000000..45465fad0c --- /dev/null +++ b/Lang/Binary-Lambda-Calculus/Ethiopian-multiplication @@ -0,0 +1 @@ +../../Task/Ethiopian-multiplication/Binary-Lambda-Calculus \ No newline at end of file diff --git a/Lang/Binary-Lambda-Calculus/Hailstone-sequence b/Lang/Binary-Lambda-Calculus/Hailstone-sequence new file mode 120000 index 0000000000..8bb334bdb3 --- /dev/null +++ b/Lang/Binary-Lambda-Calculus/Hailstone-sequence @@ -0,0 +1 @@ +../../Task/Hailstone-sequence/Binary-Lambda-Calculus \ No newline at end of file diff --git a/Lang/Binary-Lambda-Calculus/Sorting-algorithms-Merge-sort b/Lang/Binary-Lambda-Calculus/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..6a9a8bf4e0 --- /dev/null +++ b/Lang/Binary-Lambda-Calculus/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Binary-Lambda-Calculus \ No newline at end of file diff --git a/Lang/Blade/00-LANG.txt b/Lang/Blade/00-LANG.txt index f18c210bc3..71d6c9cdba 100644 --- a/Lang/Blade/00-LANG.txt +++ b/Lang/Blade/00-LANG.txt @@ -6,25 +6,13 @@ |parampass=value |LCT=yes}}{{language programming paradigm|Object-oriented}}{{language programming paradigm|functional}} -'''Blade''' is a simple, fast, clean and dynamic language that allows you to develop complex applications quickly. Blade emphasises algorithm over syntax and for this reason, it has a very small but powerful syntax set with a very natural feel. +'''Blade''' is a modern general-purpose programming language focused on enterprise Web, IoT, and secure application development. '''Blade''' offers a comprehensive set of tools and libraries out of the box leading to reduced reliance on third-party packages. -If you’ve ever had experience with a compiled language (e.g. [[C]]/[[C++]], [[Java]], etc), then one thing you’ll quickly notice (at least I did) was how much the whole process of write-compile-run-debug can be tedious and get in the way of creative programming and sometimes you even forget that mind-blowing algorithm you were going to write and take over the world in the whole process of compiling. +'''Blade''' comes equipped with an integrated package management system, simplifying the management of both internal and external dependencies and a self-hostable repository server making it ideal for private organisational and personal use. Its intuitive syntax and gentle learning curve ensure an accessible experience for developers of all skill levels. Leveraging the best features from JavaScript, Python, Ruby, and Dart, '''Blade''' provides a familiar and robust ecosystem that enables developers to harness the strengths of these languages effortlessly. -Sometimes, you just want to automate a few tasks, for example, I have a simple program to always remind me to get away from my laptop and eat something (you know how it is) and yet another one to suggest food for me. Do you find yourself needing this often? Do you know why you haven’t written it? Get out of your head, you are writing a compiled language! Compiling takes longer than the time it will take you to convince yourself that you need to eat. - -At other times, you have written this amazing program and you want users to be able to control it using a simple scripting language. I know… I know… there are many interpreted languages out there that will do the job just fine. Well… you still have one problem. Your users aren’t going to remember all the crazy going on in many of them (Yes [[Lua]]! I’m staring at you. What you gonna do about it?) - -Other times, we kind of find a very good solution to our problem in languages like [[Python]] (I must confess, even '''Blade''' did learn a lot of things from it), but the structure of such languages usually creates a new overhead in writing complex programs. It’s really difficult keeping a tab of indentations in such languages especially when you are not in a GUI IDE environment. I tried to work [[Python]] in nano, but man… it wasn’t easy. - -If you are feeling me, then Blade is just right for you. - -Blade is a simple language that has tried very much to learn from the mistake and successes of its predecessors. - -Blade is interpreted and simple like [[Python]] but with a more generic [[C]]-like syntax and a ridiculously simple Object-orientation similar to [[Dart]] and the granularity of [[JavaScript]] while still maintaining a very minimal syntax and keywords when compared to all of them. - -'''Blade is designed to be a memorizable language and the entire “language” can be learned in one sitting. However, Blade is as complete and powerful as any language can be and can be applied in the field of web, mobile, desktop, scientific, academic and research engineering to mention a few.''' +While '''Blade''' focuses on Web and IoT, it is also great for general software development. ==Links== -* [https://bladelang.com https://bladelang.com] +* [https://bladelang.org https://bladelang.org] * [https://github.com/blade-lang/blade https://github.com/blade-lang/blade] -* [https://bladelang.com/quick-learn.html Quick Language Introduction] \ No newline at end of file +* [https://bladelang.org/quick-learn.html Quick Language Introduction] \ No newline at end of file diff --git a/Lang/BlooP/00-LANG.txt b/Lang/BlooP/00-LANG.txt index 61490d18ec..d0fc3b449f 100644 --- a/Lang/BlooP/00-LANG.txt +++ b/Lang/BlooP/00-LANG.txt @@ -20,7 +20,7 @@ The best way to explain BlooP is really just to look at some examples, so here a Find the factorial of N: - + DEFINE PROCEDURE FACTORIAL [N]: BLOCK 0: BEGIN OUTPUT <= 1; @@ -31,11 +31,11 @@ BLOCK 0: BEGIN CELL(0) <= CELL(0) + 1; BLOCK 1: END; BLOCK 0: END. - - + + subtraction (this is the only way to do it, since it must be defined in terms of addition): - + DEFINE PROCEDURE MINUS [M,N]: BLOCK 0: BEGIN OUTPUT <= 0; @@ -48,12 +48,12 @@ BLOCK 0: BEGIN OUTPUT <= OUTPUT + 1; BLOCK 1: END; BLOCK 0: END. - + Nim game in BlooP. Since user input is not possible in most implementations, this version uses a procedure which takes 3 numbers. - + DEFINE PROCEDURE ''DIVIDE'' [A,B]: BLOCK 0: BEGIN IF A < B, THEN: @@ -145,7 +145,7 @@ BLOCK 0: BEGIN BLOCK 0: END. PLAY_GAME [2,1,1]; - + {{out}}
diff --git a/Lang/BootBASIC/Empty-program b/Lang/BootBASIC/Empty-program
deleted file mode 120000
index 5aaffbd057..0000000000
--- a/Lang/BootBASIC/Empty-program
+++ /dev/null
@@ -1 +0,0 @@
-../../Task/Empty-program/BootBASIC
\ No newline at end of file
diff --git a/Lang/Bracmat/Miller-Rabin-primality-test b/Lang/Bracmat/Miller-Rabin-primality-test
deleted file mode 120000
index 7c953943cd..0000000000
--- a/Lang/Bracmat/Miller-Rabin-primality-test
+++ /dev/null
@@ -1 +0,0 @@
-../../Task/Miller-Rabin-primality-test/Bracmat
\ No newline at end of file
diff --git a/Lang/Brainf---/00-LANG.txt b/Lang/Brainf---/00-LANG.txt
index 7b702b4d45..d9ca931bf4 100644
--- a/Lang/Brainf---/00-LANG.txt
+++ b/Lang/Brainf---/00-LANG.txt
@@ -63,10 +63,10 @@ BUT due to vehement opposition to the name [http://esolangs.org/wiki/Cupid vario
 ==See also==
 * [[Rosetta Code:Brainf***]]  ( why some people call it BF :)
 * [[RCBF]] - BF interpreters as a Rosetta Code task
-
+* [https://esolangs.org/wiki/brainfuck_algorithms brainf*** algorithms]
 ==Citations==
 
-* [[eso:Brainfuck|Esoteric languages wiki entry]]
+* [https://esolangs.org/wiki/Brainfuck Esoteric languages wiki entry]
 *[[wp:Brainfuck|Wikipedia entry on Brainf***]]
 * [http://dmoz.org/Computers/Programming/Languages/Brainfuck/ DMOZ Brainf*** category]
 * [http://www.iwriteiam.nl/Ha_BF.html Brainf*** tutorial]
diff --git a/Lang/Brainf---/Loops-While b/Lang/Brainf---/Loops-While
new file mode 120000
index 0000000000..057717ea5a
--- /dev/null
+++ b/Lang/Brainf---/Loops-While
@@ -0,0 +1 @@
+../../Task/Loops-While/Brainf---
\ No newline at end of file
diff --git a/Lang/Bruijn/Harmonic-series b/Lang/Bruijn/Harmonic-series
new file mode 120000
index 0000000000..b39ae4ae88
--- /dev/null
+++ b/Lang/Bruijn/Harmonic-series
@@ -0,0 +1 @@
+../../Task/Harmonic-series/Bruijn
\ No newline at end of file
diff --git a/Lang/Bruijn/Towers-of-Hanoi b/Lang/Bruijn/Towers-of-Hanoi
new file mode 120000
index 0000000000..96dafe6af8
--- /dev/null
+++ b/Lang/Bruijn/Towers-of-Hanoi
@@ -0,0 +1 @@
+../../Task/Towers-of-Hanoi/Bruijn
\ No newline at end of file
diff --git a/Lang/C++/Add-a-variable-to-a-class-instance-at-runtime b/Lang/C++/Add-a-variable-to-a-class-instance-at-runtime
new file mode 120000
index 0000000000..61888079c6
--- /dev/null
+++ b/Lang/C++/Add-a-variable-to-a-class-instance-at-runtime
@@ -0,0 +1 @@
+../../Task/Add-a-variable-to-a-class-instance-at-runtime/C++
\ No newline at end of file
diff --git a/Lang/C++/Bioinformatics-base-count b/Lang/C++/Bioinformatics-base-count
deleted file mode 120000
index e0584bb6b7..0000000000
--- a/Lang/C++/Bioinformatics-base-count
+++ /dev/null
@@ -1 +0,0 @@
-../../Task/Bioinformatics-base-count/C++
\ No newline at end of file
diff --git a/Lang/C++/Bitcoin-address-validation b/Lang/C++/Bitcoin-address-validation
new file mode 120000
index 0000000000..fdb6fa9bf8
--- /dev/null
+++ b/Lang/C++/Bitcoin-address-validation
@@ -0,0 +1 @@
+../../Task/Bitcoin-address-validation/C++
\ No newline at end of file
diff --git a/Lang/C++/Bitcoin-public-point-to-address b/Lang/C++/Bitcoin-public-point-to-address
new file mode 120000
index 0000000000..1229c8b30f
--- /dev/null
+++ b/Lang/C++/Bitcoin-public-point-to-address
@@ -0,0 +1 @@
+../../Task/Bitcoin-public-point-to-address/C++
\ No newline at end of file
diff --git a/Lang/C++/Bitwise-IO b/Lang/C++/Bitwise-IO
new file mode 120000
index 0000000000..0612736bad
--- /dev/null
+++ b/Lang/C++/Bitwise-IO
@@ -0,0 +1 @@
+../../Task/Bitwise-IO/C++
\ No newline at end of file
diff --git a/Lang/C++/Catmull-Clark-subdivision-surface b/Lang/C++/Catmull-Clark-subdivision-surface
new file mode 120000
index 0000000000..dbaa0ac83b
--- /dev/null
+++ b/Lang/C++/Catmull-Clark-subdivision-surface
@@ -0,0 +1 @@
+../../Task/Catmull-Clark-subdivision-surface/C++
\ No newline at end of file
diff --git a/Lang/C++/Commatizing-numbers b/Lang/C++/Commatizing-numbers
new file mode 120000
index 0000000000..96b27f445d
--- /dev/null
+++ b/Lang/C++/Commatizing-numbers
@@ -0,0 +1 @@
+../../Task/Commatizing-numbers/C++
\ No newline at end of file
diff --git a/Lang/C++/Compare-sorting-algorithms-performance b/Lang/C++/Compare-sorting-algorithms-performance
new file mode 120000
index 0000000000..8616fdb726
--- /dev/null
+++ b/Lang/C++/Compare-sorting-algorithms-performance
@@ -0,0 +1 @@
+../../Task/Compare-sorting-algorithms-performance/C++
\ No newline at end of file
diff --git a/Lang/C++/Compiler-virtual-machine-interpreter b/Lang/C++/Compiler-virtual-machine-interpreter
new file mode 120000
index 0000000000..94f3cd637b
--- /dev/null
+++ b/Lang/C++/Compiler-virtual-machine-interpreter
@@ -0,0 +1 @@
+../../Task/Compiler-virtual-machine-interpreter/C++
\ No newline at end of file
diff --git a/Lang/C++/Currency b/Lang/C++/Currency
new file mode 120000
index 0000000000..ae0e8d6190
--- /dev/null
+++ b/Lang/C++/Currency
@@ -0,0 +1 @@
+../../Task/Currency/C++
\ No newline at end of file
diff --git a/Lang/C++/Deconvolution-2D+ b/Lang/C++/Deconvolution-2D+
new file mode 120000
index 0000000000..dba078e8e0
--- /dev/null
+++ b/Lang/C++/Deconvolution-2D+
@@ -0,0 +1 @@
+../../Task/Deconvolution-2D+/C++
\ No newline at end of file
diff --git a/Lang/C++/Documentation b/Lang/C++/Documentation
new file mode 120000
index 0000000000..dd69dde201
--- /dev/null
+++ b/Lang/C++/Documentation
@@ -0,0 +1 @@
+../../Task/Documentation/C++
\ No newline at end of file
diff --git a/Lang/C++/Dominoes b/Lang/C++/Dominoes
new file mode 120000
index 0000000000..5c79b6947b
--- /dev/null
+++ b/Lang/C++/Dominoes
@@ -0,0 +1 @@
+../../Task/Dominoes/C++
\ No newline at end of file
diff --git a/Lang/C++/Euclid-Mullin-sequence b/Lang/C++/Euclid-Mullin-sequence
new file mode 120000
index 0000000000..f743f51e54
--- /dev/null
+++ b/Lang/C++/Euclid-Mullin-sequence
@@ -0,0 +1 @@
+../../Task/Euclid-Mullin-sequence/C++
\ No newline at end of file
diff --git a/Lang/C++/Extend-your-language b/Lang/C++/Extend-your-language
new file mode 120000
index 0000000000..da1eb035c9
--- /dev/null
+++ b/Lang/C++/Extend-your-language
@@ -0,0 +1 @@
+../../Task/Extend-your-language/C++
\ No newline at end of file
diff --git a/Lang/C++/Extreme-floating-point-values b/Lang/C++/Extreme-floating-point-values
new file mode 120000
index 0000000000..36dd74b460
--- /dev/null
+++ b/Lang/C++/Extreme-floating-point-values
@@ -0,0 +1 @@
+../../Task/Extreme-floating-point-values/C++
\ No newline at end of file
diff --git a/Lang/C++/Factorial-base-numbers-indexing-permutations-of-a-collection b/Lang/C++/Factorial-base-numbers-indexing-permutations-of-a-collection
new file mode 120000
index 0000000000..9b984d5ea4
--- /dev/null
+++ b/Lang/C++/Factorial-base-numbers-indexing-permutations-of-a-collection
@@ -0,0 +1 @@
+../../Task/Factorial-base-numbers-indexing-permutations-of-a-collection/C++
\ No newline at end of file
diff --git a/Lang/C++/First-class-environments b/Lang/C++/First-class-environments
new file mode 120000
index 0000000000..652816150b
--- /dev/null
+++ b/Lang/C++/First-class-environments
@@ -0,0 +1 @@
+../../Task/First-class-environments/C++
\ No newline at end of file
diff --git a/Lang/C++/French-Republican-calendar b/Lang/C++/French-Republican-calendar
new file mode 120000
index 0000000000..b361af00f6
--- /dev/null
+++ b/Lang/C++/French-Republican-calendar
@@ -0,0 +1 @@
+../../Task/French-Republican-calendar/C++
\ No newline at end of file
diff --git a/Lang/C++/Functional-coverage-tree b/Lang/C++/Functional-coverage-tree
new file mode 120000
index 0000000000..06e1a4bfaf
--- /dev/null
+++ b/Lang/C++/Functional-coverage-tree
@@ -0,0 +1 @@
+../../Task/Functional-coverage-tree/C++
\ No newline at end of file
diff --git a/Lang/C++/Im-a-software-engineer-get-me-out-of-here b/Lang/C++/Im-a-software-engineer-get-me-out-of-here
new file mode 120000
index 0000000000..7c9de1375f
--- /dev/null
+++ b/Lang/C++/Im-a-software-engineer-get-me-out-of-here
@@ -0,0 +1 @@
+../../Task/Im-a-software-engineer-get-me-out-of-here/C++
\ No newline at end of file
diff --git a/Lang/C++/MD5-Implementation b/Lang/C++/MD5-Implementation
new file mode 120000
index 0000000000..b31aca0e67
--- /dev/null
+++ b/Lang/C++/MD5-Implementation
@@ -0,0 +1 @@
+../../Task/MD5-Implementation/C++
\ No newline at end of file
diff --git a/Lang/C++/Meissel-Mertens-constant b/Lang/C++/Meissel-Mertens-constant
deleted file mode 120000
index 3242c970c7..0000000000
--- a/Lang/C++/Meissel-Mertens-constant
+++ /dev/null
@@ -1 +0,0 @@
-../../Task/Meissel-Mertens-constant/C++
\ No newline at end of file
diff --git a/Lang/C++/Miller-Rabin-primality-test b/Lang/C++/Miller-Rabin-primality-test
deleted file mode 120000
index 615ee001e8..0000000000
--- a/Lang/C++/Miller-Rabin-primality-test
+++ /dev/null
@@ -1 +0,0 @@
-../../Task/Miller-Rabin-primality-test/C++
\ No newline at end of file
diff --git a/Lang/C++/Natural-sorting b/Lang/C++/Natural-sorting
new file mode 120000
index 0000000000..221a15ac6d
--- /dev/null
+++ b/Lang/C++/Natural-sorting
@@ -0,0 +1 @@
+../../Task/Natural-sorting/C++
\ No newline at end of file
diff --git a/Lang/C++/Non-transitive-dice b/Lang/C++/Non-transitive-dice
new file mode 120000
index 0000000000..2c6300fda7
--- /dev/null
+++ b/Lang/C++/Non-transitive-dice
@@ -0,0 +1 @@
+../../Task/Non-transitive-dice/C++
\ No newline at end of file
diff --git a/Lang/C++/P-Adic-square-roots b/Lang/C++/P-Adic-square-roots
new file mode 120000
index 0000000000..a25d0f7d5c
--- /dev/null
+++ b/Lang/C++/P-Adic-square-roots
@@ -0,0 +1 @@
+../../Task/P-Adic-square-roots/C++
\ No newline at end of file
diff --git a/Lang/C++/Quaternion-type b/Lang/C++/Quaternion-type
deleted file mode 120000
index 053fd1142a..0000000000
--- a/Lang/C++/Quaternion-type
+++ /dev/null
@@ -1 +0,0 @@
-../../Task/Quaternion-type/C++
\ No newline at end of file
diff --git a/Lang/C++/Rendezvous b/Lang/C++/Rendezvous
new file mode 120000
index 0000000000..b1c8af4bea
--- /dev/null
+++ b/Lang/C++/Rendezvous
@@ -0,0 +1 @@
+../../Task/Rendezvous/C++
\ No newline at end of file
diff --git a/Lang/C++/Simple-database b/Lang/C++/Simple-database
new file mode 120000
index 0000000000..60394bf013
--- /dev/null
+++ b/Lang/C++/Simple-database
@@ -0,0 +1 @@
+../../Task/Simple-database/C++
\ No newline at end of file
diff --git a/Lang/C++/Sort-an-outline-at-every-level b/Lang/C++/Sort-an-outline-at-every-level
new file mode 120000
index 0000000000..5467a50bff
--- /dev/null
+++ b/Lang/C++/Sort-an-outline-at-every-level
@@ -0,0 +1 @@
+../../Task/Sort-an-outline-at-every-level/C++
\ No newline at end of file
diff --git a/Lang/C++/Sorting-Algorithms-Circle-Sort b/Lang/C++/Sorting-Algorithms-Circle-Sort
deleted file mode 120000
index 91c7b06653..0000000000
--- a/Lang/C++/Sorting-Algorithms-Circle-Sort
+++ /dev/null
@@ -1 +0,0 @@
-../../Task/Sorting-Algorithms-Circle-Sort/C++
\ No newline at end of file
diff --git a/Lang/C++/Strassens-algorithm b/Lang/C++/Strassens-algorithm
new file mode 120000
index 0000000000..1423f44a39
--- /dev/null
+++ b/Lang/C++/Strassens-algorithm
@@ -0,0 +1 @@
+../../Task/Strassens-algorithm/C++
\ No newline at end of file
diff --git a/Lang/C++/URL-parser b/Lang/C++/URL-parser
new file mode 120000
index 0000000000..c94d78f772
--- /dev/null
+++ b/Lang/C++/URL-parser
@@ -0,0 +1 @@
+../../Task/URL-parser/C++
\ No newline at end of file
diff --git a/Lang/C++/UTF-8-encode-and-decode b/Lang/C++/UTF-8-encode-and-decode
new file mode 120000
index 0000000000..a3942ee81c
--- /dev/null
+++ b/Lang/C++/UTF-8-encode-and-decode
@@ -0,0 +1 @@
+../../Task/UTF-8-encode-and-decode/C++
\ No newline at end of file
diff --git a/Lang/C++/Ukkonen-s-suffix-tree-construction b/Lang/C++/Ukkonen-s-suffix-tree-construction
new file mode 120000
index 0000000000..3dffa49793
--- /dev/null
+++ b/Lang/C++/Ukkonen-s-suffix-tree-construction
@@ -0,0 +1 @@
+../../Task/Ukkonen-s-suffix-tree-construction/C++
\ No newline at end of file
diff --git a/Lang/C++/Update-a-configuration-file b/Lang/C++/Update-a-configuration-file
new file mode 120000
index 0000000000..dd78746576
--- /dev/null
+++ b/Lang/C++/Update-a-configuration-file
@@ -0,0 +1 @@
+../../Task/Update-a-configuration-file/C++
\ No newline at end of file
diff --git a/Lang/C-sharp/00-LANG.txt b/Lang/C-sharp/00-LANG.txt
index 17083312b1..2ffb00e180 100644
--- a/Lang/C-sharp/00-LANG.txt
+++ b/Lang/C-sharp/00-LANG.txt
@@ -17,6 +17,10 @@
 ==Citations==
 *[[wp:C_Sharp_(programming_language)|Wikipedia:C#]]
 
+== External links ==
+=== Online editors and compilers ===
+*[https://www.onlinegdb.com/ GDB Online Compiler] (Select C#)
+
 {{language programming paradigm|Imperative}}
 {{language programming paradigm|Object-oriented}}
 {{language programming paradigm|Generic}}
diff --git a/Lang/C-sharp/ADFGVX-cipher b/Lang/C-sharp/ADFGVX-cipher
new file mode 120000
index 0000000000..1bd5856497
--- /dev/null
+++ b/Lang/C-sharp/ADFGVX-cipher
@@ -0,0 +1 @@
+../../Task/ADFGVX-cipher/C-sharp
\ No newline at end of file
diff --git a/Lang/C-sharp/ASCII-art-diagram-converter b/Lang/C-sharp/ASCII-art-diagram-converter
new file mode 120000
index 0000000000..a3c0a49ccd
--- /dev/null
+++ b/Lang/C-sharp/ASCII-art-diagram-converter
@@ -0,0 +1 @@
+../../Task/ASCII-art-diagram-converter/C-sharp
\ No newline at end of file
diff --git a/Lang/C-sharp/Additive-primes b/Lang/C-sharp/Additive-primes
new file mode 120000
index 0000000000..d958846baf
--- /dev/null
+++ b/Lang/C-sharp/Additive-primes
@@ -0,0 +1 @@
+../../Task/Additive-primes/C-sharp
\ No newline at end of file
diff --git a/Lang/C-sharp/Arithmetic-derivative b/Lang/C-sharp/Arithmetic-derivative
new file mode 120000
index 0000000000..99fc50446f
--- /dev/null
+++ b/Lang/C-sharp/Arithmetic-derivative
@@ -0,0 +1 @@
+../../Task/Arithmetic-derivative/C-sharp
\ No newline at end of file
diff --git a/Lang/C-sharp/Boyer-Moore-string-search b/Lang/C-sharp/Boyer-Moore-string-search
new file mode 120000
index 0000000000..6d8ebe0502
--- /dev/null
+++ b/Lang/C-sharp/Boyer-Moore-string-search
@@ -0,0 +1 @@
+../../Task/Boyer-Moore-string-search/C-sharp
\ No newline at end of file
diff --git a/Lang/C-sharp/Calkin-Wilf-sequence b/Lang/C-sharp/Calkin-Wilf-sequence
new file mode 120000
index 0000000000..75d6e98750
--- /dev/null
+++ b/Lang/C-sharp/Calkin-Wilf-sequence
@@ -0,0 +1 @@
+../../Task/Calkin-Wilf-sequence/C-sharp
\ No newline at end of file
diff --git a/Lang/C-sharp/Camel-case-and-snake-case b/Lang/C-sharp/Camel-case-and-snake-case
new file mode 120000
index 0000000000..0b673ec8ed
--- /dev/null
+++ b/Lang/C-sharp/Camel-case-and-snake-case
@@ -0,0 +1 @@
+../../Task/Camel-case-and-snake-case/C-sharp
\ No newline at end of file
diff --git a/Lang/C-sharp/Cistercian-numerals b/Lang/C-sharp/Cistercian-numerals
new file mode 120000
index 0000000000..d482ff0533
--- /dev/null
+++ b/Lang/C-sharp/Cistercian-numerals
@@ -0,0 +1 @@
+../../Task/Cistercian-numerals/C-sharp
\ No newline at end of file
diff --git a/Lang/C-sharp/Colorful-numbers b/Lang/C-sharp/Colorful-numbers
new file mode 120000
index 0000000000..b35a72c815
--- /dev/null
+++ b/Lang/C-sharp/Colorful-numbers
@@ -0,0 +1 @@
+../../Task/Colorful-numbers/C-sharp
\ No newline at end of file
diff --git a/Lang/C-sharp/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- b/Lang/C-sharp/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n-
new file mode 120000
index 0000000000..2adfbd6635
--- /dev/null
+++ b/Lang/C-sharp/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n-
@@ -0,0 +1 @@
+../../Task/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n-/C-sharp
\ No newline at end of file
diff --git a/Lang/C-sharp/Cyclops-numbers b/Lang/C-sharp/Cyclops-numbers
new file mode 120000
index 0000000000..c4380e8ccd
--- /dev/null
+++ b/Lang/C-sharp/Cyclops-numbers
@@ -0,0 +1 @@
+../../Task/Cyclops-numbers/C-sharp
\ No newline at end of file
diff --git a/Lang/C-sharp/Elliptic-Curve-Digital-Signature-Algorithm b/Lang/C-sharp/Elliptic-Curve-Digital-Signature-Algorithm
new file mode 120000
index 0000000000..82412a8f32
--- /dev/null
+++ b/Lang/C-sharp/Elliptic-Curve-Digital-Signature-Algorithm
@@ -0,0 +1 @@
+../../Task/Elliptic-Curve-Digital-Signature-Algorithm/C-sharp
\ No newline at end of file
diff --git a/Lang/C-sharp/Execute-a-Markov-algorithm b/Lang/C-sharp/Execute-a-Markov-algorithm
new file mode 120000
index 0000000000..fac2e3f425
--- /dev/null
+++ b/Lang/C-sharp/Execute-a-Markov-algorithm
@@ -0,0 +1 @@
+../../Task/Execute-a-Markov-algorithm/C-sharp
\ No newline at end of file
diff --git a/Lang/C-sharp/Extensible-prime-generator b/Lang/C-sharp/Extensible-prime-generator
new file mode 120000
index 0000000000..1e4636d3bb
--- /dev/null
+++ b/Lang/C-sharp/Extensible-prime-generator
@@ -0,0 +1 @@
+../../Task/Extensible-prime-generator/C-sharp
\ No newline at end of file
diff --git a/Lang/C-sharp/File-extension-is-in-extensions-list b/Lang/C-sharp/File-extension-is-in-extensions-list
new file mode 120000
index 0000000000..caec470709
--- /dev/null
+++ b/Lang/C-sharp/File-extension-is-in-extensions-list
@@ -0,0 +1 @@
+../../Task/File-extension-is-in-extensions-list/C-sharp
\ No newline at end of file
diff --git a/Lang/C-sharp/Find-if-a-point-is-within-a-triangle b/Lang/C-sharp/Find-if-a-point-is-within-a-triangle
new file mode 120000
index 0000000000..0c9dec87d9
--- /dev/null
+++ b/Lang/C-sharp/Find-if-a-point-is-within-a-triangle
@@ -0,0 +1 @@
+../../Task/Find-if-a-point-is-within-a-triangle/C-sharp
\ No newline at end of file
diff --git a/Lang/C-sharp/Gotchas b/Lang/C-sharp/Gotchas
new file mode 120000
index 0000000000..c20938cf21
--- /dev/null
+++ b/Lang/C-sharp/Gotchas
@@ -0,0 +1 @@
+../../Task/Gotchas/C-sharp
\ No newline at end of file
diff --git a/Lang/C-sharp/Index-finite-lists-of-positive-integers b/Lang/C-sharp/Index-finite-lists-of-positive-integers
new file mode 120000
index 0000000000..692e611ddc
--- /dev/null
+++ b/Lang/C-sharp/Index-finite-lists-of-positive-integers
@@ -0,0 +1 @@
+../../Task/Index-finite-lists-of-positive-integers/C-sharp
\ No newline at end of file
diff --git a/Lang/C-sharp/K-d-tree b/Lang/C-sharp/K-d-tree
new file mode 120000
index 0000000000..9ea6355b83
--- /dev/null
+++ b/Lang/C-sharp/K-d-tree
@@ -0,0 +1 @@
+../../Task/K-d-tree/C-sharp
\ No newline at end of file
diff --git a/Lang/C-sharp/Longest-string-challenge b/Lang/C-sharp/Longest-string-challenge
new file mode 120000
index 0000000000..bd57b65702
--- /dev/null
+++ b/Lang/C-sharp/Longest-string-challenge
@@ -0,0 +1 @@
+../../Task/Longest-string-challenge/C-sharp
\ No newline at end of file
diff --git a/Lang/C-sharp/M-bius-function b/Lang/C-sharp/M-bius-function
new file mode 120000
index 0000000000..56f84fb14c
--- /dev/null
+++ b/Lang/C-sharp/M-bius-function
@@ -0,0 +1 @@
+../../Task/M-bius-function/C-sharp
\ No newline at end of file
diff --git a/Lang/C-sharp/Miller-Rabin-primality-test b/Lang/C-sharp/Miller-Rabin-primality-test
deleted file mode 120000
index 4d27fefcbd..0000000000
--- a/Lang/C-sharp/Miller-Rabin-primality-test
+++ /dev/null
@@ -1 +0,0 @@
-../../Task/Miller-Rabin-primality-test/C-sharp
\ No newline at end of file
diff --git a/Lang/C-sharp/P-Adic-numbers-basic b/Lang/C-sharp/P-Adic-numbers-basic
new file mode 120000
index 0000000000..564565afb6
--- /dev/null
+++ b/Lang/C-sharp/P-Adic-numbers-basic
@@ -0,0 +1 @@
+../../Task/P-Adic-numbers-basic/C-sharp
\ No newline at end of file
diff --git a/Lang/C-sharp/Periodic-table b/Lang/C-sharp/Periodic-table
new file mode 120000
index 0000000000..97d676b17d
--- /dev/null
+++ b/Lang/C-sharp/Periodic-table
@@ -0,0 +1 @@
+../../Task/Periodic-table/C-sharp
\ No newline at end of file
diff --git a/Lang/C-sharp/Quaternion-type b/Lang/C-sharp/Quaternion-type
deleted file mode 120000
index 53c4bd6185..0000000000
--- a/Lang/C-sharp/Quaternion-type
+++ /dev/null
@@ -1 +0,0 @@
-../../Task/Quaternion-type/C-sharp
\ No newline at end of file
diff --git a/Lang/C-sharp/Reflection-Get-source b/Lang/C-sharp/Reflection-Get-source
new file mode 120000
index 0000000000..a8b2f45e4c
--- /dev/null
+++ b/Lang/C-sharp/Reflection-Get-source
@@ -0,0 +1 @@
+../../Task/Reflection-Get-source/C-sharp
\ No newline at end of file
diff --git a/Lang/C-sharp/Sequence:-smallest-number-with-exactly-n-divisors b/Lang/C-sharp/Sequence:-smallest-number-with-exactly-n-divisors
new file mode 120000
index 0000000000..71508d1c44
--- /dev/null
+++ b/Lang/C-sharp/Sequence:-smallest-number-with-exactly-n-divisors
@@ -0,0 +1 @@
+../../Task/Sequence:-smallest-number-with-exactly-n-divisors/C-sharp
\ No newline at end of file
diff --git a/Lang/C-sharp/Sorting-Algorithms-Circle-Sort b/Lang/C-sharp/Sorting-Algorithms-Circle-Sort
deleted file mode 120000
index 6f1414c420..0000000000
--- a/Lang/C-sharp/Sorting-Algorithms-Circle-Sort
+++ /dev/null
@@ -1 +0,0 @@
-../../Task/Sorting-Algorithms-Circle-Sort/C-sharp
\ No newline at end of file
diff --git a/Lang/C-sharp/Square-free-integers b/Lang/C-sharp/Square-free-integers
new file mode 120000
index 0000000000..6cabcf20b3
--- /dev/null
+++ b/Lang/C-sharp/Square-free-integers
@@ -0,0 +1 @@
+../../Task/Square-free-integers/C-sharp
\ No newline at end of file
diff --git a/Lang/C-sharp/Strassens-algorithm b/Lang/C-sharp/Strassens-algorithm
new file mode 120000
index 0000000000..45fd91dfa9
--- /dev/null
+++ b/Lang/C-sharp/Strassens-algorithm
@@ -0,0 +1 @@
+../../Task/Strassens-algorithm/C-sharp
\ No newline at end of file
diff --git a/Lang/C-sharp/Summarize-primes b/Lang/C-sharp/Summarize-primes
new file mode 120000
index 0000000000..de1b22714d
--- /dev/null
+++ b/Lang/C-sharp/Summarize-primes
@@ -0,0 +1 @@
+../../Task/Summarize-primes/C-sharp
\ No newline at end of file
diff --git a/Lang/C-sharp/Tau-function b/Lang/C-sharp/Tau-function
new file mode 120000
index 0000000000..aa9069413d
--- /dev/null
+++ b/Lang/C-sharp/Tau-function
@@ -0,0 +1 @@
+../../Task/Tau-function/C-sharp
\ No newline at end of file
diff --git a/Lang/C-sharp/Tau-number b/Lang/C-sharp/Tau-number
new file mode 120000
index 0000000000..0980d5ce28
--- /dev/null
+++ b/Lang/C-sharp/Tau-number
@@ -0,0 +1 @@
+../../Task/Tau-number/C-sharp
\ No newline at end of file
diff --git a/Lang/C-sharp/Tree-from-nesting-levels b/Lang/C-sharp/Tree-from-nesting-levels
new file mode 120000
index 0000000000..e46b1553ea
--- /dev/null
+++ b/Lang/C-sharp/Tree-from-nesting-levels
@@ -0,0 +1 @@
+../../Task/Tree-from-nesting-levels/C-sharp
\ No newline at end of file
diff --git a/Lang/C-sharp/Ultra-useful-primes b/Lang/C-sharp/Ultra-useful-primes
new file mode 120000
index 0000000000..2258e0373a
--- /dev/null
+++ b/Lang/C-sharp/Ultra-useful-primes
@@ -0,0 +1 @@
+../../Task/Ultra-useful-primes/C-sharp
\ No newline at end of file
diff --git a/Lang/C-sharp/Variable-declaration-reset b/Lang/C-sharp/Variable-declaration-reset
new file mode 120000
index 0000000000..ec0809da88
--- /dev/null
+++ b/Lang/C-sharp/Variable-declaration-reset
@@ -0,0 +1 @@
+../../Task/Variable-declaration-reset/C-sharp
\ No newline at end of file
diff --git a/Lang/C-sharp/Vogels-approximation-method b/Lang/C-sharp/Vogels-approximation-method
new file mode 120000
index 0000000000..bb638d067a
--- /dev/null
+++ b/Lang/C-sharp/Vogels-approximation-method
@@ -0,0 +1 @@
+../../Task/Vogels-approximation-method/C-sharp
\ No newline at end of file
diff --git a/Lang/C-sharp/Yellowstone-sequence b/Lang/C-sharp/Yellowstone-sequence
new file mode 120000
index 0000000000..793ce587ba
--- /dev/null
+++ b/Lang/C-sharp/Yellowstone-sequence
@@ -0,0 +1 @@
+../../Task/Yellowstone-sequence/C-sharp
\ No newline at end of file
diff --git a/Lang/C/Achilles-numbers b/Lang/C/Achilles-numbers
new file mode 120000
index 0000000000..5c3326676b
--- /dev/null
+++ b/Lang/C/Achilles-numbers
@@ -0,0 +1 @@
+../../Task/Achilles-numbers/C
\ No newline at end of file
diff --git a/Lang/C/Bioinformatics-base-count b/Lang/C/Bioinformatics-base-count
deleted file mode 120000
index 4819495149..0000000000
--- a/Lang/C/Bioinformatics-base-count
+++ /dev/null
@@ -1 +0,0 @@
-../../Task/Bioinformatics-base-count/C
\ No newline at end of file
diff --git a/Lang/C/Color-wheel b/Lang/C/Color-wheel
new file mode 120000
index 0000000000..9d6561adcd
--- /dev/null
+++ b/Lang/C/Color-wheel
@@ -0,0 +1 @@
+../../Task/Color-wheel/C
\ No newline at end of file
diff --git a/Lang/C/Distance-and-Bearing b/Lang/C/Distance-and-Bearing
new file mode 120000
index 0000000000..4496c69ac6
--- /dev/null
+++ b/Lang/C/Distance-and-Bearing
@@ -0,0 +1 @@
+../../Task/Distance-and-Bearing/C
\ No newline at end of file
diff --git a/Lang/C/Dynamic-variable-names b/Lang/C/Dynamic-variable-names
new file mode 120000
index 0000000000..278fe3b232
--- /dev/null
+++ b/Lang/C/Dynamic-variable-names
@@ -0,0 +1 @@
+../../Task/Dynamic-variable-names/C
\ No newline at end of file
diff --git a/Lang/C/Execute-Computer-Zero b/Lang/C/Execute-Computer-Zero
new file mode 120000
index 0000000000..c10597c078
--- /dev/null
+++ b/Lang/C/Execute-Computer-Zero
@@ -0,0 +1 @@
+../../Task/Execute-Computer-Zero/C
\ No newline at end of file
diff --git a/Lang/C/Harmonic-series b/Lang/C/Harmonic-series
new file mode 120000
index 0000000000..dfebedc2c8
--- /dev/null
+++ b/Lang/C/Harmonic-series
@@ -0,0 +1 @@
+../../Task/Harmonic-series/C
\ No newline at end of file
diff --git a/Lang/C/History-variables b/Lang/C/History-variables
new file mode 120000
index 0000000000..3a73616359
--- /dev/null
+++ b/Lang/C/History-variables
@@ -0,0 +1 @@
+../../Task/History-variables/C
\ No newline at end of file
diff --git a/Lang/C/Hunt-the-Wumpus b/Lang/C/Hunt-the-Wumpus
new file mode 120000
index 0000000000..e7186ced48
--- /dev/null
+++ b/Lang/C/Hunt-the-Wumpus
@@ -0,0 +1 @@
+../../Task/Hunt-the-Wumpus/C
\ No newline at end of file
diff --git a/Lang/C/Magic-constant b/Lang/C/Magic-constant
new file mode 120000
index 0000000000..3d29fd6624
--- /dev/null
+++ b/Lang/C/Magic-constant
@@ -0,0 +1 @@
+../../Task/Magic-constant/C
\ No newline at end of file
diff --git a/Lang/C/Miller-Rabin-primality-test b/Lang/C/Miller-Rabin-primality-test
deleted file mode 120000
index b9ab762a9c..0000000000
--- a/Lang/C/Miller-Rabin-primality-test
+++ /dev/null
@@ -1 +0,0 @@
-../../Task/Miller-Rabin-primality-test/C
\ No newline at end of file
diff --git a/Lang/C/Nested-templated-data b/Lang/C/Nested-templated-data
new file mode 120000
index 0000000000..ef78f3cb0c
--- /dev/null
+++ b/Lang/C/Nested-templated-data
@@ -0,0 +1 @@
+../../Task/Nested-templated-data/C
\ No newline at end of file
diff --git a/Lang/C/One-time-pad b/Lang/C/One-time-pad
new file mode 120000
index 0000000000..e0845d9058
--- /dev/null
+++ b/Lang/C/One-time-pad
@@ -0,0 +1 @@
+../../Task/One-time-pad/C
\ No newline at end of file
diff --git a/Lang/C/Pig-the-dice-game-Player b/Lang/C/Pig-the-dice-game-Player
new file mode 120000
index 0000000000..28ecb509a8
--- /dev/null
+++ b/Lang/C/Pig-the-dice-game-Player
@@ -0,0 +1 @@
+../../Task/Pig-the-dice-game-Player/C
\ No newline at end of file
diff --git a/Lang/C/Quaternion-type b/Lang/C/Quaternion-type
deleted file mode 120000
index 25d9910755..0000000000
--- a/Lang/C/Quaternion-type
+++ /dev/null
@@ -1 +0,0 @@
-../../Task/Quaternion-type/C
\ No newline at end of file
diff --git a/Lang/C/Sleeping-Beauty-problem b/Lang/C/Sleeping-Beauty-problem
new file mode 120000
index 0000000000..193e808670
--- /dev/null
+++ b/Lang/C/Sleeping-Beauty-problem
@@ -0,0 +1 @@
+../../Task/Sleeping-Beauty-problem/C
\ No newline at end of file
diff --git a/Lang/C/Sorting-Algorithms-Circle-Sort b/Lang/C/Sorting-Algorithms-Circle-Sort
deleted file mode 120000
index 335574f406..0000000000
--- a/Lang/C/Sorting-Algorithms-Circle-Sort
+++ /dev/null
@@ -1 +0,0 @@
-../../Task/Sorting-Algorithms-Circle-Sort/C
\ No newline at end of file
diff --git a/Lang/C3/Binary-digits b/Lang/C3/Binary-digits
new file mode 120000
index 0000000000..34a04afae2
--- /dev/null
+++ b/Lang/C3/Binary-digits
@@ -0,0 +1 @@
+../../Task/Binary-digits/C3
\ No newline at end of file
diff --git a/Lang/C3/Bulls-and-cows b/Lang/C3/Bulls-and-cows
new file mode 120000
index 0000000000..b5099b13d9
--- /dev/null
+++ b/Lang/C3/Bulls-and-cows
@@ -0,0 +1 @@
+../../Task/Bulls-and-cows/C3
\ No newline at end of file
diff --git a/Lang/CB80/00-LANG.txt b/Lang/CB80/00-LANG.txt
index 96b8bf005c..86de52ef42 100644
--- a/Lang/CB80/00-LANG.txt
+++ b/Lang/CB80/00-LANG.txt
@@ -1 +1,2 @@
-{{language}}{{Stub}}
\ No newline at end of file
+{{language}}{{Stub}}
+CB80 is not a separate language or dialect but rather a companion compiler for the [[CBASIC]] dialect of BASIC for 8-bit CP/M systems. The CBASIC compiler compiles source code into an intermediate form, which is stored on disk with the file extension INT. The compiled code is executed by invoking a run-time interpreter (CRUN.COM) from the command line. CB80, by contrast, compiles the source into a relocatable machine code file having an REL extension, which is then linked with necessary run-time library routines using the supplied linker (either LINK.COM or LK80.COM), to create a stand-alone executable file with the extension COM, which can be run simply by typing its name on the CP/M command-line. All of the posted CBASIC examples on Rosetta Code as of 9/14/2024 will compile and run without change under CB80. One subtle difference which could affect some programs lies in the behavior of the FOR .. NEXT statement. When run under CBASIC the body of the statement will always be executed at least once even if the index variable exceeds the value of the stop expression. If compiled using CB80, however, the loop will not be executed under those circumstances.
\ No newline at end of file
diff --git a/Lang/CBASIC/00-LANG.txt b/Lang/CBASIC/00-LANG.txt
new file mode 100644
index 0000000000..f0ff8ea32b
--- /dev/null
+++ b/Lang/CBASIC/00-LANG.txt
@@ -0,0 +1,21 @@
+{{stub}} {{language|CBASIC}}
+CBASIC was the commercial outgrowth of the BASIC-E compiler
+written by Gordon Eubanks as his Master's thesis while a 
+student at the Naval Postgraduate School. CBASIC -- which
+was marketed for both 8 and 16 bit CP/M systems -- differed from
+many of the BASIC dialects of the day in two major respects:
+(1) line numbers were not required unless the statement was
+the target of a GOTO or GOSUB statement (and were in any event
+treated simply as labels) and (2) real (floating point) variables
+were implemented as 14-digit binary coded decimal (BCD), which,
+particularly in business and accounting applications, avoided round-off 
+errors which purely binary floating point computations were prone
+to. Integer and string variables (which required % and $ suffixes,
+respectively) were also provided, as well as multi-dimensional arrays.
+Identifiers could be of any length, although only the first 31
+characters were significant. CBASIC supported multiline user-defined 
+functions with parameters passed by value but did not support recursion.
+CBASIC was implemented as a compiler-interpreter: the source code was
+compiled into an intermediate form, which could then be executed by
+invoking a run-time interpreter. A companion compiler, [[CB80]], was
+offered that compiled to machine code.
\ No newline at end of file
diff --git a/Lang/CBASIC/00-META.yaml b/Lang/CBASIC/00-META.yaml
new file mode 100644
index 0000000000..ad24e74664
--- /dev/null
+++ b/Lang/CBASIC/00-META.yaml
@@ -0,0 +1,2 @@
+---
+from: http://rosettacode.org/wiki/Category:CBASIC
diff --git a/Lang/CBASIC/100-doors b/Lang/CBASIC/100-doors
new file mode 120000
index 0000000000..e01a233041
--- /dev/null
+++ b/Lang/CBASIC/100-doors
@@ -0,0 +1 @@
+../../Task/100-doors/CBASIC
\ No newline at end of file
diff --git a/Lang/CBASIC/Amicable-pairs b/Lang/CBASIC/Amicable-pairs
new file mode 120000
index 0000000000..6386efc2a5
--- /dev/null
+++ b/Lang/CBASIC/Amicable-pairs
@@ -0,0 +1 @@
+../../Task/Amicable-pairs/CBASIC
\ No newline at end of file
diff --git a/Lang/CBASIC/Binary-digits b/Lang/CBASIC/Binary-digits
new file mode 120000
index 0000000000..d0de913861
--- /dev/null
+++ b/Lang/CBASIC/Binary-digits
@@ -0,0 +1 @@
+../../Task/Binary-digits/CBASIC
\ No newline at end of file
diff --git a/Lang/CBASIC/Factorial b/Lang/CBASIC/Factorial
new file mode 120000
index 0000000000..97dfd0b137
--- /dev/null
+++ b/Lang/CBASIC/Factorial
@@ -0,0 +1 @@
+../../Task/Factorial/CBASIC
\ No newline at end of file
diff --git a/Lang/CBASIC/Fibonacci-sequence b/Lang/CBASIC/Fibonacci-sequence
new file mode 120000
index 0000000000..eb9f8cf7a1
--- /dev/null
+++ b/Lang/CBASIC/Fibonacci-sequence
@@ -0,0 +1 @@
+../../Task/Fibonacci-sequence/CBASIC
\ No newline at end of file
diff --git a/Lang/CBASIC/Harmonic-series b/Lang/CBASIC/Harmonic-series
new file mode 120000
index 0000000000..aa1eac83fa
--- /dev/null
+++ b/Lang/CBASIC/Harmonic-series
@@ -0,0 +1 @@
+../../Task/Harmonic-series/CBASIC
\ No newline at end of file
diff --git a/Lang/CBASIC/Perfect-numbers b/Lang/CBASIC/Perfect-numbers
new file mode 120000
index 0000000000..3f847760d8
--- /dev/null
+++ b/Lang/CBASIC/Perfect-numbers
@@ -0,0 +1 @@
+../../Task/Perfect-numbers/CBASIC
\ No newline at end of file
diff --git a/Lang/CBASIC/Rot-13 b/Lang/CBASIC/Rot-13
new file mode 120000
index 0000000000..bbda100cd2
--- /dev/null
+++ b/Lang/CBASIC/Rot-13
@@ -0,0 +1 @@
+../../Task/Rot-13/CBASIC
\ No newline at end of file
diff --git a/Lang/CBASIC/Sieve-of-Eratosthenes b/Lang/CBASIC/Sieve-of-Eratosthenes
new file mode 120000
index 0000000000..ecdf66656a
--- /dev/null
+++ b/Lang/CBASIC/Sieve-of-Eratosthenes
@@ -0,0 +1 @@
+../../Task/Sieve-of-Eratosthenes/CBASIC
\ No newline at end of file
diff --git a/Lang/CJam/00-LANG.txt b/Lang/CJam/00-LANG.txt
new file mode 100644
index 0000000000..9d6f8331dc
--- /dev/null
+++ b/Lang/CJam/00-LANG.txt
@@ -0,0 +1,8 @@
+{{language|site=https://sourceforge.net/p/cjam/wiki/Home/}}
+
+[https://sourceforge.net/projects/cjam/ sf repo]
+
+From the [https://sourceforge.net/p/cjam/wiki/Home/ wiki]:
+
+:In order to run a CJam program, [https://sourceforge.net/projects/cjam/files/ download] the latest jar file, e.g. cjam-0.6.5.jar, and run this command:
+:
java -jar cjam-0.6.5.jar file.cjam
\ No newline at end of file diff --git a/Lang/CJam/00-META.yaml b/Lang/CJam/00-META.yaml new file mode 100644 index 0000000000..49b8d01361 --- /dev/null +++ b/Lang/CJam/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:CJam diff --git a/Lang/CLU/Arithmetic-derivative b/Lang/CLU/Arithmetic-derivative new file mode 120000 index 0000000000..f0f81c6bc1 --- /dev/null +++ b/Lang/CLU/Arithmetic-derivative @@ -0,0 +1 @@ +../../Task/Arithmetic-derivative/CLU \ No newline at end of file diff --git a/Lang/CLU/Move-to-front-algorithm b/Lang/CLU/Move-to-front-algorithm new file mode 120000 index 0000000000..bbdfe9bcdb --- /dev/null +++ b/Lang/CLU/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/CLU \ No newline at end of file diff --git a/Lang/CLU/Quaternion-type b/Lang/CLU/Quaternion-type deleted file mode 120000 index abdefd8765..0000000000 --- a/Lang/CLU/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/CLU \ No newline at end of file diff --git a/Lang/CLU/Super-d-numbers b/Lang/CLU/Super-d-numbers new file mode 120000 index 0000000000..a271a5f6dc --- /dev/null +++ b/Lang/CLU/Super-d-numbers @@ -0,0 +1 @@ +../../Task/Super-d-numbers/CLU \ No newline at end of file diff --git a/Lang/COBOL/ABC-problem b/Lang/COBOL/ABC-problem new file mode 120000 index 0000000000..ca521ee81d --- /dev/null +++ b/Lang/COBOL/ABC-problem @@ -0,0 +1 @@ +../../Task/ABC-problem/COBOL \ No newline at end of file diff --git a/Lang/COBOL/AVL-tree b/Lang/COBOL/AVL-tree new file mode 120000 index 0000000000..d8a20640c6 --- /dev/null +++ b/Lang/COBOL/AVL-tree @@ -0,0 +1 @@ +../../Task/AVL-tree/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Abundant-odd-numbers b/Lang/COBOL/Abundant-odd-numbers new file mode 120000 index 0000000000..7268a8a6ca --- /dev/null +++ b/Lang/COBOL/Abundant-odd-numbers @@ -0,0 +1 @@ +../../Task/Abundant-odd-numbers/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Achilles-numbers b/Lang/COBOL/Achilles-numbers new file mode 120000 index 0000000000..4a3a715de1 --- /dev/null +++ b/Lang/COBOL/Achilles-numbers @@ -0,0 +1 @@ +../../Task/Achilles-numbers/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Arithmetic-numbers b/Lang/COBOL/Arithmetic-numbers new file mode 120000 index 0000000000..cf8f3a0323 --- /dev/null +++ b/Lang/COBOL/Arithmetic-numbers @@ -0,0 +1 @@ +../../Task/Arithmetic-numbers/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Calkin-Wilf-sequence b/Lang/COBOL/Calkin-Wilf-sequence new file mode 120000 index 0000000000..f3e314890f --- /dev/null +++ b/Lang/COBOL/Calkin-Wilf-sequence @@ -0,0 +1 @@ +../../Task/Calkin-Wilf-sequence/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Colorful-numbers b/Lang/COBOL/Colorful-numbers new file mode 120000 index 0000000000..6d5c4f9dff --- /dev/null +++ b/Lang/COBOL/Colorful-numbers @@ -0,0 +1 @@ +../../Task/Colorful-numbers/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Cullen-and-Woodall-numbers b/Lang/COBOL/Cullen-and-Woodall-numbers new file mode 120000 index 0000000000..b212ad96a5 --- /dev/null +++ b/Lang/COBOL/Cullen-and-Woodall-numbers @@ -0,0 +1 @@ +../../Task/Cullen-and-Woodall-numbers/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Damm-algorithm b/Lang/COBOL/Damm-algorithm new file mode 120000 index 0000000000..e4f3bf1f71 --- /dev/null +++ b/Lang/COBOL/Damm-algorithm @@ -0,0 +1 @@ +../../Task/Damm-algorithm/COBOL \ No newline at end of file diff --git a/Lang/COBOL/De-Bruijn-sequences b/Lang/COBOL/De-Bruijn-sequences new file mode 120000 index 0000000000..67e8dee974 --- /dev/null +++ b/Lang/COBOL/De-Bruijn-sequences @@ -0,0 +1 @@ +../../Task/De-Bruijn-sequences/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Dijkstras-algorithm b/Lang/COBOL/Dijkstras-algorithm new file mode 120000 index 0000000000..19c743357a --- /dev/null +++ b/Lang/COBOL/Dijkstras-algorithm @@ -0,0 +1 @@ +../../Task/Dijkstras-algorithm/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Farey-sequence b/Lang/COBOL/Farey-sequence new file mode 120000 index 0000000000..b402aede64 --- /dev/null +++ b/Lang/COBOL/Farey-sequence @@ -0,0 +1 @@ +../../Task/Farey-sequence/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Floyd-Warshall-algorithm b/Lang/COBOL/Floyd-Warshall-algorithm new file mode 120000 index 0000000000..de49182ec8 --- /dev/null +++ b/Lang/COBOL/Floyd-Warshall-algorithm @@ -0,0 +1 @@ +../../Task/Floyd-Warshall-algorithm/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Fusc-sequence b/Lang/COBOL/Fusc-sequence new file mode 120000 index 0000000000..e8b4b1330c --- /dev/null +++ b/Lang/COBOL/Fusc-sequence @@ -0,0 +1 @@ +../../Task/Fusc-sequence/COBOL \ No newline at end of file diff --git a/Lang/COBOL/K-d-tree b/Lang/COBOL/K-d-tree new file mode 120000 index 0000000000..af9595a130 --- /dev/null +++ b/Lang/COBOL/K-d-tree @@ -0,0 +1 @@ +../../Task/K-d-tree/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Knuths-algorithm-S b/Lang/COBOL/Knuths-algorithm-S new file mode 120000 index 0000000000..119841f920 --- /dev/null +++ b/Lang/COBOL/Knuths-algorithm-S @@ -0,0 +1 @@ +../../Task/Knuths-algorithm-S/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Leonardo-numbers b/Lang/COBOL/Leonardo-numbers new file mode 120000 index 0000000000..65bc7509a4 --- /dev/null +++ b/Lang/COBOL/Leonardo-numbers @@ -0,0 +1 @@ +../../Task/Leonardo-numbers/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Move-to-front-algorithm b/Lang/COBOL/Move-to-front-algorithm new file mode 120000 index 0000000000..f9458888cc --- /dev/null +++ b/Lang/COBOL/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Nim-game b/Lang/COBOL/Nim-game new file mode 120000 index 0000000000..9a7c582b48 --- /dev/null +++ b/Lang/COBOL/Nim-game @@ -0,0 +1 @@ +../../Task/Nim-game/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Pancake-numbers b/Lang/COBOL/Pancake-numbers new file mode 120000 index 0000000000..22e5574a28 --- /dev/null +++ b/Lang/COBOL/Pancake-numbers @@ -0,0 +1 @@ +../../Task/Pancake-numbers/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Parametric-polymorphism b/Lang/COBOL/Parametric-polymorphism new file mode 120000 index 0000000000..44f214df50 --- /dev/null +++ b/Lang/COBOL/Parametric-polymorphism @@ -0,0 +1 @@ +../../Task/Parametric-polymorphism/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Soloways-recurring-rainfall b/Lang/COBOL/Soloways-recurring-rainfall new file mode 120000 index 0000000000..883bf3b2e0 --- /dev/null +++ b/Lang/COBOL/Soloways-recurring-rainfall @@ -0,0 +1 @@ +../../Task/Soloways-recurring-rainfall/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Strassens-algorithm b/Lang/COBOL/Strassens-algorithm new file mode 120000 index 0000000000..488f64d9e2 --- /dev/null +++ b/Lang/COBOL/Strassens-algorithm @@ -0,0 +1 @@ +../../Task/Strassens-algorithm/COBOL \ No newline at end of file diff --git a/Lang/COBOL/The-Name-Game b/Lang/COBOL/The-Name-Game new file mode 120000 index 0000000000..35866ecb72 --- /dev/null +++ b/Lang/COBOL/The-Name-Game @@ -0,0 +1 @@ +../../Task/The-Name-Game/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Twos-complement b/Lang/COBOL/Twos-complement new file mode 120000 index 0000000000..776801b9e2 --- /dev/null +++ b/Lang/COBOL/Twos-complement @@ -0,0 +1 @@ +../../Task/Twos-complement/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Vigen-re-cipher b/Lang/COBOL/Vigen-re-cipher new file mode 120000 index 0000000000..93e3f53bcb --- /dev/null +++ b/Lang/COBOL/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Zeckendorf-number-representation b/Lang/COBOL/Zeckendorf-number-representation new file mode 120000 index 0000000000..d3c11d47da --- /dev/null +++ b/Lang/COBOL/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/COBOL \ No newline at end of file diff --git a/Lang/Calc/00-LANG.txt b/Lang/Calc/00-LANG.txt new file mode 100644 index 0000000000..9066fe1741 --- /dev/null +++ b/Lang/Calc/00-LANG.txt @@ -0,0 +1,10 @@ +{{language|Calc +|untyped=yes}} +{{language programming paradigm|stack-based}} +{{language programming paradigm|imperative}} + +Calc is a stack-based RPN calculator inside [[Emacs]]. Calc is part of GNU Emacs 22, or a package for XEmacs. + +Calc presents itself as an interactive calculator. Instructions can also be stored as macros, including control flow instructions (if-then-else, for loop, etc.), which makes Calc fully programmable. Calc also provides a library available in Emacs Lisp programs. + +Calc has more numeric types than plain Emacs Lisp. Calc has big integers, big floating-point numbers, rational numbers, complex numbers, and more. (For contrast, plain Emacs Lisp can only handle integers and floating-point numbers of limited precision.) Emacs Lisp with Calc can solve tasks requiring these types of numbers. \ No newline at end of file diff --git a/Lang/Calc/00-META.yaml b/Lang/Calc/00-META.yaml new file mode 100644 index 0000000000..85b0e2ef53 --- /dev/null +++ b/Lang/Calc/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Calc diff --git a/Lang/Calc/Averages-Arithmetic-mean b/Lang/Calc/Averages-Arithmetic-mean new file mode 120000 index 0000000000..8ad84c8dbd --- /dev/null +++ b/Lang/Calc/Averages-Arithmetic-mean @@ -0,0 +1 @@ +../../Task/Averages-Arithmetic-mean/Calc \ No newline at end of file diff --git a/Lang/Calc/Modular-exponentiation b/Lang/Calc/Modular-exponentiation new file mode 120000 index 0000000000..b72a4448d5 --- /dev/null +++ b/Lang/Calc/Modular-exponentiation @@ -0,0 +1 @@ +../../Task/Modular-exponentiation/Calc \ No newline at end of file diff --git a/Lang/Calcscript/00-LANG.txt b/Lang/Calcscript/00-LANG.txt new file mode 100644 index 0000000000..d2db819bbe --- /dev/null +++ b/Lang/Calcscript/00-LANG.txt @@ -0,0 +1,10 @@ +{{language +|site=https://gitee.com/jfiewo/calc/ +}} +Calcscript is a small lisp-like language. +* It has 3 datatypes: Int, Same, and Invalid. +* The usual 4 arithmetic operations are supported. + +See [https://gitee.com/jfiewo/calc/ the respository] for details. +{{language programming paradigm|Logic Programming}} +{{language programming paradigm|Functional}} \ No newline at end of file diff --git a/Lang/Calcscript/00-META.yaml b/Lang/Calcscript/00-META.yaml new file mode 100644 index 0000000000..cee9fc468f --- /dev/null +++ b/Lang/Calcscript/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Calcscript diff --git a/Lang/Chapel/Function-definition b/Lang/Chapel/Function-definition new file mode 120000 index 0000000000..589b4afa2c --- /dev/null +++ b/Lang/Chapel/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/Chapel \ No newline at end of file diff --git a/Lang/Chapel/Maze-generation b/Lang/Chapel/Maze-generation new file mode 120000 index 0000000000..b4c55cfddb --- /dev/null +++ b/Lang/Chapel/Maze-generation @@ -0,0 +1 @@ +../../Task/Maze-generation/Chapel \ No newline at end of file diff --git a/Lang/Chapel/Repeat b/Lang/Chapel/Repeat new file mode 120000 index 0000000000..3c555a4885 --- /dev/null +++ b/Lang/Chapel/Repeat @@ -0,0 +1 @@ +../../Task/Repeat/Chapel \ No newline at end of file diff --git a/Lang/Chipmunk-Basic/ASCII-art-diagram-converter b/Lang/Chipmunk-Basic/ASCII-art-diagram-converter new file mode 120000 index 0000000000..a034d74b58 --- /dev/null +++ b/Lang/Chipmunk-Basic/ASCII-art-diagram-converter @@ -0,0 +1 @@ +../../Task/ASCII-art-diagram-converter/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/Chipmunk-Basic/Associative-array-Merging b/Lang/Chipmunk-Basic/Associative-array-Merging new file mode 120000 index 0000000000..dd87e8e06c --- /dev/null +++ b/Lang/Chipmunk-Basic/Associative-array-Merging @@ -0,0 +1 @@ +../../Task/Associative-array-Merging/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/Chipmunk-Basic/Determine-sentence-type b/Lang/Chipmunk-Basic/Determine-sentence-type new file mode 120000 index 0000000000..6851894430 --- /dev/null +++ b/Lang/Chipmunk-Basic/Determine-sentence-type @@ -0,0 +1 @@ +../../Task/Determine-sentence-type/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/Chipmunk-Basic/Display-a-linear-combination b/Lang/Chipmunk-Basic/Display-a-linear-combination new file mode 120000 index 0000000000..76f3965566 --- /dev/null +++ b/Lang/Chipmunk-Basic/Display-a-linear-combination @@ -0,0 +1 @@ +../../Task/Display-a-linear-combination/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/Chipmunk-Basic/Diversity-prediction-theorem b/Lang/Chipmunk-Basic/Diversity-prediction-theorem new file mode 120000 index 0000000000..094da6a44e --- /dev/null +++ b/Lang/Chipmunk-Basic/Diversity-prediction-theorem @@ -0,0 +1 @@ +../../Task/Diversity-prediction-theorem/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/Chipmunk-Basic/Eban-numbers b/Lang/Chipmunk-Basic/Eban-numbers new file mode 120000 index 0000000000..109253525e --- /dev/null +++ b/Lang/Chipmunk-Basic/Eban-numbers @@ -0,0 +1 @@ +../../Task/Eban-numbers/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/Chipmunk-Basic/Evaluate-binomial-coefficients b/Lang/Chipmunk-Basic/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..b45aed06e2 --- /dev/null +++ b/Lang/Chipmunk-Basic/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/Chipmunk-Basic/Fibonacci-n-step-number-sequences b/Lang/Chipmunk-Basic/Fibonacci-n-step-number-sequences new file mode 120000 index 0000000000..24e6f1fb75 --- /dev/null +++ b/Lang/Chipmunk-Basic/Fibonacci-n-step-number-sequences @@ -0,0 +1 @@ +../../Task/Fibonacci-n-step-number-sequences/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/Chipmunk-Basic/Generate-Chess960-starting-position b/Lang/Chipmunk-Basic/Generate-Chess960-starting-position new file mode 120000 index 0000000000..daceb0cf8f --- /dev/null +++ b/Lang/Chipmunk-Basic/Generate-Chess960-starting-position @@ -0,0 +1 @@ +../../Task/Generate-Chess960-starting-position/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/Chipmunk-Basic/Generate-lower-case-ASCII-alphabet b/Lang/Chipmunk-Basic/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..22e12f5ab0 --- /dev/null +++ b/Lang/Chipmunk-Basic/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/Chipmunk-Basic/Jensens-Device b/Lang/Chipmunk-Basic/Jensens-Device new file mode 120000 index 0000000000..927dca2f6f --- /dev/null +++ b/Lang/Chipmunk-Basic/Jensens-Device @@ -0,0 +1 @@ +../../Task/Jensens-Device/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/Chipmunk-Basic/Leonardo-numbers b/Lang/Chipmunk-Basic/Leonardo-numbers new file mode 120000 index 0000000000..65f7e68a9b --- /dev/null +++ b/Lang/Chipmunk-Basic/Leonardo-numbers @@ -0,0 +1 @@ +../../Task/Leonardo-numbers/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/Chipmunk-Basic/Map-range b/Lang/Chipmunk-Basic/Map-range new file mode 120000 index 0000000000..3aa5f00ecb --- /dev/null +++ b/Lang/Chipmunk-Basic/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/Chipmunk-Basic/Multiple-regression b/Lang/Chipmunk-Basic/Multiple-regression new file mode 120000 index 0000000000..82844a944e --- /dev/null +++ b/Lang/Chipmunk-Basic/Multiple-regression @@ -0,0 +1 @@ +../../Task/Multiple-regression/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/Chipmunk-Basic/Nested-templated-data b/Lang/Chipmunk-Basic/Nested-templated-data new file mode 120000 index 0000000000..a7e95ed6f1 --- /dev/null +++ b/Lang/Chipmunk-Basic/Nested-templated-data @@ -0,0 +1 @@ +../../Task/Nested-templated-data/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/Chipmunk-Basic/Pascals-triangle b/Lang/Chipmunk-Basic/Pascals-triangle new file mode 120000 index 0000000000..aa62c07130 --- /dev/null +++ b/Lang/Chipmunk-Basic/Pascals-triangle @@ -0,0 +1 @@ +../../Task/Pascals-triangle/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/Chipmunk-Basic/Perfect-numbers b/Lang/Chipmunk-Basic/Perfect-numbers new file mode 120000 index 0000000000..4bd1876580 --- /dev/null +++ b/Lang/Chipmunk-Basic/Perfect-numbers @@ -0,0 +1 @@ +../../Task/Perfect-numbers/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/Chipmunk-Basic/Phrase-reversals b/Lang/Chipmunk-Basic/Phrase-reversals new file mode 120000 index 0000000000..3d4b70a430 --- /dev/null +++ b/Lang/Chipmunk-Basic/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/Chipmunk-Basic/Price-fraction b/Lang/Chipmunk-Basic/Price-fraction new file mode 120000 index 0000000000..895d56d4cf --- /dev/null +++ b/Lang/Chipmunk-Basic/Price-fraction @@ -0,0 +1 @@ +../../Task/Price-fraction/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/Chipmunk-Basic/Proper-divisors b/Lang/Chipmunk-Basic/Proper-divisors new file mode 120000 index 0000000000..e83b2b6ef0 --- /dev/null +++ b/Lang/Chipmunk-Basic/Proper-divisors @@ -0,0 +1 @@ +../../Task/Proper-divisors/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/Chipmunk-Basic/Rate-counter b/Lang/Chipmunk-Basic/Rate-counter new file mode 120000 index 0000000000..214d671194 --- /dev/null +++ b/Lang/Chipmunk-Basic/Rate-counter @@ -0,0 +1 @@ +../../Task/Rate-counter/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/Chipmunk-Basic/Shell-one-liner b/Lang/Chipmunk-Basic/Shell-one-liner new file mode 120000 index 0000000000..a90b838683 --- /dev/null +++ b/Lang/Chipmunk-Basic/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/Chipmunk-Basic/Split-a-character-string-based-on-change-of-character b/Lang/Chipmunk-Basic/Split-a-character-string-based-on-change-of-character new file mode 120000 index 0000000000..ae1d1da2a7 --- /dev/null +++ b/Lang/Chipmunk-Basic/Split-a-character-string-based-on-change-of-character @@ -0,0 +1 @@ +../../Task/Split-a-character-string-based-on-change-of-character/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/Chipmunk-Basic/Sudan-function b/Lang/Chipmunk-Basic/Sudan-function new file mode 120000 index 0000000000..8b26708ee8 --- /dev/null +++ b/Lang/Chipmunk-Basic/Sudan-function @@ -0,0 +1 @@ +../../Task/Sudan-function/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/Chipmunk-Basic/Sum-of-a-series b/Lang/Chipmunk-Basic/Sum-of-a-series new file mode 120000 index 0000000000..f9bdcf9a6b --- /dev/null +++ b/Lang/Chipmunk-Basic/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/Chipmunk-Basic/The-Name-Game b/Lang/Chipmunk-Basic/The-Name-Game new file mode 120000 index 0000000000..5655525e11 --- /dev/null +++ b/Lang/Chipmunk-Basic/The-Name-Game @@ -0,0 +1 @@ +../../Task/The-Name-Game/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/Chipmunk-Basic/Twos-complement b/Lang/Chipmunk-Basic/Twos-complement new file mode 120000 index 0000000000..4eb5b36880 --- /dev/null +++ b/Lang/Chipmunk-Basic/Twos-complement @@ -0,0 +1 @@ +../../Task/Twos-complement/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/Chipmunk-Basic/Vector b/Lang/Chipmunk-Basic/Vector new file mode 120000 index 0000000000..68aa51b11b --- /dev/null +++ b/Lang/Chipmunk-Basic/Vector @@ -0,0 +1 @@ +../../Task/Vector/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/Clojure/Miller-Rabin-primality-test b/Lang/Clojure/Miller-Rabin-primality-test deleted file mode 120000 index 67b048eb10..0000000000 --- a/Lang/Clojure/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Clojure \ No newline at end of file diff --git a/Lang/CoffeeScript/Empty-program b/Lang/CoffeeScript/Empty-program deleted file mode 120000 index c325b31ffa..0000000000 --- a/Lang/CoffeeScript/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/Sorting-Algorithms-Circle-Sort b/Lang/CoffeeScript/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index e4d7481d88..0000000000 --- a/Lang/CoffeeScript/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/CoffeeScript \ No newline at end of file diff --git a/Lang/Comal/Fairshare-between-two-and-more b/Lang/Comal/Fairshare-between-two-and-more new file mode 120000 index 0000000000..4497e4f55d --- /dev/null +++ b/Lang/Comal/Fairshare-between-two-and-more @@ -0,0 +1 @@ +../../Task/Fairshare-between-two-and-more/Comal \ No newline at end of file diff --git a/Lang/Comal/Zeckendorf-number-representation b/Lang/Comal/Zeckendorf-number-representation new file mode 120000 index 0000000000..55d16429d3 --- /dev/null +++ b/Lang/Comal/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/Comal \ No newline at end of file diff --git a/Lang/Commodore-BASIC/Miller-Rabin-primality-test b/Lang/Commodore-BASIC/Miller-Rabin-primality-test deleted file mode 120000 index 7354bc510f..0000000000 --- a/Lang/Commodore-BASIC/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Commodore-BASIC \ No newline at end of file diff --git a/Lang/Commodore-BASIC/N-queens-problem b/Lang/Commodore-BASIC/N-queens-problem new file mode 120000 index 0000000000..d5a4ff5b7a --- /dev/null +++ b/Lang/Commodore-BASIC/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/Commodore-BASIC \ No newline at end of file diff --git a/Lang/Commodore-BASIC/Random-number-generator-device- b/Lang/Commodore-BASIC/Random-number-generator-device- new file mode 120000 index 0000000000..f23b1d0d42 --- /dev/null +++ b/Lang/Commodore-BASIC/Random-number-generator-device- @@ -0,0 +1 @@ +../../Task/Random-number-generator-device-/Commodore-BASIC \ No newline at end of file diff --git a/Lang/Common-Lisp/Blum-integer b/Lang/Common-Lisp/Blum-integer new file mode 120000 index 0000000000..854dbaeee7 --- /dev/null +++ b/Lang/Common-Lisp/Blum-integer @@ -0,0 +1 @@ +../../Task/Blum-integer/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Factorial-primes b/Lang/Common-Lisp/Factorial-primes new file mode 120000 index 0000000000..cc0d935af1 --- /dev/null +++ b/Lang/Common-Lisp/Factorial-primes @@ -0,0 +1 @@ +../../Task/Factorial-primes/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Miller-Rabin-primality-test b/Lang/Common-Lisp/Miller-Rabin-primality-test deleted file mode 120000 index 4f8dbe695d..0000000000 --- a/Lang/Common-Lisp/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Multi-dimensional-array b/Lang/Common-Lisp/Multi-dimensional-array new file mode 120000 index 0000000000..37f7ef0979 --- /dev/null +++ b/Lang/Common-Lisp/Multi-dimensional-array @@ -0,0 +1 @@ +../../Task/Multi-dimensional-array/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Quaternion-type b/Lang/Common-Lisp/Quaternion-type deleted file mode 120000 index dd7bafa7e8..0000000000 --- a/Lang/Common-Lisp/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Substitution-cipher b/Lang/Common-Lisp/Substitution-cipher new file mode 120000 index 0000000000..332d90e9f0 --- /dev/null +++ b/Lang/Common-Lisp/Substitution-cipher @@ -0,0 +1 @@ +../../Task/Substitution-cipher/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Wieferich-primes b/Lang/Common-Lisp/Wieferich-primes new file mode 120000 index 0000000000..91ad6e3ba2 --- /dev/null +++ b/Lang/Common-Lisp/Wieferich-primes @@ -0,0 +1 @@ +../../Task/Wieferich-primes/Common-Lisp \ No newline at end of file diff --git a/Lang/Component-Pascal/00-LANG.txt b/Lang/Component-Pascal/00-LANG.txt index a83cc2b2e7..7056dd922c 100644 --- a/Lang/Component-Pascal/00-LANG.txt +++ b/Lang/Component-Pascal/00-LANG.txt @@ -1,4 +1,11 @@ {{language|Component Pascal}}'''Component Pascal''' is a programming language in the tradition of Oberon and [[Oberon-2]], the last language Niklaus Wirth designed before he retired in 1999. It bears the name of the [[Pascal]] programming language but is incompatible with it. Instead, it is a minor variant and refinement of Oberon-2, designed and supported by a small ETH Zürich spin-off company called Oberon microsystems. Their [[IDE]] is called BlackBox Component Builder. At the time the first version was released (1994) it presented a novel approach to graphical user interface ([[GUI]]) construction based on editable forms, where fields and command buttons are linked to exported variables and executable procedures. This approach bears some similarity to the code-behind way used in [[Microsoft]]'s [[.NET]] 3.0 to access code in XAML. ==Citations== -* [http://en.wikipedia.org/wiki/Component_Pascal Wikipedia:Component Pascal] \ No newline at end of file +* [http://en.wikipedia.org/wiki/Component_Pascal Wikipedia:Component Pascal] + +===See also=== +* [[Oberon-07]] +* [[Oberon-2]] +* [[Zonnon]] +* [[Modula-2]] +* [[Modula-3]] \ No newline at end of file diff --git a/Lang/Component-Pascal/100-doors b/Lang/Component-Pascal/100-doors deleted file mode 120000 index 76b023254e..0000000000 --- a/Lang/Component-Pascal/100-doors +++ /dev/null @@ -1 +0,0 @@ -../../Task/100-doors/Component-Pascal \ No newline at end of file diff --git a/Lang/Computer-zero-Assembly/00-LANG.txt b/Lang/Computer-zero-Assembly/00-LANG.txt index e6ea975211..779b92356f 100644 --- a/Lang/Computer-zero-Assembly/00-LANG.txt +++ b/Lang/Computer-zero-Assembly/00-LANG.txt @@ -19,10 +19,10 @@ There are only 32 bytes of memory, and this includes your program code, leaving ==Self-Modifying Code== With such little RAM available, the biggest tool we have at our disposal for programming is self-modifying code. The CPU makes no distinction between data and instructions, and as such we can store values into memory before that memory is executed, in order to change what the computer will do. Here's an example: -LDA 4 +LDA 4 STA 2 ADD 3 STP -SUB 3 +SUB 3 The above snippet of code never actually ADDs anything, since that instruction gets overwritten by SUB 3. And what is SUB 3 subtracting? It's subtracting the value of STP, which can be encoded as any number between 0xE0 and 0xFF. Specifically, the encoding of SUB 3 (i.e. 0b10000011) is decreased by some value between 0xE0 and 0xFF, and since all arithmetic on this CPU is modulo 256 (as is standard for nearly all 8-bit CPUs), there will be roll-over across the FF-00 boundary. Without a hardware carry flag, however, it's difficult to track this overflow. \ No newline at end of file diff --git a/Lang/Convex/00-LANG.txt b/Lang/Convex/00-LANG.txt new file mode 100644 index 0000000000..6676f23dde --- /dev/null +++ b/Lang/Convex/00-LANG.txt @@ -0,0 +1,6 @@ +Convex is a stack-based golfing esolang based on Golfscript and CJam. + +{{language|site=https://github.com/ZekNikZ/Convex}} + +{{try|Convex|[https://tio.run/#convex Try Convex on tio.run].}} +{{language_programming_paradigm|Concatenative}} \ No newline at end of file diff --git a/Lang/Convex/00-META.yaml b/Lang/Convex/00-META.yaml new file mode 100644 index 0000000000..b10fffa83e --- /dev/null +++ b/Lang/Convex/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Convex diff --git a/Lang/Coq/00-LANG.txt b/Lang/Coq/00-LANG.txt index 3a03214cba..dac9774672 100644 --- a/Lang/Coq/00-LANG.txt +++ b/Lang/Coq/00-LANG.txt @@ -1,9 +1 @@ -{{language|Coq -|site=http://coq.inria.fr -}} -In computer science, Coq is a proof assistant application. It allows the expression of mathematical assertions, mechanically checks proofs of these assertions, helps to find formal proofs, and extracts a certified program from the constructive proof of its formal specification. Coq works within the theory of the calculus of inductive constructions, a derivative of the calculus of constructions. Coq is not an automated [[wp:Theorem_prover|theorem prover]] but includes automatic theorem proving tactics and various decision procedures. - -==Citations== -* [[wp:Coq|Coq]] - -[[Category:Mathematical programming languages]] \ No newline at end of file +#REDIRECT [[:Category:Rocq]] \ No newline at end of file diff --git a/Lang/Coq/100-doors b/Lang/Coq/100-doors deleted file mode 120000 index fd39f903ef..0000000000 --- a/Lang/Coq/100-doors +++ /dev/null @@ -1 +0,0 @@ -../../Task/100-doors/Coq \ No newline at end of file diff --git a/Lang/Coq/Ackermann-function b/Lang/Coq/Ackermann-function deleted file mode 120000 index 03a0752c76..0000000000 --- a/Lang/Coq/Ackermann-function +++ /dev/null @@ -1 +0,0 @@ -../../Task/Ackermann-function/Coq \ No newline at end of file diff --git a/Lang/Coq/Extend-your-language b/Lang/Coq/Extend-your-language deleted file mode 120000 index 2e717c1027..0000000000 --- a/Lang/Coq/Extend-your-language +++ /dev/null @@ -1 +0,0 @@ -../../Task/Extend-your-language/Coq \ No newline at end of file diff --git a/Lang/Coq/Factorial b/Lang/Coq/Factorial deleted file mode 120000 index 3d35ebeb5f..0000000000 --- a/Lang/Coq/Factorial +++ /dev/null @@ -1 +0,0 @@ -../../Task/Factorial/Coq \ No newline at end of file diff --git a/Lang/Coq/Fibonacci-sequence b/Lang/Coq/Fibonacci-sequence deleted file mode 120000 index fc6d7d958a..0000000000 --- a/Lang/Coq/Fibonacci-sequence +++ /dev/null @@ -1 +0,0 @@ -../../Task/Fibonacci-sequence/Coq \ No newline at end of file diff --git a/Lang/Coq/FizzBuzz b/Lang/Coq/FizzBuzz deleted file mode 120000 index 966d79dca5..0000000000 --- a/Lang/Coq/FizzBuzz +++ /dev/null @@ -1 +0,0 @@ -../../Task/FizzBuzz/Coq \ No newline at end of file diff --git a/Lang/Coq/Hello-world-Newbie b/Lang/Coq/Hello-world-Newbie deleted file mode 120000 index 53590d7473..0000000000 --- a/Lang/Coq/Hello-world-Newbie +++ /dev/null @@ -1 +0,0 @@ -../../Task/Hello-world-Newbie/Coq \ No newline at end of file diff --git a/Lang/Coq/Hello-world-Text b/Lang/Coq/Hello-world-Text deleted file mode 120000 index 194b2d17df..0000000000 --- a/Lang/Coq/Hello-world-Text +++ /dev/null @@ -1 +0,0 @@ -../../Task/Hello-world-Text/Coq \ No newline at end of file diff --git a/Lang/Coq/Loops-For b/Lang/Coq/Loops-For deleted file mode 120000 index b1341b994c..0000000000 --- a/Lang/Coq/Loops-For +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-For/Coq \ No newline at end of file diff --git a/Lang/Coq/Tree-traversal b/Lang/Coq/Tree-traversal deleted file mode 120000 index e38e9a0bdd..0000000000 --- a/Lang/Coq/Tree-traversal +++ /dev/null @@ -1 +0,0 @@ -../../Task/Tree-traversal/Coq \ No newline at end of file diff --git a/Lang/Coq/Variadic-function b/Lang/Coq/Variadic-function deleted file mode 120000 index 391626fb92..0000000000 --- a/Lang/Coq/Variadic-function +++ /dev/null @@ -1 +0,0 @@ -../../Task/Variadic-function/Coq \ No newline at end of file diff --git a/Lang/Cowgol/Align-columns b/Lang/Cowgol/Align-columns new file mode 120000 index 0000000000..2931644d20 --- /dev/null +++ b/Lang/Cowgol/Align-columns @@ -0,0 +1 @@ +../../Task/Align-columns/Cowgol \ No newline at end of file diff --git a/Lang/Cowgol/Arithmetic-derivative b/Lang/Cowgol/Arithmetic-derivative new file mode 120000 index 0000000000..5d9cc4afd2 --- /dev/null +++ b/Lang/Cowgol/Arithmetic-derivative @@ -0,0 +1 @@ +../../Task/Arithmetic-derivative/Cowgol \ No newline at end of file diff --git a/Lang/Cowgol/Compound-data-type b/Lang/Cowgol/Compound-data-type new file mode 120000 index 0000000000..f242ef8856 --- /dev/null +++ b/Lang/Cowgol/Compound-data-type @@ -0,0 +1 @@ +../../Task/Compound-data-type/Cowgol \ No newline at end of file diff --git a/Lang/Cowgol/Display-a-linear-combination b/Lang/Cowgol/Display-a-linear-combination new file mode 120000 index 0000000000..7e169cd6fe --- /dev/null +++ b/Lang/Cowgol/Display-a-linear-combination @@ -0,0 +1 @@ +../../Task/Display-a-linear-combination/Cowgol \ No newline at end of file diff --git a/Lang/Cowgol/Move-to-front-algorithm b/Lang/Cowgol/Move-to-front-algorithm new file mode 120000 index 0000000000..137327f2ab --- /dev/null +++ b/Lang/Cowgol/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/Cowgol \ No newline at end of file diff --git a/Lang/Cowgol/UTF-8-encode-and-decode b/Lang/Cowgol/UTF-8-encode-and-decode new file mode 120000 index 0000000000..93ae70053a --- /dev/null +++ b/Lang/Cowgol/UTF-8-encode-and-decode @@ -0,0 +1 @@ +../../Task/UTF-8-encode-and-decode/Cowgol \ No newline at end of file diff --git a/Lang/Crystal/00-LANG.txt b/Lang/Crystal/00-LANG.txt index b671a267bf..2d48345f43 100644 --- a/Lang/Crystal/00-LANG.txt +++ b/Lang/Crystal/00-LANG.txt @@ -6,7 +6,8 @@ |strength=strong |checking=static |compat=duck -|site=http://crystal-lang.org}} +|site=http://crystal-lang.org +|hopl=no, HOPL only has an older "Crystal" language from 1986}} Crystal is a programming language with the following goals: * Have the same syntax as Ruby, or at least as similar as possible. * Never have to specify the type of a variable or method argument. @@ -14,4 +15,7 @@ Crystal is a programming language with the following goals: * Have compile-time evaluation and generation of code, to avoid boilerplate code. * Compile to efficient native code. -You can ask for help on Freenode in the #crystal-lang channel. \ No newline at end of file +You can ask for help on LiberaChat in the [ircs://irc.libera.chat:6697#crystal-lang #crystal-lang] channel ([https://web.libera.chat/#crystal-lang web]). + +==Tasks not implemented in Crystal== +[[Tasks not implemented in Crystal]] \ No newline at end of file diff --git a/Lang/Crystal/ABC-problem b/Lang/Crystal/ABC-problem new file mode 120000 index 0000000000..4ebb385d2c --- /dev/null +++ b/Lang/Crystal/ABC-problem @@ -0,0 +1 @@ +../../Task/ABC-problem/Crystal \ No newline at end of file diff --git a/Lang/Crystal/ADFGVX-cipher b/Lang/Crystal/ADFGVX-cipher new file mode 120000 index 0000000000..20d511e75f --- /dev/null +++ b/Lang/Crystal/ADFGVX-cipher @@ -0,0 +1 @@ +../../Task/ADFGVX-cipher/Crystal \ No newline at end of file diff --git a/Lang/Crystal/ASCII-art-diagram-converter b/Lang/Crystal/ASCII-art-diagram-converter new file mode 120000 index 0000000000..0f1238b276 --- /dev/null +++ b/Lang/Crystal/ASCII-art-diagram-converter @@ -0,0 +1 @@ +../../Task/ASCII-art-diagram-converter/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Abbreviations-automatic b/Lang/Crystal/Abbreviations-automatic new file mode 120000 index 0000000000..356658ce4c --- /dev/null +++ b/Lang/Crystal/Abbreviations-automatic @@ -0,0 +1 @@ +../../Task/Abbreviations-automatic/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Abbreviations-easy b/Lang/Crystal/Abbreviations-easy new file mode 120000 index 0000000000..b3a87e7119 --- /dev/null +++ b/Lang/Crystal/Abbreviations-easy @@ -0,0 +1 @@ +../../Task/Abbreviations-easy/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Abelian-sandpile-model b/Lang/Crystal/Abelian-sandpile-model new file mode 120000 index 0000000000..8c440adf10 --- /dev/null +++ b/Lang/Crystal/Abelian-sandpile-model @@ -0,0 +1 @@ +../../Task/Abelian-sandpile-model/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Abelian-sandpile-model-Identity b/Lang/Crystal/Abelian-sandpile-model-Identity new file mode 120000 index 0000000000..ad1df3a714 --- /dev/null +++ b/Lang/Crystal/Abelian-sandpile-model-Identity @@ -0,0 +1 @@ +../../Task/Abelian-sandpile-model-Identity/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Abundant-deficient-and-perfect-number-classifications b/Lang/Crystal/Abundant-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..7cba469c21 --- /dev/null +++ b/Lang/Crystal/Abundant-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant-deficient-and-perfect-number-classifications/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Abundant-odd-numbers b/Lang/Crystal/Abundant-odd-numbers new file mode 120000 index 0000000000..3676d5a336 --- /dev/null +++ b/Lang/Crystal/Abundant-odd-numbers @@ -0,0 +1 @@ +../../Task/Abundant-odd-numbers/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Achilles-numbers b/Lang/Crystal/Achilles-numbers new file mode 120000 index 0000000000..baac6a0487 --- /dev/null +++ b/Lang/Crystal/Achilles-numbers @@ -0,0 +1 @@ +../../Task/Achilles-numbers/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Add-a-variable-to-a-class-instance-at-runtime b/Lang/Crystal/Add-a-variable-to-a-class-instance-at-runtime new file mode 120000 index 0000000000..7c0d033962 --- /dev/null +++ b/Lang/Crystal/Add-a-variable-to-a-class-instance-at-runtime @@ -0,0 +1 @@ +../../Task/Add-a-variable-to-a-class-instance-at-runtime/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Address-of-a-variable b/Lang/Crystal/Address-of-a-variable new file mode 120000 index 0000000000..55aa429a76 --- /dev/null +++ b/Lang/Crystal/Address-of-a-variable @@ -0,0 +1 @@ +../../Task/Address-of-a-variable/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Align-columns b/Lang/Crystal/Align-columns new file mode 120000 index 0000000000..2ab766781e --- /dev/null +++ b/Lang/Crystal/Align-columns @@ -0,0 +1 @@ +../../Task/Align-columns/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Aliquot-sequence-classifications b/Lang/Crystal/Aliquot-sequence-classifications new file mode 120000 index 0000000000..7453e5fb67 --- /dev/null +++ b/Lang/Crystal/Aliquot-sequence-classifications @@ -0,0 +1 @@ +../../Task/Aliquot-sequence-classifications/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Almost-prime b/Lang/Crystal/Almost-prime new file mode 120000 index 0000000000..782486465b --- /dev/null +++ b/Lang/Crystal/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Amb b/Lang/Crystal/Amb new file mode 120000 index 0000000000..31a9ff96ef --- /dev/null +++ b/Lang/Crystal/Amb @@ -0,0 +1 @@ +../../Task/Amb/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Anagrams-Deranged-anagrams b/Lang/Crystal/Anagrams-Deranged-anagrams new file mode 120000 index 0000000000..01826ee4a9 --- /dev/null +++ b/Lang/Crystal/Anagrams-Deranged-anagrams @@ -0,0 +1 @@ +../../Task/Anagrams-Deranged-anagrams/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Angle-difference-between-two-bearings b/Lang/Crystal/Angle-difference-between-two-bearings new file mode 120000 index 0000000000..80eb3d6093 --- /dev/null +++ b/Lang/Crystal/Angle-difference-between-two-bearings @@ -0,0 +1 @@ +../../Task/Angle-difference-between-two-bearings/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Angles-geometric-normalization-and-conversion b/Lang/Crystal/Angles-geometric-normalization-and-conversion new file mode 120000 index 0000000000..a07d6f6045 --- /dev/null +++ b/Lang/Crystal/Angles-geometric-normalization-and-conversion @@ -0,0 +1 @@ +../../Task/Angles-geometric-normalization-and-conversion/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Anonymous-recursion b/Lang/Crystal/Anonymous-recursion new file mode 120000 index 0000000000..8266f214bc --- /dev/null +++ b/Lang/Crystal/Anonymous-recursion @@ -0,0 +1 @@ +../../Task/Anonymous-recursion/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Append-a-record-to-the-end-of-a-text-file b/Lang/Crystal/Append-a-record-to-the-end-of-a-text-file new file mode 120000 index 0000000000..2a2afc8f9c --- /dev/null +++ b/Lang/Crystal/Append-a-record-to-the-end-of-a-text-file @@ -0,0 +1 @@ +../../Task/Append-a-record-to-the-end-of-a-text-file/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Apply-a-digital-filter-direct-form-II-transposed- b/Lang/Crystal/Apply-a-digital-filter-direct-form-II-transposed- new file mode 120000 index 0000000000..4772cfa6a5 --- /dev/null +++ b/Lang/Crystal/Apply-a-digital-filter-direct-form-II-transposed- @@ -0,0 +1 @@ +../../Task/Apply-a-digital-filter-direct-form-II-transposed-/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Approximate-equality b/Lang/Crystal/Approximate-equality new file mode 120000 index 0000000000..f45d53cb9c --- /dev/null +++ b/Lang/Crystal/Approximate-equality @@ -0,0 +1 @@ +../../Task/Approximate-equality/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Archimedean-spiral b/Lang/Crystal/Archimedean-spiral new file mode 120000 index 0000000000..38cdafc563 --- /dev/null +++ b/Lang/Crystal/Archimedean-spiral @@ -0,0 +1 @@ +../../Task/Archimedean-spiral/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Arithmetic-Complex b/Lang/Crystal/Arithmetic-Complex new file mode 120000 index 0000000000..db70676449 --- /dev/null +++ b/Lang/Crystal/Arithmetic-Complex @@ -0,0 +1 @@ +../../Task/Arithmetic-Complex/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Arithmetic-Rational b/Lang/Crystal/Arithmetic-Rational new file mode 120000 index 0000000000..9934cb69b5 --- /dev/null +++ b/Lang/Crystal/Arithmetic-Rational @@ -0,0 +1 @@ +../../Task/Arithmetic-Rational/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Arithmetic-derivative b/Lang/Crystal/Arithmetic-derivative new file mode 120000 index 0000000000..afe551091f --- /dev/null +++ b/Lang/Crystal/Arithmetic-derivative @@ -0,0 +1 @@ +../../Task/Arithmetic-derivative/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Arithmetic-evaluation b/Lang/Crystal/Arithmetic-evaluation new file mode 120000 index 0000000000..cefbf4e2d9 --- /dev/null +++ b/Lang/Crystal/Arithmetic-evaluation @@ -0,0 +1 @@ +../../Task/Arithmetic-evaluation/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Arithmetic-geometric-mean b/Lang/Crystal/Arithmetic-geometric-mean new file mode 120000 index 0000000000..c8754aa805 --- /dev/null +++ b/Lang/Crystal/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Arithmetic-geometric-mean-Calculate-Pi b/Lang/Crystal/Arithmetic-geometric-mean-Calculate-Pi new file mode 120000 index 0000000000..b641674514 --- /dev/null +++ b/Lang/Crystal/Arithmetic-geometric-mean-Calculate-Pi @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean-Calculate-Pi/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Arithmetic-numbers b/Lang/Crystal/Arithmetic-numbers new file mode 120000 index 0000000000..a07126fc36 --- /dev/null +++ b/Lang/Crystal/Arithmetic-numbers @@ -0,0 +1 @@ +../../Task/Arithmetic-numbers/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Ascending-primes b/Lang/Crystal/Ascending-primes new file mode 120000 index 0000000000..159e1b5bed --- /dev/null +++ b/Lang/Crystal/Ascending-primes @@ -0,0 +1 @@ +../../Task/Ascending-primes/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Atomic-updates b/Lang/Crystal/Atomic-updates new file mode 120000 index 0000000000..332b197fee --- /dev/null +++ b/Lang/Crystal/Atomic-updates @@ -0,0 +1 @@ +../../Task/Atomic-updates/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Attractive-numbers b/Lang/Crystal/Attractive-numbers new file mode 120000 index 0000000000..04e80138ee --- /dev/null +++ b/Lang/Crystal/Attractive-numbers @@ -0,0 +1 @@ +../../Task/Attractive-numbers/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Average-loop-length b/Lang/Crystal/Average-loop-length new file mode 120000 index 0000000000..06beee4e14 --- /dev/null +++ b/Lang/Crystal/Average-loop-length @@ -0,0 +1 @@ +../../Task/Average-loop-length/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Averages-Mean-angle b/Lang/Crystal/Averages-Mean-angle new file mode 120000 index 0000000000..8e548785b0 --- /dev/null +++ b/Lang/Crystal/Averages-Mean-angle @@ -0,0 +1 @@ +../../Task/Averages-Mean-angle/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Averages-Mean-time-of-day b/Lang/Crystal/Averages-Mean-time-of-day new file mode 120000 index 0000000000..4952b673eb --- /dev/null +++ b/Lang/Crystal/Averages-Mean-time-of-day @@ -0,0 +1 @@ +../../Task/Averages-Mean-time-of-day/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Averages-Mode b/Lang/Crystal/Averages-Mode new file mode 120000 index 0000000000..bb15fa305b --- /dev/null +++ b/Lang/Crystal/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Averages-Pythagorean-means b/Lang/Crystal/Averages-Pythagorean-means new file mode 120000 index 0000000000..a97d5df819 --- /dev/null +++ b/Lang/Crystal/Averages-Pythagorean-means @@ -0,0 +1 @@ +../../Task/Averages-Pythagorean-means/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Babbage-problem b/Lang/Crystal/Babbage-problem new file mode 120000 index 0000000000..7e1cc42ea8 --- /dev/null +++ b/Lang/Crystal/Babbage-problem @@ -0,0 +1 @@ +../../Task/Babbage-problem/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Babylonian-spiral b/Lang/Crystal/Babylonian-spiral new file mode 120000 index 0000000000..7478d85b07 --- /dev/null +++ b/Lang/Crystal/Babylonian-spiral @@ -0,0 +1 @@ +../../Task/Babylonian-spiral/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Bell-numbers b/Lang/Crystal/Bell-numbers new file mode 120000 index 0000000000..3f05e224a6 --- /dev/null +++ b/Lang/Crystal/Bell-numbers @@ -0,0 +1 @@ +../../Task/Bell-numbers/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Bifid-cipher b/Lang/Crystal/Bifid-cipher new file mode 120000 index 0000000000..6b07c1520e --- /dev/null +++ b/Lang/Crystal/Bifid-cipher @@ -0,0 +1 @@ +../../Task/Bifid-cipher/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Bin-given-limits b/Lang/Crystal/Bin-given-limits new file mode 120000 index 0000000000..40a049c833 --- /dev/null +++ b/Lang/Crystal/Bin-given-limits @@ -0,0 +1 @@ +../../Task/Bin-given-limits/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Bioinformatics-Global-alignment b/Lang/Crystal/Bioinformatics-Global-alignment new file mode 120000 index 0000000000..b8310a94b2 --- /dev/null +++ b/Lang/Crystal/Bioinformatics-Global-alignment @@ -0,0 +1 @@ +../../Task/Bioinformatics-Global-alignment/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Biorhythms b/Lang/Crystal/Biorhythms new file mode 120000 index 0000000000..adde97b4c1 --- /dev/null +++ b/Lang/Crystal/Biorhythms @@ -0,0 +1 @@ +../../Task/Biorhythms/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Bitmap-Bresenhams-line-algorithm b/Lang/Crystal/Bitmap-Bresenhams-line-algorithm new file mode 120000 index 0000000000..680f0b15d0 --- /dev/null +++ b/Lang/Crystal/Bitmap-Bresenhams-line-algorithm @@ -0,0 +1 @@ +../../Task/Bitmap-Bresenhams-line-algorithm/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Bitmap-Flood-fill b/Lang/Crystal/Bitmap-Flood-fill new file mode 120000 index 0000000000..82f2b7e4ae --- /dev/null +++ b/Lang/Crystal/Bitmap-Flood-fill @@ -0,0 +1 @@ +../../Task/Bitmap-Flood-fill/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Bitmap-Midpoint-circle-algorithm b/Lang/Crystal/Bitmap-Midpoint-circle-algorithm new file mode 120000 index 0000000000..fd45ea7903 --- /dev/null +++ b/Lang/Crystal/Bitmap-Midpoint-circle-algorithm @@ -0,0 +1 @@ +../../Task/Bitmap-Midpoint-circle-algorithm/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Bitmap-Read-a-PPM-file b/Lang/Crystal/Bitmap-Read-a-PPM-file new file mode 120000 index 0000000000..72567511a0 --- /dev/null +++ b/Lang/Crystal/Bitmap-Read-a-PPM-file @@ -0,0 +1 @@ +../../Task/Bitmap-Read-a-PPM-file/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Bitmap-Write-a-PPM-file b/Lang/Crystal/Bitmap-Write-a-PPM-file new file mode 120000 index 0000000000..86ca9711aa --- /dev/null +++ b/Lang/Crystal/Bitmap-Write-a-PPM-file @@ -0,0 +1 @@ +../../Task/Bitmap-Write-a-PPM-file/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Bitwise-operations b/Lang/Crystal/Bitwise-operations new file mode 120000 index 0000000000..1a5350f2cc --- /dev/null +++ b/Lang/Crystal/Bitwise-operations @@ -0,0 +1 @@ +../../Task/Bitwise-operations/Crystal \ No newline at end of file diff --git a/Lang/Crystal/CUSIP b/Lang/Crystal/CUSIP new file mode 120000 index 0000000000..b88441138f --- /dev/null +++ b/Lang/Crystal/CUSIP @@ -0,0 +1 @@ +../../Task/CUSIP/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Camel-case-and-snake-case b/Lang/Crystal/Camel-case-and-snake-case new file mode 120000 index 0000000000..04ca76eb1a --- /dev/null +++ b/Lang/Crystal/Camel-case-and-snake-case @@ -0,0 +1 @@ +../../Task/Camel-case-and-snake-case/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Catamorphism b/Lang/Crystal/Catamorphism new file mode 120000 index 0000000000..59ec253ef2 --- /dev/null +++ b/Lang/Crystal/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Chaocipher b/Lang/Crystal/Chaocipher new file mode 120000 index 0000000000..b200ad768f --- /dev/null +++ b/Lang/Crystal/Chaocipher @@ -0,0 +1 @@ +../../Task/Chaocipher/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Character-codes b/Lang/Crystal/Character-codes new file mode 120000 index 0000000000..bd4879b77c --- /dev/null +++ b/Lang/Crystal/Character-codes @@ -0,0 +1 @@ +../../Task/Character-codes/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Cistercian-numerals b/Lang/Crystal/Cistercian-numerals new file mode 120000 index 0000000000..b439a8a963 --- /dev/null +++ b/Lang/Crystal/Cistercian-numerals @@ -0,0 +1 @@ +../../Task/Cistercian-numerals/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Closures-Value-capture b/Lang/Crystal/Closures-Value-capture new file mode 120000 index 0000000000..f3038be393 --- /dev/null +++ b/Lang/Crystal/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Color-wheel b/Lang/Crystal/Color-wheel new file mode 120000 index 0000000000..b0d2a4f84a --- /dev/null +++ b/Lang/Crystal/Color-wheel @@ -0,0 +1 @@ +../../Task/Color-wheel/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Colour-bars-Display b/Lang/Crystal/Colour-bars-Display new file mode 120000 index 0000000000..0ec7f62738 --- /dev/null +++ b/Lang/Crystal/Colour-bars-Display @@ -0,0 +1 @@ +../../Task/Colour-bars-Display/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Comma-quibbling b/Lang/Crystal/Comma-quibbling new file mode 120000 index 0000000000..3151a9c58f --- /dev/null +++ b/Lang/Crystal/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Compare-a-list-of-strings b/Lang/Crystal/Compare-a-list-of-strings new file mode 120000 index 0000000000..f978784371 --- /dev/null +++ b/Lang/Crystal/Compare-a-list-of-strings @@ -0,0 +1 @@ +../../Task/Compare-a-list-of-strings/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Compile-time-calculation b/Lang/Crystal/Compile-time-calculation new file mode 120000 index 0000000000..306dfbb009 --- /dev/null +++ b/Lang/Crystal/Compile-time-calculation @@ -0,0 +1 @@ +../../Task/Compile-time-calculation/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Consecutive-primes-with-ascending-or-descending-differences b/Lang/Crystal/Consecutive-primes-with-ascending-or-descending-differences new file mode 120000 index 0000000000..697e7e52cd --- /dev/null +++ b/Lang/Crystal/Consecutive-primes-with-ascending-or-descending-differences @@ -0,0 +1 @@ +../../Task/Consecutive-primes-with-ascending-or-descending-differences/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Convert-seconds-to-compound-duration b/Lang/Crystal/Convert-seconds-to-compound-duration new file mode 120000 index 0000000000..313254bee3 --- /dev/null +++ b/Lang/Crystal/Convert-seconds-to-compound-duration @@ -0,0 +1 @@ +../../Task/Convert-seconds-to-compound-duration/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Count-occurrences-of-a-substring b/Lang/Crystal/Count-occurrences-of-a-substring new file mode 120000 index 0000000000..f235e95129 --- /dev/null +++ b/Lang/Crystal/Count-occurrences-of-a-substring @@ -0,0 +1 @@ +../../Task/Count-occurrences-of-a-substring/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Cullen-and-Woodall-numbers b/Lang/Crystal/Cullen-and-Woodall-numbers new file mode 120000 index 0000000000..62ef13cd07 --- /dev/null +++ b/Lang/Crystal/Cullen-and-Woodall-numbers @@ -0,0 +1 @@ +../../Task/Cullen-and-Woodall-numbers/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Currency b/Lang/Crystal/Currency new file mode 120000 index 0000000000..275fd9dcb2 --- /dev/null +++ b/Lang/Crystal/Currency @@ -0,0 +1 @@ +../../Task/Currency/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Day-of-the-week b/Lang/Crystal/Day-of-the-week new file mode 120000 index 0000000000..0f98ad94ee --- /dev/null +++ b/Lang/Crystal/Day-of-the-week @@ -0,0 +1 @@ +../../Task/Day-of-the-week/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Department-numbers b/Lang/Crystal/Department-numbers new file mode 120000 index 0000000000..1e36b398e9 --- /dev/null +++ b/Lang/Crystal/Department-numbers @@ -0,0 +1 @@ +../../Task/Department-numbers/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Detect-division-by-zero b/Lang/Crystal/Detect-division-by-zero new file mode 120000 index 0000000000..d23bedf4f0 --- /dev/null +++ b/Lang/Crystal/Detect-division-by-zero @@ -0,0 +1 @@ +../../Task/Detect-division-by-zero/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Determine-if-a-string-has-all-the-same-characters b/Lang/Crystal/Determine-if-a-string-has-all-the-same-characters new file mode 120000 index 0000000000..a0bef4d19a --- /dev/null +++ b/Lang/Crystal/Determine-if-a-string-has-all-the-same-characters @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-has-all-the-same-characters/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Determine-if-a-string-is-collapsible b/Lang/Crystal/Determine-if-a-string-is-collapsible new file mode 120000 index 0000000000..7e2d57c2cb --- /dev/null +++ b/Lang/Crystal/Determine-if-a-string-is-collapsible @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-collapsible/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Determine-if-a-string-is-numeric b/Lang/Crystal/Determine-if-a-string-is-numeric new file mode 120000 index 0000000000..907fa1cc6f --- /dev/null +++ b/Lang/Crystal/Determine-if-a-string-is-numeric @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-numeric/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Determine-sentence-type b/Lang/Crystal/Determine-sentence-type new file mode 120000 index 0000000000..95914c2896 --- /dev/null +++ b/Lang/Crystal/Determine-sentence-type @@ -0,0 +1 @@ +../../Task/Determine-sentence-type/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Digital-root-Multiplicative-digital-root b/Lang/Crystal/Digital-root-Multiplicative-digital-root new file mode 120000 index 0000000000..92366c8b32 --- /dev/null +++ b/Lang/Crystal/Digital-root-Multiplicative-digital-root @@ -0,0 +1 @@ +../../Task/Digital-root-Multiplicative-digital-root/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Dijkstras-algorithm b/Lang/Crystal/Dijkstras-algorithm new file mode 120000 index 0000000000..829bbaa132 --- /dev/null +++ b/Lang/Crystal/Dijkstras-algorithm @@ -0,0 +1 @@ +../../Task/Dijkstras-algorithm/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Diversity-prediction-theorem b/Lang/Crystal/Diversity-prediction-theorem new file mode 120000 index 0000000000..bfb6463f86 --- /dev/null +++ b/Lang/Crystal/Diversity-prediction-theorem @@ -0,0 +1 @@ +../../Task/Diversity-prediction-theorem/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Dutch-national-flag-problem b/Lang/Crystal/Dutch-national-flag-problem new file mode 120000 index 0000000000..a920e0b89a --- /dev/null +++ b/Lang/Crystal/Dutch-national-flag-problem @@ -0,0 +1 @@ +../../Task/Dutch-national-flag-problem/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Egyptian-division b/Lang/Crystal/Egyptian-division new file mode 120000 index 0000000000..6766caec22 --- /dev/null +++ b/Lang/Crystal/Egyptian-division @@ -0,0 +1 @@ +../../Task/Egyptian-division/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Elementary-cellular-automaton b/Lang/Crystal/Elementary-cellular-automaton new file mode 120000 index 0000000000..a397b94a1b --- /dev/null +++ b/Lang/Crystal/Elementary-cellular-automaton @@ -0,0 +1 @@ +../../Task/Elementary-cellular-automaton/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Elementary-cellular-automaton-Random-number-generator b/Lang/Crystal/Elementary-cellular-automaton-Random-number-generator new file mode 120000 index 0000000000..6d743a5fc8 --- /dev/null +++ b/Lang/Crystal/Elementary-cellular-automaton-Random-number-generator @@ -0,0 +1 @@ +../../Task/Elementary-cellular-automaton-Random-number-generator/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Emirp-primes b/Lang/Crystal/Emirp-primes new file mode 120000 index 0000000000..6a762271db --- /dev/null +++ b/Lang/Crystal/Emirp-primes @@ -0,0 +1 @@ +../../Task/Emirp-primes/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Empty-program b/Lang/Crystal/Empty-program deleted file mode 120000 index 78e7f559d2..0000000000 --- a/Lang/Crystal/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Enumerations b/Lang/Crystal/Enumerations new file mode 120000 index 0000000000..81276f7ab4 --- /dev/null +++ b/Lang/Crystal/Enumerations @@ -0,0 +1 @@ +../../Task/Enumerations/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Environment-variables b/Lang/Crystal/Environment-variables new file mode 120000 index 0000000000..17cbcdefee --- /dev/null +++ b/Lang/Crystal/Environment-variables @@ -0,0 +1 @@ +../../Task/Environment-variables/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Equilibrium-index b/Lang/Crystal/Equilibrium-index new file mode 120000 index 0000000000..1125331aa6 --- /dev/null +++ b/Lang/Crystal/Equilibrium-index @@ -0,0 +1 @@ +../../Task/Equilibrium-index/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Ethiopian-multiplication b/Lang/Crystal/Ethiopian-multiplication new file mode 120000 index 0000000000..e534df962f --- /dev/null +++ b/Lang/Crystal/Ethiopian-multiplication @@ -0,0 +1 @@ +../../Task/Ethiopian-multiplication/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Evolutionary-algorithm b/Lang/Crystal/Evolutionary-algorithm new file mode 120000 index 0000000000..a0bcba6242 --- /dev/null +++ b/Lang/Crystal/Evolutionary-algorithm @@ -0,0 +1 @@ +../../Task/Evolutionary-algorithm/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Execute-Brain- b/Lang/Crystal/Execute-Brain- new file mode 120000 index 0000000000..4ffee47edd --- /dev/null +++ b/Lang/Crystal/Execute-Brain- @@ -0,0 +1 @@ +../../Task/Execute-Brain-/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Exponentiation-order b/Lang/Crystal/Exponentiation-order new file mode 120000 index 0000000000..e7f6547257 --- /dev/null +++ b/Lang/Crystal/Exponentiation-order @@ -0,0 +1 @@ +../../Task/Exponentiation-order/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Exponentiation-with-infix-operators-in-or-operating-on-the-base b/Lang/Crystal/Exponentiation-with-infix-operators-in-or-operating-on-the-base new file mode 120000 index 0000000000..bea2082efb --- /dev/null +++ b/Lang/Crystal/Exponentiation-with-infix-operators-in-or-operating-on-the-base @@ -0,0 +1 @@ +../../Task/Exponentiation-with-infix-operators-in-or-operating-on-the-base/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Extensible-prime-generator b/Lang/Crystal/Extensible-prime-generator new file mode 120000 index 0000000000..f7e46afa3d --- /dev/null +++ b/Lang/Crystal/Extensible-prime-generator @@ -0,0 +1 @@ +../../Task/Extensible-prime-generator/Crystal \ No newline at end of file diff --git a/Lang/Crystal/File-extension-is-in-extensions-list b/Lang/Crystal/File-extension-is-in-extensions-list new file mode 120000 index 0000000000..d3f5d5ad97 --- /dev/null +++ b/Lang/Crystal/File-extension-is-in-extensions-list @@ -0,0 +1 @@ +../../Task/File-extension-is-in-extensions-list/Crystal \ No newline at end of file diff --git a/Lang/Crystal/File-modification-time b/Lang/Crystal/File-modification-time new file mode 120000 index 0000000000..b3a7e1065d --- /dev/null +++ b/Lang/Crystal/File-modification-time @@ -0,0 +1 @@ +../../Task/File-modification-time/Crystal \ No newline at end of file diff --git a/Lang/Crystal/File-size b/Lang/Crystal/File-size new file mode 120000 index 0000000000..f7ccd8930e --- /dev/null +++ b/Lang/Crystal/File-size @@ -0,0 +1 @@ +../../Task/File-size/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Filter b/Lang/Crystal/Filter new file mode 120000 index 0000000000..13d5962733 --- /dev/null +++ b/Lang/Crystal/Filter @@ -0,0 +1 @@ +../../Task/Filter/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Find-if-a-point-is-within-a-triangle b/Lang/Crystal/Find-if-a-point-is-within-a-triangle new file mode 120000 index 0000000000..a3ff575d32 --- /dev/null +++ b/Lang/Crystal/Find-if-a-point-is-within-a-triangle @@ -0,0 +1 @@ +../../Task/Find-if-a-point-is-within-a-triangle/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Find-the-last-Sunday-of-each-month b/Lang/Crystal/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..b7448c15e3 --- /dev/null +++ b/Lang/Crystal/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/Crystal \ No newline at end of file diff --git a/Lang/Crystal/First-class-functions b/Lang/Crystal/First-class-functions new file mode 120000 index 0000000000..41628a5683 --- /dev/null +++ b/Lang/Crystal/First-class-functions @@ -0,0 +1 @@ +../../Task/First-class-functions/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Five-weekends b/Lang/Crystal/Five-weekends new file mode 120000 index 0000000000..aee26e19f7 --- /dev/null +++ b/Lang/Crystal/Five-weekends @@ -0,0 +1 @@ +../../Task/Five-weekends/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Four-is-magic b/Lang/Crystal/Four-is-magic new file mode 120000 index 0000000000..e56a866dc3 --- /dev/null +++ b/Lang/Crystal/Four-is-magic @@ -0,0 +1 @@ +../../Task/Four-is-magic/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Function-definition b/Lang/Crystal/Function-definition new file mode 120000 index 0000000000..1fac36efe3 --- /dev/null +++ b/Lang/Crystal/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Generate-lower-case-ASCII-alphabet b/Lang/Crystal/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..8b481efdf1 --- /dev/null +++ b/Lang/Crystal/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Generator-Exponential b/Lang/Crystal/Generator-Exponential new file mode 120000 index 0000000000..d9c996b99e --- /dev/null +++ b/Lang/Crystal/Generator-Exponential @@ -0,0 +1 @@ +../../Task/Generator-Exponential/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Get-system-command-output b/Lang/Crystal/Get-system-command-output new file mode 120000 index 0000000000..75fcf73ed6 --- /dev/null +++ b/Lang/Crystal/Get-system-command-output @@ -0,0 +1 @@ +../../Task/Get-system-command-output/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Greatest-common-divisor b/Lang/Crystal/Greatest-common-divisor new file mode 120000 index 0000000000..cac765e22c --- /dev/null +++ b/Lang/Crystal/Greatest-common-divisor @@ -0,0 +1 @@ +../../Task/Greatest-common-divisor/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Hello-world-Newline-omission b/Lang/Crystal/Hello-world-Newline-omission new file mode 120000 index 0000000000..cf00f3e8a9 --- /dev/null +++ b/Lang/Crystal/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Hello-world-Standard-error b/Lang/Crystal/Hello-world-Standard-error new file mode 120000 index 0000000000..560e23c97c --- /dev/null +++ b/Lang/Crystal/Hello-world-Standard-error @@ -0,0 +1 @@ +../../Task/Hello-world-Standard-error/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Hex-words b/Lang/Crystal/Hex-words new file mode 120000 index 0000000000..1390f8d3e3 --- /dev/null +++ b/Lang/Crystal/Hex-words @@ -0,0 +1 @@ +../../Task/Hex-words/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Hofstadter-Q-sequence b/Lang/Crystal/Hofstadter-Q-sequence new file mode 120000 index 0000000000..a856d63c6d --- /dev/null +++ b/Lang/Crystal/Hofstadter-Q-sequence @@ -0,0 +1 @@ +../../Task/Hofstadter-Q-sequence/Crystal \ No newline at end of file diff --git a/Lang/Crystal/ISBN13-check-digit b/Lang/Crystal/ISBN13-check-digit new file mode 120000 index 0000000000..eedbc71ec1 --- /dev/null +++ b/Lang/Crystal/ISBN13-check-digit @@ -0,0 +1 @@ +../../Task/ISBN13-check-digit/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Idiomatically-determine-all-the-lowercase-and-uppercase-letters b/Lang/Crystal/Idiomatically-determine-all-the-lowercase-and-uppercase-letters new file mode 120000 index 0000000000..9e0f4e23b4 --- /dev/null +++ b/Lang/Crystal/Idiomatically-determine-all-the-lowercase-and-uppercase-letters @@ -0,0 +1 @@ +../../Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Increment-a-numerical-string b/Lang/Crystal/Increment-a-numerical-string new file mode 120000 index 0000000000..aeae95c765 --- /dev/null +++ b/Lang/Crystal/Increment-a-numerical-string @@ -0,0 +1 @@ +../../Task/Increment-a-numerical-string/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Input-loop b/Lang/Crystal/Input-loop new file mode 120000 index 0000000000..27bc4f9208 --- /dev/null +++ b/Lang/Crystal/Input-loop @@ -0,0 +1 @@ +../../Task/Input-loop/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Integer-comparison b/Lang/Crystal/Integer-comparison new file mode 120000 index 0000000000..1d8d9443a7 --- /dev/null +++ b/Lang/Crystal/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Integer-overflow b/Lang/Crystal/Integer-overflow new file mode 120000 index 0000000000..868816b94b --- /dev/null +++ b/Lang/Crystal/Integer-overflow @@ -0,0 +1 @@ +../../Task/Integer-overflow/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Interactive-programming-repl- b/Lang/Crystal/Interactive-programming-repl- new file mode 120000 index 0000000000..348f845b57 --- /dev/null +++ b/Lang/Crystal/Interactive-programming-repl- @@ -0,0 +1 @@ +../../Task/Interactive-programming-repl-/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Inverted-syntax b/Lang/Crystal/Inverted-syntax new file mode 120000 index 0000000000..33eb9c0c4b --- /dev/null +++ b/Lang/Crystal/Inverted-syntax @@ -0,0 +1 @@ +../../Task/Inverted-syntax/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Isograms-and-heterograms b/Lang/Crystal/Isograms-and-heterograms new file mode 120000 index 0000000000..46dc26699c --- /dev/null +++ b/Lang/Crystal/Isograms-and-heterograms @@ -0,0 +1 @@ +../../Task/Isograms-and-heterograms/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Isqrt-integer-square-root-of-X b/Lang/Crystal/Isqrt-integer-square-root-of-X new file mode 120000 index 0000000000..d671dd4e29 --- /dev/null +++ b/Lang/Crystal/Isqrt-integer-square-root-of-X @@ -0,0 +1 @@ +../../Task/Isqrt-integer-square-root-of-X/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Jacobsthal-numbers b/Lang/Crystal/Jacobsthal-numbers new file mode 120000 index 0000000000..da4fc1eede --- /dev/null +++ b/Lang/Crystal/Jacobsthal-numbers @@ -0,0 +1 @@ +../../Task/Jacobsthal-numbers/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Kernighans-large-earthquake-problem b/Lang/Crystal/Kernighans-large-earthquake-problem new file mode 120000 index 0000000000..d6f60d2a2c --- /dev/null +++ b/Lang/Crystal/Kernighans-large-earthquake-problem @@ -0,0 +1 @@ +../../Task/Kernighans-large-earthquake-problem/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Knuths-algorithm-S b/Lang/Crystal/Knuths-algorithm-S new file mode 120000 index 0000000000..fbde0f33c9 --- /dev/null +++ b/Lang/Crystal/Knuths-algorithm-S @@ -0,0 +1 @@ +../../Task/Knuths-algorithm-S/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Langtons-ant b/Lang/Crystal/Langtons-ant new file mode 120000 index 0000000000..accd634e59 --- /dev/null +++ b/Lang/Crystal/Langtons-ant @@ -0,0 +1 @@ +../../Task/Langtons-ant/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Last-Friday-of-each-month b/Lang/Crystal/Last-Friday-of-each-month new file mode 120000 index 0000000000..5dd6eb4e30 --- /dev/null +++ b/Lang/Crystal/Last-Friday-of-each-month @@ -0,0 +1 @@ +../../Task/Last-Friday-of-each-month/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Least-common-multiple b/Lang/Crystal/Least-common-multiple new file mode 120000 index 0000000000..ab85fbea40 --- /dev/null +++ b/Lang/Crystal/Least-common-multiple @@ -0,0 +1 @@ +../../Task/Least-common-multiple/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Letter-frequency b/Lang/Crystal/Letter-frequency new file mode 120000 index 0000000000..9aed428d1c --- /dev/null +++ b/Lang/Crystal/Letter-frequency @@ -0,0 +1 @@ +../../Task/Letter-frequency/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Logical-operations b/Lang/Crystal/Logical-operations new file mode 120000 index 0000000000..efa5e278dd --- /dev/null +++ b/Lang/Crystal/Logical-operations @@ -0,0 +1 @@ +../../Task/Logical-operations/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Logistic-curve-fitting-in-epidemiology b/Lang/Crystal/Logistic-curve-fitting-in-epidemiology new file mode 120000 index 0000000000..c8d098d82a --- /dev/null +++ b/Lang/Crystal/Logistic-curve-fitting-in-epidemiology @@ -0,0 +1 @@ +../../Task/Logistic-curve-fitting-in-epidemiology/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Long-year b/Lang/Crystal/Long-year new file mode 120000 index 0000000000..2a978e84d7 --- /dev/null +++ b/Lang/Crystal/Long-year @@ -0,0 +1 @@ +../../Task/Long-year/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Longest-string-challenge b/Lang/Crystal/Longest-string-challenge new file mode 120000 index 0000000000..8a9ac3dfd0 --- /dev/null +++ b/Lang/Crystal/Longest-string-challenge @@ -0,0 +1 @@ +../../Task/Longest-string-challenge/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Loops-Do-while b/Lang/Crystal/Loops-Do-while new file mode 120000 index 0000000000..16d73545fb --- /dev/null +++ b/Lang/Crystal/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Loops-Foreach b/Lang/Crystal/Loops-Foreach new file mode 120000 index 0000000000..c20a1c8c2c --- /dev/null +++ b/Lang/Crystal/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Loops-N-plus-one-half b/Lang/Crystal/Loops-N-plus-one-half new file mode 120000 index 0000000000..baee612204 --- /dev/null +++ b/Lang/Crystal/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Loops-With-multiple-ranges b/Lang/Crystal/Loops-With-multiple-ranges new file mode 120000 index 0000000000..a0c34f1c73 --- /dev/null +++ b/Lang/Crystal/Loops-With-multiple-ranges @@ -0,0 +1 @@ +../../Task/Loops-With-multiple-ranges/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Loops-Wrong-ranges b/Lang/Crystal/Loops-Wrong-ranges new file mode 120000 index 0000000000..402c2c3d6b --- /dev/null +++ b/Lang/Crystal/Loops-Wrong-ranges @@ -0,0 +1 @@ +../../Task/Loops-Wrong-ranges/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Magic-8-ball b/Lang/Crystal/Magic-8-ball new file mode 120000 index 0000000000..7694de9dbd --- /dev/null +++ b/Lang/Crystal/Magic-8-ball @@ -0,0 +1 @@ +../../Task/Magic-8-ball/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Magnanimous-numbers b/Lang/Crystal/Magnanimous-numbers new file mode 120000 index 0000000000..f025f31b2f --- /dev/null +++ b/Lang/Crystal/Magnanimous-numbers @@ -0,0 +1 @@ +../../Task/Magnanimous-numbers/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Map-range b/Lang/Crystal/Map-range new file mode 120000 index 0000000000..2ce80c8e32 --- /dev/null +++ b/Lang/Crystal/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Middle-three-digits b/Lang/Crystal/Middle-three-digits new file mode 120000 index 0000000000..c195484a68 --- /dev/null +++ b/Lang/Crystal/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Miller-Rabin-primality-test b/Lang/Crystal/Miller-Rabin-primality-test deleted file mode 120000 index 3714050251..0000000000 --- a/Lang/Crystal/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Move-to-front-algorithm b/Lang/Crystal/Move-to-front-algorithm new file mode 120000 index 0000000000..1fc15ab4a7 --- /dev/null +++ b/Lang/Crystal/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Narcissistic-decimal-number b/Lang/Crystal/Narcissistic-decimal-number new file mode 120000 index 0000000000..7713050610 --- /dev/null +++ b/Lang/Crystal/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Nested-function b/Lang/Crystal/Nested-function new file mode 120000 index 0000000000..4453485348 --- /dev/null +++ b/Lang/Crystal/Nested-function @@ -0,0 +1 @@ +../../Task/Nested-function/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Non-decimal-radices-Convert b/Lang/Crystal/Non-decimal-radices-Convert new file mode 120000 index 0000000000..342df0f845 --- /dev/null +++ b/Lang/Crystal/Non-decimal-radices-Convert @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Convert/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Number-names b/Lang/Crystal/Number-names new file mode 120000 index 0000000000..65ddc62215 --- /dev/null +++ b/Lang/Crystal/Number-names @@ -0,0 +1 @@ +../../Task/Number-names/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Numbers-with-equal-rises-and-falls b/Lang/Crystal/Numbers-with-equal-rises-and-falls new file mode 120000 index 0000000000..6aa2426e57 --- /dev/null +++ b/Lang/Crystal/Numbers-with-equal-rises-and-falls @@ -0,0 +1 @@ +../../Task/Numbers-with-equal-rises-and-falls/Crystal \ No newline at end of file diff --git a/Lang/Crystal/One-dimensional-cellular-automata b/Lang/Crystal/One-dimensional-cellular-automata new file mode 120000 index 0000000000..e519134b4d --- /dev/null +++ b/Lang/Crystal/One-dimensional-cellular-automata @@ -0,0 +1 @@ +../../Task/One-dimensional-cellular-automata/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Order-by-pair-comparisons b/Lang/Crystal/Order-by-pair-comparisons new file mode 120000 index 0000000000..7f819e26a0 --- /dev/null +++ b/Lang/Crystal/Order-by-pair-comparisons @@ -0,0 +1 @@ +../../Task/Order-by-pair-comparisons/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Order-two-numerical-lists b/Lang/Crystal/Order-two-numerical-lists new file mode 120000 index 0000000000..44bdc040e5 --- /dev/null +++ b/Lang/Crystal/Order-two-numerical-lists @@ -0,0 +1 @@ +../../Task/Order-two-numerical-lists/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Ordered-words b/Lang/Crystal/Ordered-words new file mode 120000 index 0000000000..52c1bed5c6 --- /dev/null +++ b/Lang/Crystal/Ordered-words @@ -0,0 +1 @@ +../../Task/Ordered-words/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Palindrome-dates b/Lang/Crystal/Palindrome-dates new file mode 120000 index 0000000000..e9d9714cac --- /dev/null +++ b/Lang/Crystal/Palindrome-dates @@ -0,0 +1 @@ +../../Task/Palindrome-dates/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Parallel-brute-force b/Lang/Crystal/Parallel-brute-force new file mode 120000 index 0000000000..496ce76b45 --- /dev/null +++ b/Lang/Crystal/Parallel-brute-force @@ -0,0 +1 @@ +../../Task/Parallel-brute-force/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Parse-an-IP-Address b/Lang/Crystal/Parse-an-IP-Address new file mode 120000 index 0000000000..940d156ab2 --- /dev/null +++ b/Lang/Crystal/Parse-an-IP-Address @@ -0,0 +1 @@ +../../Task/Parse-an-IP-Address/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Parsing-RPN-calculator-algorithm b/Lang/Crystal/Parsing-RPN-calculator-algorithm new file mode 120000 index 0000000000..79e0e2ae7e --- /dev/null +++ b/Lang/Crystal/Parsing-RPN-calculator-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-RPN-calculator-algorithm/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Parsing-RPN-to-infix-conversion b/Lang/Crystal/Parsing-RPN-to-infix-conversion new file mode 120000 index 0000000000..e19adc6368 --- /dev/null +++ b/Lang/Crystal/Parsing-RPN-to-infix-conversion @@ -0,0 +1 @@ +../../Task/Parsing-RPN-to-infix-conversion/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Parsing-Shunting-yard-algorithm b/Lang/Crystal/Parsing-Shunting-yard-algorithm new file mode 120000 index 0000000000..a18ff957d5 --- /dev/null +++ b/Lang/Crystal/Parsing-Shunting-yard-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-Shunting-yard-algorithm/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Partial-function-application b/Lang/Crystal/Partial-function-application new file mode 120000 index 0000000000..06b96bb5bb --- /dev/null +++ b/Lang/Crystal/Partial-function-application @@ -0,0 +1 @@ +../../Task/Partial-function-application/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Perfect-numbers b/Lang/Crystal/Perfect-numbers new file mode 120000 index 0000000000..708a2045e2 --- /dev/null +++ b/Lang/Crystal/Perfect-numbers @@ -0,0 +1 @@ +../../Task/Perfect-numbers/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Phrase-reversals b/Lang/Crystal/Phrase-reversals new file mode 120000 index 0000000000..7a12cc6718 --- /dev/null +++ b/Lang/Crystal/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Power-set b/Lang/Crystal/Power-set new file mode 120000 index 0000000000..0fd70fd5b9 --- /dev/null +++ b/Lang/Crystal/Power-set @@ -0,0 +1 @@ +../../Task/Power-set/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Priority-queue b/Lang/Crystal/Priority-queue new file mode 120000 index 0000000000..4f7dddb139 --- /dev/null +++ b/Lang/Crystal/Priority-queue @@ -0,0 +1 @@ +../../Task/Priority-queue/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Program-name b/Lang/Crystal/Program-name new file mode 120000 index 0000000000..0398fe1a1e --- /dev/null +++ b/Lang/Crystal/Program-name @@ -0,0 +1 @@ +../../Task/Program-name/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Quaternion-type b/Lang/Crystal/Quaternion-type deleted file mode 120000 index 5a28c33333..0000000000 --- a/Lang/Crystal/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Random-sentence-from-book b/Lang/Crystal/Random-sentence-from-book new file mode 120000 index 0000000000..916a4913b6 --- /dev/null +++ b/Lang/Crystal/Random-sentence-from-book @@ -0,0 +1 @@ +../../Task/Random-sentence-from-book/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Range-extraction b/Lang/Crystal/Range-extraction new file mode 120000 index 0000000000..984878874c --- /dev/null +++ b/Lang/Crystal/Range-extraction @@ -0,0 +1 @@ +../../Task/Range-extraction/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Regular-expressions b/Lang/Crystal/Regular-expressions new file mode 120000 index 0000000000..1e1b324d69 --- /dev/null +++ b/Lang/Crystal/Regular-expressions @@ -0,0 +1 @@ +../../Task/Regular-expressions/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Repeat b/Lang/Crystal/Repeat new file mode 120000 index 0000000000..cbbc5973da --- /dev/null +++ b/Lang/Crystal/Repeat @@ -0,0 +1 @@ +../../Task/Repeat/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Return-multiple-values b/Lang/Crystal/Return-multiple-values new file mode 120000 index 0000000000..df0883e4b0 --- /dev/null +++ b/Lang/Crystal/Return-multiple-values @@ -0,0 +1 @@ +../../Task/Return-multiple-values/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Reverse-words-in-a-string b/Lang/Crystal/Reverse-words-in-a-string new file mode 120000 index 0000000000..44576bae9a --- /dev/null +++ b/Lang/Crystal/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Rosetta-Code-Rank-languages-by-popularity b/Lang/Crystal/Rosetta-Code-Rank-languages-by-popularity new file mode 120000 index 0000000000..69fe9e65d5 --- /dev/null +++ b/Lang/Crystal/Rosetta-Code-Rank-languages-by-popularity @@ -0,0 +1 @@ +../../Task/Rosetta-Code-Rank-languages-by-popularity/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Rot-13 b/Lang/Crystal/Rot-13 new file mode 120000 index 0000000000..430011bd06 --- /dev/null +++ b/Lang/Crystal/Rot-13 @@ -0,0 +1 @@ +../../Task/Rot-13/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Run-length-encoding b/Lang/Crystal/Run-length-encoding new file mode 120000 index 0000000000..1a2b6b241a --- /dev/null +++ b/Lang/Crystal/Run-length-encoding @@ -0,0 +1 @@ +../../Task/Run-length-encoding/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Search-a-list b/Lang/Crystal/Search-a-list new file mode 120000 index 0000000000..975cbb3120 --- /dev/null +++ b/Lang/Crystal/Search-a-list @@ -0,0 +1 @@ +../../Task/Search-a-list/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Sequence-of-non-squares b/Lang/Crystal/Sequence-of-non-squares new file mode 120000 index 0000000000..4854c5c8ce --- /dev/null +++ b/Lang/Crystal/Sequence-of-non-squares @@ -0,0 +1 @@ +../../Task/Sequence-of-non-squares/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Set b/Lang/Crystal/Set new file mode 120000 index 0000000000..09e0457880 --- /dev/null +++ b/Lang/Crystal/Set @@ -0,0 +1 @@ +../../Task/Set/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Short-circuit-evaluation b/Lang/Crystal/Short-circuit-evaluation new file mode 120000 index 0000000000..42f8d1e06a --- /dev/null +++ b/Lang/Crystal/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Simple-database b/Lang/Crystal/Simple-database new file mode 120000 index 0000000000..91a24ce202 --- /dev/null +++ b/Lang/Crystal/Simple-database @@ -0,0 +1 @@ +../../Task/Simple-database/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Singly-linked-list-Element-definition b/Lang/Crystal/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..1c9a4e215c --- /dev/null +++ b/Lang/Crystal/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Singly-linked-list-Element-insertion b/Lang/Crystal/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..e0de17b549 --- /dev/null +++ b/Lang/Crystal/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Singly-linked-list-Traversal b/Lang/Crystal/Singly-linked-list-Traversal new file mode 120000 index 0000000000..e89e5d42db --- /dev/null +++ b/Lang/Crystal/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Sleep b/Lang/Crystal/Sleep new file mode 120000 index 0000000000..1648e77b82 --- /dev/null +++ b/Lang/Crystal/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Sleeping-Beauty-problem b/Lang/Crystal/Sleeping-Beauty-problem new file mode 120000 index 0000000000..50b43e53b7 --- /dev/null +++ b/Lang/Crystal/Sleeping-Beauty-problem @@ -0,0 +1 @@ +../../Task/Sleeping-Beauty-problem/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Soloways-recurring-rainfall b/Lang/Crystal/Soloways-recurring-rainfall new file mode 120000 index 0000000000..017187c230 --- /dev/null +++ b/Lang/Crystal/Soloways-recurring-rainfall @@ -0,0 +1 @@ +../../Task/Soloways-recurring-rainfall/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Sort-a-list-of-object-identifiers b/Lang/Crystal/Sort-a-list-of-object-identifiers new file mode 120000 index 0000000000..2b599d3df1 --- /dev/null +++ b/Lang/Crystal/Sort-a-list-of-object-identifiers @@ -0,0 +1 @@ +../../Task/Sort-a-list-of-object-identifiers/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Sort-an-array-of-composite-structures b/Lang/Crystal/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..5ea781aef9 --- /dev/null +++ b/Lang/Crystal/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Sort-disjoint-sublist b/Lang/Crystal/Sort-disjoint-sublist new file mode 120000 index 0000000000..a252445ff4 --- /dev/null +++ b/Lang/Crystal/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Sort-numbers-lexicographically b/Lang/Crystal/Sort-numbers-lexicographically new file mode 120000 index 0000000000..884dc88521 --- /dev/null +++ b/Lang/Crystal/Sort-numbers-lexicographically @@ -0,0 +1 @@ +../../Task/Sort-numbers-lexicographically/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Sort-three-variables b/Lang/Crystal/Sort-three-variables new file mode 120000 index 0000000000..e206daaf02 --- /dev/null +++ b/Lang/Crystal/Sort-three-variables @@ -0,0 +1 @@ +../../Task/Sort-three-variables/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Sort-using-a-custom-comparator b/Lang/Crystal/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..0614ceb188 --- /dev/null +++ b/Lang/Crystal/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Sorting-algorithms-Bubble-sort b/Lang/Crystal/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..88a150acfe --- /dev/null +++ b/Lang/Crystal/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Sorting-algorithms-Stooge-sort b/Lang/Crystal/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..9882d0a5e5 --- /dev/null +++ b/Lang/Crystal/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Sparkline-in-unicode b/Lang/Crystal/Sparkline-in-unicode new file mode 120000 index 0000000000..986b27240a --- /dev/null +++ b/Lang/Crystal/Sparkline-in-unicode @@ -0,0 +1 @@ +../../Task/Sparkline-in-unicode/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Spelling-of-ordinal-numbers b/Lang/Crystal/Spelling-of-ordinal-numbers new file mode 120000 index 0000000000..68e66511d0 --- /dev/null +++ b/Lang/Crystal/Spelling-of-ordinal-numbers @@ -0,0 +1 @@ +../../Task/Spelling-of-ordinal-numbers/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Split-a-character-string-based-on-change-of-character b/Lang/Crystal/Split-a-character-string-based-on-change-of-character new file mode 120000 index 0000000000..874feaced9 --- /dev/null +++ b/Lang/Crystal/Split-a-character-string-based-on-change-of-character @@ -0,0 +1 @@ +../../Task/Split-a-character-string-based-on-change-of-character/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Stack-traces b/Lang/Crystal/Stack-traces new file mode 120000 index 0000000000..9cc8cddb52 --- /dev/null +++ b/Lang/Crystal/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Stem-and-leaf-plot b/Lang/Crystal/Stem-and-leaf-plot new file mode 120000 index 0000000000..4fac378f12 --- /dev/null +++ b/Lang/Crystal/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Stirling-numbers-of-the-first-kind b/Lang/Crystal/Stirling-numbers-of-the-first-kind new file mode 120000 index 0000000000..8a52252a36 --- /dev/null +++ b/Lang/Crystal/Stirling-numbers-of-the-first-kind @@ -0,0 +1 @@ +../../Task/Stirling-numbers-of-the-first-kind/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Straddling-checkerboard b/Lang/Crystal/Straddling-checkerboard new file mode 120000 index 0000000000..1550d42cee --- /dev/null +++ b/Lang/Crystal/Straddling-checkerboard @@ -0,0 +1 @@ +../../Task/Straddling-checkerboard/Crystal \ No newline at end of file diff --git a/Lang/Crystal/String-append b/Lang/Crystal/String-append new file mode 120000 index 0000000000..4f16bddd70 --- /dev/null +++ b/Lang/Crystal/String-append @@ -0,0 +1 @@ +../../Task/String-append/Crystal \ No newline at end of file diff --git a/Lang/Crystal/String-concatenation b/Lang/Crystal/String-concatenation new file mode 120000 index 0000000000..1237b70607 --- /dev/null +++ b/Lang/Crystal/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Crystal \ No newline at end of file diff --git a/Lang/Crystal/String-interpolation-included- b/Lang/Crystal/String-interpolation-included- new file mode 120000 index 0000000000..05bff0aabd --- /dev/null +++ b/Lang/Crystal/String-interpolation-included- @@ -0,0 +1 @@ +../../Task/String-interpolation-included-/Crystal \ No newline at end of file diff --git a/Lang/Crystal/String-matching b/Lang/Crystal/String-matching new file mode 120000 index 0000000000..439dd1fa36 --- /dev/null +++ b/Lang/Crystal/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Crystal \ No newline at end of file diff --git a/Lang/Crystal/String-prepend b/Lang/Crystal/String-prepend new file mode 120000 index 0000000000..2c5c171e4c --- /dev/null +++ b/Lang/Crystal/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Strip-a-set-of-characters-from-a-string b/Lang/Crystal/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..7c09aa4ce1 --- /dev/null +++ b/Lang/Crystal/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Strip-block-comments b/Lang/Crystal/Strip-block-comments new file mode 120000 index 0000000000..2a4303ed27 --- /dev/null +++ b/Lang/Crystal/Strip-block-comments @@ -0,0 +1 @@ +../../Task/Strip-block-comments/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Strip-comments-from-a-string b/Lang/Crystal/Strip-comments-from-a-string new file mode 120000 index 0000000000..bf4a72832d --- /dev/null +++ b/Lang/Crystal/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Strip-control-codes-and-extended-characters-from-a-string b/Lang/Crystal/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..2831009e2a --- /dev/null +++ b/Lang/Crystal/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Substring-Top-and-tail b/Lang/Crystal/Substring-Top-and-tail new file mode 120000 index 0000000000..d3af8a2b7f --- /dev/null +++ b/Lang/Crystal/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Sudan-function b/Lang/Crystal/Sudan-function new file mode 120000 index 0000000000..a75bf5defc --- /dev/null +++ b/Lang/Crystal/Sudan-function @@ -0,0 +1 @@ +../../Task/Sudan-function/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Sum-to-100 b/Lang/Crystal/Sum-to-100 new file mode 120000 index 0000000000..02859f9ab7 --- /dev/null +++ b/Lang/Crystal/Sum-to-100 @@ -0,0 +1 @@ +../../Task/Sum-to-100/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Summarize-and-say-sequence b/Lang/Crystal/Summarize-and-say-sequence new file mode 120000 index 0000000000..ac69b16598 --- /dev/null +++ b/Lang/Crystal/Summarize-and-say-sequence @@ -0,0 +1 @@ +../../Task/Summarize-and-say-sequence/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Sylvesters-sequence b/Lang/Crystal/Sylvesters-sequence new file mode 120000 index 0000000000..cd026cc33a --- /dev/null +++ b/Lang/Crystal/Sylvesters-sequence @@ -0,0 +1 @@ +../../Task/Sylvesters-sequence/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Symmetric-difference b/Lang/Crystal/Symmetric-difference new file mode 120000 index 0000000000..566657d82c --- /dev/null +++ b/Lang/Crystal/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Take-notes-on-the-command-line b/Lang/Crystal/Take-notes-on-the-command-line new file mode 120000 index 0000000000..e978486e4d --- /dev/null +++ b/Lang/Crystal/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Temperature-conversion b/Lang/Crystal/Temperature-conversion new file mode 120000 index 0000000000..d97258c24c --- /dev/null +++ b/Lang/Crystal/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Ternary-logic b/Lang/Crystal/Ternary-logic new file mode 120000 index 0000000000..adfcdc28dd --- /dev/null +++ b/Lang/Crystal/Ternary-logic @@ -0,0 +1 @@ +../../Task/Ternary-logic/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Textonyms b/Lang/Crystal/Textonyms new file mode 120000 index 0000000000..e9c8a3c5ec --- /dev/null +++ b/Lang/Crystal/Textonyms @@ -0,0 +1 @@ +../../Task/Textonyms/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Towers-of-Hanoi b/Lang/Crystal/Towers-of-Hanoi new file mode 120000 index 0000000000..49ee652bdd --- /dev/null +++ b/Lang/Crystal/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Transliterate-English-text-using-the-Greek-alphabet b/Lang/Crystal/Transliterate-English-text-using-the-Greek-alphabet new file mode 120000 index 0000000000..cb70d2aa14 --- /dev/null +++ b/Lang/Crystal/Transliterate-English-text-using-the-Greek-alphabet @@ -0,0 +1 @@ +../../Task/Transliterate-English-text-using-the-Greek-alphabet/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Truncate-a-file b/Lang/Crystal/Truncate-a-file new file mode 120000 index 0000000000..a75ef5468d --- /dev/null +++ b/Lang/Crystal/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Truth-table b/Lang/Crystal/Truth-table new file mode 120000 index 0000000000..7f3aa2a526 --- /dev/null +++ b/Lang/Crystal/Truth-table @@ -0,0 +1 @@ +../../Task/Truth-table/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Twos-complement b/Lang/Crystal/Twos-complement new file mode 120000 index 0000000000..2272e1c36b --- /dev/null +++ b/Lang/Crystal/Twos-complement @@ -0,0 +1 @@ +../../Task/Twos-complement/Crystal \ No newline at end of file diff --git a/Lang/Crystal/UPC b/Lang/Crystal/UPC new file mode 120000 index 0000000000..b4d8d405f7 --- /dev/null +++ b/Lang/Crystal/UPC @@ -0,0 +1 @@ +../../Task/UPC/Crystal \ No newline at end of file diff --git a/Lang/Crystal/UTF-8-encode-and-decode b/Lang/Crystal/UTF-8-encode-and-decode new file mode 120000 index 0000000000..acebf418fa --- /dev/null +++ b/Lang/Crystal/UTF-8-encode-and-decode @@ -0,0 +1 @@ +../../Task/UTF-8-encode-and-decode/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Van-der-Corput-sequence b/Lang/Crystal/Van-der-Corput-sequence new file mode 120000 index 0000000000..c9bba5d9e9 --- /dev/null +++ b/Lang/Crystal/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Variable-length-quantity b/Lang/Crystal/Variable-length-quantity new file mode 120000 index 0000000000..4664ff0cf8 --- /dev/null +++ b/Lang/Crystal/Variable-length-quantity @@ -0,0 +1 @@ +../../Task/Variable-length-quantity/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Vector b/Lang/Crystal/Vector new file mode 120000 index 0000000000..eff97fd6f9 --- /dev/null +++ b/Lang/Crystal/Vector @@ -0,0 +1 @@ +../../Task/Vector/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Wagstaff-primes b/Lang/Crystal/Wagstaff-primes new file mode 120000 index 0000000000..ce243d1192 --- /dev/null +++ b/Lang/Crystal/Wagstaff-primes @@ -0,0 +1 @@ +../../Task/Wagstaff-primes/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Wordiff b/Lang/Crystal/Wordiff new file mode 120000 index 0000000000..fcf6f8935c --- /dev/null +++ b/Lang/Crystal/Wordiff @@ -0,0 +1 @@ +../../Task/Wordiff/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Write-entire-file b/Lang/Crystal/Write-entire-file new file mode 120000 index 0000000000..f56680457a --- /dev/null +++ b/Lang/Crystal/Write-entire-file @@ -0,0 +1 @@ +../../Task/Write-entire-file/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Write-language-name-in-3D-ASCII b/Lang/Crystal/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..668585ccef --- /dev/null +++ b/Lang/Crystal/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/Crystal \ No newline at end of file diff --git a/Lang/Crystal/XML-Input b/Lang/Crystal/XML-Input new file mode 120000 index 0000000000..186294c638 --- /dev/null +++ b/Lang/Crystal/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/Crystal \ No newline at end of file diff --git a/Lang/Crystal/XML-XPath b/Lang/Crystal/XML-XPath new file mode 120000 index 0000000000..cc58f19135 --- /dev/null +++ b/Lang/Crystal/XML-XPath @@ -0,0 +1 @@ +../../Task/XML-XPath/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Yellowstone-sequence b/Lang/Crystal/Yellowstone-sequence new file mode 120000 index 0000000000..e0ffb2052b --- /dev/null +++ b/Lang/Crystal/Yellowstone-sequence @@ -0,0 +1 @@ +../../Task/Yellowstone-sequence/Crystal \ No newline at end of file diff --git a/Lang/D/Find-Chess960-starting-position-identifier b/Lang/D/Find-Chess960-starting-position-identifier new file mode 120000 index 0000000000..79e07139b9 --- /dev/null +++ b/Lang/D/Find-Chess960-starting-position-identifier @@ -0,0 +1 @@ +../../Task/Find-Chess960-starting-position-identifier/D \ No newline at end of file diff --git a/Lang/D/Miller-Rabin-primality-test b/Lang/D/Miller-Rabin-primality-test deleted file mode 120000 index 407bdbfce4..0000000000 --- a/Lang/D/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/D \ No newline at end of file diff --git a/Lang/D/Quaternion-type b/Lang/D/Quaternion-type deleted file mode 120000 index 4703070a3f..0000000000 --- a/Lang/D/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/D \ No newline at end of file diff --git a/Lang/D/Sorting-Algorithms-Circle-Sort b/Lang/D/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 950d2a1c8c..0000000000 --- a/Lang/D/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/D \ No newline at end of file diff --git a/Lang/Dart/15-puzzle-solver b/Lang/Dart/15-puzzle-solver new file mode 120000 index 0000000000..9e8e216a39 --- /dev/null +++ b/Lang/Dart/15-puzzle-solver @@ -0,0 +1 @@ +../../Task/15-puzzle-solver/Dart \ No newline at end of file diff --git a/Lang/Dart/24-game-Solve b/Lang/Dart/24-game-Solve new file mode 120000 index 0000000000..ae64875d6c --- /dev/null +++ b/Lang/Dart/24-game-Solve @@ -0,0 +1 @@ +../../Task/24-game-Solve/Dart \ No newline at end of file diff --git a/Lang/Dart/AVL-tree b/Lang/Dart/AVL-tree new file mode 120000 index 0000000000..00bc5f9c2f --- /dev/null +++ b/Lang/Dart/AVL-tree @@ -0,0 +1 @@ +../../Task/AVL-tree/Dart \ No newline at end of file diff --git a/Lang/Dart/Benfords-law b/Lang/Dart/Benfords-law new file mode 120000 index 0000000000..bccac375ec --- /dev/null +++ b/Lang/Dart/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/Dart \ No newline at end of file diff --git a/Lang/Dart/Boyer-Moore-string-search b/Lang/Dart/Boyer-Moore-string-search new file mode 120000 index 0000000000..8b8a6a6060 --- /dev/null +++ b/Lang/Dart/Boyer-Moore-string-search @@ -0,0 +1 @@ +../../Task/Boyer-Moore-string-search/Dart \ No newline at end of file diff --git a/Lang/Dart/Break-OO-privacy b/Lang/Dart/Break-OO-privacy new file mode 120000 index 0000000000..e07e79a6ca --- /dev/null +++ b/Lang/Dart/Break-OO-privacy @@ -0,0 +1 @@ +../../Task/Break-OO-privacy/Dart \ No newline at end of file diff --git a/Lang/Dart/Character-codes b/Lang/Dart/Character-codes new file mode 120000 index 0000000000..eee070c4f5 --- /dev/null +++ b/Lang/Dart/Character-codes @@ -0,0 +1 @@ +../../Task/Character-codes/Dart \ No newline at end of file diff --git a/Lang/Dart/Continued-fraction b/Lang/Dart/Continued-fraction new file mode 120000 index 0000000000..ea5b665958 --- /dev/null +++ b/Lang/Dart/Continued-fraction @@ -0,0 +1 @@ +../../Task/Continued-fraction/Dart \ No newline at end of file diff --git a/Lang/Dart/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- b/Lang/Dart/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- new file mode 120000 index 0000000000..eb55960eb5 --- /dev/null +++ b/Lang/Dart/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n-/Dart \ No newline at end of file diff --git a/Lang/Dart/Cullen-and-Woodall-numbers b/Lang/Dart/Cullen-and-Woodall-numbers new file mode 120000 index 0000000000..573f34cd4f --- /dev/null +++ b/Lang/Dart/Cullen-and-Woodall-numbers @@ -0,0 +1 @@ +../../Task/Cullen-and-Woodall-numbers/Dart \ No newline at end of file diff --git a/Lang/Dart/Day-of-the-week b/Lang/Dart/Day-of-the-week new file mode 120000 index 0000000000..15dd0e18f6 --- /dev/null +++ b/Lang/Dart/Day-of-the-week @@ -0,0 +1 @@ +../../Task/Day-of-the-week/Dart \ No newline at end of file diff --git a/Lang/Dart/De-Bruijn-sequences b/Lang/Dart/De-Bruijn-sequences new file mode 120000 index 0000000000..f7a9a5e2e1 --- /dev/null +++ b/Lang/Dart/De-Bruijn-sequences @@ -0,0 +1 @@ +../../Task/De-Bruijn-sequences/Dart \ No newline at end of file diff --git a/Lang/Dart/Determine-sentence-type b/Lang/Dart/Determine-sentence-type new file mode 120000 index 0000000000..cbfbfb1793 --- /dev/null +++ b/Lang/Dart/Determine-sentence-type @@ -0,0 +1 @@ +../../Task/Determine-sentence-type/Dart \ No newline at end of file diff --git a/Lang/Dart/Dijkstras-algorithm b/Lang/Dart/Dijkstras-algorithm new file mode 120000 index 0000000000..fc7b73a06b --- /dev/null +++ b/Lang/Dart/Dijkstras-algorithm @@ -0,0 +1 @@ +../../Task/Dijkstras-algorithm/Dart \ No newline at end of file diff --git a/Lang/Dart/Diversity-prediction-theorem b/Lang/Dart/Diversity-prediction-theorem new file mode 120000 index 0000000000..525bb8c4cf --- /dev/null +++ b/Lang/Dart/Diversity-prediction-theorem @@ -0,0 +1 @@ +../../Task/Diversity-prediction-theorem/Dart \ No newline at end of file diff --git a/Lang/Dart/Floyd-Warshall-algorithm b/Lang/Dart/Floyd-Warshall-algorithm new file mode 120000 index 0000000000..34dc98809b --- /dev/null +++ b/Lang/Dart/Floyd-Warshall-algorithm @@ -0,0 +1 @@ +../../Task/Floyd-Warshall-algorithm/Dart \ No newline at end of file diff --git a/Lang/Dart/Generate-lower-case-ASCII-alphabet b/Lang/Dart/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..947014123e --- /dev/null +++ b/Lang/Dart/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Dart \ No newline at end of file diff --git a/Lang/Dart/Iterated-digits-squaring b/Lang/Dart/Iterated-digits-squaring new file mode 120000 index 0000000000..87955b71c0 --- /dev/null +++ b/Lang/Dart/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/Dart \ No newline at end of file diff --git a/Lang/Dart/Jensens-Device b/Lang/Dart/Jensens-Device new file mode 120000 index 0000000000..973fbf791f --- /dev/null +++ b/Lang/Dart/Jensens-Device @@ -0,0 +1 @@ +../../Task/Jensens-Device/Dart \ No newline at end of file diff --git a/Lang/Dart/Jewels-and-stones b/Lang/Dart/Jewels-and-stones new file mode 120000 index 0000000000..8673bcd41d --- /dev/null +++ b/Lang/Dart/Jewels-and-stones @@ -0,0 +1 @@ +../../Task/Jewels-and-stones/Dart \ No newline at end of file diff --git a/Lang/Dart/K-d-tree b/Lang/Dart/K-d-tree new file mode 120000 index 0000000000..4b4a8013e5 --- /dev/null +++ b/Lang/Dart/K-d-tree @@ -0,0 +1 @@ +../../Task/K-d-tree/Dart \ No newline at end of file diff --git a/Lang/Dart/Leonardo-numbers b/Lang/Dart/Leonardo-numbers new file mode 120000 index 0000000000..93d2f002c1 --- /dev/null +++ b/Lang/Dart/Leonardo-numbers @@ -0,0 +1 @@ +../../Task/Leonardo-numbers/Dart \ No newline at end of file diff --git a/Lang/Dart/Map-range b/Lang/Dart/Map-range new file mode 120000 index 0000000000..5ed6b07ca1 --- /dev/null +++ b/Lang/Dart/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/Dart \ No newline at end of file diff --git a/Lang/Dart/Meissel-Mertens-constant b/Lang/Dart/Meissel-Mertens-constant deleted file mode 120000 index bac3ec4c99..0000000000 --- a/Lang/Dart/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/Dart \ No newline at end of file diff --git a/Lang/Dart/Modular-exponentiation b/Lang/Dart/Modular-exponentiation new file mode 120000 index 0000000000..afe2138c27 --- /dev/null +++ b/Lang/Dart/Modular-exponentiation @@ -0,0 +1 @@ +../../Task/Modular-exponentiation/Dart \ No newline at end of file diff --git a/Lang/Dart/Ormiston-triples b/Lang/Dart/Ormiston-triples new file mode 120000 index 0000000000..ddb933956b --- /dev/null +++ b/Lang/Dart/Ormiston-triples @@ -0,0 +1 @@ +../../Task/Ormiston-triples/Dart \ No newline at end of file diff --git a/Lang/Dart/Pancake-numbers b/Lang/Dart/Pancake-numbers new file mode 120000 index 0000000000..78b8078b97 --- /dev/null +++ b/Lang/Dart/Pancake-numbers @@ -0,0 +1 @@ +../../Task/Pancake-numbers/Dart \ No newline at end of file diff --git a/Lang/Dart/Parse-an-IP-Address b/Lang/Dart/Parse-an-IP-Address new file mode 120000 index 0000000000..bbe41020cb --- /dev/null +++ b/Lang/Dart/Parse-an-IP-Address @@ -0,0 +1 @@ +../../Task/Parse-an-IP-Address/Dart \ No newline at end of file diff --git a/Lang/Dart/Parsing-Shunting-yard-algorithm b/Lang/Dart/Parsing-Shunting-yard-algorithm new file mode 120000 index 0000000000..764230d0e5 --- /dev/null +++ b/Lang/Dart/Parsing-Shunting-yard-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-Shunting-yard-algorithm/Dart \ No newline at end of file diff --git a/Lang/Dart/Partition-an-integer-x-into-n-primes b/Lang/Dart/Partition-an-integer-x-into-n-primes new file mode 120000 index 0000000000..4b67e26b1a --- /dev/null +++ b/Lang/Dart/Partition-an-integer-x-into-n-primes @@ -0,0 +1 @@ +../../Task/Partition-an-integer-x-into-n-primes/Dart \ No newline at end of file diff --git a/Lang/Dart/Partition-function-P b/Lang/Dart/Partition-function-P new file mode 120000 index 0000000000..9146b4b231 --- /dev/null +++ b/Lang/Dart/Partition-function-P @@ -0,0 +1 @@ +../../Task/Partition-function-P/Dart \ No newline at end of file diff --git a/Lang/Dart/Penneys-game b/Lang/Dart/Penneys-game new file mode 120000 index 0000000000..f054d83b87 --- /dev/null +++ b/Lang/Dart/Penneys-game @@ -0,0 +1 @@ +../../Task/Penneys-game/Dart \ No newline at end of file diff --git a/Lang/Dart/Quaternion-type b/Lang/Dart/Quaternion-type deleted file mode 120000 index fb391b98d0..0000000000 --- a/Lang/Dart/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Dart \ No newline at end of file diff --git a/Lang/Dart/Random-Latin-squares b/Lang/Dart/Random-Latin-squares new file mode 120000 index 0000000000..226cba5197 --- /dev/null +++ b/Lang/Dart/Random-Latin-squares @@ -0,0 +1 @@ +../../Task/Random-Latin-squares/Dart \ No newline at end of file diff --git a/Lang/Dart/Random-sentence-from-book b/Lang/Dart/Random-sentence-from-book new file mode 120000 index 0000000000..2b4a3a67d4 --- /dev/null +++ b/Lang/Dart/Random-sentence-from-book @@ -0,0 +1 @@ +../../Task/Random-sentence-from-book/Dart \ No newline at end of file diff --git a/Lang/Dart/Repeat b/Lang/Dart/Repeat new file mode 120000 index 0000000000..f9635c7eb9 --- /dev/null +++ b/Lang/Dart/Repeat @@ -0,0 +1 @@ +../../Task/Repeat/Dart \ No newline at end of file diff --git a/Lang/Dart/Solve-a-Numbrix-puzzle b/Lang/Dart/Solve-a-Numbrix-puzzle new file mode 120000 index 0000000000..38339de00c --- /dev/null +++ b/Lang/Dart/Solve-a-Numbrix-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Numbrix-puzzle/Dart \ No newline at end of file diff --git a/Lang/Dart/Sorting-algorithms-Gnome-sort b/Lang/Dart/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..0f0280ed89 --- /dev/null +++ b/Lang/Dart/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Dart \ No newline at end of file diff --git a/Lang/Dart/Split-a-character-string-based-on-change-of-character b/Lang/Dart/Split-a-character-string-based-on-change-of-character new file mode 120000 index 0000000000..06c92b1b7c --- /dev/null +++ b/Lang/Dart/Split-a-character-string-based-on-change-of-character @@ -0,0 +1 @@ +../../Task/Split-a-character-string-based-on-change-of-character/Dart \ No newline at end of file diff --git a/Lang/Dart/Strassens-algorithm b/Lang/Dart/Strassens-algorithm new file mode 120000 index 0000000000..db4cbbbc5d --- /dev/null +++ b/Lang/Dart/Strassens-algorithm @@ -0,0 +1 @@ +../../Task/Strassens-algorithm/Dart \ No newline at end of file diff --git a/Lang/Dart/The-Name-Game b/Lang/Dart/The-Name-Game new file mode 120000 index 0000000000..41a16ad1a3 --- /dev/null +++ b/Lang/Dart/The-Name-Game @@ -0,0 +1 @@ +../../Task/The-Name-Game/Dart \ No newline at end of file diff --git a/Lang/Dart/Tonelli-Shanks-algorithm b/Lang/Dart/Tonelli-Shanks-algorithm new file mode 120000 index 0000000000..72acd046bd --- /dev/null +++ b/Lang/Dart/Tonelli-Shanks-algorithm @@ -0,0 +1 @@ +../../Task/Tonelli-Shanks-algorithm/Dart \ No newline at end of file diff --git a/Lang/Dart/Topological-sort b/Lang/Dart/Topological-sort new file mode 120000 index 0000000000..7361beca1d --- /dev/null +++ b/Lang/Dart/Topological-sort @@ -0,0 +1 @@ +../../Task/Topological-sort/Dart \ No newline at end of file diff --git a/Lang/Dart/Word-search b/Lang/Dart/Word-search new file mode 120000 index 0000000000..c9693c2a8f --- /dev/null +++ b/Lang/Dart/Word-search @@ -0,0 +1 @@ +../../Task/Word-search/Dart \ No newline at end of file diff --git a/Lang/Dc/Man-or-boy-test b/Lang/Dc/Man-or-boy-test new file mode 120000 index 0000000000..3b3beb62b4 --- /dev/null +++ b/Lang/Dc/Man-or-boy-test @@ -0,0 +1 @@ +../../Task/Man-or-boy-test/Dc \ No newline at end of file diff --git a/Lang/Delphi/Bioinformatics-base-count b/Lang/Delphi/Bioinformatics-base-count deleted file mode 120000 index 8964650820..0000000000 --- a/Lang/Delphi/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Generate-Chess960-starting-position b/Lang/Delphi/Generate-Chess960-starting-position new file mode 120000 index 0000000000..2c3a66190d --- /dev/null +++ b/Lang/Delphi/Generate-Chess960-starting-position @@ -0,0 +1 @@ +../../Task/Generate-Chess960-starting-position/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Meissel-Mertens-constant b/Lang/Delphi/Meissel-Mertens-constant deleted file mode 120000 index 2b1c7d3804..0000000000 --- a/Lang/Delphi/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Quaternion-type b/Lang/Delphi/Quaternion-type deleted file mode 120000 index fe804d3654..0000000000 --- a/Lang/Delphi/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Sorting-Algorithms-Circle-Sort b/Lang/Delphi/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index d4a4f938c0..0000000000 --- a/Lang/Delphi/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Delphi \ No newline at end of file diff --git a/Lang/Draco/Align-columns b/Lang/Draco/Align-columns new file mode 120000 index 0000000000..00c426b153 --- /dev/null +++ b/Lang/Draco/Align-columns @@ -0,0 +1 @@ +../../Task/Align-columns/Draco \ No newline at end of file diff --git a/Lang/Draco/Anti-primes b/Lang/Draco/Anti-primes new file mode 120000 index 0000000000..e9ba464537 --- /dev/null +++ b/Lang/Draco/Anti-primes @@ -0,0 +1 @@ +../../Task/Anti-primes/Draco \ No newline at end of file diff --git a/Lang/Draco/Arithmetic-derivative b/Lang/Draco/Arithmetic-derivative new file mode 120000 index 0000000000..b83ffadf85 --- /dev/null +++ b/Lang/Draco/Arithmetic-derivative @@ -0,0 +1 @@ +../../Task/Arithmetic-derivative/Draco \ No newline at end of file diff --git a/Lang/Draco/Compound-data-type b/Lang/Draco/Compound-data-type new file mode 120000 index 0000000000..4fcd536f99 --- /dev/null +++ b/Lang/Draco/Compound-data-type @@ -0,0 +1 @@ +../../Task/Compound-data-type/Draco \ No newline at end of file diff --git a/Lang/Draco/Cullen-and-Woodall-numbers b/Lang/Draco/Cullen-and-Woodall-numbers new file mode 120000 index 0000000000..4559430dd4 --- /dev/null +++ b/Lang/Draco/Cullen-and-Woodall-numbers @@ -0,0 +1 @@ +../../Task/Cullen-and-Woodall-numbers/Draco \ No newline at end of file diff --git a/Lang/Draco/Display-a-linear-combination b/Lang/Draco/Display-a-linear-combination new file mode 120000 index 0000000000..bbaeb41c31 --- /dev/null +++ b/Lang/Draco/Display-a-linear-combination @@ -0,0 +1 @@ +../../Task/Display-a-linear-combination/Draco \ No newline at end of file diff --git a/Lang/Draco/Doomsday-rule b/Lang/Draco/Doomsday-rule new file mode 120000 index 0000000000..50f248643e --- /dev/null +++ b/Lang/Draco/Doomsday-rule @@ -0,0 +1 @@ +../../Task/Doomsday-rule/Draco \ No newline at end of file diff --git a/Lang/Draco/Horners-rule-for-polynomial-evaluation b/Lang/Draco/Horners-rule-for-polynomial-evaluation new file mode 120000 index 0000000000..3be037b7e6 --- /dev/null +++ b/Lang/Draco/Horners-rule-for-polynomial-evaluation @@ -0,0 +1 @@ +../../Task/Horners-rule-for-polynomial-evaluation/Draco \ No newline at end of file diff --git a/Lang/Draco/Roman-numerals-Encode b/Lang/Draco/Roman-numerals-Encode new file mode 120000 index 0000000000..11eed87fb8 --- /dev/null +++ b/Lang/Draco/Roman-numerals-Encode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Encode/Draco \ No newline at end of file diff --git a/Lang/Draco/Tokenize-a-string b/Lang/Draco/Tokenize-a-string new file mode 120000 index 0000000000..b60ddd21df --- /dev/null +++ b/Lang/Draco/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Draco \ No newline at end of file diff --git a/Lang/Draco/Zeckendorf-number-representation b/Lang/Draco/Zeckendorf-number-representation new file mode 120000 index 0000000000..5142294607 --- /dev/null +++ b/Lang/Draco/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/Draco \ No newline at end of file diff --git a/Lang/Dragonstone/00-LANG.txt b/Lang/Dragonstone/00-LANG.txt new file mode 100644 index 0000000000..910f7b9a21 --- /dev/null +++ b/Lang/Dragonstone/00-LANG.txt @@ -0,0 +1,9 @@ +{{language +|exec=both +|gc=optional +|parampass=both +|express=both +|strength=strong +|checking=both +|site=http://dragonstone-lang.org}} +'''Dragonstone''' is a general purpose, high-level, object-oriented programming language. It is both an interpreted and compiled language, it's inspired by Ruby and Crystal but designed for programmer happiness, productivity, and choice. \ No newline at end of file diff --git a/Lang/Dragonstone/00-META.yaml b/Lang/Dragonstone/00-META.yaml new file mode 100644 index 0000000000..33832d2528 --- /dev/null +++ b/Lang/Dragonstone/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Dragonstone diff --git a/Lang/Dragonstone/Comments b/Lang/Dragonstone/Comments new file mode 120000 index 0000000000..49a5841988 --- /dev/null +++ b/Lang/Dragonstone/Comments @@ -0,0 +1 @@ +../../Task/Comments/Dragonstone \ No newline at end of file diff --git a/Lang/Dragonstone/Hello-world-Newline-omission b/Lang/Dragonstone/Hello-world-Newline-omission new file mode 120000 index 0000000000..a67c99cc88 --- /dev/null +++ b/Lang/Dragonstone/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/Dragonstone \ No newline at end of file diff --git a/Lang/Dragonstone/Hello-world-Text b/Lang/Dragonstone/Hello-world-Text new file mode 120000 index 0000000000..7f601f87ad --- /dev/null +++ b/Lang/Dragonstone/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Dragonstone \ No newline at end of file diff --git a/Lang/Dragonstone/Loops-While b/Lang/Dragonstone/Loops-While new file mode 120000 index 0000000000..c8a2239e27 --- /dev/null +++ b/Lang/Dragonstone/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/Dragonstone \ No newline at end of file diff --git a/Lang/DuckDB/00-LANG.txt b/Lang/DuckDB/00-LANG.txt new file mode 100644 index 0000000000..2609130966 --- /dev/null +++ b/Lang/DuckDB/00-LANG.txt @@ -0,0 +1,4 @@ +[[DuckDB]] is an open-source, fast in-process analytical database management system based on a feature-rich SQL dialect complemented with deep integrations into client APIs. + +[[Category:Programming Languages]] +[[Category:SQL]] \ No newline at end of file diff --git a/Lang/DuckDB/00-META.yaml b/Lang/DuckDB/00-META.yaml new file mode 100644 index 0000000000..c9eafe7cf5 --- /dev/null +++ b/Lang/DuckDB/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:DuckDB diff --git a/Lang/DuckDB/100-doors b/Lang/DuckDB/100-doors new file mode 120000 index 0000000000..a0ee1f337e --- /dev/null +++ b/Lang/DuckDB/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/99-bottles-of-beer b/Lang/DuckDB/99-bottles-of-beer new file mode 120000 index 0000000000..c5f15cd273 --- /dev/null +++ b/Lang/DuckDB/99-bottles-of-beer @@ -0,0 +1 @@ +../../Task/99-bottles-of-beer/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/A+B b/Lang/DuckDB/A+B new file mode 120000 index 0000000000..ae6220876f --- /dev/null +++ b/Lang/DuckDB/A+B @@ -0,0 +1 @@ +../../Task/A+B/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/ABC-problem b/Lang/DuckDB/ABC-problem new file mode 120000 index 0000000000..36e60dd0cd --- /dev/null +++ b/Lang/DuckDB/ABC-problem @@ -0,0 +1 @@ +../../Task/ABC-problem/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Anagrams b/Lang/DuckDB/Anagrams new file mode 120000 index 0000000000..e80c01b2e3 --- /dev/null +++ b/Lang/DuckDB/Anagrams @@ -0,0 +1 @@ +../../Task/Anagrams/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Anonymous-recursion b/Lang/DuckDB/Anonymous-recursion new file mode 120000 index 0000000000..e4448d2542 --- /dev/null +++ b/Lang/DuckDB/Anonymous-recursion @@ -0,0 +1 @@ +../../Task/Anonymous-recursion/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Arithmetic-Complex b/Lang/DuckDB/Arithmetic-Complex new file mode 120000 index 0000000000..7e149e59dc --- /dev/null +++ b/Lang/DuckDB/Arithmetic-Complex @@ -0,0 +1 @@ +../../Task/Arithmetic-Complex/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Arithmetic-Integer b/Lang/DuckDB/Arithmetic-Integer new file mode 120000 index 0000000000..5bc3696b71 --- /dev/null +++ b/Lang/DuckDB/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Arithmetic-geometric-mean b/Lang/DuckDB/Arithmetic-geometric-mean new file mode 120000 index 0000000000..2519d0a8f8 --- /dev/null +++ b/Lang/DuckDB/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Arithmetic-numbers b/Lang/DuckDB/Arithmetic-numbers new file mode 120000 index 0000000000..a5e7e075b9 --- /dev/null +++ b/Lang/DuckDB/Arithmetic-numbers @@ -0,0 +1 @@ +../../Task/Arithmetic-numbers/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Array-concatenation b/Lang/DuckDB/Array-concatenation new file mode 120000 index 0000000000..7ef5be0b5a --- /dev/null +++ b/Lang/DuckDB/Array-concatenation @@ -0,0 +1 @@ +../../Task/Array-concatenation/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Array-length b/Lang/DuckDB/Array-length new file mode 120000 index 0000000000..ebd59786ea --- /dev/null +++ b/Lang/DuckDB/Array-length @@ -0,0 +1 @@ +../../Task/Array-length/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Arrays b/Lang/DuckDB/Arrays new file mode 120000 index 0000000000..85190ece0f --- /dev/null +++ b/Lang/DuckDB/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Associative-array-Creation b/Lang/DuckDB/Associative-array-Creation new file mode 120000 index 0000000000..ea2505f34f --- /dev/null +++ b/Lang/DuckDB/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Associative-array-Iteration b/Lang/DuckDB/Associative-array-Iteration new file mode 120000 index 0000000000..c8269906e9 --- /dev/null +++ b/Lang/DuckDB/Associative-array-Iteration @@ -0,0 +1 @@ +../../Task/Associative-array-Iteration/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Associative-array-Merging b/Lang/DuckDB/Associative-array-Merging new file mode 120000 index 0000000000..4e70d9ab01 --- /dev/null +++ b/Lang/DuckDB/Associative-array-Merging @@ -0,0 +1 @@ +../../Task/Associative-array-Merging/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Averages-Arithmetic-mean b/Lang/DuckDB/Averages-Arithmetic-mean new file mode 120000 index 0000000000..7ef12ec4b6 --- /dev/null +++ b/Lang/DuckDB/Averages-Arithmetic-mean @@ -0,0 +1 @@ +../../Task/Averages-Arithmetic-mean/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Averages-Mean-angle b/Lang/DuckDB/Averages-Mean-angle new file mode 120000 index 0000000000..5b1aa18e5e --- /dev/null +++ b/Lang/DuckDB/Averages-Mean-angle @@ -0,0 +1 @@ +../../Task/Averages-Mean-angle/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Averages-Mean-time-of-day b/Lang/DuckDB/Averages-Mean-time-of-day new file mode 120000 index 0000000000..7971faf640 --- /dev/null +++ b/Lang/DuckDB/Averages-Mean-time-of-day @@ -0,0 +1 @@ +../../Task/Averages-Mean-time-of-day/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Averages-Mode b/Lang/DuckDB/Averages-Mode new file mode 120000 index 0000000000..0ba388e74d --- /dev/null +++ b/Lang/DuckDB/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Averages-Pythagorean-means b/Lang/DuckDB/Averages-Pythagorean-means new file mode 120000 index 0000000000..1a5cb3068d --- /dev/null +++ b/Lang/DuckDB/Averages-Pythagorean-means @@ -0,0 +1 @@ +../../Task/Averages-Pythagorean-means/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Babbage-problem b/Lang/DuckDB/Babbage-problem new file mode 120000 index 0000000000..7cee7b9a76 --- /dev/null +++ b/Lang/DuckDB/Babbage-problem @@ -0,0 +1 @@ +../../Task/Babbage-problem/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Benfords-law b/Lang/DuckDB/Benfords-law new file mode 120000 index 0000000000..9302673cc0 --- /dev/null +++ b/Lang/DuckDB/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Bin-given-limits b/Lang/DuckDB/Bin-given-limits new file mode 120000 index 0000000000..ba754d6a93 --- /dev/null +++ b/Lang/DuckDB/Bin-given-limits @@ -0,0 +1 @@ +../../Task/Bin-given-limits/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Binary-digits b/Lang/DuckDB/Binary-digits new file mode 120000 index 0000000000..c4e4b4a580 --- /dev/null +++ b/Lang/DuckDB/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Bitwise-IO b/Lang/DuckDB/Bitwise-IO new file mode 120000 index 0000000000..d00e607776 --- /dev/null +++ b/Lang/DuckDB/Bitwise-IO @@ -0,0 +1 @@ +../../Task/Bitwise-IO/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Bitwise-operations b/Lang/DuckDB/Bitwise-operations new file mode 120000 index 0000000000..a0841908e6 --- /dev/null +++ b/Lang/DuckDB/Bitwise-operations @@ -0,0 +1 @@ +../../Task/Bitwise-operations/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/CSV-data-manipulation b/Lang/DuckDB/CSV-data-manipulation new file mode 120000 index 0000000000..799ed97795 --- /dev/null +++ b/Lang/DuckDB/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Call-a-function b/Lang/DuckDB/Call-a-function new file mode 120000 index 0000000000..bf87fb6ba8 --- /dev/null +++ b/Lang/DuckDB/Call-a-function @@ -0,0 +1 @@ +../../Task/Call-a-function/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Cartesian-product-of-two-or-more-lists b/Lang/DuckDB/Cartesian-product-of-two-or-more-lists new file mode 120000 index 0000000000..f0873100b0 --- /dev/null +++ b/Lang/DuckDB/Cartesian-product-of-two-or-more-lists @@ -0,0 +1 @@ +../../Task/Cartesian-product-of-two-or-more-lists/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Case-sensitivity-of-identifiers b/Lang/DuckDB/Case-sensitivity-of-identifiers new file mode 120000 index 0000000000..2a0900e2e4 --- /dev/null +++ b/Lang/DuckDB/Case-sensitivity-of-identifiers @@ -0,0 +1 @@ +../../Task/Case-sensitivity-of-identifiers/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Catalan-numbers b/Lang/DuckDB/Catalan-numbers new file mode 120000 index 0000000000..5591f12e62 --- /dev/null +++ b/Lang/DuckDB/Catalan-numbers @@ -0,0 +1 @@ +../../Task/Catalan-numbers/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Catalan-numbers-Pascals-triangle b/Lang/DuckDB/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..690dec4614 --- /dev/null +++ b/Lang/DuckDB/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Check-that-file-exists b/Lang/DuckDB/Check-that-file-exists new file mode 120000 index 0000000000..7a35121080 --- /dev/null +++ b/Lang/DuckDB/Check-that-file-exists @@ -0,0 +1 @@ +../../Task/Check-that-file-exists/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Collections b/Lang/DuckDB/Collections new file mode 120000 index 0000000000..4bd2b4f60a --- /dev/null +++ b/Lang/DuckDB/Collections @@ -0,0 +1 @@ +../../Task/Collections/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Combinations b/Lang/DuckDB/Combinations new file mode 120000 index 0000000000..61cb39c1bb --- /dev/null +++ b/Lang/DuckDB/Combinations @@ -0,0 +1 @@ +../../Task/Combinations/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Combinations-with-repetitions b/Lang/DuckDB/Combinations-with-repetitions new file mode 120000 index 0000000000..3781b1dd53 --- /dev/null +++ b/Lang/DuckDB/Combinations-with-repetitions @@ -0,0 +1 @@ +../../Task/Combinations-with-repetitions/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Compare-a-list-of-strings b/Lang/DuckDB/Compare-a-list-of-strings new file mode 120000 index 0000000000..dcf4a9dc8d --- /dev/null +++ b/Lang/DuckDB/Compare-a-list-of-strings @@ -0,0 +1 @@ +../../Task/Compare-a-list-of-strings/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Compare-length-of-two-strings b/Lang/DuckDB/Compare-length-of-two-strings new file mode 120000 index 0000000000..b29bfdb369 --- /dev/null +++ b/Lang/DuckDB/Compare-length-of-two-strings @@ -0,0 +1 @@ +../../Task/Compare-length-of-two-strings/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Compound-data-type b/Lang/DuckDB/Compound-data-type new file mode 120000 index 0000000000..dc469b307b --- /dev/null +++ b/Lang/DuckDB/Compound-data-type @@ -0,0 +1 @@ +../../Task/Compound-data-type/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Conditional-structures b/Lang/DuckDB/Conditional-structures new file mode 120000 index 0000000000..19bf4a5caa --- /dev/null +++ b/Lang/DuckDB/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Convert-seconds-to-compound-duration b/Lang/DuckDB/Convert-seconds-to-compound-duration new file mode 120000 index 0000000000..44055a0c42 --- /dev/null +++ b/Lang/DuckDB/Convert-seconds-to-compound-duration @@ -0,0 +1 @@ +../../Task/Convert-seconds-to-compound-duration/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Copy-a-string b/Lang/DuckDB/Copy-a-string new file mode 120000 index 0000000000..d5f908f98d --- /dev/null +++ b/Lang/DuckDB/Copy-a-string @@ -0,0 +1 @@ +../../Task/Copy-a-string/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Count-occurrences-of-a-substring b/Lang/DuckDB/Count-occurrences-of-a-substring new file mode 120000 index 0000000000..82775de6e5 --- /dev/null +++ b/Lang/DuckDB/Count-occurrences-of-a-substring @@ -0,0 +1 @@ +../../Task/Count-occurrences-of-a-substring/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Create-a-two-dimensional-array-at-runtime b/Lang/DuckDB/Create-a-two-dimensional-array-at-runtime new file mode 120000 index 0000000000..14657f9c21 --- /dev/null +++ b/Lang/DuckDB/Create-a-two-dimensional-array-at-runtime @@ -0,0 +1 @@ +../../Task/Create-a-two-dimensional-array-at-runtime/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Cumulative-standard-deviation b/Lang/DuckDB/Cumulative-standard-deviation new file mode 120000 index 0000000000..f323d6c56e --- /dev/null +++ b/Lang/DuckDB/Cumulative-standard-deviation @@ -0,0 +1 @@ +../../Task/Cumulative-standard-deviation/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Currency b/Lang/DuckDB/Currency new file mode 120000 index 0000000000..092e5fcb13 --- /dev/null +++ b/Lang/DuckDB/Currency @@ -0,0 +1 @@ +../../Task/Currency/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Day-of-the-week b/Lang/DuckDB/Day-of-the-week new file mode 120000 index 0000000000..467c28db17 --- /dev/null +++ b/Lang/DuckDB/Day-of-the-week @@ -0,0 +1 @@ +../../Task/Day-of-the-week/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Define-a-primitive-data-type b/Lang/DuckDB/Define-a-primitive-data-type new file mode 120000 index 0000000000..f086397ed2 --- /dev/null +++ b/Lang/DuckDB/Define-a-primitive-data-type @@ -0,0 +1 @@ +../../Task/Define-a-primitive-data-type/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Detect-division-by-zero b/Lang/DuckDB/Detect-division-by-zero new file mode 120000 index 0000000000..92508ad1dd --- /dev/null +++ b/Lang/DuckDB/Detect-division-by-zero @@ -0,0 +1 @@ +../../Task/Detect-division-by-zero/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Determinant-and-permanent b/Lang/DuckDB/Determinant-and-permanent new file mode 120000 index 0000000000..6bccec7e87 --- /dev/null +++ b/Lang/DuckDB/Determinant-and-permanent @@ -0,0 +1 @@ +../../Task/Determinant-and-permanent/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Determine-if-a-string-has-all-the-same-characters b/Lang/DuckDB/Determine-if-a-string-has-all-the-same-characters new file mode 120000 index 0000000000..3a9bd20a7a --- /dev/null +++ b/Lang/DuckDB/Determine-if-a-string-has-all-the-same-characters @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-has-all-the-same-characters/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Determine-if-a-string-has-all-unique-characters b/Lang/DuckDB/Determine-if-a-string-has-all-unique-characters new file mode 120000 index 0000000000..64885aacf1 --- /dev/null +++ b/Lang/DuckDB/Determine-if-a-string-has-all-unique-characters @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-has-all-unique-characters/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Determine-if-a-string-is-collapsible b/Lang/DuckDB/Determine-if-a-string-is-collapsible new file mode 120000 index 0000000000..0bb2727b9c --- /dev/null +++ b/Lang/DuckDB/Determine-if-a-string-is-collapsible @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-collapsible/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Determine-if-a-string-is-numeric b/Lang/DuckDB/Determine-if-a-string-is-numeric new file mode 120000 index 0000000000..ead16cd478 --- /dev/null +++ b/Lang/DuckDB/Determine-if-a-string-is-numeric @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-numeric/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Determine-if-a-string-is-squeezable b/Lang/DuckDB/Determine-if-a-string-is-squeezable new file mode 120000 index 0000000000..57414557b7 --- /dev/null +++ b/Lang/DuckDB/Determine-if-a-string-is-squeezable @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-squeezable/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Determine-sentence-type b/Lang/DuckDB/Determine-sentence-type new file mode 120000 index 0000000000..50fb0aaf1b --- /dev/null +++ b/Lang/DuckDB/Determine-sentence-type @@ -0,0 +1 @@ +../../Task/Determine-sentence-type/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Digital-root b/Lang/DuckDB/Digital-root new file mode 120000 index 0000000000..736b8ccc4f --- /dev/null +++ b/Lang/DuckDB/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Diversity-prediction-theorem b/Lang/DuckDB/Diversity-prediction-theorem new file mode 120000 index 0000000000..2c04d6784a --- /dev/null +++ b/Lang/DuckDB/Diversity-prediction-theorem @@ -0,0 +1 @@ +../../Task/Diversity-prediction-theorem/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Documentation b/Lang/DuckDB/Documentation new file mode 120000 index 0000000000..f9f6aaf2ce --- /dev/null +++ b/Lang/DuckDB/Documentation @@ -0,0 +1 @@ +../../Task/Documentation/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Dot-product b/Lang/DuckDB/Dot-product new file mode 120000 index 0000000000..b17f0214ea --- /dev/null +++ b/Lang/DuckDB/Dot-product @@ -0,0 +1 @@ +../../Task/Dot-product/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Dynamic-variable-names b/Lang/DuckDB/Dynamic-variable-names new file mode 120000 index 0000000000..c534bbc61d --- /dev/null +++ b/Lang/DuckDB/Dynamic-variable-names @@ -0,0 +1 @@ +../../Task/Dynamic-variable-names/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Element-wise-operations b/Lang/DuckDB/Element-wise-operations new file mode 120000 index 0000000000..7d7754f7f7 --- /dev/null +++ b/Lang/DuckDB/Element-wise-operations @@ -0,0 +1 @@ +../../Task/Element-wise-operations/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Empty-string b/Lang/DuckDB/Empty-string new file mode 120000 index 0000000000..67b471da95 --- /dev/null +++ b/Lang/DuckDB/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Entropy b/Lang/DuckDB/Entropy new file mode 120000 index 0000000000..9c2bc0a9a7 --- /dev/null +++ b/Lang/DuckDB/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Enumerations b/Lang/DuckDB/Enumerations new file mode 120000 index 0000000000..0605dce25b --- /dev/null +++ b/Lang/DuckDB/Enumerations @@ -0,0 +1 @@ +../../Task/Enumerations/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Equilibrium-index b/Lang/DuckDB/Equilibrium-index new file mode 120000 index 0000000000..40fbbe81bb --- /dev/null +++ b/Lang/DuckDB/Equilibrium-index @@ -0,0 +1 @@ +../../Task/Equilibrium-index/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Euler-method b/Lang/DuckDB/Euler-method new file mode 120000 index 0000000000..61aa9557d0 --- /dev/null +++ b/Lang/DuckDB/Euler-method @@ -0,0 +1 @@ +../../Task/Euler-method/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Eulers-constant-0.5772... b/Lang/DuckDB/Eulers-constant-0.5772... new file mode 120000 index 0000000000..c954937ec2 --- /dev/null +++ b/Lang/DuckDB/Eulers-constant-0.5772... @@ -0,0 +1 @@ +../../Task/Eulers-constant-0.5772.../DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Eulers-identity b/Lang/DuckDB/Eulers-identity new file mode 120000 index 0000000000..58919d8390 --- /dev/null +++ b/Lang/DuckDB/Eulers-identity @@ -0,0 +1 @@ +../../Task/Eulers-identity/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Evaluate-binomial-coefficients b/Lang/DuckDB/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..69d838bb98 --- /dev/null +++ b/Lang/DuckDB/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Even-or-odd b/Lang/DuckDB/Even-or-odd new file mode 120000 index 0000000000..e428a57303 --- /dev/null +++ b/Lang/DuckDB/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Exponentiation-order b/Lang/DuckDB/Exponentiation-order new file mode 120000 index 0000000000..56438a22ee --- /dev/null +++ b/Lang/DuckDB/Exponentiation-order @@ -0,0 +1 @@ +../../Task/Exponentiation-order/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Extreme-floating-point-values b/Lang/DuckDB/Extreme-floating-point-values new file mode 120000 index 0000000000..617a7e99de --- /dev/null +++ b/Lang/DuckDB/Extreme-floating-point-values @@ -0,0 +1 @@ +../../Task/Extreme-floating-point-values/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Factorial b/Lang/DuckDB/Factorial new file mode 120000 index 0000000000..24543aba0b --- /dev/null +++ b/Lang/DuckDB/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Factors-of-an-integer b/Lang/DuckDB/Factors-of-an-integer new file mode 120000 index 0000000000..70e5ed8d56 --- /dev/null +++ b/Lang/DuckDB/Factors-of-an-integer @@ -0,0 +1 @@ +../../Task/Factors-of-an-integer/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Fairshare-between-two-and-more b/Lang/DuckDB/Fairshare-between-two-and-more new file mode 120000 index 0000000000..0c62807925 --- /dev/null +++ b/Lang/DuckDB/Fairshare-between-two-and-more @@ -0,0 +1 @@ +../../Task/Fairshare-between-two-and-more/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Feigenbaum-constant-calculation b/Lang/DuckDB/Feigenbaum-constant-calculation new file mode 120000 index 0000000000..6f57f3044b --- /dev/null +++ b/Lang/DuckDB/Feigenbaum-constant-calculation @@ -0,0 +1 @@ +../../Task/Feigenbaum-constant-calculation/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Fibonacci-sequence b/Lang/DuckDB/Fibonacci-sequence new file mode 120000 index 0000000000..0411dbf9f3 --- /dev/null +++ b/Lang/DuckDB/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/File-input-output b/Lang/DuckDB/File-input-output new file mode 120000 index 0000000000..0bb640b9cd --- /dev/null +++ b/Lang/DuckDB/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Filter b/Lang/DuckDB/Filter new file mode 120000 index 0000000000..bec860336f --- /dev/null +++ b/Lang/DuckDB/Filter @@ -0,0 +1 @@ +../../Task/Filter/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Find-limit-of-recursion b/Lang/DuckDB/Find-limit-of-recursion new file mode 120000 index 0000000000..e7eff55309 --- /dev/null +++ b/Lang/DuckDB/Find-limit-of-recursion @@ -0,0 +1 @@ +../../Task/Find-limit-of-recursion/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Find-the-last-Sunday-of-each-month b/Lang/DuckDB/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..39172062a9 --- /dev/null +++ b/Lang/DuckDB/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Five-weekends b/Lang/DuckDB/Five-weekends new file mode 120000 index 0000000000..4d8ed3ebe3 --- /dev/null +++ b/Lang/DuckDB/Five-weekends @@ -0,0 +1 @@ +../../Task/Five-weekends/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Fixed-length-records b/Lang/DuckDB/Fixed-length-records new file mode 120000 index 0000000000..0b8d72de87 --- /dev/null +++ b/Lang/DuckDB/Fixed-length-records @@ -0,0 +1 @@ +../../Task/Fixed-length-records/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Flatten-a-list b/Lang/DuckDB/Flatten-a-list new file mode 120000 index 0000000000..5bd1c5b0d8 --- /dev/null +++ b/Lang/DuckDB/Flatten-a-list @@ -0,0 +1 @@ +../../Task/Flatten-a-list/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Formatted-numeric-output b/Lang/DuckDB/Formatted-numeric-output new file mode 120000 index 0000000000..789e647161 --- /dev/null +++ b/Lang/DuckDB/Formatted-numeric-output @@ -0,0 +1 @@ +../../Task/Formatted-numeric-output/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Forward-difference b/Lang/DuckDB/Forward-difference new file mode 120000 index 0000000000..6a0d935f36 --- /dev/null +++ b/Lang/DuckDB/Forward-difference @@ -0,0 +1 @@ +../../Task/Forward-difference/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Function-definition b/Lang/DuckDB/Function-definition new file mode 120000 index 0000000000..b39d093883 --- /dev/null +++ b/Lang/DuckDB/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Gamma-function b/Lang/DuckDB/Gamma-function new file mode 120000 index 0000000000..6fcec68436 --- /dev/null +++ b/Lang/DuckDB/Gamma-function @@ -0,0 +1 @@ +../../Task/Gamma-function/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Gapful-numbers b/Lang/DuckDB/Gapful-numbers new file mode 120000 index 0000000000..875c3e4310 --- /dev/null +++ b/Lang/DuckDB/Gapful-numbers @@ -0,0 +1 @@ +../../Task/Gapful-numbers/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Generate-lower-case-ASCII-alphabet b/Lang/DuckDB/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..51094f97da --- /dev/null +++ b/Lang/DuckDB/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Generic-swap b/Lang/DuckDB/Generic-swap new file mode 120000 index 0000000000..b384241f1f --- /dev/null +++ b/Lang/DuckDB/Generic-swap @@ -0,0 +1 @@ +../../Task/Generic-swap/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Golden-ratio-Convergence b/Lang/DuckDB/Golden-ratio-Convergence new file mode 120000 index 0000000000..0ca8f2458f --- /dev/null +++ b/Lang/DuckDB/Golden-ratio-Convergence @@ -0,0 +1 @@ +../../Task/Golden-ratio-Convergence/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Gotchas b/Lang/DuckDB/Gotchas new file mode 120000 index 0000000000..16cceb3ff0 --- /dev/null +++ b/Lang/DuckDB/Gotchas @@ -0,0 +1 @@ +../../Task/Gotchas/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Greatest-common-divisor b/Lang/DuckDB/Greatest-common-divisor new file mode 120000 index 0000000000..6fb062c771 --- /dev/null +++ b/Lang/DuckDB/Greatest-common-divisor @@ -0,0 +1 @@ +../../Task/Greatest-common-divisor/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Greatest-element-of-a-list b/Lang/DuckDB/Greatest-element-of-a-list new file mode 120000 index 0000000000..5a2c7a66c9 --- /dev/null +++ b/Lang/DuckDB/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Greatest-subsequential-sum b/Lang/DuckDB/Greatest-subsequential-sum new file mode 120000 index 0000000000..dd3661e978 --- /dev/null +++ b/Lang/DuckDB/Greatest-subsequential-sum @@ -0,0 +1 @@ +../../Task/Greatest-subsequential-sum/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/HTTP b/Lang/DuckDB/HTTP new file mode 120000 index 0000000000..f77a3116ff --- /dev/null +++ b/Lang/DuckDB/HTTP @@ -0,0 +1 @@ +../../Task/HTTP/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/HTTPS b/Lang/DuckDB/HTTPS new file mode 120000 index 0000000000..694faecb0f --- /dev/null +++ b/Lang/DuckDB/HTTPS @@ -0,0 +1 @@ +../../Task/HTTPS/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/HTTPS-Authenticated b/Lang/DuckDB/HTTPS-Authenticated new file mode 120000 index 0000000000..c1b123b3b8 --- /dev/null +++ b/Lang/DuckDB/HTTPS-Authenticated @@ -0,0 +1 @@ +../../Task/HTTPS-Authenticated/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Hailstone-sequence b/Lang/DuckDB/Hailstone-sequence new file mode 120000 index 0000000000..8cb9cd3c4d --- /dev/null +++ b/Lang/DuckDB/Hailstone-sequence @@ -0,0 +1 @@ +../../Task/Hailstone-sequence/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Harmonic-series b/Lang/DuckDB/Harmonic-series new file mode 120000 index 0000000000..d5b23dfe32 --- /dev/null +++ b/Lang/DuckDB/Harmonic-series @@ -0,0 +1 @@ +../../Task/Harmonic-series/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Hash-from-two-arrays b/Lang/DuckDB/Hash-from-two-arrays new file mode 120000 index 0000000000..4fd3efc241 --- /dev/null +++ b/Lang/DuckDB/Hash-from-two-arrays @@ -0,0 +1 @@ +../../Task/Hash-from-two-arrays/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Hash-join b/Lang/DuckDB/Hash-join new file mode 120000 index 0000000000..d89e18cc75 --- /dev/null +++ b/Lang/DuckDB/Hash-join @@ -0,0 +1 @@ +../../Task/Hash-join/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Haversine-formula b/Lang/DuckDB/Haversine-formula new file mode 120000 index 0000000000..102a047e33 --- /dev/null +++ b/Lang/DuckDB/Haversine-formula @@ -0,0 +1 @@ +../../Task/Haversine-formula/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Hello-world-Text b/Lang/DuckDB/Hello-world-Text new file mode 120000 index 0000000000..1af484f405 --- /dev/null +++ b/Lang/DuckDB/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Here-document b/Lang/DuckDB/Here-document new file mode 120000 index 0000000000..f233028f5b --- /dev/null +++ b/Lang/DuckDB/Here-document @@ -0,0 +1 @@ +../../Task/Here-document/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/ISBN13-check-digit b/Lang/DuckDB/ISBN13-check-digit new file mode 120000 index 0000000000..ad247e79cf --- /dev/null +++ b/Lang/DuckDB/ISBN13-check-digit @@ -0,0 +1 @@ +../../Task/ISBN13-check-digit/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Identity-matrix b/Lang/DuckDB/Identity-matrix new file mode 120000 index 0000000000..d8402f7ae8 --- /dev/null +++ b/Lang/DuckDB/Identity-matrix @@ -0,0 +1 @@ +../../Task/Identity-matrix/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols b/Lang/DuckDB/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols new file mode 120000 index 0000000000..90e880a4b1 --- /dev/null +++ b/Lang/DuckDB/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols @@ -0,0 +1 @@ +../../Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Idiomatically-determine-all-the-lowercase-and-uppercase-letters b/Lang/DuckDB/Idiomatically-determine-all-the-lowercase-and-uppercase-letters new file mode 120000 index 0000000000..3722271469 --- /dev/null +++ b/Lang/DuckDB/Idiomatically-determine-all-the-lowercase-and-uppercase-letters @@ -0,0 +1 @@ +../../Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Increment-a-numerical-string b/Lang/DuckDB/Increment-a-numerical-string new file mode 120000 index 0000000000..a9f84c0e8c --- /dev/null +++ b/Lang/DuckDB/Increment-a-numerical-string @@ -0,0 +1 @@ +../../Task/Increment-a-numerical-string/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Infinity b/Lang/DuckDB/Infinity new file mode 120000 index 0000000000..ed12f74690 --- /dev/null +++ b/Lang/DuckDB/Infinity @@ -0,0 +1 @@ +../../Task/Infinity/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Integer-comparison b/Lang/DuckDB/Integer-comparison new file mode 120000 index 0000000000..c6cacfcd06 --- /dev/null +++ b/Lang/DuckDB/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Introspection b/Lang/DuckDB/Introspection new file mode 120000 index 0000000000..c3bb6d896d --- /dev/null +++ b/Lang/DuckDB/Introspection @@ -0,0 +1 @@ +../../Task/Introspection/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Inverted-index b/Lang/DuckDB/Inverted-index new file mode 120000 index 0000000000..81053e0c15 --- /dev/null +++ b/Lang/DuckDB/Inverted-index @@ -0,0 +1 @@ +../../Task/Inverted-index/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Inverted-syntax b/Lang/DuckDB/Inverted-syntax new file mode 120000 index 0000000000..cadc81e3b6 --- /dev/null +++ b/Lang/DuckDB/Inverted-syntax @@ -0,0 +1 @@ +../../Task/Inverted-syntax/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/JSON b/Lang/DuckDB/JSON new file mode 120000 index 0000000000..e4757a4b09 --- /dev/null +++ b/Lang/DuckDB/JSON @@ -0,0 +1 @@ +../../Task/JSON/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Jaro-similarity b/Lang/DuckDB/Jaro-similarity new file mode 120000 index 0000000000..39c64b8488 --- /dev/null +++ b/Lang/DuckDB/Jaro-similarity @@ -0,0 +1 @@ +../../Task/Jaro-similarity/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Knuth-shuffle b/Lang/DuckDB/Knuth-shuffle new file mode 120000 index 0000000000..7d43c57cbe --- /dev/null +++ b/Lang/DuckDB/Knuth-shuffle @@ -0,0 +1 @@ +../../Task/Knuth-shuffle/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Largest-int-from-concatenated-ints b/Lang/DuckDB/Largest-int-from-concatenated-ints new file mode 120000 index 0000000000..8e73a50292 --- /dev/null +++ b/Lang/DuckDB/Largest-int-from-concatenated-ints @@ -0,0 +1 @@ +../../Task/Largest-int-from-concatenated-ints/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Last-Friday-of-each-month b/Lang/DuckDB/Last-Friday-of-each-month new file mode 120000 index 0000000000..1236ebdc14 --- /dev/null +++ b/Lang/DuckDB/Last-Friday-of-each-month @@ -0,0 +1 @@ +../../Task/Last-Friday-of-each-month/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Leap-year b/Lang/DuckDB/Leap-year new file mode 120000 index 0000000000..5816394f02 --- /dev/null +++ b/Lang/DuckDB/Leap-year @@ -0,0 +1 @@ +../../Task/Leap-year/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Left-factorials b/Lang/DuckDB/Left-factorials new file mode 120000 index 0000000000..6877bf1f73 --- /dev/null +++ b/Lang/DuckDB/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Leonardo-numbers b/Lang/DuckDB/Leonardo-numbers new file mode 120000 index 0000000000..206ddcfce9 --- /dev/null +++ b/Lang/DuckDB/Leonardo-numbers @@ -0,0 +1 @@ +../../Task/Leonardo-numbers/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Letter-frequency b/Lang/DuckDB/Letter-frequency new file mode 120000 index 0000000000..29228c3e0b --- /dev/null +++ b/Lang/DuckDB/Letter-frequency @@ -0,0 +1 @@ +../../Task/Letter-frequency/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Levenshtein-distance b/Lang/DuckDB/Levenshtein-distance new file mode 120000 index 0000000000..d0954b60f2 --- /dev/null +++ b/Lang/DuckDB/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/List-comprehensions b/Lang/DuckDB/List-comprehensions new file mode 120000 index 0000000000..72558c43a1 --- /dev/null +++ b/Lang/DuckDB/List-comprehensions @@ -0,0 +1 @@ +../../Task/List-comprehensions/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Literals-Integer b/Lang/DuckDB/Literals-Integer new file mode 120000 index 0000000000..39629959b4 --- /dev/null +++ b/Lang/DuckDB/Literals-Integer @@ -0,0 +1 @@ +../../Task/Literals-Integer/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Logical-operations b/Lang/DuckDB/Logical-operations new file mode 120000 index 0000000000..14d59b0f70 --- /dev/null +++ b/Lang/DuckDB/Logical-operations @@ -0,0 +1 @@ +../../Task/Logical-operations/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Longest-increasing-subsequence b/Lang/DuckDB/Longest-increasing-subsequence new file mode 120000 index 0000000000..35a8443499 --- /dev/null +++ b/Lang/DuckDB/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Loops-Break b/Lang/DuckDB/Loops-Break new file mode 120000 index 0000000000..40b7904e3f --- /dev/null +++ b/Lang/DuckDB/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Loops-Do-while b/Lang/DuckDB/Loops-Do-while new file mode 120000 index 0000000000..257f84d6ba --- /dev/null +++ b/Lang/DuckDB/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Loops-Downward-for b/Lang/DuckDB/Loops-Downward-for new file mode 120000 index 0000000000..5516907335 --- /dev/null +++ b/Lang/DuckDB/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Loops-For b/Lang/DuckDB/Loops-For new file mode 120000 index 0000000000..56dde9a604 --- /dev/null +++ b/Lang/DuckDB/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Loops-For-with-a-specified-step b/Lang/DuckDB/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..f7e2b536d7 --- /dev/null +++ b/Lang/DuckDB/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Loops-Increment-loop-index-within-loop-body b/Lang/DuckDB/Loops-Increment-loop-index-within-loop-body new file mode 120000 index 0000000000..d530992462 --- /dev/null +++ b/Lang/DuckDB/Loops-Increment-loop-index-within-loop-body @@ -0,0 +1 @@ +../../Task/Loops-Increment-loop-index-within-loop-body/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Loops-N-plus-one-half b/Lang/DuckDB/Loops-N-plus-one-half new file mode 120000 index 0000000000..f9812bda7e --- /dev/null +++ b/Lang/DuckDB/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Loops-Nested b/Lang/DuckDB/Loops-Nested new file mode 120000 index 0000000000..8b4afa46b5 --- /dev/null +++ b/Lang/DuckDB/Loops-Nested @@ -0,0 +1 @@ +../../Task/Loops-Nested/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Loops-While b/Lang/DuckDB/Loops-While new file mode 120000 index 0000000000..60343480f3 --- /dev/null +++ b/Lang/DuckDB/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Loops-With-multiple-ranges b/Lang/DuckDB/Loops-With-multiple-ranges new file mode 120000 index 0000000000..540b734a24 --- /dev/null +++ b/Lang/DuckDB/Loops-With-multiple-ranges @@ -0,0 +1 @@ +../../Task/Loops-With-multiple-ranges/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Luhn-test-of-credit-card-numbers b/Lang/DuckDB/Luhn-test-of-credit-card-numbers new file mode 120000 index 0000000000..397557411e --- /dev/null +++ b/Lang/DuckDB/Luhn-test-of-credit-card-numbers @@ -0,0 +1 @@ +../../Task/Luhn-test-of-credit-card-numbers/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/MD5 b/Lang/DuckDB/MD5 new file mode 120000 index 0000000000..ab453e87da --- /dev/null +++ b/Lang/DuckDB/MD5 @@ -0,0 +1 @@ +../../Task/MD5/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Map-range b/Lang/DuckDB/Map-range new file mode 120000 index 0000000000..6cd697a04b --- /dev/null +++ b/Lang/DuckDB/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Matrix-multiplication b/Lang/DuckDB/Matrix-multiplication new file mode 120000 index 0000000000..2110896869 --- /dev/null +++ b/Lang/DuckDB/Matrix-multiplication @@ -0,0 +1 @@ +../../Task/Matrix-multiplication/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Matrix-transposition b/Lang/DuckDB/Matrix-transposition new file mode 120000 index 0000000000..7e416217b2 --- /dev/null +++ b/Lang/DuckDB/Matrix-transposition @@ -0,0 +1 @@ +../../Task/Matrix-transposition/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Merge-and-aggregate-datasets b/Lang/DuckDB/Merge-and-aggregate-datasets new file mode 120000 index 0000000000..e9d467735b --- /dev/null +++ b/Lang/DuckDB/Merge-and-aggregate-datasets @@ -0,0 +1 @@ +../../Task/Merge-and-aggregate-datasets/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Metallic-ratios b/Lang/DuckDB/Metallic-ratios new file mode 120000 index 0000000000..56fa981641 --- /dev/null +++ b/Lang/DuckDB/Metallic-ratios @@ -0,0 +1 @@ +../../Task/Metallic-ratios/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Middle-three-digits b/Lang/DuckDB/Middle-three-digits new file mode 120000 index 0000000000..9c32c60a1c --- /dev/null +++ b/Lang/DuckDB/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Monte-Carlo-methods b/Lang/DuckDB/Monte-Carlo-methods new file mode 120000 index 0000000000..f27be4f0e8 --- /dev/null +++ b/Lang/DuckDB/Monte-Carlo-methods @@ -0,0 +1 @@ +../../Task/Monte-Carlo-methods/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Nested-function b/Lang/DuckDB/Nested-function new file mode 120000 index 0000000000..6ccb0c0029 --- /dev/null +++ b/Lang/DuckDB/Nested-function @@ -0,0 +1 @@ +../../Task/Nested-function/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Nth b/Lang/DuckDB/Nth new file mode 120000 index 0000000000..6d1fd0295b --- /dev/null +++ b/Lang/DuckDB/Nth @@ -0,0 +1 @@ +../../Task/Nth/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Nth-root b/Lang/DuckDB/Nth-root new file mode 120000 index 0000000000..bdfee4887c --- /dev/null +++ b/Lang/DuckDB/Nth-root @@ -0,0 +1 @@ +../../Task/Nth-root/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/One-of-n-lines-in-a-file b/Lang/DuckDB/One-of-n-lines-in-a-file new file mode 120000 index 0000000000..84adf8bb46 --- /dev/null +++ b/Lang/DuckDB/One-of-n-lines-in-a-file @@ -0,0 +1 @@ +../../Task/One-of-n-lines-in-a-file/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Order-two-numerical-lists b/Lang/DuckDB/Order-two-numerical-lists new file mode 120000 index 0000000000..fcd259b6c0 --- /dev/null +++ b/Lang/DuckDB/Order-two-numerical-lists @@ -0,0 +1 @@ +../../Task/Order-two-numerical-lists/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Ordered-words b/Lang/DuckDB/Ordered-words new file mode 120000 index 0000000000..57d12d9c27 --- /dev/null +++ b/Lang/DuckDB/Ordered-words @@ -0,0 +1 @@ +../../Task/Ordered-words/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Palindrome-detection b/Lang/DuckDB/Palindrome-detection new file mode 120000 index 0000000000..a318cb02ae --- /dev/null +++ b/Lang/DuckDB/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Parameterized-SQL-statement b/Lang/DuckDB/Parameterized-SQL-statement new file mode 120000 index 0000000000..dded36b01b --- /dev/null +++ b/Lang/DuckDB/Parameterized-SQL-statement @@ -0,0 +1 @@ +../../Task/Parameterized-SQL-statement/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Pascals-triangle b/Lang/DuckDB/Pascals-triangle new file mode 120000 index 0000000000..e38a99fc2d --- /dev/null +++ b/Lang/DuckDB/Pascals-triangle @@ -0,0 +1 @@ +../../Task/Pascals-triangle/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Permutations b/Lang/DuckDB/Permutations new file mode 120000 index 0000000000..fa1198c6a6 --- /dev/null +++ b/Lang/DuckDB/Permutations @@ -0,0 +1 @@ +../../Task/Permutations/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Permutations-Derangements b/Lang/DuckDB/Permutations-Derangements new file mode 120000 index 0000000000..b4140ee27e --- /dev/null +++ b/Lang/DuckDB/Permutations-Derangements @@ -0,0 +1 @@ +../../Task/Permutations-Derangements/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Pick-random-element b/Lang/DuckDB/Pick-random-element new file mode 120000 index 0000000000..4eec54c36e --- /dev/null +++ b/Lang/DuckDB/Pick-random-element @@ -0,0 +1 @@ +../../Task/Pick-random-element/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Primality-by-trial-division b/Lang/DuckDB/Primality-by-trial-division new file mode 120000 index 0000000000..8e9e10eb1a --- /dev/null +++ b/Lang/DuckDB/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Prime-decomposition b/Lang/DuckDB/Prime-decomposition new file mode 120000 index 0000000000..dbb3b57727 --- /dev/null +++ b/Lang/DuckDB/Prime-decomposition @@ -0,0 +1 @@ +../../Task/Prime-decomposition/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Probabilistic-choice b/Lang/DuckDB/Probabilistic-choice new file mode 120000 index 0000000000..caa9cf57ce --- /dev/null +++ b/Lang/DuckDB/Probabilistic-choice @@ -0,0 +1 @@ +../../Task/Probabilistic-choice/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Proper-divisors b/Lang/DuckDB/Proper-divisors new file mode 120000 index 0000000000..a8b8cf32ca --- /dev/null +++ b/Lang/DuckDB/Proper-divisors @@ -0,0 +1 @@ +../../Task/Proper-divisors/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Pseudo-random-numbers-Middle-square-method b/Lang/DuckDB/Pseudo-random-numbers-Middle-square-method new file mode 120000 index 0000000000..3424580b60 --- /dev/null +++ b/Lang/DuckDB/Pseudo-random-numbers-Middle-square-method @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-Middle-square-method/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Random-numbers b/Lang/DuckDB/Random-numbers new file mode 120000 index 0000000000..4e7ae21251 --- /dev/null +++ b/Lang/DuckDB/Random-numbers @@ -0,0 +1 @@ +../../Task/Random-numbers/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Range-expansion b/Lang/DuckDB/Range-expansion new file mode 120000 index 0000000000..73f7852f3e --- /dev/null +++ b/Lang/DuckDB/Range-expansion @@ -0,0 +1 @@ +../../Task/Range-expansion/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Range-extraction b/Lang/DuckDB/Range-extraction new file mode 120000 index 0000000000..70b9fee7f2 --- /dev/null +++ b/Lang/DuckDB/Range-extraction @@ -0,0 +1 @@ +../../Task/Range-extraction/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Read-a-file-line-by-line b/Lang/DuckDB/Read-a-file-line-by-line new file mode 120000 index 0000000000..5698cabe3f --- /dev/null +++ b/Lang/DuckDB/Read-a-file-line-by-line @@ -0,0 +1 @@ +../../Task/Read-a-file-line-by-line/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Reflection-List-methods b/Lang/DuckDB/Reflection-List-methods new file mode 120000 index 0000000000..e87f71ad29 --- /dev/null +++ b/Lang/DuckDB/Reflection-List-methods @@ -0,0 +1 @@ +../../Task/Reflection-List-methods/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Reflection-List-properties b/Lang/DuckDB/Reflection-List-properties new file mode 120000 index 0000000000..61160f5035 --- /dev/null +++ b/Lang/DuckDB/Reflection-List-properties @@ -0,0 +1 @@ +../../Task/Reflection-List-properties/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Remove-duplicate-elements b/Lang/DuckDB/Remove-duplicate-elements new file mode 120000 index 0000000000..e38927d88b --- /dev/null +++ b/Lang/DuckDB/Remove-duplicate-elements @@ -0,0 +1 @@ +../../Task/Remove-duplicate-elements/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Rep-string b/Lang/DuckDB/Rep-string new file mode 120000 index 0000000000..ce2543465d --- /dev/null +++ b/Lang/DuckDB/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Repeat-a-string b/Lang/DuckDB/Repeat-a-string new file mode 120000 index 0000000000..126fb8a5a7 --- /dev/null +++ b/Lang/DuckDB/Repeat-a-string @@ -0,0 +1 @@ +../../Task/Repeat-a-string/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Return-multiple-values b/Lang/DuckDB/Return-multiple-values new file mode 120000 index 0000000000..44885d997f --- /dev/null +++ b/Lang/DuckDB/Return-multiple-values @@ -0,0 +1 @@ +../../Task/Return-multiple-values/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Reverse-a-string b/Lang/DuckDB/Reverse-a-string new file mode 120000 index 0000000000..9c2fcefbbf --- /dev/null +++ b/Lang/DuckDB/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Roots-of-unity b/Lang/DuckDB/Roots-of-unity new file mode 120000 index 0000000000..fbae972a1d --- /dev/null +++ b/Lang/DuckDB/Roots-of-unity @@ -0,0 +1 @@ +../../Task/Roots-of-unity/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Run-length-encoding b/Lang/DuckDB/Run-length-encoding new file mode 120000 index 0000000000..798b72b50c --- /dev/null +++ b/Lang/DuckDB/Run-length-encoding @@ -0,0 +1 @@ +../../Task/Run-length-encoding/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Search-a-list-of-records b/Lang/DuckDB/Search-a-list-of-records new file mode 120000 index 0000000000..8875d845bf --- /dev/null +++ b/Lang/DuckDB/Search-a-list-of-records @@ -0,0 +1 @@ +../../Task/Search-a-list-of-records/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Set b/Lang/DuckDB/Set new file mode 120000 index 0000000000..7e25aac634 --- /dev/null +++ b/Lang/DuckDB/Set @@ -0,0 +1 @@ +../../Task/Set/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Set-consolidation b/Lang/DuckDB/Set-consolidation new file mode 120000 index 0000000000..46e9513ebb --- /dev/null +++ b/Lang/DuckDB/Set-consolidation @@ -0,0 +1 @@ +../../Task/Set-consolidation/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Show-the-epoch b/Lang/DuckDB/Show-the-epoch new file mode 120000 index 0000000000..6cd68764f9 --- /dev/null +++ b/Lang/DuckDB/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Sieve-of-Eratosthenes b/Lang/DuckDB/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..ee6aa1fbd3 --- /dev/null +++ b/Lang/DuckDB/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Sort-an-array-of-composite-structures b/Lang/DuckDB/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..35612aed66 --- /dev/null +++ b/Lang/DuckDB/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Sort-numbers-lexicographically b/Lang/DuckDB/Sort-numbers-lexicographically new file mode 120000 index 0000000000..390860d685 --- /dev/null +++ b/Lang/DuckDB/Sort-numbers-lexicographically @@ -0,0 +1 @@ +../../Task/Sort-numbers-lexicographically/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Statistics-Basic b/Lang/DuckDB/Statistics-Basic new file mode 120000 index 0000000000..c3caa99be7 --- /dev/null +++ b/Lang/DuckDB/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/String-append b/Lang/DuckDB/String-append new file mode 120000 index 0000000000..cc8ce5011e --- /dev/null +++ b/Lang/DuckDB/String-append @@ -0,0 +1 @@ +../../Task/String-append/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/String-case b/Lang/DuckDB/String-case new file mode 120000 index 0000000000..ab3478758f --- /dev/null +++ b/Lang/DuckDB/String-case @@ -0,0 +1 @@ +../../Task/String-case/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/String-comparison b/Lang/DuckDB/String-comparison new file mode 120000 index 0000000000..b7a7339e14 --- /dev/null +++ b/Lang/DuckDB/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/String-interpolation-included- b/Lang/DuckDB/String-interpolation-included- new file mode 120000 index 0000000000..807f8abec4 --- /dev/null +++ b/Lang/DuckDB/String-interpolation-included- @@ -0,0 +1 @@ +../../Task/String-interpolation-included-/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/String-length b/Lang/DuckDB/String-length new file mode 120000 index 0000000000..f49078b058 --- /dev/null +++ b/Lang/DuckDB/String-length @@ -0,0 +1 @@ +../../Task/String-length/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/String-matching b/Lang/DuckDB/String-matching new file mode 120000 index 0000000000..e3f7fa5300 --- /dev/null +++ b/Lang/DuckDB/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/String-prepend b/Lang/DuckDB/String-prepend new file mode 120000 index 0000000000..ea6f95610c --- /dev/null +++ b/Lang/DuckDB/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Strip-a-set-of-characters-from-a-string b/Lang/DuckDB/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..77ce9f900d --- /dev/null +++ b/Lang/DuckDB/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Strip-comments-from-a-string b/Lang/DuckDB/Strip-comments-from-a-string new file mode 120000 index 0000000000..f58b2c006d --- /dev/null +++ b/Lang/DuckDB/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Strip-control-codes-and-extended-characters-from-a-string b/Lang/DuckDB/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..e3de3aa487 --- /dev/null +++ b/Lang/DuckDB/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Strip-whitespace-from-a-string-Top-and-tail b/Lang/DuckDB/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..93405e661f --- /dev/null +++ b/Lang/DuckDB/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Substring b/Lang/DuckDB/Substring new file mode 120000 index 0000000000..fe9daf5b9c --- /dev/null +++ b/Lang/DuckDB/Substring @@ -0,0 +1 @@ +../../Task/Substring/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Sudoku b/Lang/DuckDB/Sudoku new file mode 120000 index 0000000000..efc19532bb --- /dev/null +++ b/Lang/DuckDB/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Sum-and-product-of-an-array b/Lang/DuckDB/Sum-and-product-of-an-array new file mode 120000 index 0000000000..9db07cfe55 --- /dev/null +++ b/Lang/DuckDB/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Sum-digits-of-an-integer b/Lang/DuckDB/Sum-digits-of-an-integer new file mode 120000 index 0000000000..2b4e9e5805 --- /dev/null +++ b/Lang/DuckDB/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Sum-multiples-of-3-and-5 b/Lang/DuckDB/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..06a19cefb7 --- /dev/null +++ b/Lang/DuckDB/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Sum-of-a-series b/Lang/DuckDB/Sum-of-a-series new file mode 120000 index 0000000000..db0f6f79c5 --- /dev/null +++ b/Lang/DuckDB/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Sum-of-squares b/Lang/DuckDB/Sum-of-squares new file mode 120000 index 0000000000..fe3d9a8a52 --- /dev/null +++ b/Lang/DuckDB/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Symmetric-difference b/Lang/DuckDB/Symmetric-difference new file mode 120000 index 0000000000..f254423d5f --- /dev/null +++ b/Lang/DuckDB/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Table-creation-Postal-addresses b/Lang/DuckDB/Table-creation-Postal-addresses new file mode 120000 index 0000000000..174f03f886 --- /dev/null +++ b/Lang/DuckDB/Table-creation-Postal-addresses @@ -0,0 +1 @@ +../../Task/Table-creation-Postal-addresses/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Test-integerness b/Lang/DuckDB/Test-integerness new file mode 120000 index 0000000000..0e9573c924 --- /dev/null +++ b/Lang/DuckDB/Test-integerness @@ -0,0 +1 @@ +../../Task/Test-integerness/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Text-processing-2 b/Lang/DuckDB/Text-processing-2 new file mode 120000 index 0000000000..b3c883d2ec --- /dev/null +++ b/Lang/DuckDB/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Thue-Morse b/Lang/DuckDB/Thue-Morse new file mode 120000 index 0000000000..e14a41e488 --- /dev/null +++ b/Lang/DuckDB/Thue-Morse @@ -0,0 +1 @@ +../../Task/Thue-Morse/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Time-a-function b/Lang/DuckDB/Time-a-function new file mode 120000 index 0000000000..d82a288f55 --- /dev/null +++ b/Lang/DuckDB/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Tokenize-a-string b/Lang/DuckDB/Tokenize-a-string new file mode 120000 index 0000000000..ee6d07a4b5 --- /dev/null +++ b/Lang/DuckDB/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Top-rank-per-group b/Lang/DuckDB/Top-rank-per-group new file mode 120000 index 0000000000..ada50a852c --- /dev/null +++ b/Lang/DuckDB/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Trigonometric-functions b/Lang/DuckDB/Trigonometric-functions new file mode 120000 index 0000000000..58530b66ee --- /dev/null +++ b/Lang/DuckDB/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/URL-decoding b/Lang/DuckDB/URL-decoding new file mode 120000 index 0000000000..c717460642 --- /dev/null +++ b/Lang/DuckDB/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/UTF-8-encode-and-decode b/Lang/DuckDB/UTF-8-encode-and-decode new file mode 120000 index 0000000000..792323a78c --- /dev/null +++ b/Lang/DuckDB/UTF-8-encode-and-decode @@ -0,0 +1 @@ +../../Task/UTF-8-encode-and-decode/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Unix-ls b/Lang/DuckDB/Unix-ls new file mode 120000 index 0000000000..85287a21f6 --- /dev/null +++ b/Lang/DuckDB/Unix-ls @@ -0,0 +1 @@ +../../Task/Unix-ls/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Variable-size-Get b/Lang/DuckDB/Variable-size-Get new file mode 120000 index 0000000000..3cff7c631a --- /dev/null +++ b/Lang/DuckDB/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Variable-size-Set b/Lang/DuckDB/Variable-size-Set new file mode 120000 index 0000000000..ee4a003cfa --- /dev/null +++ b/Lang/DuckDB/Variable-size-Set @@ -0,0 +1 @@ +../../Task/Variable-size-Set/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Vector-products b/Lang/DuckDB/Vector-products new file mode 120000 index 0000000000..3347aa5bba --- /dev/null +++ b/Lang/DuckDB/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Zero-to-the-zero-power b/Lang/DuckDB/Zero-to-the-zero-power new file mode 120000 index 0000000000..7c7bac0f0b --- /dev/null +++ b/Lang/DuckDB/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Zig-zag-matrix b/Lang/DuckDB/Zig-zag-matrix new file mode 120000 index 0000000000..dee409f57f --- /dev/null +++ b/Lang/DuckDB/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/DuckDB \ No newline at end of file diff --git a/Lang/E/Miller-Rabin-primality-test b/Lang/E/Miller-Rabin-primality-test deleted file mode 120000 index f586feb18b..0000000000 --- a/Lang/E/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/E \ No newline at end of file diff --git a/Lang/E/Quaternion-type b/Lang/E/Quaternion-type deleted file mode 120000 index ecc55ca8a4..0000000000 --- a/Lang/E/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/E \ No newline at end of file diff --git a/Lang/EDSAC-order-code/Haversine-formula b/Lang/EDSAC-order-code/Haversine-formula new file mode 120000 index 0000000000..0cab079f84 --- /dev/null +++ b/Lang/EDSAC-order-code/Haversine-formula @@ -0,0 +1 @@ +../../Task/Haversine-formula/EDSAC-order-code \ No newline at end of file diff --git a/Lang/EDSAC-order-code/Numerical-integration-Gauss-Legendre-Quadrature b/Lang/EDSAC-order-code/Numerical-integration-Gauss-Legendre-Quadrature new file mode 120000 index 0000000000..f518a6e1fc --- /dev/null +++ b/Lang/EDSAC-order-code/Numerical-integration-Gauss-Legendre-Quadrature @@ -0,0 +1 @@ +../../Task/Numerical-integration-Gauss-Legendre-Quadrature/EDSAC-order-code \ No newline at end of file diff --git a/Lang/EDSAC-order-code/Shoelace-formula-for-polygonal-area b/Lang/EDSAC-order-code/Shoelace-formula-for-polygonal-area new file mode 120000 index 0000000000..fb3446e1bf --- /dev/null +++ b/Lang/EDSAC-order-code/Shoelace-formula-for-polygonal-area @@ -0,0 +1 @@ +../../Task/Shoelace-formula-for-polygonal-area/EDSAC-order-code \ No newline at end of file diff --git a/Lang/EDSAC-order-code/Water-collected-between-towers b/Lang/EDSAC-order-code/Water-collected-between-towers new file mode 120000 index 0000000000..7c9456760f --- /dev/null +++ b/Lang/EDSAC-order-code/Water-collected-between-towers @@ -0,0 +1 @@ +../../Task/Water-collected-between-towers/EDSAC-order-code \ No newline at end of file diff --git a/Lang/EMal/00-LANG.txt b/Lang/EMal/00-LANG.txt index 9ecf11d932..3af52fab5c 100644 --- a/Lang/EMal/00-LANG.txt +++ b/Lang/EMal/00-LANG.txt @@ -6,21 +6,23 @@ |site=https://emal-lang.sourceforge.io |tags=emal |gc=yes}} -EMal is a prototyping programming language that supports english and italian syntax. +EMal is a prototyping programming language that supports English and Italian syntax. -EMal wants to be expressive and easy to read. +EMal wants to be expressive and readable. It supports closures, classes, records; it's influenced by Java, Perl, Javascript. -This is an example that, inside the same script, calculates F10 = 55 in english and in italian: +The programming environment consists of an interpreter that directly navigates the AST produced by the parser. + +This is an example that, inside the same script, calculates F10 = 55 in English and in Italian: type FibonacciInEnglish -fun fibonacci = int by int n +fun fibonacci ← int by int n if n < 2 do return n else do return fibonacci(n - 1) + fibonacci(n - 2) end end writeLine(fibonacci(10)) tipo FibonacciInItaliano -funzione fibonacci = intero da intero n +funzione fibonacci ← intero da intero n se n < 2 ritorna n altrimenti diff --git a/Lang/EMal/ABC-problem b/Lang/EMal/ABC-problem new file mode 120000 index 0000000000..4b49dc2baf --- /dev/null +++ b/Lang/EMal/ABC-problem @@ -0,0 +1 @@ +../../Task/ABC-problem/EMal \ No newline at end of file diff --git a/Lang/EMal/Babbage-problem b/Lang/EMal/Babbage-problem new file mode 120000 index 0000000000..8a7db13311 --- /dev/null +++ b/Lang/EMal/Babbage-problem @@ -0,0 +1 @@ +../../Task/Babbage-problem/EMal \ No newline at end of file diff --git a/Lang/EMal/Bifid-cipher b/Lang/EMal/Bifid-cipher new file mode 120000 index 0000000000..1dbee9fec8 --- /dev/null +++ b/Lang/EMal/Bifid-cipher @@ -0,0 +1 @@ +../../Task/Bifid-cipher/EMal \ No newline at end of file diff --git a/Lang/EMal/Delegates b/Lang/EMal/Delegates new file mode 120000 index 0000000000..5293d68109 --- /dev/null +++ b/Lang/EMal/Delegates @@ -0,0 +1 @@ +../../Task/Delegates/EMal \ No newline at end of file diff --git a/Lang/EMal/Determine-if-a-string-is-squeezable b/Lang/EMal/Determine-if-a-string-is-squeezable new file mode 120000 index 0000000000..27c56fc092 --- /dev/null +++ b/Lang/EMal/Determine-if-a-string-is-squeezable @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-squeezable/EMal \ No newline at end of file diff --git a/Lang/EMal/Dynamic-variable-names b/Lang/EMal/Dynamic-variable-names new file mode 120000 index 0000000000..28a70b20a1 --- /dev/null +++ b/Lang/EMal/Dynamic-variable-names @@ -0,0 +1 @@ +../../Task/Dynamic-variable-names/EMal \ No newline at end of file diff --git a/Lang/EMal/Gamma-function b/Lang/EMal/Gamma-function new file mode 120000 index 0000000000..f928139952 --- /dev/null +++ b/Lang/EMal/Gamma-function @@ -0,0 +1 @@ +../../Task/Gamma-function/EMal \ No newline at end of file diff --git a/Lang/EMal/Greatest-common-divisor b/Lang/EMal/Greatest-common-divisor new file mode 120000 index 0000000000..5a6de213e1 --- /dev/null +++ b/Lang/EMal/Greatest-common-divisor @@ -0,0 +1 @@ +../../Task/Greatest-common-divisor/EMal \ No newline at end of file diff --git a/Lang/EMal/Guess-the-number b/Lang/EMal/Guess-the-number new file mode 120000 index 0000000000..fc6e3366e6 --- /dev/null +++ b/Lang/EMal/Guess-the-number @@ -0,0 +1 @@ +../../Task/Guess-the-number/EMal \ No newline at end of file diff --git a/Lang/EMal/Halt-and-catch-fire b/Lang/EMal/Halt-and-catch-fire new file mode 120000 index 0000000000..63015fddfa --- /dev/null +++ b/Lang/EMal/Halt-and-catch-fire @@ -0,0 +1 @@ +../../Task/Halt-and-catch-fire/EMal \ No newline at end of file diff --git a/Lang/EMal/Mutual-recursion b/Lang/EMal/Mutual-recursion new file mode 120000 index 0000000000..cb3ebc8ca5 --- /dev/null +++ b/Lang/EMal/Mutual-recursion @@ -0,0 +1 @@ +../../Task/Mutual-recursion/EMal \ No newline at end of file diff --git a/Lang/EMal/Nth-root b/Lang/EMal/Nth-root new file mode 120000 index 0000000000..58e1f9e30f --- /dev/null +++ b/Lang/EMal/Nth-root @@ -0,0 +1 @@ +../../Task/Nth-root/EMal \ No newline at end of file diff --git a/Lang/EMal/Sorting-algorithms-Bogosort b/Lang/EMal/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..8dc8cc02d3 --- /dev/null +++ b/Lang/EMal/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/EMal \ No newline at end of file diff --git a/Lang/EMal/Sorting-algorithms-Bubble-sort b/Lang/EMal/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..53f744e6e9 --- /dev/null +++ b/Lang/EMal/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/EMal \ No newline at end of file diff --git a/Lang/EMal/Sorting-algorithms-Stooge-sort b/Lang/EMal/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..05296c2a09 --- /dev/null +++ b/Lang/EMal/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/EMal \ No newline at end of file diff --git a/Lang/EMal/String-comparison b/Lang/EMal/String-comparison new file mode 120000 index 0000000000..02b430a538 --- /dev/null +++ b/Lang/EMal/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/EMal \ No newline at end of file diff --git a/Lang/EMal/Sudan-function b/Lang/EMal/Sudan-function new file mode 120000 index 0000000000..ea87f1432e --- /dev/null +++ b/Lang/EMal/Sudan-function @@ -0,0 +1 @@ +../../Task/Sudan-function/EMal \ No newline at end of file diff --git a/Lang/EMal/Ternary-logic b/Lang/EMal/Ternary-logic new file mode 120000 index 0000000000..837bedfab5 --- /dev/null +++ b/Lang/EMal/Ternary-logic @@ -0,0 +1 @@ +../../Task/Ternary-logic/EMal \ No newline at end of file diff --git a/Lang/EMal/Tree-traversal b/Lang/EMal/Tree-traversal new file mode 120000 index 0000000000..b693d069a6 --- /dev/null +++ b/Lang/EMal/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/EMal \ No newline at end of file diff --git a/Lang/EMal/User-input-Text b/Lang/EMal/User-input-Text new file mode 120000 index 0000000000..3c00cf11ba --- /dev/null +++ b/Lang/EMal/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/EMal \ No newline at end of file diff --git a/Lang/EMal/Van-Eck-sequence b/Lang/EMal/Van-Eck-sequence new file mode 120000 index 0000000000..45280862ec --- /dev/null +++ b/Lang/EMal/Van-Eck-sequence @@ -0,0 +1 @@ +../../Task/Van-Eck-sequence/EMal \ No newline at end of file diff --git a/Lang/ERRE/Leonardo-numbers b/Lang/ERRE/Leonardo-numbers new file mode 120000 index 0000000000..3e0d0050d1 --- /dev/null +++ b/Lang/ERRE/Leonardo-numbers @@ -0,0 +1 @@ +../../Task/Leonardo-numbers/ERRE \ No newline at end of file diff --git a/Lang/ERRE/Quaternion-type b/Lang/ERRE/Quaternion-type deleted file mode 120000 index fcc1edb64e..0000000000 --- a/Lang/ERRE/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/ERRE \ No newline at end of file diff --git a/Lang/EasyLang/00-LANG.txt b/Lang/EasyLang/00-LANG.txt index aa156f93c8..e09a925b83 100644 --- a/Lang/EasyLang/00-LANG.txt +++ b/Lang/EasyLang/00-LANG.txt @@ -1,19 +1,19 @@ {{language |exec=interpreted -|site=https://easylang.dev/ +|site=https://easylang.online/ |parampass=value, reference |safety=safe |express=explicit |checking=static |tags=learning, web canvas}} -[https://easylang.dev/ide/ '''Browser IDE'''] +[https://easylang.online/ide/ '''Browser IDE'''] ''Easylang'' is a (beginners) programming language with built-in commands for graphics output. The statically typed language has a reduced syntax and semantics. Variables do not have to be declared, the data type is encoded in the variable name - as was usual in the earlier home computer BASIC. The data types are strings and numbers (floating point), arrays of strings and numbers, and arrays of arrays. Arrays are 1-based and can grow. Programs compiled into an AST tree run in the browser or in the browser IDE. -[https://easylang.dev/ide/ A browser IDE] with different tutorials, one for beginners, makes programming and learning to program as easy as possible. +[https://easylang.online/ide/ A browser IDE] with different tutorials, one for beginners, makes programming and learning to program as easy as possible. -The finished programs can be easily integrated into a [https://easylang.dev/apps/ website]. +The finished programs can be easily integrated into a [https://easylang.online/apps/ website]. ==Todo== [[Tasks not implemented in EasyLang]] \ No newline at end of file diff --git a/Lang/EasyLang/2048 b/Lang/EasyLang/2048 new file mode 120000 index 0000000000..4a69b16207 --- /dev/null +++ b/Lang/EasyLang/2048 @@ -0,0 +1 @@ +../../Task/2048/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/24-game b/Lang/EasyLang/24-game new file mode 120000 index 0000000000..85da2301e7 --- /dev/null +++ b/Lang/EasyLang/24-game @@ -0,0 +1 @@ +../../Task/24-game/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/9-billion-names-of-God-the-integer b/Lang/EasyLang/9-billion-names-of-God-the-integer new file mode 120000 index 0000000000..eab904ccaa --- /dev/null +++ b/Lang/EasyLang/9-billion-names-of-God-the-integer @@ -0,0 +1 @@ +../../Task/9-billion-names-of-God-the-integer/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/AKS-test-for-primes b/Lang/EasyLang/AKS-test-for-primes new file mode 120000 index 0000000000..fb3fd809a4 --- /dev/null +++ b/Lang/EasyLang/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Abbreviations-automatic b/Lang/EasyLang/Abbreviations-automatic new file mode 120000 index 0000000000..10b2251691 --- /dev/null +++ b/Lang/EasyLang/Abbreviations-automatic @@ -0,0 +1 @@ +../../Task/Abbreviations-automatic/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Abbreviations-easy b/Lang/EasyLang/Abbreviations-easy new file mode 120000 index 0000000000..9f43877f2b --- /dev/null +++ b/Lang/EasyLang/Abbreviations-easy @@ -0,0 +1 @@ +../../Task/Abbreviations-easy/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Abbreviations-simple b/Lang/EasyLang/Abbreviations-simple new file mode 120000 index 0000000000..53295111be --- /dev/null +++ b/Lang/EasyLang/Abbreviations-simple @@ -0,0 +1 @@ +../../Task/Abbreviations-simple/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Abelian-sandpile-model b/Lang/EasyLang/Abelian-sandpile-model new file mode 120000 index 0000000000..c97f3c3aa6 --- /dev/null +++ b/Lang/EasyLang/Abelian-sandpile-model @@ -0,0 +1 @@ +../../Task/Abelian-sandpile-model/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Abelian-sandpile-model-Identity b/Lang/EasyLang/Abelian-sandpile-model-Identity new file mode 120000 index 0000000000..c44f8cb53d --- /dev/null +++ b/Lang/EasyLang/Abelian-sandpile-model-Identity @@ -0,0 +1 @@ +../../Task/Abelian-sandpile-model-Identity/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Amb b/Lang/EasyLang/Amb new file mode 120000 index 0000000000..cee73196db --- /dev/null +++ b/Lang/EasyLang/Amb @@ -0,0 +1 @@ +../../Task/Amb/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Anagrams b/Lang/EasyLang/Anagrams new file mode 120000 index 0000000000..1a48ded8aa --- /dev/null +++ b/Lang/EasyLang/Anagrams @@ -0,0 +1 @@ +../../Task/Anagrams/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Anagrams-Deranged-anagrams b/Lang/EasyLang/Anagrams-Deranged-anagrams new file mode 120000 index 0000000000..b7af47405b --- /dev/null +++ b/Lang/EasyLang/Anagrams-Deranged-anagrams @@ -0,0 +1 @@ +../../Task/Anagrams-Deranged-anagrams/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Approximate-equality b/Lang/EasyLang/Approximate-equality new file mode 120000 index 0000000000..916cbf0873 --- /dev/null +++ b/Lang/EasyLang/Approximate-equality @@ -0,0 +1 @@ +../../Task/Approximate-equality/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Arithmetic-Complex b/Lang/EasyLang/Arithmetic-Complex new file mode 120000 index 0000000000..547a37cd78 --- /dev/null +++ b/Lang/EasyLang/Arithmetic-Complex @@ -0,0 +1 @@ +../../Task/Arithmetic-Complex/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Associative-array-Merging b/Lang/EasyLang/Associative-array-Merging new file mode 120000 index 0000000000..efe48db36d --- /dev/null +++ b/Lang/EasyLang/Associative-array-Merging @@ -0,0 +1 @@ +../../Task/Associative-array-Merging/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Babylonian-spiral b/Lang/EasyLang/Babylonian-spiral new file mode 120000 index 0000000000..a141d2cd6b --- /dev/null +++ b/Lang/EasyLang/Babylonian-spiral @@ -0,0 +1 @@ +../../Task/Babylonian-spiral/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Bioinformatics-Sequence-mutation b/Lang/EasyLang/Bioinformatics-Sequence-mutation new file mode 120000 index 0000000000..6d30bfa11e --- /dev/null +++ b/Lang/EasyLang/Bioinformatics-Sequence-mutation @@ -0,0 +1 @@ +../../Task/Bioinformatics-Sequence-mutation/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Bioinformatics-base-count b/Lang/EasyLang/Bioinformatics-base-count deleted file mode 120000 index 3bc65db849..0000000000 --- a/Lang/EasyLang/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Bitmap-B-zier-curves-Quadratic b/Lang/EasyLang/Bitmap-B-zier-curves-Quadratic new file mode 120000 index 0000000000..569a661356 --- /dev/null +++ b/Lang/EasyLang/Bitmap-B-zier-curves-Quadratic @@ -0,0 +1 @@ +../../Task/Bitmap-B-zier-curves-Quadratic/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Bitmap-Midpoint-circle-algorithm b/Lang/EasyLang/Bitmap-Midpoint-circle-algorithm new file mode 120000 index 0000000000..9b995802ee --- /dev/null +++ b/Lang/EasyLang/Bitmap-Midpoint-circle-algorithm @@ -0,0 +1 @@ +../../Task/Bitmap-Midpoint-circle-algorithm/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Boyer-Moore-string-search b/Lang/EasyLang/Boyer-Moore-string-search new file mode 120000 index 0000000000..189112146a --- /dev/null +++ b/Lang/EasyLang/Boyer-Moore-string-search @@ -0,0 +1 @@ +../../Task/Boyer-Moore-string-search/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Brace-expansion b/Lang/EasyLang/Brace-expansion new file mode 120000 index 0000000000..fadaa7c96a --- /dev/null +++ b/Lang/EasyLang/Brace-expansion @@ -0,0 +1 @@ +../../Task/Brace-expansion/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Bulls-and-cows-Player b/Lang/EasyLang/Bulls-and-cows-Player new file mode 120000 index 0000000000..9e4aef5378 --- /dev/null +++ b/Lang/EasyLang/Bulls-and-cows-Player @@ -0,0 +1 @@ +../../Task/Bulls-and-cows-Player/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Burrows-Wheeler-transform b/Lang/EasyLang/Burrows-Wheeler-transform new file mode 120000 index 0000000000..d3dcf6a651 --- /dev/null +++ b/Lang/EasyLang/Burrows-Wheeler-transform @@ -0,0 +1 @@ +../../Task/Burrows-Wheeler-transform/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/CRC-32 b/Lang/EasyLang/CRC-32 new file mode 120000 index 0000000000..75d250a063 --- /dev/null +++ b/Lang/EasyLang/CRC-32 @@ -0,0 +1 @@ +../../Task/CRC-32/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Cheryls-birthday b/Lang/EasyLang/Cheryls-birthday new file mode 120000 index 0000000000..da4092e3ea --- /dev/null +++ b/Lang/EasyLang/Cheryls-birthday @@ -0,0 +1 @@ +../../Task/Cheryls-birthday/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Cholesky-decomposition b/Lang/EasyLang/Cholesky-decomposition new file mode 120000 index 0000000000..3d9b8e35d4 --- /dev/null +++ b/Lang/EasyLang/Cholesky-decomposition @@ -0,0 +1 @@ +../../Task/Cholesky-decomposition/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Convert-decimal-number-to-rational b/Lang/EasyLang/Convert-decimal-number-to-rational new file mode 120000 index 0000000000..d8af3c05f9 --- /dev/null +++ b/Lang/EasyLang/Convert-decimal-number-to-rational @@ -0,0 +1 @@ +../../Task/Convert-decimal-number-to-rational/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Currency b/Lang/EasyLang/Currency new file mode 120000 index 0000000000..a42c848ea8 --- /dev/null +++ b/Lang/EasyLang/Currency @@ -0,0 +1 @@ +../../Task/Currency/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Date-format b/Lang/EasyLang/Date-format new file mode 120000 index 0000000000..443f76ed6a --- /dev/null +++ b/Lang/EasyLang/Date-format @@ -0,0 +1 @@ +../../Task/Date-format/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Death-Star b/Lang/EasyLang/Death-Star new file mode 120000 index 0000000000..71ec2dde3d --- /dev/null +++ b/Lang/EasyLang/Death-Star @@ -0,0 +1 @@ +../../Task/Death-Star/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Deconvolution-1D b/Lang/EasyLang/Deconvolution-1D new file mode 120000 index 0000000000..7dba9ab208 --- /dev/null +++ b/Lang/EasyLang/Deconvolution-1D @@ -0,0 +1 @@ +../../Task/Deconvolution-1D/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Deepcopy b/Lang/EasyLang/Deepcopy new file mode 120000 index 0000000000..4137c6d590 --- /dev/null +++ b/Lang/EasyLang/Deepcopy @@ -0,0 +1 @@ +../../Task/Deepcopy/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Determinant-and-permanent b/Lang/EasyLang/Determinant-and-permanent new file mode 120000 index 0000000000..09ae422506 --- /dev/null +++ b/Lang/EasyLang/Determinant-and-permanent @@ -0,0 +1 @@ +../../Task/Determinant-and-permanent/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Distribution-of-0-digits-in-factorial-series b/Lang/EasyLang/Distribution-of-0-digits-in-factorial-series new file mode 120000 index 0000000000..10532131de --- /dev/null +++ b/Lang/EasyLang/Distribution-of-0-digits-in-factorial-series @@ -0,0 +1 @@ +../../Task/Distribution-of-0-digits-in-factorial-series/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Draw-a-sphere b/Lang/EasyLang/Draw-a-sphere new file mode 120000 index 0000000000..4a92493ec5 --- /dev/null +++ b/Lang/EasyLang/Draw-a-sphere @@ -0,0 +1 @@ +../../Task/Draw-a-sphere/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/EKG-sequence-convergence b/Lang/EasyLang/EKG-sequence-convergence new file mode 120000 index 0000000000..a5d661cade --- /dev/null +++ b/Lang/EasyLang/EKG-sequence-convergence @@ -0,0 +1 @@ +../../Task/EKG-sequence-convergence/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Earliest-difference-between-prime-gaps b/Lang/EasyLang/Earliest-difference-between-prime-gaps new file mode 120000 index 0000000000..e8abb13bc1 --- /dev/null +++ b/Lang/EasyLang/Earliest-difference-between-prime-gaps @@ -0,0 +1 @@ +../../Task/Earliest-difference-between-prime-gaps/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Element-wise-operations b/Lang/EasyLang/Element-wise-operations new file mode 120000 index 0000000000..79d10fbb82 --- /dev/null +++ b/Lang/EasyLang/Element-wise-operations @@ -0,0 +1 @@ +../../Task/Element-wise-operations/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Elementary-cellular-automaton-Infinite-length b/Lang/EasyLang/Elementary-cellular-automaton-Infinite-length new file mode 120000 index 0000000000..440a0e3168 --- /dev/null +++ b/Lang/EasyLang/Elementary-cellular-automaton-Infinite-length @@ -0,0 +1 @@ +../../Task/Elementary-cellular-automaton-Infinite-length/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Erd-s-Selfridge-categorization-of-primes b/Lang/EasyLang/Erd-s-Selfridge-categorization-of-primes new file mode 120000 index 0000000000..a64dc7d4f0 --- /dev/null +++ b/Lang/EasyLang/Erd-s-Selfridge-categorization-of-primes @@ -0,0 +1 @@ +../../Task/Erd-s-Selfridge-categorization-of-primes/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Eulers-identity b/Lang/EasyLang/Eulers-identity new file mode 120000 index 0000000000..6753a604ea --- /dev/null +++ b/Lang/EasyLang/Eulers-identity @@ -0,0 +1 @@ +../../Task/Eulers-identity/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Factorions b/Lang/EasyLang/Factorions new file mode 120000 index 0000000000..52bf4a578c --- /dev/null +++ b/Lang/EasyLang/Factorions @@ -0,0 +1 @@ +../../Task/Factorions/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Fast-Fourier-transform b/Lang/EasyLang/Fast-Fourier-transform new file mode 120000 index 0000000000..6486d41d10 --- /dev/null +++ b/Lang/EasyLang/Fast-Fourier-transform @@ -0,0 +1 @@ +../../Task/Fast-Fourier-transform/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Faulhabers-formula b/Lang/EasyLang/Faulhabers-formula new file mode 120000 index 0000000000..a0587d4c22 --- /dev/null +++ b/Lang/EasyLang/Faulhabers-formula @@ -0,0 +1 @@ +../../Task/Faulhabers-formula/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Faulhabers-triangle b/Lang/EasyLang/Faulhabers-triangle new file mode 120000 index 0000000000..0ced82832c --- /dev/null +++ b/Lang/EasyLang/Faulhabers-triangle @@ -0,0 +1 @@ +../../Task/Faulhabers-triangle/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Fermat-numbers b/Lang/EasyLang/Fermat-numbers new file mode 120000 index 0000000000..0bf9bf359c --- /dev/null +++ b/Lang/EasyLang/Fermat-numbers @@ -0,0 +1 @@ +../../Task/Fermat-numbers/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Fibonacci-word-fractal b/Lang/EasyLang/Fibonacci-word-fractal new file mode 120000 index 0000000000..d075c27d88 --- /dev/null +++ b/Lang/EasyLang/Fibonacci-word-fractal @@ -0,0 +1 @@ +../../Task/Fibonacci-word-fractal/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Find-Chess960-starting-position-identifier b/Lang/EasyLang/Find-Chess960-starting-position-identifier new file mode 120000 index 0000000000..74db5136c0 --- /dev/null +++ b/Lang/EasyLang/Find-Chess960-starting-position-identifier @@ -0,0 +1 @@ +../../Task/Find-Chess960-starting-position-identifier/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Find-if-a-point-is-within-a-triangle b/Lang/EasyLang/Find-if-a-point-is-within-a-triangle new file mode 120000 index 0000000000..cd1bb80075 --- /dev/null +++ b/Lang/EasyLang/Find-if-a-point-is-within-a-triangle @@ -0,0 +1 @@ +../../Task/Find-if-a-point-is-within-a-triangle/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Floyd-Warshall-algorithm b/Lang/EasyLang/Floyd-Warshall-algorithm new file mode 120000 index 0000000000..3210a33bb1 --- /dev/null +++ b/Lang/EasyLang/Floyd-Warshall-algorithm @@ -0,0 +1 @@ +../../Task/Floyd-Warshall-algorithm/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Fortunate-numbers b/Lang/EasyLang/Fortunate-numbers new file mode 120000 index 0000000000..2c6e02874b --- /dev/null +++ b/Lang/EasyLang/Fortunate-numbers @@ -0,0 +1 @@ +../../Task/Fortunate-numbers/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Forward-difference b/Lang/EasyLang/Forward-difference new file mode 120000 index 0000000000..12de7eedb0 --- /dev/null +++ b/Lang/EasyLang/Forward-difference @@ -0,0 +1 @@ +../../Task/Forward-difference/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Fraction-reduction b/Lang/EasyLang/Fraction-reduction new file mode 120000 index 0000000000..61af524020 --- /dev/null +++ b/Lang/EasyLang/Fraction-reduction @@ -0,0 +1 @@ +../../Task/Fraction-reduction/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Fractran b/Lang/EasyLang/Fractran new file mode 120000 index 0000000000..431453ab79 --- /dev/null +++ b/Lang/EasyLang/Fractran @@ -0,0 +1 @@ +../../Task/Fractran/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/French-Republican-calendar b/Lang/EasyLang/French-Republican-calendar new file mode 120000 index 0000000000..63cacd897e --- /dev/null +++ b/Lang/EasyLang/French-Republican-calendar @@ -0,0 +1 @@ +../../Task/French-Republican-calendar/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Function-prototype b/Lang/EasyLang/Function-prototype new file mode 120000 index 0000000000..d56b3a5da3 --- /dev/null +++ b/Lang/EasyLang/Function-prototype @@ -0,0 +1 @@ +../../Task/Function-prototype/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Greatest-subsequential-sum b/Lang/EasyLang/Greatest-subsequential-sum new file mode 120000 index 0000000000..679d3c6deb --- /dev/null +++ b/Lang/EasyLang/Greatest-subsequential-sum @@ -0,0 +1 @@ +../../Task/Greatest-subsequential-sum/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Guess-the-number-With-feedback-player- b/Lang/EasyLang/Guess-the-number-With-feedback-player- new file mode 120000 index 0000000000..56ad8fd02a --- /dev/null +++ b/Lang/EasyLang/Guess-the-number-With-feedback-player- @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback-player-/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Halt-and-catch-fire b/Lang/EasyLang/Halt-and-catch-fire new file mode 120000 index 0000000000..fe61f64c40 --- /dev/null +++ b/Lang/EasyLang/Halt-and-catch-fire @@ -0,0 +1 @@ +../../Task/Halt-and-catch-fire/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Hamming-numbers b/Lang/EasyLang/Hamming-numbers new file mode 120000 index 0000000000..6f52ef2c78 --- /dev/null +++ b/Lang/EasyLang/Hamming-numbers @@ -0,0 +1 @@ +../../Task/Hamming-numbers/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Hash-from-two-arrays b/Lang/EasyLang/Hash-from-two-arrays new file mode 120000 index 0000000000..0d148a2df3 --- /dev/null +++ b/Lang/EasyLang/Hash-from-two-arrays @@ -0,0 +1 @@ +../../Task/Hash-from-two-arrays/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Heronian-triangles b/Lang/EasyLang/Heronian-triangles new file mode 120000 index 0000000000..8656dc59f0 --- /dev/null +++ b/Lang/EasyLang/Heronian-triangles @@ -0,0 +1 @@ +../../Task/Heronian-triangles/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Hex-words b/Lang/EasyLang/Hex-words new file mode 120000 index 0000000000..0d39e2eee9 --- /dev/null +++ b/Lang/EasyLang/Hex-words @@ -0,0 +1 @@ +../../Task/Hex-words/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Hofstadter-Figure-Figure-sequences b/Lang/EasyLang/Hofstadter-Figure-Figure-sequences new file mode 120000 index 0000000000..d5a34b275d --- /dev/null +++ b/Lang/EasyLang/Hofstadter-Figure-Figure-sequences @@ -0,0 +1 @@ +../../Task/Hofstadter-Figure-Figure-sequences/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Honeycombs b/Lang/EasyLang/Honeycombs new file mode 120000 index 0000000000..5885102888 --- /dev/null +++ b/Lang/EasyLang/Honeycombs @@ -0,0 +1 @@ +../../Task/Honeycombs/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Hunt-the-Wumpus b/Lang/EasyLang/Hunt-the-Wumpus new file mode 120000 index 0000000000..8a2489577d --- /dev/null +++ b/Lang/EasyLang/Hunt-the-Wumpus @@ -0,0 +1 @@ +../../Task/Hunt-the-Wumpus/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/IBAN b/Lang/EasyLang/IBAN new file mode 120000 index 0000000000..961014b963 --- /dev/null +++ b/Lang/EasyLang/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols b/Lang/EasyLang/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols new file mode 120000 index 0000000000..ff1573925b --- /dev/null +++ b/Lang/EasyLang/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols @@ -0,0 +1 @@ +../../Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Im-a-software-engineer-get-me-out-of-here b/Lang/EasyLang/Im-a-software-engineer-get-me-out-of-here new file mode 120000 index 0000000000..70ace224d9 --- /dev/null +++ b/Lang/EasyLang/Im-a-software-engineer-get-me-out-of-here @@ -0,0 +1 @@ +../../Task/Im-a-software-engineer-get-me-out-of-here/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Isograms-and-heterograms b/Lang/EasyLang/Isograms-and-heterograms new file mode 120000 index 0000000000..44f53b57ff --- /dev/null +++ b/Lang/EasyLang/Isograms-and-heterograms @@ -0,0 +1 @@ +../../Task/Isograms-and-heterograms/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Iterated-digits-squaring b/Lang/EasyLang/Iterated-digits-squaring new file mode 120000 index 0000000000..193be9fcba --- /dev/null +++ b/Lang/EasyLang/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Jacobi-symbol b/Lang/EasyLang/Jacobi-symbol new file mode 120000 index 0000000000..fec464ee0d --- /dev/null +++ b/Lang/EasyLang/Jacobi-symbol @@ -0,0 +1 @@ +../../Task/Jacobi-symbol/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Jacobsthal-numbers b/Lang/EasyLang/Jacobsthal-numbers new file mode 120000 index 0000000000..9469db92c2 --- /dev/null +++ b/Lang/EasyLang/Jacobsthal-numbers @@ -0,0 +1 @@ +../../Task/Jacobsthal-numbers/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Jaro-Winkler-distance b/Lang/EasyLang/Jaro-Winkler-distance new file mode 120000 index 0000000000..727f74b880 --- /dev/null +++ b/Lang/EasyLang/Jaro-Winkler-distance @@ -0,0 +1 @@ +../../Task/Jaro-Winkler-distance/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Jaro-similarity b/Lang/EasyLang/Jaro-similarity new file mode 120000 index 0000000000..d630573e8e --- /dev/null +++ b/Lang/EasyLang/Jaro-similarity @@ -0,0 +1 @@ +../../Task/Jaro-similarity/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/JortSort b/Lang/EasyLang/JortSort new file mode 120000 index 0000000000..69c9d425de --- /dev/null +++ b/Lang/EasyLang/JortSort @@ -0,0 +1 @@ +../../Task/JortSort/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Juggler-sequence b/Lang/EasyLang/Juggler-sequence new file mode 120000 index 0000000000..a501986168 --- /dev/null +++ b/Lang/EasyLang/Juggler-sequence @@ -0,0 +1 @@ +../../Task/Juggler-sequence/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/K-means++-clustering b/Lang/EasyLang/K-means++-clustering new file mode 120000 index 0000000000..9c59e662f6 --- /dev/null +++ b/Lang/EasyLang/K-means++-clustering @@ -0,0 +1 @@ +../../Task/K-means++-clustering/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Kernighans-large-earthquake-problem b/Lang/EasyLang/Kernighans-large-earthquake-problem new file mode 120000 index 0000000000..3ab1e4458e --- /dev/null +++ b/Lang/EasyLang/Kernighans-large-earthquake-problem @@ -0,0 +1 @@ +../../Task/Kernighans-large-earthquake-problem/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Keyboard-input-Keypress-check b/Lang/EasyLang/Keyboard-input-Keypress-check new file mode 120000 index 0000000000..749a963892 --- /dev/null +++ b/Lang/EasyLang/Keyboard-input-Keypress-check @@ -0,0 +1 @@ +../../Task/Keyboard-input-Keypress-check/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Keyboard-input-Obtain-a-Y-or-N-response b/Lang/EasyLang/Keyboard-input-Obtain-a-Y-or-N-response new file mode 120000 index 0000000000..afc72ecd9d --- /dev/null +++ b/Lang/EasyLang/Keyboard-input-Obtain-a-Y-or-N-response @@ -0,0 +1 @@ +../../Task/Keyboard-input-Obtain-a-Y-or-N-response/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Knapsack-problem-Bounded b/Lang/EasyLang/Knapsack-problem-Bounded new file mode 120000 index 0000000000..d0f7a40df2 --- /dev/null +++ b/Lang/EasyLang/Knapsack-problem-Bounded @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Bounded/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Knapsack-problem-Continuous b/Lang/EasyLang/Knapsack-problem-Continuous new file mode 120000 index 0000000000..a54e4a1363 --- /dev/null +++ b/Lang/EasyLang/Knapsack-problem-Continuous @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Continuous/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Knapsack-problem-Unbounded b/Lang/EasyLang/Knapsack-problem-Unbounded new file mode 120000 index 0000000000..feaf22d24e --- /dev/null +++ b/Lang/EasyLang/Knapsack-problem-Unbounded @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Unbounded/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Knights-tour b/Lang/EasyLang/Knights-tour new file mode 120000 index 0000000000..c3c72273c2 --- /dev/null +++ b/Lang/EasyLang/Knights-tour @@ -0,0 +1 @@ +../../Task/Knights-tour/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Kolakoski-sequence b/Lang/EasyLang/Kolakoski-sequence new file mode 120000 index 0000000000..0d808caea4 --- /dev/null +++ b/Lang/EasyLang/Kolakoski-sequence @@ -0,0 +1 @@ +../../Task/Kolakoski-sequence/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Kosaraju b/Lang/EasyLang/Kosaraju new file mode 120000 index 0000000000..84b9e66a67 --- /dev/null +++ b/Lang/EasyLang/Kosaraju @@ -0,0 +1 @@ +../../Task/Kosaraju/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Kronecker-product b/Lang/EasyLang/Kronecker-product new file mode 120000 index 0000000000..1246c0ce28 --- /dev/null +++ b/Lang/EasyLang/Kronecker-product @@ -0,0 +1 @@ +../../Task/Kronecker-product/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Kronecker-product-based-fractals b/Lang/EasyLang/Kronecker-product-based-fractals new file mode 120000 index 0000000000..563af0ba71 --- /dev/null +++ b/Lang/EasyLang/Kronecker-product-based-fractals @@ -0,0 +1 @@ +../../Task/Kronecker-product-based-fractals/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/LU-decomposition b/Lang/EasyLang/LU-decomposition new file mode 120000 index 0000000000..b8f8a0d85a --- /dev/null +++ b/Lang/EasyLang/LU-decomposition @@ -0,0 +1 @@ +../../Task/LU-decomposition/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Largest-int-from-concatenated-ints b/Lang/EasyLang/Largest-int-from-concatenated-ints new file mode 120000 index 0000000000..10e1335e8a --- /dev/null +++ b/Lang/EasyLang/Largest-int-from-concatenated-ints @@ -0,0 +1 @@ +../../Task/Largest-int-from-concatenated-ints/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Last-letter-first-letter b/Lang/EasyLang/Last-letter-first-letter new file mode 120000 index 0000000000..0b195a1260 --- /dev/null +++ b/Lang/EasyLang/Last-letter-first-letter @@ -0,0 +1 @@ +../../Task/Last-letter-first-letter/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Law-of-cosines---triples b/Lang/EasyLang/Law-of-cosines---triples new file mode 120000 index 0000000000..c863a3f9c0 --- /dev/null +++ b/Lang/EasyLang/Law-of-cosines---triples @@ -0,0 +1 @@ +../../Task/Law-of-cosines---triples/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Left-factorials b/Lang/EasyLang/Left-factorials new file mode 120000 index 0000000000..99571138e4 --- /dev/null +++ b/Lang/EasyLang/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Legendre-prime-counting-function b/Lang/EasyLang/Legendre-prime-counting-function new file mode 120000 index 0000000000..4b5478a288 --- /dev/null +++ b/Lang/EasyLang/Legendre-prime-counting-function @@ -0,0 +1 @@ +../../Task/Legendre-prime-counting-function/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/List-rooted-trees b/Lang/EasyLang/List-rooted-trees new file mode 120000 index 0000000000..14cdfaa5a6 --- /dev/null +++ b/Lang/EasyLang/List-rooted-trees @@ -0,0 +1 @@ +../../Task/List-rooted-trees/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Logistic-curve-fitting-in-epidemiology b/Lang/EasyLang/Logistic-curve-fitting-in-epidemiology new file mode 120000 index 0000000000..265f7cdf24 --- /dev/null +++ b/Lang/EasyLang/Logistic-curve-fitting-in-epidemiology @@ -0,0 +1 @@ +../../Task/Logistic-curve-fitting-in-epidemiology/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Long-literals-with-continuations b/Lang/EasyLang/Long-literals-with-continuations new file mode 120000 index 0000000000..ffe5aa4238 --- /dev/null +++ b/Lang/EasyLang/Long-literals-with-continuations @@ -0,0 +1 @@ +../../Task/Long-literals-with-continuations/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Longest-increasing-subsequence b/Lang/EasyLang/Longest-increasing-subsequence new file mode 120000 index 0000000000..eabf95f750 --- /dev/null +++ b/Lang/EasyLang/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Loops-Wrong-ranges b/Lang/EasyLang/Loops-Wrong-ranges new file mode 120000 index 0000000000..d803a36357 --- /dev/null +++ b/Lang/EasyLang/Loops-Wrong-ranges @@ -0,0 +1 @@ +../../Task/Loops-Wrong-ranges/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Ludic-numbers b/Lang/EasyLang/Ludic-numbers new file mode 120000 index 0000000000..1d6fc2e015 --- /dev/null +++ b/Lang/EasyLang/Ludic-numbers @@ -0,0 +1 @@ +../../Task/Ludic-numbers/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Lychrel-numbers b/Lang/EasyLang/Lychrel-numbers new file mode 120000 index 0000000000..a66932caaa --- /dev/null +++ b/Lang/EasyLang/Lychrel-numbers @@ -0,0 +1 @@ +../../Task/Lychrel-numbers/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/MD4 b/Lang/EasyLang/MD4 new file mode 120000 index 0000000000..607e4d2f65 --- /dev/null +++ b/Lang/EasyLang/MD4 @@ -0,0 +1 @@ +../../Task/MD4/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Mad-Libs b/Lang/EasyLang/Mad-Libs new file mode 120000 index 0000000000..80e4f5b2e7 --- /dev/null +++ b/Lang/EasyLang/Mad-Libs @@ -0,0 +1 @@ +../../Task/Mad-Libs/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Magic-squares-of-doubly-even-order b/Lang/EasyLang/Magic-squares-of-doubly-even-order new file mode 120000 index 0000000000..b5f41f3cca --- /dev/null +++ b/Lang/EasyLang/Magic-squares-of-doubly-even-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-doubly-even-order/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Magic-squares-of-singly-even-order b/Lang/EasyLang/Magic-squares-of-singly-even-order new file mode 120000 index 0000000000..bffad4e9d9 --- /dev/null +++ b/Lang/EasyLang/Magic-squares-of-singly-even-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-singly-even-order/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Map-range b/Lang/EasyLang/Map-range new file mode 120000 index 0000000000..7f2fe886c3 --- /dev/null +++ b/Lang/EasyLang/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Matrix-chain-multiplication b/Lang/EasyLang/Matrix-chain-multiplication new file mode 120000 index 0000000000..49b2582836 --- /dev/null +++ b/Lang/EasyLang/Matrix-chain-multiplication @@ -0,0 +1 @@ +../../Task/Matrix-chain-multiplication/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Matrix-exponentiation-operator b/Lang/EasyLang/Matrix-exponentiation-operator new file mode 120000 index 0000000000..ffeb77ddad --- /dev/null +++ b/Lang/EasyLang/Matrix-exponentiation-operator @@ -0,0 +1 @@ +../../Task/Matrix-exponentiation-operator/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Mayan-numerals b/Lang/EasyLang/Mayan-numerals new file mode 120000 index 0000000000..101692428a --- /dev/null +++ b/Lang/EasyLang/Mayan-numerals @@ -0,0 +1 @@ +../../Task/Mayan-numerals/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Meissel-Mertens-constant b/Lang/EasyLang/Meissel-Mertens-constant deleted file mode 120000 index 2673a3a653..0000000000 --- a/Lang/EasyLang/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Merge-and-aggregate-datasets b/Lang/EasyLang/Merge-and-aggregate-datasets new file mode 120000 index 0000000000..4240a68719 --- /dev/null +++ b/Lang/EasyLang/Merge-and-aggregate-datasets @@ -0,0 +1 @@ +../../Task/Merge-and-aggregate-datasets/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Mian-Chowla-sequence b/Lang/EasyLang/Mian-Chowla-sequence new file mode 120000 index 0000000000..314aaad4b1 --- /dev/null +++ b/Lang/EasyLang/Mian-Chowla-sequence @@ -0,0 +1 @@ +../../Task/Mian-Chowla-sequence/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Minkowski-question-mark-function b/Lang/EasyLang/Minkowski-question-mark-function new file mode 120000 index 0000000000..e4df814cca --- /dev/null +++ b/Lang/EasyLang/Minkowski-question-mark-function @@ -0,0 +1 @@ +../../Task/Minkowski-question-mark-function/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Modified-random-distribution b/Lang/EasyLang/Modified-random-distribution new file mode 120000 index 0000000000..127bc0bcb6 --- /dev/null +++ b/Lang/EasyLang/Modified-random-distribution @@ -0,0 +1 @@ +../../Task/Modified-random-distribution/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Modular-exponentiation b/Lang/EasyLang/Modular-exponentiation new file mode 120000 index 0000000000..7257cc430f --- /dev/null +++ b/Lang/EasyLang/Modular-exponentiation @@ -0,0 +1 @@ +../../Task/Modular-exponentiation/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Move-to-front-algorithm b/Lang/EasyLang/Move-to-front-algorithm new file mode 120000 index 0000000000..8c3f8fe7f9 --- /dev/null +++ b/Lang/EasyLang/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Multi-base-primes b/Lang/EasyLang/Multi-base-primes new file mode 120000 index 0000000000..0b06b01c9e --- /dev/null +++ b/Lang/EasyLang/Multi-base-primes @@ -0,0 +1 @@ +../../Task/Multi-base-primes/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Multisplit b/Lang/EasyLang/Multisplit new file mode 120000 index 0000000000..3f480eaeea --- /dev/null +++ b/Lang/EasyLang/Multisplit @@ -0,0 +1 @@ +../../Task/Multisplit/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Negative-base-numbers b/Lang/EasyLang/Negative-base-numbers new file mode 120000 index 0000000000..750b2fa4de --- /dev/null +++ b/Lang/EasyLang/Negative-base-numbers @@ -0,0 +1 @@ +../../Task/Negative-base-numbers/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Nested-function b/Lang/EasyLang/Nested-function new file mode 120000 index 0000000000..3d6f80739f --- /dev/null +++ b/Lang/EasyLang/Nested-function @@ -0,0 +1 @@ +../../Task/Nested-function/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Non-continuous-subsequences b/Lang/EasyLang/Non-continuous-subsequences new file mode 120000 index 0000000000..1ddebfbef7 --- /dev/null +++ b/Lang/EasyLang/Non-continuous-subsequences @@ -0,0 +1 @@ +../../Task/Non-continuous-subsequences/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Non-decimal-radices-Input b/Lang/EasyLang/Non-decimal-radices-Input new file mode 120000 index 0000000000..15845b7041 --- /dev/null +++ b/Lang/EasyLang/Non-decimal-radices-Input @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Input/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Nonoblock b/Lang/EasyLang/Nonoblock new file mode 120000 index 0000000000..e2c27bd166 --- /dev/null +++ b/Lang/EasyLang/Nonoblock @@ -0,0 +1 @@ +../../Task/Nonoblock/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Number-reversal-game b/Lang/EasyLang/Number-reversal-game new file mode 120000 index 0000000000..a55399f2e0 --- /dev/null +++ b/Lang/EasyLang/Number-reversal-game @@ -0,0 +1 @@ +../../Task/Number-reversal-game/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Order-by-pair-comparisons b/Lang/EasyLang/Order-by-pair-comparisons new file mode 120000 index 0000000000..78fc8f28e3 --- /dev/null +++ b/Lang/EasyLang/Order-by-pair-comparisons @@ -0,0 +1 @@ +../../Task/Order-by-pair-comparisons/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Order-disjoint-list-items b/Lang/EasyLang/Order-disjoint-list-items new file mode 120000 index 0000000000..bd0f2b89f9 --- /dev/null +++ b/Lang/EasyLang/Order-disjoint-list-items @@ -0,0 +1 @@ +../../Task/Order-disjoint-list-items/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Ordered-words b/Lang/EasyLang/Ordered-words new file mode 120000 index 0000000000..284c4e7df2 --- /dev/null +++ b/Lang/EasyLang/Ordered-words @@ -0,0 +1 @@ +../../Task/Ordered-words/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Paraffins b/Lang/EasyLang/Paraffins new file mode 120000 index 0000000000..954e9b549e --- /dev/null +++ b/Lang/EasyLang/Paraffins @@ -0,0 +1 @@ +../../Task/Paraffins/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Parsing-RPN-calculator-algorithm b/Lang/EasyLang/Parsing-RPN-calculator-algorithm new file mode 120000 index 0000000000..4c308dc876 --- /dev/null +++ b/Lang/EasyLang/Parsing-RPN-calculator-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-RPN-calculator-algorithm/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Partition-an-integer-x-into-n-primes b/Lang/EasyLang/Partition-an-integer-x-into-n-primes new file mode 120000 index 0000000000..21cc93eeed --- /dev/null +++ b/Lang/EasyLang/Partition-an-integer-x-into-n-primes @@ -0,0 +1 @@ +../../Task/Partition-an-integer-x-into-n-primes/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Partition-function-P b/Lang/EasyLang/Partition-function-P new file mode 120000 index 0000000000..07b0e608d7 --- /dev/null +++ b/Lang/EasyLang/Partition-function-P @@ -0,0 +1 @@ +../../Task/Partition-function-P/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Pascal-matrix-generation b/Lang/EasyLang/Pascal-matrix-generation new file mode 120000 index 0000000000..2a45a12baf --- /dev/null +++ b/Lang/EasyLang/Pascal-matrix-generation @@ -0,0 +1 @@ +../../Task/Pascal-matrix-generation/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Pascals-triangle-Puzzle b/Lang/EasyLang/Pascals-triangle-Puzzle new file mode 120000 index 0000000000..bb3b35817e --- /dev/null +++ b/Lang/EasyLang/Pascals-triangle-Puzzle @@ -0,0 +1 @@ +../../Task/Pascals-triangle-Puzzle/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Password-generator b/Lang/EasyLang/Password-generator new file mode 120000 index 0000000000..004d74f550 --- /dev/null +++ b/Lang/EasyLang/Password-generator @@ -0,0 +1 @@ +../../Task/Password-generator/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Pathological-floating-point-problems b/Lang/EasyLang/Pathological-floating-point-problems new file mode 120000 index 0000000000..feb17cf372 --- /dev/null +++ b/Lang/EasyLang/Pathological-floating-point-problems @@ -0,0 +1 @@ +../../Task/Pathological-floating-point-problems/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Penneys-game b/Lang/EasyLang/Penneys-game new file mode 120000 index 0000000000..8a534b3c6f --- /dev/null +++ b/Lang/EasyLang/Penneys-game @@ -0,0 +1 @@ +../../Task/Penneys-game/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Percolation-Mean-cluster-density b/Lang/EasyLang/Percolation-Mean-cluster-density new file mode 120000 index 0000000000..5231594fc4 --- /dev/null +++ b/Lang/EasyLang/Percolation-Mean-cluster-density @@ -0,0 +1 @@ +../../Task/Percolation-Mean-cluster-density/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Percolation-Site-percolation b/Lang/EasyLang/Percolation-Site-percolation new file mode 120000 index 0000000000..50ffe015c4 --- /dev/null +++ b/Lang/EasyLang/Percolation-Site-percolation @@ -0,0 +1 @@ +../../Task/Percolation-Site-percolation/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Peripheral-drift-illusion b/Lang/EasyLang/Peripheral-drift-illusion new file mode 120000 index 0000000000..6922becd71 --- /dev/null +++ b/Lang/EasyLang/Peripheral-drift-illusion @@ -0,0 +1 @@ +../../Task/Peripheral-drift-illusion/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Permutation-test b/Lang/EasyLang/Permutation-test new file mode 120000 index 0000000000..d3b1950f7a --- /dev/null +++ b/Lang/EasyLang/Permutation-test @@ -0,0 +1 @@ +../../Task/Permutation-test/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Permutations-Rank-of-a-permutation b/Lang/EasyLang/Permutations-Rank-of-a-permutation new file mode 120000 index 0000000000..0512aed3af --- /dev/null +++ b/Lang/EasyLang/Permutations-Rank-of-a-permutation @@ -0,0 +1 @@ +../../Task/Permutations-Rank-of-a-permutation/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Phrase-reversals b/Lang/EasyLang/Phrase-reversals new file mode 120000 index 0000000000..3631697399 --- /dev/null +++ b/Lang/EasyLang/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Pierpont-primes b/Lang/EasyLang/Pierpont-primes new file mode 120000 index 0000000000..6e3e44c04c --- /dev/null +++ b/Lang/EasyLang/Pierpont-primes @@ -0,0 +1 @@ +../../Task/Pierpont-primes/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Pinstripe-Display b/Lang/EasyLang/Pinstripe-Display new file mode 120000 index 0000000000..db25917458 --- /dev/null +++ b/Lang/EasyLang/Pinstripe-Display @@ -0,0 +1 @@ +../../Task/Pinstripe-Display/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Plasma-effect b/Lang/EasyLang/Plasma-effect new file mode 120000 index 0000000000..5f845f7e61 --- /dev/null +++ b/Lang/EasyLang/Plasma-effect @@ -0,0 +1 @@ +../../Task/Plasma-effect/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Playfair-cipher b/Lang/EasyLang/Playfair-cipher new file mode 120000 index 0000000000..3d1568669f --- /dev/null +++ b/Lang/EasyLang/Playfair-cipher @@ -0,0 +1 @@ +../../Task/Playfair-cipher/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Poker-hand-analyser b/Lang/EasyLang/Poker-hand-analyser new file mode 120000 index 0000000000..0d36d9a0f9 --- /dev/null +++ b/Lang/EasyLang/Poker-hand-analyser @@ -0,0 +1 @@ +../../Task/Poker-hand-analyser/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Polynomial-long-division b/Lang/EasyLang/Polynomial-long-division new file mode 120000 index 0000000000..b22845819d --- /dev/null +++ b/Lang/EasyLang/Polynomial-long-division @@ -0,0 +1 @@ +../../Task/Polynomial-long-division/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Prime-numbers-whose-neighboring-pairs-are-tetraprimes b/Lang/EasyLang/Prime-numbers-whose-neighboring-pairs-are-tetraprimes new file mode 120000 index 0000000000..deadbe682f --- /dev/null +++ b/Lang/EasyLang/Prime-numbers-whose-neighboring-pairs-are-tetraprimes @@ -0,0 +1 @@ +../../Task/Prime-numbers-whose-neighboring-pairs-are-tetraprimes/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Prime-triangle b/Lang/EasyLang/Prime-triangle new file mode 120000 index 0000000000..1d703d33b5 --- /dev/null +++ b/Lang/EasyLang/Prime-triangle @@ -0,0 +1 @@ +../../Task/Prime-triangle/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Primes---allocate-descendants-to-their-ancestors b/Lang/EasyLang/Primes---allocate-descendants-to-their-ancestors new file mode 120000 index 0000000000..c5cfa0147b --- /dev/null +++ b/Lang/EasyLang/Primes---allocate-descendants-to-their-ancestors @@ -0,0 +1 @@ +../../Task/Primes---allocate-descendants-to-their-ancestors/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Primorial-numbers b/Lang/EasyLang/Primorial-numbers new file mode 120000 index 0000000000..d0a4900284 --- /dev/null +++ b/Lang/EasyLang/Primorial-numbers @@ -0,0 +1 @@ +../../Task/Primorial-numbers/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Pseudo-random-numbers-Combined-recursive-generator-MRG32k3a b/Lang/EasyLang/Pseudo-random-numbers-Combined-recursive-generator-MRG32k3a new file mode 120000 index 0000000000..4f4d220e94 --- /dev/null +++ b/Lang/EasyLang/Pseudo-random-numbers-Combined-recursive-generator-MRG32k3a @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-Combined-recursive-generator-MRG32k3a/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Pythagorean-quadruples b/Lang/EasyLang/Pythagorean-quadruples new file mode 120000 index 0000000000..63bc250851 --- /dev/null +++ b/Lang/EasyLang/Pythagorean-quadruples @@ -0,0 +1 @@ +../../Task/Pythagorean-quadruples/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Quaternion-type b/Lang/EasyLang/Quaternion-type deleted file mode 120000 index fd590dabb6..0000000000 --- a/Lang/EasyLang/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Quoting-constructs b/Lang/EasyLang/Quoting-constructs new file mode 120000 index 0000000000..4d929963d4 --- /dev/null +++ b/Lang/EasyLang/Quoting-constructs @@ -0,0 +1 @@ +../../Task/Quoting-constructs/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/RIPEMD-160 b/Lang/EasyLang/RIPEMD-160 new file mode 120000 index 0000000000..c7b5193d17 --- /dev/null +++ b/Lang/EasyLang/RIPEMD-160 @@ -0,0 +1 @@ +../../Task/RIPEMD-160/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/RSA-code b/Lang/EasyLang/RSA-code new file mode 120000 index 0000000000..ab0c3fd0ae --- /dev/null +++ b/Lang/EasyLang/RSA-code @@ -0,0 +1 @@ +../../Task/RSA-code/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Range-consolidation b/Lang/EasyLang/Range-consolidation new file mode 120000 index 0000000000..2af9d87ce4 --- /dev/null +++ b/Lang/EasyLang/Range-consolidation @@ -0,0 +1 @@ +../../Task/Range-consolidation/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Range-expansion b/Lang/EasyLang/Range-expansion new file mode 120000 index 0000000000..b1e04fdc47 --- /dev/null +++ b/Lang/EasyLang/Range-expansion @@ -0,0 +1 @@ +../../Task/Range-expansion/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Ranking-methods b/Lang/EasyLang/Ranking-methods new file mode 120000 index 0000000000..7f1b7f2c09 --- /dev/null +++ b/Lang/EasyLang/Ranking-methods @@ -0,0 +1 @@ +../../Task/Ranking-methods/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Read-a-specific-line-from-a-file b/Lang/EasyLang/Read-a-specific-line-from-a-file new file mode 120000 index 0000000000..d7d3ddb462 --- /dev/null +++ b/Lang/EasyLang/Read-a-specific-line-from-a-file @@ -0,0 +1 @@ +../../Task/Read-a-specific-line-from-a-file/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Resistor-mesh b/Lang/EasyLang/Resistor-mesh new file mode 120000 index 0000000000..7e1b48a0ca --- /dev/null +++ b/Lang/EasyLang/Resistor-mesh @@ -0,0 +1 @@ +../../Task/Resistor-mesh/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Rhonda-numbers b/Lang/EasyLang/Rhonda-numbers new file mode 120000 index 0000000000..5ec2f03aee --- /dev/null +++ b/Lang/EasyLang/Rhonda-numbers @@ -0,0 +1 @@ +../../Task/Rhonda-numbers/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Rock-paper-scissors b/Lang/EasyLang/Rock-paper-scissors new file mode 120000 index 0000000000..f5bc56ac98 --- /dev/null +++ b/Lang/EasyLang/Rock-paper-scissors @@ -0,0 +1 @@ +../../Task/Rock-paper-scissors/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Ruth-Aaron-numbers b/Lang/EasyLang/Ruth-Aaron-numbers new file mode 120000 index 0000000000..8c50b35963 --- /dev/null +++ b/Lang/EasyLang/Ruth-Aaron-numbers @@ -0,0 +1 @@ +../../Task/Ruth-Aaron-numbers/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/SHA-1 b/Lang/EasyLang/SHA-1 new file mode 120000 index 0000000000..85ee6bdeff --- /dev/null +++ b/Lang/EasyLang/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/SHA-256 b/Lang/EasyLang/SHA-256 new file mode 120000 index 0000000000..90c60df38f --- /dev/null +++ b/Lang/EasyLang/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Sailors-coconuts-and-a-monkey-problem b/Lang/EasyLang/Sailors-coconuts-and-a-monkey-problem new file mode 120000 index 0000000000..13c2416787 --- /dev/null +++ b/Lang/EasyLang/Sailors-coconuts-and-a-monkey-problem @@ -0,0 +1 @@ +../../Task/Sailors-coconuts-and-a-monkey-problem/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Scope-Function-names-and-labels b/Lang/EasyLang/Scope-Function-names-and-labels new file mode 120000 index 0000000000..159b6679bd --- /dev/null +++ b/Lang/EasyLang/Scope-Function-names-and-labels @@ -0,0 +1 @@ +../../Task/Scope-Function-names-and-labels/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Selectively-replace-multiple-instances-of-a-character-within-a-string b/Lang/EasyLang/Selectively-replace-multiple-instances-of-a-character-within-a-string new file mode 120000 index 0000000000..c9738f521a --- /dev/null +++ b/Lang/EasyLang/Selectively-replace-multiple-instances-of-a-character-within-a-string @@ -0,0 +1 @@ +../../Task/Selectively-replace-multiple-instances-of-a-character-within-a-string/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Self-numbers b/Lang/EasyLang/Self-numbers new file mode 120000 index 0000000000..219b2abf44 --- /dev/null +++ b/Lang/EasyLang/Self-numbers @@ -0,0 +1 @@ +../../Task/Self-numbers/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Semordnilap b/Lang/EasyLang/Semordnilap new file mode 120000 index 0000000000..54e7d67bd7 --- /dev/null +++ b/Lang/EasyLang/Semordnilap @@ -0,0 +1 @@ +../../Task/Semordnilap/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Show-the-epoch b/Lang/EasyLang/Show-the-epoch new file mode 120000 index 0000000000..67a6b1a9c5 --- /dev/null +++ b/Lang/EasyLang/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Sierpinski-triangle b/Lang/EasyLang/Sierpinski-triangle new file mode 120000 index 0000000000..36520550cb --- /dev/null +++ b/Lang/EasyLang/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Solve-a-Hidato-puzzle b/Lang/EasyLang/Solve-a-Hidato-puzzle new file mode 120000 index 0000000000..91cd1509fe --- /dev/null +++ b/Lang/EasyLang/Solve-a-Hidato-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hidato-puzzle/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Solve-a-Holy-Knights-tour b/Lang/EasyLang/Solve-a-Holy-Knights-tour new file mode 120000 index 0000000000..0807789002 --- /dev/null +++ b/Lang/EasyLang/Solve-a-Holy-Knights-tour @@ -0,0 +1 @@ +../../Task/Solve-a-Holy-Knights-tour/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Solve-a-Hopido-puzzle b/Lang/EasyLang/Solve-a-Hopido-puzzle new file mode 120000 index 0000000000..f1ae260677 --- /dev/null +++ b/Lang/EasyLang/Solve-a-Hopido-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hopido-puzzle/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Solve-a-Numbrix-puzzle b/Lang/EasyLang/Solve-a-Numbrix-puzzle new file mode 120000 index 0000000000..9dc56df255 --- /dev/null +++ b/Lang/EasyLang/Solve-a-Numbrix-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Numbrix-puzzle/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Solve-the-no-connection-puzzle b/Lang/EasyLang/Solve-the-no-connection-puzzle new file mode 120000 index 0000000000..759be373e6 --- /dev/null +++ b/Lang/EasyLang/Solve-the-no-connection-puzzle @@ -0,0 +1 @@ +../../Task/Solve-the-no-connection-puzzle/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Sort-a-list-of-object-identifiers b/Lang/EasyLang/Sort-a-list-of-object-identifiers new file mode 120000 index 0000000000..6767e4212b --- /dev/null +++ b/Lang/EasyLang/Sort-a-list-of-object-identifiers @@ -0,0 +1 @@ +../../Task/Sort-a-list-of-object-identifiers/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Sort-an-integer-array b/Lang/EasyLang/Sort-an-integer-array new file mode 120000 index 0000000000..b6e22e35fd --- /dev/null +++ b/Lang/EasyLang/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Sort-an-outline-at-every-level b/Lang/EasyLang/Sort-an-outline-at-every-level new file mode 120000 index 0000000000..aa549fd59a --- /dev/null +++ b/Lang/EasyLang/Sort-an-outline-at-every-level @@ -0,0 +1 @@ +../../Task/Sort-an-outline-at-every-level/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Sort-numbers-lexicographically b/Lang/EasyLang/Sort-numbers-lexicographically new file mode 120000 index 0000000000..096e63b030 --- /dev/null +++ b/Lang/EasyLang/Sort-numbers-lexicographically @@ -0,0 +1 @@ +../../Task/Sort-numbers-lexicographically/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Sorting-algorithms-Bead-sort b/Lang/EasyLang/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..a450a04067 --- /dev/null +++ b/Lang/EasyLang/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Sorting-algorithms-Cocktail-sort b/Lang/EasyLang/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..6ea90a8bea --- /dev/null +++ b/Lang/EasyLang/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Sorting-algorithms-Cocktail-sort-with-shifting-bounds b/Lang/EasyLang/Sorting-algorithms-Cocktail-sort-with-shifting-bounds new file mode 120000 index 0000000000..885e9fc6f4 --- /dev/null +++ b/Lang/EasyLang/Sorting-algorithms-Cocktail-sort-with-shifting-bounds @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort-with-shifting-bounds/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Sorting-algorithms-Comb-sort b/Lang/EasyLang/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..105d051508 --- /dev/null +++ b/Lang/EasyLang/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Sorting-algorithms-Pancake-sort b/Lang/EasyLang/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..7f8da5bd54 --- /dev/null +++ b/Lang/EasyLang/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Sorting-algorithms-Patience-sort b/Lang/EasyLang/Sorting-algorithms-Patience-sort new file mode 120000 index 0000000000..6123828d8e --- /dev/null +++ b/Lang/EasyLang/Sorting-algorithms-Patience-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Patience-sort/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Sorting-algorithms-Permutation-sort b/Lang/EasyLang/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..858ffd0315 --- /dev/null +++ b/Lang/EasyLang/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Sorting-algorithms-Shell-sort b/Lang/EasyLang/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..f5b30c5803 --- /dev/null +++ b/Lang/EasyLang/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Sorting-algorithms-Strand-sort b/Lang/EasyLang/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..005353ca66 --- /dev/null +++ b/Lang/EasyLang/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Sparkline-in-unicode b/Lang/EasyLang/Sparkline-in-unicode new file mode 120000 index 0000000000..7ec2356a98 --- /dev/null +++ b/Lang/EasyLang/Sparkline-in-unicode @@ -0,0 +1 @@ +../../Task/Sparkline-in-unicode/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Spelling-of-ordinal-numbers b/Lang/EasyLang/Spelling-of-ordinal-numbers new file mode 120000 index 0000000000..657348f1ae --- /dev/null +++ b/Lang/EasyLang/Spelling-of-ordinal-numbers @@ -0,0 +1 @@ +../../Task/Spelling-of-ordinal-numbers/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Sphenic-numbers b/Lang/EasyLang/Sphenic-numbers new file mode 120000 index 0000000000..376288b88d --- /dev/null +++ b/Lang/EasyLang/Sphenic-numbers @@ -0,0 +1 @@ +../../Task/Sphenic-numbers/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Square-free-integers b/Lang/EasyLang/Square-free-integers new file mode 120000 index 0000000000..07046cee4c --- /dev/null +++ b/Lang/EasyLang/Square-free-integers @@ -0,0 +1 @@ +../../Task/Square-free-integers/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Stable-marriage-problem b/Lang/EasyLang/Stable-marriage-problem new file mode 120000 index 0000000000..5a03ad65b0 --- /dev/null +++ b/Lang/EasyLang/Stable-marriage-problem @@ -0,0 +1 @@ +../../Task/Stable-marriage-problem/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Stair-climbing-puzzle b/Lang/EasyLang/Stair-climbing-puzzle new file mode 120000 index 0000000000..e0c07f706d --- /dev/null +++ b/Lang/EasyLang/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Statistics-Normal-distribution b/Lang/EasyLang/Statistics-Normal-distribution new file mode 120000 index 0000000000..cfeed445c6 --- /dev/null +++ b/Lang/EasyLang/Statistics-Normal-distribution @@ -0,0 +1 @@ +../../Task/Statistics-Normal-distribution/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Stem-and-leaf-plot b/Lang/EasyLang/Stem-and-leaf-plot new file mode 120000 index 0000000000..cf4dace06c --- /dev/null +++ b/Lang/EasyLang/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Straddling-checkerboard b/Lang/EasyLang/Straddling-checkerboard new file mode 120000 index 0000000000..df23fad6e0 --- /dev/null +++ b/Lang/EasyLang/Straddling-checkerboard @@ -0,0 +1 @@ +../../Task/Straddling-checkerboard/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Suffixation-of-decimal-numbers b/Lang/EasyLang/Suffixation-of-decimal-numbers new file mode 120000 index 0000000000..2c99b570e5 --- /dev/null +++ b/Lang/EasyLang/Suffixation-of-decimal-numbers @@ -0,0 +1 @@ +../../Task/Suffixation-of-decimal-numbers/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Sum-and-product-puzzle b/Lang/EasyLang/Sum-and-product-puzzle new file mode 120000 index 0000000000..8dd4cbcafb --- /dev/null +++ b/Lang/EasyLang/Sum-and-product-puzzle @@ -0,0 +1 @@ +../../Task/Sum-and-product-puzzle/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Super-d-numbers b/Lang/EasyLang/Super-d-numbers new file mode 120000 index 0000000000..c760610b85 --- /dev/null +++ b/Lang/EasyLang/Super-d-numbers @@ -0,0 +1 @@ +../../Task/Super-d-numbers/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Superpermutation-minimisation b/Lang/EasyLang/Superpermutation-minimisation new file mode 120000 index 0000000000..6607fe41d8 --- /dev/null +++ b/Lang/EasyLang/Superpermutation-minimisation @@ -0,0 +1 @@ +../../Task/Superpermutation-minimisation/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Sutherland-Hodgman-polygon-clipping b/Lang/EasyLang/Sutherland-Hodgman-polygon-clipping new file mode 120000 index 0000000000..948deb6c32 --- /dev/null +++ b/Lang/EasyLang/Sutherland-Hodgman-polygon-clipping @@ -0,0 +1 @@ +../../Task/Sutherland-Hodgman-polygon-clipping/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Taxicab-numbers b/Lang/EasyLang/Taxicab-numbers new file mode 120000 index 0000000000..7035ad16c4 --- /dev/null +++ b/Lang/EasyLang/Taxicab-numbers @@ -0,0 +1 @@ +../../Task/Taxicab-numbers/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Teacup-rim-text b/Lang/EasyLang/Teacup-rim-text new file mode 120000 index 0000000000..6602971306 --- /dev/null +++ b/Lang/EasyLang/Teacup-rim-text @@ -0,0 +1 @@ +../../Task/Teacup-rim-text/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Tokenize-a-string-with-escaping b/Lang/EasyLang/Tokenize-a-string-with-escaping new file mode 120000 index 0000000000..1059b903ad --- /dev/null +++ b/Lang/EasyLang/Tokenize-a-string-with-escaping @@ -0,0 +1 @@ +../../Task/Tokenize-a-string-with-escaping/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Top-rank-per-group b/Lang/EasyLang/Top-rank-per-group new file mode 120000 index 0000000000..861db59645 --- /dev/null +++ b/Lang/EasyLang/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Topological-sort b/Lang/EasyLang/Topological-sort new file mode 120000 index 0000000000..8100dde197 --- /dev/null +++ b/Lang/EasyLang/Topological-sort @@ -0,0 +1 @@ +../../Task/Topological-sort/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Topswops b/Lang/EasyLang/Topswops new file mode 120000 index 0000000000..2080f48b84 --- /dev/null +++ b/Lang/EasyLang/Topswops @@ -0,0 +1 @@ +../../Task/Topswops/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Truth-table b/Lang/EasyLang/Truth-table new file mode 120000 index 0000000000..73d0946392 --- /dev/null +++ b/Lang/EasyLang/Truth-table @@ -0,0 +1 @@ +../../Task/Truth-table/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/UPC b/Lang/EasyLang/UPC new file mode 120000 index 0000000000..2bb2969064 --- /dev/null +++ b/Lang/EasyLang/UPC @@ -0,0 +1 @@ +../../Task/UPC/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/URL-decoding b/Lang/EasyLang/URL-decoding new file mode 120000 index 0000000000..a070edc78b --- /dev/null +++ b/Lang/EasyLang/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/URL-encoding b/Lang/EasyLang/URL-encoding new file mode 120000 index 0000000000..c0b065b1e5 --- /dev/null +++ b/Lang/EasyLang/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/UTF-8-encode-and-decode b/Lang/EasyLang/UTF-8-encode-and-decode new file mode 120000 index 0000000000..c4de9115dc --- /dev/null +++ b/Lang/EasyLang/UTF-8-encode-and-decode @@ -0,0 +1 @@ +../../Task/UTF-8-encode-and-decode/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Unicode-strings b/Lang/EasyLang/Unicode-strings new file mode 120000 index 0000000000..c52bd4da5c --- /dev/null +++ b/Lang/EasyLang/Unicode-strings @@ -0,0 +1 @@ +../../Task/Unicode-strings/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Universal-Turing-machine b/Lang/EasyLang/Universal-Turing-machine new file mode 120000 index 0000000000..c6c36c7e83 --- /dev/null +++ b/Lang/EasyLang/Universal-Turing-machine @@ -0,0 +1 @@ +../../Task/Universal-Turing-machine/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Unprimeable-numbers b/Lang/EasyLang/Unprimeable-numbers new file mode 120000 index 0000000000..ae808307c7 --- /dev/null +++ b/Lang/EasyLang/Unprimeable-numbers @@ -0,0 +1 @@ +../../Task/Unprimeable-numbers/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Verhoeff-algorithm b/Lang/EasyLang/Verhoeff-algorithm new file mode 120000 index 0000000000..31c375b7e9 --- /dev/null +++ b/Lang/EasyLang/Verhoeff-algorithm @@ -0,0 +1 @@ +../../Task/Verhoeff-algorithm/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Verify-distribution-uniformity-Naive b/Lang/EasyLang/Verify-distribution-uniformity-Naive new file mode 120000 index 0000000000..bc6d548e1b --- /dev/null +++ b/Lang/EasyLang/Verify-distribution-uniformity-Naive @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Naive/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Vigen-re-cipher-Cryptanalysis b/Lang/EasyLang/Vigen-re-cipher-Cryptanalysis new file mode 120000 index 0000000000..019adf3986 --- /dev/null +++ b/Lang/EasyLang/Vigen-re-cipher-Cryptanalysis @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher-Cryptanalysis/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Vogels-approximation-method b/Lang/EasyLang/Vogels-approximation-method new file mode 120000 index 0000000000..576b7c1373 --- /dev/null +++ b/Lang/EasyLang/Vogels-approximation-method @@ -0,0 +1 @@ +../../Task/Vogels-approximation-method/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/War-card-game b/Lang/EasyLang/War-card-game new file mode 120000 index 0000000000..4889819208 --- /dev/null +++ b/Lang/EasyLang/War-card-game @@ -0,0 +1 @@ +../../Task/War-card-game/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Wasteful-equidigital-and-frugal-numbers b/Lang/EasyLang/Wasteful-equidigital-and-frugal-numbers new file mode 120000 index 0000000000..2c61d301f5 --- /dev/null +++ b/Lang/EasyLang/Wasteful-equidigital-and-frugal-numbers @@ -0,0 +1 @@ +../../Task/Wasteful-equidigital-and-frugal-numbers/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Weird-numbers b/Lang/EasyLang/Weird-numbers new file mode 120000 index 0000000000..503b16eabc --- /dev/null +++ b/Lang/EasyLang/Weird-numbers @@ -0,0 +1 @@ +../../Task/Weird-numbers/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Word-ladder b/Lang/EasyLang/Word-ladder new file mode 120000 index 0000000000..c40a883a5f --- /dev/null +++ b/Lang/EasyLang/Word-ladder @@ -0,0 +1 @@ +../../Task/Word-ladder/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Word-wheel b/Lang/EasyLang/Word-wheel new file mode 120000 index 0000000000..cc8df0aac8 --- /dev/null +++ b/Lang/EasyLang/Word-wheel @@ -0,0 +1 @@ +../../Task/Word-wheel/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/World-Cup-group-stage b/Lang/EasyLang/World-Cup-group-stage new file mode 120000 index 0000000000..903f2de54b --- /dev/null +++ b/Lang/EasyLang/World-Cup-group-stage @@ -0,0 +1 @@ +../../Task/World-Cup-group-stage/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Xiaolin-Wus-line-algorithm b/Lang/EasyLang/Xiaolin-Wus-line-algorithm new file mode 120000 index 0000000000..ece28f1e59 --- /dev/null +++ b/Lang/EasyLang/Xiaolin-Wus-line-algorithm @@ -0,0 +1 @@ +../../Task/Xiaolin-Wus-line-algorithm/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Zhang-Suen-thinning-algorithm b/Lang/EasyLang/Zhang-Suen-thinning-algorithm new file mode 120000 index 0000000000..06bef59d73 --- /dev/null +++ b/Lang/EasyLang/Zhang-Suen-thinning-algorithm @@ -0,0 +1 @@ +../../Task/Zhang-Suen-thinning-algorithm/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Zig-zag-matrix b/Lang/EasyLang/Zig-zag-matrix new file mode 120000 index 0000000000..59c91477d5 --- /dev/null +++ b/Lang/EasyLang/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/EasyLang \ No newline at end of file diff --git a/Lang/EchoLisp/Miller-Rabin-primality-test b/Lang/EchoLisp/Miller-Rabin-primality-test deleted file mode 120000 index a1456f561f..0000000000 --- a/Lang/EchoLisp/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/EchoLisp \ No newline at end of file diff --git a/Lang/Ecstasy/00-LANG.txt b/Lang/Ecstasy/00-LANG.txt index 7358e7f1ea..9c977a310d 100644 --- a/Lang/Ecstasy/00-LANG.txt +++ b/Lang/Ecstasy/00-LANG.txt @@ -25,4 +25,7 @@ The primary benefits of Ecstasy are: * A security model designed for the serverless cloud, using lightweight software containers and dependency injection (IOC/DI) * A reified generic type system with support for unions, intersection, and difference types, first-class tuples and functions, type inference, and type-safe mixins * Built-in concurrency support, with first-class support for object immutability, and the elimination of shared-mutable data -* All of the modern capabilities that developers have grown to depend on, such as: [[garbage collection|Automatic memory management]], an integrated module system, first-class lambdas and functions, partial binding and currying, cross-platform portability, and an open source development model \ No newline at end of file +* All of the modern capabilities that developers have grown to depend on, such as: [[garbage collection|Automatic memory management]], an integrated module system, first-class lambdas and functions, partial binding and currying, cross-platform portability, and an open source development model + +==TODO== +* [[Tasks not implemented in Ecstasy]] \ No newline at end of file diff --git a/Lang/Ecstasy/100-prisoners b/Lang/Ecstasy/100-prisoners new file mode 120000 index 0000000000..e9fb2d2f70 --- /dev/null +++ b/Lang/Ecstasy/100-prisoners @@ -0,0 +1 @@ +../../Task/100-prisoners/Ecstasy \ No newline at end of file diff --git a/Lang/Ecstasy/Assertions b/Lang/Ecstasy/Assertions new file mode 120000 index 0000000000..0802d10c0c --- /dev/null +++ b/Lang/Ecstasy/Assertions @@ -0,0 +1 @@ +../../Task/Assertions/Ecstasy \ No newline at end of file diff --git a/Lang/Ecstasy/Pointers-and-references b/Lang/Ecstasy/Pointers-and-references new file mode 120000 index 0000000000..9b85919b2d --- /dev/null +++ b/Lang/Ecstasy/Pointers-and-references @@ -0,0 +1 @@ +../../Task/Pointers-and-references/Ecstasy \ No newline at end of file diff --git a/Lang/Ecstasy/Program-name b/Lang/Ecstasy/Program-name new file mode 120000 index 0000000000..6411623f47 --- /dev/null +++ b/Lang/Ecstasy/Program-name @@ -0,0 +1 @@ +../../Task/Program-name/Ecstasy \ No newline at end of file diff --git a/Lang/Ecstasy/Reflection-List-methods b/Lang/Ecstasy/Reflection-List-methods new file mode 120000 index 0000000000..f4010fce77 --- /dev/null +++ b/Lang/Ecstasy/Reflection-List-methods @@ -0,0 +1 @@ +../../Task/Reflection-List-methods/Ecstasy \ No newline at end of file diff --git a/Lang/Ecstasy/Reflection-List-properties b/Lang/Ecstasy/Reflection-List-properties new file mode 120000 index 0000000000..40ec86fd95 --- /dev/null +++ b/Lang/Ecstasy/Reflection-List-properties @@ -0,0 +1 @@ +../../Task/Reflection-List-properties/Ecstasy \ No newline at end of file diff --git a/Lang/Ecstasy/Search-a-list b/Lang/Ecstasy/Search-a-list new file mode 120000 index 0000000000..f6044e825c --- /dev/null +++ b/Lang/Ecstasy/Search-a-list @@ -0,0 +1 @@ +../../Task/Search-a-list/Ecstasy \ No newline at end of file diff --git a/Lang/Ecstasy/Send-an-unknown-method-call b/Lang/Ecstasy/Send-an-unknown-method-call new file mode 120000 index 0000000000..5d1a4cbed5 --- /dev/null +++ b/Lang/Ecstasy/Send-an-unknown-method-call @@ -0,0 +1 @@ +../../Task/Send-an-unknown-method-call/Ecstasy \ No newline at end of file diff --git a/Lang/Ecstasy/Singleton b/Lang/Ecstasy/Singleton new file mode 120000 index 0000000000..8c9a0eb1b2 --- /dev/null +++ b/Lang/Ecstasy/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/Ecstasy \ No newline at end of file diff --git a/Lang/Ecstasy/String-case b/Lang/Ecstasy/String-case new file mode 120000 index 0000000000..75c8cc65c2 --- /dev/null +++ b/Lang/Ecstasy/String-case @@ -0,0 +1 @@ +../../Task/String-case/Ecstasy \ No newline at end of file diff --git a/Lang/Ecstasy/String-comparison b/Lang/Ecstasy/String-comparison new file mode 120000 index 0000000000..2a690e7c01 --- /dev/null +++ b/Lang/Ecstasy/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/Ecstasy \ No newline at end of file diff --git a/Lang/Ecstasy/String-concatenation b/Lang/Ecstasy/String-concatenation new file mode 120000 index 0000000000..a8fc37bb41 --- /dev/null +++ b/Lang/Ecstasy/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Ecstasy \ No newline at end of file diff --git a/Lang/Ecstasy/String-length b/Lang/Ecstasy/String-length new file mode 120000 index 0000000000..e3f6d6a12a --- /dev/null +++ b/Lang/Ecstasy/String-length @@ -0,0 +1 @@ +../../Task/String-length/Ecstasy \ No newline at end of file diff --git a/Lang/Ecstasy/Substring b/Lang/Ecstasy/Substring new file mode 120000 index 0000000000..59160f9d22 --- /dev/null +++ b/Lang/Ecstasy/Substring @@ -0,0 +1 @@ +../../Task/Substring/Ecstasy \ No newline at end of file diff --git a/Lang/Ecstasy/Substring-Top-and-tail b/Lang/Ecstasy/Substring-Top-and-tail new file mode 120000 index 0000000000..cf035aa347 --- /dev/null +++ b/Lang/Ecstasy/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Ecstasy \ No newline at end of file diff --git a/Lang/Ecstasy/System-time b/Lang/Ecstasy/System-time new file mode 120000 index 0000000000..4b0a593cce --- /dev/null +++ b/Lang/Ecstasy/System-time @@ -0,0 +1 @@ +../../Task/System-time/Ecstasy \ No newline at end of file diff --git a/Lang/Ed/00-LANG.txt b/Lang/Ed/00-LANG.txt new file mode 100644 index 0000000000..0ffa56bf3c --- /dev/null +++ b/Lang/Ed/00-LANG.txt @@ -0,0 +1,27 @@ +{{stub}} +{{language|Ed}} +This is the command language used by [[wp:ed_(software)]], +the line oriented text editor, not to be confused with [[Sed]], the stream editor. + +Implementations are [[GNU Ed]], [[Plan 9 Ed]], BSD ed, and original UNIX ed. +Ed is also a precursor to a whole family of other text editors and command languages. +Including [[Sed]], ex, vi, vim, sam, and others. + +Ed scripts are usually ran as (on the example of [[GNU Ed]]) + +cat script.ed | ed -lEGs file.in + + +Or, more portably, with Basic Regular Expressions on BSD, Mac, and [[GNU Ed]]. + +cat script.ed | ed -s file.in + + +There's a convention of starting every ed script with capital H on a line of its own, to toggle more verbose error messages on. And optionally end the script with capital Q to force-quit without saving the changes to file. + +A good reference for Ed is it's info page, which can be found online [https://linux.die.net/man/1/ed here]. + +Also see [[Tasks not implemented in Ed]] + +[[Category:Editor]] +[[Category:Utility]] \ No newline at end of file diff --git a/Lang/Ed/00-META.yaml b/Lang/Ed/00-META.yaml new file mode 100644 index 0000000000..8c668497f3 --- /dev/null +++ b/Lang/Ed/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Ed diff --git a/Lang/Ed/A+B b/Lang/Ed/A+B new file mode 120000 index 0000000000..00ee271a45 --- /dev/null +++ b/Lang/Ed/A+B @@ -0,0 +1 @@ +../../Task/A+B/Ed \ No newline at end of file diff --git a/Lang/Ed/Address-of-a-variable b/Lang/Ed/Address-of-a-variable new file mode 120000 index 0000000000..b7216d9c2d --- /dev/null +++ b/Lang/Ed/Address-of-a-variable @@ -0,0 +1 @@ +../../Task/Address-of-a-variable/Ed \ No newline at end of file diff --git a/Lang/Ed/Append-a-record-to-the-end-of-a-text-file b/Lang/Ed/Append-a-record-to-the-end-of-a-text-file new file mode 120000 index 0000000000..c20f4ffb66 --- /dev/null +++ b/Lang/Ed/Append-a-record-to-the-end-of-a-text-file @@ -0,0 +1 @@ +../../Task/Append-a-record-to-the-end-of-a-text-file/Ed \ No newline at end of file diff --git a/Lang/Ed/Balanced-brackets b/Lang/Ed/Balanced-brackets new file mode 120000 index 0000000000..12f98da078 --- /dev/null +++ b/Lang/Ed/Balanced-brackets @@ -0,0 +1 @@ +../../Task/Balanced-brackets/Ed \ No newline at end of file diff --git a/Lang/Ed/Base64-decode-data b/Lang/Ed/Base64-decode-data new file mode 120000 index 0000000000..d08c0a29a4 --- /dev/null +++ b/Lang/Ed/Base64-decode-data @@ -0,0 +1 @@ +../../Task/Base64-decode-data/Ed \ No newline at end of file diff --git a/Lang/Ed/Binary-digits b/Lang/Ed/Binary-digits new file mode 120000 index 0000000000..3593438a83 --- /dev/null +++ b/Lang/Ed/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/Ed \ No newline at end of file diff --git a/Lang/Ed/Brace-expansion b/Lang/Ed/Brace-expansion new file mode 120000 index 0000000000..57b88b6984 --- /dev/null +++ b/Lang/Ed/Brace-expansion @@ -0,0 +1 @@ +../../Task/Brace-expansion/Ed \ No newline at end of file diff --git a/Lang/Ed/CSV-to-HTML-translation b/Lang/Ed/CSV-to-HTML-translation new file mode 120000 index 0000000000..982d76328a --- /dev/null +++ b/Lang/Ed/CSV-to-HTML-translation @@ -0,0 +1 @@ +../../Task/CSV-to-HTML-translation/Ed \ No newline at end of file diff --git a/Lang/Ed/Camel-case-and-snake-case b/Lang/Ed/Camel-case-and-snake-case new file mode 120000 index 0000000000..34e48e10ce --- /dev/null +++ b/Lang/Ed/Camel-case-and-snake-case @@ -0,0 +1 @@ +../../Task/Camel-case-and-snake-case/Ed \ No newline at end of file diff --git a/Lang/Ed/Check-input-device-is-a-terminal b/Lang/Ed/Check-input-device-is-a-terminal new file mode 120000 index 0000000000..aaa70cb2b9 --- /dev/null +++ b/Lang/Ed/Check-input-device-is-a-terminal @@ -0,0 +1 @@ +../../Task/Check-input-device-is-a-terminal/Ed \ No newline at end of file diff --git a/Lang/Ed/Check-output-device-is-a-terminal b/Lang/Ed/Check-output-device-is-a-terminal new file mode 120000 index 0000000000..7304043875 --- /dev/null +++ b/Lang/Ed/Check-output-device-is-a-terminal @@ -0,0 +1 @@ +../../Task/Check-output-device-is-a-terminal/Ed \ No newline at end of file diff --git a/Lang/Ed/Chinese-zodiac b/Lang/Ed/Chinese-zodiac new file mode 120000 index 0000000000..3a56ea0052 --- /dev/null +++ b/Lang/Ed/Chinese-zodiac @@ -0,0 +1 @@ +../../Task/Chinese-zodiac/Ed \ No newline at end of file diff --git a/Lang/Ed/Cistercian-numerals b/Lang/Ed/Cistercian-numerals new file mode 120000 index 0000000000..f8c9ddde28 --- /dev/null +++ b/Lang/Ed/Cistercian-numerals @@ -0,0 +1 @@ +../../Task/Cistercian-numerals/Ed \ No newline at end of file diff --git a/Lang/Ed/Comma-quibbling b/Lang/Ed/Comma-quibbling new file mode 120000 index 0000000000..d9dc3b3989 --- /dev/null +++ b/Lang/Ed/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Ed \ No newline at end of file diff --git a/Lang/Ed/Comments b/Lang/Ed/Comments new file mode 120000 index 0000000000..08d536496b --- /dev/null +++ b/Lang/Ed/Comments @@ -0,0 +1 @@ +../../Task/Comments/Ed \ No newline at end of file diff --git a/Lang/Ed/Conditional-structures b/Lang/Ed/Conditional-structures new file mode 120000 index 0000000000..46db5ede62 --- /dev/null +++ b/Lang/Ed/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/Ed \ No newline at end of file diff --git a/Lang/Ed/Copy-a-string b/Lang/Ed/Copy-a-string new file mode 120000 index 0000000000..55ec74ae6a --- /dev/null +++ b/Lang/Ed/Copy-a-string @@ -0,0 +1 @@ +../../Task/Copy-a-string/Ed \ No newline at end of file diff --git a/Lang/Ed/Count-occurrences-of-a-substring b/Lang/Ed/Count-occurrences-of-a-substring new file mode 120000 index 0000000000..1c698d3069 --- /dev/null +++ b/Lang/Ed/Count-occurrences-of-a-substring @@ -0,0 +1 @@ +../../Task/Count-occurrences-of-a-substring/Ed \ No newline at end of file diff --git a/Lang/Ed/Create-a-file b/Lang/Ed/Create-a-file new file mode 120000 index 0000000000..11ca37c1ec --- /dev/null +++ b/Lang/Ed/Create-a-file @@ -0,0 +1 @@ +../../Task/Create-a-file/Ed \ No newline at end of file diff --git a/Lang/Ed/Date-format b/Lang/Ed/Date-format new file mode 120000 index 0000000000..972dcea98a --- /dev/null +++ b/Lang/Ed/Date-format @@ -0,0 +1 @@ +../../Task/Date-format/Ed \ No newline at end of file diff --git a/Lang/Ed/Delete-a-file b/Lang/Ed/Delete-a-file new file mode 120000 index 0000000000..f208022c59 --- /dev/null +++ b/Lang/Ed/Delete-a-file @@ -0,0 +1 @@ +../../Task/Delete-a-file/Ed \ No newline at end of file diff --git a/Lang/Ed/Determine-if-a-string-has-all-the-same-characters b/Lang/Ed/Determine-if-a-string-has-all-the-same-characters new file mode 120000 index 0000000000..448ed7ccc8 --- /dev/null +++ b/Lang/Ed/Determine-if-a-string-has-all-the-same-characters @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-has-all-the-same-characters/Ed \ No newline at end of file diff --git a/Lang/Ed/Determine-if-a-string-has-all-unique-characters b/Lang/Ed/Determine-if-a-string-has-all-unique-characters new file mode 120000 index 0000000000..3ce9aedae3 --- /dev/null +++ b/Lang/Ed/Determine-if-a-string-has-all-unique-characters @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-has-all-unique-characters/Ed \ No newline at end of file diff --git a/Lang/Ed/Determine-if-a-string-is-collapsible b/Lang/Ed/Determine-if-a-string-is-collapsible new file mode 120000 index 0000000000..8b2921d3eb --- /dev/null +++ b/Lang/Ed/Determine-if-a-string-is-collapsible @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-collapsible/Ed \ No newline at end of file diff --git a/Lang/Ed/Determine-if-a-string-is-numeric b/Lang/Ed/Determine-if-a-string-is-numeric new file mode 120000 index 0000000000..05c951f131 --- /dev/null +++ b/Lang/Ed/Determine-if-a-string-is-numeric @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-numeric/Ed \ No newline at end of file diff --git a/Lang/Ed/Empty-string b/Lang/Ed/Empty-string new file mode 120000 index 0000000000..d609b5a73a --- /dev/null +++ b/Lang/Ed/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/Ed \ No newline at end of file diff --git a/Lang/Ed/Ethiopian-multiplication b/Lang/Ed/Ethiopian-multiplication new file mode 120000 index 0000000000..a218310c2e --- /dev/null +++ b/Lang/Ed/Ethiopian-multiplication @@ -0,0 +1 @@ +../../Task/Ethiopian-multiplication/Ed \ No newline at end of file diff --git a/Lang/Ed/Even-or-odd b/Lang/Ed/Even-or-odd new file mode 120000 index 0000000000..216cea134c --- /dev/null +++ b/Lang/Ed/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/Ed \ No newline at end of file diff --git a/Lang/Ed/File-input-output b/Lang/Ed/File-input-output new file mode 120000 index 0000000000..ab2356c090 --- /dev/null +++ b/Lang/Ed/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Ed \ No newline at end of file diff --git a/Lang/Ed/Filter b/Lang/Ed/Filter new file mode 120000 index 0000000000..0e10013135 --- /dev/null +++ b/Lang/Ed/Filter @@ -0,0 +1 @@ +../../Task/Filter/Ed \ No newline at end of file diff --git a/Lang/Ed/Find-common-directory-path b/Lang/Ed/Find-common-directory-path new file mode 120000 index 0000000000..31b50e9c25 --- /dev/null +++ b/Lang/Ed/Find-common-directory-path @@ -0,0 +1 @@ +../../Task/Find-common-directory-path/Ed \ No newline at end of file diff --git a/Lang/Ed/FizzBuzz b/Lang/Ed/FizzBuzz new file mode 120000 index 0000000000..5f01963d2b --- /dev/null +++ b/Lang/Ed/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Ed \ No newline at end of file diff --git a/Lang/Ed/Hello-world-Text b/Lang/Ed/Hello-world-Text new file mode 120000 index 0000000000..09329e9578 --- /dev/null +++ b/Lang/Ed/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Ed \ No newline at end of file diff --git a/Lang/Ed/Here-document b/Lang/Ed/Here-document new file mode 120000 index 0000000000..1aca222a29 --- /dev/null +++ b/Lang/Ed/Here-document @@ -0,0 +1 @@ +../../Task/Here-document/Ed \ No newline at end of file diff --git a/Lang/Ed/I-before-E-except-after-C b/Lang/Ed/I-before-E-except-after-C new file mode 120000 index 0000000000..017b410bd0 --- /dev/null +++ b/Lang/Ed/I-before-E-except-after-C @@ -0,0 +1 @@ +../../Task/I-before-E-except-after-C/Ed \ No newline at end of file diff --git a/Lang/Ed/Increment-a-numerical-string b/Lang/Ed/Increment-a-numerical-string new file mode 120000 index 0000000000..e55a87b09f --- /dev/null +++ b/Lang/Ed/Increment-a-numerical-string @@ -0,0 +1 @@ +../../Task/Increment-a-numerical-string/Ed \ No newline at end of file diff --git a/Lang/Ed/Jewels-and-stones b/Lang/Ed/Jewels-and-stones new file mode 120000 index 0000000000..aa6e0865ea --- /dev/null +++ b/Lang/Ed/Jewels-and-stones @@ -0,0 +1 @@ +../../Task/Jewels-and-stones/Ed \ No newline at end of file diff --git a/Lang/Ed/Longest-common-subsequence b/Lang/Ed/Longest-common-subsequence new file mode 120000 index 0000000000..d0e8efbf1e --- /dev/null +++ b/Lang/Ed/Longest-common-subsequence @@ -0,0 +1 @@ +../../Task/Longest-common-subsequence/Ed \ No newline at end of file diff --git a/Lang/Ed/Loops-For b/Lang/Ed/Loops-For new file mode 120000 index 0000000000..3de59c57c2 --- /dev/null +++ b/Lang/Ed/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/Ed \ No newline at end of file diff --git a/Lang/Ed/Loops-Foreach b/Lang/Ed/Loops-Foreach new file mode 120000 index 0000000000..c06f3655df --- /dev/null +++ b/Lang/Ed/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/Ed \ No newline at end of file diff --git a/Lang/Ed/Morse-code b/Lang/Ed/Morse-code new file mode 120000 index 0000000000..e5384e5776 --- /dev/null +++ b/Lang/Ed/Morse-code @@ -0,0 +1 @@ +../../Task/Morse-code/Ed \ No newline at end of file diff --git a/Lang/Ed/Nth b/Lang/Ed/Nth new file mode 120000 index 0000000000..d2f15b3c88 --- /dev/null +++ b/Lang/Ed/Nth @@ -0,0 +1 @@ +../../Task/Nth/Ed \ No newline at end of file diff --git a/Lang/Ed/Palindrome-detection b/Lang/Ed/Palindrome-detection new file mode 120000 index 0000000000..1bec256a92 --- /dev/null +++ b/Lang/Ed/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/Ed \ No newline at end of file diff --git a/Lang/Ed/Phrase-reversals b/Lang/Ed/Phrase-reversals new file mode 120000 index 0000000000..0ee3f41dfa --- /dev/null +++ b/Lang/Ed/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/Ed \ No newline at end of file diff --git a/Lang/Ed/Quine b/Lang/Ed/Quine new file mode 120000 index 0000000000..3690e73126 --- /dev/null +++ b/Lang/Ed/Quine @@ -0,0 +1 @@ +../../Task/Quine/Ed \ No newline at end of file diff --git a/Lang/Ed/Random-number-generator-device- b/Lang/Ed/Random-number-generator-device- new file mode 120000 index 0000000000..ebfa530984 --- /dev/null +++ b/Lang/Ed/Random-number-generator-device- @@ -0,0 +1 @@ +../../Task/Random-number-generator-device-/Ed \ No newline at end of file diff --git a/Lang/Ed/Read-a-specific-line-from-a-file b/Lang/Ed/Read-a-specific-line-from-a-file new file mode 120000 index 0000000000..68b3526a94 --- /dev/null +++ b/Lang/Ed/Read-a-specific-line-from-a-file @@ -0,0 +1 @@ +../../Task/Read-a-specific-line-from-a-file/Ed \ No newline at end of file diff --git a/Lang/Ed/Regular-expressions b/Lang/Ed/Regular-expressions new file mode 120000 index 0000000000..03fa790d32 --- /dev/null +++ b/Lang/Ed/Regular-expressions @@ -0,0 +1 @@ +../../Task/Regular-expressions/Ed \ No newline at end of file diff --git a/Lang/Ed/Rep-string b/Lang/Ed/Rep-string new file mode 120000 index 0000000000..1cabc7547c --- /dev/null +++ b/Lang/Ed/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/Ed \ No newline at end of file diff --git a/Lang/Ed/Repeat-a-string b/Lang/Ed/Repeat-a-string new file mode 120000 index 0000000000..88553bc853 --- /dev/null +++ b/Lang/Ed/Repeat-a-string @@ -0,0 +1 @@ +../../Task/Repeat-a-string/Ed \ No newline at end of file diff --git a/Lang/Ed/Reverse-a-string b/Lang/Ed/Reverse-a-string new file mode 120000 index 0000000000..6104b59dd9 --- /dev/null +++ b/Lang/Ed/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/Ed \ No newline at end of file diff --git a/Lang/Ed/Reverse-words-in-a-string b/Lang/Ed/Reverse-words-in-a-string new file mode 120000 index 0000000000..d59e80e1fb --- /dev/null +++ b/Lang/Ed/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Ed \ No newline at end of file diff --git a/Lang/Ed/Roman-numerals-Decode b/Lang/Ed/Roman-numerals-Decode new file mode 120000 index 0000000000..81a8608ea4 --- /dev/null +++ b/Lang/Ed/Roman-numerals-Decode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Decode/Ed \ No newline at end of file diff --git a/Lang/Ed/Roman-numerals-Encode b/Lang/Ed/Roman-numerals-Encode new file mode 120000 index 0000000000..686206e904 --- /dev/null +++ b/Lang/Ed/Roman-numerals-Encode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Encode/Ed \ No newline at end of file diff --git a/Lang/Ed/Rot-13 b/Lang/Ed/Rot-13 new file mode 120000 index 0000000000..731a496ae9 --- /dev/null +++ b/Lang/Ed/Rot-13 @@ -0,0 +1 @@ +../../Task/Rot-13/Ed \ No newline at end of file diff --git a/Lang/Ed/Run-length-encoding b/Lang/Ed/Run-length-encoding new file mode 120000 index 0000000000..69e6b1b531 --- /dev/null +++ b/Lang/Ed/Run-length-encoding @@ -0,0 +1 @@ +../../Task/Run-length-encoding/Ed \ No newline at end of file diff --git a/Lang/Ed/Selectively-replace-multiple-instances-of-a-character-within-a-string b/Lang/Ed/Selectively-replace-multiple-instances-of-a-character-within-a-string new file mode 120000 index 0000000000..e414614b56 --- /dev/null +++ b/Lang/Ed/Selectively-replace-multiple-instances-of-a-character-within-a-string @@ -0,0 +1 @@ +../../Task/Selectively-replace-multiple-instances-of-a-character-within-a-string/Ed \ No newline at end of file diff --git a/Lang/Ed/Semordnilap b/Lang/Ed/Semordnilap new file mode 120000 index 0000000000..daf7a5ecb1 --- /dev/null +++ b/Lang/Ed/Semordnilap @@ -0,0 +1 @@ +../../Task/Semordnilap/Ed \ No newline at end of file diff --git a/Lang/Ed/Sort-an-integer-array b/Lang/Ed/Sort-an-integer-array new file mode 120000 index 0000000000..b1a2a66ffa --- /dev/null +++ b/Lang/Ed/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Ed \ No newline at end of file diff --git a/Lang/Ed/Split-a-character-string-based-on-change-of-character b/Lang/Ed/Split-a-character-string-based-on-change-of-character new file mode 120000 index 0000000000..0033ba43dd --- /dev/null +++ b/Lang/Ed/Split-a-character-string-based-on-change-of-character @@ -0,0 +1 @@ +../../Task/Split-a-character-string-based-on-change-of-character/Ed \ No newline at end of file diff --git a/Lang/Ed/String-case b/Lang/Ed/String-case new file mode 120000 index 0000000000..daab926f48 --- /dev/null +++ b/Lang/Ed/String-case @@ -0,0 +1 @@ +../../Task/String-case/Ed \ No newline at end of file diff --git a/Lang/Ed/String-comparison b/Lang/Ed/String-comparison new file mode 120000 index 0000000000..d24860c04c --- /dev/null +++ b/Lang/Ed/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/Ed \ No newline at end of file diff --git a/Lang/Ed/String-concatenation b/Lang/Ed/String-concatenation new file mode 120000 index 0000000000..f24bfde76e --- /dev/null +++ b/Lang/Ed/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Ed \ No newline at end of file diff --git a/Lang/Ed/String-interpolation-included- b/Lang/Ed/String-interpolation-included- new file mode 120000 index 0000000000..6b90881c7e --- /dev/null +++ b/Lang/Ed/String-interpolation-included- @@ -0,0 +1 @@ +../../Task/String-interpolation-included-/Ed \ No newline at end of file diff --git a/Lang/Ed/String-length b/Lang/Ed/String-length new file mode 120000 index 0000000000..de41c29ef2 --- /dev/null +++ b/Lang/Ed/String-length @@ -0,0 +1 @@ +../../Task/String-length/Ed \ No newline at end of file diff --git a/Lang/Ed/String-matching b/Lang/Ed/String-matching new file mode 120000 index 0000000000..2895138190 --- /dev/null +++ b/Lang/Ed/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Ed \ No newline at end of file diff --git a/Lang/Ed/String-prepend b/Lang/Ed/String-prepend new file mode 120000 index 0000000000..ce1d9a46f5 --- /dev/null +++ b/Lang/Ed/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/Ed \ No newline at end of file diff --git a/Lang/Ed/Strip-a-set-of-characters-from-a-string b/Lang/Ed/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..6a57ca5210 --- /dev/null +++ b/Lang/Ed/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Ed \ No newline at end of file diff --git a/Lang/Ed/Strip-block-comments b/Lang/Ed/Strip-block-comments new file mode 120000 index 0000000000..913cdfb609 --- /dev/null +++ b/Lang/Ed/Strip-block-comments @@ -0,0 +1 @@ +../../Task/Strip-block-comments/Ed \ No newline at end of file diff --git a/Lang/Ed/Strip-comments-from-a-string b/Lang/Ed/Strip-comments-from-a-string new file mode 120000 index 0000000000..f7c3c178f3 --- /dev/null +++ b/Lang/Ed/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/Ed \ No newline at end of file diff --git a/Lang/Ed/Strip-control-codes-and-extended-characters-from-a-string b/Lang/Ed/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..8cffb60723 --- /dev/null +++ b/Lang/Ed/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/Ed \ No newline at end of file diff --git a/Lang/Ed/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Ed/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..87421d1e38 --- /dev/null +++ b/Lang/Ed/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Ed \ No newline at end of file diff --git a/Lang/Ed/Substring b/Lang/Ed/Substring new file mode 120000 index 0000000000..373a20b8f4 --- /dev/null +++ b/Lang/Ed/Substring @@ -0,0 +1 @@ +../../Task/Substring/Ed \ No newline at end of file diff --git a/Lang/Ed/Substring-Top-and-tail b/Lang/Ed/Substring-Top-and-tail new file mode 120000 index 0000000000..bff998aeb0 --- /dev/null +++ b/Lang/Ed/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Ed \ No newline at end of file diff --git a/Lang/Ed/Tokenize-a-string b/Lang/Ed/Tokenize-a-string new file mode 120000 index 0000000000..d8f4499b3c --- /dev/null +++ b/Lang/Ed/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Ed \ No newline at end of file diff --git a/Lang/Ed/Word-wrap b/Lang/Ed/Word-wrap new file mode 120000 index 0000000000..b86e0349c6 --- /dev/null +++ b/Lang/Ed/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/Ed \ No newline at end of file diff --git a/Lang/Eero/Quaternion-type b/Lang/Eero/Quaternion-type deleted file mode 120000 index 91a82e433f..0000000000 --- a/Lang/Eero/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Eero \ No newline at end of file diff --git a/Lang/Eiffel/Loops-For b/Lang/Eiffel/Loops-For new file mode 120000 index 0000000000..30f93ee824 --- /dev/null +++ b/Lang/Eiffel/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Loops-Infinite b/Lang/Eiffel/Loops-Infinite new file mode 120000 index 0000000000..1016f5af23 --- /dev/null +++ b/Lang/Eiffel/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/Eiffel \ No newline at end of file diff --git a/Lang/Elena/00-LANG.txt b/Lang/Elena/00-LANG.txt index 671257e3ee..c3a21bf2d4 100644 --- a/Lang/Elena/00-LANG.txt +++ b/Lang/Elena/00-LANG.txt @@ -1,5 +1,5 @@ {{language|Elena -|site=http://elenalang.sourceforge.net +|site=https://elena-lang.github.io/ |exec=bytecode |strength=strong |safety=safe diff --git a/Lang/Elena/Comma-quibbling b/Lang/Elena/Comma-quibbling new file mode 120000 index 0000000000..f92aff5654 --- /dev/null +++ b/Lang/Elena/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Elena \ No newline at end of file diff --git a/Lang/Elena/Concurrent-computing b/Lang/Elena/Concurrent-computing new file mode 120000 index 0000000000..d22278e519 --- /dev/null +++ b/Lang/Elena/Concurrent-computing @@ -0,0 +1 @@ +../../Task/Concurrent-computing/Elena \ No newline at end of file diff --git a/Lang/Elena/HTTP b/Lang/Elena/HTTP new file mode 120000 index 0000000000..c94b6f99cd --- /dev/null +++ b/Lang/Elena/HTTP @@ -0,0 +1 @@ +../../Task/HTTP/Elena \ No newline at end of file diff --git a/Lang/Elena/HTTPS b/Lang/Elena/HTTPS new file mode 120000 index 0000000000..879dfcb045 --- /dev/null +++ b/Lang/Elena/HTTPS @@ -0,0 +1 @@ +../../Task/HTTPS/Elena \ No newline at end of file diff --git a/Lang/Elena/Quaternion-type b/Lang/Elena/Quaternion-type deleted file mode 120000 index 1637f784c6..0000000000 --- a/Lang/Elena/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Elena \ No newline at end of file diff --git a/Lang/Elixir/Determinant-and-permanent b/Lang/Elixir/Determinant-and-permanent new file mode 120000 index 0000000000..91e99770a2 --- /dev/null +++ b/Lang/Elixir/Determinant-and-permanent @@ -0,0 +1 @@ +../../Task/Determinant-and-permanent/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Empty-program b/Lang/Elixir/Empty-program deleted file mode 120000 index e1c7956a55..0000000000 --- a/Lang/Elixir/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Elixir \ No newline at end of file diff --git a/Lang/Elixir/K-d-tree b/Lang/Elixir/K-d-tree new file mode 120000 index 0000000000..4a7008abc8 --- /dev/null +++ b/Lang/Elixir/K-d-tree @@ -0,0 +1 @@ +../../Task/K-d-tree/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Miller-Rabin-primality-test b/Lang/Elixir/Miller-Rabin-primality-test deleted file mode 120000 index 911bb7e6dd..0000000000 --- a/Lang/Elixir/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Parallel-brute-force b/Lang/Elixir/Parallel-brute-force new file mode 120000 index 0000000000..154ccc9bb9 --- /dev/null +++ b/Lang/Elixir/Parallel-brute-force @@ -0,0 +1 @@ +../../Task/Parallel-brute-force/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Parse-an-IP-Address b/Lang/Elixir/Parse-an-IP-Address new file mode 120000 index 0000000000..bad8e9a86e --- /dev/null +++ b/Lang/Elixir/Parse-an-IP-Address @@ -0,0 +1 @@ +../../Task/Parse-an-IP-Address/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Sorting-Algorithms-Circle-Sort b/Lang/Elixir/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 97335bafb5..0000000000 --- a/Lang/Elixir/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Strassens-algorithm b/Lang/Elixir/Strassens-algorithm new file mode 120000 index 0000000000..b73f87ff60 --- /dev/null +++ b/Lang/Elixir/Strassens-algorithm @@ -0,0 +1 @@ +../../Task/Strassens-algorithm/Elixir \ No newline at end of file diff --git a/Lang/Elm/Caesar-cipher b/Lang/Elm/Caesar-cipher new file mode 120000 index 0000000000..e2f4604523 --- /dev/null +++ b/Lang/Elm/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/Elm \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Abbreviations-automatic b/Lang/Emacs-Lisp/Abbreviations-automatic new file mode 120000 index 0000000000..917fbde092 --- /dev/null +++ b/Lang/Emacs-Lisp/Abbreviations-automatic @@ -0,0 +1 @@ +../../Task/Abbreviations-automatic/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Align-columns b/Lang/Emacs-Lisp/Align-columns new file mode 120000 index 0000000000..9be61160c6 --- /dev/null +++ b/Lang/Emacs-Lisp/Align-columns @@ -0,0 +1 @@ +../../Task/Align-columns/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Anagrams b/Lang/Emacs-Lisp/Anagrams new file mode 120000 index 0000000000..0bf987f884 --- /dev/null +++ b/Lang/Emacs-Lisp/Anagrams @@ -0,0 +1 @@ +../../Task/Anagrams/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Bulls-and-cows b/Lang/Emacs-Lisp/Bulls-and-cows new file mode 120000 index 0000000000..b0602ecaf2 --- /dev/null +++ b/Lang/Emacs-Lisp/Bulls-and-cows @@ -0,0 +1 @@ +../../Task/Bulls-and-cows/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Color-wheel b/Lang/Emacs-Lisp/Color-wheel new file mode 120000 index 0000000000..90b9cec116 --- /dev/null +++ b/Lang/Emacs-Lisp/Color-wheel @@ -0,0 +1 @@ +../../Task/Color-wheel/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Compare-length-of-two-strings b/Lang/Emacs-Lisp/Compare-length-of-two-strings new file mode 120000 index 0000000000..2aa87a97f8 --- /dev/null +++ b/Lang/Emacs-Lisp/Compare-length-of-two-strings @@ -0,0 +1 @@ +../../Task/Compare-length-of-two-strings/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Date-manipulation b/Lang/Emacs-Lisp/Date-manipulation new file mode 120000 index 0000000000..d88e6a9576 --- /dev/null +++ b/Lang/Emacs-Lisp/Date-manipulation @@ -0,0 +1 @@ +../../Task/Date-manipulation/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Determine-if-a-string-is-numeric b/Lang/Emacs-Lisp/Determine-if-a-string-is-numeric new file mode 120000 index 0000000000..2314291eaa --- /dev/null +++ b/Lang/Emacs-Lisp/Determine-if-a-string-is-numeric @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-numeric/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Determine-sentence-type b/Lang/Emacs-Lisp/Determine-sentence-type new file mode 120000 index 0000000000..633b068253 --- /dev/null +++ b/Lang/Emacs-Lisp/Determine-sentence-type @@ -0,0 +1 @@ +../../Task/Determine-sentence-type/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Find-palindromic-numbers-in-both-binary-and-ternary-bases b/Lang/Emacs-Lisp/Find-palindromic-numbers-in-both-binary-and-ternary-bases new file mode 120000 index 0000000000..d1e4e53b61 --- /dev/null +++ b/Lang/Emacs-Lisp/Find-palindromic-numbers-in-both-binary-and-ternary-bases @@ -0,0 +1 @@ +../../Task/Find-palindromic-numbers-in-both-binary-and-ternary-bases/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Generate-random-chess-position b/Lang/Emacs-Lisp/Generate-random-chess-position new file mode 120000 index 0000000000..7ef4f0bf90 --- /dev/null +++ b/Lang/Emacs-Lisp/Generate-random-chess-position @@ -0,0 +1 @@ +../../Task/Generate-random-chess-position/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Keyboard-input-Flush-the-keyboard-buffer b/Lang/Emacs-Lisp/Keyboard-input-Flush-the-keyboard-buffer new file mode 120000 index 0000000000..db888b4ffd --- /dev/null +++ b/Lang/Emacs-Lisp/Keyboard-input-Flush-the-keyboard-buffer @@ -0,0 +1 @@ +../../Task/Keyboard-input-Flush-the-keyboard-buffer/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Keyboard-input-Keypress-check b/Lang/Emacs-Lisp/Keyboard-input-Keypress-check new file mode 120000 index 0000000000..1bf55a234e --- /dev/null +++ b/Lang/Emacs-Lisp/Keyboard-input-Keypress-check @@ -0,0 +1 @@ +../../Task/Keyboard-input-Keypress-check/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Keyboard-input-Obtain-a-Y-or-N-response b/Lang/Emacs-Lisp/Keyboard-input-Obtain-a-Y-or-N-response new file mode 120000 index 0000000000..d6205cc54b --- /dev/null +++ b/Lang/Emacs-Lisp/Keyboard-input-Obtain-a-Y-or-N-response @@ -0,0 +1 @@ +../../Task/Keyboard-input-Obtain-a-Y-or-N-response/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Ordered-words b/Lang/Emacs-Lisp/Ordered-words new file mode 120000 index 0000000000..444b596fcd --- /dev/null +++ b/Lang/Emacs-Lisp/Ordered-words @@ -0,0 +1 @@ +../../Task/Ordered-words/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Search-a-list b/Lang/Emacs-Lisp/Search-a-list new file mode 120000 index 0000000000..6aef3bcdb0 --- /dev/null +++ b/Lang/Emacs-Lisp/Search-a-list @@ -0,0 +1 @@ +../../Task/Search-a-list/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Snake b/Lang/Emacs-Lisp/Snake new file mode 120000 index 0000000000..b334d7a373 --- /dev/null +++ b/Lang/Emacs-Lisp/Snake @@ -0,0 +1 @@ +../../Task/Snake/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Soundex b/Lang/Emacs-Lisp/Soundex new file mode 120000 index 0000000000..d8aeb9b48e --- /dev/null +++ b/Lang/Emacs-Lisp/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Split-a-character-string-based-on-change-of-character b/Lang/Emacs-Lisp/Split-a-character-string-based-on-change-of-character new file mode 120000 index 0000000000..7bff70bc55 --- /dev/null +++ b/Lang/Emacs-Lisp/Split-a-character-string-based-on-change-of-character @@ -0,0 +1 @@ +../../Task/Split-a-character-string-based-on-change-of-character/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Strip-comments-from-a-string b/Lang/Emacs-Lisp/Strip-comments-from-a-string new file mode 120000 index 0000000000..e8fcd5a3c3 --- /dev/null +++ b/Lang/Emacs-Lisp/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Substitution-cipher b/Lang/Emacs-Lisp/Substitution-cipher new file mode 120000 index 0000000000..93f7ee4d63 --- /dev/null +++ b/Lang/Emacs-Lisp/Substitution-cipher @@ -0,0 +1 @@ +../../Task/Substitution-cipher/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Word-frequency b/Lang/Emacs-Lisp/Word-frequency new file mode 120000 index 0000000000..74fd09e7f4 --- /dev/null +++ b/Lang/Emacs-Lisp/Word-frequency @@ -0,0 +1 @@ +../../Task/Word-frequency/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Erlang/Cheryls-birthday b/Lang/Erlang/Cheryls-birthday new file mode 120000 index 0000000000..2e3c0e28bc --- /dev/null +++ b/Lang/Erlang/Cheryls-birthday @@ -0,0 +1 @@ +../../Task/Cheryls-birthday/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Determinant-and-permanent b/Lang/Erlang/Determinant-and-permanent new file mode 120000 index 0000000000..1dcba08234 --- /dev/null +++ b/Lang/Erlang/Determinant-and-permanent @@ -0,0 +1 @@ +../../Task/Determinant-and-permanent/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Floyd-Warshall-algorithm b/Lang/Erlang/Floyd-Warshall-algorithm new file mode 120000 index 0000000000..ac856e6ffa --- /dev/null +++ b/Lang/Erlang/Floyd-Warshall-algorithm @@ -0,0 +1 @@ +../../Task/Floyd-Warshall-algorithm/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Long-multiplication b/Lang/Erlang/Long-multiplication new file mode 120000 index 0000000000..12ca47c665 --- /dev/null +++ b/Lang/Erlang/Long-multiplication @@ -0,0 +1 @@ +../../Task/Long-multiplication/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Miller-Rabin-primality-test b/Lang/Erlang/Miller-Rabin-primality-test deleted file mode 120000 index 5bdd377694..0000000000 --- a/Lang/Erlang/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Parse-an-IP-Address b/Lang/Erlang/Parse-an-IP-Address new file mode 120000 index 0000000000..3e48d0f0b1 --- /dev/null +++ b/Lang/Erlang/Parse-an-IP-Address @@ -0,0 +1 @@ +../../Task/Parse-an-IP-Address/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Stem-and-leaf-plot b/Lang/Erlang/Stem-and-leaf-plot new file mode 120000 index 0000000000..1763f740f3 --- /dev/null +++ b/Lang/Erlang/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Strassens-algorithm b/Lang/Erlang/Strassens-algorithm new file mode 120000 index 0000000000..62150c659e --- /dev/null +++ b/Lang/Erlang/Strassens-algorithm @@ -0,0 +1 @@ +../../Task/Strassens-algorithm/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Super-d-numbers b/Lang/Erlang/Super-d-numbers new file mode 120000 index 0000000000..de46d8ba65 --- /dev/null +++ b/Lang/Erlang/Super-d-numbers @@ -0,0 +1 @@ +../../Task/Super-d-numbers/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Tonelli-Shanks-algorithm b/Lang/Erlang/Tonelli-Shanks-algorithm new file mode 120000 index 0000000000..5c601a781e --- /dev/null +++ b/Lang/Erlang/Tonelli-Shanks-algorithm @@ -0,0 +1 @@ +../../Task/Tonelli-Shanks-algorithm/Erlang \ No newline at end of file diff --git a/Lang/Euphoria/00-LANG.txt b/Lang/Euphoria/00-LANG.txt index 702dca9e88..9dc38ade08 100644 --- a/Lang/Euphoria/00-LANG.txt +++ b/Lang/Euphoria/00-LANG.txt @@ -18,4 +18,7 @@ Euphoria is a powerful yet simple programming language, developed by Robert Crai ==See also== * [[wp:Euphoria (programming language)|Euphoria on Wikipedia]] * [http://rapideuphoria.com/ RapidEuphoria site] -* [http://openeuphoria.org/ openEuphoria site] \ No newline at end of file +* [http://openeuphoria.org/ openEuphoria site] + +==Todo== +[https://rosettacode.org/wiki/Tasks_not_implemented_in_Euphoria Tasks not implemented in Euphoria] \ No newline at end of file diff --git a/Lang/Euphoria/Calculating-the-value-of-e b/Lang/Euphoria/Calculating-the-value-of-e new file mode 120000 index 0000000000..ae2255b209 --- /dev/null +++ b/Lang/Euphoria/Calculating-the-value-of-e @@ -0,0 +1 @@ +../../Task/Calculating-the-value-of-e/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Combinations b/Lang/Euphoria/Combinations new file mode 120000 index 0000000000..10b7f0283e --- /dev/null +++ b/Lang/Euphoria/Combinations @@ -0,0 +1 @@ +../../Task/Combinations/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Convert-seconds-to-compound-duration b/Lang/Euphoria/Convert-seconds-to-compound-duration new file mode 120000 index 0000000000..91ba9055cf --- /dev/null +++ b/Lang/Euphoria/Convert-seconds-to-compound-duration @@ -0,0 +1 @@ +../../Task/Convert-seconds-to-compound-duration/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Empty-program b/Lang/Euphoria/Empty-program deleted file mode 120000 index 241cd5711b..0000000000 --- a/Lang/Euphoria/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/File-size-distribution b/Lang/Euphoria/File-size-distribution new file mode 120000 index 0000000000..a10a0eb48b --- /dev/null +++ b/Lang/Euphoria/File-size-distribution @@ -0,0 +1 @@ +../../Task/File-size-distribution/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Nth b/Lang/Euphoria/Nth new file mode 120000 index 0000000000..6f87edee5c --- /dev/null +++ b/Lang/Euphoria/Nth @@ -0,0 +1 @@ +../../Task/Nth/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Quaternion-type b/Lang/Euphoria/Quaternion-type deleted file mode 120000 index aedb6b51e1..0000000000 --- a/Lang/Euphoria/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Repeat b/Lang/Euphoria/Repeat new file mode 120000 index 0000000000..750ad0f53c --- /dev/null +++ b/Lang/Euphoria/Repeat @@ -0,0 +1 @@ +../../Task/Repeat/Euphoria \ No newline at end of file diff --git a/Lang/Excel/Arrays b/Lang/Excel/Arrays new file mode 120000 index 0000000000..bad8c856a9 --- /dev/null +++ b/Lang/Excel/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/Excel \ No newline at end of file diff --git a/Lang/Excel/Cholesky-decomposition b/Lang/Excel/Cholesky-decomposition new file mode 120000 index 0000000000..2db67f4a20 --- /dev/null +++ b/Lang/Excel/Cholesky-decomposition @@ -0,0 +1 @@ +../../Task/Cholesky-decomposition/Excel \ No newline at end of file diff --git a/Lang/Excel/Conditional-structures b/Lang/Excel/Conditional-structures new file mode 120000 index 0000000000..f4ffdbd4b9 --- /dev/null +++ b/Lang/Excel/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/Excel \ No newline at end of file diff --git a/Lang/Excel/FizzBuzz b/Lang/Excel/FizzBuzz new file mode 120000 index 0000000000..15df08a856 --- /dev/null +++ b/Lang/Excel/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Excel \ No newline at end of file diff --git a/Lang/Excel/Function-definition b/Lang/Excel/Function-definition new file mode 120000 index 0000000000..e6ecf64bef --- /dev/null +++ b/Lang/Excel/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/Excel \ No newline at end of file diff --git a/Lang/Excel/Jacobi-symbol b/Lang/Excel/Jacobi-symbol new file mode 120000 index 0000000000..85f7061c07 --- /dev/null +++ b/Lang/Excel/Jacobi-symbol @@ -0,0 +1 @@ +../../Task/Jacobi-symbol/Excel \ No newline at end of file diff --git a/Lang/Excel/Loops-For b/Lang/Excel/Loops-For new file mode 120000 index 0000000000..876b47b179 --- /dev/null +++ b/Lang/Excel/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/Excel \ No newline at end of file diff --git a/Lang/Excel/Repeat-a-string b/Lang/Excel/Repeat-a-string new file mode 120000 index 0000000000..2c684073cb --- /dev/null +++ b/Lang/Excel/Repeat-a-string @@ -0,0 +1 @@ +../../Task/Repeat-a-string/Excel \ No newline at end of file diff --git a/Lang/Excel/Reverse-a-string b/Lang/Excel/Reverse-a-string new file mode 120000 index 0000000000..2a3cf97cfe --- /dev/null +++ b/Lang/Excel/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/Excel \ No newline at end of file diff --git a/Lang/Excel/Tokenize-a-string b/Lang/Excel/Tokenize-a-string new file mode 120000 index 0000000000..9d5af3b4b4 --- /dev/null +++ b/Lang/Excel/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Excel \ No newline at end of file diff --git a/Lang/Extended-Color-BASIC/00-LANG.txt b/Lang/Extended-Color-BASIC/00-LANG.txt new file mode 100644 index 0000000000..17efd36e93 --- /dev/null +++ b/Lang/Extended-Color-BASIC/00-LANG.txt @@ -0,0 +1,7 @@ +{{language|Extended Color BASIC}} + +Microsoft Extended Color BASIC the BASIC interpreter for the Tandy Color Computer and the Dragon Data Motorola 6809 processor based machines. + +==See Also== +* [[wp:Extended Color BASIC|Wikipedia: Extended Color BASIC]] +* [[Tasks not Implemented in Extended Color BASIC]] \ No newline at end of file diff --git a/Lang/Extended-Color-BASIC/00-META.yaml b/Lang/Extended-Color-BASIC/00-META.yaml new file mode 100644 index 0000000000..57e9e4028d --- /dev/null +++ b/Lang/Extended-Color-BASIC/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Extended_Color_BASIC diff --git a/Lang/Extended-Color-BASIC/Arrays b/Lang/Extended-Color-BASIC/Arrays new file mode 120000 index 0000000000..2ca9fdf8eb --- /dev/null +++ b/Lang/Extended-Color-BASIC/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/Extended-Color-BASIC \ No newline at end of file diff --git a/Lang/Extended-Color-BASIC/Copy-a-string b/Lang/Extended-Color-BASIC/Copy-a-string new file mode 120000 index 0000000000..7a931a182a --- /dev/null +++ b/Lang/Extended-Color-BASIC/Copy-a-string @@ -0,0 +1 @@ +../../Task/Copy-a-string/Extended-Color-BASIC \ No newline at end of file diff --git a/Lang/Extended-Color-BASIC/Hello-world-Text b/Lang/Extended-Color-BASIC/Hello-world-Text new file mode 120000 index 0000000000..b5cfbf6b90 --- /dev/null +++ b/Lang/Extended-Color-BASIC/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Extended-Color-BASIC \ No newline at end of file diff --git a/Lang/Extended-Color-BASIC/Loops-For b/Lang/Extended-Color-BASIC/Loops-For new file mode 120000 index 0000000000..8719420a7c --- /dev/null +++ b/Lang/Extended-Color-BASIC/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/Extended-Color-BASIC \ No newline at end of file diff --git a/Lang/Extended-Color-BASIC/Quine b/Lang/Extended-Color-BASIC/Quine new file mode 120000 index 0000000000..fb6135d264 --- /dev/null +++ b/Lang/Extended-Color-BASIC/Quine @@ -0,0 +1 @@ +../../Task/Quine/Extended-Color-BASIC \ No newline at end of file diff --git a/Lang/Extended-Color-BASIC/User-input-Text b/Lang/Extended-Color-BASIC/User-input-Text new file mode 120000 index 0000000000..545233f9b1 --- /dev/null +++ b/Lang/Extended-Color-BASIC/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Extended-Color-BASIC \ No newline at end of file diff --git a/Lang/F-Sharp/00-LANG.txt b/Lang/F-Sharp/00-LANG.txt index ba98a5db01..db0c37eee0 100644 --- a/Lang/F-Sharp/00-LANG.txt +++ b/Lang/F-Sharp/00-LANG.txt @@ -9,8 +9,9 @@ It is based on the [[Caml]] language, and resembles it in syntax. F# is included as an 'official' .NET language in [[Visual Studio]] 2010 and later. -==External Links== +==Links== * [http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/default.aspx F# Website at Microsoft] * [http://blogs.msdn.com/dsyme/ Don Syme's F# Weblog] +* [[Tasks_not_implemented_in_F_Sharp]] [[Category:Caml Implementations]] \ No newline at end of file diff --git a/Lang/F-Sharp/Bifid-cipher b/Lang/F-Sharp/Bifid-cipher new file mode 120000 index 0000000000..4ac927ed58 --- /dev/null +++ b/Lang/F-Sharp/Bifid-cipher @@ -0,0 +1 @@ +../../Task/Bifid-cipher/F-Sharp \ No newline at end of file diff --git a/Lang/F-Sharp/Call-an-object-method b/Lang/F-Sharp/Call-an-object-method new file mode 120000 index 0000000000..69c90b1041 --- /dev/null +++ b/Lang/F-Sharp/Call-an-object-method @@ -0,0 +1 @@ +../../Task/Call-an-object-method/F-Sharp \ No newline at end of file diff --git a/Lang/F-Sharp/Define-a-primitive-data-type b/Lang/F-Sharp/Define-a-primitive-data-type new file mode 120000 index 0000000000..ef08834748 --- /dev/null +++ b/Lang/F-Sharp/Define-a-primitive-data-type @@ -0,0 +1 @@ +../../Task/Define-a-primitive-data-type/F-Sharp \ No newline at end of file diff --git a/Lang/F-Sharp/Dice-game-probabilities b/Lang/F-Sharp/Dice-game-probabilities new file mode 120000 index 0000000000..70c873d7d5 --- /dev/null +++ b/Lang/F-Sharp/Dice-game-probabilities @@ -0,0 +1 @@ +../../Task/Dice-game-probabilities/F-Sharp \ No newline at end of file diff --git a/Lang/F-Sharp/I-before-E-except-after-C b/Lang/F-Sharp/I-before-E-except-after-C new file mode 120000 index 0000000000..67d12030f9 --- /dev/null +++ b/Lang/F-Sharp/I-before-E-except-after-C @@ -0,0 +1 @@ +../../Task/I-before-E-except-after-C/F-Sharp \ No newline at end of file diff --git a/Lang/F-Sharp/Long-literals-with-continuations b/Lang/F-Sharp/Long-literals-with-continuations new file mode 120000 index 0000000000..25a8149ce8 --- /dev/null +++ b/Lang/F-Sharp/Long-literals-with-continuations @@ -0,0 +1 @@ +../../Task/Long-literals-with-continuations/F-Sharp \ No newline at end of file diff --git a/Lang/F-Sharp/Long-multiplication b/Lang/F-Sharp/Long-multiplication deleted file mode 120000 index a8ece45d37..0000000000 --- a/Lang/F-Sharp/Long-multiplication +++ /dev/null @@ -1 +0,0 @@ -../../Task/Long-multiplication/F-Sharp \ No newline at end of file diff --git a/Lang/F-Sharp/Long-year b/Lang/F-Sharp/Long-year new file mode 120000 index 0000000000..94b40682e9 --- /dev/null +++ b/Lang/F-Sharp/Long-year @@ -0,0 +1 @@ +../../Task/Long-year/F-Sharp \ No newline at end of file diff --git a/Lang/F-Sharp/Mad-Libs b/Lang/F-Sharp/Mad-Libs new file mode 120000 index 0000000000..69a30ced53 --- /dev/null +++ b/Lang/F-Sharp/Mad-Libs @@ -0,0 +1 @@ +../../Task/Mad-Libs/F-Sharp \ No newline at end of file diff --git a/Lang/F-Sharp/Miller-Rabin-primality-test b/Lang/F-Sharp/Miller-Rabin-primality-test deleted file mode 120000 index 4b1a1d67d8..0000000000 --- a/Lang/F-Sharp/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/F-Sharp \ No newline at end of file diff --git a/Lang/F-Sharp/Multi-dimensional-array b/Lang/F-Sharp/Multi-dimensional-array new file mode 120000 index 0000000000..0d6b1aaed5 --- /dev/null +++ b/Lang/F-Sharp/Multi-dimensional-array @@ -0,0 +1 @@ +../../Task/Multi-dimensional-array/F-Sharp \ No newline at end of file diff --git a/Lang/F-Sharp/Multiplicative-order b/Lang/F-Sharp/Multiplicative-order new file mode 120000 index 0000000000..b2064cc3e0 --- /dev/null +++ b/Lang/F-Sharp/Multiplicative-order @@ -0,0 +1 @@ +../../Task/Multiplicative-order/F-Sharp \ No newline at end of file diff --git a/Lang/F-Sharp/Old-lady-swallowed-a-fly b/Lang/F-Sharp/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..066ed3c32b --- /dev/null +++ b/Lang/F-Sharp/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/F-Sharp \ No newline at end of file diff --git a/Lang/F-Sharp/Probabilistic-choice b/Lang/F-Sharp/Probabilistic-choice new file mode 120000 index 0000000000..b7d2692fe4 --- /dev/null +++ b/Lang/F-Sharp/Probabilistic-choice @@ -0,0 +1 @@ +../../Task/Probabilistic-choice/F-Sharp \ No newline at end of file diff --git a/Lang/F-Sharp/Quaternion-type b/Lang/F-Sharp/Quaternion-type deleted file mode 120000 index 2de1d9f870..0000000000 --- a/Lang/F-Sharp/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/F-Sharp \ No newline at end of file diff --git a/Lang/F-Sharp/Same-fringe b/Lang/F-Sharp/Same-fringe new file mode 120000 index 0000000000..04d84b3c5a --- /dev/null +++ b/Lang/F-Sharp/Same-fringe @@ -0,0 +1 @@ +../../Task/Same-fringe/F-Sharp \ No newline at end of file diff --git a/Lang/F-Sharp/Sockets b/Lang/F-Sharp/Sockets new file mode 120000 index 0000000000..13e34e4285 --- /dev/null +++ b/Lang/F-Sharp/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/F-Sharp \ No newline at end of file diff --git a/Lang/F-Sharp/Sort-a-list-of-object-identifiers b/Lang/F-Sharp/Sort-a-list-of-object-identifiers new file mode 120000 index 0000000000..396fa34539 --- /dev/null +++ b/Lang/F-Sharp/Sort-a-list-of-object-identifiers @@ -0,0 +1 @@ +../../Task/Sort-a-list-of-object-identifiers/F-Sharp \ No newline at end of file diff --git a/Lang/F-Sharp/Sort-numbers-lexicographically b/Lang/F-Sharp/Sort-numbers-lexicographically new file mode 120000 index 0000000000..bcc33d5bb2 --- /dev/null +++ b/Lang/F-Sharp/Sort-numbers-lexicographically @@ -0,0 +1 @@ +../../Task/Sort-numbers-lexicographically/F-Sharp \ No newline at end of file diff --git a/Lang/F-Sharp/Variable-length-quantity b/Lang/F-Sharp/Variable-length-quantity new file mode 120000 index 0000000000..2c43b02869 --- /dev/null +++ b/Lang/F-Sharp/Variable-length-quantity @@ -0,0 +1 @@ +../../Task/Variable-length-quantity/F-Sharp \ No newline at end of file diff --git a/Lang/FALSE/Empty-program b/Lang/FALSE/Empty-program deleted file mode 120000 index 35445789cd..0000000000 --- a/Lang/FALSE/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/FALSE \ No newline at end of file diff --git a/Lang/FALSE/Zeckendorf-number-representation b/Lang/FALSE/Zeckendorf-number-representation new file mode 120000 index 0000000000..fdef231a56 --- /dev/null +++ b/Lang/FALSE/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/FALSE \ No newline at end of file diff --git a/Lang/FOCAL/Combinations b/Lang/FOCAL/Combinations new file mode 120000 index 0000000000..882a5e580d --- /dev/null +++ b/Lang/FOCAL/Combinations @@ -0,0 +1 @@ +../../Task/Combinations/FOCAL \ No newline at end of file diff --git a/Lang/FOCAL/Hunt-the-Wumpus b/Lang/FOCAL/Hunt-the-Wumpus new file mode 120000 index 0000000000..098e817517 --- /dev/null +++ b/Lang/FOCAL/Hunt-the-Wumpus @@ -0,0 +1 @@ +../../Task/Hunt-the-Wumpus/FOCAL \ No newline at end of file diff --git a/Lang/FOCAL/Sierpinski-carpet b/Lang/FOCAL/Sierpinski-carpet new file mode 120000 index 0000000000..986467c5d7 --- /dev/null +++ b/Lang/FOCAL/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/FOCAL \ No newline at end of file diff --git a/Lang/FOCAL/Zeckendorf-number-representation b/Lang/FOCAL/Zeckendorf-number-representation new file mode 120000 index 0000000000..d0cbc5b4d2 --- /dev/null +++ b/Lang/FOCAL/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/FOCAL \ No newline at end of file diff --git a/Lang/Factor/Best-shuffle b/Lang/Factor/Best-shuffle new file mode 120000 index 0000000000..a10c8f5d14 --- /dev/null +++ b/Lang/Factor/Best-shuffle @@ -0,0 +1 @@ +../../Task/Best-shuffle/Factor \ No newline at end of file diff --git a/Lang/Factor/Bioinformatics-base-count b/Lang/Factor/Bioinformatics-base-count deleted file mode 120000 index cf4a54a26f..0000000000 --- a/Lang/Factor/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Factor \ No newline at end of file diff --git a/Lang/Factor/Brownian-tree b/Lang/Factor/Brownian-tree new file mode 120000 index 0000000000..a93650256d --- /dev/null +++ b/Lang/Factor/Brownian-tree @@ -0,0 +1 @@ +../../Task/Brownian-tree/Factor \ No newline at end of file diff --git a/Lang/Factor/Quaternion-type b/Lang/Factor/Quaternion-type deleted file mode 120000 index 47f0548ea8..0000000000 --- a/Lang/Factor/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Factor \ No newline at end of file diff --git a/Lang/Factor/Tic-tac-toe b/Lang/Factor/Tic-tac-toe new file mode 120000 index 0000000000..183c5fb3e0 --- /dev/null +++ b/Lang/Factor/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/Factor \ No newline at end of file diff --git a/Lang/Fennel/00-LANG.txt b/Lang/Fennel/00-LANG.txt index d4313c004b..a3b3fb9075 100644 --- a/Lang/Fennel/00-LANG.txt +++ b/Lang/Fennel/00-LANG.txt @@ -10,4 +10,9 @@ According to Fennel website: Fennel is a programming language that brings togeth Anywhere you can run Lua code, you can run Fennel code. -See more examples at: [https://fennel-lang.org/ Fennel Website] \ No newline at end of file +See more examples at: [https://fennel-lang.org/ Fennel Website] + +A useful learning tool is antifennel at [https://git.sr.ht/~technomancy/antifennel https://git.sr.ht/~technomancy/antifennel] that can convert Lua programs to Fennel. +NB, some Lua features are not supported, particularly , and goto and any new features in Lua 5.5. + +As well as [[Lua]] 5.x VMs, Fennel programs can also be run with [[Pluto]], though warnings will probably be generated when Pluto parses the generated Lua. \ No newline at end of file diff --git a/Lang/Fennel/100-doors b/Lang/Fennel/100-doors new file mode 120000 index 0000000000..445ef6d734 --- /dev/null +++ b/Lang/Fennel/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/Fennel \ No newline at end of file diff --git a/Lang/Fennel/Abundant-deficient-and-perfect-number-classifications b/Lang/Fennel/Abundant-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..fbb88cf56d --- /dev/null +++ b/Lang/Fennel/Abundant-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant-deficient-and-perfect-number-classifications/Fennel \ No newline at end of file diff --git a/Lang/Fennel/Almost-prime b/Lang/Fennel/Almost-prime new file mode 120000 index 0000000000..ff96ace4e0 --- /dev/null +++ b/Lang/Fennel/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/Fennel \ No newline at end of file diff --git a/Lang/Fennel/Ascending-primes b/Lang/Fennel/Ascending-primes new file mode 120000 index 0000000000..809d348a6f --- /dev/null +++ b/Lang/Fennel/Ascending-primes @@ -0,0 +1 @@ +../../Task/Ascending-primes/Fennel \ No newline at end of file diff --git a/Lang/Fennel/Associative-array-Iteration b/Lang/Fennel/Associative-array-Iteration new file mode 120000 index 0000000000..35dee61a57 --- /dev/null +++ b/Lang/Fennel/Associative-array-Iteration @@ -0,0 +1 @@ +../../Task/Associative-array-Iteration/Fennel \ No newline at end of file diff --git a/Lang/Fennel/Chowla-numbers b/Lang/Fennel/Chowla-numbers new file mode 120000 index 0000000000..ceac262e93 --- /dev/null +++ b/Lang/Fennel/Chowla-numbers @@ -0,0 +1 @@ +../../Task/Chowla-numbers/Fennel \ No newline at end of file diff --git a/Lang/Fennel/Descending-primes b/Lang/Fennel/Descending-primes new file mode 120000 index 0000000000..0de026f662 --- /dev/null +++ b/Lang/Fennel/Descending-primes @@ -0,0 +1 @@ +../../Task/Descending-primes/Fennel \ No newline at end of file diff --git a/Lang/Fennel/Dot-product b/Lang/Fennel/Dot-product new file mode 120000 index 0000000000..ef8e13865c --- /dev/null +++ b/Lang/Fennel/Dot-product @@ -0,0 +1 @@ +../../Task/Dot-product/Fennel \ No newline at end of file diff --git a/Lang/Fennel/Equal-prime-and-composite-sums b/Lang/Fennel/Equal-prime-and-composite-sums new file mode 120000 index 0000000000..fd46523293 --- /dev/null +++ b/Lang/Fennel/Equal-prime-and-composite-sums @@ -0,0 +1 @@ +../../Task/Equal-prime-and-composite-sums/Fennel \ No newline at end of file diff --git a/Lang/Fennel/Euclid-Mullin-sequence b/Lang/Fennel/Euclid-Mullin-sequence new file mode 120000 index 0000000000..3b36037b43 --- /dev/null +++ b/Lang/Fennel/Euclid-Mullin-sequence @@ -0,0 +1 @@ +../../Task/Euclid-Mullin-sequence/Fennel \ No newline at end of file diff --git a/Lang/Fennel/Execute-Brain- b/Lang/Fennel/Execute-Brain- new file mode 120000 index 0000000000..c651f55913 --- /dev/null +++ b/Lang/Fennel/Execute-Brain- @@ -0,0 +1 @@ +../../Task/Execute-Brain-/Fennel \ No newline at end of file diff --git a/Lang/Fennel/Factorial b/Lang/Fennel/Factorial new file mode 120000 index 0000000000..ad3ab162af --- /dev/null +++ b/Lang/Fennel/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Fennel \ No newline at end of file diff --git a/Lang/Fennel/Factorial-primes b/Lang/Fennel/Factorial-primes new file mode 120000 index 0000000000..f7ae7a4fab --- /dev/null +++ b/Lang/Fennel/Factorial-primes @@ -0,0 +1 @@ +../../Task/Factorial-primes/Fennel \ No newline at end of file diff --git a/Lang/Fennel/Goldbachs-comet b/Lang/Fennel/Goldbachs-comet new file mode 120000 index 0000000000..38a9767c12 --- /dev/null +++ b/Lang/Fennel/Goldbachs-comet @@ -0,0 +1 @@ +../../Task/Goldbachs-comet/Fennel \ No newline at end of file diff --git a/Lang/Fennel/Haversine-formula b/Lang/Fennel/Haversine-formula new file mode 120000 index 0000000000..855dbd8be0 --- /dev/null +++ b/Lang/Fennel/Haversine-formula @@ -0,0 +1 @@ +../../Task/Haversine-formula/Fennel \ No newline at end of file diff --git a/Lang/Fennel/Horners-rule-for-polynomial-evaluation b/Lang/Fennel/Horners-rule-for-polynomial-evaluation new file mode 120000 index 0000000000..74fe37f151 --- /dev/null +++ b/Lang/Fennel/Horners-rule-for-polynomial-evaluation @@ -0,0 +1 @@ +../../Task/Horners-rule-for-polynomial-evaluation/Fennel \ No newline at end of file diff --git a/Lang/Fennel/Jacobsthal-numbers b/Lang/Fennel/Jacobsthal-numbers new file mode 120000 index 0000000000..fcf69f6156 --- /dev/null +++ b/Lang/Fennel/Jacobsthal-numbers @@ -0,0 +1 @@ +../../Task/Jacobsthal-numbers/Fennel \ No newline at end of file diff --git a/Lang/Fennel/Jordan-P-lya-numbers b/Lang/Fennel/Jordan-P-lya-numbers new file mode 120000 index 0000000000..b4c757f403 --- /dev/null +++ b/Lang/Fennel/Jordan-P-lya-numbers @@ -0,0 +1 @@ +../../Task/Jordan-P-lya-numbers/Fennel \ No newline at end of file diff --git a/Lang/Fennel/Juggler-sequence b/Lang/Fennel/Juggler-sequence new file mode 120000 index 0000000000..09d9faa2d8 --- /dev/null +++ b/Lang/Fennel/Juggler-sequence @@ -0,0 +1 @@ +../../Task/Juggler-sequence/Fennel \ No newline at end of file diff --git a/Lang/Fennel/Legendre-prime-counting-function b/Lang/Fennel/Legendre-prime-counting-function new file mode 120000 index 0000000000..da570fb296 --- /dev/null +++ b/Lang/Fennel/Legendre-prime-counting-function @@ -0,0 +1 @@ +../../Task/Legendre-prime-counting-function/Fennel \ No newline at end of file diff --git a/Lang/Fennel/Magic-8-ball b/Lang/Fennel/Magic-8-ball new file mode 120000 index 0000000000..aa85a0a813 --- /dev/null +++ b/Lang/Fennel/Magic-8-ball @@ -0,0 +1 @@ +../../Task/Magic-8-ball/Fennel \ No newline at end of file diff --git a/Lang/Fennel/McNuggets-problem b/Lang/Fennel/McNuggets-problem new file mode 120000 index 0000000000..6947e9ca17 --- /dev/null +++ b/Lang/Fennel/McNuggets-problem @@ -0,0 +1 @@ +../../Task/McNuggets-problem/Fennel \ No newline at end of file diff --git a/Lang/Fennel/Numbers-with-equal-rises-and-falls b/Lang/Fennel/Numbers-with-equal-rises-and-falls new file mode 120000 index 0000000000..5b24fbe9c6 --- /dev/null +++ b/Lang/Fennel/Numbers-with-equal-rises-and-falls @@ -0,0 +1 @@ +../../Task/Numbers-with-equal-rises-and-falls/Fennel \ No newline at end of file diff --git a/Lang/Fennel/Ordered-words b/Lang/Fennel/Ordered-words new file mode 120000 index 0000000000..e6920afb80 --- /dev/null +++ b/Lang/Fennel/Ordered-words @@ -0,0 +1 @@ +../../Task/Ordered-words/Fennel \ No newline at end of file diff --git a/Lang/Fennel/Program-name b/Lang/Fennel/Program-name new file mode 120000 index 0000000000..c12837ea94 --- /dev/null +++ b/Lang/Fennel/Program-name @@ -0,0 +1 @@ +../../Task/Program-name/Fennel \ No newline at end of file diff --git a/Lang/Fennel/Quoting-constructs b/Lang/Fennel/Quoting-constructs new file mode 120000 index 0000000000..69544d5ca6 --- /dev/null +++ b/Lang/Fennel/Quoting-constructs @@ -0,0 +1 @@ +../../Task/Quoting-constructs/Fennel \ No newline at end of file diff --git a/Lang/Fennel/Sleeping-Beauty-problem b/Lang/Fennel/Sleeping-Beauty-problem new file mode 120000 index 0000000000..35404c74a3 --- /dev/null +++ b/Lang/Fennel/Sleeping-Beauty-problem @@ -0,0 +1 @@ +../../Task/Sleeping-Beauty-problem/Fennel \ No newline at end of file diff --git a/Lang/Fennel/Square-but-not-cube b/Lang/Fennel/Square-but-not-cube new file mode 120000 index 0000000000..55c96cb4bd --- /dev/null +++ b/Lang/Fennel/Square-but-not-cube @@ -0,0 +1 @@ +../../Task/Square-but-not-cube/Fennel \ No newline at end of file diff --git a/Lang/Fennel/Sum-of-elements-below-main-diagonal-of-matrix b/Lang/Fennel/Sum-of-elements-below-main-diagonal-of-matrix new file mode 120000 index 0000000000..e6054255ef --- /dev/null +++ b/Lang/Fennel/Sum-of-elements-below-main-diagonal-of-matrix @@ -0,0 +1 @@ +../../Task/Sum-of-elements-below-main-diagonal-of-matrix/Fennel \ No newline at end of file diff --git a/Lang/Fennel/Tau-function b/Lang/Fennel/Tau-function new file mode 120000 index 0000000000..97342018ad --- /dev/null +++ b/Lang/Fennel/Tau-function @@ -0,0 +1 @@ +../../Task/Tau-function/Fennel \ No newline at end of file diff --git a/Lang/Fennel/Tau-number b/Lang/Fennel/Tau-number new file mode 120000 index 0000000000..b25562b44c --- /dev/null +++ b/Lang/Fennel/Tau-number @@ -0,0 +1 @@ +../../Task/Tau-number/Fennel \ No newline at end of file diff --git a/Lang/Fennel/Thue-Morse b/Lang/Fennel/Thue-Morse new file mode 120000 index 0000000000..03b98b380a --- /dev/null +++ b/Lang/Fennel/Thue-Morse @@ -0,0 +1 @@ +../../Task/Thue-Morse/Fennel \ No newline at end of file diff --git a/Lang/Fennel/Time-a-function b/Lang/Fennel/Time-a-function new file mode 120000 index 0000000000..e57c2d9bfb --- /dev/null +++ b/Lang/Fennel/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Fennel \ No newline at end of file diff --git a/Lang/Fennel/Wilson-primes-of-order-n b/Lang/Fennel/Wilson-primes-of-order-n new file mode 120000 index 0000000000..3a829de574 --- /dev/null +++ b/Lang/Fennel/Wilson-primes-of-order-n @@ -0,0 +1 @@ +../../Task/Wilson-primes-of-order-n/Fennel \ No newline at end of file diff --git a/Lang/Fennel/Yellowstone-sequence b/Lang/Fennel/Yellowstone-sequence new file mode 120000 index 0000000000..e160b50754 --- /dev/null +++ b/Lang/Fennel/Yellowstone-sequence @@ -0,0 +1 @@ +../../Task/Yellowstone-sequence/Fennel \ No newline at end of file diff --git a/Lang/Fish/00-LANG.txt b/Lang/Fish/00-LANG.txt index ae84e9d381..3479165e5a 100644 --- a/Lang/Fish/00-LANG.txt +++ b/Lang/Fish/00-LANG.txt @@ -1,4 +1,3 @@ -{{language}}Fish is an Funge-like esoteric language, consisting of the traditional Funge one-character commands. -A complete specification with a list of implementations can be found at [[eso:Fish|esolangs]]. +{{language}}Fish (properly spelled "><>") is a Funge-like esoteric language, consisting of the traditional Funge one-character commands arranged in a two-dimensional code space. A complete specification with a list of implementations can be found at [[eso:Fish|esolangs]]. [[Category:Esoteric_Languages]] \ No newline at end of file diff --git a/Lang/Forth/Almost-prime b/Lang/Forth/Almost-prime new file mode 120000 index 0000000000..bbe907fa90 --- /dev/null +++ b/Lang/Forth/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/Forth \ No newline at end of file diff --git a/Lang/Forth/Bell-numbers b/Lang/Forth/Bell-numbers new file mode 120000 index 0000000000..d0f973798a --- /dev/null +++ b/Lang/Forth/Bell-numbers @@ -0,0 +1 @@ +../../Task/Bell-numbers/Forth \ No newline at end of file diff --git a/Lang/Forth/Bioinformatics-base-count b/Lang/Forth/Bioinformatics-base-count deleted file mode 120000 index b72b7872d9..0000000000 --- a/Lang/Forth/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Forth \ No newline at end of file diff --git a/Lang/Forth/Chaocipher b/Lang/Forth/Chaocipher new file mode 120000 index 0000000000..4e26356ed4 --- /dev/null +++ b/Lang/Forth/Chaocipher @@ -0,0 +1 @@ +../../Task/Chaocipher/Forth \ No newline at end of file diff --git a/Lang/Forth/Deceptive-numbers b/Lang/Forth/Deceptive-numbers new file mode 120000 index 0000000000..68978661e4 --- /dev/null +++ b/Lang/Forth/Deceptive-numbers @@ -0,0 +1 @@ +../../Task/Deceptive-numbers/Forth \ No newline at end of file diff --git a/Lang/Forth/Duffinian-numbers b/Lang/Forth/Duffinian-numbers new file mode 120000 index 0000000000..9a7e28500f --- /dev/null +++ b/Lang/Forth/Duffinian-numbers @@ -0,0 +1 @@ +../../Task/Duffinian-numbers/Forth \ No newline at end of file diff --git a/Lang/Forth/Fibonacci-word b/Lang/Forth/Fibonacci-word new file mode 120000 index 0000000000..b5b4488597 --- /dev/null +++ b/Lang/Forth/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/Forth \ No newline at end of file diff --git a/Lang/Forth/GUI-component-interaction b/Lang/Forth/GUI-component-interaction new file mode 120000 index 0000000000..6ac944b586 --- /dev/null +++ b/Lang/Forth/GUI-component-interaction @@ -0,0 +1 @@ +../../Task/GUI-component-interaction/Forth \ No newline at end of file diff --git a/Lang/Forth/Hunt-the-Wumpus b/Lang/Forth/Hunt-the-Wumpus new file mode 120000 index 0000000000..3a835dfd4d --- /dev/null +++ b/Lang/Forth/Hunt-the-Wumpus @@ -0,0 +1 @@ +../../Task/Hunt-the-Wumpus/Forth \ No newline at end of file diff --git a/Lang/Forth/Lah-numbers b/Lang/Forth/Lah-numbers new file mode 120000 index 0000000000..63faba81d9 --- /dev/null +++ b/Lang/Forth/Lah-numbers @@ -0,0 +1 @@ +../../Task/Lah-numbers/Forth \ No newline at end of file diff --git a/Lang/Forth/Leonardo-numbers b/Lang/Forth/Leonardo-numbers new file mode 120000 index 0000000000..5742a06693 --- /dev/null +++ b/Lang/Forth/Leonardo-numbers @@ -0,0 +1 @@ +../../Task/Leonardo-numbers/Forth \ No newline at end of file diff --git a/Lang/Forth/M-bius-function b/Lang/Forth/M-bius-function new file mode 120000 index 0000000000..02d70b9302 --- /dev/null +++ b/Lang/Forth/M-bius-function @@ -0,0 +1 @@ +../../Task/M-bius-function/Forth \ No newline at end of file diff --git a/Lang/Forth/Miller-Rabin-primality-test b/Lang/Forth/Miller-Rabin-primality-test deleted file mode 120000 index 6d752b6553..0000000000 --- a/Lang/Forth/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Forth \ No newline at end of file diff --git a/Lang/Forth/Particle-fountain b/Lang/Forth/Particle-fountain new file mode 120000 index 0000000000..3ac0d2e0d6 --- /dev/null +++ b/Lang/Forth/Particle-fountain @@ -0,0 +1 @@ +../../Task/Particle-fountain/Forth \ No newline at end of file diff --git a/Lang/Forth/Pseudo-random-numbers-PCG32 b/Lang/Forth/Pseudo-random-numbers-PCG32 new file mode 120000 index 0000000000..df0bc45550 --- /dev/null +++ b/Lang/Forth/Pseudo-random-numbers-PCG32 @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-PCG32/Forth \ No newline at end of file diff --git a/Lang/Forth/Quaternion-type b/Lang/Forth/Quaternion-type deleted file mode 120000 index bed4c03ac8..0000000000 --- a/Lang/Forth/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Forth \ No newline at end of file diff --git a/Lang/Forth/Sorting-Algorithms-Circle-Sort b/Lang/Forth/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 0f0dc80920..0000000000 --- a/Lang/Forth/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Forth \ No newline at end of file diff --git a/Lang/Forth/Sorting-algorithms-Pancake-sort b/Lang/Forth/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..84e38b0321 --- /dev/null +++ b/Lang/Forth/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/Forth \ No newline at end of file diff --git a/Lang/Forth/Stirling-numbers-of-the-first-kind b/Lang/Forth/Stirling-numbers-of-the-first-kind new file mode 120000 index 0000000000..f35ec2aaf5 --- /dev/null +++ b/Lang/Forth/Stirling-numbers-of-the-first-kind @@ -0,0 +1 @@ +../../Task/Stirling-numbers-of-the-first-kind/Forth \ No newline at end of file diff --git a/Lang/Forth/Stirling-numbers-of-the-second-kind b/Lang/Forth/Stirling-numbers-of-the-second-kind new file mode 120000 index 0000000000..a86eb5dfc1 --- /dev/null +++ b/Lang/Forth/Stirling-numbers-of-the-second-kind @@ -0,0 +1 @@ +../../Task/Stirling-numbers-of-the-second-kind/Forth \ No newline at end of file diff --git a/Lang/Forth/Twin-primes b/Lang/Forth/Twin-primes new file mode 120000 index 0000000000..7812aac04a --- /dev/null +++ b/Lang/Forth/Twin-primes @@ -0,0 +1 @@ +../../Task/Twin-primes/Forth \ No newline at end of file diff --git a/Lang/Fortran/ADFGVX-cipher b/Lang/Fortran/ADFGVX-cipher new file mode 120000 index 0000000000..dc1d16bc9a --- /dev/null +++ b/Lang/Fortran/ADFGVX-cipher @@ -0,0 +1 @@ +../../Task/ADFGVX-cipher/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Abbreviations-automatic b/Lang/Fortran/Abbreviations-automatic new file mode 120000 index 0000000000..b006a0de84 --- /dev/null +++ b/Lang/Fortran/Abbreviations-automatic @@ -0,0 +1 @@ +../../Task/Abbreviations-automatic/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Abbreviations-easy b/Lang/Fortran/Abbreviations-easy new file mode 120000 index 0000000000..ad33bd3687 --- /dev/null +++ b/Lang/Fortran/Abbreviations-easy @@ -0,0 +1 @@ +../../Task/Abbreviations-easy/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Abbreviations-simple b/Lang/Fortran/Abbreviations-simple new file mode 120000 index 0000000000..9ddfe0b240 --- /dev/null +++ b/Lang/Fortran/Abbreviations-simple @@ -0,0 +1 @@ +../../Task/Abbreviations-simple/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Abelian-sandpile-model-Identity b/Lang/Fortran/Abelian-sandpile-model-Identity new file mode 120000 index 0000000000..f022469180 --- /dev/null +++ b/Lang/Fortran/Abelian-sandpile-model-Identity @@ -0,0 +1 @@ +../../Task/Abelian-sandpile-model-Identity/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Additive-primes b/Lang/Fortran/Additive-primes new file mode 120000 index 0000000000..ea531b1d68 --- /dev/null +++ b/Lang/Fortran/Additive-primes @@ -0,0 +1 @@ +../../Task/Additive-primes/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Apply-a-digital-filter-direct-form-II-transposed- b/Lang/Fortran/Apply-a-digital-filter-direct-form-II-transposed- new file mode 120000 index 0000000000..dd0e66389d --- /dev/null +++ b/Lang/Fortran/Apply-a-digital-filter-direct-form-II-transposed- @@ -0,0 +1 @@ +../../Task/Apply-a-digital-filter-direct-form-II-transposed-/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Arithmetic-derivative b/Lang/Fortran/Arithmetic-derivative new file mode 120000 index 0000000000..afa7044404 --- /dev/null +++ b/Lang/Fortran/Arithmetic-derivative @@ -0,0 +1 @@ +../../Task/Arithmetic-derivative/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Arithmetic-numbers b/Lang/Fortran/Arithmetic-numbers new file mode 120000 index 0000000000..19ae0a75dc --- /dev/null +++ b/Lang/Fortran/Arithmetic-numbers @@ -0,0 +1 @@ +../../Task/Arithmetic-numbers/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Associative-array-Merging b/Lang/Fortran/Associative-array-Merging new file mode 120000 index 0000000000..862cee9b2b --- /dev/null +++ b/Lang/Fortran/Associative-array-Merging @@ -0,0 +1 @@ +../../Task/Associative-array-Merging/Fortran \ No newline at end of file diff --git a/Lang/Fortran/B-zier-curves-Intersections b/Lang/Fortran/B-zier-curves-Intersections new file mode 120000 index 0000000000..59ae9a9e9a --- /dev/null +++ b/Lang/Fortran/B-zier-curves-Intersections @@ -0,0 +1 @@ +../../Task/B-zier-curves-Intersections/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Best-shuffle b/Lang/Fortran/Best-shuffle new file mode 120000 index 0000000000..735756bb7c --- /dev/null +++ b/Lang/Fortran/Best-shuffle @@ -0,0 +1 @@ +../../Task/Best-shuffle/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Bifid-cipher b/Lang/Fortran/Bifid-cipher new file mode 120000 index 0000000000..65b6def5fd --- /dev/null +++ b/Lang/Fortran/Bifid-cipher @@ -0,0 +1 @@ +../../Task/Bifid-cipher/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Bin-given-limits b/Lang/Fortran/Bin-given-limits new file mode 120000 index 0000000000..d5ad60904d --- /dev/null +++ b/Lang/Fortran/Bin-given-limits @@ -0,0 +1 @@ +../../Task/Bin-given-limits/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Bioinformatics-Sequence-mutation b/Lang/Fortran/Bioinformatics-Sequence-mutation new file mode 120000 index 0000000000..9bcd7a681c --- /dev/null +++ b/Lang/Fortran/Bioinformatics-Sequence-mutation @@ -0,0 +1 @@ +../../Task/Bioinformatics-Sequence-mutation/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Blum-integer b/Lang/Fortran/Blum-integer new file mode 120000 index 0000000000..814d829eed --- /dev/null +++ b/Lang/Fortran/Blum-integer @@ -0,0 +1 @@ +../../Task/Blum-integer/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Brilliant-numbers b/Lang/Fortran/Brilliant-numbers new file mode 120000 index 0000000000..6c927981ae --- /dev/null +++ b/Lang/Fortran/Brilliant-numbers @@ -0,0 +1 @@ +../../Task/Brilliant-numbers/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Burrows-Wheeler-transform b/Lang/Fortran/Burrows-Wheeler-transform new file mode 120000 index 0000000000..e312b27f94 --- /dev/null +++ b/Lang/Fortran/Burrows-Wheeler-transform @@ -0,0 +1 @@ +../../Task/Burrows-Wheeler-transform/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Calkin-Wilf-sequence b/Lang/Fortran/Calkin-Wilf-sequence new file mode 120000 index 0000000000..daedbbc7bc --- /dev/null +++ b/Lang/Fortran/Calkin-Wilf-sequence @@ -0,0 +1 @@ +../../Task/Calkin-Wilf-sequence/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Camel-case-and-snake-case b/Lang/Fortran/Camel-case-and-snake-case new file mode 120000 index 0000000000..8c737ed655 --- /dev/null +++ b/Lang/Fortran/Camel-case-and-snake-case @@ -0,0 +1 @@ +../../Task/Camel-case-and-snake-case/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Casting-out-nines b/Lang/Fortran/Casting-out-nines new file mode 120000 index 0000000000..7062811203 --- /dev/null +++ b/Lang/Fortran/Casting-out-nines @@ -0,0 +1 @@ +../../Task/Casting-out-nines/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Catalan-numbers-Pascals-triangle b/Lang/Fortran/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..e33b331d86 --- /dev/null +++ b/Lang/Fortran/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Chaocipher b/Lang/Fortran/Chaocipher new file mode 120000 index 0000000000..1db3092120 --- /dev/null +++ b/Lang/Fortran/Chaocipher @@ -0,0 +1 @@ +../../Task/Chaocipher/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Check-input-device-is-a-terminal b/Lang/Fortran/Check-input-device-is-a-terminal new file mode 120000 index 0000000000..a97eabf9a0 --- /dev/null +++ b/Lang/Fortran/Check-input-device-is-a-terminal @@ -0,0 +1 @@ +../../Task/Check-input-device-is-a-terminal/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Check-output-device-is-a-terminal b/Lang/Fortran/Check-output-device-is-a-terminal new file mode 120000 index 0000000000..47a93202b8 --- /dev/null +++ b/Lang/Fortran/Check-output-device-is-a-terminal @@ -0,0 +1 @@ +../../Task/Check-output-device-is-a-terminal/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Chinese-zodiac b/Lang/Fortran/Chinese-zodiac new file mode 120000 index 0000000000..87ed14e5e7 --- /dev/null +++ b/Lang/Fortran/Chinese-zodiac @@ -0,0 +1 @@ +../../Task/Chinese-zodiac/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Commatizing-numbers b/Lang/Fortran/Commatizing-numbers new file mode 120000 index 0000000000..b30a0bb3a4 --- /dev/null +++ b/Lang/Fortran/Commatizing-numbers @@ -0,0 +1 @@ +../../Task/Commatizing-numbers/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Consecutive-primes-with-ascending-or-descending-differences b/Lang/Fortran/Consecutive-primes-with-ascending-or-descending-differences new file mode 120000 index 0000000000..1347a887b7 --- /dev/null +++ b/Lang/Fortran/Consecutive-primes-with-ascending-or-descending-differences @@ -0,0 +1 @@ +../../Task/Consecutive-primes-with-ascending-or-descending-differences/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Copy-stdin-to-stdout b/Lang/Fortran/Copy-stdin-to-stdout new file mode 120000 index 0000000000..47cac281c7 --- /dev/null +++ b/Lang/Fortran/Copy-stdin-to-stdout @@ -0,0 +1 @@ +../../Task/Copy-stdin-to-stdout/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Count-the-coins b/Lang/Fortran/Count-the-coins new file mode 120000 index 0000000000..974abe5d75 --- /dev/null +++ b/Lang/Fortran/Count-the-coins @@ -0,0 +1 @@ +../../Task/Count-the-coins/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Cuban-primes b/Lang/Fortran/Cuban-primes new file mode 120000 index 0000000000..87850fcead --- /dev/null +++ b/Lang/Fortran/Cuban-primes @@ -0,0 +1 @@ +../../Task/Cuban-primes/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Cullen-and-Woodall-numbers b/Lang/Fortran/Cullen-and-Woodall-numbers new file mode 120000 index 0000000000..ca6a11cd97 --- /dev/null +++ b/Lang/Fortran/Cullen-and-Woodall-numbers @@ -0,0 +1 @@ +../../Task/Cullen-and-Woodall-numbers/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Currency b/Lang/Fortran/Currency new file mode 120000 index 0000000000..2f7b0a58da --- /dev/null +++ b/Lang/Fortran/Currency @@ -0,0 +1 @@ +../../Task/Currency/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Curzon-numbers b/Lang/Fortran/Curzon-numbers new file mode 120000 index 0000000000..b7d16c2b28 --- /dev/null +++ b/Lang/Fortran/Curzon-numbers @@ -0,0 +1 @@ +../../Task/Curzon-numbers/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Cyclops-numbers b/Lang/Fortran/Cyclops-numbers new file mode 120000 index 0000000000..8c606709ad --- /dev/null +++ b/Lang/Fortran/Cyclops-numbers @@ -0,0 +1 @@ +../../Task/Cyclops-numbers/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Cyclotomic-polynomial b/Lang/Fortran/Cyclotomic-polynomial new file mode 120000 index 0000000000..0c2fd63e5e --- /dev/null +++ b/Lang/Fortran/Cyclotomic-polynomial @@ -0,0 +1 @@ +../../Task/Cyclotomic-polynomial/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Demings-funnel b/Lang/Fortran/Demings-funnel new file mode 120000 index 0000000000..0a1ca7ab40 --- /dev/null +++ b/Lang/Fortran/Demings-funnel @@ -0,0 +1 @@ +../../Task/Demings-funnel/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Determine-if-a-string-is-collapsible b/Lang/Fortran/Determine-if-a-string-is-collapsible new file mode 120000 index 0000000000..f496b06786 --- /dev/null +++ b/Lang/Fortran/Determine-if-a-string-is-collapsible @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-collapsible/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Determine-if-two-triangles-overlap b/Lang/Fortran/Determine-if-two-triangles-overlap new file mode 120000 index 0000000000..902cd39054 --- /dev/null +++ b/Lang/Fortran/Determine-if-two-triangles-overlap @@ -0,0 +1 @@ +../../Task/Determine-if-two-triangles-overlap/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Dice-game-probabilities b/Lang/Fortran/Dice-game-probabilities new file mode 120000 index 0000000000..1215daca7a --- /dev/null +++ b/Lang/Fortran/Dice-game-probabilities @@ -0,0 +1 @@ +../../Task/Dice-game-probabilities/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Dinesmans-multiple-dwelling-problem b/Lang/Fortran/Dinesmans-multiple-dwelling-problem new file mode 120000 index 0000000000..4ab5caf233 --- /dev/null +++ b/Lang/Fortran/Dinesmans-multiple-dwelling-problem @@ -0,0 +1 @@ +../../Task/Dinesmans-multiple-dwelling-problem/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Dining-philosophers b/Lang/Fortran/Dining-philosophers new file mode 120000 index 0000000000..8822e00fdf --- /dev/null +++ b/Lang/Fortran/Dining-philosophers @@ -0,0 +1 @@ +../../Task/Dining-philosophers/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Disarium-numbers b/Lang/Fortran/Disarium-numbers new file mode 120000 index 0000000000..4713bf931d --- /dev/null +++ b/Lang/Fortran/Disarium-numbers @@ -0,0 +1 @@ +../../Task/Disarium-numbers/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Display-a-linear-combination b/Lang/Fortran/Display-a-linear-combination new file mode 120000 index 0000000000..4a9784f58d --- /dev/null +++ b/Lang/Fortran/Display-a-linear-combination @@ -0,0 +1 @@ +../../Task/Display-a-linear-combination/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Diversity-prediction-theorem b/Lang/Fortran/Diversity-prediction-theorem new file mode 120000 index 0000000000..c6eafa5019 --- /dev/null +++ b/Lang/Fortran/Diversity-prediction-theorem @@ -0,0 +1 @@ +../../Task/Diversity-prediction-theorem/Fortran \ No newline at end of file diff --git a/Lang/Fortran/EKG-sequence-convergence b/Lang/Fortran/EKG-sequence-convergence new file mode 120000 index 0000000000..3ba5c0a162 --- /dev/null +++ b/Lang/Fortran/EKG-sequence-convergence @@ -0,0 +1 @@ +../../Task/EKG-sequence-convergence/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Eban-numbers b/Lang/Fortran/Eban-numbers new file mode 120000 index 0000000000..0d435c16c7 --- /dev/null +++ b/Lang/Fortran/Eban-numbers @@ -0,0 +1 @@ +../../Task/Eban-numbers/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Egyptian-division b/Lang/Fortran/Egyptian-division new file mode 120000 index 0000000000..bb7a134139 --- /dev/null +++ b/Lang/Fortran/Egyptian-division @@ -0,0 +1 @@ +../../Task/Egyptian-division/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Entropy-Narcissist b/Lang/Fortran/Entropy-Narcissist new file mode 120000 index 0000000000..9050980c1c --- /dev/null +++ b/Lang/Fortran/Entropy-Narcissist @@ -0,0 +1 @@ +../../Task/Entropy-Narcissist/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Eulers-constant-0.5772... b/Lang/Fortran/Eulers-constant-0.5772... new file mode 120000 index 0000000000..e2642e24fb --- /dev/null +++ b/Lang/Fortran/Eulers-constant-0.5772... @@ -0,0 +1 @@ +../../Task/Eulers-constant-0.5772.../Fortran \ No newline at end of file diff --git a/Lang/Fortran/Exponentiation-with-infix-operators-in-or-operating-on-the-base b/Lang/Fortran/Exponentiation-with-infix-operators-in-or-operating-on-the-base new file mode 120000 index 0000000000..813fe58706 --- /dev/null +++ b/Lang/Fortran/Exponentiation-with-infix-operators-in-or-operating-on-the-base @@ -0,0 +1 @@ +../../Task/Exponentiation-with-infix-operators-in-or-operating-on-the-base/Fortran \ No newline at end of file diff --git a/Lang/Fortran/FASTA-format b/Lang/Fortran/FASTA-format new file mode 120000 index 0000000000..b5442ba0f5 --- /dev/null +++ b/Lang/Fortran/FASTA-format @@ -0,0 +1 @@ +../../Task/FASTA-format/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Factorions b/Lang/Fortran/Factorions new file mode 120000 index 0000000000..2a48b53fa3 --- /dev/null +++ b/Lang/Fortran/Factorions @@ -0,0 +1 @@ +../../Task/Factorions/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Farey-sequence b/Lang/Fortran/Farey-sequence new file mode 120000 index 0000000000..d7c19f96de --- /dev/null +++ b/Lang/Fortran/Farey-sequence @@ -0,0 +1 @@ +../../Task/Farey-sequence/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Fibonacci-word b/Lang/Fortran/Fibonacci-word new file mode 120000 index 0000000000..e92e6e10a6 --- /dev/null +++ b/Lang/Fortran/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Find-Chess960-starting-position-identifier b/Lang/Fortran/Find-Chess960-starting-position-identifier new file mode 120000 index 0000000000..9300b24a96 --- /dev/null +++ b/Lang/Fortran/Find-Chess960-starting-position-identifier @@ -0,0 +1 @@ +../../Task/Find-Chess960-starting-position-identifier/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Find-common-directory-path b/Lang/Fortran/Find-common-directory-path new file mode 120000 index 0000000000..87683f2dbe --- /dev/null +++ b/Lang/Fortran/Find-common-directory-path @@ -0,0 +1 @@ +../../Task/Find-common-directory-path/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Find-the-intersection-of-a-line-with-a-plane b/Lang/Fortran/Find-the-intersection-of-a-line-with-a-plane new file mode 120000 index 0000000000..b07ee0b0a7 --- /dev/null +++ b/Lang/Fortran/Find-the-intersection-of-a-line-with-a-plane @@ -0,0 +1 @@ +../../Task/Find-the-intersection-of-a-line-with-a-plane/Fortran \ No newline at end of file diff --git a/Lang/Fortran/First-perfect-square-in-base-n-with-n-unique-digits b/Lang/Fortran/First-perfect-square-in-base-n-with-n-unique-digits new file mode 120000 index 0000000000..6f8a8ab270 --- /dev/null +++ b/Lang/Fortran/First-perfect-square-in-base-n-with-n-unique-digits @@ -0,0 +1 @@ +../../Task/First-perfect-square-in-base-n-with-n-unique-digits/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Fivenum b/Lang/Fortran/Fivenum new file mode 120000 index 0000000000..a8fe9953dc --- /dev/null +++ b/Lang/Fortran/Fivenum @@ -0,0 +1 @@ +../../Task/Fivenum/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Fixed-length-records b/Lang/Fortran/Fixed-length-records new file mode 120000 index 0000000000..aa68735e7e --- /dev/null +++ b/Lang/Fortran/Fixed-length-records @@ -0,0 +1 @@ +../../Task/Fixed-length-records/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Fraction-reduction b/Lang/Fortran/Fraction-reduction new file mode 120000 index 0000000000..f7daa9279c --- /dev/null +++ b/Lang/Fortran/Fraction-reduction @@ -0,0 +1 @@ +../../Task/Fraction-reduction/Fortran \ No newline at end of file diff --git a/Lang/Fortran/French-Republican-calendar b/Lang/Fortran/French-Republican-calendar new file mode 120000 index 0000000000..765942db3d --- /dev/null +++ b/Lang/Fortran/French-Republican-calendar @@ -0,0 +1 @@ +../../Task/French-Republican-calendar/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Fusc-sequence b/Lang/Fortran/Fusc-sequence new file mode 120000 index 0000000000..c5e3005573 --- /dev/null +++ b/Lang/Fortran/Fusc-sequence @@ -0,0 +1 @@ +../../Task/Fusc-sequence/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Gapful-numbers b/Lang/Fortran/Gapful-numbers new file mode 120000 index 0000000000..7500b01654 --- /dev/null +++ b/Lang/Fortran/Gapful-numbers @@ -0,0 +1 @@ +../../Task/Gapful-numbers/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Giuga-numbers b/Lang/Fortran/Giuga-numbers new file mode 120000 index 0000000000..9f15a4c7e2 --- /dev/null +++ b/Lang/Fortran/Giuga-numbers @@ -0,0 +1 @@ +../../Task/Giuga-numbers/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Greedy-algorithm-for-Egyptian-fractions b/Lang/Fortran/Greedy-algorithm-for-Egyptian-fractions new file mode 120000 index 0000000000..053e501120 --- /dev/null +++ b/Lang/Fortran/Greedy-algorithm-for-Egyptian-fractions @@ -0,0 +1 @@ +../../Task/Greedy-algorithm-for-Egyptian-fractions/Fortran \ No newline at end of file diff --git a/Lang/Fortran/HTTP b/Lang/Fortran/HTTP new file mode 120000 index 0000000000..24f0692116 --- /dev/null +++ b/Lang/Fortran/HTTP @@ -0,0 +1 @@ +../../Task/HTTP/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Harmonic-series b/Lang/Fortran/Harmonic-series new file mode 120000 index 0000000000..6a6cd246a2 --- /dev/null +++ b/Lang/Fortran/Harmonic-series @@ -0,0 +1 @@ +../../Task/Harmonic-series/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Hex-words b/Lang/Fortran/Hex-words new file mode 120000 index 0000000000..2b9a4573e8 --- /dev/null +++ b/Lang/Fortran/Hex-words @@ -0,0 +1 @@ +../../Task/Hex-words/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Hofstadter-Figure-Figure-sequences b/Lang/Fortran/Hofstadter-Figure-Figure-sequences new file mode 120000 index 0000000000..46497cf751 --- /dev/null +++ b/Lang/Fortran/Hofstadter-Figure-Figure-sequences @@ -0,0 +1 @@ +../../Task/Hofstadter-Figure-Figure-sequences/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Humble-numbers b/Lang/Fortran/Humble-numbers new file mode 120000 index 0000000000..5aff41aed9 --- /dev/null +++ b/Lang/Fortran/Humble-numbers @@ -0,0 +1 @@ +../../Task/Humble-numbers/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Intersecting-number-wheels b/Lang/Fortran/Intersecting-number-wheels new file mode 120000 index 0000000000..f87ba36725 --- /dev/null +++ b/Lang/Fortran/Intersecting-number-wheels @@ -0,0 +1 @@ +../../Task/Intersecting-number-wheels/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Isograms-and-heterograms b/Lang/Fortran/Isograms-and-heterograms new file mode 120000 index 0000000000..cc9bb4e50b --- /dev/null +++ b/Lang/Fortran/Isograms-and-heterograms @@ -0,0 +1 @@ +../../Task/Isograms-and-heterograms/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Iterated-digits-squaring b/Lang/Fortran/Iterated-digits-squaring new file mode 120000 index 0000000000..b72dc14257 --- /dev/null +++ b/Lang/Fortran/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Jewels-and-stones b/Lang/Fortran/Jewels-and-stones new file mode 120000 index 0000000000..5375572de2 --- /dev/null +++ b/Lang/Fortran/Jewels-and-stones @@ -0,0 +1 @@ +../../Task/Jewels-and-stones/Fortran \ No newline at end of file diff --git a/Lang/Fortran/K-d-tree b/Lang/Fortran/K-d-tree new file mode 120000 index 0000000000..3b7491c540 --- /dev/null +++ b/Lang/Fortran/K-d-tree @@ -0,0 +1 @@ +../../Task/K-d-tree/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Kernighans-large-earthquake-problem b/Lang/Fortran/Kernighans-large-earthquake-problem new file mode 120000 index 0000000000..ae20f8ddbd --- /dev/null +++ b/Lang/Fortran/Kernighans-large-earthquake-problem @@ -0,0 +1 @@ +../../Task/Kernighans-large-earthquake-problem/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Knapsack-problem-Bounded b/Lang/Fortran/Knapsack-problem-Bounded new file mode 120000 index 0000000000..9f9870702b --- /dev/null +++ b/Lang/Fortran/Knapsack-problem-Bounded @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Bounded/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Knuths-algorithm-S b/Lang/Fortran/Knuths-algorithm-S new file mode 120000 index 0000000000..fe5b21ade9 --- /dev/null +++ b/Lang/Fortran/Knuths-algorithm-S @@ -0,0 +1 @@ +../../Task/Knuths-algorithm-S/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Knuths-power-tree b/Lang/Fortran/Knuths-power-tree new file mode 120000 index 0000000000..163172c51f --- /dev/null +++ b/Lang/Fortran/Knuths-power-tree @@ -0,0 +1 @@ +../../Task/Knuths-power-tree/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Largest-number-divisible-by-its-digits b/Lang/Fortran/Largest-number-divisible-by-its-digits new file mode 120000 index 0000000000..cd7d8d0694 --- /dev/null +++ b/Lang/Fortran/Largest-number-divisible-by-its-digits @@ -0,0 +1 @@ +../../Task/Largest-number-divisible-by-its-digits/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Logistic-curve-fitting-in-epidemiology b/Lang/Fortran/Logistic-curve-fitting-in-epidemiology new file mode 120000 index 0000000000..c968939bbf --- /dev/null +++ b/Lang/Fortran/Logistic-curve-fitting-in-epidemiology @@ -0,0 +1 @@ +../../Task/Logistic-curve-fitting-in-epidemiology/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Long-literals-with-continuations b/Lang/Fortran/Long-literals-with-continuations new file mode 120000 index 0000000000..7af1186694 --- /dev/null +++ b/Lang/Fortran/Long-literals-with-continuations @@ -0,0 +1 @@ +../../Task/Long-literals-with-continuations/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Longest-increasing-subsequence b/Lang/Fortran/Longest-increasing-subsequence new file mode 120000 index 0000000000..4d7a715c23 --- /dev/null +++ b/Lang/Fortran/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Loops-Wrong-ranges b/Lang/Fortran/Loops-Wrong-ranges new file mode 120000 index 0000000000..ecb218786f --- /dev/null +++ b/Lang/Fortran/Loops-Wrong-ranges @@ -0,0 +1 @@ +../../Task/Loops-Wrong-ranges/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Lucky-and-even-lucky-numbers b/Lang/Fortran/Lucky-and-even-lucky-numbers new file mode 120000 index 0000000000..5ac4d084fd --- /dev/null +++ b/Lang/Fortran/Lucky-and-even-lucky-numbers @@ -0,0 +1 @@ +../../Task/Lucky-and-even-lucky-numbers/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Magic-constant b/Lang/Fortran/Magic-constant new file mode 120000 index 0000000000..011d77bc86 --- /dev/null +++ b/Lang/Fortran/Magic-constant @@ -0,0 +1 @@ +../../Task/Magic-constant/Fortran \ No newline at end of file diff --git a/Lang/Fortran/McNuggets-problem b/Lang/Fortran/McNuggets-problem new file mode 120000 index 0000000000..6e4b8bc9dd --- /dev/null +++ b/Lang/Fortran/McNuggets-problem @@ -0,0 +1 @@ +../../Task/McNuggets-problem/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Metallic-ratios b/Lang/Fortran/Metallic-ratios new file mode 120000 index 0000000000..21133a8990 --- /dev/null +++ b/Lang/Fortran/Metallic-ratios @@ -0,0 +1 @@ +../../Task/Metallic-ratios/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Miller-Rabin-primality-test b/Lang/Fortran/Miller-Rabin-primality-test deleted file mode 120000 index 6d501f45e9..0000000000 --- a/Lang/Fortran/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Mind-boggling-card-trick b/Lang/Fortran/Mind-boggling-card-trick new file mode 120000 index 0000000000..bda2aaf5f0 --- /dev/null +++ b/Lang/Fortran/Mind-boggling-card-trick @@ -0,0 +1 @@ +../../Task/Mind-boggling-card-trick/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Minimum-multiple-of-m-where-digital-sum-equals-m b/Lang/Fortran/Minimum-multiple-of-m-where-digital-sum-equals-m new file mode 120000 index 0000000000..0e425fef14 --- /dev/null +++ b/Lang/Fortran/Minimum-multiple-of-m-where-digital-sum-equals-m @@ -0,0 +1 @@ +../../Task/Minimum-multiple-of-m-where-digital-sum-equals-m/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Minimum-positive-multiple-in-base-10-using-only-0-and-1 b/Lang/Fortran/Minimum-positive-multiple-in-base-10-using-only-0-and-1 new file mode 120000 index 0000000000..2524fb63f9 --- /dev/null +++ b/Lang/Fortran/Minimum-positive-multiple-in-base-10-using-only-0-and-1 @@ -0,0 +1 @@ +../../Task/Minimum-positive-multiple-in-base-10-using-only-0-and-1/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Modified-random-distribution b/Lang/Fortran/Modified-random-distribution new file mode 120000 index 0000000000..b886daca51 --- /dev/null +++ b/Lang/Fortran/Modified-random-distribution @@ -0,0 +1 @@ +../../Task/Modified-random-distribution/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Move-to-front-algorithm b/Lang/Fortran/Move-to-front-algorithm new file mode 120000 index 0000000000..aaea4a888b --- /dev/null +++ b/Lang/Fortran/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Multisplit b/Lang/Fortran/Multisplit new file mode 120000 index 0000000000..f032908bb4 --- /dev/null +++ b/Lang/Fortran/Multisplit @@ -0,0 +1 @@ +../../Task/Multisplit/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Numbers-which-are-the-cube-roots-of-the-product-of-their-proper-divisors b/Lang/Fortran/Numbers-which-are-the-cube-roots-of-the-product-of-their-proper-divisors new file mode 120000 index 0000000000..2f7237b820 --- /dev/null +++ b/Lang/Fortran/Numbers-which-are-the-cube-roots-of-the-product-of-their-proper-divisors @@ -0,0 +1 @@ +../../Task/Numbers-which-are-the-cube-roots-of-the-product-of-their-proper-divisors/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Ormiston-triples b/Lang/Fortran/Ormiston-triples new file mode 120000 index 0000000000..a2f8794905 --- /dev/null +++ b/Lang/Fortran/Ormiston-triples @@ -0,0 +1 @@ +../../Task/Ormiston-triples/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Palindrome-dates b/Lang/Fortran/Palindrome-dates new file mode 120000 index 0000000000..0f7da68189 --- /dev/null +++ b/Lang/Fortran/Palindrome-dates @@ -0,0 +1 @@ +../../Task/Palindrome-dates/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Parallel-brute-force b/Lang/Fortran/Parallel-brute-force new file mode 120000 index 0000000000..85bd9c5ced --- /dev/null +++ b/Lang/Fortran/Parallel-brute-force @@ -0,0 +1 @@ +../../Task/Parallel-brute-force/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Parse-an-IP-Address b/Lang/Fortran/Parse-an-IP-Address new file mode 120000 index 0000000000..33994c1cc1 --- /dev/null +++ b/Lang/Fortran/Parse-an-IP-Address @@ -0,0 +1 @@ +../../Task/Parse-an-IP-Address/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Pascals-triangle-Puzzle b/Lang/Fortran/Pascals-triangle-Puzzle new file mode 120000 index 0000000000..5cea267339 --- /dev/null +++ b/Lang/Fortran/Pascals-triangle-Puzzle @@ -0,0 +1 @@ +../../Task/Pascals-triangle-Puzzle/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Password-generator b/Lang/Fortran/Password-generator new file mode 120000 index 0000000000..5ff2015452 --- /dev/null +++ b/Lang/Fortran/Password-generator @@ -0,0 +1 @@ +../../Task/Password-generator/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Pells-equation b/Lang/Fortran/Pells-equation new file mode 120000 index 0000000000..5929e39745 --- /dev/null +++ b/Lang/Fortran/Pells-equation @@ -0,0 +1 @@ +../../Task/Pells-equation/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Playfair-cipher b/Lang/Fortran/Playfair-cipher new file mode 120000 index 0000000000..7f02f8e934 --- /dev/null +++ b/Lang/Fortran/Playfair-cipher @@ -0,0 +1 @@ +../../Task/Playfair-cipher/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Primality-by-Wilsons-theorem b/Lang/Fortran/Primality-by-Wilsons-theorem new file mode 120000 index 0000000000..228dd95d2d --- /dev/null +++ b/Lang/Fortran/Primality-by-Wilsons-theorem @@ -0,0 +1 @@ +../../Task/Primality-by-Wilsons-theorem/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Pseudo-random-numbers-Splitmix64 b/Lang/Fortran/Pseudo-random-numbers-Splitmix64 new file mode 120000 index 0000000000..39aac5cdd2 --- /dev/null +++ b/Lang/Fortran/Pseudo-random-numbers-Splitmix64 @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-Splitmix64/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Quaternion-type b/Lang/Fortran/Quaternion-type deleted file mode 120000 index a1829748df..0000000000 --- a/Lang/Fortran/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Ramanujan-primes-twins b/Lang/Fortran/Ramanujan-primes-twins new file mode 120000 index 0000000000..bdb1a22484 --- /dev/null +++ b/Lang/Fortran/Ramanujan-primes-twins @@ -0,0 +1 @@ +../../Task/Ramanujan-primes-twins/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Ramanujans-constant b/Lang/Fortran/Ramanujans-constant new file mode 120000 index 0000000000..8de4420011 --- /dev/null +++ b/Lang/Fortran/Ramanujans-constant @@ -0,0 +1 @@ +../../Task/Ramanujans-constant/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Ramer-Douglas-Peucker-line-simplification b/Lang/Fortran/Ramer-Douglas-Peucker-line-simplification new file mode 120000 index 0000000000..a601cbd90f --- /dev/null +++ b/Lang/Fortran/Ramer-Douglas-Peucker-line-simplification @@ -0,0 +1 @@ +../../Task/Ramer-Douglas-Peucker-line-simplification/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Ranking-methods b/Lang/Fortran/Ranking-methods new file mode 120000 index 0000000000..a369cc6fab --- /dev/null +++ b/Lang/Fortran/Ranking-methods @@ -0,0 +1 @@ +../../Task/Ranking-methods/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Read-a-file-character-by-character-UTF8 b/Lang/Fortran/Read-a-file-character-by-character-UTF8 new file mode 120000 index 0000000000..4e9ecfa6e0 --- /dev/null +++ b/Lang/Fortran/Read-a-file-character-by-character-UTF8 @@ -0,0 +1 @@ +../../Task/Read-a-file-character-by-character-UTF8/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Resistor-mesh b/Lang/Fortran/Resistor-mesh new file mode 120000 index 0000000000..4c45bf818f --- /dev/null +++ b/Lang/Fortran/Resistor-mesh @@ -0,0 +1 @@ +../../Task/Resistor-mesh/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Sailors-coconuts-and-a-monkey-problem b/Lang/Fortran/Sailors-coconuts-and-a-monkey-problem new file mode 120000 index 0000000000..e105172665 --- /dev/null +++ b/Lang/Fortran/Sailors-coconuts-and-a-monkey-problem @@ -0,0 +1 @@ +../../Task/Sailors-coconuts-and-a-monkey-problem/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Sieve-of-Pritchard b/Lang/Fortran/Sieve-of-Pritchard new file mode 120000 index 0000000000..a74974dd66 --- /dev/null +++ b/Lang/Fortran/Sieve-of-Pritchard @@ -0,0 +1 @@ +../../Task/Sieve-of-Pritchard/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Sleeping-Beauty-problem b/Lang/Fortran/Sleeping-Beauty-problem new file mode 120000 index 0000000000..35b7547112 --- /dev/null +++ b/Lang/Fortran/Sleeping-Beauty-problem @@ -0,0 +1 @@ +../../Task/Sleeping-Beauty-problem/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Solve-a-Hopido-puzzle b/Lang/Fortran/Solve-a-Hopido-puzzle new file mode 120000 index 0000000000..4726977710 --- /dev/null +++ b/Lang/Fortran/Solve-a-Hopido-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hopido-puzzle/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Sorting-Algorithms-Circle-Sort b/Lang/Fortran/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 62558aaa6e..0000000000 --- a/Lang/Fortran/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Sorting-algorithms-Cocktail-sort-with-shifting-bounds b/Lang/Fortran/Sorting-algorithms-Cocktail-sort-with-shifting-bounds new file mode 120000 index 0000000000..cbe69052c4 --- /dev/null +++ b/Lang/Fortran/Sorting-algorithms-Cocktail-sort-with-shifting-bounds @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort-with-shifting-bounds/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Square-but-not-cube b/Lang/Fortran/Square-but-not-cube new file mode 120000 index 0000000000..13809f6e51 --- /dev/null +++ b/Lang/Fortran/Square-but-not-cube @@ -0,0 +1 @@ +../../Task/Square-but-not-cube/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Stable-marriage-problem b/Lang/Fortran/Stable-marriage-problem new file mode 120000 index 0000000000..b61f49608c --- /dev/null +++ b/Lang/Fortran/Stable-marriage-problem @@ -0,0 +1 @@ +../../Task/Stable-marriage-problem/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Strassens-algorithm b/Lang/Fortran/Strassens-algorithm new file mode 120000 index 0000000000..f73f6498f4 --- /dev/null +++ b/Lang/Fortran/Strassens-algorithm @@ -0,0 +1 @@ +../../Task/Strassens-algorithm/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Fortran/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..e6e0c4696a --- /dev/null +++ b/Lang/Fortran/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Sum-of-elements-below-main-diagonal-of-matrix b/Lang/Fortran/Sum-of-elements-below-main-diagonal-of-matrix new file mode 120000 index 0000000000..a739c37e8e --- /dev/null +++ b/Lang/Fortran/Sum-of-elements-below-main-diagonal-of-matrix @@ -0,0 +1 @@ +../../Task/Sum-of-elements-below-main-diagonal-of-matrix/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Synchronous-concurrency b/Lang/Fortran/Synchronous-concurrency new file mode 120000 index 0000000000..f0f128cdfd --- /dev/null +++ b/Lang/Fortran/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Tarjan b/Lang/Fortran/Tarjan new file mode 120000 index 0000000000..22149d08b7 --- /dev/null +++ b/Lang/Fortran/Tarjan @@ -0,0 +1 @@ +../../Task/Tarjan/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Thieles-interpolation-formula b/Lang/Fortran/Thieles-interpolation-formula new file mode 120000 index 0000000000..f8f82960bc --- /dev/null +++ b/Lang/Fortran/Thieles-interpolation-formula @@ -0,0 +1 @@ +../../Task/Thieles-interpolation-formula/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Total-circles-area b/Lang/Fortran/Total-circles-area new file mode 120000 index 0000000000..7ea452c217 --- /dev/null +++ b/Lang/Fortran/Total-circles-area @@ -0,0 +1 @@ +../../Task/Total-circles-area/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Totient-function b/Lang/Fortran/Totient-function new file mode 120000 index 0000000000..2559e22f69 --- /dev/null +++ b/Lang/Fortran/Totient-function @@ -0,0 +1 @@ +../../Task/Totient-function/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Tree-datastructures b/Lang/Fortran/Tree-datastructures new file mode 120000 index 0000000000..0155519b78 --- /dev/null +++ b/Lang/Fortran/Tree-datastructures @@ -0,0 +1 @@ +../../Task/Tree-datastructures/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Twelve-statements b/Lang/Fortran/Twelve-statements new file mode 120000 index 0000000000..dfaa2166b8 --- /dev/null +++ b/Lang/Fortran/Twelve-statements @@ -0,0 +1 @@ +../../Task/Twelve-statements/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Two-bullet-roulette b/Lang/Fortran/Two-bullet-roulette new file mode 120000 index 0000000000..67f7fb2512 --- /dev/null +++ b/Lang/Fortran/Two-bullet-roulette @@ -0,0 +1 @@ +../../Task/Two-bullet-roulette/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Twos-complement b/Lang/Fortran/Twos-complement new file mode 120000 index 0000000000..b8e6672d37 --- /dev/null +++ b/Lang/Fortran/Twos-complement @@ -0,0 +1 @@ +../../Task/Twos-complement/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Ukkonen-s-suffix-tree-construction b/Lang/Fortran/Ukkonen-s-suffix-tree-construction new file mode 120000 index 0000000000..183d59f5c8 --- /dev/null +++ b/Lang/Fortran/Ukkonen-s-suffix-tree-construction @@ -0,0 +1 @@ +../../Task/Ukkonen-s-suffix-tree-construction/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Unprimeable-numbers b/Lang/Fortran/Unprimeable-numbers new file mode 120000 index 0000000000..9835babcf5 --- /dev/null +++ b/Lang/Fortran/Unprimeable-numbers @@ -0,0 +1 @@ +../../Task/Unprimeable-numbers/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Vampire-number b/Lang/Fortran/Vampire-number new file mode 120000 index 0000000000..fda3c25555 --- /dev/null +++ b/Lang/Fortran/Vampire-number @@ -0,0 +1 @@ +../../Task/Vampire-number/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Verhoeff-algorithm b/Lang/Fortran/Verhoeff-algorithm new file mode 120000 index 0000000000..da50f29648 --- /dev/null +++ b/Lang/Fortran/Verhoeff-algorithm @@ -0,0 +1 @@ +../../Task/Verhoeff-algorithm/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Vigen-re-cipher-Cryptanalysis b/Lang/Fortran/Vigen-re-cipher-Cryptanalysis new file mode 120000 index 0000000000..1fbd3a2ec4 --- /dev/null +++ b/Lang/Fortran/Vigen-re-cipher-Cryptanalysis @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher-Cryptanalysis/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Vogels-approximation-method b/Lang/Fortran/Vogels-approximation-method new file mode 120000 index 0000000000..3098233175 --- /dev/null +++ b/Lang/Fortran/Vogels-approximation-method @@ -0,0 +1 @@ +../../Task/Vogels-approximation-method/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Word-search b/Lang/Fortran/Word-search new file mode 120000 index 0000000000..1675b7de44 --- /dev/null +++ b/Lang/Fortran/Word-search @@ -0,0 +1 @@ +../../Task/Word-search/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Yellowstone-sequence b/Lang/Fortran/Yellowstone-sequence new file mode 120000 index 0000000000..ba08bc09f7 --- /dev/null +++ b/Lang/Fortran/Yellowstone-sequence @@ -0,0 +1 @@ +../../Task/Yellowstone-sequence/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Zebra-puzzle b/Lang/Fortran/Zebra-puzzle new file mode 120000 index 0000000000..93816a6fc6 --- /dev/null +++ b/Lang/Fortran/Zebra-puzzle @@ -0,0 +1 @@ +../../Task/Zebra-puzzle/Fortran \ No newline at end of file diff --git a/Lang/Free-Pascal-Lazarus/ADFGVX-cipher b/Lang/Free-Pascal-Lazarus/ADFGVX-cipher new file mode 120000 index 0000000000..b14ee34ace --- /dev/null +++ b/Lang/Free-Pascal-Lazarus/ADFGVX-cipher @@ -0,0 +1 @@ +../../Task/ADFGVX-cipher/Free-Pascal-Lazarus \ No newline at end of file diff --git a/Lang/Free-Pascal-Lazarus/Abstract-type b/Lang/Free-Pascal-Lazarus/Abstract-type new file mode 120000 index 0000000000..89db3c6334 --- /dev/null +++ b/Lang/Free-Pascal-Lazarus/Abstract-type @@ -0,0 +1 @@ +../../Task/Abstract-type/Free-Pascal-Lazarus \ No newline at end of file diff --git a/Lang/Free-Pascal-Lazarus/Abundant-odd-numbers b/Lang/Free-Pascal-Lazarus/Abundant-odd-numbers new file mode 120000 index 0000000000..04dfaa00e1 --- /dev/null +++ b/Lang/Free-Pascal-Lazarus/Abundant-odd-numbers @@ -0,0 +1 @@ +../../Task/Abundant-odd-numbers/Free-Pascal-Lazarus \ No newline at end of file diff --git a/Lang/Free-Pascal-Lazarus/Bell-numbers b/Lang/Free-Pascal-Lazarus/Bell-numbers new file mode 120000 index 0000000000..889cd61708 --- /dev/null +++ b/Lang/Free-Pascal-Lazarus/Bell-numbers @@ -0,0 +1 @@ +../../Task/Bell-numbers/Free-Pascal-Lazarus \ No newline at end of file diff --git a/Lang/Free-Pascal-Lazarus/Bin-given-limits b/Lang/Free-Pascal-Lazarus/Bin-given-limits new file mode 120000 index 0000000000..090d25165e --- /dev/null +++ b/Lang/Free-Pascal-Lazarus/Bin-given-limits @@ -0,0 +1 @@ +../../Task/Bin-given-limits/Free-Pascal-Lazarus \ No newline at end of file diff --git a/Lang/Free-Pascal-Lazarus/Binary-strings b/Lang/Free-Pascal-Lazarus/Binary-strings new file mode 120000 index 0000000000..f6ed90f24b --- /dev/null +++ b/Lang/Free-Pascal-Lazarus/Binary-strings @@ -0,0 +1 @@ +../../Task/Binary-strings/Free-Pascal-Lazarus \ No newline at end of file diff --git a/Lang/Free-Pascal-Lazarus/Boyer-Moore-string-search b/Lang/Free-Pascal-Lazarus/Boyer-Moore-string-search new file mode 120000 index 0000000000..9902c3a3ea --- /dev/null +++ b/Lang/Free-Pascal-Lazarus/Boyer-Moore-string-search @@ -0,0 +1 @@ +../../Task/Boyer-Moore-string-search/Free-Pascal-Lazarus \ No newline at end of file diff --git a/Lang/Free-Pascal-Lazarus/Brazilian-numbers b/Lang/Free-Pascal-Lazarus/Brazilian-numbers new file mode 120000 index 0000000000..2f21964a49 --- /dev/null +++ b/Lang/Free-Pascal-Lazarus/Brazilian-numbers @@ -0,0 +1 @@ +../../Task/Brazilian-numbers/Free-Pascal-Lazarus \ No newline at end of file diff --git a/Lang/Free-Pascal-Lazarus/Brilliant-numbers b/Lang/Free-Pascal-Lazarus/Brilliant-numbers new file mode 120000 index 0000000000..07a95dbd77 --- /dev/null +++ b/Lang/Free-Pascal-Lazarus/Brilliant-numbers @@ -0,0 +1 @@ +../../Task/Brilliant-numbers/Free-Pascal-Lazarus \ No newline at end of file diff --git a/Lang/Free-Pascal-Lazarus/Cistercian-numerals b/Lang/Free-Pascal-Lazarus/Cistercian-numerals new file mode 120000 index 0000000000..e09b44b1be --- /dev/null +++ b/Lang/Free-Pascal-Lazarus/Cistercian-numerals @@ -0,0 +1 @@ +../../Task/Cistercian-numerals/Free-Pascal-Lazarus \ No newline at end of file diff --git a/Lang/Free-Pascal-Lazarus/Closures-Value-capture b/Lang/Free-Pascal-Lazarus/Closures-Value-capture new file mode 120000 index 0000000000..4b2493493f --- /dev/null +++ b/Lang/Free-Pascal-Lazarus/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/Free-Pascal-Lazarus \ No newline at end of file diff --git a/Lang/Free-Pascal-Lazarus/DNS-query b/Lang/Free-Pascal-Lazarus/DNS-query new file mode 120000 index 0000000000..f7c79b4afe --- /dev/null +++ b/Lang/Free-Pascal-Lazarus/DNS-query @@ -0,0 +1 @@ +../../Task/DNS-query/Free-Pascal-Lazarus \ No newline at end of file diff --git a/Lang/Free-Pascal-Lazarus/Duffinian-numbers b/Lang/Free-Pascal-Lazarus/Duffinian-numbers new file mode 120000 index 0000000000..d54184ff4d --- /dev/null +++ b/Lang/Free-Pascal-Lazarus/Duffinian-numbers @@ -0,0 +1 @@ +../../Task/Duffinian-numbers/Free-Pascal-Lazarus \ No newline at end of file diff --git a/Lang/Free-Pascal-Lazarus/Dutch-national-flag-problem b/Lang/Free-Pascal-Lazarus/Dutch-national-flag-problem new file mode 120000 index 0000000000..da47f4535f --- /dev/null +++ b/Lang/Free-Pascal-Lazarus/Dutch-national-flag-problem @@ -0,0 +1 @@ +../../Task/Dutch-national-flag-problem/Free-Pascal-Lazarus \ No newline at end of file diff --git a/Lang/Free-Pascal-Lazarus/Ethiopian-multiplication b/Lang/Free-Pascal-Lazarus/Ethiopian-multiplication new file mode 120000 index 0000000000..845adfef13 --- /dev/null +++ b/Lang/Free-Pascal-Lazarus/Ethiopian-multiplication @@ -0,0 +1 @@ +../../Task/Ethiopian-multiplication/Free-Pascal-Lazarus \ No newline at end of file diff --git a/Lang/Free-Pascal-Lazarus/Fractal-tree b/Lang/Free-Pascal-Lazarus/Fractal-tree new file mode 120000 index 0000000000..c2081a0860 --- /dev/null +++ b/Lang/Free-Pascal-Lazarus/Fractal-tree @@ -0,0 +1 @@ +../../Task/Fractal-tree/Free-Pascal-Lazarus \ No newline at end of file diff --git a/Lang/Free-Pascal-Lazarus/Gamma-function b/Lang/Free-Pascal-Lazarus/Gamma-function new file mode 120000 index 0000000000..9c45231564 --- /dev/null +++ b/Lang/Free-Pascal-Lazarus/Gamma-function @@ -0,0 +1 @@ +../../Task/Gamma-function/Free-Pascal-Lazarus \ No newline at end of file diff --git a/Lang/Free-Pascal-Lazarus/Hickerson-series-of-almost-integers b/Lang/Free-Pascal-Lazarus/Hickerson-series-of-almost-integers new file mode 120000 index 0000000000..e8c446d1f2 --- /dev/null +++ b/Lang/Free-Pascal-Lazarus/Hickerson-series-of-almost-integers @@ -0,0 +1 @@ +../../Task/Hickerson-series-of-almost-integers/Free-Pascal-Lazarus \ No newline at end of file diff --git a/Lang/Free-Pascal-Lazarus/Kaprekar-numbers b/Lang/Free-Pascal-Lazarus/Kaprekar-numbers new file mode 120000 index 0000000000..7aca236c6b --- /dev/null +++ b/Lang/Free-Pascal-Lazarus/Kaprekar-numbers @@ -0,0 +1 @@ +../../Task/Kaprekar-numbers/Free-Pascal-Lazarus \ No newline at end of file diff --git a/Lang/Free-Pascal-Lazarus/Largest-number-divisible-by-its-digits b/Lang/Free-Pascal-Lazarus/Largest-number-divisible-by-its-digits new file mode 120000 index 0000000000..702d65adc8 --- /dev/null +++ b/Lang/Free-Pascal-Lazarus/Largest-number-divisible-by-its-digits @@ -0,0 +1 @@ +../../Task/Largest-number-divisible-by-its-digits/Free-Pascal-Lazarus \ No newline at end of file diff --git a/Lang/Free-Pascal-Lazarus/Leap-year b/Lang/Free-Pascal-Lazarus/Leap-year new file mode 120000 index 0000000000..1dc9648945 --- /dev/null +++ b/Lang/Free-Pascal-Lazarus/Leap-year @@ -0,0 +1 @@ +../../Task/Leap-year/Free-Pascal-Lazarus \ No newline at end of file diff --git a/Lang/Free-Pascal-Lazarus/Leonardo-numbers b/Lang/Free-Pascal-Lazarus/Leonardo-numbers new file mode 120000 index 0000000000..5fc9b6dc54 --- /dev/null +++ b/Lang/Free-Pascal-Lazarus/Leonardo-numbers @@ -0,0 +1 @@ +../../Task/Leonardo-numbers/Free-Pascal-Lazarus \ No newline at end of file diff --git a/Lang/Free-Pascal-Lazarus/Levenshtein-distance b/Lang/Free-Pascal-Lazarus/Levenshtein-distance new file mode 120000 index 0000000000..eebdca8158 --- /dev/null +++ b/Lang/Free-Pascal-Lazarus/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/Free-Pascal-Lazarus \ No newline at end of file diff --git a/Lang/Free-Pascal-Lazarus/Map-range b/Lang/Free-Pascal-Lazarus/Map-range new file mode 120000 index 0000000000..65b07f3cc6 --- /dev/null +++ b/Lang/Free-Pascal-Lazarus/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/Free-Pascal-Lazarus \ No newline at end of file diff --git a/Lang/Free-Pascal-Lazarus/Numbers-with-equal-rises-and-falls b/Lang/Free-Pascal-Lazarus/Numbers-with-equal-rises-and-falls new file mode 120000 index 0000000000..d3988596ad --- /dev/null +++ b/Lang/Free-Pascal-Lazarus/Numbers-with-equal-rises-and-falls @@ -0,0 +1 @@ +../../Task/Numbers-with-equal-rises-and-falls/Free-Pascal-Lazarus \ No newline at end of file diff --git a/Lang/Free-Pascal-Lazarus/Ordered-words b/Lang/Free-Pascal-Lazarus/Ordered-words new file mode 120000 index 0000000000..ec364f330e --- /dev/null +++ b/Lang/Free-Pascal-Lazarus/Ordered-words @@ -0,0 +1 @@ +../../Task/Ordered-words/Free-Pascal-Lazarus \ No newline at end of file diff --git a/Lang/Free-Pascal-Lazarus/Pancake-numbers b/Lang/Free-Pascal-Lazarus/Pancake-numbers new file mode 120000 index 0000000000..e82c81624b --- /dev/null +++ b/Lang/Free-Pascal-Lazarus/Pancake-numbers @@ -0,0 +1 @@ +../../Task/Pancake-numbers/Free-Pascal-Lazarus \ No newline at end of file diff --git a/Lang/Free-Pascal-Lazarus/Parallel-brute-force b/Lang/Free-Pascal-Lazarus/Parallel-brute-force new file mode 120000 index 0000000000..cdb4d87e7a --- /dev/null +++ b/Lang/Free-Pascal-Lazarus/Parallel-brute-force @@ -0,0 +1 @@ +../../Task/Parallel-brute-force/Free-Pascal-Lazarus \ No newline at end of file diff --git a/Lang/Free-Pascal-Lazarus/Parallel-calculations b/Lang/Free-Pascal-Lazarus/Parallel-calculations new file mode 120000 index 0000000000..191ed1dae7 --- /dev/null +++ b/Lang/Free-Pascal-Lazarus/Parallel-calculations @@ -0,0 +1 @@ +../../Task/Parallel-calculations/Free-Pascal-Lazarus \ No newline at end of file diff --git a/Lang/Free-Pascal-Lazarus/Prime-decomposition b/Lang/Free-Pascal-Lazarus/Prime-decomposition new file mode 120000 index 0000000000..358a72f6ea --- /dev/null +++ b/Lang/Free-Pascal-Lazarus/Prime-decomposition @@ -0,0 +1 @@ +../../Task/Prime-decomposition/Free-Pascal-Lazarus \ No newline at end of file diff --git a/Lang/Free-Pascal-Lazarus/Probabilistic-choice b/Lang/Free-Pascal-Lazarus/Probabilistic-choice new file mode 120000 index 0000000000..0f85f5937f --- /dev/null +++ b/Lang/Free-Pascal-Lazarus/Probabilistic-choice @@ -0,0 +1 @@ +../../Task/Probabilistic-choice/Free-Pascal-Lazarus \ No newline at end of file diff --git a/Lang/Free-Pascal-Lazarus/Sorting-algorithms-Shell-sort b/Lang/Free-Pascal-Lazarus/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..e5c8120991 --- /dev/null +++ b/Lang/Free-Pascal-Lazarus/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/Free-Pascal-Lazarus \ No newline at end of file diff --git a/Lang/Free-Pascal-Lazarus/Square-free-integers b/Lang/Free-Pascal-Lazarus/Square-free-integers new file mode 120000 index 0000000000..88fe83b6b1 --- /dev/null +++ b/Lang/Free-Pascal-Lazarus/Square-free-integers @@ -0,0 +1 @@ +../../Task/Square-free-integers/Free-Pascal-Lazarus \ No newline at end of file diff --git a/Lang/FreeBASIC/15-puzzle-solver b/Lang/FreeBASIC/15-puzzle-solver new file mode 120000 index 0000000000..aac40387ff --- /dev/null +++ b/Lang/FreeBASIC/15-puzzle-solver @@ -0,0 +1 @@ +../../Task/15-puzzle-solver/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/24-game-Solve b/Lang/FreeBASIC/24-game-Solve new file mode 120000 index 0000000000..68ad0335d9 --- /dev/null +++ b/Lang/FreeBASIC/24-game-Solve @@ -0,0 +1 @@ +../../Task/24-game-Solve/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/ADFGVX-cipher b/Lang/FreeBASIC/ADFGVX-cipher new file mode 120000 index 0000000000..43433b4959 --- /dev/null +++ b/Lang/FreeBASIC/ADFGVX-cipher @@ -0,0 +1 @@ +../../Task/ADFGVX-cipher/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/ASCII-art-diagram-converter b/Lang/FreeBASIC/ASCII-art-diagram-converter new file mode 120000 index 0000000000..f349074235 --- /dev/null +++ b/Lang/FreeBASIC/ASCII-art-diagram-converter @@ -0,0 +1 @@ +../../Task/ASCII-art-diagram-converter/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/AVL-tree b/Lang/FreeBASIC/AVL-tree new file mode 120000 index 0000000000..7500f1c637 --- /dev/null +++ b/Lang/FreeBASIC/AVL-tree @@ -0,0 +1 @@ +../../Task/AVL-tree/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Abbreviations-simple b/Lang/FreeBASIC/Abbreviations-simple new file mode 120000 index 0000000000..de9c8f171b --- /dev/null +++ b/Lang/FreeBASIC/Abbreviations-simple @@ -0,0 +1 @@ +../../Task/Abbreviations-simple/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Abelian-sandpile-model-Identity b/Lang/FreeBASIC/Abelian-sandpile-model-Identity new file mode 120000 index 0000000000..e9077c65f8 --- /dev/null +++ b/Lang/FreeBASIC/Abelian-sandpile-model-Identity @@ -0,0 +1 @@ +../../Task/Abelian-sandpile-model-Identity/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Algebraic-data-types b/Lang/FreeBASIC/Algebraic-data-types new file mode 120000 index 0000000000..f2fce8f3dc --- /dev/null +++ b/Lang/FreeBASIC/Algebraic-data-types @@ -0,0 +1 @@ +../../Task/Algebraic-data-types/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Almkvist-Giullera-formula-for-pi b/Lang/FreeBASIC/Almkvist-Giullera-formula-for-pi new file mode 120000 index 0000000000..37082cc7bb --- /dev/null +++ b/Lang/FreeBASIC/Almkvist-Giullera-formula-for-pi @@ -0,0 +1 @@ +../../Task/Almkvist-Giullera-formula-for-pi/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Arithmetic-Rational b/Lang/FreeBASIC/Arithmetic-Rational new file mode 120000 index 0000000000..3182d3a125 --- /dev/null +++ b/Lang/FreeBASIC/Arithmetic-Rational @@ -0,0 +1 @@ +../../Task/Arithmetic-Rational/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Arithmetic-derivative b/Lang/FreeBASIC/Arithmetic-derivative new file mode 120000 index 0000000000..2a22a10780 --- /dev/null +++ b/Lang/FreeBASIC/Arithmetic-derivative @@ -0,0 +1 @@ +../../Task/Arithmetic-derivative/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Associative-array-Merging b/Lang/FreeBASIC/Associative-array-Merging new file mode 120000 index 0000000000..77edeb4249 --- /dev/null +++ b/Lang/FreeBASIC/Associative-array-Merging @@ -0,0 +1 @@ +../../Task/Associative-array-Merging/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/B-zier-curves-Intersections b/Lang/FreeBASIC/B-zier-curves-Intersections new file mode 120000 index 0000000000..e1718d7dc9 --- /dev/null +++ b/Lang/FreeBASIC/B-zier-curves-Intersections @@ -0,0 +1 @@ +../../Task/B-zier-curves-Intersections/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Babylonian-spiral b/Lang/FreeBASIC/Babylonian-spiral new file mode 120000 index 0000000000..e141e5d456 --- /dev/null +++ b/Lang/FreeBASIC/Babylonian-spiral @@ -0,0 +1 @@ +../../Task/Babylonian-spiral/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Bifid-cipher b/Lang/FreeBASIC/Bifid-cipher new file mode 120000 index 0000000000..6fc87c7ae7 --- /dev/null +++ b/Lang/FreeBASIC/Bifid-cipher @@ -0,0 +1 @@ +../../Task/Bifid-cipher/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Bioinformatics-Global-alignment b/Lang/FreeBASIC/Bioinformatics-Global-alignment new file mode 120000 index 0000000000..93fb335c5b --- /dev/null +++ b/Lang/FreeBASIC/Bioinformatics-Global-alignment @@ -0,0 +1 @@ +../../Task/Bioinformatics-Global-alignment/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Bioinformatics-base-count b/Lang/FreeBASIC/Bioinformatics-base-count deleted file mode 120000 index 89403f2018..0000000000 --- a/Lang/FreeBASIC/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Bitcoin-public-point-to-address b/Lang/FreeBASIC/Bitcoin-public-point-to-address new file mode 120000 index 0000000000..6ff9b61a5b --- /dev/null +++ b/Lang/FreeBASIC/Bitcoin-public-point-to-address @@ -0,0 +1 @@ +../../Task/Bitcoin-public-point-to-address/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Bitmap-Histogram b/Lang/FreeBASIC/Bitmap-Histogram new file mode 120000 index 0000000000..dc9da15219 --- /dev/null +++ b/Lang/FreeBASIC/Bitmap-Histogram @@ -0,0 +1 @@ +../../Task/Bitmap-Histogram/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Bitmap-PPM-conversion-through-a-pipe b/Lang/FreeBASIC/Bitmap-PPM-conversion-through-a-pipe new file mode 120000 index 0000000000..9082778f9e --- /dev/null +++ b/Lang/FreeBASIC/Bitmap-PPM-conversion-through-a-pipe @@ -0,0 +1 @@ +../../Task/Bitmap-PPM-conversion-through-a-pipe/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Bitmap-Read-an-image-through-a-pipe b/Lang/FreeBASIC/Bitmap-Read-an-image-through-a-pipe new file mode 120000 index 0000000000..17dd1b6040 --- /dev/null +++ b/Lang/FreeBASIC/Bitmap-Read-an-image-through-a-pipe @@ -0,0 +1 @@ +../../Task/Bitmap-Read-an-image-through-a-pipe/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Bitmap-Write-a-PPM-file b/Lang/FreeBASIC/Bitmap-Write-a-PPM-file new file mode 120000 index 0000000000..91057d85e5 --- /dev/null +++ b/Lang/FreeBASIC/Bitmap-Write-a-PPM-file @@ -0,0 +1 @@ +../../Task/Bitmap-Write-a-PPM-file/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Brace-expansion b/Lang/FreeBASIC/Brace-expansion new file mode 120000 index 0000000000..b08a413ab2 --- /dev/null +++ b/Lang/FreeBASIC/Brace-expansion @@ -0,0 +1 @@ +../../Task/Brace-expansion/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Bulls-and-cows-Player b/Lang/FreeBASIC/Bulls-and-cows-Player new file mode 120000 index 0000000000..3f30549ded --- /dev/null +++ b/Lang/FreeBASIC/Bulls-and-cows-Player @@ -0,0 +1 @@ +../../Task/Bulls-and-cows-Player/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Calkin-Wilf-sequence b/Lang/FreeBASIC/Calkin-Wilf-sequence deleted file mode 120000 index 0cfeafa7e2..0000000000 --- a/Lang/FreeBASIC/Calkin-Wilf-sequence +++ /dev/null @@ -1 +0,0 @@ -../../Task/Calkin-Wilf-sequence/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Canny-edge-detector b/Lang/FreeBASIC/Canny-edge-detector new file mode 120000 index 0000000000..17dd124847 --- /dev/null +++ b/Lang/FreeBASIC/Canny-edge-detector @@ -0,0 +1 @@ +../../Task/Canny-edge-detector/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Catmull-Clark-subdivision-surface b/Lang/FreeBASIC/Catmull-Clark-subdivision-surface new file mode 120000 index 0000000000..aa2f6e5ed9 --- /dev/null +++ b/Lang/FreeBASIC/Catmull-Clark-subdivision-surface @@ -0,0 +1 @@ +../../Task/Catmull-Clark-subdivision-surface/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Chat-server b/Lang/FreeBASIC/Chat-server new file mode 120000 index 0000000000..59f06de348 --- /dev/null +++ b/Lang/FreeBASIC/Chat-server @@ -0,0 +1 @@ +../../Task/Chat-server/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Cistercian-numerals b/Lang/FreeBASIC/Cistercian-numerals new file mode 120000 index 0000000000..ceb56b6604 --- /dev/null +++ b/Lang/FreeBASIC/Cistercian-numerals @@ -0,0 +1 @@ +../../Task/Cistercian-numerals/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Color-quantization b/Lang/FreeBASIC/Color-quantization new file mode 120000 index 0000000000..ddc5eaabb7 --- /dev/null +++ b/Lang/FreeBASIC/Color-quantization @@ -0,0 +1 @@ +../../Task/Color-quantization/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Colorful-numbers b/Lang/FreeBASIC/Colorful-numbers new file mode 120000 index 0000000000..dcf0a876c1 --- /dev/null +++ b/Lang/FreeBASIC/Colorful-numbers @@ -0,0 +1 @@ +../../Task/Colorful-numbers/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Compiler-AST-interpreter b/Lang/FreeBASIC/Compiler-AST-interpreter new file mode 120000 index 0000000000..ea89d91369 --- /dev/null +++ b/Lang/FreeBASIC/Compiler-AST-interpreter @@ -0,0 +1 @@ +../../Task/Compiler-AST-interpreter/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Compiler-code-generator b/Lang/FreeBASIC/Compiler-code-generator new file mode 120000 index 0000000000..836b1482c2 --- /dev/null +++ b/Lang/FreeBASIC/Compiler-code-generator @@ -0,0 +1 @@ +../../Task/Compiler-code-generator/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Compiler-syntax-analyzer b/Lang/FreeBASIC/Compiler-syntax-analyzer new file mode 120000 index 0000000000..a7d7204b01 --- /dev/null +++ b/Lang/FreeBASIC/Compiler-syntax-analyzer @@ -0,0 +1 @@ +../../Task/Compiler-syntax-analyzer/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Compiler-virtual-machine-interpreter b/Lang/FreeBASIC/Compiler-virtual-machine-interpreter new file mode 120000 index 0000000000..18e70488f2 --- /dev/null +++ b/Lang/FreeBASIC/Compiler-virtual-machine-interpreter @@ -0,0 +1 @@ +../../Task/Compiler-virtual-machine-interpreter/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Constrained-genericity b/Lang/FreeBASIC/Constrained-genericity new file mode 120000 index 0000000000..1fc68e6907 --- /dev/null +++ b/Lang/FreeBASIC/Constrained-genericity @@ -0,0 +1 @@ +../../Task/Constrained-genericity/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- b/Lang/FreeBASIC/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- new file mode 120000 index 0000000000..e2defb3109 --- /dev/null +++ b/Lang/FreeBASIC/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n-/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Cut-a-rectangle b/Lang/FreeBASIC/Cut-a-rectangle new file mode 120000 index 0000000000..16e664db93 --- /dev/null +++ b/Lang/FreeBASIC/Cut-a-rectangle @@ -0,0 +1 @@ +../../Task/Cut-a-rectangle/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Cyclotomic-polynomial b/Lang/FreeBASIC/Cyclotomic-polynomial new file mode 120000 index 0000000000..82e1fdeb03 --- /dev/null +++ b/Lang/FreeBASIC/Cyclotomic-polynomial @@ -0,0 +1 @@ +../../Task/Cyclotomic-polynomial/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/De-Bruijn-sequences b/Lang/FreeBASIC/De-Bruijn-sequences new file mode 120000 index 0000000000..2f6e2651ca --- /dev/null +++ b/Lang/FreeBASIC/De-Bruijn-sequences @@ -0,0 +1 @@ +../../Task/De-Bruijn-sequences/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Death-Star b/Lang/FreeBASIC/Death-Star new file mode 120000 index 0000000000..b45f2416c8 --- /dev/null +++ b/Lang/FreeBASIC/Death-Star @@ -0,0 +1 @@ +../../Task/Death-Star/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Deconvolution-2D+ b/Lang/FreeBASIC/Deconvolution-2D+ new file mode 120000 index 0000000000..2a10e72230 --- /dev/null +++ b/Lang/FreeBASIC/Deconvolution-2D+ @@ -0,0 +1 @@ +../../Task/Deconvolution-2D+/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Dijkstras-algorithm b/Lang/FreeBASIC/Dijkstras-algorithm new file mode 120000 index 0000000000..4465c347e7 --- /dev/null +++ b/Lang/FreeBASIC/Dijkstras-algorithm @@ -0,0 +1 @@ +../../Task/Dijkstras-algorithm/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Dining-philosophers b/Lang/FreeBASIC/Dining-philosophers new file mode 120000 index 0000000000..5d616c69b5 --- /dev/null +++ b/Lang/FreeBASIC/Dining-philosophers @@ -0,0 +1 @@ +../../Task/Dining-philosophers/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Display-an-outline-as-a-nested-table b/Lang/FreeBASIC/Display-an-outline-as-a-nested-table new file mode 120000 index 0000000000..e1fe23aa03 --- /dev/null +++ b/Lang/FreeBASIC/Display-an-outline-as-a-nested-table @@ -0,0 +1 @@ +../../Task/Display-an-outline-as-a-nested-table/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Distance-and-Bearing b/Lang/FreeBASIC/Distance-and-Bearing new file mode 120000 index 0000000000..14b1500a35 --- /dev/null +++ b/Lang/FreeBASIC/Distance-and-Bearing @@ -0,0 +1 @@ +../../Task/Distance-and-Bearing/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Distributed-programming b/Lang/FreeBASIC/Distributed-programming new file mode 120000 index 0000000000..3c9ea14752 --- /dev/null +++ b/Lang/FreeBASIC/Distributed-programming @@ -0,0 +1 @@ +../../Task/Distributed-programming/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Distribution-of-0-digits-in-factorial-series b/Lang/FreeBASIC/Distribution-of-0-digits-in-factorial-series new file mode 120000 index 0000000000..caef600e25 --- /dev/null +++ b/Lang/FreeBASIC/Distribution-of-0-digits-in-factorial-series @@ -0,0 +1 @@ +../../Task/Distribution-of-0-digits-in-factorial-series/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Dominoes b/Lang/FreeBASIC/Dominoes new file mode 120000 index 0000000000..46d9dcf5f4 --- /dev/null +++ b/Lang/FreeBASIC/Dominoes @@ -0,0 +1 @@ +../../Task/Dominoes/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Echo-server b/Lang/FreeBASIC/Echo-server new file mode 120000 index 0000000000..af11371400 --- /dev/null +++ b/Lang/FreeBASIC/Echo-server @@ -0,0 +1 @@ +../../Task/Echo-server/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Elementary-cellular-automaton-Infinite-length b/Lang/FreeBASIC/Elementary-cellular-automaton-Infinite-length new file mode 120000 index 0000000000..ab22fce8e1 --- /dev/null +++ b/Lang/FreeBASIC/Elementary-cellular-automaton-Infinite-length @@ -0,0 +1 @@ +../../Task/Elementary-cellular-automaton-Infinite-length/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Elliptic-curve-arithmetic b/Lang/FreeBASIC/Elliptic-curve-arithmetic new file mode 120000 index 0000000000..ab0b3f0aed --- /dev/null +++ b/Lang/FreeBASIC/Elliptic-curve-arithmetic @@ -0,0 +1 @@ +../../Task/Elliptic-curve-arithmetic/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Executable-library b/Lang/FreeBASIC/Executable-library new file mode 120000 index 0000000000..ece6e47b6f --- /dev/null +++ b/Lang/FreeBASIC/Executable-library @@ -0,0 +1 @@ +../../Task/Executable-library/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Execute-Computer-Zero b/Lang/FreeBASIC/Execute-Computer-Zero new file mode 120000 index 0000000000..018dffe9b4 --- /dev/null +++ b/Lang/FreeBASIC/Execute-Computer-Zero @@ -0,0 +1 @@ +../../Task/Execute-Computer-Zero/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Execute-SNUSP b/Lang/FreeBASIC/Execute-SNUSP new file mode 120000 index 0000000000..7b179aedb8 --- /dev/null +++ b/Lang/FreeBASIC/Execute-SNUSP @@ -0,0 +1 @@ +../../Task/Execute-SNUSP/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Execute-a-Markov-algorithm b/Lang/FreeBASIC/Execute-a-Markov-algorithm new file mode 120000 index 0000000000..7f61263c19 --- /dev/null +++ b/Lang/FreeBASIC/Execute-a-Markov-algorithm @@ -0,0 +1 @@ +../../Task/Execute-a-Markov-algorithm/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Faces-from-a-mesh b/Lang/FreeBASIC/Faces-from-a-mesh new file mode 120000 index 0000000000..33d860451f --- /dev/null +++ b/Lang/FreeBASIC/Faces-from-a-mesh @@ -0,0 +1 @@ +../../Task/Faces-from-a-mesh/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Factorial-base-numbers-indexing-permutations-of-a-collection b/Lang/FreeBASIC/Factorial-base-numbers-indexing-permutations-of-a-collection new file mode 120000 index 0000000000..1f2b24105a --- /dev/null +++ b/Lang/FreeBASIC/Factorial-base-numbers-indexing-permutations-of-a-collection @@ -0,0 +1 @@ +../../Task/Factorial-base-numbers-indexing-permutations-of-a-collection/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Fermat-numbers b/Lang/FreeBASIC/Fermat-numbers new file mode 120000 index 0000000000..b6ff867057 --- /dev/null +++ b/Lang/FreeBASIC/Fermat-numbers @@ -0,0 +1 @@ +../../Task/Fermat-numbers/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/File-size-distribution b/Lang/FreeBASIC/File-size-distribution new file mode 120000 index 0000000000..fa04d214bc --- /dev/null +++ b/Lang/FreeBASIC/File-size-distribution @@ -0,0 +1 @@ +../../Task/File-size-distribution/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Find-duplicate-files b/Lang/FreeBASIC/Find-duplicate-files new file mode 120000 index 0000000000..f2becdf037 --- /dev/null +++ b/Lang/FreeBASIC/Find-duplicate-files @@ -0,0 +1 @@ +../../Task/Find-duplicate-files/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Find-largest-left-truncatable-prime-in-a-given-base b/Lang/FreeBASIC/Find-largest-left-truncatable-prime-in-a-given-base new file mode 120000 index 0000000000..90493830d8 --- /dev/null +++ b/Lang/FreeBASIC/Find-largest-left-truncatable-prime-in-a-given-base @@ -0,0 +1 @@ +../../Task/Find-largest-left-truncatable-prime-in-a-given-base/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Four-is-the-number-of-letters-in-the-... b/Lang/FreeBASIC/Four-is-the-number-of-letters-in-the-... new file mode 120000 index 0000000000..7c1f37136c --- /dev/null +++ b/Lang/FreeBASIC/Four-is-the-number-of-letters-in-the-... @@ -0,0 +1 @@ +../../Task/Four-is-the-number-of-letters-in-the-.../FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Fraction-reduction b/Lang/FreeBASIC/Fraction-reduction new file mode 120000 index 0000000000..fe901cf96d --- /dev/null +++ b/Lang/FreeBASIC/Fraction-reduction @@ -0,0 +1 @@ +../../Task/Fraction-reduction/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Functional-coverage-tree b/Lang/FreeBASIC/Functional-coverage-tree new file mode 120000 index 0000000000..03b730b6d0 --- /dev/null +++ b/Lang/FreeBASIC/Functional-coverage-tree @@ -0,0 +1 @@ +../../Task/Functional-coverage-tree/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Galton-box-animation b/Lang/FreeBASIC/Galton-box-animation new file mode 120000 index 0000000000..d8550e96b6 --- /dev/null +++ b/Lang/FreeBASIC/Galton-box-animation @@ -0,0 +1 @@ +../../Task/Galton-box-animation/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Gotchas b/Lang/FreeBASIC/Gotchas new file mode 120000 index 0000000000..152b1da45f --- /dev/null +++ b/Lang/FreeBASIC/Gotchas @@ -0,0 +1 @@ +../../Task/Gotchas/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Graph-colouring b/Lang/FreeBASIC/Graph-colouring new file mode 120000 index 0000000000..2b6f6e444d --- /dev/null +++ b/Lang/FreeBASIC/Graph-colouring @@ -0,0 +1 @@ +../../Task/Graph-colouring/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/HTTPS b/Lang/FreeBASIC/HTTPS new file mode 120000 index 0000000000..ffa1e6ee82 --- /dev/null +++ b/Lang/FreeBASIC/HTTPS @@ -0,0 +1 @@ +../../Task/HTTPS/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/HTTPS-Authenticated b/Lang/FreeBASIC/HTTPS-Authenticated new file mode 120000 index 0000000000..3da86c1cef --- /dev/null +++ b/Lang/FreeBASIC/HTTPS-Authenticated @@ -0,0 +1 @@ +../../Task/HTTPS-Authenticated/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/HTTPS-Client-authenticated b/Lang/FreeBASIC/HTTPS-Client-authenticated new file mode 120000 index 0000000000..8c2cbfcd86 --- /dev/null +++ b/Lang/FreeBASIC/HTTPS-Client-authenticated @@ -0,0 +1 @@ +../../Task/HTTPS-Client-authenticated/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Hello-world-Web-server b/Lang/FreeBASIC/Hello-world-Web-server new file mode 120000 index 0000000000..25d52ccee6 --- /dev/null +++ b/Lang/FreeBASIC/Hello-world-Web-server @@ -0,0 +1 @@ +../../Task/Hello-world-Web-server/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Hex-words b/Lang/FreeBASIC/Hex-words new file mode 120000 index 0000000000..fa25607a2e --- /dev/null +++ b/Lang/FreeBASIC/Hex-words @@ -0,0 +1 @@ +../../Task/Hex-words/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/History-variables b/Lang/FreeBASIC/History-variables new file mode 120000 index 0000000000..68f4bcd858 --- /dev/null +++ b/Lang/FreeBASIC/History-variables @@ -0,0 +1 @@ +../../Task/History-variables/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Honeycombs b/Lang/FreeBASIC/Honeycombs new file mode 120000 index 0000000000..12b1cd0046 --- /dev/null +++ b/Lang/FreeBASIC/Honeycombs @@ -0,0 +1 @@ +../../Task/Honeycombs/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Hough-transform b/Lang/FreeBASIC/Hough-transform new file mode 120000 index 0000000000..b825046529 --- /dev/null +++ b/Lang/FreeBASIC/Hough-transform @@ -0,0 +1 @@ +../../Task/Hough-transform/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Im-a-software-engineer-get-me-out-of-here b/Lang/FreeBASIC/Im-a-software-engineer-get-me-out-of-here new file mode 120000 index 0000000000..2169aad43b --- /dev/null +++ b/Lang/FreeBASIC/Im-a-software-engineer-get-me-out-of-here @@ -0,0 +1 @@ +../../Task/Im-a-software-engineer-get-me-out-of-here/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Image-convolution b/Lang/FreeBASIC/Image-convolution new file mode 120000 index 0000000000..5f1451fadd --- /dev/null +++ b/Lang/FreeBASIC/Image-convolution @@ -0,0 +1 @@ +../../Task/Image-convolution/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Imaginary-base-numbers b/Lang/FreeBASIC/Imaginary-base-numbers new file mode 120000 index 0000000000..00ee9d8fe6 --- /dev/null +++ b/Lang/FreeBASIC/Imaginary-base-numbers @@ -0,0 +1 @@ +../../Task/Imaginary-base-numbers/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Intersecting-number-wheels b/Lang/FreeBASIC/Intersecting-number-wheels new file mode 120000 index 0000000000..42313ae624 --- /dev/null +++ b/Lang/FreeBASIC/Intersecting-number-wheels @@ -0,0 +1 @@ +../../Task/Intersecting-number-wheels/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Inverted-index b/Lang/FreeBASIC/Inverted-index new file mode 120000 index 0000000000..affc1bf23c --- /dev/null +++ b/Lang/FreeBASIC/Inverted-index @@ -0,0 +1 @@ +../../Task/Inverted-index/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Isograms-and-heterograms b/Lang/FreeBASIC/Isograms-and-heterograms new file mode 120000 index 0000000000..c142330285 --- /dev/null +++ b/Lang/FreeBASIC/Isograms-and-heterograms @@ -0,0 +1 @@ +../../Task/Isograms-and-heterograms/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Jaro-Winkler-distance b/Lang/FreeBASIC/Jaro-Winkler-distance new file mode 120000 index 0000000000..567e61dfba --- /dev/null +++ b/Lang/FreeBASIC/Jaro-Winkler-distance @@ -0,0 +1 @@ +../../Task/Jaro-Winkler-distance/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Juggler-sequence b/Lang/FreeBASIC/Juggler-sequence new file mode 120000 index 0000000000..5aaf9a794f --- /dev/null +++ b/Lang/FreeBASIC/Juggler-sequence @@ -0,0 +1 @@ +../../Task/Juggler-sequence/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/K-d-tree b/Lang/FreeBASIC/K-d-tree new file mode 120000 index 0000000000..f6319abaa1 --- /dev/null +++ b/Lang/FreeBASIC/K-d-tree @@ -0,0 +1 @@ +../../Task/K-d-tree/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Knuths-algorithm-S b/Lang/FreeBASIC/Knuths-algorithm-S new file mode 120000 index 0000000000..720a4a3a7e --- /dev/null +++ b/Lang/FreeBASIC/Knuths-algorithm-S @@ -0,0 +1 @@ +../../Task/Knuths-algorithm-S/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Knuths-power-tree b/Lang/FreeBASIC/Knuths-power-tree new file mode 120000 index 0000000000..b6075609dd --- /dev/null +++ b/Lang/FreeBASIC/Knuths-power-tree @@ -0,0 +1 @@ +../../Task/Knuths-power-tree/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Kolakoski-sequence b/Lang/FreeBASIC/Kolakoski-sequence new file mode 120000 index 0000000000..fce085b91c --- /dev/null +++ b/Lang/FreeBASIC/Kolakoski-sequence @@ -0,0 +1 @@ +../../Task/Kolakoski-sequence/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Kosaraju b/Lang/FreeBASIC/Kosaraju new file mode 120000 index 0000000000..b8d8396338 --- /dev/null +++ b/Lang/FreeBASIC/Kosaraju @@ -0,0 +1 @@ +../../Task/Kosaraju/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/LU-decomposition b/Lang/FreeBASIC/LU-decomposition new file mode 120000 index 0000000000..a239ac6c87 --- /dev/null +++ b/Lang/FreeBASIC/LU-decomposition @@ -0,0 +1 @@ +../../Task/LU-decomposition/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Last-letter-first-letter b/Lang/FreeBASIC/Last-letter-first-letter new file mode 120000 index 0000000000..436ebfb8b9 --- /dev/null +++ b/Lang/FreeBASIC/Last-letter-first-letter @@ -0,0 +1 @@ +../../Task/Last-letter-first-letter/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Latin-Squares-in-reduced-form b/Lang/FreeBASIC/Latin-Squares-in-reduced-form new file mode 120000 index 0000000000..db9e5d8a88 --- /dev/null +++ b/Lang/FreeBASIC/Latin-Squares-in-reduced-form @@ -0,0 +1 @@ +../../Task/Latin-Squares-in-reduced-form/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/List-rooted-trees b/Lang/FreeBASIC/List-rooted-trees new file mode 120000 index 0000000000..d641d1dcf0 --- /dev/null +++ b/Lang/FreeBASIC/List-rooted-trees @@ -0,0 +1 @@ +../../Task/List-rooted-trees/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Lucky-and-even-lucky-numbers b/Lang/FreeBASIC/Lucky-and-even-lucky-numbers new file mode 120000 index 0000000000..ab68b27195 --- /dev/null +++ b/Lang/FreeBASIC/Lucky-and-even-lucky-numbers @@ -0,0 +1 @@ +../../Task/Lucky-and-even-lucky-numbers/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Mayan-calendar b/Lang/FreeBASIC/Mayan-calendar new file mode 120000 index 0000000000..4de11e93f6 --- /dev/null +++ b/Lang/FreeBASIC/Mayan-calendar @@ -0,0 +1 @@ +../../Task/Mayan-calendar/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Maze-solving b/Lang/FreeBASIC/Maze-solving new file mode 120000 index 0000000000..2140d087ef --- /dev/null +++ b/Lang/FreeBASIC/Maze-solving @@ -0,0 +1 @@ +../../Task/Maze-solving/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Median-filter b/Lang/FreeBASIC/Median-filter new file mode 120000 index 0000000000..a0d5eec8a2 --- /dev/null +++ b/Lang/FreeBASIC/Median-filter @@ -0,0 +1 @@ +../../Task/Median-filter/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Meissel-Mertens-constant b/Lang/FreeBASIC/Meissel-Mertens-constant deleted file mode 120000 index f9f037c2ea..0000000000 --- a/Lang/FreeBASIC/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Metallic-ratios b/Lang/FreeBASIC/Metallic-ratios new file mode 120000 index 0000000000..46551c0b17 --- /dev/null +++ b/Lang/FreeBASIC/Metallic-ratios @@ -0,0 +1 @@ +../../Task/Metallic-ratios/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Miller-Rabin-primality-test b/Lang/FreeBASIC/Miller-Rabin-primality-test deleted file mode 120000 index 31ca057e36..0000000000 --- a/Lang/FreeBASIC/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Multiplicative-order b/Lang/FreeBASIC/Multiplicative-order new file mode 120000 index 0000000000..1ba98d9611 --- /dev/null +++ b/Lang/FreeBASIC/Multiplicative-order @@ -0,0 +1 @@ +../../Task/Multiplicative-order/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/N-smooth-numbers b/Lang/FreeBASIC/N-smooth-numbers new file mode 120000 index 0000000000..7dad0a8519 --- /dev/null +++ b/Lang/FreeBASIC/N-smooth-numbers @@ -0,0 +1 @@ +../../Task/N-smooth-numbers/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Natural-sorting b/Lang/FreeBASIC/Natural-sorting new file mode 120000 index 0000000000..00267c2e93 --- /dev/null +++ b/Lang/FreeBASIC/Natural-sorting @@ -0,0 +1 @@ +../../Task/Natural-sorting/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Nested-templated-data b/Lang/FreeBASIC/Nested-templated-data new file mode 120000 index 0000000000..064256a2d8 --- /dev/null +++ b/Lang/FreeBASIC/Nested-templated-data @@ -0,0 +1 @@ +../../Task/Nested-templated-data/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Non-transitive-dice b/Lang/FreeBASIC/Non-transitive-dice new file mode 120000 index 0000000000..a320f65fd4 --- /dev/null +++ b/Lang/FreeBASIC/Non-transitive-dice @@ -0,0 +1 @@ +../../Task/Non-transitive-dice/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Nonoblock b/Lang/FreeBASIC/Nonoblock new file mode 120000 index 0000000000..18e71abc62 --- /dev/null +++ b/Lang/FreeBASIC/Nonoblock @@ -0,0 +1 @@ +../../Task/Nonoblock/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Numerical-and-alphabetical-suffixes b/Lang/FreeBASIC/Numerical-and-alphabetical-suffixes new file mode 120000 index 0000000000..f6a2f778c0 --- /dev/null +++ b/Lang/FreeBASIC/Numerical-and-alphabetical-suffixes @@ -0,0 +1 @@ +../../Task/Numerical-and-alphabetical-suffixes/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/OLE-automation b/Lang/FreeBASIC/OLE-automation new file mode 120000 index 0000000000..eb6c2ccae6 --- /dev/null +++ b/Lang/FreeBASIC/OLE-automation @@ -0,0 +1 @@ +../../Task/OLE-automation/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Order-disjoint-list-items b/Lang/FreeBASIC/Order-disjoint-list-items new file mode 120000 index 0000000000..d5dc6c71fd --- /dev/null +++ b/Lang/FreeBASIC/Order-disjoint-list-items @@ -0,0 +1 @@ +../../Task/Order-disjoint-list-items/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/P-value-correction b/Lang/FreeBASIC/P-value-correction new file mode 120000 index 0000000000..a2f7c2e1e2 --- /dev/null +++ b/Lang/FreeBASIC/P-value-correction @@ -0,0 +1 @@ +../../Task/P-value-correction/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Padovan-sequence b/Lang/FreeBASIC/Padovan-sequence new file mode 120000 index 0000000000..efb5ea56df --- /dev/null +++ b/Lang/FreeBASIC/Padovan-sequence @@ -0,0 +1 @@ +../../Task/Padovan-sequence/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Parse-an-IP-Address b/Lang/FreeBASIC/Parse-an-IP-Address new file mode 120000 index 0000000000..4b51728d74 --- /dev/null +++ b/Lang/FreeBASIC/Parse-an-IP-Address @@ -0,0 +1 @@ +../../Task/Parse-an-IP-Address/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Parsing-RPN-to-infix-conversion b/Lang/FreeBASIC/Parsing-RPN-to-infix-conversion new file mode 120000 index 0000000000..d524880dde --- /dev/null +++ b/Lang/FreeBASIC/Parsing-RPN-to-infix-conversion @@ -0,0 +1 @@ +../../Task/Parsing-RPN-to-infix-conversion/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Parsing-Shunting-yard-algorithm b/Lang/FreeBASIC/Parsing-Shunting-yard-algorithm new file mode 120000 index 0000000000..c598b75c18 --- /dev/null +++ b/Lang/FreeBASIC/Parsing-Shunting-yard-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-Shunting-yard-algorithm/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Particle-fountain b/Lang/FreeBASIC/Particle-fountain new file mode 120000 index 0000000000..e93e8b964f --- /dev/null +++ b/Lang/FreeBASIC/Particle-fountain @@ -0,0 +1 @@ +../../Task/Particle-fountain/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Partition-an-integer-x-into-n-primes b/Lang/FreeBASIC/Partition-an-integer-x-into-n-primes new file mode 120000 index 0000000000..1e3ac14a3f --- /dev/null +++ b/Lang/FreeBASIC/Partition-an-integer-x-into-n-primes @@ -0,0 +1 @@ +../../Task/Partition-an-integer-x-into-n-primes/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Pentagram b/Lang/FreeBASIC/Pentagram new file mode 120000 index 0000000000..60996db876 --- /dev/null +++ b/Lang/FreeBASIC/Pentagram @@ -0,0 +1 @@ +../../Task/Pentagram/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Pentomino-tiling b/Lang/FreeBASIC/Pentomino-tiling new file mode 120000 index 0000000000..684a3829b3 --- /dev/null +++ b/Lang/FreeBASIC/Pentomino-tiling @@ -0,0 +1 @@ +../../Task/Pentomino-tiling/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Percentage-difference-between-images b/Lang/FreeBASIC/Percentage-difference-between-images new file mode 120000 index 0000000000..4b5a28d9b2 --- /dev/null +++ b/Lang/FreeBASIC/Percentage-difference-between-images @@ -0,0 +1 @@ +../../Task/Percentage-difference-between-images/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Percolation-Bond-percolation b/Lang/FreeBASIC/Percolation-Bond-percolation new file mode 120000 index 0000000000..15d6381502 --- /dev/null +++ b/Lang/FreeBASIC/Percolation-Bond-percolation @@ -0,0 +1 @@ +../../Task/Percolation-Bond-percolation/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Percolation-Mean-cluster-density b/Lang/FreeBASIC/Percolation-Mean-cluster-density new file mode 120000 index 0000000000..6d9dff89ca --- /dev/null +++ b/Lang/FreeBASIC/Percolation-Mean-cluster-density @@ -0,0 +1 @@ +../../Task/Percolation-Mean-cluster-density/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Peripheral-drift-illusion b/Lang/FreeBASIC/Peripheral-drift-illusion new file mode 120000 index 0000000000..8fbf1d3fb4 --- /dev/null +++ b/Lang/FreeBASIC/Peripheral-drift-illusion @@ -0,0 +1 @@ +../../Task/Peripheral-drift-illusion/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Pig-the-dice-game-Player b/Lang/FreeBASIC/Pig-the-dice-game-Player new file mode 120000 index 0000000000..5766e4e5d7 --- /dev/null +++ b/Lang/FreeBASIC/Pig-the-dice-game-Player @@ -0,0 +1 @@ +../../Task/Pig-the-dice-game-Player/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Pinstripe-Printer b/Lang/FreeBASIC/Pinstripe-Printer new file mode 120000 index 0000000000..be78fdd396 --- /dev/null +++ b/Lang/FreeBASIC/Pinstripe-Printer @@ -0,0 +1 @@ +../../Task/Pinstripe-Printer/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Pisano-period b/Lang/FreeBASIC/Pisano-period new file mode 120000 index 0000000000..33961710c0 --- /dev/null +++ b/Lang/FreeBASIC/Pisano-period @@ -0,0 +1 @@ +../../Task/Pisano-period/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Play-recorded-sounds b/Lang/FreeBASIC/Play-recorded-sounds new file mode 120000 index 0000000000..a80641ee64 --- /dev/null +++ b/Lang/FreeBASIC/Play-recorded-sounds @@ -0,0 +1 @@ +../../Task/Play-recorded-sounds/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Primes---allocate-descendants-to-their-ancestors b/Lang/FreeBASIC/Primes---allocate-descendants-to-their-ancestors new file mode 120000 index 0000000000..49848d0592 --- /dev/null +++ b/Lang/FreeBASIC/Primes---allocate-descendants-to-their-ancestors @@ -0,0 +1 @@ +../../Task/Primes---allocate-descendants-to-their-ancestors/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Pseudo-random-numbers-Combined-recursive-generator-MRG32k3a b/Lang/FreeBASIC/Pseudo-random-numbers-Combined-recursive-generator-MRG32k3a new file mode 120000 index 0000000000..a870f104af --- /dev/null +++ b/Lang/FreeBASIC/Pseudo-random-numbers-Combined-recursive-generator-MRG32k3a @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-Combined-recursive-generator-MRG32k3a/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Pseudo-random-numbers-PCG32 b/Lang/FreeBASIC/Pseudo-random-numbers-PCG32 new file mode 120000 index 0000000000..8a007fed91 --- /dev/null +++ b/Lang/FreeBASIC/Pseudo-random-numbers-PCG32 @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-PCG32/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Pseudo-random-numbers-Splitmix64 b/Lang/FreeBASIC/Pseudo-random-numbers-Splitmix64 new file mode 120000 index 0000000000..233c73713f --- /dev/null +++ b/Lang/FreeBASIC/Pseudo-random-numbers-Splitmix64 @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-Splitmix64/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Pseudo-random-numbers-Xorshift-star b/Lang/FreeBASIC/Pseudo-random-numbers-Xorshift-star new file mode 120000 index 0000000000..a40446f6c8 --- /dev/null +++ b/Lang/FreeBASIC/Pseudo-random-numbers-Xorshift-star @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-Xorshift-star/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/QR-decomposition b/Lang/FreeBASIC/QR-decomposition new file mode 120000 index 0000000000..b4e25e341a --- /dev/null +++ b/Lang/FreeBASIC/QR-decomposition @@ -0,0 +1 @@ +../../Task/QR-decomposition/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Quaternion-type b/Lang/FreeBASIC/Quaternion-type deleted file mode 120000 index f82c3a440e..0000000000 --- a/Lang/FreeBASIC/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Random-sentence-from-book b/Lang/FreeBASIC/Random-sentence-from-book new file mode 120000 index 0000000000..9834480618 --- /dev/null +++ b/Lang/FreeBASIC/Random-sentence-from-book @@ -0,0 +1 @@ +../../Task/Random-sentence-from-book/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Reflection-List-methods b/Lang/FreeBASIC/Reflection-List-methods new file mode 120000 index 0000000000..c065c312ec --- /dev/null +++ b/Lang/FreeBASIC/Reflection-List-methods @@ -0,0 +1 @@ +../../Task/Reflection-List-methods/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Reflection-List-properties b/Lang/FreeBASIC/Reflection-List-properties new file mode 120000 index 0000000000..0fd1a0e61e --- /dev/null +++ b/Lang/FreeBASIC/Reflection-List-properties @@ -0,0 +1 @@ +../../Task/Reflection-List-properties/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Rendezvous b/Lang/FreeBASIC/Rendezvous new file mode 120000 index 0000000000..1f852cdb53 --- /dev/null +++ b/Lang/FreeBASIC/Rendezvous @@ -0,0 +1 @@ +../../Task/Rendezvous/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Repunit-primes b/Lang/FreeBASIC/Repunit-primes new file mode 120000 index 0000000000..f9270140df --- /dev/null +++ b/Lang/FreeBASIC/Repunit-primes @@ -0,0 +1 @@ +../../Task/Repunit-primes/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Rosetta-Code-Count-examples b/Lang/FreeBASIC/Rosetta-Code-Count-examples new file mode 120000 index 0000000000..c38f53ad75 --- /dev/null +++ b/Lang/FreeBASIC/Rosetta-Code-Count-examples @@ -0,0 +1 @@ +../../Task/Rosetta-Code-Count-examples/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Rosetta-Code-Find-bare-lang-tags b/Lang/FreeBASIC/Rosetta-Code-Find-bare-lang-tags new file mode 120000 index 0000000000..c9a2ddc646 --- /dev/null +++ b/Lang/FreeBASIC/Rosetta-Code-Find-bare-lang-tags @@ -0,0 +1 @@ +../../Task/Rosetta-Code-Find-bare-lang-tags/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Rosetta-Code-Find-unimplemented-tasks b/Lang/FreeBASIC/Rosetta-Code-Find-unimplemented-tasks new file mode 120000 index 0000000000..3f89d2cb42 --- /dev/null +++ b/Lang/FreeBASIC/Rosetta-Code-Find-unimplemented-tasks @@ -0,0 +1 @@ +../../Task/Rosetta-Code-Find-unimplemented-tasks/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Rosetta-Code-Fix-code-tags b/Lang/FreeBASIC/Rosetta-Code-Fix-code-tags new file mode 120000 index 0000000000..53b438e29f --- /dev/null +++ b/Lang/FreeBASIC/Rosetta-Code-Fix-code-tags @@ -0,0 +1 @@ +../../Task/Rosetta-Code-Fix-code-tags/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Rosetta-Code-Rank-languages-by-popularity b/Lang/FreeBASIC/Rosetta-Code-Rank-languages-by-popularity new file mode 120000 index 0000000000..71d538269e --- /dev/null +++ b/Lang/FreeBASIC/Rosetta-Code-Rank-languages-by-popularity @@ -0,0 +1 @@ +../../Task/Rosetta-Code-Rank-languages-by-popularity/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Runtime-evaluation-In-an-environment b/Lang/FreeBASIC/Runtime-evaluation-In-an-environment new file mode 120000 index 0000000000..80c5a69b35 --- /dev/null +++ b/Lang/FreeBASIC/Runtime-evaluation-In-an-environment @@ -0,0 +1 @@ +../../Task/Runtime-evaluation-In-an-environment/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/S-expressions b/Lang/FreeBASIC/S-expressions new file mode 120000 index 0000000000..9a014b780a --- /dev/null +++ b/Lang/FreeBASIC/S-expressions @@ -0,0 +1 @@ +../../Task/S-expressions/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/SOAP b/Lang/FreeBASIC/SOAP new file mode 120000 index 0000000000..927bc2295a --- /dev/null +++ b/Lang/FreeBASIC/SOAP @@ -0,0 +1 @@ +../../Task/SOAP/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/SQL-based-authentication b/Lang/FreeBASIC/SQL-based-authentication new file mode 120000 index 0000000000..19b09b4fc4 --- /dev/null +++ b/Lang/FreeBASIC/SQL-based-authentication @@ -0,0 +1 @@ +../../Task/SQL-based-authentication/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Same-fringe b/Lang/FreeBASIC/Same-fringe new file mode 120000 index 0000000000..756cf55a7d --- /dev/null +++ b/Lang/FreeBASIC/Same-fringe @@ -0,0 +1 @@ +../../Task/Same-fringe/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Search-in-paragraphs-text b/Lang/FreeBASIC/Search-in-paragraphs-text new file mode 120000 index 0000000000..bb0ecc2e40 --- /dev/null +++ b/Lang/FreeBASIC/Search-in-paragraphs-text @@ -0,0 +1 @@ +../../Task/Search-in-paragraphs-text/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Set-puzzle b/Lang/FreeBASIC/Set-puzzle new file mode 120000 index 0000000000..bdebb4443c --- /dev/null +++ b/Lang/FreeBASIC/Set-puzzle @@ -0,0 +1 @@ +../../Task/Set-puzzle/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Simple-database b/Lang/FreeBASIC/Simple-database new file mode 120000 index 0000000000..8d38b56c2d --- /dev/null +++ b/Lang/FreeBASIC/Simple-database @@ -0,0 +1 @@ +../../Task/Simple-database/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Simulate-input-Keyboard b/Lang/FreeBASIC/Simulate-input-Keyboard new file mode 120000 index 0000000000..504f3b18d3 --- /dev/null +++ b/Lang/FreeBASIC/Simulate-input-Keyboard @@ -0,0 +1 @@ +../../Task/Simulate-input-Keyboard/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Singular-value-decomposition b/Lang/FreeBASIC/Singular-value-decomposition new file mode 120000 index 0000000000..efbf29e97a --- /dev/null +++ b/Lang/FreeBASIC/Singular-value-decomposition @@ -0,0 +1 @@ +../../Task/Singular-value-decomposition/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Sisyphus-sequence b/Lang/FreeBASIC/Sisyphus-sequence new file mode 120000 index 0000000000..10074b9571 --- /dev/null +++ b/Lang/FreeBASIC/Sisyphus-sequence @@ -0,0 +1 @@ +../../Task/Sisyphus-sequence/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Sokoban b/Lang/FreeBASIC/Sokoban new file mode 120000 index 0000000000..4305dae36d --- /dev/null +++ b/Lang/FreeBASIC/Sokoban @@ -0,0 +1 @@ +../../Task/Sokoban/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Solve-a-Hidato-puzzle b/Lang/FreeBASIC/Solve-a-Hidato-puzzle new file mode 120000 index 0000000000..ad49dd7d72 --- /dev/null +++ b/Lang/FreeBASIC/Solve-a-Hidato-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hidato-puzzle/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Solve-a-Holy-Knights-tour b/Lang/FreeBASIC/Solve-a-Holy-Knights-tour new file mode 120000 index 0000000000..f7260b5f2d --- /dev/null +++ b/Lang/FreeBASIC/Solve-a-Holy-Knights-tour @@ -0,0 +1 @@ +../../Task/Solve-a-Holy-Knights-tour/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Solve-a-Hopido-puzzle b/Lang/FreeBASIC/Solve-a-Hopido-puzzle new file mode 120000 index 0000000000..3af9403ab8 --- /dev/null +++ b/Lang/FreeBASIC/Solve-a-Hopido-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hopido-puzzle/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Solve-a-Numbrix-puzzle b/Lang/FreeBASIC/Solve-a-Numbrix-puzzle new file mode 120000 index 0000000000..9212eac2bb --- /dev/null +++ b/Lang/FreeBASIC/Solve-a-Numbrix-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Numbrix-puzzle/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Solve-the-no-connection-puzzle b/Lang/FreeBASIC/Solve-the-no-connection-puzzle new file mode 120000 index 0000000000..b14a0d6097 --- /dev/null +++ b/Lang/FreeBASIC/Solve-the-no-connection-puzzle @@ -0,0 +1 @@ +../../Task/Solve-the-no-connection-puzzle/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Sort-a-list-of-object-identifiers b/Lang/FreeBASIC/Sort-a-list-of-object-identifiers new file mode 120000 index 0000000000..2c5a5fbb3b --- /dev/null +++ b/Lang/FreeBASIC/Sort-a-list-of-object-identifiers @@ -0,0 +1 @@ +../../Task/Sort-a-list-of-object-identifiers/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Sort-an-outline-at-every-level b/Lang/FreeBASIC/Sort-an-outline-at-every-level new file mode 120000 index 0000000000..ae4c555049 --- /dev/null +++ b/Lang/FreeBASIC/Sort-an-outline-at-every-level @@ -0,0 +1 @@ +../../Task/Sort-an-outline-at-every-level/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Sorting-Algorithms-Circle-Sort b/Lang/FreeBASIC/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index ea5bf17e30..0000000000 --- a/Lang/FreeBASIC/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Sorting-algorithms-Patience-sort b/Lang/FreeBASIC/Sorting-algorithms-Patience-sort new file mode 120000 index 0000000000..1fc80c416d --- /dev/null +++ b/Lang/FreeBASIC/Sorting-algorithms-Patience-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Patience-sort/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Sorting-algorithms-Radix-sort b/Lang/FreeBASIC/Sorting-algorithms-Radix-sort new file mode 120000 index 0000000000..bddec7031b --- /dev/null +++ b/Lang/FreeBASIC/Sorting-algorithms-Radix-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Radix-sort/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Sorting-algorithms-Strand-sort b/Lang/FreeBASIC/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..5305f3c6f7 --- /dev/null +++ b/Lang/FreeBASIC/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Stable-marriage-problem b/Lang/FreeBASIC/Stable-marriage-problem new file mode 120000 index 0000000000..e54d2883a7 --- /dev/null +++ b/Lang/FreeBASIC/Stable-marriage-problem @@ -0,0 +1 @@ +../../Task/Stable-marriage-problem/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/State-name-puzzle b/Lang/FreeBASIC/State-name-puzzle new file mode 120000 index 0000000000..31d5af215a --- /dev/null +++ b/Lang/FreeBASIC/State-name-puzzle @@ -0,0 +1 @@ +../../Task/State-name-puzzle/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Strassens-algorithm b/Lang/FreeBASIC/Strassens-algorithm new file mode 120000 index 0000000000..a5c6e9ef78 --- /dev/null +++ b/Lang/FreeBASIC/Strassens-algorithm @@ -0,0 +1 @@ +../../Task/Strassens-algorithm/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Summarize-and-say-sequence b/Lang/FreeBASIC/Summarize-and-say-sequence new file mode 120000 index 0000000000..c59e649aca --- /dev/null +++ b/Lang/FreeBASIC/Summarize-and-say-sequence @@ -0,0 +1 @@ +../../Task/Summarize-and-say-sequence/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Synchronous-concurrency b/Lang/FreeBASIC/Synchronous-concurrency new file mode 120000 index 0000000000..787a5aebfc --- /dev/null +++ b/Lang/FreeBASIC/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Tarjan b/Lang/FreeBASIC/Tarjan new file mode 120000 index 0000000000..2088963b57 --- /dev/null +++ b/Lang/FreeBASIC/Tarjan @@ -0,0 +1 @@ +../../Task/Tarjan/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Teacup-rim-text b/Lang/FreeBASIC/Teacup-rim-text new file mode 120000 index 0000000000..e0ebee7a7f --- /dev/null +++ b/Lang/FreeBASIC/Teacup-rim-text @@ -0,0 +1 @@ +../../Task/Teacup-rim-text/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Text-processing-1 b/Lang/FreeBASIC/Text-processing-1 new file mode 120000 index 0000000000..1e52cc9a2a --- /dev/null +++ b/Lang/FreeBASIC/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Text-processing-2 b/Lang/FreeBASIC/Text-processing-2 new file mode 120000 index 0000000000..03a524d892 --- /dev/null +++ b/Lang/FreeBASIC/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Textonyms b/Lang/FreeBASIC/Textonyms new file mode 120000 index 0000000000..1d60439533 --- /dev/null +++ b/Lang/FreeBASIC/Textonyms @@ -0,0 +1 @@ +../../Task/Textonyms/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Topological-sort b/Lang/FreeBASIC/Topological-sort new file mode 120000 index 0000000000..c6cd407c9f --- /dev/null +++ b/Lang/FreeBASIC/Topological-sort @@ -0,0 +1 @@ +../../Task/Topological-sort/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Transliterate-English-text-using-the-Greek-alphabet b/Lang/FreeBASIC/Transliterate-English-text-using-the-Greek-alphabet new file mode 120000 index 0000000000..a3142e6912 --- /dev/null +++ b/Lang/FreeBASIC/Transliterate-English-text-using-the-Greek-alphabet @@ -0,0 +1 @@ +../../Task/Transliterate-English-text-using-the-Greek-alphabet/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Tree-datastructures b/Lang/FreeBASIC/Tree-datastructures new file mode 120000 index 0000000000..9ca72e7eb6 --- /dev/null +++ b/Lang/FreeBASIC/Tree-datastructures @@ -0,0 +1 @@ +../../Task/Tree-datastructures/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Truth-table b/Lang/FreeBASIC/Truth-table new file mode 120000 index 0000000000..228be906c6 --- /dev/null +++ b/Lang/FreeBASIC/Truth-table @@ -0,0 +1 @@ +../../Task/Truth-table/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/UPC b/Lang/FreeBASIC/UPC new file mode 120000 index 0000000000..ddcf027e49 --- /dev/null +++ b/Lang/FreeBASIC/UPC @@ -0,0 +1 @@ +../../Task/UPC/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/URL-parser b/Lang/FreeBASIC/URL-parser new file mode 120000 index 0000000000..870d1a309b --- /dev/null +++ b/Lang/FreeBASIC/URL-parser @@ -0,0 +1 @@ +../../Task/URL-parser/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Ukkonen-s-suffix-tree-construction b/Lang/FreeBASIC/Ukkonen-s-suffix-tree-construction new file mode 120000 index 0000000000..6686d05c91 --- /dev/null +++ b/Lang/FreeBASIC/Ukkonen-s-suffix-tree-construction @@ -0,0 +1 @@ +../../Task/Ukkonen-s-suffix-tree-construction/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Universal-Turing-machine b/Lang/FreeBASIC/Universal-Turing-machine new file mode 120000 index 0000000000..a29b2e6201 --- /dev/null +++ b/Lang/FreeBASIC/Universal-Turing-machine @@ -0,0 +1 @@ +../../Task/Universal-Turing-machine/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Use-another-language-to-call-a-function b/Lang/FreeBASIC/Use-another-language-to-call-a-function new file mode 120000 index 0000000000..5d195ad8f5 --- /dev/null +++ b/Lang/FreeBASIC/Use-another-language-to-call-a-function @@ -0,0 +1 @@ +../../Task/Use-another-language-to-call-a-function/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/User-input-Graphical b/Lang/FreeBASIC/User-input-Graphical new file mode 120000 index 0000000000..8c4f2f8158 --- /dev/null +++ b/Lang/FreeBASIC/User-input-Graphical @@ -0,0 +1 @@ +../../Task/User-input-Graphical/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Verify-distribution-uniformity-Chi-squared-test b/Lang/FreeBASIC/Verify-distribution-uniformity-Chi-squared-test new file mode 120000 index 0000000000..8088ed160e --- /dev/null +++ b/Lang/FreeBASIC/Verify-distribution-uniformity-Chi-squared-test @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Chi-squared-test/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Vigen-re-cipher-Cryptanalysis b/Lang/FreeBASIC/Vigen-re-cipher-Cryptanalysis new file mode 120000 index 0000000000..a802341d36 --- /dev/null +++ b/Lang/FreeBASIC/Vigen-re-cipher-Cryptanalysis @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher-Cryptanalysis/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Vogels-approximation-method b/Lang/FreeBASIC/Vogels-approximation-method new file mode 120000 index 0000000000..e685ba3d8d --- /dev/null +++ b/Lang/FreeBASIC/Vogels-approximation-method @@ -0,0 +1 @@ +../../Task/Vogels-approximation-method/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Wasteful-equidigital-and-frugal-numbers b/Lang/FreeBASIC/Wasteful-equidigital-and-frugal-numbers new file mode 120000 index 0000000000..7889ec2570 --- /dev/null +++ b/Lang/FreeBASIC/Wasteful-equidigital-and-frugal-numbers @@ -0,0 +1 @@ +../../Task/Wasteful-equidigital-and-frugal-numbers/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Web-scraping b/Lang/FreeBASIC/Web-scraping new file mode 120000 index 0000000000..ef3ee370f4 --- /dev/null +++ b/Lang/FreeBASIC/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Window-management b/Lang/FreeBASIC/Window-management new file mode 120000 index 0000000000..f998cbb6ef --- /dev/null +++ b/Lang/FreeBASIC/Window-management @@ -0,0 +1 @@ +../../Task/Window-management/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Word-ladder b/Lang/FreeBASIC/Word-ladder new file mode 120000 index 0000000000..1390108efe --- /dev/null +++ b/Lang/FreeBASIC/Word-ladder @@ -0,0 +1 @@ +../../Task/Word-ladder/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/World-Cup-group-stage b/Lang/FreeBASIC/World-Cup-group-stage new file mode 120000 index 0000000000..10c687e006 --- /dev/null +++ b/Lang/FreeBASIC/World-Cup-group-stage @@ -0,0 +1 @@ +../../Task/World-Cup-group-stage/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Write-to-Windows-event-log b/Lang/FreeBASIC/Write-to-Windows-event-log new file mode 120000 index 0000000000..8993ae4828 --- /dev/null +++ b/Lang/FreeBASIC/Write-to-Windows-event-log @@ -0,0 +1 @@ +../../Task/Write-to-Windows-event-log/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Yahoo-search-interface b/Lang/FreeBASIC/Yahoo-search-interface new file mode 120000 index 0000000000..f92d06f36d --- /dev/null +++ b/Lang/FreeBASIC/Yahoo-search-interface @@ -0,0 +1 @@ +../../Task/Yahoo-search-interface/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Zebra-puzzle b/Lang/FreeBASIC/Zebra-puzzle new file mode 120000 index 0000000000..aa6204ae2d --- /dev/null +++ b/Lang/FreeBASIC/Zebra-puzzle @@ -0,0 +1 @@ +../../Task/Zebra-puzzle/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Zeckendorf-arithmetic b/Lang/FreeBASIC/Zeckendorf-arithmetic new file mode 120000 index 0000000000..5830437272 --- /dev/null +++ b/Lang/FreeBASIC/Zeckendorf-arithmetic @@ -0,0 +1 @@ +../../Task/Zeckendorf-arithmetic/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Zumkeller-numbers b/Lang/FreeBASIC/Zumkeller-numbers new file mode 120000 index 0000000000..6994043985 --- /dev/null +++ b/Lang/FreeBASIC/Zumkeller-numbers @@ -0,0 +1 @@ +../../Task/Zumkeller-numbers/FreeBASIC \ No newline at end of file diff --git a/Lang/Frink/24-game b/Lang/Frink/24-game new file mode 120000 index 0000000000..843d6f51e2 --- /dev/null +++ b/Lang/Frink/24-game @@ -0,0 +1 @@ +../../Task/24-game/Frink \ No newline at end of file diff --git a/Lang/Frink/Averages-Root-mean-square b/Lang/Frink/Averages-Root-mean-square new file mode 120000 index 0000000000..5ccaff432e --- /dev/null +++ b/Lang/Frink/Averages-Root-mean-square @@ -0,0 +1 @@ +../../Task/Averages-Root-mean-square/Frink \ No newline at end of file diff --git a/Lang/Frink/Blum-integer b/Lang/Frink/Blum-integer new file mode 120000 index 0000000000..51dea63ee5 --- /dev/null +++ b/Lang/Frink/Blum-integer @@ -0,0 +1 @@ +../../Task/Blum-integer/Frink \ No newline at end of file diff --git a/Lang/Frink/Combinations b/Lang/Frink/Combinations new file mode 120000 index 0000000000..ca07ce8ac3 --- /dev/null +++ b/Lang/Frink/Combinations @@ -0,0 +1 @@ +../../Task/Combinations/Frink \ No newline at end of file diff --git a/Lang/Frink/Disarium-numbers b/Lang/Frink/Disarium-numbers new file mode 120000 index 0000000000..30da6e89d2 --- /dev/null +++ b/Lang/Frink/Disarium-numbers @@ -0,0 +1 @@ +../../Task/Disarium-numbers/Frink \ No newline at end of file diff --git a/Lang/Frink/Entropy b/Lang/Frink/Entropy new file mode 120000 index 0000000000..686a6c7be3 --- /dev/null +++ b/Lang/Frink/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/Frink \ No newline at end of file diff --git a/Lang/Frink/Factorial-primes b/Lang/Frink/Factorial-primes new file mode 120000 index 0000000000..704a6876ac --- /dev/null +++ b/Lang/Frink/Factorial-primes @@ -0,0 +1 @@ +../../Task/Factorial-primes/Frink \ No newline at end of file diff --git a/Lang/Frink/Find-palindromic-numbers-in-both-binary-and-ternary-bases b/Lang/Frink/Find-palindromic-numbers-in-both-binary-and-ternary-bases new file mode 120000 index 0000000000..8a6a61669b --- /dev/null +++ b/Lang/Frink/Find-palindromic-numbers-in-both-binary-and-ternary-bases @@ -0,0 +1 @@ +../../Task/Find-palindromic-numbers-in-both-binary-and-ternary-bases/Frink \ No newline at end of file diff --git a/Lang/Frink/Floyds-triangle b/Lang/Frink/Floyds-triangle new file mode 120000 index 0000000000..993ee6e3c2 --- /dev/null +++ b/Lang/Frink/Floyds-triangle @@ -0,0 +1 @@ +../../Task/Floyds-triangle/Frink \ No newline at end of file diff --git a/Lang/Frink/Happy-numbers b/Lang/Frink/Happy-numbers new file mode 120000 index 0000000000..e83b081fcc --- /dev/null +++ b/Lang/Frink/Happy-numbers @@ -0,0 +1 @@ +../../Task/Happy-numbers/Frink \ No newline at end of file diff --git a/Lang/Frink/Knapsack-problem-0-1 b/Lang/Frink/Knapsack-problem-0-1 new file mode 120000 index 0000000000..ae292bd7e7 --- /dev/null +++ b/Lang/Frink/Knapsack-problem-0-1 @@ -0,0 +1 @@ +../../Task/Knapsack-problem-0-1/Frink \ No newline at end of file diff --git a/Lang/Frink/Knapsack-problem-Bounded b/Lang/Frink/Knapsack-problem-Bounded new file mode 120000 index 0000000000..52649c831e --- /dev/null +++ b/Lang/Frink/Knapsack-problem-Bounded @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Bounded/Frink \ No newline at end of file diff --git a/Lang/Frink/Order-two-numerical-lists b/Lang/Frink/Order-two-numerical-lists new file mode 120000 index 0000000000..7daa415aeb --- /dev/null +++ b/Lang/Frink/Order-two-numerical-lists @@ -0,0 +1 @@ +../../Task/Order-two-numerical-lists/Frink \ No newline at end of file diff --git a/Lang/Frink/Palindrome-dates b/Lang/Frink/Palindrome-dates new file mode 120000 index 0000000000..9b0bf86617 --- /dev/null +++ b/Lang/Frink/Palindrome-dates @@ -0,0 +1 @@ +../../Task/Palindrome-dates/Frink \ No newline at end of file diff --git a/Lang/Frink/Search-a-list b/Lang/Frink/Search-a-list new file mode 120000 index 0000000000..71db52cc8c --- /dev/null +++ b/Lang/Frink/Search-a-list @@ -0,0 +1 @@ +../../Task/Search-a-list/Frink \ No newline at end of file diff --git a/Lang/Frink/Smith-numbers b/Lang/Frink/Smith-numbers new file mode 120000 index 0000000000..368b2f0d50 --- /dev/null +++ b/Lang/Frink/Smith-numbers @@ -0,0 +1 @@ +../../Task/Smith-numbers/Frink \ No newline at end of file diff --git a/Lang/Frink/Square-free-integers b/Lang/Frink/Square-free-integers new file mode 120000 index 0000000000..23755894dd --- /dev/null +++ b/Lang/Frink/Square-free-integers @@ -0,0 +1 @@ +../../Task/Square-free-integers/Frink \ No newline at end of file diff --git a/Lang/Frink/String-matching b/Lang/Frink/String-matching new file mode 120000 index 0000000000..f56424a6a3 --- /dev/null +++ b/Lang/Frink/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Frink \ No newline at end of file diff --git a/Lang/FunL/Miller-Rabin-primality-test b/Lang/FunL/Miller-Rabin-primality-test deleted file mode 120000 index 592d9059fa..0000000000 --- a/Lang/FunL/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/FunL \ No newline at end of file diff --git a/Lang/FuncSug/00-LANG.txt b/Lang/FuncSug/00-LANG.txt new file mode 100644 index 0000000000..9239e3a1ef --- /dev/null +++ b/Lang/FuncSug/00-LANG.txt @@ -0,0 +1 @@ +{{stub}}{{language|FuncSug}} \ No newline at end of file diff --git a/Lang/FuncSug/00-META.yaml b/Lang/FuncSug/00-META.yaml new file mode 100644 index 0000000000..0613d9bea7 --- /dev/null +++ b/Lang/FuncSug/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:FuncSug diff --git a/Lang/FuncSug/15-puzzle-game b/Lang/FuncSug/15-puzzle-game new file mode 120000 index 0000000000..76eb121586 --- /dev/null +++ b/Lang/FuncSug/15-puzzle-game @@ -0,0 +1 @@ +../../Task/15-puzzle-game/FuncSug \ No newline at end of file diff --git a/Lang/FuncSug/GUI-component-interaction b/Lang/FuncSug/GUI-component-interaction new file mode 120000 index 0000000000..744e9aac1b --- /dev/null +++ b/Lang/FuncSug/GUI-component-interaction @@ -0,0 +1 @@ +../../Task/GUI-component-interaction/FuncSug \ No newline at end of file diff --git a/Lang/FuncSug/GUI-enabling-disabling-of-controls b/Lang/FuncSug/GUI-enabling-disabling-of-controls new file mode 120000 index 0000000000..049595483a --- /dev/null +++ b/Lang/FuncSug/GUI-enabling-disabling-of-controls @@ -0,0 +1 @@ +../../Task/GUI-enabling-disabling-of-controls/FuncSug \ No newline at end of file diff --git a/Lang/FuncSug/Hello-world-Text b/Lang/FuncSug/Hello-world-Text new file mode 120000 index 0000000000..f188530df7 --- /dev/null +++ b/Lang/FuncSug/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/FuncSug \ No newline at end of file diff --git a/Lang/FuncSug/Play-recorded-sounds b/Lang/FuncSug/Play-recorded-sounds new file mode 120000 index 0000000000..9418947577 --- /dev/null +++ b/Lang/FuncSug/Play-recorded-sounds @@ -0,0 +1 @@ +../../Task/Play-recorded-sounds/FuncSug \ No newline at end of file diff --git a/Lang/FuncSug/Simple-windowed-application b/Lang/FuncSug/Simple-windowed-application new file mode 120000 index 0000000000..8eec686bff --- /dev/null +++ b/Lang/FuncSug/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/FuncSug \ No newline at end of file diff --git a/Lang/FuncSug/Simulate-input-Mouse b/Lang/FuncSug/Simulate-input-Mouse new file mode 120000 index 0000000000..186d49bf08 --- /dev/null +++ b/Lang/FuncSug/Simulate-input-Mouse @@ -0,0 +1 @@ +../../Task/Simulate-input-Mouse/FuncSug \ No newline at end of file diff --git a/Lang/FuncSug/User-input-Graphical b/Lang/FuncSug/User-input-Graphical new file mode 120000 index 0000000000..b685a2412e --- /dev/null +++ b/Lang/FuncSug/User-input-Graphical @@ -0,0 +1 @@ +../../Task/User-input-Graphical/FuncSug \ No newline at end of file diff --git a/Lang/FutureBasic/00-LANG.txt b/Lang/FutureBasic/00-LANG.txt index d3dbdba2ec..36f5f0b065 100644 --- a/Lang/FutureBasic/00-LANG.txt +++ b/Lang/FutureBasic/00-LANG.txt @@ -12,7 +12,11 @@ [[File:FutureBasicIcon.png|64px|top]] -FutureBasic began life as Zbasic, a commercial variant of [[BASIC]] for the early Macintoshes, but has grown far beyond that into a mature freeware IDE that, through its FBtoC translator, can be used to compile C and Objective-C [[object-oriented]] code using the clang compiler included with an Xcode installation. It is excellent as a educational tool and for fast prototyping -- especially in Objective-C (Cocoa) by those who prefer programmatic code without the overhead of Xcode. Among its enthusiasts are commercial developers, engineers, professors, doctors, musicians, writers and a host of amateurs who program with FB for the sheer joy of it. +FutureBasic — commonly called FB by its users — is a robust freeware Macintosh IDE. + +It began life as Zbasic, a commercial variant of [[BASIC]] for the early Macintoshes, but has grown far beyond that into a mature IDE compatible with the latest macOSes. Through its FBtoC translator, it can be used to compile C and Objective-C [[object-oriented]] code. It uses the industry-standard clang compiler included with an Xcode installation. + +FB is excellent as a educational tool, for fast prototyping and for commercial application development. In addition to its native language, it can incorporate C and Objective-C (Cocoa) for those who prefer programmatic code without the overhead of Xcode. It is compatible with Xcode nib and xib files used for building GUIs. Among its enthusiasts are commercial developers, engineers, professors, doctors, musicians, writers and a host of amateurs who program with FB for the sheer joy of it. == FutureBasic Home Page & Download == @@ -64,11 +68,11 @@ In 1995 Staz Software, led by Chris Stasny based in Diamondhead, Miss., acquired When Apple transitioned the Mac from 68k to PowerPC, the FB editor was rewritten by Stasny and was coupled with an adaptation of the compiler by Andy Gariepy. The result of their efforts, a dramatically enhanced IDE called FB^3 (FB-cubed) was released in September 1999. -Major update releases introduced a full-featured Appearance Compliant runtime written by the late New Zealander Robert Purves renown for his brilliant programming. Once completely carbonized to run natively on the Mac OS X, the FutureBASIC Integrated Development Environment (FB IDE) was called FB4 and released in July 2004. +Major update releases introduced a full-featured Appearance Compliant runtime written by the late New Zealander Robert Purves renowned for his brilliant programming. Once completely carbonized to run natively on the Mac OS X, the FutureBASIC Integrated Development Environment (FB IDE) was called FB4 and released in July 2004. In August 2005, Staz Software was devastated by Hurricane Katrina just at the time Apple was transitioning from Motorola PPC microprocessors to Intel chips. FB development slowed almost to a standstill. On January 1, 2008, Staz Software announced that FB would henceforth be freeware and FB4 with FBtoC 1.0 was made available. -Since that time, an independent team of volunteer developers initially lead by Purves continued to improve FBtoC, which took code produced by the FB Editor and translated it to C for processing by gcc which was eventually transitioned to the more robust clang. +Since that time, an independent team of volunteer developers initially led by Purves continued to improve FBtoC, which took code produced by the FB Editor and translated it to C for processing by gcc which was eventually transitioned to the more robust clang. On Sunday, June 3, 2012, members of the FB List Serve were notified that Robert Purves had died after a long bout with cancer. The news came as a surprise to many FB developers who were unaware of Purves' illness. While coping with cancer, he continued as an active member of the FB community, improving FB, answering questions, solving problems, and posting exquisitely terse code often salted with pithy remarks from his wonderfully dry humor. He never mentioned his health problems and never complained. A tribute to Purves can be found at the bottom of the FB Home Page diff --git a/Lang/FutureBasic/15-puzzle-solver b/Lang/FutureBasic/15-puzzle-solver new file mode 120000 index 0000000000..db2f936a7e --- /dev/null +++ b/Lang/FutureBasic/15-puzzle-solver @@ -0,0 +1 @@ +../../Task/15-puzzle-solver/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/24-game b/Lang/FutureBasic/24-game new file mode 120000 index 0000000000..f1ea3d0684 --- /dev/null +++ b/Lang/FutureBasic/24-game @@ -0,0 +1 @@ +../../Task/24-game/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/9-billion-names-of-God-the-integer b/Lang/FutureBasic/9-billion-names-of-God-the-integer new file mode 120000 index 0000000000..2c2322b6ea --- /dev/null +++ b/Lang/FutureBasic/9-billion-names-of-God-the-integer @@ -0,0 +1 @@ +../../Task/9-billion-names-of-God-the-integer/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/ADFGVX-cipher b/Lang/FutureBasic/ADFGVX-cipher new file mode 120000 index 0000000000..e5f0c8a31e --- /dev/null +++ b/Lang/FutureBasic/ADFGVX-cipher @@ -0,0 +1 @@ +../../Task/ADFGVX-cipher/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/AKS-test-for-primes b/Lang/FutureBasic/AKS-test-for-primes new file mode 120000 index 0000000000..d7fcaa6502 --- /dev/null +++ b/Lang/FutureBasic/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/ASCII-art-diagram-converter b/Lang/FutureBasic/ASCII-art-diagram-converter new file mode 120000 index 0000000000..cb5711ff54 --- /dev/null +++ b/Lang/FutureBasic/ASCII-art-diagram-converter @@ -0,0 +1 @@ +../../Task/ASCII-art-diagram-converter/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Achilles-numbers b/Lang/FutureBasic/Achilles-numbers new file mode 120000 index 0000000000..a912859c01 --- /dev/null +++ b/Lang/FutureBasic/Achilles-numbers @@ -0,0 +1 @@ +../../Task/Achilles-numbers/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Aliquot-sequence-classifications b/Lang/FutureBasic/Aliquot-sequence-classifications new file mode 120000 index 0000000000..d24c82afdc --- /dev/null +++ b/Lang/FutureBasic/Aliquot-sequence-classifications @@ -0,0 +1 @@ +../../Task/Aliquot-sequence-classifications/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Almkvist-Giullera-formula-for-pi b/Lang/FutureBasic/Almkvist-Giullera-formula-for-pi new file mode 120000 index 0000000000..0079b2eae5 --- /dev/null +++ b/Lang/FutureBasic/Almkvist-Giullera-formula-for-pi @@ -0,0 +1 @@ +../../Task/Almkvist-Giullera-formula-for-pi/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Amb b/Lang/FutureBasic/Amb new file mode 120000 index 0000000000..399b8a70d5 --- /dev/null +++ b/Lang/FutureBasic/Amb @@ -0,0 +1 @@ +../../Task/Amb/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Angles-geometric-normalization-and-conversion b/Lang/FutureBasic/Angles-geometric-normalization-and-conversion new file mode 120000 index 0000000000..63c4e835a4 --- /dev/null +++ b/Lang/FutureBasic/Angles-geometric-normalization-and-conversion @@ -0,0 +1 @@ +../../Task/Angles-geometric-normalization-and-conversion/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Anonymous-recursion b/Lang/FutureBasic/Anonymous-recursion new file mode 120000 index 0000000000..d52f4bbda0 --- /dev/null +++ b/Lang/FutureBasic/Anonymous-recursion @@ -0,0 +1 @@ +../../Task/Anonymous-recursion/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Arbitrary-precision-integers-included- b/Lang/FutureBasic/Arbitrary-precision-integers-included- new file mode 120000 index 0000000000..ca9deb04e2 --- /dev/null +++ b/Lang/FutureBasic/Arbitrary-precision-integers-included- @@ -0,0 +1 @@ +../../Task/Arbitrary-precision-integers-included-/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Arithmetic-Complex b/Lang/FutureBasic/Arithmetic-Complex new file mode 120000 index 0000000000..eab72eafe1 --- /dev/null +++ b/Lang/FutureBasic/Arithmetic-Complex @@ -0,0 +1 @@ +../../Task/Arithmetic-Complex/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Arithmetic-Rational b/Lang/FutureBasic/Arithmetic-Rational new file mode 120000 index 0000000000..4ba3750b0f --- /dev/null +++ b/Lang/FutureBasic/Arithmetic-Rational @@ -0,0 +1 @@ +../../Task/Arithmetic-Rational/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Arithmetic-derivative b/Lang/FutureBasic/Arithmetic-derivative new file mode 120000 index 0000000000..4b54c16b3d --- /dev/null +++ b/Lang/FutureBasic/Arithmetic-derivative @@ -0,0 +1 @@ +../../Task/Arithmetic-derivative/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Arithmetic-geometric-mean b/Lang/FutureBasic/Arithmetic-geometric-mean new file mode 120000 index 0000000000..2894f4733f --- /dev/null +++ b/Lang/FutureBasic/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Assertions b/Lang/FutureBasic/Assertions new file mode 120000 index 0000000000..6270ababb4 --- /dev/null +++ b/Lang/FutureBasic/Assertions @@ -0,0 +1 @@ +../../Task/Assertions/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Averages-Mean-angle b/Lang/FutureBasic/Averages-Mean-angle new file mode 120000 index 0000000000..45c7d861f6 --- /dev/null +++ b/Lang/FutureBasic/Averages-Mean-angle @@ -0,0 +1 @@ +../../Task/Averages-Mean-angle/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Averages-Mean-time-of-day b/Lang/FutureBasic/Averages-Mean-time-of-day new file mode 120000 index 0000000000..0caef5a9a0 --- /dev/null +++ b/Lang/FutureBasic/Averages-Mean-time-of-day @@ -0,0 +1 @@ +../../Task/Averages-Mean-time-of-day/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Averages-Root-mean-square b/Lang/FutureBasic/Averages-Root-mean-square new file mode 120000 index 0000000000..f04b81a3b0 --- /dev/null +++ b/Lang/FutureBasic/Averages-Root-mean-square @@ -0,0 +1 @@ +../../Task/Averages-Root-mean-square/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Barnsley-fern b/Lang/FutureBasic/Barnsley-fern new file mode 120000 index 0000000000..a6da4c722a --- /dev/null +++ b/Lang/FutureBasic/Barnsley-fern @@ -0,0 +1 @@ +../../Task/Barnsley-fern/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Bernoulli-numbers b/Lang/FutureBasic/Bernoulli-numbers new file mode 120000 index 0000000000..3ed522958e --- /dev/null +++ b/Lang/FutureBasic/Bernoulli-numbers @@ -0,0 +1 @@ +../../Task/Bernoulli-numbers/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Bin-given-limits b/Lang/FutureBasic/Bin-given-limits new file mode 120000 index 0000000000..6397588001 --- /dev/null +++ b/Lang/FutureBasic/Bin-given-limits @@ -0,0 +1 @@ +../../Task/Bin-given-limits/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Binary-search b/Lang/FutureBasic/Binary-search new file mode 120000 index 0000000000..55e96bcbd8 --- /dev/null +++ b/Lang/FutureBasic/Binary-search @@ -0,0 +1 @@ +../../Task/Binary-search/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Bioinformatics-base-count b/Lang/FutureBasic/Bioinformatics-base-count deleted file mode 120000 index 8f826b0063..0000000000 --- a/Lang/FutureBasic/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Biorhythms b/Lang/FutureBasic/Biorhythms new file mode 120000 index 0000000000..db55b5c43b --- /dev/null +++ b/Lang/FutureBasic/Biorhythms @@ -0,0 +1 @@ +../../Task/Biorhythms/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Bitmap b/Lang/FutureBasic/Bitmap new file mode 120000 index 0000000000..5e3f607822 --- /dev/null +++ b/Lang/FutureBasic/Bitmap @@ -0,0 +1 @@ +../../Task/Bitmap/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Bitmap-B-zier-curves-Cubic b/Lang/FutureBasic/Bitmap-B-zier-curves-Cubic new file mode 120000 index 0000000000..743bf83068 --- /dev/null +++ b/Lang/FutureBasic/Bitmap-B-zier-curves-Cubic @@ -0,0 +1 @@ +../../Task/Bitmap-B-zier-curves-Cubic/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Blum-integer b/Lang/FutureBasic/Blum-integer new file mode 120000 index 0000000000..0ccbf69775 --- /dev/null +++ b/Lang/FutureBasic/Blum-integer @@ -0,0 +1 @@ +../../Task/Blum-integer/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Box-the-compass b/Lang/FutureBasic/Box-the-compass new file mode 120000 index 0000000000..7b89a8413c --- /dev/null +++ b/Lang/FutureBasic/Box-the-compass @@ -0,0 +1 @@ +../../Task/Box-the-compass/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Boyer-Moore-string-search b/Lang/FutureBasic/Boyer-Moore-string-search new file mode 120000 index 0000000000..574c899ddd --- /dev/null +++ b/Lang/FutureBasic/Boyer-Moore-string-search @@ -0,0 +1 @@ +../../Task/Boyer-Moore-string-search/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Brazilian-numbers b/Lang/FutureBasic/Brazilian-numbers new file mode 120000 index 0000000000..ea4e519da9 --- /dev/null +++ b/Lang/FutureBasic/Brazilian-numbers @@ -0,0 +1 @@ +../../Task/Brazilian-numbers/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Brilliant-numbers b/Lang/FutureBasic/Brilliant-numbers new file mode 120000 index 0000000000..0ee49e027a --- /dev/null +++ b/Lang/FutureBasic/Brilliant-numbers @@ -0,0 +1 @@ +../../Task/Brilliant-numbers/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Brownian-tree b/Lang/FutureBasic/Brownian-tree new file mode 120000 index 0000000000..26e06861c7 --- /dev/null +++ b/Lang/FutureBasic/Brownian-tree @@ -0,0 +1 @@ +../../Task/Brownian-tree/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/CRC-32 b/Lang/FutureBasic/CRC-32 new file mode 120000 index 0000000000..8330772d04 --- /dev/null +++ b/Lang/FutureBasic/CRC-32 @@ -0,0 +1 @@ +../../Task/CRC-32/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Caesar-cipher b/Lang/FutureBasic/Caesar-cipher new file mode 120000 index 0000000000..c0196256fa --- /dev/null +++ b/Lang/FutureBasic/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Canonicalize-CIDR b/Lang/FutureBasic/Canonicalize-CIDR new file mode 120000 index 0000000000..77fabb43fd --- /dev/null +++ b/Lang/FutureBasic/Canonicalize-CIDR @@ -0,0 +1 @@ +../../Task/Canonicalize-CIDR/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Carmichael-3-strong-pseudoprimes b/Lang/FutureBasic/Carmichael-3-strong-pseudoprimes new file mode 120000 index 0000000000..17664f9781 --- /dev/null +++ b/Lang/FutureBasic/Carmichael-3-strong-pseudoprimes @@ -0,0 +1 @@ +../../Task/Carmichael-3-strong-pseudoprimes/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Catalan-numbers-Pascals-triangle b/Lang/FutureBasic/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..48a5bd3f8b --- /dev/null +++ b/Lang/FutureBasic/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Catamorphism b/Lang/FutureBasic/Catamorphism new file mode 120000 index 0000000000..25e6699616 --- /dev/null +++ b/Lang/FutureBasic/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Check-output-device-is-a-terminal b/Lang/FutureBasic/Check-output-device-is-a-terminal new file mode 120000 index 0000000000..e2e8c9c4eb --- /dev/null +++ b/Lang/FutureBasic/Check-output-device-is-a-terminal @@ -0,0 +1 @@ +../../Task/Check-output-device-is-a-terminal/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Chinese-remainder-theorem b/Lang/FutureBasic/Chinese-remainder-theorem new file mode 120000 index 0000000000..2cdd3a4f64 --- /dev/null +++ b/Lang/FutureBasic/Chinese-remainder-theorem @@ -0,0 +1 @@ +../../Task/Chinese-remainder-theorem/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Chinese-zodiac b/Lang/FutureBasic/Chinese-zodiac new file mode 120000 index 0000000000..df6e098031 --- /dev/null +++ b/Lang/FutureBasic/Chinese-zodiac @@ -0,0 +1 @@ +../../Task/Chinese-zodiac/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Colorful-numbers b/Lang/FutureBasic/Colorful-numbers new file mode 120000 index 0000000000..f9f2dd43bc --- /dev/null +++ b/Lang/FutureBasic/Colorful-numbers @@ -0,0 +1 @@ +../../Task/Colorful-numbers/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Combinations b/Lang/FutureBasic/Combinations new file mode 120000 index 0000000000..d7395ea4d1 --- /dev/null +++ b/Lang/FutureBasic/Combinations @@ -0,0 +1 @@ +../../Task/Combinations/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Command-line-arguments b/Lang/FutureBasic/Command-line-arguments new file mode 120000 index 0000000000..2926af8716 --- /dev/null +++ b/Lang/FutureBasic/Command-line-arguments @@ -0,0 +1 @@ +../../Task/Command-line-arguments/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Compile-time-calculation b/Lang/FutureBasic/Compile-time-calculation new file mode 120000 index 0000000000..ef10ff644e --- /dev/null +++ b/Lang/FutureBasic/Compile-time-calculation @@ -0,0 +1 @@ +../../Task/Compile-time-calculation/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k b/Lang/FutureBasic/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k new file mode 120000 index 0000000000..2fbac26654 --- /dev/null +++ b/Lang/FutureBasic/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/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Consecutive-primes-with-ascending-or-descending-differences b/Lang/FutureBasic/Consecutive-primes-with-ascending-or-descending-differences new file mode 120000 index 0000000000..ca47092ad1 --- /dev/null +++ b/Lang/FutureBasic/Consecutive-primes-with-ascending-or-descending-differences @@ -0,0 +1 @@ +../../Task/Consecutive-primes-with-ascending-or-descending-differences/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Constrained-random-points-on-a-circle b/Lang/FutureBasic/Constrained-random-points-on-a-circle new file mode 120000 index 0000000000..db1c784250 --- /dev/null +++ b/Lang/FutureBasic/Constrained-random-points-on-a-circle @@ -0,0 +1 @@ +../../Task/Constrained-random-points-on-a-circle/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Continued-fraction-Arithmetic-Construct-from-rational-number b/Lang/FutureBasic/Continued-fraction-Arithmetic-Construct-from-rational-number new file mode 120000 index 0000000000..fa25a1c542 --- /dev/null +++ b/Lang/FutureBasic/Continued-fraction-Arithmetic-Construct-from-rational-number @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-Construct-from-rational-number/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Copy-stdin-to-stdout b/Lang/FutureBasic/Copy-stdin-to-stdout new file mode 120000 index 0000000000..9a5df43082 --- /dev/null +++ b/Lang/FutureBasic/Copy-stdin-to-stdout @@ -0,0 +1 @@ +../../Task/Copy-stdin-to-stdout/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Cuban-primes b/Lang/FutureBasic/Cuban-primes new file mode 120000 index 0000000000..3b2980081c --- /dev/null +++ b/Lang/FutureBasic/Cuban-primes @@ -0,0 +1 @@ +../../Task/Cuban-primes/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Cumulative-standard-deviation b/Lang/FutureBasic/Cumulative-standard-deviation new file mode 120000 index 0000000000..e51653c2b1 --- /dev/null +++ b/Lang/FutureBasic/Cumulative-standard-deviation @@ -0,0 +1 @@ +../../Task/Cumulative-standard-deviation/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Curzon-numbers b/Lang/FutureBasic/Curzon-numbers new file mode 120000 index 0000000000..bcd7e577f6 --- /dev/null +++ b/Lang/FutureBasic/Curzon-numbers @@ -0,0 +1 @@ +../../Task/Curzon-numbers/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Damm-algorithm b/Lang/FutureBasic/Damm-algorithm new file mode 120000 index 0000000000..1a53ae4466 --- /dev/null +++ b/Lang/FutureBasic/Damm-algorithm @@ -0,0 +1 @@ +../../Task/Damm-algorithm/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Deal-cards-for-FreeCell b/Lang/FutureBasic/Deal-cards-for-FreeCell new file mode 120000 index 0000000000..b84bfb771c --- /dev/null +++ b/Lang/FutureBasic/Deal-cards-for-FreeCell @@ -0,0 +1 @@ +../../Task/Deal-cards-for-FreeCell/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Death-Star b/Lang/FutureBasic/Death-Star new file mode 120000 index 0000000000..6a87d38224 --- /dev/null +++ b/Lang/FutureBasic/Death-Star @@ -0,0 +1 @@ +../../Task/Death-Star/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Deceptive-numbers b/Lang/FutureBasic/Deceptive-numbers new file mode 120000 index 0000000000..82f50bcc9e --- /dev/null +++ b/Lang/FutureBasic/Deceptive-numbers @@ -0,0 +1 @@ +../../Task/Deceptive-numbers/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Demings-funnel b/Lang/FutureBasic/Demings-funnel new file mode 120000 index 0000000000..a0b916f84d --- /dev/null +++ b/Lang/FutureBasic/Demings-funnel @@ -0,0 +1 @@ +../../Task/Demings-funnel/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Determine-if-a-string-has-all-the-same-characters b/Lang/FutureBasic/Determine-if-a-string-has-all-the-same-characters new file mode 120000 index 0000000000..94f004e3ea --- /dev/null +++ b/Lang/FutureBasic/Determine-if-a-string-has-all-the-same-characters @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-has-all-the-same-characters/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Determine-if-a-string-is-squeezable b/Lang/FutureBasic/Determine-if-a-string-is-squeezable new file mode 120000 index 0000000000..3b259327b7 --- /dev/null +++ b/Lang/FutureBasic/Determine-if-a-string-is-squeezable @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-squeezable/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Determine-if-only-one-instance-is-running b/Lang/FutureBasic/Determine-if-only-one-instance-is-running new file mode 120000 index 0000000000..e3fa96a5b5 --- /dev/null +++ b/Lang/FutureBasic/Determine-if-only-one-instance-is-running @@ -0,0 +1 @@ +../../Task/Determine-if-only-one-instance-is-running/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Determine-if-two-triangles-overlap b/Lang/FutureBasic/Determine-if-two-triangles-overlap new file mode 120000 index 0000000000..40f32b74b7 --- /dev/null +++ b/Lang/FutureBasic/Determine-if-two-triangles-overlap @@ -0,0 +1 @@ +../../Task/Determine-if-two-triangles-overlap/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Determine-sentence-type b/Lang/FutureBasic/Determine-sentence-type new file mode 120000 index 0000000000..fce2322962 --- /dev/null +++ b/Lang/FutureBasic/Determine-sentence-type @@ -0,0 +1 @@ +../../Task/Determine-sentence-type/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Digital-root b/Lang/FutureBasic/Digital-root new file mode 120000 index 0000000000..63da54faf1 --- /dev/null +++ b/Lang/FutureBasic/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Dinesmans-multiple-dwelling-problem b/Lang/FutureBasic/Dinesmans-multiple-dwelling-problem new file mode 120000 index 0000000000..cdb0294902 --- /dev/null +++ b/Lang/FutureBasic/Dinesmans-multiple-dwelling-problem @@ -0,0 +1 @@ +../../Task/Dinesmans-multiple-dwelling-problem/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Distribution-of-0-digits-in-factorial-series b/Lang/FutureBasic/Distribution-of-0-digits-in-factorial-series new file mode 120000 index 0000000000..2e525770b5 --- /dev/null +++ b/Lang/FutureBasic/Distribution-of-0-digits-in-factorial-series @@ -0,0 +1 @@ +../../Task/Distribution-of-0-digits-in-factorial-series/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Diversity-prediction-theorem b/Lang/FutureBasic/Diversity-prediction-theorem new file mode 120000 index 0000000000..75ad65e089 --- /dev/null +++ b/Lang/FutureBasic/Diversity-prediction-theorem @@ -0,0 +1 @@ +../../Task/Diversity-prediction-theorem/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Doubly-linked-list-Definition b/Lang/FutureBasic/Doubly-linked-list-Definition new file mode 120000 index 0000000000..dbb3fa0478 --- /dev/null +++ b/Lang/FutureBasic/Doubly-linked-list-Definition @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Definition/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Dutch-national-flag-problem b/Lang/FutureBasic/Dutch-national-flag-problem new file mode 120000 index 0000000000..a769d7e0d9 --- /dev/null +++ b/Lang/FutureBasic/Dutch-national-flag-problem @@ -0,0 +1 @@ +../../Task/Dutch-national-flag-problem/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Eban-numbers b/Lang/FutureBasic/Eban-numbers new file mode 120000 index 0000000000..2ae3f59434 --- /dev/null +++ b/Lang/FutureBasic/Eban-numbers @@ -0,0 +1 @@ +../../Task/Eban-numbers/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Echo-server b/Lang/FutureBasic/Echo-server new file mode 120000 index 0000000000..25d59262e7 --- /dev/null +++ b/Lang/FutureBasic/Echo-server @@ -0,0 +1 @@ +../../Task/Echo-server/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Eertree b/Lang/FutureBasic/Eertree new file mode 120000 index 0000000000..f3374493cf --- /dev/null +++ b/Lang/FutureBasic/Eertree @@ -0,0 +1 @@ +../../Task/Eertree/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Egyptian-division b/Lang/FutureBasic/Egyptian-division new file mode 120000 index 0000000000..5961af2842 --- /dev/null +++ b/Lang/FutureBasic/Egyptian-division @@ -0,0 +1 @@ +../../Task/Egyptian-division/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Entropy b/Lang/FutureBasic/Entropy new file mode 120000 index 0000000000..6336540906 --- /dev/null +++ b/Lang/FutureBasic/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Equilibrium-index b/Lang/FutureBasic/Equilibrium-index new file mode 120000 index 0000000000..92d577887f --- /dev/null +++ b/Lang/FutureBasic/Equilibrium-index @@ -0,0 +1 @@ +../../Task/Equilibrium-index/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Euclid-Mullin-sequence b/Lang/FutureBasic/Euclid-Mullin-sequence new file mode 120000 index 0000000000..20745da07c --- /dev/null +++ b/Lang/FutureBasic/Euclid-Mullin-sequence @@ -0,0 +1 @@ +../../Task/Euclid-Mullin-sequence/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Euler-method b/Lang/FutureBasic/Euler-method new file mode 120000 index 0000000000..89a7e85a03 --- /dev/null +++ b/Lang/FutureBasic/Euler-method @@ -0,0 +1 @@ +../../Task/Euler-method/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Evaluate-binomial-coefficients b/Lang/FutureBasic/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..59e49028f9 --- /dev/null +++ b/Lang/FutureBasic/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Evolutionary-algorithm b/Lang/FutureBasic/Evolutionary-algorithm new file mode 120000 index 0000000000..6ad9576429 --- /dev/null +++ b/Lang/FutureBasic/Evolutionary-algorithm @@ -0,0 +1 @@ +../../Task/Evolutionary-algorithm/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Exceptions b/Lang/FutureBasic/Exceptions new file mode 120000 index 0000000000..0e25a15f85 --- /dev/null +++ b/Lang/FutureBasic/Exceptions @@ -0,0 +1 @@ +../../Task/Exceptions/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Exceptions-Catch-an-exception-thrown-in-a-nested-call b/Lang/FutureBasic/Exceptions-Catch-an-exception-thrown-in-a-nested-call new file mode 120000 index 0000000000..fd7f3bd9e7 --- /dev/null +++ b/Lang/FutureBasic/Exceptions-Catch-an-exception-thrown-in-a-nested-call @@ -0,0 +1 @@ +../../Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/FASTA-format b/Lang/FutureBasic/FASTA-format new file mode 120000 index 0000000000..739187f0ef --- /dev/null +++ b/Lang/FutureBasic/FASTA-format @@ -0,0 +1 @@ +../../Task/FASTA-format/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Factors-of-a-Mersenne-number b/Lang/FutureBasic/Factors-of-a-Mersenne-number new file mode 120000 index 0000000000..c65e3bfb3a --- /dev/null +++ b/Lang/FutureBasic/Factors-of-a-Mersenne-number @@ -0,0 +1 @@ +../../Task/Factors-of-a-Mersenne-number/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Fermat-numbers b/Lang/FutureBasic/Fermat-numbers new file mode 120000 index 0000000000..2c5c3120a2 --- /dev/null +++ b/Lang/FutureBasic/Fermat-numbers @@ -0,0 +1 @@ +../../Task/Fermat-numbers/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Fibonacci-n-step-number-sequences b/Lang/FutureBasic/Fibonacci-n-step-number-sequences new file mode 120000 index 0000000000..4131a2e05b --- /dev/null +++ b/Lang/FutureBasic/Fibonacci-n-step-number-sequences @@ -0,0 +1 @@ +../../Task/Fibonacci-n-step-number-sequences/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Fibonacci-word b/Lang/FutureBasic/Fibonacci-word new file mode 120000 index 0000000000..c773eeed44 --- /dev/null +++ b/Lang/FutureBasic/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Find-limit-of-recursion b/Lang/FutureBasic/Find-limit-of-recursion new file mode 120000 index 0000000000..cbc1e3a568 --- /dev/null +++ b/Lang/FutureBasic/Find-limit-of-recursion @@ -0,0 +1 @@ +../../Task/Find-limit-of-recursion/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Find-the-missing-permutation b/Lang/FutureBasic/Find-the-missing-permutation new file mode 120000 index 0000000000..83f97c5dbb --- /dev/null +++ b/Lang/FutureBasic/Find-the-missing-permutation @@ -0,0 +1 @@ +../../Task/Find-the-missing-permutation/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Five-weekends b/Lang/FutureBasic/Five-weekends new file mode 120000 index 0000000000..d11a92b953 --- /dev/null +++ b/Lang/FutureBasic/Five-weekends @@ -0,0 +1 @@ +../../Task/Five-weekends/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Flipping-bits-game b/Lang/FutureBasic/Flipping-bits-game new file mode 120000 index 0000000000..439479c614 --- /dev/null +++ b/Lang/FutureBasic/Flipping-bits-game @@ -0,0 +1 @@ +../../Task/Flipping-bits-game/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Flow-control-structures b/Lang/FutureBasic/Flow-control-structures new file mode 120000 index 0000000000..47305c16bf --- /dev/null +++ b/Lang/FutureBasic/Flow-control-structures @@ -0,0 +1 @@ +../../Task/Flow-control-structures/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Floyds-triangle b/Lang/FutureBasic/Floyds-triangle new file mode 120000 index 0000000000..134b2be232 --- /dev/null +++ b/Lang/FutureBasic/Floyds-triangle @@ -0,0 +1 @@ +../../Task/Floyds-triangle/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Forest-fire b/Lang/FutureBasic/Forest-fire new file mode 120000 index 0000000000..5ed21f66e0 --- /dev/null +++ b/Lang/FutureBasic/Forest-fire @@ -0,0 +1 @@ +../../Task/Forest-fire/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Forward-difference b/Lang/FutureBasic/Forward-difference new file mode 120000 index 0000000000..8669b1c1f5 --- /dev/null +++ b/Lang/FutureBasic/Forward-difference @@ -0,0 +1 @@ +../../Task/Forward-difference/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Function-composition b/Lang/FutureBasic/Function-composition new file mode 120000 index 0000000000..363444c694 --- /dev/null +++ b/Lang/FutureBasic/Function-composition @@ -0,0 +1 @@ +../../Task/Function-composition/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Function-prototype b/Lang/FutureBasic/Function-prototype new file mode 120000 index 0000000000..00a31e111b --- /dev/null +++ b/Lang/FutureBasic/Function-prototype @@ -0,0 +1 @@ +../../Task/Function-prototype/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Fusc-sequence b/Lang/FutureBasic/Fusc-sequence new file mode 120000 index 0000000000..603bccf327 --- /dev/null +++ b/Lang/FutureBasic/Fusc-sequence @@ -0,0 +1 @@ +../../Task/Fusc-sequence/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Gamma-function b/Lang/FutureBasic/Gamma-function new file mode 120000 index 0000000000..fbf1cf8878 --- /dev/null +++ b/Lang/FutureBasic/Gamma-function @@ -0,0 +1 @@ +../../Task/Gamma-function/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Gaussian-elimination b/Lang/FutureBasic/Gaussian-elimination new file mode 120000 index 0000000000..f8adccdee8 --- /dev/null +++ b/Lang/FutureBasic/Gaussian-elimination @@ -0,0 +1 @@ +../../Task/Gaussian-elimination/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Go-Fish b/Lang/FutureBasic/Go-Fish new file mode 120000 index 0000000000..cc2210d25a --- /dev/null +++ b/Lang/FutureBasic/Go-Fish @@ -0,0 +1 @@ +../../Task/Go-Fish/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Golden-ratio-Convergence b/Lang/FutureBasic/Golden-ratio-Convergence new file mode 120000 index 0000000000..2807889e38 --- /dev/null +++ b/Lang/FutureBasic/Golden-ratio-Convergence @@ -0,0 +1 @@ +../../Task/Golden-ratio-Convergence/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Gray-code b/Lang/FutureBasic/Gray-code new file mode 120000 index 0000000000..5eafcaba04 --- /dev/null +++ b/Lang/FutureBasic/Gray-code @@ -0,0 +1 @@ +../../Task/Gray-code/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Greatest-subsequential-sum b/Lang/FutureBasic/Greatest-subsequential-sum new file mode 120000 index 0000000000..cf9f89b8cf --- /dev/null +++ b/Lang/FutureBasic/Greatest-subsequential-sum @@ -0,0 +1 @@ +../../Task/Greatest-subsequential-sum/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Greedy-algorithm-for-Egyptian-fractions b/Lang/FutureBasic/Greedy-algorithm-for-Egyptian-fractions new file mode 120000 index 0000000000..65dad8fc47 --- /dev/null +++ b/Lang/FutureBasic/Greedy-algorithm-for-Egyptian-fractions @@ -0,0 +1 @@ +../../Task/Greedy-algorithm-for-Egyptian-fractions/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Guess-the-number-With-feedback-player- b/Lang/FutureBasic/Guess-the-number-With-feedback-player- new file mode 120000 index 0000000000..0ee5d26b61 --- /dev/null +++ b/Lang/FutureBasic/Guess-the-number-With-feedback-player- @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback-player-/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/HTTPS-Authenticated b/Lang/FutureBasic/HTTPS-Authenticated new file mode 120000 index 0000000000..9edb1d8326 --- /dev/null +++ b/Lang/FutureBasic/HTTPS-Authenticated @@ -0,0 +1 @@ +../../Task/HTTPS-Authenticated/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Halt-and-catch-fire b/Lang/FutureBasic/Halt-and-catch-fire new file mode 120000 index 0000000000..d78c73210e --- /dev/null +++ b/Lang/FutureBasic/Halt-and-catch-fire @@ -0,0 +1 @@ +../../Task/Halt-and-catch-fire/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Hamming-numbers b/Lang/FutureBasic/Hamming-numbers new file mode 120000 index 0000000000..69b0f1ea7d --- /dev/null +++ b/Lang/FutureBasic/Hamming-numbers @@ -0,0 +1 @@ +../../Task/Hamming-numbers/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Hello-world-Standard-error b/Lang/FutureBasic/Hello-world-Standard-error new file mode 120000 index 0000000000..326ae936a9 --- /dev/null +++ b/Lang/FutureBasic/Hello-world-Standard-error @@ -0,0 +1 @@ +../../Task/Hello-world-Standard-error/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Here-document b/Lang/FutureBasic/Here-document new file mode 120000 index 0000000000..44b4edadd8 --- /dev/null +++ b/Lang/FutureBasic/Here-document @@ -0,0 +1 @@ +../../Task/Here-document/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Hickerson-series-of-almost-integers b/Lang/FutureBasic/Hickerson-series-of-almost-integers new file mode 120000 index 0000000000..22531fa967 --- /dev/null +++ b/Lang/FutureBasic/Hickerson-series-of-almost-integers @@ -0,0 +1 @@ +../../Task/Hickerson-series-of-almost-integers/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Hofstadter-Q-sequence b/Lang/FutureBasic/Hofstadter-Q-sequence new file mode 120000 index 0000000000..bb38370ecf --- /dev/null +++ b/Lang/FutureBasic/Hofstadter-Q-sequence @@ -0,0 +1 @@ +../../Task/Hofstadter-Q-sequence/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Home-primes b/Lang/FutureBasic/Home-primes new file mode 120000 index 0000000000..4744c5ec64 --- /dev/null +++ b/Lang/FutureBasic/Home-primes @@ -0,0 +1 @@ +../../Task/Home-primes/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Honeycombs b/Lang/FutureBasic/Honeycombs new file mode 120000 index 0000000000..306c30d982 --- /dev/null +++ b/Lang/FutureBasic/Honeycombs @@ -0,0 +1 @@ +../../Task/Honeycombs/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Host-introspection b/Lang/FutureBasic/Host-introspection new file mode 120000 index 0000000000..c342a7333a --- /dev/null +++ b/Lang/FutureBasic/Host-introspection @@ -0,0 +1 @@ +../../Task/Host-introspection/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Hunt-the-Wumpus b/Lang/FutureBasic/Hunt-the-Wumpus new file mode 120000 index 0000000000..6ac2d19ea6 --- /dev/null +++ b/Lang/FutureBasic/Hunt-the-Wumpus @@ -0,0 +1 @@ +../../Task/Hunt-the-Wumpus/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/ISBN13-check-digit b/Lang/FutureBasic/ISBN13-check-digit new file mode 120000 index 0000000000..ad5e4cffb4 --- /dev/null +++ b/Lang/FutureBasic/ISBN13-check-digit @@ -0,0 +1 @@ +../../Task/ISBN13-check-digit/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Integer-overflow b/Lang/FutureBasic/Integer-overflow new file mode 120000 index 0000000000..37f3cd9e93 --- /dev/null +++ b/Lang/FutureBasic/Integer-overflow @@ -0,0 +1 @@ +../../Task/Integer-overflow/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/JortSort b/Lang/FutureBasic/JortSort new file mode 120000 index 0000000000..a21b94121b --- /dev/null +++ b/Lang/FutureBasic/JortSort @@ -0,0 +1 @@ +../../Task/JortSort/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Josephus-problem b/Lang/FutureBasic/Josephus-problem new file mode 120000 index 0000000000..d84fa33d5d --- /dev/null +++ b/Lang/FutureBasic/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Juggler-sequence b/Lang/FutureBasic/Juggler-sequence new file mode 120000 index 0000000000..f39646025c --- /dev/null +++ b/Lang/FutureBasic/Juggler-sequence @@ -0,0 +1 @@ +../../Task/Juggler-sequence/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Keyboard-input-Flush-the-keyboard-buffer b/Lang/FutureBasic/Keyboard-input-Flush-the-keyboard-buffer new file mode 120000 index 0000000000..958993035a --- /dev/null +++ b/Lang/FutureBasic/Keyboard-input-Flush-the-keyboard-buffer @@ -0,0 +1 @@ +../../Task/Keyboard-input-Flush-the-keyboard-buffer/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Largest-number-divisible-by-its-digits b/Lang/FutureBasic/Largest-number-divisible-by-its-digits new file mode 120000 index 0000000000..3dcba1705b --- /dev/null +++ b/Lang/FutureBasic/Largest-number-divisible-by-its-digits @@ -0,0 +1 @@ +../../Task/Largest-number-divisible-by-its-digits/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Last-Friday-of-each-month b/Lang/FutureBasic/Last-Friday-of-each-month new file mode 120000 index 0000000000..a3476e0672 --- /dev/null +++ b/Lang/FutureBasic/Last-Friday-of-each-month @@ -0,0 +1 @@ +../../Task/Last-Friday-of-each-month/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Last-letter-first-letter b/Lang/FutureBasic/Last-letter-first-letter new file mode 120000 index 0000000000..82ed39c3f0 --- /dev/null +++ b/Lang/FutureBasic/Last-letter-first-letter @@ -0,0 +1 @@ +../../Task/Last-letter-first-letter/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Least-common-multiple b/Lang/FutureBasic/Least-common-multiple new file mode 120000 index 0000000000..23b8dbfe57 --- /dev/null +++ b/Lang/FutureBasic/Least-common-multiple @@ -0,0 +1 @@ +../../Task/Least-common-multiple/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Left-factorials b/Lang/FutureBasic/Left-factorials new file mode 120000 index 0000000000..b771fa0031 --- /dev/null +++ b/Lang/FutureBasic/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Long-literals-with-continuations b/Lang/FutureBasic/Long-literals-with-continuations new file mode 120000 index 0000000000..09dff817df --- /dev/null +++ b/Lang/FutureBasic/Long-literals-with-continuations @@ -0,0 +1 @@ +../../Task/Long-literals-with-continuations/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Long-multiplication b/Lang/FutureBasic/Long-multiplication new file mode 120000 index 0000000000..cc3dd93634 --- /dev/null +++ b/Lang/FutureBasic/Long-multiplication @@ -0,0 +1 @@ +../../Task/Long-multiplication/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Long-year b/Lang/FutureBasic/Long-year new file mode 120000 index 0000000000..ae89f1d742 --- /dev/null +++ b/Lang/FutureBasic/Long-year @@ -0,0 +1 @@ +../../Task/Long-year/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Loops-Increment-loop-index-within-loop-body b/Lang/FutureBasic/Loops-Increment-loop-index-within-loop-body new file mode 120000 index 0000000000..ff81b810cd --- /dev/null +++ b/Lang/FutureBasic/Loops-Increment-loop-index-within-loop-body @@ -0,0 +1 @@ +../../Task/Loops-Increment-loop-index-within-loop-body/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Lucas-Lehmer-test b/Lang/FutureBasic/Lucas-Lehmer-test new file mode 120000 index 0000000000..0d48052ee1 --- /dev/null +++ b/Lang/FutureBasic/Lucas-Lehmer-test @@ -0,0 +1 @@ +../../Task/Lucas-Lehmer-test/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/MAC-vendor-lookup b/Lang/FutureBasic/MAC-vendor-lookup new file mode 120000 index 0000000000..63a0a7c0b7 --- /dev/null +++ b/Lang/FutureBasic/MAC-vendor-lookup @@ -0,0 +1 @@ +../../Task/MAC-vendor-lookup/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Magic-constant b/Lang/FutureBasic/Magic-constant new file mode 120000 index 0000000000..1b88b55f67 --- /dev/null +++ b/Lang/FutureBasic/Magic-constant @@ -0,0 +1 @@ +../../Task/Magic-constant/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Man-or-boy-test b/Lang/FutureBasic/Man-or-boy-test new file mode 120000 index 0000000000..ffaf61719d --- /dev/null +++ b/Lang/FutureBasic/Man-or-boy-test @@ -0,0 +1 @@ +../../Task/Man-or-boy-test/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Mastermind b/Lang/FutureBasic/Mastermind new file mode 120000 index 0000000000..e02911b738 --- /dev/null +++ b/Lang/FutureBasic/Mastermind @@ -0,0 +1 @@ +../../Task/Mastermind/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Matrix-digital-rain b/Lang/FutureBasic/Matrix-digital-rain new file mode 120000 index 0000000000..26c9356719 --- /dev/null +++ b/Lang/FutureBasic/Matrix-digital-rain @@ -0,0 +1 @@ +../../Task/Matrix-digital-rain/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Mayan-calendar b/Lang/FutureBasic/Mayan-calendar new file mode 120000 index 0000000000..7b5f78ca25 --- /dev/null +++ b/Lang/FutureBasic/Mayan-calendar @@ -0,0 +1 @@ +../../Task/Mayan-calendar/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Mayan-numerals b/Lang/FutureBasic/Mayan-numerals new file mode 120000 index 0000000000..cbc6204e00 --- /dev/null +++ b/Lang/FutureBasic/Mayan-numerals @@ -0,0 +1 @@ +../../Task/Mayan-numerals/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Minesweeper-game b/Lang/FutureBasic/Minesweeper-game new file mode 120000 index 0000000000..fdc515bbc6 --- /dev/null +++ b/Lang/FutureBasic/Minesweeper-game @@ -0,0 +1 @@ +../../Task/Minesweeper-game/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Minimum-multiple-of-m-where-digital-sum-equals-m b/Lang/FutureBasic/Minimum-multiple-of-m-where-digital-sum-equals-m new file mode 120000 index 0000000000..088e4f56af --- /dev/null +++ b/Lang/FutureBasic/Minimum-multiple-of-m-where-digital-sum-equals-m @@ -0,0 +1 @@ +../../Task/Minimum-multiple-of-m-where-digital-sum-equals-m/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Modular-inverse b/Lang/FutureBasic/Modular-inverse new file mode 120000 index 0000000000..89556b3bbe --- /dev/null +++ b/Lang/FutureBasic/Modular-inverse @@ -0,0 +1 @@ +../../Task/Modular-inverse/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Monte-Carlo-methods b/Lang/FutureBasic/Monte-Carlo-methods new file mode 120000 index 0000000000..729102269f --- /dev/null +++ b/Lang/FutureBasic/Monte-Carlo-methods @@ -0,0 +1 @@ +../../Task/Monte-Carlo-methods/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Monty-Hall-problem b/Lang/FutureBasic/Monty-Hall-problem new file mode 120000 index 0000000000..0d9da7e7cc --- /dev/null +++ b/Lang/FutureBasic/Monty-Hall-problem @@ -0,0 +1 @@ +../../Task/Monty-Hall-problem/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Multi-dimensional-array b/Lang/FutureBasic/Multi-dimensional-array new file mode 120000 index 0000000000..89411e3bf7 --- /dev/null +++ b/Lang/FutureBasic/Multi-dimensional-array @@ -0,0 +1 @@ +../../Task/Multi-dimensional-array/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Munching-squares b/Lang/FutureBasic/Munching-squares new file mode 120000 index 0000000000..3fb288f688 --- /dev/null +++ b/Lang/FutureBasic/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Mutex b/Lang/FutureBasic/Mutex new file mode 120000 index 0000000000..027130dc63 --- /dev/null +++ b/Lang/FutureBasic/Mutex @@ -0,0 +1 @@ +../../Task/Mutex/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/N-queens-problem b/Lang/FutureBasic/N-queens-problem new file mode 120000 index 0000000000..68d9aebc8f --- /dev/null +++ b/Lang/FutureBasic/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Named-parameters b/Lang/FutureBasic/Named-parameters new file mode 120000 index 0000000000..77a79a818c --- /dev/null +++ b/Lang/FutureBasic/Named-parameters @@ -0,0 +1 @@ +../../Task/Named-parameters/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Nim-game b/Lang/FutureBasic/Nim-game new file mode 120000 index 0000000000..edc10ed0c5 --- /dev/null +++ b/Lang/FutureBasic/Nim-game @@ -0,0 +1 @@ +../../Task/Nim-game/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Nth b/Lang/FutureBasic/Nth new file mode 120000 index 0000000000..10c058fbd2 --- /dev/null +++ b/Lang/FutureBasic/Nth @@ -0,0 +1 @@ +../../Task/Nth/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Own-digits-power-sum b/Lang/FutureBasic/Own-digits-power-sum new file mode 120000 index 0000000000..5cd998b558 --- /dev/null +++ b/Lang/FutureBasic/Own-digits-power-sum @@ -0,0 +1 @@ +../../Task/Own-digits-power-sum/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Palindrome-dates b/Lang/FutureBasic/Palindrome-dates new file mode 120000 index 0000000000..2b72c0230b --- /dev/null +++ b/Lang/FutureBasic/Palindrome-dates @@ -0,0 +1 @@ +../../Task/Palindrome-dates/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Pascals-triangle b/Lang/FutureBasic/Pascals-triangle new file mode 120000 index 0000000000..31e8218285 --- /dev/null +++ b/Lang/FutureBasic/Pascals-triangle @@ -0,0 +1 @@ +../../Task/Pascals-triangle/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Pascals-triangle-Puzzle b/Lang/FutureBasic/Pascals-triangle-Puzzle new file mode 120000 index 0000000000..142f796d16 --- /dev/null +++ b/Lang/FutureBasic/Pascals-triangle-Puzzle @@ -0,0 +1 @@ +../../Task/Pascals-triangle-Puzzle/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Pentagram b/Lang/FutureBasic/Pentagram new file mode 120000 index 0000000000..036f2d484a --- /dev/null +++ b/Lang/FutureBasic/Pentagram @@ -0,0 +1 @@ +../../Task/Pentagram/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Perfect-shuffle b/Lang/FutureBasic/Perfect-shuffle new file mode 120000 index 0000000000..6d2e5e3668 --- /dev/null +++ b/Lang/FutureBasic/Perfect-shuffle @@ -0,0 +1 @@ +../../Task/Perfect-shuffle/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Pinstripe-Display b/Lang/FutureBasic/Pinstripe-Display new file mode 120000 index 0000000000..da5d8bc2b0 --- /dev/null +++ b/Lang/FutureBasic/Pinstripe-Display @@ -0,0 +1 @@ +../../Task/Pinstripe-Display/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Playing-cards b/Lang/FutureBasic/Playing-cards new file mode 120000 index 0000000000..965405f346 --- /dev/null +++ b/Lang/FutureBasic/Playing-cards @@ -0,0 +1 @@ +../../Task/Playing-cards/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Poker-hand-analyser b/Lang/FutureBasic/Poker-hand-analyser new file mode 120000 index 0000000000..35dd2acb93 --- /dev/null +++ b/Lang/FutureBasic/Poker-hand-analyser @@ -0,0 +1 @@ +../../Task/Poker-hand-analyser/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Prime-conspiracy b/Lang/FutureBasic/Prime-conspiracy new file mode 120000 index 0000000000..73d0f046b0 --- /dev/null +++ b/Lang/FutureBasic/Prime-conspiracy @@ -0,0 +1 @@ +../../Task/Prime-conspiracy/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Prime-decomposition b/Lang/FutureBasic/Prime-decomposition new file mode 120000 index 0000000000..16553faec7 --- /dev/null +++ b/Lang/FutureBasic/Prime-decomposition @@ -0,0 +1 @@ +../../Task/Prime-decomposition/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Pythagorean-triples b/Lang/FutureBasic/Pythagorean-triples new file mode 120000 index 0000000000..f0267047e8 --- /dev/null +++ b/Lang/FutureBasic/Pythagorean-triples @@ -0,0 +1 @@ +../../Task/Pythagorean-triples/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Radical-of-an-integer b/Lang/FutureBasic/Radical-of-an-integer new file mode 120000 index 0000000000..6713bbf881 --- /dev/null +++ b/Lang/FutureBasic/Radical-of-an-integer @@ -0,0 +1 @@ +../../Task/Radical-of-an-integer/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Range-expansion b/Lang/FutureBasic/Range-expansion new file mode 120000 index 0000000000..9b92918178 --- /dev/null +++ b/Lang/FutureBasic/Range-expansion @@ -0,0 +1 @@ +../../Task/Range-expansion/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Range-extraction b/Lang/FutureBasic/Range-extraction new file mode 120000 index 0000000000..9a5f1d0533 --- /dev/null +++ b/Lang/FutureBasic/Range-extraction @@ -0,0 +1 @@ +../../Task/Range-extraction/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Read-a-file-character-by-character-UTF8 b/Lang/FutureBasic/Read-a-file-character-by-character-UTF8 new file mode 120000 index 0000000000..beadc18b56 --- /dev/null +++ b/Lang/FutureBasic/Read-a-file-character-by-character-UTF8 @@ -0,0 +1 @@ +../../Task/Read-a-file-character-by-character-UTF8/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Read-a-file-line-by-line b/Lang/FutureBasic/Read-a-file-line-by-line new file mode 120000 index 0000000000..43ff8334a4 --- /dev/null +++ b/Lang/FutureBasic/Read-a-file-line-by-line @@ -0,0 +1 @@ +../../Task/Read-a-file-line-by-line/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Record-sound b/Lang/FutureBasic/Record-sound new file mode 120000 index 0000000000..7ce89c688d --- /dev/null +++ b/Lang/FutureBasic/Record-sound @@ -0,0 +1 @@ +../../Task/Record-sound/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Regular-expressions b/Lang/FutureBasic/Regular-expressions new file mode 120000 index 0000000000..cd49461444 --- /dev/null +++ b/Lang/FutureBasic/Regular-expressions @@ -0,0 +1 @@ +../../Task/Regular-expressions/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Rep-string b/Lang/FutureBasic/Rep-string new file mode 120000 index 0000000000..99b81bb2f4 --- /dev/null +++ b/Lang/FutureBasic/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Repunit-primes b/Lang/FutureBasic/Repunit-primes new file mode 120000 index 0000000000..366d1fc05e --- /dev/null +++ b/Lang/FutureBasic/Repunit-primes @@ -0,0 +1 @@ +../../Task/Repunit-primes/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Resistor-mesh b/Lang/FutureBasic/Resistor-mesh new file mode 120000 index 0000000000..318a1a0f13 --- /dev/null +++ b/Lang/FutureBasic/Resistor-mesh @@ -0,0 +1 @@ +../../Task/Resistor-mesh/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/SEDOLs b/Lang/FutureBasic/SEDOLs new file mode 120000 index 0000000000..87a0048d3a --- /dev/null +++ b/Lang/FutureBasic/SEDOLs @@ -0,0 +1 @@ +../../Task/SEDOLs/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/SHA-256 b/Lang/FutureBasic/SHA-256 new file mode 120000 index 0000000000..0d14776e97 --- /dev/null +++ b/Lang/FutureBasic/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Search-a-list-of-records b/Lang/FutureBasic/Search-a-list-of-records new file mode 120000 index 0000000000..3fefc25b7b --- /dev/null +++ b/Lang/FutureBasic/Search-a-list-of-records @@ -0,0 +1 @@ +../../Task/Search-a-list-of-records/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Semiprime b/Lang/FutureBasic/Semiprime new file mode 120000 index 0000000000..71cf62e6e6 --- /dev/null +++ b/Lang/FutureBasic/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Semordnilap b/Lang/FutureBasic/Semordnilap new file mode 120000 index 0000000000..23f6715ad0 --- /dev/null +++ b/Lang/FutureBasic/Semordnilap @@ -0,0 +1 @@ +../../Task/Semordnilap/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Sequence-of-primorial-primes b/Lang/FutureBasic/Sequence-of-primorial-primes new file mode 120000 index 0000000000..9447c777cb --- /dev/null +++ b/Lang/FutureBasic/Sequence-of-primorial-primes @@ -0,0 +1 @@ +../../Task/Sequence-of-primorial-primes/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Sierpinski-arrowhead-curve b/Lang/FutureBasic/Sierpinski-arrowhead-curve new file mode 120000 index 0000000000..d52f730a0b --- /dev/null +++ b/Lang/FutureBasic/Sierpinski-arrowhead-curve @@ -0,0 +1 @@ +../../Task/Sierpinski-arrowhead-curve/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Sierpinski-carpet b/Lang/FutureBasic/Sierpinski-carpet new file mode 120000 index 0000000000..c79bb878a8 --- /dev/null +++ b/Lang/FutureBasic/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Sierpinski-pentagon b/Lang/FutureBasic/Sierpinski-pentagon new file mode 120000 index 0000000000..1e105b6fb4 --- /dev/null +++ b/Lang/FutureBasic/Sierpinski-pentagon @@ -0,0 +1 @@ +../../Task/Sierpinski-pentagon/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Sierpinski-square-curve b/Lang/FutureBasic/Sierpinski-square-curve new file mode 120000 index 0000000000..2938f1fa47 --- /dev/null +++ b/Lang/FutureBasic/Sierpinski-square-curve @@ -0,0 +1 @@ +../../Task/Sierpinski-square-curve/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Sierpinski-triangle b/Lang/FutureBasic/Sierpinski-triangle new file mode 120000 index 0000000000..300049c10c --- /dev/null +++ b/Lang/FutureBasic/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Sleep b/Lang/FutureBasic/Sleep new file mode 120000 index 0000000000..8ce099ff7d --- /dev/null +++ b/Lang/FutureBasic/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Smallest-number-k-such-that-k+2^m-is-composite-for-all-m-less-than-k b/Lang/FutureBasic/Smallest-number-k-such-that-k+2^m-is-composite-for-all-m-less-than-k new file mode 120000 index 0000000000..8cc89de701 --- /dev/null +++ b/Lang/FutureBasic/Smallest-number-k-such-that-k+2^m-is-composite-for-all-m-less-than-k @@ -0,0 +1 @@ +../../Task/Smallest-number-k-such-that-k+2^m-is-composite-for-all-m-less-than-k/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Smarandache-Wellin-primes b/Lang/FutureBasic/Smarandache-Wellin-primes new file mode 120000 index 0000000000..7564a9b0b8 --- /dev/null +++ b/Lang/FutureBasic/Smarandache-Wellin-primes @@ -0,0 +1 @@ +../../Task/Smarandache-Wellin-primes/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Smarandache-prime-digital-sequence b/Lang/FutureBasic/Smarandache-prime-digital-sequence new file mode 120000 index 0000000000..879ea05348 --- /dev/null +++ b/Lang/FutureBasic/Smarandache-prime-digital-sequence @@ -0,0 +1 @@ +../../Task/Smarandache-prime-digital-sequence/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Sort-an-array-of-composite-structures b/Lang/FutureBasic/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..ffd97b8a5e --- /dev/null +++ b/Lang/FutureBasic/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Sort-disjoint-sublist b/Lang/FutureBasic/Sort-disjoint-sublist new file mode 120000 index 0000000000..030bf0bfd7 --- /dev/null +++ b/Lang/FutureBasic/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Sort-numbers-lexicographically b/Lang/FutureBasic/Sort-numbers-lexicographically new file mode 120000 index 0000000000..b8d6f91892 --- /dev/null +++ b/Lang/FutureBasic/Sort-numbers-lexicographically @@ -0,0 +1 @@ +../../Task/Sort-numbers-lexicographically/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Sort-three-variables b/Lang/FutureBasic/Sort-three-variables new file mode 120000 index 0000000000..48424426c7 --- /dev/null +++ b/Lang/FutureBasic/Sort-three-variables @@ -0,0 +1 @@ +../../Task/Sort-three-variables/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Sorting-algorithms-Insertion-sort b/Lang/FutureBasic/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..d1f91f0286 --- /dev/null +++ b/Lang/FutureBasic/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Sorting-algorithms-Sleep-sort b/Lang/FutureBasic/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..b94b39a51d --- /dev/null +++ b/Lang/FutureBasic/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Spinning-rod-animation-Text b/Lang/FutureBasic/Spinning-rod-animation-Text new file mode 120000 index 0000000000..a0c68e7478 --- /dev/null +++ b/Lang/FutureBasic/Spinning-rod-animation-Text @@ -0,0 +1 @@ +../../Task/Spinning-rod-animation-Text/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Spiral-matrix b/Lang/FutureBasic/Spiral-matrix new file mode 120000 index 0000000000..4d24174200 --- /dev/null +++ b/Lang/FutureBasic/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Square-but-not-cube b/Lang/FutureBasic/Square-but-not-cube new file mode 120000 index 0000000000..a8c6d02eba --- /dev/null +++ b/Lang/FutureBasic/Square-but-not-cube @@ -0,0 +1 @@ +../../Task/Square-but-not-cube/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Square-free-integers b/Lang/FutureBasic/Square-free-integers new file mode 120000 index 0000000000..d3a0459f3e --- /dev/null +++ b/Lang/FutureBasic/Square-free-integers @@ -0,0 +1 @@ +../../Task/Square-free-integers/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Stack b/Lang/FutureBasic/Stack new file mode 120000 index 0000000000..638a183bbc --- /dev/null +++ b/Lang/FutureBasic/Stack @@ -0,0 +1 @@ +../../Task/Stack/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Stack-traces b/Lang/FutureBasic/Stack-traces new file mode 120000 index 0000000000..589e50b2fa --- /dev/null +++ b/Lang/FutureBasic/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Start-from-a-main-routine b/Lang/FutureBasic/Start-from-a-main-routine new file mode 120000 index 0000000000..c3215fed19 --- /dev/null +++ b/Lang/FutureBasic/Start-from-a-main-routine @@ -0,0 +1 @@ +../../Task/Start-from-a-main-routine/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/String-length b/Lang/FutureBasic/String-length new file mode 120000 index 0000000000..6df040b0bc --- /dev/null +++ b/Lang/FutureBasic/String-length @@ -0,0 +1 @@ +../../Task/String-length/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Strip-block-comments b/Lang/FutureBasic/Strip-block-comments new file mode 120000 index 0000000000..1f0c4fb53d --- /dev/null +++ b/Lang/FutureBasic/Strip-block-comments @@ -0,0 +1 @@ +../../Task/Strip-block-comments/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Strip-control-codes-and-extended-characters-from-a-string b/Lang/FutureBasic/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..ae3840dae2 --- /dev/null +++ b/Lang/FutureBasic/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Sudan-function b/Lang/FutureBasic/Sudan-function new file mode 120000 index 0000000000..1f582a9d0d --- /dev/null +++ b/Lang/FutureBasic/Sudan-function @@ -0,0 +1 @@ +../../Task/Sudan-function/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Sum-digits-of-an-integer b/Lang/FutureBasic/Sum-digits-of-an-integer new file mode 120000 index 0000000000..cf8ab32c2c --- /dev/null +++ b/Lang/FutureBasic/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Sum-of-a-series b/Lang/FutureBasic/Sum-of-a-series new file mode 120000 index 0000000000..44687bc461 --- /dev/null +++ b/Lang/FutureBasic/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Sum-of-squares b/Lang/FutureBasic/Sum-of-squares new file mode 120000 index 0000000000..3bded3f286 --- /dev/null +++ b/Lang/FutureBasic/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Sum-to-100 b/Lang/FutureBasic/Sum-to-100 new file mode 120000 index 0000000000..5cdb7cf4a8 --- /dev/null +++ b/Lang/FutureBasic/Sum-to-100 @@ -0,0 +1 @@ +../../Task/Sum-to-100/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Super-d-numbers b/Lang/FutureBasic/Super-d-numbers new file mode 120000 index 0000000000..77af2a994a --- /dev/null +++ b/Lang/FutureBasic/Super-d-numbers @@ -0,0 +1 @@ +../../Task/Super-d-numbers/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Sylvesters-sequence b/Lang/FutureBasic/Sylvesters-sequence new file mode 120000 index 0000000000..1e1ae008f1 --- /dev/null +++ b/Lang/FutureBasic/Sylvesters-sequence @@ -0,0 +1 @@ +../../Task/Sylvesters-sequence/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Tau-function b/Lang/FutureBasic/Tau-function new file mode 120000 index 0000000000..4d9cc08c3d --- /dev/null +++ b/Lang/FutureBasic/Tau-function @@ -0,0 +1 @@ +../../Task/Tau-function/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Tau-number b/Lang/FutureBasic/Tau-number new file mode 120000 index 0000000000..363cfbc636 --- /dev/null +++ b/Lang/FutureBasic/Tau-number @@ -0,0 +1 @@ +../../Task/Tau-number/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Temperature-conversion b/Lang/FutureBasic/Temperature-conversion new file mode 120000 index 0000000000..b60c2baf77 --- /dev/null +++ b/Lang/FutureBasic/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Terminal-control-Clear-the-screen b/Lang/FutureBasic/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..878687a038 --- /dev/null +++ b/Lang/FutureBasic/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Terminal-control-Coloured-text b/Lang/FutureBasic/Terminal-control-Coloured-text new file mode 120000 index 0000000000..6858a62734 --- /dev/null +++ b/Lang/FutureBasic/Terminal-control-Coloured-text @@ -0,0 +1 @@ +../../Task/Terminal-control-Coloured-text/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Terminal-control-Cursor-movement b/Lang/FutureBasic/Terminal-control-Cursor-movement new file mode 120000 index 0000000000..050e1439d6 --- /dev/null +++ b/Lang/FutureBasic/Terminal-control-Cursor-movement @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-movement/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Terminal-control-Cursor-positioning b/Lang/FutureBasic/Terminal-control-Cursor-positioning new file mode 120000 index 0000000000..22f710aaf6 --- /dev/null +++ b/Lang/FutureBasic/Terminal-control-Cursor-positioning @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-positioning/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Terminal-control-Hiding-the-cursor b/Lang/FutureBasic/Terminal-control-Hiding-the-cursor new file mode 120000 index 0000000000..22bc1dda83 --- /dev/null +++ b/Lang/FutureBasic/Terminal-control-Hiding-the-cursor @@ -0,0 +1 @@ +../../Task/Terminal-control-Hiding-the-cursor/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Terminal-control-Ringing-the-terminal-bell b/Lang/FutureBasic/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..6f8d6c609a --- /dev/null +++ b/Lang/FutureBasic/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Terminal-control-Unicode-output b/Lang/FutureBasic/Terminal-control-Unicode-output new file mode 120000 index 0000000000..712dfa9fa9 --- /dev/null +++ b/Lang/FutureBasic/Terminal-control-Unicode-output @@ -0,0 +1 @@ +../../Task/Terminal-control-Unicode-output/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/The-Name-Game b/Lang/FutureBasic/The-Name-Game new file mode 120000 index 0000000000..2e6c9ef1a6 --- /dev/null +++ b/Lang/FutureBasic/The-Name-Game @@ -0,0 +1 @@ +../../Task/The-Name-Game/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/The-sieve-of-Sundaram b/Lang/FutureBasic/The-sieve-of-Sundaram new file mode 120000 index 0000000000..439633bf42 --- /dev/null +++ b/Lang/FutureBasic/The-sieve-of-Sundaram @@ -0,0 +1 @@ +../../Task/The-sieve-of-Sundaram/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Tic-tac-toe b/Lang/FutureBasic/Tic-tac-toe new file mode 120000 index 0000000000..e0c70b24fe --- /dev/null +++ b/Lang/FutureBasic/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Time-a-function b/Lang/FutureBasic/Time-a-function new file mode 120000 index 0000000000..819601365f --- /dev/null +++ b/Lang/FutureBasic/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Transliterate-English-text-using-the-Greek-alphabet b/Lang/FutureBasic/Transliterate-English-text-using-the-Greek-alphabet new file mode 120000 index 0000000000..f300e3db8a --- /dev/null +++ b/Lang/FutureBasic/Transliterate-English-text-using-the-Greek-alphabet @@ -0,0 +1 @@ +../../Task/Transliterate-English-text-using-the-Greek-alphabet/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Truncate-a-file b/Lang/FutureBasic/Truncate-a-file new file mode 120000 index 0000000000..29710d148d --- /dev/null +++ b/Lang/FutureBasic/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Twin-primes b/Lang/FutureBasic/Twin-primes new file mode 120000 index 0000000000..172e832801 --- /dev/null +++ b/Lang/FutureBasic/Twin-primes @@ -0,0 +1 @@ +../../Task/Twin-primes/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/URL-decoding b/Lang/FutureBasic/URL-decoding new file mode 120000 index 0000000000..001e7a5dfa --- /dev/null +++ b/Lang/FutureBasic/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/URL-parser b/Lang/FutureBasic/URL-parser new file mode 120000 index 0000000000..46cddba12b --- /dev/null +++ b/Lang/FutureBasic/URL-parser @@ -0,0 +1 @@ +../../Task/URL-parser/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Ultra-useful-primes b/Lang/FutureBasic/Ultra-useful-primes new file mode 120000 index 0000000000..eff79aec0f --- /dev/null +++ b/Lang/FutureBasic/Ultra-useful-primes @@ -0,0 +1 @@ +../../Task/Ultra-useful-primes/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Unicode-strings b/Lang/FutureBasic/Unicode-strings new file mode 120000 index 0000000000..dd71b73f3c --- /dev/null +++ b/Lang/FutureBasic/Unicode-strings @@ -0,0 +1 @@ +../../Task/Unicode-strings/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Use-another-language-to-call-a-function b/Lang/FutureBasic/Use-another-language-to-call-a-function new file mode 120000 index 0000000000..704ff5c0c8 --- /dev/null +++ b/Lang/FutureBasic/Use-another-language-to-call-a-function @@ -0,0 +1 @@ +../../Task/Use-another-language-to-call-a-function/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/User-input-Text b/Lang/FutureBasic/User-input-Text new file mode 120000 index 0000000000..3d0e3bd7f1 --- /dev/null +++ b/Lang/FutureBasic/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Validate-International-Securities-Identification-Number b/Lang/FutureBasic/Validate-International-Securities-Identification-Number new file mode 120000 index 0000000000..81f74f067a --- /dev/null +++ b/Lang/FutureBasic/Validate-International-Securities-Identification-Number @@ -0,0 +1 @@ +../../Task/Validate-International-Securities-Identification-Number/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Wagstaff-primes b/Lang/FutureBasic/Wagstaff-primes new file mode 120000 index 0000000000..455c60b96b --- /dev/null +++ b/Lang/FutureBasic/Wagstaff-primes @@ -0,0 +1 @@ +../../Task/Wagstaff-primes/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Wieferich-primes b/Lang/FutureBasic/Wieferich-primes new file mode 120000 index 0000000000..1c38642d13 --- /dev/null +++ b/Lang/FutureBasic/Wieferich-primes @@ -0,0 +1 @@ +../../Task/Wieferich-primes/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Wilson-primes-of-order-n b/Lang/FutureBasic/Wilson-primes-of-order-n new file mode 120000 index 0000000000..027bdd5d80 --- /dev/null +++ b/Lang/FutureBasic/Wilson-primes-of-order-n @@ -0,0 +1 @@ +../../Task/Wilson-primes-of-order-n/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Word-wrap b/Lang/FutureBasic/Word-wrap new file mode 120000 index 0000000000..d1cd565464 --- /dev/null +++ b/Lang/FutureBasic/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/XML-Output b/Lang/FutureBasic/XML-Output new file mode 120000 index 0000000000..7889975674 --- /dev/null +++ b/Lang/FutureBasic/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Yahoo-search-interface b/Lang/FutureBasic/Yahoo-search-interface new file mode 120000 index 0000000000..9f29c6ac04 --- /dev/null +++ b/Lang/FutureBasic/Yahoo-search-interface @@ -0,0 +1 @@ +../../Task/Yahoo-search-interface/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Yellowstone-sequence b/Lang/FutureBasic/Yellowstone-sequence new file mode 120000 index 0000000000..8a816499f6 --- /dev/null +++ b/Lang/FutureBasic/Yellowstone-sequence @@ -0,0 +1 @@ +../../Task/Yellowstone-sequence/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Zebra-puzzle b/Lang/FutureBasic/Zebra-puzzle new file mode 120000 index 0000000000..68d36dbfcd --- /dev/null +++ b/Lang/FutureBasic/Zebra-puzzle @@ -0,0 +1 @@ +../../Task/Zebra-puzzle/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Zeckendorf-number-representation b/Lang/FutureBasic/Zeckendorf-number-representation new file mode 120000 index 0000000000..c805683421 --- /dev/null +++ b/Lang/FutureBasic/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/FutureBasic \ No newline at end of file diff --git a/Lang/GAP/Character-codes b/Lang/GAP/Character-codes new file mode 120000 index 0000000000..ff4a3d2754 --- /dev/null +++ b/Lang/GAP/Character-codes @@ -0,0 +1 @@ +../../Task/Character-codes/GAP \ No newline at end of file diff --git a/Lang/GAP/Quaternion-type b/Lang/GAP/Quaternion-type deleted file mode 120000 index 67ec7fa115..0000000000 --- a/Lang/GAP/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/GAP \ No newline at end of file diff --git a/Lang/GDScript/Playing-cards b/Lang/GDScript/Playing-cards new file mode 120000 index 0000000000..11180c642f --- /dev/null +++ b/Lang/GDScript/Playing-cards @@ -0,0 +1 @@ +../../Task/Playing-cards/GDScript \ No newline at end of file diff --git a/Lang/GW-BASIC/Abundant-deficient-and-perfect-number-classifications b/Lang/GW-BASIC/Abundant-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..4709185f8a --- /dev/null +++ b/Lang/GW-BASIC/Abundant-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant-deficient-and-perfect-number-classifications/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Associative-array-Merging b/Lang/GW-BASIC/Associative-array-Merging new file mode 120000 index 0000000000..bd171c9e89 --- /dev/null +++ b/Lang/GW-BASIC/Associative-array-Merging @@ -0,0 +1 @@ +../../Task/Associative-array-Merging/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Case-sensitivity-of-identifiers b/Lang/GW-BASIC/Case-sensitivity-of-identifiers deleted file mode 120000 index 605ddebd53..0000000000 --- a/Lang/GW-BASIC/Case-sensitivity-of-identifiers +++ /dev/null @@ -1 +0,0 @@ -../../Task/Case-sensitivity-of-identifiers/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Colour-pinstripe-Display b/Lang/GW-BASIC/Colour-pinstripe-Display new file mode 120000 index 0000000000..383619acfb --- /dev/null +++ b/Lang/GW-BASIC/Colour-pinstripe-Display @@ -0,0 +1 @@ +../../Task/Colour-pinstripe-Display/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Damm-algorithm b/Lang/GW-BASIC/Damm-algorithm new file mode 120000 index 0000000000..b0cc19e6df --- /dev/null +++ b/Lang/GW-BASIC/Damm-algorithm @@ -0,0 +1 @@ +../../Task/Damm-algorithm/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Determine-if-a-string-is-collapsible b/Lang/GW-BASIC/Determine-if-a-string-is-collapsible new file mode 120000 index 0000000000..2b997d0c38 --- /dev/null +++ b/Lang/GW-BASIC/Determine-if-a-string-is-collapsible @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-collapsible/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Determine-sentence-type b/Lang/GW-BASIC/Determine-sentence-type new file mode 120000 index 0000000000..0a4310dab2 --- /dev/null +++ b/Lang/GW-BASIC/Determine-sentence-type @@ -0,0 +1 @@ +../../Task/Determine-sentence-type/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Display-a-linear-combination b/Lang/GW-BASIC/Display-a-linear-combination new file mode 120000 index 0000000000..8162367d7b --- /dev/null +++ b/Lang/GW-BASIC/Display-a-linear-combination @@ -0,0 +1 @@ +../../Task/Display-a-linear-combination/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Dutch-national-flag-problem b/Lang/GW-BASIC/Dutch-national-flag-problem new file mode 120000 index 0000000000..96431612bd --- /dev/null +++ b/Lang/GW-BASIC/Dutch-national-flag-problem @@ -0,0 +1 @@ +../../Task/Dutch-national-flag-problem/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Gray-code b/Lang/GW-BASIC/Gray-code new file mode 120000 index 0000000000..a45f2031ed --- /dev/null +++ b/Lang/GW-BASIC/Gray-code @@ -0,0 +1 @@ +../../Task/Gray-code/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Jensens-Device b/Lang/GW-BASIC/Jensens-Device new file mode 120000 index 0000000000..0236b00319 --- /dev/null +++ b/Lang/GW-BASIC/Jensens-Device @@ -0,0 +1 @@ +../../Task/Jensens-Device/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Langtons-ant b/Lang/GW-BASIC/Langtons-ant new file mode 120000 index 0000000000..4d565760ef --- /dev/null +++ b/Lang/GW-BASIC/Langtons-ant @@ -0,0 +1 @@ +../../Task/Langtons-ant/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Leonardo-numbers b/Lang/GW-BASIC/Leonardo-numbers new file mode 120000 index 0000000000..f7945f7063 --- /dev/null +++ b/Lang/GW-BASIC/Leonardo-numbers @@ -0,0 +1 @@ +../../Task/Leonardo-numbers/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Levenshtein-distance b/Lang/GW-BASIC/Levenshtein-distance new file mode 120000 index 0000000000..4605e15436 --- /dev/null +++ b/Lang/GW-BASIC/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Luhn-test-of-credit-card-numbers b/Lang/GW-BASIC/Luhn-test-of-credit-card-numbers new file mode 120000 index 0000000000..3e46368b55 --- /dev/null +++ b/Lang/GW-BASIC/Luhn-test-of-credit-card-numbers @@ -0,0 +1 @@ +../../Task/Luhn-test-of-credit-card-numbers/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Magic-constant b/Lang/GW-BASIC/Magic-constant new file mode 120000 index 0000000000..4dbe3ee401 --- /dev/null +++ b/Lang/GW-BASIC/Magic-constant @@ -0,0 +1 @@ +../../Task/Magic-constant/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Map-range b/Lang/GW-BASIC/Map-range new file mode 120000 index 0000000000..487538bdd0 --- /dev/null +++ b/Lang/GW-BASIC/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Mayan-numerals b/Lang/GW-BASIC/Mayan-numerals new file mode 120000 index 0000000000..5c6a4bdb6a --- /dev/null +++ b/Lang/GW-BASIC/Mayan-numerals @@ -0,0 +1 @@ +../../Task/Mayan-numerals/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Nested-templated-data b/Lang/GW-BASIC/Nested-templated-data new file mode 120000 index 0000000000..bb39849801 --- /dev/null +++ b/Lang/GW-BASIC/Nested-templated-data @@ -0,0 +1 @@ +../../Task/Nested-templated-data/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Nth-root b/Lang/GW-BASIC/Nth-root new file mode 120000 index 0000000000..44da5f255f --- /dev/null +++ b/Lang/GW-BASIC/Nth-root @@ -0,0 +1 @@ +../../Task/Nth-root/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Old-Russian-measure-of-length b/Lang/GW-BASIC/Old-Russian-measure-of-length new file mode 120000 index 0000000000..6121a6a7b1 --- /dev/null +++ b/Lang/GW-BASIC/Old-Russian-measure-of-length @@ -0,0 +1 @@ +../../Task/Old-Russian-measure-of-length/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Phrase-reversals b/Lang/GW-BASIC/Phrase-reversals new file mode 120000 index 0000000000..f735fa85b8 --- /dev/null +++ b/Lang/GW-BASIC/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Pinstripe-Display b/Lang/GW-BASIC/Pinstripe-Display new file mode 120000 index 0000000000..282b987dfa --- /dev/null +++ b/Lang/GW-BASIC/Pinstripe-Display @@ -0,0 +1 @@ +../../Task/Pinstripe-Display/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Primality-by-trial-division b/Lang/GW-BASIC/Primality-by-trial-division new file mode 120000 index 0000000000..2b782a101b --- /dev/null +++ b/Lang/GW-BASIC/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Sort-an-integer-array b/Lang/GW-BASIC/Sort-an-integer-array new file mode 120000 index 0000000000..47749b90fd --- /dev/null +++ b/Lang/GW-BASIC/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Split-a-character-string-based-on-change-of-character b/Lang/GW-BASIC/Split-a-character-string-based-on-change-of-character new file mode 120000 index 0000000000..55c414402a --- /dev/null +++ b/Lang/GW-BASIC/Split-a-character-string-based-on-change-of-character @@ -0,0 +1 @@ +../../Task/Split-a-character-string-based-on-change-of-character/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Sum-of-a-series b/Lang/GW-BASIC/Sum-of-a-series new file mode 120000 index 0000000000..0eb15c49ab --- /dev/null +++ b/Lang/GW-BASIC/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Twos-complement b/Lang/GW-BASIC/Twos-complement new file mode 120000 index 0000000000..6a1e61b45b --- /dev/null +++ b/Lang/GW-BASIC/Twos-complement @@ -0,0 +1 @@ +../../Task/Twos-complement/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Vector b/Lang/GW-BASIC/Vector new file mode 120000 index 0000000000..6d1d7a6796 --- /dev/null +++ b/Lang/GW-BASIC/Vector @@ -0,0 +1 @@ +../../Task/Vector/GW-BASIC \ No newline at end of file diff --git a/Lang/Gambas/Determine-if-a-string-has-all-the-same-characters b/Lang/Gambas/Determine-if-a-string-has-all-the-same-characters new file mode 120000 index 0000000000..448e7d07b5 --- /dev/null +++ b/Lang/Gambas/Determine-if-a-string-has-all-the-same-characters @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-has-all-the-same-characters/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Determine-sentence-type b/Lang/Gambas/Determine-sentence-type new file mode 120000 index 0000000000..2d6d98f0ec --- /dev/null +++ b/Lang/Gambas/Determine-sentence-type @@ -0,0 +1 @@ +../../Task/Determine-sentence-type/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Diversity-prediction-theorem b/Lang/Gambas/Diversity-prediction-theorem new file mode 120000 index 0000000000..f0154a9ba0 --- /dev/null +++ b/Lang/Gambas/Diversity-prediction-theorem @@ -0,0 +1 @@ +../../Task/Diversity-prediction-theorem/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Eban-numbers b/Lang/Gambas/Eban-numbers new file mode 120000 index 0000000000..238b6dbb7b --- /dev/null +++ b/Lang/Gambas/Eban-numbers @@ -0,0 +1 @@ +../../Task/Eban-numbers/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Evaluate-binomial-coefficients b/Lang/Gambas/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..d84c9e286a --- /dev/null +++ b/Lang/Gambas/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Generate-Chess960-starting-position b/Lang/Gambas/Generate-Chess960-starting-position new file mode 120000 index 0000000000..3ee17430bf --- /dev/null +++ b/Lang/Gambas/Generate-Chess960-starting-position @@ -0,0 +1 @@ +../../Task/Generate-Chess960-starting-position/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Hofstadter-Q-sequence b/Lang/Gambas/Hofstadter-Q-sequence new file mode 120000 index 0000000000..6288d88da4 --- /dev/null +++ b/Lang/Gambas/Hofstadter-Q-sequence @@ -0,0 +1 @@ +../../Task/Hofstadter-Q-sequence/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Jensens-Device b/Lang/Gambas/Jensens-Device new file mode 120000 index 0000000000..cf682dd548 --- /dev/null +++ b/Lang/Gambas/Jensens-Device @@ -0,0 +1 @@ +../../Task/Jensens-Device/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Jewels-and-stones b/Lang/Gambas/Jewels-and-stones new file mode 120000 index 0000000000..b13ca1d825 --- /dev/null +++ b/Lang/Gambas/Jewels-and-stones @@ -0,0 +1 @@ +../../Task/Jewels-and-stones/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Leonardo-numbers b/Lang/Gambas/Leonardo-numbers new file mode 120000 index 0000000000..92f225b368 --- /dev/null +++ b/Lang/Gambas/Leonardo-numbers @@ -0,0 +1 @@ +../../Task/Leonardo-numbers/Gambas \ No newline at end of file diff --git a/Lang/Gambas/M-bius-function b/Lang/Gambas/M-bius-function new file mode 120000 index 0000000000..4846367944 --- /dev/null +++ b/Lang/Gambas/M-bius-function @@ -0,0 +1 @@ +../../Task/M-bius-function/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Magic-constant b/Lang/Gambas/Magic-constant new file mode 120000 index 0000000000..3e63290c94 --- /dev/null +++ b/Lang/Gambas/Magic-constant @@ -0,0 +1 @@ +../../Task/Magic-constant/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Map-range b/Lang/Gambas/Map-range new file mode 120000 index 0000000000..47ffb049ec --- /dev/null +++ b/Lang/Gambas/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Proper-divisors b/Lang/Gambas/Proper-divisors new file mode 120000 index 0000000000..c95a4aae71 --- /dev/null +++ b/Lang/Gambas/Proper-divisors @@ -0,0 +1 @@ +../../Task/Proper-divisors/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Sort-disjoint-sublist b/Lang/Gambas/Sort-disjoint-sublist new file mode 120000 index 0000000000..d77e8ada49 --- /dev/null +++ b/Lang/Gambas/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/Gambas \ No newline at end of file diff --git a/Lang/Gambas/The-Name-Game b/Lang/Gambas/The-Name-Game new file mode 120000 index 0000000000..03cc006601 --- /dev/null +++ b/Lang/Gambas/The-Name-Game @@ -0,0 +1 @@ +../../Task/The-Name-Game/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Twos-complement b/Lang/Gambas/Twos-complement new file mode 120000 index 0000000000..4ed9e66d7c --- /dev/null +++ b/Lang/Gambas/Twos-complement @@ -0,0 +1 @@ +../../Task/Twos-complement/Gambas \ No newline at end of file diff --git a/Lang/Gleam/00-LANG.txt b/Lang/Gleam/00-LANG.txt index 1105755c96..6a2642caa9 100644 --- a/Lang/Gleam/00-LANG.txt +++ b/Lang/Gleam/00-LANG.txt @@ -1,2 +1,5 @@ {{stub}}{{language|Gleam|hopl=no|site=https://gleam.run/}} -Gleam is a type-safe functional programming language that runs on the [[Erlang]] virtual machine. \ No newline at end of file +Gleam is a type-safe functional programming language that runs on the [[Erlang]] virtual machine. + +== Todo == +[https://rosettacode.org/wiki/Tasks_not_implemented_in_Gleam Tasks not implemented in Gleam] \ No newline at end of file diff --git a/Lang/Gleam/Abstract-type b/Lang/Gleam/Abstract-type new file mode 120000 index 0000000000..e0dafb7309 --- /dev/null +++ b/Lang/Gleam/Abstract-type @@ -0,0 +1 @@ +../../Task/Abstract-type/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Ackermann-function b/Lang/Gleam/Ackermann-function new file mode 120000 index 0000000000..6d193a9b28 --- /dev/null +++ b/Lang/Gleam/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Apply-a-callback-to-an-array b/Lang/Gleam/Apply-a-callback-to-an-array new file mode 120000 index 0000000000..45d13702b0 --- /dev/null +++ b/Lang/Gleam/Apply-a-callback-to-an-array @@ -0,0 +1 @@ +../../Task/Apply-a-callback-to-an-array/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Arithmetic-Integer b/Lang/Gleam/Arithmetic-Integer new file mode 120000 index 0000000000..cf77808968 --- /dev/null +++ b/Lang/Gleam/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Array-concatenation b/Lang/Gleam/Array-concatenation new file mode 120000 index 0000000000..a1a9260979 --- /dev/null +++ b/Lang/Gleam/Array-concatenation @@ -0,0 +1 @@ +../../Task/Array-concatenation/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Array-length b/Lang/Gleam/Array-length new file mode 120000 index 0000000000..ab180dc3f2 --- /dev/null +++ b/Lang/Gleam/Array-length @@ -0,0 +1 @@ +../../Task/Array-length/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Assertions b/Lang/Gleam/Assertions new file mode 120000 index 0000000000..aca06893a5 --- /dev/null +++ b/Lang/Gleam/Assertions @@ -0,0 +1 @@ +../../Task/Assertions/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Associative-array-Creation b/Lang/Gleam/Associative-array-Creation new file mode 120000 index 0000000000..954ca71884 --- /dev/null +++ b/Lang/Gleam/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Binary-digits b/Lang/Gleam/Binary-digits new file mode 120000 index 0000000000..a13df512cd --- /dev/null +++ b/Lang/Gleam/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Catamorphism b/Lang/Gleam/Catamorphism new file mode 120000 index 0000000000..a390f8e444 --- /dev/null +++ b/Lang/Gleam/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Comments b/Lang/Gleam/Comments new file mode 120000 index 0000000000..e7d9705951 --- /dev/null +++ b/Lang/Gleam/Comments @@ -0,0 +1 @@ +../../Task/Comments/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Compare-a-list-of-strings b/Lang/Gleam/Compare-a-list-of-strings new file mode 120000 index 0000000000..1669281682 --- /dev/null +++ b/Lang/Gleam/Compare-a-list-of-strings @@ -0,0 +1 @@ +../../Task/Compare-a-list-of-strings/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Compound-data-type b/Lang/Gleam/Compound-data-type new file mode 120000 index 0000000000..7cff564dfe --- /dev/null +++ b/Lang/Gleam/Compound-data-type @@ -0,0 +1 @@ +../../Task/Compound-data-type/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Conditional-structures b/Lang/Gleam/Conditional-structures new file mode 120000 index 0000000000..c889229abf --- /dev/null +++ b/Lang/Gleam/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Copy-a-string b/Lang/Gleam/Copy-a-string new file mode 120000 index 0000000000..8cf2c44a17 --- /dev/null +++ b/Lang/Gleam/Copy-a-string @@ -0,0 +1 @@ +../../Task/Copy-a-string/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Count-in-octal b/Lang/Gleam/Count-in-octal new file mode 120000 index 0000000000..15c2c2e9c2 --- /dev/null +++ b/Lang/Gleam/Count-in-octal @@ -0,0 +1 @@ +../../Task/Count-in-octal/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Date-format b/Lang/Gleam/Date-format new file mode 120000 index 0000000000..328512d62f --- /dev/null +++ b/Lang/Gleam/Date-format @@ -0,0 +1 @@ +../../Task/Date-format/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Delete-a-file b/Lang/Gleam/Delete-a-file new file mode 120000 index 0000000000..85116e4edd --- /dev/null +++ b/Lang/Gleam/Delete-a-file @@ -0,0 +1 @@ +../../Task/Delete-a-file/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Detect-division-by-zero b/Lang/Gleam/Detect-division-by-zero new file mode 120000 index 0000000000..9eea7618bf --- /dev/null +++ b/Lang/Gleam/Detect-division-by-zero @@ -0,0 +1 @@ +../../Task/Detect-division-by-zero/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Determine-if-a-string-is-numeric b/Lang/Gleam/Determine-if-a-string-is-numeric new file mode 120000 index 0000000000..a9d9a1d6a1 --- /dev/null +++ b/Lang/Gleam/Determine-if-a-string-is-numeric @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-numeric/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Dice-game-probabilities b/Lang/Gleam/Dice-game-probabilities new file mode 120000 index 0000000000..1cf64df0ec --- /dev/null +++ b/Lang/Gleam/Dice-game-probabilities @@ -0,0 +1 @@ +../../Task/Dice-game-probabilities/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Digital-root b/Lang/Gleam/Digital-root new file mode 120000 index 0000000000..f4b00d8cfb --- /dev/null +++ b/Lang/Gleam/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Dot-product b/Lang/Gleam/Dot-product new file mode 120000 index 0000000000..cf4ac49af6 --- /dev/null +++ b/Lang/Gleam/Dot-product @@ -0,0 +1 @@ +../../Task/Dot-product/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Empty-directory b/Lang/Gleam/Empty-directory new file mode 120000 index 0000000000..1ce790d8fd --- /dev/null +++ b/Lang/Gleam/Empty-directory @@ -0,0 +1 @@ +../../Task/Empty-directory/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Empty-string b/Lang/Gleam/Empty-string new file mode 120000 index 0000000000..5b7f7b9014 --- /dev/null +++ b/Lang/Gleam/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Ethiopian-multiplication b/Lang/Gleam/Ethiopian-multiplication new file mode 120000 index 0000000000..f93edec2ee --- /dev/null +++ b/Lang/Gleam/Ethiopian-multiplication @@ -0,0 +1 @@ +../../Task/Ethiopian-multiplication/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Even-or-odd b/Lang/Gleam/Even-or-odd new file mode 120000 index 0000000000..e725b0e8c1 --- /dev/null +++ b/Lang/Gleam/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Factorial b/Lang/Gleam/Factorial new file mode 120000 index 0000000000..a5b5b846f8 --- /dev/null +++ b/Lang/Gleam/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Fibonacci-sequence b/Lang/Gleam/Fibonacci-sequence new file mode 120000 index 0000000000..1d18c4a46d --- /dev/null +++ b/Lang/Gleam/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Filter b/Lang/Gleam/Filter new file mode 120000 index 0000000000..556438c396 --- /dev/null +++ b/Lang/Gleam/Filter @@ -0,0 +1 @@ +../../Task/Filter/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Function-definition b/Lang/Gleam/Function-definition new file mode 120000 index 0000000000..ba4dddd180 --- /dev/null +++ b/Lang/Gleam/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Generic-swap b/Lang/Gleam/Generic-swap new file mode 120000 index 0000000000..21212ee1ef --- /dev/null +++ b/Lang/Gleam/Generic-swap @@ -0,0 +1 @@ +../../Task/Generic-swap/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Greatest-common-divisor b/Lang/Gleam/Greatest-common-divisor new file mode 120000 index 0000000000..9040d6ace0 --- /dev/null +++ b/Lang/Gleam/Greatest-common-divisor @@ -0,0 +1 @@ +../../Task/Greatest-common-divisor/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Greatest-element-of-a-list b/Lang/Gleam/Greatest-element-of-a-list new file mode 120000 index 0000000000..0479d1d5ea --- /dev/null +++ b/Lang/Gleam/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Increment-a-numerical-string b/Lang/Gleam/Increment-a-numerical-string new file mode 120000 index 0000000000..7bddbff85b --- /dev/null +++ b/Lang/Gleam/Increment-a-numerical-string @@ -0,0 +1 @@ +../../Task/Increment-a-numerical-string/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Integer-sequence b/Lang/Gleam/Integer-sequence new file mode 120000 index 0000000000..d2b7a0c5c2 --- /dev/null +++ b/Lang/Gleam/Integer-sequence @@ -0,0 +1 @@ +../../Task/Integer-sequence/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Jewels-and-stones b/Lang/Gleam/Jewels-and-stones new file mode 120000 index 0000000000..2eb704c9d0 --- /dev/null +++ b/Lang/Gleam/Jewels-and-stones @@ -0,0 +1 @@ +../../Task/Jewels-and-stones/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Kernighans-large-earthquake-problem b/Lang/Gleam/Kernighans-large-earthquake-problem new file mode 120000 index 0000000000..06b9c08a6c --- /dev/null +++ b/Lang/Gleam/Kernighans-large-earthquake-problem @@ -0,0 +1 @@ +../../Task/Kernighans-large-earthquake-problem/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Look-and-say-sequence b/Lang/Gleam/Look-and-say-sequence new file mode 120000 index 0000000000..dafdaa21e3 --- /dev/null +++ b/Lang/Gleam/Look-and-say-sequence @@ -0,0 +1 @@ +../../Task/Look-and-say-sequence/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Luhn-test-of-credit-card-numbers b/Lang/Gleam/Luhn-test-of-credit-card-numbers new file mode 120000 index 0000000000..784acc9d8d --- /dev/null +++ b/Lang/Gleam/Luhn-test-of-credit-card-numbers @@ -0,0 +1 @@ +../../Task/Luhn-test-of-credit-card-numbers/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Multiplication-tables b/Lang/Gleam/Multiplication-tables new file mode 120000 index 0000000000..4745c27425 --- /dev/null +++ b/Lang/Gleam/Multiplication-tables @@ -0,0 +1 @@ +../../Task/Multiplication-tables/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Nth b/Lang/Gleam/Nth new file mode 120000 index 0000000000..9607d54630 --- /dev/null +++ b/Lang/Gleam/Nth @@ -0,0 +1 @@ +../../Task/Nth/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Order-by-pair-comparisons b/Lang/Gleam/Order-by-pair-comparisons new file mode 120000 index 0000000000..fc683495ba --- /dev/null +++ b/Lang/Gleam/Order-by-pair-comparisons @@ -0,0 +1 @@ +../../Task/Order-by-pair-comparisons/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Primality-by-Wilsons-theorem b/Lang/Gleam/Primality-by-Wilsons-theorem new file mode 120000 index 0000000000..96d456e3fb --- /dev/null +++ b/Lang/Gleam/Primality-by-Wilsons-theorem @@ -0,0 +1 @@ +../../Task/Primality-by-Wilsons-theorem/Gleam \ No newline at end of file diff --git a/Lang/Gleam/RPG-attributes-generator b/Lang/Gleam/RPG-attributes-generator new file mode 120000 index 0000000000..800e60ff4c --- /dev/null +++ b/Lang/Gleam/RPG-attributes-generator @@ -0,0 +1 @@ +../../Task/RPG-attributes-generator/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Repeat b/Lang/Gleam/Repeat new file mode 120000 index 0000000000..fab6759fe5 --- /dev/null +++ b/Lang/Gleam/Repeat @@ -0,0 +1 @@ +../../Task/Repeat/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Repeat-a-string b/Lang/Gleam/Repeat-a-string new file mode 120000 index 0000000000..587cd9830b --- /dev/null +++ b/Lang/Gleam/Repeat-a-string @@ -0,0 +1 @@ +../../Task/Repeat-a-string/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Set b/Lang/Gleam/Set new file mode 120000 index 0000000000..c138abd777 --- /dev/null +++ b/Lang/Gleam/Set @@ -0,0 +1 @@ +../../Task/Set/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Sort-an-integer-array b/Lang/Gleam/Sort-an-integer-array new file mode 120000 index 0000000000..39c8723c40 --- /dev/null +++ b/Lang/Gleam/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Sorting-algorithms-Quicksort b/Lang/Gleam/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..f1e07b6052 --- /dev/null +++ b/Lang/Gleam/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Stack b/Lang/Gleam/Stack new file mode 120000 index 0000000000..174c4b56e2 --- /dev/null +++ b/Lang/Gleam/Stack @@ -0,0 +1 @@ +../../Task/Stack/Gleam \ No newline at end of file diff --git a/Lang/Gleam/String-append b/Lang/Gleam/String-append new file mode 120000 index 0000000000..8450c82d83 --- /dev/null +++ b/Lang/Gleam/String-append @@ -0,0 +1 @@ +../../Task/String-append/Gleam \ No newline at end of file diff --git a/Lang/Gleam/String-length b/Lang/Gleam/String-length new file mode 120000 index 0000000000..f57922e1a7 --- /dev/null +++ b/Lang/Gleam/String-length @@ -0,0 +1 @@ +../../Task/String-length/Gleam \ No newline at end of file diff --git a/Lang/Gleam/String-prepend b/Lang/Gleam/String-prepend new file mode 120000 index 0000000000..a7f4b33fae --- /dev/null +++ b/Lang/Gleam/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Sum-and-product-of-an-array b/Lang/Gleam/Sum-and-product-of-an-array new file mode 120000 index 0000000000..15ce85c799 --- /dev/null +++ b/Lang/Gleam/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Sum-digits-of-an-integer b/Lang/Gleam/Sum-digits-of-an-integer new file mode 120000 index 0000000000..cfe6f1a5d3 --- /dev/null +++ b/Lang/Gleam/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Sum-multiples-of-3-and-5 b/Lang/Gleam/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..3e5a3657a3 --- /dev/null +++ b/Lang/Gleam/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Sum-of-squares b/Lang/Gleam/Sum-of-squares new file mode 120000 index 0000000000..34f0e02665 --- /dev/null +++ b/Lang/Gleam/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Symmetric-difference b/Lang/Gleam/Symmetric-difference new file mode 120000 index 0000000000..51ff7c4a32 --- /dev/null +++ b/Lang/Gleam/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Temperature-conversion b/Lang/Gleam/Temperature-conversion new file mode 120000 index 0000000000..2d1d9f16a7 --- /dev/null +++ b/Lang/Gleam/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Tree-traversal b/Lang/Gleam/Tree-traversal new file mode 120000 index 0000000000..b8d43d9b74 --- /dev/null +++ b/Lang/Gleam/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Variables b/Lang/Gleam/Variables new file mode 120000 index 0000000000..b43723c7ff --- /dev/null +++ b/Lang/Gleam/Variables @@ -0,0 +1 @@ +../../Task/Variables/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Vector-products b/Lang/Gleam/Vector-products new file mode 120000 index 0000000000..e08e49670f --- /dev/null +++ b/Lang/Gleam/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/Gleam \ No newline at end of file diff --git a/Lang/Gleam/Water-collected-between-towers b/Lang/Gleam/Water-collected-between-towers new file mode 120000 index 0000000000..787299f258 --- /dev/null +++ b/Lang/Gleam/Water-collected-between-towers @@ -0,0 +1 @@ +../../Task/Water-collected-between-towers/Gleam \ No newline at end of file diff --git a/Lang/Go/Bifid-cipher b/Lang/Go/Bifid-cipher new file mode 120000 index 0000000000..329ffb397d --- /dev/null +++ b/Lang/Go/Bifid-cipher @@ -0,0 +1 @@ +../../Task/Bifid-cipher/Go \ No newline at end of file diff --git a/Lang/Go/Bioinformatics-base-count b/Lang/Go/Bioinformatics-base-count deleted file mode 120000 index 485b68c3c6..0000000000 --- a/Lang/Go/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Go \ No newline at end of file diff --git a/Lang/Go/Boyer-Moore-string-search b/Lang/Go/Boyer-Moore-string-search new file mode 120000 index 0000000000..0b971fdf3b --- /dev/null +++ b/Lang/Go/Boyer-Moore-string-search @@ -0,0 +1 @@ +../../Task/Boyer-Moore-string-search/Go \ No newline at end of file diff --git a/Lang/Go/Camel-case-and-snake-case b/Lang/Go/Camel-case-and-snake-case new file mode 120000 index 0000000000..580007cb79 --- /dev/null +++ b/Lang/Go/Camel-case-and-snake-case @@ -0,0 +1 @@ +../../Task/Camel-case-and-snake-case/Go \ No newline at end of file diff --git a/Lang/Go/Distance-and-Bearing b/Lang/Go/Distance-and-Bearing new file mode 120000 index 0000000000..566b8d5b53 --- /dev/null +++ b/Lang/Go/Distance-and-Bearing @@ -0,0 +1 @@ +../../Task/Distance-and-Bearing/Go \ No newline at end of file diff --git a/Lang/Go/Factorial-primes b/Lang/Go/Factorial-primes new file mode 120000 index 0000000000..5b25426fd0 --- /dev/null +++ b/Lang/Go/Factorial-primes @@ -0,0 +1 @@ +../../Task/Factorial-primes/Go \ No newline at end of file diff --git a/Lang/Go/Goldbachs-comet b/Lang/Go/Goldbachs-comet new file mode 120000 index 0000000000..e80a90c082 --- /dev/null +++ b/Lang/Go/Goldbachs-comet @@ -0,0 +1 @@ +../../Task/Goldbachs-comet/Go \ No newline at end of file diff --git a/Lang/Go/Meissel-Mertens-constant b/Lang/Go/Meissel-Mertens-constant deleted file mode 120000 index 8c13ff2d6b..0000000000 --- a/Lang/Go/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/Go \ No newline at end of file diff --git a/Lang/Go/Miller-Rabin-primality-test b/Lang/Go/Miller-Rabin-primality-test deleted file mode 120000 index c9da74462b..0000000000 --- a/Lang/Go/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Go \ No newline at end of file diff --git a/Lang/Go/P-Adic-square-roots b/Lang/Go/P-Adic-square-roots new file mode 120000 index 0000000000..064157bec0 --- /dev/null +++ b/Lang/Go/P-Adic-square-roots @@ -0,0 +1 @@ +../../Task/P-Adic-square-roots/Go \ No newline at end of file diff --git a/Lang/Go/Quaternion-type b/Lang/Go/Quaternion-type deleted file mode 120000 index e62c595975..0000000000 --- a/Lang/Go/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Go \ No newline at end of file diff --git a/Lang/Go/Simple-turtle-graphics b/Lang/Go/Simple-turtle-graphics new file mode 120000 index 0000000000..81f4233716 --- /dev/null +++ b/Lang/Go/Simple-turtle-graphics @@ -0,0 +1 @@ +../../Task/Simple-turtle-graphics/Go \ No newline at end of file diff --git a/Lang/Go/Sorting-Algorithms-Circle-Sort b/Lang/Go/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 1288f4ddcf..0000000000 --- a/Lang/Go/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Go \ No newline at end of file diff --git a/Lang/Go/Terminal-control-Unicode-output b/Lang/Go/Terminal-control-Unicode-output deleted file mode 120000 index 7532989408..0000000000 --- a/Lang/Go/Terminal-control-Unicode-output +++ /dev/null @@ -1 +0,0 @@ -../../Task/Terminal-control-Unicode-output/Go \ No newline at end of file diff --git a/Lang/Goboscript/00-LANG.txt b/Lang/Goboscript/00-LANG.txt new file mode 100644 index 0000000000..fbf55e819e --- /dev/null +++ b/Lang/Goboscript/00-LANG.txt @@ -0,0 +1,15 @@ +{{stub}}{{language +|tags=compiled, transpiled, Scratch +| site=https://aspizu.github.io/goboscript/ +|parampass=value +|goboscript}} + +From [https://github.com/aspizu/goboscript/ the goboscript repo]:
+ +goboscript is a text-based programming language that compiles to Scratch. Write Scratch projects in text, and compile it into a .sb3 file -- which can be opened in the Scratch editor, TurboWarp or be uploaded to the Scratch website. + +===Package managers=== +Despite being a relatively new programming language, goboscript has multiple package managers. + +* [https://github.com/aspizu/backpack backpack] - The official goboscript package manager +* [https://github.com/inflated-goboscript/inflator inflator] - A more powerful package manager inspired by Python's pip \ No newline at end of file diff --git a/Lang/Goboscript/00-META.yaml b/Lang/Goboscript/00-META.yaml new file mode 100644 index 0000000000..48464a36ad --- /dev/null +++ b/Lang/Goboscript/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Goboscript diff --git a/Lang/Goboscript/100-doors b/Lang/Goboscript/100-doors new file mode 120000 index 0000000000..293aa8a0f0 --- /dev/null +++ b/Lang/Goboscript/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/Goboscript \ No newline at end of file diff --git a/Lang/Goboscript/99-bottles-of-beer b/Lang/Goboscript/99-bottles-of-beer new file mode 120000 index 0000000000..5a60ef7f8c --- /dev/null +++ b/Lang/Goboscript/99-bottles-of-beer @@ -0,0 +1 @@ +../../Task/99-bottles-of-beer/Goboscript \ No newline at end of file diff --git a/Lang/Goboscript/Arithmetic-Complex b/Lang/Goboscript/Arithmetic-Complex new file mode 120000 index 0000000000..ed35177c3c --- /dev/null +++ b/Lang/Goboscript/Arithmetic-Complex @@ -0,0 +1 @@ +../../Task/Arithmetic-Complex/Goboscript \ No newline at end of file diff --git a/Lang/Golfscript/00-LANG.txt b/Lang/Golfscript/00-LANG.txt index 67be1df4fd..ce1ed4276d 100644 --- a/Lang/Golfscript/00-LANG.txt +++ b/Lang/Golfscript/00-LANG.txt @@ -1,5 +1,10 @@ {{language|GolfScript |site=http://www.golfscript.com/golfscript/index.html }} +{{try|Golfscript|[https://tio.run/#golfscript Try Golfscript on tio.run].}} {{language programming paradigm|Concatenative}} -GolfScript is a stack oriented esoteric programming language aimed at solving problems (holes) in as few keystrokes as possible. It also aims to be simple and easy to write. \ No newline at end of file +GolfScript is a stack oriented esoteric programming language aimed at solving problems (holes) in as few keystrokes as possible. It also aims to be simple and easy to write. + +== External links == +* [https://golfscript.com/golfscript/ Official website] +* [https://codegolf.stackexchange.com/questions/5264/tips-for-golfing-in-golfscript Tips for golfing in Golfscript] \ No newline at end of file diff --git a/Lang/Golfscript/Primality-by-trial-division b/Lang/Golfscript/Primality-by-trial-division new file mode 120000 index 0000000000..42e31431cb --- /dev/null +++ b/Lang/Golfscript/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/Golfscript \ No newline at end of file diff --git a/Lang/Groovy/Empty-program b/Lang/Groovy/Empty-program deleted file mode 120000 index 8d1c7a42ae..0000000000 --- a/Lang/Groovy/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Groovy \ No newline at end of file diff --git a/Lang/Guile/2048 b/Lang/Guile/2048 new file mode 120000 index 0000000000..69532585e1 --- /dev/null +++ b/Lang/Guile/2048 @@ -0,0 +1 @@ +../../Task/2048/Guile \ No newline at end of file diff --git a/Lang/Guile/A+B b/Lang/Guile/A+B new file mode 120000 index 0000000000..ea7ff34909 --- /dev/null +++ b/Lang/Guile/A+B @@ -0,0 +1 @@ +../../Task/A+B/Guile \ No newline at end of file diff --git a/Lang/Guile/MD5-Implementation b/Lang/Guile/MD5-Implementation new file mode 120000 index 0000000000..c467572ebf --- /dev/null +++ b/Lang/Guile/MD5-Implementation @@ -0,0 +1 @@ +../../Task/MD5-Implementation/Guile \ No newline at end of file diff --git a/Lang/Guish/00-LANG.txt b/Lang/Guish/00-LANG.txt index 593da31c91..e15298f7c3 100644 --- a/Lang/Guish/00-LANG.txt +++ b/Lang/Guish/00-LANG.txt @@ -1016,7 +1016,7 @@ Any element that's not a page has a particular text alignment that can be change -Francesco Palumbo <phranz@subfc.net> +Francesco Palumbo = THANKS = diff --git a/Lang/HPPPL/A+B b/Lang/HPPPL/A+B new file mode 120000 index 0000000000..dd8d8fff42 --- /dev/null +++ b/Lang/HPPPL/A+B @@ -0,0 +1 @@ +../../Task/A+B/HPPPL \ No newline at end of file diff --git a/Lang/HPPPL/Ackermann-function b/Lang/HPPPL/Ackermann-function new file mode 120000 index 0000000000..ff1ef99b52 --- /dev/null +++ b/Lang/HPPPL/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/HPPPL \ No newline at end of file diff --git a/Lang/HPPPL/Babbage-problem b/Lang/HPPPL/Babbage-problem new file mode 120000 index 0000000000..441aa0d4f6 --- /dev/null +++ b/Lang/HPPPL/Babbage-problem @@ -0,0 +1 @@ +../../Task/Babbage-problem/HPPPL \ No newline at end of file diff --git a/Lang/HPPPL/Jacobsthal-numbers b/Lang/HPPPL/Jacobsthal-numbers new file mode 120000 index 0000000000..5f5706ea3b --- /dev/null +++ b/Lang/HPPPL/Jacobsthal-numbers @@ -0,0 +1 @@ +../../Task/Jacobsthal-numbers/HPPPL \ No newline at end of file diff --git a/Lang/HPPPL/Jaro-similarity b/Lang/HPPPL/Jaro-similarity new file mode 120000 index 0000000000..022c80a0a8 --- /dev/null +++ b/Lang/HPPPL/Jaro-similarity @@ -0,0 +1 @@ +../../Task/Jaro-similarity/HPPPL \ No newline at end of file diff --git a/Lang/HPPPL/Numbers-with-equal-rises-and-falls b/Lang/HPPPL/Numbers-with-equal-rises-and-falls new file mode 120000 index 0000000000..7d6ca5c6b5 --- /dev/null +++ b/Lang/HPPPL/Numbers-with-equal-rises-and-falls @@ -0,0 +1 @@ +../../Task/Numbers-with-equal-rises-and-falls/HPPPL \ No newline at end of file diff --git a/Lang/HPPPL/Primality-by-trial-division b/Lang/HPPPL/Primality-by-trial-division new file mode 120000 index 0000000000..2127fa3655 --- /dev/null +++ b/Lang/HPPPL/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/HPPPL \ No newline at end of file diff --git a/Lang/HPPPL/Tau-number b/Lang/HPPPL/Tau-number new file mode 120000 index 0000000000..1180967c35 --- /dev/null +++ b/Lang/HPPPL/Tau-number @@ -0,0 +1 @@ +../../Task/Tau-number/HPPPL \ No newline at end of file diff --git a/Lang/Hare/Execute-Brain- b/Lang/Hare/Execute-Brain- new file mode 120000 index 0000000000..dc8caabad0 --- /dev/null +++ b/Lang/Hare/Execute-Brain- @@ -0,0 +1 @@ +../../Task/Execute-Brain-/Hare \ No newline at end of file diff --git a/Lang/Haskell/00-LANG.txt b/Lang/Haskell/00-LANG.txt index fe49ebce44..9b79cdd879 100644 --- a/Lang/Haskell/00-LANG.txt +++ b/Lang/Haskell/00-LANG.txt @@ -20,5 +20,5 @@ Linspire GNU/[[Linux]] chose Haskell for system tools development. ==Citations== * [[wp:Haskell_%28programming_language%29|Wikipedia:Haskell (programming language)]] -==Todo== -[[Reports:Tasks_not_implemented_in_Haskell]] \ No newline at end of file +==Unimplemented Tasks== +* [[Tasks_not_implemented_in_Haskell|Haskell Unimplemented]] \ No newline at end of file diff --git a/Lang/Haskell/Arithmetic-numbers b/Lang/Haskell/Arithmetic-numbers new file mode 120000 index 0000000000..ca4dc61dcb --- /dev/null +++ b/Lang/Haskell/Arithmetic-numbers @@ -0,0 +1 @@ +../../Task/Arithmetic-numbers/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Ascending-primes b/Lang/Haskell/Ascending-primes new file mode 120000 index 0000000000..443d61be19 --- /dev/null +++ b/Lang/Haskell/Ascending-primes @@ -0,0 +1 @@ +../../Task/Ascending-primes/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Bifid-cipher b/Lang/Haskell/Bifid-cipher new file mode 120000 index 0000000000..e9402d0afc --- /dev/null +++ b/Lang/Haskell/Bifid-cipher @@ -0,0 +1 @@ +../../Task/Bifid-cipher/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Bioinformatics-Global-alignment b/Lang/Haskell/Bioinformatics-Global-alignment new file mode 120000 index 0000000000..adcd5f4ce2 --- /dev/null +++ b/Lang/Haskell/Bioinformatics-Global-alignment @@ -0,0 +1 @@ +../../Task/Bioinformatics-Global-alignment/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Bioinformatics-base-count b/Lang/Haskell/Bioinformatics-base-count deleted file mode 120000 index cf913dcdcd..0000000000 --- a/Lang/Haskell/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Cistercian-numerals b/Lang/Haskell/Cistercian-numerals new file mode 120000 index 0000000000..2a13541c88 --- /dev/null +++ b/Lang/Haskell/Cistercian-numerals @@ -0,0 +1 @@ +../../Task/Cistercian-numerals/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Deceptive-numbers b/Lang/Haskell/Deceptive-numbers new file mode 120000 index 0000000000..6fa6eb6011 --- /dev/null +++ b/Lang/Haskell/Deceptive-numbers @@ -0,0 +1 @@ +../../Task/Deceptive-numbers/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Descending-primes b/Lang/Haskell/Descending-primes new file mode 120000 index 0000000000..58817d1239 --- /dev/null +++ b/Lang/Haskell/Descending-primes @@ -0,0 +1 @@ +../../Task/Descending-primes/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Duffinian-numbers b/Lang/Haskell/Duffinian-numbers new file mode 120000 index 0000000000..282d30bb6b --- /dev/null +++ b/Lang/Haskell/Duffinian-numbers @@ -0,0 +1 @@ +../../Task/Duffinian-numbers/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Factorial-primes b/Lang/Haskell/Factorial-primes new file mode 120000 index 0000000000..004f7e5f7d --- /dev/null +++ b/Lang/Haskell/Factorial-primes @@ -0,0 +1 @@ +../../Task/Factorial-primes/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Jordan-P-lya-numbers b/Lang/Haskell/Jordan-P-lya-numbers new file mode 120000 index 0000000000..0e7225789a --- /dev/null +++ b/Lang/Haskell/Jordan-P-lya-numbers @@ -0,0 +1 @@ +../../Task/Jordan-P-lya-numbers/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Miller-Rabin-primality-test b/Lang/Haskell/Miller-Rabin-primality-test deleted file mode 120000 index c41f1ba06c..0000000000 --- a/Lang/Haskell/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Mouse-position b/Lang/Haskell/Mouse-position new file mode 120000 index 0000000000..842d59376f --- /dev/null +++ b/Lang/Haskell/Mouse-position @@ -0,0 +1 @@ +../../Task/Mouse-position/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Pathological-floating-point-problems b/Lang/Haskell/Pathological-floating-point-problems new file mode 120000 index 0000000000..f17bacf62a --- /dev/null +++ b/Lang/Haskell/Pathological-floating-point-problems @@ -0,0 +1 @@ +../../Task/Pathological-floating-point-problems/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Quaternion-type b/Lang/Haskell/Quaternion-type deleted file mode 120000 index 14aca84bfa..0000000000 --- a/Lang/Haskell/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Sorting-Algorithms-Circle-Sort b/Lang/Haskell/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 7f6f1559db..0000000000 --- a/Lang/Haskell/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Strassens-algorithm b/Lang/Haskell/Strassens-algorithm new file mode 120000 index 0000000000..f39dbbfd50 --- /dev/null +++ b/Lang/Haskell/Strassens-algorithm @@ -0,0 +1 @@ +../../Task/Strassens-algorithm/Haskell \ No newline at end of file diff --git a/Lang/Haxe/Abstract-type b/Lang/Haxe/Abstract-type new file mode 120000 index 0000000000..6ff9aba1f6 --- /dev/null +++ b/Lang/Haxe/Abstract-type @@ -0,0 +1 @@ +../../Task/Abstract-type/Haxe \ No newline at end of file diff --git a/Lang/Haxe/Apply-a-callback-to-an-array b/Lang/Haxe/Apply-a-callback-to-an-array new file mode 120000 index 0000000000..6fdb21da75 --- /dev/null +++ b/Lang/Haxe/Apply-a-callback-to-an-array @@ -0,0 +1 @@ +../../Task/Apply-a-callback-to-an-array/Haxe \ No newline at end of file diff --git a/Lang/Haxe/Arrays b/Lang/Haxe/Arrays new file mode 120000 index 0000000000..bd303e4884 --- /dev/null +++ b/Lang/Haxe/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/Haxe \ No newline at end of file diff --git a/Lang/Haxe/Associative-array-Creation b/Lang/Haxe/Associative-array-Creation new file mode 120000 index 0000000000..38347f6de6 --- /dev/null +++ b/Lang/Haxe/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/Haxe \ No newline at end of file diff --git a/Lang/Haxe/Associative-array-Iteration b/Lang/Haxe/Associative-array-Iteration new file mode 120000 index 0000000000..aa7c7951b8 --- /dev/null +++ b/Lang/Haxe/Associative-array-Iteration @@ -0,0 +1 @@ +../../Task/Associative-array-Iteration/Haxe \ No newline at end of file diff --git a/Lang/Haxe/Binary-digits b/Lang/Haxe/Binary-digits new file mode 120000 index 0000000000..9bf8952c0d --- /dev/null +++ b/Lang/Haxe/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/Haxe \ No newline at end of file diff --git a/Lang/Haxe/Boolean-values b/Lang/Haxe/Boolean-values new file mode 120000 index 0000000000..b5ef0e7d8b --- /dev/null +++ b/Lang/Haxe/Boolean-values @@ -0,0 +1 @@ +../../Task/Boolean-values/Haxe \ No newline at end of file diff --git a/Lang/Haxe/Call-an-object-method b/Lang/Haxe/Call-an-object-method new file mode 120000 index 0000000000..953d02b76c --- /dev/null +++ b/Lang/Haxe/Call-an-object-method @@ -0,0 +1 @@ +../../Task/Call-an-object-method/Haxe \ No newline at end of file diff --git a/Lang/Haxe/Character-codes b/Lang/Haxe/Character-codes new file mode 120000 index 0000000000..92ab060a1a --- /dev/null +++ b/Lang/Haxe/Character-codes @@ -0,0 +1 @@ +../../Task/Character-codes/Haxe \ No newline at end of file diff --git a/Lang/Haxe/Classes b/Lang/Haxe/Classes new file mode 120000 index 0000000000..5c922938d4 --- /dev/null +++ b/Lang/Haxe/Classes @@ -0,0 +1 @@ +../../Task/Classes/Haxe \ No newline at end of file diff --git a/Lang/IDL/00-LANG.txt b/Lang/IDL/00-LANG.txt index ef4aad38d6..fed6398ad2 100644 --- a/Lang/IDL/00-LANG.txt +++ b/Lang/IDL/00-LANG.txt @@ -1,4 +1,4 @@ {{stub}}{{language|IDL}} IDL (Interactive Data Language) is an [[array]] programming language designed by David Stern. [[wp:IDL_%28programming_language%29|Wikipedia article]] -(free implementation: GDL - GNU Data Language http://gnudatalanguage.sourceforge.net) \ No newline at end of file +(free implementation: GDL - GNU Data Language https://github.com/gnudatalanguage/gdl) \ No newline at end of file diff --git a/Lang/IS-BASIC/Determine-if-a-string-has-all-the-same-characters b/Lang/IS-BASIC/Determine-if-a-string-has-all-the-same-characters new file mode 120000 index 0000000000..3a0ac72c5c --- /dev/null +++ b/Lang/IS-BASIC/Determine-if-a-string-has-all-the-same-characters @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-has-all-the-same-characters/IS-BASIC \ No newline at end of file diff --git a/Lang/Icon/00-LANG.txt b/Lang/Icon/00-LANG.txt index 6d6b15bfc2..16054a3927 100644 --- a/Lang/Icon/00-LANG.txt +++ b/Lang/Icon/00-LANG.txt @@ -39,5 +39,7 @@ Several extensions of Icon were developed to improve functionality. Many of the * [[Icon%2BUnicon/Intro|An introduction to Icon and Unicon for Rosetta Code]] * [[:Category:Icon/Omit|Unimplementable tasks]] * [[:Category:Icon_examples_needing_attention|Tasks requiring attention]] -* [[Reports:Tasks_not_implemented_in_Icon|Tasks not yet implemented]] -* [[:Category:Icon_Programming_Library|The Icon Programming Library]] \ No newline at end of file +* [[:Category:Icon_Programming_Library|The Icon Programming Library]] + +==Todo== +* [[Tasks not implemented in Icon]] \ No newline at end of file diff --git a/Lang/Icon/100-prisoners b/Lang/Icon/100-prisoners new file mode 120000 index 0000000000..9bc15827ac --- /dev/null +++ b/Lang/Icon/100-prisoners @@ -0,0 +1 @@ +../../Task/100-prisoners/Icon \ No newline at end of file diff --git a/Lang/Icon/Additive-primes b/Lang/Icon/Additive-primes new file mode 120000 index 0000000000..f7253ea73d --- /dev/null +++ b/Lang/Icon/Additive-primes @@ -0,0 +1 @@ +../../Task/Additive-primes/Icon \ No newline at end of file diff --git a/Lang/Icon/Amicable-pairs b/Lang/Icon/Amicable-pairs new file mode 120000 index 0000000000..13242a82ae --- /dev/null +++ b/Lang/Icon/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/Icon \ No newline at end of file diff --git a/Lang/Icon/Anti-primes b/Lang/Icon/Anti-primes new file mode 120000 index 0000000000..63243658da --- /dev/null +++ b/Lang/Icon/Anti-primes @@ -0,0 +1 @@ +../../Task/Anti-primes/Icon \ No newline at end of file diff --git a/Lang/Icon/Ascending-primes b/Lang/Icon/Ascending-primes new file mode 120000 index 0000000000..e30e0fc896 --- /dev/null +++ b/Lang/Icon/Ascending-primes @@ -0,0 +1 @@ +../../Task/Ascending-primes/Icon \ No newline at end of file diff --git a/Lang/Icon/Attractive-numbers b/Lang/Icon/Attractive-numbers new file mode 120000 index 0000000000..743b113011 --- /dev/null +++ b/Lang/Icon/Attractive-numbers @@ -0,0 +1 @@ +../../Task/Attractive-numbers/Icon \ No newline at end of file diff --git a/Lang/Icon/Babbage-problem b/Lang/Icon/Babbage-problem new file mode 120000 index 0000000000..735fcc5c8a --- /dev/null +++ b/Lang/Icon/Babbage-problem @@ -0,0 +1 @@ +../../Task/Babbage-problem/Icon \ No newline at end of file diff --git a/Lang/Icon/Bin-given-limits b/Lang/Icon/Bin-given-limits new file mode 120000 index 0000000000..39a04e7b2e --- /dev/null +++ b/Lang/Icon/Bin-given-limits @@ -0,0 +1 @@ +../../Task/Bin-given-limits/Icon \ No newline at end of file diff --git a/Lang/Icon/Brilliant-numbers b/Lang/Icon/Brilliant-numbers new file mode 120000 index 0000000000..1a8f34ef87 --- /dev/null +++ b/Lang/Icon/Brilliant-numbers @@ -0,0 +1 @@ +../../Task/Brilliant-numbers/Icon \ No newline at end of file diff --git a/Lang/Icon/Colorful-numbers b/Lang/Icon/Colorful-numbers new file mode 120000 index 0000000000..d1f1a0b56b --- /dev/null +++ b/Lang/Icon/Colorful-numbers @@ -0,0 +1 @@ +../../Task/Colorful-numbers/Icon \ No newline at end of file diff --git a/Lang/Icon/Compare-length-of-two-strings b/Lang/Icon/Compare-length-of-two-strings new file mode 120000 index 0000000000..beabf2e98e --- /dev/null +++ b/Lang/Icon/Compare-length-of-two-strings @@ -0,0 +1 @@ +../../Task/Compare-length-of-two-strings/Icon \ No newline at end of file diff --git a/Lang/Icon/Copy-stdin-to-stdout b/Lang/Icon/Copy-stdin-to-stdout new file mode 120000 index 0000000000..7a52714a89 --- /dev/null +++ b/Lang/Icon/Copy-stdin-to-stdout @@ -0,0 +1 @@ +../../Task/Copy-stdin-to-stdout/Icon \ No newline at end of file diff --git a/Lang/Icon/Curzon-numbers b/Lang/Icon/Curzon-numbers new file mode 120000 index 0000000000..4ee931a90d --- /dev/null +++ b/Lang/Icon/Curzon-numbers @@ -0,0 +1 @@ +../../Task/Curzon-numbers/Icon \ No newline at end of file diff --git a/Lang/Icon/Damm-algorithm b/Lang/Icon/Damm-algorithm new file mode 120000 index 0000000000..67c033a005 --- /dev/null +++ b/Lang/Icon/Damm-algorithm @@ -0,0 +1 @@ +../../Task/Damm-algorithm/Icon \ No newline at end of file diff --git a/Lang/Icon/Department-numbers b/Lang/Icon/Department-numbers new file mode 120000 index 0000000000..ce0a0885c3 --- /dev/null +++ b/Lang/Icon/Department-numbers @@ -0,0 +1 @@ +../../Task/Department-numbers/Icon \ No newline at end of file diff --git a/Lang/Icon/Descending-primes b/Lang/Icon/Descending-primes new file mode 120000 index 0000000000..c0f125d9e3 --- /dev/null +++ b/Lang/Icon/Descending-primes @@ -0,0 +1 @@ +../../Task/Descending-primes/Icon \ No newline at end of file diff --git a/Lang/Icon/Determine-if-a-string-is-collapsible b/Lang/Icon/Determine-if-a-string-is-collapsible new file mode 120000 index 0000000000..d589db9f61 --- /dev/null +++ b/Lang/Icon/Determine-if-a-string-is-collapsible @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-collapsible/Icon \ No newline at end of file diff --git a/Lang/Icon/Determine-if-a-string-is-squeezable b/Lang/Icon/Determine-if-a-string-is-squeezable new file mode 120000 index 0000000000..46209569af --- /dev/null +++ b/Lang/Icon/Determine-if-a-string-is-squeezable @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-squeezable/Icon \ No newline at end of file diff --git a/Lang/Icon/Disarium-numbers b/Lang/Icon/Disarium-numbers new file mode 120000 index 0000000000..12c9e05e7d --- /dev/null +++ b/Lang/Icon/Disarium-numbers @@ -0,0 +1 @@ +../../Task/Disarium-numbers/Icon \ No newline at end of file diff --git a/Lang/Icon/Duffinian-numbers b/Lang/Icon/Duffinian-numbers new file mode 120000 index 0000000000..5897c057e3 --- /dev/null +++ b/Lang/Icon/Duffinian-numbers @@ -0,0 +1 @@ +../../Task/Duffinian-numbers/Icon \ No newline at end of file diff --git a/Lang/Icon/Exponentiation-order b/Lang/Icon/Exponentiation-order new file mode 120000 index 0000000000..c87e5174b5 --- /dev/null +++ b/Lang/Icon/Exponentiation-order @@ -0,0 +1 @@ +../../Task/Exponentiation-order/Icon \ No newline at end of file diff --git a/Lang/Icon/Exponentiation-with-infix-operators-in-or-operating-on-the-base b/Lang/Icon/Exponentiation-with-infix-operators-in-or-operating-on-the-base new file mode 120000 index 0000000000..08ed217100 --- /dev/null +++ b/Lang/Icon/Exponentiation-with-infix-operators-in-or-operating-on-the-base @@ -0,0 +1 @@ +../../Task/Exponentiation-with-infix-operators-in-or-operating-on-the-base/Icon \ No newline at end of file diff --git a/Lang/Icon/Gapful-numbers b/Lang/Icon/Gapful-numbers new file mode 120000 index 0000000000..fc3d78f9a2 --- /dev/null +++ b/Lang/Icon/Gapful-numbers @@ -0,0 +1 @@ +../../Task/Gapful-numbers/Icon \ No newline at end of file diff --git a/Lang/Icon/General-FizzBuzz b/Lang/Icon/General-FizzBuzz new file mode 120000 index 0000000000..ea33dc312a --- /dev/null +++ b/Lang/Icon/General-FizzBuzz @@ -0,0 +1 @@ +../../Task/General-FizzBuzz/Icon \ No newline at end of file diff --git a/Lang/Icon/Halt-and-catch-fire b/Lang/Icon/Halt-and-catch-fire new file mode 120000 index 0000000000..cc36db873b --- /dev/null +++ b/Lang/Icon/Halt-and-catch-fire @@ -0,0 +1 @@ +../../Task/Halt-and-catch-fire/Icon \ No newline at end of file diff --git a/Lang/Icon/History-variables b/Lang/Icon/History-variables new file mode 120000 index 0000000000..3757ea49f2 --- /dev/null +++ b/Lang/Icon/History-variables @@ -0,0 +1 @@ +../../Task/History-variables/Icon \ No newline at end of file diff --git a/Lang/Icon/Humble-numbers b/Lang/Icon/Humble-numbers new file mode 120000 index 0000000000..4ff6385336 --- /dev/null +++ b/Lang/Icon/Humble-numbers @@ -0,0 +1 @@ +../../Task/Humble-numbers/Icon \ No newline at end of file diff --git a/Lang/Icon/JSON b/Lang/Icon/JSON new file mode 120000 index 0000000000..cac5544cb8 --- /dev/null +++ b/Lang/Icon/JSON @@ -0,0 +1 @@ +../../Task/JSON/Icon \ No newline at end of file diff --git a/Lang/Icon/Jewels-and-stones b/Lang/Icon/Jewels-and-stones new file mode 120000 index 0000000000..5dee8d7cee --- /dev/null +++ b/Lang/Icon/Jewels-and-stones @@ -0,0 +1 @@ +../../Task/Jewels-and-stones/Icon \ No newline at end of file diff --git a/Lang/Icon/JortSort b/Lang/Icon/JortSort new file mode 120000 index 0000000000..f9d0bbf2dd --- /dev/null +++ b/Lang/Icon/JortSort @@ -0,0 +1 @@ +../../Task/JortSort/Icon \ No newline at end of file diff --git a/Lang/Icon/Kernighans-large-earthquake-problem b/Lang/Icon/Kernighans-large-earthquake-problem new file mode 120000 index 0000000000..c766366430 --- /dev/null +++ b/Lang/Icon/Kernighans-large-earthquake-problem @@ -0,0 +1 @@ +../../Task/Kernighans-large-earthquake-problem/Icon \ No newline at end of file diff --git a/Lang/Icon/Largest-number-divisible-by-its-digits b/Lang/Icon/Largest-number-divisible-by-its-digits new file mode 120000 index 0000000000..13b83b49d7 --- /dev/null +++ b/Lang/Icon/Largest-number-divisible-by-its-digits @@ -0,0 +1 @@ +../../Task/Largest-number-divisible-by-its-digits/Icon \ No newline at end of file diff --git a/Lang/Icon/Largest-proper-divisor-of-n b/Lang/Icon/Largest-proper-divisor-of-n new file mode 120000 index 0000000000..31002a6508 --- /dev/null +++ b/Lang/Icon/Largest-proper-divisor-of-n @@ -0,0 +1 @@ +../../Task/Largest-proper-divisor-of-n/Icon \ No newline at end of file diff --git a/Lang/Icon/Longest-common-substring b/Lang/Icon/Longest-common-substring new file mode 120000 index 0000000000..911a5f7a03 --- /dev/null +++ b/Lang/Icon/Longest-common-substring @@ -0,0 +1 @@ +../../Task/Longest-common-substring/Icon \ No newline at end of file diff --git a/Lang/Icon/Loops-Increment-loop-index-within-loop-body b/Lang/Icon/Loops-Increment-loop-index-within-loop-body new file mode 120000 index 0000000000..19c94ce3da --- /dev/null +++ b/Lang/Icon/Loops-Increment-loop-index-within-loop-body @@ -0,0 +1 @@ +../../Task/Loops-Increment-loop-index-within-loop-body/Icon \ No newline at end of file diff --git a/Lang/Icon/Loops-Wrong-ranges b/Lang/Icon/Loops-Wrong-ranges new file mode 120000 index 0000000000..0317af2079 --- /dev/null +++ b/Lang/Icon/Loops-Wrong-ranges @@ -0,0 +1 @@ +../../Task/Loops-Wrong-ranges/Icon \ No newline at end of file diff --git a/Lang/Icon/Lychrel-numbers b/Lang/Icon/Lychrel-numbers new file mode 120000 index 0000000000..17b9194dd0 --- /dev/null +++ b/Lang/Icon/Lychrel-numbers @@ -0,0 +1 @@ +../../Task/Lychrel-numbers/Icon \ No newline at end of file diff --git a/Lang/Icon/Matrix-exponentiation-operator b/Lang/Icon/Matrix-exponentiation-operator new file mode 120000 index 0000000000..7d0b44e7a5 --- /dev/null +++ b/Lang/Icon/Matrix-exponentiation-operator @@ -0,0 +1 @@ +../../Task/Matrix-exponentiation-operator/Icon \ No newline at end of file diff --git a/Lang/Icon/Mian-Chowla-sequence b/Lang/Icon/Mian-Chowla-sequence new file mode 120000 index 0000000000..c2755bd935 --- /dev/null +++ b/Lang/Icon/Mian-Chowla-sequence @@ -0,0 +1 @@ +../../Task/Mian-Chowla-sequence/Icon \ No newline at end of file diff --git a/Lang/Icon/Miller-Rabin-primality-test b/Lang/Icon/Miller-Rabin-primality-test deleted file mode 120000 index 0a9d526a8b..0000000000 --- a/Lang/Icon/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Icon \ No newline at end of file diff --git a/Lang/Icon/Minimum-multiple-of-m-where-digital-sum-equals-m b/Lang/Icon/Minimum-multiple-of-m-where-digital-sum-equals-m new file mode 120000 index 0000000000..e9ef6d5260 --- /dev/null +++ b/Lang/Icon/Minimum-multiple-of-m-where-digital-sum-equals-m @@ -0,0 +1 @@ +../../Task/Minimum-multiple-of-m-where-digital-sum-equals-m/Icon \ No newline at end of file diff --git a/Lang/Icon/Palindromic-gapful-numbers b/Lang/Icon/Palindromic-gapful-numbers new file mode 120000 index 0000000000..0baaac39e3 --- /dev/null +++ b/Lang/Icon/Palindromic-gapful-numbers @@ -0,0 +1 @@ +../../Task/Palindromic-gapful-numbers/Icon \ No newline at end of file diff --git a/Lang/Icon/Perfect-shuffle b/Lang/Icon/Perfect-shuffle new file mode 120000 index 0000000000..6f3471d6c3 --- /dev/null +++ b/Lang/Icon/Perfect-shuffle @@ -0,0 +1 @@ +../../Task/Perfect-shuffle/Icon \ No newline at end of file diff --git a/Lang/Icon/Repeat b/Lang/Icon/Repeat new file mode 120000 index 0000000000..c83ed88406 --- /dev/null +++ b/Lang/Icon/Repeat @@ -0,0 +1 @@ +../../Task/Repeat/Icon \ No newline at end of file diff --git a/Lang/Icon/Search-a-list-of-records b/Lang/Icon/Search-a-list-of-records new file mode 120000 index 0000000000..b796eca599 --- /dev/null +++ b/Lang/Icon/Search-a-list-of-records @@ -0,0 +1 @@ +../../Task/Search-a-list-of-records/Icon \ No newline at end of file diff --git a/Lang/Icon/Sort-numbers-lexicographically b/Lang/Icon/Sort-numbers-lexicographically new file mode 120000 index 0000000000..7c99f7d928 --- /dev/null +++ b/Lang/Icon/Sort-numbers-lexicographically @@ -0,0 +1 @@ +../../Task/Sort-numbers-lexicographically/Icon \ No newline at end of file diff --git a/Lang/Icon/Tau-function b/Lang/Icon/Tau-function new file mode 120000 index 0000000000..a9852ae0fc --- /dev/null +++ b/Lang/Icon/Tau-function @@ -0,0 +1 @@ +../../Task/Tau-function/Icon \ No newline at end of file diff --git a/Lang/Icon/Tau-number b/Lang/Icon/Tau-number new file mode 120000 index 0000000000..16be5aedc6 --- /dev/null +++ b/Lang/Icon/Tau-number @@ -0,0 +1 @@ +../../Task/Tau-number/Icon \ No newline at end of file diff --git a/Lang/Icon/Thue-Morse b/Lang/Icon/Thue-Morse new file mode 120000 index 0000000000..bfa031f039 --- /dev/null +++ b/Lang/Icon/Thue-Morse @@ -0,0 +1 @@ +../../Task/Thue-Morse/Icon \ No newline at end of file diff --git a/Lang/Icon/Tokenize-a-string-with-escaping b/Lang/Icon/Tokenize-a-string-with-escaping new file mode 120000 index 0000000000..6a5856de9c --- /dev/null +++ b/Lang/Icon/Tokenize-a-string-with-escaping @@ -0,0 +1 @@ +../../Task/Tokenize-a-string-with-escaping/Icon \ No newline at end of file diff --git a/Lang/Icon/Tree-from-nesting-levels b/Lang/Icon/Tree-from-nesting-levels new file mode 120000 index 0000000000..670d6ecf62 --- /dev/null +++ b/Lang/Icon/Tree-from-nesting-levels @@ -0,0 +1 @@ +../../Task/Tree-from-nesting-levels/Icon \ No newline at end of file diff --git a/Lang/Icon/UTF-8-encode-and-decode b/Lang/Icon/UTF-8-encode-and-decode new file mode 120000 index 0000000000..354f23e4f3 --- /dev/null +++ b/Lang/Icon/UTF-8-encode-and-decode @@ -0,0 +1 @@ +../../Task/UTF-8-encode-and-decode/Icon \ No newline at end of file diff --git a/Lang/Icon/Unix-ls b/Lang/Icon/Unix-ls new file mode 120000 index 0000000000..a60d089d88 --- /dev/null +++ b/Lang/Icon/Unix-ls @@ -0,0 +1 @@ +../../Task/Unix-ls/Icon \ No newline at end of file diff --git a/Lang/Icon/Word-frequency b/Lang/Icon/Word-frequency new file mode 120000 index 0000000000..24fef71b7b --- /dev/null +++ b/Lang/Icon/Word-frequency @@ -0,0 +1 @@ +../../Task/Word-frequency/Icon \ No newline at end of file diff --git a/Lang/Icon/Write-entire-file b/Lang/Icon/Write-entire-file new file mode 120000 index 0000000000..a982401a37 --- /dev/null +++ b/Lang/Icon/Write-entire-file @@ -0,0 +1 @@ +../../Task/Write-entire-file/Icon \ No newline at end of file diff --git a/Lang/Idris/Comments b/Lang/Idris/Comments new file mode 120000 index 0000000000..ffaead275c --- /dev/null +++ b/Lang/Idris/Comments @@ -0,0 +1 @@ +../../Task/Comments/Idris \ No newline at end of file diff --git a/Lang/Idris/Palindrome-detection b/Lang/Idris/Palindrome-detection new file mode 120000 index 0000000000..58af724843 --- /dev/null +++ b/Lang/Idris/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/Idris \ No newline at end of file diff --git a/Lang/Idris/Quaternion-type b/Lang/Idris/Quaternion-type deleted file mode 120000 index 6489466168..0000000000 --- a/Lang/Idris/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Idris \ No newline at end of file diff --git a/Lang/Imp77/00-LANG.txt b/Lang/Imp77/00-LANG.txt new file mode 100644 index 0000000000..85ea555671 --- /dev/null +++ b/Lang/Imp77/00-LANG.txt @@ -0,0 +1,37 @@ +{{language +|exec=machine +|gc=no +|parampass=value or by address +|checking=static +|tags=imp77 +}}{{language programming paradigm|Imperative}} +'''Imp77''' is a general-purpose, [[procedural programming|procedural]], [[imperative programming|imperative]] computer programming language developed around 1977 by the Computer Science Department at Edinburgh University. The original Imp was an incremental development of its predecessor, [[derived from::AtlasAutocode]], via Imp9 . + +==Versions== +* '''Atlas Autocode''' was originally created by Tony Brooker as his response to the 1958 IAL proposal which was the prototype for Algol60. It was very similar to Algol 60 but without some of the problematic areas such as 'call-by-name'. +* '''Imp(AA)''' was the first Imp compiler (running on the KDF9) to use the name Imp, but it was almost identical to Atlas Autocode apart from having removed a few unused language features such as %complex variables and minor syntax that was dependent on the use of the Flexowriter and the KDF9 character set, which happened when the compiler was modified to use the 7-bit ISO character set. +* '''Imp9''' was the final release of Imp on the ICL System 4/75. By this point Imp had acquired records and strings. +* '''Impi''' was an interactive version of the Imp language based on the Imp9 specification, which compiled a statement at a time or a procedure at a time to executable code in memory. Although the Impi name meant "Imp Interpreter" it was not an interpreter in the sense of interpreting an intermediate code, but was rather a true dynamic and interactive compiler. +* '''Iopt''' was the Imp9 compiler modernised and ported to the ICL 29XX range. This was the most fully-featured version of Imp until Imp77 was created. +* '''Skimp''' was a cut-down version of the language, at about the same level of complexity as Atlas Autocode, used for teaching compiler-writing to third-year computer science students at Edinburgh University. It was also used as a bootstrapping compiler when porting imp to new systems. +* '''Imp15''' was an implementation of Imp for the PDP9 and PDP15 systems, which ran in 8K words (words being 18 bits). +* '''Imp11''' was a version of Imp, bootstrapped through Skimp but implementing most of the language, written to support the PDP11 processors used at Edinburgh for the communications network. +* '''Imp77''' was a full implementation of Imp supporting all language features, written by Peter Robertson of the Department of Computer Science in support of his PhD thesis on the subject of portable intermediate codes. Imp77 was adopted as the primary compiler of the Department of Computer Science at Edinburgh and made available on many architectures. Most Imp submissions to Rosetta Code will be in Imp77 because it is the only version of Imp remaining with a native compiler available (x86) although there are a few other architectures still usable under emulation. The current Imp77 compiler is a hobbyist revival and is to some extent still under development, lacking the extensive library support and runtime diagnostics that were present in Edinburgh University implementations. +* '''Imp80''' was an attempt to merge Iopt and Imp77 into a common subset language, as the versions of Imp used by the Edinburgh Regional Computing Center and the Department of Computer Science had diverged sufficiently by 1980, that much code was not compatible between the two versions. The standardisation process that Imp80 started was never completed as Edinburgh abandoned the use of Imp in the 1980's, under political pressure to switch to using languages with a broader code base. + +==Overview== + +Imp is structurally very similar to Algol 60 except that instead of Algol's "name" parameters which implement a somewhat broken call-by-substitution mechanism, Imp uses call-by-reference, passing the address of a variable instead, and implicitly de-referencing such variables within a procedure, without requiring explicit syntax to access them as would be done in C for example. + +==Stropping== + +Imp uses keywords rather than reserved words, and in principle keywords in an Imp program are written with underlining. However this was seldom done in practise (in fact the last implementation to support underlining was back when the language was still called Atlas Autocode) and the convention used was that alphabetic sequences introduced by a '%' character were to be considered as being underlined, with the underlining terminating on the first non-alphabetic character. Imp compilers applied a 'line reconstruction' phase to their input, converting underlined letters into an internal representation distinct from regular letters, whilst removing all spaces (but not line endings) from the input other than within quoted strings and characters. + +It is however quite acceptable to show listings of Imp programs with underlined (or bold) keywords in place of %-stropped keywords. +==Citation== + +==Todo== +* [[Tasks not implemented in Imp77]] + + +{{language programming paradigm|Imperative}} \ No newline at end of file diff --git a/Lang/Imp77/00-META.yaml b/Lang/Imp77/00-META.yaml new file mode 100644 index 0000000000..382e836f84 --- /dev/null +++ b/Lang/Imp77/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Imp77 diff --git a/Lang/Imp77/Towers-of-Hanoi b/Lang/Imp77/Towers-of-Hanoi new file mode 120000 index 0000000000..9cf1e23a14 --- /dev/null +++ b/Lang/Imp77/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Imp77 \ No newline at end of file diff --git a/Lang/Imp77/Trabb-Pardo-Knuth-algorithm b/Lang/Imp77/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..974a19fbc9 --- /dev/null +++ b/Lang/Imp77/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/Imp77 \ No newline at end of file diff --git a/Lang/Insitux/00-LANG.txt b/Lang/Insitux/00-LANG.txt index ffe7dc9e9e..b852a0706e 100644 --- a/Lang/Insitux/00-LANG.txt +++ b/Lang/Insitux/00-LANG.txt @@ -3,10 +3,8 @@ |hopl=no |tags=insitux}} -Insitux (pronounced /ɪnˈsɪtjuːɪks/) is a dynamically-typed functional scripting language inspired by Clojure, originally commissioned in July 2021 for safe and extensible in-game scripting in a popular Roblox game. It has retained compatibility with Roblox by using two sets of "poly-fills" between [https://roblox-ts.com/ roblox-ts] and Node.js / web, meaning it can target Roblox, Node.js, and web with two slightly varying codebases. +Insitux (pronounced /ɪnˈsɪtjuːɪks/) is a dynamically-typed functional scripting language inspired by Clojure, originally commissioned in July 2021 for safe and extensible in-game scripting in a popular Roblox game. It now targets Node.js/Bun and client-side web. -Despite its origins it is a capable language, with development focusing on the language itself, its Node.js ecosystem, and to a lesser extent its web ecosystem. This primarily involves adding to the already 200+ built-in operations, which tend to cause existing Insitux programs to shrink in size over time. - -Insitux currently does not have a performance focus, and due to its syntactic flexibility, and its engine being transpiled into both JavaScript and [https://luau-lang.org/ Luau], it is difficult to optimise. Eventually Roblox support will be dropped / forked, pivoting mainline Insitux into AOT and JIT JavaScript transpilation. +Despite its origins it is a capable language, with development focusing on the language itself, its Node.js ecosystem, and to a lesser extent its web ecosystem. This primarily involves adding to the already 200+ built-in operations, which tend to cause existing Insitux programs to shrink in size over time; and improving language performance since dropping Roblox compatibility in 2024. {{language programming paradigm|functional}} \ No newline at end of file diff --git a/Lang/Isabelle/Bernoulli-numbers b/Lang/Isabelle/Bernoulli-numbers new file mode 120000 index 0000000000..73728f3564 --- /dev/null +++ b/Lang/Isabelle/Bernoulli-numbers @@ -0,0 +1 @@ +../../Task/Bernoulli-numbers/Isabelle \ No newline at end of file diff --git a/Lang/Isabelle/Catalan-numbers b/Lang/Isabelle/Catalan-numbers new file mode 120000 index 0000000000..b2ce7b3a40 --- /dev/null +++ b/Lang/Isabelle/Catalan-numbers @@ -0,0 +1 @@ +../../Task/Catalan-numbers/Isabelle \ No newline at end of file diff --git a/Lang/J/00-LANG.txt b/Lang/J/00-LANG.txt index c3a67e79d5..5ca185b4f1 100644 --- a/Lang/J/00-LANG.txt +++ b/Lang/J/00-LANG.txt @@ -117,6 +117,7 @@ Discussion of the goals of the J community on RC and general guidelines for pres *[[User:Lambertdw|David Lambert]]:[[Special:Contributions/Lambertdw|contributions]] *[[User:JimTheriot|JimTheriot]]: [[Special:Contributions/JimTheriot|contributions]] *[[User:DevonMcC|Devon McCormick]]: [[Special:Contributions/DevonMcC|contributions]] +*[[User:Cchando|Cameron Chandoke]]: [[Special:Contributions/Cchando|contributions]], [[j:User:Cameron_Chandoke|J wiki]] == Try me == diff --git a/Lang/J/Bioinformatics-base-count b/Lang/J/Bioinformatics-base-count deleted file mode 120000 index 78c6127b60..0000000000 --- a/Lang/J/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/J \ No newline at end of file diff --git a/Lang/J/Meissel-Mertens-constant b/Lang/J/Meissel-Mertens-constant deleted file mode 120000 index 04eb0042a3..0000000000 --- a/Lang/J/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/J \ No newline at end of file diff --git a/Lang/J/Quaternion-type b/Lang/J/Quaternion-type deleted file mode 120000 index 0868577467..0000000000 --- a/Lang/J/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/J \ No newline at end of file diff --git a/Lang/J/Sorting-Algorithms-Circle-Sort b/Lang/J/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index c9563959dd..0000000000 --- a/Lang/J/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/J \ No newline at end of file diff --git a/Lang/Jactl/00-LANG.txt b/Lang/Jactl/00-LANG.txt new file mode 100644 index 0000000000..108b3303c1 --- /dev/null +++ b/Lang/Jactl/00-LANG.txt @@ -0,0 +1,8 @@ +{{stub}}{{language|Jactl}} + +Jactl is an open source scripting language that compiles to JVM byte-code. +It can be run stand-alone or embedded in Java applications. + +Documentation site: https://jactl.io + +Github repository: https://github.com/jaccomoc/jactl \ No newline at end of file diff --git a/Lang/Jactl/00-META.yaml b/Lang/Jactl/00-META.yaml new file mode 100644 index 0000000000..c4f2a6e6a8 --- /dev/null +++ b/Lang/Jactl/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Jactl diff --git a/Lang/Jactl/Apply-a-callback-to-an-array b/Lang/Jactl/Apply-a-callback-to-an-array new file mode 120000 index 0000000000..0b25c16ea6 --- /dev/null +++ b/Lang/Jactl/Apply-a-callback-to-an-array @@ -0,0 +1 @@ +../../Task/Apply-a-callback-to-an-array/Jactl \ No newline at end of file diff --git a/Lang/Jactl/Associative-array-Creation b/Lang/Jactl/Associative-array-Creation new file mode 120000 index 0000000000..df471994d0 --- /dev/null +++ b/Lang/Jactl/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/Jactl \ No newline at end of file diff --git a/Lang/Jactl/Associative-array-Iteration b/Lang/Jactl/Associative-array-Iteration new file mode 120000 index 0000000000..c89bf33985 --- /dev/null +++ b/Lang/Jactl/Associative-array-Iteration @@ -0,0 +1 @@ +../../Task/Associative-array-Iteration/Jactl \ No newline at end of file diff --git a/Lang/Jactl/Closures-Value-capture b/Lang/Jactl/Closures-Value-capture new file mode 120000 index 0000000000..838f9ae309 --- /dev/null +++ b/Lang/Jactl/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/Jactl \ No newline at end of file diff --git a/Lang/Jactl/Colorful-numbers b/Lang/Jactl/Colorful-numbers new file mode 120000 index 0000000000..a03bdecce3 --- /dev/null +++ b/Lang/Jactl/Colorful-numbers @@ -0,0 +1 @@ +../../Task/Colorful-numbers/Jactl \ No newline at end of file diff --git a/Lang/Jactl/Fibonacci-sequence b/Lang/Jactl/Fibonacci-sequence new file mode 120000 index 0000000000..6763bcee23 --- /dev/null +++ b/Lang/Jactl/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/Jactl \ No newline at end of file diff --git a/Lang/Jactl/FizzBuzz b/Lang/Jactl/FizzBuzz new file mode 120000 index 0000000000..fd8d004ee0 --- /dev/null +++ b/Lang/Jactl/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Jactl \ No newline at end of file diff --git a/Lang/Jactl/Hello-world-Newline-omission b/Lang/Jactl/Hello-world-Newline-omission new file mode 120000 index 0000000000..d612b43ea9 --- /dev/null +++ b/Lang/Jactl/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/Jactl \ No newline at end of file diff --git a/Lang/Jactl/Hello-world-Text b/Lang/Jactl/Hello-world-Text new file mode 120000 index 0000000000..fba754494d --- /dev/null +++ b/Lang/Jactl/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Jactl \ No newline at end of file diff --git a/Lang/Jactl/Loop-over-multiple-arrays-simultaneously b/Lang/Jactl/Loop-over-multiple-arrays-simultaneously new file mode 120000 index 0000000000..208e0c484c --- /dev/null +++ b/Lang/Jactl/Loop-over-multiple-arrays-simultaneously @@ -0,0 +1 @@ +../../Task/Loop-over-multiple-arrays-simultaneously/Jactl \ No newline at end of file diff --git a/Lang/Jactl/Loops-Break b/Lang/Jactl/Loops-Break new file mode 120000 index 0000000000..e1f4382462 --- /dev/null +++ b/Lang/Jactl/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/Jactl \ No newline at end of file diff --git a/Lang/Jactl/Loops-Continue b/Lang/Jactl/Loops-Continue new file mode 120000 index 0000000000..d7062f586e --- /dev/null +++ b/Lang/Jactl/Loops-Continue @@ -0,0 +1 @@ +../../Task/Loops-Continue/Jactl \ No newline at end of file diff --git a/Lang/Jactl/Loops-Do-while b/Lang/Jactl/Loops-Do-while new file mode 120000 index 0000000000..70f4e6642c --- /dev/null +++ b/Lang/Jactl/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/Jactl \ No newline at end of file diff --git a/Lang/Jactl/Loops-Downward-for b/Lang/Jactl/Loops-Downward-for new file mode 120000 index 0000000000..e955b7c7cb --- /dev/null +++ b/Lang/Jactl/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/Jactl \ No newline at end of file diff --git a/Lang/Jactl/Loops-For b/Lang/Jactl/Loops-For new file mode 120000 index 0000000000..69ac8efd8b --- /dev/null +++ b/Lang/Jactl/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/Jactl \ No newline at end of file diff --git a/Lang/Jactl/Loops-For-with-a-specified-step b/Lang/Jactl/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..cc4794f4cd --- /dev/null +++ b/Lang/Jactl/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/Jactl \ No newline at end of file diff --git a/Lang/Jactl/Loops-Foreach b/Lang/Jactl/Loops-Foreach new file mode 120000 index 0000000000..5acefa1624 --- /dev/null +++ b/Lang/Jactl/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/Jactl \ No newline at end of file diff --git a/Lang/Jactl/Loops-Increment-loop-index-within-loop-body b/Lang/Jactl/Loops-Increment-loop-index-within-loop-body new file mode 120000 index 0000000000..db9efe2bf3 --- /dev/null +++ b/Lang/Jactl/Loops-Increment-loop-index-within-loop-body @@ -0,0 +1 @@ +../../Task/Loops-Increment-loop-index-within-loop-body/Jactl \ No newline at end of file diff --git a/Lang/Jactl/Loops-Infinite b/Lang/Jactl/Loops-Infinite new file mode 120000 index 0000000000..7f2c46419c --- /dev/null +++ b/Lang/Jactl/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/Jactl \ No newline at end of file diff --git a/Lang/Jactl/Loops-N-plus-one-half b/Lang/Jactl/Loops-N-plus-one-half new file mode 120000 index 0000000000..03de5e2ce5 --- /dev/null +++ b/Lang/Jactl/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/Jactl \ No newline at end of file diff --git a/Lang/Jactl/Loops-Nested b/Lang/Jactl/Loops-Nested new file mode 120000 index 0000000000..4ee2958398 --- /dev/null +++ b/Lang/Jactl/Loops-Nested @@ -0,0 +1 @@ +../../Task/Loops-Nested/Jactl \ No newline at end of file diff --git a/Lang/Jactl/Loops-While b/Lang/Jactl/Loops-While new file mode 120000 index 0000000000..306a1e9dea --- /dev/null +++ b/Lang/Jactl/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/Jactl \ No newline at end of file diff --git a/Lang/Jactl/Selectively-replace-multiple-instances-of-a-character-within-a-string b/Lang/Jactl/Selectively-replace-multiple-instances-of-a-character-within-a-string new file mode 120000 index 0000000000..5c89cea762 --- /dev/null +++ b/Lang/Jactl/Selectively-replace-multiple-instances-of-a-character-within-a-string @@ -0,0 +1 @@ +../../Task/Selectively-replace-multiple-instances-of-a-character-within-a-string/Jactl \ No newline at end of file diff --git a/Lang/Jactl/Sorting-algorithms-Merge-sort b/Lang/Jactl/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..f5d29cd0bd --- /dev/null +++ b/Lang/Jactl/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Jactl \ No newline at end of file diff --git a/Lang/Jactl/Sorting-algorithms-Quicksort b/Lang/Jactl/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..6ebc4a30df --- /dev/null +++ b/Lang/Jactl/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Jactl \ No newline at end of file diff --git a/Lang/Jactl/String-interpolation-included- b/Lang/Jactl/String-interpolation-included- new file mode 120000 index 0000000000..4aeb71ddbe --- /dev/null +++ b/Lang/Jactl/String-interpolation-included- @@ -0,0 +1 @@ +../../Task/String-interpolation-included-/Jactl \ No newline at end of file diff --git a/Lang/Janet/Check-input-device-is-a-terminal b/Lang/Janet/Check-input-device-is-a-terminal new file mode 120000 index 0000000000..2a4f62bb71 --- /dev/null +++ b/Lang/Janet/Check-input-device-is-a-terminal @@ -0,0 +1 @@ +../../Task/Check-input-device-is-a-terminal/Janet \ No newline at end of file diff --git a/Lang/Janet/Check-output-device-is-a-terminal b/Lang/Janet/Check-output-device-is-a-terminal new file mode 120000 index 0000000000..8405e395e2 --- /dev/null +++ b/Lang/Janet/Check-output-device-is-a-terminal @@ -0,0 +1 @@ +../../Task/Check-output-device-is-a-terminal/Janet \ No newline at end of file diff --git a/Lang/Janet/Comments b/Lang/Janet/Comments new file mode 120000 index 0000000000..b5297d4f4d --- /dev/null +++ b/Lang/Janet/Comments @@ -0,0 +1 @@ +../../Task/Comments/Janet \ No newline at end of file diff --git a/Lang/Janet/Determine-if-a-string-has-all-the-same-characters b/Lang/Janet/Determine-if-a-string-has-all-the-same-characters new file mode 120000 index 0000000000..361efcff47 --- /dev/null +++ b/Lang/Janet/Determine-if-a-string-has-all-the-same-characters @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-has-all-the-same-characters/Janet \ No newline at end of file diff --git a/Lang/Janet/Environment-variables b/Lang/Janet/Environment-variables new file mode 120000 index 0000000000..7f09b690ca --- /dev/null +++ b/Lang/Janet/Environment-variables @@ -0,0 +1 @@ +../../Task/Environment-variables/Janet \ No newline at end of file diff --git a/Lang/Janet/Loops-Infinite b/Lang/Janet/Loops-Infinite new file mode 120000 index 0000000000..6c4ed476ed --- /dev/null +++ b/Lang/Janet/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/Janet \ No newline at end of file diff --git a/Lang/Janet/Nested-function b/Lang/Janet/Nested-function new file mode 120000 index 0000000000..cc57c8a9fa --- /dev/null +++ b/Lang/Janet/Nested-function @@ -0,0 +1 @@ +../../Task/Nested-function/Janet \ No newline at end of file diff --git a/Lang/Janet/Partial-function-application b/Lang/Janet/Partial-function-application new file mode 120000 index 0000000000..2936ce5923 --- /dev/null +++ b/Lang/Janet/Partial-function-application @@ -0,0 +1 @@ +../../Task/Partial-function-application/Janet \ No newline at end of file diff --git a/Lang/Janet/Short-circuit-evaluation b/Lang/Janet/Short-circuit-evaluation new file mode 120000 index 0000000000..c41f99f9ac --- /dev/null +++ b/Lang/Janet/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Janet \ No newline at end of file diff --git a/Lang/Janet/Sum-and-product-of-an-array b/Lang/Janet/Sum-and-product-of-an-array new file mode 120000 index 0000000000..798628772b --- /dev/null +++ b/Lang/Janet/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Janet \ No newline at end of file diff --git a/Lang/Java/00-LANG.txt b/Lang/Java/00-LANG.txt index 72a980a538..9df12a7429 100644 --- a/Lang/Java/00-LANG.txt +++ b/Lang/Java/00-LANG.txt @@ -41,4 +41,4 @@ Useful Java links: * [http://openjdk.java.net OpenJDK] ==Todo== -[[Reports:Tasks_not_implemented_in_Java]] \ No newline at end of file +[https://rosettacode.org/wiki/Tasks_not_implemented_in_Java Tasks not implemented in Java] \ No newline at end of file diff --git a/Lang/Java/Arena-storage-pool b/Lang/Java/Arena-storage-pool new file mode 120000 index 0000000000..11592b83c1 --- /dev/null +++ b/Lang/Java/Arena-storage-pool @@ -0,0 +1 @@ +../../Task/Arena-storage-pool/Java \ No newline at end of file diff --git a/Lang/Java/Bioinformatics-base-count b/Lang/Java/Bioinformatics-base-count deleted file mode 120000 index a3d5761560..0000000000 --- a/Lang/Java/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Java \ No newline at end of file diff --git a/Lang/Java/Bitcoin-public-point-to-address b/Lang/Java/Bitcoin-public-point-to-address new file mode 120000 index 0000000000..cbdcab404f --- /dev/null +++ b/Lang/Java/Bitcoin-public-point-to-address @@ -0,0 +1 @@ +../../Task/Bitcoin-public-point-to-address/Java \ No newline at end of file diff --git a/Lang/Java/Bitwise-IO b/Lang/Java/Bitwise-IO new file mode 120000 index 0000000000..91887eddd0 --- /dev/null +++ b/Lang/Java/Bitwise-IO @@ -0,0 +1 @@ +../../Task/Bitwise-IO/Java \ No newline at end of file diff --git a/Lang/Java/Catmull-Clark-subdivision-surface b/Lang/Java/Catmull-Clark-subdivision-surface new file mode 120000 index 0000000000..cc0173bf86 --- /dev/null +++ b/Lang/Java/Catmull-Clark-subdivision-surface @@ -0,0 +1 @@ +../../Task/Catmull-Clark-subdivision-surface/Java \ No newline at end of file diff --git a/Lang/Java/Check-output-device-is-a-terminal b/Lang/Java/Check-output-device-is-a-terminal new file mode 120000 index 0000000000..f5afcf5e18 --- /dev/null +++ b/Lang/Java/Check-output-device-is-a-terminal @@ -0,0 +1 @@ +../../Task/Check-output-device-is-a-terminal/Java \ No newline at end of file diff --git a/Lang/Java/Compare-sorting-algorithms-performance b/Lang/Java/Compare-sorting-algorithms-performance new file mode 120000 index 0000000000..1c312e8af3 --- /dev/null +++ b/Lang/Java/Compare-sorting-algorithms-performance @@ -0,0 +1 @@ +../../Task/Compare-sorting-algorithms-performance/Java \ No newline at end of file diff --git a/Lang/Java/Compiler-virtual-machine-interpreter b/Lang/Java/Compiler-virtual-machine-interpreter new file mode 120000 index 0000000000..8a6c333099 --- /dev/null +++ b/Lang/Java/Compiler-virtual-machine-interpreter @@ -0,0 +1 @@ +../../Task/Compiler-virtual-machine-interpreter/Java \ No newline at end of file diff --git a/Lang/Java/Cyclops-numbers b/Lang/Java/Cyclops-numbers new file mode 120000 index 0000000000..2d9674ea30 --- /dev/null +++ b/Lang/Java/Cyclops-numbers @@ -0,0 +1 @@ +../../Task/Cyclops-numbers/Java \ No newline at end of file diff --git a/Lang/Java/Deconvolution-2D+ b/Lang/Java/Deconvolution-2D+ new file mode 120000 index 0000000000..a4641fed07 --- /dev/null +++ b/Lang/Java/Deconvolution-2D+ @@ -0,0 +1 @@ +../../Task/Deconvolution-2D+/Java \ No newline at end of file diff --git a/Lang/Java/Dominoes b/Lang/Java/Dominoes new file mode 120000 index 0000000000..f00d194617 --- /dev/null +++ b/Lang/Java/Dominoes @@ -0,0 +1 @@ +../../Task/Dominoes/Java \ No newline at end of file diff --git a/Lang/Java/Events b/Lang/Java/Events new file mode 120000 index 0000000000..c4d1c5d403 --- /dev/null +++ b/Lang/Java/Events @@ -0,0 +1 @@ +../../Task/Events/Java \ No newline at end of file diff --git a/Lang/Java/Fixed-length-records b/Lang/Java/Fixed-length-records new file mode 120000 index 0000000000..8506be253e --- /dev/null +++ b/Lang/Java/Fixed-length-records @@ -0,0 +1 @@ +../../Task/Fixed-length-records/Java \ No newline at end of file diff --git a/Lang/Java/French-Republican-calendar b/Lang/Java/French-Republican-calendar new file mode 120000 index 0000000000..2451cb085a --- /dev/null +++ b/Lang/Java/French-Republican-calendar @@ -0,0 +1 @@ +../../Task/French-Republican-calendar/Java \ No newline at end of file diff --git a/Lang/Java/Im-a-software-engineer-get-me-out-of-here b/Lang/Java/Im-a-software-engineer-get-me-out-of-here new file mode 120000 index 0000000000..5e4c7fd308 --- /dev/null +++ b/Lang/Java/Im-a-software-engineer-get-me-out-of-here @@ -0,0 +1 @@ +../../Task/Im-a-software-engineer-get-me-out-of-here/Java \ No newline at end of file diff --git a/Lang/Java/Matrix-exponentiation-operator b/Lang/Java/Matrix-exponentiation-operator new file mode 120000 index 0000000000..e07ce3d287 --- /dev/null +++ b/Lang/Java/Matrix-exponentiation-operator @@ -0,0 +1 @@ +../../Task/Matrix-exponentiation-operator/Java \ No newline at end of file diff --git a/Lang/Java/Meissel-Mertens-constant b/Lang/Java/Meissel-Mertens-constant deleted file mode 120000 index f7dce3ca3d..0000000000 --- a/Lang/Java/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/Java \ No newline at end of file diff --git a/Lang/Java/Miller-Rabin-primality-test b/Lang/Java/Miller-Rabin-primality-test deleted file mode 120000 index 5708188da1..0000000000 --- a/Lang/Java/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Java \ No newline at end of file diff --git a/Lang/Java/Natural-sorting b/Lang/Java/Natural-sorting new file mode 120000 index 0000000000..9f37ed8709 --- /dev/null +++ b/Lang/Java/Natural-sorting @@ -0,0 +1 @@ +../../Task/Natural-sorting/Java \ No newline at end of file diff --git a/Lang/Java/Nested-templated-data b/Lang/Java/Nested-templated-data new file mode 120000 index 0000000000..ffed37deff --- /dev/null +++ b/Lang/Java/Nested-templated-data @@ -0,0 +1 @@ +../../Task/Nested-templated-data/Java \ No newline at end of file diff --git a/Lang/Java/Numerical-and-alphabetical-suffixes b/Lang/Java/Numerical-and-alphabetical-suffixes new file mode 120000 index 0000000000..b77e52fdf7 --- /dev/null +++ b/Lang/Java/Numerical-and-alphabetical-suffixes @@ -0,0 +1 @@ +../../Task/Numerical-and-alphabetical-suffixes/Java \ No newline at end of file diff --git a/Lang/Java/P-Adic-square-roots b/Lang/Java/P-Adic-square-roots new file mode 120000 index 0000000000..768922bdbb --- /dev/null +++ b/Lang/Java/P-Adic-square-roots @@ -0,0 +1 @@ +../../Task/P-Adic-square-roots/Java \ No newline at end of file diff --git a/Lang/Java/Quaternion-type b/Lang/Java/Quaternion-type deleted file mode 120000 index 3cf154640d..0000000000 --- a/Lang/Java/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Java \ No newline at end of file diff --git a/Lang/Java/Rendezvous b/Lang/Java/Rendezvous new file mode 120000 index 0000000000..b182a3392e --- /dev/null +++ b/Lang/Java/Rendezvous @@ -0,0 +1 @@ +../../Task/Rendezvous/Java \ No newline at end of file diff --git a/Lang/Java/Sorting-Algorithms-Circle-Sort b/Lang/Java/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 2c7141e7c3..0000000000 --- a/Lang/Java/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Java \ No newline at end of file diff --git a/Lang/Java/Strassens-algorithm b/Lang/Java/Strassens-algorithm new file mode 120000 index 0000000000..1c8b3f279b --- /dev/null +++ b/Lang/Java/Strassens-algorithm @@ -0,0 +1 @@ +../../Task/Strassens-algorithm/Java \ No newline at end of file diff --git a/Lang/Java/Suffixation-of-decimal-numbers b/Lang/Java/Suffixation-of-decimal-numbers new file mode 120000 index 0000000000..a2b82d2da9 --- /dev/null +++ b/Lang/Java/Suffixation-of-decimal-numbers @@ -0,0 +1 @@ +../../Task/Suffixation-of-decimal-numbers/Java \ No newline at end of file diff --git a/Lang/Java/Sylvesters-sequence b/Lang/Java/Sylvesters-sequence new file mode 120000 index 0000000000..6dfb05d095 --- /dev/null +++ b/Lang/Java/Sylvesters-sequence @@ -0,0 +1 @@ +../../Task/Sylvesters-sequence/Java \ No newline at end of file diff --git a/Lang/Java/Topic-variable b/Lang/Java/Topic-variable new file mode 120000 index 0000000000..25c03be6d5 --- /dev/null +++ b/Lang/Java/Topic-variable @@ -0,0 +1 @@ +../../Task/Topic-variable/Java \ No newline at end of file diff --git a/Lang/Java/Untouchable-numbers b/Lang/Java/Untouchable-numbers new file mode 120000 index 0000000000..4fdd94665a --- /dev/null +++ b/Lang/Java/Untouchable-numbers @@ -0,0 +1 @@ +../../Task/Untouchable-numbers/Java \ No newline at end of file diff --git a/Lang/JavaScript/15-puzzle-solver b/Lang/JavaScript/15-puzzle-solver new file mode 120000 index 0000000000..34b980cd29 --- /dev/null +++ b/Lang/JavaScript/15-puzzle-solver @@ -0,0 +1 @@ +../../Task/15-puzzle-solver/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/ADFGVX-cipher b/Lang/JavaScript/ADFGVX-cipher new file mode 120000 index 0000000000..eeef4038b2 --- /dev/null +++ b/Lang/JavaScript/ADFGVX-cipher @@ -0,0 +1 @@ +../../Task/ADFGVX-cipher/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Achilles-numbers b/Lang/JavaScript/Achilles-numbers new file mode 120000 index 0000000000..0c343baad5 --- /dev/null +++ b/Lang/JavaScript/Achilles-numbers @@ -0,0 +1 @@ +../../Task/Achilles-numbers/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Aliquot-sequence-classifications b/Lang/JavaScript/Aliquot-sequence-classifications new file mode 120000 index 0000000000..5043f9bf29 --- /dev/null +++ b/Lang/JavaScript/Aliquot-sequence-classifications @@ -0,0 +1 @@ +../../Task/Aliquot-sequence-classifications/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Arithmetic-geometric-mean-Calculate-Pi b/Lang/JavaScript/Arithmetic-geometric-mean-Calculate-Pi new file mode 120000 index 0000000000..28dcd16b9c --- /dev/null +++ b/Lang/JavaScript/Arithmetic-geometric-mean-Calculate-Pi @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean-Calculate-Pi/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Arithmetic-numbers b/Lang/JavaScript/Arithmetic-numbers new file mode 120000 index 0000000000..ca8b16d782 --- /dev/null +++ b/Lang/JavaScript/Arithmetic-numbers @@ -0,0 +1 @@ +../../Task/Arithmetic-numbers/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Average-loop-length b/Lang/JavaScript/Average-loop-length new file mode 120000 index 0000000000..c1bd894dc5 --- /dev/null +++ b/Lang/JavaScript/Average-loop-length @@ -0,0 +1 @@ +../../Task/Average-loop-length/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/B-zier-curves-Intersections b/Lang/JavaScript/B-zier-curves-Intersections new file mode 120000 index 0000000000..e14b622f07 --- /dev/null +++ b/Lang/JavaScript/B-zier-curves-Intersections @@ -0,0 +1 @@ +../../Task/B-zier-curves-Intersections/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Babylonian-spiral b/Lang/JavaScript/Babylonian-spiral new file mode 120000 index 0000000000..c1ab7a098f --- /dev/null +++ b/Lang/JavaScript/Babylonian-spiral @@ -0,0 +1 @@ +../../Task/Babylonian-spiral/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Balanced-ternary b/Lang/JavaScript/Balanced-ternary new file mode 120000 index 0000000000..c71298b653 --- /dev/null +++ b/Lang/JavaScript/Balanced-ternary @@ -0,0 +1 @@ +../../Task/Balanced-ternary/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Bell-numbers b/Lang/JavaScript/Bell-numbers new file mode 120000 index 0000000000..d4be94731e --- /dev/null +++ b/Lang/JavaScript/Bell-numbers @@ -0,0 +1 @@ +../../Task/Bell-numbers/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Bernoulli-numbers b/Lang/JavaScript/Bernoulli-numbers new file mode 120000 index 0000000000..96368f729e --- /dev/null +++ b/Lang/JavaScript/Bernoulli-numbers @@ -0,0 +1 @@ +../../Task/Bernoulli-numbers/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Bifid-cipher b/Lang/JavaScript/Bifid-cipher new file mode 120000 index 0000000000..837e122e66 --- /dev/null +++ b/Lang/JavaScript/Bifid-cipher @@ -0,0 +1 @@ +../../Task/Bifid-cipher/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Bioinformatics-base-count b/Lang/JavaScript/Bioinformatics-base-count deleted file mode 120000 index 033fba4ffa..0000000000 --- a/Lang/JavaScript/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Bitcoin-address-validation b/Lang/JavaScript/Bitcoin-address-validation new file mode 120000 index 0000000000..d09d433cd8 --- /dev/null +++ b/Lang/JavaScript/Bitcoin-address-validation @@ -0,0 +1 @@ +../../Task/Bitcoin-address-validation/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Bitcoin-public-point-to-address b/Lang/JavaScript/Bitcoin-public-point-to-address new file mode 120000 index 0000000000..c3f037151b --- /dev/null +++ b/Lang/JavaScript/Bitcoin-public-point-to-address @@ -0,0 +1 @@ +../../Task/Bitcoin-public-point-to-address/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Boyer-Moore-string-search b/Lang/JavaScript/Boyer-Moore-string-search new file mode 120000 index 0000000000..b25016942d --- /dev/null +++ b/Lang/JavaScript/Boyer-Moore-string-search @@ -0,0 +1 @@ +../../Task/Boyer-Moore-string-search/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Brazilian-numbers b/Lang/JavaScript/Brazilian-numbers new file mode 120000 index 0000000000..a5d5cf431a --- /dev/null +++ b/Lang/JavaScript/Brazilian-numbers @@ -0,0 +1 @@ +../../Task/Brazilian-numbers/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Break-OO-privacy b/Lang/JavaScript/Break-OO-privacy new file mode 120000 index 0000000000..085d7969ff --- /dev/null +++ b/Lang/JavaScript/Break-OO-privacy @@ -0,0 +1 @@ +../../Task/Break-OO-privacy/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Brilliant-numbers b/Lang/JavaScript/Brilliant-numbers new file mode 120000 index 0000000000..447591badd --- /dev/null +++ b/Lang/JavaScript/Brilliant-numbers @@ -0,0 +1 @@ +../../Task/Brilliant-numbers/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Burrows-Wheeler-transform b/Lang/JavaScript/Burrows-Wheeler-transform new file mode 120000 index 0000000000..79a79f877d --- /dev/null +++ b/Lang/JavaScript/Burrows-Wheeler-transform @@ -0,0 +1 @@ +../../Task/Burrows-Wheeler-transform/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Calkin-Wilf-sequence b/Lang/JavaScript/Calkin-Wilf-sequence new file mode 120000 index 0000000000..3eaf3f5375 --- /dev/null +++ b/Lang/JavaScript/Calkin-Wilf-sequence @@ -0,0 +1 @@ +../../Task/Calkin-Wilf-sequence/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Camel-case-and-snake-case b/Lang/JavaScript/Camel-case-and-snake-case new file mode 120000 index 0000000000..0e52d396b8 --- /dev/null +++ b/Lang/JavaScript/Camel-case-and-snake-case @@ -0,0 +1 @@ +../../Task/Camel-case-and-snake-case/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Carmichael-3-strong-pseudoprimes b/Lang/JavaScript/Carmichael-3-strong-pseudoprimes new file mode 120000 index 0000000000..a3d0ffd992 --- /dev/null +++ b/Lang/JavaScript/Carmichael-3-strong-pseudoprimes @@ -0,0 +1 @@ +../../Task/Carmichael-3-strong-pseudoprimes/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Catmull-Clark-subdivision-surface b/Lang/JavaScript/Catmull-Clark-subdivision-surface new file mode 120000 index 0000000000..40bf4ef0fc --- /dev/null +++ b/Lang/JavaScript/Catmull-Clark-subdivision-surface @@ -0,0 +1 @@ +../../Task/Catmull-Clark-subdivision-surface/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Check-output-device-is-a-terminal b/Lang/JavaScript/Check-output-device-is-a-terminal new file mode 120000 index 0000000000..0efca1a6ff --- /dev/null +++ b/Lang/JavaScript/Check-output-device-is-a-terminal @@ -0,0 +1 @@ +../../Task/Check-output-device-is-a-terminal/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Checkpoint-synchronization b/Lang/JavaScript/Checkpoint-synchronization new file mode 120000 index 0000000000..cf18aef6aa --- /dev/null +++ b/Lang/JavaScript/Checkpoint-synchronization @@ -0,0 +1 @@ +../../Task/Checkpoint-synchronization/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Chernicks-Carmichael-numbers b/Lang/JavaScript/Chernicks-Carmichael-numbers new file mode 120000 index 0000000000..45e47ff0f0 --- /dev/null +++ b/Lang/JavaScript/Chernicks-Carmichael-numbers @@ -0,0 +1 @@ +../../Task/Chernicks-Carmichael-numbers/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Chowla-numbers b/Lang/JavaScript/Chowla-numbers new file mode 120000 index 0000000000..44b573de9f --- /dev/null +++ b/Lang/JavaScript/Chowla-numbers @@ -0,0 +1 @@ +../../Task/Chowla-numbers/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Circular-primes b/Lang/JavaScript/Circular-primes new file mode 120000 index 0000000000..ce0d83b0b4 --- /dev/null +++ b/Lang/JavaScript/Circular-primes @@ -0,0 +1 @@ +../../Task/Circular-primes/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Colorful-numbers b/Lang/JavaScript/Colorful-numbers new file mode 120000 index 0000000000..861658de92 --- /dev/null +++ b/Lang/JavaScript/Colorful-numbers @@ -0,0 +1 @@ +../../Task/Colorful-numbers/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Commatizing-numbers b/Lang/JavaScript/Commatizing-numbers new file mode 120000 index 0000000000..dac4a7f279 --- /dev/null +++ b/Lang/JavaScript/Commatizing-numbers @@ -0,0 +1 @@ +../../Task/Commatizing-numbers/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Compiler-code-generator b/Lang/JavaScript/Compiler-code-generator new file mode 120000 index 0000000000..7b6f8e25b0 --- /dev/null +++ b/Lang/JavaScript/Compiler-code-generator @@ -0,0 +1 @@ +../../Task/Compiler-code-generator/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k b/Lang/JavaScript/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k new file mode 120000 index 0000000000..2b7b501bb6 --- /dev/null +++ b/Lang/JavaScript/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/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Continued-fraction b/Lang/JavaScript/Continued-fraction new file mode 120000 index 0000000000..73bc586c57 --- /dev/null +++ b/Lang/JavaScript/Continued-fraction @@ -0,0 +1 @@ +../../Task/Continued-fraction/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Continued-fraction-Arithmetic-Construct-from-rational-number b/Lang/JavaScript/Continued-fraction-Arithmetic-Construct-from-rational-number new file mode 120000 index 0000000000..b87cd7b6a5 --- /dev/null +++ b/Lang/JavaScript/Continued-fraction-Arithmetic-Construct-from-rational-number @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-Construct-from-rational-number/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- b/Lang/JavaScript/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- new file mode 120000 index 0000000000..95862446c9 --- /dev/null +++ b/Lang/JavaScript/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n-/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Create-a-file-on-magnetic-tape b/Lang/JavaScript/Create-a-file-on-magnetic-tape new file mode 120000 index 0000000000..0f15206dcf --- /dev/null +++ b/Lang/JavaScript/Create-a-file-on-magnetic-tape @@ -0,0 +1 @@ +../../Task/Create-a-file-on-magnetic-tape/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Cuban-primes b/Lang/JavaScript/Cuban-primes new file mode 120000 index 0000000000..4659a4500f --- /dev/null +++ b/Lang/JavaScript/Cuban-primes @@ -0,0 +1 @@ +../../Task/Cuban-primes/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Cullen-and-Woodall-numbers b/Lang/JavaScript/Cullen-and-Woodall-numbers new file mode 120000 index 0000000000..7d700fedb9 --- /dev/null +++ b/Lang/JavaScript/Cullen-and-Woodall-numbers @@ -0,0 +1 @@ +../../Task/Cullen-and-Woodall-numbers/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Curzon-numbers b/Lang/JavaScript/Curzon-numbers new file mode 120000 index 0000000000..5d5da06bda --- /dev/null +++ b/Lang/JavaScript/Curzon-numbers @@ -0,0 +1 @@ +../../Task/Curzon-numbers/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Cyclops-numbers b/Lang/JavaScript/Cyclops-numbers new file mode 120000 index 0000000000..6c3c7fc0d0 --- /dev/null +++ b/Lang/JavaScript/Cyclops-numbers @@ -0,0 +1 @@ +../../Task/Cyclops-numbers/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Cyclotomic-polynomial b/Lang/JavaScript/Cyclotomic-polynomial new file mode 120000 index 0000000000..1407b6559c --- /dev/null +++ b/Lang/JavaScript/Cyclotomic-polynomial @@ -0,0 +1 @@ +../../Task/Cyclotomic-polynomial/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/De-Bruijn-sequences b/Lang/JavaScript/De-Bruijn-sequences new file mode 120000 index 0000000000..d753d9f9d0 --- /dev/null +++ b/Lang/JavaScript/De-Bruijn-sequences @@ -0,0 +1 @@ +../../Task/De-Bruijn-sequences/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Deconvolution-1D b/Lang/JavaScript/Deconvolution-1D new file mode 120000 index 0000000000..719c208ec2 --- /dev/null +++ b/Lang/JavaScript/Deconvolution-1D @@ -0,0 +1 @@ +../../Task/Deconvolution-1D/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Deconvolution-2D+ b/Lang/JavaScript/Deconvolution-2D+ new file mode 120000 index 0000000000..61f93d9cd6 --- /dev/null +++ b/Lang/JavaScript/Deconvolution-2D+ @@ -0,0 +1 @@ +../../Task/Deconvolution-2D+/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Demings-funnel b/Lang/JavaScript/Demings-funnel new file mode 120000 index 0000000000..6225280d4a --- /dev/null +++ b/Lang/JavaScript/Demings-funnel @@ -0,0 +1 @@ +../../Task/Demings-funnel/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Digital-root-Multiplicative-digital-root b/Lang/JavaScript/Digital-root-Multiplicative-digital-root new file mode 120000 index 0000000000..6bac52bd37 --- /dev/null +++ b/Lang/JavaScript/Digital-root-Multiplicative-digital-root @@ -0,0 +1 @@ +../../Task/Digital-root-Multiplicative-digital-root/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Display-a-linear-combination b/Lang/JavaScript/Display-a-linear-combination new file mode 120000 index 0000000000..4b7084cb84 --- /dev/null +++ b/Lang/JavaScript/Display-a-linear-combination @@ -0,0 +1 @@ +../../Task/Display-a-linear-combination/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Distribution-of-0-digits-in-factorial-series b/Lang/JavaScript/Distribution-of-0-digits-in-factorial-series new file mode 120000 index 0000000000..3fd7f0feb5 --- /dev/null +++ b/Lang/JavaScript/Distribution-of-0-digits-in-factorial-series @@ -0,0 +1 @@ +../../Task/Distribution-of-0-digits-in-factorial-series/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Dominoes b/Lang/JavaScript/Dominoes new file mode 120000 index 0000000000..240a06d327 --- /dev/null +++ b/Lang/JavaScript/Dominoes @@ -0,0 +1 @@ +../../Task/Dominoes/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Doomsday-rule b/Lang/JavaScript/Doomsday-rule new file mode 120000 index 0000000000..53e067c157 --- /dev/null +++ b/Lang/JavaScript/Doomsday-rule @@ -0,0 +1 @@ +../../Task/Doomsday-rule/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Duffinian-numbers b/Lang/JavaScript/Duffinian-numbers new file mode 120000 index 0000000000..852d875370 --- /dev/null +++ b/Lang/JavaScript/Duffinian-numbers @@ -0,0 +1 @@ +../../Task/Duffinian-numbers/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/EKG-sequence-convergence b/Lang/JavaScript/EKG-sequence-convergence new file mode 120000 index 0000000000..2eef93ef6c --- /dev/null +++ b/Lang/JavaScript/EKG-sequence-convergence @@ -0,0 +1 @@ +../../Task/EKG-sequence-convergence/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Eban-numbers b/Lang/JavaScript/Eban-numbers new file mode 120000 index 0000000000..584fb39bde --- /dev/null +++ b/Lang/JavaScript/Eban-numbers @@ -0,0 +1 @@ +../../Task/Eban-numbers/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Element-wise-operations b/Lang/JavaScript/Element-wise-operations new file mode 120000 index 0000000000..179f9154f4 --- /dev/null +++ b/Lang/JavaScript/Element-wise-operations @@ -0,0 +1 @@ +../../Task/Element-wise-operations/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Elliptic-Curve-Digital-Signature-Algorithm b/Lang/JavaScript/Elliptic-Curve-Digital-Signature-Algorithm new file mode 120000 index 0000000000..b9a9906259 --- /dev/null +++ b/Lang/JavaScript/Elliptic-Curve-Digital-Signature-Algorithm @@ -0,0 +1 @@ +../../Task/Elliptic-Curve-Digital-Signature-Algorithm/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Elliptic-curve-arithmetic b/Lang/JavaScript/Elliptic-curve-arithmetic new file mode 120000 index 0000000000..41de6c075f --- /dev/null +++ b/Lang/JavaScript/Elliptic-curve-arithmetic @@ -0,0 +1 @@ +../../Task/Elliptic-curve-arithmetic/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Erd-s-Nicolas-numbers b/Lang/JavaScript/Erd-s-Nicolas-numbers new file mode 120000 index 0000000000..2d8924574b --- /dev/null +++ b/Lang/JavaScript/Erd-s-Nicolas-numbers @@ -0,0 +1 @@ +../../Task/Erd-s-Nicolas-numbers/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Erd-s-Selfridge-categorization-of-primes b/Lang/JavaScript/Erd-s-Selfridge-categorization-of-primes new file mode 120000 index 0000000000..376367be26 --- /dev/null +++ b/Lang/JavaScript/Erd-s-Selfridge-categorization-of-primes @@ -0,0 +1 @@ +../../Task/Erd-s-Selfridge-categorization-of-primes/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Euclid-Mullin-sequence b/Lang/JavaScript/Euclid-Mullin-sequence new file mode 120000 index 0000000000..f2430affeb --- /dev/null +++ b/Lang/JavaScript/Euclid-Mullin-sequence @@ -0,0 +1 @@ +../../Task/Euclid-Mullin-sequence/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Eulers-constant-0.5772... b/Lang/JavaScript/Eulers-constant-0.5772... new file mode 120000 index 0000000000..3aac1cafba --- /dev/null +++ b/Lang/JavaScript/Eulers-constant-0.5772... @@ -0,0 +1 @@ +../../Task/Eulers-constant-0.5772.../JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Exponentiation-order b/Lang/JavaScript/Exponentiation-order new file mode 120000 index 0000000000..a3de1259b9 --- /dev/null +++ b/Lang/JavaScript/Exponentiation-order @@ -0,0 +1 @@ +../../Task/Exponentiation-order/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Exponentiation-with-infix-operators-in-or-operating-on-the-base b/Lang/JavaScript/Exponentiation-with-infix-operators-in-or-operating-on-the-base new file mode 120000 index 0000000000..d16e5defb5 --- /dev/null +++ b/Lang/JavaScript/Exponentiation-with-infix-operators-in-or-operating-on-the-base @@ -0,0 +1 @@ +../../Task/Exponentiation-with-infix-operators-in-or-operating-on-the-base/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Factorial-base-numbers-indexing-permutations-of-a-collection b/Lang/JavaScript/Factorial-base-numbers-indexing-permutations-of-a-collection new file mode 120000 index 0000000000..7b4e06b0ab --- /dev/null +++ b/Lang/JavaScript/Factorial-base-numbers-indexing-permutations-of-a-collection @@ -0,0 +1 @@ +../../Task/Factorial-base-numbers-indexing-permutations-of-a-collection/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Factorions b/Lang/JavaScript/Factorions new file mode 120000 index 0000000000..d7c8ae41c4 --- /dev/null +++ b/Lang/JavaScript/Factorions @@ -0,0 +1 @@ +../../Task/Factorions/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Farey-sequence b/Lang/JavaScript/Farey-sequence new file mode 120000 index 0000000000..e324d68d34 --- /dev/null +++ b/Lang/JavaScript/Farey-sequence @@ -0,0 +1 @@ +../../Task/Farey-sequence/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Faulhabers-formula b/Lang/JavaScript/Faulhabers-formula new file mode 120000 index 0000000000..547452171f --- /dev/null +++ b/Lang/JavaScript/Faulhabers-formula @@ -0,0 +1 @@ +../../Task/Faulhabers-formula/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Fermat-numbers b/Lang/JavaScript/Fermat-numbers new file mode 120000 index 0000000000..14c8b8d697 --- /dev/null +++ b/Lang/JavaScript/Fermat-numbers @@ -0,0 +1 @@ +../../Task/Fermat-numbers/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Fraction-reduction b/Lang/JavaScript/Fraction-reduction new file mode 120000 index 0000000000..f3f2ab2629 --- /dev/null +++ b/Lang/JavaScript/Fraction-reduction @@ -0,0 +1 @@ +../../Task/Fraction-reduction/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/French-Republican-calendar b/Lang/JavaScript/French-Republican-calendar new file mode 120000 index 0000000000..b3233aa527 --- /dev/null +++ b/Lang/JavaScript/French-Republican-calendar @@ -0,0 +1 @@ +../../Task/French-Republican-calendar/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Gauss-Jordan-matrix-inversion b/Lang/JavaScript/Gauss-Jordan-matrix-inversion new file mode 120000 index 0000000000..77acac5de4 --- /dev/null +++ b/Lang/JavaScript/Gauss-Jordan-matrix-inversion @@ -0,0 +1 @@ +../../Task/Gauss-Jordan-matrix-inversion/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Giuga-numbers b/Lang/JavaScript/Giuga-numbers new file mode 120000 index 0000000000..757d93b792 --- /dev/null +++ b/Lang/JavaScript/Giuga-numbers @@ -0,0 +1 @@ +../../Task/Giuga-numbers/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Graph-colouring b/Lang/JavaScript/Graph-colouring new file mode 120000 index 0000000000..8c22e6e014 --- /dev/null +++ b/Lang/JavaScript/Graph-colouring @@ -0,0 +1 @@ +../../Task/Graph-colouring/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Greedy-algorithm-for-Egyptian-fractions b/Lang/JavaScript/Greedy-algorithm-for-Egyptian-fractions new file mode 120000 index 0000000000..4b7a0299ee --- /dev/null +++ b/Lang/JavaScript/Greedy-algorithm-for-Egyptian-fractions @@ -0,0 +1 @@ +../../Task/Greedy-algorithm-for-Egyptian-fractions/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Halt-and-catch-fire b/Lang/JavaScript/Halt-and-catch-fire new file mode 120000 index 0000000000..34a6fcf7d2 --- /dev/null +++ b/Lang/JavaScript/Halt-and-catch-fire @@ -0,0 +1 @@ +../../Task/Halt-and-catch-fire/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Home-primes b/Lang/JavaScript/Home-primes new file mode 120000 index 0000000000..903d43b23e --- /dev/null +++ b/Lang/JavaScript/Home-primes @@ -0,0 +1 @@ +../../Task/Home-primes/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Horizontal-sundial-calculations b/Lang/JavaScript/Horizontal-sundial-calculations new file mode 120000 index 0000000000..854f95761b --- /dev/null +++ b/Lang/JavaScript/Horizontal-sundial-calculations @@ -0,0 +1 @@ +../../Task/Horizontal-sundial-calculations/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/ISBN13-check-digit b/Lang/JavaScript/ISBN13-check-digit new file mode 120000 index 0000000000..a76c26065c --- /dev/null +++ b/Lang/JavaScript/ISBN13-check-digit @@ -0,0 +1 @@ +../../Task/ISBN13-check-digit/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Isqrt-integer-square-root-of-X b/Lang/JavaScript/Isqrt-integer-square-root-of-X new file mode 120000 index 0000000000..7c262657f5 --- /dev/null +++ b/Lang/JavaScript/Isqrt-integer-square-root-of-X @@ -0,0 +1 @@ +../../Task/Isqrt-integer-square-root-of-X/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Jacobi-symbol b/Lang/JavaScript/Jacobi-symbol new file mode 120000 index 0000000000..7ca750b7ca --- /dev/null +++ b/Lang/JavaScript/Jacobi-symbol @@ -0,0 +1 @@ +../../Task/Jacobi-symbol/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Jaro-Winkler-distance b/Lang/JavaScript/Jaro-Winkler-distance new file mode 120000 index 0000000000..48d79ffb3b --- /dev/null +++ b/Lang/JavaScript/Jaro-Winkler-distance @@ -0,0 +1 @@ +../../Task/Jaro-Winkler-distance/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Jaro-similarity b/Lang/JavaScript/Jaro-similarity new file mode 120000 index 0000000000..72e11e0e2b --- /dev/null +++ b/Lang/JavaScript/Jaro-similarity @@ -0,0 +1 @@ +../../Task/Jaro-similarity/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Jordan-P-lya-numbers b/Lang/JavaScript/Jordan-P-lya-numbers new file mode 120000 index 0000000000..1c850674c3 --- /dev/null +++ b/Lang/JavaScript/Jordan-P-lya-numbers @@ -0,0 +1 @@ +../../Task/Jordan-P-lya-numbers/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/K-d-tree b/Lang/JavaScript/K-d-tree new file mode 120000 index 0000000000..f551f8aa55 --- /dev/null +++ b/Lang/JavaScript/K-d-tree @@ -0,0 +1 @@ +../../Task/K-d-tree/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Knuths-algorithm-S b/Lang/JavaScript/Knuths-algorithm-S new file mode 120000 index 0000000000..78ce9e9420 --- /dev/null +++ b/Lang/JavaScript/Knuths-algorithm-S @@ -0,0 +1 @@ +../../Task/Knuths-algorithm-S/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Knuths-power-tree b/Lang/JavaScript/Knuths-power-tree new file mode 120000 index 0000000000..65f212b8ef --- /dev/null +++ b/Lang/JavaScript/Knuths-power-tree @@ -0,0 +1 @@ +../../Task/Knuths-power-tree/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Kolakoski-sequence b/Lang/JavaScript/Kolakoski-sequence new file mode 120000 index 0000000000..eac78035ff --- /dev/null +++ b/Lang/JavaScript/Kolakoski-sequence @@ -0,0 +1 @@ +../../Task/Kolakoski-sequence/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Kosaraju b/Lang/JavaScript/Kosaraju new file mode 120000 index 0000000000..679452fdc1 --- /dev/null +++ b/Lang/JavaScript/Kosaraju @@ -0,0 +1 @@ +../../Task/Kosaraju/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Largest-number-divisible-by-its-digits b/Lang/JavaScript/Largest-number-divisible-by-its-digits new file mode 120000 index 0000000000..04fdf583a0 --- /dev/null +++ b/Lang/JavaScript/Largest-number-divisible-by-its-digits @@ -0,0 +1 @@ +../../Task/Largest-number-divisible-by-its-digits/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Largest-proper-divisor-of-n b/Lang/JavaScript/Largest-proper-divisor-of-n new file mode 120000 index 0000000000..3f1ca809f7 --- /dev/null +++ b/Lang/JavaScript/Largest-proper-divisor-of-n @@ -0,0 +1 @@ +../../Task/Largest-proper-divisor-of-n/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Levenshtein-distance-Alignment b/Lang/JavaScript/Levenshtein-distance-Alignment new file mode 120000 index 0000000000..fabac4db0b --- /dev/null +++ b/Lang/JavaScript/Levenshtein-distance-Alignment @@ -0,0 +1 @@ +../../Task/Levenshtein-distance-Alignment/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Linear-congruential-generator b/Lang/JavaScript/Linear-congruential-generator new file mode 120000 index 0000000000..9664d4ce1d --- /dev/null +++ b/Lang/JavaScript/Linear-congruential-generator @@ -0,0 +1 @@ +../../Task/Linear-congruential-generator/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Literals-Floating-point b/Lang/JavaScript/Literals-Floating-point new file mode 120000 index 0000000000..d4ebfbadf6 --- /dev/null +++ b/Lang/JavaScript/Literals-Floating-point @@ -0,0 +1 @@ +../../Task/Literals-Floating-point/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Long-literals-with-continuations b/Lang/JavaScript/Long-literals-with-continuations new file mode 120000 index 0000000000..51b7c2433b --- /dev/null +++ b/Lang/JavaScript/Long-literals-with-continuations @@ -0,0 +1 @@ +../../Task/Long-literals-with-continuations/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Loops-With-multiple-ranges b/Lang/JavaScript/Loops-With-multiple-ranges new file mode 120000 index 0000000000..0fe86f1b4e --- /dev/null +++ b/Lang/JavaScript/Loops-With-multiple-ranges @@ -0,0 +1 @@ +../../Task/Loops-With-multiple-ranges/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Loops-Wrong-ranges b/Lang/JavaScript/Loops-Wrong-ranges new file mode 120000 index 0000000000..285ca2bf4f --- /dev/null +++ b/Lang/JavaScript/Loops-Wrong-ranges @@ -0,0 +1 @@ +../../Task/Loops-Wrong-ranges/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Lychrel-numbers b/Lang/JavaScript/Lychrel-numbers new file mode 120000 index 0000000000..ddc0a3b2ae --- /dev/null +++ b/Lang/JavaScript/Lychrel-numbers @@ -0,0 +1 @@ +../../Task/Lychrel-numbers/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/M-bius-function b/Lang/JavaScript/M-bius-function new file mode 120000 index 0000000000..8b88e437b9 --- /dev/null +++ b/Lang/JavaScript/M-bius-function @@ -0,0 +1 @@ +../../Task/M-bius-function/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/MD5 b/Lang/JavaScript/MD5 new file mode 120000 index 0000000000..764b1e5dd2 --- /dev/null +++ b/Lang/JavaScript/MD5 @@ -0,0 +1 @@ +../../Task/MD5/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/MD5-Implementation b/Lang/JavaScript/MD5-Implementation new file mode 120000 index 0000000000..96da37623c --- /dev/null +++ b/Lang/JavaScript/MD5-Implementation @@ -0,0 +1 @@ +../../Task/MD5-Implementation/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Magic-constant b/Lang/JavaScript/Magic-constant new file mode 120000 index 0000000000..93ac503011 --- /dev/null +++ b/Lang/JavaScript/Magic-constant @@ -0,0 +1 @@ +../../Task/Magic-constant/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Memory-layout-of-a-data-structure b/Lang/JavaScript/Memory-layout-of-a-data-structure new file mode 120000 index 0000000000..40a22a351b --- /dev/null +++ b/Lang/JavaScript/Memory-layout-of-a-data-structure @@ -0,0 +1 @@ +../../Task/Memory-layout-of-a-data-structure/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Merge-and-aggregate-datasets b/Lang/JavaScript/Merge-and-aggregate-datasets new file mode 120000 index 0000000000..d1ec3fd3c7 --- /dev/null +++ b/Lang/JavaScript/Merge-and-aggregate-datasets @@ -0,0 +1 @@ +../../Task/Merge-and-aggregate-datasets/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Miller-Rabin-primality-test b/Lang/JavaScript/Miller-Rabin-primality-test deleted file mode 120000 index 41f625032e..0000000000 --- a/Lang/JavaScript/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Motzkin-numbers b/Lang/JavaScript/Motzkin-numbers new file mode 120000 index 0000000000..f887ca66ad --- /dev/null +++ b/Lang/JavaScript/Motzkin-numbers @@ -0,0 +1 @@ +../../Task/Motzkin-numbers/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Numeric-error-propagation b/Lang/JavaScript/Numeric-error-propagation new file mode 120000 index 0000000000..4c3115218f --- /dev/null +++ b/Lang/JavaScript/Numeric-error-propagation @@ -0,0 +1 @@ +../../Task/Numeric-error-propagation/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Numerical-integration b/Lang/JavaScript/Numerical-integration new file mode 120000 index 0000000000..b80325338d --- /dev/null +++ b/Lang/JavaScript/Numerical-integration @@ -0,0 +1 @@ +../../Task/Numerical-integration/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Old-lady-swallowed-a-fly b/Lang/JavaScript/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..a49e302025 --- /dev/null +++ b/Lang/JavaScript/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Own-digits-power-sum b/Lang/JavaScript/Own-digits-power-sum new file mode 120000 index 0000000000..af2067363a --- /dev/null +++ b/Lang/JavaScript/Own-digits-power-sum @@ -0,0 +1 @@ +../../Task/Own-digits-power-sum/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/P-Adic-numbers-basic b/Lang/JavaScript/P-Adic-numbers-basic new file mode 120000 index 0000000000..8430626fe6 --- /dev/null +++ b/Lang/JavaScript/P-Adic-numbers-basic @@ -0,0 +1 @@ +../../Task/P-Adic-numbers-basic/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/P-Adic-square-roots b/Lang/JavaScript/P-Adic-square-roots new file mode 120000 index 0000000000..dc1614d80a --- /dev/null +++ b/Lang/JavaScript/P-Adic-square-roots @@ -0,0 +1 @@ +../../Task/P-Adic-square-roots/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/P-value-correction b/Lang/JavaScript/P-value-correction new file mode 120000 index 0000000000..0bb6d9d877 --- /dev/null +++ b/Lang/JavaScript/P-value-correction @@ -0,0 +1 @@ +../../Task/P-value-correction/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Palindromic-gapful-numbers b/Lang/JavaScript/Palindromic-gapful-numbers new file mode 120000 index 0000000000..3ea405216b --- /dev/null +++ b/Lang/JavaScript/Palindromic-gapful-numbers @@ -0,0 +1 @@ +../../Task/Palindromic-gapful-numbers/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Pancake-numbers b/Lang/JavaScript/Pancake-numbers new file mode 120000 index 0000000000..6f2eb315df --- /dev/null +++ b/Lang/JavaScript/Pancake-numbers @@ -0,0 +1 @@ +../../Task/Pancake-numbers/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Paraffins b/Lang/JavaScript/Paraffins new file mode 120000 index 0000000000..583d8a86f5 --- /dev/null +++ b/Lang/JavaScript/Paraffins @@ -0,0 +1 @@ +../../Task/Paraffins/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Parse-an-IP-Address b/Lang/JavaScript/Parse-an-IP-Address new file mode 120000 index 0000000000..5981d2ba9f --- /dev/null +++ b/Lang/JavaScript/Parse-an-IP-Address @@ -0,0 +1 @@ +../../Task/Parse-an-IP-Address/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Pascals-triangle-Puzzle b/Lang/JavaScript/Pascals-triangle-Puzzle new file mode 120000 index 0000000000..2acf8cdb4d --- /dev/null +++ b/Lang/JavaScript/Pascals-triangle-Puzzle @@ -0,0 +1 @@ +../../Task/Pascals-triangle-Puzzle/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Percolation-Bond-percolation b/Lang/JavaScript/Percolation-Bond-percolation new file mode 120000 index 0000000000..b784faa7b0 --- /dev/null +++ b/Lang/JavaScript/Percolation-Bond-percolation @@ -0,0 +1 @@ +../../Task/Percolation-Bond-percolation/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Percolation-Mean-cluster-density b/Lang/JavaScript/Percolation-Mean-cluster-density new file mode 120000 index 0000000000..8cad881ab4 --- /dev/null +++ b/Lang/JavaScript/Percolation-Mean-cluster-density @@ -0,0 +1 @@ +../../Task/Percolation-Mean-cluster-density/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Percolation-Mean-run-density b/Lang/JavaScript/Percolation-Mean-run-density new file mode 120000 index 0000000000..6c804e3579 --- /dev/null +++ b/Lang/JavaScript/Percolation-Mean-run-density @@ -0,0 +1 @@ +../../Task/Percolation-Mean-run-density/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Percolation-Site-percolation b/Lang/JavaScript/Percolation-Site-percolation new file mode 120000 index 0000000000..3d8672383d --- /dev/null +++ b/Lang/JavaScript/Percolation-Site-percolation @@ -0,0 +1 @@ +../../Task/Percolation-Site-percolation/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Periodic-table b/Lang/JavaScript/Periodic-table new file mode 120000 index 0000000000..3252400859 --- /dev/null +++ b/Lang/JavaScript/Periodic-table @@ -0,0 +1 @@ +../../Task/Periodic-table/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Perlin-noise b/Lang/JavaScript/Perlin-noise new file mode 120000 index 0000000000..d4cfceb70d --- /dev/null +++ b/Lang/JavaScript/Perlin-noise @@ -0,0 +1 @@ +../../Task/Perlin-noise/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Playfair-cipher b/Lang/JavaScript/Playfair-cipher new file mode 120000 index 0000000000..e94d50f327 --- /dev/null +++ b/Lang/JavaScript/Playfair-cipher @@ -0,0 +1 @@ +../../Task/Playfair-cipher/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Priority-queue b/Lang/JavaScript/Priority-queue new file mode 120000 index 0000000000..01d2cd2765 --- /dev/null +++ b/Lang/JavaScript/Priority-queue @@ -0,0 +1 @@ +../../Task/Priority-queue/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Pseudo-random-numbers-Middle-square-method b/Lang/JavaScript/Pseudo-random-numbers-Middle-square-method new file mode 120000 index 0000000000..670dfa6542 --- /dev/null +++ b/Lang/JavaScript/Pseudo-random-numbers-Middle-square-method @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-Middle-square-method/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Pseudo-random-numbers-PCG32 b/Lang/JavaScript/Pseudo-random-numbers-PCG32 new file mode 120000 index 0000000000..689b737182 --- /dev/null +++ b/Lang/JavaScript/Pseudo-random-numbers-PCG32 @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-PCG32/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Pseudo-random-numbers-Splitmix64 b/Lang/JavaScript/Pseudo-random-numbers-Splitmix64 new file mode 120000 index 0000000000..e21d263f6d --- /dev/null +++ b/Lang/JavaScript/Pseudo-random-numbers-Splitmix64 @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-Splitmix64/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Pseudo-random-numbers-Xorshift-star b/Lang/JavaScript/Pseudo-random-numbers-Xorshift-star new file mode 120000 index 0000000000..40211cc2a7 --- /dev/null +++ b/Lang/JavaScript/Pseudo-random-numbers-Xorshift-star @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-Xorshift-star/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/QR-decomposition b/Lang/JavaScript/QR-decomposition new file mode 120000 index 0000000000..0913aa7d30 --- /dev/null +++ b/Lang/JavaScript/QR-decomposition @@ -0,0 +1 @@ +../../Task/QR-decomposition/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Quaternion-type b/Lang/JavaScript/Quaternion-type deleted file mode 120000 index e2a6535526..0000000000 --- a/Lang/JavaScript/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/RIPEMD-160 b/Lang/JavaScript/RIPEMD-160 new file mode 120000 index 0000000000..aa85f54790 --- /dev/null +++ b/Lang/JavaScript/RIPEMD-160 @@ -0,0 +1 @@ +../../Task/RIPEMD-160/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Repeat b/Lang/JavaScript/Repeat new file mode 120000 index 0000000000..e8bb71f4ce --- /dev/null +++ b/Lang/JavaScript/Repeat @@ -0,0 +1 @@ +../../Task/Repeat/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/SHA-1 b/Lang/JavaScript/SHA-1 new file mode 120000 index 0000000000..2773e9c63c --- /dev/null +++ b/Lang/JavaScript/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/SHA-256-Merkle-tree b/Lang/JavaScript/SHA-256-Merkle-tree new file mode 120000 index 0000000000..0c2b665899 --- /dev/null +++ b/Lang/JavaScript/SHA-256-Merkle-tree @@ -0,0 +1 @@ +../../Task/SHA-256-Merkle-tree/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Set-puzzle b/Lang/JavaScript/Set-puzzle new file mode 120000 index 0000000000..22b0bad552 --- /dev/null +++ b/Lang/JavaScript/Set-puzzle @@ -0,0 +1 @@ +../../Task/Set-puzzle/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Shortest-common-supersequence b/Lang/JavaScript/Shortest-common-supersequence new file mode 120000 index 0000000000..4e107e522e --- /dev/null +++ b/Lang/JavaScript/Shortest-common-supersequence @@ -0,0 +1 @@ +../../Task/Shortest-common-supersequence/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Sisyphus-sequence b/Lang/JavaScript/Sisyphus-sequence new file mode 120000 index 0000000000..67b00353f0 --- /dev/null +++ b/Lang/JavaScript/Sisyphus-sequence @@ -0,0 +1 @@ +../../Task/Sisyphus-sequence/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Smarandache-prime-digital-sequence b/Lang/JavaScript/Smarandache-prime-digital-sequence new file mode 120000 index 0000000000..14cb702228 --- /dev/null +++ b/Lang/JavaScript/Smarandache-prime-digital-sequence @@ -0,0 +1 @@ +../../Task/Smarandache-prime-digital-sequence/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Sokoban b/Lang/JavaScript/Sokoban new file mode 120000 index 0000000000..3ab86467bd --- /dev/null +++ b/Lang/JavaScript/Sokoban @@ -0,0 +1 @@ +../../Task/Sokoban/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Solve-a-Hidato-puzzle b/Lang/JavaScript/Solve-a-Hidato-puzzle new file mode 120000 index 0000000000..3e3c25cd7c --- /dev/null +++ b/Lang/JavaScript/Solve-a-Hidato-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hidato-puzzle/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Solve-a-Hopido-puzzle b/Lang/JavaScript/Solve-a-Hopido-puzzle new file mode 120000 index 0000000000..aea3983b76 --- /dev/null +++ b/Lang/JavaScript/Solve-a-Hopido-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hopido-puzzle/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Solve-a-Numbrix-puzzle b/Lang/JavaScript/Solve-a-Numbrix-puzzle new file mode 120000 index 0000000000..43202401f9 --- /dev/null +++ b/Lang/JavaScript/Solve-a-Numbrix-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Numbrix-puzzle/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Sort-numbers-lexicographically b/Lang/JavaScript/Sort-numbers-lexicographically new file mode 120000 index 0000000000..0350e5ac3a --- /dev/null +++ b/Lang/JavaScript/Sort-numbers-lexicographically @@ -0,0 +1 @@ +../../Task/Sort-numbers-lexicographically/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Sorting-algorithms-Radix-sort b/Lang/JavaScript/Sorting-algorithms-Radix-sort new file mode 120000 index 0000000000..0d4b9cb23d --- /dev/null +++ b/Lang/JavaScript/Sorting-algorithms-Radix-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Radix-sort/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Spelling-of-ordinal-numbers b/Lang/JavaScript/Spelling-of-ordinal-numbers new file mode 120000 index 0000000000..5ed638cc81 --- /dev/null +++ b/Lang/JavaScript/Spelling-of-ordinal-numbers @@ -0,0 +1 @@ +../../Task/Spelling-of-ordinal-numbers/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Square-free-integers b/Lang/JavaScript/Square-free-integers new file mode 120000 index 0000000000..5f495f4fd4 --- /dev/null +++ b/Lang/JavaScript/Square-free-integers @@ -0,0 +1 @@ +../../Task/Square-free-integers/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/State-name-puzzle b/Lang/JavaScript/State-name-puzzle new file mode 120000 index 0000000000..12f667dc4c --- /dev/null +++ b/Lang/JavaScript/State-name-puzzle @@ -0,0 +1 @@ +../../Task/State-name-puzzle/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Steffensens-method b/Lang/JavaScript/Steffensens-method new file mode 120000 index 0000000000..12c21e29e2 --- /dev/null +++ b/Lang/JavaScript/Steffensens-method @@ -0,0 +1 @@ +../../Task/Steffensens-method/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Strassens-algorithm b/Lang/JavaScript/Strassens-algorithm new file mode 120000 index 0000000000..f4d0497694 --- /dev/null +++ b/Lang/JavaScript/Strassens-algorithm @@ -0,0 +1 @@ +../../Task/Strassens-algorithm/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Stream-merge b/Lang/JavaScript/Stream-merge new file mode 120000 index 0000000000..cf7057043d --- /dev/null +++ b/Lang/JavaScript/Stream-merge @@ -0,0 +1 @@ +../../Task/Stream-merge/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Subleq b/Lang/JavaScript/Subleq new file mode 120000 index 0000000000..19f1606c88 --- /dev/null +++ b/Lang/JavaScript/Subleq @@ -0,0 +1 @@ +../../Task/Subleq/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Substitution-cipher b/Lang/JavaScript/Substitution-cipher new file mode 120000 index 0000000000..e8fd969b4a --- /dev/null +++ b/Lang/JavaScript/Substitution-cipher @@ -0,0 +1 @@ +../../Task/Substitution-cipher/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Superpermutation-minimisation b/Lang/JavaScript/Superpermutation-minimisation new file mode 120000 index 0000000000..a257c8e7e7 --- /dev/null +++ b/Lang/JavaScript/Superpermutation-minimisation @@ -0,0 +1 @@ +../../Task/Superpermutation-minimisation/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Sylvesters-sequence b/Lang/JavaScript/Sylvesters-sequence new file mode 120000 index 0000000000..472599a8bf --- /dev/null +++ b/Lang/JavaScript/Sylvesters-sequence @@ -0,0 +1 @@ +../../Task/Sylvesters-sequence/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Tarjan b/Lang/JavaScript/Tarjan new file mode 120000 index 0000000000..c299c7aebb --- /dev/null +++ b/Lang/JavaScript/Tarjan @@ -0,0 +1 @@ +../../Task/Tarjan/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Tau-number b/Lang/JavaScript/Tau-number new file mode 120000 index 0000000000..ff78310d47 --- /dev/null +++ b/Lang/JavaScript/Tau-number @@ -0,0 +1 @@ +../../Task/Tau-number/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Thieles-interpolation-formula b/Lang/JavaScript/Thieles-interpolation-formula new file mode 120000 index 0000000000..4aa6c84146 --- /dev/null +++ b/Lang/JavaScript/Thieles-interpolation-formula @@ -0,0 +1 @@ +../../Task/Thieles-interpolation-formula/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Tonelli-Shanks-algorithm b/Lang/JavaScript/Tonelli-Shanks-algorithm new file mode 120000 index 0000000000..f646a271d1 --- /dev/null +++ b/Lang/JavaScript/Tonelli-Shanks-algorithm @@ -0,0 +1 @@ +../../Task/Tonelli-Shanks-algorithm/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Topswops b/Lang/JavaScript/Topswops new file mode 120000 index 0000000000..cffdbd99df --- /dev/null +++ b/Lang/JavaScript/Topswops @@ -0,0 +1 @@ +../../Task/Topswops/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Transliterate-English-text-using-the-Greek-alphabet b/Lang/JavaScript/Transliterate-English-text-using-the-Greek-alphabet new file mode 120000 index 0000000000..90b7eb9492 --- /dev/null +++ b/Lang/JavaScript/Transliterate-English-text-using-the-Greek-alphabet @@ -0,0 +1 @@ +../../Task/Transliterate-English-text-using-the-Greek-alphabet/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Twos-complement b/Lang/JavaScript/Twos-complement new file mode 120000 index 0000000000..d0b1730478 --- /dev/null +++ b/Lang/JavaScript/Twos-complement @@ -0,0 +1 @@ +../../Task/Twos-complement/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Ukkonen-s-suffix-tree-construction b/Lang/JavaScript/Ukkonen-s-suffix-tree-construction new file mode 120000 index 0000000000..7a4d0832f5 --- /dev/null +++ b/Lang/JavaScript/Ukkonen-s-suffix-tree-construction @@ -0,0 +1 @@ +../../Task/Ukkonen-s-suffix-tree-construction/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Unbias-a-random-generator b/Lang/JavaScript/Unbias-a-random-generator new file mode 120000 index 0000000000..1e801c1fa5 --- /dev/null +++ b/Lang/JavaScript/Unbias-a-random-generator @@ -0,0 +1 @@ +../../Task/Unbias-a-random-generator/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Unicode-strings b/Lang/JavaScript/Unicode-strings new file mode 120000 index 0000000000..ad6c128bef --- /dev/null +++ b/Lang/JavaScript/Unicode-strings @@ -0,0 +1 @@ +../../Task/Unicode-strings/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Van-der-Corput-sequence b/Lang/JavaScript/Van-der-Corput-sequence new file mode 120000 index 0000000000..41397b68df --- /dev/null +++ b/Lang/JavaScript/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Vector b/Lang/JavaScript/Vector new file mode 120000 index 0000000000..fec6065641 --- /dev/null +++ b/Lang/JavaScript/Vector @@ -0,0 +1 @@ +../../Task/Vector/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Verhoeff-algorithm b/Lang/JavaScript/Verhoeff-algorithm new file mode 120000 index 0000000000..cd27def09b --- /dev/null +++ b/Lang/JavaScript/Verhoeff-algorithm @@ -0,0 +1 @@ +../../Task/Verhoeff-algorithm/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Vigen-re-cipher-Cryptanalysis b/Lang/JavaScript/Vigen-re-cipher-Cryptanalysis new file mode 120000 index 0000000000..53c004e91c --- /dev/null +++ b/Lang/JavaScript/Vigen-re-cipher-Cryptanalysis @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher-Cryptanalysis/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Vogels-approximation-method b/Lang/JavaScript/Vogels-approximation-method new file mode 120000 index 0000000000..72693f1daa --- /dev/null +++ b/Lang/JavaScript/Vogels-approximation-method @@ -0,0 +1 @@ +../../Task/Vogels-approximation-method/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Word-ladder b/Lang/JavaScript/Word-ladder new file mode 120000 index 0000000000..f78d94e145 --- /dev/null +++ b/Lang/JavaScript/Word-ladder @@ -0,0 +1 @@ +../../Task/Word-ladder/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Wordiff b/Lang/JavaScript/Wordiff new file mode 120000 index 0000000000..18ec352da6 --- /dev/null +++ b/Lang/JavaScript/Wordiff @@ -0,0 +1 @@ +../../Task/Wordiff/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Zebra-puzzle b/Lang/JavaScript/Zebra-puzzle new file mode 120000 index 0000000000..5c531004b3 --- /dev/null +++ b/Lang/JavaScript/Zebra-puzzle @@ -0,0 +1 @@ +../../Task/Zebra-puzzle/JavaScript \ No newline at end of file diff --git a/Lang/Joy/Case-sensitivity-of-identifiers b/Lang/Joy/Case-sensitivity-of-identifiers new file mode 120000 index 0000000000..e8f5c2c1db --- /dev/null +++ b/Lang/Joy/Case-sensitivity-of-identifiers @@ -0,0 +1 @@ +../../Task/Case-sensitivity-of-identifiers/Joy \ No newline at end of file diff --git a/Lang/Joy/Read-a-file-line-by-line b/Lang/Joy/Read-a-file-line-by-line new file mode 120000 index 0000000000..9985d0bc9c --- /dev/null +++ b/Lang/Joy/Read-a-file-line-by-line @@ -0,0 +1 @@ +../../Task/Read-a-file-line-by-line/Joy \ No newline at end of file diff --git a/Lang/Joy/Sort-an-integer-array b/Lang/Joy/Sort-an-integer-array new file mode 120000 index 0000000000..91921cd08e --- /dev/null +++ b/Lang/Joy/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Joy \ No newline at end of file diff --git a/Lang/Joy/Unicode-variable-names b/Lang/Joy/Unicode-variable-names new file mode 120000 index 0000000000..b7f93a76ef --- /dev/null +++ b/Lang/Joy/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/Joy \ No newline at end of file diff --git a/Lang/Jq/00-LANG.txt b/Lang/Jq/00-LANG.txt index 3eba7f05c0..a2d6626be7 100644 --- a/Lang/Jq/00-LANG.txt +++ b/Lang/Jq/00-LANG.txt @@ -7,9 +7,14 @@ 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/bitwise.jq|bitwise.jq]] - bit streams, bit arrays, and integers * [[: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/rational.jq|rational.jq]] - rational numbers + +* [[:Category:Jq/Date.jq|Date.jq]] - Gregorian calendar from the year 1 +* [[:Category:Jq/MRG32k3a.jq|MRG32k3a.jq]] - MRG32k3a Combined Recursive Pseudo-Random Number Generator * [[:Category:Jq/RealSet.jq|RealSet.jq]] - Union of finite real intervals ==Todo== diff --git a/Lang/Jq/15-puzzle-game b/Lang/Jq/15-puzzle-game new file mode 120000 index 0000000000..9c065d8ccc --- /dev/null +++ b/Lang/Jq/15-puzzle-game @@ -0,0 +1 @@ +../../Task/15-puzzle-game/Jq \ No newline at end of file diff --git a/Lang/Jq/15-puzzle-solver b/Lang/Jq/15-puzzle-solver new file mode 120000 index 0000000000..e822e3d4e7 --- /dev/null +++ b/Lang/Jq/15-puzzle-solver @@ -0,0 +1 @@ +../../Task/15-puzzle-solver/Jq \ No newline at end of file diff --git a/Lang/Jq/2048 b/Lang/Jq/2048 new file mode 120000 index 0000000000..e78d154a28 --- /dev/null +++ b/Lang/Jq/2048 @@ -0,0 +1 @@ +../../Task/2048/Jq \ No newline at end of file diff --git a/Lang/Jq/24-game b/Lang/Jq/24-game new file mode 120000 index 0000000000..1db8a29eb4 --- /dev/null +++ b/Lang/Jq/24-game @@ -0,0 +1 @@ +../../Task/24-game/Jq \ No newline at end of file diff --git a/Lang/Jq/Averages-Simple-moving-average b/Lang/Jq/Averages-Simple-moving-average new file mode 120000 index 0000000000..7c27d5bee2 --- /dev/null +++ b/Lang/Jq/Averages-Simple-moving-average @@ -0,0 +1 @@ +../../Task/Averages-Simple-moving-average/Jq \ No newline at end of file diff --git a/Lang/Jq/Bioinformatics-base-count b/Lang/Jq/Bioinformatics-base-count deleted file mode 120000 index 87df406d18..0000000000 --- a/Lang/Jq/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Jq \ No newline at end of file diff --git a/Lang/Jq/Bitwise-operations b/Lang/Jq/Bitwise-operations new file mode 120000 index 0000000000..eff5a2f904 --- /dev/null +++ b/Lang/Jq/Bitwise-operations @@ -0,0 +1 @@ +../../Task/Bitwise-operations/Jq \ No newline at end of file diff --git a/Lang/Jq/CRC-32 b/Lang/Jq/CRC-32 new file mode 120000 index 0000000000..800ab8f0ad --- /dev/null +++ b/Lang/Jq/CRC-32 @@ -0,0 +1 @@ +../../Task/CRC-32/Jq \ No newline at end of file diff --git a/Lang/Jq/Chaocipher b/Lang/Jq/Chaocipher new file mode 120000 index 0000000000..3383992151 --- /dev/null +++ b/Lang/Jq/Chaocipher @@ -0,0 +1 @@ +../../Task/Chaocipher/Jq \ No newline at end of file diff --git a/Lang/Jq/Continued-fraction-Arithmetic-Construct-from-rational-number b/Lang/Jq/Continued-fraction-Arithmetic-Construct-from-rational-number new file mode 120000 index 0000000000..90c56c3b3a --- /dev/null +++ b/Lang/Jq/Continued-fraction-Arithmetic-Construct-from-rational-number @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Jq \ No newline at end of file diff --git a/Lang/Jq/Deconvolution-1D b/Lang/Jq/Deconvolution-1D new file mode 120000 index 0000000000..4f872c1005 --- /dev/null +++ b/Lang/Jq/Deconvolution-1D @@ -0,0 +1 @@ +../../Task/Deconvolution-1D/Jq \ No newline at end of file diff --git a/Lang/Jq/Display-an-outline-as-a-nested-table b/Lang/Jq/Display-an-outline-as-a-nested-table new file mode 120000 index 0000000000..37137659b6 --- /dev/null +++ b/Lang/Jq/Display-an-outline-as-a-nested-table @@ -0,0 +1 @@ +../../Task/Display-an-outline-as-a-nested-table/Jq \ No newline at end of file diff --git a/Lang/Jq/Draw-a-cuboid b/Lang/Jq/Draw-a-cuboid new file mode 120000 index 0000000000..2af657c230 --- /dev/null +++ b/Lang/Jq/Draw-a-cuboid @@ -0,0 +1 @@ +../../Task/Draw-a-cuboid/Jq \ No newline at end of file diff --git a/Lang/Jq/Entropy-Narcissist b/Lang/Jq/Entropy-Narcissist new file mode 120000 index 0000000000..f142d7e681 --- /dev/null +++ b/Lang/Jq/Entropy-Narcissist @@ -0,0 +1 @@ +../../Task/Entropy-Narcissist/Jq \ No newline at end of file diff --git a/Lang/Jq/Factors-of-a-Mersenne-number b/Lang/Jq/Factors-of-a-Mersenne-number new file mode 120000 index 0000000000..e34af6567d --- /dev/null +++ b/Lang/Jq/Factors-of-a-Mersenne-number @@ -0,0 +1 @@ +../../Task/Factors-of-a-Mersenne-number/Jq \ No newline at end of file diff --git a/Lang/Jq/File-size-distribution b/Lang/Jq/File-size-distribution new file mode 120000 index 0000000000..d42e94402e --- /dev/null +++ b/Lang/Jq/File-size-distribution @@ -0,0 +1 @@ +../../Task/File-size-distribution/Jq \ No newline at end of file diff --git a/Lang/Jq/Find-Chess960-starting-position-identifier b/Lang/Jq/Find-Chess960-starting-position-identifier new file mode 120000 index 0000000000..ea292cff65 --- /dev/null +++ b/Lang/Jq/Find-Chess960-starting-position-identifier @@ -0,0 +1 @@ +../../Task/Find-Chess960-starting-position-identifier/Jq \ No newline at end of file diff --git a/Lang/Jq/Find-duplicate-files b/Lang/Jq/Find-duplicate-files new file mode 120000 index 0000000000..289f08d02f --- /dev/null +++ b/Lang/Jq/Find-duplicate-files @@ -0,0 +1 @@ +../../Task/Find-duplicate-files/Jq \ No newline at end of file diff --git a/Lang/Jq/French-Republican-calendar b/Lang/Jq/French-Republican-calendar new file mode 120000 index 0000000000..d495d14d71 --- /dev/null +++ b/Lang/Jq/French-Republican-calendar @@ -0,0 +1 @@ +../../Task/French-Republican-calendar/Jq \ No newline at end of file diff --git a/Lang/Jq/Generate-random-chess-position b/Lang/Jq/Generate-random-chess-position new file mode 120000 index 0000000000..a6ff2b1df0 --- /dev/null +++ b/Lang/Jq/Generate-random-chess-position @@ -0,0 +1 @@ +../../Task/Generate-random-chess-position/Jq \ No newline at end of file diff --git a/Lang/Jq/Giuga-numbers b/Lang/Jq/Giuga-numbers new file mode 120000 index 0000000000..b5850902a3 --- /dev/null +++ b/Lang/Jq/Giuga-numbers @@ -0,0 +1 @@ +../../Task/Giuga-numbers/Jq \ No newline at end of file diff --git a/Lang/Jq/Graph-colouring b/Lang/Jq/Graph-colouring new file mode 120000 index 0000000000..07b418f3a3 --- /dev/null +++ b/Lang/Jq/Graph-colouring @@ -0,0 +1 @@ +../../Task/Graph-colouring/Jq \ No newline at end of file diff --git a/Lang/Jq/Introspection b/Lang/Jq/Introspection new file mode 120000 index 0000000000..cdb6f22cc1 --- /dev/null +++ b/Lang/Jq/Introspection @@ -0,0 +1 @@ +../../Task/Introspection/Jq \ No newline at end of file diff --git a/Lang/Jq/Knights-tour b/Lang/Jq/Knights-tour new file mode 120000 index 0000000000..ca47275558 --- /dev/null +++ b/Lang/Jq/Knights-tour @@ -0,0 +1 @@ +../../Task/Knights-tour/Jq \ No newline at end of file diff --git a/Lang/Jq/Levenshtein-distance-Alignment b/Lang/Jq/Levenshtein-distance-Alignment new file mode 120000 index 0000000000..b331da38ff --- /dev/null +++ b/Lang/Jq/Levenshtein-distance-Alignment @@ -0,0 +1 @@ +../../Task/Levenshtein-distance-Alignment/Jq \ No newline at end of file diff --git a/Lang/Jq/Mayan-calendar b/Lang/Jq/Mayan-calendar new file mode 120000 index 0000000000..aa0964c1d8 --- /dev/null +++ b/Lang/Jq/Mayan-calendar @@ -0,0 +1 @@ +../../Task/Mayan-calendar/Jq \ No newline at end of file diff --git a/Lang/Jq/Mind-boggling-card-trick b/Lang/Jq/Mind-boggling-card-trick new file mode 120000 index 0000000000..11a1e6dd3d --- /dev/null +++ b/Lang/Jq/Mind-boggling-card-trick @@ -0,0 +1 @@ +../../Task/Mind-boggling-card-trick/Jq \ No newline at end of file diff --git a/Lang/Jq/Minimal-steps-down-to-1 b/Lang/Jq/Minimal-steps-down-to-1 new file mode 120000 index 0000000000..d05488db25 --- /dev/null +++ b/Lang/Jq/Minimal-steps-down-to-1 @@ -0,0 +1 @@ +../../Task/Minimal-steps-down-to-1/Jq \ No newline at end of file diff --git a/Lang/Jq/Modified-random-distribution b/Lang/Jq/Modified-random-distribution new file mode 120000 index 0000000000..5585f4b8dd --- /dev/null +++ b/Lang/Jq/Modified-random-distribution @@ -0,0 +1 @@ +../../Task/Modified-random-distribution/Jq \ No newline at end of file diff --git a/Lang/Jq/Multiplicative-order b/Lang/Jq/Multiplicative-order new file mode 120000 index 0000000000..72c4d667a9 --- /dev/null +++ b/Lang/Jq/Multiplicative-order @@ -0,0 +1 @@ +../../Task/Multiplicative-order/Jq \ No newline at end of file diff --git a/Lang/Jq/Nonoblock b/Lang/Jq/Nonoblock new file mode 120000 index 0000000000..f2323057e5 --- /dev/null +++ b/Lang/Jq/Nonoblock @@ -0,0 +1 @@ +../../Task/Nonoblock/Jq \ No newline at end of file diff --git a/Lang/Jq/Nonogram-solver b/Lang/Jq/Nonogram-solver new file mode 120000 index 0000000000..2ae5949d16 --- /dev/null +++ b/Lang/Jq/Nonogram-solver @@ -0,0 +1 @@ +../../Task/Nonogram-solver/Jq \ No newline at end of file diff --git a/Lang/Jq/P-value-correction b/Lang/Jq/P-value-correction new file mode 120000 index 0000000000..4685fd057d --- /dev/null +++ b/Lang/Jq/P-value-correction @@ -0,0 +1 @@ +../../Task/P-value-correction/Jq \ No newline at end of file diff --git a/Lang/Jq/Palindromic-gapful-numbers b/Lang/Jq/Palindromic-gapful-numbers new file mode 120000 index 0000000000..3f1d4b0a65 --- /dev/null +++ b/Lang/Jq/Palindromic-gapful-numbers @@ -0,0 +1 @@ +../../Task/Palindromic-gapful-numbers/Jq \ No newline at end of file diff --git a/Lang/Jq/Pancake-numbers b/Lang/Jq/Pancake-numbers new file mode 120000 index 0000000000..7c0b6487cc --- /dev/null +++ b/Lang/Jq/Pancake-numbers @@ -0,0 +1 @@ +../../Task/Pancake-numbers/Jq \ No newline at end of file diff --git a/Lang/Jq/Peaceful-chess-queen-armies b/Lang/Jq/Peaceful-chess-queen-armies new file mode 120000 index 0000000000..7c675a3306 --- /dev/null +++ b/Lang/Jq/Peaceful-chess-queen-armies @@ -0,0 +1 @@ +../../Task/Peaceful-chess-queen-armies/Jq \ No newline at end of file diff --git a/Lang/Jq/Pentomino-tiling b/Lang/Jq/Pentomino-tiling new file mode 120000 index 0000000000..cce133df04 --- /dev/null +++ b/Lang/Jq/Pentomino-tiling @@ -0,0 +1 @@ +../../Task/Pentomino-tiling/Jq \ No newline at end of file diff --git a/Lang/Jq/Perlin-noise b/Lang/Jq/Perlin-noise new file mode 120000 index 0000000000..eb52c317a2 --- /dev/null +++ b/Lang/Jq/Perlin-noise @@ -0,0 +1 @@ +../../Task/Perlin-noise/Jq \ No newline at end of file diff --git a/Lang/Jq/Pisano-period b/Lang/Jq/Pisano-period new file mode 120000 index 0000000000..223468a26a --- /dev/null +++ b/Lang/Jq/Pisano-period @@ -0,0 +1 @@ +../../Task/Pisano-period/Jq \ No newline at end of file diff --git a/Lang/Jq/Poker-hand-analyser b/Lang/Jq/Poker-hand-analyser new file mode 120000 index 0000000000..fd9738ce61 --- /dev/null +++ b/Lang/Jq/Poker-hand-analyser @@ -0,0 +1 @@ +../../Task/Poker-hand-analyser/Jq \ No newline at end of file diff --git a/Lang/Jq/Polynomial-regression b/Lang/Jq/Polynomial-regression new file mode 120000 index 0000000000..56985e2ba4 --- /dev/null +++ b/Lang/Jq/Polynomial-regression @@ -0,0 +1 @@ +../../Task/Polynomial-regression/Jq \ No newline at end of file diff --git a/Lang/Jq/Prime-numbers-whose-neighboring-pairs-are-tetraprimes b/Lang/Jq/Prime-numbers-whose-neighboring-pairs-are-tetraprimes new file mode 120000 index 0000000000..e1fd0d226c --- /dev/null +++ b/Lang/Jq/Prime-numbers-whose-neighboring-pairs-are-tetraprimes @@ -0,0 +1 @@ +../../Task/Prime-numbers-whose-neighboring-pairs-are-tetraprimes/Jq \ No newline at end of file diff --git a/Lang/Jq/Pseudo-random-numbers-Combined-recursive-generator-MRG32k3a b/Lang/Jq/Pseudo-random-numbers-Combined-recursive-generator-MRG32k3a new file mode 120000 index 0000000000..8a1fa69d52 --- /dev/null +++ b/Lang/Jq/Pseudo-random-numbers-Combined-recursive-generator-MRG32k3a @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-Combined-recursive-generator-MRG32k3a/Jq \ No newline at end of file diff --git a/Lang/Jq/Pseudo-random-numbers-PCG32 b/Lang/Jq/Pseudo-random-numbers-PCG32 new file mode 120000 index 0000000000..c80dea5d5d --- /dev/null +++ b/Lang/Jq/Pseudo-random-numbers-PCG32 @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-PCG32/Jq \ No newline at end of file diff --git a/Lang/Jq/Pseudo-random-numbers-Xorshift-star b/Lang/Jq/Pseudo-random-numbers-Xorshift-star new file mode 120000 index 0000000000..54ff010417 --- /dev/null +++ b/Lang/Jq/Pseudo-random-numbers-Xorshift-star @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-Xorshift-star/Jq \ No newline at end of file diff --git a/Lang/Jq/Quaternion-type b/Lang/Jq/Quaternion-type deleted file mode 120000 index 36df977f17..0000000000 --- a/Lang/Jq/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Jq \ No newline at end of file diff --git a/Lang/Jq/Ramer-Douglas-Peucker-line-simplification b/Lang/Jq/Ramer-Douglas-Peucker-line-simplification new file mode 120000 index 0000000000..2692c011c6 --- /dev/null +++ b/Lang/Jq/Ramer-Douglas-Peucker-line-simplification @@ -0,0 +1 @@ +../../Task/Ramer-Douglas-Peucker-line-simplification/Jq \ No newline at end of file diff --git a/Lang/Jq/Random-sentence-from-book b/Lang/Jq/Random-sentence-from-book new file mode 120000 index 0000000000..677f7ffdcc --- /dev/null +++ b/Lang/Jq/Random-sentence-from-book @@ -0,0 +1 @@ +../../Task/Random-sentence-from-book/Jq \ No newline at end of file diff --git a/Lang/Jq/Rosetta-Code-Rank-languages-by-number-of-users b/Lang/Jq/Rosetta-Code-Rank-languages-by-number-of-users new file mode 120000 index 0000000000..41c301e751 --- /dev/null +++ b/Lang/Jq/Rosetta-Code-Rank-languages-by-number-of-users @@ -0,0 +1 @@ +../../Task/Rosetta-Code-Rank-languages-by-number-of-users/Jq \ No newline at end of file diff --git a/Lang/Jq/Set-puzzle b/Lang/Jq/Set-puzzle new file mode 120000 index 0000000000..4d4860ff33 --- /dev/null +++ b/Lang/Jq/Set-puzzle @@ -0,0 +1 @@ +../../Task/Set-puzzle/Jq \ No newline at end of file diff --git a/Lang/Jq/Set-right-adjacent-bits b/Lang/Jq/Set-right-adjacent-bits new file mode 120000 index 0000000000..74d85af7c9 --- /dev/null +++ b/Lang/Jq/Set-right-adjacent-bits @@ -0,0 +1 @@ +../../Task/Set-right-adjacent-bits/Jq \ No newline at end of file diff --git a/Lang/Jq/Sierpinski-pentagon b/Lang/Jq/Sierpinski-pentagon new file mode 120000 index 0000000000..25b52521df --- /dev/null +++ b/Lang/Jq/Sierpinski-pentagon @@ -0,0 +1 @@ +../../Task/Sierpinski-pentagon/Jq \ No newline at end of file diff --git a/Lang/Jq/Sleeping-Beauty-problem b/Lang/Jq/Sleeping-Beauty-problem new file mode 120000 index 0000000000..56204d6c76 --- /dev/null +++ b/Lang/Jq/Sleeping-Beauty-problem @@ -0,0 +1 @@ +../../Task/Sleeping-Beauty-problem/Jq \ No newline at end of file diff --git a/Lang/Jq/Solve-a-Hidato-puzzle b/Lang/Jq/Solve-a-Hidato-puzzle new file mode 120000 index 0000000000..e3f6b38721 --- /dev/null +++ b/Lang/Jq/Solve-a-Hidato-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hidato-puzzle/Jq \ No newline at end of file diff --git a/Lang/Jq/Solve-a-Holy-Knights-tour b/Lang/Jq/Solve-a-Holy-Knights-tour new file mode 120000 index 0000000000..d69331eff1 --- /dev/null +++ b/Lang/Jq/Solve-a-Holy-Knights-tour @@ -0,0 +1 @@ +../../Task/Solve-a-Holy-Knights-tour/Jq \ No newline at end of file diff --git a/Lang/Jq/Solve-a-Numbrix-puzzle b/Lang/Jq/Solve-a-Numbrix-puzzle new file mode 120000 index 0000000000..29721632e1 --- /dev/null +++ b/Lang/Jq/Solve-a-Numbrix-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Numbrix-puzzle/Jq \ No newline at end of file diff --git a/Lang/Jq/Sort-an-outline-at-every-level b/Lang/Jq/Sort-an-outline-at-every-level new file mode 120000 index 0000000000..bce371340d --- /dev/null +++ b/Lang/Jq/Sort-an-outline-at-every-level @@ -0,0 +1 @@ +../../Task/Sort-an-outline-at-every-level/Jq \ No newline at end of file diff --git a/Lang/Jq/Sorting-Algorithms-Circle-Sort b/Lang/Jq/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index acb625912d..0000000000 --- a/Lang/Jq/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Jq \ No newline at end of file diff --git a/Lang/Jq/Strassens-algorithm b/Lang/Jq/Strassens-algorithm new file mode 120000 index 0000000000..d6ccda4254 --- /dev/null +++ b/Lang/Jq/Strassens-algorithm @@ -0,0 +1 @@ +../../Task/Strassens-algorithm/Jq \ No newline at end of file diff --git a/Lang/Jq/Thieles-interpolation-formula b/Lang/Jq/Thieles-interpolation-formula new file mode 120000 index 0000000000..25d4327e8c --- /dev/null +++ b/Lang/Jq/Thieles-interpolation-formula @@ -0,0 +1 @@ +../../Task/Thieles-interpolation-formula/Jq \ No newline at end of file diff --git a/Lang/Jq/Tic-tac-toe b/Lang/Jq/Tic-tac-toe new file mode 120000 index 0000000000..29e18a13ef --- /dev/null +++ b/Lang/Jq/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/Jq \ No newline at end of file diff --git a/Lang/Jq/Twos-complement b/Lang/Jq/Twos-complement new file mode 120000 index 0000000000..79d28d31d7 --- /dev/null +++ b/Lang/Jq/Twos-complement @@ -0,0 +1 @@ +../../Task/Twos-complement/Jq \ No newline at end of file diff --git a/Lang/Jq/Vogels-approximation-method b/Lang/Jq/Vogels-approximation-method new file mode 120000 index 0000000000..fb9aff7884 --- /dev/null +++ b/Lang/Jq/Vogels-approximation-method @@ -0,0 +1 @@ +../../Task/Vogels-approximation-method/Jq \ No newline at end of file diff --git a/Lang/Jq/War-card-game b/Lang/Jq/War-card-game new file mode 120000 index 0000000000..428c4a1307 --- /dev/null +++ b/Lang/Jq/War-card-game @@ -0,0 +1 @@ +../../Task/War-card-game/Jq \ No newline at end of file diff --git a/Lang/Jq/Wordiff b/Lang/Jq/Wordiff new file mode 120000 index 0000000000..61aa15852c --- /dev/null +++ b/Lang/Jq/Wordiff @@ -0,0 +1 @@ +../../Task/Wordiff/Jq \ No newline at end of file diff --git a/Lang/Julia/Bioinformatics-base-count b/Lang/Julia/Bioinformatics-base-count deleted file mode 120000 index 37835d6558..0000000000 --- a/Lang/Julia/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Julia \ No newline at end of file diff --git a/Lang/Julia/Meissel-Mertens-constant b/Lang/Julia/Meissel-Mertens-constant deleted file mode 120000 index 24fa8f526c..0000000000 --- a/Lang/Julia/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/Julia \ No newline at end of file diff --git a/Lang/Julia/Miller-Rabin-primality-test b/Lang/Julia/Miller-Rabin-primality-test deleted file mode 120000 index 1a7339a0d3..0000000000 --- a/Lang/Julia/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Julia \ No newline at end of file diff --git a/Lang/Julia/OLE-automation b/Lang/Julia/OLE-automation new file mode 120000 index 0000000000..58b1722653 --- /dev/null +++ b/Lang/Julia/OLE-automation @@ -0,0 +1 @@ +../../Task/OLE-automation/Julia \ No newline at end of file diff --git a/Lang/Julia/Quaternion-type b/Lang/Julia/Quaternion-type deleted file mode 120000 index 8a462d73ba..0000000000 --- a/Lang/Julia/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Julia \ No newline at end of file diff --git a/Lang/Julia/Simulate-input-Keyboard b/Lang/Julia/Simulate-input-Keyboard new file mode 120000 index 0000000000..79cc3689e4 --- /dev/null +++ b/Lang/Julia/Simulate-input-Keyboard @@ -0,0 +1 @@ +../../Task/Simulate-input-Keyboard/Julia \ No newline at end of file diff --git a/Lang/Julia/Sorting-Algorithms-Circle-Sort b/Lang/Julia/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index a8c5c2c2be..0000000000 --- a/Lang/Julia/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Julia \ No newline at end of file diff --git a/Lang/Julia/Use-another-language-to-call-a-function b/Lang/Julia/Use-another-language-to-call-a-function new file mode 120000 index 0000000000..c21a8c88ad --- /dev/null +++ b/Lang/Julia/Use-another-language-to-call-a-function @@ -0,0 +1 @@ +../../Task/Use-another-language-to-call-a-function/Julia \ No newline at end of file diff --git a/Lang/K/Abundant-odd-numbers b/Lang/K/Abundant-odd-numbers new file mode 120000 index 0000000000..e7fe0d3fc3 --- /dev/null +++ b/Lang/K/Abundant-odd-numbers @@ -0,0 +1 @@ +../../Task/Abundant-odd-numbers/K \ No newline at end of file diff --git a/Lang/K/Ascending-primes b/Lang/K/Ascending-primes new file mode 120000 index 0000000000..d9555980d2 --- /dev/null +++ b/Lang/K/Ascending-primes @@ -0,0 +1 @@ +../../Task/Ascending-primes/K \ No newline at end of file diff --git a/Lang/K/Benfords-law b/Lang/K/Benfords-law new file mode 120000 index 0000000000..75ff9d97ad --- /dev/null +++ b/Lang/K/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/K \ No newline at end of file diff --git a/Lang/K/Bulls-and-cows b/Lang/K/Bulls-and-cows new file mode 120000 index 0000000000..97544c963d --- /dev/null +++ b/Lang/K/Bulls-and-cows @@ -0,0 +1 @@ +../../Task/Bulls-and-cows/K \ No newline at end of file diff --git a/Lang/K/Circular-primes b/Lang/K/Circular-primes new file mode 120000 index 0000000000..5e07afa7a8 --- /dev/null +++ b/Lang/K/Circular-primes @@ -0,0 +1 @@ +../../Task/Circular-primes/K \ No newline at end of file diff --git a/Lang/K/Compare-a-list-of-strings b/Lang/K/Compare-a-list-of-strings new file mode 120000 index 0000000000..e673df5891 --- /dev/null +++ b/Lang/K/Compare-a-list-of-strings @@ -0,0 +1 @@ +../../Task/Compare-a-list-of-strings/K \ No newline at end of file diff --git a/Lang/K/Compare-length-of-two-strings b/Lang/K/Compare-length-of-two-strings new file mode 120000 index 0000000000..9854a6e09b --- /dev/null +++ b/Lang/K/Compare-length-of-two-strings @@ -0,0 +1 @@ +../../Task/Compare-length-of-two-strings/K \ No newline at end of file diff --git a/Lang/K/Descending-primes b/Lang/K/Descending-primes new file mode 120000 index 0000000000..1478a33e22 --- /dev/null +++ b/Lang/K/Descending-primes @@ -0,0 +1 @@ +../../Task/Descending-primes/K \ No newline at end of file diff --git a/Lang/K/Distribution-of-0-digits-in-factorial-series b/Lang/K/Distribution-of-0-digits-in-factorial-series new file mode 120000 index 0000000000..c4d66f6a7e --- /dev/null +++ b/Lang/K/Distribution-of-0-digits-in-factorial-series @@ -0,0 +1 @@ +../../Task/Distribution-of-0-digits-in-factorial-series/K \ No newline at end of file diff --git a/Lang/K/Empty-program b/Lang/K/Empty-program deleted file mode 120000 index f255a9c6f6..0000000000 --- a/Lang/K/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/K \ No newline at end of file diff --git a/Lang/K/Euler-method b/Lang/K/Euler-method new file mode 120000 index 0000000000..c1f821dc7c --- /dev/null +++ b/Lang/K/Euler-method @@ -0,0 +1 @@ +../../Task/Euler-method/K \ No newline at end of file diff --git a/Lang/K/Find-common-directory-path b/Lang/K/Find-common-directory-path new file mode 120000 index 0000000000..21e1ffcdd3 --- /dev/null +++ b/Lang/K/Find-common-directory-path @@ -0,0 +1 @@ +../../Task/Find-common-directory-path/K \ No newline at end of file diff --git a/Lang/K/M-bius-function b/Lang/K/M-bius-function new file mode 120000 index 0000000000..e4dca86d37 --- /dev/null +++ b/Lang/K/M-bius-function @@ -0,0 +1 @@ +../../Task/M-bius-function/K \ No newline at end of file diff --git a/Lang/K/Monads-Maybe-monad b/Lang/K/Monads-Maybe-monad new file mode 120000 index 0000000000..c39136ba4b --- /dev/null +++ b/Lang/K/Monads-Maybe-monad @@ -0,0 +1 @@ +../../Task/Monads-Maybe-monad/K \ No newline at end of file diff --git a/Lang/K/Monty-Hall-problem b/Lang/K/Monty-Hall-problem new file mode 120000 index 0000000000..8fb0f9e98b --- /dev/null +++ b/Lang/K/Monty-Hall-problem @@ -0,0 +1 @@ +../../Task/Monty-Hall-problem/K \ No newline at end of file diff --git a/Lang/K/Reverse-words-in-a-string b/Lang/K/Reverse-words-in-a-string new file mode 120000 index 0000000000..d83b97640c --- /dev/null +++ b/Lang/K/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/K \ No newline at end of file diff --git a/Lang/K/Sieve-of-Eratosthenes b/Lang/K/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..c66b9a1b22 --- /dev/null +++ b/Lang/K/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/K \ No newline at end of file diff --git a/Lang/K/Square-free-integers b/Lang/K/Square-free-integers new file mode 120000 index 0000000000..a0f2a0affe --- /dev/null +++ b/Lang/K/Square-free-integers @@ -0,0 +1 @@ +../../Task/Square-free-integers/K \ No newline at end of file diff --git a/Lang/K/Substring b/Lang/K/Substring new file mode 120000 index 0000000000..002d50df4f --- /dev/null +++ b/Lang/K/Substring @@ -0,0 +1 @@ +../../Task/Substring/K \ No newline at end of file diff --git a/Lang/K/Sum-multiples-of-3-and-5 b/Lang/K/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..625ba55b5f --- /dev/null +++ b/Lang/K/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/K \ No newline at end of file diff --git a/Lang/K/Tic-tac-toe b/Lang/K/Tic-tac-toe new file mode 120000 index 0000000000..bdd7e9ba5b --- /dev/null +++ b/Lang/K/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/K \ No newline at end of file diff --git a/Lang/K/UTF-8-encode-and-decode b/Lang/K/UTF-8-encode-and-decode new file mode 120000 index 0000000000..f38c9e1894 --- /dev/null +++ b/Lang/K/UTF-8-encode-and-decode @@ -0,0 +1 @@ +../../Task/UTF-8-encode-and-decode/K \ No newline at end of file diff --git a/Lang/K/Write-float-arrays-to-a-text-file b/Lang/K/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..2af99671ba --- /dev/null +++ b/Lang/K/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/K \ No newline at end of file diff --git a/Lang/Kantalo/00-LANG.txt b/Lang/Kantalo/00-LANG.txt new file mode 100644 index 0000000000..453580c58d --- /dev/null +++ b/Lang/Kantalo/00-LANG.txt @@ -0,0 +1,40 @@ +{{language|Kantalo +|version=0.0.2 +|exec=interpreted +|strength=weak +|express=explicit +|checking=dynamic +|gc=yes +|tags=Kantalo,Language +|LCT=yes +|hopl=no +|safety=unsafe +|site=http://kantalo.kesug.com/}} + +=={{header|Kantalo}}== + +Kantalo is a non-object-oriented programming language, with the aim of making it easier to use. + +==Main commands== + +Here are some kantalo commands: + +
  • var.save - It is used to define variable.
  • +
  • var.import - Import variable outside functions.
  • +
  • var.edit - Edit an Existing Variable.
  • +
  • terminal.text - Returns a message passed within the argument.
  • +
  • terminal.input - Creates a text input.
  • +
  • if- Used to create conditions .
  • +
  • func - It is used to create functions.
  • +
  • execute - Performs functions.
  • + +
    +Simple Hello world with kantalo: +
    + +var.save nome = "Alice", +func saudacao > ( + terminal.text("Seja bem-vindo(a), -*nome*-!") +) +execute saudacao + \ No newline at end of file diff --git a/Lang/Kantalo/00-META.yaml b/Lang/Kantalo/00-META.yaml new file mode 100644 index 0000000000..c7d465ac08 --- /dev/null +++ b/Lang/Kantalo/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Kantalo diff --git a/Lang/Koka/00-LANG.txt b/Lang/Koka/00-LANG.txt index 96ea39de13..540a8fe180 100644 --- a/Lang/Koka/00-LANG.txt +++ b/Lang/Koka/00-LANG.txt @@ -3,7 +3,7 @@ Releases: - https://github.com/koka-lang/koka/releases -Latest: v2.4.2 +Latest: v3.1.3 '''Language Reference''' diff --git a/Lang/Koka/A+B b/Lang/Koka/A+B new file mode 120000 index 0000000000..5fcfbb2462 --- /dev/null +++ b/Lang/Koka/A+B @@ -0,0 +1 @@ +../../Task/A+B/Koka \ No newline at end of file diff --git a/Lang/Koka/Extend-your-language b/Lang/Koka/Extend-your-language new file mode 120000 index 0000000000..fa9d061610 --- /dev/null +++ b/Lang/Koka/Extend-your-language @@ -0,0 +1 @@ +../../Task/Extend-your-language/Koka \ No newline at end of file diff --git a/Lang/Koka/Jump-anywhere b/Lang/Koka/Jump-anywhere new file mode 120000 index 0000000000..39d5f8124d --- /dev/null +++ b/Lang/Koka/Jump-anywhere @@ -0,0 +1 @@ +../../Task/Jump-anywhere/Koka \ No newline at end of file diff --git a/Lang/Koka/Letter-frequency b/Lang/Koka/Letter-frequency new file mode 120000 index 0000000000..35e2486b2e --- /dev/null +++ b/Lang/Koka/Letter-frequency @@ -0,0 +1 @@ +../../Task/Letter-frequency/Koka \ No newline at end of file diff --git a/Lang/Koka/Loops-Break b/Lang/Koka/Loops-Break new file mode 120000 index 0000000000..21d8774db0 --- /dev/null +++ b/Lang/Koka/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/Koka \ No newline at end of file diff --git a/Lang/Koka/Man-or-boy-test b/Lang/Koka/Man-or-boy-test new file mode 120000 index 0000000000..d04c480201 --- /dev/null +++ b/Lang/Koka/Man-or-boy-test @@ -0,0 +1 @@ +../../Task/Man-or-boy-test/Koka \ No newline at end of file diff --git a/Lang/Koka/Monads-Writer-monad b/Lang/Koka/Monads-Writer-monad new file mode 120000 index 0000000000..21e3e4c596 --- /dev/null +++ b/Lang/Koka/Monads-Writer-monad @@ -0,0 +1 @@ +../../Task/Monads-Writer-monad/Koka \ No newline at end of file diff --git a/Lang/Koka/Nim-game b/Lang/Koka/Nim-game new file mode 120000 index 0000000000..f3fed42c95 --- /dev/null +++ b/Lang/Koka/Nim-game @@ -0,0 +1 @@ +../../Task/Nim-game/Koka \ No newline at end of file diff --git a/Lang/Koka/Order-by-pair-comparisons b/Lang/Koka/Order-by-pair-comparisons new file mode 120000 index 0000000000..f453142a5f --- /dev/null +++ b/Lang/Koka/Order-by-pair-comparisons @@ -0,0 +1 @@ +../../Task/Order-by-pair-comparisons/Koka \ No newline at end of file diff --git a/Lang/Komodo/00-LANG.txt b/Lang/Komodo/00-LANG.txt new file mode 100644 index 0000000000..90f6e00b5c --- /dev/null +++ b/Lang/Komodo/00-LANG.txt @@ -0,0 +1,4 @@ +{{language +|exec=interpreted +|site=https://komodo-lang.org}}{{language programming paradigm|Declarative}}{{language programming paradigm|Procedural}} +Komodo is a programming language to test ideas in a fast and easy way. It is ideal for problems with basic discrete structures, like numbers and words. Komodo tries to make operating with these entities as easy as possible while minimizing the amount of code needed to achieve a successful implementation. Komodo is a scripting language regarding its flexibility, but it is a pretty specific language with a lot of assumptions about how things should be. Komodo is an experimental language, and some of its features are there because I had a personal preference for them. \ No newline at end of file diff --git a/Lang/Komodo/00-META.yaml b/Lang/Komodo/00-META.yaml new file mode 100644 index 0000000000..c626a5f324 --- /dev/null +++ b/Lang/Komodo/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Komodo diff --git a/Lang/Komodo/Arithmetic-Integer b/Lang/Komodo/Arithmetic-Integer new file mode 120000 index 0000000000..bfaefbd88d --- /dev/null +++ b/Lang/Komodo/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Komodo \ No newline at end of file diff --git a/Lang/Komodo/Array-concatenation b/Lang/Komodo/Array-concatenation new file mode 120000 index 0000000000..bc329941d2 --- /dev/null +++ b/Lang/Komodo/Array-concatenation @@ -0,0 +1 @@ +../../Task/Array-concatenation/Komodo \ No newline at end of file diff --git a/Lang/Komodo/Empty-string b/Lang/Komodo/Empty-string new file mode 120000 index 0000000000..9210767339 --- /dev/null +++ b/Lang/Komodo/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/Komodo \ No newline at end of file diff --git a/Lang/Komodo/FizzBuzz b/Lang/Komodo/FizzBuzz new file mode 120000 index 0000000000..49b35c998a --- /dev/null +++ b/Lang/Komodo/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Komodo \ No newline at end of file diff --git a/Lang/Komodo/Function-definition b/Lang/Komodo/Function-definition new file mode 120000 index 0000000000..375c03b7e3 --- /dev/null +++ b/Lang/Komodo/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/Komodo \ No newline at end of file diff --git a/Lang/Komodo/Greatest-element-of-a-list b/Lang/Komodo/Greatest-element-of-a-list new file mode 120000 index 0000000000..61a341a27e --- /dev/null +++ b/Lang/Komodo/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/Komodo \ No newline at end of file diff --git a/Lang/Komodo/Hello-world-Text b/Lang/Komodo/Hello-world-Text new file mode 120000 index 0000000000..cf4d6242bb --- /dev/null +++ b/Lang/Komodo/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Komodo \ No newline at end of file diff --git a/Lang/Komodo/Literals-Integer b/Lang/Komodo/Literals-Integer new file mode 120000 index 0000000000..e770e3710e --- /dev/null +++ b/Lang/Komodo/Literals-Integer @@ -0,0 +1 @@ +../../Task/Literals-Integer/Komodo \ No newline at end of file diff --git a/Lang/Komodo/Logical-operations b/Lang/Komodo/Logical-operations new file mode 120000 index 0000000000..f15b7485a0 --- /dev/null +++ b/Lang/Komodo/Logical-operations @@ -0,0 +1 @@ +../../Task/Logical-operations/Komodo \ No newline at end of file diff --git a/Lang/Komodo/Null-object b/Lang/Komodo/Null-object new file mode 120000 index 0000000000..a6a020a8ca --- /dev/null +++ b/Lang/Komodo/Null-object @@ -0,0 +1 @@ +../../Task/Null-object/Komodo \ No newline at end of file diff --git a/Lang/Komodo/Set b/Lang/Komodo/Set new file mode 120000 index 0000000000..a5c8370f07 --- /dev/null +++ b/Lang/Komodo/Set @@ -0,0 +1 @@ +../../Task/Set/Komodo \ No newline at end of file diff --git a/Lang/Komodo/String-concatenation b/Lang/Komodo/String-concatenation new file mode 120000 index 0000000000..72385e6195 --- /dev/null +++ b/Lang/Komodo/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Komodo \ No newline at end of file diff --git a/Lang/Kotlin/00-LANG.txt b/Lang/Kotlin/00-LANG.txt index 5f33d4bd2a..95d9b59867 100644 --- a/Lang/Kotlin/00-LANG.txt +++ b/Lang/Kotlin/00-LANG.txt @@ -4,7 +4,7 @@ |site=http://kotlinlang.org |hopl=no }} -Kotlin is a statically-typed programming language that runs on the [[JVM]] and can also be compiled to JavaScript. It is being developed by JetBrains with assistance from open source contributors and is intended for industrial use. +Kotlin is a statically-typed programming language that runs on the [[runs on vm::Java Virtual Machine]] (JVM) and can also be compiled to JavaScript. It is being developed by JetBrains with assistance from open source contributors and is intended for industrial use. In addition, a separate team at JetBrains is developing a version of Kotlin which compiles (via LLVM) directly to machine code for various platforms. The first Technology Preview for this version was rolled out in April 2017. diff --git a/Lang/Kotlin/Bioinformatics-base-count b/Lang/Kotlin/Bioinformatics-base-count deleted file mode 120000 index 998809c6ab..0000000000 --- a/Lang/Kotlin/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Boyer-Moore-string-search b/Lang/Kotlin/Boyer-Moore-string-search new file mode 120000 index 0000000000..985c6560bd --- /dev/null +++ b/Lang/Kotlin/Boyer-Moore-string-search @@ -0,0 +1 @@ +../../Task/Boyer-Moore-string-search/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Compare-length-of-two-strings b/Lang/Kotlin/Compare-length-of-two-strings new file mode 120000 index 0000000000..a8c0b8d6cf --- /dev/null +++ b/Lang/Kotlin/Compare-length-of-two-strings @@ -0,0 +1 @@ +../../Task/Compare-length-of-two-strings/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Compiler-AST-interpreter b/Lang/Kotlin/Compiler-AST-interpreter new file mode 120000 index 0000000000..5990b7f53e --- /dev/null +++ b/Lang/Kotlin/Compiler-AST-interpreter @@ -0,0 +1 @@ +../../Task/Compiler-AST-interpreter/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Factorial-primes b/Lang/Kotlin/Factorial-primes new file mode 120000 index 0000000000..36b19250f9 --- /dev/null +++ b/Lang/Kotlin/Factorial-primes @@ -0,0 +1 @@ +../../Task/Factorial-primes/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Miller-Rabin-primality-test b/Lang/Kotlin/Miller-Rabin-primality-test deleted file mode 120000 index 4a724f8c08..0000000000 --- a/Lang/Kotlin/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Quaternion-type b/Lang/Kotlin/Quaternion-type deleted file mode 120000 index a85b316d4c..0000000000 --- a/Lang/Kotlin/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Radical-of-an-integer b/Lang/Kotlin/Radical-of-an-integer new file mode 120000 index 0000000000..e9d51e3e8d --- /dev/null +++ b/Lang/Kotlin/Radical-of-an-integer @@ -0,0 +1 @@ +../../Task/Radical-of-an-integer/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Sorting-Algorithms-Circle-Sort b/Lang/Kotlin/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 74cde5ab2a..0000000000 --- a/Lang/Kotlin/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Strassens-algorithm b/Lang/Kotlin/Strassens-algorithm new file mode 120000 index 0000000000..f68cd59b88 --- /dev/null +++ b/Lang/Kotlin/Strassens-algorithm @@ -0,0 +1 @@ +../../Task/Strassens-algorithm/Kotlin \ No newline at end of file diff --git a/Lang/LDPL/Command-line-arguments b/Lang/LDPL/Command-line-arguments new file mode 120000 index 0000000000..7b4b88a226 --- /dev/null +++ b/Lang/LDPL/Command-line-arguments @@ -0,0 +1 @@ +../../Task/Command-line-arguments/LDPL \ No newline at end of file diff --git a/Lang/LOLCODE/00-LANG.txt b/Lang/LOLCODE/00-LANG.txt index 57c4165430..2195760c79 100644 --- a/Lang/LOLCODE/00-LANG.txt +++ b/Lang/LOLCODE/00-LANG.txt @@ -3,4 +3,21 @@ |site=http://lolcode.org/ |hopl=no }} + +LOLCODE is an esoteric language created by Adam Lindsay in 2007. It was inspired by the [https://en.wikipedia.org/wiki/Lolcat lolcat] phenomenon which began a year earlier. LOLCODE uses intentionally grammatically incorrect text known as lolspeak, a humorous imagining of what a cat might say if it could speak something resembling English. + +Here is an example program that prints the numbers 0 through 9 to standard output: + +HAI 1.3 + +IM IN YR loop UPPIN YR var TIL BOTH SAEM var AN 10 + VISIBLE var +IM OUTTA YR loop + +KTHXBYE + + +==Todo== +[https://rosettacode.org/wiki/Tasks_not_implemented_in_LOLCODE Tasks not implemented in LOLCODE] + [[Category:Esoteric Languages]] \ No newline at end of file diff --git a/Lang/LOLCODE/A+B b/Lang/LOLCODE/A+B new file mode 120000 index 0000000000..d5ea45853c --- /dev/null +++ b/Lang/LOLCODE/A+B @@ -0,0 +1 @@ +../../Task/A+B/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Arithmetic-Integer b/Lang/LOLCODE/Arithmetic-Integer new file mode 120000 index 0000000000..bba2907420 --- /dev/null +++ b/Lang/LOLCODE/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Boolean-values b/Lang/LOLCODE/Boolean-values new file mode 120000 index 0000000000..b3ad6a0e0d --- /dev/null +++ b/Lang/LOLCODE/Boolean-values @@ -0,0 +1 @@ +../../Task/Boolean-values/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Case-sensitivity-of-identifiers b/Lang/LOLCODE/Case-sensitivity-of-identifiers new file mode 120000 index 0000000000..32c69366ea --- /dev/null +++ b/Lang/LOLCODE/Case-sensitivity-of-identifiers @@ -0,0 +1 @@ +../../Task/Case-sensitivity-of-identifiers/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Catalan-numbers b/Lang/LOLCODE/Catalan-numbers new file mode 120000 index 0000000000..3fdf885cda --- /dev/null +++ b/Lang/LOLCODE/Catalan-numbers @@ -0,0 +1 @@ +../../Task/Catalan-numbers/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Chinese-zodiac b/Lang/LOLCODE/Chinese-zodiac new file mode 120000 index 0000000000..0169fc21dd --- /dev/null +++ b/Lang/LOLCODE/Chinese-zodiac @@ -0,0 +1 @@ +../../Task/Chinese-zodiac/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Compound-data-type b/Lang/LOLCODE/Compound-data-type new file mode 120000 index 0000000000..a58d5bfd2a --- /dev/null +++ b/Lang/LOLCODE/Compound-data-type @@ -0,0 +1 @@ +../../Task/Compound-data-type/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Conditional-structures b/Lang/LOLCODE/Conditional-structures new file mode 120000 index 0000000000..15617a63e0 --- /dev/null +++ b/Lang/LOLCODE/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Copy-a-string b/Lang/LOLCODE/Copy-a-string new file mode 120000 index 0000000000..deb186939a --- /dev/null +++ b/Lang/LOLCODE/Copy-a-string @@ -0,0 +1 @@ +../../Task/Copy-a-string/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Determine-if-a-string-has-all-the-same-characters b/Lang/LOLCODE/Determine-if-a-string-has-all-the-same-characters new file mode 120000 index 0000000000..492082be7e --- /dev/null +++ b/Lang/LOLCODE/Determine-if-a-string-has-all-the-same-characters @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-has-all-the-same-characters/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Dot-product b/Lang/LOLCODE/Dot-product new file mode 120000 index 0000000000..0667fd8bc3 --- /dev/null +++ b/Lang/LOLCODE/Dot-product @@ -0,0 +1 @@ +../../Task/Dot-product/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Empty-program b/Lang/LOLCODE/Empty-program new file mode 120000 index 0000000000..31b87c5a4b --- /dev/null +++ b/Lang/LOLCODE/Empty-program @@ -0,0 +1 @@ +../../Task/Empty-program/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Evaluate-binomial-coefficients b/Lang/LOLCODE/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..f6f761fd40 --- /dev/null +++ b/Lang/LOLCODE/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Function-definition b/Lang/LOLCODE/Function-definition new file mode 120000 index 0000000000..c9fc3fa7a5 --- /dev/null +++ b/Lang/LOLCODE/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Gotchas b/Lang/LOLCODE/Gotchas new file mode 120000 index 0000000000..753dc0a0c3 --- /dev/null +++ b/Lang/LOLCODE/Gotchas @@ -0,0 +1 @@ +../../Task/Gotchas/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Hello-world-Newline-omission b/Lang/LOLCODE/Hello-world-Newline-omission new file mode 120000 index 0000000000..29d6dd8c2e --- /dev/null +++ b/Lang/LOLCODE/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Integer-comparison b/Lang/LOLCODE/Integer-comparison new file mode 120000 index 0000000000..565277c685 --- /dev/null +++ b/Lang/LOLCODE/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Isqrt-integer-square-root-of-X b/Lang/LOLCODE/Isqrt-integer-square-root-of-X new file mode 120000 index 0000000000..4aa1c0772e --- /dev/null +++ b/Lang/LOLCODE/Isqrt-integer-square-root-of-X @@ -0,0 +1 @@ +../../Task/Isqrt-integer-square-root-of-X/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Jewels-and-stones b/Lang/LOLCODE/Jewels-and-stones new file mode 120000 index 0000000000..5c30a50d3b --- /dev/null +++ b/Lang/LOLCODE/Jewels-and-stones @@ -0,0 +1 @@ +../../Task/Jewels-and-stones/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Jordan-P-lya-numbers b/Lang/LOLCODE/Jordan-P-lya-numbers new file mode 120000 index 0000000000..d942ad0dab --- /dev/null +++ b/Lang/LOLCODE/Jordan-P-lya-numbers @@ -0,0 +1 @@ +../../Task/Jordan-P-lya-numbers/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Loops-Do-while b/Lang/LOLCODE/Loops-Do-while new file mode 120000 index 0000000000..55da8969f1 --- /dev/null +++ b/Lang/LOLCODE/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Loops-Downward-for b/Lang/LOLCODE/Loops-Downward-for new file mode 120000 index 0000000000..098dda4410 --- /dev/null +++ b/Lang/LOLCODE/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Loops-For b/Lang/LOLCODE/Loops-For new file mode 120000 index 0000000000..131d677c68 --- /dev/null +++ b/Lang/LOLCODE/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Loops-For-with-a-specified-step b/Lang/LOLCODE/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..5debcbe8c4 --- /dev/null +++ b/Lang/LOLCODE/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Loops-N-plus-one-half b/Lang/LOLCODE/Loops-N-plus-one-half new file mode 120000 index 0000000000..f67d63ceea --- /dev/null +++ b/Lang/LOLCODE/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Menu b/Lang/LOLCODE/Menu new file mode 120000 index 0000000000..8ec9ba2bbb --- /dev/null +++ b/Lang/LOLCODE/Menu @@ -0,0 +1 @@ +../../Task/Menu/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Nested-function b/Lang/LOLCODE/Nested-function new file mode 120000 index 0000000000..28b8eedc4f --- /dev/null +++ b/Lang/LOLCODE/Nested-function @@ -0,0 +1 @@ +../../Task/Nested-function/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Nim-game b/Lang/LOLCODE/Nim-game new file mode 120000 index 0000000000..8694962a96 --- /dev/null +++ b/Lang/LOLCODE/Nim-game @@ -0,0 +1 @@ +../../Task/Nim-game/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Nth b/Lang/LOLCODE/Nth new file mode 120000 index 0000000000..ca0f39b290 --- /dev/null +++ b/Lang/LOLCODE/Nth @@ -0,0 +1 @@ +../../Task/Nth/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Primality-by-trial-division b/Lang/LOLCODE/Primality-by-trial-division new file mode 120000 index 0000000000..243da2a0b6 --- /dev/null +++ b/Lang/LOLCODE/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Real-constants-and-functions b/Lang/LOLCODE/Real-constants-and-functions new file mode 120000 index 0000000000..9cae154fda --- /dev/null +++ b/Lang/LOLCODE/Real-constants-and-functions @@ -0,0 +1 @@ +../../Task/Real-constants-and-functions/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Repeat b/Lang/LOLCODE/Repeat new file mode 120000 index 0000000000..bfb28ef859 --- /dev/null +++ b/Lang/LOLCODE/Repeat @@ -0,0 +1 @@ +../../Task/Repeat/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Repeat-a-string b/Lang/LOLCODE/Repeat-a-string new file mode 120000 index 0000000000..b733bdc3e9 --- /dev/null +++ b/Lang/LOLCODE/Repeat-a-string @@ -0,0 +1 @@ +../../Task/Repeat-a-string/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Return-multiple-values b/Lang/LOLCODE/Return-multiple-values new file mode 120000 index 0000000000..326bda4561 --- /dev/null +++ b/Lang/LOLCODE/Return-multiple-values @@ -0,0 +1 @@ +../../Task/Return-multiple-values/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Reverse-a-string b/Lang/LOLCODE/Reverse-a-string new file mode 120000 index 0000000000..c092ce2e24 --- /dev/null +++ b/Lang/LOLCODE/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Short-circuit-evaluation b/Lang/LOLCODE/Short-circuit-evaluation new file mode 120000 index 0000000000..747e2d63b6 --- /dev/null +++ b/Lang/LOLCODE/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Split-a-character-string-based-on-change-of-character b/Lang/LOLCODE/Split-a-character-string-based-on-change-of-character new file mode 120000 index 0000000000..3d417eb3b9 --- /dev/null +++ b/Lang/LOLCODE/Split-a-character-string-based-on-change-of-character @@ -0,0 +1 @@ +../../Task/Split-a-character-string-based-on-change-of-character/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/String-concatenation b/Lang/LOLCODE/String-concatenation new file mode 120000 index 0000000000..8f1d425354 --- /dev/null +++ b/Lang/LOLCODE/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/String-interpolation-included- b/Lang/LOLCODE/String-interpolation-included- new file mode 120000 index 0000000000..2477427706 --- /dev/null +++ b/Lang/LOLCODE/String-interpolation-included- @@ -0,0 +1 @@ +../../Task/String-interpolation-included-/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Sum-of-a-series b/Lang/LOLCODE/Sum-of-a-series new file mode 120000 index 0000000000..3071bb174e --- /dev/null +++ b/Lang/LOLCODE/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Terminal-control-Display-an-extended-character b/Lang/LOLCODE/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..506d7e357c --- /dev/null +++ b/Lang/LOLCODE/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Terminal-control-Ringing-the-terminal-bell b/Lang/LOLCODE/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..a3dce93aeb --- /dev/null +++ b/Lang/LOLCODE/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Tokenize-a-string b/Lang/LOLCODE/Tokenize-a-string new file mode 120000 index 0000000000..61653af306 --- /dev/null +++ b/Lang/LOLCODE/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Topic-variable b/Lang/LOLCODE/Topic-variable new file mode 120000 index 0000000000..8a1f58e75e --- /dev/null +++ b/Lang/LOLCODE/Topic-variable @@ -0,0 +1 @@ +../../Task/Topic-variable/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Variable-declaration-reset b/Lang/LOLCODE/Variable-declaration-reset new file mode 120000 index 0000000000..126975a58e --- /dev/null +++ b/Lang/LOLCODE/Variable-declaration-reset @@ -0,0 +1 @@ +../../Task/Variable-declaration-reset/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Zeckendorf-number-representation b/Lang/LOLCODE/Zeckendorf-number-representation new file mode 120000 index 0000000000..093dc5325c --- /dev/null +++ b/Lang/LOLCODE/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/LOLCODE \ No newline at end of file diff --git a/Lang/LSE/Empty-program b/Lang/LSE/Empty-program deleted file mode 120000 index 16856f6969..0000000000 --- a/Lang/LSE/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/LSE \ No newline at end of file diff --git a/Lang/LSL/00-LANG.txt b/Lang/LSL/00-LANG.txt index bdb68f1bc2..3025477b27 100644 --- a/Lang/LSL/00-LANG.txt +++ b/Lang/LSL/00-LANG.txt @@ -1,25 +1,42 @@ {{language |hopl=no }} -The [[wp:Linden_Scripting_Language|'''Linden Scripting Language''']], usually just called '''LSL''' for short, is a language developed by [http://en.wikipedia.org/wiki/Linden_Lab Linden Labs] for their [[wp:Second_Life|Second Life]] virtual world. LSL allows Second Life objects to sense, respond to events, and interact with the (virtual) world around them, and the Avatars in that world. +'''LSL''' ([[wp:Linden_Scripting_Language|'''Linden Scripting Language''']]) is the scripting language developed by [http://en.wikipedia.org/wiki/Linden_Lab Linden Labs] for their virtual sandbox world [[wp:Second_Life|Second Life]]. Also [[wp:OpenSimulator|OpenSimulator]] along with other [https://omrg.org Open Metaverse] proprietors run a largely compatible superset version of LSL. LSL scripts allow objects rezzed in-world(in-game) to interact with and manipulate the virtual world around them, but also the internet in limited fashion. LSL has many built-in functions, and the ability for inter script messaging, http POST and GET requests, gui dialog boxes, chat channel messaging, java & C like semantics, is turning complete, etc. + +==In Depth: Syntax Structure== +LSL is C-like with scoping of local varaibles and global; strict typing with type-recasting possible; use of {} to encapsulate function blocks, and ; to denote an execution block, and () to encapsulate parameters, and equivalency from right to left and for assignment myint=1-2, variables can be formed as procedures that return a value. Oprands are the same, but there are no pointers nor triple oprands such as +++. +LSL is not like C in many ways, there are only 3 basic types, and 4 special types of data structures: integer (unsigned 32bit), float (unsigned 32bit), string (max string length varies), key ( a 32bit base16 UUID often treated as a string),vectors (set of three floats, aka a tuple <0.0,0.0,0.0> ); quaternions or rot ( set of four floats <0.0,0.0,0.0,0.0> ); lists (1D array that can contain any of or a mix of types of data), There is no void as a type! Nor is there any keyword for functions. Simply outside of a script's default loop function called a state, one forms a function with it's name(type prams){;} and can be called anywhere else. Over-loading is not valid, nor is under-loading when calling a function or variable-function that returns a value. + +==In Depth: Where & when LSL scripts can run== +Rezzing is dragging and dropping from the user's inventory into to the virtual world space, or being worn as attachments to one's avatar (including HUDs). These aforementioned objects take the form of built-in 3d models of basic shapes commonly known as primitives or just prims, sculpted prims, and user uploaded 3D models. Each object has in-turn it's own inventory where the scripts run. In truth one can link many objects into a meta-object known as a link-set, each linked object retains it's own inventory instance, and running scripts. When an object is derezzed, that is brought back into the user's inventory, or an attached object derezzes when the user logs off the scripts' current status is paused and saved. + +==In Depth: LSL basic script structure== +Each script must contain a default script state, this is very similar to the default loop found with in Arduino Clike programming. It is possible to switch the currently running state of a script to a knew one, and back again, thus ignoring/clearing any callback functions called "events". (However the timer does not get cleared upon state changes). +Each state in LSL scripts can have built in call-back functions known as "event types" which are triggered with interrupt like behavior from a cue that is filled by the current simulator or sim (a sim is world instance, generally a 256x256meter block, although some communication with adjacent sims maybe possible) the script is residing in. Most events are repeatable, but there are logically single fire events such as state_entry, on_rez, on_attach, on_deattach. Aforementioned user functions, variables, + +==Back-ends of LSL with in Second-Life== +In Second-life, one can save & run scripts optionally for the two current back-ends that actually run the code over a server, each with their own pros and cons. +[https://wiki.secondlife.com/wiki/LSO LSO] exists for backward compatibility. LSO saved scripts are interpreted at runtime by the server. LSO scripts take less initial script memory, they are limited to less available memory as well. In rare circumstances LSO may run faster than MONO. However LSO suffers from memory fragmentation slow downs with list connotation (there are some work around). LSO handles the jump to @location in unexpected ways. +Mono saved scripts are compiled under [[wp:Mono_(software)|Mono]] (the most recent) to byte-code ran by the server. + Most scripts will benefit from being set to MONO compilation for greater speed and more available memory, at the cost of higher initial memory used. ==Flavors of LSL== -There are currently three flavors of the LSL language -# LSL compiled under [[wp:Mono_(software)|Mono]] (the most recent) -# The original interpreted version (no longer being developed and only exists for backward compatibility) -# A largely compatible version of LSL that can run in the [[wp:OpenSimulator|OpenSimulator]] virtual world. +# A largely compatible version of LSL that can run in the [[http://opensimulator.org/wiki/OSSL_Script_Library|OpenSimulator]] virtual world. ==Documentation== There are two popular web sites documenting LSL # Second Life's own [http://wiki.secondlife.com/wiki/LSL_Portal LSL Portal] # a user supported [http://lslwiki.net/lslwiki/wakka.php LSL Wiki] -==Libraries== +==Libraries of Scripts== There exists several open source libraries where users share code +* [https://outworldz.com/cgi/freescripts.plx Free LSL Scripts] * [http://community.secondlife.com/t5/LSL-Scripting-Library/bd-p/LSLScriptingLibrary LSL Scripting Library] * [http://wiki.secondlife.com/wiki/Category:LSL_Examples LSL Examples] -* [http://www.free-lsl-scripts.com/cgi/freescripts.plx Free LSL Scripts] * [http://community.secondlife.com/t5/LSL-Scripting/bd-p/LSLScripting LSL Scripting] ==External Editors== -There are also many [http://wiki.secondlife.com/wiki/LSL_Alternate_Editors external editors] for LSL allowing you to write, syntax check, and (to a limited extent) execute LSL outside of the Second Life environment. You will need to sign up at [http://secondlife.com Second Life] and have a Second Life account to execute LSL in the virtual world. Your scripts can exist by themselves in a folder of your inventory, or in an Object in your inventory, but need to be in an Object that is in-world to execute (if an Object containing scripts is taken in to your inventory, the scripts will be suspended and will resume when brought out in to the world again.) \ No newline at end of file +There are also many [http://wiki.secondlife.com/wiki/LSL_Alternate_Editors external editors] for LSL allowing you to write with highlighting, [https://github.com/Feay/LSL-for-Scite api tool-tips], [https://github.com/Makopo/lslint syntax check], and (to a limited extent) +[https://github.com/Sei-Lisa/LSL-compiler compile and execute LSL] outside of the Second Life environment. + +You will need to sign up at [http://secondlife.com Second Life] and have a Second Life account to execute LSL in the virtual world. Your scripts can exist by themselves in a folder of your inventory, or in an Object in your inventory, but need to be in an Object that is in-world to execute (if an Object containing scripts is taken in to your inventory, the scripts will be suspended and will resume when brought out in to the world again.) \ No newline at end of file diff --git a/Lang/LSL/Binary-digits b/Lang/LSL/Binary-digits new file mode 120000 index 0000000000..54627407f6 --- /dev/null +++ b/Lang/LSL/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/LSL \ No newline at end of file diff --git a/Lang/Labyrinth/00-LANG.txt b/Lang/Labyrinth/00-LANG.txt new file mode 100644 index 0000000000..6b7624f3ac --- /dev/null +++ b/Lang/Labyrinth/00-LANG.txt @@ -0,0 +1 @@ +{{stub}}{{language|site=https://github.com/m-ender/labyrinth}} \ No newline at end of file diff --git a/Lang/Labyrinth/00-META.yaml b/Lang/Labyrinth/00-META.yaml new file mode 100644 index 0000000000..2e09fd26db --- /dev/null +++ b/Lang/Labyrinth/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Labyrinth diff --git a/Lang/Lambdatalk/Bioinformatics-base-count b/Lang/Lambdatalk/Bioinformatics-base-count deleted file mode 120000 index 03508c2431..0000000000 --- a/Lang/Lambdatalk/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Lambdatalk \ No newline at end of file diff --git a/Lang/Langur/00-LANG.txt b/Lang/Langur/00-LANG.txt index c2da20439a..612e66c8de 100644 --- a/Lang/Langur/00-LANG.txt +++ b/Lang/Langur/00-LANG.txt @@ -3,12 +3,22 @@ |hopl=no }} -Langur is an open-source imperative/functional programming language. The name langur begins with a lowercase letter when it does not start a sentence. +Langur is an open-source programming language that natively uses arbitrary-precision decimal floating point, and deals with extremely large and small numbers. It also has native complex numbers that are arbitrary-precision decimal. Its principles of design are accuracy in calculation and a concise, expressive syntax. -Langur code can be run with script files or with its REPL. The recommended file name extension is .langur. +Langur has a high number of mathematical operators (rem, mod, etc.) and logical operators (including nand, nor, nxor). -Langur uses a hash mark for single line comments. Therefore, script files may begin with a shebang to tell a Linux shell where to find the interpreter. +Langur has date/time literals (using ISO 8601 syntax) and duration literals. -Source code is in UTF-8, with no BOM, using Linux line returns (line feed) only. +Langur has flexible parameter options, with both positional parameters and parameters by name, and with parameter expansion (on last positional parameter). Parameters by name may be optional or required. + +Langur uses exceptions instead of error codes. + +Langur code can be run from executable files, or you can use interactive mode or the REPL. The file name extension is .langur. + +Langur uses a hash mark for single line comments. Therefore, script files can begin with a shebang to tell a Linux shell where to find the interpreter. + +Source code is always UTF-8, with no BOM, using Linux line returns (line feed) only. + +The name langur begins with a lowercase letter when it does not start a sentence. website: https://langurlang.org/ \ No newline at end of file diff --git a/Lang/Langur/99-bottles-of-beer b/Lang/Langur/99-bottles-of-beer new file mode 120000 index 0000000000..043a4c56e9 --- /dev/null +++ b/Lang/Langur/99-bottles-of-beer @@ -0,0 +1 @@ +../../Task/99-bottles-of-beer/Langur \ No newline at end of file diff --git a/Lang/Langur/Angle-difference-between-two-bearings b/Lang/Langur/Angle-difference-between-two-bearings new file mode 120000 index 0000000000..7b4ef17804 --- /dev/null +++ b/Lang/Langur/Angle-difference-between-two-bearings @@ -0,0 +1 @@ +../../Task/Angle-difference-between-two-bearings/Langur \ No newline at end of file diff --git a/Lang/Langur/Arithmetic-Complex b/Lang/Langur/Arithmetic-Complex new file mode 120000 index 0000000000..5341d853ac --- /dev/null +++ b/Lang/Langur/Arithmetic-Complex @@ -0,0 +1 @@ +../../Task/Arithmetic-Complex/Langur \ No newline at end of file diff --git a/Lang/Langur/Babbage-problem b/Lang/Langur/Babbage-problem new file mode 120000 index 0000000000..662297217a --- /dev/null +++ b/Lang/Langur/Babbage-problem @@ -0,0 +1 @@ +../../Task/Babbage-problem/Langur \ No newline at end of file diff --git a/Lang/Langur/Currency b/Lang/Langur/Currency new file mode 120000 index 0000000000..5a712c5b9d --- /dev/null +++ b/Lang/Langur/Currency @@ -0,0 +1 @@ +../../Task/Currency/Langur \ No newline at end of file diff --git a/Lang/Langur/Enforced-immutability b/Lang/Langur/Enforced-immutability new file mode 120000 index 0000000000..a6a872e8c6 --- /dev/null +++ b/Lang/Langur/Enforced-immutability @@ -0,0 +1 @@ +../../Task/Enforced-immutability/Langur \ No newline at end of file diff --git a/Lang/Langur/I-before-E-except-after-C b/Lang/Langur/I-before-E-except-after-C new file mode 120000 index 0000000000..a4c67c55c7 --- /dev/null +++ b/Lang/Langur/I-before-E-except-after-C @@ -0,0 +1 @@ +../../Task/I-before-E-except-after-C/Langur \ No newline at end of file diff --git a/Lang/Langur/Monty-Hall-problem b/Lang/Langur/Monty-Hall-problem new file mode 120000 index 0000000000..b5a048c861 --- /dev/null +++ b/Lang/Langur/Monty-Hall-problem @@ -0,0 +1 @@ +../../Task/Monty-Hall-problem/Langur \ No newline at end of file diff --git a/Lang/Langur/Morse-code b/Lang/Langur/Morse-code new file mode 120000 index 0000000000..ee4498f8de --- /dev/null +++ b/Lang/Langur/Morse-code @@ -0,0 +1 @@ +../../Task/Morse-code/Langur \ No newline at end of file diff --git a/Lang/Langur/Old-Russian-measure-of-length b/Lang/Langur/Old-Russian-measure-of-length new file mode 120000 index 0000000000..45d7b04413 --- /dev/null +++ b/Lang/Langur/Old-Russian-measure-of-length @@ -0,0 +1 @@ +../../Task/Old-Russian-measure-of-length/Langur \ No newline at end of file diff --git a/Lang/Langur/Program-name b/Lang/Langur/Program-name deleted file mode 120000 index 04198cf0de..0000000000 --- a/Lang/Langur/Program-name +++ /dev/null @@ -1 +0,0 @@ -../../Task/Program-name/Langur \ No newline at end of file diff --git a/Lang/Langur/Safe-addition b/Lang/Langur/Safe-addition new file mode 120000 index 0000000000..9cd478ca7f --- /dev/null +++ b/Lang/Langur/Safe-addition @@ -0,0 +1 @@ +../../Task/Safe-addition/Langur \ No newline at end of file diff --git a/Lang/Langur/String-interpolation-included- b/Lang/Langur/String-interpolation-included- new file mode 120000 index 0000000000..e0b5bfaf9c --- /dev/null +++ b/Lang/Langur/String-interpolation-included- @@ -0,0 +1 @@ +../../Task/String-interpolation-included-/Langur \ No newline at end of file diff --git a/Lang/Lapyst/00-LANG.txt b/Lang/Lapyst/00-LANG.txt new file mode 100644 index 0000000000..4b906ad0c0 --- /dev/null +++ b/Lang/Lapyst/00-LANG.txt @@ -0,0 +1,14 @@ +{{stub}} +{{language|Lapyst +|site=https://lang.lapyst.dev +|exec=both +|parampass=both +|strength=strong +|express=both +|checking=static +|tags=lapyst +|gc=yes (optional)}} + +Lapyst is an general-purpose language designed by [[User:Mai Lapyst]]. It features multiple backend strategies (machinecode, bytecode and interpretation), while combining many usefull features of other languages for the user to choose from. The philosophy in the language is generally to empower the user and give it as much choice as possible. + +The current default implementation is [[Lapystc]]. \ No newline at end of file diff --git a/Lang/Lapyst/00-META.yaml b/Lang/Lapyst/00-META.yaml new file mode 100644 index 0000000000..3187527652 --- /dev/null +++ b/Lang/Lapyst/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Lapyst diff --git a/Lang/Lapyst/Conditional-structures b/Lang/Lapyst/Conditional-structures new file mode 120000 index 0000000000..d244d152bd --- /dev/null +++ b/Lang/Lapyst/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/Lapyst \ No newline at end of file diff --git a/Lang/Lean/00-LANG.txt b/Lang/Lean/00-LANG.txt index 174b82817c..ae97385d36 100644 --- a/Lang/Lean/00-LANG.txt +++ b/Lang/Lean/00-LANG.txt @@ -1,17 +1,22 @@ -{{language +{{language|Lean |exec=machine |strength=strong |safety=safe |checking=both |gc=yes -|LCT=yes}} -{{implementation|Lean}} +|LCT=yes +|site=https://lean-lang.org/}} {{language programming paradigm|functional}} {{language programming paradigm|dependent-types}} +'''Lean''' is a dependently typed programming language and proof assistant, similar to [[Rocq]] and [[Agda]]. It aims to bridge the gap between interactive and automated theorem proving by situating automated tools and methods in a framework that supports user interaction and the construction of fully specified axiomatic proofs. -'''Lean'''   is an open source theorem prover and programming language being developed at Microsoft Research. +As a proof assistant / theorem prover, Lean primarily benefits from Mathlib, a mechanized implementation of swaths of mathematics at the undergraduate and graduate level. -Lean aims to bridge the gap between interactive and automated theorem proving, by situating automated tools and methods in a framework that supports user interaction and the construction of fully specified axiomatic proofs. +As a general-purpose programming language, Lean benefits from its use as a theorem prover, as several features developed for the purpose of theorem proving, such as its dependent types system and its syntax-rewriting macros, also find much utility outside their original theorem proving contexts. -https://leanprover.github.io/about/ \ No newline at end of file +Lean 4 is the current major version of the language, being a bootstrapped rewrite of the older (and different) Lean 3 system. + +=== Citations === + +Frequently asked questions: https://lean-lang.org/faq/ \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Calculating-the-value-of-e b/Lang/Liberty-BASIC/Calculating-the-value-of-e new file mode 120000 index 0000000000..95f95733b8 --- /dev/null +++ b/Lang/Liberty-BASIC/Calculating-the-value-of-e @@ -0,0 +1 @@ +../../Task/Calculating-the-value-of-e/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Egyptian-division b/Lang/Liberty-BASIC/Egyptian-division new file mode 120000 index 0000000000..91346c7989 --- /dev/null +++ b/Lang/Liberty-BASIC/Egyptian-division @@ -0,0 +1 @@ +../../Task/Egyptian-division/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Hunt-the-Wumpus b/Lang/Liberty-BASIC/Hunt-the-Wumpus new file mode 120000 index 0000000000..4e2d0e150d --- /dev/null +++ b/Lang/Liberty-BASIC/Hunt-the-Wumpus @@ -0,0 +1 @@ +../../Task/Hunt-the-Wumpus/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Jacobsthal-numbers b/Lang/Liberty-BASIC/Jacobsthal-numbers new file mode 120000 index 0000000000..c1008ff58b --- /dev/null +++ b/Lang/Liberty-BASIC/Jacobsthal-numbers @@ -0,0 +1 @@ +../../Task/Jacobsthal-numbers/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Jaro-similarity b/Lang/Liberty-BASIC/Jaro-similarity new file mode 120000 index 0000000000..0f3ee067c6 --- /dev/null +++ b/Lang/Liberty-BASIC/Jaro-similarity @@ -0,0 +1 @@ +../../Task/Jaro-similarity/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Miller-Rabin-primality-test b/Lang/Liberty-BASIC/Miller-Rabin-primality-test deleted file mode 120000 index 01eccc1a73..0000000000 --- a/Lang/Liberty-BASIC/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Minesweeper-game b/Lang/Liberty-BASIC/Minesweeper-game new file mode 120000 index 0000000000..19abfc9a07 --- /dev/null +++ b/Lang/Liberty-BASIC/Minesweeper-game @@ -0,0 +1 @@ +../../Task/Minesweeper-game/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Numbers-which-are-not-the-sum-of-distinct-squares b/Lang/Liberty-BASIC/Numbers-which-are-not-the-sum-of-distinct-squares new file mode 120000 index 0000000000..18d07e8ad3 --- /dev/null +++ b/Lang/Liberty-BASIC/Numbers-which-are-not-the-sum-of-distinct-squares @@ -0,0 +1 @@ +../../Task/Numbers-which-are-not-the-sum-of-distinct-squares/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Numbers-with-equal-rises-and-falls b/Lang/Liberty-BASIC/Numbers-with-equal-rises-and-falls new file mode 120000 index 0000000000..019f830246 --- /dev/null +++ b/Lang/Liberty-BASIC/Numbers-with-equal-rises-and-falls @@ -0,0 +1 @@ +../../Task/Numbers-with-equal-rises-and-falls/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Poker-hand-analyser b/Lang/Liberty-BASIC/Poker-hand-analyser new file mode 120000 index 0000000000..3ed8c3b507 --- /dev/null +++ b/Lang/Liberty-BASIC/Poker-hand-analyser @@ -0,0 +1 @@ +../../Task/Poker-hand-analyser/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Primality-by-Wilsons-theorem b/Lang/Liberty-BASIC/Primality-by-Wilsons-theorem new file mode 120000 index 0000000000..d68ab9bb3f --- /dev/null +++ b/Lang/Liberty-BASIC/Primality-by-Wilsons-theorem @@ -0,0 +1 @@ +../../Task/Primality-by-Wilsons-theorem/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Quaternion-type b/Lang/Liberty-BASIC/Quaternion-type deleted file mode 120000 index 33da9602b0..0000000000 --- a/Lang/Liberty-BASIC/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Snake b/Lang/Liberty-BASIC/Snake new file mode 120000 index 0000000000..20a60d8427 --- /dev/null +++ b/Lang/Liberty-BASIC/Snake @@ -0,0 +1 @@ +../../Task/Snake/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Lilypond/00-LANG.txt b/Lang/Lilypond/00-LANG.txt index 5c24c70c93..9afe2b1bd9 100644 --- a/Lang/Lilypond/00-LANG.txt +++ b/Lang/Lilypond/00-LANG.txt @@ -1,9 +1 @@ -{{stub}} -{{language|lilypond -|site=http://www.lilypond.org/ -|hopl=no -}} - -The lilypond language is used by the lilypond score production software for describing the layout of musical score sheets. - -[[Category:Musical Notation]] \ No newline at end of file +#REDIRECT [[:Category:LilyPond]] \ No newline at end of file diff --git a/Lang/Locomotive-Basic/00-LANG.txt b/Lang/Locomotive-Basic/00-LANG.txt index 04db5b5ea8..5045a1b047 100644 --- a/Lang/Locomotive-Basic/00-LANG.txt +++ b/Lang/Locomotive-Basic/00-LANG.txt @@ -7,9 +7,9 @@ '''Locomotive BASIC''' is a variant of BASIC that is built into the ROM of the [[wp:Amstrad CPC|Amstrad CPC]] series of home computers introduced in 1984. In the 1980s, the CPC was a popular, slightly more expensive alternative to the Commodore C64/C128. It was not just suited for games but also office work because of its high resolution display and [[wp:CP/M|CP/M]] support. -The easiest way to use Locomotive BASIC today is [https://benchmarko.github.io/CPCBasic/cpcbasic.html CPCBasic], a very fast implementation in JavaScript which also allows easy pasting of code from Rosetta Code. Note that programs will run much faster in CPCBasic than on a real CPC. To slow down a program, add an extra delay loop to the main loop, e.g.:for delay=1 to 5:frame:nextwhich will pause for five frames or 0.1 seconds. +The easiest way to use Locomotive BASIC today is [https://benchmarko.github.io/CPCBasic/cpcbasic.html CPCBasic], a very fast implementation in JavaScript which also allows easy pasting of code from Rosetta Code. Note that programs will run much faster in CPCBasic than on a real CPC. To slow down a program, add an extra delay loop to the main loop, e.g. for delay=1 to 5:frame:nextwhich will pause for five frames or 0.1 seconds. -[https://www.retrovm.com/ CPCBox] is another option for the web browser, a whole-machine JavaScript CPC emulator mainly for games which has good compatibility but which lacks copy and paste support. +[https://retroshowcase.gr/cpcbox-master/ CPCBox] is another option for the web browser, a whole-machine JavaScript CPC emulator mainly for games which has good compatibility but which lacks copy and paste support. Locomotive BASIC can also be used via native CPC emulators such as [http://www.winape.net/ WinAPE] (Windows) or [http://sourceforge.net/projects/javacpc/ JavaCPC] (Windows/macOS/Linux). All these CPC emulators are also perfectly legal because Amstrad has given their permission for distributing CPC ROM images with emulators. @@ -19,14 +19,14 @@ Either use the CPCBasic browser-based Locomotive Basic emulator (https://benchma In CPCBasic, enter your program, e.g. -10 print "Hello World!" +10 print "Hello World!" into the "CPC Basic" text box at the top and then press the Run button below it. Output goes to the blue CPC screen below. You can also interact with the CPC screen directly if you first click on it with the mouse. The Reset button stops a running program and returns you to the Ready prompt. In a native emulator, just type -10 print "Hello World!" -run +10 print "Hello World!" +run to run your first Locomotive BASIC program. @@ -56,7 +56,7 @@ As on many other 8-bit machines of the era, BASIC programs are often extended wi Memory on the CPC 464 and 664 is subdivided into four 16 kB blocks (0 to 3), with block 3 at &c000 normally reserved for the screen. The CPC 6128 features a second 64 kB bank (blocks 4 to 7) which can be accessed from BASIC with [[wp:Bank switching|bank switching]] in block 1 (&4000 and &7fff), e.g. -out &7fff,&x11000100 +out &7fff,&x11000100 would make block 4 accessible in the address space of block 1.http://k1.dyndns.org/Vintage/Schneider%20CPC/Das%20Schneider%20CPC%20Systembuch/z87.htm This way, the entire 128 kB of memory can be used by BASIC. Alternatively, RSX commands for bank switching and copying between banks are included on the system discs and discussed in chapter 8 of the CPC user manual.http://www.cpcwiki.eu/index.php/User_Manual Even on the 64 kB models, it is possible to do [[wp:Multiple buffering|double buffering]] in BASIC by reserving another RAM block for the screen, drawing into the hidden screen, and then setting the CRTC screen address to the currently hidden screen with the BASIC [[wp:I/o port|port I/O]] command OUT. diff --git a/Lang/Locomotive-Basic/Abelian-sandpile-model b/Lang/Locomotive-Basic/Abelian-sandpile-model new file mode 120000 index 0000000000..e00a530896 --- /dev/null +++ b/Lang/Locomotive-Basic/Abelian-sandpile-model @@ -0,0 +1 @@ +../../Task/Abelian-sandpile-model/Locomotive-Basic \ No newline at end of file diff --git a/Lang/Locomotive-Basic/Animate-a-pendulum b/Lang/Locomotive-Basic/Animate-a-pendulum new file mode 120000 index 0000000000..32a0ee5149 --- /dev/null +++ b/Lang/Locomotive-Basic/Animate-a-pendulum @@ -0,0 +1 @@ +../../Task/Animate-a-pendulum/Locomotive-Basic \ No newline at end of file diff --git a/Lang/Locomotive-Basic/Dragon-curve b/Lang/Locomotive-Basic/Dragon-curve new file mode 120000 index 0000000000..2088f12a68 --- /dev/null +++ b/Lang/Locomotive-Basic/Dragon-curve @@ -0,0 +1 @@ +../../Task/Dragon-curve/Locomotive-Basic \ No newline at end of file diff --git a/Lang/Locomotive-Basic/Draw-a-cuboid b/Lang/Locomotive-Basic/Draw-a-cuboid new file mode 120000 index 0000000000..cbfb396b7f --- /dev/null +++ b/Lang/Locomotive-Basic/Draw-a-cuboid @@ -0,0 +1 @@ +../../Task/Draw-a-cuboid/Locomotive-Basic \ No newline at end of file diff --git a/Lang/Locomotive-Basic/Forest-fire b/Lang/Locomotive-Basic/Forest-fire new file mode 120000 index 0000000000..44a3c54d6a --- /dev/null +++ b/Lang/Locomotive-Basic/Forest-fire @@ -0,0 +1 @@ +../../Task/Forest-fire/Locomotive-Basic \ No newline at end of file diff --git a/Lang/Locomotive-Basic/Hilbert-curve b/Lang/Locomotive-Basic/Hilbert-curve new file mode 120000 index 0000000000..8355f1c6bf --- /dev/null +++ b/Lang/Locomotive-Basic/Hilbert-curve @@ -0,0 +1 @@ +../../Task/Hilbert-curve/Locomotive-Basic \ No newline at end of file diff --git a/Lang/Locomotive-Basic/Koch-curve b/Lang/Locomotive-Basic/Koch-curve new file mode 120000 index 0000000000..87294988f6 --- /dev/null +++ b/Lang/Locomotive-Basic/Koch-curve @@ -0,0 +1 @@ +../../Task/Koch-curve/Locomotive-Basic \ No newline at end of file diff --git a/Lang/Loglan82/AKS-test-for-primes b/Lang/Loglan82/AKS-test-for-primes new file mode 120000 index 0000000000..335d9d190f --- /dev/null +++ b/Lang/Loglan82/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/Loglan82 \ No newline at end of file diff --git a/Lang/Loglan82/Abundant-deficient-and-perfect-number-classifications b/Lang/Loglan82/Abundant-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..c3fb63599e --- /dev/null +++ b/Lang/Loglan82/Abundant-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant-deficient-and-perfect-number-classifications/Loglan82 \ No newline at end of file diff --git a/Lang/Loglan82/Abundant-odd-numbers b/Lang/Loglan82/Abundant-odd-numbers new file mode 120000 index 0000000000..282ee6e007 --- /dev/null +++ b/Lang/Loglan82/Abundant-odd-numbers @@ -0,0 +1 @@ +../../Task/Abundant-odd-numbers/Loglan82 \ No newline at end of file diff --git a/Lang/Loglan82/Bell-numbers b/Lang/Loglan82/Bell-numbers new file mode 120000 index 0000000000..7761831a2e --- /dev/null +++ b/Lang/Loglan82/Bell-numbers @@ -0,0 +1 @@ +../../Task/Bell-numbers/Loglan82 \ No newline at end of file diff --git a/Lang/Loglan82/CUSIP b/Lang/Loglan82/CUSIP new file mode 120000 index 0000000000..8aaccb215d --- /dev/null +++ b/Lang/Loglan82/CUSIP @@ -0,0 +1 @@ +../../Task/CUSIP/Loglan82 \ No newline at end of file diff --git a/Lang/Loglan82/Catalan-numbers b/Lang/Loglan82/Catalan-numbers new file mode 120000 index 0000000000..309128cccf --- /dev/null +++ b/Lang/Loglan82/Catalan-numbers @@ -0,0 +1 @@ +../../Task/Catalan-numbers/Loglan82 \ No newline at end of file diff --git a/Lang/Loglan82/Cumulative-standard-deviation b/Lang/Loglan82/Cumulative-standard-deviation new file mode 120000 index 0000000000..e030ba56eb --- /dev/null +++ b/Lang/Loglan82/Cumulative-standard-deviation @@ -0,0 +1 @@ +../../Task/Cumulative-standard-deviation/Loglan82 \ No newline at end of file diff --git a/Lang/Loglan82/Day-of-the-week b/Lang/Loglan82/Day-of-the-week new file mode 120000 index 0000000000..65e7a590f5 --- /dev/null +++ b/Lang/Loglan82/Day-of-the-week @@ -0,0 +1 @@ +../../Task/Day-of-the-week/Loglan82 \ No newline at end of file diff --git a/Lang/Loglan82/Diversity-prediction-theorem b/Lang/Loglan82/Diversity-prediction-theorem new file mode 120000 index 0000000000..99f7aed5fc --- /dev/null +++ b/Lang/Loglan82/Diversity-prediction-theorem @@ -0,0 +1 @@ +../../Task/Diversity-prediction-theorem/Loglan82 \ No newline at end of file diff --git a/Lang/Loglan82/Dot-product b/Lang/Loglan82/Dot-product new file mode 120000 index 0000000000..e65fed671f --- /dev/null +++ b/Lang/Loglan82/Dot-product @@ -0,0 +1 @@ +../../Task/Dot-product/Loglan82 \ No newline at end of file diff --git a/Lang/Loglan82/Dutch-national-flag-problem b/Lang/Loglan82/Dutch-national-flag-problem new file mode 120000 index 0000000000..80274c2f7b --- /dev/null +++ b/Lang/Loglan82/Dutch-national-flag-problem @@ -0,0 +1 @@ +../../Task/Dutch-national-flag-problem/Loglan82 \ No newline at end of file diff --git a/Lang/Loglan82/Equilibrium-index b/Lang/Loglan82/Equilibrium-index new file mode 120000 index 0000000000..99b2d35b94 --- /dev/null +++ b/Lang/Loglan82/Equilibrium-index @@ -0,0 +1 @@ +../../Task/Equilibrium-index/Loglan82 \ No newline at end of file diff --git a/Lang/Loglan82/Ethiopian-multiplication b/Lang/Loglan82/Ethiopian-multiplication new file mode 120000 index 0000000000..13a8b5d45c --- /dev/null +++ b/Lang/Loglan82/Ethiopian-multiplication @@ -0,0 +1 @@ +../../Task/Ethiopian-multiplication/Loglan82 \ No newline at end of file diff --git a/Lang/Loglan82/Factors-of-an-integer b/Lang/Loglan82/Factors-of-an-integer new file mode 120000 index 0000000000..106a23d5a7 --- /dev/null +++ b/Lang/Loglan82/Factors-of-an-integer @@ -0,0 +1 @@ +../../Task/Factors-of-an-integer/Loglan82 \ No newline at end of file diff --git a/Lang/Loglan82/Gamma-function b/Lang/Loglan82/Gamma-function new file mode 120000 index 0000000000..e6dce092fb --- /dev/null +++ b/Lang/Loglan82/Gamma-function @@ -0,0 +1 @@ +../../Task/Gamma-function/Loglan82 \ No newline at end of file diff --git a/Lang/Loglan82/Hello-world-Text b/Lang/Loglan82/Hello-world-Text new file mode 120000 index 0000000000..02b527238f --- /dev/null +++ b/Lang/Loglan82/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Loglan82 \ No newline at end of file diff --git a/Lang/Loglan82/Horners-rule-for-polynomial-evaluation b/Lang/Loglan82/Horners-rule-for-polynomial-evaluation new file mode 120000 index 0000000000..5eca5139bd --- /dev/null +++ b/Lang/Loglan82/Horners-rule-for-polynomial-evaluation @@ -0,0 +1 @@ +../../Task/Horners-rule-for-polynomial-evaluation/Loglan82 \ No newline at end of file diff --git a/Lang/Loglan82/Josephus-problem b/Lang/Loglan82/Josephus-problem new file mode 120000 index 0000000000..74e740313f --- /dev/null +++ b/Lang/Loglan82/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/Loglan82 \ No newline at end of file diff --git a/Lang/Loglan82/Levenshtein-distance b/Lang/Loglan82/Levenshtein-distance new file mode 120000 index 0000000000..64975523f2 --- /dev/null +++ b/Lang/Loglan82/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/Loglan82 \ No newline at end of file diff --git a/Lang/Loglan82/Long-year b/Lang/Loglan82/Long-year new file mode 120000 index 0000000000..b249596823 --- /dev/null +++ b/Lang/Loglan82/Long-year @@ -0,0 +1 @@ +../../Task/Long-year/Loglan82 \ No newline at end of file diff --git a/Lang/Loglan82/Loops-Do-while b/Lang/Loglan82/Loops-Do-while new file mode 120000 index 0000000000..e038a12c06 --- /dev/null +++ b/Lang/Loglan82/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/Loglan82 \ No newline at end of file diff --git a/Lang/Loglan82/Loops-For-with-a-specified-step b/Lang/Loglan82/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..bace3aec2b --- /dev/null +++ b/Lang/Loglan82/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/Loglan82 \ No newline at end of file diff --git a/Lang/Loglan82/M-bius-function b/Lang/Loglan82/M-bius-function new file mode 120000 index 0000000000..82e1041f7d --- /dev/null +++ b/Lang/Loglan82/M-bius-function @@ -0,0 +1 @@ +../../Task/M-bius-function/Loglan82 \ No newline at end of file diff --git a/Lang/Loglan82/Monty-Hall-problem b/Lang/Loglan82/Monty-Hall-problem new file mode 120000 index 0000000000..3c5ec1bb89 --- /dev/null +++ b/Lang/Loglan82/Monty-Hall-problem @@ -0,0 +1 @@ +../../Task/Monty-Hall-problem/Loglan82 \ No newline at end of file diff --git a/Lang/Loglan82/Shoelace-formula-for-polygonal-area b/Lang/Loglan82/Shoelace-formula-for-polygonal-area new file mode 120000 index 0000000000..7a3facc57c --- /dev/null +++ b/Lang/Loglan82/Shoelace-formula-for-polygonal-area @@ -0,0 +1 @@ +../../Task/Shoelace-formula-for-polygonal-area/Loglan82 \ No newline at end of file diff --git a/Lang/Loglan82/Statistics-Basic b/Lang/Loglan82/Statistics-Basic new file mode 120000 index 0000000000..06f2b88d7e --- /dev/null +++ b/Lang/Loglan82/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/Loglan82 \ No newline at end of file diff --git a/Lang/Loglan82/Statistics-Normal-distribution b/Lang/Loglan82/Statistics-Normal-distribution new file mode 120000 index 0000000000..c0cf6b079d --- /dev/null +++ b/Lang/Loglan82/Statistics-Normal-distribution @@ -0,0 +1 @@ +../../Task/Statistics-Normal-distribution/Loglan82 \ No newline at end of file diff --git a/Lang/Loglan82/Tau-number b/Lang/Loglan82/Tau-number new file mode 120000 index 0000000000..0f86291ac1 --- /dev/null +++ b/Lang/Loglan82/Tau-number @@ -0,0 +1 @@ +../../Task/Tau-number/Loglan82 \ No newline at end of file diff --git a/Lang/Logo/Associative-array-Creation b/Lang/Logo/Associative-array-Creation deleted file mode 120000 index 3776b1b4e9..0000000000 --- a/Lang/Logo/Associative-array-Creation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Associative-array-Creation/Logo \ No newline at end of file diff --git a/Lang/Logo/Merge-and-aggregate-datasets b/Lang/Logo/Merge-and-aggregate-datasets new file mode 120000 index 0000000000..f9a42bcf33 --- /dev/null +++ b/Lang/Logo/Merge-and-aggregate-datasets @@ -0,0 +1 @@ +../../Task/Merge-and-aggregate-datasets/Logo \ No newline at end of file diff --git a/Lang/Logo/Sort-three-variables b/Lang/Logo/Sort-three-variables new file mode 120000 index 0000000000..98d62a0bb1 --- /dev/null +++ b/Lang/Logo/Sort-three-variables @@ -0,0 +1 @@ +../../Task/Sort-three-variables/Logo \ No newline at end of file diff --git a/Lang/Logo/Sparkline-in-unicode b/Lang/Logo/Sparkline-in-unicode new file mode 120000 index 0000000000..d2b466f59a --- /dev/null +++ b/Lang/Logo/Sparkline-in-unicode @@ -0,0 +1 @@ +../../Task/Sparkline-in-unicode/Logo \ No newline at end of file diff --git a/Lang/Lua/100-doors b/Lang/Lua/100-doors deleted file mode 120000 index ce373fa8af..0000000000 --- a/Lang/Lua/100-doors +++ /dev/null @@ -1 +0,0 @@ -../../Task/100-doors/Lua \ No newline at end of file diff --git a/Lang/Lua/Bioinformatics-base-count b/Lang/Lua/Bioinformatics-base-count deleted file mode 120000 index cb9548dcc8..0000000000 --- a/Lang/Lua/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Lua \ No newline at end of file diff --git a/Lang/Lua/Calkin-Wilf-sequence b/Lang/Lua/Calkin-Wilf-sequence new file mode 120000 index 0000000000..1f9b22fde7 --- /dev/null +++ b/Lang/Lua/Calkin-Wilf-sequence @@ -0,0 +1 @@ +../../Task/Calkin-Wilf-sequence/Lua \ No newline at end of file diff --git a/Lang/Lua/Check-input-device-is-a-terminal b/Lang/Lua/Check-input-device-is-a-terminal new file mode 120000 index 0000000000..fdc01bb562 --- /dev/null +++ b/Lang/Lua/Check-input-device-is-a-terminal @@ -0,0 +1 @@ +../../Task/Check-input-device-is-a-terminal/Lua \ No newline at end of file diff --git a/Lang/Lua/Demings-funnel b/Lang/Lua/Demings-funnel new file mode 120000 index 0000000000..bfeba4e463 --- /dev/null +++ b/Lang/Lua/Demings-funnel @@ -0,0 +1 @@ +../../Task/Demings-funnel/Lua \ No newline at end of file diff --git a/Lang/Lua/Duffinian-numbers b/Lang/Lua/Duffinian-numbers new file mode 120000 index 0000000000..3d384f7bda --- /dev/null +++ b/Lang/Lua/Duffinian-numbers @@ -0,0 +1 @@ +../../Task/Duffinian-numbers/Lua \ No newline at end of file diff --git a/Lang/Lua/Empty-program b/Lang/Lua/Empty-program deleted file mode 120000 index 451d4b192d..0000000000 --- a/Lang/Lua/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Lua \ No newline at end of file diff --git a/Lang/Lua/GUI-component-interaction b/Lang/Lua/GUI-component-interaction new file mode 120000 index 0000000000..da7428ad7e --- /dev/null +++ b/Lang/Lua/GUI-component-interaction @@ -0,0 +1 @@ +../../Task/GUI-component-interaction/Lua \ No newline at end of file diff --git a/Lang/Lua/Gauss-Jordan-matrix-inversion b/Lang/Lua/Gauss-Jordan-matrix-inversion new file mode 120000 index 0000000000..4e412c8561 --- /dev/null +++ b/Lang/Lua/Gauss-Jordan-matrix-inversion @@ -0,0 +1 @@ +../../Task/Gauss-Jordan-matrix-inversion/Lua \ No newline at end of file diff --git a/Lang/Lua/Generate-random-chess-position b/Lang/Lua/Generate-random-chess-position new file mode 120000 index 0000000000..7d17633430 --- /dev/null +++ b/Lang/Lua/Generate-random-chess-position @@ -0,0 +1 @@ +../../Task/Generate-random-chess-position/Lua \ No newline at end of file diff --git a/Lang/Lua/Hello-world-Line-printer b/Lang/Lua/Hello-world-Line-printer new file mode 120000 index 0000000000..1ade14f20f --- /dev/null +++ b/Lang/Lua/Hello-world-Line-printer @@ -0,0 +1 @@ +../../Task/Hello-world-Line-printer/Lua \ No newline at end of file diff --git a/Lang/Lua/Jacobsthal-numbers b/Lang/Lua/Jacobsthal-numbers new file mode 120000 index 0000000000..ff787752c3 --- /dev/null +++ b/Lang/Lua/Jacobsthal-numbers @@ -0,0 +1 @@ +../../Task/Jacobsthal-numbers/Lua \ No newline at end of file diff --git a/Lang/Lua/Jordan-P-lya-numbers b/Lang/Lua/Jordan-P-lya-numbers new file mode 120000 index 0000000000..860eeeaaa4 --- /dev/null +++ b/Lang/Lua/Jordan-P-lya-numbers @@ -0,0 +1 @@ +../../Task/Jordan-P-lya-numbers/Lua \ No newline at end of file diff --git a/Lang/Lua/Juggler-sequence b/Lang/Lua/Juggler-sequence new file mode 120000 index 0000000000..94ab059422 --- /dev/null +++ b/Lang/Lua/Juggler-sequence @@ -0,0 +1 @@ +../../Task/Juggler-sequence/Lua \ No newline at end of file diff --git a/Lang/Lua/Knapsack-problem-Bounded b/Lang/Lua/Knapsack-problem-Bounded new file mode 120000 index 0000000000..edddb60b00 --- /dev/null +++ b/Lang/Lua/Knapsack-problem-Bounded @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Bounded/Lua \ No newline at end of file diff --git a/Lang/Lua/Legendre-prime-counting-function b/Lang/Lua/Legendre-prime-counting-function new file mode 120000 index 0000000000..cf72af7d74 --- /dev/null +++ b/Lang/Lua/Legendre-prime-counting-function @@ -0,0 +1 @@ +../../Task/Legendre-prime-counting-function/Lua \ No newline at end of file diff --git a/Lang/Lua/Miller-Rabin-primality-test b/Lang/Lua/Miller-Rabin-primality-test deleted file mode 120000 index 45a2ff22f4..0000000000 --- a/Lang/Lua/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Lua \ No newline at end of file diff --git a/Lang/Lua/Numbers-with-equal-rises-and-falls b/Lang/Lua/Numbers-with-equal-rises-and-falls new file mode 120000 index 0000000000..5900c5ba75 --- /dev/null +++ b/Lang/Lua/Numbers-with-equal-rises-and-falls @@ -0,0 +1 @@ +../../Task/Numbers-with-equal-rises-and-falls/Lua \ No newline at end of file diff --git a/Lang/Lua/Parse-an-IP-Address b/Lang/Lua/Parse-an-IP-Address new file mode 120000 index 0000000000..aa0f24a93c --- /dev/null +++ b/Lang/Lua/Parse-an-IP-Address @@ -0,0 +1 @@ +../../Task/Parse-an-IP-Address/Lua \ No newline at end of file diff --git a/Lang/Lua/Parsing-RPN-calculator-algorithm b/Lang/Lua/Parsing-RPN-calculator-algorithm deleted file mode 120000 index 397c1ccfd1..0000000000 --- a/Lang/Lua/Parsing-RPN-calculator-algorithm +++ /dev/null @@ -1 +0,0 @@ -../../Task/Parsing-RPN-calculator-algorithm/Lua \ No newline at end of file diff --git a/Lang/Lua/Quaternion-type b/Lang/Lua/Quaternion-type deleted file mode 120000 index 09499b7f9c..0000000000 --- a/Lang/Lua/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Lua \ No newline at end of file diff --git a/Lang/Lua/Ramer-Douglas-Peucker-line-simplification b/Lang/Lua/Ramer-Douglas-Peucker-line-simplification new file mode 120000 index 0000000000..516d951928 --- /dev/null +++ b/Lang/Lua/Ramer-Douglas-Peucker-line-simplification @@ -0,0 +1 @@ +../../Task/Ramer-Douglas-Peucker-line-simplification/Lua \ No newline at end of file diff --git a/Lang/Lua/Sleeping-Beauty-problem b/Lang/Lua/Sleeping-Beauty-problem new file mode 120000 index 0000000000..75e2ee6eb2 --- /dev/null +++ b/Lang/Lua/Sleeping-Beauty-problem @@ -0,0 +1 @@ +../../Task/Sleeping-Beauty-problem/Lua \ No newline at end of file diff --git a/Lang/Lua/Sorting-Algorithms-Circle-Sort b/Lang/Lua/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index e6dc299d24..0000000000 --- a/Lang/Lua/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Lua \ No newline at end of file diff --git a/Lang/Lua/Strassens-algorithm b/Lang/Lua/Strassens-algorithm new file mode 120000 index 0000000000..9da800cb02 --- /dev/null +++ b/Lang/Lua/Strassens-algorithm @@ -0,0 +1 @@ +../../Task/Strassens-algorithm/Lua \ No newline at end of file diff --git a/Lang/Lua/Sum-of-elements-below-main-diagonal-of-matrix b/Lang/Lua/Sum-of-elements-below-main-diagonal-of-matrix new file mode 120000 index 0000000000..63a3cd2cf9 --- /dev/null +++ b/Lang/Lua/Sum-of-elements-below-main-diagonal-of-matrix @@ -0,0 +1 @@ +../../Task/Sum-of-elements-below-main-diagonal-of-matrix/Lua \ No newline at end of file diff --git a/Lang/Lua/Summarize-primes b/Lang/Lua/Summarize-primes new file mode 120000 index 0000000000..601bc61d3c --- /dev/null +++ b/Lang/Lua/Summarize-primes @@ -0,0 +1 @@ +../../Task/Summarize-primes/Lua \ No newline at end of file diff --git a/Lang/Lua/Super-d-numbers b/Lang/Lua/Super-d-numbers new file mode 120000 index 0000000000..64e775e306 --- /dev/null +++ b/Lang/Lua/Super-d-numbers @@ -0,0 +1 @@ +../../Task/Super-d-numbers/Lua \ No newline at end of file diff --git a/Lang/Lua/Terminal-control-Hiding-the-cursor b/Lang/Lua/Terminal-control-Hiding-the-cursor new file mode 120000 index 0000000000..68700a27b1 --- /dev/null +++ b/Lang/Lua/Terminal-control-Hiding-the-cursor @@ -0,0 +1 @@ +../../Task/Terminal-control-Hiding-the-cursor/Lua \ No newline at end of file diff --git a/Lang/Lua/Terminal-control-Unicode-output b/Lang/Lua/Terminal-control-Unicode-output new file mode 120000 index 0000000000..b9be1e6352 --- /dev/null +++ b/Lang/Lua/Terminal-control-Unicode-output @@ -0,0 +1 @@ +../../Task/Terminal-control-Unicode-output/Lua \ No newline at end of file diff --git a/Lang/Lua/Total-circles-area b/Lang/Lua/Total-circles-area new file mode 120000 index 0000000000..368862d6f6 --- /dev/null +++ b/Lang/Lua/Total-circles-area @@ -0,0 +1 @@ +../../Task/Total-circles-area/Lua \ No newline at end of file diff --git a/Lang/Lua/Update-a-configuration-file b/Lang/Lua/Update-a-configuration-file new file mode 120000 index 0000000000..75ad1d2a09 --- /dev/null +++ b/Lang/Lua/Update-a-configuration-file @@ -0,0 +1 @@ +../../Task/Update-a-configuration-file/Lua \ No newline at end of file diff --git a/Lang/Lua/Use-another-language-to-call-a-function b/Lang/Lua/Use-another-language-to-call-a-function new file mode 120000 index 0000000000..05e8f054e4 --- /dev/null +++ b/Lang/Lua/Use-another-language-to-call-a-function @@ -0,0 +1 @@ +../../Task/Use-another-language-to-call-a-function/Lua \ No newline at end of file diff --git a/Lang/Lua/Wagstaff-primes b/Lang/Lua/Wagstaff-primes new file mode 120000 index 0000000000..c8cec659a4 --- /dev/null +++ b/Lang/Lua/Wagstaff-primes @@ -0,0 +1 @@ +../../Task/Wagstaff-primes/Lua \ No newline at end of file diff --git a/Lang/Lua/Wieferich-primes b/Lang/Lua/Wieferich-primes new file mode 120000 index 0000000000..ac68d34377 --- /dev/null +++ b/Lang/Lua/Wieferich-primes @@ -0,0 +1 @@ +../../Task/Wieferich-primes/Lua \ No newline at end of file diff --git a/Lang/Lua/Wilson-primes-of-order-n b/Lang/Lua/Wilson-primes-of-order-n new file mode 120000 index 0000000000..338cbe60ca --- /dev/null +++ b/Lang/Lua/Wilson-primes-of-order-n @@ -0,0 +1 @@ +../../Task/Wilson-primes-of-order-n/Lua \ No newline at end of file diff --git a/Lang/M2000-Interpreter/00-LANG.txt b/Lang/M2000-Interpreter/00-LANG.txt index ed77df4b81..ab29824f45 100644 --- a/Lang/M2000-Interpreter/00-LANG.txt +++ b/Lang/M2000-Interpreter/00-LANG.txt @@ -9,7 +9,7 @@ |gc=allowed |hopl=no }} -M2000 is an interpreter running on its own Environment written in Visual Basic 6, as an open source project and can be found in GitHub[https://github.com/M2000Interpreter/Version9]. Current version is 12, revision 13. See [[M2000 Interpreter Implementation]] +M2000 is an interpreter running on its own Environment written in Visual Basic 6, as an open source project and can be found in GitHub[https://github.com/M2000Interpreter/Environment]. Current version is 14, revision 8. See [[M2000 Interpreter Implementation]] {{language programming paradigm|Imperative}} {{language programming paradigm|Object-oriented}} {{Language programming paradigm|Event-driven}} @@ -21,12 +21,68 @@ M2000 has two set of vocabularies, one with English identifiers and one with Gre M2000 start as an experimental interpreted language, using a Module in Module idea (like a Procedure in Procedure) where each inner Module is closed for modification, but open for expansion, by replacing code at run time. Source code executed as is, without second interpretation of a simple form, although block of code arranged for execution in a manner of consuming code (code which executed deleted, code in a loop kept as a copy for next iteration). +We can use BASIC type statement's. Although there are some differences. Like the FOR NEXT: + +SET SWITCHES "+FOR" +// WHY ? BECAUSE WHEN STEP IS POSITIVE (+1 HERE) +// WE GET ITERATION IF START VALUE IS LESS OR EQUAL THE LAST VALUE +FOR I=10 TO 0 + PRINT "NEVER PRINT - IS LIKE BASIC" +NEXT +SET SWITCHES "+DIM" +// WHY ? BECAUSE DIM MAKE AN ARRAY FROM 0 TO TOP VALUE (10) +DIM A(10)=1 +PRINT LEN(A())=11, A(0), A(10), "BASIC" + +SET SWITCHES "-FOR" ' THE DEFAULT +// WHY ? BECAUSE EVERY TIME ITERATE FROM START VALUE TO END VALUE +FOR I=10 TO 0 + PRINT "ALWAYS PRINT - IS NOT LIKE BASIC" +NEXT + +SET SWITCHES "-DIM" +// WHY ? BECAUSE DIM MAKE AN ARRAY N (10) ITEMS +DIM A(10)=1 +PRINT LEN(A())=10, A(0), A(9), "M2000" +DIM B(0 TO 10)=1 ' WE CAN DEFINE MIN AND MAX INDEX (CAN BE NEGATIVE) +PRINT LEN(B())=11, B(0), B(10), "M2000" + + Module's may be Global, or local to other modules. We can define global modules in a module, and all these definitions deleted at the end of module execution. Because we have to execute the definition of a module, we can select definition, or load definition before we call the module. Also modules can be part of object's of type Group. A module can't call itself unless we use Call module_name. The standard call is by using only the name of module. So from a module we can call local modules or global, but we can't call parent module (if isn't global). In a group we can call anything like a module plus the modules of the groups. +We can use labels and line numbers (each number is just a label). After a line number we can place statement. Static subs/functions have same scope as the module scope. Here SomethingElse() is like Module as a program, with own scope. + + +MODULE alfa { + FUNCTION SomethingElse(A, ZZ) { + =A/ZZ ' WE CAN'T READ Z HERE + } + 000 READ X + 001 Z=10 + 005 GOSUB alfa + 010 COMPUTE(&X) + 020 PRINT @MUL10(X), SomethingElse(@MUL10(X), Z) + 030 IF X<20 THEN 10 + 040 GOSUB alfa + 050 END + 060 SUB COMPUTE(&A) + 070 A++ + 080 Z++ // SIDE EFFECT + 090 END SUB + 100 FUNCTION MUL10(A) + 110 =A*Z + 120 END FUNCTION +alfa: + 130 PRINT "-------------------------" + 140 RETURN +} +alfa 14 + + We can change a inner module at the calling of a module, see the example: We call inner Beta in two stages. At the second stage we change inner Theta with Theta2. This is the decoration of Beta with Theta as Theta2. This is a temporary decoration because Beta after execution erase any new identifier including Theta. So each time we call Beta, statement Module Theta make this module unless a decoration stop it. ====English Vocabulary==== -Module Beta { +Module Beta { Module Theta (x){ Print "This is Theta, we get x=";x } @@ -38,8 +94,141 @@ Module Theta2 (x) { } Beta ; Theta as Theta2 + +This is a rare case. Most cases use alternative definitions: + +Module Beta { + Module Theta (x){ + Print "This is Theta, we get x=";x + } + For i=1 to 3 : Theta i : Next i +} +Beta +Module Beta { + Module Theta (x) { + Print "This is Theta2, we get x=";x + } + For i=1 to 3 : Theta i : Next i +} +Beta + + +Another variation is the use of function pass by reference: + +Module Beta { + Read &theta() + For i=1 to 3 :Call Theta(i) : Next i +} +Function Theta(x){ + Print "This is Theta, we get x=";x +} +Function Theta2(x) { + Print "This is Theta2, we get x=";x +} +Beta &Theta() +Beta &Theta2() + + +Or a more compact way to use a Group: + +Module Beta { + Read That + For i=1 to 3 :Call That.Theta(i) : Next i +} +Group A { + Function Theta(x){ + Print "This is Theta, we get x=";x + } +} +Group B { + Function Theta(x) { + Print "This is Theta2, we get x=";x + } +} +Beta A +Beta B + + +Or a more compact way to use a Class: + +Module Beta { + Read That + For i=1 to 3 :Call That.Theta(i) : Next i +} +Class Something { +Private: + string message=letter$ ' letter$ read from stack of values a string +Public: + Function Theta(x){ + Print .message;x + } +} +A=Something("This is Theta, we get x=") +B=Something("This is Theta2, we get x=") +Beta A +Beta B + + + +Or a variant of class which made an object which return value + +Module Beta { + Read &That + For i=1 to 3 :Print That(i) : Next i +} +Class Something { +Private: + string message=letter$ ' letter$ read from stack of values a string +Public: + Set { + Read This + } + Value (x){ ' (x) change to: Read x + = .message + x ' .message is string (x can be string or number) + } +} +A=Something("This is Theta, we get x=") +Beta &A +A=Something("This is Theta2, we get x=") +Beta &A + + +Or by using lambda functions (functions which we hold in variables, with closures) + + +Module Beta { + Read &That + For i=1 to 3 :Print That(i) : Next i +} +m="This is Theta, we get x=" +A=lambda m (x)->m + x ' one line lambda function +Beta &A +' we can use multiline lambda functions +A=lambda m="This is Theta2, we get x=" (x)->{ + =m + x +} +Beta &A + + +The same but now we bass by value (we remove & from the caller and the callee too: + + +Module Beta { + Read That + For i=1 to 3 :Print That(i) : Next i +} +m="This is Theta, we get x=" +A=lambda m (x)->m + x ' one line lambda function +Beta A +' we can use multiline lambda functions +A=lambda m="This is Theta2, we get x=" (x)->{ + =m + x +} +Beta A + + ====Greek Vocabulary==== -Τμήμα Βήτα { +Τμήμα Βήτα { Τμήμα Θήτα (χ){ Τύπωσε "Αυτό είναι το Θήτα, θα πάρουμε το χ=";χ } @@ -52,9 +241,9 @@ Beta ; Theta as Theta2 Βήτα ; Θήτα ως Θήτα2 -As we can see from code, some statements are like BASIC, except the use of curly brackets {}. Check the code below. We have a Module (as a Procedure), where we define some functions and some variables, as entities. These entities defined in every call to CheckIt, and erased when execution return from CheckIt. By default every parameter in M2000 pass by value. We define two functions, Alfa() where we set type for parameter x and ExpType$() where we not set type for x, and we wish to return the name of type when we make a call. +As we can see from code, some statements are like BASIC, except the use of curly brackets {}. Check the code below. We have a Module (as a Procedure), where we define some functions and some variables, as entities. These entities defined in every call to CheckIt, and erased when execution return from CheckIt. By default every parameter in M2000 pass by value. We define a function, Alfa() where we set type for parameter. -Module CheckIt { +Module CheckIt { \\ We can't call something out of this module Function Alfa(X as double) { =X**2 @@ -70,14 +259,13 @@ As we can see from code, some statements are like BASIC, except the use of curly Print Type$(Z) Currency Z1=212.12, Z2=323233.12, Z3=223212323323.12 Print Z1, Z2, Z3 - Def ExpType$(x)=Type$(x) - Print ExpType$(Z1+Z2) ' Currency - Print ExpType$(Z1*Z2) ' Currency - Print ExpType$(Z2*Z3) ' Double (Currency can't hold this number) + Print Type$(Z1+Z2) ' Currency + Print Type$(Z1*Z2) ' Currency + Print Type$(Z2*Z3) ' Double (Currency can't hold this number) \\ Integer, Long, Single, Currency, Decimal - Print ExpType$(10%), ExpType$(10&), ExpType$(10~), ExpType$(10#), ExpType$(10@) + Print Type$(10%), Type$(10&), Type$(10~), Type$(10#), Type$(10@) \\ Without symbol is a Double - Print ExpType$(10) + Print Type$(10) } \\ We call it CheckIt @@ -92,7 +280,7 @@ A statement Input Alfa$ can input characters for a string or for object typed gr Types are strong for values with a name (variables, constants), but weak for items in containers. In a container (Array, Inventory and Stack) we can place anything including other containers. We can bypass the "strong" capability but this isn't a practice for good programming. Internal or variables are of type of Variant, so we can make a reference of A to A$ and we can save a string "1212" and read from A the number 1212. - + Module AKindOfMess { a=10@ Print Type$(a)="Decimal" @@ -131,7 +319,7 @@ Print Error$="" So check this for proper use of types. -Module CheckInt { +Module CheckInt { A%=1212212.12@ Print A% ' 1212212 A%=1212212.52@ @@ -149,18 +337,19 @@ So check this for proper use of types. } CheckInt -So we say about Integer Variables, and no Integer Numeric Type. Like in Basic, M2000 is not case sensitive (except for labels), so A% and a% is the same. We may have A, A$ and A% as three variables, or A(), A%(), A$() as arrays or and functions. We can use name(@ ) to call function and not array if we have each with same name. +So we say about Integer Variables, and no Integer Numeric Type. Like in Basic, M2000 is not case sensitive (except for labels), so A% and a% is the same. We may have A, A$ and A% as three variables, or A(), A%(), A$() as arrays or and functions. We can use name(* ) to call function and not array if we have each with same name. -Dim A(10)=1 +Dim A(10)=1 Def A(x)=x**2 -Print A(3), A(@ 4) +Print A(3), A(* 4) ' change @ to * from later versions + By default all variables are local. M2000 uses heap to store local variables, not stack. We can use global variables, but a local definition hide a global one. We can make global variables for temporary use (at return from module which we define a global, this global erased). A global definition in an already defined global variable with same name, hide for temporary use the old global variable. It is easy to make modules, with modules, functions, variables, arrays. We can use subroutines when we want code in a module or a function to used more than once. We can use local variables inside subroutines. In subroutines we can use module's variables, functions, subroutines. Until here we see something like BASIC, except that variables are local to modules and functions, but can be used by subroutines. Also we have see that we can replace a module in a module when we call it. With this replacement we can use a predefined logic with some "terminals", modules that get parameters and do final things. We can make global modules and functions in local modules and functions, but these exist until creator module or function exit. -M2000 can be used for more advanced programming. Modules and functions can be members of Groups. Groups are values. So a function can return a Group. +M2000 can be used for more advanced programming. Modules and functions can be members of Groups. Groups are values. So a function can return a Group. ===Stack of Values=== Modules and functions get parameters in a stack. Modules get the parent stack with parameters, and functions get a new stack with parameters. Modules return from call and are responsible to clear as needed the stack. Functions drop the stack after the call from an expression. A module can return entities in stack, if we want to do that. We can call a module and pass parameters, and that module can call other module leaving parameters in stack to be read in last module. @@ -170,7 +359,7 @@ In the example below (y) is a Read y for module definition. Early versions of la As we see alfa has no read statement, because before get the first number need to make two modules, and then pop one number and call a module passing current stack, so if choose beta, then the second value feed y from a read y statement. - + module alfa { module beta (y) { print y**3 @@ -195,15 +384,13 @@ function sumall { print sumall(1,2,3,4,5,6,7)=28 - - ===OOP=== Groups are objects for M2000. We can use them as values, and if we want we can use pointers for groups (but we can make a lot of programs without using pointers to groups). Without using pointer, a Group may be local with a name in a Module or can be in a container like array, inventory (a type of map) and stack objects, without name. Groups may have private and public members, may have properties as read only, may get value and return value, and may have operators. Members of Groups can be anything, including other groups. Groups may have events too. We can make groups by using CLASS statement or by using own function which return a Group or a pointer to Group. A special object is the lambda object, which may have a number of closures, and have to faces, a variable and a function: -Module Delta { +Module Delta { \\ Make a group like a lambda \\ A Class make a Global Function \\ (in a group a Class definition make a group member, not a global function) @@ -244,7 +431,7 @@ We can place a lambda function as closure in a lambda function, and we can build a class define a type too. We can make a class from other classes too. We can make inner classes too. - + Form 80,50 \\ counters supposed we provide them from a file global LastCustomerId=100, ReportId=80 @@ -342,7 +529,7 @@ While M { Until now we see modules/functions/subs for procedural programming, Groups for OOP, Groups as lambda functions and lambda functions for functional programming. We can use events for groups and for COM objects, including GUI objects. -Module Beta { +Module Beta { Group WithEvents Alpha { Event "One" Module DoIt (x) { @@ -380,7 +567,7 @@ Until now we see that programming with events can be used in M2000. There is an Modules may have Threads, part of modules that can be executed in intervals, can be halted, or can be released, and can be erased. Each thread has own stack and may have own static variables (Modules and Functions also may have static variables), but can use modules variables and functions/modules/subs. Threads can run concurrent (thread return to task manager after execution of a statement or a block of statements) or sequential (a thread has to exit from interval to start other thread) -Module Zeta { +Module Zeta { k=10 Thread { k++ @@ -399,7 +586,7 @@ Zeta M2000 Interpreter can work with Structures and Buffers. Buffer is a memory block and Structure can define types of memory, and a buffer can hold arrays of structures. Each structure can be made from other structures or arrays of structures, and may have unions. We can use buffers for code execution (writing machine code), using standard buffers (not executable), for data holder. Also we can use Buffers calling external dll and passing by address. -Module Kappa { +Module Kappa { Function Theta(x) { Structure Points_single { x as single @@ -415,4 +602,26 @@ M2000 Interpreter can work with Structures and Buffers. Buffer is a memory block \\ Print Eval(P, 0!x)=1212.12~, Eval(P, 0!y)=21.1212~ } -Kappa \ No newline at end of file +Kappa +Module Kappa { + Function Theta(x) { + Structure Points_single { + x as single + y as single + } + Buffer Clear Points as Points_single*x + =Points + } + P=Theta(100) + Print Len(P)=800 ' 2x4x100 bytes + ' new way to use fields of structure + P[0]|x=1212.12 + P[0]|y=21.1212 + Print Eval(P, 0!x)=1212.12~, Eval(P, 0!y)=21.1212~ + Print P[0]|x=1212.12~, P[0]|y=21.1212~ + P[4]=P[0] ' copy of structure at offser 4*len of structrure Points_single + ' p(0) is address of first struct, p(4) is address of 5th struct + Print P[4]|x=1212.12~, P[4]|y=21.1212~, p(4)-p(0)=32 +} +Kappa + \ No newline at end of file diff --git a/Lang/M2000-Interpreter/ADFGVX-cipher b/Lang/M2000-Interpreter/ADFGVX-cipher new file mode 120000 index 0000000000..58053e0f2d --- /dev/null +++ b/Lang/M2000-Interpreter/ADFGVX-cipher @@ -0,0 +1 @@ +../../Task/ADFGVX-cipher/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Apply-a-digital-filter-direct-form-II-transposed- b/Lang/M2000-Interpreter/Apply-a-digital-filter-direct-form-II-transposed- new file mode 120000 index 0000000000..0994290aa3 --- /dev/null +++ b/Lang/M2000-Interpreter/Apply-a-digital-filter-direct-form-II-transposed- @@ -0,0 +1 @@ +../../Task/Apply-a-digital-filter-direct-form-II-transposed-/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Arbitrary-precision-integers-included- b/Lang/M2000-Interpreter/Arbitrary-precision-integers-included- new file mode 120000 index 0000000000..4f4595771b --- /dev/null +++ b/Lang/M2000-Interpreter/Arbitrary-precision-integers-included- @@ -0,0 +1 @@ +../../Task/Arbitrary-precision-integers-included-/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Arithmetic-Complex b/Lang/M2000-Interpreter/Arithmetic-Complex new file mode 120000 index 0000000000..d7240f321f --- /dev/null +++ b/Lang/M2000-Interpreter/Arithmetic-Complex @@ -0,0 +1 @@ +../../Task/Arithmetic-Complex/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Associative-array-Merging b/Lang/M2000-Interpreter/Associative-array-Merging new file mode 120000 index 0000000000..e54ba7cbfd --- /dev/null +++ b/Lang/M2000-Interpreter/Associative-array-Merging @@ -0,0 +1 @@ +../../Task/Associative-array-Merging/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Averages-Mean-angle b/Lang/M2000-Interpreter/Averages-Mean-angle new file mode 120000 index 0000000000..5bcc89482d --- /dev/null +++ b/Lang/M2000-Interpreter/Averages-Mean-angle @@ -0,0 +1 @@ +../../Task/Averages-Mean-angle/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Averages-Root-mean-square b/Lang/M2000-Interpreter/Averages-Root-mean-square new file mode 120000 index 0000000000..226fa9019d --- /dev/null +++ b/Lang/M2000-Interpreter/Averages-Root-mean-square @@ -0,0 +1 @@ +../../Task/Averages-Root-mean-square/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Averages-Simple-moving-average b/Lang/M2000-Interpreter/Averages-Simple-moving-average new file mode 120000 index 0000000000..4d812f1b4c --- /dev/null +++ b/Lang/M2000-Interpreter/Averages-Simple-moving-average @@ -0,0 +1 @@ +../../Task/Averages-Simple-moving-average/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Babylonian-spiral b/Lang/M2000-Interpreter/Babylonian-spiral new file mode 120000 index 0000000000..70eeaaf834 --- /dev/null +++ b/Lang/M2000-Interpreter/Babylonian-spiral @@ -0,0 +1 @@ +../../Task/Babylonian-spiral/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Bernoulli-numbers b/Lang/M2000-Interpreter/Bernoulli-numbers new file mode 120000 index 0000000000..91c31cbe94 --- /dev/null +++ b/Lang/M2000-Interpreter/Bernoulli-numbers @@ -0,0 +1 @@ +../../Task/Bernoulli-numbers/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Bifid-cipher b/Lang/M2000-Interpreter/Bifid-cipher new file mode 120000 index 0000000000..c97cd39b1f --- /dev/null +++ b/Lang/M2000-Interpreter/Bifid-cipher @@ -0,0 +1 @@ +../../Task/Bifid-cipher/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Binary-strings b/Lang/M2000-Interpreter/Binary-strings new file mode 120000 index 0000000000..7890dd1bf5 --- /dev/null +++ b/Lang/M2000-Interpreter/Binary-strings @@ -0,0 +1 @@ +../../Task/Binary-strings/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Bitmap-B-zier-curves-Quadratic b/Lang/M2000-Interpreter/Bitmap-B-zier-curves-Quadratic new file mode 120000 index 0000000000..2471b47323 --- /dev/null +++ b/Lang/M2000-Interpreter/Bitmap-B-zier-curves-Quadratic @@ -0,0 +1 @@ +../../Task/Bitmap-B-zier-curves-Quadratic/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Bitmap-Bresenhams-line-algorithm b/Lang/M2000-Interpreter/Bitmap-Bresenhams-line-algorithm new file mode 120000 index 0000000000..37e0c9a050 --- /dev/null +++ b/Lang/M2000-Interpreter/Bitmap-Bresenhams-line-algorithm @@ -0,0 +1 @@ +../../Task/Bitmap-Bresenhams-line-algorithm/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Bitwise-operations b/Lang/M2000-Interpreter/Bitwise-operations new file mode 120000 index 0000000000..7b5956a12b --- /dev/null +++ b/Lang/M2000-Interpreter/Bitwise-operations @@ -0,0 +1 @@ +../../Task/Bitwise-operations/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Cartesian-product-of-two-or-more-lists b/Lang/M2000-Interpreter/Cartesian-product-of-two-or-more-lists new file mode 120000 index 0000000000..afa95add18 --- /dev/null +++ b/Lang/M2000-Interpreter/Cartesian-product-of-two-or-more-lists @@ -0,0 +1 @@ +../../Task/Cartesian-product-of-two-or-more-lists/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Chinese-zodiac b/Lang/M2000-Interpreter/Chinese-zodiac new file mode 120000 index 0000000000..ba20540cb2 --- /dev/null +++ b/Lang/M2000-Interpreter/Chinese-zodiac @@ -0,0 +1 @@ +../../Task/Chinese-zodiac/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Compare-length-of-two-strings b/Lang/M2000-Interpreter/Compare-length-of-two-strings new file mode 120000 index 0000000000..1726357b73 --- /dev/null +++ b/Lang/M2000-Interpreter/Compare-length-of-two-strings @@ -0,0 +1 @@ +../../Task/Compare-length-of-two-strings/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Compound-data-type b/Lang/M2000-Interpreter/Compound-data-type new file mode 120000 index 0000000000..661e74ca81 --- /dev/null +++ b/Lang/M2000-Interpreter/Compound-data-type @@ -0,0 +1 @@ +../../Task/Compound-data-type/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Count-occurrences-of-a-substring b/Lang/M2000-Interpreter/Count-occurrences-of-a-substring new file mode 120000 index 0000000000..96e93abdc4 --- /dev/null +++ b/Lang/M2000-Interpreter/Count-occurrences-of-a-substring @@ -0,0 +1 @@ +../../Task/Count-occurrences-of-a-substring/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Deal-cards-for-FreeCell b/Lang/M2000-Interpreter/Deal-cards-for-FreeCell new file mode 120000 index 0000000000..59b0374429 --- /dev/null +++ b/Lang/M2000-Interpreter/Deal-cards-for-FreeCell @@ -0,0 +1 @@ +../../Task/Deal-cards-for-FreeCell/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Doomsday-rule b/Lang/M2000-Interpreter/Doomsday-rule new file mode 120000 index 0000000000..64bda385da --- /dev/null +++ b/Lang/M2000-Interpreter/Doomsday-rule @@ -0,0 +1 @@ +../../Task/Doomsday-rule/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Egyptian-division b/Lang/M2000-Interpreter/Egyptian-division new file mode 120000 index 0000000000..ed8318ad3d --- /dev/null +++ b/Lang/M2000-Interpreter/Egyptian-division @@ -0,0 +1 @@ +../../Task/Egyptian-division/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Equilibrium-index b/Lang/M2000-Interpreter/Equilibrium-index new file mode 120000 index 0000000000..52fd43669a --- /dev/null +++ b/Lang/M2000-Interpreter/Equilibrium-index @@ -0,0 +1 @@ +../../Task/Equilibrium-index/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Eulers-identity b/Lang/M2000-Interpreter/Eulers-identity new file mode 120000 index 0000000000..af0f40c33c --- /dev/null +++ b/Lang/M2000-Interpreter/Eulers-identity @@ -0,0 +1 @@ +../../Task/Eulers-identity/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Execute-Computer-Zero b/Lang/M2000-Interpreter/Execute-Computer-Zero new file mode 120000 index 0000000000..fecab5c3ec --- /dev/null +++ b/Lang/M2000-Interpreter/Execute-Computer-Zero @@ -0,0 +1 @@ +../../Task/Execute-Computer-Zero/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Factors-of-a-Mersenne-number b/Lang/M2000-Interpreter/Factors-of-a-Mersenne-number new file mode 120000 index 0000000000..dcb49d5579 --- /dev/null +++ b/Lang/M2000-Interpreter/Factors-of-a-Mersenne-number @@ -0,0 +1 @@ +../../Task/Factors-of-a-Mersenne-number/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Fast-Fourier-transform b/Lang/M2000-Interpreter/Fast-Fourier-transform new file mode 120000 index 0000000000..e70d70854c --- /dev/null +++ b/Lang/M2000-Interpreter/Fast-Fourier-transform @@ -0,0 +1 @@ +../../Task/Fast-Fourier-transform/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/File-extension-is-in-extensions-list b/Lang/M2000-Interpreter/File-extension-is-in-extensions-list new file mode 120000 index 0000000000..6d12e57411 --- /dev/null +++ b/Lang/M2000-Interpreter/File-extension-is-in-extensions-list @@ -0,0 +1 @@ +../../Task/File-extension-is-in-extensions-list/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Find-the-last-Sunday-of-each-month b/Lang/M2000-Interpreter/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..14e77f2ff4 --- /dev/null +++ b/Lang/M2000-Interpreter/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Four-is-magic b/Lang/M2000-Interpreter/Four-is-magic new file mode 120000 index 0000000000..3bd19ce379 --- /dev/null +++ b/Lang/M2000-Interpreter/Four-is-magic @@ -0,0 +1 @@ +../../Task/Four-is-magic/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Globally-replace-text-in-several-files b/Lang/M2000-Interpreter/Globally-replace-text-in-several-files new file mode 120000 index 0000000000..6371957a66 --- /dev/null +++ b/Lang/M2000-Interpreter/Globally-replace-text-in-several-files @@ -0,0 +1 @@ +../../Task/Globally-replace-text-in-several-files/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Greatest-subsequential-sum b/Lang/M2000-Interpreter/Greatest-subsequential-sum new file mode 120000 index 0000000000..5470dd7511 --- /dev/null +++ b/Lang/M2000-Interpreter/Greatest-subsequential-sum @@ -0,0 +1 @@ +../../Task/Greatest-subsequential-sum/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/HTTPS b/Lang/M2000-Interpreter/HTTPS new file mode 120000 index 0000000000..07f4e45833 --- /dev/null +++ b/Lang/M2000-Interpreter/HTTPS @@ -0,0 +1 @@ +../../Task/HTTPS/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/ISBN13-check-digit b/Lang/M2000-Interpreter/ISBN13-check-digit new file mode 120000 index 0000000000..b320adf2bf --- /dev/null +++ b/Lang/M2000-Interpreter/ISBN13-check-digit @@ -0,0 +1 @@ +../../Task/ISBN13-check-digit/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols b/Lang/M2000-Interpreter/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols new file mode 120000 index 0000000000..85569db69f --- /dev/null +++ b/Lang/M2000-Interpreter/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols @@ -0,0 +1 @@ +../../Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/K-d-tree b/Lang/M2000-Interpreter/K-d-tree new file mode 120000 index 0000000000..5f1e9bff31 --- /dev/null +++ b/Lang/M2000-Interpreter/K-d-tree @@ -0,0 +1 @@ +../../Task/K-d-tree/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Leonardo-numbers b/Lang/M2000-Interpreter/Leonardo-numbers new file mode 120000 index 0000000000..4f37c1babb --- /dev/null +++ b/Lang/M2000-Interpreter/Leonardo-numbers @@ -0,0 +1 @@ +../../Task/Leonardo-numbers/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Logistic-curve-fitting-in-epidemiology b/Lang/M2000-Interpreter/Logistic-curve-fitting-in-epidemiology new file mode 120000 index 0000000000..d60f5aa239 --- /dev/null +++ b/Lang/M2000-Interpreter/Logistic-curve-fitting-in-epidemiology @@ -0,0 +1 @@ +../../Task/Logistic-curve-fitting-in-epidemiology/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Long-multiplication b/Lang/M2000-Interpreter/Long-multiplication new file mode 120000 index 0000000000..ba1dc9bc62 --- /dev/null +++ b/Lang/M2000-Interpreter/Long-multiplication @@ -0,0 +1 @@ +../../Task/Long-multiplication/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Long-year b/Lang/M2000-Interpreter/Long-year new file mode 120000 index 0000000000..7119be8d2b --- /dev/null +++ b/Lang/M2000-Interpreter/Long-year @@ -0,0 +1 @@ +../../Task/Long-year/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Mastermind b/Lang/M2000-Interpreter/Mastermind new file mode 120000 index 0000000000..3cfbb80935 --- /dev/null +++ b/Lang/M2000-Interpreter/Mastermind @@ -0,0 +1 @@ +../../Task/Mastermind/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Matrix-digital-rain b/Lang/M2000-Interpreter/Matrix-digital-rain new file mode 120000 index 0000000000..c3f5d509a7 --- /dev/null +++ b/Lang/M2000-Interpreter/Matrix-digital-rain @@ -0,0 +1 @@ +../../Task/Matrix-digital-rain/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Matrix-transposition b/Lang/M2000-Interpreter/Matrix-transposition new file mode 120000 index 0000000000..5ea61d7980 --- /dev/null +++ b/Lang/M2000-Interpreter/Matrix-transposition @@ -0,0 +1 @@ +../../Task/Matrix-transposition/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Modified-random-distribution b/Lang/M2000-Interpreter/Modified-random-distribution new file mode 120000 index 0000000000..bbbb129f02 --- /dev/null +++ b/Lang/M2000-Interpreter/Modified-random-distribution @@ -0,0 +1 @@ +../../Task/Modified-random-distribution/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Modular-exponentiation b/Lang/M2000-Interpreter/Modular-exponentiation new file mode 120000 index 0000000000..99e9549d1a --- /dev/null +++ b/Lang/M2000-Interpreter/Modular-exponentiation @@ -0,0 +1 @@ +../../Task/Modular-exponentiation/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Morse-code b/Lang/M2000-Interpreter/Morse-code new file mode 120000 index 0000000000..77ce05e92e --- /dev/null +++ b/Lang/M2000-Interpreter/Morse-code @@ -0,0 +1 @@ +../../Task/Morse-code/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Multi-dimensional-array b/Lang/M2000-Interpreter/Multi-dimensional-array new file mode 120000 index 0000000000..24c2948fdf --- /dev/null +++ b/Lang/M2000-Interpreter/Multi-dimensional-array @@ -0,0 +1 @@ +../../Task/Multi-dimensional-array/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Multiple-regression b/Lang/M2000-Interpreter/Multiple-regression new file mode 120000 index 0000000000..f645ea689c --- /dev/null +++ b/Lang/M2000-Interpreter/Multiple-regression @@ -0,0 +1 @@ +../../Task/Multiple-regression/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Number-names b/Lang/M2000-Interpreter/Number-names new file mode 120000 index 0000000000..acf20af45b --- /dev/null +++ b/Lang/M2000-Interpreter/Number-names @@ -0,0 +1 @@ +../../Task/Number-names/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Old-lady-swallowed-a-fly b/Lang/M2000-Interpreter/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..f9fe169db2 --- /dev/null +++ b/Lang/M2000-Interpreter/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Ordered-words b/Lang/M2000-Interpreter/Ordered-words new file mode 120000 index 0000000000..ccf0ec6f16 --- /dev/null +++ b/Lang/M2000-Interpreter/Ordered-words @@ -0,0 +1 @@ +../../Task/Ordered-words/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Password-generator b/Lang/M2000-Interpreter/Password-generator new file mode 120000 index 0000000000..0b48ccbf39 --- /dev/null +++ b/Lang/M2000-Interpreter/Password-generator @@ -0,0 +1 @@ +../../Task/Password-generator/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Periodic-table b/Lang/M2000-Interpreter/Periodic-table new file mode 120000 index 0000000000..0e286fad08 --- /dev/null +++ b/Lang/M2000-Interpreter/Periodic-table @@ -0,0 +1 @@ +../../Task/Periodic-table/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Polyspiral b/Lang/M2000-Interpreter/Polyspiral new file mode 120000 index 0000000000..f2eb619d45 --- /dev/null +++ b/Lang/M2000-Interpreter/Polyspiral @@ -0,0 +1 @@ +../../Task/Polyspiral/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Power-set b/Lang/M2000-Interpreter/Power-set new file mode 120000 index 0000000000..c99b047826 --- /dev/null +++ b/Lang/M2000-Interpreter/Power-set @@ -0,0 +1 @@ +../../Task/Power-set/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Problem-of-Apollonius b/Lang/M2000-Interpreter/Problem-of-Apollonius new file mode 120000 index 0000000000..3c1d7459c0 --- /dev/null +++ b/Lang/M2000-Interpreter/Problem-of-Apollonius @@ -0,0 +1 @@ +../../Task/Problem-of-Apollonius/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Pseudo-random-numbers-Middle-square-method b/Lang/M2000-Interpreter/Pseudo-random-numbers-Middle-square-method new file mode 120000 index 0000000000..71371c48fd --- /dev/null +++ b/Lang/M2000-Interpreter/Pseudo-random-numbers-Middle-square-method @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-Middle-square-method/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Pseudo-random-numbers-Xorshift-star b/Lang/M2000-Interpreter/Pseudo-random-numbers-Xorshift-star new file mode 120000 index 0000000000..a60ebed0a5 --- /dev/null +++ b/Lang/M2000-Interpreter/Pseudo-random-numbers-Xorshift-star @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-Xorshift-star/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Quaternion-type b/Lang/M2000-Interpreter/Quaternion-type deleted file mode 120000 index 7027a86930..0000000000 --- a/Lang/M2000-Interpreter/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Read-a-specific-line-from-a-file b/Lang/M2000-Interpreter/Read-a-specific-line-from-a-file new file mode 120000 index 0000000000..12c1b22a47 --- /dev/null +++ b/Lang/M2000-Interpreter/Read-a-specific-line-from-a-file @@ -0,0 +1 @@ +../../Task/Read-a-specific-line-from-a-file/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Roots-of-a-quadratic-function b/Lang/M2000-Interpreter/Roots-of-a-quadratic-function new file mode 120000 index 0000000000..0f141b08fb --- /dev/null +++ b/Lang/M2000-Interpreter/Roots-of-a-quadratic-function @@ -0,0 +1 @@ +../../Task/Roots-of-a-quadratic-function/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Simple-turtle-graphics b/Lang/M2000-Interpreter/Simple-turtle-graphics new file mode 120000 index 0000000000..8bb4a18e49 --- /dev/null +++ b/Lang/M2000-Interpreter/Simple-turtle-graphics @@ -0,0 +1 @@ +../../Task/Simple-turtle-graphics/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Sleeping-Beauty-problem b/Lang/M2000-Interpreter/Sleeping-Beauty-problem new file mode 120000 index 0000000000..aee1fdd4f8 --- /dev/null +++ b/Lang/M2000-Interpreter/Sleeping-Beauty-problem @@ -0,0 +1 @@ +../../Task/Sleeping-Beauty-problem/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Sort-an-integer-array b/Lang/M2000-Interpreter/Sort-an-integer-array new file mode 120000 index 0000000000..f409389d27 --- /dev/null +++ b/Lang/M2000-Interpreter/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Sort-an-outline-at-every-level b/Lang/M2000-Interpreter/Sort-an-outline-at-every-level new file mode 120000 index 0000000000..b5c1e68e5d --- /dev/null +++ b/Lang/M2000-Interpreter/Sort-an-outline-at-every-level @@ -0,0 +1 @@ +../../Task/Sort-an-outline-at-every-level/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Sorting-algorithms-Strand-sort b/Lang/M2000-Interpreter/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..94b7b8369f --- /dev/null +++ b/Lang/M2000-Interpreter/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Stable-marriage-problem b/Lang/M2000-Interpreter/Stable-marriage-problem new file mode 120000 index 0000000000..1148451e3c --- /dev/null +++ b/Lang/M2000-Interpreter/Stable-marriage-problem @@ -0,0 +1 @@ +../../Task/Stable-marriage-problem/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Statistics-Basic b/Lang/M2000-Interpreter/Statistics-Basic new file mode 120000 index 0000000000..9d5dab6ba7 --- /dev/null +++ b/Lang/M2000-Interpreter/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Statistics-Normal-distribution b/Lang/M2000-Interpreter/Statistics-Normal-distribution new file mode 120000 index 0000000000..6018d24b87 --- /dev/null +++ b/Lang/M2000-Interpreter/Statistics-Normal-distribution @@ -0,0 +1 @@ +../../Task/Statistics-Normal-distribution/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Strip-a-set-of-characters-from-a-string b/Lang/M2000-Interpreter/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..ca8f98d606 --- /dev/null +++ b/Lang/M2000-Interpreter/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Taxicab-numbers b/Lang/M2000-Interpreter/Taxicab-numbers new file mode 120000 index 0000000000..6c7f58f7d6 --- /dev/null +++ b/Lang/M2000-Interpreter/Taxicab-numbers @@ -0,0 +1 @@ +../../Task/Taxicab-numbers/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Temperature-conversion b/Lang/M2000-Interpreter/Temperature-conversion new file mode 120000 index 0000000000..75d9db05ed --- /dev/null +++ b/Lang/M2000-Interpreter/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Terminal-control-Hiding-the-cursor b/Lang/M2000-Interpreter/Terminal-control-Hiding-the-cursor new file mode 120000 index 0000000000..7d9e8bacf5 --- /dev/null +++ b/Lang/M2000-Interpreter/Terminal-control-Hiding-the-cursor @@ -0,0 +1 @@ +../../Task/Terminal-control-Hiding-the-cursor/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Tree-datastructures b/Lang/M2000-Interpreter/Tree-datastructures new file mode 120000 index 0000000000..1fa6a47d52 --- /dev/null +++ b/Lang/M2000-Interpreter/Tree-datastructures @@ -0,0 +1 @@ +../../Task/Tree-datastructures/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Truth-table b/Lang/M2000-Interpreter/Truth-table new file mode 120000 index 0000000000..b77fe8354b --- /dev/null +++ b/Lang/M2000-Interpreter/Truth-table @@ -0,0 +1 @@ +../../Task/Truth-table/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Ultra-useful-primes b/Lang/M2000-Interpreter/Ultra-useful-primes new file mode 120000 index 0000000000..5330980a0e --- /dev/null +++ b/Lang/M2000-Interpreter/Ultra-useful-primes @@ -0,0 +1 @@ +../../Task/Ultra-useful-primes/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Video-display-modes b/Lang/M2000-Interpreter/Video-display-modes new file mode 120000 index 0000000000..39ee17dc2d --- /dev/null +++ b/Lang/M2000-Interpreter/Video-display-modes @@ -0,0 +1 @@ +../../Task/Video-display-modes/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Window-management b/Lang/M2000-Interpreter/Window-management new file mode 120000 index 0000000000..bb8ac9e26a --- /dev/null +++ b/Lang/M2000-Interpreter/Window-management @@ -0,0 +1 @@ +../../Task/Window-management/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Write-language-name-in-3D-ASCII b/Lang/M2000-Interpreter/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..3ec6cbeb80 --- /dev/null +++ b/Lang/M2000-Interpreter/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M4/Cantor-set b/Lang/M4/Cantor-set new file mode 120000 index 0000000000..cb3913e176 --- /dev/null +++ b/Lang/M4/Cantor-set @@ -0,0 +1 @@ +../../Task/Cantor-set/M4 \ No newline at end of file diff --git a/Lang/M4/Empty-program b/Lang/M4/Empty-program deleted file mode 120000 index 3ce502532c..0000000000 --- a/Lang/M4/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/M4 \ No newline at end of file diff --git a/Lang/MACRO-11/Run-length-encoding b/Lang/MACRO-11/Run-length-encoding new file mode 120000 index 0000000000..3f700314e0 --- /dev/null +++ b/Lang/MACRO-11/Run-length-encoding @@ -0,0 +1 @@ +../../Task/Run-length-encoding/MACRO-11 \ No newline at end of file diff --git a/Lang/MACRO-11/Square-but-not-cube b/Lang/MACRO-11/Square-but-not-cube new file mode 120000 index 0000000000..7130b2c620 --- /dev/null +++ b/Lang/MACRO-11/Square-but-not-cube @@ -0,0 +1 @@ +../../Task/Square-but-not-cube/MACRO-11 \ No newline at end of file diff --git a/Lang/MAD/Arithmetic-derivative b/Lang/MAD/Arithmetic-derivative new file mode 120000 index 0000000000..e7c006ae6c --- /dev/null +++ b/Lang/MAD/Arithmetic-derivative @@ -0,0 +1 @@ +../../Task/Arithmetic-derivative/MAD \ No newline at end of file diff --git a/Lang/MAD/Look-and-say-sequence b/Lang/MAD/Look-and-say-sequence new file mode 120000 index 0000000000..dbca6a6456 --- /dev/null +++ b/Lang/MAD/Look-and-say-sequence @@ -0,0 +1 @@ +../../Task/Look-and-say-sequence/MAD \ No newline at end of file diff --git a/Lang/MAD/Zeckendorf-number-representation b/Lang/MAD/Zeckendorf-number-representation new file mode 120000 index 0000000000..3be8d0f3cc --- /dev/null +++ b/Lang/MAD/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/MAD \ No newline at end of file diff --git a/Lang/MATLAB/Bioinformatics-base-count b/Lang/MATLAB/Bioinformatics-base-count deleted file mode 120000 index 2622a73422..0000000000 --- a/Lang/MATLAB/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Find-the-last-Sunday-of-each-month b/Lang/MATLAB/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..989cc5e7f4 --- /dev/null +++ b/Lang/MATLAB/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/MATLAB \ No newline at end of file diff --git a/Lang/ML-I/Empty-program b/Lang/ML-I/Empty-program deleted file mode 120000 index 48b06f2449..0000000000 --- a/Lang/ML-I/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/ML-I \ No newline at end of file diff --git a/Lang/MSX-Basic/Colour-pinstripe-Display b/Lang/MSX-Basic/Colour-pinstripe-Display new file mode 120000 index 0000000000..f0497934ea --- /dev/null +++ b/Lang/MSX-Basic/Colour-pinstripe-Display @@ -0,0 +1 @@ +../../Task/Colour-pinstripe-Display/MSX-Basic \ No newline at end of file diff --git a/Lang/MSX-Basic/Diversity-prediction-theorem b/Lang/MSX-Basic/Diversity-prediction-theorem new file mode 120000 index 0000000000..e57f4cb084 --- /dev/null +++ b/Lang/MSX-Basic/Diversity-prediction-theorem @@ -0,0 +1 @@ +../../Task/Diversity-prediction-theorem/MSX-Basic \ No newline at end of file diff --git a/Lang/MSX-Basic/Evaluate-binomial-coefficients b/Lang/MSX-Basic/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..806e2bfad2 --- /dev/null +++ b/Lang/MSX-Basic/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/MSX-Basic \ No newline at end of file diff --git a/Lang/MSX-Basic/Generate-lower-case-ASCII-alphabet b/Lang/MSX-Basic/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..8cceece87f --- /dev/null +++ b/Lang/MSX-Basic/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/MSX-Basic \ No newline at end of file diff --git a/Lang/MSX-Basic/Leonardo-numbers b/Lang/MSX-Basic/Leonardo-numbers new file mode 120000 index 0000000000..070fbe9186 --- /dev/null +++ b/Lang/MSX-Basic/Leonardo-numbers @@ -0,0 +1 @@ +../../Task/Leonardo-numbers/MSX-Basic \ No newline at end of file diff --git a/Lang/MSX-Basic/Map-range b/Lang/MSX-Basic/Map-range new file mode 120000 index 0000000000..749213e0f6 --- /dev/null +++ b/Lang/MSX-Basic/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/MSX-Basic \ No newline at end of file diff --git a/Lang/MSX-Basic/Pascals-triangle b/Lang/MSX-Basic/Pascals-triangle new file mode 120000 index 0000000000..bfaa04f0db --- /dev/null +++ b/Lang/MSX-Basic/Pascals-triangle @@ -0,0 +1 @@ +../../Task/Pascals-triangle/MSX-Basic \ No newline at end of file diff --git a/Lang/MSX-Basic/Pinstripe-Display b/Lang/MSX-Basic/Pinstripe-Display new file mode 120000 index 0000000000..b37582657e --- /dev/null +++ b/Lang/MSX-Basic/Pinstripe-Display @@ -0,0 +1 @@ +../../Task/Pinstripe-Display/MSX-Basic \ No newline at end of file diff --git a/Lang/MUMPS/00-LANG.txt b/Lang/MUMPS/00-LANG.txt index cfb6ac9800..491ec139a6 100644 --- a/Lang/MUMPS/00-LANG.txt +++ b/Lang/MUMPS/00-LANG.txt @@ -1,14 +1,21 @@ {{language -|untyped=yes}} +|untyped=yes +|gc +|parampass| +}} + {{language programming paradigm|procedural}} -

    Visit the Google group comp.lang.mumps for discussions about this language.

    +

    Visit the Google group/ Usenet newsgroupcomp.lang.mumps for discussions about this language.

    Visit [[wp:MUMPS|Wikipedia]] for a general description.

    See http://71.174.62.16/Demo/AnnoStd for details about the language.

    -

    Standard MUMPS has one data types (strings) and some dialects (Cache, MSM) add a second data type (objects). A variable can be unsubscripted or not, and the subscripted variables form a -sparse n-tree. MUMPS doesn't have traditional arrays, but has an array syntax that manipulates trees as if they were arrays, using indexing to access nodes of the tree. You can create a tree that can have unlimited levels of branching, with keys and values associated with each node in the tree. Similarly, while the language doesn't have lists, you can mimic lists by creating strings with a consistent character (or string) as a delimiter separating the entries. -The Cache dialect also supports explicit List operations and data structures. +

    Standard MUMPS has one data type (strings) and some dialects (Cache, MSM, IRIS) add a second data type (objects). A variable can be unsubscripted or not, and the subscripted variables form a +sparse n-tree, or associative arrays or sparse multidimensional hierarchical key-value pair with keys as strings and values as strings. + +MUMPS doesn't have traditional arrays, but has an array syntax that manipulates trees as if they were arrays, using indexing to access nodes of the tree. You can create a tree that can have unlimited levels of branching, with keys and values associated with each node in the tree. Similarly, while the language doesn't have lists, you can mimic lists by creating strings with a consistent character (or string) as a delimiter separating the entries. + +The Cache and IRIS dialects also support explicit List operations and data structures as values.

    \ No newline at end of file diff --git a/Lang/MUMPS/Menu b/Lang/MUMPS/Menu deleted file mode 120000 index e9b86505e7..0000000000 --- a/Lang/MUMPS/Menu +++ /dev/null @@ -1 +0,0 @@ -../../Task/Menu/MUMPS \ No newline at end of file diff --git a/Lang/Maple/Empty-program b/Lang/Maple/Empty-program deleted file mode 120000 index f9fceb04a1..0000000000 --- a/Lang/Maple/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Maple \ No newline at end of file diff --git a/Lang/Maple/Pythagoras-tree b/Lang/Maple/Pythagoras-tree new file mode 120000 index 0000000000..0342fe2180 --- /dev/null +++ b/Lang/Maple/Pythagoras-tree @@ -0,0 +1 @@ +../../Task/Pythagoras-tree/Maple \ No newline at end of file diff --git a/Lang/Maple/Quaternion-type b/Lang/Maple/Quaternion-type deleted file mode 120000 index dc174952ef..0000000000 --- a/Lang/Maple/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Maple \ No newline at end of file diff --git a/Lang/MariaDB/00-LANG.txt b/Lang/MariaDB/00-LANG.txt new file mode 100644 index 0000000000..fc505f9a24 --- /dev/null +++ b/Lang/MariaDB/00-LANG.txt @@ -0,0 +1,15 @@ +{{language|MariaDB}} +{{implementation|SQL}} + +'''MariaDB''' is a relational database management system (RDBMS) with non-relational extensions, like JSON and dynamic columns. It was originally forked from MySQL. After Oracle acquired MySQL in 2009, its creator Michael "Monty" Widenius and other developers from the team created MariaDB. MariaDB was named after Monty's second daughter, Maria. + +MariaDB is backed by two organisations: the MariaDB Foundation, a not-for-profit organisation that makes sure that MariaDB will remain free forever; and MariaDB plc, a company that provides MariaDB support and sells the MariaDB Enterprise edition. MariaDB code is distributed under the GNU GPL 2. Part of the code belongs to Oracle, because it derives from MySQL. MariaDB KnowledgeBase, its documentation, is available under that GNU FDL and the CC-BY-SA 3.0. + +MariaDB SQL has procedural extensions, which can be used to develop stored procedures, stored functions, triggers and events, as well as anonymous code blocks. It also supports a PL/SQL parser, available when MariaDB is used in Oracle compatibility mode. User-Defined Functions can also be written in a compiled language and be used in SQL statements. MariaDB also supports storage engines and other types of plugins. + +== External Links == +* [https://en.wikipedia.org/wiki/MariaDB Wikipedia:MariaDB] +* [https://mariadb.com/kb MariaDB KnowledgeBase] +* [https://mariadb.com/ MariaDB website] + +[[Category:SQL Derivatives]] \ No newline at end of file diff --git a/Lang/MariaDB/00-META.yaml b/Lang/MariaDB/00-META.yaml new file mode 100644 index 0000000000..4ad202983e --- /dev/null +++ b/Lang/MariaDB/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:MariaDB diff --git a/Lang/MariaDB/Conditional-structures b/Lang/MariaDB/Conditional-structures new file mode 120000 index 0000000000..1ed7f68fbf --- /dev/null +++ b/Lang/MariaDB/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/MariaDB \ No newline at end of file diff --git a/Lang/MariaDB/Hello-world-Text b/Lang/MariaDB/Hello-world-Text new file mode 120000 index 0000000000..bc1357e35b --- /dev/null +++ b/Lang/MariaDB/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/MariaDB \ No newline at end of file diff --git a/Lang/MariaDB/Parameterized-SQL-statement b/Lang/MariaDB/Parameterized-SQL-statement new file mode 120000 index 0000000000..28a4df441a --- /dev/null +++ b/Lang/MariaDB/Parameterized-SQL-statement @@ -0,0 +1 @@ +../../Task/Parameterized-SQL-statement/MariaDB \ No newline at end of file diff --git a/Lang/MariaDB/Table-creation-Postal-addresses b/Lang/MariaDB/Table-creation-Postal-addresses new file mode 120000 index 0000000000..5f671a41e1 --- /dev/null +++ b/Lang/MariaDB/Table-creation-Postal-addresses @@ -0,0 +1 @@ +../../Task/Table-creation-Postal-addresses/MariaDB \ No newline at end of file diff --git a/Lang/Mastermind/00-LANG.txt b/Lang/Mastermind/00-LANG.txt new file mode 100644 index 0000000000..faed2e3417 --- /dev/null +++ b/Lang/Mastermind/00-LANG.txt @@ -0,0 +1,292 @@ +{{stub}}{{language|Mastermind}} +Mastermind is a programming language designed specifically to create [[Brainf***]] code. The [https://mastermind.lostpixels.org Mastermind IDE] includes a [[Rust]]-based compiler, which converts (compiles) Mastermind source programs into Brainf***. +The current Mastermind compiler generates Brainf*** code assuming an infinite bi-directional tape, as well as 8-bit wrapping cells https://github.com/Heathcorp/Mastermind. + +== Usage == + +=== Variables & Values === + +Variables can be defined as single cells, or as contiguous sets of cells: +// single-cell: +let var = 56; +let c = 'g'; +let bool = true; // true/false equivalent to 1/0 +// multi-cell: +let array[4] = [1, 2, 3, 4]; +let string[5] = "hello"; +If left uninitialised, a cell is assumed to have a value of 0. + +Expressions consist of simple adds and subtractions, arrays and strings cannot be used in expressions: + +// supported: +var += 4 + (5 - 4 + (3 - 2)); +var = 'g' - 23 + true; +var = var + 5; // inefficient but supported +var += array[0] + 5; +let arr[3] = [4 + 3 - ('5' - 46), 1, 3]; + +// NOT supported: +var += [4, 5, 7][1] + 3; +Array indices must be compile-time constant integers + +=== Input & Output === + +Single bytes can be output using the ''output'' operator: + +output 'h'; +output var; +output var + 6; +output array[0]; +// the following are equivalent: +output '\n'; +output 10; +Likewise for ''input'': + +input var; +input arr[2]; +There is also ''*'' spread syntax and support for strings and arrays for ease of use: + +output "hello"; +output ['1', '2', '3']; +output *array; + +input *array; + +=== Loops === + +The simplest is the ''while'' loop, which only supports cell references, not expressions: + +while var { + // do stuff + // var -= 1; + // etc +} + +==== Draining loops ==== +The "drain" loop is equivalent to the common Brainf*** construction of repeating an action ''N'' times, where ''N'' is the value of a tape cell. Hence, "draining" the cell while doing the actions in the loop body. + +drain var { + +} +// shorthand for following: +while var { + // do stuff + var -= 1; +} +This destructively loops as many times as the value in the cell being referenced, this can be used with expressions: + +drain 10 {} +drain var - 6 {} +There is also shorthand "into" syntax for adding to other cells: + +drain var into other_var other_var_2 *spread_array etc; + +// example of typical "for loop": +let i; +drain 10 into i { + output '0' + i; // inefficient for the example +} +// "0123456789" +// equivalent to the following: +let i; +let N = 10; +while N { + output '0' + i; +} + +==== Copying loops ==== +The "copy" loop is equivalent to the drain loop, except it is not destructive. This means the variable can be accessed safely from inside the loop body. + +copy var into other_var *spread_var etc; + +// examples: +copy var { + // this will output the original var value, var times + output var; +} + +let rows = 3; +let columns = 6; +let total; +drain rows { + copy columns into total { + output '.'; + } +} +// ...... +// ...... +// ...... + +=== If/Else === +The "if" and "else" keywords operate similar to [[C]], except "else if" is not supported. The code in the "if" body will be executed if the provided expression is positive, otherwise the "else" body is executed. If the "not" keyword is used, the behavior is reversed. +Examples: + +if 13 { + output "13"; +} + +if var { + output "true"; +} else { + output "false"; +} + +// typical equivalence use-case: +if not var - 10 { + // == +} else { + // != +} + +=== Functions === +Functions work like templates/macros, as they do not perform any passing by value. All functions are in-lined at compile time. This means multiple calls to a large function will significantly increase your compiled [[Brainf***]] size. + +For this reason, function arguments are given using ''<'' angled bracket ''>'' syntax, much like generic functions in other languages: + +def quote { + output 39; // ASCII single quote + output arg; + output 39; +} + +let N = 'g'; +quote; +N += 3; +quote; +// gj + +=== Imports === + +Imports work much like the [[C]] preprocessor: + +#include "other_file" +This copies the contents of "other_file" into the current file at compile-time. + +=== In-line Brainf*** features === + +In-line Brainf*** allows the programmer to define custom behavior as if writing raw [[Brainf***]], this is analogous to [[C]]'s in-line [[Assembly]]. + + +// This is its most basic form: +// find the next cell that equals -1 +bf { + +[->+]- +} + +// This is its more advanced form: +// input a line of lowercase letters and output the uppercase version +// this is an intentionally inefficient example +bf @3 clobbers var *spread_var etc { + ,----------[++++++++++>,----------] + <[<]> + [ + { + let g @0; + assert g unknown; + output g + ('A' - 'a'); + // embedded Mastermind! + } + > + ] + // now clear and return + <[[-]<]> +} +It is the programmer's responsibility to clear used cells and return back to the cell in which the in-line Brainf*** context began. If the programmer does not do this, any Mastermind code after the in-line Brainf*** command will likely break. + +==== Memory location specifiers ==== +For hand-tuning optimizations and in-line Brainf*** that reads from Mastermind variables, you can specify the location on the Brainf*** tape: +Variables can be fixed to a specified location on the eventual Brainf*** tape. This can also be done with in-line Brainf*** code sections. This can be used to share values between Mastermind and Brainf*** contexts. + +let var @3 = 4; +// compiled: >>>++++ + +bf @4 { + <><><> +} +// compiled: >>>><><><> + +==== Clobbering and Assertions ==== +The Mastermind compiler will try to predict the value of cells at compile-time, so it can prevent unnecessary cell clean-ups and unreachable code (with optimizations turned on). If your in-line Brainf*** affects existing Mastermind variables, you should tell the compiler using the "clobbers" keyword, the syntax is similar to the ''drain into'' variable list: + +bf clobbers var *spread_var other_var etc {} +The compiler will now assume nothing about the values of those variables afterwards. + +If instead you want to tell the compiler specifically that a value has become certain, you can use ''assert'': + +assert var equals 3; +// most common use cases: +assert var equals 0; +assert var unknown; +Asserting a variable as ''unknown'' is equivalent to clobbering. + +==== Embedded Mastermind ==== +Embedding Mastermind into your in-line [[Brainf***]] allows you to use Mastermind syntax features for programs within your Brainf***, this is useful for ''N''-length string based programs, or anything not possible in pure Mastermind: + + +let sum @0; + +bf @0 { + >> + // read input (until eof) to the tape, nullifying any spaces or newlines + // (this is probably not a good practical example, ideas are appreciated) + ,[ + { + let c @0; + assert c unknown; // needed otherwise the compiler assumes c = 0 + + if not (c - '\n') { + c = 0; + } + if not (c - ' ') { + c = 0; + } + } + >, + ] +} +Memory location specifiers are relative to the current Mastermind context. Also, top-level variables are not cleared by default in Mastermind contexts, this allows you to "leave" variables in cells for your Brainf*** to use. If you want your embedded Mastermind to clean itself up, you can simply open a scope at the top level: + +bf { + ++----++[][][<><><>] // the program doesn't matter for this example + { + // variables here will not be cleared + let g @2; + assert g unknown; + { + // variables here will be cleared + let b = 32; + } + } + {{ + // self-cleaning Mastermind code here + }} +} + +==== Advanced ==== +All Mastermind features are available within the embedded Mastermind contexts, including in-line [[Brainf***]] code. + +bf { + ++++[ + { + let i @0; + assert i unknown; + let j @1 = i + 1; + + bf @1 { + [.+] + { + // even more layers are possible + bf { + { + output "h" + } + } + } + } + } + -] +} + + +== References == +{{reflist}} \ No newline at end of file diff --git a/Lang/Mastermind/00-META.yaml b/Lang/Mastermind/00-META.yaml new file mode 100644 index 0000000000..52ba5ad7eb --- /dev/null +++ b/Lang/Mastermind/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Mastermind diff --git a/Lang/Mastermind/Hello-world-Text b/Lang/Mastermind/Hello-world-Text new file mode 120000 index 0000000000..a0461bd60e --- /dev/null +++ b/Lang/Mastermind/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Mastermind \ No newline at end of file diff --git a/Lang/Mastermind/Repeat b/Lang/Mastermind/Repeat new file mode 120000 index 0000000000..25794ace84 --- /dev/null +++ b/Lang/Mastermind/Repeat @@ -0,0 +1 @@ +../../Task/Repeat/Mastermind \ No newline at end of file diff --git a/Lang/Mathematica/00-LANG.txt b/Lang/Mathematica/00-LANG.txt index 5daf1eef81..15e81dd703 100644 --- a/Lang/Mathematica/00-LANG.txt +++ b/Lang/Mathematica/00-LANG.txt @@ -11,4 +11,4 @@ It is used in many scientific, engineering, mathematical and computing fields, a [[Category:Mathematical programming languages]] ==Todo== -[[Reports:Tasks_not_implemented_in_Mathematica]] \ No newline at end of file +[[Tasks not implemented in Mathematica]] \ No newline at end of file diff --git a/Lang/Mathematica/15-puzzle-solver b/Lang/Mathematica/15-puzzle-solver new file mode 120000 index 0000000000..c802cd3973 --- /dev/null +++ b/Lang/Mathematica/15-puzzle-solver @@ -0,0 +1 @@ +../../Task/15-puzzle-solver/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/ADFGVX-cipher b/Lang/Mathematica/ADFGVX-cipher new file mode 120000 index 0000000000..0a44fcd7ef --- /dev/null +++ b/Lang/Mathematica/ADFGVX-cipher @@ -0,0 +1 @@ +../../Task/ADFGVX-cipher/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/ASCII-art-diagram-converter b/Lang/Mathematica/ASCII-art-diagram-converter new file mode 120000 index 0000000000..1006da4cf6 --- /dev/null +++ b/Lang/Mathematica/ASCII-art-diagram-converter @@ -0,0 +1 @@ +../../Task/ASCII-art-diagram-converter/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Arithmetic-derivative b/Lang/Mathematica/Arithmetic-derivative new file mode 120000 index 0000000000..a9033ded41 --- /dev/null +++ b/Lang/Mathematica/Arithmetic-derivative @@ -0,0 +1 @@ +../../Task/Arithmetic-derivative/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/B-zier-curves-Intersections b/Lang/Mathematica/B-zier-curves-Intersections new file mode 120000 index 0000000000..85dc8fb4ae --- /dev/null +++ b/Lang/Mathematica/B-zier-curves-Intersections @@ -0,0 +1 @@ +../../Task/B-zier-curves-Intersections/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Bioinformatics-base-count b/Lang/Mathematica/Bioinformatics-base-count deleted file mode 120000 index 986950c20f..0000000000 --- a/Lang/Mathematica/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Camel-case-and-snake-case b/Lang/Mathematica/Camel-case-and-snake-case new file mode 120000 index 0000000000..6d73876132 --- /dev/null +++ b/Lang/Mathematica/Camel-case-and-snake-case @@ -0,0 +1 @@ +../../Task/Camel-case-and-snake-case/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Doomsday-rule b/Lang/Mathematica/Doomsday-rule new file mode 120000 index 0000000000..92b8fc707b --- /dev/null +++ b/Lang/Mathematica/Doomsday-rule @@ -0,0 +1 @@ +../../Task/Doomsday-rule/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Empty-program b/Lang/Mathematica/Empty-program deleted file mode 120000 index 7445caa973..0000000000 --- a/Lang/Mathematica/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Erd-s-Nicolas-numbers b/Lang/Mathematica/Erd-s-Nicolas-numbers new file mode 120000 index 0000000000..d74b7bd3b7 --- /dev/null +++ b/Lang/Mathematica/Erd-s-Nicolas-numbers @@ -0,0 +1 @@ +../../Task/Erd-s-Nicolas-numbers/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Jordan-P-lya-numbers b/Lang/Mathematica/Jordan-P-lya-numbers new file mode 120000 index 0000000000..4fd2ab0262 --- /dev/null +++ b/Lang/Mathematica/Jordan-P-lya-numbers @@ -0,0 +1 @@ +../../Task/Jordan-P-lya-numbers/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Meissel-Mertens-constant b/Lang/Mathematica/Meissel-Mertens-constant deleted file mode 120000 index 8d1d0df59d..0000000000 --- a/Lang/Mathematica/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Miller-Rabin-primality-test b/Lang/Mathematica/Miller-Rabin-primality-test deleted file mode 120000 index 400d0fb0e3..0000000000 --- a/Lang/Mathematica/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Parse-an-IP-Address b/Lang/Mathematica/Parse-an-IP-Address new file mode 120000 index 0000000000..32b7086e88 --- /dev/null +++ b/Lang/Mathematica/Parse-an-IP-Address @@ -0,0 +1 @@ +../../Task/Parse-an-IP-Address/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Perlin-noise b/Lang/Mathematica/Perlin-noise new file mode 120000 index 0000000000..9de4d18cd6 --- /dev/null +++ b/Lang/Mathematica/Perlin-noise @@ -0,0 +1 @@ +../../Task/Perlin-noise/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Prime-numbers-whose-neighboring-pairs-are-tetraprimes b/Lang/Mathematica/Prime-numbers-whose-neighboring-pairs-are-tetraprimes new file mode 120000 index 0000000000..e8da31b0d4 --- /dev/null +++ b/Lang/Mathematica/Prime-numbers-whose-neighboring-pairs-are-tetraprimes @@ -0,0 +1 @@ +../../Task/Prime-numbers-whose-neighboring-pairs-are-tetraprimes/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Quaternion-type b/Lang/Mathematica/Quaternion-type deleted file mode 120000 index 700c56b146..0000000000 --- a/Lang/Mathematica/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Radical-of-an-integer b/Lang/Mathematica/Radical-of-an-integer new file mode 120000 index 0000000000..e6b1268eae --- /dev/null +++ b/Lang/Mathematica/Radical-of-an-integer @@ -0,0 +1 @@ +../../Task/Radical-of-an-integer/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Ramer-Douglas-Peucker-line-simplification b/Lang/Mathematica/Ramer-Douglas-Peucker-line-simplification new file mode 120000 index 0000000000..40a31497c6 --- /dev/null +++ b/Lang/Mathematica/Ramer-Douglas-Peucker-line-simplification @@ -0,0 +1 @@ +../../Task/Ramer-Douglas-Peucker-line-simplification/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Same-fringe b/Lang/Mathematica/Same-fringe new file mode 120000 index 0000000000..9a80cee1d8 --- /dev/null +++ b/Lang/Mathematica/Same-fringe @@ -0,0 +1 @@ +../../Task/Same-fringe/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Singular-value-decomposition b/Lang/Mathematica/Singular-value-decomposition new file mode 120000 index 0000000000..1a576b3373 --- /dev/null +++ b/Lang/Mathematica/Singular-value-decomposition @@ -0,0 +1 @@ +../../Task/Singular-value-decomposition/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Sisyphus-sequence b/Lang/Mathematica/Sisyphus-sequence new file mode 120000 index 0000000000..82e0aee9dd --- /dev/null +++ b/Lang/Mathematica/Sisyphus-sequence @@ -0,0 +1 @@ +../../Task/Sisyphus-sequence/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Sorting-Algorithms-Circle-Sort b/Lang/Mathematica/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 9ff1fc78ae..0000000000 --- a/Lang/Mathematica/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Sphenic-numbers b/Lang/Mathematica/Sphenic-numbers new file mode 120000 index 0000000000..c276d09072 --- /dev/null +++ b/Lang/Mathematica/Sphenic-numbers @@ -0,0 +1 @@ +../../Task/Sphenic-numbers/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Strassens-algorithm b/Lang/Mathematica/Strassens-algorithm new file mode 120000 index 0000000000..c75340ee0d --- /dev/null +++ b/Lang/Mathematica/Strassens-algorithm @@ -0,0 +1 @@ +../../Task/Strassens-algorithm/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Sudan-function b/Lang/Mathematica/Sudan-function new file mode 120000 index 0000000000..915d15ee53 --- /dev/null +++ b/Lang/Mathematica/Sudan-function @@ -0,0 +1 @@ +../../Task/Sudan-function/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Suffixation-of-decimal-numbers b/Lang/Mathematica/Suffixation-of-decimal-numbers new file mode 120000 index 0000000000..dd6272f891 --- /dev/null +++ b/Lang/Mathematica/Suffixation-of-decimal-numbers @@ -0,0 +1 @@ +../../Task/Suffixation-of-decimal-numbers/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Tonelli-Shanks-algorithm b/Lang/Mathematica/Tonelli-Shanks-algorithm new file mode 120000 index 0000000000..747956daa4 --- /dev/null +++ b/Lang/Mathematica/Tonelli-Shanks-algorithm @@ -0,0 +1 @@ +../../Task/Tonelli-Shanks-algorithm/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Transliterate-English-text-using-the-Greek-alphabet b/Lang/Mathematica/Transliterate-English-text-using-the-Greek-alphabet new file mode 120000 index 0000000000..d987c7e779 --- /dev/null +++ b/Lang/Mathematica/Transliterate-English-text-using-the-Greek-alphabet @@ -0,0 +1 @@ +../../Task/Transliterate-English-text-using-the-Greek-alphabet/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Tropical-algebra-overloading b/Lang/Mathematica/Tropical-algebra-overloading new file mode 120000 index 0000000000..6a45231ead --- /dev/null +++ b/Lang/Mathematica/Tropical-algebra-overloading @@ -0,0 +1 @@ +../../Task/Tropical-algebra-overloading/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Vogels-approximation-method b/Lang/Mathematica/Vogels-approximation-method new file mode 120000 index 0000000000..2d01457a6e --- /dev/null +++ b/Lang/Mathematica/Vogels-approximation-method @@ -0,0 +1 @@ +../../Task/Vogels-approximation-method/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Wagstaff-primes b/Lang/Mathematica/Wagstaff-primes new file mode 120000 index 0000000000..7e781a92a6 --- /dev/null +++ b/Lang/Mathematica/Wagstaff-primes @@ -0,0 +1 @@ +../../Task/Wagstaff-primes/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/World-Cup-group-stage b/Lang/Mathematica/World-Cup-group-stage new file mode 120000 index 0000000000..c3a327e4ad --- /dev/null +++ b/Lang/Mathematica/World-Cup-group-stage @@ -0,0 +1 @@ +../../Task/World-Cup-group-stage/Mathematica \ No newline at end of file diff --git a/Lang/Maxima/Angle-difference-between-two-bearings b/Lang/Maxima/Angle-difference-between-two-bearings new file mode 120000 index 0000000000..b086194fa4 --- /dev/null +++ b/Lang/Maxima/Angle-difference-between-two-bearings @@ -0,0 +1 @@ +../../Task/Angle-difference-between-two-bearings/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Arithmetic-derivative b/Lang/Maxima/Arithmetic-derivative new file mode 120000 index 0000000000..b682390e8a --- /dev/null +++ b/Lang/Maxima/Arithmetic-derivative @@ -0,0 +1 @@ +../../Task/Arithmetic-derivative/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Array-length b/Lang/Maxima/Array-length new file mode 120000 index 0000000000..da5c3a4dcd --- /dev/null +++ b/Lang/Maxima/Array-length @@ -0,0 +1 @@ +../../Task/Array-length/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Carmichael-3-strong-pseudoprimes b/Lang/Maxima/Carmichael-3-strong-pseudoprimes new file mode 120000 index 0000000000..cca27bae48 --- /dev/null +++ b/Lang/Maxima/Carmichael-3-strong-pseudoprimes @@ -0,0 +1 @@ +../../Task/Carmichael-3-strong-pseudoprimes/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Chinese-zodiac b/Lang/Maxima/Chinese-zodiac new file mode 120000 index 0000000000..5fc6134cf1 --- /dev/null +++ b/Lang/Maxima/Chinese-zodiac @@ -0,0 +1 @@ +../../Task/Chinese-zodiac/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Chowla-numbers b/Lang/Maxima/Chowla-numbers new file mode 120000 index 0000000000..4a1835dd7a --- /dev/null +++ b/Lang/Maxima/Chowla-numbers @@ -0,0 +1 @@ +../../Task/Chowla-numbers/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Conjugate-transpose b/Lang/Maxima/Conjugate-transpose new file mode 120000 index 0000000000..f1ca6a05e7 --- /dev/null +++ b/Lang/Maxima/Conjugate-transpose @@ -0,0 +1 @@ +../../Task/Conjugate-transpose/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Continued-fraction-Arithmetic-Construct-from-rational-number b/Lang/Maxima/Continued-fraction-Arithmetic-Construct-from-rational-number new file mode 120000 index 0000000000..29d02a5a5d --- /dev/null +++ b/Lang/Maxima/Continued-fraction-Arithmetic-Construct-from-rational-number @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Delete-a-file b/Lang/Maxima/Delete-a-file new file mode 120000 index 0000000000..9515074358 --- /dev/null +++ b/Lang/Maxima/Delete-a-file @@ -0,0 +1 @@ +../../Task/Delete-a-file/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Diversity-prediction-theorem b/Lang/Maxima/Diversity-prediction-theorem new file mode 120000 index 0000000000..5f6277f150 --- /dev/null +++ b/Lang/Maxima/Diversity-prediction-theorem @@ -0,0 +1 @@ +../../Task/Diversity-prediction-theorem/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Doomsday-rule b/Lang/Maxima/Doomsday-rule new file mode 120000 index 0000000000..e92ce2f9d2 --- /dev/null +++ b/Lang/Maxima/Doomsday-rule @@ -0,0 +1 @@ +../../Task/Doomsday-rule/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Exponentiation-order b/Lang/Maxima/Exponentiation-order new file mode 120000 index 0000000000..3914b83865 --- /dev/null +++ b/Lang/Maxima/Exponentiation-order @@ -0,0 +1 @@ +../../Task/Exponentiation-order/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Exponentiation-with-infix-operators-in-or-operating-on-the-base b/Lang/Maxima/Exponentiation-with-infix-operators-in-or-operating-on-the-base new file mode 120000 index 0000000000..571c836707 --- /dev/null +++ b/Lang/Maxima/Exponentiation-with-infix-operators-in-or-operating-on-the-base @@ -0,0 +1 @@ +../../Task/Exponentiation-with-infix-operators-in-or-operating-on-the-base/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Fermat-numbers b/Lang/Maxima/Fermat-numbers new file mode 120000 index 0000000000..705c8192a4 --- /dev/null +++ b/Lang/Maxima/Fermat-numbers @@ -0,0 +1 @@ +../../Task/Fermat-numbers/Maxima \ No newline at end of file diff --git a/Lang/Maxima/General-FizzBuzz b/Lang/Maxima/General-FizzBuzz new file mode 120000 index 0000000000..e422ed53f2 --- /dev/null +++ b/Lang/Maxima/General-FizzBuzz @@ -0,0 +1 @@ +../../Task/General-FizzBuzz/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Guess-the-number b/Lang/Maxima/Guess-the-number new file mode 120000 index 0000000000..386c9c38ac --- /dev/null +++ b/Lang/Maxima/Guess-the-number @@ -0,0 +1 @@ +../../Task/Guess-the-number/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Guess-the-number-With-feedback b/Lang/Maxima/Guess-the-number-With-feedback new file mode 120000 index 0000000000..8b04db909f --- /dev/null +++ b/Lang/Maxima/Guess-the-number-With-feedback @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Hash-from-two-arrays b/Lang/Maxima/Hash-from-two-arrays new file mode 120000 index 0000000000..b59b47ec09 --- /dev/null +++ b/Lang/Maxima/Hash-from-two-arrays @@ -0,0 +1 @@ +../../Task/Hash-from-two-arrays/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Humble-numbers b/Lang/Maxima/Humble-numbers new file mode 120000 index 0000000000..d093fa7dd0 --- /dev/null +++ b/Lang/Maxima/Humble-numbers @@ -0,0 +1 @@ +../../Task/Humble-numbers/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Jacobi-symbol b/Lang/Maxima/Jacobi-symbol new file mode 120000 index 0000000000..73e8a14256 --- /dev/null +++ b/Lang/Maxima/Jacobi-symbol @@ -0,0 +1 @@ +../../Task/Jacobi-symbol/Maxima \ No newline at end of file diff --git a/Lang/Maxima/List-comprehensions b/Lang/Maxima/List-comprehensions new file mode 120000 index 0000000000..de6043c392 --- /dev/null +++ b/Lang/Maxima/List-comprehensions @@ -0,0 +1 @@ +../../Task/List-comprehensions/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Loops-N-plus-one-half b/Lang/Maxima/Loops-N-plus-one-half new file mode 120000 index 0000000000..8fb12a3bb8 --- /dev/null +++ b/Lang/Maxima/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Loops-With-multiple-ranges b/Lang/Maxima/Loops-With-multiple-ranges new file mode 120000 index 0000000000..0d4ccad640 --- /dev/null +++ b/Lang/Maxima/Loops-With-multiple-ranges @@ -0,0 +1 @@ +../../Task/Loops-With-multiple-ranges/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Magic-constant b/Lang/Maxima/Magic-constant new file mode 120000 index 0000000000..406aae118d --- /dev/null +++ b/Lang/Maxima/Magic-constant @@ -0,0 +1 @@ +../../Task/Magic-constant/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Meissel-Mertens-constant b/Lang/Maxima/Meissel-Mertens-constant deleted file mode 120000 index ea7cea2fda..0000000000 --- a/Lang/Maxima/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Miller-Rabin-primality-test b/Lang/Maxima/Miller-Rabin-primality-test deleted file mode 120000 index 331b953779..0000000000 --- a/Lang/Maxima/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Nested-function b/Lang/Maxima/Nested-function new file mode 120000 index 0000000000..14e0a5c6e4 --- /dev/null +++ b/Lang/Maxima/Nested-function @@ -0,0 +1 @@ +../../Task/Nested-function/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Nth b/Lang/Maxima/Nth new file mode 120000 index 0000000000..76e7cadf39 --- /dev/null +++ b/Lang/Maxima/Nth @@ -0,0 +1 @@ +../../Task/Nth/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Old-lady-swallowed-a-fly b/Lang/Maxima/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..7f7aab63d3 --- /dev/null +++ b/Lang/Maxima/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Pernicious-numbers b/Lang/Maxima/Pernicious-numbers new file mode 120000 index 0000000000..1062304d91 --- /dev/null +++ b/Lang/Maxima/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Phrase-reversals b/Lang/Maxima/Phrase-reversals new file mode 120000 index 0000000000..e9f3fbc16e --- /dev/null +++ b/Lang/Maxima/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Population-count b/Lang/Maxima/Population-count new file mode 120000 index 0000000000..ae8e574cce --- /dev/null +++ b/Lang/Maxima/Population-count @@ -0,0 +1 @@ +../../Task/Population-count/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Proper-divisors b/Lang/Maxima/Proper-divisors new file mode 120000 index 0000000000..d541bf6c4d --- /dev/null +++ b/Lang/Maxima/Proper-divisors @@ -0,0 +1 @@ +../../Task/Proper-divisors/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Pseudo-random-numbers-PCG32 b/Lang/Maxima/Pseudo-random-numbers-PCG32 new file mode 120000 index 0000000000..6feec056ab --- /dev/null +++ b/Lang/Maxima/Pseudo-random-numbers-PCG32 @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-PCG32/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Pseudo-random-numbers-Splitmix64 b/Lang/Maxima/Pseudo-random-numbers-Splitmix64 new file mode 120000 index 0000000000..c67133774e --- /dev/null +++ b/Lang/Maxima/Pseudo-random-numbers-Splitmix64 @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-Splitmix64/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Pseudo-random-numbers-Xorshift-star b/Lang/Maxima/Pseudo-random-numbers-Xorshift-star new file mode 120000 index 0000000000..601269aa2d --- /dev/null +++ b/Lang/Maxima/Pseudo-random-numbers-Xorshift-star @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-Xorshift-star/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Real-constants-and-functions b/Lang/Maxima/Real-constants-and-functions new file mode 120000 index 0000000000..5465f4ddf0 --- /dev/null +++ b/Lang/Maxima/Real-constants-and-functions @@ -0,0 +1 @@ +../../Task/Real-constants-and-functions/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Regular-expressions b/Lang/Maxima/Regular-expressions new file mode 120000 index 0000000000..ad80bc2114 --- /dev/null +++ b/Lang/Maxima/Regular-expressions @@ -0,0 +1 @@ +../../Task/Regular-expressions/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Rename-a-file b/Lang/Maxima/Rename-a-file new file mode 120000 index 0000000000..875c72e05d --- /dev/null +++ b/Lang/Maxima/Rename-a-file @@ -0,0 +1 @@ +../../Task/Rename-a-file/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Repeat b/Lang/Maxima/Repeat new file mode 120000 index 0000000000..69cf6bc4f0 --- /dev/null +++ b/Lang/Maxima/Repeat @@ -0,0 +1 @@ +../../Task/Repeat/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Repunit-primes b/Lang/Maxima/Repunit-primes new file mode 120000 index 0000000000..fb23d38994 --- /dev/null +++ b/Lang/Maxima/Repunit-primes @@ -0,0 +1 @@ +../../Task/Repunit-primes/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Safe-primes-and-unsafe-primes b/Lang/Maxima/Safe-primes-and-unsafe-primes new file mode 120000 index 0000000000..3ba21ce950 --- /dev/null +++ b/Lang/Maxima/Safe-primes-and-unsafe-primes @@ -0,0 +1 @@ +../../Task/Safe-primes-and-unsafe-primes/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Sequence-of-primorial-primes b/Lang/Maxima/Sequence-of-primorial-primes new file mode 120000 index 0000000000..987ddfd5b4 --- /dev/null +++ b/Lang/Maxima/Sequence-of-primorial-primes @@ -0,0 +1 @@ +../../Task/Sequence-of-primorial-primes/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Sequence:-smallest-number-with-exactly-n-divisors b/Lang/Maxima/Sequence:-smallest-number-with-exactly-n-divisors new file mode 120000 index 0000000000..2edcd184a6 --- /dev/null +++ b/Lang/Maxima/Sequence:-smallest-number-with-exactly-n-divisors @@ -0,0 +1 @@ +../../Task/Sequence:-smallest-number-with-exactly-n-divisors/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Shoelace-formula-for-polygonal-area b/Lang/Maxima/Shoelace-formula-for-polygonal-area new file mode 120000 index 0000000000..4b2db308ce --- /dev/null +++ b/Lang/Maxima/Shoelace-formula-for-polygonal-area @@ -0,0 +1 @@ +../../Task/Shoelace-formula-for-polygonal-area/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Sorting-algorithms-Counting-sort b/Lang/Maxima/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..3b3f2f0c39 --- /dev/null +++ b/Lang/Maxima/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Sorting-algorithms-Stooge-sort b/Lang/Maxima/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..df60525c6e --- /dev/null +++ b/Lang/Maxima/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Statistics-Basic b/Lang/Maxima/Statistics-Basic new file mode 120000 index 0000000000..3aa4fcf62d --- /dev/null +++ b/Lang/Maxima/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Stirling-numbers-of-the-first-kind b/Lang/Maxima/Stirling-numbers-of-the-first-kind new file mode 120000 index 0000000000..00938d2052 --- /dev/null +++ b/Lang/Maxima/Stirling-numbers-of-the-first-kind @@ -0,0 +1 @@ +../../Task/Stirling-numbers-of-the-first-kind/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Stirling-numbers-of-the-second-kind b/Lang/Maxima/Stirling-numbers-of-the-second-kind new file mode 120000 index 0000000000..3b2dde9483 --- /dev/null +++ b/Lang/Maxima/Stirling-numbers-of-the-second-kind @@ -0,0 +1 @@ +../../Task/Stirling-numbers-of-the-second-kind/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Substring-Top-and-tail b/Lang/Maxima/Substring-Top-and-tail new file mode 120000 index 0000000000..6897859615 --- /dev/null +++ b/Lang/Maxima/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Summarize-primes b/Lang/Maxima/Summarize-primes new file mode 120000 index 0000000000..d202f40be0 --- /dev/null +++ b/Lang/Maxima/Summarize-primes @@ -0,0 +1 @@ +../../Task/Summarize-primes/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Superellipse b/Lang/Maxima/Superellipse new file mode 120000 index 0000000000..4ecd2801c8 --- /dev/null +++ b/Lang/Maxima/Superellipse @@ -0,0 +1 @@ +../../Task/Superellipse/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Tau-function b/Lang/Maxima/Tau-function new file mode 120000 index 0000000000..40243f7b1e --- /dev/null +++ b/Lang/Maxima/Tau-function @@ -0,0 +1 @@ +../../Task/Tau-function/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Tau-number b/Lang/Maxima/Tau-number new file mode 120000 index 0000000000..053b7e480c --- /dev/null +++ b/Lang/Maxima/Tau-number @@ -0,0 +1 @@ +../../Task/Tau-number/Maxima \ No newline at end of file diff --git a/Lang/Maxima/The-Twelve-Days-of-Christmas b/Lang/Maxima/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..dd36e626f6 --- /dev/null +++ b/Lang/Maxima/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Topic-variable b/Lang/Maxima/Topic-variable new file mode 120000 index 0000000000..e2a8f808d7 --- /dev/null +++ b/Lang/Maxima/Topic-variable @@ -0,0 +1 @@ +../../Task/Topic-variable/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Towers-of-Hanoi b/Lang/Maxima/Towers-of-Hanoi new file mode 120000 index 0000000000..40963f2edb --- /dev/null +++ b/Lang/Maxima/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Unicode-variable-names b/Lang/Maxima/Unicode-variable-names new file mode 120000 index 0000000000..34b765c308 --- /dev/null +++ b/Lang/Maxima/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Variable-declaration-reset b/Lang/Maxima/Variable-declaration-reset new file mode 120000 index 0000000000..127cccc10e --- /dev/null +++ b/Lang/Maxima/Variable-declaration-reset @@ -0,0 +1 @@ +../../Task/Variable-declaration-reset/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Vector b/Lang/Maxima/Vector new file mode 120000 index 0000000000..8d6cbd46ca --- /dev/null +++ b/Lang/Maxima/Vector @@ -0,0 +1 @@ +../../Task/Vector/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Wagstaff-primes b/Lang/Maxima/Wagstaff-primes new file mode 120000 index 0000000000..f74c4ee3f2 --- /dev/null +++ b/Lang/Maxima/Wagstaff-primes @@ -0,0 +1 @@ +../../Task/Wagstaff-primes/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Wieferich-primes b/Lang/Maxima/Wieferich-primes new file mode 120000 index 0000000000..8ad2bd1a72 --- /dev/null +++ b/Lang/Maxima/Wieferich-primes @@ -0,0 +1 @@ +../../Task/Wieferich-primes/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Wilson-primes-of-order-n b/Lang/Maxima/Wilson-primes-of-order-n new file mode 120000 index 0000000000..83b27ec734 --- /dev/null +++ b/Lang/Maxima/Wilson-primes-of-order-n @@ -0,0 +1 @@ +../../Task/Wilson-primes-of-order-n/Maxima \ No newline at end of file diff --git a/Lang/MelonBasic/Empty-program b/Lang/MelonBasic/Empty-program deleted file mode 120000 index 8fb3b62c73..0000000000 --- a/Lang/MelonBasic/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/MelonBasic \ No newline at end of file diff --git a/Lang/Mercury/Miller-Rabin-primality-test b/Lang/Mercury/Miller-Rabin-primality-test deleted file mode 120000 index 6022def69b..0000000000 --- a/Lang/Mercury/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Mercury \ No newline at end of file diff --git a/Lang/Mercury/Quaternion-type b/Lang/Mercury/Quaternion-type deleted file mode 120000 index 34fd045795..0000000000 --- a/Lang/Mercury/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Mercury \ No newline at end of file diff --git a/Lang/Mia/Loops-While b/Lang/Mia/Loops-While new file mode 120000 index 0000000000..acad4e8591 --- /dev/null +++ b/Lang/Mia/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/Mia \ No newline at end of file diff --git a/Lang/Microsoft-Small-Basic/A+B b/Lang/Microsoft-Small-Basic/A+B new file mode 120000 index 0000000000..f3a4fe9f2e --- /dev/null +++ b/Lang/Microsoft-Small-Basic/A+B @@ -0,0 +1 @@ +../../Task/A+B/Microsoft-Small-Basic \ No newline at end of file diff --git a/Lang/Microsoft-Small-Basic/Array-length b/Lang/Microsoft-Small-Basic/Array-length new file mode 120000 index 0000000000..5cb5fd80e3 --- /dev/null +++ b/Lang/Microsoft-Small-Basic/Array-length @@ -0,0 +1 @@ +../../Task/Array-length/Microsoft-Small-Basic \ No newline at end of file diff --git a/Lang/Microsoft-Small-Basic/Halt-and-catch-fire b/Lang/Microsoft-Small-Basic/Halt-and-catch-fire new file mode 120000 index 0000000000..85dd00fc29 --- /dev/null +++ b/Lang/Microsoft-Small-Basic/Halt-and-catch-fire @@ -0,0 +1 @@ +../../Task/Halt-and-catch-fire/Microsoft-Small-Basic \ No newline at end of file diff --git a/Lang/Microsoft-Small-Basic/Hello-world-Graphical b/Lang/Microsoft-Small-Basic/Hello-world-Graphical new file mode 120000 index 0000000000..e9bfd8a7e0 --- /dev/null +++ b/Lang/Microsoft-Small-Basic/Hello-world-Graphical @@ -0,0 +1 @@ +../../Task/Hello-world-Graphical/Microsoft-Small-Basic \ No newline at end of file diff --git a/Lang/Microsoft-Small-Basic/I-before-E-except-after-C b/Lang/Microsoft-Small-Basic/I-before-E-except-after-C new file mode 120000 index 0000000000..e009793925 --- /dev/null +++ b/Lang/Microsoft-Small-Basic/I-before-E-except-after-C @@ -0,0 +1 @@ +../../Task/I-before-E-except-after-C/Microsoft-Small-Basic \ No newline at end of file diff --git a/Lang/Microsoft-Small-Basic/Jump-anywhere b/Lang/Microsoft-Small-Basic/Jump-anywhere new file mode 120000 index 0000000000..ef9c52343e --- /dev/null +++ b/Lang/Microsoft-Small-Basic/Jump-anywhere @@ -0,0 +1 @@ +../../Task/Jump-anywhere/Microsoft-Small-Basic \ No newline at end of file diff --git a/Lang/Microsoft-Small-Basic/Program-termination b/Lang/Microsoft-Small-Basic/Program-termination new file mode 120000 index 0000000000..ecf78f2fdc --- /dev/null +++ b/Lang/Microsoft-Small-Basic/Program-termination @@ -0,0 +1 @@ +../../Task/Program-termination/Microsoft-Small-Basic \ No newline at end of file diff --git a/Lang/Microsoft-Small-Basic/RPG-attributes-generator b/Lang/Microsoft-Small-Basic/RPG-attributes-generator new file mode 120000 index 0000000000..b4096f1ae1 --- /dev/null +++ b/Lang/Microsoft-Small-Basic/RPG-attributes-generator @@ -0,0 +1 @@ +../../Task/RPG-attributes-generator/Microsoft-Small-Basic \ No newline at end of file diff --git a/Lang/Microsoft-Small-Basic/Simple-windowed-application b/Lang/Microsoft-Small-Basic/Simple-windowed-application new file mode 120000 index 0000000000..372561cd34 --- /dev/null +++ b/Lang/Microsoft-Small-Basic/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/Microsoft-Small-Basic \ No newline at end of file diff --git a/Lang/Microsoft-Small-Basic/Substring b/Lang/Microsoft-Small-Basic/Substring new file mode 120000 index 0000000000..187fdf47c4 --- /dev/null +++ b/Lang/Microsoft-Small-Basic/Substring @@ -0,0 +1 @@ +../../Task/Substring/Microsoft-Small-Basic \ No newline at end of file diff --git a/Lang/Microsoft-Small-Basic/The-Name-Game b/Lang/Microsoft-Small-Basic/The-Name-Game new file mode 120000 index 0000000000..904bd0e9c8 --- /dev/null +++ b/Lang/Microsoft-Small-Basic/The-Name-Game @@ -0,0 +1 @@ +../../Task/The-Name-Game/Microsoft-Small-Basic \ No newline at end of file diff --git a/Lang/Microsoft-Small-Basic/Transliterate-English-text-using-the-Greek-alphabet b/Lang/Microsoft-Small-Basic/Transliterate-English-text-using-the-Greek-alphabet new file mode 120000 index 0000000000..5d28e3f2bb --- /dev/null +++ b/Lang/Microsoft-Small-Basic/Transliterate-English-text-using-the-Greek-alphabet @@ -0,0 +1 @@ +../../Task/Transliterate-English-text-using-the-Greek-alphabet/Microsoft-Small-Basic \ No newline at end of file diff --git a/Lang/Microsoft-Small-Basic/Variables b/Lang/Microsoft-Small-Basic/Variables new file mode 120000 index 0000000000..3ad596872d --- /dev/null +++ b/Lang/Microsoft-Small-Basic/Variables @@ -0,0 +1 @@ +../../Task/Variables/Microsoft-Small-Basic \ No newline at end of file diff --git a/Lang/Microsoft-Small-Basic/Window-creation b/Lang/Microsoft-Small-Basic/Window-creation new file mode 120000 index 0000000000..31935ba19c --- /dev/null +++ b/Lang/Microsoft-Small-Basic/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/Microsoft-Small-Basic \ No newline at end of file diff --git a/Lang/MiniScript/Apply-a-callback-to-an-array b/Lang/MiniScript/Apply-a-callback-to-an-array new file mode 120000 index 0000000000..9f2b7eb3c8 --- /dev/null +++ b/Lang/MiniScript/Apply-a-callback-to-an-array @@ -0,0 +1 @@ +../../Task/Apply-a-callback-to-an-array/MiniScript \ No newline at end of file diff --git a/Lang/MiniScript/Count-in-factors b/Lang/MiniScript/Count-in-factors new file mode 120000 index 0000000000..7a0ecccaf4 --- /dev/null +++ b/Lang/MiniScript/Count-in-factors @@ -0,0 +1 @@ +../../Task/Count-in-factors/MiniScript \ No newline at end of file diff --git a/Lang/MiniScript/Empty-program b/Lang/MiniScript/Empty-program deleted file mode 120000 index 60da45f9ae..0000000000 --- a/Lang/MiniScript/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/MiniScript \ No newline at end of file diff --git a/Lang/MiniScript/Haversine-formula b/Lang/MiniScript/Haversine-formula new file mode 120000 index 0000000000..0bba2877d8 --- /dev/null +++ b/Lang/MiniScript/Haversine-formula @@ -0,0 +1 @@ +../../Task/Haversine-formula/MiniScript \ No newline at end of file diff --git a/Lang/MiniScript/Read-a-file-line-by-line b/Lang/MiniScript/Read-a-file-line-by-line new file mode 120000 index 0000000000..7064fcf098 --- /dev/null +++ b/Lang/MiniScript/Read-a-file-line-by-line @@ -0,0 +1 @@ +../../Task/Read-a-file-line-by-line/MiniScript \ No newline at end of file diff --git a/Lang/MiniScript/Sleeping-Beauty-problem b/Lang/MiniScript/Sleeping-Beauty-problem new file mode 120000 index 0000000000..feb4e597cb --- /dev/null +++ b/Lang/MiniScript/Sleeping-Beauty-problem @@ -0,0 +1 @@ +../../Task/Sleeping-Beauty-problem/MiniScript \ No newline at end of file diff --git a/Lang/Minimal-BASIC/Abundant-deficient-and-perfect-number-classifications b/Lang/Minimal-BASIC/Abundant-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..ca944f9e1d --- /dev/null +++ b/Lang/Minimal-BASIC/Abundant-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant-deficient-and-perfect-number-classifications/Minimal-BASIC \ No newline at end of file diff --git a/Lang/Minimal-BASIC/Evaluate-binomial-coefficients b/Lang/Minimal-BASIC/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..6ad0769264 --- /dev/null +++ b/Lang/Minimal-BASIC/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/Minimal-BASIC \ No newline at end of file diff --git a/Lang/Minimal-BASIC/Jensens-Device b/Lang/Minimal-BASIC/Jensens-Device new file mode 120000 index 0000000000..f729ff931e --- /dev/null +++ b/Lang/Minimal-BASIC/Jensens-Device @@ -0,0 +1 @@ +../../Task/Jensens-Device/Minimal-BASIC \ No newline at end of file diff --git a/Lang/Minimal-BASIC/Leonardo-numbers b/Lang/Minimal-BASIC/Leonardo-numbers new file mode 120000 index 0000000000..c45ebe1ebc --- /dev/null +++ b/Lang/Minimal-BASIC/Leonardo-numbers @@ -0,0 +1 @@ +../../Task/Leonardo-numbers/Minimal-BASIC \ No newline at end of file diff --git a/Lang/Minimal-BASIC/Loops-Infinite b/Lang/Minimal-BASIC/Loops-Infinite new file mode 120000 index 0000000000..a936b362aa --- /dev/null +++ b/Lang/Minimal-BASIC/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/Minimal-BASIC \ No newline at end of file diff --git a/Lang/Minimal-BASIC/Monty-Hall-problem b/Lang/Minimal-BASIC/Monty-Hall-problem new file mode 120000 index 0000000000..e997b4d558 --- /dev/null +++ b/Lang/Minimal-BASIC/Monty-Hall-problem @@ -0,0 +1 @@ +../../Task/Monty-Hall-problem/Minimal-BASIC \ No newline at end of file diff --git a/Lang/Minimal-BASIC/Pancake-numbers b/Lang/Minimal-BASIC/Pancake-numbers new file mode 120000 index 0000000000..5141be0a11 --- /dev/null +++ b/Lang/Minimal-BASIC/Pancake-numbers @@ -0,0 +1 @@ +../../Task/Pancake-numbers/Minimal-BASIC \ No newline at end of file diff --git a/Lang/Minimal-BASIC/Sum-of-a-series b/Lang/Minimal-BASIC/Sum-of-a-series new file mode 120000 index 0000000000..b515c8004d --- /dev/null +++ b/Lang/Minimal-BASIC/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Minimal-BASIC \ No newline at end of file diff --git a/Lang/Miranda/Align-columns b/Lang/Miranda/Align-columns new file mode 120000 index 0000000000..ca88577a8d --- /dev/null +++ b/Lang/Miranda/Align-columns @@ -0,0 +1 @@ +../../Task/Align-columns/Miranda \ No newline at end of file diff --git a/Lang/Miranda/Arithmetic-derivative b/Lang/Miranda/Arithmetic-derivative new file mode 120000 index 0000000000..91683ddf96 --- /dev/null +++ b/Lang/Miranda/Arithmetic-derivative @@ -0,0 +1 @@ +../../Task/Arithmetic-derivative/Miranda \ No newline at end of file diff --git a/Lang/Miranda/Bell-numbers b/Lang/Miranda/Bell-numbers new file mode 120000 index 0000000000..6635e596b0 --- /dev/null +++ b/Lang/Miranda/Bell-numbers @@ -0,0 +1 @@ +../../Task/Bell-numbers/Miranda \ No newline at end of file diff --git a/Lang/Miranda/Combinations b/Lang/Miranda/Combinations new file mode 120000 index 0000000000..b252f73176 --- /dev/null +++ b/Lang/Miranda/Combinations @@ -0,0 +1 @@ +../../Task/Combinations/Miranda \ No newline at end of file diff --git a/Lang/Miranda/Display-a-linear-combination b/Lang/Miranda/Display-a-linear-combination new file mode 120000 index 0000000000..38a961bb6a --- /dev/null +++ b/Lang/Miranda/Display-a-linear-combination @@ -0,0 +1 @@ +../../Task/Display-a-linear-combination/Miranda \ No newline at end of file diff --git a/Lang/Miranda/Doomsday-rule b/Lang/Miranda/Doomsday-rule new file mode 120000 index 0000000000..91e25767d0 --- /dev/null +++ b/Lang/Miranda/Doomsday-rule @@ -0,0 +1 @@ +../../Task/Doomsday-rule/Miranda \ No newline at end of file diff --git a/Lang/Miranda/Execute-Brain- b/Lang/Miranda/Execute-Brain- new file mode 120000 index 0000000000..e3f7d58819 --- /dev/null +++ b/Lang/Miranda/Execute-Brain- @@ -0,0 +1 @@ +../../Task/Execute-Brain-/Miranda \ No newline at end of file diff --git a/Lang/Miranda/Fractran b/Lang/Miranda/Fractran new file mode 120000 index 0000000000..528ab3ee2e --- /dev/null +++ b/Lang/Miranda/Fractran @@ -0,0 +1 @@ +../../Task/Fractran/Miranda \ No newline at end of file diff --git a/Lang/Miranda/Hailstone-sequence b/Lang/Miranda/Hailstone-sequence new file mode 120000 index 0000000000..1f03fbb737 --- /dev/null +++ b/Lang/Miranda/Hailstone-sequence @@ -0,0 +1 @@ +../../Task/Hailstone-sequence/Miranda \ No newline at end of file diff --git a/Lang/Miranda/Isqrt-integer-square-root-of-X b/Lang/Miranda/Isqrt-integer-square-root-of-X new file mode 120000 index 0000000000..4b479d99e5 --- /dev/null +++ b/Lang/Miranda/Isqrt-integer-square-root-of-X @@ -0,0 +1 @@ +../../Task/Isqrt-integer-square-root-of-X/Miranda \ No newline at end of file diff --git a/Lang/Miranda/Leonardo-numbers b/Lang/Miranda/Leonardo-numbers new file mode 120000 index 0000000000..6f062a014a --- /dev/null +++ b/Lang/Miranda/Leonardo-numbers @@ -0,0 +1 @@ +../../Task/Leonardo-numbers/Miranda \ No newline at end of file diff --git a/Lang/Miranda/Loops-Infinite b/Lang/Miranda/Loops-Infinite new file mode 120000 index 0000000000..8845df4b78 --- /dev/null +++ b/Lang/Miranda/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/Miranda \ No newline at end of file diff --git a/Lang/Miranda/Modular-exponentiation b/Lang/Miranda/Modular-exponentiation new file mode 120000 index 0000000000..876dc45d07 --- /dev/null +++ b/Lang/Miranda/Modular-exponentiation @@ -0,0 +1 @@ +../../Task/Modular-exponentiation/Miranda \ No newline at end of file diff --git a/Lang/Miranda/Move-to-front-algorithm b/Lang/Miranda/Move-to-front-algorithm new file mode 120000 index 0000000000..ed5becbabe --- /dev/null +++ b/Lang/Miranda/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/Miranda \ No newline at end of file diff --git a/Lang/Miranda/Mutual-recursion b/Lang/Miranda/Mutual-recursion new file mode 120000 index 0000000000..42af709518 --- /dev/null +++ b/Lang/Miranda/Mutual-recursion @@ -0,0 +1 @@ +../../Task/Mutual-recursion/Miranda \ No newline at end of file diff --git a/Lang/Miranda/Old-lady-swallowed-a-fly b/Lang/Miranda/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..91f1f84abb --- /dev/null +++ b/Lang/Miranda/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/Miranda \ No newline at end of file diff --git a/Lang/Miranda/Partition-an-integer-x-into-n-primes b/Lang/Miranda/Partition-an-integer-x-into-n-primes new file mode 120000 index 0000000000..0d73af13aa --- /dev/null +++ b/Lang/Miranda/Partition-an-integer-x-into-n-primes @@ -0,0 +1 @@ +../../Task/Partition-an-integer-x-into-n-primes/Miranda \ No newline at end of file diff --git a/Lang/Miranda/Run-length-encoding b/Lang/Miranda/Run-length-encoding new file mode 120000 index 0000000000..e0fd07015b --- /dev/null +++ b/Lang/Miranda/Run-length-encoding @@ -0,0 +1 @@ +../../Task/Run-length-encoding/Miranda \ No newline at end of file diff --git a/Lang/Miranda/Sudan-function b/Lang/Miranda/Sudan-function new file mode 120000 index 0000000000..30973d5427 --- /dev/null +++ b/Lang/Miranda/Sudan-function @@ -0,0 +1 @@ +../../Task/Sudan-function/Miranda \ No newline at end of file diff --git a/Lang/Miranda/Super-d-numbers b/Lang/Miranda/Super-d-numbers new file mode 120000 index 0000000000..d99b0c174b --- /dev/null +++ b/Lang/Miranda/Super-d-numbers @@ -0,0 +1 @@ +../../Task/Super-d-numbers/Miranda \ No newline at end of file diff --git a/Lang/Miranda/Zeckendorf-number-representation b/Lang/Miranda/Zeckendorf-number-representation new file mode 120000 index 0000000000..8a316c3af1 --- /dev/null +++ b/Lang/Miranda/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/Miranda \ No newline at end of file diff --git a/Lang/Mn/00-LANG.txt b/Lang/Mn/00-LANG.txt new file mode 100644 index 0000000000..0fd90d2c3a --- /dev/null +++ b/Lang/Mn/00-LANG.txt @@ -0,0 +1,7 @@ +{{stub}}{{language|mn}} +mn is a minimalistic, concatenative, functional stack language. It is a very simple subset of [[min]]. + +==Links== +*[https://h3rald.com/mn/Mn_DeveloperGuide.htm Learn mn] + +{{Language programming paradigm|Concatenative}} \ No newline at end of file diff --git a/Lang/Mn/00-META.yaml b/Lang/Mn/00-META.yaml new file mode 100644 index 0000000000..f79f1602c3 --- /dev/null +++ b/Lang/Mn/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Mn diff --git a/Lang/Mn/Factorial b/Lang/Mn/Factorial new file mode 120000 index 0000000000..4c7a3c3b43 --- /dev/null +++ b/Lang/Mn/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Mn \ No newline at end of file diff --git a/Lang/Mn/Loops-While b/Lang/Mn/Loops-While new file mode 120000 index 0000000000..9e10aebd40 --- /dev/null +++ b/Lang/Mn/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/Mn \ No newline at end of file diff --git a/Lang/Modula-2/00-LANG.txt b/Lang/Modula-2/00-LANG.txt index 854aa29a1a..62faf6e14c 100644 --- a/Lang/Modula-2/00-LANG.txt +++ b/Lang/Modula-2/00-LANG.txt @@ -26,4 +26,11 @@ Modula-2 was designed by Niklaus Wirth at ETH Zurich as a systems implementation * [http://sourceforge.net/projects/schwarzerkaffee Schwarzer Kaffee] ==Modula-2 on IRC== -* [irc://irc.freenode.net/#modula-2 irc://irc.freenode.net/#modula-2] \ No newline at end of file +* [irc://irc.freenode.net/#modula-2 irc://irc.freenode.net/#modula-2] + +===See also=== +* [[Modula-3]] +* [[Oberon-07]] +* [[Oberon-2]] +* [[Component Pascal]] +* [[Zonnon]] \ No newline at end of file diff --git a/Lang/Modula-2/AKS-test-for-primes b/Lang/Modula-2/AKS-test-for-primes new file mode 120000 index 0000000000..f86ed2a172 --- /dev/null +++ b/Lang/Modula-2/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Abundant-odd-numbers b/Lang/Modula-2/Abundant-odd-numbers new file mode 120000 index 0000000000..acae176170 --- /dev/null +++ b/Lang/Modula-2/Abundant-odd-numbers @@ -0,0 +1 @@ +../../Task/Abundant-odd-numbers/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Cistercian-numerals b/Lang/Modula-2/Cistercian-numerals new file mode 120000 index 0000000000..5da4e51fc7 --- /dev/null +++ b/Lang/Modula-2/Cistercian-numerals @@ -0,0 +1 @@ +../../Task/Cistercian-numerals/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Cumulative-standard-deviation b/Lang/Modula-2/Cumulative-standard-deviation new file mode 120000 index 0000000000..49f430ac8e --- /dev/null +++ b/Lang/Modula-2/Cumulative-standard-deviation @@ -0,0 +1 @@ +../../Task/Cumulative-standard-deviation/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Day-of-the-week b/Lang/Modula-2/Day-of-the-week new file mode 120000 index 0000000000..626da93e5e --- /dev/null +++ b/Lang/Modula-2/Day-of-the-week @@ -0,0 +1 @@ +../../Task/Day-of-the-week/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Diversity-prediction-theorem b/Lang/Modula-2/Diversity-prediction-theorem new file mode 120000 index 0000000000..c351696cc1 --- /dev/null +++ b/Lang/Modula-2/Diversity-prediction-theorem @@ -0,0 +1 @@ +../../Task/Diversity-prediction-theorem/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Dutch-national-flag-problem b/Lang/Modula-2/Dutch-national-flag-problem new file mode 120000 index 0000000000..b6400fd8d9 --- /dev/null +++ b/Lang/Modula-2/Dutch-national-flag-problem @@ -0,0 +1 @@ +../../Task/Dutch-national-flag-problem/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Equilibrium-index b/Lang/Modula-2/Equilibrium-index new file mode 120000 index 0000000000..434b864e3f --- /dev/null +++ b/Lang/Modula-2/Equilibrium-index @@ -0,0 +1 @@ +../../Task/Equilibrium-index/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Factors-of-an-integer b/Lang/Modula-2/Factors-of-an-integer new file mode 120000 index 0000000000..19271a7965 --- /dev/null +++ b/Lang/Modula-2/Factors-of-an-integer @@ -0,0 +1 @@ +../../Task/Factors-of-an-integer/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Gamma-function b/Lang/Modula-2/Gamma-function new file mode 120000 index 0000000000..f14cc894e2 --- /dev/null +++ b/Lang/Modula-2/Gamma-function @@ -0,0 +1 @@ +../../Task/Gamma-function/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Generate-lower-case-ASCII-alphabet b/Lang/Modula-2/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..94aba1f8a9 --- /dev/null +++ b/Lang/Modula-2/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Gray-code b/Lang/Modula-2/Gray-code new file mode 120000 index 0000000000..8cb45ff695 --- /dev/null +++ b/Lang/Modula-2/Gray-code @@ -0,0 +1 @@ +../../Task/Gray-code/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Luhn-test-of-credit-card-numbers b/Lang/Modula-2/Luhn-test-of-credit-card-numbers new file mode 120000 index 0000000000..7ff802d85c --- /dev/null +++ b/Lang/Modula-2/Luhn-test-of-credit-card-numbers @@ -0,0 +1 @@ +../../Task/Luhn-test-of-credit-card-numbers/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/M-bius-function b/Lang/Modula-2/M-bius-function new file mode 120000 index 0000000000..e2d4a4a9b1 --- /dev/null +++ b/Lang/Modula-2/M-bius-function @@ -0,0 +1 @@ +../../Task/M-bius-function/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Magic-constant b/Lang/Modula-2/Magic-constant new file mode 120000 index 0000000000..d6cf44baf4 --- /dev/null +++ b/Lang/Modula-2/Magic-constant @@ -0,0 +1 @@ +../../Task/Magic-constant/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Map-range b/Lang/Modula-2/Map-range new file mode 120000 index 0000000000..d2da488e09 --- /dev/null +++ b/Lang/Modula-2/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Mayan-numerals b/Lang/Modula-2/Mayan-numerals new file mode 120000 index 0000000000..68f34cbb07 --- /dev/null +++ b/Lang/Modula-2/Mayan-numerals @@ -0,0 +1 @@ +../../Task/Mayan-numerals/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Monty-Hall-problem b/Lang/Modula-2/Monty-Hall-problem new file mode 120000 index 0000000000..9ad6c8767a --- /dev/null +++ b/Lang/Modula-2/Monty-Hall-problem @@ -0,0 +1 @@ +../../Task/Monty-Hall-problem/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Multifactorial b/Lang/Modula-2/Multifactorial new file mode 120000 index 0000000000..ba5a38f5d3 --- /dev/null +++ b/Lang/Modula-2/Multifactorial @@ -0,0 +1 @@ +../../Task/Multifactorial/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Nth-root b/Lang/Modula-2/Nth-root new file mode 120000 index 0000000000..0efaa69472 --- /dev/null +++ b/Lang/Modula-2/Nth-root @@ -0,0 +1 @@ +../../Task/Nth-root/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Periodic-table b/Lang/Modula-2/Periodic-table new file mode 120000 index 0000000000..20953bda9a --- /dev/null +++ b/Lang/Modula-2/Periodic-table @@ -0,0 +1 @@ +../../Task/Periodic-table/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Ramer-Douglas-Peucker-line-simplification b/Lang/Modula-2/Ramer-Douglas-Peucker-line-simplification new file mode 120000 index 0000000000..ff583aca48 --- /dev/null +++ b/Lang/Modula-2/Ramer-Douglas-Peucker-line-simplification @@ -0,0 +1 @@ +../../Task/Ramer-Douglas-Peucker-line-simplification/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Semiprime b/Lang/Modula-2/Semiprime new file mode 120000 index 0000000000..108e390f08 --- /dev/null +++ b/Lang/Modula-2/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Temperature-conversion b/Lang/Modula-2/Temperature-conversion new file mode 120000 index 0000000000..fa236503d3 --- /dev/null +++ b/Lang/Modula-2/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Tic-tac-toe b/Lang/Modula-2/Tic-tac-toe new file mode 120000 index 0000000000..21b0370c7a --- /dev/null +++ b/Lang/Modula-2/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Zeckendorf-number-representation b/Lang/Modula-2/Zeckendorf-number-representation new file mode 120000 index 0000000000..bbadf943ec --- /dev/null +++ b/Lang/Modula-2/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-3/00-LANG.txt b/Lang/Modula-3/00-LANG.txt index 582f870540..aaa0f4b8bf 100644 --- a/Lang/Modula-3/00-LANG.txt +++ b/Lang/Modula-3/00-LANG.txt @@ -21,4 +21,11 @@ Its main implementation is [[Critical Mass Modula-3]]. Modula-3 influenced a few languages such as [[C Sharp|C#]], [[Java]], [[Ocaml]] and [[Python]]. ==Links== -* [http://en.wikipedia.org/wiki/Modula-3 Modula-3 at Wikipedia] \ No newline at end of file +* [http://en.wikipedia.org/wiki/Modula-3 Modula-3 at Wikipedia] + +===See also=== +* [[Modula-2]] +* [[Oberon-07]] +* [[Oberon-2]] +* [[Component Pascal]] +* [[Zonnon]] \ No newline at end of file diff --git a/Lang/Modula-3/Additive-primes b/Lang/Modula-3/Additive-primes new file mode 120000 index 0000000000..b81b571c35 --- /dev/null +++ b/Lang/Modula-3/Additive-primes @@ -0,0 +1 @@ +../../Task/Additive-primes/Modula-3 \ No newline at end of file diff --git a/Lang/Modula-3/Comments b/Lang/Modula-3/Comments deleted file mode 120000 index 8c3489c305..0000000000 --- a/Lang/Modula-3/Comments +++ /dev/null @@ -1 +0,0 @@ -../../Task/Comments/Modula-3 \ No newline at end of file diff --git a/Lang/Modula-3/Pascals-triangle b/Lang/Modula-3/Pascals-triangle new file mode 120000 index 0000000000..093a7901c2 --- /dev/null +++ b/Lang/Modula-3/Pascals-triangle @@ -0,0 +1 @@ +../../Task/Pascals-triangle/Modula-3 \ No newline at end of file diff --git a/Lang/Mojo/Hunt-the-Wumpus b/Lang/Mojo/Hunt-the-Wumpus new file mode 120000 index 0000000000..a79c86df71 --- /dev/null +++ b/Lang/Mojo/Hunt-the-Wumpus @@ -0,0 +1 @@ +../../Task/Hunt-the-Wumpus/Mojo \ No newline at end of file diff --git a/Lang/MoonBit/00-LANG.txt b/Lang/MoonBit/00-LANG.txt new file mode 100644 index 0000000000..cf5345dc27 --- /dev/null +++ b/Lang/MoonBit/00-LANG.txt @@ -0,0 +1,13 @@ +{{language|MoonBit +|exec=bytecode +|safety=safe +|strength=strong +|gc=yes +|site=https://www.moonbitlang.com/} +}} +'''MoonBit''' is a general-purpose programming language and toolchain designed for high performance and resource efficiency, optimized for WebAssembly (Wasm). It is developed by a young and passionate team led by Zhang Hongbo. One of the motivations behind MoonBit’s creation was Zhang’s belief that existing languages like Java, Go, and Rust do not fully leverage the security and speed advantages of the WebAssembly instruction set, particularly in cloud computing and edge computing. After its initial release with native WebAssembly support, MoonBit later added support for JavaScript, Native, and the LLVM backend. + +MoonBit was publicly released in August 2023 and is currently in its beta stage. + +==Todo== +* [[Tasks not implemented in MoonBit]] \ No newline at end of file diff --git a/Lang/MoonBit/00-META.yaml b/Lang/MoonBit/00-META.yaml new file mode 100644 index 0000000000..97e1356190 --- /dev/null +++ b/Lang/MoonBit/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:MoonBit diff --git a/Lang/MoonBit/Array-length b/Lang/MoonBit/Array-length new file mode 120000 index 0000000000..4a5666710a --- /dev/null +++ b/Lang/MoonBit/Array-length @@ -0,0 +1 @@ +../../Task/Array-length/MoonBit \ No newline at end of file diff --git a/Lang/MoonBit/Hello-world-Text b/Lang/MoonBit/Hello-world-Text new file mode 120000 index 0000000000..f3db6f7a6c --- /dev/null +++ b/Lang/MoonBit/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/MoonBit \ No newline at end of file diff --git a/Lang/MoonRock/00-LANG.txt b/Lang/MoonRock/00-LANG.txt new file mode 100644 index 0000000000..dcba29adb9 --- /dev/null +++ b/Lang/MoonRock/00-LANG.txt @@ -0,0 +1,68 @@ +{{language|MoonRock +|exec=machine +|site=http://www.rowan.sensation.net.au/moonrock.html}} +{{language programming paradigm|Imperative}} +{{implementation|BASIC}} +'''MoonRock''' is a compiler for a [[BASIC]]-like programming language, developed by Rowan Crowe. Released for [[MS-DOS]] and compatible systems, MoonRock enables compilation to assembly language and linking to COM executable files. The compiler is known for producing exceptionally concise executables; for example, a "[[Hello world|Hello, World!]]" program can be compiled into a COM file as small as 276 bytes. + +MoonRock is a programming language specifically designed to facilitate the creation of programs that can be easily translated into assembly language. This design choice emphasizes simplicity and direct mapping to low-level operations, making it particularly suitable for environments where performance and control over hardware are critical. The language's syntax and features are structured to align closely with assembly language constructs while benefiting from some higher-level abstractions provided by BASIC. + +== MoonRock Version 0.50 == +=== Program Structure === +The definitions of arrays must be included within the BEGIN DEF section of the program. + +=== Control Structures === +The ''[[Loops/For|for]]'' loop requires that both the start and end values be variables, constants, or literals; expressions are not permitted. The language does not implement a ''[[Loops/Do-while|repeat-until]]'' loop. + +=== Arithmetic Operations === +MoonRock 0.50 does not support [[Floating point|floating-point numbers]] and operations. Division using the / operator produces rounded [[Arithmetic/Integer|integer]] results. For integer division, the \ operator must be used. For example: + +A% = 1 / 3 +PRINT A% + "\n" +A% = 2 / 3 +PRINT A% + "\n" +A% = 3 / 3 +PRINT A% + "\n" + +produces the output: +
    +0
    +1
    +1
    +
    +The MOD function is not implemented for 32-bit integers (doublewords). + +=== Comparison Operations === +Both operands in comparison operations must be literals, constants, or variables; expressions are not allowed. Only variables of the same type can be compared. Attempting to compare variables of different types, such as A& > B%, may produce incorrect results. + +=== Output === +To output the value of a named constant, it must be passed as an argument to the STR function: + +PRINT "Up to " + STR(%MaxNumber) + "\n" + +Formatted output is not supported. Users may create custom subroutines as a workaround, such as: + +SUB PrintStr(S$, Width%) + IF LEN(S$) > Width% THEN + PRINT S$ + ELSE + S$ = SPACE(Width%) + S$ + PRINT RIGHT(S$, Width%) + ENDIF +END SUB + + +=== Abnormal Behaviors === +The manual states: ''Keywords are shown in all upper case to aid readability. They may be of any case in the source code''. However, some statements function solely when written in lowercase. For example, the statement: + +if A@ = 0 then print B% + " " + +operates correctly only when if and then are in lowercase. Conversely, the following formulation works regardless of case: + +IF A@ = 0 THEN + PRINT B% + " " +ENDIF + + +== External links == +* [https://github.com/DosWorld/moonrock MoonRock on GitHub] \ No newline at end of file diff --git a/Lang/MoonRock/00-META.yaml b/Lang/MoonRock/00-META.yaml new file mode 100644 index 0000000000..8869a57523 --- /dev/null +++ b/Lang/MoonRock/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:MoonRock diff --git a/Lang/MoonRock/100-doors b/Lang/MoonRock/100-doors new file mode 120000 index 0000000000..35643d2a2f --- /dev/null +++ b/Lang/MoonRock/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/MoonRock \ No newline at end of file diff --git a/Lang/MoonRock/Abundant-deficient-and-perfect-number-classifications b/Lang/MoonRock/Abundant-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..5a720f6808 --- /dev/null +++ b/Lang/MoonRock/Abundant-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant-deficient-and-perfect-number-classifications/MoonRock \ No newline at end of file diff --git a/Lang/MoonRock/Bell-numbers b/Lang/MoonRock/Bell-numbers new file mode 120000 index 0000000000..1519c89b24 --- /dev/null +++ b/Lang/MoonRock/Bell-numbers @@ -0,0 +1 @@ +../../Task/Bell-numbers/MoonRock \ No newline at end of file diff --git a/Lang/MoonRock/Day-of-the-week b/Lang/MoonRock/Day-of-the-week new file mode 120000 index 0000000000..3423abb3da --- /dev/null +++ b/Lang/MoonRock/Day-of-the-week @@ -0,0 +1 @@ +../../Task/Day-of-the-week/MoonRock \ No newline at end of file diff --git a/Lang/MoonRock/Ethiopian-multiplication b/Lang/MoonRock/Ethiopian-multiplication new file mode 120000 index 0000000000..99b728ad22 --- /dev/null +++ b/Lang/MoonRock/Ethiopian-multiplication @@ -0,0 +1 @@ +../../Task/Ethiopian-multiplication/MoonRock \ No newline at end of file diff --git a/Lang/MoonRock/Factors-of-an-integer b/Lang/MoonRock/Factors-of-an-integer new file mode 120000 index 0000000000..9cb6716a51 --- /dev/null +++ b/Lang/MoonRock/Factors-of-an-integer @@ -0,0 +1 @@ +../../Task/Factors-of-an-integer/MoonRock \ No newline at end of file diff --git a/Lang/MoonRock/Fibonacci-sequence b/Lang/MoonRock/Fibonacci-sequence new file mode 120000 index 0000000000..633e95692a --- /dev/null +++ b/Lang/MoonRock/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/MoonRock \ No newline at end of file diff --git a/Lang/MoonRock/Josephus-problem b/Lang/MoonRock/Josephus-problem new file mode 120000 index 0000000000..1084916ce4 --- /dev/null +++ b/Lang/MoonRock/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/MoonRock \ No newline at end of file diff --git a/Lang/MoonRock/Leap-year b/Lang/MoonRock/Leap-year new file mode 120000 index 0000000000..5ab049d315 --- /dev/null +++ b/Lang/MoonRock/Leap-year @@ -0,0 +1 @@ +../../Task/Leap-year/MoonRock \ No newline at end of file diff --git a/Lang/MoonRock/Long-year b/Lang/MoonRock/Long-year new file mode 120000 index 0000000000..cc090c489a --- /dev/null +++ b/Lang/MoonRock/Long-year @@ -0,0 +1 @@ +../../Task/Long-year/MoonRock \ No newline at end of file diff --git a/Lang/MoonRock/Semiprime b/Lang/MoonRock/Semiprime new file mode 120000 index 0000000000..9c66936bd7 --- /dev/null +++ b/Lang/MoonRock/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/MoonRock \ No newline at end of file diff --git a/Lang/MySQL/00-LANG.txt b/Lang/MySQL/00-LANG.txt index 9f2e3a69fb..bf94001666 100644 --- a/Lang/MySQL/00-LANG.txt +++ b/Lang/MySQL/00-LANG.txt @@ -1,9 +1,9 @@ {{language}} '''MySQL''' is a multithreaded, multi-user, SQL Database Management System (DBMS) with more than six million installations. -'''MySQL''' is owned and sponsored by a single for-profit firm, the Swedish company MySQL AB, which holds the copyright to most of the codebase. This is similar to the JBoss model and how the Free Software Foundation handles copyright in its projects, and dissimilar to how the Apache project does it, where the software is developed by a public community, and the copyright to the codebase is owned by its individual authors. +'''MySQL''' is owned and sponsored by a single for-profit firm, Oracle, which holds the copyright to most of the codebase. This is similar to the JBoss model and how the Free Software Foundation handles copyright in its projects, and dissimilar to how the Apache project does it, where the software is developed by a public community, and the copyright to the codebase is owned by its individual authors. -The company develops and maintains the system, selling support and service contracts, as well as proprietary-licensed copies of MySQL, and employing people all over the world who collaborate via the Internet. MySQL AB was founded by David Axmark, Allan Larsson, and Michael "Monty" Widenius. +The company develops and maintains the system, selling support and service contracts, as well as a cloud variant called HeatWave (part of Oracle Cloud), proprietary-licensed copies of MySQL, and employing people all over the world who collaborate via the Internet. MySQL AB was founded by David Axmark, Allan Larsson, and Michael "Monty" Widenius. ==Citations== * [http://en.wikipedia.org/wiki/Mysql Wikipedia:MySQL] diff --git a/Lang/NS-HUBASIC/Empty-program b/Lang/NS-HUBASIC/Empty-program deleted file mode 120000 index 8edcb8591a..0000000000 --- a/Lang/NS-HUBASIC/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/NS-HUBASIC \ No newline at end of file diff --git a/Lang/Nascom-BASIC/Damm-algorithm b/Lang/Nascom-BASIC/Damm-algorithm new file mode 120000 index 0000000000..5a6439a18c --- /dev/null +++ b/Lang/Nascom-BASIC/Damm-algorithm @@ -0,0 +1 @@ +../../Task/Damm-algorithm/Nascom-BASIC \ No newline at end of file diff --git a/Lang/Nascom-BASIC/Dragon-curve b/Lang/Nascom-BASIC/Dragon-curve new file mode 120000 index 0000000000..36b4172957 --- /dev/null +++ b/Lang/Nascom-BASIC/Dragon-curve @@ -0,0 +1 @@ +../../Task/Dragon-curve/Nascom-BASIC \ No newline at end of file diff --git a/Lang/Nascom-BASIC/Langtons-ant b/Lang/Nascom-BASIC/Langtons-ant new file mode 120000 index 0000000000..d0fdcffe2f --- /dev/null +++ b/Lang/Nascom-BASIC/Langtons-ant @@ -0,0 +1 @@ +../../Task/Langtons-ant/Nascom-BASIC \ No newline at end of file diff --git a/Lang/Nascom-BASIC/Levenshtein-distance b/Lang/Nascom-BASIC/Levenshtein-distance new file mode 120000 index 0000000000..c821e59923 --- /dev/null +++ b/Lang/Nascom-BASIC/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/Nascom-BASIC \ No newline at end of file diff --git a/Lang/Nascom-BASIC/Luhn-test-of-credit-card-numbers b/Lang/Nascom-BASIC/Luhn-test-of-credit-card-numbers new file mode 120000 index 0000000000..1d7e8b0698 --- /dev/null +++ b/Lang/Nascom-BASIC/Luhn-test-of-credit-card-numbers @@ -0,0 +1 @@ +../../Task/Luhn-test-of-credit-card-numbers/Nascom-BASIC \ No newline at end of file diff --git a/Lang/Nascom-BASIC/Mayan-numerals b/Lang/Nascom-BASIC/Mayan-numerals new file mode 120000 index 0000000000..d2108ce9fa --- /dev/null +++ b/Lang/Nascom-BASIC/Mayan-numerals @@ -0,0 +1 @@ +../../Task/Mayan-numerals/Nascom-BASIC \ No newline at end of file diff --git a/Lang/Nascom-BASIC/Old-Russian-measure-of-length b/Lang/Nascom-BASIC/Old-Russian-measure-of-length new file mode 120000 index 0000000000..73ef2957e7 --- /dev/null +++ b/Lang/Nascom-BASIC/Old-Russian-measure-of-length @@ -0,0 +1 @@ +../../Task/Old-Russian-measure-of-length/Nascom-BASIC \ No newline at end of file diff --git a/Lang/NetRexx/00-LANG.txt b/Lang/NetRexx/00-LANG.txt index f110c9bdb8..3f624ad431 100644 --- a/Lang/NetRexx/00-LANG.txt +++ b/Lang/NetRexx/00-LANG.txt @@ -29,7 +29,7 @@ as languages such as Java, while preserving the low threshold to learning and th On the 8th of June 2011, IBM transferred ownership of the reference implementation of NetRexx to The Rexx Language Association (RexxLA) for administration under the [http://site.icu-project.org ICU - International Components for Unicode] open source license. -On September 12th 2022, NetRexx 4.04 was released +On March 3rd, 2024, NetRexx 4.06-GA was released. ==== Useful Links ==== * [http://www.netrexx.org The NetRexx Programming Language - www.netrexx.org] diff --git a/Lang/NetRexx/Haversine-formula b/Lang/NetRexx/Haversine-formula new file mode 120000 index 0000000000..bbcbbd8775 --- /dev/null +++ b/Lang/NetRexx/Haversine-formula @@ -0,0 +1 @@ +../../Task/Haversine-formula/NetRexx \ No newline at end of file diff --git a/Lang/NewLISP/Abbreviations-simple b/Lang/NewLISP/Abbreviations-simple new file mode 120000 index 0000000000..ec4184c6a2 --- /dev/null +++ b/Lang/NewLISP/Abbreviations-simple @@ -0,0 +1 @@ +../../Task/Abbreviations-simple/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Ascending-primes b/Lang/NewLISP/Ascending-primes new file mode 120000 index 0000000000..68daf13118 --- /dev/null +++ b/Lang/NewLISP/Ascending-primes @@ -0,0 +1 @@ +../../Task/Ascending-primes/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Associative-array-Merging b/Lang/NewLISP/Associative-array-Merging new file mode 120000 index 0000000000..8ebd2e6646 --- /dev/null +++ b/Lang/NewLISP/Associative-array-Merging @@ -0,0 +1 @@ +../../Task/Associative-array-Merging/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Cartesian-product-of-two-or-more-lists b/Lang/NewLISP/Cartesian-product-of-two-or-more-lists new file mode 120000 index 0000000000..4a3b5275b2 --- /dev/null +++ b/Lang/NewLISP/Cartesian-product-of-two-or-more-lists @@ -0,0 +1 @@ +../../Task/Cartesian-product-of-two-or-more-lists/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Compare-a-list-of-strings b/Lang/NewLISP/Compare-a-list-of-strings new file mode 120000 index 0000000000..9b0eddc19c --- /dev/null +++ b/Lang/NewLISP/Compare-a-list-of-strings @@ -0,0 +1 @@ +../../Task/Compare-a-list-of-strings/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Department-numbers b/Lang/NewLISP/Department-numbers new file mode 120000 index 0000000000..17043dfb0a --- /dev/null +++ b/Lang/NewLISP/Department-numbers @@ -0,0 +1 @@ +../../Task/Department-numbers/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Dinesmans-multiple-dwelling-problem b/Lang/NewLISP/Dinesmans-multiple-dwelling-problem new file mode 120000 index 0000000000..0b5efae41b --- /dev/null +++ b/Lang/NewLISP/Dinesmans-multiple-dwelling-problem @@ -0,0 +1 @@ +../../Task/Dinesmans-multiple-dwelling-problem/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Find-Chess960-starting-position-identifier b/Lang/NewLISP/Find-Chess960-starting-position-identifier new file mode 120000 index 0000000000..772e0d75d4 --- /dev/null +++ b/Lang/NewLISP/Find-Chess960-starting-position-identifier @@ -0,0 +1 @@ +../../Task/Find-Chess960-starting-position-identifier/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Loops-With-multiple-ranges b/Lang/NewLISP/Loops-With-multiple-ranges new file mode 120000 index 0000000000..ef48847607 --- /dev/null +++ b/Lang/NewLISP/Loops-With-multiple-ranges @@ -0,0 +1 @@ +../../Task/Loops-With-multiple-ranges/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Matrix-multiplication b/Lang/NewLISP/Matrix-multiplication new file mode 120000 index 0000000000..0badc9299f --- /dev/null +++ b/Lang/NewLISP/Matrix-multiplication @@ -0,0 +1 @@ +../../Task/Matrix-multiplication/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Multisplit b/Lang/NewLISP/Multisplit new file mode 120000 index 0000000000..1bb5fea36e --- /dev/null +++ b/Lang/NewLISP/Multisplit @@ -0,0 +1 @@ +../../Task/Multisplit/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Range-consolidation b/Lang/NewLISP/Range-consolidation new file mode 120000 index 0000000000..15f7beee34 --- /dev/null +++ b/Lang/NewLISP/Range-consolidation @@ -0,0 +1 @@ +../../Task/Range-consolidation/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Range-expansion b/Lang/NewLISP/Range-expansion new file mode 120000 index 0000000000..8f2d253805 --- /dev/null +++ b/Lang/NewLISP/Range-expansion @@ -0,0 +1 @@ +../../Task/Range-expansion/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Run-length-encoding b/Lang/NewLISP/Run-length-encoding new file mode 120000 index 0000000000..91cae97224 --- /dev/null +++ b/Lang/NewLISP/Run-length-encoding @@ -0,0 +1 @@ +../../Task/Run-length-encoding/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Set-consolidation b/Lang/NewLISP/Set-consolidation new file mode 120000 index 0000000000..9d4d20d448 --- /dev/null +++ b/Lang/NewLISP/Set-consolidation @@ -0,0 +1 @@ +../../Task/Set-consolidation/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Sorting-algorithms-Permutation-sort b/Lang/NewLISP/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..a14257af91 --- /dev/null +++ b/Lang/NewLISP/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Split-a-character-string-based-on-change-of-character b/Lang/NewLISP/Split-a-character-string-based-on-change-of-character new file mode 120000 index 0000000000..5af27e593c --- /dev/null +++ b/Lang/NewLISP/Split-a-character-string-based-on-change-of-character @@ -0,0 +1 @@ +../../Task/Split-a-character-string-based-on-change-of-character/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Text-processing-1 b/Lang/NewLISP/Text-processing-1 new file mode 120000 index 0000000000..39b0cd8b87 --- /dev/null +++ b/Lang/NewLISP/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Text-processing-Max-licenses-in-use b/Lang/NewLISP/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..fca40fd641 --- /dev/null +++ b/Lang/NewLISP/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Truncatable-primes b/Lang/NewLISP/Truncatable-primes new file mode 120000 index 0000000000..52cd8db47d --- /dev/null +++ b/Lang/NewLISP/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/NewLISP \ No newline at end of file diff --git a/Lang/Nickle/00-LANG.txt b/Lang/Nickle/00-LANG.txt index 53bb3afeae..e2643c2540 100644 --- a/Lang/Nickle/00-LANG.txt +++ b/Lang/Nickle/00-LANG.txt @@ -19,7 +19,7 @@ Other datatypes include multi-dimensional arrays, strings, structures, tagged un The reference implementation includes an interactive top level with byte code compilation before evaluation. Example: -/* Arrays to JSON */ +/* Arrays to JSON */ autoimport JSON; int [*] d = {1,2,3}; poly [*] p = {1, "abc", 42}; @@ -39,7 +39,8 @@ print f; for (int i = 0; i < dim(p); i++) { printf("%v ", p[i]); } -printf("\n"); +printf("\n"); +
    {{out}}
    prompt$ nickle sampler.5c
    diff --git a/Lang/Nim/Bioinformatics-base-count b/Lang/Nim/Bioinformatics-base-count
    deleted file mode 120000
    index 14fcd687ff..0000000000
    --- a/Lang/Nim/Bioinformatics-base-count
    +++ /dev/null
    @@ -1 +0,0 @@
    -../../Task/Bioinformatics-base-count/Nim
    \ No newline at end of file
    diff --git a/Lang/Nim/Meissel-Mertens-constant b/Lang/Nim/Meissel-Mertens-constant
    deleted file mode 120000
    index 760c7d7443..0000000000
    --- a/Lang/Nim/Meissel-Mertens-constant
    +++ /dev/null
    @@ -1 +0,0 @@
    -../../Task/Meissel-Mertens-constant/Nim
    \ No newline at end of file
    diff --git a/Lang/Nim/Miller-Rabin-primality-test b/Lang/Nim/Miller-Rabin-primality-test
    deleted file mode 120000
    index 1ce4ac13f6..0000000000
    --- a/Lang/Nim/Miller-Rabin-primality-test
    +++ /dev/null
    @@ -1 +0,0 @@
    -../../Task/Miller-Rabin-primality-test/Nim
    \ No newline at end of file
    diff --git a/Lang/Nim/Quaternion-type b/Lang/Nim/Quaternion-type
    deleted file mode 120000
    index 384e273bfc..0000000000
    --- a/Lang/Nim/Quaternion-type
    +++ /dev/null
    @@ -1 +0,0 @@
    -../../Task/Quaternion-type/Nim
    \ No newline at end of file
    diff --git a/Lang/Nim/Sorting-Algorithms-Circle-Sort b/Lang/Nim/Sorting-Algorithms-Circle-Sort
    deleted file mode 120000
    index 80141c2866..0000000000
    --- a/Lang/Nim/Sorting-Algorithms-Circle-Sort
    +++ /dev/null
    @@ -1 +0,0 @@
    -../../Task/Sorting-Algorithms-Circle-Sort/Nim
    \ No newline at end of file
    diff --git a/Lang/Nom/00-LANG.txt b/Lang/Nom/00-LANG.txt
    new file mode 100644
    index 0000000000..596e8bc965
    --- /dev/null
    +++ b/Lang/Nom/00-LANG.txt
    @@ -0,0 +1,18 @@
    +{{language|Nom}}
    +
    +Nom is an interpreted and also compiling (via the translation scripts)
    +language. Documentation for ''Nom'' can be found at [www.nomlang.org] along
    +with the downloadable [http://nomlang.org/download implementation]. 
    +All the source code is also hosted in [https://sourceforge.net sourceforge] 
    +at https://bumble.sf.net/books/pars/
    +
    +Nom is based on the PEP (''Parsing Engine for Patterns'') virtual machine, 
    +which is a text-based virtual machine. The PEP virtual machine is 
    +documented at [http://nomlang.org/doc/machine/]. Nom was first ''conceived'' 
    +around about 2005 but a good working implementation (the 
    +[https://bumble.sf.net/books/pars/object/pep.c pep] interpreter) was not 
    +achieved until approximately 2019. 
    +
    +Nom is, I believe a new approach to recognising/parsing/transforming/transpiling/compiling context-free languages
    +since it uses the same standard Unix-style approach of a ''text-stream-filter''
    +as with tools like ''sed'' or ''awk''.
    \ No newline at end of file
    diff --git a/Lang/Nom/00-META.yaml b/Lang/Nom/00-META.yaml
    new file mode 100644
    index 0000000000..347649abaa
    --- /dev/null
    +++ b/Lang/Nom/00-META.yaml
    @@ -0,0 +1,2 @@
    +---
    +from: http://rosettacode.org/wiki/Category:Nom
    diff --git a/Lang/Nom/Balanced-brackets b/Lang/Nom/Balanced-brackets
    new file mode 120000
    index 0000000000..53c6847c48
    --- /dev/null
    +++ b/Lang/Nom/Balanced-brackets
    @@ -0,0 +1 @@
    +../../Task/Balanced-brackets/Nom
    \ No newline at end of file
    diff --git a/Lang/Nom/CSV-to-HTML-translation b/Lang/Nom/CSV-to-HTML-translation
    new file mode 120000
    index 0000000000..efc535b187
    --- /dev/null
    +++ b/Lang/Nom/CSV-to-HTML-translation
    @@ -0,0 +1 @@
    +../../Task/CSV-to-HTML-translation/Nom
    \ No newline at end of file
    diff --git a/Lang/Nom/Determine-if-a-string-is-numeric b/Lang/Nom/Determine-if-a-string-is-numeric
    new file mode 120000
    index 0000000000..dc0b5a67ea
    --- /dev/null
    +++ b/Lang/Nom/Determine-if-a-string-is-numeric
    @@ -0,0 +1 @@
    +../../Task/Determine-if-a-string-is-numeric/Nom
    \ No newline at end of file
    diff --git a/Lang/Nom/Empty-string b/Lang/Nom/Empty-string
    new file mode 120000
    index 0000000000..e51cf14c29
    --- /dev/null
    +++ b/Lang/Nom/Empty-string
    @@ -0,0 +1 @@
    +../../Task/Empty-string/Nom
    \ No newline at end of file
    diff --git a/Lang/Nom/Even-or-odd b/Lang/Nom/Even-or-odd
    new file mode 120000
    index 0000000000..a93a39c338
    --- /dev/null
    +++ b/Lang/Nom/Even-or-odd
    @@ -0,0 +1 @@
    +../../Task/Even-or-odd/Nom
    \ No newline at end of file
    diff --git a/Lang/Nom/Hello-world-Text b/Lang/Nom/Hello-world-Text
    new file mode 120000
    index 0000000000..6575bd7149
    --- /dev/null
    +++ b/Lang/Nom/Hello-world-Text
    @@ -0,0 +1 @@
    +../../Task/Hello-world-Text/Nom
    \ No newline at end of file
    diff --git a/Lang/Nom/Input-loop b/Lang/Nom/Input-loop
    new file mode 120000
    index 0000000000..c687c9a3a9
    --- /dev/null
    +++ b/Lang/Nom/Input-loop
    @@ -0,0 +1 @@
    +../../Task/Input-loop/Nom
    \ No newline at end of file
    diff --git a/Lang/Nom/Odd-word-problem b/Lang/Nom/Odd-word-problem
    new file mode 120000
    index 0000000000..43979a4bb7
    --- /dev/null
    +++ b/Lang/Nom/Odd-word-problem
    @@ -0,0 +1 @@
    +../../Task/Odd-word-problem/Nom
    \ No newline at end of file
    diff --git a/Lang/Nom/Reverse-a-string b/Lang/Nom/Reverse-a-string
    new file mode 120000
    index 0000000000..38692d6625
    --- /dev/null
    +++ b/Lang/Nom/Reverse-a-string
    @@ -0,0 +1 @@
    +../../Task/Reverse-a-string/Nom
    \ No newline at end of file
    diff --git a/Lang/Nu/00-LANG.txt b/Lang/Nu/00-LANG.txt
    index d173c3d735..4a1eea655e 100644
    --- a/Lang/Nu/00-LANG.txt
    +++ b/Lang/Nu/00-LANG.txt
    @@ -1,3 +1,5 @@
    -{{stub}}{{language|Nu}}
    +{{stub}}
    +{{language|Nu|site=https://www.nushell.sh|tags=nu}}
    +{{Language programming paradigm|Functional}}
     
     Nu is the programming language used by Nushell.
    \ No newline at end of file
    diff --git a/Lang/Nu/Associative-array-Merging b/Lang/Nu/Associative-array-Merging
    new file mode 120000
    index 0000000000..7f423eb251
    --- /dev/null
    +++ b/Lang/Nu/Associative-array-Merging
    @@ -0,0 +1 @@
    +../../Task/Associative-array-Merging/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Averages-Arithmetic-mean b/Lang/Nu/Averages-Arithmetic-mean
    new file mode 120000
    index 0000000000..21a1e77aec
    --- /dev/null
    +++ b/Lang/Nu/Averages-Arithmetic-mean
    @@ -0,0 +1 @@
    +../../Task/Averages-Arithmetic-mean/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Averages-Median b/Lang/Nu/Averages-Median
    new file mode 120000
    index 0000000000..8b1a3ddc2c
    --- /dev/null
    +++ b/Lang/Nu/Averages-Median
    @@ -0,0 +1 @@
    +../../Task/Averages-Median/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Averages-Mode b/Lang/Nu/Averages-Mode
    new file mode 120000
    index 0000000000..bb3150600b
    --- /dev/null
    +++ b/Lang/Nu/Averages-Mode
    @@ -0,0 +1 @@
    +../../Task/Averages-Mode/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Averages-Pythagorean-means b/Lang/Nu/Averages-Pythagorean-means
    new file mode 120000
    index 0000000000..02b10a7b5e
    --- /dev/null
    +++ b/Lang/Nu/Averages-Pythagorean-means
    @@ -0,0 +1 @@
    +../../Task/Averages-Pythagorean-means/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Averages-Root-mean-square b/Lang/Nu/Averages-Root-mean-square
    new file mode 120000
    index 0000000000..ed92d8f206
    --- /dev/null
    +++ b/Lang/Nu/Averages-Root-mean-square
    @@ -0,0 +1 @@
    +../../Task/Averages-Root-mean-square/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Base64-decode-data b/Lang/Nu/Base64-decode-data
    new file mode 120000
    index 0000000000..3620ff6de5
    --- /dev/null
    +++ b/Lang/Nu/Base64-decode-data
    @@ -0,0 +1 @@
    +../../Task/Base64-decode-data/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Binary-digits b/Lang/Nu/Binary-digits
    new file mode 120000
    index 0000000000..cbbd7fb698
    --- /dev/null
    +++ b/Lang/Nu/Binary-digits
    @@ -0,0 +1 @@
    +../../Task/Binary-digits/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/CSV-data-manipulation b/Lang/Nu/CSV-data-manipulation
    new file mode 120000
    index 0000000000..212f9d037c
    --- /dev/null
    +++ b/Lang/Nu/CSV-data-manipulation
    @@ -0,0 +1 @@
    +../../Task/CSV-data-manipulation/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Calculating-the-value-of-e b/Lang/Nu/Calculating-the-value-of-e
    new file mode 120000
    index 0000000000..60dd80e1f7
    --- /dev/null
    +++ b/Lang/Nu/Calculating-the-value-of-e
    @@ -0,0 +1 @@
    +../../Task/Calculating-the-value-of-e/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Check-input-device-is-a-terminal b/Lang/Nu/Check-input-device-is-a-terminal
    new file mode 120000
    index 0000000000..2c12886796
    --- /dev/null
    +++ b/Lang/Nu/Check-input-device-is-a-terminal
    @@ -0,0 +1 @@
    +../../Task/Check-input-device-is-a-terminal/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Check-output-device-is-a-terminal b/Lang/Nu/Check-output-device-is-a-terminal
    new file mode 120000
    index 0000000000..8ac81dc9fd
    --- /dev/null
    +++ b/Lang/Nu/Check-output-device-is-a-terminal
    @@ -0,0 +1 @@
    +../../Task/Check-output-device-is-a-terminal/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Check-that-file-exists b/Lang/Nu/Check-that-file-exists
    new file mode 120000
    index 0000000000..aa750c153c
    --- /dev/null
    +++ b/Lang/Nu/Check-that-file-exists
    @@ -0,0 +1 @@
    +../../Task/Check-that-file-exists/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Comma-quibbling b/Lang/Nu/Comma-quibbling
    new file mode 120000
    index 0000000000..6196295075
    --- /dev/null
    +++ b/Lang/Nu/Comma-quibbling
    @@ -0,0 +1 @@
    +../../Task/Comma-quibbling/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Count-in-octal b/Lang/Nu/Count-in-octal
    new file mode 120000
    index 0000000000..b2bc3a9f84
    --- /dev/null
    +++ b/Lang/Nu/Count-in-octal
    @@ -0,0 +1 @@
    +../../Task/Count-in-octal/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Count-occurrences-of-a-substring b/Lang/Nu/Count-occurrences-of-a-substring
    new file mode 120000
    index 0000000000..1a4f958e67
    --- /dev/null
    +++ b/Lang/Nu/Count-occurrences-of-a-substring
    @@ -0,0 +1 @@
    +../../Task/Count-occurrences-of-a-substring/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Date-format b/Lang/Nu/Date-format
    new file mode 120000
    index 0000000000..b99fcd9487
    --- /dev/null
    +++ b/Lang/Nu/Date-format
    @@ -0,0 +1 @@
    +../../Task/Date-format/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Day-of-the-week b/Lang/Nu/Day-of-the-week
    new file mode 120000
    index 0000000000..628ae77cde
    --- /dev/null
    +++ b/Lang/Nu/Day-of-the-week
    @@ -0,0 +1 @@
    +../../Task/Day-of-the-week/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Department-numbers b/Lang/Nu/Department-numbers
    new file mode 120000
    index 0000000000..bb0cfc31a5
    --- /dev/null
    +++ b/Lang/Nu/Department-numbers
    @@ -0,0 +1 @@
    +../../Task/Department-numbers/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Determine-if-a-string-has-all-the-same-characters b/Lang/Nu/Determine-if-a-string-has-all-the-same-characters
    new file mode 120000
    index 0000000000..1b0a4160eb
    --- /dev/null
    +++ b/Lang/Nu/Determine-if-a-string-has-all-the-same-characters
    @@ -0,0 +1 @@
    +../../Task/Determine-if-a-string-has-all-the-same-characters/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Dot-product b/Lang/Nu/Dot-product
    new file mode 120000
    index 0000000000..98aeabb740
    --- /dev/null
    +++ b/Lang/Nu/Dot-product
    @@ -0,0 +1 @@
    +../../Task/Dot-product/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Entropy b/Lang/Nu/Entropy
    new file mode 120000
    index 0000000000..5bed68a8b8
    --- /dev/null
    +++ b/Lang/Nu/Entropy
    @@ -0,0 +1 @@
    +../../Task/Entropy/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Even-or-odd b/Lang/Nu/Even-or-odd
    new file mode 120000
    index 0000000000..7bc71663d2
    --- /dev/null
    +++ b/Lang/Nu/Even-or-odd
    @@ -0,0 +1 @@
    +../../Task/Even-or-odd/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Factors-of-an-integer b/Lang/Nu/Factors-of-an-integer
    new file mode 120000
    index 0000000000..5aa37c904e
    --- /dev/null
    +++ b/Lang/Nu/Factors-of-an-integer
    @@ -0,0 +1 @@
    +../../Task/Factors-of-an-integer/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Fibonacci-sequence b/Lang/Nu/Fibonacci-sequence
    new file mode 120000
    index 0000000000..c835014e2a
    --- /dev/null
    +++ b/Lang/Nu/Fibonacci-sequence
    @@ -0,0 +1 @@
    +../../Task/Fibonacci-sequence/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/File-extension-is-in-extensions-list b/Lang/Nu/File-extension-is-in-extensions-list
    new file mode 120000
    index 0000000000..ee608b6863
    --- /dev/null
    +++ b/Lang/Nu/File-extension-is-in-extensions-list
    @@ -0,0 +1 @@
    +../../Task/File-extension-is-in-extensions-list/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/File-size b/Lang/Nu/File-size
    new file mode 120000
    index 0000000000..14db7aa8d0
    --- /dev/null
    +++ b/Lang/Nu/File-size
    @@ -0,0 +1 @@
    +../../Task/File-size/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/File-size-distribution b/Lang/Nu/File-size-distribution
    new file mode 120000
    index 0000000000..2ee98ba338
    --- /dev/null
    +++ b/Lang/Nu/File-size-distribution
    @@ -0,0 +1 @@
    +../../Task/File-size-distribution/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Find-limit-of-recursion b/Lang/Nu/Find-limit-of-recursion
    new file mode 120000
    index 0000000000..c6b78c9274
    --- /dev/null
    +++ b/Lang/Nu/Find-limit-of-recursion
    @@ -0,0 +1 @@
    +../../Task/Find-limit-of-recursion/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Find-the-last-Sunday-of-each-month b/Lang/Nu/Find-the-last-Sunday-of-each-month
    new file mode 120000
    index 0000000000..7d0aedf546
    --- /dev/null
    +++ b/Lang/Nu/Find-the-last-Sunday-of-each-month
    @@ -0,0 +1 @@
    +../../Task/Find-the-last-Sunday-of-each-month/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Generate-lower-case-ASCII-alphabet b/Lang/Nu/Generate-lower-case-ASCII-alphabet
    new file mode 120000
    index 0000000000..2680ace5a7
    --- /dev/null
    +++ b/Lang/Nu/Generate-lower-case-ASCII-alphabet
    @@ -0,0 +1 @@
    +../../Task/Generate-lower-case-ASCII-alphabet/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Greatest-common-divisor b/Lang/Nu/Greatest-common-divisor
    new file mode 120000
    index 0000000000..d844f147ad
    --- /dev/null
    +++ b/Lang/Nu/Greatest-common-divisor
    @@ -0,0 +1 @@
    +../../Task/Greatest-common-divisor/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Greatest-element-of-a-list b/Lang/Nu/Greatest-element-of-a-list
    new file mode 120000
    index 0000000000..3b8838db94
    --- /dev/null
    +++ b/Lang/Nu/Greatest-element-of-a-list
    @@ -0,0 +1 @@
    +../../Task/Greatest-element-of-a-list/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Harshad-or-Niven-series b/Lang/Nu/Harshad-or-Niven-series
    new file mode 120000
    index 0000000000..87dd3a6ea5
    --- /dev/null
    +++ b/Lang/Nu/Harshad-or-Niven-series
    @@ -0,0 +1 @@
    +../../Task/Harshad-or-Niven-series/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Hello-world-Newline-omission b/Lang/Nu/Hello-world-Newline-omission
    new file mode 120000
    index 0000000000..f00be9e5a7
    --- /dev/null
    +++ b/Lang/Nu/Hello-world-Newline-omission
    @@ -0,0 +1 @@
    +../../Task/Hello-world-Newline-omission/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Hex-words b/Lang/Nu/Hex-words
    new file mode 120000
    index 0000000000..14f92faeab
    --- /dev/null
    +++ b/Lang/Nu/Hex-words
    @@ -0,0 +1 @@
    +../../Task/Hex-words/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/I-before-E-except-after-C b/Lang/Nu/I-before-E-except-after-C
    new file mode 120000
    index 0000000000..3f6ace8c86
    --- /dev/null
    +++ b/Lang/Nu/I-before-E-except-after-C
    @@ -0,0 +1 @@
    +../../Task/I-before-E-except-after-C/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Identity-matrix b/Lang/Nu/Identity-matrix
    new file mode 120000
    index 0000000000..31adec2ac4
    --- /dev/null
    +++ b/Lang/Nu/Identity-matrix
    @@ -0,0 +1 @@
    +../../Task/Identity-matrix/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Integer-sequence b/Lang/Nu/Integer-sequence
    new file mode 120000
    index 0000000000..32270a6fb8
    --- /dev/null
    +++ b/Lang/Nu/Integer-sequence
    @@ -0,0 +1 @@
    +../../Task/Integer-sequence/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Jewels-and-stones b/Lang/Nu/Jewels-and-stones
    new file mode 120000
    index 0000000000..31ec593a67
    --- /dev/null
    +++ b/Lang/Nu/Jewels-and-stones
    @@ -0,0 +1 @@
    +../../Task/Jewels-and-stones/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Last-Friday-of-each-month b/Lang/Nu/Last-Friday-of-each-month
    new file mode 120000
    index 0000000000..6075ef1dcc
    --- /dev/null
    +++ b/Lang/Nu/Last-Friday-of-each-month
    @@ -0,0 +1 @@
    +../../Task/Last-Friday-of-each-month/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Letter-frequency b/Lang/Nu/Letter-frequency
    new file mode 120000
    index 0000000000..0b7cf31f44
    --- /dev/null
    +++ b/Lang/Nu/Letter-frequency
    @@ -0,0 +1 @@
    +../../Task/Letter-frequency/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Levenshtein-distance b/Lang/Nu/Levenshtein-distance
    new file mode 120000
    index 0000000000..f8c80b6b68
    --- /dev/null
    +++ b/Lang/Nu/Levenshtein-distance
    @@ -0,0 +1 @@
    +../../Task/Levenshtein-distance/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/MD5 b/Lang/Nu/MD5
    new file mode 120000
    index 0000000000..feac42125d
    --- /dev/null
    +++ b/Lang/Nu/MD5
    @@ -0,0 +1 @@
    +../../Task/MD5/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Matrix-transposition b/Lang/Nu/Matrix-transposition
    new file mode 120000
    index 0000000000..adc758bbe0
    --- /dev/null
    +++ b/Lang/Nu/Matrix-transposition
    @@ -0,0 +1 @@
    +../../Task/Matrix-transposition/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Multiplication-tables b/Lang/Nu/Multiplication-tables
    new file mode 120000
    index 0000000000..ac72d93e8f
    --- /dev/null
    +++ b/Lang/Nu/Multiplication-tables
    @@ -0,0 +1 @@
    +../../Task/Multiplication-tables/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Non-decimal-radices-Convert b/Lang/Nu/Non-decimal-radices-Convert
    new file mode 120000
    index 0000000000..1dbd245069
    --- /dev/null
    +++ b/Lang/Nu/Non-decimal-radices-Convert
    @@ -0,0 +1 @@
    +../../Task/Non-decimal-radices-Convert/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Null-object b/Lang/Nu/Null-object
    new file mode 120000
    index 0000000000..74589e5538
    --- /dev/null
    +++ b/Lang/Nu/Null-object
    @@ -0,0 +1 @@
    +../../Task/Null-object/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Order-two-numerical-lists b/Lang/Nu/Order-two-numerical-lists
    new file mode 120000
    index 0000000000..a09725d44a
    --- /dev/null
    +++ b/Lang/Nu/Order-two-numerical-lists
    @@ -0,0 +1 @@
    +../../Task/Order-two-numerical-lists/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Ordered-words b/Lang/Nu/Ordered-words
    new file mode 120000
    index 0000000000..fb4962c2af
    --- /dev/null
    +++ b/Lang/Nu/Ordered-words
    @@ -0,0 +1 @@
    +../../Task/Ordered-words/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Phrase-reversals b/Lang/Nu/Phrase-reversals
    new file mode 120000
    index 0000000000..df54742816
    --- /dev/null
    +++ b/Lang/Nu/Phrase-reversals
    @@ -0,0 +1 @@
    +../../Task/Phrase-reversals/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Pick-random-element b/Lang/Nu/Pick-random-element
    new file mode 120000
    index 0000000000..184348b826
    --- /dev/null
    +++ b/Lang/Nu/Pick-random-element
    @@ -0,0 +1 @@
    +../../Task/Pick-random-element/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Random-numbers b/Lang/Nu/Random-numbers
    new file mode 120000
    index 0000000000..ba277327c8
    --- /dev/null
    +++ b/Lang/Nu/Random-numbers
    @@ -0,0 +1 @@
    +../../Task/Random-numbers/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Remove-duplicate-elements b/Lang/Nu/Remove-duplicate-elements
    new file mode 120000
    index 0000000000..d498c34eae
    --- /dev/null
    +++ b/Lang/Nu/Remove-duplicate-elements
    @@ -0,0 +1 @@
    +../../Task/Remove-duplicate-elements/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Repeat-a-string b/Lang/Nu/Repeat-a-string
    new file mode 120000
    index 0000000000..962454e331
    --- /dev/null
    +++ b/Lang/Nu/Repeat-a-string
    @@ -0,0 +1 @@
    +../../Task/Repeat-a-string/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Reverse-a-string b/Lang/Nu/Reverse-a-string
    new file mode 120000
    index 0000000000..34f43d53f3
    --- /dev/null
    +++ b/Lang/Nu/Reverse-a-string
    @@ -0,0 +1 @@
    +../../Task/Reverse-a-string/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Rot-13 b/Lang/Nu/Rot-13
    new file mode 120000
    index 0000000000..d2902fe7ad
    --- /dev/null
    +++ b/Lang/Nu/Rot-13
    @@ -0,0 +1 @@
    +../../Task/Rot-13/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/SHA-256 b/Lang/Nu/SHA-256
    new file mode 120000
    index 0000000000..b58398940b
    --- /dev/null
    +++ b/Lang/Nu/SHA-256
    @@ -0,0 +1 @@
    +../../Task/SHA-256/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Show-the-epoch b/Lang/Nu/Show-the-epoch
    new file mode 120000
    index 0000000000..9547f199df
    --- /dev/null
    +++ b/Lang/Nu/Show-the-epoch
    @@ -0,0 +1 @@
    +../../Task/Show-the-epoch/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Sort-a-list-of-object-identifiers b/Lang/Nu/Sort-a-list-of-object-identifiers
    new file mode 120000
    index 0000000000..9efe53a3b5
    --- /dev/null
    +++ b/Lang/Nu/Sort-a-list-of-object-identifiers
    @@ -0,0 +1 @@
    +../../Task/Sort-a-list-of-object-identifiers/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Sort-an-integer-array b/Lang/Nu/Sort-an-integer-array
    new file mode 120000
    index 0000000000..cff6ab8400
    --- /dev/null
    +++ b/Lang/Nu/Sort-an-integer-array
    @@ -0,0 +1 @@
    +../../Task/Sort-an-integer-array/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Split-a-character-string-based-on-change-of-character b/Lang/Nu/Split-a-character-string-based-on-change-of-character
    new file mode 120000
    index 0000000000..c6103b5715
    --- /dev/null
    +++ b/Lang/Nu/Split-a-character-string-based-on-change-of-character
    @@ -0,0 +1 @@
    +../../Task/Split-a-character-string-based-on-change-of-character/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Nu/Strip-whitespace-from-a-string-Top-and-tail
    new file mode 120000
    index 0000000000..c8922d283e
    --- /dev/null
    +++ b/Lang/Nu/Strip-whitespace-from-a-string-Top-and-tail
    @@ -0,0 +1 @@
    +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Substring-Top-and-tail b/Lang/Nu/Substring-Top-and-tail
    new file mode 120000
    index 0000000000..8e1ec9809c
    --- /dev/null
    +++ b/Lang/Nu/Substring-Top-and-tail
    @@ -0,0 +1 @@
    +../../Task/Substring-Top-and-tail/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Sum-and-product-of-an-array b/Lang/Nu/Sum-and-product-of-an-array
    new file mode 120000
    index 0000000000..c3f15d2743
    --- /dev/null
    +++ b/Lang/Nu/Sum-and-product-of-an-array
    @@ -0,0 +1 @@
    +../../Task/Sum-and-product-of-an-array/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Sum-digits-of-an-integer b/Lang/Nu/Sum-digits-of-an-integer
    new file mode 120000
    index 0000000000..41b99ca024
    --- /dev/null
    +++ b/Lang/Nu/Sum-digits-of-an-integer
    @@ -0,0 +1 @@
    +../../Task/Sum-digits-of-an-integer/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Sum-of-a-series b/Lang/Nu/Sum-of-a-series
    new file mode 120000
    index 0000000000..8172f12fc3
    --- /dev/null
    +++ b/Lang/Nu/Sum-of-a-series
    @@ -0,0 +1 @@
    +../../Task/Sum-of-a-series/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Sum-of-squares b/Lang/Nu/Sum-of-squares
    new file mode 120000
    index 0000000000..d7b0eacde8
    --- /dev/null
    +++ b/Lang/Nu/Sum-of-squares
    @@ -0,0 +1 @@
    +../../Task/Sum-of-squares/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Terminal-control-Clear-the-screen b/Lang/Nu/Terminal-control-Clear-the-screen
    new file mode 120000
    index 0000000000..929018a6f7
    --- /dev/null
    +++ b/Lang/Nu/Terminal-control-Clear-the-screen
    @@ -0,0 +1 @@
    +../../Task/Terminal-control-Clear-the-screen/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Terminal-control-Dimensions b/Lang/Nu/Terminal-control-Dimensions
    new file mode 120000
    index 0000000000..6f437c04e4
    --- /dev/null
    +++ b/Lang/Nu/Terminal-control-Dimensions
    @@ -0,0 +1 @@
    +../../Task/Terminal-control-Dimensions/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Terminal-control-Display-an-extended-character b/Lang/Nu/Terminal-control-Display-an-extended-character
    new file mode 120000
    index 0000000000..e54390beea
    --- /dev/null
    +++ b/Lang/Nu/Terminal-control-Display-an-extended-character
    @@ -0,0 +1 @@
    +../../Task/Terminal-control-Display-an-extended-character/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Terminal-control-Hiding-the-cursor b/Lang/Nu/Terminal-control-Hiding-the-cursor
    new file mode 120000
    index 0000000000..e19aad16bb
    --- /dev/null
    +++ b/Lang/Nu/Terminal-control-Hiding-the-cursor
    @@ -0,0 +1 @@
    +../../Task/Terminal-control-Hiding-the-cursor/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Terminal-control-Inverse-video b/Lang/Nu/Terminal-control-Inverse-video
    new file mode 120000
    index 0000000000..dbb97c54ab
    --- /dev/null
    +++ b/Lang/Nu/Terminal-control-Inverse-video
    @@ -0,0 +1 @@
    +../../Task/Terminal-control-Inverse-video/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Terminal-control-Ringing-the-terminal-bell b/Lang/Nu/Terminal-control-Ringing-the-terminal-bell
    new file mode 120000
    index 0000000000..f67008c1f1
    --- /dev/null
    +++ b/Lang/Nu/Terminal-control-Ringing-the-terminal-bell
    @@ -0,0 +1 @@
    +../../Task/Terminal-control-Ringing-the-terminal-bell/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Time-a-function b/Lang/Nu/Time-a-function
    new file mode 120000
    index 0000000000..d32498490a
    --- /dev/null
    +++ b/Lang/Nu/Time-a-function
    @@ -0,0 +1 @@
    +../../Task/Time-a-function/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Tokenize-a-string b/Lang/Nu/Tokenize-a-string
    new file mode 120000
    index 0000000000..e254094f94
    --- /dev/null
    +++ b/Lang/Nu/Tokenize-a-string
    @@ -0,0 +1 @@
    +../../Task/Tokenize-a-string/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Word-frequency b/Lang/Nu/Word-frequency
    new file mode 120000
    index 0000000000..b6ff2592c2
    --- /dev/null
    +++ b/Lang/Nu/Word-frequency
    @@ -0,0 +1 @@
    +../../Task/Word-frequency/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Y-combinator b/Lang/Nu/Y-combinator
    new file mode 120000
    index 0000000000..77e8ec4916
    --- /dev/null
    +++ b/Lang/Nu/Y-combinator
    @@ -0,0 +1 @@
    +../../Task/Y-combinator/Nu
    \ No newline at end of file
    diff --git a/Lang/Nu/Zero-to-the-zero-power b/Lang/Nu/Zero-to-the-zero-power
    new file mode 120000
    index 0000000000..950e81f484
    --- /dev/null
    +++ b/Lang/Nu/Zero-to-the-zero-power
    @@ -0,0 +1 @@
    +../../Task/Zero-to-the-zero-power/Nu
    \ No newline at end of file
    diff --git a/Lang/OCaml/Anti-primes b/Lang/OCaml/Anti-primes
    new file mode 120000
    index 0000000000..5c78fd8505
    --- /dev/null
    +++ b/Lang/OCaml/Anti-primes
    @@ -0,0 +1 @@
    +../../Task/Anti-primes/OCaml
    \ No newline at end of file
    diff --git a/Lang/OCaml/Attractive-numbers b/Lang/OCaml/Attractive-numbers
    new file mode 120000
    index 0000000000..7813955dbc
    --- /dev/null
    +++ b/Lang/OCaml/Attractive-numbers
    @@ -0,0 +1 @@
    +../../Task/Attractive-numbers/OCaml
    \ No newline at end of file
    diff --git a/Lang/OCaml/Cuban-primes b/Lang/OCaml/Cuban-primes
    new file mode 120000
    index 0000000000..d69918cc8d
    --- /dev/null
    +++ b/Lang/OCaml/Cuban-primes
    @@ -0,0 +1 @@
    +../../Task/Cuban-primes/OCaml
    \ No newline at end of file
    diff --git a/Lang/OCaml/Harmonic-series b/Lang/OCaml/Harmonic-series
    new file mode 120000
    index 0000000000..7ea0abbec3
    --- /dev/null
    +++ b/Lang/OCaml/Harmonic-series
    @@ -0,0 +1 @@
    +../../Task/Harmonic-series/OCaml
    \ No newline at end of file
    diff --git a/Lang/OCaml/Kosaraju b/Lang/OCaml/Kosaraju
    new file mode 120000
    index 0000000000..7243692ec3
    --- /dev/null
    +++ b/Lang/OCaml/Kosaraju
    @@ -0,0 +1 @@
    +../../Task/Kosaraju/OCaml
    \ No newline at end of file
    diff --git a/Lang/OCaml/Parse-an-IP-Address b/Lang/OCaml/Parse-an-IP-Address
    new file mode 120000
    index 0000000000..f01fc56f01
    --- /dev/null
    +++ b/Lang/OCaml/Parse-an-IP-Address
    @@ -0,0 +1 @@
    +../../Task/Parse-an-IP-Address/OCaml
    \ No newline at end of file
    diff --git a/Lang/OCaml/Pseudo-random-numbers-Xorshift-star b/Lang/OCaml/Pseudo-random-numbers-Xorshift-star
    new file mode 120000
    index 0000000000..3fd6f20cda
    --- /dev/null
    +++ b/Lang/OCaml/Pseudo-random-numbers-Xorshift-star
    @@ -0,0 +1 @@
    +../../Task/Pseudo-random-numbers-Xorshift-star/OCaml
    \ No newline at end of file
    diff --git a/Lang/OCaml/Quaternion-type b/Lang/OCaml/Quaternion-type
    deleted file mode 120000
    index cc65de3875..0000000000
    --- a/Lang/OCaml/Quaternion-type
    +++ /dev/null
    @@ -1 +0,0 @@
    -../../Task/Quaternion-type/OCaml
    \ No newline at end of file
    diff --git a/Lang/OCaml/Sorting-algorithms-Sleep-sort b/Lang/OCaml/Sorting-algorithms-Sleep-sort
    new file mode 120000
    index 0000000000..1cc75210f7
    --- /dev/null
    +++ b/Lang/OCaml/Sorting-algorithms-Sleep-sort
    @@ -0,0 +1 @@
    +../../Task/Sorting-algorithms-Sleep-sort/OCaml
    \ No newline at end of file
    diff --git a/Lang/OCaml/Strassens-algorithm b/Lang/OCaml/Strassens-algorithm
    new file mode 120000
    index 0000000000..f94e8ddb52
    --- /dev/null
    +++ b/Lang/OCaml/Strassens-algorithm
    @@ -0,0 +1 @@
    +../../Task/Strassens-algorithm/OCaml
    \ No newline at end of file
    diff --git a/Lang/OOC/00-LANG.txt b/Lang/OOC/00-LANG.txt
    index 6ab39964dc..65c190709f 100644
    --- a/Lang/OOC/00-LANG.txt
    +++ b/Lang/OOC/00-LANG.txt
    @@ -1,2 +1,2 @@
     {{stub}}{{language
    -|site=http://ooc-lang.org}}
    \ No newline at end of file
    +|site=https://ooc-lang.github.io/}}
    \ No newline at end of file
    diff --git a/Lang/OPL/00-LANG.txt b/Lang/OPL/00-LANG.txt
    index 8357c2d27a..5d7f1fba8f 100644
    --- a/Lang/OPL/00-LANG.txt
    +++ b/Lang/OPL/00-LANG.txt
    @@ -1,3 +1,11 @@
     {{stub}}
     {{language
    -|site=http://opl-dev.sourceforge.net/}}
    \ No newline at end of file
    +|site=http://opl-dev.sourceforge.net/}}
    +
    +'''OPL (Open Programming Language'''; formerly '''Organiser Programming Language)''' is a high-level programming language designed primarily for use on mobile devices, particularly those running the Psion Series 3 and Series 5 operating systems. Developed in the early 1990s, '''OPL''' was created to provide a simple yet powerful environment for application development on handheld devices, allowing users to create software that could leverage the unique features of these portable platforms.
    +
    +OPL is known for its ease of use, making it accessible to both novice and experienced programmers. The language features a syntax that is similar to [[BASIC]], which helps in rapid application development. It supports structured programming concepts, including variables, control structures, and functions, enabling developers to write clear and maintainable code.
    +
    +One of the key strengths of OPL is its ability to interact seamlessly with the underlying operating system, allowing developers to access device-specific features such as file management, user interface elements, and hardware capabilities. This makes OPL particularly suitable for creating productivity applications, games, and utilities tailored for mobile users.
    +
    +Despite its niche status, OPL has garnered a dedicated community of enthusiasts and developers who continue to explore its capabilities and create innovative applications. As mobile computing continues to evolve, OPL remains a notable example of early efforts to bring programming to handheld devices, showcasing the potential of portable technology in software development.
    \ No newline at end of file
    diff --git a/Lang/OPL/100-doors b/Lang/OPL/100-doors
    new file mode 120000
    index 0000000000..a3b7e045e6
    --- /dev/null
    +++ b/Lang/OPL/100-doors
    @@ -0,0 +1 @@
    +../../Task/100-doors/OPL
    \ No newline at end of file
    diff --git a/Lang/OPL/Arithmetic-Integer b/Lang/OPL/Arithmetic-Integer
    new file mode 120000
    index 0000000000..dfcb743d43
    --- /dev/null
    +++ b/Lang/OPL/Arithmetic-Integer
    @@ -0,0 +1 @@
    +../../Task/Arithmetic-Integer/OPL
    \ No newline at end of file
    diff --git a/Lang/OPL/Array-length b/Lang/OPL/Array-length
    new file mode 120000
    index 0000000000..691e5be366
    --- /dev/null
    +++ b/Lang/OPL/Array-length
    @@ -0,0 +1 @@
    +../../Task/Array-length/OPL
    \ No newline at end of file
    diff --git a/Lang/OPL/Arrays b/Lang/OPL/Arrays
    new file mode 120000
    index 0000000000..f57347887c
    --- /dev/null
    +++ b/Lang/OPL/Arrays
    @@ -0,0 +1 @@
    +../../Task/Arrays/OPL
    \ No newline at end of file
    diff --git a/Lang/OPL/Character-codes b/Lang/OPL/Character-codes
    new file mode 120000
    index 0000000000..2dac3156b8
    --- /dev/null
    +++ b/Lang/OPL/Character-codes
    @@ -0,0 +1 @@
    +../../Task/Character-codes/OPL
    \ No newline at end of file
    diff --git a/Lang/OPL/Comments b/Lang/OPL/Comments
    new file mode 120000
    index 0000000000..8aec78d8aa
    --- /dev/null
    +++ b/Lang/OPL/Comments
    @@ -0,0 +1 @@
    +../../Task/Comments/OPL
    \ No newline at end of file
    diff --git a/Lang/OPL/Compare-length-of-two-strings b/Lang/OPL/Compare-length-of-two-strings
    new file mode 120000
    index 0000000000..c36f1e31fc
    --- /dev/null
    +++ b/Lang/OPL/Compare-length-of-two-strings
    @@ -0,0 +1 @@
    +../../Task/Compare-length-of-two-strings/OPL
    \ No newline at end of file
    diff --git a/Lang/OPL/Copy-a-string b/Lang/OPL/Copy-a-string
    new file mode 120000
    index 0000000000..76609905e5
    --- /dev/null
    +++ b/Lang/OPL/Copy-a-string
    @@ -0,0 +1 @@
    +../../Task/Copy-a-string/OPL
    \ No newline at end of file
    diff --git a/Lang/OPL/Draw-a-clock b/Lang/OPL/Draw-a-clock
    new file mode 120000
    index 0000000000..438c8aadf3
    --- /dev/null
    +++ b/Lang/OPL/Draw-a-clock
    @@ -0,0 +1 @@
    +../../Task/Draw-a-clock/OPL
    \ No newline at end of file
    diff --git a/Lang/OPL/Draw-a-pixel b/Lang/OPL/Draw-a-pixel
    new file mode 120000
    index 0000000000..d5c6ecea21
    --- /dev/null
    +++ b/Lang/OPL/Draw-a-pixel
    @@ -0,0 +1 @@
    +../../Task/Draw-a-pixel/OPL
    \ No newline at end of file
    diff --git a/Lang/OPL/Empty-string b/Lang/OPL/Empty-string
    new file mode 120000
    index 0000000000..9f6569303b
    --- /dev/null
    +++ b/Lang/OPL/Empty-string
    @@ -0,0 +1 @@
    +../../Task/Empty-string/OPL
    \ No newline at end of file
    diff --git a/Lang/OPL/Factors-of-an-integer b/Lang/OPL/Factors-of-an-integer
    new file mode 120000
    index 0000000000..2dc5a0a29e
    --- /dev/null
    +++ b/Lang/OPL/Factors-of-an-integer
    @@ -0,0 +1 @@
    +../../Task/Factors-of-an-integer/OPL
    \ No newline at end of file
    diff --git a/Lang/OPL/Filter b/Lang/OPL/Filter
    new file mode 120000
    index 0000000000..89ea7a2c54
    --- /dev/null
    +++ b/Lang/OPL/Filter
    @@ -0,0 +1 @@
    +../../Task/Filter/OPL
    \ No newline at end of file
    diff --git a/Lang/OPL/Hello-world-Text b/Lang/OPL/Hello-world-Text
    new file mode 120000
    index 0000000000..a870057a16
    --- /dev/null
    +++ b/Lang/OPL/Hello-world-Text
    @@ -0,0 +1 @@
    +../../Task/Hello-world-Text/OPL
    \ No newline at end of file
    diff --git a/Lang/OPL/Program-termination b/Lang/OPL/Program-termination
    new file mode 120000
    index 0000000000..8287761646
    --- /dev/null
    +++ b/Lang/OPL/Program-termination
    @@ -0,0 +1 @@
    +../../Task/Program-termination/OPL
    \ No newline at end of file
    diff --git a/Lang/OPL/Reverse-a-string b/Lang/OPL/Reverse-a-string
    new file mode 120000
    index 0000000000..8dba18d4c9
    --- /dev/null
    +++ b/Lang/OPL/Reverse-a-string
    @@ -0,0 +1 @@
    +../../Task/Reverse-a-string/OPL
    \ No newline at end of file
    diff --git a/Lang/OPL/Show-ASCII-table b/Lang/OPL/Show-ASCII-table
    new file mode 120000
    index 0000000000..72f35c10c7
    --- /dev/null
    +++ b/Lang/OPL/Show-ASCII-table
    @@ -0,0 +1 @@
    +../../Task/Show-ASCII-table/OPL
    \ No newline at end of file
    diff --git a/Lang/OPL/String-length b/Lang/OPL/String-length
    new file mode 120000
    index 0000000000..ebd9f5ed88
    --- /dev/null
    +++ b/Lang/OPL/String-length
    @@ -0,0 +1 @@
    +../../Task/String-length/OPL
    \ No newline at end of file
    diff --git a/Lang/OPL/String-prepend b/Lang/OPL/String-prepend
    new file mode 120000
    index 0000000000..78cb69646e
    --- /dev/null
    +++ b/Lang/OPL/String-prepend
    @@ -0,0 +1 @@
    +../../Task/String-prepend/OPL
    \ No newline at end of file
    diff --git a/Lang/OPL/Substring b/Lang/OPL/Substring
    new file mode 120000
    index 0000000000..046b764f06
    --- /dev/null
    +++ b/Lang/OPL/Substring
    @@ -0,0 +1 @@
    +../../Task/Substring/OPL
    \ No newline at end of file
    diff --git a/Lang/OPL/User-input-Text b/Lang/OPL/User-input-Text
    new file mode 120000
    index 0000000000..ad39694040
    --- /dev/null
    +++ b/Lang/OPL/User-input-Text
    @@ -0,0 +1 @@
    +../../Task/User-input-Text/OPL
    \ No newline at end of file
    diff --git a/Lang/Oberon-07/00-LANG.txt b/Lang/Oberon-07/00-LANG.txt
    new file mode 100644
    index 0000000000..fecc62a2b8
    --- /dev/null
    +++ b/Lang/Oberon-07/00-LANG.txt
    @@ -0,0 +1,30 @@
    +{{stub}}
    +{{language|Oberon-07
    +|strength=strong
    +|safety=safe
    +|express=explicit
    +|compat=structural
    +|checking=static
    +|parampass=both
    +|gc=yes
    +}}
    +
    +'''Oberon-07''' is a revision of the Oberon language by Niklaus Wirth. Oberon-07 is based on Wirth's original Oberon language (not [[Oberon-2]]), Wirth lists the changes [https://people.inf.ethz.ch/wirth/Oberon/Oberon07.pdf here], which are largely aimed at  simplification - in [https://people.inf.ethz.ch/wirth/Oberon/Oberon07.Report.pdf his defining document], Wirth quotes Einstein: "Make it as simple as possible, but not simpler".

    + +Oberon-07 contains a WHILE loop that allows multiple conditions and statements - similar to the loop in [[wp:Guarded_Command_Language|Edsgar Dijkstra's Guarded Command Language]], though with different syntax and without non-determinism. See [[Loops/N_plus_one_half#Oberon-07]] for an example. +

    +In addition to the samples below, many of the [[Oberon-2]] samples should work with Oberon-07, particularly if the Oberon-07 compiler you are using allows LONGINT as a synonym for INTEGER (LONGINT, SHORTINT, LONGREAL and SHORTREAL were dropped from Oberon-07). + +==Tasks not implemented in Oberon-07== +[[Tasks not implemented in Oberon-07]] + +== Library modules used in Rosetta Code samples == +* [[:Category:Oberon-07-primes|Prime related]] +* [[:Category:Oberon-07-words|Word related]] + +== See also == +* [[Oberon-2]] +* [[Modula-2]] +* [[Modula-3]] +* [[Component Pascal]] +* [[Zonnon]] \ No newline at end of file diff --git a/Lang/Oberon-07/00-META.yaml b/Lang/Oberon-07/00-META.yaml new file mode 100644 index 0000000000..df5ec38ad0 --- /dev/null +++ b/Lang/Oberon-07/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Oberon-07 diff --git a/Lang/Oberon-07/Abundant-odd-numbers b/Lang/Oberon-07/Abundant-odd-numbers new file mode 120000 index 0000000000..93003f8da4 --- /dev/null +++ b/Lang/Oberon-07/Abundant-odd-numbers @@ -0,0 +1 @@ +../../Task/Abundant-odd-numbers/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Additive-primes b/Lang/Oberon-07/Additive-primes new file mode 120000 index 0000000000..29e374f522 --- /dev/null +++ b/Lang/Oberon-07/Additive-primes @@ -0,0 +1 @@ +../../Task/Additive-primes/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Almost-prime b/Lang/Oberon-07/Almost-prime new file mode 120000 index 0000000000..a487d08ae3 --- /dev/null +++ b/Lang/Oberon-07/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Arithmetic-derivative b/Lang/Oberon-07/Arithmetic-derivative new file mode 120000 index 0000000000..8a23f5aca7 --- /dev/null +++ b/Lang/Oberon-07/Arithmetic-derivative @@ -0,0 +1 @@ +../../Task/Arithmetic-derivative/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Arithmetic-numbers b/Lang/Oberon-07/Arithmetic-numbers new file mode 120000 index 0000000000..12d1ac60ce --- /dev/null +++ b/Lang/Oberon-07/Arithmetic-numbers @@ -0,0 +1 @@ +../../Task/Arithmetic-numbers/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Bell-numbers b/Lang/Oberon-07/Bell-numbers new file mode 120000 index 0000000000..e9a3518583 --- /dev/null +++ b/Lang/Oberon-07/Bell-numbers @@ -0,0 +1 @@ +../../Task/Bell-numbers/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Brilliant-numbers b/Lang/Oberon-07/Brilliant-numbers new file mode 120000 index 0000000000..9a2690e4fa --- /dev/null +++ b/Lang/Oberon-07/Brilliant-numbers @@ -0,0 +1 @@ +../../Task/Brilliant-numbers/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/CUSIP b/Lang/Oberon-07/CUSIP new file mode 120000 index 0000000000..fca08cc3e6 --- /dev/null +++ b/Lang/Oberon-07/CUSIP @@ -0,0 +1 @@ +../../Task/CUSIP/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Calculating-the-value-of-e b/Lang/Oberon-07/Calculating-the-value-of-e new file mode 120000 index 0000000000..3693146162 --- /dev/null +++ b/Lang/Oberon-07/Calculating-the-value-of-e @@ -0,0 +1 @@ +../../Task/Calculating-the-value-of-e/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Carmichael-3-strong-pseudoprimes b/Lang/Oberon-07/Carmichael-3-strong-pseudoprimes new file mode 120000 index 0000000000..1732f66395 --- /dev/null +++ b/Lang/Oberon-07/Carmichael-3-strong-pseudoprimes @@ -0,0 +1 @@ +../../Task/Carmichael-3-strong-pseudoprimes/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Catalan-numbers b/Lang/Oberon-07/Catalan-numbers new file mode 120000 index 0000000000..97d7a62fcd --- /dev/null +++ b/Lang/Oberon-07/Catalan-numbers @@ -0,0 +1 @@ +../../Task/Catalan-numbers/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Copy-stdin-to-stdout b/Lang/Oberon-07/Copy-stdin-to-stdout new file mode 120000 index 0000000000..15b9092fd0 --- /dev/null +++ b/Lang/Oberon-07/Copy-stdin-to-stdout @@ -0,0 +1 @@ +../../Task/Copy-stdin-to-stdout/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Count-in-factors b/Lang/Oberon-07/Count-in-factors new file mode 120000 index 0000000000..213e18b9fd --- /dev/null +++ b/Lang/Oberon-07/Count-in-factors @@ -0,0 +1 @@ +../../Task/Count-in-factors/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Cumulative-standard-deviation b/Lang/Oberon-07/Cumulative-standard-deviation new file mode 120000 index 0000000000..998c4d523e --- /dev/null +++ b/Lang/Oberon-07/Cumulative-standard-deviation @@ -0,0 +1 @@ +../../Task/Cumulative-standard-deviation/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Day-of-the-week b/Lang/Oberon-07/Day-of-the-week new file mode 120000 index 0000000000..f4a166cd18 --- /dev/null +++ b/Lang/Oberon-07/Day-of-the-week @@ -0,0 +1 @@ +../../Task/Day-of-the-week/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Department-numbers b/Lang/Oberon-07/Department-numbers new file mode 120000 index 0000000000..ee00d69bb6 --- /dev/null +++ b/Lang/Oberon-07/Department-numbers @@ -0,0 +1 @@ +../../Task/Department-numbers/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Determine-if-a-string-has-all-the-same-characters b/Lang/Oberon-07/Determine-if-a-string-has-all-the-same-characters new file mode 120000 index 0000000000..f2c11ea5d4 --- /dev/null +++ b/Lang/Oberon-07/Determine-if-a-string-has-all-the-same-characters @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-has-all-the-same-characters/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Dice-game-probabilities b/Lang/Oberon-07/Dice-game-probabilities new file mode 120000 index 0000000000..527f78ea60 --- /dev/null +++ b/Lang/Oberon-07/Dice-game-probabilities @@ -0,0 +1 @@ +../../Task/Dice-game-probabilities/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Empty-program b/Lang/Oberon-07/Empty-program new file mode 120000 index 0000000000..ba46e2aae6 --- /dev/null +++ b/Lang/Oberon-07/Empty-program @@ -0,0 +1 @@ +../../Task/Empty-program/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Equal-prime-and-composite-sums b/Lang/Oberon-07/Equal-prime-and-composite-sums new file mode 120000 index 0000000000..91c57a6baf --- /dev/null +++ b/Lang/Oberon-07/Equal-prime-and-composite-sums @@ -0,0 +1 @@ +../../Task/Equal-prime-and-composite-sums/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Ethiopian-multiplication b/Lang/Oberon-07/Ethiopian-multiplication new file mode 120000 index 0000000000..13a766a6c8 --- /dev/null +++ b/Lang/Oberon-07/Ethiopian-multiplication @@ -0,0 +1 @@ +../../Task/Ethiopian-multiplication/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Euclid-Mullin-sequence b/Lang/Oberon-07/Euclid-Mullin-sequence new file mode 120000 index 0000000000..81b23466eb --- /dev/null +++ b/Lang/Oberon-07/Euclid-Mullin-sequence @@ -0,0 +1 @@ +../../Task/Euclid-Mullin-sequence/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Factorial b/Lang/Oberon-07/Factorial new file mode 120000 index 0000000000..42b8c4919c --- /dev/null +++ b/Lang/Oberon-07/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Find-the-last-Sunday-of-each-month b/Lang/Oberon-07/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..1d918212c0 --- /dev/null +++ b/Lang/Oberon-07/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Giuga-numbers b/Lang/Oberon-07/Giuga-numbers new file mode 120000 index 0000000000..cce0bf5fc2 --- /dev/null +++ b/Lang/Oberon-07/Giuga-numbers @@ -0,0 +1 @@ +../../Task/Giuga-numbers/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Harmonic-series b/Lang/Oberon-07/Harmonic-series new file mode 120000 index 0000000000..8e08686cfc --- /dev/null +++ b/Lang/Oberon-07/Harmonic-series @@ -0,0 +1 @@ +../../Task/Harmonic-series/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Isqrt-integer-square-root-of-X b/Lang/Oberon-07/Isqrt-integer-square-root-of-X new file mode 120000 index 0000000000..a51f2f67a5 --- /dev/null +++ b/Lang/Oberon-07/Isqrt-integer-square-root-of-X @@ -0,0 +1 @@ +../../Task/Isqrt-integer-square-root-of-X/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Iterated-digits-squaring b/Lang/Oberon-07/Iterated-digits-squaring new file mode 120000 index 0000000000..7a2da6ed31 --- /dev/null +++ b/Lang/Oberon-07/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Jordan-P-lya-numbers b/Lang/Oberon-07/Jordan-P-lya-numbers new file mode 120000 index 0000000000..9a4df048e8 --- /dev/null +++ b/Lang/Oberon-07/Jordan-P-lya-numbers @@ -0,0 +1 @@ +../../Task/Jordan-P-lya-numbers/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Julia-set b/Lang/Oberon-07/Julia-set new file mode 120000 index 0000000000..e864d34442 --- /dev/null +++ b/Lang/Oberon-07/Julia-set @@ -0,0 +1 @@ +../../Task/Julia-set/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Knapsack-problem-Continuous b/Lang/Oberon-07/Knapsack-problem-Continuous new file mode 120000 index 0000000000..43a5919216 --- /dev/null +++ b/Lang/Oberon-07/Knapsack-problem-Continuous @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Continuous/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Last-Friday-of-each-month b/Lang/Oberon-07/Last-Friday-of-each-month new file mode 120000 index 0000000000..e8c07d9c19 --- /dev/null +++ b/Lang/Oberon-07/Last-Friday-of-each-month @@ -0,0 +1 @@ +../../Task/Last-Friday-of-each-month/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Leap-year b/Lang/Oberon-07/Leap-year new file mode 120000 index 0000000000..8797ca0922 --- /dev/null +++ b/Lang/Oberon-07/Leap-year @@ -0,0 +1 @@ +../../Task/Leap-year/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Legendre-prime-counting-function b/Lang/Oberon-07/Legendre-prime-counting-function new file mode 120000 index 0000000000..7d4d3489c5 --- /dev/null +++ b/Lang/Oberon-07/Legendre-prime-counting-function @@ -0,0 +1 @@ +../../Task/Legendre-prime-counting-function/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Long-year b/Lang/Oberon-07/Long-year new file mode 120000 index 0000000000..a0709fd34e --- /dev/null +++ b/Lang/Oberon-07/Long-year @@ -0,0 +1 @@ +../../Task/Long-year/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Loops-Break b/Lang/Oberon-07/Loops-Break new file mode 120000 index 0000000000..bcd210938e --- /dev/null +++ b/Lang/Oberon-07/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Loops-N-plus-one-half b/Lang/Oberon-07/Loops-N-plus-one-half new file mode 120000 index 0000000000..f9ed03d1cc --- /dev/null +++ b/Lang/Oberon-07/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Magic-8-ball b/Lang/Oberon-07/Magic-8-ball new file mode 120000 index 0000000000..060c6dd973 --- /dev/null +++ b/Lang/Oberon-07/Magic-8-ball @@ -0,0 +1 @@ +../../Task/Magic-8-ball/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/McNuggets-problem b/Lang/Oberon-07/McNuggets-problem new file mode 120000 index 0000000000..f69d28cb85 --- /dev/null +++ b/Lang/Oberon-07/McNuggets-problem @@ -0,0 +1 @@ +../../Task/McNuggets-problem/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Motzkin-numbers b/Lang/Oberon-07/Motzkin-numbers new file mode 120000 index 0000000000..b3b2948803 --- /dev/null +++ b/Lang/Oberon-07/Motzkin-numbers @@ -0,0 +1 @@ +../../Task/Motzkin-numbers/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Numbers-with-equal-rises-and-falls b/Lang/Oberon-07/Numbers-with-equal-rises-and-falls new file mode 120000 index 0000000000..5077c6cc5f --- /dev/null +++ b/Lang/Oberon-07/Numbers-with-equal-rises-and-falls @@ -0,0 +1 @@ +../../Task/Numbers-with-equal-rises-and-falls/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/One-dimensional-cellular-automata b/Lang/Oberon-07/One-dimensional-cellular-automata new file mode 120000 index 0000000000..95f88799f3 --- /dev/null +++ b/Lang/Oberon-07/One-dimensional-cellular-automata @@ -0,0 +1 @@ +../../Task/One-dimensional-cellular-automata/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Ordered-words b/Lang/Oberon-07/Ordered-words new file mode 120000 index 0000000000..6b04795e94 --- /dev/null +++ b/Lang/Oberon-07/Ordered-words @@ -0,0 +1 @@ +../../Task/Ordered-words/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Pell-numbers b/Lang/Oberon-07/Pell-numbers new file mode 120000 index 0000000000..7b4ee7e909 --- /dev/null +++ b/Lang/Oberon-07/Pell-numbers @@ -0,0 +1 @@ +../../Task/Pell-numbers/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Primality-by-trial-division b/Lang/Oberon-07/Primality-by-trial-division new file mode 120000 index 0000000000..bbe4339271 --- /dev/null +++ b/Lang/Oberon-07/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Rare-numbers b/Lang/Oberon-07/Rare-numbers new file mode 120000 index 0000000000..ee9d392e3c --- /dev/null +++ b/Lang/Oberon-07/Rare-numbers @@ -0,0 +1 @@ +../../Task/Rare-numbers/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Scope-modifiers b/Lang/Oberon-07/Scope-modifiers new file mode 120000 index 0000000000..5c7c859780 --- /dev/null +++ b/Lang/Oberon-07/Scope-modifiers @@ -0,0 +1 @@ +../../Task/Scope-modifiers/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Semiprime b/Lang/Oberon-07/Semiprime new file mode 120000 index 0000000000..46f4d8859c --- /dev/null +++ b/Lang/Oberon-07/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Sequence-of-non-squares b/Lang/Oberon-07/Sequence-of-non-squares new file mode 120000 index 0000000000..45e81c48c5 --- /dev/null +++ b/Lang/Oberon-07/Sequence-of-non-squares @@ -0,0 +1 @@ +../../Task/Sequence-of-non-squares/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Sequence-of-primorial-primes b/Lang/Oberon-07/Sequence-of-primorial-primes new file mode 120000 index 0000000000..7f1050cb25 --- /dev/null +++ b/Lang/Oberon-07/Sequence-of-primorial-primes @@ -0,0 +1 @@ +../../Task/Sequence-of-primorial-primes/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Shoelace-formula-for-polygonal-area b/Lang/Oberon-07/Shoelace-formula-for-polygonal-area new file mode 120000 index 0000000000..b71cae6abb --- /dev/null +++ b/Lang/Oberon-07/Shoelace-formula-for-polygonal-area @@ -0,0 +1 @@ +../../Task/Shoelace-formula-for-polygonal-area/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Sierpinski-triangle b/Lang/Oberon-07/Sierpinski-triangle new file mode 120000 index 0000000000..bdad2ec3ac --- /dev/null +++ b/Lang/Oberon-07/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Sleeping-Beauty-problem b/Lang/Oberon-07/Sleeping-Beauty-problem new file mode 120000 index 0000000000..94be576322 --- /dev/null +++ b/Lang/Oberon-07/Sleeping-Beauty-problem @@ -0,0 +1 @@ +../../Task/Sleeping-Beauty-problem/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Square-but-not-cube b/Lang/Oberon-07/Square-but-not-cube new file mode 120000 index 0000000000..917704f475 --- /dev/null +++ b/Lang/Oberon-07/Square-but-not-cube @@ -0,0 +1 @@ +../../Task/Square-but-not-cube/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Stack b/Lang/Oberon-07/Stack new file mode 120000 index 0000000000..abb833bb1a --- /dev/null +++ b/Lang/Oberon-07/Stack @@ -0,0 +1 @@ +../../Task/Stack/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Stirling-numbers-of-the-first-kind b/Lang/Oberon-07/Stirling-numbers-of-the-first-kind new file mode 120000 index 0000000000..fc333d5e86 --- /dev/null +++ b/Lang/Oberon-07/Stirling-numbers-of-the-first-kind @@ -0,0 +1 @@ +../../Task/Stirling-numbers-of-the-first-kind/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Tau-number b/Lang/Oberon-07/Tau-number new file mode 120000 index 0000000000..c494dc7ed9 --- /dev/null +++ b/Lang/Oberon-07/Tau-number @@ -0,0 +1 @@ +../../Task/Tau-number/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Thue-Morse b/Lang/Oberon-07/Thue-Morse new file mode 120000 index 0000000000..9ae7bad9e1 --- /dev/null +++ b/Lang/Oberon-07/Thue-Morse @@ -0,0 +1 @@ +../../Task/Thue-Morse/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Van-Eck-sequence b/Lang/Oberon-07/Van-Eck-sequence new file mode 120000 index 0000000000..1d825043d7 --- /dev/null +++ b/Lang/Oberon-07/Van-Eck-sequence @@ -0,0 +1 @@ +../../Task/Van-Eck-sequence/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Van-der-Corput-sequence b/Lang/Oberon-07/Van-der-Corput-sequence new file mode 120000 index 0000000000..9bcb9702bb --- /dev/null +++ b/Lang/Oberon-07/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Verhoeff-algorithm b/Lang/Oberon-07/Verhoeff-algorithm new file mode 120000 index 0000000000..5e73a5c36f --- /dev/null +++ b/Lang/Oberon-07/Verhoeff-algorithm @@ -0,0 +1 @@ +../../Task/Verhoeff-algorithm/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Yellowstone-sequence b/Lang/Oberon-07/Yellowstone-sequence new file mode 120000 index 0000000000..cf4e2d20b9 --- /dev/null +++ b/Lang/Oberon-07/Yellowstone-sequence @@ -0,0 +1 @@ +../../Task/Yellowstone-sequence/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon-07/Zeckendorf-number-representation b/Lang/Oberon-07/Zeckendorf-number-representation new file mode 120000 index 0000000000..3ada43b974 --- /dev/null +++ b/Lang/Oberon-07/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/Oberon-07 \ No newline at end of file diff --git a/Lang/Oberon/100-doors b/Lang/Oberon/100-doors deleted file mode 120000 index 9d190b3c16..0000000000 --- a/Lang/Oberon/100-doors +++ /dev/null @@ -1 +0,0 @@ -../../Task/100-doors/Oberon \ No newline at end of file diff --git a/Lang/Oberon/Abundant-deficient-and-perfect-number-classifications b/Lang/Oberon/Abundant-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..e8005ff3ac --- /dev/null +++ b/Lang/Oberon/Abundant-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant-deficient-and-perfect-number-classifications/Oberon \ No newline at end of file diff --git a/Lang/Oberon/Arithmetic-Integer b/Lang/Oberon/Arithmetic-Integer deleted file mode 120000 index e9f7a593d7..0000000000 --- a/Lang/Oberon/Arithmetic-Integer +++ /dev/null @@ -1 +0,0 @@ -../../Task/Arithmetic-Integer/Oberon \ No newline at end of file diff --git a/Lang/Oberon/Calkin-Wilf-sequence b/Lang/Oberon/Calkin-Wilf-sequence new file mode 120000 index 0000000000..15bedf6a9d --- /dev/null +++ b/Lang/Oberon/Calkin-Wilf-sequence @@ -0,0 +1 @@ +../../Task/Calkin-Wilf-sequence/Oberon \ No newline at end of file diff --git a/Lang/Oberon/Cumulative-standard-deviation b/Lang/Oberon/Cumulative-standard-deviation new file mode 120000 index 0000000000..efd10bee3a --- /dev/null +++ b/Lang/Oberon/Cumulative-standard-deviation @@ -0,0 +1 @@ +../../Task/Cumulative-standard-deviation/Oberon \ No newline at end of file diff --git a/Lang/Oberon/Euclid-Mullin-sequence b/Lang/Oberon/Euclid-Mullin-sequence new file mode 120000 index 0000000000..7808b89779 --- /dev/null +++ b/Lang/Oberon/Euclid-Mullin-sequence @@ -0,0 +1 @@ +../../Task/Euclid-Mullin-sequence/Oberon \ No newline at end of file diff --git a/Lang/Oberon/Even-or-odd b/Lang/Oberon/Even-or-odd deleted file mode 120000 index 02920c353c..0000000000 --- a/Lang/Oberon/Even-or-odd +++ /dev/null @@ -1 +0,0 @@ -../../Task/Even-or-odd/Oberon \ No newline at end of file diff --git a/Lang/Oberon/Golden-ratio-Convergence b/Lang/Oberon/Golden-ratio-Convergence new file mode 120000 index 0000000000..dd21277799 --- /dev/null +++ b/Lang/Oberon/Golden-ratio-Convergence @@ -0,0 +1 @@ +../../Task/Golden-ratio-Convergence/Oberon \ No newline at end of file diff --git a/Lang/Oberon/Greatest-common-divisor b/Lang/Oberon/Greatest-common-divisor deleted file mode 120000 index 23dd5fc156..0000000000 --- a/Lang/Oberon/Greatest-common-divisor +++ /dev/null @@ -1 +0,0 @@ -../../Task/Greatest-common-divisor/Oberon \ No newline at end of file diff --git a/Lang/Oberon/Loops-Continue b/Lang/Oberon/Loops-Continue new file mode 120000 index 0000000000..2ebf84aa8e --- /dev/null +++ b/Lang/Oberon/Loops-Continue @@ -0,0 +1 @@ +../../Task/Loops-Continue/Oberon \ No newline at end of file diff --git a/Lang/Oberon/Loops-For-with-a-specified-step b/Lang/Oberon/Loops-For-with-a-specified-step deleted file mode 120000 index e73c849d2b..0000000000 --- a/Lang/Oberon/Loops-For-with-a-specified-step +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-For-with-a-specified-step/Oberon \ No newline at end of file diff --git a/Lang/Oberon/Rare-numbers b/Lang/Oberon/Rare-numbers new file mode 120000 index 0000000000..9dc08ea100 --- /dev/null +++ b/Lang/Oberon/Rare-numbers @@ -0,0 +1 @@ +../../Task/Rare-numbers/Oberon \ No newline at end of file diff --git a/Lang/Objeck/Catalan-numbers-Pascals-triangle b/Lang/Objeck/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..bc3c684d61 --- /dev/null +++ b/Lang/Objeck/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Copy-stdin-to-stdout b/Lang/Objeck/Copy-stdin-to-stdout new file mode 120000 index 0000000000..b358bbac43 --- /dev/null +++ b/Lang/Objeck/Copy-stdin-to-stdout @@ -0,0 +1 @@ +../../Task/Copy-stdin-to-stdout/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Disarium-numbers b/Lang/Objeck/Disarium-numbers new file mode 120000 index 0000000000..bc58c40d5c --- /dev/null +++ b/Lang/Objeck/Disarium-numbers @@ -0,0 +1 @@ +../../Task/Disarium-numbers/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Distributed-programming b/Lang/Objeck/Distributed-programming new file mode 120000 index 0000000000..728f38ee28 --- /dev/null +++ b/Lang/Objeck/Distributed-programming @@ -0,0 +1 @@ +../../Task/Distributed-programming/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Floyds-triangle b/Lang/Objeck/Floyds-triangle new file mode 120000 index 0000000000..743553b677 --- /dev/null +++ b/Lang/Objeck/Floyds-triangle @@ -0,0 +1 @@ +../../Task/Floyds-triangle/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Generate-lower-case-ASCII-alphabet b/Lang/Objeck/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..92f0212a12 --- /dev/null +++ b/Lang/Objeck/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Objeck \ No newline at end of file diff --git a/Lang/Objeck/HTTPS-Client-authenticated b/Lang/Objeck/HTTPS-Client-authenticated new file mode 120000 index 0000000000..6f56878ef9 --- /dev/null +++ b/Lang/Objeck/HTTPS-Client-authenticated @@ -0,0 +1 @@ +../../Task/HTTPS-Client-authenticated/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Hello-world-Standard-error b/Lang/Objeck/Hello-world-Standard-error new file mode 120000 index 0000000000..49d3f16aa6 --- /dev/null +++ b/Lang/Objeck/Hello-world-Standard-error @@ -0,0 +1 @@ +../../Task/Hello-world-Standard-error/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Knuth-shuffle b/Lang/Objeck/Knuth-shuffle new file mode 120000 index 0000000000..a7bb43880d --- /dev/null +++ b/Lang/Objeck/Knuth-shuffle @@ -0,0 +1 @@ +../../Task/Knuth-shuffle/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Mad-Libs b/Lang/Objeck/Mad-Libs new file mode 120000 index 0000000000..39f19ea059 --- /dev/null +++ b/Lang/Objeck/Mad-Libs @@ -0,0 +1 @@ +../../Task/Mad-Libs/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Magic-squares-of-doubly-even-order b/Lang/Objeck/Magic-squares-of-doubly-even-order new file mode 120000 index 0000000000..526cd66745 --- /dev/null +++ b/Lang/Objeck/Magic-squares-of-doubly-even-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-doubly-even-order/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Matrix-multiplication b/Lang/Objeck/Matrix-multiplication new file mode 120000 index 0000000000..e2801343eb --- /dev/null +++ b/Lang/Objeck/Matrix-multiplication @@ -0,0 +1 @@ +../../Task/Matrix-multiplication/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Multiplication-tables b/Lang/Objeck/Multiplication-tables new file mode 120000 index 0000000000..3bad27bce2 --- /dev/null +++ b/Lang/Objeck/Multiplication-tables @@ -0,0 +1 @@ +../../Task/Multiplication-tables/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Queue-Definition b/Lang/Objeck/Queue-Definition new file mode 120000 index 0000000000..392e43e236 --- /dev/null +++ b/Lang/Objeck/Queue-Definition @@ -0,0 +1 @@ +../../Task/Queue-Definition/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Roman-numerals-Decode b/Lang/Objeck/Roman-numerals-Decode new file mode 120000 index 0000000000..bd8b56a721 --- /dev/null +++ b/Lang/Objeck/Roman-numerals-Decode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Decode/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Rosetta-Code-Find-unimplemented-tasks b/Lang/Objeck/Rosetta-Code-Find-unimplemented-tasks new file mode 120000 index 0000000000..7e77326aa1 --- /dev/null +++ b/Lang/Objeck/Rosetta-Code-Find-unimplemented-tasks @@ -0,0 +1 @@ +../../Task/Rosetta-Code-Find-unimplemented-tasks/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Sorting-Algorithms-Circle-Sort b/Lang/Objeck/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 4475fe5763..0000000000 --- a/Lang/Objeck/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Strip-a-set-of-characters-from-a-string b/Lang/Objeck/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..f651f9d55d --- /dev/null +++ b/Lang/Objeck/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Take-notes-on-the-command-line b/Lang/Objeck/Take-notes-on-the-command-line new file mode 120000 index 0000000000..5d55699b35 --- /dev/null +++ b/Lang/Objeck/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/Objeck \ No newline at end of file diff --git a/Lang/Object-Pascal-Implementations/00-LANG.txt b/Lang/Object-Pascal-Implementations/00-LANG.txt new file mode 100644 index 0000000000..74167ef7a7 --- /dev/null +++ b/Lang/Object-Pascal-Implementations/00-LANG.txt @@ -0,0 +1,3 @@ +{{language|Object Pascal}} +{{implementation cat|Object Pascal}} +{{implementation|Pascal}} \ No newline at end of file diff --git a/Lang/Object-Pascal-Implementations/00-META.yaml b/Lang/Object-Pascal-Implementations/00-META.yaml new file mode 100644 index 0000000000..34f0628a46 --- /dev/null +++ b/Lang/Object-Pascal-Implementations/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Object_Pascal_Implementations diff --git a/Lang/Object-Pascal/Sorting-algorithms-Shell-sort b/Lang/Object-Pascal/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..6ae9067d88 --- /dev/null +++ b/Lang/Object-Pascal/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/Object-Pascal \ No newline at end of file diff --git a/Lang/Octave/Peripheral-drift-illusion b/Lang/Octave/Peripheral-drift-illusion new file mode 120000 index 0000000000..9bda77fd28 --- /dev/null +++ b/Lang/Octave/Peripheral-drift-illusion @@ -0,0 +1 @@ +../../Task/Peripheral-drift-illusion/Octave \ No newline at end of file diff --git a/Lang/Octave/Quaternion-type b/Lang/Octave/Quaternion-type deleted file mode 120000 index 6dec972e26..0000000000 --- a/Lang/Octave/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Octave \ No newline at end of file diff --git a/Lang/Odin/00-LANG.txt b/Lang/Odin/00-LANG.txt index 2c96551228..1a08002d21 100644 --- a/Lang/Odin/00-LANG.txt +++ b/Lang/Odin/00-LANG.txt @@ -1 +1,24 @@ -{{stub}}{{language|Odin}} \ No newline at end of file +{{language +|exec=machine +|gc=no +|safety=unsafe +|parampass=reference +|checking=static +|compat=nominative +|strength=strong +|site=https://odin-lang.org/ +|tag=odin +}}{{language programming paradigm|Imperative}}{{Codepad}} + +'''Odin''' is a general-purpose, [[procedural programming|procedural]], [[imperative programming|imperative]] programming language developed by [https://www.gingerbill.org/ gingerBill] as a "C alternative for the joy of programming". + +Odin is distributed under [https://github.com/odin-lang/Odin/blob/master/LICENSE zlib license]. + +==Links== +* [https://odin-lang.org/docs/install/ Compiler installation instructions] +* [https://github.com/odin-lang/Odin Repository] +* [https://odin-lang.org/docs/overview/ Language overview] +* [https://pkg.odin-lang.org/ Standard library documentation] + +==Todo== +[[Tasks_not_implemented_in_Odin]] \ No newline at end of file diff --git a/Lang/Odin/100-doors b/Lang/Odin/100-doors new file mode 120000 index 0000000000..67c11787e6 --- /dev/null +++ b/Lang/Odin/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/Odin \ No newline at end of file diff --git a/Lang/Odin/Call-a-function-in-a-shared-library b/Lang/Odin/Call-a-function-in-a-shared-library new file mode 120000 index 0000000000..cf4ca70486 --- /dev/null +++ b/Lang/Odin/Call-a-function-in-a-shared-library @@ -0,0 +1 @@ +../../Task/Call-a-function-in-a-shared-library/Odin \ No newline at end of file diff --git a/Lang/Odin/Character-codes b/Lang/Odin/Character-codes new file mode 120000 index 0000000000..409b8a73d1 --- /dev/null +++ b/Lang/Odin/Character-codes @@ -0,0 +1 @@ +../../Task/Character-codes/Odin \ No newline at end of file diff --git a/Lang/Odin/Color-wheel b/Lang/Odin/Color-wheel new file mode 120000 index 0000000000..5b87562427 --- /dev/null +++ b/Lang/Odin/Color-wheel @@ -0,0 +1 @@ +../../Task/Color-wheel/Odin \ No newline at end of file diff --git a/Lang/Odin/Comments b/Lang/Odin/Comments new file mode 120000 index 0000000000..69505856e6 --- /dev/null +++ b/Lang/Odin/Comments @@ -0,0 +1 @@ +../../Task/Comments/Odin \ No newline at end of file diff --git a/Lang/Odin/Date-format b/Lang/Odin/Date-format new file mode 120000 index 0000000000..63e481d689 --- /dev/null +++ b/Lang/Odin/Date-format @@ -0,0 +1 @@ +../../Task/Date-format/Odin \ No newline at end of file diff --git a/Lang/Odin/Draw-a-clock b/Lang/Odin/Draw-a-clock new file mode 120000 index 0000000000..b014eb3c8e --- /dev/null +++ b/Lang/Odin/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/Odin \ No newline at end of file diff --git a/Lang/Odin/Draw-a-cuboid b/Lang/Odin/Draw-a-cuboid new file mode 120000 index 0000000000..124ff7cfe9 --- /dev/null +++ b/Lang/Odin/Draw-a-cuboid @@ -0,0 +1 @@ +../../Task/Draw-a-cuboid/Odin \ No newline at end of file diff --git a/Lang/Odin/Draw-a-sphere b/Lang/Odin/Draw-a-sphere new file mode 120000 index 0000000000..b20b72cdc0 --- /dev/null +++ b/Lang/Odin/Draw-a-sphere @@ -0,0 +1 @@ +../../Task/Draw-a-sphere/Odin \ No newline at end of file diff --git a/Lang/Odin/Euler-method b/Lang/Odin/Euler-method new file mode 120000 index 0000000000..2085f38551 --- /dev/null +++ b/Lang/Odin/Euler-method @@ -0,0 +1 @@ +../../Task/Euler-method/Odin \ No newline at end of file diff --git a/Lang/Odin/Execute-Brain- b/Lang/Odin/Execute-Brain- new file mode 120000 index 0000000000..748dbb9c99 --- /dev/null +++ b/Lang/Odin/Execute-Brain- @@ -0,0 +1 @@ +../../Task/Execute-Brain-/Odin \ No newline at end of file diff --git a/Lang/Odin/Fractran b/Lang/Odin/Fractran new file mode 120000 index 0000000000..5bd1840a6a --- /dev/null +++ b/Lang/Odin/Fractran @@ -0,0 +1 @@ +../../Task/Fractran/Odin \ No newline at end of file diff --git a/Lang/Odin/Function-composition b/Lang/Odin/Function-composition new file mode 120000 index 0000000000..27b230f571 --- /dev/null +++ b/Lang/Odin/Function-composition @@ -0,0 +1 @@ +../../Task/Function-composition/Odin \ No newline at end of file diff --git a/Lang/Odin/Hailstone-sequence b/Lang/Odin/Hailstone-sequence new file mode 120000 index 0000000000..678ea867f0 --- /dev/null +++ b/Lang/Odin/Hailstone-sequence @@ -0,0 +1 @@ +../../Task/Hailstone-sequence/Odin \ No newline at end of file diff --git a/Lang/Odin/Hello-world-Graphical b/Lang/Odin/Hello-world-Graphical new file mode 120000 index 0000000000..00108512b1 --- /dev/null +++ b/Lang/Odin/Hello-world-Graphical @@ -0,0 +1 @@ +../../Task/Hello-world-Graphical/Odin \ No newline at end of file diff --git a/Lang/Odin/Image-noise b/Lang/Odin/Image-noise new file mode 120000 index 0000000000..9b2e03c5b6 --- /dev/null +++ b/Lang/Odin/Image-noise @@ -0,0 +1 @@ +../../Task/Image-noise/Odin \ No newline at end of file diff --git a/Lang/Odin/Musical-scale b/Lang/Odin/Musical-scale new file mode 120000 index 0000000000..cd45a36de9 --- /dev/null +++ b/Lang/Odin/Musical-scale @@ -0,0 +1 @@ +../../Task/Musical-scale/Odin \ No newline at end of file diff --git a/Lang/Odin/One-dimensional-cellular-automata b/Lang/Odin/One-dimensional-cellular-automata new file mode 120000 index 0000000000..5cf45742c4 --- /dev/null +++ b/Lang/Odin/One-dimensional-cellular-automata @@ -0,0 +1 @@ +../../Task/One-dimensional-cellular-automata/Odin \ No newline at end of file diff --git a/Lang/Odin/Primality-by-trial-division b/Lang/Odin/Primality-by-trial-division new file mode 120000 index 0000000000..8e356363dd --- /dev/null +++ b/Lang/Odin/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/Odin \ No newline at end of file diff --git a/Lang/Odin/Quine b/Lang/Odin/Quine new file mode 120000 index 0000000000..53e4cf3687 --- /dev/null +++ b/Lang/Odin/Quine @@ -0,0 +1 @@ +../../Task/Quine/Odin \ No newline at end of file diff --git a/Lang/Odin/Read-a-configuration-file b/Lang/Odin/Read-a-configuration-file new file mode 120000 index 0000000000..fa189332d6 --- /dev/null +++ b/Lang/Odin/Read-a-configuration-file @@ -0,0 +1 @@ +../../Task/Read-a-configuration-file/Odin \ No newline at end of file diff --git a/Lang/Odin/Reverse-words-in-a-string b/Lang/Odin/Reverse-words-in-a-string new file mode 120000 index 0000000000..9648c360e7 --- /dev/null +++ b/Lang/Odin/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Odin \ No newline at end of file diff --git a/Lang/Odin/Runge-Kutta-method b/Lang/Odin/Runge-Kutta-method new file mode 120000 index 0000000000..1b9162c995 --- /dev/null +++ b/Lang/Odin/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/Odin \ No newline at end of file diff --git a/Lang/Odin/Sieve-of-Eratosthenes b/Lang/Odin/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..265789a7db --- /dev/null +++ b/Lang/Odin/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Odin \ No newline at end of file diff --git a/Lang/Odin/Sockets b/Lang/Odin/Sockets new file mode 120000 index 0000000000..ccedc5dd5d --- /dev/null +++ b/Lang/Odin/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/Odin \ No newline at end of file diff --git a/Lang/Odin/Strip-a-set-of-characters-from-a-string b/Lang/Odin/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..b76ef81d13 --- /dev/null +++ b/Lang/Odin/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Odin \ No newline at end of file diff --git a/Lang/Odin/Unicode-variable-names b/Lang/Odin/Unicode-variable-names new file mode 120000 index 0000000000..f070da9637 --- /dev/null +++ b/Lang/Odin/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/Odin \ No newline at end of file diff --git a/Lang/Odin/Write-entire-file b/Lang/Odin/Write-entire-file new file mode 120000 index 0000000000..53b4243bae --- /dev/null +++ b/Lang/Odin/Write-entire-file @@ -0,0 +1 @@ +../../Task/Write-entire-file/Odin \ No newline at end of file diff --git a/Lang/Oforth/Quaternion-type b/Lang/Oforth/Quaternion-type deleted file mode 120000 index 51caedda0e..0000000000 --- a/Lang/Oforth/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Oforth \ No newline at end of file diff --git a/Lang/Ol/Quaternion-type b/Lang/Ol/Quaternion-type deleted file mode 120000 index a3e712c033..0000000000 --- a/Lang/Ol/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Ol \ No newline at end of file diff --git a/Lang/Ol/Runge-Kutta-method b/Lang/Ol/Runge-Kutta-method new file mode 120000 index 0000000000..55f8d1bf18 --- /dev/null +++ b/Lang/Ol/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/Ol \ No newline at end of file diff --git a/Lang/OmniMark/00-LANG.txt b/Lang/OmniMark/00-LANG.txt new file mode 100644 index 0000000000..43585c3f19 --- /dev/null +++ b/Lang/OmniMark/00-LANG.txt @@ -0,0 +1,15 @@ +{{language|OmniMark +|tags=omnimark +|site=https://www.stilo.com/omnimark/}} +'''OmniMark''' is a fourth-generation programming language used mostly in the publishing industry. It is currently a proprietary software product of Stilo International. The most recent release of OmniMark is 12.0 (as at 2024-06-25). + +For a brief period, in 1999-2000, OmniMark was available free of charge (versions 4 and 5, including a 'Lite edition' of version 4, which was limited to 200 actions). + +==Links== +* [[wp:OmniMark|Omnimark in Wikipedia]] +* [https://developers.stilo.com/docs/html/index.html Version 12.0 documentation] +* [https://developers.stilo.com/documentation/docs/html/index.htm Version 6.5 documentation] +* [https://developers.stilo.com/documentation/v4r0/index.htm Version 4.0 documentation] + +==Todo== +* [[Tasks not implemented in OmniMark]] \ No newline at end of file diff --git a/Lang/OmniMark/00-META.yaml b/Lang/OmniMark/00-META.yaml new file mode 100644 index 0000000000..4f47c1011a --- /dev/null +++ b/Lang/OmniMark/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:OmniMark diff --git a/Lang/OmniMark/100-doors b/Lang/OmniMark/100-doors new file mode 120000 index 0000000000..97ec6d7965 --- /dev/null +++ b/Lang/OmniMark/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/OmniMark \ No newline at end of file diff --git a/Lang/OmniMark/Array-concatenation b/Lang/OmniMark/Array-concatenation new file mode 120000 index 0000000000..826b17e39e --- /dev/null +++ b/Lang/OmniMark/Array-concatenation @@ -0,0 +1 @@ +../../Task/Array-concatenation/OmniMark \ No newline at end of file diff --git a/Lang/OmniMark/Array-length b/Lang/OmniMark/Array-length new file mode 120000 index 0000000000..47ea995113 --- /dev/null +++ b/Lang/OmniMark/Array-length @@ -0,0 +1 @@ +../../Task/Array-length/OmniMark \ No newline at end of file diff --git a/Lang/OmniMark/CSV-to-HTML-translation b/Lang/OmniMark/CSV-to-HTML-translation new file mode 120000 index 0000000000..78c14aa62b --- /dev/null +++ b/Lang/OmniMark/CSV-to-HTML-translation @@ -0,0 +1 @@ +../../Task/CSV-to-HTML-translation/OmniMark \ No newline at end of file diff --git a/Lang/OmniMark/Caesar-cipher b/Lang/OmniMark/Caesar-cipher new file mode 120000 index 0000000000..abca569385 --- /dev/null +++ b/Lang/OmniMark/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/OmniMark \ No newline at end of file diff --git a/Lang/OmniMark/Camel-case-and-snake-case b/Lang/OmniMark/Camel-case-and-snake-case new file mode 120000 index 0000000000..977f7a6fec --- /dev/null +++ b/Lang/OmniMark/Camel-case-and-snake-case @@ -0,0 +1 @@ +../../Task/Camel-case-and-snake-case/OmniMark \ No newline at end of file diff --git a/Lang/OmniMark/Determine-if-a-string-has-all-the-same-characters b/Lang/OmniMark/Determine-if-a-string-has-all-the-same-characters new file mode 120000 index 0000000000..c1672ea012 --- /dev/null +++ b/Lang/OmniMark/Determine-if-a-string-has-all-the-same-characters @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-has-all-the-same-characters/OmniMark \ No newline at end of file diff --git a/Lang/OmniMark/Hello-world-Standard-error b/Lang/OmniMark/Hello-world-Standard-error new file mode 120000 index 0000000000..8ef2028e3a --- /dev/null +++ b/Lang/OmniMark/Hello-world-Standard-error @@ -0,0 +1 @@ +../../Task/Hello-world-Standard-error/OmniMark \ No newline at end of file diff --git a/Lang/OmniMark/Hex-words b/Lang/OmniMark/Hex-words new file mode 120000 index 0000000000..b43e37ad28 --- /dev/null +++ b/Lang/OmniMark/Hex-words @@ -0,0 +1 @@ +../../Task/Hex-words/OmniMark \ No newline at end of file diff --git a/Lang/OmniMark/ISBN13-check-digit b/Lang/OmniMark/ISBN13-check-digit new file mode 120000 index 0000000000..5629e040c9 --- /dev/null +++ b/Lang/OmniMark/ISBN13-check-digit @@ -0,0 +1 @@ +../../Task/ISBN13-check-digit/OmniMark \ No newline at end of file diff --git a/Lang/OmniMark/Input-loop b/Lang/OmniMark/Input-loop new file mode 120000 index 0000000000..c2f5884755 --- /dev/null +++ b/Lang/OmniMark/Input-loop @@ -0,0 +1 @@ +../../Task/Input-loop/OmniMark \ No newline at end of file diff --git a/Lang/OmniMark/Repeat-a-string b/Lang/OmniMark/Repeat-a-string new file mode 120000 index 0000000000..a5c79bdf8d --- /dev/null +++ b/Lang/OmniMark/Repeat-a-string @@ -0,0 +1 @@ +../../Task/Repeat-a-string/OmniMark \ No newline at end of file diff --git a/Lang/OmniMark/Reverse-a-string b/Lang/OmniMark/Reverse-a-string new file mode 120000 index 0000000000..ac30e9d9f0 --- /dev/null +++ b/Lang/OmniMark/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/OmniMark \ No newline at end of file diff --git a/Lang/OmniMark/Rot-13 b/Lang/OmniMark/Rot-13 new file mode 120000 index 0000000000..34ecde427b --- /dev/null +++ b/Lang/OmniMark/Rot-13 @@ -0,0 +1 @@ +../../Task/Rot-13/OmniMark \ No newline at end of file diff --git a/Lang/OmniMark/Strip-control-codes-and-extended-characters-from-a-string b/Lang/OmniMark/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..e108d513e0 --- /dev/null +++ b/Lang/OmniMark/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/OmniMark \ No newline at end of file diff --git a/Lang/OmniMark/Substring b/Lang/OmniMark/Substring new file mode 120000 index 0000000000..3eb9323ac2 --- /dev/null +++ b/Lang/OmniMark/Substring @@ -0,0 +1 @@ +../../Task/Substring/OmniMark \ No newline at end of file diff --git a/Lang/OmniMark/Substring-Top-and-tail b/Lang/OmniMark/Substring-Top-and-tail new file mode 120000 index 0000000000..b88887f219 --- /dev/null +++ b/Lang/OmniMark/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/OmniMark \ No newline at end of file diff --git a/Lang/OmniMark/XML-Input b/Lang/OmniMark/XML-Input new file mode 120000 index 0000000000..56ac42b963 --- /dev/null +++ b/Lang/OmniMark/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/OmniMark \ No newline at end of file diff --git a/Lang/OoRexx/00-LANG.txt b/Lang/OoRexx/00-LANG.txt index 8031f8ae00..84a3f74109 100644 --- a/Lang/OoRexx/00-LANG.txt +++ b/Lang/OoRexx/00-LANG.txt @@ -10,4 +10,7 @@ open sourced, maintained by the [http://www.rexxla.org/ Rexx Language Associatio ooRexx can be used to run many programs shown here in the [[REXX]] category. See http://rosettacode.org/wiki/Rosetta_Code:Village_Pump/Dialects#REXX.2C_ooRexx.2C_and_others -for differences. \ No newline at end of file +for differences. + +== Rosetta Code tasks not implemented in OoRexx == +[[Tasks not implemented in OoRexx]] \ No newline at end of file diff --git a/Lang/OoRexx/Giuga-numbers b/Lang/OoRexx/Giuga-numbers new file mode 120000 index 0000000000..86fe47decb --- /dev/null +++ b/Lang/OoRexx/Giuga-numbers @@ -0,0 +1 @@ +../../Task/Giuga-numbers/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Nth-root b/Lang/OoRexx/Nth-root new file mode 120000 index 0000000000..05543d43a8 --- /dev/null +++ b/Lang/OoRexx/Nth-root @@ -0,0 +1 @@ +../../Task/Nth-root/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Prime-decomposition b/Lang/OoRexx/Prime-decomposition new file mode 120000 index 0000000000..f16b4825fb --- /dev/null +++ b/Lang/OoRexx/Prime-decomposition @@ -0,0 +1 @@ +../../Task/Prime-decomposition/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Quaternion-type b/Lang/OoRexx/Quaternion-type deleted file mode 120000 index be3652b55d..0000000000 --- a/Lang/OoRexx/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Sorting-algorithms-Merge-sort b/Lang/OoRexx/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..ae6f4594d4 --- /dev/null +++ b/Lang/OoRexx/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/OoRexx \ No newline at end of file diff --git a/Lang/Openscad/Empty-program b/Lang/Openscad/Empty-program deleted file mode 120000 index 89182791e6..0000000000 --- a/Lang/Openscad/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Openscad \ No newline at end of file diff --git a/Lang/OxygenBasic/Array-length b/Lang/OxygenBasic/Array-length new file mode 120000 index 0000000000..00db990da9 --- /dev/null +++ b/Lang/OxygenBasic/Array-length @@ -0,0 +1 @@ +../../Task/Array-length/OxygenBasic \ No newline at end of file diff --git a/Lang/OxygenBasic/Blum-integer b/Lang/OxygenBasic/Blum-integer new file mode 120000 index 0000000000..343ecf7af1 --- /dev/null +++ b/Lang/OxygenBasic/Blum-integer @@ -0,0 +1 @@ +../../Task/Blum-integer/OxygenBasic \ No newline at end of file diff --git a/Lang/OxygenBasic/Cullen-and-Woodall-numbers b/Lang/OxygenBasic/Cullen-and-Woodall-numbers new file mode 120000 index 0000000000..75020e6fa5 --- /dev/null +++ b/Lang/OxygenBasic/Cullen-and-Woodall-numbers @@ -0,0 +1 @@ +../../Task/Cullen-and-Woodall-numbers/OxygenBasic \ No newline at end of file diff --git a/Lang/OxygenBasic/Determine-if-a-string-has-all-the-same-characters b/Lang/OxygenBasic/Determine-if-a-string-has-all-the-same-characters new file mode 120000 index 0000000000..5577d0b0ab --- /dev/null +++ b/Lang/OxygenBasic/Determine-if-a-string-has-all-the-same-characters @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-has-all-the-same-characters/OxygenBasic \ No newline at end of file diff --git a/Lang/OxygenBasic/Diversity-prediction-theorem b/Lang/OxygenBasic/Diversity-prediction-theorem new file mode 120000 index 0000000000..e07716f11a --- /dev/null +++ b/Lang/OxygenBasic/Diversity-prediction-theorem @@ -0,0 +1 @@ +../../Task/Diversity-prediction-theorem/OxygenBasic \ No newline at end of file diff --git a/Lang/OxygenBasic/Eban-numbers b/Lang/OxygenBasic/Eban-numbers new file mode 120000 index 0000000000..4b362db2df --- /dev/null +++ b/Lang/OxygenBasic/Eban-numbers @@ -0,0 +1 @@ +../../Task/Eban-numbers/OxygenBasic \ No newline at end of file diff --git a/Lang/OxygenBasic/Evaluate-binomial-coefficients b/Lang/OxygenBasic/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..2fc6117dc9 --- /dev/null +++ b/Lang/OxygenBasic/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/OxygenBasic \ No newline at end of file diff --git a/Lang/OxygenBasic/FizzBuzz b/Lang/OxygenBasic/FizzBuzz new file mode 120000 index 0000000000..7f3e716c79 --- /dev/null +++ b/Lang/OxygenBasic/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/OxygenBasic \ No newline at end of file diff --git a/Lang/OxygenBasic/Generate-lower-case-ASCII-alphabet b/Lang/OxygenBasic/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..dc06638a04 --- /dev/null +++ b/Lang/OxygenBasic/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/OxygenBasic \ No newline at end of file diff --git a/Lang/OxygenBasic/Hello-world-Newline-omission b/Lang/OxygenBasic/Hello-world-Newline-omission new file mode 120000 index 0000000000..b315730342 --- /dev/null +++ b/Lang/OxygenBasic/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/OxygenBasic \ No newline at end of file diff --git a/Lang/OxygenBasic/Hello-world-Text b/Lang/OxygenBasic/Hello-world-Text new file mode 120000 index 0000000000..0286beeff0 --- /dev/null +++ b/Lang/OxygenBasic/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/OxygenBasic \ No newline at end of file diff --git a/Lang/OxygenBasic/Hofstadter-Q-sequence b/Lang/OxygenBasic/Hofstadter-Q-sequence new file mode 120000 index 0000000000..99d7dde29e --- /dev/null +++ b/Lang/OxygenBasic/Hofstadter-Q-sequence @@ -0,0 +1 @@ +../../Task/Hofstadter-Q-sequence/OxygenBasic \ No newline at end of file diff --git a/Lang/OxygenBasic/Jewels-and-stones b/Lang/OxygenBasic/Jewels-and-stones new file mode 120000 index 0000000000..af9c0e197d --- /dev/null +++ b/Lang/OxygenBasic/Jewels-and-stones @@ -0,0 +1 @@ +../../Task/Jewels-and-stones/OxygenBasic \ No newline at end of file diff --git a/Lang/OxygenBasic/Josephus-problem b/Lang/OxygenBasic/Josephus-problem new file mode 120000 index 0000000000..26c79416e6 --- /dev/null +++ b/Lang/OxygenBasic/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/OxygenBasic \ No newline at end of file diff --git a/Lang/OxygenBasic/Leonardo-numbers b/Lang/OxygenBasic/Leonardo-numbers new file mode 120000 index 0000000000..9d8949a99b --- /dev/null +++ b/Lang/OxygenBasic/Leonardo-numbers @@ -0,0 +1 @@ +../../Task/Leonardo-numbers/OxygenBasic \ No newline at end of file diff --git a/Lang/OxygenBasic/Loops-Continue b/Lang/OxygenBasic/Loops-Continue new file mode 120000 index 0000000000..df4c4e529e --- /dev/null +++ b/Lang/OxygenBasic/Loops-Continue @@ -0,0 +1 @@ +../../Task/Loops-Continue/OxygenBasic \ No newline at end of file diff --git a/Lang/OxygenBasic/Numbers-with-equal-rises-and-falls b/Lang/OxygenBasic/Numbers-with-equal-rises-and-falls new file mode 120000 index 0000000000..0060a020b0 --- /dev/null +++ b/Lang/OxygenBasic/Numbers-with-equal-rises-and-falls @@ -0,0 +1 @@ +../../Task/Numbers-with-equal-rises-and-falls/OxygenBasic \ No newline at end of file diff --git a/Lang/OxygenBasic/Primality-by-trial-division b/Lang/OxygenBasic/Primality-by-trial-division new file mode 120000 index 0000000000..90df6937ed --- /dev/null +++ b/Lang/OxygenBasic/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/OxygenBasic \ No newline at end of file diff --git a/Lang/OxygenBasic/Repeat b/Lang/OxygenBasic/Repeat new file mode 120000 index 0000000000..56b4dec43d --- /dev/null +++ b/Lang/OxygenBasic/Repeat @@ -0,0 +1 @@ +../../Task/Repeat/OxygenBasic \ No newline at end of file diff --git a/Lang/OxygenBasic/Sudan-function b/Lang/OxygenBasic/Sudan-function new file mode 120000 index 0000000000..05a812bb81 --- /dev/null +++ b/Lang/OxygenBasic/Sudan-function @@ -0,0 +1 @@ +../../Task/Sudan-function/OxygenBasic \ No newline at end of file diff --git a/Lang/OxygenBasic/Tau-number b/Lang/OxygenBasic/Tau-number new file mode 120000 index 0000000000..4f73054594 --- /dev/null +++ b/Lang/OxygenBasic/Tau-number @@ -0,0 +1 @@ +../../Task/Tau-number/OxygenBasic \ No newline at end of file diff --git a/Lang/Oz/FizzBuzz b/Lang/Oz/FizzBuzz deleted file mode 120000 index 287980acd6..0000000000 --- a/Lang/Oz/FizzBuzz +++ /dev/null @@ -1 +0,0 @@ -../../Task/FizzBuzz/Oz \ No newline at end of file diff --git a/Lang/Oz/Miller-Rabin-primality-test b/Lang/Oz/Miller-Rabin-primality-test deleted file mode 120000 index e6999d8858..0000000000 --- a/Lang/Oz/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Oz \ No newline at end of file diff --git a/Lang/PARI-GP/00-LANG.txt b/Lang/PARI-GP/00-LANG.txt index bacfec6d7d..81b37f3de6 100644 --- a/Lang/PARI-GP/00-LANG.txt +++ b/Lang/PARI-GP/00-LANG.txt @@ -17,7 +17,7 @@ PARI/GP is a widely used computer algebra system designed for fast computations PARI/GP is composed of two parts: a [[C]] library called PARI and an interface, gp, to this library. GP scripts are concise, easy to write, and resemble mathematical language. (Terminology: the scripting language of gp is called GP.) -PARI was written by Henri Cohen and others at Université de Bordeaux and is now maintained by Karim Belabas. gp was originally written by Dominique Bernardi, then maintained and enhanced by Karim Belabas and Ilya Zakharevich, and finally rewritten by Bill Allombert. +PARI was written by Henri Cohen and others at Université de Bordeaux; Aurel Page is the current project leader. gp was originally written by Dominique Bernardi, then maintained and enhanced by Karim Belabas and Ilya Zakharevich, and finally rewritten by Bill Allombert. == Getting PARI/GP == PARI/GP can be used in many different operating systems. This is a reasonably comprehensive list of currently-supported systems; for other systems, please use the [https://pari.math.u-bordeaux.fr/lists-index.html mailing lists]. @@ -219,12 +219,16 @@ If you want to program with PARI, many languages are supported: ** [https://pari.math.u-bordeaux.fr/Events/PARI2017c/talks/TAN2.pdf Théorie algébrique des nombres avancée] (22 pp.) ** [https://pari.math.u-bordeaux.fr/Events/PARI2017c/talks/ecc.pdf Courbes elliptiques sur les corps finis] (4 pp.) *[http://w3.countnumber.de/fischer/res-ZT2007/PariByExample.pdf Erste Schritte mit PARI/GP] by Lars Fischer (13 pp., 2007; German) -*[https://www.youtube.com/watch?v=I_GfMUGAlns Pari Gp مع NotPad++] by NoorDeen Rahmani (2020; 2:46; Arabic) -- setting up Notepad++ for syntax highlighting for PARI/GP. +* [https://www.youtube.com/watch?v=I_GfMUGAlns Pari Gp مع NotPad++] by NoorDeen Rahmani (2020; 2:46; Arabic) -- setting up Notepad++ for syntax highlighting for PARI/GP. ==== Video tutorials ==== * [https://www.youtube.com/watch?v=RQLqQHu7i0Y Pari/GP Tutorial: Basics] by Leandro Junes (2020, 19:04) -*[https://www.youtube.com/watch?v=FeG0BYRrDOE&t=12m Video demo of RSA in PARI/GP] by Maren1955 (2014, 17:39) -*Video tutorials, parts [http://www.youtube.com/watch?v=0G-9JzlrzBM 1] [http://www.youtube.com/watch?v=d7i0rv59hns 2] [http://www.youtube.com/watch?v=wCyU2n-G-pk 3] [http://www.youtube.com/watch?v=WOCuBvK8O6Q 4] (2011, appx. 20 minutes) +* [https://www.youtube.com/watch?v=FeG0BYRrDOE&t=12m Video demo of RSA in PARI/GP] by Maren1955 (2014, 17:39) +* Video tutorials, parts [http://www.youtube.com/watch?v=0G-9JzlrzBM 1] [http://www.youtube.com/watch?v=d7i0rv59hns 2] [http://www.youtube.com/watch?v=wCyU2n-G-pk 3] [http://www.youtube.com/watch?v=WOCuBvK8O6Q 4] (2011, appx. 20 minutes) + +== Syntax highlighting == +* [https://github.com/notepad-plus-plus/userDefinedLanguages/blob/master/UDLs/PARI-GP_by-third_maths.xml Notepad++] +* [https://www.youtube.com/watch?v=I_GfMUGAlns Pari Gp مع NotPad++] (Arabic tutorial) === Papers on PARI/GP === * Karim Belabas and Henri Cohen, [https://arxiv.org/abs/1810.00547 Modular Forms in Pari/GP], ''Research in the Mathematical Sciences'' '''5''':37 (2018) diff --git a/Lang/PARI-GP/4-rings-or-4-squares-puzzle b/Lang/PARI-GP/4-rings-or-4-squares-puzzle new file mode 120000 index 0000000000..b8cfa5a07c --- /dev/null +++ b/Lang/PARI-GP/4-rings-or-4-squares-puzzle @@ -0,0 +1 @@ +../../Task/4-rings-or-4-squares-puzzle/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Achilles-numbers b/Lang/PARI-GP/Achilles-numbers new file mode 120000 index 0000000000..73f3f645b5 --- /dev/null +++ b/Lang/PARI-GP/Achilles-numbers @@ -0,0 +1 @@ +../../Task/Achilles-numbers/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Almkvist-Giullera-formula-for-pi b/Lang/PARI-GP/Almkvist-Giullera-formula-for-pi new file mode 120000 index 0000000000..53d950c5f0 --- /dev/null +++ b/Lang/PARI-GP/Almkvist-Giullera-formula-for-pi @@ -0,0 +1 @@ +../../Task/Almkvist-Giullera-formula-for-pi/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Attractive-numbers b/Lang/PARI-GP/Attractive-numbers new file mode 120000 index 0000000000..9c5ab01706 --- /dev/null +++ b/Lang/PARI-GP/Attractive-numbers @@ -0,0 +1 @@ +../../Task/Attractive-numbers/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Bell-numbers b/Lang/PARI-GP/Bell-numbers new file mode 120000 index 0000000000..c0de777713 --- /dev/null +++ b/Lang/PARI-GP/Bell-numbers @@ -0,0 +1 @@ +../../Task/Bell-numbers/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Disarium-numbers b/Lang/PARI-GP/Disarium-numbers new file mode 120000 index 0000000000..e21e95674b --- /dev/null +++ b/Lang/PARI-GP/Disarium-numbers @@ -0,0 +1 @@ +../../Task/Disarium-numbers/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Empty-program b/Lang/PARI-GP/Empty-program deleted file mode 120000 index e5621857fc..0000000000 --- a/Lang/PARI-GP/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Gapful-numbers b/Lang/PARI-GP/Gapful-numbers new file mode 120000 index 0000000000..a3ce3c2de1 --- /dev/null +++ b/Lang/PARI-GP/Gapful-numbers @@ -0,0 +1 @@ +../../Task/Gapful-numbers/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Meissel-Mertens-constant b/Lang/PARI-GP/Meissel-Mertens-constant deleted file mode 120000 index b03a10e2fd..0000000000 --- a/Lang/PARI-GP/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Miller-Rabin-primality-test b/Lang/PARI-GP/Miller-Rabin-primality-test deleted file mode 120000 index 6c17b6de21..0000000000 --- a/Lang/PARI-GP/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Pell-numbers b/Lang/PARI-GP/Pell-numbers new file mode 120000 index 0000000000..6dc31a644a --- /dev/null +++ b/Lang/PARI-GP/Pell-numbers @@ -0,0 +1 @@ +../../Task/Pell-numbers/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Prime-numbers-whose-neighboring-pairs-are-tetraprimes b/Lang/PARI-GP/Prime-numbers-whose-neighboring-pairs-are-tetraprimes new file mode 120000 index 0000000000..497a956889 --- /dev/null +++ b/Lang/PARI-GP/Prime-numbers-whose-neighboring-pairs-are-tetraprimes @@ -0,0 +1 @@ +../../Task/Prime-numbers-whose-neighboring-pairs-are-tetraprimes/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Quaternion-type b/Lang/PARI-GP/Quaternion-type deleted file mode 120000 index 87636fd8d1..0000000000 --- a/Lang/PARI-GP/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Sorting-Algorithms-Circle-Sort b/Lang/PARI-GP/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 2e42235ea5..0000000000 --- a/Lang/PARI-GP/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Tonelli-Shanks-algorithm b/Lang/PARI-GP/Tonelli-Shanks-algorithm new file mode 120000 index 0000000000..de551c5a5b --- /dev/null +++ b/Lang/PARI-GP/Tonelli-Shanks-algorithm @@ -0,0 +1 @@ +../../Task/Tonelli-Shanks-algorithm/PARI-GP \ No newline at end of file diff --git a/Lang/PHP/00-LANG.txt b/Lang/PHP/00-LANG.txt index ad1d2b043d..894fa89337 100644 --- a/Lang/PHP/00-LANG.txt +++ b/Lang/PHP/00-LANG.txt @@ -13,4 +13,13 @@ '''PHP''' (PHP: Hypertext Preprocessor) is a [[reflective programming]] language originally designed for producing dynamic Web pages. PHP is used mainly in server-side application software, but can be used from a command line interface or in standalone graphical applications. ==Citations== -* [[wp:PHP|Wikipedia:PHP]] \ No newline at end of file +* [[wp:PHP|Wikipedia:PHP]] + +==External links== +=== Online compilers === +* [https://onlinephp.io/ PHP Sandbox - Execute PHP code online through your browser] (online compiler) +* [https://www.mycompiler.io/new/php Create a new PHP program - myCompiler - myCompiler] (online compiler) + +=== Tutorials and manuals === +* [https://www.w3schools.com/php/default.asp PHP Tutorial] on [https://www.w3schools.com www.w3schools.com] +* [https://www.geeksforgeeks.org/php/php-tutorial/ PHP Tutorial - GeeksforGeeks] \ No newline at end of file diff --git a/Lang/PHP/AKS-test-for-primes b/Lang/PHP/AKS-test-for-primes new file mode 120000 index 0000000000..e35d324f89 --- /dev/null +++ b/Lang/PHP/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/PHP \ No newline at end of file diff --git a/Lang/PHP/Abbreviations-automatic b/Lang/PHP/Abbreviations-automatic new file mode 120000 index 0000000000..30112aa9b6 --- /dev/null +++ b/Lang/PHP/Abbreviations-automatic @@ -0,0 +1 @@ +../../Task/Abbreviations-automatic/PHP \ No newline at end of file diff --git a/Lang/PHP/Abundant-deficient-and-perfect-number-classifications b/Lang/PHP/Abundant-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..c5476da28d --- /dev/null +++ b/Lang/PHP/Abundant-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant-deficient-and-perfect-number-classifications/PHP \ No newline at end of file diff --git a/Lang/PHP/Abundant-odd-numbers b/Lang/PHP/Abundant-odd-numbers new file mode 120000 index 0000000000..c610a0d9cd --- /dev/null +++ b/Lang/PHP/Abundant-odd-numbers @@ -0,0 +1 @@ +../../Task/Abundant-odd-numbers/PHP \ No newline at end of file diff --git a/Lang/PHP/Angle-difference-between-two-bearings b/Lang/PHP/Angle-difference-between-two-bearings new file mode 120000 index 0000000000..357602b50f --- /dev/null +++ b/Lang/PHP/Angle-difference-between-two-bearings @@ -0,0 +1 @@ +../../Task/Angle-difference-between-two-bearings/PHP \ No newline at end of file diff --git a/Lang/PHP/Arithmetic-numbers b/Lang/PHP/Arithmetic-numbers new file mode 120000 index 0000000000..21fbcc7304 --- /dev/null +++ b/Lang/PHP/Arithmetic-numbers @@ -0,0 +1 @@ +../../Task/Arithmetic-numbers/PHP \ No newline at end of file diff --git a/Lang/PHP/Bell-numbers b/Lang/PHP/Bell-numbers new file mode 120000 index 0000000000..879d53dae5 --- /dev/null +++ b/Lang/PHP/Bell-numbers @@ -0,0 +1 @@ +../../Task/Bell-numbers/PHP \ No newline at end of file diff --git a/Lang/PHP/Brazilian-numbers b/Lang/PHP/Brazilian-numbers new file mode 120000 index 0000000000..5bd899327e --- /dev/null +++ b/Lang/PHP/Brazilian-numbers @@ -0,0 +1 @@ +../../Task/Brazilian-numbers/PHP \ No newline at end of file diff --git a/Lang/PHP/Diversity-prediction-theorem b/Lang/PHP/Diversity-prediction-theorem new file mode 120000 index 0000000000..a50f50e661 --- /dev/null +++ b/Lang/PHP/Diversity-prediction-theorem @@ -0,0 +1 @@ +../../Task/Diversity-prediction-theorem/PHP \ No newline at end of file diff --git a/Lang/PHP/Gamma-function b/Lang/PHP/Gamma-function new file mode 120000 index 0000000000..4d00e2f50d --- /dev/null +++ b/Lang/PHP/Gamma-function @@ -0,0 +1 @@ +../../Task/Gamma-function/PHP \ No newline at end of file diff --git a/Lang/PHP/Horizontal-sundial-calculations b/Lang/PHP/Horizontal-sundial-calculations new file mode 120000 index 0000000000..a385f37a68 --- /dev/null +++ b/Lang/PHP/Horizontal-sundial-calculations @@ -0,0 +1 @@ +../../Task/Horizontal-sundial-calculations/PHP \ No newline at end of file diff --git a/Lang/PHP/Leonardo-numbers b/Lang/PHP/Leonardo-numbers new file mode 120000 index 0000000000..4b3cefd6f0 --- /dev/null +++ b/Lang/PHP/Leonardo-numbers @@ -0,0 +1 @@ +../../Task/Leonardo-numbers/PHP \ No newline at end of file diff --git a/Lang/PHP/M-bius-function b/Lang/PHP/M-bius-function new file mode 120000 index 0000000000..6f4e3a47bb --- /dev/null +++ b/Lang/PHP/M-bius-function @@ -0,0 +1 @@ +../../Task/M-bius-function/PHP \ No newline at end of file diff --git a/Lang/PHP/Magic-constant b/Lang/PHP/Magic-constant new file mode 120000 index 0000000000..b67d20fb19 --- /dev/null +++ b/Lang/PHP/Magic-constant @@ -0,0 +1 @@ +../../Task/Magic-constant/PHP \ No newline at end of file diff --git a/Lang/PHP/Map-range b/Lang/PHP/Map-range new file mode 120000 index 0000000000..07d5696e85 --- /dev/null +++ b/Lang/PHP/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/PHP \ No newline at end of file diff --git a/Lang/PHP/Miller-Rabin-primality-test b/Lang/PHP/Miller-Rabin-primality-test deleted file mode 120000 index bff04d1a83..0000000000 --- a/Lang/PHP/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/PHP \ No newline at end of file diff --git a/Lang/PHP/Multifactorial b/Lang/PHP/Multifactorial new file mode 120000 index 0000000000..a4051140a1 --- /dev/null +++ b/Lang/PHP/Multifactorial @@ -0,0 +1 @@ +../../Task/Multifactorial/PHP \ No newline at end of file diff --git a/Lang/PHP/Partial-function-application b/Lang/PHP/Partial-function-application new file mode 120000 index 0000000000..8596466c3e --- /dev/null +++ b/Lang/PHP/Partial-function-application @@ -0,0 +1 @@ +../../Task/Partial-function-application/PHP \ No newline at end of file diff --git a/Lang/PHP/Prime-decomposition b/Lang/PHP/Prime-decomposition new file mode 120000 index 0000000000..6265ac9618 --- /dev/null +++ b/Lang/PHP/Prime-decomposition @@ -0,0 +1 @@ +../../Task/Prime-decomposition/PHP \ No newline at end of file diff --git a/Lang/PHP/Square-free-integers b/Lang/PHP/Square-free-integers new file mode 120000 index 0000000000..49d9fb45c0 --- /dev/null +++ b/Lang/PHP/Square-free-integers @@ -0,0 +1 @@ +../../Task/Square-free-integers/PHP \ No newline at end of file diff --git a/Lang/PHP/Statistics-Basic b/Lang/PHP/Statistics-Basic new file mode 120000 index 0000000000..199b45c315 --- /dev/null +++ b/Lang/PHP/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/PHP \ No newline at end of file diff --git a/Lang/PHP/Statistics-Normal-distribution b/Lang/PHP/Statistics-Normal-distribution new file mode 120000 index 0000000000..e8fce08a80 --- /dev/null +++ b/Lang/PHP/Statistics-Normal-distribution @@ -0,0 +1 @@ +../../Task/Statistics-Normal-distribution/PHP \ No newline at end of file diff --git a/Lang/PHP/Tau-number b/Lang/PHP/Tau-number new file mode 120000 index 0000000000..67a4445d30 --- /dev/null +++ b/Lang/PHP/Tau-number @@ -0,0 +1 @@ +../../Task/Tau-number/PHP \ No newline at end of file diff --git a/Lang/PHP/Water-collected-between-towers b/Lang/PHP/Water-collected-between-towers new file mode 120000 index 0000000000..524c5ae99b --- /dev/null +++ b/Lang/PHP/Water-collected-between-towers @@ -0,0 +1 @@ +../../Task/Water-collected-between-towers/PHP \ No newline at end of file diff --git a/Lang/PILOT/00-LANG.txt b/Lang/PILOT/00-LANG.txt index 742582e7c0..5e238de7ae 100644 --- a/Lang/PILOT/00-LANG.txt +++ b/Lang/PILOT/00-LANG.txt @@ -9,4 +9,6 @@ NO:Sorry, it was Napoleon Bonaparte. PILOT was also marketed in the 1980s as a first programming language for children and beginners, including in extended versions supporting turtle graphics; and it even found use as a scripting language under CP/M. -Keywords—written in block capitals in the example above—are case-insensitive and can usually be abbreviated to one or two letters (T for TYPE, JM for JUMPMATCH). The only data types supported are strings and integers. \ No newline at end of file +Keywords—written in block capitals in the example above—are case-insensitive and can usually be abbreviated to one or two letters (T for TYPE, JM for JUMPMATCH). The only data types supported are strings and integers. +=== External Links === +[https://handwiki.org/wiki/PILOT HandWiki PILOT], where you can find a list of PILOT implementations. \ No newline at end of file diff --git a/Lang/PL-I-80/Additive-primes b/Lang/PL-I-80/Additive-primes new file mode 120000 index 0000000000..a065cd3d8e --- /dev/null +++ b/Lang/PL-I-80/Additive-primes @@ -0,0 +1 @@ +../../Task/Additive-primes/PL-I-80 \ No newline at end of file diff --git a/Lang/PL-I-80/Character-codes b/Lang/PL-I-80/Character-codes new file mode 120000 index 0000000000..c19a7eafa1 --- /dev/null +++ b/Lang/PL-I-80/Character-codes @@ -0,0 +1 @@ +../../Task/Character-codes/PL-I-80 \ No newline at end of file diff --git a/Lang/PL-I-80/Integer-overflow b/Lang/PL-I-80/Integer-overflow new file mode 120000 index 0000000000..f1947b64b4 --- /dev/null +++ b/Lang/PL-I-80/Integer-overflow @@ -0,0 +1 @@ +../../Task/Integer-overflow/PL-I-80 \ No newline at end of file diff --git a/Lang/PL-I-80/Square-free-integers b/Lang/PL-I-80/Square-free-integers new file mode 120000 index 0000000000..6f8a00edb8 --- /dev/null +++ b/Lang/PL-I-80/Square-free-integers @@ -0,0 +1 @@ +../../Task/Square-free-integers/PL-I-80 \ No newline at end of file diff --git a/Lang/PL-I-80/Strip-whitespace-from-a-string-Top-and-tail b/Lang/PL-I-80/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..ac54cb4639 --- /dev/null +++ b/Lang/PL-I-80/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/PL-I-80 \ No newline at end of file diff --git a/Lang/PL-I/00-LANG.txt b/Lang/PL-I/00-LANG.txt index e9ccbaa140..3b9ba57193 100644 --- a/Lang/PL-I/00-LANG.txt +++ b/Lang/PL-I/00-LANG.txt @@ -84,4 +84,8 @@ The pre-processor keywords are prefixed with a   %   (perce ==See Also== * [[wp:PL/I|PL/I on Wikipedia]] * [[PL/M]] -* [[Polyglot:PL/I and PL/M]] \ No newline at end of file +* [[Polyglot:PL/I and PL/M]] + +==External links== +* [http://teampli.net/index.html Team PL/I] +** [http://teampli.net/candt.html PL/I Compilers and Tools] \ No newline at end of file diff --git a/Lang/PL-I/Abundant-odd-numbers b/Lang/PL-I/Abundant-odd-numbers new file mode 120000 index 0000000000..666cd2c37f --- /dev/null +++ b/Lang/PL-I/Abundant-odd-numbers @@ -0,0 +1 @@ +../../Task/Abundant-odd-numbers/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Arithmetic-derivative b/Lang/PL-I/Arithmetic-derivative new file mode 120000 index 0000000000..37f109623d --- /dev/null +++ b/Lang/PL-I/Arithmetic-derivative @@ -0,0 +1 @@ +../../Task/Arithmetic-derivative/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Arithmetic-numbers b/Lang/PL-I/Arithmetic-numbers new file mode 120000 index 0000000000..6912369ef9 --- /dev/null +++ b/Lang/PL-I/Arithmetic-numbers @@ -0,0 +1 @@ +../../Task/Arithmetic-numbers/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Bell-numbers b/Lang/PL-I/Bell-numbers new file mode 120000 index 0000000000..4afaf5b11f --- /dev/null +++ b/Lang/PL-I/Bell-numbers @@ -0,0 +1 @@ +../../Task/Bell-numbers/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Diversity-prediction-theorem b/Lang/PL-I/Diversity-prediction-theorem new file mode 120000 index 0000000000..a449ec2ac9 --- /dev/null +++ b/Lang/PL-I/Diversity-prediction-theorem @@ -0,0 +1 @@ +../../Task/Diversity-prediction-theorem/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Fairshare-between-two-and-more b/Lang/PL-I/Fairshare-between-two-and-more new file mode 120000 index 0000000000..38f481a639 --- /dev/null +++ b/Lang/PL-I/Fairshare-between-two-and-more @@ -0,0 +1 @@ +../../Task/Fairshare-between-two-and-more/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Quaternion-type b/Lang/PL-I/Quaternion-type deleted file mode 120000 index b86d406fec..0000000000 --- a/Lang/PL-I/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Tau-number b/Lang/PL-I/Tau-number new file mode 120000 index 0000000000..3dade8db80 --- /dev/null +++ b/Lang/PL-I/Tau-number @@ -0,0 +1 @@ +../../Task/Tau-number/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Zeckendorf-number-representation b/Lang/PL-I/Zeckendorf-number-representation new file mode 120000 index 0000000000..eabc5808d1 --- /dev/null +++ b/Lang/PL-I/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/PL-I \ No newline at end of file diff --git a/Lang/PL-M/100-doors b/Lang/PL-M/100-doors deleted file mode 120000 index fb7e956c0e..0000000000 --- a/Lang/PL-M/100-doors +++ /dev/null @@ -1 +0,0 @@ -../../Task/100-doors/PL-M \ No newline at end of file diff --git a/Lang/PL-M/Arithmetic-derivative b/Lang/PL-M/Arithmetic-derivative new file mode 120000 index 0000000000..13f3e396fe --- /dev/null +++ b/Lang/PL-M/Arithmetic-derivative @@ -0,0 +1 @@ +../../Task/Arithmetic-derivative/PL-M \ No newline at end of file diff --git a/Lang/PL-M/Draw-a-cuboid b/Lang/PL-M/Draw-a-cuboid new file mode 120000 index 0000000000..c6084a0c66 --- /dev/null +++ b/Lang/PL-M/Draw-a-cuboid @@ -0,0 +1 @@ +../../Task/Draw-a-cuboid/PL-M \ No newline at end of file diff --git a/Lang/PL-M/Empty-program b/Lang/PL-M/Empty-program new file mode 120000 index 0000000000..80a556ac57 --- /dev/null +++ b/Lang/PL-M/Empty-program @@ -0,0 +1 @@ +../../Task/Empty-program/PL-M \ No newline at end of file diff --git a/Lang/PL-M/Move-to-front-algorithm b/Lang/PL-M/Move-to-front-algorithm new file mode 120000 index 0000000000..23bec2ef3f --- /dev/null +++ b/Lang/PL-M/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/PL-M \ No newline at end of file diff --git a/Lang/PL-M/Nested-function b/Lang/PL-M/Nested-function new file mode 120000 index 0000000000..2fbc4399dd --- /dev/null +++ b/Lang/PL-M/Nested-function @@ -0,0 +1 @@ +../../Task/Nested-function/PL-M \ No newline at end of file diff --git a/Lang/PL-M/Super-d-numbers b/Lang/PL-M/Super-d-numbers new file mode 120000 index 0000000000..bb5c98f089 --- /dev/null +++ b/Lang/PL-M/Super-d-numbers @@ -0,0 +1 @@ +../../Task/Super-d-numbers/PL-M \ No newline at end of file diff --git a/Lang/PL-M/The-Twelve-Days-of-Christmas b/Lang/PL-M/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..a94c814e99 --- /dev/null +++ b/Lang/PL-M/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/PL-M \ No newline at end of file diff --git a/Lang/PL-M/Zeckendorf-number-representation b/Lang/PL-M/Zeckendorf-number-representation new file mode 120000 index 0000000000..3d48575a07 --- /dev/null +++ b/Lang/PL-M/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/PL-M \ No newline at end of file diff --git a/Lang/POV-Ray/Bitmap b/Lang/POV-Ray/Bitmap new file mode 120000 index 0000000000..90fece7e75 --- /dev/null +++ b/Lang/POV-Ray/Bitmap @@ -0,0 +1 @@ +../../Task/Bitmap/POV-Ray \ No newline at end of file diff --git a/Lang/POV-Ray/Maze-generation b/Lang/POV-Ray/Maze-generation new file mode 120000 index 0000000000..724f710098 --- /dev/null +++ b/Lang/POV-Ray/Maze-generation @@ -0,0 +1 @@ +../../Task/Maze-generation/POV-Ray \ No newline at end of file diff --git a/Lang/Pascal-P/00-LANG.txt b/Lang/Pascal-P/00-LANG.txt new file mode 100644 index 0000000000..ce87f461ab --- /dev/null +++ b/Lang/Pascal-P/00-LANG.txt @@ -0,0 +1,23 @@ +{{language|Pascal-P +|exec=bytecode +|strength=strong +|safety=safe +|express=explicit +|checking=static +|parampass=both +|gc=no +|LCT=yes +}}{{language programming paradigm|Procedural}} + +{{implementation|Pascal}}{{Compiler}} + +'''Pascal-P''' is a renowned [[:Category:Pascal|Pascal]] compiler designed to generate [[bytecode]], known as ''p-code'', and interpret the resulting code. The compilers and interpreters of Pascal-P are developed using the Pascal programming language. + +Originally developed in Zurich in 1973, the earliest iteration of Pascal-P, known as Pascal-P1, laid the foundation for subsequent versions, including P2, P3, and P4. While versions P1 and P3 are no longer accessible, P2 is still readily available and has notably served as the base for the UCSD system. Furthermore, there exist derivative versions, such as P5 and P6, which have evolved from the core Pascal-P compiler. + +Notably, Pascal-P is heralded for its portability, as it is capable of generating code suitable for a hypothetical stack computer system. This feature enhances its versatility and applicability across various platforms and environments. Additionally, Pascal-P has made significant contributions to the realm of education, often being utilized as an educational tool to impart knowledge and foster learning in the field of computer programming. + +== External links == +* [http://pascal.hansotten.com/niklaus-wirth/px-compilers Px compilers] on [http://pascal.hansotten.com/ Pascal for small machines] +* [https://sourceforge.net/projects/pascalp4/ Scott Moore's version of P4] The package includes crucial components essential for program execution on the MS-DOS platform - the compiler and the p-code interpreter executables. +* [https://www.moorecad.com/standardpascal/p4.html The P4 compiler] on [https://www.moorecad.com/ Scott Moore's page] \ No newline at end of file diff --git a/Lang/Pascal-P/00-META.yaml b/Lang/Pascal-P/00-META.yaml new file mode 100644 index 0000000000..5af4159a1f --- /dev/null +++ b/Lang/Pascal-P/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Pascal-P diff --git a/Lang/Pascal-P/Abundant-deficient-and-perfect-number-classifications b/Lang/Pascal-P/Abundant-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..248c55dcbd --- /dev/null +++ b/Lang/Pascal-P/Abundant-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant-deficient-and-perfect-number-classifications/Pascal-P \ No newline at end of file diff --git a/Lang/Pascal-P/Abundant-odd-numbers b/Lang/Pascal-P/Abundant-odd-numbers new file mode 120000 index 0000000000..745698036f --- /dev/null +++ b/Lang/Pascal-P/Abundant-odd-numbers @@ -0,0 +1 @@ +../../Task/Abundant-odd-numbers/Pascal-P \ No newline at end of file diff --git a/Lang/Pascal-P/Angle-difference-between-two-bearings b/Lang/Pascal-P/Angle-difference-between-two-bearings new file mode 120000 index 0000000000..506fbb7a95 --- /dev/null +++ b/Lang/Pascal-P/Angle-difference-between-two-bearings @@ -0,0 +1 @@ +../../Task/Angle-difference-between-two-bearings/Pascal-P \ No newline at end of file diff --git a/Lang/Pascal-P/Anti-primes b/Lang/Pascal-P/Anti-primes new file mode 120000 index 0000000000..fe2e4f4a10 --- /dev/null +++ b/Lang/Pascal-P/Anti-primes @@ -0,0 +1 @@ +../../Task/Anti-primes/Pascal-P \ No newline at end of file diff --git a/Lang/Pascal-P/Arithmetic-numbers b/Lang/Pascal-P/Arithmetic-numbers new file mode 120000 index 0000000000..3ad1b31145 --- /dev/null +++ b/Lang/Pascal-P/Arithmetic-numbers @@ -0,0 +1 @@ +../../Task/Arithmetic-numbers/Pascal-P \ No newline at end of file diff --git a/Lang/Pascal-P/Bell-numbers b/Lang/Pascal-P/Bell-numbers new file mode 120000 index 0000000000..fccbe75006 --- /dev/null +++ b/Lang/Pascal-P/Bell-numbers @@ -0,0 +1 @@ +../../Task/Bell-numbers/Pascal-P \ No newline at end of file diff --git a/Lang/Pascal-P/Brazilian-numbers b/Lang/Pascal-P/Brazilian-numbers new file mode 120000 index 0000000000..f79a88ea27 --- /dev/null +++ b/Lang/Pascal-P/Brazilian-numbers @@ -0,0 +1 @@ +../../Task/Brazilian-numbers/Pascal-P \ No newline at end of file diff --git a/Lang/Pascal-P/CUSIP b/Lang/Pascal-P/CUSIP new file mode 120000 index 0000000000..3a5ce6c0b7 --- /dev/null +++ b/Lang/Pascal-P/CUSIP @@ -0,0 +1 @@ +../../Task/CUSIP/Pascal-P \ No newline at end of file diff --git a/Lang/Pascal-P/Catalan-numbers b/Lang/Pascal-P/Catalan-numbers new file mode 120000 index 0000000000..9dee46f2ca --- /dev/null +++ b/Lang/Pascal-P/Catalan-numbers @@ -0,0 +1 @@ +../../Task/Catalan-numbers/Pascal-P \ No newline at end of file diff --git a/Lang/Pascal-P/Cistercian-numerals b/Lang/Pascal-P/Cistercian-numerals new file mode 120000 index 0000000000..3169bb4737 --- /dev/null +++ b/Lang/Pascal-P/Cistercian-numerals @@ -0,0 +1 @@ +../../Task/Cistercian-numerals/Pascal-P \ No newline at end of file diff --git a/Lang/Pascal-P/Day-of-the-week b/Lang/Pascal-P/Day-of-the-week new file mode 120000 index 0000000000..04c1bf395c --- /dev/null +++ b/Lang/Pascal-P/Day-of-the-week @@ -0,0 +1 @@ +../../Task/Day-of-the-week/Pascal-P \ No newline at end of file diff --git a/Lang/Pascal-P/Diversity-prediction-theorem b/Lang/Pascal-P/Diversity-prediction-theorem new file mode 120000 index 0000000000..1c77b9f4a8 --- /dev/null +++ b/Lang/Pascal-P/Diversity-prediction-theorem @@ -0,0 +1 @@ +../../Task/Diversity-prediction-theorem/Pascal-P \ No newline at end of file diff --git a/Lang/Pascal-P/Dot-product b/Lang/Pascal-P/Dot-product new file mode 120000 index 0000000000..1354e110a2 --- /dev/null +++ b/Lang/Pascal-P/Dot-product @@ -0,0 +1 @@ +../../Task/Dot-product/Pascal-P \ No newline at end of file diff --git a/Lang/Pascal-P/Ethiopian-multiplication b/Lang/Pascal-P/Ethiopian-multiplication new file mode 120000 index 0000000000..cf25f4fb51 --- /dev/null +++ b/Lang/Pascal-P/Ethiopian-multiplication @@ -0,0 +1 @@ +../../Task/Ethiopian-multiplication/Pascal-P \ No newline at end of file diff --git a/Lang/Pascal-P/Factors-of-an-integer b/Lang/Pascal-P/Factors-of-an-integer new file mode 120000 index 0000000000..db1f886bee --- /dev/null +++ b/Lang/Pascal-P/Factors-of-an-integer @@ -0,0 +1 @@ +../../Task/Factors-of-an-integer/Pascal-P \ No newline at end of file diff --git a/Lang/Pascal-P/FizzBuzz b/Lang/Pascal-P/FizzBuzz new file mode 120000 index 0000000000..8d0c857c1d --- /dev/null +++ b/Lang/Pascal-P/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Pascal-P \ No newline at end of file diff --git a/Lang/Pascal-P/Gamma-function b/Lang/Pascal-P/Gamma-function new file mode 120000 index 0000000000..b35d39ded3 --- /dev/null +++ b/Lang/Pascal-P/Gamma-function @@ -0,0 +1 @@ +../../Task/Gamma-function/Pascal-P \ No newline at end of file diff --git a/Lang/Pascal-P/Generate-lower-case-ASCII-alphabet b/Lang/Pascal-P/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..54db5eb4c2 --- /dev/null +++ b/Lang/Pascal-P/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Pascal-P \ No newline at end of file diff --git a/Lang/Pascal-P/Horners-rule-for-polynomial-evaluation b/Lang/Pascal-P/Horners-rule-for-polynomial-evaluation new file mode 120000 index 0000000000..1bf2158b09 --- /dev/null +++ b/Lang/Pascal-P/Horners-rule-for-polynomial-evaluation @@ -0,0 +1 @@ +../../Task/Horners-rule-for-polynomial-evaluation/Pascal-P \ No newline at end of file diff --git a/Lang/Pascal-P/Josephus-problem b/Lang/Pascal-P/Josephus-problem new file mode 120000 index 0000000000..ee86f2f03c --- /dev/null +++ b/Lang/Pascal-P/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/Pascal-P \ No newline at end of file diff --git a/Lang/Pascal-P/Leap-year b/Lang/Pascal-P/Leap-year new file mode 120000 index 0000000000..e7c0275cd7 --- /dev/null +++ b/Lang/Pascal-P/Leap-year @@ -0,0 +1 @@ +../../Task/Leap-year/Pascal-P \ No newline at end of file diff --git a/Lang/Pascal-P/Leonardo-numbers b/Lang/Pascal-P/Leonardo-numbers new file mode 120000 index 0000000000..33730eb927 --- /dev/null +++ b/Lang/Pascal-P/Leonardo-numbers @@ -0,0 +1 @@ +../../Task/Leonardo-numbers/Pascal-P \ No newline at end of file diff --git a/Lang/Pascal-P/Levenshtein-distance b/Lang/Pascal-P/Levenshtein-distance new file mode 120000 index 0000000000..369c4fda51 --- /dev/null +++ b/Lang/Pascal-P/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/Pascal-P \ No newline at end of file diff --git a/Lang/Pascal-P/Long-year b/Lang/Pascal-P/Long-year new file mode 120000 index 0000000000..4a8c200f91 --- /dev/null +++ b/Lang/Pascal-P/Long-year @@ -0,0 +1 @@ +../../Task/Long-year/Pascal-P \ No newline at end of file diff --git a/Lang/Pascal-P/M-bius-function b/Lang/Pascal-P/M-bius-function new file mode 120000 index 0000000000..5ac8d7d007 --- /dev/null +++ b/Lang/Pascal-P/M-bius-function @@ -0,0 +1 @@ +../../Task/M-bius-function/Pascal-P \ No newline at end of file diff --git a/Lang/Pascal-P/Magic-constant b/Lang/Pascal-P/Magic-constant new file mode 120000 index 0000000000..d71a46b136 --- /dev/null +++ b/Lang/Pascal-P/Magic-constant @@ -0,0 +1 @@ +../../Task/Magic-constant/Pascal-P \ No newline at end of file diff --git a/Lang/Pascal-P/Map-range b/Lang/Pascal-P/Map-range new file mode 120000 index 0000000000..ecc77d75f6 --- /dev/null +++ b/Lang/Pascal-P/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/Pascal-P \ No newline at end of file diff --git a/Lang/Pascal-P/Multifactorial b/Lang/Pascal-P/Multifactorial new file mode 120000 index 0000000000..3a5245db30 --- /dev/null +++ b/Lang/Pascal-P/Multifactorial @@ -0,0 +1 @@ +../../Task/Multifactorial/Pascal-P \ No newline at end of file diff --git a/Lang/Pascal-P/Periodic-table b/Lang/Pascal-P/Periodic-table new file mode 120000 index 0000000000..d1e817f294 --- /dev/null +++ b/Lang/Pascal-P/Periodic-table @@ -0,0 +1 @@ +../../Task/Periodic-table/Pascal-P \ No newline at end of file diff --git a/Lang/Pascal-P/Prime-decomposition b/Lang/Pascal-P/Prime-decomposition new file mode 120000 index 0000000000..b9ce930a04 --- /dev/null +++ b/Lang/Pascal-P/Prime-decomposition @@ -0,0 +1 @@ +../../Task/Prime-decomposition/Pascal-P \ No newline at end of file diff --git a/Lang/Pascal-P/Ramer-Douglas-Peucker-line-simplification b/Lang/Pascal-P/Ramer-Douglas-Peucker-line-simplification new file mode 120000 index 0000000000..41e4d1e47d --- /dev/null +++ b/Lang/Pascal-P/Ramer-Douglas-Peucker-line-simplification @@ -0,0 +1 @@ +../../Task/Ramer-Douglas-Peucker-line-simplification/Pascal-P \ No newline at end of file diff --git a/Lang/Pascal-P/Square-free-integers b/Lang/Pascal-P/Square-free-integers new file mode 120000 index 0000000000..011a7d78bb --- /dev/null +++ b/Lang/Pascal-P/Square-free-integers @@ -0,0 +1 @@ +../../Task/Square-free-integers/Pascal-P \ No newline at end of file diff --git a/Lang/Pascal-P/Tau-number b/Lang/Pascal-P/Tau-number new file mode 120000 index 0000000000..23629ebb6c --- /dev/null +++ b/Lang/Pascal-P/Tau-number @@ -0,0 +1 @@ +../../Task/Tau-number/Pascal-P \ No newline at end of file diff --git a/Lang/Pascal/Abundant-odd-numbers b/Lang/Pascal/Abundant-odd-numbers deleted file mode 120000 index b58a9a885b..0000000000 --- a/Lang/Pascal/Abundant-odd-numbers +++ /dev/null @@ -1 +0,0 @@ -../../Task/Abundant-odd-numbers/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Bell-numbers b/Lang/Pascal/Bell-numbers deleted file mode 120000 index c4ab57da43..0000000000 --- a/Lang/Pascal/Bell-numbers +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bell-numbers/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Bioinformatics-base-count b/Lang/Pascal/Bioinformatics-base-count deleted file mode 120000 index 97aaee2dbb..0000000000 --- a/Lang/Pascal/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Brazilian-numbers b/Lang/Pascal/Brazilian-numbers deleted file mode 120000 index 152f3a22d2..0000000000 --- a/Lang/Pascal/Brazilian-numbers +++ /dev/null @@ -1 +0,0 @@ -../../Task/Brazilian-numbers/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Count-the-coins b/Lang/Pascal/Count-the-coins new file mode 120000 index 0000000000..8d7999b667 --- /dev/null +++ b/Lang/Pascal/Count-the-coins @@ -0,0 +1 @@ +../../Task/Count-the-coins/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Date-manipulation b/Lang/Pascal/Date-manipulation new file mode 120000 index 0000000000..9edece533b --- /dev/null +++ b/Lang/Pascal/Date-manipulation @@ -0,0 +1 @@ +../../Task/Date-manipulation/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Ethiopian-multiplication b/Lang/Pascal/Ethiopian-multiplication deleted file mode 120000 index 53e5b905d2..0000000000 --- a/Lang/Pascal/Ethiopian-multiplication +++ /dev/null @@ -1 +0,0 @@ -../../Task/Ethiopian-multiplication/Pascal \ No newline at end of file diff --git a/Lang/Pascal/FizzBuzz b/Lang/Pascal/FizzBuzz deleted file mode 120000 index 786dae3647..0000000000 --- a/Lang/Pascal/FizzBuzz +++ /dev/null @@ -1 +0,0 @@ -../../Task/FizzBuzz/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Gamma-function b/Lang/Pascal/Gamma-function deleted file mode 120000 index f83dad18cb..0000000000 --- a/Lang/Pascal/Gamma-function +++ /dev/null @@ -1 +0,0 @@ -../../Task/Gamma-function/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Leap-year b/Lang/Pascal/Leap-year deleted file mode 120000 index 5eb674ed97..0000000000 --- a/Lang/Pascal/Leap-year +++ /dev/null @@ -1 +0,0 @@ -../../Task/Leap-year/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Levenshtein-distance b/Lang/Pascal/Levenshtein-distance deleted file mode 120000 index aa9f13dc0f..0000000000 --- a/Lang/Pascal/Levenshtein-distance +++ /dev/null @@ -1 +0,0 @@ -../../Task/Levenshtein-distance/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Map-range b/Lang/Pascal/Map-range deleted file mode 120000 index 71c05c40ec..0000000000 --- a/Lang/Pascal/Map-range +++ /dev/null @@ -1 +0,0 @@ -../../Task/Map-range/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Prime-decomposition b/Lang/Pascal/Prime-decomposition deleted file mode 120000 index 7b392e005f..0000000000 --- a/Lang/Pascal/Prime-decomposition +++ /dev/null @@ -1 +0,0 @@ -../../Task/Prime-decomposition/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Sorting-Algorithms-Circle-Sort b/Lang/Pascal/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 3100a6716d..0000000000 --- a/Lang/Pascal/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Square-free-integers b/Lang/Pascal/Square-free-integers deleted file mode 120000 index 874a24625c..0000000000 --- a/Lang/Pascal/Square-free-integers +++ /dev/null @@ -1 +0,0 @@ -../../Task/Square-free-integers/Pascal \ No newline at end of file diff --git a/Lang/PascalABC.NET/00-LANG.txt b/Lang/PascalABC.NET/00-LANG.txt index d9efe4d43e..7f652b8be9 100644 --- a/Lang/PascalABC.NET/00-LANG.txt +++ b/Lang/PascalABC.NET/00-LANG.txt @@ -1,4 +1,4 @@ -{{language|PascalABC.NET}} +{{language|site=https://pascalabc.net/en/}} {{implementation|Pascal}} PascalABC.NET is the new generation Pascal programming language that combines simplicity of classic Pascal, a great number of modern extensions and broad capabilities of Microsoft .NET Framework. @@ -16,4 +16,5 @@ begin end. -{{unimpl_Page|PacalABC.NET}} \ No newline at end of file +==Tasks not implemented in PascalABC.NET== +[[Tasks not implemented in PascalABC.NET]] \ No newline at end of file diff --git a/Lang/PascalABC.NET/100-doors b/Lang/PascalABC.NET/100-doors deleted file mode 120000 index ba816799a0..0000000000 --- a/Lang/PascalABC.NET/100-doors +++ /dev/null @@ -1 +0,0 @@ -../../Task/100-doors/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/15-puzzle-game b/Lang/PascalABC.NET/15-puzzle-game new file mode 120000 index 0000000000..caf890e56b --- /dev/null +++ b/Lang/PascalABC.NET/15-puzzle-game @@ -0,0 +1 @@ +../../Task/15-puzzle-game/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/15-puzzle-solver b/Lang/PascalABC.NET/15-puzzle-solver new file mode 120000 index 0000000000..73063f2237 --- /dev/null +++ b/Lang/PascalABC.NET/15-puzzle-solver @@ -0,0 +1 @@ +../../Task/15-puzzle-solver/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/99-bottles-of-beer b/Lang/PascalABC.NET/99-bottles-of-beer new file mode 120000 index 0000000000..bc29442ab5 --- /dev/null +++ b/Lang/PascalABC.NET/99-bottles-of-beer @@ -0,0 +1 @@ +../../Task/99-bottles-of-beer/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/A+B b/Lang/PascalABC.NET/A+B new file mode 120000 index 0000000000..7a5a9db498 --- /dev/null +++ b/Lang/PascalABC.NET/A+B @@ -0,0 +1 @@ +../../Task/A+B/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Abbreviations-easy b/Lang/PascalABC.NET/Abbreviations-easy new file mode 120000 index 0000000000..ea782fa0b0 --- /dev/null +++ b/Lang/PascalABC.NET/Abbreviations-easy @@ -0,0 +1 @@ +../../Task/Abbreviations-easy/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Abbreviations-simple b/Lang/PascalABC.NET/Abbreviations-simple new file mode 120000 index 0000000000..abc650feac --- /dev/null +++ b/Lang/PascalABC.NET/Abbreviations-simple @@ -0,0 +1 @@ +../../Task/Abbreviations-simple/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Abstract-type b/Lang/PascalABC.NET/Abstract-type new file mode 120000 index 0000000000..305270825e --- /dev/null +++ b/Lang/PascalABC.NET/Abstract-type @@ -0,0 +1 @@ +../../Task/Abstract-type/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Accumulator-factory b/Lang/PascalABC.NET/Accumulator-factory new file mode 120000 index 0000000000..dd94a031d6 --- /dev/null +++ b/Lang/PascalABC.NET/Accumulator-factory @@ -0,0 +1 @@ +../../Task/Accumulator-factory/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Ackermann-function b/Lang/PascalABC.NET/Ackermann-function new file mode 120000 index 0000000000..c2fa2dd278 --- /dev/null +++ b/Lang/PascalABC.NET/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Add-a-variable-to-a-class-instance-at-runtime b/Lang/PascalABC.NET/Add-a-variable-to-a-class-instance-at-runtime new file mode 120000 index 0000000000..ec0970f459 --- /dev/null +++ b/Lang/PascalABC.NET/Add-a-variable-to-a-class-instance-at-runtime @@ -0,0 +1 @@ +../../Task/Add-a-variable-to-a-class-instance-at-runtime/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Additive-primes b/Lang/PascalABC.NET/Additive-primes new file mode 120000 index 0000000000..0022732e2e --- /dev/null +++ b/Lang/PascalABC.NET/Additive-primes @@ -0,0 +1 @@ +../../Task/Additive-primes/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Address-of-a-variable b/Lang/PascalABC.NET/Address-of-a-variable new file mode 120000 index 0000000000..8477592c7b --- /dev/null +++ b/Lang/PascalABC.NET/Address-of-a-variable @@ -0,0 +1 @@ +../../Task/Address-of-a-variable/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Amicable-pairs b/Lang/PascalABC.NET/Amicable-pairs new file mode 120000 index 0000000000..e8f5a09925 --- /dev/null +++ b/Lang/PascalABC.NET/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Anagrams b/Lang/PascalABC.NET/Anagrams new file mode 120000 index 0000000000..2bec53abb4 --- /dev/null +++ b/Lang/PascalABC.NET/Anagrams @@ -0,0 +1 @@ +../../Task/Anagrams/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Angle-difference-between-two-bearings b/Lang/PascalABC.NET/Angle-difference-between-two-bearings new file mode 120000 index 0000000000..a9e8619c23 --- /dev/null +++ b/Lang/PascalABC.NET/Angle-difference-between-two-bearings @@ -0,0 +1 @@ +../../Task/Angle-difference-between-two-bearings/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Angles-geometric-normalization-and-conversion b/Lang/PascalABC.NET/Angles-geometric-normalization-and-conversion new file mode 120000 index 0000000000..27c57b8ea0 --- /dev/null +++ b/Lang/PascalABC.NET/Angles-geometric-normalization-and-conversion @@ -0,0 +1 @@ +../../Task/Angles-geometric-normalization-and-conversion/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Anonymous-recursion b/Lang/PascalABC.NET/Anonymous-recursion new file mode 120000 index 0000000000..7a2a34d4d5 --- /dev/null +++ b/Lang/PascalABC.NET/Anonymous-recursion @@ -0,0 +1 @@ +../../Task/Anonymous-recursion/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Anti-primes b/Lang/PascalABC.NET/Anti-primes new file mode 120000 index 0000000000..0107c4a2bb --- /dev/null +++ b/Lang/PascalABC.NET/Anti-primes @@ -0,0 +1 @@ +../../Task/Anti-primes/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Apply-a-callback-to-an-array b/Lang/PascalABC.NET/Apply-a-callback-to-an-array new file mode 120000 index 0000000000..88f34b5a9e --- /dev/null +++ b/Lang/PascalABC.NET/Apply-a-callback-to-an-array @@ -0,0 +1 @@ +../../Task/Apply-a-callback-to-an-array/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Approximate-equality b/Lang/PascalABC.NET/Approximate-equality new file mode 120000 index 0000000000..9d80191945 --- /dev/null +++ b/Lang/PascalABC.NET/Approximate-equality @@ -0,0 +1 @@ +../../Task/Approximate-equality/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Arbitrary-precision-integers-included- b/Lang/PascalABC.NET/Arbitrary-precision-integers-included- new file mode 120000 index 0000000000..8e9998f39e --- /dev/null +++ b/Lang/PascalABC.NET/Arbitrary-precision-integers-included- @@ -0,0 +1 @@ +../../Task/Arbitrary-precision-integers-included-/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Archimedean-spiral b/Lang/PascalABC.NET/Archimedean-spiral new file mode 120000 index 0000000000..8c791b5144 --- /dev/null +++ b/Lang/PascalABC.NET/Archimedean-spiral @@ -0,0 +1 @@ +../../Task/Archimedean-spiral/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Arithmetic-Complex b/Lang/PascalABC.NET/Arithmetic-Complex new file mode 120000 index 0000000000..bccd03a873 --- /dev/null +++ b/Lang/PascalABC.NET/Arithmetic-Complex @@ -0,0 +1 @@ +../../Task/Arithmetic-Complex/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Arithmetic-Integer b/Lang/PascalABC.NET/Arithmetic-Integer new file mode 120000 index 0000000000..30d5138cbd --- /dev/null +++ b/Lang/PascalABC.NET/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Arithmetic-Rational b/Lang/PascalABC.NET/Arithmetic-Rational new file mode 120000 index 0000000000..e1c3c085b7 --- /dev/null +++ b/Lang/PascalABC.NET/Arithmetic-Rational @@ -0,0 +1 @@ +../../Task/Arithmetic-Rational/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Arithmetic-evaluation b/Lang/PascalABC.NET/Arithmetic-evaluation new file mode 120000 index 0000000000..816270d1cc --- /dev/null +++ b/Lang/PascalABC.NET/Arithmetic-evaluation @@ -0,0 +1 @@ +../../Task/Arithmetic-evaluation/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Arithmetic-geometric-mean b/Lang/PascalABC.NET/Arithmetic-geometric-mean new file mode 120000 index 0000000000..de68d8badc --- /dev/null +++ b/Lang/PascalABC.NET/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Arithmetic-numbers b/Lang/PascalABC.NET/Arithmetic-numbers new file mode 120000 index 0000000000..91fbd5c07a --- /dev/null +++ b/Lang/PascalABC.NET/Arithmetic-numbers @@ -0,0 +1 @@ +../../Task/Arithmetic-numbers/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Array-concatenation b/Lang/PascalABC.NET/Array-concatenation new file mode 120000 index 0000000000..bfe26798bc --- /dev/null +++ b/Lang/PascalABC.NET/Array-concatenation @@ -0,0 +1 @@ +../../Task/Array-concatenation/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Arrays b/Lang/PascalABC.NET/Arrays new file mode 120000 index 0000000000..62dfb07030 --- /dev/null +++ b/Lang/PascalABC.NET/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Ascending-primes b/Lang/PascalABC.NET/Ascending-primes new file mode 120000 index 0000000000..764168a0be --- /dev/null +++ b/Lang/PascalABC.NET/Ascending-primes @@ -0,0 +1 @@ +../../Task/Ascending-primes/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Assertions b/Lang/PascalABC.NET/Assertions new file mode 120000 index 0000000000..bdc3ed57c2 --- /dev/null +++ b/Lang/PascalABC.NET/Assertions @@ -0,0 +1 @@ +../../Task/Assertions/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Associative-array-Creation b/Lang/PascalABC.NET/Associative-array-Creation new file mode 120000 index 0000000000..fc1bef5cdb --- /dev/null +++ b/Lang/PascalABC.NET/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Associative-array-Iteration b/Lang/PascalABC.NET/Associative-array-Iteration new file mode 120000 index 0000000000..2f1ab21d84 --- /dev/null +++ b/Lang/PascalABC.NET/Associative-array-Iteration @@ -0,0 +1 @@ +../../Task/Associative-array-Iteration/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Associative-array-Merging b/Lang/PascalABC.NET/Associative-array-Merging new file mode 120000 index 0000000000..debbdc2521 --- /dev/null +++ b/Lang/PascalABC.NET/Associative-array-Merging @@ -0,0 +1 @@ +../../Task/Associative-array-Merging/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Attractive-numbers b/Lang/PascalABC.NET/Attractive-numbers new file mode 120000 index 0000000000..974a121495 --- /dev/null +++ b/Lang/PascalABC.NET/Attractive-numbers @@ -0,0 +1 @@ +../../Task/Attractive-numbers/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Averages-Arithmetic-mean b/Lang/PascalABC.NET/Averages-Arithmetic-mean new file mode 120000 index 0000000000..c13a81b3d2 --- /dev/null +++ b/Lang/PascalABC.NET/Averages-Arithmetic-mean @@ -0,0 +1 @@ +../../Task/Averages-Arithmetic-mean/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Averages-Mean-angle b/Lang/PascalABC.NET/Averages-Mean-angle new file mode 120000 index 0000000000..1138410560 --- /dev/null +++ b/Lang/PascalABC.NET/Averages-Mean-angle @@ -0,0 +1 @@ +../../Task/Averages-Mean-angle/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Averages-Median b/Lang/PascalABC.NET/Averages-Median new file mode 120000 index 0000000000..3e861f57c5 --- /dev/null +++ b/Lang/PascalABC.NET/Averages-Median @@ -0,0 +1 @@ +../../Task/Averages-Median/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Averages-Mode b/Lang/PascalABC.NET/Averages-Mode new file mode 120000 index 0000000000..73a256bfd8 --- /dev/null +++ b/Lang/PascalABC.NET/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Averages-Pythagorean-means b/Lang/PascalABC.NET/Averages-Pythagorean-means new file mode 120000 index 0000000000..d41041c28e --- /dev/null +++ b/Lang/PascalABC.NET/Averages-Pythagorean-means @@ -0,0 +1 @@ +../../Task/Averages-Pythagorean-means/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Averages-Root-mean-square b/Lang/PascalABC.NET/Averages-Root-mean-square new file mode 120000 index 0000000000..fcd93926c8 --- /dev/null +++ b/Lang/PascalABC.NET/Averages-Root-mean-square @@ -0,0 +1 @@ +../../Task/Averages-Root-mean-square/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Babbage-problem b/Lang/PascalABC.NET/Babbage-problem new file mode 120000 index 0000000000..0c9b0d20ea --- /dev/null +++ b/Lang/PascalABC.NET/Babbage-problem @@ -0,0 +1 @@ +../../Task/Babbage-problem/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Balanced-brackets b/Lang/PascalABC.NET/Balanced-brackets new file mode 120000 index 0000000000..4b5678c4d8 --- /dev/null +++ b/Lang/PascalABC.NET/Balanced-brackets @@ -0,0 +1 @@ +../../Task/Balanced-brackets/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Bifid-cipher b/Lang/PascalABC.NET/Bifid-cipher new file mode 120000 index 0000000000..b627ea6e1a --- /dev/null +++ b/Lang/PascalABC.NET/Bifid-cipher @@ -0,0 +1 @@ +../../Task/Bifid-cipher/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Binary-digits b/Lang/PascalABC.NET/Binary-digits new file mode 120000 index 0000000000..e0597a5dc1 --- /dev/null +++ b/Lang/PascalABC.NET/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Binary-search b/Lang/PascalABC.NET/Binary-search new file mode 120000 index 0000000000..aa5ba91c87 --- /dev/null +++ b/Lang/PascalABC.NET/Binary-search @@ -0,0 +1 @@ +../../Task/Binary-search/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Bitwise-operations b/Lang/PascalABC.NET/Bitwise-operations new file mode 120000 index 0000000000..acc6123f1c --- /dev/null +++ b/Lang/PascalABC.NET/Bitwise-operations @@ -0,0 +1 @@ +../../Task/Bitwise-operations/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Break-OO-privacy b/Lang/PascalABC.NET/Break-OO-privacy new file mode 120000 index 0000000000..29ee336925 --- /dev/null +++ b/Lang/PascalABC.NET/Break-OO-privacy @@ -0,0 +1 @@ +../../Task/Break-OO-privacy/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/CRC-32 b/Lang/PascalABC.NET/CRC-32 new file mode 120000 index 0000000000..dfed202f62 --- /dev/null +++ b/Lang/PascalABC.NET/CRC-32 @@ -0,0 +1 @@ +../../Task/CRC-32/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/CSV-data-manipulation b/Lang/PascalABC.NET/CSV-data-manipulation new file mode 120000 index 0000000000..ab9f191d41 --- /dev/null +++ b/Lang/PascalABC.NET/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/CUSIP b/Lang/PascalABC.NET/CUSIP new file mode 120000 index 0000000000..1b4c6de901 --- /dev/null +++ b/Lang/PascalABC.NET/CUSIP @@ -0,0 +1 @@ +../../Task/CUSIP/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Caesar-cipher b/Lang/PascalABC.NET/Caesar-cipher new file mode 120000 index 0000000000..7b80169afb --- /dev/null +++ b/Lang/PascalABC.NET/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Calculating-the-value-of-e b/Lang/PascalABC.NET/Calculating-the-value-of-e new file mode 120000 index 0000000000..c544f3c00f --- /dev/null +++ b/Lang/PascalABC.NET/Calculating-the-value-of-e @@ -0,0 +1 @@ +../../Task/Calculating-the-value-of-e/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Calendar---for-REAL-programmers b/Lang/PascalABC.NET/Calendar---for-REAL-programmers new file mode 120000 index 0000000000..aa32b573de --- /dev/null +++ b/Lang/PascalABC.NET/Calendar---for-REAL-programmers @@ -0,0 +1 @@ +../../Task/Calendar---for-REAL-programmers/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Call-an-object-method b/Lang/PascalABC.NET/Call-an-object-method new file mode 120000 index 0000000000..0c1cf230d7 --- /dev/null +++ b/Lang/PascalABC.NET/Call-an-object-method @@ -0,0 +1 @@ +../../Task/Call-an-object-method/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Cartesian-product-of-two-or-more-lists b/Lang/PascalABC.NET/Cartesian-product-of-two-or-more-lists new file mode 120000 index 0000000000..e9abacde8d --- /dev/null +++ b/Lang/PascalABC.NET/Cartesian-product-of-two-or-more-lists @@ -0,0 +1 @@ +../../Task/Cartesian-product-of-two-or-more-lists/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Case-sensitivity-of-identifiers b/Lang/PascalABC.NET/Case-sensitivity-of-identifiers new file mode 120000 index 0000000000..b0fc4ead7c --- /dev/null +++ b/Lang/PascalABC.NET/Case-sensitivity-of-identifiers @@ -0,0 +1 @@ +../../Task/Case-sensitivity-of-identifiers/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Casting-out-nines b/Lang/PascalABC.NET/Casting-out-nines new file mode 120000 index 0000000000..2635cd3c59 --- /dev/null +++ b/Lang/PascalABC.NET/Casting-out-nines @@ -0,0 +1 @@ +../../Task/Casting-out-nines/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Catalan-numbers b/Lang/PascalABC.NET/Catalan-numbers new file mode 120000 index 0000000000..a970e535cd --- /dev/null +++ b/Lang/PascalABC.NET/Catalan-numbers @@ -0,0 +1 @@ +../../Task/Catalan-numbers/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Catalan-numbers-Pascals-triangle b/Lang/PascalABC.NET/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..47a30d7f38 --- /dev/null +++ b/Lang/PascalABC.NET/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Catamorphism b/Lang/PascalABC.NET/Catamorphism new file mode 120000 index 0000000000..4cd74052dd --- /dev/null +++ b/Lang/PascalABC.NET/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Character-codes b/Lang/PascalABC.NET/Character-codes new file mode 120000 index 0000000000..1888f78c06 --- /dev/null +++ b/Lang/PascalABC.NET/Character-codes @@ -0,0 +1 @@ +../../Task/Character-codes/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Check-input-device-is-a-terminal b/Lang/PascalABC.NET/Check-input-device-is-a-terminal new file mode 120000 index 0000000000..942e91ecc8 --- /dev/null +++ b/Lang/PascalABC.NET/Check-input-device-is-a-terminal @@ -0,0 +1 @@ +../../Task/Check-input-device-is-a-terminal/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Check-output-device-is-a-terminal b/Lang/PascalABC.NET/Check-output-device-is-a-terminal new file mode 120000 index 0000000000..ddcd688824 --- /dev/null +++ b/Lang/PascalABC.NET/Check-output-device-is-a-terminal @@ -0,0 +1 @@ +../../Task/Check-output-device-is-a-terminal/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Check-that-file-exists b/Lang/PascalABC.NET/Check-that-file-exists new file mode 120000 index 0000000000..8a6772fd4b --- /dev/null +++ b/Lang/PascalABC.NET/Check-that-file-exists @@ -0,0 +1 @@ +../../Task/Check-that-file-exists/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Cheryls-birthday b/Lang/PascalABC.NET/Cheryls-birthday new file mode 120000 index 0000000000..a54346abfd --- /dev/null +++ b/Lang/PascalABC.NET/Cheryls-birthday @@ -0,0 +1 @@ +../../Task/Cheryls-birthday/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Chinese-remainder-theorem b/Lang/PascalABC.NET/Chinese-remainder-theorem new file mode 120000 index 0000000000..72e58e3a4a --- /dev/null +++ b/Lang/PascalABC.NET/Chinese-remainder-theorem @@ -0,0 +1 @@ +../../Task/Chinese-remainder-theorem/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Chinese-zodiac b/Lang/PascalABC.NET/Chinese-zodiac new file mode 120000 index 0000000000..f7393d9042 --- /dev/null +++ b/Lang/PascalABC.NET/Chinese-zodiac @@ -0,0 +1 @@ +../../Task/Chinese-zodiac/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Cholesky-decomposition b/Lang/PascalABC.NET/Cholesky-decomposition new file mode 120000 index 0000000000..35182d3cfc --- /dev/null +++ b/Lang/PascalABC.NET/Cholesky-decomposition @@ -0,0 +1 @@ +../../Task/Cholesky-decomposition/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Chowla-numbers b/Lang/PascalABC.NET/Chowla-numbers new file mode 120000 index 0000000000..556f1a6dfd --- /dev/null +++ b/Lang/PascalABC.NET/Chowla-numbers @@ -0,0 +1 @@ +../../Task/Chowla-numbers/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Circular-primes b/Lang/PascalABC.NET/Circular-primes new file mode 120000 index 0000000000..5224e07ad0 --- /dev/null +++ b/Lang/PascalABC.NET/Circular-primes @@ -0,0 +1 @@ +../../Task/Circular-primes/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Classes b/Lang/PascalABC.NET/Classes new file mode 120000 index 0000000000..08756ef03a --- /dev/null +++ b/Lang/PascalABC.NET/Classes @@ -0,0 +1 @@ +../../Task/Classes/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Closest-pair-problem b/Lang/PascalABC.NET/Closest-pair-problem new file mode 120000 index 0000000000..4b7bc32806 --- /dev/null +++ b/Lang/PascalABC.NET/Closest-pair-problem @@ -0,0 +1 @@ +../../Task/Closest-pair-problem/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Closures-Value-capture b/Lang/PascalABC.NET/Closures-Value-capture new file mode 120000 index 0000000000..428138cdfe --- /dev/null +++ b/Lang/PascalABC.NET/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Collections b/Lang/PascalABC.NET/Collections new file mode 120000 index 0000000000..c3fa3dc417 --- /dev/null +++ b/Lang/PascalABC.NET/Collections @@ -0,0 +1 @@ +../../Task/Collections/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Color-of-a-screen-pixel b/Lang/PascalABC.NET/Color-of-a-screen-pixel new file mode 120000 index 0000000000..45582746a3 --- /dev/null +++ b/Lang/PascalABC.NET/Color-of-a-screen-pixel @@ -0,0 +1 @@ +../../Task/Color-of-a-screen-pixel/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Color-wheel b/Lang/PascalABC.NET/Color-wheel new file mode 120000 index 0000000000..ea27bb369f --- /dev/null +++ b/Lang/PascalABC.NET/Color-wheel @@ -0,0 +1 @@ +../../Task/Color-wheel/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Colour-bars-Display b/Lang/PascalABC.NET/Colour-bars-Display new file mode 120000 index 0000000000..e504c543a7 --- /dev/null +++ b/Lang/PascalABC.NET/Colour-bars-Display @@ -0,0 +1 @@ +../../Task/Colour-bars-Display/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Colour-pinstripe-Display b/Lang/PascalABC.NET/Colour-pinstripe-Display new file mode 120000 index 0000000000..c9febd7d37 --- /dev/null +++ b/Lang/PascalABC.NET/Colour-pinstripe-Display @@ -0,0 +1 @@ +../../Task/Colour-pinstripe-Display/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Combinations b/Lang/PascalABC.NET/Combinations new file mode 120000 index 0000000000..fad981495d --- /dev/null +++ b/Lang/PascalABC.NET/Combinations @@ -0,0 +1 @@ +../../Task/Combinations/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Combinations-with-repetitions b/Lang/PascalABC.NET/Combinations-with-repetitions new file mode 120000 index 0000000000..f75050c914 --- /dev/null +++ b/Lang/PascalABC.NET/Combinations-with-repetitions @@ -0,0 +1 @@ +../../Task/Combinations-with-repetitions/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Command-line-arguments b/Lang/PascalABC.NET/Command-line-arguments new file mode 120000 index 0000000000..f229191025 --- /dev/null +++ b/Lang/PascalABC.NET/Command-line-arguments @@ -0,0 +1 @@ +../../Task/Command-line-arguments/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Comments b/Lang/PascalABC.NET/Comments new file mode 120000 index 0000000000..5e528e6991 --- /dev/null +++ b/Lang/PascalABC.NET/Comments @@ -0,0 +1 @@ +../../Task/Comments/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Compare-a-list-of-strings b/Lang/PascalABC.NET/Compare-a-list-of-strings new file mode 120000 index 0000000000..b8b040023f --- /dev/null +++ b/Lang/PascalABC.NET/Compare-a-list-of-strings @@ -0,0 +1 @@ +../../Task/Compare-a-list-of-strings/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Compare-length-of-two-strings b/Lang/PascalABC.NET/Compare-length-of-two-strings new file mode 120000 index 0000000000..92be62a3df --- /dev/null +++ b/Lang/PascalABC.NET/Compare-length-of-two-strings @@ -0,0 +1 @@ +../../Task/Compare-length-of-two-strings/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Compile-time-calculation b/Lang/PascalABC.NET/Compile-time-calculation new file mode 120000 index 0000000000..aa6140bdc4 --- /dev/null +++ b/Lang/PascalABC.NET/Compile-time-calculation @@ -0,0 +1 @@ +../../Task/Compile-time-calculation/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k b/Lang/PascalABC.NET/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k new file mode 120000 index 0000000000..54d237d7ab --- /dev/null +++ b/Lang/PascalABC.NET/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/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Compound-data-type b/Lang/PascalABC.NET/Compound-data-type new file mode 120000 index 0000000000..89ad664595 --- /dev/null +++ b/Lang/PascalABC.NET/Compound-data-type @@ -0,0 +1 @@ +../../Task/Compound-data-type/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Concurrent-computing b/Lang/PascalABC.NET/Concurrent-computing new file mode 120000 index 0000000000..ced9fcccc5 --- /dev/null +++ b/Lang/PascalABC.NET/Concurrent-computing @@ -0,0 +1 @@ +../../Task/Concurrent-computing/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Conditional-structures b/Lang/PascalABC.NET/Conditional-structures new file mode 120000 index 0000000000..6186fdd1f8 --- /dev/null +++ b/Lang/PascalABC.NET/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Constrained-genericity b/Lang/PascalABC.NET/Constrained-genericity new file mode 120000 index 0000000000..4d89cf348d --- /dev/null +++ b/Lang/PascalABC.NET/Constrained-genericity @@ -0,0 +1 @@ +../../Task/Constrained-genericity/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Constrained-random-points-on-a-circle b/Lang/PascalABC.NET/Constrained-random-points-on-a-circle new file mode 120000 index 0000000000..5d3f518fc9 --- /dev/null +++ b/Lang/PascalABC.NET/Constrained-random-points-on-a-circle @@ -0,0 +1 @@ +../../Task/Constrained-random-points-on-a-circle/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Continued-fraction b/Lang/PascalABC.NET/Continued-fraction new file mode 120000 index 0000000000..f6f45a7af5 --- /dev/null +++ b/Lang/PascalABC.NET/Continued-fraction @@ -0,0 +1 @@ +../../Task/Continued-fraction/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Continued-fraction-Arithmetic-Construct-from-rational-number b/Lang/PascalABC.NET/Continued-fraction-Arithmetic-Construct-from-rational-number new file mode 120000 index 0000000000..2bab87463d --- /dev/null +++ b/Lang/PascalABC.NET/Continued-fraction-Arithmetic-Construct-from-rational-number @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-Construct-from-rational-number/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Convert-decimal-number-to-rational b/Lang/PascalABC.NET/Convert-decimal-number-to-rational new file mode 120000 index 0000000000..7827892fb4 --- /dev/null +++ b/Lang/PascalABC.NET/Convert-decimal-number-to-rational @@ -0,0 +1 @@ +../../Task/Convert-decimal-number-to-rational/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Copy-a-string b/Lang/PascalABC.NET/Copy-a-string new file mode 120000 index 0000000000..d102da9b43 --- /dev/null +++ b/Lang/PascalABC.NET/Copy-a-string @@ -0,0 +1 @@ +../../Task/Copy-a-string/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Copy-stdin-to-stdout b/Lang/PascalABC.NET/Copy-stdin-to-stdout new file mode 120000 index 0000000000..08f7b00296 --- /dev/null +++ b/Lang/PascalABC.NET/Copy-stdin-to-stdout @@ -0,0 +1 @@ +../../Task/Copy-stdin-to-stdout/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Count-in-factors b/Lang/PascalABC.NET/Count-in-factors new file mode 120000 index 0000000000..42811aa9aa --- /dev/null +++ b/Lang/PascalABC.NET/Count-in-factors @@ -0,0 +1 @@ +../../Task/Count-in-factors/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Count-in-octal b/Lang/PascalABC.NET/Count-in-octal new file mode 120000 index 0000000000..8965e8c25f --- /dev/null +++ b/Lang/PascalABC.NET/Count-in-octal @@ -0,0 +1 @@ +../../Task/Count-in-octal/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Count-occurrences-of-a-substring b/Lang/PascalABC.NET/Count-occurrences-of-a-substring new file mode 120000 index 0000000000..d67adab506 --- /dev/null +++ b/Lang/PascalABC.NET/Count-occurrences-of-a-substring @@ -0,0 +1 @@ +../../Task/Count-occurrences-of-a-substring/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Count-the-coins b/Lang/PascalABC.NET/Count-the-coins new file mode 120000 index 0000000000..43a4fdb837 --- /dev/null +++ b/Lang/PascalABC.NET/Count-the-coins @@ -0,0 +1 @@ +../../Task/Count-the-coins/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Create-a-file b/Lang/PascalABC.NET/Create-a-file new file mode 120000 index 0000000000..5f3fa97f14 --- /dev/null +++ b/Lang/PascalABC.NET/Create-a-file @@ -0,0 +1 @@ +../../Task/Create-a-file/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Create-a-two-dimensional-array-at-runtime b/Lang/PascalABC.NET/Create-a-two-dimensional-array-at-runtime new file mode 120000 index 0000000000..2c7befc65f --- /dev/null +++ b/Lang/PascalABC.NET/Create-a-two-dimensional-array-at-runtime @@ -0,0 +1 @@ +../../Task/Create-a-two-dimensional-array-at-runtime/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Create-an-object-at-a-given-address b/Lang/PascalABC.NET/Create-an-object-at-a-given-address new file mode 120000 index 0000000000..aa2e5f2ab2 --- /dev/null +++ b/Lang/PascalABC.NET/Create-an-object-at-a-given-address @@ -0,0 +1 @@ +../../Task/Create-an-object-at-a-given-address/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Cuban-primes b/Lang/PascalABC.NET/Cuban-primes new file mode 120000 index 0000000000..844ac15cb4 --- /dev/null +++ b/Lang/PascalABC.NET/Cuban-primes @@ -0,0 +1 @@ +../../Task/Cuban-primes/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Cullen-and-Woodall-numbers b/Lang/PascalABC.NET/Cullen-and-Woodall-numbers new file mode 120000 index 0000000000..714083d23b --- /dev/null +++ b/Lang/PascalABC.NET/Cullen-and-Woodall-numbers @@ -0,0 +1 @@ +../../Task/Cullen-and-Woodall-numbers/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Cumulative-standard-deviation b/Lang/PascalABC.NET/Cumulative-standard-deviation new file mode 120000 index 0000000000..b6ef0ab016 --- /dev/null +++ b/Lang/PascalABC.NET/Cumulative-standard-deviation @@ -0,0 +1 @@ +../../Task/Cumulative-standard-deviation/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Currency b/Lang/PascalABC.NET/Currency new file mode 120000 index 0000000000..2017d69d57 --- /dev/null +++ b/Lang/PascalABC.NET/Currency @@ -0,0 +1 @@ +../../Task/Currency/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Curzon-numbers b/Lang/PascalABC.NET/Curzon-numbers new file mode 120000 index 0000000000..13437cd157 --- /dev/null +++ b/Lang/PascalABC.NET/Curzon-numbers @@ -0,0 +1 @@ +../../Task/Curzon-numbers/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/DNS-query b/Lang/PascalABC.NET/DNS-query new file mode 120000 index 0000000000..52bda8e0aa --- /dev/null +++ b/Lang/PascalABC.NET/DNS-query @@ -0,0 +1 @@ +../../Task/DNS-query/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Damm-algorithm b/Lang/PascalABC.NET/Damm-algorithm new file mode 120000 index 0000000000..6fee5b0ddc --- /dev/null +++ b/Lang/PascalABC.NET/Damm-algorithm @@ -0,0 +1 @@ +../../Task/Damm-algorithm/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Date-format b/Lang/PascalABC.NET/Date-format new file mode 120000 index 0000000000..176b256586 --- /dev/null +++ b/Lang/PascalABC.NET/Date-format @@ -0,0 +1 @@ +../../Task/Date-format/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Day-of-the-week b/Lang/PascalABC.NET/Day-of-the-week new file mode 120000 index 0000000000..3300b037b4 --- /dev/null +++ b/Lang/PascalABC.NET/Day-of-the-week @@ -0,0 +1 @@ +../../Task/Day-of-the-week/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Deceptive-numbers b/Lang/PascalABC.NET/Deceptive-numbers new file mode 120000 index 0000000000..007d2d649c --- /dev/null +++ b/Lang/PascalABC.NET/Deceptive-numbers @@ -0,0 +1 @@ +../../Task/Deceptive-numbers/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Deconvolution-1D b/Lang/PascalABC.NET/Deconvolution-1D new file mode 120000 index 0000000000..9604235c77 --- /dev/null +++ b/Lang/PascalABC.NET/Deconvolution-1D @@ -0,0 +1 @@ +../../Task/Deconvolution-1D/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Define-a-primitive-data-type b/Lang/PascalABC.NET/Define-a-primitive-data-type new file mode 120000 index 0000000000..684571f697 --- /dev/null +++ b/Lang/PascalABC.NET/Define-a-primitive-data-type @@ -0,0 +1 @@ +../../Task/Define-a-primitive-data-type/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Demings-funnel b/Lang/PascalABC.NET/Demings-funnel new file mode 120000 index 0000000000..0255de8e51 --- /dev/null +++ b/Lang/PascalABC.NET/Demings-funnel @@ -0,0 +1 @@ +../../Task/Demings-funnel/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Department-numbers b/Lang/PascalABC.NET/Department-numbers new file mode 120000 index 0000000000..1b068d9b34 --- /dev/null +++ b/Lang/PascalABC.NET/Department-numbers @@ -0,0 +1 @@ +../../Task/Department-numbers/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Descending-primes b/Lang/PascalABC.NET/Descending-primes new file mode 120000 index 0000000000..5641c47c94 --- /dev/null +++ b/Lang/PascalABC.NET/Descending-primes @@ -0,0 +1 @@ +../../Task/Descending-primes/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Detect-division-by-zero b/Lang/PascalABC.NET/Detect-division-by-zero new file mode 120000 index 0000000000..a843cd631e --- /dev/null +++ b/Lang/PascalABC.NET/Detect-division-by-zero @@ -0,0 +1 @@ +../../Task/Detect-division-by-zero/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Determine-if-a-string-has-all-the-same-characters b/Lang/PascalABC.NET/Determine-if-a-string-has-all-the-same-characters new file mode 120000 index 0000000000..bb838a1f25 --- /dev/null +++ b/Lang/PascalABC.NET/Determine-if-a-string-has-all-the-same-characters @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-has-all-the-same-characters/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Determine-if-a-string-has-all-unique-characters b/Lang/PascalABC.NET/Determine-if-a-string-has-all-unique-characters new file mode 120000 index 0000000000..7c66082879 --- /dev/null +++ b/Lang/PascalABC.NET/Determine-if-a-string-has-all-unique-characters @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-has-all-unique-characters/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Determine-if-a-string-is-collapsible b/Lang/PascalABC.NET/Determine-if-a-string-is-collapsible new file mode 120000 index 0000000000..d22cc466fc --- /dev/null +++ b/Lang/PascalABC.NET/Determine-if-a-string-is-collapsible @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-collapsible/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Determine-if-a-string-is-numeric b/Lang/PascalABC.NET/Determine-if-a-string-is-numeric new file mode 120000 index 0000000000..3ddeb93c61 --- /dev/null +++ b/Lang/PascalABC.NET/Determine-if-a-string-is-numeric @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-numeric/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Determine-sentence-type b/Lang/PascalABC.NET/Determine-sentence-type new file mode 120000 index 0000000000..dc0284a0e0 --- /dev/null +++ b/Lang/PascalABC.NET/Determine-sentence-type @@ -0,0 +1 @@ +../../Task/Determine-sentence-type/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Dice-game-probabilities b/Lang/PascalABC.NET/Dice-game-probabilities new file mode 120000 index 0000000000..e5f12572e0 --- /dev/null +++ b/Lang/PascalABC.NET/Dice-game-probabilities @@ -0,0 +1 @@ +../../Task/Dice-game-probabilities/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Digital-root b/Lang/PascalABC.NET/Digital-root new file mode 120000 index 0000000000..2ade97cd7d --- /dev/null +++ b/Lang/PascalABC.NET/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Digital-root-Multiplicative-digital-root b/Lang/PascalABC.NET/Digital-root-Multiplicative-digital-root new file mode 120000 index 0000000000..3dcbce4c26 --- /dev/null +++ b/Lang/PascalABC.NET/Digital-root-Multiplicative-digital-root @@ -0,0 +1 @@ +../../Task/Digital-root-Multiplicative-digital-root/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Dijkstras-algorithm b/Lang/PascalABC.NET/Dijkstras-algorithm new file mode 120000 index 0000000000..d9c1782412 --- /dev/null +++ b/Lang/PascalABC.NET/Dijkstras-algorithm @@ -0,0 +1 @@ +../../Task/Dijkstras-algorithm/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Dinesmans-multiple-dwelling-problem b/Lang/PascalABC.NET/Dinesmans-multiple-dwelling-problem new file mode 120000 index 0000000000..b9659a07e6 --- /dev/null +++ b/Lang/PascalABC.NET/Dinesmans-multiple-dwelling-problem @@ -0,0 +1 @@ +../../Task/Dinesmans-multiple-dwelling-problem/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Disarium-numbers b/Lang/PascalABC.NET/Disarium-numbers new file mode 120000 index 0000000000..25866ae831 --- /dev/null +++ b/Lang/PascalABC.NET/Disarium-numbers @@ -0,0 +1 @@ +../../Task/Disarium-numbers/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Distribution-of-0-digits-in-factorial-series b/Lang/PascalABC.NET/Distribution-of-0-digits-in-factorial-series new file mode 120000 index 0000000000..f8efbe37d1 --- /dev/null +++ b/Lang/PascalABC.NET/Distribution-of-0-digits-in-factorial-series @@ -0,0 +1 @@ +../../Task/Distribution-of-0-digits-in-factorial-series/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Diversity-prediction-theorem b/Lang/PascalABC.NET/Diversity-prediction-theorem new file mode 120000 index 0000000000..a1a0483997 --- /dev/null +++ b/Lang/PascalABC.NET/Diversity-prediction-theorem @@ -0,0 +1 @@ +../../Task/Diversity-prediction-theorem/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Doomsday-rule b/Lang/PascalABC.NET/Doomsday-rule new file mode 120000 index 0000000000..4aed9db54a --- /dev/null +++ b/Lang/PascalABC.NET/Doomsday-rule @@ -0,0 +1 @@ +../../Task/Doomsday-rule/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Dot-product b/Lang/PascalABC.NET/Dot-product new file mode 120000 index 0000000000..75977e9d01 --- /dev/null +++ b/Lang/PascalABC.NET/Dot-product @@ -0,0 +1 @@ +../../Task/Dot-product/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Doubly-linked-list-Definition b/Lang/PascalABC.NET/Doubly-linked-list-Definition new file mode 120000 index 0000000000..f2561705cf --- /dev/null +++ b/Lang/PascalABC.NET/Doubly-linked-list-Definition @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Definition/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Doubly-linked-list-Element-definition b/Lang/PascalABC.NET/Doubly-linked-list-Element-definition new file mode 120000 index 0000000000..50c9d03e8c --- /dev/null +++ b/Lang/PascalABC.NET/Doubly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Element-definition/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Doubly-linked-list-Element-insertion b/Lang/PascalABC.NET/Doubly-linked-list-Element-insertion new file mode 120000 index 0000000000..28af162224 --- /dev/null +++ b/Lang/PascalABC.NET/Doubly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Element-insertion/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Doubly-linked-list-Traversal b/Lang/PascalABC.NET/Doubly-linked-list-Traversal new file mode 120000 index 0000000000..9cc3d51b16 --- /dev/null +++ b/Lang/PascalABC.NET/Doubly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Traversal/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Dragon-curve b/Lang/PascalABC.NET/Dragon-curve new file mode 120000 index 0000000000..1a8a6239bd --- /dev/null +++ b/Lang/PascalABC.NET/Dragon-curve @@ -0,0 +1 @@ +../../Task/Dragon-curve/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Draw-a-pixel b/Lang/PascalABC.NET/Draw-a-pixel new file mode 120000 index 0000000000..cdcb7e2918 --- /dev/null +++ b/Lang/PascalABC.NET/Draw-a-pixel @@ -0,0 +1 @@ +../../Task/Draw-a-pixel/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Draw-a-rotating-cube b/Lang/PascalABC.NET/Draw-a-rotating-cube new file mode 120000 index 0000000000..9092790488 --- /dev/null +++ b/Lang/PascalABC.NET/Draw-a-rotating-cube @@ -0,0 +1 @@ +../../Task/Draw-a-rotating-cube/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Duffinian-numbers b/Lang/PascalABC.NET/Duffinian-numbers new file mode 120000 index 0000000000..ed0f087334 --- /dev/null +++ b/Lang/PascalABC.NET/Duffinian-numbers @@ -0,0 +1 @@ +../../Task/Duffinian-numbers/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Dutch-national-flag-problem b/Lang/PascalABC.NET/Dutch-national-flag-problem new file mode 120000 index 0000000000..20b563dbd5 --- /dev/null +++ b/Lang/PascalABC.NET/Dutch-national-flag-problem @@ -0,0 +1 @@ +../../Task/Dutch-national-flag-problem/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Egyptian-division b/Lang/PascalABC.NET/Egyptian-division new file mode 120000 index 0000000000..d931ff8696 --- /dev/null +++ b/Lang/PascalABC.NET/Egyptian-division @@ -0,0 +1 @@ +../../Task/Egyptian-division/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Emirp-primes b/Lang/PascalABC.NET/Emirp-primes new file mode 120000 index 0000000000..69e5f4d7f7 --- /dev/null +++ b/Lang/PascalABC.NET/Emirp-primes @@ -0,0 +1 @@ +../../Task/Emirp-primes/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Empty-program b/Lang/PascalABC.NET/Empty-program new file mode 120000 index 0000000000..9a2aa557cd --- /dev/null +++ b/Lang/PascalABC.NET/Empty-program @@ -0,0 +1 @@ +../../Task/Empty-program/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Empty-string b/Lang/PascalABC.NET/Empty-string new file mode 120000 index 0000000000..39d89b0e6b --- /dev/null +++ b/Lang/PascalABC.NET/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Entropy b/Lang/PascalABC.NET/Entropy new file mode 120000 index 0000000000..792ccf7d2a --- /dev/null +++ b/Lang/PascalABC.NET/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Enumerations b/Lang/PascalABC.NET/Enumerations new file mode 120000 index 0000000000..3fbeab7aac --- /dev/null +++ b/Lang/PascalABC.NET/Enumerations @@ -0,0 +1 @@ +../../Task/Enumerations/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Environment-variables b/Lang/PascalABC.NET/Environment-variables new file mode 120000 index 0000000000..a87e0f0eca --- /dev/null +++ b/Lang/PascalABC.NET/Environment-variables @@ -0,0 +1 @@ +../../Task/Environment-variables/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Equal-prime-and-composite-sums b/Lang/PascalABC.NET/Equal-prime-and-composite-sums new file mode 120000 index 0000000000..e0ef8faaeb --- /dev/null +++ b/Lang/PascalABC.NET/Equal-prime-and-composite-sums @@ -0,0 +1 @@ +../../Task/Equal-prime-and-composite-sums/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Equilibrium-index b/Lang/PascalABC.NET/Equilibrium-index new file mode 120000 index 0000000000..1ebc161d1d --- /dev/null +++ b/Lang/PascalABC.NET/Equilibrium-index @@ -0,0 +1 @@ +../../Task/Equilibrium-index/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Erd-s-Nicolas-numbers b/Lang/PascalABC.NET/Erd-s-Nicolas-numbers new file mode 120000 index 0000000000..8d04b147b5 --- /dev/null +++ b/Lang/PascalABC.NET/Erd-s-Nicolas-numbers @@ -0,0 +1 @@ +../../Task/Erd-s-Nicolas-numbers/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Ethiopian-multiplication b/Lang/PascalABC.NET/Ethiopian-multiplication new file mode 120000 index 0000000000..225d8834fa --- /dev/null +++ b/Lang/PascalABC.NET/Ethiopian-multiplication @@ -0,0 +1 @@ +../../Task/Ethiopian-multiplication/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Euclid-Mullin-sequence b/Lang/PascalABC.NET/Euclid-Mullin-sequence new file mode 120000 index 0000000000..c1a4f722c5 --- /dev/null +++ b/Lang/PascalABC.NET/Euclid-Mullin-sequence @@ -0,0 +1 @@ +../../Task/Euclid-Mullin-sequence/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Euler-method b/Lang/PascalABC.NET/Euler-method new file mode 120000 index 0000000000..d3b60b57ad --- /dev/null +++ b/Lang/PascalABC.NET/Euler-method @@ -0,0 +1 @@ +../../Task/Euler-method/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Eulers-constant-0.5772... b/Lang/PascalABC.NET/Eulers-constant-0.5772... new file mode 120000 index 0000000000..093c235349 --- /dev/null +++ b/Lang/PascalABC.NET/Eulers-constant-0.5772... @@ -0,0 +1 @@ +../../Task/Eulers-constant-0.5772.../PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Eulers-identity b/Lang/PascalABC.NET/Eulers-identity new file mode 120000 index 0000000000..05f2a3a1ec --- /dev/null +++ b/Lang/PascalABC.NET/Eulers-identity @@ -0,0 +1 @@ +../../Task/Eulers-identity/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Eulers-sum-of-powers-conjecture b/Lang/PascalABC.NET/Eulers-sum-of-powers-conjecture new file mode 120000 index 0000000000..a568356eba --- /dev/null +++ b/Lang/PascalABC.NET/Eulers-sum-of-powers-conjecture @@ -0,0 +1 @@ +../../Task/Eulers-sum-of-powers-conjecture/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Evaluate-binomial-coefficients b/Lang/PascalABC.NET/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..6ad68ae41d --- /dev/null +++ b/Lang/PascalABC.NET/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Even-or-odd b/Lang/PascalABC.NET/Even-or-odd new file mode 120000 index 0000000000..4191597943 --- /dev/null +++ b/Lang/PascalABC.NET/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Events b/Lang/PascalABC.NET/Events new file mode 120000 index 0000000000..75843719a2 --- /dev/null +++ b/Lang/PascalABC.NET/Events @@ -0,0 +1 @@ +../../Task/Events/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Evolutionary-algorithm b/Lang/PascalABC.NET/Evolutionary-algorithm new file mode 120000 index 0000000000..bc9856dbc0 --- /dev/null +++ b/Lang/PascalABC.NET/Evolutionary-algorithm @@ -0,0 +1 @@ +../../Task/Evolutionary-algorithm/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Exceptions b/Lang/PascalABC.NET/Exceptions new file mode 120000 index 0000000000..b4b7999bea --- /dev/null +++ b/Lang/PascalABC.NET/Exceptions @@ -0,0 +1 @@ +../../Task/Exceptions/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Exceptions-Catch-an-exception-thrown-in-a-nested-call b/Lang/PascalABC.NET/Exceptions-Catch-an-exception-thrown-in-a-nested-call new file mode 120000 index 0000000000..7cf9286a5e --- /dev/null +++ b/Lang/PascalABC.NET/Exceptions-Catch-an-exception-thrown-in-a-nested-call @@ -0,0 +1 @@ +../../Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Execute-a-system-command b/Lang/PascalABC.NET/Execute-a-system-command new file mode 120000 index 0000000000..7b3f5b40fe --- /dev/null +++ b/Lang/PascalABC.NET/Execute-a-system-command @@ -0,0 +1 @@ +../../Task/Execute-a-system-command/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Exponentiation-order b/Lang/PascalABC.NET/Exponentiation-order new file mode 120000 index 0000000000..7066d9dd6b --- /dev/null +++ b/Lang/PascalABC.NET/Exponentiation-order @@ -0,0 +1 @@ +../../Task/Exponentiation-order/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Exponentiation-with-infix-operators-in-or-operating-on-the-base b/Lang/PascalABC.NET/Exponentiation-with-infix-operators-in-or-operating-on-the-base new file mode 120000 index 0000000000..cc33366128 --- /dev/null +++ b/Lang/PascalABC.NET/Exponentiation-with-infix-operators-in-or-operating-on-the-base @@ -0,0 +1 @@ +../../Task/Exponentiation-with-infix-operators-in-or-operating-on-the-base/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Extend-your-language b/Lang/PascalABC.NET/Extend-your-language new file mode 120000 index 0000000000..ee51376fd1 --- /dev/null +++ b/Lang/PascalABC.NET/Extend-your-language @@ -0,0 +1 @@ +../../Task/Extend-your-language/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Extensible-prime-generator b/Lang/PascalABC.NET/Extensible-prime-generator new file mode 120000 index 0000000000..c255987252 --- /dev/null +++ b/Lang/PascalABC.NET/Extensible-prime-generator @@ -0,0 +1 @@ +../../Task/Extensible-prime-generator/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Extreme-floating-point-values b/Lang/PascalABC.NET/Extreme-floating-point-values new file mode 120000 index 0000000000..438be3c964 --- /dev/null +++ b/Lang/PascalABC.NET/Extreme-floating-point-values @@ -0,0 +1 @@ +../../Task/Extreme-floating-point-values/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Factorial b/Lang/PascalABC.NET/Factorial new file mode 120000 index 0000000000..64716300fa --- /dev/null +++ b/Lang/PascalABC.NET/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Factorial-primes b/Lang/PascalABC.NET/Factorial-primes new file mode 120000 index 0000000000..5b7eb12507 --- /dev/null +++ b/Lang/PascalABC.NET/Factorial-primes @@ -0,0 +1 @@ +../../Task/Factorial-primes/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Factorions b/Lang/PascalABC.NET/Factorions new file mode 120000 index 0000000000..8d771f5a56 --- /dev/null +++ b/Lang/PascalABC.NET/Factorions @@ -0,0 +1 @@ +../../Task/Factorions/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Factors-of-a-Mersenne-number b/Lang/PascalABC.NET/Factors-of-a-Mersenne-number new file mode 120000 index 0000000000..3160230a03 --- /dev/null +++ b/Lang/PascalABC.NET/Factors-of-a-Mersenne-number @@ -0,0 +1 @@ +../../Task/Factors-of-a-Mersenne-number/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Factors-of-an-integer b/Lang/PascalABC.NET/Factors-of-an-integer new file mode 120000 index 0000000000..b2f675ad56 --- /dev/null +++ b/Lang/PascalABC.NET/Factors-of-an-integer @@ -0,0 +1 @@ +../../Task/Factors-of-an-integer/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Fairshare-between-two-and-more b/Lang/PascalABC.NET/Fairshare-between-two-and-more new file mode 120000 index 0000000000..c21d1ab427 --- /dev/null +++ b/Lang/PascalABC.NET/Fairshare-between-two-and-more @@ -0,0 +1 @@ +../../Task/Fairshare-between-two-and-more/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Farey-sequence b/Lang/PascalABC.NET/Farey-sequence new file mode 120000 index 0000000000..cd060f6fa5 --- /dev/null +++ b/Lang/PascalABC.NET/Farey-sequence @@ -0,0 +1 @@ +../../Task/Farey-sequence/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Fast-Fourier-transform b/Lang/PascalABC.NET/Fast-Fourier-transform new file mode 120000 index 0000000000..2ebeb31f36 --- /dev/null +++ b/Lang/PascalABC.NET/Fast-Fourier-transform @@ -0,0 +1 @@ +../../Task/Fast-Fourier-transform/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Feigenbaum-constant-calculation b/Lang/PascalABC.NET/Feigenbaum-constant-calculation new file mode 120000 index 0000000000..df0fd85992 --- /dev/null +++ b/Lang/PascalABC.NET/Feigenbaum-constant-calculation @@ -0,0 +1 @@ +../../Task/Feigenbaum-constant-calculation/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Fermat-numbers b/Lang/PascalABC.NET/Fermat-numbers new file mode 120000 index 0000000000..87303a8419 --- /dev/null +++ b/Lang/PascalABC.NET/Fermat-numbers @@ -0,0 +1 @@ +../../Task/Fermat-numbers/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Fibonacci-word b/Lang/PascalABC.NET/Fibonacci-word new file mode 120000 index 0000000000..6accc7df5c --- /dev/null +++ b/Lang/PascalABC.NET/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Fibonacci-word-fractal b/Lang/PascalABC.NET/Fibonacci-word-fractal new file mode 120000 index 0000000000..32647433c7 --- /dev/null +++ b/Lang/PascalABC.NET/Fibonacci-word-fractal @@ -0,0 +1 @@ +../../Task/Fibonacci-word-fractal/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/File-input-output b/Lang/PascalABC.NET/File-input-output new file mode 120000 index 0000000000..aa29aa165d --- /dev/null +++ b/Lang/PascalABC.NET/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/File-modification-time b/Lang/PascalABC.NET/File-modification-time new file mode 120000 index 0000000000..f54091dc36 --- /dev/null +++ b/Lang/PascalABC.NET/File-modification-time @@ -0,0 +1 @@ +../../Task/File-modification-time/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/File-size b/Lang/PascalABC.NET/File-size new file mode 120000 index 0000000000..cb4f56c334 --- /dev/null +++ b/Lang/PascalABC.NET/File-size @@ -0,0 +1 @@ +../../Task/File-size/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Filter b/Lang/PascalABC.NET/Filter new file mode 120000 index 0000000000..b6b1f56f68 --- /dev/null +++ b/Lang/PascalABC.NET/Filter @@ -0,0 +1 @@ +../../Task/Filter/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Find-common-directory-path b/Lang/PascalABC.NET/Find-common-directory-path new file mode 120000 index 0000000000..48495d80e3 --- /dev/null +++ b/Lang/PascalABC.NET/Find-common-directory-path @@ -0,0 +1 @@ +../../Task/Find-common-directory-path/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Find-if-a-point-is-within-a-triangle b/Lang/PascalABC.NET/Find-if-a-point-is-within-a-triangle new file mode 120000 index 0000000000..995f2a0af8 --- /dev/null +++ b/Lang/PascalABC.NET/Find-if-a-point-is-within-a-triangle @@ -0,0 +1 @@ +../../Task/Find-if-a-point-is-within-a-triangle/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Find-limit-of-recursion b/Lang/PascalABC.NET/Find-limit-of-recursion new file mode 120000 index 0000000000..8e738ede74 --- /dev/null +++ b/Lang/PascalABC.NET/Find-limit-of-recursion @@ -0,0 +1 @@ +../../Task/Find-limit-of-recursion/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Find-palindromic-numbers-in-both-binary-and-ternary-bases b/Lang/PascalABC.NET/Find-palindromic-numbers-in-both-binary-and-ternary-bases new file mode 120000 index 0000000000..d897fb9951 --- /dev/null +++ b/Lang/PascalABC.NET/Find-palindromic-numbers-in-both-binary-and-ternary-bases @@ -0,0 +1 @@ +../../Task/Find-palindromic-numbers-in-both-binary-and-ternary-bases/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Find-the-intersection-of-a-line-with-a-plane b/Lang/PascalABC.NET/Find-the-intersection-of-a-line-with-a-plane new file mode 120000 index 0000000000..db54cce940 --- /dev/null +++ b/Lang/PascalABC.NET/Find-the-intersection-of-a-line-with-a-plane @@ -0,0 +1 @@ +../../Task/Find-the-intersection-of-a-line-with-a-plane/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Find-the-intersection-of-two-lines b/Lang/PascalABC.NET/Find-the-intersection-of-two-lines new file mode 120000 index 0000000000..654d760b69 --- /dev/null +++ b/Lang/PascalABC.NET/Find-the-intersection-of-two-lines @@ -0,0 +1 @@ +../../Task/Find-the-intersection-of-two-lines/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Find-the-last-Sunday-of-each-month b/Lang/PascalABC.NET/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..14b7c01559 --- /dev/null +++ b/Lang/PascalABC.NET/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Find-the-missing-permutation b/Lang/PascalABC.NET/Find-the-missing-permutation new file mode 120000 index 0000000000..74bb4ee6f0 --- /dev/null +++ b/Lang/PascalABC.NET/Find-the-missing-permutation @@ -0,0 +1 @@ +../../Task/Find-the-missing-permutation/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/First-class-functions b/Lang/PascalABC.NET/First-class-functions new file mode 120000 index 0000000000..d4c191f6d3 --- /dev/null +++ b/Lang/PascalABC.NET/First-class-functions @@ -0,0 +1 @@ +../../Task/First-class-functions/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/First-class-functions-Use-numbers-analogously b/Lang/PascalABC.NET/First-class-functions-Use-numbers-analogously new file mode 120000 index 0000000000..60d3a6b1c4 --- /dev/null +++ b/Lang/PascalABC.NET/First-class-functions-Use-numbers-analogously @@ -0,0 +1 @@ +../../Task/First-class-functions-Use-numbers-analogously/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/First-perfect-square-in-base-n-with-n-unique-digits b/Lang/PascalABC.NET/First-perfect-square-in-base-n-with-n-unique-digits new file mode 120000 index 0000000000..dd9c2365f8 --- /dev/null +++ b/Lang/PascalABC.NET/First-perfect-square-in-base-n-with-n-unique-digits @@ -0,0 +1 @@ +../../Task/First-perfect-square-in-base-n-with-n-unique-digits/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/First-power-of-2-that-has-leading-decimal-digits-of-12 b/Lang/PascalABC.NET/First-power-of-2-that-has-leading-decimal-digits-of-12 new file mode 120000 index 0000000000..31a48a0c89 --- /dev/null +++ b/Lang/PascalABC.NET/First-power-of-2-that-has-leading-decimal-digits-of-12 @@ -0,0 +1 @@ +../../Task/First-power-of-2-that-has-leading-decimal-digits-of-12/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Five-weekends b/Lang/PascalABC.NET/Five-weekends new file mode 120000 index 0000000000..868fa3eedb --- /dev/null +++ b/Lang/PascalABC.NET/Five-weekends @@ -0,0 +1 @@ +../../Task/Five-weekends/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Fivenum b/Lang/PascalABC.NET/Fivenum new file mode 120000 index 0000000000..ef9246e91a --- /dev/null +++ b/Lang/PascalABC.NET/Fivenum @@ -0,0 +1 @@ +../../Task/Fivenum/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/FizzBuzz b/Lang/PascalABC.NET/FizzBuzz new file mode 120000 index 0000000000..9af47ffeb0 --- /dev/null +++ b/Lang/PascalABC.NET/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Flatten-a-list b/Lang/PascalABC.NET/Flatten-a-list new file mode 120000 index 0000000000..951e9e626d --- /dev/null +++ b/Lang/PascalABC.NET/Flatten-a-list @@ -0,0 +1 @@ +../../Task/Flatten-a-list/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Floyds-triangle b/Lang/PascalABC.NET/Floyds-triangle new file mode 120000 index 0000000000..741db9a754 --- /dev/null +++ b/Lang/PascalABC.NET/Floyds-triangle @@ -0,0 +1 @@ +../../Task/Floyds-triangle/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Fork b/Lang/PascalABC.NET/Fork new file mode 120000 index 0000000000..21f23b18c9 --- /dev/null +++ b/Lang/PascalABC.NET/Fork @@ -0,0 +1 @@ +../../Task/Fork/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Formatted-numeric-output b/Lang/PascalABC.NET/Formatted-numeric-output new file mode 120000 index 0000000000..d5385037bc --- /dev/null +++ b/Lang/PascalABC.NET/Formatted-numeric-output @@ -0,0 +1 @@ +../../Task/Formatted-numeric-output/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Forward-difference b/Lang/PascalABC.NET/Forward-difference new file mode 120000 index 0000000000..6ba594a872 --- /dev/null +++ b/Lang/PascalABC.NET/Forward-difference @@ -0,0 +1 @@ +../../Task/Forward-difference/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Fractal-tree b/Lang/PascalABC.NET/Fractal-tree new file mode 120000 index 0000000000..1018455008 --- /dev/null +++ b/Lang/PascalABC.NET/Fractal-tree @@ -0,0 +1 @@ +../../Task/Fractal-tree/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Function-composition b/Lang/PascalABC.NET/Function-composition new file mode 120000 index 0000000000..10938e885c --- /dev/null +++ b/Lang/PascalABC.NET/Function-composition @@ -0,0 +1 @@ +../../Task/Function-composition/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Function-definition b/Lang/PascalABC.NET/Function-definition new file mode 120000 index 0000000000..cc1ff414b4 --- /dev/null +++ b/Lang/PascalABC.NET/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Fusc-sequence b/Lang/PascalABC.NET/Fusc-sequence new file mode 120000 index 0000000000..30b9581633 --- /dev/null +++ b/Lang/PascalABC.NET/Fusc-sequence @@ -0,0 +1 @@ +../../Task/Fusc-sequence/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Gamma-function b/Lang/PascalABC.NET/Gamma-function new file mode 120000 index 0000000000..d0d1bc1bed --- /dev/null +++ b/Lang/PascalABC.NET/Gamma-function @@ -0,0 +1 @@ +../../Task/Gamma-function/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Gapful-numbers b/Lang/PascalABC.NET/Gapful-numbers new file mode 120000 index 0000000000..c53e98533f --- /dev/null +++ b/Lang/PascalABC.NET/Gapful-numbers @@ -0,0 +1 @@ +../../Task/Gapful-numbers/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Gauss-Jordan-matrix-inversion b/Lang/PascalABC.NET/Gauss-Jordan-matrix-inversion new file mode 120000 index 0000000000..af61f036c2 --- /dev/null +++ b/Lang/PascalABC.NET/Gauss-Jordan-matrix-inversion @@ -0,0 +1 @@ +../../Task/Gauss-Jordan-matrix-inversion/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Gaussian-elimination b/Lang/PascalABC.NET/Gaussian-elimination new file mode 120000 index 0000000000..263ffc6099 --- /dev/null +++ b/Lang/PascalABC.NET/Gaussian-elimination @@ -0,0 +1 @@ +../../Task/Gaussian-elimination/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/General-FizzBuzz b/Lang/PascalABC.NET/General-FizzBuzz new file mode 120000 index 0000000000..655ae97e52 --- /dev/null +++ b/Lang/PascalABC.NET/General-FizzBuzz @@ -0,0 +1 @@ +../../Task/General-FizzBuzz/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Generate-Chess960-starting-position b/Lang/PascalABC.NET/Generate-Chess960-starting-position new file mode 120000 index 0000000000..0f95aaeb00 --- /dev/null +++ b/Lang/PascalABC.NET/Generate-Chess960-starting-position @@ -0,0 +1 @@ +../../Task/Generate-Chess960-starting-position/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Generate-lower-case-ASCII-alphabet b/Lang/PascalABC.NET/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..8ef0c3c6f0 --- /dev/null +++ b/Lang/PascalABC.NET/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Generator-Exponential b/Lang/PascalABC.NET/Generator-Exponential new file mode 120000 index 0000000000..ca6d0b1093 --- /dev/null +++ b/Lang/PascalABC.NET/Generator-Exponential @@ -0,0 +1 @@ +../../Task/Generator-Exponential/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Generic-swap b/Lang/PascalABC.NET/Generic-swap new file mode 120000 index 0000000000..35fd1c3542 --- /dev/null +++ b/Lang/PascalABC.NET/Generic-swap @@ -0,0 +1 @@ +../../Task/Generic-swap/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Get-system-command-output b/Lang/PascalABC.NET/Get-system-command-output new file mode 120000 index 0000000000..41cb609755 --- /dev/null +++ b/Lang/PascalABC.NET/Get-system-command-output @@ -0,0 +1 @@ +../../Task/Get-system-command-output/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Giuga-numbers b/Lang/PascalABC.NET/Giuga-numbers new file mode 120000 index 0000000000..e5f281e7e3 --- /dev/null +++ b/Lang/PascalABC.NET/Giuga-numbers @@ -0,0 +1 @@ +../../Task/Giuga-numbers/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Globally-replace-text-in-several-files b/Lang/PascalABC.NET/Globally-replace-text-in-several-files new file mode 120000 index 0000000000..d8545a73f2 --- /dev/null +++ b/Lang/PascalABC.NET/Globally-replace-text-in-several-files @@ -0,0 +1 @@ +../../Task/Globally-replace-text-in-several-files/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Goldbachs-comet b/Lang/PascalABC.NET/Goldbachs-comet new file mode 120000 index 0000000000..01fcc2a336 --- /dev/null +++ b/Lang/PascalABC.NET/Goldbachs-comet @@ -0,0 +1 @@ +../../Task/Goldbachs-comet/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Golden-ratio-Convergence b/Lang/PascalABC.NET/Golden-ratio-Convergence new file mode 120000 index 0000000000..375683d4e0 --- /dev/null +++ b/Lang/PascalABC.NET/Golden-ratio-Convergence @@ -0,0 +1 @@ +../../Task/Golden-ratio-Convergence/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Gray-code b/Lang/PascalABC.NET/Gray-code new file mode 120000 index 0000000000..078fdc2c8b --- /dev/null +++ b/Lang/PascalABC.NET/Gray-code @@ -0,0 +1 @@ +../../Task/Gray-code/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Greatest-common-divisor b/Lang/PascalABC.NET/Greatest-common-divisor new file mode 120000 index 0000000000..27dc1c21f9 --- /dev/null +++ b/Lang/PascalABC.NET/Greatest-common-divisor @@ -0,0 +1 @@ +../../Task/Greatest-common-divisor/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Greatest-element-of-a-list b/Lang/PascalABC.NET/Greatest-element-of-a-list new file mode 120000 index 0000000000..b5185eb27d --- /dev/null +++ b/Lang/PascalABC.NET/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Greatest-subsequential-sum b/Lang/PascalABC.NET/Greatest-subsequential-sum new file mode 120000 index 0000000000..10aeb8b0f0 --- /dev/null +++ b/Lang/PascalABC.NET/Greatest-subsequential-sum @@ -0,0 +1 @@ +../../Task/Greatest-subsequential-sum/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Guess-the-number b/Lang/PascalABC.NET/Guess-the-number new file mode 120000 index 0000000000..7fff26f7e2 --- /dev/null +++ b/Lang/PascalABC.NET/Guess-the-number @@ -0,0 +1 @@ +../../Task/Guess-the-number/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/HTTP b/Lang/PascalABC.NET/HTTP new file mode 120000 index 0000000000..28d630c27b --- /dev/null +++ b/Lang/PascalABC.NET/HTTP @@ -0,0 +1 @@ +../../Task/HTTP/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/HTTPS b/Lang/PascalABC.NET/HTTPS new file mode 120000 index 0000000000..88259c85d4 --- /dev/null +++ b/Lang/PascalABC.NET/HTTPS @@ -0,0 +1 @@ +../../Task/HTTPS/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/HTTPS-Authenticated b/Lang/PascalABC.NET/HTTPS-Authenticated new file mode 120000 index 0000000000..5f39b0a90c --- /dev/null +++ b/Lang/PascalABC.NET/HTTPS-Authenticated @@ -0,0 +1 @@ +../../Task/HTTPS-Authenticated/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Hailstone-sequence b/Lang/PascalABC.NET/Hailstone-sequence new file mode 120000 index 0000000000..f83360c3ea --- /dev/null +++ b/Lang/PascalABC.NET/Hailstone-sequence @@ -0,0 +1 @@ +../../Task/Hailstone-sequence/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Halt-and-catch-fire b/Lang/PascalABC.NET/Halt-and-catch-fire new file mode 120000 index 0000000000..531d664087 --- /dev/null +++ b/Lang/PascalABC.NET/Halt-and-catch-fire @@ -0,0 +1 @@ +../../Task/Halt-and-catch-fire/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Hamming-numbers b/Lang/PascalABC.NET/Hamming-numbers new file mode 120000 index 0000000000..bd37bceed8 --- /dev/null +++ b/Lang/PascalABC.NET/Hamming-numbers @@ -0,0 +1 @@ +../../Task/Hamming-numbers/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Handle-a-signal b/Lang/PascalABC.NET/Handle-a-signal new file mode 120000 index 0000000000..e3f3390134 --- /dev/null +++ b/Lang/PascalABC.NET/Handle-a-signal @@ -0,0 +1 @@ +../../Task/Handle-a-signal/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Happy-numbers b/Lang/PascalABC.NET/Happy-numbers new file mode 120000 index 0000000000..2b0f0e30d5 --- /dev/null +++ b/Lang/PascalABC.NET/Happy-numbers @@ -0,0 +1 @@ +../../Task/Happy-numbers/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Harmonic-series b/Lang/PascalABC.NET/Harmonic-series new file mode 120000 index 0000000000..c5dec236a3 --- /dev/null +++ b/Lang/PascalABC.NET/Harmonic-series @@ -0,0 +1 @@ +../../Task/Harmonic-series/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Harshad-or-Niven-series b/Lang/PascalABC.NET/Harshad-or-Niven-series new file mode 120000 index 0000000000..4a30ac9f34 --- /dev/null +++ b/Lang/PascalABC.NET/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Hash-from-two-arrays b/Lang/PascalABC.NET/Hash-from-two-arrays new file mode 120000 index 0000000000..06b09f8bf9 --- /dev/null +++ b/Lang/PascalABC.NET/Hash-from-two-arrays @@ -0,0 +1 @@ +../../Task/Hash-from-two-arrays/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Haversine-formula b/Lang/PascalABC.NET/Haversine-formula new file mode 120000 index 0000000000..505d4c95b1 --- /dev/null +++ b/Lang/PascalABC.NET/Haversine-formula @@ -0,0 +1 @@ +../../Task/Haversine-formula/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Hello-world-Line-printer b/Lang/PascalABC.NET/Hello-world-Line-printer new file mode 120000 index 0000000000..87d7f6b37c --- /dev/null +++ b/Lang/PascalABC.NET/Hello-world-Line-printer @@ -0,0 +1 @@ +../../Task/Hello-world-Line-printer/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Hello-world-Newline-omission b/Lang/PascalABC.NET/Hello-world-Newline-omission new file mode 120000 index 0000000000..2c094828d8 --- /dev/null +++ b/Lang/PascalABC.NET/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Hello-world-Standard-error b/Lang/PascalABC.NET/Hello-world-Standard-error new file mode 120000 index 0000000000..4b2452f23e --- /dev/null +++ b/Lang/PascalABC.NET/Hello-world-Standard-error @@ -0,0 +1 @@ +../../Task/Hello-world-Standard-error/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Here-document b/Lang/PascalABC.NET/Here-document new file mode 120000 index 0000000000..073a394aa5 --- /dev/null +++ b/Lang/PascalABC.NET/Here-document @@ -0,0 +1 @@ +../../Task/Here-document/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Heronian-triangles b/Lang/PascalABC.NET/Heronian-triangles new file mode 120000 index 0000000000..38597384c9 --- /dev/null +++ b/Lang/PascalABC.NET/Heronian-triangles @@ -0,0 +1 @@ +../../Task/Heronian-triangles/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Hex-words b/Lang/PascalABC.NET/Hex-words new file mode 120000 index 0000000000..487faee543 --- /dev/null +++ b/Lang/PascalABC.NET/Hex-words @@ -0,0 +1 @@ +../../Task/Hex-words/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Hickerson-series-of-almost-integers b/Lang/PascalABC.NET/Hickerson-series-of-almost-integers new file mode 120000 index 0000000000..8789a0cbe0 --- /dev/null +++ b/Lang/PascalABC.NET/Hickerson-series-of-almost-integers @@ -0,0 +1 @@ +../../Task/Hickerson-series-of-almost-integers/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Higher-order-functions b/Lang/PascalABC.NET/Higher-order-functions new file mode 120000 index 0000000000..c3ac017464 --- /dev/null +++ b/Lang/PascalABC.NET/Higher-order-functions @@ -0,0 +1 @@ +../../Task/Higher-order-functions/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Hilbert-curve b/Lang/PascalABC.NET/Hilbert-curve new file mode 120000 index 0000000000..319eba89d6 --- /dev/null +++ b/Lang/PascalABC.NET/Hilbert-curve @@ -0,0 +1 @@ +../../Task/Hilbert-curve/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Hofstadter-Conway-$10-000-sequence b/Lang/PascalABC.NET/Hofstadter-Conway-$10-000-sequence new file mode 120000 index 0000000000..6f07522b20 --- /dev/null +++ b/Lang/PascalABC.NET/Hofstadter-Conway-$10-000-sequence @@ -0,0 +1 @@ +../../Task/Hofstadter-Conway-$10-000-sequence/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Hofstadter-Figure-Figure-sequences b/Lang/PascalABC.NET/Hofstadter-Figure-Figure-sequences new file mode 120000 index 0000000000..658c56f7ad --- /dev/null +++ b/Lang/PascalABC.NET/Hofstadter-Figure-Figure-sequences @@ -0,0 +1 @@ +../../Task/Hofstadter-Figure-Figure-sequences/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Hofstadter-Q-sequence b/Lang/PascalABC.NET/Hofstadter-Q-sequence new file mode 120000 index 0000000000..454e935a80 --- /dev/null +++ b/Lang/PascalABC.NET/Hofstadter-Q-sequence @@ -0,0 +1 @@ +../../Task/Hofstadter-Q-sequence/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Horizontal-sundial-calculations b/Lang/PascalABC.NET/Horizontal-sundial-calculations new file mode 120000 index 0000000000..6ab4227b2a --- /dev/null +++ b/Lang/PascalABC.NET/Horizontal-sundial-calculations @@ -0,0 +1 @@ +../../Task/Horizontal-sundial-calculations/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Horners-rule-for-polynomial-evaluation b/Lang/PascalABC.NET/Horners-rule-for-polynomial-evaluation new file mode 120000 index 0000000000..43a8514719 --- /dev/null +++ b/Lang/PascalABC.NET/Horners-rule-for-polynomial-evaluation @@ -0,0 +1 @@ +../../Task/Horners-rule-for-polynomial-evaluation/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Host-introspection b/Lang/PascalABC.NET/Host-introspection new file mode 120000 index 0000000000..786a9617c6 --- /dev/null +++ b/Lang/PascalABC.NET/Host-introspection @@ -0,0 +1 @@ +../../Task/Host-introspection/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Hostname b/Lang/PascalABC.NET/Hostname new file mode 120000 index 0000000000..89e14c01f4 --- /dev/null +++ b/Lang/PascalABC.NET/Hostname @@ -0,0 +1 @@ +../../Task/Hostname/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Humble-numbers b/Lang/PascalABC.NET/Humble-numbers new file mode 120000 index 0000000000..ee2cb9aa95 --- /dev/null +++ b/Lang/PascalABC.NET/Humble-numbers @@ -0,0 +1 @@ +../../Task/Humble-numbers/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/I-before-E-except-after-C b/Lang/PascalABC.NET/I-before-E-except-after-C new file mode 120000 index 0000000000..db9c4689f9 --- /dev/null +++ b/Lang/PascalABC.NET/I-before-E-except-after-C @@ -0,0 +1 @@ +../../Task/I-before-E-except-after-C/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/IBAN b/Lang/PascalABC.NET/IBAN new file mode 120000 index 0000000000..2a1610e29a --- /dev/null +++ b/Lang/PascalABC.NET/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/ISBN13-check-digit b/Lang/PascalABC.NET/ISBN13-check-digit new file mode 120000 index 0000000000..1cc5a9193a --- /dev/null +++ b/Lang/PascalABC.NET/ISBN13-check-digit @@ -0,0 +1 @@ +../../Task/ISBN13-check-digit/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Identity-matrix b/Lang/PascalABC.NET/Identity-matrix new file mode 120000 index 0000000000..e498197ea6 --- /dev/null +++ b/Lang/PascalABC.NET/Identity-matrix @@ -0,0 +1 @@ +../../Task/Identity-matrix/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Include-a-file b/Lang/PascalABC.NET/Include-a-file new file mode 120000 index 0000000000..5762928418 --- /dev/null +++ b/Lang/PascalABC.NET/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Increasing-gaps-between-consecutive-Niven-numbers b/Lang/PascalABC.NET/Increasing-gaps-between-consecutive-Niven-numbers new file mode 120000 index 0000000000..cff91f6819 --- /dev/null +++ b/Lang/PascalABC.NET/Increasing-gaps-between-consecutive-Niven-numbers @@ -0,0 +1 @@ +../../Task/Increasing-gaps-between-consecutive-Niven-numbers/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Increment-a-numerical-string b/Lang/PascalABC.NET/Increment-a-numerical-string new file mode 120000 index 0000000000..5570e6302a --- /dev/null +++ b/Lang/PascalABC.NET/Increment-a-numerical-string @@ -0,0 +1 @@ +../../Task/Increment-a-numerical-string/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Infinity b/Lang/PascalABC.NET/Infinity new file mode 120000 index 0000000000..e5b6807ad7 --- /dev/null +++ b/Lang/PascalABC.NET/Infinity @@ -0,0 +1 @@ +../../Task/Infinity/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Inheritance-Multiple b/Lang/PascalABC.NET/Inheritance-Multiple new file mode 120000 index 0000000000..f3f065b097 --- /dev/null +++ b/Lang/PascalABC.NET/Inheritance-Multiple @@ -0,0 +1 @@ +../../Task/Inheritance-Multiple/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Inheritance-Single b/Lang/PascalABC.NET/Inheritance-Single new file mode 120000 index 0000000000..2843b9d512 --- /dev/null +++ b/Lang/PascalABC.NET/Inheritance-Single @@ -0,0 +1 @@ +../../Task/Inheritance-Single/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Input-loop b/Lang/PascalABC.NET/Input-loop new file mode 120000 index 0000000000..8086164ab5 --- /dev/null +++ b/Lang/PascalABC.NET/Input-loop @@ -0,0 +1 @@ +../../Task/Input-loop/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Integer-comparison b/Lang/PascalABC.NET/Integer-comparison new file mode 120000 index 0000000000..b60ac826c4 --- /dev/null +++ b/Lang/PascalABC.NET/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Intersecting-number-wheels b/Lang/PascalABC.NET/Intersecting-number-wheels new file mode 120000 index 0000000000..5d79870677 --- /dev/null +++ b/Lang/PascalABC.NET/Intersecting-number-wheels @@ -0,0 +1 @@ +../../Task/Intersecting-number-wheels/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Isograms-and-heterograms b/Lang/PascalABC.NET/Isograms-and-heterograms new file mode 120000 index 0000000000..bf330eefcd --- /dev/null +++ b/Lang/PascalABC.NET/Isograms-and-heterograms @@ -0,0 +1 @@ +../../Task/Isograms-and-heterograms/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Isqrt-integer-square-root-of-X b/Lang/PascalABC.NET/Isqrt-integer-square-root-of-X new file mode 120000 index 0000000000..5e922bc6f6 --- /dev/null +++ b/Lang/PascalABC.NET/Isqrt-integer-square-root-of-X @@ -0,0 +1 @@ +../../Task/Isqrt-integer-square-root-of-X/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Iterated-digits-squaring b/Lang/PascalABC.NET/Iterated-digits-squaring new file mode 120000 index 0000000000..d26b072d9f --- /dev/null +++ b/Lang/PascalABC.NET/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/JSON b/Lang/PascalABC.NET/JSON new file mode 120000 index 0000000000..e24e87ebee --- /dev/null +++ b/Lang/PascalABC.NET/JSON @@ -0,0 +1 @@ +../../Task/JSON/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Jacobi-symbol b/Lang/PascalABC.NET/Jacobi-symbol new file mode 120000 index 0000000000..beae5f110d --- /dev/null +++ b/Lang/PascalABC.NET/Jacobi-symbol @@ -0,0 +1 @@ +../../Task/Jacobi-symbol/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Jacobsthal-numbers b/Lang/PascalABC.NET/Jacobsthal-numbers new file mode 120000 index 0000000000..876df13cd2 --- /dev/null +++ b/Lang/PascalABC.NET/Jacobsthal-numbers @@ -0,0 +1 @@ +../../Task/Jacobsthal-numbers/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Jensens-Device b/Lang/PascalABC.NET/Jensens-Device new file mode 120000 index 0000000000..b995733017 --- /dev/null +++ b/Lang/PascalABC.NET/Jensens-Device @@ -0,0 +1 @@ +../../Task/Jensens-Device/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Jewels-and-stones b/Lang/PascalABC.NET/Jewels-and-stones new file mode 120000 index 0000000000..3c21e35293 --- /dev/null +++ b/Lang/PascalABC.NET/Jewels-and-stones @@ -0,0 +1 @@ +../../Task/Jewels-and-stones/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/JortSort b/Lang/PascalABC.NET/JortSort new file mode 120000 index 0000000000..7235c60479 --- /dev/null +++ b/Lang/PascalABC.NET/JortSort @@ -0,0 +1 @@ +../../Task/JortSort/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Josephus-problem b/Lang/PascalABC.NET/Josephus-problem new file mode 120000 index 0000000000..b62f88327b --- /dev/null +++ b/Lang/PascalABC.NET/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Juggler-sequence b/Lang/PascalABC.NET/Juggler-sequence new file mode 120000 index 0000000000..11d7432b3c --- /dev/null +++ b/Lang/PascalABC.NET/Juggler-sequence @@ -0,0 +1 @@ +../../Task/Juggler-sequence/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Julia-set b/Lang/PascalABC.NET/Julia-set new file mode 120000 index 0000000000..905a140bc7 --- /dev/null +++ b/Lang/PascalABC.NET/Julia-set @@ -0,0 +1 @@ +../../Task/Julia-set/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Jump-anywhere b/Lang/PascalABC.NET/Jump-anywhere new file mode 120000 index 0000000000..cb395144b9 --- /dev/null +++ b/Lang/PascalABC.NET/Jump-anywhere @@ -0,0 +1 @@ +../../Task/Jump-anywhere/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Kaprekar-numbers b/Lang/PascalABC.NET/Kaprekar-numbers new file mode 120000 index 0000000000..f1765dac14 --- /dev/null +++ b/Lang/PascalABC.NET/Kaprekar-numbers @@ -0,0 +1 @@ +../../Task/Kaprekar-numbers/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Kernighans-large-earthquake-problem b/Lang/PascalABC.NET/Kernighans-large-earthquake-problem new file mode 120000 index 0000000000..bfd99d6f53 --- /dev/null +++ b/Lang/PascalABC.NET/Kernighans-large-earthquake-problem @@ -0,0 +1 @@ +../../Task/Kernighans-large-earthquake-problem/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Keyboard-input-Obtain-a-Y-or-N-response b/Lang/PascalABC.NET/Keyboard-input-Obtain-a-Y-or-N-response new file mode 120000 index 0000000000..d70dc96806 --- /dev/null +++ b/Lang/PascalABC.NET/Keyboard-input-Obtain-a-Y-or-N-response @@ -0,0 +1 @@ +../../Task/Keyboard-input-Obtain-a-Y-or-N-response/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Knapsack-problem-0-1 b/Lang/PascalABC.NET/Knapsack-problem-0-1 new file mode 120000 index 0000000000..2fbfd42a60 --- /dev/null +++ b/Lang/PascalABC.NET/Knapsack-problem-0-1 @@ -0,0 +1 @@ +../../Task/Knapsack-problem-0-1/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Knuth-shuffle b/Lang/PascalABC.NET/Knuth-shuffle new file mode 120000 index 0000000000..a80c329b34 --- /dev/null +++ b/Lang/PascalABC.NET/Knuth-shuffle @@ -0,0 +1 @@ +../../Task/Knuth-shuffle/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Knuths-algorithm-S b/Lang/PascalABC.NET/Knuths-algorithm-S new file mode 120000 index 0000000000..5898ddfb2a --- /dev/null +++ b/Lang/PascalABC.NET/Knuths-algorithm-S @@ -0,0 +1 @@ +../../Task/Knuths-algorithm-S/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Knuths-power-tree b/Lang/PascalABC.NET/Knuths-power-tree new file mode 120000 index 0000000000..985187fb94 --- /dev/null +++ b/Lang/PascalABC.NET/Knuths-power-tree @@ -0,0 +1 @@ +../../Task/Knuths-power-tree/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Kolakoski-sequence b/Lang/PascalABC.NET/Kolakoski-sequence new file mode 120000 index 0000000000..141e5ac2f1 --- /dev/null +++ b/Lang/PascalABC.NET/Kolakoski-sequence @@ -0,0 +1 @@ +../../Task/Kolakoski-sequence/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Kosaraju b/Lang/PascalABC.NET/Kosaraju new file mode 120000 index 0000000000..b461c7f092 --- /dev/null +++ b/Lang/PascalABC.NET/Kosaraju @@ -0,0 +1 @@ +../../Task/Kosaraju/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Kronecker-product b/Lang/PascalABC.NET/Kronecker-product new file mode 120000 index 0000000000..d78d832294 --- /dev/null +++ b/Lang/PascalABC.NET/Kronecker-product @@ -0,0 +1 @@ +../../Task/Kronecker-product/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Kronecker-product-based-fractals b/Lang/PascalABC.NET/Kronecker-product-based-fractals new file mode 120000 index 0000000000..47d2054ae1 --- /dev/null +++ b/Lang/PascalABC.NET/Kronecker-product-based-fractals @@ -0,0 +1 @@ +../../Task/Kronecker-product-based-fractals/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/LZW-compression b/Lang/PascalABC.NET/LZW-compression new file mode 120000 index 0000000000..caca350ee1 --- /dev/null +++ b/Lang/PascalABC.NET/LZW-compression @@ -0,0 +1 @@ +../../Task/LZW-compression/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Lah-numbers b/Lang/PascalABC.NET/Lah-numbers new file mode 120000 index 0000000000..6d00cf7c92 --- /dev/null +++ b/Lang/PascalABC.NET/Lah-numbers @@ -0,0 +1 @@ +../../Task/Lah-numbers/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Langtons-ant b/Lang/PascalABC.NET/Langtons-ant new file mode 120000 index 0000000000..7c98b40d3c --- /dev/null +++ b/Lang/PascalABC.NET/Langtons-ant @@ -0,0 +1 @@ +../../Task/Langtons-ant/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Largest-int-from-concatenated-ints b/Lang/PascalABC.NET/Largest-int-from-concatenated-ints new file mode 120000 index 0000000000..97fdfc9525 --- /dev/null +++ b/Lang/PascalABC.NET/Largest-int-from-concatenated-ints @@ -0,0 +1 @@ +../../Task/Largest-int-from-concatenated-ints/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Largest-number-divisible-by-its-digits b/Lang/PascalABC.NET/Largest-number-divisible-by-its-digits new file mode 120000 index 0000000000..40a547007f --- /dev/null +++ b/Lang/PascalABC.NET/Largest-number-divisible-by-its-digits @@ -0,0 +1 @@ +../../Task/Largest-number-divisible-by-its-digits/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Largest-proper-divisor-of-n b/Lang/PascalABC.NET/Largest-proper-divisor-of-n new file mode 120000 index 0000000000..2988b13d98 --- /dev/null +++ b/Lang/PascalABC.NET/Largest-proper-divisor-of-n @@ -0,0 +1 @@ +../../Task/Largest-proper-divisor-of-n/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Last-Friday-of-each-month b/Lang/PascalABC.NET/Last-Friday-of-each-month new file mode 120000 index 0000000000..bcb04c8152 --- /dev/null +++ b/Lang/PascalABC.NET/Last-Friday-of-each-month @@ -0,0 +1 @@ +../../Task/Last-Friday-of-each-month/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Last-letter-first-letter b/Lang/PascalABC.NET/Last-letter-first-letter new file mode 120000 index 0000000000..19b2a978ef --- /dev/null +++ b/Lang/PascalABC.NET/Last-letter-first-letter @@ -0,0 +1 @@ +../../Task/Last-letter-first-letter/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Law-of-cosines---triples b/Lang/PascalABC.NET/Law-of-cosines---triples new file mode 120000 index 0000000000..c3f4700866 --- /dev/null +++ b/Lang/PascalABC.NET/Law-of-cosines---triples @@ -0,0 +1 @@ +../../Task/Law-of-cosines---triples/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Leap-year b/Lang/PascalABC.NET/Leap-year new file mode 120000 index 0000000000..250d71014a --- /dev/null +++ b/Lang/PascalABC.NET/Leap-year @@ -0,0 +1 @@ +../../Task/Leap-year/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Least-common-multiple b/Lang/PascalABC.NET/Least-common-multiple new file mode 120000 index 0000000000..446b96ac48 --- /dev/null +++ b/Lang/PascalABC.NET/Least-common-multiple @@ -0,0 +1 @@ +../../Task/Least-common-multiple/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Left-factorials b/Lang/PascalABC.NET/Left-factorials new file mode 120000 index 0000000000..8ed1d03134 --- /dev/null +++ b/Lang/PascalABC.NET/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Leonardo-numbers b/Lang/PascalABC.NET/Leonardo-numbers new file mode 120000 index 0000000000..0895bc3d59 --- /dev/null +++ b/Lang/PascalABC.NET/Leonardo-numbers @@ -0,0 +1 @@ +../../Task/Leonardo-numbers/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Levenshtein-distance b/Lang/PascalABC.NET/Levenshtein-distance new file mode 120000 index 0000000000..e32fc71042 --- /dev/null +++ b/Lang/PascalABC.NET/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Linear-congruential-generator b/Lang/PascalABC.NET/Linear-congruential-generator new file mode 120000 index 0000000000..901b6b4116 --- /dev/null +++ b/Lang/PascalABC.NET/Linear-congruential-generator @@ -0,0 +1 @@ +../../Task/Linear-congruential-generator/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/List-comprehensions b/Lang/PascalABC.NET/List-comprehensions new file mode 120000 index 0000000000..e9fa93e9e6 --- /dev/null +++ b/Lang/PascalABC.NET/List-comprehensions @@ -0,0 +1 @@ +../../Task/List-comprehensions/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Literals-Floating-point b/Lang/PascalABC.NET/Literals-Floating-point new file mode 120000 index 0000000000..e11300a194 --- /dev/null +++ b/Lang/PascalABC.NET/Literals-Floating-point @@ -0,0 +1 @@ +../../Task/Literals-Floating-point/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Literals-Integer b/Lang/PascalABC.NET/Literals-Integer new file mode 120000 index 0000000000..a9aac3cffe --- /dev/null +++ b/Lang/PascalABC.NET/Literals-Integer @@ -0,0 +1 @@ +../../Task/Literals-Integer/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Literals-String b/Lang/PascalABC.NET/Literals-String new file mode 120000 index 0000000000..2f02c8af92 --- /dev/null +++ b/Lang/PascalABC.NET/Literals-String @@ -0,0 +1 @@ +../../Task/Literals-String/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Logistic-curve-fitting-in-epidemiology b/Lang/PascalABC.NET/Logistic-curve-fitting-in-epidemiology new file mode 120000 index 0000000000..9ae308e46e --- /dev/null +++ b/Lang/PascalABC.NET/Logistic-curve-fitting-in-epidemiology @@ -0,0 +1 @@ +../../Task/Logistic-curve-fitting-in-epidemiology/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Long-literals-with-continuations b/Lang/PascalABC.NET/Long-literals-with-continuations new file mode 120000 index 0000000000..cef817d9b6 --- /dev/null +++ b/Lang/PascalABC.NET/Long-literals-with-continuations @@ -0,0 +1 @@ +../../Task/Long-literals-with-continuations/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Long-multiplication b/Lang/PascalABC.NET/Long-multiplication new file mode 120000 index 0000000000..3da90eb79b --- /dev/null +++ b/Lang/PascalABC.NET/Long-multiplication @@ -0,0 +1 @@ +../../Task/Long-multiplication/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Long-primes b/Lang/PascalABC.NET/Long-primes new file mode 120000 index 0000000000..f90c1c5b51 --- /dev/null +++ b/Lang/PascalABC.NET/Long-primes @@ -0,0 +1 @@ +../../Task/Long-primes/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Long-year b/Lang/PascalABC.NET/Long-year new file mode 120000 index 0000000000..cfbd0a990c --- /dev/null +++ b/Lang/PascalABC.NET/Long-year @@ -0,0 +1 @@ +../../Task/Long-year/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Longest-common-subsequence b/Lang/PascalABC.NET/Longest-common-subsequence new file mode 120000 index 0000000000..1dfbd5ef9d --- /dev/null +++ b/Lang/PascalABC.NET/Longest-common-subsequence @@ -0,0 +1 @@ +../../Task/Longest-common-subsequence/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Longest-common-substring b/Lang/PascalABC.NET/Longest-common-substring new file mode 120000 index 0000000000..c8e27105a8 --- /dev/null +++ b/Lang/PascalABC.NET/Longest-common-substring @@ -0,0 +1 @@ +../../Task/Longest-common-substring/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Longest-increasing-subsequence b/Lang/PascalABC.NET/Longest-increasing-subsequence new file mode 120000 index 0000000000..256a8afb28 --- /dev/null +++ b/Lang/PascalABC.NET/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Look-and-say-sequence b/Lang/PascalABC.NET/Look-and-say-sequence new file mode 120000 index 0000000000..a23016f201 --- /dev/null +++ b/Lang/PascalABC.NET/Look-and-say-sequence @@ -0,0 +1 @@ +../../Task/Look-and-say-sequence/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Loop-over-multiple-arrays-simultaneously b/Lang/PascalABC.NET/Loop-over-multiple-arrays-simultaneously new file mode 120000 index 0000000000..52655fded4 --- /dev/null +++ b/Lang/PascalABC.NET/Loop-over-multiple-arrays-simultaneously @@ -0,0 +1 @@ +../../Task/Loop-over-multiple-arrays-simultaneously/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Loops-Break b/Lang/PascalABC.NET/Loops-Break new file mode 120000 index 0000000000..75f285786e --- /dev/null +++ b/Lang/PascalABC.NET/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Loops-Continue b/Lang/PascalABC.NET/Loops-Continue new file mode 120000 index 0000000000..75da2856ce --- /dev/null +++ b/Lang/PascalABC.NET/Loops-Continue @@ -0,0 +1 @@ +../../Task/Loops-Continue/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Loops-Do-while b/Lang/PascalABC.NET/Loops-Do-while new file mode 120000 index 0000000000..a15c938618 --- /dev/null +++ b/Lang/PascalABC.NET/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Loops-Downward-for b/Lang/PascalABC.NET/Loops-Downward-for new file mode 120000 index 0000000000..c2c6306f3a --- /dev/null +++ b/Lang/PascalABC.NET/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Loops-For b/Lang/PascalABC.NET/Loops-For new file mode 120000 index 0000000000..bf236f094e --- /dev/null +++ b/Lang/PascalABC.NET/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Loops-For-with-a-specified-step b/Lang/PascalABC.NET/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..5244453d5c --- /dev/null +++ b/Lang/PascalABC.NET/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Loops-Foreach b/Lang/PascalABC.NET/Loops-Foreach new file mode 120000 index 0000000000..68b06931af --- /dev/null +++ b/Lang/PascalABC.NET/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Loops-Increment-loop-index-within-loop-body b/Lang/PascalABC.NET/Loops-Increment-loop-index-within-loop-body new file mode 120000 index 0000000000..f5d20bce59 --- /dev/null +++ b/Lang/PascalABC.NET/Loops-Increment-loop-index-within-loop-body @@ -0,0 +1 @@ +../../Task/Loops-Increment-loop-index-within-loop-body/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Loops-N-plus-one-half b/Lang/PascalABC.NET/Loops-N-plus-one-half new file mode 120000 index 0000000000..95fe8496ec --- /dev/null +++ b/Lang/PascalABC.NET/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Loops-Nested b/Lang/PascalABC.NET/Loops-Nested new file mode 120000 index 0000000000..d1a88ee15f --- /dev/null +++ b/Lang/PascalABC.NET/Loops-Nested @@ -0,0 +1 @@ +../../Task/Loops-Nested/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Loops-While b/Lang/PascalABC.NET/Loops-While new file mode 120000 index 0000000000..19d817b9f2 --- /dev/null +++ b/Lang/PascalABC.NET/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Loops-With-multiple-ranges b/Lang/PascalABC.NET/Loops-With-multiple-ranges new file mode 120000 index 0000000000..1b3c0e8a85 --- /dev/null +++ b/Lang/PascalABC.NET/Loops-With-multiple-ranges @@ -0,0 +1 @@ +../../Task/Loops-With-multiple-ranges/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Loops-Wrong-ranges b/Lang/PascalABC.NET/Loops-Wrong-ranges new file mode 120000 index 0000000000..cd717ae408 --- /dev/null +++ b/Lang/PascalABC.NET/Loops-Wrong-ranges @@ -0,0 +1 @@ +../../Task/Loops-Wrong-ranges/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Lucas-Lehmer-test b/Lang/PascalABC.NET/Lucas-Lehmer-test new file mode 120000 index 0000000000..bec917b045 --- /dev/null +++ b/Lang/PascalABC.NET/Lucas-Lehmer-test @@ -0,0 +1 @@ +../../Task/Lucas-Lehmer-test/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Ludic-numbers b/Lang/PascalABC.NET/Ludic-numbers new file mode 120000 index 0000000000..84c5abb4fd --- /dev/null +++ b/Lang/PascalABC.NET/Ludic-numbers @@ -0,0 +1 @@ +../../Task/Ludic-numbers/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Luhn-test-of-credit-card-numbers b/Lang/PascalABC.NET/Luhn-test-of-credit-card-numbers new file mode 120000 index 0000000000..00804b09b8 --- /dev/null +++ b/Lang/PascalABC.NET/Luhn-test-of-credit-card-numbers @@ -0,0 +1 @@ +../../Task/Luhn-test-of-credit-card-numbers/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Lychrel-numbers b/Lang/PascalABC.NET/Lychrel-numbers new file mode 120000 index 0000000000..c6935e364e --- /dev/null +++ b/Lang/PascalABC.NET/Lychrel-numbers @@ -0,0 +1 @@ +../../Task/Lychrel-numbers/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/M-bius-function b/Lang/PascalABC.NET/M-bius-function new file mode 120000 index 0000000000..e6445ec3ed --- /dev/null +++ b/Lang/PascalABC.NET/M-bius-function @@ -0,0 +1 @@ +../../Task/M-bius-function/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/MAC-vendor-lookup b/Lang/PascalABC.NET/MAC-vendor-lookup new file mode 120000 index 0000000000..d35cdd8c9b --- /dev/null +++ b/Lang/PascalABC.NET/MAC-vendor-lookup @@ -0,0 +1 @@ +../../Task/MAC-vendor-lookup/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/MD5 b/Lang/PascalABC.NET/MD5 new file mode 120000 index 0000000000..375523a297 --- /dev/null +++ b/Lang/PascalABC.NET/MD5 @@ -0,0 +1 @@ +../../Task/MD5/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Magic-constant b/Lang/PascalABC.NET/Magic-constant new file mode 120000 index 0000000000..822ebb4fb2 --- /dev/null +++ b/Lang/PascalABC.NET/Magic-constant @@ -0,0 +1 @@ +../../Task/Magic-constant/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Magic-squares-of-doubly-even-order b/Lang/PascalABC.NET/Magic-squares-of-doubly-even-order new file mode 120000 index 0000000000..b8c93bc64a --- /dev/null +++ b/Lang/PascalABC.NET/Magic-squares-of-doubly-even-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-doubly-even-order/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Magnanimous-numbers b/Lang/PascalABC.NET/Magnanimous-numbers new file mode 120000 index 0000000000..0a895d4414 --- /dev/null +++ b/Lang/PascalABC.NET/Magnanimous-numbers @@ -0,0 +1 @@ +../../Task/Magnanimous-numbers/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Man-or-boy-test b/Lang/PascalABC.NET/Man-or-boy-test new file mode 120000 index 0000000000..f9b9ccb7a0 --- /dev/null +++ b/Lang/PascalABC.NET/Man-or-boy-test @@ -0,0 +1 @@ +../../Task/Man-or-boy-test/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Map-range b/Lang/PascalABC.NET/Map-range new file mode 120000 index 0000000000..2c5d9ac526 --- /dev/null +++ b/Lang/PascalABC.NET/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Matrix-exponentiation-operator b/Lang/PascalABC.NET/Matrix-exponentiation-operator new file mode 120000 index 0000000000..31137ceb77 --- /dev/null +++ b/Lang/PascalABC.NET/Matrix-exponentiation-operator @@ -0,0 +1 @@ +../../Task/Matrix-exponentiation-operator/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Matrix-multiplication b/Lang/PascalABC.NET/Matrix-multiplication new file mode 120000 index 0000000000..ab9b502408 --- /dev/null +++ b/Lang/PascalABC.NET/Matrix-multiplication @@ -0,0 +1 @@ +../../Task/Matrix-multiplication/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Matrix-transposition b/Lang/PascalABC.NET/Matrix-transposition new file mode 120000 index 0000000000..2ba6e5da4b --- /dev/null +++ b/Lang/PascalABC.NET/Matrix-transposition @@ -0,0 +1 @@ +../../Task/Matrix-transposition/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Maximum-triangle-path-sum b/Lang/PascalABC.NET/Maximum-triangle-path-sum new file mode 120000 index 0000000000..d476233920 --- /dev/null +++ b/Lang/PascalABC.NET/Maximum-triangle-path-sum @@ -0,0 +1 @@ +../../Task/Maximum-triangle-path-sum/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Maze-generation b/Lang/PascalABC.NET/Maze-generation new file mode 120000 index 0000000000..147e928cb8 --- /dev/null +++ b/Lang/PascalABC.NET/Maze-generation @@ -0,0 +1 @@ +../../Task/Maze-generation/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/McNuggets-problem b/Lang/PascalABC.NET/McNuggets-problem new file mode 120000 index 0000000000..ceb4630090 --- /dev/null +++ b/Lang/PascalABC.NET/McNuggets-problem @@ -0,0 +1 @@ +../../Task/McNuggets-problem/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Memory-allocation b/Lang/PascalABC.NET/Memory-allocation new file mode 120000 index 0000000000..b7e94af0dd --- /dev/null +++ b/Lang/PascalABC.NET/Memory-allocation @@ -0,0 +1 @@ +../../Task/Memory-allocation/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Mertens-function b/Lang/PascalABC.NET/Mertens-function new file mode 120000 index 0000000000..f3e21033e6 --- /dev/null +++ b/Lang/PascalABC.NET/Mertens-function @@ -0,0 +1 @@ +../../Task/Mertens-function/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Metallic-ratios b/Lang/PascalABC.NET/Metallic-ratios new file mode 120000 index 0000000000..1f47416b87 --- /dev/null +++ b/Lang/PascalABC.NET/Metallic-ratios @@ -0,0 +1 @@ +../../Task/Metallic-ratios/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Metered-concurrency b/Lang/PascalABC.NET/Metered-concurrency new file mode 120000 index 0000000000..925b288d53 --- /dev/null +++ b/Lang/PascalABC.NET/Metered-concurrency @@ -0,0 +1 @@ +../../Task/Metered-concurrency/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Mian-Chowla-sequence b/Lang/PascalABC.NET/Mian-Chowla-sequence new file mode 120000 index 0000000000..8a0250e208 --- /dev/null +++ b/Lang/PascalABC.NET/Mian-Chowla-sequence @@ -0,0 +1 @@ +../../Task/Mian-Chowla-sequence/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Middle-three-digits b/Lang/PascalABC.NET/Middle-three-digits new file mode 120000 index 0000000000..5e135c1794 --- /dev/null +++ b/Lang/PascalABC.NET/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Minimum-multiple-of-m-where-digital-sum-equals-m b/Lang/PascalABC.NET/Minimum-multiple-of-m-where-digital-sum-equals-m new file mode 120000 index 0000000000..97c186fb9d --- /dev/null +++ b/Lang/PascalABC.NET/Minimum-multiple-of-m-where-digital-sum-equals-m @@ -0,0 +1 @@ +../../Task/Minimum-multiple-of-m-where-digital-sum-equals-m/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Modified-random-distribution b/Lang/PascalABC.NET/Modified-random-distribution new file mode 120000 index 0000000000..0b45ed8c91 --- /dev/null +++ b/Lang/PascalABC.NET/Modified-random-distribution @@ -0,0 +1 @@ +../../Task/Modified-random-distribution/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Modular-exponentiation b/Lang/PascalABC.NET/Modular-exponentiation new file mode 120000 index 0000000000..06db8e7a38 --- /dev/null +++ b/Lang/PascalABC.NET/Modular-exponentiation @@ -0,0 +1 @@ +../../Task/Modular-exponentiation/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Modular-inverse b/Lang/PascalABC.NET/Modular-inverse new file mode 120000 index 0000000000..cf592b925c --- /dev/null +++ b/Lang/PascalABC.NET/Modular-inverse @@ -0,0 +1 @@ +../../Task/Modular-inverse/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Monte-Carlo-methods b/Lang/PascalABC.NET/Monte-Carlo-methods new file mode 120000 index 0000000000..097d7017f6 --- /dev/null +++ b/Lang/PascalABC.NET/Monte-Carlo-methods @@ -0,0 +1 @@ +../../Task/Monte-Carlo-methods/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Monty-Hall-problem b/Lang/PascalABC.NET/Monty-Hall-problem new file mode 120000 index 0000000000..194ee5c033 --- /dev/null +++ b/Lang/PascalABC.NET/Monty-Hall-problem @@ -0,0 +1 @@ +../../Task/Monty-Hall-problem/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Morse-code b/Lang/PascalABC.NET/Morse-code new file mode 120000 index 0000000000..957358167f --- /dev/null +++ b/Lang/PascalABC.NET/Morse-code @@ -0,0 +1 @@ +../../Task/Morse-code/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Motzkin-numbers b/Lang/PascalABC.NET/Motzkin-numbers new file mode 120000 index 0000000000..119a6ee6b9 --- /dev/null +++ b/Lang/PascalABC.NET/Motzkin-numbers @@ -0,0 +1 @@ +../../Task/Motzkin-numbers/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Mouse-position b/Lang/PascalABC.NET/Mouse-position new file mode 120000 index 0000000000..207ee7b935 --- /dev/null +++ b/Lang/PascalABC.NET/Mouse-position @@ -0,0 +1 @@ +../../Task/Mouse-position/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Move-to-front-algorithm b/Lang/PascalABC.NET/Move-to-front-algorithm new file mode 120000 index 0000000000..e365638bb3 --- /dev/null +++ b/Lang/PascalABC.NET/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Multifactorial b/Lang/PascalABC.NET/Multifactorial new file mode 120000 index 0000000000..1a4d72f284 --- /dev/null +++ b/Lang/PascalABC.NET/Multifactorial @@ -0,0 +1 @@ +../../Task/Multifactorial/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Multiple-regression b/Lang/PascalABC.NET/Multiple-regression new file mode 120000 index 0000000000..c2b1f827d2 --- /dev/null +++ b/Lang/PascalABC.NET/Multiple-regression @@ -0,0 +1 @@ +../../Task/Multiple-regression/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Multiplication-tables b/Lang/PascalABC.NET/Multiplication-tables new file mode 120000 index 0000000000..bbe1dc2627 --- /dev/null +++ b/Lang/PascalABC.NET/Multiplication-tables @@ -0,0 +1 @@ +../../Task/Multiplication-tables/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Multisplit b/Lang/PascalABC.NET/Multisplit new file mode 120000 index 0000000000..cacc0acc3b --- /dev/null +++ b/Lang/PascalABC.NET/Multisplit @@ -0,0 +1 @@ +../../Task/Multisplit/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Munchausen-numbers b/Lang/PascalABC.NET/Munchausen-numbers new file mode 120000 index 0000000000..e5388bf0cf --- /dev/null +++ b/Lang/PascalABC.NET/Munchausen-numbers @@ -0,0 +1 @@ +../../Task/Munchausen-numbers/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Musical-scale b/Lang/PascalABC.NET/Musical-scale new file mode 120000 index 0000000000..33d370124c --- /dev/null +++ b/Lang/PascalABC.NET/Musical-scale @@ -0,0 +1 @@ +../../Task/Musical-scale/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Mutual-recursion b/Lang/PascalABC.NET/Mutual-recursion new file mode 120000 index 0000000000..ccdccec66f --- /dev/null +++ b/Lang/PascalABC.NET/Mutual-recursion @@ -0,0 +1 @@ +../../Task/Mutual-recursion/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/N-queens-problem b/Lang/PascalABC.NET/N-queens-problem new file mode 120000 index 0000000000..d0df5430cc --- /dev/null +++ b/Lang/PascalABC.NET/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Named-parameters b/Lang/PascalABC.NET/Named-parameters new file mode 120000 index 0000000000..f91e295fc0 --- /dev/null +++ b/Lang/PascalABC.NET/Named-parameters @@ -0,0 +1 @@ +../../Task/Named-parameters/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Naming-conventions b/Lang/PascalABC.NET/Naming-conventions new file mode 120000 index 0000000000..5fc365228c --- /dev/null +++ b/Lang/PascalABC.NET/Naming-conventions @@ -0,0 +1 @@ +../../Task/Naming-conventions/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Narcissistic-decimal-number b/Lang/PascalABC.NET/Narcissistic-decimal-number new file mode 120000 index 0000000000..6e25078669 --- /dev/null +++ b/Lang/PascalABC.NET/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Nested-function b/Lang/PascalABC.NET/Nested-function new file mode 120000 index 0000000000..406d1380f0 --- /dev/null +++ b/Lang/PascalABC.NET/Nested-function @@ -0,0 +1 @@ +../../Task/Nested-function/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Next-highest-int-from-digits b/Lang/PascalABC.NET/Next-highest-int-from-digits new file mode 120000 index 0000000000..f57c5311ba --- /dev/null +++ b/Lang/PascalABC.NET/Next-highest-int-from-digits @@ -0,0 +1 @@ +../../Task/Next-highest-int-from-digits/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Nim-game b/Lang/PascalABC.NET/Nim-game new file mode 120000 index 0000000000..11fed8b04f --- /dev/null +++ b/Lang/PascalABC.NET/Nim-game @@ -0,0 +1 @@ +../../Task/Nim-game/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Non-continuous-subsequences b/Lang/PascalABC.NET/Non-continuous-subsequences new file mode 120000 index 0000000000..fb90313f8e --- /dev/null +++ b/Lang/PascalABC.NET/Non-continuous-subsequences @@ -0,0 +1 @@ +../../Task/Non-continuous-subsequences/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Nonoblock b/Lang/PascalABC.NET/Nonoblock new file mode 120000 index 0000000000..27ec8aac45 --- /dev/null +++ b/Lang/PascalABC.NET/Nonoblock @@ -0,0 +1 @@ +../../Task/Nonoblock/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Nth b/Lang/PascalABC.NET/Nth new file mode 120000 index 0000000000..2151e00c8d --- /dev/null +++ b/Lang/PascalABC.NET/Nth @@ -0,0 +1 @@ +../../Task/Nth/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Null-object b/Lang/PascalABC.NET/Null-object new file mode 120000 index 0000000000..39b6da0acb --- /dev/null +++ b/Lang/PascalABC.NET/Null-object @@ -0,0 +1 @@ +../../Task/Null-object/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Numbers-which-are-not-the-sum-of-distinct-squares b/Lang/PascalABC.NET/Numbers-which-are-not-the-sum-of-distinct-squares new file mode 120000 index 0000000000..11f633b289 --- /dev/null +++ b/Lang/PascalABC.NET/Numbers-which-are-not-the-sum-of-distinct-squares @@ -0,0 +1 @@ +../../Task/Numbers-which-are-not-the-sum-of-distinct-squares/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Numbers-which-are-the-cube-roots-of-the-product-of-their-proper-divisors b/Lang/PascalABC.NET/Numbers-which-are-the-cube-roots-of-the-product-of-their-proper-divisors new file mode 120000 index 0000000000..3b98dabeae --- /dev/null +++ b/Lang/PascalABC.NET/Numbers-which-are-the-cube-roots-of-the-product-of-their-proper-divisors @@ -0,0 +1 @@ +../../Task/Numbers-which-are-the-cube-roots-of-the-product-of-their-proper-divisors/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Numbers-with-equal-rises-and-falls b/Lang/PascalABC.NET/Numbers-with-equal-rises-and-falls new file mode 120000 index 0000000000..265a6e57f2 --- /dev/null +++ b/Lang/PascalABC.NET/Numbers-with-equal-rises-and-falls @@ -0,0 +1 @@ +../../Task/Numbers-with-equal-rises-and-falls/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Numeric-error-propagation b/Lang/PascalABC.NET/Numeric-error-propagation new file mode 120000 index 0000000000..b8b2e6d9b5 --- /dev/null +++ b/Lang/PascalABC.NET/Numeric-error-propagation @@ -0,0 +1 @@ +../../Task/Numeric-error-propagation/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Numerical-integration b/Lang/PascalABC.NET/Numerical-integration new file mode 120000 index 0000000000..dc5bfcc884 --- /dev/null +++ b/Lang/PascalABC.NET/Numerical-integration @@ -0,0 +1 @@ +../../Task/Numerical-integration/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Object-serialization b/Lang/PascalABC.NET/Object-serialization new file mode 120000 index 0000000000..07426b45b7 --- /dev/null +++ b/Lang/PascalABC.NET/Object-serialization @@ -0,0 +1 @@ +../../Task/Object-serialization/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Odd-word-problem b/Lang/PascalABC.NET/Odd-word-problem new file mode 120000 index 0000000000..b0936fb34b --- /dev/null +++ b/Lang/PascalABC.NET/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/One-dimensional-cellular-automata b/Lang/PascalABC.NET/One-dimensional-cellular-automata new file mode 120000 index 0000000000..19b52c40ec --- /dev/null +++ b/Lang/PascalABC.NET/One-dimensional-cellular-automata @@ -0,0 +1 @@ +../../Task/One-dimensional-cellular-automata/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/One-of-n-lines-in-a-file b/Lang/PascalABC.NET/One-of-n-lines-in-a-file new file mode 120000 index 0000000000..6a1426ac8c --- /dev/null +++ b/Lang/PascalABC.NET/One-of-n-lines-in-a-file @@ -0,0 +1 @@ +../../Task/One-of-n-lines-in-a-file/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/OpenWebNet-password b/Lang/PascalABC.NET/OpenWebNet-password new file mode 120000 index 0000000000..41ce8aa36a --- /dev/null +++ b/Lang/PascalABC.NET/OpenWebNet-password @@ -0,0 +1 @@ +../../Task/OpenWebNet-password/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Operator-precedence b/Lang/PascalABC.NET/Operator-precedence new file mode 120000 index 0000000000..08a1b040c3 --- /dev/null +++ b/Lang/PascalABC.NET/Operator-precedence @@ -0,0 +1 @@ +../../Task/Operator-precedence/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Order-two-numerical-lists b/Lang/PascalABC.NET/Order-two-numerical-lists new file mode 120000 index 0000000000..8f392c8ff3 --- /dev/null +++ b/Lang/PascalABC.NET/Order-two-numerical-lists @@ -0,0 +1 @@ +../../Task/Order-two-numerical-lists/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Ordered-words b/Lang/PascalABC.NET/Ordered-words new file mode 120000 index 0000000000..d3217a2d03 --- /dev/null +++ b/Lang/PascalABC.NET/Ordered-words @@ -0,0 +1 @@ +../../Task/Ordered-words/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Padovan-n-step-number-sequences b/Lang/PascalABC.NET/Padovan-n-step-number-sequences new file mode 120000 index 0000000000..2e49ed2259 --- /dev/null +++ b/Lang/PascalABC.NET/Padovan-n-step-number-sequences @@ -0,0 +1 @@ +../../Task/Padovan-n-step-number-sequences/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Padovan-sequence b/Lang/PascalABC.NET/Padovan-sequence new file mode 120000 index 0000000000..c2c68fb6dd --- /dev/null +++ b/Lang/PascalABC.NET/Padovan-sequence @@ -0,0 +1 @@ +../../Task/Padovan-sequence/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Palindrome-dates b/Lang/PascalABC.NET/Palindrome-dates new file mode 120000 index 0000000000..09644b6a7c --- /dev/null +++ b/Lang/PascalABC.NET/Palindrome-dates @@ -0,0 +1 @@ +../../Task/Palindrome-dates/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Palindrome-detection b/Lang/PascalABC.NET/Palindrome-detection new file mode 120000 index 0000000000..cc92721e9f --- /dev/null +++ b/Lang/PascalABC.NET/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Palindromic-gapful-numbers b/Lang/PascalABC.NET/Palindromic-gapful-numbers new file mode 120000 index 0000000000..532e5bda78 --- /dev/null +++ b/Lang/PascalABC.NET/Palindromic-gapful-numbers @@ -0,0 +1 @@ +../../Task/Palindromic-gapful-numbers/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Pancake-numbers b/Lang/PascalABC.NET/Pancake-numbers new file mode 120000 index 0000000000..b4faf1b68d --- /dev/null +++ b/Lang/PascalABC.NET/Pancake-numbers @@ -0,0 +1 @@ +../../Task/Pancake-numbers/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Pangram-checker b/Lang/PascalABC.NET/Pangram-checker new file mode 120000 index 0000000000..114e870600 --- /dev/null +++ b/Lang/PascalABC.NET/Pangram-checker @@ -0,0 +1 @@ +../../Task/Pangram-checker/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Paraffins b/Lang/PascalABC.NET/Paraffins new file mode 120000 index 0000000000..bafd6e0939 --- /dev/null +++ b/Lang/PascalABC.NET/Paraffins @@ -0,0 +1 @@ +../../Task/Paraffins/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Parallel-calculations b/Lang/PascalABC.NET/Parallel-calculations new file mode 120000 index 0000000000..e88e92c1df --- /dev/null +++ b/Lang/PascalABC.NET/Parallel-calculations @@ -0,0 +1 @@ +../../Task/Parallel-calculations/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Parametric-polymorphism b/Lang/PascalABC.NET/Parametric-polymorphism new file mode 120000 index 0000000000..7c242be133 --- /dev/null +++ b/Lang/PascalABC.NET/Parametric-polymorphism @@ -0,0 +1 @@ +../../Task/Parametric-polymorphism/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Parsing-RPN-calculator-algorithm b/Lang/PascalABC.NET/Parsing-RPN-calculator-algorithm new file mode 120000 index 0000000000..c4ae7949cd --- /dev/null +++ b/Lang/PascalABC.NET/Parsing-RPN-calculator-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-RPN-calculator-algorithm/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Partition-an-integer-x-into-n-primes b/Lang/PascalABC.NET/Partition-an-integer-x-into-n-primes new file mode 120000 index 0000000000..eb7a5e97f7 --- /dev/null +++ b/Lang/PascalABC.NET/Partition-an-integer-x-into-n-primes @@ -0,0 +1 @@ +../../Task/Partition-an-integer-x-into-n-primes/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Partition-function-P b/Lang/PascalABC.NET/Partition-function-P new file mode 120000 index 0000000000..e780cc5e40 --- /dev/null +++ b/Lang/PascalABC.NET/Partition-function-P @@ -0,0 +1 @@ +../../Task/Partition-function-P/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Pascal-matrix-generation b/Lang/PascalABC.NET/Pascal-matrix-generation new file mode 120000 index 0000000000..c8097eca88 --- /dev/null +++ b/Lang/PascalABC.NET/Pascal-matrix-generation @@ -0,0 +1 @@ +../../Task/Pascal-matrix-generation/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Pascals-triangle b/Lang/PascalABC.NET/Pascals-triangle new file mode 120000 index 0000000000..1089718a97 --- /dev/null +++ b/Lang/PascalABC.NET/Pascals-triangle @@ -0,0 +1 @@ +../../Task/Pascals-triangle/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Pascals-triangle-Puzzle b/Lang/PascalABC.NET/Pascals-triangle-Puzzle new file mode 120000 index 0000000000..8106a5db3a --- /dev/null +++ b/Lang/PascalABC.NET/Pascals-triangle-Puzzle @@ -0,0 +1 @@ +../../Task/Pascals-triangle-Puzzle/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Pathological-floating-point-problems b/Lang/PascalABC.NET/Pathological-floating-point-problems new file mode 120000 index 0000000000..7eaa34e4a8 --- /dev/null +++ b/Lang/PascalABC.NET/Pathological-floating-point-problems @@ -0,0 +1 @@ +../../Task/Pathological-floating-point-problems/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Pells-equation b/Lang/PascalABC.NET/Pells-equation new file mode 120000 index 0000000000..1729f4ebb8 --- /dev/null +++ b/Lang/PascalABC.NET/Pells-equation @@ -0,0 +1 @@ +../../Task/Pells-equation/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Perfect-shuffle b/Lang/PascalABC.NET/Perfect-shuffle new file mode 120000 index 0000000000..5ea5d5cf28 --- /dev/null +++ b/Lang/PascalABC.NET/Perfect-shuffle @@ -0,0 +1 @@ +../../Task/Perfect-shuffle/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Perfect-totient-numbers b/Lang/PascalABC.NET/Perfect-totient-numbers new file mode 120000 index 0000000000..8aae312612 --- /dev/null +++ b/Lang/PascalABC.NET/Perfect-totient-numbers @@ -0,0 +1 @@ +../../Task/Perfect-totient-numbers/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Permutation-test b/Lang/PascalABC.NET/Permutation-test new file mode 120000 index 0000000000..38efc59733 --- /dev/null +++ b/Lang/PascalABC.NET/Permutation-test @@ -0,0 +1 @@ +../../Task/Permutation-test/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Permutations b/Lang/PascalABC.NET/Permutations new file mode 120000 index 0000000000..e1329591d7 --- /dev/null +++ b/Lang/PascalABC.NET/Permutations @@ -0,0 +1 @@ +../../Task/Permutations/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Permutations-Derangements b/Lang/PascalABC.NET/Permutations-Derangements new file mode 120000 index 0000000000..4c7dd2b64b --- /dev/null +++ b/Lang/PascalABC.NET/Permutations-Derangements @@ -0,0 +1 @@ +../../Task/Permutations-Derangements/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Pick-random-element b/Lang/PascalABC.NET/Pick-random-element new file mode 120000 index 0000000000..9dd6351bad --- /dev/null +++ b/Lang/PascalABC.NET/Pick-random-element @@ -0,0 +1 @@ +../../Task/Pick-random-element/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Plot-coordinate-pairs b/Lang/PascalABC.NET/Plot-coordinate-pairs new file mode 120000 index 0000000000..4d0282311b --- /dev/null +++ b/Lang/PascalABC.NET/Plot-coordinate-pairs @@ -0,0 +1 @@ +../../Task/Plot-coordinate-pairs/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Pointers-and-references b/Lang/PascalABC.NET/Pointers-and-references new file mode 120000 index 0000000000..6985ca1666 --- /dev/null +++ b/Lang/PascalABC.NET/Pointers-and-references @@ -0,0 +1 @@ +../../Task/Pointers-and-references/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Polymorphic-copy b/Lang/PascalABC.NET/Polymorphic-copy new file mode 120000 index 0000000000..7ed8b814ad --- /dev/null +++ b/Lang/PascalABC.NET/Polymorphic-copy @@ -0,0 +1 @@ +../../Task/Polymorphic-copy/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Polymorphism b/Lang/PascalABC.NET/Polymorphism new file mode 120000 index 0000000000..4996bdacfd --- /dev/null +++ b/Lang/PascalABC.NET/Polymorphism @@ -0,0 +1 @@ +../../Task/Polymorphism/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Population-count b/Lang/PascalABC.NET/Population-count new file mode 120000 index 0000000000..742c56a591 --- /dev/null +++ b/Lang/PascalABC.NET/Population-count @@ -0,0 +1 @@ +../../Task/Population-count/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Power-set b/Lang/PascalABC.NET/Power-set new file mode 120000 index 0000000000..042d839f30 --- /dev/null +++ b/Lang/PascalABC.NET/Power-set @@ -0,0 +1 @@ +../../Task/Power-set/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Primality-by-trial-division b/Lang/PascalABC.NET/Primality-by-trial-division new file mode 120000 index 0000000000..62ca027b6e --- /dev/null +++ b/Lang/PascalABC.NET/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Prime-decomposition b/Lang/PascalABC.NET/Prime-decomposition new file mode 120000 index 0000000000..ea96188341 --- /dev/null +++ b/Lang/PascalABC.NET/Prime-decomposition @@ -0,0 +1 @@ +../../Task/Prime-decomposition/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Program-name b/Lang/PascalABC.NET/Program-name new file mode 120000 index 0000000000..6bdce5a90a --- /dev/null +++ b/Lang/PascalABC.NET/Program-name @@ -0,0 +1 @@ +../../Task/Program-name/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Program-termination b/Lang/PascalABC.NET/Program-termination new file mode 120000 index 0000000000..63645717ea --- /dev/null +++ b/Lang/PascalABC.NET/Program-termination @@ -0,0 +1 @@ +../../Task/Program-termination/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Queue-Definition b/Lang/PascalABC.NET/Queue-Definition new file mode 120000 index 0000000000..efb10e6df2 --- /dev/null +++ b/Lang/PascalABC.NET/Queue-Definition @@ -0,0 +1 @@ +../../Task/Queue-Definition/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Queue-Usage b/Lang/PascalABC.NET/Queue-Usage new file mode 120000 index 0000000000..eab42cf449 --- /dev/null +++ b/Lang/PascalABC.NET/Queue-Usage @@ -0,0 +1 @@ +../../Task/Queue-Usage/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Quine b/Lang/PascalABC.NET/Quine new file mode 120000 index 0000000000..98ce8f9f2f --- /dev/null +++ b/Lang/PascalABC.NET/Quine @@ -0,0 +1 @@ +../../Task/Quine/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Quoting-constructs b/Lang/PascalABC.NET/Quoting-constructs new file mode 120000 index 0000000000..971db935d4 --- /dev/null +++ b/Lang/PascalABC.NET/Quoting-constructs @@ -0,0 +1 @@ +../../Task/Quoting-constructs/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/RPG-attributes-generator b/Lang/PascalABC.NET/RPG-attributes-generator new file mode 120000 index 0000000000..ddbe45c835 --- /dev/null +++ b/Lang/PascalABC.NET/RPG-attributes-generator @@ -0,0 +1 @@ +../../Task/RPG-attributes-generator/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Radical-of-an-integer b/Lang/PascalABC.NET/Radical-of-an-integer new file mode 120000 index 0000000000..430a252ecf --- /dev/null +++ b/Lang/PascalABC.NET/Radical-of-an-integer @@ -0,0 +1 @@ +../../Task/Radical-of-an-integer/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Ramer-Douglas-Peucker-line-simplification b/Lang/PascalABC.NET/Ramer-Douglas-Peucker-line-simplification new file mode 120000 index 0000000000..31e2b26ec5 --- /dev/null +++ b/Lang/PascalABC.NET/Ramer-Douglas-Peucker-line-simplification @@ -0,0 +1 @@ +../../Task/Ramer-Douglas-Peucker-line-simplification/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Random-numbers b/Lang/PascalABC.NET/Random-numbers new file mode 120000 index 0000000000..da187d2cc0 --- /dev/null +++ b/Lang/PascalABC.NET/Random-numbers @@ -0,0 +1 @@ +../../Task/Random-numbers/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Read-a-file-character-by-character-UTF8 b/Lang/PascalABC.NET/Read-a-file-character-by-character-UTF8 new file mode 120000 index 0000000000..a425a12499 --- /dev/null +++ b/Lang/PascalABC.NET/Read-a-file-character-by-character-UTF8 @@ -0,0 +1 @@ +../../Task/Read-a-file-character-by-character-UTF8/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Read-a-file-line-by-line b/Lang/PascalABC.NET/Read-a-file-line-by-line new file mode 120000 index 0000000000..bd96f90ae1 --- /dev/null +++ b/Lang/PascalABC.NET/Read-a-file-line-by-line @@ -0,0 +1 @@ +../../Task/Read-a-file-line-by-line/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Read-a-specific-line-from-a-file b/Lang/PascalABC.NET/Read-a-specific-line-from-a-file new file mode 120000 index 0000000000..28703147aa --- /dev/null +++ b/Lang/PascalABC.NET/Read-a-specific-line-from-a-file @@ -0,0 +1 @@ +../../Task/Read-a-specific-line-from-a-file/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Read-entire-file b/Lang/PascalABC.NET/Read-entire-file new file mode 120000 index 0000000000..20a95b9d77 --- /dev/null +++ b/Lang/PascalABC.NET/Read-entire-file @@ -0,0 +1 @@ +../../Task/Read-entire-file/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Real-constants-and-functions b/Lang/PascalABC.NET/Real-constants-and-functions new file mode 120000 index 0000000000..a6e7dce16d --- /dev/null +++ b/Lang/PascalABC.NET/Real-constants-and-functions @@ -0,0 +1 @@ +../../Task/Real-constants-and-functions/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Reflection-List-methods b/Lang/PascalABC.NET/Reflection-List-methods new file mode 120000 index 0000000000..7e40bca2fa --- /dev/null +++ b/Lang/PascalABC.NET/Reflection-List-methods @@ -0,0 +1 @@ +../../Task/Reflection-List-methods/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Reflection-List-properties b/Lang/PascalABC.NET/Reflection-List-properties new file mode 120000 index 0000000000..ed60f425f0 --- /dev/null +++ b/Lang/PascalABC.NET/Reflection-List-properties @@ -0,0 +1 @@ +../../Task/Reflection-List-properties/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Regular-expressions b/Lang/PascalABC.NET/Regular-expressions new file mode 120000 index 0000000000..a3ccbe1574 --- /dev/null +++ b/Lang/PascalABC.NET/Regular-expressions @@ -0,0 +1 @@ +../../Task/Regular-expressions/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Remove-duplicate-elements b/Lang/PascalABC.NET/Remove-duplicate-elements new file mode 120000 index 0000000000..6f37a5852e --- /dev/null +++ b/Lang/PascalABC.NET/Remove-duplicate-elements @@ -0,0 +1 @@ +../../Task/Remove-duplicate-elements/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Remove-lines-from-a-file b/Lang/PascalABC.NET/Remove-lines-from-a-file new file mode 120000 index 0000000000..6e76bee372 --- /dev/null +++ b/Lang/PascalABC.NET/Remove-lines-from-a-file @@ -0,0 +1 @@ +../../Task/Remove-lines-from-a-file/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Rename-a-file b/Lang/PascalABC.NET/Rename-a-file new file mode 120000 index 0000000000..e7599165d6 --- /dev/null +++ b/Lang/PascalABC.NET/Rename-a-file @@ -0,0 +1 @@ +../../Task/Rename-a-file/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Repeat b/Lang/PascalABC.NET/Repeat new file mode 120000 index 0000000000..e16283f972 --- /dev/null +++ b/Lang/PascalABC.NET/Repeat @@ -0,0 +1 @@ +../../Task/Repeat/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Repeat-a-string b/Lang/PascalABC.NET/Repeat-a-string new file mode 120000 index 0000000000..c21e0bfde3 --- /dev/null +++ b/Lang/PascalABC.NET/Repeat-a-string @@ -0,0 +1 @@ +../../Task/Repeat-a-string/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Return-multiple-values b/Lang/PascalABC.NET/Return-multiple-values new file mode 120000 index 0000000000..5178c8dd1d --- /dev/null +++ b/Lang/PascalABC.NET/Return-multiple-values @@ -0,0 +1 @@ +../../Task/Return-multiple-values/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Reverse-a-string b/Lang/PascalABC.NET/Reverse-a-string new file mode 120000 index 0000000000..8e67838296 --- /dev/null +++ b/Lang/PascalABC.NET/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Reverse-words-in-a-string b/Lang/PascalABC.NET/Reverse-words-in-a-string new file mode 120000 index 0000000000..aa82b64f3b --- /dev/null +++ b/Lang/PascalABC.NET/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Roman-numerals-Decode b/Lang/PascalABC.NET/Roman-numerals-Decode new file mode 120000 index 0000000000..990d667ad0 --- /dev/null +++ b/Lang/PascalABC.NET/Roman-numerals-Decode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Decode/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Roman-numerals-Encode b/Lang/PascalABC.NET/Roman-numerals-Encode new file mode 120000 index 0000000000..c8f15e15fa --- /dev/null +++ b/Lang/PascalABC.NET/Roman-numerals-Encode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Encode/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Roots-of-unity b/Lang/PascalABC.NET/Roots-of-unity new file mode 120000 index 0000000000..31b7a73b39 --- /dev/null +++ b/Lang/PascalABC.NET/Roots-of-unity @@ -0,0 +1 @@ +../../Task/Roots-of-unity/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Rosetta-Code-Rank-languages-by-popularity b/Lang/PascalABC.NET/Rosetta-Code-Rank-languages-by-popularity new file mode 120000 index 0000000000..55aa7d4f0c --- /dev/null +++ b/Lang/PascalABC.NET/Rosetta-Code-Rank-languages-by-popularity @@ -0,0 +1 @@ +../../Task/Rosetta-Code-Rank-languages-by-popularity/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Rot-13 b/Lang/PascalABC.NET/Rot-13 new file mode 120000 index 0000000000..f7c9e778c9 --- /dev/null +++ b/Lang/PascalABC.NET/Rot-13 @@ -0,0 +1 @@ +../../Task/Rot-13/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Scope-modifiers b/Lang/PascalABC.NET/Scope-modifiers new file mode 120000 index 0000000000..eb11f44070 --- /dev/null +++ b/Lang/PascalABC.NET/Scope-modifiers @@ -0,0 +1 @@ +../../Task/Scope-modifiers/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Search-a-list-of-records b/Lang/PascalABC.NET/Search-a-list-of-records new file mode 120000 index 0000000000..7e72a33d4d --- /dev/null +++ b/Lang/PascalABC.NET/Search-a-list-of-records @@ -0,0 +1 @@ +../../Task/Search-a-list-of-records/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Send-an-unknown-method-call b/Lang/PascalABC.NET/Send-an-unknown-method-call new file mode 120000 index 0000000000..2e049c05b3 --- /dev/null +++ b/Lang/PascalABC.NET/Send-an-unknown-method-call @@ -0,0 +1 @@ +../../Task/Send-an-unknown-method-call/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Sequence-of-primes-by-trial-division b/Lang/PascalABC.NET/Sequence-of-primes-by-trial-division new file mode 120000 index 0000000000..4182c218d4 --- /dev/null +++ b/Lang/PascalABC.NET/Sequence-of-primes-by-trial-division @@ -0,0 +1 @@ +../../Task/Sequence-of-primes-by-trial-division/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Short-circuit-evaluation b/Lang/PascalABC.NET/Short-circuit-evaluation new file mode 120000 index 0000000000..582c107471 --- /dev/null +++ b/Lang/PascalABC.NET/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Sierpinski-triangle b/Lang/PascalABC.NET/Sierpinski-triangle new file mode 120000 index 0000000000..7eb8f22264 --- /dev/null +++ b/Lang/PascalABC.NET/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Sieve-of-Eratosthenes b/Lang/PascalABC.NET/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..c9a2623742 --- /dev/null +++ b/Lang/PascalABC.NET/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Simple-windowed-application b/Lang/PascalABC.NET/Simple-windowed-application new file mode 120000 index 0000000000..a619cd32f7 --- /dev/null +++ b/Lang/PascalABC.NET/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Singly-linked-list-Element-definition b/Lang/PascalABC.NET/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..71d3f5d628 --- /dev/null +++ b/Lang/PascalABC.NET/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Singly-linked-list-Element-insertion b/Lang/PascalABC.NET/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..f60548d528 --- /dev/null +++ b/Lang/PascalABC.NET/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Sleep b/Lang/PascalABC.NET/Sleep new file mode 120000 index 0000000000..d8f830cd4f --- /dev/null +++ b/Lang/PascalABC.NET/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Sort-an-array-of-composite-structures b/Lang/PascalABC.NET/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..e0459e8577 --- /dev/null +++ b/Lang/PascalABC.NET/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Sort-an-integer-array b/Lang/PascalABC.NET/Sort-an-integer-array new file mode 120000 index 0000000000..e2137f1191 --- /dev/null +++ b/Lang/PascalABC.NET/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Sort-three-variables b/Lang/PascalABC.NET/Sort-three-variables new file mode 120000 index 0000000000..2143247222 --- /dev/null +++ b/Lang/PascalABC.NET/Sort-three-variables @@ -0,0 +1 @@ +../../Task/Sort-three-variables/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Sort-using-a-custom-comparator b/Lang/PascalABC.NET/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..a2ade4323b --- /dev/null +++ b/Lang/PascalABC.NET/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Sorting-algorithms-Bubble-sort b/Lang/PascalABC.NET/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..75fb7e1472 --- /dev/null +++ b/Lang/PascalABC.NET/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Sorting-algorithms-Quicksort b/Lang/PascalABC.NET/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..d84582d974 --- /dev/null +++ b/Lang/PascalABC.NET/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Special-variables b/Lang/PascalABC.NET/Special-variables new file mode 120000 index 0000000000..00db4953ba --- /dev/null +++ b/Lang/PascalABC.NET/Special-variables @@ -0,0 +1 @@ +../../Task/Special-variables/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Split-a-character-string-based-on-change-of-character b/Lang/PascalABC.NET/Split-a-character-string-based-on-change-of-character new file mode 120000 index 0000000000..b7c7bef74b --- /dev/null +++ b/Lang/PascalABC.NET/Split-a-character-string-based-on-change-of-character @@ -0,0 +1 @@ +../../Task/Split-a-character-string-based-on-change-of-character/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Stack b/Lang/PascalABC.NET/Stack new file mode 120000 index 0000000000..71f695fe1b --- /dev/null +++ b/Lang/PascalABC.NET/Stack @@ -0,0 +1 @@ +../../Task/Stack/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Stack-traces b/Lang/PascalABC.NET/Stack-traces new file mode 120000 index 0000000000..b6976dc3e0 --- /dev/null +++ b/Lang/PascalABC.NET/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Statistics-Basic b/Lang/PascalABC.NET/Statistics-Basic new file mode 120000 index 0000000000..5ef44d7d18 --- /dev/null +++ b/Lang/PascalABC.NET/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/String-append b/Lang/PascalABC.NET/String-append new file mode 120000 index 0000000000..78fd361243 --- /dev/null +++ b/Lang/PascalABC.NET/String-append @@ -0,0 +1 @@ +../../Task/String-append/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/String-case b/Lang/PascalABC.NET/String-case new file mode 120000 index 0000000000..980e55192e --- /dev/null +++ b/Lang/PascalABC.NET/String-case @@ -0,0 +1 @@ +../../Task/String-case/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/String-concatenation b/Lang/PascalABC.NET/String-concatenation new file mode 120000 index 0000000000..d7b52bf492 --- /dev/null +++ b/Lang/PascalABC.NET/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/String-interpolation-included- b/Lang/PascalABC.NET/String-interpolation-included- new file mode 120000 index 0000000000..6a1179d384 --- /dev/null +++ b/Lang/PascalABC.NET/String-interpolation-included- @@ -0,0 +1 @@ +../../Task/String-interpolation-included-/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/String-length b/Lang/PascalABC.NET/String-length new file mode 120000 index 0000000000..1bc629e3ec --- /dev/null +++ b/Lang/PascalABC.NET/String-length @@ -0,0 +1 @@ +../../Task/String-length/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/String-matching b/Lang/PascalABC.NET/String-matching new file mode 120000 index 0000000000..f031375ab5 --- /dev/null +++ b/Lang/PascalABC.NET/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/String-prepend b/Lang/PascalABC.NET/String-prepend new file mode 120000 index 0000000000..205b3e4638 --- /dev/null +++ b/Lang/PascalABC.NET/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Strip-a-set-of-characters-from-a-string b/Lang/PascalABC.NET/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..5548033cde --- /dev/null +++ b/Lang/PascalABC.NET/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Strip-block-comments b/Lang/PascalABC.NET/Strip-block-comments new file mode 120000 index 0000000000..7a95085577 --- /dev/null +++ b/Lang/PascalABC.NET/Strip-block-comments @@ -0,0 +1 @@ +../../Task/Strip-block-comments/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Strip-comments-from-a-string b/Lang/PascalABC.NET/Strip-comments-from-a-string new file mode 120000 index 0000000000..c415553cce --- /dev/null +++ b/Lang/PascalABC.NET/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Strip-control-codes-and-extended-characters-from-a-string b/Lang/PascalABC.NET/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..3175c3c416 --- /dev/null +++ b/Lang/PascalABC.NET/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Strip-whitespace-from-a-string-Top-and-tail b/Lang/PascalABC.NET/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..075fc6a71b --- /dev/null +++ b/Lang/PascalABC.NET/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Substitution-cipher b/Lang/PascalABC.NET/Substitution-cipher new file mode 120000 index 0000000000..5c9f1bb54c --- /dev/null +++ b/Lang/PascalABC.NET/Substitution-cipher @@ -0,0 +1 @@ +../../Task/Substitution-cipher/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Substring b/Lang/PascalABC.NET/Substring new file mode 120000 index 0000000000..f2a607112d --- /dev/null +++ b/Lang/PascalABC.NET/Substring @@ -0,0 +1 @@ +../../Task/Substring/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Substring-Top-and-tail b/Lang/PascalABC.NET/Substring-Top-and-tail new file mode 120000 index 0000000000..b64b9c4948 --- /dev/null +++ b/Lang/PascalABC.NET/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Sudan-function b/Lang/PascalABC.NET/Sudan-function new file mode 120000 index 0000000000..2a6cccd8a5 --- /dev/null +++ b/Lang/PascalABC.NET/Sudan-function @@ -0,0 +1 @@ +../../Task/Sudan-function/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Sum-and-product-of-an-array b/Lang/PascalABC.NET/Sum-and-product-of-an-array new file mode 120000 index 0000000000..5bf49387d6 --- /dev/null +++ b/Lang/PascalABC.NET/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Sum-digits-of-an-integer b/Lang/PascalABC.NET/Sum-digits-of-an-integer new file mode 120000 index 0000000000..84d553224a --- /dev/null +++ b/Lang/PascalABC.NET/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Sum-multiples-of-3-and-5 b/Lang/PascalABC.NET/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..3792b87fe0 --- /dev/null +++ b/Lang/PascalABC.NET/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Sum-of-a-series b/Lang/PascalABC.NET/Sum-of-a-series new file mode 120000 index 0000000000..1c91b8532b --- /dev/null +++ b/Lang/PascalABC.NET/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Sum-of-elements-below-main-diagonal-of-matrix b/Lang/PascalABC.NET/Sum-of-elements-below-main-diagonal-of-matrix new file mode 120000 index 0000000000..055fd11a3e --- /dev/null +++ b/Lang/PascalABC.NET/Sum-of-elements-below-main-diagonal-of-matrix @@ -0,0 +1 @@ +../../Task/Sum-of-elements-below-main-diagonal-of-matrix/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Sum-of-squares b/Lang/PascalABC.NET/Sum-of-squares new file mode 120000 index 0000000000..0d6573d1ec --- /dev/null +++ b/Lang/PascalABC.NET/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Symmetric-difference b/Lang/PascalABC.NET/Symmetric-difference new file mode 120000 index 0000000000..6a0af3805f --- /dev/null +++ b/Lang/PascalABC.NET/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/System-time b/Lang/PascalABC.NET/System-time new file mode 120000 index 0000000000..b4cf3d92cb --- /dev/null +++ b/Lang/PascalABC.NET/System-time @@ -0,0 +1 @@ +../../Task/System-time/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Take-notes-on-the-command-line b/Lang/PascalABC.NET/Take-notes-on-the-command-line new file mode 120000 index 0000000000..ce2c9c51c4 --- /dev/null +++ b/Lang/PascalABC.NET/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Tau-function b/Lang/PascalABC.NET/Tau-function new file mode 120000 index 0000000000..fcb633b959 --- /dev/null +++ b/Lang/PascalABC.NET/Tau-function @@ -0,0 +1 @@ +../../Task/Tau-function/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Tau-number b/Lang/PascalABC.NET/Tau-number new file mode 120000 index 0000000000..4be8374dc0 --- /dev/null +++ b/Lang/PascalABC.NET/Tau-number @@ -0,0 +1 @@ +../../Task/Tau-number/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Teacup-rim-text b/Lang/PascalABC.NET/Teacup-rim-text new file mode 120000 index 0000000000..408b28d813 --- /dev/null +++ b/Lang/PascalABC.NET/Teacup-rim-text @@ -0,0 +1 @@ +../../Task/Teacup-rim-text/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Temperature-conversion b/Lang/PascalABC.NET/Temperature-conversion new file mode 120000 index 0000000000..607c5a8aa1 --- /dev/null +++ b/Lang/PascalABC.NET/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Terminal-control-Clear-the-screen b/Lang/PascalABC.NET/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..ba3f668e83 --- /dev/null +++ b/Lang/PascalABC.NET/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Terminal-control-Coloured-text b/Lang/PascalABC.NET/Terminal-control-Coloured-text new file mode 120000 index 0000000000..26edde266f --- /dev/null +++ b/Lang/PascalABC.NET/Terminal-control-Coloured-text @@ -0,0 +1 @@ +../../Task/Terminal-control-Coloured-text/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Terminal-control-Cursor-movement b/Lang/PascalABC.NET/Terminal-control-Cursor-movement new file mode 120000 index 0000000000..75b038bfd2 --- /dev/null +++ b/Lang/PascalABC.NET/Terminal-control-Cursor-movement @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-movement/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Terminal-control-Cursor-positioning b/Lang/PascalABC.NET/Terminal-control-Cursor-positioning new file mode 120000 index 0000000000..440e989070 --- /dev/null +++ b/Lang/PascalABC.NET/Terminal-control-Cursor-positioning @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-positioning/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Terminal-control-Dimensions b/Lang/PascalABC.NET/Terminal-control-Dimensions new file mode 120000 index 0000000000..294b1506e4 --- /dev/null +++ b/Lang/PascalABC.NET/Terminal-control-Dimensions @@ -0,0 +1 @@ +../../Task/Terminal-control-Dimensions/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Terminal-control-Display-an-extended-character b/Lang/PascalABC.NET/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..51ff55a04f --- /dev/null +++ b/Lang/PascalABC.NET/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Terminal-control-Hiding-the-cursor b/Lang/PascalABC.NET/Terminal-control-Hiding-the-cursor new file mode 120000 index 0000000000..0f79ee5b6d --- /dev/null +++ b/Lang/PascalABC.NET/Terminal-control-Hiding-the-cursor @@ -0,0 +1 @@ +../../Task/Terminal-control-Hiding-the-cursor/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Terminal-control-Ringing-the-terminal-bell b/Lang/PascalABC.NET/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..dbea7c8c1b --- /dev/null +++ b/Lang/PascalABC.NET/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Test-a-function b/Lang/PascalABC.NET/Test-a-function new file mode 120000 index 0000000000..561aaeccdd --- /dev/null +++ b/Lang/PascalABC.NET/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Time-a-function b/Lang/PascalABC.NET/Time-a-function new file mode 120000 index 0000000000..2c161d3642 --- /dev/null +++ b/Lang/PascalABC.NET/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Tokenize-a-string b/Lang/PascalABC.NET/Tokenize-a-string new file mode 120000 index 0000000000..790ef58cc8 --- /dev/null +++ b/Lang/PascalABC.NET/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Top-rank-per-group b/Lang/PascalABC.NET/Top-rank-per-group new file mode 120000 index 0000000000..09da721479 --- /dev/null +++ b/Lang/PascalABC.NET/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Totient-function b/Lang/PascalABC.NET/Totient-function new file mode 120000 index 0000000000..cbbd5dcdf5 --- /dev/null +++ b/Lang/PascalABC.NET/Totient-function @@ -0,0 +1 @@ +../../Task/Totient-function/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Towers-of-Hanoi b/Lang/PascalABC.NET/Towers-of-Hanoi new file mode 120000 index 0000000000..2c8ecfee74 --- /dev/null +++ b/Lang/PascalABC.NET/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Trabb-Pardo-Knuth-algorithm b/Lang/PascalABC.NET/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..c211c9d9e3 --- /dev/null +++ b/Lang/PascalABC.NET/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Transliterate-English-text-using-the-Greek-alphabet b/Lang/PascalABC.NET/Transliterate-English-text-using-the-Greek-alphabet new file mode 120000 index 0000000000..d24a02b5a0 --- /dev/null +++ b/Lang/PascalABC.NET/Transliterate-English-text-using-the-Greek-alphabet @@ -0,0 +1 @@ +../../Task/Transliterate-English-text-using-the-Greek-alphabet/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Tree-datastructures b/Lang/PascalABC.NET/Tree-datastructures new file mode 120000 index 0000000000..2b711cc827 --- /dev/null +++ b/Lang/PascalABC.NET/Tree-datastructures @@ -0,0 +1 @@ +../../Task/Tree-datastructures/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Tree-traversal b/Lang/PascalABC.NET/Tree-traversal new file mode 120000 index 0000000000..7b8540d436 --- /dev/null +++ b/Lang/PascalABC.NET/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Trigonometric-functions b/Lang/PascalABC.NET/Trigonometric-functions new file mode 120000 index 0000000000..90b97e3cc1 --- /dev/null +++ b/Lang/PascalABC.NET/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Truncate-a-file b/Lang/PascalABC.NET/Truncate-a-file new file mode 120000 index 0000000000..e41951adf8 --- /dev/null +++ b/Lang/PascalABC.NET/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Twos-complement b/Lang/PascalABC.NET/Twos-complement new file mode 120000 index 0000000000..b0daea87d5 --- /dev/null +++ b/Lang/PascalABC.NET/Twos-complement @@ -0,0 +1 @@ +../../Task/Twos-complement/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/URL-decoding b/Lang/PascalABC.NET/URL-decoding new file mode 120000 index 0000000000..bb79d3d611 --- /dev/null +++ b/Lang/PascalABC.NET/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/URL-encoding b/Lang/PascalABC.NET/URL-encoding new file mode 120000 index 0000000000..4e193b1e1d --- /dev/null +++ b/Lang/PascalABC.NET/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Undefined-values b/Lang/PascalABC.NET/Undefined-values new file mode 120000 index 0000000000..799f03aa4e --- /dev/null +++ b/Lang/PascalABC.NET/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Unicode-strings b/Lang/PascalABC.NET/Unicode-strings new file mode 120000 index 0000000000..1596fd402d --- /dev/null +++ b/Lang/PascalABC.NET/Unicode-strings @@ -0,0 +1 @@ +../../Task/Unicode-strings/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Unicode-variable-names b/Lang/PascalABC.NET/Unicode-variable-names new file mode 120000 index 0000000000..356bcbe63e --- /dev/null +++ b/Lang/PascalABC.NET/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/User-input-Text b/Lang/PascalABC.NET/User-input-Text new file mode 120000 index 0000000000..c49d403c30 --- /dev/null +++ b/Lang/PascalABC.NET/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Variables b/Lang/PascalABC.NET/Variables new file mode 120000 index 0000000000..fb0f3cb656 --- /dev/null +++ b/Lang/PascalABC.NET/Variables @@ -0,0 +1 @@ +../../Task/Variables/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Variadic-function b/Lang/PascalABC.NET/Variadic-function new file mode 120000 index 0000000000..c1bc454958 --- /dev/null +++ b/Lang/PascalABC.NET/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Vector b/Lang/PascalABC.NET/Vector new file mode 120000 index 0000000000..d45a06a593 --- /dev/null +++ b/Lang/PascalABC.NET/Vector @@ -0,0 +1 @@ +../../Task/Vector/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Vector-products b/Lang/PascalABC.NET/Vector-products new file mode 120000 index 0000000000..8bc6e1a1f1 --- /dev/null +++ b/Lang/PascalABC.NET/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Walk-a-directory-Non-recursively b/Lang/PascalABC.NET/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..117d045320 --- /dev/null +++ b/Lang/PascalABC.NET/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Walk-a-directory-Recursively b/Lang/PascalABC.NET/Walk-a-directory-Recursively new file mode 120000 index 0000000000..6fba185f99 --- /dev/null +++ b/Lang/PascalABC.NET/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Window-creation b/Lang/PascalABC.NET/Window-creation new file mode 120000 index 0000000000..c656ea2a7f --- /dev/null +++ b/Lang/PascalABC.NET/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Word-frequency b/Lang/PascalABC.NET/Word-frequency new file mode 120000 index 0000000000..eed444f9fc --- /dev/null +++ b/Lang/PascalABC.NET/Word-frequency @@ -0,0 +1 @@ +../../Task/Word-frequency/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Word-wrap b/Lang/PascalABC.NET/Word-wrap new file mode 120000 index 0000000000..b2cbb831f8 --- /dev/null +++ b/Lang/PascalABC.NET/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Write-entire-file b/Lang/PascalABC.NET/Write-entire-file new file mode 120000 index 0000000000..fb24fa3029 --- /dev/null +++ b/Lang/PascalABC.NET/Write-entire-file @@ -0,0 +1 @@ +../../Task/Write-entire-file/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Write-to-Windows-event-log b/Lang/PascalABC.NET/Write-to-Windows-event-log new file mode 120000 index 0000000000..556c794eaf --- /dev/null +++ b/Lang/PascalABC.NET/Write-to-Windows-event-log @@ -0,0 +1 @@ +../../Task/Write-to-Windows-event-log/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/XML-DOM-serialization b/Lang/PascalABC.NET/XML-DOM-serialization new file mode 120000 index 0000000000..ac8822f809 --- /dev/null +++ b/Lang/PascalABC.NET/XML-DOM-serialization @@ -0,0 +1 @@ +../../Task/XML-DOM-serialization/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/XML-Input b/Lang/PascalABC.NET/XML-Input new file mode 120000 index 0000000000..6c693b433f --- /dev/null +++ b/Lang/PascalABC.NET/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/XML-Output b/Lang/PascalABC.NET/XML-Output new file mode 120000 index 0000000000..c33649037e --- /dev/null +++ b/Lang/PascalABC.NET/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Zero-to-the-zero-power b/Lang/PascalABC.NET/Zero-to-the-zero-power new file mode 120000 index 0000000000..315543b2a3 --- /dev/null +++ b/Lang/PascalABC.NET/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/PascalABC.NET \ No newline at end of file diff --git a/Lang/Perl/Bioinformatics-base-count b/Lang/Perl/Bioinformatics-base-count deleted file mode 120000 index 38044107bd..0000000000 --- a/Lang/Perl/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Perl \ No newline at end of file diff --git a/Lang/Perl/Compare-sorting-algorithms-performance b/Lang/Perl/Compare-sorting-algorithms-performance new file mode 120000 index 0000000000..a54a5351fe --- /dev/null +++ b/Lang/Perl/Compare-sorting-algorithms-performance @@ -0,0 +1 @@ +../../Task/Compare-sorting-algorithms-performance/Perl \ No newline at end of file diff --git a/Lang/Perl/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- b/Lang/Perl/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- new file mode 120000 index 0000000000..bc2932bdb0 --- /dev/null +++ b/Lang/Perl/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n-/Perl \ No newline at end of file diff --git a/Lang/Perl/Execute-Computer-Zero b/Lang/Perl/Execute-Computer-Zero new file mode 120000 index 0000000000..f5f02da865 --- /dev/null +++ b/Lang/Perl/Execute-Computer-Zero @@ -0,0 +1 @@ +../../Task/Execute-Computer-Zero/Perl \ No newline at end of file diff --git a/Lang/Perl/K-d-tree b/Lang/Perl/K-d-tree new file mode 120000 index 0000000000..1cd4d50962 --- /dev/null +++ b/Lang/Perl/K-d-tree @@ -0,0 +1 @@ +../../Task/K-d-tree/Perl \ No newline at end of file diff --git a/Lang/Perl/Machine-code b/Lang/Perl/Machine-code new file mode 120000 index 0000000000..4729cd6042 --- /dev/null +++ b/Lang/Perl/Machine-code @@ -0,0 +1 @@ +../../Task/Machine-code/Perl \ No newline at end of file diff --git a/Lang/Perl/Meissel-Mertens-constant b/Lang/Perl/Meissel-Mertens-constant deleted file mode 120000 index d5ec169595..0000000000 --- a/Lang/Perl/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/Perl \ No newline at end of file diff --git a/Lang/Perl/Miller-Rabin-primality-test b/Lang/Perl/Miller-Rabin-primality-test deleted file mode 120000 index f2d8f376aa..0000000000 --- a/Lang/Perl/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Perl \ No newline at end of file diff --git a/Lang/Perl/Prime-numbers-whose-neighboring-pairs-are-tetraprimes b/Lang/Perl/Prime-numbers-whose-neighboring-pairs-are-tetraprimes new file mode 120000 index 0000000000..fc79cb9bd2 --- /dev/null +++ b/Lang/Perl/Prime-numbers-whose-neighboring-pairs-are-tetraprimes @@ -0,0 +1 @@ +../../Task/Prime-numbers-whose-neighboring-pairs-are-tetraprimes/Perl \ No newline at end of file diff --git a/Lang/Perl/Quaternion-type b/Lang/Perl/Quaternion-type deleted file mode 120000 index 6c26830ce6..0000000000 --- a/Lang/Perl/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Perl \ No newline at end of file diff --git a/Lang/Perl/Search-in-paragraphs-text b/Lang/Perl/Search-in-paragraphs-text new file mode 120000 index 0000000000..3327049060 --- /dev/null +++ b/Lang/Perl/Search-in-paragraphs-text @@ -0,0 +1 @@ +../../Task/Search-in-paragraphs-text/Perl \ No newline at end of file diff --git a/Lang/Perl/Singular-value-decomposition b/Lang/Perl/Singular-value-decomposition new file mode 120000 index 0000000000..0fe6468df6 --- /dev/null +++ b/Lang/Perl/Singular-value-decomposition @@ -0,0 +1 @@ +../../Task/Singular-value-decomposition/Perl \ No newline at end of file diff --git a/Lang/Perl/Sorting-Algorithms-Circle-Sort b/Lang/Perl/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index dec6111fc4..0000000000 --- a/Lang/Perl/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Perl \ No newline at end of file diff --git a/Lang/Perl/Steffensens-method b/Lang/Perl/Steffensens-method new file mode 120000 index 0000000000..3b3d8146aa --- /dev/null +++ b/Lang/Perl/Steffensens-method @@ -0,0 +1 @@ +../../Task/Steffensens-method/Perl \ No newline at end of file diff --git a/Lang/Perl/Strassens-algorithm b/Lang/Perl/Strassens-algorithm new file mode 120000 index 0000000000..013c3f70b0 --- /dev/null +++ b/Lang/Perl/Strassens-algorithm @@ -0,0 +1 @@ +../../Task/Strassens-algorithm/Perl \ No newline at end of file diff --git a/Lang/Perl/Tropical-algebra-overloading b/Lang/Perl/Tropical-algebra-overloading new file mode 120000 index 0000000000..380da329d3 --- /dev/null +++ b/Lang/Perl/Tropical-algebra-overloading @@ -0,0 +1 @@ +../../Task/Tropical-algebra-overloading/Perl \ No newline at end of file diff --git a/Lang/Phix/00-LANG.txt b/Lang/Phix/00-LANG.txt index cbc88ce28e..7a127fa93c 100644 --- a/Lang/Phix/00-LANG.txt +++ b/Lang/Phix/00-LANG.txt @@ -11,13 +11,13 @@ |LCT=yes |bnf=http://phix.x10.mx/bnf.php }} -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]. +Phix is a self-hosted hybrid interpreter/compiler, developed by Pete Lomax.
    + -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.) +On 26th December 2021, Phix became the first language on this site to have [https://rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_popularity/Full_list?oldid=294533 submissions for 100%] of all tasks.
    +(On 20th June 2022 [[Wren]] became the second, albeit there are [https://www.rosettacode.org/wiki/Category:WrenGo 13]+[https://rosettacode.org/wiki/Special:Search?search=wren.h&wprov=acrw1_-1 66] of those I have never been able 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. +[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 demos. 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] diff --git a/Lang/Phix/Bioinformatics-base-count b/Lang/Phix/Bioinformatics-base-count deleted file mode 120000 index 88d72c5b75..0000000000 --- a/Lang/Phix/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Phix \ No newline at end of file diff --git a/Lang/Phix/Meissel-Mertens-constant b/Lang/Phix/Meissel-Mertens-constant deleted file mode 120000 index a9b8084fb5..0000000000 --- a/Lang/Phix/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/Phix \ No newline at end of file diff --git a/Lang/Phix/Miller-Rabin-primality-test b/Lang/Phix/Miller-Rabin-primality-test deleted file mode 120000 index 440728dd57..0000000000 --- a/Lang/Phix/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Phix \ No newline at end of file diff --git a/Lang/Phix/Quaternion-type b/Lang/Phix/Quaternion-type deleted file mode 120000 index bae473b66e..0000000000 --- a/Lang/Phix/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Phix \ No newline at end of file diff --git a/Lang/Phix/Sorting-Algorithms-Circle-Sort b/Lang/Phix/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 2aea38718d..0000000000 --- a/Lang/Phix/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Phix \ No newline at end of file diff --git a/Lang/Picat/Bioinformatics-base-count b/Lang/Picat/Bioinformatics-base-count deleted file mode 120000 index c724eb719d..0000000000 --- a/Lang/Picat/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Picat \ No newline at end of file diff --git a/Lang/Picat/Quaternion-type b/Lang/Picat/Quaternion-type deleted file mode 120000 index e15dda2aeb..0000000000 --- a/Lang/Picat/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Picat \ No newline at end of file diff --git a/Lang/Pico-8/00-LANG.txt b/Lang/Pico-8/00-LANG.txt new file mode 100644 index 0000000000..017ddd4004 --- /dev/null +++ b/Lang/Pico-8/00-LANG.txt @@ -0,0 +1 @@ +{{stub}}{{language|Pico-8}} \ No newline at end of file diff --git a/Lang/Pico-8/00-META.yaml b/Lang/Pico-8/00-META.yaml new file mode 100644 index 0000000000..5d0c380905 --- /dev/null +++ b/Lang/Pico-8/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Pico-8 diff --git a/Lang/Pico-8/Hello-world-Text b/Lang/Pico-8/Hello-world-Text new file mode 120000 index 0000000000..8a6a254eaa --- /dev/null +++ b/Lang/Pico-8/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Pico-8 \ No newline at end of file diff --git a/Lang/PicoLisp/Bioinformatics-base-count b/Lang/PicoLisp/Bioinformatics-base-count deleted file mode 120000 index a4931ebf04..0000000000 --- a/Lang/PicoLisp/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Miller-Rabin-primality-test b/Lang/PicoLisp/Miller-Rabin-primality-test deleted file mode 120000 index eae524ec57..0000000000 --- a/Lang/PicoLisp/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Quaternion-type b/Lang/PicoLisp/Quaternion-type deleted file mode 120000 index 2120681801..0000000000 --- a/Lang/PicoLisp/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/PicoLisp \ No newline at end of file diff --git a/Lang/Pike/Execute-Brain- b/Lang/Pike/Execute-Brain- new file mode 120000 index 0000000000..dd7ee4c73b --- /dev/null +++ b/Lang/Pike/Execute-Brain- @@ -0,0 +1 @@ +../../Task/Execute-Brain-/Pike \ No newline at end of file diff --git a/Lang/Pike/Miller-Rabin-primality-test b/Lang/Pike/Miller-Rabin-primality-test deleted file mode 120000 index 2cc78451b0..0000000000 --- a/Lang/Pike/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Pike \ No newline at end of file diff --git a/Lang/Plain-English/00-LANG.txt b/Lang/Plain-English/00-LANG.txt index ff86a2a8e2..087f59b9fa 100644 --- a/Lang/Plain-English/00-LANG.txt +++ b/Lang/Plain-English/00-LANG.txt @@ -25,13 +25,19 @@ or compiled to a self-contained Microsoft Windows .exe file. Here is a list of what you must understand from the start: '''Fully Implemented in Itself:''' It is a single executable, with one or more human readable libraries (also written in Plain English Programming Language) which produces a new stand alone .exe with your new program in it. -It is NOT a compiler only that takes in source and produces compiled code. -It is NOT an IDE only, that shells out to a compiler. -It is both. +The project originally started as an IDE with a built-in compiler. +Over time, this evolved into a separate effort, resulting in a standalone compiler developed as an independent project. +Today, the ecosystem consists of two distinct components: +an IDE that includes its own integrated compiler, and a separate command-line compiler, each maintained independently. There is NO complete source code in another language; the system was bootstrapped in a Pascal-like language (which is no longer available) and was later re-written entirely in Plain English. It is "Machine Code" Low Level: The bootstrap is very basic, only able to copy itself and add raw machine code in Intel hex format, make calls to the operating system, e.g. -Call "kernel32.dll" "SetFilePointer" with the file and 0 and 0 and 2 [file_end] returning a result number. +Call "kernel32.dll" "SetFilePointer" with + the file [hFile] + and 0 [lDistanceToMove] + and 0 [lpDistanceToMoveHigh] + and 2 [file_end / dwMoveMethod] + returning a result number. and call other DLLs e.g. @@ -43,21 +49,25 @@ and it can do a few other things. To run: -Start up. -Clear the screen. -Use medium letters. Use the fat pen. -Pick a really dark color. -Loop. -Start in the center of the screen. -Turn left 1/32 of the way. -Turn right. Move 2 inches. Turn left. -Write "HELLO WORLD". -Refresh the screen. -Lighten the current color about 20 percent. -Add 1 to a count. If the count is 32, break. -Repeat. -Wait for the escape key. -Shut down. + Start up. + Clear the screen. + Use medium letters. + Use the fat pen. + Pick a really dark color. + Loop. + Start in the center of the screen. + Turn left 1/32 of the way. + Turn right. + Move 2 inches. + Turn left. + Write "HELLO WORLD". + Refresh the screen. + Lighten the current color about 20 percent. + Add 1 to a count. + If the count is 32, break. + Repeat. + Wait for the escape key. + Shut down. Note that standard English punctuation, word types, and sentence structure are all used. @@ -79,10 +89,10 @@ Intel $8B85080000008B008B9D0C0000000103. And yes, that is 80x86 machine code in Intel hex format. It decompiles to -mov eax, [ebp+8] ; $8B8508000000 -> load the current stack address + 8 into the accumulator -mov eax, [eax] ; $8B00 -> load memory pointed to by accumulator into accumulator -mov ebx, [ebp+12] ; $8B9D0C000000-> load the current stack address + 12 into working register -add [ebx],eax ; $0103 -> add accumulator to memory pointed to by working register +mov eax, [ebp+8] ; $8B8508000000 -> Load the value at (EBP + 8) into EAX (1st function argument) +mov eax, [eax] ; $8B00 -> Dereference EAX (load the value from the address stored in EAX) +mov ebx, [ebp+12] ; $8B9D0C000000-> Load the value at (EBP + 12) into EBX (2nd function argument) +add [ebx],eax ; $0103 -> Add EAX to the value stored at the address in EBX So the language has stacked pointers (all parameters are passed by reference) to the two numbers via a number to another number and then it calls this code which gets the first number, and adds it to the second. Hopefully this example shows how high level and low level Plain English is at the same time. @@ -118,7 +128,7 @@ The great foo is a number. then values may be assigned, inside a routine -Put 0 into the great foo +Put 0 into the great foo. or be passed by address... @@ -172,8 +182,8 @@ Type reductions proceed, recursively, from left to right, until a match is found To decide if a number is greater than another number: -If the first number is greater than the second number, say yes. -Say no. + If the first number is greater than the second number, say yes. + Say no. '''Function:''' A routine that extracts, calculates, or otherwise derives a value from a passed parameter. Function headers take this form: @@ -187,14 +197,14 @@ Unlike procedures (which are called via imperative sentences) and deciders (whic '''Statements''' From the instruction manual (see link below): -(1) I really only understand five kinds of sentences: -(a) type definitions, which always start with A, AN, or SOME; -(b) global variable definitions, which always start with THE; -(c) routine headers, which always start with TO, which can contain: -(d) conditional statements, which always start with IF; and -(e) imperative statements, which start with anything else. +(1) The compiler really only understand five kinds of sentences: +(a) Type definitions, which always start with A, AN, or SOME; +(b) Global variable definitions, which always start with THE; +(c) Routine headers, which always start with TO, which can contain: +(d) Conditional statements, which always start with IF; and +(e) Imperative statements, which start with anything else. -(2) I treat as a name anything after A, AN, ANOTHER, SOME, or THE, up to: +(2) I treat as a name (that is, a variable, argument, parameter or a type) anything after A, AN, ANOTHER, SOME, or THE, up to: (a) any simple verb, like IS, ARE, CAN, or DO, or (b) any conjunction, like AND or OR, or @@ -211,7 +221,9 @@ From the instruction manual (see link below): The noodle built into Plain English is simply not useful enough by itself, and therefore libraries were created to assist in writing Rosetta Code tasks in Plain English. See also: -https://github.com/Folds/english A work in progress to normalize Plain English into a more standard compiler. For documentation on the language in general, see the instructions.pdf file in the documentation folder. The author objects (see the issues) +https://github.com/Folds/english A work in progress to normalize Plain English into a more standard compiler. +For documentation on the language in general, see the instructions.pdf file in the documentation folder. +The author objects (see the issues) https://forums.parallax.com/discussion/163792/plain-english-programming a long rambling and unproductive (but educational, so productive in that sense) discussion of Plain English with it's author and proponents of a bare metal processor. {| class="wikitable" @@ -233,9 +245,219 @@ https://forums.parallax.com/discussion/163792/plain-english-programming a long r * Complete IDE Download ** [http://www.Osmosian.com/cal-4700.zip cal-4700.zip] *** requires Microsoft Windows +* Plain English Compiler (CMD / Command Line) +** [https://github.com/elisson-zlq3x/Plain-English-Compiler GitHub repo] ==Discussion== * [https://forums.parallax.com/discussion/163792/plain-english-programming Plain English Programming] ==Todo== -[[Reports:Tasks_not_implemented_in_PlainEnglish]] \ No newline at end of file +[[Reports:Tasks_not_implemented_in_PlainEnglish]] + +=Plain English Sources= +[http://osmosian.com/cal-4700.zip IDE] +and [https://github.com/elisson-zlq3x/Plain-English-Compiler Compiler]. +==Creators== +* Gerry Rzeppa (Father) +[https://www.quora.com/profile/Gerry-Rzeppa Quora Profile] +[https://www.linkedin.com/in/gerry-rzeppa-17b8051b/ LinkedIn Profile] +[https://twitter.com/gerryrzeppa Twitter Profile] +[https://github.com/GerryRzeppa GitHub Profile] +* Dan Rzeppa (Son) +[https://github.com/danrzeppa GitHub Profile] + +==Contributors== +* Elender Góis Gallas (Plain Portuguese Creator) +[https://www.quora.com/profile/Elender-G%C3%B3is-Gallas-%E3%82%A8%E3%83%AC%E3%83%B3%E3%83%87-%E3%82%AC%E3%83%A9%E3%82%B9 Quora Profile] +[https://www.linkedin.com/in/elender/ LinkedIn Profile] +[https://twitter.com/elenderg Twitter Profile] +[https://github.com/elenderg GitHub Profile] +* Pablo Cayuela (Plain Spanish Creator) +[https://www.linkedin.com/in/pablo-cayuela-a42b019/ LinkedIn Profile] + +==Copyright Owner== +* The Osmosian Order +** [http://www.Osmosian.com/ The Osmosian Order of Plain English Programmers] Brochure +*** [http://www.osmosian.com/manifesto.pdf The Osmosian Manifesto] +** [https://OsmosianPlainEnglishProgramming.blog/ Wordpress Blog]
    In chronological order: +*** 2018 +**** 05 +***** 01 [https://OsmosianPlainEnglishProgramming.blog/2018/05/01/a-solution-to-the-fatal-flaw-in-relational-database-systems/ A Solution to the Fatal Flaw in Relational Database Systems] +***** 02 [https://OsmosianPlainEnglishProgramming.blog/2018/05/02/plain-english-programming-fractal-forests/ Fractal Forests] +***** 02 [https://OsmosianPlainEnglishProgramming.blog/2018/05/02/plain-english-programming-is-a-picture-worth-1000-words/ Plain English Programming — Is a Picture Worth 1000 Words?] +***** 03 [https://OsmosianPlainEnglishProgramming.blog/2018/05/03/plain-english-programming-robotics/ Robotics] +***** 03 [https://OsmosianPlainEnglishProgramming.blog/2018/05/03/plain-english-programming-a-wysiwyg-document-editor/ A WYSIWYG Document Editor] +***** 04 [https://OsmosianPlainEnglishProgramming.blog/2018/05/04/plain-english-programming-musings-on-the-a-in-ai/ Musings on the “A” in “AI”] +***** 04 [https://OsmosianPlainEnglishProgramming.blog/2018/05/04/plain-english-programming-a-simple-merge-sort/ Robotics] +***** 05 [https://OsmosianPlainEnglishProgramming.blog/2018/05/05/plain-english-programming-smoothing-polygons/ Plain English Programming — Smoothing Polygons] +***** 05 [https://OsmosianPlainEnglishProgramming.blog/2018/05/05/plain-english-programming-kobayashi-maru-primes/ Kobayashi Maru Primes] +***** 06 [https://OsmosianPlainEnglishProgramming.blog/2018/05/06/plain-english-programming-nested-ifs/ Plain English Programming — Nested IFs] +***** 06 [https://OsmosianPlainEnglishProgramming.blog/2018/05/06/plain-english-programming-the-malevolent-mathemagician/ Plain English Programming — The Malevolent Mathemagician] +***** 07 [https://OsmosianPlainEnglishProgramming.blog/2018/05/07/plain-english-programming-parsing-with-riders/ Parsing with Riders] +***** 07 [https://OsmosianPlainEnglishProgramming.blog/2018/05/07/plain-english-programming-jackson-pollocks-alphabet-soup/ Plain English Programming — Jackson Pollock’s Alphabet Soup] +***** 08 [https://OsmosianPlainEnglishProgramming.blog/2018/05/08/plain-english-programming-random-numbers/ Random Numbers] +***** 08 [https://OsmosianPlainEnglishProgramming.blog/2018/05/08/plain-english-programming-sierpinski-koch/ Sierpinski & Koch] +***** 09 [https://OsmosianPlainEnglishProgramming.blog/2018/05/09/plain-english-programming-the-travelling-salesman/ The Travelling Salesman] +***** 09 [https://OsmosianPlainEnglishProgramming.blog/2018/05/09/plain-english-programming-a-jigsaw-puzzle/ A Jigsaw Puzzle] +***** 10 [https://OsmosianPlainEnglishProgramming.blog/2018/05/10/plain-english-programming-anagrams/ Anagrams] +***** 11 [https://OsmosianPlainEnglishProgramming.blog/2018/05/11/plain-english-programming-the-amazing-multimaze/ The Amazing MultiMaze] +***** 12 [https://OsmosianPlainEnglishProgramming.blog/2018/05/12/plain-english-programming-painting-like-monet/ Painting Like Monet] +***** 13 [https://OsmosianPlainEnglishProgramming.blog/2018/05/13/plain-english-programming-bresenhams-circle-drawing-algorithm/ Bresenham’s Circle Drawing Algorithm] +***** 14 [https://OsmosianPlainEnglishProgramming.blog/2018/05/14/plain-english-programming-hiding-in-plain-sight/ Hiding in Plain Sight] +***** 14 [https://OsmosianPlainEnglishProgramming.blog/2018/05/14/plain-english-programming-sudoku-solver/ Sudoku Solver] +***** 15 [https://OsmosianPlainEnglishProgramming.blog/2018/05/15/plain-english-programming-teaching-kids/ Teaching Kids to Program] +***** 16 [https://OsmosianPlainEnglishProgramming.blog/2018/05/16/the-journey-begins/ Plain English Programming] +==IDE including Compiler== +===Creator supplied=== +*[http://www.osmosian.com/cal-3040.zip cal-3040] 2006/08/14 +**[http://www.osmosian.com/ebnf EBNF] +**[http://www.osmosian.com/instructions.pdf instructions] +*[http://www.osmosian.com/cal-4700.zip cal-4700] 2017/01/27 + +===GitHub=== +*[https://GitHub.com/GerryRzeppa/osmosian /GerryRzeppa/osmosian] cal-3040 +*[https://GitHub.com/Folds/osmosian /Folds/osmosian] cal-3040 (Unauthorized) +*[https://GitHub.com/elenderg/Portugues-Puro /elenderg/Portugues-Puro] cal-4700 Translated to Portuguese + +==Forums== +===[https://www.AnandTech.com/ AnandTech]=== +*[https://forums.anandtech.com/threads/natural-language-programming.2358744/ Natural Language Programming: Good Idea? Yes Maybe No] +*[https://forums.anandtech.com/threads/conversational-storytelling-with-javascript.2410448/ Conversational Storytelling with JavaScript] +*[https://forums.anandtech.com/threads/natural-language-programming-english-and-or-español.2559516/ Natural Language Programming -- English and/or Español] +*[https://forums.anandtech.com/threads/learning-programming.2406202/#post-36858285 Learning programming] +*[https://forums.anandtech.com/threads/official-free-tools-thread.199156/page-4#post-36861957 Official Free Tools Thread | Plain English contribution] +*[https://news.yCombinator.com/item?id=8719957 Plain English Programming (2013)] +*[https://news.yCombinator.com/item?id=19355965 Do You Approve the Plain English?] +===[https://Forum.Arduino.cc/ Arduino]=== +*[https://forum.arduino.cc/t/plain-english-programming/371096/15 Plain English Programming] +===[https://groups.google.com/g/comp.compilers/ comp.compilers]=== +*[https://groups.google.com/g/comp.compilers/c/p30I_zVRlps/m/9UshbYjqZzwJ Writing A Plain English Compiler] +*[https://groups.google.com/g/comp.compilers/c/4t3_Dq6foFA/m/CYfdnKMBkAsJ Re: A Plain English Compiler] +===[https://www.GeeksForGeeks.org/ GeeksForGeeks]=== +*[https://www.geeksforgeeks.org/the-malevolent-mathemagician-natural-language-programming/ The Malevolent Mathemagician | Natural Language Programming] +*[https://www.geeksforgeeks.org/creating-wysiwyg-document-editor/ Creating WYSIWYG Document Editor | Natural Language Programming] +*[https://www.geeksforgeeks.org/a-kobayashi-maru-approach-to-finding-primes/ A Kobayashi Maru Approach to Finding Primes] +*[https://www.geeksforgeeks.org/natural-language-programming-sorting/ Sorting | Natural Language Programming] +*[https://www.geeksforgeeks.org/natural-language-programming-teaching-kids/ Natural Language Programming — Teaching Kids] +*[https://www.geeksforgeeks.org/natural-language-programming/ Natural Language Programming] +===[https://IntFiction.org/ Interactive Fiction Community Forum]=== +*[https://intfiction.org/t/writer-wanted-for-a-conversational-storytelling-project/6169 Writer wanted for a “Conversational Storytelling” project] +*[https://intfiction.org/t/inform-system-developers-do-you-approve-the-plain-english-programming/42213 Inform system developers, do you approve the Plain English Programming?] +===[https://Forums.Parallax.com/ Parallax Forums]=== +*[https://forums.parallax.com/discussion/163792/plain-english-programming Plain English Programming] +===[https://www.PC-Control.co.uk/ PC Control Limited]=== +*[https://www.pc-control.co.uk/control/articles/article10.php Automated Maze solver using a servo hawk] +**[https://www.pc-control.co.uk/control/articles/images/photo%2009%20-%20definitions.png photo 09 - definitions] +**[https://www.pc-control.co.uk/control/articles/images/photo%2010%20-%20low-level%20helper%20routines.png photo 10 - low-level helper routines] +**[https://www.pc-control.co.uk/control/articles/images/photo%2011%20-%20mid-level%20helper%20routines.png photo 11 - mid-level helper routines] +**[https://www.pc-control.co.uk/control/articles/images/photo%2012%20-%20high-level%20helper%20routines.png photo 12 - high-level helper routines] +**[https://www.pc-control.co.uk/control/articles/images/photo%2013%20-%20main%20routine.png photo 13 - main routine] +**[https://www.pc-control.co.uk/control/articles/images/photo%2014%20-%20terminal%20output.png photo 14 - terminal output] +===[https://www.Quora.com/ Quora]=== +*Jul 06, 2021 - [https://www.quora.com/What-can-a-beginner-programmer-use-as-a-programming-IDE-I-tried-using-Visual-Studio-Express-but-it-was-too-hard-to-use-and-understand-Is-there-anything-else-I-can-use/answer/Gerry-Rzeppa What can a beginner programmer use as a programming IDE? I tried using Visual Studio Express but it was too hard to use and understand. Is there anything else I can use?] +**"To get started with Plain English, see here (it’s fast, friendly, and free):" +**Reference to another Gerry Rzeppa Quora article: Jun 27, 2021 - [https://www.quora.com/Is-there-a-right-way-to-learn-to-code-1/answer/Gerry-Rzeppa Is there a right way to learn to code?] +*Jul 06, 2021 - [https://www.quora.com/How-often-when-puzzling-out-a-solution-to-a-problem-do-you-think-or-say-aloud-Are-we-asking-the-right-question-questions/answer/Gerry-Rzeppa How often when puzzling out a solution to a problem, do you think or say aloud, “Are we asking the right question/questions?”] +**"Almost every time." +**Reference to another Gerry Rzeppa Quora article: May 11, 2021 [https://www.quora.com/What-IDE-has-impressed-you-with-its-ease-of-use-and-how-productive-were-you-with-it/answer/Gerry-Rzeppa What IDE has impressed you with its ease of use, and how productive were you with it?] +*Jul 06, 2021 - [https://www.quora.com/What-are-the-best-examples-of-poetry-written-in-programming-languages/answer/Gerry-Rzeppa What are the best examples of poetry written in programming languages?] +**A poem written in Plain English that, when run, makes the picture the poem describes. +*Jul 05, 2021 - [https://www.quora.com/What-is-the-character-limit-for-one-line-of-code-you-go-by/answer/Gerry-Rzeppa What is the character limit for one line of code you go by?] +**"... if handwritten code fits on the screen, it’s okay by me." +*Jul 05, 2021 - [https://www.quora.com/How-is-a-one-dimensional-character-array-and-a-string-similar/answer/Gerry-Rzeppa How is a one-dimensional character array and a string similar?] + +**Strings +**Substrings +**String Riders +*Jun 27, 2021 - [https://www.quora.com/Is-there-a-right-way-to-learn-to-code-1/answer/Gerry-Rzeppa Is there a right way to learn to code?] +**A offering of the Plain English IDE and personal tutoring. +*Jun 10, 2021 - [https://www.quora.com/Is-there-any-way-to-write-genuine-self-modifying-code-in-Windows/answer/Gerry-Rzeppa Is there any way to write genuine self-modifying code in Windows?] + +**Memory Map +**Memory Pointers +*Jun 10, 2021 - [https://www.quora.com/How-can-I-write-a-Python-program-where-a-bunch-of-students-will-be-assigned-thesis-themes-using-the-FIFO-method/answer/Gerry-Rzeppa How can I write a Python program where a bunch of students will be assigned thesis themes using the FIFO method?] +** Use of path variable. +** Iterative development. +** Relation of item in a list and the name of the list. +** Screen space management. +** Use of "backwards". +*Jun 09, 2021 - [https://www.quora.com/How-do-computers-execute-if-statements-to-the-core-machine-code-and-opcodes/answer/Gerry-Rzeppa How do computers execute if statements to the core machine code and opcodes?] + +** List command and explanation of display produced +** Memory Map +** Uses [https://defuse.ca/online-x86-assembler.htm Online x86 and x64 Intel Instruction Assembler] to disassemble code in the List output. +** Offers free “How to Write a Plain English Compiler in Plain English” course via email. +*Jun 08, 2021 - [https://www.quora.com/How-can-I-draw-the-flag-of-a-country-in-C-beginner/answer/Gerry-Rzeppa How can I draw the flag of a country in C#? (beginner)] +** Make a box +** Center the box +** Draw and fill the box +** Stroke +*Jun 07, 2021 - [https://www.quora.com/Is-it-wise-to-ask-query-like-why-curly-braces-are-preferred-in-C-instead-of-opening-and-closing-bracket-when-writing-functions-or-we-just-need-to-memorize-that-as-a-random-rule-Is-there-any-book-which-deals-with/answer/Gerry-Rzeppa Is it wise to ask query like why curly braces are preferred in C instead of opening and closing bracket when writing functions, or we just need to memorize that as a random rule? Is there any book which deals with such miscellaneous things about C?] +** “Arbitrary and unnecessary rule” +*Jun 06, 2021 - [https://www.quora.com/How-would-I-go-about-creating-dots-and-boxes-in-Java/answer/Gerry-Rzeppa How would I go about creating dots and boxes in Java?] +*Jun 06, 2021 - [https://www.quora.com/How-can-I-write-a-menu-driven-program-to-perform-following-operations-on-the-stack-using-array-a-i-Push-ii-Pop-iii-Peek/answer/Gerry-Rzeppa How can I write a menu-driven program to perform the following operations on the stack using array- a (i) Push (ii) Pop (iii) Peek?] +*Jun 06, 2021 - [https://www.quora.com/How-do-I-make-a-countdown-and-when-it-finishes-it-shows-a-text-in-coding-I-want-to-add-a-picture-as-a-border-or-what-else-to-countdown/answer/Gerry-Rzeppa How do I make a countdown and when it finishes, it shows a text in coding? I want to add a picture as a border or what else to countdown.] +*Jun 06, 2021 - [https://www.quora.com/What-is-recursion-Can-you-explain-the-main-principles-of-recursions-Can-you-do-the-code-algorithm-of-the-Fibonacci-series-using-recursion/answer/Gerry-Rzeppa What is recursion? Can you explain the main principles of recursions? Can you do the code/algorithm of the Fibonacci series using recursion?] +*Jun 06, 2021 - [https://www.quora.com/How-do-you-find-the-intersection-point-between-a-line-and-a-rectangle-algorithm-geometry-line-intersection-development/answer/Gerry-Rzeppa What is recursion? How do you find the intersection point between a line and a rectangle (algorithm, geometry, line, intersection, development)?] +*Jun 06, 2021 - [https://www.quora.com/How-do-you-handle-algorithms-to-create-polygons-no-Thiesen-Voronoi-Python-Shapely-Voronoi-development/answer/Gerry-Rzeppa How do you handle algorithms to create polygons (no Thiesen/Voronoi) (Python, Shapely, Voronoi, development)?] +*Jun 04, 2021 - [https://www.quora.com/I-want-to-get-into-programming-What-languages-should-I-learn-first/answer/Gerry-Rzeppa I want to get into programming. What languages should I learn first?] +*Jun 04, 2021 - [https://www.quora.com/How-do-I-make-a-programme-using-codes/answer/Gerry-Rzeppa How do I make a programme using codes?] +*Jun 04, 2021 - [https://www.quora.com/Why-is-Hello-World-the-default-line-in-programming-languages/answer/Gerry-Rzeppa Why is "Hello World" the default line in programming languages?] +*Jun 04, 2021 - [https://www.quora.com/Why-cant-I-find-any-real-photo-of-a-compiler-Is-it-too-small/answer/Gerry-Rzeppa Why can't I find any real photo of a compiler? Is it too small?] +*Jun 03, 2021 - [https://www.quora.com/Why-must-the-starting-value-of-a-control-variable-be-less-than-the-ending-value-in-a-for-loop-expression/answer/Gerry-Rzeppa Why must the starting value of a control variable be less than the ending value in a for loop expression?] +*Jun 03, 2021 - [https://www.quora.com/What-is-the-purpose-of-initialization-of-counter-variable-in-a-loop/answer/Gerry-Rzeppa What is the purpose of "initialization of counter variable" in a loop?] +*Jun 03, 2021 - [https://www.quora.com/What-is-the-nature-of-a-variable-with-real-life-examples/answer/Gerry-Rzeppa What is the nature of a variable with real life examples?] +*Jun 03, 2021 - [https://www.quora.com/Why-is-UML-a-significant-area-of-study/answer/Gerry-Rzeppa Why is UML a significant area of study?] +*May 29, 2021 [https://www.quora.com/Is-it-easier-to-write-an-interpreter-than-a-compiler-Why/answer/Gerry-Rzeppa Is it easier to write an interpreter than a compiler? Why?] +**"Yes. An interpreter can be written with less knowledge of the hardware and operating system." +**Reference to another Gerry Rzeppa Quora article: May 18, 2021 [https://www.quora.com/How-do-I-make-programming-language/answer/Gerry-Rzeppa How do I make programming language?] +*May 18, 2021 [https://www.quora.com/How-do-I-make-programming-language/answer/Gerry-Rzeppa How do I make programming language?] +**Reference to another Gerry Rzeppa Quora article: Dec 22, 2020 [https://www.quora.com/How-do-you-start-writing-your-interpreter-from-scratch/answer/Gerry-Rzeppa How do you start writing your interpreter from scratch?] +**Reference to another Gerry Rzeppa Quora article: Aug 30, 2020 [https://www.quora.com/What-is-a-compiler-and-the-stages-of-a-compiler/answer/Gerry-Rzeppa What is a compiler and the stages of a compiler?] +*May 11, 2021 [https://www.quora.com/What-IDE-has-impressed-you-with-its-ease-of-use-and-how-productive-were-you-with-it/answer/Gerry-Rzeppa What IDE has impressed you with its ease of use, and how productive were you with it?] +*Apr 28, 2021 - [https://www.quora.com/I-need-some-good-project-related-to-data-structure-I-am-a-2rd-year-computer-science-student-What-is-your-suggestion/answer/Gerry-Rzeppa I need some good project related to data structure. I am a 2rd year computer science student. What is your suggestion?] + +**Data types +***Fundamental +****byte +****record +***Pointers +****Generic +****Typed +***Strings +***Things +****Stacks +****Queues +****Hashed Indices +**Memory Map +**WYSIWYG document editor +*Apr 12, 2021 - [https://www.quora.com/What-is-the-relationship-between-a-compiler-algorithm-and-data-structure/answer/Gerry-Rzeppa What is the relationship between a compiler, algorithm, and data structure?] +** "A compiler uses data structures and algorithms to translate high-level source code into low-level executable machine code." +** Discussion of the Plain English compiler +*Mar 29, 2021 - [https://www.quora.com/What-is-the-most-interesting-Python-algorithm-in-less-than-ten-lines-of-code/answer/Gerry-Rzeppa What is the most interesting Python algorithm in less than ten lines of code?] +**Lindenmayer interpreter +*Mar 27, 2021 - [https://www.quora.com/What-is-the-best-way-to-present-an-algorithm/answer/Gerry-Rzeppa What is the best way to present an algorithm?] +**Three-step process +*Mar 24, 2021 - [https://www.quora.com/Why-is-it-hard-to-understand-linked-lists-in-programming/answer/Gerry-Rzeppa Why is it hard to understand linked lists in programming?] +**Discuss Plain English linked list. +*Dec 22, 2020 [https://www.quora.com/How-do-you-start-writing-your-interpreter-from-scratch/answer/Gerry-Rzeppa How do you start writing your interpreter from scratch?] +** “primitive” BASIC editor/interpreter +*Oct 03, 2020 - [https://www.quora.com/In-procedural-programming-how-do-you-plan-your-code-without-UML/answer/Gerry-Rzeppa In procedural programming, how do you plan your code without UML?] +**Osmosian maxim: “If it’s hard, it’s wrong.” +**Pair Programming +**"During the winter of 2005-2006, we wrote (and documented) 25,000 lines of Plain English code in just six months ..." +**'“Just tell us what you need, sonny, and we’ll show you how to live without it.”' +*Aug 30, 2020 [https://www.quora.com/What-is-a-compiler-and-the-stages-of-a-compiler/answer/Gerry-Rzeppa What is a compiler and the stages of a compiler?] +**Structure of the Plain English compiler. +*Jul 09, 2020 - [https://www.quora.com/Who-can-print-this-string-Hello-world-more-smartly-and-clearly/answer/Gerry-Rzeppa Who can print this string "Hello world" more smartly and clearly?] +**Plain English program to print in a circle. +**Español Llano (Plain Spanish) program to print in a circle. +*Jun 08, 2020 - [https://www.quora.com/Why-do-some-programmers-write-their-own-compilers/answer/Gerry-Rzeppa Why do some programmers write their own compilers?] +**'My elder son and I wrote our own Plain English compiler and IDE, in Plain English, originally, for three reasons. We wanted to know:' +***'1. Is it easier to program when you don’t have to translate your natural-language thoughts into an alternate syntax?' +***'2. Can natural languages be parsed in a relatively “sloppy” manner (as humans apparently parse them) and still provide a stable enough environment for productive programming?' +***'3. Can low-level programs (like compilers) be conveniently and efficiently written in high level languages (like English)? +**'Turns out the answers to all of three questions is, “Yes!”' + +==Successor Project (Trial)== +*[https://www.indiegogo.com/projects/the-hybrid-programming-language#/ The Hybrid Programming Language] - Plain English with snippets of formulas and graphics where needed \ No newline at end of file diff --git a/Lang/Pluto/00-LANG.txt b/Lang/Pluto/00-LANG.txt new file mode 100644 index 0000000000..80e65c9293 --- /dev/null +++ b/Lang/Pluto/00-LANG.txt @@ -0,0 +1,47 @@ +{{language|Pluto +|exec=interpreted +|strength=strong +|safety=safe +|express=implicit +|checking=dynamic +|gc=yes +|hopl=no +|site=https://pluto-lang.org/}} +Pluto is a superset of Lua 5.4 with a focus on general-purpose programming. While being remarkably compatible with Lua 5.4 source-code & bytecode, it enhances the standard library & adds more than a dozen highly-desired syntaxes such as switch statements, compound operators, classes, class inheritance, string interpolation, type hinting, enums, and so on. + +Pluto aspires to be a version of Lua with a larger feature-set, that is all. Pluto is not a Lua-killer, an attempted successor, or any of that. Many people (rightly so) love Lua precisely because of the design philosophy. And fundamentally, Pluto is a major deviation from Lua's design philosophy. Some may prefer this, some may not. + +The language is being developed on [https://github.com/PlutoLang/Pluto github] and pre-built binaries for 64-bit Linux, MacOS and Windows can be downloaded [https://github.com/PlutoLang/Pluto/releases here]. + +Here is a list of custom libraries used on Rosetta Code: +{|class="wikitable" +! No. !! Module name !! No. !! Module name +|- +| 1 || [[:Category:Pluto-fmt|fmt]] || 2 || [[:Category:Pluto-math2|math2]] +|- +| 3 || [[:Category:Pluto-int|int]] || 4 || [[:Category:Pluto-table2|table2]] +|- +| 5 || [[:Category:Pluto-complex|complex]] || 6 || [[:Category:Pluto-rat|rat]] +|- +| 7 || [[:Category:Pluto-queue|queue]] || 8 || [[:Category:Pluto-map|map]] +|- +| 9 || [[:Category:Pluto-list|list]] || 10 || [[:Category:Pluto-perm|perm]] +|- +|11 || [[:Category:Pluto-ansi|ansi]] || 12 || [[:Category:Pluto-io2|io2]] +|- +|13 || [[:Category:Pluto-uchar|uchar]] || 14 || [[:Category:Pluto-gchar|gchar]] +|- +|15 || [[:Category:Pluto-matrix|matrix]] || 16 || [[:Category:Pluto-poly|poly]] +|- +|17 || [[:Category:Pluto-audio|audio]] || 18 || [[:Category:Pluto-bitmap|bitmap]] +|- +|19 || [[:Category:Pluto-lsystem|lsystem]] || 20 || [[:Category:Pluto-bignum|bignum]] +|- +|} + +== To do == +[[Tasks not implemented in Pluto]] + +== See also == + +[[Lua]] \ No newline at end of file diff --git a/Lang/Pluto/00-META.yaml b/Lang/Pluto/00-META.yaml new file mode 100644 index 0000000000..4169e06d3e --- /dev/null +++ b/Lang/Pluto/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Pluto diff --git a/Lang/Pluto/100-prisoners b/Lang/Pluto/100-prisoners new file mode 120000 index 0000000000..2439d4fa2a --- /dev/null +++ b/Lang/Pluto/100-prisoners @@ -0,0 +1 @@ +../../Task/100-prisoners/Pluto \ No newline at end of file diff --git a/Lang/Pluto/9-billion-names-of-God-the-integer b/Lang/Pluto/9-billion-names-of-God-the-integer new file mode 120000 index 0000000000..03c26b8d5f --- /dev/null +++ b/Lang/Pluto/9-billion-names-of-God-the-integer @@ -0,0 +1 @@ +../../Task/9-billion-names-of-God-the-integer/Pluto \ No newline at end of file diff --git a/Lang/Pluto/99-bottles-of-beer b/Lang/Pluto/99-bottles-of-beer new file mode 120000 index 0000000000..cc21927564 --- /dev/null +++ b/Lang/Pluto/99-bottles-of-beer @@ -0,0 +1 @@ +../../Task/99-bottles-of-beer/Pluto \ No newline at end of file diff --git a/Lang/Pluto/A+B b/Lang/Pluto/A+B new file mode 120000 index 0000000000..c26f431720 --- /dev/null +++ b/Lang/Pluto/A+B @@ -0,0 +1 @@ +../../Task/A+B/Pluto \ No newline at end of file diff --git a/Lang/Pluto/ABC-problem b/Lang/Pluto/ABC-problem new file mode 120000 index 0000000000..13affeffe2 --- /dev/null +++ b/Lang/Pluto/ABC-problem @@ -0,0 +1 @@ +../../Task/ABC-problem/Pluto \ No newline at end of file diff --git a/Lang/Pluto/AKS-test-for-primes b/Lang/Pluto/AKS-test-for-primes new file mode 120000 index 0000000000..55e9fce3e0 --- /dev/null +++ b/Lang/Pluto/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/Pluto \ No newline at end of file diff --git a/Lang/Pluto/ASCII-art-diagram-converter b/Lang/Pluto/ASCII-art-diagram-converter new file mode 120000 index 0000000000..395927ab4a --- /dev/null +++ b/Lang/Pluto/ASCII-art-diagram-converter @@ -0,0 +1 @@ +../../Task/ASCII-art-diagram-converter/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Abbreviations-automatic b/Lang/Pluto/Abbreviations-automatic new file mode 120000 index 0000000000..1d471effa2 --- /dev/null +++ b/Lang/Pluto/Abbreviations-automatic @@ -0,0 +1 @@ +../../Task/Abbreviations-automatic/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Abbreviations-easy b/Lang/Pluto/Abbreviations-easy new file mode 120000 index 0000000000..4e4f49cf5b --- /dev/null +++ b/Lang/Pluto/Abbreviations-easy @@ -0,0 +1 @@ +../../Task/Abbreviations-easy/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Abbreviations-simple b/Lang/Pluto/Abbreviations-simple new file mode 120000 index 0000000000..d62c58f891 --- /dev/null +++ b/Lang/Pluto/Abbreviations-simple @@ -0,0 +1 @@ +../../Task/Abbreviations-simple/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Abelian-sandpile-model b/Lang/Pluto/Abelian-sandpile-model new file mode 120000 index 0000000000..84e194b9d0 --- /dev/null +++ b/Lang/Pluto/Abelian-sandpile-model @@ -0,0 +1 @@ +../../Task/Abelian-sandpile-model/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Abelian-sandpile-model-Identity b/Lang/Pluto/Abelian-sandpile-model-Identity new file mode 120000 index 0000000000..5258fd0a4e --- /dev/null +++ b/Lang/Pluto/Abelian-sandpile-model-Identity @@ -0,0 +1 @@ +../../Task/Abelian-sandpile-model-Identity/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Abstract-type b/Lang/Pluto/Abstract-type new file mode 120000 index 0000000000..f418e6a876 --- /dev/null +++ b/Lang/Pluto/Abstract-type @@ -0,0 +1 @@ +../../Task/Abstract-type/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Abundant-deficient-and-perfect-number-classifications b/Lang/Pluto/Abundant-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..f5843a0883 --- /dev/null +++ b/Lang/Pluto/Abundant-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant-deficient-and-perfect-number-classifications/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Abundant-odd-numbers b/Lang/Pluto/Abundant-odd-numbers new file mode 120000 index 0000000000..18495df602 --- /dev/null +++ b/Lang/Pluto/Abundant-odd-numbers @@ -0,0 +1 @@ +../../Task/Abundant-odd-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Accumulator-factory b/Lang/Pluto/Accumulator-factory new file mode 120000 index 0000000000..09dad4bd16 --- /dev/null +++ b/Lang/Pluto/Accumulator-factory @@ -0,0 +1 @@ +../../Task/Accumulator-factory/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Achilles-numbers b/Lang/Pluto/Achilles-numbers new file mode 120000 index 0000000000..0121ec15f3 --- /dev/null +++ b/Lang/Pluto/Achilles-numbers @@ -0,0 +1 @@ +../../Task/Achilles-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Ackermann-function b/Lang/Pluto/Ackermann-function new file mode 120000 index 0000000000..b2e9e8bcf4 --- /dev/null +++ b/Lang/Pluto/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Add-a-variable-to-a-class-instance-at-runtime b/Lang/Pluto/Add-a-variable-to-a-class-instance-at-runtime new file mode 120000 index 0000000000..9c086b6c80 --- /dev/null +++ b/Lang/Pluto/Add-a-variable-to-a-class-instance-at-runtime @@ -0,0 +1 @@ +../../Task/Add-a-variable-to-a-class-instance-at-runtime/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Additive-primes b/Lang/Pluto/Additive-primes new file mode 120000 index 0000000000..5fa0027662 --- /dev/null +++ b/Lang/Pluto/Additive-primes @@ -0,0 +1 @@ +../../Task/Additive-primes/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Address-of-a-variable b/Lang/Pluto/Address-of-a-variable new file mode 120000 index 0000000000..db8c9fa74c --- /dev/null +++ b/Lang/Pluto/Address-of-a-variable @@ -0,0 +1 @@ +../../Task/Address-of-a-variable/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Algebraic-data-types b/Lang/Pluto/Algebraic-data-types new file mode 120000 index 0000000000..a63223b643 --- /dev/null +++ b/Lang/Pluto/Algebraic-data-types @@ -0,0 +1 @@ +../../Task/Algebraic-data-types/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Aliquot-sequence-classifications b/Lang/Pluto/Aliquot-sequence-classifications new file mode 120000 index 0000000000..3d08da68d2 --- /dev/null +++ b/Lang/Pluto/Aliquot-sequence-classifications @@ -0,0 +1 @@ +../../Task/Aliquot-sequence-classifications/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Almkvist-Giullera-formula-for-pi b/Lang/Pluto/Almkvist-Giullera-formula-for-pi new file mode 120000 index 0000000000..a4dbb156c2 --- /dev/null +++ b/Lang/Pluto/Almkvist-Giullera-formula-for-pi @@ -0,0 +1 @@ +../../Task/Almkvist-Giullera-formula-for-pi/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Almost-prime b/Lang/Pluto/Almost-prime new file mode 120000 index 0000000000..8dfdefc597 --- /dev/null +++ b/Lang/Pluto/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Amb b/Lang/Pluto/Amb new file mode 120000 index 0000000000..5d885d9898 --- /dev/null +++ b/Lang/Pluto/Amb @@ -0,0 +1 @@ +../../Task/Amb/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Amicable-pairs b/Lang/Pluto/Amicable-pairs new file mode 120000 index 0000000000..8f6d71ca71 --- /dev/null +++ b/Lang/Pluto/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Anagrams b/Lang/Pluto/Anagrams new file mode 120000 index 0000000000..ed05036541 --- /dev/null +++ b/Lang/Pluto/Anagrams @@ -0,0 +1 @@ +../../Task/Anagrams/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Anagrams-Deranged-anagrams b/Lang/Pluto/Anagrams-Deranged-anagrams new file mode 120000 index 0000000000..15515547a0 --- /dev/null +++ b/Lang/Pluto/Anagrams-Deranged-anagrams @@ -0,0 +1 @@ +../../Task/Anagrams-Deranged-anagrams/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Angle-difference-between-two-bearings b/Lang/Pluto/Angle-difference-between-two-bearings new file mode 120000 index 0000000000..e89e19b294 --- /dev/null +++ b/Lang/Pluto/Angle-difference-between-two-bearings @@ -0,0 +1 @@ +../../Task/Angle-difference-between-two-bearings/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Angles-geometric-normalization-and-conversion b/Lang/Pluto/Angles-geometric-normalization-and-conversion new file mode 120000 index 0000000000..bf11da216a --- /dev/null +++ b/Lang/Pluto/Angles-geometric-normalization-and-conversion @@ -0,0 +1 @@ +../../Task/Angles-geometric-normalization-and-conversion/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Anonymous-recursion b/Lang/Pluto/Anonymous-recursion new file mode 120000 index 0000000000..e9e2ff5cdd --- /dev/null +++ b/Lang/Pluto/Anonymous-recursion @@ -0,0 +1 @@ +../../Task/Anonymous-recursion/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Anti-primes b/Lang/Pluto/Anti-primes new file mode 120000 index 0000000000..62e9118e82 --- /dev/null +++ b/Lang/Pluto/Anti-primes @@ -0,0 +1 @@ +../../Task/Anti-primes/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Approximate-equality b/Lang/Pluto/Approximate-equality new file mode 120000 index 0000000000..65832f9c4c --- /dev/null +++ b/Lang/Pluto/Approximate-equality @@ -0,0 +1 @@ +../../Task/Approximate-equality/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Arbitrary-precision-integers-included- b/Lang/Pluto/Arbitrary-precision-integers-included- new file mode 120000 index 0000000000..63cf45fedf --- /dev/null +++ b/Lang/Pluto/Arbitrary-precision-integers-included- @@ -0,0 +1 @@ +../../Task/Arbitrary-precision-integers-included-/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Archimedean-spiral b/Lang/Pluto/Archimedean-spiral new file mode 120000 index 0000000000..bf76191b73 --- /dev/null +++ b/Lang/Pluto/Archimedean-spiral @@ -0,0 +1 @@ +../../Task/Archimedean-spiral/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Arena-storage-pool b/Lang/Pluto/Arena-storage-pool new file mode 120000 index 0000000000..2287439dec --- /dev/null +++ b/Lang/Pluto/Arena-storage-pool @@ -0,0 +1 @@ +../../Task/Arena-storage-pool/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Arithmetic-Complex b/Lang/Pluto/Arithmetic-Complex new file mode 120000 index 0000000000..e8437b9a01 --- /dev/null +++ b/Lang/Pluto/Arithmetic-Complex @@ -0,0 +1 @@ +../../Task/Arithmetic-Complex/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Arithmetic-Integer b/Lang/Pluto/Arithmetic-Integer new file mode 120000 index 0000000000..3b77091442 --- /dev/null +++ b/Lang/Pluto/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Arithmetic-Rational b/Lang/Pluto/Arithmetic-Rational new file mode 120000 index 0000000000..497dafd0e0 --- /dev/null +++ b/Lang/Pluto/Arithmetic-Rational @@ -0,0 +1 @@ +../../Task/Arithmetic-Rational/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Arithmetic-derivative b/Lang/Pluto/Arithmetic-derivative new file mode 120000 index 0000000000..9254d1c7e4 --- /dev/null +++ b/Lang/Pluto/Arithmetic-derivative @@ -0,0 +1 @@ +../../Task/Arithmetic-derivative/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Arithmetic-evaluation b/Lang/Pluto/Arithmetic-evaluation new file mode 120000 index 0000000000..4f46626913 --- /dev/null +++ b/Lang/Pluto/Arithmetic-evaluation @@ -0,0 +1 @@ +../../Task/Arithmetic-evaluation/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Arithmetic-geometric-mean b/Lang/Pluto/Arithmetic-geometric-mean new file mode 120000 index 0000000000..7f7bd49c54 --- /dev/null +++ b/Lang/Pluto/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Arithmetic-geometric-mean-Calculate-Pi b/Lang/Pluto/Arithmetic-geometric-mean-Calculate-Pi new file mode 120000 index 0000000000..f64109ba32 --- /dev/null +++ b/Lang/Pluto/Arithmetic-geometric-mean-Calculate-Pi @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean-Calculate-Pi/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Arithmetic-numbers b/Lang/Pluto/Arithmetic-numbers new file mode 120000 index 0000000000..9d3c7548ad --- /dev/null +++ b/Lang/Pluto/Arithmetic-numbers @@ -0,0 +1 @@ +../../Task/Arithmetic-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Array-concatenation b/Lang/Pluto/Array-concatenation new file mode 120000 index 0000000000..b151e60e5d --- /dev/null +++ b/Lang/Pluto/Array-concatenation @@ -0,0 +1 @@ +../../Task/Array-concatenation/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Arrays b/Lang/Pluto/Arrays new file mode 120000 index 0000000000..36aa2a73e2 --- /dev/null +++ b/Lang/Pluto/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Ascending-primes b/Lang/Pluto/Ascending-primes new file mode 120000 index 0000000000..b086dde9de --- /dev/null +++ b/Lang/Pluto/Ascending-primes @@ -0,0 +1 @@ +../../Task/Ascending-primes/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Assertions b/Lang/Pluto/Assertions new file mode 120000 index 0000000000..8561bd9006 --- /dev/null +++ b/Lang/Pluto/Assertions @@ -0,0 +1 @@ +../../Task/Assertions/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Associative-array-Creation b/Lang/Pluto/Associative-array-Creation new file mode 120000 index 0000000000..dab36a66d3 --- /dev/null +++ b/Lang/Pluto/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Associative-array-Iteration b/Lang/Pluto/Associative-array-Iteration new file mode 120000 index 0000000000..5ced29976c --- /dev/null +++ b/Lang/Pluto/Associative-array-Iteration @@ -0,0 +1 @@ +../../Task/Associative-array-Iteration/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Associative-array-Merging b/Lang/Pluto/Associative-array-Merging new file mode 120000 index 0000000000..e8bdf6f6ca --- /dev/null +++ b/Lang/Pluto/Associative-array-Merging @@ -0,0 +1 @@ +../../Task/Associative-array-Merging/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Attractive-numbers b/Lang/Pluto/Attractive-numbers new file mode 120000 index 0000000000..cc6d5fdf22 --- /dev/null +++ b/Lang/Pluto/Attractive-numbers @@ -0,0 +1 @@ +../../Task/Attractive-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Average-loop-length b/Lang/Pluto/Average-loop-length new file mode 120000 index 0000000000..da02c11d74 --- /dev/null +++ b/Lang/Pluto/Average-loop-length @@ -0,0 +1 @@ +../../Task/Average-loop-length/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Averages-Arithmetic-mean b/Lang/Pluto/Averages-Arithmetic-mean new file mode 120000 index 0000000000..a80eb1d9ce --- /dev/null +++ b/Lang/Pluto/Averages-Arithmetic-mean @@ -0,0 +1 @@ +../../Task/Averages-Arithmetic-mean/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Averages-Mean-angle b/Lang/Pluto/Averages-Mean-angle new file mode 120000 index 0000000000..b2c7bb37d8 --- /dev/null +++ b/Lang/Pluto/Averages-Mean-angle @@ -0,0 +1 @@ +../../Task/Averages-Mean-angle/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Averages-Mean-time-of-day b/Lang/Pluto/Averages-Mean-time-of-day new file mode 120000 index 0000000000..11b930dc65 --- /dev/null +++ b/Lang/Pluto/Averages-Mean-time-of-day @@ -0,0 +1 @@ +../../Task/Averages-Mean-time-of-day/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Averages-Median b/Lang/Pluto/Averages-Median new file mode 120000 index 0000000000..4877cdaa55 --- /dev/null +++ b/Lang/Pluto/Averages-Median @@ -0,0 +1 @@ +../../Task/Averages-Median/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Averages-Mode b/Lang/Pluto/Averages-Mode new file mode 120000 index 0000000000..9ba2618c12 --- /dev/null +++ b/Lang/Pluto/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Averages-Pythagorean-means b/Lang/Pluto/Averages-Pythagorean-means new file mode 120000 index 0000000000..f4cb6461df --- /dev/null +++ b/Lang/Pluto/Averages-Pythagorean-means @@ -0,0 +1 @@ +../../Task/Averages-Pythagorean-means/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Averages-Root-mean-square b/Lang/Pluto/Averages-Root-mean-square new file mode 120000 index 0000000000..744197c17a --- /dev/null +++ b/Lang/Pluto/Averages-Root-mean-square @@ -0,0 +1 @@ +../../Task/Averages-Root-mean-square/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Averages-Simple-moving-average b/Lang/Pluto/Averages-Simple-moving-average new file mode 120000 index 0000000000..79f88ee858 --- /dev/null +++ b/Lang/Pluto/Averages-Simple-moving-average @@ -0,0 +1 @@ +../../Task/Averages-Simple-moving-average/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Babbage-problem b/Lang/Pluto/Babbage-problem new file mode 120000 index 0000000000..7dd4f1e4c1 --- /dev/null +++ b/Lang/Pluto/Babbage-problem @@ -0,0 +1 @@ +../../Task/Babbage-problem/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Balanced-brackets b/Lang/Pluto/Balanced-brackets new file mode 120000 index 0000000000..e55ebe8e48 --- /dev/null +++ b/Lang/Pluto/Balanced-brackets @@ -0,0 +1 @@ +../../Task/Balanced-brackets/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Barnsley-fern b/Lang/Pluto/Barnsley-fern new file mode 120000 index 0000000000..a90021bfee --- /dev/null +++ b/Lang/Pluto/Barnsley-fern @@ -0,0 +1 @@ +../../Task/Barnsley-fern/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Base64-decode-data b/Lang/Pluto/Base64-decode-data new file mode 120000 index 0000000000..9e79a215f0 --- /dev/null +++ b/Lang/Pluto/Base64-decode-data @@ -0,0 +1 @@ +../../Task/Base64-decode-data/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Bell-numbers b/Lang/Pluto/Bell-numbers new file mode 120000 index 0000000000..12ebb36a37 --- /dev/null +++ b/Lang/Pluto/Bell-numbers @@ -0,0 +1 @@ +../../Task/Bell-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Benfords-law b/Lang/Pluto/Benfords-law new file mode 120000 index 0000000000..b781bccffa --- /dev/null +++ b/Lang/Pluto/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Bernoulli-numbers b/Lang/Pluto/Bernoulli-numbers new file mode 120000 index 0000000000..def2b8378f --- /dev/null +++ b/Lang/Pluto/Bernoulli-numbers @@ -0,0 +1 @@ +../../Task/Bernoulli-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Best-shuffle b/Lang/Pluto/Best-shuffle new file mode 120000 index 0000000000..eb98710b09 --- /dev/null +++ b/Lang/Pluto/Best-shuffle @@ -0,0 +1 @@ +../../Task/Best-shuffle/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Bifid-cipher b/Lang/Pluto/Bifid-cipher new file mode 120000 index 0000000000..7fb890e12d --- /dev/null +++ b/Lang/Pluto/Bifid-cipher @@ -0,0 +1 @@ +../../Task/Bifid-cipher/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Bin-given-limits b/Lang/Pluto/Bin-given-limits new file mode 120000 index 0000000000..89b9600240 --- /dev/null +++ b/Lang/Pluto/Bin-given-limits @@ -0,0 +1 @@ +../../Task/Bin-given-limits/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Binary-search b/Lang/Pluto/Binary-search new file mode 120000 index 0000000000..a0b45e9e17 --- /dev/null +++ b/Lang/Pluto/Binary-search @@ -0,0 +1 @@ +../../Task/Binary-search/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Binary-strings b/Lang/Pluto/Binary-strings new file mode 120000 index 0000000000..fbf99b0505 --- /dev/null +++ b/Lang/Pluto/Binary-strings @@ -0,0 +1 @@ +../../Task/Binary-strings/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Biorhythms b/Lang/Pluto/Biorhythms new file mode 120000 index 0000000000..22eb307022 --- /dev/null +++ b/Lang/Pluto/Biorhythms @@ -0,0 +1 @@ +../../Task/Biorhythms/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Bitcoin-address-validation b/Lang/Pluto/Bitcoin-address-validation new file mode 120000 index 0000000000..44983f1ea0 --- /dev/null +++ b/Lang/Pluto/Bitcoin-address-validation @@ -0,0 +1 @@ +../../Task/Bitcoin-address-validation/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Bitmap b/Lang/Pluto/Bitmap new file mode 120000 index 0000000000..2eae4de5c9 --- /dev/null +++ b/Lang/Pluto/Bitmap @@ -0,0 +1 @@ +../../Task/Bitmap/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Bitmap-Bresenhams-line-algorithm b/Lang/Pluto/Bitmap-Bresenhams-line-algorithm new file mode 120000 index 0000000000..648ca4156e --- /dev/null +++ b/Lang/Pluto/Bitmap-Bresenhams-line-algorithm @@ -0,0 +1 @@ +../../Task/Bitmap-Bresenhams-line-algorithm/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Bitmap-Midpoint-circle-algorithm b/Lang/Pluto/Bitmap-Midpoint-circle-algorithm new file mode 120000 index 0000000000..30e98198c1 --- /dev/null +++ b/Lang/Pluto/Bitmap-Midpoint-circle-algorithm @@ -0,0 +1 @@ +../../Task/Bitmap-Midpoint-circle-algorithm/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Bitwise-operations b/Lang/Pluto/Bitwise-operations new file mode 120000 index 0000000000..7aa2755b89 --- /dev/null +++ b/Lang/Pluto/Bitwise-operations @@ -0,0 +1 @@ +../../Task/Bitwise-operations/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Blum-integer b/Lang/Pluto/Blum-integer new file mode 120000 index 0000000000..29fd128c56 --- /dev/null +++ b/Lang/Pluto/Blum-integer @@ -0,0 +1 @@ +../../Task/Blum-integer/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Box-the-compass b/Lang/Pluto/Box-the-compass new file mode 120000 index 0000000000..06e763904d --- /dev/null +++ b/Lang/Pluto/Box-the-compass @@ -0,0 +1 @@ +../../Task/Box-the-compass/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Brazilian-numbers b/Lang/Pluto/Brazilian-numbers new file mode 120000 index 0000000000..2847bc95cf --- /dev/null +++ b/Lang/Pluto/Brazilian-numbers @@ -0,0 +1 @@ +../../Task/Brazilian-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Break-OO-privacy b/Lang/Pluto/Break-OO-privacy new file mode 120000 index 0000000000..00a12e0cb3 --- /dev/null +++ b/Lang/Pluto/Break-OO-privacy @@ -0,0 +1 @@ +../../Task/Break-OO-privacy/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Brilliant-numbers b/Lang/Pluto/Brilliant-numbers new file mode 120000 index 0000000000..3c956fa37f --- /dev/null +++ b/Lang/Pluto/Brilliant-numbers @@ -0,0 +1 @@ +../../Task/Brilliant-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Burrows-Wheeler-transform b/Lang/Pluto/Burrows-Wheeler-transform new file mode 120000 index 0000000000..d346f62601 --- /dev/null +++ b/Lang/Pluto/Burrows-Wheeler-transform @@ -0,0 +1 @@ +../../Task/Burrows-Wheeler-transform/Pluto \ No newline at end of file diff --git a/Lang/Pluto/CRC-32 b/Lang/Pluto/CRC-32 new file mode 120000 index 0000000000..a2f9755cc8 --- /dev/null +++ b/Lang/Pluto/CRC-32 @@ -0,0 +1 @@ +../../Task/CRC-32/Pluto \ No newline at end of file diff --git a/Lang/Pluto/CUSIP b/Lang/Pluto/CUSIP new file mode 120000 index 0000000000..ffc1be79c9 --- /dev/null +++ b/Lang/Pluto/CUSIP @@ -0,0 +1 @@ +../../Task/CUSIP/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Caesar-cipher b/Lang/Pluto/Caesar-cipher new file mode 120000 index 0000000000..92165c560f --- /dev/null +++ b/Lang/Pluto/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Calculating-the-value-of-e b/Lang/Pluto/Calculating-the-value-of-e new file mode 120000 index 0000000000..c85ceb9feb --- /dev/null +++ b/Lang/Pluto/Calculating-the-value-of-e @@ -0,0 +1 @@ +../../Task/Calculating-the-value-of-e/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Calkin-Wilf-sequence b/Lang/Pluto/Calkin-Wilf-sequence new file mode 120000 index 0000000000..e7c08bf16e --- /dev/null +++ b/Lang/Pluto/Calkin-Wilf-sequence @@ -0,0 +1 @@ +../../Task/Calkin-Wilf-sequence/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Call-a-foreign-language-function b/Lang/Pluto/Call-a-foreign-language-function new file mode 120000 index 0000000000..f071bb1596 --- /dev/null +++ b/Lang/Pluto/Call-a-foreign-language-function @@ -0,0 +1 @@ +../../Task/Call-a-foreign-language-function/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Call-a-function-in-a-shared-library b/Lang/Pluto/Call-a-function-in-a-shared-library new file mode 120000 index 0000000000..fb03a37240 --- /dev/null +++ b/Lang/Pluto/Call-a-function-in-a-shared-library @@ -0,0 +1 @@ +../../Task/Call-a-function-in-a-shared-library/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Call-an-object-method b/Lang/Pluto/Call-an-object-method new file mode 120000 index 0000000000..9b34265855 --- /dev/null +++ b/Lang/Pluto/Call-an-object-method @@ -0,0 +1 @@ +../../Task/Call-an-object-method/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Camel-case-and-snake-case b/Lang/Pluto/Camel-case-and-snake-case new file mode 120000 index 0000000000..63e934e944 --- /dev/null +++ b/Lang/Pluto/Camel-case-and-snake-case @@ -0,0 +1 @@ +../../Task/Camel-case-and-snake-case/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Canonicalize-CIDR b/Lang/Pluto/Canonicalize-CIDR new file mode 120000 index 0000000000..47427dcbdb --- /dev/null +++ b/Lang/Pluto/Canonicalize-CIDR @@ -0,0 +1 @@ +../../Task/Canonicalize-CIDR/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Cantor-set b/Lang/Pluto/Cantor-set new file mode 120000 index 0000000000..e41e42a9fe --- /dev/null +++ b/Lang/Pluto/Cantor-set @@ -0,0 +1 @@ +../../Task/Cantor-set/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Carmichael-3-strong-pseudoprimes b/Lang/Pluto/Carmichael-3-strong-pseudoprimes new file mode 120000 index 0000000000..15460b52f8 --- /dev/null +++ b/Lang/Pluto/Carmichael-3-strong-pseudoprimes @@ -0,0 +1 @@ +../../Task/Carmichael-3-strong-pseudoprimes/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Case-sensitivity-of-identifiers b/Lang/Pluto/Case-sensitivity-of-identifiers new file mode 120000 index 0000000000..e37b951419 --- /dev/null +++ b/Lang/Pluto/Case-sensitivity-of-identifiers @@ -0,0 +1 @@ +../../Task/Case-sensitivity-of-identifiers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Casting-out-nines b/Lang/Pluto/Casting-out-nines new file mode 120000 index 0000000000..f9d2b5090f --- /dev/null +++ b/Lang/Pluto/Casting-out-nines @@ -0,0 +1 @@ +../../Task/Casting-out-nines/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Catalan-numbers b/Lang/Pluto/Catalan-numbers new file mode 120000 index 0000000000..13ef84ea7e --- /dev/null +++ b/Lang/Pluto/Catalan-numbers @@ -0,0 +1 @@ +../../Task/Catalan-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Catalan-numbers-Pascals-triangle b/Lang/Pluto/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..ba6ed52865 --- /dev/null +++ b/Lang/Pluto/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Catamorphism b/Lang/Pluto/Catamorphism new file mode 120000 index 0000000000..5d492b9b1c --- /dev/null +++ b/Lang/Pluto/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Chaocipher b/Lang/Pluto/Chaocipher new file mode 120000 index 0000000000..a4b28d7a7d --- /dev/null +++ b/Lang/Pluto/Chaocipher @@ -0,0 +1 @@ +../../Task/Chaocipher/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Check-input-device-is-a-terminal b/Lang/Pluto/Check-input-device-is-a-terminal new file mode 120000 index 0000000000..3b90efa3c8 --- /dev/null +++ b/Lang/Pluto/Check-input-device-is-a-terminal @@ -0,0 +1 @@ +../../Task/Check-input-device-is-a-terminal/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Check-output-device-is-a-terminal b/Lang/Pluto/Check-output-device-is-a-terminal new file mode 120000 index 0000000000..fc1799c10c --- /dev/null +++ b/Lang/Pluto/Check-output-device-is-a-terminal @@ -0,0 +1 @@ +../../Task/Check-output-device-is-a-terminal/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Check-that-file-exists b/Lang/Pluto/Check-that-file-exists new file mode 120000 index 0000000000..4438ce2610 --- /dev/null +++ b/Lang/Pluto/Check-that-file-exists @@ -0,0 +1 @@ +../../Task/Check-that-file-exists/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Chernicks-Carmichael-numbers b/Lang/Pluto/Chernicks-Carmichael-numbers new file mode 120000 index 0000000000..027fba1c47 --- /dev/null +++ b/Lang/Pluto/Chernicks-Carmichael-numbers @@ -0,0 +1 @@ +../../Task/Chernicks-Carmichael-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Cheryls-birthday b/Lang/Pluto/Cheryls-birthday new file mode 120000 index 0000000000..30af57e589 --- /dev/null +++ b/Lang/Pluto/Cheryls-birthday @@ -0,0 +1 @@ +../../Task/Cheryls-birthday/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Chinese-remainder-theorem b/Lang/Pluto/Chinese-remainder-theorem new file mode 120000 index 0000000000..9b0d96ce42 --- /dev/null +++ b/Lang/Pluto/Chinese-remainder-theorem @@ -0,0 +1 @@ +../../Task/Chinese-remainder-theorem/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Chinese-zodiac b/Lang/Pluto/Chinese-zodiac new file mode 120000 index 0000000000..9268137a2b --- /dev/null +++ b/Lang/Pluto/Chinese-zodiac @@ -0,0 +1 @@ +../../Task/Chinese-zodiac/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Cholesky-decomposition b/Lang/Pluto/Cholesky-decomposition new file mode 120000 index 0000000000..87b60466d9 --- /dev/null +++ b/Lang/Pluto/Cholesky-decomposition @@ -0,0 +1 @@ +../../Task/Cholesky-decomposition/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Chowla-numbers b/Lang/Pluto/Chowla-numbers new file mode 120000 index 0000000000..b10ca6f6d9 --- /dev/null +++ b/Lang/Pluto/Chowla-numbers @@ -0,0 +1 @@ +../../Task/Chowla-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Church-numerals b/Lang/Pluto/Church-numerals new file mode 120000 index 0000000000..1d195312b9 --- /dev/null +++ b/Lang/Pluto/Church-numerals @@ -0,0 +1 @@ +../../Task/Church-numerals/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Circles-of-given-radius-through-two-points b/Lang/Pluto/Circles-of-given-radius-through-two-points new file mode 120000 index 0000000000..95277c7cbf --- /dev/null +++ b/Lang/Pluto/Circles-of-given-radius-through-two-points @@ -0,0 +1 @@ +../../Task/Circles-of-given-radius-through-two-points/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Circular-primes b/Lang/Pluto/Circular-primes new file mode 120000 index 0000000000..03acc9542a --- /dev/null +++ b/Lang/Pluto/Circular-primes @@ -0,0 +1 @@ +../../Task/Circular-primes/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Classes b/Lang/Pluto/Classes new file mode 120000 index 0000000000..26462a13cb --- /dev/null +++ b/Lang/Pluto/Classes @@ -0,0 +1 @@ +../../Task/Classes/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Closest-pair-problem b/Lang/Pluto/Closest-pair-problem new file mode 120000 index 0000000000..37a54ff46b --- /dev/null +++ b/Lang/Pluto/Closest-pair-problem @@ -0,0 +1 @@ +../../Task/Closest-pair-problem/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Closures-Value-capture b/Lang/Pluto/Closures-Value-capture new file mode 120000 index 0000000000..86d660ee42 --- /dev/null +++ b/Lang/Pluto/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Collections b/Lang/Pluto/Collections new file mode 120000 index 0000000000..82a2dd2b4f --- /dev/null +++ b/Lang/Pluto/Collections @@ -0,0 +1 @@ +../../Task/Collections/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Color-wheel b/Lang/Pluto/Color-wheel new file mode 120000 index 0000000000..1f743faae0 --- /dev/null +++ b/Lang/Pluto/Color-wheel @@ -0,0 +1 @@ +../../Task/Color-wheel/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Colorful-numbers b/Lang/Pluto/Colorful-numbers new file mode 120000 index 0000000000..6fd26697f2 --- /dev/null +++ b/Lang/Pluto/Colorful-numbers @@ -0,0 +1 @@ +../../Task/Colorful-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Combinations b/Lang/Pluto/Combinations new file mode 120000 index 0000000000..1554032a2c --- /dev/null +++ b/Lang/Pluto/Combinations @@ -0,0 +1 @@ +../../Task/Combinations/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Combinations-with-repetitions b/Lang/Pluto/Combinations-with-repetitions new file mode 120000 index 0000000000..27271a521e --- /dev/null +++ b/Lang/Pluto/Combinations-with-repetitions @@ -0,0 +1 @@ +../../Task/Combinations-with-repetitions/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Comma-quibbling b/Lang/Pluto/Comma-quibbling new file mode 120000 index 0000000000..d45769fa57 --- /dev/null +++ b/Lang/Pluto/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Command-line-arguments b/Lang/Pluto/Command-line-arguments new file mode 120000 index 0000000000..0f5f02829e --- /dev/null +++ b/Lang/Pluto/Command-line-arguments @@ -0,0 +1 @@ +../../Task/Command-line-arguments/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Commatizing-numbers b/Lang/Pluto/Commatizing-numbers new file mode 120000 index 0000000000..703f59f582 --- /dev/null +++ b/Lang/Pluto/Commatizing-numbers @@ -0,0 +1 @@ +../../Task/Commatizing-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Comments b/Lang/Pluto/Comments new file mode 120000 index 0000000000..8d1e636123 --- /dev/null +++ b/Lang/Pluto/Comments @@ -0,0 +1 @@ +../../Task/Comments/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Compare-a-list-of-strings b/Lang/Pluto/Compare-a-list-of-strings new file mode 120000 index 0000000000..6f0ca59023 --- /dev/null +++ b/Lang/Pluto/Compare-a-list-of-strings @@ -0,0 +1 @@ +../../Task/Compare-a-list-of-strings/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Compare-length-of-two-strings b/Lang/Pluto/Compare-length-of-two-strings new file mode 120000 index 0000000000..a17ca1cb1f --- /dev/null +++ b/Lang/Pluto/Compare-length-of-two-strings @@ -0,0 +1 @@ +../../Task/Compare-length-of-two-strings/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Compile-time-calculation b/Lang/Pluto/Compile-time-calculation new file mode 120000 index 0000000000..f08af0ba8e --- /dev/null +++ b/Lang/Pluto/Compile-time-calculation @@ -0,0 +1 @@ +../../Task/Compile-time-calculation/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Compiler-lexical-analyzer b/Lang/Pluto/Compiler-lexical-analyzer new file mode 120000 index 0000000000..0e5b3d7d41 --- /dev/null +++ b/Lang/Pluto/Compiler-lexical-analyzer @@ -0,0 +1 @@ +../../Task/Compiler-lexical-analyzer/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Compound-data-type b/Lang/Pluto/Compound-data-type new file mode 120000 index 0000000000..d8d7d92b91 --- /dev/null +++ b/Lang/Pluto/Compound-data-type @@ -0,0 +1 @@ +../../Task/Compound-data-type/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Concurrent-computing b/Lang/Pluto/Concurrent-computing new file mode 120000 index 0000000000..edc4e372c5 --- /dev/null +++ b/Lang/Pluto/Concurrent-computing @@ -0,0 +1 @@ +../../Task/Concurrent-computing/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Conditional-structures b/Lang/Pluto/Conditional-structures new file mode 120000 index 0000000000..480797a688 --- /dev/null +++ b/Lang/Pluto/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Conjugate-transpose b/Lang/Pluto/Conjugate-transpose new file mode 120000 index 0000000000..dfb7444c0e --- /dev/null +++ b/Lang/Pluto/Conjugate-transpose @@ -0,0 +1 @@ +../../Task/Conjugate-transpose/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Consecutive-primes-with-ascending-or-descending-differences b/Lang/Pluto/Consecutive-primes-with-ascending-or-descending-differences new file mode 120000 index 0000000000..855ac67f9b --- /dev/null +++ b/Lang/Pluto/Consecutive-primes-with-ascending-or-descending-differences @@ -0,0 +1 @@ +../../Task/Consecutive-primes-with-ascending-or-descending-differences/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Constrained-genericity b/Lang/Pluto/Constrained-genericity new file mode 120000 index 0000000000..27aef58dac --- /dev/null +++ b/Lang/Pluto/Constrained-genericity @@ -0,0 +1 @@ +../../Task/Constrained-genericity/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Continued-fraction b/Lang/Pluto/Continued-fraction new file mode 120000 index 0000000000..413f477143 --- /dev/null +++ b/Lang/Pluto/Continued-fraction @@ -0,0 +1 @@ +../../Task/Continued-fraction/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Continued-fraction-Arithmetic-Construct-from-rational-number b/Lang/Pluto/Continued-fraction-Arithmetic-Construct-from-rational-number new file mode 120000 index 0000000000..4207df96c4 --- /dev/null +++ b/Lang/Pluto/Continued-fraction-Arithmetic-Construct-from-rational-number @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Convert-decimal-number-to-rational b/Lang/Pluto/Convert-decimal-number-to-rational new file mode 120000 index 0000000000..67bc18205b --- /dev/null +++ b/Lang/Pluto/Convert-decimal-number-to-rational @@ -0,0 +1 @@ +../../Task/Convert-decimal-number-to-rational/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Convert-seconds-to-compound-duration b/Lang/Pluto/Convert-seconds-to-compound-duration new file mode 120000 index 0000000000..694dec3e9d --- /dev/null +++ b/Lang/Pluto/Convert-seconds-to-compound-duration @@ -0,0 +1 @@ +../../Task/Convert-seconds-to-compound-duration/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Count-in-factors b/Lang/Pluto/Count-in-factors new file mode 120000 index 0000000000..875d6814c3 --- /dev/null +++ b/Lang/Pluto/Count-in-factors @@ -0,0 +1 @@ +../../Task/Count-in-factors/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Count-in-octal b/Lang/Pluto/Count-in-octal new file mode 120000 index 0000000000..c5624def8e --- /dev/null +++ b/Lang/Pluto/Count-in-octal @@ -0,0 +1 @@ +../../Task/Count-in-octal/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Count-occurrences-of-a-substring b/Lang/Pluto/Count-occurrences-of-a-substring new file mode 120000 index 0000000000..282d7ede4a --- /dev/null +++ b/Lang/Pluto/Count-occurrences-of-a-substring @@ -0,0 +1 @@ +../../Task/Count-occurrences-of-a-substring/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Count-the-coins b/Lang/Pluto/Count-the-coins new file mode 120000 index 0000000000..7996299523 --- /dev/null +++ b/Lang/Pluto/Count-the-coins @@ -0,0 +1 @@ +../../Task/Count-the-coins/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Cramers-rule b/Lang/Pluto/Cramers-rule new file mode 120000 index 0000000000..371e1d9db7 --- /dev/null +++ b/Lang/Pluto/Cramers-rule @@ -0,0 +1 @@ +../../Task/Cramers-rule/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Create-a-file b/Lang/Pluto/Create-a-file new file mode 120000 index 0000000000..1e22b0b1e3 --- /dev/null +++ b/Lang/Pluto/Create-a-file @@ -0,0 +1 @@ +../../Task/Create-a-file/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Create-a-two-dimensional-array-at-runtime b/Lang/Pluto/Create-a-two-dimensional-array-at-runtime new file mode 120000 index 0000000000..4da351e86e --- /dev/null +++ b/Lang/Pluto/Create-a-two-dimensional-array-at-runtime @@ -0,0 +1 @@ +../../Task/Create-a-two-dimensional-array-at-runtime/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Cuban-primes b/Lang/Pluto/Cuban-primes new file mode 120000 index 0000000000..6b91d15127 --- /dev/null +++ b/Lang/Pluto/Cuban-primes @@ -0,0 +1 @@ +../../Task/Cuban-primes/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Cullen-and-Woodall-numbers b/Lang/Pluto/Cullen-and-Woodall-numbers new file mode 120000 index 0000000000..663a789226 --- /dev/null +++ b/Lang/Pluto/Cullen-and-Woodall-numbers @@ -0,0 +1 @@ +../../Task/Cullen-and-Woodall-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Cumulative-standard-deviation b/Lang/Pluto/Cumulative-standard-deviation new file mode 120000 index 0000000000..bfd250d57c --- /dev/null +++ b/Lang/Pluto/Cumulative-standard-deviation @@ -0,0 +1 @@ +../../Task/Cumulative-standard-deviation/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Currency b/Lang/Pluto/Currency new file mode 120000 index 0000000000..022bd123d4 --- /dev/null +++ b/Lang/Pluto/Currency @@ -0,0 +1 @@ +../../Task/Currency/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Currying b/Lang/Pluto/Currying new file mode 120000 index 0000000000..98e5282551 --- /dev/null +++ b/Lang/Pluto/Currying @@ -0,0 +1 @@ +../../Task/Currying/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Curzon-numbers b/Lang/Pluto/Curzon-numbers new file mode 120000 index 0000000000..19e831cce8 --- /dev/null +++ b/Lang/Pluto/Curzon-numbers @@ -0,0 +1 @@ +../../Task/Curzon-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Cut-a-rectangle b/Lang/Pluto/Cut-a-rectangle new file mode 120000 index 0000000000..503ba83f0f --- /dev/null +++ b/Lang/Pluto/Cut-a-rectangle @@ -0,0 +1 @@ +../../Task/Cut-a-rectangle/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Cyclops-numbers b/Lang/Pluto/Cyclops-numbers new file mode 120000 index 0000000000..c731e7f9d2 --- /dev/null +++ b/Lang/Pluto/Cyclops-numbers @@ -0,0 +1 @@ +../../Task/Cyclops-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/DNS-query b/Lang/Pluto/DNS-query new file mode 120000 index 0000000000..abafcfbe46 --- /dev/null +++ b/Lang/Pluto/DNS-query @@ -0,0 +1 @@ +../../Task/DNS-query/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Damm-algorithm b/Lang/Pluto/Damm-algorithm new file mode 120000 index 0000000000..4db0c540c5 --- /dev/null +++ b/Lang/Pluto/Damm-algorithm @@ -0,0 +1 @@ +../../Task/Damm-algorithm/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Date-format b/Lang/Pluto/Date-format new file mode 120000 index 0000000000..e6307f8af0 --- /dev/null +++ b/Lang/Pluto/Date-format @@ -0,0 +1 @@ +../../Task/Date-format/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Date-manipulation b/Lang/Pluto/Date-manipulation new file mode 120000 index 0000000000..541e3b8538 --- /dev/null +++ b/Lang/Pluto/Date-manipulation @@ -0,0 +1 @@ +../../Task/Date-manipulation/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Day-of-the-week b/Lang/Pluto/Day-of-the-week new file mode 120000 index 0000000000..c857bee861 --- /dev/null +++ b/Lang/Pluto/Day-of-the-week @@ -0,0 +1 @@ +../../Task/Day-of-the-week/Pluto \ No newline at end of file diff --git a/Lang/Pluto/De-Bruijn-sequences b/Lang/Pluto/De-Bruijn-sequences new file mode 120000 index 0000000000..7208c6eb97 --- /dev/null +++ b/Lang/Pluto/De-Bruijn-sequences @@ -0,0 +1 @@ +../../Task/De-Bruijn-sequences/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Deceptive-numbers b/Lang/Pluto/Deceptive-numbers new file mode 120000 index 0000000000..f13a36d2f4 --- /dev/null +++ b/Lang/Pluto/Deceptive-numbers @@ -0,0 +1 @@ +../../Task/Deceptive-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Deepcopy b/Lang/Pluto/Deepcopy new file mode 120000 index 0000000000..066df45f7c --- /dev/null +++ b/Lang/Pluto/Deepcopy @@ -0,0 +1 @@ +../../Task/Deepcopy/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Delegates b/Lang/Pluto/Delegates new file mode 120000 index 0000000000..52103da749 --- /dev/null +++ b/Lang/Pluto/Delegates @@ -0,0 +1 @@ +../../Task/Delegates/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Delete-a-file b/Lang/Pluto/Delete-a-file new file mode 120000 index 0000000000..b17ce9999b --- /dev/null +++ b/Lang/Pluto/Delete-a-file @@ -0,0 +1 @@ +../../Task/Delete-a-file/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Demings-funnel b/Lang/Pluto/Demings-funnel new file mode 120000 index 0000000000..56a8ba2ece --- /dev/null +++ b/Lang/Pluto/Demings-funnel @@ -0,0 +1 @@ +../../Task/Demings-funnel/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Department-numbers b/Lang/Pluto/Department-numbers new file mode 120000 index 0000000000..1666a30ed8 --- /dev/null +++ b/Lang/Pluto/Department-numbers @@ -0,0 +1 @@ +../../Task/Department-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Descending-primes b/Lang/Pluto/Descending-primes new file mode 120000 index 0000000000..c35e1667b5 --- /dev/null +++ b/Lang/Pluto/Descending-primes @@ -0,0 +1 @@ +../../Task/Descending-primes/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Detect-division-by-zero b/Lang/Pluto/Detect-division-by-zero new file mode 120000 index 0000000000..36d9e93987 --- /dev/null +++ b/Lang/Pluto/Detect-division-by-zero @@ -0,0 +1 @@ +../../Task/Detect-division-by-zero/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Determinant-and-permanent b/Lang/Pluto/Determinant-and-permanent new file mode 120000 index 0000000000..e1b29bc12a --- /dev/null +++ b/Lang/Pluto/Determinant-and-permanent @@ -0,0 +1 @@ +../../Task/Determinant-and-permanent/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Determine-if-a-string-has-all-the-same-characters b/Lang/Pluto/Determine-if-a-string-has-all-the-same-characters new file mode 120000 index 0000000000..030ea85992 --- /dev/null +++ b/Lang/Pluto/Determine-if-a-string-has-all-the-same-characters @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-has-all-the-same-characters/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Determine-if-a-string-has-all-unique-characters b/Lang/Pluto/Determine-if-a-string-has-all-unique-characters new file mode 120000 index 0000000000..79e7e032c2 --- /dev/null +++ b/Lang/Pluto/Determine-if-a-string-has-all-unique-characters @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-has-all-unique-characters/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Determine-if-a-string-is-collapsible b/Lang/Pluto/Determine-if-a-string-is-collapsible new file mode 120000 index 0000000000..dac3838017 --- /dev/null +++ b/Lang/Pluto/Determine-if-a-string-is-collapsible @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-collapsible/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Determine-if-a-string-is-numeric b/Lang/Pluto/Determine-if-a-string-is-numeric new file mode 120000 index 0000000000..f3177e5d6e --- /dev/null +++ b/Lang/Pluto/Determine-if-a-string-is-numeric @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-numeric/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Determine-if-a-string-is-squeezable b/Lang/Pluto/Determine-if-a-string-is-squeezable new file mode 120000 index 0000000000..17dbb0267a --- /dev/null +++ b/Lang/Pluto/Determine-if-a-string-is-squeezable @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-squeezable/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Determine-if-two-triangles-overlap b/Lang/Pluto/Determine-if-two-triangles-overlap new file mode 120000 index 0000000000..d35e94d3a0 --- /dev/null +++ b/Lang/Pluto/Determine-if-two-triangles-overlap @@ -0,0 +1 @@ +../../Task/Determine-if-two-triangles-overlap/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Determine-sentence-type b/Lang/Pluto/Determine-sentence-type new file mode 120000 index 0000000000..d97a791028 --- /dev/null +++ b/Lang/Pluto/Determine-sentence-type @@ -0,0 +1 @@ +../../Task/Determine-sentence-type/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Dice-game-probabilities b/Lang/Pluto/Dice-game-probabilities new file mode 120000 index 0000000000..b6d7ab05ea --- /dev/null +++ b/Lang/Pluto/Dice-game-probabilities @@ -0,0 +1 @@ +../../Task/Dice-game-probabilities/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Digital-root b/Lang/Pluto/Digital-root new file mode 120000 index 0000000000..fb194db4fd --- /dev/null +++ b/Lang/Pluto/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Digital-root-Multiplicative-digital-root b/Lang/Pluto/Digital-root-Multiplicative-digital-root new file mode 120000 index 0000000000..27b8582991 --- /dev/null +++ b/Lang/Pluto/Digital-root-Multiplicative-digital-root @@ -0,0 +1 @@ +../../Task/Digital-root-Multiplicative-digital-root/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Disarium-numbers b/Lang/Pluto/Disarium-numbers new file mode 120000 index 0000000000..fd659f8581 --- /dev/null +++ b/Lang/Pluto/Disarium-numbers @@ -0,0 +1 @@ +../../Task/Disarium-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Discordian-date b/Lang/Pluto/Discordian-date new file mode 120000 index 0000000000..eef2a0d868 --- /dev/null +++ b/Lang/Pluto/Discordian-date @@ -0,0 +1 @@ +../../Task/Discordian-date/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Display-a-linear-combination b/Lang/Pluto/Display-a-linear-combination new file mode 120000 index 0000000000..b9e618e087 --- /dev/null +++ b/Lang/Pluto/Display-a-linear-combination @@ -0,0 +1 @@ +../../Task/Display-a-linear-combination/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Distribution-of-0-digits-in-factorial-series b/Lang/Pluto/Distribution-of-0-digits-in-factorial-series new file mode 120000 index 0000000000..a06ffa876b --- /dev/null +++ b/Lang/Pluto/Distribution-of-0-digits-in-factorial-series @@ -0,0 +1 @@ +../../Task/Distribution-of-0-digits-in-factorial-series/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Diversity-prediction-theorem b/Lang/Pluto/Diversity-prediction-theorem new file mode 120000 index 0000000000..1855763e0b --- /dev/null +++ b/Lang/Pluto/Diversity-prediction-theorem @@ -0,0 +1 @@ +../../Task/Diversity-prediction-theorem/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Doomsday-rule b/Lang/Pluto/Doomsday-rule new file mode 120000 index 0000000000..0bae1c428f --- /dev/null +++ b/Lang/Pluto/Doomsday-rule @@ -0,0 +1 @@ +../../Task/Doomsday-rule/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Doubly-linked-list-Definition b/Lang/Pluto/Doubly-linked-list-Definition new file mode 120000 index 0000000000..2c673acc7c --- /dev/null +++ b/Lang/Pluto/Doubly-linked-list-Definition @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Definition/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Doubly-linked-list-Element-definition b/Lang/Pluto/Doubly-linked-list-Element-definition new file mode 120000 index 0000000000..7b2f1839e3 --- /dev/null +++ b/Lang/Pluto/Doubly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Element-definition/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Doubly-linked-list-Element-insertion b/Lang/Pluto/Doubly-linked-list-Element-insertion new file mode 120000 index 0000000000..566d3ce443 --- /dev/null +++ b/Lang/Pluto/Doubly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Element-insertion/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Doubly-linked-list-Traversal b/Lang/Pluto/Doubly-linked-list-Traversal new file mode 120000 index 0000000000..9a9262d67b --- /dev/null +++ b/Lang/Pluto/Doubly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Traversal/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Dragon-curve b/Lang/Pluto/Dragon-curve new file mode 120000 index 0000000000..f1e72e5ef1 --- /dev/null +++ b/Lang/Pluto/Dragon-curve @@ -0,0 +1 @@ +../../Task/Dragon-curve/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Draw-a-sphere b/Lang/Pluto/Draw-a-sphere new file mode 120000 index 0000000000..639e598bda --- /dev/null +++ b/Lang/Pluto/Draw-a-sphere @@ -0,0 +1 @@ +../../Task/Draw-a-sphere/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Dutch-national-flag-problem b/Lang/Pluto/Dutch-national-flag-problem new file mode 120000 index 0000000000..4ca6eb0344 --- /dev/null +++ b/Lang/Pluto/Dutch-national-flag-problem @@ -0,0 +1 @@ +../../Task/Dutch-national-flag-problem/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Dynamic-variable-names b/Lang/Pluto/Dynamic-variable-names new file mode 120000 index 0000000000..9f84b3a575 --- /dev/null +++ b/Lang/Pluto/Dynamic-variable-names @@ -0,0 +1 @@ +../../Task/Dynamic-variable-names/Pluto \ No newline at end of file diff --git a/Lang/Pluto/EKG-sequence-convergence b/Lang/Pluto/EKG-sequence-convergence new file mode 120000 index 0000000000..5e7a87aa27 --- /dev/null +++ b/Lang/Pluto/EKG-sequence-convergence @@ -0,0 +1 @@ +../../Task/EKG-sequence-convergence/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Earliest-difference-between-prime-gaps b/Lang/Pluto/Earliest-difference-between-prime-gaps new file mode 120000 index 0000000000..7c35dd843e --- /dev/null +++ b/Lang/Pluto/Earliest-difference-between-prime-gaps @@ -0,0 +1 @@ +../../Task/Earliest-difference-between-prime-gaps/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Eban-numbers b/Lang/Pluto/Eban-numbers new file mode 120000 index 0000000000..3c27b7fc5e --- /dev/null +++ b/Lang/Pluto/Eban-numbers @@ -0,0 +1 @@ +../../Task/Eban-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Egyptian-division b/Lang/Pluto/Egyptian-division new file mode 120000 index 0000000000..1935b9a4b4 --- /dev/null +++ b/Lang/Pluto/Egyptian-division @@ -0,0 +1 @@ +../../Task/Egyptian-division/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Element-wise-operations b/Lang/Pluto/Element-wise-operations new file mode 120000 index 0000000000..a809ac3319 --- /dev/null +++ b/Lang/Pluto/Element-wise-operations @@ -0,0 +1 @@ +../../Task/Element-wise-operations/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Elementary-cellular-automaton-Random-number-generator b/Lang/Pluto/Elementary-cellular-automaton-Random-number-generator new file mode 120000 index 0000000000..c9e4dd2c5e --- /dev/null +++ b/Lang/Pluto/Elementary-cellular-automaton-Random-number-generator @@ -0,0 +1 @@ +../../Task/Elementary-cellular-automaton-Random-number-generator/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Elliptic-curve-arithmetic b/Lang/Pluto/Elliptic-curve-arithmetic new file mode 120000 index 0000000000..01ab3acc14 --- /dev/null +++ b/Lang/Pluto/Elliptic-curve-arithmetic @@ -0,0 +1 @@ +../../Task/Elliptic-curve-arithmetic/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Emirp-primes b/Lang/Pluto/Emirp-primes new file mode 120000 index 0000000000..70bc487ce4 --- /dev/null +++ b/Lang/Pluto/Emirp-primes @@ -0,0 +1 @@ +../../Task/Emirp-primes/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Entropy b/Lang/Pluto/Entropy new file mode 120000 index 0000000000..ad4816da25 --- /dev/null +++ b/Lang/Pluto/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Entropy-Narcissist b/Lang/Pluto/Entropy-Narcissist new file mode 120000 index 0000000000..b44bd0dceb --- /dev/null +++ b/Lang/Pluto/Entropy-Narcissist @@ -0,0 +1 @@ +../../Task/Entropy-Narcissist/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Enumerations b/Lang/Pluto/Enumerations new file mode 120000 index 0000000000..f1e25dcea7 --- /dev/null +++ b/Lang/Pluto/Enumerations @@ -0,0 +1 @@ +../../Task/Enumerations/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Environment-variables b/Lang/Pluto/Environment-variables new file mode 120000 index 0000000000..544499e35f --- /dev/null +++ b/Lang/Pluto/Environment-variables @@ -0,0 +1 @@ +../../Task/Environment-variables/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Equal-prime-and-composite-sums b/Lang/Pluto/Equal-prime-and-composite-sums new file mode 120000 index 0000000000..5924d0c24d --- /dev/null +++ b/Lang/Pluto/Equal-prime-and-composite-sums @@ -0,0 +1 @@ +../../Task/Equal-prime-and-composite-sums/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Equilibrium-index b/Lang/Pluto/Equilibrium-index new file mode 120000 index 0000000000..d670c800de --- /dev/null +++ b/Lang/Pluto/Equilibrium-index @@ -0,0 +1 @@ +../../Task/Equilibrium-index/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Erd-s-Selfridge-categorization-of-primes b/Lang/Pluto/Erd-s-Selfridge-categorization-of-primes new file mode 120000 index 0000000000..ee9715de69 --- /dev/null +++ b/Lang/Pluto/Erd-s-Selfridge-categorization-of-primes @@ -0,0 +1 @@ +../../Task/Erd-s-Selfridge-categorization-of-primes/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Esthetic-numbers b/Lang/Pluto/Esthetic-numbers new file mode 120000 index 0000000000..5b009a94ca --- /dev/null +++ b/Lang/Pluto/Esthetic-numbers @@ -0,0 +1 @@ +../../Task/Esthetic-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Ethiopian-multiplication b/Lang/Pluto/Ethiopian-multiplication new file mode 120000 index 0000000000..b71d5e1260 --- /dev/null +++ b/Lang/Pluto/Ethiopian-multiplication @@ -0,0 +1 @@ +../../Task/Ethiopian-multiplication/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Euclid-Mullin-sequence b/Lang/Pluto/Euclid-Mullin-sequence new file mode 120000 index 0000000000..4b920b7289 --- /dev/null +++ b/Lang/Pluto/Euclid-Mullin-sequence @@ -0,0 +1 @@ +../../Task/Euclid-Mullin-sequence/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Euler-method b/Lang/Pluto/Euler-method new file mode 120000 index 0000000000..b7dbfe93a0 --- /dev/null +++ b/Lang/Pluto/Euler-method @@ -0,0 +1 @@ +../../Task/Euler-method/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Eulers-constant-0.5772... b/Lang/Pluto/Eulers-constant-0.5772... new file mode 120000 index 0000000000..43d30a3576 --- /dev/null +++ b/Lang/Pluto/Eulers-constant-0.5772... @@ -0,0 +1 @@ +../../Task/Eulers-constant-0.5772.../Pluto \ No newline at end of file diff --git a/Lang/Pluto/Eulers-identity b/Lang/Pluto/Eulers-identity new file mode 120000 index 0000000000..97a4ba8ed8 --- /dev/null +++ b/Lang/Pluto/Eulers-identity @@ -0,0 +1 @@ +../../Task/Eulers-identity/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Eulers-sum-of-powers-conjecture b/Lang/Pluto/Eulers-sum-of-powers-conjecture new file mode 120000 index 0000000000..d14dd7e926 --- /dev/null +++ b/Lang/Pluto/Eulers-sum-of-powers-conjecture @@ -0,0 +1 @@ +../../Task/Eulers-sum-of-powers-conjecture/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Evaluate-binomial-coefficients b/Lang/Pluto/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..00328c39e4 --- /dev/null +++ b/Lang/Pluto/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Even-or-odd b/Lang/Pluto/Even-or-odd new file mode 120000 index 0000000000..fc5cc6a785 --- /dev/null +++ b/Lang/Pluto/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Exceptions b/Lang/Pluto/Exceptions new file mode 120000 index 0000000000..d201ead5a3 --- /dev/null +++ b/Lang/Pluto/Exceptions @@ -0,0 +1 @@ +../../Task/Exceptions/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Exceptions-Catch-an-exception-thrown-in-a-nested-call b/Lang/Pluto/Exceptions-Catch-an-exception-thrown-in-a-nested-call new file mode 120000 index 0000000000..eeff87c8ee --- /dev/null +++ b/Lang/Pluto/Exceptions-Catch-an-exception-thrown-in-a-nested-call @@ -0,0 +1 @@ +../../Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Execute-Brain- b/Lang/Pluto/Execute-Brain- new file mode 120000 index 0000000000..19151dc329 --- /dev/null +++ b/Lang/Pluto/Execute-Brain- @@ -0,0 +1 @@ +../../Task/Execute-Brain-/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Execute-Computer-Zero b/Lang/Pluto/Execute-Computer-Zero new file mode 120000 index 0000000000..23a9487cf2 --- /dev/null +++ b/Lang/Pluto/Execute-Computer-Zero @@ -0,0 +1 @@ +../../Task/Execute-Computer-Zero/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Execute-a-system-command b/Lang/Pluto/Execute-a-system-command new file mode 120000 index 0000000000..005fc83a4b --- /dev/null +++ b/Lang/Pluto/Execute-a-system-command @@ -0,0 +1 @@ +../../Task/Execute-a-system-command/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Exponentiation-operator b/Lang/Pluto/Exponentiation-operator new file mode 120000 index 0000000000..ebdd988197 --- /dev/null +++ b/Lang/Pluto/Exponentiation-operator @@ -0,0 +1 @@ +../../Task/Exponentiation-operator/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Exponentiation-order b/Lang/Pluto/Exponentiation-order new file mode 120000 index 0000000000..9327e0a3aa --- /dev/null +++ b/Lang/Pluto/Exponentiation-order @@ -0,0 +1 @@ +../../Task/Exponentiation-order/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Exponentiation-with-infix-operators-in-or-operating-on-the-base b/Lang/Pluto/Exponentiation-with-infix-operators-in-or-operating-on-the-base new file mode 120000 index 0000000000..3b14bba6bd --- /dev/null +++ b/Lang/Pluto/Exponentiation-with-infix-operators-in-or-operating-on-the-base @@ -0,0 +1 @@ +../../Task/Exponentiation-with-infix-operators-in-or-operating-on-the-base/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Extensible-prime-generator b/Lang/Pluto/Extensible-prime-generator new file mode 120000 index 0000000000..e39589d864 --- /dev/null +++ b/Lang/Pluto/Extensible-prime-generator @@ -0,0 +1 @@ +../../Task/Extensible-prime-generator/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Extreme-floating-point-values b/Lang/Pluto/Extreme-floating-point-values new file mode 120000 index 0000000000..f7dff2ba0b --- /dev/null +++ b/Lang/Pluto/Extreme-floating-point-values @@ -0,0 +1 @@ +../../Task/Extreme-floating-point-values/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Factorial b/Lang/Pluto/Factorial new file mode 120000 index 0000000000..26b76cb13d --- /dev/null +++ b/Lang/Pluto/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Factorial-primes b/Lang/Pluto/Factorial-primes new file mode 120000 index 0000000000..b57eac84ac --- /dev/null +++ b/Lang/Pluto/Factorial-primes @@ -0,0 +1 @@ +../../Task/Factorial-primes/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Factorions b/Lang/Pluto/Factorions new file mode 120000 index 0000000000..0d6fdce25f --- /dev/null +++ b/Lang/Pluto/Factorions @@ -0,0 +1 @@ +../../Task/Factorions/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Factors-of-a-Mersenne-number b/Lang/Pluto/Factors-of-a-Mersenne-number new file mode 120000 index 0000000000..d60ce6e99f --- /dev/null +++ b/Lang/Pluto/Factors-of-a-Mersenne-number @@ -0,0 +1 @@ +../../Task/Factors-of-a-Mersenne-number/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Factors-of-an-integer b/Lang/Pluto/Factors-of-an-integer new file mode 120000 index 0000000000..cc13f27676 --- /dev/null +++ b/Lang/Pluto/Factors-of-an-integer @@ -0,0 +1 @@ +../../Task/Factors-of-an-integer/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Fairshare-between-two-and-more b/Lang/Pluto/Fairshare-between-two-and-more new file mode 120000 index 0000000000..bfe6b9462c --- /dev/null +++ b/Lang/Pluto/Fairshare-between-two-and-more @@ -0,0 +1 @@ +../../Task/Fairshare-between-two-and-more/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Farey-sequence b/Lang/Pluto/Farey-sequence new file mode 120000 index 0000000000..d29c19b41e --- /dev/null +++ b/Lang/Pluto/Farey-sequence @@ -0,0 +1 @@ +../../Task/Farey-sequence/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Fast-Fourier-transform b/Lang/Pluto/Fast-Fourier-transform new file mode 120000 index 0000000000..d83789d068 --- /dev/null +++ b/Lang/Pluto/Fast-Fourier-transform @@ -0,0 +1 @@ +../../Task/Fast-Fourier-transform/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Feigenbaum-constant-calculation b/Lang/Pluto/Feigenbaum-constant-calculation new file mode 120000 index 0000000000..256bf8cb19 --- /dev/null +++ b/Lang/Pluto/Feigenbaum-constant-calculation @@ -0,0 +1 @@ +../../Task/Feigenbaum-constant-calculation/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Fermat-numbers b/Lang/Pluto/Fermat-numbers new file mode 120000 index 0000000000..45d4d630d7 --- /dev/null +++ b/Lang/Pluto/Fermat-numbers @@ -0,0 +1 @@ +../../Task/Fermat-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Fibonacci-n-step-number-sequences b/Lang/Pluto/Fibonacci-n-step-number-sequences new file mode 120000 index 0000000000..82a6f3ddc3 --- /dev/null +++ b/Lang/Pluto/Fibonacci-n-step-number-sequences @@ -0,0 +1 @@ +../../Task/Fibonacci-n-step-number-sequences/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Fibonacci-sequence b/Lang/Pluto/Fibonacci-sequence new file mode 120000 index 0000000000..efff8e1eb6 --- /dev/null +++ b/Lang/Pluto/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Fibonacci-word b/Lang/Pluto/Fibonacci-word new file mode 120000 index 0000000000..cbcb68d78f --- /dev/null +++ b/Lang/Pluto/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/Pluto \ No newline at end of file diff --git a/Lang/Pluto/File-extension-is-in-extensions-list b/Lang/Pluto/File-extension-is-in-extensions-list new file mode 120000 index 0000000000..7414b8a00c --- /dev/null +++ b/Lang/Pluto/File-extension-is-in-extensions-list @@ -0,0 +1 @@ +../../Task/File-extension-is-in-extensions-list/Pluto \ No newline at end of file diff --git a/Lang/Pluto/File-modification-time b/Lang/Pluto/File-modification-time new file mode 120000 index 0000000000..b0430abc54 --- /dev/null +++ b/Lang/Pluto/File-modification-time @@ -0,0 +1 @@ +../../Task/File-modification-time/Pluto \ No newline at end of file diff --git a/Lang/Pluto/File-size b/Lang/Pluto/File-size new file mode 120000 index 0000000000..998a7a784d --- /dev/null +++ b/Lang/Pluto/File-size @@ -0,0 +1 @@ +../../Task/File-size/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Filter b/Lang/Pluto/Filter new file mode 120000 index 0000000000..98b0321ee6 --- /dev/null +++ b/Lang/Pluto/Filter @@ -0,0 +1 @@ +../../Task/Filter/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Find-if-a-point-is-within-a-triangle b/Lang/Pluto/Find-if-a-point-is-within-a-triangle new file mode 120000 index 0000000000..2f4b95698d --- /dev/null +++ b/Lang/Pluto/Find-if-a-point-is-within-a-triangle @@ -0,0 +1 @@ +../../Task/Find-if-a-point-is-within-a-triangle/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Find-the-last-Sunday-of-each-month b/Lang/Pluto/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..dbefdf7ab1 --- /dev/null +++ b/Lang/Pluto/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/Pluto \ No newline at end of file diff --git a/Lang/Pluto/First-class-functions b/Lang/Pluto/First-class-functions new file mode 120000 index 0000000000..0fe40c3eac --- /dev/null +++ b/Lang/Pluto/First-class-functions @@ -0,0 +1 @@ +../../Task/First-class-functions/Pluto \ No newline at end of file diff --git a/Lang/Pluto/First-class-functions-Use-numbers-analogously b/Lang/Pluto/First-class-functions-Use-numbers-analogously new file mode 120000 index 0000000000..8d26dcc696 --- /dev/null +++ b/Lang/Pluto/First-class-functions-Use-numbers-analogously @@ -0,0 +1 @@ +../../Task/First-class-functions-Use-numbers-analogously/Pluto \ No newline at end of file diff --git a/Lang/Pluto/First-perfect-square-in-base-n-with-n-unique-digits b/Lang/Pluto/First-perfect-square-in-base-n-with-n-unique-digits new file mode 120000 index 0000000000..5163776997 --- /dev/null +++ b/Lang/Pluto/First-perfect-square-in-base-n-with-n-unique-digits @@ -0,0 +1 @@ +../../Task/First-perfect-square-in-base-n-with-n-unique-digits/Pluto \ No newline at end of file diff --git a/Lang/Pluto/First-power-of-2-that-has-leading-decimal-digits-of-12 b/Lang/Pluto/First-power-of-2-that-has-leading-decimal-digits-of-12 new file mode 120000 index 0000000000..e709baba03 --- /dev/null +++ b/Lang/Pluto/First-power-of-2-that-has-leading-decimal-digits-of-12 @@ -0,0 +1 @@ +../../Task/First-power-of-2-that-has-leading-decimal-digits-of-12/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Five-weekends b/Lang/Pluto/Five-weekends new file mode 120000 index 0000000000..00a410b463 --- /dev/null +++ b/Lang/Pluto/Five-weekends @@ -0,0 +1 @@ +../../Task/Five-weekends/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Fivenum b/Lang/Pluto/Fivenum new file mode 120000 index 0000000000..a69f6ae762 --- /dev/null +++ b/Lang/Pluto/Fivenum @@ -0,0 +1 @@ +../../Task/Fivenum/Pluto \ No newline at end of file diff --git a/Lang/Pluto/FizzBuzz b/Lang/Pluto/FizzBuzz new file mode 120000 index 0000000000..bd54d0d8bb --- /dev/null +++ b/Lang/Pluto/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Flatten-a-list b/Lang/Pluto/Flatten-a-list new file mode 120000 index 0000000000..821ee95cae --- /dev/null +++ b/Lang/Pluto/Flatten-a-list @@ -0,0 +1 @@ +../../Task/Flatten-a-list/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Floyd-Warshall-algorithm b/Lang/Pluto/Floyd-Warshall-algorithm new file mode 120000 index 0000000000..7df2d45291 --- /dev/null +++ b/Lang/Pluto/Floyd-Warshall-algorithm @@ -0,0 +1 @@ +../../Task/Floyd-Warshall-algorithm/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Floyds-triangle b/Lang/Pluto/Floyds-triangle new file mode 120000 index 0000000000..7d85d7bf3e --- /dev/null +++ b/Lang/Pluto/Floyds-triangle @@ -0,0 +1 @@ +../../Task/Floyds-triangle/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Formatted-numeric-output b/Lang/Pluto/Formatted-numeric-output new file mode 120000 index 0000000000..ca4bc2e2c0 --- /dev/null +++ b/Lang/Pluto/Formatted-numeric-output @@ -0,0 +1 @@ +../../Task/Formatted-numeric-output/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Fortunate-numbers b/Lang/Pluto/Fortunate-numbers new file mode 120000 index 0000000000..78cf9f5f36 --- /dev/null +++ b/Lang/Pluto/Fortunate-numbers @@ -0,0 +1 @@ +../../Task/Fortunate-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Forward-difference b/Lang/Pluto/Forward-difference new file mode 120000 index 0000000000..f75e0263fe --- /dev/null +++ b/Lang/Pluto/Forward-difference @@ -0,0 +1 @@ +../../Task/Forward-difference/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Four-is-magic b/Lang/Pluto/Four-is-magic new file mode 120000 index 0000000000..8f0564da6b --- /dev/null +++ b/Lang/Pluto/Four-is-magic @@ -0,0 +1 @@ +../../Task/Four-is-magic/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Function-composition b/Lang/Pluto/Function-composition new file mode 120000 index 0000000000..89443d02fb --- /dev/null +++ b/Lang/Pluto/Function-composition @@ -0,0 +1 @@ +../../Task/Function-composition/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Function-definition b/Lang/Pluto/Function-definition new file mode 120000 index 0000000000..8c3e064f65 --- /dev/null +++ b/Lang/Pluto/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Fusc-sequence b/Lang/Pluto/Fusc-sequence new file mode 120000 index 0000000000..af89d11bec --- /dev/null +++ b/Lang/Pluto/Fusc-sequence @@ -0,0 +1 @@ +../../Task/Fusc-sequence/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Gamma-function b/Lang/Pluto/Gamma-function new file mode 120000 index 0000000000..8b7dee23dc --- /dev/null +++ b/Lang/Pluto/Gamma-function @@ -0,0 +1 @@ +../../Task/Gamma-function/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Gapful-numbers b/Lang/Pluto/Gapful-numbers new file mode 120000 index 0000000000..0b3bce275e --- /dev/null +++ b/Lang/Pluto/Gapful-numbers @@ -0,0 +1 @@ +../../Task/Gapful-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Gauss-Jordan-matrix-inversion b/Lang/Pluto/Gauss-Jordan-matrix-inversion new file mode 120000 index 0000000000..75ed24ffd1 --- /dev/null +++ b/Lang/Pluto/Gauss-Jordan-matrix-inversion @@ -0,0 +1 @@ +../../Task/Gauss-Jordan-matrix-inversion/Pluto \ No newline at end of file diff --git a/Lang/Pluto/General-FizzBuzz b/Lang/Pluto/General-FizzBuzz new file mode 120000 index 0000000000..a7cf491b38 --- /dev/null +++ b/Lang/Pluto/General-FizzBuzz @@ -0,0 +1 @@ +../../Task/General-FizzBuzz/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Generate-lower-case-ASCII-alphabet b/Lang/Pluto/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..64f2576fe0 --- /dev/null +++ b/Lang/Pluto/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Generator-Exponential b/Lang/Pluto/Generator-Exponential new file mode 120000 index 0000000000..26eb55a2a0 --- /dev/null +++ b/Lang/Pluto/Generator-Exponential @@ -0,0 +1 @@ +../../Task/Generator-Exponential/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Giuga-numbers b/Lang/Pluto/Giuga-numbers new file mode 120000 index 0000000000..221b7a2689 --- /dev/null +++ b/Lang/Pluto/Giuga-numbers @@ -0,0 +1 @@ +../../Task/Giuga-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Goldbachs-comet b/Lang/Pluto/Goldbachs-comet new file mode 120000 index 0000000000..ff1cca329d --- /dev/null +++ b/Lang/Pluto/Goldbachs-comet @@ -0,0 +1 @@ +../../Task/Goldbachs-comet/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Golden-ratio-Convergence b/Lang/Pluto/Golden-ratio-Convergence new file mode 120000 index 0000000000..15a2256122 --- /dev/null +++ b/Lang/Pluto/Golden-ratio-Convergence @@ -0,0 +1 @@ +../../Task/Golden-ratio-Convergence/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Gray-code b/Lang/Pluto/Gray-code new file mode 120000 index 0000000000..afd6df8f4b --- /dev/null +++ b/Lang/Pluto/Gray-code @@ -0,0 +1 @@ +../../Task/Gray-code/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Greatest-common-divisor b/Lang/Pluto/Greatest-common-divisor new file mode 120000 index 0000000000..a4feeee2fd --- /dev/null +++ b/Lang/Pluto/Greatest-common-divisor @@ -0,0 +1 @@ +../../Task/Greatest-common-divisor/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Greatest-element-of-a-list b/Lang/Pluto/Greatest-element-of-a-list new file mode 120000 index 0000000000..85148f8e2b --- /dev/null +++ b/Lang/Pluto/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Greatest-subsequential-sum b/Lang/Pluto/Greatest-subsequential-sum new file mode 120000 index 0000000000..308ac33a20 --- /dev/null +++ b/Lang/Pluto/Greatest-subsequential-sum @@ -0,0 +1 @@ +../../Task/Greatest-subsequential-sum/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Greedy-algorithm-for-Egyptian-fractions b/Lang/Pluto/Greedy-algorithm-for-Egyptian-fractions new file mode 120000 index 0000000000..97dc6bbde7 --- /dev/null +++ b/Lang/Pluto/Greedy-algorithm-for-Egyptian-fractions @@ -0,0 +1 @@ +../../Task/Greedy-algorithm-for-Egyptian-fractions/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Guess-the-number b/Lang/Pluto/Guess-the-number new file mode 120000 index 0000000000..f68fa3fc41 --- /dev/null +++ b/Lang/Pluto/Guess-the-number @@ -0,0 +1 @@ +../../Task/Guess-the-number/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Hailstone-sequence b/Lang/Pluto/Hailstone-sequence new file mode 120000 index 0000000000..0c70c36e8a --- /dev/null +++ b/Lang/Pluto/Hailstone-sequence @@ -0,0 +1 @@ +../../Task/Hailstone-sequence/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Halt-and-catch-fire b/Lang/Pluto/Halt-and-catch-fire new file mode 120000 index 0000000000..f8e69baccf --- /dev/null +++ b/Lang/Pluto/Halt-and-catch-fire @@ -0,0 +1 @@ +../../Task/Halt-and-catch-fire/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Happy-numbers b/Lang/Pluto/Happy-numbers new file mode 120000 index 0000000000..8184fae2dd --- /dev/null +++ b/Lang/Pluto/Happy-numbers @@ -0,0 +1 @@ +../../Task/Happy-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Harmonic-series b/Lang/Pluto/Harmonic-series new file mode 120000 index 0000000000..9e5681ab0c --- /dev/null +++ b/Lang/Pluto/Harmonic-series @@ -0,0 +1 @@ +../../Task/Harmonic-series/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Harshad-or-Niven-series b/Lang/Pluto/Harshad-or-Niven-series new file mode 120000 index 0000000000..8a3855605b --- /dev/null +++ b/Lang/Pluto/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Hash-from-two-arrays b/Lang/Pluto/Hash-from-two-arrays new file mode 120000 index 0000000000..5612dbf1a3 --- /dev/null +++ b/Lang/Pluto/Hash-from-two-arrays @@ -0,0 +1 @@ +../../Task/Hash-from-two-arrays/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Hash-join b/Lang/Pluto/Hash-join new file mode 120000 index 0000000000..857fcc5b68 --- /dev/null +++ b/Lang/Pluto/Hash-join @@ -0,0 +1 @@ +../../Task/Hash-join/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Haversine-formula b/Lang/Pluto/Haversine-formula new file mode 120000 index 0000000000..b9fcee8ac0 --- /dev/null +++ b/Lang/Pluto/Haversine-formula @@ -0,0 +1 @@ +../../Task/Haversine-formula/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Hello-world-Graphical b/Lang/Pluto/Hello-world-Graphical new file mode 120000 index 0000000000..b0cbed710e --- /dev/null +++ b/Lang/Pluto/Hello-world-Graphical @@ -0,0 +1 @@ +../../Task/Hello-world-Graphical/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Hello-world-Newbie b/Lang/Pluto/Hello-world-Newbie new file mode 120000 index 0000000000..d7c1d093e2 --- /dev/null +++ b/Lang/Pluto/Hello-world-Newbie @@ -0,0 +1 @@ +../../Task/Hello-world-Newbie/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Hello-world-Newline-omission b/Lang/Pluto/Hello-world-Newline-omission new file mode 120000 index 0000000000..5020503885 --- /dev/null +++ b/Lang/Pluto/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Hello-world-Standard-error b/Lang/Pluto/Hello-world-Standard-error new file mode 120000 index 0000000000..2b41d962cc --- /dev/null +++ b/Lang/Pluto/Hello-world-Standard-error @@ -0,0 +1 @@ +../../Task/Hello-world-Standard-error/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Hello-world-Text b/Lang/Pluto/Hello-world-Text new file mode 120000 index 0000000000..6d5bb1406f --- /dev/null +++ b/Lang/Pluto/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Hex-words b/Lang/Pluto/Hex-words new file mode 120000 index 0000000000..62ff8632b8 --- /dev/null +++ b/Lang/Pluto/Hex-words @@ -0,0 +1 @@ +../../Task/Hex-words/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Hickerson-series-of-almost-integers b/Lang/Pluto/Hickerson-series-of-almost-integers new file mode 120000 index 0000000000..1706eca746 --- /dev/null +++ b/Lang/Pluto/Hickerson-series-of-almost-integers @@ -0,0 +1 @@ +../../Task/Hickerson-series-of-almost-integers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Higher-order-functions b/Lang/Pluto/Higher-order-functions new file mode 120000 index 0000000000..532e183ee0 --- /dev/null +++ b/Lang/Pluto/Higher-order-functions @@ -0,0 +1 @@ +../../Task/Higher-order-functions/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Hofstadter-Q-sequence b/Lang/Pluto/Hofstadter-Q-sequence new file mode 120000 index 0000000000..55c19c4e5e --- /dev/null +++ b/Lang/Pluto/Hofstadter-Q-sequence @@ -0,0 +1 @@ +../../Task/Hofstadter-Q-sequence/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Home-primes b/Lang/Pluto/Home-primes new file mode 120000 index 0000000000..66e3e487a6 --- /dev/null +++ b/Lang/Pluto/Home-primes @@ -0,0 +1 @@ +../../Task/Home-primes/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Horners-rule-for-polynomial-evaluation b/Lang/Pluto/Horners-rule-for-polynomial-evaluation new file mode 120000 index 0000000000..02512d6f7e --- /dev/null +++ b/Lang/Pluto/Horners-rule-for-polynomial-evaluation @@ -0,0 +1 @@ +../../Task/Horners-rule-for-polynomial-evaluation/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Hostname b/Lang/Pluto/Hostname new file mode 120000 index 0000000000..c1fe0db0ef --- /dev/null +++ b/Lang/Pluto/Hostname @@ -0,0 +1 @@ +../../Task/Hostname/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Humble-numbers b/Lang/Pluto/Humble-numbers new file mode 120000 index 0000000000..f616a12fe9 --- /dev/null +++ b/Lang/Pluto/Humble-numbers @@ -0,0 +1 @@ +../../Task/Humble-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/IBAN b/Lang/Pluto/IBAN new file mode 120000 index 0000000000..3c48349f04 --- /dev/null +++ b/Lang/Pluto/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/Pluto \ No newline at end of file diff --git a/Lang/Pluto/ISBN13-check-digit b/Lang/Pluto/ISBN13-check-digit new file mode 120000 index 0000000000..18cc8cf2ba --- /dev/null +++ b/Lang/Pluto/ISBN13-check-digit @@ -0,0 +1 @@ +../../Task/ISBN13-check-digit/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Identity-matrix b/Lang/Pluto/Identity-matrix new file mode 120000 index 0000000000..755ad3b6ef --- /dev/null +++ b/Lang/Pluto/Identity-matrix @@ -0,0 +1 @@ +../../Task/Identity-matrix/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Idiomatically-determine-all-the-lowercase-and-uppercase-letters b/Lang/Pluto/Idiomatically-determine-all-the-lowercase-and-uppercase-letters new file mode 120000 index 0000000000..1ce83f951b --- /dev/null +++ b/Lang/Pluto/Idiomatically-determine-all-the-lowercase-and-uppercase-letters @@ -0,0 +1 @@ +../../Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Increment-a-numerical-string b/Lang/Pluto/Increment-a-numerical-string new file mode 120000 index 0000000000..5413743d7c --- /dev/null +++ b/Lang/Pluto/Increment-a-numerical-string @@ -0,0 +1 @@ +../../Task/Increment-a-numerical-string/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Index-finite-lists-of-positive-integers b/Lang/Pluto/Index-finite-lists-of-positive-integers new file mode 120000 index 0000000000..44f395ae80 --- /dev/null +++ b/Lang/Pluto/Index-finite-lists-of-positive-integers @@ -0,0 +1 @@ +../../Task/Index-finite-lists-of-positive-integers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Infinity b/Lang/Pluto/Infinity new file mode 120000 index 0000000000..cb81bde8e2 --- /dev/null +++ b/Lang/Pluto/Infinity @@ -0,0 +1 @@ +../../Task/Infinity/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Inheritance-Multiple b/Lang/Pluto/Inheritance-Multiple new file mode 120000 index 0000000000..8172d1b878 --- /dev/null +++ b/Lang/Pluto/Inheritance-Multiple @@ -0,0 +1 @@ +../../Task/Inheritance-Multiple/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Inheritance-Single b/Lang/Pluto/Inheritance-Single new file mode 120000 index 0000000000..978ce6e7cf --- /dev/null +++ b/Lang/Pluto/Inheritance-Single @@ -0,0 +1 @@ +../../Task/Inheritance-Single/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Integer-overflow b/Lang/Pluto/Integer-overflow new file mode 120000 index 0000000000..21ae81881b --- /dev/null +++ b/Lang/Pluto/Integer-overflow @@ -0,0 +1 @@ +../../Task/Integer-overflow/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Inverted-syntax b/Lang/Pluto/Inverted-syntax new file mode 120000 index 0000000000..689ac95819 --- /dev/null +++ b/Lang/Pluto/Inverted-syntax @@ -0,0 +1 @@ +../../Task/Inverted-syntax/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Isqrt-integer-square-root-of-X b/Lang/Pluto/Isqrt-integer-square-root-of-X new file mode 120000 index 0000000000..e61bc6f394 --- /dev/null +++ b/Lang/Pluto/Isqrt-integer-square-root-of-X @@ -0,0 +1 @@ +../../Task/Isqrt-integer-square-root-of-X/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Iterated-digits-squaring b/Lang/Pluto/Iterated-digits-squaring new file mode 120000 index 0000000000..1e0c30dec8 --- /dev/null +++ b/Lang/Pluto/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/Pluto \ No newline at end of file diff --git a/Lang/Pluto/JSON b/Lang/Pluto/JSON new file mode 120000 index 0000000000..bc77142a3f --- /dev/null +++ b/Lang/Pluto/JSON @@ -0,0 +1 @@ +../../Task/JSON/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Jacobi-symbol b/Lang/Pluto/Jacobi-symbol new file mode 120000 index 0000000000..004a1623cc --- /dev/null +++ b/Lang/Pluto/Jacobi-symbol @@ -0,0 +1 @@ +../../Task/Jacobi-symbol/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Jacobsthal-numbers b/Lang/Pluto/Jacobsthal-numbers new file mode 120000 index 0000000000..310c137dfd --- /dev/null +++ b/Lang/Pluto/Jacobsthal-numbers @@ -0,0 +1 @@ +../../Task/Jacobsthal-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Jaro-Winkler-distance b/Lang/Pluto/Jaro-Winkler-distance new file mode 120000 index 0000000000..c18faa1587 --- /dev/null +++ b/Lang/Pluto/Jaro-Winkler-distance @@ -0,0 +1 @@ +../../Task/Jaro-Winkler-distance/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Jaro-similarity b/Lang/Pluto/Jaro-similarity new file mode 120000 index 0000000000..7fbb18452a --- /dev/null +++ b/Lang/Pluto/Jaro-similarity @@ -0,0 +1 @@ +../../Task/Jaro-similarity/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Jensens-Device b/Lang/Pluto/Jensens-Device new file mode 120000 index 0000000000..1f301e92cb --- /dev/null +++ b/Lang/Pluto/Jensens-Device @@ -0,0 +1 @@ +../../Task/Jensens-Device/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Jewels-and-stones b/Lang/Pluto/Jewels-and-stones new file mode 120000 index 0000000000..0d8632e132 --- /dev/null +++ b/Lang/Pluto/Jewels-and-stones @@ -0,0 +1 @@ +../../Task/Jewels-and-stones/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Jordan-P-lya-numbers b/Lang/Pluto/Jordan-P-lya-numbers new file mode 120000 index 0000000000..69c05770d3 --- /dev/null +++ b/Lang/Pluto/Jordan-P-lya-numbers @@ -0,0 +1 @@ +../../Task/Jordan-P-lya-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/JortSort b/Lang/Pluto/JortSort new file mode 120000 index 0000000000..2f3a60be62 --- /dev/null +++ b/Lang/Pluto/JortSort @@ -0,0 +1 @@ +../../Task/JortSort/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Josephus-problem b/Lang/Pluto/Josephus-problem new file mode 120000 index 0000000000..c17c5c052c --- /dev/null +++ b/Lang/Pluto/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Juggler-sequence b/Lang/Pluto/Juggler-sequence new file mode 120000 index 0000000000..55e904505f --- /dev/null +++ b/Lang/Pluto/Juggler-sequence @@ -0,0 +1 @@ +../../Task/Juggler-sequence/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Julia-set b/Lang/Pluto/Julia-set new file mode 120000 index 0000000000..47c2b492f2 --- /dev/null +++ b/Lang/Pluto/Julia-set @@ -0,0 +1 @@ +../../Task/Julia-set/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Jump-anywhere b/Lang/Pluto/Jump-anywhere new file mode 120000 index 0000000000..0cc6c03c6c --- /dev/null +++ b/Lang/Pluto/Jump-anywhere @@ -0,0 +1 @@ +../../Task/Jump-anywhere/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Kaprekar-numbers b/Lang/Pluto/Kaprekar-numbers new file mode 120000 index 0000000000..1c32b1316d --- /dev/null +++ b/Lang/Pluto/Kaprekar-numbers @@ -0,0 +1 @@ +../../Task/Kaprekar-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Knapsack-problem-0-1 b/Lang/Pluto/Knapsack-problem-0-1 new file mode 120000 index 0000000000..154c3bec73 --- /dev/null +++ b/Lang/Pluto/Knapsack-problem-0-1 @@ -0,0 +1 @@ +../../Task/Knapsack-problem-0-1/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Knapsack-problem-Bounded b/Lang/Pluto/Knapsack-problem-Bounded new file mode 120000 index 0000000000..fdfd53d307 --- /dev/null +++ b/Lang/Pluto/Knapsack-problem-Bounded @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Bounded/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Knapsack-problem-Continuous b/Lang/Pluto/Knapsack-problem-Continuous new file mode 120000 index 0000000000..afd8aad5a0 --- /dev/null +++ b/Lang/Pluto/Knapsack-problem-Continuous @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Continuous/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Knapsack-problem-Unbounded b/Lang/Pluto/Knapsack-problem-Unbounded new file mode 120000 index 0000000000..a47d914c76 --- /dev/null +++ b/Lang/Pluto/Knapsack-problem-Unbounded @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Unbounded/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Knuth-shuffle b/Lang/Pluto/Knuth-shuffle new file mode 120000 index 0000000000..e7dddcd355 --- /dev/null +++ b/Lang/Pluto/Knuth-shuffle @@ -0,0 +1 @@ +../../Task/Knuth-shuffle/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Knuths-algorithm-S b/Lang/Pluto/Knuths-algorithm-S new file mode 120000 index 0000000000..541d484707 --- /dev/null +++ b/Lang/Pluto/Knuths-algorithm-S @@ -0,0 +1 @@ +../../Task/Knuths-algorithm-S/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Kronecker-product b/Lang/Pluto/Kronecker-product new file mode 120000 index 0000000000..3e6a6e5b94 --- /dev/null +++ b/Lang/Pluto/Kronecker-product @@ -0,0 +1 @@ +../../Task/Kronecker-product/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Kronecker-product-based-fractals b/Lang/Pluto/Kronecker-product-based-fractals new file mode 120000 index 0000000000..3cfc235117 --- /dev/null +++ b/Lang/Pluto/Kronecker-product-based-fractals @@ -0,0 +1 @@ +../../Task/Kronecker-product-based-fractals/Pluto \ No newline at end of file diff --git a/Lang/Pluto/LU-decomposition b/Lang/Pluto/LU-decomposition new file mode 120000 index 0000000000..6a8af92062 --- /dev/null +++ b/Lang/Pluto/LU-decomposition @@ -0,0 +1 @@ +../../Task/LU-decomposition/Pluto \ No newline at end of file diff --git a/Lang/Pluto/LZW-compression b/Lang/Pluto/LZW-compression new file mode 120000 index 0000000000..50427fda5c --- /dev/null +++ b/Lang/Pluto/LZW-compression @@ -0,0 +1 @@ +../../Task/LZW-compression/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Lah-numbers b/Lang/Pluto/Lah-numbers new file mode 120000 index 0000000000..f5d9d24027 --- /dev/null +++ b/Lang/Pluto/Lah-numbers @@ -0,0 +1 @@ +../../Task/Lah-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Langtons-ant b/Lang/Pluto/Langtons-ant new file mode 120000 index 0000000000..fbf8c4cec8 --- /dev/null +++ b/Lang/Pluto/Langtons-ant @@ -0,0 +1 @@ +../../Task/Langtons-ant/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Largest-number-divisible-by-its-digits b/Lang/Pluto/Largest-number-divisible-by-its-digits new file mode 120000 index 0000000000..0399c7d845 --- /dev/null +++ b/Lang/Pluto/Largest-number-divisible-by-its-digits @@ -0,0 +1 @@ +../../Task/Largest-number-divisible-by-its-digits/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Largest-proper-divisor-of-n b/Lang/Pluto/Largest-proper-divisor-of-n new file mode 120000 index 0000000000..d21ea35abe --- /dev/null +++ b/Lang/Pluto/Largest-proper-divisor-of-n @@ -0,0 +1 @@ +../../Task/Largest-proper-divisor-of-n/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Last-Friday-of-each-month b/Lang/Pluto/Last-Friday-of-each-month new file mode 120000 index 0000000000..34cb3bb01f --- /dev/null +++ b/Lang/Pluto/Last-Friday-of-each-month @@ -0,0 +1 @@ +../../Task/Last-Friday-of-each-month/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Leap-year b/Lang/Pluto/Leap-year new file mode 120000 index 0000000000..9574544885 --- /dev/null +++ b/Lang/Pluto/Leap-year @@ -0,0 +1 @@ +../../Task/Leap-year/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Least-common-multiple b/Lang/Pluto/Least-common-multiple new file mode 120000 index 0000000000..315d9ee3c1 --- /dev/null +++ b/Lang/Pluto/Least-common-multiple @@ -0,0 +1 @@ +../../Task/Least-common-multiple/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Legendre-prime-counting-function b/Lang/Pluto/Legendre-prime-counting-function new file mode 120000 index 0000000000..f91e3cb00d --- /dev/null +++ b/Lang/Pluto/Legendre-prime-counting-function @@ -0,0 +1 @@ +../../Task/Legendre-prime-counting-function/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Leonardo-numbers b/Lang/Pluto/Leonardo-numbers new file mode 120000 index 0000000000..6a0846d95e --- /dev/null +++ b/Lang/Pluto/Leonardo-numbers @@ -0,0 +1 @@ +../../Task/Leonardo-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/List-comprehensions b/Lang/Pluto/List-comprehensions new file mode 120000 index 0000000000..e183959a9e --- /dev/null +++ b/Lang/Pluto/List-comprehensions @@ -0,0 +1 @@ +../../Task/List-comprehensions/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Literals-Floating-point b/Lang/Pluto/Literals-Floating-point new file mode 120000 index 0000000000..f40aa2eb22 --- /dev/null +++ b/Lang/Pluto/Literals-Floating-point @@ -0,0 +1 @@ +../../Task/Literals-Floating-point/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Literals-Integer b/Lang/Pluto/Literals-Integer new file mode 120000 index 0000000000..2ca0134201 --- /dev/null +++ b/Lang/Pluto/Literals-Integer @@ -0,0 +1 @@ +../../Task/Literals-Integer/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Logistic-curve-fitting-in-epidemiology b/Lang/Pluto/Logistic-curve-fitting-in-epidemiology new file mode 120000 index 0000000000..5620c74aa1 --- /dev/null +++ b/Lang/Pluto/Logistic-curve-fitting-in-epidemiology @@ -0,0 +1 @@ +../../Task/Logistic-curve-fitting-in-epidemiology/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Long-year b/Lang/Pluto/Long-year new file mode 120000 index 0000000000..e81c486cc5 --- /dev/null +++ b/Lang/Pluto/Long-year @@ -0,0 +1 @@ +../../Task/Long-year/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Longest-increasing-subsequence b/Lang/Pluto/Longest-increasing-subsequence new file mode 120000 index 0000000000..24fdc53a13 --- /dev/null +++ b/Lang/Pluto/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Longest-string-challenge b/Lang/Pluto/Longest-string-challenge new file mode 120000 index 0000000000..8e8deb88da --- /dev/null +++ b/Lang/Pluto/Longest-string-challenge @@ -0,0 +1 @@ +../../Task/Longest-string-challenge/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Loop-over-multiple-arrays-simultaneously b/Lang/Pluto/Loop-over-multiple-arrays-simultaneously new file mode 120000 index 0000000000..cebc902b5b --- /dev/null +++ b/Lang/Pluto/Loop-over-multiple-arrays-simultaneously @@ -0,0 +1 @@ +../../Task/Loop-over-multiple-arrays-simultaneously/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Loops-Break b/Lang/Pluto/Loops-Break new file mode 120000 index 0000000000..2b3657d2de --- /dev/null +++ b/Lang/Pluto/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Loops-Continue b/Lang/Pluto/Loops-Continue new file mode 120000 index 0000000000..5f41db6125 --- /dev/null +++ b/Lang/Pluto/Loops-Continue @@ -0,0 +1 @@ +../../Task/Loops-Continue/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Loops-Do-while b/Lang/Pluto/Loops-Do-while new file mode 120000 index 0000000000..a265d4decf --- /dev/null +++ b/Lang/Pluto/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Loops-Downward-for b/Lang/Pluto/Loops-Downward-for new file mode 120000 index 0000000000..6302a5cc0d --- /dev/null +++ b/Lang/Pluto/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Loops-For b/Lang/Pluto/Loops-For new file mode 120000 index 0000000000..9f83ae12bd --- /dev/null +++ b/Lang/Pluto/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Loops-For-with-a-specified-step b/Lang/Pluto/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..508122a2e3 --- /dev/null +++ b/Lang/Pluto/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Loops-Foreach b/Lang/Pluto/Loops-Foreach new file mode 120000 index 0000000000..9dbfba413e --- /dev/null +++ b/Lang/Pluto/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Loops-Increment-loop-index-within-loop-body b/Lang/Pluto/Loops-Increment-loop-index-within-loop-body new file mode 120000 index 0000000000..f1ce9d6778 --- /dev/null +++ b/Lang/Pluto/Loops-Increment-loop-index-within-loop-body @@ -0,0 +1 @@ +../../Task/Loops-Increment-loop-index-within-loop-body/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Loops-Infinite b/Lang/Pluto/Loops-Infinite new file mode 120000 index 0000000000..50986dd414 --- /dev/null +++ b/Lang/Pluto/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Loops-N-plus-one-half b/Lang/Pluto/Loops-N-plus-one-half new file mode 120000 index 0000000000..433e3f6336 --- /dev/null +++ b/Lang/Pluto/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Loops-Nested b/Lang/Pluto/Loops-Nested new file mode 120000 index 0000000000..96f4c43c62 --- /dev/null +++ b/Lang/Pluto/Loops-Nested @@ -0,0 +1 @@ +../../Task/Loops-Nested/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Loops-While b/Lang/Pluto/Loops-While new file mode 120000 index 0000000000..3aa5f84aba --- /dev/null +++ b/Lang/Pluto/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Loops-With-multiple-ranges b/Lang/Pluto/Loops-With-multiple-ranges new file mode 120000 index 0000000000..b1ef3af096 --- /dev/null +++ b/Lang/Pluto/Loops-With-multiple-ranges @@ -0,0 +1 @@ +../../Task/Loops-With-multiple-ranges/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Loops-Wrong-ranges b/Lang/Pluto/Loops-Wrong-ranges new file mode 120000 index 0000000000..7b8bd4ecb0 --- /dev/null +++ b/Lang/Pluto/Loops-Wrong-ranges @@ -0,0 +1 @@ +../../Task/Loops-Wrong-ranges/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Lucas-Lehmer-test b/Lang/Pluto/Lucas-Lehmer-test new file mode 120000 index 0000000000..247c0bbafb --- /dev/null +++ b/Lang/Pluto/Lucas-Lehmer-test @@ -0,0 +1 @@ +../../Task/Lucas-Lehmer-test/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Luhn-test-of-credit-card-numbers b/Lang/Pluto/Luhn-test-of-credit-card-numbers new file mode 120000 index 0000000000..c06ed72be3 --- /dev/null +++ b/Lang/Pluto/Luhn-test-of-credit-card-numbers @@ -0,0 +1 @@ +../../Task/Luhn-test-of-credit-card-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/M-bius-function b/Lang/Pluto/M-bius-function new file mode 120000 index 0000000000..99da13a437 --- /dev/null +++ b/Lang/Pluto/M-bius-function @@ -0,0 +1 @@ +../../Task/M-bius-function/Pluto \ No newline at end of file diff --git a/Lang/Pluto/MD4 b/Lang/Pluto/MD4 new file mode 120000 index 0000000000..b6660e39bc --- /dev/null +++ b/Lang/Pluto/MD4 @@ -0,0 +1 @@ +../../Task/MD4/Pluto \ No newline at end of file diff --git a/Lang/Pluto/MD5 b/Lang/Pluto/MD5 new file mode 120000 index 0000000000..c54a09dd7b --- /dev/null +++ b/Lang/Pluto/MD5 @@ -0,0 +1 @@ +../../Task/MD5/Pluto \ No newline at end of file diff --git a/Lang/Pluto/MD5-Implementation b/Lang/Pluto/MD5-Implementation new file mode 120000 index 0000000000..6cfead7533 --- /dev/null +++ b/Lang/Pluto/MD5-Implementation @@ -0,0 +1 @@ +../../Task/MD5-Implementation/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Machine-code b/Lang/Pluto/Machine-code new file mode 120000 index 0000000000..82c80d52fd --- /dev/null +++ b/Lang/Pluto/Machine-code @@ -0,0 +1 @@ +../../Task/Machine-code/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Magic-8-ball b/Lang/Pluto/Magic-8-ball new file mode 120000 index 0000000000..e4c5118cb4 --- /dev/null +++ b/Lang/Pluto/Magic-8-ball @@ -0,0 +1 @@ +../../Task/Magic-8-ball/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Magic-constant b/Lang/Pluto/Magic-constant new file mode 120000 index 0000000000..640896b2e7 --- /dev/null +++ b/Lang/Pluto/Magic-constant @@ -0,0 +1 @@ +../../Task/Magic-constant/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Magic-squares-of-doubly-even-order b/Lang/Pluto/Magic-squares-of-doubly-even-order new file mode 120000 index 0000000000..357d3e5480 --- /dev/null +++ b/Lang/Pluto/Magic-squares-of-doubly-even-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-doubly-even-order/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Magic-squares-of-odd-order b/Lang/Pluto/Magic-squares-of-odd-order new file mode 120000 index 0000000000..5df4846612 --- /dev/null +++ b/Lang/Pluto/Magic-squares-of-odd-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-odd-order/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Magic-squares-of-singly-even-order b/Lang/Pluto/Magic-squares-of-singly-even-order new file mode 120000 index 0000000000..2430b82023 --- /dev/null +++ b/Lang/Pluto/Magic-squares-of-singly-even-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-singly-even-order/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Man-or-boy-test b/Lang/Pluto/Man-or-boy-test new file mode 120000 index 0000000000..a1f41c4398 --- /dev/null +++ b/Lang/Pluto/Man-or-boy-test @@ -0,0 +1 @@ +../../Task/Man-or-boy-test/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Mandelbrot-set b/Lang/Pluto/Mandelbrot-set new file mode 120000 index 0000000000..3e79f825ad --- /dev/null +++ b/Lang/Pluto/Mandelbrot-set @@ -0,0 +1 @@ +../../Task/Mandelbrot-set/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Map-range b/Lang/Pluto/Map-range new file mode 120000 index 0000000000..a57c07d536 --- /dev/null +++ b/Lang/Pluto/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Matrix-exponentiation-operator b/Lang/Pluto/Matrix-exponentiation-operator new file mode 120000 index 0000000000..1f6eb5cbaa --- /dev/null +++ b/Lang/Pluto/Matrix-exponentiation-operator @@ -0,0 +1 @@ +../../Task/Matrix-exponentiation-operator/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Matrix-multiplication b/Lang/Pluto/Matrix-multiplication new file mode 120000 index 0000000000..61008dcc0b --- /dev/null +++ b/Lang/Pluto/Matrix-multiplication @@ -0,0 +1 @@ +../../Task/Matrix-multiplication/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Matrix-transposition b/Lang/Pluto/Matrix-transposition new file mode 120000 index 0000000000..aaa00341d6 --- /dev/null +++ b/Lang/Pluto/Matrix-transposition @@ -0,0 +1 @@ +../../Task/Matrix-transposition/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Maximum-triangle-path-sum b/Lang/Pluto/Maximum-triangle-path-sum new file mode 120000 index 0000000000..916e59e364 --- /dev/null +++ b/Lang/Pluto/Maximum-triangle-path-sum @@ -0,0 +1 @@ +../../Task/Maximum-triangle-path-sum/Pluto \ No newline at end of file diff --git a/Lang/Pluto/McNuggets-problem b/Lang/Pluto/McNuggets-problem new file mode 120000 index 0000000000..2540339e72 --- /dev/null +++ b/Lang/Pluto/McNuggets-problem @@ -0,0 +1 @@ +../../Task/McNuggets-problem/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Menu b/Lang/Pluto/Menu new file mode 120000 index 0000000000..058fd3fb23 --- /dev/null +++ b/Lang/Pluto/Menu @@ -0,0 +1 @@ +../../Task/Menu/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Mian-Chowla-sequence b/Lang/Pluto/Mian-Chowla-sequence new file mode 120000 index 0000000000..f966e85ca5 --- /dev/null +++ b/Lang/Pluto/Mian-Chowla-sequence @@ -0,0 +1 @@ +../../Task/Mian-Chowla-sequence/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Middle-three-digits b/Lang/Pluto/Middle-three-digits new file mode 120000 index 0000000000..8d3393e673 --- /dev/null +++ b/Lang/Pluto/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Mind-boggling-card-trick b/Lang/Pluto/Mind-boggling-card-trick new file mode 120000 index 0000000000..230afb38bb --- /dev/null +++ b/Lang/Pluto/Mind-boggling-card-trick @@ -0,0 +1 @@ +../../Task/Mind-boggling-card-trick/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Modified-random-distribution b/Lang/Pluto/Modified-random-distribution new file mode 120000 index 0000000000..a50baa585f --- /dev/null +++ b/Lang/Pluto/Modified-random-distribution @@ -0,0 +1 @@ +../../Task/Modified-random-distribution/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Modular-exponentiation b/Lang/Pluto/Modular-exponentiation new file mode 120000 index 0000000000..5694ee1899 --- /dev/null +++ b/Lang/Pluto/Modular-exponentiation @@ -0,0 +1 @@ +../../Task/Modular-exponentiation/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Modular-inverse b/Lang/Pluto/Modular-inverse new file mode 120000 index 0000000000..339ad0f426 --- /dev/null +++ b/Lang/Pluto/Modular-inverse @@ -0,0 +1 @@ +../../Task/Modular-inverse/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Monads-Maybe-monad b/Lang/Pluto/Monads-Maybe-monad new file mode 120000 index 0000000000..38ba5a7df2 --- /dev/null +++ b/Lang/Pluto/Monads-Maybe-monad @@ -0,0 +1 @@ +../../Task/Monads-Maybe-monad/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Monte-Carlo-methods b/Lang/Pluto/Monte-Carlo-methods new file mode 120000 index 0000000000..8639690631 --- /dev/null +++ b/Lang/Pluto/Monte-Carlo-methods @@ -0,0 +1 @@ +../../Task/Monte-Carlo-methods/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Monty-Hall-problem b/Lang/Pluto/Monty-Hall-problem new file mode 120000 index 0000000000..dac7cd8df3 --- /dev/null +++ b/Lang/Pluto/Monty-Hall-problem @@ -0,0 +1 @@ +../../Task/Monty-Hall-problem/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Morse-code b/Lang/Pluto/Morse-code new file mode 120000 index 0000000000..cf03e5492b --- /dev/null +++ b/Lang/Pluto/Morse-code @@ -0,0 +1 @@ +../../Task/Morse-code/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Motzkin-numbers b/Lang/Pluto/Motzkin-numbers new file mode 120000 index 0000000000..32bef98749 --- /dev/null +++ b/Lang/Pluto/Motzkin-numbers @@ -0,0 +1 @@ +../../Task/Motzkin-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Move-to-front-algorithm b/Lang/Pluto/Move-to-front-algorithm new file mode 120000 index 0000000000..2cc1837031 --- /dev/null +++ b/Lang/Pluto/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Multi-dimensional-array b/Lang/Pluto/Multi-dimensional-array new file mode 120000 index 0000000000..53ab69b153 --- /dev/null +++ b/Lang/Pluto/Multi-dimensional-array @@ -0,0 +1 @@ +../../Task/Multi-dimensional-array/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Multifactorial b/Lang/Pluto/Multifactorial new file mode 120000 index 0000000000..db75308a5f --- /dev/null +++ b/Lang/Pluto/Multifactorial @@ -0,0 +1 @@ +../../Task/Multifactorial/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Multiple-distinct-objects b/Lang/Pluto/Multiple-distinct-objects new file mode 120000 index 0000000000..3449d4226d --- /dev/null +++ b/Lang/Pluto/Multiple-distinct-objects @@ -0,0 +1 @@ +../../Task/Multiple-distinct-objects/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Multiple-regression b/Lang/Pluto/Multiple-regression new file mode 120000 index 0000000000..41b57d2c96 --- /dev/null +++ b/Lang/Pluto/Multiple-regression @@ -0,0 +1 @@ +../../Task/Multiple-regression/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Multiplication-tables b/Lang/Pluto/Multiplication-tables new file mode 120000 index 0000000000..98a4d7bd3c --- /dev/null +++ b/Lang/Pluto/Multiplication-tables @@ -0,0 +1 @@ +../../Task/Multiplication-tables/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Munchausen-numbers b/Lang/Pluto/Munchausen-numbers new file mode 120000 index 0000000000..9b090f8c02 --- /dev/null +++ b/Lang/Pluto/Munchausen-numbers @@ -0,0 +1 @@ +../../Task/Munchausen-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Munching-squares b/Lang/Pluto/Munching-squares new file mode 120000 index 0000000000..71dcd71a08 --- /dev/null +++ b/Lang/Pluto/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Musical-scale b/Lang/Pluto/Musical-scale new file mode 120000 index 0000000000..9692211175 --- /dev/null +++ b/Lang/Pluto/Musical-scale @@ -0,0 +1 @@ +../../Task/Musical-scale/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Mutual-recursion b/Lang/Pluto/Mutual-recursion new file mode 120000 index 0000000000..3866a9925a --- /dev/null +++ b/Lang/Pluto/Mutual-recursion @@ -0,0 +1 @@ +../../Task/Mutual-recursion/Pluto \ No newline at end of file diff --git a/Lang/Pluto/N-queens-problem b/Lang/Pluto/N-queens-problem new file mode 120000 index 0000000000..a29c7467b2 --- /dev/null +++ b/Lang/Pluto/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Named-parameters b/Lang/Pluto/Named-parameters new file mode 120000 index 0000000000..8f0b72ba9b --- /dev/null +++ b/Lang/Pluto/Named-parameters @@ -0,0 +1 @@ +../../Task/Named-parameters/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Narcissistic-decimal-number b/Lang/Pluto/Narcissistic-decimal-number new file mode 120000 index 0000000000..feead3c3a0 --- /dev/null +++ b/Lang/Pluto/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Nested-function b/Lang/Pluto/Nested-function new file mode 120000 index 0000000000..ea9816ec32 --- /dev/null +++ b/Lang/Pluto/Nested-function @@ -0,0 +1 @@ +../../Task/Nested-function/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Nested-templated-data b/Lang/Pluto/Nested-templated-data new file mode 120000 index 0000000000..d56f50a5d8 --- /dev/null +++ b/Lang/Pluto/Nested-templated-data @@ -0,0 +1 @@ +../../Task/Nested-templated-data/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Non-continuous-subsequences b/Lang/Pluto/Non-continuous-subsequences new file mode 120000 index 0000000000..f226b8c60b --- /dev/null +++ b/Lang/Pluto/Non-continuous-subsequences @@ -0,0 +1 @@ +../../Task/Non-continuous-subsequences/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Non-decimal-radices-Convert b/Lang/Pluto/Non-decimal-radices-Convert new file mode 120000 index 0000000000..e1fddc5a20 --- /dev/null +++ b/Lang/Pluto/Non-decimal-radices-Convert @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Convert/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Non-decimal-radices-Input b/Lang/Pluto/Non-decimal-radices-Input new file mode 120000 index 0000000000..e530fe6bb6 --- /dev/null +++ b/Lang/Pluto/Non-decimal-radices-Input @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Input/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Non-decimal-radices-Output b/Lang/Pluto/Non-decimal-radices-Output new file mode 120000 index 0000000000..8cfb1c729a --- /dev/null +++ b/Lang/Pluto/Non-decimal-radices-Output @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Output/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Nonoblock b/Lang/Pluto/Nonoblock new file mode 120000 index 0000000000..733d16326f --- /dev/null +++ b/Lang/Pluto/Nonoblock @@ -0,0 +1 @@ +../../Task/Nonoblock/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Nth b/Lang/Pluto/Nth new file mode 120000 index 0000000000..54dfb50037 --- /dev/null +++ b/Lang/Pluto/Nth @@ -0,0 +1 @@ +../../Task/Nth/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Number-names b/Lang/Pluto/Number-names new file mode 120000 index 0000000000..1ede3bfc36 --- /dev/null +++ b/Lang/Pluto/Number-names @@ -0,0 +1 @@ +../../Task/Number-names/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Numbers-with-equal-rises-and-falls b/Lang/Pluto/Numbers-with-equal-rises-and-falls new file mode 120000 index 0000000000..b08f5ff647 --- /dev/null +++ b/Lang/Pluto/Numbers-with-equal-rises-and-falls @@ -0,0 +1 @@ +../../Task/Numbers-with-equal-rises-and-falls/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Numeric-error-propagation b/Lang/Pluto/Numeric-error-propagation new file mode 120000 index 0000000000..2f5e41e871 --- /dev/null +++ b/Lang/Pluto/Numeric-error-propagation @@ -0,0 +1 @@ +../../Task/Numeric-error-propagation/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Numerical-integration b/Lang/Pluto/Numerical-integration new file mode 120000 index 0000000000..e89c1b753a --- /dev/null +++ b/Lang/Pluto/Numerical-integration @@ -0,0 +1 @@ +../../Task/Numerical-integration/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Old-Russian-measure-of-length b/Lang/Pluto/Old-Russian-measure-of-length new file mode 120000 index 0000000000..9f7493d0af --- /dev/null +++ b/Lang/Pluto/Old-Russian-measure-of-length @@ -0,0 +1 @@ +../../Task/Old-Russian-measure-of-length/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Old-lady-swallowed-a-fly b/Lang/Pluto/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..e29df6472a --- /dev/null +++ b/Lang/Pluto/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/Pluto \ No newline at end of file diff --git a/Lang/Pluto/One-dimensional-cellular-automata b/Lang/Pluto/One-dimensional-cellular-automata new file mode 120000 index 0000000000..b90efd8831 --- /dev/null +++ b/Lang/Pluto/One-dimensional-cellular-automata @@ -0,0 +1 @@ +../../Task/One-dimensional-cellular-automata/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Order-by-pair-comparisons b/Lang/Pluto/Order-by-pair-comparisons new file mode 120000 index 0000000000..1c7665f6b2 --- /dev/null +++ b/Lang/Pluto/Order-by-pair-comparisons @@ -0,0 +1 @@ +../../Task/Order-by-pair-comparisons/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Ordered-words b/Lang/Pluto/Ordered-words new file mode 120000 index 0000000000..018c8529a3 --- /dev/null +++ b/Lang/Pluto/Ordered-words @@ -0,0 +1 @@ +../../Task/Ordered-words/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Ormiston-triples b/Lang/Pluto/Ormiston-triples new file mode 120000 index 0000000000..e6fe78c60e --- /dev/null +++ b/Lang/Pluto/Ormiston-triples @@ -0,0 +1 @@ +../../Task/Ormiston-triples/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Palindrome-detection b/Lang/Pluto/Palindrome-detection new file mode 120000 index 0000000000..755083778a --- /dev/null +++ b/Lang/Pluto/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Pancake-numbers b/Lang/Pluto/Pancake-numbers new file mode 120000 index 0000000000..129dac7c77 --- /dev/null +++ b/Lang/Pluto/Pancake-numbers @@ -0,0 +1 @@ +../../Task/Pancake-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Paraffins b/Lang/Pluto/Paraffins new file mode 120000 index 0000000000..4b8b6e0ba9 --- /dev/null +++ b/Lang/Pluto/Paraffins @@ -0,0 +1 @@ +../../Task/Paraffins/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Parametric-polymorphism b/Lang/Pluto/Parametric-polymorphism new file mode 120000 index 0000000000..bdc68d3723 --- /dev/null +++ b/Lang/Pluto/Parametric-polymorphism @@ -0,0 +1 @@ +../../Task/Parametric-polymorphism/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Parsing-RPN-calculator-algorithm b/Lang/Pluto/Parsing-RPN-calculator-algorithm new file mode 120000 index 0000000000..f120a8c76e --- /dev/null +++ b/Lang/Pluto/Parsing-RPN-calculator-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-RPN-calculator-algorithm/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Parsing-Shunting-yard-algorithm b/Lang/Pluto/Parsing-Shunting-yard-algorithm new file mode 120000 index 0000000000..6a968b87bd --- /dev/null +++ b/Lang/Pluto/Parsing-Shunting-yard-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-Shunting-yard-algorithm/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Partial-function-application b/Lang/Pluto/Partial-function-application new file mode 120000 index 0000000000..bc39fe1347 --- /dev/null +++ b/Lang/Pluto/Partial-function-application @@ -0,0 +1 @@ +../../Task/Partial-function-application/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Partition-an-integer-x-into-n-primes b/Lang/Pluto/Partition-an-integer-x-into-n-primes new file mode 120000 index 0000000000..b3156a2b19 --- /dev/null +++ b/Lang/Pluto/Partition-an-integer-x-into-n-primes @@ -0,0 +1 @@ +../../Task/Partition-an-integer-x-into-n-primes/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Partition-function-P b/Lang/Pluto/Partition-function-P new file mode 120000 index 0000000000..74dceccc52 --- /dev/null +++ b/Lang/Pluto/Partition-function-P @@ -0,0 +1 @@ +../../Task/Partition-function-P/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Pascal-matrix-generation b/Lang/Pluto/Pascal-matrix-generation new file mode 120000 index 0000000000..08137286fd --- /dev/null +++ b/Lang/Pluto/Pascal-matrix-generation @@ -0,0 +1 @@ +../../Task/Pascal-matrix-generation/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Pascals-triangle b/Lang/Pluto/Pascals-triangle new file mode 120000 index 0000000000..b148762a81 --- /dev/null +++ b/Lang/Pluto/Pascals-triangle @@ -0,0 +1 @@ +../../Task/Pascals-triangle/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Pascals-triangle-Puzzle b/Lang/Pluto/Pascals-triangle-Puzzle new file mode 120000 index 0000000000..312b0f9b1b --- /dev/null +++ b/Lang/Pluto/Pascals-triangle-Puzzle @@ -0,0 +1 @@ +../../Task/Pascals-triangle-Puzzle/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Pells-equation b/Lang/Pluto/Pells-equation new file mode 120000 index 0000000000..330936d009 --- /dev/null +++ b/Lang/Pluto/Pells-equation @@ -0,0 +1 @@ +../../Task/Pells-equation/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Perfect-numbers b/Lang/Pluto/Perfect-numbers new file mode 120000 index 0000000000..c44c743521 --- /dev/null +++ b/Lang/Pluto/Perfect-numbers @@ -0,0 +1 @@ +../../Task/Perfect-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Perfect-shuffle b/Lang/Pluto/Perfect-shuffle new file mode 120000 index 0000000000..1dd4b8c882 --- /dev/null +++ b/Lang/Pluto/Perfect-shuffle @@ -0,0 +1 @@ +../../Task/Perfect-shuffle/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Perfect-totient-numbers b/Lang/Pluto/Perfect-totient-numbers new file mode 120000 index 0000000000..ff9d8e3ace --- /dev/null +++ b/Lang/Pluto/Perfect-totient-numbers @@ -0,0 +1 @@ +../../Task/Perfect-totient-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Periodic-table b/Lang/Pluto/Periodic-table new file mode 120000 index 0000000000..9aa6afb48f --- /dev/null +++ b/Lang/Pluto/Periodic-table @@ -0,0 +1 @@ +../../Task/Periodic-table/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Peripheral-drift-illusion b/Lang/Pluto/Peripheral-drift-illusion new file mode 120000 index 0000000000..28e04374ac --- /dev/null +++ b/Lang/Pluto/Peripheral-drift-illusion @@ -0,0 +1 @@ +../../Task/Peripheral-drift-illusion/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Perlin-noise b/Lang/Pluto/Perlin-noise new file mode 120000 index 0000000000..9a99043b16 --- /dev/null +++ b/Lang/Pluto/Perlin-noise @@ -0,0 +1 @@ +../../Task/Perlin-noise/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Permutations b/Lang/Pluto/Permutations new file mode 120000 index 0000000000..750604fad2 --- /dev/null +++ b/Lang/Pluto/Permutations @@ -0,0 +1 @@ +../../Task/Permutations/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Pernicious-numbers b/Lang/Pluto/Pernicious-numbers new file mode 120000 index 0000000000..29e4a1f27e --- /dev/null +++ b/Lang/Pluto/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Phrase-reversals b/Lang/Pluto/Phrase-reversals new file mode 120000 index 0000000000..8398529c2c --- /dev/null +++ b/Lang/Pluto/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Pick-random-element b/Lang/Pluto/Pick-random-element new file mode 120000 index 0000000000..f181e160e5 --- /dev/null +++ b/Lang/Pluto/Pick-random-element @@ -0,0 +1 @@ +../../Task/Pick-random-element/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Pisano-period b/Lang/Pluto/Pisano-period new file mode 120000 index 0000000000..377c8913e0 --- /dev/null +++ b/Lang/Pluto/Pisano-period @@ -0,0 +1 @@ +../../Task/Pisano-period/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Pointers-and-references b/Lang/Pluto/Pointers-and-references new file mode 120000 index 0000000000..e2ffa489f1 --- /dev/null +++ b/Lang/Pluto/Pointers-and-references @@ -0,0 +1 @@ +../../Task/Pointers-and-references/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Polynomial-long-division b/Lang/Pluto/Polynomial-long-division new file mode 120000 index 0000000000..feb0f9bb3e --- /dev/null +++ b/Lang/Pluto/Polynomial-long-division @@ -0,0 +1 @@ +../../Task/Polynomial-long-division/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Polynomial-regression b/Lang/Pluto/Polynomial-regression new file mode 120000 index 0000000000..11b7492061 --- /dev/null +++ b/Lang/Pluto/Polynomial-regression @@ -0,0 +1 @@ +../../Task/Polynomial-regression/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Population-count b/Lang/Pluto/Population-count new file mode 120000 index 0000000000..c275fa8665 --- /dev/null +++ b/Lang/Pluto/Population-count @@ -0,0 +1 @@ +../../Task/Population-count/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Power-set b/Lang/Pluto/Power-set new file mode 120000 index 0000000000..72362c1ec0 --- /dev/null +++ b/Lang/Pluto/Power-set @@ -0,0 +1 @@ +../../Task/Power-set/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Price-fraction b/Lang/Pluto/Price-fraction new file mode 120000 index 0000000000..1ac1f34fe5 --- /dev/null +++ b/Lang/Pluto/Price-fraction @@ -0,0 +1 @@ +../../Task/Price-fraction/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Primality-by-Wilsons-theorem b/Lang/Pluto/Primality-by-Wilsons-theorem new file mode 120000 index 0000000000..9b5599f64b --- /dev/null +++ b/Lang/Pluto/Primality-by-Wilsons-theorem @@ -0,0 +1 @@ +../../Task/Primality-by-Wilsons-theorem/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Primality-by-trial-division b/Lang/Pluto/Primality-by-trial-division new file mode 120000 index 0000000000..01622c5c43 --- /dev/null +++ b/Lang/Pluto/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Prime-conspiracy b/Lang/Pluto/Prime-conspiracy new file mode 120000 index 0000000000..fb52d53fda --- /dev/null +++ b/Lang/Pluto/Prime-conspiracy @@ -0,0 +1 @@ +../../Task/Prime-conspiracy/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Prime-decomposition b/Lang/Pluto/Prime-decomposition new file mode 120000 index 0000000000..3af54a0bb5 --- /dev/null +++ b/Lang/Pluto/Prime-decomposition @@ -0,0 +1 @@ +../../Task/Prime-decomposition/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Prime-triangle b/Lang/Pluto/Prime-triangle new file mode 120000 index 0000000000..9d4d789f0f --- /dev/null +++ b/Lang/Pluto/Prime-triangle @@ -0,0 +1 @@ +../../Task/Prime-triangle/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Primes---allocate-descendants-to-their-ancestors b/Lang/Pluto/Primes---allocate-descendants-to-their-ancestors new file mode 120000 index 0000000000..f8c226f8bd --- /dev/null +++ b/Lang/Pluto/Primes---allocate-descendants-to-their-ancestors @@ -0,0 +1 @@ +../../Task/Primes---allocate-descendants-to-their-ancestors/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Primorial-numbers b/Lang/Pluto/Primorial-numbers new file mode 120000 index 0000000000..c8bd364676 --- /dev/null +++ b/Lang/Pluto/Primorial-numbers @@ -0,0 +1 @@ +../../Task/Primorial-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Priority-queue b/Lang/Pluto/Priority-queue new file mode 120000 index 0000000000..ad7bed4159 --- /dev/null +++ b/Lang/Pluto/Priority-queue @@ -0,0 +1 @@ +../../Task/Priority-queue/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Program-name b/Lang/Pluto/Program-name new file mode 120000 index 0000000000..6b084789ed --- /dev/null +++ b/Lang/Pluto/Program-name @@ -0,0 +1 @@ +../../Task/Program-name/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Program-termination b/Lang/Pluto/Program-termination new file mode 120000 index 0000000000..50e8764745 --- /dev/null +++ b/Lang/Pluto/Program-termination @@ -0,0 +1 @@ +../../Task/Program-termination/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Proper-divisors b/Lang/Pluto/Proper-divisors new file mode 120000 index 0000000000..8bb1a6945e --- /dev/null +++ b/Lang/Pluto/Proper-divisors @@ -0,0 +1 @@ +../../Task/Proper-divisors/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Pseudo-random-numbers-Middle-square-method b/Lang/Pluto/Pseudo-random-numbers-Middle-square-method new file mode 120000 index 0000000000..13c5850baa --- /dev/null +++ b/Lang/Pluto/Pseudo-random-numbers-Middle-square-method @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-Middle-square-method/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Pseudo-random-numbers-PCG32 b/Lang/Pluto/Pseudo-random-numbers-PCG32 new file mode 120000 index 0000000000..a7591cbf7d --- /dev/null +++ b/Lang/Pluto/Pseudo-random-numbers-PCG32 @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-PCG32/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Pseudo-random-numbers-Splitmix64 b/Lang/Pluto/Pseudo-random-numbers-Splitmix64 new file mode 120000 index 0000000000..5899b47f2e --- /dev/null +++ b/Lang/Pluto/Pseudo-random-numbers-Splitmix64 @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-Splitmix64/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Pythagoras-tree b/Lang/Pluto/Pythagoras-tree new file mode 120000 index 0000000000..08b1af9c83 --- /dev/null +++ b/Lang/Pluto/Pythagoras-tree @@ -0,0 +1 @@ +../../Task/Pythagoras-tree/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Pythagorean-triples b/Lang/Pluto/Pythagorean-triples new file mode 120000 index 0000000000..8be426ea15 --- /dev/null +++ b/Lang/Pluto/Pythagorean-triples @@ -0,0 +1 @@ +../../Task/Pythagorean-triples/Pluto \ No newline at end of file diff --git a/Lang/Pluto/QR-decomposition b/Lang/Pluto/QR-decomposition new file mode 120000 index 0000000000..6d72ede0a4 --- /dev/null +++ b/Lang/Pluto/QR-decomposition @@ -0,0 +1 @@ +../../Task/QR-decomposition/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Queue-Definition b/Lang/Pluto/Queue-Definition new file mode 120000 index 0000000000..8cf42a0b6a --- /dev/null +++ b/Lang/Pluto/Queue-Definition @@ -0,0 +1 @@ +../../Task/Queue-Definition/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Queue-Usage b/Lang/Pluto/Queue-Usage new file mode 120000 index 0000000000..6d7d7a3b25 --- /dev/null +++ b/Lang/Pluto/Queue-Usage @@ -0,0 +1 @@ +../../Task/Queue-Usage/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Quoting-constructs b/Lang/Pluto/Quoting-constructs new file mode 120000 index 0000000000..21c1cfccbd --- /dev/null +++ b/Lang/Pluto/Quoting-constructs @@ -0,0 +1 @@ +../../Task/Quoting-constructs/Pluto \ No newline at end of file diff --git a/Lang/Pluto/RIPEMD-160 b/Lang/Pluto/RIPEMD-160 new file mode 120000 index 0000000000..18207c76aa --- /dev/null +++ b/Lang/Pluto/RIPEMD-160 @@ -0,0 +1 @@ +../../Task/RIPEMD-160/Pluto \ No newline at end of file diff --git a/Lang/Pluto/RPG-attributes-generator b/Lang/Pluto/RPG-attributes-generator new file mode 120000 index 0000000000..94703dd51c --- /dev/null +++ b/Lang/Pluto/RPG-attributes-generator @@ -0,0 +1 @@ +../../Task/RPG-attributes-generator/Pluto \ No newline at end of file diff --git a/Lang/Pluto/RSA-code b/Lang/Pluto/RSA-code new file mode 120000 index 0000000000..fa27ed3ec1 --- /dev/null +++ b/Lang/Pluto/RSA-code @@ -0,0 +1 @@ +../../Task/RSA-code/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Ramanujans-constant b/Lang/Pluto/Ramanujans-constant new file mode 120000 index 0000000000..c98dc7a621 --- /dev/null +++ b/Lang/Pluto/Ramanujans-constant @@ -0,0 +1 @@ +../../Task/Ramanujans-constant/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Ramer-Douglas-Peucker-line-simplification b/Lang/Pluto/Ramer-Douglas-Peucker-line-simplification new file mode 120000 index 0000000000..f3927eff81 --- /dev/null +++ b/Lang/Pluto/Ramer-Douglas-Peucker-line-simplification @@ -0,0 +1 @@ +../../Task/Ramer-Douglas-Peucker-line-simplification/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Random-number-generator-device- b/Lang/Pluto/Random-number-generator-device- new file mode 120000 index 0000000000..6f23d7dfa7 --- /dev/null +++ b/Lang/Pluto/Random-number-generator-device- @@ -0,0 +1 @@ +../../Task/Random-number-generator-device-/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Random-numbers b/Lang/Pluto/Random-numbers new file mode 120000 index 0000000000..7bda811b12 --- /dev/null +++ b/Lang/Pluto/Random-numbers @@ -0,0 +1 @@ +../../Task/Random-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Range-expansion b/Lang/Pluto/Range-expansion new file mode 120000 index 0000000000..c486f1e65b --- /dev/null +++ b/Lang/Pluto/Range-expansion @@ -0,0 +1 @@ +../../Task/Range-expansion/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Range-extraction b/Lang/Pluto/Range-extraction new file mode 120000 index 0000000000..c2738db56f --- /dev/null +++ b/Lang/Pluto/Range-extraction @@ -0,0 +1 @@ +../../Task/Range-extraction/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Rare-numbers b/Lang/Pluto/Rare-numbers new file mode 120000 index 0000000000..f80bc44b48 --- /dev/null +++ b/Lang/Pluto/Rare-numbers @@ -0,0 +1 @@ +../../Task/Rare-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Read-a-configuration-file b/Lang/Pluto/Read-a-configuration-file new file mode 120000 index 0000000000..90fb599972 --- /dev/null +++ b/Lang/Pluto/Read-a-configuration-file @@ -0,0 +1 @@ +../../Task/Read-a-configuration-file/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Read-a-file-line-by-line b/Lang/Pluto/Read-a-file-line-by-line new file mode 120000 index 0000000000..d35b8cfbc4 --- /dev/null +++ b/Lang/Pluto/Read-a-file-line-by-line @@ -0,0 +1 @@ +../../Task/Read-a-file-line-by-line/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Read-entire-file b/Lang/Pluto/Read-entire-file new file mode 120000 index 0000000000..f49bee994d --- /dev/null +++ b/Lang/Pluto/Read-entire-file @@ -0,0 +1 @@ +../../Task/Read-entire-file/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Real-constants-and-functions b/Lang/Pluto/Real-constants-and-functions new file mode 120000 index 0000000000..0f3f45eaa6 --- /dev/null +++ b/Lang/Pluto/Real-constants-and-functions @@ -0,0 +1 @@ +../../Task/Real-constants-and-functions/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Recamans-sequence b/Lang/Pluto/Recamans-sequence new file mode 120000 index 0000000000..b47a985a96 --- /dev/null +++ b/Lang/Pluto/Recamans-sequence @@ -0,0 +1 @@ +../../Task/Recamans-sequence/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Reduced-row-echelon-form b/Lang/Pluto/Reduced-row-echelon-form new file mode 120000 index 0000000000..8086c26ac8 --- /dev/null +++ b/Lang/Pluto/Reduced-row-echelon-form @@ -0,0 +1 @@ +../../Task/Reduced-row-echelon-form/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Rename-a-file b/Lang/Pluto/Rename-a-file new file mode 120000 index 0000000000..dd234bb854 --- /dev/null +++ b/Lang/Pluto/Rename-a-file @@ -0,0 +1 @@ +../../Task/Rename-a-file/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Repeat b/Lang/Pluto/Repeat new file mode 120000 index 0000000000..a6a3c03575 --- /dev/null +++ b/Lang/Pluto/Repeat @@ -0,0 +1 @@ +../../Task/Repeat/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Repeat-a-string b/Lang/Pluto/Repeat-a-string new file mode 120000 index 0000000000..7cea8b7235 --- /dev/null +++ b/Lang/Pluto/Repeat-a-string @@ -0,0 +1 @@ +../../Task/Repeat-a-string/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Repunit-primes b/Lang/Pluto/Repunit-primes new file mode 120000 index 0000000000..7e185e6e79 --- /dev/null +++ b/Lang/Pluto/Repunit-primes @@ -0,0 +1 @@ +../../Task/Repunit-primes/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Resistor-mesh b/Lang/Pluto/Resistor-mesh new file mode 120000 index 0000000000..e4f455a984 --- /dev/null +++ b/Lang/Pluto/Resistor-mesh @@ -0,0 +1 @@ +../../Task/Resistor-mesh/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Return-multiple-values b/Lang/Pluto/Return-multiple-values new file mode 120000 index 0000000000..18f6c32d09 --- /dev/null +++ b/Lang/Pluto/Return-multiple-values @@ -0,0 +1 @@ +../../Task/Return-multiple-values/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Reverse-a-string b/Lang/Pluto/Reverse-a-string new file mode 120000 index 0000000000..dc5b2e2493 --- /dev/null +++ b/Lang/Pluto/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Reverse-words-in-a-string b/Lang/Pluto/Reverse-words-in-a-string new file mode 120000 index 0000000000..378e6ea4b7 --- /dev/null +++ b/Lang/Pluto/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Roman-numerals-Encode b/Lang/Pluto/Roman-numerals-Encode new file mode 120000 index 0000000000..d12a85d68f --- /dev/null +++ b/Lang/Pluto/Roman-numerals-Encode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Encode/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Roots-of-a-function b/Lang/Pluto/Roots-of-a-function new file mode 120000 index 0000000000..a5bb6f8f20 --- /dev/null +++ b/Lang/Pluto/Roots-of-a-function @@ -0,0 +1 @@ +../../Task/Roots-of-a-function/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Roots-of-a-quadratic-function b/Lang/Pluto/Roots-of-a-quadratic-function new file mode 120000 index 0000000000..8e5bf4c688 --- /dev/null +++ b/Lang/Pluto/Roots-of-a-quadratic-function @@ -0,0 +1 @@ +../../Task/Roots-of-a-quadratic-function/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Roots-of-unity b/Lang/Pluto/Roots-of-unity new file mode 120000 index 0000000000..e0f1ada438 --- /dev/null +++ b/Lang/Pluto/Roots-of-unity @@ -0,0 +1 @@ +../../Task/Roots-of-unity/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Rot-13 b/Lang/Pluto/Rot-13 new file mode 120000 index 0000000000..ca2ef70221 --- /dev/null +++ b/Lang/Pluto/Rot-13 @@ -0,0 +1 @@ +../../Task/Rot-13/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Runge-Kutta-method b/Lang/Pluto/Runge-Kutta-method new file mode 120000 index 0000000000..1f412f01e7 --- /dev/null +++ b/Lang/Pluto/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/Pluto \ No newline at end of file diff --git a/Lang/Pluto/SEDOLs b/Lang/Pluto/SEDOLs new file mode 120000 index 0000000000..4a14938cfb --- /dev/null +++ b/Lang/Pluto/SEDOLs @@ -0,0 +1 @@ +../../Task/SEDOLs/Pluto \ No newline at end of file diff --git a/Lang/Pluto/SHA-1 b/Lang/Pluto/SHA-1 new file mode 120000 index 0000000000..b2417e97b6 --- /dev/null +++ b/Lang/Pluto/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/Pluto \ No newline at end of file diff --git a/Lang/Pluto/SHA-256 b/Lang/Pluto/SHA-256 new file mode 120000 index 0000000000..69f9d4a47c --- /dev/null +++ b/Lang/Pluto/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Safe-primes-and-unsafe-primes b/Lang/Pluto/Safe-primes-and-unsafe-primes new file mode 120000 index 0000000000..0dd190920e --- /dev/null +++ b/Lang/Pluto/Safe-primes-and-unsafe-primes @@ -0,0 +1 @@ +../../Task/Safe-primes-and-unsafe-primes/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sailors-coconuts-and-a-monkey-problem b/Lang/Pluto/Sailors-coconuts-and-a-monkey-problem new file mode 120000 index 0000000000..29da882738 --- /dev/null +++ b/Lang/Pluto/Sailors-coconuts-and-a-monkey-problem @@ -0,0 +1 @@ +../../Task/Sailors-coconuts-and-a-monkey-problem/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Search-a-list b/Lang/Pluto/Search-a-list new file mode 120000 index 0000000000..7284791eca --- /dev/null +++ b/Lang/Pluto/Search-a-list @@ -0,0 +1 @@ +../../Task/Search-a-list/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Search-a-list-of-records b/Lang/Pluto/Search-a-list-of-records new file mode 120000 index 0000000000..53af5de4bf --- /dev/null +++ b/Lang/Pluto/Search-a-list-of-records @@ -0,0 +1 @@ +../../Task/Search-a-list-of-records/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Selectively-replace-multiple-instances-of-a-character-within-a-string b/Lang/Pluto/Selectively-replace-multiple-instances-of-a-character-within-a-string new file mode 120000 index 0000000000..b494f69bf0 --- /dev/null +++ b/Lang/Pluto/Selectively-replace-multiple-instances-of-a-character-within-a-string @@ -0,0 +1 @@ +../../Task/Selectively-replace-multiple-instances-of-a-character-within-a-string/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Self-numbers b/Lang/Pluto/Self-numbers new file mode 120000 index 0000000000..6ddaee76e3 --- /dev/null +++ b/Lang/Pluto/Self-numbers @@ -0,0 +1 @@ +../../Task/Self-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Semiprime b/Lang/Pluto/Semiprime new file mode 120000 index 0000000000..8587fb750c --- /dev/null +++ b/Lang/Pluto/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Semordnilap b/Lang/Pluto/Semordnilap new file mode 120000 index 0000000000..92f96e5b0c --- /dev/null +++ b/Lang/Pluto/Semordnilap @@ -0,0 +1 @@ +../../Task/Semordnilap/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sequence-of-non-squares b/Lang/Pluto/Sequence-of-non-squares new file mode 120000 index 0000000000..ffd6b85122 --- /dev/null +++ b/Lang/Pluto/Sequence-of-non-squares @@ -0,0 +1 @@ +../../Task/Sequence-of-non-squares/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sequence-of-primes-by-trial-division b/Lang/Pluto/Sequence-of-primes-by-trial-division new file mode 120000 index 0000000000..0a541cb28c --- /dev/null +++ b/Lang/Pluto/Sequence-of-primes-by-trial-division @@ -0,0 +1 @@ +../../Task/Sequence-of-primes-by-trial-division/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sequence-of-primorial-primes b/Lang/Pluto/Sequence-of-primorial-primes new file mode 120000 index 0000000000..cc2120f894 --- /dev/null +++ b/Lang/Pluto/Sequence-of-primorial-primes @@ -0,0 +1 @@ +../../Task/Sequence-of-primorial-primes/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sequence:-smallest-number-with-exactly-n-divisors b/Lang/Pluto/Sequence:-smallest-number-with-exactly-n-divisors new file mode 120000 index 0000000000..ac5bc99ced --- /dev/null +++ b/Lang/Pluto/Sequence:-smallest-number-with-exactly-n-divisors @@ -0,0 +1 @@ +../../Task/Sequence:-smallest-number-with-exactly-n-divisors/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Set b/Lang/Pluto/Set new file mode 120000 index 0000000000..9bbe04e32f --- /dev/null +++ b/Lang/Pluto/Set @@ -0,0 +1 @@ +../../Task/Set/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Set-consolidation b/Lang/Pluto/Set-consolidation new file mode 120000 index 0000000000..af203f8560 --- /dev/null +++ b/Lang/Pluto/Set-consolidation @@ -0,0 +1 @@ +../../Task/Set-consolidation/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Set-of-real-numbers b/Lang/Pluto/Set-of-real-numbers new file mode 120000 index 0000000000..80d4d8a2d1 --- /dev/null +++ b/Lang/Pluto/Set-of-real-numbers @@ -0,0 +1 @@ +../../Task/Set-of-real-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Set-right-adjacent-bits b/Lang/Pluto/Set-right-adjacent-bits new file mode 120000 index 0000000000..7f599e0236 --- /dev/null +++ b/Lang/Pluto/Set-right-adjacent-bits @@ -0,0 +1 @@ +../../Task/Set-right-adjacent-bits/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sexy-primes b/Lang/Pluto/Sexy-primes new file mode 120000 index 0000000000..2ab94558b6 --- /dev/null +++ b/Lang/Pluto/Sexy-primes @@ -0,0 +1 @@ +../../Task/Sexy-primes/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Shoelace-formula-for-polygonal-area b/Lang/Pluto/Shoelace-formula-for-polygonal-area new file mode 120000 index 0000000000..beae637d82 --- /dev/null +++ b/Lang/Pluto/Shoelace-formula-for-polygonal-area @@ -0,0 +1 @@ +../../Task/Shoelace-formula-for-polygonal-area/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Show-ASCII-table b/Lang/Pluto/Show-ASCII-table new file mode 120000 index 0000000000..cac0997662 --- /dev/null +++ b/Lang/Pluto/Show-ASCII-table @@ -0,0 +1 @@ +../../Task/Show-ASCII-table/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sierpinski-arrowhead-curve b/Lang/Pluto/Sierpinski-arrowhead-curve new file mode 120000 index 0000000000..18f606e730 --- /dev/null +++ b/Lang/Pluto/Sierpinski-arrowhead-curve @@ -0,0 +1 @@ +../../Task/Sierpinski-arrowhead-curve/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sierpinski-square-curve b/Lang/Pluto/Sierpinski-square-curve new file mode 120000 index 0000000000..35f7d5150e --- /dev/null +++ b/Lang/Pluto/Sierpinski-square-curve @@ -0,0 +1 @@ +../../Task/Sierpinski-square-curve/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sierpinski-triangle-Graphical b/Lang/Pluto/Sierpinski-triangle-Graphical new file mode 120000 index 0000000000..008a1742b1 --- /dev/null +++ b/Lang/Pluto/Sierpinski-triangle-Graphical @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle-Graphical/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Simple-turtle-graphics b/Lang/Pluto/Simple-turtle-graphics new file mode 120000 index 0000000000..0cf7b3ba67 --- /dev/null +++ b/Lang/Pluto/Simple-turtle-graphics @@ -0,0 +1 @@ +../../Task/Simple-turtle-graphics/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Singleton b/Lang/Pluto/Singleton new file mode 120000 index 0000000000..b0a6a2c730 --- /dev/null +++ b/Lang/Pluto/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Singly-linked-list-Element-definition b/Lang/Pluto/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..1f46e7b961 --- /dev/null +++ b/Lang/Pluto/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Singly-linked-list-Element-insertion b/Lang/Pluto/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..27b69c63f5 --- /dev/null +++ b/Lang/Pluto/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Singly-linked-list-Traversal b/Lang/Pluto/Singly-linked-list-Traversal new file mode 120000 index 0000000000..a9f1239636 --- /dev/null +++ b/Lang/Pluto/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sleep b/Lang/Pluto/Sleep new file mode 120000 index 0000000000..fe338781ff --- /dev/null +++ b/Lang/Pluto/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sleeping-Beauty-problem b/Lang/Pluto/Sleeping-Beauty-problem new file mode 120000 index 0000000000..34cc3d8c3d --- /dev/null +++ b/Lang/Pluto/Sleeping-Beauty-problem @@ -0,0 +1 @@ +../../Task/Sleeping-Beauty-problem/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Smallest-number-k-such-that-k+2^m-is-composite-for-all-m-less-than-k b/Lang/Pluto/Smallest-number-k-such-that-k+2^m-is-composite-for-all-m-less-than-k new file mode 120000 index 0000000000..b69fb666de --- /dev/null +++ b/Lang/Pluto/Smallest-number-k-such-that-k+2^m-is-composite-for-all-m-less-than-k @@ -0,0 +1 @@ +../../Task/Smallest-number-k-such-that-k+2^m-is-composite-for-all-m-less-than-k/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Smarandache-Wellin-primes b/Lang/Pluto/Smarandache-Wellin-primes new file mode 120000 index 0000000000..44308127bf --- /dev/null +++ b/Lang/Pluto/Smarandache-Wellin-primes @@ -0,0 +1 @@ +../../Task/Smarandache-Wellin-primes/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Smarandache-prime-digital-sequence b/Lang/Pluto/Smarandache-prime-digital-sequence new file mode 120000 index 0000000000..c1bae0f65e --- /dev/null +++ b/Lang/Pluto/Smarandache-prime-digital-sequence @@ -0,0 +1 @@ +../../Task/Smarandache-prime-digital-sequence/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sockets b/Lang/Pluto/Sockets new file mode 120000 index 0000000000..50dbde578c --- /dev/null +++ b/Lang/Pluto/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sokoban b/Lang/Pluto/Sokoban new file mode 120000 index 0000000000..542f29a2fd --- /dev/null +++ b/Lang/Pluto/Sokoban @@ -0,0 +1 @@ +../../Task/Sokoban/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Soloways-recurring-rainfall b/Lang/Pluto/Soloways-recurring-rainfall new file mode 120000 index 0000000000..3292890eaf --- /dev/null +++ b/Lang/Pluto/Soloways-recurring-rainfall @@ -0,0 +1 @@ +../../Task/Soloways-recurring-rainfall/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Solve-a-Numbrix-puzzle b/Lang/Pluto/Solve-a-Numbrix-puzzle new file mode 120000 index 0000000000..a0c76a1703 --- /dev/null +++ b/Lang/Pluto/Solve-a-Numbrix-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Numbrix-puzzle/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sort-a-list-of-object-identifiers b/Lang/Pluto/Sort-a-list-of-object-identifiers new file mode 120000 index 0000000000..243d019eeb --- /dev/null +++ b/Lang/Pluto/Sort-a-list-of-object-identifiers @@ -0,0 +1 @@ +../../Task/Sort-a-list-of-object-identifiers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sort-an-array-of-composite-structures b/Lang/Pluto/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..11ca6daaca --- /dev/null +++ b/Lang/Pluto/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sort-an-integer-array b/Lang/Pluto/Sort-an-integer-array new file mode 120000 index 0000000000..43fcfc8222 --- /dev/null +++ b/Lang/Pluto/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sort-disjoint-sublist b/Lang/Pluto/Sort-disjoint-sublist new file mode 120000 index 0000000000..43eaf99d0d --- /dev/null +++ b/Lang/Pluto/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sort-numbers-lexicographically b/Lang/Pluto/Sort-numbers-lexicographically new file mode 120000 index 0000000000..e54ac23b46 --- /dev/null +++ b/Lang/Pluto/Sort-numbers-lexicographically @@ -0,0 +1 @@ +../../Task/Sort-numbers-lexicographically/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sort-using-a-custom-comparator b/Lang/Pluto/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..017bd9f879 --- /dev/null +++ b/Lang/Pluto/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sorting-algorithms-Bead-sort b/Lang/Pluto/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..732611b770 --- /dev/null +++ b/Lang/Pluto/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sorting-algorithms-Bogosort b/Lang/Pluto/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..2902c3ee3a --- /dev/null +++ b/Lang/Pluto/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sorting-algorithms-Bubble-sort b/Lang/Pluto/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..c4cdca7c13 --- /dev/null +++ b/Lang/Pluto/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sorting-algorithms-Cocktail-sort b/Lang/Pluto/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..468360189f --- /dev/null +++ b/Lang/Pluto/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sorting-algorithms-Cocktail-sort-with-shifting-bounds b/Lang/Pluto/Sorting-algorithms-Cocktail-sort-with-shifting-bounds new file mode 120000 index 0000000000..c01e910e78 --- /dev/null +++ b/Lang/Pluto/Sorting-algorithms-Cocktail-sort-with-shifting-bounds @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort-with-shifting-bounds/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sorting-algorithms-Comb-sort b/Lang/Pluto/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..b6f9e143fc --- /dev/null +++ b/Lang/Pluto/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sorting-algorithms-Counting-sort b/Lang/Pluto/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..d4c1acd3d5 --- /dev/null +++ b/Lang/Pluto/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sorting-algorithms-Gnome-sort b/Lang/Pluto/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..77a2f09b42 --- /dev/null +++ b/Lang/Pluto/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sorting-algorithms-Heapsort b/Lang/Pluto/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..4be9369490 --- /dev/null +++ b/Lang/Pluto/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sorting-algorithms-Insertion-sort b/Lang/Pluto/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..2f3123eb14 --- /dev/null +++ b/Lang/Pluto/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sorting-algorithms-Merge-sort b/Lang/Pluto/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..e46aac85a3 --- /dev/null +++ b/Lang/Pluto/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sorting-algorithms-Pancake-sort b/Lang/Pluto/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..857f218dec --- /dev/null +++ b/Lang/Pluto/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sorting-algorithms-Patience-sort b/Lang/Pluto/Sorting-algorithms-Patience-sort new file mode 120000 index 0000000000..bf8f7e3856 --- /dev/null +++ b/Lang/Pluto/Sorting-algorithms-Patience-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Patience-sort/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sorting-algorithms-Permutation-sort b/Lang/Pluto/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..a892e63103 --- /dev/null +++ b/Lang/Pluto/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sorting-algorithms-Quicksort b/Lang/Pluto/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..dcb1016c3c --- /dev/null +++ b/Lang/Pluto/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sorting-algorithms-Radix-sort b/Lang/Pluto/Sorting-algorithms-Radix-sort new file mode 120000 index 0000000000..2aa1cd2582 --- /dev/null +++ b/Lang/Pluto/Sorting-algorithms-Radix-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Radix-sort/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sorting-algorithms-Selection-sort b/Lang/Pluto/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..7993c7d392 --- /dev/null +++ b/Lang/Pluto/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sorting-algorithms-Shell-sort b/Lang/Pluto/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..aa83ab75ed --- /dev/null +++ b/Lang/Pluto/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sorting-algorithms-Sleep-sort b/Lang/Pluto/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..2b4156ef57 --- /dev/null +++ b/Lang/Pluto/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sorting-algorithms-Stooge-sort b/Lang/Pluto/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..adcd800531 --- /dev/null +++ b/Lang/Pluto/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sorting-algorithms-Strand-sort b/Lang/Pluto/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..a3576da55b --- /dev/null +++ b/Lang/Pluto/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sparkline-in-unicode b/Lang/Pluto/Sparkline-in-unicode new file mode 120000 index 0000000000..d4375bf194 --- /dev/null +++ b/Lang/Pluto/Sparkline-in-unicode @@ -0,0 +1 @@ +../../Task/Sparkline-in-unicode/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Spelling-of-ordinal-numbers b/Lang/Pluto/Spelling-of-ordinal-numbers new file mode 120000 index 0000000000..707c9a5de7 --- /dev/null +++ b/Lang/Pluto/Spelling-of-ordinal-numbers @@ -0,0 +1 @@ +../../Task/Spelling-of-ordinal-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Spiral-matrix b/Lang/Pluto/Spiral-matrix new file mode 120000 index 0000000000..ab63b333d6 --- /dev/null +++ b/Lang/Pluto/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Square-but-not-cube b/Lang/Pluto/Square-but-not-cube new file mode 120000 index 0000000000..93ef364cf3 --- /dev/null +++ b/Lang/Pluto/Square-but-not-cube @@ -0,0 +1 @@ +../../Task/Square-but-not-cube/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Square-free-integers b/Lang/Pluto/Square-free-integers new file mode 120000 index 0000000000..bd620174b2 --- /dev/null +++ b/Lang/Pluto/Square-free-integers @@ -0,0 +1 @@ +../../Task/Square-free-integers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Stack b/Lang/Pluto/Stack new file mode 120000 index 0000000000..b73a91dd58 --- /dev/null +++ b/Lang/Pluto/Stack @@ -0,0 +1 @@ +../../Task/Stack/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Start-from-a-main-routine b/Lang/Pluto/Start-from-a-main-routine new file mode 120000 index 0000000000..cbf12fbc14 --- /dev/null +++ b/Lang/Pluto/Start-from-a-main-routine @@ -0,0 +1 @@ +../../Task/Start-from-a-main-routine/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Statistics-Basic b/Lang/Pluto/Statistics-Basic new file mode 120000 index 0000000000..4f94a6e6d7 --- /dev/null +++ b/Lang/Pluto/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Statistics-Normal-distribution b/Lang/Pluto/Statistics-Normal-distribution new file mode 120000 index 0000000000..bc2d3ac3d4 --- /dev/null +++ b/Lang/Pluto/Statistics-Normal-distribution @@ -0,0 +1 @@ +../../Task/Statistics-Normal-distribution/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Stem-and-leaf-plot b/Lang/Pluto/Stem-and-leaf-plot new file mode 120000 index 0000000000..cc3ba5ca9e --- /dev/null +++ b/Lang/Pluto/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Stirling-numbers-of-the-first-kind b/Lang/Pluto/Stirling-numbers-of-the-first-kind new file mode 120000 index 0000000000..0c81546d18 --- /dev/null +++ b/Lang/Pluto/Stirling-numbers-of-the-first-kind @@ -0,0 +1 @@ +../../Task/Stirling-numbers-of-the-first-kind/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Stirling-numbers-of-the-second-kind b/Lang/Pluto/Stirling-numbers-of-the-second-kind new file mode 120000 index 0000000000..05d2a235b3 --- /dev/null +++ b/Lang/Pluto/Stirling-numbers-of-the-second-kind @@ -0,0 +1 @@ +../../Task/Stirling-numbers-of-the-second-kind/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Straddling-checkerboard b/Lang/Pluto/Straddling-checkerboard new file mode 120000 index 0000000000..d74538b05d --- /dev/null +++ b/Lang/Pluto/Straddling-checkerboard @@ -0,0 +1 @@ +../../Task/Straddling-checkerboard/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Strassens-algorithm b/Lang/Pluto/Strassens-algorithm new file mode 120000 index 0000000000..79ee4e726f --- /dev/null +++ b/Lang/Pluto/Strassens-algorithm @@ -0,0 +1 @@ +../../Task/Strassens-algorithm/Pluto \ No newline at end of file diff --git a/Lang/Pluto/String-append b/Lang/Pluto/String-append new file mode 120000 index 0000000000..e24995b130 --- /dev/null +++ b/Lang/Pluto/String-append @@ -0,0 +1 @@ +../../Task/String-append/Pluto \ No newline at end of file diff --git a/Lang/Pluto/String-interpolation-included- b/Lang/Pluto/String-interpolation-included- new file mode 120000 index 0000000000..7953b3790b --- /dev/null +++ b/Lang/Pluto/String-interpolation-included- @@ -0,0 +1 @@ +../../Task/String-interpolation-included-/Pluto \ No newline at end of file diff --git a/Lang/Pluto/String-length b/Lang/Pluto/String-length new file mode 120000 index 0000000000..9313ae7886 --- /dev/null +++ b/Lang/Pluto/String-length @@ -0,0 +1 @@ +../../Task/String-length/Pluto \ No newline at end of file diff --git a/Lang/Pluto/String-matching b/Lang/Pluto/String-matching new file mode 120000 index 0000000000..422a3c7f0c --- /dev/null +++ b/Lang/Pluto/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Pluto \ No newline at end of file diff --git a/Lang/Pluto/String-prepend b/Lang/Pluto/String-prepend new file mode 120000 index 0000000000..84229275c1 --- /dev/null +++ b/Lang/Pluto/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Strip-a-set-of-characters-from-a-string b/Lang/Pluto/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..805462a850 --- /dev/null +++ b/Lang/Pluto/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Pluto/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..f8b3fd3947 --- /dev/null +++ b/Lang/Pluto/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Subleq b/Lang/Pluto/Subleq new file mode 120000 index 0000000000..100b00d22e --- /dev/null +++ b/Lang/Pluto/Subleq @@ -0,0 +1 @@ +../../Task/Subleq/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Substring b/Lang/Pluto/Substring new file mode 120000 index 0000000000..830ca3e467 --- /dev/null +++ b/Lang/Pluto/Substring @@ -0,0 +1 @@ +../../Task/Substring/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Substring-Top-and-tail b/Lang/Pluto/Substring-Top-and-tail new file mode 120000 index 0000000000..ac12380468 --- /dev/null +++ b/Lang/Pluto/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Successive-prime-differences b/Lang/Pluto/Successive-prime-differences new file mode 120000 index 0000000000..17a80e33ef --- /dev/null +++ b/Lang/Pluto/Successive-prime-differences @@ -0,0 +1 @@ +../../Task/Successive-prime-differences/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sudan-function b/Lang/Pluto/Sudan-function new file mode 120000 index 0000000000..18faadc2cc --- /dev/null +++ b/Lang/Pluto/Sudan-function @@ -0,0 +1 @@ +../../Task/Sudan-function/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sudoku b/Lang/Pluto/Sudoku new file mode 120000 index 0000000000..0219f968ec --- /dev/null +++ b/Lang/Pluto/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Suffixation-of-decimal-numbers b/Lang/Pluto/Suffixation-of-decimal-numbers new file mode 120000 index 0000000000..c7008ba8db --- /dev/null +++ b/Lang/Pluto/Suffixation-of-decimal-numbers @@ -0,0 +1 @@ +../../Task/Suffixation-of-decimal-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sum-and-product-of-an-array b/Lang/Pluto/Sum-and-product-of-an-array new file mode 120000 index 0000000000..de37da7c3f --- /dev/null +++ b/Lang/Pluto/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sum-and-product-puzzle b/Lang/Pluto/Sum-and-product-puzzle new file mode 120000 index 0000000000..b5887c9a13 --- /dev/null +++ b/Lang/Pluto/Sum-and-product-puzzle @@ -0,0 +1 @@ +../../Task/Sum-and-product-puzzle/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sum-digits-of-an-integer b/Lang/Pluto/Sum-digits-of-an-integer new file mode 120000 index 0000000000..0c6a6782ed --- /dev/null +++ b/Lang/Pluto/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sum-multiples-of-3-and-5 b/Lang/Pluto/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..7476a45c41 --- /dev/null +++ b/Lang/Pluto/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sum-of-elements-below-main-diagonal-of-matrix b/Lang/Pluto/Sum-of-elements-below-main-diagonal-of-matrix new file mode 120000 index 0000000000..45a9f51475 --- /dev/null +++ b/Lang/Pluto/Sum-of-elements-below-main-diagonal-of-matrix @@ -0,0 +1 @@ +../../Task/Sum-of-elements-below-main-diagonal-of-matrix/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Summarize-and-say-sequence b/Lang/Pluto/Summarize-and-say-sequence new file mode 120000 index 0000000000..fc93ce6bcc --- /dev/null +++ b/Lang/Pluto/Summarize-and-say-sequence @@ -0,0 +1 @@ +../../Task/Summarize-and-say-sequence/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Summarize-primes b/Lang/Pluto/Summarize-primes new file mode 120000 index 0000000000..ecbdeed375 --- /dev/null +++ b/Lang/Pluto/Summarize-primes @@ -0,0 +1 @@ +../../Task/Summarize-primes/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Super-d-numbers b/Lang/Pluto/Super-d-numbers new file mode 120000 index 0000000000..f56d2824e5 --- /dev/null +++ b/Lang/Pluto/Super-d-numbers @@ -0,0 +1 @@ +../../Task/Super-d-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Superellipse b/Lang/Pluto/Superellipse new file mode 120000 index 0000000000..71cba61449 --- /dev/null +++ b/Lang/Pluto/Superellipse @@ -0,0 +1 @@ +../../Task/Superellipse/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sylvesters-sequence b/Lang/Pluto/Sylvesters-sequence new file mode 120000 index 0000000000..27749333cd --- /dev/null +++ b/Lang/Pluto/Sylvesters-sequence @@ -0,0 +1 @@ +../../Task/Sylvesters-sequence/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Symmetric-difference b/Lang/Pluto/Symmetric-difference new file mode 120000 index 0000000000..09ce1d13b8 --- /dev/null +++ b/Lang/Pluto/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Synchronous-concurrency b/Lang/Pluto/Synchronous-concurrency new file mode 120000 index 0000000000..4eb3a63418 --- /dev/null +++ b/Lang/Pluto/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/Pluto \ No newline at end of file diff --git a/Lang/Pluto/System-time b/Lang/Pluto/System-time new file mode 120000 index 0000000000..8575dc8b3a --- /dev/null +++ b/Lang/Pluto/System-time @@ -0,0 +1 @@ +../../Task/System-time/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Tau-function b/Lang/Pluto/Tau-function new file mode 120000 index 0000000000..03b50006f6 --- /dev/null +++ b/Lang/Pluto/Tau-function @@ -0,0 +1 @@ +../../Task/Tau-function/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Tau-number b/Lang/Pluto/Tau-number new file mode 120000 index 0000000000..532021c510 --- /dev/null +++ b/Lang/Pluto/Tau-number @@ -0,0 +1 @@ +../../Task/Tau-number/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Temperature-conversion b/Lang/Pluto/Temperature-conversion new file mode 120000 index 0000000000..dfda68998c --- /dev/null +++ b/Lang/Pluto/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Terminal-control-Clear-the-screen b/Lang/Pluto/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..edabc9ce73 --- /dev/null +++ b/Lang/Pluto/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Terminal-control-Coloured-text b/Lang/Pluto/Terminal-control-Coloured-text new file mode 120000 index 0000000000..378909157d --- /dev/null +++ b/Lang/Pluto/Terminal-control-Coloured-text @@ -0,0 +1 @@ +../../Task/Terminal-control-Coloured-text/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Terminal-control-Cursor-movement b/Lang/Pluto/Terminal-control-Cursor-movement new file mode 120000 index 0000000000..bf8c8572a2 --- /dev/null +++ b/Lang/Pluto/Terminal-control-Cursor-movement @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-movement/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Terminal-control-Cursor-positioning b/Lang/Pluto/Terminal-control-Cursor-positioning new file mode 120000 index 0000000000..feeca5cd4b --- /dev/null +++ b/Lang/Pluto/Terminal-control-Cursor-positioning @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-positioning/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Terminal-control-Dimensions b/Lang/Pluto/Terminal-control-Dimensions new file mode 120000 index 0000000000..79b01b1a8a --- /dev/null +++ b/Lang/Pluto/Terminal-control-Dimensions @@ -0,0 +1 @@ +../../Task/Terminal-control-Dimensions/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Terminal-control-Display-an-extended-character b/Lang/Pluto/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..d9f4ec60f5 --- /dev/null +++ b/Lang/Pluto/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Terminal-control-Hiding-the-cursor b/Lang/Pluto/Terminal-control-Hiding-the-cursor new file mode 120000 index 0000000000..5126fbbc31 --- /dev/null +++ b/Lang/Pluto/Terminal-control-Hiding-the-cursor @@ -0,0 +1 @@ +../../Task/Terminal-control-Hiding-the-cursor/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Terminal-control-Inverse-video b/Lang/Pluto/Terminal-control-Inverse-video new file mode 120000 index 0000000000..a011de6856 --- /dev/null +++ b/Lang/Pluto/Terminal-control-Inverse-video @@ -0,0 +1 @@ +../../Task/Terminal-control-Inverse-video/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Terminal-control-Preserve-screen b/Lang/Pluto/Terminal-control-Preserve-screen new file mode 120000 index 0000000000..4985e385ae --- /dev/null +++ b/Lang/Pluto/Terminal-control-Preserve-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Preserve-screen/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Terminal-control-Ringing-the-terminal-bell b/Lang/Pluto/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..c14ff1f9fd --- /dev/null +++ b/Lang/Pluto/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Terminal-control-Unicode-output b/Lang/Pluto/Terminal-control-Unicode-output new file mode 120000 index 0000000000..c67e68f15d --- /dev/null +++ b/Lang/Pluto/Terminal-control-Unicode-output @@ -0,0 +1 @@ +../../Task/Terminal-control-Unicode-output/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Ternary-logic b/Lang/Pluto/Ternary-logic new file mode 120000 index 0000000000..ca522a2f56 --- /dev/null +++ b/Lang/Pluto/Ternary-logic @@ -0,0 +1 @@ +../../Task/Ternary-logic/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Test-integerness b/Lang/Pluto/Test-integerness new file mode 120000 index 0000000000..9a3717f805 --- /dev/null +++ b/Lang/Pluto/Test-integerness @@ -0,0 +1 @@ +../../Task/Test-integerness/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Textonyms b/Lang/Pluto/Textonyms new file mode 120000 index 0000000000..4c3ea903b1 --- /dev/null +++ b/Lang/Pluto/Textonyms @@ -0,0 +1 @@ +../../Task/Textonyms/Pluto \ No newline at end of file diff --git a/Lang/Pluto/The-Name-Game b/Lang/Pluto/The-Name-Game new file mode 120000 index 0000000000..de7bc541a3 --- /dev/null +++ b/Lang/Pluto/The-Name-Game @@ -0,0 +1 @@ +../../Task/The-Name-Game/Pluto \ No newline at end of file diff --git a/Lang/Pluto/The-Twelve-Days-of-Christmas b/Lang/Pluto/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..0c2a346005 --- /dev/null +++ b/Lang/Pluto/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/Pluto \ No newline at end of file diff --git a/Lang/Pluto/The-sieve-of-Sundaram b/Lang/Pluto/The-sieve-of-Sundaram new file mode 120000 index 0000000000..bf60d24d46 --- /dev/null +++ b/Lang/Pluto/The-sieve-of-Sundaram @@ -0,0 +1 @@ +../../Task/The-sieve-of-Sundaram/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Thue-Morse b/Lang/Pluto/Thue-Morse new file mode 120000 index 0000000000..b1a06a67e8 --- /dev/null +++ b/Lang/Pluto/Thue-Morse @@ -0,0 +1 @@ +../../Task/Thue-Morse/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Time-a-function b/Lang/Pluto/Time-a-function new file mode 120000 index 0000000000..1ca7d0a7b7 --- /dev/null +++ b/Lang/Pluto/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Tokenize-a-string-with-escaping b/Lang/Pluto/Tokenize-a-string-with-escaping new file mode 120000 index 0000000000..ba51452013 --- /dev/null +++ b/Lang/Pluto/Tokenize-a-string-with-escaping @@ -0,0 +1 @@ +../../Task/Tokenize-a-string-with-escaping/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Top-rank-per-group b/Lang/Pluto/Top-rank-per-group new file mode 120000 index 0000000000..c27cb54f5d --- /dev/null +++ b/Lang/Pluto/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Total-circles-area b/Lang/Pluto/Total-circles-area new file mode 120000 index 0000000000..2f856ad28d --- /dev/null +++ b/Lang/Pluto/Total-circles-area @@ -0,0 +1 @@ +../../Task/Total-circles-area/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Totient-function b/Lang/Pluto/Totient-function new file mode 120000 index 0000000000..73b5eb6381 --- /dev/null +++ b/Lang/Pluto/Totient-function @@ -0,0 +1 @@ +../../Task/Totient-function/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Towers-of-Hanoi b/Lang/Pluto/Towers-of-Hanoi new file mode 120000 index 0000000000..9b1428dcf0 --- /dev/null +++ b/Lang/Pluto/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Trabb-Pardo-Knuth-algorithm b/Lang/Pluto/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..e85f9f54de --- /dev/null +++ b/Lang/Pluto/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Transliterate-English-text-using-the-Greek-alphabet b/Lang/Pluto/Transliterate-English-text-using-the-Greek-alphabet new file mode 120000 index 0000000000..329d1e52f1 --- /dev/null +++ b/Lang/Pluto/Transliterate-English-text-using-the-Greek-alphabet @@ -0,0 +1 @@ +../../Task/Transliterate-English-text-using-the-Greek-alphabet/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Trigonometric-functions b/Lang/Pluto/Trigonometric-functions new file mode 120000 index 0000000000..8bcbebbd97 --- /dev/null +++ b/Lang/Pluto/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Truncatable-primes b/Lang/Pluto/Truncatable-primes new file mode 120000 index 0000000000..e57c3ab40f --- /dev/null +++ b/Lang/Pluto/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Truncate-a-file b/Lang/Pluto/Truncate-a-file new file mode 120000 index 0000000000..f472b828c2 --- /dev/null +++ b/Lang/Pluto/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Truth-table b/Lang/Pluto/Truth-table new file mode 120000 index 0000000000..e15e65e09d --- /dev/null +++ b/Lang/Pluto/Truth-table @@ -0,0 +1 @@ +../../Task/Truth-table/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Twelve-statements b/Lang/Pluto/Twelve-statements new file mode 120000 index 0000000000..f003bdd498 --- /dev/null +++ b/Lang/Pluto/Twelve-statements @@ -0,0 +1 @@ +../../Task/Twelve-statements/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Twos-complement b/Lang/Pluto/Twos-complement new file mode 120000 index 0000000000..5830145b21 --- /dev/null +++ b/Lang/Pluto/Twos-complement @@ -0,0 +1 @@ +../../Task/Twos-complement/Pluto \ No newline at end of file diff --git a/Lang/Pluto/UPC b/Lang/Pluto/UPC new file mode 120000 index 0000000000..477e69b6c6 --- /dev/null +++ b/Lang/Pluto/UPC @@ -0,0 +1 @@ +../../Task/UPC/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Ultra-useful-primes b/Lang/Pluto/Ultra-useful-primes new file mode 120000 index 0000000000..5db52360c1 --- /dev/null +++ b/Lang/Pluto/Ultra-useful-primes @@ -0,0 +1 @@ +../../Task/Ultra-useful-primes/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Unbias-a-random-generator b/Lang/Pluto/Unbias-a-random-generator new file mode 120000 index 0000000000..14b505ac5e --- /dev/null +++ b/Lang/Pluto/Unbias-a-random-generator @@ -0,0 +1 @@ +../../Task/Unbias-a-random-generator/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Unicode-strings b/Lang/Pluto/Unicode-strings new file mode 120000 index 0000000000..482c486148 --- /dev/null +++ b/Lang/Pluto/Unicode-strings @@ -0,0 +1 @@ +../../Task/Unicode-strings/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Unprimeable-numbers b/Lang/Pluto/Unprimeable-numbers new file mode 120000 index 0000000000..ec55975821 --- /dev/null +++ b/Lang/Pluto/Unprimeable-numbers @@ -0,0 +1 @@ +../../Task/Unprimeable-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/User-input-Text b/Lang/Pluto/User-input-Text new file mode 120000 index 0000000000..6c3afd2860 --- /dev/null +++ b/Lang/Pluto/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Vampire-number b/Lang/Pluto/Vampire-number new file mode 120000 index 0000000000..39b76c4ae2 --- /dev/null +++ b/Lang/Pluto/Vampire-number @@ -0,0 +1 @@ +../../Task/Vampire-number/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Van-Eck-sequence b/Lang/Pluto/Van-Eck-sequence new file mode 120000 index 0000000000..d053bbc892 --- /dev/null +++ b/Lang/Pluto/Van-Eck-sequence @@ -0,0 +1 @@ +../../Task/Van-Eck-sequence/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Van-der-Corput-sequence b/Lang/Pluto/Van-der-Corput-sequence new file mode 120000 index 0000000000..e6ce56ddef --- /dev/null +++ b/Lang/Pluto/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Variable-declaration-reset b/Lang/Pluto/Variable-declaration-reset new file mode 120000 index 0000000000..26738839ca --- /dev/null +++ b/Lang/Pluto/Variable-declaration-reset @@ -0,0 +1 @@ +../../Task/Variable-declaration-reset/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Variable-length-quantity b/Lang/Pluto/Variable-length-quantity new file mode 120000 index 0000000000..3f78793bbd --- /dev/null +++ b/Lang/Pluto/Variable-length-quantity @@ -0,0 +1 @@ +../../Task/Variable-length-quantity/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Variadic-function b/Lang/Pluto/Variadic-function new file mode 120000 index 0000000000..8d2be144f4 --- /dev/null +++ b/Lang/Pluto/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Vector b/Lang/Pluto/Vector new file mode 120000 index 0000000000..fd56d6c8ab --- /dev/null +++ b/Lang/Pluto/Vector @@ -0,0 +1 @@ +../../Task/Vector/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Vector-products b/Lang/Pluto/Vector-products new file mode 120000 index 0000000000..83a09bc1a3 --- /dev/null +++ b/Lang/Pluto/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Verhoeff-algorithm b/Lang/Pluto/Verhoeff-algorithm new file mode 120000 index 0000000000..1b001cd3c1 --- /dev/null +++ b/Lang/Pluto/Verhoeff-algorithm @@ -0,0 +1 @@ +../../Task/Verhoeff-algorithm/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Voronoi-diagram b/Lang/Pluto/Voronoi-diagram new file mode 120000 index 0000000000..50678561e7 --- /dev/null +++ b/Lang/Pluto/Voronoi-diagram @@ -0,0 +1 @@ +../../Task/Voronoi-diagram/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Wagstaff-primes b/Lang/Pluto/Wagstaff-primes new file mode 120000 index 0000000000..d8a1a2f0da --- /dev/null +++ b/Lang/Pluto/Wagstaff-primes @@ -0,0 +1 @@ +../../Task/Wagstaff-primes/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Water-collected-between-towers b/Lang/Pluto/Water-collected-between-towers new file mode 120000 index 0000000000..94e32bc8f3 --- /dev/null +++ b/Lang/Pluto/Water-collected-between-towers @@ -0,0 +1 @@ +../../Task/Water-collected-between-towers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Wieferich-primes b/Lang/Pluto/Wieferich-primes new file mode 120000 index 0000000000..453231fbab --- /dev/null +++ b/Lang/Pluto/Wieferich-primes @@ -0,0 +1 @@ +../../Task/Wieferich-primes/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Wilson-primes-of-order-n b/Lang/Pluto/Wilson-primes-of-order-n new file mode 120000 index 0000000000..9bafdd051b --- /dev/null +++ b/Lang/Pluto/Wilson-primes-of-order-n @@ -0,0 +1 @@ +../../Task/Wilson-primes-of-order-n/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Wireworld b/Lang/Pluto/Wireworld new file mode 120000 index 0000000000..1eed665c2c --- /dev/null +++ b/Lang/Pluto/Wireworld @@ -0,0 +1 @@ +../../Task/Wireworld/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Word-wheel b/Lang/Pluto/Word-wheel new file mode 120000 index 0000000000..c83ad2ab7f --- /dev/null +++ b/Lang/Pluto/Word-wheel @@ -0,0 +1 @@ +../../Task/Word-wheel/Pluto \ No newline at end of file diff --git a/Lang/Pluto/World-Cup-group-stage b/Lang/Pluto/World-Cup-group-stage new file mode 120000 index 0000000000..1c8f3e8b53 --- /dev/null +++ b/Lang/Pluto/World-Cup-group-stage @@ -0,0 +1 @@ +../../Task/World-Cup-group-stage/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Write-entire-file b/Lang/Pluto/Write-entire-file new file mode 120000 index 0000000000..be63715e40 --- /dev/null +++ b/Lang/Pluto/Write-entire-file @@ -0,0 +1 @@ +../../Task/Write-entire-file/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Write-float-arrays-to-a-text-file b/Lang/Pluto/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..eaa4582b34 --- /dev/null +++ b/Lang/Pluto/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Write-language-name-in-3D-ASCII b/Lang/Pluto/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..54358f8cdd --- /dev/null +++ b/Lang/Pluto/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Y-combinator b/Lang/Pluto/Y-combinator new file mode 120000 index 0000000000..b356912f44 --- /dev/null +++ b/Lang/Pluto/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Yellowstone-sequence b/Lang/Pluto/Yellowstone-sequence new file mode 120000 index 0000000000..f4fb013414 --- /dev/null +++ b/Lang/Pluto/Yellowstone-sequence @@ -0,0 +1 @@ +../../Task/Yellowstone-sequence/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Zebra-puzzle b/Lang/Pluto/Zebra-puzzle new file mode 120000 index 0000000000..d1dee531e9 --- /dev/null +++ b/Lang/Pluto/Zebra-puzzle @@ -0,0 +1 @@ +../../Task/Zebra-puzzle/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Zeckendorf-number-representation b/Lang/Pluto/Zeckendorf-number-representation new file mode 120000 index 0000000000..6f7ac19b32 --- /dev/null +++ b/Lang/Pluto/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Zero-to-the-zero-power b/Lang/Pluto/Zero-to-the-zero-power new file mode 120000 index 0000000000..88cbcf1376 --- /dev/null +++ b/Lang/Pluto/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Zig-zag-matrix b/Lang/Pluto/Zig-zag-matrix new file mode 120000 index 0000000000..49521638f6 --- /dev/null +++ b/Lang/Pluto/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Pluto \ No newline at end of file diff --git a/Lang/PostScript/Sieve-of-Eratosthenes b/Lang/PostScript/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..bf5fd9fe66 --- /dev/null +++ b/Lang/PostScript/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/PostScript \ No newline at end of file diff --git a/Lang/PowerShell/AKS-test-for-primes b/Lang/PowerShell/AKS-test-for-primes new file mode 120000 index 0000000000..d5622ba541 --- /dev/null +++ b/Lang/PowerShell/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Abundant-odd-numbers b/Lang/PowerShell/Abundant-odd-numbers new file mode 120000 index 0000000000..fa7795f731 --- /dev/null +++ b/Lang/PowerShell/Abundant-odd-numbers @@ -0,0 +1 @@ +../../Task/Abundant-odd-numbers/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Anti-primes b/Lang/PowerShell/Anti-primes new file mode 120000 index 0000000000..f56c16a315 --- /dev/null +++ b/Lang/PowerShell/Anti-primes @@ -0,0 +1 @@ +../../Task/Anti-primes/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Base64-decode-data b/Lang/PowerShell/Base64-decode-data new file mode 120000 index 0000000000..64cfcd61a8 --- /dev/null +++ b/Lang/PowerShell/Base64-decode-data @@ -0,0 +1 @@ +../../Task/Base64-decode-data/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Bell-numbers b/Lang/PowerShell/Bell-numbers new file mode 120000 index 0000000000..175671e690 --- /dev/null +++ b/Lang/PowerShell/Bell-numbers @@ -0,0 +1 @@ +../../Task/Bell-numbers/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Brazilian-numbers b/Lang/PowerShell/Brazilian-numbers new file mode 120000 index 0000000000..93e2e48db6 --- /dev/null +++ b/Lang/PowerShell/Brazilian-numbers @@ -0,0 +1 @@ +../../Task/Brazilian-numbers/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Call-a-foreign-language-function b/Lang/PowerShell/Call-a-foreign-language-function new file mode 120000 index 0000000000..b222a9fc7d --- /dev/null +++ b/Lang/PowerShell/Call-a-foreign-language-function @@ -0,0 +1 @@ +../../Task/Call-a-foreign-language-function/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Department-numbers b/Lang/PowerShell/Department-numbers new file mode 120000 index 0000000000..089828bb9a --- /dev/null +++ b/Lang/PowerShell/Department-numbers @@ -0,0 +1 @@ +../../Task/Department-numbers/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Gray-code b/Lang/PowerShell/Gray-code new file mode 120000 index 0000000000..c7adcf7cdb --- /dev/null +++ b/Lang/PowerShell/Gray-code @@ -0,0 +1 @@ +../../Task/Gray-code/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Hello-world-Web-server b/Lang/PowerShell/Hello-world-Web-server new file mode 120000 index 0000000000..3b4f878f34 --- /dev/null +++ b/Lang/PowerShell/Hello-world-Web-server @@ -0,0 +1 @@ +../../Task/Hello-world-Web-server/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Leonardo-numbers b/Lang/PowerShell/Leonardo-numbers new file mode 120000 index 0000000000..fda0fa0dbc --- /dev/null +++ b/Lang/PowerShell/Leonardo-numbers @@ -0,0 +1 @@ +../../Task/Leonardo-numbers/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/M-bius-function b/Lang/PowerShell/M-bius-function new file mode 120000 index 0000000000..a50c276864 --- /dev/null +++ b/Lang/PowerShell/M-bius-function @@ -0,0 +1 @@ +../../Task/M-bius-function/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Mayan-numerals b/Lang/PowerShell/Mayan-numerals new file mode 120000 index 0000000000..24e3ef5efb --- /dev/null +++ b/Lang/PowerShell/Mayan-numerals @@ -0,0 +1 @@ +../../Task/Mayan-numerals/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Multifactorial b/Lang/PowerShell/Multifactorial new file mode 120000 index 0000000000..45d4ca2539 --- /dev/null +++ b/Lang/PowerShell/Multifactorial @@ -0,0 +1 @@ +../../Task/Multifactorial/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Periodic-table b/Lang/PowerShell/Periodic-table new file mode 120000 index 0000000000..bcfd7f5cf0 --- /dev/null +++ b/Lang/PowerShell/Periodic-table @@ -0,0 +1 @@ +../../Task/Periodic-table/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Quaternion-type b/Lang/PowerShell/Quaternion-type deleted file mode 120000 index 60f8156bec..0000000000 --- a/Lang/PowerShell/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Statistics-Basic b/Lang/PowerShell/Statistics-Basic new file mode 120000 index 0000000000..604034a29d --- /dev/null +++ b/Lang/PowerShell/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Statistics-Normal-distribution b/Lang/PowerShell/Statistics-Normal-distribution new file mode 120000 index 0000000000..9ce69e4094 --- /dev/null +++ b/Lang/PowerShell/Statistics-Normal-distribution @@ -0,0 +1 @@ +../../Task/Statistics-Normal-distribution/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Strassens-algorithm b/Lang/PowerShell/Strassens-algorithm new file mode 120000 index 0000000000..1b221ce844 --- /dev/null +++ b/Lang/PowerShell/Strassens-algorithm @@ -0,0 +1 @@ +../../Task/Strassens-algorithm/PowerShell \ No newline at end of file diff --git a/Lang/ProDOS/00-LANG.txt b/Lang/ProDOS/00-LANG.txt index 3affb9c53a..d4852ff3b2 100644 --- a/Lang/ProDOS/00-LANG.txt +++ b/Lang/ProDOS/00-LANG.txt @@ -4,18 +4,18 @@ ProDOS is an open-source command-based programming language created by Riley Hou ===Overview=== ProDOS is a command-based language. This term refers to any form of language that uses built-in commands to function, instead of strings of keywords to function. For example: -printline Hello, World! +printline Hello, World! The command "printline" is used to display the line "Hello, World". For clarification, in Java the alternative would be: -public class HelloWorld +public class HelloWorld { public static void main(String[] args) { System.out.println("Goodbye, World!"); } -} +}
    -As you can see, the difference is quite significant. The command "printline" is pre-defined, this means that the user does not have to define classes,etc. +As you can see, the difference is quite significant. The command "printline" is pre-defined, this means that the user does not have to define classes,etc. ===Future Implementations=== ProDOS has not yet reached a release stage, but due to it being only a few months left until it is able to be released, ProDOS 1 will be ready to be released for public distribution by early 2012. \ No newline at end of file diff --git a/Lang/Prog8/Quine b/Lang/Prog8/Quine new file mode 120000 index 0000000000..d19dfe3196 --- /dev/null +++ b/Lang/Prog8/Quine @@ -0,0 +1 @@ +../../Task/Quine/Prog8 \ No newline at end of file diff --git a/Lang/ProgressBASIC/00-LANG.txt b/Lang/ProgressBASIC/00-LANG.txt new file mode 100644 index 0000000000..d243dbaa3d --- /dev/null +++ b/Lang/ProgressBASIC/00-LANG.txt @@ -0,0 +1,3 @@ +{{language}} +ProgressBASIC is a BASIC-like programming language used in the mobile/steam game Progressbar95. To get acses to the programming language. You must unlock the 8-bit category of systems. +To understand how this programming language works, [https://progressbar95.fandom.com/wiki/ProgressBASIC#Commands click this] \ No newline at end of file diff --git a/Lang/ProgressBASIC/00-META.yaml b/Lang/ProgressBASIC/00-META.yaml new file mode 100644 index 0000000000..82857e2590 --- /dev/null +++ b/Lang/ProgressBASIC/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:ProgressBASIC diff --git a/Lang/Prolog/100-prisoners b/Lang/Prolog/100-prisoners new file mode 120000 index 0000000000..f105600099 --- /dev/null +++ b/Lang/Prolog/100-prisoners @@ -0,0 +1 @@ +../../Task/100-prisoners/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Boolean-values b/Lang/Prolog/Boolean-values new file mode 120000 index 0000000000..a4d04329bd --- /dev/null +++ b/Lang/Prolog/Boolean-values @@ -0,0 +1 @@ +../../Task/Boolean-values/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Damm-algorithm b/Lang/Prolog/Damm-algorithm new file mode 120000 index 0000000000..beadc26281 --- /dev/null +++ b/Lang/Prolog/Damm-algorithm @@ -0,0 +1 @@ +../../Task/Damm-algorithm/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Determine-sentence-type b/Lang/Prolog/Determine-sentence-type new file mode 120000 index 0000000000..d87bf5b582 --- /dev/null +++ b/Lang/Prolog/Determine-sentence-type @@ -0,0 +1 @@ +../../Task/Determine-sentence-type/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Evaluate-binomial-coefficients b/Lang/Prolog/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..15602e690b --- /dev/null +++ b/Lang/Prolog/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Hello-world-Newline-omission b/Lang/Prolog/Hello-world-Newline-omission new file mode 120000 index 0000000000..c1a7a16c3a --- /dev/null +++ b/Lang/Prolog/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/Prolog \ No newline at end of file diff --git a/Lang/Prolog/ISBN13-check-digit b/Lang/Prolog/ISBN13-check-digit new file mode 120000 index 0000000000..a76610ede1 --- /dev/null +++ b/Lang/Prolog/ISBN13-check-digit @@ -0,0 +1 @@ +../../Task/ISBN13-check-digit/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Integer-comparison b/Lang/Prolog/Integer-comparison new file mode 120000 index 0000000000..700709dfc3 --- /dev/null +++ b/Lang/Prolog/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Iterated-digits-squaring b/Lang/Prolog/Iterated-digits-squaring new file mode 120000 index 0000000000..2783b6cb96 --- /dev/null +++ b/Lang/Prolog/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Josephus-problem b/Lang/Prolog/Josephus-problem new file mode 120000 index 0000000000..f88549c05c --- /dev/null +++ b/Lang/Prolog/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Magic-8-ball b/Lang/Prolog/Magic-8-ball new file mode 120000 index 0000000000..6daea6349e --- /dev/null +++ b/Lang/Prolog/Magic-8-ball @@ -0,0 +1 @@ +../../Task/Magic-8-ball/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Map-range b/Lang/Prolog/Map-range new file mode 120000 index 0000000000..09c2135423 --- /dev/null +++ b/Lang/Prolog/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Miller-Rabin-primality-test b/Lang/Prolog/Miller-Rabin-primality-test deleted file mode 120000 index 77f0bc56fd..0000000000 --- a/Lang/Prolog/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Old-Russian-measure-of-length b/Lang/Prolog/Old-Russian-measure-of-length new file mode 120000 index 0000000000..d1594e7647 --- /dev/null +++ b/Lang/Prolog/Old-Russian-measure-of-length @@ -0,0 +1 @@ +../../Task/Old-Russian-measure-of-length/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Order-by-pair-comparisons b/Lang/Prolog/Order-by-pair-comparisons new file mode 120000 index 0000000000..b08bc67036 --- /dev/null +++ b/Lang/Prolog/Order-by-pair-comparisons @@ -0,0 +1 @@ +../../Task/Order-by-pair-comparisons/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Phrase-reversals b/Lang/Prolog/Phrase-reversals new file mode 120000 index 0000000000..1afa8eb5f5 --- /dev/null +++ b/Lang/Prolog/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Population-count b/Lang/Prolog/Population-count new file mode 120000 index 0000000000..1ffa420c15 --- /dev/null +++ b/Lang/Prolog/Population-count @@ -0,0 +1 @@ +../../Task/Population-count/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Quaternion-type b/Lang/Prolog/Quaternion-type deleted file mode 120000 index 458f5f70bc..0000000000 --- a/Lang/Prolog/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Prolog \ No newline at end of file diff --git a/Lang/Prolog/RPG-attributes-generator b/Lang/Prolog/RPG-attributes-generator new file mode 120000 index 0000000000..cde5e146a7 --- /dev/null +++ b/Lang/Prolog/RPG-attributes-generator @@ -0,0 +1 @@ +../../Task/RPG-attributes-generator/Prolog \ No newline at end of file diff --git a/Lang/Prolog/SEDOLs b/Lang/Prolog/SEDOLs new file mode 120000 index 0000000000..21d9643112 --- /dev/null +++ b/Lang/Prolog/SEDOLs @@ -0,0 +1 @@ +../../Task/SEDOLs/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Semordnilap b/Lang/Prolog/Semordnilap new file mode 120000 index 0000000000..c4e2d18fc4 --- /dev/null +++ b/Lang/Prolog/Semordnilap @@ -0,0 +1 @@ +../../Task/Semordnilap/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Sort-three-variables b/Lang/Prolog/Sort-three-variables new file mode 120000 index 0000000000..8518a9819c --- /dev/null +++ b/Lang/Prolog/Sort-three-variables @@ -0,0 +1 @@ +../../Task/Sort-three-variables/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Stem-and-leaf-plot b/Lang/Prolog/Stem-and-leaf-plot new file mode 120000 index 0000000000..8a3d5cbab0 --- /dev/null +++ b/Lang/Prolog/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/Prolog \ No newline at end of file diff --git a/Lang/Prolog/String-concatenation b/Lang/Prolog/String-concatenation new file mode 120000 index 0000000000..47d572fb22 --- /dev/null +++ b/Lang/Prolog/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Thue-Morse b/Lang/Prolog/Thue-Morse new file mode 120000 index 0000000000..c42ff58a18 --- /dev/null +++ b/Lang/Prolog/Thue-Morse @@ -0,0 +1 @@ +../../Task/Thue-Morse/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Topswops b/Lang/Prolog/Topswops new file mode 120000 index 0000000000..20c5cfbba8 --- /dev/null +++ b/Lang/Prolog/Topswops @@ -0,0 +1 @@ +../../Task/Topswops/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Trabb-Pardo-Knuth-algorithm b/Lang/Prolog/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..dcd294e9ea --- /dev/null +++ b/Lang/Prolog/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Twos-complement b/Lang/Prolog/Twos-complement new file mode 120000 index 0000000000..1ba2d1e131 --- /dev/null +++ b/Lang/Prolog/Twos-complement @@ -0,0 +1 @@ +../../Task/Twos-complement/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Wireworld b/Lang/Prolog/Wireworld new file mode 120000 index 0000000000..b45eaa2601 --- /dev/null +++ b/Lang/Prolog/Wireworld @@ -0,0 +1 @@ +../../Task/Wireworld/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Zero-to-the-zero-power b/Lang/Prolog/Zero-to-the-zero-power new file mode 120000 index 0000000000..5d3d1cb814 --- /dev/null +++ b/Lang/Prolog/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Prolog \ No newline at end of file diff --git a/Lang/PureBasic/ASCII-art-diagram-converter b/Lang/PureBasic/ASCII-art-diagram-converter new file mode 120000 index 0000000000..33f4c7eea5 --- /dev/null +++ b/Lang/PureBasic/ASCII-art-diagram-converter @@ -0,0 +1 @@ +../../Task/ASCII-art-diagram-converter/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Bioinformatics-base-count b/Lang/PureBasic/Bioinformatics-base-count deleted file mode 120000 index 16be5f27be..0000000000 --- a/Lang/PureBasic/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Blum-integer b/Lang/PureBasic/Blum-integer new file mode 120000 index 0000000000..d3f0a3d564 --- /dev/null +++ b/Lang/PureBasic/Blum-integer @@ -0,0 +1 @@ +../../Task/Blum-integer/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Determine-if-a-string-has-all-the-same-characters b/Lang/PureBasic/Determine-if-a-string-has-all-the-same-characters new file mode 120000 index 0000000000..8ce6b940bc --- /dev/null +++ b/Lang/PureBasic/Determine-if-a-string-has-all-the-same-characters @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-has-all-the-same-characters/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Determine-sentence-type b/Lang/PureBasic/Determine-sentence-type new file mode 120000 index 0000000000..58f4c9411b --- /dev/null +++ b/Lang/PureBasic/Determine-sentence-type @@ -0,0 +1 @@ +../../Task/Determine-sentence-type/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Generate-Chess960-starting-position b/Lang/PureBasic/Generate-Chess960-starting-position new file mode 120000 index 0000000000..d1a0ea8b2a --- /dev/null +++ b/Lang/PureBasic/Generate-Chess960-starting-position @@ -0,0 +1 @@ +../../Task/Generate-Chess960-starting-position/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Jewels-and-stones b/Lang/PureBasic/Jewels-and-stones new file mode 120000 index 0000000000..90d847c8e7 --- /dev/null +++ b/Lang/PureBasic/Jewels-and-stones @@ -0,0 +1 @@ +../../Task/Jewels-and-stones/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/M-bius-function b/Lang/PureBasic/M-bius-function new file mode 120000 index 0000000000..86603635cf --- /dev/null +++ b/Lang/PureBasic/M-bius-function @@ -0,0 +1 @@ +../../Task/M-bius-function/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Meissel-Mertens-constant b/Lang/PureBasic/Meissel-Mertens-constant deleted file mode 120000 index 81f0bd26b3..0000000000 --- a/Lang/PureBasic/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Miller-Rabin-primality-test b/Lang/PureBasic/Miller-Rabin-primality-test deleted file mode 120000 index af69162304..0000000000 --- a/Lang/PureBasic/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Numerical-and-alphabetical-suffixes b/Lang/PureBasic/Numerical-and-alphabetical-suffixes new file mode 120000 index 0000000000..1544fa8d4a --- /dev/null +++ b/Lang/PureBasic/Numerical-and-alphabetical-suffixes @@ -0,0 +1 @@ +../../Task/Numerical-and-alphabetical-suffixes/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Periodic-table b/Lang/PureBasic/Periodic-table new file mode 120000 index 0000000000..d212a3056c --- /dev/null +++ b/Lang/PureBasic/Periodic-table @@ -0,0 +1 @@ +../../Task/Periodic-table/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Quaternion-type b/Lang/PureBasic/Quaternion-type deleted file mode 120000 index 6551ed8e89..0000000000 --- a/Lang/PureBasic/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/The-Name-Game b/Lang/PureBasic/The-Name-Game new file mode 120000 index 0000000000..50ae0fd1b6 --- /dev/null +++ b/Lang/PureBasic/The-Name-Game @@ -0,0 +1 @@ +../../Task/The-Name-Game/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Twos-complement b/Lang/PureBasic/Twos-complement new file mode 120000 index 0000000000..dfe56459f4 --- /dev/null +++ b/Lang/PureBasic/Twos-complement @@ -0,0 +1 @@ +../../Task/Twos-complement/PureBasic \ No newline at end of file diff --git a/Lang/Python/Bioinformatics-base-count b/Lang/Python/Bioinformatics-base-count deleted file mode 120000 index 7f8a0873e8..0000000000 --- a/Lang/Python/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Python \ No newline at end of file diff --git a/Lang/Python/Compile-time-calculation b/Lang/Python/Compile-time-calculation new file mode 120000 index 0000000000..33879ac69d --- /dev/null +++ b/Lang/Python/Compile-time-calculation @@ -0,0 +1 @@ +../../Task/Compile-time-calculation/Python \ No newline at end of file diff --git a/Lang/Python/Constrained-genericity b/Lang/Python/Constrained-genericity new file mode 120000 index 0000000000..3ac238c57a --- /dev/null +++ b/Lang/Python/Constrained-genericity @@ -0,0 +1 @@ +../../Task/Constrained-genericity/Python \ No newline at end of file diff --git a/Lang/Python/Dominoes b/Lang/Python/Dominoes new file mode 120000 index 0000000000..648f074afc --- /dev/null +++ b/Lang/Python/Dominoes @@ -0,0 +1 @@ +../../Task/Dominoes/Python \ No newline at end of file diff --git a/Lang/Python/Erd-s-Selfridge-categorization-of-primes b/Lang/Python/Erd-s-Selfridge-categorization-of-primes new file mode 120000 index 0000000000..fd2fdbcb3f --- /dev/null +++ b/Lang/Python/Erd-s-Selfridge-categorization-of-primes @@ -0,0 +1 @@ +../../Task/Erd-s-Selfridge-categorization-of-primes/Python \ No newline at end of file diff --git a/Lang/Python/Execute-Brain- b/Lang/Python/Execute-Brain- new file mode 120000 index 0000000000..ad83d880d6 --- /dev/null +++ b/Lang/Python/Execute-Brain- @@ -0,0 +1 @@ +../../Task/Execute-Brain-/Python \ No newline at end of file diff --git a/Lang/Python/Im-a-software-engineer-get-me-out-of-here b/Lang/Python/Im-a-software-engineer-get-me-out-of-here new file mode 120000 index 0000000000..d238ff00d2 --- /dev/null +++ b/Lang/Python/Im-a-software-engineer-get-me-out-of-here @@ -0,0 +1 @@ +../../Task/Im-a-software-engineer-get-me-out-of-here/Python \ No newline at end of file diff --git a/Lang/Python/Isograms-and-heterograms b/Lang/Python/Isograms-and-heterograms new file mode 120000 index 0000000000..f277330152 --- /dev/null +++ b/Lang/Python/Isograms-and-heterograms @@ -0,0 +1 @@ +../../Task/Isograms-and-heterograms/Python \ No newline at end of file diff --git a/Lang/Python/Meissel-Mertens-constant b/Lang/Python/Meissel-Mertens-constant deleted file mode 120000 index 04fd530b92..0000000000 --- a/Lang/Python/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/Python \ No newline at end of file diff --git a/Lang/Python/Miller-Rabin-primality-test b/Lang/Python/Miller-Rabin-primality-test deleted file mode 120000 index 4ec507954a..0000000000 --- a/Lang/Python/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Python \ No newline at end of file diff --git a/Lang/Python/Multi-base-primes b/Lang/Python/Multi-base-primes new file mode 120000 index 0000000000..6190bc944f --- /dev/null +++ b/Lang/Python/Multi-base-primes @@ -0,0 +1 @@ +../../Task/Multi-base-primes/Python \ No newline at end of file diff --git a/Lang/Python/Numbers-which-are-not-the-sum-of-distinct-squares b/Lang/Python/Numbers-which-are-not-the-sum-of-distinct-squares new file mode 120000 index 0000000000..3a47a71cf2 --- /dev/null +++ b/Lang/Python/Numbers-which-are-not-the-sum-of-distinct-squares @@ -0,0 +1 @@ +../../Task/Numbers-which-are-not-the-sum-of-distinct-squares/Python \ No newline at end of file diff --git a/Lang/Python/P-Adic-square-roots b/Lang/Python/P-Adic-square-roots new file mode 120000 index 0000000000..3ecdf0d3ca --- /dev/null +++ b/Lang/Python/P-Adic-square-roots @@ -0,0 +1 @@ +../../Task/P-Adic-square-roots/Python \ No newline at end of file diff --git a/Lang/Python/Parametric-polymorphism b/Lang/Python/Parametric-polymorphism new file mode 120000 index 0000000000..b6d5668cdf --- /dev/null +++ b/Lang/Python/Parametric-polymorphism @@ -0,0 +1 @@ +../../Task/Parametric-polymorphism/Python \ No newline at end of file diff --git a/Lang/Python/Peripheral-drift-illusion b/Lang/Python/Peripheral-drift-illusion new file mode 120000 index 0000000000..4e0e7d7c77 --- /dev/null +++ b/Lang/Python/Peripheral-drift-illusion @@ -0,0 +1 @@ +../../Task/Peripheral-drift-illusion/Python \ No newline at end of file diff --git a/Lang/Python/Prime-numbers-whose-neighboring-pairs-are-tetraprimes b/Lang/Python/Prime-numbers-whose-neighboring-pairs-are-tetraprimes new file mode 120000 index 0000000000..9997b73880 --- /dev/null +++ b/Lang/Python/Prime-numbers-whose-neighboring-pairs-are-tetraprimes @@ -0,0 +1 @@ +../../Task/Prime-numbers-whose-neighboring-pairs-are-tetraprimes/Python \ No newline at end of file diff --git a/Lang/Python/Quaternion-type b/Lang/Python/Quaternion-type deleted file mode 120000 index 4219e34b85..0000000000 --- a/Lang/Python/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Python \ No newline at end of file diff --git a/Lang/Python/Ramanujan-primes-twins b/Lang/Python/Ramanujan-primes-twins new file mode 120000 index 0000000000..8b76bc210b --- /dev/null +++ b/Lang/Python/Ramanujan-primes-twins @@ -0,0 +1 @@ +../../Task/Ramanujan-primes-twins/Python \ No newline at end of file diff --git a/Lang/Python/Rhonda-numbers b/Lang/Python/Rhonda-numbers new file mode 120000 index 0000000000..26cc73526d --- /dev/null +++ b/Lang/Python/Rhonda-numbers @@ -0,0 +1 @@ +../../Task/Rhonda-numbers/Python \ No newline at end of file diff --git a/Lang/Python/Ruth-Aaron-numbers b/Lang/Python/Ruth-Aaron-numbers new file mode 120000 index 0000000000..933b3d03bc --- /dev/null +++ b/Lang/Python/Ruth-Aaron-numbers @@ -0,0 +1 @@ +../../Task/Ruth-Aaron-numbers/Python \ No newline at end of file diff --git a/Lang/Python/Smarandache-Wellin-primes b/Lang/Python/Smarandache-Wellin-primes new file mode 120000 index 0000000000..87eea97b5c --- /dev/null +++ b/Lang/Python/Smarandache-Wellin-primes @@ -0,0 +1 @@ +../../Task/Smarandache-Wellin-primes/Python \ No newline at end of file diff --git a/Lang/Python/Sorting-Algorithms-Circle-Sort b/Lang/Python/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 3e7a80b339..0000000000 --- a/Lang/Python/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Python \ No newline at end of file diff --git a/Lang/Python/Square-form-factorization b/Lang/Python/Square-form-factorization new file mode 120000 index 0000000000..38da301a59 --- /dev/null +++ b/Lang/Python/Square-form-factorization @@ -0,0 +1 @@ +../../Task/Square-form-factorization/Python \ No newline at end of file diff --git a/Lang/Python/Start-from-a-main-routine b/Lang/Python/Start-from-a-main-routine new file mode 120000 index 0000000000..e9c472aaa4 --- /dev/null +++ b/Lang/Python/Start-from-a-main-routine @@ -0,0 +1 @@ +../../Task/Start-from-a-main-routine/Python \ No newline at end of file diff --git a/Lang/Python/Untouchable-numbers b/Lang/Python/Untouchable-numbers new file mode 120000 index 0000000000..c4bd0ba9e1 --- /dev/null +++ b/Lang/Python/Untouchable-numbers @@ -0,0 +1 @@ +../../Task/Untouchable-numbers/Python \ No newline at end of file diff --git a/Lang/Python/Wasteful-equidigital-and-frugal-numbers b/Lang/Python/Wasteful-equidigital-and-frugal-numbers new file mode 120000 index 0000000000..c89de12312 --- /dev/null +++ b/Lang/Python/Wasteful-equidigital-and-frugal-numbers @@ -0,0 +1 @@ +../../Task/Wasteful-equidigital-and-frugal-numbers/Python \ No newline at end of file diff --git a/Lang/Q/00-LANG.txt b/Lang/Q/00-LANG.txt index 761de14eda..1cf9ed3990 100644 --- a/Lang/Q/00-LANG.txt +++ b/Lang/Q/00-LANG.txt @@ -1,5 +1,6 @@ -{{language}}Q is another vector language (in the family of [[APL]] [[J]] [[K]] and [[Nial]]) +{{language}} +Q is another vector language (in the family of [[APL]], [[J]], [[K]], and [[Nial]]) -There is a totally unrelated language called Q [http://q-lang.sourceforge.net/ here]. (It is an equational programming language) +There is a totally unrelated language called Q [http://q-lang.sourceforge.net/ here]. (It is an equational programming language.) -Q [https://code.kx.com/trac/wiki/QforMortals docs](anonymous/anonymous) \ No newline at end of file +Documentation: [https://code.kx.com/q4m3/ Q for Mortals] An introduction to q programming \ No newline at end of file diff --git a/Lang/Q/Euler-method b/Lang/Q/Euler-method new file mode 120000 index 0000000000..093ad80e13 --- /dev/null +++ b/Lang/Q/Euler-method @@ -0,0 +1 @@ +../../Task/Euler-method/Q \ No newline at end of file diff --git a/Lang/QB64/Averages-Mean-angle b/Lang/QB64/Averages-Mean-angle new file mode 120000 index 0000000000..aab53ced3a --- /dev/null +++ b/Lang/QB64/Averages-Mean-angle @@ -0,0 +1 @@ +../../Task/Averages-Mean-angle/QB64 \ No newline at end of file diff --git a/Lang/QB64/Blum-integer b/Lang/QB64/Blum-integer new file mode 120000 index 0000000000..6d55cd1ae1 --- /dev/null +++ b/Lang/QB64/Blum-integer @@ -0,0 +1 @@ +../../Task/Blum-integer/QB64 \ No newline at end of file diff --git a/Lang/QB64/Determine-if-a-string-has-all-the-same-characters b/Lang/QB64/Determine-if-a-string-has-all-the-same-characters new file mode 120000 index 0000000000..e5cb75941f --- /dev/null +++ b/Lang/QB64/Determine-if-a-string-has-all-the-same-characters @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-has-all-the-same-characters/QB64 \ No newline at end of file diff --git a/Lang/QB64/Fibonacci-n-step-number-sequences b/Lang/QB64/Fibonacci-n-step-number-sequences new file mode 120000 index 0000000000..dbe9d19cad --- /dev/null +++ b/Lang/QB64/Fibonacci-n-step-number-sequences @@ -0,0 +1 @@ +../../Task/Fibonacci-n-step-number-sequences/QB64 \ No newline at end of file diff --git a/Lang/QB64/Hello-world-Newline-omission b/Lang/QB64/Hello-world-Newline-omission new file mode 120000 index 0000000000..355c4d1286 --- /dev/null +++ b/Lang/QB64/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/QB64 \ No newline at end of file diff --git a/Lang/QB64/Hofstadter-Q-sequence b/Lang/QB64/Hofstadter-Q-sequence new file mode 120000 index 0000000000..636c2bd5e2 --- /dev/null +++ b/Lang/QB64/Hofstadter-Q-sequence @@ -0,0 +1 @@ +../../Task/Hofstadter-Q-sequence/QB64 \ No newline at end of file diff --git a/Lang/QB64/Intersecting-number-wheels b/Lang/QB64/Intersecting-number-wheels new file mode 120000 index 0000000000..226a608551 --- /dev/null +++ b/Lang/QB64/Intersecting-number-wheels @@ -0,0 +1 @@ +../../Task/Intersecting-number-wheels/QB64 \ No newline at end of file diff --git a/Lang/QB64/Mayan-calendar b/Lang/QB64/Mayan-calendar new file mode 120000 index 0000000000..13deaa3e8a --- /dev/null +++ b/Lang/QB64/Mayan-calendar @@ -0,0 +1 @@ +../../Task/Mayan-calendar/QB64 \ No newline at end of file diff --git a/Lang/QB64/Multiple-regression b/Lang/QB64/Multiple-regression new file mode 120000 index 0000000000..f5a655fb07 --- /dev/null +++ b/Lang/QB64/Multiple-regression @@ -0,0 +1 @@ +../../Task/Multiple-regression/QB64 \ No newline at end of file diff --git a/Lang/QB64/Perfect-numbers b/Lang/QB64/Perfect-numbers new file mode 120000 index 0000000000..313898bfff --- /dev/null +++ b/Lang/QB64/Perfect-numbers @@ -0,0 +1 @@ +../../Task/Perfect-numbers/QB64 \ No newline at end of file diff --git a/Lang/QB64/Price-fraction b/Lang/QB64/Price-fraction new file mode 120000 index 0000000000..b2a7164220 --- /dev/null +++ b/Lang/QB64/Price-fraction @@ -0,0 +1 @@ +../../Task/Price-fraction/QB64 \ No newline at end of file diff --git a/Lang/QB64/Safe-primes-and-unsafe-primes b/Lang/QB64/Safe-primes-and-unsafe-primes new file mode 120000 index 0000000000..2fe9c13027 --- /dev/null +++ b/Lang/QB64/Safe-primes-and-unsafe-primes @@ -0,0 +1 @@ +../../Task/Safe-primes-and-unsafe-primes/QB64 \ No newline at end of file diff --git a/Lang/QB64/Sum-of-a-series b/Lang/QB64/Sum-of-a-series new file mode 120000 index 0000000000..67ad320160 --- /dev/null +++ b/Lang/QB64/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/QB64 \ No newline at end of file diff --git a/Lang/QB64/Tau-number b/Lang/QB64/Tau-number new file mode 120000 index 0000000000..0690f3645f --- /dev/null +++ b/Lang/QB64/Tau-number @@ -0,0 +1 @@ +../../Task/Tau-number/QB64 \ No newline at end of file diff --git a/Lang/QB64/Trabb-Pardo-Knuth-algorithm b/Lang/QB64/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..bd61960412 --- /dev/null +++ b/Lang/QB64/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/QB64 \ No newline at end of file diff --git a/Lang/QB64/Twos-complement b/Lang/QB64/Twos-complement new file mode 120000 index 0000000000..fd393f8160 --- /dev/null +++ b/Lang/QB64/Twos-complement @@ -0,0 +1 @@ +../../Task/Twos-complement/QB64 \ No newline at end of file diff --git a/Lang/QB64/Web-scraping b/Lang/QB64/Web-scraping new file mode 120000 index 0000000000..bdf604fdc3 --- /dev/null +++ b/Lang/QB64/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/QB64 \ No newline at end of file diff --git a/Lang/QBasic/00-LANG.txt b/Lang/QBasic/00-LANG.txt index 4ab26db45d..66c4f1d834 100644 --- a/Lang/QBasic/00-LANG.txt +++ b/Lang/QBasic/00-LANG.txt @@ -1,3 +1,4 @@ {{language}} +{{implementation|BASIC}} QBasic is a BASIC that was written by Microsoft and normally executes under Windows. \ No newline at end of file diff --git a/Lang/QBasic/15-puzzle-game b/Lang/QBasic/15-puzzle-game new file mode 120000 index 0000000000..4cdffaba3f --- /dev/null +++ b/Lang/QBasic/15-puzzle-game @@ -0,0 +1 @@ +../../Task/15-puzzle-game/QBasic \ No newline at end of file diff --git a/Lang/QBasic/ASCII-art-diagram-converter b/Lang/QBasic/ASCII-art-diagram-converter new file mode 120000 index 0000000000..75bc551903 --- /dev/null +++ b/Lang/QBasic/ASCII-art-diagram-converter @@ -0,0 +1 @@ +../../Task/ASCII-art-diagram-converter/QBasic \ No newline at end of file diff --git a/Lang/QBasic/Associative-array-Merging b/Lang/QBasic/Associative-array-Merging new file mode 120000 index 0000000000..7cdfcc0848 --- /dev/null +++ b/Lang/QBasic/Associative-array-Merging @@ -0,0 +1 @@ +../../Task/Associative-array-Merging/QBasic \ No newline at end of file diff --git a/Lang/QBasic/Averages-Mean-angle b/Lang/QBasic/Averages-Mean-angle new file mode 120000 index 0000000000..499df28583 --- /dev/null +++ b/Lang/QBasic/Averages-Mean-angle @@ -0,0 +1 @@ +../../Task/Averages-Mean-angle/QBasic \ No newline at end of file diff --git a/Lang/QBasic/Determine-sentence-type b/Lang/QBasic/Determine-sentence-type new file mode 120000 index 0000000000..5f23645126 --- /dev/null +++ b/Lang/QBasic/Determine-sentence-type @@ -0,0 +1 @@ +../../Task/Determine-sentence-type/QBasic \ No newline at end of file diff --git a/Lang/QBasic/Dinesmans-multiple-dwelling-problem b/Lang/QBasic/Dinesmans-multiple-dwelling-problem deleted file mode 120000 index 58659e8fb4..0000000000 --- a/Lang/QBasic/Dinesmans-multiple-dwelling-problem +++ /dev/null @@ -1 +0,0 @@ -../../Task/Dinesmans-multiple-dwelling-problem/QBasic \ No newline at end of file diff --git a/Lang/QBasic/Display-a-linear-combination b/Lang/QBasic/Display-a-linear-combination new file mode 120000 index 0000000000..e9d158c960 --- /dev/null +++ b/Lang/QBasic/Display-a-linear-combination @@ -0,0 +1 @@ +../../Task/Display-a-linear-combination/QBasic \ No newline at end of file diff --git a/Lang/QBasic/Diversity-prediction-theorem b/Lang/QBasic/Diversity-prediction-theorem new file mode 120000 index 0000000000..01e16fde09 --- /dev/null +++ b/Lang/QBasic/Diversity-prediction-theorem @@ -0,0 +1 @@ +../../Task/Diversity-prediction-theorem/QBasic \ No newline at end of file diff --git a/Lang/QBasic/Evaluate-binomial-coefficients b/Lang/QBasic/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..86b00c5e75 --- /dev/null +++ b/Lang/QBasic/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/QBasic \ No newline at end of file diff --git a/Lang/QBasic/Fibonacci-n-step-number-sequences b/Lang/QBasic/Fibonacci-n-step-number-sequences new file mode 120000 index 0000000000..77136c7137 --- /dev/null +++ b/Lang/QBasic/Fibonacci-n-step-number-sequences @@ -0,0 +1 @@ +../../Task/Fibonacci-n-step-number-sequences/QBasic \ No newline at end of file diff --git a/Lang/QBasic/Horizontal-sundial-calculations b/Lang/QBasic/Horizontal-sundial-calculations new file mode 120000 index 0000000000..48a7ed5986 --- /dev/null +++ b/Lang/QBasic/Horizontal-sundial-calculations @@ -0,0 +1 @@ +../../Task/Horizontal-sundial-calculations/QBasic \ No newline at end of file diff --git a/Lang/QBasic/Jensens-Device b/Lang/QBasic/Jensens-Device new file mode 120000 index 0000000000..199e4d7809 --- /dev/null +++ b/Lang/QBasic/Jensens-Device @@ -0,0 +1 @@ +../../Task/Jensens-Device/QBasic \ No newline at end of file diff --git a/Lang/QBasic/Leonardo-numbers b/Lang/QBasic/Leonardo-numbers new file mode 120000 index 0000000000..d0e3199c8a --- /dev/null +++ b/Lang/QBasic/Leonardo-numbers @@ -0,0 +1 @@ +../../Task/Leonardo-numbers/QBasic \ No newline at end of file diff --git a/Lang/QBasic/Loops-Continue b/Lang/QBasic/Loops-Continue new file mode 120000 index 0000000000..eeea4ac585 --- /dev/null +++ b/Lang/QBasic/Loops-Continue @@ -0,0 +1 @@ +../../Task/Loops-Continue/QBasic \ No newline at end of file diff --git a/Lang/QBasic/Map-range b/Lang/QBasic/Map-range new file mode 120000 index 0000000000..be9705365d --- /dev/null +++ b/Lang/QBasic/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/QBasic \ No newline at end of file diff --git a/Lang/QBasic/Nested-templated-data b/Lang/QBasic/Nested-templated-data new file mode 120000 index 0000000000..ddf5a87c1b --- /dev/null +++ b/Lang/QBasic/Nested-templated-data @@ -0,0 +1 @@ +../../Task/Nested-templated-data/QBasic \ No newline at end of file diff --git a/Lang/QBasic/Numbers-with-equal-rises-and-falls b/Lang/QBasic/Numbers-with-equal-rises-and-falls new file mode 120000 index 0000000000..8e3ab8bbe9 --- /dev/null +++ b/Lang/QBasic/Numbers-with-equal-rises-and-falls @@ -0,0 +1 @@ +../../Task/Numbers-with-equal-rises-and-falls/QBasic \ No newline at end of file diff --git a/Lang/QBasic/Phrase-reversals b/Lang/QBasic/Phrase-reversals new file mode 120000 index 0000000000..7f3671bcb7 --- /dev/null +++ b/Lang/QBasic/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/QBasic \ No newline at end of file diff --git a/Lang/QBasic/Pinstripe-Display b/Lang/QBasic/Pinstripe-Display new file mode 120000 index 0000000000..f245a0ccf2 --- /dev/null +++ b/Lang/QBasic/Pinstripe-Display @@ -0,0 +1 @@ +../../Task/Pinstripe-Display/QBasic \ No newline at end of file diff --git a/Lang/QBasic/Ramer-Douglas-Peucker-line-simplification b/Lang/QBasic/Ramer-Douglas-Peucker-line-simplification new file mode 120000 index 0000000000..574b7acaf0 --- /dev/null +++ b/Lang/QBasic/Ramer-Douglas-Peucker-line-simplification @@ -0,0 +1 @@ +../../Task/Ramer-Douglas-Peucker-line-simplification/QBasic \ No newline at end of file diff --git a/Lang/QBasic/Repeat-a-string b/Lang/QBasic/Repeat-a-string deleted file mode 120000 index 4c99978a73..0000000000 --- a/Lang/QBasic/Repeat-a-string +++ /dev/null @@ -1 +0,0 @@ -../../Task/Repeat-a-string/QBasic \ No newline at end of file diff --git a/Lang/QBasic/Rot-13 b/Lang/QBasic/Rot-13 new file mode 120000 index 0000000000..8ebe820c50 --- /dev/null +++ b/Lang/QBasic/Rot-13 @@ -0,0 +1 @@ +../../Task/Rot-13/QBasic \ No newline at end of file diff --git a/Lang/QBasic/Soundex b/Lang/QBasic/Soundex new file mode 120000 index 0000000000..2d904fe964 --- /dev/null +++ b/Lang/QBasic/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/QBasic \ No newline at end of file diff --git a/Lang/QBasic/Split-a-character-string-based-on-change-of-character b/Lang/QBasic/Split-a-character-string-based-on-change-of-character new file mode 120000 index 0000000000..5e5ffa8a44 --- /dev/null +++ b/Lang/QBasic/Split-a-character-string-based-on-change-of-character @@ -0,0 +1 @@ +../../Task/Split-a-character-string-based-on-change-of-character/QBasic \ No newline at end of file diff --git a/Lang/QBasic/Statistics-Normal-distribution b/Lang/QBasic/Statistics-Normal-distribution new file mode 120000 index 0000000000..9e5e8f24f2 --- /dev/null +++ b/Lang/QBasic/Statistics-Normal-distribution @@ -0,0 +1 @@ +../../Task/Statistics-Normal-distribution/QBasic \ No newline at end of file diff --git a/Lang/QBasic/The-Name-Game b/Lang/QBasic/The-Name-Game new file mode 120000 index 0000000000..f7f2e9b30b --- /dev/null +++ b/Lang/QBasic/The-Name-Game @@ -0,0 +1 @@ +../../Task/The-Name-Game/QBasic \ No newline at end of file diff --git a/Lang/QBasic/Vector b/Lang/QBasic/Vector new file mode 120000 index 0000000000..7bbf551f69 --- /dev/null +++ b/Lang/QBasic/Vector @@ -0,0 +1 @@ +../../Task/Vector/QBasic \ No newline at end of file diff --git a/Lang/Quackery/00-LANG.txt b/Lang/Quackery/00-LANG.txt index 498188387d..b70d597b46 100644 --- a/Lang/Quackery/00-LANG.txt +++ b/Lang/Quackery/00-LANG.txt @@ -1,9 +1,9 @@ {{language|Quackery}} {{language programming paradigm|Concatenative}} {{language programming paradigm|Imperative}} -Quackery is an open-source, lightweight, entry-level concatenative language for educational and recreational programming. +Quackery is an open-source, lightweight, entry-level concatenative language for educational and recreational programming, and an extensible compiler for a hypothetical processor, the Quackery Engine. -It is coded as a Python 3 function in under 48k of Pythonscript, about half of which is a string of Quackery code. +It is coded as a Python 3 function in about 50k of Pythonscript, about half of which is a string of Quackery code. The Quackery GitHub repository, which includes the Quackery manual "The Book of Quackery" as a pdf, is at [https://github.com/GordonCharlton/Quackery github.com/GordonCharlton/Quackery]. @@ -19,7 +19,7 @@ To compile this definition of quackery, build takes a The words is, [, and ] are builders; they can be found in the builders dictionary, which extends the functionality of build beyond building a flat nest for do to evaluate. is takes the item that do most recently added to its output nest, and adds it to the names dictionary, along with the string that follows it, "quackery" as its name. The syntax of Quackery is; words and numbers are sequences of printable characters, separated by spaces and carriage returns unless a builder treats the text that follows it otherwise. The builder builds is equivalent to is for adding new words and behaviours to the builders dictionary. -Evaluation of a nest proceeds from left to right unless a control flow operator redirects it. done causes doto stop evaluating a nest and return to the nest that pointed to it immediately, rather than at the end of the nest. again restarts the evaluation of that nest, non-recursively. The word recurse does it recursively. if and iff conditionally (depending on the item on the top of the Quackery stack) skip over the next one and two items in the nest respectively. else skips over one item, unconditionally. As with the other provided control flow operators, these words are nests, not operators, that make use of the "meta-control flow" operators, which grant the behaviours described above to words that use them. (They modify items on the return stack, rather than acting on the Quackery engine's various pointers registers directly, so their changes are enacted upon exiting the nest that called them.) +Evaluation of a nest proceeds from left to right unless a control flow operator redirects it. done causes doto stop evaluating a nest and return to the nest that pointed to it immediately, rather than at the end of the nest. again restarts the evaluation of that nest, non-recursively. The word recurse does it recursively. if and iff conditionally (depending on the item on the top of the Quackery stack) skip over the next one and two items in the nest respectively. else skips over one item, unconditionally. As with the other provided control flow operators, these words are nests, not operators, that make use of the "meta-control flow" operators, which grant the behaviours described above to words that use them. (They modify items on the return stack, rather than acting on the Quackery engine's various registers directly, so their changes are enacted upon exiting the nest that called them.) There are no variables in Quackery. Instead, there are stack management words to rearrange the uppermost items on the Quackery stack as required, and nameable ancillary stacks that fulfil the roles of variables. @@ -27,8 +27,28 @@ Everything is code except when it is data. When do does a number, t Conceptually, the Quackery engine is a stack based processor which does not have direct access to physical memory but has a memory management co-processor that intermediates, that takes care of the nests and bignums, provides pointers to the Quackery engine CPU on request, and garbage collects continuously. -Quackery is not intended to be a super-fast enterprise-level language; it is intended as a fun programming project straight out of a textbook. (The textbook is included in the download.) +Quackery is not intended to be a super-fast enterprise-level language; it is intended as an exploration of a novel architecture, and a fun programming project straight out of a textbook. (The textbook is included in the download.) -If your language supports bignums, first-class functions and dynamic arrays of bignums, functions and dynamic arrays, and has automatic garbage collection, and if you can code depth-first traversal of a tree you can implement Quackery in your preferred language with reasonable ease, and modify it as you please. +Why not try your hand at one of the [[Tasks not implemented in Quackery]]. -Or try your hand at one of the [[Tasks not implemented in Quackery]]. \ No newline at end of file +== Selected Quackery Examples == + +Rosetta Code has hundreds of Quackery examples. Here’s a curated set that showcases some of Quackery's strengths: + +* [[99 bottles of beer#Quackery|99 bottles of beer]] Shows simple, readable control flow and output. +* [[Gosper's hack#Quackery|Gosper's hack]] A nifty one-liner. +* [[Temperature conversion#Quackery|Temperature conversion]] Co-operative brevity. +* [[Balanced brackets#Quackery|Balanced brackets]] Demonstrates natural stack use for classic problems. +* [[Loops/Increment loop index within loop body#Quackery|Increment loop index within loop body]] You want a loop that's indexed ''and'' indefinite? Here's how. +* [[Quine#Quackery|Quine]] Illustrates code-as-data and quotation handling. +* [[Bacon cipher#Quackery|Bacon cipher]] Highlights clear text manipulation with minimal code. +* [[Permutations#Quackery|Permutations]] Uses recursion and stack shuffling expressively. +* [[Sorting algorithms/Insertion sort#Quackery|Insertion sort]] Demonstrates some built-in higher-order functions. +* [[Higher-order functions#Quackery|Higher-order functions]] Defining and using fold, map, and filter. +* [[Conway's Game of Life#Quackery|Conway's Game of Life]] Handles structured simulation with clarity. +* [[Execute Brain****#Quackery|Brainf*** interpreter]] Demonstrates interpreter-building and extensibility. +* [[Dinesman's multiple-dwelling problem#Quackery|Dinesman's multiple-dwelling problem]] Crafting a Domain Specific Language. + +== The Task that Nearly Broke the Author == + +* [[Zeckendorf arithmetic#Quackery|Zeckendorf arithmetic]] Forget everything you thought you knew about arithmetic… \ No newline at end of file diff --git a/Lang/Quackery/4-rings-or-4-squares-puzzle b/Lang/Quackery/4-rings-or-4-squares-puzzle new file mode 120000 index 0000000000..786cc93b7f --- /dev/null +++ b/Lang/Quackery/4-rings-or-4-squares-puzzle @@ -0,0 +1 @@ +../../Task/4-rings-or-4-squares-puzzle/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Balanced-ternary b/Lang/Quackery/Balanced-ternary new file mode 120000 index 0000000000..c02c0b6483 --- /dev/null +++ b/Lang/Quackery/Balanced-ternary @@ -0,0 +1 @@ +../../Task/Balanced-ternary/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Benfords-law b/Lang/Quackery/Benfords-law new file mode 120000 index 0000000000..83c8fdffec --- /dev/null +++ b/Lang/Quackery/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Bioinformatics-base-count b/Lang/Quackery/Bioinformatics-base-count deleted file mode 120000 index 65cab8d1ed..0000000000 --- a/Lang/Quackery/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Chowla-numbers b/Lang/Quackery/Chowla-numbers new file mode 120000 index 0000000000..017749c553 --- /dev/null +++ b/Lang/Quackery/Chowla-numbers @@ -0,0 +1 @@ +../../Task/Chowla-numbers/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Combinations-and-permutations b/Lang/Quackery/Combinations-and-permutations new file mode 120000 index 0000000000..fc6f331f4d --- /dev/null +++ b/Lang/Quackery/Combinations-and-permutations @@ -0,0 +1 @@ +../../Task/Combinations-and-permutations/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Cuban-primes b/Lang/Quackery/Cuban-primes new file mode 120000 index 0000000000..8c512d4853 --- /dev/null +++ b/Lang/Quackery/Cuban-primes @@ -0,0 +1 @@ +../../Task/Cuban-primes/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Dice-game-probabilities b/Lang/Quackery/Dice-game-probabilities new file mode 120000 index 0000000000..87d28dc799 --- /dev/null +++ b/Lang/Quackery/Dice-game-probabilities @@ -0,0 +1 @@ +../../Task/Dice-game-probabilities/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Dinesmans-multiple-dwelling-problem b/Lang/Quackery/Dinesmans-multiple-dwelling-problem new file mode 120000 index 0000000000..2061e87b20 --- /dev/null +++ b/Lang/Quackery/Dinesmans-multiple-dwelling-problem @@ -0,0 +1 @@ +../../Task/Dinesmans-multiple-dwelling-problem/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Distribution-of-0-digits-in-factorial-series b/Lang/Quackery/Distribution-of-0-digits-in-factorial-series new file mode 120000 index 0000000000..8627f3195b --- /dev/null +++ b/Lang/Quackery/Distribution-of-0-digits-in-factorial-series @@ -0,0 +1 @@ +../../Task/Distribution-of-0-digits-in-factorial-series/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Doomsday-rule b/Lang/Quackery/Doomsday-rule new file mode 120000 index 0000000000..f3df2f0b9b --- /dev/null +++ b/Lang/Quackery/Doomsday-rule @@ -0,0 +1 @@ +../../Task/Doomsday-rule/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Dutch-national-flag-problem b/Lang/Quackery/Dutch-national-flag-problem new file mode 120000 index 0000000000..133393cf2e --- /dev/null +++ b/Lang/Quackery/Dutch-national-flag-problem @@ -0,0 +1 @@ +../../Task/Dutch-national-flag-problem/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Execute-Computer-Zero b/Lang/Quackery/Execute-Computer-Zero new file mode 120000 index 0000000000..bffceead11 --- /dev/null +++ b/Lang/Quackery/Execute-Computer-Zero @@ -0,0 +1 @@ +../../Task/Execute-Computer-Zero/Quackery \ No newline at end of file diff --git a/Lang/Quackery/First-class-functions-Use-numbers-analogously b/Lang/Quackery/First-class-functions-Use-numbers-analogously new file mode 120000 index 0000000000..c8416f6780 --- /dev/null +++ b/Lang/Quackery/First-class-functions-Use-numbers-analogously @@ -0,0 +1 @@ +../../Task/First-class-functions-Use-numbers-analogously/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Flipping-bits-game b/Lang/Quackery/Flipping-bits-game new file mode 120000 index 0000000000..fd3aa38458 --- /dev/null +++ b/Lang/Quackery/Flipping-bits-game @@ -0,0 +1 @@ +../../Task/Flipping-bits-game/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Golden-ratio-Convergence b/Lang/Quackery/Golden-ratio-Convergence new file mode 120000 index 0000000000..177994dc3e --- /dev/null +++ b/Lang/Quackery/Golden-ratio-Convergence @@ -0,0 +1 @@ +../../Task/Golden-ratio-Convergence/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Menu b/Lang/Quackery/Menu new file mode 120000 index 0000000000..07087595bc --- /dev/null +++ b/Lang/Quackery/Menu @@ -0,0 +1 @@ +../../Task/Menu/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Miller-Rabin-primality-test b/Lang/Quackery/Miller-Rabin-primality-test deleted file mode 120000 index d8e4ec56b5..0000000000 --- a/Lang/Quackery/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Minimum-multiple-of-m-where-digital-sum-equals-m b/Lang/Quackery/Minimum-multiple-of-m-where-digital-sum-equals-m new file mode 120000 index 0000000000..ddb9ece049 --- /dev/null +++ b/Lang/Quackery/Minimum-multiple-of-m-where-digital-sum-equals-m @@ -0,0 +1 @@ +../../Task/Minimum-multiple-of-m-where-digital-sum-equals-m/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Old-lady-swallowed-a-fly b/Lang/Quackery/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..0d6823a2fd --- /dev/null +++ b/Lang/Quackery/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Password-generator b/Lang/Quackery/Password-generator new file mode 120000 index 0000000000..8d0efee13f --- /dev/null +++ b/Lang/Quackery/Password-generator @@ -0,0 +1 @@ +../../Task/Password-generator/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Pseudo-random-numbers-Xorshift-star b/Lang/Quackery/Pseudo-random-numbers-Xorshift-star new file mode 120000 index 0000000000..0d802ea7eb --- /dev/null +++ b/Lang/Quackery/Pseudo-random-numbers-Xorshift-star @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-Xorshift-star/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Sleep b/Lang/Quackery/Sleep new file mode 120000 index 0000000000..7cd0464b5f --- /dev/null +++ b/Lang/Quackery/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Solve-the-no-connection-puzzle b/Lang/Quackery/Solve-the-no-connection-puzzle new file mode 120000 index 0000000000..d37f201a93 --- /dev/null +++ b/Lang/Quackery/Solve-the-no-connection-puzzle @@ -0,0 +1 @@ +../../Task/Solve-the-no-connection-puzzle/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Sorting-Algorithms-Circle-Sort b/Lang/Quackery/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index e4abaee49d..0000000000 --- a/Lang/Quackery/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Square-free-integers b/Lang/Quackery/Square-free-integers new file mode 120000 index 0000000000..1d2a5a3f4e --- /dev/null +++ b/Lang/Quackery/Square-free-integers @@ -0,0 +1 @@ +../../Task/Square-free-integers/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Sum-of-elements-below-main-diagonal-of-matrix b/Lang/Quackery/Sum-of-elements-below-main-diagonal-of-matrix new file mode 120000 index 0000000000..1f9736ed88 --- /dev/null +++ b/Lang/Quackery/Sum-of-elements-below-main-diagonal-of-matrix @@ -0,0 +1 @@ +../../Task/Sum-of-elements-below-main-diagonal-of-matrix/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Two-bullet-roulette b/Lang/Quackery/Two-bullet-roulette new file mode 120000 index 0000000000..24f00326c1 --- /dev/null +++ b/Lang/Quackery/Two-bullet-roulette @@ -0,0 +1 @@ +../../Task/Two-bullet-roulette/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Ultra-useful-primes b/Lang/Quackery/Ultra-useful-primes new file mode 120000 index 0000000000..d6fc3551e1 --- /dev/null +++ b/Lang/Quackery/Ultra-useful-primes @@ -0,0 +1 @@ +../../Task/Ultra-useful-primes/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Universal-Turing-machine b/Lang/Quackery/Universal-Turing-machine new file mode 120000 index 0000000000..9346211d7e --- /dev/null +++ b/Lang/Quackery/Universal-Turing-machine @@ -0,0 +1 @@ +../../Task/Universal-Turing-machine/Quackery \ No newline at end of file diff --git a/Lang/QuickBASIC/AKS-test-for-primes b/Lang/QuickBASIC/AKS-test-for-primes new file mode 120000 index 0000000000..3fb1fc33c1 --- /dev/null +++ b/Lang/QuickBASIC/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/QuickBASIC \ No newline at end of file diff --git a/Lang/QuickBASIC/Abundant-odd-numbers b/Lang/QuickBASIC/Abundant-odd-numbers new file mode 120000 index 0000000000..baf10a6d8e --- /dev/null +++ b/Lang/QuickBASIC/Abundant-odd-numbers @@ -0,0 +1 @@ +../../Task/Abundant-odd-numbers/QuickBASIC \ No newline at end of file diff --git a/Lang/QuickBASIC/Arithmetic-numbers b/Lang/QuickBASIC/Arithmetic-numbers new file mode 120000 index 0000000000..e7076b98ae --- /dev/null +++ b/Lang/QuickBASIC/Arithmetic-numbers @@ -0,0 +1 @@ +../../Task/Arithmetic-numbers/QuickBASIC \ No newline at end of file diff --git a/Lang/QuickBASIC/Brazilian-numbers b/Lang/QuickBASIC/Brazilian-numbers new file mode 120000 index 0000000000..28cd1e19d8 --- /dev/null +++ b/Lang/QuickBASIC/Brazilian-numbers @@ -0,0 +1 @@ +../../Task/Brazilian-numbers/QuickBASIC \ No newline at end of file diff --git a/Lang/QuickBASIC/CUSIP b/Lang/QuickBASIC/CUSIP new file mode 120000 index 0000000000..cb4c762939 --- /dev/null +++ b/Lang/QuickBASIC/CUSIP @@ -0,0 +1 @@ +../../Task/CUSIP/QuickBASIC \ No newline at end of file diff --git a/Lang/QuickBASIC/Catalan-numbers b/Lang/QuickBASIC/Catalan-numbers new file mode 120000 index 0000000000..d84bc84044 --- /dev/null +++ b/Lang/QuickBASIC/Catalan-numbers @@ -0,0 +1 @@ +../../Task/Catalan-numbers/QuickBASIC \ No newline at end of file diff --git a/Lang/QuickBASIC/Cumulative-standard-deviation b/Lang/QuickBASIC/Cumulative-standard-deviation new file mode 120000 index 0000000000..969c73b001 --- /dev/null +++ b/Lang/QuickBASIC/Cumulative-standard-deviation @@ -0,0 +1 @@ +../../Task/Cumulative-standard-deviation/QuickBASIC \ No newline at end of file diff --git a/Lang/QuickBASIC/Determine-if-a-string-is-collapsible b/Lang/QuickBASIC/Determine-if-a-string-is-collapsible new file mode 120000 index 0000000000..d58e5303fd --- /dev/null +++ b/Lang/QuickBASIC/Determine-if-a-string-is-collapsible @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-collapsible/QuickBASIC \ No newline at end of file diff --git a/Lang/QuickBASIC/Dutch-national-flag-problem b/Lang/QuickBASIC/Dutch-national-flag-problem new file mode 120000 index 0000000000..f213f50587 --- /dev/null +++ b/Lang/QuickBASIC/Dutch-national-flag-problem @@ -0,0 +1 @@ +../../Task/Dutch-national-flag-problem/QuickBASIC \ No newline at end of file diff --git a/Lang/QuickBASIC/Equilibrium-index b/Lang/QuickBASIC/Equilibrium-index new file mode 120000 index 0000000000..d38cfdf137 --- /dev/null +++ b/Lang/QuickBASIC/Equilibrium-index @@ -0,0 +1 @@ +../../Task/Equilibrium-index/QuickBASIC \ No newline at end of file diff --git a/Lang/QuickBASIC/Ethiopian-multiplication b/Lang/QuickBASIC/Ethiopian-multiplication new file mode 120000 index 0000000000..8a8cc43790 --- /dev/null +++ b/Lang/QuickBASIC/Ethiopian-multiplication @@ -0,0 +1 @@ +../../Task/Ethiopian-multiplication/QuickBASIC \ No newline at end of file diff --git a/Lang/QuickBASIC/Function-definition b/Lang/QuickBASIC/Function-definition new file mode 120000 index 0000000000..0251617973 --- /dev/null +++ b/Lang/QuickBASIC/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/QuickBASIC \ No newline at end of file diff --git a/Lang/QuickBASIC/Gamma-function b/Lang/QuickBASIC/Gamma-function new file mode 120000 index 0000000000..6180b04d53 --- /dev/null +++ b/Lang/QuickBASIC/Gamma-function @@ -0,0 +1 @@ +../../Task/Gamma-function/QuickBASIC \ No newline at end of file diff --git a/Lang/QuickBASIC/Knights-tour b/Lang/QuickBASIC/Knights-tour new file mode 120000 index 0000000000..7c54f50c61 --- /dev/null +++ b/Lang/QuickBASIC/Knights-tour @@ -0,0 +1 @@ +../../Task/Knights-tour/QuickBASIC \ No newline at end of file diff --git a/Lang/QuickBASIC/Langtons-ant b/Lang/QuickBASIC/Langtons-ant new file mode 120000 index 0000000000..c0bbe5661c --- /dev/null +++ b/Lang/QuickBASIC/Langtons-ant @@ -0,0 +1 @@ +../../Task/Langtons-ant/QuickBASIC \ No newline at end of file diff --git a/Lang/QuickBASIC/M-bius-function b/Lang/QuickBASIC/M-bius-function new file mode 120000 index 0000000000..8f60fadaa9 --- /dev/null +++ b/Lang/QuickBASIC/M-bius-function @@ -0,0 +1 @@ +../../Task/M-bius-function/QuickBASIC \ No newline at end of file diff --git a/Lang/QuickBASIC/Monty-Hall-problem b/Lang/QuickBASIC/Monty-Hall-problem new file mode 120000 index 0000000000..5a322fee75 --- /dev/null +++ b/Lang/QuickBASIC/Monty-Hall-problem @@ -0,0 +1 @@ +../../Task/Monty-Hall-problem/QuickBASIC \ No newline at end of file diff --git a/Lang/QuickBASIC/Multifactorial b/Lang/QuickBASIC/Multifactorial new file mode 120000 index 0000000000..1f38ec7f4d --- /dev/null +++ b/Lang/QuickBASIC/Multifactorial @@ -0,0 +1 @@ +../../Task/Multifactorial/QuickBASIC \ No newline at end of file diff --git a/Lang/QuickBASIC/Nth-root b/Lang/QuickBASIC/Nth-root new file mode 120000 index 0000000000..db6d881466 --- /dev/null +++ b/Lang/QuickBASIC/Nth-root @@ -0,0 +1 @@ +../../Task/Nth-root/QuickBASIC \ No newline at end of file diff --git a/Lang/QuickBASIC/Prime-decomposition b/Lang/QuickBASIC/Prime-decomposition new file mode 120000 index 0000000000..1a12af5b95 --- /dev/null +++ b/Lang/QuickBASIC/Prime-decomposition @@ -0,0 +1 @@ +../../Task/Prime-decomposition/QuickBASIC \ No newline at end of file diff --git a/Lang/QuickBASIC/Random-numbers b/Lang/QuickBASIC/Random-numbers new file mode 120000 index 0000000000..8332f543fa --- /dev/null +++ b/Lang/QuickBASIC/Random-numbers @@ -0,0 +1 @@ +../../Task/Random-numbers/QuickBASIC \ No newline at end of file diff --git a/Lang/QuickBASIC/Repeat-a-string b/Lang/QuickBASIC/Repeat-a-string new file mode 120000 index 0000000000..f019b580c1 --- /dev/null +++ b/Lang/QuickBASIC/Repeat-a-string @@ -0,0 +1 @@ +../../Task/Repeat-a-string/QuickBASIC \ No newline at end of file diff --git a/Lang/QuickBASIC/Semiprime b/Lang/QuickBASIC/Semiprime new file mode 120000 index 0000000000..ded745aaee --- /dev/null +++ b/Lang/QuickBASIC/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/QuickBASIC \ No newline at end of file diff --git a/Lang/QuickBASIC/Shoelace-formula-for-polygonal-area b/Lang/QuickBASIC/Shoelace-formula-for-polygonal-area new file mode 120000 index 0000000000..dc63463382 --- /dev/null +++ b/Lang/QuickBASIC/Shoelace-formula-for-polygonal-area @@ -0,0 +1 @@ +../../Task/Shoelace-formula-for-polygonal-area/QuickBASIC \ No newline at end of file diff --git a/Lang/QuickBASIC/Sorting-algorithms-Quicksort b/Lang/QuickBASIC/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..573bd236b2 --- /dev/null +++ b/Lang/QuickBASIC/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/QuickBASIC \ No newline at end of file diff --git a/Lang/Quite-BASIC/Determine-sentence-type b/Lang/Quite-BASIC/Determine-sentence-type new file mode 120000 index 0000000000..6c274b9228 --- /dev/null +++ b/Lang/Quite-BASIC/Determine-sentence-type @@ -0,0 +1 @@ +../../Task/Determine-sentence-type/Quite-BASIC \ No newline at end of file diff --git a/Lang/Quite-BASIC/Empty-program b/Lang/Quite-BASIC/Empty-program deleted file mode 120000 index fb2bfba5b2..0000000000 --- a/Lang/Quite-BASIC/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Quite-BASIC \ No newline at end of file diff --git a/Lang/R/15-puzzle-solver b/Lang/R/15-puzzle-solver new file mode 120000 index 0000000000..f3e79214e0 --- /dev/null +++ b/Lang/R/15-puzzle-solver @@ -0,0 +1 @@ +../../Task/15-puzzle-solver/R \ No newline at end of file diff --git a/Lang/R/ADFGVX-cipher b/Lang/R/ADFGVX-cipher new file mode 120000 index 0000000000..78a519cccb --- /dev/null +++ b/Lang/R/ADFGVX-cipher @@ -0,0 +1 @@ +../../Task/ADFGVX-cipher/R \ No newline at end of file diff --git a/Lang/R/Angle-difference-between-two-bearings b/Lang/R/Angle-difference-between-two-bearings new file mode 120000 index 0000000000..a27ae03f18 --- /dev/null +++ b/Lang/R/Angle-difference-between-two-bearings @@ -0,0 +1 @@ +../../Task/Angle-difference-between-two-bearings/R \ No newline at end of file diff --git a/Lang/R/Angles-geometric-normalization-and-conversion b/Lang/R/Angles-geometric-normalization-and-conversion new file mode 120000 index 0000000000..d1e56f507e --- /dev/null +++ b/Lang/R/Angles-geometric-normalization-and-conversion @@ -0,0 +1 @@ +../../Task/Angles-geometric-normalization-and-conversion/R \ No newline at end of file diff --git a/Lang/R/Arithmetic-derivative b/Lang/R/Arithmetic-derivative new file mode 120000 index 0000000000..b37750c7e7 --- /dev/null +++ b/Lang/R/Arithmetic-derivative @@ -0,0 +1 @@ +../../Task/Arithmetic-derivative/R \ No newline at end of file diff --git a/Lang/R/Balanced-ternary b/Lang/R/Balanced-ternary new file mode 120000 index 0000000000..593bb03a22 --- /dev/null +++ b/Lang/R/Balanced-ternary @@ -0,0 +1 @@ +../../Task/Balanced-ternary/R \ No newline at end of file diff --git a/Lang/R/Bioinformatics-Sequence-mutation b/Lang/R/Bioinformatics-Sequence-mutation new file mode 120000 index 0000000000..2779ce82b8 --- /dev/null +++ b/Lang/R/Bioinformatics-Sequence-mutation @@ -0,0 +1 @@ +../../Task/Bioinformatics-Sequence-mutation/R \ No newline at end of file diff --git a/Lang/R/Bioinformatics-base-count b/Lang/R/Bioinformatics-base-count deleted file mode 120000 index 2ca416a985..0000000000 --- a/Lang/R/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/R \ No newline at end of file diff --git a/Lang/R/Boyer-Moore-string-search b/Lang/R/Boyer-Moore-string-search new file mode 120000 index 0000000000..32fa72f304 --- /dev/null +++ b/Lang/R/Boyer-Moore-string-search @@ -0,0 +1 @@ +../../Task/Boyer-Moore-string-search/R \ No newline at end of file diff --git a/Lang/R/Brazilian-numbers b/Lang/R/Brazilian-numbers new file mode 120000 index 0000000000..87e6a7046a --- /dev/null +++ b/Lang/R/Brazilian-numbers @@ -0,0 +1 @@ +../../Task/Brazilian-numbers/R \ No newline at end of file diff --git a/Lang/R/CUSIP b/Lang/R/CUSIP new file mode 120000 index 0000000000..e43a376539 --- /dev/null +++ b/Lang/R/CUSIP @@ -0,0 +1 @@ +../../Task/CUSIP/R \ No newline at end of file diff --git a/Lang/R/Call-a-foreign-language-function b/Lang/R/Call-a-foreign-language-function new file mode 120000 index 0000000000..606c52dbec --- /dev/null +++ b/Lang/R/Call-a-foreign-language-function @@ -0,0 +1 @@ +../../Task/Call-a-foreign-language-function/R \ No newline at end of file diff --git a/Lang/R/Camel-case-and-snake-case b/Lang/R/Camel-case-and-snake-case new file mode 120000 index 0000000000..e76dd2d66a --- /dev/null +++ b/Lang/R/Camel-case-and-snake-case @@ -0,0 +1 @@ +../../Task/Camel-case-and-snake-case/R \ No newline at end of file diff --git a/Lang/R/Catalan-numbers-Pascals-triangle b/Lang/R/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..dbe83426e3 --- /dev/null +++ b/Lang/R/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/R \ No newline at end of file diff --git a/Lang/R/Chinese-zodiac b/Lang/R/Chinese-zodiac new file mode 120000 index 0000000000..55811323ec --- /dev/null +++ b/Lang/R/Chinese-zodiac @@ -0,0 +1 @@ +../../Task/Chinese-zodiac/R \ No newline at end of file diff --git a/Lang/R/Colour-pinstripe-Display b/Lang/R/Colour-pinstripe-Display new file mode 120000 index 0000000000..88bf4afbbd --- /dev/null +++ b/Lang/R/Colour-pinstripe-Display @@ -0,0 +1 @@ +../../Task/Colour-pinstripe-Display/R \ No newline at end of file diff --git a/Lang/R/Compare-length-of-two-strings b/Lang/R/Compare-length-of-two-strings new file mode 120000 index 0000000000..834feb9f20 --- /dev/null +++ b/Lang/R/Compare-length-of-two-strings @@ -0,0 +1 @@ +../../Task/Compare-length-of-two-strings/R \ No newline at end of file diff --git a/Lang/R/Compare-sorting-algorithms-performance b/Lang/R/Compare-sorting-algorithms-performance new file mode 120000 index 0000000000..61629d6cd5 --- /dev/null +++ b/Lang/R/Compare-sorting-algorithms-performance @@ -0,0 +1 @@ +../../Task/Compare-sorting-algorithms-performance/R \ No newline at end of file diff --git a/Lang/R/Conjugate-transpose b/Lang/R/Conjugate-transpose new file mode 120000 index 0000000000..573e26fb04 --- /dev/null +++ b/Lang/R/Conjugate-transpose @@ -0,0 +1 @@ +../../Task/Conjugate-transpose/R \ No newline at end of file diff --git a/Lang/R/Continued-fraction b/Lang/R/Continued-fraction new file mode 120000 index 0000000000..8e8db83048 --- /dev/null +++ b/Lang/R/Continued-fraction @@ -0,0 +1 @@ +../../Task/Continued-fraction/R \ No newline at end of file diff --git a/Lang/R/Continued-fraction-Arithmetic-Construct-from-rational-number b/Lang/R/Continued-fraction-Arithmetic-Construct-from-rational-number new file mode 120000 index 0000000000..6bffaf9997 --- /dev/null +++ b/Lang/R/Continued-fraction-Arithmetic-Construct-from-rational-number @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-Construct-from-rational-number/R \ No newline at end of file diff --git a/Lang/R/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- b/Lang/R/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- new file mode 120000 index 0000000000..794241b476 --- /dev/null +++ b/Lang/R/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n-/R \ No newline at end of file diff --git a/Lang/R/Convert-seconds-to-compound-duration b/Lang/R/Convert-seconds-to-compound-duration new file mode 120000 index 0000000000..85f297d7da --- /dev/null +++ b/Lang/R/Convert-seconds-to-compound-duration @@ -0,0 +1 @@ +../../Task/Convert-seconds-to-compound-duration/R \ No newline at end of file diff --git a/Lang/R/Convex-hull b/Lang/R/Convex-hull new file mode 120000 index 0000000000..8db2946ae1 --- /dev/null +++ b/Lang/R/Convex-hull @@ -0,0 +1 @@ +../../Task/Convex-hull/R \ No newline at end of file diff --git a/Lang/R/Count-in-octal b/Lang/R/Count-in-octal new file mode 120000 index 0000000000..37edd3a31e --- /dev/null +++ b/Lang/R/Count-in-octal @@ -0,0 +1 @@ +../../Task/Count-in-octal/R \ No newline at end of file diff --git a/Lang/R/Cramers-rule b/Lang/R/Cramers-rule new file mode 120000 index 0000000000..839896c59f --- /dev/null +++ b/Lang/R/Cramers-rule @@ -0,0 +1 @@ +../../Task/Cramers-rule/R \ No newline at end of file diff --git a/Lang/R/Create-an-HTML-table b/Lang/R/Create-an-HTML-table new file mode 120000 index 0000000000..209500efb4 --- /dev/null +++ b/Lang/R/Create-an-HTML-table @@ -0,0 +1 @@ +../../Task/Create-an-HTML-table/R \ No newline at end of file diff --git a/Lang/R/Curzon-numbers b/Lang/R/Curzon-numbers new file mode 120000 index 0000000000..a381ff9f97 --- /dev/null +++ b/Lang/R/Curzon-numbers @@ -0,0 +1 @@ +../../Task/Curzon-numbers/R \ No newline at end of file diff --git a/Lang/R/De-Bruijn-sequences b/Lang/R/De-Bruijn-sequences new file mode 120000 index 0000000000..bd74daf8c7 --- /dev/null +++ b/Lang/R/De-Bruijn-sequences @@ -0,0 +1 @@ +../../Task/De-Bruijn-sequences/R \ No newline at end of file diff --git a/Lang/R/Deceptive-numbers b/Lang/R/Deceptive-numbers new file mode 120000 index 0000000000..68b87065ac --- /dev/null +++ b/Lang/R/Deceptive-numbers @@ -0,0 +1 @@ +../../Task/Deceptive-numbers/R \ No newline at end of file diff --git a/Lang/R/Deepcopy b/Lang/R/Deepcopy new file mode 120000 index 0000000000..85c0e9d496 --- /dev/null +++ b/Lang/R/Deepcopy @@ -0,0 +1 @@ +../../Task/Deepcopy/R \ No newline at end of file diff --git a/Lang/R/Demings-funnel b/Lang/R/Demings-funnel new file mode 120000 index 0000000000..ae9cefb48f --- /dev/null +++ b/Lang/R/Demings-funnel @@ -0,0 +1 @@ +../../Task/Demings-funnel/R \ No newline at end of file diff --git a/Lang/R/Determine-sentence-type b/Lang/R/Determine-sentence-type new file mode 120000 index 0000000000..b5e3ac4763 --- /dev/null +++ b/Lang/R/Determine-sentence-type @@ -0,0 +1 @@ +../../Task/Determine-sentence-type/R \ No newline at end of file diff --git a/Lang/R/Digital-root-Multiplicative-digital-root b/Lang/R/Digital-root-Multiplicative-digital-root new file mode 120000 index 0000000000..09c29b1f07 --- /dev/null +++ b/Lang/R/Digital-root-Multiplicative-digital-root @@ -0,0 +1 @@ +../../Task/Digital-root-Multiplicative-digital-root/R \ No newline at end of file diff --git a/Lang/R/Dijkstras-algorithm b/Lang/R/Dijkstras-algorithm new file mode 120000 index 0000000000..3bff2fae1d --- /dev/null +++ b/Lang/R/Dijkstras-algorithm @@ -0,0 +1 @@ +../../Task/Dijkstras-algorithm/R \ No newline at end of file diff --git a/Lang/R/Disarium-numbers b/Lang/R/Disarium-numbers new file mode 120000 index 0000000000..233dce846c --- /dev/null +++ b/Lang/R/Disarium-numbers @@ -0,0 +1 @@ +../../Task/Disarium-numbers/R \ No newline at end of file diff --git a/Lang/R/Display-a-linear-combination b/Lang/R/Display-a-linear-combination new file mode 120000 index 0000000000..c292ce3aec --- /dev/null +++ b/Lang/R/Display-a-linear-combination @@ -0,0 +1 @@ +../../Task/Display-a-linear-combination/R \ No newline at end of file diff --git a/Lang/R/Doomsday-rule b/Lang/R/Doomsday-rule new file mode 120000 index 0000000000..d2c2b8b054 --- /dev/null +++ b/Lang/R/Doomsday-rule @@ -0,0 +1 @@ +../../Task/Doomsday-rule/R \ No newline at end of file diff --git a/Lang/R/Draw-a-cuboid b/Lang/R/Draw-a-cuboid new file mode 120000 index 0000000000..b0d15ca88e --- /dev/null +++ b/Lang/R/Draw-a-cuboid @@ -0,0 +1 @@ +../../Task/Draw-a-cuboid/R \ No newline at end of file diff --git a/Lang/R/Draw-a-pixel b/Lang/R/Draw-a-pixel new file mode 120000 index 0000000000..64a7037eb8 --- /dev/null +++ b/Lang/R/Draw-a-pixel @@ -0,0 +1 @@ +../../Task/Draw-a-pixel/R \ No newline at end of file diff --git a/Lang/R/Draw-a-sphere b/Lang/R/Draw-a-sphere new file mode 120000 index 0000000000..5508f91f81 --- /dev/null +++ b/Lang/R/Draw-a-sphere @@ -0,0 +1 @@ +../../Task/Draw-a-sphere/R \ No newline at end of file diff --git a/Lang/R/Dutch-national-flag-problem b/Lang/R/Dutch-national-flag-problem new file mode 120000 index 0000000000..422342365f --- /dev/null +++ b/Lang/R/Dutch-national-flag-problem @@ -0,0 +1 @@ +../../Task/Dutch-national-flag-problem/R \ No newline at end of file diff --git a/Lang/R/Equilibrium-index b/Lang/R/Equilibrium-index new file mode 120000 index 0000000000..7c36abe0f6 --- /dev/null +++ b/Lang/R/Equilibrium-index @@ -0,0 +1 @@ +../../Task/Equilibrium-index/R \ No newline at end of file diff --git a/Lang/R/Euclid-Mullin-sequence b/Lang/R/Euclid-Mullin-sequence new file mode 120000 index 0000000000..3929a900d8 --- /dev/null +++ b/Lang/R/Euclid-Mullin-sequence @@ -0,0 +1 @@ +../../Task/Euclid-Mullin-sequence/R \ No newline at end of file diff --git a/Lang/R/Execute-HQ9+ b/Lang/R/Execute-HQ9+ new file mode 120000 index 0000000000..0972c0bb4f --- /dev/null +++ b/Lang/R/Execute-HQ9+ @@ -0,0 +1 @@ +../../Task/Execute-HQ9+/R \ No newline at end of file diff --git a/Lang/R/Factorial-primes b/Lang/R/Factorial-primes new file mode 120000 index 0000000000..90b75c9d38 --- /dev/null +++ b/Lang/R/Factorial-primes @@ -0,0 +1 @@ +../../Task/Factorial-primes/R \ No newline at end of file diff --git a/Lang/R/Factorions b/Lang/R/Factorions new file mode 120000 index 0000000000..351fcd0d06 --- /dev/null +++ b/Lang/R/Factorions @@ -0,0 +1 @@ +../../Task/Factorions/R \ No newline at end of file diff --git a/Lang/R/Factors-of-a-Mersenne-number b/Lang/R/Factors-of-a-Mersenne-number new file mode 120000 index 0000000000..7aad181edd --- /dev/null +++ b/Lang/R/Factors-of-a-Mersenne-number @@ -0,0 +1 @@ +../../Task/Factors-of-a-Mersenne-number/R \ No newline at end of file diff --git a/Lang/R/Fermat-numbers b/Lang/R/Fermat-numbers new file mode 120000 index 0000000000..17ea6a5311 --- /dev/null +++ b/Lang/R/Fermat-numbers @@ -0,0 +1 @@ +../../Task/Fermat-numbers/R \ No newline at end of file diff --git a/Lang/R/Fibonacci-n-step-number-sequences b/Lang/R/Fibonacci-n-step-number-sequences new file mode 120000 index 0000000000..1cf227761a --- /dev/null +++ b/Lang/R/Fibonacci-n-step-number-sequences @@ -0,0 +1 @@ +../../Task/Fibonacci-n-step-number-sequences/R \ No newline at end of file diff --git a/Lang/R/File-extension-is-in-extensions-list b/Lang/R/File-extension-is-in-extensions-list new file mode 120000 index 0000000000..154f141040 --- /dev/null +++ b/Lang/R/File-extension-is-in-extensions-list @@ -0,0 +1 @@ +../../Task/File-extension-is-in-extensions-list/R \ No newline at end of file diff --git a/Lang/R/Find-palindromic-numbers-in-both-binary-and-ternary-bases b/Lang/R/Find-palindromic-numbers-in-both-binary-and-ternary-bases new file mode 120000 index 0000000000..1adf6989fe --- /dev/null +++ b/Lang/R/Find-palindromic-numbers-in-both-binary-and-ternary-bases @@ -0,0 +1 @@ +../../Task/Find-palindromic-numbers-in-both-binary-and-ternary-bases/R \ No newline at end of file diff --git a/Lang/R/Flipping-bits-game b/Lang/R/Flipping-bits-game new file mode 120000 index 0000000000..45f9cba067 --- /dev/null +++ b/Lang/R/Flipping-bits-game @@ -0,0 +1 @@ +../../Task/Flipping-bits-game/R \ No newline at end of file diff --git a/Lang/R/Floyd-Warshall-algorithm b/Lang/R/Floyd-Warshall-algorithm new file mode 120000 index 0000000000..f0f7534bc6 --- /dev/null +++ b/Lang/R/Floyd-Warshall-algorithm @@ -0,0 +1 @@ +../../Task/Floyd-Warshall-algorithm/R \ No newline at end of file diff --git a/Lang/R/Fractran b/Lang/R/Fractran new file mode 120000 index 0000000000..4684d03d23 --- /dev/null +++ b/Lang/R/Fractran @@ -0,0 +1 @@ +../../Task/Fractran/R \ No newline at end of file diff --git a/Lang/R/Gapful-numbers b/Lang/R/Gapful-numbers new file mode 120000 index 0000000000..d00abda6e0 --- /dev/null +++ b/Lang/R/Gapful-numbers @@ -0,0 +1 @@ +../../Task/Gapful-numbers/R \ No newline at end of file diff --git a/Lang/R/Gauss-Jordan-matrix-inversion b/Lang/R/Gauss-Jordan-matrix-inversion new file mode 120000 index 0000000000..abdff0e0d3 --- /dev/null +++ b/Lang/R/Gauss-Jordan-matrix-inversion @@ -0,0 +1 @@ +../../Task/Gauss-Jordan-matrix-inversion/R \ No newline at end of file diff --git a/Lang/R/Giuga-numbers b/Lang/R/Giuga-numbers new file mode 120000 index 0000000000..e45399fcf4 --- /dev/null +++ b/Lang/R/Giuga-numbers @@ -0,0 +1 @@ +../../Task/Giuga-numbers/R \ No newline at end of file diff --git a/Lang/R/Golden-ratio-Convergence b/Lang/R/Golden-ratio-Convergence new file mode 120000 index 0000000000..c3444860a4 --- /dev/null +++ b/Lang/R/Golden-ratio-Convergence @@ -0,0 +1 @@ +../../Task/Golden-ratio-Convergence/R \ No newline at end of file diff --git a/Lang/R/Greedy-algorithm-for-Egyptian-fractions b/Lang/R/Greedy-algorithm-for-Egyptian-fractions new file mode 120000 index 0000000000..142b97c38d --- /dev/null +++ b/Lang/R/Greedy-algorithm-for-Egyptian-fractions @@ -0,0 +1 @@ +../../Task/Greedy-algorithm-for-Egyptian-fractions/R \ No newline at end of file diff --git a/Lang/R/Halt-and-catch-fire b/Lang/R/Halt-and-catch-fire new file mode 120000 index 0000000000..f754df332d --- /dev/null +++ b/Lang/R/Halt-and-catch-fire @@ -0,0 +1 @@ +../../Task/Halt-and-catch-fire/R \ No newline at end of file diff --git a/Lang/R/Harshad-or-Niven-series b/Lang/R/Harshad-or-Niven-series new file mode 120000 index 0000000000..30268e28d1 --- /dev/null +++ b/Lang/R/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/R \ No newline at end of file diff --git a/Lang/R/Hello-world-Newbie b/Lang/R/Hello-world-Newbie new file mode 120000 index 0000000000..af7f835953 --- /dev/null +++ b/Lang/R/Hello-world-Newbie @@ -0,0 +1 @@ +../../Task/Hello-world-Newbie/R \ No newline at end of file diff --git a/Lang/R/Hex-words b/Lang/R/Hex-words new file mode 120000 index 0000000000..f38acbfb8b --- /dev/null +++ b/Lang/R/Hex-words @@ -0,0 +1 @@ +../../Task/Hex-words/R \ No newline at end of file diff --git a/Lang/R/Humble-numbers b/Lang/R/Humble-numbers new file mode 120000 index 0000000000..66447beec9 --- /dev/null +++ b/Lang/R/Humble-numbers @@ -0,0 +1 @@ +../../Task/Humble-numbers/R \ No newline at end of file diff --git a/Lang/R/ISBN13-check-digit b/Lang/R/ISBN13-check-digit new file mode 120000 index 0000000000..2ffb9a42ca --- /dev/null +++ b/Lang/R/ISBN13-check-digit @@ -0,0 +1 @@ +../../Task/ISBN13-check-digit/R \ No newline at end of file diff --git a/Lang/R/Integer-overflow b/Lang/R/Integer-overflow new file mode 120000 index 0000000000..35a7fbe410 --- /dev/null +++ b/Lang/R/Integer-overflow @@ -0,0 +1 @@ +../../Task/Integer-overflow/R \ No newline at end of file diff --git a/Lang/R/Isqrt-integer-square-root-of-X b/Lang/R/Isqrt-integer-square-root-of-X new file mode 120000 index 0000000000..3aa4e6becf --- /dev/null +++ b/Lang/R/Isqrt-integer-square-root-of-X @@ -0,0 +1 @@ +../../Task/Isqrt-integer-square-root-of-X/R \ No newline at end of file diff --git a/Lang/R/Kernighans-large-earthquake-problem b/Lang/R/Kernighans-large-earthquake-problem new file mode 120000 index 0000000000..e4a703f050 --- /dev/null +++ b/Lang/R/Kernighans-large-earthquake-problem @@ -0,0 +1 @@ +../../Task/Kernighans-large-earthquake-problem/R \ No newline at end of file diff --git a/Lang/R/LZW-compression b/Lang/R/LZW-compression new file mode 120000 index 0000000000..52a9a7c425 --- /dev/null +++ b/Lang/R/LZW-compression @@ -0,0 +1 @@ +../../Task/LZW-compression/R \ No newline at end of file diff --git a/Lang/R/Literals-Floating-point b/Lang/R/Literals-Floating-point new file mode 120000 index 0000000000..45971f0459 --- /dev/null +++ b/Lang/R/Literals-Floating-point @@ -0,0 +1 @@ +../../Task/Literals-Floating-point/R \ No newline at end of file diff --git a/Lang/R/Loops-With-multiple-ranges b/Lang/R/Loops-With-multiple-ranges new file mode 120000 index 0000000000..b09ac16be3 --- /dev/null +++ b/Lang/R/Loops-With-multiple-ranges @@ -0,0 +1 @@ +../../Task/Loops-With-multiple-ranges/R \ No newline at end of file diff --git a/Lang/R/M-bius-function b/Lang/R/M-bius-function new file mode 120000 index 0000000000..54d202ad87 --- /dev/null +++ b/Lang/R/M-bius-function @@ -0,0 +1 @@ +../../Task/M-bius-function/R \ No newline at end of file diff --git a/Lang/R/Magic-constant b/Lang/R/Magic-constant new file mode 120000 index 0000000000..42b2f79fd6 --- /dev/null +++ b/Lang/R/Magic-constant @@ -0,0 +1 @@ +../../Task/Magic-constant/R \ No newline at end of file diff --git a/Lang/R/Make-directory-path b/Lang/R/Make-directory-path new file mode 120000 index 0000000000..4c5b0435c3 --- /dev/null +++ b/Lang/R/Make-directory-path @@ -0,0 +1 @@ +../../Task/Make-directory-path/R \ No newline at end of file diff --git a/Lang/R/Middle-three-digits b/Lang/R/Middle-three-digits new file mode 120000 index 0000000000..d0b65517a3 --- /dev/null +++ b/Lang/R/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/R \ No newline at end of file diff --git a/Lang/R/Modular-arithmetic b/Lang/R/Modular-arithmetic new file mode 120000 index 0000000000..d91672ac00 --- /dev/null +++ b/Lang/R/Modular-arithmetic @@ -0,0 +1 @@ +../../Task/Modular-arithmetic/R \ No newline at end of file diff --git a/Lang/R/Modular-exponentiation b/Lang/R/Modular-exponentiation new file mode 120000 index 0000000000..00a5ab3605 --- /dev/null +++ b/Lang/R/Modular-exponentiation @@ -0,0 +1 @@ +../../Task/Modular-exponentiation/R \ No newline at end of file diff --git a/Lang/R/Move-to-front-algorithm b/Lang/R/Move-to-front-algorithm new file mode 120000 index 0000000000..4c2217c694 --- /dev/null +++ b/Lang/R/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/R \ No newline at end of file diff --git a/Lang/R/Multi-dimensional-array b/Lang/R/Multi-dimensional-array new file mode 120000 index 0000000000..c00f08cfcf --- /dev/null +++ b/Lang/R/Multi-dimensional-array @@ -0,0 +1 @@ +../../Task/Multi-dimensional-array/R \ No newline at end of file diff --git a/Lang/R/Munchausen-numbers b/Lang/R/Munchausen-numbers new file mode 120000 index 0000000000..aa4d45945f --- /dev/null +++ b/Lang/R/Munchausen-numbers @@ -0,0 +1 @@ +../../Task/Munchausen-numbers/R \ No newline at end of file diff --git a/Lang/R/Munching-squares b/Lang/R/Munching-squares new file mode 120000 index 0000000000..5c31288892 --- /dev/null +++ b/Lang/R/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/R \ No newline at end of file diff --git a/Lang/R/Naming-conventions b/Lang/R/Naming-conventions new file mode 120000 index 0000000000..6ca70fbd5c --- /dev/null +++ b/Lang/R/Naming-conventions @@ -0,0 +1 @@ +../../Task/Naming-conventions/R \ No newline at end of file diff --git a/Lang/R/Numbers-with-equal-rises-and-falls b/Lang/R/Numbers-with-equal-rises-and-falls new file mode 120000 index 0000000000..bd2b09b1a8 --- /dev/null +++ b/Lang/R/Numbers-with-equal-rises-and-falls @@ -0,0 +1 @@ +../../Task/Numbers-with-equal-rises-and-falls/R \ No newline at end of file diff --git a/Lang/R/Numeric-error-propagation b/Lang/R/Numeric-error-propagation new file mode 120000 index 0000000000..b4d737b26d --- /dev/null +++ b/Lang/R/Numeric-error-propagation @@ -0,0 +1 @@ +../../Task/Numeric-error-propagation/R \ No newline at end of file diff --git a/Lang/R/Old-Russian-measure-of-length b/Lang/R/Old-Russian-measure-of-length new file mode 120000 index 0000000000..10e03acc09 --- /dev/null +++ b/Lang/R/Old-Russian-measure-of-length @@ -0,0 +1 @@ +../../Task/Old-Russian-measure-of-length/R \ No newline at end of file diff --git a/Lang/R/Order-two-numerical-lists b/Lang/R/Order-two-numerical-lists new file mode 120000 index 0000000000..7823304c26 --- /dev/null +++ b/Lang/R/Order-two-numerical-lists @@ -0,0 +1 @@ +../../Task/Order-two-numerical-lists/R \ No newline at end of file diff --git a/Lang/R/Padovan-n-step-number-sequences b/Lang/R/Padovan-n-step-number-sequences new file mode 120000 index 0000000000..bb121da853 --- /dev/null +++ b/Lang/R/Padovan-n-step-number-sequences @@ -0,0 +1 @@ +../../Task/Padovan-n-step-number-sequences/R \ No newline at end of file diff --git a/Lang/R/Parse-an-IP-Address b/Lang/R/Parse-an-IP-Address new file mode 120000 index 0000000000..9f23986592 --- /dev/null +++ b/Lang/R/Parse-an-IP-Address @@ -0,0 +1 @@ +../../Task/Parse-an-IP-Address/R \ No newline at end of file diff --git a/Lang/R/Parsing-RPN-calculator-algorithm b/Lang/R/Parsing-RPN-calculator-algorithm new file mode 120000 index 0000000000..121dbc0d6c --- /dev/null +++ b/Lang/R/Parsing-RPN-calculator-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-RPN-calculator-algorithm/R \ No newline at end of file diff --git a/Lang/R/Parsing-Shunting-yard-algorithm b/Lang/R/Parsing-Shunting-yard-algorithm new file mode 120000 index 0000000000..ceae410d30 --- /dev/null +++ b/Lang/R/Parsing-Shunting-yard-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-Shunting-yard-algorithm/R \ No newline at end of file diff --git a/Lang/R/Pernicious-numbers b/Lang/R/Pernicious-numbers new file mode 120000 index 0000000000..e0d8d55200 --- /dev/null +++ b/Lang/R/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/R \ No newline at end of file diff --git a/Lang/R/Phrase-reversals b/Lang/R/Phrase-reversals new file mode 120000 index 0000000000..a54a2683b7 --- /dev/null +++ b/Lang/R/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/R \ No newline at end of file diff --git a/Lang/R/Pig-the-dice-game b/Lang/R/Pig-the-dice-game new file mode 120000 index 0000000000..eb7f5b9e91 --- /dev/null +++ b/Lang/R/Pig-the-dice-game @@ -0,0 +1 @@ +../../Task/Pig-the-dice-game/R \ No newline at end of file diff --git a/Lang/R/Pinstripe-Display b/Lang/R/Pinstripe-Display new file mode 120000 index 0000000000..ecca9291db --- /dev/null +++ b/Lang/R/Pinstripe-Display @@ -0,0 +1 @@ +../../Task/Pinstripe-Display/R \ No newline at end of file diff --git a/Lang/R/Plasma-effect b/Lang/R/Plasma-effect new file mode 120000 index 0000000000..0d663e21d0 --- /dev/null +++ b/Lang/R/Plasma-effect @@ -0,0 +1 @@ +../../Task/Plasma-effect/R \ No newline at end of file diff --git a/Lang/R/Poker-hand-analyser b/Lang/R/Poker-hand-analyser new file mode 120000 index 0000000000..1291d08bb2 --- /dev/null +++ b/Lang/R/Poker-hand-analyser @@ -0,0 +1 @@ +../../Task/Poker-hand-analyser/R \ No newline at end of file diff --git a/Lang/R/Pseudo-random-numbers-Middle-square-method b/Lang/R/Pseudo-random-numbers-Middle-square-method new file mode 120000 index 0000000000..27657f10ef --- /dev/null +++ b/Lang/R/Pseudo-random-numbers-Middle-square-method @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-Middle-square-method/R \ No newline at end of file diff --git a/Lang/R/Quaternion-type b/Lang/R/Quaternion-type deleted file mode 120000 index 2e826895b9..0000000000 --- a/Lang/R/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/R \ No newline at end of file diff --git a/Lang/R/Quickselect-algorithm b/Lang/R/Quickselect-algorithm new file mode 120000 index 0000000000..996073d670 --- /dev/null +++ b/Lang/R/Quickselect-algorithm @@ -0,0 +1 @@ +../../Task/Quickselect-algorithm/R \ No newline at end of file diff --git a/Lang/R/Rename-a-file b/Lang/R/Rename-a-file new file mode 120000 index 0000000000..d3214c3f95 --- /dev/null +++ b/Lang/R/Rename-a-file @@ -0,0 +1 @@ +../../Task/Rename-a-file/R \ No newline at end of file diff --git a/Lang/R/Rep-string b/Lang/R/Rep-string new file mode 120000 index 0000000000..6f2483d2e5 --- /dev/null +++ b/Lang/R/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/R \ No newline at end of file diff --git a/Lang/R/Repunit-primes b/Lang/R/Repunit-primes new file mode 120000 index 0000000000..9ae6100164 --- /dev/null +++ b/Lang/R/Repunit-primes @@ -0,0 +1 @@ +../../Task/Repunit-primes/R \ No newline at end of file diff --git a/Lang/R/Retrieve-and-search-chat-history b/Lang/R/Retrieve-and-search-chat-history new file mode 120000 index 0000000000..6f350b7b8c --- /dev/null +++ b/Lang/R/Retrieve-and-search-chat-history @@ -0,0 +1 @@ +../../Task/Retrieve-and-search-chat-history/R \ No newline at end of file diff --git a/Lang/R/Search-a-list-of-records b/Lang/R/Search-a-list-of-records new file mode 120000 index 0000000000..ee8b509a32 --- /dev/null +++ b/Lang/R/Search-a-list-of-records @@ -0,0 +1 @@ +../../Task/Search-a-list-of-records/R \ No newline at end of file diff --git a/Lang/R/Self-describing-numbers b/Lang/R/Self-describing-numbers new file mode 120000 index 0000000000..3e9383f257 --- /dev/null +++ b/Lang/R/Self-describing-numbers @@ -0,0 +1 @@ +../../Task/Self-describing-numbers/R \ No newline at end of file diff --git a/Lang/R/Semordnilap b/Lang/R/Semordnilap new file mode 120000 index 0000000000..8ef388caef --- /dev/null +++ b/Lang/R/Semordnilap @@ -0,0 +1 @@ +../../Task/Semordnilap/R \ No newline at end of file diff --git a/Lang/R/Shoelace-formula-for-polygonal-area b/Lang/R/Shoelace-formula-for-polygonal-area new file mode 120000 index 0000000000..8e6ea3fcc6 --- /dev/null +++ b/Lang/R/Shoelace-formula-for-polygonal-area @@ -0,0 +1 @@ +../../Task/Shoelace-formula-for-polygonal-area/R \ No newline at end of file diff --git a/Lang/R/Soloways-recurring-rainfall b/Lang/R/Soloways-recurring-rainfall new file mode 120000 index 0000000000..33b1f84311 --- /dev/null +++ b/Lang/R/Soloways-recurring-rainfall @@ -0,0 +1 @@ +../../Task/Soloways-recurring-rainfall/R \ No newline at end of file diff --git a/Lang/R/Sort-numbers-lexicographically b/Lang/R/Sort-numbers-lexicographically new file mode 120000 index 0000000000..77a76317d2 --- /dev/null +++ b/Lang/R/Sort-numbers-lexicographically @@ -0,0 +1 @@ +../../Task/Sort-numbers-lexicographically/R \ No newline at end of file diff --git a/Lang/R/Sorting-algorithms-Bead-sort b/Lang/R/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..4be00936ef --- /dev/null +++ b/Lang/R/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/R \ No newline at end of file diff --git a/Lang/R/Sorting-algorithms-Patience-sort b/Lang/R/Sorting-algorithms-Patience-sort new file mode 120000 index 0000000000..bcaf3b078e --- /dev/null +++ b/Lang/R/Sorting-algorithms-Patience-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Patience-sort/R \ No newline at end of file diff --git a/Lang/R/Sorting-algorithms-Strand-sort b/Lang/R/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..80a612e755 --- /dev/null +++ b/Lang/R/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/R \ No newline at end of file diff --git a/Lang/R/Spinning-rod-animation-Text b/Lang/R/Spinning-rod-animation-Text new file mode 120000 index 0000000000..3083d1bb50 --- /dev/null +++ b/Lang/R/Spinning-rod-animation-Text @@ -0,0 +1 @@ +../../Task/Spinning-rod-animation-Text/R \ No newline at end of file diff --git a/Lang/R/Split-a-character-string-based-on-change-of-character b/Lang/R/Split-a-character-string-based-on-change-of-character new file mode 120000 index 0000000000..16a92812f1 --- /dev/null +++ b/Lang/R/Split-a-character-string-based-on-change-of-character @@ -0,0 +1 @@ +../../Task/Split-a-character-string-based-on-change-of-character/R \ No newline at end of file diff --git a/Lang/R/Square-free-integers b/Lang/R/Square-free-integers new file mode 120000 index 0000000000..a07b4300b5 --- /dev/null +++ b/Lang/R/Square-free-integers @@ -0,0 +1 @@ +../../Task/Square-free-integers/R \ No newline at end of file diff --git a/Lang/R/Start-from-a-main-routine b/Lang/R/Start-from-a-main-routine new file mode 120000 index 0000000000..915851ff80 --- /dev/null +++ b/Lang/R/Start-from-a-main-routine @@ -0,0 +1 @@ +../../Task/Start-from-a-main-routine/R \ No newline at end of file diff --git a/Lang/R/Strassens-algorithm b/Lang/R/Strassens-algorithm new file mode 120000 index 0000000000..e4aa0075a9 --- /dev/null +++ b/Lang/R/Strassens-algorithm @@ -0,0 +1 @@ +../../Task/Strassens-algorithm/R \ No newline at end of file diff --git a/Lang/R/String-interpolation-included- b/Lang/R/String-interpolation-included- new file mode 120000 index 0000000000..f311002546 --- /dev/null +++ b/Lang/R/String-interpolation-included- @@ -0,0 +1 @@ +../../Task/String-interpolation-included-/R \ No newline at end of file diff --git a/Lang/R/String-matching b/Lang/R/String-matching new file mode 120000 index 0000000000..2461134ac0 --- /dev/null +++ b/Lang/R/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/R \ No newline at end of file diff --git a/Lang/R/Strip-a-set-of-characters-from-a-string b/Lang/R/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..b83d60c994 --- /dev/null +++ b/Lang/R/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/R \ No newline at end of file diff --git a/Lang/R/Strip-block-comments b/Lang/R/Strip-block-comments new file mode 120000 index 0000000000..17c55383a8 --- /dev/null +++ b/Lang/R/Strip-block-comments @@ -0,0 +1 @@ +../../Task/Strip-block-comments/R \ No newline at end of file diff --git a/Lang/R/Substitution-cipher b/Lang/R/Substitution-cipher new file mode 120000 index 0000000000..ce3c7f1ac2 --- /dev/null +++ b/Lang/R/Substitution-cipher @@ -0,0 +1 @@ +../../Task/Substitution-cipher/R \ No newline at end of file diff --git a/Lang/R/Substring-Top-and-tail b/Lang/R/Substring-Top-and-tail new file mode 120000 index 0000000000..271cd3b15f --- /dev/null +++ b/Lang/R/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/R \ No newline at end of file diff --git a/Lang/R/Superellipse b/Lang/R/Superellipse new file mode 120000 index 0000000000..3b8dc95f89 --- /dev/null +++ b/Lang/R/Superellipse @@ -0,0 +1 @@ +../../Task/Superellipse/R \ No newline at end of file diff --git a/Lang/R/Sylvesters-sequence b/Lang/R/Sylvesters-sequence new file mode 120000 index 0000000000..29d289c6ff --- /dev/null +++ b/Lang/R/Sylvesters-sequence @@ -0,0 +1 @@ +../../Task/Sylvesters-sequence/R \ No newline at end of file diff --git a/Lang/R/Textonyms b/Lang/R/Textonyms new file mode 120000 index 0000000000..a6ba4b7c41 --- /dev/null +++ b/Lang/R/Textonyms @@ -0,0 +1 @@ +../../Task/Textonyms/R \ No newline at end of file diff --git a/Lang/R/The-Name-Game b/Lang/R/The-Name-Game new file mode 120000 index 0000000000..a5e981bf52 --- /dev/null +++ b/Lang/R/The-Name-Game @@ -0,0 +1 @@ +../../Task/The-Name-Game/R \ No newline at end of file diff --git a/Lang/R/Tonelli-Shanks-algorithm b/Lang/R/Tonelli-Shanks-algorithm new file mode 120000 index 0000000000..2ad48c9cd5 --- /dev/null +++ b/Lang/R/Tonelli-Shanks-algorithm @@ -0,0 +1 @@ +../../Task/Tonelli-Shanks-algorithm/R \ No newline at end of file diff --git a/Lang/R/Transliterate-English-text-using-the-Greek-alphabet b/Lang/R/Transliterate-English-text-using-the-Greek-alphabet new file mode 120000 index 0000000000..0b8d7b7463 --- /dev/null +++ b/Lang/R/Transliterate-English-text-using-the-Greek-alphabet @@ -0,0 +1 @@ +../../Task/Transliterate-English-text-using-the-Greek-alphabet/R \ No newline at end of file diff --git a/Lang/R/Twelve-statements b/Lang/R/Twelve-statements new file mode 120000 index 0000000000..89536cfc68 --- /dev/null +++ b/Lang/R/Twelve-statements @@ -0,0 +1 @@ +../../Task/Twelve-statements/R \ No newline at end of file diff --git a/Lang/R/Van-der-Corput-sequence b/Lang/R/Van-der-Corput-sequence new file mode 120000 index 0000000000..66a8a345d5 --- /dev/null +++ b/Lang/R/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/R \ No newline at end of file diff --git a/Lang/R/Variable-declaration-reset b/Lang/R/Variable-declaration-reset new file mode 120000 index 0000000000..d5c07caba9 --- /dev/null +++ b/Lang/R/Variable-declaration-reset @@ -0,0 +1 @@ +../../Task/Variable-declaration-reset/R \ No newline at end of file diff --git a/Lang/R/Vector b/Lang/R/Vector new file mode 120000 index 0000000000..3d5cfd297c --- /dev/null +++ b/Lang/R/Vector @@ -0,0 +1 @@ +../../Task/Vector/R \ No newline at end of file diff --git a/Lang/R/Verhoeff-algorithm b/Lang/R/Verhoeff-algorithm new file mode 120000 index 0000000000..2838835d10 --- /dev/null +++ b/Lang/R/Verhoeff-algorithm @@ -0,0 +1 @@ +../../Task/Verhoeff-algorithm/R \ No newline at end of file diff --git a/Lang/R/Wieferich-primes b/Lang/R/Wieferich-primes new file mode 120000 index 0000000000..1c103bdf36 --- /dev/null +++ b/Lang/R/Wieferich-primes @@ -0,0 +1 @@ +../../Task/Wieferich-primes/R \ No newline at end of file diff --git a/Lang/R/Wilson-primes-of-order-n b/Lang/R/Wilson-primes-of-order-n new file mode 120000 index 0000000000..0638b273a2 --- /dev/null +++ b/Lang/R/Wilson-primes-of-order-n @@ -0,0 +1 @@ +../../Task/Wilson-primes-of-order-n/R \ No newline at end of file diff --git a/Lang/R/Write-entire-file b/Lang/R/Write-entire-file new file mode 120000 index 0000000000..2972bb07fe --- /dev/null +++ b/Lang/R/Write-entire-file @@ -0,0 +1 @@ +../../Task/Write-entire-file/R \ No newline at end of file diff --git a/Lang/REBOL/00-LANG.txt b/Lang/REBOL/00-LANG.txt deleted file mode 100644 index 0117c8198c..0000000000 --- a/Lang/REBOL/00-LANG.txt +++ /dev/null @@ -1,3 +0,0 @@ -{{stub}}{{language|REBOL -|site=http://rebol.com}} -REBOL stands for Relative Expression Based Object Language. \ No newline at end of file diff --git a/Lang/REBOL/00-META.yaml b/Lang/REBOL/00-META.yaml deleted file mode 100644 index 58070bb517..0000000000 --- a/Lang/REBOL/00-META.yaml +++ /dev/null @@ -1,2 +0,0 @@ ---- -from: http://rosettacode.org/wiki/Category:REBOL diff --git a/Lang/REBOL/100-doors b/Lang/REBOL/100-doors deleted file mode 120000 index 3c604849c4..0000000000 --- a/Lang/REBOL/100-doors +++ /dev/null @@ -1 +0,0 @@ -../../Task/100-doors/REBOL \ No newline at end of file diff --git a/Lang/REBOL/15-puzzle-game b/Lang/REBOL/15-puzzle-game deleted file mode 120000 index ca19266202..0000000000 --- a/Lang/REBOL/15-puzzle-game +++ /dev/null @@ -1 +0,0 @@ -../../Task/15-puzzle-game/REBOL \ No newline at end of file diff --git a/Lang/REBOL/99-bottles-of-beer b/Lang/REBOL/99-bottles-of-beer deleted file mode 120000 index 464d38e243..0000000000 --- a/Lang/REBOL/99-bottles-of-beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-bottles-of-beer/REBOL \ No newline at end of file diff --git a/Lang/REBOL/A+B b/Lang/REBOL/A+B deleted file mode 120000 index a6531c3ec1..0000000000 --- a/Lang/REBOL/A+B +++ /dev/null @@ -1 +0,0 @@ -../../Task/A+B/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Abstract-type b/Lang/REBOL/Abstract-type deleted file mode 120000 index c01205f584..0000000000 --- a/Lang/REBOL/Abstract-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Abstract-type/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Accumulator-factory b/Lang/REBOL/Accumulator-factory deleted file mode 120000 index 9f94ac82f1..0000000000 --- a/Lang/REBOL/Accumulator-factory +++ /dev/null @@ -1 +0,0 @@ -../../Task/Accumulator-factory/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Add-a-variable-to-a-class-instance-at-runtime b/Lang/REBOL/Add-a-variable-to-a-class-instance-at-runtime deleted file mode 120000 index 901f7e7487..0000000000 --- a/Lang/REBOL/Add-a-variable-to-a-class-instance-at-runtime +++ /dev/null @@ -1 +0,0 @@ -../../Task/Add-a-variable-to-a-class-instance-at-runtime/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Align-columns b/Lang/REBOL/Align-columns deleted file mode 120000 index 67ffa18d54..0000000000 --- a/Lang/REBOL/Align-columns +++ /dev/null @@ -1 +0,0 @@ -../../Task/Align-columns/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Amicable-pairs b/Lang/REBOL/Amicable-pairs deleted file mode 120000 index 238ed42eb6..0000000000 --- a/Lang/REBOL/Amicable-pairs +++ /dev/null @@ -1 +0,0 @@ -../../Task/Amicable-pairs/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Animation b/Lang/REBOL/Animation deleted file mode 120000 index 0fccfbad33..0000000000 --- a/Lang/REBOL/Animation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Animation/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Anonymous-recursion b/Lang/REBOL/Anonymous-recursion deleted file mode 120000 index 5c9e13cbb0..0000000000 --- a/Lang/REBOL/Anonymous-recursion +++ /dev/null @@ -1 +0,0 @@ -../../Task/Anonymous-recursion/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Apply-a-callback-to-an-array b/Lang/REBOL/Apply-a-callback-to-an-array deleted file mode 120000 index a9a331e92d..0000000000 --- a/Lang/REBOL/Apply-a-callback-to-an-array +++ /dev/null @@ -1 +0,0 @@ -../../Task/Apply-a-callback-to-an-array/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Arithmetic-Integer b/Lang/REBOL/Arithmetic-Integer deleted file mode 120000 index acafb7724e..0000000000 --- a/Lang/REBOL/Arithmetic-Integer +++ /dev/null @@ -1 +0,0 @@ -../../Task/Arithmetic-Integer/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Array-concatenation b/Lang/REBOL/Array-concatenation deleted file mode 120000 index 679c10ed62..0000000000 --- a/Lang/REBOL/Array-concatenation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Array-concatenation/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Array-length b/Lang/REBOL/Array-length deleted file mode 120000 index d083adde64..0000000000 --- a/Lang/REBOL/Array-length +++ /dev/null @@ -1 +0,0 @@ -../../Task/Array-length/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Arrays b/Lang/REBOL/Arrays deleted file mode 120000 index 9fc95551ee..0000000000 --- a/Lang/REBOL/Arrays +++ /dev/null @@ -1 +0,0 @@ -../../Task/Arrays/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Averages-Arithmetic-mean b/Lang/REBOL/Averages-Arithmetic-mean deleted file mode 120000 index de8cb5e395..0000000000 --- a/Lang/REBOL/Averages-Arithmetic-mean +++ /dev/null @@ -1 +0,0 @@ -../../Task/Averages-Arithmetic-mean/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Averages-Median b/Lang/REBOL/Averages-Median deleted file mode 120000 index 96ef2cd694..0000000000 --- a/Lang/REBOL/Averages-Median +++ /dev/null @@ -1 +0,0 @@ -../../Task/Averages-Median/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Calendar b/Lang/REBOL/Calendar deleted file mode 120000 index f396941538..0000000000 --- a/Lang/REBOL/Calendar +++ /dev/null @@ -1 +0,0 @@ -../../Task/Calendar/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Check-that-file-exists b/Lang/REBOL/Check-that-file-exists deleted file mode 120000 index 70f5435458..0000000000 --- a/Lang/REBOL/Check-that-file-exists +++ /dev/null @@ -1 +0,0 @@ -../../Task/Check-that-file-exists/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Classes b/Lang/REBOL/Classes deleted file mode 120000 index f823823847..0000000000 --- a/Lang/REBOL/Classes +++ /dev/null @@ -1 +0,0 @@ -../../Task/Classes/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Comma-quibbling b/Lang/REBOL/Comma-quibbling deleted file mode 120000 index b2f7530541..0000000000 --- a/Lang/REBOL/Comma-quibbling +++ /dev/null @@ -1 +0,0 @@ -../../Task/Comma-quibbling/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Comments b/Lang/REBOL/Comments deleted file mode 120000 index 2dad54191c..0000000000 --- a/Lang/REBOL/Comments +++ /dev/null @@ -1 +0,0 @@ -../../Task/Comments/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Copy-a-string b/Lang/REBOL/Copy-a-string deleted file mode 120000 index 8babad9959..0000000000 --- a/Lang/REBOL/Copy-a-string +++ /dev/null @@ -1 +0,0 @@ -../../Task/Copy-a-string/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Create-a-file b/Lang/REBOL/Create-a-file deleted file mode 120000 index 3089537d01..0000000000 --- a/Lang/REBOL/Create-a-file +++ /dev/null @@ -1 +0,0 @@ -../../Task/Create-a-file/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Date-format b/Lang/REBOL/Date-format deleted file mode 120000 index 33ce065e87..0000000000 --- a/Lang/REBOL/Date-format +++ /dev/null @@ -1 +0,0 @@ -../../Task/Date-format/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Date-manipulation b/Lang/REBOL/Date-manipulation deleted file mode 120000 index 2722a008ce..0000000000 --- a/Lang/REBOL/Date-manipulation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Date-manipulation/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Day-of-the-week b/Lang/REBOL/Day-of-the-week deleted file mode 120000 index 82d7509a60..0000000000 --- a/Lang/REBOL/Day-of-the-week +++ /dev/null @@ -1 +0,0 @@ -../../Task/Day-of-the-week/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Delete-a-file b/Lang/REBOL/Delete-a-file deleted file mode 120000 index 66f14845d7..0000000000 --- a/Lang/REBOL/Delete-a-file +++ /dev/null @@ -1 +0,0 @@ -../../Task/Delete-a-file/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Detect-division-by-zero b/Lang/REBOL/Detect-division-by-zero deleted file mode 120000 index b0ccafd718..0000000000 --- a/Lang/REBOL/Detect-division-by-zero +++ /dev/null @@ -1 +0,0 @@ -../../Task/Detect-division-by-zero/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Determine-if-a-string-is-numeric b/Lang/REBOL/Determine-if-a-string-is-numeric deleted file mode 120000 index 045a0ae13f..0000000000 --- a/Lang/REBOL/Determine-if-a-string-is-numeric +++ /dev/null @@ -1 +0,0 @@ -../../Task/Determine-if-a-string-is-numeric/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Documentation b/Lang/REBOL/Documentation deleted file mode 120000 index daa69740d8..0000000000 --- a/Lang/REBOL/Documentation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Documentation/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Dot-product b/Lang/REBOL/Dot-product deleted file mode 120000 index 0e405ceca0..0000000000 --- a/Lang/REBOL/Dot-product +++ /dev/null @@ -1 +0,0 @@ -../../Task/Dot-product/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Dynamic-variable-names b/Lang/REBOL/Dynamic-variable-names deleted file mode 120000 index dc26f8842e..0000000000 --- a/Lang/REBOL/Dynamic-variable-names +++ /dev/null @@ -1 +0,0 @@ -../../Task/Dynamic-variable-names/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Echo-server b/Lang/REBOL/Echo-server deleted file mode 120000 index e5f15ce096..0000000000 --- a/Lang/REBOL/Echo-server +++ /dev/null @@ -1 +0,0 @@ -../../Task/Echo-server/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Empty-program b/Lang/REBOL/Empty-program deleted file mode 120000 index 15b162acc2..0000000000 --- a/Lang/REBOL/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Environment-variables b/Lang/REBOL/Environment-variables deleted file mode 120000 index 1742700711..0000000000 --- a/Lang/REBOL/Environment-variables +++ /dev/null @@ -1 +0,0 @@ -../../Task/Environment-variables/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Execute-Brain- b/Lang/REBOL/Execute-Brain- deleted file mode 120000 index 5d49896311..0000000000 --- a/Lang/REBOL/Execute-Brain- +++ /dev/null @@ -1 +0,0 @@ -../../Task/Execute-Brain-/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Execute-a-system-command b/Lang/REBOL/Execute-a-system-command deleted file mode 120000 index 6177e36583..0000000000 --- a/Lang/REBOL/Execute-a-system-command +++ /dev/null @@ -1 +0,0 @@ -../../Task/Execute-a-system-command/REBOL \ No newline at end of file diff --git a/Lang/REBOL/FTP b/Lang/REBOL/FTP deleted file mode 120000 index 7ab1c53c58..0000000000 --- a/Lang/REBOL/FTP +++ /dev/null @@ -1 +0,0 @@ -../../Task/FTP/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Factorial b/Lang/REBOL/Factorial deleted file mode 120000 index 8643656c0a..0000000000 --- a/Lang/REBOL/Factorial +++ /dev/null @@ -1 +0,0 @@ -../../Task/Factorial/REBOL \ No newline at end of file diff --git a/Lang/REBOL/File-input-output b/Lang/REBOL/File-input-output deleted file mode 120000 index 30e510fb5d..0000000000 --- a/Lang/REBOL/File-input-output +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-input-output/REBOL \ No newline at end of file diff --git a/Lang/REBOL/File-size b/Lang/REBOL/File-size deleted file mode 120000 index 61c4252f32..0000000000 --- a/Lang/REBOL/File-size +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-size/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Filter b/Lang/REBOL/Filter deleted file mode 120000 index d25c807398..0000000000 --- a/Lang/REBOL/Filter +++ /dev/null @@ -1 +0,0 @@ -../../Task/Filter/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Find-the-last-Sunday-of-each-month b/Lang/REBOL/Find-the-last-Sunday-of-each-month deleted file mode 120000 index c54d330170..0000000000 --- a/Lang/REBOL/Find-the-last-Sunday-of-each-month +++ /dev/null @@ -1 +0,0 @@ -../../Task/Find-the-last-Sunday-of-each-month/REBOL \ No newline at end of file diff --git a/Lang/REBOL/First-class-functions b/Lang/REBOL/First-class-functions deleted file mode 120000 index 729d2ef773..0000000000 --- a/Lang/REBOL/First-class-functions +++ /dev/null @@ -1 +0,0 @@ -../../Task/First-class-functions/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Fixed-length-records b/Lang/REBOL/Fixed-length-records deleted file mode 120000 index c6d6d1ea72..0000000000 --- a/Lang/REBOL/Fixed-length-records +++ /dev/null @@ -1 +0,0 @@ -../../Task/Fixed-length-records/REBOL \ No newline at end of file diff --git a/Lang/REBOL/FizzBuzz b/Lang/REBOL/FizzBuzz deleted file mode 120000 index 5fada5dc79..0000000000 --- a/Lang/REBOL/FizzBuzz +++ /dev/null @@ -1 +0,0 @@ -../../Task/FizzBuzz/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Flatten-a-list b/Lang/REBOL/Flatten-a-list deleted file mode 120000 index c63e60f1ae..0000000000 --- a/Lang/REBOL/Flatten-a-list +++ /dev/null @@ -1 +0,0 @@ -../../Task/Flatten-a-list/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Flow-control-structures b/Lang/REBOL/Flow-control-structures deleted file mode 120000 index 02978f970b..0000000000 --- a/Lang/REBOL/Flow-control-structures +++ /dev/null @@ -1 +0,0 @@ -../../Task/Flow-control-structures/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Formatted-numeric-output b/Lang/REBOL/Formatted-numeric-output deleted file mode 120000 index 6231201b56..0000000000 --- a/Lang/REBOL/Formatted-numeric-output +++ /dev/null @@ -1 +0,0 @@ -../../Task/Formatted-numeric-output/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Function-composition b/Lang/REBOL/Function-composition deleted file mode 120000 index 00fbef410f..0000000000 --- a/Lang/REBOL/Function-composition +++ /dev/null @@ -1 +0,0 @@ -../../Task/Function-composition/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Function-definition b/Lang/REBOL/Function-definition deleted file mode 120000 index 24045b17c8..0000000000 --- a/Lang/REBOL/Function-definition +++ /dev/null @@ -1 +0,0 @@ -../../Task/Function-definition/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Generic-swap b/Lang/REBOL/Generic-swap deleted file mode 120000 index 252d05095f..0000000000 --- a/Lang/REBOL/Generic-swap +++ /dev/null @@ -1 +0,0 @@ -../../Task/Generic-swap/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Greatest-common-divisor b/Lang/REBOL/Greatest-common-divisor deleted file mode 120000 index 66251fda3d..0000000000 --- a/Lang/REBOL/Greatest-common-divisor +++ /dev/null @@ -1 +0,0 @@ -../../Task/Greatest-common-divisor/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Greatest-element-of-a-list b/Lang/REBOL/Greatest-element-of-a-list deleted file mode 120000 index bf835b648c..0000000000 --- a/Lang/REBOL/Greatest-element-of-a-list +++ /dev/null @@ -1 +0,0 @@ -../../Task/Greatest-element-of-a-list/REBOL \ No newline at end of file diff --git a/Lang/REBOL/HTTP b/Lang/REBOL/HTTP deleted file mode 120000 index 7ade844f73..0000000000 --- a/Lang/REBOL/HTTP +++ /dev/null @@ -1 +0,0 @@ -../../Task/HTTP/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Hailstone-sequence b/Lang/REBOL/Hailstone-sequence deleted file mode 120000 index f668d98fe0..0000000000 --- a/Lang/REBOL/Hailstone-sequence +++ /dev/null @@ -1 +0,0 @@ -../../Task/Hailstone-sequence/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Hello-world-Graphical b/Lang/REBOL/Hello-world-Graphical deleted file mode 120000 index 65375f6063..0000000000 --- a/Lang/REBOL/Hello-world-Graphical +++ /dev/null @@ -1 +0,0 @@ -../../Task/Hello-world-Graphical/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Hello-world-Newline-omission b/Lang/REBOL/Hello-world-Newline-omission deleted file mode 120000 index a1ab230770..0000000000 --- a/Lang/REBOL/Hello-world-Newline-omission +++ /dev/null @@ -1 +0,0 @@ -../../Task/Hello-world-Newline-omission/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Hello-world-Text b/Lang/REBOL/Hello-world-Text deleted file mode 120000 index 417f675e90..0000000000 --- a/Lang/REBOL/Hello-world-Text +++ /dev/null @@ -1 +0,0 @@ -../../Task/Hello-world-Text/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Higher-order-functions b/Lang/REBOL/Higher-order-functions deleted file mode 120000 index e0da7764d4..0000000000 --- a/Lang/REBOL/Higher-order-functions +++ /dev/null @@ -1 +0,0 @@ -../../Task/Higher-order-functions/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Horners-rule-for-polynomial-evaluation b/Lang/REBOL/Horners-rule-for-polynomial-evaluation deleted file mode 120000 index 3ed4d272a6..0000000000 --- a/Lang/REBOL/Horners-rule-for-polynomial-evaluation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Horners-rule-for-polynomial-evaluation/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Hostname b/Lang/REBOL/Hostname deleted file mode 120000 index 00509fe88c..0000000000 --- a/Lang/REBOL/Hostname +++ /dev/null @@ -1 +0,0 @@ -../../Task/Hostname/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Increment-a-numerical-string b/Lang/REBOL/Increment-a-numerical-string deleted file mode 120000 index 0b8ae5b473..0000000000 --- a/Lang/REBOL/Increment-a-numerical-string +++ /dev/null @@ -1 +0,0 @@ -../../Task/Increment-a-numerical-string/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Inheritance-Single b/Lang/REBOL/Inheritance-Single deleted file mode 120000 index 8790c38450..0000000000 --- a/Lang/REBOL/Inheritance-Single +++ /dev/null @@ -1 +0,0 @@ -../../Task/Inheritance-Single/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Input-loop b/Lang/REBOL/Input-loop deleted file mode 120000 index 81d9914a81..0000000000 --- a/Lang/REBOL/Input-loop +++ /dev/null @@ -1 +0,0 @@ -../../Task/Input-loop/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Integer-comparison b/Lang/REBOL/Integer-comparison deleted file mode 120000 index 6f12d33801..0000000000 --- a/Lang/REBOL/Integer-comparison +++ /dev/null @@ -1 +0,0 @@ -../../Task/Integer-comparison/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Interactive-programming-repl- b/Lang/REBOL/Interactive-programming-repl- deleted file mode 120000 index a2a59ee516..0000000000 --- a/Lang/REBOL/Interactive-programming-repl- +++ /dev/null @@ -1 +0,0 @@ -../../Task/Interactive-programming-repl-/REBOL \ No newline at end of file diff --git a/Lang/REBOL/JSON b/Lang/REBOL/JSON deleted file mode 120000 index bbdd962074..0000000000 --- a/Lang/REBOL/JSON +++ /dev/null @@ -1 +0,0 @@ -../../Task/JSON/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Josephus-problem b/Lang/REBOL/Josephus-problem deleted file mode 120000 index d092745290..0000000000 --- a/Lang/REBOL/Josephus-problem +++ /dev/null @@ -1 +0,0 @@ -../../Task/Josephus-problem/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Keyboard-macros b/Lang/REBOL/Keyboard-macros deleted file mode 120000 index 4c918106f7..0000000000 --- a/Lang/REBOL/Keyboard-macros +++ /dev/null @@ -1 +0,0 @@ -../../Task/Keyboard-macros/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Knuth-shuffle b/Lang/REBOL/Knuth-shuffle deleted file mode 120000 index e1ef5ac835..0000000000 --- a/Lang/REBOL/Knuth-shuffle +++ /dev/null @@ -1 +0,0 @@ -../../Task/Knuth-shuffle/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Last-Friday-of-each-month b/Lang/REBOL/Last-Friday-of-each-month deleted file mode 120000 index 592b3befd7..0000000000 --- a/Lang/REBOL/Last-Friday-of-each-month +++ /dev/null @@ -1 +0,0 @@ -../../Task/Last-Friday-of-each-month/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Leap-year b/Lang/REBOL/Leap-year deleted file mode 120000 index e1fde0d2a0..0000000000 --- a/Lang/REBOL/Leap-year +++ /dev/null @@ -1 +0,0 @@ -../../Task/Leap-year/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Literals-Integer b/Lang/REBOL/Literals-Integer deleted file mode 120000 index c018808d2d..0000000000 --- a/Lang/REBOL/Literals-Integer +++ /dev/null @@ -1 +0,0 @@ -../../Task/Literals-Integer/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Logical-operations b/Lang/REBOL/Logical-operations deleted file mode 120000 index b2be03cb20..0000000000 --- a/Lang/REBOL/Logical-operations +++ /dev/null @@ -1 +0,0 @@ -../../Task/Logical-operations/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Loops-Break b/Lang/REBOL/Loops-Break deleted file mode 120000 index b12b588bcd..0000000000 --- a/Lang/REBOL/Loops-Break +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-Break/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Loops-Continue b/Lang/REBOL/Loops-Continue deleted file mode 120000 index 620f8d42c2..0000000000 --- a/Lang/REBOL/Loops-Continue +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-Continue/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Loops-Do-while b/Lang/REBOL/Loops-Do-while deleted file mode 120000 index a092621ef7..0000000000 --- a/Lang/REBOL/Loops-Do-while +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-Do-while/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Loops-Downward-for b/Lang/REBOL/Loops-Downward-for deleted file mode 120000 index e956288e68..0000000000 --- a/Lang/REBOL/Loops-Downward-for +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-Downward-for/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Loops-For b/Lang/REBOL/Loops-For deleted file mode 120000 index 9c59f991f0..0000000000 --- a/Lang/REBOL/Loops-For +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-For/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Loops-For-with-a-specified-step b/Lang/REBOL/Loops-For-with-a-specified-step deleted file mode 120000 index 3174e4899e..0000000000 --- a/Lang/REBOL/Loops-For-with-a-specified-step +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-For-with-a-specified-step/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Loops-Foreach b/Lang/REBOL/Loops-Foreach deleted file mode 120000 index 98cc61392e..0000000000 --- a/Lang/REBOL/Loops-Foreach +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-Foreach/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Loops-Infinite b/Lang/REBOL/Loops-Infinite deleted file mode 120000 index cd80f1fc2f..0000000000 --- a/Lang/REBOL/Loops-Infinite +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-Infinite/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Loops-N-plus-one-half b/Lang/REBOL/Loops-N-plus-one-half deleted file mode 120000 index 530a004b19..0000000000 --- a/Lang/REBOL/Loops-N-plus-one-half +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-N-plus-one-half/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Loops-Nested b/Lang/REBOL/Loops-Nested deleted file mode 120000 index fad704e1b5..0000000000 --- a/Lang/REBOL/Loops-Nested +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-Nested/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Loops-While b/Lang/REBOL/Loops-While deleted file mode 120000 index 7caecdb43d..0000000000 --- a/Lang/REBOL/Loops-While +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-While/REBOL \ No newline at end of file diff --git a/Lang/REBOL/MD5 b/Lang/REBOL/MD5 deleted file mode 120000 index 5cb019110c..0000000000 --- a/Lang/REBOL/MD5 +++ /dev/null @@ -1 +0,0 @@ -../../Task/MD5/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Mad-Libs b/Lang/REBOL/Mad-Libs deleted file mode 120000 index db4b8d6171..0000000000 --- a/Lang/REBOL/Mad-Libs +++ /dev/null @@ -1 +0,0 @@ -../../Task/Mad-Libs/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Menu b/Lang/REBOL/Menu deleted file mode 120000 index 3b0b7dc2de..0000000000 --- a/Lang/REBOL/Menu +++ /dev/null @@ -1 +0,0 @@ -../../Task/Menu/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Multiplication-tables b/Lang/REBOL/Multiplication-tables deleted file mode 120000 index 1b70d39ee9..0000000000 --- a/Lang/REBOL/Multiplication-tables +++ /dev/null @@ -1 +0,0 @@ -../../Task/Multiplication-tables/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Mutual-recursion b/Lang/REBOL/Mutual-recursion deleted file mode 120000 index cb2de22d29..0000000000 --- a/Lang/REBOL/Mutual-recursion +++ /dev/null @@ -1 +0,0 @@ -../../Task/Mutual-recursion/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Null-object b/Lang/REBOL/Null-object deleted file mode 120000 index 0b324069d2..0000000000 --- a/Lang/REBOL/Null-object +++ /dev/null @@ -1 +0,0 @@ -../../Task/Null-object/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Number-reversal-game b/Lang/REBOL/Number-reversal-game deleted file mode 120000 index a23e4203b5..0000000000 --- a/Lang/REBOL/Number-reversal-game +++ /dev/null @@ -1 +0,0 @@ -../../Task/Number-reversal-game/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Palindrome-detection b/Lang/REBOL/Palindrome-detection deleted file mode 120000 index 45e3490dd4..0000000000 --- a/Lang/REBOL/Palindrome-detection +++ /dev/null @@ -1 +0,0 @@ -../../Task/Palindrome-detection/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Percentage-difference-between-images b/Lang/REBOL/Percentage-difference-between-images deleted file mode 120000 index 47e0c29027..0000000000 --- a/Lang/REBOL/Percentage-difference-between-images +++ /dev/null @@ -1 +0,0 @@ -../../Task/Percentage-difference-between-images/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Perfect-numbers b/Lang/REBOL/Perfect-numbers deleted file mode 120000 index 888589d0dd..0000000000 --- a/Lang/REBOL/Perfect-numbers +++ /dev/null @@ -1 +0,0 @@ -../../Task/Perfect-numbers/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Primality-by-trial-division b/Lang/REBOL/Primality-by-trial-division deleted file mode 120000 index 6e14471054..0000000000 --- a/Lang/REBOL/Primality-by-trial-division +++ /dev/null @@ -1 +0,0 @@ -../../Task/Primality-by-trial-division/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Program-termination b/Lang/REBOL/Program-termination deleted file mode 120000 index 7c4ce8b3c8..0000000000 --- a/Lang/REBOL/Program-termination +++ /dev/null @@ -1 +0,0 @@ -../../Task/Program-termination/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Queue-Definition b/Lang/REBOL/Queue-Definition deleted file mode 120000 index aa21697e36..0000000000 --- a/Lang/REBOL/Queue-Definition +++ /dev/null @@ -1 +0,0 @@ -../../Task/Queue-Definition/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Queue-Usage b/Lang/REBOL/Queue-Usage deleted file mode 120000 index 488c4682f8..0000000000 --- a/Lang/REBOL/Queue-Usage +++ /dev/null @@ -1 +0,0 @@ -../../Task/Queue-Usage/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Quine b/Lang/REBOL/Quine deleted file mode 120000 index 391f27dc9c..0000000000 --- a/Lang/REBOL/Quine +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quine/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Read-a-specific-line-from-a-file b/Lang/REBOL/Read-a-specific-line-from-a-file deleted file mode 120000 index fc3cb7c086..0000000000 --- a/Lang/REBOL/Read-a-specific-line-from-a-file +++ /dev/null @@ -1 +0,0 @@ -../../Task/Read-a-specific-line-from-a-file/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Read-entire-file b/Lang/REBOL/Read-entire-file deleted file mode 120000 index 8d1ffdb8c8..0000000000 --- a/Lang/REBOL/Read-entire-file +++ /dev/null @@ -1 +0,0 @@ -../../Task/Read-entire-file/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Regular-expressions b/Lang/REBOL/Regular-expressions deleted file mode 120000 index cc056f3dfc..0000000000 --- a/Lang/REBOL/Regular-expressions +++ /dev/null @@ -1 +0,0 @@ -../../Task/Regular-expressions/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Remove-duplicate-elements b/Lang/REBOL/Remove-duplicate-elements deleted file mode 120000 index 989597f93c..0000000000 --- a/Lang/REBOL/Remove-duplicate-elements +++ /dev/null @@ -1 +0,0 @@ -../../Task/Remove-duplicate-elements/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Rename-a-file b/Lang/REBOL/Rename-a-file deleted file mode 120000 index d5b1f76dba..0000000000 --- a/Lang/REBOL/Rename-a-file +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rename-a-file/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Repeat-a-string b/Lang/REBOL/Repeat-a-string deleted file mode 120000 index df3bda003c..0000000000 --- a/Lang/REBOL/Repeat-a-string +++ /dev/null @@ -1 +0,0 @@ -../../Task/Repeat-a-string/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Reverse-a-string b/Lang/REBOL/Reverse-a-string deleted file mode 120000 index 4fa66fa042..0000000000 --- a/Lang/REBOL/Reverse-a-string +++ /dev/null @@ -1 +0,0 @@ -../../Task/Reverse-a-string/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Rot-13 b/Lang/REBOL/Rot-13 deleted file mode 120000 index 344b9949b8..0000000000 --- a/Lang/REBOL/Rot-13 +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rot-13/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Runtime-evaluation b/Lang/REBOL/Runtime-evaluation deleted file mode 120000 index 4f29a7904a..0000000000 --- a/Lang/REBOL/Runtime-evaluation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Runtime-evaluation/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Runtime-evaluation-In-an-environment b/Lang/REBOL/Runtime-evaluation-In-an-environment deleted file mode 120000 index 00ac88948d..0000000000 --- a/Lang/REBOL/Runtime-evaluation-In-an-environment +++ /dev/null @@ -1 +0,0 @@ -../../Task/Runtime-evaluation-In-an-environment/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Search-a-list b/Lang/REBOL/Search-a-list deleted file mode 120000 index 30c4450829..0000000000 --- a/Lang/REBOL/Search-a-list +++ /dev/null @@ -1 +0,0 @@ -../../Task/Search-a-list/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Send-email b/Lang/REBOL/Send-email deleted file mode 120000 index 7a102c33ea..0000000000 --- a/Lang/REBOL/Send-email +++ /dev/null @@ -1 +0,0 @@ -../../Task/Send-email/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Shell-one-liner b/Lang/REBOL/Shell-one-liner deleted file mode 120000 index 3efd76bee3..0000000000 --- a/Lang/REBOL/Shell-one-liner +++ /dev/null @@ -1 +0,0 @@ -../../Task/Shell-one-liner/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Simple-database b/Lang/REBOL/Simple-database deleted file mode 120000 index 2171f3e8b2..0000000000 --- a/Lang/REBOL/Simple-database +++ /dev/null @@ -1 +0,0 @@ -../../Task/Simple-database/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Simple-windowed-application b/Lang/REBOL/Simple-windowed-application deleted file mode 120000 index 3eb2f5011a..0000000000 --- a/Lang/REBOL/Simple-windowed-application +++ /dev/null @@ -1 +0,0 @@ -../../Task/Simple-windowed-application/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Sleep b/Lang/REBOL/Sleep deleted file mode 120000 index 49498dee8f..0000000000 --- a/Lang/REBOL/Sleep +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sleep/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Sort-an-integer-array b/Lang/REBOL/Sort-an-integer-array deleted file mode 120000 index be40906bd3..0000000000 --- a/Lang/REBOL/Sort-an-integer-array +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sort-an-integer-array/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Sort-stability b/Lang/REBOL/Sort-stability deleted file mode 120000 index 7a6119bc4e..0000000000 --- a/Lang/REBOL/Sort-stability +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sort-stability/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Sorting-algorithms-Insertion-sort b/Lang/REBOL/Sorting-algorithms-Insertion-sort deleted file mode 120000 index 5a9f9f2f24..0000000000 --- a/Lang/REBOL/Sorting-algorithms-Insertion-sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-algorithms-Insertion-sort/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Stack b/Lang/REBOL/Stack deleted file mode 120000 index 70bb3936ee..0000000000 --- a/Lang/REBOL/Stack +++ /dev/null @@ -1 +0,0 @@ -../../Task/Stack/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Stair-climbing-puzzle b/Lang/REBOL/Stair-climbing-puzzle deleted file mode 120000 index 935f1a3925..0000000000 --- a/Lang/REBOL/Stair-climbing-puzzle +++ /dev/null @@ -1 +0,0 @@ -../../Task/Stair-climbing-puzzle/REBOL \ No newline at end of file diff --git a/Lang/REBOL/String-case b/Lang/REBOL/String-case deleted file mode 120000 index 2279191d8d..0000000000 --- a/Lang/REBOL/String-case +++ /dev/null @@ -1 +0,0 @@ -../../Task/String-case/REBOL \ No newline at end of file diff --git a/Lang/REBOL/String-concatenation b/Lang/REBOL/String-concatenation deleted file mode 120000 index 8be78ed69f..0000000000 --- a/Lang/REBOL/String-concatenation +++ /dev/null @@ -1 +0,0 @@ -../../Task/String-concatenation/REBOL \ No newline at end of file diff --git a/Lang/REBOL/String-interpolation-included- b/Lang/REBOL/String-interpolation-included- deleted file mode 120000 index 1158cc37bc..0000000000 --- a/Lang/REBOL/String-interpolation-included- +++ /dev/null @@ -1 +0,0 @@ -../../Task/String-interpolation-included-/REBOL \ No newline at end of file diff --git a/Lang/REBOL/String-length b/Lang/REBOL/String-length deleted file mode 120000 index 06c8f5cbd6..0000000000 --- a/Lang/REBOL/String-length +++ /dev/null @@ -1 +0,0 @@ -../../Task/String-length/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Substring b/Lang/REBOL/Substring deleted file mode 120000 index ae87eb5a53..0000000000 --- a/Lang/REBOL/Substring +++ /dev/null @@ -1 +0,0 @@ -../../Task/Substring/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Sum-and-product-of-an-array b/Lang/REBOL/Sum-and-product-of-an-array deleted file mode 120000 index 5ce08d6535..0000000000 --- a/Lang/REBOL/Sum-and-product-of-an-array +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sum-and-product-of-an-array/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Symmetric-difference b/Lang/REBOL/Symmetric-difference deleted file mode 120000 index 27c9c680ad..0000000000 --- a/Lang/REBOL/Symmetric-difference +++ /dev/null @@ -1 +0,0 @@ -../../Task/Symmetric-difference/REBOL \ No newline at end of file diff --git a/Lang/REBOL/System-time b/Lang/REBOL/System-time deleted file mode 120000 index 7ea31d4a27..0000000000 --- a/Lang/REBOL/System-time +++ /dev/null @@ -1 +0,0 @@ -../../Task/System-time/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Take-notes-on-the-command-line b/Lang/REBOL/Take-notes-on-the-command-line deleted file mode 120000 index f00a0f5d0a..0000000000 --- a/Lang/REBOL/Take-notes-on-the-command-line +++ /dev/null @@ -1 +0,0 @@ -../../Task/Take-notes-on-the-command-line/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Tokenize-a-string b/Lang/REBOL/Tokenize-a-string deleted file mode 120000 index ee10fb0551..0000000000 --- a/Lang/REBOL/Tokenize-a-string +++ /dev/null @@ -1 +0,0 @@ -../../Task/Tokenize-a-string/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Towers-of-Hanoi b/Lang/REBOL/Towers-of-Hanoi deleted file mode 120000 index a173272546..0000000000 --- a/Lang/REBOL/Towers-of-Hanoi +++ /dev/null @@ -1 +0,0 @@ -../../Task/Towers-of-Hanoi/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Tree-traversal b/Lang/REBOL/Tree-traversal deleted file mode 120000 index 0c44bbca9b..0000000000 --- a/Lang/REBOL/Tree-traversal +++ /dev/null @@ -1 +0,0 @@ -../../Task/Tree-traversal/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Trigonometric-functions b/Lang/REBOL/Trigonometric-functions deleted file mode 120000 index 8f4c11188c..0000000000 --- a/Lang/REBOL/Trigonometric-functions +++ /dev/null @@ -1 +0,0 @@ -../../Task/Trigonometric-functions/REBOL \ No newline at end of file diff --git a/Lang/REBOL/User-input-Graphical b/Lang/REBOL/User-input-Graphical deleted file mode 120000 index 001538e055..0000000000 --- a/Lang/REBOL/User-input-Graphical +++ /dev/null @@ -1 +0,0 @@ -../../Task/User-input-Graphical/REBOL \ No newline at end of file diff --git a/Lang/REBOL/User-input-Text b/Lang/REBOL/User-input-Text deleted file mode 120000 index b81fcf9c85..0000000000 --- a/Lang/REBOL/User-input-Text +++ /dev/null @@ -1 +0,0 @@ -../../Task/User-input-Text/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Variadic-function b/Lang/REBOL/Variadic-function deleted file mode 120000 index c3eb7c285d..0000000000 --- a/Lang/REBOL/Variadic-function +++ /dev/null @@ -1 +0,0 @@ -../../Task/Variadic-function/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Web-scraping b/Lang/REBOL/Web-scraping deleted file mode 120000 index 4c37db2bfe..0000000000 --- a/Lang/REBOL/Web-scraping +++ /dev/null @@ -1 +0,0 @@ -../../Task/Web-scraping/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Window-creation b/Lang/REBOL/Window-creation deleted file mode 120000 index d3c3450624..0000000000 --- a/Lang/REBOL/Window-creation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Window-creation/REBOL \ No newline at end of file diff --git a/Lang/REBOL/XML-Input b/Lang/REBOL/XML-Input deleted file mode 120000 index f96cb4fd5e..0000000000 --- a/Lang/REBOL/XML-Input +++ /dev/null @@ -1 +0,0 @@ -../../Task/XML-Input/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Y-combinator b/Lang/REBOL/Y-combinator deleted file mode 120000 index 492c58627d..0000000000 --- a/Lang/REBOL/Y-combinator +++ /dev/null @@ -1 +0,0 @@ -../../Task/Y-combinator/REBOL \ No newline at end of file diff --git a/Lang/REXX/00-LANG.txt b/Lang/REXX/00-LANG.txt index 26a483d9aa..592349f719 100644 --- a/Lang/REXX/00-LANG.txt +++ b/Lang/REXX/00-LANG.txt @@ -26,6 +26,21 @@ The '''REXX''' language was influenced by the computer programming languages:   '''ALGOL,   PL/I,   EXEC,'''  and  '''EXEC 2.''' +Using Classic REXX closely resembles pseudo code and many languages like Basic or Julia. Experienced programmers should have no problem reading REXX code and translating it to other languages.
    +Some items that might differ from what you are familiar with.
    +* Caseless, fully free format. +* Code blocks delimited by do...end, no brackets (){}. +* A programs starts always with line 1, so you'll need 'exit' before the code for procedures and routines. +* Usual control structures present: do...by...to, do while/until, select, leave, iterate, call, return, exit, & (and), \ (not). +* No data types, no declarations, everything is string. String functions such as 'Left()' or 'Substr()' may be applied on numbers. +* All arithmetic is decimal based, not binary. So stuff like bit shifting or multiply/divide by 2 using exponent add/subtract does not apply. +* Exponentiation is designated by '**' thus x^2 = x**2. +* Integer division is designated by '%' thus 13%3 = 4. +* Modulo division (remainder) is designated by '//' thus 13//3 = 1 ('13 mod 3'). +* Arrays (here called 'stems') are designated by something like 'stem.a.b. etc' (stem = name array; a, b etc any value; 'associative arrays'). +* Precision is unlimited (default 9 digits), but you have to specify it yourself ('numeric digits nn'). +* Parameter passing always by value. Stems cannot be passed, but must be made available with 'expose'. + Versions of REXX: * '''[[wp:ARexx|ARexx]]'''   is a classic REXX implementation (with extensions) for the AmigaOS,   given in bundle since AmigaOS 2.   (Regina REXX has specific support for the extended functions that were introduced in ARexx.)   ARexx was written in 1987 by William S. Hawes. @@ -36,7 +51,7 @@ The '''REXX''' language was influenced by the computer programming languages: &n * '''[[CRX REXX]]'''   (Compact REXX) is a classic REXX first written by Dr. Brian Marks. -* '''[[CTC REXX]]'''   is a classic REXX that is bundled with PC/SPF and written by Command Technology Corporation,   a license is required to use this product.   This version of REXX can only be used under PC/SPF and it's panels.   PC/SPF resembles the IBM program product SPF (which has other names and versions). +* '''[[REXX/2]]'''   is a classic REXX that is bundled with PC/SPF and written by Command Technology Corporation,   a license is required to use this product.   This version of REXX can only be used under PC/SPF and it's panels.   PC/SPF resembles the IBM program product SPF (which has other names and versions). The last version was published in 1996. Company CTC doesn't exist anymore. * '''[[KEXX]]'''   is a subset of REXX that is bundled with KEDIT and written by Keven J. Kearney of Mansfield Software Group, Inc., a license is required to use this product.   KEXX only executes under the KEDIT licensed product.   KEDIT is an XEDIT clone (an editor from IBM for VM/CMS program products). @@ -75,7 +90,7 @@ The '''REXX''' language was influenced by the computer programming languages: &n * '''[[Regina REXX]]'''   is an implementation first created by Anders Christensen (in 1992) and is now maintained by others, notably Mark Hessling.   Regina REXX runs on more different platforms than any other REXX,   too many to name here.   It can be downloaded freely. -* '''[[Reginald REXX]]'''   is a REXX developed by Jeff Glatt.   It can be downloaded freely. +* '''[[Reginald REXX]]'''   is a REXX developed by Jeff Glatt.   It can be downloaded freely. According to Rexxinfo.org, Reginald is out of maintenance. * '''[[REXX/imc]]'''   a classic REXX developed by Ian M. Collier (imc) for Linux/Unix. @@ -84,10 +99,10 @@ The '''REXX''' language was influenced by the computer programming languages: &n * '''REXX/Personal'''   is another name for   '''Personal REXX'''     (see above). -* '''[[ROO oo-REXX]]'''   an object-oriented REXX developed by Keith Watts of Kilowatt Software, Inc.     It can be downloaded freely.   '''ROO'''   is also known as   '''ROO!'''. +* '''[[ROO oo-REXX]]'''   an object-oriented REXX developed by Keith Watts of Kilowatt Software, Inc.     It can be downloaded freely.   '''ROO'''   is also known as   '''ROO!'''. According to Rexxinfo.org, Roo! is out of maintenance. -* '''[[R4 REXX]]'''   a classic REXX developed by Keith Watts of Kilowatt Software, Inc.     It was also known as '''Portable REXX'''.   It can be downloaded freely. +* '''[[R4 REXX]]'''   a classic REXX developed by Keith Watts of Kilowatt Software, Inc.     It was also known as '''Portable REXX'''.   It can be downloaded freely. According to Rexxinfo.org, R4 is out of maintenance. * '''[[T/REXX, a REXX compiler for CMS]]'''   is an implementation of classic REXX written by Leigh Lundin and Mark Woodruff   (according to Wikipedia). @@ -112,16 +127,7 @@ The '''REXX''' language was influenced by the computer programming languages: &n * [http://www.rexxla.org The Rexx Language Association - www.rexxla.org] * [http://regina-rexx.sourceforge.net/index.html Regina Rexx Interpreter] * [http://www.kedit.com/ Mansfield Software Group, Inc. (KEDIT)] -* [http://www.quercus-sys.com/ Personal REXX, Quercus Systems] -* [http://www.commandtechnology.com/ CTC Command Technology] * [http://www.rexxla.org/ CRX Open Source (right column side)] -* [http://www.kilowattsoftware.com/r4Page.htm R4, Kilowatt Software] -* [http://www.kilowattsoftware.com/rooPage.htm ROO, Kilowatt Software] -* [http://publib.boulder.ibm.com/cgi-bin/bookmgr_OS390/BOOKS/HCSE2C00/CCONTENTS?SHELF=hcsh2ab0&DN=SC24-6221-00&DT=20090724140455 z/VM V6R1 REXX/VM Reference] -* [http://publib.boulder.ibm.com/cgi-bin/bookmgr_OS390/BOOKS/HCSB3C00/CCONTENTS?SHELF=hcsh2ab0&DN=SC24-6222-00&DT=20090724131829 z/VM V6R1 REXX/VM User's Guide] -* [http://www.rexxinfo.org/html/rexxinfo1.html#Rexx-Manuals {many references to REXX manuals}] - - == Rosetta Code tasks not implemented in REXX == -[[Reports:Tasks_not_implemented_in_REXX]] \ No newline at end of file +[[Tasks not implemented in REXX]] \ No newline at end of file diff --git a/Lang/REXX/Arithmetic-numbers b/Lang/REXX/Arithmetic-numbers new file mode 120000 index 0000000000..71a3332017 --- /dev/null +++ b/Lang/REXX/Arithmetic-numbers @@ -0,0 +1 @@ +../../Task/Arithmetic-numbers/REXX \ No newline at end of file diff --git a/Lang/REXX/Ascending-primes b/Lang/REXX/Ascending-primes new file mode 120000 index 0000000000..bbc0af4983 --- /dev/null +++ b/Lang/REXX/Ascending-primes @@ -0,0 +1 @@ +../../Task/Ascending-primes/REXX \ No newline at end of file diff --git a/Lang/REXX/Base64-decode-data b/Lang/REXX/Base64-decode-data new file mode 120000 index 0000000000..226b0ce798 --- /dev/null +++ b/Lang/REXX/Base64-decode-data @@ -0,0 +1 @@ +../../Task/Base64-decode-data/REXX \ No newline at end of file diff --git a/Lang/REXX/Bioinformatics-base-count b/Lang/REXX/Bioinformatics-base-count deleted file mode 120000 index c722864481..0000000000 --- a/Lang/REXX/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/REXX \ No newline at end of file diff --git a/Lang/REXX/Blum-integer b/Lang/REXX/Blum-integer new file mode 120000 index 0000000000..2aa27c2ff0 --- /dev/null +++ b/Lang/REXX/Blum-integer @@ -0,0 +1 @@ +../../Task/Blum-integer/REXX \ No newline at end of file diff --git a/Lang/REXX/Chernicks-Carmichael-numbers b/Lang/REXX/Chernicks-Carmichael-numbers new file mode 120000 index 0000000000..4050cb562e --- /dev/null +++ b/Lang/REXX/Chernicks-Carmichael-numbers @@ -0,0 +1 @@ +../../Task/Chernicks-Carmichael-numbers/REXX \ No newline at end of file diff --git a/Lang/REXX/Deceptive-numbers b/Lang/REXX/Deceptive-numbers new file mode 120000 index 0000000000..3f3cdd6f00 --- /dev/null +++ b/Lang/REXX/Deceptive-numbers @@ -0,0 +1 @@ +../../Task/Deceptive-numbers/REXX \ No newline at end of file diff --git a/Lang/REXX/Descending-primes b/Lang/REXX/Descending-primes new file mode 120000 index 0000000000..c55d765868 --- /dev/null +++ b/Lang/REXX/Descending-primes @@ -0,0 +1 @@ +../../Task/Descending-primes/REXX \ No newline at end of file diff --git a/Lang/REXX/Euclid-Mullin-sequence b/Lang/REXX/Euclid-Mullin-sequence new file mode 120000 index 0000000000..3ded1fce93 --- /dev/null +++ b/Lang/REXX/Euclid-Mullin-sequence @@ -0,0 +1 @@ +../../Task/Euclid-Mullin-sequence/REXX \ No newline at end of file diff --git a/Lang/REXX/Eulers-constant-0.5772... b/Lang/REXX/Eulers-constant-0.5772... new file mode 120000 index 0000000000..4dd79a59f3 --- /dev/null +++ b/Lang/REXX/Eulers-constant-0.5772... @@ -0,0 +1 @@ +../../Task/Eulers-constant-0.5772.../REXX \ No newline at end of file diff --git a/Lang/REXX/Find-largest-left-truncatable-prime-in-a-given-base b/Lang/REXX/Find-largest-left-truncatable-prime-in-a-given-base new file mode 120000 index 0000000000..528dd8a890 --- /dev/null +++ b/Lang/REXX/Find-largest-left-truncatable-prime-in-a-given-base @@ -0,0 +1 @@ +../../Task/Find-largest-left-truncatable-prime-in-a-given-base/REXX \ No newline at end of file diff --git a/Lang/REXX/Goldbachs-comet b/Lang/REXX/Goldbachs-comet new file mode 120000 index 0000000000..ddf76b927f --- /dev/null +++ b/Lang/REXX/Goldbachs-comet @@ -0,0 +1 @@ +../../Task/Goldbachs-comet/REXX \ No newline at end of file diff --git a/Lang/REXX/Jacobsthal-numbers b/Lang/REXX/Jacobsthal-numbers new file mode 120000 index 0000000000..7f86ce7033 --- /dev/null +++ b/Lang/REXX/Jacobsthal-numbers @@ -0,0 +1 @@ +../../Task/Jacobsthal-numbers/REXX \ No newline at end of file diff --git a/Lang/REXX/Legendre-prime-counting-function b/Lang/REXX/Legendre-prime-counting-function new file mode 120000 index 0000000000..74d1b424e1 --- /dev/null +++ b/Lang/REXX/Legendre-prime-counting-function @@ -0,0 +1 @@ +../../Task/Legendre-prime-counting-function/REXX \ No newline at end of file diff --git a/Lang/REXX/Magic-constant b/Lang/REXX/Magic-constant new file mode 120000 index 0000000000..13d81a62dd --- /dev/null +++ b/Lang/REXX/Magic-constant @@ -0,0 +1 @@ +../../Task/Magic-constant/REXX \ No newline at end of file diff --git a/Lang/REXX/Miller-Rabin-primality-test b/Lang/REXX/Miller-Rabin-primality-test deleted file mode 120000 index 6b9607754b..0000000000 --- a/Lang/REXX/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/REXX \ No newline at end of file diff --git a/Lang/REXX/Primes---allocate-descendants-to-their-ancestors b/Lang/REXX/Primes---allocate-descendants-to-their-ancestors new file mode 120000 index 0000000000..e6293c9090 --- /dev/null +++ b/Lang/REXX/Primes---allocate-descendants-to-their-ancestors @@ -0,0 +1 @@ +../../Task/Primes---allocate-descendants-to-their-ancestors/REXX \ No newline at end of file diff --git a/Lang/REXX/Quaternion-type b/Lang/REXX/Quaternion-type deleted file mode 120000 index 18e452fac4..0000000000 --- a/Lang/REXX/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/REXX \ No newline at end of file diff --git a/Lang/REXX/Ramanujan-primes-twins b/Lang/REXX/Ramanujan-primes-twins new file mode 120000 index 0000000000..09da3d7f76 --- /dev/null +++ b/Lang/REXX/Ramanujan-primes-twins @@ -0,0 +1 @@ +../../Task/Ramanujan-primes-twins/REXX \ No newline at end of file diff --git a/Lang/REXX/Sequence-of-primorial-primes b/Lang/REXX/Sequence-of-primorial-primes new file mode 120000 index 0000000000..cd4ebe8c73 --- /dev/null +++ b/Lang/REXX/Sequence-of-primorial-primes @@ -0,0 +1 @@ +../../Task/Sequence-of-primorial-primes/REXX \ No newline at end of file diff --git a/Lang/REXX/Sieve-of-Pritchard b/Lang/REXX/Sieve-of-Pritchard new file mode 120000 index 0000000000..601b18d906 --- /dev/null +++ b/Lang/REXX/Sieve-of-Pritchard @@ -0,0 +1 @@ +../../Task/Sieve-of-Pritchard/REXX \ No newline at end of file diff --git a/Lang/REXX/Sorting-Algorithms-Circle-Sort b/Lang/REXX/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 383d356065..0000000000 --- a/Lang/REXX/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/REXX \ No newline at end of file diff --git a/Lang/REXX/Verhoeff-algorithm b/Lang/REXX/Verhoeff-algorithm new file mode 120000 index 0000000000..0bc439ccea --- /dev/null +++ b/Lang/REXX/Verhoeff-algorithm @@ -0,0 +1 @@ +../../Task/Verhoeff-algorithm/REXX \ No newline at end of file diff --git a/Lang/REXX/Web-scraping b/Lang/REXX/Web-scraping new file mode 120000 index 0000000000..818c9c985e --- /dev/null +++ b/Lang/REXX/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/REXX \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/00-LANG.txt b/Lang/RISC-V-Assembly/00-LANG.txt index f524ed95fb..3f4a6ea98e 100644 --- a/Lang/RISC-V-Assembly/00-LANG.txt +++ b/Lang/RISC-V-Assembly/00-LANG.txt @@ -1,4 +1,79 @@ {{language|RISC-V Assembly}}[https://riscv.org Risc-V] is an open source hardware instruction set architecture based on the principle of a '''R'''educed '''I'''nstruction '''S'''et '''C'''omputer. The project was started by the university of California, Berkeley in 2010. This site refers to the Risc-V assembly language. ([https://en.wikipedia.org/wiki/RISC-V#Software Wikipedia page]), Website: [https://riscv.org https://riscv.org]. +'''Riscv on raspberry pico 2''' + +A pico2 with the chip rp2335 contains 2 cores hazard3 with risc v assembly +it is possible to programm assembly riscv with the sdk C++ and a compiler riscv32-unknown-elf-as.exe + +It is also possible to programm without SDK but it is necessary to write functions for init +the clocks and to communicate for usb connexion. + +install under Windows11 (or see documentation raspberry py pico SDK) : + +Create main folder (ex : \pico2) + +install SDK C++ (see instructions in raspberry pi pico2 SDK documentation) + +install toolchaine under \Pico2\tools\bin from + +https://github.com/raspberrypi/pico-sdk-tools/releases/download/v2.0.0-2/riscv-toolchain-14-x64-win.zip + + +Create work folder (ex : \pico2\hello) + +Create file CMakeLists.txt (see instructions in raspberry pi pico2 SDK documentation) + +Create program hello.s with a editor + +Copy a file pico_sdk_import.cmake from \pico2\pico-sdk\external + +Create a folder build under \pico2\hello + +Go to this folder + +Compile program with : + + cmake -DPICO_PLATFORM=rp2350-riscv -DPICO_TOOLCHAIN_PATH=E:\Pico2\tools\bin -G "NMake Makefiles" .. + +and + nmake + +copy the file .uf2 to raspberry pico2 (see documentation raspberry pi pico2) + +Start serial connexion on host (ex: putty on windows11) + +Example CMakeLists.txt : + +cmake_minimum_required(VERSION 3.13) + +include(pico_sdk_import.cmake) + +project(hello C CXX ASM) + +set(CMAKE_C_STANDARD 11) + +set(CMAKE_CXX_STANDARD 17) + +pico_sdk_init() + +add_executable(hello +hello.s # pgm source assembly riscv +) + +target_link_libraries(hello pico_stdlib) + +pico_enable_stdio_usb(hello 1) + +pico_enable_stdio_uart(hello 0) + +pico_add_extra_outputs(hello) + + +see source program on hello world rosetta code + +cmake -DPython3_EXECUTABLE=C:\Users\Vincent\AppData\Local\Microsoft\WindowsApps\python3.10.exe -DPICO_PLATFORM=rp2350-riscv -DPICO_TOOLCHAIN_PATH=E:\Pico2\tools\bin -DPICO_SDK_PATH=..\..\..\pico-sdk -G "NMake Makefiles" .. + +see instructions list on chapter 3.8.1.6. Alphabetical list of instructions on rp2350 datasheet + [[Category:Assembler language]] [[Category:Assembly]] \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/Address-of-a-variable b/Lang/RISC-V-Assembly/Address-of-a-variable new file mode 120000 index 0000000000..7e7b85f7fc --- /dev/null +++ b/Lang/RISC-V-Assembly/Address-of-a-variable @@ -0,0 +1 @@ +../../Task/Address-of-a-variable/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/Arithmetic-Integer b/Lang/RISC-V-Assembly/Arithmetic-Integer new file mode 120000 index 0000000000..41172f4754 --- /dev/null +++ b/Lang/RISC-V-Assembly/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/Array-length b/Lang/RISC-V-Assembly/Array-length new file mode 120000 index 0000000000..51b567c37e --- /dev/null +++ b/Lang/RISC-V-Assembly/Array-length @@ -0,0 +1 @@ +../../Task/Array-length/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/Binary-digits b/Lang/RISC-V-Assembly/Binary-digits new file mode 120000 index 0000000000..45c4e871d7 --- /dev/null +++ b/Lang/RISC-V-Assembly/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/Binary-search b/Lang/RISC-V-Assembly/Binary-search new file mode 120000 index 0000000000..ad0fc6f909 --- /dev/null +++ b/Lang/RISC-V-Assembly/Binary-search @@ -0,0 +1 @@ +../../Task/Binary-search/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/Bitwise-operations b/Lang/RISC-V-Assembly/Bitwise-operations new file mode 120000 index 0000000000..d2de2c0d91 --- /dev/null +++ b/Lang/RISC-V-Assembly/Bitwise-operations @@ -0,0 +1 @@ +../../Task/Bitwise-operations/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/Compare-length-of-two-strings b/Lang/RISC-V-Assembly/Compare-length-of-two-strings new file mode 120000 index 0000000000..b61a06982a --- /dev/null +++ b/Lang/RISC-V-Assembly/Compare-length-of-two-strings @@ -0,0 +1 @@ +../../Task/Compare-length-of-two-strings/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/Conditional-structures b/Lang/RISC-V-Assembly/Conditional-structures new file mode 120000 index 0000000000..2fb608a736 --- /dev/null +++ b/Lang/RISC-V-Assembly/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/Count-in-octal b/Lang/RISC-V-Assembly/Count-in-octal new file mode 120000 index 0000000000..bf7e472328 --- /dev/null +++ b/Lang/RISC-V-Assembly/Count-in-octal @@ -0,0 +1 @@ +../../Task/Count-in-octal/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/Determine-if-a-string-is-numeric b/Lang/RISC-V-Assembly/Determine-if-a-string-is-numeric new file mode 120000 index 0000000000..fe9d1269a0 --- /dev/null +++ b/Lang/RISC-V-Assembly/Determine-if-a-string-is-numeric @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-numeric/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/Doubly-linked-list-Definition b/Lang/RISC-V-Assembly/Doubly-linked-list-Definition new file mode 120000 index 0000000000..f016184b4e --- /dev/null +++ b/Lang/RISC-V-Assembly/Doubly-linked-list-Definition @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Definition/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/Factorial b/Lang/RISC-V-Assembly/Factorial new file mode 120000 index 0000000000..d4cbcd152f --- /dev/null +++ b/Lang/RISC-V-Assembly/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/Factors-of-an-integer b/Lang/RISC-V-Assembly/Factors-of-an-integer new file mode 120000 index 0000000000..e6286a7691 --- /dev/null +++ b/Lang/RISC-V-Assembly/Factors-of-an-integer @@ -0,0 +1 @@ +../../Task/Factors-of-an-integer/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/FizzBuzz b/Lang/RISC-V-Assembly/FizzBuzz new file mode 120000 index 0000000000..fa85a0bece --- /dev/null +++ b/Lang/RISC-V-Assembly/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/Guess-the-number b/Lang/RISC-V-Assembly/Guess-the-number new file mode 120000 index 0000000000..3c820e8397 --- /dev/null +++ b/Lang/RISC-V-Assembly/Guess-the-number @@ -0,0 +1 @@ +../../Task/Guess-the-number/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/Hello-world-Newbie b/Lang/RISC-V-Assembly/Hello-world-Newbie new file mode 120000 index 0000000000..5721ad4125 --- /dev/null +++ b/Lang/RISC-V-Assembly/Hello-world-Newbie @@ -0,0 +1 @@ +../../Task/Hello-world-Newbie/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/Include-a-file b/Lang/RISC-V-Assembly/Include-a-file new file mode 120000 index 0000000000..2742cb0a60 --- /dev/null +++ b/Lang/RISC-V-Assembly/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/Integer-comparison b/Lang/RISC-V-Assembly/Integer-comparison new file mode 120000 index 0000000000..c89ef738d7 --- /dev/null +++ b/Lang/RISC-V-Assembly/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/Jump-anywhere b/Lang/RISC-V-Assembly/Jump-anywhere new file mode 120000 index 0000000000..97bc1d7493 --- /dev/null +++ b/Lang/RISC-V-Assembly/Jump-anywhere @@ -0,0 +1 @@ +../../Task/Jump-anywhere/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/Logical-operations b/Lang/RISC-V-Assembly/Logical-operations new file mode 120000 index 0000000000..c149f117e3 --- /dev/null +++ b/Lang/RISC-V-Assembly/Logical-operations @@ -0,0 +1 @@ +../../Task/Logical-operations/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/Loops-Do-while b/Lang/RISC-V-Assembly/Loops-Do-while new file mode 120000 index 0000000000..c6ea94d0bd --- /dev/null +++ b/Lang/RISC-V-Assembly/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/Loops-For b/Lang/RISC-V-Assembly/Loops-For new file mode 120000 index 0000000000..eb2a1946a7 --- /dev/null +++ b/Lang/RISC-V-Assembly/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/Loops-While b/Lang/RISC-V-Assembly/Loops-While new file mode 120000 index 0000000000..aefdc14d66 --- /dev/null +++ b/Lang/RISC-V-Assembly/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/Loops-With-multiple-ranges b/Lang/RISC-V-Assembly/Loops-With-multiple-ranges new file mode 120000 index 0000000000..e4ac51774c --- /dev/null +++ b/Lang/RISC-V-Assembly/Loops-With-multiple-ranges @@ -0,0 +1 @@ +../../Task/Loops-With-multiple-ranges/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/Primality-by-trial-division b/Lang/RISC-V-Assembly/Primality-by-trial-division new file mode 120000 index 0000000000..2d5326d125 --- /dev/null +++ b/Lang/RISC-V-Assembly/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/Sieve-of-Eratosthenes b/Lang/RISC-V-Assembly/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..048e79765f --- /dev/null +++ b/Lang/RISC-V-Assembly/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/Singly-linked-list-Element-definition b/Lang/RISC-V-Assembly/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..c46a1c1483 --- /dev/null +++ b/Lang/RISC-V-Assembly/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/Singly-linked-list-Element-insertion b/Lang/RISC-V-Assembly/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..3942e77b33 --- /dev/null +++ b/Lang/RISC-V-Assembly/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/Singly-linked-list-Traversal b/Lang/RISC-V-Assembly/Singly-linked-list-Traversal new file mode 120000 index 0000000000..704ea88764 --- /dev/null +++ b/Lang/RISC-V-Assembly/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/Sorting-algorithms-Bubble-sort b/Lang/RISC-V-Assembly/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..eb7e9f655b --- /dev/null +++ b/Lang/RISC-V-Assembly/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/Sorting-algorithms-Heapsort b/Lang/RISC-V-Assembly/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..623c46da1a --- /dev/null +++ b/Lang/RISC-V-Assembly/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/Sorting-algorithms-Insertion-sort b/Lang/RISC-V-Assembly/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..3748bff361 --- /dev/null +++ b/Lang/RISC-V-Assembly/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/Sorting-algorithms-Merge-sort b/Lang/RISC-V-Assembly/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..e189625c7b --- /dev/null +++ b/Lang/RISC-V-Assembly/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/Sorting-algorithms-Patience-sort b/Lang/RISC-V-Assembly/Sorting-algorithms-Patience-sort new file mode 120000 index 0000000000..ff4a528100 --- /dev/null +++ b/Lang/RISC-V-Assembly/Sorting-algorithms-Patience-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Patience-sort/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/Sorting-algorithms-Quicksort b/Lang/RISC-V-Assembly/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..61ec2d6c95 --- /dev/null +++ b/Lang/RISC-V-Assembly/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/Sorting-algorithms-Selection-sort b/Lang/RISC-V-Assembly/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..dc2705e303 --- /dev/null +++ b/Lang/RISC-V-Assembly/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/Sorting-algorithms-Shell-sort b/Lang/RISC-V-Assembly/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..3181770874 --- /dev/null +++ b/Lang/RISC-V-Assembly/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/String-append b/Lang/RISC-V-Assembly/String-append new file mode 120000 index 0000000000..c4e4abff3f --- /dev/null +++ b/Lang/RISC-V-Assembly/String-append @@ -0,0 +1 @@ +../../Task/String-append/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/String-comparison b/Lang/RISC-V-Assembly/String-comparison new file mode 120000 index 0000000000..05a600887a --- /dev/null +++ b/Lang/RISC-V-Assembly/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/String-concatenation b/Lang/RISC-V-Assembly/String-concatenation new file mode 120000 index 0000000000..14bea49904 --- /dev/null +++ b/Lang/RISC-V-Assembly/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/String-interpolation-included- b/Lang/RISC-V-Assembly/String-interpolation-included- new file mode 120000 index 0000000000..d5a6926006 --- /dev/null +++ b/Lang/RISC-V-Assembly/String-interpolation-included- @@ -0,0 +1 @@ +../../Task/String-interpolation-included-/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/String-length b/Lang/RISC-V-Assembly/String-length new file mode 120000 index 0000000000..9f0b9ba1b7 --- /dev/null +++ b/Lang/RISC-V-Assembly/String-length @@ -0,0 +1 @@ +../../Task/String-length/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/String-matching b/Lang/RISC-V-Assembly/String-matching new file mode 120000 index 0000000000..daa67c8da0 --- /dev/null +++ b/Lang/RISC-V-Assembly/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/String-prepend b/Lang/RISC-V-Assembly/String-prepend new file mode 120000 index 0000000000..4cf66d1f37 --- /dev/null +++ b/Lang/RISC-V-Assembly/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/Substring b/Lang/RISC-V-Assembly/Substring new file mode 120000 index 0000000000..346f148efa --- /dev/null +++ b/Lang/RISC-V-Assembly/Substring @@ -0,0 +1 @@ +../../Task/Substring/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/Tree-traversal b/Lang/RISC-V-Assembly/Tree-traversal new file mode 120000 index 0000000000..e386a26400 --- /dev/null +++ b/Lang/RISC-V-Assembly/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/Visualize-a-tree b/Lang/RISC-V-Assembly/Visualize-a-tree new file mode 120000 index 0000000000..20ab2b2342 --- /dev/null +++ b/Lang/RISC-V-Assembly/Visualize-a-tree @@ -0,0 +1 @@ +../../Task/Visualize-a-tree/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RPL/Guess-the-number b/Lang/RPL/Guess-the-number deleted file mode 120000 index c108a4519e..0000000000 --- a/Lang/RPL/Guess-the-number +++ /dev/null @@ -1 +0,0 @@ -../../Task/Guess-the-number/RPL \ No newline at end of file diff --git a/Lang/RTL-2/00-LANG.txt b/Lang/RTL-2/00-LANG.txt index 4f020fcdf0..1ed7c9f33f 100644 --- a/Lang/RTL-2/00-LANG.txt +++ b/Lang/RTL-2/00-LANG.txt @@ -52,6 +52,9 @@ While the specifics varied by operating system the following is an example of a This code insert moves the value of a variable passed into the RTL/2 procedure into a variable called COUNTER in a data brick called MYDATA. +== Design and Rationale == +J. G. P. Barnes describes RTL/2 and the reasons behind some of the design decisions made during its development in his 1976 book RTL/2 Design and Philosophy. + == Reserved Words == ABS AND @@ -83,6 +86,7 @@ LENGTH LET LOR MOD +MODE NEV NOT OCT diff --git a/Lang/Racket/Arithmetic-derivative b/Lang/Racket/Arithmetic-derivative new file mode 120000 index 0000000000..67478aafca --- /dev/null +++ b/Lang/Racket/Arithmetic-derivative @@ -0,0 +1 @@ +../../Task/Arithmetic-derivative/Racket \ No newline at end of file diff --git a/Lang/Racket/Bioinformatics-base-count b/Lang/Racket/Bioinformatics-base-count deleted file mode 120000 index e2d3d89548..0000000000 --- a/Lang/Racket/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Racket \ No newline at end of file diff --git a/Lang/Racket/Miller-Rabin-primality-test b/Lang/Racket/Miller-Rabin-primality-test deleted file mode 120000 index db07b51bff..0000000000 --- a/Lang/Racket/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Racket \ No newline at end of file diff --git a/Lang/Racket/Quaternion-type b/Lang/Racket/Quaternion-type deleted file mode 120000 index 88e3ea41c9..0000000000 --- a/Lang/Racket/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Racket \ No newline at end of file diff --git a/Lang/Racket/Sorting-Algorithms-Circle-Sort b/Lang/Racket/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 4c351d18cc..0000000000 --- a/Lang/Racket/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Racket \ No newline at end of file diff --git a/Lang/Racket/Strassens-algorithm b/Lang/Racket/Strassens-algorithm new file mode 120000 index 0000000000..c6d669358e --- /dev/null +++ b/Lang/Racket/Strassens-algorithm @@ -0,0 +1 @@ +../../Task/Strassens-algorithm/Racket \ No newline at end of file diff --git a/Lang/Racket/Twos-complement b/Lang/Racket/Twos-complement new file mode 120000 index 0000000000..0d85b62ede --- /dev/null +++ b/Lang/Racket/Twos-complement @@ -0,0 +1 @@ +../../Task/Twos-complement/Racket \ No newline at end of file diff --git a/Lang/Raku/Bioinformatics-base-count b/Lang/Raku/Bioinformatics-base-count deleted file mode 120000 index 7d4ea3da69..0000000000 --- a/Lang/Raku/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Raku \ No newline at end of file diff --git a/Lang/Raku/Catmull-Clark-subdivision-surface b/Lang/Raku/Catmull-Clark-subdivision-surface new file mode 120000 index 0000000000..ca92993d5e --- /dev/null +++ b/Lang/Raku/Catmull-Clark-subdivision-surface @@ -0,0 +1 @@ +../../Task/Catmull-Clark-subdivision-surface/Raku \ No newline at end of file diff --git a/Lang/Raku/Dominoes b/Lang/Raku/Dominoes new file mode 120000 index 0000000000..48ba3c99bf --- /dev/null +++ b/Lang/Raku/Dominoes @@ -0,0 +1 @@ +../../Task/Dominoes/Raku \ No newline at end of file diff --git a/Lang/Raku/Meissel-Mertens-constant b/Lang/Raku/Meissel-Mertens-constant deleted file mode 120000 index 5a835b7f73..0000000000 --- a/Lang/Raku/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/Raku \ No newline at end of file diff --git a/Lang/Raku/Miller-Rabin-primality-test b/Lang/Raku/Miller-Rabin-primality-test deleted file mode 120000 index 5ec2c83bd9..0000000000 --- a/Lang/Raku/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Raku \ No newline at end of file diff --git a/Lang/Raku/Play-recorded-sounds b/Lang/Raku/Play-recorded-sounds new file mode 120000 index 0000000000..7d18ecbdee --- /dev/null +++ b/Lang/Raku/Play-recorded-sounds @@ -0,0 +1 @@ +../../Task/Play-recorded-sounds/Raku \ No newline at end of file diff --git a/Lang/Raku/Quaternion-type b/Lang/Raku/Quaternion-type deleted file mode 120000 index 3333adafb6..0000000000 --- a/Lang/Raku/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Raku \ No newline at end of file diff --git a/Lang/Raku/Simple-turtle-graphics b/Lang/Raku/Simple-turtle-graphics new file mode 120000 index 0000000000..496cec69f4 --- /dev/null +++ b/Lang/Raku/Simple-turtle-graphics @@ -0,0 +1 @@ +../../Task/Simple-turtle-graphics/Raku \ No newline at end of file diff --git a/Lang/Raku/Sorting-Algorithms-Circle-Sort b/Lang/Raku/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 1ba8b44162..0000000000 --- a/Lang/Raku/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Raku \ No newline at end of file diff --git a/Lang/RapidQ/Levenshtein-distance b/Lang/RapidQ/Levenshtein-distance new file mode 120000 index 0000000000..43ee94415c --- /dev/null +++ b/Lang/RapidQ/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/RapidQ \ No newline at end of file diff --git a/Lang/RapidQ/Map-range b/Lang/RapidQ/Map-range new file mode 120000 index 0000000000..a3da155381 --- /dev/null +++ b/Lang/RapidQ/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/RapidQ \ No newline at end of file diff --git a/Lang/RapidQ/Nth-root b/Lang/RapidQ/Nth-root new file mode 120000 index 0000000000..f4c270323f --- /dev/null +++ b/Lang/RapidQ/Nth-root @@ -0,0 +1 @@ +../../Task/Nth-root/RapidQ \ No newline at end of file diff --git a/Lang/RapidQ/Temperature-conversion b/Lang/RapidQ/Temperature-conversion new file mode 120000 index 0000000000..757db1c288 --- /dev/null +++ b/Lang/RapidQ/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/RapidQ \ No newline at end of file diff --git a/Lang/Rebol/00-LANG.txt b/Lang/Rebol/00-LANG.txt new file mode 100644 index 0000000000..4aa183678a --- /dev/null +++ b/Lang/Rebol/00-LANG.txt @@ -0,0 +1,32 @@ +{{language|Rebol +|site=http://rebol.com +|strength=strong +|checking=dynamic +|gc=yes +|exec=interpreted +|tags=rebol, REBOL}} + +{{Language programming paradigm|Dynamic}} +{{Language programming paradigm|Declarative}} +{{Language programming paradigm|Functional}} +{{Language programming paradigm|Event-driven}} +{{Language programming paradigm|Reflective}} +{{Language programming paradigm|Procedural}} +{{Language programming paradigm|Imperative}} +{{Language programming paradigm|Concurrent}} +{{Language programming paradigm|Distributed}} + +Another entry (before merge) is available at [https://rosettacode.org/wiki/Category:REBOL Category:REBOL] + +'''Rebol''' (originally named '''REBOL''') stands for Relative Expression Based Object Language and was designed by Carl Sassenrath to combat unnecessary software complexity through a language-centric approach. Rebol has been around since about 1998, with [https://www.rebol.com/downloads.html Rebol 2 widely available] and free to use across many platforms. In December 2012, the Rebol 3 (R3) interpreter was [https://github.com/rebol/rebol/ released as open source] under the Apache 2.0 license. Today, an actively maintained community fork of Rebol 3 is available at https://github.com/Oldes/Rebol3/ with [https://github.com/Oldes/Rebol3/releases current releases and binaries]. This fork's goal is to keep the code close to the original design while improving usability, maintainability, and buildability. + +The functions dictionary for the latest available Rebol version can be found at: https://rebol.tech/docs/functions.html + +==Todo== +[https://rosettacode.org/wiki/Tasks_not_implemented_in_Rebol Tasks not implemented in Rebol] + +==Useful links== +* [http://www.rebol.com Original (outdated) Rebol site] +* [https://github.com/Oldes/Rebol3 Rebol3 source] on Github (active development). +* [https://rebol.zulipchat.com/ Rebol Zulip chat]. +* [https://app.element.io/#/room/#Rebol3:gitter.im Rebol Matrix chat]. \ No newline at end of file diff --git a/Lang/Rebol/00-META.yaml b/Lang/Rebol/00-META.yaml new file mode 100644 index 0000000000..1edb7cbb3e --- /dev/null +++ b/Lang/Rebol/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Rebol diff --git a/Lang/Rebol/100-doors b/Lang/Rebol/100-doors new file mode 120000 index 0000000000..5b331a9eba --- /dev/null +++ b/Lang/Rebol/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/Rebol \ No newline at end of file diff --git a/Lang/Rebol/100-prisoners b/Lang/Rebol/100-prisoners new file mode 120000 index 0000000000..97501a6eb7 --- /dev/null +++ b/Lang/Rebol/100-prisoners @@ -0,0 +1 @@ +../../Task/100-prisoners/Rebol \ No newline at end of file diff --git a/Lang/Rebol/15-puzzle-game b/Lang/Rebol/15-puzzle-game new file mode 120000 index 0000000000..067f887d80 --- /dev/null +++ b/Lang/Rebol/15-puzzle-game @@ -0,0 +1 @@ +../../Task/15-puzzle-game/Rebol \ No newline at end of file diff --git a/Lang/Rebol/21-game b/Lang/Rebol/21-game new file mode 120000 index 0000000000..26c96de104 --- /dev/null +++ b/Lang/Rebol/21-game @@ -0,0 +1 @@ +../../Task/21-game/Rebol \ No newline at end of file diff --git a/Lang/Rebol/24-game b/Lang/Rebol/24-game new file mode 120000 index 0000000000..da2db22523 --- /dev/null +++ b/Lang/Rebol/24-game @@ -0,0 +1 @@ +../../Task/24-game/Rebol \ No newline at end of file diff --git a/Lang/Rebol/9-billion-names-of-God-the-integer b/Lang/Rebol/9-billion-names-of-God-the-integer new file mode 120000 index 0000000000..73577ad2b4 --- /dev/null +++ b/Lang/Rebol/9-billion-names-of-God-the-integer @@ -0,0 +1 @@ +../../Task/9-billion-names-of-God-the-integer/Rebol \ No newline at end of file diff --git a/Lang/Rebol/99-bottles-of-beer b/Lang/Rebol/99-bottles-of-beer new file mode 120000 index 0000000000..5fa8a19390 --- /dev/null +++ b/Lang/Rebol/99-bottles-of-beer @@ -0,0 +1 @@ +../../Task/99-bottles-of-beer/Rebol \ No newline at end of file diff --git a/Lang/Rebol/A+B b/Lang/Rebol/A+B new file mode 120000 index 0000000000..b25e6fbd34 --- /dev/null +++ b/Lang/Rebol/A+B @@ -0,0 +1 @@ +../../Task/A+B/Rebol \ No newline at end of file diff --git a/Lang/Rebol/ABC-problem b/Lang/Rebol/ABC-problem new file mode 120000 index 0000000000..4e6e666878 --- /dev/null +++ b/Lang/Rebol/ABC-problem @@ -0,0 +1 @@ +../../Task/ABC-problem/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Abbreviations-automatic b/Lang/Rebol/Abbreviations-automatic new file mode 120000 index 0000000000..85b470e105 --- /dev/null +++ b/Lang/Rebol/Abbreviations-automatic @@ -0,0 +1 @@ +../../Task/Abbreviations-automatic/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Abbreviations-easy b/Lang/Rebol/Abbreviations-easy new file mode 120000 index 0000000000..f54524f132 --- /dev/null +++ b/Lang/Rebol/Abbreviations-easy @@ -0,0 +1 @@ +../../Task/Abbreviations-easy/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Abbreviations-simple b/Lang/Rebol/Abbreviations-simple new file mode 120000 index 0000000000..1036d0a126 --- /dev/null +++ b/Lang/Rebol/Abbreviations-simple @@ -0,0 +1 @@ +../../Task/Abbreviations-simple/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Abelian-sandpile-model-Identity b/Lang/Rebol/Abelian-sandpile-model-Identity new file mode 120000 index 0000000000..fa169923d8 --- /dev/null +++ b/Lang/Rebol/Abelian-sandpile-model-Identity @@ -0,0 +1 @@ +../../Task/Abelian-sandpile-model-Identity/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Abstract-type b/Lang/Rebol/Abstract-type new file mode 120000 index 0000000000..98f9214f95 --- /dev/null +++ b/Lang/Rebol/Abstract-type @@ -0,0 +1 @@ +../../Task/Abstract-type/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Abundant-odd-numbers b/Lang/Rebol/Abundant-odd-numbers new file mode 120000 index 0000000000..3a7c4247e0 --- /dev/null +++ b/Lang/Rebol/Abundant-odd-numbers @@ -0,0 +1 @@ +../../Task/Abundant-odd-numbers/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Accumulator-factory b/Lang/Rebol/Accumulator-factory new file mode 120000 index 0000000000..2ad70f64ad --- /dev/null +++ b/Lang/Rebol/Accumulator-factory @@ -0,0 +1 @@ +../../Task/Accumulator-factory/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Ackermann-function b/Lang/Rebol/Ackermann-function new file mode 120000 index 0000000000..699a619796 --- /dev/null +++ b/Lang/Rebol/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Add-a-variable-to-a-class-instance-at-runtime b/Lang/Rebol/Add-a-variable-to-a-class-instance-at-runtime new file mode 120000 index 0000000000..a74659ec86 --- /dev/null +++ b/Lang/Rebol/Add-a-variable-to-a-class-instance-at-runtime @@ -0,0 +1 @@ +../../Task/Add-a-variable-to-a-class-instance-at-runtime/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Additive-primes b/Lang/Rebol/Additive-primes new file mode 120000 index 0000000000..1f4da61e10 --- /dev/null +++ b/Lang/Rebol/Additive-primes @@ -0,0 +1 @@ +../../Task/Additive-primes/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Align-columns b/Lang/Rebol/Align-columns new file mode 120000 index 0000000000..f1de5b19b7 --- /dev/null +++ b/Lang/Rebol/Align-columns @@ -0,0 +1 @@ +../../Task/Align-columns/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Almost-prime b/Lang/Rebol/Almost-prime new file mode 120000 index 0000000000..485728d591 --- /dev/null +++ b/Lang/Rebol/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Amb b/Lang/Rebol/Amb new file mode 120000 index 0000000000..ada18b3a53 --- /dev/null +++ b/Lang/Rebol/Amb @@ -0,0 +1 @@ +../../Task/Amb/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Amicable-pairs b/Lang/Rebol/Amicable-pairs new file mode 120000 index 0000000000..7715d03a59 --- /dev/null +++ b/Lang/Rebol/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Anagrams b/Lang/Rebol/Anagrams new file mode 120000 index 0000000000..19dbe7b94f --- /dev/null +++ b/Lang/Rebol/Anagrams @@ -0,0 +1 @@ +../../Task/Anagrams/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Anagrams-Deranged-anagrams b/Lang/Rebol/Anagrams-Deranged-anagrams new file mode 120000 index 0000000000..dc92d83901 --- /dev/null +++ b/Lang/Rebol/Anagrams-Deranged-anagrams @@ -0,0 +1 @@ +../../Task/Anagrams-Deranged-anagrams/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Animation b/Lang/Rebol/Animation new file mode 120000 index 0000000000..9bc983a74f --- /dev/null +++ b/Lang/Rebol/Animation @@ -0,0 +1 @@ +../../Task/Animation/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Anonymous-recursion b/Lang/Rebol/Anonymous-recursion new file mode 120000 index 0000000000..bb89ba8ad2 --- /dev/null +++ b/Lang/Rebol/Anonymous-recursion @@ -0,0 +1 @@ +../../Task/Anonymous-recursion/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Anti-primes b/Lang/Rebol/Anti-primes new file mode 120000 index 0000000000..a605291c15 --- /dev/null +++ b/Lang/Rebol/Anti-primes @@ -0,0 +1 @@ +../../Task/Anti-primes/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Apply-a-callback-to-an-array b/Lang/Rebol/Apply-a-callback-to-an-array new file mode 120000 index 0000000000..846524932e --- /dev/null +++ b/Lang/Rebol/Apply-a-callback-to-an-array @@ -0,0 +1 @@ +../../Task/Apply-a-callback-to-an-array/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Archimedean-spiral b/Lang/Rebol/Archimedean-spiral new file mode 120000 index 0000000000..485754061d --- /dev/null +++ b/Lang/Rebol/Archimedean-spiral @@ -0,0 +1 @@ +../../Task/Archimedean-spiral/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Arena-storage-pool b/Lang/Rebol/Arena-storage-pool new file mode 120000 index 0000000000..261e2b68b6 --- /dev/null +++ b/Lang/Rebol/Arena-storage-pool @@ -0,0 +1 @@ +../../Task/Arena-storage-pool/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Arithmetic-Integer b/Lang/Rebol/Arithmetic-Integer new file mode 120000 index 0000000000..beda640d8b --- /dev/null +++ b/Lang/Rebol/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Arithmetic-evaluation b/Lang/Rebol/Arithmetic-evaluation new file mode 120000 index 0000000000..eace662534 --- /dev/null +++ b/Lang/Rebol/Arithmetic-evaluation @@ -0,0 +1 @@ +../../Task/Arithmetic-evaluation/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Array-concatenation b/Lang/Rebol/Array-concatenation new file mode 120000 index 0000000000..54981e3b27 --- /dev/null +++ b/Lang/Rebol/Array-concatenation @@ -0,0 +1 @@ +../../Task/Array-concatenation/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Array-length b/Lang/Rebol/Array-length new file mode 120000 index 0000000000..b057893924 --- /dev/null +++ b/Lang/Rebol/Array-length @@ -0,0 +1 @@ +../../Task/Array-length/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Arrays b/Lang/Rebol/Arrays new file mode 120000 index 0000000000..c2505cc17f --- /dev/null +++ b/Lang/Rebol/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Assertions b/Lang/Rebol/Assertions new file mode 120000 index 0000000000..410d203693 --- /dev/null +++ b/Lang/Rebol/Assertions @@ -0,0 +1 @@ +../../Task/Assertions/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Associative-array-Creation b/Lang/Rebol/Associative-array-Creation new file mode 120000 index 0000000000..ed84b3cd74 --- /dev/null +++ b/Lang/Rebol/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Attractive-numbers b/Lang/Rebol/Attractive-numbers new file mode 120000 index 0000000000..bd3dc833b3 --- /dev/null +++ b/Lang/Rebol/Attractive-numbers @@ -0,0 +1 @@ +../../Task/Attractive-numbers/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Averages-Arithmetic-mean b/Lang/Rebol/Averages-Arithmetic-mean new file mode 120000 index 0000000000..1b2f7cd050 --- /dev/null +++ b/Lang/Rebol/Averages-Arithmetic-mean @@ -0,0 +1 @@ +../../Task/Averages-Arithmetic-mean/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Averages-Median b/Lang/Rebol/Averages-Median new file mode 120000 index 0000000000..308cc999e7 --- /dev/null +++ b/Lang/Rebol/Averages-Median @@ -0,0 +1 @@ +../../Task/Averages-Median/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Babbage-problem b/Lang/Rebol/Babbage-problem new file mode 120000 index 0000000000..da5afb5375 --- /dev/null +++ b/Lang/Rebol/Babbage-problem @@ -0,0 +1 @@ +../../Task/Babbage-problem/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Babylonian-spiral b/Lang/Rebol/Babylonian-spiral new file mode 120000 index 0000000000..18aac82eae --- /dev/null +++ b/Lang/Rebol/Babylonian-spiral @@ -0,0 +1 @@ +../../Task/Babylonian-spiral/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Balanced-brackets b/Lang/Rebol/Balanced-brackets new file mode 120000 index 0000000000..99271027bc --- /dev/null +++ b/Lang/Rebol/Balanced-brackets @@ -0,0 +1 @@ +../../Task/Balanced-brackets/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Barnsley-fern b/Lang/Rebol/Barnsley-fern new file mode 120000 index 0000000000..e98ef998d2 --- /dev/null +++ b/Lang/Rebol/Barnsley-fern @@ -0,0 +1 @@ +../../Task/Barnsley-fern/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Base64-decode-data b/Lang/Rebol/Base64-decode-data new file mode 120000 index 0000000000..0ea7b555cb --- /dev/null +++ b/Lang/Rebol/Base64-decode-data @@ -0,0 +1 @@ +../../Task/Base64-decode-data/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Bifid-cipher b/Lang/Rebol/Bifid-cipher new file mode 120000 index 0000000000..b00839dd98 --- /dev/null +++ b/Lang/Rebol/Bifid-cipher @@ -0,0 +1 @@ +../../Task/Bifid-cipher/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Binary-digits b/Lang/Rebol/Binary-digits new file mode 120000 index 0000000000..7cb2d23198 --- /dev/null +++ b/Lang/Rebol/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Binary-strings b/Lang/Rebol/Binary-strings new file mode 120000 index 0000000000..9671e7ddf3 --- /dev/null +++ b/Lang/Rebol/Binary-strings @@ -0,0 +1 @@ +../../Task/Binary-strings/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Biorhythms b/Lang/Rebol/Biorhythms new file mode 120000 index 0000000000..7e80c97327 --- /dev/null +++ b/Lang/Rebol/Biorhythms @@ -0,0 +1 @@ +../../Task/Biorhythms/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Bitcoin-address-validation b/Lang/Rebol/Bitcoin-address-validation new file mode 120000 index 0000000000..9344a9c4c3 --- /dev/null +++ b/Lang/Rebol/Bitcoin-address-validation @@ -0,0 +1 @@ +../../Task/Bitcoin-address-validation/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Bitmap b/Lang/Rebol/Bitmap new file mode 120000 index 0000000000..629709bef1 --- /dev/null +++ b/Lang/Rebol/Bitmap @@ -0,0 +1 @@ +../../Task/Bitmap/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Bitmap-Flood-fill b/Lang/Rebol/Bitmap-Flood-fill new file mode 120000 index 0000000000..af82299463 --- /dev/null +++ b/Lang/Rebol/Bitmap-Flood-fill @@ -0,0 +1 @@ +../../Task/Bitmap-Flood-fill/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Bitmap-Histogram b/Lang/Rebol/Bitmap-Histogram new file mode 120000 index 0000000000..3dc33a01e1 --- /dev/null +++ b/Lang/Rebol/Bitmap-Histogram @@ -0,0 +1 @@ +../../Task/Bitmap-Histogram/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Bitmap-Midpoint-circle-algorithm b/Lang/Rebol/Bitmap-Midpoint-circle-algorithm new file mode 120000 index 0000000000..d8a14cc133 --- /dev/null +++ b/Lang/Rebol/Bitmap-Midpoint-circle-algorithm @@ -0,0 +1 @@ +../../Task/Bitmap-Midpoint-circle-algorithm/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Bitmap-Read-a-PPM-file b/Lang/Rebol/Bitmap-Read-a-PPM-file new file mode 120000 index 0000000000..4c8503a5c6 --- /dev/null +++ b/Lang/Rebol/Bitmap-Read-a-PPM-file @@ -0,0 +1 @@ +../../Task/Bitmap-Read-a-PPM-file/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Bitmap-Write-a-PPM-file b/Lang/Rebol/Bitmap-Write-a-PPM-file new file mode 120000 index 0000000000..f47ca4a660 --- /dev/null +++ b/Lang/Rebol/Bitmap-Write-a-PPM-file @@ -0,0 +1 @@ +../../Task/Bitmap-Write-a-PPM-file/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Bitwise-IO b/Lang/Rebol/Bitwise-IO new file mode 120000 index 0000000000..d928c50478 --- /dev/null +++ b/Lang/Rebol/Bitwise-IO @@ -0,0 +1 @@ +../../Task/Bitwise-IO/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Bitwise-operations b/Lang/Rebol/Bitwise-operations new file mode 120000 index 0000000000..ed4b6220a6 --- /dev/null +++ b/Lang/Rebol/Bitwise-operations @@ -0,0 +1 @@ +../../Task/Bitwise-operations/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Box-the-compass b/Lang/Rebol/Box-the-compass new file mode 120000 index 0000000000..8772a92d1c --- /dev/null +++ b/Lang/Rebol/Box-the-compass @@ -0,0 +1 @@ +../../Task/Box-the-compass/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Bulls-and-cows b/Lang/Rebol/Bulls-and-cows new file mode 120000 index 0000000000..acbfc00124 --- /dev/null +++ b/Lang/Rebol/Bulls-and-cows @@ -0,0 +1 @@ +../../Task/Bulls-and-cows/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Bulls-and-cows-Player b/Lang/Rebol/Bulls-and-cows-Player new file mode 120000 index 0000000000..3cce956d9f --- /dev/null +++ b/Lang/Rebol/Bulls-and-cows-Player @@ -0,0 +1 @@ +../../Task/Bulls-and-cows-Player/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Burrows-Wheeler-transform b/Lang/Rebol/Burrows-Wheeler-transform new file mode 120000 index 0000000000..0a3a26dcec --- /dev/null +++ b/Lang/Rebol/Burrows-Wheeler-transform @@ -0,0 +1 @@ +../../Task/Burrows-Wheeler-transform/Rebol \ No newline at end of file diff --git a/Lang/Rebol/CRC-32 b/Lang/Rebol/CRC-32 new file mode 120000 index 0000000000..634c717528 --- /dev/null +++ b/Lang/Rebol/CRC-32 @@ -0,0 +1 @@ +../../Task/CRC-32/Rebol \ No newline at end of file diff --git a/Lang/Rebol/CSV-data-manipulation b/Lang/Rebol/CSV-data-manipulation new file mode 120000 index 0000000000..7ac497a786 --- /dev/null +++ b/Lang/Rebol/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/Rebol \ No newline at end of file diff --git a/Lang/Rebol/CSV-to-HTML-translation b/Lang/Rebol/CSV-to-HTML-translation new file mode 120000 index 0000000000..f5ad170ee4 --- /dev/null +++ b/Lang/Rebol/CSV-to-HTML-translation @@ -0,0 +1 @@ +../../Task/CSV-to-HTML-translation/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Caesar-cipher b/Lang/Rebol/Caesar-cipher new file mode 120000 index 0000000000..a6b4726d60 --- /dev/null +++ b/Lang/Rebol/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Calendar b/Lang/Rebol/Calendar new file mode 120000 index 0000000000..ab6fe69315 --- /dev/null +++ b/Lang/Rebol/Calendar @@ -0,0 +1 @@ +../../Task/Calendar/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Calendar---for-REAL-programmers b/Lang/Rebol/Calendar---for-REAL-programmers new file mode 120000 index 0000000000..af1c969dec --- /dev/null +++ b/Lang/Rebol/Calendar---for-REAL-programmers @@ -0,0 +1 @@ +../../Task/Calendar---for-REAL-programmers/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Catalan-numbers b/Lang/Rebol/Catalan-numbers new file mode 120000 index 0000000000..0e39f685c0 --- /dev/null +++ b/Lang/Rebol/Catalan-numbers @@ -0,0 +1 @@ +../../Task/Catalan-numbers/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Catalan-numbers-Pascals-triangle b/Lang/Rebol/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..6b1b6d4970 --- /dev/null +++ b/Lang/Rebol/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Character-codes b/Lang/Rebol/Character-codes new file mode 120000 index 0000000000..3daa301cb2 --- /dev/null +++ b/Lang/Rebol/Character-codes @@ -0,0 +1 @@ +../../Task/Character-codes/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Check-input-device-is-a-terminal b/Lang/Rebol/Check-input-device-is-a-terminal new file mode 120000 index 0000000000..82d5a1e6e2 --- /dev/null +++ b/Lang/Rebol/Check-input-device-is-a-terminal @@ -0,0 +1 @@ +../../Task/Check-input-device-is-a-terminal/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Check-that-file-exists b/Lang/Rebol/Check-that-file-exists new file mode 120000 index 0000000000..83129a7375 --- /dev/null +++ b/Lang/Rebol/Check-that-file-exists @@ -0,0 +1 @@ +../../Task/Check-that-file-exists/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Chinese-zodiac b/Lang/Rebol/Chinese-zodiac new file mode 120000 index 0000000000..e983432942 --- /dev/null +++ b/Lang/Rebol/Chinese-zodiac @@ -0,0 +1 @@ +../../Task/Chinese-zodiac/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Classes b/Lang/Rebol/Classes new file mode 120000 index 0000000000..19c13253ee --- /dev/null +++ b/Lang/Rebol/Classes @@ -0,0 +1 @@ +../../Task/Classes/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Closures-Value-capture b/Lang/Rebol/Closures-Value-capture new file mode 120000 index 0000000000..c746b0b21a --- /dev/null +++ b/Lang/Rebol/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Color-quantization b/Lang/Rebol/Color-quantization new file mode 120000 index 0000000000..fca9b62778 --- /dev/null +++ b/Lang/Rebol/Color-quantization @@ -0,0 +1 @@ +../../Task/Color-quantization/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Comma-quibbling b/Lang/Rebol/Comma-quibbling new file mode 120000 index 0000000000..8f9382035d --- /dev/null +++ b/Lang/Rebol/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Comments b/Lang/Rebol/Comments new file mode 120000 index 0000000000..1a45f1afdb --- /dev/null +++ b/Lang/Rebol/Comments @@ -0,0 +1 @@ +../../Task/Comments/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Compare-a-list-of-strings b/Lang/Rebol/Compare-a-list-of-strings new file mode 120000 index 0000000000..8b48806d25 --- /dev/null +++ b/Lang/Rebol/Compare-a-list-of-strings @@ -0,0 +1 @@ +../../Task/Compare-a-list-of-strings/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Conways-Game-of-Life b/Lang/Rebol/Conways-Game-of-Life new file mode 120000 index 0000000000..1be297f380 --- /dev/null +++ b/Lang/Rebol/Conways-Game-of-Life @@ -0,0 +1 @@ +../../Task/Conways-Game-of-Life/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Copy-a-string b/Lang/Rebol/Copy-a-string new file mode 120000 index 0000000000..713a966385 --- /dev/null +++ b/Lang/Rebol/Copy-a-string @@ -0,0 +1 @@ +../../Task/Copy-a-string/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Create-a-file b/Lang/Rebol/Create-a-file new file mode 120000 index 0000000000..eb56f3709c --- /dev/null +++ b/Lang/Rebol/Create-a-file @@ -0,0 +1 @@ +../../Task/Create-a-file/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Create-a-two-dimensional-array-at-runtime b/Lang/Rebol/Create-a-two-dimensional-array-at-runtime new file mode 120000 index 0000000000..2338b1da0a --- /dev/null +++ b/Lang/Rebol/Create-a-two-dimensional-array-at-runtime @@ -0,0 +1 @@ +../../Task/Create-a-two-dimensional-array-at-runtime/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Create-an-HTML-table b/Lang/Rebol/Create-an-HTML-table new file mode 120000 index 0000000000..479c62b61c --- /dev/null +++ b/Lang/Rebol/Create-an-HTML-table @@ -0,0 +1 @@ +../../Task/Create-an-HTML-table/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Currency b/Lang/Rebol/Currency new file mode 120000 index 0000000000..918d212fb1 --- /dev/null +++ b/Lang/Rebol/Currency @@ -0,0 +1 @@ +../../Task/Currency/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Currying b/Lang/Rebol/Currying new file mode 120000 index 0000000000..8810de2a28 --- /dev/null +++ b/Lang/Rebol/Currying @@ -0,0 +1 @@ +../../Task/Currying/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Date-format b/Lang/Rebol/Date-format new file mode 120000 index 0000000000..bbad545c0e --- /dev/null +++ b/Lang/Rebol/Date-format @@ -0,0 +1 @@ +../../Task/Date-format/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Date-manipulation b/Lang/Rebol/Date-manipulation new file mode 120000 index 0000000000..0ef2caa486 --- /dev/null +++ b/Lang/Rebol/Date-manipulation @@ -0,0 +1 @@ +../../Task/Date-manipulation/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Day-of-the-week b/Lang/Rebol/Day-of-the-week new file mode 120000 index 0000000000..27a96c7aab --- /dev/null +++ b/Lang/Rebol/Day-of-the-week @@ -0,0 +1 @@ +../../Task/Day-of-the-week/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Deal-cards-for-FreeCell b/Lang/Rebol/Deal-cards-for-FreeCell new file mode 120000 index 0000000000..6092f801ff --- /dev/null +++ b/Lang/Rebol/Deal-cards-for-FreeCell @@ -0,0 +1 @@ +../../Task/Deal-cards-for-FreeCell/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Delete-a-file b/Lang/Rebol/Delete-a-file new file mode 120000 index 0000000000..60299e91d7 --- /dev/null +++ b/Lang/Rebol/Delete-a-file @@ -0,0 +1 @@ +../../Task/Delete-a-file/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Detect-division-by-zero b/Lang/Rebol/Detect-division-by-zero new file mode 120000 index 0000000000..fb477e9779 --- /dev/null +++ b/Lang/Rebol/Detect-division-by-zero @@ -0,0 +1 @@ +../../Task/Detect-division-by-zero/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Determine-if-a-string-is-numeric b/Lang/Rebol/Determine-if-a-string-is-numeric new file mode 120000 index 0000000000..6a7216a9d5 --- /dev/null +++ b/Lang/Rebol/Determine-if-a-string-is-numeric @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-numeric/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Digital-root b/Lang/Rebol/Digital-root new file mode 120000 index 0000000000..c70057beb3 --- /dev/null +++ b/Lang/Rebol/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Display-a-linear-combination b/Lang/Rebol/Display-a-linear-combination new file mode 120000 index 0000000000..701713c8e0 --- /dev/null +++ b/Lang/Rebol/Display-a-linear-combination @@ -0,0 +1 @@ +../../Task/Display-a-linear-combination/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Documentation b/Lang/Rebol/Documentation new file mode 120000 index 0000000000..92c3f85b3b --- /dev/null +++ b/Lang/Rebol/Documentation @@ -0,0 +1 @@ +../../Task/Documentation/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Dot-product b/Lang/Rebol/Dot-product new file mode 120000 index 0000000000..a29d1db870 --- /dev/null +++ b/Lang/Rebol/Dot-product @@ -0,0 +1 @@ +../../Task/Dot-product/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Dragon-curve b/Lang/Rebol/Dragon-curve new file mode 120000 index 0000000000..e192bc1b6c --- /dev/null +++ b/Lang/Rebol/Dragon-curve @@ -0,0 +1 @@ +../../Task/Dragon-curve/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Draw-a-clock b/Lang/Rebol/Draw-a-clock new file mode 120000 index 0000000000..9c767ac91b --- /dev/null +++ b/Lang/Rebol/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Draw-a-pixel b/Lang/Rebol/Draw-a-pixel new file mode 120000 index 0000000000..4424b2ecc5 --- /dev/null +++ b/Lang/Rebol/Draw-a-pixel @@ -0,0 +1 @@ +../../Task/Draw-a-pixel/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Dynamic-variable-names b/Lang/Rebol/Dynamic-variable-names new file mode 120000 index 0000000000..36e09e119f --- /dev/null +++ b/Lang/Rebol/Dynamic-variable-names @@ -0,0 +1 @@ +../../Task/Dynamic-variable-names/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Echo-server b/Lang/Rebol/Echo-server new file mode 120000 index 0000000000..cdc4b2fda6 --- /dev/null +++ b/Lang/Rebol/Echo-server @@ -0,0 +1 @@ +../../Task/Echo-server/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Empty-directory b/Lang/Rebol/Empty-directory new file mode 120000 index 0000000000..2945783dae --- /dev/null +++ b/Lang/Rebol/Empty-directory @@ -0,0 +1 @@ +../../Task/Empty-directory/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Empty-program b/Lang/Rebol/Empty-program new file mode 120000 index 0000000000..f34c1f5023 --- /dev/null +++ b/Lang/Rebol/Empty-program @@ -0,0 +1 @@ +../../Task/Empty-program/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Empty-string b/Lang/Rebol/Empty-string new file mode 120000 index 0000000000..33318a0a63 --- /dev/null +++ b/Lang/Rebol/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Enumerations b/Lang/Rebol/Enumerations new file mode 120000 index 0000000000..ba3f469c4e --- /dev/null +++ b/Lang/Rebol/Enumerations @@ -0,0 +1 @@ +../../Task/Enumerations/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Environment-variables b/Lang/Rebol/Environment-variables new file mode 120000 index 0000000000..5354438b20 --- /dev/null +++ b/Lang/Rebol/Environment-variables @@ -0,0 +1 @@ +../../Task/Environment-variables/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Ethiopian-multiplication b/Lang/Rebol/Ethiopian-multiplication new file mode 120000 index 0000000000..1671fc4362 --- /dev/null +++ b/Lang/Rebol/Ethiopian-multiplication @@ -0,0 +1 @@ +../../Task/Ethiopian-multiplication/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Euler-method b/Lang/Rebol/Euler-method new file mode 120000 index 0000000000..d587d93232 --- /dev/null +++ b/Lang/Rebol/Euler-method @@ -0,0 +1 @@ +../../Task/Euler-method/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Eulers-constant-0.5772... b/Lang/Rebol/Eulers-constant-0.5772... new file mode 120000 index 0000000000..02917c130f --- /dev/null +++ b/Lang/Rebol/Eulers-constant-0.5772... @@ -0,0 +1 @@ +../../Task/Eulers-constant-0.5772.../Rebol \ No newline at end of file diff --git a/Lang/Rebol/Evolutionary-algorithm b/Lang/Rebol/Evolutionary-algorithm new file mode 120000 index 0000000000..ccdf89518f --- /dev/null +++ b/Lang/Rebol/Evolutionary-algorithm @@ -0,0 +1 @@ +../../Task/Evolutionary-algorithm/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Execute-Brain- b/Lang/Rebol/Execute-Brain- new file mode 120000 index 0000000000..60bfe033c3 --- /dev/null +++ b/Lang/Rebol/Execute-Brain- @@ -0,0 +1 @@ +../../Task/Execute-Brain-/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Execute-a-system-command b/Lang/Rebol/Execute-a-system-command new file mode 120000 index 0000000000..14651b49c9 --- /dev/null +++ b/Lang/Rebol/Execute-a-system-command @@ -0,0 +1 @@ +../../Task/Execute-a-system-command/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Exponentiation-order b/Lang/Rebol/Exponentiation-order new file mode 120000 index 0000000000..852ef49526 --- /dev/null +++ b/Lang/Rebol/Exponentiation-order @@ -0,0 +1 @@ +../../Task/Exponentiation-order/Rebol \ No newline at end of file diff --git a/Lang/Rebol/FASTA-format b/Lang/Rebol/FASTA-format new file mode 120000 index 0000000000..40d663436d --- /dev/null +++ b/Lang/Rebol/FASTA-format @@ -0,0 +1 @@ +../../Task/FASTA-format/Rebol \ No newline at end of file diff --git a/Lang/Rebol/FTP b/Lang/Rebol/FTP new file mode 120000 index 0000000000..3480e1937d --- /dev/null +++ b/Lang/Rebol/FTP @@ -0,0 +1 @@ +../../Task/FTP/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Factorial b/Lang/Rebol/Factorial new file mode 120000 index 0000000000..359724a1fc --- /dev/null +++ b/Lang/Rebol/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Factors-of-an-integer b/Lang/Rebol/Factors-of-an-integer new file mode 120000 index 0000000000..9d42008357 --- /dev/null +++ b/Lang/Rebol/Factors-of-an-integer @@ -0,0 +1 @@ +../../Task/Factors-of-an-integer/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Fibonacci-sequence b/Lang/Rebol/Fibonacci-sequence new file mode 120000 index 0000000000..f57b59f681 --- /dev/null +++ b/Lang/Rebol/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/Rebol \ No newline at end of file diff --git a/Lang/Rebol/File-input-output b/Lang/Rebol/File-input-output new file mode 120000 index 0000000000..b8c077dcb5 --- /dev/null +++ b/Lang/Rebol/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Rebol \ No newline at end of file diff --git a/Lang/Rebol/File-size b/Lang/Rebol/File-size new file mode 120000 index 0000000000..896b2c8e3b --- /dev/null +++ b/Lang/Rebol/File-size @@ -0,0 +1 @@ +../../Task/File-size/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Filter b/Lang/Rebol/Filter new file mode 120000 index 0000000000..eaf8ebe826 --- /dev/null +++ b/Lang/Rebol/Filter @@ -0,0 +1 @@ +../../Task/Filter/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Find-the-last-Sunday-of-each-month b/Lang/Rebol/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..d3b115bfb8 --- /dev/null +++ b/Lang/Rebol/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/Rebol \ No newline at end of file diff --git a/Lang/Rebol/First-class-functions b/Lang/Rebol/First-class-functions new file mode 120000 index 0000000000..5b2c2417e0 --- /dev/null +++ b/Lang/Rebol/First-class-functions @@ -0,0 +1 @@ +../../Task/First-class-functions/Rebol \ No newline at end of file diff --git a/Lang/Rebol/First-class-functions-Use-numbers-analogously b/Lang/Rebol/First-class-functions-Use-numbers-analogously new file mode 120000 index 0000000000..de2ebe8414 --- /dev/null +++ b/Lang/Rebol/First-class-functions-Use-numbers-analogously @@ -0,0 +1 @@ +../../Task/First-class-functions-Use-numbers-analogously/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Five-weekends b/Lang/Rebol/Five-weekends new file mode 120000 index 0000000000..01c1c36611 --- /dev/null +++ b/Lang/Rebol/Five-weekends @@ -0,0 +1 @@ +../../Task/Five-weekends/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Fixed-length-records b/Lang/Rebol/Fixed-length-records new file mode 120000 index 0000000000..9039851f51 --- /dev/null +++ b/Lang/Rebol/Fixed-length-records @@ -0,0 +1 @@ +../../Task/Fixed-length-records/Rebol \ No newline at end of file diff --git a/Lang/Rebol/FizzBuzz b/Lang/Rebol/FizzBuzz new file mode 120000 index 0000000000..eab06ab9bd --- /dev/null +++ b/Lang/Rebol/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Flatten-a-list b/Lang/Rebol/Flatten-a-list new file mode 120000 index 0000000000..c1a20ef65d --- /dev/null +++ b/Lang/Rebol/Flatten-a-list @@ -0,0 +1 @@ +../../Task/Flatten-a-list/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Flow-control-structures b/Lang/Rebol/Flow-control-structures new file mode 120000 index 0000000000..07ef2d4ad0 --- /dev/null +++ b/Lang/Rebol/Flow-control-structures @@ -0,0 +1 @@ +../../Task/Flow-control-structures/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Formatted-numeric-output b/Lang/Rebol/Formatted-numeric-output new file mode 120000 index 0000000000..7f83bb070c --- /dev/null +++ b/Lang/Rebol/Formatted-numeric-output @@ -0,0 +1 @@ +../../Task/Formatted-numeric-output/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Fractal-tree b/Lang/Rebol/Fractal-tree new file mode 120000 index 0000000000..dc8b11466f --- /dev/null +++ b/Lang/Rebol/Fractal-tree @@ -0,0 +1 @@ +../../Task/Fractal-tree/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Fraction-reduction b/Lang/Rebol/Fraction-reduction new file mode 120000 index 0000000000..b0104cd06a --- /dev/null +++ b/Lang/Rebol/Fraction-reduction @@ -0,0 +1 @@ +../../Task/Fraction-reduction/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Fractran b/Lang/Rebol/Fractran new file mode 120000 index 0000000000..9377d42c62 --- /dev/null +++ b/Lang/Rebol/Fractran @@ -0,0 +1 @@ +../../Task/Fractran/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Function-composition b/Lang/Rebol/Function-composition new file mode 120000 index 0000000000..76d75e3285 --- /dev/null +++ b/Lang/Rebol/Function-composition @@ -0,0 +1 @@ +../../Task/Function-composition/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Function-definition b/Lang/Rebol/Function-definition new file mode 120000 index 0000000000..70c2821920 --- /dev/null +++ b/Lang/Rebol/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Gapful-numbers b/Lang/Rebol/Gapful-numbers new file mode 120000 index 0000000000..68fbc7017f --- /dev/null +++ b/Lang/Rebol/Gapful-numbers @@ -0,0 +1 @@ +../../Task/Gapful-numbers/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Generic-swap b/Lang/Rebol/Generic-swap new file mode 120000 index 0000000000..283afac298 --- /dev/null +++ b/Lang/Rebol/Generic-swap @@ -0,0 +1 @@ +../../Task/Generic-swap/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Get-system-command-output b/Lang/Rebol/Get-system-command-output new file mode 120000 index 0000000000..62cff72de6 --- /dev/null +++ b/Lang/Rebol/Get-system-command-output @@ -0,0 +1 @@ +../../Task/Get-system-command-output/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Globally-replace-text-in-several-files b/Lang/Rebol/Globally-replace-text-in-several-files new file mode 120000 index 0000000000..03354f183a --- /dev/null +++ b/Lang/Rebol/Globally-replace-text-in-several-files @@ -0,0 +1 @@ +../../Task/Globally-replace-text-in-several-files/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Go-Fish b/Lang/Rebol/Go-Fish new file mode 120000 index 0000000000..7c0ef6e6d5 --- /dev/null +++ b/Lang/Rebol/Go-Fish @@ -0,0 +1 @@ +../../Task/Go-Fish/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Greatest-common-divisor b/Lang/Rebol/Greatest-common-divisor new file mode 120000 index 0000000000..e924b899c0 --- /dev/null +++ b/Lang/Rebol/Greatest-common-divisor @@ -0,0 +1 @@ +../../Task/Greatest-common-divisor/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Greatest-element-of-a-list b/Lang/Rebol/Greatest-element-of-a-list new file mode 120000 index 0000000000..e262faf6c6 --- /dev/null +++ b/Lang/Rebol/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/Rebol \ No newline at end of file diff --git a/Lang/Rebol/HTTP b/Lang/Rebol/HTTP new file mode 120000 index 0000000000..f7583ff32a --- /dev/null +++ b/Lang/Rebol/HTTP @@ -0,0 +1 @@ +../../Task/HTTP/Rebol \ No newline at end of file diff --git a/Lang/Rebol/HTTPS b/Lang/Rebol/HTTPS new file mode 120000 index 0000000000..39a4cf4015 --- /dev/null +++ b/Lang/Rebol/HTTPS @@ -0,0 +1 @@ +../../Task/HTTPS/Rebol \ No newline at end of file diff --git a/Lang/Rebol/HTTPS-Authenticated b/Lang/Rebol/HTTPS-Authenticated new file mode 120000 index 0000000000..325f33d148 --- /dev/null +++ b/Lang/Rebol/HTTPS-Authenticated @@ -0,0 +1 @@ +../../Task/HTTPS-Authenticated/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Hailstone-sequence b/Lang/Rebol/Hailstone-sequence new file mode 120000 index 0000000000..52670d11f8 --- /dev/null +++ b/Lang/Rebol/Hailstone-sequence @@ -0,0 +1 @@ +../../Task/Hailstone-sequence/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Halt-and-catch-fire b/Lang/Rebol/Halt-and-catch-fire new file mode 120000 index 0000000000..4e21d500fa --- /dev/null +++ b/Lang/Rebol/Halt-and-catch-fire @@ -0,0 +1 @@ +../../Task/Halt-and-catch-fire/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Handle-a-signal b/Lang/Rebol/Handle-a-signal new file mode 120000 index 0000000000..67b30c2214 --- /dev/null +++ b/Lang/Rebol/Handle-a-signal @@ -0,0 +1 @@ +../../Task/Handle-a-signal/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Hash-from-two-arrays b/Lang/Rebol/Hash-from-two-arrays new file mode 120000 index 0000000000..de8389960e --- /dev/null +++ b/Lang/Rebol/Hash-from-two-arrays @@ -0,0 +1 @@ +../../Task/Hash-from-two-arrays/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Hash-join b/Lang/Rebol/Hash-join new file mode 120000 index 0000000000..02b63d13c7 --- /dev/null +++ b/Lang/Rebol/Hash-join @@ -0,0 +1 @@ +../../Task/Hash-join/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Hello-world-Graphical b/Lang/Rebol/Hello-world-Graphical new file mode 120000 index 0000000000..e8f4608f84 --- /dev/null +++ b/Lang/Rebol/Hello-world-Graphical @@ -0,0 +1 @@ +../../Task/Hello-world-Graphical/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Hello-world-Newline-omission b/Lang/Rebol/Hello-world-Newline-omission new file mode 120000 index 0000000000..2762747194 --- /dev/null +++ b/Lang/Rebol/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Hello-world-Text b/Lang/Rebol/Hello-world-Text new file mode 120000 index 0000000000..2b783947da --- /dev/null +++ b/Lang/Rebol/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Higher-order-functions b/Lang/Rebol/Higher-order-functions new file mode 120000 index 0000000000..6c4634db1c --- /dev/null +++ b/Lang/Rebol/Higher-order-functions @@ -0,0 +1 @@ +../../Task/Higher-order-functions/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Horners-rule-for-polynomial-evaluation b/Lang/Rebol/Horners-rule-for-polynomial-evaluation new file mode 120000 index 0000000000..2e9d363a9e --- /dev/null +++ b/Lang/Rebol/Horners-rule-for-polynomial-evaluation @@ -0,0 +1 @@ +../../Task/Horners-rule-for-polynomial-evaluation/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Hostname b/Lang/Rebol/Hostname new file mode 120000 index 0000000000..3effe6dbed --- /dev/null +++ b/Lang/Rebol/Hostname @@ -0,0 +1 @@ +../../Task/Hostname/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Huffman-coding b/Lang/Rebol/Huffman-coding new file mode 120000 index 0000000000..545f0a329b --- /dev/null +++ b/Lang/Rebol/Huffman-coding @@ -0,0 +1 @@ +../../Task/Huffman-coding/Rebol \ No newline at end of file diff --git a/Lang/Rebol/I-before-E-except-after-C b/Lang/Rebol/I-before-E-except-after-C new file mode 120000 index 0000000000..e2b7750d9c --- /dev/null +++ b/Lang/Rebol/I-before-E-except-after-C @@ -0,0 +1 @@ +../../Task/I-before-E-except-after-C/Rebol \ No newline at end of file diff --git a/Lang/Rebol/ISBN13-check-digit b/Lang/Rebol/ISBN13-check-digit new file mode 120000 index 0000000000..aef47eac0f --- /dev/null +++ b/Lang/Rebol/ISBN13-check-digit @@ -0,0 +1 @@ +../../Task/ISBN13-check-digit/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Identity-matrix b/Lang/Rebol/Identity-matrix new file mode 120000 index 0000000000..6dfa288d93 --- /dev/null +++ b/Lang/Rebol/Identity-matrix @@ -0,0 +1 @@ +../../Task/Identity-matrix/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Image-noise b/Lang/Rebol/Image-noise new file mode 120000 index 0000000000..a58b511104 --- /dev/null +++ b/Lang/Rebol/Image-noise @@ -0,0 +1 @@ +../../Task/Image-noise/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Increment-a-numerical-string b/Lang/Rebol/Increment-a-numerical-string new file mode 120000 index 0000000000..1d874b5b6c --- /dev/null +++ b/Lang/Rebol/Increment-a-numerical-string @@ -0,0 +1 @@ +../../Task/Increment-a-numerical-string/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Inheritance-Single b/Lang/Rebol/Inheritance-Single new file mode 120000 index 0000000000..0d3eb9573f --- /dev/null +++ b/Lang/Rebol/Inheritance-Single @@ -0,0 +1 @@ +../../Task/Inheritance-Single/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Input-loop b/Lang/Rebol/Input-loop new file mode 120000 index 0000000000..62007f0b87 --- /dev/null +++ b/Lang/Rebol/Input-loop @@ -0,0 +1 @@ +../../Task/Input-loop/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Integer-comparison b/Lang/Rebol/Integer-comparison new file mode 120000 index 0000000000..7349100994 --- /dev/null +++ b/Lang/Rebol/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Integer-overflow b/Lang/Rebol/Integer-overflow new file mode 120000 index 0000000000..8caca51571 --- /dev/null +++ b/Lang/Rebol/Integer-overflow @@ -0,0 +1 @@ +../../Task/Integer-overflow/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Interactive-programming-repl- b/Lang/Rebol/Interactive-programming-repl- new file mode 120000 index 0000000000..e63ccabe70 --- /dev/null +++ b/Lang/Rebol/Interactive-programming-repl- @@ -0,0 +1 @@ +../../Task/Interactive-programming-repl-/Rebol \ No newline at end of file diff --git a/Lang/Rebol/JSON b/Lang/Rebol/JSON new file mode 120000 index 0000000000..8bd9ae2a02 --- /dev/null +++ b/Lang/Rebol/JSON @@ -0,0 +1 @@ +../../Task/JSON/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Jacobsthal-numbers b/Lang/Rebol/Jacobsthal-numbers new file mode 120000 index 0000000000..0faf5cccbd --- /dev/null +++ b/Lang/Rebol/Jacobsthal-numbers @@ -0,0 +1 @@ +../../Task/Jacobsthal-numbers/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Jewels-and-stones b/Lang/Rebol/Jewels-and-stones new file mode 120000 index 0000000000..b876a95e71 --- /dev/null +++ b/Lang/Rebol/Jewels-and-stones @@ -0,0 +1 @@ +../../Task/Jewels-and-stones/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Josephus-problem b/Lang/Rebol/Josephus-problem new file mode 120000 index 0000000000..0a4a059418 --- /dev/null +++ b/Lang/Rebol/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Keyboard-macros b/Lang/Rebol/Keyboard-macros new file mode 120000 index 0000000000..6090099e1c --- /dev/null +++ b/Lang/Rebol/Keyboard-macros @@ -0,0 +1 @@ +../../Task/Keyboard-macros/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Knapsack-problem-0-1 b/Lang/Rebol/Knapsack-problem-0-1 new file mode 120000 index 0000000000..a86da2e20d --- /dev/null +++ b/Lang/Rebol/Knapsack-problem-0-1 @@ -0,0 +1 @@ +../../Task/Knapsack-problem-0-1/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Knapsack-problem-Bounded b/Lang/Rebol/Knapsack-problem-Bounded new file mode 120000 index 0000000000..75ecc0ad88 --- /dev/null +++ b/Lang/Rebol/Knapsack-problem-Bounded @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Bounded/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Knapsack-problem-Continuous b/Lang/Rebol/Knapsack-problem-Continuous new file mode 120000 index 0000000000..d2d9139eb3 --- /dev/null +++ b/Lang/Rebol/Knapsack-problem-Continuous @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Continuous/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Knapsack-problem-Unbounded b/Lang/Rebol/Knapsack-problem-Unbounded new file mode 120000 index 0000000000..05a28b3b91 --- /dev/null +++ b/Lang/Rebol/Knapsack-problem-Unbounded @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Unbounded/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Knights-tour b/Lang/Rebol/Knights-tour new file mode 120000 index 0000000000..71e91ef802 --- /dev/null +++ b/Lang/Rebol/Knights-tour @@ -0,0 +1 @@ +../../Task/Knights-tour/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Knuth-shuffle b/Lang/Rebol/Knuth-shuffle new file mode 120000 index 0000000000..34c5744ed5 --- /dev/null +++ b/Lang/Rebol/Knuth-shuffle @@ -0,0 +1 @@ +../../Task/Knuth-shuffle/Rebol \ No newline at end of file diff --git a/Lang/Rebol/LZW-compression b/Lang/Rebol/LZW-compression new file mode 120000 index 0000000000..6ef643485d --- /dev/null +++ b/Lang/Rebol/LZW-compression @@ -0,0 +1 @@ +../../Task/LZW-compression/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Largest-number-divisible-by-its-digits b/Lang/Rebol/Largest-number-divisible-by-its-digits new file mode 120000 index 0000000000..ded7dc4f52 --- /dev/null +++ b/Lang/Rebol/Largest-number-divisible-by-its-digits @@ -0,0 +1 @@ +../../Task/Largest-number-divisible-by-its-digits/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Last-Friday-of-each-month b/Lang/Rebol/Last-Friday-of-each-month new file mode 120000 index 0000000000..22f9e289f1 --- /dev/null +++ b/Lang/Rebol/Last-Friday-of-each-month @@ -0,0 +1 @@ +../../Task/Last-Friday-of-each-month/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Leap-year b/Lang/Rebol/Leap-year new file mode 120000 index 0000000000..fe28d10471 --- /dev/null +++ b/Lang/Rebol/Leap-year @@ -0,0 +1 @@ +../../Task/Leap-year/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Letter-frequency b/Lang/Rebol/Letter-frequency new file mode 120000 index 0000000000..f821174d22 --- /dev/null +++ b/Lang/Rebol/Letter-frequency @@ -0,0 +1 @@ +../../Task/Letter-frequency/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Levenshtein-distance b/Lang/Rebol/Levenshtein-distance new file mode 120000 index 0000000000..8eb20cd9e5 --- /dev/null +++ b/Lang/Rebol/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Literals-Floating-point b/Lang/Rebol/Literals-Floating-point new file mode 120000 index 0000000000..446f0ca13c --- /dev/null +++ b/Lang/Rebol/Literals-Floating-point @@ -0,0 +1 @@ +../../Task/Literals-Floating-point/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Literals-Integer b/Lang/Rebol/Literals-Integer new file mode 120000 index 0000000000..61eb2276ad --- /dev/null +++ b/Lang/Rebol/Literals-Integer @@ -0,0 +1 @@ +../../Task/Literals-Integer/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Logical-operations b/Lang/Rebol/Logical-operations new file mode 120000 index 0000000000..4ccc093b6a --- /dev/null +++ b/Lang/Rebol/Logical-operations @@ -0,0 +1 @@ +../../Task/Logical-operations/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Look-and-say-sequence b/Lang/Rebol/Look-and-say-sequence new file mode 120000 index 0000000000..5af8fa2fe8 --- /dev/null +++ b/Lang/Rebol/Look-and-say-sequence @@ -0,0 +1 @@ +../../Task/Look-and-say-sequence/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Loop-over-multiple-arrays-simultaneously b/Lang/Rebol/Loop-over-multiple-arrays-simultaneously new file mode 120000 index 0000000000..7e8df4a406 --- /dev/null +++ b/Lang/Rebol/Loop-over-multiple-arrays-simultaneously @@ -0,0 +1 @@ +../../Task/Loop-over-multiple-arrays-simultaneously/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Loops-Break b/Lang/Rebol/Loops-Break new file mode 120000 index 0000000000..a7d70b8ddf --- /dev/null +++ b/Lang/Rebol/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Loops-Continue b/Lang/Rebol/Loops-Continue new file mode 120000 index 0000000000..eb55ae4a46 --- /dev/null +++ b/Lang/Rebol/Loops-Continue @@ -0,0 +1 @@ +../../Task/Loops-Continue/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Loops-Do-while b/Lang/Rebol/Loops-Do-while new file mode 120000 index 0000000000..7b9c11e6c9 --- /dev/null +++ b/Lang/Rebol/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Loops-Downward-for b/Lang/Rebol/Loops-Downward-for new file mode 120000 index 0000000000..aabadccc5d --- /dev/null +++ b/Lang/Rebol/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Loops-For b/Lang/Rebol/Loops-For new file mode 120000 index 0000000000..3441cbf3e4 --- /dev/null +++ b/Lang/Rebol/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Loops-For-with-a-specified-step b/Lang/Rebol/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..48cddeed7c --- /dev/null +++ b/Lang/Rebol/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Loops-Foreach b/Lang/Rebol/Loops-Foreach new file mode 120000 index 0000000000..5113646d4a --- /dev/null +++ b/Lang/Rebol/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Loops-Increment-loop-index-within-loop-body b/Lang/Rebol/Loops-Increment-loop-index-within-loop-body new file mode 120000 index 0000000000..2a105f8219 --- /dev/null +++ b/Lang/Rebol/Loops-Increment-loop-index-within-loop-body @@ -0,0 +1 @@ +../../Task/Loops-Increment-loop-index-within-loop-body/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Loops-Infinite b/Lang/Rebol/Loops-Infinite new file mode 120000 index 0000000000..b9782bb44c --- /dev/null +++ b/Lang/Rebol/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Loops-N-plus-one-half b/Lang/Rebol/Loops-N-plus-one-half new file mode 120000 index 0000000000..fde94d5278 --- /dev/null +++ b/Lang/Rebol/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Loops-Nested b/Lang/Rebol/Loops-Nested new file mode 120000 index 0000000000..8570918c54 --- /dev/null +++ b/Lang/Rebol/Loops-Nested @@ -0,0 +1 @@ +../../Task/Loops-Nested/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Loops-While b/Lang/Rebol/Loops-While new file mode 120000 index 0000000000..d6ae658607 --- /dev/null +++ b/Lang/Rebol/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Loops-With-multiple-ranges b/Lang/Rebol/Loops-With-multiple-ranges new file mode 120000 index 0000000000..1444c994ba --- /dev/null +++ b/Lang/Rebol/Loops-With-multiple-ranges @@ -0,0 +1 @@ +../../Task/Loops-With-multiple-ranges/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Loops-Wrong-ranges b/Lang/Rebol/Loops-Wrong-ranges new file mode 120000 index 0000000000..8c6fabb9b5 --- /dev/null +++ b/Lang/Rebol/Loops-Wrong-ranges @@ -0,0 +1 @@ +../../Task/Loops-Wrong-ranges/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Ludic-numbers b/Lang/Rebol/Ludic-numbers new file mode 120000 index 0000000000..a4ebabb376 --- /dev/null +++ b/Lang/Rebol/Ludic-numbers @@ -0,0 +1 @@ +../../Task/Ludic-numbers/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Luhn-test-of-credit-card-numbers b/Lang/Rebol/Luhn-test-of-credit-card-numbers new file mode 120000 index 0000000000..54db6d0086 --- /dev/null +++ b/Lang/Rebol/Luhn-test-of-credit-card-numbers @@ -0,0 +1 @@ +../../Task/Luhn-test-of-credit-card-numbers/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Lychrel-numbers b/Lang/Rebol/Lychrel-numbers new file mode 120000 index 0000000000..a9ccc00139 --- /dev/null +++ b/Lang/Rebol/Lychrel-numbers @@ -0,0 +1 @@ +../../Task/Lychrel-numbers/Rebol \ No newline at end of file diff --git a/Lang/Rebol/MAC-vendor-lookup b/Lang/Rebol/MAC-vendor-lookup new file mode 120000 index 0000000000..ea5da48c4a --- /dev/null +++ b/Lang/Rebol/MAC-vendor-lookup @@ -0,0 +1 @@ +../../Task/MAC-vendor-lookup/Rebol \ No newline at end of file diff --git a/Lang/Rebol/MD5 b/Lang/Rebol/MD5 new file mode 120000 index 0000000000..8e783d3330 --- /dev/null +++ b/Lang/Rebol/MD5 @@ -0,0 +1 @@ +../../Task/MD5/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Mad-Libs b/Lang/Rebol/Mad-Libs new file mode 120000 index 0000000000..e503266ac3 --- /dev/null +++ b/Lang/Rebol/Mad-Libs @@ -0,0 +1 @@ +../../Task/Mad-Libs/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Mandelbrot-set b/Lang/Rebol/Mandelbrot-set new file mode 120000 index 0000000000..9795649798 --- /dev/null +++ b/Lang/Rebol/Mandelbrot-set @@ -0,0 +1 @@ +../../Task/Mandelbrot-set/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Mayan-numerals b/Lang/Rebol/Mayan-numerals new file mode 120000 index 0000000000..f3c3f1ac1b --- /dev/null +++ b/Lang/Rebol/Mayan-numerals @@ -0,0 +1 @@ +../../Task/Mayan-numerals/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Maze-generation b/Lang/Rebol/Maze-generation new file mode 120000 index 0000000000..16909e3bd3 --- /dev/null +++ b/Lang/Rebol/Maze-generation @@ -0,0 +1 @@ +../../Task/Maze-generation/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Menu b/Lang/Rebol/Menu new file mode 120000 index 0000000000..0970cb6584 --- /dev/null +++ b/Lang/Rebol/Menu @@ -0,0 +1 @@ +../../Task/Menu/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Morse-code b/Lang/Rebol/Morse-code new file mode 120000 index 0000000000..9b184a4368 --- /dev/null +++ b/Lang/Rebol/Morse-code @@ -0,0 +1 @@ +../../Task/Morse-code/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Multiplication-tables b/Lang/Rebol/Multiplication-tables new file mode 120000 index 0000000000..19c593899a --- /dev/null +++ b/Lang/Rebol/Multiplication-tables @@ -0,0 +1 @@ +../../Task/Multiplication-tables/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Mutual-recursion b/Lang/Rebol/Mutual-recursion new file mode 120000 index 0000000000..3927e2e3d0 --- /dev/null +++ b/Lang/Rebol/Mutual-recursion @@ -0,0 +1 @@ +../../Task/Mutual-recursion/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Nim-game b/Lang/Rebol/Nim-game new file mode 120000 index 0000000000..3d509e2da0 --- /dev/null +++ b/Lang/Rebol/Nim-game @@ -0,0 +1 @@ +../../Task/Nim-game/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Null-object b/Lang/Rebol/Null-object new file mode 120000 index 0000000000..6d91c61493 --- /dev/null +++ b/Lang/Rebol/Null-object @@ -0,0 +1 @@ +../../Task/Null-object/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Number-reversal-game b/Lang/Rebol/Number-reversal-game new file mode 120000 index 0000000000..225b967208 --- /dev/null +++ b/Lang/Rebol/Number-reversal-game @@ -0,0 +1 @@ +../../Task/Number-reversal-game/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Object-serialization b/Lang/Rebol/Object-serialization new file mode 120000 index 0000000000..b546950e51 --- /dev/null +++ b/Lang/Rebol/Object-serialization @@ -0,0 +1 @@ +../../Task/Object-serialization/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Ordered-words b/Lang/Rebol/Ordered-words new file mode 120000 index 0000000000..62492c8748 --- /dev/null +++ b/Lang/Rebol/Ordered-words @@ -0,0 +1 @@ +../../Task/Ordered-words/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Padovan-n-step-number-sequences b/Lang/Rebol/Padovan-n-step-number-sequences new file mode 120000 index 0000000000..6ce6076d9f --- /dev/null +++ b/Lang/Rebol/Padovan-n-step-number-sequences @@ -0,0 +1 @@ +../../Task/Padovan-n-step-number-sequences/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Palindrome-detection b/Lang/Rebol/Palindrome-detection new file mode 120000 index 0000000000..976abf960a --- /dev/null +++ b/Lang/Rebol/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Palindromic-gapful-numbers b/Lang/Rebol/Palindromic-gapful-numbers new file mode 120000 index 0000000000..ce1a9844df --- /dev/null +++ b/Lang/Rebol/Palindromic-gapful-numbers @@ -0,0 +1 @@ +../../Task/Palindromic-gapful-numbers/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Parsing-Shunting-yard-algorithm b/Lang/Rebol/Parsing-Shunting-yard-algorithm new file mode 120000 index 0000000000..b48c2dd4c0 --- /dev/null +++ b/Lang/Rebol/Parsing-Shunting-yard-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-Shunting-yard-algorithm/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Pentagram b/Lang/Rebol/Pentagram new file mode 120000 index 0000000000..707cf04e6c --- /dev/null +++ b/Lang/Rebol/Pentagram @@ -0,0 +1 @@ +../../Task/Pentagram/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Percentage-difference-between-images b/Lang/Rebol/Percentage-difference-between-images new file mode 120000 index 0000000000..4b4ccc789a --- /dev/null +++ b/Lang/Rebol/Percentage-difference-between-images @@ -0,0 +1 @@ +../../Task/Percentage-difference-between-images/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Perfect-numbers b/Lang/Rebol/Perfect-numbers new file mode 120000 index 0000000000..cc7bf3b1d8 --- /dev/null +++ b/Lang/Rebol/Perfect-numbers @@ -0,0 +1 @@ +../../Task/Perfect-numbers/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Permutation-test b/Lang/Rebol/Permutation-test new file mode 120000 index 0000000000..33aca0c009 --- /dev/null +++ b/Lang/Rebol/Permutation-test @@ -0,0 +1 @@ +../../Task/Permutation-test/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Pick-random-element b/Lang/Rebol/Pick-random-element new file mode 120000 index 0000000000..a63070b88e --- /dev/null +++ b/Lang/Rebol/Pick-random-element @@ -0,0 +1 @@ +../../Task/Pick-random-element/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Playing-cards b/Lang/Rebol/Playing-cards new file mode 120000 index 0000000000..77a603d4f6 --- /dev/null +++ b/Lang/Rebol/Playing-cards @@ -0,0 +1 @@ +../../Task/Playing-cards/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Poker-hand-analyser b/Lang/Rebol/Poker-hand-analyser new file mode 120000 index 0000000000..cd92bc4893 --- /dev/null +++ b/Lang/Rebol/Poker-hand-analyser @@ -0,0 +1 @@ +../../Task/Poker-hand-analyser/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Polyspiral b/Lang/Rebol/Polyspiral new file mode 120000 index 0000000000..a68aec96f7 --- /dev/null +++ b/Lang/Rebol/Polyspiral @@ -0,0 +1 @@ +../../Task/Polyspiral/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Primality-by-trial-division b/Lang/Rebol/Primality-by-trial-division new file mode 120000 index 0000000000..efa17720e9 --- /dev/null +++ b/Lang/Rebol/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Program-termination b/Lang/Rebol/Program-termination new file mode 120000 index 0000000000..24f49d0325 --- /dev/null +++ b/Lang/Rebol/Program-termination @@ -0,0 +1 @@ +../../Task/Program-termination/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Pythagoras-tree b/Lang/Rebol/Pythagoras-tree new file mode 120000 index 0000000000..f30dc63938 --- /dev/null +++ b/Lang/Rebol/Pythagoras-tree @@ -0,0 +1 @@ +../../Task/Pythagoras-tree/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Queue-Definition b/Lang/Rebol/Queue-Definition new file mode 120000 index 0000000000..162ba667c2 --- /dev/null +++ b/Lang/Rebol/Queue-Definition @@ -0,0 +1 @@ +../../Task/Queue-Definition/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Queue-Usage b/Lang/Rebol/Queue-Usage new file mode 120000 index 0000000000..f4c7c7a4c3 --- /dev/null +++ b/Lang/Rebol/Queue-Usage @@ -0,0 +1 @@ +../../Task/Queue-Usage/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Quine b/Lang/Rebol/Quine new file mode 120000 index 0000000000..27b88ad2ff --- /dev/null +++ b/Lang/Rebol/Quine @@ -0,0 +1 @@ +../../Task/Quine/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Quoting-constructs b/Lang/Rebol/Quoting-constructs new file mode 120000 index 0000000000..cfd2d459f0 --- /dev/null +++ b/Lang/Rebol/Quoting-constructs @@ -0,0 +1 @@ +../../Task/Quoting-constructs/Rebol \ No newline at end of file diff --git a/Lang/Rebol/RPG-attributes-generator b/Lang/Rebol/RPG-attributes-generator new file mode 120000 index 0000000000..b156c392e1 --- /dev/null +++ b/Lang/Rebol/RPG-attributes-generator @@ -0,0 +1 @@ +../../Task/RPG-attributes-generator/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Read-a-specific-line-from-a-file b/Lang/Rebol/Read-a-specific-line-from-a-file new file mode 120000 index 0000000000..14a1597027 --- /dev/null +++ b/Lang/Rebol/Read-a-specific-line-from-a-file @@ -0,0 +1 @@ +../../Task/Read-a-specific-line-from-a-file/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Read-entire-file b/Lang/Rebol/Read-entire-file new file mode 120000 index 0000000000..28b35bf7cc --- /dev/null +++ b/Lang/Rebol/Read-entire-file @@ -0,0 +1 @@ +../../Task/Read-entire-file/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Recamans-sequence b/Lang/Rebol/Recamans-sequence new file mode 120000 index 0000000000..bfdd733327 --- /dev/null +++ b/Lang/Rebol/Recamans-sequence @@ -0,0 +1 @@ +../../Task/Recamans-sequence/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Reduced-row-echelon-form b/Lang/Rebol/Reduced-row-echelon-form new file mode 120000 index 0000000000..743fe9cee3 --- /dev/null +++ b/Lang/Rebol/Reduced-row-echelon-form @@ -0,0 +1 @@ +../../Task/Reduced-row-echelon-form/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Regular-expressions b/Lang/Rebol/Regular-expressions new file mode 120000 index 0000000000..8b6a46c176 --- /dev/null +++ b/Lang/Rebol/Regular-expressions @@ -0,0 +1 @@ +../../Task/Regular-expressions/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Remove-duplicate-elements b/Lang/Rebol/Remove-duplicate-elements new file mode 120000 index 0000000000..e15cb15fa9 --- /dev/null +++ b/Lang/Rebol/Remove-duplicate-elements @@ -0,0 +1 @@ +../../Task/Remove-duplicate-elements/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Rename-a-file b/Lang/Rebol/Rename-a-file new file mode 120000 index 0000000000..b1a36bd846 --- /dev/null +++ b/Lang/Rebol/Rename-a-file @@ -0,0 +1 @@ +../../Task/Rename-a-file/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Repeat-a-string b/Lang/Rebol/Repeat-a-string new file mode 120000 index 0000000000..ef9fbbc4ad --- /dev/null +++ b/Lang/Rebol/Repeat-a-string @@ -0,0 +1 @@ +../../Task/Repeat-a-string/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Reverse-a-string b/Lang/Rebol/Reverse-a-string new file mode 120000 index 0000000000..58f8abd089 --- /dev/null +++ b/Lang/Rebol/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Rock-paper-scissors b/Lang/Rebol/Rock-paper-scissors new file mode 120000 index 0000000000..cda68fe0a1 --- /dev/null +++ b/Lang/Rebol/Rock-paper-scissors @@ -0,0 +1 @@ +../../Task/Rock-paper-scissors/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Rosetta-Code-Count-examples b/Lang/Rebol/Rosetta-Code-Count-examples new file mode 120000 index 0000000000..d0380c9f7b --- /dev/null +++ b/Lang/Rebol/Rosetta-Code-Count-examples @@ -0,0 +1 @@ +../../Task/Rosetta-Code-Count-examples/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Rosetta-Code-Find-unimplemented-tasks b/Lang/Rebol/Rosetta-Code-Find-unimplemented-tasks new file mode 120000 index 0000000000..24ea450c68 --- /dev/null +++ b/Lang/Rebol/Rosetta-Code-Find-unimplemented-tasks @@ -0,0 +1 @@ +../../Task/Rosetta-Code-Find-unimplemented-tasks/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Rosetta-Code-Rank-languages-by-popularity b/Lang/Rebol/Rosetta-Code-Rank-languages-by-popularity new file mode 120000 index 0000000000..fab9075fea --- /dev/null +++ b/Lang/Rebol/Rosetta-Code-Rank-languages-by-popularity @@ -0,0 +1 @@ +../../Task/Rosetta-Code-Rank-languages-by-popularity/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Rot-13 b/Lang/Rebol/Rot-13 new file mode 120000 index 0000000000..237e499a3f --- /dev/null +++ b/Lang/Rebol/Rot-13 @@ -0,0 +1 @@ +../../Task/Rot-13/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Runtime-evaluation b/Lang/Rebol/Runtime-evaluation new file mode 120000 index 0000000000..b5e1f8ecde --- /dev/null +++ b/Lang/Rebol/Runtime-evaluation @@ -0,0 +1 @@ +../../Task/Runtime-evaluation/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Runtime-evaluation-In-an-environment b/Lang/Rebol/Runtime-evaluation-In-an-environment new file mode 120000 index 0000000000..f0cf1819d7 --- /dev/null +++ b/Lang/Rebol/Runtime-evaluation-In-an-environment @@ -0,0 +1 @@ +../../Task/Runtime-evaluation-In-an-environment/Rebol \ No newline at end of file diff --git a/Lang/Rebol/SHA-1 b/Lang/Rebol/SHA-1 new file mode 120000 index 0000000000..6006c706a1 --- /dev/null +++ b/Lang/Rebol/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/Rebol \ No newline at end of file diff --git a/Lang/Rebol/SHA-256 b/Lang/Rebol/SHA-256 new file mode 120000 index 0000000000..a282c64fe3 --- /dev/null +++ b/Lang/Rebol/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/Rebol \ No newline at end of file diff --git a/Lang/Rebol/SHA-256-Merkle-tree b/Lang/Rebol/SHA-256-Merkle-tree new file mode 120000 index 0000000000..3ec6fddf77 --- /dev/null +++ b/Lang/Rebol/SHA-256-Merkle-tree @@ -0,0 +1 @@ +../../Task/SHA-256-Merkle-tree/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Search-a-list b/Lang/Rebol/Search-a-list new file mode 120000 index 0000000000..318894f6a3 --- /dev/null +++ b/Lang/Rebol/Search-a-list @@ -0,0 +1 @@ +../../Task/Search-a-list/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Self-describing-numbers b/Lang/Rebol/Self-describing-numbers new file mode 120000 index 0000000000..e068493027 --- /dev/null +++ b/Lang/Rebol/Self-describing-numbers @@ -0,0 +1 @@ +../../Task/Self-describing-numbers/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Semordnilap b/Lang/Rebol/Semordnilap new file mode 120000 index 0000000000..0da3f78b6d --- /dev/null +++ b/Lang/Rebol/Semordnilap @@ -0,0 +1 @@ +../../Task/Semordnilap/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Send-email b/Lang/Rebol/Send-email new file mode 120000 index 0000000000..bdcdb84d73 --- /dev/null +++ b/Lang/Rebol/Send-email @@ -0,0 +1 @@ +../../Task/Send-email/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Shell-one-liner b/Lang/Rebol/Shell-one-liner new file mode 120000 index 0000000000..d93fe376ad --- /dev/null +++ b/Lang/Rebol/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Show-ASCII-table b/Lang/Rebol/Show-ASCII-table new file mode 120000 index 0000000000..73b59f4704 --- /dev/null +++ b/Lang/Rebol/Show-ASCII-table @@ -0,0 +1 @@ +../../Task/Show-ASCII-table/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Sieve-of-Eratosthenes b/Lang/Rebol/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..304a7c5cc4 --- /dev/null +++ b/Lang/Rebol/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Sieve-of-Pritchard b/Lang/Rebol/Sieve-of-Pritchard new file mode 120000 index 0000000000..ae2da5fd4b --- /dev/null +++ b/Lang/Rebol/Sieve-of-Pritchard @@ -0,0 +1 @@ +../../Task/Sieve-of-Pritchard/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Simple-database b/Lang/Rebol/Simple-database new file mode 120000 index 0000000000..91cc755165 --- /dev/null +++ b/Lang/Rebol/Simple-database @@ -0,0 +1 @@ +../../Task/Simple-database/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Simple-windowed-application b/Lang/Rebol/Simple-windowed-application new file mode 120000 index 0000000000..9329534018 --- /dev/null +++ b/Lang/Rebol/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Sleep b/Lang/Rebol/Sleep new file mode 120000 index 0000000000..93ccbde879 --- /dev/null +++ b/Lang/Rebol/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Sort-an-integer-array b/Lang/Rebol/Sort-an-integer-array new file mode 120000 index 0000000000..964bc28a49 --- /dev/null +++ b/Lang/Rebol/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Sort-stability b/Lang/Rebol/Sort-stability new file mode 120000 index 0000000000..398ebf99ce --- /dev/null +++ b/Lang/Rebol/Sort-stability @@ -0,0 +1 @@ +../../Task/Sort-stability/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Sorting-algorithms-Gnome-sort b/Lang/Rebol/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..5a1b4b5c4b --- /dev/null +++ b/Lang/Rebol/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Sorting-algorithms-Insertion-sort b/Lang/Rebol/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..542842155d --- /dev/null +++ b/Lang/Rebol/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Sorting-algorithms-Merge-sort b/Lang/Rebol/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..c0e13b1fde --- /dev/null +++ b/Lang/Rebol/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Sorting-algorithms-Stooge-sort b/Lang/Rebol/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..330c056497 --- /dev/null +++ b/Lang/Rebol/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Spiral-matrix b/Lang/Rebol/Spiral-matrix new file mode 120000 index 0000000000..5be66bebd7 --- /dev/null +++ b/Lang/Rebol/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Stack b/Lang/Rebol/Stack new file mode 120000 index 0000000000..4ddf42dff7 --- /dev/null +++ b/Lang/Rebol/Stack @@ -0,0 +1 @@ +../../Task/Stack/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Stair-climbing-puzzle b/Lang/Rebol/Stair-climbing-puzzle new file mode 120000 index 0000000000..30110c39ff --- /dev/null +++ b/Lang/Rebol/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Statistics-Normal-distribution b/Lang/Rebol/Statistics-Normal-distribution new file mode 120000 index 0000000000..c2c6f8e607 --- /dev/null +++ b/Lang/Rebol/Statistics-Normal-distribution @@ -0,0 +1 @@ +../../Task/Statistics-Normal-distribution/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Straddling-checkerboard b/Lang/Rebol/Straddling-checkerboard new file mode 120000 index 0000000000..b2cd63efdf --- /dev/null +++ b/Lang/Rebol/Straddling-checkerboard @@ -0,0 +1 @@ +../../Task/Straddling-checkerboard/Rebol \ No newline at end of file diff --git a/Lang/Rebol/String-case b/Lang/Rebol/String-case new file mode 120000 index 0000000000..99d32eb89d --- /dev/null +++ b/Lang/Rebol/String-case @@ -0,0 +1 @@ +../../Task/String-case/Rebol \ No newline at end of file diff --git a/Lang/Rebol/String-concatenation b/Lang/Rebol/String-concatenation new file mode 120000 index 0000000000..60e5df3a60 --- /dev/null +++ b/Lang/Rebol/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Rebol \ No newline at end of file diff --git a/Lang/Rebol/String-interpolation-included- b/Lang/Rebol/String-interpolation-included- new file mode 120000 index 0000000000..0d16a99c3d --- /dev/null +++ b/Lang/Rebol/String-interpolation-included- @@ -0,0 +1 @@ +../../Task/String-interpolation-included-/Rebol \ No newline at end of file diff --git a/Lang/Rebol/String-length b/Lang/Rebol/String-length new file mode 120000 index 0000000000..4008031d32 --- /dev/null +++ b/Lang/Rebol/String-length @@ -0,0 +1 @@ +../../Task/String-length/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Strip-comments-from-a-string b/Lang/Rebol/Strip-comments-from-a-string new file mode 120000 index 0000000000..7d0be8f55b --- /dev/null +++ b/Lang/Rebol/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Substring b/Lang/Rebol/Substring new file mode 120000 index 0000000000..16d8520df3 --- /dev/null +++ b/Lang/Rebol/Substring @@ -0,0 +1 @@ +../../Task/Substring/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Sum-and-product-of-an-array b/Lang/Rebol/Sum-and-product-of-an-array new file mode 120000 index 0000000000..f0691c6c52 --- /dev/null +++ b/Lang/Rebol/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Symmetric-difference b/Lang/Rebol/Symmetric-difference new file mode 120000 index 0000000000..ead8d7c53a --- /dev/null +++ b/Lang/Rebol/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Rebol \ No newline at end of file diff --git a/Lang/Rebol/System-time b/Lang/Rebol/System-time new file mode 120000 index 0000000000..26192d37e7 --- /dev/null +++ b/Lang/Rebol/System-time @@ -0,0 +1 @@ +../../Task/System-time/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Take-notes-on-the-command-line b/Lang/Rebol/Take-notes-on-the-command-line new file mode 120000 index 0000000000..686f0e9609 --- /dev/null +++ b/Lang/Rebol/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Terminal-control-Clear-the-screen b/Lang/Rebol/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..26092c08d5 --- /dev/null +++ b/Lang/Rebol/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Terminal-control-Coloured-text b/Lang/Rebol/Terminal-control-Coloured-text new file mode 120000 index 0000000000..91c395fe7a --- /dev/null +++ b/Lang/Rebol/Terminal-control-Coloured-text @@ -0,0 +1 @@ +../../Task/Terminal-control-Coloured-text/Rebol \ No newline at end of file diff --git a/Lang/Rebol/The-Twelve-Days-of-Christmas b/Lang/Rebol/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..1cd8cfb663 --- /dev/null +++ b/Lang/Rebol/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Tokenize-a-string b/Lang/Rebol/Tokenize-a-string new file mode 120000 index 0000000000..683933fc1a --- /dev/null +++ b/Lang/Rebol/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Towers-of-Hanoi b/Lang/Rebol/Towers-of-Hanoi new file mode 120000 index 0000000000..256a976fba --- /dev/null +++ b/Lang/Rebol/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Transliterate-English-text-using-the-Greek-alphabet b/Lang/Rebol/Transliterate-English-text-using-the-Greek-alphabet new file mode 120000 index 0000000000..6cd5a9fcd9 --- /dev/null +++ b/Lang/Rebol/Transliterate-English-text-using-the-Greek-alphabet @@ -0,0 +1 @@ +../../Task/Transliterate-English-text-using-the-Greek-alphabet/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Tree-traversal b/Lang/Rebol/Tree-traversal new file mode 120000 index 0000000000..a9acbc3e12 --- /dev/null +++ b/Lang/Rebol/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Trigonometric-functions b/Lang/Rebol/Trigonometric-functions new file mode 120000 index 0000000000..31689c9f7b --- /dev/null +++ b/Lang/Rebol/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Truncate-a-file b/Lang/Rebol/Truncate-a-file new file mode 120000 index 0000000000..a6b1c49090 --- /dev/null +++ b/Lang/Rebol/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Twos-complement b/Lang/Rebol/Twos-complement new file mode 120000 index 0000000000..7d177dca86 --- /dev/null +++ b/Lang/Rebol/Twos-complement @@ -0,0 +1 @@ +../../Task/Twos-complement/Rebol \ No newline at end of file diff --git a/Lang/Rebol/URL-decoding b/Lang/Rebol/URL-decoding new file mode 120000 index 0000000000..13aaaaf76d --- /dev/null +++ b/Lang/Rebol/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/Rebol \ No newline at end of file diff --git a/Lang/Rebol/URL-encoding b/Lang/Rebol/URL-encoding new file mode 120000 index 0000000000..f2738b2378 --- /dev/null +++ b/Lang/Rebol/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/Rebol \ No newline at end of file diff --git a/Lang/Rebol/User-input-Graphical b/Lang/Rebol/User-input-Graphical new file mode 120000 index 0000000000..9826592fbf --- /dev/null +++ b/Lang/Rebol/User-input-Graphical @@ -0,0 +1 @@ +../../Task/User-input-Graphical/Rebol \ No newline at end of file diff --git a/Lang/Rebol/User-input-Text b/Lang/Rebol/User-input-Text new file mode 120000 index 0000000000..61cd5bb640 --- /dev/null +++ b/Lang/Rebol/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Validate-International-Securities-Identification-Number b/Lang/Rebol/Validate-International-Securities-Identification-Number new file mode 120000 index 0000000000..c8f6432cf5 --- /dev/null +++ b/Lang/Rebol/Validate-International-Securities-Identification-Number @@ -0,0 +1 @@ +../../Task/Validate-International-Securities-Identification-Number/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Variadic-function b/Lang/Rebol/Variadic-function new file mode 120000 index 0000000000..eb753c87ca --- /dev/null +++ b/Lang/Rebol/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Vigen-re-cipher b/Lang/Rebol/Vigen-re-cipher new file mode 120000 index 0000000000..e4c0684470 --- /dev/null +++ b/Lang/Rebol/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Walk-a-directory-Non-recursively b/Lang/Rebol/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..7d9b757781 --- /dev/null +++ b/Lang/Rebol/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Walk-a-directory-Recursively b/Lang/Rebol/Walk-a-directory-Recursively new file mode 120000 index 0000000000..6bdc6972ee --- /dev/null +++ b/Lang/Rebol/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/Rebol \ No newline at end of file diff --git a/Lang/Rebol/War-card-game b/Lang/Rebol/War-card-game new file mode 120000 index 0000000000..25923c64aa --- /dev/null +++ b/Lang/Rebol/War-card-game @@ -0,0 +1 @@ +../../Task/War-card-game/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Web-scraping b/Lang/Rebol/Web-scraping new file mode 120000 index 0000000000..4e9367ba38 --- /dev/null +++ b/Lang/Rebol/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Window-creation b/Lang/Rebol/Window-creation new file mode 120000 index 0000000000..bd0bbb0b87 --- /dev/null +++ b/Lang/Rebol/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Word-frequency b/Lang/Rebol/Word-frequency new file mode 120000 index 0000000000..520eed281f --- /dev/null +++ b/Lang/Rebol/Word-frequency @@ -0,0 +1 @@ +../../Task/Word-frequency/Rebol \ No newline at end of file diff --git a/Lang/Rebol/XML-Input b/Lang/Rebol/XML-Input new file mode 120000 index 0000000000..014dc4f1f1 --- /dev/null +++ b/Lang/Rebol/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Y-combinator b/Lang/Rebol/Y-combinator new file mode 120000 index 0000000000..dcc94474b6 --- /dev/null +++ b/Lang/Rebol/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Zero-to-the-zero-power b/Lang/Rebol/Zero-to-the-zero-power new file mode 120000 index 0000000000..8722267184 --- /dev/null +++ b/Lang/Rebol/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Rebol \ No newline at end of file diff --git a/Lang/Rebol/Zig-zag-matrix b/Lang/Rebol/Zig-zag-matrix new file mode 120000 index 0000000000..ff69ef9beb --- /dev/null +++ b/Lang/Rebol/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Rebol \ No newline at end of file diff --git a/Lang/Red/00-LANG.txt b/Lang/Red/00-LANG.txt index 1cb6089084..bde0f4b81e 100644 --- a/Lang/Red/00-LANG.txt +++ b/Lang/Red/00-LANG.txt @@ -8,6 +8,9 @@ Like Rebol, Red has a low memory footprint, is garbage collected, and has a [htt Red embeds several DSLs, among which Red/System (C semantics meet Red syntax), dedicated to low-level and system programming. It is also used as an intermediate language (IL) when Red is compiled. The Red executable is able to build Red/System files directly (`*.reds`) as well as Red files (`*.red`), and Red/System code may be embedded freely in Red code. +==Todo== +[https://rosettacode.org/wiki/Tasks_not_implemented_in_Red Tasks not implemented in Red] + ==Useful links== * [http://www.red-lang.org Red Language Website] * [https://twitter.com/red_lang @red_lang] on Twitter. diff --git a/Lang/Red/Accumulator-factory b/Lang/Red/Accumulator-factory new file mode 120000 index 0000000000..73cf9ffff0 --- /dev/null +++ b/Lang/Red/Accumulator-factory @@ -0,0 +1 @@ +../../Task/Accumulator-factory/Red \ No newline at end of file diff --git a/Lang/Red/Address-of-a-variable b/Lang/Red/Address-of-a-variable new file mode 120000 index 0000000000..81b5a1a171 --- /dev/null +++ b/Lang/Red/Address-of-a-variable @@ -0,0 +1 @@ +../../Task/Address-of-a-variable/Red \ No newline at end of file diff --git a/Lang/Red/Angle-difference-between-two-bearings b/Lang/Red/Angle-difference-between-two-bearings new file mode 120000 index 0000000000..e218e0c4ee --- /dev/null +++ b/Lang/Red/Angle-difference-between-two-bearings @@ -0,0 +1 @@ +../../Task/Angle-difference-between-two-bearings/Red \ No newline at end of file diff --git a/Lang/Red/Angles-geometric-normalization-and-conversion b/Lang/Red/Angles-geometric-normalization-and-conversion new file mode 120000 index 0000000000..f969ff2c56 --- /dev/null +++ b/Lang/Red/Angles-geometric-normalization-and-conversion @@ -0,0 +1 @@ +../../Task/Angles-geometric-normalization-and-conversion/Red \ No newline at end of file diff --git a/Lang/Red/Arithmetic-Integer b/Lang/Red/Arithmetic-Integer new file mode 120000 index 0000000000..cb3f74d046 --- /dev/null +++ b/Lang/Red/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Red \ No newline at end of file diff --git a/Lang/Red/Arithmetic-evaluation b/Lang/Red/Arithmetic-evaluation new file mode 120000 index 0000000000..c6c5c304b5 --- /dev/null +++ b/Lang/Red/Arithmetic-evaluation @@ -0,0 +1 @@ +../../Task/Arithmetic-evaluation/Red \ No newline at end of file diff --git a/Lang/Red/Boolean-values b/Lang/Red/Boolean-values new file mode 120000 index 0000000000..3df0e7a087 --- /dev/null +++ b/Lang/Red/Boolean-values @@ -0,0 +1 @@ +../../Task/Boolean-values/Red \ No newline at end of file diff --git a/Lang/Red/Calendar b/Lang/Red/Calendar new file mode 120000 index 0000000000..3283fd5906 --- /dev/null +++ b/Lang/Red/Calendar @@ -0,0 +1 @@ +../../Task/Calendar/Red \ No newline at end of file diff --git a/Lang/Red/Calendar---for-REAL-programmers b/Lang/Red/Calendar---for-REAL-programmers new file mode 120000 index 0000000000..e0db1bd24f --- /dev/null +++ b/Lang/Red/Calendar---for-REAL-programmers @@ -0,0 +1 @@ +../../Task/Calendar---for-REAL-programmers/Red \ No newline at end of file diff --git a/Lang/Red/Call-a-function b/Lang/Red/Call-a-function new file mode 120000 index 0000000000..2907d38f1e --- /dev/null +++ b/Lang/Red/Call-a-function @@ -0,0 +1 @@ +../../Task/Call-a-function/Red \ No newline at end of file diff --git a/Lang/Red/Call-an-object-method b/Lang/Red/Call-an-object-method new file mode 120000 index 0000000000..50c2f71ec1 --- /dev/null +++ b/Lang/Red/Call-an-object-method @@ -0,0 +1 @@ +../../Task/Call-an-object-method/Red \ No newline at end of file diff --git a/Lang/Red/Case-sensitivity-of-identifiers b/Lang/Red/Case-sensitivity-of-identifiers new file mode 120000 index 0000000000..1f46e1aec5 --- /dev/null +++ b/Lang/Red/Case-sensitivity-of-identifiers @@ -0,0 +1 @@ +../../Task/Case-sensitivity-of-identifiers/Red \ No newline at end of file diff --git a/Lang/Red/Classes b/Lang/Red/Classes new file mode 120000 index 0000000000..5db3a1a49b --- /dev/null +++ b/Lang/Red/Classes @@ -0,0 +1 @@ +../../Task/Classes/Red \ No newline at end of file diff --git a/Lang/Red/Compare-length-of-two-strings b/Lang/Red/Compare-length-of-two-strings new file mode 120000 index 0000000000..0a8b824021 --- /dev/null +++ b/Lang/Red/Compare-length-of-two-strings @@ -0,0 +1 @@ +../../Task/Compare-length-of-two-strings/Red \ No newline at end of file diff --git a/Lang/Red/Compiler-AST-interpreter b/Lang/Red/Compiler-AST-interpreter new file mode 120000 index 0000000000..38de1297c9 --- /dev/null +++ b/Lang/Red/Compiler-AST-interpreter @@ -0,0 +1 @@ +../../Task/Compiler-AST-interpreter/Red \ No newline at end of file diff --git a/Lang/Red/Compiler-code-generator b/Lang/Red/Compiler-code-generator new file mode 120000 index 0000000000..7af219c35c --- /dev/null +++ b/Lang/Red/Compiler-code-generator @@ -0,0 +1 @@ +../../Task/Compiler-code-generator/Red \ No newline at end of file diff --git a/Lang/Red/Compiler-lexical-analyzer b/Lang/Red/Compiler-lexical-analyzer new file mode 120000 index 0000000000..6b88c28f94 --- /dev/null +++ b/Lang/Red/Compiler-lexical-analyzer @@ -0,0 +1 @@ +../../Task/Compiler-lexical-analyzer/Red \ No newline at end of file diff --git a/Lang/Red/Compiler-syntax-analyzer b/Lang/Red/Compiler-syntax-analyzer new file mode 120000 index 0000000000..406b1710ff --- /dev/null +++ b/Lang/Red/Compiler-syntax-analyzer @@ -0,0 +1 @@ +../../Task/Compiler-syntax-analyzer/Red \ No newline at end of file diff --git a/Lang/Red/Compiler-virtual-machine-interpreter b/Lang/Red/Compiler-virtual-machine-interpreter new file mode 120000 index 0000000000..85d28b0fea --- /dev/null +++ b/Lang/Red/Compiler-virtual-machine-interpreter @@ -0,0 +1 @@ +../../Task/Compiler-virtual-machine-interpreter/Red \ No newline at end of file diff --git a/Lang/Red/Currying b/Lang/Red/Currying new file mode 120000 index 0000000000..a40d4bf838 --- /dev/null +++ b/Lang/Red/Currying @@ -0,0 +1 @@ +../../Task/Currying/Red \ No newline at end of file diff --git a/Lang/Red/Dot-product b/Lang/Red/Dot-product new file mode 120000 index 0000000000..7a0eb69ac3 --- /dev/null +++ b/Lang/Red/Dot-product @@ -0,0 +1 @@ +../../Task/Dot-product/Red \ No newline at end of file diff --git a/Lang/Red/Empty-directory b/Lang/Red/Empty-directory new file mode 120000 index 0000000000..171a4f4f65 --- /dev/null +++ b/Lang/Red/Empty-directory @@ -0,0 +1 @@ +../../Task/Empty-directory/Red \ No newline at end of file diff --git a/Lang/Red/Execute-Brain- b/Lang/Red/Execute-Brain- new file mode 120000 index 0000000000..603437fa06 --- /dev/null +++ b/Lang/Red/Execute-Brain- @@ -0,0 +1 @@ +../../Task/Execute-Brain-/Red \ No newline at end of file diff --git a/Lang/Red/Extend-your-language b/Lang/Red/Extend-your-language new file mode 120000 index 0000000000..af9a4e8c46 --- /dev/null +++ b/Lang/Red/Extend-your-language @@ -0,0 +1 @@ +../../Task/Extend-your-language/Red \ No newline at end of file diff --git a/Lang/Red/First-class-functions b/Lang/Red/First-class-functions new file mode 120000 index 0000000000..fbfe38fd28 --- /dev/null +++ b/Lang/Red/First-class-functions @@ -0,0 +1 @@ +../../Task/First-class-functions/Red \ No newline at end of file diff --git a/Lang/Red/Five-weekends b/Lang/Red/Five-weekends new file mode 120000 index 0000000000..4b364097a6 --- /dev/null +++ b/Lang/Red/Five-weekends @@ -0,0 +1 @@ +../../Task/Five-weekends/Red \ No newline at end of file diff --git a/Lang/Red/Function-composition b/Lang/Red/Function-composition new file mode 120000 index 0000000000..880a1c6e87 --- /dev/null +++ b/Lang/Red/Function-composition @@ -0,0 +1 @@ +../../Task/Function-composition/Red \ No newline at end of file diff --git a/Lang/Red/HTTP b/Lang/Red/HTTP new file mode 120000 index 0000000000..f7d36ebcff --- /dev/null +++ b/Lang/Red/HTTP @@ -0,0 +1 @@ +../../Task/HTTP/Red \ No newline at end of file diff --git a/Lang/Red/Leap-year b/Lang/Red/Leap-year new file mode 120000 index 0000000000..cb911ae827 --- /dev/null +++ b/Lang/Red/Leap-year @@ -0,0 +1 @@ +../../Task/Leap-year/Red \ No newline at end of file diff --git a/Lang/Red/Logical-operations b/Lang/Red/Logical-operations new file mode 120000 index 0000000000..b02eaed36f --- /dev/null +++ b/Lang/Red/Logical-operations @@ -0,0 +1 @@ +../../Task/Logical-operations/Red \ No newline at end of file diff --git a/Lang/Red/Metaprogramming b/Lang/Red/Metaprogramming new file mode 120000 index 0000000000..764ff52337 --- /dev/null +++ b/Lang/Red/Metaprogramming @@ -0,0 +1 @@ +../../Task/Metaprogramming/Red \ No newline at end of file diff --git a/Lang/Red/Parsing-RPN-calculator-algorithm b/Lang/Red/Parsing-RPN-calculator-algorithm new file mode 120000 index 0000000000..f68a7bf5c6 --- /dev/null +++ b/Lang/Red/Parsing-RPN-calculator-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-RPN-calculator-algorithm/Red \ No newline at end of file diff --git a/Lang/Red/Parsing-RPN-to-infix-conversion b/Lang/Red/Parsing-RPN-to-infix-conversion new file mode 120000 index 0000000000..27fb99e707 --- /dev/null +++ b/Lang/Red/Parsing-RPN-to-infix-conversion @@ -0,0 +1 @@ +../../Task/Parsing-RPN-to-infix-conversion/Red \ No newline at end of file diff --git a/Lang/Red/Parsing-Shunting-yard-algorithm b/Lang/Red/Parsing-Shunting-yard-algorithm new file mode 120000 index 0000000000..64583c9508 --- /dev/null +++ b/Lang/Red/Parsing-Shunting-yard-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-Shunting-yard-algorithm/Red \ No newline at end of file diff --git a/Lang/Red/Partial-function-application b/Lang/Red/Partial-function-application new file mode 120000 index 0000000000..dbffa4d18e --- /dev/null +++ b/Lang/Red/Partial-function-application @@ -0,0 +1 @@ +../../Task/Partial-function-application/Red \ No newline at end of file diff --git a/Lang/Red/Quaternion-type b/Lang/Red/Quaternion-type deleted file mode 120000 index 7b5fc87ddd..0000000000 --- a/Lang/Red/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Red \ No newline at end of file diff --git a/Lang/Red/Rosetta-Code-Find-unimplemented-tasks b/Lang/Red/Rosetta-Code-Find-unimplemented-tasks new file mode 120000 index 0000000000..53726178b5 --- /dev/null +++ b/Lang/Red/Rosetta-Code-Find-unimplemented-tasks @@ -0,0 +1 @@ +../../Task/Rosetta-Code-Find-unimplemented-tasks/Red \ No newline at end of file diff --git a/Lang/Red/Runtime-evaluation-In-an-environment b/Lang/Red/Runtime-evaluation-In-an-environment new file mode 120000 index 0000000000..ee82b72bbd --- /dev/null +++ b/Lang/Red/Runtime-evaluation-In-an-environment @@ -0,0 +1 @@ +../../Task/Runtime-evaluation-In-an-environment/Red \ No newline at end of file diff --git a/Lang/Red/Towers-of-Hanoi b/Lang/Red/Towers-of-Hanoi new file mode 120000 index 0000000000..112b276dee --- /dev/null +++ b/Lang/Red/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Red \ No newline at end of file diff --git a/Lang/Red/Vector-products b/Lang/Red/Vector-products new file mode 120000 index 0000000000..28d3b45939 --- /dev/null +++ b/Lang/Red/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/Red \ No newline at end of file diff --git a/Lang/Red/Word-frequency b/Lang/Red/Word-frequency new file mode 120000 index 0000000000..535322fbdc --- /dev/null +++ b/Lang/Red/Word-frequency @@ -0,0 +1 @@ +../../Task/Word-frequency/Red \ No newline at end of file diff --git a/Lang/Refal/Align-columns b/Lang/Refal/Align-columns new file mode 120000 index 0000000000..8c214d7af1 --- /dev/null +++ b/Lang/Refal/Align-columns @@ -0,0 +1 @@ +../../Task/Align-columns/Refal \ No newline at end of file diff --git a/Lang/Refal/Arbitrary-precision-integers-included- b/Lang/Refal/Arbitrary-precision-integers-included- new file mode 120000 index 0000000000..f00d324a4e --- /dev/null +++ b/Lang/Refal/Arbitrary-precision-integers-included- @@ -0,0 +1 @@ +../../Task/Arbitrary-precision-integers-included-/Refal \ No newline at end of file diff --git a/Lang/Refal/Arithmetic-derivative b/Lang/Refal/Arithmetic-derivative new file mode 120000 index 0000000000..c88f60d44d --- /dev/null +++ b/Lang/Refal/Arithmetic-derivative @@ -0,0 +1 @@ +../../Task/Arithmetic-derivative/Refal \ No newline at end of file diff --git a/Lang/Refal/Bell-numbers b/Lang/Refal/Bell-numbers new file mode 120000 index 0000000000..a73ced2740 --- /dev/null +++ b/Lang/Refal/Bell-numbers @@ -0,0 +1 @@ +../../Task/Bell-numbers/Refal \ No newline at end of file diff --git a/Lang/Refal/Case-sensitivity-of-identifiers b/Lang/Refal/Case-sensitivity-of-identifiers new file mode 120000 index 0000000000..7def95d498 --- /dev/null +++ b/Lang/Refal/Case-sensitivity-of-identifiers @@ -0,0 +1 @@ +../../Task/Case-sensitivity-of-identifiers/Refal \ No newline at end of file diff --git a/Lang/Refal/Combinations b/Lang/Refal/Combinations new file mode 120000 index 0000000000..d4a5475872 --- /dev/null +++ b/Lang/Refal/Combinations @@ -0,0 +1 @@ +../../Task/Combinations/Refal \ No newline at end of file diff --git a/Lang/Refal/Copy-stdin-to-stdout b/Lang/Refal/Copy-stdin-to-stdout new file mode 120000 index 0000000000..974e13964c --- /dev/null +++ b/Lang/Refal/Copy-stdin-to-stdout @@ -0,0 +1 @@ +../../Task/Copy-stdin-to-stdout/Refal \ No newline at end of file diff --git a/Lang/Refal/Damm-algorithm b/Lang/Refal/Damm-algorithm new file mode 120000 index 0000000000..9b99056b8a --- /dev/null +++ b/Lang/Refal/Damm-algorithm @@ -0,0 +1 @@ +../../Task/Damm-algorithm/Refal \ No newline at end of file diff --git a/Lang/Refal/Determine-sentence-type b/Lang/Refal/Determine-sentence-type new file mode 120000 index 0000000000..13809ebd86 --- /dev/null +++ b/Lang/Refal/Determine-sentence-type @@ -0,0 +1 @@ +../../Task/Determine-sentence-type/Refal \ No newline at end of file diff --git a/Lang/Refal/Disarium-numbers b/Lang/Refal/Disarium-numbers new file mode 120000 index 0000000000..7389ead892 --- /dev/null +++ b/Lang/Refal/Disarium-numbers @@ -0,0 +1 @@ +../../Task/Disarium-numbers/Refal \ No newline at end of file diff --git a/Lang/Refal/Discordian-date b/Lang/Refal/Discordian-date new file mode 120000 index 0000000000..e18bd824ca --- /dev/null +++ b/Lang/Refal/Discordian-date @@ -0,0 +1 @@ +../../Task/Discordian-date/Refal \ No newline at end of file diff --git a/Lang/Refal/Display-a-linear-combination b/Lang/Refal/Display-a-linear-combination new file mode 120000 index 0000000000..fc164db566 --- /dev/null +++ b/Lang/Refal/Display-a-linear-combination @@ -0,0 +1 @@ +../../Task/Display-a-linear-combination/Refal \ No newline at end of file diff --git a/Lang/Refal/Doomsday-rule b/Lang/Refal/Doomsday-rule new file mode 120000 index 0000000000..87fb488eaa --- /dev/null +++ b/Lang/Refal/Doomsday-rule @@ -0,0 +1 @@ +../../Task/Doomsday-rule/Refal \ No newline at end of file diff --git a/Lang/Refal/Duffinian-numbers b/Lang/Refal/Duffinian-numbers new file mode 120000 index 0000000000..7aec5bb21b --- /dev/null +++ b/Lang/Refal/Duffinian-numbers @@ -0,0 +1 @@ +../../Task/Duffinian-numbers/Refal \ No newline at end of file diff --git a/Lang/Refal/Factors-of-an-integer b/Lang/Refal/Factors-of-an-integer new file mode 120000 index 0000000000..b8b431c369 --- /dev/null +++ b/Lang/Refal/Factors-of-an-integer @@ -0,0 +1 @@ +../../Task/Factors-of-an-integer/Refal \ No newline at end of file diff --git a/Lang/Refal/Flatten-a-list b/Lang/Refal/Flatten-a-list new file mode 120000 index 0000000000..b2445ac726 --- /dev/null +++ b/Lang/Refal/Flatten-a-list @@ -0,0 +1 @@ +../../Task/Flatten-a-list/Refal \ No newline at end of file diff --git a/Lang/Refal/Fractran b/Lang/Refal/Fractran new file mode 120000 index 0000000000..30b9e7a511 --- /dev/null +++ b/Lang/Refal/Fractran @@ -0,0 +1 @@ +../../Task/Fractran/Refal \ No newline at end of file diff --git a/Lang/Refal/General-FizzBuzz b/Lang/Refal/General-FizzBuzz new file mode 120000 index 0000000000..019727fd06 --- /dev/null +++ b/Lang/Refal/General-FizzBuzz @@ -0,0 +1 @@ +../../Task/General-FizzBuzz/Refal \ No newline at end of file diff --git a/Lang/Refal/Horners-rule-for-polynomial-evaluation b/Lang/Refal/Horners-rule-for-polynomial-evaluation new file mode 120000 index 0000000000..29b0a0f26a --- /dev/null +++ b/Lang/Refal/Horners-rule-for-polynomial-evaluation @@ -0,0 +1 @@ +../../Task/Horners-rule-for-polynomial-evaluation/Refal \ No newline at end of file diff --git a/Lang/Refal/Isqrt-integer-square-root-of-X b/Lang/Refal/Isqrt-integer-square-root-of-X new file mode 120000 index 0000000000..812b5e86d3 --- /dev/null +++ b/Lang/Refal/Isqrt-integer-square-root-of-X @@ -0,0 +1 @@ +../../Task/Isqrt-integer-square-root-of-X/Refal \ No newline at end of file diff --git a/Lang/Refal/Lah-numbers b/Lang/Refal/Lah-numbers new file mode 120000 index 0000000000..a761f59719 --- /dev/null +++ b/Lang/Refal/Lah-numbers @@ -0,0 +1 @@ +../../Task/Lah-numbers/Refal \ No newline at end of file diff --git a/Lang/Refal/Letter-frequency b/Lang/Refal/Letter-frequency new file mode 120000 index 0000000000..e9c48e99dd --- /dev/null +++ b/Lang/Refal/Letter-frequency @@ -0,0 +1 @@ +../../Task/Letter-frequency/Refal \ No newline at end of file diff --git a/Lang/Refal/Loops-Infinite b/Lang/Refal/Loops-Infinite new file mode 120000 index 0000000000..536c01c9bd --- /dev/null +++ b/Lang/Refal/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/Refal \ No newline at end of file diff --git a/Lang/Refal/McNuggets-problem b/Lang/Refal/McNuggets-problem new file mode 120000 index 0000000000..90628a4989 --- /dev/null +++ b/Lang/Refal/McNuggets-problem @@ -0,0 +1 @@ +../../Task/McNuggets-problem/Refal \ No newline at end of file diff --git a/Lang/Refal/Modular-exponentiation b/Lang/Refal/Modular-exponentiation new file mode 120000 index 0000000000..68c13863de --- /dev/null +++ b/Lang/Refal/Modular-exponentiation @@ -0,0 +1 @@ +../../Task/Modular-exponentiation/Refal \ No newline at end of file diff --git a/Lang/Refal/Move-to-front-algorithm b/Lang/Refal/Move-to-front-algorithm new file mode 120000 index 0000000000..e69e4f5498 --- /dev/null +++ b/Lang/Refal/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/Refal \ No newline at end of file diff --git a/Lang/Refal/Narcissistic-decimal-number b/Lang/Refal/Narcissistic-decimal-number new file mode 120000 index 0000000000..3c509c9753 --- /dev/null +++ b/Lang/Refal/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/Refal \ No newline at end of file diff --git a/Lang/Refal/Nested-templated-data b/Lang/Refal/Nested-templated-data new file mode 120000 index 0000000000..ceaf039a10 --- /dev/null +++ b/Lang/Refal/Nested-templated-data @@ -0,0 +1 @@ +../../Task/Nested-templated-data/Refal \ No newline at end of file diff --git a/Lang/Refal/Old-lady-swallowed-a-fly b/Lang/Refal/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..63d7ebf658 --- /dev/null +++ b/Lang/Refal/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/Refal \ No newline at end of file diff --git a/Lang/Refal/One-dimensional-cellular-automata b/Lang/Refal/One-dimensional-cellular-automata new file mode 120000 index 0000000000..89b9ba280e --- /dev/null +++ b/Lang/Refal/One-dimensional-cellular-automata @@ -0,0 +1 @@ +../../Task/One-dimensional-cellular-automata/Refal \ No newline at end of file diff --git a/Lang/Refal/Ordered-words b/Lang/Refal/Ordered-words new file mode 120000 index 0000000000..b546984c01 --- /dev/null +++ b/Lang/Refal/Ordered-words @@ -0,0 +1 @@ +../../Task/Ordered-words/Refal \ No newline at end of file diff --git a/Lang/Refal/Palindrome-detection b/Lang/Refal/Palindrome-detection new file mode 120000 index 0000000000..87f1ace89c --- /dev/null +++ b/Lang/Refal/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/Refal \ No newline at end of file diff --git a/Lang/Refal/Population-count b/Lang/Refal/Population-count new file mode 120000 index 0000000000..3cdd939b69 --- /dev/null +++ b/Lang/Refal/Population-count @@ -0,0 +1 @@ +../../Task/Population-count/Refal \ No newline at end of file diff --git a/Lang/Refal/Power-set b/Lang/Refal/Power-set new file mode 120000 index 0000000000..f50da086ad --- /dev/null +++ b/Lang/Refal/Power-set @@ -0,0 +1 @@ +../../Task/Power-set/Refal \ No newline at end of file diff --git a/Lang/Refal/Repeat b/Lang/Refal/Repeat new file mode 120000 index 0000000000..1cdb36e096 --- /dev/null +++ b/Lang/Refal/Repeat @@ -0,0 +1 @@ +../../Task/Repeat/Refal \ No newline at end of file diff --git a/Lang/Refal/Roman-numerals-Encode b/Lang/Refal/Roman-numerals-Encode new file mode 120000 index 0000000000..a35e7a2ee0 --- /dev/null +++ b/Lang/Refal/Roman-numerals-Encode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Encode/Refal \ No newline at end of file diff --git a/Lang/Refal/Run-length-encoding b/Lang/Refal/Run-length-encoding new file mode 120000 index 0000000000..afeb7091c3 --- /dev/null +++ b/Lang/Refal/Run-length-encoding @@ -0,0 +1 @@ +../../Task/Run-length-encoding/Refal \ No newline at end of file diff --git a/Lang/Refal/Sierpinski-triangle b/Lang/Refal/Sierpinski-triangle new file mode 120000 index 0000000000..078d645de8 --- /dev/null +++ b/Lang/Refal/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/Refal \ No newline at end of file diff --git a/Lang/Refal/Split-a-character-string-based-on-change-of-character b/Lang/Refal/Split-a-character-string-based-on-change-of-character new file mode 120000 index 0000000000..8a3aec8866 --- /dev/null +++ b/Lang/Refal/Split-a-character-string-based-on-change-of-character @@ -0,0 +1 @@ +../../Task/Split-a-character-string-based-on-change-of-character/Refal \ No newline at end of file diff --git a/Lang/Refal/Square-but-not-cube b/Lang/Refal/Square-but-not-cube new file mode 120000 index 0000000000..a50417a708 --- /dev/null +++ b/Lang/Refal/Square-but-not-cube @@ -0,0 +1 @@ +../../Task/Square-but-not-cube/Refal \ No newline at end of file diff --git a/Lang/Refal/Strip-comments-from-a-string b/Lang/Refal/Strip-comments-from-a-string new file mode 120000 index 0000000000..6f86213c31 --- /dev/null +++ b/Lang/Refal/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/Refal \ No newline at end of file diff --git a/Lang/Refal/Super-d-numbers b/Lang/Refal/Super-d-numbers new file mode 120000 index 0000000000..923b4678f8 --- /dev/null +++ b/Lang/Refal/Super-d-numbers @@ -0,0 +1 @@ +../../Task/Super-d-numbers/Refal \ No newline at end of file diff --git a/Lang/Refal/Tokenize-a-string b/Lang/Refal/Tokenize-a-string new file mode 120000 index 0000000000..f8ac7459de --- /dev/null +++ b/Lang/Refal/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Refal \ No newline at end of file diff --git a/Lang/Refal/Word-ladder b/Lang/Refal/Word-ladder new file mode 120000 index 0000000000..b43f6deb31 --- /dev/null +++ b/Lang/Refal/Word-ladder @@ -0,0 +1 @@ +../../Task/Word-ladder/Refal \ No newline at end of file diff --git a/Lang/Refal/Zeckendorf-number-representation b/Lang/Refal/Zeckendorf-number-representation new file mode 120000 index 0000000000..70b5a3265e --- /dev/null +++ b/Lang/Refal/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/Refal \ No newline at end of file diff --git a/Lang/Retro/Sieve-of-Eratosthenes b/Lang/Retro/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..d5617b7054 --- /dev/null +++ b/Lang/Retro/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Retro \ No newline at end of file diff --git a/Lang/Retro/String-append b/Lang/Retro/String-append new file mode 120000 index 0000000000..db032f3f0a --- /dev/null +++ b/Lang/Retro/String-append @@ -0,0 +1 @@ +../../Task/String-append/Retro \ No newline at end of file diff --git a/Lang/Retro/Sum-multiples-of-3-and-5 b/Lang/Retro/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..cb0c42540d --- /dev/null +++ b/Lang/Retro/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Retro \ No newline at end of file diff --git a/Lang/Rhombus/00-LANG.txt b/Lang/Rhombus/00-LANG.txt new file mode 100644 index 0000000000..ef9932595f --- /dev/null +++ b/Lang/Rhombus/00-LANG.txt @@ -0,0 +1,5 @@ +{{language +|exec=both +|gc=yes +|site=https://rhombus-lang.org/ +}} \ No newline at end of file diff --git a/Lang/Rhombus/00-META.yaml b/Lang/Rhombus/00-META.yaml new file mode 100644 index 0000000000..732b96d2eb --- /dev/null +++ b/Lang/Rhombus/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Rhombus diff --git a/Lang/Rhombus/99-bottles-of-beer b/Lang/Rhombus/99-bottles-of-beer new file mode 120000 index 0000000000..bcb9ee7049 --- /dev/null +++ b/Lang/Rhombus/99-bottles-of-beer @@ -0,0 +1 @@ +../../Task/99-bottles-of-beer/Rhombus \ No newline at end of file diff --git a/Lang/Rhombus/Arbitrary-precision-integers-included- b/Lang/Rhombus/Arbitrary-precision-integers-included- new file mode 120000 index 0000000000..31558e19d7 --- /dev/null +++ b/Lang/Rhombus/Arbitrary-precision-integers-included- @@ -0,0 +1 @@ +../../Task/Arbitrary-precision-integers-included-/Rhombus \ No newline at end of file diff --git a/Lang/Rhombus/Caesar-cipher b/Lang/Rhombus/Caesar-cipher new file mode 120000 index 0000000000..dd9f5453ed --- /dev/null +++ b/Lang/Rhombus/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/Rhombus \ No newline at end of file diff --git a/Lang/Rhombus/Factorial b/Lang/Rhombus/Factorial new file mode 120000 index 0000000000..92b62c830f --- /dev/null +++ b/Lang/Rhombus/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Rhombus \ No newline at end of file diff --git a/Lang/Rhombus/Fibonacci-sequence b/Lang/Rhombus/Fibonacci-sequence new file mode 120000 index 0000000000..d496e8a0b2 --- /dev/null +++ b/Lang/Rhombus/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/Rhombus \ No newline at end of file diff --git a/Lang/Rhombus/FizzBuzz b/Lang/Rhombus/FizzBuzz new file mode 120000 index 0000000000..5740514b72 --- /dev/null +++ b/Lang/Rhombus/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Rhombus \ No newline at end of file diff --git a/Lang/Rhombus/Guess-the-number-With-feedback b/Lang/Rhombus/Guess-the-number-With-feedback new file mode 120000 index 0000000000..c51dd719ba --- /dev/null +++ b/Lang/Rhombus/Guess-the-number-With-feedback @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback/Rhombus \ No newline at end of file diff --git a/Lang/Rhombus/Hello-world-Text b/Lang/Rhombus/Hello-world-Text new file mode 120000 index 0000000000..11fb03859d --- /dev/null +++ b/Lang/Rhombus/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Rhombus \ No newline at end of file diff --git a/Lang/Rhombus/Inheritance-Single b/Lang/Rhombus/Inheritance-Single new file mode 120000 index 0000000000..2f478862d8 --- /dev/null +++ b/Lang/Rhombus/Inheritance-Single @@ -0,0 +1 @@ +../../Task/Inheritance-Single/Rhombus \ No newline at end of file diff --git a/Lang/Rhombus/Polymorphism b/Lang/Rhombus/Polymorphism new file mode 120000 index 0000000000..a5540935b5 --- /dev/null +++ b/Lang/Rhombus/Polymorphism @@ -0,0 +1 @@ +../../Task/Polymorphism/Rhombus \ No newline at end of file diff --git a/Lang/Rhombus/Rot-13 b/Lang/Rhombus/Rot-13 new file mode 120000 index 0000000000..369226ff2f --- /dev/null +++ b/Lang/Rhombus/Rot-13 @@ -0,0 +1 @@ +../../Task/Rot-13/Rhombus \ No newline at end of file diff --git a/Lang/Rhombus/Y-combinator b/Lang/Rhombus/Y-combinator new file mode 120000 index 0000000000..745c50d95d --- /dev/null +++ b/Lang/Rhombus/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Rhombus \ No newline at end of file diff --git a/Lang/Ring/Bioinformatics-base-count b/Lang/Ring/Bioinformatics-base-count deleted file mode 120000 index 291f269ac6..0000000000 --- a/Lang/Ring/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Ring \ No newline at end of file diff --git a/Lang/Ring/Brilliant-numbers b/Lang/Ring/Brilliant-numbers new file mode 120000 index 0000000000..4e2621cdb9 --- /dev/null +++ b/Lang/Ring/Brilliant-numbers @@ -0,0 +1 @@ +../../Task/Brilliant-numbers/Ring \ No newline at end of file diff --git a/Lang/Ring/Colorful-numbers b/Lang/Ring/Colorful-numbers new file mode 120000 index 0000000000..0882269c01 --- /dev/null +++ b/Lang/Ring/Colorful-numbers @@ -0,0 +1 @@ +../../Task/Colorful-numbers/Ring \ No newline at end of file diff --git a/Lang/Ring/Compare-a-list-of-strings b/Lang/Ring/Compare-a-list-of-strings new file mode 120000 index 0000000000..308f7db9af --- /dev/null +++ b/Lang/Ring/Compare-a-list-of-strings @@ -0,0 +1 @@ +../../Task/Compare-a-list-of-strings/Ring \ No newline at end of file diff --git a/Lang/Ring/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k b/Lang/Ring/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k new file mode 120000 index 0000000000..cd105cb2cf --- /dev/null +++ b/Lang/Ring/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/Ring \ No newline at end of file diff --git a/Lang/Ring/Draw-a-clock b/Lang/Ring/Draw-a-clock new file mode 120000 index 0000000000..d4e59a0d8d --- /dev/null +++ b/Lang/Ring/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/Ring \ No newline at end of file diff --git a/Lang/Ring/Duffinian-numbers b/Lang/Ring/Duffinian-numbers new file mode 120000 index 0000000000..297b9a5500 --- /dev/null +++ b/Lang/Ring/Duffinian-numbers @@ -0,0 +1 @@ +../../Task/Duffinian-numbers/Ring \ No newline at end of file diff --git a/Lang/Ring/Empty-program b/Lang/Ring/Empty-program deleted file mode 120000 index 05941ac0c2..0000000000 --- a/Lang/Ring/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Ring \ No newline at end of file diff --git a/Lang/Ring/Miller-Rabin-primality-test b/Lang/Ring/Miller-Rabin-primality-test deleted file mode 120000 index dd0885b5c9..0000000000 --- a/Lang/Ring/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Ring \ No newline at end of file diff --git a/Lang/Ring/Selectively-replace-multiple-instances-of-a-character-within-a-string b/Lang/Ring/Selectively-replace-multiple-instances-of-a-character-within-a-string new file mode 120000 index 0000000000..238083a2d3 --- /dev/null +++ b/Lang/Ring/Selectively-replace-multiple-instances-of-a-character-within-a-string @@ -0,0 +1 @@ +../../Task/Selectively-replace-multiple-instances-of-a-character-within-a-string/Ring \ No newline at end of file diff --git a/Lang/Ring/Sorting-Algorithms-Circle-Sort b/Lang/Ring/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index de0338125a..0000000000 --- a/Lang/Ring/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Ring \ No newline at end of file diff --git a/Lang/Ring/Sorting-algorithms-Bead-sort b/Lang/Ring/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..eea2153977 --- /dev/null +++ b/Lang/Ring/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/Ring \ No newline at end of file diff --git a/Lang/Ring/Special-characters b/Lang/Ring/Special-characters new file mode 120000 index 0000000000..0dd3c257c9 --- /dev/null +++ b/Lang/Ring/Special-characters @@ -0,0 +1 @@ +../../Task/Special-characters/Ring \ No newline at end of file diff --git a/Lang/Ring/Truth-table b/Lang/Ring/Truth-table new file mode 120000 index 0000000000..b2ddf39eb1 --- /dev/null +++ b/Lang/Ring/Truth-table @@ -0,0 +1 @@ +../../Task/Truth-table/Ring \ No newline at end of file diff --git a/Lang/Ring/Twelve-statements b/Lang/Ring/Twelve-statements new file mode 120000 index 0000000000..539ba91df6 --- /dev/null +++ b/Lang/Ring/Twelve-statements @@ -0,0 +1 @@ +../../Task/Twelve-statements/Ring \ No newline at end of file diff --git a/Lang/Ring/Universal-Turing-machine b/Lang/Ring/Universal-Turing-machine new file mode 120000 index 0000000000..1e0cfd8b67 --- /dev/null +++ b/Lang/Ring/Universal-Turing-machine @@ -0,0 +1 @@ +../../Task/Universal-Turing-machine/Ring \ No newline at end of file diff --git a/Lang/Ring/Wagstaff-primes b/Lang/Ring/Wagstaff-primes new file mode 120000 index 0000000000..877433f537 --- /dev/null +++ b/Lang/Ring/Wagstaff-primes @@ -0,0 +1 @@ +../../Task/Wagstaff-primes/Ring \ No newline at end of file diff --git a/Lang/Ring/Wieferich-primes b/Lang/Ring/Wieferich-primes new file mode 120000 index 0000000000..4a7c97a04d --- /dev/null +++ b/Lang/Ring/Wieferich-primes @@ -0,0 +1 @@ +../../Task/Wieferich-primes/Ring \ No newline at end of file diff --git a/Lang/Ring/Yin-and-yang b/Lang/Ring/Yin-and-yang new file mode 120000 index 0000000000..b4e272e04d --- /dev/null +++ b/Lang/Ring/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/Ring \ No newline at end of file diff --git a/Lang/Robotic/Empty-program b/Lang/Robotic/Empty-program deleted file mode 120000 index 5e2d95817a..0000000000 --- a/Lang/Robotic/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Robotic \ No newline at end of file diff --git a/Lang/Rockstar/00-LANG.txt b/Lang/Rockstar/00-LANG.txt index 9dc3cbc2f7..c22e2c3636 100644 --- a/Lang/Rockstar/00-LANG.txt +++ b/Lang/Rockstar/00-LANG.txt @@ -1,4 +1,8 @@ -{{stub}}{{language|Rockstar}} +{{stub}} +{{language|Rockstar +|site=https://codewithrockstar.com/ +|hopl=no +}} Rockstar was created by a rockin' dude named Dylan Beattie. diff --git a/Lang/Rocq/00-LANG.txt b/Lang/Rocq/00-LANG.txt new file mode 100644 index 0000000000..3a6e02cc5b --- /dev/null +++ b/Lang/Rocq/00-LANG.txt @@ -0,0 +1,9 @@ +{{language|Rocq +|site=https://rocq-prover.org/ +}} +The '''Rocq Prover''' (previously known as '''Coq''') is a proof assistant application. It allows the expression of mathematical assertions, mechanically checks proofs of these assertions, helps to find formal proofs, and extracts a certified program from the constructive proof of its formal specification. Rocq works within the theory of the calculus of inductive constructions, a derivative of the calculus of constructions. Rocq is not an automated [[wp:Theorem_prover|theorem prover]] but includes automatic theorem proving tactics and various decision procedures. + +==Citations== +* [[wp:Rocq|Rocq]] + +[[Category:Mathematical programming languages]] \ No newline at end of file diff --git a/Lang/Rocq/00-META.yaml b/Lang/Rocq/00-META.yaml new file mode 100644 index 0000000000..7a4ef3c3e3 --- /dev/null +++ b/Lang/Rocq/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Rocq diff --git a/Lang/Rocq/100-doors b/Lang/Rocq/100-doors new file mode 120000 index 0000000000..ddc9d15706 --- /dev/null +++ b/Lang/Rocq/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/Rocq \ No newline at end of file diff --git a/Lang/Rocq/Ackermann-function b/Lang/Rocq/Ackermann-function new file mode 120000 index 0000000000..2c359313d3 --- /dev/null +++ b/Lang/Rocq/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/Rocq \ No newline at end of file diff --git a/Lang/Rocq/Extend-your-language b/Lang/Rocq/Extend-your-language new file mode 120000 index 0000000000..7a189585f3 --- /dev/null +++ b/Lang/Rocq/Extend-your-language @@ -0,0 +1 @@ +../../Task/Extend-your-language/Rocq \ No newline at end of file diff --git a/Lang/Rocq/Factorial b/Lang/Rocq/Factorial new file mode 120000 index 0000000000..73a7e2f546 --- /dev/null +++ b/Lang/Rocq/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Rocq \ No newline at end of file diff --git a/Lang/Rocq/Fibonacci-sequence b/Lang/Rocq/Fibonacci-sequence new file mode 120000 index 0000000000..a31a4762d2 --- /dev/null +++ b/Lang/Rocq/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/Rocq \ No newline at end of file diff --git a/Lang/Rocq/FizzBuzz b/Lang/Rocq/FizzBuzz new file mode 120000 index 0000000000..3dc20e67b5 --- /dev/null +++ b/Lang/Rocq/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Rocq \ No newline at end of file diff --git a/Lang/Rocq/Hello-world-Newbie b/Lang/Rocq/Hello-world-Newbie new file mode 120000 index 0000000000..f8f6323716 --- /dev/null +++ b/Lang/Rocq/Hello-world-Newbie @@ -0,0 +1 @@ +../../Task/Hello-world-Newbie/Rocq \ No newline at end of file diff --git a/Lang/Rocq/Hello-world-Text b/Lang/Rocq/Hello-world-Text new file mode 120000 index 0000000000..3d91fcb1de --- /dev/null +++ b/Lang/Rocq/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Rocq \ No newline at end of file diff --git a/Lang/Rocq/Loops-For b/Lang/Rocq/Loops-For new file mode 120000 index 0000000000..ea834fd5b7 --- /dev/null +++ b/Lang/Rocq/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/Rocq \ No newline at end of file diff --git a/Lang/Rocq/Tree-traversal b/Lang/Rocq/Tree-traversal new file mode 120000 index 0000000000..944802a525 --- /dev/null +++ b/Lang/Rocq/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/Rocq \ No newline at end of file diff --git a/Lang/Rocq/Variadic-function b/Lang/Rocq/Variadic-function new file mode 120000 index 0000000000..0c5215f0a1 --- /dev/null +++ b/Lang/Rocq/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Rocq \ No newline at end of file diff --git a/Lang/Ruby/Bioinformatics-base-count b/Lang/Ruby/Bioinformatics-base-count deleted file mode 120000 index af92d7709c..0000000000 --- a/Lang/Ruby/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Miller-Rabin-primality-test b/Lang/Ruby/Miller-Rabin-primality-test deleted file mode 120000 index d7cbf43733..0000000000 --- a/Lang/Ruby/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Quaternion-type b/Lang/Ruby/Quaternion-type deleted file mode 120000 index c1af2a1904..0000000000 --- a/Lang/Ruby/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Sorting-Algorithms-Circle-Sort b/Lang/Ruby/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 022b44ef66..0000000000 --- a/Lang/Ruby/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Strassens-algorithm b/Lang/Ruby/Strassens-algorithm new file mode 120000 index 0000000000..ecb75a8f11 --- /dev/null +++ b/Lang/Ruby/Strassens-algorithm @@ -0,0 +1 @@ +../../Task/Strassens-algorithm/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Variable-declaration-reset b/Lang/Ruby/Variable-declaration-reset new file mode 120000 index 0000000000..42ba082e34 --- /dev/null +++ b/Lang/Ruby/Variable-declaration-reset @@ -0,0 +1 @@ +../../Task/Variable-declaration-reset/Ruby \ No newline at end of file diff --git a/Lang/Run-BASIC/Determine-sentence-type b/Lang/Run-BASIC/Determine-sentence-type new file mode 120000 index 0000000000..5db5f89e0c --- /dev/null +++ b/Lang/Run-BASIC/Determine-sentence-type @@ -0,0 +1 @@ +../../Task/Determine-sentence-type/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Josephus-problem b/Lang/Run-BASIC/Josephus-problem new file mode 120000 index 0000000000..d5ce7e543e --- /dev/null +++ b/Lang/Run-BASIC/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Meissel-Mertens-constant b/Lang/Run-BASIC/Meissel-Mertens-constant deleted file mode 120000 index 44168b020e..0000000000 --- a/Lang/Run-BASIC/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Miller-Rabin-primality-test b/Lang/Run-BASIC/Miller-Rabin-primality-test deleted file mode 120000 index 13b7319b57..0000000000 --- a/Lang/Run-BASIC/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Nested-templated-data b/Lang/Run-BASIC/Nested-templated-data new file mode 120000 index 0000000000..e2c607e939 --- /dev/null +++ b/Lang/Run-BASIC/Nested-templated-data @@ -0,0 +1 @@ +../../Task/Nested-templated-data/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Numbers-with-equal-rises-and-falls b/Lang/Run-BASIC/Numbers-with-equal-rises-and-falls new file mode 120000 index 0000000000..b0e664881e --- /dev/null +++ b/Lang/Run-BASIC/Numbers-with-equal-rises-and-falls @@ -0,0 +1 @@ +../../Task/Numbers-with-equal-rises-and-falls/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Pancake-numbers b/Lang/Run-BASIC/Pancake-numbers new file mode 120000 index 0000000000..8078e50109 --- /dev/null +++ b/Lang/Run-BASIC/Pancake-numbers @@ -0,0 +1 @@ +../../Task/Pancake-numbers/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Phrase-reversals b/Lang/Run-BASIC/Phrase-reversals new file mode 120000 index 0000000000..db249e8a6e --- /dev/null +++ b/Lang/Run-BASIC/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Split-a-character-string-based-on-change-of-character b/Lang/Run-BASIC/Split-a-character-string-based-on-change-of-character new file mode 120000 index 0000000000..afd1d6a928 --- /dev/null +++ b/Lang/Run-BASIC/Split-a-character-string-based-on-change-of-character @@ -0,0 +1 @@ +../../Task/Split-a-character-string-based-on-change-of-character/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/The-Name-Game b/Lang/Run-BASIC/The-Name-Game new file mode 120000 index 0000000000..a0ca866e4a --- /dev/null +++ b/Lang/Run-BASIC/The-Name-Game @@ -0,0 +1 @@ +../../Task/The-Name-Game/Run-BASIC \ No newline at end of file diff --git a/Lang/Rust/Almkvist-Giullera-formula-for-pi b/Lang/Rust/Almkvist-Giullera-formula-for-pi new file mode 120000 index 0000000000..495c52095c --- /dev/null +++ b/Lang/Rust/Almkvist-Giullera-formula-for-pi @@ -0,0 +1 @@ +../../Task/Almkvist-Giullera-formula-for-pi/Rust \ No newline at end of file diff --git a/Lang/Rust/Ascending-primes b/Lang/Rust/Ascending-primes new file mode 120000 index 0000000000..84fdafe351 --- /dev/null +++ b/Lang/Rust/Ascending-primes @@ -0,0 +1 @@ +../../Task/Ascending-primes/Rust \ No newline at end of file diff --git a/Lang/Rust/B-zier-curves-Intersections b/Lang/Rust/B-zier-curves-Intersections new file mode 120000 index 0000000000..732ede6e4e --- /dev/null +++ b/Lang/Rust/B-zier-curves-Intersections @@ -0,0 +1 @@ +../../Task/B-zier-curves-Intersections/Rust \ No newline at end of file diff --git a/Lang/Rust/Bifid-cipher b/Lang/Rust/Bifid-cipher new file mode 120000 index 0000000000..8ddce2026b --- /dev/null +++ b/Lang/Rust/Bifid-cipher @@ -0,0 +1 @@ +../../Task/Bifid-cipher/Rust \ No newline at end of file diff --git a/Lang/Rust/Bioinformatics-Global-alignment b/Lang/Rust/Bioinformatics-Global-alignment new file mode 120000 index 0000000000..3bbbc3b358 --- /dev/null +++ b/Lang/Rust/Bioinformatics-Global-alignment @@ -0,0 +1 @@ +../../Task/Bioinformatics-Global-alignment/Rust \ No newline at end of file diff --git a/Lang/Rust/Bioinformatics-base-count b/Lang/Rust/Bioinformatics-base-count deleted file mode 120000 index 412ded1361..0000000000 --- a/Lang/Rust/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Rust \ No newline at end of file diff --git a/Lang/Rust/Biorhythms b/Lang/Rust/Biorhythms new file mode 120000 index 0000000000..8d5ffa21d8 --- /dev/null +++ b/Lang/Rust/Biorhythms @@ -0,0 +1 @@ +../../Task/Biorhythms/Rust \ No newline at end of file diff --git a/Lang/Rust/Blum-integer b/Lang/Rust/Blum-integer new file mode 120000 index 0000000000..7a0e8a69ae --- /dev/null +++ b/Lang/Rust/Blum-integer @@ -0,0 +1 @@ +../../Task/Blum-integer/Rust \ No newline at end of file diff --git a/Lang/Rust/Boyer-Moore-string-search b/Lang/Rust/Boyer-Moore-string-search new file mode 120000 index 0000000000..b70383335b --- /dev/null +++ b/Lang/Rust/Boyer-Moore-string-search @@ -0,0 +1 @@ +../../Task/Boyer-Moore-string-search/Rust \ No newline at end of file diff --git a/Lang/Rust/Break-OO-privacy b/Lang/Rust/Break-OO-privacy new file mode 120000 index 0000000000..37b6e0d417 --- /dev/null +++ b/Lang/Rust/Break-OO-privacy @@ -0,0 +1 @@ +../../Task/Break-OO-privacy/Rust \ No newline at end of file diff --git a/Lang/Rust/Calendar---for-REAL-programmers b/Lang/Rust/Calendar---for-REAL-programmers new file mode 120000 index 0000000000..5bd1cebf14 --- /dev/null +++ b/Lang/Rust/Calendar---for-REAL-programmers @@ -0,0 +1 @@ +../../Task/Calendar---for-REAL-programmers/Rust \ No newline at end of file diff --git a/Lang/Rust/Camel-case-and-snake-case b/Lang/Rust/Camel-case-and-snake-case new file mode 120000 index 0000000000..5c92d90b28 --- /dev/null +++ b/Lang/Rust/Camel-case-and-snake-case @@ -0,0 +1 @@ +../../Task/Camel-case-and-snake-case/Rust \ No newline at end of file diff --git a/Lang/Rust/Color-quantization b/Lang/Rust/Color-quantization new file mode 120000 index 0000000000..76c5471c0f --- /dev/null +++ b/Lang/Rust/Color-quantization @@ -0,0 +1 @@ +../../Task/Color-quantization/Rust \ No newline at end of file diff --git a/Lang/Rust/Commatizing-numbers b/Lang/Rust/Commatizing-numbers new file mode 120000 index 0000000000..5df0e95315 --- /dev/null +++ b/Lang/Rust/Commatizing-numbers @@ -0,0 +1 @@ +../../Task/Commatizing-numbers/Rust \ No newline at end of file diff --git a/Lang/Rust/Compare-sorting-algorithms-performance b/Lang/Rust/Compare-sorting-algorithms-performance new file mode 120000 index 0000000000..7676ca3dd8 --- /dev/null +++ b/Lang/Rust/Compare-sorting-algorithms-performance @@ -0,0 +1 @@ +../../Task/Compare-sorting-algorithms-performance/Rust \ No newline at end of file diff --git a/Lang/Rust/Compiler-AST-interpreter b/Lang/Rust/Compiler-AST-interpreter new file mode 120000 index 0000000000..2028e35209 --- /dev/null +++ b/Lang/Rust/Compiler-AST-interpreter @@ -0,0 +1 @@ +../../Task/Compiler-AST-interpreter/Rust \ No newline at end of file diff --git a/Lang/Rust/Compiler-code-generator b/Lang/Rust/Compiler-code-generator new file mode 120000 index 0000000000..fa460708f3 --- /dev/null +++ b/Lang/Rust/Compiler-code-generator @@ -0,0 +1 @@ +../../Task/Compiler-code-generator/Rust \ No newline at end of file diff --git a/Lang/Rust/Compiler-lexical-analyzer b/Lang/Rust/Compiler-lexical-analyzer new file mode 120000 index 0000000000..b603fdc69a --- /dev/null +++ b/Lang/Rust/Compiler-lexical-analyzer @@ -0,0 +1 @@ +../../Task/Compiler-lexical-analyzer/Rust \ No newline at end of file diff --git a/Lang/Rust/Compiler-syntax-analyzer b/Lang/Rust/Compiler-syntax-analyzer new file mode 120000 index 0000000000..4fa6fc40a8 --- /dev/null +++ b/Lang/Rust/Compiler-syntax-analyzer @@ -0,0 +1 @@ +../../Task/Compiler-syntax-analyzer/Rust \ No newline at end of file diff --git a/Lang/Rust/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- b/Lang/Rust/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- new file mode 120000 index 0000000000..7e0955d429 --- /dev/null +++ b/Lang/Rust/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n-/Rust \ No newline at end of file diff --git a/Lang/Rust/Cyclops-numbers b/Lang/Rust/Cyclops-numbers new file mode 120000 index 0000000000..044bb62e43 --- /dev/null +++ b/Lang/Rust/Cyclops-numbers @@ -0,0 +1 @@ +../../Task/Cyclops-numbers/Rust \ No newline at end of file diff --git a/Lang/Rust/Cyclotomic-polynomial b/Lang/Rust/Cyclotomic-polynomial new file mode 120000 index 0000000000..8ff16fabbb --- /dev/null +++ b/Lang/Rust/Cyclotomic-polynomial @@ -0,0 +1 @@ +../../Task/Cyclotomic-polynomial/Rust \ No newline at end of file diff --git a/Lang/Rust/De-Bruijn-sequences b/Lang/Rust/De-Bruijn-sequences new file mode 120000 index 0000000000..69c62c6871 --- /dev/null +++ b/Lang/Rust/De-Bruijn-sequences @@ -0,0 +1 @@ +../../Task/De-Bruijn-sequences/Rust \ No newline at end of file diff --git a/Lang/Rust/Deconvolution-1D b/Lang/Rust/Deconvolution-1D new file mode 120000 index 0000000000..d02a914ea3 --- /dev/null +++ b/Lang/Rust/Deconvolution-1D @@ -0,0 +1 @@ +../../Task/Deconvolution-1D/Rust \ No newline at end of file diff --git a/Lang/Rust/Deconvolution-2D+ b/Lang/Rust/Deconvolution-2D+ new file mode 120000 index 0000000000..4b9cb470ba --- /dev/null +++ b/Lang/Rust/Deconvolution-2D+ @@ -0,0 +1 @@ +../../Task/Deconvolution-2D+/Rust \ No newline at end of file diff --git a/Lang/Rust/Demings-funnel b/Lang/Rust/Demings-funnel new file mode 120000 index 0000000000..295d5542ba --- /dev/null +++ b/Lang/Rust/Demings-funnel @@ -0,0 +1 @@ +../../Task/Demings-funnel/Rust \ No newline at end of file diff --git a/Lang/Rust/Descending-primes b/Lang/Rust/Descending-primes new file mode 120000 index 0000000000..fc953fbf4e --- /dev/null +++ b/Lang/Rust/Descending-primes @@ -0,0 +1 @@ +../../Task/Descending-primes/Rust \ No newline at end of file diff --git a/Lang/Rust/Determine-if-two-triangles-overlap b/Lang/Rust/Determine-if-two-triangles-overlap new file mode 120000 index 0000000000..2bc1e5e063 --- /dev/null +++ b/Lang/Rust/Determine-if-two-triangles-overlap @@ -0,0 +1 @@ +../../Task/Determine-if-two-triangles-overlap/Rust \ No newline at end of file diff --git a/Lang/Rust/Determine-sentence-type b/Lang/Rust/Determine-sentence-type new file mode 120000 index 0000000000..caee594e4d --- /dev/null +++ b/Lang/Rust/Determine-sentence-type @@ -0,0 +1 @@ +../../Task/Determine-sentence-type/Rust \ No newline at end of file diff --git a/Lang/Rust/Doubly-linked-list-Definition b/Lang/Rust/Doubly-linked-list-Definition new file mode 120000 index 0000000000..9eb9054258 --- /dev/null +++ b/Lang/Rust/Doubly-linked-list-Definition @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Definition/Rust \ No newline at end of file diff --git a/Lang/Rust/Doubly-linked-list-Traversal b/Lang/Rust/Doubly-linked-list-Traversal new file mode 120000 index 0000000000..b44bd60c3c --- /dev/null +++ b/Lang/Rust/Doubly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Traversal/Rust \ No newline at end of file diff --git a/Lang/Rust/Duffinian-numbers b/Lang/Rust/Duffinian-numbers new file mode 120000 index 0000000000..5a84e9b8ff --- /dev/null +++ b/Lang/Rust/Duffinian-numbers @@ -0,0 +1 @@ +../../Task/Duffinian-numbers/Rust \ No newline at end of file diff --git a/Lang/Rust/Eban-numbers b/Lang/Rust/Eban-numbers new file mode 120000 index 0000000000..cf564cdce5 --- /dev/null +++ b/Lang/Rust/Eban-numbers @@ -0,0 +1 @@ +../../Task/Eban-numbers/Rust \ No newline at end of file diff --git a/Lang/Rust/Elliptic-Curve-Digital-Signature-Algorithm b/Lang/Rust/Elliptic-Curve-Digital-Signature-Algorithm new file mode 120000 index 0000000000..f6d4ecb90e --- /dev/null +++ b/Lang/Rust/Elliptic-Curve-Digital-Signature-Algorithm @@ -0,0 +1 @@ +../../Task/Elliptic-Curve-Digital-Signature-Algorithm/Rust \ No newline at end of file diff --git a/Lang/Rust/Elliptic-curve-arithmetic b/Lang/Rust/Elliptic-curve-arithmetic new file mode 120000 index 0000000000..cb1c49b6dd --- /dev/null +++ b/Lang/Rust/Elliptic-curve-arithmetic @@ -0,0 +1 @@ +../../Task/Elliptic-curve-arithmetic/Rust \ No newline at end of file diff --git a/Lang/Rust/Faulhabers-formula b/Lang/Rust/Faulhabers-formula new file mode 120000 index 0000000000..f7691b3566 --- /dev/null +++ b/Lang/Rust/Faulhabers-formula @@ -0,0 +1 @@ +../../Task/Faulhabers-formula/Rust \ No newline at end of file diff --git a/Lang/Rust/Faulhabers-triangle b/Lang/Rust/Faulhabers-triangle new file mode 120000 index 0000000000..49b5537877 --- /dev/null +++ b/Lang/Rust/Faulhabers-triangle @@ -0,0 +1 @@ +../../Task/Faulhabers-triangle/Rust \ No newline at end of file diff --git a/Lang/Rust/Find-largest-left-truncatable-prime-in-a-given-base b/Lang/Rust/Find-largest-left-truncatable-prime-in-a-given-base new file mode 120000 index 0000000000..e7da5ced0b --- /dev/null +++ b/Lang/Rust/Find-largest-left-truncatable-prime-in-a-given-base @@ -0,0 +1 @@ +../../Task/Find-largest-left-truncatable-prime-in-a-given-base/Rust \ No newline at end of file diff --git a/Lang/Rust/Fractran b/Lang/Rust/Fractran new file mode 120000 index 0000000000..46ed1ab96e --- /dev/null +++ b/Lang/Rust/Fractran @@ -0,0 +1 @@ +../../Task/Fractran/Rust \ No newline at end of file diff --git a/Lang/Rust/French-Republican-calendar b/Lang/Rust/French-Republican-calendar new file mode 120000 index 0000000000..60dfe0f429 --- /dev/null +++ b/Lang/Rust/French-Republican-calendar @@ -0,0 +1 @@ +../../Task/French-Republican-calendar/Rust \ No newline at end of file diff --git a/Lang/Rust/Functional-coverage-tree b/Lang/Rust/Functional-coverage-tree new file mode 120000 index 0000000000..fab149755e --- /dev/null +++ b/Lang/Rust/Functional-coverage-tree @@ -0,0 +1 @@ +../../Task/Functional-coverage-tree/Rust \ No newline at end of file diff --git a/Lang/Rust/Graph-colouring b/Lang/Rust/Graph-colouring new file mode 120000 index 0000000000..acb44a12b7 --- /dev/null +++ b/Lang/Rust/Graph-colouring @@ -0,0 +1 @@ +../../Task/Graph-colouring/Rust \ No newline at end of file diff --git a/Lang/Rust/Hex-words b/Lang/Rust/Hex-words new file mode 120000 index 0000000000..9322882ab9 --- /dev/null +++ b/Lang/Rust/Hex-words @@ -0,0 +1 @@ +../../Task/Hex-words/Rust \ No newline at end of file diff --git a/Lang/Rust/Humble-numbers b/Lang/Rust/Humble-numbers new file mode 120000 index 0000000000..001b631312 --- /dev/null +++ b/Lang/Rust/Humble-numbers @@ -0,0 +1 @@ +../../Task/Humble-numbers/Rust \ No newline at end of file diff --git a/Lang/Rust/Knapsack-problem-Bounded b/Lang/Rust/Knapsack-problem-Bounded new file mode 120000 index 0000000000..db57c7551f --- /dev/null +++ b/Lang/Rust/Knapsack-problem-Bounded @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Bounded/Rust \ No newline at end of file diff --git a/Lang/Rust/Kosaraju b/Lang/Rust/Kosaraju new file mode 120000 index 0000000000..69a0c5ef3e --- /dev/null +++ b/Lang/Rust/Kosaraju @@ -0,0 +1 @@ +../../Task/Kosaraju/Rust \ No newline at end of file diff --git a/Lang/Rust/Latin-Squares-in-reduced-form b/Lang/Rust/Latin-Squares-in-reduced-form new file mode 120000 index 0000000000..17d284a00f --- /dev/null +++ b/Lang/Rust/Latin-Squares-in-reduced-form @@ -0,0 +1 @@ +../../Task/Latin-Squares-in-reduced-form/Rust \ No newline at end of file diff --git a/Lang/Rust/List-rooted-trees b/Lang/Rust/List-rooted-trees new file mode 120000 index 0000000000..ef07119312 --- /dev/null +++ b/Lang/Rust/List-rooted-trees @@ -0,0 +1 @@ +../../Task/List-rooted-trees/Rust \ No newline at end of file diff --git a/Lang/Rust/Long-literals-with-continuations b/Lang/Rust/Long-literals-with-continuations new file mode 120000 index 0000000000..ad69d0820b --- /dev/null +++ b/Lang/Rust/Long-literals-with-continuations @@ -0,0 +1 @@ +../../Task/Long-literals-with-continuations/Rust \ No newline at end of file diff --git a/Lang/Rust/Mayan-calendar b/Lang/Rust/Mayan-calendar new file mode 120000 index 0000000000..8da8002279 --- /dev/null +++ b/Lang/Rust/Mayan-calendar @@ -0,0 +1 @@ +../../Task/Mayan-calendar/Rust \ No newline at end of file diff --git a/Lang/Rust/Median-filter b/Lang/Rust/Median-filter new file mode 120000 index 0000000000..1cdae0e790 --- /dev/null +++ b/Lang/Rust/Median-filter @@ -0,0 +1 @@ +../../Task/Median-filter/Rust \ No newline at end of file diff --git a/Lang/Rust/Miller-Rabin-primality-test b/Lang/Rust/Miller-Rabin-primality-test deleted file mode 120000 index 937aebe94f..0000000000 --- a/Lang/Rust/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Rust \ No newline at end of file diff --git a/Lang/Rust/Modular-arithmetic b/Lang/Rust/Modular-arithmetic new file mode 120000 index 0000000000..bf3b8fce76 --- /dev/null +++ b/Lang/Rust/Modular-arithmetic @@ -0,0 +1 @@ +../../Task/Modular-arithmetic/Rust \ No newline at end of file diff --git a/Lang/Rust/Multiple-regression b/Lang/Rust/Multiple-regression new file mode 120000 index 0000000000..84425ee458 --- /dev/null +++ b/Lang/Rust/Multiple-regression @@ -0,0 +1 @@ +../../Task/Multiple-regression/Rust \ No newline at end of file diff --git a/Lang/Rust/Natural-sorting b/Lang/Rust/Natural-sorting new file mode 120000 index 0000000000..77b1a7de05 --- /dev/null +++ b/Lang/Rust/Natural-sorting @@ -0,0 +1 @@ +../../Task/Natural-sorting/Rust \ No newline at end of file diff --git a/Lang/Rust/Non-continuous-subsequences b/Lang/Rust/Non-continuous-subsequences new file mode 120000 index 0000000000..7152418d6c --- /dev/null +++ b/Lang/Rust/Non-continuous-subsequences @@ -0,0 +1 @@ +../../Task/Non-continuous-subsequences/Rust \ No newline at end of file diff --git a/Lang/Rust/Nonogram-solver b/Lang/Rust/Nonogram-solver new file mode 120000 index 0000000000..670a3f0f6a --- /dev/null +++ b/Lang/Rust/Nonogram-solver @@ -0,0 +1 @@ +../../Task/Nonogram-solver/Rust \ No newline at end of file diff --git a/Lang/Rust/Numerical-and-alphabetical-suffixes b/Lang/Rust/Numerical-and-alphabetical-suffixes new file mode 120000 index 0000000000..0446d710e5 --- /dev/null +++ b/Lang/Rust/Numerical-and-alphabetical-suffixes @@ -0,0 +1 @@ +../../Task/Numerical-and-alphabetical-suffixes/Rust \ No newline at end of file diff --git a/Lang/Rust/OpenWebNet-password b/Lang/Rust/OpenWebNet-password new file mode 120000 index 0000000000..24be1f8b4a --- /dev/null +++ b/Lang/Rust/OpenWebNet-password @@ -0,0 +1 @@ +../../Task/OpenWebNet-password/Rust \ No newline at end of file diff --git a/Lang/Rust/P-Adic-numbers-basic b/Lang/Rust/P-Adic-numbers-basic new file mode 120000 index 0000000000..2ccd34b2fd --- /dev/null +++ b/Lang/Rust/P-Adic-numbers-basic @@ -0,0 +1 @@ +../../Task/P-Adic-numbers-basic/Rust \ No newline at end of file diff --git a/Lang/Rust/P-Adic-square-roots b/Lang/Rust/P-Adic-square-roots new file mode 120000 index 0000000000..ed4fb995e0 --- /dev/null +++ b/Lang/Rust/P-Adic-square-roots @@ -0,0 +1 @@ +../../Task/P-Adic-square-roots/Rust \ No newline at end of file diff --git a/Lang/Rust/Permutations-Derangements b/Lang/Rust/Permutations-Derangements new file mode 120000 index 0000000000..9efa9a4159 --- /dev/null +++ b/Lang/Rust/Permutations-Derangements @@ -0,0 +1 @@ +../../Task/Permutations-Derangements/Rust \ No newline at end of file diff --git a/Lang/Rust/Playfair-cipher b/Lang/Rust/Playfair-cipher new file mode 120000 index 0000000000..f3e93df373 --- /dev/null +++ b/Lang/Rust/Playfair-cipher @@ -0,0 +1 @@ +../../Task/Playfair-cipher/Rust \ No newline at end of file diff --git a/Lang/Rust/Polynomial-regression b/Lang/Rust/Polynomial-regression new file mode 120000 index 0000000000..cdb9cdc8ff --- /dev/null +++ b/Lang/Rust/Polynomial-regression @@ -0,0 +1 @@ +../../Task/Polynomial-regression/Rust \ No newline at end of file diff --git a/Lang/Rust/Pseudo-random-numbers-Combined-recursive-generator-MRG32k3a b/Lang/Rust/Pseudo-random-numbers-Combined-recursive-generator-MRG32k3a new file mode 120000 index 0000000000..a557952f5e --- /dev/null +++ b/Lang/Rust/Pseudo-random-numbers-Combined-recursive-generator-MRG32k3a @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-Combined-recursive-generator-MRG32k3a/Rust \ No newline at end of file diff --git a/Lang/Rust/Pseudo-random-numbers-Middle-square-method b/Lang/Rust/Pseudo-random-numbers-Middle-square-method new file mode 120000 index 0000000000..07d7dfdf71 --- /dev/null +++ b/Lang/Rust/Pseudo-random-numbers-Middle-square-method @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-Middle-square-method/Rust \ No newline at end of file diff --git a/Lang/Rust/Pseudo-random-numbers-Splitmix64 b/Lang/Rust/Pseudo-random-numbers-Splitmix64 new file mode 120000 index 0000000000..af868efefa --- /dev/null +++ b/Lang/Rust/Pseudo-random-numbers-Splitmix64 @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-Splitmix64/Rust \ No newline at end of file diff --git a/Lang/Rust/QR-decomposition b/Lang/Rust/QR-decomposition new file mode 120000 index 0000000000..b6ec08cee6 --- /dev/null +++ b/Lang/Rust/QR-decomposition @@ -0,0 +1 @@ +../../Task/QR-decomposition/Rust \ No newline at end of file diff --git a/Lang/Rust/Quaternion-type b/Lang/Rust/Quaternion-type deleted file mode 120000 index 92c25b946f..0000000000 --- a/Lang/Rust/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Rust \ No newline at end of file diff --git a/Lang/Rust/Ramanujan-primes-twins b/Lang/Rust/Ramanujan-primes-twins new file mode 120000 index 0000000000..ec360cedbc --- /dev/null +++ b/Lang/Rust/Ramanujan-primes-twins @@ -0,0 +1 @@ +../../Task/Ramanujan-primes-twins/Rust \ No newline at end of file diff --git a/Lang/Rust/Rendezvous b/Lang/Rust/Rendezvous new file mode 120000 index 0000000000..2ae4407138 --- /dev/null +++ b/Lang/Rust/Rendezvous @@ -0,0 +1 @@ +../../Task/Rendezvous/Rust \ No newline at end of file diff --git a/Lang/Rust/Resistor-mesh b/Lang/Rust/Resistor-mesh new file mode 120000 index 0000000000..245eca7f06 --- /dev/null +++ b/Lang/Rust/Resistor-mesh @@ -0,0 +1 @@ +../../Task/Resistor-mesh/Rust \ No newline at end of file diff --git a/Lang/Rust/Shoelace-formula-for-polygonal-area b/Lang/Rust/Shoelace-formula-for-polygonal-area new file mode 120000 index 0000000000..4ce5ca075a --- /dev/null +++ b/Lang/Rust/Shoelace-formula-for-polygonal-area @@ -0,0 +1 @@ +../../Task/Shoelace-formula-for-polygonal-area/Rust \ No newline at end of file diff --git a/Lang/Rust/Singleton b/Lang/Rust/Singleton new file mode 120000 index 0000000000..480988c162 --- /dev/null +++ b/Lang/Rust/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/Rust \ No newline at end of file diff --git a/Lang/Rust/Sokoban b/Lang/Rust/Sokoban new file mode 120000 index 0000000000..57d1bc73b3 --- /dev/null +++ b/Lang/Rust/Sokoban @@ -0,0 +1 @@ +../../Task/Sokoban/Rust \ No newline at end of file diff --git a/Lang/Rust/Solve-a-Holy-Knights-tour b/Lang/Rust/Solve-a-Holy-Knights-tour new file mode 120000 index 0000000000..7d376bff89 --- /dev/null +++ b/Lang/Rust/Solve-a-Holy-Knights-tour @@ -0,0 +1 @@ +../../Task/Solve-a-Holy-Knights-tour/Rust \ No newline at end of file diff --git a/Lang/Rust/Solve-a-Hopido-puzzle b/Lang/Rust/Solve-a-Hopido-puzzle new file mode 120000 index 0000000000..13eae5b688 --- /dev/null +++ b/Lang/Rust/Solve-a-Hopido-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hopido-puzzle/Rust \ No newline at end of file diff --git a/Lang/Rust/Solve-a-Numbrix-puzzle b/Lang/Rust/Solve-a-Numbrix-puzzle new file mode 120000 index 0000000000..6da0fac9a0 --- /dev/null +++ b/Lang/Rust/Solve-a-Numbrix-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Numbrix-puzzle/Rust \ No newline at end of file diff --git a/Lang/Rust/Sorting-Algorithms-Circle-Sort b/Lang/Rust/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 924c0eb5ac..0000000000 --- a/Lang/Rust/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Rust \ No newline at end of file diff --git a/Lang/Rust/Sorting-algorithms-Bead-sort b/Lang/Rust/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..1096740d47 --- /dev/null +++ b/Lang/Rust/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/Rust \ No newline at end of file diff --git a/Lang/Rust/Sorting-algorithms-Patience-sort b/Lang/Rust/Sorting-algorithms-Patience-sort new file mode 120000 index 0000000000..98bfba78ce --- /dev/null +++ b/Lang/Rust/Sorting-algorithms-Patience-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Patience-sort/Rust \ No newline at end of file diff --git a/Lang/Rust/Sorting-algorithms-Permutation-sort b/Lang/Rust/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..0bbf7e172b --- /dev/null +++ b/Lang/Rust/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/Rust \ No newline at end of file diff --git a/Lang/Rust/Sorting-algorithms-Strand-sort b/Lang/Rust/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..c01a273a80 --- /dev/null +++ b/Lang/Rust/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/Rust \ No newline at end of file diff --git a/Lang/Rust/Special-characters b/Lang/Rust/Special-characters new file mode 120000 index 0000000000..7cb915367e --- /dev/null +++ b/Lang/Rust/Special-characters @@ -0,0 +1 @@ +../../Task/Special-characters/Rust \ No newline at end of file diff --git a/Lang/Rust/Stable-marriage-problem b/Lang/Rust/Stable-marriage-problem new file mode 120000 index 0000000000..98e509ab20 --- /dev/null +++ b/Lang/Rust/Stable-marriage-problem @@ -0,0 +1 @@ +../../Task/Stable-marriage-problem/Rust \ No newline at end of file diff --git a/Lang/Rust/State-name-puzzle b/Lang/Rust/State-name-puzzle new file mode 120000 index 0000000000..a88b598d4b --- /dev/null +++ b/Lang/Rust/State-name-puzzle @@ -0,0 +1 @@ +../../Task/State-name-puzzle/Rust \ No newline at end of file diff --git a/Lang/Rust/Steffensens-method b/Lang/Rust/Steffensens-method new file mode 120000 index 0000000000..4aa426ad52 --- /dev/null +++ b/Lang/Rust/Steffensens-method @@ -0,0 +1 @@ +../../Task/Steffensens-method/Rust \ No newline at end of file diff --git a/Lang/Rust/Stem-and-leaf-plot b/Lang/Rust/Stem-and-leaf-plot new file mode 120000 index 0000000000..c5e2a0d27c --- /dev/null +++ b/Lang/Rust/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/Rust \ No newline at end of file diff --git a/Lang/Rust/Stern-Brocot-sequence b/Lang/Rust/Stern-Brocot-sequence new file mode 120000 index 0000000000..72080b645a --- /dev/null +++ b/Lang/Rust/Stern-Brocot-sequence @@ -0,0 +1 @@ +../../Task/Stern-Brocot-sequence/Rust \ No newline at end of file diff --git a/Lang/Rust/Strassens-algorithm b/Lang/Rust/Strassens-algorithm new file mode 120000 index 0000000000..059089e819 --- /dev/null +++ b/Lang/Rust/Strassens-algorithm @@ -0,0 +1 @@ +../../Task/Strassens-algorithm/Rust \ No newline at end of file diff --git a/Lang/Rust/Stream-merge b/Lang/Rust/Stream-merge new file mode 120000 index 0000000000..101f42c85a --- /dev/null +++ b/Lang/Rust/Stream-merge @@ -0,0 +1 @@ +../../Task/Stream-merge/Rust \ No newline at end of file diff --git a/Lang/Rust/Strip-block-comments b/Lang/Rust/Strip-block-comments new file mode 120000 index 0000000000..c9f77902d0 --- /dev/null +++ b/Lang/Rust/Strip-block-comments @@ -0,0 +1 @@ +../../Task/Strip-block-comments/Rust \ No newline at end of file diff --git a/Lang/Rust/Strip-control-codes-and-extended-characters-from-a-string b/Lang/Rust/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..56a1876479 --- /dev/null +++ b/Lang/Rust/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/Rust \ No newline at end of file diff --git a/Lang/Rust/Subleq b/Lang/Rust/Subleq new file mode 120000 index 0000000000..cc28544f34 --- /dev/null +++ b/Lang/Rust/Subleq @@ -0,0 +1 @@ +../../Task/Subleq/Rust \ No newline at end of file diff --git a/Lang/Rust/Substitution-cipher b/Lang/Rust/Substitution-cipher new file mode 120000 index 0000000000..aa3ad1011d --- /dev/null +++ b/Lang/Rust/Substitution-cipher @@ -0,0 +1 @@ +../../Task/Substitution-cipher/Rust \ No newline at end of file diff --git a/Lang/Rust/Sudan-function b/Lang/Rust/Sudan-function new file mode 120000 index 0000000000..29cdeee99f --- /dev/null +++ b/Lang/Rust/Sudan-function @@ -0,0 +1 @@ +../../Task/Sudan-function/Rust \ No newline at end of file diff --git a/Lang/Rust/Suffixation-of-decimal-numbers b/Lang/Rust/Suffixation-of-decimal-numbers new file mode 120000 index 0000000000..2428a135a4 --- /dev/null +++ b/Lang/Rust/Suffixation-of-decimal-numbers @@ -0,0 +1 @@ +../../Task/Suffixation-of-decimal-numbers/Rust \ No newline at end of file diff --git a/Lang/Rust/Summarize-and-say-sequence b/Lang/Rust/Summarize-and-say-sequence new file mode 120000 index 0000000000..030276987c --- /dev/null +++ b/Lang/Rust/Summarize-and-say-sequence @@ -0,0 +1 @@ +../../Task/Summarize-and-say-sequence/Rust \ No newline at end of file diff --git a/Lang/Rust/Superpermutation-minimisation b/Lang/Rust/Superpermutation-minimisation new file mode 120000 index 0000000000..8b214e27cd --- /dev/null +++ b/Lang/Rust/Superpermutation-minimisation @@ -0,0 +1 @@ +../../Task/Superpermutation-minimisation/Rust \ No newline at end of file diff --git a/Lang/Rust/The-Name-Game b/Lang/Rust/The-Name-Game new file mode 120000 index 0000000000..92835f00de --- /dev/null +++ b/Lang/Rust/The-Name-Game @@ -0,0 +1 @@ +../../Task/The-Name-Game/Rust \ No newline at end of file diff --git a/Lang/Rust/Tonelli-Shanks-algorithm b/Lang/Rust/Tonelli-Shanks-algorithm new file mode 120000 index 0000000000..b90bd71718 --- /dev/null +++ b/Lang/Rust/Tonelli-Shanks-algorithm @@ -0,0 +1 @@ +../../Task/Tonelli-Shanks-algorithm/Rust \ No newline at end of file diff --git a/Lang/Rust/Tree-datastructures b/Lang/Rust/Tree-datastructures new file mode 120000 index 0000000000..37b567712c --- /dev/null +++ b/Lang/Rust/Tree-datastructures @@ -0,0 +1 @@ +../../Task/Tree-datastructures/Rust \ No newline at end of file diff --git a/Lang/Rust/Tropical-algebra-overloading b/Lang/Rust/Tropical-algebra-overloading new file mode 120000 index 0000000000..271296f0b3 --- /dev/null +++ b/Lang/Rust/Tropical-algebra-overloading @@ -0,0 +1 @@ +../../Task/Tropical-algebra-overloading/Rust \ No newline at end of file diff --git a/Lang/Rust/Twos-complement b/Lang/Rust/Twos-complement new file mode 120000 index 0000000000..086c8719d1 --- /dev/null +++ b/Lang/Rust/Twos-complement @@ -0,0 +1 @@ +../../Task/Twos-complement/Rust \ No newline at end of file diff --git a/Lang/Rust/UPC b/Lang/Rust/UPC new file mode 120000 index 0000000000..775faf96be --- /dev/null +++ b/Lang/Rust/UPC @@ -0,0 +1 @@ +../../Task/UPC/Rust \ No newline at end of file diff --git a/Lang/Rust/Ukkonen-s-suffix-tree-construction b/Lang/Rust/Ukkonen-s-suffix-tree-construction new file mode 120000 index 0000000000..684e412fed --- /dev/null +++ b/Lang/Rust/Ukkonen-s-suffix-tree-construction @@ -0,0 +1 @@ +../../Task/Ukkonen-s-suffix-tree-construction/Rust \ No newline at end of file diff --git a/Lang/Rust/Verhoeff-algorithm b/Lang/Rust/Verhoeff-algorithm new file mode 120000 index 0000000000..fd5322e5ec --- /dev/null +++ b/Lang/Rust/Verhoeff-algorithm @@ -0,0 +1 @@ +../../Task/Verhoeff-algorithm/Rust \ No newline at end of file diff --git a/Lang/Rust/Vogels-approximation-method b/Lang/Rust/Vogels-approximation-method new file mode 120000 index 0000000000..377b0aef0a --- /dev/null +++ b/Lang/Rust/Vogels-approximation-method @@ -0,0 +1 @@ +../../Task/Vogels-approximation-method/Rust \ No newline at end of file diff --git a/Lang/Rust/War-card-game b/Lang/Rust/War-card-game new file mode 120000 index 0000000000..bc45c42250 --- /dev/null +++ b/Lang/Rust/War-card-game @@ -0,0 +1 @@ +../../Task/War-card-game/Rust \ No newline at end of file diff --git a/Lang/Rust/Word-ladder b/Lang/Rust/Word-ladder new file mode 120000 index 0000000000..9973e5c323 --- /dev/null +++ b/Lang/Rust/Word-ladder @@ -0,0 +1 @@ +../../Task/Word-ladder/Rust \ No newline at end of file diff --git a/Lang/Rust/Word-search b/Lang/Rust/Word-search new file mode 120000 index 0000000000..737b35c0c7 --- /dev/null +++ b/Lang/Rust/Word-search @@ -0,0 +1 @@ +../../Task/Word-search/Rust \ No newline at end of file diff --git a/Lang/Rust/Word-wheel b/Lang/Rust/Word-wheel new file mode 120000 index 0000000000..3c8a9835e5 --- /dev/null +++ b/Lang/Rust/Word-wheel @@ -0,0 +1 @@ +../../Task/Word-wheel/Rust \ No newline at end of file diff --git a/Lang/Rust/Wordiff b/Lang/Rust/Wordiff new file mode 120000 index 0000000000..44e42a760a --- /dev/null +++ b/Lang/Rust/Wordiff @@ -0,0 +1 @@ +../../Task/Wordiff/Rust \ No newline at end of file diff --git a/Lang/Rust/Xiaolin-Wus-line-algorithm b/Lang/Rust/Xiaolin-Wus-line-algorithm new file mode 120000 index 0000000000..68352a1cb5 --- /dev/null +++ b/Lang/Rust/Xiaolin-Wus-line-algorithm @@ -0,0 +1 @@ +../../Task/Xiaolin-Wus-line-algorithm/Rust \ No newline at end of file diff --git a/Lang/Rust/Zebra-puzzle b/Lang/Rust/Zebra-puzzle new file mode 120000 index 0000000000..2b9c2729f7 --- /dev/null +++ b/Lang/Rust/Zebra-puzzle @@ -0,0 +1 @@ +../../Task/Zebra-puzzle/Rust \ No newline at end of file diff --git a/Lang/Rye/00-LANG.txt b/Lang/Rye/00-LANG.txt new file mode 100644 index 0000000000..10b016e264 --- /dev/null +++ b/Lang/Rye/00-LANG.txt @@ -0,0 +1,11 @@ +{{stub}}{{language|rye}} +Rye is a flexible, high-level programming language designed for predictable state management. Rye takes ideas from Rebol, and adds few from Factor, Linux shell, and Go. Written in Go, Rye doubles as a scripting companion for Go programs. Go's libraries integrate seamlessly, and Rye can be embedded as a scripting or config language for Go programs. + +As a high-level language, Rye explores bridging coding and user interfaces. Its interactive console features syntax highlighting, history, tab completion, and tools to explore the language and environment you’re crafting. + +==Todo== +[https://rosettacode.org/wiki/Tasks_not_implemented_in_Rye Tasks not implemented in Rye] + +==Links== +*[https://ryelang.org/ Homepage] +*[https://github.com/refaktor/rye Github repository] \ No newline at end of file diff --git a/Lang/Rye/00-META.yaml b/Lang/Rye/00-META.yaml new file mode 100644 index 0000000000..c4fbe956c0 --- /dev/null +++ b/Lang/Rye/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Rye diff --git a/Lang/Rye/100-doors b/Lang/Rye/100-doors new file mode 120000 index 0000000000..438aa2dd57 --- /dev/null +++ b/Lang/Rye/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/Rye \ No newline at end of file diff --git a/Lang/Rye/99-bottles-of-beer b/Lang/Rye/99-bottles-of-beer new file mode 120000 index 0000000000..bd33c6e283 --- /dev/null +++ b/Lang/Rye/99-bottles-of-beer @@ -0,0 +1 @@ +../../Task/99-bottles-of-beer/Rye \ No newline at end of file diff --git a/Lang/Rye/A+B b/Lang/Rye/A+B new file mode 120000 index 0000000000..cd82f2f9d7 --- /dev/null +++ b/Lang/Rye/A+B @@ -0,0 +1 @@ +../../Task/A+B/Rye \ No newline at end of file diff --git a/Lang/Rye/Arithmetic-Integer b/Lang/Rye/Arithmetic-Integer new file mode 120000 index 0000000000..3854f98ef8 --- /dev/null +++ b/Lang/Rye/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Rye \ No newline at end of file diff --git a/Lang/Rye/Array-concatenation b/Lang/Rye/Array-concatenation new file mode 120000 index 0000000000..e06de8357b --- /dev/null +++ b/Lang/Rye/Array-concatenation @@ -0,0 +1 @@ +../../Task/Array-concatenation/Rye \ No newline at end of file diff --git a/Lang/Rye/Array-length b/Lang/Rye/Array-length new file mode 120000 index 0000000000..f3ddf845d5 --- /dev/null +++ b/Lang/Rye/Array-length @@ -0,0 +1 @@ +../../Task/Array-length/Rye \ No newline at end of file diff --git a/Lang/Rye/Arrays b/Lang/Rye/Arrays new file mode 120000 index 0000000000..0051f3551e --- /dev/null +++ b/Lang/Rye/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/Rye \ No newline at end of file diff --git a/Lang/Rye/Assertions b/Lang/Rye/Assertions new file mode 120000 index 0000000000..55dc6c4a1c --- /dev/null +++ b/Lang/Rye/Assertions @@ -0,0 +1 @@ +../../Task/Assertions/Rye \ No newline at end of file diff --git a/Lang/Rye/Associative-array-Creation b/Lang/Rye/Associative-array-Creation new file mode 120000 index 0000000000..6d8b394caa --- /dev/null +++ b/Lang/Rye/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/Rye \ No newline at end of file diff --git a/Lang/Rye/Catamorphism b/Lang/Rye/Catamorphism new file mode 120000 index 0000000000..1cc0f4cd16 --- /dev/null +++ b/Lang/Rye/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/Rye \ No newline at end of file diff --git a/Lang/Rye/Check-that-file-exists b/Lang/Rye/Check-that-file-exists new file mode 120000 index 0000000000..0f1689d415 --- /dev/null +++ b/Lang/Rye/Check-that-file-exists @@ -0,0 +1 @@ +../../Task/Check-that-file-exists/Rye \ No newline at end of file diff --git a/Lang/Rye/Collections b/Lang/Rye/Collections new file mode 120000 index 0000000000..8619dddf36 --- /dev/null +++ b/Lang/Rye/Collections @@ -0,0 +1 @@ +../../Task/Collections/Rye \ No newline at end of file diff --git a/Lang/Rye/Compare-length-of-two-strings b/Lang/Rye/Compare-length-of-two-strings new file mode 120000 index 0000000000..3ee03067fd --- /dev/null +++ b/Lang/Rye/Compare-length-of-two-strings @@ -0,0 +1 @@ +../../Task/Compare-length-of-two-strings/Rye \ No newline at end of file diff --git a/Lang/Rye/Copy-a-string b/Lang/Rye/Copy-a-string new file mode 120000 index 0000000000..5130e809be --- /dev/null +++ b/Lang/Rye/Copy-a-string @@ -0,0 +1 @@ +../../Task/Copy-a-string/Rye \ No newline at end of file diff --git a/Lang/Rye/Create-a-file b/Lang/Rye/Create-a-file new file mode 120000 index 0000000000..933dfda3ec --- /dev/null +++ b/Lang/Rye/Create-a-file @@ -0,0 +1 @@ +../../Task/Create-a-file/Rye \ No newline at end of file diff --git a/Lang/Rye/DNS-query b/Lang/Rye/DNS-query new file mode 120000 index 0000000000..25d8db99dd --- /dev/null +++ b/Lang/Rye/DNS-query @@ -0,0 +1 @@ +../../Task/DNS-query/Rye \ No newline at end of file diff --git a/Lang/Rye/Date-format b/Lang/Rye/Date-format new file mode 120000 index 0000000000..3a4d47e12d --- /dev/null +++ b/Lang/Rye/Date-format @@ -0,0 +1 @@ +../../Task/Date-format/Rye \ No newline at end of file diff --git a/Lang/Rye/Date-manipulation b/Lang/Rye/Date-manipulation new file mode 120000 index 0000000000..aae44dde34 --- /dev/null +++ b/Lang/Rye/Date-manipulation @@ -0,0 +1 @@ +../../Task/Date-manipulation/Rye \ No newline at end of file diff --git a/Lang/Rye/Day-of-the-week b/Lang/Rye/Day-of-the-week new file mode 120000 index 0000000000..39e63de9c9 --- /dev/null +++ b/Lang/Rye/Day-of-the-week @@ -0,0 +1 @@ +../../Task/Day-of-the-week/Rye \ No newline at end of file diff --git a/Lang/Rye/Delete-a-file b/Lang/Rye/Delete-a-file new file mode 120000 index 0000000000..9eea0e6587 --- /dev/null +++ b/Lang/Rye/Delete-a-file @@ -0,0 +1 @@ +../../Task/Delete-a-file/Rye \ No newline at end of file diff --git a/Lang/Rye/Detect-division-by-zero b/Lang/Rye/Detect-division-by-zero new file mode 120000 index 0000000000..f063a804c3 --- /dev/null +++ b/Lang/Rye/Detect-division-by-zero @@ -0,0 +1 @@ +../../Task/Detect-division-by-zero/Rye \ No newline at end of file diff --git a/Lang/Rye/Determine-if-a-string-is-numeric b/Lang/Rye/Determine-if-a-string-is-numeric new file mode 120000 index 0000000000..921464be9b --- /dev/null +++ b/Lang/Rye/Determine-if-a-string-is-numeric @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-numeric/Rye \ No newline at end of file diff --git a/Lang/Rye/Dot-product b/Lang/Rye/Dot-product new file mode 120000 index 0000000000..ae39c4baea --- /dev/null +++ b/Lang/Rye/Dot-product @@ -0,0 +1 @@ +../../Task/Dot-product/Rye \ No newline at end of file diff --git a/Lang/Rye/Empty-string b/Lang/Rye/Empty-string new file mode 120000 index 0000000000..f9e83f3c4d --- /dev/null +++ b/Lang/Rye/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/Rye \ No newline at end of file diff --git a/Lang/Rye/Environment-variables b/Lang/Rye/Environment-variables new file mode 120000 index 0000000000..61b0fc4a40 --- /dev/null +++ b/Lang/Rye/Environment-variables @@ -0,0 +1 @@ +../../Task/Environment-variables/Rye \ No newline at end of file diff --git a/Lang/Rye/Even-or-odd b/Lang/Rye/Even-or-odd new file mode 120000 index 0000000000..8e627fbc05 --- /dev/null +++ b/Lang/Rye/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/Rye \ No newline at end of file diff --git a/Lang/Rye/Exceptions b/Lang/Rye/Exceptions new file mode 120000 index 0000000000..98c5a1f0b9 --- /dev/null +++ b/Lang/Rye/Exceptions @@ -0,0 +1 @@ +../../Task/Exceptions/Rye \ No newline at end of file diff --git a/Lang/Rye/Execute-a-system-command b/Lang/Rye/Execute-a-system-command new file mode 120000 index 0000000000..6ef49fa4fa --- /dev/null +++ b/Lang/Rye/Execute-a-system-command @@ -0,0 +1 @@ +../../Task/Execute-a-system-command/Rye \ No newline at end of file diff --git a/Lang/Rye/File-input-output b/Lang/Rye/File-input-output new file mode 120000 index 0000000000..92a41d1ae9 --- /dev/null +++ b/Lang/Rye/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Rye \ No newline at end of file diff --git a/Lang/Rye/File-size b/Lang/Rye/File-size new file mode 120000 index 0000000000..434016471c --- /dev/null +++ b/Lang/Rye/File-size @@ -0,0 +1 @@ +../../Task/File-size/Rye \ No newline at end of file diff --git a/Lang/Rye/Filter b/Lang/Rye/Filter new file mode 120000 index 0000000000..be25d82950 --- /dev/null +++ b/Lang/Rye/Filter @@ -0,0 +1 @@ +../../Task/Filter/Rye \ No newline at end of file diff --git a/Lang/Rye/Function-definition b/Lang/Rye/Function-definition new file mode 120000 index 0000000000..aacf81b6b4 --- /dev/null +++ b/Lang/Rye/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/Rye \ No newline at end of file diff --git a/Lang/Rye/Get-system-command-output b/Lang/Rye/Get-system-command-output new file mode 120000 index 0000000000..0faad90e64 --- /dev/null +++ b/Lang/Rye/Get-system-command-output @@ -0,0 +1 @@ +../../Task/Get-system-command-output/Rye \ No newline at end of file diff --git a/Lang/Rye/Globally-replace-text-in-several-files b/Lang/Rye/Globally-replace-text-in-several-files new file mode 120000 index 0000000000..3bc1b5796d --- /dev/null +++ b/Lang/Rye/Globally-replace-text-in-several-files @@ -0,0 +1 @@ +../../Task/Globally-replace-text-in-several-files/Rye \ No newline at end of file diff --git a/Lang/Rye/Greatest-element-of-a-list b/Lang/Rye/Greatest-element-of-a-list new file mode 120000 index 0000000000..3f8290710b --- /dev/null +++ b/Lang/Rye/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/Rye \ No newline at end of file diff --git a/Lang/Rye/Guess-the-number b/Lang/Rye/Guess-the-number new file mode 120000 index 0000000000..3554ecb000 --- /dev/null +++ b/Lang/Rye/Guess-the-number @@ -0,0 +1 @@ +../../Task/Guess-the-number/Rye \ No newline at end of file diff --git a/Lang/Rye/Hello-world-Graphical b/Lang/Rye/Hello-world-Graphical new file mode 120000 index 0000000000..8ba960fd9f --- /dev/null +++ b/Lang/Rye/Hello-world-Graphical @@ -0,0 +1 @@ +../../Task/Hello-world-Graphical/Rye \ No newline at end of file diff --git a/Lang/Rye/Hello-world-Newbie b/Lang/Rye/Hello-world-Newbie new file mode 120000 index 0000000000..404d5bf799 --- /dev/null +++ b/Lang/Rye/Hello-world-Newbie @@ -0,0 +1 @@ +../../Task/Hello-world-Newbie/Rye \ No newline at end of file diff --git a/Lang/Rye/Hello-world-Newline-omission b/Lang/Rye/Hello-world-Newline-omission new file mode 120000 index 0000000000..8978311a91 --- /dev/null +++ b/Lang/Rye/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/Rye \ No newline at end of file diff --git a/Lang/Rye/Hello-world-Text b/Lang/Rye/Hello-world-Text new file mode 120000 index 0000000000..527e3f5d07 --- /dev/null +++ b/Lang/Rye/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Rye \ No newline at end of file diff --git a/Lang/Rye/Hello-world-Web-server b/Lang/Rye/Hello-world-Web-server new file mode 120000 index 0000000000..3eb3a08cd7 --- /dev/null +++ b/Lang/Rye/Hello-world-Web-server @@ -0,0 +1 @@ +../../Task/Hello-world-Web-server/Rye \ No newline at end of file diff --git a/Lang/Rye/Hostname b/Lang/Rye/Hostname new file mode 120000 index 0000000000..794d1a04af --- /dev/null +++ b/Lang/Rye/Hostname @@ -0,0 +1 @@ +../../Task/Hostname/Rye \ No newline at end of file diff --git a/Lang/Rye/Include-a-file b/Lang/Rye/Include-a-file new file mode 120000 index 0000000000..075626de41 --- /dev/null +++ b/Lang/Rye/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/Rye \ No newline at end of file diff --git a/Lang/Rye/Increment-a-numerical-string b/Lang/Rye/Increment-a-numerical-string new file mode 120000 index 0000000000..a92efbbcc7 --- /dev/null +++ b/Lang/Rye/Increment-a-numerical-string @@ -0,0 +1 @@ +../../Task/Increment-a-numerical-string/Rye \ No newline at end of file diff --git a/Lang/Rye/Integer-comparison b/Lang/Rye/Integer-comparison new file mode 120000 index 0000000000..b464263441 --- /dev/null +++ b/Lang/Rye/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/Rye \ No newline at end of file diff --git a/Lang/Rye/Jewels-and-stones b/Lang/Rye/Jewels-and-stones new file mode 120000 index 0000000000..2e39bc84a7 --- /dev/null +++ b/Lang/Rye/Jewels-and-stones @@ -0,0 +1 @@ +../../Task/Jewels-and-stones/Rye \ No newline at end of file diff --git a/Lang/Rye/Loops-Do-while b/Lang/Rye/Loops-Do-while new file mode 120000 index 0000000000..fb7d5e8d59 --- /dev/null +++ b/Lang/Rye/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/Rye \ No newline at end of file diff --git a/Lang/Rye/Loops-For b/Lang/Rye/Loops-For new file mode 120000 index 0000000000..3149a28871 --- /dev/null +++ b/Lang/Rye/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/Rye \ No newline at end of file diff --git a/Lang/Rye/Loops-Foreach b/Lang/Rye/Loops-Foreach new file mode 120000 index 0000000000..5feb6cdb06 --- /dev/null +++ b/Lang/Rye/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/Rye \ No newline at end of file diff --git a/Lang/Rye/Loops-Infinite b/Lang/Rye/Loops-Infinite new file mode 120000 index 0000000000..7267542117 --- /dev/null +++ b/Lang/Rye/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/Rye \ No newline at end of file diff --git a/Lang/Rye/Loops-While b/Lang/Rye/Loops-While new file mode 120000 index 0000000000..376326123c --- /dev/null +++ b/Lang/Rye/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/Rye \ No newline at end of file diff --git a/Lang/Rye/Nth b/Lang/Rye/Nth new file mode 120000 index 0000000000..5490f22f35 --- /dev/null +++ b/Lang/Rye/Nth @@ -0,0 +1 @@ +../../Task/Nth/Rye \ No newline at end of file diff --git a/Lang/Rye/Operator-precedence b/Lang/Rye/Operator-precedence new file mode 120000 index 0000000000..43eb0d7842 --- /dev/null +++ b/Lang/Rye/Operator-precedence @@ -0,0 +1 @@ +../../Task/Operator-precedence/Rye \ No newline at end of file diff --git a/Lang/Rye/Ordered-words b/Lang/Rye/Ordered-words new file mode 120000 index 0000000000..c1d477486c --- /dev/null +++ b/Lang/Rye/Ordered-words @@ -0,0 +1 @@ +../../Task/Ordered-words/Rye \ No newline at end of file diff --git a/Lang/Rye/Partial-function-application b/Lang/Rye/Partial-function-application new file mode 120000 index 0000000000..ae25414b27 --- /dev/null +++ b/Lang/Rye/Partial-function-application @@ -0,0 +1 @@ +../../Task/Partial-function-application/Rye \ No newline at end of file diff --git a/Lang/Rye/RPG-attributes-generator b/Lang/Rye/RPG-attributes-generator new file mode 120000 index 0000000000..fa9afbb45f --- /dev/null +++ b/Lang/Rye/RPG-attributes-generator @@ -0,0 +1 @@ +../../Task/RPG-attributes-generator/Rye \ No newline at end of file diff --git a/Lang/Rye/Read-entire-file b/Lang/Rye/Read-entire-file new file mode 120000 index 0000000000..345a900f2b --- /dev/null +++ b/Lang/Rye/Read-entire-file @@ -0,0 +1 @@ +../../Task/Read-entire-file/Rye \ No newline at end of file diff --git a/Lang/Rye/Remove-duplicate-elements b/Lang/Rye/Remove-duplicate-elements new file mode 120000 index 0000000000..c6a95084fa --- /dev/null +++ b/Lang/Rye/Remove-duplicate-elements @@ -0,0 +1 @@ +../../Task/Remove-duplicate-elements/Rye \ No newline at end of file diff --git a/Lang/Rye/Rename-a-file b/Lang/Rye/Rename-a-file new file mode 120000 index 0000000000..3dce3fa2f0 --- /dev/null +++ b/Lang/Rye/Rename-a-file @@ -0,0 +1 @@ +../../Task/Rename-a-file/Rye \ No newline at end of file diff --git a/Lang/Rye/Return-multiple-values b/Lang/Rye/Return-multiple-values new file mode 120000 index 0000000000..9f9f2d8ad1 --- /dev/null +++ b/Lang/Rye/Return-multiple-values @@ -0,0 +1 @@ +../../Task/Return-multiple-values/Rye \ No newline at end of file diff --git a/Lang/Rye/Reverse-a-string b/Lang/Rye/Reverse-a-string new file mode 120000 index 0000000000..71a229a461 --- /dev/null +++ b/Lang/Rye/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/Rye \ No newline at end of file diff --git a/Lang/Rye/Sleep b/Lang/Rye/Sleep new file mode 120000 index 0000000000..caf7749aa7 --- /dev/null +++ b/Lang/Rye/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Rye \ No newline at end of file diff --git a/Lang/Rye/Sort-an-integer-array b/Lang/Rye/Sort-an-integer-array new file mode 120000 index 0000000000..8cac11dd37 --- /dev/null +++ b/Lang/Rye/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Rye \ No newline at end of file diff --git a/Lang/Rye/String-append b/Lang/Rye/String-append new file mode 120000 index 0000000000..7184f2004b --- /dev/null +++ b/Lang/Rye/String-append @@ -0,0 +1 @@ +../../Task/String-append/Rye \ No newline at end of file diff --git a/Lang/Rye/String-case b/Lang/Rye/String-case new file mode 120000 index 0000000000..d596578a64 --- /dev/null +++ b/Lang/Rye/String-case @@ -0,0 +1 @@ +../../Task/String-case/Rye \ No newline at end of file diff --git a/Lang/Rye/String-concatenation b/Lang/Rye/String-concatenation new file mode 120000 index 0000000000..7a56a81ca6 --- /dev/null +++ b/Lang/Rye/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Rye \ No newline at end of file diff --git a/Lang/Rye/String-interpolation-included- b/Lang/Rye/String-interpolation-included- new file mode 120000 index 0000000000..8918c4450c --- /dev/null +++ b/Lang/Rye/String-interpolation-included- @@ -0,0 +1 @@ +../../Task/String-interpolation-included-/Rye \ No newline at end of file diff --git a/Lang/Rye/String-length b/Lang/Rye/String-length new file mode 120000 index 0000000000..bf2836e136 --- /dev/null +++ b/Lang/Rye/String-length @@ -0,0 +1 @@ +../../Task/String-length/Rye \ No newline at end of file diff --git a/Lang/Rye/Strip-a-set-of-characters-from-a-string b/Lang/Rye/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..a8703fda98 --- /dev/null +++ b/Lang/Rye/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Rye \ No newline at end of file diff --git a/Lang/Rye/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Rye/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..d53cb2cf57 --- /dev/null +++ b/Lang/Rye/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Rye \ No newline at end of file diff --git a/Lang/Rye/Substring-Top-and-tail b/Lang/Rye/Substring-Top-and-tail new file mode 120000 index 0000000000..1cf4555801 --- /dev/null +++ b/Lang/Rye/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Rye \ No newline at end of file diff --git a/Lang/Rye/Sum-and-product-of-an-array b/Lang/Rye/Sum-and-product-of-an-array new file mode 120000 index 0000000000..95d8d590bc --- /dev/null +++ b/Lang/Rye/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Rye \ No newline at end of file diff --git a/Lang/Rye/System-time b/Lang/Rye/System-time new file mode 120000 index 0000000000..14391ca376 --- /dev/null +++ b/Lang/Rye/System-time @@ -0,0 +1 @@ +../../Task/System-time/Rye \ No newline at end of file diff --git a/Lang/Rye/Tokenize-a-string b/Lang/Rye/Tokenize-a-string new file mode 120000 index 0000000000..404261ec01 --- /dev/null +++ b/Lang/Rye/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Rye \ No newline at end of file diff --git a/Lang/Rye/User-input-Text b/Lang/Rye/User-input-Text new file mode 120000 index 0000000000..8cd3ad9295 --- /dev/null +++ b/Lang/Rye/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Rye \ No newline at end of file diff --git a/Lang/Rye/Variables b/Lang/Rye/Variables new file mode 120000 index 0000000000..d50ac89ca0 --- /dev/null +++ b/Lang/Rye/Variables @@ -0,0 +1 @@ +../../Task/Variables/Rye \ No newline at end of file diff --git a/Lang/Rye/Window-creation b/Lang/Rye/Window-creation new file mode 120000 index 0000000000..334b72f881 --- /dev/null +++ b/Lang/Rye/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/Rye \ No newline at end of file diff --git a/Lang/Rye/Write-entire-file b/Lang/Rye/Write-entire-file new file mode 120000 index 0000000000..7a14255070 --- /dev/null +++ b/Lang/Rye/Write-entire-file @@ -0,0 +1 @@ +../../Task/Write-entire-file/Rye \ No newline at end of file diff --git a/Lang/Rye/Zero-to-the-zero-power b/Lang/Rye/Zero-to-the-zero-power new file mode 120000 index 0000000000..2c54da2a61 --- /dev/null +++ b/Lang/Rye/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Rye \ No newline at end of file diff --git a/Lang/S-BASIC/00-LANG.txt b/Lang/S-BASIC/00-LANG.txt index 7e71ba9085..cb4f4a5c14 100644 --- a/Lang/S-BASIC/00-LANG.txt +++ b/Lang/S-BASIC/00-LANG.txt @@ -1,4 +1,5 @@ {{stub}}{{language|S-BASIC}} +{{implementation|BASIC}} S-BASIC (the S stands for "structured") was a native-code compiler for an ALGOL-like dialect of the BASIC programming language, and ran on 8-bit microcomputers using the Z80 CPU and diff --git a/Lang/S-BASIC/Additive-primes b/Lang/S-BASIC/Additive-primes new file mode 120000 index 0000000000..b90d39a158 --- /dev/null +++ b/Lang/S-BASIC/Additive-primes @@ -0,0 +1 @@ +../../Task/Additive-primes/S-BASIC \ No newline at end of file diff --git a/Lang/S-BASIC/Address-of-a-variable b/Lang/S-BASIC/Address-of-a-variable new file mode 120000 index 0000000000..e42c14ed1b --- /dev/null +++ b/Lang/S-BASIC/Address-of-a-variable @@ -0,0 +1 @@ +../../Task/Address-of-a-variable/S-BASIC \ No newline at end of file diff --git a/Lang/S-BASIC/Case-sensitivity-of-identifiers b/Lang/S-BASIC/Case-sensitivity-of-identifiers new file mode 120000 index 0000000000..cf49bbdc11 --- /dev/null +++ b/Lang/S-BASIC/Case-sensitivity-of-identifiers @@ -0,0 +1 @@ +../../Task/Case-sensitivity-of-identifiers/S-BASIC \ No newline at end of file diff --git a/Lang/S-BASIC/Character-codes b/Lang/S-BASIC/Character-codes new file mode 120000 index 0000000000..f408189f94 --- /dev/null +++ b/Lang/S-BASIC/Character-codes @@ -0,0 +1 @@ +../../Task/Character-codes/S-BASIC \ No newline at end of file diff --git a/Lang/S-BASIC/Copy-a-string b/Lang/S-BASIC/Copy-a-string new file mode 120000 index 0000000000..cf54fdae2e --- /dev/null +++ b/Lang/S-BASIC/Copy-a-string @@ -0,0 +1 @@ +../../Task/Copy-a-string/S-BASIC \ No newline at end of file diff --git a/Lang/S-BASIC/Determine-if-a-string-has-all-unique-characters b/Lang/S-BASIC/Determine-if-a-string-has-all-unique-characters new file mode 120000 index 0000000000..f2a5cead6b --- /dev/null +++ b/Lang/S-BASIC/Determine-if-a-string-has-all-unique-characters @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-has-all-unique-characters/S-BASIC \ No newline at end of file diff --git a/Lang/S-BASIC/Factorial b/Lang/S-BASIC/Factorial new file mode 120000 index 0000000000..3c6e9121ba --- /dev/null +++ b/Lang/S-BASIC/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/S-BASIC \ No newline at end of file diff --git a/Lang/S-BASIC/Golden-ratio-Convergence b/Lang/S-BASIC/Golden-ratio-Convergence new file mode 120000 index 0000000000..4ad7ad99cc --- /dev/null +++ b/Lang/S-BASIC/Golden-ratio-Convergence @@ -0,0 +1 @@ +../../Task/Golden-ratio-Convergence/S-BASIC \ No newline at end of file diff --git a/Lang/S-BASIC/Harmonic-series b/Lang/S-BASIC/Harmonic-series new file mode 120000 index 0000000000..32781a4eaa --- /dev/null +++ b/Lang/S-BASIC/Harmonic-series @@ -0,0 +1 @@ +../../Task/Harmonic-series/S-BASIC \ No newline at end of file diff --git a/Lang/S-BASIC/Hello-world-Line-printer b/Lang/S-BASIC/Hello-world-Line-printer new file mode 120000 index 0000000000..c091e2e975 --- /dev/null +++ b/Lang/S-BASIC/Hello-world-Line-printer @@ -0,0 +1 @@ +../../Task/Hello-world-Line-printer/S-BASIC \ No newline at end of file diff --git a/Lang/S-BASIC/Integer-overflow b/Lang/S-BASIC/Integer-overflow new file mode 120000 index 0000000000..60893ea23b --- /dev/null +++ b/Lang/S-BASIC/Integer-overflow @@ -0,0 +1 @@ +../../Task/Integer-overflow/S-BASIC \ No newline at end of file diff --git a/Lang/S-BASIC/Loops-Break b/Lang/S-BASIC/Loops-Break new file mode 120000 index 0000000000..4109f93543 --- /dev/null +++ b/Lang/S-BASIC/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/S-BASIC \ No newline at end of file diff --git a/Lang/S-BASIC/Loops-Do-while b/Lang/S-BASIC/Loops-Do-while new file mode 120000 index 0000000000..026ddb5c46 --- /dev/null +++ b/Lang/S-BASIC/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/S-BASIC \ No newline at end of file diff --git a/Lang/S-BASIC/Loops-Increment-loop-index-within-loop-body b/Lang/S-BASIC/Loops-Increment-loop-index-within-loop-body new file mode 120000 index 0000000000..0b105df636 --- /dev/null +++ b/Lang/S-BASIC/Loops-Increment-loop-index-within-loop-body @@ -0,0 +1 @@ +../../Task/Loops-Increment-loop-index-within-loop-body/S-BASIC \ No newline at end of file diff --git a/Lang/S-BASIC/Loops-While b/Lang/S-BASIC/Loops-While new file mode 120000 index 0000000000..cf0317c07f --- /dev/null +++ b/Lang/S-BASIC/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/S-BASIC \ No newline at end of file diff --git a/Lang/S-BASIC/Real-constants-and-functions b/Lang/S-BASIC/Real-constants-and-functions new file mode 120000 index 0000000000..dd7abd08ca --- /dev/null +++ b/Lang/S-BASIC/Real-constants-and-functions @@ -0,0 +1 @@ +../../Task/Real-constants-and-functions/S-BASIC \ No newline at end of file diff --git a/Lang/S-BASIC/Rename-a-file b/Lang/S-BASIC/Rename-a-file new file mode 120000 index 0000000000..918d2d7e4f --- /dev/null +++ b/Lang/S-BASIC/Rename-a-file @@ -0,0 +1 @@ +../../Task/Rename-a-file/S-BASIC \ No newline at end of file diff --git a/Lang/S-BASIC/Sort-an-integer-array b/Lang/S-BASIC/Sort-an-integer-array new file mode 120000 index 0000000000..ee8b6cb035 --- /dev/null +++ b/Lang/S-BASIC/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/S-BASIC \ No newline at end of file diff --git a/Lang/S-BASIC/Sorting-algorithms-Insertion-sort b/Lang/S-BASIC/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..60391d0e75 --- /dev/null +++ b/Lang/S-BASIC/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/S-BASIC \ No newline at end of file diff --git a/Lang/S-BASIC/Square-free-integers b/Lang/S-BASIC/Square-free-integers new file mode 120000 index 0000000000..d6296e2f26 --- /dev/null +++ b/Lang/S-BASIC/Square-free-integers @@ -0,0 +1 @@ +../../Task/Square-free-integers/S-BASIC \ No newline at end of file diff --git a/Lang/S-BASIC/String-interpolation-included- b/Lang/S-BASIC/String-interpolation-included- new file mode 120000 index 0000000000..c71873859b --- /dev/null +++ b/Lang/S-BASIC/String-interpolation-included- @@ -0,0 +1 @@ +../../Task/String-interpolation-included-/S-BASIC \ No newline at end of file diff --git a/Lang/S-BASIC/Strip-whitespace-from-a-string-Top-and-tail b/Lang/S-BASIC/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..e52fe4d75d --- /dev/null +++ b/Lang/S-BASIC/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/S-BASIC \ No newline at end of file diff --git a/Lang/S-BASIC/Sum-of-a-series b/Lang/S-BASIC/Sum-of-a-series new file mode 120000 index 0000000000..1396d4d958 --- /dev/null +++ b/Lang/S-BASIC/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/S-BASIC \ No newline at end of file diff --git a/Lang/S-BASIC/Variables b/Lang/S-BASIC/Variables new file mode 120000 index 0000000000..09187048df --- /dev/null +++ b/Lang/S-BASIC/Variables @@ -0,0 +1 @@ +../../Task/Variables/S-BASIC \ No newline at end of file diff --git a/Lang/S-BASIC/Zero-to-the-zero-power b/Lang/S-BASIC/Zero-to-the-zero-power new file mode 120000 index 0000000000..e660e2efea --- /dev/null +++ b/Lang/S-BASIC/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/S-BASIC \ No newline at end of file diff --git a/Lang/SETL/Arbitrary-precision-integers-included- b/Lang/SETL/Arbitrary-precision-integers-included- new file mode 120000 index 0000000000..36386fe719 --- /dev/null +++ b/Lang/SETL/Arbitrary-precision-integers-included- @@ -0,0 +1 @@ +../../Task/Arbitrary-precision-integers-included-/SETL \ No newline at end of file diff --git a/Lang/SETL/Arithmetic-derivative b/Lang/SETL/Arithmetic-derivative new file mode 120000 index 0000000000..56f987cef7 --- /dev/null +++ b/Lang/SETL/Arithmetic-derivative @@ -0,0 +1 @@ +../../Task/Arithmetic-derivative/SETL \ No newline at end of file diff --git a/Lang/SETL/Bell-numbers b/Lang/SETL/Bell-numbers new file mode 120000 index 0000000000..32b1473efe --- /dev/null +++ b/Lang/SETL/Bell-numbers @@ -0,0 +1 @@ +../../Task/Bell-numbers/SETL \ No newline at end of file diff --git a/Lang/SETL/Best-shuffle b/Lang/SETL/Best-shuffle new file mode 120000 index 0000000000..25f39d305e --- /dev/null +++ b/Lang/SETL/Best-shuffle @@ -0,0 +1 @@ +../../Task/Best-shuffle/SETL \ No newline at end of file diff --git a/Lang/SETL/Brilliant-numbers b/Lang/SETL/Brilliant-numbers new file mode 120000 index 0000000000..8c8cbe8558 --- /dev/null +++ b/Lang/SETL/Brilliant-numbers @@ -0,0 +1 @@ +../../Task/Brilliant-numbers/SETL \ No newline at end of file diff --git a/Lang/SETL/Calculating-the-value-of-e b/Lang/SETL/Calculating-the-value-of-e new file mode 120000 index 0000000000..751e6b54b5 --- /dev/null +++ b/Lang/SETL/Calculating-the-value-of-e @@ -0,0 +1 @@ +../../Task/Calculating-the-value-of-e/SETL \ No newline at end of file diff --git a/Lang/SETL/Damm-algorithm b/Lang/SETL/Damm-algorithm new file mode 120000 index 0000000000..8e8b8d193a --- /dev/null +++ b/Lang/SETL/Damm-algorithm @@ -0,0 +1 @@ +../../Task/Damm-algorithm/SETL \ No newline at end of file diff --git a/Lang/SETL/Doomsday-rule b/Lang/SETL/Doomsday-rule new file mode 120000 index 0000000000..b9fa54eb7b --- /dev/null +++ b/Lang/SETL/Doomsday-rule @@ -0,0 +1 @@ +../../Task/Doomsday-rule/SETL \ No newline at end of file diff --git a/Lang/SETL/Duffinian-numbers b/Lang/SETL/Duffinian-numbers new file mode 120000 index 0000000000..93694a20c6 --- /dev/null +++ b/Lang/SETL/Duffinian-numbers @@ -0,0 +1 @@ +../../Task/Duffinian-numbers/SETL \ No newline at end of file diff --git a/Lang/SETL/Fractran b/Lang/SETL/Fractran new file mode 120000 index 0000000000..20f759abeb --- /dev/null +++ b/Lang/SETL/Fractran @@ -0,0 +1 @@ +../../Task/Fractran/SETL \ No newline at end of file diff --git a/Lang/SETL/General-FizzBuzz b/Lang/SETL/General-FizzBuzz new file mode 120000 index 0000000000..c26977365f --- /dev/null +++ b/Lang/SETL/General-FizzBuzz @@ -0,0 +1 @@ +../../Task/General-FizzBuzz/SETL \ No newline at end of file diff --git a/Lang/SETL/Gray-code b/Lang/SETL/Gray-code new file mode 120000 index 0000000000..a07e0b4e7b --- /dev/null +++ b/Lang/SETL/Gray-code @@ -0,0 +1 @@ +../../Task/Gray-code/SETL \ No newline at end of file diff --git a/Lang/SETL/Horners-rule-for-polynomial-evaluation b/Lang/SETL/Horners-rule-for-polynomial-evaluation new file mode 120000 index 0000000000..c30c2e1637 --- /dev/null +++ b/Lang/SETL/Horners-rule-for-polynomial-evaluation @@ -0,0 +1 @@ +../../Task/Horners-rule-for-polynomial-evaluation/SETL \ No newline at end of file diff --git a/Lang/SETL/Largest-proper-divisor-of-n b/Lang/SETL/Largest-proper-divisor-of-n new file mode 120000 index 0000000000..a82ec82f9e --- /dev/null +++ b/Lang/SETL/Largest-proper-divisor-of-n @@ -0,0 +1 @@ +../../Task/Largest-proper-divisor-of-n/SETL \ No newline at end of file diff --git a/Lang/SETL/Levenshtein-distance b/Lang/SETL/Levenshtein-distance new file mode 120000 index 0000000000..5a234fcd60 --- /dev/null +++ b/Lang/SETL/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/SETL \ No newline at end of file diff --git a/Lang/SETL/Loops-Do-while b/Lang/SETL/Loops-Do-while new file mode 120000 index 0000000000..8e0329f189 --- /dev/null +++ b/Lang/SETL/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/SETL \ No newline at end of file diff --git a/Lang/SETL/Loops-Increment-loop-index-within-loop-body b/Lang/SETL/Loops-Increment-loop-index-within-loop-body new file mode 120000 index 0000000000..21b3e5953d --- /dev/null +++ b/Lang/SETL/Loops-Increment-loop-index-within-loop-body @@ -0,0 +1 @@ +../../Task/Loops-Increment-loop-index-within-loop-body/SETL \ No newline at end of file diff --git a/Lang/SETL/Loops-Infinite b/Lang/SETL/Loops-Infinite new file mode 120000 index 0000000000..582c03e313 --- /dev/null +++ b/Lang/SETL/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/SETL \ No newline at end of file diff --git a/Lang/SETL/Loops-N-plus-one-half b/Lang/SETL/Loops-N-plus-one-half new file mode 120000 index 0000000000..111820383b --- /dev/null +++ b/Lang/SETL/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/SETL \ No newline at end of file diff --git a/Lang/SETL/Luhn-test-of-credit-card-numbers b/Lang/SETL/Luhn-test-of-credit-card-numbers new file mode 120000 index 0000000000..d5c47a10ed --- /dev/null +++ b/Lang/SETL/Luhn-test-of-credit-card-numbers @@ -0,0 +1 @@ +../../Task/Luhn-test-of-credit-card-numbers/SETL \ No newline at end of file diff --git a/Lang/SETL/Matrix-transposition b/Lang/SETL/Matrix-transposition new file mode 120000 index 0000000000..9a975d9213 --- /dev/null +++ b/Lang/SETL/Matrix-transposition @@ -0,0 +1 @@ +../../Task/Matrix-transposition/SETL \ No newline at end of file diff --git a/Lang/SETL/Mayan-numerals b/Lang/SETL/Mayan-numerals new file mode 120000 index 0000000000..fd50100876 --- /dev/null +++ b/Lang/SETL/Mayan-numerals @@ -0,0 +1 @@ +../../Task/Mayan-numerals/SETL \ No newline at end of file diff --git a/Lang/SETL/Modular-exponentiation b/Lang/SETL/Modular-exponentiation new file mode 120000 index 0000000000..fcea778ebb --- /dev/null +++ b/Lang/SETL/Modular-exponentiation @@ -0,0 +1 @@ +../../Task/Modular-exponentiation/SETL \ No newline at end of file diff --git a/Lang/SETL/Monte-Carlo-methods b/Lang/SETL/Monte-Carlo-methods new file mode 120000 index 0000000000..da6adaf82b --- /dev/null +++ b/Lang/SETL/Monte-Carlo-methods @@ -0,0 +1 @@ +../../Task/Monte-Carlo-methods/SETL \ No newline at end of file diff --git a/Lang/SETL/Monty-Hall-problem b/Lang/SETL/Monty-Hall-problem new file mode 120000 index 0000000000..0740052c5e --- /dev/null +++ b/Lang/SETL/Monty-Hall-problem @@ -0,0 +1 @@ +../../Task/Monty-Hall-problem/SETL \ No newline at end of file diff --git a/Lang/SETL/Move-to-front-algorithm b/Lang/SETL/Move-to-front-algorithm new file mode 120000 index 0000000000..7a6129ce08 --- /dev/null +++ b/Lang/SETL/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/SETL \ No newline at end of file diff --git a/Lang/SETL/Nested-templated-data b/Lang/SETL/Nested-templated-data new file mode 120000 index 0000000000..58fd3f508a --- /dev/null +++ b/Lang/SETL/Nested-templated-data @@ -0,0 +1 @@ +../../Task/Nested-templated-data/SETL \ No newline at end of file diff --git a/Lang/SETL/Old-lady-swallowed-a-fly b/Lang/SETL/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..948ed47605 --- /dev/null +++ b/Lang/SETL/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/SETL \ No newline at end of file diff --git a/Lang/SETL/Ordered-words b/Lang/SETL/Ordered-words new file mode 120000 index 0000000000..efd35b209e --- /dev/null +++ b/Lang/SETL/Ordered-words @@ -0,0 +1 @@ +../../Task/Ordered-words/SETL \ No newline at end of file diff --git a/Lang/SETL/Partition-function-P b/Lang/SETL/Partition-function-P new file mode 120000 index 0000000000..f47b3bd593 --- /dev/null +++ b/Lang/SETL/Partition-function-P @@ -0,0 +1 @@ +../../Task/Partition-function-P/SETL \ No newline at end of file diff --git a/Lang/SETL/Pisano-period b/Lang/SETL/Pisano-period new file mode 120000 index 0000000000..735d169166 --- /dev/null +++ b/Lang/SETL/Pisano-period @@ -0,0 +1 @@ +../../Task/Pisano-period/SETL \ No newline at end of file diff --git a/Lang/SETL/RPG-attributes-generator b/Lang/SETL/RPG-attributes-generator new file mode 120000 index 0000000000..86469ad6af --- /dev/null +++ b/Lang/SETL/RPG-attributes-generator @@ -0,0 +1 @@ +../../Task/RPG-attributes-generator/SETL \ No newline at end of file diff --git a/Lang/SETL/Radical-of-an-integer b/Lang/SETL/Radical-of-an-integer new file mode 120000 index 0000000000..7020a7b45c --- /dev/null +++ b/Lang/SETL/Radical-of-an-integer @@ -0,0 +1 @@ +../../Task/Radical-of-an-integer/SETL \ No newline at end of file diff --git a/Lang/SETL/Range-consolidation b/Lang/SETL/Range-consolidation new file mode 120000 index 0000000000..b24d504011 --- /dev/null +++ b/Lang/SETL/Range-consolidation @@ -0,0 +1 @@ +../../Task/Range-consolidation/SETL \ No newline at end of file diff --git a/Lang/SETL/Show-ASCII-table b/Lang/SETL/Show-ASCII-table new file mode 120000 index 0000000000..5c4e8348ce --- /dev/null +++ b/Lang/SETL/Show-ASCII-table @@ -0,0 +1 @@ +../../Task/Show-ASCII-table/SETL \ No newline at end of file diff --git a/Lang/SETL/Sleeping-Beauty-problem b/Lang/SETL/Sleeping-Beauty-problem new file mode 120000 index 0000000000..cf1ef983c1 --- /dev/null +++ b/Lang/SETL/Sleeping-Beauty-problem @@ -0,0 +1 @@ +../../Task/Sleeping-Beauty-problem/SETL \ No newline at end of file diff --git a/Lang/SETL/Split-a-character-string-based-on-change-of-character b/Lang/SETL/Split-a-character-string-based-on-change-of-character new file mode 120000 index 0000000000..ff9aa0b4dd --- /dev/null +++ b/Lang/SETL/Split-a-character-string-based-on-change-of-character @@ -0,0 +1 @@ +../../Task/Split-a-character-string-based-on-change-of-character/SETL \ No newline at end of file diff --git a/Lang/SETL/Square-free-integers b/Lang/SETL/Square-free-integers new file mode 120000 index 0000000000..328ef78775 --- /dev/null +++ b/Lang/SETL/Square-free-integers @@ -0,0 +1 @@ +../../Task/Square-free-integers/SETL \ No newline at end of file diff --git a/Lang/SETL/Strip-comments-from-a-string b/Lang/SETL/Strip-comments-from-a-string new file mode 120000 index 0000000000..6397b858bf --- /dev/null +++ b/Lang/SETL/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/SETL \ No newline at end of file diff --git a/Lang/SETL/Super-d-numbers b/Lang/SETL/Super-d-numbers new file mode 120000 index 0000000000..0f77d4c38c --- /dev/null +++ b/Lang/SETL/Super-d-numbers @@ -0,0 +1 @@ +../../Task/Super-d-numbers/SETL \ No newline at end of file diff --git a/Lang/SETL/Tokenize-a-string b/Lang/SETL/Tokenize-a-string new file mode 120000 index 0000000000..bd55474aef --- /dev/null +++ b/Lang/SETL/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/SETL \ No newline at end of file diff --git a/Lang/SETL/Vector-products b/Lang/SETL/Vector-products new file mode 120000 index 0000000000..936d45f3d5 --- /dev/null +++ b/Lang/SETL/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/SETL \ No newline at end of file diff --git a/Lang/SETL/Word-ladder b/Lang/SETL/Word-ladder new file mode 120000 index 0000000000..c8dccafa85 --- /dev/null +++ b/Lang/SETL/Word-ladder @@ -0,0 +1 @@ +../../Task/Word-ladder/SETL \ No newline at end of file diff --git a/Lang/SETL/Zeckendorf-number-representation b/Lang/SETL/Zeckendorf-number-representation new file mode 120000 index 0000000000..536fc12840 --- /dev/null +++ b/Lang/SETL/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/SETL \ No newline at end of file diff --git a/Lang/SIL/00-LANG.txt b/Lang/SIL/00-LANG.txt new file mode 100644 index 0000000000..2639d4af86 --- /dev/null +++ b/Lang/SIL/00-LANG.txt @@ -0,0 +1,8 @@ +{{stub}}{{language|sil}} +SIL (Simple Interpreted Language) is designed for a nostalgic view of the past. It is simple and minimalist, but remains capable of universal computation. SIL used to be known as S.I.L.O.S. + +=== Todo === +[[Tasks not implemented in SIL]] + +==Links== +*[https://github.com/rjhunjhunwala/SIL-S.I.L.O.S SIL on GitHub] \ No newline at end of file diff --git a/Lang/SIL/00-META.yaml b/Lang/SIL/00-META.yaml new file mode 100644 index 0000000000..ac7ba9e679 --- /dev/null +++ b/Lang/SIL/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:SIL diff --git a/Lang/SIL/Apply-a-callback-to-an-array b/Lang/SIL/Apply-a-callback-to-an-array new file mode 120000 index 0000000000..c6346f2693 --- /dev/null +++ b/Lang/SIL/Apply-a-callback-to-an-array @@ -0,0 +1 @@ +../../Task/Apply-a-callback-to-an-array/SIL \ No newline at end of file diff --git a/Lang/SIL/Arithmetic-Integer b/Lang/SIL/Arithmetic-Integer new file mode 120000 index 0000000000..0359dfe6a8 --- /dev/null +++ b/Lang/SIL/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/SIL \ No newline at end of file diff --git a/Lang/SIL/Function-definition b/Lang/SIL/Function-definition new file mode 120000 index 0000000000..1ed935d033 --- /dev/null +++ b/Lang/SIL/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/SIL \ No newline at end of file diff --git a/Lang/SIL/Hello-world-Text b/Lang/SIL/Hello-world-Text new file mode 120000 index 0000000000..67a60a7cc4 --- /dev/null +++ b/Lang/SIL/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/SIL \ No newline at end of file diff --git a/Lang/SIL/Loops-Do-while b/Lang/SIL/Loops-Do-while new file mode 120000 index 0000000000..226040ebd7 --- /dev/null +++ b/Lang/SIL/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/SIL \ No newline at end of file diff --git a/Lang/SIL/Loops-For b/Lang/SIL/Loops-For new file mode 120000 index 0000000000..f6976d2ec6 --- /dev/null +++ b/Lang/SIL/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/SIL \ No newline at end of file diff --git a/Lang/SIL/Loops-Infinite b/Lang/SIL/Loops-Infinite new file mode 120000 index 0000000000..923cceed13 --- /dev/null +++ b/Lang/SIL/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/SIL \ No newline at end of file diff --git a/Lang/SIL/Loops-N-plus-one-half b/Lang/SIL/Loops-N-plus-one-half new file mode 120000 index 0000000000..8adce730cd --- /dev/null +++ b/Lang/SIL/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/SIL \ No newline at end of file diff --git a/Lang/SIL/Loops-While b/Lang/SIL/Loops-While new file mode 120000 index 0000000000..401dee2479 --- /dev/null +++ b/Lang/SIL/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/SIL \ No newline at end of file diff --git a/Lang/SNOBOL4/Find-the-intersection-of-two-lines b/Lang/SNOBOL4/Find-the-intersection-of-two-lines new file mode 120000 index 0000000000..b2451a2b39 --- /dev/null +++ b/Lang/SNOBOL4/Find-the-intersection-of-two-lines @@ -0,0 +1 @@ +../../Task/Find-the-intersection-of-two-lines/SNOBOL4 \ No newline at end of file diff --git a/Lang/SNOBOL4/Multiplication-tables b/Lang/SNOBOL4/Multiplication-tables new file mode 120000 index 0000000000..756425cd3a --- /dev/null +++ b/Lang/SNOBOL4/Multiplication-tables @@ -0,0 +1 @@ +../../Task/Multiplication-tables/SNOBOL4 \ No newline at end of file diff --git a/Lang/SQL/Factorial b/Lang/SQL/Factorial new file mode 120000 index 0000000000..c6f45973cd --- /dev/null +++ b/Lang/SQL/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/SQL \ No newline at end of file diff --git a/Lang/SapbotVM/00-LANG.txt b/Lang/SapbotVM/00-LANG.txt new file mode 100644 index 0000000000..a83fdbd907 --- /dev/null +++ b/Lang/SapbotVM/00-LANG.txt @@ -0,0 +1,4 @@ +{{stub}}{{language|SapbotVM}} +SapbotVM is easy-to-implement virtual machine architecture, made by Romarchive, that's not compilable, but only have interpreted Assembler. Also, this language have two formats: SVM1, SVM2. First, is based on JSON, second is custom. + +SapbotVM have limited support for monitor, no internet and plug and play devices. So only serial port. \ No newline at end of file diff --git a/Lang/SapbotVM/00-META.yaml b/Lang/SapbotVM/00-META.yaml new file mode 100644 index 0000000000..f50043dbce --- /dev/null +++ b/Lang/SapbotVM/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:SapbotVM diff --git a/Lang/SapbotVM/Guess-the-number-With-feedback b/Lang/SapbotVM/Guess-the-number-With-feedback new file mode 120000 index 0000000000..0038e4427f --- /dev/null +++ b/Lang/SapbotVM/Guess-the-number-With-feedback @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback/SapbotVM \ No newline at end of file diff --git a/Lang/SapbotVM/Hello-world-Text b/Lang/SapbotVM/Hello-world-Text new file mode 120000 index 0000000000..c695d3ee98 --- /dev/null +++ b/Lang/SapbotVM/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/SapbotVM \ No newline at end of file diff --git a/Lang/Scala/Additive-primes b/Lang/Scala/Additive-primes new file mode 120000 index 0000000000..ba2692b54f --- /dev/null +++ b/Lang/Scala/Additive-primes @@ -0,0 +1 @@ +../../Task/Additive-primes/Scala \ No newline at end of file diff --git a/Lang/Scala/Boyer-Moore-string-search b/Lang/Scala/Boyer-Moore-string-search new file mode 120000 index 0000000000..58b64a7997 --- /dev/null +++ b/Lang/Scala/Boyer-Moore-string-search @@ -0,0 +1 @@ +../../Task/Boyer-Moore-string-search/Scala \ No newline at end of file diff --git a/Lang/Scala/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- b/Lang/Scala/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- new file mode 120000 index 0000000000..03b359aab4 --- /dev/null +++ b/Lang/Scala/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n-/Scala \ No newline at end of file diff --git a/Lang/Scala/Descending-primes b/Lang/Scala/Descending-primes new file mode 120000 index 0000000000..461c6bfefd --- /dev/null +++ b/Lang/Scala/Descending-primes @@ -0,0 +1 @@ +../../Task/Descending-primes/Scala \ No newline at end of file diff --git a/Lang/Scala/ISBN13-check-digit b/Lang/Scala/ISBN13-check-digit new file mode 120000 index 0000000000..b0dc1022b2 --- /dev/null +++ b/Lang/Scala/ISBN13-check-digit @@ -0,0 +1 @@ +../../Task/ISBN13-check-digit/Scala \ No newline at end of file diff --git a/Lang/Scala/Miller-Rabin-primality-test b/Lang/Scala/Miller-Rabin-primality-test deleted file mode 120000 index 28de5ef463..0000000000 --- a/Lang/Scala/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Scala \ No newline at end of file diff --git a/Lang/Scala/Parallel-calculations b/Lang/Scala/Parallel-calculations new file mode 120000 index 0000000000..525e6ca1ba --- /dev/null +++ b/Lang/Scala/Parallel-calculations @@ -0,0 +1 @@ +../../Task/Parallel-calculations/Scala \ No newline at end of file diff --git a/Lang/Scala/Quaternion-type b/Lang/Scala/Quaternion-type deleted file mode 120000 index 15f3eda4c9..0000000000 --- a/Lang/Scala/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Scala \ No newline at end of file diff --git a/Lang/Scala/Sorting-Algorithms-Circle-Sort b/Lang/Scala/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 5b9f057951..0000000000 --- a/Lang/Scala/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Scala \ No newline at end of file diff --git a/Lang/Scala/Tonelli-Shanks-algorithm b/Lang/Scala/Tonelli-Shanks-algorithm new file mode 120000 index 0000000000..a29f0a9b6f --- /dev/null +++ b/Lang/Scala/Tonelli-Shanks-algorithm @@ -0,0 +1 @@ +../../Task/Tonelli-Shanks-algorithm/Scala \ No newline at end of file diff --git a/Lang/Scala/UPC b/Lang/Scala/UPC new file mode 120000 index 0000000000..bc3faec2ef --- /dev/null +++ b/Lang/Scala/UPC @@ -0,0 +1 @@ +../../Task/UPC/Scala \ No newline at end of file diff --git a/Lang/Scheme/Cantor-set b/Lang/Scheme/Cantor-set new file mode 120000 index 0000000000..a799296687 --- /dev/null +++ b/Lang/Scheme/Cantor-set @@ -0,0 +1 @@ +../../Task/Cantor-set/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Cholesky-decomposition b/Lang/Scheme/Cholesky-decomposition new file mode 120000 index 0000000000..ade9e83803 --- /dev/null +++ b/Lang/Scheme/Cholesky-decomposition @@ -0,0 +1 @@ +../../Task/Cholesky-decomposition/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Circular-primes b/Lang/Scheme/Circular-primes new file mode 120000 index 0000000000..9f4430f520 --- /dev/null +++ b/Lang/Scheme/Circular-primes @@ -0,0 +1 @@ +../../Task/Circular-primes/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Compare-length-of-two-strings b/Lang/Scheme/Compare-length-of-two-strings new file mode 120000 index 0000000000..d6e6006fa7 --- /dev/null +++ b/Lang/Scheme/Compare-length-of-two-strings @@ -0,0 +1 @@ +../../Task/Compare-length-of-two-strings/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Conjugate-transpose b/Lang/Scheme/Conjugate-transpose new file mode 120000 index 0000000000..ef50892884 --- /dev/null +++ b/Lang/Scheme/Conjugate-transpose @@ -0,0 +1 @@ +../../Task/Conjugate-transpose/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Egyptian-division b/Lang/Scheme/Egyptian-division new file mode 120000 index 0000000000..ca3a36ae83 --- /dev/null +++ b/Lang/Scheme/Egyptian-division @@ -0,0 +1 @@ +../../Task/Egyptian-division/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Empty-program b/Lang/Scheme/Empty-program deleted file mode 120000 index ee1ee662be..0000000000 --- a/Lang/Scheme/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Find-the-missing-permutation b/Lang/Scheme/Find-the-missing-permutation new file mode 120000 index 0000000000..8f7e82d271 --- /dev/null +++ b/Lang/Scheme/Find-the-missing-permutation @@ -0,0 +1 @@ +../../Task/Find-the-missing-permutation/Scheme \ No newline at end of file diff --git a/Lang/Scheme/French-Republican-calendar b/Lang/Scheme/French-Republican-calendar new file mode 120000 index 0000000000..f19a245ee9 --- /dev/null +++ b/Lang/Scheme/French-Republican-calendar @@ -0,0 +1 @@ +../../Task/French-Republican-calendar/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Kronecker-product b/Lang/Scheme/Kronecker-product new file mode 120000 index 0000000000..58539a69b9 --- /dev/null +++ b/Lang/Scheme/Kronecker-product @@ -0,0 +1 @@ +../../Task/Kronecker-product/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Kronecker-product-based-fractals b/Lang/Scheme/Kronecker-product-based-fractals new file mode 120000 index 0000000000..c27228f2e0 --- /dev/null +++ b/Lang/Scheme/Kronecker-product-based-fractals @@ -0,0 +1 @@ +../../Task/Kronecker-product-based-fractals/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Last-letter-first-letter b/Lang/Scheme/Last-letter-first-letter new file mode 120000 index 0000000000..a5c5c31b6e --- /dev/null +++ b/Lang/Scheme/Last-letter-first-letter @@ -0,0 +1 @@ +../../Task/Last-letter-first-letter/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Miller-Rabin-primality-test b/Lang/Scheme/Miller-Rabin-primality-test deleted file mode 120000 index 644cc32269..0000000000 --- a/Lang/Scheme/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Own-digits-power-sum b/Lang/Scheme/Own-digits-power-sum new file mode 120000 index 0000000000..0897a09d02 --- /dev/null +++ b/Lang/Scheme/Own-digits-power-sum @@ -0,0 +1 @@ +../../Task/Own-digits-power-sum/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Pick-random-element b/Lang/Scheme/Pick-random-element new file mode 120000 index 0000000000..5745ea287d --- /dev/null +++ b/Lang/Scheme/Pick-random-element @@ -0,0 +1 @@ +../../Task/Pick-random-element/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Pseudo-random-numbers-Splitmix64 b/Lang/Scheme/Pseudo-random-numbers-Splitmix64 new file mode 120000 index 0000000000..730c9170c9 --- /dev/null +++ b/Lang/Scheme/Pseudo-random-numbers-Splitmix64 @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-Splitmix64/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Runge-Kutta-method b/Lang/Scheme/Runge-Kutta-method new file mode 120000 index 0000000000..55b6f782a6 --- /dev/null +++ b/Lang/Scheme/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Sierpinski-triangle-Graphical b/Lang/Scheme/Sierpinski-triangle-Graphical new file mode 120000 index 0000000000..13f8e60559 --- /dev/null +++ b/Lang/Scheme/Sierpinski-triangle-Graphical @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle-Graphical/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Tau-number b/Lang/Scheme/Tau-number new file mode 120000 index 0000000000..fe45f01d25 --- /dev/null +++ b/Lang/Scheme/Tau-number @@ -0,0 +1 @@ +../../Task/Tau-number/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Unicode-variable-names b/Lang/Scheme/Unicode-variable-names new file mode 120000 index 0000000000..e5f49b3fae --- /dev/null +++ b/Lang/Scheme/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Word-frequency b/Lang/Scheme/Word-frequency new file mode 120000 index 0000000000..109edef2da --- /dev/null +++ b/Lang/Scheme/Word-frequency @@ -0,0 +1 @@ +../../Task/Word-frequency/Scheme \ No newline at end of file diff --git a/Lang/Scilab/Empty-program b/Lang/Scilab/Empty-program deleted file mode 120000 index 0cb8f21cc3..0000000000 --- a/Lang/Scilab/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Scilab \ No newline at end of file diff --git a/Lang/Sed/00-LANG.txt b/Lang/Sed/00-LANG.txt index 23390cea6c..5d2641e2db 100644 --- a/Lang/Sed/00-LANG.txt +++ b/Lang/Sed/00-LANG.txt @@ -6,5 +6,7 @@ a non interactive tool for text manipulation and filtering. One implementation is [[GNU Sed]] +See [[Tasks not implemented in sed]] + [[Category:Editor]] [[Category:Utility]] \ No newline at end of file diff --git a/Lang/Seed7/Miller-Rabin-primality-test b/Lang/Seed7/Miller-Rabin-primality-test deleted file mode 120000 index 298c8872f9..0000000000 --- a/Lang/Seed7/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Quaternion-type b/Lang/Seed7/Quaternion-type deleted file mode 120000 index d621b24ce0..0000000000 --- a/Lang/Seed7/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Seed7 \ No newline at end of file diff --git a/Lang/SequenceL/00-LANG.txt b/Lang/SequenceL/00-LANG.txt index 3c3098bf74..5e5a95101f 100644 --- a/Lang/SequenceL/00-LANG.txt +++ b/Lang/SequenceL/00-LANG.txt @@ -3,7 +3,7 @@ |strength=strong |safety=safe |checking=static -|site=http://sequencel.com +|site= |tags=sequencel |hopl=no}} {{language programming paradigm|Declarative}} diff --git a/Lang/Set-lang/Empty-program b/Lang/Set-lang/Empty-program deleted file mode 120000 index e6f84e5a85..0000000000 --- a/Lang/Set-lang/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Set-lang \ No newline at end of file diff --git a/Lang/SheerPower-4GL/00-LANG.txt b/Lang/SheerPower-4GL/00-LANG.txt index bd4b7049ad..fc11170935 100644 --- a/Lang/SheerPower-4GL/00-LANG.txt +++ b/Lang/SheerPower-4GL/00-LANG.txt @@ -1,6 +1,6 @@ {{stub}} {{language -|site=http://www.sp4gl.com/ +|site=https://sheerpower.ttinet.com/index.html/ }} SheerPower 4GL is a Fourth-generation programming language developed by Touch Technologies, Inc. @@ -16,4 +16,7 @@ SheerPower 4GL has several key features: #There is also a Common Gateway Interface (CGI) interface built into SheerPower, along with many other built-in functions designed for high-performance and increased programmer productivity. == See Also == -[[wp:SheerPower4GL|Wikipedia:SheerPower4GL]] \ No newline at end of file +[[wp:SheerPower4GL|Wikipedia:SheerPower4GL]] + +==Todo== +[[Tasks_not_implemented_in_SheerPower_4GL]] \ No newline at end of file diff --git a/Lang/SheerPower-4GL/99-bottles-of-beer b/Lang/SheerPower-4GL/99-bottles-of-beer new file mode 120000 index 0000000000..71e6136936 --- /dev/null +++ b/Lang/SheerPower-4GL/99-bottles-of-beer @@ -0,0 +1 @@ +../../Task/99-bottles-of-beer/SheerPower-4GL \ No newline at end of file diff --git a/Lang/SheerPower-4GL/Caesar-cipher b/Lang/SheerPower-4GL/Caesar-cipher new file mode 120000 index 0000000000..b9d2a1d1d1 --- /dev/null +++ b/Lang/SheerPower-4GL/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/SheerPower-4GL \ No newline at end of file diff --git a/Lang/SheerPower-4GL/FizzBuzz b/Lang/SheerPower-4GL/FizzBuzz new file mode 120000 index 0000000000..339e329e2c --- /dev/null +++ b/Lang/SheerPower-4GL/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/SheerPower-4GL \ No newline at end of file diff --git a/Lang/SheerPower-4GL/Towers-of-Hanoi b/Lang/SheerPower-4GL/Towers-of-Hanoi new file mode 120000 index 0000000000..a6bc7f6597 --- /dev/null +++ b/Lang/SheerPower-4GL/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/SheerPower-4GL \ No newline at end of file diff --git a/Lang/Sidef/00-LANG.txt b/Lang/Sidef/00-LANG.txt index a63ddf8a52..03c8af9ab7 100644 --- a/Lang/Sidef/00-LANG.txt +++ b/Lang/Sidef/00-LANG.txt @@ -18,14 +18,11 @@ [https://tio.run/#sidef Try Sidef on tio.run] {{infobox_end}} -Sidef is a modern, dynamic, object-oriented programming language, focusing on simplicity, readability and elegance, taking the best from languages like [[derived from::Ruby]], [[derived from::Go]], [[derived from::Raku]] and [[derived from::Julia]]. +Sidef is a modern, expressive programming language that combines the elegance of [[derived from::Ruby]], the versatility of [[derived from::Raku]], and the mathematical power of a built-in computer algebra system. The language is mostly used as a research programming language. -For more details, see: -* Gitbook: [https://trizen.gitbook.io/sidef-lang/ https://trizen.gitbook.io/sidef-lang/] -* Tutorial: [https://notabug.org/trizen/sidef/wiki https://notabug.org/trizen/sidef/wiki] -* Development page: [https://github.com/trizen/sidef https://github.com/trizen/sidef] +For more details, see: [https://github.com/trizen/sidef https://github.com/trizen/sidef] ==Todo== diff --git a/Lang/Sidef/Arithmetic-derivative b/Lang/Sidef/Arithmetic-derivative new file mode 120000 index 0000000000..bdcd1874e7 --- /dev/null +++ b/Lang/Sidef/Arithmetic-derivative @@ -0,0 +1 @@ +../../Task/Arithmetic-derivative/Sidef \ No newline at end of file diff --git a/Lang/Sidef/Arithmetic-numbers b/Lang/Sidef/Arithmetic-numbers new file mode 120000 index 0000000000..672bca881d --- /dev/null +++ b/Lang/Sidef/Arithmetic-numbers @@ -0,0 +1 @@ +../../Task/Arithmetic-numbers/Sidef \ No newline at end of file diff --git a/Lang/Sidef/Binary-strings b/Lang/Sidef/Binary-strings new file mode 120000 index 0000000000..86bf141c80 --- /dev/null +++ b/Lang/Sidef/Binary-strings @@ -0,0 +1 @@ +../../Task/Binary-strings/Sidef \ No newline at end of file diff --git a/Lang/Sidef/CRC-32 b/Lang/Sidef/CRC-32 new file mode 120000 index 0000000000..7abbf21ee3 --- /dev/null +++ b/Lang/Sidef/CRC-32 @@ -0,0 +1 @@ +../../Task/CRC-32/Sidef \ No newline at end of file diff --git a/Lang/Sidef/Empty-program b/Lang/Sidef/Empty-program deleted file mode 120000 index c7465e3077..0000000000 --- a/Lang/Sidef/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Sidef \ No newline at end of file diff --git a/Lang/Sidef/Increasing-gaps-between-consecutive-Niven-numbers b/Lang/Sidef/Increasing-gaps-between-consecutive-Niven-numbers new file mode 120000 index 0000000000..b80a20c4f5 --- /dev/null +++ b/Lang/Sidef/Increasing-gaps-between-consecutive-Niven-numbers @@ -0,0 +1 @@ +../../Task/Increasing-gaps-between-consecutive-Niven-numbers/Sidef \ No newline at end of file diff --git a/Lang/Sidef/Jaro-Winkler-distance b/Lang/Sidef/Jaro-Winkler-distance new file mode 120000 index 0000000000..48f92f7ccd --- /dev/null +++ b/Lang/Sidef/Jaro-Winkler-distance @@ -0,0 +1 @@ +../../Task/Jaro-Winkler-distance/Sidef \ No newline at end of file diff --git a/Lang/Sidef/Jordan-P-lya-numbers b/Lang/Sidef/Jordan-P-lya-numbers new file mode 120000 index 0000000000..b084543da1 --- /dev/null +++ b/Lang/Sidef/Jordan-P-lya-numbers @@ -0,0 +1 @@ +../../Task/Jordan-P-lya-numbers/Sidef \ No newline at end of file diff --git a/Lang/Sidef/Meissel-Mertens-constant b/Lang/Sidef/Meissel-Mertens-constant deleted file mode 120000 index 7eda1518da..0000000000 --- a/Lang/Sidef/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/Sidef \ No newline at end of file diff --git a/Lang/Sidef/Miller-Rabin-primality-test b/Lang/Sidef/Miller-Rabin-primality-test deleted file mode 120000 index 5bb5523a0e..0000000000 --- a/Lang/Sidef/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Sidef \ No newline at end of file diff --git a/Lang/Sidef/Pell-numbers b/Lang/Sidef/Pell-numbers new file mode 120000 index 0000000000..af14680327 --- /dev/null +++ b/Lang/Sidef/Pell-numbers @@ -0,0 +1 @@ +../../Task/Pell-numbers/Sidef \ No newline at end of file diff --git a/Lang/Sidef/Prime-numbers-whose-neighboring-pairs-are-tetraprimes b/Lang/Sidef/Prime-numbers-whose-neighboring-pairs-are-tetraprimes new file mode 120000 index 0000000000..1f840ef9e4 --- /dev/null +++ b/Lang/Sidef/Prime-numbers-whose-neighboring-pairs-are-tetraprimes @@ -0,0 +1 @@ +../../Task/Prime-numbers-whose-neighboring-pairs-are-tetraprimes/Sidef \ No newline at end of file diff --git a/Lang/Sidef/Quaternion-type b/Lang/Sidef/Quaternion-type deleted file mode 120000 index 5e28a5e41d..0000000000 --- a/Lang/Sidef/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Sidef \ No newline at end of file diff --git a/Lang/Sidef/Smarandache-Wellin-primes b/Lang/Sidef/Smarandache-Wellin-primes new file mode 120000 index 0000000000..056e5bc295 --- /dev/null +++ b/Lang/Sidef/Smarandache-Wellin-primes @@ -0,0 +1 @@ +../../Task/Smarandache-Wellin-primes/Sidef \ No newline at end of file diff --git a/Lang/Sidef/Sorting-Algorithms-Circle-Sort b/Lang/Sidef/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index e866329cad..0000000000 --- a/Lang/Sidef/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Sidef \ No newline at end of file diff --git a/Lang/Sidef/Wagstaff-primes b/Lang/Sidef/Wagstaff-primes new file mode 120000 index 0000000000..d0053cfbed --- /dev/null +++ b/Lang/Sidef/Wagstaff-primes @@ -0,0 +1 @@ +../../Task/Wagstaff-primes/Sidef \ No newline at end of file diff --git a/Lang/SimpleCode/Empty-program b/Lang/SimpleCode/Empty-program deleted file mode 120000 index dc55c70d09..0000000000 --- a/Lang/SimpleCode/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/SimpleCode \ No newline at end of file diff --git a/Lang/Slate/Empty-program b/Lang/Slate/Empty-program deleted file mode 120000 index cea8e90b74..0000000000 --- a/Lang/Slate/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Slate \ No newline at end of file diff --git a/Lang/Smalltalk/Miller-Rabin-primality-test b/Lang/Smalltalk/Miller-Rabin-primality-test deleted file mode 120000 index e3a303744d..0000000000 --- a/Lang/Smalltalk/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Smalltalk \ No newline at end of file diff --git a/Lang/SmileBASIC/Execute-Brain- b/Lang/SmileBASIC/Execute-Brain- new file mode 120000 index 0000000000..f5b6561ddd --- /dev/null +++ b/Lang/SmileBASIC/Execute-Brain- @@ -0,0 +1 @@ +../../Task/Execute-Brain-/SmileBASIC \ No newline at end of file diff --git a/Lang/Sparkling/Empty-program b/Lang/Sparkling/Empty-program deleted file mode 120000 index 519287810d..0000000000 --- a/Lang/Sparkling/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Sparkling \ No newline at end of file diff --git a/Lang/Standard-ML/Averages-Mean-angle b/Lang/Standard-ML/Averages-Mean-angle new file mode 120000 index 0000000000..38ef0bd393 --- /dev/null +++ b/Lang/Standard-ML/Averages-Mean-angle @@ -0,0 +1 @@ +../../Task/Averages-Mean-angle/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Averages-Simple-moving-average b/Lang/Standard-ML/Averages-Simple-moving-average new file mode 120000 index 0000000000..6dd59a5e2f --- /dev/null +++ b/Lang/Standard-ML/Averages-Simple-moving-average @@ -0,0 +1 @@ +../../Task/Averages-Simple-moving-average/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Box-the-compass b/Lang/Standard-ML/Box-the-compass new file mode 120000 index 0000000000..bdb5283192 --- /dev/null +++ b/Lang/Standard-ML/Box-the-compass @@ -0,0 +1 @@ +../../Task/Box-the-compass/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Call-a-foreign-language-function b/Lang/Standard-ML/Call-a-foreign-language-function new file mode 120000 index 0000000000..1f398efa97 --- /dev/null +++ b/Lang/Standard-ML/Call-a-foreign-language-function @@ -0,0 +1 @@ +../../Task/Call-a-foreign-language-function/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Knuth-shuffle b/Lang/Standard-ML/Knuth-shuffle new file mode 120000 index 0000000000..da7fa35b79 --- /dev/null +++ b/Lang/Standard-ML/Knuth-shuffle @@ -0,0 +1 @@ +../../Task/Knuth-shuffle/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Last-Friday-of-each-month b/Lang/Standard-ML/Last-Friday-of-each-month new file mode 120000 index 0000000000..39c2756109 --- /dev/null +++ b/Lang/Standard-ML/Last-Friday-of-each-month @@ -0,0 +1 @@ +../../Task/Last-Friday-of-each-month/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Miller-Rabin-primality-test b/Lang/Standard-ML/Miller-Rabin-primality-test deleted file mode 120000 index ba4b002043..0000000000 --- a/Lang/Standard-ML/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Pi b/Lang/Standard-ML/Pi new file mode 120000 index 0000000000..f806ddbcae --- /dev/null +++ b/Lang/Standard-ML/Pi @@ -0,0 +1 @@ +../../Task/Pi/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Pseudo-random-numbers-Splitmix64 b/Lang/Standard-ML/Pseudo-random-numbers-Splitmix64 new file mode 120000 index 0000000000..bce7d31edd --- /dev/null +++ b/Lang/Standard-ML/Pseudo-random-numbers-Splitmix64 @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-Splitmix64/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/URL-encoding b/Lang/Standard-ML/URL-encoding new file mode 120000 index 0000000000..f4e1b1b4e1 --- /dev/null +++ b/Lang/Standard-ML/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/Standard-ML \ No newline at end of file diff --git a/Lang/Stax/00-LANG.txt b/Lang/Stax/00-LANG.txt index daeb2cc2d2..9436dc0940 100644 --- a/Lang/Stax/00-LANG.txt +++ b/Lang/Stax/00-LANG.txt @@ -1 +1,2 @@ -{{stub}}{{language|Stax}} \ No newline at end of file +[https://github.com/tomtheisen/stax Github] +{{language|site=https://staxlang.xyz/}} \ No newline at end of file diff --git a/Lang/SuperCollider/00-LANG.txt b/Lang/SuperCollider/00-LANG.txt index f804a4a144..d6b538fcd2 100644 --- a/Lang/SuperCollider/00-LANG.txt +++ b/Lang/SuperCollider/00-LANG.txt @@ -9,4 +9,130 @@ The programming language was originally devised by James McCartney and has been [https://github.com/supercollider/supercollider SuperCollider at GitHub] -[http://supercollider.github.io/ SuperCollider Homepage] \ No newline at end of file +[http://supercollider.github.io/ SuperCollider Homepage] + + +

    +Some additional notes on SuperCollider 2024-06-21 + +From the SuperCollider GitHub website: https://supercollider.github.io/ :
    +Quote:
    +A PLATFORM FOR AUDIO SYNTHESIS AND ALGORITHMIC COMPOSITION,
    +      USED BY MUSICIANS, ARTISTS AND RESEARCHERS WORKING WITH SOUND. +

    +FREE AND OPEN SOURCE SOFTWARE FOR WINDOWS, MACOS AND LINUX. +

    +SuperCollider features three major components:
    +scsynth – A real-time audio server
    +sclang – An interpreted programming language
    +scide – An editor for sclang with an integrated help system
    +End-Quote.
    +
    +Some people try to squeeze a musical composition into 140 characters: (but just for the challenge):
    +Don't judge SuperCollider or the language by these examples, they are just for fun.
    + +f={|t|Pbind(\note,Pseq([-1,1,6,8,9,1,-1,8,6,1,9,8]+5,319),\dur,t)};Ptpar([0,f.(1/6),12,f.(0.1672)],1).play + +Listen to the results here: https://supercollider.github.io/assets/audio/sc-140/06_batuhanbozkurt_celesteh.mp3
    +You can see/hear more at: https://supercollider.github.io/sc-140.html
    +
    +
    +As of today (2024-06-21) the current version of SuperCollider for all supported platforms is: 3.13.0 +

    +While SClang (SuperCollider language) and its companion components are designed for the creation of sounds and music, the language is a full featured programming language. +

    +The language is OO, to the extent that everything is an object, even numbers.
    +In this snippet: 123 + 456 the 123 is an object, + is a method on the class of that object, and 456 is a parameter to that method.
    +Even though + is a method the syntax of the addition is what you would typically expect. +

    +The print function in SClang is a method called postln, which first appears in the root of the class tree: Object.
    +
    +Some examples, showing two possible call formats: + +postln("Hello World"); // prints: Hello World +"Hello World".postln; // prints: Hello World +postln(1001); // prints: 1001 +1001.postln; // prints: 1001 +postln(123 + 456); // prints: 579 +(123 + 456).postln; // prints: 579 + + +The method postln, adds a new-line after printing the text, if you don't want the new-line, use: post. +

    + +SuperCollider from the command line (not used much) + +SuperCollider scripts are stored in files with an extension of .scd. +These are typically referred to as supercollider documents, hence .scd. +

    +99.99% of the time, you will execute code from within the IDE (scide).
    +
    +It is possible but not typical, to run a script from the command line, for example:
    + > sclang.exe ABC_problem.scd
    +This will output the expected results. +See code at: https://rosettacode.org/wiki/ABC_problem#SuperCollider

    +However, before executing your code, sclang will compile its class library, and you will see all of the messages about the compilation, before you see the output from your code. +

    +Also, once your code is finished, you will be stuck as sclang is still waiting for more input from a file, not the keyboard. The second problem can be solved by adding exit(0); to the end of your script (.scd file); +

    +SuperCollider comes packaged with QT, and has classes that represent GUI objects, for example:
    + > sclang.exe Barnsley_fern.scd
    +Will open a window and draw the Barnsley Fern.
    +See code at: https://rosettacode.org/wiki/Barnsley_fern#SuperCollider
    +You will have to use Ctrl-c to kill the sclang process, you cannot add exit(0) to you script as the exit would happen before the GUI was fully created. +

    +It is theoretically possible to create a thread within your script which waits until all work is done and then for it to execute exit(0); but you are just giving yourself extra work. +

    +You can also run sclang without giving it a file, then it will accept input from the keyboard. + > sclang.exe
    +You will get this prompt sc3> now you can type in ONE LINE OF CODE. +For example, the following line of code has three statements, the end result is printing the sum of the two numbers:
    +sc3> var v1=123; var v2=456; postf("v1+v2=%\n", v1+v2);
    +v1+v2=579
    +-> v1+v2=579
    +
    +The line with the arrow: -> v1+v2=579, is sclang printing the value of the last expression executed +

    +Summary: You can start sclang from the command line and type in some code, or you could give sclang a script to run, both will work, but it is much more productive to use scide. +Using sclang from the command line is like playing your guitar with winter gloves on, you could do it, but why make life difficult? +

    +If you have composed (written code for) a long piece of music, and now you want to execute the code from the command line, yes, you can do it, but it isn't going to sound any different than it would if you execute the code from within scide.

    +Also, scide offers the ability to 'live code', i.e. execute some code to make some music, and change the code as the music is playing, so the music evolves as you change the code. +

    + +SuperCollider from the IDE
    +Start scide, or 'open' a SuperCollider Document (*.scd), if scide is 'associated' with that file type.
    +See: https://doc.sccode.org/Guides/SCIde.html
    +After you start scide, it starts sclang, which compiles the SuperCollider classes.
    +Now you can start coding.
    +
    +How to execute code (borrowed from the page at the URL above)
    +
    +To evaluate code, use one of the following keyboard commands:
    +Ctrl+Return
    +Most used, "smart" code evaluation:
    +Normally, the current line will be evaluated (where the cursor is).
    +If the cursor is within a region, the entire region will be evaluated. See below for explanation of regions.
    +If some code is selected, the selection will be evaluated.
    +
    +Shift+Return +

    +Evaluates either the current line, or the selection (if any). Use this to evaluate a single line within a region without the need to select it.
    +Regions make it quick and easy to evaluate larger portions of code. A region is surrounded by parentheses; to be interpreted as a region, the parenthesis must each be the only character on a line.
    + +( +Pbind( + \degree, Pseries(0, 1, 8), + \dur, 0.25 +).play; +) + +If the cursor is anywhere between the outermost parentheses, pressing Ctrl+Return will automatically evaluate the entire contents within the parentheses, starting with Pbind and ending with play;.
    +

    +To quickly evaluate a portion of code, you can also double-click on any bracket (round, squared, or curly), which will select everything between this and the other matching bracket, so you can quickly evaluate it. +

    +To stop any running code, use the Ctrl+. shortcut (Ctrl+Period).
    +This will stop all the code scheduled on the clocks, as well as all the sound processes on the audio server. +

    + +... more coming soon ... \ No newline at end of file diff --git a/Lang/SuperCollider/Averages-Pythagorean-means b/Lang/SuperCollider/Averages-Pythagorean-means new file mode 120000 index 0000000000..9ee9ff6fef --- /dev/null +++ b/Lang/SuperCollider/Averages-Pythagorean-means @@ -0,0 +1 @@ +../../Task/Averages-Pythagorean-means/SuperCollider \ No newline at end of file diff --git a/Lang/SuperCollider/Catalan-numbers b/Lang/SuperCollider/Catalan-numbers new file mode 120000 index 0000000000..3ee9240cf0 --- /dev/null +++ b/Lang/SuperCollider/Catalan-numbers @@ -0,0 +1 @@ +../../Task/Catalan-numbers/SuperCollider \ No newline at end of file diff --git a/Lang/SuperCollider/Golden-ratio-Convergence b/Lang/SuperCollider/Golden-ratio-Convergence new file mode 120000 index 0000000000..77807cac46 --- /dev/null +++ b/Lang/SuperCollider/Golden-ratio-Convergence @@ -0,0 +1 @@ +../../Task/Golden-ratio-Convergence/SuperCollider \ No newline at end of file diff --git a/Lang/SuperCollider/Iterated-digits-squaring b/Lang/SuperCollider/Iterated-digits-squaring new file mode 120000 index 0000000000..197266fc01 --- /dev/null +++ b/Lang/SuperCollider/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/SuperCollider \ No newline at end of file diff --git a/Lang/SuperCollider/Multiplication-tables b/Lang/SuperCollider/Multiplication-tables new file mode 120000 index 0000000000..f5418ea2b2 --- /dev/null +++ b/Lang/SuperCollider/Multiplication-tables @@ -0,0 +1 @@ +../../Task/Multiplication-tables/SuperCollider \ No newline at end of file diff --git a/Lang/SuperCollider/Semordnilap b/Lang/SuperCollider/Semordnilap deleted file mode 120000 index ace051dba8..0000000000 --- a/Lang/SuperCollider/Semordnilap +++ /dev/null @@ -1 +0,0 @@ -../../Task/Semordnilap/SuperCollider \ No newline at end of file diff --git a/Lang/SuperCollider/Vampire-number b/Lang/SuperCollider/Vampire-number new file mode 120000 index 0000000000..96124ca653 --- /dev/null +++ b/Lang/SuperCollider/Vampire-number @@ -0,0 +1 @@ +../../Task/Vampire-number/SuperCollider \ No newline at end of file diff --git a/Lang/Swift/AVL-tree b/Lang/Swift/AVL-tree new file mode 120000 index 0000000000..ff46aae38e --- /dev/null +++ b/Lang/Swift/AVL-tree @@ -0,0 +1 @@ +../../Task/AVL-tree/Swift \ No newline at end of file diff --git a/Lang/Swift/Bioinformatics-base-count b/Lang/Swift/Bioinformatics-base-count deleted file mode 120000 index c497b7a9fe..0000000000 --- a/Lang/Swift/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Swift \ No newline at end of file diff --git a/Lang/Swift/Boyer-Moore-string-search b/Lang/Swift/Boyer-Moore-string-search new file mode 120000 index 0000000000..d0d21c21e5 --- /dev/null +++ b/Lang/Swift/Boyer-Moore-string-search @@ -0,0 +1 @@ +../../Task/Boyer-Moore-string-search/Swift \ No newline at end of file diff --git a/Lang/Swift/Chaocipher b/Lang/Swift/Chaocipher new file mode 120000 index 0000000000..6e9ab31392 --- /dev/null +++ b/Lang/Swift/Chaocipher @@ -0,0 +1 @@ +../../Task/Chaocipher/Swift \ No newline at end of file diff --git a/Lang/Swift/Compare-length-of-two-strings b/Lang/Swift/Compare-length-of-two-strings new file mode 120000 index 0000000000..d53f307b7e --- /dev/null +++ b/Lang/Swift/Compare-length-of-two-strings @@ -0,0 +1 @@ +../../Task/Compare-length-of-two-strings/Swift \ No newline at end of file diff --git a/Lang/Swift/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- b/Lang/Swift/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- new file mode 120000 index 0000000000..bfa2341e33 --- /dev/null +++ b/Lang/Swift/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n-/Swift \ No newline at end of file diff --git a/Lang/Swift/De-Bruijn-sequences b/Lang/Swift/De-Bruijn-sequences new file mode 120000 index 0000000000..0fbdf1e9f8 --- /dev/null +++ b/Lang/Swift/De-Bruijn-sequences @@ -0,0 +1 @@ +../../Task/De-Bruijn-sequences/Swift \ No newline at end of file diff --git a/Lang/Swift/Empty-program b/Lang/Swift/Empty-program deleted file mode 120000 index 2c1baaa481..0000000000 --- a/Lang/Swift/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Swift \ No newline at end of file diff --git a/Lang/Swift/Floyd-Warshall-algorithm b/Lang/Swift/Floyd-Warshall-algorithm new file mode 120000 index 0000000000..d1366dce22 --- /dev/null +++ b/Lang/Swift/Floyd-Warshall-algorithm @@ -0,0 +1 @@ +../../Task/Floyd-Warshall-algorithm/Swift \ No newline at end of file diff --git a/Lang/Swift/K-d-tree b/Lang/Swift/K-d-tree new file mode 120000 index 0000000000..a4758e806b --- /dev/null +++ b/Lang/Swift/K-d-tree @@ -0,0 +1 @@ +../../Task/K-d-tree/Swift \ No newline at end of file diff --git a/Lang/Swift/M-bius-function b/Lang/Swift/M-bius-function new file mode 120000 index 0000000000..cd32d72e63 --- /dev/null +++ b/Lang/Swift/M-bius-function @@ -0,0 +1 @@ +../../Task/M-bius-function/Swift \ No newline at end of file diff --git a/Lang/Swift/Miller-Rabin-primality-test b/Lang/Swift/Miller-Rabin-primality-test deleted file mode 120000 index 08a41b9961..0000000000 --- a/Lang/Swift/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Swift \ No newline at end of file diff --git a/Lang/Swift/Parse-an-IP-Address b/Lang/Swift/Parse-an-IP-Address new file mode 120000 index 0000000000..b157f3f9a2 --- /dev/null +++ b/Lang/Swift/Parse-an-IP-Address @@ -0,0 +1 @@ +../../Task/Parse-an-IP-Address/Swift \ No newline at end of file diff --git a/Lang/Swift/Pseudo-random-numbers-Splitmix64 b/Lang/Swift/Pseudo-random-numbers-Splitmix64 new file mode 120000 index 0000000000..7f3d66c35a --- /dev/null +++ b/Lang/Swift/Pseudo-random-numbers-Splitmix64 @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-Splitmix64/Swift \ No newline at end of file diff --git a/Lang/Swift/Quaternion-type b/Lang/Swift/Quaternion-type deleted file mode 120000 index d74f88c4be..0000000000 --- a/Lang/Swift/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Swift \ No newline at end of file diff --git a/Lang/Swift/Sorting-Algorithms-Circle-Sort b/Lang/Swift/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 367310fdad..0000000000 --- a/Lang/Swift/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Swift \ No newline at end of file diff --git a/Lang/Swift/Tonelli-Shanks-algorithm b/Lang/Swift/Tonelli-Shanks-algorithm new file mode 120000 index 0000000000..9e28b1de2a --- /dev/null +++ b/Lang/Swift/Tonelli-Shanks-algorithm @@ -0,0 +1 @@ +../../Task/Tonelli-Shanks-algorithm/Swift \ No newline at end of file diff --git a/Lang/Symsyn/Empty-program b/Lang/Symsyn/Empty-program deleted file mode 120000 index 73cbdf1eb6..0000000000 --- a/Lang/Symsyn/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Symsyn \ No newline at end of file diff --git a/Lang/TAV/00-LANG.txt b/Lang/TAV/00-LANG.txt new file mode 100644 index 0000000000..bb9d8890a2 --- /dev/null +++ b/Lang/TAV/00-LANG.txt @@ -0,0 +1,46 @@ +{{language|TAV +|site=https://tavpl.de +|untyped=yes +|exec=machine +|gc=no +|parampass=reference +|checking=dynamic +|safety=safe +}} +{{language programming paradigm|Procedural}} +{{CompileOnline}} + +'''TAV''' is the '''terse and verbose''' +language that borrows from [[Python]], Stage2, [[Genie]] and more. + +Its most outstanding feature is the use of templates for function calls instead of the +traditional function_name(parameter, parameter, ...) form. +Matched parenthesis are consequently rarely necessary. + +Summary of important points: + +* C precompiler, should work on any system with a reasonable C compiler +* Block structuring by indentation, like in Python; line oriented +* No keywords in the core language, only symbols (i.e. bigraphs) +* Variables are of any kind (type) dynamically; no declarations necessary +* Function definition and calls by word sequences with interspersed parameters, often no parenthesis needed +* Maps (dictionaries) with all kinds of keys (except floating-point numbers) +* Rows (arrays) if the keys are dense integers, dynamically expanding +* Arbitrary precision integer numbers +* Dynamic Unicode strings +* Fields for extra data in rows and maps +* Attributes for information about an item +* Fault items for reliable error handling +* Reference counting avoids unsolicited delays for garbage-collection +* Basic support for object-oriented programming (no inheritance) +* Discretionary type system specified, but not yet tested +* Publication syntax with common English keywords instead of symbols +* Bindings to SDL, Cairo and GTK (proof-of-concept level) + +Many examples can be run via copy and paste in the Playground. + +Because there are no keywords and rarely nested parenthesis (of any kind), +syntax highlighting is not used. + +==Links== +*[[https://tavpl.de/TAV-Online TAV Online Playground]] \ No newline at end of file diff --git a/Lang/TAV/00-META.yaml b/Lang/TAV/00-META.yaml new file mode 100644 index 0000000000..94650f22a2 --- /dev/null +++ b/Lang/TAV/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:TAV diff --git a/Lang/TAV/A+B b/Lang/TAV/A+B new file mode 120000 index 0000000000..a5e97665e3 --- /dev/null +++ b/Lang/TAV/A+B @@ -0,0 +1 @@ +../../Task/A+B/TAV \ No newline at end of file diff --git a/Lang/TAV/Ackermann-function b/Lang/TAV/Ackermann-function new file mode 120000 index 0000000000..237de07217 --- /dev/null +++ b/Lang/TAV/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/TAV \ No newline at end of file diff --git a/Lang/TAV/Anagrams b/Lang/TAV/Anagrams new file mode 120000 index 0000000000..335a62bd1c --- /dev/null +++ b/Lang/TAV/Anagrams @@ -0,0 +1 @@ +../../Task/Anagrams/TAV \ No newline at end of file diff --git a/Lang/TAV/Arithmetic-Integer b/Lang/TAV/Arithmetic-Integer new file mode 120000 index 0000000000..b9d994e37f --- /dev/null +++ b/Lang/TAV/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/TAV \ No newline at end of file diff --git a/Lang/TAV/Array-concatenation b/Lang/TAV/Array-concatenation new file mode 120000 index 0000000000..a1b0d9260d --- /dev/null +++ b/Lang/TAV/Array-concatenation @@ -0,0 +1 @@ +../../Task/Array-concatenation/TAV \ No newline at end of file diff --git a/Lang/TAV/Array-length b/Lang/TAV/Array-length new file mode 120000 index 0000000000..0d849f41e8 --- /dev/null +++ b/Lang/TAV/Array-length @@ -0,0 +1 @@ +../../Task/Array-length/TAV \ No newline at end of file diff --git a/Lang/TAV/Ascending-primes b/Lang/TAV/Ascending-primes new file mode 120000 index 0000000000..b4add5cfb9 --- /dev/null +++ b/Lang/TAV/Ascending-primes @@ -0,0 +1 @@ +../../Task/Ascending-primes/TAV \ No newline at end of file diff --git a/Lang/TAV/Associative-array-Iteration b/Lang/TAV/Associative-array-Iteration new file mode 120000 index 0000000000..48bdb805ad --- /dev/null +++ b/Lang/TAV/Associative-array-Iteration @@ -0,0 +1 @@ +../../Task/Associative-array-Iteration/TAV \ No newline at end of file diff --git a/Lang/TAV/Averages-Root-mean-square b/Lang/TAV/Averages-Root-mean-square new file mode 120000 index 0000000000..75f73fbdb8 --- /dev/null +++ b/Lang/TAV/Averages-Root-mean-square @@ -0,0 +1 @@ +../../Task/Averages-Root-mean-square/TAV \ No newline at end of file diff --git a/Lang/TAV/Babbage-problem b/Lang/TAV/Babbage-problem new file mode 120000 index 0000000000..141507242e --- /dev/null +++ b/Lang/TAV/Babbage-problem @@ -0,0 +1 @@ +../../Task/Babbage-problem/TAV \ No newline at end of file diff --git a/Lang/TAV/Bernoulli-numbers b/Lang/TAV/Bernoulli-numbers new file mode 120000 index 0000000000..164f4e8e6c --- /dev/null +++ b/Lang/TAV/Bernoulli-numbers @@ -0,0 +1 @@ +../../Task/Bernoulli-numbers/TAV \ No newline at end of file diff --git a/Lang/TAV/Character-codes b/Lang/TAV/Character-codes new file mode 120000 index 0000000000..46e37f6e83 --- /dev/null +++ b/Lang/TAV/Character-codes @@ -0,0 +1 @@ +../../Task/Character-codes/TAV \ No newline at end of file diff --git a/Lang/TAV/Command-line-arguments b/Lang/TAV/Command-line-arguments new file mode 120000 index 0000000000..72fc191937 --- /dev/null +++ b/Lang/TAV/Command-line-arguments @@ -0,0 +1 @@ +../../Task/Command-line-arguments/TAV \ No newline at end of file diff --git a/Lang/TAV/Conditional-structures b/Lang/TAV/Conditional-structures new file mode 120000 index 0000000000..bf797da6e6 --- /dev/null +++ b/Lang/TAV/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/TAV \ No newline at end of file diff --git a/Lang/TAV/Convert-decimal-number-to-rational b/Lang/TAV/Convert-decimal-number-to-rational new file mode 120000 index 0000000000..c7b635149b --- /dev/null +++ b/Lang/TAV/Convert-decimal-number-to-rational @@ -0,0 +1 @@ +../../Task/Convert-decimal-number-to-rational/TAV \ No newline at end of file diff --git a/Lang/TAV/Copy-a-string b/Lang/TAV/Copy-a-string new file mode 120000 index 0000000000..3ca111af72 --- /dev/null +++ b/Lang/TAV/Copy-a-string @@ -0,0 +1 @@ +../../Task/Copy-a-string/TAV \ No newline at end of file diff --git a/Lang/TAV/Create-a-two-dimensional-array-at-runtime b/Lang/TAV/Create-a-two-dimensional-array-at-runtime new file mode 120000 index 0000000000..ec0fae01dd --- /dev/null +++ b/Lang/TAV/Create-a-two-dimensional-array-at-runtime @@ -0,0 +1 @@ +../../Task/Create-a-two-dimensional-array-at-runtime/TAV \ No newline at end of file diff --git a/Lang/TAV/Empty-string b/Lang/TAV/Empty-string new file mode 120000 index 0000000000..c001916e31 --- /dev/null +++ b/Lang/TAV/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/TAV \ No newline at end of file diff --git a/Lang/TAV/Factorial b/Lang/TAV/Factorial new file mode 120000 index 0000000000..005136367e --- /dev/null +++ b/Lang/TAV/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/TAV \ No newline at end of file diff --git a/Lang/TAV/Fibonacci-sequence b/Lang/TAV/Fibonacci-sequence new file mode 120000 index 0000000000..e65f13e72b --- /dev/null +++ b/Lang/TAV/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/TAV \ No newline at end of file diff --git a/Lang/TAV/Formatted-numeric-output b/Lang/TAV/Formatted-numeric-output new file mode 120000 index 0000000000..efbc60523a --- /dev/null +++ b/Lang/TAV/Formatted-numeric-output @@ -0,0 +1 @@ +../../Task/Formatted-numeric-output/TAV \ No newline at end of file diff --git a/Lang/TAV/Greatest-element-of-a-list b/Lang/TAV/Greatest-element-of-a-list new file mode 120000 index 0000000000..b4f81674a0 --- /dev/null +++ b/Lang/TAV/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/TAV \ No newline at end of file diff --git a/Lang/TAV/Guess-the-number-With-feedback b/Lang/TAV/Guess-the-number-With-feedback new file mode 120000 index 0000000000..5779e4d532 --- /dev/null +++ b/Lang/TAV/Guess-the-number-With-feedback @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback/TAV \ No newline at end of file diff --git a/Lang/TAV/HTTPS b/Lang/TAV/HTTPS new file mode 120000 index 0000000000..3b5c7b8988 --- /dev/null +++ b/Lang/TAV/HTTPS @@ -0,0 +1 @@ +../../Task/HTTPS/TAV \ No newline at end of file diff --git a/Lang/TAV/Halt-and-catch-fire b/Lang/TAV/Halt-and-catch-fire new file mode 120000 index 0000000000..802c4aa7b1 --- /dev/null +++ b/Lang/TAV/Halt-and-catch-fire @@ -0,0 +1 @@ +../../Task/Halt-and-catch-fire/TAV \ No newline at end of file diff --git a/Lang/TAV/Hello-world-Graphical b/Lang/TAV/Hello-world-Graphical new file mode 120000 index 0000000000..5207716bc0 --- /dev/null +++ b/Lang/TAV/Hello-world-Graphical @@ -0,0 +1 @@ +../../Task/Hello-world-Graphical/TAV \ No newline at end of file diff --git a/Lang/TAV/Hello-world-Text b/Lang/TAV/Hello-world-Text new file mode 120000 index 0000000000..3fd6788564 --- /dev/null +++ b/Lang/TAV/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/TAV \ No newline at end of file diff --git a/Lang/TAV/Letter-frequency b/Lang/TAV/Letter-frequency new file mode 120000 index 0000000000..891b699844 --- /dev/null +++ b/Lang/TAV/Letter-frequency @@ -0,0 +1 @@ +../../Task/Letter-frequency/TAV \ No newline at end of file diff --git a/Lang/TAV/Loop-over-multiple-arrays-simultaneously b/Lang/TAV/Loop-over-multiple-arrays-simultaneously new file mode 120000 index 0000000000..b6133fd1e3 --- /dev/null +++ b/Lang/TAV/Loop-over-multiple-arrays-simultaneously @@ -0,0 +1 @@ +../../Task/Loop-over-multiple-arrays-simultaneously/TAV \ No newline at end of file diff --git a/Lang/TAV/Loops-Break b/Lang/TAV/Loops-Break new file mode 120000 index 0000000000..9576a14c29 --- /dev/null +++ b/Lang/TAV/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/TAV \ No newline at end of file diff --git a/Lang/TAV/Loops-Do-while b/Lang/TAV/Loops-Do-while new file mode 120000 index 0000000000..1fc4e33872 --- /dev/null +++ b/Lang/TAV/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/TAV \ No newline at end of file diff --git a/Lang/TAV/Loops-Downward-for b/Lang/TAV/Loops-Downward-for new file mode 120000 index 0000000000..414c0842ce --- /dev/null +++ b/Lang/TAV/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/TAV \ No newline at end of file diff --git a/Lang/TAV/Loops-For b/Lang/TAV/Loops-For new file mode 120000 index 0000000000..b5f2be83c7 --- /dev/null +++ b/Lang/TAV/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/TAV \ No newline at end of file diff --git a/Lang/TAV/Loops-Infinite b/Lang/TAV/Loops-Infinite new file mode 120000 index 0000000000..6ab04989e3 --- /dev/null +++ b/Lang/TAV/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/TAV \ No newline at end of file diff --git a/Lang/TAV/Loops-N-plus-one-half b/Lang/TAV/Loops-N-plus-one-half new file mode 120000 index 0000000000..eaeea87dec --- /dev/null +++ b/Lang/TAV/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/TAV \ No newline at end of file diff --git a/Lang/TAV/Loops-While b/Lang/TAV/Loops-While new file mode 120000 index 0000000000..b408169718 --- /dev/null +++ b/Lang/TAV/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/TAV \ No newline at end of file diff --git a/Lang/TAV/Multiplication-tables b/Lang/TAV/Multiplication-tables new file mode 120000 index 0000000000..294070cfc4 --- /dev/null +++ b/Lang/TAV/Multiplication-tables @@ -0,0 +1 @@ +../../Task/Multiplication-tables/TAV \ No newline at end of file diff --git a/Lang/TAV/Ordered-words b/Lang/TAV/Ordered-words new file mode 120000 index 0000000000..1dd34f0734 --- /dev/null +++ b/Lang/TAV/Ordered-words @@ -0,0 +1 @@ +../../Task/Ordered-words/TAV \ No newline at end of file diff --git a/Lang/TAV/Permutations b/Lang/TAV/Permutations new file mode 120000 index 0000000000..c61f5ead43 --- /dev/null +++ b/Lang/TAV/Permutations @@ -0,0 +1 @@ +../../Task/Permutations/TAV \ No newline at end of file diff --git a/Lang/TAV/Real-constants-and-functions b/Lang/TAV/Real-constants-and-functions new file mode 120000 index 0000000000..074b803009 --- /dev/null +++ b/Lang/TAV/Real-constants-and-functions @@ -0,0 +1 @@ +../../Task/Real-constants-and-functions/TAV \ No newline at end of file diff --git a/Lang/TAV/Reverse-a-string b/Lang/TAV/Reverse-a-string new file mode 120000 index 0000000000..ded0969ffb --- /dev/null +++ b/Lang/TAV/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/TAV \ No newline at end of file diff --git a/Lang/TAV/Semordnilap b/Lang/TAV/Semordnilap new file mode 120000 index 0000000000..2269a5f472 --- /dev/null +++ b/Lang/TAV/Semordnilap @@ -0,0 +1 @@ +../../Task/Semordnilap/TAV \ No newline at end of file diff --git a/Lang/TAV/Show-ASCII-table b/Lang/TAV/Show-ASCII-table new file mode 120000 index 0000000000..f220b6d5c2 --- /dev/null +++ b/Lang/TAV/Show-ASCII-table @@ -0,0 +1 @@ +../../Task/Show-ASCII-table/TAV \ No newline at end of file diff --git a/Lang/TAV/Simple-windowed-application b/Lang/TAV/Simple-windowed-application new file mode 120000 index 0000000000..16b1926606 --- /dev/null +++ b/Lang/TAV/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/TAV \ No newline at end of file diff --git a/Lang/TAV/Stack b/Lang/TAV/Stack new file mode 120000 index 0000000000..a05bead248 --- /dev/null +++ b/Lang/TAV/Stack @@ -0,0 +1 @@ +../../Task/Stack/TAV \ No newline at end of file diff --git a/Lang/TAV/String-length b/Lang/TAV/String-length new file mode 120000 index 0000000000..6374cb4fac --- /dev/null +++ b/Lang/TAV/String-length @@ -0,0 +1 @@ +../../Task/String-length/TAV \ No newline at end of file diff --git a/Lang/TAV/Sudoku b/Lang/TAV/Sudoku new file mode 120000 index 0000000000..c7ddc3598c --- /dev/null +++ b/Lang/TAV/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/TAV \ No newline at end of file diff --git a/Lang/TAV/Tic-tac-toe b/Lang/TAV/Tic-tac-toe new file mode 120000 index 0000000000..c75d3a40ab --- /dev/null +++ b/Lang/TAV/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/TAV \ No newline at end of file diff --git a/Lang/TAV/Tokenize-a-string b/Lang/TAV/Tokenize-a-string new file mode 120000 index 0000000000..8b4118dfbe --- /dev/null +++ b/Lang/TAV/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/TAV \ No newline at end of file diff --git a/Lang/TAV/Twelve-statements b/Lang/TAV/Twelve-statements new file mode 120000 index 0000000000..0036358c10 --- /dev/null +++ b/Lang/TAV/Twelve-statements @@ -0,0 +1 @@ +../../Task/Twelve-statements/TAV \ No newline at end of file diff --git a/Lang/TAV/Window-creation b/Lang/TAV/Window-creation new file mode 120000 index 0000000000..83a0431016 --- /dev/null +++ b/Lang/TAV/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/TAV \ No newline at end of file diff --git a/Lang/TAV/Word-frequency b/Lang/TAV/Word-frequency new file mode 120000 index 0000000000..569f86daf5 --- /dev/null +++ b/Lang/TAV/Word-frequency @@ -0,0 +1 @@ +../../Task/Word-frequency/TAV \ No newline at end of file diff --git a/Lang/TI-83-BASIC/00-LANG.txt b/Lang/TI-83-BASIC/00-LANG.txt index 571b0d2a73..a8830c103d 100644 --- a/Lang/TI-83-BASIC/00-LANG.txt +++ b/Lang/TI-83-BASIC/00-LANG.txt @@ -8,24 +8,24 @@ The language contains control flow for structured programming. The main control flow statements are: ====If==== -If condition +If condition Then ... Else ... -End +End ====For==== -For(variable,start,stop,step) +For(variable,start,stop,step) ... -End +End ====While==== -While condition +While condition ... -End +End ====Repeat==== -Repeat condition +Repeat condition ... -End +End ===Data types=== '''TI-BASIC''' is a strongly and dynamically-typed language Variables are global. There is no local variables. So programs cannot be recursive, even if a program can call itself. @@ -37,11 +37,11 @@ Variables are global. There is no local variables. So programs cannot be recursi ==Example== One popular example is the quadratic formula program. -Prompt A,B,C +Prompt A,B,C B²-4AC->D (-B-sqrt(D))/(2A)->Y (-B+sqrt(D))/(2A)->X -{Y,X} +{Y,X} As far there is a complex mode and variable can be real or complex, this program is very ubiquitous. diff --git a/Lang/TXR/Cheryls-birthday b/Lang/TXR/Cheryls-birthday new file mode 120000 index 0000000000..3755473e4e --- /dev/null +++ b/Lang/TXR/Cheryls-birthday @@ -0,0 +1 @@ +../../Task/Cheryls-birthday/TXR \ No newline at end of file diff --git a/Lang/Tailspin/00-LANG.txt b/Lang/Tailspin/00-LANG.txt index a8437326e6..02c82847dd 100644 --- a/Lang/Tailspin/00-LANG.txt +++ b/Lang/Tailspin/00-LANG.txt @@ -18,4 +18,6 @@ The inspiration comes mostly from xslt, but data structures are json-like. The m [https://github.com/tobega/tailspin-v0/blob/master/TailspinReference.md Syntax reference] -Development page, also how to run Tailspin programs [https://github.com/tobega/tailspin-v0 on github] \ No newline at end of file +Development page, also how to run Tailspin programs [https://github.com/tobega/tailspin-v0 on github] + +Next version v0.5 [https://github.com/tobega/tailspin-v0.5 under development] \ No newline at end of file diff --git a/Lang/Tailspin/Combinations b/Lang/Tailspin/Combinations new file mode 120000 index 0000000000..987b496fbb --- /dev/null +++ b/Lang/Tailspin/Combinations @@ -0,0 +1 @@ +../../Task/Combinations/Tailspin \ No newline at end of file diff --git a/Lang/Tailspin/Sierpinski-triangle b/Lang/Tailspin/Sierpinski-triangle new file mode 120000 index 0000000000..b603b111a2 --- /dev/null +++ b/Lang/Tailspin/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/Tailspin \ No newline at end of file diff --git a/Lang/Tcl/Ascending-primes b/Lang/Tcl/Ascending-primes new file mode 120000 index 0000000000..aad1d565ea --- /dev/null +++ b/Lang/Tcl/Ascending-primes @@ -0,0 +1 @@ +../../Task/Ascending-primes/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Bioinformatics-base-count b/Lang/Tcl/Bioinformatics-base-count deleted file mode 120000 index 2d2ea8e987..0000000000 --- a/Lang/Tcl/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Chaocipher b/Lang/Tcl/Chaocipher new file mode 120000 index 0000000000..8d836b3e4a --- /dev/null +++ b/Lang/Tcl/Chaocipher @@ -0,0 +1 @@ +../../Task/Chaocipher/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Character-codes b/Lang/Tcl/Character-codes deleted file mode 120000 index 3f7702eaa9..0000000000 --- a/Lang/Tcl/Character-codes +++ /dev/null @@ -1 +0,0 @@ -../../Task/Character-codes/Tcl \ No newline at end of file diff --git a/Lang/Tcl/De-Bruijn-sequences b/Lang/Tcl/De-Bruijn-sequences new file mode 120000 index 0000000000..b3e1240d2e --- /dev/null +++ b/Lang/Tcl/De-Bruijn-sequences @@ -0,0 +1 @@ +../../Task/De-Bruijn-sequences/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Descending-primes b/Lang/Tcl/Descending-primes new file mode 120000 index 0000000000..11b4ea6aa0 --- /dev/null +++ b/Lang/Tcl/Descending-primes @@ -0,0 +1 @@ +../../Task/Descending-primes/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Find-if-a-point-is-within-a-triangle b/Lang/Tcl/Find-if-a-point-is-within-a-triangle new file mode 120000 index 0000000000..340eb44d03 --- /dev/null +++ b/Lang/Tcl/Find-if-a-point-is-within-a-triangle @@ -0,0 +1 @@ +../../Task/Find-if-a-point-is-within-a-triangle/Tcl \ No newline at end of file diff --git a/Lang/Tcl/M-bius-function b/Lang/Tcl/M-bius-function new file mode 120000 index 0000000000..1c7ccdef59 --- /dev/null +++ b/Lang/Tcl/M-bius-function @@ -0,0 +1 @@ +../../Task/M-bius-function/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Miller-Rabin-primality-test b/Lang/Tcl/Miller-Rabin-primality-test deleted file mode 120000 index 5e3095425f..0000000000 --- a/Lang/Tcl/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Quaternion-type b/Lang/Tcl/Quaternion-type deleted file mode 120000 index 50905d75b8..0000000000 --- a/Lang/Tcl/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Strassens-algorithm b/Lang/Tcl/Strassens-algorithm new file mode 120000 index 0000000000..8ac35c1ae0 --- /dev/null +++ b/Lang/Tcl/Strassens-algorithm @@ -0,0 +1 @@ +../../Task/Strassens-algorithm/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Unicode-strings b/Lang/Tcl/Unicode-strings new file mode 120000 index 0000000000..5d3bbc0431 --- /dev/null +++ b/Lang/Tcl/Unicode-strings @@ -0,0 +1 @@ +../../Task/Unicode-strings/Tcl \ No newline at end of file diff --git a/Lang/Tiny-BASIC/Leonardo-numbers b/Lang/Tiny-BASIC/Leonardo-numbers new file mode 120000 index 0000000000..731e542c2f --- /dev/null +++ b/Lang/Tiny-BASIC/Leonardo-numbers @@ -0,0 +1 @@ +../../Task/Leonardo-numbers/Tiny-BASIC \ No newline at end of file diff --git a/Lang/Tiny-BASIC/Magic-constant b/Lang/Tiny-BASIC/Magic-constant new file mode 120000 index 0000000000..e64a075712 --- /dev/null +++ b/Lang/Tiny-BASIC/Magic-constant @@ -0,0 +1 @@ +../../Task/Magic-constant/Tiny-BASIC \ No newline at end of file diff --git a/Lang/Tiny-BASIC/Mandelbrot-set b/Lang/Tiny-BASIC/Mandelbrot-set new file mode 120000 index 0000000000..9aab104307 --- /dev/null +++ b/Lang/Tiny-BASIC/Mandelbrot-set @@ -0,0 +1 @@ +../../Task/Mandelbrot-set/Tiny-BASIC \ No newline at end of file diff --git a/Lang/Tiny-BASIC/The-Twelve-Days-of-Christmas b/Lang/Tiny-BASIC/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..8dad6cc4e9 --- /dev/null +++ b/Lang/Tiny-BASIC/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/Tiny-BASIC \ No newline at end of file diff --git a/Lang/Transd/Compare-length-of-two-strings b/Lang/Transd/Compare-length-of-two-strings deleted file mode 120000 index 28f3956c3e..0000000000 --- a/Lang/Transd/Compare-length-of-two-strings +++ /dev/null @@ -1 +0,0 @@ -../../Task/Compare-length-of-two-strings/Transd \ No newline at end of file diff --git a/Lang/Trith/Empty-program b/Lang/Trith/Empty-program deleted file mode 120000 index a3056b4a8b..0000000000 --- a/Lang/Trith/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Trith \ No newline at end of file diff --git a/Lang/True-BASIC/00-LANG.txt b/Lang/True-BASIC/00-LANG.txt index 765d6ad0cc..7ebdbc548e 100644 --- a/Lang/True-BASIC/00-LANG.txt +++ b/Lang/True-BASIC/00-LANG.txt @@ -2,6 +2,7 @@ |exec=interpreted |tags=basic,TrueBasic |site=http://www.truebasic.com/}} +{{implementation|BASIC}} True BASIC is a variant of the BASIC programming language descended from Dartmouth BASIC, the original BASIC. It was invented by college professors John G. Kemeny and Thomas E. Kurtz. It is an interpreted, procedural language and sold as a commercial product. Versions have existed for Microsoft Windows, Apple Mac OS, MS-DOS, OS/2, and the Atari ST. The latest version of the language is 6.007 and currently only runs on Microsoft Windows. diff --git a/Lang/True-BASIC/100-prisoners b/Lang/True-BASIC/100-prisoners new file mode 120000 index 0000000000..b793e357f7 --- /dev/null +++ b/Lang/True-BASIC/100-prisoners @@ -0,0 +1 @@ +../../Task/100-prisoners/True-BASIC \ No newline at end of file diff --git a/Lang/True-BASIC/Determine-sentence-type b/Lang/True-BASIC/Determine-sentence-type new file mode 120000 index 0000000000..988197fd95 --- /dev/null +++ b/Lang/True-BASIC/Determine-sentence-type @@ -0,0 +1 @@ +../../Task/Determine-sentence-type/True-BASIC \ No newline at end of file diff --git a/Lang/True-BASIC/Diversity-prediction-theorem b/Lang/True-BASIC/Diversity-prediction-theorem new file mode 120000 index 0000000000..85980181c1 --- /dev/null +++ b/Lang/True-BASIC/Diversity-prediction-theorem @@ -0,0 +1 @@ +../../Task/Diversity-prediction-theorem/True-BASIC \ No newline at end of file diff --git a/Lang/True-BASIC/Evaluate-binomial-coefficients b/Lang/True-BASIC/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..8a2a036883 --- /dev/null +++ b/Lang/True-BASIC/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/True-BASIC \ No newline at end of file diff --git a/Lang/True-BASIC/Greatest-element-of-a-list b/Lang/True-BASIC/Greatest-element-of-a-list new file mode 120000 index 0000000000..3c9a45a72c --- /dev/null +++ b/Lang/True-BASIC/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/True-BASIC \ No newline at end of file diff --git a/Lang/True-BASIC/Leonardo-numbers b/Lang/True-BASIC/Leonardo-numbers new file mode 120000 index 0000000000..7faae2372e --- /dev/null +++ b/Lang/True-BASIC/Leonardo-numbers @@ -0,0 +1 @@ +../../Task/Leonardo-numbers/True-BASIC \ No newline at end of file diff --git a/Lang/True-BASIC/Loop-over-multiple-arrays-simultaneously b/Lang/True-BASIC/Loop-over-multiple-arrays-simultaneously new file mode 120000 index 0000000000..0cb7e37da5 --- /dev/null +++ b/Lang/True-BASIC/Loop-over-multiple-arrays-simultaneously @@ -0,0 +1 @@ +../../Task/Loop-over-multiple-arrays-simultaneously/True-BASIC \ No newline at end of file diff --git a/Lang/True-BASIC/Meissel-Mertens-constant b/Lang/True-BASIC/Meissel-Mertens-constant deleted file mode 120000 index fd72ec2c53..0000000000 --- a/Lang/True-BASIC/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/True-BASIC \ No newline at end of file diff --git a/Lang/True-BASIC/Multiple-regression b/Lang/True-BASIC/Multiple-regression new file mode 120000 index 0000000000..ca0e5c404e --- /dev/null +++ b/Lang/True-BASIC/Multiple-regression @@ -0,0 +1 @@ +../../Task/Multiple-regression/True-BASIC \ No newline at end of file diff --git a/Lang/True-BASIC/Phrase-reversals b/Lang/True-BASIC/Phrase-reversals new file mode 120000 index 0000000000..564680054e --- /dev/null +++ b/Lang/True-BASIC/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/True-BASIC \ No newline at end of file diff --git a/Lang/True-BASIC/Soundex b/Lang/True-BASIC/Soundex new file mode 120000 index 0000000000..33e7fb68ee --- /dev/null +++ b/Lang/True-BASIC/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/True-BASIC \ No newline at end of file diff --git a/Lang/True-BASIC/Split-a-character-string-based-on-change-of-character b/Lang/True-BASIC/Split-a-character-string-based-on-change-of-character new file mode 120000 index 0000000000..e25a5cf6f3 --- /dev/null +++ b/Lang/True-BASIC/Split-a-character-string-based-on-change-of-character @@ -0,0 +1 @@ +../../Task/Split-a-character-string-based-on-change-of-character/True-BASIC \ No newline at end of file diff --git a/Lang/True-BASIC/The-Name-Game b/Lang/True-BASIC/The-Name-Game new file mode 120000 index 0000000000..bf4d14fb81 --- /dev/null +++ b/Lang/True-BASIC/The-Name-Game @@ -0,0 +1 @@ +../../Task/The-Name-Game/True-BASIC \ No newline at end of file diff --git a/Lang/True-BASIC/Vector b/Lang/True-BASIC/Vector new file mode 120000 index 0000000000..4da227d0fe --- /dev/null +++ b/Lang/True-BASIC/Vector @@ -0,0 +1 @@ +../../Task/Vector/True-BASIC \ No newline at end of file diff --git a/Lang/TypeScript/Additive-primes b/Lang/TypeScript/Additive-primes new file mode 120000 index 0000000000..698823ecab --- /dev/null +++ b/Lang/TypeScript/Additive-primes @@ -0,0 +1 @@ +../../Task/Additive-primes/TypeScript \ No newline at end of file diff --git a/Lang/TypeScript/Arithmetic-numbers b/Lang/TypeScript/Arithmetic-numbers new file mode 120000 index 0000000000..0a37af8cff --- /dev/null +++ b/Lang/TypeScript/Arithmetic-numbers @@ -0,0 +1 @@ +../../Task/Arithmetic-numbers/TypeScript \ No newline at end of file diff --git a/Lang/TypeScript/Deal-cards-for-FreeCell b/Lang/TypeScript/Deal-cards-for-FreeCell new file mode 120000 index 0000000000..04eefe17ef --- /dev/null +++ b/Lang/TypeScript/Deal-cards-for-FreeCell @@ -0,0 +1 @@ +../../Task/Deal-cards-for-FreeCell/TypeScript \ No newline at end of file diff --git a/Lang/TypeScript/Leonardo-numbers b/Lang/TypeScript/Leonardo-numbers new file mode 120000 index 0000000000..501c953b40 --- /dev/null +++ b/Lang/TypeScript/Leonardo-numbers @@ -0,0 +1 @@ +../../Task/Leonardo-numbers/TypeScript \ No newline at end of file diff --git a/Lang/TypeScript/Map-range b/Lang/TypeScript/Map-range new file mode 120000 index 0000000000..50eeda25cd --- /dev/null +++ b/Lang/TypeScript/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/TypeScript \ No newline at end of file diff --git a/Lang/TypeScript/Sum-of-a-series b/Lang/TypeScript/Sum-of-a-series new file mode 120000 index 0000000000..810faf05f3 --- /dev/null +++ b/Lang/TypeScript/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/TypeScript \ No newline at end of file diff --git a/Lang/UNIX-Shell/CRC-32 b/Lang/UNIX-Shell/CRC-32 new file mode 120000 index 0000000000..7be1bb462f --- /dev/null +++ b/Lang/UNIX-Shell/CRC-32 @@ -0,0 +1 @@ +../../Task/CRC-32/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Color-of-a-screen-pixel b/Lang/UNIX-Shell/Color-of-a-screen-pixel new file mode 120000 index 0000000000..8344bcd2f2 --- /dev/null +++ b/Lang/UNIX-Shell/Color-of-a-screen-pixel @@ -0,0 +1 @@ +../../Task/Color-of-a-screen-pixel/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Color-quantization b/Lang/UNIX-Shell/Color-quantization new file mode 120000 index 0000000000..6c518f1af5 --- /dev/null +++ b/Lang/UNIX-Shell/Color-quantization @@ -0,0 +1 @@ +../../Task/Color-quantization/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Copy-stdin-to-stdout b/Lang/UNIX-Shell/Copy-stdin-to-stdout new file mode 120000 index 0000000000..217727646b --- /dev/null +++ b/Lang/UNIX-Shell/Copy-stdin-to-stdout @@ -0,0 +1 @@ +../../Task/Copy-stdin-to-stdout/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Horners-rule-for-polynomial-evaluation b/Lang/UNIX-Shell/Horners-rule-for-polynomial-evaluation new file mode 120000 index 0000000000..18a4ccc4dc --- /dev/null +++ b/Lang/UNIX-Shell/Horners-rule-for-polynomial-evaluation @@ -0,0 +1 @@ +../../Task/Horners-rule-for-polynomial-evaluation/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Pi b/Lang/UNIX-Shell/Pi new file mode 120000 index 0000000000..854a52d02a --- /dev/null +++ b/Lang/UNIX-Shell/Pi @@ -0,0 +1 @@ +../../Task/Pi/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Trabb-Pardo-Knuth-algorithm b/Lang/UNIX-Shell/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..d9c18fe35b --- /dev/null +++ b/Lang/UNIX-Shell/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/UNIX-Shell \ No newline at end of file diff --git a/Lang/Uiua/00-LANG.txt b/Lang/Uiua/00-LANG.txt index 2a4f3f689f..f3cc2f1ee5 100644 --- a/Lang/Uiua/00-LANG.txt +++ b/Lang/Uiua/00-LANG.txt @@ -1,7 +1,15 @@ {{language -|site=https://www.uiua.org/}} -{{language programming paradigm|functional}} -Uiua (''wee-wuh'') is a general purpose, stack-based, array-oriented programming language with a focus on simplicity, beauty, and tacit code. +|exec=bytecode +|site=https://www.uiua.org/ +|checking=dynamic +|gc=yes +|express=implicit +|LCT=yes}} +{{language programming paradigm|array}} +{{language programming paradigm|functional|array}} +From [https://www.uiua.org uiua.org]: + +"Uiua (''wee-wuh'') is a general purpose, stack-based, array-oriented programming language with a focus on simplicity, beauty, and tacit code. Uiua has a simple, context-free, LL(3) grammar. Code runs from right to left, top to bottom, with only one precedence rule. As operators are to the left of their operands, Uiua code reads a little bit like a Lisp, but with fewer parentheses. @@ -11,4 +19,10 @@ Uiua's one and only composite data type, the array, is based on those of APL, J, Unlike other array languages, Uiua does not have monadic and dyadic versions of each glyph. Every glyph does only one thing, so you don't need to parse an entire expression to know which version it is. -Find out more, and run code in your browser at https://www.uiua.org \ No newline at end of file +Find out more, and run code in your browser at [https://www.uiua.org https://www.uiua.org]." + +===Note=== +The Uiua programming language uses a custom font and colorful syntax highlighting to increase the readability of its code. As such syntax highlighting is not possible to display on this wiki, it is recommended to paste code into [https://www.uiua.org/pad the online Uiua pad] (or a [https://www.uiua.org/install#editor-support supported editor]) to view code more easily. + +==Todo== +[https://rosettacode.org/wiki/Tasks_not_implemented_in_Uiua Tasks not implemented in Uiua] \ No newline at end of file diff --git a/Lang/Uiua/100-doors b/Lang/Uiua/100-doors new file mode 120000 index 0000000000..58d6cad56c --- /dev/null +++ b/Lang/Uiua/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/Uiua \ No newline at end of file diff --git a/Lang/Uiua/15-puzzle-solver b/Lang/Uiua/15-puzzle-solver new file mode 120000 index 0000000000..d2c4541287 --- /dev/null +++ b/Lang/Uiua/15-puzzle-solver @@ -0,0 +1 @@ +../../Task/15-puzzle-solver/Uiua \ No newline at end of file diff --git a/Lang/Uiua/21-game b/Lang/Uiua/21-game new file mode 120000 index 0000000000..629762436d --- /dev/null +++ b/Lang/Uiua/21-game @@ -0,0 +1 @@ +../../Task/21-game/Uiua \ No newline at end of file diff --git a/Lang/Uiua/4-rings-or-4-squares-puzzle b/Lang/Uiua/4-rings-or-4-squares-puzzle new file mode 120000 index 0000000000..a31782d205 --- /dev/null +++ b/Lang/Uiua/4-rings-or-4-squares-puzzle @@ -0,0 +1 @@ +../../Task/4-rings-or-4-squares-puzzle/Uiua \ No newline at end of file diff --git a/Lang/Uiua/99-bottles-of-beer b/Lang/Uiua/99-bottles-of-beer new file mode 120000 index 0000000000..bd1d75c2c7 --- /dev/null +++ b/Lang/Uiua/99-bottles-of-beer @@ -0,0 +1 @@ +../../Task/99-bottles-of-beer/Uiua \ No newline at end of file diff --git a/Lang/Uiua/A+B b/Lang/Uiua/A+B new file mode 120000 index 0000000000..df9da8c183 --- /dev/null +++ b/Lang/Uiua/A+B @@ -0,0 +1 @@ +../../Task/A+B/Uiua \ No newline at end of file diff --git a/Lang/Uiua/ABC-problem b/Lang/Uiua/ABC-problem new file mode 120000 index 0000000000..e3c88d305a --- /dev/null +++ b/Lang/Uiua/ABC-problem @@ -0,0 +1 @@ +../../Task/ABC-problem/Uiua \ No newline at end of file diff --git a/Lang/Uiua/ADFGVX-cipher b/Lang/Uiua/ADFGVX-cipher new file mode 120000 index 0000000000..3b808ce65e --- /dev/null +++ b/Lang/Uiua/ADFGVX-cipher @@ -0,0 +1 @@ +../../Task/ADFGVX-cipher/Uiua \ No newline at end of file diff --git a/Lang/Uiua/ASCII-art-diagram-converter b/Lang/Uiua/ASCII-art-diagram-converter new file mode 120000 index 0000000000..7868ebc205 --- /dev/null +++ b/Lang/Uiua/ASCII-art-diagram-converter @@ -0,0 +1 @@ +../../Task/ASCII-art-diagram-converter/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Abbreviations-automatic b/Lang/Uiua/Abbreviations-automatic new file mode 120000 index 0000000000..4ed38ebb71 --- /dev/null +++ b/Lang/Uiua/Abbreviations-automatic @@ -0,0 +1 @@ +../../Task/Abbreviations-automatic/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Abelian-sandpile-model b/Lang/Uiua/Abelian-sandpile-model new file mode 120000 index 0000000000..511d6d21ce --- /dev/null +++ b/Lang/Uiua/Abelian-sandpile-model @@ -0,0 +1 @@ +../../Task/Abelian-sandpile-model/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Abundant-deficient-and-perfect-number-classifications b/Lang/Uiua/Abundant-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..4ea7de4aaa --- /dev/null +++ b/Lang/Uiua/Abundant-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant-deficient-and-perfect-number-classifications/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Abundant-odd-numbers b/Lang/Uiua/Abundant-odd-numbers new file mode 120000 index 0000000000..15f27f9ef1 --- /dev/null +++ b/Lang/Uiua/Abundant-odd-numbers @@ -0,0 +1 @@ +../../Task/Abundant-odd-numbers/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Ackermann-function b/Lang/Uiua/Ackermann-function new file mode 120000 index 0000000000..94bc0faf99 --- /dev/null +++ b/Lang/Uiua/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Align-columns b/Lang/Uiua/Align-columns new file mode 120000 index 0000000000..90d8156011 --- /dev/null +++ b/Lang/Uiua/Align-columns @@ -0,0 +1 @@ +../../Task/Align-columns/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Almost-prime b/Lang/Uiua/Almost-prime new file mode 120000 index 0000000000..392773baf7 --- /dev/null +++ b/Lang/Uiua/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Amicable-pairs b/Lang/Uiua/Amicable-pairs new file mode 120000 index 0000000000..8c9ce68129 --- /dev/null +++ b/Lang/Uiua/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Anagrams b/Lang/Uiua/Anagrams new file mode 120000 index 0000000000..a823cee1f3 --- /dev/null +++ b/Lang/Uiua/Anagrams @@ -0,0 +1 @@ +../../Task/Anagrams/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Angle-difference-between-two-bearings b/Lang/Uiua/Angle-difference-between-two-bearings new file mode 120000 index 0000000000..ee9bbb083d --- /dev/null +++ b/Lang/Uiua/Angle-difference-between-two-bearings @@ -0,0 +1 @@ +../../Task/Angle-difference-between-two-bearings/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Anonymous-recursion b/Lang/Uiua/Anonymous-recursion new file mode 120000 index 0000000000..8c1b1c25c3 --- /dev/null +++ b/Lang/Uiua/Anonymous-recursion @@ -0,0 +1 @@ +../../Task/Anonymous-recursion/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Anti-primes b/Lang/Uiua/Anti-primes new file mode 120000 index 0000000000..caaf04d665 --- /dev/null +++ b/Lang/Uiua/Anti-primes @@ -0,0 +1 @@ +../../Task/Anti-primes/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Apply-a-callback-to-an-array b/Lang/Uiua/Apply-a-callback-to-an-array new file mode 120000 index 0000000000..685e6558c3 --- /dev/null +++ b/Lang/Uiua/Apply-a-callback-to-an-array @@ -0,0 +1 @@ +../../Task/Apply-a-callback-to-an-array/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Arithmetic-Complex b/Lang/Uiua/Arithmetic-Complex new file mode 120000 index 0000000000..acbbaad1bb --- /dev/null +++ b/Lang/Uiua/Arithmetic-Complex @@ -0,0 +1 @@ +../../Task/Arithmetic-Complex/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Arithmetic-Integer b/Lang/Uiua/Arithmetic-Integer new file mode 120000 index 0000000000..8f8007cc44 --- /dev/null +++ b/Lang/Uiua/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Arithmetic-derivative b/Lang/Uiua/Arithmetic-derivative new file mode 120000 index 0000000000..940b88708d --- /dev/null +++ b/Lang/Uiua/Arithmetic-derivative @@ -0,0 +1 @@ +../../Task/Arithmetic-derivative/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Arithmetic-geometric-mean b/Lang/Uiua/Arithmetic-geometric-mean new file mode 120000 index 0000000000..6adeb66a11 --- /dev/null +++ b/Lang/Uiua/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Arithmetic-geometric-mean-Calculate-Pi b/Lang/Uiua/Arithmetic-geometric-mean-Calculate-Pi new file mode 120000 index 0000000000..e30c23f938 --- /dev/null +++ b/Lang/Uiua/Arithmetic-geometric-mean-Calculate-Pi @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean-Calculate-Pi/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Arithmetic-numbers b/Lang/Uiua/Arithmetic-numbers new file mode 120000 index 0000000000..e537c98fb0 --- /dev/null +++ b/Lang/Uiua/Arithmetic-numbers @@ -0,0 +1 @@ +../../Task/Arithmetic-numbers/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Array-concatenation b/Lang/Uiua/Array-concatenation new file mode 120000 index 0000000000..48fabf1a40 --- /dev/null +++ b/Lang/Uiua/Array-concatenation @@ -0,0 +1 @@ +../../Task/Array-concatenation/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Array-length b/Lang/Uiua/Array-length new file mode 120000 index 0000000000..7c3be21b34 --- /dev/null +++ b/Lang/Uiua/Array-length @@ -0,0 +1 @@ +../../Task/Array-length/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Arrays b/Lang/Uiua/Arrays new file mode 120000 index 0000000000..ae2ca1c8a6 --- /dev/null +++ b/Lang/Uiua/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Ascending-primes b/Lang/Uiua/Ascending-primes new file mode 120000 index 0000000000..83b9f7be7a --- /dev/null +++ b/Lang/Uiua/Ascending-primes @@ -0,0 +1 @@ +../../Task/Ascending-primes/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Assertions b/Lang/Uiua/Assertions new file mode 120000 index 0000000000..b370cee8a3 --- /dev/null +++ b/Lang/Uiua/Assertions @@ -0,0 +1 @@ +../../Task/Assertions/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Associative-array-Creation b/Lang/Uiua/Associative-array-Creation new file mode 120000 index 0000000000..8f5e350a55 --- /dev/null +++ b/Lang/Uiua/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Associative-array-Iteration b/Lang/Uiua/Associative-array-Iteration new file mode 120000 index 0000000000..5ba8f9745a --- /dev/null +++ b/Lang/Uiua/Associative-array-Iteration @@ -0,0 +1 @@ +../../Task/Associative-array-Iteration/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Associative-array-Merging b/Lang/Uiua/Associative-array-Merging new file mode 120000 index 0000000000..d769831c9b --- /dev/null +++ b/Lang/Uiua/Associative-array-Merging @@ -0,0 +1 @@ +../../Task/Associative-array-Merging/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Attractive-numbers b/Lang/Uiua/Attractive-numbers new file mode 120000 index 0000000000..d36ccc01ec --- /dev/null +++ b/Lang/Uiua/Attractive-numbers @@ -0,0 +1 @@ +../../Task/Attractive-numbers/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Averages-Arithmetic-mean b/Lang/Uiua/Averages-Arithmetic-mean new file mode 120000 index 0000000000..b50b3b064d --- /dev/null +++ b/Lang/Uiua/Averages-Arithmetic-mean @@ -0,0 +1 @@ +../../Task/Averages-Arithmetic-mean/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Averages-Mean-time-of-day b/Lang/Uiua/Averages-Mean-time-of-day new file mode 120000 index 0000000000..970582690e --- /dev/null +++ b/Lang/Uiua/Averages-Mean-time-of-day @@ -0,0 +1 @@ +../../Task/Averages-Mean-time-of-day/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Averages-Median b/Lang/Uiua/Averages-Median new file mode 120000 index 0000000000..254605ff30 --- /dev/null +++ b/Lang/Uiua/Averages-Median @@ -0,0 +1 @@ +../../Task/Averages-Median/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Averages-Mode b/Lang/Uiua/Averages-Mode new file mode 120000 index 0000000000..13987f5b7d --- /dev/null +++ b/Lang/Uiua/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Averages-Pythagorean-means b/Lang/Uiua/Averages-Pythagorean-means new file mode 120000 index 0000000000..a42d46aee7 --- /dev/null +++ b/Lang/Uiua/Averages-Pythagorean-means @@ -0,0 +1 @@ +../../Task/Averages-Pythagorean-means/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Averages-Root-mean-square b/Lang/Uiua/Averages-Root-mean-square new file mode 120000 index 0000000000..681a323abf --- /dev/null +++ b/Lang/Uiua/Averages-Root-mean-square @@ -0,0 +1 @@ +../../Task/Averages-Root-mean-square/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Babbage-problem b/Lang/Uiua/Babbage-problem new file mode 120000 index 0000000000..485d090cb5 --- /dev/null +++ b/Lang/Uiua/Babbage-problem @@ -0,0 +1 @@ +../../Task/Babbage-problem/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Barnsley-fern b/Lang/Uiua/Barnsley-fern new file mode 120000 index 0000000000..39f57d2d79 --- /dev/null +++ b/Lang/Uiua/Barnsley-fern @@ -0,0 +1 @@ +../../Task/Barnsley-fern/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Bell-numbers b/Lang/Uiua/Bell-numbers new file mode 120000 index 0000000000..88832c268c --- /dev/null +++ b/Lang/Uiua/Bell-numbers @@ -0,0 +1 @@ +../../Task/Bell-numbers/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Benfords-law b/Lang/Uiua/Benfords-law new file mode 120000 index 0000000000..c9f7d29ef6 --- /dev/null +++ b/Lang/Uiua/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Bifid-cipher b/Lang/Uiua/Bifid-cipher new file mode 120000 index 0000000000..7118fdadf7 --- /dev/null +++ b/Lang/Uiua/Bifid-cipher @@ -0,0 +1 @@ +../../Task/Bifid-cipher/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Bin-given-limits b/Lang/Uiua/Bin-given-limits new file mode 120000 index 0000000000..66cb90c004 --- /dev/null +++ b/Lang/Uiua/Bin-given-limits @@ -0,0 +1 @@ +../../Task/Bin-given-limits/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Binary-digits b/Lang/Uiua/Binary-digits new file mode 120000 index 0000000000..126c2d6665 --- /dev/null +++ b/Lang/Uiua/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Bitmap b/Lang/Uiua/Bitmap new file mode 120000 index 0000000000..6ff7a055f3 --- /dev/null +++ b/Lang/Uiua/Bitmap @@ -0,0 +1 @@ +../../Task/Bitmap/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Bitmap-Flood-fill b/Lang/Uiua/Bitmap-Flood-fill new file mode 120000 index 0000000000..8833733b75 --- /dev/null +++ b/Lang/Uiua/Bitmap-Flood-fill @@ -0,0 +1 @@ +../../Task/Bitmap-Flood-fill/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Bitwise-operations b/Lang/Uiua/Bitwise-operations new file mode 120000 index 0000000000..1b1bf97751 --- /dev/null +++ b/Lang/Uiua/Bitwise-operations @@ -0,0 +1 @@ +../../Task/Bitwise-operations/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Boolean-values b/Lang/Uiua/Boolean-values new file mode 120000 index 0000000000..ac8910eee9 --- /dev/null +++ b/Lang/Uiua/Boolean-values @@ -0,0 +1 @@ +../../Task/Boolean-values/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Bulls-and-cows-Player b/Lang/Uiua/Bulls-and-cows-Player new file mode 120000 index 0000000000..b45c91dd88 --- /dev/null +++ b/Lang/Uiua/Bulls-and-cows-Player @@ -0,0 +1 @@ +../../Task/Bulls-and-cows-Player/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Burrows-Wheeler-transform b/Lang/Uiua/Burrows-Wheeler-transform new file mode 120000 index 0000000000..d53398fc74 --- /dev/null +++ b/Lang/Uiua/Burrows-Wheeler-transform @@ -0,0 +1 @@ +../../Task/Burrows-Wheeler-transform/Uiua \ No newline at end of file diff --git a/Lang/Uiua/CRC-32 b/Lang/Uiua/CRC-32 new file mode 120000 index 0000000000..063f3e4ee3 --- /dev/null +++ b/Lang/Uiua/CRC-32 @@ -0,0 +1 @@ +../../Task/CRC-32/Uiua \ No newline at end of file diff --git a/Lang/Uiua/CSV-data-manipulation b/Lang/Uiua/CSV-data-manipulation new file mode 120000 index 0000000000..78747e6f49 --- /dev/null +++ b/Lang/Uiua/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/Uiua \ No newline at end of file diff --git a/Lang/Uiua/CSV-to-HTML-translation b/Lang/Uiua/CSV-to-HTML-translation new file mode 120000 index 0000000000..cd311bcc18 --- /dev/null +++ b/Lang/Uiua/CSV-to-HTML-translation @@ -0,0 +1 @@ +../../Task/CSV-to-HTML-translation/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Caesar-cipher b/Lang/Uiua/Caesar-cipher new file mode 120000 index 0000000000..ef50c0e2e1 --- /dev/null +++ b/Lang/Uiua/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Calculating-the-value-of-e b/Lang/Uiua/Calculating-the-value-of-e new file mode 120000 index 0000000000..d7cc261bf8 --- /dev/null +++ b/Lang/Uiua/Calculating-the-value-of-e @@ -0,0 +1 @@ +../../Task/Calculating-the-value-of-e/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Calkin-Wilf-sequence b/Lang/Uiua/Calkin-Wilf-sequence new file mode 120000 index 0000000000..23330ada15 --- /dev/null +++ b/Lang/Uiua/Calkin-Wilf-sequence @@ -0,0 +1 @@ +../../Task/Calkin-Wilf-sequence/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Call-a-function b/Lang/Uiua/Call-a-function new file mode 120000 index 0000000000..1d6b22e4f5 --- /dev/null +++ b/Lang/Uiua/Call-a-function @@ -0,0 +1 @@ +../../Task/Call-a-function/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Cantor-set b/Lang/Uiua/Cantor-set new file mode 120000 index 0000000000..1c94d38d0e --- /dev/null +++ b/Lang/Uiua/Cantor-set @@ -0,0 +1 @@ +../../Task/Cantor-set/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Cartesian-product-of-two-or-more-lists b/Lang/Uiua/Cartesian-product-of-two-or-more-lists new file mode 120000 index 0000000000..bff2250b36 --- /dev/null +++ b/Lang/Uiua/Cartesian-product-of-two-or-more-lists @@ -0,0 +1 @@ +../../Task/Cartesian-product-of-two-or-more-lists/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Catalan-numbers b/Lang/Uiua/Catalan-numbers new file mode 120000 index 0000000000..39a3cbd336 --- /dev/null +++ b/Lang/Uiua/Catalan-numbers @@ -0,0 +1 @@ +../../Task/Catalan-numbers/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Catalan-numbers-Pascals-triangle b/Lang/Uiua/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..d4426dbc39 --- /dev/null +++ b/Lang/Uiua/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Catamorphism b/Lang/Uiua/Catamorphism new file mode 120000 index 0000000000..f0a8a02f45 --- /dev/null +++ b/Lang/Uiua/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Character-codes b/Lang/Uiua/Character-codes new file mode 120000 index 0000000000..511eef1d48 --- /dev/null +++ b/Lang/Uiua/Character-codes @@ -0,0 +1 @@ +../../Task/Character-codes/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Check-output-device-is-a-terminal b/Lang/Uiua/Check-output-device-is-a-terminal new file mode 120000 index 0000000000..9599dac818 --- /dev/null +++ b/Lang/Uiua/Check-output-device-is-a-terminal @@ -0,0 +1 @@ +../../Task/Check-output-device-is-a-terminal/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Check-that-file-exists b/Lang/Uiua/Check-that-file-exists new file mode 120000 index 0000000000..2ad54c3db1 --- /dev/null +++ b/Lang/Uiua/Check-that-file-exists @@ -0,0 +1 @@ +../../Task/Check-that-file-exists/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Circular-primes b/Lang/Uiua/Circular-primes new file mode 120000 index 0000000000..65d19beab0 --- /dev/null +++ b/Lang/Uiua/Circular-primes @@ -0,0 +1 @@ +../../Task/Circular-primes/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Cistercian-numerals b/Lang/Uiua/Cistercian-numerals new file mode 120000 index 0000000000..7a072fe82a --- /dev/null +++ b/Lang/Uiua/Cistercian-numerals @@ -0,0 +1 @@ +../../Task/Cistercian-numerals/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Collections b/Lang/Uiua/Collections new file mode 120000 index 0000000000..3ea461802a --- /dev/null +++ b/Lang/Uiua/Collections @@ -0,0 +1 @@ +../../Task/Collections/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Color-wheel b/Lang/Uiua/Color-wheel new file mode 120000 index 0000000000..f9a74260bf --- /dev/null +++ b/Lang/Uiua/Color-wheel @@ -0,0 +1 @@ +../../Task/Color-wheel/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Colorful-numbers b/Lang/Uiua/Colorful-numbers new file mode 120000 index 0000000000..b2f820f214 --- /dev/null +++ b/Lang/Uiua/Colorful-numbers @@ -0,0 +1 @@ +../../Task/Colorful-numbers/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Colour-bars-Display b/Lang/Uiua/Colour-bars-Display new file mode 120000 index 0000000000..dbff1dc862 --- /dev/null +++ b/Lang/Uiua/Colour-bars-Display @@ -0,0 +1 @@ +../../Task/Colour-bars-Display/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Combinations b/Lang/Uiua/Combinations new file mode 120000 index 0000000000..1300366dbb --- /dev/null +++ b/Lang/Uiua/Combinations @@ -0,0 +1 @@ +../../Task/Combinations/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Combinations-and-permutations b/Lang/Uiua/Combinations-and-permutations new file mode 120000 index 0000000000..c2af258e0d --- /dev/null +++ b/Lang/Uiua/Combinations-and-permutations @@ -0,0 +1 @@ +../../Task/Combinations-and-permutations/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Command-line-arguments b/Lang/Uiua/Command-line-arguments new file mode 120000 index 0000000000..d8dd4a464b --- /dev/null +++ b/Lang/Uiua/Command-line-arguments @@ -0,0 +1 @@ +../../Task/Command-line-arguments/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Comments b/Lang/Uiua/Comments new file mode 120000 index 0000000000..c903ca1910 --- /dev/null +++ b/Lang/Uiua/Comments @@ -0,0 +1 @@ +../../Task/Comments/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Compare-a-list-of-strings b/Lang/Uiua/Compare-a-list-of-strings new file mode 120000 index 0000000000..7a7f8f4123 --- /dev/null +++ b/Lang/Uiua/Compare-a-list-of-strings @@ -0,0 +1 @@ +../../Task/Compare-a-list-of-strings/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Compare-length-of-two-strings b/Lang/Uiua/Compare-length-of-two-strings new file mode 120000 index 0000000000..ca614fc73a --- /dev/null +++ b/Lang/Uiua/Compare-length-of-two-strings @@ -0,0 +1 @@ +../../Task/Compare-length-of-two-strings/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Continued-fraction b/Lang/Uiua/Continued-fraction new file mode 120000 index 0000000000..e2c428ddc0 --- /dev/null +++ b/Lang/Uiua/Continued-fraction @@ -0,0 +1 @@ +../../Task/Continued-fraction/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Convert-seconds-to-compound-duration b/Lang/Uiua/Convert-seconds-to-compound-duration new file mode 120000 index 0000000000..7c892696f2 --- /dev/null +++ b/Lang/Uiua/Convert-seconds-to-compound-duration @@ -0,0 +1 @@ +../../Task/Convert-seconds-to-compound-duration/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Conways-Game-of-Life b/Lang/Uiua/Conways-Game-of-Life new file mode 120000 index 0000000000..577dcf20b1 --- /dev/null +++ b/Lang/Uiua/Conways-Game-of-Life @@ -0,0 +1 @@ +../../Task/Conways-Game-of-Life/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Copy-a-string b/Lang/Uiua/Copy-a-string new file mode 120000 index 0000000000..ecc8029f9f --- /dev/null +++ b/Lang/Uiua/Copy-a-string @@ -0,0 +1 @@ +../../Task/Copy-a-string/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Count-in-factors b/Lang/Uiua/Count-in-factors new file mode 120000 index 0000000000..fee553f727 --- /dev/null +++ b/Lang/Uiua/Count-in-factors @@ -0,0 +1 @@ +../../Task/Count-in-factors/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Count-in-octal b/Lang/Uiua/Count-in-octal new file mode 120000 index 0000000000..8d3356f54e --- /dev/null +++ b/Lang/Uiua/Count-in-octal @@ -0,0 +1 @@ +../../Task/Count-in-octal/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Count-occurrences-of-a-substring b/Lang/Uiua/Count-occurrences-of-a-substring new file mode 120000 index 0000000000..5aa05050f1 --- /dev/null +++ b/Lang/Uiua/Count-occurrences-of-a-substring @@ -0,0 +1 @@ +../../Task/Count-occurrences-of-a-substring/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Count-the-coins b/Lang/Uiua/Count-the-coins new file mode 120000 index 0000000000..061cac0c44 --- /dev/null +++ b/Lang/Uiua/Count-the-coins @@ -0,0 +1 @@ +../../Task/Count-the-coins/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Cramers-rule b/Lang/Uiua/Cramers-rule new file mode 120000 index 0000000000..cdb9c1d147 --- /dev/null +++ b/Lang/Uiua/Cramers-rule @@ -0,0 +1 @@ +../../Task/Cramers-rule/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Create-a-two-dimensional-array-at-runtime b/Lang/Uiua/Create-a-two-dimensional-array-at-runtime new file mode 120000 index 0000000000..4ef285f54f --- /dev/null +++ b/Lang/Uiua/Create-a-two-dimensional-array-at-runtime @@ -0,0 +1 @@ +../../Task/Create-a-two-dimensional-array-at-runtime/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Cuban-primes b/Lang/Uiua/Cuban-primes new file mode 120000 index 0000000000..36dfb34863 --- /dev/null +++ b/Lang/Uiua/Cuban-primes @@ -0,0 +1 @@ +../../Task/Cuban-primes/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Cut-a-rectangle b/Lang/Uiua/Cut-a-rectangle new file mode 120000 index 0000000000..c91aef1334 --- /dev/null +++ b/Lang/Uiua/Cut-a-rectangle @@ -0,0 +1 @@ +../../Task/Cut-a-rectangle/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Damm-algorithm b/Lang/Uiua/Damm-algorithm new file mode 120000 index 0000000000..af8244172d --- /dev/null +++ b/Lang/Uiua/Damm-algorithm @@ -0,0 +1 @@ +../../Task/Damm-algorithm/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Day-of-the-week b/Lang/Uiua/Day-of-the-week new file mode 120000 index 0000000000..3e8980f9e6 --- /dev/null +++ b/Lang/Uiua/Day-of-the-week @@ -0,0 +1 @@ +../../Task/Day-of-the-week/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Delete-a-file b/Lang/Uiua/Delete-a-file new file mode 120000 index 0000000000..a33b49cc5b --- /dev/null +++ b/Lang/Uiua/Delete-a-file @@ -0,0 +1 @@ +../../Task/Delete-a-file/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Department-numbers b/Lang/Uiua/Department-numbers new file mode 120000 index 0000000000..d3bc5b010c --- /dev/null +++ b/Lang/Uiua/Department-numbers @@ -0,0 +1 @@ +../../Task/Department-numbers/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Descending-primes b/Lang/Uiua/Descending-primes new file mode 120000 index 0000000000..9ae82c1998 --- /dev/null +++ b/Lang/Uiua/Descending-primes @@ -0,0 +1 @@ +../../Task/Descending-primes/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Detect-division-by-zero b/Lang/Uiua/Detect-division-by-zero new file mode 120000 index 0000000000..40e2698013 --- /dev/null +++ b/Lang/Uiua/Detect-division-by-zero @@ -0,0 +1 @@ +../../Task/Detect-division-by-zero/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Determine-if-a-string-has-all-the-same-characters b/Lang/Uiua/Determine-if-a-string-has-all-the-same-characters new file mode 120000 index 0000000000..55e1bace7e --- /dev/null +++ b/Lang/Uiua/Determine-if-a-string-has-all-the-same-characters @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-has-all-the-same-characters/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Determine-if-a-string-has-all-unique-characters b/Lang/Uiua/Determine-if-a-string-has-all-unique-characters new file mode 120000 index 0000000000..76105a59e1 --- /dev/null +++ b/Lang/Uiua/Determine-if-a-string-has-all-unique-characters @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-has-all-unique-characters/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Determine-if-a-string-is-collapsible b/Lang/Uiua/Determine-if-a-string-is-collapsible new file mode 120000 index 0000000000..9891000cca --- /dev/null +++ b/Lang/Uiua/Determine-if-a-string-is-collapsible @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-collapsible/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Determine-if-a-string-is-numeric b/Lang/Uiua/Determine-if-a-string-is-numeric new file mode 120000 index 0000000000..12d7b2bbd9 --- /dev/null +++ b/Lang/Uiua/Determine-if-a-string-is-numeric @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-numeric/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Digital-root b/Lang/Uiua/Digital-root new file mode 120000 index 0000000000..709355d0c9 --- /dev/null +++ b/Lang/Uiua/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Dijkstras-algorithm b/Lang/Uiua/Dijkstras-algorithm new file mode 120000 index 0000000000..f3d03f9e62 --- /dev/null +++ b/Lang/Uiua/Dijkstras-algorithm @@ -0,0 +1 @@ +../../Task/Dijkstras-algorithm/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Disarium-numbers b/Lang/Uiua/Disarium-numbers new file mode 120000 index 0000000000..28107527a2 --- /dev/null +++ b/Lang/Uiua/Disarium-numbers @@ -0,0 +1 @@ +../../Task/Disarium-numbers/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Dominoes b/Lang/Uiua/Dominoes new file mode 120000 index 0000000000..bd5d6f0291 --- /dev/null +++ b/Lang/Uiua/Dominoes @@ -0,0 +1 @@ +../../Task/Dominoes/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Doomsday-rule b/Lang/Uiua/Doomsday-rule new file mode 120000 index 0000000000..d408a1ec32 --- /dev/null +++ b/Lang/Uiua/Doomsday-rule @@ -0,0 +1 @@ +../../Task/Doomsday-rule/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Dot-product b/Lang/Uiua/Dot-product new file mode 120000 index 0000000000..920d49c003 --- /dev/null +++ b/Lang/Uiua/Dot-product @@ -0,0 +1 @@ +../../Task/Dot-product/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Dutch-national-flag-problem b/Lang/Uiua/Dutch-national-flag-problem new file mode 120000 index 0000000000..198949a01a --- /dev/null +++ b/Lang/Uiua/Dutch-national-flag-problem @@ -0,0 +1 @@ +../../Task/Dutch-national-flag-problem/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Earliest-difference-between-prime-gaps b/Lang/Uiua/Earliest-difference-between-prime-gaps new file mode 120000 index 0000000000..3fd8b6678f --- /dev/null +++ b/Lang/Uiua/Earliest-difference-between-prime-gaps @@ -0,0 +1 @@ +../../Task/Earliest-difference-between-prime-gaps/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Echo-server b/Lang/Uiua/Echo-server new file mode 120000 index 0000000000..13818666c0 --- /dev/null +++ b/Lang/Uiua/Echo-server @@ -0,0 +1 @@ +../../Task/Echo-server/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Emirp-primes b/Lang/Uiua/Emirp-primes new file mode 120000 index 0000000000..277723b92d --- /dev/null +++ b/Lang/Uiua/Emirp-primes @@ -0,0 +1 @@ +../../Task/Emirp-primes/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Empty-string b/Lang/Uiua/Empty-string new file mode 120000 index 0000000000..9b9da2a9b4 --- /dev/null +++ b/Lang/Uiua/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Enforced-immutability b/Lang/Uiua/Enforced-immutability new file mode 120000 index 0000000000..243ebb8f2a --- /dev/null +++ b/Lang/Uiua/Enforced-immutability @@ -0,0 +1 @@ +../../Task/Enforced-immutability/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Enumerations b/Lang/Uiua/Enumerations new file mode 120000 index 0000000000..08a4a901fa --- /dev/null +++ b/Lang/Uiua/Enumerations @@ -0,0 +1 @@ +../../Task/Enumerations/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Ethiopian-multiplication b/Lang/Uiua/Ethiopian-multiplication new file mode 120000 index 0000000000..4091de8f8e --- /dev/null +++ b/Lang/Uiua/Ethiopian-multiplication @@ -0,0 +1 @@ +../../Task/Ethiopian-multiplication/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Exceptions b/Lang/Uiua/Exceptions new file mode 120000 index 0000000000..4cf4e7dfeb --- /dev/null +++ b/Lang/Uiua/Exceptions @@ -0,0 +1 @@ +../../Task/Exceptions/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Exponentiation-operator b/Lang/Uiua/Exponentiation-operator new file mode 120000 index 0000000000..bf3e3a41e0 --- /dev/null +++ b/Lang/Uiua/Exponentiation-operator @@ -0,0 +1 @@ +../../Task/Exponentiation-operator/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Exponentiation-order b/Lang/Uiua/Exponentiation-order new file mode 120000 index 0000000000..8518c14141 --- /dev/null +++ b/Lang/Uiua/Exponentiation-order @@ -0,0 +1 @@ +../../Task/Exponentiation-order/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Extreme-floating-point-values b/Lang/Uiua/Extreme-floating-point-values new file mode 120000 index 0000000000..05ab571554 --- /dev/null +++ b/Lang/Uiua/Extreme-floating-point-values @@ -0,0 +1 @@ +../../Task/Extreme-floating-point-values/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Factorial b/Lang/Uiua/Factorial new file mode 120000 index 0000000000..5664c30904 --- /dev/null +++ b/Lang/Uiua/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Factors-of-an-integer b/Lang/Uiua/Factors-of-an-integer new file mode 120000 index 0000000000..c83bd4a95a --- /dev/null +++ b/Lang/Uiua/Factors-of-an-integer @@ -0,0 +1 @@ +../../Task/Factors-of-an-integer/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Find-the-missing-permutation b/Lang/Uiua/Find-the-missing-permutation new file mode 120000 index 0000000000..e1361833f3 --- /dev/null +++ b/Lang/Uiua/Find-the-missing-permutation @@ -0,0 +1 @@ +../../Task/Find-the-missing-permutation/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Flatten-a-list b/Lang/Uiua/Flatten-a-list new file mode 120000 index 0000000000..8d22eb4f6e --- /dev/null +++ b/Lang/Uiua/Flatten-a-list @@ -0,0 +1 @@ +../../Task/Flatten-a-list/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Flipping-bits-game b/Lang/Uiua/Flipping-bits-game new file mode 120000 index 0000000000..4647df0617 --- /dev/null +++ b/Lang/Uiua/Flipping-bits-game @@ -0,0 +1 @@ +../../Task/Flipping-bits-game/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Forest-fire b/Lang/Uiua/Forest-fire new file mode 120000 index 0000000000..1c1ded9f8f --- /dev/null +++ b/Lang/Uiua/Forest-fire @@ -0,0 +1 @@ +../../Task/Forest-fire/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Greatest-common-divisor b/Lang/Uiua/Greatest-common-divisor new file mode 120000 index 0000000000..ed42b8017f --- /dev/null +++ b/Lang/Uiua/Greatest-common-divisor @@ -0,0 +1 @@ +../../Task/Greatest-common-divisor/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Hailstone-sequence b/Lang/Uiua/Hailstone-sequence new file mode 120000 index 0000000000..eb6ae1ccd8 --- /dev/null +++ b/Lang/Uiua/Hailstone-sequence @@ -0,0 +1 @@ +../../Task/Hailstone-sequence/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Halt-and-catch-fire b/Lang/Uiua/Halt-and-catch-fire new file mode 120000 index 0000000000..098009e021 --- /dev/null +++ b/Lang/Uiua/Halt-and-catch-fire @@ -0,0 +1 @@ +../../Task/Halt-and-catch-fire/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Hash-from-two-arrays b/Lang/Uiua/Hash-from-two-arrays new file mode 120000 index 0000000000..63b4a8d5f8 --- /dev/null +++ b/Lang/Uiua/Hash-from-two-arrays @@ -0,0 +1 @@ +../../Task/Hash-from-two-arrays/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Hickerson-series-of-almost-integers b/Lang/Uiua/Hickerson-series-of-almost-integers new file mode 120000 index 0000000000..d1dde8e508 --- /dev/null +++ b/Lang/Uiua/Hickerson-series-of-almost-integers @@ -0,0 +1 @@ +../../Task/Hickerson-series-of-almost-integers/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Identity-matrix b/Lang/Uiua/Identity-matrix new file mode 120000 index 0000000000..73bc76c89c --- /dev/null +++ b/Lang/Uiua/Identity-matrix @@ -0,0 +1 @@ +../../Task/Identity-matrix/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Include-a-file b/Lang/Uiua/Include-a-file new file mode 120000 index 0000000000..2dd83554d2 --- /dev/null +++ b/Lang/Uiua/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Increment-a-numerical-string b/Lang/Uiua/Increment-a-numerical-string new file mode 120000 index 0000000000..5102531751 --- /dev/null +++ b/Lang/Uiua/Increment-a-numerical-string @@ -0,0 +1 @@ +../../Task/Increment-a-numerical-string/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Infinity b/Lang/Uiua/Infinity new file mode 120000 index 0000000000..13e94dd0ff --- /dev/null +++ b/Lang/Uiua/Infinity @@ -0,0 +1 @@ +../../Task/Infinity/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Integer-sequence b/Lang/Uiua/Integer-sequence new file mode 120000 index 0000000000..71a2ec5539 --- /dev/null +++ b/Lang/Uiua/Integer-sequence @@ -0,0 +1 @@ +../../Task/Integer-sequence/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Iterated-digits-squaring b/Lang/Uiua/Iterated-digits-squaring new file mode 120000 index 0000000000..e658bdae0a --- /dev/null +++ b/Lang/Uiua/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Jacobi-symbol b/Lang/Uiua/Jacobi-symbol new file mode 120000 index 0000000000..c75e72b791 --- /dev/null +++ b/Lang/Uiua/Jacobi-symbol @@ -0,0 +1 @@ +../../Task/Jacobi-symbol/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Jacobsthal-numbers b/Lang/Uiua/Jacobsthal-numbers new file mode 120000 index 0000000000..18c3697b6e --- /dev/null +++ b/Lang/Uiua/Jacobsthal-numbers @@ -0,0 +1 @@ +../../Task/Jacobsthal-numbers/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Langtons-ant b/Lang/Uiua/Langtons-ant new file mode 120000 index 0000000000..ea25fbedff --- /dev/null +++ b/Lang/Uiua/Langtons-ant @@ -0,0 +1 @@ +../../Task/Langtons-ant/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Largest-int-from-concatenated-ints b/Lang/Uiua/Largest-int-from-concatenated-ints new file mode 120000 index 0000000000..1440573f32 --- /dev/null +++ b/Lang/Uiua/Largest-int-from-concatenated-ints @@ -0,0 +1 @@ +../../Task/Largest-int-from-concatenated-ints/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Largest-number-divisible-by-its-digits b/Lang/Uiua/Largest-number-divisible-by-its-digits new file mode 120000 index 0000000000..acf7bb2c5f --- /dev/null +++ b/Lang/Uiua/Largest-number-divisible-by-its-digits @@ -0,0 +1 @@ +../../Task/Largest-number-divisible-by-its-digits/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Leap-year b/Lang/Uiua/Leap-year new file mode 120000 index 0000000000..526002b745 --- /dev/null +++ b/Lang/Uiua/Leap-year @@ -0,0 +1 @@ +../../Task/Leap-year/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Least-common-multiple b/Lang/Uiua/Least-common-multiple new file mode 120000 index 0000000000..83973eef06 --- /dev/null +++ b/Lang/Uiua/Least-common-multiple @@ -0,0 +1 @@ +../../Task/Least-common-multiple/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Levenshtein-distance b/Lang/Uiua/Levenshtein-distance new file mode 120000 index 0000000000..2d4dd26520 --- /dev/null +++ b/Lang/Uiua/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/Uiua \ No newline at end of file diff --git a/Lang/Uiua/List-comprehensions b/Lang/Uiua/List-comprehensions new file mode 120000 index 0000000000..bf7b708e56 --- /dev/null +++ b/Lang/Uiua/List-comprehensions @@ -0,0 +1 @@ +../../Task/List-comprehensions/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Literals-Floating-point b/Lang/Uiua/Literals-Floating-point new file mode 120000 index 0000000000..47d46d3181 --- /dev/null +++ b/Lang/Uiua/Literals-Floating-point @@ -0,0 +1 @@ +../../Task/Literals-Floating-point/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Look-and-say-sequence b/Lang/Uiua/Look-and-say-sequence new file mode 120000 index 0000000000..f3d748e2f9 --- /dev/null +++ b/Lang/Uiua/Look-and-say-sequence @@ -0,0 +1 @@ +../../Task/Look-and-say-sequence/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Loop-over-multiple-arrays-simultaneously b/Lang/Uiua/Loop-over-multiple-arrays-simultaneously new file mode 120000 index 0000000000..59937c5207 --- /dev/null +++ b/Lang/Uiua/Loop-over-multiple-arrays-simultaneously @@ -0,0 +1 @@ +../../Task/Loop-over-multiple-arrays-simultaneously/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Loops-Break b/Lang/Uiua/Loops-Break new file mode 120000 index 0000000000..34504412c0 --- /dev/null +++ b/Lang/Uiua/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Loops-While b/Lang/Uiua/Loops-While new file mode 120000 index 0000000000..d29e38976b --- /dev/null +++ b/Lang/Uiua/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Luhn-test-of-credit-card-numbers b/Lang/Uiua/Luhn-test-of-credit-card-numbers new file mode 120000 index 0000000000..6eae093c92 --- /dev/null +++ b/Lang/Uiua/Luhn-test-of-credit-card-numbers @@ -0,0 +1 @@ +../../Task/Luhn-test-of-credit-card-numbers/Uiua \ No newline at end of file diff --git a/Lang/Uiua/M-bius-function b/Lang/Uiua/M-bius-function new file mode 120000 index 0000000000..5b29f0bb61 --- /dev/null +++ b/Lang/Uiua/M-bius-function @@ -0,0 +1 @@ +../../Task/M-bius-function/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Mandelbrot-set b/Lang/Uiua/Mandelbrot-set new file mode 120000 index 0000000000..da1b6d50fa --- /dev/null +++ b/Lang/Uiua/Mandelbrot-set @@ -0,0 +1 @@ +../../Task/Mandelbrot-set/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Matrix-multiplication b/Lang/Uiua/Matrix-multiplication new file mode 120000 index 0000000000..8ecd583efc --- /dev/null +++ b/Lang/Uiua/Matrix-multiplication @@ -0,0 +1 @@ +../../Task/Matrix-multiplication/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Matrix-transposition b/Lang/Uiua/Matrix-transposition new file mode 120000 index 0000000000..877ca2d6ea --- /dev/null +++ b/Lang/Uiua/Matrix-transposition @@ -0,0 +1 @@ +../../Task/Matrix-transposition/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Maze-solving b/Lang/Uiua/Maze-solving new file mode 120000 index 0000000000..02af57731f --- /dev/null +++ b/Lang/Uiua/Maze-solving @@ -0,0 +1 @@ +../../Task/Maze-solving/Uiua \ No newline at end of file diff --git a/Lang/Uiua/McNuggets-problem b/Lang/Uiua/McNuggets-problem new file mode 120000 index 0000000000..93b54a1053 --- /dev/null +++ b/Lang/Uiua/McNuggets-problem @@ -0,0 +1 @@ +../../Task/McNuggets-problem/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Mertens-function b/Lang/Uiua/Mertens-function new file mode 120000 index 0000000000..8c5970d27b --- /dev/null +++ b/Lang/Uiua/Mertens-function @@ -0,0 +1 @@ +../../Task/Mertens-function/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Middle-three-digits b/Lang/Uiua/Middle-three-digits new file mode 120000 index 0000000000..5c8f171c17 --- /dev/null +++ b/Lang/Uiua/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Modular-inverse b/Lang/Uiua/Modular-inverse new file mode 120000 index 0000000000..70c091b2ce --- /dev/null +++ b/Lang/Uiua/Modular-inverse @@ -0,0 +1 @@ +../../Task/Modular-inverse/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Motzkin-numbers b/Lang/Uiua/Motzkin-numbers new file mode 120000 index 0000000000..bef04d5aa9 --- /dev/null +++ b/Lang/Uiua/Motzkin-numbers @@ -0,0 +1 @@ +../../Task/Motzkin-numbers/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Multifactorial b/Lang/Uiua/Multifactorial new file mode 120000 index 0000000000..cd3719d315 --- /dev/null +++ b/Lang/Uiua/Multifactorial @@ -0,0 +1 @@ +../../Task/Multifactorial/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Munchausen-numbers b/Lang/Uiua/Munchausen-numbers new file mode 120000 index 0000000000..2170e259d6 --- /dev/null +++ b/Lang/Uiua/Munchausen-numbers @@ -0,0 +1 @@ +../../Task/Munchausen-numbers/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Munching-squares b/Lang/Uiua/Munching-squares new file mode 120000 index 0000000000..65b5e765bd --- /dev/null +++ b/Lang/Uiua/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Musical-scale b/Lang/Uiua/Musical-scale new file mode 120000 index 0000000000..1f1e1695ce --- /dev/null +++ b/Lang/Uiua/Musical-scale @@ -0,0 +1 @@ +../../Task/Musical-scale/Uiua \ No newline at end of file diff --git a/Lang/Uiua/N-queens-problem b/Lang/Uiua/N-queens-problem new file mode 120000 index 0000000000..d8b56e5e2a --- /dev/null +++ b/Lang/Uiua/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Narcissistic-decimal-number b/Lang/Uiua/Narcissistic-decimal-number new file mode 120000 index 0000000000..fa8d4f2d6a --- /dev/null +++ b/Lang/Uiua/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Next-highest-int-from-digits b/Lang/Uiua/Next-highest-int-from-digits new file mode 120000 index 0000000000..c924583411 --- /dev/null +++ b/Lang/Uiua/Next-highest-int-from-digits @@ -0,0 +1 @@ +../../Task/Next-highest-int-from-digits/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Non-continuous-subsequences b/Lang/Uiua/Non-continuous-subsequences new file mode 120000 index 0000000000..cbb45eef3a --- /dev/null +++ b/Lang/Uiua/Non-continuous-subsequences @@ -0,0 +1 @@ +../../Task/Non-continuous-subsequences/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Non-decimal-radices-Input b/Lang/Uiua/Non-decimal-radices-Input new file mode 120000 index 0000000000..4980368463 --- /dev/null +++ b/Lang/Uiua/Non-decimal-radices-Input @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Input/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Non-decimal-radices-Output b/Lang/Uiua/Non-decimal-radices-Output new file mode 120000 index 0000000000..8d901b62f2 --- /dev/null +++ b/Lang/Uiua/Non-decimal-radices-Output @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Output/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Numbers-which-are-not-the-sum-of-distinct-squares b/Lang/Uiua/Numbers-which-are-not-the-sum-of-distinct-squares new file mode 120000 index 0000000000..fd1772b308 --- /dev/null +++ b/Lang/Uiua/Numbers-which-are-not-the-sum-of-distinct-squares @@ -0,0 +1 @@ +../../Task/Numbers-which-are-not-the-sum-of-distinct-squares/Uiua \ No newline at end of file diff --git a/Lang/Uiua/One-dimensional-cellular-automata b/Lang/Uiua/One-dimensional-cellular-automata new file mode 120000 index 0000000000..5df7e9b84a --- /dev/null +++ b/Lang/Uiua/One-dimensional-cellular-automata @@ -0,0 +1 @@ +../../Task/One-dimensional-cellular-automata/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Ordered-words b/Lang/Uiua/Ordered-words new file mode 120000 index 0000000000..7046edd964 --- /dev/null +++ b/Lang/Uiua/Ordered-words @@ -0,0 +1 @@ +../../Task/Ordered-words/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Padovan-sequence b/Lang/Uiua/Padovan-sequence new file mode 120000 index 0000000000..5ff77d41cb --- /dev/null +++ b/Lang/Uiua/Padovan-sequence @@ -0,0 +1 @@ +../../Task/Padovan-sequence/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Pangram-checker b/Lang/Uiua/Pangram-checker new file mode 120000 index 0000000000..f48b39bf42 --- /dev/null +++ b/Lang/Uiua/Pangram-checker @@ -0,0 +1 @@ +../../Task/Pangram-checker/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Parsing-RPN-calculator-algorithm b/Lang/Uiua/Parsing-RPN-calculator-algorithm new file mode 120000 index 0000000000..650f272e3c --- /dev/null +++ b/Lang/Uiua/Parsing-RPN-calculator-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-RPN-calculator-algorithm/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Particle-fountain b/Lang/Uiua/Particle-fountain new file mode 120000 index 0000000000..5a4eedea1a --- /dev/null +++ b/Lang/Uiua/Particle-fountain @@ -0,0 +1 @@ +../../Task/Particle-fountain/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Partition-an-integer-x-into-n-primes b/Lang/Uiua/Partition-an-integer-x-into-n-primes new file mode 120000 index 0000000000..b54ce3d232 --- /dev/null +++ b/Lang/Uiua/Partition-an-integer-x-into-n-primes @@ -0,0 +1 @@ +../../Task/Partition-an-integer-x-into-n-primes/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Partition-function-P b/Lang/Uiua/Partition-function-P new file mode 120000 index 0000000000..e15b2a3f0a --- /dev/null +++ b/Lang/Uiua/Partition-function-P @@ -0,0 +1 @@ +../../Task/Partition-function-P/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Pascal-matrix-generation b/Lang/Uiua/Pascal-matrix-generation new file mode 120000 index 0000000000..d6006d5f28 --- /dev/null +++ b/Lang/Uiua/Pascal-matrix-generation @@ -0,0 +1 @@ +../../Task/Pascal-matrix-generation/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Pascals-triangle b/Lang/Uiua/Pascals-triangle new file mode 120000 index 0000000000..d3ded33bae --- /dev/null +++ b/Lang/Uiua/Pascals-triangle @@ -0,0 +1 @@ +../../Task/Pascals-triangle/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Pascals-triangle-Puzzle b/Lang/Uiua/Pascals-triangle-Puzzle new file mode 120000 index 0000000000..9d1c439151 --- /dev/null +++ b/Lang/Uiua/Pascals-triangle-Puzzle @@ -0,0 +1 @@ +../../Task/Pascals-triangle-Puzzle/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Password-generator b/Lang/Uiua/Password-generator new file mode 120000 index 0000000000..0a559819ad --- /dev/null +++ b/Lang/Uiua/Password-generator @@ -0,0 +1 @@ +../../Task/Password-generator/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Peaceful-chess-queen-armies b/Lang/Uiua/Peaceful-chess-queen-armies new file mode 120000 index 0000000000..e3e9bf7f31 --- /dev/null +++ b/Lang/Uiua/Peaceful-chess-queen-armies @@ -0,0 +1 @@ +../../Task/Peaceful-chess-queen-armies/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Perfect-numbers b/Lang/Uiua/Perfect-numbers new file mode 120000 index 0000000000..45883a0ea8 --- /dev/null +++ b/Lang/Uiua/Perfect-numbers @@ -0,0 +1 @@ +../../Task/Perfect-numbers/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Perfect-shuffle b/Lang/Uiua/Perfect-shuffle new file mode 120000 index 0000000000..85b9185041 --- /dev/null +++ b/Lang/Uiua/Perfect-shuffle @@ -0,0 +1 @@ +../../Task/Perfect-shuffle/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Perfect-totient-numbers b/Lang/Uiua/Perfect-totient-numbers new file mode 120000 index 0000000000..473a593e75 --- /dev/null +++ b/Lang/Uiua/Perfect-totient-numbers @@ -0,0 +1 @@ +../../Task/Perfect-totient-numbers/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Periodic-table b/Lang/Uiua/Periodic-table new file mode 120000 index 0000000000..5e6b72eb1b --- /dev/null +++ b/Lang/Uiua/Periodic-table @@ -0,0 +1 @@ +../../Task/Periodic-table/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Peripheral-drift-illusion b/Lang/Uiua/Peripheral-drift-illusion new file mode 120000 index 0000000000..6946c8b8f1 --- /dev/null +++ b/Lang/Uiua/Peripheral-drift-illusion @@ -0,0 +1 @@ +../../Task/Peripheral-drift-illusion/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Permutations b/Lang/Uiua/Permutations new file mode 120000 index 0000000000..850f4f7144 --- /dev/null +++ b/Lang/Uiua/Permutations @@ -0,0 +1 @@ +../../Task/Permutations/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Pernicious-numbers b/Lang/Uiua/Pernicious-numbers new file mode 120000 index 0000000000..bcc3ebf322 --- /dev/null +++ b/Lang/Uiua/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Phrase-reversals b/Lang/Uiua/Phrase-reversals new file mode 120000 index 0000000000..4584c0fe62 --- /dev/null +++ b/Lang/Uiua/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Pick-random-element b/Lang/Uiua/Pick-random-element new file mode 120000 index 0000000000..e85c1a21e1 --- /dev/null +++ b/Lang/Uiua/Pick-random-element @@ -0,0 +1 @@ +../../Task/Pick-random-element/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Pisano-period b/Lang/Uiua/Pisano-period new file mode 120000 index 0000000000..2e3ec789ad --- /dev/null +++ b/Lang/Uiua/Pisano-period @@ -0,0 +1 @@ +../../Task/Pisano-period/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Plasma-effect b/Lang/Uiua/Plasma-effect new file mode 120000 index 0000000000..ca73067f67 --- /dev/null +++ b/Lang/Uiua/Plasma-effect @@ -0,0 +1 @@ +../../Task/Plasma-effect/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Population-count b/Lang/Uiua/Population-count new file mode 120000 index 0000000000..601ac5e44a --- /dev/null +++ b/Lang/Uiua/Population-count @@ -0,0 +1 @@ +../../Task/Population-count/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Power-set b/Lang/Uiua/Power-set new file mode 120000 index 0000000000..21a40d792f --- /dev/null +++ b/Lang/Uiua/Power-set @@ -0,0 +1 @@ +../../Task/Power-set/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Primality-by-Wilsons-theorem b/Lang/Uiua/Primality-by-Wilsons-theorem new file mode 120000 index 0000000000..8e83e31c35 --- /dev/null +++ b/Lang/Uiua/Primality-by-Wilsons-theorem @@ -0,0 +1 @@ +../../Task/Primality-by-Wilsons-theorem/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Prime-conspiracy b/Lang/Uiua/Prime-conspiracy new file mode 120000 index 0000000000..d1cad5b5e0 --- /dev/null +++ b/Lang/Uiua/Prime-conspiracy @@ -0,0 +1 @@ +../../Task/Prime-conspiracy/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Prime-decomposition b/Lang/Uiua/Prime-decomposition new file mode 120000 index 0000000000..bdff89da46 --- /dev/null +++ b/Lang/Uiua/Prime-decomposition @@ -0,0 +1 @@ +../../Task/Prime-decomposition/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Prime-numbers-whose-neighboring-pairs-are-tetraprimes b/Lang/Uiua/Prime-numbers-whose-neighboring-pairs-are-tetraprimes new file mode 120000 index 0000000000..fead595d8f --- /dev/null +++ b/Lang/Uiua/Prime-numbers-whose-neighboring-pairs-are-tetraprimes @@ -0,0 +1 @@ +../../Task/Prime-numbers-whose-neighboring-pairs-are-tetraprimes/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Prime-triangle b/Lang/Uiua/Prime-triangle new file mode 120000 index 0000000000..59527b37eb --- /dev/null +++ b/Lang/Uiua/Prime-triangle @@ -0,0 +1 @@ +../../Task/Prime-triangle/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Program-termination b/Lang/Uiua/Program-termination new file mode 120000 index 0000000000..58f6f7fb66 --- /dev/null +++ b/Lang/Uiua/Program-termination @@ -0,0 +1 @@ +../../Task/Program-termination/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Proper-divisors b/Lang/Uiua/Proper-divisors new file mode 120000 index 0000000000..94a040a034 --- /dev/null +++ b/Lang/Uiua/Proper-divisors @@ -0,0 +1 @@ +../../Task/Proper-divisors/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Quoting-constructs b/Lang/Uiua/Quoting-constructs new file mode 120000 index 0000000000..0a39b9c1b8 --- /dev/null +++ b/Lang/Uiua/Quoting-constructs @@ -0,0 +1 @@ +../../Task/Quoting-constructs/Uiua \ No newline at end of file diff --git a/Lang/Uiua/RPG-attributes-generator b/Lang/Uiua/RPG-attributes-generator new file mode 120000 index 0000000000..96e8262b6d --- /dev/null +++ b/Lang/Uiua/RPG-attributes-generator @@ -0,0 +1 @@ +../../Task/RPG-attributes-generator/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Radical-of-an-integer b/Lang/Uiua/Radical-of-an-integer new file mode 120000 index 0000000000..dd623262df --- /dev/null +++ b/Lang/Uiua/Radical-of-an-integer @@ -0,0 +1 @@ +../../Task/Radical-of-an-integer/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Random-Latin-squares b/Lang/Uiua/Random-Latin-squares new file mode 120000 index 0000000000..1244042116 --- /dev/null +++ b/Lang/Uiua/Random-Latin-squares @@ -0,0 +1 @@ +../../Task/Random-Latin-squares/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Random-numbers b/Lang/Uiua/Random-numbers new file mode 120000 index 0000000000..bc115ba91a --- /dev/null +++ b/Lang/Uiua/Random-numbers @@ -0,0 +1 @@ +../../Task/Random-numbers/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Real-constants-and-functions b/Lang/Uiua/Real-constants-and-functions new file mode 120000 index 0000000000..fb71bc51b7 --- /dev/null +++ b/Lang/Uiua/Real-constants-and-functions @@ -0,0 +1 @@ +../../Task/Real-constants-and-functions/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Recamans-sequence b/Lang/Uiua/Recamans-sequence new file mode 120000 index 0000000000..fdc4665a6a --- /dev/null +++ b/Lang/Uiua/Recamans-sequence @@ -0,0 +1 @@ +../../Task/Recamans-sequence/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Repeat b/Lang/Uiua/Repeat new file mode 120000 index 0000000000..e75d6dc3ae --- /dev/null +++ b/Lang/Uiua/Repeat @@ -0,0 +1 @@ +../../Task/Repeat/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Reverse-words-in-a-string b/Lang/Uiua/Reverse-words-in-a-string new file mode 120000 index 0000000000..a6f43bc773 --- /dev/null +++ b/Lang/Uiua/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Rosetta-Code-Rank-languages-by-popularity b/Lang/Uiua/Rosetta-Code-Rank-languages-by-popularity new file mode 120000 index 0000000000..582776a4d1 --- /dev/null +++ b/Lang/Uiua/Rosetta-Code-Rank-languages-by-popularity @@ -0,0 +1 @@ +../../Task/Rosetta-Code-Rank-languages-by-popularity/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Run-length-encoding b/Lang/Uiua/Run-length-encoding new file mode 120000 index 0000000000..b6eee5ca86 --- /dev/null +++ b/Lang/Uiua/Run-length-encoding @@ -0,0 +1 @@ +../../Task/Run-length-encoding/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Ruth-Aaron-numbers b/Lang/Uiua/Ruth-Aaron-numbers new file mode 120000 index 0000000000..bbf8bc039a --- /dev/null +++ b/Lang/Uiua/Ruth-Aaron-numbers @@ -0,0 +1 @@ +../../Task/Ruth-Aaron-numbers/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Self-describing-numbers b/Lang/Uiua/Self-describing-numbers new file mode 120000 index 0000000000..158e71854a --- /dev/null +++ b/Lang/Uiua/Self-describing-numbers @@ -0,0 +1 @@ +../../Task/Self-describing-numbers/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Sequence-of-primes-by-trial-division b/Lang/Uiua/Sequence-of-primes-by-trial-division new file mode 120000 index 0000000000..d94d81ea51 --- /dev/null +++ b/Lang/Uiua/Sequence-of-primes-by-trial-division @@ -0,0 +1 @@ +../../Task/Sequence-of-primes-by-trial-division/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Set-puzzle b/Lang/Uiua/Set-puzzle new file mode 120000 index 0000000000..3e3bc1d78f --- /dev/null +++ b/Lang/Uiua/Set-puzzle @@ -0,0 +1 @@ +../../Task/Set-puzzle/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Set-right-adjacent-bits b/Lang/Uiua/Set-right-adjacent-bits new file mode 120000 index 0000000000..902c125b59 --- /dev/null +++ b/Lang/Uiua/Set-right-adjacent-bits @@ -0,0 +1 @@ +../../Task/Set-right-adjacent-bits/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Sexy-primes b/Lang/Uiua/Sexy-primes new file mode 120000 index 0000000000..8d61a811ee --- /dev/null +++ b/Lang/Uiua/Sexy-primes @@ -0,0 +1 @@ +../../Task/Sexy-primes/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Shoelace-formula-for-polygonal-area b/Lang/Uiua/Shoelace-formula-for-polygonal-area new file mode 120000 index 0000000000..d0a37fe60f --- /dev/null +++ b/Lang/Uiua/Shoelace-formula-for-polygonal-area @@ -0,0 +1 @@ +../../Task/Shoelace-formula-for-polygonal-area/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Smith-numbers b/Lang/Uiua/Smith-numbers new file mode 120000 index 0000000000..3e4afb53bf --- /dev/null +++ b/Lang/Uiua/Smith-numbers @@ -0,0 +1 @@ +../../Task/Smith-numbers/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Solve-a-Hidato-puzzle b/Lang/Uiua/Solve-a-Hidato-puzzle new file mode 120000 index 0000000000..961a795fe0 --- /dev/null +++ b/Lang/Uiua/Solve-a-Hidato-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hidato-puzzle/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Solve-a-Numbrix-puzzle b/Lang/Uiua/Solve-a-Numbrix-puzzle new file mode 120000 index 0000000000..d5e755e9d5 --- /dev/null +++ b/Lang/Uiua/Solve-a-Numbrix-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Numbrix-puzzle/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Sort-disjoint-sublist b/Lang/Uiua/Sort-disjoint-sublist new file mode 120000 index 0000000000..247b8fbb37 --- /dev/null +++ b/Lang/Uiua/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Spiral-matrix b/Lang/Uiua/Spiral-matrix new file mode 120000 index 0000000000..58fe68a534 --- /dev/null +++ b/Lang/Uiua/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Split-a-character-string-based-on-change-of-character b/Lang/Uiua/Split-a-character-string-based-on-change-of-character new file mode 120000 index 0000000000..61d4dd8555 --- /dev/null +++ b/Lang/Uiua/Split-a-character-string-based-on-change-of-character @@ -0,0 +1 @@ +../../Task/Split-a-character-string-based-on-change-of-character/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Square-free-integers b/Lang/Uiua/Square-free-integers new file mode 120000 index 0000000000..7a649e9779 --- /dev/null +++ b/Lang/Uiua/Square-free-integers @@ -0,0 +1 @@ +../../Task/Square-free-integers/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Stem-and-leaf-plot b/Lang/Uiua/Stem-and-leaf-plot new file mode 120000 index 0000000000..cfafe7201a --- /dev/null +++ b/Lang/Uiua/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/Uiua \ No newline at end of file diff --git a/Lang/Uiua/String-case b/Lang/Uiua/String-case new file mode 120000 index 0000000000..4362c13413 --- /dev/null +++ b/Lang/Uiua/String-case @@ -0,0 +1 @@ +../../Task/String-case/Uiua \ No newline at end of file diff --git a/Lang/Uiua/String-concatenation b/Lang/Uiua/String-concatenation new file mode 120000 index 0000000000..cd5c2325bd --- /dev/null +++ b/Lang/Uiua/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Uiua \ No newline at end of file diff --git a/Lang/Uiua/String-interpolation-included- b/Lang/Uiua/String-interpolation-included- new file mode 120000 index 0000000000..e880f170b4 --- /dev/null +++ b/Lang/Uiua/String-interpolation-included- @@ -0,0 +1 @@ +../../Task/String-interpolation-included-/Uiua \ No newline at end of file diff --git a/Lang/Uiua/String-matching b/Lang/Uiua/String-matching new file mode 120000 index 0000000000..d45ce27782 --- /dev/null +++ b/Lang/Uiua/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Strip-a-set-of-characters-from-a-string b/Lang/Uiua/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..951d176969 --- /dev/null +++ b/Lang/Uiua/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Sudan-function b/Lang/Uiua/Sudan-function new file mode 120000 index 0000000000..afedd391cb --- /dev/null +++ b/Lang/Uiua/Sudan-function @@ -0,0 +1 @@ +../../Task/Sudan-function/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Sudoku b/Lang/Uiua/Sudoku new file mode 120000 index 0000000000..be7e18a94a --- /dev/null +++ b/Lang/Uiua/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Sum-multiples-of-3-and-5 b/Lang/Uiua/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..1949126562 --- /dev/null +++ b/Lang/Uiua/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Sum-of-elements-below-main-diagonal-of-matrix b/Lang/Uiua/Sum-of-elements-below-main-diagonal-of-matrix new file mode 120000 index 0000000000..37e45429c6 --- /dev/null +++ b/Lang/Uiua/Sum-of-elements-below-main-diagonal-of-matrix @@ -0,0 +1 @@ +../../Task/Sum-of-elements-below-main-diagonal-of-matrix/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Summarize-primes b/Lang/Uiua/Summarize-primes new file mode 120000 index 0000000000..4ad940883d --- /dev/null +++ b/Lang/Uiua/Summarize-primes @@ -0,0 +1 @@ +../../Task/Summarize-primes/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Sylvesters-sequence b/Lang/Uiua/Sylvesters-sequence new file mode 120000 index 0000000000..859c7ca10b --- /dev/null +++ b/Lang/Uiua/Sylvesters-sequence @@ -0,0 +1 @@ +../../Task/Sylvesters-sequence/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Tau-function b/Lang/Uiua/Tau-function new file mode 120000 index 0000000000..314431f8dd --- /dev/null +++ b/Lang/Uiua/Tau-function @@ -0,0 +1 @@ +../../Task/Tau-function/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Test-a-function b/Lang/Uiua/Test-a-function new file mode 120000 index 0000000000..4e61b05504 --- /dev/null +++ b/Lang/Uiua/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Tic-tac-toe b/Lang/Uiua/Tic-tac-toe new file mode 120000 index 0000000000..fc3b26168b --- /dev/null +++ b/Lang/Uiua/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Totient-function b/Lang/Uiua/Totient-function new file mode 120000 index 0000000000..838bb52e2f --- /dev/null +++ b/Lang/Uiua/Totient-function @@ -0,0 +1 @@ +../../Task/Totient-function/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Trigonometric-functions b/Lang/Uiua/Trigonometric-functions new file mode 120000 index 0000000000..07a1fc051e --- /dev/null +++ b/Lang/Uiua/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Truncatable-primes b/Lang/Uiua/Truncatable-primes new file mode 120000 index 0000000000..b02bf04462 --- /dev/null +++ b/Lang/Uiua/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Unprimeable-numbers b/Lang/Uiua/Unprimeable-numbers new file mode 120000 index 0000000000..5a99955431 --- /dev/null +++ b/Lang/Uiua/Unprimeable-numbers @@ -0,0 +1 @@ +../../Task/Unprimeable-numbers/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Validate-International-Securities-Identification-Number b/Lang/Uiua/Validate-International-Securities-Identification-Number new file mode 120000 index 0000000000..6d28391590 --- /dev/null +++ b/Lang/Uiua/Validate-International-Securities-Identification-Number @@ -0,0 +1 @@ +../../Task/Validate-International-Securities-Identification-Number/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Voronoi-diagram b/Lang/Uiua/Voronoi-diagram new file mode 120000 index 0000000000..d3162948cc --- /dev/null +++ b/Lang/Uiua/Voronoi-diagram @@ -0,0 +1 @@ +../../Task/Voronoi-diagram/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Water-collected-between-towers b/Lang/Uiua/Water-collected-between-towers new file mode 120000 index 0000000000..cfd5fa722a --- /dev/null +++ b/Lang/Uiua/Water-collected-between-towers @@ -0,0 +1 @@ +../../Task/Water-collected-between-towers/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Weird-numbers b/Lang/Uiua/Weird-numbers new file mode 120000 index 0000000000..3d24f8a95b --- /dev/null +++ b/Lang/Uiua/Weird-numbers @@ -0,0 +1 @@ +../../Task/Weird-numbers/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Wieferich-primes b/Lang/Uiua/Wieferich-primes new file mode 120000 index 0000000000..b9d2d78697 --- /dev/null +++ b/Lang/Uiua/Wieferich-primes @@ -0,0 +1 @@ +../../Task/Wieferich-primes/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Wireworld b/Lang/Uiua/Wireworld new file mode 120000 index 0000000000..eaa729b6f4 --- /dev/null +++ b/Lang/Uiua/Wireworld @@ -0,0 +1 @@ +../../Task/Wireworld/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Word-frequency b/Lang/Uiua/Word-frequency new file mode 120000 index 0000000000..f59b23af8e --- /dev/null +++ b/Lang/Uiua/Word-frequency @@ -0,0 +1 @@ +../../Task/Word-frequency/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Word-wheel b/Lang/Uiua/Word-wheel new file mode 120000 index 0000000000..f8bafcb6c7 --- /dev/null +++ b/Lang/Uiua/Word-wheel @@ -0,0 +1 @@ +../../Task/Word-wheel/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Yellowstone-sequence b/Lang/Uiua/Yellowstone-sequence new file mode 120000 index 0000000000..0bae4da70f --- /dev/null +++ b/Lang/Uiua/Yellowstone-sequence @@ -0,0 +1 @@ +../../Task/Yellowstone-sequence/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Zebra-puzzle b/Lang/Uiua/Zebra-puzzle new file mode 120000 index 0000000000..cd343323b4 --- /dev/null +++ b/Lang/Uiua/Zebra-puzzle @@ -0,0 +1 @@ +../../Task/Zebra-puzzle/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Zeckendorf-number-representation b/Lang/Uiua/Zeckendorf-number-representation new file mode 120000 index 0000000000..1748bf90ef --- /dev/null +++ b/Lang/Uiua/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Zhang-Suen-thinning-algorithm b/Lang/Uiua/Zhang-Suen-thinning-algorithm new file mode 120000 index 0000000000..a7e773ae5b --- /dev/null +++ b/Lang/Uiua/Zhang-Suen-thinning-algorithm @@ -0,0 +1 @@ +../../Task/Zhang-Suen-thinning-algorithm/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Zig-zag-matrix b/Lang/Uiua/Zig-zag-matrix new file mode 120000 index 0000000000..3d79e2a814 --- /dev/null +++ b/Lang/Uiua/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Uiua \ No newline at end of file diff --git a/Lang/Ultimate++/00-LANG.txt b/Lang/Ultimate++/00-LANG.txt index b340f85de9..a819e23329 100644 --- a/Lang/Ultimate++/00-LANG.txt +++ b/Lang/Ultimate++/00-LANG.txt @@ -23,7 +23,7 @@ https://www.ultimatepp.org/www$uppweb$overview$en-us.html ==Language== This example is a hello world using the Upp namespace. - +
     #include 
     #include 
     
    @@ -39,7 +39,7 @@ CONSOLE_APP_MAIN
     	for(int i = 0; i < cmdline.GetCount(); i++) {
     	}
     }
    -
    +
    {{out}} @@ -51,7 +51,7 @@ and Hello World '''A+B B-A'''   - +
     #include 
     #include 
     #include 
    @@ -69,7 +69,7 @@ CONSOLE_APP_MAIN
     	for(int i = 0; i < cmdline.GetCount(); i++) {
     	}
     }
    -
    +
    {{out}} @@ -84,7 +84,7 @@ CONSOLE_APP_MAIN '''Conditional loop''' - +
     #include 
     #include 
     #include 
    @@ -108,7 +108,7 @@ CONSOLE_APP_MAIN
     	for(int i = 0; i < cmdline.GetCount(); i++) {
     	}
     }
    -
    +
    diff --git a/Lang/Unicon/Circular-primes b/Lang/Unicon/Circular-primes new file mode 120000 index 0000000000..2ebcc862f3 --- /dev/null +++ b/Lang/Unicon/Circular-primes @@ -0,0 +1 @@ +../../Task/Circular-primes/Unicon \ No newline at end of file diff --git a/Lang/Unicon/Deceptive-numbers b/Lang/Unicon/Deceptive-numbers new file mode 120000 index 0000000000..74debdb49f --- /dev/null +++ b/Lang/Unicon/Deceptive-numbers @@ -0,0 +1 @@ +../../Task/Deceptive-numbers/Unicon \ No newline at end of file diff --git a/Lang/Unicon/Emirp-primes b/Lang/Unicon/Emirp-primes new file mode 120000 index 0000000000..63628f22b5 --- /dev/null +++ b/Lang/Unicon/Emirp-primes @@ -0,0 +1 @@ +../../Task/Emirp-primes/Unicon \ No newline at end of file diff --git a/Lang/Unicon/Equal-prime-and-composite-sums b/Lang/Unicon/Equal-prime-and-composite-sums new file mode 120000 index 0000000000..108da6ee4a --- /dev/null +++ b/Lang/Unicon/Equal-prime-and-composite-sums @@ -0,0 +1 @@ +../../Task/Equal-prime-and-composite-sums/Unicon \ No newline at end of file diff --git a/Lang/Unicon/Factorial-primes b/Lang/Unicon/Factorial-primes new file mode 120000 index 0000000000..2f492134d2 --- /dev/null +++ b/Lang/Unicon/Factorial-primes @@ -0,0 +1 @@ +../../Task/Factorial-primes/Unicon \ No newline at end of file diff --git a/Lang/Unicon/Fermat-numbers b/Lang/Unicon/Fermat-numbers new file mode 120000 index 0000000000..18314c4e86 --- /dev/null +++ b/Lang/Unicon/Fermat-numbers @@ -0,0 +1 @@ +../../Task/Fermat-numbers/Unicon \ No newline at end of file diff --git a/Lang/Unicon/Pell-numbers b/Lang/Unicon/Pell-numbers new file mode 120000 index 0000000000..1e5fe97247 --- /dev/null +++ b/Lang/Unicon/Pell-numbers @@ -0,0 +1 @@ +../../Task/Pell-numbers/Unicon \ No newline at end of file diff --git a/Lang/Unicon/Repunit-primes b/Lang/Unicon/Repunit-primes new file mode 120000 index 0000000000..a063ca9ca3 --- /dev/null +++ b/Lang/Unicon/Repunit-primes @@ -0,0 +1 @@ +../../Task/Repunit-primes/Unicon \ No newline at end of file diff --git a/Lang/Unicon/Ultra-useful-primes b/Lang/Unicon/Ultra-useful-primes new file mode 120000 index 0000000000..c78c99febd --- /dev/null +++ b/Lang/Unicon/Ultra-useful-primes @@ -0,0 +1 @@ +../../Task/Ultra-useful-primes/Unicon \ No newline at end of file diff --git a/Lang/Unicon/Unix-ls b/Lang/Unicon/Unix-ls new file mode 120000 index 0000000000..4501440ef6 --- /dev/null +++ b/Lang/Unicon/Unix-ls @@ -0,0 +1 @@ +../../Task/Unix-ls/Unicon \ No newline at end of file diff --git a/Lang/Unicon/Vector b/Lang/Unicon/Vector new file mode 120000 index 0000000000..2c82c9664f --- /dev/null +++ b/Lang/Unicon/Vector @@ -0,0 +1 @@ +../../Task/Vector/Unicon \ No newline at end of file diff --git a/Lang/Unicon/Wagstaff-primes b/Lang/Unicon/Wagstaff-primes new file mode 120000 index 0000000000..9aef3c7dca --- /dev/null +++ b/Lang/Unicon/Wagstaff-primes @@ -0,0 +1 @@ +../../Task/Wagstaff-primes/Unicon \ No newline at end of file diff --git a/Lang/Unison/Spiral-matrix b/Lang/Unison/Spiral-matrix new file mode 120000 index 0000000000..423c950e4b --- /dev/null +++ b/Lang/Unison/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/Unison \ No newline at end of file diff --git a/Lang/UnixPipes/00-LANG.txt b/Lang/UnixPipes/00-LANG.txt index 8a315a0473..421b024690 100644 --- a/Lang/UnixPipes/00-LANG.txt +++ b/Lang/UnixPipes/00-LANG.txt @@ -13,7 +13,7 @@ Using utilities from, [http://packages.debian.org/unstable/utils/moreutils moreu Defining unfold as the opposite of xargs, i.e take a list of arguments and send them one at a time. The definition would be - + |cat unfold num=$1 while read xxx; do @@ -27,7 +27,7 @@ done 4 5 6 7 8 - + == Deleted solutions == We delete a UnixPipes solution when it is too similar to its UNIX Shell equivalent, or when it is incorrect (but the UNIX Shell solution is correct). diff --git a/Lang/Ursalang/Anagrams b/Lang/Ursalang/Anagrams new file mode 120000 index 0000000000..955e3f6b2d --- /dev/null +++ b/Lang/Ursalang/Anagrams @@ -0,0 +1 @@ +../../Task/Anagrams/Ursalang \ No newline at end of file diff --git a/Lang/Ursalang/Averages-Arithmetic-mean b/Lang/Ursalang/Averages-Arithmetic-mean new file mode 120000 index 0000000000..47e790e66c --- /dev/null +++ b/Lang/Ursalang/Averages-Arithmetic-mean @@ -0,0 +1 @@ +../../Task/Averages-Arithmetic-mean/Ursalang \ No newline at end of file diff --git a/Lang/Ursalang/Averages-Mode b/Lang/Ursalang/Averages-Mode new file mode 120000 index 0000000000..3250a246da --- /dev/null +++ b/Lang/Ursalang/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/Ursalang \ No newline at end of file diff --git a/Lang/Ursalang/Averages-Root-mean-square b/Lang/Ursalang/Averages-Root-mean-square new file mode 120000 index 0000000000..1acc742630 --- /dev/null +++ b/Lang/Ursalang/Averages-Root-mean-square @@ -0,0 +1 @@ +../../Task/Averages-Root-mean-square/Ursalang \ No newline at end of file diff --git a/Lang/Ursalang/FizzBuzz b/Lang/Ursalang/FizzBuzz new file mode 120000 index 0000000000..7a0a8b495c --- /dev/null +++ b/Lang/Ursalang/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Ursalang \ No newline at end of file diff --git a/Lang/Ursalang/Generator-Exponential b/Lang/Ursalang/Generator-Exponential new file mode 120000 index 0000000000..4533fcc114 --- /dev/null +++ b/Lang/Ursalang/Generator-Exponential @@ -0,0 +1 @@ +../../Task/Generator-Exponential/Ursalang \ No newline at end of file diff --git a/Lang/Ursalang/Hailstone-sequence b/Lang/Ursalang/Hailstone-sequence new file mode 120000 index 0000000000..fd3a016859 --- /dev/null +++ b/Lang/Ursalang/Hailstone-sequence @@ -0,0 +1 @@ +../../Task/Hailstone-sequence/Ursalang \ No newline at end of file diff --git a/Lang/Ursalang/Loops-Break b/Lang/Ursalang/Loops-Break new file mode 120000 index 0000000000..9956e0ecbe --- /dev/null +++ b/Lang/Ursalang/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/Ursalang \ No newline at end of file diff --git a/Lang/Ursalang/Loops-Continue b/Lang/Ursalang/Loops-Continue new file mode 120000 index 0000000000..b92db2e19a --- /dev/null +++ b/Lang/Ursalang/Loops-Continue @@ -0,0 +1 @@ +../../Task/Loops-Continue/Ursalang \ No newline at end of file diff --git a/Lang/Ursalang/Loops-For b/Lang/Ursalang/Loops-For new file mode 120000 index 0000000000..11a1ba7e0e --- /dev/null +++ b/Lang/Ursalang/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/Ursalang \ No newline at end of file diff --git a/Lang/Ursalang/Loops-While b/Lang/Ursalang/Loops-While new file mode 120000 index 0000000000..45dc0e4ade --- /dev/null +++ b/Lang/Ursalang/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/Ursalang \ No newline at end of file diff --git a/Lang/Ursalang/Man-or-boy-test b/Lang/Ursalang/Man-or-boy-test new file mode 120000 index 0000000000..14bf7f1c8c --- /dev/null +++ b/Lang/Ursalang/Man-or-boy-test @@ -0,0 +1 @@ +../../Task/Man-or-boy-test/Ursalang \ No newline at end of file diff --git a/Lang/Uxntal/00-LANG.txt b/Lang/Uxntal/00-LANG.txt index d0204e9b73..29f2256564 100644 --- a/Lang/Uxntal/00-LANG.txt +++ b/Lang/Uxntal/00-LANG.txt @@ -1,5 +1,7 @@ {{language|Uxntal}} +''For unimplemented tasks see: [https://rosettacode.org/wiki/Tasks_not_implemented_in_Uxntal Uxntal Unimplemened]'' + '''Uxntal''' is the assembly language for the Uxn virtual machine. The VM has 64KiB of addressable memory, two 256-byte stacks (data and return), and a 256-byte block of I/O ports, divided into 16 devices with 16 ports each. The Uxntal assembler features sub-labels, simple lambdas, user-defined macros, and shorthands for common immediate operations. == Uxn VM == @@ -12,10 +14,23 @@ The 256 opcodes are divided into 8 special instructions, and 31 regular instruct == Syntax == +
    +In concatenative programming, there are no precedence rules, the calculations are merely performed in the sequence in which they are presented. The order with which elements come off a stack is known as last in, first out. '''''— [https://wiki.xxiivv.com/site/uxntal_syntax.html Uxntal Syntax]''''' +
    + 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) 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. -For further details on Uxntal syntax, see the [https://wiki.xxiivv.com/site/uxntal_syntax.html syntax page] on the XXIIVV wiki. \ No newline at end of file +For further details on Uxntal syntax, see the [https://wiki.xxiivv.com/site/uxntal_syntax.html syntax page] on the XXIIVV wiki. + +[[Category:Assembler_language]] +[[Category:Assembly]] +[[Category:Esoteric_Languages]] +[[Category:Execution_method/Compiled/Bytecode]] +[[Category:Programming_paradigm/Object-oriented]] +[[Category:Programming_paradigm/Concatenative]] +[[Category:Typing/Unsafe]] +[[Category:Typing/Untyped]] \ No newline at end of file diff --git a/Lang/Uxntal/Array-length b/Lang/Uxntal/Array-length new file mode 120000 index 0000000000..438c43e439 --- /dev/null +++ b/Lang/Uxntal/Array-length @@ -0,0 +1 @@ +../../Task/Array-length/Uxntal \ No newline at end of file diff --git a/Lang/Uxntal/Chaos-game b/Lang/Uxntal/Chaos-game new file mode 120000 index 0000000000..80920dd6ff --- /dev/null +++ b/Lang/Uxntal/Chaos-game @@ -0,0 +1 @@ +../../Task/Chaos-game/Uxntal \ No newline at end of file diff --git a/Lang/Uxntal/Comments b/Lang/Uxntal/Comments new file mode 120000 index 0000000000..b23db936ba --- /dev/null +++ b/Lang/Uxntal/Comments @@ -0,0 +1 @@ +../../Task/Comments/Uxntal \ No newline at end of file diff --git a/Lang/Uxntal/Conditional-structures b/Lang/Uxntal/Conditional-structures new file mode 120000 index 0000000000..75d2f67746 --- /dev/null +++ b/Lang/Uxntal/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/Uxntal \ No newline at end of file diff --git a/Lang/Uxntal/Copy-a-string b/Lang/Uxntal/Copy-a-string new file mode 120000 index 0000000000..00610fac74 --- /dev/null +++ b/Lang/Uxntal/Copy-a-string @@ -0,0 +1 @@ +../../Task/Copy-a-string/Uxntal \ No newline at end of file diff --git a/Lang/Uxntal/Draw-a-pixel b/Lang/Uxntal/Draw-a-pixel deleted file mode 120000 index 68f5f2e311..0000000000 --- a/Lang/Uxntal/Draw-a-pixel +++ /dev/null @@ -1 +0,0 @@ -../../Task/Draw-a-pixel/Uxntal \ No newline at end of file diff --git a/Lang/Uxntal/Fibonacci-sequence b/Lang/Uxntal/Fibonacci-sequence new file mode 120000 index 0000000000..7795c4564a --- /dev/null +++ b/Lang/Uxntal/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/Uxntal \ No newline at end of file diff --git a/Lang/Uxntal/Flow-control-structures b/Lang/Uxntal/Flow-control-structures new file mode 120000 index 0000000000..db95ed817d --- /dev/null +++ b/Lang/Uxntal/Flow-control-structures @@ -0,0 +1 @@ +../../Task/Flow-control-structures/Uxntal \ No newline at end of file diff --git a/Lang/Uxntal/Hello-world-Graphical b/Lang/Uxntal/Hello-world-Graphical new file mode 120000 index 0000000000..2a5fadb101 --- /dev/null +++ b/Lang/Uxntal/Hello-world-Graphical @@ -0,0 +1 @@ +../../Task/Hello-world-Graphical/Uxntal \ No newline at end of file diff --git a/Lang/Uxntal/Hello-world-Standard-error b/Lang/Uxntal/Hello-world-Standard-error new file mode 120000 index 0000000000..be0ab3efa0 --- /dev/null +++ b/Lang/Uxntal/Hello-world-Standard-error @@ -0,0 +1 @@ +../../Task/Hello-world-Standard-error/Uxntal \ No newline at end of file diff --git a/Lang/Uxntal/Hello-world-Text b/Lang/Uxntal/Hello-world-Text deleted file mode 120000 index 9024a6cde4..0000000000 --- a/Lang/Uxntal/Hello-world-Text +++ /dev/null @@ -1 +0,0 @@ -../../Task/Hello-world-Text/Uxntal \ No newline at end of file diff --git a/Lang/Uxntal/Integer-sequence b/Lang/Uxntal/Integer-sequence new file mode 120000 index 0000000000..6d76150081 --- /dev/null +++ b/Lang/Uxntal/Integer-sequence @@ -0,0 +1 @@ +../../Task/Integer-sequence/Uxntal \ No newline at end of file diff --git a/Lang/Uxntal/Loops-Break b/Lang/Uxntal/Loops-Break new file mode 120000 index 0000000000..5d6d57196c --- /dev/null +++ b/Lang/Uxntal/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/Uxntal \ No newline at end of file diff --git a/Lang/Uxntal/Loops-Continue b/Lang/Uxntal/Loops-Continue new file mode 120000 index 0000000000..88d5768874 --- /dev/null +++ b/Lang/Uxntal/Loops-Continue @@ -0,0 +1 @@ +../../Task/Loops-Continue/Uxntal \ No newline at end of file diff --git a/Lang/Uxntal/Loops-Do-while b/Lang/Uxntal/Loops-Do-while new file mode 120000 index 0000000000..a3d655278d --- /dev/null +++ b/Lang/Uxntal/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/Uxntal \ No newline at end of file diff --git a/Lang/Uxntal/Loops-For-with-a-specified-step b/Lang/Uxntal/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..4f79f37c9f --- /dev/null +++ b/Lang/Uxntal/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/Uxntal \ No newline at end of file diff --git a/Lang/Uxntal/Loops-Foreach b/Lang/Uxntal/Loops-Foreach new file mode 120000 index 0000000000..f8f61da6a7 --- /dev/null +++ b/Lang/Uxntal/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/Uxntal \ No newline at end of file diff --git a/Lang/Uxntal/Loops-N-plus-one-half b/Lang/Uxntal/Loops-N-plus-one-half new file mode 120000 index 0000000000..f7ee606c95 --- /dev/null +++ b/Lang/Uxntal/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/Uxntal \ No newline at end of file diff --git a/Lang/Uxntal/Loops-While b/Lang/Uxntal/Loops-While new file mode 120000 index 0000000000..f8307c2951 --- /dev/null +++ b/Lang/Uxntal/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/Uxntal \ No newline at end of file diff --git a/Lang/Uxntal/Quine b/Lang/Uxntal/Quine new file mode 120000 index 0000000000..9f3a4ca4d4 --- /dev/null +++ b/Lang/Uxntal/Quine @@ -0,0 +1 @@ +../../Task/Quine/Uxntal \ No newline at end of file diff --git a/Lang/Uxntal/Stack-traces b/Lang/Uxntal/Stack-traces new file mode 120000 index 0000000000..0b9cf24839 --- /dev/null +++ b/Lang/Uxntal/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/Uxntal \ No newline at end of file diff --git a/Lang/Uxntal/String-length b/Lang/Uxntal/String-length new file mode 120000 index 0000000000..8dd88d3b90 --- /dev/null +++ b/Lang/Uxntal/String-length @@ -0,0 +1 @@ +../../Task/String-length/Uxntal \ No newline at end of file diff --git a/Lang/Uxntal/Weird-numbers b/Lang/Uxntal/Weird-numbers new file mode 120000 index 0000000000..1bddac81d2 --- /dev/null +++ b/Lang/Uxntal/Weird-numbers @@ -0,0 +1 @@ +../../Task/Weird-numbers/Uxntal \ No newline at end of file diff --git a/Lang/V-(Vlang)/00-LANG.txt b/Lang/V-(Vlang)/00-LANG.txt index 9a2f5797f1..56c1cc8279 100644 --- a/Lang/V-(Vlang)/00-LANG.txt +++ b/Lang/V-(Vlang)/00-LANG.txt @@ -13,7 +13,7 @@ ''Simple, fast, safe, compiled. For developing maintainable software.''

    -'''Note: V is also known as Vlang. There was a language naming collision, so V (Vlang) was chosen.''' +'''Note: V (or Vlang). There was a language naming collision, so V (Vlang) was chosen.''' V (Vlang) is used here on Rosetta Code to disambiguate from the other language called [[:Category:V|V]]. @@ -21,13 +21,15 @@ V is an easier to learn, read, and use language. [https://vlang.io V] first appeared in 2019 in a trial web sandbox, "The V Playground". -V's design has been influenced by Go, Oberon, Rust, Swift, Kotlin, and Python. [https://github.com/vlang/v/wiki/FAQ For V's FAQ] +V's design and history has been influenced by Go, C, Oberon, Rust, Swift, Kotlin, and Python. -V's sources are published at [https://github.com/vlang/v GitHub], presently on version [https://github.com/vlang/v/releases 0.4.x]. +V's sources are published at [https://github.com/vlang/v GitHub], presently on version [https://github.com/vlang/v/releases 0.5.x]. + +V's [https://github.com/vlang/v/wiki/FAQ FAQ] and [https://github.com/vlang/v/blob/master/ROADMAP.md roadmap] to see its validity, promise, and delivery of features. V's compiler tool is similar in implementation to a multi purpose command processor: ''prompt$ v help'' -V language review and documentation are [https://github.com/vlang/v/blob/master/doc/docs.md here]. +V language review and documentation is [https://github.com/vlang/v/blob/master/doc/docs.md here] for the professional, student, or as a hobby. ==Helpful links== * [https://en.everybodywiki.com/V_(programming_language) V in Wiki] @@ -35,59 +37,45 @@ V language review and documentation are [https://github.com/vlang/v/blob/master/ * [https://www.youtube.com/watch?v=pchEsYwA74Q V language overview and introduction] on behalf of the Sydney Computing Society * [https://www.youtube.com/watch?v=_dIAcNp9bJs V language overview and presentation] for IBM * Some of the code snippets are available at the archived [//github.com/v-community/v_rosetta V-Community (V Rosetta) GitHub] +* For venturing into how to contribute, join, or help the V project can be found [https://github.com/vlang/v/blob/master/CONTRIBUTING.md#how-to-help-and-contribute-to-the-v-project here]. * More info on the below can be found at [https://modules.vlang.io/ modules used by V] {| class="wikitable" -! No. !! Module name !! !! No. !! Module name +! No. !! Module name !! !! No. !! Module name !! !! No. !! Module name |- -| 1 || [https://rosettacode.org/wiki/Category:Vlang-arrays arrays] || || 2 || [https://rosettacode.org/wiki/Category:Vlang-benchmark benchmark] +| 1 || [https://modules.vlang.io/arrays.html arrays] || || 2 || [https://modules.vlang.io/benchmark.html benchmark] || || 3 || [https://modules.vlang.io/bitfield.html bifield] |- -| 3 || [https://rosettacode.org/wiki/Category:Vlang-bifield bifield] || || 4 || [https://rosettacode.org/wiki/Category:Vlang-cli cli] +| 4 || [https://modules.vlang.io/cli.html cli] || || 5 || [https://modules.vlang.io/clipboard.html clipboard] || || 6 || [https://modules.vlang.io/compress.html compress] |- -| 5 || [https://rosettacode.org/wiki/Category:Vlang-clipboard clipboard] || || 6 || [https://rosettacode.org/wiki/Category:Vlang-compress compress] +| 7 || [https://modules.vlang.io/context.html context] || || 8 || [https://modules.vlang.io/crypto.html crypto] || || 9 || [https://modules.vlang.io/net.websocket.html websocket] |- -| 7 || [https://rosettacode.org/wiki/Category:Vlang-context context] || || 8 || [https://rosettacode.org/wiki/Category:Vlang-crypto crypto] +| 10 || [https://modules.vlang.io/datatypes.html datatypes] || || 11 || [https://modules.vlang.io/main.html main] || || 12 || [https://modules.vlang.io/dl.html dl] |- -| 9 || [https://rosettacode.org/wiki/Category:Vlang-darwin darwin] || || 10 || [https://rosettacode.org/wiki/Category:Vlang-datatypes datatypes] +| 13 || [https://modules.vlang.io/dlmalloc.html dlmalloc] || || 14 || [https://modules.vlang.io/encoding.html encoding] || || 15 || [https://modules.vlang.io/eventbus.html eventbus] |- -| 11 || [https://rosettacode.org/wiki/Category:Vlang-main main] || || 12 || [https://rosettacode.org/wiki/Category:Vlang-dl dl] +| 16 || [https://modules.vlang.io/flag.html flag] || || 17 || [https://modules.vlang.io/fontstash.html fontstash] || || 18 || [https://modules.vlang.io/gg.html gg] |- -| 13 || [https://rosettacode.org/wiki/Category:Vlang-dlmalloc dlmalloc] || || 14 || [https://rosettacode.org/wiki/Category:Vlang-encoding encoding] +| 19 || [https://modules.vlang.io/gx.html gx] || || 20 || [https://modules.vlang.io/hash.html hash] || || 21 || [https://modules.vlang.io/io.html io] |- -| 15 || [https://rosettacode.org/wiki/Category:Vlang-eventbus eventbus] || || 16 || [https://rosettacode.org/wiki/Category:Vlang-flag flag] +| 22 || [https://modules.vlang.io/json.html json] || || 23 || [https://modules.vlang.io/log.html log] || || 24 || [https://modules.vlang.io/math.html math] |- -| 17 || [https://rosettacode.org/wiki/Category:Vlang-fontstash fontstash] || || 18 || [https://rosettacode.org/wiki/Category:Vlang-gg gg] +| 25 || [https://modules.vlang.io/db.mssql.html mssql] || || 26 || [https://modules.vlang.io/db.mysql.html mysql] || || 27 || [https://modules.vlang.io/net.html net] |- -| 19 || [https://rosettacode.org/wiki/Category:Vlang-gx gx] || || 20 || [https://rosettacode.org/wiki/Category:Vlang-crypto hash] +| 28 || [https://modules.vlang.io/orm.html orm] || || 29 || [https://modules.vlang.io/os.html os] || || 30 || [https://modules.vlang.io/pg.html pg] |- -| 21 || [https://rosettacode.org/wiki/Category:Vlang-io io] || || 22 || [https://rosettacode.org/wiki/Category:Vlang-json json] +| 31 || [https://modules.vlang.io/picoev.html picoev] || || 32 || [https://modules.vlang.io/veb.html veb] || || 33 || [https://modules.vlang.io/picohttpparser.html picohttpparser] |- -| 23 || [https://rosettacode.org/wiki/Category:Vlang-log log] || || 24 || [https://rosettacode.org/wiki/Category:Vlang-math math] +| 34 || [https://modules.vlang.io/rand.html rand]|| || 35 || [https://modules.vlang.io/readline.html readline] || || 36 || [https://modules.vlang.io/regex.html regex] |- -| 25 || [https://rosettacode.org/wiki/Category:Vlang-mssql mssql] || || 26 || [https://rosettacode.org/wiki/Category:Vlang-mysql mysql] +| 37 || [https://modules.vlang.io/runtime.html runtime] || || 38 || [https://modules.vlang.io/semver.html semver] || || 39 || [https://modules.vlang.io/sokol.sapp.html sokol.sapp] |- -| 27 || [https://rosettacode.org/wiki/Category:Vlang-net net] || || 28 || [https://rosettacode.org/wiki/Category:Vlang-orm orm] +| 40 || [https://modules.vlang.io/db.sqlite.html sqlite] || || 41 || [https://modules.vlang.io/stbi.html stbi] || || 42 || [https://modules.vlang.io/strconv.html strconv] |- -| 29 || [https://rosettacode.org/wiki/Category:Vlang-os os] || || 30 || [https://rosettacode.org/wiki/Category:Vlang-pg pg] +| 43 || [https://modules.vlang.io/strings.html strings] || || 44 || [https://modules.vlang.io/sync.html sync] || || 45 || [https://modules.vlang.io/szip.html szip] |- -| 31 || [https://rosettacode.org/wiki/Category:Vlang-picoev picoev] || || 32 || [https://rosettacode.org/wiki/Category:Vlang-event picoev] +| 46 || [https://modules.vlang.io/term.html term] || || 47 || [https://modules.vlang.io/time.html time] || || 48 || [https://modules.vlang.io/toml.html toml] |- -| 33 || [https://rosettacode.org/wiki/Category:Vlang-picohttpparser picohttpparser] || || 34 || [https://rosettacode.org/wiki/Category:Vlang-rand rand] -|- -| 35 || [https://rosettacode.org/wiki/Category:Vlang-readline readline] || || 36 || [https://rosettacode.org/wiki/Category:Vlang-regex regex] -|- -| 37 || [https://rosettacode.org/wiki/Category:Vlang-runtime runtime] || || 38 || [https://rosettacode.org/wiki/Category:Vlang-semver semver] -|- -| 39 || [https://rosettacode.org/wiki/Category:Vlang-sokol sokol] || || 40 || [https://rosettacode.org/wiki/Category:Vlang-sqlite sqlite] -|- -| 41 || [https://rosettacode.org/wiki/Category:Vlang-stbi stbi] || || 42 || [https://rosettacode.org/wiki/Category:Vlang-strconv strconv] -|- -| 43 || [https://rosettacode.org/wiki/Category:Vlang-strings strings] || || 44 || [https://rosettacode.org/wiki/Category:Vlang-sync sync] -|- -| 45 || [https://rosettacode.org/wiki/Category:Vlang-szip szip] || || 46 || [https://rosettacode.org/wiki/Category:Vlang-term term] -|- -| 47 || [https://rosettacode.org/wiki/Category:Vlang-time time] || || 48 || [https://rosettacode.org/wiki/Category:Vlang-toml toml] -|- -| 49 || [https://rosettacode.org/wiki/Category:Vlang-vweb vweb] || || 50 || [https://rosettacode.org/wiki/Category:Vlang-wasm wasm] +| 49 || [https://modules.vlang.io/vweb.html vweb] || || 50 || [https://modules.vlang.io/wasm.html wasm] || || 51 || [https://modules.vlang.io/maps.html maps] |- +| 52 || [https://modules.vlang.io/sokol.audio.html sokol.audio] || || 53 || [https://modules.vlang.io/x.ttf.html ttf] || || 54 || [https://modules.vlang.io/x.json2.html json2] |} \ No newline at end of file diff --git a/Lang/V-(Vlang)/15-puzzle-solver b/Lang/V-(Vlang)/15-puzzle-solver new file mode 120000 index 0000000000..9193bcde1c --- /dev/null +++ b/Lang/V-(Vlang)/15-puzzle-solver @@ -0,0 +1 @@ +../../Task/15-puzzle-solver/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Accumulator-factory b/Lang/V-(Vlang)/Accumulator-factory new file mode 120000 index 0000000000..20257d9d8b --- /dev/null +++ b/Lang/V-(Vlang)/Accumulator-factory @@ -0,0 +1 @@ +../../Task/Accumulator-factory/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Add-a-variable-to-a-class-instance-at-runtime b/Lang/V-(Vlang)/Add-a-variable-to-a-class-instance-at-runtime new file mode 120000 index 0000000000..dccc76d376 --- /dev/null +++ b/Lang/V-(Vlang)/Add-a-variable-to-a-class-instance-at-runtime @@ -0,0 +1 @@ +../../Task/Add-a-variable-to-a-class-instance-at-runtime/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Animate-a-pendulum b/Lang/V-(Vlang)/Animate-a-pendulum new file mode 120000 index 0000000000..87bb2b5f80 --- /dev/null +++ b/Lang/V-(Vlang)/Animate-a-pendulum @@ -0,0 +1 @@ +../../Task/Animate-a-pendulum/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Apply-a-callback-to-an-array b/Lang/V-(Vlang)/Apply-a-callback-to-an-array new file mode 120000 index 0000000000..8b7f34e888 --- /dev/null +++ b/Lang/V-(Vlang)/Apply-a-callback-to-an-array @@ -0,0 +1 @@ +../../Task/Apply-a-callback-to-an-array/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Approximate-equality b/Lang/V-(Vlang)/Approximate-equality new file mode 120000 index 0000000000..ba99a599b6 --- /dev/null +++ b/Lang/V-(Vlang)/Approximate-equality @@ -0,0 +1 @@ +../../Task/Approximate-equality/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Archimedean-spiral b/Lang/V-(Vlang)/Archimedean-spiral new file mode 120000 index 0000000000..0915aa0768 --- /dev/null +++ b/Lang/V-(Vlang)/Archimedean-spiral @@ -0,0 +1 @@ +../../Task/Archimedean-spiral/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Arithmetic-derivative b/Lang/V-(Vlang)/Arithmetic-derivative new file mode 120000 index 0000000000..0d28ff0c59 --- /dev/null +++ b/Lang/V-(Vlang)/Arithmetic-derivative @@ -0,0 +1 @@ +../../Task/Arithmetic-derivative/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Best-shuffle b/Lang/V-(Vlang)/Best-shuffle new file mode 120000 index 0000000000..a5a48fba81 --- /dev/null +++ b/Lang/V-(Vlang)/Best-shuffle @@ -0,0 +1 @@ +../../Task/Best-shuffle/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Bioinformatics-base-count b/Lang/V-(Vlang)/Bioinformatics-base-count deleted file mode 120000 index 93867218eb..0000000000 --- a/Lang/V-(Vlang)/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Bitcoin-address-validation b/Lang/V-(Vlang)/Bitcoin-address-validation new file mode 120000 index 0000000000..28da42f695 --- /dev/null +++ b/Lang/V-(Vlang)/Bitcoin-address-validation @@ -0,0 +1 @@ +../../Task/Bitcoin-address-validation/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Bitwise-operations b/Lang/V-(Vlang)/Bitwise-operations new file mode 120000 index 0000000000..e781b4c06c --- /dev/null +++ b/Lang/V-(Vlang)/Bitwise-operations @@ -0,0 +1 @@ +../../Task/Bitwise-operations/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Box-the-compass b/Lang/V-(Vlang)/Box-the-compass new file mode 120000 index 0000000000..8aa45acb1f --- /dev/null +++ b/Lang/V-(Vlang)/Box-the-compass @@ -0,0 +1 @@ +../../Task/Box-the-compass/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Burrows-Wheeler-transform b/Lang/V-(Vlang)/Burrows-Wheeler-transform new file mode 120000 index 0000000000..c6a4d26892 --- /dev/null +++ b/Lang/V-(Vlang)/Burrows-Wheeler-transform @@ -0,0 +1 @@ +../../Task/Burrows-Wheeler-transform/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Canonicalize-CIDR b/Lang/V-(Vlang)/Canonicalize-CIDR new file mode 120000 index 0000000000..42ce54344e --- /dev/null +++ b/Lang/V-(Vlang)/Canonicalize-CIDR @@ -0,0 +1 @@ +../../Task/Canonicalize-CIDR/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Classes b/Lang/V-(Vlang)/Classes new file mode 120000 index 0000000000..a7d339230e --- /dev/null +++ b/Lang/V-(Vlang)/Classes @@ -0,0 +1 @@ +../../Task/Classes/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Closures-Value-capture b/Lang/V-(Vlang)/Closures-Value-capture new file mode 120000 index 0000000000..d671104741 --- /dev/null +++ b/Lang/V-(Vlang)/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Color-wheel b/Lang/V-(Vlang)/Color-wheel new file mode 120000 index 0000000000..b828d5a770 --- /dev/null +++ b/Lang/V-(Vlang)/Color-wheel @@ -0,0 +1 @@ +../../Task/Color-wheel/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Compile-time-calculation b/Lang/V-(Vlang)/Compile-time-calculation new file mode 120000 index 0000000000..1ec9e378fa --- /dev/null +++ b/Lang/V-(Vlang)/Compile-time-calculation @@ -0,0 +1 @@ +../../Task/Compile-time-calculation/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Constrained-genericity b/Lang/V-(Vlang)/Constrained-genericity new file mode 120000 index 0000000000..af413abe8c --- /dev/null +++ b/Lang/V-(Vlang)/Constrained-genericity @@ -0,0 +1 @@ +../../Task/Constrained-genericity/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Convert-seconds-to-compound-duration b/Lang/V-(Vlang)/Convert-seconds-to-compound-duration new file mode 120000 index 0000000000..90e9599792 --- /dev/null +++ b/Lang/V-(Vlang)/Convert-seconds-to-compound-duration @@ -0,0 +1 @@ +../../Task/Convert-seconds-to-compound-duration/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Create-an-object-at-a-given-address b/Lang/V-(Vlang)/Create-an-object-at-a-given-address new file mode 120000 index 0000000000..2a735f50a4 --- /dev/null +++ b/Lang/V-(Vlang)/Create-an-object-at-a-given-address @@ -0,0 +1 @@ +../../Task/Create-an-object-at-a-given-address/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/De-Bruijn-sequences b/Lang/V-(Vlang)/De-Bruijn-sequences new file mode 120000 index 0000000000..03d47939a3 --- /dev/null +++ b/Lang/V-(Vlang)/De-Bruijn-sequences @@ -0,0 +1 @@ +../../Task/De-Bruijn-sequences/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Death-Star b/Lang/V-(Vlang)/Death-Star new file mode 120000 index 0000000000..ed8ea3e0a6 --- /dev/null +++ b/Lang/V-(Vlang)/Death-Star @@ -0,0 +1 @@ +../../Task/Death-Star/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Define-a-primitive-data-type b/Lang/V-(Vlang)/Define-a-primitive-data-type new file mode 120000 index 0000000000..aebf4cbe69 --- /dev/null +++ b/Lang/V-(Vlang)/Define-a-primitive-data-type @@ -0,0 +1 @@ +../../Task/Define-a-primitive-data-type/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Dijkstras-algorithm b/Lang/V-(Vlang)/Dijkstras-algorithm new file mode 120000 index 0000000000..c6cb06de44 --- /dev/null +++ b/Lang/V-(Vlang)/Dijkstras-algorithm @@ -0,0 +1 @@ +../../Task/Dijkstras-algorithm/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Dragon-curve b/Lang/V-(Vlang)/Dragon-curve new file mode 120000 index 0000000000..ea14877291 --- /dev/null +++ b/Lang/V-(Vlang)/Dragon-curve @@ -0,0 +1 @@ +../../Task/Dragon-curve/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Draw-a-cuboid b/Lang/V-(Vlang)/Draw-a-cuboid new file mode 120000 index 0000000000..675b202e8b --- /dev/null +++ b/Lang/V-(Vlang)/Draw-a-cuboid @@ -0,0 +1 @@ +../../Task/Draw-a-cuboid/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Draw-a-rotating-cube b/Lang/V-(Vlang)/Draw-a-rotating-cube new file mode 120000 index 0000000000..c731b8a529 --- /dev/null +++ b/Lang/V-(Vlang)/Draw-a-rotating-cube @@ -0,0 +1 @@ +../../Task/Draw-a-rotating-cube/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Dutch-national-flag-problem b/Lang/V-(Vlang)/Dutch-national-flag-problem new file mode 120000 index 0000000000..826568fc3d --- /dev/null +++ b/Lang/V-(Vlang)/Dutch-national-flag-problem @@ -0,0 +1 @@ +../../Task/Dutch-national-flag-problem/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Dynamic-variable-names b/Lang/V-(Vlang)/Dynamic-variable-names new file mode 120000 index 0000000000..59780bc7d8 --- /dev/null +++ b/Lang/V-(Vlang)/Dynamic-variable-names @@ -0,0 +1 @@ +../../Task/Dynamic-variable-names/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Eertree b/Lang/V-(Vlang)/Eertree new file mode 120000 index 0000000000..df3a9103a6 --- /dev/null +++ b/Lang/V-(Vlang)/Eertree @@ -0,0 +1 @@ +../../Task/Eertree/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Elementary-cellular-automaton-Random-number-generator b/Lang/V-(Vlang)/Elementary-cellular-automaton-Random-number-generator new file mode 120000 index 0000000000..d02a93aeca --- /dev/null +++ b/Lang/V-(Vlang)/Elementary-cellular-automaton-Random-number-generator @@ -0,0 +1 @@ +../../Task/Elementary-cellular-automaton-Random-number-generator/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Enumerations b/Lang/V-(Vlang)/Enumerations new file mode 120000 index 0000000000..711e1f8ea0 --- /dev/null +++ b/Lang/V-(Vlang)/Enumerations @@ -0,0 +1 @@ +../../Task/Enumerations/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Execute-HQ9+ b/Lang/V-(Vlang)/Execute-HQ9+ new file mode 120000 index 0000000000..cecaa41a14 --- /dev/null +++ b/Lang/V-(Vlang)/Execute-HQ9+ @@ -0,0 +1 @@ +../../Task/Execute-HQ9+/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Exponentiation-with-infix-operators-in-or-operating-on-the-base b/Lang/V-(Vlang)/Exponentiation-with-infix-operators-in-or-operating-on-the-base new file mode 120000 index 0000000000..119da73572 --- /dev/null +++ b/Lang/V-(Vlang)/Exponentiation-with-infix-operators-in-or-operating-on-the-base @@ -0,0 +1 @@ +../../Task/Exponentiation-with-infix-operators-in-or-operating-on-the-base/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Find-Chess960-starting-position-identifier b/Lang/V-(Vlang)/Find-Chess960-starting-position-identifier new file mode 120000 index 0000000000..b88e0a4eb1 --- /dev/null +++ b/Lang/V-(Vlang)/Find-Chess960-starting-position-identifier @@ -0,0 +1 @@ +../../Task/Find-Chess960-starting-position-identifier/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Find-the-last-Sunday-of-each-month b/Lang/V-(Vlang)/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..8c3dbc9a79 --- /dev/null +++ b/Lang/V-(Vlang)/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Five-weekends b/Lang/V-(Vlang)/Five-weekends new file mode 120000 index 0000000000..ed2a49051d --- /dev/null +++ b/Lang/V-(Vlang)/Five-weekends @@ -0,0 +1 @@ +../../Task/Five-weekends/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Fivenum b/Lang/V-(Vlang)/Fivenum new file mode 120000 index 0000000000..77154f6b56 --- /dev/null +++ b/Lang/V-(Vlang)/Fivenum @@ -0,0 +1 @@ +../../Task/Fivenum/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Flipping-bits-game b/Lang/V-(Vlang)/Flipping-bits-game new file mode 120000 index 0000000000..f272f02e11 --- /dev/null +++ b/Lang/V-(Vlang)/Flipping-bits-game @@ -0,0 +1 @@ +../../Task/Flipping-bits-game/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Floyds-triangle b/Lang/V-(Vlang)/Floyds-triangle new file mode 120000 index 0000000000..cc0e0a9649 --- /dev/null +++ b/Lang/V-(Vlang)/Floyds-triangle @@ -0,0 +1 @@ +../../Task/Floyds-triangle/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Galton-box-animation b/Lang/V-(Vlang)/Galton-box-animation new file mode 120000 index 0000000000..2caf8cb18c --- /dev/null +++ b/Lang/V-(Vlang)/Galton-box-animation @@ -0,0 +1 @@ +../../Task/Galton-box-animation/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Generate-random-chess-position b/Lang/V-(Vlang)/Generate-random-chess-position new file mode 120000 index 0000000000..7687c7236a --- /dev/null +++ b/Lang/V-(Vlang)/Generate-random-chess-position @@ -0,0 +1 @@ +../../Task/Generate-random-chess-position/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Get-system-command-output b/Lang/V-(Vlang)/Get-system-command-output new file mode 120000 index 0000000000..1b29764574 --- /dev/null +++ b/Lang/V-(Vlang)/Get-system-command-output @@ -0,0 +1 @@ +../../Task/Get-system-command-output/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Hash-join b/Lang/V-(Vlang)/Hash-join new file mode 120000 index 0000000000..a28257577b --- /dev/null +++ b/Lang/V-(Vlang)/Hash-join @@ -0,0 +1 @@ +../../Task/Hash-join/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Hello-world-Standard-error b/Lang/V-(Vlang)/Hello-world-Standard-error new file mode 120000 index 0000000000..f1aa7945d1 --- /dev/null +++ b/Lang/V-(Vlang)/Hello-world-Standard-error @@ -0,0 +1 @@ +../../Task/Hello-world-Standard-error/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Higher-order-functions b/Lang/V-(Vlang)/Higher-order-functions new file mode 120000 index 0000000000..a6c0b9843e --- /dev/null +++ b/Lang/V-(Vlang)/Higher-order-functions @@ -0,0 +1 @@ +../../Task/Higher-order-functions/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Hilbert-curve b/Lang/V-(Vlang)/Hilbert-curve new file mode 120000 index 0000000000..d691e8f108 --- /dev/null +++ b/Lang/V-(Vlang)/Hilbert-curve @@ -0,0 +1 @@ +../../Task/Hilbert-curve/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Humble-numbers b/Lang/V-(Vlang)/Humble-numbers new file mode 120000 index 0000000000..c32de84293 --- /dev/null +++ b/Lang/V-(Vlang)/Humble-numbers @@ -0,0 +1 @@ +../../Task/Humble-numbers/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Idiomatically-determine-all-the-lowercase-and-uppercase-letters b/Lang/V-(Vlang)/Idiomatically-determine-all-the-lowercase-and-uppercase-letters new file mode 120000 index 0000000000..efa66c489c --- /dev/null +++ b/Lang/V-(Vlang)/Idiomatically-determine-all-the-lowercase-and-uppercase-letters @@ -0,0 +1 @@ +../../Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Include-a-file b/Lang/V-(Vlang)/Include-a-file new file mode 120000 index 0000000000..439a7ac6c3 --- /dev/null +++ b/Lang/V-(Vlang)/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Inheritance-Multiple b/Lang/V-(Vlang)/Inheritance-Multiple new file mode 120000 index 0000000000..5c8421d069 --- /dev/null +++ b/Lang/V-(Vlang)/Inheritance-Multiple @@ -0,0 +1 @@ +../../Task/Inheritance-Multiple/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Inheritance-Single b/Lang/V-(Vlang)/Inheritance-Single new file mode 120000 index 0000000000..e9a1dd6d9f --- /dev/null +++ b/Lang/V-(Vlang)/Inheritance-Single @@ -0,0 +1 @@ +../../Task/Inheritance-Single/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Integer-comparison b/Lang/V-(Vlang)/Integer-comparison new file mode 120000 index 0000000000..0152b2d289 --- /dev/null +++ b/Lang/V-(Vlang)/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Juggler-sequence b/Lang/V-(Vlang)/Juggler-sequence new file mode 120000 index 0000000000..56d41efb28 --- /dev/null +++ b/Lang/V-(Vlang)/Juggler-sequence @@ -0,0 +1 @@ +../../Task/Juggler-sequence/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Knights-tour b/Lang/V-(Vlang)/Knights-tour new file mode 120000 index 0000000000..542607dce0 --- /dev/null +++ b/Lang/V-(Vlang)/Knights-tour @@ -0,0 +1 @@ +../../Task/Knights-tour/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/LU-decomposition b/Lang/V-(Vlang)/LU-decomposition new file mode 120000 index 0000000000..1eb080d8ba --- /dev/null +++ b/Lang/V-(Vlang)/LU-decomposition @@ -0,0 +1 @@ +../../Task/LU-decomposition/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/LZW-compression b/Lang/V-(Vlang)/LZW-compression new file mode 120000 index 0000000000..36e201b60a --- /dev/null +++ b/Lang/V-(Vlang)/LZW-compression @@ -0,0 +1 @@ +../../Task/LZW-compression/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Langtons-ant b/Lang/V-(Vlang)/Langtons-ant new file mode 120000 index 0000000000..ccce40cc4e --- /dev/null +++ b/Lang/V-(Vlang)/Langtons-ant @@ -0,0 +1 @@ +../../Task/Langtons-ant/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Legendre-prime-counting-function b/Lang/V-(Vlang)/Legendre-prime-counting-function new file mode 120000 index 0000000000..ca54942178 --- /dev/null +++ b/Lang/V-(Vlang)/Legendre-prime-counting-function @@ -0,0 +1 @@ +../../Task/Legendre-prime-counting-function/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Logical-operations b/Lang/V-(Vlang)/Logical-operations new file mode 120000 index 0000000000..bed3efe6b2 --- /dev/null +++ b/Lang/V-(Vlang)/Logical-operations @@ -0,0 +1 @@ +../../Task/Logical-operations/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/MD4 b/Lang/V-(Vlang)/MD4 new file mode 120000 index 0000000000..4ef84d93a7 --- /dev/null +++ b/Lang/V-(Vlang)/MD4 @@ -0,0 +1 @@ +../../Task/MD4/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Magic-8-ball b/Lang/V-(Vlang)/Magic-8-ball new file mode 120000 index 0000000000..01ad1da8ee --- /dev/null +++ b/Lang/V-(Vlang)/Magic-8-ball @@ -0,0 +1 @@ +../../Task/Magic-8-ball/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Magic-squares-of-odd-order b/Lang/V-(Vlang)/Magic-squares-of-odd-order new file mode 120000 index 0000000000..15a07e422e --- /dev/null +++ b/Lang/V-(Vlang)/Magic-squares-of-odd-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-odd-order/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Map-range b/Lang/V-(Vlang)/Map-range new file mode 120000 index 0000000000..bd9191a4a1 --- /dev/null +++ b/Lang/V-(Vlang)/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Matrix-chain-multiplication b/Lang/V-(Vlang)/Matrix-chain-multiplication new file mode 120000 index 0000000000..6f5b000cff --- /dev/null +++ b/Lang/V-(Vlang)/Matrix-chain-multiplication @@ -0,0 +1 @@ +../../Task/Matrix-chain-multiplication/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Matrix-transposition b/Lang/V-(Vlang)/Matrix-transposition new file mode 120000 index 0000000000..f283dea370 --- /dev/null +++ b/Lang/V-(Vlang)/Matrix-transposition @@ -0,0 +1 @@ +../../Task/Matrix-transposition/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Mayan-numerals b/Lang/V-(Vlang)/Mayan-numerals new file mode 120000 index 0000000000..005198e98f --- /dev/null +++ b/Lang/V-(Vlang)/Mayan-numerals @@ -0,0 +1 @@ +../../Task/Mayan-numerals/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Maze-generation b/Lang/V-(Vlang)/Maze-generation new file mode 120000 index 0000000000..62cabc5306 --- /dev/null +++ b/Lang/V-(Vlang)/Maze-generation @@ -0,0 +1 @@ +../../Task/Maze-generation/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Maze-solving b/Lang/V-(Vlang)/Maze-solving new file mode 120000 index 0000000000..1dd904fdc6 --- /dev/null +++ b/Lang/V-(Vlang)/Maze-solving @@ -0,0 +1 @@ +../../Task/Maze-solving/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Memory-allocation b/Lang/V-(Vlang)/Memory-allocation new file mode 120000 index 0000000000..28b226407c --- /dev/null +++ b/Lang/V-(Vlang)/Memory-allocation @@ -0,0 +1 @@ +../../Task/Memory-allocation/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Metaprogramming b/Lang/V-(Vlang)/Metaprogramming new file mode 120000 index 0000000000..6b8564d95e --- /dev/null +++ b/Lang/V-(Vlang)/Metaprogramming @@ -0,0 +1 @@ +../../Task/Metaprogramming/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Mind-boggling-card-trick b/Lang/V-(Vlang)/Mind-boggling-card-trick new file mode 120000 index 0000000000..765932978d --- /dev/null +++ b/Lang/V-(Vlang)/Mind-boggling-card-trick @@ -0,0 +1 @@ +../../Task/Mind-boggling-card-trick/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Monads-List-monad b/Lang/V-(Vlang)/Monads-List-monad new file mode 120000 index 0000000000..60c249323a --- /dev/null +++ b/Lang/V-(Vlang)/Monads-List-monad @@ -0,0 +1 @@ +../../Task/Monads-List-monad/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Monads-Maybe-monad b/Lang/V-(Vlang)/Monads-Maybe-monad new file mode 120000 index 0000000000..bcf0927f50 --- /dev/null +++ b/Lang/V-(Vlang)/Monads-Maybe-monad @@ -0,0 +1 @@ +../../Task/Monads-Maybe-monad/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Morse-code b/Lang/V-(Vlang)/Morse-code new file mode 120000 index 0000000000..ac98ffd266 --- /dev/null +++ b/Lang/V-(Vlang)/Morse-code @@ -0,0 +1 @@ +../../Task/Morse-code/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Multiplication-tables b/Lang/V-(Vlang)/Multiplication-tables new file mode 120000 index 0000000000..3bdff7103e --- /dev/null +++ b/Lang/V-(Vlang)/Multiplication-tables @@ -0,0 +1 @@ +../../Task/Multiplication-tables/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/N-queens-problem b/Lang/V-(Vlang)/N-queens-problem new file mode 120000 index 0000000000..50b06d4a76 --- /dev/null +++ b/Lang/V-(Vlang)/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Nonoblock b/Lang/V-(Vlang)/Nonoblock new file mode 120000 index 0000000000..930ce96e10 --- /dev/null +++ b/Lang/V-(Vlang)/Nonoblock @@ -0,0 +1 @@ +../../Task/Nonoblock/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/One-dimensional-cellular-automata b/Lang/V-(Vlang)/One-dimensional-cellular-automata new file mode 120000 index 0000000000..7b9510a27e --- /dev/null +++ b/Lang/V-(Vlang)/One-dimensional-cellular-automata @@ -0,0 +1 @@ +../../Task/One-dimensional-cellular-automata/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Operator-precedence b/Lang/V-(Vlang)/Operator-precedence new file mode 120000 index 0000000000..749797e963 --- /dev/null +++ b/Lang/V-(Vlang)/Operator-precedence @@ -0,0 +1 @@ +../../Task/Operator-precedence/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Optional-parameters b/Lang/V-(Vlang)/Optional-parameters new file mode 120000 index 0000000000..34451b5a74 --- /dev/null +++ b/Lang/V-(Vlang)/Optional-parameters @@ -0,0 +1 @@ +../../Task/Optional-parameters/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Palindrome-dates b/Lang/V-(Vlang)/Palindrome-dates new file mode 120000 index 0000000000..58cd472885 --- /dev/null +++ b/Lang/V-(Vlang)/Palindrome-dates @@ -0,0 +1 @@ +../../Task/Palindrome-dates/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Pancake-numbers b/Lang/V-(Vlang)/Pancake-numbers new file mode 120000 index 0000000000..03055f6721 --- /dev/null +++ b/Lang/V-(Vlang)/Pancake-numbers @@ -0,0 +1 @@ +../../Task/Pancake-numbers/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Pangram-checker b/Lang/V-(Vlang)/Pangram-checker new file mode 120000 index 0000000000..281ca7e770 --- /dev/null +++ b/Lang/V-(Vlang)/Pangram-checker @@ -0,0 +1 @@ +../../Task/Pangram-checker/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Parametric-polymorphism b/Lang/V-(Vlang)/Parametric-polymorphism new file mode 120000 index 0000000000..2fba74d455 --- /dev/null +++ b/Lang/V-(Vlang)/Parametric-polymorphism @@ -0,0 +1 @@ +../../Task/Parametric-polymorphism/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Partial-function-application b/Lang/V-(Vlang)/Partial-function-application new file mode 120000 index 0000000000..2ab67a8d88 --- /dev/null +++ b/Lang/V-(Vlang)/Partial-function-application @@ -0,0 +1 @@ +../../Task/Partial-function-application/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Pascals-triangle b/Lang/V-(Vlang)/Pascals-triangle new file mode 120000 index 0000000000..91982b11d4 --- /dev/null +++ b/Lang/V-(Vlang)/Pascals-triangle @@ -0,0 +1 @@ +../../Task/Pascals-triangle/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Password-generator b/Lang/V-(Vlang)/Password-generator new file mode 120000 index 0000000000..7e3dac059f --- /dev/null +++ b/Lang/V-(Vlang)/Password-generator @@ -0,0 +1 @@ +../../Task/Password-generator/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Peano-curve b/Lang/V-(Vlang)/Peano-curve new file mode 120000 index 0000000000..859acf6031 --- /dev/null +++ b/Lang/V-(Vlang)/Peano-curve @@ -0,0 +1 @@ +../../Task/Peano-curve/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Permutations-by-swapping b/Lang/V-(Vlang)/Permutations-by-swapping new file mode 120000 index 0000000000..247ffcc655 --- /dev/null +++ b/Lang/V-(Vlang)/Permutations-by-swapping @@ -0,0 +1 @@ +../../Task/Permutations-by-swapping/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Polymorphic-copy b/Lang/V-(Vlang)/Polymorphic-copy new file mode 120000 index 0000000000..d1d9a95084 --- /dev/null +++ b/Lang/V-(Vlang)/Polymorphic-copy @@ -0,0 +1 @@ +../../Task/Polymorphic-copy/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Polymorphism b/Lang/V-(Vlang)/Polymorphism new file mode 120000 index 0000000000..1ca2c9e1ef --- /dev/null +++ b/Lang/V-(Vlang)/Polymorphism @@ -0,0 +1 @@ +../../Task/Polymorphism/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Polyspiral b/Lang/V-(Vlang)/Polyspiral new file mode 120000 index 0000000000..f6495b4e02 --- /dev/null +++ b/Lang/V-(Vlang)/Polyspiral @@ -0,0 +1 @@ +../../Task/Polyspiral/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Price-fraction b/Lang/V-(Vlang)/Price-fraction new file mode 120000 index 0000000000..065a5d4d27 --- /dev/null +++ b/Lang/V-(Vlang)/Price-fraction @@ -0,0 +1 @@ +../../Task/Price-fraction/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Prime-decomposition b/Lang/V-(Vlang)/Prime-decomposition new file mode 120000 index 0000000000..092f726639 --- /dev/null +++ b/Lang/V-(Vlang)/Prime-decomposition @@ -0,0 +1 @@ +../../Task/Prime-decomposition/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Probabilistic-choice b/Lang/V-(Vlang)/Probabilistic-choice new file mode 120000 index 0000000000..5f44e37240 --- /dev/null +++ b/Lang/V-(Vlang)/Probabilistic-choice @@ -0,0 +1 @@ +../../Task/Probabilistic-choice/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Program-name b/Lang/V-(Vlang)/Program-name new file mode 120000 index 0000000000..9b2935c679 --- /dev/null +++ b/Lang/V-(Vlang)/Program-name @@ -0,0 +1 @@ +../../Task/Program-name/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Pseudo-random-numbers-Splitmix64 b/Lang/V-(Vlang)/Pseudo-random-numbers-Splitmix64 new file mode 120000 index 0000000000..05590ef252 --- /dev/null +++ b/Lang/V-(Vlang)/Pseudo-random-numbers-Splitmix64 @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-Splitmix64/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Quine b/Lang/V-(Vlang)/Quine new file mode 120000 index 0000000000..a258f08a53 --- /dev/null +++ b/Lang/V-(Vlang)/Quine @@ -0,0 +1 @@ +../../Task/Quine/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/RPG-attributes-generator b/Lang/V-(Vlang)/RPG-attributes-generator new file mode 120000 index 0000000000..e14499c2a5 --- /dev/null +++ b/Lang/V-(Vlang)/RPG-attributes-generator @@ -0,0 +1 @@ +../../Task/RPG-attributes-generator/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Range-extraction b/Lang/V-(Vlang)/Range-extraction new file mode 120000 index 0000000000..76ae7cce99 --- /dev/null +++ b/Lang/V-(Vlang)/Range-extraction @@ -0,0 +1 @@ +../../Task/Range-extraction/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Read-a-specific-line-from-a-file b/Lang/V-(Vlang)/Read-a-specific-line-from-a-file new file mode 120000 index 0000000000..8f9a931625 --- /dev/null +++ b/Lang/V-(Vlang)/Read-a-specific-line-from-a-file @@ -0,0 +1 @@ +../../Task/Read-a-specific-line-from-a-file/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Regular-expressions b/Lang/V-(Vlang)/Regular-expressions new file mode 120000 index 0000000000..bc8ed031b0 --- /dev/null +++ b/Lang/V-(Vlang)/Regular-expressions @@ -0,0 +1 @@ +../../Task/Regular-expressions/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Respond-to-an-unknown-method-call b/Lang/V-(Vlang)/Respond-to-an-unknown-method-call new file mode 120000 index 0000000000..3cfbcab7fa --- /dev/null +++ b/Lang/V-(Vlang)/Respond-to-an-unknown-method-call @@ -0,0 +1 @@ +../../Task/Respond-to-an-unknown-method-call/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Return-multiple-values b/Lang/V-(Vlang)/Return-multiple-values new file mode 120000 index 0000000000..ddbdb0227d --- /dev/null +++ b/Lang/V-(Vlang)/Return-multiple-values @@ -0,0 +1 @@ +../../Task/Return-multiple-values/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/SEDOLs b/Lang/V-(Vlang)/SEDOLs new file mode 120000 index 0000000000..3d43f78e48 --- /dev/null +++ b/Lang/V-(Vlang)/SEDOLs @@ -0,0 +1 @@ +../../Task/SEDOLs/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Scope-modifiers b/Lang/V-(Vlang)/Scope-modifiers new file mode 120000 index 0000000000..429eb578e5 --- /dev/null +++ b/Lang/V-(Vlang)/Scope-modifiers @@ -0,0 +1 @@ +../../Task/Scope-modifiers/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Send-an-unknown-method-call b/Lang/V-(Vlang)/Send-an-unknown-method-call new file mode 120000 index 0000000000..682a1fe636 --- /dev/null +++ b/Lang/V-(Vlang)/Send-an-unknown-method-call @@ -0,0 +1 @@ +../../Task/Send-an-unknown-method-call/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Sierpinski-arrowhead-curve b/Lang/V-(Vlang)/Sierpinski-arrowhead-curve new file mode 120000 index 0000000000..ce49e15c40 --- /dev/null +++ b/Lang/V-(Vlang)/Sierpinski-arrowhead-curve @@ -0,0 +1 @@ +../../Task/Sierpinski-arrowhead-curve/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Sierpinski-square-curve b/Lang/V-(Vlang)/Sierpinski-square-curve new file mode 120000 index 0000000000..c9f1debc78 --- /dev/null +++ b/Lang/V-(Vlang)/Sierpinski-square-curve @@ -0,0 +1 @@ +../../Task/Sierpinski-square-curve/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Sieve-of-Pritchard b/Lang/V-(Vlang)/Sieve-of-Pritchard new file mode 120000 index 0000000000..c1742abeaf --- /dev/null +++ b/Lang/V-(Vlang)/Sieve-of-Pritchard @@ -0,0 +1 @@ +../../Task/Sieve-of-Pritchard/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Singly-linked-list-Element-definition b/Lang/V-(Vlang)/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..4870f24a23 --- /dev/null +++ b/Lang/V-(Vlang)/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Sokoban b/Lang/V-(Vlang)/Sokoban new file mode 120000 index 0000000000..ac9a6fb995 --- /dev/null +++ b/Lang/V-(Vlang)/Sokoban @@ -0,0 +1 @@ +../../Task/Sokoban/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Solve-a-Holy-Knights-tour b/Lang/V-(Vlang)/Solve-a-Holy-Knights-tour new file mode 120000 index 0000000000..4753f7fb1d --- /dev/null +++ b/Lang/V-(Vlang)/Solve-a-Holy-Knights-tour @@ -0,0 +1 @@ +../../Task/Solve-a-Holy-Knights-tour/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Sort-a-list-of-object-identifiers b/Lang/V-(Vlang)/Sort-a-list-of-object-identifiers new file mode 120000 index 0000000000..f40fb70fcb --- /dev/null +++ b/Lang/V-(Vlang)/Sort-a-list-of-object-identifiers @@ -0,0 +1 @@ +../../Task/Sort-a-list-of-object-identifiers/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Sort-numbers-lexicographically b/Lang/V-(Vlang)/Sort-numbers-lexicographically new file mode 120000 index 0000000000..05897e6739 --- /dev/null +++ b/Lang/V-(Vlang)/Sort-numbers-lexicographically @@ -0,0 +1 @@ +../../Task/Sort-numbers-lexicographically/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Sorting-Algorithms-Circle-Sort b/Lang/V-(Vlang)/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 90876b0ca9..0000000000 --- a/Lang/V-(Vlang)/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Special-variables b/Lang/V-(Vlang)/Special-variables new file mode 120000 index 0000000000..cf6afb2ad0 --- /dev/null +++ b/Lang/V-(Vlang)/Special-variables @@ -0,0 +1 @@ +../../Task/Special-variables/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Spiral-matrix b/Lang/V-(Vlang)/Spiral-matrix new file mode 120000 index 0000000000..3966b6fb8b --- /dev/null +++ b/Lang/V-(Vlang)/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Stair-climbing-puzzle b/Lang/V-(Vlang)/Stair-climbing-puzzle new file mode 120000 index 0000000000..f0a6ae3661 --- /dev/null +++ b/Lang/V-(Vlang)/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Straddling-checkerboard b/Lang/V-(Vlang)/Straddling-checkerboard new file mode 120000 index 0000000000..fcc5be8fde --- /dev/null +++ b/Lang/V-(Vlang)/Straddling-checkerboard @@ -0,0 +1 @@ +../../Task/Straddling-checkerboard/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Substring-Top-and-tail b/Lang/V-(Vlang)/Substring-Top-and-tail new file mode 120000 index 0000000000..6ff0a67c24 --- /dev/null +++ b/Lang/V-(Vlang)/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Sudoku b/Lang/V-(Vlang)/Sudoku new file mode 120000 index 0000000000..930f85b4d1 --- /dev/null +++ b/Lang/V-(Vlang)/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Sum-of-squares b/Lang/V-(Vlang)/Sum-of-squares new file mode 120000 index 0000000000..bdf6276079 --- /dev/null +++ b/Lang/V-(Vlang)/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Summarize-and-say-sequence b/Lang/V-(Vlang)/Summarize-and-say-sequence new file mode 120000 index 0000000000..6bf589b063 --- /dev/null +++ b/Lang/V-(Vlang)/Summarize-and-say-sequence @@ -0,0 +1 @@ +../../Task/Summarize-and-say-sequence/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Superellipse b/Lang/V-(Vlang)/Superellipse new file mode 120000 index 0000000000..f4877a60ae --- /dev/null +++ b/Lang/V-(Vlang)/Superellipse @@ -0,0 +1 @@ +../../Task/Superellipse/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Superpermutation-minimisation b/Lang/V-(Vlang)/Superpermutation-minimisation new file mode 120000 index 0000000000..8aeb5ea4bd --- /dev/null +++ b/Lang/V-(Vlang)/Superpermutation-minimisation @@ -0,0 +1 @@ +../../Task/Superpermutation-minimisation/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Table-creation-Postal-addresses b/Lang/V-(Vlang)/Table-creation-Postal-addresses new file mode 120000 index 0000000000..07c82be810 --- /dev/null +++ b/Lang/V-(Vlang)/Table-creation-Postal-addresses @@ -0,0 +1 @@ +../../Task/Table-creation-Postal-addresses/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Taxicab-numbers b/Lang/V-(Vlang)/Taxicab-numbers new file mode 120000 index 0000000000..d3f4a716c8 --- /dev/null +++ b/Lang/V-(Vlang)/Taxicab-numbers @@ -0,0 +1 @@ +../../Task/Taxicab-numbers/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/The-Twelve-Days-of-Christmas b/Lang/V-(Vlang)/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..ac2e9fb7b5 --- /dev/null +++ b/Lang/V-(Vlang)/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Thue-Morse b/Lang/V-(Vlang)/Thue-Morse new file mode 120000 index 0000000000..82f9127b9d --- /dev/null +++ b/Lang/V-(Vlang)/Thue-Morse @@ -0,0 +1 @@ +../../Task/Thue-Morse/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Topic-variable b/Lang/V-(Vlang)/Topic-variable new file mode 120000 index 0000000000..99a32af3bb --- /dev/null +++ b/Lang/V-(Vlang)/Topic-variable @@ -0,0 +1 @@ +../../Task/Topic-variable/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Transliterate-English-text-using-the-Greek-alphabet b/Lang/V-(Vlang)/Transliterate-English-text-using-the-Greek-alphabet new file mode 120000 index 0000000000..9c6f1c38d1 --- /dev/null +++ b/Lang/V-(Vlang)/Transliterate-English-text-using-the-Greek-alphabet @@ -0,0 +1 @@ +../../Task/Transliterate-English-text-using-the-Greek-alphabet/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Twos-complement b/Lang/V-(Vlang)/Twos-complement new file mode 120000 index 0000000000..b9ca937183 --- /dev/null +++ b/Lang/V-(Vlang)/Twos-complement @@ -0,0 +1 @@ +../../Task/Twos-complement/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/UPC b/Lang/V-(Vlang)/UPC new file mode 120000 index 0000000000..bb6c7d3bca --- /dev/null +++ b/Lang/V-(Vlang)/UPC @@ -0,0 +1 @@ +../../Task/UPC/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/User-input-Graphical b/Lang/V-(Vlang)/User-input-Graphical new file mode 120000 index 0000000000..d985c46dcb --- /dev/null +++ b/Lang/V-(Vlang)/User-input-Graphical @@ -0,0 +1 @@ +../../Task/User-input-Graphical/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Variable-length-quantity b/Lang/V-(Vlang)/Variable-length-quantity new file mode 120000 index 0000000000..e0a7eee24f --- /dev/null +++ b/Lang/V-(Vlang)/Variable-length-quantity @@ -0,0 +1 @@ +../../Task/Variable-length-quantity/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/War-card-game b/Lang/V-(Vlang)/War-card-game new file mode 120000 index 0000000000..b1fa28907b --- /dev/null +++ b/Lang/V-(Vlang)/War-card-game @@ -0,0 +1 @@ +../../Task/War-card-game/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Word-frequency b/Lang/V-(Vlang)/Word-frequency new file mode 120000 index 0000000000..7472df9d00 --- /dev/null +++ b/Lang/V-(Vlang)/Word-frequency @@ -0,0 +1 @@ +../../Task/Word-frequency/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Yin-and-yang b/Lang/V-(Vlang)/Yin-and-yang new file mode 120000 index 0000000000..bfc21b3e37 --- /dev/null +++ b/Lang/V-(Vlang)/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Zhang-Suen-thinning-algorithm b/Lang/V-(Vlang)/Zhang-Suen-thinning-algorithm new file mode 120000 index 0000000000..b0618c7785 --- /dev/null +++ b/Lang/V-(Vlang)/Zhang-Suen-thinning-algorithm @@ -0,0 +1 @@ +../../Task/Zhang-Suen-thinning-algorithm/V-(Vlang) \ No newline at end of file diff --git a/Lang/V/00-LANG.txt b/Lang/V/00-LANG.txt index c4203ea969..6de2ee34df 100644 --- a/Lang/V/00-LANG.txt +++ b/Lang/V/00-LANG.txt @@ -5,6 +5,7 @@ |site=http://code.google.com/p/v-language/ |LCT=yes}} {{language programming paradigm|concatenative}} +''Note: There is another language called V at Rosetta Code, it can be found at [[:Category:V_(Vlang)|V (Vlang)]].'' + '''V''' is a simple, stack-based (concatenative), dynamic language. It is similar to [[Joy]] and [[PostScript]]. -
    -Note: There is another language called V at Rosetta Code, it can be found over [[:Category:V_(Vlang)|here]]. \ No newline at end of file +
    \ No newline at end of file diff --git a/Lang/V/99-bottles-of-beer b/Lang/V/99-bottles-of-beer new file mode 120000 index 0000000000..9e72431c34 --- /dev/null +++ b/Lang/V/99-bottles-of-beer @@ -0,0 +1 @@ +../../Task/99-bottles-of-beer/V \ No newline at end of file diff --git a/Lang/VBA/Abundant-odd-numbers b/Lang/VBA/Abundant-odd-numbers new file mode 120000 index 0000000000..634e142877 --- /dev/null +++ b/Lang/VBA/Abundant-odd-numbers @@ -0,0 +1 @@ +../../Task/Abundant-odd-numbers/VBA \ No newline at end of file diff --git a/Lang/VBA/Bell-numbers b/Lang/VBA/Bell-numbers new file mode 120000 index 0000000000..825db8e67d --- /dev/null +++ b/Lang/VBA/Bell-numbers @@ -0,0 +1 @@ +../../Task/Bell-numbers/VBA \ No newline at end of file diff --git a/Lang/VBA/Brazilian-numbers b/Lang/VBA/Brazilian-numbers new file mode 120000 index 0000000000..3b990aab5c --- /dev/null +++ b/Lang/VBA/Brazilian-numbers @@ -0,0 +1 @@ +../../Task/Brazilian-numbers/VBA \ No newline at end of file diff --git a/Lang/VBA/Deal-cards-for-FreeCell b/Lang/VBA/Deal-cards-for-FreeCell new file mode 120000 index 0000000000..33506ab6dc --- /dev/null +++ b/Lang/VBA/Deal-cards-for-FreeCell @@ -0,0 +1 @@ +../../Task/Deal-cards-for-FreeCell/VBA \ No newline at end of file diff --git a/Lang/VBA/Gamma-function b/Lang/VBA/Gamma-function new file mode 120000 index 0000000000..75f8622191 --- /dev/null +++ b/Lang/VBA/Gamma-function @@ -0,0 +1 @@ +../../Task/Gamma-function/VBA \ No newline at end of file diff --git a/Lang/VBA/M-bius-function b/Lang/VBA/M-bius-function new file mode 120000 index 0000000000..eb8fdee7b1 --- /dev/null +++ b/Lang/VBA/M-bius-function @@ -0,0 +1 @@ +../../Task/M-bius-function/VBA \ No newline at end of file diff --git a/Lang/VBA/Monty-Hall-problem b/Lang/VBA/Monty-Hall-problem new file mode 120000 index 0000000000..cbcc810f65 --- /dev/null +++ b/Lang/VBA/Monty-Hall-problem @@ -0,0 +1 @@ +../../Task/Monty-Hall-problem/VBA \ No newline at end of file diff --git a/Lang/VBA/Quaternion-type b/Lang/VBA/Quaternion-type deleted file mode 120000 index b9d823193e..0000000000 --- a/Lang/VBA/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/VBA \ No newline at end of file diff --git a/Lang/VBScript/Bioinformatics-base-count b/Lang/VBScript/Bioinformatics-base-count deleted file mode 120000 index 27b49dfc57..0000000000 --- a/Lang/VBScript/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Simple-windowed-application b/Lang/VBScript/Simple-windowed-application new file mode 120000 index 0000000000..99e416c344 --- /dev/null +++ b/Lang/VBScript/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/VBScript \ No newline at end of file diff --git a/Lang/VTL-2/RPG-attributes-generator b/Lang/VTL-2/RPG-attributes-generator new file mode 120000 index 0000000000..1167e48571 --- /dev/null +++ b/Lang/VTL-2/RPG-attributes-generator @@ -0,0 +1 @@ +../../Task/RPG-attributes-generator/VTL-2 \ No newline at end of file diff --git a/Lang/VTL-2/Zeckendorf-number-representation b/Lang/VTL-2/Zeckendorf-number-representation new file mode 120000 index 0000000000..f281019c65 --- /dev/null +++ b/Lang/VTL-2/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/VTL-2 \ No newline at end of file diff --git a/Lang/Vala/Execute-Brain- b/Lang/Vala/Execute-Brain- new file mode 120000 index 0000000000..ae24a4e37d --- /dev/null +++ b/Lang/Vala/Execute-Brain- @@ -0,0 +1 @@ +../../Task/Execute-Brain-/Vala \ No newline at end of file diff --git a/Lang/Verilog/Leonardo-numbers b/Lang/Verilog/Leonardo-numbers new file mode 120000 index 0000000000..fdea2f05f8 --- /dev/null +++ b/Lang/Verilog/Leonardo-numbers @@ -0,0 +1 @@ +../../Task/Leonardo-numbers/Verilog \ No newline at end of file diff --git a/Lang/Verilog/Loops-Infinite b/Lang/Verilog/Loops-Infinite new file mode 120000 index 0000000000..07545a5d7e --- /dev/null +++ b/Lang/Verilog/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/Verilog \ No newline at end of file diff --git a/Lang/Verilog/Pancake-numbers b/Lang/Verilog/Pancake-numbers new file mode 120000 index 0000000000..f9cd19af94 --- /dev/null +++ b/Lang/Verilog/Pancake-numbers @@ -0,0 +1 @@ +../../Task/Pancake-numbers/Verilog \ No newline at end of file diff --git a/Lang/Verilog/Twos-complement b/Lang/Verilog/Twos-complement new file mode 120000 index 0000000000..8527a62e79 --- /dev/null +++ b/Lang/Verilog/Twos-complement @@ -0,0 +1 @@ +../../Task/Twos-complement/Verilog \ No newline at end of file diff --git a/Lang/Vim-Script/Hello-world-Graphical b/Lang/Vim-Script/Hello-world-Graphical new file mode 120000 index 0000000000..799696cc16 --- /dev/null +++ b/Lang/Vim-Script/Hello-world-Graphical @@ -0,0 +1 @@ +../../Task/Hello-world-Graphical/Vim-Script \ No newline at end of file diff --git a/Lang/Vim-Script/Here-document b/Lang/Vim-Script/Here-document new file mode 120000 index 0000000000..4f2967d090 --- /dev/null +++ b/Lang/Vim-Script/Here-document @@ -0,0 +1 @@ +../../Task/Here-document/Vim-Script \ No newline at end of file diff --git a/Lang/Vim-Script/Loop-over-multiple-arrays-simultaneously b/Lang/Vim-Script/Loop-over-multiple-arrays-simultaneously new file mode 120000 index 0000000000..3e8729e53b --- /dev/null +++ b/Lang/Vim-Script/Loop-over-multiple-arrays-simultaneously @@ -0,0 +1 @@ +../../Task/Loop-over-multiple-arrays-simultaneously/Vim-Script \ No newline at end of file diff --git a/Lang/Vim-Script/Loops-For b/Lang/Vim-Script/Loops-For new file mode 120000 index 0000000000..427dcdb8bf --- /dev/null +++ b/Lang/Vim-Script/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/Vim-Script \ No newline at end of file diff --git a/Lang/Vim-Script/XML-Input b/Lang/Vim-Script/XML-Input new file mode 120000 index 0000000000..57be30dc70 --- /dev/null +++ b/Lang/Vim-Script/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/Vim-Script \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/Execute-Brain- b/Lang/Visual-Basic-.NET/Execute-Brain- new file mode 120000 index 0000000000..40c465e5ff --- /dev/null +++ b/Lang/Visual-Basic-.NET/Execute-Brain- @@ -0,0 +1 @@ +../../Task/Execute-Brain-/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/Quaternion-type b/Lang/Visual-Basic-.NET/Quaternion-type deleted file mode 120000 index 111784d7c2..0000000000 --- a/Lang/Visual-Basic-.NET/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Vyxal/00-LANG.txt b/Lang/Vyxal/00-LANG.txt new file mode 100644 index 0000000000..0acceafc9b --- /dev/null +++ b/Lang/Vyxal/00-LANG.txt @@ -0,0 +1,3 @@ +{{language|Vyxal}} + +Vyxal is an esoteric golfing language designed to make code golf challenges fun, and to allow code golfers to win said challenges. \ No newline at end of file diff --git a/Lang/Vyxal/00-META.yaml b/Lang/Vyxal/00-META.yaml new file mode 100644 index 0000000000..a5968dda5e --- /dev/null +++ b/Lang/Vyxal/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Vyxal diff --git a/Lang/Vyxal/Arithmetic-geometric-mean b/Lang/Vyxal/Arithmetic-geometric-mean new file mode 120000 index 0000000000..5c957e3635 --- /dev/null +++ b/Lang/Vyxal/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/Vyxal \ No newline at end of file diff --git a/Lang/Vyxal/Execute-Brain- b/Lang/Vyxal/Execute-Brain- new file mode 120000 index 0000000000..76839bca71 --- /dev/null +++ b/Lang/Vyxal/Execute-Brain- @@ -0,0 +1 @@ +../../Task/Execute-Brain-/Vyxal \ No newline at end of file diff --git a/Lang/Vyxal/Factorial b/Lang/Vyxal/Factorial new file mode 120000 index 0000000000..1cdfde0f4b --- /dev/null +++ b/Lang/Vyxal/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Vyxal \ No newline at end of file diff --git a/Lang/Vyxal/Factorions b/Lang/Vyxal/Factorions new file mode 120000 index 0000000000..df658fe37b --- /dev/null +++ b/Lang/Vyxal/Factorions @@ -0,0 +1 @@ +../../Task/Factorions/Vyxal \ No newline at end of file diff --git a/Lang/Vyxal/FizzBuzz b/Lang/Vyxal/FizzBuzz new file mode 120000 index 0000000000..22964032ea --- /dev/null +++ b/Lang/Vyxal/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Vyxal \ No newline at end of file diff --git a/Lang/Vyxal/Linear-congruential-generator b/Lang/Vyxal/Linear-congruential-generator new file mode 120000 index 0000000000..7a8e447f9f --- /dev/null +++ b/Lang/Vyxal/Linear-congruential-generator @@ -0,0 +1 @@ +../../Task/Linear-congruential-generator/Vyxal \ No newline at end of file diff --git a/Lang/Vyxal/Narcissistic-decimal-number b/Lang/Vyxal/Narcissistic-decimal-number new file mode 120000 index 0000000000..4f717275c0 --- /dev/null +++ b/Lang/Vyxal/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/Vyxal \ No newline at end of file diff --git a/Lang/Waduzitdo/00-LANG.txt b/Lang/Waduzitdo/00-LANG.txt new file mode 100644 index 0000000000..140eff39b3 --- /dev/null +++ b/Lang/Waduzitdo/00-LANG.txt @@ -0,0 +1,7 @@ +{{stub}} +{{language|Waduzitdo +|site=https://waduzitdo.org/ +|hopl=no +}} + +Waduzitdo is a programming language created by Larry Kheriaty and published in the popular computer culture magazine BYTE in 1978. It very closely resembles [[PILOT]], but is even more simplified and has been proven to not be Turing complete. It appears to have been created as an attempt to create an extremely small compiler, as well as being a good language for demonstrating basic functions; the language only has eight commands, which demonstrate input and output, along with basic pattern-matching and decision-making. The language gets its name from the fact that it was designed for demonstrating a computer to people who had never used one before who are asking "What does it do?" \ No newline at end of file diff --git a/Lang/Waduzitdo/00-META.yaml b/Lang/Waduzitdo/00-META.yaml new file mode 100644 index 0000000000..7c62d1f448 --- /dev/null +++ b/Lang/Waduzitdo/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Waduzitdo diff --git a/Lang/Waduzitdo/Hello-world-Text b/Lang/Waduzitdo/Hello-world-Text new file mode 120000 index 0000000000..4d7c98308f --- /dev/null +++ b/Lang/Waduzitdo/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Waduzitdo \ No newline at end of file diff --git a/Lang/Waduzitdo/Nim-game b/Lang/Waduzitdo/Nim-game new file mode 120000 index 0000000000..d8c3766378 --- /dev/null +++ b/Lang/Waduzitdo/Nim-game @@ -0,0 +1 @@ +../../Task/Nim-game/Waduzitdo \ No newline at end of file diff --git a/Lang/Wee-Basic/Empty-program b/Lang/Wee-Basic/Empty-program deleted file mode 120000 index 132197773e..0000000000 --- a/Lang/Wee-Basic/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Wee-Basic \ No newline at end of file diff --git a/Lang/Wisp/Knuth-shuffle b/Lang/Wisp/Knuth-shuffle new file mode 120000 index 0000000000..14993ebaba --- /dev/null +++ b/Lang/Wisp/Knuth-shuffle @@ -0,0 +1 @@ +../../Task/Knuth-shuffle/Wisp \ No newline at end of file diff --git a/Lang/Wisp/Levenshtein-distance b/Lang/Wisp/Levenshtein-distance new file mode 120000 index 0000000000..4fa74a1890 --- /dev/null +++ b/Lang/Wisp/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/Wisp \ No newline at end of file diff --git a/Lang/Wren/00-LANG.txt b/Lang/Wren/00-LANG.txt index 1dbc2e611b..2d52115f0a 100644 --- a/Lang/Wren/00-LANG.txt +++ b/Lang/Wren/00-LANG.txt @@ -15,7 +15,7 @@ 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]. -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: +As a language mainly designed for embedding, Wren's standard library is (of necessity) quite small and I ([[User:PureFox|PureFox]]) 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" ! No. !! Module name !! !! No. !! Module name @@ -64,7 +64,11 @@ As a language mainly designed for embedding, Wren's standard library is (of nece |- | 43 || [[:Category:Wren-vector|vector]] || || 44 || [[:Category:Wren-ordered|ordered]] |- -| 45 || [[:Category:Wren-psieve|psieve]] || || || +| 45 || [[:Category:Wren-psieve|psieve]] || || 46 || [[:Category:Wren-hash|hash]] +|- +| 47 || [[:Category:Wren-roman|roman]] || || 48 || [[:Category:Wren-std|std]] +|- +| 49 || [[:Category:Wren-ansi|ansi]] || || || |}
    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: @@ -91,5 +95,7 @@ There are also a number of third-party modules available for Wren of which the f
    For further information and licensing requirements, please consult their individual pages. +Finally, there are some RC tasks which require a special C executable to solve but where it is not worthwhile to create a dedicated module to house the Wren source code. See [[:Category:libwren|libwren]] for details. + ==Todo== * [[Tasks not implemented in Wren]] \ No newline at end of file diff --git a/Lang/Wren/Bioinformatics-base-count b/Lang/Wren/Bioinformatics-base-count deleted file mode 120000 index 620c92bb71..0000000000 --- a/Lang/Wren/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Wren \ No newline at end of file diff --git a/Lang/Wren/Empty-program b/Lang/Wren/Empty-program deleted file mode 120000 index e0842518a1..0000000000 --- a/Lang/Wren/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Wren \ No newline at end of file diff --git a/Lang/Wren/Meissel-Mertens-constant b/Lang/Wren/Meissel-Mertens-constant deleted file mode 120000 index 2a9c71a439..0000000000 --- a/Lang/Wren/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/Wren \ No newline at end of file diff --git a/Lang/Wren/Miller-Rabin-primality-test b/Lang/Wren/Miller-Rabin-primality-test deleted file mode 120000 index 26f77867d2..0000000000 --- a/Lang/Wren/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Wren \ No newline at end of file diff --git a/Lang/Wren/Quaternion-type b/Lang/Wren/Quaternion-type deleted file mode 120000 index 42a26f0111..0000000000 --- a/Lang/Wren/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Wren \ No newline at end of file diff --git a/Lang/Wren/Sorting-Algorithms-Circle-Sort b/Lang/Wren/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 3d8f8916cb..0000000000 --- a/Lang/Wren/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Wren \ No newline at end of file diff --git a/Lang/X-script/00-LANG.txt b/Lang/X-script/00-LANG.txt new file mode 100644 index 0000000000..af743e22c3 --- /dev/null +++ b/Lang/X-script/00-LANG.txt @@ -0,0 +1,38 @@ +{{language|X-script}} +X-script is a minimalistic programming language which is characterised by user friendlyness and simplicity. +All data are strings. It can also handle binary data, which are then encoded as hexadecimal strings. +It can read from and write to files and serial devices like TCP/IP ports and serial ports. +It has a window that has similarities with consoles, where you can start programs, call functions and call states or just write code (like in Python). + +Here is an example of an x-script that implements a chemical calculator: +[[Chemical_calculator#X-script]]. + +The development of X-script started around 1980 and the language has been improved ever since. Originally, the goal was to enable the creation of rapid prototypes of programs, to test ideas before the real programming started. + +The "Hello world" program looks like this: + + +In x-script, you can develop an application in two different ways. One is as a function, which is similar to functions in other languages, except that all data are strings. + +The other is as a state, which is a list of inputs and outputs. +A state is mostly the quickest way to solve a programming problem. It is also easy to read, since it is a list of inputs and the corresponding outputs or actions. The inputs are surrounded by ?"..."? and the corresponding outputs or actions by !"..."!. If you for example want to read a comma-separated account from a bank, the state could look like this: + +accountStatement.x +------------------ +(* Titles *) +?"TransactionDate;Reference;Amount +"? +!""! + +(* Example: 2023-09-04;Accessa Finance Inc 305653152413;-3850.00 *) +?";; +"? +!" you '<0,payed to,earned from>

    :

    dollars."! + +?""? +!""! + + +Function calls have this format: . + +The example above calls the library functions , , , ,

    , and .

    , , and are "pattern functions" which are used to match input strings.

    ,

    and are ordinary functions. prints a string to the X-window.

    retrieves stringparts identified in the input file. returns from the state, \ No newline at end of file diff --git a/Lang/X-script/00-META.yaml b/Lang/X-script/00-META.yaml new file mode 100644 index 0000000000..2fd50d732b --- /dev/null +++ b/Lang/X-script/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:X-script diff --git a/Lang/X86-64-Assembly/A+B b/Lang/X86-64-Assembly/A+B new file mode 120000 index 0000000000..8da0da2282 --- /dev/null +++ b/Lang/X86-64-Assembly/A+B @@ -0,0 +1 @@ +../../Task/A+B/X86-64-Assembly \ No newline at end of file diff --git a/Lang/X86-64-Assembly/Binary-digits b/Lang/X86-64-Assembly/Binary-digits new file mode 120000 index 0000000000..1eb48aa18a --- /dev/null +++ b/Lang/X86-64-Assembly/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/X86-64-Assembly \ No newline at end of file diff --git a/Lang/X86-64-Assembly/Command-line-arguments b/Lang/X86-64-Assembly/Command-line-arguments new file mode 120000 index 0000000000..112452a5d5 --- /dev/null +++ b/Lang/X86-64-Assembly/Command-line-arguments @@ -0,0 +1 @@ +../../Task/Command-line-arguments/X86-64-Assembly \ No newline at end of file diff --git a/Lang/X86-64-Assembly/Create-an-HTML-table b/Lang/X86-64-Assembly/Create-an-HTML-table new file mode 120000 index 0000000000..e10bb5efed --- /dev/null +++ b/Lang/X86-64-Assembly/Create-an-HTML-table @@ -0,0 +1 @@ +../../Task/Create-an-HTML-table/X86-64-Assembly \ No newline at end of file diff --git a/Lang/X86-64-Assembly/Generate-lower-case-ASCII-alphabet b/Lang/X86-64-Assembly/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..0146a7c580 --- /dev/null +++ b/Lang/X86-64-Assembly/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/X86-64-Assembly \ No newline at end of file diff --git a/Lang/X86-64-Assembly/HTTPS b/Lang/X86-64-Assembly/HTTPS new file mode 120000 index 0000000000..2a06876bd2 --- /dev/null +++ b/Lang/X86-64-Assembly/HTTPS @@ -0,0 +1 @@ +../../Task/HTTPS/X86-64-Assembly \ No newline at end of file diff --git a/Lang/X86-64-Assembly/Include-a-file b/Lang/X86-64-Assembly/Include-a-file new file mode 120000 index 0000000000..b94c0093ef --- /dev/null +++ b/Lang/X86-64-Assembly/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/X86-64-Assembly \ No newline at end of file diff --git a/Lang/X86-64-Assembly/Magic-8-ball b/Lang/X86-64-Assembly/Magic-8-ball new file mode 120000 index 0000000000..63e5e8cfbb --- /dev/null +++ b/Lang/X86-64-Assembly/Magic-8-ball @@ -0,0 +1 @@ +../../Task/Magic-8-ball/X86-64-Assembly \ No newline at end of file diff --git a/Lang/X86-64-Assembly/Password-generator b/Lang/X86-64-Assembly/Password-generator new file mode 120000 index 0000000000..e8e77773e7 --- /dev/null +++ b/Lang/X86-64-Assembly/Password-generator @@ -0,0 +1 @@ +../../Task/Password-generator/X86-64-Assembly \ No newline at end of file diff --git a/Lang/X86-64-Assembly/Pseudo-random-numbers-Middle-square-method b/Lang/X86-64-Assembly/Pseudo-random-numbers-Middle-square-method new file mode 120000 index 0000000000..9ff7bee727 --- /dev/null +++ b/Lang/X86-64-Assembly/Pseudo-random-numbers-Middle-square-method @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-Middle-square-method/X86-64-Assembly \ No newline at end of file diff --git a/Lang/X86-64-Assembly/Random-number-generator-device- b/Lang/X86-64-Assembly/Random-number-generator-device- new file mode 120000 index 0000000000..17f5db574d --- /dev/null +++ b/Lang/X86-64-Assembly/Random-number-generator-device- @@ -0,0 +1 @@ +../../Task/Random-number-generator-device-/X86-64-Assembly \ No newline at end of file diff --git a/Lang/X86-64-Assembly/Rot-13 b/Lang/X86-64-Assembly/Rot-13 new file mode 120000 index 0000000000..498ce19193 --- /dev/null +++ b/Lang/X86-64-Assembly/Rot-13 @@ -0,0 +1 @@ +../../Task/Rot-13/X86-64-Assembly \ No newline at end of file diff --git a/Lang/X86-64-Assembly/Sieve-of-Eratosthenes b/Lang/X86-64-Assembly/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..2ec4e68176 --- /dev/null +++ b/Lang/X86-64-Assembly/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/X86-64-Assembly \ No newline at end of file diff --git a/Lang/X86-64-Assembly/Stack b/Lang/X86-64-Assembly/Stack new file mode 120000 index 0000000000..f458d7ec5f --- /dev/null +++ b/Lang/X86-64-Assembly/Stack @@ -0,0 +1 @@ +../../Task/Stack/X86-64-Assembly \ No newline at end of file diff --git a/Lang/X86-64-Assembly/String-length b/Lang/X86-64-Assembly/String-length new file mode 120000 index 0000000000..d3dacaf4b5 --- /dev/null +++ b/Lang/X86-64-Assembly/String-length @@ -0,0 +1 @@ +../../Task/String-length/X86-64-Assembly \ No newline at end of file diff --git a/Lang/X86-64-Assembly/Terminal-control-Clear-the-screen b/Lang/X86-64-Assembly/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..8974ae4cd4 --- /dev/null +++ b/Lang/X86-64-Assembly/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/X86-64-Assembly \ No newline at end of file diff --git a/Lang/X86-64-Assembly/Twos-complement b/Lang/X86-64-Assembly/Twos-complement new file mode 120000 index 0000000000..03daa00fb9 --- /dev/null +++ b/Lang/X86-64-Assembly/Twos-complement @@ -0,0 +1 @@ +../../Task/Twos-complement/X86-64-Assembly \ No newline at end of file diff --git a/Lang/X86-Assembly/Pythagoras-tree b/Lang/X86-Assembly/Pythagoras-tree new file mode 120000 index 0000000000..2ed69a8164 --- /dev/null +++ b/Lang/X86-Assembly/Pythagoras-tree @@ -0,0 +1 @@ +../../Task/Pythagoras-tree/X86-Assembly \ No newline at end of file diff --git a/Lang/X86-Assembly/Stack b/Lang/X86-Assembly/Stack deleted file mode 120000 index c0f7dc8fa0..0000000000 --- a/Lang/X86-Assembly/Stack +++ /dev/null @@ -1 +0,0 @@ -../../Task/Stack/X86-Assembly \ No newline at end of file diff --git a/Lang/XBS/00-LANG.txt b/Lang/XBS/00-LANG.txt index 46cebd0203..87ee4c9802 100644 --- a/Lang/XBS/00-LANG.txt +++ b/Lang/XBS/00-LANG.txt @@ -1,29 +1,8 @@ {{language|XBS}} == What is XBS? == -XBS is an interpreted language written in [[JavaScript]]. XBS has similarities to JavaScript and Python, as well as some other languages. XBS can be used for any web page with the correct library. ----- - -== Details == - -XBS has a github page and is currently open-sourced. The github page has a wiki for the documentation; but just know, this language still isn't done. It has most features a programming language has, except for some minor details that I need to fix. - ----- - -== Code Examples == - -Variable declaration - -set x = "Hello, world!"; -log(x) - -Functions - -func FirstFunction(a,b){ - send a+b; #Add a and b -} -log(FirstFunction(1,2)); +XBS is an interpreted language written in [[JavaScript]]. The language does not have its own sandbox, and relies on methods passed down from JavaScript. XBS was created originally to help its creator understand how to create a basic programming language, and later branched out its syntax in creative ways. ---- @@ -34,4 +13,5 @@ log(FirstFunction(1,2)); == Notes == -XBS is currently going through a rewrite, and the wiki has not been rewritten yet. \ No newline at end of file +* XBS was re-written back in 2021 as the language had a lot of issues with expressional parsing priorities. Most XBS examples on this site are outdated. +* XBS is a slow language, as it is interpreted using [[JavaScript]] \ No newline at end of file diff --git a/Lang/XBasic/AKS-test-for-primes b/Lang/XBasic/AKS-test-for-primes new file mode 120000 index 0000000000..dcd18f7155 --- /dev/null +++ b/Lang/XBasic/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/XBasic \ No newline at end of file diff --git a/Lang/XBasic/Associative-array-Merging b/Lang/XBasic/Associative-array-Merging new file mode 120000 index 0000000000..9fcd826207 --- /dev/null +++ b/Lang/XBasic/Associative-array-Merging @@ -0,0 +1 @@ +../../Task/Associative-array-Merging/XBasic \ No newline at end of file diff --git a/Lang/XBasic/Determine-sentence-type b/Lang/XBasic/Determine-sentence-type new file mode 120000 index 0000000000..ea580ad280 --- /dev/null +++ b/Lang/XBasic/Determine-sentence-type @@ -0,0 +1 @@ +../../Task/Determine-sentence-type/XBasic \ No newline at end of file diff --git a/Lang/XBasic/Diversity-prediction-theorem b/Lang/XBasic/Diversity-prediction-theorem new file mode 120000 index 0000000000..76939265dd --- /dev/null +++ b/Lang/XBasic/Diversity-prediction-theorem @@ -0,0 +1 @@ +../../Task/Diversity-prediction-theorem/XBasic \ No newline at end of file diff --git a/Lang/XBasic/Euler-method b/Lang/XBasic/Euler-method new file mode 120000 index 0000000000..546ca521e8 --- /dev/null +++ b/Lang/XBasic/Euler-method @@ -0,0 +1 @@ +../../Task/Euler-method/XBasic \ No newline at end of file diff --git a/Lang/XBasic/Jewels-and-stones b/Lang/XBasic/Jewels-and-stones new file mode 120000 index 0000000000..b0451efebb --- /dev/null +++ b/Lang/XBasic/Jewels-and-stones @@ -0,0 +1 @@ +../../Task/Jewels-and-stones/XBasic \ No newline at end of file diff --git a/Lang/XBasic/Josephus-problem b/Lang/XBasic/Josephus-problem new file mode 120000 index 0000000000..425d14bd16 --- /dev/null +++ b/Lang/XBasic/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/XBasic \ No newline at end of file diff --git a/Lang/XBasic/Levenshtein-distance b/Lang/XBasic/Levenshtein-distance new file mode 120000 index 0000000000..57fd900b58 --- /dev/null +++ b/Lang/XBasic/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/XBasic \ No newline at end of file diff --git a/Lang/XBasic/Loops-Infinite b/Lang/XBasic/Loops-Infinite new file mode 120000 index 0000000000..b803a965e4 --- /dev/null +++ b/Lang/XBasic/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/XBasic \ No newline at end of file diff --git a/Lang/XBasic/M-bius-function b/Lang/XBasic/M-bius-function new file mode 120000 index 0000000000..09886c7873 --- /dev/null +++ b/Lang/XBasic/M-bius-function @@ -0,0 +1 @@ +../../Task/M-bius-function/XBasic \ No newline at end of file diff --git a/Lang/XBasic/Nim-game b/Lang/XBasic/Nim-game new file mode 120000 index 0000000000..49a494ab0c --- /dev/null +++ b/Lang/XBasic/Nim-game @@ -0,0 +1 @@ +../../Task/Nim-game/XBasic \ No newline at end of file diff --git a/Lang/XBasic/Pancake-numbers b/Lang/XBasic/Pancake-numbers new file mode 120000 index 0000000000..ba6560d347 --- /dev/null +++ b/Lang/XBasic/Pancake-numbers @@ -0,0 +1 @@ +../../Task/Pancake-numbers/XBasic \ No newline at end of file diff --git a/Lang/XBasic/Sorting-algorithms-Quicksort b/Lang/XBasic/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..baefc61c90 --- /dev/null +++ b/Lang/XBasic/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/XBasic \ No newline at end of file diff --git a/Lang/XBasic/The-Name-Game b/Lang/XBasic/The-Name-Game new file mode 120000 index 0000000000..bc5b69cbc8 --- /dev/null +++ b/Lang/XBasic/The-Name-Game @@ -0,0 +1 @@ +../../Task/The-Name-Game/XBasic \ No newline at end of file diff --git a/Lang/XBasic/Twos-complement b/Lang/XBasic/Twos-complement new file mode 120000 index 0000000000..651db096a5 --- /dev/null +++ b/Lang/XBasic/Twos-complement @@ -0,0 +1 @@ +../../Task/Twos-complement/XBasic \ No newline at end of file diff --git a/Lang/XPL0/AKS-test-for-primes b/Lang/XPL0/AKS-test-for-primes new file mode 120000 index 0000000000..16474e53df --- /dev/null +++ b/Lang/XPL0/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Arithmetic-geometric-mean-Calculate-Pi b/Lang/XPL0/Arithmetic-geometric-mean-Calculate-Pi new file mode 120000 index 0000000000..34337f3f2d --- /dev/null +++ b/Lang/XPL0/Arithmetic-geometric-mean-Calculate-Pi @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean-Calculate-Pi/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Average-loop-length b/Lang/XPL0/Average-loop-length new file mode 120000 index 0000000000..b29c22437d --- /dev/null +++ b/Lang/XPL0/Average-loop-length @@ -0,0 +1 @@ +../../Task/Average-loop-length/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Bifid-cipher b/Lang/XPL0/Bifid-cipher new file mode 120000 index 0000000000..224f51d976 --- /dev/null +++ b/Lang/XPL0/Bifid-cipher @@ -0,0 +1 @@ +../../Task/Bifid-cipher/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Bin-given-limits b/Lang/XPL0/Bin-given-limits new file mode 120000 index 0000000000..d093bfd306 --- /dev/null +++ b/Lang/XPL0/Bin-given-limits @@ -0,0 +1 @@ +../../Task/Bin-given-limits/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Bioinformatics-base-count b/Lang/XPL0/Bioinformatics-base-count deleted file mode 120000 index 485c648b6c..0000000000 --- a/Lang/XPL0/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Cistercian-numerals b/Lang/XPL0/Cistercian-numerals new file mode 120000 index 0000000000..c2ce89db06 --- /dev/null +++ b/Lang/XPL0/Cistercian-numerals @@ -0,0 +1 @@ +../../Task/Cistercian-numerals/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Count-the-coins b/Lang/XPL0/Count-the-coins new file mode 120000 index 0000000000..7a91396756 --- /dev/null +++ b/Lang/XPL0/Count-the-coins @@ -0,0 +1 @@ +../../Task/Count-the-coins/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Create-an-object-at-a-given-address b/Lang/XPL0/Create-an-object-at-a-given-address new file mode 120000 index 0000000000..10ca5e5926 --- /dev/null +++ b/Lang/XPL0/Create-an-object-at-a-given-address @@ -0,0 +1 @@ +../../Task/Create-an-object-at-a-given-address/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Currency b/Lang/XPL0/Currency new file mode 120000 index 0000000000..05aee1c3b1 --- /dev/null +++ b/Lang/XPL0/Currency @@ -0,0 +1 @@ +../../Task/Currency/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Determinant-and-permanent b/Lang/XPL0/Determinant-and-permanent new file mode 120000 index 0000000000..ffda863c8d --- /dev/null +++ b/Lang/XPL0/Determinant-and-permanent @@ -0,0 +1 @@ +../../Task/Determinant-and-permanent/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Display-a-linear-combination b/Lang/XPL0/Display-a-linear-combination new file mode 120000 index 0000000000..bd14d58a74 --- /dev/null +++ b/Lang/XPL0/Display-a-linear-combination @@ -0,0 +1 @@ +../../Task/Display-a-linear-combination/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Draw-a-clock b/Lang/XPL0/Draw-a-clock new file mode 120000 index 0000000000..7d1040eda3 --- /dev/null +++ b/Lang/XPL0/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Find-common-directory-path b/Lang/XPL0/Find-common-directory-path new file mode 120000 index 0000000000..29427fdf4b --- /dev/null +++ b/Lang/XPL0/Find-common-directory-path @@ -0,0 +1 @@ +../../Task/Find-common-directory-path/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Fivenum b/Lang/XPL0/Fivenum new file mode 120000 index 0000000000..2bd4e43614 --- /dev/null +++ b/Lang/XPL0/Fivenum @@ -0,0 +1 @@ +../../Task/Fivenum/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Floyd-Warshall-algorithm b/Lang/XPL0/Floyd-Warshall-algorithm new file mode 120000 index 0000000000..ffd21f6111 --- /dev/null +++ b/Lang/XPL0/Floyd-Warshall-algorithm @@ -0,0 +1 @@ +../../Task/Floyd-Warshall-algorithm/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/GUI-component-interaction b/Lang/XPL0/GUI-component-interaction new file mode 120000 index 0000000000..8745be4ca4 --- /dev/null +++ b/Lang/XPL0/GUI-component-interaction @@ -0,0 +1 @@ +../../Task/GUI-component-interaction/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Gaussian-elimination b/Lang/XPL0/Gaussian-elimination new file mode 120000 index 0000000000..6a178b8f16 --- /dev/null +++ b/Lang/XPL0/Gaussian-elimination @@ -0,0 +1 @@ +../../Task/Gaussian-elimination/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Hex-words b/Lang/XPL0/Hex-words new file mode 120000 index 0000000000..4ed3e2b550 --- /dev/null +++ b/Lang/XPL0/Hex-words @@ -0,0 +1 @@ +../../Task/Hex-words/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/I-before-E-except-after-C b/Lang/XPL0/I-before-E-except-after-C new file mode 120000 index 0000000000..4eed624cc7 --- /dev/null +++ b/Lang/XPL0/I-before-E-except-after-C @@ -0,0 +1 @@ +../../Task/I-before-E-except-after-C/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/IBAN b/Lang/XPL0/IBAN new file mode 120000 index 0000000000..ce771b5589 --- /dev/null +++ b/Lang/XPL0/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Joystick-position b/Lang/XPL0/Joystick-position new file mode 120000 index 0000000000..0ba634deb3 --- /dev/null +++ b/Lang/XPL0/Joystick-position @@ -0,0 +1 @@ +../../Task/Joystick-position/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Knapsack-problem-Bounded b/Lang/XPL0/Knapsack-problem-Bounded new file mode 120000 index 0000000000..3ed5296747 --- /dev/null +++ b/Lang/XPL0/Knapsack-problem-Bounded @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Bounded/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Largest-int-from-concatenated-ints b/Lang/XPL0/Largest-int-from-concatenated-ints new file mode 120000 index 0000000000..c906e77c82 --- /dev/null +++ b/Lang/XPL0/Largest-int-from-concatenated-ints @@ -0,0 +1 @@ +../../Task/Largest-int-from-concatenated-ints/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Last-letter-first-letter b/Lang/XPL0/Last-letter-first-letter new file mode 120000 index 0000000000..f77624cd59 --- /dev/null +++ b/Lang/XPL0/Last-letter-first-letter @@ -0,0 +1 @@ +../../Task/Last-letter-first-letter/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Left-factorials b/Lang/XPL0/Left-factorials new file mode 120000 index 0000000000..c9ff64d1b6 --- /dev/null +++ b/Lang/XPL0/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Levenshtein-distance b/Lang/XPL0/Levenshtein-distance new file mode 120000 index 0000000000..0172b975ff --- /dev/null +++ b/Lang/XPL0/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Long-literals-with-continuations b/Lang/XPL0/Long-literals-with-continuations new file mode 120000 index 0000000000..d850e008c5 --- /dev/null +++ b/Lang/XPL0/Long-literals-with-continuations @@ -0,0 +1 @@ +../../Task/Long-literals-with-continuations/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Long-primes b/Lang/XPL0/Long-primes new file mode 120000 index 0000000000..4b515cb676 --- /dev/null +++ b/Lang/XPL0/Long-primes @@ -0,0 +1 @@ +../../Task/Long-primes/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Longest-increasing-subsequence b/Lang/XPL0/Longest-increasing-subsequence new file mode 120000 index 0000000000..bed908bffb --- /dev/null +++ b/Lang/XPL0/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Longest-string-challenge b/Lang/XPL0/Longest-string-challenge new file mode 120000 index 0000000000..08f945d149 --- /dev/null +++ b/Lang/XPL0/Longest-string-challenge @@ -0,0 +1 @@ +../../Task/Longest-string-challenge/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Magic-squares-of-doubly-even-order b/Lang/XPL0/Magic-squares-of-doubly-even-order new file mode 120000 index 0000000000..31327c15e8 --- /dev/null +++ b/Lang/XPL0/Magic-squares-of-doubly-even-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-doubly-even-order/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Meissel-Mertens-constant b/Lang/XPL0/Meissel-Mertens-constant deleted file mode 120000 index 8f73d24896..0000000000 --- a/Lang/XPL0/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Modified-random-distribution b/Lang/XPL0/Modified-random-distribution new file mode 120000 index 0000000000..dfbceea492 --- /dev/null +++ b/Lang/XPL0/Modified-random-distribution @@ -0,0 +1 @@ +../../Task/Modified-random-distribution/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Numerical-integration-Gauss-Legendre-Quadrature b/Lang/XPL0/Numerical-integration-Gauss-Legendre-Quadrature new file mode 120000 index 0000000000..a05d2a56e6 --- /dev/null +++ b/Lang/XPL0/Numerical-integration-Gauss-Legendre-Quadrature @@ -0,0 +1 @@ +../../Task/Numerical-integration-Gauss-Legendre-Quadrature/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Phrase-reversals b/Lang/XPL0/Phrase-reversals new file mode 120000 index 0000000000..2aa0453c8b --- /dev/null +++ b/Lang/XPL0/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Poker-hand-analyser b/Lang/XPL0/Poker-hand-analyser new file mode 120000 index 0000000000..5fc0329088 --- /dev/null +++ b/Lang/XPL0/Poker-hand-analyser @@ -0,0 +1 @@ +../../Task/Poker-hand-analyser/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Polynomial-regression b/Lang/XPL0/Polynomial-regression new file mode 120000 index 0000000000..01f5c8d75a --- /dev/null +++ b/Lang/XPL0/Polynomial-regression @@ -0,0 +1 @@ +../../Task/Polynomial-regression/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Primorial-numbers b/Lang/XPL0/Primorial-numbers new file mode 120000 index 0000000000..6512549f63 --- /dev/null +++ b/Lang/XPL0/Primorial-numbers @@ -0,0 +1 @@ +../../Task/Primorial-numbers/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Quaternion-type b/Lang/XPL0/Quaternion-type deleted file mode 120000 index 03ac35a45d..0000000000 --- a/Lang/XPL0/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Read-a-configuration-file b/Lang/XPL0/Read-a-configuration-file new file mode 120000 index 0000000000..338d315c72 --- /dev/null +++ b/Lang/XPL0/Read-a-configuration-file @@ -0,0 +1 @@ +../../Task/Read-a-configuration-file/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Rep-string b/Lang/XPL0/Rep-string new file mode 120000 index 0000000000..d90ffe53d7 --- /dev/null +++ b/Lang/XPL0/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Sierpinski-square-curve b/Lang/XPL0/Sierpinski-square-curve new file mode 120000 index 0000000000..f8060a7322 --- /dev/null +++ b/Lang/XPL0/Sierpinski-square-curve @@ -0,0 +1 @@ +../../Task/Sierpinski-square-curve/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Sort-numbers-lexicographically b/Lang/XPL0/Sort-numbers-lexicographically new file mode 120000 index 0000000000..f415eaee2b --- /dev/null +++ b/Lang/XPL0/Sort-numbers-lexicographically @@ -0,0 +1 @@ +../../Task/Sort-numbers-lexicographically/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Sort-three-variables b/Lang/XPL0/Sort-three-variables new file mode 120000 index 0000000000..6a041ebc3e --- /dev/null +++ b/Lang/XPL0/Sort-three-variables @@ -0,0 +1 @@ +../../Task/Sort-three-variables/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Sorting-Algorithms-Circle-Sort b/Lang/XPL0/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index a68d7b0426..0000000000 --- a/Lang/XPL0/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Sorting-algorithms-Patience-sort b/Lang/XPL0/Sorting-algorithms-Patience-sort new file mode 120000 index 0000000000..5ca2b1424f --- /dev/null +++ b/Lang/XPL0/Sorting-algorithms-Patience-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Patience-sort/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Sorting-algorithms-Permutation-sort b/Lang/XPL0/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..a50b3c1c69 --- /dev/null +++ b/Lang/XPL0/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Square-free-integers b/Lang/XPL0/Square-free-integers new file mode 120000 index 0000000000..791b667893 --- /dev/null +++ b/Lang/XPL0/Square-free-integers @@ -0,0 +1 @@ +../../Task/Square-free-integers/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Stern-Brocot-sequence b/Lang/XPL0/Stern-Brocot-sequence new file mode 120000 index 0000000000..a67d0ce67d --- /dev/null +++ b/Lang/XPL0/Stern-Brocot-sequence @@ -0,0 +1 @@ +../../Task/Stern-Brocot-sequence/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Strip-block-comments b/Lang/XPL0/Strip-block-comments new file mode 120000 index 0000000000..734cf1b909 --- /dev/null +++ b/Lang/XPL0/Strip-block-comments @@ -0,0 +1 @@ +../../Task/Strip-block-comments/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Substitution-cipher b/Lang/XPL0/Substitution-cipher new file mode 120000 index 0000000000..e26a399b99 --- /dev/null +++ b/Lang/XPL0/Substitution-cipher @@ -0,0 +1 @@ +../../Task/Substitution-cipher/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Subtractive-generator b/Lang/XPL0/Subtractive-generator new file mode 120000 index 0000000000..e69b094ce6 --- /dev/null +++ b/Lang/XPL0/Subtractive-generator @@ -0,0 +1 @@ +../../Task/Subtractive-generator/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Text-processing-1 b/Lang/XPL0/Text-processing-1 new file mode 120000 index 0000000000..395543f260 --- /dev/null +++ b/Lang/XPL0/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Text-processing-2 b/Lang/XPL0/Text-processing-2 new file mode 120000 index 0000000000..8d2b9925ef --- /dev/null +++ b/Lang/XPL0/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Thieles-interpolation-formula b/Lang/XPL0/Thieles-interpolation-formula new file mode 120000 index 0000000000..fcd209a547 --- /dev/null +++ b/Lang/XPL0/Thieles-interpolation-formula @@ -0,0 +1 @@ +../../Task/Thieles-interpolation-formula/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/User-input-Graphical b/Lang/XPL0/User-input-Graphical new file mode 120000 index 0000000000..9b08de25b4 --- /dev/null +++ b/Lang/XPL0/User-input-Graphical @@ -0,0 +1 @@ +../../Task/User-input-Graphical/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Visualize-a-tree b/Lang/XPL0/Visualize-a-tree new file mode 120000 index 0000000000..022c2d2ff2 --- /dev/null +++ b/Lang/XPL0/Visualize-a-tree @@ -0,0 +1 @@ +../../Task/Visualize-a-tree/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Window-creation b/Lang/XPL0/Window-creation new file mode 120000 index 0000000000..8cbc53df4a --- /dev/null +++ b/Lang/XPL0/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/World-Cup-group-stage b/Lang/XPL0/World-Cup-group-stage new file mode 120000 index 0000000000..4312a43d55 --- /dev/null +++ b/Lang/XPL0/World-Cup-group-stage @@ -0,0 +1 @@ +../../Task/World-Cup-group-stage/XPL0 \ No newline at end of file diff --git a/Lang/YAMLScript/00-LANG.txt b/Lang/YAMLScript/00-LANG.txt index 1ead096361..7e44330500 100644 --- a/Lang/YAMLScript/00-LANG.txt +++ b/Lang/YAMLScript/00-LANG.txt @@ -4,22 +4,33 @@ {{language programming paradigm|hosted}} {{implementation|Lisp}} -'''[https://yamlscript.org 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 [https://github.com/yaml/yamlscript/releases ys] and is also available in several programming languages as a binding module to the [https://github.com/yaml/yamlscript/releases libyamlscript.so] shared library: +'''[https://yamlscript.org YS (pronounced "wise", aka 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 YS programs. +You can learn YS for free (with help from experienced mentors) at [https://exercism.org/tracks/yamlscript Exercism]. + +YS has a compiler/interpreter CLI program called [https://github.com/yaml/yamlscript/releases ys] and is also available in several programming languages as a binding module to the [https://github.com/yaml/yamlscript/releases libys.so] shared library: + +* [https://www.nuget.org/packages/YAMLScript/ C#] * [https://clojars.org/org.yamlscript/clj-yamlscript Clojure] +* [https://shardbox.org/shards/yamlscript Crystal] +* [https://github.com/yaml/yamlscript-go Go] +* [https://hackage.haskell.org/package/yamlscript Haskell] * [https://clojars.org/org.yamlscript/yamlscript Java] +* [https://juliahub.com/ui/Packages/General/YAMLScript Julia] +* [https://luarocks.org/modules/ingy/yamlscript Lua] * [https://www.npmjs.com/package/@yaml/yamlscript NodeJS] * [https://metacpan.org/pod/YAMLScript Perl] +* [https://packagist.org/packages/yaml/yamlscript PHP] * [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== +==Installing YS== -Run this command to install the ys command line YAMLScript runner/loader/compiler program. +Run this command to install the ys command line YS runner/loader/compiler binary. - curl -sSL yamlscript.org/install | bash + curl https://getys.org/ys | bash That will install $HOME/.local/bin/ys. If $HOME/.local/bin is not in your PATH, run: @@ -28,14 +39,77 @@ That will install $HOME/.local/bin/ys. If $HOME/.local/bin +#!/usr/bin/env ys-0 + +# Create a Rosetta Code entry for a YS program: + +defn main(program *args): + say: |- + + =={{header|YAMLScript}}== + + $chomp(program:read) + + + when-not ENV.NO_OUT.?: + command =: "ys $program$fmt-args(args)" + output =: bash(command).out:chomp + say: |- + + {{out}} +

    +      $ $command
    +      $output
    +      </pre>
    +
    +defn fmt-args(args):
    +  args =: !:joins
    +    map _ args:
    +      \(re-matches(/[-+,.:\w]+/ _:S)
    +        .if(_ pr-str(_)))
    +  when args.?: " $args"
    +
    + +You run it like this: + +
    +$ ys rosetta-code-ys-entry fibonacci-sequence.ys 5
    +
    +=={{header|YAMLScript}}==
    +
    +!YS-v0
    +
    +defn main(n=10):
    +  loop a 0, b 1, i 1:
    +    say: a
    +    when i < n:
    +      recur: b, (a + b), i.++
    +
    +
    +{{out}}
    +
    +$ ys fibonacci-sequence.ys 5
    +0
    +1
    +1
    +2
    +3
    +</pre>
    +
    \ No newline at end of file diff --git a/Lang/YAMLScript/100-prisoners b/Lang/YAMLScript/100-prisoners new file mode 120000 index 0000000000..bebf8d5d8f --- /dev/null +++ b/Lang/YAMLScript/100-prisoners @@ -0,0 +1 @@ +../../Task/100-prisoners/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/21-game b/Lang/YAMLScript/21-game new file mode 120000 index 0000000000..80f0a3594c --- /dev/null +++ b/Lang/YAMLScript/21-game @@ -0,0 +1 @@ +../../Task/21-game/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/Array-length b/Lang/YAMLScript/Array-length new file mode 120000 index 0000000000..6ab2707560 --- /dev/null +++ b/Lang/YAMLScript/Array-length @@ -0,0 +1 @@ +../../Task/Array-length/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/Average-loop-length b/Lang/YAMLScript/Average-loop-length new file mode 120000 index 0000000000..21710eecef --- /dev/null +++ b/Lang/YAMLScript/Average-loop-length @@ -0,0 +1 @@ +../../Task/Average-loop-length/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/Base64-decode-data b/Lang/YAMLScript/Base64-decode-data new file mode 120000 index 0000000000..0f66fa60fa --- /dev/null +++ b/Lang/YAMLScript/Base64-decode-data @@ -0,0 +1 @@ +../../Task/Base64-decode-data/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/Best-shuffle b/Lang/YAMLScript/Best-shuffle new file mode 120000 index 0000000000..99ffbfc9b1 --- /dev/null +++ b/Lang/YAMLScript/Best-shuffle @@ -0,0 +1 @@ +../../Task/Best-shuffle/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/Conways-Game-of-Life b/Lang/YAMLScript/Conways-Game-of-Life new file mode 120000 index 0000000000..3153c05b26 --- /dev/null +++ b/Lang/YAMLScript/Conways-Game-of-Life @@ -0,0 +1 @@ +../../Task/Conways-Game-of-Life/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/Dragon-curve b/Lang/YAMLScript/Dragon-curve new file mode 120000 index 0000000000..7f9deedb82 --- /dev/null +++ b/Lang/YAMLScript/Dragon-curve @@ -0,0 +1 @@ +../../Task/Dragon-curve/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/Even-or-odd b/Lang/YAMLScript/Even-or-odd new file mode 120000 index 0000000000..95556dd2eb --- /dev/null +++ b/Lang/YAMLScript/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/Floyds-triangle b/Lang/YAMLScript/Floyds-triangle new file mode 120000 index 0000000000..9c388f69f3 --- /dev/null +++ b/Lang/YAMLScript/Floyds-triangle @@ -0,0 +1 @@ +../../Task/Floyds-triangle/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/Function-definition b/Lang/YAMLScript/Function-definition new file mode 120000 index 0000000000..cc6f6727f4 --- /dev/null +++ b/Lang/YAMLScript/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/Greatest-common-divisor b/Lang/YAMLScript/Greatest-common-divisor new file mode 120000 index 0000000000..134280cc97 --- /dev/null +++ b/Lang/YAMLScript/Greatest-common-divisor @@ -0,0 +1 @@ +../../Task/Greatest-common-divisor/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/Integer-comparison b/Lang/YAMLScript/Integer-comparison new file mode 120000 index 0000000000..47b0c04990 --- /dev/null +++ b/Lang/YAMLScript/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/Integer-overflow b/Lang/YAMLScript/Integer-overflow new file mode 120000 index 0000000000..fe6aaac55c --- /dev/null +++ b/Lang/YAMLScript/Integer-overflow @@ -0,0 +1 @@ +../../Task/Integer-overflow/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/JortSort b/Lang/YAMLScript/JortSort new file mode 120000 index 0000000000..28bb797476 --- /dev/null +++ b/Lang/YAMLScript/JortSort @@ -0,0 +1 @@ +../../Task/JortSort/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/Knuth-shuffle b/Lang/YAMLScript/Knuth-shuffle new file mode 120000 index 0000000000..676dc89553 --- /dev/null +++ b/Lang/YAMLScript/Knuth-shuffle @@ -0,0 +1 @@ +../../Task/Knuth-shuffle/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/Luhn-test-of-credit-card-numbers b/Lang/YAMLScript/Luhn-test-of-credit-card-numbers new file mode 120000 index 0000000000..f96e4c4d21 --- /dev/null +++ b/Lang/YAMLScript/Luhn-test-of-credit-card-numbers @@ -0,0 +1 @@ +../../Task/Luhn-test-of-credit-card-numbers/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/Munching-squares b/Lang/YAMLScript/Munching-squares new file mode 120000 index 0000000000..2b7870226f --- /dev/null +++ b/Lang/YAMLScript/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/Next-highest-int-from-digits b/Lang/YAMLScript/Next-highest-int-from-digits new file mode 120000 index 0000000000..6dd0221650 --- /dev/null +++ b/Lang/YAMLScript/Next-highest-int-from-digits @@ -0,0 +1 @@ +../../Task/Next-highest-int-from-digits/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/One-dimensional-cellular-automata b/Lang/YAMLScript/One-dimensional-cellular-automata new file mode 120000 index 0000000000..74c105b72e --- /dev/null +++ b/Lang/YAMLScript/One-dimensional-cellular-automata @@ -0,0 +1 @@ +../../Task/One-dimensional-cellular-automata/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/Palindrome-detection b/Lang/YAMLScript/Palindrome-detection new file mode 120000 index 0000000000..fc4c1cdd2f --- /dev/null +++ b/Lang/YAMLScript/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/Quickselect-algorithm b/Lang/YAMLScript/Quickselect-algorithm new file mode 120000 index 0000000000..978322a04a --- /dev/null +++ b/Lang/YAMLScript/Quickselect-algorithm @@ -0,0 +1 @@ +../../Task/Quickselect-algorithm/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/Sieve-of-Eratosthenes b/Lang/YAMLScript/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..b42b0394f6 --- /dev/null +++ b/Lang/YAMLScript/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/Sparkline-in-unicode b/Lang/YAMLScript/Sparkline-in-unicode new file mode 120000 index 0000000000..ae2a07413c --- /dev/null +++ b/Lang/YAMLScript/Sparkline-in-unicode @@ -0,0 +1 @@ +../../Task/Sparkline-in-unicode/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/Terminal-control-Ringing-the-terminal-bell b/Lang/YAMLScript/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..21baf990a9 --- /dev/null +++ b/Lang/YAMLScript/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/Tokenize-a-string b/Lang/YAMLScript/Tokenize-a-string new file mode 120000 index 0000000000..4c9f0efdcc --- /dev/null +++ b/Lang/YAMLScript/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/Undefined-values b/Lang/YAMLScript/Undefined-values new file mode 120000 index 0000000000..ff7699a995 --- /dev/null +++ b/Lang/YAMLScript/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/Validate-International-Securities-Identification-Number b/Lang/YAMLScript/Validate-International-Securities-Identification-Number new file mode 120000 index 0000000000..40c80b8d7d --- /dev/null +++ b/Lang/YAMLScript/Validate-International-Securities-Identification-Number @@ -0,0 +1 @@ +../../Task/Validate-International-Securities-Identification-Number/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/Van-der-Corput-sequence b/Lang/YAMLScript/Van-der-Corput-sequence new file mode 120000 index 0000000000..654ffd3cbb --- /dev/null +++ b/Lang/YAMLScript/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/Weird-numbers b/Lang/YAMLScript/Weird-numbers new file mode 120000 index 0000000000..bf5aa481d4 --- /dev/null +++ b/Lang/YAMLScript/Weird-numbers @@ -0,0 +1 @@ +../../Task/Weird-numbers/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/Xiaolin-Wus-line-algorithm b/Lang/YAMLScript/Xiaolin-Wus-line-algorithm new file mode 120000 index 0000000000..be316f6902 --- /dev/null +++ b/Lang/YAMLScript/Xiaolin-Wus-line-algorithm @@ -0,0 +1 @@ +../../Task/Xiaolin-Wus-line-algorithm/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/Yellowstone-sequence b/Lang/YAMLScript/Yellowstone-sequence new file mode 120000 index 0000000000..efac2d410f --- /dev/null +++ b/Lang/YAMLScript/Yellowstone-sequence @@ -0,0 +1 @@ +../../Task/Yellowstone-sequence/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/Zig-zag-matrix b/Lang/YAMLScript/Zig-zag-matrix new file mode 120000 index 0000000000..691eda7cd9 --- /dev/null +++ b/Lang/YAMLScript/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/YAMLScript \ No newline at end of file diff --git a/Lang/Yabasic/Associative-array-Merging b/Lang/Yabasic/Associative-array-Merging new file mode 120000 index 0000000000..446716ab58 --- /dev/null +++ b/Lang/Yabasic/Associative-array-Merging @@ -0,0 +1 @@ +../../Task/Associative-array-Merging/Yabasic \ No newline at end of file diff --git a/Lang/Yabasic/Averages-Mean-angle b/Lang/Yabasic/Averages-Mean-angle new file mode 120000 index 0000000000..ee2478f1ef --- /dev/null +++ b/Lang/Yabasic/Averages-Mean-angle @@ -0,0 +1 @@ +../../Task/Averages-Mean-angle/Yabasic \ No newline at end of file diff --git a/Lang/Yabasic/Determine-if-a-string-has-all-the-same-characters b/Lang/Yabasic/Determine-if-a-string-has-all-the-same-characters new file mode 120000 index 0000000000..c1da4813dd --- /dev/null +++ b/Lang/Yabasic/Determine-if-a-string-has-all-the-same-characters @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-has-all-the-same-characters/Yabasic \ No newline at end of file diff --git a/Lang/Yabasic/Determine-sentence-type b/Lang/Yabasic/Determine-sentence-type new file mode 120000 index 0000000000..54129c23c0 --- /dev/null +++ b/Lang/Yabasic/Determine-sentence-type @@ -0,0 +1 @@ +../../Task/Determine-sentence-type/Yabasic \ No newline at end of file diff --git a/Lang/Yabasic/Display-a-linear-combination b/Lang/Yabasic/Display-a-linear-combination new file mode 120000 index 0000000000..3089327b6e --- /dev/null +++ b/Lang/Yabasic/Display-a-linear-combination @@ -0,0 +1 @@ +../../Task/Display-a-linear-combination/Yabasic \ No newline at end of file diff --git a/Lang/Yabasic/Diversity-prediction-theorem b/Lang/Yabasic/Diversity-prediction-theorem new file mode 120000 index 0000000000..5dec4248b2 --- /dev/null +++ b/Lang/Yabasic/Diversity-prediction-theorem @@ -0,0 +1 @@ +../../Task/Diversity-prediction-theorem/Yabasic \ No newline at end of file diff --git a/Lang/Yabasic/Empty-program b/Lang/Yabasic/Empty-program deleted file mode 120000 index 86460983fb..0000000000 --- a/Lang/Yabasic/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Yabasic \ No newline at end of file diff --git a/Lang/Yabasic/Evaluate-binomial-coefficients b/Lang/Yabasic/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..2d010b1897 --- /dev/null +++ b/Lang/Yabasic/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/Yabasic \ No newline at end of file diff --git a/Lang/Yabasic/Kronecker-product b/Lang/Yabasic/Kronecker-product new file mode 120000 index 0000000000..64e2f55421 --- /dev/null +++ b/Lang/Yabasic/Kronecker-product @@ -0,0 +1 @@ +../../Task/Kronecker-product/Yabasic \ No newline at end of file diff --git a/Lang/Yabasic/Meissel-Mertens-constant b/Lang/Yabasic/Meissel-Mertens-constant deleted file mode 120000 index 2300a0e96d..0000000000 --- a/Lang/Yabasic/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/Yabasic \ No newline at end of file diff --git a/Lang/Yabasic/Modular-inverse b/Lang/Yabasic/Modular-inverse new file mode 120000 index 0000000000..996963babe --- /dev/null +++ b/Lang/Yabasic/Modular-inverse @@ -0,0 +1 @@ +../../Task/Modular-inverse/Yabasic \ No newline at end of file diff --git a/Lang/Yabasic/Multiple-regression b/Lang/Yabasic/Multiple-regression new file mode 120000 index 0000000000..047c89f1aa --- /dev/null +++ b/Lang/Yabasic/Multiple-regression @@ -0,0 +1 @@ +../../Task/Multiple-regression/Yabasic \ No newline at end of file diff --git a/Lang/Yabasic/Nested-templated-data b/Lang/Yabasic/Nested-templated-data new file mode 120000 index 0000000000..026a122d79 --- /dev/null +++ b/Lang/Yabasic/Nested-templated-data @@ -0,0 +1 @@ +../../Task/Nested-templated-data/Yabasic \ No newline at end of file diff --git a/Lang/Yabasic/Pascals-triangle b/Lang/Yabasic/Pascals-triangle new file mode 120000 index 0000000000..9cb7c7cced --- /dev/null +++ b/Lang/Yabasic/Pascals-triangle @@ -0,0 +1 @@ +../../Task/Pascals-triangle/Yabasic \ No newline at end of file diff --git a/Lang/Yabasic/Sexy-primes b/Lang/Yabasic/Sexy-primes new file mode 120000 index 0000000000..a3fa026246 --- /dev/null +++ b/Lang/Yabasic/Sexy-primes @@ -0,0 +1 @@ +../../Task/Sexy-primes/Yabasic \ No newline at end of file diff --git a/Lang/Yabasic/Shell-one-liner b/Lang/Yabasic/Shell-one-liner new file mode 120000 index 0000000000..04ae90ab0a --- /dev/null +++ b/Lang/Yabasic/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Yabasic \ No newline at end of file diff --git a/Lang/Yabasic/Sorting-algorithms-Counting-sort b/Lang/Yabasic/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..c5fee45d6b --- /dev/null +++ b/Lang/Yabasic/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/Yabasic \ No newline at end of file diff --git a/Lang/Yabasic/Sorting-algorithms-Stooge-sort b/Lang/Yabasic/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..920cab2b30 --- /dev/null +++ b/Lang/Yabasic/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/Yabasic \ No newline at end of file diff --git a/Lang/Yabasic/Soundex b/Lang/Yabasic/Soundex new file mode 120000 index 0000000000..154bd39b85 --- /dev/null +++ b/Lang/Yabasic/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/Yabasic \ No newline at end of file diff --git a/Lang/Yabasic/Statistics-Normal-distribution b/Lang/Yabasic/Statistics-Normal-distribution new file mode 120000 index 0000000000..f9d32e077f --- /dev/null +++ b/Lang/Yabasic/Statistics-Normal-distribution @@ -0,0 +1 @@ +../../Task/Statistics-Normal-distribution/Yabasic \ No newline at end of file diff --git a/Lang/Yabasic/The-Name-Game b/Lang/Yabasic/The-Name-Game new file mode 120000 index 0000000000..97bfdf9347 --- /dev/null +++ b/Lang/Yabasic/The-Name-Game @@ -0,0 +1 @@ +../../Task/The-Name-Game/Yabasic \ No newline at end of file diff --git a/Lang/Yabasic/Tree-datastructures b/Lang/Yabasic/Tree-datastructures new file mode 120000 index 0000000000..da4a839e0d --- /dev/null +++ b/Lang/Yabasic/Tree-datastructures @@ -0,0 +1 @@ +../../Task/Tree-datastructures/Yabasic \ No newline at end of file diff --git a/Lang/Yabasic/Twos-complement b/Lang/Yabasic/Twos-complement new file mode 120000 index 0000000000..3889fdcaf6 --- /dev/null +++ b/Lang/Yabasic/Twos-complement @@ -0,0 +1 @@ +../../Task/Twos-complement/Yabasic \ No newline at end of file diff --git a/Lang/Yabasic/Web-scraping b/Lang/Yabasic/Web-scraping new file mode 120000 index 0000000000..2a4cb5ee13 --- /dev/null +++ b/Lang/Yabasic/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/Yabasic \ No newline at end of file diff --git a/Lang/ZED/00-LANG.txt b/Lang/ZED/00-LANG.txt index b0cb425a84..5b0358bc17 100644 --- a/Lang/ZED/00-LANG.txt +++ b/Lang/ZED/00-LANG.txt @@ -12,8 +12,9 @@ Development of ZEDc is also happening on GitHub: https://github.com/zelah/ZEDc ZED can be seen compiling itself here: http://ideone.com/ARpMCM +(begin (define (ZED* ZEDnumber1 ZEDnumber2) (cond (#t (* ZEDnumber1 ZEDnumber2)) (else err))) (define (ZED+ ZEDnumber1 ZEDnumber2) (cond (#t (+ ZEDnumber1 ZEDnumber2)) (else err))) (define (ZED- ZEDnumber1 ZEDnumber2) (cond (#t (- ZEDnumber1 ZEDnumber2)) (else err))) (define (ZED/ ZEDnumber1 ZEDnumber2) (cond (#t (/ ZEDnumber1 ZEDnumber2)) (else err))) (define (ZED= value1 value2) (cond (#t (eqv? value1 value2)) (else err))) (define (ZEDadd-between! item list collect) (cond ((null? list) collect) ((null? (cdr list)) (cons (car list) collect)) (#t (ZEDadd-between! item (cdr list) (cons item (cons (car list) collect)))) (else err))) (define (ZEDadd-between item list) (cond (#t (reverse (ZEDadd-between! item list (quote ())))) (else err))) (define (ZEDadd-between-ra list item) (cond (#t (reverse (ZEDadd-between! item list (quote ())))) (else err))) (define (ZEDalpha) (cond (#t (ZEDwrite-all (ZEDrd (quote ()) append (ZEDrd (quote ()) append (ZEDnewlines (ZEDby-four (ZEDfunction-sort (ZEDsentences (ZEDleading-newline (ZEDspace-newline (ZEDtab-replace (ZEDnewline-space-tab-repeats (ZEDnewline-space (ZEDfilter ZEDnot-return? (ZEDreplace-trailing-white-space (ZEDread-all)))))))))))))))) (else err))) (define (ZEDapplication? expression) (cond (#t (and (not (null? expression)) (pair? (car expression)) (null? (cdar expression)))) (else err))) (define (ZEDarity arity-hash function) (cond (#t (cdr (assoc function arity-hash))) (else err))) (define (ZEDarity-hash! clause) (cond (#t (cons (ZEDclause-name clause) (ZEDclause-arity clause))) (else err))) (define (ZEDarity-hash program) (cond (#t (append (map ZEDarity-hash! program) (append (list (cons (quote ZED1) 1) (cons (quote ZED!) 1) (cons (quote ZED001) 1) (cons (quote or) 2) (cons (quote and) 2) (cons (quote begin) 2) (cons (quote ZEDc) 2) (cons (quote quote) 1)) (list (cons (quote ZED002) 2) (cons (quote ZED003) 3) (cons (quote ZED004) 4) (cons (quote ZED005) 5) (cons (quote ZED006) 6) (cons (quote ZED007) 7) (cons (quote ZED008) 8) (cons (quote ZED009) 9) (cons (quote ZED010) 10) (cons (quote ZED011) 11) (cons (quote ZED012) 12) (cons (quote ZED013) 13) (cons (quote ZED014) 14) (cons (quote ZED015) 15) (cons (quote ZED016) 16) (cons (quote ZED017) 17) (cons (quote ZED018) 18) (cons (quote ZED019) 19) (cons (quote ZED020) 20) (cons (quote ZED021) 21) (cons (quote ZED022) 22) (cons (quote ZED023) 23) (cons (quote ZED024) 24) (cons (quote ZED025) 25) (cons (quote ZED026) 26) (cons (quote ZED027) 27) (cons (quote ZED028) 28) (cons (quote ZED029) 29) (cons (quote ZED030) 30) (cons (quote ZED031) 31) (cons (quote ZED032) 32) (cons (quote ZED033) 33) (cons (quote ZED034) 34) (cons (quote ZED035) 35) (cons (quote ZED036) 36) (cons (quote ZED037) 37) (cons (quote ZED038) 38) (cons (quote ZED039) 39) (cons (quote ZED040) 40) (cons (quote ZED041) 41) (cons (quote ZED042) 42) (cons (quote ZED043) 43) (cons (quote ZED044) 44) (cons (quote ZED045) 45) (cons (quote ZED046) 46) (cons (quote ZED047) 47) (cons (quote ZED048) 48) (cons (quote ZED049) 49) (cons (quote ZED050) 50) (cons (quote ZED051) 51) (cons (quote ZED052) 52) (cons (quote ZED053) 53) (cons (quote ZED054) 54) (cons (quote ZED055) 55) (cons (quote ZED056) 56) (cons (quote ZED057) 57) (cons (quote ZED058) 58) (cons (quote ZED059) 59) (cons (quote ZED060) 60) (cons (quote ZED061) 61) (cons (quote ZED062) 62) (cons (quote ZED063) 63) (cons (quote ZED064) 64) (cons (quote ZED065) 65) (cons (quote ZED066) 66) (cons (quote ZED067) 67) (cons (quote ZED068) 68) (cons (quote ZED069) 69) (cons (quote ZED070) 70) (cons (quote ZED071) 71) (cons (quote ZED072) 72) (cons (quote ZED073) 73) (cons (quote ZED074) 74) (cons (quote ZED075) 75) (cons (quote ZED076) 76) (cons (quote ZED077) 77) (cons (quote ZED078) 78) (cons (quote ZED079) 79) (cons (quote ZED080) 80) (cons (quote ZED081) 81) (cons (quote ZED082) 82) (cons (quote ZED083) 83) (cons (quote ZED084) 84) (cons (quote ZED085) 85) (cons (quote ZED086) 86) (cons (quote ZED087) 87) (cons (quote ZED088) 88) (cons (quote ZED089) 89) (cons (quote ZED090) 90) (cons (quote ZED091) 91) (cons (quote ZED092) 92) (cons (quote ZED093) 93) (cons (quote ZED094) 94) (cons (quote ZED095) 95) (cons (quote ZED096) 96) (cons (quote ZED097) 97) (cons (quote ZED098) 98) (cons (quote ZED099) 99))))) (else err))) (define (ZEDby-four! sentences collect) (cond ((null? sentences) collect) (#t (ZEDby-four! (cddddr sentences) (cons (list (car sentences) (cadr sentences) (caddr sentences) (cadddr sentences)) collect))) (else err))) (define (ZEDby-four sentences) (cond (#t (reverse (ZEDby-four! sentences (quote ())))) (else err))) (define (ZEDby-three! sentences collect) (cond ((null? sentences) collect) (#t (ZEDby-three! (cdddr sentences) (cons (list (car sentences) (cadr sentences) (caddr sentences)) collect))) (else err))) (define (ZEDby-three sentences) (cond (#t (reverse (ZEDby-three! sentences (quote ())))) (else err))) (define (ZEDcharacter-less? character1 character2) (cond (#t (< (char->integer character1) (char->integer character2))) (else err))) (define (ZEDclause-arguments clause) (cond (#t (cadr clause)) (else err))) (define (ZEDclause-arguments-agree clause1 clause2) (cond ((equal? (ZEDclause-arguments clause1) (ZEDclause-arguments clause2)) (ZEDclause-arguments clause1)) (else err))) (define (ZEDclause-arity clause) (cond (#t (length (ZEDclause-arguments clause))) (else err))) (define (ZEDclause-body clause) (cond (#t (cddr clause)) (else err))) (define (ZEDclause-less? clause1 clause2) (cond (#t (ZEDsentence-less? (car clause1) (car clause2))) (else err))) (define (ZEDclause-name clause) (cond (#t (car clause)) (else err))) (define (ZEDclause-name-agree clause1 clause2) (cond ((eq? (ZEDclause-name clause1) (ZEDclause-name clause2)) (ZEDclause-name clause1)) (else err))) (define (ZEDcombine-all! program collect) (cond ((null? program) collect) ((null? (cdr program)) (cons (car program) collect)) ((eq? (ZEDclause-name (car program)) (ZEDclause-name (cadr program))) (ZEDcombine-all! (ZEDcombine-head-clauses program) collect)) (#t (ZEDcombine-all! (cdr program) (cons (car program) collect))) (else err))) (define (ZEDcombine-all program) (cond (#t (reverse (ZEDcombine-all! program (quote ())))) (else err))) (define (ZEDcombine-clauses clause1 clause2) (cond (#t (cons (ZEDclause-name-agree clause1 clause2) (cons (ZEDclause-arguments-agree clause1 clause2) (append (ZEDclause-body clause1) (ZEDclause-body clause2))))) (else err))) (define (ZEDcombine-head-clauses program) (cond (#t (cons (ZEDcombine-clauses (car program) (cadr program)) (cddr program))) (else err))) (define (ZEDcombine-program-clauses program) (cond (#t (ZEDcombine-all (ZEDready-program program))) (else err))) (define (ZEDcomp!) (cond (#t (ZEDcomp!a (ZEDcombine-program-clauses (ZEDby-three (ZEDread-sentences (ZEDdiscard-comments (ZEDfunction-sort (ZEDsentences (ZEDleading-newline (ZEDspace-newline (ZEDtab-replace (ZEDnewline-space-tab-repeats (ZEDnewline-space (ZEDfilter ZEDnot-return? (ZEDreplace-trailing-white-space (ZEDread-all)))))))))))))))) (else err))) (define (ZEDcomp!a combined) (cond (#t (ZEDcomp!aa (ZEDprogramize combined (ZEDarity-hash combined)))) (else err))) (define (ZEDcomp!aa programized) (cond (#t (write programized)) (else err))) (define (ZEDcomp) (cond (#t (ZEDcomp!)) (else err))) (define (ZEDcondefy! expressions collect) (cond ((null? expressions) collect) (#t (ZEDcondefy! (cddr expressions) (cons (append (car expressions) (cadr expressions)) collect))) (else err))) (define (ZEDcondefy expressions) (cond (#t (reverse (ZEDcondefy! expressions (quote ())))) (else err))) (define (ZEDcons ZEDvalue1 ZEDvalue2) (cond (#t (cons ZEDvalue1 ZEDvalue2)) (else err))) (define (ZEDcount ZEDnumber) (cond (#t (cons (delay ZEDnumber) (delay (ZEDcount (ZED+ ZEDnumber 1))))) (else err))) (define (ZEDcount-by ZEDstep ZEDnumber) (cond (#t (cons (delay ZEDnumber) (delay (ZEDcount-by ZEDstep (ZED+ ZEDnumber ZEDstep))))) (else err))) (define (ZEDdelay-wrap expression) (cond (#t (list (quote delay) expression)) (else err))) (define (ZEDdigit? character) (cond (#t (or (eqv? #\0 character) (eqv? #\1 character) (eqv? #\2 character) (eqv? #\3 character) (eqv? #\4 character) (eqv? #\5 character) (eqv? #\6 character) (eqv? #\7 character) (eqv? #\8 character) (eqv? #\9 character))) (else err))) (define (ZEDdiscard-comments! program collect) (cond ((null? program) collect) (#t (ZEDdiscard-comments! (cddddr program) (cons (cadddr program) (cons (caddr program) (cons (car program) collect))))) (else err))) (define (ZEDdiscard-comments program) (cond (#t (reverse (ZEDdiscard-comments! program (quote ())))) (else err))) (define (ZEDdr! value) (cond ((pair? value) (ZEDmp ZEDdr! (ZEDfirst 64 value))) (#t value) (else err))) (define (ZEDdr value) (cond (#t (begin (display (ZEDpr (ZEDdr! value))) (newline) (newline) value)) (else err))) (define (ZEDdrr value) (cond (#t (begin (display (ZEDpr value)) (newline) (newline) value)) (else err))) (define (ZEDfalse? noun-list) (cond (#t (equal? noun-list (list ## #\f #\a #\l #\s #\e))) (else err))) (define (ZEDfi function list) (cond ((null? list) (quote ())) ((function (if (promise? (car list)) (force (car list)) (car list))) (cons (delay (if (promise? (car list)) (force (car list)) (car list))) (delay (ZEDfi function (if (promise? (cdr list)) (force (cdr list)) (cdr list)))))) (#t (ZEDfi function (if (promise? (cdr list)) (force (cdr list)) (cdr list)))) (else err))) (define (ZEDfilter! predicate list collect) (cond ((null? list) collect) ((predicate (car list)) (ZEDfilter! predicate (cdr list) (cons (car list) collect))) (#t (ZEDfilter! predicate (cdr list) collect)) (else err))) (define (ZEDfilter predicate list) (cond (#t (reverse (ZEDfilter! predicate list (quote ())))) (else err))) (define (ZEDfirst! integer list collect) (cond ((or (zero? integer) (null? list)) (reverse collect)) ((not (pair? list)) (reverse (cons list collect))) ((> integer 0) (ZEDfirst! (- integer 1) (if (promise? (cdr list)) (force (cdr list)) (cdr list)) (cons (if (promise? (car list)) (force (car list)) (car list)) collect))) (else err))) (define (ZEDfirst integer list) (cond ((not (pair? list)) list) (#t (ZEDfirst! integer list (quote ()))) (else err))) (define (ZEDflatten! ZEDlist ZEDsub-list-found? ZEDcollect) (cond ((and (ZEDnull? ZEDlist) (ZEDnot ZEDsub-list-found?)) (ZEDreverse ZEDcollect)) ((ZEDnull? ZEDlist) (ZEDflatten! (ZEDreverse ZEDcollect) #f (quote ()))) ((ZEDnot (ZEDpair? ZEDlist)) (ZEDflatten! (quote ()) ZEDsub-list-found? (ZEDcons ZEDlist ZEDcollect))) ((ZEDpair? (if (promise? (car ZEDlist)) (force (car ZEDlist)) (car ZEDlist))) (ZEDflatten! (if (promise? (cdr ZEDlist)) (force (cdr ZEDlist)) (cdr ZEDlist)) #t (ZEDcons (if (promise? (cdr (if (promise? (car ZEDlist)) (force (car ZEDlist)) (car ZEDlist)))) (force (cdr (if (promise? (car ZEDlist)) (force (car ZEDlist)) (car ZEDlist)))) (cdr (if (promise? (car ZEDlist)) (force (car ZEDlist)) (car ZEDlist)))) (ZEDcons (if (promise? (car (if (promise? (car ZEDlist)) (force (car ZEDlist)) (car ZEDlist)))) (force (car (if (promise? (car ZEDlist)) (force (car ZEDlist)) (car ZEDlist)))) (car (if (promise? (car ZEDlist)) (force (car ZEDlist)) (car ZEDlist)))) ZEDcollect)))) ((ZEDnull? (if (promise? (car ZEDlist)) (force (car ZEDlist)) (car ZEDlist))) (ZEDflatten! (if (promise? (cdr ZEDlist)) (force (cdr ZEDlist)) (cdr ZEDlist)) ZEDsub-list-found? ZEDcollect)) (#t (ZEDflatten! (if (promise? (cdr ZEDlist)) (force (cdr ZEDlist)) (cdr ZEDlist)) ZEDsub-list-found? (ZEDcons (if (promise? (car ZEDlist)) (force (car ZEDlist)) (car ZEDlist)) ZEDcollect))) (else err))) (define (ZEDflatten ZEDlist) (cond (#t (ZEDflatten! ZEDlist #f (quote ()))) (else err))) (define (ZEDfor-each ZEDeffect ZEDlist) (cond (#t (for-each ZEDeffect ZEDlist)) (else err))) (define (ZEDfunction expression) (cond (#t (caar expression)) (else err))) (define (ZEDfunction-sort sentences) (cond (#t (ZEDrd (quote ()) append (ZEDsort ZEDclause-less? (ZEDby-four sentences)))) (else err))) (define (ZEDfunctionize clause arity-hash) (cond (#t (list (quote define) (cons (ZEDclause-name clause) (ZEDclause-arguments clause)) (cons (quote cond) (append (ZEDcondefy (ZEDmap-with ZEDschemefy (ZEDclause-body clause) arity-hash)) (list (list (quote else) (quote err))))))) (else err))) (define (ZEDgather-count?! candidate) (cond (#t (and (= 6 (length candidate)) (eqv? #\Z (car candidate)) (eqv? #\E (cadr candidate)) (eqv? #\D (caddr candidate)) (eqv? #\0 (cadddr candidate)) (ZEDdigit? (car (cddddr candidate))) (ZEDdigit? (cadr (cddddr candidate))))) (else err))) (define (ZEDgather-count? symbol) (cond (#t (ZEDgather-count?! (string->list (symbol->string symbol)))) (else err))) (define (ZEDgather-noun sentence) (cond ((null? sentence) (quote ())) ((eqv? #\space (car sentence)) (quote ())) (#t (cons (car sentence) (ZEDgather-noun (cdr sentence)))) (else err))) (define (ZEDgather-verb sentence) (cond ((eqv? #) (car sentence)) (quote ())) (#t (cons (car sentence) (ZEDgather-verb (cdr sentence)))) (else err))) (define (ZEDgr garbage value) (cond (#t (begin (ZEDdr garbage) value)) (else err))) (define (ZEDgrr garbage value) (cond (#t (begin (ZEDdrr garbage) value)) (else err))) (define (ZEDleading-newline program) (cond ((null? program) (quote ())) ((eqv? #\newline (car program)) (cdr program)) (#t program) (else err))) (define (ZEDliteral? literal-list) (cond (#t (eqv? #" (car literal-list))) (else err))) (define (ZEDmake-ZED ZED-list) (cond ((equal? ZED-list (list #\e #\r #\r)) "'err") ((equal? ZED-list (list #\n #\i #\l)) "'()") ((equal? ZED-list (list #\a #\n #\d)) "and") ((equal? ZED-list (list #\o #\r)) "or") ((equal? ZED-list (list #\q #\u #\o #\t #\e)) "quote") ((equal? ZED-list (list #\s #\e)) "begin") (#t (list->string (append (list #\Z #\E #\D) ZED-list))) (else err))) (define (ZEDmake-character noun-list) (cond (#t (list->string (cons ## (cons # +(cdr noun-list))))) (else err))) (define (ZEDmake-exact exact-list) (cond (#t (list->string (append (list ## #\e) exact-list))) (else err))) (define (ZEDmake-literal literal-list) (cond (#t (list->string (cdr (reverse (cdr (reverse literal-list)))))) (else err))) (define (ZEDmake-number-character noun-list) (cond (#t (list->string (list ## # +(integer->char (string->number (list->string (cddr noun-list))))))) (else err))) (define (ZEDmap-with! function list extra collect) (cond ((null? list) collect) (#t (ZEDmap-with! function (cdr list) extra (cons (function (car list) extra) collect))) (else err))) (define (ZEDmap-with function list extra) (cond (#t (reverse (ZEDmap-with! function list extra (quote ())))) (else err))) (define (ZEDmerge! comparator list1 list2 collect) (cond ((null? list2) (append (reverse collect) list1)) ((null? list1) (append (reverse collect) list2)) ((comparator (car list2) (car list1)) (ZEDmerge! comparator list1 (cdr list2) (cons (car list2) collect))) (#t (ZEDmerge! comparator (cdr list1) list2 (cons (car list1) collect))) (else err))) (define (ZEDmerge comparator list1 list2) (cond (#t (ZEDmerge! comparator list1 list2 (quote ()))) (else err))) (define (ZEDmp function list) (cond ((null? list) (quote ())) ((pair? list) (cons (delay (function (if (promise? (car list)) (force (car list)) (car list)))) (delay (ZEDmp function (if (promise? (cdr list)) (force (cdr list)) (cdr list)))))) (#t (function list)) (else err))) (define (ZEDnewline-space! program) (cond (#t (cons #\newline (ZEDnewline-space!a program))) (else err))) (define (ZEDnewline-space!a program) (cond (#t (ZEDnewline-space!aa program (reverse (ZEDnewline-space!ab program (quote ()))))) (else err))) (define (ZEDnewline-space!aa program transformed) (cond ((equal? program transformed) program) (#t (ZEDnewline-space!a transformed)) (else err))) (define (ZEDnewline-space!ab program collect) (cond ((null? program) collect) ((null? (cdr program)) (cons (car program) collect)) ((and (eqv? #\newline (car program)) (or (eqv? #\space (cadr program)) (eqv? #\ht (cadr program)))) (ZEDnewline-space!ab (cdr program) collect)) (#t (ZEDnewline-space!ab (cdr program) (cons (car program) collect))) (else err))) (define (ZEDnewline-space program) (cond (#t (ZEDnewline-space! program)) (else err))) (define (ZEDnewline-space-tab-repeats! program collect) (cond ((or (null? program) (null? (cdr program))) (append program collect)) ((and (eqv? #\newline (car program)) (eqv? #\newline (cadr program))) (ZEDnewline-space-tab-repeats! (cdr program) collect)) ((and (or (eqv? #\space (car program)) (eqv? #\ht (car program))) (or (eqv? #\space (cadr program)) (eqv? #\ht (cadr program)))) (ZEDnewline-space-tab-repeats! (cdr program) collect)) (#t (ZEDnewline-space-tab-repeats! (cdr program) (cons (car program) collect))) (else err))) (define (ZEDnewline-space-tab-repeats program) (cond (#t (reverse (ZEDnewline-space-tab-repeats! program (quote ())))) (else err))) (define (ZEDnewlines clauses) (cond (#t (ZEDadd-between-ra (ZEDmap-with ZEDadd-between-ra clauses (list #\newline)) (list (list #\newline #\newline)))) (else err))) (define (ZEDnormal-character? noun-list) (cond (#t (eqv? (car noun-list) ##)) (else err))) (define (ZEDnot ZEDvalue) (cond (#t (not ZEDvalue)) (else err))) (define (ZEDnot-return? character) (cond (#t (not (eqv? #\cr character))) (else err))) (define (ZEDnoun! noun-list number?) (cond (number? (ZEDmake-exact noun-list)) ((ZEDliteral? noun-list) (ZEDmake-literal noun-list)) ((ZEDtrue? noun-list) "#t") ((ZEDfalse? noun-list) "#f") ((ZEDnumber-character? noun-list) (ZEDmake-number-character noun-list)) ((ZEDnormal-character? noun-list) (ZEDmake-character noun-list)) (#t (ZEDmake-ZED noun-list)) (else err))) (define (ZEDnoun noun-list) (cond (#t (ZEDnoun! noun-list (string->number (list->string noun-list)))) (else err))) (define (ZEDnull? ZEDvalue) (cond (#t (null? ZEDvalue)) (else err))) (define (ZEDnumber-character? noun-list) (cond (#t (and (eqv? (car noun-list) ##) (eqv? (cadr noun-list) #\0) (not (null? (cddr noun-list))))) (else err))) (define (ZEDpair? ZEDvalue) (cond (#t (pair? ZEDvalue)) (else err))) (define (ZEDpop stack) (cond (#t (cdr stack)) (else err))) (define (ZEDpr! value output-string) (cond (#t (begin (display (ZEDpr!a value (quote ())) output-string) (ZEDpr!b output-string (get-output-string output-string)))) (else err))) (define (ZEDpr!a value collect) (cond ((char? value) (ZEDpr!aa (list->string (list ## value)) collect)) ((string? value) (ZEDpr!aa (string-append """ value """) collect)) ((symbol? value) (ZEDpr!aa (symbol->string value) collect)) ((number? value) (ZEDpr!aa (number->string value) collect)) ((and (boolean? value) value) (ZEDpr!aa "#true" collect)) ((boolean? value) (ZEDpr!aa "#false" collect)) ((null? value) (reverse collect)) (#t (ZEDpr!a (if (promise? (cdr value)) (force (cdr value)) (cdr value)) (cons (ZEDpr!a (if (promise? (car value)) (force (car value)) (car value)) (quote ())) collect))) (else err))) (define (ZEDpr!aa string collect) (cond ((null? collect) string) (#t (reverse (cons string (cons "." collect)))) (else err))) (define (ZEDpr!b output-string value) (cond (#t (begin (close-output-port output-string) value)) (else err))) (define (ZEDpr value) (cond (#t (ZEDpr! value (open-output-string))) (else err))) (define (ZEDprogramize program arity-hash) (cond (#t (cons (quote begin) (ZEDmap-with ZEDfunctionize program arity-hash))) (else err))) (define (ZEDpush object stack) (cond (#t (cons object stack)) (else err))) (define (ZEDrd! function list) (cond ((null? (if (promise? (cdr list)) (force (cdr list)) (cdr list))) (if (promise? (car list)) (force (car list)) (car list))) (#t (ZEDrd! function (cons (function (if (promise? (car (if (promise? (cdr list)) (force (cdr list)) (cdr list)))) (force (car (if (promise? (cdr list)) (force (cdr list)) (cdr list)))) (car (if (promise? (cdr list)) (force (cdr list)) (cdr list)))) (if (promise? (car list)) (force (car list)) (car list))) (if (promise? (cdr (if (promise? (cdr list)) (force (cdr list)) (cdr list)))) (force (cdr (if (promise? (cdr list)) (force (cdr list)) (cdr list)))) (cdr (if (promise? (cdr list)) (force (cdr list)) (cdr list))))))) (else err))) (define (ZEDrd final function list) (cond (#t (ZEDrd! function (cons final (reverse list)))) (else err))) (define (ZEDread-all! collect) (cond (#t (ZEDread-all!a (read-char) collect)) (else err))) (define (ZEDread-all!a character collect) (cond ((eof-object? character) collect) (#t (ZEDread-all! (cons character collect))) (else err))) (define (ZEDread-all) (cond (#t (reverse (ZEDread-all! (quote ())))) (else err))) (define (ZEDread-sentence!a sentence collect) (cond ((null? sentence) collect) ((eqv? #\space (car sentence)) (ZEDread-sentence!a (cdr sentence) collect)) ((eqv? #( (car sentence)) (ZEDread-sentence!aa sentence (ZEDgather-verb (cdr sentence)) collect)) (#t (ZEDread-sentence!ab sentence (ZEDgather-noun sentence) collect)) (else err))) (define (ZEDread-sentence!aa sentence gather-verb collect) (cond (#t (ZEDread-sentence!a (ZEDtails (+ 2 (length gather-verb)) sentence) (cons (ZEDverb gather-verb) collect))) (else err))) (define (ZEDread-sentence!ab sentence gather-noun collect) (cond (#t (ZEDread-sentence!a (ZEDtails (length gather-noun) sentence) (cons (ZEDnoun gather-noun) collect))) (else err))) (define (ZEDread-sentence!b list output-string) (cond (#t (begin (display list output-string) (ZEDread-sentence!ba output-string (get-output-string output-string)))) (else err))) (define (ZEDread-sentence!ba output-string get-output-string) (cond (#t (begin (close-output-port output-string) (ZEDread-sentence!baa (open-input-string get-output-string)))) (else err))) (define (ZEDread-sentence!baa input-string) (cond (#t (ZEDread-sentence!baaa input-string (read input-string))) (else err))) (define (ZEDread-sentence!baaa input-string answer) (cond (#t (begin (close-input-port input-string) answer)) (else err))) (define (ZEDread-sentence sentence) (cond (#t (ZEDread-sentence!b (reverse (ZEDread-sentence!a sentence (quote ()))) (open-output-string))) (else err))) (define (ZEDread-sentences sentences) (cond (#t (map ZEDread-sentence sentences)) (else err))) (define (ZEDready-clause clause) (cond (#t (cons (caaar clause) (cons (cdar clause) (cdr clause)))) (else err))) (define (ZEDready-program program) (cond (#t (map ZEDready-clause program)) (else err))) (define (ZEDreplace-trailing-white-space! program) (cond ((null? program) (quote ())) ((or (eqv? (car program) #\space) (eqv? (car program) #\ht) (eqv? (car program) #\cr) (eqv? (car program) #\newline)) (ZEDreplace-trailing-white-space! (cdr program))) (#t (cons #\newline program)) (else err))) (define (ZEDreplace-trailing-white-space program) (cond (#t (reverse (ZEDreplace-trailing-white-space! (reverse program)))) (else err))) (define (ZEDreverse ZEDlist) (cond (#t (reverse ZEDlist)) (else err))) (define (ZEDschemefy! expression arity-hash stack) (cond ((null? expression) (ZEDtop stack)) ((ZEDapplication? expression) (ZEDschemefy!a expression arity-hash stack (ZEDfunction expression))) (#t (ZEDschemefy! (cdr expression) arity-hash (ZEDpush (car expression) stack))) (else err))) (define (ZEDschemefy!a expression arity-hash stack function) (cond (#t (ZEDschemefy!aa expression arity-hash stack function (ZEDarity arity-hash function))) (else err))) (define (ZEDschemefy!aa expression arity-hash stack function arity) (cond ((ZEDgather-count? function) (ZEDschemefy! (cdr expression) arity-hash (ZEDpush (ZEDfirst arity stack) (ZEDtails arity stack)))) ((eq? function (quote ZED1)) (ZEDschemefy! (cdr expression) arity-hash (ZEDpush (list (quote if) (list (quote promise?) (cons (quote car) (ZEDfirst arity stack))) (list (quote force) (cons (quote car) (ZEDfirst arity stack))) (cons (quote car) (ZEDfirst arity stack))) (ZEDtails arity stack)))) ((eq? function (quote ZED!)) (ZEDschemefy! (cdr expression) arity-hash (ZEDpush (list (quote if) (list (quote promise?) (cons (quote cdr) (ZEDfirst arity stack))) (list (quote force) (cons (quote cdr) (ZEDfirst arity stack))) (cons (quote cdr) (ZEDfirst arity stack))) (ZEDtails arity stack)))) ((eq? function (quote ZEDc)) (ZEDschemefy! (cdr expression) arity-hash (ZEDpush (cons (quote cons) (map ZEDdelay-wrap (ZEDfirst arity stack))) (ZEDtails arity stack)))) (#t (ZEDschemefy! (cdr expression) arity-hash (ZEDpush (cons function (ZEDfirst arity stack)) (ZEDtails arity stack)))) (else err))) (define (ZEDschemefy expression arity-hash) (cond (#t (list (ZEDschemefy! (reverse expression) arity-hash (ZEDstack)))) (else err))) (define (ZEDsentence-less? sentence1 sentence2) (cond ((null? sentence2) #f) ((null? sentence1) #t) ((ZEDcharacter-less? (car sentence1) (car sentence2)) #t) ((ZEDcharacter-less? (car sentence2) (car sentence1)) #f) (#t (ZEDsentence-less? (cdr sentence1) (cdr sentence2))) (else err))) (define (ZEDsentences! program collect1 collect2) (cond ((null? program) collect2) ((eqv? #\newline (car program)) (ZEDsentences! (cdr program) (quote ()) (cons (reverse collect1) collect2))) (#t (ZEDsentences! (cdr program) (cons (car program) collect1) collect2)) (else err))) (define (ZEDsentences program) (cond (#t (reverse (ZEDsentences! program (quote ()) (quote ())))) (else err))) (define (ZEDsort!a jumble) (cond (#t (map list jumble)) (else err))) (define (ZEDsort!b comparator jumble) (cond ((null? jumble) (quote ())) ((null? (cdr jumble)) jumble) (#t (ZEDsort!b comparator (cons (ZEDmerge comparator (car jumble) (cadr jumble)) (ZEDsort!b comparator (cddr jumble))))) (else err))) (define (ZEDsort comparator jumble) (cond (#t (car (ZEDsort!b comparator (ZEDsort!a jumble)))) (else err))) (define (ZEDspace-newline! program collect) (cond ((or (null? program) (null? (cdr program))) (append program collect)) ((and (eqv? #\space (car program)) (eqv? #\newline (cadr program))) (ZEDspace-newline! (cdr program) collect)) (#t (ZEDspace-newline! (cdr program) (cons (car program) collect))) (else err))) (define (ZEDspace-newline program) (cond (#t (reverse (ZEDspace-newline! program (quote ())))) (else err))) (define (ZEDstack) (cond (#t (quote ())) (else err))) (define (ZEDtab-replace! program collect) (cond ((null? program) collect) ((eqv? #\ht (car program)) (ZEDtab-replace! (cdr program) (cons #\space collect))) (#t (ZEDtab-replace! (cdr program) (cons (car program) collect))) (else err))) (define (ZEDtab-replace program) (cond (#t (reverse (ZEDtab-replace! program (quote ())))) (else err))) (define (ZEDtails number list) (cond ((null? list) (quote ())) ((zero? number) list) ((> number 0) (ZEDtails (- number 1) (cdr list))) (else err))) (define (ZEDtop stack) (cond (#t (car stack)) (else err))) (define (ZEDtrue? noun-list) (cond (#t (equal? noun-list (list ## #\t #\r #\u #\e))) (else err))) (define (ZEDverb verb-list) (cond ((ZEDliteral? verb-list) (list (ZEDmake-literal verb-list))) (#t (list (ZEDmake-ZED verb-list))) (else err))) (define (ZEDwrite-all program) (cond ((null? program) (quote err)) (#t (ZEDwrite-all (begin (write-char (car program)) (cdr program)))) (else err))) (define (ZEDzed->scheme! value collect) (cond ((null? value) (reverse collect)) (#t (ZEDzed->scheme! (if (promise? (cdr value)) (force (cdr value)) (cdr value)) (cons (ZEDzed->scheme (if (promise? (car value)) (force (car value)) (car value))) collect))) (else err))) (define (ZEDzed->scheme value) (cond ((not (pair? value)) value) (#t (ZEDzed->scheme! value (quote ()))) (else err)))) (ZEDcomp) Language author on RC: [[User:Zelah|Zelah]] ([[User_talk:Zelah|talk]] | [[Special:Contributions/Zelah|contribs]]) - -165x2 194x2 207x2 . \ No newline at end of file diff --git a/Lang/ZX-Spectrum-Basic/Sorting-Algorithms-Circle-Sort b/Lang/ZX-Spectrum-Basic/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index c34f35480d..0000000000 --- a/Lang/ZX-Spectrum-Basic/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/ZX-Spectrum-Basic \ No newline at end of file diff --git a/Lang/Zig/15-puzzle-game b/Lang/Zig/15-puzzle-game new file mode 120000 index 0000000000..67842297fa --- /dev/null +++ b/Lang/Zig/15-puzzle-game @@ -0,0 +1 @@ +../../Task/15-puzzle-game/Zig \ No newline at end of file diff --git a/Lang/Zig/15-puzzle-solver b/Lang/Zig/15-puzzle-solver new file mode 120000 index 0000000000..31e2e98f6a --- /dev/null +++ b/Lang/Zig/15-puzzle-solver @@ -0,0 +1 @@ +../../Task/15-puzzle-solver/Zig \ No newline at end of file diff --git a/Lang/Zig/2048 b/Lang/Zig/2048 new file mode 120000 index 0000000000..d2ac81be16 --- /dev/null +++ b/Lang/Zig/2048 @@ -0,0 +1 @@ +../../Task/2048/Zig \ No newline at end of file diff --git a/Lang/Zig/24-game b/Lang/Zig/24-game new file mode 120000 index 0000000000..7b40225753 --- /dev/null +++ b/Lang/Zig/24-game @@ -0,0 +1 @@ +../../Task/24-game/Zig \ No newline at end of file diff --git a/Lang/Zig/24-game-Solve b/Lang/Zig/24-game-Solve new file mode 120000 index 0000000000..cf80fe1aa1 --- /dev/null +++ b/Lang/Zig/24-game-Solve @@ -0,0 +1 @@ +../../Task/24-game-Solve/Zig \ No newline at end of file diff --git a/Lang/Zig/9-billion-names-of-God-the-integer b/Lang/Zig/9-billion-names-of-God-the-integer new file mode 120000 index 0000000000..891e6336a6 --- /dev/null +++ b/Lang/Zig/9-billion-names-of-God-the-integer @@ -0,0 +1 @@ +../../Task/9-billion-names-of-God-the-integer/Zig \ No newline at end of file diff --git a/Lang/Zig/A+B b/Lang/Zig/A+B new file mode 120000 index 0000000000..99c5298cb2 --- /dev/null +++ b/Lang/Zig/A+B @@ -0,0 +1 @@ +../../Task/A+B/Zig \ No newline at end of file diff --git a/Lang/Zig/ABC-problem b/Lang/Zig/ABC-problem new file mode 120000 index 0000000000..4f4592d850 --- /dev/null +++ b/Lang/Zig/ABC-problem @@ -0,0 +1 @@ +../../Task/ABC-problem/Zig \ No newline at end of file diff --git a/Lang/Zig/AVL-tree b/Lang/Zig/AVL-tree new file mode 120000 index 0000000000..05056fdece --- /dev/null +++ b/Lang/Zig/AVL-tree @@ -0,0 +1 @@ +../../Task/AVL-tree/Zig \ No newline at end of file diff --git a/Lang/Zig/Abelian-sandpile-model b/Lang/Zig/Abelian-sandpile-model new file mode 120000 index 0000000000..aff7b1b955 --- /dev/null +++ b/Lang/Zig/Abelian-sandpile-model @@ -0,0 +1 @@ +../../Task/Abelian-sandpile-model/Zig \ No newline at end of file diff --git a/Lang/Zig/Abelian-sandpile-model-Identity b/Lang/Zig/Abelian-sandpile-model-Identity new file mode 120000 index 0000000000..5a22dd3380 --- /dev/null +++ b/Lang/Zig/Abelian-sandpile-model-Identity @@ -0,0 +1 @@ +../../Task/Abelian-sandpile-model-Identity/Zig \ No newline at end of file diff --git a/Lang/Zig/Anti-primes b/Lang/Zig/Anti-primes new file mode 120000 index 0000000000..bde3882591 --- /dev/null +++ b/Lang/Zig/Anti-primes @@ -0,0 +1 @@ +../../Task/Anti-primes/Zig \ No newline at end of file diff --git a/Lang/Zig/Arithmetic-Integer b/Lang/Zig/Arithmetic-Integer new file mode 120000 index 0000000000..3faa5af494 --- /dev/null +++ b/Lang/Zig/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Zig \ No newline at end of file diff --git a/Lang/Zig/Arrays b/Lang/Zig/Arrays new file mode 120000 index 0000000000..8271fea84a --- /dev/null +++ b/Lang/Zig/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/Zig \ No newline at end of file diff --git a/Lang/Zig/Associative-array-Creation b/Lang/Zig/Associative-array-Creation new file mode 120000 index 0000000000..9dff0b181f --- /dev/null +++ b/Lang/Zig/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/Zig \ No newline at end of file diff --git a/Lang/Zig/Associative-array-Iteration b/Lang/Zig/Associative-array-Iteration new file mode 120000 index 0000000000..0120ea3ca0 --- /dev/null +++ b/Lang/Zig/Associative-array-Iteration @@ -0,0 +1 @@ +../../Task/Associative-array-Iteration/Zig \ No newline at end of file diff --git a/Lang/Zig/Babbage-problem b/Lang/Zig/Babbage-problem new file mode 120000 index 0000000000..c79a638466 --- /dev/null +++ b/Lang/Zig/Babbage-problem @@ -0,0 +1 @@ +../../Task/Babbage-problem/Zig \ No newline at end of file diff --git a/Lang/Zig/Babylonian-spiral b/Lang/Zig/Babylonian-spiral new file mode 120000 index 0000000000..518c958994 --- /dev/null +++ b/Lang/Zig/Babylonian-spiral @@ -0,0 +1 @@ +../../Task/Babylonian-spiral/Zig \ No newline at end of file diff --git a/Lang/Zig/Balanced-brackets b/Lang/Zig/Balanced-brackets new file mode 120000 index 0000000000..0a6293637f --- /dev/null +++ b/Lang/Zig/Balanced-brackets @@ -0,0 +1 @@ +../../Task/Balanced-brackets/Zig \ No newline at end of file diff --git a/Lang/Zig/Balanced-ternary b/Lang/Zig/Balanced-ternary new file mode 120000 index 0000000000..aaf8a47b9b --- /dev/null +++ b/Lang/Zig/Balanced-ternary @@ -0,0 +1 @@ +../../Task/Balanced-ternary/Zig \ No newline at end of file diff --git a/Lang/Zig/Base64-decode-data b/Lang/Zig/Base64-decode-data new file mode 120000 index 0000000000..9291a91364 --- /dev/null +++ b/Lang/Zig/Base64-decode-data @@ -0,0 +1 @@ +../../Task/Base64-decode-data/Zig \ No newline at end of file diff --git a/Lang/Zig/Bifid-cipher b/Lang/Zig/Bifid-cipher new file mode 120000 index 0000000000..c3e619eb90 --- /dev/null +++ b/Lang/Zig/Bifid-cipher @@ -0,0 +1 @@ +../../Task/Bifid-cipher/Zig \ No newline at end of file diff --git a/Lang/Zig/Binary-digits b/Lang/Zig/Binary-digits new file mode 120000 index 0000000000..6e0bd7354f --- /dev/null +++ b/Lang/Zig/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/Zig \ No newline at end of file diff --git a/Lang/Zig/Bitcoin-address-validation b/Lang/Zig/Bitcoin-address-validation new file mode 120000 index 0000000000..582e8551db --- /dev/null +++ b/Lang/Zig/Bitcoin-address-validation @@ -0,0 +1 @@ +../../Task/Bitcoin-address-validation/Zig \ No newline at end of file diff --git a/Lang/Zig/Bitmap b/Lang/Zig/Bitmap new file mode 120000 index 0000000000..ef66b502ad --- /dev/null +++ b/Lang/Zig/Bitmap @@ -0,0 +1 @@ +../../Task/Bitmap/Zig \ No newline at end of file diff --git a/Lang/Zig/Boolean-values b/Lang/Zig/Boolean-values new file mode 120000 index 0000000000..8bbec67819 --- /dev/null +++ b/Lang/Zig/Boolean-values @@ -0,0 +1 @@ +../../Task/Boolean-values/Zig \ No newline at end of file diff --git a/Lang/Zig/Boyer-Moore-string-search b/Lang/Zig/Boyer-Moore-string-search new file mode 120000 index 0000000000..9c6dd89c45 --- /dev/null +++ b/Lang/Zig/Boyer-Moore-string-search @@ -0,0 +1 @@ +../../Task/Boyer-Moore-string-search/Zig \ No newline at end of file diff --git a/Lang/Zig/Break-OO-privacy b/Lang/Zig/Break-OO-privacy new file mode 120000 index 0000000000..535f70b15b --- /dev/null +++ b/Lang/Zig/Break-OO-privacy @@ -0,0 +1 @@ +../../Task/Break-OO-privacy/Zig \ No newline at end of file diff --git a/Lang/Zig/Camel-case-and-snake-case b/Lang/Zig/Camel-case-and-snake-case new file mode 120000 index 0000000000..ab00dfd34b --- /dev/null +++ b/Lang/Zig/Camel-case-and-snake-case @@ -0,0 +1 @@ +../../Task/Camel-case-and-snake-case/Zig \ No newline at end of file diff --git a/Lang/Zig/Canonicalize-CIDR b/Lang/Zig/Canonicalize-CIDR new file mode 120000 index 0000000000..792c271f68 --- /dev/null +++ b/Lang/Zig/Canonicalize-CIDR @@ -0,0 +1 @@ +../../Task/Canonicalize-CIDR/Zig \ No newline at end of file diff --git a/Lang/Zig/Cholesky-decomposition b/Lang/Zig/Cholesky-decomposition new file mode 120000 index 0000000000..7fbe65969f --- /dev/null +++ b/Lang/Zig/Cholesky-decomposition @@ -0,0 +1 @@ +../../Task/Cholesky-decomposition/Zig \ No newline at end of file diff --git a/Lang/Zig/Chowla-numbers b/Lang/Zig/Chowla-numbers new file mode 120000 index 0000000000..034b021f26 --- /dev/null +++ b/Lang/Zig/Chowla-numbers @@ -0,0 +1 @@ +../../Task/Chowla-numbers/Zig \ No newline at end of file diff --git a/Lang/Zig/Command-line-arguments b/Lang/Zig/Command-line-arguments new file mode 120000 index 0000000000..5b9231a470 --- /dev/null +++ b/Lang/Zig/Command-line-arguments @@ -0,0 +1 @@ +../../Task/Command-line-arguments/Zig \ No newline at end of file diff --git a/Lang/Zig/Compare-sorting-algorithms-performance b/Lang/Zig/Compare-sorting-algorithms-performance new file mode 120000 index 0000000000..2f98698afb --- /dev/null +++ b/Lang/Zig/Compare-sorting-algorithms-performance @@ -0,0 +1 @@ +../../Task/Compare-sorting-algorithms-performance/Zig \ No newline at end of file diff --git a/Lang/Zig/Convex-hull b/Lang/Zig/Convex-hull new file mode 120000 index 0000000000..bb63712423 --- /dev/null +++ b/Lang/Zig/Convex-hull @@ -0,0 +1 @@ +../../Task/Convex-hull/Zig \ No newline at end of file diff --git a/Lang/Zig/Conways-Game-of-Life b/Lang/Zig/Conways-Game-of-Life new file mode 120000 index 0000000000..d6337a8a7a --- /dev/null +++ b/Lang/Zig/Conways-Game-of-Life @@ -0,0 +1 @@ +../../Task/Conways-Game-of-Life/Zig \ No newline at end of file diff --git a/Lang/Zig/Count-occurrences-of-a-substring b/Lang/Zig/Count-occurrences-of-a-substring new file mode 120000 index 0000000000..820b93c2bb --- /dev/null +++ b/Lang/Zig/Count-occurrences-of-a-substring @@ -0,0 +1 @@ +../../Task/Count-occurrences-of-a-substring/Zig \ No newline at end of file diff --git a/Lang/Zig/Cumulative-standard-deviation b/Lang/Zig/Cumulative-standard-deviation new file mode 120000 index 0000000000..225e824146 --- /dev/null +++ b/Lang/Zig/Cumulative-standard-deviation @@ -0,0 +1 @@ +../../Task/Cumulative-standard-deviation/Zig \ No newline at end of file diff --git a/Lang/Zig/Cyclops-numbers b/Lang/Zig/Cyclops-numbers new file mode 120000 index 0000000000..625d97b345 --- /dev/null +++ b/Lang/Zig/Cyclops-numbers @@ -0,0 +1 @@ +../../Task/Cyclops-numbers/Zig \ No newline at end of file diff --git a/Lang/Zig/De-Bruijn-sequences b/Lang/Zig/De-Bruijn-sequences new file mode 120000 index 0000000000..1e82ee12c7 --- /dev/null +++ b/Lang/Zig/De-Bruijn-sequences @@ -0,0 +1 @@ +../../Task/De-Bruijn-sequences/Zig \ No newline at end of file diff --git a/Lang/Zig/Deal-cards-for-FreeCell b/Lang/Zig/Deal-cards-for-FreeCell new file mode 120000 index 0000000000..8f0b26df35 --- /dev/null +++ b/Lang/Zig/Deal-cards-for-FreeCell @@ -0,0 +1 @@ +../../Task/Deal-cards-for-FreeCell/Zig \ No newline at end of file diff --git a/Lang/Zig/Deconvolution-1D b/Lang/Zig/Deconvolution-1D new file mode 120000 index 0000000000..26b778762a --- /dev/null +++ b/Lang/Zig/Deconvolution-1D @@ -0,0 +1 @@ +../../Task/Deconvolution-1D/Zig \ No newline at end of file diff --git a/Lang/Zig/Determinant-and-permanent b/Lang/Zig/Determinant-and-permanent new file mode 120000 index 0000000000..6aec06c204 --- /dev/null +++ b/Lang/Zig/Determinant-and-permanent @@ -0,0 +1 @@ +../../Task/Determinant-and-permanent/Zig \ No newline at end of file diff --git a/Lang/Zig/Determine-if-a-string-is-numeric b/Lang/Zig/Determine-if-a-string-is-numeric new file mode 120000 index 0000000000..1317ba1b29 --- /dev/null +++ b/Lang/Zig/Determine-if-a-string-is-numeric @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-numeric/Zig \ No newline at end of file diff --git a/Lang/Zig/Dijkstras-algorithm b/Lang/Zig/Dijkstras-algorithm new file mode 120000 index 0000000000..e85779f749 --- /dev/null +++ b/Lang/Zig/Dijkstras-algorithm @@ -0,0 +1 @@ +../../Task/Dijkstras-algorithm/Zig \ No newline at end of file diff --git a/Lang/Zig/Eertree b/Lang/Zig/Eertree new file mode 120000 index 0000000000..297f5d26a6 --- /dev/null +++ b/Lang/Zig/Eertree @@ -0,0 +1 @@ +../../Task/Eertree/Zig \ No newline at end of file diff --git a/Lang/Zig/Egyptian-division b/Lang/Zig/Egyptian-division new file mode 120000 index 0000000000..fbc8453acb --- /dev/null +++ b/Lang/Zig/Egyptian-division @@ -0,0 +1 @@ +../../Task/Egyptian-division/Zig \ No newline at end of file diff --git a/Lang/Zig/Elliptic-Curve-Digital-Signature-Algorithm b/Lang/Zig/Elliptic-Curve-Digital-Signature-Algorithm new file mode 120000 index 0000000000..8631c5bdb3 --- /dev/null +++ b/Lang/Zig/Elliptic-Curve-Digital-Signature-Algorithm @@ -0,0 +1 @@ +../../Task/Elliptic-Curve-Digital-Signature-Algorithm/Zig \ No newline at end of file diff --git a/Lang/Zig/Elliptic-curve-arithmetic b/Lang/Zig/Elliptic-curve-arithmetic new file mode 120000 index 0000000000..6d1206bc71 --- /dev/null +++ b/Lang/Zig/Elliptic-curve-arithmetic @@ -0,0 +1 @@ +../../Task/Elliptic-curve-arithmetic/Zig \ No newline at end of file diff --git a/Lang/Zig/Evolutionary-algorithm b/Lang/Zig/Evolutionary-algorithm new file mode 120000 index 0000000000..59ff814ffb --- /dev/null +++ b/Lang/Zig/Evolutionary-algorithm @@ -0,0 +1 @@ +../../Task/Evolutionary-algorithm/Zig \ No newline at end of file diff --git a/Lang/Zig/Execute-a-Markov-algorithm b/Lang/Zig/Execute-a-Markov-algorithm new file mode 120000 index 0000000000..5b70cd7b50 --- /dev/null +++ b/Lang/Zig/Execute-a-Markov-algorithm @@ -0,0 +1 @@ +../../Task/Execute-a-Markov-algorithm/Zig \ No newline at end of file diff --git a/Lang/Zig/Factors-of-an-integer b/Lang/Zig/Factors-of-an-integer new file mode 120000 index 0000000000..9bd33985d3 --- /dev/null +++ b/Lang/Zig/Factors-of-an-integer @@ -0,0 +1 @@ +../../Task/Factors-of-an-integer/Zig \ No newline at end of file diff --git a/Lang/Zig/Farey-sequence b/Lang/Zig/Farey-sequence new file mode 120000 index 0000000000..44274502d4 --- /dev/null +++ b/Lang/Zig/Farey-sequence @@ -0,0 +1 @@ +../../Task/Farey-sequence/Zig \ No newline at end of file diff --git a/Lang/Zig/Fibonacci-sequence b/Lang/Zig/Fibonacci-sequence new file mode 120000 index 0000000000..8c7ee19f72 --- /dev/null +++ b/Lang/Zig/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/Zig \ No newline at end of file diff --git a/Lang/Zig/Fibonacci-word b/Lang/Zig/Fibonacci-word new file mode 120000 index 0000000000..e5d3567eb0 --- /dev/null +++ b/Lang/Zig/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/Zig \ No newline at end of file diff --git a/Lang/Zig/Find-the-missing-permutation b/Lang/Zig/Find-the-missing-permutation new file mode 120000 index 0000000000..720e08365d --- /dev/null +++ b/Lang/Zig/Find-the-missing-permutation @@ -0,0 +1 @@ +../../Task/Find-the-missing-permutation/Zig \ No newline at end of file diff --git a/Lang/Zig/Floyd-Warshall-algorithm b/Lang/Zig/Floyd-Warshall-algorithm new file mode 120000 index 0000000000..e20cfd03e2 --- /dev/null +++ b/Lang/Zig/Floyd-Warshall-algorithm @@ -0,0 +1 @@ +../../Task/Floyd-Warshall-algorithm/Zig \ No newline at end of file diff --git a/Lang/Zig/Gray-code b/Lang/Zig/Gray-code new file mode 120000 index 0000000000..f2147c406a --- /dev/null +++ b/Lang/Zig/Gray-code @@ -0,0 +1 @@ +../../Task/Gray-code/Zig \ No newline at end of file diff --git a/Lang/Zig/Halt-and-catch-fire b/Lang/Zig/Halt-and-catch-fire new file mode 120000 index 0000000000..c9706c0075 --- /dev/null +++ b/Lang/Zig/Halt-and-catch-fire @@ -0,0 +1 @@ +../../Task/Halt-and-catch-fire/Zig \ No newline at end of file diff --git a/Lang/Zig/Integer-sequence b/Lang/Zig/Integer-sequence new file mode 120000 index 0000000000..43f4f97f8b --- /dev/null +++ b/Lang/Zig/Integer-sequence @@ -0,0 +1 @@ +../../Task/Integer-sequence/Zig \ No newline at end of file diff --git a/Lang/Zig/Jaro-similarity b/Lang/Zig/Jaro-similarity new file mode 120000 index 0000000000..26cb0df4ff --- /dev/null +++ b/Lang/Zig/Jaro-similarity @@ -0,0 +1 @@ +../../Task/Jaro-similarity/Zig \ No newline at end of file diff --git a/Lang/Zig/K-d-tree b/Lang/Zig/K-d-tree new file mode 120000 index 0000000000..3fd542d0d2 --- /dev/null +++ b/Lang/Zig/K-d-tree @@ -0,0 +1 @@ +../../Task/K-d-tree/Zig \ No newline at end of file diff --git a/Lang/Zig/Knapsack-problem-0-1 b/Lang/Zig/Knapsack-problem-0-1 new file mode 120000 index 0000000000..95f8fcd9fc --- /dev/null +++ b/Lang/Zig/Knapsack-problem-0-1 @@ -0,0 +1 @@ +../../Task/Knapsack-problem-0-1/Zig \ No newline at end of file diff --git a/Lang/Zig/Knights-tour b/Lang/Zig/Knights-tour new file mode 120000 index 0000000000..a8fa50bb64 --- /dev/null +++ b/Lang/Zig/Knights-tour @@ -0,0 +1 @@ +../../Task/Knights-tour/Zig \ No newline at end of file diff --git a/Lang/Zig/LZW-compression b/Lang/Zig/LZW-compression new file mode 120000 index 0000000000..fd9ce93698 --- /dev/null +++ b/Lang/Zig/LZW-compression @@ -0,0 +1 @@ +../../Task/LZW-compression/Zig \ No newline at end of file diff --git a/Lang/Zig/Latin-Squares-in-reduced-form b/Lang/Zig/Latin-Squares-in-reduced-form new file mode 120000 index 0000000000..4ae8de3ec8 --- /dev/null +++ b/Lang/Zig/Latin-Squares-in-reduced-form @@ -0,0 +1 @@ +../../Task/Latin-Squares-in-reduced-form/Zig \ No newline at end of file diff --git a/Lang/Zig/Loops-Nested b/Lang/Zig/Loops-Nested new file mode 120000 index 0000000000..a78e39957d --- /dev/null +++ b/Lang/Zig/Loops-Nested @@ -0,0 +1 @@ +../../Task/Loops-Nested/Zig \ No newline at end of file diff --git a/Lang/Zig/M-bius-function b/Lang/Zig/M-bius-function new file mode 120000 index 0000000000..b4ad984b09 --- /dev/null +++ b/Lang/Zig/M-bius-function @@ -0,0 +1 @@ +../../Task/M-bius-function/Zig \ No newline at end of file diff --git a/Lang/Zig/Main-step-of-GOST-28147-89 b/Lang/Zig/Main-step-of-GOST-28147-89 new file mode 120000 index 0000000000..433b294fbc --- /dev/null +++ b/Lang/Zig/Main-step-of-GOST-28147-89 @@ -0,0 +1 @@ +../../Task/Main-step-of-GOST-28147-89/Zig \ No newline at end of file diff --git a/Lang/Zig/Matrix-exponentiation-operator b/Lang/Zig/Matrix-exponentiation-operator new file mode 120000 index 0000000000..273e429228 --- /dev/null +++ b/Lang/Zig/Matrix-exponentiation-operator @@ -0,0 +1 @@ +../../Task/Matrix-exponentiation-operator/Zig \ No newline at end of file diff --git a/Lang/Zig/Modular-arithmetic b/Lang/Zig/Modular-arithmetic new file mode 120000 index 0000000000..a64c6161fe --- /dev/null +++ b/Lang/Zig/Modular-arithmetic @@ -0,0 +1 @@ +../../Task/Modular-arithmetic/Zig \ No newline at end of file diff --git a/Lang/Zig/Modular-inverse b/Lang/Zig/Modular-inverse new file mode 120000 index 0000000000..f96c2102b0 --- /dev/null +++ b/Lang/Zig/Modular-inverse @@ -0,0 +1 @@ +../../Task/Modular-inverse/Zig \ No newline at end of file diff --git a/Lang/Zig/Monty-Hall-problem b/Lang/Zig/Monty-Hall-problem new file mode 120000 index 0000000000..5c32ef8986 --- /dev/null +++ b/Lang/Zig/Monty-Hall-problem @@ -0,0 +1 @@ +../../Task/Monty-Hall-problem/Zig \ No newline at end of file diff --git a/Lang/Zig/Move-to-front-algorithm b/Lang/Zig/Move-to-front-algorithm new file mode 120000 index 0000000000..820f21fe3e --- /dev/null +++ b/Lang/Zig/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/Zig \ No newline at end of file diff --git a/Lang/Zig/Mutual-recursion b/Lang/Zig/Mutual-recursion new file mode 120000 index 0000000000..ad6fe03709 --- /dev/null +++ b/Lang/Zig/Mutual-recursion @@ -0,0 +1 @@ +../../Task/Mutual-recursion/Zig \ No newline at end of file diff --git a/Lang/Zig/Natural-sorting b/Lang/Zig/Natural-sorting new file mode 120000 index 0000000000..ce3fd8d2e1 --- /dev/null +++ b/Lang/Zig/Natural-sorting @@ -0,0 +1 @@ +../../Task/Natural-sorting/Zig \ No newline at end of file diff --git a/Lang/Zig/P-Adic-numbers-basic b/Lang/Zig/P-Adic-numbers-basic new file mode 120000 index 0000000000..7be77909db --- /dev/null +++ b/Lang/Zig/P-Adic-numbers-basic @@ -0,0 +1 @@ +../../Task/P-Adic-numbers-basic/Zig \ No newline at end of file diff --git a/Lang/Zig/P-Adic-square-roots b/Lang/Zig/P-Adic-square-roots new file mode 120000 index 0000000000..bf2f9425e2 --- /dev/null +++ b/Lang/Zig/P-Adic-square-roots @@ -0,0 +1 @@ +../../Task/P-Adic-square-roots/Zig \ No newline at end of file diff --git a/Lang/Zig/Parametric-polymorphism b/Lang/Zig/Parametric-polymorphism new file mode 120000 index 0000000000..76dd4a7ae3 --- /dev/null +++ b/Lang/Zig/Parametric-polymorphism @@ -0,0 +1 @@ +../../Task/Parametric-polymorphism/Zig \ No newline at end of file diff --git a/Lang/Zig/Parse-an-IP-Address b/Lang/Zig/Parse-an-IP-Address new file mode 120000 index 0000000000..dcc1d9a064 --- /dev/null +++ b/Lang/Zig/Parse-an-IP-Address @@ -0,0 +1 @@ +../../Task/Parse-an-IP-Address/Zig \ No newline at end of file diff --git a/Lang/Zig/Parsing-RPN-calculator-algorithm b/Lang/Zig/Parsing-RPN-calculator-algorithm new file mode 120000 index 0000000000..64d52e74e9 --- /dev/null +++ b/Lang/Zig/Parsing-RPN-calculator-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-RPN-calculator-algorithm/Zig \ No newline at end of file diff --git a/Lang/Zig/Parsing-Shunting-yard-algorithm b/Lang/Zig/Parsing-Shunting-yard-algorithm new file mode 120000 index 0000000000..36cb3a3892 --- /dev/null +++ b/Lang/Zig/Parsing-Shunting-yard-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-Shunting-yard-algorithm/Zig \ No newline at end of file diff --git a/Lang/Zig/Pells-equation b/Lang/Zig/Pells-equation new file mode 120000 index 0000000000..dc6754d05f --- /dev/null +++ b/Lang/Zig/Pells-equation @@ -0,0 +1 @@ +../../Task/Pells-equation/Zig \ No newline at end of file diff --git a/Lang/Zig/Permutations-by-swapping b/Lang/Zig/Permutations-by-swapping new file mode 120000 index 0000000000..5e667cc7e2 --- /dev/null +++ b/Lang/Zig/Permutations-by-swapping @@ -0,0 +1 @@ +../../Task/Permutations-by-swapping/Zig \ No newline at end of file diff --git a/Lang/Zig/Quickselect-algorithm b/Lang/Zig/Quickselect-algorithm new file mode 120000 index 0000000000..7dbb81ef78 --- /dev/null +++ b/Lang/Zig/Quickselect-algorithm @@ -0,0 +1 @@ +../../Task/Quickselect-algorithm/Zig \ No newline at end of file diff --git a/Lang/Zig/Quine b/Lang/Zig/Quine new file mode 120000 index 0000000000..20f1f12898 --- /dev/null +++ b/Lang/Zig/Quine @@ -0,0 +1 @@ +../../Task/Quine/Zig \ No newline at end of file diff --git a/Lang/Zig/SHA-1 b/Lang/Zig/SHA-1 new file mode 120000 index 0000000000..374af24054 --- /dev/null +++ b/Lang/Zig/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/Zig \ No newline at end of file diff --git a/Lang/Zig/Sisyphus-sequence b/Lang/Zig/Sisyphus-sequence new file mode 120000 index 0000000000..58dd5ff994 --- /dev/null +++ b/Lang/Zig/Sisyphus-sequence @@ -0,0 +1 @@ +../../Task/Sisyphus-sequence/Zig \ No newline at end of file diff --git a/Lang/Zig/Solve-a-Holy-Knights-tour b/Lang/Zig/Solve-a-Holy-Knights-tour new file mode 120000 index 0000000000..b0fe3fcb9a --- /dev/null +++ b/Lang/Zig/Solve-a-Holy-Knights-tour @@ -0,0 +1 @@ +../../Task/Solve-a-Holy-Knights-tour/Zig \ No newline at end of file diff --git a/Lang/Zig/Solve-the-no-connection-puzzle b/Lang/Zig/Solve-the-no-connection-puzzle new file mode 120000 index 0000000000..4b3367c677 --- /dev/null +++ b/Lang/Zig/Solve-the-no-connection-puzzle @@ -0,0 +1 @@ +../../Task/Solve-the-no-connection-puzzle/Zig \ No newline at end of file diff --git a/Lang/Zig/Sorting-algorithms-Patience-sort b/Lang/Zig/Sorting-algorithms-Patience-sort new file mode 120000 index 0000000000..a696e81abf --- /dev/null +++ b/Lang/Zig/Sorting-algorithms-Patience-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Patience-sort/Zig \ No newline at end of file diff --git a/Lang/Zig/Sorting-algorithms-Strand-sort b/Lang/Zig/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..67361c524c --- /dev/null +++ b/Lang/Zig/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/Zig \ No newline at end of file diff --git a/Lang/Zig/Stern-Brocot-sequence b/Lang/Zig/Stern-Brocot-sequence new file mode 120000 index 0000000000..4e68e871bc --- /dev/null +++ b/Lang/Zig/Stern-Brocot-sequence @@ -0,0 +1 @@ +../../Task/Stern-Brocot-sequence/Zig \ No newline at end of file diff --git a/Lang/Zig/Strassens-algorithm b/Lang/Zig/Strassens-algorithm new file mode 120000 index 0000000000..f02a6cb05a --- /dev/null +++ b/Lang/Zig/Strassens-algorithm @@ -0,0 +1 @@ +../../Task/Strassens-algorithm/Zig \ No newline at end of file diff --git a/Lang/Zig/Stream-merge b/Lang/Zig/Stream-merge new file mode 120000 index 0000000000..83ddc64918 --- /dev/null +++ b/Lang/Zig/Stream-merge @@ -0,0 +1 @@ +../../Task/Stream-merge/Zig \ No newline at end of file diff --git a/Lang/Zig/Sudoku b/Lang/Zig/Sudoku new file mode 120000 index 0000000000..cc0b8be01d --- /dev/null +++ b/Lang/Zig/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/Zig \ No newline at end of file diff --git a/Lang/Zig/Sutherland-Hodgman-polygon-clipping b/Lang/Zig/Sutherland-Hodgman-polygon-clipping new file mode 120000 index 0000000000..2e08ab9fc7 --- /dev/null +++ b/Lang/Zig/Sutherland-Hodgman-polygon-clipping @@ -0,0 +1 @@ +../../Task/Sutherland-Hodgman-polygon-clipping/Zig \ No newline at end of file diff --git a/Lang/Zig/Tarjan b/Lang/Zig/Tarjan new file mode 120000 index 0000000000..47db828add --- /dev/null +++ b/Lang/Zig/Tarjan @@ -0,0 +1 @@ +../../Task/Tarjan/Zig \ No newline at end of file diff --git a/Lang/Zig/Thue-Morse b/Lang/Zig/Thue-Morse new file mode 120000 index 0000000000..514eeceeed --- /dev/null +++ b/Lang/Zig/Thue-Morse @@ -0,0 +1 @@ +../../Task/Thue-Morse/Zig \ No newline at end of file diff --git a/Lang/Zig/Tonelli-Shanks-algorithm b/Lang/Zig/Tonelli-Shanks-algorithm new file mode 120000 index 0000000000..364e6278fd --- /dev/null +++ b/Lang/Zig/Tonelli-Shanks-algorithm @@ -0,0 +1 @@ +../../Task/Tonelli-Shanks-algorithm/Zig \ No newline at end of file diff --git a/Lang/Zig/Tree-datastructures b/Lang/Zig/Tree-datastructures new file mode 120000 index 0000000000..2483259e7c --- /dev/null +++ b/Lang/Zig/Tree-datastructures @@ -0,0 +1 @@ +../../Task/Tree-datastructures/Zig \ No newline at end of file diff --git a/Lang/Zig/Verhoeff-algorithm b/Lang/Zig/Verhoeff-algorithm new file mode 120000 index 0000000000..d90fb8e2ca --- /dev/null +++ b/Lang/Zig/Verhoeff-algorithm @@ -0,0 +1 @@ +../../Task/Verhoeff-algorithm/Zig \ No newline at end of file diff --git a/Lang/Zig/Vigen-re-cipher-Cryptanalysis b/Lang/Zig/Vigen-re-cipher-Cryptanalysis new file mode 120000 index 0000000000..7fd7d3aa92 --- /dev/null +++ b/Lang/Zig/Vigen-re-cipher-Cryptanalysis @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher-Cryptanalysis/Zig \ No newline at end of file diff --git a/Lang/Zig/Vogels-approximation-method b/Lang/Zig/Vogels-approximation-method new file mode 120000 index 0000000000..af40cfb307 --- /dev/null +++ b/Lang/Zig/Vogels-approximation-method @@ -0,0 +1 @@ +../../Task/Vogels-approximation-method/Zig \ No newline at end of file diff --git a/Lang/Zig/War-card-game b/Lang/Zig/War-card-game new file mode 120000 index 0000000000..6bc9afa5bf --- /dev/null +++ b/Lang/Zig/War-card-game @@ -0,0 +1 @@ +../../Task/War-card-game/Zig \ No newline at end of file diff --git a/Lang/Zig/Y-combinator b/Lang/Zig/Y-combinator new file mode 120000 index 0000000000..1478dbbdb7 --- /dev/null +++ b/Lang/Zig/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Zig \ No newline at end of file diff --git a/Lang/Zkl/Bioinformatics-base-count b/Lang/Zkl/Bioinformatics-base-count deleted file mode 120000 index f344937ca4..0000000000 --- a/Lang/Zkl/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Miller-Rabin-primality-test b/Lang/Zkl/Miller-Rabin-primality-test deleted file mode 120000 index 92bfcfa6ff..0000000000 --- a/Lang/Zkl/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Quaternion-type b/Lang/Zkl/Quaternion-type deleted file mode 120000 index d36f19dd00..0000000000 --- a/Lang/Zkl/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Sorting-Algorithms-Circle-Sort b/Lang/Zkl/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 6de597a14d..0000000000 --- a/Lang/Zkl/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Zkl \ No newline at end of file diff --git a/Lang/Zonnon/00-LANG.txt b/Lang/Zonnon/00-LANG.txt index 8a95e192c9..e4a45b3fa4 100644 --- a/Lang/Zonnon/00-LANG.txt +++ b/Lang/Zonnon/00-LANG.txt @@ -3,4 +3,11 @@ |site=http://www.zonnon.ethz.ch/ |LCT=yes }} -Zonnon is a general-purpose programming language in the [[Pascal]], [[Modula-2]] and [[Oberon]] family. It retains an emphasis on simplicity, clear syntax and separation of concerns whilst focusing on concurrency and ease of composition and expression. Unification of abstractions is at the heart of its design and this is reflected in its conceptual model based on modules, objects, definitions and implementations. Zonnon offers a new computing model based on active objects with their interaction defined by syntax controlled dialogs. It also introduces new features including operator overloading and exception handling, and is specifically designed to be platform independent. \ No newline at end of file +Zonnon is a general-purpose programming language in the [[Pascal]], [[Modula-2]] and [[Oberon]] family. It retains an emphasis on simplicity, clear syntax and separation of concerns whilst focusing on concurrency and ease of composition and expression. Unification of abstractions is at the heart of its design and this is reflected in its conceptual model based on modules, objects, definitions and implementations. Zonnon offers a new computing model based on active objects with their interaction defined by syntax controlled dialogs. It also introduces new features including operator overloading and exception handling, and is specifically designed to be platform independent. + +===See also=== +* [[Oberon-07]] +* [[Oberon-2]] +* [[Component Pascal]] +* [[Modula-2]] +* [[Modula-3]] \ No newline at end of file diff --git a/Task/100-doors/00-TASK.txt b/Task/100-doors/00-TASK.txt index fd7471448b..83471393d8 100644 --- a/Task/100-doors/00-TASK.txt +++ b/Task/100-doors/00-TASK.txt @@ -2,21 +2,26 @@ There are 100 doors in a row that are all initially closed. You make 100 [[task feature::Rosetta Code:multiple passes|passes]] by the doors. -The first time through, visit every door and  ''toggle''  the door  (if the door is closed,  open it;   if it is open,  close it). +The first time through, visit every door and ''toggle'' the door (if the door is closed, open it; if it is open, close it). -The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. +The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it. -The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door. +The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door. ;Task: -Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed? +Answer the question: what state are the doors in after the last pass? Which are open, which are closed? '''[[task feature::Rosetta Code:extra credit|Alternate]]:''' -As noted in this page's   [[Talk:100 doors|discussion page]],   the only doors that remain open are those whose numbers are perfect squares. +As noted in this page's [[Talk:100 doors|discussion page]], the only doors that remain open are those whose numbers are perfect squares. -Opening only those doors is an   [[task feature::Rosetta Code:optimization|optimization]]   that may also be expressed; +Opening only those doors is an [[task feature::Rosetta Code:optimization|optimization]] that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.

    +;Why doesn't syntax highlighting work on this page ?: +Currently, there is a limit on how many <syntaxhighlight> tags can appear on a page, so only the first few languages get highlighting, the rest are shown in monochrome.
    +You could try "manual highlighting", possibly using one of the highlighters on [[Syntax highlighting using Mediawiki formatting]] or something similar. + + diff --git a/Task/100-doors/11l/100-doors.11l b/Task/100-doors/11l/100-doors.11l index 3783f3ff5a..2808744415 100644 --- a/Task/100-doors/11l/100-doors.11l +++ b/Task/100-doors/11l/100-doors.11l @@ -1,5 +1,5 @@ V doors = [0B] * 100 -L(i) 100 +L(i) 0.<100 L(j) (i .< 100).step(i + 1) doors[j] = !doors[j] print(‘Door ’(i + 1)‘: ’(I doors[i] {‘open’} E ‘close’)) diff --git a/Task/100-doors/8080-Assembly/100-doors.8080 b/Task/100-doors/8080-Assembly/100-doors-1.8080 similarity index 100% rename from Task/100-doors/8080-Assembly/100-doors.8080 rename to Task/100-doors/8080-Assembly/100-doors-1.8080 diff --git a/Task/100-doors/8080-Assembly/100-doors-2.8080 b/Task/100-doors/8080-Assembly/100-doors-2.8080 new file mode 100644 index 0000000000..d5cb28c55f --- /dev/null +++ b/Task/100-doors/8080-Assembly/100-doors-2.8080 @@ -0,0 +1,79 @@ +wboot equ 0 ; jump to BIOS warm boot routine +bdos equ 5 ; BDOS entry +conout equ 2 ; BDOS console output function +putstr equ 9 ; BDOS print string function +ndoors equ 100 ; number of doors + ; + org 100h + lxi sp,stack ; set our own stack + lxi d,intro ; print introductory message + mvi c,putstr + call bdos + ; + ; generate sequence of squares to specified limit + ; HL holds the current square + ; DE holds the increment + ; BC holds the negative of the limit + ; +gensqr: lxi h,1 ; starting value of square + lxi d,3 ; starting value of increment + lxi b,-ndoors +sqrs2: call putdec ; otherwise print current square + mvi a,' ' ; separate with a space + call putchr + push h ; have we reached the limit? + dad b + pop h + jc done ; CY if HL > limit + dad d ; square += incrememnt + inx d ; increment += 2 + inx d + jmp sqrs2 ; repeat until finished + ; +done: jmp wboot ; exit with warm boot + ;--------------------------------------------------- + ; console output of char in A register + ;--------------------------------------------------- +putchr: push h + push d + push b + mov e,a + mvi c,conout + call bdos + pop b + pop d + pop h + ret + ;--------------------------------------------------- + ; Output decimal number to console + ; HL holds 16-bit unsigned binary number to print + ;--------------------------------------------------- +putdec: push b + push d + push h + lxi b,-10 + lxi d,-1 +putdec2: + dad b + inx d + jc putdec2 + lxi b,10 + dad b + xchg + mov a,h + ora l + cnz putdec ; recursive call + mov a,e + adi '0' + call putchr + pop h + pop d + pop b + ret + ;--------------------------------------------------- + ; data area and stack + ;--------------------------------------------------- +intro: db 'The open doors are: $' +stack equ $+128 ; 64-level stack + ; + end diff --git a/Task/100-doors/ANSI-BASIC/100-doors.basic b/Task/100-doors/ANSI-BASIC/100-doors.basic new file mode 100644 index 0000000000..eec806c191 --- /dev/null +++ b/Task/100-doors/ANSI-BASIC/100-doors.basic @@ -0,0 +1,21 @@ +100 REM 100 doors +110 REM The unoptimised door flipping method +120 REM which simulates the process +130 DIM IsDoorOpen(1 TO 100) +140 LET DoorMax = UBOUND(IsDoorOpen) +150 REM Set all doors to closed +160 FOR I = 1 TO DoorMax +170 LET IsDoorOpen(I) = 0 +180 NEXT I +190 REM Repeatedly flip the doors +200 FOR I = 1 TO DoorMax +210 FOR J = I TO DoorMax STEP I +220 LET IsDoorOpen(J) = 1 - IsDoorOpen(J) +230 NEXT J +240 NEXT I +250 REM Display the results +260 FOR I = 1 TO DoorMax +270 IF IsDoorOpen(I) <> 0 THEN PRINT I; +280 NEXT I +290 PRINT +300 END diff --git a/Task/100-doors/APL/100-doors-2.apl b/Task/100-doors/APL/100-doors-2.apl index ba6d739dae..bff8982b24 100644 --- a/Task/100-doors/APL/100-doors-2.apl +++ b/Task/100-doors/APL/100-doors-2.apl @@ -1,3 +1 @@ -⍝⍝ Also works with GNU APL after introduction of -⍝⍝ the ⍸ function with SVN r1368, Dec 03 2020 -⍸≠⌿0=(⍳100)∘.|⍳100 +≠⌿0=(⍳100)∘.|⍳100 diff --git a/Task/100-doors/APL/100-doors-3.apl b/Task/100-doors/APL/100-doors-3.apl new file mode 100644 index 0000000000..5fcad5e104 --- /dev/null +++ b/Task/100-doors/APL/100-doors-3.apl @@ -0,0 +1 @@ +⍸≠⌿0=(⍳100)∘.|⍳100 diff --git a/Task/100-doors/AWK/100-doors-1.awk b/Task/100-doors/AWK/100-doors-1.awk deleted file mode 100644 index 1c2a279c09..0000000000 --- a/Task/100-doors/AWK/100-doors-1.awk +++ /dev/null @@ -1,17 +0,0 @@ -BEGIN { - for(i=1; i <= 100; i++) - { - doors[i] = 0 # close the doors - } - for(i=1; i <= 100; i++) - { - for(j=i; j <= 100; j += i) - { - doors[j] = (doors[j]+1) % 2 - } - } - for(i=1; i <= 100; i++) - { - print i, doors[i] ? "open" : "close" - } -} diff --git a/Task/100-doors/AWK/100-doors-2.awk b/Task/100-doors/AWK/100-doors-2.awk deleted file mode 100644 index 9344bbec27..0000000000 --- a/Task/100-doors/AWK/100-doors-2.awk +++ /dev/null @@ -1,14 +0,0 @@ -BEGIN { - for(i=1; i <= 100; i++) { - doors[i] = 0 # close the doors - } - for(i=1; i <= 100; i++) { - if ( int(sqrt(i)) == sqrt(i) ) { - doors[i] = 1 - } - } - for(i=1; i <= 100; i++) - { - print i, doors[i] ? "open" : "close" - } -} diff --git a/Task/100-doors/Ada/100-doors-1.ada b/Task/100-doors/Ada/100-doors-1.adb similarity index 100% rename from Task/100-doors/Ada/100-doors-1.ada rename to Task/100-doors/Ada/100-doors-1.adb diff --git a/Task/100-doors/Ada/100-doors-2.ada b/Task/100-doors/Ada/100-doors-2.adb similarity index 100% rename from Task/100-doors/Ada/100-doors-2.ada rename to Task/100-doors/Ada/100-doors-2.adb diff --git a/Task/100-doors/Adina/100-doors-1.adina b/Task/100-doors/Adina/100-doors-1.adina new file mode 100644 index 0000000000..0e7190c89e --- /dev/null +++ b/Task/100-doors/Adina/100-doors-1.adina @@ -0,0 +1,16 @@ +двери = новый-массив 100 ложь + +цикл + шаг + в-диапазоне 1 101 + цикл + номер + в-диапазоне (шаг - 1) 100 шаг + двери[номер] := не двери[номер] + +цикл + номер 100 + вывести/перенос + формат «Дверь ~a ~a» + номер + 1 + двери[номер] ? «открыта» «закрыта» diff --git a/Task/100-doors/Adina/100-doors-2.adina b/Task/100-doors/Adina/100-doors-2.adina new file mode 100644 index 0000000000..6286140dc0 --- /dev/null +++ b/Task/100-doors/Adina/100-doors-2.adina @@ -0,0 +1,17 @@ +english() +doors = make-vector 100 #f + +for + $ step + in-range 1 101 + for + $ number + in-range (step - 1) 100 step + doors[number] := not doors[number] + +for + $ number 100 + displayln + format "Door ~a ~a" + number + 1 + if doors[number] "open" "closed" diff --git a/Task/100-doors/Agena/100-doors.agena b/Task/100-doors/Agena/100-doors.agena deleted file mode 100644 index 18c9cb1963..0000000000 --- a/Task/100-doors/Agena/100-doors.agena +++ /dev/null @@ -1,19 +0,0 @@ -# find the first few squares via the unoptimised door flipping method -scope - - local doorMax := 100; - local door; - create register door( doorMax ); - - # set all doors to closed - for i to doorMax do door[ i ] := false od; - - # repeatedly flip the doors - for i to doorMax do - for j from i to doorMax by i do door[ j ] := not door[ j ] od - od; - - # display the results - for i to doorMax do if door[ i ] then write( " ", i ) fi od; print() - -epocs diff --git a/Task/100-doors/ArkScript/100-doors-1.ark b/Task/100-doors/ArkScript/100-doors-1.ark new file mode 100644 index 0000000000..713e3b360f --- /dev/null +++ b/Task/100-doors/ArkScript/100-doors-1.ark @@ -0,0 +1,21 @@ +(import std.Range :range :forEach) +(import std.List) + +(mut doors (list:fill 100 false)) +(let r (range 0 100)) + +(forEach r + (fun (i) { + (mut j i) + (while (< j 100) { + (@= doors j (not (@ doors j))) + (set j (+ j i 1)) }) + (print doors) })) + +(print + (list:map + (list:filter + (list:zipWithIndex doors) + (fun (e) + (@ e 1))) + (fun (e) (@ e 0)))) diff --git a/Task/100-doors/ArkScript/100-doors-2.ark b/Task/100-doors/ArkScript/100-doors-2.ark new file mode 100644 index 0000000000..b1cb4380b2 --- /dev/null +++ b/Task/100-doors/ArkScript/100-doors-2.ark @@ -0,0 +1,4 @@ +[true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true] +... +[true false false true false false false false true false false false false false false true false false false false false false false false true false false false false false false false false false false true false false false false false false false false false false false false true false false false false false false false false false false false false false false true false false false false false false false false false false false false false false false false true false false false false false false false false false false false false false false false false false false true] +[0 3 8 15 24 35 48 63 80 99] diff --git a/Task/100-doors/AutoIt/100-doors.autoit b/Task/100-doors/AutoIt/100-doors.au3 similarity index 100% rename from Task/100-doors/AutoIt/100-doors.autoit rename to Task/100-doors/AutoIt/100-doors.au3 diff --git a/Task/100-doors/AutoLISP/100-doors.lsp b/Task/100-doors/AutoLISP/100-doors.lsp new file mode 100644 index 0000000000..d4a0ebbe77 --- /dev/null +++ b/Task/100-doors/AutoLISP/100-doors.lsp @@ -0,0 +1,18 @@ +(defun CreateDoors (n / doors) + (repeat n + (setq doors (cons nil doors)) + ) +) + +(defun Doors (doors / cnt) + (setq cnt 0) + (mapcar + '(lambda (d) + (zerop (rem (sqrt (setq cnt (1+ cnt))) 1)) + ) + doors + ) +) + +> (Doors (CreateDoors 100)) +(T nil nil T nil nil nil nil T nil nil nil nil nil nil T nil nil nil nil nil nil nil nil T nil nil nil nil nil nil nil nil nil nil T nil nil nil nil nil nil nil nil nil nil nil nil T nil nil nil nil nil nil nil nil nil nil nil nil nil nil T nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil T nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil T nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil T nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil T nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil T nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil T nil nil nil nil) diff --git a/Task/100-doors/BQN/100-doors-4.bqn b/Task/100-doors/BQN/100-doors-4.bqn new file mode 100644 index 0000000000..cfab61e191 --- /dev/null +++ b/Task/100-doors/BQN/100-doors-4.bqn @@ -0,0 +1,3 @@ +F ← {1+ / 2| +˝ 0= |⌜˜ 1+↕𝕩} +F 100 +# ⟨ 1 4 9 16 25 36 49 64 81 100 ⟩ diff --git a/Task/100-doors/BQN/100-doors-5.bqn b/Task/100-doors/BQN/100-doors-5.bqn new file mode 100644 index 0000000000..b78e4f3de6 --- /dev/null +++ b/Task/100-doors/BQN/100-doors-5.bqn @@ -0,0 +1,3 @@ +F ← {ט1+↕⌊√𝕩} +F 100 +# ⟨ 1 4 9 16 25 36 49 64 81 100 ⟩ diff --git a/Task/100-doors/Ballerina/100-doors.ballerina b/Task/100-doors/Ballerina/100-doors.ballerina new file mode 100644 index 0000000000..35d7c63798 --- /dev/null +++ b/Task/100-doors/Ballerina/100-doors.ballerina @@ -0,0 +1,16 @@ +// https://rosettacode.org/wiki/100_doors +import ballerina/io; + +public function main() { + boolean[100] doors = []; + foreach int i in int:range(0,100,1) { + foreach int j in int:range(i, 100, i+1) { + doors[j] = ! doors[j]; + } + } + foreach int i in int:range(0,doors.length(),1) { + if doors[i] { + io:println("Door #",i+1," is ","open"); + } + } +} diff --git a/Task/100-doors/C-sharp/100-doors-1.cs b/Task/100-doors/C-sharp/100-doors-1.cs index d06413f95c..3e031cc721 100644 --- a/Task/100-doors/C-sharp/100-doors-1.cs +++ b/Task/100-doors/C-sharp/100-doors-1.cs @@ -5,11 +5,10 @@ namespace ConsoleApplication1 { static void Main(string[] args) { + // Arrays are initialized to their type default values; the default for bool is false + // Use false to indicate closed door bool[] doors = new bool[100]; - //Close all doors to start. - for (int d = 0; d < 100; d++) doors[d] = false; - //For each pass... for (int p = 0; p < 100; p++)//number of passes { @@ -24,7 +23,7 @@ namespace ConsoleApplication1 } //Output the results. - Console.WriteLine("Passes Completed!!! Here are the results: \r\n"); + Console.WriteLine("Passes Completed!!! Here are the results:"); for (int d = 0; d < 100; d++) { if (doors[d]) diff --git a/Task/100-doors/C/100-doors-3.c b/Task/100-doors/C/100-doors-3.c index fb7f7feb29..d8fed2c66e 100644 --- a/Task/100-doors/C/100-doors-3.c +++ b/Task/100-doors/C/100-doors-3.c @@ -1,19 +1,14 @@ #include +#include -int main() -{ - int square = 1, increment = 3, door; - for (door = 1; door <= 100; ++door) - { - printf("door #%d", door); - if (door == square) - { - printf(" is open.\n"); - square += increment; - increment += 2; - } - else - printf(" is closed.\n"); - } - return 0; +int main() { + uint32_t doorBytes[4] = {0}; + + for (uint32_t i = 1; i <= 100; ++i) + for (uint32_t j = i - 1; j <= 99; j += i) + doorBytes[j % 4] ^= (uint32_t)1 << j / 4; + + for (uint32_t i = 0; i <= 99; doorBytes[i++ % 4] >>= 1) + if (doorBytes[i % 4] & 1) + printf("door %d is open\n", i + 1); } diff --git a/Task/100-doors/C/100-doors-4.c b/Task/100-doors/C/100-doors-4.c index a1972a382b..fb7f7feb29 100644 --- a/Task/100-doors/C/100-doors-4.c +++ b/Task/100-doors/C/100-doors-4.c @@ -2,8 +2,18 @@ int main() { - int door, square, increment; - for (door = 1, square = 1, increment = 1; door <= 100; door++ == square && (square += increment += 2)) - printf("door #%d is %s.\n", door, (door == square? "open" : "closed")); + int square = 1, increment = 3, door; + for (door = 1; door <= 100; ++door) + { + printf("door #%d", door); + if (door == square) + { + printf(" is open.\n"); + square += increment; + increment += 2; + } + else + printf(" is closed.\n"); + } return 0; } diff --git a/Task/100-doors/C/100-doors-5.c b/Task/100-doors/C/100-doors-5.c index 4988099e36..a1972a382b 100644 --- a/Task/100-doors/C/100-doors-5.c +++ b/Task/100-doors/C/100-doors-5.c @@ -2,9 +2,8 @@ int main() { - int i; - for (i = 1; i * i <= 100; i++) - printf("door %d open\n", i * i); - - return 0; + int door, square, increment; + for (door = 1, square = 1, increment = 1; door <= 100; door++ == square && (square += increment += 2)) + printf("door #%d is %s.\n", door, (door == square? "open" : "closed")); + return 0; } diff --git a/Task/100-doors/C/100-doors-6.c b/Task/100-doors/C/100-doors-6.c new file mode 100644 index 0000000000..4988099e36 --- /dev/null +++ b/Task/100-doors/C/100-doors-6.c @@ -0,0 +1,10 @@ +#include + +int main() +{ + int i; + for (i = 1; i * i <= 100; i++) + printf("door %d open\n", i * i); + + return 0; +} diff --git a/Task/100-doors/CBASIC/100-doors.basic b/Task/100-doors/CBASIC/100-doors.basic new file mode 100644 index 0000000000..f81972b2ae --- /dev/null +++ b/Task/100-doors/CBASIC/100-doors.basic @@ -0,0 +1,27 @@ +dim doors%(100) + +print "Finding solution to the 100 Doors Problem" + +rem - all doors are initially closed +for i% = 1 to 100 + doors%(i%) = 0 +next i% + +rem - pass through at increasing intervals +for i% = 1 to 100 + for j% = i% to 100 step i% + rem - flip each door encountered + doors%(j%) = 1 - doors%(j%) + next j% +next i% + +rem - show which doors are open +print "The open doors are: "; +for i% = 1 to 100 + if doors%(i%) = 1 then print i%; +next i% + +print +print "Thanks for consulting the puzzle guru!" + +end diff --git a/Task/100-doors/COBOL/100-doors.cobol b/Task/100-doors/COBOL/100-doors.cob similarity index 100% rename from Task/100-doors/COBOL/100-doors.cobol rename to Task/100-doors/COBOL/100-doors.cob diff --git a/Task/100-doors/Component-Pascal/100-doors.pas b/Task/100-doors/Component-Pascal/100-doors.pas deleted file mode 100644 index 0e11914244..0000000000 --- a/Task/100-doors/Component-Pascal/100-doors.pas +++ /dev/null @@ -1,26 +0,0 @@ -MODULE Doors100; -IMPORT StdLog; - -PROCEDURE Do*; -VAR - i,j: INTEGER; - closed: ARRAY 101 OF BOOLEAN; -BEGIN - (* initialization of closed to true *) - FOR i := 0 TO LEN(closed) - 1 DO closed[i] := TRUE END; - (* process *) - FOR i := 1 TO LEN(closed) DO; - j := 1; - WHILE j < LEN(closed) DO - IF j MOD i = 0 THEN closed[j] := ~closed[j] END;INC(j) - END - END; - (* print results *) - i := 1; - WHILE i < LEN(closed) DO - IF (i - 1) MOD 10 = 0 THEN StdLog.Ln END; - IF closed[i] THEN StdLog.String("C ") ELSE StdLog.String("O ") END; - INC(i) - END; -END Do; -END Doors100. diff --git a/Task/100-doors/Crystal/100-doors.crystal b/Task/100-doors/Crystal/100-doors.cr similarity index 100% rename from Task/100-doors/Crystal/100-doors.crystal rename to Task/100-doors/Crystal/100-doors.cr diff --git a/Task/100-doors/DuckDB/100-doors.duckdb b/Task/100-doors/DuckDB/100-doors.duckdb new file mode 100644 index 0000000000..aa3716882e --- /dev/null +++ b/Task/100-doors/DuckDB/100-doors.duckdb @@ -0,0 +1,19 @@ +# Show the state of n doors after n iterations +create or replace function doors(n) as ( + with recursive cte(ix,d) as ( + select 0 as ix, list_transform(range(0, n), x -> false) as d + union all + select ix+1, + list_transform(d, (x,i) -> if (i % (ix + 1) = 0, NOT x, x)) + from cte + where ix < n + ) + select last(d order by ix) + from cte +); + +# For brevity, we just show the indices of the doors that are open after all +# have been visited: +select ix +from (select unnest(generate_series(1,100)) as ix, unnest(doors(100)) as d) +where d = true; diff --git a/Task/100-doors/EMal/100-doors.emal b/Task/100-doors/EMal/100-doors.emal index 6f7b1360d1..f7294803da 100644 --- a/Task/100-doors/EMal/100-doors.emal +++ b/Task/100-doors/EMal/100-doors.emal @@ -4,7 +4,7 @@ type Door model int id Door:State state - new by int =id, Door:State =state do end + new by int ←id, Door:State ←state do end fun toggle ← <|me.state ← when(me.state æ Door:State.CLOSED, Door:State.OPEN, Door:State.CLOSED) fun asText ← <|"Door #" + me.id + " is " + when(me.state æ Door:State.CLOSED, "closed", "open") end @@ -13,7 +13,7 @@ type Main List doors ← Door[].with(100, false); for(int i := 0; i < 100; i++) @@ -14,8 +14,8 @@ public program() for(int i := 0; i < 100; i++) { - console.printLine("Door #",i + 1," :",Doors[i].iif("Open","Closed")) + Console.printLine("Door #",i + 1," :",Doors[i].iif("Open","Closed")) }; - console.readChar() + Console.readChar() } diff --git a/Task/100-doors/Elixir/100-doors.elixir b/Task/100-doors/Elixir/100-doors.ex similarity index 100% rename from Task/100-doors/Elixir/100-doors.elixir rename to Task/100-doors/Elixir/100-doors.ex diff --git a/Task/100-doors/Emacs-Lisp/100-doors.l b/Task/100-doors/Emacs-Lisp/100-doors-1.el similarity index 100% rename from Task/100-doors/Emacs-Lisp/100-doors.l rename to Task/100-doors/Emacs-Lisp/100-doors-1.el diff --git a/Task/100-doors/Emacs-Lisp/100-doors-2.el b/Task/100-doors/Emacs-Lisp/100-doors-2.el new file mode 100644 index 0000000000..66b2cff437 --- /dev/null +++ b/Task/100-doors/Emacs-Lisp/100-doors-2.el @@ -0,0 +1,16 @@ +(defun one-hundred-doors(initial-state) + "Turn doors in INITIAL-STATE according to 100 Doors problem." + (interactive "nEnter initial doors' state (as a number): ") + (cl-loop for x from 1 to 100 + do (cl-loop for y from (1- x) to 99 by x + do (setq initial-state (logxor initial-state (ash 1 y))))) + (let ((counter 1) + (open-doors nil)) + (while (> initial-state 0) + (when (eq (mod initial-state 2) 1) + (push counter open-doors)) + (cl-incf counter) + (setq initial-state (/ initial-state 2))) + (message "Open doors are %s" (reverse open-doors)))) + +(one-hundred-doors 0) diff --git a/Task/100-doors/Euphoria/100-doors.euphoria b/Task/100-doors/Euphoria/100-doors.eu similarity index 100% rename from Task/100-doors/Euphoria/100-doors.euphoria rename to Task/100-doors/Euphoria/100-doors.eu diff --git a/Task/100-doors/Excel/100-doors-4.excel b/Task/100-doors/Excel/100-doors-4.excel new file mode 100644 index 0000000000..619e31a91c --- /dev/null +++ b/Task/100-doors/Excel/100-doors-4.excel @@ -0,0 +1 @@ +=LET(i, SEQUENCE(100), root, SQRT(i), "Door " & i & ": " & IF(root = INT(root), "open", "close")) diff --git a/Task/100-doors/F-Sharp/100-doors-2.fs b/Task/100-doors/F-Sharp/100-doors-2.fs index dff5b85a51..abda597121 100644 --- a/Task/100-doors/F-Sharp/100-doors-2.fs +++ b/Task/100-doors/F-Sharp/100-doors-2.fs @@ -1,6 +1 @@ -open System -let answer2 = - let PerfectSquare n = - let sqrt = int(Math.Sqrt(float n)) - n = sqrt * sqrt - [| for i in 1..100 do yield PerfectSquare i |] +[1..100] |> List.fold (fun doors pass->List.mapi (fun i x->if ((i + 1) % pass)=0 then not x else x) doors) (List.init 100 (fun _->false)) diff --git a/Task/100-doors/F-Sharp/100-doors-3.fs b/Task/100-doors/F-Sharp/100-doors-3.fs index abda597121..0e020e7034 100644 --- a/Task/100-doors/F-Sharp/100-doors-3.fs +++ b/Task/100-doors/F-Sharp/100-doors-3.fs @@ -1 +1,8 @@ -[1..100] |> List.fold (fun doors pass->List.mapi (fun i x->if ((i + 1) % pass)=0 then not x else x) doors) (List.init 100 (fun _->false)) +let X q=not q +let mutable q = false +let mutable doors = [] +for n in 1..100 do + for g in 1..n do if n%g=0 then q<-X(q) + if q then doors<-n::doors + q<-false +printfn "%A" (doors|>List.rev) diff --git a/Task/100-doors/Fennel/100-doors.fennel b/Task/100-doors/Fennel/100-doors.fennel new file mode 100644 index 0000000000..b6e72cb03e --- /dev/null +++ b/Task/100-doors/Fennel/100-doors.fennel @@ -0,0 +1,15 @@ +(do ;;; find the first few squares via the unoptimised door flipping method + + (local door-max 100) + + ; repeatedly flip the doors and show the ones that are left open + (var door {}) + (for [i 1 door-max] + (for [j i door-max i] + (tset door j (not (. door j))) + ) + (when (. door i) + (io.write (.. " " i)) + ) + ) +) diff --git a/Task/100-doors/Fortran/100-doors-3.f b/Task/100-doors/Fortran/100-doors-3.f new file mode 100644 index 0000000000..2041b696fe --- /dev/null +++ b/Task/100-doors/Fortran/100-doors-3.f @@ -0,0 +1,73 @@ +! ============================================================================= +! DOORS PROBLEM +! ============================================================================= +! +! PROBLEM STATEMENT: +! 100 doors are all initially closed. We make 100 passes. +! Pass 1 toggles every door (1, 2, 3, ..., 100). +! Pass 2 toggles every 2nd (2, 4, 6, ..., 100). +! Pass k toggles every k-th (k, 2k, 3k, ...). +! Pass 100 toggles only door 100. +! What state is each door in after all 100 passes? +! +! ALGORITHM -- DIVISOR COUNTING: +! Door number D is toggled on pass k if and only if k divides D evenly, +! i.e. mod(D, k) == 0. So the total number of toggles that door D receives +! equals the number of divisors of D (including 1 and D itself). +! +! Example: door 6 +! Divisors of 6 are 1, 2, 3, 6 => 4 toggles => even => CLOSED +! +! Example: door 9 +! Divisors of 9 are 1, 3, 9 => 3 toggles => odd => OPEN +! +! A door ends up OPEN when its divisor count is ODD. +! A door ends up CLOSED when its divisor count is EVEN. +! +! KEY MATHEMATICAL INSIGHT (why the pattern is perfect squares): +! Divisors normally come in pairs: if j divides D then (D/j) also divides D, +! giving an even count. The only exception is when j == D/j, i.e. j*j == D. +! That "pairing trick" breaks at the square root, leaving one unpaired divisor +! and making the total ODD. This happens exactly when D is a perfect square. +! So doors 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 are open; all others closed. +! +! This program proves the result by brute-force divisor counting, rather than +! assuming the mathematical conclusion up front. +! ============================================================================= + +program doors + implicit none + + integer, parameter :: n = 100 ! total number of doors (and passes) + integer :: door ! current door being evaluated (1..n) + integer :: pass ! current pass number being tested (1..n) + integer :: toggles ! number of times this door was toggled + character(6) :: state ! final state label: 'open' or 'closed' + + ! --- outer loop: consider each door in turn --- + do door = 1, n + + toggles = 0 ! reset the toggle counter for this door + + ! --- inner loop: check every pass to see if it touches this door --- + ! Pass number 'pass' visits door 'door' only when 'pass' is a divisor + ! of 'door'. mod(door, pass) == 0 means pass divides door exactly. + do pass = 1, n + if (mod(door, pass) == 0) toggles = toggles + 1 + end do + + ! --- determine final state from parity of toggle count --- + ! Starting closed, an odd number of toggles leaves the door open; + ! an even number returns it to closed. + if (mod(toggles, 2) == 1) then + state = 'open' + else + state = 'closed' + end if + + ! --- report result for this door --- + write(*, '(A, I3, A, A)') 'Door', door, ' is ', trim(state) + + end do + +end program doors diff --git a/Task/100-doors/Goboscript/100-doors.gobo b/Task/100-doors/Goboscript/100-doors.gobo new file mode 100644 index 0000000000..f0bc39fd44 --- /dev/null +++ b/Task/100-doors/Goboscript/100-doors.gobo @@ -0,0 +1,37 @@ +costumes "assets/blank.svg"; + +list doors; + +proc do_100_doors { + delete doors; + repeat 100 {add false to doors;} + + local pass_i = 1; + repeat 100 { + local i = 0; + repeat length doors / pass_i { + i += pass_i; + doors[i] = not doors[i]; + } + + pass_i++; + } +} + +onflag{main;} +proc main { + do_100_doors; + + show doors; + local i = 1; + repeat length doors { + if doors[i] { + local state = "open"; + } else { + local state = "closed"; + } + + log "Door " & i & " is " & state; + i++; + } +} diff --git a/Task/100-doors/Haskell/100-doors-3.hs b/Task/100-doors/Haskell/100-doors-3.hs index 2cea247dfd..3b66096632 100644 --- a/Task/100-doors/Haskell/100-doors-3.hs +++ b/Task/100-doors/Haskell/100-doors-3.hs @@ -1,6 +1,9 @@ -gate :: Eq a => [a] -> [a] -> [Door] -gate (x:xs) (y:ys) | x == y = Open : gate xs ys -gate (x:xs) ys = Closed : gate xs ys -gate [] _ = [] +isDoorOpen :: Integral a => a -> Bool +-- In Haskell, we are too lazy to open and close doors. Instead we +-- count how many times we would have toggled them, and then check if +-- that number is odd. +isDoorOpen doorNumber = odd numToggles + where numToggles = length [ 1 | x <- [1..doorNumber], doorNumber `rem` x == 0] -run n = gate [1..n] [k*k | k <- [1..]] +main = do + print $ "Open doors are " ++ show [x | x <- [0..100], isDoorOpen x] diff --git a/Task/100-doors/Haskell/100-doors-4.hs b/Task/100-doors/Haskell/100-doors-4.hs index 44f44aa391..2cea247dfd 100644 --- a/Task/100-doors/Haskell/100-doors-4.hs +++ b/Task/100-doors/Haskell/100-doors-4.hs @@ -1 +1,6 @@ -run n = takeWhile (< n) [k*k | k <- [1..]] +gate :: Eq a => [a] -> [a] -> [Door] +gate (x:xs) (y:ys) | x == y = Open : gate xs ys +gate (x:xs) ys = Closed : gate xs ys +gate [] _ = [] + +run n = gate [1..n] [k*k | k <- [1..]] diff --git a/Task/100-doors/Haskell/100-doors-5.hs b/Task/100-doors/Haskell/100-doors-5.hs new file mode 100644 index 0000000000..44f44aa391 --- /dev/null +++ b/Task/100-doors/Haskell/100-doors-5.hs @@ -0,0 +1 @@ +run n = takeWhile (< n) [k*k | k <- [1..]] diff --git a/Task/100-doors/Haxe/100-doors-1.haxe b/Task/100-doors/Haxe/100-doors-1.hx similarity index 100% rename from Task/100-doors/Haxe/100-doors-1.haxe rename to Task/100-doors/Haxe/100-doors-1.hx diff --git a/Task/100-doors/Haxe/100-doors-2.haxe b/Task/100-doors/Haxe/100-doors-2.hx similarity index 100% rename from Task/100-doors/Haxe/100-doors-2.haxe rename to Task/100-doors/Haxe/100-doors-2.hx diff --git a/Task/100-doors/Informix-4GL/100-doors-2.4gl b/Task/100-doors/Informix-4GL/100-doors-2.4gl index 77483d70d0..6a8949775e 100644 --- a/Task/100-doors/Informix-4GL/100-doors-2.4gl +++ b/Task/100-doors/Informix-4GL/100-doors-2.4gl @@ -2,7 +2,7 @@ (for i (range 1 101) i2 (range (dec i) 100 i) - (var! doors (set-at [i2] (! (i2 doors)))) + (var! doors (set-at [i2] (not (i2 doors)))) (continue)) (-> (xmap vec doors) diff --git a/Task/100-doors/Julia/100-doors-1.julia b/Task/100-doors/Julia/100-doors-1.jl similarity index 100% rename from Task/100-doors/Julia/100-doors-1.julia rename to Task/100-doors/Julia/100-doors-1.jl diff --git a/Task/100-doors/Julia/100-doors-2.julia b/Task/100-doors/Julia/100-doors-2.jl similarity index 100% rename from Task/100-doors/Julia/100-doors-2.julia rename to Task/100-doors/Julia/100-doors-2.jl diff --git a/Task/100-doors/Kotlin/100-doors.kotlin b/Task/100-doors/Kotlin/100-doors.kts similarity index 100% rename from Task/100-doors/Kotlin/100-doors.kotlin rename to Task/100-doors/Kotlin/100-doors.kts diff --git a/Task/100-doors/Langur/100-doors-1.langur b/Task/100-doors/Langur/100-doors-1.langur index 48e130366a..caac5fccf7 100644 --- a/Task/100-doors/Langur/100-doors-1.langur +++ b/Task/100-doors/Langur/100-doors-1.langur @@ -1,9 +1,9 @@ -var .doors = [false] * 100 +var doors = [false] * 100 -for .i of .doors { - for .j = .i; .j <= len(.doors); .j += .i { - .doors[.j] = not .doors[.j] +for i of doors { + for j = i; j <= len(doors); j += i { + doors[j] = not doors[j] } } -writeln for[=[]] .i of .doors { if(.doors[.i]: _for ~= [.i]) } +writeln for[=[]] i of doors { if doors[i]: _for = more(_for, i) } diff --git a/Task/100-doors/Langur/100-doors-2.langur b/Task/100-doors/Langur/100-doors-2.langur index f120dd60c3..1933c0187f 100644 --- a/Task/100-doors/Langur/100-doors-2.langur +++ b/Task/100-doors/Langur/100-doors-2.langur @@ -1 +1 @@ -writeln foldfrom(fn(.a, .b, .c) if(.b: .a~[.c]; .a), [], .doors, series 1..len .doors) +writeln fold(doors, series(1..len(doors)), by=fn(a, b, c) { if(b: a~[c]; a) }, init=[]) diff --git a/Task/100-doors/Langur/100-doors-3.langur b/Task/100-doors/Langur/100-doors-3.langur index d1c575957b..61d90f3fb8 100644 --- a/Task/100-doors/Langur/100-doors-3.langur +++ b/Task/100-doors/Langur/100-doors-3.langur @@ -1 +1 @@ -writeln map fn{^2}, 1..10 +writeln map(1..10, by=fn{^2}) diff --git a/Task/100-doors/Lua/100-doors.lua b/Task/100-doors/Lua/100-doors.lua deleted file mode 100644 index 3183bc7730..0000000000 --- a/Task/100-doors/Lua/100-doors.lua +++ /dev/null @@ -1,11 +0,0 @@ -local is_open = {} - -for pass = 1,100 do - for door = pass,100,pass do - is_open[door] = not is_open[door] - end -end - -for i,v in next,is_open do - print ('Door '..i..':',v and 'open' or 'close') -end diff --git a/Task/100-doors/MoonRock/100-doors.moonrock b/Task/100-doors/MoonRock/100-doors.moonrock new file mode 100644 index 0000000000..f942ba2444 --- /dev/null +++ b/Task/100-doors/MoonRock/100-doors.moonrock @@ -0,0 +1,35 @@ +' 100 doors + +BEGIN DEF +%DoorMax = 100 +%LastI = %DoorMax - 1 +DIM DoorOpen%[%DoorMax] + +BEGIN CODE +' The unoptimised door flipping method +' which simulates the process +' Set all doors to closed +FOR I% = 0 TO %LastI + DoorOpen%[I%] = FALSE +NEXT +' Repeatedly flip the doors +FOR I% = 1 TO %DoorMax + J% = I% - 1 + WHILE J% < %DoorMax + IF DoorOpen%[J%] = TRUE THEN + DoorOpen%[J%] = FALSE + ELSE + DoorOpen%[J%] = TRUE + ENDIF + J% = J% + I% + WEND +NEXT +' Display the results +FOR I% = 0 TO %LastI + IF DoorOpen%[I%] = TRUE THEN + IPl1% = I% + 1 + PRINT " " + IPl1% + ENDIF +NEXT +PRINT "\n" +END diff --git a/Task/100-doors/OCaml/100-doors-1.ocaml b/Task/100-doors/OCaml/100-doors-1.ml similarity index 100% rename from Task/100-doors/OCaml/100-doors-1.ocaml rename to Task/100-doors/OCaml/100-doors-1.ml diff --git a/Task/100-doors/OCaml/100-doors-2.ocaml b/Task/100-doors/OCaml/100-doors-2.ml similarity index 100% rename from Task/100-doors/OCaml/100-doors-2.ocaml rename to Task/100-doors/OCaml/100-doors-2.ml diff --git a/Task/100-doors/OCaml/100-doors-3.ocaml b/Task/100-doors/OCaml/100-doors-3.ml similarity index 100% rename from Task/100-doors/OCaml/100-doors-3.ocaml rename to Task/100-doors/OCaml/100-doors-3.ml diff --git a/Task/100-doors/OPL/100-doors.opl b/Task/100-doors/OPL/100-doors.opl new file mode 100644 index 0000000000..097dc00ccd --- /dev/null +++ b/Task/100-doors/OPL/100-doors.opl @@ -0,0 +1,27 @@ +REM https://github.com/Eva-Broccoli/OPL-Rosetta-Code/blob/main/A100door.opl +PROC main: + LOCAL door%(100),i%,j% + i%=1 + j%=1 + WHILE j%<101 + WHILE i%<101 + IF door%(i%)=0 + door%(i%)=1 + ELSE + door%(i%)=0 + ENDIF + i%=i%+j% + ENDWH + j%=j%+1 + i%=0+j% + ENDWH + PRINT "Open doors:", + i%=1 + WHILE i%<101 + IF door%(i%)=1 + PRINT i%, + ENDIF + i%=i%+1 + ENDWH + GET +ENDP diff --git a/Task/100-doors/Oberon/100-doors.oberon b/Task/100-doors/Oberon/100-doors.oberon deleted file mode 100644 index ddec2b2de8..0000000000 --- a/Task/100-doors/Oberon/100-doors.oberon +++ /dev/null @@ -1,27 +0,0 @@ -MODULE Doors; - IMPORT Out; - - PROCEDURE Do*; (* In Oberon an asterisk after an identifier is an export mark *) - CONST N = 100; len = N + 1; - VAR i, j: INTEGER; - closed: ARRAY len OF BOOLEAN; (* Arrays in Oberon always start with index 0; closed[0] is not used *) - BEGIN - FOR i := 1 TO N DO closed[i] := TRUE END; - FOR i := 1 TO N DO - j := 1; - WHILE j < len DO - IF j MOD i = 0 THEN closed[j] := ~closed[j] END; INC(j) (* ~ = NOT *) - END - END; - (* Print a state diagram of all doors *) - FOR i := 1 TO N DO - IF (i - 1) MOD 10 = 0 THEN Out.Ln END; - IF closed[i] THEN Out.String("- ") ELSE Out.String("+ ") END - END; Out.Ln; - (* Print the numbers of the open doors *) - FOR i := 1 TO N DO - IF ~closed[i] THEN Out.Int(i, 0); Out.Char(" ") END - END; Out.Ln - END Do; - -END Doors. diff --git a/Task/100-doors/Odin/100-doors-1.odin b/Task/100-doors/Odin/100-doors-1.odin new file mode 100644 index 0000000000..7169d3893a --- /dev/null +++ b/Task/100-doors/Odin/100-doors-1.odin @@ -0,0 +1,22 @@ +package doors + +import "core:fmt" + +main :: proc() { + doors: [100]bool + + for every_n := 1; every_n < len(doors); every_n += 1 { + i := every_n - 1 + for true { + if i >= len(doors) do break + + doors[i] = !doors[i] + + i += every_n + } + } + + for &door, i in doors { + if door do fmt.printf("%d ", i + 1) + } +} diff --git a/Task/100-doors/Odin/100-doors-2.odin b/Task/100-doors/Odin/100-doors-2.odin new file mode 100644 index 0000000000..b4fcc95bd6 --- /dev/null +++ b/Task/100-doors/Odin/100-doors-2.odin @@ -0,0 +1,24 @@ +package main + +import "core:fmt" + +main :: proc() { + using fmt + + Door_State :: enum {Closed, Open} + + doors := [?]Door_State { 0..<100 = .Closed } + + for i in 1..=100 { + for j := i-1; j < 100; j += i { + if doors[j] == .Closed { + doors[j] = .Open + } else { + doors[j] = .Closed + } + } + } + for state, i in doors { + println("Door: ",int(i+1)," -> ",state) + } +} diff --git a/Task/100-doors/Odin/100-doors-3.odin b/Task/100-doors/Odin/100-doors-3.odin new file mode 100644 index 0000000000..77e9cd99ef --- /dev/null +++ b/Task/100-doors/Odin/100-doors-3.odin @@ -0,0 +1,22 @@ +package main + +import "core:fmt" +import "core:math" + +main :: proc() { + using fmt + + Door_State :: enum {Closed, Open} + + doors := [?]Door_State { 0..<100 = .Closed } + + for i in 1..=100 { + res := math.sqrt_f64( f64(i) ) + if math.mod_f64( res, 1) == 0 { + doors[i-1] = .Open + } else { + doors[i-1] = .Closed + } + println("Door: ", i, " -> ", doors[i-1]) + } +} diff --git a/Task/100-doors/OmniMark/100-doors-1.xom b/Task/100-doors/OmniMark/100-doors-1.xom new file mode 100644 index 0000000000..8a04ae39c7 --- /dev/null +++ b/Task/100-doors/OmniMark/100-doors-1.xom @@ -0,0 +1,18 @@ +process + local switch doors size 100 ; all initialised ('1st pass' to false) + + repeat over doors + repeat for integer door from #item to 100 by #item + do when doors[door] = false + activate doors[door] ; illustrating alternative to set ... to + else + set doors[door] to false + done + again + again + + repeat over doors + do when doors = true + put #error '%d(#item)%n' + done + again diff --git a/Task/100-doors/OmniMark/100-doors-2.xom b/Task/100-doors/OmniMark/100-doors-2.xom new file mode 100644 index 0000000000..8c4bd45aa7 --- /dev/null +++ b/Task/100-doors/OmniMark/100-doors-2.xom @@ -0,0 +1,10 @@ +process + local integer door initial {1} + local integer step initial {3} + + repeat + output "Door %d(door) is open%n" + increment door by step + increment step by 2 + exit when door > 100 + again diff --git a/Task/100-doors/PL-M/100-doors.plm b/Task/100-doors/PL-M/100-doors.plm deleted file mode 100644 index 0013832477..0000000000 --- a/Task/100-doors/PL-M/100-doors.plm +++ /dev/null @@ -1,55 +0,0 @@ -100H: /* FIND THE FIRST FEW SQUARES VIA THE UNOPTIMISED DOOR FLIPPING METHOD */ - - /* BDOS SYSTEM CALL */ - BDOS: PROCEDURE( FN, ARG ); - DECLARE FN BYTE, ARG ADDRESS; - GO TO 5; - END BDOS; - - /* PRINTS A BYTE AS A CHARACTER */ - PRINT$CHAR: PROCEDURE( CH ); - DECLARE CH BYTE; - CALL BDOS( 2, CH ); - END PRINT$CHAR; - - /* PRINTS A BYTE AS A NUMBER */ - PRINT$BYTE: PROCEDURE( N ); - DECLARE N BYTE; - DECLARE ( V, D3, D2 ) BYTE; - V = N; - D3 = V MOD 10; - IF ( V := V / 10 ) <> 0 THEN DO; - D2 = V MOD 10; - IF ( V := V / 10 ) <> 0 THEN CALL PRINT$CHAR( '0' + V ); - CALL PRINT$CHAR( '0' + D2 ); - END; - CALL PRINT$CHAR( '0' + D3 ); - END PRINT$BYTE; - - DECLARE DOOR$DCL LITERALLY '101'; - DECLARE FALSE LITERALLY '0'; - DECLARE CR LITERALLY '0DH'; - DECLARE LF LITERALLY '0AH'; - - /* ARRAY OF DOORS - DOOR( I ) IS TRUE IF OPEN, FALSE IF CLOSED */ - DECLARE DOOR( DOOR$DCL ) BYTE; - DECLARE ( I, J ) BYTE; - - /* SET ALL DOORS TO CLOSED */ - DO I = 0 TO LAST( DOOR ); DOOR( I ) = FALSE; END; - /* REPEATEDLY FLIP THE DOORS */ - DO I = 1 TO LAST( DOOR ); - DO J = I TO LAST( DOOR ) BY I; - DOOR( J ) = NOT DOOR( J ); - END; - END; - /* DISPLAY THE RESULTS */ - DO I = 1 TO LAST( DOOR ); - IF DOOR( I ) THEN DO; - CALL PRINT$CHAR( ' ' ); - CALL PRINT$BYTE( I ); - END; - END; - CALL PRINT$CHAR( CR ); - CALL PRINT$CHAR( LF ); -EOF diff --git a/Task/100-doors/PascalABC.NET/100-doors.pas b/Task/100-doors/PascalABC.NET/100-doors.pas deleted file mode 100644 index fab41ed069..0000000000 --- a/Task/100-doors/PascalABC.NET/100-doors.pas +++ /dev/null @@ -1,8 +0,0 @@ -// 100 doors. Nigel Galloway: January 1th., 2023 -type doorState=(Open,Closed); -function flip(n:doorState):doorState:=if n=Open then Closed else Open; -var Doors:Array of doorState:=ArrFill(100,Closed); -begin - for var n:=1 to 100 do for var g:=n-1 to 99 step n do Doors[g]:=flip(Doors[g]); - for var n:=0 to 99 do if Doors[n]=Open then write(n+1,' '); writeLn -end. diff --git a/Task/100-doors/Plain-English/100-doors.plain b/Task/100-doors/Plain-English/100-doors.plain index f6ee5c1b2e..2ebc38ce0b 100644 --- a/Task/100-doors/Plain-English/100-doors.plain +++ b/Task/100-doors/Plain-English/100-doors.plain @@ -1,51 +1,57 @@ -To create some doors given a count: -Loop. -If a counter is past the count, exit. -Allocate memory for a door. -Clear the door's flag. -Append the door to the doors. -Repeat. - -A door is a flag thing. - -To go through some doors given a number and some passes: -Put 0 into a counter. -Loop. -Add the number to the counter. -If the counter is greater than the passes, exit. -Pick a door from the doors given the number. -Invert the door's flag. -Repeat. - -To output the states of some doors: -Loop. -Bump a counter. -Get a door from the doors. -If the door is nil, exit. -If the door's flag is set, write "Door " then the counter then " is open" to the output; repeat. -Write "Door " then the counter then " is closed" to the output. -Repeat. - -To pass doors given a count and some passes: -Create some doors given the count. -Loop. -If a counter is past the passes, break. -Go through the doors given the counter and the passes. -Repeat. -Output the states of the doors. -Destroy the doors. - +A flag list is a doubly linked list with a flag. +A door is a flag list. A pass is a number. -To pick a door from some doors given a number: -Loop. -If a counter is past the number, exit. -Get the door from the doors. -If the door is nil, exit. -Repeat. - To run: -Start up. -Pass doors given 100 and 100 passes. -Wait for the escape key. -Shut down. + Start up. + Pass doors given 1000 and 1000 passes. + Shut down. + +To pass doors given a count and some passes: + Create some doors given the count. + Loop. + Add 1 to a counter. + If the counter is greater than the passes, break. + Go through the doors given the counter and the passes. + Repeat. + Output the states of the doors. + Destroy the doors. + +To create some doors given a count: + Loop. + Add 1 to a counter. + If the counter is greater than the count, exit. + Allocate memory for a door. + Clear the door's flag. + Append the door to the doors. + Repeat. + +To go through some doors given a number and some passes: + Put 0 into a counter. + Loop. + Add the number to the counter. + If the counter is greater than the passes, exit. + Pick a door from the doors given the number. + Invert the door's flag. + Repeat. + +To pick a door from some doors given a number: + Loop. + Add 1 to a counter. + If the counter is greater than the number, exit. + Get the door from the doors. + If the door is nil, exit. + Repeat. + +To output the states of some doors: + Loop. + Bump a counter. + Get a door from the doors. + If the door is nil, exit. + If the door's flag is set, + Write "Door " then the counter then " is open" + then the CRLF string to StdOut; + Repeat. + \Write "Door " then the counter then " is closed" + \then the CRLF string to StdOut. + Repeat. diff --git a/Task/100-doors/PowerShell/100-doors-1.psh b/Task/100-doors/PowerShell/100-doors-1.ps1 similarity index 100% rename from Task/100-doors/PowerShell/100-doors-1.psh rename to Task/100-doors/PowerShell/100-doors-1.ps1 diff --git a/Task/100-doors/PowerShell/100-doors-2.psh b/Task/100-doors/PowerShell/100-doors-2.ps1 similarity index 100% rename from Task/100-doors/PowerShell/100-doors-2.psh rename to Task/100-doors/PowerShell/100-doors-2.ps1 diff --git a/Task/100-doors/PowerShell/100-doors-3.psh b/Task/100-doors/PowerShell/100-doors-3.ps1 similarity index 100% rename from Task/100-doors/PowerShell/100-doors-3.psh rename to Task/100-doors/PowerShell/100-doors-3.ps1 diff --git a/Task/100-doors/PowerShell/100-doors-4.psh b/Task/100-doors/PowerShell/100-doors-4.ps1 similarity index 100% rename from Task/100-doors/PowerShell/100-doors-4.psh rename to Task/100-doors/PowerShell/100-doors-4.ps1 diff --git a/Task/100-doors/PowerShell/100-doors-5.psh b/Task/100-doors/PowerShell/100-doors-5.ps1 similarity index 100% rename from Task/100-doors/PowerShell/100-doors-5.psh rename to Task/100-doors/PowerShell/100-doors-5.ps1 diff --git a/Task/100-doors/PowerShell/100-doors-6.psh b/Task/100-doors/PowerShell/100-doors-6.ps1 similarity index 100% rename from Task/100-doors/PowerShell/100-doors-6.psh rename to Task/100-doors/PowerShell/100-doors-6.ps1 diff --git a/Task/100-doors/PowerShell/100-doors-7.psh b/Task/100-doors/PowerShell/100-doors-7.ps1 similarity index 100% rename from Task/100-doors/PowerShell/100-doors-7.psh rename to Task/100-doors/PowerShell/100-doors-7.ps1 diff --git a/Task/100-doors/Pyret/100-doors.pyret b/Task/100-doors/Pyret/100-doors.arr similarity index 100% rename from Task/100-doors/Pyret/100-doors.pyret rename to Task/100-doors/Pyret/100-doors.arr diff --git a/Task/100-doors/Python/100-doors-5.py b/Task/100-doors/Python/100-doors-5.py index c3f39a49a6..96e57804d7 100644 --- a/Task/100-doors/Python/100-doors-5.py +++ b/Task/100-doors/Python/100-doors-5.py @@ -1,6 +1,2 @@ for i in range(1, 101): - if i**0.5 % 1: - state='closed' - else: - state='open' - print("Door {}:{}".format(i, state)) + print(f"Door {i}:{"closed" if i**0.5 % 1 else "open"}") diff --git a/Task/100-doors/Python/100-doors-6.py b/Task/100-doors/Python/100-doors-6.py index 7524fc9970..b42230ac44 100644 --- a/Task/100-doors/Python/100-doors-6.py +++ b/Task/100-doors/Python/100-doors-6.py @@ -1 +1 @@ -for i in range(1,11): print("Door %s is open" % i**2) +for i in range(1,11): print(f"Door {i**2} is open") diff --git a/Task/100-doors/Quackery/100-doors-1.quackery b/Task/100-doors/Quackery/100-doors-1.quackery new file mode 100644 index 0000000000..e3d105d0cd --- /dev/null +++ b/Task/100-doors/Quackery/100-doors-1.quackery @@ -0,0 +1,17 @@ + [ bit ^ ] is toggle ( f n --> f ) + + [ 0 + 100 times + [ i^ 1+ swap + 101 times + [ i^ toggle over step ] + nip ] ] is toggledoors ( --> f ) + + [ 100 times + [ 1 >> dup 1 & + if [ i^ 1+ echo sp ] ] + drop ] is echodoors ( f --> ) + + toggledoors + say " These doors are open: " echodoors cr + say " The rest are closed." cr diff --git a/Task/100-doors/Quackery/100-doors-2.quackery b/Task/100-doors/Quackery/100-doors-2.quackery new file mode 100644 index 0000000000..85074cd60f --- /dev/null +++ b/Task/100-doors/Quackery/100-doors-2.quackery @@ -0,0 +1 @@ + 10 times [ i^ 1+ 2 ** echo sp ] diff --git a/Task/100-doors/Quackery/100-doors.quackery b/Task/100-doors/Quackery/100-doors.quackery deleted file mode 100644 index 5577d1c6c4..0000000000 --- a/Task/100-doors/Quackery/100-doors.quackery +++ /dev/null @@ -1,22 +0,0 @@ -/O> [ bit ^ ] is toggle ( f n --> f ) -... -... [ 0 -... 100 times -... [ i^ 1+ swap -... 101 times -... [ i^ toggle over step ] -... nip ] ] is toggledoors ( --> f ) -... -... [ 100 times -... [ 1 >> dup 1 & -... if [ i^ 1+ echo sp ] ] -... drop ] is echodoors ( f --> ) -... -... toggledoors -... say " These doors are open: " echodoors cr -... say " The rest are closed." cr -... - These doors are open: 1 4 9 16 25 36 49 64 81 100 - The rest are closed. - -Stack empty. diff --git a/Task/100-doors/REBOL/100-doors-2.rebol b/Task/100-doors/REBOL/100-doors-2.rebol deleted file mode 100644 index 73f1f448f3..0000000000 --- a/Task/100-doors/REBOL/100-doors-2.rebol +++ /dev/null @@ -1,2 +0,0 @@ -doors: array/initial 100 'closed -repeat i 10 [doors/(i * i): 'open] diff --git a/Task/100-doors/REBOL/100-doors-1.rebol b/Task/100-doors/Rebol/100-doors-1.rebol similarity index 100% rename from Task/100-doors/REBOL/100-doors-1.rebol rename to Task/100-doors/Rebol/100-doors-1.rebol diff --git a/Task/100-doors/Rebol/100-doors-2.rebol b/Task/100-doors/Rebol/100-doors-2.rebol new file mode 100644 index 0000000000..b8428a69d9 --- /dev/null +++ b/Task/100-doors/Rebol/100-doors-2.rebol @@ -0,0 +1,26 @@ +;; Create a bitset with capacity for 100 bits (representing 100 doors) +;; Each bit represents a door state: 0 = closed, 1 = open +doors: make bitset! 100 + +;; Outer loop: Make 100 passes (i = 1 to 100) +repeat i 100 [ + ;; Inner loop: Check each door position (j = 1 to 100) + repeat j 100 [ + ;; If door j index is divisible by pass number i (no remainder) + if zero? (j // i) [ + ;; Toggle the door's bit: + ;; doors/:j accesses door j in the bitset + ;; 'not' flips the bit value (0 -> 1, 1 -> 0) + doors/:j: not doors/:j + ] + ] +] + +;; Final loop: Check which doors are open, print their numbers +repeat i 100 [ + ;; If door i's bit is set (open) + if doors/:i [ + ;; Print the door's number and that it is open + print ["door" i "is open"] + ] +] diff --git a/Task/100-doors/Rebol/100-doors-3.rebol b/Task/100-doors/Rebol/100-doors-3.rebol new file mode 100644 index 0000000000..318cdd4a11 --- /dev/null +++ b/Task/100-doors/Rebol/100-doors-3.rebol @@ -0,0 +1,6 @@ +;; Loop variable i from 1 to 10 (since 10^2 = 100, covers doors 1 to 100) +repeat i 10 [ + ;; Print that door number (i squared) is open + ;; These are exactly the doors with perfect square numbers: 1, 4, 9, ..., 100 + print ["door" (i * i) "is open"] +] diff --git a/Task/100-doors/Coq/100-doors-1.coq b/Task/100-doors/Rocq/100-doors-1.rocq similarity index 100% rename from Task/100-doors/Coq/100-doors-1.coq rename to Task/100-doors/Rocq/100-doors-1.rocq diff --git a/Task/100-doors/Coq/100-doors-2.coq b/Task/100-doors/Rocq/100-doors-2.rocq similarity index 100% rename from Task/100-doors/Coq/100-doors-2.coq rename to Task/100-doors/Rocq/100-doors-2.rocq diff --git a/Task/100-doors/Coq/100-doors-3.coq b/Task/100-doors/Rocq/100-doors-3.rocq similarity index 100% rename from Task/100-doors/Coq/100-doors-3.coq rename to Task/100-doors/Rocq/100-doors-3.rocq diff --git a/Task/100-doors/Coq/100-doors-4.coq b/Task/100-doors/Rocq/100-doors-4.rocq similarity index 100% rename from Task/100-doors/Coq/100-doors-4.coq rename to Task/100-doors/Rocq/100-doors-4.rocq diff --git a/Task/100-doors/Rust/100-doors-1.rust b/Task/100-doors/Rust/100-doors-1.rs similarity index 100% rename from Task/100-doors/Rust/100-doors-1.rust rename to Task/100-doors/Rust/100-doors-1.rs diff --git a/Task/100-doors/Rust/100-doors-2.rust b/Task/100-doors/Rust/100-doors-2.rs similarity index 100% rename from Task/100-doors/Rust/100-doors-2.rust rename to Task/100-doors/Rust/100-doors-2.rs diff --git a/Task/100-doors/Rust/100-doors-3.rust b/Task/100-doors/Rust/100-doors-3.rs similarity index 100% rename from Task/100-doors/Rust/100-doors-3.rust rename to Task/100-doors/Rust/100-doors-3.rs diff --git a/Task/100-doors/Rust/100-doors-4.rust b/Task/100-doors/Rust/100-doors-4.rs similarity index 100% rename from Task/100-doors/Rust/100-doors-4.rust rename to Task/100-doors/Rust/100-doors-4.rs diff --git a/Task/100-doors/Rye/100-doors.rye b/Task/100-doors/Rye/100-doors.rye new file mode 100644 index 0000000000..1bd595c1c9 --- /dev/null +++ b/Task/100-doors/Rye/100-doors.rye @@ -0,0 +1,8 @@ +replicate 100 { false } +|walk\pos 'p { + .map\pos 'r { ::d , + either r .is-multiple-of p { not d } { d } } + |at p } +|map\pos 'p { .either { p } { false } } +|filter { .is-integer } +|for { .embed "Door {} is open." |print } diff --git a/Task/100-doors/Scheme/100-doors-1.ss b/Task/100-doors/Scheme/100-doors-1.scm similarity index 100% rename from Task/100-doors/Scheme/100-doors-1.ss rename to Task/100-doors/Scheme/100-doors-1.scm diff --git a/Task/100-doors/Scheme/100-doors-2.ss b/Task/100-doors/Scheme/100-doors-2.scm similarity index 100% rename from Task/100-doors/Scheme/100-doors-2.ss rename to Task/100-doors/Scheme/100-doors-2.scm diff --git a/Task/100-doors/Scheme/100-doors-3.ss b/Task/100-doors/Scheme/100-doors-3.scm similarity index 100% rename from Task/100-doors/Scheme/100-doors-3.ss rename to Task/100-doors/Scheme/100-doors-3.scm diff --git a/Task/100-doors/Scheme/100-doors-4.scm b/Task/100-doors/Scheme/100-doors-4.scm new file mode 100644 index 0000000000..a65ab0f484 --- /dev/null +++ b/Task/100-doors/Scheme/100-doors-4.scm @@ -0,0 +1,17 @@ +(define (doors-toggle door-state) + (define (doors-toggle-helper door-state num-doors step counter) + (cond ((> step num-doors) door-state) + ((> counter (1- num-doors)) + (doors-toggle-helper door-state num-doors (1+ step) step)) + (else (vector-set! door-state + counter + (not (array-ref door-state counter))) + (doors-toggle-helper door-state + num-doors + step + (+ step counter))))) + (let ((step 1) + (num-doors (vector-length door-state))) + (doors-toggle-helper door-state num-doors step (1- step)))) + +(doors-toggle (make-vector 100 #f)) ;; #t is an open door, #f a closed one diff --git a/Task/100-doors/Tailspin/100-doors-1.tailspin b/Task/100-doors/Tailspin/100-doors-1.tailspin new file mode 100644 index 0000000000..3a2f81f4c2 --- /dev/null +++ b/Task/100-doors/Tailspin/100-doors-1.tailspin @@ -0,0 +1,14 @@ +source hundredDoors + @: [ 1..100 -> 0 ]; + templates toggle + def jump: $; + $jump..100:$jump -> \( + when )> do @hundredDoors($): 1; + otherwise @hundredDoors($): 0; + \) -> !VOID + end toggle + 1..100 -> toggle -> !VOID + $@ -> \[i](<=1> ' $i;' !\) ! +end hundredDoors + +$hundredDoors -> 'Open doors:$...;' -> !OUT::write diff --git a/Task/100-doors/Tailspin/100-doors-2.tailspin b/Task/100-doors/Tailspin/100-doors-2.tailspin new file mode 100644 index 0000000000..fb29ae1395 --- /dev/null +++ b/Task/100-doors/Tailspin/100-doors-2.tailspin @@ -0,0 +1,14 @@ +hundredDoors source + @ set [ 1..100 -> 0 ]; + toggle templates + jump is $; + $jump..100:$jump -> templates + when <|?($@hundredDoors($) matches <|=0>)> do @hundredDoors($) set 1; + otherwise @hundredDoors($) set 0; + end -> !VOID + end toggle + 1..100 -> toggle -> !VOID + $@(.. as i; -> if <|=1> -> ' $i;') ! +end hundredDoors + +$hundredDoors -> 'Open doors:$...;' ! diff --git a/Task/100-doors/Tailspin/100-doors.tailspin b/Task/100-doors/Tailspin/100-doors.tailspin deleted file mode 100644 index 8ea97723d3..0000000000 --- a/Task/100-doors/Tailspin/100-doors.tailspin +++ /dev/null @@ -1,11 +0,0 @@ -source hundredDoors - @: [ 1..100 -> 0 ]; - templates toggle - def jump: $; - $jump..100:$jump -> \(when )> do @hundredDoors($): 1; otherwise @hundredDoors($): 0;\) -> !VOID - end toggle - 1..100 -> toggle -> !VOID - $@ -> \[i](<=1> ' $i;' !\) ! -end hundredDoors - -$hundredDoors -> 'Open doors:$...;' -> !OUT::write diff --git a/Task/100-doors/Tcl/100-doors-1.tcl b/Task/100-doors/Tcl/100-doors-1.tcl index 43badf3380..71a614db6d 100644 --- a/Task/100-doors/Tcl/100-doors-1.tcl +++ b/Task/100-doors/Tcl/100-doors-1.tcl @@ -1,11 +1,85 @@ -package require Tcl 8.5 -set n 100 -set doors [concat - [lrepeat $n 0]] -for {set step 1} {$step <= $n} {incr step} { - for {set i $step} {$i <= $n} {incr i $step} { - lset doors $i [expr { ! [lindex $doors $i]}] +#!/usr/bin/env tclsh + +# 100 doors + +proc seq { m n } { + set r {} + for {set i $m} {$i <= $n} {incr i} { + lappend r $i + } + return $r +} + +proc toggle {val a b} { + # expr has ternary operators + return [expr { + ${val} == ${a}? ${b} : + ${val} == ${b}? ${a} : + [error "bad value: ${val}"] + }] +} + +proc multiples {n max} { + set ret {} + set x $n + + # maximum multiple + set mid [expr $max / 2] + + if {$x>=$mid && $x<$max} { return $x } + + # calculate multiples + if {[expr $x <= $mid]} { + for {set i 1} {$i <= $max } {incr i} { + + set x [expr $i * $n] + + if {$x > $max} { break } + + lappend ret $x + } + } + + return $ret +} + +# states +array set state { + open "open" + closed "closed" + unknown "?" +} + +# ============================== +# start program + +# 100 doors +variable MAX 100 + +variable mid [expr int($MAX / 2)] + +variable Seq_100 [seq 1 $MAX] + +# initialize doors closed +foreach n $Seq_100 { + set door($n) $state(closed) +} + +# do for 1 .. 100 +foreach m $Seq_100 { + + set mults [multiples $m $MAX] + + foreach d $mults { + set door($d) [toggle $door($d) $state(open) $state(closed)] } } -for {set i 1} {$i <= $n} {incr i} { - puts [format "door %d is %s" $i [expr {[lindex $doors $i] ? "open" : "closed"}]] + +# output +foreach n $Seq_100 { + if { $door($n) eq $state(open) } { + puts stdout "$n: $door($n)" + } } + +# end diff --git a/Task/100-doors/Tcl/100-doors-2.tcl b/Task/100-doors/Tcl/100-doors-2.tcl index df7078d750..43badf3380 100644 --- a/Task/100-doors/Tcl/100-doors-2.tcl +++ b/Task/100-doors/Tcl/100-doors-2.tcl @@ -1,8 +1,11 @@ package require Tcl 8.5 -set doors [lrepeat [expr {$n + 1}] closed] -for {set i 1} {$i <= sqrt($n)} {incr i} { - lset doors [expr {$i ** 2}] open +set n 100 +set doors [concat - [lrepeat $n 0]] +for {set step 1} {$step <= $n} {incr step} { + for {set i $step} {$i <= $n} {incr i $step} { + lset doors $i [expr { ! [lindex $doors $i]}] + } } for {set i 1} {$i <= $n} {incr i} { - puts [format "door %d is %s" $i [lindex $doors $i]] + puts [format "door %d is %s" $i [expr {[lindex $doors $i] ? "open" : "closed"}]] } diff --git a/Task/100-doors/Tcl/100-doors-3.tcl b/Task/100-doors/Tcl/100-doors-3.tcl index 8e3db5488e..df7078d750 100644 --- a/Task/100-doors/Tcl/100-doors-3.tcl +++ b/Task/100-doors/Tcl/100-doors-3.tcl @@ -1,46 +1,8 @@ package require Tcl 8.5 -package require Tk - -array set door_status {} - -# create the gui -set doors [list x] -for {set i 0} {$i < 10} {incr i} { - for {set j 0} {$j < 10} {incr j} { - set k [expr {1 + $j + 10*$i}] - lappend doors [radiobutton .d_$k -text $k -variable door_status($k) \ - -indicatoron no -offrelief flat -width 3 -value open] - grid [lindex $doors $k] -column $j -row $i - } +set doors [lrepeat [expr {$n + 1}] closed] +for {set i 1} {$i <= sqrt($n)} {incr i} { + lset doors [expr {$i ** 2}] open } - -# create the controls -button .start -command go -text Start -label .i_label -text " door:" -entry .i -textvariable i -width 4 -label .step_label -text " step:" -entry .step -textvariable step -width 4 -grid .start - .i_label - .i - .step_label - .step - -row $i -grid configure .start -sticky ew -grid configure .i_label .step_label -sticky e -grid configure .i .step -sticky w - -proc go {} { - global doors door_status i step - - # initialize the door_status (all closed) - for {set d 1} {$d <= 100} {incr d} { - set door_status($d) closed - } - - # now, begin opening and closing - for {set step 1} {$step <= 100} {incr step} { - for {set i 1} {$i <= 100} {incr i} { - if {$i % $step == 0} { - [lindex $doors $i] [expr {$door_status($i) eq "open" ? "deselect" : "select"}] - update - after 50 - } - } - } +for {set i 1} {$i <= $n} {incr i} { + puts [format "door %d is %s" $i [lindex $doors $i]] } diff --git a/Task/100-doors/Tcl/100-doors-4.tcl b/Task/100-doors/Tcl/100-doors-4.tcl new file mode 100644 index 0000000000..8e3db5488e --- /dev/null +++ b/Task/100-doors/Tcl/100-doors-4.tcl @@ -0,0 +1,46 @@ +package require Tcl 8.5 +package require Tk + +array set door_status {} + +# create the gui +set doors [list x] +for {set i 0} {$i < 10} {incr i} { + for {set j 0} {$j < 10} {incr j} { + set k [expr {1 + $j + 10*$i}] + lappend doors [radiobutton .d_$k -text $k -variable door_status($k) \ + -indicatoron no -offrelief flat -width 3 -value open] + grid [lindex $doors $k] -column $j -row $i + } +} + +# create the controls +button .start -command go -text Start +label .i_label -text " door:" +entry .i -textvariable i -width 4 +label .step_label -text " step:" +entry .step -textvariable step -width 4 +grid .start - .i_label - .i - .step_label - .step - -row $i +grid configure .start -sticky ew +grid configure .i_label .step_label -sticky e +grid configure .i .step -sticky w + +proc go {} { + global doors door_status i step + + # initialize the door_status (all closed) + for {set d 1} {$d <= 100} {incr d} { + set door_status($d) closed + } + + # now, begin opening and closing + for {set step 1} {$step <= 100} {incr step} { + for {set i 1} {$i <= 100} {incr i} { + if {$i % $step == 0} { + [lindex $doors $i] [expr {$door_status($i) eq "open" ? "deselect" : "select"}] + update + after 50 + } + } + } +} diff --git a/Task/100-doors/Uiua/100-doors-1.uiua b/Task/100-doors/Uiua/100-doors-1.uiua new file mode 100644 index 0000000000..a9b6f157a4 --- /dev/null +++ b/Task/100-doors/Uiua/100-doors-1.uiua @@ -0,0 +1,6 @@ +◿2/+=0⊞◿.+1⇡100 + +1⇡100 # 1-100 + ⊞◿. # Mod each with 1-100 + =0 # Find where mod = 0, aka the divisors + /+ # Sum to get num of divisors +◿2 # Num divisors is odd diff --git a/Task/100-doors/Uiua/100-doors-2.uiua b/Task/100-doors/Uiua/100-doors-2.uiua new file mode 100644 index 0000000000..c1e094976b --- /dev/null +++ b/Task/100-doors/Uiua/100-doors-2.uiua @@ -0,0 +1 @@ +⊜∘/≠±⊞◿..+1⇡100 diff --git a/Task/100-doors/Uiua/100-doors-3.uiua b/Task/100-doors/Uiua/100-doors-3.uiua new file mode 100644 index 0000000000..35552aab2a --- /dev/null +++ b/Task/100-doors/Uiua/100-doors-3.uiua @@ -0,0 +1 @@ +×.+1⇡⌊√ 100 diff --git a/Task/100-doors/Unison/100-doors.unison b/Task/100-doors/Unison/100-doors.u similarity index 100% rename from Task/100-doors/Unison/100-doors.unison rename to Task/100-doors/Unison/100-doors.u diff --git a/Task/100-doors/V-(Vlang)/100-doors-2.v b/Task/100-doors/V-(Vlang)/100-doors-2.v index 6ec392d9a6..35ff929ac5 100644 --- a/Task/100-doors/V-(Vlang)/100-doors-2.v +++ b/Task/100-doors/V-(Vlang)/100-doors-2.v @@ -11,11 +11,10 @@ fn main(){ doors[current - 1] = true increment++ door_nbr += 2 * increment + 1 - } + print('O') + } else { + print('=') + } } - doors.map( fn( it bool) bool { // graphically represent opened doors - print( if it {( 'O')} else {('=')} ) - return it - }) println('') } diff --git a/Task/100-doors/V-(Vlang)/100-doors-3.v b/Task/100-doors/V-(Vlang)/100-doors-3.v new file mode 100644 index 0000000000..8f720ebff3 --- /dev/null +++ b/Task/100-doors/V-(Vlang)/100-doors-3.v @@ -0,0 +1,11 @@ +import math + +const number_doors = 101 + +fn main() { + max_i := int(math.sqrt(f64(number_doors - 1))) + 1 + for i in 1..max_i { + door := i * i + println("Door ${door} open") + } +} diff --git a/Task/100-doors/V-(Vlang)/100-doors-4.v b/Task/100-doors/V-(Vlang)/100-doors-4.v new file mode 100644 index 0000000000..bce04b6c59 --- /dev/null +++ b/Task/100-doors/V-(Vlang)/100-doors-4.v @@ -0,0 +1,5 @@ +fn main() { + for i in 1..11 { + print ( " Door ${i*i} is open.\n" ) + } +} diff --git a/Task/100-doors/VBScript/100-doors.vb b/Task/100-doors/VBScript/100-doors.vbs similarity index 100% rename from Task/100-doors/VBScript/100-doors.vb rename to Task/100-doors/VBScript/100-doors.vbs diff --git a/Task/100-doors/VHDL/100-doors-1.vhdl b/Task/100-doors/VHDL/100-doors-1.vhd similarity index 100% rename from Task/100-doors/VHDL/100-doors-1.vhdl rename to Task/100-doors/VHDL/100-doors-1.vhd diff --git a/Task/100-doors/VHDL/100-doors-2.vhdl b/Task/100-doors/VHDL/100-doors-2.vhd similarity index 100% rename from Task/100-doors/VHDL/100-doors-2.vhdl rename to Task/100-doors/VHDL/100-doors-2.vhd diff --git a/Task/100-doors/YAMLScript/100-doors.ys b/Task/100-doors/YAMLScript/100-doors.ys index d5248aee43..7e63c2a67d 100644 --- a/Task/100-doors/YAMLScript/100-doors.ys +++ b/Task/100-doors/YAMLScript/100-doors.ys @@ -1,16 +1,14 @@ -!yamlscript/v0 +!YS-v0 defn main(): - 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 - -defn doors(): - reduce: - fn(doors idx): assoc(doors idx true) - into []: repeat(100 false) - map \(dec (%1 * %1)): 1 .. 10 + open =: + reduce _ vec([true] * 100) (1 .. 100): + fn(doors i): + loop j i, doors doors: + if j < 100: + recur (j + i).++: + update-in doors [j]: \(doors.$j.!) + else: doors + say: -"Open doors after 100 passes:\ " + + (1 .. 100).map(\(_.--:open && _)) + .filter(a).join(', ') diff --git a/Task/100-doors/Zig/100-doors-4.zig b/Task/100-doors/Zig/100-doors-4.zig index 53b792a533..14d911f591 100644 --- a/Task/100-doors/Zig/100-doors-4.zig +++ b/Task/100-doors/Zig/100-doors-4.zig @@ -1,8 +1,7 @@ pub fn main() !void { const stdout = @import("std").io.getStdOut().writer(); - var door: u8 = 1; - while (door * door <= 100) : (door += 1) { + for(1..11) |door| { try stdout.print("Door {d} is open\n", .{door * door}); } } diff --git a/Task/100-prisoners/11l/100-prisoners.11l b/Task/100-prisoners/11l/100-prisoners.11l index f8e57ab878..0bacfb4489 100644 --- a/Task/100-prisoners/11l/100-prisoners.11l +++ b/Task/100-prisoners/11l/100-prisoners.11l @@ -5,7 +5,7 @@ F play_random(n) L 0 .< n random:shuffle(&in_drawer) V found = 0B - L(prisoner) 100 + L(prisoner) 0.<100 found = 0B L(reveal) random:sample(sampler, 50) V card = in_drawer[reveal] @@ -24,7 +24,7 @@ F play_optimal(n) L 0 .< n random:shuffle(&in_drawer) V found = 0B - L(prisoner) 100 + L(prisoner) 0.<100 V reveal = prisoner found = 0B L 50 diff --git a/Task/100-prisoners/ALGOL-68/100-prisoners.alg b/Task/100-prisoners/ALGOL-68/100-prisoners.alg new file mode 100644 index 0000000000..e8858ff506 --- /dev/null +++ b/Task/100-prisoners/ALGOL-68/100-prisoners.alg @@ -0,0 +1,66 @@ +BEGIN # 100 prisoners # + +CO begin code from the Knuth shuffle task CO +PROC between = (INT a, b)INT : +( + ENTIER (random * ABS (b-a+1) + (a ?n 1) do + (bind ?k (+ 1 (random ?n))) + (bind ?tmp (nth$ ?n ?lst)) + (bind ?lst (replace$ ?lst ?n ?n (nth$ ?k ?lst))) + (bind ?lst (replace$ ?lst ?k ?k ?tmp)) + (bind ?n (- ?n 1))) + ?lst) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; Create a random permutation of 1..100 representing box contents +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +(deffunction random-permutation () + (shuffle (create$ 1 2 3 4 5 6 7 8 9 10 + 11 12 13 14 15 16 17 18 19 20 + 21 22 23 24 25 26 27 28 29 30 + 31 32 33 34 35 36 37 38 39 40 + 41 42 43 44 45 46 47 48 49 50 + 51 52 53 54 55 56 57 58 59 60 + 61 62 63 64 65 66 67 68 69 70 + 71 72 73 74 75 76 77 78 79 80 + 81 82 83 84 85 86 87 88 89 90 + 91 92 93 94 95 96 97 98 99 100))) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; Prisoner loop strategy: +;; Start at your own number, open that box, then follow the chain. +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +(deffunction prisoner-succeeds (?id ?perm) + (bind ?next ?id) + (bind ?opens 0) + (while (< ?opens MAX-OPENS) do + (bind ?opens (+ ?opens 1)) + (bind ?found (nth$ ?next ?perm)) + (if (= ?found ?id) then + (return TRUE)) + (bind ?next ?found)) + FALSE) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; Run one full trial: all prisoners must succeed +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +(deffunction run-trial () + (bind ?perm (random-permutation)) + (foreach ?p (create$ 1 to NUM-PRISONERS) do + (if (not (prisoner-succeeds ?p ?perm)) then + (return FALSE))) + TRUE) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; Run many trials to estimate probability +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +(deffunction simulate (?trials) + (bind ?wins 0) + (loop-for-count (?i 1 ?trials) do + (if (run-trial) then + (bind ?wins (+ ?wins 1)))) + (printout t "Trials: " ?trials crlf) + (printout t "Successful trials: " ?wins crlf) + (printout t "Estimated probability: " + (/ (float ?wins) (float ?trials)) crlf)) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; Entry point +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +(reset) +(simulate 1000) diff --git a/Task/100-prisoners/Crystal/100-prisoners.crystal b/Task/100-prisoners/Crystal/100-prisoners.cr similarity index 100% rename from Task/100-prisoners/Crystal/100-prisoners.crystal rename to Task/100-prisoners/Crystal/100-prisoners.cr diff --git a/Task/100-prisoners/D/100-prisoners.d b/Task/100-prisoners/D/100-prisoners.d index 04986ae37c..5c70291510 100644 --- a/Task/100-prisoners/D/100-prisoners.d +++ b/Task/100-prisoners/D/100-prisoners.d @@ -37,7 +37,7 @@ bool playRandom() { double exec(const size_t n, bool function() play) { size_t success = 0; - for (int i = n; i > 0; i--) { + for (size_t i = n; i > 0; i--) { if (play()) { success++; } diff --git a/Task/100-prisoners/EasyLang/100-prisoners.easy b/Task/100-prisoners/EasyLang/100-prisoners.easy index 6bdc815b68..d43959b394 100644 --- a/Task/100-prisoners/EasyLang/100-prisoners.easy +++ b/Task/100-prisoners/EasyLang/100-prisoners.easy @@ -1,60 +1,51 @@ -for i = 1 to 100 - drawer[] &= i - sampler[] &= i +global drawer[] sampler[] . +proc init . + for i = 1 to 100 + drawer[] &= i + sampler[] &= i + . . -subr shuffle_drawer +init +proc shuffle_drawer . for i = len drawer[] downto 2 - r = randint i + r = random 1 i swap drawer[r] drawer[i] . . -subr play_random +func play_random . shuffle_drawer for prisoner = 1 to 100 - found = 0 for i = 1 to 50 - r = randint (100 - i) + r = random 1 (100 - i + 1) card = drawer[sampler[r]] - swap sampler[r] sampler[100 - i - 1] - if card = prisoner - found = 1 - break 1 - . - . - if found = 0 - break 1 + swap sampler[r] sampler[100 - i + 1] + if card = prisoner : break 1 . + if i > 50 : return 0 . + return 1 . -subr play_optimal +func play_optimal . shuffle_drawer for prisoner = 1 to 100 reveal = prisoner - found = 0 for i = 1 to 50 card = drawer[reveal] - if card = prisoner - found = 1 - break 1 - . + if card = prisoner : break 1 reveal = card . - if found = 0 - break 1 - . + if i > 50 : return 0 . + return 1 . -n = 10000 -win = 0 -for _ = 1 to n - play_random - win += found +n = 100000 +for i to n + win += play_random . print "random: " & 100.0 * win / n & "%" # win = 0 -for _ = 1 to n - play_optimal - win += found +for i to n + win += play_optimal . print "optimal: " & 100.0 * win / n & "%" diff --git a/Task/100-prisoners/Ecstasy/100-prisoners.ecstasy b/Task/100-prisoners/Ecstasy/100-prisoners.ecstasy new file mode 100644 index 0000000000..9f66539ddd --- /dev/null +++ b/Task/100-prisoners/Ecstasy/100-prisoners.ecstasy @@ -0,0 +1,49 @@ +module OneHundredPrisoners { + @Inject Console console; + + void run() { + console.print($"# of executions: {attempts}"); + console.print($"Optimal play success rate: {simulate(tryOpt)}%"); + console.print($" Random play success rate: {simulate(tryRnd)}%"); + } + + Int attempts = 10000; + + Dec simulate(function Boolean(Int[]) allFoundNumber) { + Int[] drawers = new Int[100](i->i); + Int pardoned = 0; + for (Int i : 1..attempts) { + if (allFoundNumber(drawers.shuffled())) { + ++pardoned; + } + } + return (pardoned * 1000000 / attempts).toDec() / 10000; + } + + Boolean tryRnd(Int[] drawers) { + Inmates: for (Int inmate : 0..<100) { + Int[] choices = drawers.shuffled(); + for (Int attempt : 0..<50) { + if (drawers[choices[attempt]] == inmate) { + continue Inmates; + } + } + return False; + } + return True; + } + + Boolean tryOpt(Int[] drawers) { + Inmates: for (Int inmate : 0..<100) { + Int choice = inmate; + for (Int attempt : 0..<50) { + if (drawers[choice] == inmate) { + continue Inmates; + } + choice = drawers[choice]; + } + return False; + } + return True; + } +} diff --git a/Task/100-prisoners/Elixir/100-prisoners.elixir b/Task/100-prisoners/Elixir/100-prisoners.ex similarity index 100% rename from Task/100-prisoners/Elixir/100-prisoners.elixir rename to Task/100-prisoners/Elixir/100-prisoners.ex diff --git a/Task/100-prisoners/Icon/100-prisoners.icon b/Task/100-prisoners/Icon/100-prisoners.icon new file mode 100644 index 0000000000..adcfba193c --- /dev/null +++ b/Task/100-prisoners/Icon/100-prisoners.icon @@ -0,0 +1,40 @@ +link "numbers" +global lp # lucky prisoner list +global p # starting prisoner list +global pardoned # Count of trials with all prisoners pardoned + +procedure main(A) + n := \A[1] | 100 + runs := \A[2] | 3000 + + write(runs," runs using ",n," prisoners.") + every (pardoned := 0, 1 to runs) do + runTrial(simplePrisoner, n) + write("Simple: ",fix(100*pardoned,runs,6,2),"%") + every (pardoned := 0, 1 to runs) do + runTrial(smartPrisoner, n) + write("Smart: ",fix(100*pardoned,runs,6,2),"%") +end + +procedure runTrial(pCode,n) + d := mkDrawers(n) + p := set([: 1 to n :]) + lp := set() + every pCode(d, !p) + if *lp = n then pardoned +:= 1 +end + +procedure mkDrawers(n) + d := [: 1 to n :] + every !d :=: ?d + return d +end + +procedure simplePrisoner(d, n) + every 1 to *d/2 do if n = (i := ?d) then break (insert(lp,n)) +end + +procedure smartPrisoner(d, n) + i := n + every 1 to *d/2 do if n = (i := d[i]) then break (insert(lp,n)) +end diff --git a/Task/100-prisoners/Julia/100-prisoners.julia b/Task/100-prisoners/Julia/100-prisoners.jl similarity index 100% rename from Task/100-prisoners/Julia/100-prisoners.julia rename to Task/100-prisoners/Julia/100-prisoners.jl diff --git a/Task/100-prisoners/Kotlin/100-prisoners.kotlin b/Task/100-prisoners/Kotlin/100-prisoners.kts similarity index 100% rename from Task/100-prisoners/Kotlin/100-prisoners.kotlin rename to Task/100-prisoners/Kotlin/100-prisoners.kts diff --git a/Task/100-prisoners/Pluto/100-prisoners.pluto b/Task/100-prisoners/Pluto/100-prisoners.pluto new file mode 100644 index 0000000000..029aec0590 --- /dev/null +++ b/Task/100-prisoners/Pluto/100-prisoners.pluto @@ -0,0 +1,55 @@ +local fmt = require "fmt" +require "table2" + +local function do_trials(trials, np, strategy) + local pardoned = 0 + for _ = 1, trials do + local drawers = table.create(100) + for i = 1, 100 do drawers[i] = i end + drawers:shuffle() + local next_trial = false + for p = 1, np do + local next_prisoner = false + if strategy == "optimal" then + local prev = p + for __ = 1, 50 do + local curr = drawers[prev] + if curr == p then + next_prisoner = true + break + end + prev = curr + end + else + local opened = table.rep(100, false) + for ___ = 1, 50 do + local n + while true do + n = math.random(100) + if !opened[n] then + opened[n] = true + break + end + end + if drawers[n] == p then + next_prisoner = true + break + end + end + end + if !next_prisoner then + next_trial = true + break + end + end + if !next_trial then pardoned += 1 end + end + local rf = pardoned / trials * 100 + fmt.print(" strategy = %-7s pardoned = %,6s relative frequency = %5.2f%%\n", strategy, pardoned, rf) +end + +local trials = 1e5 +for {10, 100} as np do + fmt.print("Results from %,s trials with %d prisoners:\n", trials, np) + for {"random", "optimal"} as strategy do do_trials(trials, np, strategy) end +end diff --git a/Task/100-prisoners/PowerShell/100-prisoners.psh b/Task/100-prisoners/PowerShell/100-prisoners.ps1 similarity index 100% rename from Task/100-prisoners/PowerShell/100-prisoners.psh rename to Task/100-prisoners/PowerShell/100-prisoners.ps1 diff --git a/Task/100-prisoners/Prolog/100-prisoners.pro b/Task/100-prisoners/Prolog/100-prisoners.pro new file mode 100644 index 0000000000..375a4acfc8 --- /dev/null +++ b/Task/100-prisoners/Prolog/100-prisoners.pro @@ -0,0 +1,43 @@ +:- use_module(library(aggregate)). +:- use_module(library(lists)). +:- use_module(library(random)). + +random_subset(Length, List, Subset) :- + random_permutation(List, Shuffled), + length(Subset, Length), + prefix(Subset, Shuffled). + +random_play :- + numlist(1, 100, Prisoners), + random_permutation(Prisoners, Drawers), + forall(member(Prisoner, Prisoners), ( + random_subset(50, Drawers, CheckedDrawers), + memberchk(Prisoner, CheckedDrawers) + )). + +optimal_play :- + numlist(1, 100, Prisoners), + random_permutation(Prisoners, Drawers), + forall(member(Prisoner, Prisoners), optimal_play(50, Prisoner, Prisoner, Drawers)). + +optimal_play(ChecksRemaining, Prisoner, NumberToCheck, Drawers) :- + ChecksRemaining > 0, + nth1(NumberToCheck, Drawers, NumberInDrawer), + ( NumberInDrawer = Prisoner + -> true + ; ChecksRemaining0 is ChecksRemaining - 1, + optimal_play(ChecksRemaining0, Prisoner, NumberInDrawer, Drawers) + ). + +:- meta_predicate play_n_times(+, 0, -). +play_n_times(PlayCount, Play, Percentage) :- + aggregate_all(count, ( between(1, PlayCount, _), call(Play) ), Victories), + Percentage is Victories / PlayCount * 100. + +main(SimulationCount) :- + play_n_times(SimulationCount, random_play, RandomPlayPercent), + play_n_times(SimulationCount, optimal_play, OptimalPlayPercent), + format("Simulation count: ~d\nRandom play wins: ~f% of the simulations.\nOptimal play wins ~f% of the simulations.", + [SimulationCount, RandomPlayPercent, OptimalPlayPercent]). + +:- main(100_000). diff --git a/Task/100-prisoners/Rebol/100-prisoners.rebol b/Task/100-prisoners/Rebol/100-prisoners.rebol new file mode 100644 index 0000000000..e7378827ab --- /dev/null +++ b/Task/100-prisoners/Rebol/100-prisoners.rebol @@ -0,0 +1,77 @@ +Rebol [ + title: "Rosetta code: 100 prisoners" + file: %100_prisoners.r3 + url: https://rosettacode.org/wiki/100_prisoners + needs: 3.0.0 + note: "Based on Red language implementation!" +] + +random/seed 1 +prisoners: 100 ;; Total number of prisoners in the puzzle +K_runs: 10000 ;; Number of simulation runs to perform + +rand_arr: make block! prisoners ;; Will hold the numbers 1..100 +repeat n prisoners [append rand_arr n] ;; Fill rand_arr with [1 2 3 ... 100] + +;; -------------------------------------------------- +;; strat_optimal: "optimal" strategy from the puzzle +;; Each prisoner starts at the locker with their own number, +;; then follows the chain inside the lockers until they find their number +;; or until they have opened 50 lockers. +;; Returns TRUE if the prisoner finds their own number, FALSE otherwise. +;; -------------------------------------------------- +strat_optimal: func [pris /local locker][ + locker: pris ;; Start at 'own-numbered' locker + loop 50 [ + if Board/:locker = pris [ return true ] ;; Found prisoner's number? -> success + locker: Board/:locker ;; Move to the locker whose number was inside + ] + false ;; Not found within 50 tries -> fail +] + +;; -------------------------------------------------- +;; strat_rand: "random" strategy +;; Each prisoner picks a random permutation of lockers, +;; then opens the first 50 in that random order, checking for their number. +;; Returns TRUE if found, FALSE if not. +;; -------------------------------------------------- +strat_rand: func [pris][ + random rand_arr ;; Randomize the locker opening order + repeat n 50 [ + if Board/(rand_arr/:n) = pris [ return true ];; Check the nth randomly chosen locker + ] ;; If found -> success + false ;; Not found in 50 tries -> fail +] + +;; -------------------------------------------------- +;; check_board: Runs a strategy for the entire set of prisoners +;; Returns TRUE if *every prisoner* finds their number, FALSE if any fail. +;; Argument 'strat' is the symbol 'optimal or 'rand +;; -------------------------------------------------- +check_board: func [strat][ + ;; Choose which strategy function to run + strat: either strat = 'optimal [:strat_optimal] [:strat_rand] + + ;; Test each prisoner with the chosen strategy + repeat pris prisoners [ + unless strat pris [return false] ;; If any fail, run ends -> false + ] + true ;; All prisoners succeeded -> true +] + +saved: saved_rand: 0 ;; Counters for the number of successful runs per strategy + +;; -------------------------------------------------- +;; Run the given number of simulations +;; -------------------------------------------------- +loop K_runs [ + Board: random copy rand_arr ;; Create a random locker arrangement for this run + if check_board 'optimal [saved: saved + 1] ;; Attempt "optimal" strategy, count full successes + if check_board 'rand [saved_rand: saved_rand + 1] ;; Attempt "random" strategy, count full successes +] + +;; At this point: +;; - 'saved' = number of runs where *all prisoners* survived using optimal strategy +;; - 'saved_rand' = number of runs where *all prisoners* survived using random strategy +print ["runs" k_runs newline "Percent saved opt.strategy:" saved * 100.0 / k_runs ] +print ["Percent saved random strategy:" saved_rand * 100.0 / k_runs ] diff --git a/Task/100-prisoners/Rust/100-prisoners-1.rust b/Task/100-prisoners/Rust/100-prisoners-1.rs similarity index 100% rename from Task/100-prisoners/Rust/100-prisoners-1.rust rename to Task/100-prisoners/Rust/100-prisoners-1.rs diff --git a/Task/100-prisoners/Rust/100-prisoners-2.rust b/Task/100-prisoners/Rust/100-prisoners-2.rs similarity index 100% rename from Task/100-prisoners/Rust/100-prisoners-2.rust rename to Task/100-prisoners/Rust/100-prisoners-2.rs diff --git a/Task/100-prisoners/True-BASIC/100-prisoners.basic b/Task/100-prisoners/True-BASIC/100-prisoners.basic new file mode 100644 index 0000000000..eacc0cac4a --- /dev/null +++ b/Task/100-prisoners/True-BASIC/100-prisoners.basic @@ -0,0 +1,40 @@ +FUNCTION trials(prisoners, iterations, optimal) + DIM drawers(100) + FOR i = 1 TO prisoners + LET drawers(i) = i + NEXT i + FOR i = 1 TO iterations + FOR k = 1 TO prisoners + LET x = RND+1 + LET p = drawers(x) + LET drawers(x) = drawers(k) + LET drawers(k) = p + NEXT k + FOR prisoner = 1 TO prisoners + LET found = false + IF optimal<>0 THEN LET drawer = prisoner ELSE LET drawer = RND+1 + FOR j = 1 TO prisoners/2 + LET drawer = drawers(drawer) + IF drawer = prisoner THEN + LET found = true + EXIT FOR + END IF + IF (NOT optimal<>0) THEN LET drawer = RND+1 + NEXT j + IF (NOT found<>0) THEN EXIT FOR + NEXT prisoner + LET pardoned = pardoned+found + NEXT i + LET trials = (100*pardoned/iterations) +END FUNCTION + +LET false = 0 +LET true = 1 +LET iterations = 10000 +PRINT "Simulation count: "; iterations +FOR prisoners = 10 TO 100 STEP 90 + LET randon = trials(prisoners,iterations,false) + LET optimal = trials(prisoners,iterations,true) + PRINT "Prisoners: "; prisoners; ", random: "; randon; ", optimal: "; optimal +NEXT prisoners +END diff --git a/Task/100-prisoners/VBScript/100-prisoners.vb b/Task/100-prisoners/VBScript/100-prisoners.vbs similarity index 100% rename from Task/100-prisoners/VBScript/100-prisoners.vb rename to Task/100-prisoners/VBScript/100-prisoners.vbs diff --git a/Task/100-prisoners/YAMLScript/100-prisoners.ys b/Task/100-prisoners/YAMLScript/100-prisoners.ys new file mode 100644 index 0000000000..d44a0487cc --- /dev/null +++ b/Task/100-prisoners/YAMLScript/100-prisoners.ys @@ -0,0 +1,79 @@ +!YS-v0 + +defn main(n=5000): + :: https://rosettacode.org/wiki/100_prisoners + + random-successes optimal-successes run-count =: + simulate-n-runs(n) + .slice(q(random-successes optimal-successes run-count)) + + say: "Probability of survival with random search: $F(random-successes / run-count)" + + say: "Probability of survival with ordered search: $F(optimal-successes / run-count)" + +defn simulate-n-runs(n): + :: Simulate n runs of the 100 prisoner problem and returns a success count + for each search method. + + loop random-successes 0, optimal-successes 0, run-count 0: + # If we've done the loop n times + if n == run-count: + # return results + then:: + random-successes :: random-successes + optimal-successes :: optimal-successes + run-count :: run-count + + # Otherwise, run for another batch of prisoners + else: + next-result =: simulate-100-prisoners() + recur: + (random-successes + next-result.random) + (optimal-successes + next-result.optimal) + run-count.++ + +defn simulate-100-prisoners(): + :: Simulates all prisoners searching the same drawers by both strategies, + returns map showing whether each was successful. + + # Create 100 drawers with randomly ordered prisoner numbers: + drawers =: random-drawers() + hash-map: + :random try-luck(drawers search-50-random-drawers) + :optimal try-luck(drawers search-50-optimal-drawers) + +defn try-luck(drawers drawer-searching-function): + :: Returns 1 if all prisoners find their number otherwise 0. + + loop prisoners range(100): + if prisoners.?: + if prisoners.0.drawer-searching-function(drawers): + recur: rest(prisoners) + else: 0 + else: 1 + +defn search-50-optimal-drawers(prisoner-number drawers): + :: Open 50 drawers according to the agreed strategy, returning true if + prisoner's number was found. + + loop next-drawer prisoner-number, drawers-opened 0: + when drawers-opened != 50: + result =: drawers.$next-drawer + result == prisoner-number ||: + recur: result drawers-opened.++ + +defn search-50-random-drawers(prisoner-number drawers): + :: Select 50 random drawers and return true if the prisoner's number was + found. + + drawers: + .shuffle() + .take(50) + .filter(eq(prisoner-number)) + .count() + .eq(1) + +defn random-drawers(): + :: Returns a list of shuffled numbers. + + shuffle: range(100) diff --git a/Task/15-puzzle-game/Ada/15-puzzle-game-1.ada b/Task/15-puzzle-game/Ada/15-puzzle-game-1.adb similarity index 100% rename from Task/15-puzzle-game/Ada/15-puzzle-game-1.ada rename to Task/15-puzzle-game/Ada/15-puzzle-game-1.adb diff --git a/Task/15-puzzle-game/Ada/15-puzzle-game-2.ada b/Task/15-puzzle-game/Ada/15-puzzle-game-2.adb similarity index 100% rename from Task/15-puzzle-game/Ada/15-puzzle-game-2.ada rename to Task/15-puzzle-game/Ada/15-puzzle-game-2.adb diff --git a/Task/15-puzzle-game/Ada/15-puzzle-game-3.ada b/Task/15-puzzle-game/Ada/15-puzzle-game-3.adb similarity index 100% rename from Task/15-puzzle-game/Ada/15-puzzle-game-3.ada rename to Task/15-puzzle-game/Ada/15-puzzle-game-3.adb diff --git a/Task/15-puzzle-game/Ada/15-puzzle-game-4.ada b/Task/15-puzzle-game/Ada/15-puzzle-game-4.adb similarity index 100% rename from Task/15-puzzle-game/Ada/15-puzzle-game-4.ada rename to Task/15-puzzle-game/Ada/15-puzzle-game-4.adb diff --git a/Task/15-puzzle-game/Arturo/15-puzzle-game.arturo b/Task/15-puzzle-game/Arturo/15-puzzle-game.arturo index 4d08ffb095..9dcfaaed59 100644 --- a/Task/15-puzzle-game/Arturo/15-puzzle-game.arturo +++ b/Task/15-puzzle-game/Arturo/15-puzzle-game.arturo @@ -107,17 +107,13 @@ validMovement?: $[ movement :literal ][ pos: game\playerPosition - case [movement] - when? [='up] - -> return (not? in? pos [0..3]) - when? [='down] - -> return (not? in? pos [12..15]) - when? [='left] - -> return (not? in? pos [0 4 8 12]) - when? [='right] - -> return (not? in? pos [3 7 11 15]) - else - -> return false + case movement [ + 'up -> return (not? in? pos [0..3]) + 'down -> return (not? in? pos [12..15]) + 'left -> return (not? in? pos [0 4 8 12]) + 'right -> return (not? in? pos [3 7 11 15]) + any -> return false + ] ] @@ -130,13 +126,14 @@ validMovement?: $[ ;; will be returned the same input as a :string parseInput: $[inp :string][ lowerInp: lower inp - case [lowerInp] - when? [="w"] -> return 'up - when? [="a"] -> return 'left - when? [="s"] -> return 'down - when? [="d"] -> return 'right - when? [="q"] -> return 'quit - else -> return inp + case lowerInp [ + "w" -> return 'up + "a" -> return 'left + "s" -> return 'down + "d" -> return 'right + "q" -> return 'quit + any -> return inp + ] ] ;; Moves the player in Game's Table @@ -155,7 +152,7 @@ movePlayer: $[ playerPosition :integer relativePosition :integer ][ - try [ + if throws? [ ; 'otherPosition is the real index of the 'relativePosition otherPosition: + playerPosition relativePosition @@ -168,20 +165,16 @@ movePlayer: $[ ; -- Updates player's status game\playerPosition: otherPosition game\movements: inc game\movements - ] else -> panic "'movement didn't checked." + ] -> panic "'movement didn't checked." ] - case [movement] - when? [='up] - -> (updateGame game position (neg 4)) - when? [='down] - -> (updateGame game position (4)) - when? [='left] - -> (updateGame game position (neg 1)) - when? [='right] - -> (updateGame game position (1)) - else -> panic "'movement didn't checked." - + case movement [ + 'up -> updateGame game position neg 4 + 'down -> updateGame game position 4 + 'left -> updateGame game position neg 1 + 'right -> updateGame game position 1 + any -> panic "movement didn't check." + ] ] endGame: $[ @@ -209,13 +202,12 @@ runGame: $[sampleTable :block][ -> endGame "Exiting game..." validInp: validInput? command - if? validInp [ + switch validInp [ validMov: validMovement? game command (validMov)? -> movePlayer game command -> printWrongMovement command - ] else - -> printWrongInput command + ] -> printWrongInput command if sampleTable = game -> endGame "Congratulations! You won!" diff --git a/Task/15-puzzle-game/COBOL/15-puzzle-game.cobol b/Task/15-puzzle-game/COBOL/15-puzzle-game.cob similarity index 100% rename from Task/15-puzzle-game/COBOL/15-puzzle-game.cobol rename to Task/15-puzzle-game/COBOL/15-puzzle-game.cob diff --git a/Task/15-puzzle-game/Delphi/15-puzzle-game.delphi b/Task/15-puzzle-game/Delphi/15-puzzle-game.pas similarity index 100% rename from Task/15-puzzle-game/Delphi/15-puzzle-game.delphi rename to Task/15-puzzle-game/Delphi/15-puzzle-game.pas diff --git a/Task/15-puzzle-game/EasyLang/15-puzzle-game.easy b/Task/15-puzzle-game/EasyLang/15-puzzle-game.easy index e10e23f2a7..17beb79a5a 100644 --- a/Task/15-puzzle-game/EasyLang/15-puzzle-game.easy +++ b/Task/15-puzzle-game/EasyLang/15-puzzle-game.easy @@ -1,68 +1,53 @@ -sys topleft -background 432 -textsize 13 +sysconf topleft +gbackground 432 +gtextsize 13 len f[] 16 -proc draw . . - clear +proc draw . + gclear for i = 1 to 16 - h = f[i] - if h < 16 + v = f[i] + if v < 16 x = (i - 1) mod 4 * 24 + 3 y = (i - 1) div 4 * 24 + 3 - color 210 - move x y - rect 22 22 - move x + 4 y + 6 - if h < 10 - move x + 6 y + 6 - . - color 885 - text h + gcolor 210 + grect x y 22 22 + if v < 10 : x += 2 + gcolor 885 + gtext x + 4 y + 6 v . . . -global done . -proc smiley . . +proc smiley . s = 3.5 x = 86 y = 86 - move x y - color 983 - circle 2.8 * s - color 000 - move x - s y - s - circle s / 3 - move x + 3.5 y - 3.5 - circle s / 3 - linewidth s / 3 - curve [ x - s y + s x y + 2 * s x + s y + s ] + gcolor 983 + gcircle x y 2.8 * s + gcolor 000 + gcircle (x - s) (y - s) (s / 3) + gcircle x + 3.5 y - 3.5 s / 3 + glinewidth s / 3 + gcurve [ x - s y + s x y + 2 * s x + s y + s ] . -proc init . . +global done . +proc init . done = 0 - for i = 1 to 16 - f[i] = i - . + for i = 1 to 16 : f[i] = i # shuffle for i = 15 downto 2 - r = randint i + r = random 1 i swap f[r] f[i] . # make it solvable inv = 0 - for i = 1 to 15 - for j = 1 to i - 1 - if f[j] > f[i] - inv += 1 - . - . + for i = 1 to 15 : for j = 1 to i - 1 + if f[j] > f[i] : inv += 1 . - if inv mod 2 <> 0 - swap f[1] f[2] - . - textsize 12 + if inv mod 2 <> 0 : swap f[1] f[2] + gtextsize 12 draw . -proc move_tile . . +proc move_tile . c = mouse_x div 25 r = mouse_y div 25 i = r * 4 + c + 1 @@ -77,9 +62,7 @@ proc move_tile . . . draw for i = 1 to 15 - if f[i] > f[i + 1] - return - . + if f[i] > f[i + 1] : return . done = 1 timer 0.5 @@ -87,7 +70,7 @@ proc move_tile . . on mouse_down if done = 0 move_tile - elif done = 3 + elif done = 3 and mouse_x > 75 and mouse_y > 75 init . . diff --git a/Task/15-puzzle-game/FuncSug/15-puzzle-game-1.funcsug b/Task/15-puzzle-game/FuncSug/15-puzzle-game-1.funcsug new file mode 100644 index 0000000000..9bbdbf9e3e --- /dev/null +++ b/Task/15-puzzle-game/FuncSug/15-puzzle-game-1.funcsug @@ -0,0 +1,33 @@ +#--------------- +# Prepare game +#--------------- +# 'import' imports from JavaScript code +var buttonList := import('buttonList') +var emptyButton := import('emptyButton') + +#--------------- +# Shuffle cards +#--------------- +repeat 100: + var adj := calljs getAdjacentButtons(emptyButton) + var button := calljs randomChoose(adj) + waitSeconds(0) + calljs exchange(button, emptyButton) + emptyButton := button + +#--------------- +# Play +#--------------- +while not (calljs isOrdered(buttonList)): + var adj := listToPar(calljs getAdjacentButtons(emptyButton)) + parallel(for button in adj, select 1): + select: + awaitClickBeep(button) + do: + calljs exchange(button, emptyButton) + emptyButton := button + +#---------- +# Success +#---------- +displayNewMessage('Congratulations! You succeeded!') diff --git a/Task/15-puzzle-game/FuncSug/15-puzzle-game-2.funcsug b/Task/15-puzzle-game/FuncSug/15-puzzle-game-2.funcsug new file mode 100644 index 0000000000..18dae3021f --- /dev/null +++ b/Task/15-puzzle-game/FuncSug/15-puzzle-game-2.funcsug @@ -0,0 +1,53 @@ +const $ = document.getElementById.bind(document) + +// Parameters +//------------ +const width = 4 +const height = 4 +const size = width*height-1 + +// Make cards +//------------ +const gameTable = $('gameTable') +gameTable.style.gridTemplateColumns = 'repeat(' + width + ', 60px)' +for (let i=0; i' + (i+1) + '' +} +gameTable.innerHTML += '' +const buttonList = document.querySelectorAll('#gameTable > button') +const emptyButton = $(''+size) + +// Utils functions +//----------------- +function idToXy(id) { + return [id%width, Math.floor(id/width)] +} + +function xyToId(x,y) { + return '' + (width*y + x) +} + +function getAdjacentButtons(button) { + const [x,y] = idToXy(button.id) + const inTheXFrame = n=>(0<=n && n (0<=n && n $(xyToId(coord[0],coord[1])) + const horizAdj = [x-1,x+1].filter(inTheXFrame).map(e=>[e,y]) + const verticAdj = [y-1,y+1].filter(inTheYFrame).map(e=>[x,e]) + return [...horizAdj, ...verticAdj].map( coordToButton ) +} + +function exchange(button, empty) { + empty.innerHTML = button.innerHTML + button.innerHTML = '' +} + +function randomChoose(array) { + const index = Math.floor(Math.random()*array.length) + return array[index] +} + +function isOrdered(buttonList) { + const isAtRightPlace = button=>(button.innerHTML=='' || button.innerHTML==(1*button.id+1)) + return Array.from(buttonList).every(isAtRightPlace) +} diff --git a/Task/15-puzzle-game/FuncSug/15-puzzle-game-3.funcsug b/Task/15-puzzle-game/FuncSug/15-puzzle-game-3.funcsug new file mode 100644 index 0000000000..fd210e543c --- /dev/null +++ b/Task/15-puzzle-game/FuncSug/15-puzzle-game-3.funcsug @@ -0,0 +1,13 @@ +#gameTable { + display: inline-grid; + row-gap: 10px; +} + +#gameTable > button { + width: 50px; + height: 50px; +} + +#gameTable > button:empty { + visibility: hidden; +} diff --git a/Task/15-puzzle-game/Jq/15-puzzle-game.jq b/Task/15-puzzle-game/Jq/15-puzzle-game.jq new file mode 100644 index 0000000000..6ae4fa4c93 --- /dev/null +++ b/Task/15-puzzle-game/Jq/15-puzzle-game.jq @@ -0,0 +1,93 @@ +include "MRG32k3a" {search: "."}; # see above + +# The following may be omitted if using the C implementation of jq +def _nwise($n): + def n: if length <= $n then . else .[0:$n] , (.[$n:] | n) end; + n; + +### Generic utilities + +def lpad($len): tostring | ($len - length) as $l | (" " * $l) + .; + +# tabular print +def tprint($columns; $width): + reduce _nwise($columns) as $row (""; + . + ($row|map(lpad($width)) | join(" ")) + "\n" ); + +def array_swap($i; $j): + if $j < $i then array_swap($j;$i) + elif $i == $j then . + else .[:$i] + [.[$j]] + .[$i+1:$j] + [.[$i]] + .[$j+1:] + end ; + +### Pre-requisite: MRG32k3a +# Input: an array to be shuffled +# Output: the shuffled array using a seed based on `now` +def shuffle: + { prng: (seed(now | tostring | sub("^.*[.]";"") | tonumber)), + array: . } + | knuthShuffle + | .array; + +### 15-Puzzle + +# Pretty-print the board +def pp: + .board | map(if . == 0 then "" end) | tprint(4;3); + +def row: ./4 | floor; +def col: . % 4; + +def move($p): + .zero as $zero + | (.board |= array_swap($zero; $p)) + | .zero = $p + | .n += 1 ; + +def SolvedBoard: [range(1;16), 0]; + +# Output: {goal, n, board, zero} +def init($easy): + SolvedBoard as $init + | { goal: $init, + n: 0, # number of moves so far + board: ($init | if $easy then array_swap(14;15) else shuffle end) + } + | .zero = (.board|index(0)) ; + +# If $m is a valid single-letter move, then emit the corresponding +# index of the proposed new position. +# Input must include .zero +def isValidMove($m): + if ($m == "u") then if (.zero|row) != 0 then .zero - 4 else false end + elif ($m == "d") then if (.zero|row) != 3 then .zero + 4 else false end + elif ($m == "r") then if (.zero|col) != 3 then .zero + 1 else false end + elif ($m == "l") then if (.zero|col) != 0 then .zero - 1 else false end + else false + end; + +def instructions: + "Please enter \"u\", \"d\", \"l\", or \"r\" to move the empty cell", + "up, down, left, or right. You can also enter \"q\" to quit.", + "Upper or lowercase is accepted and only the first character", + "is important, so for example you could enter `up` instead of `u`."; + +def play($easy): + def prompt: + pp, + if .board == .goal then "Congratulations. You solved the puzzle in \(.n) moves." + else + "Enter move #\(.n + 1) (u, d, l, r or q): ", + ( (limit(1;inputs)[:1]|ascii_downcase) as $m + | if $m == "q" then halt + else isValidMove($m) as $p + | if $p then move($p) | prompt + else "Invalid move.", prompt + end + end) + end; + + instructions, + (init($easy) | prompt); + +play(ARGS.named.easy) diff --git a/Task/15-puzzle-game/Julia/15-puzzle-game.julia b/Task/15-puzzle-game/Julia/15-puzzle-game.jl similarity index 100% rename from Task/15-puzzle-game/Julia/15-puzzle-game.julia rename to Task/15-puzzle-game/Julia/15-puzzle-game.jl diff --git a/Task/15-puzzle-game/Kotlin/15-puzzle-game.kotlin b/Task/15-puzzle-game/Kotlin/15-puzzle-game.kts similarity index 100% rename from Task/15-puzzle-game/Kotlin/15-puzzle-game.kotlin rename to Task/15-puzzle-game/Kotlin/15-puzzle-game.kts diff --git a/Task/15-puzzle-game/OCaml/15-puzzle-game.ocaml b/Task/15-puzzle-game/OCaml/15-puzzle-game.ml similarity index 100% rename from Task/15-puzzle-game/OCaml/15-puzzle-game.ocaml rename to Task/15-puzzle-game/OCaml/15-puzzle-game.ml diff --git a/Task/15-puzzle-game/PascalABC.NET/15-puzzle-game.pas b/Task/15-puzzle-game/PascalABC.NET/15-puzzle-game.pas new file mode 100644 index 0000000000..2d5275fb8f --- /dev/null +++ b/Task/15-puzzle-game/PascalABC.NET/15-puzzle-game.pas @@ -0,0 +1,178 @@ +// Игра в 15 PABCWork.NET\Samples\Games\15.pas +uses GraphABC,ABCObjects,ABCButtons; + +const +/// размер поля + n = 4; +/// размер фишки + sz = 100; +/// зазор между фишками + zz = 10; +/// отступ от левого и правого краев + x0 = 20; +/// отступ от верхнего и нижнего краев + y0 = 20; + +var + p: array [1..n,1..n] of SquareABC; + digits: array [1..n*n-1] of integer; + + MeshButton: ButtonABC; + StatusRect: RectangleABC; + + EmptyCellX,EmptyCellY: integer; + MovesCount: integer; + EndOfGame: boolean; // True если все фишки стоят на своих местах + +// Поменять местами две фишки +procedure Swap(var p,p1: SquareABC); +begin + PABCSystem.Swap(p,p1); + var i := p.Left; + p.Left := p1.Left; + p1.Left := i; + i := p.Top; + p.Top := p1.Top; + p1.Top := i; +end; + +// Определить, являются ли клетки соседями +function Neighbours(x1,y1,x2,y2: integer): boolean; +begin + Result := (Abs(x1-x2)=1) and (y1=y2) or (Abs(y1-y2)=1) and (x1=x2) +end; + +// Заполнить вспомогательный массив цифр +procedure FillDigitsArr; +begin + for var i:=1 to n*n-1 do + digits[i] := i; +end; + +// Перемешать вспомогательный массив цифр. Количество обменов должно быть четным +procedure MixDigitsArr; +var x: integer; +begin + for var i:=1 to n*n-1 do + begin + repeat + x := Random(15)+1; + until x<>i; + Swap(digits[i],digits[x]); + end; + if n mod 2=0 then + Swap(digits[1],digits[2]); // количество обменов должно быть четным +end; + +// Заполнить двумерный массив фишек. Вместо пустой ячейки - белая фишка с числом 0 +procedure Fill15ByDigitsArr; +begin + Swap(p[EmptyCellY,EmptyCellX],p[n,n]); // Переместить пустую фишку в правый нижний угол + EmptyCellX := n; + EmptyCellY := n; + var i := 1; + for var y:=1 to n do + for var x:=1 to n do + begin + if x*y=n*n then exit; + p[y,x].Number := digits[i]; + i += 1; + end; +end; + +// Перемешать массив фишек +procedure Mix15; +begin + MixDigitsArr; + Fill15ByDigitsArr; + MovesCount := 0; + EndOfGame := False; + StatusRect.Text := 'Количество ходов: '+IntToStr(MovesCount); + StatusRect.Color := RGB(200,200,255); +end; + +// Создать массив фишек +procedure Create15; +begin + EmptyCellX := n; + EmptyCellY := n; + for var x:=1 to n do + for var y:=1 to n do + begin + p[y,x] := new SquareABC(x0+(x-1)*(sz+zz),y0+(y-1)*(sz+zz),sz,clMoneyGreen); + p[y,x].BorderColor := clGreen; + p[y,x].BorderWidth := 2; + p[y,x].TextScale := 0.7; + end; + p[EmptyCellY,EmptyCellX].Color := clWhite; + p[EmptyCellY,EmptyCellX].BorderColor := clWhite; + FillDigitsArr; + MixDigitsArr; + Fill15ByDigitsArr; +end; + +// Проверить, все ли фишки стоят на своих местах +function IsSolution: boolean; +begin + Result:=True; + var i:=1; + for var y:=1 to n do + for var x:=1 to n do + begin + if p[y,x].Number<>i then + begin + Result:=False; + break; + end; + i += 1; + if i=n*n then i:=0; + end; +end; + +procedure MouseDown(x,y,mb: integer); +begin + if EndOfGame then // Если все фишки на своих местах, то не реагировать на мышь и ждать нажатия кнопки "Перемешать" + exit; + if ObjectUnderPoint(x,y)=nil then // Eсли мы щелкнули не на объекте, то не реагировать на мышь + exit; + var fx := (x-x0) div (sz+zz) + 1; // Вычислить координаты на доске для ячейки, на которой мы щелкнули мышью + var fy := (y-y0) div (sz+zz) + 1; + if (fx>n) or (fy>n) then + exit; + if Neighbours(fx,fy,EmptyCellX,EmptyCellY) then // Если ячейка соседствует с пустой, то поменять их местами + begin + Swap(p[EmptyCellY,EmptyCellX],p[fy,fx]); + EmptyCellX := fx; + EmptyCellY := fy; + Inc(MovesCount); + StatusRect.Text := 'Количество ходов: ' + MovesCount; + if IsSolution then + begin + StatusRect.Text := 'Победа! Сделано ходов: ' + MovesCount; + StatusRect.Color := RGB(255,200,200); + EndOfGame := True; + end + end; +end; + +begin + SetSmoothingOff; + Window.Title := 'Игра в 15'; + Window.IsFixedSize := True; + SetWindowSize(2*x0+(sz+zz)*n-zz,2*y0+(sz+zz)*n-zz+90); + + EndOfGame := False; + Create15; + + MeshButton := ButtonABC.Create((WindowWidth-200) div 2,2*y0+(sz+zz)*n-zz,200,'Перемешать',clLightGray); + MeshButton.OnClick := Mix15; + StatusRect := new RectangleABC(0,WindowHeight-40,WindowWidth,40,RGB(200,200,255)); + StatusRect.TextVisible := True; + StatusRect.Text := 'Количество ходов: '+IntToStr(MovesCount); + StatusRect.BorderWidth := 2; + StatusRect.BorderColor := RGB(80,80,255); + + MovesCount := 0; + + OnMouseDown := MouseDown; +end. diff --git a/Task/15-puzzle-game/PowerShell/15-puzzle-game.psh b/Task/15-puzzle-game/PowerShell/15-puzzle-game.ps1 similarity index 100% rename from Task/15-puzzle-game/PowerShell/15-puzzle-game.psh rename to Task/15-puzzle-game/PowerShell/15-puzzle-game.ps1 diff --git a/Task/15-puzzle-game/QBasic/15-puzzle-game.basic b/Task/15-puzzle-game/QBasic/15-puzzle-game.basic new file mode 100644 index 0000000000..14a9e86aef --- /dev/null +++ b/Task/15-puzzle-game/QBasic/15-puzzle-game.basic @@ -0,0 +1,133 @@ +DECLARE SUB printPuzzle () +DECLARE SUB buildBoard (level AS INTEGER) +DECLARE FUNCTION introAndLevel! () +DECLARE FUNCTION isMoveValid! (piece AS INTEGER, piecePos AS INTEGER, emptyPos AS INTEGER) +DECLARE FUNCTION piecePosition! (piece AS INTEGER) +DECLARE FUNCTION isPuzzleComplete! () + +DIM SHARED d(16) AS INTEGER +DIM SHARED dbp$(16) ' Board pieces +DIM SHARED sh(3) AS INTEGER +DIM level AS INTEGER, x AS INTEGER, y AS INTEGER, z AS INTEGER + +' Main Program +level = introAndLevel +buildBoard (level) +DO + printPuzzle + PRINT "To move a piece, enter its number (0 to quit): " + INPUT x + IF x = 0 THEN END + + WHILE isMoveValid(x, y, z) = 0 + PRINT "Wrong move." + printPuzzle + PRINT "To move a piece, enter its number (0 to quit): " + INPUT x + IF x = 0 THEN END + WEND + + d(z) = x + d(y) = 0 + CLS +LOOP UNTIL isPuzzleComplete +PRINT "YOU WON!" +END + +SUB buildBoard (level AS INTEGER) + ' Set pieces in correct order first + FOR p = 1 TO 15 + d(p) = p + NEXT p + d(16) = 0 ' 0 = empty piece/slot + z = 16 ' z = empty position + + PRINT + PRINT "Shuffling pieces"; + RANDOMIZE TIMER + FOR n = 1 TO sh(level) + PRINT "."; + DO + x = INT(RND * 4) + 1 + r = 0 + SELECT CASE x + CASE 1: r = z - 4 + CASE 2: r = z + 4 + CASE 3: IF (z - 1) MOD 4 <> 0 THEN r = z - 1 + CASE 4: IF z MOD 4 <> 0 THEN r = z + 1 + END SELECT + LOOP WHILE (r < 1) OR (r > 16) + d(z) = d(r) + z = r + d(z) = 0 + NEXT n + CLS +END SUB + +FUNCTION introAndLevel + CLS + sh(1) = 10 + sh(2) = 50 + sh(3) = 100 + PRINT "15 PUZZLE GAME": PRINT: PRINT + PRINT "Please enter level of difficulty," + DO + PRINT "1 (easy), 2 (medium) or 3 (hard): "; + INPUT level + LOOP WHILE (level < 1) OR (level > 3) + introAndLevel = level +END FUNCTION + +FUNCTION isMoveValid (piece AS INTEGER, piecePos AS INTEGER, emptyPos AS INTEGER) + mv = 0 + IF (piece >= 1) AND (piece <= 15) THEN + piecePos = piecePosition(piece) + emptyPos = piecePosition(0) + IF (piecePos - 4 = emptyPos) OR (piecePos + 4 = emptyPos) OR ((piecePos - 1 = emptyPos) AND (emptyPos MOD 4 <> 0)) OR ((piecePos + 1 = emptyPos) AND (piecePos MOD 4 <> 0)) THEN + mv = 1 + END IF + END IF + isMoveValid = mv +END FUNCTION + +FUNCTION isPuzzleComplete + pc = 0 + p = 1 + WHILE (p < 16) AND (d(p) = p) + p = p + 1 + WEND + IF p = 16 THEN pc = 1 + isPuzzleComplete = pc +END FUNCTION + +FUNCTION piecePosition (piece AS INTEGER) + p = 1 + WHILE d(p) <> piece + p = p + 1 + IF p > 16 THEN + PRINT "UH OH!" + STOP + END IF + WEND + piecePosition = p +END FUNCTION + +SUB printPuzzle + FOR p = 1 TO 16 + IF d(p) = 0 THEN + dbp$(p) = " " + ELSE + dbp$(p) = RIGHT$(" " + LTRIM$(STR$(d(p))), 3) + " " + END IF + NEXT p + + PRINT "+-----+-----+-----+-----+" + PRINT "|"; dbp$(1); "|"; dbp$(2); "|"; dbp$(3); "|"; dbp$(4); "|" + PRINT "+-----+-----+-----+-----+" + PRINT "|"; dbp$(5); "|"; dbp$(6); "|"; dbp$(7); "|"; dbp$(8); "|" + PRINT "+-----+-----+-----+-----+" + PRINT "|"; dbp$(9); "|"; dbp$(10); "|"; dbp$(11); "|"; dbp$(12); "|" + PRINT "+-----+-----+-----+-----+" + PRINT "|"; dbp$(13); "|"; dbp$(14); "|"; dbp$(15); "|"; dbp$(16); "|" + PRINT "+-----+-----+-----+-----+" +END SUB diff --git a/Task/15-puzzle-game/REBOL/15-puzzle-game.rebol b/Task/15-puzzle-game/Rebol/15-puzzle-game.rebol similarity index 100% rename from Task/15-puzzle-game/REBOL/15-puzzle-game.rebol rename to Task/15-puzzle-game/Rebol/15-puzzle-game.rebol diff --git a/Task/15-puzzle-game/Rust/15-puzzle-game.rust b/Task/15-puzzle-game/Rust/15-puzzle-game.rs similarity index 100% rename from Task/15-puzzle-game/Rust/15-puzzle-game.rust rename to Task/15-puzzle-game/Rust/15-puzzle-game.rs diff --git a/Task/15-puzzle-game/Scheme/15-puzzle-game.ss b/Task/15-puzzle-game/Scheme/15-puzzle-game.scm similarity index 100% rename from Task/15-puzzle-game/Scheme/15-puzzle-game.ss rename to Task/15-puzzle-game/Scheme/15-puzzle-game.scm diff --git a/Task/15-puzzle-game/VBScript/15-puzzle-game.vb b/Task/15-puzzle-game/VBScript/15-puzzle-game.vbs similarity index 100% rename from Task/15-puzzle-game/VBScript/15-puzzle-game.vb rename to Task/15-puzzle-game/VBScript/15-puzzle-game.vbs diff --git a/Task/15-puzzle-game/Zig/15-puzzle-game.zig b/Task/15-puzzle-game/Zig/15-puzzle-game.zig new file mode 100644 index 0000000000..431b73eab5 --- /dev/null +++ b/Task/15-puzzle-game/Zig/15-puzzle-game.zig @@ -0,0 +1,91 @@ +const std = @import("std"); +const stdout = std.io.getStdOut().writer(); + +const tokens = [16][]const u8{ " 1", " 2", " 3", " 4", " 5", " 6", " 7", " 8", " 9", "10", "11", "12", "13", "14", "15", " " }; + +const empty_token = 15; +var empty: u8 = empty_token; +var cells: [16]u8 = undefined; +var invalid: bool = false; + +const Move = enum { no, up, down, left, right }; + +fn showBoard() !void { + try stdout.writeAll("\n"); + + var solved = true; + var i: u8 = 0; + while (i < 16) : (i += 1) { + try stdout.print(" {s} ", .{tokens[cells[i]]}); + if ((i + 1) % 4 == 0) try stdout.writeAll("\n"); + if (i != cells[i]) solved = false; + } + + try stdout.writeAll("\n"); + + if (solved) { + try stdout.writeAll("\n\n** You did it! **\n\n"); + std.posix.exit(0); + } +} + +fn updateToken(move: Move) !void { + const newEmpty = switch (move) { + Move.up => if (empty / 4 < 3) empty + 4 else empty, + Move.down => if (empty / 4 > 0) empty - 4 else empty, + Move.left => if (empty % 4 < 3) empty + 1 else empty, + Move.right => if (empty % 4 > 0) empty - 1 else empty, + else => empty, + }; + + if (empty == newEmpty) { + invalid = true; + } else { + invalid = false; + cells[empty] = cells[newEmpty]; + cells[newEmpty] = empty_token; + empty = newEmpty; + } +} + +fn waitForMove() !Move { + const reader = std.io.getStdIn().reader(); + if (invalid) try stdout.writeAll("(invalid) "); + try stdout.writeAll("enter u/d/l/r or q: "); + const input = try reader.readBytesNoEof(2); + switch (std.ascii.toLower(input[0])) { + 'q' => std.posix.exit(0), + 'u' => return Move.up, + 'd' => return Move.down, + 'l' => return Move.left, + 'r' => return Move.right, + else => return Move.no, + } +} + +fn shuffle(moves: u8) !void { + var random = std.Random.DefaultPrng.init(@intCast(std.time.microTimestamp())); + const rand = random.random(); + var n: u8 = 0; + while (n < moves) { + const move: Move = rand.enumValue(Move); + try updateToken(move); + if (!invalid) n += 1; + } + invalid = false; +} + +pub fn main() !void { + var n: u8 = 0; + while (n < 16) : (n += 1) { + cells[n] = n; + } + + try shuffle(50); + try showBoard(); + + while (true) { + try updateToken(try waitForMove()); + try showBoard(); + } +} diff --git a/Task/15-puzzle-solver/Ada/15-puzzle-solver.ada b/Task/15-puzzle-solver/Ada/15-puzzle-solver.adb similarity index 100% rename from Task/15-puzzle-solver/Ada/15-puzzle-solver.ada rename to Task/15-puzzle-solver/Ada/15-puzzle-solver.adb diff --git a/Task/15-puzzle-solver/C-sharp/15-puzzle-solver.cs b/Task/15-puzzle-solver/C-sharp/15-puzzle-solver.cs index 16d2c2a882..591dbc1385 100644 --- a/Task/15-puzzle-solver/C-sharp/15-puzzle-solver.cs +++ b/Task/15-puzzle-solver/C-sharp/15-puzzle-solver.cs @@ -1,1466 +1,97 @@ -using System; -using System.IO; -using System.IO.Compression; -using System.Runtime.InteropServices; -using System.Text; +// Translated from C++ by Nigel Galloway -public static class Program +new FifteenSolver(8, 0xFE169B4C0A73D852).Solve(); + +class FifteenSolver { - public static void Main(string[] args) + readonly int[] RowIndex = [3, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3]; + readonly int[] ColIndex = [3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2]; + int n = 0, maxCost = 0; + readonly int[] Hole = new int[100]; + readonly char[] Move = new char[100]; + readonly int[] Cost = new int[100]; + readonly ulong[] State = new ulong[100]; + + bool Scan() { - byte[] t = new byte[] + if (Cost[n] < maxCost) + return Explore(); + + if (State[n] == 0x123456789ABCDEF0) { - 15, 14, 1, 6, - 9, 11, 4, 12, - 0, 10, 7, 3, - 13, 8, 5, 2, - }; + Console.WriteLine($"Solution found in {n} moves :"); - Ultimate.SolvePuzzle15(t); - } -} + for (var g = 1; g <= n; ++g) + Console.Write(Move[g]); -public static class NativeLibraryHelper -{ - [DllImport("kernel32.dll")] - public static extern IntPtr LoadLibrary(string DllToLoad); - - [DllImport("kernel32.dll")] - public static extern IntPtr GetProcAddress(IntPtr DllHandle, string ProcedureName); - - [DllImport("kernel32.dll")] - public static extern bool FreeLibrary(IntPtr DllHandle); - - public static T GetMethod(IntPtr DllHandle, string MethodName) where T : class - { - T Method = null; - - IntPtr MethodHandle = NativeLibraryHelper.GetProcAddress(DllHandle, MethodName); - if (MethodHandle != IntPtr.Zero) - { - Method = (T)((Object)Marshal.GetDelegateForFunctionPointer(MethodHandle, typeof(T))); - } - - return Method; - } -} - -public static class Ultimate -{ - [UnmanagedFunctionPointer(CallingConvention.StdCall)] - [return: MarshalAs(UnmanagedType.LPWStr)] - private delegate string GetSolverName(); - - [UnmanagedFunctionPointer(CallingConvention.StdCall)] - [return: MarshalAs(UnmanagedType.LPWStr)] - private delegate string CallSolver([In] [Out] byte[] Array, int Len); - - public static void SolvePuzzle15(byte[] t) - { - string LibPath = "Solver.dll"; - - byte[] ZipedData = Convert.FromBase64String(Data.ToString()); - byte[] UnzipedData = DecompressGZipArhive(new MemoryStream(ZipedData)); - File.WriteAllBytes(LibPath, UnzipedData); - - IntPtr DllHandle = NativeLibraryHelper.LoadLibrary(LibPath); - - GetSolverName GetSolverName = NativeLibraryHelper.GetMethod(DllHandle, "GetSolverName"); - Console.WriteLine("Hi! My name is {0}.", GetSolverName()); - Console.WriteLine(); - - Console.WriteLine("And I try solve puzzle15 with board:"); - for (int i = 0; i < t.Length; i += 4) Console.WriteLine("{0} {1} {2} {3}", t[i], t[i + 1], t[i + 2], t[i + 3]); - Console.WriteLine(); - - CallSolver SolveThis = NativeLibraryHelper.GetMethod(DllHandle, "SolvePuzzle15"); - - DateTime StartTime = DateTime.Now; - string Path = SolveThis(t, t.Length); - - if (!String.IsNullOrEmpty(Path)) - { - Path = Path.Trim(); - Console.WriteLine("Ready! Solution path is : {0}", Path); - Console.WriteLine("Moves {0} and Time: {1}", Path.Length, (DateTime.Now - StartTime).ToString()); Console.WriteLine(); - Console.WriteLine("Bye bye :)"); - } - else - { - Console.WriteLine("Sorry! I do know a solution :("); + return true; } - NativeLibraryHelper.FreeLibrary(DllHandle); - File.Delete(LibPath); + if (Cost[n] == maxCost) + return Explore(); - Console.ReadKey(); + return false; } - private static byte[] DecompressGZipArhive(Stream FStream) + bool Explore() { - if (FStream == null) return new byte[0]; - - FStream.Seek(0, SeekOrigin.Begin); - MemoryStream OutStream = new MemoryStream(); - - using (GZipStream DecompressedStream = new GZipStream(FStream, CompressionMode.Decompress)) - { - byte[] Buffer = new byte[1024]; - int CountReadingBytes = 0; - - while ((CountReadingBytes = DecompressedStream.Read(Buffer, 0, Buffer.Length)) > 0) - { - OutStream.Write(Buffer, 0, CountReadingBytes); - } - } - return OutStream.ToArray(); + if (Move[n] != 'u' && Hole[n] / 4 < 3) { Down(); ++n; if (Scan()) return true; --n; } + if (Move[n] != 'd' && Hole[n] / 4 > 0) { Up(); ++n; if (Scan()) return true; --n; } + if (Move[n] != 'l' && Hole[n] % 4 < 3) { Right(); ++n; if (Scan()) return true; --n; } + if (Move[n] != 'r' && Hole[n] % 4 > 0) { Left(); ++n; if (Scan()) return true; --n; } + return false; } - // no way make normal long string literal - private delegate StringBuilder AppendDelegate(string v); - private static StringBuilder Data = new StringBuilder(100000); - static Ultimate() + void Down() { - AppendDelegate a = Data.Append; - a("H4sICB6/w2MCAFBhc2NhbFNvbHZlci54ODYtNjQuZGxsAOxaZ3QbRRC+kyVHFg7nBAdCaDYYiKg21ab6ggR7cKL3HgJHDcWRqK"); - a("5RDDof4on26I/OAx79QTDVkmwcOTTboTgxxYQm+yimOcYU8c2eZORLaP/xi253dmdnZmdnZmd3EzgxJhQIguDEL5MRhHbB+qsV"); - a("/vmvGb/1t3hxfeHZojfL20X1zfKjzzl3UdnFdRedXTd/YdmC+RdeeFGw7IyzyupCF5ade2GZ77CjyhZedOZZO02f7qnI0jjcLw"); - a("hnXl00he6osNOW6zkKNozf7hC6thGE448RhJINBXzww1cUsnWHJTfBztzgIWcO4PPi3Tn8/AqKKS1POYVzqLzHKRw+RZgC4avd"); - a("8uC4Uzh9tvCf/8653ynMLvjr/p2CZ10eRIk5WwLdSZObilMmCKfvdOb84HzUoRfIDJy5JLNjCl4tyOxUR4jg6xGhE/QXo0ythV"); - a("e708UcD3O05irsgfIdlHa8MxYtQpWvhVDpXLc9EN8Djjya6m76xIBHLD0o7fKda/HdfTrXOQwJZfE68M7KzoOvUZbeHJR2+erO"); - a("uuCiBQLWhq8RcFBuuhbePOH/vyl/ma3PuNE5BT7RBh9pgw+2wfNs8F42eBcbvJ0N3tIGz7HBM22wxwY7bPDEDVPh723wiA1ebY"); - a("NX2eB+G7zcBidt8Is2+Bkb/KgNvs8G326Db7DBbTZ4sQ2+0gbX2eDzbPAZNvhEG3ykDT7YBs+zwXvZ4F1s8HY2eEsbPMcGz7TB"); - a("HhvssMET19vW3waP2ODVNniVDe63wcttcNIGv2iDn7HBj9rg+2zw7Tb4BhvcZoMX2+ArbXCdDT7PBp9hg0+0wUfa4INt8DwbvJ"); - a("cN3sUGb2eDt7TBc2zwTBvsscEOGzwRs62/DR6xwatt8Cob3G+Dl/8DnLTBL/4D/IwNftQG32eDb7fBN9jgNhu82AZfOQVuc213"); - a("h0OIuHZD3tEJmEXPrBhgeqrb1YIMRGS6a9XGTkGfVbqTU1B112Yo0qlMJsOi0/tucwhp9S1s8zRoLkbz8a6Nl4NUjv4xTH+Tuo"); - a("dYdFYZOlg0MJ5+/qrsoLJTcoh5+J9TT5zpp6SZHhpl+us+vZst84/zjEKNulb2ZMnEThOEqvjZ0WMzrf31e8ntGfzJ4bioGoFx"); - a("ZUHKLy0tLQosSCmJTxwv7IPBqrdHWbE6oK9Q9ZWsKIFZ+mqSTW/GGEA9KbdT2pVe7ytRQMtweh7N0oAQBoSIniVA1KnzgQSbVw"); - a("okymh6llVJp+9keVOzzWdI1ntzE0E5mi3TKIjlck7yl9+J7THjnOyFmkMAMMpJlx8sAPCnWWs8NA16TuzgFJjeyYU9i4TVByDv"); - a("0J+yCrn1TD/Ukr9K+X8s/NXcTH+MhbusrrPYve5sF8FgMDRlCDOcFfkNqh5n3j5pyfWoLypiYkpavBCZphIed0vXLkDjWHJacM"); - a("+xpBgsbnPOUDKpiIOFk+JY0hGUNAMt4bRD06nNMZZ0BqdbTU7e4gzoCSUx7ApVW5WC4KwYAwLjvW4l0xMaVcJD0wKt8cZSaYtm"); - a("kgdMwCGTBKfQD51Ky8+UNdcVMVRKIOGuGFjGDN+MIdU4egYMbN6Qqh+ZBilqHKXGcTSOonE8tALEtzDD7aAgSFsswRflbOcMab"); - a("ZvRi1rSRJDsPmKtYwQ8fZawKBfqxrqjDiRSqlS58FxfI5MUVsvtQ1QWy+1DWSoNSsJtQ5RaxptWUGobRQfiPKw0pImHkrLOBVS"); - a("+GwsuPTE6PBKmIsqJknf9fNJ13uQrtdjmeU5dXNVs/CII0/dXNVoc06qO6fqfXOqLkW3m7QN3UDhf2p6jqZpOW1osTxGdn2PZj"); - a("J1u4EK1/dsmlEJVDsbqi3J6tutGqUz0OZW9Zmhd0nbww2YF1d4dj2h2+Z8tVv6Tubpe4Tru5roV5LGqkljldQ2l9rKqG0utZVx"); - a("fWclodbZ1FqCNksQanLjMzP0qF3b52W1/R603WnznwkYep1AyEMZKl4Qs38B6cnEWGJasGosgRXxRUQWTuA3Io4lHMFizadTg4"); - a("NWZizhBAKHnbQqDHEivHp/lkgXhra3gGkACoLTYyrHcjPo4UfW2t/I6WYSWIbQT51sX9L+or3zVgjItaoux/FL4deL3wAGoxjC"); - a("L43fKH7joffNW6QtfBY+dIAB+KToQ7ZKYzgwRJ80fcgwMe5tUssJmUm1aLJ0YUrRU5p0eg8LfzIKGakanAfCJZp0cY+gSRdhsD"); - a("ehSUH83o+vGNqarh5WpM1Z0hY0/iKnm5Bz/Yh2Hlaz/LLPWTiV6ZRejrOoTxxlNclLv+nM5zc/x49zCR5BNHK85LG4GDpak0JT"); - a("OfYNm+U5XXGTq7X4M1IxsNfNvy9NEoyTBF91alLTck265Ds3Pv34mIBs82Jiv7+q39yE9Gubn5wYKSHcviFfUa+sJ/vSvvLerY"); - a("/BGdvi2bf2nFnfeL4FKmsGgptghqo3yenPk5Y6xXl7OR0hxMd4aLQq3ommYgfzpviw8L7n3oQjdNA1mikyHZki6aZ4Pjn0K7y/"); - a("cJQBoYDZMNDvnewXqV+0+YOeepH2YXbDqJRwZDhTe7+IMtsft/dfM0PvzW9j1/QB0aODUBaewfIxpCfSBOTBozbYUpc9vxhd2T"); - a("CuGf7xrenSy9oyp/ZLT5wyjn6rK1/+jZl+LgLW/BJVPxfB7JIyVb9iLtMvqWX6FQzrVOFmulxJ+yTK6h+kpksOx+eK03/wSU3y"); - a("xfTVKaJR5fpYtnLbPdnKvU9lK4/Es5Wne7OVF4b4dG4bRbHyhR/xxdoK4Qkx3C8gRBgbMwNyGZDLgFwG5DIglwG5DMhlzK/8Qb"); - a("qIRLmIi3IRRMGXi0IViGJVIIpVgShWBaJYFYhiVbKiXE+iDK5e+QgJk5lfTWo67thcBsmi++5cQRlK9wseGsceZMbhs5k+61y0"); - a("olqC6oVWtQzVRRw3kTbfzKUqp54GgkfxZEtPhcc3qDsknN7i0s3DaTFYFU4fHqwIp8uD24bT2wS3DKc3Cm5tbo/4IT2fcIUpDu"); - a("md5haAtZfOEswNtZj2kksw16eyQDALUeqvI5dwPb4LuLbGgx5j+rxyp5DpNSmz2h9VTZ9t5XEnTbEfanqYRdWKMn9V/MVKyhh/"); - a("/jmT4S3pb7/NZAxfRS0feHznZP7VvG/F9eQ0c9INv2Uymu7SAKavR113nY8q5ExvINhSNJu9aoarEqia7h83XHugpvt/Hfz0jp"); - a("ULx6UnjvnVMtMcP9naitKnQbJ8mvb+wyZy/fZ88Rd7R+4P8VW67k4eLGnv20K67lIAsvR8XNYRzj4pkYsS/vIeFeufGCpTixCb"); - a("EwwAkgeGwOlNsr4hZImmlN3fJ7fBmtRlPyh6v9K3WgmvHleiTo/pAQ9VL6JgTN0/wvExOkdKB6nVjPDWA94UOnlCHxWo6kdyBD"); - a("mfAAQKNFx+wQ1A8SaU8CfTlL7hgDel9H2iiD1mtU96fmPp+TmKdzCgrwq0DgY3D7T2NxSzZXGKasNdGNcu4jP8Yk4HSQfxVWp6"); - a("LusM6J1K36dK+NPxQLR4vUkILMyAPmBuS/MhP80jv57cTscxs8Si5abJEq33AWcJiK8rNa/XFSl9Q6DqNvdVliVgORlzN9qvIK"); - a("+I35yAdyCgJwMw5VkkcFFWYHNDLq0p5cv5elV80qiPyvnr66qeqG2rqpWWdrOa3saC2sh7VFejtSLTV6VLf8xkaiO7Zj0Tw3Pj"); - a("jztWPlo+hnspJ9Kt6m/7pKXb4LezsqBLWfAmlpsozgKE0icdtho1WIKsv4v8UQfv79Ee2tYfSZ8tI36KLHqYmDXRrenDoqUF6R"); - a("t/gPqbAPEREzRi77wRh6w9Yj5G+CM4Dx2F/kNz/emD0WzWrKOjCh1/L4MEjLMPiDp3iBRYsUE+RT751NP+1EYuXklLN5aWOryd"); - a("odlQgxhYEIf6efqXVsfh9J1aTB+wRZd8/2OtPcFSxBeGrZT/NaUfGIPUjqq43SuxzlTQiBKKawznX61lHxkZxI+d1vrQiF64Vi"); - a("B6oqjqg0BtmNldsCMLd4rkmWsG4KJmgaIjzf+E6W9pPI9QcRxtf/MN64+tWc0SIwVMf5+Fu0V2/vse8m9vL5hVRgoV/WfWmgm9"); - a("yfRRZBkwFtW7iom9qjeO08ImDJMXEzFzpkW3rTBSwDmHvxFZzXd136reQTkyh2SsJE1m5X1K0fsC0SNEHNaZ/inTP+KM1y0Tyc"); - a("Py5GH58gxYYmzGxYDezQ1ycsiRAmVSkB/qvgl4V/gjGxPzw0kQu39gYitg3QGqrKKNyvEdHbm/Qw+l5gyRBPcNBTL3N2XFkFqU"); - a("jJQW5PmLPZ7rgXFNn36y4aAtdGEu0QA5nDrI4hrdcjuVWswXESbH/ylNn6onIQ1cvqEwUBW34rHYWEgnDFhKPyyvSKnpa3Ch05"); - a("zNIW9foCbRUJytYzCnrUYPhrkfnjN3ueUTKlSxJ73F6FrbgLQ0EU7PD4/PWeTm1TLTEUlxD7FQfJFJOuFxsb7Sp8fJImPYtcE2"); - a("jmVFzJXU6KzwtQ7hoLZiz4GRYhEL6QR20yotlmO0zv3q7sxa8nSLJe0zUK5Ff6t10e+c1F+kpGW15ddMlPmBM50Yt1PP+c8DFU"); - a("OIuDkboAiHmKXo42QGd/yKo+HSQlYz0HAQSjIObzJH+9qKMhGUr4HcanQJBxT9uxep08oYXplAD+JNGbekifRCwLEYcSxDwjBp"); - a("h/9Bnpf+hTxrfv8reXa0yfPhz/9GHpgzMxxwgzJjl4BRoiRGymSjmukVFbLe6YOM0pODBOk/+Mv7FenJVQSUI2OYAJDkwFh5hk"); - a("lPrmGJb8rKx2TaXJtV8T1ZX8W/SUX8nsiXx1VxgCXMsvJBJg4QHxBUxV6mi1LHkW5Z6qh1i73heK2my27/kp7gpswQaeDWRDC0"); - a("PkEi4uO5blHQ+FqX2OaUiz9Mf0/qcO3XhuSsY9ZFcNKzfVFniSbXpOpdWtWgeYgqdfQoUkccWQRrr7nu02r8W19ZM4zLk/1Vcb"); - a("mGwCV1JNn58ZkBYKlinGEAspOgS2vpBPeWX6qERpf2UpUQQ08nu41nyWzNz+TZ1NB+tmb9KWvSLDHhUBJpEE7yIPytQ0OE2xnJ"); - a("rnp+fDauVlt1h3Cw4XQwvfBgw+fAEeRAN1VKUCkZvkjkuQocmw475/dhxPSjMMK6TMNq88sYqs2lWgnVKsFBuk4XBIj6rYi8eh"); - a("mzWHm4TkBa6ji6olLs1cBBa6mvQC4c3OtPtE9BX41CoujR2CefFsm+qtNvkt0iRa6GoFTWkqDDz4ILH9mLka5HuGTFkGJ9oJS4"); - a("OcpjQIGeltH+hi1L05fxk1uW2UP6X8u055+UmyyZSqbKVLMumcytWr60GLxNDPyWtjwWiofLhBP9853oOwF9bU7HEpwimPQqtp"); - a("lC6Dpm30jy4z/cqfd3cuC7yjJUvDKXF89VolD1B6t58XgtL55jvHjlcBSarL+t6e9rkrfXp7/ODH8l01vPQQeq1aheTDgtmQGh"); - a("0al1DAia3JIRm5umaXIHkoeNNX9rpqFQ81dlzOnUlYH9UZegr4JuCq7B4cIoRmKCKY1dDcBnnLkYl4a7f01ADfKCw76zSECMN8"); - a("1tZawGrg5RvOPtRdNroPmbQ2gAzVdodM2w5pPUYaYvbP5emtF6OWRra23Ct6JZutkfl55vbQSQSDu3zkwT6FyD8xjHymU9ksDK"); - a("4dn+CH6IL+jH2UdraRiHsbTew++2GkZRvZm2Af+tAgy23qctg+mKAhVziWp9Ra3mw7eaRf23Zm39ZlKZry2AO1quMrpAfxYngi"); - a("VxqXUrp8AHVws5Gnw4w/dMTuqCisp/IHWbC8eDwQKMhKyZaZasXHObQ7V3tOLoNiB1FC+mr2+xQ0yF407ob1lMWurHTRC/HvEm"); - a("EUD4/EJVXIC5WKJmDJ3CV+p4PY/vdwXguwAfxKfJMSf//ZhXaMzOWVnhLJswA7p+Mff/YlhRLylfe2k9wdwW0x7FamKZ4Imv9I"); - a("ZcfN9o3x8fBgtAVtviHxcFBg5sxVmjiGGuDCiH47tpXiycgd++nZn6zbTWeNNs4gPSQwzNKNPaMv8AzimHSR3HjMvtnVnx3nLQ"); - a("GiZY9JgUomf6NOxOEBSIoZl2AmapGvWngEmPJUP+yp70fOxd3Zg5SRRIszUr8S40pKwYBs6tSK6J/jfrccvrgvBoAek0bCvqxg"); - a("pA3HRunPySldPhLGciIwWdU3B52qOWr0RGau7N80lEbYZ3JiYux3lSc3E1pDBW0VcoK0zp+UCXL3Ly9FsxjJX3YRh01QUz3ffT"); - a("TMNGQH2LDgcI+6d0qTUrG104ZYcep2Y1eoJIYnThCNi0AZqlmxNWfibrKfN0LebXl+NVydzfpyfAXhZTct9IHntZf92vd/v0lf"); - a("KKb3yR73BSPKVrXkTd7Faf3ucrT4CIJYidV6PLj3vPR7UYiuC2aO3mgRerQ2e4plloCMcdpDrq6/a5bkOOp+0d6mrYnFQu+jg9"); - a("9ELXpGh/EVRK+Tc56WF5bqkZpH042qRTgccAbIcsCq68bhcrdFneGuL5sebbe2FXw2Z8rf1Sx5v5jN9wc8axtb34bzgjmaSe6n"); - a("Uzf0GkZzArdBtW6Das0G1YoduwQrdhhW6Dh24rvbfyWdhrcQUEjUsd/bK3V0bte2k7/E5wNYQdwvdM2iGuQfGNG0odvejBlfLO"); - a("iSsdwWlYWNrHgU9k3J1554l78L4Ik25AShjCJf9ZA6q+EEYaSjOcM3iamMS031KNhZUI7GdVa7K0tAEhcyxE4Xzc9FA0j4uox0"); - a("meF8jEvAkI+RmBsrcLAf0TCuifQLLPsL/4xaEACaKvTLMfaGt6VRR419ZZjxwFh24WLS5QsENkU+xTvwamX/yC7GAs6MOn0UNo"); - a("3c6C7U13trYjNpJuys/MrbQYuHdLHe+LtCb8mIFLiffntZVuh8MVT0xgUE2rmIHJG5i8gckbmLyByRuYPNf6uvZfrBDtv5fzoq"); - a("EZWotAazFoDT4aukfVGx62NHdMXIUDRd4GOdLcwmpSXy0+AQYLOhwu0K4ZpxyPqffI0p3LaHdcs1KL5YyxB4bYS9HGwNvux24e"); - a("bp7Savzt9dNAw99uuqh4CtPsgvqtf5osxqGDX0WcAVHGSRe0CjzeepOIrwR5E7jD1GpWaZK6SmsdpL1cHIhhTYhXHAeC9FPfQd"); - a("tYFurdNrsqKX7BYxwTx8o44LsrsivTZQJX/ChWuyQTXD+H0+107GgW50FlGq0M5vp1YylWqxDnbfS+Rb0Rp2cKaiVHzU5jBjre"); - a("gwToKNnJ6sA2Z1ZoMen5JAg5C8+OskofRhPSvEixQEj4JIlEzbuNhfi+09RPaoLT8N2GZuX961nxq9lvRvis4DN5kvk5bT9NNE"); - a("8sTDQP2p7jIB63Sx3+p7yc2dw8ZoRHzErymLVYzLQYYuhT4WFRa+2pr9ReymTono4n/cgXpaU+V+/Z0cPzJluanWzNyqaV2Fwt"); - a("mzRgkwZs0oBNGrBJAzZpwCZzBm235zLLng+38snjrXzydCufPMfKJy+28snLeQHylnm3B/Quf+RNnkzCNGHLtZrRkLPte7r9cS"); - a("RXDwuYJjRxD6XW3XDbBjc2bORI5kEI+tUNMrZOQI2zVCBVw/6eIrNPf/wxTV7gvpDdEaqpgzvDLgU8MoO4CBxSsNuiEloPOeoY"); - a("MlNYyJba3qdUN5bCR0LVlgjVSI1k/X3Tje9HlMxiZMN0OkLxY4E/YhZCtAjfwSNwtHsa3KjdQz2I79UUTyi5OiYG6B7Qi5FD+S"); - a("O87VaY4mvAeE9MUnZLk01Cpnsws42wqBFCF1Oo3SqmyE/FJKgks7ES8qQoakvXliJrwXCpY7k3BUOF6Q4g3KoDNMcCTVzFMEjR"); - a("yU3bVX11uuibP910B5tBt5NB88npyaynzklnbRom/HVwg6wxtpMJa1bcRP7X5n8Y55FTzLk5k6ObsUQON1JckvWvTu6i33CfHm"); - a("vqN6uAD7ZPwSUduSEkB4Y41jnkbXwzjTuuS2wFOoDYWe9Y8CXE9om/Q26+HlDUki/RkRsBx7QiAxQegcK3+wtNHBPJEpxJBAtC"); - a("ES1mTVYztwPtfBej0MSnW+rOk71lYYwzwYNXU59ZnX2HmDpvGkk8EdT+YuTbKG+FmNv+lZi3ZsU8/wvuA/Ajsc2PNbdc1LBc1L"); - a("Bc1LBc1LBc1LBcFBHA7u15+/1Q7v9HkRu3nVKpIX31GyWaX3fjMaantm03z5LBkFLb/LszdIACU2Th4QJsDispv9yFGprrPb+7"); - a("67aVUQ0PY3GHeajtCa6HJHHlvOZ95hQFR6gh5KxdWhQDIZe0+F7Kt6x662LUlwxKS66kNj/dWINqj2aoHuTon4g4mJ2OnspBc4"); - a("b1rt4yIgoQbXnbph5CpGyTxECy2eBcMhj8COLuYh5g7qRl38lJIJpKs9Mj8nIfj2dRiYyh4QTlKW5zQ+iVODf1dzvQskzADNpF"); - a("So/s/29rbf3FoL8Udv5e6HAAO/8Qdv60mtUnLn+QqPvaQpX0/1iW3773Io+/qsdf9bX+tqkpdAu98yHnLlz86tBMZc1qVexnfa"); - a("twxbgZPV+dmyR85k3obystE3ysm8bq75o7qHrfnyPZmk9wWMiOlJGN66lz44Qve5PA5jETmziStk5KFXnIvFsgxSBeLxkLzqRk"); - a("K1QMu+12FqL1ZSv9km6OR3gq20kHc35pRcNBya8PcyInciJi1yTmIO2qhFmQxZT1nzlmZRaT+qFRZFdQlwF1GVCXAXXZNPyX9s"); - a("kwPdgolipE9w/9Zo0svZIIufj9dnmcHy3Ojffh6I27umLMMJl9lp+17+UOwbd38eI6XGJQMhDzw1Qk1CeKhAa0vVgEe4TRrzDV"); - a("nN2QnZE57uDTl/PXgjWr8U6gr9AHzo970OZN0rUdft8zcTRSKsr6SlPKNvXj3aLbyTXZ3/SsDC3aLSm335LfYooRmFAM07wVJn"); - a("QPTOhhmNBT2F3brWm/H9BfU/UAaawSx9LPrJjw4gYUGI5cDQp0QZPJhFwdG/MrWISScLVQL/Ga4aZDqr83+4ZHVatdwE7H9ASd"); - a("WGMydIenmz/fRRTYFebb7qEh0pO9uOhXojLu4ZMR36xP1/2E0kfnzed8OrGLG6F4oPXrYGG4m/ZlVBv2D3e7WDjjbijscPNX6g"); - a("XdzDuOGwuq1IxL6hraA0r035Ff+bwTei/FQ/NMJDe8cpLh7xW7zVl8fUCVhREL0YlT46eVKMPjrvo0fwVVvWlQ9elpGmf4Uzh7"); - a("boIiPO5sXI8jULsWA4EUyebz/u6nS8pb0VM1eLY/epkD5Hw1ow1FkAQWXSfGlAXdzfWuT3av28aqra5ZtL6y4D16JGmGPkRzOt"); - a("ohyepKfsiPhX8RQ4dkUStDsrlBdn/w6aNcXhkTQB3dn9YER1CTlqI5HEfj96TgrADu3DwnVYSKWjPUuAHdA3kI8A7J4rKYT/8i"); - a("pgLHgJEgF/jtczwPfgelS9GX8ywi5MSV8zTQPjt6/C+tg/WlZ0eP+D17qW/4ByhhNees1bYjW0BJkd5J5W0yNwllDQgmKftMEB"); - a("Zln0hV1QV/ed+8NrZDWtqX5eDHWJzTSrXYn22VaJPDy0RMtH4Yj6nHiT4ILtf01h8k6+/JeG6j/UDmClqYEvkyh0r+HL8TpwmW"); - a("PdBu29GuT7Oc3Wj314w2vRaDPeE1J7Tln2N2tOQoyZejDG3YG75hBrzUgJca8FIDXmrASw14qQEvXWt/kOl0L3Q7BLlb8DTX4K"); - a("IJT530buix4ouCzQeyzQjULK/fyA9uB+LVb4YcnigKfoZvWfCj4Ae8uQ2tzRPb120uN49sHyzF1xGaqcWwUxEJcxrslyogpdYs"); - a("l64lG5YxDsOaJyqkxRHAzSMVwS2aR8TgdvSpah7xBKubR+YG12seKZNaNb4XQ8wSojN8HEDQBOzgDA7mfW5e30+LWXwad1PwqG"); - a("oZCckdnjg+OC08cXnQEZoDTAdRw1zXnzrf7FgPyde8z4zK4AjpZK33f7j961bIC1R9VjWGZ1j+kkSX7RXpB3Dfreh+cJ2m7I3i"); - a("2rtFLi9o+oXmfabhnlMx/ALDwkrXhdHHcgd+dFZKrRejSVnmB0yXnHwsaKkgb/1Hh6p+tua75vqKMk9oI2kpOLIXcm/n2GaHX+"); - a("NP5UmCh18gPwffgNBWLC3pkZY8R1yGK6XFJ/FK0aUbNg+7645oHnZdWtY8vEndQVTbzqylMWBaLIWHK+VIytwVMky2Ib/akxo3"); - a("12L5bcdRmwf6PArtT5XE8NzGxUZofguP7b69oKFFdJZOUfbgRTr0fZ1LrUkt8kCJwzy3ilEvE99Swn4BayEpe4N6dG9MJacQRf"); - a("8RU68Qgi5lzQdajNdDMtdGcC+GkFa/G8PVZXB9/i3F1xGcY5Yp0qtdit5lbkS2KHXw+npUX0BVDZchQzH+MJ/7bw78PRzWTx7g"); - a("wVNyQFL7AlKgt2rQ+q+tSdE8JPf/sMXatl1qq7uDOwF3QA6b8+XwL3MWOXco47790WRLYW3zN2gDaqgUvHOEGJ7mlZpVTc/j01"); - a("jCDaHlC/oy76hZGPCmVD2OZ/W8fCP3Jq7SSdaYqSK5EhPpk/vwgGm5ed77efSIja33zq9PIkuDooSgnxk+Mie8IAIvB5QIOUAz"); - a("ZmXSBYKml1jgslqHiLGozuYN3dwmeTXvFfkoS7hwjRCEVCKLHp9my8CA2F7lFuo3oTHRQ/7g7DrAm6qi8EvTphMTaauIiqhVW2"); - a("dxEmtHsMX3NEHcuP0cce/E2aVFbXxG87n93Ip7T9xSCi24KM4qqJWqvBpHnBQpjf859+UtUxx+n80b995z7rnnnHvWfRRoHR+n"); - a("0/BiiimgNvdIHstWIeLM/8PCEfS6KCU1F6GpnNKOxRgGbGd9D4xauWaXyFbYPxF7K5U7WlNSawkKYFLaNuiHsQh0kO0as87Hft"); - a("7hvU31Yw4LxUVKe23T7Ocd7nHa1wIDEYZcYjkFoVlPQyR4zFMmSRI0dQqmKAObhXu4VhqhEIoNaC9tRu9xDRrkhlRlGEnuRsry"); - a("4Vm6/Lw/3eIARwBTcZqtFk6w6a/AoYHD9DqZJdBhCPnBqHwXqGrhWthnhai+y1nphiySPw+zpCy8g0uKoq5QOx2nYfCQZDysbv"); - a("r5twAOA3Y5VaB40H8wWQxFqJ1UJknUNUZBgMh47l2m7WTre6/e9wusj9n3Z60qa99fe619T6K+aEE5OMYXRki4ydv4bbjJ/1uU"); - a("omcLIihWXd3knfuOEktRav/AUSqocoHohGspXlLM8B10HzpV6FfgIZ6j9fP0/AD9eWwYXSK5stoA0iM0kUJLcavEFio19dHTZf"); - a("9owHtjz77xsu0wACxV7SCkWshv2TqI4PtkRfWCg+kYy7g/V7tR6Yaen055X9thBGCWkUqLN7k4KI9XIAIAcON30Vi0dFPLZ6hl"); - a("zR7RwyyAvisyetvgXG+Fs3ANsflRYnhRL0RtzqI2UxajwRw0SB5iGfYGDJulx15Gj/PQYwysNzSwDqERBoQ/+2FT9TxtdLwk6S"); - a("r22MAxzmoy53mjlDZjoi5/TRNNscuaXz5H+CcJiOCtMge0T3oY/gl8kyiCTi2wzEMQyUP6grCowerv/P08EgwzOmk0HlI1AMyf"); - a("A+ZD+7hFvgX5BYrsgtOKIRnaIKnFpn7KLBfr+p8sQOWET2T/IYuaizEWarP26pMimnJCr1zTtKi1VB/2KBo2lcN8hdhjfxjGGw"); - a("lYKbN5eUIrXmjl85ZB5vOj+xvmumgolYKJJfO1PNQA6aJZzj1pT9OWLLD2DQzq8gWjdH+XGl3kf897zYmcSns30PGDC/YO4b0Q"); - a("Ay/EwITxfClShzsDzF2+DBhDDk+3wfh8BWBA+H6NeBqq00lPotH/Y9tjwAVxde8V10lCa2Lez2MBoZsa/Wuag/Bczk4bdHPA35"); - a("rvQoBf1sVLvy9cRexxGpqkmCkewVCAk2zrBhydrHlUx6OGUoaKROsB6MimfhlP0+Wh393S0MUQZ30ZC7Cm0X70z2jmxtgoVm2A"); - a("nA/v7JPxANQ20KAXNb5oPi0y+ujzaBxrHqCc6FIQnUB4yCrqKCi+gARtILYqWYAxCP+3+Xc0WqxPogHvRfsccKKhb6a8r4YW+X"); - a("9u3h4e3llWeCHAA6fNUHPnhah9CO3hwaASoW2AhiQxfsfD7hHufcF4xUS1BainmxUd9QY73rvOJ8VWYVVwgB+M7+2Cr0aqeRQK"); - a("XHEtZ7x/MugP6f6YpHuyV+J779xD+gNPuzQf7nkbXbkqneYtatIIb1EQNkgph/ghpSqkVIWUqpBSx3blPH9Yt4FdDZj779MQ/j"); - a("4Ifz+EfwDCr0H4UzA4sblB3BcY5ykxC1D6YyDk1OpXLPNe24MmaP4NuGOAokuWfe/8Lq5HWZgsBL+rO3z9pZtafk+b3UXj0Auv"); - a("bHK8t73989ze/32kQN+ydgQm2MdpjSqR3SXq9nnoF6Hyfhr1+l6iFe2Lx2nJauxJTIG9QAEKwVoZhIvhPsVWt0BYBMf9olsEb4"); - a("4yubGyoIsaHQC5NZBbD+7Y7aX3UA8NLorm9XiQqBIWlwnBjyB+EGUzh7qAnbaqJ53unGTWejrtC4sJBvR7w5RU3wDz1nRabjOP"); - a("dEiv0CG1t30BdKmEGvYY+IwosgGCHyHkVjeV1VIqWSYr6HIARQvv3E+I154vyRwfsO8hgJ+pzW7oNKGX6dDLtMfetMLelGBjVA"); - a("DlOhTtDjfR1505cxoCKRs6q024e2XgTiaojnpwk93AWHnt9SKOUS7zjqq7Y9ppS2ge3ebyVxFI5EKCVs4z9O2aN2x8dMbnOt+p"); - a("G+h8ctpCrsvNbLG3F1tsafsO65QXdG8B0lEN8pKCvAyLCSBBRsbg1U3VsM+rMrPYSoFf6xJT0R58j+cAVysdLVHiR1W4knn8Y8"); - a("7qoBwxqxmELRmWlEW1yNOWYl4LxLy2unG5myUPAMTUtOsXZOb1Ec2ru0j3N4C2CrRVoK0CbdUoJc6iL85Cpp73jJNwYSqOsc9f"); - a("f+A4r2yeU74fI2BqPNotYthhKLlXhtaCa7YGcvTGeFCOB0GIqaGXafdC1JEk6sBhPkTcBwISm5WjTauP36uAs/FiJi3L707GKW"); - a("eR2Xfym3By/F9EC6ekh+aL86kwmfPIDltP7u1l9/9R8Ry+Tl+BCKfb9NTtr9nWoWSZm3XRnIIsOu3s12y8OPAZ67RvonthvQBY"); - a("zNS6e8D9kauohJMCrhU00c2grAiXXRfR1HoRe9EfnD/KD6CVx2Jdp34R0tYIKlJQdEOOodQhDkBCkcfF6h7yTBx+xGOv2ua7Ce"); - a("ZArgdp2tgsbegNwMA1uZmu6FF8pU1gE5eKjX8M4i0AxveZQBXksv+D5s0gBJO9116ZOanRJaMglo6ALB2WEQM8V/jd5SHdq0bs"); - a("H8N5EslZhOYxKUITjwmQejA53Q1aODZNw72p4RFtZR28JujdvzfonYEg/XrcWjuri2VEuxLj8PAYmrq6hnvENGIXDScLqMWJaP"); - a("EP+pLUnnrOMLXu+UkshlocjE93kT+Uy5AuHEYjgeM+Gq3aOJ4A+rgtStH4z4wHqBtRSIDPs7uYtpEi7bI0czp40zwckoW/g7He"); - a("UOyd0JQfUAbswlK35CIHnrBxmX+guRCuyzY4MNo63voGYXtEdmgn2SUY+0r7CZlneGxE2S2Rt6wLxr6jnaUS29F+OOUCmoViJ6"); - a("Fyb7oGDmniCW4PSgRj243Fk058EQZkURDgAUhwRoguWsSBLIhCBm3kzk/hh5/oD9uGbd2rekPx49Iz4mfkpJN7ZuKTC1yBq5uk"); - a("Pd3RCqvUYSqE7udQmqRUcGDzWzpzhvYLXUH/ypZeXIMyznngTKVC5xZmKJwUEbYzIl3NtWg/Ix7MSZtKyz+/eSsFUUqBB5gysG"); - a("dhNB+6rFuP7aJF20pc0zlNZ/0+pFscl5qSttJAruWjHzi+5ZEgwNhl8JIkhmt/tGNW0YKluH6Zptf6nUVJzOF6fppHFn/waVFv"); - a("LOC+oPFPH6kjFbljFFfIvW6h5lEQJ44DxCXmR8BGXgzVhKg6nq/VfsBGhxy/id7SvrbxKn6im7w75JKcCTAqgxGKekx7CNwcVL"); - a("cER0byQipK4xT/b95r6Dg2eNZ77aW4YG1GB+xZZ782Qvw3gCgg0iot48Sl0Ai9xvPm3ehUj35bpSsMDkWX1UGGMxGB9iFyy/sV"); - a("CPgLSagDMuqr/hTWj3b/n9kUhPP7H9+b2+i/zi8vUWIfBi2fNLEZ3lQWcY6Lp9+W/4aL9yoFZ4lt9q3/1xbgfz75XjRR6wCY4g"); - a("RCjaYwAP/J3hcX1YpaUqF95DK3M2GDIF+g3f2Cvp/V8n7mw3fgkjuTXn5QNO9x+Ndni/Y9Yu/YbeADtll+JxOFcCCG2CSH59K6"); - a("pRyLVEwm2Bnq5yCYGkR+S0RPdv3O6YFgvSxxlg8RfcNCUQe09nDrflpe7KF7iEvugvZCcQTjJXtYwd2wUoCjIFfvEMc7oQLpSy"); - a("ta/3e6O7YZ+HXdiW7TPyBzGvKjc0t0mHqWGsoBXEYFXtqZ0D+mX5Cd/yn8oosfRsPmQgNWYEDcZazYj4RERHwAosR4T7r8FRA/"); - a("4WRR8lI8YTWgJfMRmZnxvlviVHp3dv/xmCGTf8f+/k449rHBrE2wgScBCcQSengIFZYFUZGE8zoMl/TSVTlYj7bG2DkaU/aKbB"); - a("/Tce4XAlRjJw551CDqcAPBy+yv/h7v7MulLPZa8lmb/XLUUje1+T0cS6FMzWJfdz9rs9V2RTuqdSwmgy2SB0M16QahMb1oKWAK"); - a("e6dQn0KyWGg47QswiH3LMPIP2gp8f4i9Ve3ld0hX59QD/b/HmzOZsvbadnIJIpvEPpuyWHvhBd3woc1qH+3BNK1tso4YeymWaq"); - a("ZHmE11exvpik2FfbN0MDYhk4/IpZe4zE3maSdiBDMXUW2eZ8xQmmgc2SbRXrv6QEKjCByr1QOLZIncsV0u3U0BMMGXZibC5H8x"); - a("gB8NmeVUZUReOqRtyntGj/AY8bQBTzU6Q6xgGmgK4XtrLjVxniTOzp9vfPvP/KmLUZfBoj1uSbjrGfhCR/h74LL3ZNTB7EHSJ1"); - a("1g47yqJegQPwSBgru/whXV9ws1kfpJ1wsnZ+deJ/+aHr7Mwd52YI/UHMltQRM2txFl6fdke9WDD9eGY8MoXTb5eMunbfx543ts"); - a("h/8EFysU+4qyG5D5dPnaAfjn63IInPpFYPIt65ZVwES3qlCvcQgpkXfXCOmx5zRuecomUwUClxXYKy1B7WkriIKrkUyGfkmXnw"); - a("7MoFOd+si0p01sZunKrAbtMaAlFrDjK2zPCDWozcSuQ5iWCqUHFiKUr6ZNJ+E0r8fKd3lnNwt/D+bE7FMpv1tbMJMYvlIRdnF+"); - a("k9qAhSHjltY8SGoCMqhoW4ywDDbgKbXzqAeCl9iopG/kjsHhpYSh9jzEqIBaXjtiUf8O/MJMDhFlCYsRw7FqvbVTXv1vRfMQdN"); - a("g1oQjONrEm29FAwz8vAtMRp2cIAU16kx0KizthrofwFtm2GpR0T9FHW/2RnBnxwE0mWi2fAVpF95A7dszF7sy6aJYH7pb2Wx06"); - a("+bsvKMVjXUXR1GtZ6XV4codOQ38ar5jH6xYOnFUiA45HZKT5h1vzsNLJ8r+/Q8Es4DIPfKZd+RytDQHcnoefpGPhRu0v413BeJ"); - a("fRMEtXxi4aSQivbxRGnZ1zeDW0K+eN9b2LdnhpHq6/6mYzvmO1O0LZwN/ecku8xRa/bdtizf3g/Wft+8EvU9e5HxiqfqJQ9QfV"); - a("Gqp+mu7KzvI5UtQiK33xW/asdI41K830GGM/+E/56cG5Zn56w9r/l59+c66DzOvWnw1fGfpTOAekPOtM5WnEMFY+atOdsxZn1Z"); - a("2HL8+iO7Pryw1cY+jLO//Ipi9PftSmL/sXZdOX4z+36csPlmXRlw79ZZqTIPo06BKhs4SHa+qbi7B1ZNtOs41n1WM+7O0OLWgO"); - a("uqVt0LHHGy8KCYq5kOAL1s009py1jl3emW+328BEJJ+u9m+jKF2O0P3RUl0vz6aHP4gaJxtPKLG1aAeSIPAJfR89QPavotTzfv"); - a("Gy7QmR7XJE3nkTeHf0wRh3KeyQUIxmqtU/hUGp8sp4F0ICF29IcW1BL9kBramJ7pEZbrkrS2sYS789yQ4Awif6NjWIB8l6wU69"); - a("MBszA9yOAWwNX0HDbPDvw3NBPjMz7LSPdgQ7/uf8T8iS/oGPDKGyJn1aAxQZeuFXIVF2Pm97yCZnqYVuiXw9dEC+hZyrdPmJ/W"); - a("6RjzG1twgQuuiLBHly/FhXAnLBc/yFA7yvPAHKoUpQrvqMaBAvOYb8nzlP67ZXcXpdORvH/riTvj8KCbEGVhxb4zdznVujPf7X"); - a("l9EGqzgO8Qfrwxp9i5T/pM7uIVLrhq9wEK5ssdH398BbqmA5ePxERD7P2wC1bZO9V96CTiAKnngvV43vLuRNtcVD3Ymhs/X9c9"); - a("lqIyTqtjryrQHrA7F7plrzENNKlto8URRTgRDgUeygILsIlDY9DvISO46sNiKlbnnpt7J7l3CvR0xLxErRph9txLbxD/YmIjns"); - a("FUwLJzJ0iexuCaN6eS69iKHqYkPi/spjIpJKkM7iBjVKbASMaVeN2et1UkGQpgDhRIrv51ZQi6GhPDA23dFah6YsC035Q+nt1Z"); - a("1j7+yX89BmhCsOGmmiR1UUTL+6YuPGzsH2wfZoTaB9BCWEdDxyeXhabJNzFRSq0o0S+zJZnvUxfUVm6DEM2Ng5QN9aKac8More"); - a("lg5eNjgKqJ39FBzs7Kbhtf3im4AwScQG374gX3wsJqHEL0qjvtp1Xh0+VqXnsxUsG9piKSMVBVdvMqmh84uG9m/bcfSiPZofvm"); - a("ywQYoUhGJ9nDsP+j+5cAl+A6/T1hLkPJTLe7kLKBGoyC78109/vbPbMLi4ynPpV5d/Iq5yvFcuxNXQIpeEseqJlq/jMsE4hKep"); - a("m0wCYDp+uqxr0COfsEyJfZ55ddQkF97VSzJeBguTeKN0rG3zXtViDAX8Mt+hsI3nFeOVZB3PhIVBba9znOCQRM6XpAu2xMUoqH"); - a("D+RFxI/YB3+WpAp9df4uaq76UMQuHEEJ78DZ98AXP8OvApyYbPutF1/x1dSXLhQ6mEWNonXVAgkErur1z2A72R40ekg/5fL9gh"); - a("GEvKXcki+bJumo3Be/T4skE6X09vlksSBk2OD7m6wYGUy83MEaJxgTcU+yk8PbY9d8R80Sro/+WCwpD/U+9Va8isQB5bjpVVDD"); - a("2Zgz66XBzMcjGxsXNF+4r26DYsF+N0tv9QwQm8YssNy8Cxpgys732xb+mKy1Yw//cx/8+nYTRsg24qvkdBsYX/ZfD/6jH4/2Di"); - a("/4mdn6F7+5/t0aJw7LPwZSvs/L/Uxv+oWf8TXN2FwQEK/M9//fhr8D9d5Yn3aHmLuAL/X0H832nyf4vg/4N5GUsm4mAT8f/irq"); - a("+wyIuV2LuZV8GJLrzjFV4cLBzCG8H/tTb+30nwv208rxivJOt4JiwManud4wQ3Nv+/bOX/x638f7f0d3zyBczx68CnJBs+60bX"); - a("7UB3TP73ElMlC238mw/+pcfgW2bZ49BF4TwcYtsq/qfv+GQtoHPaS+v9+i/jSYaBJAw4z+/pNEcQovRMRATE9srD9iIHYi9CQT"); - a("JUYdNfZJCElY3kUDyvGIFHsnsygag1fW7ky7Hv0Z6+ETqmeciISKtwfLrzN90W2skZh7LUP7fX9tXRpjb7QbZK8j5AgQ3hM04d"); - a("1w8HMd0HXzQJgOXv4w547HJ2joTAY/NJ3PoBs/WjeuuuJKE3B3faVSdyo3az0RW2IdvEkJPFkFViyAPN1ofZhjyAhtwVQ2pP3W"); - a("+4yN9JuF9SZXORTf98g7TTcbS//2N07Pd5n3JMMm/Fu266e0zcnfEe3639ie/eE++8Kb5bJO7WF3f7oqU5KhmXebIaGO7WDx7Y"); - a("ATr5qSUFnhoWPCWi2udlZM4txy9C5qoeuRTtwfvssYKeSuJ9etlaR0Zg+GF2vndGwRFO34Dz47vmwO8qkyIbyuo+BfyRRnU6wh"); - a("0+8kWmbiZMx3N2MAK4gmuAjRrVy0Mc+PYB32Ga3M6AGz88BWQJsXEOxHaoJBmll62FZLD98BARXkVXsx7Dnqsmu+8W0El37paP"); - a("sl9oD8KMXb96K0h4D0j4MFyYp+HCoHY1Oi/In7kIDXChdhOyayENB1KoVLFlgnbkvQbGiwnjS7dhesPDAOXghbiQ8szhs3Qqvj"); - a("uuTpU7LgEZC3FXFlQrk25KrHN1pQ9HNFAfGz/e11T9R6YWMnosvaQr6AJQlnKGXAIzZzuu9UvpBVvfgLPpFF0l9sf8juFxEfzx"); - a("4ZSN+O5NXPbRMEFVCoIkhVRCH3jRNZSA/GaGF3W3RLFHqfK6kGBlaiE7NLgh4hsbpHXQHLvZ15gsBsngU6bjQ4VcPqLDQcCIW6"); - a("szCxhIja9lffGgoUBkSHuS+WLq1fAiMPsmKskRCM8khAG8gCqRCu4h/dtYkYJL1zqJGqC/D57bBKqJQsaVC55W3EexACJCjRw/"); - a("Jg3XsnlnubeHZIbWA/ocepRpbBkhB3l7bREKWpHjbFuGdhkqzIGZwvajgTJUrD4P7+xDXWQxjPia8VH7lj6pddOg/6S+1g21GX"); - a("fbmeGsrUiuDKJdMSn7gK0zCO2pVj4QfQSOJhnFGlbND8anuQjzNzbG+IInqL51W1gQTwGulcxYRIDI8cZvxotMSw9a8qagBhgP"); - a("ATIeMMAF0VtHB+Bgq4gmROdL7hWspjhYzU97BzE52I1ahzDgNB/OxDjQV6r6qIqBOLFtoq6bBHOBnRKgZ7+r9XDCWrCeS4QJmq"); - a("cba0n2mlhPFM0C0MfW9WQgcZmA9UNNpQnMBKwl1pfqfTk0s5PRgRg8lsO3dJpbsLANdqCA1g96QYVeUKEXVOgFFXpBhV5ANe86"); - a("ziMv0urvZHbwvjhu66k5ErhCO3pLY8dxxC/hP0+g7QsWaBH6aM/xJ4ciuUgU5lQbn2G160/xRUbqWgE9TL1auFe0XFtwh8GJy4"); - a("gTv96C66MM1Zk9P1eOYdh/ltKQQKHKwwkjZOGItwJiFzcFjXQE/x6vK6KQpOpBowSDWM8KIpywxuwc+xlWIgaOgm0dLaclohI9"); - a("QEwfeAoxC8t0S0qKzAJsHCIg3qBfrKL+oh4/wxKJFUZCfwKZ6JSoykW8KaWVtr6deVxCUy+g/Mh6WCZ66gygO+f3R+t6bDW504"); - a("mEUf/nxXPMWzyfeU7CmKCDfl7MhvMxOuxsFkXyAP37uOrhM5uQlorvjU8FYu4dF02GzkaIJaTKPsW1FPEn+CckP/MqAxBXOlCO"); - a("U3IX+7DXBNWAL6RKtNdgL+vifA5ezZSij3Tb49FqqQgPTd8qkwwQWXByLCfjLeSf9tcLma8nIWI/U4qM0yOmB2IBxPz3l9X9Gg"); - a("jKdO3d8aJgD4ztV90nI/CAU7o7BV6j1dLPPyxwoeQWH++GIdvoLoEMe/T79MHu3Eb/yrblVDfFMSNrhMbJv9r8XK5n0L6rMPPH"); - a("2eO/Qyea/95HUD2/MoTlqg+oHtT3n5J+M83zwEmD2DBhoahBTy7N77xeUdo1TjxHMNhTktwq4F974QfMi5f6eFvf24fVpC8nC7"); - a("0VvQvnKhFcskdW/zE+PXQqo9hg4LdPBj9Bu4SFbkpNs6ckOgl3Aq9G4Kt/ZFWLz0H4sRL4oergwrfXhefNqDt3IpnlvBoXaMEB"); - a("D7TD+7ryerTgAF9Q3WKomXyVkIpPndH2cIQSjxYhWtskQY/GuqHB5Tct+hv0hWpGEL9I26hHEBYIecRg8V19yVrSDWQJFFFE0f"); - a("tiQxEZof41OI+tgDMxiSIFPJGZhSgz9F7RzDG4P4KxVPZzTiiakNotIoYdcCrdZvvesdowQVBxn/sNc1+8V5UJ2vELGW3vjbZv"); - a("ZJPKq0pukNBFD8MbdBaSl0ex46/wBx27q81KvezxxnlMbzl2cEWlmsOfSdXJvfNQm/BX1dbJIeQj1lPibQUBNZ/aTE3mAxxdoO"); - a("3UkxHZAfXr3mC+oW3zhB5iFLyrrinLj26u3wfVM/JhoEJuCEQlguzBmJbuS/oT2DoXKR2tNB9FnW5SvAeM6b3iEgzLPVhE9S0h"); - a("0Z6p4miwroB9fjC757F5Lj4TLMdurKjEr70E8e17afgbuQVN+x7hz2Des2jeGwbgtETW55nPrqhGIyJEsggE0O9V8YMvGRAZ9m"); - a("cyhC10wAmjfKH1noYFCT6stBNkjkBOFcgZZGkIE11eGpsuRwBOppcMJGiUDHX+ou1a4KKssvgMMDoIOOODQtMaFQ1MDCoNQmpG"); - a("wQaFwtXssWvauo6WbRrMoG2K4mAxflJTmWuvrX202267ZZkJPQVKqLby0cOsLSWrD2czMsO3s/9z7jffnRlG2Mdv/RVzz73nnv"); - a("s6332ce+45G6h32CwcIsM7KFIf+OJAjlOpsjtJbwPn3Y6+ROE46zulEAFRtlOWjT01nfvflscdxZgf5xmHrV0C9owJisGBY9Yo"); - a("gGZUhez/o7OVRAdeSvXDypGAGOAgR/xGIzGnvJ+Q56sWiH3E08QMFlHsZK6HYR7a8SqTbZjqx5LPjFL8sdTUIJKgC+jPDRzl06"); - a("LS2n8txpIbYMRX17t9NXeMgNEmiipnPuc4LE/G7RwNTqOeUEqgPYrvIVDmVGYiPT4sXU8EkUA25e+abRDT7YJOdQJbwWJN9DVE"); - a("bP1ovnZJ2TEWTjbWnuaTM7r3PMcLxsAMTQlpJPP1m8U+TVGY7RM4at8Aal+HUmSDyZFyHPPPC7xfVLPffS6i0I+0s47HztriVP"); - a("Bfb7HVQt0g8+yqktNd/ZBHq8es6HoM6a4eFxV7lxuYu4sMIQ4jGymR1UsOr153dZPyk5lnkq/EXq9XRqzXZcVKrxKshHjPsmyG"); - a("tqYYxHq9cGtGad0vesEKxYR0rjeEdbLe50VEmxH9FvXJJydpyDw5fqzlK7Z0s0a6k3jHY1m9BGXGXtZj17/mjPW/Lnb9aYVL01"); - a("a4tLAWDItMkG34ETsypIs2bPp32lBxxjZEjlfejgiHTFgaI9+bSe1yPosoZlYWV1+APimHNIXVX+BZja4zjjKi/L/wELgTIMk3"); - a("1cfZDSt15uB0clKiXrRe8kys/ThrjXz7IOzZbMMkfh7AZPU0QDLd0i+k+cQ78jnoH19HLA2Gnvf3LZPMhNYyKZl+hLRWhZS3h3"); - a("1/1/0FzqjqF+tkk6LSvUvNGGYhBFuQKl31iP6afJhKxA0zqeZwvSLSIQ0thNBTczT055fjQ46G/ogg2EGWqeMPlPh3SPxKxgcz"); - a("FezKJCW2kYSC3YfTVqjYh4hDvTmYugWJDZ/wfnMAqgr0wgyge5JF5O6BOMfAcljKFYhVbxkgWyP7WzHd/5ZegyMv6TU4jKBTSU"); - a("P3ghrrro1G/sC13jvTDB4Tlkiwdidyz5C5G2TuFzn3dMzwVrA9VJuScTSxqS1w2q3Zn5gwiGSWpvvOjxPdH8kXsn8Ot+r0r5f0"); - a("ZxL9FkYEznaJM1LiDJc4stkx5Ml0h//599EMwekkVEujtp++N2Y6OzwqmJPBirV0RE69BuHI82RXfHsY/rh/A98Whp/aLb6j/m"); - a("QQ/1Jfb4g3xOLvYOrm6JSo9Loe0mf1kL68h/R5XdJjv3feJe9vusqv6e5GXtwQ/jN7dOX0YKqxQXsG/JS4RpGqvDH615LR+IPl"); - a("hlbu3CfqZeW0dHoNQ4n4AcIKiRBqb33s9sTOf2WX/Ju39DAePaQv7yF9dQ/pv+whfSTSD1lukEetqHRTD/l/fLH79He7pEfLFz"); - a("CeI+Ngoz9eShei0velc7pRpjP9abgHcBjFxrQ5Ap5rN5P8RZ6ra8m7Cs7hfJJaY5iQaFmVjDlvTJ9K2xijOwP/Z+P/GfjfOibO"); - a("nTvG5DaPibesVlEOW8pr/5rXgtfTKLxH2zeDrlpJHAipwrawuHIt7nmO42MlBLaoHHnnGQjZ8WUG9yDIQYWp8hedxpC+UByScX"); - a("iaaEZuvs2wPNhr5eWQFC0g/VXSBJlNAaiA9Kc/Q+lPBv25OFDsp3sPyMIpT4D1sRleauaI0aiHgK0MD9bhNIb7ABavaukRU5e9"); - a("eWz/YM66KWjURDRqAizDzR/i9LbYHN6TxmXpMLDpJ/sLdKVFtwm8ibViCQhuB5IV1gJWRG1mo8bTntwcud+LKtHYCNEbaQu5C0"); - a("nX9SEYw0OfkUwAVz/0tBAii2WZxUKwrb0v5HuKo/BTs42qhF0616c07/CK/XKjFlt/cwaYJo6Y5mUDM835Y3Da+hPCYBiE3Vfg"); - a("/wFgnEvBOEnEOA+I85cm6OVtagn8oWgHehufDwC0L5R6K+CRyWgc9DcgpIEWN/NIL41HyiSPkLAGtGaF05qDVY6uDfkMQUzgTk"); - a("U0xQStPLbAST4WqQYq9ZVl8/ibSHRfguaUURMPA0/7Lm4luBUwmjlnjEkLx+Os+bFoA+uXvYA2tUh4wS7AWyTsfBfwnwSMNtwR"); - a("3obk00hTRNp//M2Al4WIn3d3yaBHUSw/Rzn9wsu5BLdwgVGiT65TER7MYU5Xe7chIlHo0x0J6cp1ww+9RYddzDyADvpOdNh0/L"); - a("+Q4F2iw2ZTh70sOuz89p3avJCkHt2ENjeH9dffAW8SMKUv3Qn497H76zO6R7v7v+afrHBatpOSfy7lScKdrTEQ3yUEhov6bthH"); - a("jghFuOQbhDXeMhyRvBXjPC9lHCGPVOKxxPVQvxTixRW9V7KC/FjtKTTe47a8KeRJ/M7Xp+K7fYOnEpzJbqKnozDTsj/KqJ3812"); - a("P5cVT+J8f+u/Ib//fy47n9/2X5t5/6N8r3pTy8Md6QQ07boNhxD8LOua2FSuGak+RhpP3cwpzGm9+a5+t9KzmKMLbiBZUvYU3B"); - a("InTMsr+3mN6Gl7DFCEui9aHzNJlC3Q6pTD5IKiX3JfiawE5jARQpCX7f2942uHXaU932xUbzQ3D3RgsWuasKrnAkwqWJWpjThH"); - a("ogx8lnoXN88braS3qhro2ICFCEb2BtQZsBddhQTz/h5b2DdL281wD8Z+Wt1cpzY/C4vDtD5d0WR+UpqbdQASk2bC592717yTnV"); - a("SCJavY9pthHNxB072nNaLzYt2gwk04/Y7bWYHj9PnHBi7m+UoTVI9pqW469RMS3ZEG/IN+UMjTN4zNUnbkfG8hFKyk2IVUsw/x"); - a("1JnYmgYirbQOT7AO1lGgR/9Qn80PuIJUDK+bTFdAGRE/0DB2p1pmefQbaBG3zbG9WknO2+psa23tVtK2eOeSynybejcZ+F2rDt"); - a("u5wdvtZGtX9Oq9xHxTqfs7093zb1MvpphDMcm7NeN8E5rNGZ+D2dyVPo7PKQ88gJCPRJWAIwYgrAusyPUXqXKMZiBfoVEk4sVU"); - a("hMCraOA2pM/RXF9NlL+pnv9j/rZ77bEHRV5+K4dJ5li9W3i1/FqNkrQneymIymm7hfIi9kpT6LenEtkJWhP3sa9JV8Vte9IKfT"); - a("L/QYOlhw7Z0Qz+cxhoLQc/RVmPEaYQnrMXgLDIPYcXYw9WhanLSZE2v/u810GCjGbaZ/0I+6VErnNP5ARXb9BQ+QMlH+QjMqsJ"); - a("vP/o1tqMQyKwRSVhmFeztrmp9f8yzZETWE8jz9hwa93449pPdbJ4LVS83PY7H2jARWVYOu07ULSVKn611A6uIJfOy+XpI6d71O"); - a("6pz1ktQoYF0sSR19MJzUIUDqSJDyAytF0lr1hE5rxRORtL6p12n9DEmS1kxA6if5glZjvU5r2+91Ws0IhtN6RNJ6AkmS1sOA1D"); - a("rQijhnT2dzDrvxgQUKcD/I7ZflHPyjXk4AQWY7jN2fzoojIcej+KF/GCva4RbcS7Dn1ZUF488mThlO7Ze16a/VpjmQ6awbmgwo"); - a("YANGYIte2pzH9dJmIQhUEJ1CRC01r3A5n2MCO3BlHEKHoKi3Es+46AFsLlBETJWdd5wf6yizCqjCqb2AIe5k1q7VHURSekGBMN"); - a("U1bwKTB+qnqRpqMHU7coXh9tNw84DLr2xNzwIXWRaAy9Xfx3HR6yYjip9Etwk0tQ9+8fZkOlYv9TRmYbSpE32JNi2mCw7THgDa"); - a("ZdIUvkwK2RkH5feQhtsjYUkvAxGvigg25jctldv2Fy2qJaHJIOZG3CPhrWHKfUhQxwAJQ1WNMP3De/PB2lVRBhnbOIM8/Wuq7L"); - a("RpwIx5PvalPHg/aG+X33Us+e07oscHK+hxCqEz0EGT0EHiJq76ri4iXDlfhbYO6K3rUomb+rLZgEMkCHEiwuUb6hhIXT1uNP8U"); - a("fElDrJge3ayz0/eSeYmP+YBgBRUxmhfP4L6CFPHYAAwfPbboMqfp5wVt91si3G0hRE3LUC1spZDiFMRhrC8Pyt1zjPkdi8yyO+"); - a("Sczf5g5YQdiQ/funOoYlM5A3uuO6p5hzuqrudXLxRpugBIQuHJtBf9gvZkUrYZpyPtBse2p8IedDqghKj6QX93S9F+g67uZVat"); - a("Y6H8XvRB+1KOY3d1u1EFlRX0BlAVvMtV8LFIp/i6D0A2mPrrAfThrAbA0iv09od5hIKan8wNqdMU+b1F+42ob3H/OINyzX7n3C"); - a("YnvPv2Wrn8A4Mno/o4rfQrbFxuftHuyrPUYVhHEOyoTGq/DaWo/cjmSXQbEYrtbwSMdB6qhTuMYOrZA4TP+u+W6EpNu4gjLdGd"); - a("Fq0PiqedK3HheQ3N/5v0mS33N+HKxBcBAp/PncTKxJ+hvcA2Sew+SJezcgIgteVSejkBtM+f19G+fCyc6D8AQXURBBVB8AWJ2Y"); - a("A0SXATILXyUka6VyKtiyB3DyCaJydyHXMFyZsktisCew4X3gHMvgLzUok5IQJzvKB7t6C7V9QiUWL3jcA2E/bcFmDOvIwxv3hO"); - a("x9z/aDjm54BA9wpBt1bQfU5iv4h02QUbAakPjGektRLpvgiSiiC5384kxwmSN0rsuREkZxFJO0g2fEmM0hn9DrurfE8dvohl8D"); - a("RqO9WRAOTeJSb+odvC8E094mP/GUwdz3NffAhTyh+zkNCt/LOH9K8GdJ/+YQ/pr/aQvryH9HlnSr82tF9/34n191l9sl/3N32y"); - a("vw9BZ93GreL6xamQ7q89je3WzbQ1mBD9g/NJbdM+m8jH7l+cRyT5cZL8RUTeJKhDF3sKqP8E1OEU02lTytJ805OVMptvulWxW3"); - a("3xLZMSiKp+yzdQ/KSJnyHixyZ+0uknetCh92ODt4FbRZIjlwSK1W17YYmVDhjevXuLja3QgC1RijPYhWc77DYmv+XyC5FQv2IY"); - a("AVWmmfGGw1rqm2LleKseb0W8GfHmAI4nTtgYS4QYsjhva0VjbPvrtPtZGKR5v4qIhPeub2JaIAmSE4S8wrdtVZqOkgYUK1C4/C"); - a("qbYVmi9+l1QDICJm1O6Iq0wdbVA9sRpx4ItzkRXj401/hV5l6jO8V7l5/yO70jTgcmKAzkm/amxBkqrAIH1npNhr5xhsoU7Mao"); - a("3hfTw9l+LBuaZIayoUZBltTlPrUVfcVtIJv8E9MwzFBUK7NxH9r0eBsNP+LTAhY+sHBnrHqKWmLvuj8Cz0zLoDENeoaL8fRRHi"); - a("dEV/sSPBbQFuG9sDgY+DLiPQLuwp97QrM8MsyvtepvYjRwd4l2HQkkIX9lWqDN5c8ha1QxpigSFkPLkzin1NdIznW8xzLKF5TU"); - a("DQRPNBd7v0zwmK+qGwILrUl+LaI08Z1S3w3I1b9EYxf07znsWhe0SEHbRM0tbpnIjMxK9lPSeLuVCKDEN81GOuVggO3NsC7X3f"); - a("04lGfE+IqL6tc7WfaiRaNPSPlgJsJtCaRxOtWaAHOTxg66kWUOQhnMdv0l29nAdjbQIL7T+dGms6wF9MygHxozyQ4R80H2p+g3"); - a("qkOC51wttJcFtMpECsd5zMxfm4z+WvkgO1q+8Bzv9iZRBrNnBNiUDhyZ21C6oGHVxrSdt2Y/SDuKVJ/Y+nzMF6VQECOr//D4dj"); - a("k53RBzhdKbexJy8fNPwwSEGeI23G/7Lg+UFcOTrDlQ7GIcmkHg4ykvsCSnNO9g+ZhS34WEmch3GL5eAQ4U0yNl7zP8wdDDnPlk"); - a("XD4F/HGSKJOZA7/ObVEKkrH1UXGmAifgAVEuGxdy4HRnhTmS4pY3xJvnbxWv+KRT+sQZys/m4wMsDmjKakfRQai0n9wMrT4iHk"); - a("n9gnf49RsB4d0PQvUcSvHWEyGolr7PeClj/oSF/E/9OJyNPOojZg6nU/i8RBy8Cp5CkHVROSEJUFj56p2icDZ0t4h9l8zKgFoT"); - a("zYeQV0bOh9BzQsi0ACSAkiZQouZDxfsEUwGm92UKGtxJWmSJb4EVLlKsBg4/TVF+1Ohmqmo6msDtv8IoX97nOk3sdwza1ro5rk"); - a("43nIwqpCCozjkiq07aniiG4hmx/TbdaUi+aYs5zrAEHJryDAJqpp7NXYJV8WHEcRZ/oCCUYT1lGI4MdZThaKee4RxkuCOUIZAi"); - a("bgp3i3RU3zNGxGzTc3gGryzY8msMgLs3bOA+hsY1vEN1f+EQMNDVof7oqd+ov3gAvbxSs8jfiLHRluz8PpXgbIIxBtwKUDKw/i"); - a("EtQijFZmDyncWNX5sYoSSzA4ZJKzUdmnTUx1Gfi+DUugkZ4H7ha0XqZUGFz/u2kdTj6cFp4tsoqZSmqhlE6RBMa5b3u6ouObvE"); - a("58Tn5UB9WwOwP5D8A0WUku0viqU5YMIPXi8vltUv008tczNbmKx+GcOHfwm86omxNOKH9Yo4j4HDgeupPUH8K65bnou6iu7wHs"); - a("ilWRPVxM0RPc/QFqjrzDQRVTfRfIhWcUfwIxJnGl9ImRlw2FC3OBCTt4g93wdgrGmeajxoAl98/6S+2f5Ikw210A6rYDugEiX9"); - a("CFn2GMnKdfCqV+r7qjjzTXxGeKdwdbG31GD0PssTEtp3BU1K/cUDl/6Co2qEMdr25awjJ2Q4hHXrCb58QLlsBfum0rpb01vh9s"); - a("JmSTOQxWtzMZDRAQlHnHWikxIsaXGsGxUaYTT47nCmShNMlebMn2KuBA9SBOtVwuGRjWSbPd6XhOZGLNrVJ+jbrUxbWfDcOpqG"); - a("Vp+DT0Cw3HNszk0xNfxB77ff/E702zbqt3EbANECsgF7TiwETuUuGkL2IxUYH3rnlH+ddclw6lmqqbU4f0a6taI/eoQS3IP8DX"); - a("2EDIkmMTgg4xfBq99a0kqLwjk4mwh7+6OOh3pR85+JN/BQJNS0CS1QAgxffimaFl8RLRff/oiI2jOB88h8y0yacrwl6Vbc263n"); - a("vjZOTGMrIE50s9NcSSsvETFLBhSdK+3f0wNl02tG/lBOQ0JnWDIYd4XnO0fS5hldRj114ynmkgAu8U+3ViQh/VJe2jkV98ucGr"); - a("4MR+1X6lI+IwnttUnEDTMzWGh9P61BxAEiZhWDOJcT4m1AlLQizhtA8RNKElA04Tdo1QtaaQSCFoFAnE+Iw5O6nhai9ovx9OHo"); - a("u4wMkvtXf8PNz2uFwRfvbcSeR4FkYrcYLZPE1OqbbhbmV7Drc/qGNDozG3YjnrdQK87nn+VJgieHwiE62zGbcRhMlqTZ/v4YHd"); - a("d1+xnbvp9Shd3PN9iu32h29yVKB3iBPRn4KZ8NvDdZT/GrQpOYjhzadISKTdP3mACm2GiuNKtrO/kUrW3SkmGzJtnTWx2F2iE9"); - a("82VqR0zrLLHrV1dB5s8xNZC+oBnfVOAa/jZM436rf4ODHw+fuwYCwvxA5VA2pRdqQfqiddNVmn5OcePeYCvpBJcK+Mz1kfwWGC"); - a("bk85uIoTCc4AcvB0Wfx4MSVkKxAfpEZzKZX08027M7A6PQDnDSUBI/bTALSbUfEwXiEinuDcTZXzTaa6X+4pnqw0wpTn71sj4D"); - a("RH3qo+oj+V1Lw1kGZT5IUiurVo8Noh7VFDfBHEs/CuzJ9pIS/erU07EtIcnzDoawCQsdzKHytw0bR81iEkDQHPv8r24WVv9oiA"); - a("dRlTZTlXRruS0uPpd0KbPLfheWIoqy9wt196Wox1Hek1+KgFaD6uM0M1nuTjMCqJtyPh/98hotd5OKBRT+24OkSHOc52TCtiK6"); - a("Igk0278Wcfzt1GEurLsOluu/ROYTSwbAXBUCuyv6EIVXNb0LU/VvdHGG61FdnAE5F82GVMeSusVqcX6l2bLax3lgmqwEH+SxQ6"); - a("xMnVKsHcPA6qCX90UF7nHuEnKQ4yWZB6JXQmdoJcQ+EbWq6Ie5ncj9ik358xsCkb0k8zuncWlE3kQ9L1pQWBtDpTy2fJb44lxp"); - a("fZcUNi6AOCGkkLRCmsFCRXawsaZ4fhqnvTm8nF9beG6gjE2nuJ5wcWuLQ6cPDBmKdNqced9XmEEhEE8zVN77TsuVx1QvU9tGHW"); - a("wRjyNw1aA+dhPmR4Dsj4vfpiqRlvUFv7mqCxofpjpWjQDj1yKoxpswBNWmvyBspC+1giLHmrSx3PyoPv88jAS+V6PhHLoOkOb/"); - a("RKUJeggMJwL/w5NGRHs3REqYZPktJgeXD9QbJOkrIkjnRZFunMukfyVJ03qIO3wd43FgyOKkfAXN3fkQFbeiDCW3IMhN9COgvh"); - a("PPtfjgESnffihCvg0IPjzULw/yVVpF0Chk+gsR0O0RNnfhD1i67HccjpEL3gFvjDAaEPo7QoMQov6cJ4ub8lB4owsBobojuLpV"); - a("Q1GBA6S2MC9eTFWzsBGi36/w6yft8YzQPkupModm/xRtStwIa+sB3HCPOu30naZ3VXs0xmzBaZf/UVH1GyjOck8V91aqgsMQZf"); - a("7hW52/Lib9+g0UPTkNXWBGkN9Bm4KMu9iKfhBHIUCmA4iEb5zqrNnAM1IJM0UJ65rRmiHUmo/B4OSXGnAywfMBg4Zk1Jjybfh8"); - a("VwtO8Sj8zccntmDqkwj41bN3IOlQFg9k0sP6rPNErT7rPFYrbpO5abl2+m2m+4+HdOQHJLK/lpqVpmbfiMIY70WJt1DiLSC8C9"); - a("KQvl6m58v0XEEH7wvQSKZzm8QbUanj2RD0pXWZ2iX/osXNoMV89zICdJf0gOiJT09q/LgLAYr/6Rf8lSTIkho88j0BguLYhaxL"); - a("USvWr1i8IVJfG65V8d+OFpxiRBXo2SZdRb6ENZpuL3qHPuvcZv3+EF5ES5RrclnUQs89g6m3gxHk7VakvN3z6x70qXtIn9dD+q"); - a("we0ot6SM/qIT21h/RT62OmR9gT3mTEIExar41rPgK1zX58FunY1o0E1DBCXB0AK5WxkoKpKYyFca7dLb+WGOU/ub4Hffge0j09"); - a("pM/qIb2oh/SsHtJTe0g/9WD36V/1kP7ugz3py7P/dV7Slel4InQJMsDHbjIv5wdi2IdWht5xF7TD8qHotGxwTif0KUj0W9gMka"); - a("WZ7dPnHVlxoIsdbpkfJY4Vdo4UM+q3jndJgCBmM5MNyLmTzNoevuH6YFCvyvsRBCPq0776jPW568z1kfMtP4EpWUfyS96NDt1I"); - a("4aePyjVWvKdTUrYgwWc2pj6L39j2xdXDZcEgT4FTjxoN1blE25PU0AYM9Y4vhJwhBymo20tloYXHM15J/RlINtgJreknenwfkd"); - a("EuprpjRygfbacWAQV9iCn+wbKY1nil/tYbR/RqDFHPJtJK6kbE+eKwKF3L9qdPS38RXfW/avT8bitAD9dB/Xwa8vD6DrjFQMmS"); - a("QJS+ibrvatL/A3KuyNwIGCNNDRymvnGa2zZUJP1RJDWQ/EltpxHAfvI5RJJaYkK+HES9fvs79fqNof1YJ9O5EVlYtkSPtaqnaf"); - a("IdToOUJXtaLP0awFuFdyftnTEYkRYDBKwUyKb17359tZm6SF9tnAiSaaYkEpFlqznMORic2jZNKZriM9Q/z9SKtaP+PfuDkU6d"); - a("3i1U5mHR8eSqo9BbLaZXOozc5Q1p7E+CSvHlsp+bReLbudbaUnRSjGLRSW5EoQ8dh2v5VGSDsWmq3WXMf804gCexPdl9zFNK0U"); - a("mHr5dvdw/uTri/eHQnobWk344e72J/BkvoQJRyxvdnw95SE3pIP3x1t+niEesXV/PxordaWRoM0htamSOa3iVXdUMPp5x42GQB"); - a("2mOy2Mj867qvj1rTXbo6uTQqtau/QU13qKVot8GqqwftheYQlIlaiv4prDPXle6GPuYPRoOjvhciwNOPlqDlvdRrWqTuzhnkoW"); - a("zrufo0Twkp6v6rmAtw8g2kOnwd2TsbDAlgqn+IaJwSxd1QMPXpe+MN9Na8DyD4d4v2MRPln+O3PdpTjDKniPuUXHXJVcKWPOuj"); - a("8X0dvVHNRskG92BEMu2f/05oPwHjfNbqE4/37uxiA7Gb94JVq/6r+n1cyvU7B1XBWYwpzfitXps8rb4r76H69hGNqEFkT/WT/P"); - a("FibP6Q7697SF//P6a7Snt47x/mM7SwlvzNNbARuap/8D1ThNVw8pEKH04BC6LIwuXIzCpytL3Pbg46YLEByvUkg3Ec2W03d1oe"); - a("bKpuI/DIHmKvFSUsFaJLPZ816mVXV32SJHX2FHFaPPsf4ZNQ7PexWB2yS2QrY6XbZHr0+q49nk+CCa9fTeWn/MOz6FzqHpC1in"); - a("7SskgS6R4UOB98+VocG7Hy53QGbCwwhx2L1/ipxntOTJqwEJUoYODGfM+M7gOf5ezEPHrrVFmnsPEq7n48Z07tPn1U9+kvsfOV"); - a("+6ZIpKj8lV2SosYH7xmUeIJZr1kE2b4mu7EyrUcMoGePMeQX0D4BrRHQDwKqEZDpOENVAvq1SFspoEEi7RYBXSCgWwVUICCXgK"); - a("4W0BwB3SSgGwQ0/QRDMwT0lYCuEtC1JxlyCuhmAU0U0J0CmiCgOgGNF9DjAsoW0HM/MjRaQLs6GUoX0GaRdq6Azj7CUJqA7hBU"); - a("+gvohICSBTT0FEO9BHShgAwCcgjo+BqGfi+gwwLaLKCDAmoRkCqgTwTUJqCAgD4T0CkBfcRQyuuQTqh9DoFXir7Xtr+3+vSd0j"); - a("CXvlM6F0EIHGajlci2HQ8f1IrJfLFAuJCvpv6d4r7gOFMuaIQ+Z2wnSXmowL2GDwwNvcSZkRTNJD+GbOe+fgfqs2ay5M0u/vke"); - a("6eG9+NuR78UPAj/cOO+NVEDmZOmB9jHdA602uWv12UnoqRcSep+I+nC68PmhdhTJlCh9caSYt2K2lMmx37+vi9ke6CM/Ifw7qv"); - a("yzuYN/3tMbpxYVspd6IiKUxw//msS62O1Suu70USkSjvd4Kqruz88DWgstr8PnegNtU9RSVBRyZniEFO/rQaUEmZgm1JdJs0S9"); - a("HpWE9jKFdbtnD16rLY9jeHkU9VS4njHs/aLnBwaM0C8+1Z2/mO1ifaKFofM6cdQIiXgcvpPwGW1ZW8nWroP4J94VD4Brd5eSMN"); - a("EFN5sVM0ZS1Sy/N2V8YzRUTLbXdHrGCSN7nix2SLGjTWjgt35IDbpS81kgnnwmTJV+EzS6LQkTf2agR8oPYJ4/0521Mz+l/Wsj"); - a("VKwQ6KBAIgJHEJAmns6g39oU5M2veHeqzpjEtrGS1YUT6bmV+gGOfGd+n9UKAoW+bXr/lJD6PbaBbJ9vIlPqpw4TlNaAUvs1QM"); - a("p3p2dY7pmKEO2+2XnJ5w5eCy/L/lSdiwoUbMQesjw96zn8VA7KunA0oLNgSqoyJav3+wj3QXiJyb/J6CI5UIIPBEnbX4japP3F"); - a("1sh6qQtEjQaq9zqoRt5jv3Sb1R+m8R5Q5g9bH5E9XWRHwNEQJ7bKDmoPCBfwFvgs1SEqn6LmMln1t6AYbscw0j/jU9qT3Vz0W2"); - a("Ht+74OKAUZoU8wHUg4MhZsxIOhZcOy6Mc9Ee1clupV41aw/WUnvQYa6/KL9/Om4hp9ivy8XJ8iPy1nCa7L0H7MSFt9BU2y1x4n"); - a("jstVzwLjk37ufiOpJ2NvAPH779ogfB5pheAdulIz1qTeD7h2e3qHOxnm8G2QSx8H45qFSf3AJchwO2fIRoZsTuBdyjlIuI4T7E"); - a("iwGzx9ChVTC8rhvYl3b/yyAuojtgdGf0YEssjGznNo5ktsReBcF8HPa7A90JfhTRq8lfrJSrJsUZypXtyKoFGu6jzSx1gIWJlq"); - a("rj5GJC1rTwKsbqewm/QlLGsDiECgajD+uEe2f8bZUzZ/ST2R1P4uT9USflWDnxSwqBm1JfT+GaxhTxNTHE6gYs5z0kCHz320sy"); - a("NOIfazc2VVt50vt6q/NhjpjlXztTIIulqDUZSbx3klRkkr0a8hJALhGLrXM0DdeTlzWf7VjER8UpKPMXaniAJ2QcYfmieuE7NE"); - a("l/1u8ASzwVNtzAbd67MXsmWp6dmU70+0Z5iLI86kDKemHh3KLOmz/Z1CZLOFsm0/IbLlT7K5R6Bcf7W0n7NY2s9ZzIw7DySjaE"); - a("feb9NHQuO6bEwW/QiesuIjcQ+g/TF9TbBl+JrRit8c/Brxm0nfyyBZ7DNS+PI0guJ7WS2KnL4UMxLmsKLst9TJaDBwXuclZ1IZ"); - a("KsZjXH0nM64nhfZfIs0eKAbQqQEo7emVeml2WVoBgvxg1DOYembycT4Q9kXKyyKrE2Mnd/IxxoMu8UDaoO65kgfxy708iBorsK"); - a("6IkfXrluFDAcFsWf9cxfQjsEPf4UC21xcY53e1eJcC2diH+qlOoTBEPQ9b4wziYXg2OBzfo46X0sVHm/Q/DdbVHZ6pqCG5FuOl"); - a("Wix5mx+kDr1zqbMOJgIa7GITBrqVoKu9f7MhyFzbzfn7dPm/ba8ndNB+Z5n0J4tPR+wa/hhlsSf2e4O9VfpQen6pD2U5gjyUun"); - a("0N5kyefW5ERBZ9v1W9wZien7j8YBmCPb1JGDLdzt91vmn8F0bMTwgUUMCCQCEFejFSmRxTfA78m0G/fDak+V9W6/Nb5fyPIPh5"); - a("Pu4WY38/vo/0ZWa4WGYm0TJzFi0z/YT9hGDEOrNvuV5OpSynAkHx3bDvCjxJjq6nS/Eui8cPu3fWfeo9kB8MIopsNbiUcaYbsE"); - a("V3+TYRIjc6FwUulgWaZIFxCIq31r1Fx8jvJGq8smX+Nxfq+ZsQFJ/eWcK+hVjSXsKwQF51Wm5zuo7/Mjn+kl75Qn3854nx18bY"); - a("PT00P6Qj8+9l5lyZedxC7r2bDQGSOq+QOAMlTj8EeSQDsBsi2EZWMbb/figX+iBuXUC6zjaoZQbyhcpaNsFwUTClLnkUfNSpv8"); - a("EqBPWOUuM/S4wLbYK2wLQyZibe3n1YnHdq2dau+Ul94kZaxYx32rrKVqLl98xwTGSpRrolcAX1v6TL5tznfuyoJ+5RH4BIIvO0"); - a("c24LXhXErJnv47wjqFd0/o+0/NOLabHpdBorbFLcH27fbKnTwHL9YJmca5sjxrvjV/pwrL5ZH45VN+vjfW/0934DIsRqdCG+Jc"); - a("9VLj+8dGOypHIfuCNOXKcXs+bVnSj+J9wuZ2CK0P+RxZ0lixuAoOAQ4qJZEufQAh3nuwWxvvXY73Wx/kkaz0gaTy/Qm7WODbuG"); - a("2vRzvU2XUptmuvyWF892zoWX+Kbl/eASwLcns4nUdfqjWdze3ny4QQz50dHa9uQdepmXyTIvRVC2rVrinCVxBsi2yXE803pw8N"); - a("bu/BVi3JdjaD0q7kc6urgqJP2MpfK92nz5Xm2+3jOjjaTfo1wZ6pvOUN9YalqElVvL6jYEXBGOD33NcKjf13cocw9dkBxgv78w"); - a("oHsP7T1Jm/apVTwVRvpCrBgfPj9+NYPmx/wtND+6L8ep+W6EdPcO891iTQvJCXqDZ+jYXAqK7KmQyt2J3Rd0qTgXqsaIny8AIo"); - a("YSyZuQDF7WxuvHJXpPrJFil7td4eO1Q+K4JM5clxwvWlp/Knze4ytF3yvoe2WeXGblfgFYYSxaKUknSdJmV2jmHu3X3v0fczTw"); - a("pkLz7/wMC3wPcSK+tODJsBfsgm9il9dLlvfIPL28DfN6Ku+9yPLujVme/P4Ka6mwhyr1wsbKwi6Yp3PZBtpaVmlrCAIbQ2vIbJ"); - a("nz8C/0nN8jKNaHnwMnX+JslzjvIihG7nKXH977qizz66YH6SP96XEe99DDq/wy67LeiA/OtPs5Tsyt9toJcJAx2Wbs5j6eOxMz"); - a("GvhqrAnSt9tZIpmPHQEqUPOD2DpXnxZfzgJq40GeVszeg3QOvN5P8k6BZmfTn8FU6h+Xj7cPgSJKfyyUHsfpfWU68XDwoLhXAa"); - a("JbIDppv9rgArLaf2ssv96+1pFB5BYStMa2PonbpbNl+pcjJSY9wXK+gW5PzlbB5NHp/284JN/8xW4jyzeTuso3Wd8Eyd3qE50p"); - a("XTEWmHAMt6wKAsjiYM0HPPWlWWqaObDIUrNGmwxrHgoFFmuBVaF58q67Qkm/DAXcIuCeT38u46ibQ2krOTDfne9VCyw1t1Dhvz"); - a("KS97klIXo0yDy/+etb8bfZ5a/PxjdKv29p8Nva78Va/EXab472+7GWnqHBuzX4E+13j/Zr1NKDvP5LZmF+8u4zYmcaxzQhXNoX"); - a("R9BFISiBoOwQZCbo4hBk1TG9e206jZY4Lu6M7wuhevYRyZB8b5XmBKtzJ5VN3kvPA+1QOEgLDMA94tEdJGJwBVM7EICgeVhnib"); - a("FT6UVuGlpg06vU8Yr008D+OeAFLKF47hsldWOaHNXLDZTqHuiAAvKUuoHZtIPp/bi4X0VcwlV1E7Jx/0SOO0jPqiT2O8Mu+te6"); - a("WZucTtzorLopnlOlCt0MCNrqE4wGticwNhhEtbduK4QHVge9v3di1bwfidiGCN9kpkJQwEMDOl2mqy3jMDfHjWXhf/52owEm+t"); - a("v7AJ3Wtz7S7iIcGlEvwG1ueYeDLVp+x2u3PTtY6jsM9XX4mXWs6TXBWJ4zxlaZCIt5/fjMZa8JurPgkJJkVY6VVcbh7kRE2S3r"); - a("WgLJRDfQy+VHsp/CRNfzEr1bA79T5X2HqPIfAuBivoYeTe0cthBTooxpap+h+QER5eZp5Q4KXKiVW4AER22RgeyvBUZ1KX8gl4"); - a("85T6KF1eMvjm1F+D4EiIXmBK2C447N5uLZL1RjWzyE40cQo07cyXKFAKdikBI6UDVpmuYMD8oi7JuyQQ6WgOYvti37GYeU62zz"); - a("62aavW1HGcSDbf51zkVAlH4Hlf4GxFd6AoYZG35OVlJuQDJF1CU3kq7/p9gniXOwQ9QUCR3OuezyWa3aEe5ZOEo+QPcLOIRuM3"); - a("3zrpGsoN2H/D6TsguaSEWHCRf2qBBFb6jatJkplf4s5gnpEZpuBvN+UN1yAfrR9P1tfIk1ZTGqP+4yFjGP9gdTnwcNEAziX/sB"); - a("1t+CjxatBPXbJ1HB9l1EvmDvFHwEML4+ki+wd/uKDre/ZGD638DFoNBlGvoBa7Fe8z4KFnVAj6g3xmMtnIg4lz9kexFIdkJy9w"); - a("VCCyPkAPaT/tcO1m1aNVroNl2vtoJoALIJb0EWmmBwTxNvT6oXoSG35nFDbKC3/b0QvSVMrxGwX/3pZu5/ddMefHN98afFtP+X"); - a("2tdsumyn0DBSig5ryiRS/tD+pNh1TycrUyPd6DuYWC0grZGqgfgoBiCmniBnJj+gw066AphTs5F2pIIvD/cuokxNkCypH+bQQX"); - a("Tc50hA+scifSvStyVYDU5o7yOGiHkuXFmQ9ncjy93qUh8HQlHOWxByvXrKSDPNa2Npj0D2wQmf65eJUkmUabl3WjBCR66rPW7K"); - a("UzUKdK/U6c4TdF2gC6r5hCHGB1CWgCLXWZACgY9YUFdmR/AdEXQi6A9ysAx5vy8XeaW8Fen1J3CndeKfLKp8IShEfTRdqwelUE"); - a("PXj+ZO6NfQCTz12gyeKjciDkn1nNS/4UdKmiCSnkScH2l/1dIOU5pNpD1EaXgP+Tbx5GrwMtu/WSjfB8yMeB8ASJ2M7GT/RiIl"); - a("TA9HOv0TIA0TSLdIpNenhiM1AEKrm46j1aZ/Mu7lEnfE1eG4QwEBdz3hfhJg3P4S9+Mrw3F3AALuLYT7N+C2/yiatO8WPcO2q8"); - a("IzbAVUgvuQd4yGl2hHq35zmEvYKDOYImoenMIZypBBiJ1eFBlWyAyFEVW6HBAyXKhnWC0yXCUzNE8Lz/AqIGQ4+HYowwyRYajM"); - a("MPya8AxDACHDu3qGEcggOTOW/s5WIW9yFfpIgYcuPnIJI+LWlyNCq3qRb59ly/vCgI47E5KnuSpOGjB5TPP4AwvZzWDV+K6ECn"); - a("23pmeErMaGE7kQRBDv8i1VhUKkXJKi9xv6NaULxxSusMvX4SoYbSgvcmWNhmzDlRX3Rnke/hoqL3BlxcP3AYXd5/HfQa4sz+Dy"); - a("c1xZiTBY4soad165hQ7qSxL9sCkdSGLf0MIvQ+xGv4f6FsJ/420Z1OoOnFXw/lztWEFN7qw6v9Dnpgb25gZGZChABiS4Wuzqxg"); - a("RxLykX3qj722VCeentlfiN8uU/LMJjv5IU0j/4/DqyX4he1OVGkl65Ru9X/wG9e4jeQ+H0uun/6tPtpzwm6sBeove677uLzg/v"); - a("u3VLRN+dd+a+MyKDP7rPZPsuqtTb1Uuxn3TuUKllI0TLEPUTRB0Ia9vz18ZjPsiQbYvq/zbPf0bv50Tvl7Hpwb5Af7qfHER/bP"); - a("jjGUFr7NWjWMsiQPKh6Vq4D8KXpnPYsqVZkoqWv2L+guBcySX99vE5n3qb2X4hokiAekkTaGr6+33J5Io6kFrj3cYmmz0H8r5Y"); - a("8Z7LT/o6J4S+zgxeYM87zdB2Af1WQG8L6EsBvSGgN0W+8dcwNF/TYxJQ3imGRgvoTgGlC+hbQWUUIHXaSGqlaY+DRBmmffjZmI"); - a("CAikD7KRfsbyKA9AP4kad8VsUrwzKYGveW0YCgHcGPibhid4Ly37EKdNHvXVnwQTPtdUYrpmXI5T0aVzEAI7YY8idhIvrrbLIy"); - a("3WI6DrEK/XPR+tfM69/L2vr3C7n+RaxEmwCpf/xKrH8SKaEkYv2bCqRqgXSLRLrQEY6UCUj9mUAqkkijneFI6YDUSwWSTSJ5Cs"); - a("ORFgFS+wPJ5cf+2g7gSVvU7N9V3wOvlPUPVX0T+KBGgrAMvCN1CHXO1xFL2+dXxJ4nZ6fjeWP7b7m/fNvXlCRkuOCoYqTF4Kjd"); - a("Wtua3uGobazBfnSMzd1vjNWdMibbPWyM353TTrIirDJbXSN7Q6egl8FhWdfUfi3T1OKTEZ/A8Xxms7y4dfXWY24c7uIwdg7L/U"); - a("2BC2iOXnnU4hnknAsHrYUJmZor2zR4tDLhJXVgMD27Ti3K3umH/8Gimp3uRO9xi2XtdOxC+JW11CmJtR7iVDTnOCtFscUfGMV+"); - a("hd3QNdyjPUqiq3+6s90NWB01GueOwvTJRsx+OZ3FLTjXauc+9CCpCKxNz+BLA+FOTr1reOipg7tEro91wtMdz3wE2DQgm4A0Dc"); - a("goUWqYGKnrK6AnztSFoAizCkhrJUQFuALN6RVRMCL1CkdAGaQwP+uDRqNh+VTMAfmPpm9Hcnki3FlZ7ilF7xTmHVwxEFMF7l7o"); - a("iEYS7fXPsY1wZWA6FJf01viSmxx0Hm0/m3L5VD8rlkGGpC9o0v4/68dCvWHtt5qSjZH1zJWplwhV/XXY0+qqNdld7p/LMN9Id2"); - a("185XzRMIp6Id3PfkMfTd+A3xJ01FMMHxdIWadZRYE64wlOX8v4jnr8Ed9+AwlYVM9QTdK7MSHylprirkPh1AJ9PQPpbM24SiN0"); - a("cUux3fnAJghw8VH6sPX4Vt1zdDHuJ9N0Me5HCGKshLUJfhBipd8MHJKHUCAbKTYK5LawVgo7IpJmYoShpC6NeWqI9rE7m2P4/8"); - a("Ry+kGp703oKJUolTayU0GmeAqVqmyEc5n5qi8nOpaahcI0Dxe5DY3nCwrImM9Hr7Kx4Fmv07R6NqQgnxzZbSnGIB8KphYjkkj6"); - a("2fuch2QZlpoHQQLlWcFNLF3Hbu8+rBoOiKw+Xd5LLcpClRuod9Upz7L6JD/i94H7Ksya3twkW6HvziGaMT906bDZepfeVaZ3qR"); - a("dBZn9SbzGdulHH+bnEmU04vjRqknEN/sRyNdpVPifVJrFd/RhdWOp7T7kywbvX5ZlTfQWJTj2DipW6o9SIJ4UCSGIR7IN5ybY6"); - a("OwI5hqajnOeM6jzQwft+O3/RCGRwv+MKFgcVB/BLfMdKyb7yuTiuFADmcmyWmpw4bvoo2Szlar1ZtQhqX34ZxoXdtKz+s5FzHJ"); - a("6l57i5SM/hQpDQ7UASNVSnniSNzSN7LMVNviZy6ZnLBB4VONBD+NaoGVy+/UvawNUwgogJYskBSquOchVQnApXh5lcaKstvYjQ"); - a("MOsJpMwvxcZ0GmT2oYK6ZILc5RWjISzXD20i1zltsgjv0iF4yH0Hs8c6jlEmDiG56LbVncvmsXV5aq2TO0f8GruWSPIpDUkZ2K"); - a("SVfklk6R6t9Mf2YdoSyHnbVvzF5Q/rqWOBUDdcqWEvArZL4R6jnU0HvlllLUPqQKisBGbgkxr9CkC3PVQd8tUWCgufbbJjZBgv"); - a("Jn942aj5cHuLZFAi+BqCWD9BErlh84SXtSiXpd36r91Y7HtfsyBnB7uzZgV7pi2huyS6ujdDkufwfVikuJwO8TVYVo8DWvu5LE"); - a("sDb+dCEpkQ8hFdNyGuMH+RuTwdf5MrzlWwYhvdJqzqlf3VjfcJL2obasD15PUcOAmWVTtEyGzx0uRHfj1rXkPAoX1zOLvwElvL"); - a("H96YI/zhJWsOdNtzjJQlrjKP1HDtJWDwW47pDF6o9C7G5hixDhR7uxqyQeJJJbF5YDbLl8keX/xkM1JAB1uSRkFJ+5jVR/hLF4"); - a("5qgN/1oy6Fr056/6dZG3x6MMvXqADqm8J8m2UV2e9hQV+JuLXTutW3i+8/eB8fux8Tyq+knqmA+1x829SNnvH5sxPK++XPNlck"); - a("i/GwebJR3nwHamt0+CY7Q931hIGmlWRqW3C7P6w+5Q8AI5fnxLIIRpHnmX/RdiXwURVnfDcX4dxFCARFCQoaBDF4JgZ1Q7K6kQ"); - a("2NAooWlTY1YuuBklWsIQmGaJY1uPWqtrXiVW3VitaD4pUETKJVDIgaATUq6ksXNaJCuLL9f9/Me/P2vc2GXvx+ZOfN+c3MN9/M"); - a("fPMdwOl3R/FoIfQGhco809nlq2dB7JXFV9vl7vqggd7g1PdXlu/d8lvV3yjYoyujugWCky406FfX2Qb9+hJBslRw/eF6viEqX5"); - a("PK9yqCwlLBjnlG+m9U+kpRD9nToPP1rVCHrDl91YvMG0MPv8pg/dhFxZQrifVbiyWpTZ2JEGzib/cRs3kYPrCGr8dV0AFZaxde"); - a("YrRB8EZE7/+3I/zHG/EnjxQiinbgz2tf4s9pzBlPna0A084yAPsCQeF8YgRgGN+IBrdcIvRRqvkmtQOQm0ccNb3hY9jWmfULMx"); - a("Pr+5zSZ7rir+MRlPFZG5OprHbL8qMS119ArlLQh+hoWzbpP9GaYNV36Cf9/X7SW/pJ/1PidODFHJBX7ZrPVDa7/arQ4e8QGoXw"); - a("5rEoWrfL5i892KN7yYdXahhpW58VGR4uxvZCusfLoTFFUSqT24+l2JnXW73erE8p4L0lmmi+lGNuJSnPjl3v7kas9uHNxFGuEz"); - a("of3h4IzHSn8FmypBscw8XvOHGWlHbPutDpLRc6HWwnG/yPr8mvilf4kfonfQLSuenaBT8YGHEQ7V+YsP0Rpva/0tD+Rf23/8H3"); - a("RvvKH6fS9o3nvzhhOgBnIULccNnddybCMrOejqufNcmsH++MhnscKiWu/JxqIpnrofd9Fl9Mskazg2q2BKQibebe4srLBnqk1O"); - a("6yXiTWVA5EgBzsVE3GUD++WQ31L3Ig4eG6gIeaBIlYwlfTloJWhblxbrmbZxIVh1BxzHwvEvpEj/PPK6uFWtEa/PiDjzbyz1Nt"); - a("/PN8O/+80iFO0jg6lHuD66FAtIs1KEdDybkncliYxZ9qfy18IM9QPpC9iF3aA+lwei/6DuDme3sCm0TciewAcLUYnn2+BtQQSv"); - a("KLCJzYaXNFV/LaA4Nkc8AjUuA9wut6cX1x2Xs4/qIGMb509r2bpIoiF5pw2AUc1giH765mHEaYnUUAhzWJwxoG9p1/qIE96kvg"); - a("8D3n6wP7tBzYCVCIC9V1sjCVGLWQGLWQGLWQGLWQGLWQGLUQj5oY+INf711VidZbmQnWG74ArP+c2+96u7xbrXeTfjSQeinrSE"); - a("Mer8dw4GBDvSlo9bhNqtUucOS1u+ZYUS+pm8+uwR5oBNPuobDQzZICWAtoMYQWQ2gxhBYtwt6J5QVhT0HBiGuapNOQkSou24xX"); - a("SDTsndSpN5lOh+bg617nDghGVKSCV1L9HkLcF6dpBF8hitU229qXU76lvljF5mA7QQFtk38MlXRqK29MoI9e0k1rhSwBFJCynQ"); - a("HDQCwLmBzXloWpO95OXktc3Zl/5xiNBfnu4Oc4fCgQzPLkbRgZ40mAeBPSG/g6JlGEQJq4DO8sous52zPEd3z77rBjrl23gDiv"); - a("UdgRbFTyuab0mxOkA5qyTWxm0mEhrH3Ru9BMtojyNiqFEtxxmKYtbWqaNkwDyo0/zzpNt38tZA8UqnUoghcfvxT8Oy+1i1gp+F"); - a("ZhvjoxX5ofS7C8CJMHmgXx2xGYgk5MENKaouct5PlCSqdDiE+Fw1iuHXSOoIX9gpM1LGndenlGcXC4CbkoD/WMC1acyW5iKnIp"); - a("A9XOg1bPKuciZQTa6zCnli7A+wP6rk2twwxSrESKWHnc1dolBX3hY42tfwCK7V/228+7nKqfsnlY/XMT1mpXocFyYHj5REf0+s"); - a("NcL87tLsI5lD3bfAY8EBXOSI9kUBJH/9QUzVXBMUPUVdfBxt7gBycauIKJpNPQX/U2ou01gwmjP17oBOXnriYjiPTVSG9Hettg"); - a("QTLX0DvveoVJUz7Fgn+xVMekByUmeSPYOS7vu6GAauh3l/fZ0ABTQ09QQ7NsDW37p1R5mY3F97/Ag5mAXDu61oIHB+1fnxaedu"); - a("rFABPO+4bR7jpQOdSPo//EhKYUV3CPe53uL0Gl83dmfPus2MGhwkZvcrPRaCZM7Fadg7e4Si+E5yiFIyeBcGxA0lKXKQqi2WF8"); - a("pvMnfPyWtWiXuaJRkplKLswE5zAT7xnd8aBFD72s81KwTHPC45r8HRQZS+Zx6R2PDeE6yVVDZmQA0RLnuZmqD2Z+uIWm8hgSM5"); - a("/dXABWENRPMKcG81Nxxs3/+tl/6blvKSxpp7GCkYelc4LthEJNe4AfnybD74WvqScJ/ASMThqp8lXBB2FrVTJcF1BEatTFBu67"); - a("idSnYdQgUpwWSPOHytIjZ/saQGVDo7Qb7jOMfJ9ILVYRvT22WSHvER8BeZ/xW+ntOI3pLWTr+9jL+8c3tmeIEH5BDI+A/hgh3n"); - a("BCvCEG4tl07+znfd3YuE8y2gEo6ptl7Gjx90eeOS2b90GyCV+YiRF0Vw1iZGM8SuCvVvm4IpwaAKmkTMfSAfR+Xgh9g7Kv/Mll"); - a("mf78MnfVaPzNqhoK5ju1thYPqkgPlpH6Zjq36WyGWydiLv1xSDSKlMyC4AG8x9i1eGLpuaatzO/LPkCNOM+vEef5RnGebxPn+X"); - a("Zxnu8Q53nd+ZwuB1C04qocOg+zKJR0IgHQvh9A2YA+eECs24Q07/KvWYhSiQcY4vh+cbKWUvn8noG7jzx7M+DvFSEqByZQ+Our"); - a("c8VRRj/eDlbH2wmNCgu7O4GFg2fqWLhcYuF94FpHCk1QLOVK0lQln7xmosNUScs5eiWvy0rmoBJeXehqtuhqNnf13X+rq68cZu"); - a("vqPwvNXd1f2mdX80xQphKUWedYu/rX7f119YdXVSWNn6CSrcXWrl6BSsJ6X/1p9IjTAlKarZWm6UabSyDCd+ReuTMFWTldoFJI"); - a("oFJIoFJIoFJIoFKIUUms/MTnJ79xfBppP1aU6+eK22LOT/K4NP8qfqnNIn2abujTkAWi1MdOTsZ3SY5xUN6137qZzhBbZr5tM3"); - a("WNS7yf7vsc0/r+Tf/FfpqtnQrPjxzoTUGAKd1JVwlK5yJKN8igdIreqP0zK8R7q/1+oWlVd6r1b6cPHdrVpybSv2KZWxomSqDu"); - a("gWz7cgDciyhGhzGK4oGiHHxPJumB93X3hhBaPX0RclJkE6PcXA3FurXdAaeDDogYMOGp03Ub6dDAXaLy1wlfhuQDMeSF34WUZr"); - a("xFkLJUyrTGSDIu/TW5rsDF1Lo/RE1pobnINbKdK7+oSnINphspKe1grU/GuuNO3wglSJ5J2SFc32jUP8USOIzObl2fYlDyL97u"); - a("uv0Gk52xh3WDXmuFglS7mOnY+YXiPC2a33KF6obBQjnHEfc3mwYlG87o2JkL6jbfefXi81DcNM8J9UfUbrWR9kejZMx5pFO8zx"); - a("fBvA2em7R5qfygZ7tvgcUcgx/t2iwI5vOYeUWgR5uOgMIYtZ+E+9pPfKy4Byxqp+w6NiktPvJXliaGSRqI/xniiLnD90/B+ZmF"); - a("YUJUBw+VJvALvaaLROrOgUl86RWl2rVfohSS2xkfG4hy7IFsr+C6aV/ngkCOh9AUKDDRJu1JrDMZ5oyN2kVnyIn+rrcPuqbWuB"); - a("r/2iXZjsAwDKmdpRj3PpmlbUpWOazpbJ8YlcEgEYF0zNlGVp4fLK5WDz2m980Padf5B1g2VaPEcqQb1CFESO8QtEfWQ0SQw8IP"); - a("20BeRSkYLh6FENYAJwJzcH/CB5KBarVFuuPRTDFHwylB5HTIM5kaKFv/yPMImBi0FbFvFF4B9vFQ+GjtAknSKETsix8U6DTGIU"); - a("je35/SnHQA1yaW86seqzmZ4eYTephH4FlOAsrfh40Oj4MRJzwK58IUI99ia707nJxtcpTNtobm7uDMYxmRmnW07iS7ORfvqG7n"); - a("sTw+Sn6+aBfioo2QvBA8I4Aph4pQCVOCkL3/PVTyIPvPtJs2B/ZPODGsyLXqJMA93CGn+a6oevSJby94lJQ3nJmlHcMEpEl7p5"); - a("w9sHEb1V9YZBnt66MqrXZhNmz/8FoZRBW8ut9sg9a+X8JJOTb6XyC+9qZsCDuQvjYdpocXsC0a/nty5Gx6l8WAB7cY7HXth0KH"); - a("g2whmOKTKX4bxY+yx69HvKK5cd4Lgu1ouDKtKN/jrjwEVLyEGJQZX+ANUVuYpDBXwS9MaZCuFt1Fx+/CNmS/c8bkz1/srkxnJu"); - a("qAKpw1BuPiiiYeoiZSqYn8xSMryAaCFNyi25m2LQTkXDzSqNhcX90uo7qRRnWzn0N1L/DbPdqrOhWVVg0S9vQXISvFHeUrK2Tp"); - a("MNbhSSLwQzPd0NNpI2I0aBDNGa5D9s4c5H1uiXGfm/WLg7zPxa8ft7D8wpGBwVTpbKEvxsDOxuXspHak1ha6nX34B2Lcqhgr4G"); - a("jBKInQlRSS7kUtCG25HxrXQ7KXV/srt9PPo9ZSPKmxuKkzmS5vrKXlb06XCNAwslvb1tsbDRWOPN0BcKuOaNKS6D45auOvRvrK"); - a("Zo80ZjVthVoXgDw+fTOZyaLtr0FdGtzyvF8cbNfP+i9vJvtpp5tZ/yk4Isfy/a/pUETANt5isJemwf9R5ALYRRmJ1PSqAaTy5I"); - a("zk8neNo2oQOtekJcMp8EREgeWuRyUh6pDam0ZSETebglpLTOZk9Bpj+CMIASr22dgy0xqL4Gs1klzb6CzIa8IlGd5XC4KNM/NH"); - a("NgciiKlOW8P0GNnj6jdjDaQSTqv1dAItgOfpNCfRJ50AGClwf+nkPmZxDmYRrK9gN+mxwR5XL+ZHTmtwejfhWSL/xbU3uh3sH8"); - a("0F9tHlDaVRbbN0iBPs27+lM0r2s2t7oxVifbJ9KcsAmfnr++xvxnZ66gY9nSepqIvp53j+eyL0ta001JMcn4ZmJ8enoW78jXM/"); - a("SVf3k3jvG7V7nYEMfXc3rnndrnF8vAC4lfo9D9wk4/hRcWk0quP2om2Y0TJEcA3gC1NepMnzyZnifJKr9nkzn7RH3Os0lSrudU"); - a("e9j9NhL06HfDSSq6J/+ibIylDz6Z/isAcfLsYKYn/iYVj7FH+x2t1adp7Twct+HAKCDJ18qSCMbiKMgw3CaKEJdnuPHfxj5tk0"); - a("eHv4ZJyxqRejdPhCNhpofvMcpr95PvjzRG+ehz2lGAeXvouqHsqzvnnmQC+R+xrI0HO+t4Xeyy6mGpk9K7j+p+6luRLAWrgCB9"); - a("+fJOpPyeV992fjzxL1Z+aTqj+3b0JVm3Kt/VnwruxPxXgD9Pn7hdNZOvIEBvH0XXEq62nau2P3XyUuQ3gPh3F34fT5THJXiwWC"); - a("NYjjxTScM9c5Sa4cx01faJY7uEX7C7sLhUvaLi8z2+DzqRhHS3fd1uot5WGrJydF/8zPZC1krL2VcGlErKhBO+GnWdRAnfcO5f"); - a("Me819ZZBQG0ukDV2TeZPnM96kiXnb6K5pH69ouloaXX2t7CLWjFRnoi0FrDGAUJP/dfvfW25jS6CmJ97vqjQn2Oz9zvdJJW/Ux"); - a("iBTS4B1iGzxF7/5z+nZXPPp210Xi2iXZ1ly+wZep7b9P0b15HejjE3v/t3RvMvkaSrtCp3uJ3q+7tVfNoC27T7EG/sP7KKqcad"); - a("xG4UFdu+oiY0SORJCvKjdilEQPR4l+uGJvnmEz0LMlsBdCP6IpUzsAX3imPVed77kH4+6zbKEqvWbJFJiVafFMPbLFc/yUFk/O"); - a("6aGMBb9xOqD02+KZ4kRx0vj96x7MyH0TUIusRre37SRfqtAVl9F9789ZuE/THQvyl/yyPZg/yuEShX27ay9zNFmaW5wVGcdIKe"); - a("+aLMNAHPiIsOhmQc4E7xuZjHYzqQNf96ADa3IEf2oYTj8+arT1KNxbS0KFHoqk08Lh9GdK5DSGifSfqdiDyMX2FkTcQxTXQHEj"); - a("jLgNFHcj4sJ9ne93FxQRkYbp43X6d7rlO0l9W/HxYyyWvvmd4Ice2b+8BT9t6Pfj47BeuOY5VHPsSsJwR46kXMTX1Mqg3G9dT2"); - a("GS3uZ6vBXsTHcjI7AP482x394qb9/n22/f6v0Uqk2ptb6ipHW1C4oOqPT4+JMp8CdTu3OkwB/+OPoCHX8qRxr4kxnJioc/mZGB"); - a("2tFuJwfVLMW33zV1/EHb7xIQmvl+Whh6ZmYBnGBr7bdOWDg5UbdwUiTsm2DfE/y/Hs5KFdBeTFUcB2YzmTLpYPtlL8vhRG/7sm"); - a("Gl5Pd8zgTye6sl27K2GgM6FT7bM1ngKuPtD2h9XEiHDiKfF2RSu5kusbrXRTL+5owMN48nWN8PrKufPyGL7NvzQYQV7iom5LBp"); - a("Y6k/yaLsFOuRKgh7SE/+R5IbGGDaZkotlwsL/qr9sUjuiw77vviHVnTgq+MT74uXv2mgoxqvdMt42fnRdvwYNg6dAwBaKgLife"); - a("uIWIwx+8NZA3xBPwJtwJd2yG91+MG/i8UbvVfGKgVWsNXqCbj9sI/mpd04XFA/qnvMuAXd9eLar53QWK+cXtzaQvhl2JXxsuFr"); - a("WsUm/PJqhga139npb5iQW5L3Y3U7vwcL5Z+U4kn7CY/xbkt8kZunENKdEr9R120PoFajYY/eLhoVYKp2e4x2xZN7hRunDiIXeG"); - a("vV7v+mNxr2O79UrQhROdBjf1539RACL7iHz8QT2T1qj7NyLMYlXIx1RDvujBVzjozWY+NsQYHOag2dct1+jemdI188b0CnDXMR"); - a("wlyEMBchzAWYlAn9y+g37lg5PvRBRYQRAU8gUIPiOM0Fi/IWP712e0nQzmwpIS2VDlyIpEo7YkLHwCheVao/78ulI/zsRHs8lA"); - a("Rgo6crJB6mv2D5DBjUQUe/qTxkBpRIJ0drewaREulQKJF+UZx/RGC0nw0aFK+Jin/V2q/ApI14Ea2di2dp/MLuZsmkznMa5hwV"); - a("xTuCNhPKTVThsBk1lZOjQwNp1EJ5mKJcHDUoMICi0HZJ8HjPi3D5m8DCkk1/j/Vx3sXZ00/6h35ilOcCoauGx/Q/r2cpyDZ1eg"); - a("q9nefs6nqK0Cv0Ex+cMfOb/Bbgo+FuKz+mMFgpFJ9/RMVVxcEf/Zjzy/EqjV/Mi7mnP5tG5iB9NEpoC6d10yh5pyJtKhG/ySiL"); - a("X0vZiShbHDrbp6wQOFsNR/nBpIIX4IW2266WZ32/HDYw0X7eqf310AT7T4lG+3lRPV/9OplahLnW+nSwquj8eAh90lI3NvSw8S"); - a("rMsXyo+/BbkMxHYJyAhnIO34ukCJosrbZ6/kgnN024p3byhXHyAV6N70RO7LucuQBD+KUotIlXZJf+8uhQp4SE5zkfudngFVaw"); - a("2qn90yy1Gf/8Z+SHHIK2Nia/zP2mcEmj3T9FbQIHx+/lI+0YPsU6hvCRZIivAR8nZrONeT6ycHqm1jlYT8fHCE6X7JBR8CSQgE"); - a("/8392/wvHuXyOhKa2Ng9doebfK5BqkWq64mBWNlcEWz3GO2KuXR1xM8mxXr3DCu9fT69Doip/a7159+WeOPT3FfJGZJT2iDRFW"); - a("fQJ7fSA6eoFSrg81BPcq0bU4dVjX6yV4GEokb9A7qq/1ukr4wwu0W9atkD3gyjemINTnulUx+q7YYXrzUjulc11MVoeMzltXNd"); - a("1WR3CdrYrLG0Ymx+TLEe8Otoz6i2E5STUoPSHIM4D+Br3bg80xRdxCP6QI6fJK0SHTjANvh6ldTE00PA9lIKdQ/YS+d1+jU4pb"); - a("EBCe/DCgdn8qtMxrLaJvlvXTSWb0j0eExML48utkfiyx/EgnzSXxa4rqgetUZlCyPo0jYoVt+E1KRak546VS24xL9li3nm6dvB"); - a("MTFnQ2q2Q1Z/DKhgk6udW7jSaoXMqdbHMyGS7zboNISWy5Uh7wbcR342H+NkYURI0vkd2jrL5q4r/ndvsbZqBjGVc+43Sw/YSf"); - a("ybth4SLLUok7vkv5jRvnZQ0LWA41C7MLrswSWAj8KpnUvjdfwyKc2Kaljv/s7b1RlMPnp8gLMDwExhersdfVCyfrqAwJWP+k0D"); - a("5BR638qOxzaCk/XON8qMn+2+/jszBgCe7b6l0+8KZ4l284S7zLb1BC1RrXtNkR7/4NIClCW+GZUj9jivqaWj9jqvo6vn7G8eor"); - a("p35Gjv4V8niCMzxiTZX6JCfLp31wSDSqshQFZxTJLJkMSz2EZWVEFkecCuMWtrs/6WHL/Tvm1f/NiWpRmd4ja286CfbdMNrPOp"); - a("neegSO1hae5FTcKvN7+kn8nn4Szp4IC9mTHCF74lE3NUXf+T6LkR78Bmb4aC/fYFxSdpNss9SvA4zi83GIW9avq+/ox343+jJ1"); - a("uBQLmjjchq12+t4IfGUaD7zrwP0OeBvQjPtdd4xcEBxTWjc3davO6wn8HGMjuAVzC16JsYf6Ou5VmhQh4hJUoR9LAtHimtdtum"); - a("5BKJL444eL090Q2EX9tvol1A0PmDx5Q8j0ST3JLzcC45mgAuNxGwL0oYDC/Pjyd7N6E8vffePi8WvXvnDZx89+nqVtMai2Rfy2"); - a("q+3xWSI4QDJjl1DbircT+4rcU1QijwCw3FYAcjmWenj3Rx2cl6SsYuoAmWi3Fshycnyntf5sEd9hjc/SV8tLOqHZRIEE48v+xo"); - a("b140+kzcRwaiKMMISzzG7dbh2cDH/IexEp3brdY3XrZj8v8V1XuzgiWEFy5Wxo430H1USGy6h/tOpRqFCtqPj9+XiovT92+X8r"); - a("L21aNJIM/WO1XmiFVE2Ghls8tpk6FzILjNC+ObZoII01m6U9eIRQkZLfN42I3b/eQcLPxKgIQ6J3AUZisswr3LkOMcOmbQ1HBs"); - a("p9eZ0zhgJ0UP861DI3969H5lT9iy0aSHtJ9S+f+tdxkP07Y4jkZ52MgOrowe7Pdj4Wy8Pc+xW0laFORHwhTJqVJ+R6YSZLLstn"); - a("41+CVhG/pyC4Hj7tKqeWlL2lUhm4DlzJxda90zLTFZk2PKlu4MnmsXDxXCfY3a33D0At58eOfyPU3YGpUF53YEt8PDNfK1T9bb"); - a("TC3qEurDPfYyTzSF1KVFn7fK0cdLD86fg4mWHDyWTgpL/scyNe8d+K89ZXjjXHIw50QI6PuAz8Gzi7gWfkOMbO+Lzs2PP8iXZ1"); - a("dPt5/YgzE6xPde+ik1fB37McSuf0QIvQOR0KP9Os21e0gi/UYpsboBPvlYpDEbf9P57Rb/v+YLz2l8r2G1pk+4TfNl5Ktw7HLT"); - a("Y4bPef2f2PF/Rn8HKdiP80NT3BfdbOf+JrT2ACdY+qh10xdAEzOghH34Lobwj8rt1C54Cb/+RHrp4VGwrRlL7xY993Svtz2Hqb"); - a("OgcFvW/5yua+5UvGDo/sxKn5HvZEGMbfjZbi7nyDmuOOYh9/S9095TUq6N3sK0O809uxbGk7hu/MpSkbL2uHiP7mfO9bFfdSIt"); - a("cyqRlBUqDWG1qBhmwzQTaPZAbAfnmGJDB/FLLZ2m5PkdtBPuCoUA74O2zLkLP8Xm379vno/SHBfGRkTU7iRrXLz5Vi6yvTEumz"); - a("SnxT8xPLb/gZNwaNTopC9U3HJrHiJjUhafElkIbXT2FQ7aQ4457fxvOy3leG/8ksjo6SGZX2SsagEqnm0o5xxfSsjzM9b3FFTm"); - a("/7sqVtPD2pGy9rKw9jLvO96yvCnIoKMD9iHvUGB9sbfPwkMQt+yF2L4zDG7PseaqWRAcFGka6zioFXjTDpTZZhikIljX6ky4Nk"); - a("t+b63uEwT+chtUsbHa4Hmnn4ZnwudOJRP32OgFaFaTArJtnAGn6SQFQbIjFefH9A4tAghSA2/Ph4Z+LzdlWKSk98vlZocNHO/+"); - a("xcrZa46ehrrSeMOD+G33Qk1vb0yJ5mRWXgVEXOLPeLPCT0e7+G+YCoIqUnNAlSOqOJSakWtt1c3brs/+1oNyH/Z0PuQdPzWCCe"); - a("ahRAvNKYiJ5nJh08PS9U9DyB//8keX4LJP1X91X7Oc4LxvVhfsjCq0MXg9/1kqTn8p2yErqxCR4pO4trdzhLyFVx7X/yXvg6hd"); - a("246Orv4x+9jH4meiyc/xG/NLgLgsyNojJ/pjIleT9Uh3S+4otYcv3egO30ODwxycHD/gGcI+O7Bt88+q38Dfz9xiE3qS8cieeD"); - a("34dXYz7WYD4aMR9tmA/MS6DDUE3t64nY2Hwx5AGM002Z1O/nuN8VRTyg0i5MllMNqKJ/UEA/QnfOlV5Cw4xYfXyXvsRwz9Wozl"); - a("Xb+Nytibneo+V87XDQcY0ciw0sgUPfHnqF7euB+B7zhJvmu1PNt66sOJWosIRce3MH6ukLvo/W9jf/W8X8Q8bCmH8qg3fhWP23"); - a("owQOrAYOrAEONKJjbcAB4ALmQOKA/f0/2nuw/j7JFslgLjQwAsEaDuLo4EcNAExHerUf3BnfBehsf6i4NNhORrZKQmOd6qs4NN"); - a("+JSS0oLQhuLG76NMWLF5Kmz1JmhUa6ZwVHcsr4TRDAR0IT0pHgT0/HI6wbSeeWwmoxVeIPjk2inN7xjcX4PCc435EeK5IRWkbP"); - a("POylJsl1RyPkKYMYJl8p1LlQKUAaqL4A0kDU7rODNBwgDUSKDaSBBNJwKgSQmpFGIA0HrsYHSfELQ6Xzl+2lk0TlOF/Zm8XBth"); - a("LUCRsBxbARUOJsK4aNAL+zKfhmZBj5pGPR/EgylD90JcEcq/RHXH33DRBurV+fXzXP1UC+FmtevYXyVJSGzpp3eVHDwmhB3gHX"); - a("bdc66Bnl0qhxrw+dXxrsoOElj5CY83mQrjdH+pPStRS8HRbkfVT9DunjnmCqr3Ii1RWOV48b9VCZz1EmWDUPNHp7wMXP5rhpyS"); - a("5Zdejt9nTxDA/VSfEgny0esENAgho2kQyVUVoXec2BYf6G06sPEAGAh9zISGHWIeT2h9ZSRo4lRYKyd3GYIrGM6ry8j10rh7Ld"); - a("oW5Ihof8lJ8c77dDaGgluZuB8AGnwUdTtJ18WH/CewkKbCsKflUQ/LEoGCku+6G47G14f/JNatKq/YDF2Q3vSWW6XUnT/Tyvt2"); - a("os1bc3tq3qAZHPwEOOOPM+XpoRB5bq7QxHR3Avw5G3O5ACDZDUvO9dRbvz9lX/mXoFfCerSnntlaMxL2dhEDBWRcHPuCaNzF9J"); - a("h0UwL43Bqh4Dl0JOzoS9SmSq7WVa04epXhs+4z2a8dKndK9s8ihtuskCEwshF/lDhfPyC+cLvY9t+0nvY97SE6H3Mc/Q+8A2Mb"); - a("sUXwKZ5iSR6HppsJs/nU3a6H/0EqzIpEe2kr6kQ8UwCoIDqN22l3C5sBR6Ik1fYrH+Iie9tnCesQnkJMVKwKj3AEj9uZBrLWti"); - a("pKVhJgeJt/C9qUozyfp+MBHP6QtgrwTgLoQMSHT2AkPpgK5qnwxh/OnrPSFwCDRAFzlAhkO+JbiSKn3zePzPNmHbAugkpAgeAl"); - a("zc0yjenDCAI3NpM7ltT2/UzKEJFcyPpZcF88zfNv05P2pV4wekzElXT/7x/RlqS4R8Fnkl8laxRgV1flMH3UeE4NEu0DeFEeYW"); - a("MG85NG+be3qjtklSnNt44yGln+Rw3Nl3E8HKnPT4dSt/XExL66JLR/DBLOP+avQDwzm0g3TTq+a7VpL1A3jfpS1A2kufTXzByg"); - a("lZmEdRaKEs1PEBpVSVOipgAXY+kJPetWeVwpEokzPN14a+lp01H9VJt12CAiDdyT67RoMXTyVAvbTIebxOpdmas0qDVfO7qgEL"); - a("AdVwPQI4ZU2qrZrnqHKjbbyEAmU/2MNlqAou72s9q5QN1niBPZxJew5ZYrpThnwCylZekAzpH1sFINqjnKpACAu6YZ8f83oaZp"); - a("6PyBD7FKDwQegvsrEOLXmPrjK4Z1v/ujrx5XVrX6LDQlLFQFAkumBHCkj+03yFKE1iueFJoVriKuCEdzI5zE+LZEam0N06I/VG"); - a("A793vkf4De6+kLHq0HduD6qgkVLQ2MeHCcA8R8WksIVUGt0diUtpvAGLow95n9OM+VaiiLqW/NgbrXlJHA1Gi1S10R+W4uR3z1"); - a("/Ncyaky5zdbV64I3O0qtdZL88Mp+q1fb0Wmdbr50gENpI+p6NP+ENDktSXPwR4CQDUAbTFmiMIZ4VSsHGnmCBDrUgGArvJCQCW"); - a("PmqQZmCDqM8gmThg5PZFF+LrC/+tnobw0NrepIBLLzgPBem8Q2mq94n0meeRPnPGYTcJAYQnoPSk7POZ91PdA3PNq8t56k4g2j"); - a("K/XTyAsVTBHu3+p4wHsEIZdc6TRhRbtzg2tsTvVYnhMupeowTQ2Lw7Hsz93B9c2s0W/N8nSzLenCjd6FrZqx3VPf8Hvu+QXcfi"); - a("G5UG2P1AWq3baTVgdcn9tKZgPVJcEQ2+PkxFRi7jcxXMivLhq9lHZ/quM33ON30b94L9RjT2Anke9YdSkvDMrFfiE7I+RF0G4L"); - a("hU5oyMwc+voogIuApedNa+RovdWeTyfh725n2x9PfUhaJgVlF9T1+3cH9oqfUmZKc3vKH+9HsegOGCyGh/AJeOSc+R8UlPYFAr"); - a("olk+JmynIvb9V5K0AG2+bdcbxGkutIoiU4Qy7rwq7E/dSH98CadruUiMedbx2JE/Pv28aZ6zqqDmpTpKCQzUyenxlsMeBteDBr"); - a("4T5PrQH2IpmYlOx9qnoCuVXNFOdRfz4XYmSatdhUCVBxI9g0HTcy5IsuaM//77bfz7MvyWHGB9SI1/nu/Gj1WhApvPBKH92EPa"); - a("j+/CU5UMU9U0CTU4i0Xc9AXoICfh0L5Be1Yjhp3E/hzM34OpAjSl3cKV1SFsVaUEBqY6rlMLyU8mpW+NOuRCekAupIzfSVbmEL"); - a("62i36EuB8Sbe32bEge6ICSUounb3CQ+rh23dv38JdVbp88oNsiaD6qP1sE/55+6s/XkT/CKX3rp047JpF+6hPXqkH99reo6oRe"); - a("h0U/tRHKbNw/pW972QPIOY+9DxWywjrLILe++j/Qt72jGVV/NLnv/vzs6ET92bpI9Wcc9efnB6z96f6t7E/FeAP0HY3Cfoahb5"); - a("uu7dnn6EffVvEjpK/D2ipUOh2qtumGqu1UVrUNCz3bdMjLz3iZoHgd+gksOLGTBOKhGMOKth9a+QT28yX47MTCGm4yrNTmULe2"); - a("k/Yrn54J1n+kr/XfKOZHE/PT3Wtf/1itcul3TDCWPqaOVv4tOHEplXQhClDMDEQJqoZIIZh8gkEGGlJ/Cy69kMBLU9aUvlPWlB"); - a("4A+dD5gyfKhS0mpdtu6S3++0C3X5j87ha23ohxrRlC2hrbetPYBIyU0e6krUhm7CHLohQnBa81ofPaTTqv6hlB6byyzKnlkYHl"); - a("rk+9B6N2yFTMkMVg8r9rn7Jq3H9hzyS02B05XNiZvD6dLUy2eqCpII0EJO9BAAeEj/uyZ4IVI5zdXXgEmyp08+hA7V6hnWqPbb"); - a("Ff646kUFtKL1yKWTh4599ugdlGn4Hufh/bF/L68n1uLE8Y50Cr7sgkXwh/B/Cd7zz0BarJ5L/El9cU+MaXf056gPit6aSy7MVR"); - a("cIB2yxEWO0Dx1sfQzv2w6vzSc2qJ2OwdSdY/8j5Heas5b+3p9+CDkSK1ASEfaAChc8TF8Hm7EZFOEQJDhskoNxuR+0TH78UC75"); - a("RUvh0+D7V5WAL4tFmoRNrJC1yLEsOoxId/E1B27wOUgWNhr/D2F0z2KP/mxE/qI/jhmSGfJK3IybAPfQUhTWzLzch8PgpqNx4m"); - a("GpErxM3gz7GAH5/+/HFXAvn9oQuosfy/9d0/5JlOeQZQHmmWfOihFFOnv97eFpWBhy1Pevb3xVT3XpqsjIH8cwhThRzVtEVeHQ"); - a("P4NDLChGMYRd/bw0U37FFFs8P6kGaSRaUTeZSatHwdoJsVQPHtsaGFEm5hHNubatSre4OqewQJVN0OED47P1KREFaEeWwUMrNq"); - a("VoHr7vUVk7Fas3E5ID7IbYfGJLmRlCmkg7QmeLANQxY15kbEvkp9+ee6A8mrnety1OnIZH+F4w7eHmWmtvtQnbfx1KH98zYS6X"); - a("9+0RtFIEdLRcA6dYnlG/k24QdS+YNvaKOonhDqGUr1sM5QYCIWStUzaqHcvJoXyk2r1UIpzBT9+WCvvkBKUECbl8m2d0gNic8Y"); - a("GkTh8ZGNjxxtK30E6ZFwsVg5x9LK6VNCEO/7tTdmMs+UDEHPcAM3+tCv0dqFqbjICcjD+sq8QbcyrcbnRlb6wt4BkEGNCRtW7h"); - a("V6271E+d/C8PP6AXLAlEDcC5LFfuPKz3v7knew2VuVYiz/rt3VMOWUpCYTv93c8Ml/YMG2dt3Yu7YckEh50v+NHfNayJpplxzd"); - a("tz37EMCYmplIHqRNu/qz3gT6SGabAG2GTQAaOC1VHHI7DBHsLuKJyP1EKgp0aJfu5xm9lCN5ozwGwQ6kZ3HzLmEzoE0UwiidgQ"); - a("MV7Q3HoePtjsAoHbdX3gm0XTaK22wP03Bw9759lnk13NaI/QIilOyApbwKDDNXgnMeiWd73MLSauVpOJbH6CNprI+kBZu5yunP"); - a("8FIRI+3LJCQcCNZf/sVa9WYR6cnkrgTyZK/S4Ztfh/PLO8hfe4aySGJY8kAE/FMIeA179i0wosgf5fhY4d3B3A21tuLbAwxk6q"); - a("0todZ+lSEuO6hXt3bT8Uzf9lMVPVYk0GUmgahH3EFOp2sHj9uSKNQMpgqjBGSPgNrB45bmXi3HaugpPyQ5aKg+hrwgzBHgvsA3"); - a("lZ98qx8ML8tIREclMbf3F1ThpX2MQ4PF+Yz3l9XKpp08/4EG5QgDY0NgCyxHu/5pm3Ux+U/kTMY1GgQrB/RqXWJ7Ejmm8U7/Dc"); - a("Z73wge7xwx3jk03gt5HC6xWIuw3Y82ag8Ukl/EQo8OlDW9WqTPiJveOoMNtzNMFROobe2dZ/lymMP4OJyjpo9k+305cez32ez/"); - a("5ToqpqBQrnarqCeX6xnDUT+M4HrYce+ystIobetx62P3tR3iPuaplyY48kgSaG0U6eIx44WveqPsC4C3I98oYV9lhGf5LhyKg/"); - a("AkIP2+Mj48wj5/MYyW87brxVKPtmOJYiTZ02dob/WV3gDzrdGPeqMy0WbvQspz446cSbAlh5Z4ykOzPcGe8rxmWFupL2IbFldF"); - a("DRsW85UNi9G9IjYXsdKGheAZnI9TK7+1t1PnQoUzmr51L4O0Oz7yelStp8at9dMDfdSaJWu1W8aw84fQdT3COl5EhrUd29SQ2P"); - a("1RcPnaBaW968zfvlJnHP9whrV/eGwPDJHL9f40QChQ9vwwoSoRlKKGBVH4vdbtqeYQLVn/BNlZ7+FiTYaSSgGkwahUUf4Cd6Vb"); - a("lhey/1h/EP9f+pqZgNj5Z29PV+hghxf4uhzHx9qZpbgJ1paVfisgPZMuZadRa4r8TRbkj/1I6jC7ATOg9dTzWeWhqKB9H8XQNL"); - a("O8Pcvaq2MwkY4SrVfYB38OsBFtvABTjBcnyAQ/ezffQs8yWbMPWE3iH32pOv89WwvqNDTisFiz/z1c3hh65odjXfIalKYL4VzB"); - a("0NWLZFCiziYGfRbR+AIwGdhd5ZT+BUFW09McCPGxUInBSfzwrIvFn9ds95VVdv0Q5WKBBuKX8jEkdCe/+/3Ul39JZmCu9BHxQr"); - a("Lg4XiNwUEV1sF5Y74anLtvpveNLuvgVC2n8+XuwlIW3z1KDNJYGiA208HoqMaI6FMC5RDLfamdHJ1AyIjKLrIxyvvi916nMv43"); - a("/KIlNn5Rq2eO02ByDaVirGbrx0jGspA8gg2QZ2MhhRPykL6vxXl0w2EWHpLt/YxsebiEroc6b2CbL2KfxVW5gP0qxJKrbiw+oU"); - a("Jynng7zwWT8v7HWI1Xfl3zZ8ZKqPAKtnZxKGUCCIesShwIDqGq8ue5qwZynfPcLOsDTZanfA2zcrUnv3Rw+xUOLpTJYzMrk9bm"); - a("M/xmwVZG7tGEAbzhJLY6RICv+FqK/Kj53O0pJd5VYDBdii9HyMjbF/8+MonkXHkTb/0LX5Tkgtuzm/mYjMrc7gJxLtmszhtx71"); - a("tAawbBA/qWLijbyQZRYw+eR7P+kaG/hKYh+XHanwRj4FkkwTvnl+VhddOync+26FPZCOhYEVBFtSNqtTOSlNOoAFXyZaZqilvX"); - a("OyT5KxVwFodjqW9eATj40q9wi6C/mKDwo8yxLg6VMC392e1EKQKpJcEdkfSivN3V7wrfO1YTkWgqsT24DpxipTfjtxFU0MfZX3"); - a("Ma+6lPjcdClnWfJd8YIRmvaKy0b/sjTzQo65/QrE6VhgoJEcR6IHJh95SpwOujP2JtGPlRHQh60S6DoN+HZkUbiN/WQyJ8ZxlA"); - a("vqEDGZ+DG+99HMvIx1bYZvmEexwsPB+TiVwsZrdymeMeSoblY5+4/w38arPjVwJ4RtvhcQOcwxQ4TW6+aRDRSH0pyeOoiYXMQq"); - a("9rl6BSN5vICXlE99IjqWuiynNtv/ndtvz281q884N2K2dsoZuycnaDDNYd8Na5ageM3EDvnZ9Zd8DKpTT53byN96PPPXTVF+Bk"); - a("/uMpxVIwv8/GeT8rIfbnr6jQ9SgEZOTXgn/+ic06f+MEAfqZdCdAejw7+B6+g/3raBOZCHnZEaC8RzTQ1U+7cmsvve1QmFVwhg"); - a("zmSXML/yXkLFCbtJRkxAI72C4ImJY924lpeZ5kx0bwBQbpdvzwzvY4xgfN4kUsh30YDH1TZFjHP0rVpVu0MIZaaK0kWmRWYu3S"); - a("3mWIkM3yMJdgPEtpaG560jKedv8NBPYEynv8k2oYH35UDeN5PIwMk2UcP3qEQPGkMy//KHSQIttEZKbq1Tjq1Xc3yXF7ydq3sy"); - a("Xz3OKswdqfGgyZ9sQTqj92+zZL29GnDhzWuF90nkE5H5Wb/YTqW+sjqm+zYvk1tTAzhPMXO1HDGYb3R7DScQTAKsaSIrlHYquY"); - a("/NmMEf3SqtehX0gTfSqM6iwXsJ8AFsT4UafqWrz7zbQo0OnvnxM6zQTcqxHSDqPBLOv2AVofwD2RLMuhHfouDm4L7kS+eso3W0"); - a("AZbZc2yQaUh5G/+gM+//TYCI2dPyzHCxAcQxAEDl8jV/a5y4TtkAcfZo/pg5BabvD6JzyIZX92stAyQi7xujnDLbmW3fRIFgb6"); - a("sDhiWrn06zH09c8AsgcV5nt3VE0QC+MZirvtIUKFUi7PLLsnBvACbEWGMGUYLAudKQpVUtwFXGhup3hVmuEOHCkSL6XE05CoQ8"); - a("JKVTcC2sgkUvEQufIo1y8eQ+RITr8Q6dpy8jR/KVnd6FvftkObmpxIP7VHnqe1Fjhb4qMtfNqHLhOUh85rTFsHOVhFjY3B6KP6"); - a("/kqMasFdguMYFsdgN7c4PYhIRswkRrMro4DbTWxLNAJ5CDc+neEV3u12fbbUrE5+tBnT2f97j8IHlNM+4XKf4kc99gj1STdg4P"); - a("fZeu8O+f7EaC9bt9ozueStft7fOwV91/AjAHjXIBSenF3gt2HR3UeSdHntFeX4JKKLGe+uuFDcQdnfNXuqdEcgCin8ywAkTz3b"); - a("3pIenUenonoRxkmHIVv/Hr+AsCodbPWQasw0JHvSW7hbJ3MdSBUQhgChnfja7eFeDUF21r+6TARg3xwBNQI2ewasb6XUxFHgJh"); - a("Swq1rhlkXXj12Rn5K7iHPoDeN7Fh8ArFcIpXcBwZDl+JCErBOSWXJbzxSGRjLm0vLN7mAmgc9V9L2ouSKV3kOe5J5PjuobONOw"); - a("OPRL6XFguqReRqm0l/D3qUQhR2/rpYY9LzpQbQlnqVmCi97RltzA/O2rANAx2ISDLXWNHtfdrZhXFMqUOT1KG4+Ux6A1UrahuL"); - a("bLaVRknEe1E7aQ1PUusMP4wJJyhsjT4OsRz/ifASizVLN9fbdpsyz6Vbb3j2g/7xuKBvjxrNHi3eaQasfSOjfw2FW3X/eEdPtv"); - a("6MDK547lCOatc9V16mmLEYGJG4w6nF1vIlbR4HlBjNk6iHIRGTBiZ1DsUyK2LezHfPuFSax2mtb1gup0Sr3QNopbLdpqpwcNPp"); - a("pw4wxQG+LaVFzeusBJtpx4shW5QGcRz/bFD39YPLikEdiRFPwVu+PduhWaJ/llYpv9ZSIuvX31QOL3NqkPi7HWaJxj/Xqfe73Q"); - a("iX3jfHwSXZVMig56MzIEiqTnOo03MUwSt3v0xfKkcpXlEVvaHy8/nbfG6JYkno+t2FBqoYuP8FgKP5YPovNQGEid+iSy6AB5QM"); - a("i0yQ9y0ZO2ctGLKfsSyp78IGW/mGpsTb0D0fhHwd9yUPVq369RyZeruJJLt6rKP6f4DSL+bFGLf0ts0UWb+UX3CvzIvmP/Zleq"); - a("y5o7RZavPwQ82fuoKxmf4nqIqEMxjNrru23W1+znz3a0p+17UG2RlnQPpW+1pSt5FGo8cppKt79nBzTsT74PeX8q+NC0P6H6c6"); - a("n6+Q+qY1/779Sx75hW73469oW8+/k8u1+cZ4f+TjAn5qLL+YH91Z0868cgIyp0UIX5SEH4hw46L4twD4WPQnjaJphmPfYTHqY7"); - a("CfgNeVQw9cWNScxOHBQauh/R0fbIAIz7HoY3Xevay7XcQQU+QhiFz6LwtZt5Cn6J2rEbPbynl06HIaRAHgj5b6Y8B+5TvtNy0C"); - a("WD32LqF/KeT3mn3Sf6diPayL94f/U2JJxOCQsRAfQ4DmH6R+9tFH2uiD5aRrekXgp3D046b1J/k1epgb3hPjWwUwkKdZ62jO9T"); - a("9woYftxjHt+vDvCQ5VC9N73LEDz3AY2vmPuhH9DHQ7kk4ozR/DO+hPyNJwfI/Tt8yqfSbPDDmHqWZ9GdD8NViURH4E10oxoh48"); - a("Jxj2jwaap37e96ibAOw/c19H1oLpW1XFit/rbV+4RExn/w8xPvPsQU0+bcJV6ksumhUvf3gzjehMpJ98/1Gv5MdNSQsf3migHl"); - a("y7CYotWcVI7b4tH4UzGw/LhodYUrMiZsXMMjF4fLEc6ODojMxt5YvuzKCdmO6aLY6W9HK8eiXPVon+s1euTZ/aHv3SvRHhVA0S"); - a("yVLa389N4BVYN2utypH0I2PzLPt/EXyBh2vYgc9CqUA8H6k2QAVeDd048gb6ED2zgeTxtjEIHYtXIwanwD2zmpHLOGH9Qu2Doe"); - a("ucEqfoUcriYxNIZZh3JqgGDIktTFnj/FnD+kcvZVf7o5v89agIJtMfkHqfz68+JoXegod11c+Y6ig/Kn2xjPn+6QXcAJPs2Rz+"); - a("8XihRD5c1fgM6+0u6wqExMvpLv4dSGvGul+4QdOMiHGL7/y+Z2a8vGWiVBCgQH/jSbJEh5OKEsyA1oUzsvRcmCHLz8Zmj2WLz6"); - a("TAIRomXglM5tFOODj+zD4JwNsEMK82tm8POT/h2Qqe1f1tM+307z/LleUPNteZ+WsrrQhBqrLECa/BfMs7+p2O1fvZbg/JdIf0"); - a("a9RUHDJMcQMhZ+5mVf+fl1Qvf0blfdsyqWYS6obykvCnaXT3Q5XK81BtP+zD47loes2YKtUJO/biZ02mx+RTibNNX6amNwQOTc"); - a("sNkGAKpF3OlGnAdxiCC9nnMLFZJO/DmQNHODFUlvuYJoqNk63gJhTZTMoWodr/ZG46d1aS8jTdgfwJrrXxvHNF8L1Hwlsues/W"); - a("Uf+2oqa5d8Xunv9ny4vYsx/WGX/1LnvRaLLzhr+lnUBjDve5fbTm+Qfj7SfVc0uo+hgVM5jPRTkM4JO80V2Nabl152/8hWObUB"); - a("FWPZ0dwv6a9reYWITak4q6uBOqO2J545ZfsO0VKIfTzdNEOjinjNmEciMkv3Q/MnkpMa8wrUXPINnzPnUVwqxSnfNJdQ3Hcv95"); - a("p909xBcR8hLvzvrN9X447fCziKAkNVgnV+9iSen/fjp9vt37+U6L7BsmvGnVznckm5AzY3jyxkgjiUxAbIJKIjwbjDInBpWNBy"); - a("kJNrdhGveFttTzQwGQtNO1MttJcvweg9/aZ1oR1ejo64XvBucz3h3RFZwYefKwaQv1UkaA/09korjBP5qLvDTLrj2/PEotyvP+"); - a("ukmDEllDp+itOR791fQTTg6zMUaOMJtJE20G6+jGmAMiFifz+Sk74uMV4G26DOSnrX14+Ki54Kn8z8CH6dKajtGXJdJtbBkIo0"); - a("/E0PDGH7u7vp0BwBL0A0oredZtozgusAe9m70md1GkCo21qFt97RwsKgkdnKQbDTm9OotVbxBPTNe6gnyv0AtSnY2Gnph53i2O"); - a("v75y5V36vbEtXXv33hDWt6haGg1xHo194mAWFzEINT4InCVxxGjd+FoNHEWCRB0cT5Yli54e/OlxK7x+H0rZm3rQje0JWh5hqn"); - a("Lfdn5twGftORPaE9W/iverE3gf1UzazjELY54K/tyXDd6sBOO74RaB7B25evLOVmqKJGccbr+krYk46Mlv00l653WiJkP7bY2u"); - a("gC+0suLPTqaSdiVjqZ15Mk435Pcb8WcSky7laKKxdxg2TcYoo7j+Okwftu2ZKkQzz/L/RGu44zvFXf/gM/mG5hfSMqf4hRXlss"); - a("0zZ+RqkZlPqDzpu6gNKaRco+6sUWh1GO2BWSX9V1vbLfZxsOnFFqe5IXj7AOHMoZ4/EAIccwY3y1aB/j+pllXOPmctUtAdLYck"); - a("bGq3E9nr6Hh9emy+9xUs6C9SsOMMbJC6JVXhH7t7RsE8lneJftc6DWqgGv0k8kKfix5Fj6eqCryxdFxeHUN79J30M1rkVILKaw"); - a("xGIC+6o4X/YYInLFwR+67hLn78Kx+YVZlXNICL6IRY1msrtkZfmwMKtO6GvvyVM0vQSnX82z3krT/3op0fTWwrG8QnCwx/F+Uj"); - a("u0tWHWu8jl/5ZagXPrsWSIoKTsdUhTaTPreqNFzl+NhWWaYuf6oknf1kVdt5fHcSCGw12PZTDt9o+fO1h7V/bDJ+v//U3p6dXr"); - a("lq7ui2vpKr7+zt8Oun2J5zYwzAblEKj+WPBD+4Lhv7hvtsW7b/7hK/N986xT1JRfdD75e222TvlLF/N9sygkFJ7U1VAiqWh8Rr"); - a("a8epZqa4+2XjtniKtlvu3aiXoT3jujaFvb8mOv/d558Po2DTNLtbMBEhA/W6tC76W+KEJ0u3TR7XKQcbtUZwkbvwJdu32pEmaN"); - a("l16dID3kwxB5sg0+s5m/QfbHlAu5DwOYiLu+tZ5Q4+JboEd3BIuaC7MN8pbXzce0P52s5vfXc1DtVY3W+d0KhZHIcKMCRTBRfS"); - a("igVmR8/ZfVvcIQbN3qBOcHm/85MVsrvDnFIebkFQsFwZ7ikJMwuDhUQJ+aVP5QZmOFeKDfF7qT7ERww1OuIFhJzHMnQzSWv0va"); - a("ycZQ6Svi8eEwJvIw10TKMyEqKszm5tBdU/F3lU+2+PIHaO0Mk5qVfTwe16qe5vFYrQUQSDgeNRiPVfY3C9qkk+jBhnU68Zwj33"); - a("6RC9DxKDViOB6Xw7JaH5Y2rPdJ+u0ixGY0GI6hC3kqV9PSZQj3X87j8zh5MMt5WQgH133rkCWBpOLXo1CJXLqVxk2tlw221LgR"); - a("cgLfTjlR4dsgHD60A69Y8e1XFwLfxtjqk3hnlF5+NfnT/6xXvICr7CAS5iKOWBB45pEnOreNJ/YMMBEEYapX0573sn4rOpOTMQ"); - a("9qvu3rVR0YlHvZuPK4Ldi/QfHW0Oom37mh+nZ+eeSH0Wa56leo++zB+RcPWgSU/vGCSUBpmDaW1elAmwk+7w7w05Y4Ko7wNSAY"); - a("5PNEqMaQ1/LyIpi9pGbpDkfFsSS/NU1N109LMeCzXrZO18sXJBA7stt/xXMeACVjGtp1IqwR0OUI25eDuf8eYX9jEf+8skSY4a"); - a("jBjz/4aD3/PBXmn+fv5Z9XVh0gAN9SVknrqFUZpEZ5aRTDYJcHa+MATqElIYSLQze4u7YlGedQP+uCn5/N4J8JMItrX57Ay6si"); - a("szh024TVPHpe8upTEL2LU4CNs9hZOUnlT+/UvQC6lr/PyHgWuzKtewPP85sisPQ1vOa0YYEj0AZJLOZA6JtN08KI6Dyct3E2Pi"); - a("NJL+WGsilKvUGlBtXkjXLVXeOMm6ad/5V4mG0oHON6YfYY3EHoNRyPmxhwkmpgjNHCt/aaxRzkXGx5jk4Ar/AQBX6hxPvsgPvI"); - a("dVKwjiYcY0rTL+xNNFAQ6NM2VaHP2Fm0Xtfq6POoRJ+lc7GNYfy6JRwkcb8HTUOiZ5Q+JPQErW2noaA7h8lciguF1hAqXf45da"); - a("SOwoCnUcCzRsKDBFFzXbtIaFOArhGARqcoQBeXANCzDEAbJKCbocDd9TfKoiZKe/o7APVHEZmtBBpQHnwhnHpp0qvxTfm165oY"); - a("iMfZRuWs7JK6Nypgj7S4hw6+k5rwl11AoSJ9In7zd+K3Ma7yWi0pe5tEGVRb+kpaiIz+EIf9PEvnA/0aqCHt8PUYXxZRZ+3mV1"); - a("+jtbELZxpX3ZG0QEB8PFr2GnnS/QkrVIhFFhKLLCQWWUgsspBYZCGxyEK0yNRaT0wfJVGLm96j0s33F9bJkAcPtaEohKxNF6KR"); - a("VrHTRSa8e2QmpvOGNfp0viqnM3W27XYW976/VD9D2Q5AeM/sHRhIhYPRyEm1vekI5UQjRDTPMyHT0dT6mBetRPPW80haqIcBCC"); - a("01naOs9HLWY/3wIwIxdwppnVq7IMt6kYDB08BAivKsyGEon5ysoKw5B1AufsEK5afnShmMhYjwuF5oAbwW9WubP+rX/iN4jxmv"); - a("4E0Lefb7NmoK4vKQgHjvsQriDcWAuOl5K8TH6xDT/dH1oh1gO7+MOXVsGp4AOaKHzesUI147oYLuspHTFV9qFXCMUtZcxzSdOA"); - a("34Zpt1XpfIcmA/S+F0Ufg3g0XcG7tZQvEVvbEc2di1SE/kz5EZMhi3GbnSeybOx6Uk5Xev9v4W+34Zz97+sEd7hX+r1EdVgbj7"); - a("aylGDFNUo9jWVh9XDd52JkNSozhbOk0ljvB2jpOrmRl6MiKXzqMy7EZ4Daq7l6vTncvx+fIDJ2J2QwiSX6mS8KM0tkfL9mhHbd"); - a("dO3yCM5kfSdQajUDiqu8uhF1qzhnfnUwymIwoKdwml40kIqUlUWN8oPWfJgYY/xzV6dUAARWXYdQRdk+sliakHMl51tELGgrOJ"); - a("v/2cjoxNEhkfmgX8ifWLea90mUdzKnuYC9jfd8honOkpqet1EwPVgP6OLCZ2q2Uve7iXE2RnHE7d0BMyGB3q4Tu07FMJaqHCq6"); - a("OlxAdYhfFOkT5AvKuWQaeSbbFRQT8EJ5B5la+1mTkDSFfkFx8ozX0iRczIWGF9vUs7JJn1BdO0K9DxsFb4JTDO0Ad7j3WZZBnD"); - a("Dshc0h+/gWf0XuE/olmJq5S0et9SfiHhZ4PlRN4KNnPO5c1c7PHdnjnci9Ho9eO8Nn79awb5cWqpPJx/8Vssd61jV93vCfuklY"); - a("BYM0Uep4FCjKMVR8nBXSXmvd2PnGpwKQ/6B6y0+SNl2b8ZmwBHvlcLHEtpGGAHjYEar8+ccrzySmi8RnyhxiswXIiPk26AtsXP"); - a("eMRuPriOCpekBxrRA/RNjmsSd3/w9WoIj5VDiDym8eNsRYFolMrQ+HzOddgdxYmKF5Qe4BLPBlTFk/S5CVvr3QGqSUW4XjHuSa"); - a("ax9OWCUdTGsEsKYXgZKdcpQGCoubNjZEEfFdKuWkz01dVA1h64vbEmqE41uuux9XdOBdsK0CvTTro2GgWMLP8e08JhSGC+kw7N"); - a("ACHyOojR7uL3MEvarfCfoP38cwTDQj9hr9x3qhAQIwhKypuO5D/p4q8QUtbue4kNlz+73MniXf/s6GWXm9fp4ie7PaJhN8hDj4"); - a("M2wcHaF5uJfrcmE17qjGCmwjmb9E9FgGsIbU5EKyxqKfnI3SqfTqQh9ByG0LJiacn9g3BBijjmSFTrBKrlYuuw+zeJZPD6FDxy"); - a("imrWcsEPZ5L1TjfvfJ/zx80pxraQwxREbRGdsY8pPZIe6u1jHHIEVnRTjwBKTmwBh4muRtwMj3QjffgeqadTJEDR+GN3sjzwDp"); - a("OKJYaKyhBOv/U73Qar3d8+M9fKXdWwJ6+OhWZuSGpgHO3u62BIKCY1nXDcNaklMpySaVXs9LmObaQo/O8Ol7uuQZ38XIipOPj2"); - a("XIFjbIdTFSHlaFzZMLfF9kbx8T2aRYQru8XeqIGvG3BpQfmzzE250ZSMVU2pCOnBA0+nGXRMmibcXUg5BmUOg3Ht4Ps3PJCduH"); - a("+Z+sC6qYPk72Vnn+Pa9/k++L79iN9a17inwgXZCbw8XYc/aXsqnD2Lx3DG4E68qFJ2g1ryKXVOljoYZON9XjvsCespNQgfu/aj"); - a("fwL+rQ0w8m1x80XiUaxiKEl1ZNGfEyPFYVNeJbzTEplvjpcCPBRfpOLlDojI44H76EpwnOrKxWegK6V/sXblVS/bdO+Ozw3uF5"); - a("9G9IdPPolPwwifPmU3Bo02RLLLbzDU2neajUUu00EYNlsS4/Ovr14j+dev3ycVNfzPyhfxhz9SJ+o45+kF4jx9L1BsFabxcYFi"); - a("sRxrpbDBNU77SNihW5MK8AOETAMOVzOwdTrJaz9unYHpRbqRybWZ1On9V/ILhlbRTVIA/BL991NNL9Hc0tlg2fAxBKOa/5EoMG"); - a("IUeBlH8hmQ8xSa8oyWeb7NQJ5ep253sfQAPety7okfqdxdEDro6pCXnP3EIZCZPKZM6ynT3/hNnPNtNuXr2aby/YHyhaQv5mi6"); - a("626RJcNU1Y3bBHTnEnQLZLsn7TPVZ8rsp/ryVbt/wI7tym7jfGFTvgmUb4TKl4J8ICdNnPFWU8Z9W5Hxn4Ytyin7TPkeMOV7l/"); - a("I16/kQ26nlHGJSxKk1dfoxynuPKW+HttwtrgKc91RT3puQN3KVzIf3jRGcr53zXWPKN5vyeZWcMEQPgX2NDnG2bQS23WjCtqtO"); - a("o/fdx3Rsa5HYtqHA8BP4rjC+gXM7EDwEBOelb9FvWnkPr5Y1Wp0IPK5VisC92mIRWKX9EgFjIan1g8Vu3EWVehPf7UwPHPfK31"); - a("VCxEq/m3KnzXfSbtOds5NSjAcBvoIGSN7eeWcS633o54eOtczL+90yvne1E3PibJoCrDXuwYPgyeP7Xr9QdOkAF6+kTBo45p61"); - a("P8oZVjEk/MKA9Xk3pmGSuZqLZDXmXO8jV9dOcf1k1i0AkA8b6doVG1BAv8aGOf/1GxnGNurKxGedND/rsJTpWPlEkn4HbMNZko"); - a("839+7gU0+bwTVuJHZuUk2uKzBCmEMDoVu8jatsjKTraIIkQDz0DuK9XNZGh9aA1xhw/Ma8+wCfJo1R+HR4Lgq5H7FSr6oz5d2m"); - a("keal61ZMut7L2rdtvQy3G72sGOUX9wjh5/6WZCz9JuRRUytvNOrBGKXN6U5Rcw3VbH5wd628ETE5m2gMq51iDC93qjF01V2IL8"); - a("FPiIAnPFPwIMOE5uL9aA80c8TRNJ38Pxai52lvM0v7EBFdmsVr4rs7xcP1GnPzgaONoneHiQscgkqkDMsmtNz7pdVwug5wBcG6"); - a("eVHmbRMbh22Hgw95qNOBhIUiYYGR4NUQu0TELlKxYfl8WI/prhGcjgaqDRPZOVpN5JxTSP/uYX0iA3Iinz8doJa+D9w+IxzJRz"); - a("W8FGvW8ExUHC7qL02PcXOoCTO3qVruGSg8ggo7BW15UYjPqvvTGro/5da/63mBNflyAStd0zsczDCagkZUNJDF+G7wPa6tuKM3"); - a("yl8tntUOGXjOUT9/QpbIU6v5WSdB/yqlr2xTffWdDlP9flqi8huMkk6ZUNpt5BDnGP6sWbLaUTG/ZslzjsD58SEMAcI2qIIRDp"); - a("yoZ+EFcPObvACsxbQVb1PZOYgMzmgLczI1UDHJlNOn4I9Zlbh+Ao/1O58PxyeL/FtY8gvfC0vq/PJmScFn/5kDjdpF4g27TXsm"); - a("rAi37fyTFeX3OsFWfGUe/zwPJKT3uoX889Qi/nmeUNHsRLDbzHZkGDIBg6L9ghgpk5C11W4HyyfdmKHQ9KkTgaarHrDSm2H5gt"); - a("6MNtM92PMpWJEyYYpzeqbrVg9uqROjwkeq43jTwQnjFudyMiCwQPcs+RAcOyC8n0lD3WvCBZK/zLtfmvd4dhNo1KQUJo1TRypQ"); - a("kwjUH/9oBbXsNBCXvcniNPMl6vaXNcqaFlJNnyQbZxMfLLpB7FVPLqbkRlnyrdi04yjtEZm2QKO0F/W04ZRWL9LQkTatfSfrkr"); - a("eRTP4Pb5Do8X6IHvNYXzXCxP88AR04ydaBh/JorE0D8MxG1J8t236um89JzTLtPQ1pQ0TaWqI+2olwEEkNh94kdPcNND88xkxE"); - a("KcBQY+OnRmjviz9fQ+NcJmHH9gXMuKxgXwQV3IwKWBlXzm3LdxgJdm8BaobThXebJBLebv0ZPcwarnvYu/+W6J2UtWbpNmwXpw"); - a("gXNunYsAzH/4Tj4iRSyJIsUiJrcBJBg2gByiICZTfvPcacVKYJk6W8Sp9u6CWwMpnIjjdx6ENZzhho+IocJm63rPqLLagavABZ"); - a("b6O2PZ254fowZnyO9EojfY22fACnr5Hpl32C9PlG+iotBRgK0FfJ9Lk7kI4bS9w5uO6SWm1oxUC6smZHzisP22ZEVFKCrW7pO1"); - a("KOtI882lukDih0B8d/iRXTJkxUeoR94g0XKjT97ALWZt16gck+sYfa9minPiRdD3xTHLw+hyalOHiWuzhYlakP++vfiqVQ3DAr"); - a("W8u9DVvVz8V5f+x3VFQftmHAvojPOGMXuF5ImQDeNohVWB60w1g83cMVVCmgMdoHv7c+Hlx2CnZAYa+XWYqCkIYEIQ0JQhoShD"); - a("QkCGkIhDSxvReQpas/jPatr56a81tdDRV+LAw11J8j6KvNBT/SYJ5egCd2nW/a6vFRPXqtFvmvFXKvqBOBRq0SASbqi1ckvj8L"); - a("eZd7Y68B7QbpV1uBOv7HPYx2moXRsUTarI9Y7UDb7ZjkbfZHLJaDzGVu/g8vRKNASClq3CS2U166wArbA0DXd8qfC3Gy3fz0sE"); - a("2cSjkrPIbWtiUHZ5RKDgBVwwO0NdgrOJYPfYC5ivzasDvT6eQzO948MCl1C5ziMagM7rv/LiwY1JGMkHyz0Tb/slcIddyNWDHi"); - a("Tpw32ZkYf41AvHzMWYPeP06NK88S3gZKpfn6e1TIgN2EWukGYO2r1Ndn+/LqWSLdFHaTPfi7DNQadL+BWgMQBGpB2AhZnlVZvv"); - a("qDkWU7guIkj/7O8EXGGHrteWRPCqJanIqksM4fNtDU81N6LFiaaUs49ULm75oZynq49pzSZJPN5G6dO6zeRGSEeBdJ3X+nAfU0"); - a("BfVUBHnN+GR2nzIAfTJmXL1r0bzK9thE8/QLWAHa4BjnX9xZvRWwGvIZ2gooVkfAN2P3vB/hQ6CpeJ94hWTXtK9OQL7mNxEU7/"); - a("coJqaM15OiEXZ7JA/0Sv/cj0p7JG/dksgeibSfaTC3NLMDaPXMb2esgpdaMQTKNxXgqo6sSAqU2HmqbK+uNjrSVfc8r49RDNi2"); - a("Z8SMA7cZPj8A1Z0trwKsXfVUf09tzyGo9WjUyrwAo85FTrEEperQBvQ3ciFlzzBl7zayL5EPCzL7J4/0ChmPqwcpCj5jEhDx5L"); - a("utx5+Hc+Sb0O8w5GarnWr47fITl9RJ7uLcOjkROx7ue/zNYy/H2joHvEcthINEDMgeWJrVRoJ3vHg+xRKvD4MfyKNeF6wZgtwx"); - a("Q7VQDhWDcdlqMezM38ModF2J7HLOYgY3cr4u1LGJxYcQrttEt9vzeIqGiruxkkyBmEflUdM2hWubIR86DK6R/Ugt90LHKj1a7g"); - a("0WFffmtVd/JnlO74ihNA2jVf5/uRy/R/8gx2/I8sT4e7BjOGFrvDH82CHGcErMGHZbx5CH7cinMWx1yJEIKbVtD9PZQh/Dlfvj"); - a("jGHXn3ppFBC5lSJ/2lO7z1l5/DRlRxN5fnysl9x5skxn2TvlOIj4MZ5Bf2lv3j5FT15LgJqJ5Lk6lLyWRT61nX9esYipqrGlA2"); - a("lDQ48hgng4jlJ0OCZonE59yz2CTTQBRTJ8+YXpFS7kcFMO4X9ZZppI/TzwtBCvDO7B0ls1DSvx9y8xq2UA5rbHyDsep2RN93cZ"); - a("6hZHsR79dKycL40kskp2s6mmc7mmQIlxnJOOn6T8qOSRaEKE8A8piiI4jkHp5Dt0ivCypAi/gS8yaRYL48THOZvIrM0+KXuCPr"); - a("Rrpe5P2h9anFNStws8KbY3e30SLnBTC+DD3lv3deX5MfZUiZQWtST5Q1nSslEY4853qgvW8hiNQxjwXZEDcH8hooZwVn9wQU9k"); - a("ahjevatftNrNcsBuViPLlqbmoKAvr8NVdzlatVk5Ndu/2OkaXmQy/wQH9wyowzeefMMP4cuUSGrSTvJNjOKyUa7zZLKU+Qhkd9"); - a("3dVB5CSjnOJLddSixy2nxhBmNAhY/vEhDozcZVaiEltSKjc3rEJe1gAFxYsRAtZcfUWtEp08ORE8rDXC5aHTmGyyHsmC6KbNRs"); - a("piyykWf5GxXp5cv8yFcT5owMIVkKJUvq0uBHWSlRJGA64nLkKesniOvD/kV5ELqn/CeOJYx0p02eknLG5k6Jk9u0njlzbIn0OC"); - a("XE+ywWMS7rQglbmwQskoU6hEUMWzn1gv2/toex/1mzflKLU626h44ke1YN1n34sEkHaw/j2g97/0f2MC5Hm9qMpt7/wB6G/uUw"); - a("jF8MNYxfdHfo2kn3PNu/7Qvze+gwwrZzB5vwII6/zJ99g8++MCe+vuxfK/v0lxl/P2D+H5FMQxXRG3zL2Ggh+H5qsGcofdR79z"); - a("Mzzaz5zfDsbmV5Ihf83etj5eP9c5huve/C53ut1vvSbpHHF+ypvx7E8tpZFL4aYaUfbCfLfMtWpvxi35edKNzn+/L2gbZEla7t"); - a("sqb27d9dqL+z2q52+0DdR3KqsIevTFLw2NgVuu3+7AeyfDr+RobSJ9OmUweanXUkkHdpAxXYICFKpZIHUB5x3xFMG8G1twqUyP"); - a("Io+b1rOPYyWdZFZZtQln1lo+zJVJZL9W8fe62bSteitG/NzAtvyX3/9atO8u3+0tf0z8FU1aGoylgFqv2d5vaHUw0FVIMOwPa9"); - a("dgDs5/NXb+xXvtniFhKTxCUfOQGNicNF8bkgVJtvEbpnhxA4QwmcZ7HpddG7pl7kWlXkfVK+eVAVkfNWTUUCpiJnqCLrqMjVso"); - a("iaeT+KRLx6/mEq/2zKf4bMP0SQmXGUOZPKIoD3uwHcEs/XALlwtmFxWMSsE/mz6a2pPAl/q6unUq28Ca5NI0m0CrkR2Rd81zX0"); - a("tazXURONVh6FQBQqFdWHUvlkKv9rlHe9yKYPXuvB1bgQWWiDrjwSASzr6uoxlDeF8s5CXtGB9cgqujaCEk5OM7q2pceEPzb4q2"); - a("+YbEDu6AfyyMUS2hsUtG+lGtAOJxBOk0DeoID8c6oO5DgDyFGUEE5V428GMoG/6W5sEMbbYtWhxlR6VVW/TCVaYKDhZHyqmq34"); - a("f30s/ifQN9cdUquVoHP230AvC1427OmvdxYFO4M7a3vGXZ/cE0l2Pdy8+AgvG0XnJreuFsZ/eH5RksvsH1fZIlD0SUQJf1Z2lX"); - a("GFkHZ7pPoA7ZYDVN2zjFXCqnl60wjO8Sk0vZV9T+9oyjqEsu5K1gnzlbC+ARcTI4UvGUWcDT/XOf3Y71h7CFX4KCqUwKWFqqEQ"); - a("8a2ofihXf32Gbs1jp53891d/Bs8/1686L2p/+keufbS9dobfVr9d/6NB4Yddv5dtXVnoYyhtYtSFWb2NbFSQvtRixLKFoioZuO"); - a("0qpwisrNSTPtcDu/TA83ogxSkDozmQrNeTWsHWjqYjrWL2cRF+N6Z3hS6XeF9R+J+EyBncX+mvnCKm8fDiwjlkLZ3Bms1Hj66R"); - a("+ENp7X+PSSulNPSS035AWr2RlElJHzlknUti68ylxEZZbizSIJ+kp2VT2iMyLQtpLGskE7Mo8Vbl08RjSc8hpP1lubEnrQJMvL"); - a("Q4XXC72FawvPCCUKVJR9IO5Uj6vD1KC3fqaNJvqtXP3Ovkmfuxw5Wfua3CDgbb6FLr0X4+kQYoyPlNuvan46JRtiKhziV9+3uK"); - a("XEo0IbifzslsXGJSc3HZel9e89JhMGjBFiiEvybD+oSzuQQZMEIbZsD4xKSvipxlY6mIs4XNYWQGhqpjOB9Lq1dZDKTbzs/1MT"); - a("cpZx8n6P7pT1Xaa/QTTkR4Doq+/J/uX5WPxtiH+EHhwpEZwIXjaqz3r98f1rd9CM1iH6LFk+P8X/im/Aptas1/+0/uXzXk/mUQ"); - a("G4O4Fl2VNODoR/u9byXilzmciew5XHsqnQe7E9pzUPNXJP2F9j9/iyzzR5feHnqaUab33f8j+4+Hkv3HZ/sdbwyrD1wkn7E0Co"); - a("KNcPilD0RnAQZiMONNI9/QzNnn2V3A2PXdjrg6gb1F8/6zYm7/tiU6dPtVs8Xo+LmJl65ijqUHzEM8l3GU7xqmox0x7xzdQkNF"); - a("Y7sSnTJJqbsK+wJRK2209GfWVf+P/lwg+lPKTUSutPVnydV99YctyH+oPYawrUeSR59v7VNifrKVSsbzh/T446gS7oDV9Md/34"); - a("Y8+oP92+MLtgt7GfjhkerQ0W/aFKDfH8DIpvEKC8Pfc7Wo0u8y3pOD3u38rd4Us0HfYrUg3frT6EXKJHhf/c9U/bfo//7qoO0J"); - a("LfuM9g39WezugLG1a8EsCckqMTUJ9Hevrv132kODXGrNLaqx6XpjD1sbi79/x6BRm/TCdQ7tzQ/hERMPhd862f+W+b7A8uK4ps"); - a("AHImWcdAqLerP+bpqQLnofqeQLcWOYvtrwZd+/7f5IfWw75jyD7ij/PM21e6NQymstZBeorYWlBE1knMooJ5w9kwRnZwKzgoWl"); - a("8f2VUmSb4d91nqNijnD7N5JcjQMNt2SSvcz7mR2fx97/mBPewCxl5uMX5kqG+cwF5M9LPmPMnsfGlsnrtr4v5cb3D058UDxf78"); - a("O0WPW9Mg19L/WG34Fwbt/rSTnw75ThTIt6Vwe7osfLegoHhP8C3HqNj6/ER7dS6pJabHElOjSdfOboruNPVUts7myJ0B1chr1e"); - a("/VQp+HE1av/RNQfzIFoi9Blrve2m9/h2o4TyxNSkzbufDKS3s383IbUNmYLPr9eR7KcK3WPGt4OkFGwyElK3jsKhuZuDpXNE6K"); - a("1gaalZ3y5sHW+rCp0BKcabq/DMCXo3i1Ap9CDDZmkdCsMhowoyQtPQKx1TAK0zzJWsBCFo3ih6L/qd0FrEeU/ZEchCwr6SqCGS"); - a("oeODXukwoxb02NA15r7jxLiR/QySlrsXRAy/Yhoy9VrUNiTnBy7pSq7EzOsVpcuK5h2wVGRGq26JPfw+zYELew3ssZxXQE3F2s"); - a("wKnVX6Z9GFP2cx+1mQC2myOjJ891nUQ45I4b1QpGeECufkF5YGBnA1AdgYbUsqDxeFZs5Rb+dKNE6USa0tnOMMS+ZMiVRnScVv"); - a("zU1ZsF8vE7YfiM8AYugFo5b3GL7/hTxKPe9g7I95VL6Y9LJNRhafrSp7ffEyx02f1096pyNxuuaw75+sxND7WmJ+lVxT0hhvDy"); - a("mvbn1I+mOrmk9O4aTQTpH0AhZm/198lMbqGwn6QPvfKvYNmCnj/aGUdoO0kQwlOW8nPzWG/32EbeSuXRhVszrQUf3hFutyUVzS"); - a("aQ10B4JFdxMZ1B4p642aOmovby2wGAUoTpJXzW6MBVVZ/fW/+nMWq6jXvDdxoEabzoGGJVTlKk5tWEThu0R4IYWzl3F4AYXHij"); - a("CDsEjkyabwL0S4vRfh+ns43EbhShEmezOaR+RZReEJf+LwGsqTLeIbKTwWYQW9zX5UDf+UaLpVNZMsYb38rRG/rCIhg4tUcKEK"); - a("LlDBHBXMVkF0Rg+2qSC6wkG9J6fhbonoNSpHowyGDQ//ruWrRgm6Z9HZ0am9j12nz6JdBmo8rrprkT2s45j2GKsN1nkAmlBKud"); - a("4NSn2tJOFerppThTUFNDdNlPdqqBj0bzIHpZI0m+TQJEVmRGc/ReTDZzv78NnuIDhWOCBRP9p165cZSqJ+lMMkUa/guxWC+tis"); - a("apZuh100iZSZlKpdxSntkUFiI5uAMISY872bA4NPJya/q+5WVK9P/jhIjYo9oHQyaLeOH+m/JPtIPMLy2O7BVUcvtOJnVOhuhG"); - a("3rQe043J/pTtfN6AD6VZE9RdpQp982+k1yLa+n3yHi4t31Af4Y+yaJCOrWudK1e1ey7YpGRFZkkXhxqGRzdG4jKwhJaVLtX7Rd"); - a("C3xT1Rlv0geFFlKBQgGBIoWCPGx9QSlqAw2mkkyePgBxs1rYg+mwUaYtrYRuDbEY3XROh7KNaTenq9NhcQotdW15iEXYrOKjzt"); - a("etAa3KpOJo9v++c27uzU2atJvj96O55/Wd73Xe53zfjTiP6vwZYGBSwBG3UsQmHlssO2Xcp18g7oci7jkZtxC2duEDhM0RXvkw"); - a("T0kHksYkOkllYGpcJRKAJZ3aXSV/FtYxR3nOJ3m36pcE4n76ZvAHv4rMJtXWSOepYfwblO1K2BXC2ZutnqWbESLdy2RanX+MJl"); - a("+hzg1ZX1hWiETYuLfVl1jOs9XdMco1ksBYqu5FLXeVtwkV2IyAiu/Zq40qwEJOXMsq0GBQAVnop9ezCtRHUwFg4axnFvyyu3cW"); - a("gP6hTL9D7nfxXds1uDXC5I+UlWdQMpJ8igNJ/jTdS0Yf/TZXvUl9gGyAa+NK59prOEquBWw+XgHgYzuvCSQ6tzi80o6fvGUMUy"); - a("/ApfJFKgqurRwqDbjk23yWzU4Kucu3x5WqZKRBOx1IV+2qVcAhTeWL+EThn4wbqnF556qIXH60JBqXJ6yOyWWJz9Je8PkUN5jl"); - a("t655Ty2JDpedy49Rk3JfDUuMqs/ZZxnkKSrd8ZjWLuTwNwFMYSmP1ktZHRBvRQG9mst48WSw+btMAiLwI6A9s5aPYlWF356mU/"); - a("ifpWmimLYyoiiG3xRNFA+sii0KqXwbqPev4dFQp2rVNEqGa9sGH6BSVm4oaWkxeHvAYmwr1Ur+E720lUolE0n+dI2FFAnm7bqN"); - a("tx8q7V4UX4WAjm3ftejYtsqise3ktRHZ9lZxNLZdv7IvbFtezdSfb4lCva/zlSEG2sVc6eCTQDVcieTs6Smk+jM0Dsh4smdQxq"); - a("ghhB8B6kdlIaxYPUTHisVDNFZ0XhORFa/eEI0Vy1bEZgXS16q6UDgkhi7sGcy/ZP/gpTjV/sGb2uKyCV4QlUNrwuwfwMOqxkMx"); - a("o3rwOZ7Q0DdmPXHIiVCtCCWLUJ0IpSHE3C40cJvhLAqBo/To4XT16OF0I+QfLg03Bm0x3DKNuyuKQxLhYa3nhNdmIIEOO/enam"); - a("K44eqIYlj4nWhiePma2GIACnGqGMo/jzZ25aeGjt03PxKcN7IObaYt5JAR3ClyiPede8nOZxL5+90iZpbPCiWg8kgyUdJ0mfRL"); - a("TuKCao68vZbNmzjaKWaX+dbZlqpbOGYehZJdJXKeym+oJQuu4Ha2jb4ZoEyV7JvOqfxNJo2vKxZtYqwEJHHH+UaKvYU/hU25Fy"); - a("kRjWYnQmrWfE63bE5P0YT25PKIQnvg+mhCy7g6ttDUBHL5DQcMIekFscasW/mKm26+//ZAsP6urYL1y42paxOQWixTHeZgqmZb"); - a("jaVh67ZsnolU1txJ+NB4aMePkU2fDOQcdgEomV9AvYE4XvFxn9W1jPggCnv46XrnQXHPmUVAuWCrGHykL1mM2Zi+kd5cHF7OB0"); - a("5cEMrIOsPenSdTpNSDsNLKQyjWeadksfAIzbldmZFqemEaalqDIv6Fvqhg5yOPzMCIMEFqDM30UzCYZoIH5yAM6igaj8sk/bTM"); - a("Qp8XpDoT+hFaAV4zLiJcji2Tb+8YgVDLBXcma5o5bGlEzfz3qmiauXFZbM2UmInzlhP46H2M8w8QXJYMmR3QKlX3AI4vgRBlng"); - a("LkwfGLAW1e+ttWMXfxzTZ0uUdN3JDNFg7qEJLv3NRNDu0hW9lV2qRM12/dj/4HH7zl7eMOSFL05gm5K+j+BDH6VvL5AHD/Eq9o"); - a("JWeBMgY7OwTspQArrMxhF8jOaWJfsobgKIGfBqh01ZEkTU7fXxxRTstWRpPTP5bElpOR05tQkU9jEE07r0Q3pSf++g8l8c3gAv"); - a("yxTEsKHQ8sD3Bvj7f9kXj62f2cmoFUv4VJKi7IoggGL37yuTDuF8rV+75EjRPfWRSRE1esiMaJg4v7pLGZKomr/DHWr7MSQ2n2"); - a("bxU93v1V7/dIsseGkL0/mKGjR5qu73JvyIqTEdpkbQtDmMOxrsHBqVhzgsaC1VdGZMHl10Zjwb5FsVmw5X7ULThwx3tR2+ysBO"); - a("O8lPfk3n+A+2T6xjxgKOO8rRUh2ox+bRPsorPv9RezaKwSRT67TlhP+SCeh+BWMUDTD98boB7BHpxZ7DbOLL643zCz2HsGzfnE"); - a("XaL9PRQyfbCr0wd32PThR/rpwxrqbQ3Th5QB0aYPJ5JCpg/jVorpwzgJSCIIfhnnD/aQ+YNdPzD+3awJfJ0zosCvujqawNu/1a"); - a("/5w+tZ/Z0/XGAWWEeeA6Src4BUczhx3YAdHO79Jv1wb3KGDfcvsz+82OP91gnoe991/lfj/R+c/RnvD04ke+HO2OP9Uuf/fbz/"); - a("NuHid/Q+3nvjNE2auDCiJqUuj6ZJWx39G+8PfRCt7+Ch48BH/JKiUrMMH/t86JYY5z8bYqRX6tLdndeQu8/tKEP/KNzZchu1Sy"); - a("38kSE84HZ9OKMzOzM0/JEh/PgEfTitc83K0HD2qtDwRwjr6Vc+vCuKf0k+n+pQznfzqsm7ygz7XuXsYX0PTKAjqhV7hko89ubC"); - a("DZSGvR88UELHmF/uIbPH/tUlvqLiZrwLJYcQhxXcioSBwMaOBIB+/wW0xELvdHNJYd4nrgm4ki0TDrzAryTMyejo6Q30E0vRNr"); - a("J8Jda8f92avMZWU5pl8ietsdaUZQUK806VPyouzKUX9YS/CAy/bzJkTdT7Jp4jutvj+7nEmyhB4zI648Yb2Tgka93vuFNpN1w4"); - a("CffPVRLr/QbqLPQ0h1V7k6wWzthQ8+O6mh+WNRvfQBjlYb1avWni9DTbPK+wPcXLAdWdj+HvR1QZrDPhXqFqjm59oRmVtHCMbP"); - a("QQGO6+m8oW2HJPSLsQVvffTJadA6yW3ybdOrFg85euEQR4Mq8wh8GphL2mzBwo2El5Ck3d1TiIbjHZ8o7zeaTghPV6TURSP627"); - a("yEIBeqC3b0IPlBd83amdj+eyS/OqfeIBMo7K5Qvl27rteW87LI5mh8XZxP7xQM14+9QvcHuyfAC/+/QPwffGAbyvg7ekr3raQv"); - a("xzCi7l7cdxyTH/AOWPZ/eQW8F2eZcG98OKPK1csRMMKfIcRsXCj4Yzr9FpcRx2WpxtucecVa9uXORfUOLbYirYcn7B7ObSmbCC"); - a("1G51+79jdX89+taE6fBljpi3gzFJBZWfIA5ZXcN5H6rRZHfvxf8mU1HeG/wOFr8bLXyUddeH9Hdql3+8c2qrs6ohSBq+Q0gDUR"); - a("H6v0D6YCsJdy+QLx9QL7kClAfUy6KqJyE1/wcFfcxP/NlnV32LWN1fmcqTcxo6t5F+QQ1snv1W92lcqr+bL4sd81lBH9SmNKuo"); - a("+Jhl56pRAbef2LE+1f31OHrs7s9EyHJfA3TTb8fdwbHIV1k2KjDTNcyGA6uLbHmvWx5tAGSaA2VrQHLcXw9aP9ztPysSMBRMRX"); - a("5b3huWe+4U8yfJKKP/i0JDe438fh/vTRT4N+wKXgkPtt+qgCtxD/EInZ7swFZg7bSmsGZNwFb1vuXuDdSGXtTscVB74vsV6OZQ"); - a("pqj4ZfvU/eS5wf2uBQ2ivBFZtqQmVzvSAvbGTxKoKR30X0x36nFo1WFBh7kCWSw7h5vVq3iDeLaG42ZvPGOwT8mw9XBhXHVztX"); - a("AnkhQIfYjv8IIg7zpDb2K4/2mwX/AGuSHaxS+IsmkvwtNc4i3vLsGbyvm6F+zX8XX+FO06//xD2h6r5RI09yuWqnusf5N7rO0n"); - a("0Aa7wg0FaO8DPUfQUTpqUItA4DHsI5R46QVz1asWW5P2sM5433BetPutTFvk53R/QUFPu7sbmnxaPP0oTac/q/jtB/kB7fwn/q"); - a("hvGTRrPEbyE17WyE8jE7sLlxhtMb0OX1rsLTMWrO59GqyX8gErsNgIq+Y4zSyh77FgHT+gwdpAsJ4Jg2U9rhp4eTzcLkak8a9e"); - a("6SmQ/uf+xR81lSio/Pha/q7m8w+RwaccLTBIxmjfr0fY9+sR9v16hH2/HmHfj0MHQj3XuXJ0JvzqxG8V1S8/qXr9Eai8eX+wwG"); - a("AwRHq462De8O11zVpgZ0Wqup7wp6jrCmTlS3b5yxsqUghUZVlaYJLrQ3wi0ta+MceBq0LSgKsDP9RYmQdpoA4RPoyksuWutkKv"); - a("fbIk3BCYUR8J4EP8WqtfmjvJsmkYhDh9kmXz14PwO770SrogcHu8uChwXoL4/Yh+kyybr04S4XsSxQWChQPxiydLgSQRbjGJcA"); - a("XiO58fRPrMBpzY/m4KXzpaJO/ptfJ0rdhhTg6ag/LpzEH9LVMIHp2Salj0c7uIYohKwlVQ8hYURBAPbAVZN0eqw1uIuaA3cjWr"); - a("w6vxhlSzjXZSi+GK6vmzZB0poo4r+1zH6fFhdWSH1JFH+8Le5Ts8bafaLUVtnuU77MVshLdOUyIyPLi8luIqZ88onQYp1z6fg7"); - a("pY7rVLucf2OZDMYCH5Gy8Df+idtB1ZyVMXZ1ebzW1cAt9sArJO7j1WLkaZ+IG8pg7KbcygcHq9vYltSDit+ZfraXUuQxWtBrHV"); - a("D+yn2GaFV3N0gb6aD2nSf6NebMv6W8eRcWF13BJSxybUUWKUm207KqjTzN9MbSMDaHgfoknr9OJwae28BGzx0Btl4kuqxHl7Mu"); - a("O8IGg611OaNSUCAWmFcH6Dm51qDRnZ+EAN3HPmzwXomQBN3IiXkBcki62uEYiPDh3XSOJCwdMNTeVfk3VVtOejigNi71WPf8cA"); - a("xv9y3Iigk/he0bfusgBjKKFKwNV66HcQ9HVJoQRUATSfDSE+KnjgnxwGf5Ye/mjAx95xSjj+mQL/+X3iP/SEYT88SQd79xzg/n"); - a("RiKO77UBMfKSb2gfnJetgVetg3zGG8lyaG4b02qX98j1f58k6WDr6ZcP9XQijugyXubyX0ne8a/D16+L/JY/x/lqDiH6ykNpHx"); - a("t/e5ggS1gtX6Cqx5IOBCSYDKG0eiIOBsxMfkjxH8nok68P+czfgfiVfxD7pZVxIY/3P0MHlLQjWInT0PmDWbRC9olqX+HKGUZa"); - a("eu1I+olE+WSpKlymLV9QSVWiFLDVLbvyh1UXgpOceqEgc29K0CWkKjw1kS0EAJ6Ex8OCDLczpAjqVhgAYu1o0BFgno2fgYdBxZ"); - a("hFL3yVIpstRGUersiKWUgllkm4zyD5X5vyXyj++tFj4f959HCjNYFhkjioyJXMWJMqNNdOrvoVgwPFw6jLx/5NtqywfxwIAEsm"); - a("nrrAWoelIh0acq1y4AZXebhJ4mymp3QC3CqrTWp4lBnIejCSP1ltbr2D4gjfpWgNLmXSvNjP9YPTDWb1511qbxPhtyB0fKc0WB"); - a("cRFaxGwqMZ5KTAeuwfGb9tCj5WbqwYeN07GDYauFpQSVhCEjwkhIIRI2Sq8JvFswkPxj2d0I0VyG1hSN75rFWuPIP+15p29Pss"); - a("PVT9lbajXlA5ANDuN8VNt2XW3b08Nq23Yp5D0M7ZcisFb5+1IsXZIv6gm4y3cExClP6ESsGKN8XpulZgfbS/5VnOtKijJO1vDY"); - a("TCeoVq1etSefdGn4JOBpVOt3xgb343Bw/7hEnfkvD4K7AeBK5FoAaRz3LREnjXh28G1sdXGw9SdfyNPUDXzpBmslYcKXf7BWEi"); - a("Z8DQY5xXqa7b7lHBPmz9wbagMui+rHC2n2Vv9gNVhLQTXQSrtWiGjTIvLtSsUQsgMPISfY84cnl06ykWFymWNR9y42S1JFz49l"); - a("dWvbTH7zM6bqdoM9HCN+tAvfUlBLszsu2VKwQ/e9nb4xHE+hXwm5AGxS6yUz95VlZqzEEp6Z5M+DwzuFDCbQb3ec+N0uf6fgN6"); - a("QcrBmaA4ppGEwqNFl2Nunx1JvNs4ZUNNM1XwIpUFFBLuUJkwTu3jAFB9MSe1QpjQPRg0COxGGDZ9524669Vp/yHT0k9LzhpXeo"); - a("0MVbs97ez6DPS80yoj+D3NQnZBH2zQW/MvG3Sok/VZfEIJIJanR+zClNFRz4PXUKBsIFn0Lzu5ZqfMoIybKLlzvWT4I6VFwwRS"); - a("PfM69WT3eoEAw8MNij/VZOtP16tDendA4jvbsQbpYqJ9ChkESP3te1+4eVaH7q1MpDMuUvaqhIow5iS2FaYG7e7Qlzc249bMyx"); - a("caQWA7p5vCk6Ie06Gjl2rqVqlkmrUjTkIVrOa9r8o3ShWh1utUbc2iuS7PnXKJHq33dcX3/NUhPobdNl68LxhBhGEszoBcWeJz"); - a("7oEZuSBr8RtHF2uf8mX8Qyzm4afTzWKf5VEdORSBsm3jjYcPDnaTC4y3mPMmToMmSEoz/oOLWFELl0euNCJNgOBnSU/1CNwdWa"); - a("DvzSfk0wCkE9aNaeRWJQUMi/uNiXHFLAMd1ApQRnpbAdedvEcIw2+LG/zltFrLKyF79BGDLRNtiM51Wt2Korx9aj7BwblTYSTK"); - a("/7cdLL9/dnaCre9/019p/RI/xn8M+LlZylppZ/+DIUWYqweV722nJwOP0gRXhds/XO70FhwZaC+GrbSZAKfZgmbOokSgs6MwbK"); - a("j5OD5McsTOI6t46gfahCTxd2X9dnIt41ht9lnwmUJuHvsI2Z1heHCZsRI0p8wXjLxmTri5Y4raxl07/jJNyH5Rbut+DPzlL1gc"); - a("BtW628XVI0HYMsjSTEWnbbwrfEaCXNB1yLBlhZbkUtDbzT8EuIvfNrROhgJPYGY0Uc3pk0CDhJztx9KpBlBGSnuA8hU2UZ3rkN"); - a("COOvJxGWJehhz80TSb1YBmKbg9IVz0VaLO90PIglhP+6Ej2NN02LQWNyCI3wtwOt8Y8CDAFYTH2FXcKprPb3UzR7dcosfQPgRD"); - a("BN76V++1zyUt9CVznODEfFApTSiYVqUfFrW5wn+ZTDWNRGRW9CUZQMWLZWoOSamtvNOK07B7z6/oFBWgl7cTMMOZsDpla3koO3"); - a("1s0mLS24p4NMZKunWV+shXxeiVEPc/0m+6l2TxPOrhFffARn1ziY4Umjm0xYf33asvUOfFCk+2OTxn/lFqwoq45Z7u4ExjjxKa"); - a("YTn7JLd3OLBi4qvV/lEb2vSJbhhRSIp6M/65ZlaYHqZckBK85MrXknKw6APrXQS3l6Jln5jEmjAJgK7MdSWf9Iwv21EFEpbnAw"); - a("rECOpYoVN5xLhGDefsvWN0OTa6ymLWDwHNtJy+ZGGsd/4Sg+UHRKtRhUk77KbsIPK6qyaCCqhFIK9qgd0MfnEyL87SxuKUI7lJ"); - a("xQGoCiSu/R2cwk4v/Uw0FWDQJZjuImx9S9YD0x7CxmmFro0dl6Jrm/DpRmqkmbQ+C5O03NMPidA30OJ93zD3+Cz/2JCcZ6hofo"); - a("FnOs9IOQOMkNVzwXKB3u7jG5srUclXNmuDIkDuDOanLd/d0paOr1Z5EG/UOnPedfjOhfIxrzBqN2SRnuQUuBgQqD5iomgdjBsH"); - a("gVuXERof1IQAMPIrWEaa4xCKEnMJTKRyn/OaRlY2ldFzHPSOQxApVIvkL3vf6axv3cN9BXb5vcv776xGwwORDaV187uZ99dS0B"); - a("eb6ffXXT2Eh99VvnGfrq43PB3u+E9NW7JvWvrx44m/rqsXL+Gd5f/xjpeg1Ff63vvme4snTBDeaZruFqI7oMI8uW5SerF5n9E/"); - a("V5TDidV/OMUfOYfJG78ocuDo4Cz+CRDjoss5enC+7uhI2pvFkn5w8Ru6UWOksp5nT6qplnIlMs91OYwbC77qdIBMU1FNR3Th/N"); - a("1zqnZxIidU7OmfrOSe2YskngSUA2Qr86bVZPb4hilMks4pZnlmXkQc0pauo7Bwu7DU8SlqYg7lsfQXykjvonNBkqp7Gk807xdk"); - a("llGyb5DFeyzT9STRgKfg7VEtS2dVxtW/fItnUFt62/G9qWdWKveucQAhB6R/ahIfTOw4bypolR25WEgXYFAMsJgA8AZGwv7Sn3"); - a("VWpKG0ZHakr3TTc0pV/noSldBj7pcFp3Tp9p2nshsvpCGoprVITmdC7vyUSe8Tx1QVDXW1K0Gc+pXB6M0EwwekGeT6T0TZ4WyN"); - a("PyX8vzRxP6THvzBRHkmTuh7/KsuqAf8qzNiCTPveca5Hl4Vrg8t2X2mabPz++bPFdc0Ls8386V8izNUGU5LUc/5/CP1vpFbQcQ"); - a("ox9KWd2fxvtX8j06QwtXx/AZ/LyjAJ1uXOlM+rLsXGTW9U7nnRupd/IAYR8Bt7oDporHOq8j69qaLg2TgBI8bapCjdY6CIu+gw"); - a("Bv+6lTY8f3mf/rcyPo1Fvj+q5Tubn90KllIyLp1A+nGHSq/KJwnSoa12eaHskx6tQMy8+bXKMjqFU8sEc9kfXqJ+eF6dWRGQa9"); - a("Ch9jMPgF9Wq+1Kuo+vNpdiT9KcrV68/uSBXhCt/GUZuPlabLMrQ/sYlPV0Gub/MxSxUdLPH6HnGlI2CxYg7+r6bLJo/RRRk6M1"); - a("X55PByTrZmp0pon3IruN75myQeE5HKz5g0TLR8CynfHcF8wjRVVZt4oTV5Lr/Qag+dPHju7xBPtiiXBkoOxvszAXAq4ac1XQ3i"); - a("0XwNolZdNHh3ZPK54muJkiEFprkWy09bEzWrJEpcqJ9PVFMjqqkLraYewRCkGgRSFSJ3q8CizoAFb7CfRMPks2UBf50o0RYKv9"); - a("0APypdvyGIJkCMwPch+f3n+xKC93SCAZ4Ro3ZRwZPwDx4DPzPB+w7BQ/5LRP46I7h6HQM0fp43JyY/d5DaxSeo/ByLEmHo9k9P"); - a("lowj+gHcF8IyydEX8vqrd+ZxRH84PKPIGfx1eTH5+eexdF4cL/g5Q+SvMwq4XoB7ajYnN+jqisHPZQT9GbPKz5dn96r/eIcqoR"); - a("srj6r/Z5P+S/h6CdUJmP/GTnmv+nDZ7Jj68HOC/4WJ4asANOiPSOhGjCX8d2bFhH8hwf9Zb/Av1eAj5JvVf/4cHQP4F5h65c/c"); - a("kBoOXdxf+ZYS/CNxqnyfjAIg8RYkRmn7916s19UGQ228z56E2vxrkdd2cTRWJCaJ5MhtYmrseh4ZTX07Hfx0w7Z76ZzexsoJoQ"); - a("vqobphcyHgqLbZrleiHtSyr1X+EZvu3hcrDae3hvc3D8qjgCO2nBPy7Kw7wSXfByQ+b9YdtRUUbNmAVekFuBOuvqP4R1mJo+YG"); - a("eS+9CHZPHUim7DiHLzhp3ZWJ4mQh3I5zh0kXYSOr4+SZALmXsiNDi5Y+RWlBwnzsxE4OWH6LeZTVct/fbh2AuxN5H1Y8Dtptm0"); - a("+Ujg/iVzocky79TOl1zFJ8hdUKn1Ks1R6LGO/jt9KFX+/yHJwZzabpGhUWXqYcZJa0kZzaKWd/pJ2JGO57s81CWZ4MP3UTkIRI"); - a("QF77UGW73r9BQTXuibcQUHoHM5mmjpd+Do6Y2v0TcBYh+Fgw58J8V5K9JiHfn0pvYSrn5se5Ps5tMPg2CD3fpe3AZ9CdGw8rtf"); - a("vvB9xNCezvi/xjsTlo4OwZbXeDqQnMWuNherh/Bok82RnPrcyPK51OFJR9RjK9xQQ7t/cG2NcdLWPOcmDTXPhsSIElSLb3362R"); - a("YMQfjenZbDPee6h3RBuVox+ekeRE848B/x140QJXeyQKAS59DnoiBzk2w6sIuefympXehAEFe1VALLHEPbDPixAFZRLHanQhRj"); - a("NRb3zvBvkXevbhdl6OvXifswa7wUBTs+4oxW30NzE0hr1i6CTec+0nsNobguJXi0xtUpf0dnsIV2UlQOLX8lz6r0+b6HKU0olF"); - a("CncPldHtJw9um2yG/8G3zmgo6fBBeh2lf5/T3ZfcgUCcK1O9479qLHunXo4f6WfWk3gNsnDFv+CKE+0c5soN/qQuxpdRmuH45V"); - a("D9X7+p4Wc8T0eeVMrTwnm8gz+dhMBDlxJDmugghfZ+W2wnA/jntp00AaWXkQM3bE7avak4ck7fzUEbggl7g+9CwcqrvjLFwULg"); - a("EmR5WJ/Fg567/GRc6VQkbOIEJxISb8cnO/xN2I+E7yIkXkmYscZgl4W72H/UXyGX/OtOWu65WbwhgivExOPdmkc43wjmqQc/wv"); - a("kF1QfwGQBIrShZ3Qyg/0hTAPnnc038BAPFP8syx0kF/xI8AD/eQYyyBUdvVBpjythDiEB8C8WvRzyw/StHwUfT8CZU9SRCQrPS"); - a("WJLrxEjXrR0kR5FXJYFdeKxXffo2pY85JvTpnKwQfXp2FNP+5CidPsVlhepT10SDPhnqp/zKgTd6rb9jIun7G6L+5yeG1H90JN"); - a("f/8khd/Q9ODK2/Okb9lQR/oaF+4/0P5LuG8g2jfFI5ae/OdhJC9dhOQqbd55iBS+pe5bKxcXHQt8T170JoQ6nUi/lSuctmwgkd"); - a("l1X9bXeRfp9AUXIOSPqtfHs+2X3uqngP8NVrJ+Q3b05QZXafE1SZprmy1zgXQDVxc3ut196bAUm2brCMKmpJOMx1dyeu/4joR5"); - a("zivStk3OHySPvBUAz4n0KbiH7K59bn0/7lNjT1Ot5U7bNsvhFx9Xq6JT4vTSDFvfCwPe8L14CC50x+a4mP8HoHnGufQPXhTKmq"); - a("oSz7eaZF+O9N3E2livcXeS9spYJJVDDZBw++HQU5gYJq4xCl2UNXJ0oOvL11Y+ybhHt29J5sCt3/akU+MptyF37VgaizlJj8Cb"); - a("vB2xvM+QjnLB2k/J0T4v2LlTtPh2a5U81yw2mRZaYy5UxolmvULJYzIguMLl+gVuzFr2ZcXa+v6ZnoY9jd4JqrIj+eCtdfl8I6"); - a("7GlzeJo0f8NwIawOfpnSCnpIf+WJF32IPRMypOgiRDeavLggu9ee11g2EE9DE/Em0x+PZ5v0unOqo1gWWZRJZon5fe0zJn+K4n"); - a("j3DHoz2jYqqH5bnQdnBwKQFr34Y1davfsLeGpQH/zhQbiGN9WCNITIAYj1Ljw2pk3EQ9LrcSD9siSokf7Rl3xrXQG8en9qHel9"); - a("+aC++ytjPG2elxyeV/BYLQa2zuKDQWzvTQzDNu8Ly5Vv45Uz5mlNmKexIZkb0EFJHxlXMx1h3spi0/N29v/Ibw/uvkpu41aUwP"); - a("/1hMjcvisCt43vc7O/Sf4ydpK7QezyE3rl7jBwt+hwh8pg0+tnAv3mr9eaFsXf46EBfZhfRiWFwazZHQg6yBiTLceF+wyzycj+"); - a("FXj96kqXrgK6gm5+uoRv6644YYIfdEsL5fJdKU+G3vnUFEfN3Ub79dISsfAvRrnxI0CUWoX36zmUl7IZ/f50C78/ipYu/P5UwO"); - a("WPsuIKEESxhqE8nB4F9HTRrTSqVfguUhisSpTCvosU0FSm0tQRQhN3YU5FpUfR09Mh6VEEPV2CHoWyGenpEvR0aOmCnj89DXq2"); - a("FAl6lFj0SH9MffanVRvqjwmZQI5nXpr46vLM48JYAMMxMVIuqcPat2z8DNqS3Zg6Y9ZXCJ2Fk5+KVOEqKznOPwiwxbfBbVaB4E"); - a("NemCOn6H6c/lRH9NsNfpzC18Nea4aH9iG8RcML0YDUOV9mCs/5RuGHpGJYkkT0N5MQw79ROdqZqx39Rwfe9ytyUSqdBstW56hZ"); - a("1+1AezoHsPDLnt1O08nEBGwOYe3xxnETt0Jayo3DvpTw3hXeSvECQ+kZHfbamD1KLJjCU7wubcn7/vmGnOxf04EYJ8U4KcY7gv"); - a("ul7x5V+6VAj+obCXR5QZcXdHnXyQFWv3/ELNKTW+T5FxF5SbyByLmjiKL2SF0PkCWazwVN+AQn2mCPiajMGK1y3eCsnQq3UcAY"); - a("Nu53iI5PXylrq2VTIz5n0GfpEj6tLKfw7K+QVPWY9h4/XkycuybzToLOxZ1Sk0tsjW+O+5T+Fpj+yj/mPZ13q+/vzaLss+FlF6"); - a("tlA6Jsj38F6tOVqQwvM1Yt0yPKBPyTZRk5uXeEl+mkS+nqdo42/va5vy4N6a+pT7XWK2f4/PLQaWEwDi3a0EXPE91wflgXDbhR"); - a("++hjf0Sb3lkYuY+W7VltwHuSuQHXJ/OiLWIDXlOTsMTdYG7qTT++IX50Cn7s/uob58eBJ8CPx+b3iR+WgcyP5IHR+dHUx/ai1/"); - a("2TE8P06t6ZkXU/ZOew0NNwuIM/w+cj6K0OF3qaHJ79uPN9+L28JsuV7ZgmJWOapLz/yhkxJeoOpbioGJLaC9/Zl7FNqG6REAs+"); - a("BmJs0x3jRwAKSjbZD39dmNdkRYViTqaU9lJfPXUOvfqPXd1z5puYb516VptvPTE2+nyr//q6IUxfoak3YjyQmipdKsE63jc1zx"); - a("r5e+js5wVGnQ1vvwNE+x1g1Nfe+L11TIz1RCuvyRuDLHcW76OZOQYT9weoJH0btttCh8HDHXLMHDpBjJmagtdNYwUPWcrSsDke"); - a("pnGcFMkmnSjSO4xHzvNePhP0IztfiE+OlWH25IAk4QaEoZBFpsaiw1/RDPit9wnLT0+ZVFZ42kKaTxxWzEb9j95+5VhyYWZY+z"); - a("18rmH86cWf/Adow9iPPtyR12q5stFe3Oow7fNPk/svQNpsbVSSbdWmIizpHXn7bksu3GJGEHcdhU0qMyJvf03yQcITDbKBH3N2"); - a("gpRWkFKY14AG2YAKimpSi/xZ4hzJ02az7EyzNv4zGb8FJpuprcTmYbAAz6Df1LO4/ulo7fWp099Ie738aa29fj0qSns16Ht2Eu"); - a("t7ZlKf9D29cpxJ1PdRdpT9mVj2pcLnnzOyAVi54WOcTHrexZEH7QzoDy8EaZ85PYqyDmcJ0oPXetVB5LWxjT9FpqdurKTn1Pz+"); - a("0xORFjyQcA0GqujQln51JuC/xge3yLI9zxsr2zNqlBr/DvjIU9GviESlch+dVQkx/pzSr+xk4/zkqRicAUtCPbDlRCBcEB27/T"); - a("17dvj8L9swl4v8ftVrNuz9KyYcjPkvFPux/Kah1brl7IEO71B8ObyjnRR2DDLNr05NkcnVqwaarJgGoYlVvIwK/qf5z0uG8YS4"); - a("Xb2dKLoH7j+Vc3FmIIpuag06v6umT+VmJPFgU9kuqxehN2UI9/SwAvizCeuEwh8EoTxIRW88BFmFDE4FYgDKCxucoo9Nd/4GOF"); - a("41J9LYZFzPaE6XB+udLqOMl8lt+B7h6GXSljG+Xsa1FmzYI/f1cWTrgSm1HzRleLqhD03skNOf5nN6jju96+Ic2L4duARaWXXC"); - a("ddwdsJS9QsepQ+hUfWDQbXPktU/E8a8cDHN1A3HspgLNdn5vefAMLSLhffBm9qLfouJfAPxxWurApqsblqg2zlJL3I4SMB7Xna"); - a("6dTZGjeiWQYHRnsQ43G4P8aINXGO/VqTgPg1P8CW2uqwmqazCSScCKFVB9Ko926Hh3DfjlHyr0WY27EXGyIBr3xSiKa6W3v6s4"); - a("8OVN/HJ9XJzp8lSx56ugPeLXZZi5RezfmTc5ryo3mYmSZrvqwd97FdBuWE9ol5Z4Ex/A19QFqUrPAdS7EUQMV4lYhRjlI/yBbF"); - a("V22REEH1NV2hTwQeXJv9f2CAhzZDeaHy/m/OeCwS3DNQZPjAeDH4k3Mjj1UeLTdf2iD5KuMjF9VLOl6o/Ip+L/wn7gPxIIs4nh"); - a("Ep+Sgm81sQKJ/M5WCuHR78o7pz8junbx65BpiMNVXne3+dZpIKFQR8K3zWTv32wkoegR6IhaxVyq/xf4w8xj4V7LtcL0NYH/AQ"); - a("LuBakmA82x5Hl/nCrP0qUsy/dvYVkucP8w1cT8L1ExeGgf65JrrBJHdf2Vu6LbgjQ/sZZpltKqoUGPZdU0TCP0dhMI/dxkJPTb"); - a("24yyCutP0NTovLjHxAe6g7yDpx/DXKDNP4DuD+HTOxtrFE+3mOKl5p4WE6TM3P3iIwsfjUpOrpyMWD1HrY3HE6y5R63u9y2wgc"); - a("sdjf9s4G/12pLzE3ffjDPOBPQFPupsFAtIR0+DN1P55WmuN/FpqfqFuH9SekWweB7eZcnyG6l8ZlGNM9mbfgO+lW2tWCY15190"); - a("EyUMsHrK0/wWAfuZVobtai7x0c/8Xew5xukkS+t/o4zWFlsqsRrn2TcT6rZkpwflHkY524T3r6hxvJfh8HysrES4yGNjm+4exd"); - a("D1af6Pj9CFqREt89NYKa9qpV6hDa7lPPOTfZofY7395mR7C2uQUjRZO3nU0nEwlSZH/DRyflcHoxI5DTJf5PGS94cdfdofLtX2"); - a("h6Vtaih+R1aP6gEimSck93SdCYTuDF8mxrrZYTvDUfeFf/Ewxrj1Fxj3hY3z4TblkU8N8+Hw/WKH9N+v2iyMvW/885B9Yx9t2o"); - a("LYLyb2sOMjB5YSRCzX/8NGnki3MTRwQakhhNheG4p+I3vE3ofAi5LzDXvE/6s8N0SSZ9pEvTwBxpumvPCJUaQFQnB5YSKNvtff"); - a("9EvQ8UiuQaYGeR468X+Q54MR5TnxHCFPSSiJlVF4eI9BpM+fkCJdHCZSq+DInDCRlkSX6XMPghf35RhlatTvDmX38cj82JFVJ+"); - a("wVtAlDBe38Iy23dkhjAyn2Gr6ArtTjAaX8xsybAd/0JcSKusUtnMS3B9PVT2LG/GT8QrlJaz7TLkP/rksyYRWri6jXy/Vq2Ov7"); - a("q0pyYzoI0lA+BqM12yvafU0QQcWLPIeEDWGn52DlJXOvBgyy5ZI4rFuMMYO9gzPeozEG10b8U+01Y4ci5M9Ejs9OBUehkneCo1"); - a("AxPpEVwxAGvSGgC903+mVMye8tB9cPzuUFobg5uIfniVjkiAy3UIYnkMFaPwdoiMhjlYh8AJEOstdVhoCHAwAx+Po2ej8xjl3H"); - a("X1/keavIOwQXQAF4QVaPHvBIArwExYDSb1NNErKJYuci1uldkCyiPqGoqbKys6iysxHoJA0WNaZvpvmmViMArggCrKMCftywCe"); - a("Kxe2IIHvdQhv35jEd+sNiPKfbZfFHpr+5E4HEE/JMF+AuC+RZTvrtlvlLKV4EAcqn8DKS/vRyIavWNpxIrZIl5VMKJQFVg42JY"); - a("MAhUfVlWJJcZBbTOIEh4EO8d/pKE5guFdpgApEpoJ+9AIIBlUF5PRRPGWmD6dApJ/g3kfJxy/hOJNAXaTzn/joAPKse3ZPVXap"); - a("+X6xyyP+Bpc36/IcNRM/incHt3uWVnqslR3Agz564RWtIPkLSwJsHURGVOjytrMVz4Yf3mKzbqep/NJpeRrY/SITP2k3oP4G8/"); - a("fN9Neitgiut8CTjh+136pqU12aeQvidGO9grpz1ZXA0ecpoazEud9yEE/7IE2my5OxUhTGlLbya4t/E50I/V52tl6kcFfwyEyz"); - a("f+WG7ZXKUmVasf/yHuusOjKoL4vcu95JIQLpBEo4LGDoKaKGpE0BwkkkBi7/WzECsWSLAFOIloHkf07FhQbFiwYCGCSkzRJEiL"); - a("IIrYAgK+4yxBWgrh/M3s3r13zxyI+un9cW9md3a2zc622V1vCLg/BDwYAh4JATTe8j/JOg5lvvJWYNOAAS4YC9gj4AWlgEsE3O"); - a("sWwNcKeD3RXCLg+YADZ4u6O/JWwCMEXAv6wEkCPpfcjxawRvDBAp5B8N6y3glOFPCn4Omjtc29QmPdd79EuX3ZxuUWOD681YSD"); - a("bZlhK1s2r0Xow5HqULi7KNzEdg7nBnU6NM6kzWGNk7o2rHF6ASymsRlb3/5OU+K9HpJDtGwpZxb70VNdSEGtfrTFjNSi/1fp1R"); - a("ui9Yc+sV9bClNo6pNY5WPmfQZnkLJA02nZF2irmZnSUzyszAoetk/y9muMmtVfxxoZX70BGZ+7jTqUhsB+8DyzxPBcQJ7ztrKn"); - a("dlk6Jg/tPHmg3kLPeFAuJZ4QDO27ljaL7iGafc36riBbcK1cb8mo9f5reqoVWZ6JJYJXkO05WFKbF75+vshYUjOMurTV6OyY+e"); - a("0YlPHIhA4ipNlvkqugaxBnwAU6wkCrnwE6seZl3BPeBIY1VFK0Lw64mQ3kJ8iy5QKsQRlVjjHKKH4Nnf/gMqot0lqKpqwrUYtw"); - a("X5ivUFtLiLMAxupOyKv+2wOywDZwd4rceZE7L3LnRe4M+0UI2ZaFbNK5BH0esCrIM7BlZ5DiUM+41Yi85Cu6f2ILe3s6FVtDTj"); - a("qRJN1ikFxHkr1lM5OMkSTgCZEll1HgCWxQJ2N9CWtUe7cjrFVYDXlG00gVjBSYK8YD1F+kfXLEazjbybkSzmYmcj6krzyUjXz5"); - a("EQqn3kiYNx19uHkqJO0XZYx9l1/NSWvEh36BVLn+Ms5JWn/LKaT96RmM0p/N712waqZKzrRJ60aPzbjGVms+lKSnVnccWAN98A"); - a("B453kdnvK1MSiSW4F5U32YadF7IUnDWhRa8NNHviFFN3uX/Fmo7l7L7Dc6DlwOhplgmOt1hDm2/sAcPwBJjb75dYOt8TP4Z4QV"); - a("l54NUmilWDKVDKhsXSpDdk/fNnvX9KvyMI+kQyDU+R7iBaBvRRANTIYScWlvfetrzCK+EQRyVA1fo2Yt+m4Wgls8LfXJTVm+GH"); - a("E7Py/WWuoCrnsRNB6vvdUY01nUZCR/1MIhc0wxRLdPtO3h+xZLta9gQlcEHqEl+1xtrdaOgXEREvrWmyiVemz5Dsa9OnTBDEcy"); - a("34EVpk5lYiotxbu1rzmEXs60PuhJmj1SNhUkJpAIB1o2OGeNHGCP2uXuhFyfz62o54GRW1yzth0iiH292KlwCtgrVvFBW/NqfN"); - a("T935auXd/3N0HaOC4K5z8rmLWNxj4NitZK73VuUzAZKqtrs5VmCpXLjLdu7OIdJqJJmk40lYW1sD9CfDzkCziJx864svc508Vw"); - a("0thIH9k2mz9a979++KfpLURayssm7wiWZpmSeyont6gN88Knng4Geah9ECi13Ad3/P306vrO77t2995G+D7FrG94HFyv8MN+V2"); - a("/lMqujJGUj1+z4ABwbc5F4/Mo748pwH/3r8GrAFvEWWErNp37qg8RkSMT62SwRo30NNBzAdG4Lz+USQMAJU0WGdTGsfPmpIGSz"); - a("XI8pb4sZl4W8Y3YYdGMh73chYNx+4YzuKuQcw/sls4394pig9U0Mq7xVtiG4Hog4r2Odz4qJ7IIWMa3Vxf17rYxhasvvPnNhaY"); - a("uygqzv5f5EYUM2bhwbkevGGFVbHYrrgB18opJg2iUEkf4zoqcA0xpoUkVhsiPDBDojwgg6fS6ClQd7lEGcikPxinud1Pwn5sdR"); - a("sW5vx3KmYN1GrPPQQLMMvg9b+DKRfmk4OZmKDHOEEeZySxgm0vtzWuJc00hP0m7c0VTtffl+DgSoOFWlt2mS6nbS3d98f7Fklx"); - a("xmh8o8LVlvwbEjJn2fSTNMpOs7zKTp+lyQUlSDKar9KapxHFUshz99B4XvZwr/UkT4DL00FFUuk/Y3kd4ZQdpPHxkizeok0kNN"); - a("pKczKcNoFpumB2nbIrG4kd8cV64NpIOQwEKMl7pobkcJ3XdeV1A+yU3NXbK6en2XKdZM8QDgDwikb/y2O/pBEfTZgn4Z0X/A6S"); - a("2i5pVqSusL7eZsOfVx38hsXdRB2drPRHp7uzlb+yJbFaJcj2bSPibSogjS3x6nOlCoYgZSxbgov6vbydFOjkeRY09y/JQdY5jr"); - a("1+3EdR8T1+1tZq5PMFdHmGsPYnAPM4jjpt6Pm5Voq17RVr2irXq5rcrmb+7/X0bmaathySjwciK8+b2tJl6sQCd+M8gyl7uq6n"); - a("KnFjoOwxefwwOFpBcrmnKzm8b2z6tocnuwgVxRF3qPzVOn5FEI12w1uQjjqezm2wLQSZ46u6ejx7hkCzMfOcbn3YP3uu5ZWPqa"); - a("ZYBljEfTOMH6zlldWI9poPsHMb4o1urnH8H6Er70Aq26+hfFNn8kn4cPOTXBqVF9G//xDhug2QTZCHoJEKvb6bN48JQZsskoxl"); - a("bAwZp6N/wxAA1CtWrq7UDYF6PFBC1tDFCf6/1F+keQZn5/yDP0ErjZSmL1V1E14T2DyP5y/+1R+x/jPMwi83tPCCWazeZOCLx5"); - a("HBuUk6LQe3nDVtJyCw9CbA7aEIFZ1nwbdT79nucdqokDqEvlffmrmml0VHx32Zk7k2x0Iw+7MZ5gw92Buh0op7iskzd7Q2Ok77"); - a("bJYRGNMo3zMVb5Kp4ZbXxJfUs+L9yqlb+ivORgnJYzxBrgUy9i6wXZ1NS3YbgM6BBNfV9A/TR1gYAGamo9IBJgfCjgIPc8D++P"); - a("ot4Z14fN7QpWqK+zf9KCdvh5ZlJe1P6/ilWDPpgE9QUMLm+S9xrh3YFqxHmuoW6EjB2XCDkZKZIOtyPJbWxK+dBBAJSxCY3qdH"); - a("jayZMyNg+AJcPh+WKBjc8fOxR5/hjHlhH/d3AOTTfuXqHY2F+/7wVIex2cqkUofda6aOVpka8v5fw9DUDU+TvLm/l8Chu5LfVO"); - a("yLTM2nnpZnx6kVZLtmQPVis2Mm8JpsV9rtB+GqwKxu9XoG0izxLh2cpnVn5qZn9okDHPdAmLDimkM5ZLIZWO4dPS/Qohm0Whd/"); - a("vYjpyCQKlfjyBaB8u0fj8kmcy8SEDlKZ1OUnDGYRdDHi357W4+UYj9XuOgt7Y41zsmE4meN4MEoQQG/ho94Km1423nXG2jSMJJ"); - a("SELhVa0F5b/a9UkgRB5OoLWDcYDL224v3TdXu/GQjCI2hJKbvhW8rN7g008X9HH6vfy+eKHW2t3MotC8TS3P3y+XZxTpfCLeuq"); - a("wZl+LWagsr+87AkuwIbx9vXvzqYt+UmrEtuTRPlM9CxuV5C3YUfO6XL0YCzQGqw4vqIq0XajEkeypgnTYRrFJ2tmG50oyAhq3/"); - a("MZSzo2DaT9+qH6maU4xLJ7yJIc6zm8H5y+ewtJMgXjTrWAHRlNpxd/yXgpa+50XnP4r4P2bi/6SZv+jPUACCPcvgPs1SBsPsUG"); - a("b9IOTy5EJBWPR+W6bAoEDUe8rMsOgZvVS3/Ocv+6v8H1gmbQBEFHOetUZh8A+/JABe0PAEhlJ2RzfB5G+X4U0xHx+VBYdH2jlc"); - a("roblCjALxRx8xhqse3pTTIufiRKTVd70d5Am84qT1X9sN/67bS9jzoreXkTdmJ9XDbWUn5YYLeUbwPqszmDU/k0t4LO3qn2xQt"); - a("iHAushsKQuxmIFdrnAbAJ7W2AdixiL2cnYFoEdJ7BfBXaNwHSBaQJbK7APBfatwJYI7EuB/QBMxlcfeR66BjpQ92wQmxx7R25y"); - a("9F9DoeoD2eFlK2+sltvNcn36hcai5os1CLlMhOQl3aTX5sLlyBjeKoMN113p81NAujn/JV+oFnOs5mjGe9HrRcpi6YYcXuTPBf"); - a("9u34+429+Cj/8T186gGf/Cgq+z4I5vgpH+VnxVJL7la8Zl+g6D3YGu0ND9Wz/f3fOSKOlnBrNEnBBkbCYw/aktoDpsK/42bSP6"); - a("7Uz/6c9Msf8wI1fW97Af2gjyvvTXVkNh0h7cxCWdkAOuW3FlJeCJbsD7LO0ieDLBSQKeRbAi4NcInrKB4LSTf2cWL6+FTL/DLN"); - a("IGCKcXyelZwXU6hahfwiFKOth7JXl7RIjrdrDTsHVwGiOc7hVOl9Ps4iLB5CqCJ4KJ3F637Cf42nm9YTp/Fszkz9xX2nm9YQ7v"); - a("+nw2NS+zsHJGDSMp7obhThv+4vHu5PCEvIrhofcuK6cQReGJq8ZnNEyZBxC7pTAWn0vg/IVC4vyz7Xx3LmzxT1KvPw2mR5JW6Y"); - a("Z2EtO6PXclYHCfN3iUc0JsQXkgOfBoUeXwZLerangCMjwaTKY67O6KnHj31OFOfJ3wyomH10XwclXDz1V9dmL/5toWUH2S76pu"); - a("ElenrmgpODgGjcQ9NSd+CJ5zjUN0uKrwgIFyb4++LkV8J+Hr36BQesBteGJ5jQMxJSKmMxIhRM1FHFMydCucE9yeGxIUymP/Vd"); - a("QCa9cmw8S/QLMVuKpzEtkirAPmQGtj4Jpf22aH82KiW7ERtTUarJDG1F50z/wD4xSa2OGUJe4RvEbc0SXi1yPiPyMcvxKK326K"); - a("f+MexL++0BT/tM02I/6fbKb4axQZPxhWpjUXipIu152h+B3m/DtM8WOVyCFWiTheDCBX6PR+hYjXoeCyZLzNbIr3ZnO8ekS8F4"); - a("TjdYTidZrz/RfiVU3xlsXJOAvK65P9A/jZDdEwvKJheEXD8HLDMLUmqc+N5rSIVyn3gUhBNiugvMN4rqu6hx1/6o1AsAl3KH14"); - a("M+IG9Fcgu64mP5YNzQesUfAZYs+vxKt2oUZhJkgAgWcIbvh0VvS9DGyKfbhNircI4Q+NHn39v1W/CQaE4n35hXs2X+HHdXEcSy"); - a("9DQGOPke3AkvJxfYL+MDyQsSGA5X3bWFfroPswBwBGDVaot8CvQdXwj89D4vMUPkGxSOtVgyqVyhlOXqt1ggcn+sIviDOAOVh8"); - a("oLFMbUsGrCgzqH9GABk4rQ4wB4wLBcwIBbzNFDBGnQ9ChH2ewqqd+Kdxi0fdBEjhcPmwRnRVqbWcmrSRI2nen1rHXm/Ai5a7jW"); - a("vTyndCiSwlS1i246A7vmiuNTU3G7PhpcQCtT4LX0hirJDEirTxwBHDW/jgpQpXVdpojivpe1w+UOHo5apKOocd1O/gMDXtfBXO"); - a("qU5wShsiCKdASvUM2IIgbH/htPx7zNscDyK2bGJbgwI/GsAQdeLhlISDI5IA1s+D3tvD90FwEirpXLDy5Z+40/XASWIc5xmqII"); - a("BtQjLDK5GMSa5pX6GXbVBfARL0qM/ho4DPYHyRiof5k7SYEpyaPDjVWZaOHE5wcBkez3FN1pfS4wH7wX20cN9fuIs0fA5Pz9CR"); - a("8FHLZjaoborG51FPpHgQ5Bh8jVbg+F60AmGrAe+UCO/13yn48DN56tcxdhJV9XN8ga7GR3YVp+RjMMVXR6UNcnAhHulgIdLXN9"); - a("KWuToDtMkIOouCem3ovV4fgd7rHQSIEQF2wEcshm7cjjy8gXA+z9ApcFVd004J8o3CoF4JB/2WBrmYcw3afJQJNI9vjCGJMR5B"); - a("cn3buVVpSIJekswd/xvCaRY5XQEnwB/YEdWUT7sIvoyivQOwL8KemSMJWw+Q6cKjaLEw9PCc3Lv0BK1tSrDsYDr5v3+xLwdX+1"); - a("F/WygbASaHr4JfwA25kPM/oLD3yyzA2n0vN3ZLlf5fBbDuiN6njp41wUwNr0xMCU76GX2Q3OHcsDS0vmKxD/mzfVxoZ1Q0OTlb"); - a("Le3Bu1L8CAP0NjxpLUss3A0Gb0pmnY2zlJf1C9N6Tupdmk0LBN6k6TQ0Ongir57HZQXZTkf43Es+8ezjmnIpnPmdlcB5RVDGvQ"); - a("JZbNO8SZiWba5DNGCQ4Mb6mHLNsMoh/dA/xRYqrXTKB8sP9LJ/OTaLY92ek22ljQT2lAsU9+GZU63Rp7V1a5Jl/Fiyz0Qjc9vR"); - a("pdVHKx+csTPnf0mXyBKPzyi6eWyiQi9F9Ibg9wYrSiKZ21dOtGMx6Xg3lFjZiXlZ6+j9pE8Q3+kDRCZ7ikyWHA2xbcOoYwACDg"); - a("iHb8zDhY5LaV3Fr6ceTHHVk73BtCwkKkrW5P6tq2rYETAyKG+JKdmXrKomS1us8f3wV7K3f7w4u+8dlo6jhVPT/cWMA+Wd8Ir6"); - a("wAUGBzoLkMikGm3/4iCAkh8DzCsXBWhOLKhjy1uUkmR+IQ9uQWQQnHqaENSv8Qph1PNEKNHineJqRNfH5ydjoBODJkRi/dujXa"); - a("F7rYgqR1BZyp3M6V3v52HB+JOC8k/tgRO5nsipX375kAZbaQ+GC7WBDSxv0A6i3F1VNhOL8p8VnJ6bhNbbrj9+IBc+ieN9Fot7"); - a("pN+SdlguBJHw25PzYYjYB9c6yAzoa/qQ1cleRBMLicG0r5F6i8irHsP2+/pZHdTOajHk4vvVLOsCFvuYeL0+aEzho9s3vYIhxx"); - a("wMOeZhybAGS4ZNhTDxKsQyIsxks75BDiihTZgUk/RlrnMvoMHd1LghEKEGOXgv5m/JSL5/3F5y0cB41+TX2G38EcBPhvtRRDdR"); - a("0k8W38n3iu995I52sMCJr/9W/AFWCB4tYDvBFxJMRX8JVHnu1Ozcijbwjx1oH58QSBb0ASdoBS/oUDoCCGPFEoirw+165JPAvq"); - a("E43O8pgSQJI0uo82LvqUcUHxpjc00bS3MhBN2n+EgF6FVAGbq/nRJxDtC8e9aJ0wm5mk4X90+7D47UiPaiv0PJLHIQxsklw/03"); - a("2UWbOtVJOspVTRLjvxCOhtvH7JZndruKnY6JCOtNx/j8ALsRZ0q0ODsUUzhXFfPaEOH2PrstJzdLnNXKn+KcDSdT+RQPVWylCU"); - a("RBttuBngXe2PwYIF4b4ZAcqKxTRbtHPZebCul7+ahBGv31owSfRAk+zf8p1av3vAzauQme20qGJJyYN6zuQeH+aKQ7BpnkOknM"); - a("XQx3OAL3X2NKwsUyCb3p70BKQiYl4aRAns8SeeBYhLVEHDgAbhGRQoaMyIp9LBd3meK7WcaXQH+9AlchPISgnkKez/DHBPsCIy"); - a("PuIzl1AIqSjf0chrVkTq6x7rQuSPsnS4JBcZSqVh6lSsMpLJ/YJoBBH5q0F03aiybtRZP2oknTGrz1OJzVvhPZmsA2nlAGcrhS"); - a("KIYrDX2oZ0R+eqJNjY0t11U0q3FO90dOanix7o8otUQ4ozvCsYPJa3IfsTP0JDZ/p5J2SB1ovy0j/+6f+GTWR3bi1MtHuI1wRd"); - a("SpkCg79Vzp3HORLwH3jgXg3yRMpFq4yAciDPdn9HcQVfGRVMXZ/hQhx5BcvKiWmp5TMdhvg1MIL9YG+1ttBg50DfFlXEFJZKMt"); - a("LLOkh/vBBCbhxkAXH8QAEY2BbtNwl+9wlh4ZbhIQPSmgBRqJjX8COBKKLoHQm4CaiF0gdmttUsYCZ2sdITB/d/LS6jbk5T0yGT"); - a("h/kVVe1o/mwyCoci+qnAUEVR7tPii9od3SmVj8q7oM/2jyZdz3JGXLULtoN6x2ewu1eyNQgib2DlxNykaBWGf7n2HdHkUXyeJ3"); - a("morfXJZmzdAYON8Ej0Kd7q48a3KM8rx6B8oz7jNreT56Nbe/NvPtT1yce1AeaGsmae/N0j5GjtNSA8XFvrA4yrLYA1m0FIYhhY"); - a("HzDBH8K7rokVOMsrigE2XR2WQtC+0qlEW0gmB5IVvGlAjzXqt9Jq7L1Gu72OybDnjvQ5MRnLnqSaOfJzZ1YY29VGU7O0xUzEaa"); - a("Uh4fM3b69qj8xQwr+2fMsLwjpHDeK4UzTQjnbSHh7Ou/kRvwCAgo+stkhNV3BjAXmEE5Q3iznIJKVg31mUBk1XCfOSI8Vs71js"); - a("hAFkMt/TwDttTNiO7qJv1ko24+oh3/yxutdfPLFVHq5q+Wzyb9g70wArQN6ema3IeWbXuWJA90uu5ZR9o4UbHq7FSW4rukFO8v"); - a("xndCz/ZIh9TpizeixFbssW6NrlXvi9SqtwPdbfseYpTbPW0ot8MbrOVGrwT4AkfxGZQ17Qb5kidBnv4pyCNONt8L8uLuylnK57"); - a("Yo+2uW83i8PwwA8S/ZzXkFn7BnbOLPAusxPa47eYIgbAAqhH0UzEhoYP1jKldrnGvymbRCH1dy6UC7657rFB7cx6Oa+/uz7aEz"); - a("J5ymW1W++kSXawxXLkVNpoHEJ2g4A985maZF0kxcAZpNCmiM9lUV2b5eNtrX0wDRcNAlZ8rw+1cj/NvK321f/dG+WFbk6UQIiI"); - a("Qk/+oF4H8m+O+K6AkiorGGtT3yeQ0pV82Qq4rBhqAM3Eb7hfVWubr0MsiV/wch/39V50SoHO+7SA33B/+JzrHm8cUTjTzmb0Ue"); - a("A3XWPN5x6U55P+IBYq2/SRjydXOm03oeaWkzy3+LPvezPZH/uc0mwc9rCx1YMs6qQo1t7hWS9yKTvI8xy/sgu7jbh1OQQmc3cY"); - a("JVLinlogz8KfzeDdNwcg/4nGlWSZo5caD5LYpOfFfqxIP8r1KSpEpEaGkP9+MHqNd3lOj9vG7Rizrd8GDSiwMkLza7pELWfWBZ"); - a("WDmFYKEzW4Pn6v7TEMefSEeDFFJPcIjuME6LVZc2o1CbpDw0QR5KTjDkIXsz8vFNjVUerruYZP4rW/flclu4rxhjKhc+7j9zDo"); - a("rkWRHu75VJssw35Rd5CpxLCHgzkr+7vE0/3sjbJb+TfcjH1rxVXhSS9WPNsg6BlEK+a33//RKp7497azf7RR7kbB765xo056bd"); - a("6fjzPxM6PtgzJPNZCst8LyzQJEHeCyDvh/r7KBH6/TkM+qV+19MWouh3gKNJtysxYd2uzyXl/y38/964qWqhHDf9LzqsZZCp/2"); - a("+l/r/6T/3/BaF6HcUVirL3ouy9KHuu1Sj12XOxrM/Rb/xb9blJPzEpVItHi1pMQS26UIunoxYH+PfldsrXx9Zw3AsbWCvpUit9"); - a("BqN2/1bBrINT+Qd7VxnjRBCFt6UNxdLC4RYCxa24BooXL+6kBAnuxaVoIAfkgAQLrgf8oLgEOQiB4sWdKxa6HFLcKW92vrLtQP"); - a("HAHybZ++abeTO7M/Pe7t7s64ztRMSt7Y2W+ZNI0jdtU3yPe35Ytc2/8X+JOIbvS6pjmPCIxrDzbnEMn7QMjWGraGMojl+Vgxi/"); - a("Vev/pD3mP87tsV+qKPZYkEaylmiPaV+q9sieh6I93nxH+bBH57HfssfJx/6lPdpLqGP5/AGN5dxd4ljmbfFL9tj3AMbz/No/Z4"); - a("9rU0Sxx+I0ivW/tMfhngh7rPhKtMfuRyLs8TKN60/b48Ej/9YeexdXx9CSRGN4doc4hp2a/Yg94v3Owb9XzKPhWNrNONaZwMeE"); - a("NoktM5VURJ1LSo4p/KxczV9rQlP4y6k2WdZg0J4n57ORqe8Eg5/3UM1NRzHspdpI1mNenk1A0ea4Fvk5FQan81rkOwI/F8Ztxk"); - a("IS7Xd2SN7H3/+Qnljgegc/CdeiPx31F5MkRYjy5blc7sfnt1griqEVtW+jFdnpym3sK0t/9nVFyxejkSvxutXBdZpgjtSugHKf"); - a("wWCHklKwfvqKvNKkBxLk1aTL0jfkd38pv1aQz49MapwvsY/vegcf6yQf66RN9yXek86IapjOJfa5dL3DJSZ5iUlOgWRSo26YV/"); - a("/2+5y/iKqj0/yko8W3iTq6x046SnXSjZF0L5bpXj9nAvRTvF8oH9LClJPKXfhi/jpRg/lrRR9Ph/Sxi56P5KibYfqYj46SdFSh"); - a("o6n8UAMbV/St7aFnxrSSfIkSP6eltcgege8Im+cmpSxC28pp5RWR8+GsfU+NbfQ2WZJIpmgCkxmr+dl7hzL/r+PN2OpDM7LRpd"); - a("dhCtkPCjmXUM7NrDJCX6hBJzGyso7rIyVdCCU9+Zp+0XU/YZnnuGIg6SlL2v8t+ZVfys8U5LMqmegXi5/3i5fd+3qiZCgzhmU2"); - a("oE5jmQ1/6HuOvZCqd+nZAhfbN4t6V6sRn6dTPuSE6dyPfK85nIw/osiBNOIFYBFeADLzO+OM0AtAaXmCBH2oY2gw3WyhRSOME7"); - a("ezlwtaRYL2R6pLHhd0G6phIJnQM+VfzG+WL6j227U7bP3FTWK/pWkY9bvGT86/Z1SsdTSesGZ5kBRhM7bY5GQlvN3VDfxd6def"); - a("s/SMDeuTt4j/iC7pCqh94rlNfdJro9gnb+pHm/MV13/nm4Y5C7Pnt1mt1z+J6i3lFic5l6He16hP3H8M6hibZkd+Kj+b+2bx99"); - a("VghpWUJuwWFrX8FFa+GZXnhZWfYA2OUt42vYnBNqGi5ExGCyWxffpitchF/oQKoby0lEeg38l818Qlg5NScH9ritIuaOmpR2Yx"); - a("sc5e5mdbt1Jqk/Nu2PeGbUG+97+uxJmkGLribiTLHSB15NijIR3xYro33B/srOIo5d9Jf7AWZ7u4BrH52JotKRrGdjG/ZpvC1i"); - a("XHk6QK1M8ZaalmpcJYxc2upplbEvtN4eHWim+VURWKraxlvkUPFI8oPTmujN479bXgAfZd/zfrbWX4L+dl/m+y4uB2ncXnLWbx"); - a("DJ3uKNkjrmnIn5Gyo+8nQ9sHxhQlMjgL9U1Kivm7dmdurfq3RbiUul4bvjcKzitR19dY/J31ydV1GaizuJ/sTrPy++IN3J0sM/"); - a("32ja/Hc4SatPgdZbVZQv52qbFOj78wnYLv79U2GMRv8oZi/ylh8fLv7m9DLhIB+PbSBl5KrQsX0TKgJV4yh7DmJYKhz95WZU5R"); - a("Xfo6Iy3mwdaV0zymtULHxNBK48oPZ5W8rG7mD8hUxdb5UIMKvlF6knHuoz8NjI1f8fXQF9I/FFMDX9uapoGw0VoQQZIE/j/8kS"); - a("D2pcOtNWkIA0DJxzHXRnAEXyYJHCEkb9EpaIK8QTif421kucB7cCG4PkSm51rL63MP42gazjEunuNSoO+Dhpf7yDFuHPKBWha/"); - a("y+OtiyT74twhbr3AZL4f+qO9OnbNiLuS0fWVVuNLy6lxSyU1nlBFjdurUxzX50DcwOoPi7sQ17F2hcWXhsVNtVT5XGFxixKHfB"); - a("Me94uNgezvBK30b4M4ZiVjhIQsorwQjh33HLl4ynPi5NVLVy4fvXb9RqLv5u1zd+7K95MesH5fBL38weBYCvlfDCaBP1+Q/fLs"); - a("ysbqK5Ltaxdf+EOen61PJya4vidhAgplhIw/dX/WSL8Xkv2kvKVEyVKly5QtV75Cteo1ataqnZI0OC3VkkHSKUcMOyjNTKjUX7"); - a("dvt4jzNerUN6K+YYM85uMdx8/5yPnqIPSw6fVcvVMVuHUa6TuQ3jCnc2Vbb4GDacCPAs/OGtRjvtm8ri74NWDyDjlmzXg0a/Yk"); - a("8EdABNd+cDVYh1TslerGe6SnQ+rmDMmPjDw5N6E8uBnYtHej1dbKqdcMBi8LrF8xx/29xjtxbnAbsP2SeSsGLjj0MiMMfwvSJ4"); - a("5/MO9evVsPe0OdumNgK1U9dCbxnGdirw+cN8B1jR9b0lpg4L6pGd5xPu9jpE5ogpJGQ3+IqC2kKFgQcqCRISUdXejws/tyfrr/"); - a("TdZI1upGyTWHZqNuvtBLRxdU+lzj8CX2mJpnq4b4AG0Uu3Rzu7Zv4hjYDL4F9r6NYy7waMG+EuVXfF1uSkwfazh3H4U80HqMow"); - a("PoAiaE8AZHL9AHDAClRI4mYC6gBWgF2oEOYLT3h6XveL4b6AUGgKb3qB9oB/YHxgHdQC8wFBzt1GdaQI2TIqrx8NDcXtsSzn3Z"); - a("8MzPzjEX0Ap0AF3A7wWNvkgxbdGKRfq34vJxQDfQB5Ra43xAK7A7cAowHugB+oGGNhwLAG3A7sApwHigB+gHGtpytADtwP7AOK"); - a("Ab6AUGgJnbcSwPdACnAOOBHqAfaGiP6wbagN2BU4DxQA8wAMzcAecFlhSfr0j/W8H1k+fLC4xDua0oPA/8OfhS8INazuPBveA7"); - a("wG+CJ4AnxwPPA94U3AveHPwSeCtwH3hrcD94G/AAeFvw1+DtwQ0dOe8AbgLv+Im9u4xxIorCMDy4u0tgcAlSHIK7BtcQ3N2h+O"); - a("DuVrxYcCjuUNyCuxd3ggYnwLlvA5xgP/jJTdiP59zpdK5Md7c0AcfH9bCN6+O0uAF24YY4N26CC+GmuBRuiSviVrg+no/b40XY"); - a("wevwWLwee3HI0KwHjod9uDP24y74OO6KA7gbford2Kpn3B1Hxz2wjXtiF+6FC+HeuCL24fp4FW6Pb2AH38Rj8S3sxbexD9/Bfn"); - a("wXH8f3cADfx0/xA2zVN64UhvHjI5HYTzh6GuYDx8AuHBMXwrFwfRwbt8dxsIPj4rE4Hvbi+NiHE+LjOBkO4FT4Kc6IrQbcHzg6"); - a("boBt3BC7cCAT48PXcSlsl2e8yu1xMuzg5HisshenwD6cEvtxKnwcD8MBPBw/xSOw1dB4JI6OZ2Mbp6rA+HFGXAhnwRVxDlwT58"); - a("T1cW7cHOfD7XF+7MZFsINL46F4Dx6L92MPPoC9uEEl5hM3xQdwf3weD8EBPBbfw4vxU7wVv8F7cPhGXA+Ojs9gGyerzHzjFLgQ"); - a("blmN+cYr2zG/2Ifb41XYwavxWLwGe/Fa7MPrsB+vx8fxBhzAG/FTvAlbjY234Oh4K7bxNuzC23EhXLoD48f7JjN+nGEP48cZsY"); - a("Mz4bE4C/bibNiHc2A/fr6P8eMXOIBfYauJ8WscHr/F0fF7HB9fPsR84ABOix9jFz5wlPnBnrPMD15ylfnBS3F7vAw7eDkei1dg"); - a("L16JfdiH/XgVPo5X4wBeg5/iex+Zr6bG93F4rN8fSEu9FNmc/O73ob5/+Q4Hx+t+Hk87QNbMzPweDyl5kHohl6m7T5v6Ier+gh"); - a("xP/UjwfNl5HaR+lLovBz8PnjH1Y9TfZDX18ydN/Tj1QDZTf8PxJ6lXLMbxp0z9FHV3Ec5/zNRPU2+fm+MZ11nqT/Pz/Zb6Oepp"); - a("s3CfnzD18xaN4z2c/wLlRYUYL+e5SP18Aa6HebhE3ZWX52W8l6nHz0edcV1R9dzUr6q6m+e9puobmbeAqp+nfl3VPdRvUq9flP"); - a("lnvLeohy/JeZif28HxluJ5Ge9d6mMLczz1e9QPlGZ+GNd96nYJzkP9AfWNZbhO6g+pLyrLPFB/RD13ca6f51VNv9tYyAph+fVd"); - a("FFK93yd15adXt05zV88e04jjQ3xpIb+0UF+aFSLk93/CRIkSIVy0aJG+/gkbNWpEK4Q5LDTNihQr6s/e+PR0ZV7I8+QbMtjid2"); - a("O/kDVJN+khN5LnyTdkfDePJ2uSbtJDbiTPk2+C9e6Sv2x2D173u5Nk3Qntw8t+ob+mytGdB0WR+cZ+lXvSrZHHN+9pnFZl1rc5"); - a("ZWne4EUq1yTtGEleL3oZu1RWWfEhojw/XqQyZtJSkeV1qDePUxmzQnrpd/VhnqgH84z/slyfh/7mKlenuyTjC9/X+Dj1YDZyV5"); - a("Trd9NfSOWElRPMz3V4kcqToRLI9VV0jG2VVedGlmX1Y0dll5YJpN/uZ/zUIcn4c+eZ1wP6a6q8MNuR9bX6Gx+gHswkVc1vfg79"); - a("uVXODCyKLOuDN6rc/dC8g1xzAPtC5dxlO+X6N+KhKhc/SxRWxjeQcVEPZughD6Tfob+iysZh9oaT/Yc3qmz8IryMr/0g9o3KSD"); - a("nfRJD1w4tUxt4SyoxvMOumMmW9PDK/B/BYlXtfXZP94xpibKlcXfKInN+Lm6vcMyVKGHn9GWp8nnowJ+aZEVHWn/76KlcP3GTW"); - a("f5ixn3owq+aaIfPnpr+QyvKfroWR9ccbVbaN4JXrTzvCuBTZnPzbNvQPx3tH/eF8o9nXo0hyQOLWZv3pz63y6O4Ncv3n8SKVod"); - a("3Xosr6jTEOr3L+oGwhZP5xfZWZlg6LaG5Qrot6MLO2eSL7uzn9uVW2iOZI/wHsUZmyYy05f6FxzI/KeRMWy/V7cHuVsc+3N+uL"); - a("D6jMMO50BNn/441tlYsmJYgm9zceqrLghwzy+PgTjO9RD+aCzSNkfdz0l/qWnD+U7M8A9qks5h8YRcY/0Ti+ypeJysn8eXB7lS"); - a("tiNJH78w0+oHJtnTNhZH0mGbtUTox+Web3OPaqzJEqpHx/yT2ZfaOyW+nX0u/BzVXuybhQ1jf8FK6LejCL3HfJ/Lanv5DKlL7j"); - a("oeX6sFflnv6f5PEuj7Gl8tXh8+b+w81VZv3YXM7/Bh9X2fhMdpn/+lON06q8US2yjO889qhccWVkNFnfacybyqPNm5nfg7Bb5c"); - a("sH5h+A7ensO+rBbHv6k6zfIvorqsw0arqsf6kZxgHqwUzSoqFc/z36HZWj4/WW668509hWOfrBLZmfjXioyg+pd8hypJ1l/JR6"); - a("ME+drS/736G/psrSVT7J4wPYp/J1/IGhZH5nG0dXWTfrKfP9CbdXmfxNHRn/G3xc5cI0q8z6e1l3lVXfJTI//2CPyqwFQ8n9EX"); - a("8O4/aSZMzYu+X63fSXUlnl9dqosj7Yp3LtkZ2RZH3msi4qzy0KLY8/gIeqHD0mt7l/5hm/oR7MXdU+yPp46W+uMnTaxtIff77x"); - a("eerBTNC2nMyvQ38plX2LPpL9qZuf/l+1+mf5PZnj/tTiL/j9cSUqFrWzZcqaKatdO6sra9bMrjyZs2avYzdt19F2585ZL2d2O6"); - a("Ndo0XbnNmt/+1ftDBk/OHsV9I9yqRDelhfL3mAPE6WYl0rkr7QIX/4PFAUnqei1cDqZDX68rW1ZVtVvnxtZ3W1mlgd6Y8ToUi7"); - a("Bh0bF+neuUkISs4ts8ViiEwLW6Vd665Nvv5np4EfP2f4Rn3+yHNd+n/dbtP/h+bvxecTepus2Mek45iM7v192v1MWv1N+oaY9J"); - a("PHyWALV7VCw5ZNGnU+wPiCzc9tsohxpe7pomX89qUof6Nlz9nb8nN8fM5zj3nyUvd/5u5KY5opwnDL54GIUm+84nrjgRZBKZ6F"); - a("shUUZIWixCN2LatUy3btFuXTGBs1indj1KAxpj+MIWpijZr4wx/9oQne9YrXD+sV8cYzeNYp+wxtt9t30SiubjI8zPHu7PPOO7"); - a("Oz7850P6D1MFVHT8smucycC/N+Wk8u5AvAv6qnHUKDalJJXCBHlElDY/Dj/YzrAEpALvskeL+F6/dwvSB9jZ8p3hOaiurC+VFV"); - a("TmwWpmRdUOOCnkxE1QuFSFxlJqlH46qgz2haPJFkSdNaNKZMClEV7+kuHFWQKCSnFEHWtFg0IidLQpdFk1OCLMyo0STLk5NMSE"); - a("/KsZhuJEbikwpqmpZV+UIlwQqsnkRLxC9MyNPCjK7oQiQmMzzChWP70Rk1GZ1WBCWRYGOoa0uBnfgA5gcT2N8S715dVxKr9V8g"); - a("ly4Vcg1Cm2GHhwuxqKoILp5+iHHqi5WEqsQ6j+LpY0oyNJVQ5Ml+RY8kolrpjKvltzMeW8RS9QzdW6BrY6mWhs7tbhybYhpjje"); - a("lKVfrQ55C/05Ys65iurZCcgvletYD8Hbfui8djiqy6q72Ai8jfpqlX1aNjq/pbbWekt1h2NIwxm/WkMl09TmzfODiuXqzGL1N5"); - a("Mbe5a67JbWKjnxdyLbWGyk2rDUWqauT9zf8oQ9SS/bLBdcblRlHhwd+LbSzEWEixcAcLCyw8hSAgFFjoeogh4v3s/y9YaH749+"); - a("KvDH99kAXEWxkm2Q9ESM/9XpxnyMO1z7JvNzxnpDc/awT2fzlA5hyW3sXCwyy8zsJTiwa2sbyP2P9cW5nDN7meeMzgwePPPG7E"); - a("m19hcix8z0Lo1d+LGgtPsTD3Wjm4XmdcWOh6wwj+11lA/C0ml2FhrzdYQD7PK7xm5K+uoy2yOhDy7qKBDWw83KIcft2yWGxsLB"); - a("af3sUI6R2KxZu3Kf1vlE97isV7W0oBZRBWtioWzeNsqh3z1SV6nJ3dZ5Mj7kfZs6qvs1lkfUeRp3k/nvjE+n7iAz/PpzTPrEN5"); - a("bicGA4xnUgFR/xLNc8WG55JDeW4rBkc0RQVLZpef0jwLn9E8BcGxPNldLbHG0/OZNc9lpC9+TvOccCjPJnGU3XxBkx0rNjyzX9"); - a("A85xzKc1vxzESU9052FD6nec5/SfPMOZTn9mIgJuv6afFkMD6jTroW0V717iupr2ieKw7l2czstsyyNMeheU59TfP07utMnk3i"); - a("UFRPlvvn/Fc0T2mZ5hl2KE+PaMyxq9my+r6m+fq/ofnOO5Rvixhgj3NxVVENutoyfy4/5pjOwDHezkB7Z5D96QoEjm73HcX+6w"); - a("34vN09wZ7uHvHoK10T39B6mfiW1kveoXrZRhw5X1cS7IEY95NvrP003P+Q+Y7m6drPGTzzwLTbvYqF31G+aKAfKAD5eTNFIMrn"); - a("gB6X28AGnG+T2+QHMubdGuygDelvmfX3vc246DD95a4xeAqQMyM/tgqtzt9c2e/A3w3+vxv8F8A79wPNfwH8wzZ6kO50byj/5b"); - a("vQ3vOIo/783bCLe4AoV7jPbB+leZ+SyEIPc0ifLVbrJ/+jzfx9f7wvsNFP+M2N0Y/rXaMe6W3YyTsG5lB/geM7Zn2szg8TedhD"); - a("GOkZ6GPuN8wLV2zGVehDAvJj0SQnxa314dXdlvz9mvsv6SM1AfuIgu/FBnrPhh4uqj5vDvE8T0d5gcsB18ojLsXqXPc08oE8PY"); - a("y4XzWdD/w1pKeBwiXABK4DmEJ5fjSF1u6rq3H/b6gfGAZqwAaTX3cB7TRRx6/btsMmy3ITSOdH4Ufab77yk8087YD1jbv+VvcG"); - a("v18ISqU5WhuuX+B8zfx+pvml6/Br/aVaTth7Y/jx8vk9YU8C6gXyY8tQiT2r/zfkAzPAGk7gw+0gZZqvNkJPfsRzJj0Kv9o8h6"); - a("7TTqT9NtZOtg0Zbn1DW6y+X+j+4P3NZh6/vzXPCZNcdmJjeGJcLc/TEOfjahpY1oekJHSmDAxMWdhLDpivYz9+8PPUsR8f7MOH"); - a("+KLpfpX/ndar/0CsFzDZUcEkl9vp39Vrbmfod0f0tx0MzALzQC7H/hrn2wm4K3AXA6Vdze0TiMdiSoS/f+JHGnqUEM+a9Cu46f"); - a("7nOQjrFaFnfnjdpvgRf69+80e7Sf26DoYeEQ93Vdtt4aDqebanrTruRVwDeg+1vv9n25EOfkIP6j0S8xJgoQPXdZSB/k6UAxba"); - a("ref96W7w9OH6cX7pWJznOMgdXy1fQDx7AniciHo4+nF9fTh/AOfrhxwwHYT+BtzV43rI8Gfo5vfe6FdpxDXuL4c9ZDfR9uQ/yD"); - a("o/Z5Y73aH2dBrygRowBeT2lEXcO4J8ILenvAS7CuF8p/81e1qGnHcU6UBuT/lx2p68Z7j/UXuSBpE/DHlgZgjnAWZCON+ZiJ9h"); - a("Ht/K/rUqe4Ldebh98uc/7lfZkrbH2YOc5R9Yr39F2wL6BnqBEtDjAm5p7V/ZLjQgq5MxxfCysPrR/8zzGw/0N7AVracV6DFrp8"); - a("9G9/9Kj9syP01Zi0x/0Jf5uYLbY3prWj/eg51pjxrajesxzOKUvy+FfLO/z7WNtR53CgVm9GR8eliZjic2l/UZht2Z/X8L0ONS"); - a("I60vbZ361JrcjtSna1t3lT79LE7pM72NuZ9XazQLvXmRnzfp09tE62thnfqUWpypz79qny3M36jHZxIR3te32UT69Qvb0noqOK"); - a("yfr5X/jyM/dgn1nq8nE3IkaSw6M7zF7D7WZD2erKC95rej20VoW1+75a/bWL9P6nrct4AZYIGn34Dx43b0F8RzwAJQuBF2D/QD"); - a("PTchDgwDU8AcMH0z5G9BOWAB6L3VwCwwfZv5PtC3usa0utXY0Uz3t4EWG/99m7P625+3b2f103r9zHgLwfwF21n3szDaacVjs1"); - a("9xne1VeHZj+pn0HOwcqAEzzyMdWADy8y+/jn71Buz8BfRHYBqY5+kvQh6YBeZfQvmXEX8V/TGPcsDwKwYuA6VXqf6F1mLHFNrl"); - a("/cWvTnJ9dMApTz28j/vkyZ5HW3fYhPf6nUFRDPjEjnaxi62y7+o9qqu9L9AbaO8Ieju6uo/p6uzp67jS5d3B9Dxm9pPuaONvOs"); - a("RZ/bR8/x+Kqhcrq/7gwaQyHd6BHo+EnWgeAw7jae7XO1bwPSOqR5NY0TLA2o/yg7fuTPNKrZO359yN6dfhc8zPc+ANP4N/J+v5"); - a("sp/b8S40n9ZD4T8t8XZAO/Nj59C4mlD00m6iyVHlAiWhqBGlxBPtZ/bHt4Lnsg3fiUOdZdf82D00FI/IsXF11Ewa87pdrJ/beT"); - a("sv7Urzml8n74K8Ye+xMN6XKQ+W9tWAceuu1uO0D/Ze2I3m89Z6+V7g/lfGrx1CfTPRWM3w5WrczZr3CtLfaqV5eQ5zFu/UhdXj"); - a("V2sIrb1m35w+L2CyczP/3Wl+C+AvldAB/F1KNf/dGP/puAX93en71uIeNJ+lw5w5rjWHBtVo0vDlltp4xYZndk+ah3C4M3luF5"); - a("LiesXSmMJaexl/izg2obw4EixBTf5WSB3bPH1+PEbkY8ecOX9r5Jc2tbGtiDX5WyI/GIvLSYv6m5B/ZnRSQR2W18m5HwE86Iq+"); - a("QHdn9zFib3tHT09pXe1Rve2+Y3xd7cEun/fooPeYno5A75U152ng+mui62HZZP52wHr6wNvCuu1xWjRWbkyL5wyz3BYoN6RckH"); - a("QR7RyKayWo2w4jZ54mjjKsp5f2E12kfFCO6QrDetcXSswo1PWplbyJ85w2E4tR+j/PTn58aIjk0Ts0JlI8RsdFisdpg0O0ni9T"); - a("lQTR345AgZaqDXV8N91cjPfmrVe3fyi6eV9gS/UGNb49bWGfOoJZLle54avtU0IK4yWXq9xA5fnMVk4QIFexIWkFYpJQKzbBy1"); - a("du7Cl8Xl8AxxyXM22UWfyCFs1xuaqNJ9kv7fS/wuUqNnLMf1VfyrsvytdsiEh9TdUV5nK1GwvIS5zncuWF93PfEBJ5Xr5mgfnH"); - a("DZYq2A/lsSA7+x1d3MvL8wXK1AeGVh1h2JDd6K72V/LzmBc6TyDDVPECL4+FwOuu12+a15vPk/+BrFfYH+VNC1fXU7VQkS7x81"); - a("QuNPP9SinbaH+L+vna1UXkNayJNdTU7a072fFtcZo8reRQvg2pHN01vLybQvKFrjy/nvJCU5JD+ACUNxZmNv5swzjNy1cuUJR+"); - a("sdVTjsvVLhSzbyhvOXnF6jxYZAaFW9bP1+lt3zKIqULvpKwx+wrjmt1dR96rfzGa3+G+B1zCIydc/U75FA3sbjIL+ZbywiTi4h"); - a("tYyELChzROZqCq5JM1513+nSLjOQjlKxek+N2o6qD6/Llc9cILvuyibb86krNczrTQYF3t5iknZ63OwxcrLNS/7hUuZ/WCPrwV"); - a("ffVYzwDelZL8NfTUwXUkNS5X++KVlFzgctYvANnrP7qnFLi85YuoZjxctdWfB7RB3vrFCHstQtcf5vJWjnrupJ+vX38GWc1rnX"); - a("Yrk/27M8Y/4Mvrq3Vwk1fqOQRyFo5i+IgtRQe4XKWjFU5WavxKcTlrxyU9FtSM+jzeVh4HyPNzr6j/EAvFw88L+fqORu5ilA61"); - a("OMkEl7dy2MFZR1TvmufytY4v7vKatZJ+i8vVdxzBY9R4mOV4iNSWeo6XPztW4ZBsz7s7dVmuBS5f5SCBd4QwtCUuV+1wKOxBCp"); - a("b9JtknjQIHFNnvx7DwOgsHsPtXkoXXWTjAzf5n4WkWDmgoFq9l4SMW+jcVi/ezsMUWxWKMhXr+G63d5j13DENUCR21L3Y2omjl"); - a("SUeG64u3t3n/7xH09adjzvBT1fIUZ9lIrcoxPK+1W/OcAj//kTbt5Fieg3hAw/36CGueEvi1eWkeyw7l2ST2Ry/t23yWkojjex"); - a("Q0T08HzaNt2pk8txVHZfVCZa1F/V6a54oNz7BDeTaX7HaEeQkuiMUvw3c1qP5ZOIrmMe9Qnk3isJycKndQz1HWPJeRvthJ88g7"); - a("luegeqkci06OaPhuC80z20XzaFSdyXNbsTQEsbGIvTfAd2hInvNH0zz8DuW5jcg7J/9uD80zdQzNQ3MozyZxXJ2sIJo92vRe1v"); - a("z7P900jwWH8tyW9c+RmfJMYf4Ymqfko3kU/irPsxv+4d//GVBkzXBxVP3+T7fN/K+H5tMad2a77rg2z62e2Gs+6/adQrr3WJrP"); - a("RNyZ7dvC7zNSPKoy4uEemmfrcTSPtEN5Noust45cYBgyiw+w9qJ+p8l1PM1j0aH228zbMyDrSXz/jBqXlmx4ujRn8txOPENORG"); - a("U8q+G7asR4lD+B5uFzKE+P2BuJKLp+RjQekyvfbZxgzXcJ6bkTaT6aQ/luI/bN6GhTfDeQbNeFk2geGYfybBKlBJv0xthiG3y/"); - a("kOaZ9tusW3Qoz+3Z63I5cvHa5Dd3Es1ztpfm4bnEmTy3EQNxNZmIxwL8O5X0/SXcR/PwO5TndiWerDH5uJvupXkOBGgesw7lub"); - a("2I11wgOttH8/T20zyyDuXpEdc+GBCs/F5AOEDzFUSaz5JD+TaLxovHwJQSuRjft6V4NgZpHkLCqTyNZRT8VuoTaZ7LNjwnHMqz"); - a("URyLXnj6TDSJuBCkeb51Ms1jzqE8ty/5dy9gk3qMR40n0/P63ADNI+dQno3iyFiln2H5ZLo9FwZpHssO5bmjOCZfoETkmMnP8N"); - a("YAzXf+FJqPV3cmX494WtwYkcaMb+mUv0tN8p07leYz5VC+OzO+5bXw4IzvalN8Z4ds/KEO5bsD49u/WR2Knq+DLP9eOL1vdnGY"); - a("5jOQdAZfen/7+lE6toHM58c2IVGNxCfX9lHMD1mP929Bf20jNvNsh+kxdzx+z/cEA70nGpgDugLAfgO1kwzMcOwzMIX8NDADdP"); - a("kNzAMzvQ3m34/pC4yVdVwYttavD3qdk2zm9/8z/WpBxIFZHu9HXLTT73go2F3Wr3/EWr/z0OvS6TbPE/8z/aZOhh6BOWCex4Pr"); - a("0K+vrN+MZD3O8vHBN0brT5hxln6FAegVqAHTwNQpyD/VwALSPYNIR34Y+RowzeODpvlJaNz4JN+aSnGMWutVgj7TIZvnJofqtc"); - a("D1wPU8BL0OGyidBn0hPQcUhq316hmx1uvubLnvhaI6GZVVSwVPQI+jN3uuuG3vd4fufe/MwiW7n3DSkyH++xzdfR1eX+Doo9o7"); - a("+n1Btj+wv6+9J9AfbD+6W/R2d3T0dPZ3Bq905VF+ib9fRDsJH+K7kOM2613qtJPvjOr0vNSwId/DzEGf/DggNDwTS0ZX92DNRm"); - a("IzevRSZXXx9NhmNTKViKvRy5VE6bpm0X7AMFADpoBpYAbI61rk9gzeBaSvmO18nJ7H+s+0Gc8d0i9qnrNDw6PimeVnMg16qLd/"); - a("8QAXvc9y8sjpIzdb5Ht4/uR+wn7T7GCwmR1Irruvs3eYzpeG6euZmjpWVS3yGyvzj9V1ROvumzxFVsn8oHI+mT8sJ8j8Xi1hI7"); - a("+Zvr4/aDuXXadhIAx3AQuWvAEbJFgYOU6cy5LboiAuUkEsK8dxG9M2qZyECh4ekcSTuplSV0LCm9Hn+W3PeOI0PTo5p6vu+Pf+"); - a("9but179SR6//k2y9/o/1D6//jZI330uG/e+E+XldR7f/ZhR4rk+ogyxv+KEOev8PdXjg6qD8/v3PW++zQx26pr32P3J1aNUhV8"); - a("bzHjfUo7YqtF+uHvNpsM7VZdL5r48719+H2u//0imv/5sq/OPLzn8+jfbHL1r/3xnoqsKWHvun/MCP6+Hya6wA1dXlV40KTz0g"); - a("TwOym/FCvqBC87h8OwMK3/X6Qm62C+/nwbzp/EDDZLTRYJevPnBKFwvRHGqS0HTSvfm0Igmjgy4BfZLw0aacgmXj+JT3/fKY8n"); - a("gB/VZPacphPquLYVwc2PnTmNn+EPwRWDtfPM0XZ7Y/6cefdFXUp4akSdR7R10flmtNqTft+rtugLc5CwPm/LtmLdc8pgEJsrSP"); - a("M9dbDvsSUBaPcQc0SkBuOYjoRR4DB4gZ4hBxhObjiGPECRqfIs4m7toNCcbRwPahdrPZqJGn/QoYp4gDxAxxiDhCzBHHiBPEYw"); - a("7v6lLkw3lcvh/jOwipq7ZuyunnQqTvId/FUVSqURPLUg/YGlFMic70u9ooUTkWRuRaOi5VbtTJ8dYotbsYL38avd9ridZr9OH4"); - a("1/VMfRCVFtXE3c4IPXQAt6XQl3qp5uO1VHtRFVpO+s7sdFM6valF209n6xuyyb56u7iK57WNdf3642pkiJ3IqrF8ZJTSYNKvQU"); - a("/etqq61CvLoA9BP3GEmJ95+ZLP4tGCk60y/Qad/WR1UsWYH/DH2pzUdkiwa4hopNaL2fwsDhBn7nywJASbgE2tTSlYex9hKbc2"); - a("o2CtPmIUrL3vRCy6jP/tq9dvlq/J+/GSGn75sipUMehtVaHtap0SY+9PSWAtrJ9Ruy6lmZv57dfX5N3nKZ8shCM78flAy2NAGQ"); - a("eY/H1Xcrlu5/y6qUma8owEiBniEHGEmCOOESeIU8QZjociDhCHiCPEHHE81acz9VFc5Z8SPTGjjJHv9uTKZrn6NHT0m4/8c96Z"); - a("837znm26jl19spDOrneVy0K7W5aoiq6RohKFmPQhWA42ATvMqTrZh2KtrEZrQ4FW/iLbnLjPsG0epBQigPM2HB9SqDnniFuBGP"); - a("lFM+fazHmHxh8Qb7s5H4X7fErApp7nFAn2ln9zx/9kcd1+w+MdNO/4p2Af0qHd1lGwD0Dmjcfjf3bH//yOn8z/18NV/v/re/vj"); - a("8/cOUexruXtSqFbJVhU31vvDyPkzpw0DUJzL0GZISzL0jrsOVZdeh15CL+2VS/8BDSRN27tcQ5qMuKAUl8T22SYHW8aMGTNmZG"); - a("RkZGTsyMjIyEcoJnpYkm0JT5H1fpJO5ECW39NzfP9Z9fn2EAleMdM6+U3PbJeSIv1jWvOKBP6A3S0anlkrXVLLPzFMv2y75Gxu"); - a("DyKmRZbZitqc9+TONPH9PAvHGTQUN8zgfuJ87RC23i5YpGU1DKse4BT7NsSu1VquO7tl+CRYk68wYKMUSuZGINbOU2J6xLJ9Yp"); - a("+RWpCAJgvhZlD/QuagN8jcbn0PBVL1c8jFVn2r04nWr6F+dpH6K4K9oJVGQ/mctmNZyv6wm9OkrkXPtxfr5j3q75pes+xSeuQY"); - a("NVpqF+59Q+nKD9vyG8EZMQXXNTpVGIqUxy2k8n/Z+QyPKyeUNhc4FtIP1XjqivGP0pWy7V4Y/hH1ff44lDbEfAiHP2dI6mBdKm"); - a("dQ1hyZgHJWKucwDjbQvFS+Y+U+K2NHFeWcOP4Bu/1EGDhA/L161PGOffPcS/WaTP+gUuz41ENrV0y5gYYFKpUaMy6NoPqSp+PI"); - a("9ZnzSDuIuuPsAKHjKvRhcByRcZxfJehvoA8D2Ihe9+P0A+i5IDMyzJMYANcUHB8Mzme1IPLNaSFo+/K1DqyC44KryKz2FeO8Bc"); - a("cFQZEBHV4kc//A8cHK8bYWXLUYFwYVh28UVB56LvDXe6sfnwOOD9AhPHedPCFdcJFA2tU7FTwGFxPscnL6zyFjMz4pKLVux8Kn"); - a("4ITg0f6OAkJ+ChwX5Mm+103QEJwYjMl80IEO46JBk4+q2cmBCwMbiGo0nBjAgZ4LPow+6ef/DpwUJBh8VrMjcKExv5tXIMgVpE"); - a("WD+01BM395cJJhvF1Ug21wEQN29YuK7IETjMyHu7qPeQJOMAbnSjqOuIxbGG1JWcWcQi8ZVlf31D1dg1sYQKdKYgB9jJFytJ9M"); - a("4pqCjxgTh19VdNZjXKzBr3+g67kBPmqY635TwF1wkjEsUCnP6/bkdcZ64KRhK8XoiiHjR/q5/a74nd+HXjRUwU7l+AkT0QYnGo"); - a("VgE+omcT2By4GD/WWcxE3ARY0eP1VDJS3GJRsZYGE4bMU0cAp+uRf4x8zlG51qyaeQll5UO7/U/3kTxq2llluRk0vosZBekfVj"); - a("Xn94qX5PXtc8X7c09a6m/j9zV87rRAyEEYIOEOK+ZQFB3AIEEqLilpC4xCGgoDBZByw23ijeBUJFzdFT8l+oaBAlJT+BkhKPPZ"); - a("MlXnvechQI3ntJ1t/32eNrdux1yiXuv08e59frTkMC/jrLf5rjB/0TafwKwmMC7jqbvxPH/0v95XN91j7Av9R13v54mYkj9Ypn"); - a("rZrfCK5k+8fZGfWPVzSusuknmD633nnrztULN67fvnM7k8/dFEcyQ2XraopBipF7tXtgd/tQxAiOPj6axm+nflSXw8rY2h61Eq"); - a("kc1CNZ3AVpQMJp6sdGSDGwoq7836NJ3KauXsAqmNu76TeQDhQrKlKKf0uX31skKkwHt4906AS8oFVUynpBPZ6Uakyfd/F7ErpE"); - a("BSSmnjMk9U9RPK+ZlHooayWMHKsz4pyY0/hPipAvWYJnMhPqhXZa/exQEDXw5OwwWDjfXpSOvjWCLJ2HLeY8Kd1tjK5lzv8/SO"); - a("uqZakey1Jc16Ww/gBU35bxUGjhOafNEA9a7FUPajypZ4FLB/apJ/ujfMDU/M/y8dyTJfEP5/tPxLNw3yZscAd9PibTagI3B8oe"); - a("FTdLJa0SjfupnyhKbkVjdA1h2VnVeICPTkpTiKmCNqVLldDdlcj3dGoqZMU8dHGbEedbJ4VAjajwjPJO+q0ZnZoQcJHJ310jH5"); - a("UKxpqhPyVfjLR7C+pnxMAijtcbBaQfeNSLjN6Ojp4zvInV0vaI9QCJatnx5wrEEEZyqKLx54l8psCgV65cdF0zmc9YTxOVqbQu"); - a("LKC6uI2Iw6BC29Yh1tqvXDpA9Vg+Vtn5CUoThcajkS1t/01ZPcTw5aGOMhMTF2Vj23vMT0gA5sc50nG/G+W7JuGY9Q1WzzNl8w"); - a("nn3DrDNc5o+wfFAVE1fmniEcxt9mivdg9jumfAKTeZz0O0Py7wj32YSjx/Au1evZhIA3c49LGlU7p7tcsAChifBW4e97f8wiX1"); - a("egML/7DP9dUjw84Xgbj1tHDothcUnH02dHUAAxC2n92k9qitFzlSmXLG+FcRP6RuGxjTP+kQ8chl4vsX6bTeUpbf+Xe3lXq66B"); - a("upLv/OLr91OAdbRMW4vdT+XFF92LF1QFQh3FtbTR3SOyjL+vkhAQEArKUUTqTHw2qeDSz4b7S/QIG9HArP6d7Clj6aVmOnhUMm"); - a("zv1oKra8sa6psPPw8yn4NaBbVxnV/nrg1WT1ti70axsW88jKVr/MrT9vyek5CoSx88dd89TlzMxH5zORH8+UqwlQQvL5i3WEm0"); - a("CUGGTrbdeSekCQ6h+kN6+kVhOdNdJO6R5I6LZUxIREwJPJ/7rFcdN7tILpXxu7uh6DkFy/oPvMxoKnZ/wI0JhoDGD2PUR+JlAY"); - a("pYpfxgS2fkgfy1dXra2hGR3l/f9Wd+hZPEldEQXXn0kX+nBXM2UvRhdI4lb8/RM+9/N5Ofvczo/XSzwn+PY/fW7nEs64eErlfi"); - a("zH337/Gf/9dcz+9gc3r1y/fKNz/dhifVtVi1vn7om5Dx8mhCs4vLSfpw8r+Xi2b3z2+xuMG0eGAjtFXyp1Zza5YkbVYn2vXn3n"); - a("UpjGz5VaWqJd23cPwX3k2bhugcfvESGS95AGbUWvKTcfKB8Ob5oxzNKq8BRqycx8BWy0UPKN8rO5w7eYqf3v2kz514smOoYffc"); - a("F+9d3/ZZ4zeHDbx/nwbdqPIv9fm0K9SPj/zLxkZ9aPB8H99wQ45DJ+DOkN5UQOdT0LkuBHq0IVR5m4YKRHBCjJzNO0WCrGqn5S"); - a("4f4vxg9tdSQiUSNKv5r4/WK2KJTRqkjnI+b1CATkntcj3mftcYy8/xPzt0D+vvGathY8Jjl93PhwpDZ4s44OzZJ6hBwHJpLLlG"); - a("tgXaXbw6LURglX+7lybezqwPI11gZjN1rkxn2Ev2E3QiKQj8Odb2xwS4T774ouS4g5F6KQtRShClj/ptV91Ni2UNl2hpsLjlwQ"); - a("T3Tdi3cYEEPiTa8HwOY8cRm/PLMXb+EQIwBw7aqNMy70POHAE1kPn/Tof5QUjZOpb9h4ZKG6H82EW9iscvW9PsH/7NEMIGz7u+"); - a("UdJWlrocBLHPlIXS9+l74aQWqWnzYL/bKldPCi1zioEDkHsvt6L0OgpV1ZUUXvfgFFcMAlcGtincz9/qYcfyb96pgXgp6MPTu8"); - a("mfSbU7w+3qbNT8auWCeOGIhenYQ2Shc3SCmSbeiiNChFRBGhcJf0m9072AK82Bzo/p5n+xmL9XmYCgF+M7bXM/M8M3s37x/qeC"); - a("nJB4yoOl429SDSAiLc40R9RDfsouQbgGJ9Rvu8mVgoQNGeznH3uIGFT4OxbJlS+nNQzowQnk/JXy8SCPX4Wv5u6H0jfp8u9olR"); - a("jFyoioL6fYOgKGIl99lTb7pSh2mq4yD1ENPcN8of3YREv5+3w7QD4VDYI+VHYOO5L86XSW3xjbqucL4E3OeFHj6NvBBnmHBRnA"); - a("PqiwKa/oV6svXr94mA1n2bdYpQaiEAP/NXn6v4NWEFpcozwqz6mAqbLZAl36iPj9RrZ9FvUF9Ss3WVIvX6KAD/UukjuZDsR9YH"); - a("AQWm1vfm+j4K+uxcj//B8ak1cJEm7cxVLq2GZM21Cxkx+FvzEEbTuF2n8+uQHFGU3pj/ZeZVBzj/aQBP/++w9K12ZuMr3KFMsb"); - a("KPen7AAuap5Pj8fpfv/2f93+CN1B6WkdjNI8h7qKw2J9jP+HV2E+7hGdkJ/qfMj/ebp6SV0OZ5W1/8+vP3YmNAmsDRQol8i40Y"); - a("oUqOC0UfkPf8vFnBz6fmXMjPX5I5+dBjoNhvG5FDaOtliJT88PqASHpr4siv5svl2vy0Y7zBfT95d+oV67Feqn+dHKsPquIhmJ"); - a("DdcbzA8xb+kMxDcd/JQ2V7f2k2h39nKwechMbPzhkpnov4EomJT0uuI1byXUAS0ubtsem9bIsirvqAyIBmvqe8zgZK5dlBzSuh"); - a("ji9kkHzPec+/TkA9cod0+xMRzf358Mo/U7DqXCZvS0DzHGysDW7oUNpAfCN/X8m3NgADjjCxv4WJ3qv93bfNdMuaikHp+6w7G1"); - a("eK+w7LSA6FfuBb6/p03N72+d0dPf8oEInvnN8xJAddPjmpcFqY/ulWKjvh+uiipP3/Rx7Qh9wt06SGKB3/ABGIYKZYhfxcrS/V"); - a("XfD2KruUxpVeX0LI/LHoiz2Gz7RdS6vTQBT+JjYmk8ZHfWHEggUfwW5qra9CQa8PFBUl6koUxW50JdqVuBMEQVDci+JO3Ii/QP"); - a("D+ANGiuHPRjTsXBcGNfqYTJ53EIQouDie5mXO+b85rQi7cu220iU5Gl9m6fH9NvVT/XkdcctVGxv7K62RofM6pkLdfy4bq//rp"); - a("7+IrP1Bbfu9y8sDZo1TYpNbtV3oTpYMd6GInetiF3diDvdiHA1jAQRzCYRwBbN/dzybnzh47cQYAqvz9nusK96HSwhVwF6ilA9"); - a("kVpxuNpWgMKT0X8oY4/fkbkPl4uQ5Yx8F8aV1u/bIalvVqhbX3uO4NpUPJMKKaQI3661TZrxKnf2tvCbwF55K4DoilDpZ2RSe1"); - a("e5bZa5vsvqCFgOgAma/0OlyKsOu9dV8vueRcFx3tW9n4NfjJ7Fl6/Wh2rX1UwK27qItDmFma9wpjVQnGoIHBdCUGkxUYjJdjsL"); - a("gMg2GIwaiOQS9AKLZCnFY4DnVrOVoTidbYR2vRQ4t5ao1ctBh/+Yr82g20p8vQnoRoj+toLwZoDyXaIx/tnkd/62f++g30pyH6"); - a("kzr64wD9RYn+0Ed/5KHfY7zExtm6tBYc1oJIcz3DD4lfJ35AfEl8cqFv+Y7PzfVxA/G0jngSIB5LxIs+4qGHeLQUcc8lzhriqB"); - a("wluRw5Dn5FXtWYjruZO50jXY9RgIg4EXEi4kTEka/ma/MBO/EjZRNFrPSxMql/lZ9z+JmvlH9A/pL8ffL3yJ/cRy7518h/Vco/"); - a("7zs6Adw6BTw9nuPUDNGkfZP2Tdo3ad+kvXw0zwv09YXy8pSxt8BFsEB2+XrqKq5mfadYklg+sTxiEa/npljzPVvs7x1ngeeUz2"); - a("eKfWPloPJi2pj3s77YrPtig4cNQ0pac9vTWBo4OobW2pvfx53zgLwAdKgtcaw08zoXgSuUrxeKMcns0/0nOg4asxrG+0tA6zLw"); - a("kLp63A2c/LXiodfqninnrJ/b8TWO9Xq5h+UL+Y76+174cRV4fI29cNXYT1LGS/XxKqOPK8R+003WPOXzDc2xMN/X+ljLOl3LXl"); - a("qrfIishxJe5+Nsn3lqZhSx8v5scy6ind7DTM7dBu5SXlD0Ws3fjFXm38xTee7KZ+R8jNSaG8aa1RKrRQz9U7OGjZxa54fGrMxb"); - a("LoHkvMnHohjT8pjZtcXmf2jzXSuZr+FP94GvlKeU/83FPIuVtubRzE3pvEqMeWa8E9jvy2fvn3r0j+8TQQ2B2AJaG/Vt1FLel+"); - a("I+hyWdVEfhkt/nWr5fjz0BvlPwVOe2eJ4W9b/mquzd2l7/lnOmYK96v6u63JJzM2f2s8V+npm2dl92v4Yu5W7NTzFm5Tn7yap5"); - a("hv4UhXH8eey9R4SQn+y9905GRNmrv1227E1WZEYoI1FSyi6RTVmFvEIo8YJIVrwQn64r7nPPPa5x69tzzv0959xznvOsc84vCx"); - a("rqxr/an0uf/w91ydtTDnl9/jDR9qZR9+Z18Vj4r5T4Gck1gOy8JHISnAF/kyNOvixyCNQDafgLXxHpCW5fTjtuzz42dVxKv+7h"); - a("/mtK2viT94ZITXD7eooYFuT8+cj58+Iba8X2T8/pZ8JNXCP0R1uvr8/6Za5ZJufZG895DHX6NrN//+38V98T2Qt6A0+/zn2StS"); - a("efDfr2uDZ/Pnhf5MsDkRFQu++y9UTbzqHB+lh9CKnb7xfNI0WJoeG7WI6H/UXkB0SeiRQDVYBLf517lGkm1mQZf21knobHt2+K"); - a("6Frh3FJYj0usrz4/dGfrL7LNJnl0y/e5LI3k0iZPrmXy5JB3k+H15gT/Lb5YP/jzfZDTVEMvTPlv4lbgI3NK0dCmvp+HcQZGPG"); - a("hNPGhNPGhNPGhNPGgdnF81iH83sIXc2AJ2wF6yTHgWmeocBGp98/HsKlfBCJDGl9o5ROLM0aieT+W3s+Ap+DGGgO/td75s4Riy"); - a("cqlsya3yBj6lPpD6VeovgTeXQf+S5OGai/uc1PiaJoWlCevRhPVowno0YT2asB5NgvWoF/PfdQuo1C2kcj6/OmVwhN9KFVZpCV"); - a("znJDFfuykqm4mcWpcsSv+0F56y1CtQf0Ld5zt+niORX6APldCHSsF+vE5sDlOKqeQuTg2auO6hb0SHYvHgE20LllDZA/Wdr1uf"); - a("nbOkykCwgbY/+F39v4DnPdgArB/wr/OflxPPtDYZnUqRE6Y5y9heTuU1KF7erGeQN+Qhb8gd5g3ud2lz98g7M5+ksc2ppPIc5K"); - a("/sX58V/L4bVAT+/NXK3dqD9VVRWyifwU+Bw1W+fzkf5WngNnXTV+q8YVxVlQugIvgxxsidRTiO8DdzPpuPPB774hu/2pg9nz1c"); - a("TeVLdZV2UBNnnDmFK2a65GN9xeNaKutrqyyGCs8j6Dbqe6BuuafX0891VLLqqqwEzvzJjtHa/tHoWPfUUzlVX6UeVHi2Qi9S7w"); - a("21srY+0q7h2AYq1RuyhtDYOtn44Gifl/ub8mAEffhi5U54ejVmHaFWz515q/f+Ktr3qiYqBZoyB2iatT4H74JmjAUqPCegK6iP"); - a("gP72/Ay+bM3RC6hz3MH5L2e/jLUk7WM5A20LtlCZAk3bZhb8r0A98CdrM6WlymdQBHj0LrW952+tsgacb2V1xb3m1dqotAC3ae"); - a("PjOwDPRdAbJOov1NrBprYqg9rRC1R4hkEXUK8IdbW3uVOR9uROHYiNtBGeXNR3UT/cLp0ele6osgocpo3wFKS8Edzu4J/vO3jy"); - a("dkKHoD6+2fBsAhWBkcsf2UezzipFuzAu+knT3vrgB7Qt2RV7gf7OPubAtx+0A+Ede0jt+YTfZ/vvI/znaUm5RuJdQthX+rzG87"); - a("2kcWeKSIb74QwyzyDzDDLPIPMMMs+Ea/ZH/Vt9iOQ33WJ56qn+KkMG4HegYdu/yJk8Z0uRceSiTc5w32XGMVil8RDGAXXFyp38"); - a("dh98BSnWw8rFm2vdHYYeD8feoT6+2fDcA/WA0w/0ifqB7iOQLXgDv/B0ozwaFAGRdg2i33nI7x/BYuDSGzPv1PFiX5ZKoZHYIN"); - a("Tl68s4fFmDUSpDwXnaKfXqlNeBYyApl7D+uNlo5j2GPmgjPBWoT6P+hLrnbt2ztuZdAvXcxdi81O9b3O/DfXtucrFcgdy+75vz"); - a("EivzECuJl7xHFvYcxanftyaxB52s0hEkfT+NH/Ddk5lyStl75BFSKwe3zdeI2fywGdj8TOwBmmZvux/eorPIx6B/8l+dJbR5Bu"); - a("oBMxfnWnyYTbyfo3IURGzD6HWjuSo9wHn4DjzLJgUp9wNjgC9+X+P3h2AKiMoqJ7LK4fSPLeZhc+DNr21+OTeysuoyX+UQeEKb"); - a("SExLabOzF6pkX0QusuB7j1nUC1A/v8DMzXx3LTynQT2QlLM5xx/KKPuP7y9ROQKeLP7e852lrP0yyrwL/BLlpaAi9fAeyH+/k+"); - a("W6twErVHaAc8B79mPjiD9ux3SwwiqVzGrkt1JT3b/9y51Mkj9X8GCNyrC1+F8gPPepT6e8B6o/c7d4ztHHf4cX1adcMb24s06l"); - a("73piGvR3/yE7CN+VjdgH9LsPXx74cP95rD//HL+ZfTyo9419swrBIoii8PnHLuxE7O7u7u7u7tYXxcbAwsDu7m7sBLuwu1FUDG"); - a("yszxjz2i8+uHA4Z3ZnZqd28i74md+b+Ik8kvk7bLWZ9jyLNCqgrMCol1/f5/Xp+Mo26Ot5du4xrB/AltE/GHO/WsNkGRdQC7CU"); - a("cOKqNDagAbgP4f4qXfZ8zsf/bj89LPvpYdhPZy+d8S03fnMzvuV+Z3NX7Zu+qu2EgDpP5l3jjXe9S2+Id2Vq2UT9ytln7qnM1Y"); - a("DAr/i/g78C0ygL+Ed7KzEjBFOEd3mKJp+nYCIe8Hw648HMgA4A3GoyK6DL4BXArbPcHzgnoCVAXDfwvwwtWFzj4HW488Gftxm/"); - a("B2yNE0/mUofz+GbgQFjGhWbv9+e9/sre5Qs/Vtl+3f5+af0QI5RiNALs18d41z6ifFPfWszabinpXOTrw9utZJL3G0RSu+tOtZ"); - a("YFtGpFQNtX4h93Htw70VoFRN3iDqC3LP1QTr3fp+/LswTOEWiLWWiLWWiLWWiLWbzN8VdpS7+GfZUN9CWrA98dh2JGDqbI5O3z"); - a("9Ab15+ybGHdBOeIQV87N9AlbiA83d1RnY0DJcJcF4sqFuxx6C8/NebkxVh/F/4GtxAn/yjyo3DbSsJ25wNZff8dI/DffQf8Hf6"); - a("zjd+cYrPMpv/iU3w/2v386xvqzI6u/jLg7oPngIPilNpcszNd20ub88eUexq69jF2wlS7bnuar78ewG/P3fqVvObQ/oIUH6I/g"); - a("H8+zf38f/fQh5seHiRv+9THYp5czdMOu+d6RgPYfpS+EfXnY8/vPx327XocfDyjFCdo++FG9WmHLn2TeBTaDH9o6G/P54acCug"); - a("nSgV/xX/90QBuBgDGf+uF8dsAZvk2QDvyqLUv2swFVAwI/8zsPPztBO/B1PVg2Kn688GyeWZynT7rAOgkW13E4Pe52cCB0EN7h"); - a("0n0Tx5Ev48h8iXUMyEc4cdW4GFBb3IcuGHX9t/aoRtsfciWgcyAf+O764V2/HfKLOYhfPzx6GFDfR6wtr76Pse5j1gug3Ad3uO"); - a("u0iRd8W7h/Na1Gv/jT+o3xOqCM4OKrX5urDMXvIlAOWOdYRvv9yubK6KP9/d+0ny8bxOkBEHg/nwCMFVH9vobvJ41+5+tvMG4w"); - a("p/T4vxjUfdXPY99OmGTEm+zdGJTrm34+dAinQ5GdyhHev9OzWWfOu3/+j1mO6E6jYxIA9nYvvzb3tdPaKpZT5/TkkzjftZdtRn"); - a("vx65XlP7ApJm/WM3st/+M22DCz01gQD/xof/M6zyNmcVoK/2r5DcT/mazUDfyjuLNkc6oPBH7kbzXPL4Ge4GfvzpPd6QAQ+OG4"); - a("/6n/NPdOvo43aC6nXmBpTvdL3+wV/MbM7TQV/p3xfThhLoF84FfeUzGPU38QAfzOe+7jP39e0gf/rK1swN910BNY43b2fE4jwB"); - a("pgPQ+X36kB6A+s55fePi/Ac/BNG7PW98Z4nqGg0ylwkTjMcwe+HWtf72ZhpyxFnGqCH+3FPuN5kaJOLYH3Z9nof65/Vq6pijtV"); - a("AfeKOfOd83j2HMQtYX179j7JFPxGLelUD/46nV/PE36WvrOlCFeaNgL7uH53vFhO+LugHPid8+juZZxugHjAp9+fDZr1U5Y+u5"); - a("zTevBV/f/CuvcX3L9kJ22nLXVVpy5gCvjRuUqCak6VwFL8BURc6H5gAbDifcn9MtWdOoIfxfuA50lr8P3C79o8XAN3D2DsNZvr"); - a("qlP4TVXTaRjs82rY5L5fNzQw1g2/sA7ZV8+pfH3eAX/0HzuMYjPGxiZMbMbY2Iyx1v+xpwjXu4FTO9hYh9pngA1+zD/ea/39by"); - a("F9E6ch4GJj36Z/3RYkfVPyB+4R/lfDXMJ/hmZ8v/CvzMcG4rdwc75V+LP52Nf/GprtYw3h0rWm34G/3mP35f9lGkKRhpDfpCF8"); - a("W6eZ4FAbH4+3dY7u3V/lPxT5h438DG3vlLoD6YLf/w8SBhuG0NgwfLbH8dV5nGkzQB5+kX9sc9DB3tf3+Qm8K+uglHUQytpR1g"); - a("HK+gBl/cG2Hv0+hl8vg9zdndr3os11+7YP/2ptaX7P1j3fdu3/Dez+8f3/q+GUDJvfZEff5jM0+QxFPmlbpNt/0+Z56RHD7vzr"); - a("fOPHumd8v38exydb38//JzJtfQeNcHo2kvELNuwuzDB9RzldG0MY+Lv1++Crf4TGOm0cx/wP/tUwecczl51Amxj362Fe47/0JP"); - a("oS+FfDHMR/xCn0yXAgJnXaLPj7ev1szzgQLaSiNQuqaPQv0ahr4jDPzO26+cH/0l7/yhm+/X/2z+2X5jltBflA4Ed2qnyT+n/9"); - a("k1eEaFJJUG1WENWDe4F66GFwquhSM3Q6uBYYhq4HnwRj0Rfh+2ADWjGksGAH+l4cKUxc6RA6ApwEnESXiydNBhfRU+FE8aXb6H"); - a("RwLfAQXQ8eCV6gp8L7QdDZQXQIvgHCou/BIRNIUdAR4PggNvoi/Cwh8aKVSMoGUqHzwUUS40aXg3uDYuhh8BpQDn0RHpaEckDD"); - a("iplUaoSOBzcD7dDt4KGgK3opnCyZ1Ac9FV4LBqPvwdGSkwd0PHgamIheCqdPIS1E54ODpaTc0BHgBqmlXeh2cJuM0tG3Gt4IXq"); - a("C3wFczUQ5ziB9elZXsobfAM3JKpdBL4au5pE7oe3CRPKQNXQ5Ok1eaiU4HBy0orUTnKySlLiKdRaeDN4Pb6C3wLfAQfQ+uVZQ0"); - a("oOvBM0HQubwLPgnCoi/C8YpRF2hYpUA8dDn4EUiGVnHKoyRli54Kbwet0IfgmWVJM3opvAesRB+Cw5SnfNAR4ErgHroefBK8QF"); - a("+Ey1QgDfN4F/wYxECronQaJENfhINUkgqhI8CbQCn0FnhZZer0rYZDVpV6oiPADcEwdDt4CpiIngoXrkZa0eXgcNVJJ7odfAzs"); - a("QF+Em9ag7tDt4OQ1aa/odHAJ8BRdDk5bW9J87sOtQDZ0uzcM3Xl0HVMAgPFBUU4x59hqf/ateAiKYFAEwaAogociKAZFUIy9Kh"); - a("gURfHsRfEQVBtMq6gqXq0Rxdhjf4i9lt8f3/m+pmky986997VNOuU5GKYbvPjhxqxDPhttOuXoCPdUR3wMxuuEv8ZE3eCNK65T"); - a("l/kiTNYZP4gpusZbeSZKriOegT5d57ajXKeu8AwMfMjb+cSj3V+d8M0o6Sr/gCG6wfM9wqxJB8f4u3NEOuYz0KJT/hOxDo41Vo"); - a("zQMXegolP+F+06OM5+QofOeC7G6oLXaTd2XeZ2VHXCjxxvvLrGs5HrOj9/gv2lc17sRNeqQ95slPU82Tzw/Qh1jd85zRh1wX+h"); - a("SQen+zho1jlPGO180FV+DKN0znMxWsdnGC/G6OBMaxWZjvlCTNQZv3uO7+nWBS9+rjNTh7w9enTEV6DQGXfjO53zx+jXBa88xr"); - a("h0iZ/CwIe9D/+D9XRwXhCsiSad8e7nG4uO+WS06oQHXmDt6ZAfRruu8ZgUuso5Mp3zB5igSxe6d6hq/wdPsNrF9ogucYI5usbP"); - a("XGJcOucDLnVm6Qr/hH4dXGb9YMAjfi1/jEG64Lsvd190nRcdayw65I0R6TLvghYd8/WIdZV/RZsOrnBOoF2XeAckOuIj0KEr3I"); - a("lUZ7zEOGtPh/wQMl3jAVe6jzrk9XGPLvPumKxjPh1dOuW70a1r/BZm6oL/wBwddPqncXhbl3gzzNMR74fPdYVPw3c65evQr6s8"); - a("FfN1zgte5foedW28CdbTZY5R1jEfhaE64QyRzvgutOgaz0Cs6/wpRugGL3i1PatDXgPtusy7ItExH4UOnfBFSHXGd2GsrvEcZL"); - a("rO32GCDq+xNjJrSVf4OUzWdW691hzqmDe6zn7RZW673lzpCl8x3lzpjBe8wWuHDvkiBDVv5wVvtN91dpN1NMG60hF3Yj2d84o3"); - a("+zld4osQ6YwfRauu8e8YroNbfB/Era5DR7zjbc4HHfOxSHTCl6NDZzwbqa7zgbf73LrCt2CCrvKrqOo6r3mHedBlXrRqXekSj0"); - a("CPrvAldzkrdMZP4Dud82fo1w1e4m7rRIe8BgY85mPyThikYz4Ky+iEL8LKOuO7sJau8QwM0XX+FE26wTve42zRMfegRVfutZcR"); - a("64J3v89c6ZjvR7sueN37zZXOecQkZ46u8C0Yq6vch0w3+LYH7EFd5esednt1lR9/xP7SOS9Vs6d0yKfgc53wNDR0zos8Zk50yP"); - a("dhwOPGyLs8bp3omN9BSRdcesI+0hyciGadcA0tmoPvMFw3eOku49UxX46ROuPfnvTaoYOn/H4Pqc55m6etBx3xAxiva7z8FOPV"); - a("JT72GWeOTvioqT63TvhjTNEFh9Oc1zrkLTFLR7wf6rrCp6FHp3wdCl3lx9Gnc34TDV3wz/hDB93OKwRPuB7eDAN1xOMR6io/jp"); - a("V1zm9iLV3wzxiig2d9HDTpEm+GZh3xfhimK3waWnXK12G4rvLjaNM5v4mRuuAlnzO3OuQ9MFrHfCtSXeVedOqCl3jevtNl7kJV"); - a("5/w7Jusgd16iS0d8B7p1lb/CLN3gI6abW13hVWeYW13iZvyhI94fQZf34dMxUKd8PUJd5RcxWNf5M5R0gxd/wRmlQ14TZV3mnT"); - a("FUx3wkIp3wC2jRdS7PtNc0B3ugQ8f8AlJd528wSTf46BetK53whejRGd+JQtd4Ovp0nT9BQzd4gZeMV4c8AcGTxsXTEeo6f4XB"); - a("usGLvmyMOuRzsZ5O+VY06So/hmad81wM0wX/hFYdzPLnLwzXJd4UbTribLa1oTN+EKN0jV/DaF3nbzBGNzh61XmqIz4Mk3SFz0"); - a("JNp3wjpugqT0Wucx47x6XojCehX9f42NecM7rKb2PQU66fz3vdeatTnoaSznnQG+ZBh9w51/3TGT+BSOfcQIvmoPVNZ6yOeZe3"); - a("nKE65j6M1A3e6W1j1zGfgDE64S5conPufMd164xPetd4dcLT0K1zPvw9Z6yucD/m6KAnCK7GPJ3xo+jTNe5437XqlA/stTZ0hc"); - a("/BgKe9nVeaZ8y6xFejWWf8L1p18KE9izZd8C0fWc+6wcHH7qNOeBzG6IzvwiW6xjPQqeNP/Bn8U+eUDvmzz4xXN7jzc2PUGYdf"); - a("uo865B706YI3+MqYdYUzzNcZz/zaWKZYS3zmN8aiU2771hmoK1xDWbMXCXtWB5wh0hnPw3Bd8JDv/Xpd5rMwUqec/uA+6hrP+N"); - a("H86jrPbfg5XfBGPxuPLnM7qjrhPkzSDV7nF2tYl/lR5LrGX/Ubu27wm7+7Jl3w338auw7+Mg8Y+Ixx8cS/zZeu8XQM1nX+BCXd"); - a("4CXnW8865NVR1mVuwVAd85GIdMIXokVnfCdiXePpGKHr/AkqusED/zFOHXKKRKd8LVJd5dK/9qfmoIrxmoMnUNU5v4VJuuDgP/"); - a("dMB7wSpugSb4FcR3wDZukqh4F/E6dDvsLXbD/XGYcL+nrGVG/nOzFY1/hAz0Qp6wqfg1ad8vsYrgte39esR+sy74NUx3wKxuqE"); - a("r0amM/Z3uMEEHfLamKTL/ANqusGLe/5JXYf8m2eg9GhfaAp2wcBproF/wTI6Wsz3iqGkMz5pcd9PpxOejkjX+U+06sBzSrbGcB"); - a("3xVFR0zr1IdMHHeW5Jh054V88a6dIxP4C3dc69KHTBf6FPB6E583yShubgWqzVbT75FZR1nf/DUB145sgQRLrMG3iGSIsu8/7o"); - a("0BU+A6lOuYqxmoPHkOmc91/G3OoKX4opOuMnkeucz/cMkVk64yfR0DkvtNwCwR865J0x+Fnj5XNR0ikvvLy51SHvgCYd8XFo1g"); - a("nnaNE5Nw02zzria1HRVf4Ao3TBy6xgjLrENyDVVR644gJBpw55HMbrnIetZPw65nMwWaf8ELp0jV9Eruu8+8rGqyu86irunS7x"); - a("A+jXNT5v1QX8Yc7H4dbVXJOOOcd6mm1OY9QBb4UWHfE4xDrjP9Cmg9WtMYzUES+3hnWlS7wbMh3zq5ig6/wDpugGD1zT59Yh74"); - a("NZOuZjUdcJv4seXfCpa9nLusaz0dB1/gZ/6AZfuLYxPO99ePl1rENd4m3QrCP+GMN0wb9itA7WdSZgjK5xuJ61p0NeG5mOeBQm"); - a("6ITX3MA90mU+Dz065eM2tEd0wud7Jsd8nfItCHP3nadisM75/o2sPV3jjxHrgpfa2DzrkDdAuy7zM0h0ztdt4pp1lb/ARN3g9c"); - a("vOHF3mPdClYz4B3TrhHs/hmKkL7sd8HWzmujBgunnjbTBIR7zt5taMjng4huoK34BIV3nbJmtGR3wIOnSFT9rCmtcJT0RVV/kN"); - a("TNJ1Xm5LZ6Mu8c7o1jFvsZXr1BEfgvm6whdjwAxrkm8Y6jp1laeiWee8/NbutS5xO9p1wuMwWme8/jbmUJd5D0zSMS+2revRIW"); - a("+OeTriFZqtQ13iFMu84P5yN0o6514M0QU/tJ0zQtd4JkbqOn+DUbrBu2/venTMJ2C8TnguJuqC+9GtA8+MWBEzdYm3wRwdcWdk"); - a("7+uMH8SAmT4v92KQLvjhnVyzrvFsDNN1/gatusHVnd1jzcFUXKJzHjzM59Al3gaTdcR3okvXeCbe1nX+BfN0sIvzZFfzpiO+GC"); - a("u/6Dp52xavHTriQ9CmK/w0Ruqcm3a3H3XMLyPTdV5zD/tRl/lfVHWwp33R6t7pKk/DTJ3zBXuZK53yI5ina/wdPtcNXn5vP9Yl"); - a("Phz9OuXJCF7y/rzGPuZTl/l8DNYpz4iNRdf5P5R1sO8CwQEYqiv8GYbpBpf3s981B+9jhC74xv2NXVf5PSS64KWGW6s65Ntwia"); - a("7y9AOsGV3n9Q90xuoyX4+Zusr/oK6Dg1wL5umIj8LnOuFx+E5n3DHC2HXKt6D0srHzKgd7vdAl/h5NusHdh9j7Oud1DnUfdZlH"); - a("YpROeBxG64z3bTMWXeHFD7PvdMhHYpZO+CG8rWv8AQpd8LKHO2N1iS9Gv874YczXNV7vCOt/lmvgvbCWjvkrDNENXrxizeuQN8"); - a("JwXebRaNMpT0KnrvHCR5pnHfKe6NIxP4puXfCmR1ljOuKj0aMT3vBo169j7sKgV8wV92KwLvi5keZZ59yLWBf8F0bo4BjPZvKc"); - a("gorOeC7G64LHHGf965QfRU3XuAfdOmj3e0vM1DGfhLpO+Cr06IzfRqELXut486zL3ImGzvghzNc1fhUDZlt73IdBusHTTnDO6I"); - a("L/RkmXT/RvHLCezrkXQ3XB8SivIzrm7U/yY13hLU82Xh3xkejQCY9DqjPe+xTng465OXHPdMRHY4pO+EnkOudVT3WPdIkPR4+u"); - a("8Gf4XDd45dP8vkJHPA0DXvVrec3TvY7rMqdYWaf8HIbonFccbVy6xHuiRcd8LmKd8cJnuKc65I3Qrst8wJn2u67weZioU97Qsw"); - a("Lu0WXeC3N0zIt0uGc65IsxYI6Pz8+cbf51zr1o0gUn55gjnfAEjNJV/gGjdYMXP9e60iG/iYm64EFj7E0d8kuo6zpPOM9c6SpP"); - a("xYDXfF7uxSBd8OoXuB5d5j3QomOejVjX+c3U9emC/0GHDi505iDVJd4OY3XET13stUDX+c9L3EcdXOpcRaE5OAR9usJXoqEzzv"); - a("GHznn2Zc72130c3utya1XHfC6G6JRvR5Ou8pNo1jn3YpgueJ8rnCc65mMwVifchUznPBcTdcF/4x4djDNGTNYlbkaXjniJK+1f"); - a("HfK2mKUjHo66rvCp6NEpX4tCV3kq+nTOl3Yau874L5Te8Hmv8iwVDNEV7sVQXfA6VxuXLvOZiHXKd6NN1/iYa5zvOuFxGKszfu"); - a("9a49UFb3+dseiI17revOsy74F5Ov6fYrsMlSKKAyg+dhfYhYKFCDY2dtfY3S12K7aiomJ3C3aLLWI3drfPbjGx4zcfDucg+9y7"); - a("996dh8KfV+Kp3sZnkfCSs+Ccc3zXdAGuMNf+65DXo6HexqfRVl/il+iqP3DKee6SjlwYQ3Q53o3R+jA/wQz9gTfOd4/1Nj6L4/"); - a("oSf8Y5HZhXX7zQd02v4BNIeNlrOMki76dT8jmk15c49mJ7q1Py3mXWrw9zDAboyMFyz24deSDG69H8FzN0sMLzBKt0Nt6ATXob"); - a("n8U1fYlbrLSfui3/QNwrftZsdyGk1OW4A9LrPnxprTugIw9f5+z0aF6GOXoFz17vrkbNCTa4hzolD8dpPZpf4pr+wG02+my6Lf"); - a("/AWx1sspcIrnovLrjZenQ5bozMui33Rw49mnchnz7Mh7bZt6j5LzrqYLu/Y5dnl2az1H7f6ch7cEAf5soHvLcOuTuCa17Dh5FQ"); - a("R/6KlDowJ93tsP3RfXgJ+ugV/PKI+6M/cOajzkJn4/zHnIUuwC1xTbflccedhZ7B25DwuvPifye8lw5O+n8S5NGX+Mcp33kdnP"); - a("bsQiUduTVq6bY8Aw115DNoqS/xnTP2RMdw9bPujw65M2boPrwgQq/g/VihD/NSs8rr9ArejXv6MF/FUx3DH/FWB+f8ux5fdMhj"); - a("ENywHj6PhPoSxznvOa9Tcl1k1iGPRx49gzeggN7GRy945uhLPP2i77KewUUuOV9djqdhiJ7BGzBeb+MGZpGn6rb8HAf0B65yxf"); - a("3UIa/BNb2NzyJGX+In15yr/sAZrjuXm86UVyG93sZ3kEfHcJUb1qxDbn7Teem2vA8t9WGOQVcdOc4t90en5LMYoi9xrtvOQhfg"); - a("GlilQ/6HTTq44/uOazobX8U9HcPBXd/rW17DOZFUF+AaSK9Dvo9sOoajed9yOnJGVNPZuDtC3YcnY4CewTcxXMdwx/vuie7D17"); - a("BNx3C9B55lui33wnHdhxfhnF7B0YzuNR35JOLe9tk5eYx91il55CNr1qO56GNr0+W4KxrqPjwDLXXkHeioD3MMeujIwRPr15Gz"); - a("YbiOXA7jdeTmmKrbcoKnnm86JVfEXh3yNBzWM7jWM/dHh3zlt2eljuHgjzXficPeK0JHLoc8OoY/ooAO/rrDKK7L8V2U0zH8Ew"); - a("118M/nRksdcneM1n34JCbpSzwyMJejR/MyHNcr+A/OaQO1QTbc0pGvIEbHcIrYZpl0Si6LD7oc/8J3Hc3SZkRw189y6rjmHaLm"); - a("TSitt/F9hDqGf6KpjgZbq8Y3d6FDnoNJegX/NB87Qwep/TmO6xVcOo0163K8Ftf0Nv6MezpIGzuojqc65G94q4N01okvOhuvM8"); - a("/6W2/jm8h2z9r4D/LowNzr3oLmL/Rh3lgotvvu9fwG4/UHzl84djBVF+CxmKNn8Cqs0Nv4EdbpD1y5iLPQIffHAT2aX+G4/sBZ"); - a("i5oh0dm4JG7pcrwBMXobn0fc+86Xc5tVTaoLcHnk0yH3RBHdhz8Ws3c6mlfNgrY6Gw9GVz2al2KSXsHfMEMHJbwe23Q2jsFeHT"); - a("lzSXuus3ElPNVt+SXe6g+8pZR7orfxZcR94Gd5UWlr1it4P4row1ywjHXqctwcHXVbjmXWs4dOyXmxRBfg5VilV/B+nNOHuV1Z"); - a("d0OP5kWI+9Br+DuSapc4OIoC+hLPKu9+6hU8q4KzjpqvYYaO4Z9YoIOK7j9WRF0pdjAI1/QK3lbZPujInavYB92H5yJpjLXxoK"); - a("q+J3o0r0YRfYkzVfPZdQHuikp6Bt9CqD9wYjOVLXVK7oqOug/nreHsdAFuhHW6LQ/DNj2ac9d0droAt8U9PYOv4amO4fy1rFkX"); - a("4Mn4olfwfvzWhzl9bfv5yLlzZeTRIfdFAT2aU5l9LK6zcXn00CHHN+s4QKfkhlil2/IubNKH+aQ5yJ36EverZ316NM+qb516Bf"); - a("dr4Cz1aO7c0DPnsX3grI2sT2fjno2tTffhJSiuV/BBlNOH+Tmq6Q+8oYl91tv4LProS7zbrOIQfZhHNrO3ejQvwmm9gic3953V"); - a("M3gDgif+Hq7Wwtp0yL1RRPfhv62ctQ5bW39b76v78CS01TN4A7rqbdylnfXoPjwbC/QKXtEeOnLRDvZKl+NhuKdH81o81dv4Hd"); - a("7qD1y7oz3UIa9C8NRr+AES6hhO3sl8jk7JDZFet+W+yKZH8x7k0Yf5KoroGP6J0jow97cVlfQ2fowh+gMn7mK2U6fkZZikV/B+"); - a("7NSHuU5Xz0kdcne81H24RTe/j3RbHoH0z6yHm/e0Nt2WR6GhHs3xevnu6JR8CR115NfooT/w/t7upz7Ml7FEx/DRPvZIX+Lsfd"); - a("1VXYAbYKduyzX6WacOOVl/69QpeSISPnem/B4p9QeuM8CadcgbkU1v4+QD7adOyZVRQIc8CcX1DD6Ecvowf0I1HQwya4tQZ+MS"); - a("aKrL8Xa01X0Ge5YOca90Si6MAXobJxoaOxiuU/IrjNcfuNgIv+N0Ob6KdTqG44z0PNEpeYo5vcN6Bi/BW72C3+OL/sATxnqG6B"); - a("k8c5zn4Qvvyz3+s1v3vAxFcQDG6+UDGMQgTdyhG0OFUaJJV0MtImLoILFWYjJVgkjjpQiplrjES5n6EYiRoYsQi8tUYiAxivj1"); - a("e/QmT55naXL/555z0iWz6xz3Lts/OuAXjOiIkyvtsTHd9DgmdZbnkdV5XiyYSxf5ZM29rWt8g6qu8ytq+ou/172/jm3Yq7hv9q"); - a("a7GZEOeBoNneU5/Og87xXNokP+2/JNG3677d5DQgecxoDOcHzXXDrgNGZ0httK5tddPISSTvHjvnOtI+4oezfdxZWKM65DvkXs"); - a("3Vw8e2iP6RzvYFiH3H9kDXWS746tj67z6Klzp1O8cOZ/i85z4dze1kV+xrWOuOfCO+iAJ/Ck6xyrult006v41EU+wK8O+Q2dH9"); - a("ac+y59dx3wILp1iqcQ11l+QEJHXL6yt3XraT3/7MitSwMBAMbhQw6DGBYWRNRkGgYxiJhMi7JgEDEaLl0WkWEyH5dFjg38OD8Q"); - a("kywtikFMC8ZhWhCjXPLgHlzZn7C3PC+/6cxaWfj/aw9hEHXD4Lczbstlq12FwUJ33BplWy/bpJ3pCTt8Yp8fHPKHM9eVdTa4wz"); - a("1GbDPlJXO+8I2fHLHg/E3lIte4zRYPGfOE50x5wZw9vnLAIUcsOHdbucQNNnnAmKdMmPGRPQ74zdm8coVb3OURY7aZ8p59vvOL"); - a("Bet3lavcZJP7jHjMhBmf/wSlj0DpG1D6FZT+A6U51kDjE0rrgGkEcILyw6B0Gpp8DZTfBaXnQOl1UHoPlD4Hpe9A6XdQmmkty2"); - a("i+GM0Xo/kCR75AAPfUkuCSFI/EvJScVCjfOT+vGEA31e62DcPAvJrnuliAeDFqY/6t2NdUgywZFFXUe/pJFoUlQfpLvCPFj6Pk"); - a("DFo378xgfCR/KxOQ/SfluSFylLz9A35T2qP5mrCydjYxzZfmjtwE70s9RRzWo313Vam4LLGDk7YoTCCCLfeO8x07fBDUHMlnsa"); - a("mH6BXUYnG05bg4UDB41Qa/1BIL3bK7AJkbSfMeJZnEPNTGeYnLcydH57RlFCUaO5/fE12U3TxjSYNGfHIqTnghRdso/tRkNc+U"); - a("2z68EiARCTlaFLfRp67Yb9QElVsb7zZ1DrwGrjvJem7aYhdRfkKtiUlnZYybxE4VZcc7LbbQ0erL5kv1rH3Zq6B9ukkZySFIsv"); - a("QGWNMZ/Ao7y5WkrQ/LTb4BtGh7W2JUmqMKvbbXOOTlDybOOueIjrQjzbLde+7xvUiN8wr7Hx39Cy7hegV1BA/LZUo0nxFVh9wl"); - a("eIdlx8U+Ws1aGf0XNUUrDtxjkkf/AgN+wjeWQY900gvqE0/4gbZvrrTBsP6xMQY36hn1h6LIFnNwxS9/tqq7+9+d8Rv/I6OMeh"); - a("UGYSjsX8PtmtyEp+udeybamUUF0o3M/XuPtCTiHs9HCxR6em9cnBMT8EzPWZgN4ZbiIfl8Gm7Aq0afRljX3Tu/jP4iTMXPM9eX"); - a("HnixkPhM/2ukyexqmq23pdb5a3JXXTlgu7Jiao3RYtRLheR/wS+EoRDtwFvRxVuqizt7bBuWqR0Zrxp4NcpPxBPKlpMwmqJjOs"); - a("6MLiwRub1JBphW0gD4i2OFdV6/yVMC077VZwdLDMixJhLTTcQtDQ6/a5vfNte+inflKEs+s+xhQaL/aBOls2UfpFL0TRcj8T4N"); - a("Q79TYsNSEY1BwleGqTIqJevVTHzJNxXojuRiBiRXgEqJ7NSivNQcYyO9lJwcBmAqTSwtgXJKgR6HMocp0NjAAj7bhwmKTYB8Gy"); - a("B2AeJgf58w1yCw78FnwASIActvoHgYSA80XPNzylKLQNmLAcwMKK2qykk1NGUYBQBm7I7vcSAKw/iDweJgMVgMFgMLxWBhIVgM"); - a("LBSDhYXgmZfMnJnMSzCwUFgYLAYWisHCAwMLO9vffog9X+H6H7n/45vzrpkD7oDAHkqooIYTNHCBKwyAMMMCd4jwgBWesMEn/A"); - a("ZCj/QLbehXeqHfaE+/U6CWLvQnfdBfdKOf9MDPvFJHVauTatRZXVWvZrWou4rqoVb1VJt6qaQ+sMAdEtxjiQc8YYNnbPGCHV6x"); - a("xxsOCDjjD4z4woQfutA7TXStT7rRZ93qi+70Vff6pgcNGvWsF33XUT/0qp960y+d9IcpzM4QszelOZjKHE1tTqYxZ9Oai+nM1f"); - a("TmZgYDBs3dHKZ26qZ+GiaclilO67RNaSossaWtbG0b29rO9nawaBcb7Wo3m2zhiCtd5WrXuNZ1rneDQ7e46Fa3ueQKT3zpK1/7"); - a("xre+870fPPrFR7/6zSdfBBLKUIU6NKENXejDEDAsIYY1bCGF3Omed9f8lAWQf5UaaKGD/l1pgQhrrpOgoISWtKJ17tPSLtcZKO"); - a("Y2ka65TKIFI6xkFatZw1rWsZ4NDNnCIlvZxhIrOOElr3jNG97yjvd84MgXHvnKN554IYgoRSVq0YhWdKIXg0CxiChWsYkkipGM"); - a("h7EajyOO83gf47iOz/E1prGQO7mXpazkUZ5kI1t5kVfZy0GCnOUio3zIp9xkkh9qp4gq1eGvoLefi+qyoJsChW9F2dBbUPbz1n"); - a("PACuvsJ+t52/lDmd3yyAmGURgmqaEOuRKJRK5EIpErkUjkJDUkNUjkypev7bvDpxyJRCJHIpHIyp59OJmk2512+w/Iw3XumcxQ"); - a("yCd8iAy6EBWHCYoYzxeYWM7X83rezz/PRmM1D43duM1j4zVB89SETQwvSZNBjGpGmJmaBWrWZocbo7Ugx25d2PHaAHrCNoafpM"); - a("0gSLUjDE3tAkVru8OR0VmQZHcuLHldAE1hF8NT0mUQpboRpqZugaq12+HK6C3IsnsXtrw+gK6wj+Er6TMIU/3S770FW/bgQpc3"); - a("BPAVDjGEJUMGY2oYoWwaFjhbh/1N2oLf/d+Cro4iuLDmSRFCFcNbojKIU0cXWIUd7ozcgjw7d2HPywPoC/MY/pI8g0CVjzA45Q"); - a("sUrvkOh0ZhQaJduLDoFQE0hkUMj0mRQaQqRpicigUq12KHS6O0INMuXdj0ygA6wzKGz6TMIFSVI4xO5QKla7nDqVFZkGpXLqx6"); - a("VQCtYRXDa1JlEKuqEWanaoHatdrh1qgtyLVpN6if6rCO61Od1Fn9XCtYvkDzctNsvNhw7MMwbrXifw3czFSs6HE1KWmJK624js"); - a("PL+LxNxOukucJlNtzDLJzbJSLeIuU1dDHKJTZewi6TSuH5Vzz519rBs36rv8tzRthK9pfSPkplT+iqRlkvekJbF33Vq97YWPv1"); - a("8dXDdu6vxpSW+u/rybXM5wVbMbEUV/YRcSEpN6JlJVfZxwNW4XMXEZeRchuTrMLoHK7B5x4iLiLtNLYwo6/HBhyuwOcOIiwhQ2"); - a("XHfkFhjcEcjiU43IIvazjJDi7Qvx3+d/wfj84a6v3bjGA/VZrmN6o36R7vF282EetTvtG4SeUOnftFJG9VU/ZG2yZ1O/TtU3hE"); - a("4ymUa/ie0eDDtUPZPm1H1J3Ct4aMudrg+jDtULVP1xFlp7StoXuG600a7UqhfWl0KJU+SaczKbWWVk8v15cdpX74YbPSgXQ6kl"); - a("In0upnqfU/P/Uh0tP+H5/91Ck2N3FpfUKmITX30PHonk7WfEPL34w6KLkvSlPWe2a/NxbcRMNdURq3qcjU7PbMcm9st8l6i1V+"); - a("D1CdhtHl1muzv6OV3U6PcovbSz/1m8iF2Vu9I/Y7ZcE1Gz6z4nRs4L/eLx859lnziD1PWfTbd70PhD9KtU55Bt2aLZ9Z87vW77"); - a("WMbZ//dwMs/VyuWIF5zz/7rln4mY2XNcgSsIHf9bPtM+u+se+/2juz0JnCMIwfBh1ZGkVOpCypIcufLCdLja1EMrZMoZALW7IU"); - a("QvYsyXYhU8I5M2dmzpnvnBmKsu9ZUxPRlCXhYkppkCX7872+rN98thsX5mbu3+f3PO/zfk0N94LBGws5Ik4+SIB83lNK1FQq1F"); - a("V0aiutqa+YEi+4nH+Qryae2u73qQzued81/6DrRqnLrPyRe9FjdNFkIqLLDGUxRVqTK+AG3mZMSVb/xBGKDN9H7qgEv+OJi0j0"); - a("Uv4evFGRJPtkcof1vR/C/Leof+eHMFI+Tns7oeA/StSvVHJuEtuLQbMrmstF0V3Kor3oToToBtcKoj917biC5jDxG5NluCBZI3"); - a("qjyux+RfSaKl4/sxpV0QpKOaE1RKc8o0tEqKFg8hRbV9iC3DtZuAB9nxfe8fuodUg7AH0Nq7PVE4pOs2ZDyx3WbusQ6Vex6tmN"); - a("oV8/ezA0nG8vQZZ59n6oeMt+AP3qJ5vwu4jU24iU2p88DN1qIZE6pLohi5YhfdKpADrdTj2EQhGkzgxnHvJmp7MXulx1bkCP9l"); - a("BjRHoc9utG6HA//RQbtUWmLfJjRGYcEmR9ZiumfwfJUTfbCIkxJDsCc1+RXY95H86exo58mf2QNdyebn+kwyJ3BWZ80D2OJHjq"); - a("vnF1r43XAfOd6E3DdDd7OzDVx9573DBdcr1wvSzILcUkg9xBeP1R7hk6WEfWHVPciJmdZpew016w9+hcXf3e1LngWe5WhU9X0t"); - a("VxKihX3V7TyZ+uwpEx2ljbZDuqJqRN/KprmeTExYpd1Jo69GS0ZlwV0l2k0wYaqtg5lSR3YI1stwg3lsiDhmK7nCIHaopm5ZIH"); - a("y2mxQyStahv5sKjYIYvJiYcUvWm66ErfNnh6JUFbing1XpycmPirTREhL06XbATRk7AXIuhIMcVOeOVzwsyvs1/ctK64asvEV0"); - a("SR/UXiKyzau6wNHSK+6L0kGtIWg63qOW9xwsCWaPCSC20DEXZR0W/mEmH7FD0mToQlZAkvLtShxNcGSbrzq1THXVpDfM1VtBVD"); - a("dJRqGX/vF1K+THxFFL2kSISFKePlb3CniDBN8dK2T9yH1buHxekCV7p4O+Fkmd/ciduIraKyYcgpK1GOGX/cMUxxM1Zv3VospA"); - a("3+hZ6RoIQrfbkgFS8EkqwDkZxG84/6dYxyb1uV3qG+L/eB0Fd0V5pgUn5LEp/fNmjKPrz5EaGuokHHspjd5JBm4WtKbiaosXIe"); - a("culJrhZrwtqwbmwAG8WmsHlsFduOLDrCzrMSJdAg0DHLX4D82eWnkDxX/OvooW/9OqCjZ9AfVMwJFoIGJ/DROW8HD5E3zfKtsM"); - a("eG58eAg2X5tdD/YP44dH+af42c6VToAb1nFOYhXfYUMlD7ZuEuV3luSDvH/6vFag5th1mjoelSaw009a0DVpG2lW63tNtBz5H2"); - a("eOgIDaHfGfsydtQL+71tJLskeyE/piZnQjmoBsUuJ69BqzqphlBoYGoYttPy1DrspKOps1Ao7LSFGmOcCdBhvbMVbfCkcwE58d"); - a("L5gBbYPd0HaixIL4UKJ9LnkQu4YDD77pm+mPvUzCz0v9HeBLh1tbcJPuU/SAppY/GFDUBOnay4lHVW22/gG+TDmL8e6X6MXr6b"); - a("wnWjgknCaZz5kNYUX9iQlGM8tbT/n3/68xHeVZKEADYEAA=="); + var shift = (11 - Hole[n]) * 4; + var a = State[n] & (0xFUL << shift); + Hole[n + 1] = Hole[n] + 4; + State[n + 1] = State[n] - a + (a << 16); + Move[n + 1] = 'd'; + Cost[n + 1] = Cost[n] + (RowIndex[a >> shift] <= Hole[n] / 4 ? 0 : 1); + } + + void Up() + { + var shift = (19 - Hole[n]) * 4; + var a = State[n] & (0xFUL << shift); + Hole[n + 1] = Hole[n] - 4; + State[n + 1] = State[n] - a + (a >> 16); + Move[n + 1] = 'u'; + Cost[n + 1] = Cost[n] + (RowIndex[a >> shift] >= Hole[n] / 4 ? 0 : 1); + } + + void Right() + { + var shift = (14 - Hole[n]) * 4; + var a = State[n] & (0xFUL << shift); + Hole[n + 1] = Hole[n] + 1; + State[n + 1] = State[n] - a + (a << 4); + Move[n + 1] = 'r'; + Cost[n + 1] = Cost[n] + (ColIndex[a >> shift] <= Hole[n] % 4 ? 0 : 1); + } + + void Left() + { + int shift = (16 - Hole[n]) * 4; + ulong a = State[n] & (0xFUL << shift); + Hole[n + 1] = Hole[n] - 1; + State[n + 1] = State[n] - a + (a >> 4); + Move[n + 1] = 'l'; + Cost[n + 1] = Cost[n] + (ColIndex[a >> shift] >= Hole[n] % 4 ? 0 : 1); + } + + public FifteenSolver(int n, ulong g) + { + Hole[0] = n; + State[0] = g; + } + + public void Solve() + { + for (; !Scan(); ++maxCost) + ; } } diff --git a/Task/15-puzzle-solver/Dart/15-puzzle-solver.dart b/Task/15-puzzle-solver/Dart/15-puzzle-solver.dart new file mode 100644 index 0000000000..27546c8101 --- /dev/null +++ b/Task/15-puzzle-solver/Dart/15-puzzle-solver.dart @@ -0,0 +1,78 @@ +import 'package:collection/collection.dart'; + +typedef OffsetFunction = int Function(int a, int b); +Function eq = const ListEquality().equals; + +/// Solve Random 15 Puzzles +class FifteenSolver { + static const target = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0]; + static const trN = [3, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3]; + static const tcN = [3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2]; + var pos0 = List.filled(100, 0); + var moves = List.filled(100, 0); + var dirs = List.filled(100, ''); + int step = 0, best = 0; + var board = List.generate(100, (int i) => List.filled(16, 0)); + + bool isFinished() { + if (moves[step] < best) return nextMove(); + if (eq(board[step], target)) { + print("Solution found in $step moves :${dirs.join('')}"); + return true; + } + return (moves[step] == best) ? nextMove() : false; + } + + var passNumber = 0; + + /// Try all valid moves from here, but don't retrace your steps. + /// Return true if a solution is found. + bool nextMove() { + // if (passNumber++ ~/ 100000 == 0) print("${dirs.join('')}"); + return (dirs[step] != 'u' && pos0[step] ~/ 4 < 3 && down()) || + (dirs[step] != 'd' && pos0[step] ~/ 4 > 0 && up()) || + (dirs[step] != 'l' && pos0[step] % 4 < 3 && right()) || + (dirs[step] != 'r' && pos0[step] % 4 > 0 && left()) || + false; + } + + bool move(int offset, String dir, List rcArray, OffsetFunction rcFunc) { + final int ix = pos0[step] + offset; + final n = board[step][ix]; + pos0[step + 1] = pos0[step] + offset; + board[step + 1] = board[step].toList() + ..[pos0[step]] = n + ..[ix] = 0; + dirs[step + 1] = dir; + moves[step + 1] = moves[step] + rcFunc(rcArray[n], pos0[step]); + step++; + if (isFinished()) return true; + step--; + return false; + } + + bool right() => move(1, 'r', tcN, (a, b) => (a <= b % 4 ? 0 : 1)); + bool left() => move(-1, 'l', tcN, (a, b) => (a >= b % 4 ? 0 : 1)); + bool down() => move(4, 'd', trN, (a, b) => (a <= b ~/ 4 ? 0 : 1)); + bool up() => move(-4, 'u', trN, (a, b) => (a >= b ~/ 4 ? 0 : 1)); + + void solve(List initBoard) { + pos0[0] = initBoard.indexOf(0); + board[0] = initBoard; + while (!isFinished()) best++; + } +} + +void main(List args) { + print("running"); + // test values + // final start = [5, 1, 2, 3, 6, 10, 7, 4, 13, 9, 11, 8, 14, 0, 15, 12]; + // final start = [9, 1, 2, 4, 13, 6, 5, 7, 3, 11, 14, 15, 10, 0, 8, 12]; + // final start = [10, 3, 1, 4, 13, 5, 8, 7, 9, 6, 0, 11, 14, 15, 12, 2]; + // required solution + final start = [15, 14, 1, 6, 9, 11, 4, 12, 0, 10, 7, 3, 13, 8, 5, 2]; + // Extra credit + // final start = [0, 12, 9, 13, 15, 11, 10, 14, 3, 7, 2, 5, 4, 8, 6, 1]; + print(start); + FifteenSolver().solve(start); +} diff --git a/Task/15-puzzle-solver/FreeBASIC/15-puzzle-solver.basic b/Task/15-puzzle-solver/FreeBASIC/15-puzzle-solver.basic new file mode 100644 index 0000000000..4dcdf807c9 --- /dev/null +++ b/Task/15-puzzle-solver/FreeBASIC/15-puzzle-solver.basic @@ -0,0 +1,288 @@ +Randomize Timer + +Dim Shared As Integer Nr(15) = {3, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3} +Dim Shared As Integer Nc(15) = {3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2} +Dim Shared As Integer n, nn +Dim Shared As Integer N0(99), N3(100), N4(99) +Dim Shared As Ulongint N2(99) + +Enum + Ki = 1 + Kg = 8 + Ke = 2 + Kl = 4 +End Enum + +Dim Shared As Integer l = 108, r = 114, u = 117, d = 100 + +Declare Function fY() As Boolean +Declare Function fZ(w As Integer) As Boolean +Declare Function fN() As Boolean + +Sub fI() + Dim As Integer g = (11 - N0(n)) * 4 + Dim As Ulongint a = (N2(n) And (15ULL Shl g)) + N0(n + 1) = N0(n) + 4 + N2(n + 1) = N2(n) - a + (a Shl 16) + N3(n + 1) = d + N4(n + 1) = N4(n) + If Not(Nr((a Shr g)) <= N0(n)\4) Then N4(n + 1) += 1 + n += 1 +End Sub + +Sub fG() + Dim As Integer g = (19 - N0(n)) * 4 + Dim As Ulongint a = (N2(n) And (15ULL Shl g)) + N0(n + 1) = N0(n) - 4 + N2(n + 1) = N2(n) - a + (a Shr 16) + N3(n + 1) = u + N4(n + 1) = N4(n) + If Not(Nr((a Shr g)) >= N0(n)\4) Then N4(n + 1) += 1 + n += 1 +End Sub + +Sub fE() + Dim As Integer g = (14 - N0(n)) * 4 + Dim As Ulongint a = (N2(n) And (15ULL Shl g)) + N0(n + 1) = N0(n) + 1 + N2(n + 1) = N2(n) - a + (a Shl 4) + N3(n + 1) = r + N4(n + 1) = N4(n) + If Not(Nc((a Shr g)) <= (N0(n) Mod 4)) Then N4(n + 1) += 1 + n += 1 +End Sub + +Sub fL() + Dim As Integer g = (16 - N0(n)) * 4 + Dim As Ulongint a = (N2(n) And (15ULL Shl g)) + N0(n + 1) = N0(n) - 1 + N2(n + 1) = N2(n) - a + (a Shr 4) + N3(n + 1) = l + N4(n + 1) = N4(n) + If Not(Nc((a Shr g)) >= (N0(n) Mod 4)) Then N4(n + 1) += 1 + n += 1 +End Sub + +Function fY() As Boolean + If N2(n) = &h123456789abcdef0ULL Then Return True + If N4(n) <= nn Then Return fN() + Return False +End Function + +Function fZ(w As Integer) As Boolean + If (w And Ki) > 0 Then + fI() + If fY() Then Return True + n -= 1 + End If + If (w And Kg) > 0 Then + fG() + If fY() Then Return True + n -= 1 + End If + If (w And Ke) > 0 Then + fE() + If fY() Then Return True + n -= 1 + End If + If (w And Kl) > 0 Then + fL() + If fY() Then Return True + n -= 1 + End If + Return False +End Function + +Function fN() As Boolean + Select Case N0(n) + Case 0 + Select Case N3(n) + Case l: Return fZ(Ki) + Case u: Return fZ(Ke) + Case Else: Return fZ(Ki Or Ke) + End Select + Case 3 + Select Case N3(n) + Case r: Return fZ(Ki) + Case u: Return fZ(Kl) + Case Else: Return fZ(Ki Or Kl) + End Select + Case 1, 2 + Select Case N3(n) + Case l: Return fZ(Ki Or Kl) + Case r: Return fZ(Ki Or Ke) + Case u: Return fZ(Ke Or Kl) + Case Else: Return fZ(Kl Or Ke Or Ki) + End Select + Case 12 + Select Case N3(n) + Case l: Return fZ(Kg) + Case d: Return fZ(Ke) + Case Else: Return fZ(Ke Or Kg) + End Select + Case 15 + Select Case N3(n) + Case r: Return fZ(Kg) + Case d: Return fZ(Kl) + Case Else: Return fZ(Kg Or Kl) + End Select + Case 13, 14 + Select Case N3(n) + Case l: Return fZ(Kg Or Kl) + Case r: Return fZ(Ke Or Kg) + Case d: Return fZ(Ke Or Kl) + Case Else: Return fZ(Kg Or Ke Or Kl) + End Select + Case 4, 8 + Select Case N3(n) + Case l: Return fZ(Ki Or Kg) + Case u: Return fZ(Kg Or Ke) + Case d: Return fZ(Ki Or Ke) + Case Else: Return fZ(Ki Or Kg Or Ke) + End Select + Case 7, 11 + Select Case N3(n) + Case d: Return fZ(Ki Or Kl) + Case u: Return fZ(Kg Or Kl) + Case r: Return fZ(Ki Or Kg) + Case Else: Return fZ(Ki Or Kg Or Kl) + End Select + Case Else + Select Case N3(n) + Case d: Return fZ(Ki Or Ke Or Kl) + Case l: Return fZ(Ki Or Kg Or Kl) + Case r: Return fZ(Ki Or Kg Or Ke) + Case u: Return fZ(Kg Or Ke Or Kl) + Case Else: Return fZ(Ki Or Kg Or Ke Or Kl) + End Select + End Select +End Function + +Sub solve() + If fN() Then + Exit Sub + Else + n = 0 + nn += 1 + solve() + End If +End Sub + +Function createPuzzle(Byval j As Integer) As Ulongint + Dim As Ulongint q = &h123456789abcdef0ULL + Dim As String h = Hex(q, 16) + Dim As Integer z, d, r, u = 0 + While j > 0 ' number of moves to do + Do + d = Int(Rnd * 4) + 1 + Loop While d = u + u = -d + r = Int(Rnd * 3) + 1 + While r > 0 + z = Instr(h, "0") + Select Case d + Case 1 ' -1 + If (z Mod 4) <> 1 Then + Mid(h, z, 1) = Mid(h, z - 1, 1) + Mid(h, z - 1, 1) = "0" + j -= 1 + End If + Case 2 ' +1 + If (z Mod 4) <> 0 Then + Mid(h, z, 1) = Mid(h, z + 1, 1) + Mid(h, z + 1, 1) = "0" + j -= 1 + End If + Case 3 ' -4 + If z >= 5 Then + Mid(h, z, 1) = Mid(h, z - 4, 1) + Mid(h, z - 4, 1) = "0" + j -= 1 + End If + Case 4 ' +4 + If z <= 12 Then + Mid(h, z, 1) = Mid(h, z + 4, 1) + Mid(h, z + 4, 1) = "0" + j -= 1 + End If + End Select + r -= 1 + Wend + Wend + Return Valulng("&h" + h) +End Function + +Sub ShowConfiguration(Byval h As String, i As Integer) + Dim As Integer r, c + Dim x As String + Color 14 + For r = 1 To 4 + For c = 1 To 4 + x = Mid(h, r * 4 - 4 + c, 1) + If x = "0" Then x = " " + Locate r + i, c + c - 1: Print x; + Next + Next + Color 7 +End Sub + +Sub shoWMoves(Byval h As String, Byval s As String, Byval m As Integer, Byval p As Integer) + Dim As Integer j, z, d + ShowConfiguration(h, 12) + For j = 1 To m + d = Asc(Mid(s, j, 1)) + z = Instr(h, "0") + Select Case d + Case l + If (z Mod 4) <> 1 Then + Mid(h, z, 1) = Mid(h, z - 1, 1) + Mid(h, z - 1, 1) = "0" + End If + Case r + If (z Mod 4) <> 0 Then + Mid(h, z, 1) = Mid(h, z + 1, 1) + Mid(h, z + 1, 1) = "0" + End If + Case u + If z >= 5 Then + Mid(h, z, 1) = Mid(h, z - 4, 1) + Mid(h, z - 4, 1) = "0" + End If + Case d + If z <= 12 Then + Mid(h, z, 1) = Mid(h, z + 4, 1) + Mid(h, z + 4, 1) = "0" + End If + End Select + ShowConfiguration(h, 12) + Sleep p + Next + Print +End Sub + +Sub fifteenSolver(Byval g As Ulongint, Byval p As Integer) + Dim As String h, s + Dim As Integer j + Dim As Double t0 = Timer + n = 0 + nn = 0 + h = Hex(g, 16) + Cls + Print "Puzzle: "; Lcase(h) + ShowConfiguration(h, 2) + Print Chr(10) + N0(0) = Instr(h, "0") - 1 + N2(0) = g + solve() + Print Using "Solution found in & moves: "; n; + For j = 1 To n + s &= Chr(N3(j)) + Next + Print s + Print Using !"\nTook ###.######## seconds on i5 @ 3.20 GHz"; Timer - t0 + If p Then showMoves(h, s, n, p) +End Sub + +fifteenSolver(&hfe169b4c0a73d852ULL, 1000) + +Sleep diff --git a/Task/15-puzzle-solver/FutureBasic/15-puzzle-solver.basic b/Task/15-puzzle-solver/FutureBasic/15-puzzle-solver.basic new file mode 100644 index 0000000000..16a309133a --- /dev/null +++ b/Task/15-puzzle-solver/FutureBasic/15-puzzle-solver.basic @@ -0,0 +1,165 @@ +// 15 Puzzle Solver +//https://rosettacode.org/wiki/15_puzzle_solver +// Requires FutureBasic 7.0.30 or later + +begin globals + int Nr(15), Nc(15), n, un, N0(99), N3(99), N4(99) + UInt64 N2(99) +end globals + +def fn fY as BOOL +void def fn fI +void def fn fG +void def fn fE +void def fn fL + +local fn fN1 as BOOL + if ( N3(n) != _"u" && N0(n) / 4 < 3 ) + fn fI + n++ + if ( fn fY ) then return YES + n-- + end if + + if ( N3(n) != _"d" && N0(n) / 4 > 0 ) + fn fG + n++ + if ( fn fY ) then return YES + n-- + end if + + if ( N3(n) != _"l" && N0(n) % 4 < 3 ) + fn fE + n++ + if ( fn fY ) then return YES + n-- + end if + + if ( N3(n) != _"r" && N0(n) %4 > 0 ) + fn fL + n++ + if ( fn fY ) then return YES + n-- + end if +end fn = NO + +void local fn fI + int g = ( 11 - N0(n)) * 4 + UInt64 a = N2(n) & ((UInt64)15 << g) + N0(n + 1) = N0(n) + 4 + N2(n + 1) = N2(n) - a + (a << 16) + N3(n + 1) = _"d" + if ( Nr(a >> g) <= N0(n) / 4 ) + N4(n + 1) = N4(n) + else + N4(n + 1) = N4(n) + 1 + end if +end fn + +void local fn fG + int g = (19 - N0(n)) * 4 + UInt64 a = N2(n) & ((UInt64)15 << g) + N0(n + 1) = N0(n) - 4 + N2(n + 1) = N2(n) - a + (a >> 16) + N3(n + 1) = _"u" + if ( Nr(a >> g) >= N0(n) / 4 ) + N4(n + 1) = N4(n) + else + N4(n + 1) = N4(n) + 1 + end if +end fn + +void local fn fE + int g = (14 - N0(n)) * 4 + UInt64 a = N2(n) & ((UInt64)15 << g) + N0(n + 1) = N0(n) + 1 + N2(n + 1) = N2(n) - a + (a << 4) + N3(n + 1) = _"r" + if ( Nc(a >> g) <= N0(n) % 4 ) + N4(n + 1) = N4(n) + else + N4(n + 1) = N4(n) + 1 + end if +end fn + +void local fn fL + int g = (16 - N0(n)) * 4 + UInt64 a = N2(n) & ((UInt64)15 << g) + N0(n + 1) = N0(n) - 1 + N2(n + 1) = N2(n) - a + (a >> 4) + N3(n + 1) = _"l" + if ( Nc(a >> g) >= N0(n) % 4 ) + N4(n + 1) = N4(n) + else + N4(n + 1) = N4(n) + 1 + end if +end fn + +local fn fY as BOOL + if ( N4(n) < un ) then return fn fN1 + if ( N2(n) == 0x123456789abcdef0 ) + printf @"Solution found in %d moves:",n + for int g = 1 to n + printf @"%c\b",N3(g) + next + print + return YES + end if + if ( N4(n) == un ) then return fn fN1 +end fn = NO + +void local fn Solve( initN as int, initG as UInt64 ) + int tempNr(15) = {3,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3} + int tempNc(15) = {3,0,1,2,3,0,1,2,3,0,1,2,3,0,1,2} + + fn memcpy(@Nr(0),@tempNr(0),sizeof(int)*16) + fn memcpy(@Nc(0),@tempNc(0),sizeof(int)*16) + + n = 0 + un = 0 + + N0(0) = initN + N2(0) = initG + + while ( !fn fY ) + un++ + wend +end fn + + +window 1, @"15 Puzzle Solver" +windowcenter(1) +WindowSetBackgroundColor(1,fn ColorBlack) + +text ,14,fn colorWhite +Print "Puzzle: "; "fe169b4c0a73d852" + +text ,14,fn colorYellow +print +print @"15 14 1 6" +print @" 9 11 4 12" +print @" 0 10 7 3" +print @"13 8 5 2" +print +text ,14,fn colorWhite + +CFStringRef ComputerChip = unix @"sysctl -n machdep.cpu.brand_string" + +CFTimeInterval t : t = fn CACurrentMediaTime +fn Solve( 8, 0xfe169b4c0a73d852 ) +CFTimeInterval CurrentTime = fn CACurrentMediaTime-t + +print +text ,14,fn colorYellow +print +print @" 1 2 3 4" +print @" 5 6 7 8" +print @" 9 10 11 12" +print @"13 14 15 0" +print +text ,14,fn colorWhite + +print : printf @"Compute time: %.3f seconds",(CurrentTime) +print ComputerChip + +HandleEvents diff --git a/Task/15-puzzle-solver/JavaScript/15-puzzle-solver.js b/Task/15-puzzle-solver/JavaScript/15-puzzle-solver.js new file mode 100644 index 0000000000..1904d1d75b --- /dev/null +++ b/Task/15-puzzle-solver/JavaScript/15-puzzle-solver.js @@ -0,0 +1,97 @@ +class FifteenSolver { + constructor(n, g) { + this.Nr = [3,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3]; + this.Nc = [3,0,1,2,3,0,1,2,3,0,1,2,3,0,1,2]; + this.n = 0; + this._n = 0; + this.N0 = new Array(100).fill(0); + this.N3 = new Array(100).fill(''); + this.N4 = new Array(100).fill(0); + this.N2 = new Array(100).fill(0n); + this.N0[0] = n; + this.N2[0] = BigInt(g); + } + + fY() { + if (this.N4[this.n] < this._n) return this.fN(); + if (this.N2[this.n] === 0x123456789abcdef0n) { + let moves = ''; + for (let g = 1; g <= this.n; g++) moves += this.N3[g]; + console.log(`Solution found in ${this.n} moves: ${moves}`); + return true; + } + if (this.N4[this.n] === this._n) return this.fN(); + return false; + } + + fN() { + if (this.N3[this.n] !== 'u' && Math.floor(this.N0[this.n]/4) < 3) { + this.fI(); + this.n++; + if (this.fY()) return true; + this.n--; + } + if (this.N3[this.n] !== 'd' && Math.floor(this.N0[this.n]/4) > 0) { + this.fG(); + this.n++; + if (this.fY()) return true; + this.n--; + } + if (this.N3[this.n] !== 'l' && this.N0[this.n]%4 < 3) { + this.fE(); + this.n++; + if (this.fY()) return true; + this.n--; + } + if (this.N3[this.n] !== 'r' && this.N0[this.n]%4 > 0) { + this.fL(); + this.n++; + if (this.fY()) return true; + this.n--; + } + return false; + } + + fI() { + const g = (11 - this.N0[this.n]) * 4; + const a = this.N2[this.n] & (15n << BigInt(g)); + this.N0[this.n + 1] = this.N0[this.n] + 4; + this.N2[this.n + 1] = this.N2[this.n] - a + (a << 16n); + this.N3[this.n + 1] = 'd'; + this.N4[this.n + 1] = this.N4[this.n] + (this.Nr[Number(a >> BigInt(g))] <= Math.floor(this.N0[this.n]/4) ? 0 : 1); + } + + fG() { + const g = (19 - this.N0[this.n]) * 4; + const a = this.N2[this.n] & (15n << BigInt(g)); + this.N0[this.n + 1] = this.N0[this.n] - 4; + this.N2[this.n + 1] = this.N2[this.n] - a + (a >> 16n); + this.N3[this.n + 1] = 'u'; + this.N4[this.n + 1] = this.N4[this.n] + (this.Nr[Number(a >> BigInt(g))] >= Math.floor(this.N0[this.n]/4) ? 0 : 1); + } + + fE() { + const g = (14 - this.N0[this.n]) * 4; + const a = this.N2[this.n] & (15n << BigInt(g)); + this.N0[this.n + 1] = this.N0[this.n] + 1; + this.N2[this.n + 1] = this.N2[this.n] - a + (a << 4n); + this.N3[this.n + 1] = 'r'; + this.N4[this.n + 1] = this.N4[this.n] + (this.Nc[Number(a >> BigInt(g))] <= this.N0[this.n]%4 ? 0 : 1); + } + + fL() { + const g = (16 - this.N0[this.n]) * 4; + const a = this.N2[this.n] & (15n << BigInt(g)); + this.N0[this.n + 1] = this.N0[this.n] - 1; + this.N2[this.n + 1] = this.N2[this.n] - a + (a >> 4n); + this.N3[this.n + 1] = 'l'; + this.N4[this.n + 1] = this.N4[this.n] + (this.Nc[Number(a >> BigInt(g))] >= this.N0[this.n]%4 ? 0 : 1); + } + + solve() { + while (!this.fY()) this._n++; + } +} + +const start = new FifteenSolver(8, '0xfe169b4c0a73d852'); +start.solve(); diff --git a/Task/15-puzzle-solver/Jq/15-puzzle-solver.jq b/Task/15-puzzle-solver/Jq/15-puzzle-solver.jq new file mode 100644 index 0000000000..0e7f033340 --- /dev/null +++ b/Task/15-puzzle-solver/Jq/15-puzzle-solver.jq @@ -0,0 +1,192 @@ +# The following may be omitted if using the C implementation +# or if the debug messages are deleted. +def debug(msg): (msg | tostring | debug | empty), .; + +### Generic functions + +def array_swap($i; $j): + if $j < $i then array_swap($j;$i) + elif $i == $j then . + else .[:$i] + [.[$j]] + .[$i+1:$j] + [.[$i]] + .[$j+1:] + end ; + +def sum(s): reduce s as $x (0; . + $x); + +### The 15-Puzzle + +# manhattan distance between points $ix and $iy where these are indices in the flat array +def distance($ix; $jx): + def row: ./4 | floor; + def col: . % 4; + [$ix, $jx] + | map(row) as $mr # [$ri, $rj] + | map(col) as $mc # [$ci, $cj] + | [$mr[0] - $mr[1], $mc[0] - $mc[1]] + | map(length) # i.e. abs + | add; + +# What is the Manhattan distance between the position of $tile in the goal +# and the location corresponding to index $ix, where $ix is in range(0;16) +def manhattan($tile; $ix): + .position[$tile|tostring] as $jx + | distance($ix; $jx); + +# The total of the discrepancies +def total_manhattan_distance: + sum( range(0;16) as $p | .board[$p] as $tile | select($tile != 0) | manhattan($tile; $p) ) + | debug; + +# Input: +# .goal is the desired board (flat array) +# .position is the JSON object mapping tiles to the goal index +# .zero is the location of 0 +# .board is the current state of the board (flat array) +# .distance is incremented by $delta after each move +# .seen is our memory +# If allowed, move the zero tile to $p where $p has been properly specified in relation to .zero; +# otherwise emit empty +def move($p): + if $p >= 0 and $p < 16 + then .board[$p] as $tile + # Are we making things worse off? + | (manhattan($tile; .zero) - manhattan($tile; $p)) as $delta + | if $delta > 0 and .distance > (.N - .n) + then if .n >= .N then debug({n, N, distance,sequence: (.sequence|length)}) end | empty + else # make the move + .zero as $zero + | (.board | array_swap($zero; $p)) as $candidate + | ($candidate|tostring) as $s + | if .seen[$s] + then empty + else .board = $candidate + | .zero = $p + | .n += 1 + | .seen[$s] = true + end + end + # We should only reach here if the move has been made + | if $delta != 0 + then .distance += $delta + end + else empty + end +; + +def row: . / 4 | floor; +def col: . % 4; + +def up: + if (.zero | row) == 0 then empty + else move(.zero - 4) + | .sequence += ["u"] + end; + +def down: + if (.zero | row) == 3 then empty + else move(.zero + 4) + | .sequence += ["d"] + end; + +def left: + if (.zero|col) == 0 then empty + else move(.zero - 1) + | .sequence += ["l"] + end; + +def right: + if (.zero|col) == 3 then empty + else move(.zero + 1) + | .sequence += ["r"] + end; + +# $array is a permutation of range(0;16), e.g. the goal +# Output: a JSON object such that .[$tile] is the position of $tile in the goal +def positions($array): + reduce range(0; $array|length) as $i ({}; . + {($array[$i]|tostring): $i}); + +# map a string of lowercase hex digits to an array of decimals +def symbols2array: explode | map(if . > 96 then .-87 else .-48 end); + +# $start should be a string of length 16 representing the starting state; +# the goal is: "123456789abcdef0" +def init($start): + if $start|length == 16 then . else error end + | [range(1;16), 0] as $init + | {goal: $init, + position: positions($init), + distance: 0, + n: 0, # number of moves so far + sequence: [], # the sequence of moves so far + seen: {} + } + | .board = ($start | symbols2array) + | .zero = (.board|index(0)) + | (.board|tostring) as $s + | .seen[$s] = true +; + +# Output: If the move of the zero tile to $p is legal in one step, +# then emit manhattan($tile; .zero) - manhattan($tile; $p) +# where $tile is the tile at $p; +# otherwise: null +def delta_move($p): + if $p >= 0 and $p < 16 + then distance($p; .zero) as $base + | if ($base|length) == 1 # abs + then .board[$p] as $tile + | manhattan($tile; .zero) - manhattan($tile; $p) + else null + end + else null + end ; + +# For comparing the possible moves: +def moves: + {"u": delta_move( .zero - 4), + "d": delta_move( .zero + 4), + "l": delta_move( .zero - 1), + "r": delta_move( .zero + 1) } + | to_entries + | map(select( .value ) ) + | sort_by(.value) + ; + + +# input: the output of moves +def execute($moves): + ($moves[] |.key) as $key + | if $key == "l" then left + elif $key == "r" then right + elif $key == "u" then up + elif $key == "d" then down + else empty + end; + +# $N is the maximum number of moves allowed +# Input: as per `input`; .n is the number of moves so far +def possible_moves($N): + def possible_moves: + if .board == .goal then . # a solution + elif (.sequence|length) >= $N then empty + else .sequence[-1] as $lastmove + | if $lastmove == "l" then execute(moves | map(select(.key != "r"))) + elif $lastmove == "r" then execute(moves | map(select(.key != "l"))) + elif $lastmove == "u" then execute(moves | map(select(.key != "d"))) + elif $lastmove == "d" then execute(moves | map(select(.key != "u"))) + else execute(moves) + end + | possible_moves + end ; + possible_moves; + +def solve($goal): + init($goal) + | total_manhattan_distance as $d + | first( range($d; 100) as $n + | .N = $n + | .distance = $d + | debug("before: n=\($n) distance = \($d))") + | possible_moves($n) + | .sequence | join("") ) ; + +solve("fe169b4c0a73d852") diff --git a/Task/15-puzzle-solver/Julia/15-puzzle-solver.julia b/Task/15-puzzle-solver/Julia/15-puzzle-solver.jl similarity index 100% rename from Task/15-puzzle-solver/Julia/15-puzzle-solver.julia rename to Task/15-puzzle-solver/Julia/15-puzzle-solver.jl diff --git a/Task/15-puzzle-solver/Mathematica/15-puzzle-solver.math b/Task/15-puzzle-solver/Mathematica/15-puzzle-solver.math new file mode 100644 index 0000000000..3a7bdde6e4 --- /dev/null +++ b/Task/15-puzzle-solver/Mathematica/15-puzzle-solver.math @@ -0,0 +1,178 @@ +(* Constants for the correct ordering and board position mapping *) +correctOrder = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0}; +rowOf = {0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3} + 1; (* +1 because Mathematica uses 1-based indexing *) +colOf = {0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3} + 1; (* +1 because Mathematica uses 1-based indexing *) + +(* Function to estimate remaining moves using Manhattan distance *) +EstimateMoves[board_] := Module[{h = 0}, + Do[ + (* Skip the empty tile (0) *) + If[board[[i]] != 0, + (* Find where this tile should be in the correct order *) + correctPos = Position[correctOrder, board[[i]]][[1, 1]]; + (* Calculate Manhattan distance: |current_row - correct_row| + |current_col - correct_col| *) + h += Abs[rowOf[[i]] - rowOf[[correctPos]]] + Abs[colOf[[i]] - colOf[[correctPos]]]; + ], + {i, 1, 16} + ]; + h +] + +(* Find the position of the blank tile (0) *) +FindBlankPosition[board_] := Position[board, 0][[1, 1]] + +(* Generate possible moves from current state *) +GenerateMoves[board_, movesSoFar_] := Module[ + {blankPos, possibleMoves = {}, newBoard, newMoves}, + + blankPos = FindBlankPosition[board]; + + (* Check if we can move left (blank goes right) *) + If[Mod[blankPos, 4] != 1, + newBoard = board; + newBoard[[blankPos]] = newBoard[[blankPos - 1]]; + newBoard[[blankPos - 1]] = 0; + newMoves = movesSoFar <> "r"; + AppendTo[possibleMoves, {newBoard, newMoves, Length[newMoves] + EstimateMoves[newBoard]}]; + ]; + + (* Check if we can move right (blank goes left) *) + If[Mod[blankPos, 4] != 0, + newBoard = board; + newBoard[[blankPos]] = newBoard[[blankPos + 1]]; + newBoard[[blankPos + 1]] = 0; + newMoves = movesSoFar <> "l"; + AppendTo[possibleMoves, {newBoard, newMoves, Length[newMoves] + EstimateMoves[newBoard]}]; + ]; + + (* Check if we can move up (blank goes down) *) + If[blankPos > 4, + newBoard = board; + newBoard[[blankPos]] = newBoard[[blankPos - 4]]; + newBoard[[blankPos - 4]] = 0; + newMoves = movesSoFar <> "d"; + AppendTo[possibleMoves, {newBoard, newMoves, Length[newMoves] + EstimateMoves[newBoard]}]; + ]; + + (* Check if we can move down (blank goes up) *) + If[blankPos <= 12, + newBoard = board; + newBoard[[blankPos]] = newBoard[[blankPos + 4]]; + newBoard[[blankPos + 4]] = 0; + newMoves = movesSoFar <> "u"; + AppendTo[possibleMoves, {newBoard, newMoves, Length[newMoves] + EstimateMoves[newBoard]}]; + ]; + + possibleMoves +] + +(* A* Search algorithm for solving the puzzle *) +Solve15Puzzle[startBoard_] := Module[ + {openSet = {}, closedSet = {}, current, children, bestMoves = {}}, + + (* Initialize the priority queue (Mathematica doesn't have a built-in priority queue, + so we'll use a list and sort it each time) *) + openSet = {{startBoard, "", EstimateMoves[startBoard]}}; + + While[Length[openSet] > 0, + (* Sort the open set by total estimated cost *) + openSet = Sort[openSet, #1[[3]] < #2[[3]] &]; + + (* Get the most promising state *) + current = First[openSet]; + openSet = Rest[openSet]; + + (* Check if we've reached the goal state *) + If[current[[1]] == correctOrder, + Print["Solution found!"]; + Print["Moves: ", current[[2]]]; + Print["Number of moves: ", StringLength[current[[2]]]]; + Print["Open set size: ", Length[openSet]]; + Print["Closed set size: ", Length[closedSet]]; + + (* Format the final board *) + Print["Final board:"]; + Print[Partition[current[[1]], 4]]; + Return[current[[2]]]; + ]; + + (* Generate all possible moves from current state *) + children = GenerateMoves[current[[1]], current[[2]]]; + + (* Process each child state *) + For[i = 1, i <= Length[children], i++, + child = children[[i]]; + childBoard = child[[1]]; + + (* Check if this board is already in the closed set *) + If[Not[MemberQ[Map[First, closedSet], childBoard]], + (* Check if this board is already in the open set *) + existingIdx = Position[Map[First, openSet], childBoard]; + + If[existingIdx == {}, + (* Add to open set if not already there *) + AppendTo[openSet, child]; + , + (* Update if this path is better than existing one *) + existingIdx = existingIdx[[1, 1]]; + If[StringLength[child[[2]]] < StringLength[openSet[[existingIdx, 2]]], + openSet[[existingIdx]] = child; + ]; + ]; + ]; + ]; + + (* Add current state to closed set *) + AppendTo[closedSet, current]; + ]; + + Print["No solution found!"]; + Return[{}]; +] + +(* Example usage *) +startingBoard = {15, 14, 1, 6, 9, 11, 4, 12, 0, 10, 7, 3, 13, 8, 5, 2}; +(* startingBoard = {0, 1, 2, 3, 5, 6, 7, 4, 9, 10, 11, 8, 13, 14, 15, 12}; *) + +solution = Solve15Puzzle[startingBoard]; + +(* Pretty print function to visualize a board *) +PrintBoard[board_] := Module[{}, + Grid[Partition[board, 4], Frame -> All] +] + +(* Visualization code to show the solution step by step *) +VisualizeSolution[startBoard_, moves_] := Module[ + {currentBoard = startBoard, frames = {PrintBoard[startBoard]}, blankPos}, + + Do[ + blankPos = FindBlankPosition[currentBoard]; + + Switch[StringTake[moves, {i}], + "l", (* blank moves left *) + currentBoard[[blankPos]] = currentBoard[[blankPos - 1]]; + currentBoard[[blankPos - 1]] = 0, + + "r", (* blank moves right *) + currentBoard[[blankPos]] = currentBoard[[blankPos + 1]]; + currentBoard[[blankPos + 1]] = 0, + + "u", (* blank moves up *) + currentBoard[[blankPos]] = currentBoard[[blankPos - 4]]; + currentBoard[[blankPos - 4]] = 0, + + "d", (* blank moves down *) + currentBoard[[blankPos]] = currentBoard[[blankPos + 4]]; + currentBoard[[blankPos + 4]] = 0 + ]; + + AppendTo[frames, PrintBoard[currentBoard]]; + + ,{i, 1, StringLength[moves]} + ]; + + ListAnimate[frames] +] + +(* Uncomment to visualize the solution *) +(* If[solution != {}, VisualizeSolution[startingBoard, solution]]; *) diff --git a/Task/15-puzzle-solver/PascalABC.NET/15-puzzle-solver.pas b/Task/15-puzzle-solver/PascalABC.NET/15-puzzle-solver.pas new file mode 100644 index 0000000000..36a40f7d75 --- /dev/null +++ b/Task/15-puzzle-solver/PascalABC.NET/15-puzzle-solver.pas @@ -0,0 +1,3 @@ +// Игра в 15 PABCWork.NET\Samples\Games\15.pas +see +https://rosettacode.org/wiki/15_puzzle_game#PascalABC.NET diff --git a/Task/15-puzzle-solver/R/15-puzzle-solver.r b/Task/15-puzzle-solver/R/15-puzzle-solver.r new file mode 100644 index 0000000000..624401ed4e --- /dev/null +++ b/Task/15-puzzle-solver/R/15-puzzle-solver.r @@ -0,0 +1,239 @@ +## ----- Constants (match Julia) ----- +Nr <- c(3, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3) +Nc <- c(3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2) + +N0 <- integer(85) +# N2 is a list of nibble vectors (each length 16, values 0..15, LSB-first) +N2 <- vector("list", 85) +N3 <- rep("", 85) # chars 'd','u','r','l' +N4 <- integer(85) + +i <- 1L +g <- 8L +ee <- 2L +l <- 4L +.n <- 1L # scalar (Julia used a 1-element Vector{Int32}) + +## ----- Helpers for nibble representation ----- +# Convert a 16-hex string like "fe169b4c0a73d852" to nibble vector (LSB first) +hex_to_nibbles <- function(hexstr) { + hexstr <- gsub("^0x", "", tolower(hexstr)) + stopifnot(nchar(hexstr) == 16) + chars <- strsplit(hexstr, "")[[1]] + lookup <- c(as.character(0:9), letters[1:6]) + to_val <- function(ch) match(ch, lookup) - 1L + nibs_msbf <- vapply(chars, to_val, integer(1)) + rev(nibs_msbf) +} + + +# Compare two nibble vectors for equality +nibbles_equal <- function(a, b) { + if (is.null(a) || is.null(b)) return(FALSE) + length(a) == length(b) && all(a == b) +} + +# Extract nibble value at bit-offset gg (multiple of 4) +# LSB-first indexing: position = gg/4, R index = pos+1 +get_nibble_at <- function(nibs, gg) { + pos <- as.integer(gg / 4L) + nibs[pos + 1L] +} + +# Move nibble at position pos by delta positions (delta can be +/-1, +/-4) +# Clears original pos (sets to 0), and adds the nibble to new position. +move_nibble <- function(nibs, pos, delta) { + src <- pos + dst <- pos + delta + if (dst < 0L || dst > 15L) stop("Nibble move out of bounds") + v <- nibs[src + 1L] + if (v == 0L) return(nibs) # nothing to move + nibs[src + 1L] <- 0L + nibs[dst + 1L] <- nibs[dst + 1L] + v # original code “-a + (a << …)” effectively relocates the nibble + nibs +} + +# (a >> gg) when a is a single-nibble mask at gg just yields that nibble value. +# In our model we already read that nibble directly. + +## ----- Target and initial states (as nibbles) ----- +# Goal: 0x123456789abcdef0 => nibbles MSB→LSB: 1 2 3 4 5 6 7 8 9 a b c d e f 0 +GOAL <- hex_to_nibbles("123456789abcdef0") + +# Initial: 0xfe169b4c0a73d852 => nibbles MSB→LSB: f e 1 6 9 b 4 c 0 a 7 3 d 8 5 2 +INIT <- hex_to_nibbles("fe169b4c0a73d852") + +## ----- Core functions (translated) ----- +fY <- function(n) { + if (nibbles_equal(N2[[n + 1L]], GOAL)) { + return(list(ans = TRUE, n = n)) + } + if (N4[n + 1L] <= .n) { + return(fN(n)) + } + list(ans = FALSE, n = n) +} + +fZ <- function(w, n) { + if (bitwAnd(w, i) > 0L) { + n <- fI(n) + tmp <- fY(n) + if (tmp$ans) return(tmp) + n <- n - 1L + } + if (bitwAnd(w, g) > 0L) { + n <- fG(n) + tmp <- fY(n) + if (tmp$ans) return(tmp) + n <- n - 1L + } + if (bitwAnd(w, ee) > 0L) { + n <- fE(n) + tmp <- fY(n) + if (tmp$ans) return(tmp) + n <- n - 1L + } + if (bitwAnd(w, l) > 0L) { + n <- fL(n) + tmp <- fY(n) + if (tmp$ans) return(tmp) + n <- n - 1L + } + list(ans = FALSE, n = n) +} + +fN <- function(n) { + x <- N0[n + 1L] + y <- N3[n + 1L] # "d","u","r","l" + if (x == 0L) { + if (y == "l") return(fZ(i, n)) + else if (y == "u") return(fZ(ee, n)) + else return(fZ(i + ee, n)) + } else if (x == 3L) { + if (y == "r") return(fZ(i, n)) + else if (y == "u") return(fZ(l, n)) + else return(fZ(i + l, n)) + } else if (x == 1L || x == 2L) { + if (y == "l") return(fZ(i + l, n)) + else if (y == "r") return(fZ(i + ee, n)) + else if (y == "u") return(fZ(ee + l, n)) + else return(fZ(l + ee + i, n)) + } else if (x == 12L) { + if (y == "l") return(fZ(g, n)) + else if (y == "d") return(fZ(ee, n)) + else return(fZ(ee + g, n)) + } else if (x == 15L) { + if (y == "r") return(fZ(g, n)) + else if (y == "d") return(fZ(l, n)) + else return(fZ(g + l, n)) + } else if (x == 13L || x == 14L) { + if (y == "l") return(fZ(g + l, n)) + else if (y == "r") return(fZ(ee + g, n)) + else if (y == "d") return(fZ(ee + l, n)) + else return(fZ(g + ee + l, n)) + } else if (x == 4L || x == 8L) { + if (y == "l") return(fZ(i + g, n)) + else if (y == "u") return(fZ(g + ee, n)) + else if (y == "d") return(fZ(i + ee, n)) + else return(fZ(i + g + ee, n)) + } else if (x == 7L || x == 11L) { + if (y == "d") return(fZ(i + l, n)) + else if (y == "u") return(fZ(g + l, n)) + else if (y == "r") return(fZ(i + g, n)) + else return(fZ(i + g + l, n)) + } else { + if (y == "d") return(fZ(i + ee + l, n)) + else if (y == "l") return(fZ(i + g + l, n)) + else if (y == "r") return(fZ(i + g + ee, n)) + else if (y == "u") return(fZ(g + ee + l, n)) + else return(fZ(i + g + ee + l, n)) + } +} + +# Down: take nibble at gg=(11-N0)*4 and move it left by 16 bits => +4 nibbles +fI <- function(n) { + gg <- (11L - N0[n + 1L]) * 4L + pos <- as.integer(gg / 4L) + a <- get_nibble_at(N2[[n + 1L]], gg) + N0[n + 2L] <<- N0[n + 1L] + 4L + N2[[n + 2L]] <<- move_nibble(N2[[n + 1L]], pos, +4L) + N3[n + 2L] <<- "d" + N4[n + 2L] <<- N4[n + 1L] + cond <- Nr[a + 1L] <= (N0[n + 1L] %/% 4L) + if (!cond) N4[n + 2L] <<- N4[n + 2L] + 1L + n + 1L +} + +# Up: gg=(19-N0)*4, move right by 16 bits => -4 nibbles +fG <- function(n) { + gg <- (19L - N0[n + 1L]) * 4L + pos <- as.integer(gg / 4L) + a <- get_nibble_at(N2[[n + 1L]], gg) + N0[n + 2L] <<- N0[n + 1L] - 4L + N2[[n + 2L]] <<- move_nibble(N2[[n + 1L]], pos, -4L) + N3[n + 2L] <<- "u" + N4[n + 2L] <<- N4[n + 1L] + cond <- Nr[a + 1L] >= (N0[n + 1L] %/% 4L) + if (!cond) N4[n + 2L] <<- N4[n + 2L] + 1L + n + 1L +} + +# Right: gg=(14-N0)*4, shift by +4 bits => +1 nibble +fE <- function(n) { + gg <- (14L - N0[n + 1L]) * 4L + pos <- as.integer(gg / 4L) + a <- get_nibble_at(N2[[n + 1L]], gg) + N0[n + 2L] <<- N0[n + 1L] + 1L + N2[[n + 2L]] <<- move_nibble(N2[[n + 1L]], pos, +1L) + N3[n + 2L] <<- "r" + N4[n + 2L] <<- N4[n + 1L] + cond <- Nc[a + 1L] <= (N0[n + 1L] %% 4L) + if (!cond) N4[n + 2L] <<- N4[n + 2L] + 1L + n + 1L +} + +# Left: gg=(16-N0)*4, shift by -4 bits => -1 nibble +fL <- function(n) { + gg <- (16L - N0[n + 1L]) * 4L + pos <- as.integer(gg / 4L) + a <- get_nibble_at(N2[[n + 1L]], gg) + N0[n + 2L] <<- N0[n + 1L] - 1L + N2[[n + 2L]] <<- move_nibble(N2[[n + 1L]], pos, -1L) + N3[n + 2L] <<- "l" + N4[n + 2L] <<- N4[n + 1L] + cond <- Nc[a + 1L] >= (N0[n + 1L] %% 4L) + if (!cond) N4[n + 2L] <<- N4[n + 2L] + 1L + n + 1L +} + +solve_fn <- function(n) { + tmp <- fN(n) + ans <- tmp$ans + n <- tmp$n + if (ans) { + cat(sprintf("Solution found in %d moves:\n", n)) + if (n >= 1L) { + cat(paste0(N3[2:(n + 1L)], collapse = ""), "\n") + } else { + cat("\n") + } + } else { + cat(sprintf("next iteration, .n will be %d...\n", .n + 1L)) + n <<- 0L + .n <<- .n + 1L + solve_fn(n) + } +} + +run <- function() { + N0[1L] <<- 8L + .n <<- 1L + N2[[1L]] <<- INIT + # carry forward initial defaults + N3[1L] <<- "" + N4[1L] <<- 0L + solve_fn(0L) +} + +# Execute +run() diff --git a/Task/15-puzzle-solver/Rust/15-puzzle-solver-1.rust b/Task/15-puzzle-solver/Rust/15-puzzle-solver-1.rs similarity index 100% rename from Task/15-puzzle-solver/Rust/15-puzzle-solver-1.rust rename to Task/15-puzzle-solver/Rust/15-puzzle-solver-1.rs diff --git a/Task/15-puzzle-solver/Rust/15-puzzle-solver-2.rust b/Task/15-puzzle-solver/Rust/15-puzzle-solver-2.rs similarity index 100% rename from Task/15-puzzle-solver/Rust/15-puzzle-solver-2.rust rename to Task/15-puzzle-solver/Rust/15-puzzle-solver-2.rs diff --git a/Task/15-puzzle-solver/Uiua/15-puzzle-solver.uiua b/Task/15-puzzle-solver/Uiua/15-puzzle-solver.uiua new file mode 100644 index 0000000000..2ee70f4190 --- /dev/null +++ b/Task/15-puzzle-solver/Uiua/15-puzzle-solver.uiua @@ -0,0 +1,37 @@ +# Solve a 15 puzzle https://rosettacode.org/wiki/15_puzzle_solver#Uiua +T ← ↯4_4 ↻1⇡16 +Pos ← ≡(⊢⊚⌕)↘1⇡16¤ # Positions of the numbers (not 0) + +# Applying a very gentle weighting to certain cells massively +# speeds up the algorithm +Weights ← [[2 1 1 2] [2 1 1 2] [2 1 1 2] [2 1 1 1]] +Distance ← /+×⊡: Weights :≡/+⌵-⊙.∩Pos +Heuristic ← Distance T + +Nfour ← [[1 0] [¯1 0] [0 1] [0 ¯1]] + +ValidN ← ≡⊟⊙¤▽≡/↧×⊃(≡₀<4|≡₀≥0).+Nfour¤. # Actual neighbours at a point. +ValidNs ← ⊞(□ValidN⊟).⇡4 # Precalculate them. + +Moves ← °□⊡:ValidNs⊢⊚⌕0 # Get valid (from to) moves from grid. +Swap ← ⍜⊡⇌ # Swap the values at the indexes +Next ← ⊸≡⋅1 ≡Swap⊙¤⊸Moves # Next positions, set costs=1 + +Solve ← ( + &p$"Solving: _". + ⍜now (⊢path(Next|≍|Heuristic):T) + &p$"_ seconds" + ≡/-⧈∘2◇≡(⊢⊚⌕0)⇌⊢ # Track the movement of the 0 + ⇌˜≡get¤mapNfour"udlr" # Map to directions +) + +# Uncomment one of the following lines to try these grids +# ⍥(Swap⊡⊸(⌊×⚂⧻)⊸Moves)90 T +# [[2 14 6 4] [5 1 3 8] [9 10 7 11] [13 0 15 12]] # Simple 40 shuffles +# [[5 1 2 3] [6 10 7 4] [13 9 11 8] [14 0 15 12]] # Simple 12 steps +# [[9 1 2 4] [13 6 5 7] [3 11 14 15] [10 0 8 12]] # 34 steps +# [[10 3 1 4] [13 5 8 7] [9 6 0 11] [14 15 12 2]] # 38 steps (a few seconds) +[[15 14 1 6] [9 11 4 12] [0 10 7 3] [13 8 5 2]] # Main Challenge +# [[0 12 9 13] [15 11 10 14] [3 7 2 5] [4 8 6 1]] # Extra Credit + +Solve diff --git a/Task/15-puzzle-solver/V-(Vlang)/15-puzzle-solver.v b/Task/15-puzzle-solver/V-(Vlang)/15-puzzle-solver.v new file mode 100644 index 0000000000..35fa9515b9 --- /dev/null +++ b/Task/15-puzzle-solver/V-(Vlang)/15-puzzle-solver.v @@ -0,0 +1,194 @@ +import strconv + +struct FifteenSolver { + mut: + n int + n1 int + n0 []int + n2 []u64 + n3 []rune + n4 []int + xx u64 +} + +const nr = [3, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3] +const nc = [3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2] +const i_flag = 1 +const g_flag = 8 +const e_flag = 2 +const l_flag = 4 +const fifteen = u64(15) + +fn u64_from_hex(s string) u64 { + return strconv.parse_uint(s, 16, 64) or { 0 } +} + +fn (mut fs FifteenSolver) f_y() bool { + if fs.n2[fs.n] == fs.xx { return true } + if fs.n4[fs.n] <= fs.n1 { return fs.f_n() } + return false +} + +fn (mut fs FifteenSolver) f_i() { + g := (11 - fs.n0[fs.n]) * 4 + a := fs.n2[fs.n] & (fifteen << g) + fs.n0[fs.n + 1] = fs.n0[fs.n] + 4 + fs.n2[fs.n + 1] = fs.n2[fs.n] - a + (a << 16) + fs.n3[fs.n + 1] = `d` + fs.n4[fs.n + 1] = fs.n4[fs.n] + cond := nr[(a >> g) & 0xF] <= (fs.n0[fs.n] >> 2) + if !cond { fs.n4[fs.n + 1] = fs.n4[fs.n + 1] + 1 } + fs.n++ +} + +fn (mut fs FifteenSolver) f_g() { + g := (19 - fs.n0[fs.n]) * 4 + a := fs.n2[fs.n] & (fifteen << g) + fs.n0[fs.n + 1] = fs.n0[fs.n] - 4 + fs.n2[fs.n + 1] = fs.n2[fs.n] - a + (a >> 16) + fs.n3[fs.n + 1] = `u` + fs.n4[fs.n + 1] = fs.n4[fs.n] + cond := nr[(a >> g) & 0xF] >= (fs.n0[fs.n] >> 2) + if !cond { fs.n4[fs.n + 1] = fs.n4[fs.n + 1] + 1 } + fs.n++ +} + +fn (mut fs FifteenSolver) f_e() { + g := (14 - fs.n0[fs.n]) * 4 + a := fs.n2[fs.n] & (fifteen << g) + fs.n0[fs.n + 1] = fs.n0[fs.n] + 1 + fs.n2[fs.n + 1] = fs.n2[fs.n] - a + (a << 4) + fs.n3[fs.n + 1] = `r` + fs.n4[fs.n + 1] = fs.n4[fs.n] + cond := nc[(a >> g) & 0xF] <= fs.n0[fs.n] % 4 + if !cond { fs.n4[fs.n + 1] = fs.n4[fs.n + 1] + 1 } + fs.n++ +} + +fn (mut fs FifteenSolver) f_l() { + g := (16 - fs.n0[fs.n]) * 4 + a := fs.n2[fs.n] & (fifteen << g) + fs.n0[fs.n + 1] = fs.n0[fs.n] - 1 + fs.n2[fs.n + 1] = fs.n2[fs.n] - a + (a >> 4) + fs.n3[fs.n + 1] = `l` + fs.n4[fs.n + 1] = fs.n4[fs.n] + cond := nc[(a >> g) & 0xF] >= fs.n0[fs.n] % 4 + if !cond { fs.n4[fs.n + 1] = fs.n4[fs.n + 1] + 1 } + fs.n++ +} + +fn (mut fs FifteenSolver) f_z(w int) bool { + if w & i_flag > 0 { + fs.f_i() + if fs.f_y() { return true } + fs.n-- + } + if w & g_flag > 0 { + fs.f_g() + if fs.f_y() { return true } + fs.n-- + } + if w & e_flag > 0 { + fs.f_e() + if fs.f_y() { return true } + fs.n-- + } + if w & l_flag > 0 { + fs.f_l() + if fs.f_y() { return true } + fs.n-- + } + return false +} + +fn (mut fs FifteenSolver) f_n() bool { + p0 := fs.n0[fs.n] + p3 := fs.n3[fs.n] + return match p0 { + 0 { + if p3 == `l` { fs.f_z(i_flag) } + else if p3 == `u` { fs.f_z(e_flag) } + else { fs.f_z(i_flag + e_flag) } + } + 3 { + if p3 == `r` { fs.f_z(i_flag) } + else if p3 == `u` { fs.f_z(l_flag) } + else { fs.f_z(i_flag + l_flag) } + } + 1, 2 { + if p3 == `l` { fs.f_z(i_flag + l_flag) } + else if p3 == `r` { fs.f_z(i_flag + e_flag) } + else if p3 == `u` { fs.f_z(e_flag + l_flag) } + else { fs.f_z(l_flag + e_flag + i_flag) } + } + 12 { + if p3 == `l` { fs.f_z(g_flag) } + else if p3 == `d` { fs.f_z(e_flag) } + else { fs.f_z(e_flag + g_flag) } + } + 15 { + if p3 == `r` { fs.f_z(g_flag) } + else if p3 == `d` { fs.f_z(l_flag) } + else { fs.f_z(g_flag + l_flag) } + } + 13, 14 { + if p3 == `l` { fs.f_z(g_flag + l_flag) } + else if p3 == `r` { fs.f_z(e_flag + g_flag) } + else if p3 == `d` { fs.f_z(e_flag + l_flag) } + else { fs.f_z(g_flag + e_flag + l_flag) } + } + 4, 8 { + if p3 == `l` { fs.f_z(i_flag + g_flag) } + else if p3 == `u` { fs.f_z(g_flag + e_flag) } + else if p3 == `d` { fs.f_z(i_flag + e_flag) } + else { fs.f_z(i_flag + g_flag + e_flag) } + } + 7, 11 { + if p3 == `d` { fs.f_z(i_flag + l_flag) } + else if p3 == `u` { fs.f_z(g_flag + l_flag) } + else if p3 == `r` { fs.f_z(i_flag + g_flag) } + else { fs.f_z(i_flag + g_flag + l_flag) } + } + else { + if p3 == `d` { fs.f_z(i_flag + e_flag + l_flag) } + else if p3 == `l` { fs.f_z(i_flag + g_flag + l_flag) } + else if p3 == `r` { fs.f_z(i_flag + g_flag + e_flag) } + else if p3 == `u` { fs.f_z(g_flag + e_flag + l_flag) } + else { fs.f_z(i_flag + g_flag + e_flag + l_flag) } + } + } +} + +fn (mut fs FifteenSolver) fifteen_solver(n_val int, g_val u64) { + fs.n0[0] = n_val + fs.n2[0] = g_val + fs.n4[0] = 0 +} + +fn (mut fs FifteenSolver) solve() { + if fs.f_n() { + println("Solution found in $fs.n moves: ") + for g in 1 .. fs.n + 1 { + print(fs.n3[g].str()) + } + println("") + } else { + fs.n = 0 + fs.n1++ + fs.solve() + } +} + +fn main() { + mut fs := FifteenSolver{ + n0: []int{len: 85, init: 0} + n2: []u64{len: 85, init: 0} + n3: []rune{len: 85, init: ` `} + n4: []int{len: 85, init: 0} + n: 0 + n1: 0 + xx: u64_from_hex("123456789abcdef0") + } + fs.fifteen_solver(8, u64_from_hex("fe169b4c0a73d852")) + fs.solve() +} diff --git a/Task/15-puzzle-solver/Zig/15-puzzle-solver.zig b/Task/15-puzzle-solver/Zig/15-puzzle-solver.zig new file mode 100644 index 0000000000..e566437561 --- /dev/null +++ b/Task/15-puzzle-solver/Zig/15-puzzle-solver.zig @@ -0,0 +1,187 @@ +const std = @import("std"); +const Allocator = std.mem.Allocator; +const ArrayList = std.ArrayList; +const PriorityQueue = std.PriorityQueue; +const AutoHashMap = std.AutoHashMap; + +// Constants for the puzzle +const CORRECT_ORDER = [16]u8{ 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,0 }; +const ROW = [16]i32{ 0,0,0,0, 1,1,1,1, 2,2,2,2, 3,3,3,3 }; +const COLUMN = [16]i32{ 0,1,2,3, 0,1,2,3, 0,1,2,3, 0,1,2,3 }; + +// State struct to represent the puzzle state +const State = struct { + est_tot_moves: u8, + moves: []u8, + est_moves_rem: u8, + allocator: Allocator, + + pub fn init(allocator: Allocator, order: [16]u8) !State { + return State{ + .est_tot_moves = estimate_moves(order), + .moves = try allocator.dupe(u8, ""), // empty + .est_moves_rem = estimate_moves(order), + .allocator = allocator, + }; + } + + pub fn deinit(self: *State) void { + self.allocator.free(self.moves); + } +}; + +// BoardState represents the entire game state +const BoardState = struct { + order: [16]u8, + state: State, +}; + +// Find the index of a tile in the order array +fn findIndex(order: [16]u8, tile: u8) usize { + var i: usize = 0; + for (order) |v| { + if (v == tile) return i; + i += 1; + } + @panic("findIndex: tile not found"); +} + +// Estimate the number of moves (Manhattan distance) +fn estimate_moves(current: [16]u8) u8 { + var h: u8 = 0; + for (current) |tile| { + const ci = findIndex(current, tile); + const gi = findIndex(CORRECT_ORDER, tile); + const rd = @abs(ROW[ci] - ROW[gi]); + const cd = @abs(COLUMN[ci] - COLUMN[gi]); + h += @as(u8, @intCast(rd + cd)); + } + return h; +} + +// Make a single move (swap hole with neighbor) +fn makeMove( + allocator: Allocator, + parent: *const State, + order: [16]u8, + dir: u8, + idx: usize, + new_idx: usize, +) !BoardState { + var new_order = order; + new_order[idx] = order[new_idx]; + new_order[new_idx] = order[idx]; + + const rem = estimate_moves(new_order); + const mv: [1]u8 = .{dir}; + const combined = try std.mem.concat(allocator, u8, &[_][]const u8{ parent.moves, &mv }); + + return BoardState{ + .order = new_order, + .state = State{ + .est_tot_moves = @as(u8, @intCast(combined.len)) + rem, + .moves = combined, + .est_moves_rem = rem, + .allocator = allocator, + }, + }; +} + +// Generate all children from a parent (takes *const so we don't double-free) +fn generateChildren(allocator: Allocator, parent: *const BoardState) !ArrayList(BoardState) { + var children = ArrayList(BoardState).init(allocator); + const hole = findIndex(parent.order, 0); + + if (COLUMN[hole] > 0) { + const c = try makeMove(allocator, &parent.state, parent.order, 'l', hole, hole - 1); + try children.append(c); + } + if (COLUMN[hole] < 3) { + const c = try makeMove(allocator, &parent.state, parent.order, 'r', hole, hole + 1); + try children.append(c); + } + if (ROW[hole] > 0) { + const c = try makeMove(allocator, &parent.state, parent.order, 'u', hole, hole - 4); + try children.append(c); + } + if (ROW[hole] < 3) { + const c = try makeMove(allocator, &parent.state, parent.order, 'd', hole, hole + 4); + try children.append(c); + } + + return children; +} + +// Compare function for priority queue +fn boardCompare(_: void, a: BoardState, b: BoardState) std.math.Order { + return std.math.order(a.state.est_tot_moves, b.state.est_tot_moves); +} + +// Hash an order into a u64 +fn hashOrder(order: [16]u8) u64 { + var r: u64 = 0; + for (order) |v| r = (r << 4) | v; + return r; +} + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + const allocator = gpa.allocator(); + + var open_states = PriorityQueue(BoardState, void, boardCompare).init(allocator, {}); + defer { + while (open_states.count() > 0) { + var item = open_states.remove(); + item.state.deinit(); + } + open_states.deinit(); + } + + var closed_states = AutoHashMap(u64, void).init(allocator); + defer closed_states.deinit(); + + const start_order = [16]u8{15,14,1,6,9,11,4,12, 0,10,7,3,13,8,5,2}; + const initial_state = try State.init(allocator, start_order); + try open_states.add(BoardState{ .order = start_order, .state = initial_state }); + + const stdout = std.io.getStdOut().writer(); + + while (open_states.count() > 0) { + var current = open_states.remove(); + + // goal check + if (std.mem.eql(u8, ¤t.order, &CORRECT_ORDER)) { + try stdout.print( + "Open: {d}, Closed: {d}, Moves: {d}\n", + .{ open_states.count(), closed_states.count(), current.state.moves.len }, + ); + try stdout.print("Path: {s}\n", .{ current.state.moves }); + current.state.deinit(); + break; + } + + const h = hashOrder(current.order); + if (closed_states.contains(h)) { + current.state.deinit(); + continue; + } + try closed_states.put(h, {}); + + var children = try generateChildren(allocator, ¤t); + defer children.deinit(); + + // ↓ Here’s the fix: shadow each child into a mutable `var child` + for (children.items) |child| { + var my_child = child; // now `child.state.deinit()` sees a `*State`, not `*const State` + const ch = hashOrder(my_child.order); + if (closed_states.contains(ch)) { + my_child.state.deinit(); + continue; + } + try open_states.add(my_child); + } + + current.state.deinit(); + } +} diff --git a/Task/2048/Ada/2048.ada b/Task/2048/Ada/2048.adb similarity index 100% rename from Task/2048/Ada/2048.ada rename to Task/2048/Ada/2048.adb diff --git a/Task/2048/BQN/2048.bqn b/Task/2048/BQN/2048.bqn index a73e95c7b4..cb0a27ed3b 100644 --- a/Task/2048/BQN/2048.bqn +++ b/Task/2048/BQN/2048.bqn @@ -15,7 +15,7 @@ Spawn←{i←•rand.Range∘≠⊸⊑(0⊸= /○⥊ ↕∘≢)𝕩 ⋄ (•rand Lose←Left∘Right∘Down∘Up⊸≡ # Losing condition, no moves change the board Win←∨´·∨˝2048⊸= # Winning condition, 2048! -Quit←{•Out e∾"[?12l"∾e∾"[?25h" ⋄ •Exit 𝕩} # Restores the terminal and exits +Quit←{•Out e∾"[?12l"∾e∾"[?25h" ⋄ •term.RawMode 0 ⋄ •Exit 𝕩} # Restores the terminal and exits Display←{ # Displays the board, score and controls •Out e∾"[H"∾e∾"[2J" # Cursor to origin and clear screen •Out "Controls: h: left, j: down, k: up, l: right, q: quit" diff --git a/Task/2048/Delphi/2048.delphi b/Task/2048/Delphi/2048.pas similarity index 100% rename from Task/2048/Delphi/2048.delphi rename to Task/2048/Delphi/2048.pas diff --git a/Task/2048/EasyLang/2048.easy b/Task/2048/EasyLang/2048.easy new file mode 100644 index 0000000000..345c4962c4 --- /dev/null +++ b/Task/2048/EasyLang/2048.easy @@ -0,0 +1,161 @@ +len brd[] 16 +gbackground 987 +proc newtile . + for i to 16 : if brd[i] = 0 : break 1 + if i > 16 : return + v = 2 + if randomf < 0.1 : v = 4 + repeat + ind = random 1 16 + until brd[ind] = 0 + . + brd[ind] = v +. +global pts stat . +proc show . + gclear + gtextsize 5 + gcolor 222 + gtext 10 94 "2048 Game" + gtext 60 94 "Pts: " & pts + gtextsize 7 + gcolor 876 + grect 9 9 82 82 + gcolor 987 + grect 10 10 80 80 + for i to 16 : if brd[i] <> 0 + x = i mod1 4 * 20 - 9.5 + y = i div1 4 * 20 - 9.5 + gcolor 765 + grect x y 19 19 + v = brd[i] + h = 2 * floor log v 10 + gcolor 000 + gtext x + 7 - h y + 7 brd[i] + . +. +proc init . + for i to 16 : brd[i] = 0 + newtile + newtile + stat = 0 + pts = 0 + show +. +init +# +dir[] = [ -4 -1 4 1 ] +start[] = [ 16 4 1 13 ] +proc domove indk test &moved . + moved = 0 + dir = dir[indk] + bdir = dir[(indk + 1) mod1 4] + start = start[indk] + for i to 4 + h0 = start + dir + for j to 3 + if brd[h0] <> 0 + v = brd[h0] + h = h0 + while h <> start and brd[h - dir] = 0 : h -= dir + if h <> h0 + moved = 1 + if test = 1 : return + . + if h <> start and brd[h - dir] = v + moved = 1 + if test = 1 : return + v *= 2 + pts += v + brd[h - dir] = -v + if v = 2048 : stat = 1 + v = 0 + . + brd[h0] = 0 + brd[h] = v + . + h0 += dir + . + h0 = start + for j to 3 + brd[h0] = abs brd[h0] + h0 += dir + . + sleep 0.1 + show + start += bdir + . +. +proc handle indk . + if indk = 0 : return + domove indk 0 moved + if moved = 1 + newtile + sleep 0.2 + show + if stat = 0 + stat = 2 + for indk to 4 + domove indk 1 moved + if moved = 1 + stat = 0 + break 1 + . + . + . + . + if stat <> 0 + gtextsize 5 + if stat = 1 + stat = 0 + gtext 10 3 "You got 2048 😊" + else + gtext 10 3 "No more moves 🙁" + . + . +. +on mouse_down + mx = mouse_x + my = mouse_y +. +proc handle_mup . + dx = mouse_x - mx + dy = mouse_y - my + indk = 0 + if abs dx > abs dy + if abs dx > 3 + indk = 4 + if dx > 0 : indk = 2 + . + else + if abs dy > 3 + indk = 3 + if dy > 0 : indk = 1 + . + . + if indk <> 0 and stat = 2 + init + else + handle indk + . +. +on mouse_up + handle_mup +. +on key_down + if stat = 2 + if keybkey = " " : init + return + . + indk = 0 + if keybkey = "ArrowUp" + indk = 1 + elif keybkey = "ArrowRight" + indk = 2 + elif keybkey = "ArrowDown" + indk = 3 + elif keybkey = "ArrowLeft" + indk = 4 + . + handle indk +. diff --git a/Task/2048/Elixir/2048.elixir b/Task/2048/Elixir/2048.ex similarity index 100% rename from Task/2048/Elixir/2048.elixir rename to Task/2048/Elixir/2048.ex diff --git a/Task/2048/Guile/2048.guile b/Task/2048/Guile/2048.guile new file mode 100644 index 0000000000..f8b103f0d4 --- /dev/null +++ b/Task/2048/Guile/2048.guile @@ -0,0 +1,312 @@ +;;require-module (ice-9 format) +;;usage -> [~4d] print-board +;; +(use-modules (ice-9 format)) + +;;require-module (srfi srfi-64) +;;usage -> test-assert +;; +(use-modules (srfi srfi-64)) + +;;prodedure-name 2or4-generator +;;input -> <$:nil> +;;output -> _ (number) +;;note -> "it only generates 2 or 4, with a 10% of outputting 4" +;; +(define 2or4-generator + (lambda () + (let ([random-number (random 10)]) + (if (zero? random-number) + 4 + 2)))) + +;;procedure-name print-board +;;input -> board (array::4*4) +;;output -> <$:nil> +;; +(define print-board + (lambda (board) + (do ((i 0 (1+ i))) + ((> i 3)) + (do ((j 0 (1+ j))) + ((> j 3)) + (format #t "[~4d]" (array-ref board i j))) + (newline)))) + +;;procedure-name spawn! +;;input -> 4x4board (array::4*4) +;;output -> <$:nil> +;; +(define spawn! + (lambda (4x4board) + (let ([indexes '()]) + (do ((i 0 (1+ i))) + ((> i 3)) + (do ((j 0 (1+ j))) + ((> j 3)) + (when (zero? (array-ref 4x4board i j)) + (set! indexes (cons (cons i j) indexes))))) + (let* ([indexes-length (length indexes)] + [used-index-index (random indexes-length)] + [used-index-pair (list-ref indexes used-index-index)]) + (array-set! 4x4board (2or4-generator) (car used-index-pair) (cdr used-index-pair)))))) + +;;procedure-name ask-user +;;input -> valid-moves (list:symbol) +;;output -> _ (symbol) [(memq <$:self:_> (list 'up 'down 'left 'right)) => #t] +;;note -> "this procedure assumes there is at least one valid move" +;; +(define ask-user + (lambda (valid-moves) + (let loop () + (let ([option (read)]) + (if (memq option valid-moves) + (case option + [(up) 'up] + [(down) 'down] + [(left) 'left] + [(right) 'right] + [else (begin + (display "wrong input! Please type up, down, left, or right only!") + (newline) + (loop))]) + (begin + (display "please use valid moves!") + (newline) + (display "valid moves: ") + (display valid-moves) + (newline) + (loop))))))) + +;;procedure-name update-row! +;;input -> row (array::1*4) +;;output -> <$:nil> +;; +(define update-row! + (lambda (row) + (unless (array-equal? row #(0 0 0 0)) + (let ([lst '()] [l 0]) + (when (not (zero? (array-ref row 3))) (set! l (1+ l)) (set! lst (cons (array-ref row 3) lst))) + (when (not (zero? (array-ref row 2))) (set! l (1+ l)) (set! lst (cons (array-ref row 2) lst))) + (when (not (zero? (array-ref row 1))) (set! l (1+ l)) (set! lst (cons (array-ref row 1) lst))) + (when (not (zero? (array-ref row 0))) (set! l (1+ l)) (set! lst (cons (array-ref row 0) lst))) + (do ((i 0 (1+ i))) + ((>= i (- 4 l))) + (array-set! row 0 i)) + (do ((i (- 4 l) (1+ i)) (j 0 (1+ j))) + ((>= i 4)) + (array-set! row (list-ref lst j) i))) + (if (= (array-ref row 3) (array-ref row 2)) + (begin (array-set! row (+ (array-ref row 3) (array-ref row 2)) 3) + (array-set! row (array-ref row 1) 2) + (array-set! row (array-ref row 0) 1) + (array-set! row 0 0) + (when (= (array-ref row 2) (array-ref row 1)) + (array-set! row (+ (array-ref row 2) (array-ref row 1)) 2) + (array-set! row 0 1))) + (if (= (array-ref row 2) (array-ref row 1)) + (begin (array-set! row (+ (array-ref row 2) (array-ref row 1)) 2) + (array-set! row (array-ref row 0) 1) + (array-set! row 0 0)) + (when (= (array-ref row 1) (array-ref row 0)) + (array-set! row (+ (array-ref row 1) (array-ref row 0)) 1) + (array-set! row 0 0))))))) + +;;procedure-name update-board! +;;input -> board (array::4*4) +;;output -> <$:nil> +;;note -> "this procedure can assume that the opertion is shifting the piles right" +;; +(define update-board! + (lambda (board) + (do ((i 0 (1+ i))) + ((>= i 4)) + (update-row! (array-cell-ref board i))))) + +;;procedure-name row-can-shift-qright? +;;input -> row (array::1*4) +;;output -> _ (#t or #f) +;; +(define row-can-shift-right? + (lambda (row) + (if (and (zero? (array-ref row 0)) + (zero? (array-ref row 1)) + (zero? (array-ref row 2))) + #f + (if (or (zero? (array-ref row 3)) + (and (not (zero? (array-ref row 0))) (member 0 (list + (array-ref row 1) + (array-ref row 2) + (array-ref row 3)))) + (and (not (zero? (array-ref row 1))) (member 0 (list + (array-ref row 2) + (array-ref row 3)))) + (and (not (zero? (array-ref row 2))) (member 0 (list + (array-ref row 3))))) + #t + (if (or (and (not (zero? (array-ref row 0))) (= (array-ref row 0) (array-ref row 1))) + (and (not (zero? (array-ref row 1))) (= (array-ref row 1) (array-ref row 2))) + (and (not (zero? (array-ref row 2))) (= (array-ref row 2) (array-ref row 3)))) + #t + #f))))) + +(define test-row-can-shift-right? + (lambda () + (test-begin "row-can-shift-right? test") + (test-assert (row-can-shift-right? #(2 0 0 0))) + (test-assert (row-can-shift-right? #(0 2 0 0))) + (test-assert (row-can-shift-right? #(0 0 2 0))) + (test-assert (not (row-can-shift-right? #(0 0 0 2)))) + (test-assert (row-can-shift-right? #(4 2 0 0))) + (test-assert (row-can-shift-right? #(2 0 0 2))) + (test-assert (row-can-shift-right? #(1024 8 2 2))) + (test-end "row-can-shift-right? test"))) + +;;procedure-name can-shift-right? +;;input -> board (array::4*4) +;;output -> _ (#t or #f) +;; +(define can-shift-right? + (lambda (board) + (or (row-can-shift-right? (array-cell-ref board 0)) + (row-can-shift-right? (array-cell-ref board 1)) + (row-can-shift-right? (array-cell-ref board 2)) + (row-can-shift-right? (array-cell-ref board 3))))) + +(define test-can-shift-right? + (lambda () + (test-begin "can-shift-right? test") + (test-assert (can-shift-right? #2((2 0 0 2) + (0 0 0 0) + (0 0 0 0) + (0 0 0 0)))) + (test-assert (can-shift-right? #2((2 0 0 0) + (0 0 0 0) + (0 0 0 0) + (2 0 0 0)))) + (test-assert (not (can-shift-right? #2((2 8 4 8) + (2 16 4 8) + (0 0 0 4) + (0 0 0 2))))) + (test-end "can-shift-right? test"))) + +;;procedure-name valid-move? +;;input -> board (array::4*4) +;;output -> _ (symbol) [(eq? 'gameover <$:self:_>) => #t] +;;output -> _ (list:symbol[1 or 2 or 3 or 4]) +;;note -> "the list symbol should only contain up, down, left, right" +;; +(define valid-move? + (lambda (board) + (let* ([output-lst '()] + [rows board] + [columns (make-shared-array rows + (lambda (i j) + (list j i)) + 4 4)] + [rows-reversed (make-shared-array rows + (lambda (i j) + (list i (- 3 j))) + 4 4)] + [columns-reversed (make-shared-array columns + (lambda (i j) + (list i (- 3 j))) + 4 4)]) + (when (can-shift-right? rows) (set! output-lst (append (list 'right) output-lst))) + (when (can-shift-right? rows-reversed) (set! output-lst (append (list 'left) output-lst))) + (when (can-shift-right? columns) (set! output-lst (append (list 'down) output-lst))) + (when (can-shift-right? columns-reversed) (set! output-lst (append (list 'up) output-lst))) + (if (null? output-lst) + 'gameover + output-lst)))) + +(define test-valid-move? + (lambda () + (test-begin "valid-move? test") + (test-assert (eq? 'gameover (valid-move? #2((8 4 2 16) + (2 8 4 32) + (4 2 8 16) + (128 4 16 64))))) + (test-assert (equal? (list 'up 'down 'left 'right) (valid-move? #2((0 0 0 0) + (0 2 0 0) + (0 0 0 0) + (0 0 0 2))))) + (test-end "valid-move? test"))) + +;;prodedure-name check-game-status! +;;input -> board (array::4*4) +;;output -> _ (symbol) +;;note -> "The thing this procedure should implement: 1.decide whether there is a 2048 tile on board, if so, return 'win 2.decide the valid moves next time and return them as a list like (list 'up 'down 'right) or anything equivalent (if there is no valid moves, just return 'gameover)" +;; +(define check-game-status! + (lambda (board) + (spawn! board) + (let ([all-tiles (list (array-ref board 0 0) + (array-ref board 0 1) + (array-ref board 0 2) + (array-ref board 0 3) + (array-ref board 1 0) + (array-ref board 1 1) + (array-ref board 1 2) + (array-ref board 1 3) + (array-ref board 2 0) + (array-ref board 2 1) + (array-ref board 2 2) + (array-ref board 2 3) + (array-ref board 3 0) + (array-ref board 3 1) + (array-ref board 3 2) + (array-ref board 3 3))]) + (if (member 2048 all-tiles) + 'win + (valid-move? board))))) + +;;procedure-name play +;;input -> <$:nil> +;;output -> _ (array:4*4) +;; +(define play + (lambda () + (set! *random-state* (random-state-from-platform)) + (let ([board (make-array 0 4 4)]) + (let* ([rows board] + [columns (make-shared-array rows + (lambda (i j) + (list j i)) + 4 4)] + [rows-reversed (make-shared-array rows + (lambda (i j) + (list i (- 3 j))) + 4 4)] + [columns-reversed (make-shared-array columns + (lambda (i j) + (list i (- 3 j))) + 4 4)]) + (spawn! rows) + (let loop ([turn 1] [available-moves (valid-move? rows)]) + (format #t "TURN ~d" turn) + (newline) + (print-board rows) + (case (ask-user available-moves) + [(up) (update-board! columns-reversed)] + [(down) (update-board! columns)] + [(left) (update-board! rows-reversed)] + [(right) (update-board! rows)] + [else (error "something went wrong! The return stuff from (ask-user availuable-moves) is not among 'up 'down 'left 'right! This normally should never be reached.")]) + (let ([symbols (check-game-status! rows)]) + (cond + [(symbol? symbols) (case symbols + [(win) (begin + (display "You win!") + (newline) + (print-board rows))] + [(gameover) (begin + (display "You lose!") + (newline) + (print-board rows))] + [else (error "While not intended, we named what the procedure (check-game-status rows) returned as symbols, checking it as a symbol which passed, then we get this. But we coded this to be 'win or 'gameover !")])] + [(list? symbols) (begin + (display "Valid moves: ") + (display symbols) + (newline) + (loop (1+ turn) symbols))]))))))) diff --git a/Task/2048/Jq/2048.jq b/Task/2048/Jq/2048.jq new file mode 100644 index 0000000000..367500faf2 --- /dev/null +++ b/Task/2048/Jq/2048.jq @@ -0,0 +1,127 @@ +include "MRG32k3a" {search: "."}; # see comment above + +### Generic functions + +def lpad($len): tostring | ($len - length) as $l | (" " * $l) + .; + +# Create an m x n matrix with initial values specified by . +def matrix($m; $n): + if $m == 0 then [] + else . as $init + | if $m == 1 then [range(0;$n) | $init] + elif $m > 0 then + matrix(1; $n) as $row + | [range(0; $m) | $row ] + else error("matrix\($m);\($n)) invalid") + end + end; + + +### The 2048 Game +# Left-squish the input array in accordance with the game requirements for a single row +def squish: + def squish($n): + def s: + if length == 0 then [range(0;$n)|null] + elif .[0] == null then .[1:] | s + elif length == 1 then . + [range(0; $n - 1)|null] + elif .[0] == .[1] then [.[0] + .[1]] + (.[2:]|squish($n-1)) + else .[0:1] + (.[1:]|squish($n-1)) + end; + s; + squish(length); + +# Input: a matrix of rows +def squish_left: + [.[] | squish]; + +def squish_right: + [.[] | reverse | squish | reverse]; + +def squish_up: + transpose + | [.[] | squish] + | transpose; + +def squish_down: + transpose + | [.[] | reverse | squish | reverse] + | transpose; + +# Gather the [i,j] co-ordinates of all the null values in the input matrix +def gather: + if length == 0 then error end + | (.[0] | length) as $cols + | [range(0;length) as $i + | range(0; $cols) as $j + | select(.[$i][$j] == null) | [$i,$j]] + | if length == 0 then error end ; + +# Input: {matrix} +# Add a random 2 or 4 if possible, else error +# Output: includes .prng for the PRN generator +def add_random: + (.matrix | gather) as $gather + | ($gather | length) as $n + | if $n == 0 then error end + | if .prng == null then .prng = seed(now | tostring | sub("^.*[.]";"") | tonumber) end + | .prng |= nextFloat + | $gather[.prng.nextFloat * $n | trunc] as [$i,$j] + | .prng |= nextFloat + | (if (.prng.nextFloat) < 0.1 then 4 else 2 end) as $exmachina + | .matrix[$i][$j] = $exmachina ; + +def prompt: "[ijkl] or [wasd] or q to quit or n to restart:"; + +def direction: + {"i": "up", "j": "left", "k": "down", "l": "right", + "w": "up", "a": "left", "s": "down", "d": "right", + "q": "quit", + "n": "restart" + }; + +# Recognize $goal as the goal +def play($goal): + + # Pretty print + def pp: + .matrix[] | map(. // "." | lpad(4)) | join(" "); + + def won: + any(.matrix[][]; . == $goal); + + def lost: + .matrix + | (squish_left == .) and (squish_right == .) and + (squish_up == .) and (squish_down == .); + + def round: + pp, + if lost then "Sorry! Better luck next time.", play($goal) + else prompt, + ( (try input catch halt) as $in + | .matrix as $matrix # for checking if a move is legal + | .emit = null + | direction[$in | ascii_downcase] as $direction + | if $direction == "up" then .matrix |= squish_up + elif $direction == "down" then .matrix |= squish_down + elif $direction == "left" then .matrix |= squish_left + elif $direction == "right" then .matrix |= squish_right + elif $direction == "quit" then .emit = "bye" + elif $direction == "restart" then .emit = "restart" + else .emit = "unknown direction \($direction) ... please try again." + end + | if .emit == "bye" then .emit, halt + elif .emit == "restart" then "Restarting...", play($goal) + elif .emit != null then .emit, round + elif .matrix == $matrix then "Disallowed direction! Please try again.", round + elif won then pp, "Congratulations!", play($goal) + else add_random | round + end) + end; + + { matrix: (null | matrix(4;4))} + | .matrix[2] = [null,2,2,2] + | round; + +play(2048) diff --git a/Task/2048/Julia/2048.julia b/Task/2048/Julia/2048.jl similarity index 100% rename from Task/2048/Julia/2048.julia rename to Task/2048/Julia/2048.jl diff --git a/Task/2048/Kotlin/2048.kotlin b/Task/2048/Kotlin/2048.kts similarity index 100% rename from Task/2048/Kotlin/2048.kotlin rename to Task/2048/Kotlin/2048.kts diff --git a/Task/2048/OCaml/2048.ocaml b/Task/2048/OCaml/2048.ml similarity index 100% rename from Task/2048/OCaml/2048.ocaml rename to Task/2048/OCaml/2048.ml diff --git a/Task/2048/Rust/2048.rust b/Task/2048/Rust/2048.rs similarity index 100% rename from Task/2048/Rust/2048.rust rename to Task/2048/Rust/2048.rs diff --git a/Task/2048/Wren/2048.wren b/Task/2048/Wren/2048.wren index ddff0c113d..b92bc4948d 100644 --- a/Task/2048/Wren/2048.wren +++ b/Task/2048/Wren/2048.wren @@ -20,13 +20,6 @@ class G2048 { for (j in 0..3) _board[i][j] = Tile.new(0, false) } _rand = Random.new() - initializeBoard() - } - - initializeBoard() { - for (y in 0..3) { - for (x in 0..3) _board[x][y] = Tile.new(0, false) - } } loop() { diff --git a/Task/2048/Zig/2048.zig b/Task/2048/Zig/2048.zig new file mode 100644 index 0000000000..ffe55ff922 --- /dev/null +++ b/Task/2048/Zig/2048.zig @@ -0,0 +1,362 @@ +// git repository at https://codeberg.org/Vulwsztyn/2048_zig +const std = @import("std"); +const builtin = @import("builtin"); + +const Io = std.Io; +const Random = std.Random; +const fmt = std.fmt; + +const mibu = @import("mibu"); +const color = mibu.color; +const events = mibu.events; +const term = mibu.term; +const cursor = mibu.cursor; + +// You can change these constants to modify the game behavior +const ROW_SIZE = 4; // program won't work if less than 2 +const COL_SIZE = 4; // program won't work if less than 2 +const TARGET_SCORE = 11; // 2^11 = 2048 +const PROBABILITY_OF_FOUR_NUMERATOR = 10; +const PROBABILITY_OF_FOUR_DENOMINATOR = 100; // these 2 work in tandem to give chance of spawning a 4 instead of 2 + +const Dir = enum { up, down, left, right }; +const Action = union(enum) { + Move: Dir, + Quit, + Noop, +}; + +fn spawn(comptime X: usize, comptime Y: usize, matrix_p: *[X][Y]u8, rand: Random) void { + var buffer: [X * Y]u8 = undefined; + var zero_indices = std.ArrayListUnmanaged(u8).initBuffer(&buffer); + for (matrix_p, 0..) |row, i| { + for (row, 0..) |val, j| { + if (val == 0) { + zero_indices.appendBounded(@intCast(i * Y + j)) catch unreachable; + } + } + } + const random_index = rand.intRangeAtMost(u8, 0, @intCast(zero_indices.items.len - 1)); + const chosen = zero_indices.items[random_index]; + const row = chosen / Y; + const col = chosen % Y; + const value: u8 = if (rand.intRangeAtMost(u8, 0, PROBABILITY_OF_FOUR_DENOMINATOR) < PROBABILITY_OF_FOUR_NUMERATOR) 2 else 1; + matrix_p[row][col] = value; +} + +fn additives_for_previous(dir: Dir) [2]i8 { + // assuming that for a move in a direction, we look at the values at the end + // and check backwards + // e.g. for up, we look at the top row and check downwards + // so we return 1, 0 meaning one row down, same column + switch (dir) { + .up => { + return .{ 1, 0 }; + }, + .down => { + return .{ -1, 0 }; + }, + .left => { + return .{ 0, 1 }; + }, + .right => { + return .{ 0, -1 }; + }, + } +} +fn is_move_possible(comptime X: usize, comptime Y: usize, matrix_p: [X][Y]u8, dir: Dir) bool { + // checks if move is possible by checking if any tile can be moved or combined + const additives = additives_for_previous(dir); + for (0..X) |i| { + const i_signed: i8 = @intCast(i); + const new_i = i_signed + additives[0]; + if (new_i < 0 or new_i >= X) continue; + for (0..Y) |j| { + const j_signed: i8 = @intCast(j); + const new_j = j_signed + additives[1]; + if (new_j < 0 or new_j >= Y) continue; + const val = matrix_p[i][j]; + const prev_val = matrix_p[@intCast(new_i)][@intCast(new_j)]; + if (val != 0 and val == prev_val) return true; + if (val == 0 and prev_val != 0) return true; + } + } + return false; +} + +fn is_game_lost(comptime X: usize, comptime Y: usize, matrix_p: [X][Y]u8) bool { + // checks if move in any direction is possible + for (std.meta.tags(Dir)) |dir| { + if (is_move_possible(X, Y, matrix_p, dir)) { + return false; + } + } + return true; +} + +fn is_game_won(comptime X: usize, comptime Y: usize, matrix_p: [X][Y]u8) bool { + for (matrix_p) |row| { + for (row) |val| { + if (val >= TARGET_SCORE) { + return true; + } + } + } + return false; +} + +fn last_positions(comptime X: usize, comptime Y: usize, dir: Dir, gpa: std.mem.Allocator) std.ArrayList([2]u8) { + // see comment in additives_for_previous + // e.g. for move up we start at the top row and go downwards + // this function returns the list positions in the top row (for that scenario) + var list: std.ArrayList([2]u8) = .empty; + switch (dir) { + .up => { + for (0..Y) |i| { + list.append(gpa, .{ 0, @intCast(i) }) catch unreachable; + } + }, + .down => { + for (0..Y) |i| { + list.append(gpa, .{ X - 1, @intCast(i) }) catch unreachable; + } + }, + .left => { + for (0..X) |i| { + list.append(gpa, .{ @intCast(i), 0 }) catch unreachable; + } + }, + .right => { + for (0..X) |i| { + list.append(gpa, .{ @intCast(i), X - 1 }) catch unreachable; + } + }, + } + return list; +} + +fn move_matrix(comptime X: usize, comptime Y: usize, matrix_p: *[X][Y]u8, dir: Dir) void { + const gpa = std.heap.page_allocator; + const additives = additives_for_previous(dir); + var postions = last_positions(X, Y, dir, gpa); + defer postions.deinit(gpa); + std.debug.print("\n", .{}); + for (postions.items) |pos| { + var target_row: i8 = @intCast(pos[0]); + var target_col: i8 = @intCast(pos[1]); + var target_val: u8 = matrix_p[pos[0]][pos[1]]; + var current_row: i8 = target_row; + var current_col: i8 = target_col; + while (true) { + current_row += additives[0]; + current_col += additives[1]; + const went_out_of_bounds = current_row < 0 or current_row >= (X) or + current_col < 0 or current_col >= (Y); + if (went_out_of_bounds) { + break; + } + const current_val: u8 = matrix_p[@intCast(current_row)][@intCast(current_col)]; + if (current_val == 0) { + // nothing to do, + continue; + } + if (target_val != 0 and target_val != current_val) { + // cannot combine, move target forward + // e.g 0 0 2 4 (for was target, now 2 becomes target) + matrix_p[@intCast(current_row)][@intCast(current_col)] = 0; + target_row = (target_row) + (additives[0]); + target_col = (target_col) + (additives[1]); + matrix_p[@intCast(target_row)][@intCast(target_col)] = current_val; + target_val = matrix_p[@intCast(target_row)][@intCast(target_col)]; + continue; + } + if (target_val == 0) { + // move current to target + // e.g 0 0 2 0 -> 0 0 0 2 (2 remains target, since we want 0 2 2 0 to become 0 0 0 4) + matrix_p[@intCast(target_row)][@intCast(target_col)] = current_val; + target_val = current_val; + } else { + // combine + // e.g 0 0 2 2 -> 0 0 0 4 (with rightmost zero becoming target, since the movements are not greedy) + matrix_p[@intCast(target_row)][@intCast(target_col)] = target_val + 1; + target_val = 0; + target_row = target_row + (additives[0]); + target_col = target_col + (additives[1]); + } + // both in case of move and combine we clear current + matrix_p[@intCast(current_row)][@intCast(current_col)] = 0; + } + } +} + +fn print(comptime X: usize, comptime Y: usize, matrix_p: [X][Y]u8, stdout: *Io.Writer) !void { + for (matrix_p, 0..) |row, i| { + try cursor.goTo(stdout, 1, 2 + i); + var buf: [100]u8 = undefined; + const all_together_slice = buf[0..]; + for (row) |val| { + const value = if (val != 0) std.math.pow(u16, 2, @intCast(val)) else 0; + const value_as_str = if (val > 0) try fmt.bufPrint(all_together_slice, "{d}", .{value}) else "_"; + + try color.fg256(stdout, if (val > 1) @enumFromInt(val) else color.Color.white); // sets colour based on value + try stdout.print("{s:>5} ", .{value_as_str}); // prints with padding + } + try stdout.print("\x1b[K\n", .{}); + } +} + +fn init_matrix(comptime X: usize, comptime Y: usize, matrix_p: *[X][Y]u8) void { + // initializes matrix to all zeros + for (matrix_p) |*row| { + for (row) |*val| { + val.* = @intCast(0); + } + } +} + +fn action_from_event(next: events.Event) Action { + switch (next) { + .key => |k| switch (k.code) { + .char => |c| switch (c) { + 'c' => { + return .Quit; + }, + 'q' => { + return .Quit; + }, + 'w' => { + return .{ .Move = .up }; + }, + 's' => { + return .{ .Move = .down }; + }, + 'a' => { + return .{ .Move = .left }; + }, + 'd' => { + return .{ .Move = .right }; + }, + 'h' => { + return .{ .Move = .left }; + }, + 'j' => { + return .{ .Move = .down }; + }, + 'k' => { + return .{ .Move = .up }; + }, + 'l' => { + return .{ .Move = .right }; + }, + else => { + return .Noop; + }, + }, + .up => { + return .{ .Move = .up }; + }, + .down => { + return .{ .Move = .down }; + }, + .left => { + return .{ .Move = .left }; + }, + .right => { + return .{ .Move = .right }; + }, + else => { + return .Noop; + }, + }, + else => { + return .Noop; + }, + } +} + +pub fn main() !void { + const row_size = ROW_SIZE; + const col_size = COL_SIZE; + var seed: u64 = undefined; + try std.posix.getrandom(std.mem.asBytes(&seed)); + + var prng = Random.DefaultPrng.init(seed); + const rand = prng.random(); + + var stdout_buffer: [1024]u8 = undefined; + + const stdin = std.fs.File.stdin(); + var stdout_file = std.fs.File.stdout(); + var stdout_writer = stdout_file.writer(&stdout_buffer); + const stdout = &stdout_writer.interface; + + if (!std.posix.isatty(stdin.handle)) { + try stdout.print("The current file descriptor is not a referring to a terminal.\n", .{}); + return; + } + + if (builtin.os.tag == .windows) { + try mibu.enableWindowsVTS(stdout.handle); + } + + // Enable terminal raw mode, its very recommended when listening for events + var raw_term = try term.enableRawMode(stdin.handle); + defer raw_term.disableRawMode() catch { + std.debug.print("Failed to disable raw mode\n", .{}); + }; + + try term.enterAlternateScreen(stdout); + defer term.exitAlternateScreen(stdout) catch { + std.debug.print("Failed to exit alternate screen\n", .{}); + }; + + try cursor.hide(stdout); + defer cursor.show(stdout) catch { + std.debug.print("Failed to show cursor\n", .{}); + }; + + try cursor.goTo(stdout, 1, 1); + try mibu.style.italic(stdout, true); + + var matrix: [row_size][col_size]u8 = undefined; + + init_matrix(row_size, col_size, &matrix); + + spawn(row_size, col_size, &matrix, rand); + try stdout.print("move with wsad, hjkl, or arrows; quit with c or q\x1b[K\n", .{}); // prints with padding + + try print(row_size, col_size, matrix, stdout); + + try stdout.flush(); + + while (true) { + try cursor.goTo(stdout, 1, 2); + const next = try events.next(stdin); + const action = action_from_event(next); + switch (action) { + .Quit => break, + .Noop => continue, + .Move => |dir| { + if (is_move_possible(row_size, col_size, matrix, dir)) { + move_matrix(row_size, col_size, &matrix, dir); + try print(row_size, col_size, matrix, stdout); + if (is_game_won(row_size, col_size, matrix)) { + try cursor.goTo(stdout, 1, row_size + 3); + try stdout.print("You won! Congratulations!\n", .{}); + try stdout.flush(); + break; + } + spawn(row_size, col_size, &matrix, rand); + try print(row_size, col_size, matrix, stdout); + if (is_game_lost(row_size, col_size, matrix)) { + try cursor.goTo(stdout, 1, (row_size + 3)); + try stdout.print("Game over! No more moves possible!\n", .{}); + try stdout.flush(); + break; + } + } + try stdout.flush(); + }, + } + } +} diff --git a/Task/21-game/00-TASK.txt b/Task/21-game/00-TASK.txt index 85e5e6c32b..0fd624861d 100644 --- a/Task/21-game/00-TASK.txt +++ b/Task/21-game/00-TASK.txt @@ -9,6 +9,7 @@ One player will be the computer. Players alternate supplying a number to be added to the ''running total''. +This game is a variant of [https://en.wikipedia.org/wiki/Nim#The_21_game Nim]. ;Task: Write a computer program that will: @@ -19,4 +20,7 @@ Write a computer program that will: ::* provide a mechanism for the player to quit/exit/halt/stop/close the program, ::* issue a notification when there is a winner, and ::* determine who goes first (maybe a random or user choice, or can be specified when the game begins). + +;Related tasks: +::* [[Nim game]]

    diff --git a/Task/21-game/ALGOL-68/21-game.alg b/Task/21-game/ALGOL-68/21-game.alg new file mode 100644 index 0000000000..e9dfe16bed --- /dev/null +++ b/Task/21-game/ALGOL-68/21-game.alg @@ -0,0 +1,41 @@ +IF print( ( "Player who reaches 21, wins", newline ) ); # 21 game - based on the EasyLang sample # + INT human = 1, computer = 2; + []STRING name = ( "Human ", "Computer" ); + INT player := human, sum := 0; + STRING a := "?"; + WHILE a /= "y" AND a /= "n" AND a /= "q" DO + print( ( "Do you want to go first (y/n/q) " ) ); + read( ( a, newline ) ); + IF a = "n" THEN player := computer FI + OD; + a /= "q" +THEN + WHILE + INT add := IF player = human THEN + a := "?"; + WHILE a /= "q" AND a /= "1" AND a /= "2" AND a /= "3" DO + print( ( newline, "Add 1, 2 or 3 (q to quit) " ) ); + read( ( a, newline ) ) + OD; + IF a = "1" THEN 1 ELIF a = "2" THEN 2 ELSE 3 FI + ELIF sum MOD 4 = 1 THEN + # player = computer, optimal move not possible # + ENTIER ( random * 3 ) + 1 + ELSE + # player = computer, can make the optimal move # + 4 - ( sum + 3 ) MOD 4 + FI; + sum +:= add; + IF a /= "q" THEN + print( ( name[ player ], ": ", whole( add, 0 ), " --> ", whole( sum, 0 ), newline ) ) + FI; + a /= "q" AND sum < 21 + DO + player := IF player = human THEN computer ELSE human FI + OD; + IF a /= "q" THEN + print( ( newline ) ); + print( ( IF player = human THEN "Congratulations, you won" ELSE "Sorry, you lost" FI ) ); + print( ( newline ) ) + FI +FI diff --git a/Task/21-game/Ada/21-game.ada b/Task/21-game/Ada/21-game.adb similarity index 100% rename from Task/21-game/Ada/21-game.ada rename to Task/21-game/Ada/21-game.adb diff --git a/Task/21-game/AppleScript/21-game.applescript b/Task/21-game/AppleScript/21-game.applescript new file mode 100644 index 0000000000..c850f044a1 --- /dev/null +++ b/Task/21-game/AppleScript/21-game.applescript @@ -0,0 +1,44 @@ +repeat + set pstart to some item of {true, false} + if pstart then + display alert "You go first!" + set score to 0 + else + display alert "The computer goes first!" + log "The computer chose 1" + log "The score is now 1" + set score to 1 + end if + repeat + repeat + set input to display alert "Choose a number:" buttons {1, 2, 3} + set pmove to button returned of input + set score to score + pmove + if score > 21 then + display alert "You can't go above 21! Try again." + set score to score - pmove + else + exit repeat + end if + end repeat + log "You chose " & pmove + log "The score is now " & score + if score = 21 then + log "You win!" + exit repeat + else if score mod 4 is not 1 then + set cmove to (5 - (score mod 4)) mod 4 + else + set cmove to random number from 1 to 3 + end if + set score to score + cmove + log "The computer chose " & cmove + log "The score is now " & score + if score = 21 then + log "Too bad! The computer wins." + exit repeat + end if + end repeat + set again to display alert "Play again?" buttons {"Yes", "No"} + if button returned of again = "No" then exit repeat +end repeat diff --git a/Task/21-game/Arturo/21-game.arturo b/Task/21-game/Arturo/21-game.arturo index 3b62d3b212..a4c0d5eb0f 100644 --- a/Task/21-game/Arturo/21-game.arturo +++ b/Task/21-game/Arturo/21-game.arturo @@ -5,7 +5,7 @@ print "-----------------------------" players: ["A" "B"] currentPlayer: sample players nextPlayer: first players -- currentPlayer -runningTotal: new 0 +runningTotal: 0 num: 0 getNum: function [][ diff --git a/Task/21-game/AutoHotkey/21-game.ahk b/Task/21-game/AutoHotkey/21-game.ahk index 89fc54b3c2..ba112f623d 100644 --- a/Task/21-game/AutoHotkey/21-game.ahk +++ b/Task/21-game/AutoHotkey/21-game.ahk @@ -6,7 +6,7 @@ Gui, add, text, xs vT, Total : 00 Gui, add, text, xs vComputer, Computer Dealt 00 Gui, add, text, xs Section, Player 1 loop, 3 - Gui, add, button, x+5 vPlayer1_%A_Index% gTotal, % A_Index + Gui, add, button, x+5 vPlayer1_%A_Index% gTotal, % A_Index Gui, add, button, xs vReset gReset, reset Gui show,, 21 Game Winners := [1,5,9,13,17,21] @@ -18,13 +18,13 @@ total := 0 GuiControl,, T, % "Total : " SubStr("00" Total, -1) GuiControl,, Computer, % "Computer Waiting" Loop 3 - GuiControl, Enable, % "Player1_" A_Index + GuiControl, Enable, % "Player1_" A_Index Random, rnd, 0, 1 if rnd { - Loop 3 - GuiControl, Disable, % "Player1_" A_Index - gosub ComputerTurn + Loop 3 + GuiControl, Disable, % "Player1_" A_Index + gosub ComputerTurn } return ;----------------------------------- @@ -34,12 +34,12 @@ Total += Added GuiControl,, T, % "Total : " SubStr("00" Total, -1) if (total >= 21) { - MsgBox % "Player 1 Wins" - gosub reset - return + MsgBox % "Player 1 Wins" + gosub reset + return } Loop 3 - GuiControl, Disable, % "Player1_" A_Index + GuiControl, Disable, % "Player1_" A_Index gosub, ComputerTurn return ;----------------------------------- @@ -48,38 +48,38 @@ Gui, Submit, NoHide Sleep 500 if RadioE { - if (total < 13) - RadioC := true - else - RadioH := true + if (total < 13) + RadioC := true + else + RadioH := true } if RadioC { - Random, Deal, 1, 3 - total += Deal + Random, Deal, 1, 3 + total += Deal } if RadioH { - for i, v in Winners - if (total >= v) - continue - else - { - Deal := v - total - if Deal > 3 - Random, Deal, 1, 3 - total += Deal - break - } + for i, v in Winners + if (total >= v) + continue + else + { + Deal := v - total + if Deal > 3 + Random, Deal, 1, 3 + total += Deal + break + } } GuiControl,, T, % "Total : " SubStr("00" Total, -1) GuiControl,, Computer, % "Computer Dealt " Deal if (total=21) { - MsgBox Computer Wins - gosub, reset + MsgBox Computer Wins + gosub, reset } else - Loop 3 - GuiControl, Enable, % "Player1_" A_Index + Loop 3 + GuiControl, Enable, % "Player1_" A_Index return diff --git a/Task/21-game/EasyLang/21-game.easy b/Task/21-game/EasyLang/21-game.easy index 1ed700b063..6f4e5100cd 100644 --- a/Task/21-game/EasyLang/21-game.easy +++ b/Task/21-game/EasyLang/21-game.easy @@ -2,36 +2,36 @@ print "Who reaches 21, wins" print "Do you want to begin (y/n)" who = 1 if input = "n" - who = 2 + who = 2 . who$[] = [ "Human" "Computer" ] repeat - if who = 1 - repeat - print "" - print "Choose 1,2 or 3 (q for quit)" - a$ = input - n = number a$ - until a$ = "q" or (n >= 1 and n <= 3) - . - else - sleep 1 - if sum mod 4 = 1 - n = randint 3 - else - n = 4 - (sum + 3) mod 4 - . - . - sum += n - print who$[who] & ": " & n & " --> " & sum - until sum >= 21 or a$ = "q" - who = who mod 2 + 1 + if who = 1 + repeat + print "" + print "Choose 1,2 or 3 (q for quit)" + a$ = input + n = number a$ + until a$ = "q" or (n >= 1 and n <= 3) + . + else + sleep 1 + if sum mod 4 = 1 + n = random 1 3 + else + n = 4 - (sum + 3) mod 4 + . + . + sum += n + print who$[who] & ": " & n & " --> " & sum + until sum >= 21 or a$ = "q" + who = who mod 2 + 1 . if a$ <> "q" - print "" - if who = 0 - print "Congratulation, you won" - else - print "Sorry, you lost" - . + print "" + if who = 0 + print "Congratulation, you won" + else + print "Sorry, you lost" + . . diff --git a/Task/21-game/GDScript/21-game.gd b/Task/21-game/GDScript/21-game.gd index 78f190267d..009e2e3a9a 100644 --- a/Task/21-game/GDScript/21-game.gd +++ b/Task/21-game/GDScript/21-game.gd @@ -8,81 +8,81 @@ const target: int = 21 # -1 is returned to request quit func get_player_choice(total: int) -> int: - while true: - printraw("Player's choice: ") - var input: String = OS.read_string_from_stdin().strip_edges() + while true: + printraw("Player's choice: ") + var input: String = OS.read_string_from_stdin().strip_edges() - if input == "quit": - return -1 + if input == "quit": + return -1 - if not input.is_valid_int(): - print("Please input an integer.") - continue + if not input.is_valid_int(): + print("Please input an integer.") + continue - var input_int := int(input) - if input_int < 1 or input_int > 3: - print("Please pick a number from 1 to 3") - continue + var input_int := int(input) + if input_int < 1 or input_int > 3: + print("Please pick a number from 1 to 3") + continue - if input_int + total > target: - print("Please do not exceed a total of %d" % target) - continue + if input_int + total > target: + print("Please do not exceed a total of %d" % target) + continue - return input_int + return input_int - # This is required since Godot does not detect the unreachable code path - OS.crash("unreachable") - return 0 + # This is required since Godot does not detect the unreachable code path + OS.crash("unreachable") + return 0 func get_computer_choice(total: int) -> int: - # This can be shortened using max() if you do not have type checking OCD - var remaining: int = target - total - return randi_range(1, 3 if remaining > 3 else remaining) + # This can be shortened using max() if you do not have type checking OCD + var remaining: int = target - total + return randi_range(1, 3 if remaining > 3 else remaining) func play() -> void: - print("""\ + print("""\ Welcome to the 21 game. Type quit to exit.""") - var total: int = 0 - var player: Player - match randi_range(1, 2): - 1: - player = Player.Human - print("You will go first.") - 2: - player = Player.Computer - print("The computer will go first.") + var total: int = 0 + var player: Player + match randi_range(1, 2): + 1: + player = Player.Human + print("You will go first.") + 2: + player = Player.Computer + print("The computer will go first.") - while true: - print("\nThe total is %d" % total) + while true: + print("\nThe total is %d" % total) - var choice: int - match player: - Player.Human: - choice = get_player_choice(total) - if choice == -1: - return - Player.Computer: - choice = get_computer_choice(total) - print("The computer plays %d" % choice) - assert(1 <= choice and choice <= 3) + var choice: int + match player: + Player.Human: + choice = get_player_choice(total) + if choice == -1: + return + Player.Computer: + choice = get_computer_choice(total) + print("The computer plays %d" % choice) + assert(1 <= choice and choice <= 3) - total += choice - if total == target: - match player: - Player.Human: print("You win!") - Player.Computer: print("The computer won, you lose.") - return - assert(total < target) + total += choice + if total == target: + match player: + Player.Human: print("You win!") + Player.Computer: print("The computer won, you lose.") + return + assert(total < target) - match player: - Player.Human: player = Player.Computer - Player.Computer: player = Player.Human + match player: + Player.Human: player = Player.Computer + Player.Computer: player = Player.Human func _process(_delta: float) -> bool: - randomize() - play() - return true + randomize() + play() + return true diff --git a/Task/21-game/J/21-game.j b/Task/21-game/J/21-game.j index 821237993a..04b5ac792e 100644 --- a/Task/21-game/J/21-game.j +++ b/Task/21-game/J/21-game.j @@ -1,37 +1,32 @@ -g21=: summarize@play@setup ::('g21: error termination'"_) +g21=: summarize@play@setup ::'g21: error termination' -NB. non-verb must be defined before use, otherwise are assumed verbs. -Until=: 2 :'u^:(0-:v)^:_' +Until=: {{u^:(0-:v)^:_}} -t=: 'score turn choice' -(t)=: i. # ;: t -empty erase't' - -Fetch=: &{ -Alter=: } +'score turn choice'=: 0 1 2 play=: move Until done -done=: 21 <: score Fetch -move=: [: update you`it@.(turn Fetch) +move=: [: update you`it@.(turn&{) +done=: 21 <: score&{ + update=: swap@display@add -add=: score Alter~ (score Fetch + choice Fetch) -display=: [ ([: echo 'sum: {}' format~ score Fetch) -swap=: turn Alter~ ([: -. turn Fetch) +add=: score}~ score&{ + choice&{ +display=: [ 'sum: {}' echo@format~ score&{ +swap=: turn}~ [: -. turn&{ -it=: ([ [: echo 'It chose {}.' format~ choice Fetch)@(choice Alter~ cb) -cb=: (1:`r`3:`2:)@.(4 | score Fetch) NB. computer brain -r=: 3 :'>:?3' +it=: ([ 'It chose {}.' echo@format~ choice&{)@(choice}~ cb) +cb=: 1:`(>:@?@3)`3:`2:@.(4 | score&{) NB. computer brain you=: qio1@check@acquire@prompt -prompt=: [ ([: echo 'your choice?'"_) -acquire=: choice Alter~ ('123' i. 0 { ' ' ,~ read) -check=: (choice Alter~ (665 - score Fetch))@([ ([: echo 'g21: early termination'"_))^:(3 = choice Fetch) -qio1=: choice Alter~ ([: >: choice Fetch) +prompt=: [ echo@'your choice?' +acquire=: choice}~'123'i.0{' ',~read +check=: (choice}~ 665 - score&{)@([ echo@'g21: early termination')^:(3 = choice&{) +qio1=: choice}~ ([: >: choice&{) -setup=: ([ [: echo 'On your turn enter 1 2 or 3, other entries exit'"_)@((3 :'?2') turn Alter ])@0 0 0"_ NB. choose first player randomly -summarize=: ' won' ,~ (];._2 'it you ') {~ turn Fetch +setup=: ([ echo@'On your turn enter 1 2 or 3, other entries exit')@(?@2 turn} ])@0 0 0 NB. choose first player randomly -read=: 1!:1@:1: -write=: 1!:2 4: NB. unused -format=: ''&$: :([: ; (a: , [: ":&.> [) ,. '{}' ([ (E. <@}.;._1 ]) ,) ]) +summarize=: ' won',~ ];._2@'it you '{~turn&{ + +read=: 1!:1@1 +write=: 1!:2&4 NB. unused +format=: ''&$: : ([: ; (a: , [: ":&.> [) ,. '{}' ([ (E. <@}.;._1 ]) ,) ]) diff --git a/Task/21-game/Julia/21-game.julia b/Task/21-game/Julia/21-game.jl similarity index 100% rename from Task/21-game/Julia/21-game.julia rename to Task/21-game/Julia/21-game.jl diff --git a/Task/21-game/Python/21-game-1.py b/Task/21-game/Python/21-game-1.py index 61db2b29a5..fa4bcbcfdc 100644 --- a/Task/21-game/Python/21-game-1.py +++ b/Task/21-game/Python/21-game-1.py @@ -1,62 +1,62 @@ from random import randint def start(): - game_count=0 - print("Enter q to quit at any time.\nThe computer will choose first.\nRunning total is now {}".format(game_count)) - roundno=1 - while game_count<21: - print("\nROUND {}: \n".format(roundno)) - t = select_count(game_count) - game_count = game_count+t - print("Running total is now {}\n".format(game_count)) - if game_count>=21: - print("So, commiserations, the computer has won!") - return 0 - t = request_count() - if not t: - print('OK,quitting the game') - return -1 - game_count = game_count+t - print("Running total is now {}\n".format(game_count)) - if game_count>=21: - print("So, congratulations, you've won!") - return 1 - roundno+=1 + game_count=0 + print("Enter q to quit at any time.\nThe computer will choose first.\nRunning total is now {}".format(game_count)) + roundno=1 + while game_count<21: + print("\nROUND {}: \n".format(roundno)) + t = select_count(game_count) + game_count = game_count+t + print("Running total is now {}\n".format(game_count)) + if game_count>=21: + print("So, commiserations, the computer has won!") + return 0 + t = request_count() + if not t: + print('OK,quitting the game') + return -1 + game_count = game_count+t + print("Running total is now {}\n".format(game_count)) + if game_count>=21: + print("So, congratulations, you've won!") + return 1 + roundno+=1 def select_count(game_count): - '''selects a random number if the game_count is less than 18. otherwise chooses the winning number''' - if game_count<18: - t= randint(1,3) - else: - t = 21-game_count - print("The computer chooses {}".format(t)) - return t + '''selects a random number if the game_count is less than 18. otherwise chooses the winning number''' + if game_count<18: + t= randint(1,3) + else: + t = 21-game_count + print("The computer chooses {}".format(t)) + return t def request_count(): - '''request user input between 1,2 and 3. It will continue till either quit(q) or one of those numbers is requested.''' - t="" - while True: - try: - t = raw_input('Your choice 1 to 3 :') - if int(t) in [1,2,3]: - return int(t) - else: - print("Out of range, try again") - except: - if t=="q": - return None - else: - print("Invalid Entry, try again") + '''request user input between 1,2 and 3. It will continue till either quit(q) or one of those numbers is requested.''' + t="" + while True: + try: + t = raw_input('Your choice 1 to 3 :') + if int(t) in [1,2,3]: + return int(t) + else: + print("Out of range, try again") + except: + if t=="q": + return None + else: + print("Invalid Entry, try again") c=0 m=0 r=True while r: - o = start() - if o==-1: - break - else: - c+=1 if o==0 else 0 - m+=1 if o==1 else 0 - print("Computer wins {0} game, human wins {1} games".format(c,m)) - t = raw_input("Another game?(press y to continue):") - r = (t=="y") + o = start() + if o==-1: + break + else: + c+=1 if o==0 else 0 + m+=1 if o==1 else 0 + print("Computer wins {0} game, human wins {1} games".format(c,m)) + t = raw_input("Another game?(press y to continue):") + r = (t=="y") diff --git a/Task/21-game/Rebol/21-game.rebol b/Task/21-game/Rebol/21-game.rebol new file mode 100644 index 0000000000..03fa84803d --- /dev/null +++ b/Task/21-game/Rebol/21-game.rebol @@ -0,0 +1,26 @@ +Rebol [ + title: "Rosetta code: 21 game" + file: %21_game.r3 + url: https://rosettacode.org/wiki/21_game +] + +game-21: function[][ + total: 0 + human?: true + while [total <> 21][ + either human? [ + n: ask "Enter a number between 1 and 3 (CTRL+C to quit): " + if none? n [quit] + unless parse n [#"1" | #"2" | #"3"][ continue ] + n: to integer! n + ][ ;computer + if 3 < n: 21 - total [ n: random 3 ] + print ["Computer picks:" as-yellow n] + ] + total: total + n + print ["Total:" as-green total] + human?: not human? + ] + print as-green pick ["Computer wins!" "You win!"] human? +] +game-21 diff --git a/Task/21-game/Ring/21-game.ring b/Task/21-game/Ring/21-game.ring index 51094dea5e..06bcf1934e 100644 --- a/Task/21-game/Ring/21-game.ring +++ b/Task/21-game/Ring/21-game.ring @@ -100,9 +100,9 @@ func choose(ch,ym) ok func msgBox(text) { - m = new qMessageBox(win1) { - setWindowTitle("21 Game") - setText(text) - show() - } + m = new qMessageBox(win1) { + setWindowTitle("21 Game") + setText(text) + show() + } } diff --git a/Task/21-game/Rust/21-game.rust b/Task/21-game/Rust/21-game.rs similarity index 100% rename from Task/21-game/Rust/21-game.rust rename to Task/21-game/Rust/21-game.rs diff --git a/Task/21-game/Uiua/21-game.uiua b/Task/21-game/Uiua/21-game.uiua new file mode 100644 index 0000000000..8f17d8a5d9 --- /dev/null +++ b/Task/21-game/Uiua/21-game.uiua @@ -0,0 +1,6 @@ +T ← 21 +P ← &p$"_ played: _\tTotal: _" +Play‼ ← ⍥(&p$"_ won." ^0)⊸=T⊸P ^0 ⟜+ ^1 +Computer ← Play‼"Computer" ⍥+₁⊸=0◿4⊸˜-T # Aim for Rem mod 4 = 0 +Random ← Play‼"Random"+1⌊×3⚂ # Random play. +◌⍢(⍥Computer⊸ 21: + recur() + val + else: recur() diff --git a/Task/24-game-Solve/Ada/24-game-solve.adb b/Task/24-game-Solve/Ada/24-game-solve.adb new file mode 100644 index 0000000000..2494b4e14f --- /dev/null +++ b/Task/24-game-Solve/Ada/24-game-solve.adb @@ -0,0 +1,245 @@ +with Ada.Text_IO; use Ada.Text_IO; + +procedure Game24_Solver is + subtype Index is Positive range 1 .. 4; + subtype Digit is Integer range 1 .. 9; + type Digit_Array_Type is array (Index) of Digit; + + Success_Exception : exception; + + Digit_Array : Digit_Array_Type; + + procedure Swap (A, B : Index) is + Tmp : Digit; + begin + if A /= B then + Tmp := Digit_Array (A); + Digit_Array (A) := Digit_Array (B); + Digit_Array (B) := Tmp; + end if; + end Swap; + + procedure Do_Operation_Options is + type Operation_Character is ('+', '-', '*', '/'); + type Operation_Access is + access function (Left, Right : Float) return Float; + type Allowed_Operation_Array_Type is + array (Operation_Character) of Operation_Access; + + function Operation_Character_To_String + (C : in Operation_Character) return String is + begin + case C is + when '+' => + return "+"; + + when '-' => + return "-"; + + when '*' => + return "*"; + + when '/' => + return "/"; + end case; + end Operation_Character_To_String; + + function Add_Floats (Left, Right : Float) return Float is + begin + return Left + Right; + end Add_Floats; + + function Subtract_Floats (Left, Right : Float) return Float is + begin + return Left - Right; + end Subtract_Floats; + + function Multiply_Floats (Left, Right : Float) return Float is + begin + return Left * Right; + end Multiply_Floats; + + function Divide_Floats (Left, Right : Float) return Float is + begin + return Left / Right; + end Divide_Floats; + + Allowed_Operation_Array : constant Allowed_Operation_Array_Type := + ('+' => Add_Floats'Access, + '-' => Subtract_Floats'Access, + '*' => Multiply_Floats'Access, + '/' => Divide_Floats'Access); + + A : Digit renames Digit_Array (1); + B : Digit renames Digit_Array (2); + C : Digit renames Digit_Array (3); + D : Digit renames Digit_Array (4); + begin + for Op1 in Operation_Character loop + for Op2 in Operation_Character loop + for Op3 in Operation_Character loop + if (Allowed_Operation_Array (Op3) + (Allowed_Operation_Array (Op2) + (Allowed_Operation_Array (Op1) (Float (A), Float (B)), + Float (C)), + Float (D))) + = 24.0 + then + Put_Line + ("((" + & Digit'Image (A) + & " " + & Operation_Character_To_String (Op1) + & " " + & Digit'Image (B) + & ") " + & Operation_Character_To_String (Op2) + & " " + & Digit'Image (C) + & ") " + & Operation_Character_To_String (Op3) + & " " + & Digit'Image (D)); + raise Success_Exception; + end if; + if (Allowed_Operation_Array (Op2) + (Allowed_Operation_Array (Op1) (Float (A), Float (B)), + Allowed_Operation_Array (Op3) (Float (C), Float (D)))) + = 24.0 + then + Put_Line + ("(" + & Digit'Image (A) + & " " + & Operation_Character_To_String (Op1) + & " " + & Digit'Image (B) + & ") " + & Operation_Character_To_String (Op2) + & " (" + & Digit'Image (C) + & " " + & Operation_Character_To_String (Op3) + & " " + & Digit'Image (D) + & ")"); + raise Success_Exception; + end if; + if (Allowed_Operation_Array (Op1) + (Float (A), + Allowed_Operation_Array (Op2) + (Float (B), + Allowed_Operation_Array (Op3) + (Float (C), Float (D))))) + = 24.0 + then + Put_Line + (Digit'Image (A) + & " " + & Operation_Character_To_String (Op1) + & " (" + & Digit'Image (B) + & " " + & Operation_Character_To_String (Op2) + & " (" + & Digit'Image (C) + & " " + & Operation_Character_To_String (Op3) + & " " + & Digit'Image (D) + & "))"); + raise Success_Exception; + end if; + if (Allowed_Operation_Array (Op1) + (Float (A), + Allowed_Operation_Array (Op3) + (Allowed_Operation_Array (Op2) (Float (B), Float (C)), + Float (D)))) + = 24.0 + then + Put_Line + (Digit'Image (A) + & " " + & Operation_Character_To_String (Op1) + & " ((" + & Digit'Image (B) + & " " + & Operation_Character_To_String (Op2) + & " " + & Digit'Image (C) + & ") " + & Operation_Character_To_String (Op3) + & " " + & Digit'Image (D) + & ")"); + raise Success_Exception; + end if; + if (Allowed_Operation_Array (Op3) + (Allowed_Operation_Array (Op1) + (Float (A), + Allowed_Operation_Array (Op2) (Float (B), Float (C))), + Float (D))) + = 24.0 + then + Put_Line + ("(" + & Digit'Image (A) + & " " + & Operation_Character_To_String (Op1) + & " (" + & Digit'Image (B) + & " " + & Operation_Character_To_String (Op2) + & " " + & Digit'Image (C) + & ")) " + & Operation_Character_To_String (Op3) + & " " + & Digit'Image (D)); + raise Success_Exception; + end if; + end loop; + end loop; + end loop; + end Do_Operation_Options; + + procedure Do_Permutations (Start_Index : Index := Index'First) is + begin + if Start_Index = Index'Last then + Do_Operation_Options; + return; + end if; + + for I in Start_Index .. Index'Last loop + Swap (Start_Index, I); + Do_Permutations (Start_Index + 1); + Swap (Start_Index, I); + end loop; + end Do_Permutations; +begin + Put ("Enter 4 digits: "); + declare + Zero_Pos : constant Integer := Character'Pos ('0'); + Input : String := Get_Line; + begin + if Input'Length = 4 then + for I in Index'Range loop + if Input (I) in '1' .. '9' then + Digit_Array (I) := Character'Pos (Input (I)) - Zero_Pos; + else + Put_Line + ("Invalid input: all characters must be non-zero digits"); + return; + end if; + end loop; + else + Put_Line ("Invalid input: it must have length of 4"); + return; + end if; + end; + Do_Permutations; + Put_Line ("Solution not found"); +exception + when Success_Exception => + null; +end Game24_Solver; diff --git a/Task/24-game-Solve/COBOL/24-game-solve.cobol b/Task/24-game-Solve/COBOL/24-game-solve.cob similarity index 100% rename from Task/24-game-Solve/COBOL/24-game-solve.cobol rename to Task/24-game-Solve/COBOL/24-game-solve.cob diff --git a/Task/24-game-Solve/Dart/24-game-solve.dart b/Task/24-game-Solve/Dart/24-game-solve.dart new file mode 100644 index 0000000000..38d41aaba9 --- /dev/null +++ b/Task/24-game-Solve/Dart/24-game-solve.dart @@ -0,0 +1,226 @@ +enum Operator { + Sub, + Plus, + Mul, + Div +} + +class Factor { + String content; + int value; + + Factor({this.content, this.value}); + + Factor copyWith({String content, int value}) { + return Factor( + content: content ?? this.content, + value: value ?? this.value + ); + } +} + +List apply(Operator op, List left, List right) { + List ret = []; + for (var l in left) { + for (var r in right) { + switch (op) { + case Operator.Sub: + if (l.value > r.value) { + ret.add(Factor( + content: "(${l.content} - ${r.content})", + value: l.value - r.value + )); + } + break; + case Operator.Plus: + ret.add(Factor( + content: "(${l.content} + ${r.content})", + value: l.value + r.value + )); + break; + case Operator.Mul: + ret.add(Factor( + content: "(${l.content} × ${r.content})", + value: l.value * r.value + )); + break; + case Operator.Div: + if (l.value >= r.value && r.value > 0 && l.value % r.value == 0) { + ret.add(Factor( + content: "(${l.content} / ${r.content})", + value: l.value ~/ r.value + )); + } + break; + } + } + } + return ret; +} + +List calc(List op, List numbers) { + List _calc(List op, List numbers, List acc) { + if (op.isEmpty) { + return List.from(acc); + } + + List ret = []; + var monoFactor = [Factor( + content: numbers[0].toString(), + value: numbers[0], + )]; + + switch (op[0]) { + case Operator.Mul: + ret.addAll(apply(op[0], acc, monoFactor)); + break; + case Operator.Div: + ret.addAll(apply(op[0], acc, monoFactor)); + ret.addAll(apply(op[0], monoFactor, acc)); + break; + case Operator.Sub: + ret.addAll(apply(op[0], acc, monoFactor)); + ret.addAll(apply(op[0], monoFactor, acc)); + break; + case Operator.Plus: + ret.addAll(apply(op[0], acc, monoFactor)); + break; + } + + return _calc( + op.sublist(1), + numbers.sublist(1), + ret + ); + } + + return _calc( + op, + numbers.sublist(1), + [Factor(content: numbers[0].toString(), value: numbers[0])] + ); +} + +List solutions(List numbers) { + List ret = []; + Set hashSet = {}; + + for (var ops in OpIter()) { + for (var order in orders()) { + var orderedNumbers = applyOrder(numbers, order); + var results = calc(ops, orderedNumbers); + + for (var factor in results) { + if (factor.value == 24 && !hashSet.contains(factor.content)) { + hashSet.add(factor.content); + ret.add(factor); + } + } + } + } + + return ret; +} + +class OpIter extends Iterable> { + @override + Iterator> get iterator => _OpIterator(); +} + +class _OpIterator implements Iterator> { + int _index = 0; + static const List OPTIONS = [ + Operator.Mul, + Operator.Sub, + Operator.Plus, + Operator.Div + ]; + + @override + List get current { + final f1 = OPTIONS[(_index & (3 << 4)) >> 4]; + final f2 = OPTIONS[(_index & (3 << 2)) >> 2]; + final f3 = OPTIONS[(_index & 3)]; + return [f1, f2, f3]; + } + + @override + bool moveNext() { + if (_index >= 1 << 6) { + return false; + } + _index++; + return true; + } +} + +List> orders() { + return [ + [0, 1, 2, 3], + [0, 1, 3, 2], + [0, 2, 1, 3], + [0, 2, 3, 1], + [0, 3, 1, 2], + [0, 3, 2, 1], + [1, 0, 2, 3], + [1, 0, 3, 2], + [1, 2, 0, 3], + [1, 2, 3, 0], + [1, 3, 0, 2], + [1, 3, 2, 0], + [2, 0, 1, 3], + [2, 0, 3, 1], + [2, 1, 0, 3], + [2, 1, 3, 0], + [2, 3, 0, 1], + [2, 3, 1, 0], + [3, 0, 1, 2], + [3, 0, 2, 1], + [3, 1, 0, 2], + [3, 1, 2, 0], + [3, 2, 0, 1], + [3, 2, 1, 0] + ]; +} + +List applyOrder(List numbers, List order) { + return [ + numbers[order[0]], + numbers[order[1]], + numbers[order[2]], + numbers[order[3]] + ]; +} + +void main(List args) { + List numbers = []; + + if (args.isNotEmpty) { + String input = args[0]; + for (var char in input.split('')) { + int n = int.tryParse(char); + if (n != null) { + numbers.add(n); + } + + if (numbers.length == 4) { + var sols = solutions(numbers); + var len = sols.length; + + if (len == 0) { + print('no solution for ${numbers[0]}, ${numbers[1]}, ${numbers[2]}, ${numbers[3]}'); + return; + } + + print('solutions for ${numbers[0]}, ${numbers[1]}, ${numbers[2]}, ${numbers[3]}'); + for (var s in sols) { + print(s.content); + } + print('$len solutions found'); + return; + } + } + } else { + print('empty input'); + } +} diff --git a/Task/24-game-Solve/Elixir/24-game-solve.elixir b/Task/24-game-Solve/Elixir/24-game-solve.ex similarity index 100% rename from Task/24-game-Solve/Elixir/24-game-solve.elixir rename to Task/24-game-Solve/Elixir/24-game-solve.ex diff --git a/Task/24-game-Solve/Fortran/24-game-solve-3.f b/Task/24-game-Solve/Fortran/24-game-solve-3.f new file mode 100644 index 0000000000..c3f0095d7a --- /dev/null +++ b/Task/24-game-Solve/Fortran/24-game-solve-3.f @@ -0,0 +1,481 @@ +module game24_module + use omp_lib + use iso_fortran_env, only: int64 + implicit none + ! Define constants + integer, parameter :: max_limit = 8 ! Maximum allowed value for the number of inputs + integer, parameter :: expr_len = 200 ! Maximum length for expressions + + ! Precomputed total calls for n=6,7,8 + integer(int64), parameter :: total_calls_n6 = 20000000_int64 + integer(int64), parameter :: total_calls_n7 = 2648275200_int64 + integer(int64), parameter :: total_calls_n8 = 444557593600_int64 + + !----------------------- Progress Indicator Variables --------------------- + integer(int64) :: total_calls = 0 ! Total number of recursive calls + integer(int64) :: completed_calls = 0 ! Number of completed recursive calls + integer :: last_percentage = -1 ! Last percentage reported + integer, parameter :: progress_bar_width = 50 ! Width of the progress bar + character(len=1) :: carriage_return = char(13) ! Carriage return character + logical :: show_progress = .false. ! Flag to show progress bar + !-------------------------------------------------------------------------- +contains + + !----------------------------------------------------------------------- + ! ! Aborted function: calculate_total_calls + ! ! Description: + ! ! Estimates the total number of recursive calls for a given n, + ! ! considering commutativity (addition and multiplication). + ! ! Arguments: + ! ! n: The number of input numbers. + ! ! Returns: + ! ! The estimated total number of recursive calls as an integer. + ! !----------------------------------------------------------------------- + ! integer function calculate_total_calls(n) + ! implicit none + ! integer, intent(in) :: n + ! integer :: k + ! calculate_total_calls = 1 + ! do k = 2, n + ! ! For each pair, there are 6 possible operations: + ! ! 1 addition, 1 multiplication (commutative) + ! ! 2 subtraction, 2 division (non-commutative) + ! calculate_total_calls = calculate_total_calls * ((k * (k - 1)) / 2) * 6 + ! end do + ! end function calculate_total_calls + + !----------------------------------------------------------------------- + ! Subroutine: convert_to_number + ! Description: + ! Converts user input (numbers or card values) into numeric values. + ! Handles card values such as 'A', 'J', 'Q', 'K' and converts them into + ! corresponding numbers (A=1, J=11, Q=12, K=13). + ! Arguments: + ! input_str: Input string representing the number or card. + ! number: Output real number after conversion. + ! ios: I/O status indicator (0 for success, non-zero for error). + !----------------------------------------------------------------------- + subroutine convert_to_number(input_str, number, ios) + implicit none + character(len=*), intent(in) :: input_str + real, intent(out) :: number + integer, intent(out) :: ios + character(len=1) :: first_char + real :: temp_number + + ios = 0 ! Reset the I/O status to 0 (valid input by default) + first_char = input_str(1:1) + + select case (first_char) + case ('A', 'a') + number = 1.0 + case ('J', 'j') + number = 11.0 + case ('Q', 'q') + number = 12.0 + case ('K', 'k') + number = 13.0 + case default + read (input_str, *, iostat=ios) temp_number ! Attempt to read a real number + + ! If input is not a valid real number or is not an integer, set ios to 1 + if (ios /= 0 .or. mod(temp_number, 1.0) /= 0.0) then + ios = 1 ! Invalid input + else + number = temp_number ! Valid integer input + end if + end select + end subroutine convert_to_number + + !----------------------------------------------------------------------- + ! Subroutine: remove_decimal_zeros + ! Description: + ! Removes trailing zeros after the decimal point from a string. + ! Arguments: + ! str: Input string that may contain trailing zeros. + ! result: Output string with trailing zeros removed. + !----------------------------------------------------------------------- + subroutine remove_decimal_zeros(str, result) + implicit none + character(len=*), intent(in) :: str ! Input: String to remove zeros from + character(len=*), intent(out) :: result ! Output: String without trailing zeros + integer :: i, len_str ! Loop counter and string length + + len_str = len_trim(str) + result = adjustl(str(1:len_str)) + + ! Find the position of the decimal point + i = index(result, '.') + + ! If there's a decimal point, remove trailing zeros + if (i > 0) then + do while (len_str > i .and. result(len_str:len_str) == '0') + len_str = len_str - 1 + end do + if (result(len_str:len_str) == '.') len_str = len_str - 1 + result = result(1:len_str) + end if + end subroutine remove_decimal_zeros + + !----------------------------------------------------------------------- + ! Subroutine: create_new_arrays + ! Description: + ! Creates new arrays after performing an operation. + ! Arguments: + ! nums: Input array of numbers. + ! exprs: Input array of expressions. + ! idx1: Index of the first element to remove. + ! idx2: Index of the second element to remove. + ! result: Result of the operation. + ! new_expr: New expression string. + ! new_nums: Output array of numbers with elements removed and result added. + ! new_exprs: Output array of expressions with elements removed and new_expr added. + !----------------------------------------------------------------------- + subroutine create_new_arrays(nums, exprs, idx1, idx2, result, new_expr, new_nums, new_exprs) + implicit none + real, intent(in) :: nums(:) ! Input: Array of numbers + character(len=expr_len), intent(in) :: exprs(:) ! Input: Array of expressions + integer, intent(in) :: idx1, idx2 ! Input: Indices of elements to remove + real, intent(in) :: result ! Input: Result of the operation + character(len=expr_len), intent(in) :: new_expr ! Input: New expression + real, allocatable, intent(out) :: new_nums(:) ! Output: New array of numbers + character(len=expr_len), allocatable, intent(out) :: new_exprs(:) ! Output: New array of expressions + integer :: i, j, n ! Loop counters and size of input arrays + + n = size(nums) + allocate (new_nums(n - 1)) + allocate (new_exprs(n - 1)) + + j = 0 + do i = 1, n + if (i /= idx1 .and. i /= idx2) then + j = j + 1 + new_nums(j) = nums(i) + new_exprs(j) = exprs(i) + end if + end do + + ! Add the result of the operation to the new arrays + new_nums(n - 1) = result + new_exprs(n - 1) = new_expr + end subroutine create_new_arrays + + !----------------------------------------------------------------------- + ! Subroutine: update_progress_bar + ! Description: + ! Updates and displays the horizontal percentage-based progress bar. + ! Arguments: + ! None + !----------------------------------------------------------------------- + subroutine update_progress_bar() + implicit none + real :: percentage + integer :: filled_length + character(len=progress_bar_width) :: bar + integer :: int_percentage + + if (total_calls == 0 .or. .not. show_progress) return ! Avoid division by zero and check the flag + + percentage = real(completed_calls) / real(total_calls) * 100.0 + + ! Ensure percentage does not exceed 100% + if (percentage > 100.0) percentage = 100.0 + + ! Calculate integer percentage + int_percentage = int(percentage) + + ! Update progress bar only when percentage increases by at least 1% + if (int_percentage > last_percentage) then + last_percentage = int_percentage + + ! Calculate the filled length of the progress bar + filled_length = min(int(percentage / 100.0 * progress_bar_width), progress_bar_width) + + ! Construct the progress bar string + bar = repeat('=', filled_length) + if (filled_length < progress_bar_width) then + bar = bar//'>'//repeat(' ', progress_bar_width - filled_length - 1) + end if + + ! Print the progress bar and integer percentage + write (*, '(A, F4.1, A)', advance='no') carriage_return//'['//bar//'] ', percentage, '%' + call flush (0) ! Ensure output is displayed immediately + end if + end subroutine update_progress_bar + + !----------------------------------------------------------------------- + ! Recursive Subroutine: solve_24 + ! Description: + ! Recursively solves the 24 game by trying all possible operations. + ! Utilizes OpenMP tasks for parallelization. + ! Arguments: + ! nums: Array of numbers to use in the game. + ! exprs: Array of string expressions representing the numbers. + ! found: Logical flag indicating if a solution has been found. + !----------------------------------------------------------------------- + recursive subroutine solve_24(nums, exprs, found) + use omp_lib + implicit none + real, intent(in) :: nums(:) ! Input: Array of numbers + character(len=expr_len), intent(in) :: exprs(:) ! Input: Array of expressions + logical, intent(inout) :: found ! Input/Output: Flag indicating if a solution is found + integer :: n ! Size of the input arrays + integer :: i, j, op ! Loop counters + real :: a, b, result ! Temporary variables for calculations + real, allocatable :: new_nums(:) ! Temp array to store numbers after an operation + character(len=expr_len), allocatable :: new_exprs(:) ! Temp array to store expressions after an operation + character(len=expr_len) :: expr_a, expr_b, new_expr ! Temp variables for expressions + + n = size(nums) + + ! Increment the completed_calls counter and update progress bar + if (show_progress) then + !$omp atomic + completed_calls = completed_calls + 1 + call update_progress_bar() + end if + + ! If a solution is found, return + if (found) return + + ! Base case: If only one number is left, check if it is 24 + if (n == 1) then + if (abs(nums(1) - 24.0) < 1e-4) then + if (show_progress) then + write (*, '(A, F5.1, A)', advance='no') carriage_return//'['//repeat('=', progress_bar_width)//'] ', 100.0, '%' + write (*, '(A)') '' ! Insert a blank line + end if + !$omp critical + write (*, '(A, A, A, F10.7, A)') 'Solution found:', trim(exprs(1)), '= 24 (', nums(1), ')' + found = .true. + !$omp end critical + end if + return + end if + + ! Iterate over all pairs of numbers + do i = 1, n - 1 + do j = i + 1, n + a = nums(i) + b = nums(j) + expr_a = exprs(i) + expr_b = exprs(j) + + ! Iterate over all operators + do op = 1, 4 + ! Avoid division by zero + if ((op == 4 .and. abs(b) < 1e-6)) cycle + + ! Perform the operation and create the new expression + select case (op) + case (1) + result = a + b + new_expr = '('//trim(expr_a)//'+'//trim(expr_b)//')' + case (2) + result = a - b + new_expr = '('//trim(expr_a)//'-'//trim(expr_b)//')' + case (3) + result = a * b + new_expr = '('//trim(expr_a)//'*'//trim(expr_b)//')' + case (4) + result = a / b + new_expr = '('//trim(expr_a)//'/'//trim(expr_b)//')' + end select + + ! Create new arrays with the selected numbers removed + call create_new_arrays(nums, exprs, i, j, result, new_expr, new_nums, new_exprs) + + ! For the first few recursion levels, create parallel tasks + if (n >= 6 .and. omp_get_level() < 2) then + !$omp task shared(found) firstprivate(new_nums, new_exprs) + call solve_24(new_nums, new_exprs, found) + !$omp end task + else + call solve_24(new_nums, new_exprs, found) + end if + + ! If a solution is found, deallocate memory and return + if (found) then + deallocate (new_nums) + deallocate (new_exprs) + return + end if + + ! Handle commutative operations only once + if (op == 1 .or. op == 3) cycle + + ! Swap operands for subtraction and division + if (op == 2 .or. op == 4) then + if (op == 4 .and. abs(a) < 1e-6) cycle ! Avoid division by zero + + select case (op) + case (2) + result = b - a + new_expr = '('//trim(expr_b)//'-'//trim(expr_a)//')' + case (4) + result = b / a + new_expr = '('//trim(expr_b)//'/'//trim(expr_a)//')' + end select + + ! Create new arrays with the selected numbers removed + call create_new_arrays(nums, exprs, i, j, result, new_expr, new_nums, new_exprs) + + ! For the first few recursion levels, create parallel tasks + if (n >= 6 .and. omp_get_level() < 2) then + !$omp task shared(found) firstprivate(new_nums, new_exprs) + call solve_24(new_nums, new_exprs, found) + !$omp end task + else + ! Recursively call the solve_24 function with the new arrays + call solve_24(new_nums, new_exprs, found) + end if + + ! If a solution is found, deallocate memory and return + if (found) then + deallocate (new_nums) + deallocate (new_exprs) + return + end if + end if + + end do ! End of operator loop + end do ! End of j loop + end do ! End of i loop + end subroutine solve_24 + +end module game24_module + +program game24 + use game24_module + implicit none + + ! Declare variables + integer :: maxn ! Number of numbers to be entered by the user + real, allocatable :: numbers(:) ! Array to store the numbers entered by the user + character(len=expr_len), allocatable :: expressions(:) ! Array to store the expressions + integer :: i, ios ! Loop counter and I/O status + logical :: found_solution ! Flag to indicate if a solution was found + character(len=10) :: user_input ! Variable to store user input + character(len=1) :: play_again ! Variable to store the user's decision + + do ! Game loop to allow restarting the game + + ! Prompt the user for the number of numbers to use in the game + do + write (*, '(A,I0,A)', advance='no') 'Enter the number of numbers (1 to ', max_limit, '): ' + read (*, *, iostat=ios) maxn + + ! Check if the input is valid + if (ios /= 0) then + write (*, '(A,I0,A)') 'Invalid input. Please enter an integer between 1 and ', max_limit, '.' + cycle + end if + + ! Validate the input: Ensure the number of numbers is within the valid range + if (maxn < 1 .or. maxn > max_limit) then + write (*, '(A,I0,A)') 'Error: Number of numbers must be between 1 and ', max_limit, '. Try again.' + cycle + end if + + exit ! Exit loop if the input is valid + end do + + ! Allocate memory for the arrays based on the number of numbers + allocate (numbers(maxn)) + allocate (expressions(maxn)) + + ! Prompt the user to enter the numbers or card values + write (*, '(A,I0,A)') 'Enter ', maxn, ' numbers or card values (A=1, J=11, Q=12, K=13).' + do i = 1, maxn + do + ! Prompt the user to enter a number or card value + write (*, '(A,I0,A)', advance='no') 'Enter value for card ', i, ': ' + read (*, '(A)', iostat=ios) user_input + + ! Check if input is an integer or valid card symbol (A, J, Q, K) + call convert_to_number(user_input, numbers(i), ios) + + ! If the input is valid, exit loop + if (ios == 0) exit + + ! Invalid input: prompt the user to try again + write (*, '(A)') 'Invalid input. Please enter an integer or valid card symbol (A, J, Q, K).' + end do + + ! Convert the number to a string expression and remove trailing zeros + write (expressions(i), '(F0.2)') numbers(i) + call remove_decimal_zeros(expressions(i), expressions(i)) + end do + + ! Initialize the solution flag to false + found_solution = .false. + + ! Assign precomputed total_calls based on n + select case (maxn) + case (6) + total_calls = total_calls_n6 + case (7) + total_calls = total_calls_n7 + case (8) + total_calls = total_calls_n8 + case default + total_calls = 0 + end select + + ! Decide whether to show progress bar based on n + if (maxn >= 6) then + show_progress = .true. + completed_calls = 0 + last_percentage = -1 + + ! Initialize progress bar display + write (*, '(A)', advance='no') '['//repeat(' ', progress_bar_width)//'] 0%' + call flush (0) ! Ensure the output is displayed immediately + else + show_progress = .false. + end if + + ! Start parallel region + !$omp parallel + !$omp single nowait + call solve_24(numbers, expressions, found_solution) + !$omp end single + !$omp end parallel + + ! After search completes, ensure the progress bar reaches 100% if shown + if (show_progress .and. .not. found_solution) then + write (*, '(A, A)', advance='no') carriage_return//'['//repeat('=', progress_bar_width)//'] 100% ' + call flush (0) + write (*, '(A)') '' ! Insert a blank line + end if + + ! If a solution was found and progress bar is shown, ensure a blank line + if (show_progress .and. found_solution) then + ! Progress bar already refreshed to 100% and blank line inserted in solve_24 + end if + + ! If no solution was found, print a message + if (.not. found_solution) then + write (*, '(A)') 'No valid solution found.' + end if + + ! Deallocate the memory used by the arrays + deallocate (numbers) + deallocate (expressions) + + ! Ask the user if they want to play again + if (show_progress) then + write (*, '(A)', advance='no') carriage_return//'Play again? (Enter y/n to continue or any other key to exit): ' + else + write (*, '(A)', advance='no') 'Play again? (Enter y/n to continue or any other key to exit): ' + end if + read (*, '(A)') play_again ! Read user input + + ! Check if the user wants to exit + if (play_again /= 'y' .and. play_again /= 'Y') exit + + end do ! End of game loop + + write (*, '(A)') 'Exiting the game...' + +end program game24 diff --git a/Task/24-game-Solve/FreeBASIC/24-game-solve.basic b/Task/24-game-Solve/FreeBASIC/24-game-solve.basic new file mode 100644 index 0000000000..4593f64cb2 --- /dev/null +++ b/Task/24-game-Solve/FreeBASIC/24-game-solve.basic @@ -0,0 +1,124 @@ +Type GameState + digitos(3) As Double + operaciones(2) As String +End Type + +Function randomDigits() As String + Dim As String resultado = "" + For i As Integer = 0 To 3 + resultado &= Str(Int(Rnd * 9) + 1) + Next + Return resultado +End Function + +Function evaluate(digitos() As Double, operaciones() As String) As Double + Dim As Double valor = digitos(0) + + For i As Integer = 0 To 2 + Select Case operaciones(i) + Case "+": valor += digitos(i +1) + Case "-": valor -= digitos(i +1) + Case "*": valor *= digitos(i +1) + Case "/": If digitos(i +1) <> 0 Then valor /= digitos(i +1) + End Select + Next + + Return valor +End Function + +Sub permute(digitos() As Double, soluciones() As GameState, Byref solutionCnt As Integer, k As Integer) + Dim As String*1 opChars(3) = {"+", "-", "*", "/"} + Dim As String ops(2) + Dim As Integer i, j, l, m + + If k = 4 Then + For i = 0 To 3 + ops(0) = opChars(i) + For j = 0 To 3 + ops(1) = opChars(j) + For l = 0 To 3 + ops(2) = opChars(l) + If Abs(evaluate(digitos(), ops()) - 24) < 0.001 Then + With soluciones(solutionCnt) + For m = 0 To 3: .digitos(m) = digitos(m): Next + For m = 0 To 2: .operaciones(m) = ops(m): Next + End With + solutionCnt += 1 + Exit For 'Stop after first solution + End If + Next + If solutionCnt Then Exit For + Next + If solutionCnt Then Exit For + Next + Else + For i = k To 3 + Swap digitos(i), digitos(k) + permute(digitos(), soluciones(), solutionCnt, k +1) + If solutionCnt Then Exit For + Swap digitos(k), digitos(i) + Next + End If +End Sub + +' Main program +Randomize Timer +Dim As Integer i +Dim As String cmd +Dim As Double digitos(3) +Dim As String operaciones(2) + +Do + Cls + Print "24 Game" + Print "Generating 4 digitos..." + + Dim As String inputDigits = randomDigits() + Print "Make 24 using these digitos: "; + For i = 1 To Len(inputDigits) + Print Mid(inputDigits, i, 1); " "; + Next + Print + + Line Input "Enter your expression (e.g. 4+5*3-2): ", cmd + + Dim As Integer digitCnt = 0, opCnt = 0 + ' Parse user input + For i = 1 To Len(cmd) + Select Case Mid(cmd, i, 1) + Case "1" To "9" + digitos(digitCnt) = Val(Mid(cmd, i, 1)) + digitCnt += 1 + Case "+", "-", "*", "/" + operaciones(opCnt) = Mid(cmd, i, 1) + opCnt += 1 + End Select + Next + + Dim As Double resultado = evaluate(digitos(), operaciones()) + Print "Your resultado: "; resultado + + If Abs(resultado - 24) < 0.001 Then + Print !"\nCongratulations, you found a solution!" + Else + Print !"\nThe valor of your expression is "; resultado; " instead of 24!" + + Dim As GameState soluciones(1000) + Dim As Integer solucCnt = 0 + + permute(digitos(), soluciones(), solucCnt, 0) + + If solucCnt > 0 Then + Print !"\nA possible solution could have been: "; + With soluciones(0) + Print .digitos(0) & .operaciones(0) & .digitos(1) & .operaciones(1) & .digitos(2) & .operaciones(2) & .digitos(3) + End With + Else + Print !"\nThere was no known solution for these digitos." + End If + End If + + Print !"\nDo you want to try again? (press N for exit, other key to continue)" +Loop Until (Ucase(Input(1)) = "N") + +Sleep diff --git a/Task/24-game-Solve/FutureBasic/24-game-solve.basic b/Task/24-game-Solve/FutureBasic/24-game-solve.basic index 5a2f9b5cf2..4f6e1c9984 100644 --- a/Task/24-game-Solve/FutureBasic/24-game-solve.basic +++ b/Task/24-game-Solve/FutureBasic/24-game-solve.basic @@ -15,7 +15,6 @@ void local fn eval( t as CFStringRef ) end if end fn - clear local fn work( t as CFStringRef ) Short a, b, c, d, e, f, g CGFloat n(3) @@ -44,7 +43,6 @@ clear local fn work( t as CFStringRef ) next : next : next : next end fn - window 1, @"24 Game", ( 0, 0, 250, 250 ) fn work(@"3388") fn work(@"1346") diff --git a/Task/24-game-Solve/Julia/24-game-solve.julia b/Task/24-game-Solve/Julia/24-game-solve.jl similarity index 100% rename from Task/24-game-Solve/Julia/24-game-solve.julia rename to Task/24-game-Solve/Julia/24-game-solve.jl diff --git a/Task/24-game-Solve/Kotlin/24-game-solve.kotlin b/Task/24-game-Solve/Kotlin/24-game-solve.kts similarity index 100% rename from Task/24-game-Solve/Kotlin/24-game-solve.kotlin rename to Task/24-game-Solve/Kotlin/24-game-solve.kts diff --git a/Task/24-game-Solve/OCaml/24-game-solve.ocaml b/Task/24-game-Solve/OCaml/24-game-solve.ml similarity index 100% rename from Task/24-game-Solve/OCaml/24-game-solve.ocaml rename to Task/24-game-Solve/OCaml/24-game-solve.ml diff --git a/Task/24-game-Solve/Rust/24-game-solve.rust b/Task/24-game-Solve/Rust/24-game-solve.rs similarity index 100% rename from Task/24-game-Solve/Rust/24-game-solve.rust rename to Task/24-game-Solve/Rust/24-game-solve.rs diff --git a/Task/24-game-Solve/Scheme/24-game-solve-1.ss b/Task/24-game-Solve/Scheme/24-game-solve-1.scm similarity index 100% rename from Task/24-game-Solve/Scheme/24-game-solve-1.ss rename to Task/24-game-Solve/Scheme/24-game-solve-1.scm diff --git a/Task/24-game-Solve/Scheme/24-game-solve-2.ss b/Task/24-game-Solve/Scheme/24-game-solve-2.scm similarity index 100% rename from Task/24-game-Solve/Scheme/24-game-solve-2.ss rename to Task/24-game-Solve/Scheme/24-game-solve-2.scm diff --git a/Task/24-game-Solve/Zig/24-game-solve.zig b/Task/24-game-Solve/Zig/24-game-solve.zig new file mode 100644 index 0000000000..1837c9404d --- /dev/null +++ b/Task/24-game-Solve/Zig/24-game-solve.zig @@ -0,0 +1,273 @@ +const std = @import("std"); +const print = std.debug.print; +const ArrayList = std.ArrayList; +const HashMap = std.HashMap; +const Allocator = std.mem.Allocator; + +const Operator = enum { + sub, + plus, + mul, + div, +}; + +const Factor = struct { + content: []const u8, + value: i32, + + fn deinit(self: Factor, allocator: Allocator) void { + allocator.free(self.content); + } +}; + +fn apply(allocator: Allocator, op: Operator, left: []const Factor, right: []const Factor) !ArrayList(Factor) { + var ret = ArrayList(Factor).init(allocator); + + for (left) |l| { + for (right) |r| { + switch (op) { + .sub => { + if (l.value > r.value) { + const content = try std.fmt.allocPrint(allocator, "({s} - {s})", .{ l.content, r.content }); + try ret.append(Factor{ + .content = content, + .value = l.value - r.value, + }); + } + }, + .plus => { + const content = try std.fmt.allocPrint(allocator, "({s} + {s})", .{ l.content, r.content }); + try ret.append(Factor{ + .content = content, + .value = l.value + r.value, + }); + }, + .mul => { + const content = try std.fmt.allocPrint(allocator, "({s} x {s})", .{ l.content, r.content }); + try ret.append(Factor{ + .content = content, + .value = l.value * r.value, + }); + }, + .div => { + if (l.value >= r.value and r.value > 0 and @rem(l.value, r.value) == 0) { + const content = try std.fmt.allocPrint(allocator, "({s} / {s})", .{ l.content, r.content }); + try ret.append(Factor{ + .content = content, + .value = @divTrunc(l.value, r.value), + }); + } + }, + } + } + } + + return ret; +} + +fn calc(allocator: Allocator, ops: [3]Operator, numbers: [4]i32) !ArrayList(Factor) { + var current_factors = ArrayList(Factor).init(allocator); + defer { + for (current_factors.items) |factor| { + factor.deinit(allocator); + } + current_factors.deinit(); + } + + // Initialize with first number + const initial_content = try std.fmt.allocPrint(allocator, "{}", .{numbers[0]}); + try current_factors.append(Factor{ + .content = initial_content, + .value = numbers[0], + }); + + // Process each operation + for (ops, 0..) |op, i| { + var next_factors = ArrayList(Factor).init(allocator); + defer { + for (next_factors.items) |factor| { + factor.deinit(allocator); + } + next_factors.deinit(); + } + + const mono_content = try std.fmt.allocPrint(allocator, "{}", .{numbers[i + 1]}); + defer allocator.free(mono_content); + const mono_factor = Factor{ + .content = mono_content, + .value = numbers[i + 1], + }; + const mono_slice = &[_]Factor{mono_factor}; + + switch (op) { + .mul, .plus => { + var applied = try apply(allocator, op, current_factors.items, mono_slice); + defer applied.deinit(); + try next_factors.appendSlice(applied.items); + }, + .div, .sub => { + var applied1 = try apply(allocator, op, current_factors.items, mono_slice); + defer applied1.deinit(); + try next_factors.appendSlice(applied1.items); + + var applied2 = try apply(allocator, op, mono_slice, current_factors.items); + defer applied2.deinit(); + try next_factors.appendSlice(applied2.items); + }, + } + + // Clear current factors and move next_factors to current_factors + for (current_factors.items) |factor| { + factor.deinit(allocator); + } + current_factors.clearRetainingCapacity(); + + // Move ownership from next_factors to current_factors + try current_factors.appendSlice(next_factors.items); + next_factors.clearRetainingCapacity(); // Don't deinit the items, we moved them + } + + // Create result and transfer ownership + var result = ArrayList(Factor).init(allocator); + try result.appendSlice(current_factors.items); + current_factors.clearRetainingCapacity(); // Don't deinit, we transferred ownership + + return result; +} + +const OpIter = struct { + index: usize, + + const OPTIONS = [_]Operator{ .mul, .sub, .plus, .div }; + + fn init() OpIter { + return OpIter{ .index = 0 }; + } + + fn next(self: *OpIter) ?[3]Operator { + if (self.index >= 64) { + return null; + } + + const f1 = OPTIONS[(self.index & (3 << 4)) >> 4]; + const f2 = OPTIONS[(self.index & (3 << 2)) >> 2]; + const f3 = OPTIONS[(self.index & (3 << 0)) >> 0]; + + self.index += 1; + return [3]Operator{ f1, f2, f3 }; + } +}; + +fn orders() [24][4]usize { + return [24][4]usize{ + [4]usize{ 0, 1, 2, 3 }, + [4]usize{ 0, 1, 3, 2 }, + [4]usize{ 0, 2, 1, 3 }, + [4]usize{ 0, 2, 3, 1 }, + [4]usize{ 0, 3, 1, 2 }, + [4]usize{ 0, 3, 2, 1 }, + [4]usize{ 1, 0, 2, 3 }, + [4]usize{ 1, 0, 3, 2 }, + [4]usize{ 1, 2, 0, 3 }, + [4]usize{ 1, 2, 3, 0 }, + [4]usize{ 1, 3, 0, 2 }, + [4]usize{ 1, 3, 2, 0 }, + [4]usize{ 2, 0, 1, 3 }, + [4]usize{ 2, 0, 3, 1 }, + [4]usize{ 2, 1, 0, 3 }, + [4]usize{ 2, 1, 3, 0 }, + [4]usize{ 2, 3, 0, 1 }, + [4]usize{ 2, 3, 1, 0 }, + [4]usize{ 3, 0, 1, 2 }, + [4]usize{ 3, 0, 2, 1 }, + [4]usize{ 3, 1, 0, 2 }, + [4]usize{ 3, 1, 2, 0 }, + [4]usize{ 3, 2, 0, 1 }, + [4]usize{ 3, 2, 1, 0 }, + }; +} + +fn applyOrder(numbers: [4]i32, order: [4]usize) [4]i32 { + return [4]i32{ numbers[order[0]], numbers[order[1]], numbers[order[2]], numbers[order[3]] }; +} + +fn solutions(allocator: Allocator, numbers: [4]i32) !ArrayList(Factor) { + var ret = ArrayList(Factor).init(allocator); + var hash_set = HashMap([]const u8, void, std.hash_map.StringContext, std.hash_map.default_max_load_percentage).init(allocator); + defer { + // Free all keys in the hash map + var iterator = hash_set.iterator(); + while (iterator.next()) |entry| { + allocator.free(entry.key_ptr.*); + } + hash_set.deinit(); + } + + var op_iter = OpIter.init(); + while (op_iter.next()) |ops| { + const all_orders = orders(); + for (all_orders) |order| { + const reordered_numbers = applyOrder(numbers, order); + var results = calc(allocator, ops, reordered_numbers) catch continue; + defer { + for (results.items) |factor| { + factor.deinit(allocator); + } + results.deinit(); + } + + for (results.items) |factor| { + if (factor.value == 24) { + // Check if we've seen this content before + if (hash_set.contains(factor.content)) { + continue; + } + + // Add to hash set with a duplicated key + const key_copy = try allocator.dupe(u8, factor.content); + try hash_set.put(key_copy, {}); + + // Add to results with a duplicated content + try ret.append(Factor{ + .content = try allocator.dupe(u8, factor.content), + .value = factor.value, + }); + } + } + } + } + + return ret; +} + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + const allocator = gpa.allocator(); + + // Hard-coded input: 5598 + const nums = [4]i32{ 5, 5, 9, 8 }; + + var sols = solutions(allocator, nums) catch { + print("Error computing solutions\n", .{}); + return; + }; + defer { + for (sols.items) |factor| { + factor.deinit(allocator); + } + sols.deinit(); + } + + const len = sols.items.len; + if (len == 0) { + print("no solution for {}, {}, {}, {}\n", .{ nums[0], nums[1], nums[2], nums[3] }); + return; + } + + print("solutions for {}, {}, {}, {}\n", .{ nums[0], nums[1], nums[2], nums[3] }); + for (sols.items) |s| { + print("{s}\n", .{s.content}); + } + print("{} solutions found\n", .{len}); +} diff --git a/Task/24-game/ALGOL-68/24-game.alg b/Task/24-game/ALGOL-68/24-game.alg index 3ba4ed6a03..b74144035a 100644 --- a/Task/24-game/ALGOL-68/24-game.alg +++ b/Task/24-game/ALGOL-68/24-game.alg @@ -40,7 +40,7 @@ BEGIN # play the 24 game - present the user with 4 digits and invite them to # error( "Unexpected """ + curr ch + """" ); 0 FI # factor # ; - PROC term = REAL: + PROC expr term = REAL: BEGIN REAL result := factor; WHILE curr ch = "*" OR curr ch = "/" DO @@ -49,14 +49,14 @@ BEGIN # play the 24 game - present the user with 4 digits and invite them to # IF op = "*" THEN result *:= factor ELSE result /:= factor FI OD; result - END # term # ; + END # expr term # ; PROC expression = REAL: BEGIN - REAL result := term; + REAL result := expr term; WHILE curr ch = "+" OR curr ch = "-" DO CHAR op = curr ch; next ch; - IF op = "+" THEN result +:= term ELSE result -:= term FI + IF op = "+" THEN result +:= expr term ELSE result -:= expr term FI OD; result END # expression # ; @@ -80,7 +80,7 @@ BEGIN # play the 24 game - present the user with 4 digits and invite them to # puzzle digits[ i ] := 0 OD; print( ( "Enter an expression using these digits:" ) ); - FOR i TO 4 DO # pick 4 random digits # + TO 4 DO # pick 4 random digits # INT digit := 1 + ENTIER ( next random * 9 ); IF digit > 9 THEN digit := 9 FI; puzzle digits[ digit ] +:= 1; diff --git a/Task/24-game/Ada/24-game.ada b/Task/24-game/Ada/24-game.adb similarity index 100% rename from Task/24-game/Ada/24-game.ada rename to Task/24-game/Ada/24-game.adb diff --git a/Task/24-game/Arturo/24-game.arturo b/Task/24-game/Arturo/24-game.arturo index a44398760e..0175c79a13 100644 --- a/Task/24-game/Arturo/24-game.arturo +++ b/Task/24-game/Arturo/24-game.arturo @@ -28,11 +28,10 @@ result: 0 while [result<>24][ got: input "Enter an expression to form 24: " blo: to :block got - if? validExpression? blo [ + switch validExpression? blo [ result: do blo print ["The result is:" result] - ] - else [ + ][ print "Invalid expression. Please try again!" ] print "" diff --git a/Task/24-game/AutoIt/24-game.autoit b/Task/24-game/AutoIt/24-game.au3 similarity index 100% rename from Task/24-game/AutoIt/24-game.autoit rename to Task/24-game/AutoIt/24-game.au3 diff --git a/Task/24-game/COBOL/24-game.cobol b/Task/24-game/COBOL/24-game.cob similarity index 100% rename from Task/24-game/COBOL/24-game.cobol rename to Task/24-game/COBOL/24-game.cob diff --git a/Task/24-game/Delphi/24-game.delphi b/Task/24-game/Delphi/24-game.pas similarity index 100% rename from Task/24-game/Delphi/24-game.delphi rename to Task/24-game/Delphi/24-game.pas diff --git a/Task/24-game/EasyLang/24-game.easy b/Task/24-game/EasyLang/24-game.easy new file mode 100644 index 0000000000..03d699645f --- /dev/null +++ b/Task/24-game/EasyLang/24-game.easy @@ -0,0 +1,68 @@ +print "Enter an equation in RPN form using all of, and only " +print "the following single digits which evaluates to 24:" +func game . + len cnt[] 9 + write ">> " + for i to 4 + h = random 1 9 + write h & " " + cnt[h] += 1 + . + print "" + s$ = input + print s$ + if s$ = "" + return 1 + . + for c$ in strchars s$ + if c$ = "+" or c$ = "-" or c$ = "*" or c$ = "/" + if len st[] < 2 + print "Stack empty" + return 1 + . + if c$ = "+" + st[$ - 1] = st[$ - 1] + st[$] + elif c$ = "-" + st[$ - 1] = st[$ - 1] - st[$] + elif c$ = "*" + st[$ - 1] = st[$ - 1] * st[$] + else + st[$ - 1] = st[$ - 1] / st[$] + . + len st[] -1 + elif c$ <> " " + h = strcode c$ - 48 + if h < 1 or h > 9 + print "Wrong command " & c$ + return 0 + . + if cnt[h] = 0 + print "Wrong number " & h + return 0 + . + cnt[h] -= 1 + st[] &= h + . + . + for c in cnt[] + s += c + . + if s > 0 + print "Not all numbers used" + return 0 + . + if len st[] > 1 + print "Calculation not finished" + return 0 + . + print st[1] + if abs (st[1] - 24) < 1e-10 + print "Well done" + else + print "Wrong result" + . +. +repeat + print "" + until game = 1 +. diff --git a/Task/24-game/Elena/24-game.elena b/Task/24-game/Elena/24-game.elena index d4170cfc82..2a65ccecd2 100644 --- a/Task/24-game/Elena/24-game.elena +++ b/Task/24-game/Elena/24-game.elena @@ -18,13 +18,13 @@ class ExpressionTree var node := new DynamicStruct(); ch => - $43 { node.Level := level + 1; node.Operation := mssg add } // + - $45 { node.Level := level + 1; node.Operation := mssg subtract } // - - $42 { node.Level := level + 2; node.Operation := mssg multiply } // * - $47 { node.Level := level + 2; node.Operation := mssg divide } // / - $40 { level.append(10); ^ self } // ( - $41 { level.reduce(10); ^ self } // ) - ! { + $43 : { node.Level := level + 1; node.Operation := mssg add } // + + $45 : { node.Level := level + 1; node.Operation := mssg subtract } // - + $42 : { node.Level := level + 2; node.Operation := mssg multiply } // * + $47 : { node.Level := level + 2; node.Operation := mssg divide } // / + $40 : { level.append(10); ^ self } // ( + $41 : { level.reduce(10); ^ self } // ) + ! : { node.Leaf := ch.toString().toReal(); node.Level := level + 3 }; @@ -112,16 +112,16 @@ class TwentyFourGame { theNumbers := new object[] { - 1 + randomGenerator.nextInt(9), - 1 + randomGenerator.nextInt(9), - 1 + randomGenerator.nextInt(9), - 1 + randomGenerator.nextInt(9) + 1 + Random.nextInt(9), + 1 + Random.nextInt(9), + 1 + Random.nextInt(9), + 1 + Random.nextInt(9) } } help() { - console + Console .printLine("------------------------------- Instructions ------------------------------") .printLine("Four digits will be displayed.") .printLine("Enter an equation using all of those four digits that evaluates to 24") @@ -137,9 +137,9 @@ class TwentyFourGame prompt() { - theNumbers.forEach::(n){ console.print(n," ") }; + theNumbers.forEach::(n){ Console.print(n," ") }; - console.print(": ") + Console.print(": ") } resolve(expr) @@ -149,19 +149,19 @@ class TwentyFourGame var leaves := new ArrayList(); tree.readLeaves(leaves); - ifnot (leaves.ascendant().sequenceEqual(theNumbers.ascendant())) - { console.printLine("Invalid input. Enter an equation using all of those four digits. Try again."); ^ self }; + if:not (leaves.ascendant().sequenceEqual(theNumbers.ascendant())) + { Console.printLine("Invalid input. Enter an equation using all of those four digits. Try again."); ^ self }; var result := tree.Value; if (result == 24) { - console.printLine("Good work. ",expr,"=",result); + Console.printLine("Good work. ",expr,"=",result); self.newPuzzle() } else { - console.printLine("Incorrect. ",expr,"=",result) + Console.printLine("Incorrect. ",expr,"=",result) } } } @@ -178,7 +178,7 @@ extension gameOp { if (expr == "") { - console.printLine("Skipping this puzzle"); self.newPuzzle() + Console.printLine("Skipping this puzzle"); self.newPuzzle() } else { @@ -188,8 +188,7 @@ extension gameOp } catch(Exception e) { - console.printLine(e) - //console.printLine:"An error occurred. Check your input and try again." + Console.printLine("An error occurred. Check your input and try again.") } }; @@ -198,11 +197,11 @@ extension gameOp } } -// --- program --- +// --- Program --- -public program() +public Program() { var game := new TwentyFourGame().help(); - while (game.prompt().playRound(console.readLine())) {} + while (game.prompt().playRound(Console.readLine())) {} } diff --git a/Task/24-game/Elixir/24-game.elixir b/Task/24-game/Elixir/24-game.ex similarity index 100% rename from Task/24-game/Elixir/24-game.elixir rename to Task/24-game/Elixir/24-game.ex diff --git a/Task/24-game/Frink/24-game.frink b/Task/24-game/Frink/24-game.frink new file mode 100644 index 0000000000..a7a123bc86 --- /dev/null +++ b/Task/24-game/Frink/24-game.frink @@ -0,0 +1,15 @@ +ops = ["+", "-", "*", "/"] + +chosen = new array[[4], {|x| random[1,9]}] +println[chosen] + +for d = chosen.lexicographicPermute[] + multifor o = [ops, ops, ops] + { + str = "((" + d@0 + o@0 + d@1 + ")" + o@1 + d@2 + ")" + o@2 + d@3 + if eval[str] == 24 + println[str] + str = "(" + d@0 + o@0 + d@1 + ")" + o@1 + "(" + d@2 + + o@2 + d@3 + ")" + if eval[str] == 24 + println[str] + } diff --git a/Task/24-game/FutureBasic/24-game.basic b/Task/24-game/FutureBasic/24-game.basic new file mode 100644 index 0000000000..e3cb41f183 --- /dev/null +++ b/Task/24-game/FutureBasic/24-game.basic @@ -0,0 +1,310 @@ +//include resources "24 Game Icon.icns" + +#build CompilerOptions @"-Wno-unused-variable" + +_mEdit = 2 +editmenu _mEdit + +begin globals +long gPosition +end globals + +void local fn EraseErrorText + + CGRect r + r = fn CGRectMake(10, 200, 400, 15) + rect fill r,fn ColorBlack + +end fn + +local fn ArcRandom( a as long, b as long ) as long + long i + cln i = (arc4random()%(b-a+1))+a; +end fn = fn floor(i) + +local fn GetRandomNumbers as CFStringRef + + // 96 number groups + + CFArrayRef combos = @[¬ + + // The first 32 are easy + @"1 2 3 4", @"2 4 6 8", @"1 2 4 8", @"1 3 4 6", @"1 2 6 8", + @"2 3 4 8", @"1 3 6 9", @"1 2 7 8", @"2 3 6 8", @"1 4 6 8", + @"2 2 3 9", @"3 4 6 6", @"2 3 3 8", @"1 5 6 6", @"2 4 4 6", + @"1 3 8 8", @"2 2 6 9", @"3 3 6 9", @"1 2 5 9", @"2 4 5 5", + @"1 3 5 9", @"2 2 4 9", @"1 2 3 6", @"1 2 2 9", @"1 2 3 9", + @"1 2 4 6", @"1 2 4 4", @"1 2 2 6", @"1 3 3 6", @"1 1 4 6", + @"1 1 2 8", @"1 1 3 8", + // The middle 32 are medium + @"1 5 5 9", @"4 4 6 9", @"2 3 7 9",@"3 5 8 8", @"1 6 6 8", + @"3 3 5 6", @"1 4 5 8", @"3 3 6 7",@"2 5 5 8", @"4 4 7 9", + @"1 5 6 9", @"3 3 8 9", @"2 6 6 7",@"4 5 7 8", @"2 2 5 9", + @"2 4 6 7", @"1 5 6 8", @"3 4 7 7",@"2 5 6 6", @"3 4 5 9", + @"1 6 7 9", @"2 3 7 8", @"1 4 6 9",@"2 3 5 9", @"3 4 4 8", + @"2 5 8 9", @"1 4 8 9", @"3 3 4 9",@"2 6 7 9", @"1 3 5 7", + @"1 3 6 6", @"2 2 5 7", + // The last 32 are hard + @"1 5 7 9",@"3 4 7 9", @"2 5 7 8", @"3 4 8 9", @"3 4 5 8", + @"2 6 6 9",@"4 4 5 7", @"2 4 6 9", @"1 4 7 7", @"2 3 8 9", + @"2 3 4 7",@"3 3 4 8", @"1 3 7 9", @"2 4 5 9", @"1 3 6 8", + @"2 4 4 9",@"1 5 8 9", @"3 3 5 9", @"2 6 8 9", @"1 4 4 7", + @"2 3 6 7",@"1 3 5 8", @"2 4 7 8", @"1 3 4 7", @"2 3 5 6", + @"1 4 5 6",@"3 3 5 7", @"2 2 3 6", @"3 3 7 7", @"3 3 7 9", + @"4 4 8 9",@"2 4 8 9"] + + long i = fn ArcRandom( 0, len(combos) - 1 ) + gPosition = i + +end fn = combos[i] + + +local fn EvaluateMath( equation as CFStringRef ) as CFStringRef + equation = fn StringByReplacingOccurrencesOfString( lcase(equation), @"x", @"*" ) + + CFStringRef result = NULL + RegularExpressionRef regex = fn RegularExpressionWithPattern( @"[0-9.]+", NSRegularExpressionCaseInsensitive, NULL ) + CFArrayRef matches = fn RegularExpressionMatches( regex, equation, 0, fn CFRangeMake( 0, len(equation) ) ) + NSInteger intConversions = 0 + TextCheckingResultRef match + CFRange originalRange + CFRange adjustedRange + CFStringRef value + + for match in matches + originalRange = fn TextCheckingResultRange( match ) + adjustedRange = fn CFRangeMake( ( originalRange.location + ( intConversions * len( @".0") ) ), originalRange.length ) + value = fn StringSubstringWithRange( equation, adjustedRange ) + if fn StringContainsString( value, @"." ) + continue + else + equation = fn StringByReplacingCharactersInRange( equation, adjustedRange, fn StringWithFormat( @"%@.0", value ) ) + intConversions++ + end if + next + ExceptionRef e + try + ExpressionRef expression = fn ExpressionWithFormat( equation ) + CFNumberRef number = fn ExpressionValueWithObject( expression, NULL, NULL ) + result = fn StringWithFormat( @"%.3f", dblval( number ) ) + end try + + catch (e) + result = fn StringWithFormat( @"%@", e ) : exit fn + end catch + // Test if result is an integer and, if so, return result as an integer + if( fn StringDoubleValue( result ) == fn floorf( fn StringDoubleValue( result ) ) ) + result = fn ArrayFirstObject( fn StringComponentsSeparatedByString( result, @"." ) ) + end if +end fn = result + + +local fn QuitOrPlayAlert(GameResult as CFStringRef) + alert -2,,GameResult,@"You won!",@"Quit;Play Again" + AlertButtonSetKeyEquivalent( 2, 2, @"\e" ) + short result + result = alert 2 + if ( result != NSAlertSecondButtonReturn ) then appterminate +end fn + + +local fn BuildWindow + CGRect r = fn CGRectMake( 0, 0, 580, 250) + window 1, @"24 Game", r + windowcenter(1) + WindowSetBackgroundColor(1,fn ColorBlack) + +end fn + +///////// Start ////////// + +fn BuildWindow + + +short d(4), i +CFStringRef CheckForDuplicates(97) +for i = 1 to 96 + CheckForDuplicates(i) = @"" +next i + +short DuplicatesCounter +DuplicatesCounter = 0 + + +"Main" + +cls +text ,,fn colorWhite + +print +print %(10,15),"Given four numbers and using just the +, -, *, and / operators; and the" +print %(10,30),"possible use of parenthesis (), enter an expression that equates to 24." +print %(10,45),"You must use all your numbers and only those numbers." +print %(10,60),"Examples: 9618 Solution 9 + 6 + 1 + 8 or 3173 Solution (3 * 7) - (1 - 4)" +print +print %(10,85),"Enter Q to quit or S to skip to the next number." + +"GetFourNumbers" + +CFArrayRef randomNumbers : randomNumbers= fn StringComponentsSeparatedByString( fn GetRandomNumbers, @" " ) +CFStringRef RandomNumberblock : RandomNumberblock = @"" +CFStringRef RandomNumberblockAdd : RandomNumberblockAdd = @"" + +for i = 0 to 3 + // create a string from the 4 numbers + RandomNumberblockAdd = randomNumbers[i] + RandomNumberblock = fn StringByAppendingString(RandomNumberblock,RandomNumberblockAdd) + RandomNumberblock = fn StringByAppendingString(RandomNumberblock,@" ") +next i + + +if DuplicatesCounter = > 96 + // reset counter when last number is retrieved and start from the first number block + DuplicatesCounter = 0 + for i = 1 to 96 + CheckForDuplicates(i) = @"" + next i +end if + +for i = 1 to 96 + // check the current numbers with the numbers already used + if fn StringIsEqual(RandomNumberblock,CheckForDuplicates(i)) + RandomNumberblock = fn StringWithString(CheckForDuplicates(DuplicatesCounter)) + goto "GetFourNumbers" + end if +next i + +DuplicatesCounter ++ +CheckForDuplicates(DuplicatesCounter) = fn StringWithString(RandomNumberblock) + +d(1) = fn StringIntegerValue( randomNumbers[0] ) +d(2) = fn StringIntegerValue( randomNumbers[1] ) +d(3) = fn StringIntegerValue( randomNumbers[2] ) +d(4) = fn StringIntegerValue( randomNumbers[3] ) + +short dots = 0 + +//d(1) = 9:d(2) = 6:d(3) = 1:d(4) = 8 // Uncomment to test with 9618 numbers. Solution 9 + 6 + 1 + 8 +//d(1) = 6:d(2) = 5:d(3) = 3:d(4) = 8 // Uncomment to test with 6538 numbers. Solution 6 / ( 5 - 3 ) * 8 +//d(1) = 3:d(2) = 1:d(3) = 7:d(4) = 3 // Uncomment to test with 3773 numbers. Solution ((3 * 1) * 7) + 3 +//d(1) = 4:d(2) = 2:d(3) = 7:d(4) = 1 // Uncomment to test with 4271 numbers. Solution (4 * ( 7 - 2 + 1 ) +// NOTE: When using these test numbers, also uncomment dots = 0 below here to prevent misleading dot displays + + +if gPosition <= 32 then dots = 1 +if gPosition > 32 and gPosition < 65 then dots = 2 +if gPosition > 64 then dots = 3 + +//dots = 0 uncomment when testing the numbers above to prevent misleading dot displays + +print +text ,,fn colorGreen +print %(15,110),"These are your numbers, difficulty level "; +// @"\U000026AA" is white unicode dot - Easy difficulty (One-Dot) +// @"\U0001F534" is red unicode dot - Medium difficulty (Two-Dots) +// @"\U0001F7E1" is yellow unicode dot - Hard difficulty (Three-Dots) + +if dots = 1 then print @"\U000026AA Easy" +if dots = 2 then print @"\U0001F534 \U0001F534 Medium" +if dots = 3 then print @"\U0001F7E1 \U0001F7E1 \U0001F7E1 Hard" + +print %(55,125) +text ,18,fn colorGreen +for i = 1 to 4 + print d(i); " "; +next + +print + +text ,12,fn colorWhite +printf @"\n\n\n" + +CFStringRef expr +bool TryAgain : TryAgain = _false +CFStringRef MessageText +CFStringRef UserInput = NULL + +"InputExpression" + +if TryAgain + MessageText = fn StringWithFormat( @"Enter math expression: [ '%@' was incorrect ]", expr ) + UserInput = input %(10, 190), MessageText, @"123456789+-*/()qs", YES,, 0 +else + UserInput = input %(10, 190), @"Enter math expression:", @"123456789+-*/()qs", YES,, 0 +end if + +if ( UserInput == NULL ) then "InputExpression" +expr = UserInput +if expr = @"" then "InputExpression" +if fn StringIsEqual(ucase(expr) , @"Q") then appterminate +if fn StringIsEqual(ucase(expr) , @"S") then "Main" + + +//check expr for validity + +short j +bool GotAllNumbers : GotAllNumbers = _false +short ThisNumberPosition : ThisNumberPosition = 0 +short GotaNumber : GotaNumber = 0 +short TotalNumbers : TotalNumbers = 0 + +short ExtraNumbers:ExtraNumbers = 0 + +for i = 1 to len$(fn stringpascalstring(expr)) + if asc(mid$(fn stringpascalstring(expr),i,1)) > 48 && asc(mid$(fn stringpascalstring(expr),i,1)) < 58 + ExtraNumbers ++ + end if +next i + +if ExtraNumbers > 4 + fn EraseErrorText + text ,,fn colorRed + TryAgain = _true + print %(10,200);"Error! Extra numbers not allowed": goto "InputExpression" + text ,,fn colorWhite +end if + + +for i = 1 to 4 + GotaNumber = 0 + for j = 0 to len(expr) -1 + ThisNumberPosition = instr( j, expr, right(str( d(i)),1 )) + ThisNumberPosition ++ + if ThisNumberPosition then GotaNumber = _true + next j + if GotaNumber then TotalNumbers ++ +next i + +if TotalNumbers => 4 then GotAllNumbers = _true + +if GotAllNumbers = _false + fn EraseErrorText + text ,,fn colorRed + TryAgain = _true + print %(10,200);"ERROR! Must use all your numbers and only those numbers." : goto "InputExpression" + text ,,fn colorWhite +end if + +fn EraseErrorText + + +if fn EvaluateMath( expr ) = _false + text ,,fn colorRed + TryAgain = _true + Print %(10,200);"Error! Incorrect math sequence." + goto "InputExpression" + text ,,fn colorWhite +end if + +CFStringRef GameResult +if fn StringIntegerValue( fn EvaluateMath( expr ) ) == 24 then GameResult = @"Correct" else GameResult = @"Incorrect" + +if GameResult = @"Incorrect" + TryAgain = _true + goto "InputExpression" +end if + +fn QuitOrPlayAlert(GameResult) +goto "Main" + +handleevents diff --git a/Task/24-game/J/24-game.j b/Task/24-game/J/24-game.j index 73034a24eb..928663b455 100644 --- a/Task/24-game/J/24-game.j +++ b/Task/24-game/J/24-game.j @@ -1,6 +1,6 @@ require'misc' -deal=: 1 + ? bind 9 9 9 9 -rules=: smoutput bind 'see http://en.wikipedia.org/wiki/24_Game' +deal=: 1 + ? @ 9 9 9 9 +rules=: echo @ 'see http://en.wikipedia.org/wiki/24_Game' input=: prompt @ ('enter 24 expression using ', ":, ': '"_) wellformed=: (' '<;._1@, ":@[) -:&(/:~) '(+-*%)' -.&;:~ ] diff --git a/Task/24-game/Jq/24-game.jq b/Task/24-game/Jq/24-game.jq new file mode 100644 index 0000000000..09ce6dfc30 --- /dev/null +++ b/Task/24-game/Jq/24-game.jq @@ -0,0 +1,90 @@ +### The MRG32k3a combined recursive PRNG - see above +import "MRG32k3a" as MRG {search: "."}; + +### Generic utilities +def sum(stream): reduce stream as $x (0; .+$x); + +# like while/2 but emit the final term rather than the first one +def whilst(cond; update): + def _whilst: + if cond then update | (., _whilst) else empty end; + _whilst; + +### Reverse Polish Notation +# An array of the allowed operators +def operators: "+-*/" | split(""); + +# If $a and $b are numbers and $c an operator, then "$a $b $c" is evaluated as an RPN expression. +# Output: {emit, result} with .emit == null if there is a valid result. +def applyOperator($a; $b; $c): + if ([$a,$b] | map(type) | unique) == ["number"] + then + if $c == "+" then {result: ($a + $b)} + elif $c == "-" then {result: ($a - $b)} + elif $c == "*" then {result: ($a * $b)} + elif ($c == "/") then {result: ($b / $a)} + else {emit: "unrecognized operator: \($c)"} + end + else {emit: "invalid number"} + end; + +# Input: an array representing an RPN expression. +# Output: {emit, result} as per applyOperator/3 +# Example: [1,2,3,"+","+"] | evaluate #=> 6 +def evaluate: + if length == 1 + then if .[0]|type == "number" then {result: .[0]} + else {emit: "invalid RPN expression"} + end + elif length < 3 then {emit: "invalid RPN expression: \(. | join(" "))"} + else . as $in + | (first( range(0; length) as $i | select(any( operators[]; . == $in[$i]) ) | $i) // null) as $ix + | if $ix == null then {emit: "invalid RPN expression"} + else applyOperator(.[$ix-2]; .[$ix-1]; .[$ix]) as $result + | if $result.result then .[:$ix-2] + [$result.result] + .[$ix+1:] | evaluate + else $result + end + end + end; + +### The "24 Game" + +# . is the putative RPN string to be checked. +# $four is the string of the four expected digits, in order. +# Output: {emit, result} with .emit set to "Correct!" if .result == 24 +def check($four): + if (gsub("[^1-9]";"") | explode | sort | implode) != $four + then {emit: "You must use each of the four digits \($four | split("") | join(" ")) exactly once:"} + else . as $in + | {s: [], emit: null} + | [$in | split("")[] | select(. != " ") + | . as $in | explode[0] | if . >= 48 and . <= 57 then . - 48 else $in end] + | evaluate + | if .result + then if .result|round == 24 then .emit = "Correct!" + else .emit = "Value \(.result) is not 24." + end + else .emit += "\nTry again, or enter . to start again, or q to quit." + end + end ; + +def run: + # Populate .digits with four non-negative digits selected at random, with replacement: + {digits: (9 | MRG::prn(4) | map(. + 1))} + | (.digits | sort | join("")) as $four + | "At the prompt, enter an RPN string (e.g. 64*1+1-), or . for a new set of four digits, or q to quit.", + "Make 24 using these digits, once each, in any order: \(.digits):", + ( whilst( .stop | not; + .emit = null + | . as $state + | try input catch halt + | if IN( "q", "quit") then halt + elif . == "." then $state | .stop = true + else check($four) + | if .result then .stop = true end + end ) + | select(.emit).emit ), + # rerun + run; + +run diff --git a/Task/24-game/Julia/24-game.julia b/Task/24-game/Julia/24-game.jl similarity index 100% rename from Task/24-game/Julia/24-game.julia rename to Task/24-game/Julia/24-game.jl diff --git a/Task/24-game/Kotlin/24-game.kotlin b/Task/24-game/Kotlin/24-game.kts similarity index 100% rename from Task/24-game/Kotlin/24-game.kotlin rename to Task/24-game/Kotlin/24-game.kts diff --git a/Task/24-game/OCaml/24-game.ocaml b/Task/24-game/OCaml/24-game.ml similarity index 100% rename from Task/24-game/OCaml/24-game.ocaml rename to Task/24-game/OCaml/24-game.ml diff --git a/Task/24-game/Perl/24-game.pl b/Task/24-game/Perl/24-game.pl index 071bb8e2b8..d4dd33e728 100644 --- a/Task/24-game/Perl/24-game.pl +++ b/Task/24-game/Perl/24-game.pl @@ -25,18 +25,21 @@ while (1) { print "Expression (try ", $try++, "): "; my $entry = <>; - if (!defined $entry || $entry eq 'q') + if (!defined $entry || substr($entry,0,1) eq 'q') { say "Goodbye. Sorry you couldn't win."; last; } - $entry =~ s/\s+//g; # remove all white space + $entry =~ s/\s+//g; # remove all white space (newline is whitespace too) next if $entry eq ''; my $given_digits = join "", sort @digits; my $entry_digits = join "", sort grep { /\d/ } split(//, $entry); - if ($given_digits ne $entry_digits || # not correct digits - $entry =~ /\d\d/ || # combined digits - $entry =~ m|[-+*/]{2}| || # combined operators - $entry =~ tr|-0-9()+*/||c) # Invalid characters - { say "That's not valid"; next; } + if ($given_digits ne $entry_digits) + { say "incorrect digits"; next; } + if ($entry =~ /\d\d/) + { say "error, combined digits"; next; } + if ($entry =~ m|[-+*/]{2}|) + { say "error, combined operators"; next; } + if ($entry =~ tr|-0-9()+*/||c) + { say "invalid characters!"; next; } my $n = eval $entry; diff --git a/Task/24-game/PowerShell/24-game.psh b/Task/24-game/PowerShell/24-game.ps1 similarity index 100% rename from Task/24-game/PowerShell/24-game.psh rename to Task/24-game/PowerShell/24-game.ps1 diff --git a/Task/24-game/Rebol/24-game.rebol b/Task/24-game/Rebol/24-game.rebol new file mode 100644 index 0000000000..246a8cc6b5 --- /dev/null +++ b/Task/24-game/Rebol/24-game.rebol @@ -0,0 +1,43 @@ +Rebol [ + title: "Rosetta code: 24 game" + file: %24_game.r3 + url: https://rosettacode.org/wiki/24_game + needs: 3.10.0 ; or something like that (ajoin/with) +] +game-24: function/with [ + /seed val +][ + random/seed any [val now/precise] + valid: copy/part random digits 4 + prin "Using the following numbers, enter an expression that equals 24: " + print [valid/1 ", " valid/2 ", " valid/3 " and " valid/4] + print "Evaluation from left to right with no precedence, unless you use parenthesis." + sort valid + + sucess: false + + while [not sucess] [ + guess: ask "Enter your expression: " + if guess = "q" [halt] + numbers: sort copy guess + numbers: take/part find numbers digit 4 + either all [ + valid = numbers + parse guess [some chars end] + integer? result: try load ajoin/with split guess 1 #" " + ][ + print ["The result of your expression is: " result] + if result = 24 [sucess: true] + ][ + print "Something is wrong with the expression, try again." + ] + ] + print "You got it right!" +][ + valid: guess: none + digits: "123456789" + digit: charset digits + chars: union digit charset "+-*/()" +] + +game-24/seed 1 diff --git a/Task/24-game/Rust/24-game.rs b/Task/24-game/Rust/24-game.rs new file mode 100644 index 0000000000..149fb0aa62 --- /dev/null +++ b/Task/24-game/Rust/24-game.rs @@ -0,0 +1,108 @@ +use std::io::{self,BufRead}; +extern crate rand; +use rand::Rng; + +fn op_type(x: char) -> i32{ + match x { + '-' | '+' => return 1, + '/' | '*' => return 2, + '(' | ')' => return -1, + _ => return 0, + } +} + +fn to_rpn(input: &mut String){ + + let mut rpn_string : String = String::new(); + let mut rpn_stack : String = String::new(); + let mut last_token = '#'; + for token in input.chars(){ + if token.is_digit(10) { + rpn_string.push(token); + } + else if op_type(token) == 0 { + continue; + } + else if op_type(token) > op_type(last_token) || token == '(' { + rpn_stack.push(token); + last_token=token; + } + else { + while let Some(top) = rpn_stack.pop() { + if top=='(' { + break; + } + rpn_string.push(top); + } + if token != ')'{ + rpn_stack.push(token); + } + } + } + while let Some(top) = rpn_stack.pop() { + rpn_string.push(top); + } + + println!("your formula results in {}", rpn_string); + + *input=rpn_string; +} + +fn calculate(input: &String, list : &mut [u32;4]) -> f32{ + let mut stack : Vec = Vec::new(); + let mut accumulator : f32 = 0.0; + + for token in input.chars(){ + if token.is_digit(10) { + let test = token.to_digit(10).unwrap() as u32; + match list.iter().position(|&x| x == test){ + Some(idx) => list[idx]=10 , + _ => println!(" invalid digit: {} ",test), + } + stack.push(accumulator); + accumulator = test as f32; + }else{ + let a = stack.pop().unwrap(); + accumulator = match token { + '-' => a-accumulator, + '+' => a+accumulator, + '/' => a/accumulator, + '*' => a*accumulator, + _ => {accumulator},//NOP + }; + } + } + println!("your formula results in {}",accumulator); + accumulator +} + +fn main() { + + let mut rng = rand::thread_rng(); + // each from 1 ──► 9 (inclusive) + let mut list :[u32;4]=[ + rng.gen::()%9+1, + rng.gen::()%9+1, + rng.gen::()%9+1, + rng.gen::()%9+1 + ]; + + println!("form 24 with using + - / * {:?}",list); + //get user input + let mut input = String::new(); + io::stdin().read_line(&mut input).unwrap(); + //convert to rpn + to_rpn(&mut input); + let result = calculate(&input, &mut list); + + if list.iter().any(|&num| num != 10) { + println!("you didn't use all the numbers"); + } else { + println!("and you used all numbers"); + match result { + 24.0 => println!("you won"), + _ => println!("but your formula doesn't result in 24"), + } + } + +} diff --git a/Task/24-game/Rust/24-game.rust b/Task/24-game/Rust/24-game.rust deleted file mode 100644 index bdcad8b01d..0000000000 --- a/Task/24-game/Rust/24-game.rust +++ /dev/null @@ -1,102 +0,0 @@ -use std::io::{self,BufRead}; -extern crate rand; -use rand::Rng; - -fn op_type(x: char) -> i32{ - match x { - '-' | '+' => return 1, - '/' | '*' => return 2, - '(' | ')' => return -1, - _ => return 0, - } -} - -fn to_rpn(input: &mut String){ - - let mut rpn_string : String = String::new(); - let mut rpn_stack : String = String::new(); - let mut last_token = '#'; - for token in input.chars(){ - if token.is_digit(10) { - rpn_string.push(token); - } - else if op_type(token) == 0 { - continue; - } - else if op_type(token) > op_type(last_token) || token == '(' { - rpn_stack.push(token); - last_token=token; - } - else { - while let Some(top) = rpn_stack.pop() { - if top=='(' { - break; - } - rpn_string.push(top); - } - if token != ')'{ - rpn_stack.push(token); - } - } - } - while let Some(top) = rpn_stack.pop() { - rpn_string.push(top); - } - - println!("you formula results in {}", rpn_string); - - *input=rpn_string; -} - -fn calculate(input: &String, list : &mut [u32;4]) -> f32{ - let mut stack : Vec = Vec::new(); - let mut accumulator : f32 = 0.0; - - for token in input.chars(){ - if token.is_digit(10) { - let test = token.to_digit(10).unwrap() as u32; - match list.iter().position(|&x| x == test){ - Some(idx) => list[idx]=10 , - _ => println!(" invalid digit: {} ",test), - } - stack.push(accumulator); - accumulator = test as f32; - }else{ - let a = stack.pop().unwrap(); - accumulator = match token { - '-' => a-accumulator, - '+' => a+accumulator, - '/' => a/accumulator, - '*' => a*accumulator, - _ => {accumulator},//NOP - }; - } - } - println!("you formula results in {}",accumulator); - accumulator -} - -fn main() { - - let mut rng = rand::thread_rng(); - let mut list :[u32;4]=[rng.gen::()%10,rng.gen::()%10,rng.gen::()%10,rng.gen::()%10]; - - println!("form 24 with using + - / * {:?}",list); - //get user input - let mut input = String::new(); - io::stdin().read_line(&mut input).unwrap(); - //convert to rpn - to_rpn(&mut input); - let result = calculate(&input, &mut list); - - if list.iter().any(|&list| list !=10){ - println!("and you used all numbers"); - match result { - 24.0 => println!("you won"), - _ => println!("but your formulla doesn't result in 24"), - } - }else{ - println!("you didn't use all the numbers"); - } - -} diff --git a/Task/24-game/Scheme/24-game.ss b/Task/24-game/Scheme/24-game.scm similarity index 100% rename from Task/24-game/Scheme/24-game.ss rename to Task/24-game/Scheme/24-game.scm diff --git a/Task/24-game/Zig/24-game.zig b/Task/24-game/Zig/24-game.zig new file mode 100644 index 0000000000..4c224f1030 --- /dev/null +++ b/Task/24-game/Zig/24-game.zig @@ -0,0 +1,153 @@ +const std = @import("std"); +const rand = std.Random; +// (hint: errors cannot be handled at comptime) +var stdout: std.fs.File.Writer = undefined; +var stdin: std.fs.File.Reader = undefined; + +fn opType(x: u8) i32 { + return switch (x) { + '-', '+' => 1, + '/', '*' => 2, + '(', ')' => -1, + else => 0, + }; +} + +fn toRpn(allocator: std.mem.Allocator, input: []const u8) ![]u8 { + var rpnString = std.ArrayList(u8).init(allocator); + defer rpnString.deinit(); + + var rpnStack = std.ArrayList(u8).init(allocator); + defer rpnStack.deinit(); + + var lastToken: u8 = '#'; + + for (input) |token| { + if (token >= '1' and token <= '9') { + try rpnString.append(token); + } else if (opType(token) == 0) { + continue; + } else if (opType(token) > opType(lastToken) or token == '(') { + try rpnStack.append(token); + lastToken = token; + } else { + while (rpnStack.items.len > 0) { + const top = rpnStack.pop().?; + if (top == '(') { + break; + } + try rpnString.append(top); + } + if (token != ')') { + try rpnStack.append(token); + } + } + } + + while (rpnStack.items.len > 0) { + try rpnString.append(rpnStack.pop().?); + } + + if (rpnString.items.len > 0) { + try stdout.print("your formula results in {s}\n", .{rpnString.items}); + } else { + stdout.print("no input available.\n", .{}) catch {}; + } + + return rpnString.toOwnedSlice(); +} + +fn calculate(input: []const u8, list: *[4]u32) f32 { + var stack = std.ArrayList(f32).init(std.heap.page_allocator); + defer stack.deinit(); + + var accumulator: f32 = 0.0; + + for (input) |token| { + if (token >= '1' and token <= '9') { + const digit = @as(u32, token - '0'); + + // Find and mark the used digit + var found = false; + for (list, 0..) |val, idx| { + if (val == digit) { + list[idx] = 10; + found = true; + break; + } + } + + if (!found) { + stdout.print(" invalid digit: {d} \n", .{digit}) catch {}; + } + + stack.append(accumulator) catch {}; + accumulator = @floatFromInt(digit); + } else { + const a = stack.pop().?; + + accumulator = switch (token) { + '-' => a - accumulator, + '+' => a + accumulator, + '/' => a / accumulator, + '*' => a * accumulator, + else => accumulator, // NOP + }; + } + } + + stdout.print("your formula results in {d}\n", .{accumulator}) catch {}; + return accumulator; +} + +pub fn main() !void { + stdout = std.io.getStdOut().writer(); + stdin = std.io.getStdIn().reader(); + var prng = rand.DefaultPrng.init(@as(u64, @intCast(std.time.timestamp()))); + const random = prng.random(); + // only values from 1 --> 9 (inclusive) + var list = [_]u32{ + @mod(random.int(u32), 9) + 1, + @mod(random.int(u32), 9) + 1, + @mod(random.int(u32), 9) + 1, + @mod(random.int(u32), 9) + 1, + }; + + try stdout.print("form 24 with using + - / * {d} {d} {d} {d}\n", .{ list[0], list[1], list[2], list[3] }); + + // Get user input + var buffer: [1024]u8 = undefined; + const input = try stdin.readUntilDelimiterOrEof(buffer[0..], '\n') orelse ""; + + var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); + defer arena.deinit(); + const allocator = arena.allocator(); + + // Convert to RPN + const rpnInput = try toRpn(allocator, input); + if (rpnInput.len == 0) { + stdout.print("exit.\n", .{}) catch {}; + return; + } + + const result = calculate(rpnInput, &list); + + var allUsed = true; + for (list) |val| { + if (val != 10) { + allUsed = false; + break; + } + } + + if (allUsed) { + try stdout.print("and you used all numbers\n", .{}); + if (result == 24.0) { + try stdout.print("you won\n", .{}); + } else { + try stdout.print("but your formula doesn't result in 24\n", .{}); + } + } else { + try stdout.print("you didn't use all the numbers\n", .{}); + } +} diff --git a/Task/4-rings-or-4-squares-puzzle/Ada/4-rings-or-4-squares-puzzle.ada b/Task/4-rings-or-4-squares-puzzle/Ada/4-rings-or-4-squares-puzzle.adb similarity index 100% rename from Task/4-rings-or-4-squares-puzzle/Ada/4-rings-or-4-squares-puzzle.ada rename to Task/4-rings-or-4-squares-puzzle/Ada/4-rings-or-4-squares-puzzle.adb diff --git a/Task/4-rings-or-4-squares-puzzle/Crystal/4-rings-or-4-squares-puzzle.crystal b/Task/4-rings-or-4-squares-puzzle/Crystal/4-rings-or-4-squares-puzzle.cr similarity index 100% rename from Task/4-rings-or-4-squares-puzzle/Crystal/4-rings-or-4-squares-puzzle.crystal rename to Task/4-rings-or-4-squares-puzzle/Crystal/4-rings-or-4-squares-puzzle.cr diff --git a/Task/4-rings-or-4-squares-puzzle/EasyLang/4-rings-or-4-squares-puzzle.easy b/Task/4-rings-or-4-squares-puzzle/EasyLang/4-rings-or-4-squares-puzzle.easy index f2e05dc87f..22e54e305a 100644 --- a/Task/4-rings-or-4-squares-puzzle/EasyLang/4-rings-or-4-squares-puzzle.easy +++ b/Task/4-rings-or-4-squares-puzzle/EasyLang/4-rings-or-4-squares-puzzle.easy @@ -1,12 +1,10 @@ func ok v t[] . for h in t[] - if v = h - return 0 - . + if v = h : return 0 . return 1 . -proc four lo hi uni show . . +proc four lo hi uni show . # subr bf for f = lo to hi diff --git a/Task/4-rings-or-4-squares-puzzle/Julia/4-rings-or-4-squares-puzzle.julia b/Task/4-rings-or-4-squares-puzzle/Julia/4-rings-or-4-squares-puzzle.jl similarity index 100% rename from Task/4-rings-or-4-squares-puzzle/Julia/4-rings-or-4-squares-puzzle.julia rename to Task/4-rings-or-4-squares-puzzle/Julia/4-rings-or-4-squares-puzzle.jl diff --git a/Task/4-rings-or-4-squares-puzzle/Kotlin/4-rings-or-4-squares-puzzle.kotlin b/Task/4-rings-or-4-squares-puzzle/Kotlin/4-rings-or-4-squares-puzzle.kts similarity index 100% rename from Task/4-rings-or-4-squares-puzzle/Kotlin/4-rings-or-4-squares-puzzle.kotlin rename to Task/4-rings-or-4-squares-puzzle/Kotlin/4-rings-or-4-squares-puzzle.kts diff --git a/Task/4-rings-or-4-squares-puzzle/OCaml/4-rings-or-4-squares-puzzle.ocaml b/Task/4-rings-or-4-squares-puzzle/OCaml/4-rings-or-4-squares-puzzle.ml similarity index 100% rename from Task/4-rings-or-4-squares-puzzle/OCaml/4-rings-or-4-squares-puzzle.ocaml rename to Task/4-rings-or-4-squares-puzzle/OCaml/4-rings-or-4-squares-puzzle.ml diff --git a/Task/4-rings-or-4-squares-puzzle/PARI-GP/4-rings-or-4-squares-puzzle.parigp b/Task/4-rings-or-4-squares-puzzle/PARI-GP/4-rings-or-4-squares-puzzle.parigp new file mode 100644 index 0000000000..d8c0e765a3 --- /dev/null +++ b/Task/4-rings-or-4-squares-puzzle/PARI-GP/4-rings-or-4-squares-puzzle.parigp @@ -0,0 +1,39 @@ +foursquares(plo, phi, punique, pshow) = { + my(lo=plo, hi=phi, unique=punique, show=pshow, solutions, a, b, c, d, e, f, g); + print(); + for (c = lo, hi, + for (d = lo, hi, + if (!unique || c != d, + a = c + d; + if (a >= lo && a <= hi && (!unique || (c != 0 && d != 0)), + for (e = lo, hi, + if (!unique || (e != a && e != c && e != d), + g = d + e; + if (g >= lo && g <= hi && (!unique || (g != a && g != c && g != d && g != e)), + for (f = lo, hi, + if (!unique || (f != a && f != c && f != d && f != g && f != e), + b = e + f - c; + if (b >= lo && b <= hi && (!unique || (b != a && b != c && b != d && b != g && b != e && b != f)), + solutions++; + if (show, print(a, " ", b, " ", c, " ", d, " ", e, " ", f, " ", g)); + ) + ) + ) + ) + ) + ) + ) + ) + ) + ); + + if (unique, + print("\n", solutions, " unique solutions in ", lo, " to ", hi); + , + print("\n", solutions, " non-unique solutions in ", lo, " to ", hi); + ); +} + +foursquares(1,7,1,1); +foursquares(3,9,1,1); +foursquares(0,9,0,0); diff --git a/Task/4-rings-or-4-squares-puzzle/Quackery/4-rings-or-4-squares-puzzle.quackery b/Task/4-rings-or-4-squares-puzzle/Quackery/4-rings-or-4-squares-puzzle.quackery new file mode 100644 index 0000000000..fd5fa00757 --- /dev/null +++ b/Task/4-rings-or-4-squares-puzzle/Quackery/4-rings-or-4-squares-puzzle.quackery @@ -0,0 +1,36 @@ + [ swap dip [ 1+ split drop ] + split nip ] is slice ( [ n n --> [ ) + + [ 0 swap witheach + ] is sum ( [ --> n ) + + [ slice sum join ] is square ( [ [ n n --> [ ) + + [ true swap + behead swap witheach + [ over = not if + [ dip not conclude ] ] + drop ] is same ( [ --> b ) + + [ [] temp put + over - 1+ times + [ dup i^ + temp gather ] + drop + temp take ] is low->high ( n n --> [ ) + + [ [] temp put + witheach + [ [] + over 0 1 square + over 1 3 square + over 3 5 square + over 5 6 square + same iff + [ nested temp gather ] + else drop ] + temp take ] is task ( [ n --> [ ) + + 1 7 low->high permutations task + witheach [ echo cr ] cr + 3 9 low->high permutations task + witheach [ echo cr ] cr + 0 9 low->high 7 arrangements task size echo diff --git a/Task/4-rings-or-4-squares-puzzle/Rust/4-rings-or-4-squares-puzzle.rust b/Task/4-rings-or-4-squares-puzzle/Rust/4-rings-or-4-squares-puzzle.rs similarity index 100% rename from Task/4-rings-or-4-squares-puzzle/Rust/4-rings-or-4-squares-puzzle.rust rename to Task/4-rings-or-4-squares-puzzle/Rust/4-rings-or-4-squares-puzzle.rs diff --git a/Task/4-rings-or-4-squares-puzzle/Scheme/4-rings-or-4-squares-puzzle.ss b/Task/4-rings-or-4-squares-puzzle/Scheme/4-rings-or-4-squares-puzzle.scm similarity index 100% rename from Task/4-rings-or-4-squares-puzzle/Scheme/4-rings-or-4-squares-puzzle.ss rename to Task/4-rings-or-4-squares-puzzle/Scheme/4-rings-or-4-squares-puzzle.scm diff --git a/Task/4-rings-or-4-squares-puzzle/Uiua/4-rings-or-4-squares-puzzle.uiua b/Task/4-rings-or-4-squares-puzzle/Uiua/4-rings-or-4-squares-puzzle.uiua new file mode 100644 index 0000000000..be7a6495bb --- /dev/null +++ b/Task/4-rings-or-4-squares-puzzle/Uiua/4-rings-or-4-squares-puzzle.uiua @@ -0,0 +1,4 @@ +# Solve 4 equations in 7 variables, all distinct. +Test ← =1⧻◴≡⌟◇(/+⊏){0_1 1_2_3 3_4_5 5_6} +▽⊸≡Test⧅≠⊸⧻+1⇡7 +▽⊸≡Test⧅≠⊸⧻+3⇡7 diff --git a/Task/4-rings-or-4-squares-puzzle/V-(Vlang)/4-rings-or-4-squares-puzzle.v b/Task/4-rings-or-4-squares-puzzle/V-(Vlang)/4-rings-or-4-squares-puzzle-1.v similarity index 100% rename from Task/4-rings-or-4-squares-puzzle/V-(Vlang)/4-rings-or-4-squares-puzzle.v rename to Task/4-rings-or-4-squares-puzzle/V-(Vlang)/4-rings-or-4-squares-puzzle-1.v diff --git a/Task/4-rings-or-4-squares-puzzle/V-(Vlang)/4-rings-or-4-squares-puzzle-2.v b/Task/4-rings-or-4-squares-puzzle/V-(Vlang)/4-rings-or-4-squares-puzzle-2.v new file mode 100644 index 0000000000..f44447a8e6 --- /dev/null +++ b/Task/4-rings-or-4-squares-puzzle/V-(Vlang)/4-rings-or-4-squares-puzzle-2.v @@ -0,0 +1,38 @@ +import math.bits + +fn main ( ) { + mut n := 0 + mut t := []u8{len:7} + + n = solve ( 0, mut t, 1, 7, true ) + println ( "$n unique solutions in 1 to 7" ) + n = solve ( 0, mut t, 3, 9, true ) + println("$n unique solutions in 3 to 9") + n = solve ( 0, mut t, 0, 9, false ) + println("$n non-unique solutions in 0 to 9") +} + +fn solve ( lvl u8, mut t []u8, low u8, high u8,unique bool ) int { + if lvl==7 { + return int(suma(t) && (!unique || isunique( t ))) + } + mut cnt:=0 + for v := low; v <= high; v++ { + t[lvl] = v + cnt += solve ( lvl + 1, mut t, low, high, unique ) + } + return cnt +} + +@[inline] +fn isunique ( t []u8 ) bool { + return bits.ones_count_32(u32(1)<= n - 1 THEN 1 + ELIF ( n - col ) < col THEN names[ n - col ] + ELIF ( n - col ) = col AND NOT ODD n THEN names[ n - col ] + ELSE + NAMEG partial sum := 0; + FOR k TO col DO partial sum +:= c[ n - col ][ k ] OD; + partial sum + FI + OD; + names[ n ]:= 0; + FOR k TO n DO names[ n ] +:= c[ n ][ k ] OD +; IF n MOD 200 = 0 THEN print( ( "...", whole( n, 0 ), newline ) ) FI +OD; + +# display the first 25 rows of the triangle # +FOR n TO 25 DO + print( ( "(", whole( names[ n ], -6 ), ")", whole( n, -3 ), ":" ) ); + FOR col TO n DO + print( ( " ", whole( c[ n ][ col ], -3 ) ) ) + OD; + print( ( newline ) ) +OD; + +print( ( " 23: ", whole( names[ 23 ], 0 ), newline ) ); +print( ( " 123: ", whole( names[ 123 ], 0 ), newline ) ) diff --git a/Task/9-billion-names-of-God-the-integer/Ada/9-billion-names-of-god-the-integer.ada b/Task/9-billion-names-of-God-the-integer/Ada/9-billion-names-of-god-the-integer.adb similarity index 100% rename from Task/9-billion-names-of-God-the-integer/Ada/9-billion-names-of-god-the-integer.ada rename to Task/9-billion-names-of-God-the-integer/Ada/9-billion-names-of-god-the-integer.adb diff --git a/Task/9-billion-names-of-God-the-integer/Crystal/9-billion-names-of-god-the-integer.crystal b/Task/9-billion-names-of-God-the-integer/Crystal/9-billion-names-of-god-the-integer.cr similarity index 100% rename from Task/9-billion-names-of-God-the-integer/Crystal/9-billion-names-of-god-the-integer.crystal rename to Task/9-billion-names-of-God-the-integer/Crystal/9-billion-names-of-god-the-integer.cr diff --git a/Task/9-billion-names-of-God-the-integer/EasyLang/9-billion-names-of-god-the-integer.easy b/Task/9-billion-names-of-God-the-integer/EasyLang/9-billion-names-of-god-the-integer.easy new file mode 100644 index 0000000000..31f4c0500b --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/EasyLang/9-billion-names-of-god-the-integer.easy @@ -0,0 +1,64 @@ +func[] bnadd a[] b[] . + if len a[] < len b[] : swap a[] b[] + for i = 1 to len a[] + bi = 0 + if i <= len b[] : bi = b[i] + h = a[i] + bi + c + r[] &= h mod 10000000 + c = h div 10000000 + . + if c > 0 : r[] &= c + return r[] +. +func[] bnsub a[] b[] . + for i = 1 to len a[] + ai = a[i] + bi = 0 + if i <= len b[] : bi = b[i] + bi += c + c = 0 + if bi > ai + ai += 10000000 + c = 1 + . + r[] &= ai - bi + . + while r[$] = 0 : len r[] -1 + return r[] +. +func$ str bn[] . + s$ = bn[$] + for i = len bn[] - 1 downto 1 + h$ = bn[i] + s$ &= substr "0000000" 1 (7 - len h$) & h$ + . + return s$ +. +proc parti n &p[][] . + subr upd + if k mod 2 = 1 + h[] = bnadd p[n][] p[d][] + else + h[] = bnsub p[n][] p[d][] + . + p[n][] = h[] + . + for k = 1 to n + d = n - k * (3 * k - 1) div 2 + if d < 0 : break 1 + upd + d -= k + if d < 0 : break 1 + upd + . +. +proc partitions_p n &p[][] . + p[][] = [ ] + len p[][] n + 1 + p[0][] = [ 1 ] + for i to n : parti i p[][] +. +for nn in [ 23 123 1234 12345 ] + partitions_p nn p[][] + print nn & ": " & str p[nn][] +. diff --git a/Task/9-billion-names-of-God-the-integer/Elixir/9-billion-names-of-god-the-integer.elixir b/Task/9-billion-names-of-God-the-integer/Elixir/9-billion-names-of-god-the-integer.ex similarity index 100% rename from Task/9-billion-names-of-God-the-integer/Elixir/9-billion-names-of-god-the-integer.elixir rename to Task/9-billion-names-of-God-the-integer/Elixir/9-billion-names-of-god-the-integer.ex diff --git a/Task/9-billion-names-of-God-the-integer/FutureBasic/9-billion-names-of-god-the-integer.basic b/Task/9-billion-names-of-God-the-integer/FutureBasic/9-billion-names-of-god-the-integer.basic new file mode 100644 index 0000000000..6c25428226 --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/FutureBasic/9-billion-names-of-god-the-integer.basic @@ -0,0 +1,179 @@ +// +// 9 billion names of G-D the integer +// +// Using FutureBasic 7.0.35 +// September 2025, R.W. +// + +include "gmp.incl" // GMP only (MPFR not needed here) + +_kTriMax = 25 +_kMaxP = 123456 // compile-time bound for big_p[] + +UInt64 tri(_kTriMax, _kTriMax) // the 25 by 25 triangle +mpz_t big_p(_kMaxP) // partition values P(0.._kMaxP) + +// +// Integer partition via GMP (mpz_t) +// +// Computes P(0..partMax) in global big_p[] +// big_p(xxxxx) will have _kMaxP elements +// +// At its largest sum term (123456), +// it would be greater than 10^385 or hundreds of digits +// beyond a centillion + +local fn ComputePartitions( partMax as long ) + long i, j, k + long a, b + mpz_t s + + if partMax > _kMaxP then partMax = _kMaxP + // temp accumulator + mpz_init( s ) + + // base case + mpz_set_ui( big_p(0), 1 ) + + for i = 1 to partMax + // generalized pentagonal sequence setup + j = 1 + k = 1 + b = 2 + a = 5 + + while j > 0 + // j = i - (3*k*k+k) \ 2 + // (implemented incrementally via b,a) + j = i - b + b = b + a + a = a + 3 + + if j >= 0 + if (k AND 1) <> 0 + mpz_add( s, s, big_p(j) ) + else + mpz_sub( s, s, big_p(j) ) + end if + end if + // second term at j + k + j = j + k + if j >= 0 + if (k AND 1) <> 0 + mpz_add( s, s, big_p(j) ) + else + mpz_sub( s, s, big_p(j) ) + end if + end if + k ++ + wend + + mpz_swap( big_p(i), s ) + next + + mpz_clear( s ) +end fn + +// +// Partition triangle using 64-bit ints +// p(n,k) -> # of partitions of n with +// largest part exactly k +// +local fn BuildPartitionTriangle + CFStringRef pLine, filler + pLine = @"" + filler = @" " + long n, k + + // first 3 rows are always 1's + tri(1,1) = 1 + tri(2,1) = 1 + tri(2,2) = 1 + tri(3,1) = 1 + tri(3,2) = 1 + tri(3,3) = 1 + + for n = 4 to _kTriMax + for k = 1 to n + if k * 2 > n + tri(n,k) = tri(n-1, k-1) + else + tri(n,k) = tri(n-1, k-1) + tri(n-k, k) + end if + next + next + + // display the triangle + for n = 1 to 25 + pLine = @"" + for k = 1 to n + pLine = concat(pLine, mid(str(tri(n,k)),1),@" ") + next k + pLine = concat(left(filler, 38 - len(pLine)/2) , pLine) + print pLine + next n +end fn +// +// MAIN +// ---------------------------------------------- +Window 1, @"9 Billion Names of G-D the integer",¬ +(0,0,980,540) + +long n, k, max +max = 123456 // must not exceed _kMaxP +CFStringRef pLine +pLine = @"" + +CFTimeInterval t +t = fn CACurrentMediaTime // start clock + +fn BuildPartitionTriangle + +// Initialize big_p(0..kPartMax) to 0 +for n = 0 to max + mpz_init( big_p(n) ) +next + +// Compute partitions P(0..kPartMax) +fn ComputePartitions( max ) +print@ +print @"Sums" +print @"----" + +long cxCount +cxCount = 5 +Int i +long cx(5) +cx(1) = 23 +cx(2) = 123 +cx(3) = 1234 +cx(4) = 12345 +cx(5) = 123456 + +long at +at = 1 + +for i = 1 to max + if at <= cxCount + if i = cx(at) + pLine = fn mpz_cf( 10,big_p(i) ) + print concat( @"G(", mid(str(i),1), @") = ", pLine ) + at = at + 1 + end if + else + exit for + end if +next +// +// stop the clock +print@ +printf @"Elapsed time = %.4f ms.", (fn CACurrentMediaTime - t)*1000 + +// Cleanup +for n = 0 to max + mpz_clear( big_p(n) ) +next + +HandleEvents + +// diff --git a/Task/9-billion-names-of-God-the-integer/Groovy/9-billion-names-of-god-the-integer.groovy b/Task/9-billion-names-of-God-the-integer/Groovy/9-billion-names-of-god-the-integer.groovy index fed2cfdfba..006cf36944 100644 --- a/Task/9-billion-names-of-God-the-integer/Groovy/9-billion-names-of-god-the-integer.groovy +++ b/Task/9-billion-names-of-God-the-integer/Groovy/9-billion-names-of-god-the-integer.groovy @@ -1,4 +1,4 @@ -def partitions(c) +static def partitions(c) { def p=[]; diff --git a/Task/9-billion-names-of-God-the-integer/Julia/9-billion-names-of-god-the-integer.julia b/Task/9-billion-names-of-God-the-integer/Julia/9-billion-names-of-god-the-integer.jl similarity index 100% rename from Task/9-billion-names-of-God-the-integer/Julia/9-billion-names-of-god-the-integer.julia rename to Task/9-billion-names-of-God-the-integer/Julia/9-billion-names-of-god-the-integer.jl diff --git a/Task/9-billion-names-of-God-the-integer/Kotlin/9-billion-names-of-god-the-integer.kotlin b/Task/9-billion-names-of-God-the-integer/Kotlin/9-billion-names-of-god-the-integer.kts similarity index 100% rename from Task/9-billion-names-of-God-the-integer/Kotlin/9-billion-names-of-god-the-integer.kotlin rename to Task/9-billion-names-of-God-the-integer/Kotlin/9-billion-names-of-god-the-integer.kts diff --git a/Task/9-billion-names-of-God-the-integer/OCaml/9-billion-names-of-god-the-integer.ocaml b/Task/9-billion-names-of-God-the-integer/OCaml/9-billion-names-of-god-the-integer.ml similarity index 100% rename from Task/9-billion-names-of-God-the-integer/OCaml/9-billion-names-of-god-the-integer.ocaml rename to Task/9-billion-names-of-God-the-integer/OCaml/9-billion-names-of-god-the-integer.ml diff --git a/Task/9-billion-names-of-God-the-integer/Pluto/9-billion-names-of-god-the-integer.pluto b/Task/9-billion-names-of-God-the-integer/Pluto/9-billion-names-of-god-the-integer.pluto new file mode 100644 index 0000000000..32f0b981d9 --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/Pluto/9-billion-names-of-god-the-integer.pluto @@ -0,0 +1,39 @@ +local bigint = require "pluto:bigint" +local fmt = require "fmt" + +local zero = bigint.new(0) +local one = bigint.new(1) + +local cache = {{one}} + +local function cumu(n) + if #cache <= n then + for l = #cache, n do + local r = {zero} + for x = 1, l do + local min = l - x + if x < min then min = x end + r:insert(r:back() + cache[l - x + 1][min + 1]) + end + cache:insert(r) + end + end + return cache[n + 1] +end + +local function row(n) + local r = cumu(n) + return range(1, n):map(|i| -> r[i + 1] - r[i]) +end + +print("Rows:") +for i = 1, 25 do + fmt.write("%2d: ", i) + local r = row(i) + fmt.tprint("%3s", r, #r) +end + +print("\nSums:") +for {23, 123, 1234, 12345} as i do + fmt.print("%5d: %s", i, cumu(i):back()) +end diff --git a/Task/9-billion-names-of-God-the-integer/Rebol/9-billion-names-of-god-the-integer.rebol b/Task/9-billion-names-of-God-the-integer/Rebol/9-billion-names-of-god-the-integer.rebol new file mode 100644 index 0000000000..4c937e4e34 --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/Rebol/9-billion-names-of-god-the-integer.rebol @@ -0,0 +1,101 @@ +Rebol [ + title: "Rosetta code: 9 billion names of God the integer" + file: %9_billion_names_of_God_the_integer.r3 + url: https://rosettacode.org/wiki/9_billion_names_of_God_the_integer + needs: 3.0.0 + note: {Based on Red language version} +] +names-of-god: function/with [ + row [integer!] "row number (>= 1)" + /show "Display intermediate results" + /all "When showing, print all intermediate data" +][ + ;; Validate input - require row >= 1, otherwise trigger a runtime error + assert [row >= 1] + + ;; If /show refinement is used, display results for the given row + if show [ + ;; Ensure nums/:row is computed; if not, recursively compute it + unless nums/:row [names-of-god row] + + ;; Loop from 1 to row + repeat i row [ + either all [ ;; If /all refinement is used, display extra details + probe reduce [i nums/:i sums/:i] ;; Show index, sequence, and sum + ][ + print nums/:i ;; Otherwise, just print the sequence + ] + ] + ] + + ;; Compute a new row from scratch (if row not already computed)... + unless sum: sums/:row [ + out: clear [] ;; Temporary storage for row's elements + half: to integer! row / 2 ;; Middle position of the row + + ;; Ensure all required previous rows exist; generate missing ones + if row - 1 > last: length? nums [ + repeat i row - last - 1 [ + names-of-god last + i + ] + ] + + ;; Build the `out` block for this row + repeat col row - 1 [ + ;; Special case: the middle element + either col = (half + 1) [ + append out at nums/(row - 1) half ;; Insert from previous row's middle + break ;; Stop building here + ][ + ;; General case: append sum-part of two earlier sequences + append out sum-part nums/(row - col) col + ] + ] + + ;; Compute the sum of the row + sum: 0.0 + forall out [ + sum: sum + out/1 + ] + + ;; Cache the computed row and its sum + sums/:row: sum + nums/:row: copy out + clear out + ] + sums/:row ;; Return sum of the row +][ + ;; ===== WITH BLOCK (local helper definitions and persistent state) ===== + + ;; Helper function: sum the first `count` elements from the given block `nums` + sum-part: function [nums [block!] count [integer!]][ + out: 0.0 + loop count [ + out: out + nums/1 + if empty? nums: next nums [break] ;; Stop if we've exhausted the block + ] + ;; If within integer range, convert to integer + if out <= 0#7fffffffffffffff [out: to integer! out] + out + ] + + ;; Persistent storage for each computed row (map! with row → sequence) + ;; Start with base cases: + ;; row 1 = [1] + ;; row 2 = [1 1] + nums: make map! [1 [1] 2 [1 1]] + + ;; Persistent storage for row sums (map! with row → sum) + ;; Base sums: row 1 sum = 1, row 2 sum = 2 + sums: make map! [1 1 2 2] +] + + + +print "rows: ^/" +names-of-god/show 25 + +print "^/sums: ^/" +probe names-of-god 23 +probe names-of-god 123 +probe names-of-god 1234 diff --git a/Task/9-billion-names-of-God-the-integer/Rust/9-billion-names-of-god-the-integer.rust b/Task/9-billion-names-of-God-the-integer/Rust/9-billion-names-of-god-the-integer.rs similarity index 100% rename from Task/9-billion-names-of-God-the-integer/Rust/9-billion-names-of-god-the-integer.rust rename to Task/9-billion-names-of-God-the-integer/Rust/9-billion-names-of-god-the-integer.rs diff --git a/Task/9-billion-names-of-God-the-integer/Scheme/9-billion-names-of-god-the-integer.ss b/Task/9-billion-names-of-God-the-integer/Scheme/9-billion-names-of-god-the-integer.scm similarity index 100% rename from Task/9-billion-names-of-God-the-integer/Scheme/9-billion-names-of-god-the-integer.ss rename to Task/9-billion-names-of-God-the-integer/Scheme/9-billion-names-of-god-the-integer.scm diff --git a/Task/9-billion-names-of-God-the-integer/Zig/9-billion-names-of-god-the-integer-1.zig b/Task/9-billion-names-of-God-the-integer/Zig/9-billion-names-of-god-the-integer-1.zig new file mode 100644 index 0000000000..7502e47386 --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/Zig/9-billion-names-of-god-the-integer-1.zig @@ -0,0 +1,63 @@ +const std = @import("std"); +const print = std.debug.print; +const bigint = std.math.big.int.Managed; +const eql = std.mem.eql; +const Array = std.ArrayList; +const Array1 = Array(bigint); +const Array2 = Array(Array1); +var gpa = std.heap.GeneralPurposeAllocator(.{}){}; +const allocator = gpa.allocator(); + +fn cumu(cache: *Array2, n: usize) !*Array1 { + var y = cache.items.len; + while (cache.items.len <= n) : (y += 1) { + var roww = Array1.init(allocator); + try roww.append(try bigint.init(allocator)); + for (1..y + 1) |x| { + var cache_value = try cache.items[y - x].items[@min(x, y - x)].clone(); + try cache_value.add(&cache_value, &roww.getLast()); + try roww.append(cache_value); + } + try cache.append(roww); + } + return &(cache.items[n]); +} + +fn row(cache: *Array2, n: usize) !void { + const e = try cumu(cache, n); + var v = try bigint.init(allocator); + for (0..n) |i| { + try v.sub(&e.items[i + 1], &e.items[i]); + print(" {} ", .{v}); + } + v.deinit(); + print("\n", .{}); +} + +pub fn main() !void { + var cache = Array2.init(allocator); + defer { + cache.deinit(); + } + defer { + while (cache.popOrNull()) |l| { + l.deinit(); + } + } + var cache0 = Array1.init(allocator); + var v = try bigint.init(allocator); + try v.set(1); + try cache0.append(v); + try cache.append(cache0); + + print("rows:\n", .{}); + for (1..1000) |x| { + try row(&cache, x); + } + + print("\nsums:\n", .{}); + for ([_]usize{ 23, 123, 999 }) |num| { + const r = try cumu(&cache, num); + print("{d: >4} {d}\n", .{ num, r.getLast() }); + } +} diff --git a/Task/9-billion-names-of-God-the-integer/Zig/9-billion-names-of-god-the-integer-2.zig b/Task/9-billion-names-of-God-the-integer/Zig/9-billion-names-of-god-the-integer-2.zig new file mode 100644 index 0000000000..3b8f04f057 --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/Zig/9-billion-names-of-god-the-integer-2.zig @@ -0,0 +1,35 @@ +const std = @import("std"); +const print = std.debug.print; +const bigint = std.math.big.int.Managed; +const eql = std.mem.eql; +const Array = std.ArrayList; +const Array1 = Array(bigint); +var gpa = std.heap.GeneralPurposeAllocator(.{}){}; +const allocator = gpa.allocator(); + +fn calc ( n:usize, p:*Array1) !void { + for ( 1..n+1 ) |k| { + var d:i64 = @intCast(n); + d -= @intCast(k*(3*k - 1)/2); + inline for ( 0..2 ) |_| { + if ( d < 0 ) return; + if (k&1>0) try p.items[n].add ( &p.items[n], &p.items[@intCast(d)] ) + else try p.items[n].sub ( &p.items[n], &p.items[@intCast(d)] ); + d -= @intCast(k); + } + } +} + +fn main() !void { + const s = [_]usize{ 23, 123, 1234, 12345, 123456 }; + var p = Array1.init ( allocator ); + try p.append ( try bigint.initSet ( allocator, 1 ) ); + var i:usize=1; + for ( s )|m|{ + while (i<=m):(i+=1){ + try p.append( try bigint.init(allocator) ); + try calc( i, &p ); + } + print("P({d}) = {d}\n", .{m,p.items[m]} ); + } +} diff --git a/Task/99-bottles-of-beer/8th/99-bottles-of-beer-1.8th b/Task/99-bottles-of-beer/8th/99-bottles-of-beer-1.8th new file mode 100644 index 0000000000..f07c88a955 --- /dev/null +++ b/Task/99-bottles-of-beer/8th/99-bottles-of-beer-1.8th @@ -0,0 +1,26 @@ +\ 99 bottles of beer on the wall: +[ + "no more bottles" , + "one bottle" , + ( dup . " bottles" ) +] var, bottles + +: .bottles + dup 2 n:min bottles @ caseof ; + +: .beer + .bottles . " of beer" . ; + +: .wall + .beer " on the wall" . ; + +: .take + " Take one down and pass it around" . ; + +: beers + .wall ", " . .beer '; putc cr + n:1- 0 max .take ", " . + .wall '. putc cr drop ; + +' beers 1 99 loop- +bye diff --git a/Task/99-bottles-of-beer/8th/99-bottles-of-beer-2.8th b/Task/99-bottles-of-beer/8th/99-bottles-of-beer-2.8th new file mode 100644 index 0000000000..f736dda979 --- /dev/null +++ b/Task/99-bottles-of-beer/8th/99-bottles-of-beer-2.8th @@ -0,0 +1,12 @@ +[ + ( "Just one more bottle of beer on the wall, one bottle of beer.\n" . ) , + ( I dup "%d bottles of beer on the wall, %d bottles of beer.\n" s:strfmt . ) +] constant lyrics + +: app:main + ( + dup lyrics [2,99] rot ' n:cmp a:pigeon w:exec + n:1- "Take one down, pass it around, %d bottles of beer on the wall.\n\n" s:strfmt . + ) 1 99 loop- + + "No more bottles of beer on the wall, no more bottles of beer.\n" . ; diff --git a/Task/99-bottles-of-beer/8th/99-bottles-of-beer.8th b/Task/99-bottles-of-beer/8th/99-bottles-of-beer.8th deleted file mode 100644 index fa816e4a36..0000000000 --- a/Task/99-bottles-of-beer/8th/99-bottles-of-beer.8th +++ /dev/null @@ -1,20 +0,0 @@ -\ 99 bottles of beer on the wall: -: allout "no more bottles" ; -: just-one "1 bottle" ; -: yeah! dup . " bottles" ; - -[ - ' allout , - ' just-one , - ' yeah! , -] var, bottles - -: .bottles dup 2 n:min bottles @ swap caseof ; -: .beer .bottles . " of beer" . ; -: .wall .beer " on the wall" . ; -: .take " Take one down and pass it around" . ; -: beers .wall ", " . .beer '; putc cr - n:1- 0 max .take ", " . - .wall '. putc cr drop ; - -' beers 1 99 loop- bye diff --git a/Task/99-bottles-of-beer/ALGOL-68/99-bottles-of-beer.alg b/Task/99-bottles-of-beer/ALGOL-68/99-bottles-of-beer.alg index 5ec893ef5a..194eebdb25 100644 --- a/Task/99-bottles-of-beer/ALGOL-68/99-bottles-of-beer.alg +++ b/Task/99-bottles-of-beer/ALGOL-68/99-bottles-of-beer.alg @@ -1,8 +1,10 @@ -main:( - FOR bottles FROM 99 TO 1 BY -1 DO - printf(($z-d" bottles of beer on the wall"l$, bottles)); - printf(($z-d" bottles of beer"l$, bottles)); - printf(($"Take one down, pass it around"l$)); - printf(($z-d" bottles of beer on the wall"ll$, bottles-1)) - OD -) +FOR bottles FROM 99 BY -1 TO 1 DO + STRING bottles now = whole(bottles,0) + " bottle" + IF bottles = 1 THEN "" ELSE "s" FI; + STRING bottles left = IF bottles = 1 THEN "No more" ELSE whole(bottles-1,0) FI + + " bottle" + + IF bottles = 2 THEN "" ELSE "s" FI; + print((bottles now," of beer on the wall",newline)); + print((bottles now," of beer",newline)); + print(("Take one down, pass it around",newline)); + print((bottles left," of beer on the wall",newline,newline)) +OD diff --git a/Task/99-bottles-of-beer/Ada/99-bottles-of-beer-1.ada b/Task/99-bottles-of-beer/Ada/99-bottles-of-beer-1.adb similarity index 100% rename from Task/99-bottles-of-beer/Ada/99-bottles-of-beer-1.ada rename to Task/99-bottles-of-beer/Ada/99-bottles-of-beer-1.adb diff --git a/Task/99-bottles-of-beer/Ada/99-bottles-of-beer-2.ada b/Task/99-bottles-of-beer/Ada/99-bottles-of-beer-2.adb similarity index 100% rename from Task/99-bottles-of-beer/Ada/99-bottles-of-beer-2.ada rename to Task/99-bottles-of-beer/Ada/99-bottles-of-beer-2.adb diff --git a/Task/99-bottles-of-beer/Aria/99-bottles-of-beer.aria b/Task/99-bottles-of-beer/Aria/99-bottles-of-beer.aria new file mode 100644 index 0000000000..7e36393581 --- /dev/null +++ b/Task/99-bottles-of-beer/Aria/99-bottles-of-beer.aria @@ -0,0 +1,48 @@ +struct Lyrics { + type func new(n: Int) { + assert n > 0; + return alloc(This) { + .n = n, + }; + } + + func prettyprint() { + val suffix_n = this.n == 1 ? "" : "s"; + val suffix_n_minus_1 = this.n == 2 ? "" : "s"; + return "{0} bottle{2} of beer on the wall, {0} bottle{2} of beer.\nTake one down and pass it around, {1} bottle{3} of beer on the wall.\n".format(this.n, this.n-1, suffix_n, suffix_n_minus_1); + } +} + +struct Song { + type func new(n: Int) { + assert n > 0; + return alloc(This) { + .n = n, + }; + } + + func iterator() { + return this; + } + + func next() { + if this.n == 0 { + return Box(){.done = true}; + } + + val n = this.n; + this.n -= 1; + + return Box() { + .done = false, + .value = Lyrics.new(n), + }; + } +} + +func main() { + val song = Song.new(99); + for verse in song { + println(verse); + } +} diff --git a/Task/99-bottles-of-beer/ArkScript/99-bottles-of-beer.ark b/Task/99-bottles-of-beer/ArkScript/99-bottles-of-beer.ark new file mode 100644 index 0000000000..d12274823c --- /dev/null +++ b/Task/99-bottles-of-beer/ArkScript/99-bottles-of-beer.ark @@ -0,0 +1,24 @@ +# try and get an argument from the command line invocation +(let arg + (if (>= (len sys:args) 1) + (toNumber (@ sys:args 0)) + nil)) +# if no argument was passed the default value will be 100 +(let i + (if (nil? arg) + 100 + arg)) + +(let explode-bottles (fun (n) + (if (> n 1) { + (print (string:format "{} Bottles of beer on the wall\n{} bottles of beer\nTake one down, pass it around" n n)) + (print (string:format "{} Bottles of beer on the wall." (- n 1))) + (explode-bottles (- n 1)) }) +(explode-bottles i) + +# alternative solution with a loop +(mut n i) +(while (> n 1) { + (print (string:format "{} Bottles of beer on the wall\n{} bottles of beer\nTake one down, pass it around" n n)) + (set n (- n 1)) + (print (string:format "{} Bottles of beer on the wall." n)) }) diff --git a/Task/99-bottles-of-beer/Arturo/99-bottles-of-beer.arturo b/Task/99-bottles-of-beer/Arturo/99-bottles-of-beer.arturo index 36bb34201e..a751484f40 100644 --- a/Task/99-bottles-of-beer/Arturo/99-bottles-of-beer.arturo +++ b/Task/99-bottles-of-beer/Arturo/99-bottles-of-beer.arturo @@ -6,9 +6,8 @@ loop 99..1 'i [ print ~"Take one down, pass it around!" if 1=i-1 -> s: "" - if? i>1 [ + switch i>1 [ print ~"|i-1| bottle|s| of beer on the wall!" print "" - ] - else -> print "No more bottles of beer on the wall!" + ] -> print "No more bottles of beer on the wall!" ] diff --git a/Task/99-bottles-of-beer/Ballerina/99-bottles-of-beer.ballerina b/Task/99-bottles-of-beer/Ballerina/99-bottles-of-beer.ballerina new file mode 100644 index 0000000000..d81204e77e --- /dev/null +++ b/Task/99-bottles-of-beer/Ballerina/99-bottles-of-beer.ballerina @@ -0,0 +1,11 @@ +// https://rosettacode.org/wiki/99_bottles_of_beer +import ballerina/io; + +public function main() { + foreach int i in int:range(99, 0, -1) { + io:print(i); io:println(" bottles of beer on the wall"); + io:print(i); io:println(" bottles of beer"); + io:println("Take one down, pass it around"); + io:print(i-1); io:println(" bottles of beer on the wall\n"); + } +} diff --git a/Task/99-bottles-of-beer/COBOL/99-bottles-of-beer-1.cobol b/Task/99-bottles-of-beer/COBOL/99-bottles-of-beer-1.cob similarity index 100% rename from Task/99-bottles-of-beer/COBOL/99-bottles-of-beer-1.cobol rename to Task/99-bottles-of-beer/COBOL/99-bottles-of-beer-1.cob diff --git a/Task/99-bottles-of-beer/COBOL/99-bottles-of-beer-2.cobol b/Task/99-bottles-of-beer/COBOL/99-bottles-of-beer-2.cob similarity index 100% rename from Task/99-bottles-of-beer/COBOL/99-bottles-of-beer-2.cobol rename to Task/99-bottles-of-beer/COBOL/99-bottles-of-beer-2.cob diff --git a/Task/99-bottles-of-beer/COBOL/99-bottles-of-beer-3.cobol b/Task/99-bottles-of-beer/COBOL/99-bottles-of-beer-3.cob similarity index 100% rename from Task/99-bottles-of-beer/COBOL/99-bottles-of-beer-3.cobol rename to Task/99-bottles-of-beer/COBOL/99-bottles-of-beer-3.cob diff --git a/Task/99-bottles-of-beer/Chapel/99-bottles-of-beer.chapel b/Task/99-bottles-of-beer/Chapel/99-bottles-of-beer.chpl similarity index 100% rename from Task/99-bottles-of-beer/Chapel/99-bottles-of-beer.chapel rename to Task/99-bottles-of-beer/Chapel/99-bottles-of-beer.chpl diff --git a/Task/99-bottles-of-beer/Crystal/99-bottles-of-beer.crystal b/Task/99-bottles-of-beer/Crystal/99-bottles-of-beer.cr similarity index 100% rename from Task/99-bottles-of-beer/Crystal/99-bottles-of-beer.crystal rename to Task/99-bottles-of-beer/Crystal/99-bottles-of-beer.cr diff --git a/Task/99-bottles-of-beer/Dart/99-bottles-of-beer.dart b/Task/99-bottles-of-beer/Dart/99-bottles-of-beer.dart index 3251bd7375..07a966aa75 100644 --- a/Task/99-bottles-of-beer/Dart/99-bottles-of-beer.dart +++ b/Task/99-bottles-of-beer/Dart/99-bottles-of-beer.dart @@ -57,5 +57,3 @@ class BeerSong extends Song { return theLyrics; } } - -} diff --git a/Task/99-bottles-of-beer/DuckDB/99-bottles-of-beer-1.duckdb b/Task/99-bottles-of-beer/DuckDB/99-bottles-of-beer-1.duckdb new file mode 100644 index 0000000000..3fe002df2b --- /dev/null +++ b/Task/99-bottles-of-beer/DuckDB/99-bottles-of-beer-1.duckdb @@ -0,0 +1,13 @@ +.header off +.mode list +select list_transform( range(99,-1,-1), + n -> + if (n = 0, + 'No more bottles of beer on the wall' || chr(10) + || 'no more bottles of beer.' || chr(10) + || 'Go to the store, buy some more!' || chr(10) + || '99 bottles of beer on the wall.', + n || ' bottle' || if ( n = 1, '', 's') || ' of beer on the wall' || chr(10) + || n || ' bottle' || if ( n = 1, '', 's') || ' of beer;' || chr(10) + || 'Take one down, pass it around' || chr(10) ) ) + .array_to_string(chr(10)) ; diff --git a/Task/99-bottles-of-beer/DuckDB/99-bottles-of-beer-2.duckdb b/Task/99-bottles-of-beer/DuckDB/99-bottles-of-beer-2.duckdb new file mode 100644 index 0000000000..02dd9eb97c --- /dev/null +++ b/Task/99-bottles-of-beer/DuckDB/99-bottles-of-beer-2.duckdb @@ -0,0 +1,21 @@ +.header off +.mode list + +with recursive cte as ( + select 99 as n, '' as s + union all + select n-1 as n, + if (n = 0, + 'No more bottles of beer on the wall' || chr(10) + || 'no more bottles of beer.' || chr(10) + || 'Go to the store, buy some more!' || chr(10) + || '99 bottles of beer on the wall.', + n || ' bottle' || if ( n = 1, '', 's') || ' of beer on the wall' || chr(10) + || n || ' bottle' || if ( n = 1, '', 's') || ' of beer;' || chr(10) + || 'Take one down, pass it around' || chr(10) ) + from cte + where n > -1 + ) select s + from cte + where s != '' + order by n desc ; diff --git a/Task/99-bottles-of-beer/EMal/99-bottles-of-beer.emal b/Task/99-bottles-of-beer/EMal/99-bottles-of-beer.emal index 7f8bf2daa2..4993f8c5ee 100644 --- a/Task/99-bottles-of-beer/EMal/99-bottles-of-beer.emal +++ b/Task/99-bottles-of-beer/EMal/99-bottles-of-beer.emal @@ -1,30 +1,28 @@ type NinetynineBottles -int DEFAULT_BOTTLES_COUNT = 99 +int DEFAULT_BOTTLES_COUNT ← 99 model int initialBottlesCount, bottlesCount - new by int =bottlesCount - me.initialBottlesCount = bottlesCount + new by int ←bottlesCount + me.initialBottlesCount ← bottlesCount end - fun subject = <|when(me.bottlesCount == 1, "bottle", "bottles") - fun bottles = <|when(me.bottlesCount == 0, "no more", text!me.bottlesCount) - fun goToWall = void by block - text line = me.bottles() + " " + me.subject() + " of beer on the wall, " + + fun subject ← <|when(me.bottlesCount æ 1, "bottle", "bottles") + fun bottles ← <|when(me.bottlesCount æ 0, "no more", text!me.bottlesCount) + fun goToWall ← void by block + text line ← me.bottles() + " " + me.subject() + " of beer on the wall, " + me.bottles() + " " + me.subject() + " of beer." - if me.bottlesCount == 0 do line[0] = line[0].upper() end # text can be modified + if me.bottlesCount æ 0 do line[0] ← line[0].upper() end # text can be modified writeLine(line) end - fun takeOne = logic by block + fun takeOne ← logic by block if --me.bottlesCount < 0 do return false end # cannot take a beer down writeLine("Take one down and pass it around, " + me.bottles() + " " + me.subject() + " of beer on the wall.") writeLine() return true end - fun goToStore = void by block - writeLine("Go to the store and buy some more, " + me.initialBottlesCount + - " bottles of beer on the wall.") - end - fun play = void by block + fun goToStore ← <|writeLine("Go to the store and buy some more, " + + me.initialBottlesCount + " bottles of beer on the wall.") + fun play ← void by block for ever me.goToWall() if not me.takeOne() diff --git a/Task/99-bottles-of-beer/EasyLang/99-bottles-of-beer.easy b/Task/99-bottles-of-beer/EasyLang/99-bottles-of-beer.easy index f1f30f9082..deabe7c1be 100644 --- a/Task/99-bottles-of-beer/EasyLang/99-bottles-of-beer.easy +++ b/Task/99-bottles-of-beer/EasyLang/99-bottles-of-beer.easy @@ -1,18 +1,15 @@ func$ bottle num . - if num = 1 - return "bottle" - . - return "bottles" + if num = 1 : return "1 bottle" + return num & " bottles" . -# i = 99 repeat - print i & " " & bottle i & " of beer on the wall" - print i & " " & bottle i & " of beer" + print bottle i & " of beer on the wall" + print bottle i & " of beer" print "Take one down, pass it around" i -= 1 until i = 0 - print i & " " & bottle i & " of beer on the wall" + print bottle i & " of beer on the wall" print "" . print "No more bottles of beer on the wall" diff --git a/Task/99-bottles-of-beer/Elena/99-bottles-of-beer.elena b/Task/99-bottles-of-beer/Elena/99-bottles-of-beer.elena index e88bc758db..496eaa2e0c 100644 --- a/Task/99-bottles-of-beer/Elena/99-bottles-of-beer.elena +++ b/Task/99-bottles-of-beer/Elena/99-bottles-of-beer.elena @@ -27,9 +27,9 @@ extension bottleOp }; } -public program() +public Program() { var bottles := 99; - bottles.bottleEnumerator().forEach(printingLn) + bottles.bottleEnumerator().forEach(PrintingLn) } diff --git a/Task/99-bottles-of-beer/Elixir/99-bottles-of-beer.elixir b/Task/99-bottles-of-beer/Elixir/99-bottles-of-beer-1.ex similarity index 100% rename from Task/99-bottles-of-beer/Elixir/99-bottles-of-beer.elixir rename to Task/99-bottles-of-beer/Elixir/99-bottles-of-beer-1.ex diff --git a/Task/99-bottles-of-beer/Elixir/99-bottles-of-beer-2.ex b/Task/99-bottles-of-beer/Elixir/99-bottles-of-beer-2.ex new file mode 100644 index 0000000000..21f101524c --- /dev/null +++ b/Task/99-bottles-of-beer/Elixir/99-bottles-of-beer-2.ex @@ -0,0 +1,36 @@ +last = [ + """ + 2 bottles of beer on the wall + 2 bottles of beer + Take one down, pass it around + 1 bottle of beer on the wall + """, + """ + 1 bottle of beer on the wall + 1 bottle of beer + Take one down, pass it around + No bottles of beer on the wall + """, + """ + No more bottles of beer on the wall + No more bottles of beer + Go to the store and buy some more + 99 bottles of beer on the wall + """ +] + +skeleton = fn n -> + """ + #{n} bottles of beer on the wall + #{n} bottles of beer + Take one down, pass it around + #{n - 1} bottles of beer on the wall + """ +end + +99..3 +|> Stream.map(skeleton) +|> Stream.concat(last) +|> Enum.intersperse("\n") +|> IO.iodata_to_binary() +|> IO.puts() diff --git a/Task/99-bottles-of-beer/Emacs-Lisp/99-bottles-of-beer.l b/Task/99-bottles-of-beer/Emacs-Lisp/99-bottles-of-beer.el similarity index 100% rename from Task/99-bottles-of-beer/Emacs-Lisp/99-bottles-of-beer.l rename to Task/99-bottles-of-beer/Emacs-Lisp/99-bottles-of-beer.el diff --git a/Task/99-bottles-of-beer/Euphoria/99-bottles-of-beer-1.euphoria b/Task/99-bottles-of-beer/Euphoria/99-bottles-of-beer-1.eu similarity index 100% rename from Task/99-bottles-of-beer/Euphoria/99-bottles-of-beer-1.euphoria rename to Task/99-bottles-of-beer/Euphoria/99-bottles-of-beer-1.eu diff --git a/Task/99-bottles-of-beer/Euphoria/99-bottles-of-beer-2.euphoria b/Task/99-bottles-of-beer/Euphoria/99-bottles-of-beer-2.eu similarity index 100% rename from Task/99-bottles-of-beer/Euphoria/99-bottles-of-beer-2.euphoria rename to Task/99-bottles-of-beer/Euphoria/99-bottles-of-beer-2.eu diff --git a/Task/99-bottles-of-beer/Euphoria/99-bottles-of-beer-3.euphoria b/Task/99-bottles-of-beer/Euphoria/99-bottles-of-beer-3.eu similarity index 100% rename from Task/99-bottles-of-beer/Euphoria/99-bottles-of-beer-3.euphoria rename to Task/99-bottles-of-beer/Euphoria/99-bottles-of-beer-3.eu diff --git a/Task/99-bottles-of-beer/Factor/99-bottles-of-beer-1.factor b/Task/99-bottles-of-beer/Factor/99-bottles-of-beer-1.factor new file mode 100644 index 0000000000..55688df8a7 --- /dev/null +++ b/Task/99-bottles-of-beer/Factor/99-bottles-of-beer-1.factor @@ -0,0 +1,6 @@ +USE: math.parser +100 +[ dup 1 - [ >dec " bottles of beer" append [ " on the wall" append ] keep ] bi@ + "Take one down, pass it around" -rot + first CHAR: - = [ 2drop "..." "why's all the rum gone??" ] when ! if leading character is "-" then replace with new string + 4array "\n" join print nl ] each diff --git a/Task/99-bottles-of-beer/Factor/99-bottles-of-beer.factor b/Task/99-bottles-of-beer/Factor/99-bottles-of-beer-2.factor similarity index 100% rename from Task/99-bottles-of-beer/Factor/99-bottles-of-beer.factor rename to Task/99-bottles-of-beer/Factor/99-bottles-of-beer-2.factor diff --git a/Task/99-bottles-of-beer/Goboscript/99-bottles-of-beer.gobo b/Task/99-bottles-of-beer/Goboscript/99-bottles-of-beer.gobo new file mode 100644 index 0000000000..3d8b925c28 --- /dev/null +++ b/Task/99-bottles-of-beer/Goboscript/99-bottles-of-beer.gobo @@ -0,0 +1,44 @@ +%include inflator/string + +costumes "assets/blank.svg"; + +func add_bottle(n) { + local s = "s"; + local s2 = "s"; + local n_minus_1 = $n - 1; + local end = "\n"; + + if $n == 1 { + n_minus_1 = "No more"; + s = ""; + end = ""; + } elif $n == 2 { + s2 = ""; + } + + return $n&" bottle"&s&" of beer on the wall\n" & + $n&" bottle"&s&" of beer\n" & + "Take one down, pass it around\n" & + n_minus_1&" bottle"&s2&" of beer on the wall" & end; +} + +proc do_99_bottles_of_beer { + local ret = ""; + local i = 99; + repeat 99 { + ret &= add_bottle(i); + i--; + } + + split ret, "\n"; + i = 1; + repeat length split { + log split[i]; + i++; + } +} + +onflag{main;} +proc main { + do_99_bottles_of_beer; +} diff --git a/Task/99-bottles-of-beer/Haxe/99-bottles-of-beer-1.haxe b/Task/99-bottles-of-beer/Haxe/99-bottles-of-beer-1.hx similarity index 100% rename from Task/99-bottles-of-beer/Haxe/99-bottles-of-beer-1.haxe rename to Task/99-bottles-of-beer/Haxe/99-bottles-of-beer-1.hx diff --git a/Task/99-bottles-of-beer/Haxe/99-bottles-of-beer-2.haxe b/Task/99-bottles-of-beer/Haxe/99-bottles-of-beer-2.hx similarity index 100% rename from Task/99-bottles-of-beer/Haxe/99-bottles-of-beer-2.haxe rename to Task/99-bottles-of-beer/Haxe/99-bottles-of-beer-2.hx diff --git a/Task/99-bottles-of-beer/Java/99-bottles-of-beer-5.java b/Task/99-bottles-of-beer/Java/99-bottles-of-beer-5.java new file mode 100644 index 0000000000..394eb68af8 --- /dev/null +++ b/Task/99-bottles-of-beer/Java/99-bottles-of-beer-5.java @@ -0,0 +1,76 @@ +import java.util.Scanner; + +public class NineNineBottles { + static int bottlesOfBeer = 99; + static boolean hasBeer = true; + static Scanner keyboard = new Scanner(System.in); + + public static void main(String[] args) { + beerCheck(); + keyboard.close(); + } + + private static void beerCheck() { + if(hasBeer) { + party(bottlesOfBeer); + } + + if(!hasBeer) { + System.out.println("Your ran out of beer. Would you like to go to the store?: "); + String blurryVision, fallingOver, youAreDrunk; + youAreDrunk = keyboard.nextLine(); + fallingOver = "RUHFO" + youAreDrunk.toLowerCase() + "RUHFOISafhur"; + blurryVision = fallingOver.split("[a-zA-Z]", 2).toString(); + if(blurryVision.contains("y")) + blurryVision = blurryVision.substring(0, 1).toUpperCase(); + System.out.println("You entered: " + blurryVision.toString() + fallingOver); + System.out.println("Did you mean yes?: "); + blurryVision = keyboard.nextLine(); + if(blurryVision.contains("y") || blurryVision.contains("Y") || blurryVision.contains("8") + || blurryVision.contains("2") || blurryVision.equalsIgnoreCase(youAreDrunk)) + {String beRECcheeck = blurryVision.toLowerCase(); + if(beRECcheeck.equals("y")) { + goToStore(); + beerCheck(); + } + } + } + } + + private static void party(int bottlesOfBeer) { + while(bottlesOfBeer > 1) { + putOnWall(bottlesOfBeer); + bottlesOfBeer = takeOneDown(bottlesOfBeer); + } + putLastOnWall(bottlesOfBeer); + } + + private static void putOnWall(int bottlesOfBeer) { + System.out.printf("%d bottles of beer on the wall%n", bottlesOfBeer); + + } + + private static int takeOneDown(int bottlesOfBeer) { + System.out.printf("%d bottles of beer%n", bottlesOfBeer); + System.out.println("Take one down, pass it around"); + bottlesOfBeer--; + putOnWall(bottlesOfBeer); + System.out.println(); + return bottlesOfBeer; + + } + + private static void putLastOnWall(int bottleOfBeer) { + System.out.printf("%d bottle of beer on the wall%n", bottleOfBeer); + System.out.printf("%d bottle of beer%n", bottleOfBeer); + System.out.println("Take it down, pass it around"); + bottleOfBeer--; + System.out.println("No more bottles of beer on the wall."); + hasBeer = false; + } + + private static void goToStore() { + bottlesOfBeer = 99; + hasBeer = true; + } +} diff --git a/Task/99-bottles-of-beer/Julia/99-bottles-of-beer-1.julia b/Task/99-bottles-of-beer/Julia/99-bottles-of-beer-1.jl similarity index 100% rename from Task/99-bottles-of-beer/Julia/99-bottles-of-beer-1.julia rename to Task/99-bottles-of-beer/Julia/99-bottles-of-beer-1.jl diff --git a/Task/99-bottles-of-beer/Julia/99-bottles-of-beer-2.julia b/Task/99-bottles-of-beer/Julia/99-bottles-of-beer-2.jl similarity index 100% rename from Task/99-bottles-of-beer/Julia/99-bottles-of-beer-2.julia rename to Task/99-bottles-of-beer/Julia/99-bottles-of-beer-2.jl diff --git a/Task/99-bottles-of-beer/Julia/99-bottles-of-beer-3.julia b/Task/99-bottles-of-beer/Julia/99-bottles-of-beer-3.jl similarity index 100% rename from Task/99-bottles-of-beer/Julia/99-bottles-of-beer-3.julia rename to Task/99-bottles-of-beer/Julia/99-bottles-of-beer-3.jl diff --git a/Task/99-bottles-of-beer/Kotlin/99-bottles-of-beer.kotlin b/Task/99-bottles-of-beer/Kotlin/99-bottles-of-beer.kts similarity index 100% rename from Task/99-bottles-of-beer/Kotlin/99-bottles-of-beer.kotlin rename to Task/99-bottles-of-beer/Kotlin/99-bottles-of-beer.kts diff --git a/Task/99-bottles-of-beer/Langur/99-bottles-of-beer.langur b/Task/99-bottles-of-beer/Langur/99-bottles-of-beer.langur new file mode 100644 index 0000000000..355e6adcbb --- /dev/null +++ b/Task/99-bottles-of-beer/Langur/99-bottles-of-beer.langur @@ -0,0 +1,6 @@ +for i=99; i>0; i-=1 { + writeln "{{i}} bottles of beer on the wall" + writeln "{{i}} bottles of beer" + writeln "Take one down, pass it around" + writeln "{{i-1}} bottles of beer on the wall\n" +} diff --git a/Task/99-bottles-of-beer/Lua/99-bottles-of-beer-4.lua b/Task/99-bottles-of-beer/Lua/99-bottles-of-beer-4.lua new file mode 100644 index 0000000000..5fdc0aa064 --- /dev/null +++ b/Task/99-bottles-of-beer/Lua/99-bottles-of-beer-4.lua @@ -0,0 +1,13 @@ +local bottlesCount = 99 +local word = function(n) return n == 1 and "bottle" or "bottles" end +while bottlesCount do + print (string.format("%d %s of beer on the wall, %d %s of beer", bottlesCount, word(bottlesCount),bottlesCount, word(bottlesCount))) + print ("You take one down, pass it around, ") + bottlesCount = bottlesCount - 1 + if bottlesCount > 0 then + print (string.format("%d %s of beer on the wall", bottlesCount, word(bottlesCount))) + else + print ("No more bottles of beer on the wall.") + end + if bottlesCount == 0 then bottlesCount = false end -- coud use reserved word break instead +end diff --git a/Task/99-bottles-of-beer/Lua/99-bottles-of-beer-5.lua b/Task/99-bottles-of-beer/Lua/99-bottles-of-beer-5.lua new file mode 100644 index 0000000000..8bc69c1a98 --- /dev/null +++ b/Task/99-bottles-of-beer/Lua/99-bottles-of-beer-5.lua @@ -0,0 +1,10 @@ +word = function(n) return n == 1 and "bottle" or "bottles" end + +coldOne = function (bottlesCount) + if bottlesCount < 1 then return print ("drunk, eh?") end + if bottlesCount == 1 then return print ("1 bottle of beer and it's mine!") end + print (string.format("%d %s of beer on the wall, %d %s of beer", bottlesCount, word(bottlesCount),bottlesCount, word(bottlesCount))) + print ("You take one down, pass it around, ") + print (string.format("%d %s of beer on the wall", bottlesCount-1, word(bottlesCount-1))) + coldOne ( bottlesCount - 1) +end diff --git a/Task/99-bottles-of-beer/Nutt/99-bottles-of-beer.nutt b/Task/99-bottles-of-beer/Nutt/99-bottles-of-beer.nutt index ccd2ec6780..fcac676e27 100644 --- a/Task/99-bottles-of-beer/Nutt/99-bottles-of-beer.nutt +++ b/Task/99-bottles-of-beer/Nutt/99-bottles-of-beer.nutt @@ -1,8 +1,8 @@ -module main imports native.io.output.say +module main +import $native 'io' : output#sayn -for i|->{1,2..99;<|>) do - say(""+i+" bottles of beer on the wall, "+i+" bottles of beer") - say("Take one down and pass it around, "+(i-1)+" bottles of beer on the wall.") -done - -end +funct main () : () = + [1, 2; 99]#reverse#each { + sayn "\(it) bottles of beer on the wall, \(it) bottles of beer"; + sayn "Take one down and pass it around, \(it# - 1) bottles of beer on the wall." + } diff --git a/Task/99-bottles-of-beer/OCaml/99-bottles-of-beer-1.ocaml b/Task/99-bottles-of-beer/OCaml/99-bottles-of-beer-1.ml similarity index 100% rename from Task/99-bottles-of-beer/OCaml/99-bottles-of-beer-1.ocaml rename to Task/99-bottles-of-beer/OCaml/99-bottles-of-beer-1.ml diff --git a/Task/99-bottles-of-beer/OCaml/99-bottles-of-beer-2.ocaml b/Task/99-bottles-of-beer/OCaml/99-bottles-of-beer-2.ml similarity index 100% rename from Task/99-bottles-of-beer/OCaml/99-bottles-of-beer-2.ocaml rename to Task/99-bottles-of-beer/OCaml/99-bottles-of-beer-2.ml diff --git a/Task/99-bottles-of-beer/OCaml/99-bottles-of-beer-3.ocaml b/Task/99-bottles-of-beer/OCaml/99-bottles-of-beer-3.ml similarity index 100% rename from Task/99-bottles-of-beer/OCaml/99-bottles-of-beer-3.ocaml rename to Task/99-bottles-of-beer/OCaml/99-bottles-of-beer-3.ml diff --git a/Task/99-bottles-of-beer/OCaml/99-bottles-of-beer-4.ocaml b/Task/99-bottles-of-beer/OCaml/99-bottles-of-beer-4.ml similarity index 100% rename from Task/99-bottles-of-beer/OCaml/99-bottles-of-beer-4.ocaml rename to Task/99-bottles-of-beer/OCaml/99-bottles-of-beer-4.ml diff --git a/Task/99-bottles-of-beer/Oxygene/99-bottles-of-beer.oxy b/Task/99-bottles-of-beer/Oxygene/99-bottles-of-beer-1.oxy similarity index 100% rename from Task/99-bottles-of-beer/Oxygene/99-bottles-of-beer.oxy rename to Task/99-bottles-of-beer/Oxygene/99-bottles-of-beer-1.oxy diff --git a/Task/99-bottles-of-beer/Oxygene/99-bottles-of-beer-2.oxy b/Task/99-bottles-of-beer/Oxygene/99-bottles-of-beer-2.oxy new file mode 100644 index 0000000000..5fc3a8fccb --- /dev/null +++ b/Task/99-bottles-of-beer/Oxygene/99-bottles-of-beer-2.oxy @@ -0,0 +1,21 @@ +namespace _99_beers; + +method bottles(number: Integer): String; +begin +if (number = 1) then + Result := "bottle" + else + Result := "bottles"; +end; + +begin + for n: Integer := 99 downto 1 do + begin + writeLn($"{n} {bottles(n)} of beer on the wall,"); + writeLn($"{n} {bottles(n)} of beer,"); + writeLn($"Take one down, and pass it around,"); + writeLn($"{n-1} {bottles(n-1)} of beer on the wall."); + writeLn(); + end; + readLn; +end. diff --git a/Task/99-bottles-of-beer/PascalABC.NET/99-bottles-of-beer-1.pas b/Task/99-bottles-of-beer/PascalABC.NET/99-bottles-of-beer-1.pas new file mode 100644 index 0000000000..f455395d06 --- /dev/null +++ b/Task/99-bottles-of-beer/PascalABC.NET/99-bottles-of-beer-1.pas @@ -0,0 +1,10 @@ +begin + for var i:=99 to 1 step -1 do + begin + Println(i,'bottles of beer on the wall'); + Println(i,'bottles of beer'); + Println('Take one down, pass it around'); + Println(i-1,'bottles of beer on the wall'); + Println + end; +end. diff --git a/Task/99-bottles-of-beer/PascalABC.NET/99-bottles-of-beer-2.pas b/Task/99-bottles-of-beer/PascalABC.NET/99-bottles-of-beer-2.pas new file mode 100644 index 0000000000..3ce09c9fc9 --- /dev/null +++ b/Task/99-bottles-of-beer/PascalABC.NET/99-bottles-of-beer-2.pas @@ -0,0 +1,10 @@ +begin + for var i:=99 to 1 step -1 do + begin + writeLn($'{i} bottles of beer on the wall'); + writeLn($'{i} bottles of beer'); + writeLn($'Take one down, pass it around'); + writeLn($'{i-1}bottles of beer on the wall'); + writeLn + end; +end. diff --git a/Task/99-bottles-of-beer/Plain-English/99-bottles-of-beer.plain b/Task/99-bottles-of-beer/Plain-English/99-bottles-of-beer.plain index 65fd694264..871d7a9918 100644 --- a/Task/99-bottles-of-beer/Plain-English/99-bottles-of-beer.plain +++ b/Task/99-bottles-of-beer/Plain-English/99-bottles-of-beer.plain @@ -1,26 +1,32 @@ To run: -Start up. -Sing 99 of bottles of beer on the wall. -Wait for the escape key. -Shut down. + Start up. + Sing 99 of bottles of beer on the wall. + Wait for the escape key. + Shut down. To sing a number of bottles of beer on the wall: -Put the number into a counter. -Loop. -Write the first line given the counter. -Write the second line given the counter. -Write "Take one down, pass it around" to the console. -Subtract 1 from the counter. -Write the first line given the counter. -If the counter is 0, break. -Write "" on the console. -Repeat. + Put the number into a counter. + Loop. + Write the first line given the counter. + Write the second line given the counter. + Write "Take one down, pass it around" to the console. + Subtract 1 from the counter. + Write the first line given the counter. + If the counter is 0, break. + Write "" on the console. + Repeat. To write the first line given a counter: -If the counter is 0, write "No more bottles of beer on the wall" to the console; exit. -If the counter is 1, write "1 bottle of beer on the wall" to the console; exit. -Write the counter then " bottles of beer on the wall" to the console. + If the counter is 0, + Write "No more bottles of beer on the wall" to the console; + Exit. + If the counter is 1, + Write "1 bottle of beer on the wall" to the console; + Exit. + Write the counter then " bottles of beer on the wall" to the console. To write the second line given a counter: -If the counter is 1, write "1 bottle of beer" to the console; exit. -Write the counter then " bottles of beer" to the console. + If the counter is 1, + Write "1 bottle of beer" to the console; + Exit. + Write the counter then " bottles of beer" to the console. diff --git a/Task/99-bottles-of-beer/Pluto/99-bottles-of-beer.pluto b/Task/99-bottles-of-beer/Pluto/99-bottles-of-beer.pluto new file mode 100644 index 0000000000..1e20d4e1f4 --- /dev/null +++ b/Task/99-bottles-of-beer/Pluto/99-bottles-of-beer.pluto @@ -0,0 +1,12 @@ +function pl(n) return n==1?"":"s" end + +function fmt(s) + return $"{s} bottle{pl(s)} of beer on the wall, \n" .. + $"{s} bottle{pl(s)} of beer. \n" .. + $"Take one down, pass it around, \n" .. + $"{s-1} bottle{pl(s-1)} of beer on the wall.\n\n" +end + +for i = 99, 1, -1 do + print(fmt(i)) +end diff --git a/Task/99-bottles-of-beer/REBOL/99-bottles-of-beer-1.rebol b/Task/99-bottles-of-beer/Rebol/99-bottles-of-beer-1.rebol similarity index 100% rename from Task/99-bottles-of-beer/REBOL/99-bottles-of-beer-1.rebol rename to Task/99-bottles-of-beer/Rebol/99-bottles-of-beer-1.rebol diff --git a/Task/99-bottles-of-beer/REBOL/99-bottles-of-beer-2.rebol b/Task/99-bottles-of-beer/Rebol/99-bottles-of-beer-2.rebol similarity index 100% rename from Task/99-bottles-of-beer/REBOL/99-bottles-of-beer-2.rebol rename to Task/99-bottles-of-beer/Rebol/99-bottles-of-beer-2.rebol diff --git a/Task/99-bottles-of-beer/REBOL/99-bottles-of-beer-3.rebol b/Task/99-bottles-of-beer/Rebol/99-bottles-of-beer-3.rebol similarity index 100% rename from Task/99-bottles-of-beer/REBOL/99-bottles-of-beer-3.rebol rename to Task/99-bottles-of-beer/Rebol/99-bottles-of-beer-3.rebol diff --git a/Task/99-bottles-of-beer/Red/99-bottles-of-beer.red b/Task/99-bottles-of-beer/Red/99-bottles-of-beer-1.red similarity index 100% rename from Task/99-bottles-of-beer/Red/99-bottles-of-beer.red rename to Task/99-bottles-of-beer/Red/99-bottles-of-beer-1.red diff --git a/Task/99-bottles-of-beer/Red/99-bottles-of-beer-2.red b/Task/99-bottles-of-beer/Red/99-bottles-of-beer-2.red new file mode 100644 index 0000000000..e01dbbd378 --- /dev/null +++ b/Task/99-bottles-of-beer/Red/99-bottles-of-beer-2.red @@ -0,0 +1,21 @@ +w: 99 +while [w][ + print [ + reform [ + w x: either 1 < w ["bottles"] ["bottle"] y: "of beer" z: "on the wall" "," + w x y + ] + ] + w: w - 1 + if w = 1 [remove at x length? x] + print [ + "take one down pass it around, " + either 0 < w [ + reform [w x y z] + ][ + w: false reform [ + "no more bottles " y rejoin [z "."] + ] + ] + ] +] diff --git a/Task/99-bottles-of-beer/Red/99-bottles-of-beer-3.red b/Task/99-bottles-of-beer/Red/99-bottles-of-beer-3.red new file mode 100644 index 0000000000..67973dc127 --- /dev/null +++ b/Task/99-bottles-of-beer/Red/99-bottles-of-beer-3.red @@ -0,0 +1,21 @@ +cold-one?: function [ + count [integer!] +][ + case [ + count < 1 [return print "drunk, eh?"] + count = 1 [print "1 bottle of beer and it's mine." ] + 'otherwise [ + print [count x: "bottles of beer" y: "on the wall" "," + count x + ] + print [ + "take one down pass it around, " + z: (-1 + count) + either z = 1 [replace x "s" ""][x] + y + ] + ] + ] + cold-one? -1 + count + +] diff --git a/Task/99-bottles-of-beer/Rhombus/99-bottles-of-beer.rhombus b/Task/99-bottles-of-beer/Rhombus/99-bottles-of-beer.rhombus new file mode 100644 index 0000000000..b7564c4ae9 --- /dev/null +++ b/Task/99-bottles-of-beer/Rhombus/99-bottles-of-beer.rhombus @@ -0,0 +1,13 @@ +#lang rhombus/static + +for (i in 1..100): + fun plural(n :: Int): + if n == 1: + | "" + | "s" + let bottles = 100 - i + println(@str{@(bottles) bottle@(plural(bottles)) of beer on the wall, @(bottles) bottle@(plural(bottles)) of beer.}) + println(@str{Take one down and pass it around, @(bottles - 1) bottle@(plural(bottles - 1)) of beer on the wall.}) + +println("No more bottles of beer on the wall, no more bottles of beer.") +println("Go to the store and buy some more, 99 bottles of beer on the wall.") diff --git a/Task/99-bottles-of-beer/Rust/99-bottles-of-beer-1.rust b/Task/99-bottles-of-beer/Rust/99-bottles-of-beer-1.rs similarity index 100% rename from Task/99-bottles-of-beer/Rust/99-bottles-of-beer-1.rust rename to Task/99-bottles-of-beer/Rust/99-bottles-of-beer-1.rs diff --git a/Task/99-bottles-of-beer/Rust/99-bottles-of-beer-2.rust b/Task/99-bottles-of-beer/Rust/99-bottles-of-beer-2.rs similarity index 100% rename from Task/99-bottles-of-beer/Rust/99-bottles-of-beer-2.rust rename to Task/99-bottles-of-beer/Rust/99-bottles-of-beer-2.rs diff --git a/Task/99-bottles-of-beer/Rye/99-bottles-of-beer.rye b/Task/99-bottles-of-beer/Rye/99-bottles-of-beer.rye new file mode 100644 index 0000000000..0bfe1a8f2d --- /dev/null +++ b/Task/99-bottles-of-beer/Rye/99-bottles-of-beer.rye @@ -0,0 +1,16 @@ +private { + + bottles: fn1 { = 1 |either { "bottle" } { "bottles" } } + verse1: closure { n } { .embed join [ "{} " bottles n " of beer on the wall" ] } + verse2: closure { n } { .embed join [ "{} " bottles n " of beer" ] } + verse3: does { "Take one down and pass it around, " } + + closure { n } { + prn join [ verse1 n ", " verse2 n "." newline verse3 ] + ( n - 1 :m > 0 ) |either + { verse1 m |++ "." |print , beers m } + { print "no more bottles of beer on the wall." } + } +} :beers + +99 |beers diff --git a/Task/99-bottles-of-beer/Scheme/99-bottles-of-beer.ss b/Task/99-bottles-of-beer/Scheme/99-bottles-of-beer.scm similarity index 100% rename from Task/99-bottles-of-beer/Scheme/99-bottles-of-beer.ss rename to Task/99-bottles-of-beer/Scheme/99-bottles-of-beer.scm diff --git a/Task/99-bottles-of-beer/SheerPower-4GL/99-bottles-of-beer.4gl b/Task/99-bottles-of-beer/SheerPower-4GL/99-bottles-of-beer.4gl new file mode 100644 index 0000000000..4f2fa34121 --- /dev/null +++ b/Task/99-bottles-of-beer/SheerPower-4GL/99-bottles-of-beer.4gl @@ -0,0 +1,28 @@ +declare integer n% + +for n% = 99 to 1 step -1 + print bottles$(n%); ' of beer on the wall, '; bottles$(n%); ' of beer.' + print 'Take one down and pass it around, '; bottles$(n% - 1); ' of beer on the wall.' + print +next n% + +print 'No more bottles of beer on the wall, no more bottles of beer.' +print 'Go to the store and buy some more, 99 bottles of beer on the wall.' + +! ============================================================================= +! Routine: bottles$(n%) +! +! Return the correct phrase for n% bottles: +! 0 → "no more bottles" +! 1 → "1 bottle" +! 2 or more → " bottles" +! ============================================================================= +routine bottles$(n%) + if n% = 0 then + bottles$ = 'no more bottles' + elseif n% = 1 then + bottles$ = '1 bottle' + else + bottles$ = str$(n%) + ' bottles' + end if +end routine diff --git a/Task/99-bottles-of-beer/Tailspin/99-bottles-of-beer.tailspin b/Task/99-bottles-of-beer/Tailspin/99-bottles-of-beer-1.tailspin similarity index 100% rename from Task/99-bottles-of-beer/Tailspin/99-bottles-of-beer.tailspin rename to Task/99-bottles-of-beer/Tailspin/99-bottles-of-beer-1.tailspin diff --git a/Task/99-bottles-of-beer/Tailspin/99-bottles-of-beer-2.tailspin b/Task/99-bottles-of-beer/Tailspin/99-bottles-of-beer-2.tailspin new file mode 100644 index 0000000000..2925e02e15 --- /dev/null +++ b/Task/99-bottles-of-beer/Tailspin/99-bottles-of-beer-2.tailspin @@ -0,0 +1,16 @@ +sayBottleCount templates + when <|=1> do + '1 bottle' ! + when <|=0> do + 'No bottles' ! + otherwise + '$; bottles' ! +end sayBottleCount + +'$:99..1:-1 -> +'$->sayBottleCount; of beer on the wall, +$->sayBottleCount; of beer. +Take one down, pass it around, +$ - 1 -> sayBottleCount; of beer on the wall. + +';' ! diff --git a/Task/99-bottles-of-beer/Uiua/99-bottles-of-beer.uiua b/Task/99-bottles-of-beer/Uiua/99-bottles-of-beer.uiua new file mode 100644 index 0000000000..3909ab4598 --- /dev/null +++ b/Task/99-bottles-of-beer/Uiua/99-bottles-of-beer.uiua @@ -0,0 +1,9 @@ +b ← ( + &p $$ _ bottles of beer on the wall + $$ _ bottles of beer + $$ Take one down, pass it around + $$ _ bottles of beer on the wall + $$ +) + +⍚(b.+1.-1) ⇌↘1⇡100 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 index 2d10b5487c..868c8dd512 100644 --- a/Task/99-bottles-of-beer/Uxntal/99-bottles-of-beer.uxnatl +++ b/Task/99-bottles-of-beer/Uxntal/99-bottles-of-beer.uxnatl @@ -1,63 +1,73 @@ -( uxncli 99bottles.rom ) +%\n { 0a } %\s { 20 } %\0 { 00 } +%newline { [ LIT2 \n -Console/write ] DEO } +%plural { [ LIT2 "s -Console/write ] DEO } -|10 @Console &vector $2 &read $1 &pad $4 &type $1 &write $1 &error $1 +|18 @Console/write -|0100 ( -> ) - #63 &loop - DUP - [ LIT2 0a -Console/write ] DEO - #01 EQUk ?&done - POP #01 SUB - !&loop - &done BRK +|100 -@ ( num -- ) - DUP ;dict/wall - DUP [ LIT2 0a -Console/write ] DEO - ;dict/take - #01 SUB ;dict/wall ! +#63 +&loop + DUP print/verse + newline + #01 EQUk ?/done + POP #01 SUB + !/done -@ ( num -- ) - DUP #00 EQU ?&zero - DUP #01 EQU ?&one - ;dict/bottle - [ LIT2 "s -Console/write ] DEO - !&end + &done + POP2 - &one ( num -- ) - ;dict/bottle - !&end - &zero ( num -- ) - POP ;dict/no-more - ;dict/bottle - [ LIT2 "s -Console/write ] DEO - ( >> ) - &end - ;dict/of-beer +BRK + +@print/verse ( num -- ) + DUP /bottle ;msgs/wall /str + DUP /bottle newline + ;msgs/take /str + #01 SUB /bottle ;msgs/wall !/str + +@print/bottle ( num -- ) + DUP #00 EQU ?/bottle/zero + DUP #01 EQU ?/bottle/one + /dec ;msgs/bottle /str + plural + !/bottle/end + + &bottle/one ( num -- ) + /dec ;msgs/bottle /str + !/bottle/end + + &bottle/zero ( num -- ) + POP ;msgs/no-more /str + ;msgs/bottle /str + plural ( >> ) -@ ( str -- ) - &loop - LDAk .Console/write DEO - INC2 LDAk ?&loop + &bottle/end + ;msgs/of-beer + ( >> ) + +@print/str ( str -- ) + LDAk .Console/write DEO + INC2 LDAk ?/str POP2 JMP2r -@ ( byte -- ) - DUP #64 DIV /try - DUP #0a DIV /try +@print/dec ( byte -- ) + DUP #64 DIV /dec/try + DUP #0a DIV /dec/try ( >> ) -@ ( num -- ) - #0a DIVk MUL SUB - [ LIT "0 ] ADD .Console/write DEO - JMP2r + &dec/try/num ( num -- ) + #0a DIVk MUL SUB + [ LIT "0 ] ADD .Console/write DEO + JMP2r - &try ( num -- ) - DUP ? + &dec/try ( num -- ) + DUP ?/dec/try/num 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 +@msgs [ + &no-more "No \s "more \0 + &bottle \s "bottle \0 + &of-beer \s "of \s "beer \s \0 + &wall "on \s "the \s "wall \n \0 + &take "Take \s "one \s "down, \s "pass \s "it \s "around \n \0 ] diff --git a/Task/99-bottles-of-beer/V-(Vlang)/99-bottles-of-beer.v b/Task/99-bottles-of-beer/V-(Vlang)/99-bottles-of-beer.v index 0490354be6..3e3d0cd41d 100644 --- a/Task/99-bottles-of-beer/V-(Vlang)/99-bottles-of-beer.v +++ b/Task/99-bottles-of-beer/V-(Vlang)/99-bottles-of-beer.v @@ -11,7 +11,6 @@ fn verse(beers int) { mut beer := beers - 1 mut numno := beers.str() mut elipsis := "" - if beers == 0 { numno = "No" } println("$numno bottle${plural(beers)} of beer on the wall") println("$numno bottle${plural(beers)} of beer") @@ -20,12 +19,10 @@ fn verse(beers int) { println("To the store, to buy some more") numno = "99" elipsis = "..." - } else { - println("Take one down, pass it around") } + else { println("Take one down, pass it around") } println("$numno bottle${plural(beer)} of beer on the wall${elipsis}") } - // passing time pub fn main() { for beers := 99; beers >= 0; beers-- { diff --git a/Task/99-bottles-of-beer/V/99-bottles-of-beer.v b/Task/99-bottles-of-beer/V/99-bottles-of-beer.v new file mode 100644 index 0000000000..67c9827af0 --- /dev/null +++ b/Task/99-bottles-of-beer/V/99-bottles-of-beer.v @@ -0,0 +1,12 @@ +[bottles + [newline '' puts]. + [beer + [0 =] ['No more bottles of beer' put] if + [1 =] ['One bottle of beer' put] if + [1 >] [dup put ' bottles of beer' put] if]. + [0 =] [newline] + [beer ' on the wall, ' put beer newline + 'Take one down and pass it around, ' put pred beer ' on the wall' puts newline] + tailrec]. + +99 bottles diff --git a/Task/99-bottles-of-beer/YAMLScript/99-bottles-of-beer-1.ys b/Task/99-bottles-of-beer/YAMLScript/99-bottles-of-beer-1.ys new file mode 100644 index 0000000000..30910edf41 --- /dev/null +++ b/Task/99-bottles-of-beer/YAMLScript/99-bottles-of-beer-1.ys @@ -0,0 +1,15 @@ +!ys-0 + +defn main(number=99): + each num (number .. 1): + say: | + $bottles(num) of beer on the wall, + $bottles(num) of beer. + Take one down, pass it around. + $bottles(num.--) of beer on the wall. + +defn bottles(n): + condp eq n: + 0 :: No more bottles + 1 :: 1 bottle + else : "$n bottles" diff --git a/Task/99-bottles-of-beer/YAMLScript/99-bottles-of-beer-2.ys b/Task/99-bottles-of-beer/YAMLScript/99-bottles-of-beer-2.ys new file mode 100644 index 0000000000..d830a6c4a7 --- /dev/null +++ b/Task/99-bottles-of-beer/YAMLScript/99-bottles-of-beer-2.ys @@ -0,0 +1,9 @@ +!yamlscript/v0 + +defn main(number=99): + each num (number .. 1): + say: | + $num bottles of beer on the wall, + $num bottles of beer. + Take one down, pass it around. + $(num.--) bottles of beer on the wall. 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 deleted file mode 100644 index 4aa8dbc7b3..0000000000 --- a/Task/99-bottles-of-beer/YAMLScript/99-bottles-of-beer.ys +++ /dev/null @@ -1,22 +0,0 @@ -#!/usr/bin/env ys-0 - -# Print the verses to "99 Bottles of Beer" -# -# usage: -# ys 99-bottles.ys [] - -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. - Take one down, pass it around. - $bottles(num - 1) of beer on the wall. - -defn bottles(n): - cond: - n == 0 : 'No more bottles' - n == 1 : '1 bottle' - => : "$n bottles" diff --git a/Task/A+B/11l/a+b.11l b/Task/A+B/11l/a+b.11l index 2eea3c99c2..fada22ecf1 100644 --- a/Task/A+B/11l/a+b.11l +++ b/Task/A+B/11l/a+b.11l @@ -1 +1 @@ -print(sum(input().split(‘ ’, group_delimiters' 1B).map(i -> Int(i)))) +print(sum(input().split(‘ ’, group_delimiters' 1B).map(Int))) diff --git a/Task/A+B/Ada/a+b-1.ada b/Task/A+B/Ada/a+b-1.adb similarity index 100% rename from Task/A+B/Ada/a+b-1.ada rename to Task/A+B/Ada/a+b-1.adb diff --git a/Task/A+B/Ada/a+b-2.ada b/Task/A+B/Ada/a+b-2.adb similarity index 100% rename from Task/A+B/Ada/a+b-2.ada rename to Task/A+B/Ada/a+b-2.adb diff --git a/Task/A+B/Agena/a+b.agena b/Task/A+B/Agena/a+b.agena index 5b94875c68..0ac7496582 100644 --- a/Task/A+B/Agena/a+b.agena +++ b/Task/A+B/Agena/a+b.agena @@ -1,6 +1,10 @@ scope local f := trim( io.read() ) split " "; # read a line and split into fields - local a := tonumber( f[ 1 ] ); - local b := tonumber( f[ 2 ] ); - print( a + b ) -epocs + try + local a := tonumber( f[ 1 ] ); + local b := tonumber( f[ 2 ] ); + print( a + b ) + catch in ex then + print( "Unable to add the numbers: ", tostring( ex ) ) + yrt +end diff --git a/Task/A+B/ArkScript/a+b.ark b/Task/A+B/ArkScript/a+b.ark new file mode 100644 index 0000000000..71c47670c9 --- /dev/null +++ b/Task/A+B/ArkScript/a+b.ark @@ -0,0 +1,9 @@ +(import std.String :split) +(import std.List :map :reduce) + +(let in (input)) +(let numbers (map (split in " ") (fun (t) (toNumber t)))) +(print (reduce numbers (fun (a b) + (if (nil? b) + a + (+ a b))))) diff --git a/Task/A+B/AutoIt/a+b-1.autoit b/Task/A+B/AutoIt/a+b-1.au3 similarity index 100% rename from Task/A+B/AutoIt/a+b-1.autoit rename to Task/A+B/AutoIt/a+b-1.au3 diff --git a/Task/A+B/AutoIt/a+b-2.autoit b/Task/A+B/AutoIt/a+b-2.au3 similarity index 100% rename from Task/A+B/AutoIt/a+b-2.autoit rename to Task/A+B/AutoIt/a+b-2.au3 diff --git a/Task/A+B/Ballerina/a+b.ballerina b/Task/A+B/Ballerina/a+b.ballerina new file mode 100644 index 0000000000..7c90b9d2f5 --- /dev/null +++ b/Task/A+B/Ballerina/a+b.ballerina @@ -0,0 +1,16 @@ +import ballerina/io; + +public function main() returns error? { + while true { + io:print("Enter two integers separated by a space : "); + string[] s = re ` `.split(io:readln()); + if s.length() < 2 { + io:println("Insufficient numbers, try again"); + } else { + int a = check int:fromString(s[0]); + int b = check int:fromString(s[1]); + io:println("Their sum is ", a + b, "."); + break; + } + } +} diff --git a/Task/A+B/Batch-File/a+b-3.bat b/Task/A+B/Batch-File/a+b-3.bat index f89aab8525..46420dac6d 100644 --- a/Task/A+B/Batch-File/a+b-3.bat +++ b/Task/A+B/Batch-File/a+b-3.bat @@ -1,6 +1 @@ -::aplusb.cmd -@echo off -setlocal -set /a c=%~1 -echo %c% -endlocal +doskey add=setlocal^& set a=$1^& set b=$2^& set /a res=a+b^& endlocal diff --git a/Task/A+B/Batch-File/a+b-5.bat b/Task/A+B/Batch-File/a+b-5.bat new file mode 100644 index 0000000000..3f5d39e1f4 --- /dev/null +++ b/Task/A+B/Batch-File/a+b-5.bat @@ -0,0 +1,12 @@ +@echo off +setlocal enableextensions +set /p ab= +call :setab %ab% +set /a res=a+b +echo %res% +goto:eof + +:setab +set a=%1 +set b=%2 +goto:eof diff --git a/Task/A+B/Batch-File/a+b-6.bat b/Task/A+B/Batch-File/a+b-6.bat new file mode 100644 index 0000000000..0f331e1554 --- /dev/null +++ b/Task/A+B/Batch-File/a+b-6.bat @@ -0,0 +1,6 @@ +@echo off +setlocal enableextensions +set /p ab= +set res=0 +for %%i in (%ab%) do set /a res+=%%i +echo %res% diff --git a/Task/A+B/Binary-Lambda-Calculus/a+b.blc b/Task/A+B/Binary-Lambda-Calculus/a+b.blc new file mode 100644 index 0000000000..4b57e7a05a --- /dev/null +++ b/Task/A+B/Binary-Lambda-Calculus/a+b.blc @@ -0,0 +1,2 @@ +(lambda (augend addend f x) + (augend f (addend f x))) diff --git a/Task/A+B/COBOL/a+b-1.cobol b/Task/A+B/COBOL/a+b-1.cob similarity index 100% rename from Task/A+B/COBOL/a+b-1.cobol rename to Task/A+B/COBOL/a+b-1.cob diff --git a/Task/A+B/COBOL/a+b-2.cobol b/Task/A+B/COBOL/a+b-2.cob similarity index 100% rename from Task/A+B/COBOL/a+b-2.cobol rename to Task/A+B/COBOL/a+b-2.cob diff --git a/Task/A+B/Crystal/a+b-1.crystal b/Task/A+B/Crystal/a+b-1.cr similarity index 100% rename from Task/A+B/Crystal/a+b-1.crystal rename to Task/A+B/Crystal/a+b-1.cr diff --git a/Task/A+B/Crystal/a+b-2.crystal b/Task/A+B/Crystal/a+b-2.cr similarity index 100% rename from Task/A+B/Crystal/a+b-2.crystal rename to Task/A+B/Crystal/a+b-2.cr diff --git a/Task/A+B/Delphi/a+b.delphi b/Task/A+B/Delphi/a+b.pas similarity index 100% rename from Task/A+B/Delphi/a+b.delphi rename to Task/A+B/Delphi/a+b.pas diff --git a/Task/A+B/DuckDB/a+b-1.duckdb b/Task/A+B/DuckDB/a+b-1.duckdb new file mode 100644 index 0000000000..06fc2868f4 --- /dev/null +++ b/Task/A+B/DuckDB/a+b-1.duckdb @@ -0,0 +1,5 @@ +.headers off +.mode list +select sum(c::INTEGER) +from (select unnest(regexp_extract_all(content, '[-0-9]+') ) as c + from read_text('rc-a+b.txt') ); diff --git a/Task/A+B/DuckDB/a+b-2.duckdb b/Task/A+B/DuckDB/a+b-2.duckdb new file mode 100644 index 0000000000..ce4c1aa6c7 --- /dev/null +++ b/Task/A+B/DuckDB/a+b-2.duckdb @@ -0,0 +1,2 @@ +select a+b from (select column0 as a, column1 as b +from read_csv('/dev/stdin', header=false, sep=' ')); diff --git a/Task/A+B/EMal/a+b.emal b/Task/A+B/EMal/a+b.emal index c2e2652cab..22106f56f5 100644 --- a/Task/A+B/EMal/a+b.emal +++ b/Task/A+B/EMal/a+b.emal @@ -1,17 +1,15 @@ -fun main = int by List args - text input = when(args.length == 1, args[0], ask(text, "Enter n integers separated by a space: ")) +fun main ← int by List args + text input ← when(args.length æ 1, args[0], ask(text, "Enter n integers separated by a space: ")) int sum, count for each text word in input.split(" ") - word = word.trim() + word ← word.trim() if word.isEmpty() do continue end # ignore empty words - int nr = int!word # this can raise an exception - if abs(nr) > 1000 - Event.error(0, "Integers must be in the interval [-1000, 1000]").raise() - end + int nr ← int!word # this can raise an exception + if abs(nr) > 1000 do error(0, "Integers must be in the interval [-1000, 1000]") end sum += nr ++count end - if count < 2 do Event.error(1, "At least two integers must be provided").raise() end + if count < 2 do error(1, "At least two integers must be provided") end writeLine("The sum of " + count + " integers is: " + sum) return 0 end diff --git a/Task/A+B/Ed/a+b.ed b/Task/A+B/Ed/a+b.ed new file mode 100644 index 0000000000..fdc4ec064b --- /dev/null +++ b/Task/A+B/Ed/a+b.ed @@ -0,0 +1,101 @@ +H +g/[^0-9]{1,}/s///g +,p +# decimal -> unary +g/^0+([0-9])/s//\1/ +g/^9([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiiiiii/ +g/^8([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiiiii/ +g/^7([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiiii/ +g/^6([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiii/ +g/^5([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiii/ +g/^4([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiii/ +g/^3([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iii/ +g/^2([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2ii/ +g/^1([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2i/ +g/^0([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2/ +g/^9([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiiiiii/ +g/^8([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiiiii/ +g/^7([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiiii/ +g/^6([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiii/ +g/^5([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiii/ +g/^4([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiii/ +g/^3([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iii/ +g/^2([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2ii/ +g/^1([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2i/ +g/^0([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2/ +g/^9([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiiiiii/ +g/^8([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiiiii/ +g/^7([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiiii/ +g/^6([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiii/ +g/^5([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiii/ +g/^4([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiii/ +g/^3([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iii/ +g/^2([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2ii/ +g/^1([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2i/ +g/^0([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2/ +g/^9([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiiiiii/ +g/^8([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiiiii/ +g/^7([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiiii/ +g/^6([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiii/ +g/^5([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiii/ +g/^4([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiii/ +g/^3([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iii/ +g/^2([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2ii/ +g/^1([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2i/ +g/^0([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2/ +g/^9([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiiiiii/ +g/^8([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiiiii/ +g/^7([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiiii/ +g/^6([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiii/ +g/^5([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiii/ +g/^4([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiii/ +g/^3([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iii/ +g/^2([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2ii/ +g/^1([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2i/ +g/^0([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2/ +# actual logic +,j +# unary -> decimal (for 0-10000 range) +g/i{9000}(i{0,999})/s//9\1/ +g/i{8000}(i{0,999})/s//8\1/ +g/i{7000}(i{0,999})/s//7\1/ +g/i{6000}(i{0,999})/s//6\1/ +g/i{5000}(i{0,999})/s//5\1/ +g/i{4000}(i{0,999})/s//4\1/ +g/i{3000}(i{0,999})/s//3\1/ +g/i{2000}(i{0,999})/s//2\1/ +g/i{1000}(i{0,999})/s//1\1/ +v/^[0-9]i*$/s/.*/0&/ +g/i{900}(i{0,99})/s//9\1/ +g/i{800}(i{0,99})/s//8\1/ +g/i{700}(i{0,99})/s//7\1/ +g/i{600}(i{0,99})/s//6\1/ +g/i{500}(i{0,99})/s//5\1/ +g/i{400}(i{0,99})/s//4\1/ +g/i{300}(i{0,99})/s//3\1/ +g/i{200}(i{0,99})/s//2\1/ +g/i{100}(i{0,99})/s//1\1/ +v/^[0-9]{2}i*$/s/^([0-9])(i*)$/\10\2/ +g/i{90}(i{0,9})/s//9\1/ +g/i{80}(i{0,9})/s//8\1/ +g/i{70}(i{0,9})/s//7\1/ +g/i{60}(i{0,9})/s//6\1/ +g/i{50}(i{0,9})/s//5\1/ +g/i{40}(i{0,9})/s//4\1/ +g/i{30}(i{0,9})/s//3\1/ +g/i{20}(i{0,9})/s//2\1/ +g/i{10}(i{0,9})/s//1\1/ +v/^[0-9]{3}i*$/s/^([0-9]{2})(i*)$/\10\2/ +g/i{9}/s//9/ +g/i{8}/s//8/ +g/i{7}/s//7/ +g/i{6}/s//6/ +g/i{5}/s//5/ +g/i{4}/s//4/ +g/i{3}/s//3/ +g/i{2}/s//2/ +g/i{1}/s//1/ +v/^[0-9]{4}i*$/s/^([0-9]{3})(i*)$/\10\2/ +g/^0+([0-9])/s//\1/ +,p +Q diff --git a/Task/A+B/Elena/a+b-1.elena b/Task/A+B/Elena/a+b-1.elena index a4c98a1213..d585433b10 100644 --- a/Task/A+B/Elena/a+b-1.elena +++ b/Task/A+B/Elena/a+b-1.elena @@ -1,9 +1,9 @@ import extensions; -public program() +public Program() { - var A := Integer.new(); - var B := Integer.new(); + var A := Integer.new(); + var B := Integer.new(); - console.loadLine(A,B).printLine(A + B) + Console.loadLine(A,B).printLine(A + B) } diff --git a/Task/A+B/Elena/a+b-2.elena b/Task/A+B/Elena/a+b-2.elena index 8097b76574..a1042363c6 100644 --- a/Task/A+B/Elena/a+b-2.elena +++ b/Task/A+B/Elena/a+b-2.elena @@ -1,9 +1,9 @@ import system'routines; import extensions; -public program() +public Program() { - console.printLine(console.readLine() + Console.printLine(Console.readLine() .split() .selectBy(mssgconst toInt[1]) .summarize()) diff --git a/Task/A+B/Elixir/a+b.elixir b/Task/A+B/Elixir/a+b.ex similarity index 100% rename from Task/A+B/Elixir/a+b.elixir rename to Task/A+B/Elixir/a+b.ex diff --git a/Task/A+B/Emacs-Lisp/a+b.l b/Task/A+B/Emacs-Lisp/a+b.el similarity index 100% rename from Task/A+B/Emacs-Lisp/a+b.l rename to Task/A+B/Emacs-Lisp/a+b.el diff --git a/Task/A+B/Euphoria/a+b.euphoria b/Task/A+B/Euphoria/a+b.eu similarity index 100% rename from Task/A+B/Euphoria/a+b.euphoria rename to Task/A+B/Euphoria/a+b.eu diff --git a/Task/A+B/Forth/a+b.fth b/Task/A+B/Forth/a+b-1.fth similarity index 100% rename from Task/A+B/Forth/a+b.fth rename to Task/A+B/Forth/a+b-1.fth diff --git a/Task/A+B/Forth/a+b-2.fth b/Task/A+B/Forth/a+b-2.fth new file mode 100644 index 0000000000..f83c5b0b46 --- /dev/null +++ b/Task/A+B/Forth/a+b-2.fth @@ -0,0 +1 @@ +: addab + cr . cr ; diff --git a/Task/A+B/FutureBasic/a+b.basic b/Task/A+B/FutureBasic/a+b-1.basic similarity index 100% rename from Task/A+B/FutureBasic/a+b.basic rename to Task/A+B/FutureBasic/a+b-1.basic diff --git a/Task/A+B/FutureBasic/a+b-2.basic b/Task/A+B/FutureBasic/a+b-2.basic new file mode 100644 index 0000000000..aee4ef9505 --- /dev/null +++ b/Task/A+B/FutureBasic/a+b-2.basic @@ -0,0 +1,15 @@ +void local fn InputIntegers + while ( 1 ) + CFStringRef s = input @"", @"0123456789 ", YES + if ( !s ) then end + CFArrayRef a = fn StringComponentsSeparatedByString( s, @" " ) + if ( len(a) != 2 ) then beep : continue + cls : print %(150,95),a[0];@" + ";a[1];@" = ";intval(a[0]) + intval(a[1]) + wend +end fn + +window 1, @"A+B", (0,0,290,200) +textlabel 1, @"Enter two integers separated by space(s).\nPress 'return' to calculate or 'esc' to quit.", (20,160,270,32) +fn InputIntegers + +HandleEvents diff --git a/Task/A+B/Guile/a+b.guile b/Task/A+B/Guile/a+b.guile new file mode 100644 index 0000000000..d3ef4f223d --- /dev/null +++ b/Task/A+B/Guile/a+b.guile @@ -0,0 +1,3 @@ +;;;Actually, the solution is same as that of many other Lisp dialects here +(+ (read) (read)) +;;Yes, it is neat but not strong, error prone actually. Other than this walkaround, if you dislike fetching a line in string format then parse the chars one by one by hand or byte by byte from stdin, you can use one read and do the work, with the price of typing (1 2) instead of 1 2 at the prompt since read would treat the input as a symbolic expression. So.,.there is sadly no easy way like scanf and %d %d in c unless one is willing to type ()s! diff --git a/Task/A+B/HPPPL/a+b.hpppl b/Task/A+B/HPPPL/a+b.hpppl new file mode 100644 index 0000000000..068fec62c3 --- /dev/null +++ b/Task/A+B/HPPPL/a+b.hpppl @@ -0,0 +1,6 @@ +EXPORT A_plus_B() +BEGIN +LOCAL A, B; +INPUT({A, B}); +PRINT(A + " " + B + " " + (A + B)); +END; diff --git a/Task/A+B/Julia/a+b-1.julia b/Task/A+B/Julia/a+b-1.jl similarity index 100% rename from Task/A+B/Julia/a+b-1.julia rename to Task/A+B/Julia/a+b-1.jl diff --git a/Task/A+B/Julia/a+b-2.julia b/Task/A+B/Julia/a+b-2.jl similarity index 100% rename from Task/A+B/Julia/a+b-2.julia rename to Task/A+B/Julia/a+b-2.jl diff --git a/Task/A+B/Koka/a+b.koka b/Task/A+B/Koka/a+b.koka new file mode 100644 index 0000000000..f0f1738e2d --- /dev/null +++ b/Task/A+B/Koka/a+b.koka @@ -0,0 +1,32 @@ +import std/os/readline + +// A prompt effect which retries getting input until a valid result is returned. +effect prompt + ctl delimit(): () // Captures the retry resumption + final ctl fail(): e // A failed input + +// Prompt for input, with retry until successful result +// - `message` is the original prompt +// - `err-message` is the error shown on failure +fun prompt(message: string, err-message: string, action: (string) -> a): a + var reattempt := fn() impossible() // We ensure all paths include a delimiter + with handler + raw ctl delimit() + reattempt := (fn() rcontext.resume(())) // set reattempt resumption + reattempt() // Initial try + final ctl fail() + reattempt() // Handle failure by reattempting + // Print the initial request message + println(message) + delimit() // Mark retry point + try { + action(readline()) // Read the input and apply the action + } fn(err) + // On an exception, print the error message and retry + println(err-message) + fail() // reset + +fun main() + with line <- prompt("Enter two numbers separated by space: ", "Invalid input, please enter two integers.") + val [a, b] = line.split(" ") + a.parse-int.unjust + b.parse-int.unjust diff --git a/Task/A+B/Kotlin/a+b.kotlin b/Task/A+B/Kotlin/a+b.kts similarity index 100% rename from Task/A+B/Kotlin/a+b.kotlin rename to Task/A+B/Kotlin/a+b.kts diff --git a/Task/A+B/LOLCODE/a+b.lol b/Task/A+B/LOLCODE/a+b.lol new file mode 100644 index 0000000000..711b24849b --- /dev/null +++ b/Task/A+B/LOLCODE/a+b.lol @@ -0,0 +1,9 @@ +HAI 1.2 + I HAS A VAR1 ITZ A YARN BTW DECLARE A VARIABLE FOR LATER USE + I HAS A VAR2 ITZ A YARN BTW DECLARE A VARIABLE FOR LATER USE + VISIBLE "NUMBAH 1?" + GIMMEH VAR1 BTW GET INPUT (NUMBER) INTO VARIABLE + VISIBLE "NUMBAH 2?" + GIMMEH VAR2 BTW GET INPUT (NUMBER) INTO VARIABLE + VISIBLE SUM OF VAR1 AN VAR2 +KTHXBYE diff --git a/Task/A+B/Microsoft-Small-Basic/a+b.basic b/Task/A+B/Microsoft-Small-Basic/a+b.basic new file mode 100644 index 0000000000..d35e63fe64 --- /dev/null +++ b/Task/A+B/Microsoft-Small-Basic/a+b.basic @@ -0,0 +1,14 @@ +getIntegers: +integers = TextWindow.Read() +spacePosition = Text.GetIndexOf(integers, " ") +If spacePosition = 0 Then + TextWindow.WriteLine("Please enter two integers.") + Goto getIntegers +EndIf +A = Text.GetSubText(integers, 1, spacePosition - 1) +B = Text.GetSubTextToEnd(integers, spacePosition + 1) +If A < -1000 Or A > 1000 Or B < -1000 Or B > 1000 Then + TextWindow.WriteLine("Integers are outside the range -1000 to 1000. Try again.") + Goto getIntegers +EndIf +TextWindow.WriteLine(A + B) diff --git a/Task/A+B/Nu/a+b.nu b/Task/A+B/Nu/a+b.nu index fe56af1ee0..1cb2baca8a 100644 --- a/Task/A+B/Nu/a+b.nu +++ b/Task/A+B/Nu/a+b.nu @@ -1 +1 @@ -input | parse "{a} {b}" | first | values | into int | math sum +input | split words | into int | math sum diff --git a/Task/A+B/Nutt/a+b.nutt b/Task/A+B/Nutt/a+b.nutt index 50a609c5d5..5b0625667e 100644 --- a/Task/A+B/Nutt/a+b.nutt +++ b/Task/A+B/Nutt/a+b.nutt @@ -1,7 +1,8 @@ module main -imports native.io{input.hear,output.say} +import $native 'io' [input#hear output#sayn] -vals a=hear(Int),b=hear(Int) -say(a+b) - -end +funct main () : () = + val read_int = {(hear ())#to_int#fold {0} {it}}; + val a = read_int (); + val b = read_int (); + sayn (a# + b) diff --git a/Task/A+B/OCaml/a+b.ocaml b/Task/A+B/OCaml/a+b.ml similarity index 100% rename from Task/A+B/OCaml/a+b.ocaml rename to Task/A+B/OCaml/a+b.ml diff --git a/Task/A+B/PascalABC.NET/a+b.pas b/Task/A+B/PascalABC.NET/a+b.pas new file mode 100644 index 0000000000..ac390aa674 --- /dev/null +++ b/Task/A+B/PascalABC.NET/a+b.pas @@ -0,0 +1,3 @@ +## +var (a,b) := ReadInteger2; +Writeln(a + b); diff --git a/Task/A+B/Plain-English/a+b.plain b/Task/A+B/Plain-English/a+b.plain index 92c92ca2e1..4187b423eb 100644 --- a/Task/A+B/Plain-English/a+b.plain +++ b/Task/A+B/Plain-English/a+b.plain @@ -1,17 +1,42 @@ To run: -Start up. -Read a number from the console. -Read another number from the console. -Output the sum of the number and the other number. -Wait for the escape key. -Shut down. + Start up. + Set up the console. + Write "Type the first number: " to Stdout. + Read a buffer from stdin. + Trim the buffer. + If the buffer is not any integer, + Write "Invalid input. Aborting Operation." + then the CRLF string to StdOut; + Shut down; + Exit. + Write "Type the second number: " to Stdout. + Read a second buffer from stdin. + Trim the second buffer. + If the second buffer is not any integer, + Write "Invalid input. Aborting Operation." + then the CRLF string to StdOut; + Shut down; + Exit. + Convert the buffer to a number. + Convert the second buffer to a second number. + Output the sum of the number and the second number. + Shut down. To output the sum of a number and another number: -If the number is not valid, write "Invalid input" to the console; exit. -If the other number is not valid, write "Invalid input" to the console; exit. -Write the number plus the other number then " is the sum." to the console. + If the number is not valid, + Write "Invalid input. Aborting Operation." + then the CRLF string to StdOut; + Exit. + If the other number is not valid, + Write "Invalid input. Aborting Operation." + then the CRLF string to StdOut; + Exit. + Add the other number to the number. + Convert the number to a string called result. + Write "The sum is " then the result + then the CRLF string to StdOut. To decide if a number is valid: -If the number is not greater than or equal to -1000, say no. -If the number is not less than or equal to 1000, say no. -Say yes. + If the number is less than -1000, say no. + If the number is greater than 1000, say no. + Say yes. diff --git a/Task/A+B/Pluto/a+b.pluto b/Task/A+B/Pluto/a+b.pluto new file mode 100644 index 0000000000..974f2e0a29 --- /dev/null +++ b/Task/A+B/Pluto/a+b.pluto @@ -0,0 +1,2 @@ +a, b = io.read("*n", "*n") +print(a+b) diff --git a/Task/A+B/PowerShell/a+b-1.psh b/Task/A+B/PowerShell/a+b-1.ps1 similarity index 100% rename from Task/A+B/PowerShell/a+b-1.psh rename to Task/A+B/PowerShell/a+b-1.ps1 diff --git a/Task/A+B/PowerShell/a+b-2.psh b/Task/A+B/PowerShell/a+b-2.ps1 similarity index 100% rename from Task/A+B/PowerShell/a+b-2.psh rename to Task/A+B/PowerShell/a+b-2.ps1 diff --git a/Task/A+B/PowerShell/a+b-3.psh b/Task/A+B/PowerShell/a+b-3.ps1 similarity index 100% rename from Task/A+B/PowerShell/a+b-3.psh rename to Task/A+B/PowerShell/a+b-3.ps1 diff --git a/Task/A+B/PowerShell/a+b-4.psh b/Task/A+B/PowerShell/a+b-4.ps1 similarity index 100% rename from Task/A+B/PowerShell/a+b-4.psh rename to Task/A+B/PowerShell/a+b-4.ps1 diff --git a/Task/A+B/REXX/a+b-1.rexx b/Task/A+B/REXX/a+b-1.rexx deleted file mode 100644 index 46a34f359e..0000000000 --- a/Task/A+B/REXX/a+b-1.rexx +++ /dev/null @@ -1,4 +0,0 @@ -/*REXX program obtains two numbers from the input stream (the console), shows their sum.*/ -parse pull a b /*obtain two numbers from input stream.*/ -say a+b /*display the sum to the terminal. */ - /*stick a fork in it, we're all done. */ diff --git a/Task/A+B/REXX/a+b-2.rexx b/Task/A+B/REXX/a+b-2.rexx deleted file mode 100644 index 064640ab38..0000000000 --- a/Task/A+B/REXX/a+b-2.rexx +++ /dev/null @@ -1,4 +0,0 @@ -/*REXX program obtains two numbers from the input stream (the console), shows their sum.*/ -parse pull a b /*obtain two numbers from input stream.*/ -say (a+b) / 1 /*display normalized sum to terminal. */ - /*stick a fork in it, we're all done. */ diff --git a/Task/A+B/REXX/a+b-3.rexx b/Task/A+B/REXX/a+b-3.rexx deleted file mode 100644 index 774178e64d..0000000000 --- a/Task/A+B/REXX/a+b-3.rexx +++ /dev/null @@ -1,6 +0,0 @@ -/*REXX program obtains two numbers from the input stream (the console), shows their sum.*/ -numeric digits 300 /*the default is nine decimal digits.*/ -parse pull a b /*obtain two numbers from input stream.*/ -z= (a+b) / 1 /*add and normalize sum, store it in Z.*/ -say z /*display normalized sum Z to terminal.*/ - /*stick a fork in it, we're all done. */ diff --git a/Task/A+B/REXX/a+b-4.rexx b/Task/A+B/REXX/a+b-4.rexx deleted file mode 100644 index 05e988dfb5..0000000000 --- a/Task/A+B/REXX/a+b-4.rexx +++ /dev/null @@ -1,11 +0,0 @@ -/*REXX program obtains some numbers from the input stream (the console), shows their sum*/ -numeric digits 1000 /*just in case the user gets ka-razy. */ -say 'enter some numbers to be summed:' /*display a prompt message to terminal.*/ -parse pull y /*obtain all numbers from input stream.*/ -many= words(y) /*obtain the number of numbers entered.*/ -$= 0 /*initialize the sum to zero. */ - do j=1 for many /*process each of the numbers. */ - $= $ + word(y, j) /*add one number to the sum. */ - end /*j*/ - /*stick a fork in it, we're all done. */ -say 'sum of ' many " numbers = " $/1 /*display normalized sum $ to terminal.*/ diff --git a/Task/A+B/REXX/a+b-5.rexx b/Task/A+B/REXX/a+b-5.rexx deleted file mode 100644 index 3aed91ea3f..0000000000 --- a/Task/A+B/REXX/a+b-5.rexx +++ /dev/null @@ -1,8 +0,0 @@ -/*REXX program obtains some numbers from the input stream (the console), shows their sum*/ -numeric digits 1000 /*just in case the user gets ka-razy. */ -say 'enter some numbers to be summed:' /*display a prompt message to terminal.*/ -parse pull y /*obtain all numbers from input stream.*/ -y=space(y) -y=translate(y,'+',' ') -Interpret 's='y -say 'sum of ' many " numbers = " s/1 /*display normalized sum s to terminal.*/ diff --git a/Task/A+B/REXX/a+b.rexx b/Task/A+B/REXX/a+b.rexx new file mode 100644 index 0000000000..787c3a6be7 --- /dev/null +++ b/Task/A+B/REXX/a+b.rexx @@ -0,0 +1,27 @@ +-- 23 Aug 2025 +include Setting + +say 'A+B' +say version +say +do forever + call Charout, 'REXX ' + pull x + if x = '' then + leave + parse var x a b + say + say 'As given...' + say 'A =' a + say 'B =' b + say 'A+B =' a+b + say + say 'Normalized...' + say 'A =' a/1 + say 'B =' b/1 + say 'A+B =' (a+b)/1 + say +end +exit + +include Abend diff --git a/Task/A+B/REBOL/a+b.rebol b/Task/A+B/Rebol/a+b.rebol similarity index 100% rename from Task/A+B/REBOL/a+b.rebol rename to Task/A+B/Rebol/a+b.rebol diff --git a/Task/A+B/Rust/a+b-1.rust b/Task/A+B/Rust/a+b-1.rs similarity index 100% rename from Task/A+B/Rust/a+b-1.rust rename to Task/A+B/Rust/a+b-1.rs diff --git a/Task/A+B/Rust/a+b-2.rust b/Task/A+B/Rust/a+b-2.rs similarity index 100% rename from Task/A+B/Rust/a+b-2.rust rename to Task/A+B/Rust/a+b-2.rs diff --git a/Task/A+B/Rye/a+b-1.rye b/Task/A+B/Rye/a+b-1.rye new file mode 100644 index 0000000000..e2cff104bd --- /dev/null +++ b/Task/A+B/Rye/a+b-1.rye @@ -0,0 +1,5 @@ +rye .stdin ; +|Read\string ; "123 321" +|load ; [ 123 321 ] +|apply* ?_+ ; 444 +|print diff --git a/Task/A+B/Rye/a+b-2.rye b/Task/A+B/Rye/a+b-2.rye new file mode 100644 index 0000000000..f929e645ca --- /dev/null +++ b/Task/A+B/Rye/a+b-2.rye @@ -0,0 +1 @@ +echo "5 2" | rye -do 'rye .stdin .Read\string .load .apply* ?_+' diff --git a/Task/A+B/Scheme/a+b.ss b/Task/A+B/Scheme/a+b.scm similarity index 100% rename from Task/A+B/Scheme/a+b.ss rename to Task/A+B/Scheme/a+b.scm diff --git a/Task/A+B/TAV/a+b.tav b/Task/A+B/TAV/a+b.tav new file mode 100644 index 0000000000..29b223afca --- /dev/null +++ b/Task/A+B/TAV/a+b.tav @@ -0,0 +1,6 @@ +main(parms):+ + ?# lne =: file () give lines \ void is standard input + ab =: string lne split by many of #Whitespace + a =: string ab[1] as integer + b =: string ab[2] as integer + print a + b diff --git a/Task/A+B/Uiua/a+b.uiua b/Task/A+B/Uiua/a+b.uiua new file mode 100644 index 0000000000..4a62fbacd3 --- /dev/null +++ b/Task/A+B/Uiua/a+b.uiua @@ -0,0 +1,5 @@ +/+∵⋕⊜□≠@ .&sc +
    +{{out|input=3 4}} +
    +7
    diff --git a/Task/A+B/VBScript/a+b-1.vb b/Task/A+B/VBScript/a+b-1.vbs
    similarity index 100%
    rename from Task/A+B/VBScript/a+b-1.vb
    rename to Task/A+B/VBScript/a+b-1.vbs
    diff --git a/Task/A+B/VBScript/a+b-2.vb b/Task/A+B/VBScript/a+b-2.vbs
    similarity index 100%
    rename from Task/A+B/VBScript/a+b-2.vb
    rename to Task/A+B/VBScript/a+b-2.vbs
    diff --git a/Task/A+B/VHDL/a+b.vhdl b/Task/A+B/VHDL/a+b.vhd
    similarity index 100%
    rename from Task/A+B/VHDL/a+b.vhdl
    rename to Task/A+B/VHDL/a+b.vhd
    diff --git a/Task/A+B/X86-64-Assembly/a+b.x86-64 b/Task/A+B/X86-64-Assembly/a+b.x86-64
    new file mode 100644
    index 0000000000..6254ca0053
    --- /dev/null
    +++ b/Task/A+B/X86-64-Assembly/a+b.x86-64
    @@ -0,0 +1,150 @@
    +format ELF64 executable 3
    +entry start
    +bsize equ 24
    +
    +segment executable readable
    +start:
    +    pop    rdx
    +    cmp    rdx,    1
    +    jg     .getargv0
    +    mov    qword[avar], 0
    +    mov    qword[bvar], 0
    +    jmp    .calculate
    + .getargv0:
    +    pop    rdi
    +    pop    rdi
    +    call   atoq
    +    mov    qword[avar], rax
    +    cmp    rdx,     2
    +    jg     .getargv1
    +    mov    qword[bvar], 0
    +    jmp    .calculate
    + .getargv1:
    +    pop    rdi
    +    call   atoq
    +    mov    qword[bvar], rax
    + .calculate:
    +    xor    rdi,    rdi
    +    add    rdi,    qword[avar]
    +    add    rdi,    qword[bvar]
    +    call   printq
    + .exit0:
    +    mov    rax,    60
    +    xor    rdi,    rdi
    +    syscall
    +
    +atoq:
    +    push r8
    +    push r9
    +    push rdi
    +    push rsi
    +    push rdx
    +    push rcx
    +    xor  rcx, rcx
    +    xor  rax, rax
    +    xor  r8, r8
    +    mov  r9, 1
    +    cmp  byte[rdi], 0
    +    jz  .exit
    +    cmp byte[rdi], '-'
    +    jne .stbegin
    +    mov r9, -1
    +    inc rdi
    +  .stbegin:
    +    cmp byte[rdi], '0'
    +    jl  .return
    +    cmp byte[rdi], '9'
    +    jg  .return
    +  .stloop:
    +    cmp byte[rdi + r8], '0'
    +    jl .calc0
    +    cmp byte[rdi + r8], '9'
    +    jg .calc0
    +    mov sil, byte[rdi + r8]
    +    sub rsi, '0'
    +    push rsi
    +    inc r8
    +    jmp .stloop
    +  .calc0:
    +    xor rcx, rcx
    +    mov rdi,  10
    +    mov rsi, 1
    +  .calc1:
    +    pop rax
    +    mul rsi
    +    add rcx, rax
    +    dec r8
    +    jz  .return
    +    mov rax, rsi
    +    mul rdi
    +    mov rsi, rax
    +    jmp .calc1
    +  .return:
    +    xor rdx, rdx
    +    mov rax, rcx
    +    imul r9
    +  .exit:
    +    pop rcx
    +    pop rdx
    +    pop rsi
    +    pop rdi
    +    pop r9
    +    pop r8
    +    ret
    +
    +printq:
    +    push   r9
    +    push   rdi
    +    push   rsi
    +    push   rdx
    +    mov    rax,    rdi
    +    mov    r9,    bsize
    +    dec    r9
    +    mov    rsi,   10
    +    sub    rsp,   bsize
    +    sub    rax,    0
    +    jns    .stloop
    +    neg    rax
    +  .stloop:
    +    xor    rdx,   rdx
    +    div    rsi
    +    add    dl,   '0'
    +    mov    byte[rsp + r9], dl
    +    sub    rax,    0
    +    jz     .negtest
    +    dec    r9
    +    jmp .stloop
    +  .negtest:
    +    sub    rdi,    0
    +    jns    .printit
    +    dec    r9
    +    mov    byte[rsp + r9], '-'
    +  .printit:
    +    mov    rdx, bsize
    +    sub    rdx, r9
    +    mov    rsi, rsp
    +    add    rsi, r9
    +    mov    rdi, 1
    +    mov    rax, 1
    +    syscall
    +    sub    rsp, 8
    +    mov    byte[rsp], 0x0a
    +    mov    rax, 1
    +    mov    rdi, 1
    +    mov    rsi, rsp
    +    mov    rdx, 1
    +    syscall
    +    add    rsp, 8
    +  .restores:
    +    add    rsp, bsize
    +    mov    rax, rdx
    +    pop    rdx
    +    pop    rsi
    +    pop    rdi
    +    pop    r9
    +  .return:
    +    ret
    +
    +segment readable writable
    +avar: rq 1
    +bvar: rq 1
    diff --git a/Task/A+B/ZED/a+b.zed b/Task/A+B/ZED/a+b.zed
    index 6c28d79b86..b3605ef199 100644
    --- a/Task/A+B/ZED/a+b.zed
    +++ b/Task/A+B/ZED/a+b.zed
    @@ -1,14 +1,14 @@
     (A+B)
    -comment:
    +READ AND ADD
     #true
     (+) (read) (read)
     
     (+) one two
    -comment:
    +=========
     #true
     (003) "+" one two
     
     (read)
    -comment:
    +=========
     #true
     (001) "read"
    diff --git a/Task/A+B/Zig/a+b.zig b/Task/A+B/Zig/a+b.zig
    new file mode 100644
    index 0000000000..378622f54f
    --- /dev/null
    +++ b/Task/A+B/Zig/a+b.zig
    @@ -0,0 +1,18 @@
    +const std = @import("std");
    +
    +pub fn main() !void {
    +    var buf: [1024]u8 = undefined;
    +    const reader = std.io.getStdIn().reader();
    +    const stdout = std.io.getStdOut().writer();
    +    try stdout.writeAll("Enter two integers separated by a space: ");
    +    const input = try reader.readUntilDelimiter(&buf, '\n');
    +    const text = std.mem.trimRight(u8, input, "\r\n");
    +
    +    var it = std.mem.tokenizeScalar(u8, text, ' ');
    +
    +    const a = try std.fmt.parseInt(i64, it.next().?, 10);
    +    const b = try std.fmt.parseInt(i64, it.next().?, 10);
    +
    +
    +    try stdout.print("{d}\n", .{a + b});
    +}
    diff --git a/Task/ABC-problem/8080-Assembly/abc-problem.8080 b/Task/ABC-problem/8080-Assembly/abc-problem.8080
    index e6c7c4d5f4..1c9a496782 100644
    --- a/Task/ABC-problem/8080-Assembly/abc-problem.8080
    +++ b/Task/ABC-problem/8080-Assembly/abc-problem.8080
    @@ -1,77 +1,77 @@
    -		org	100h
    -		jmp	test
    -		;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
    -		;;; Subroutine 'blocks': takes a $-terminated string in
    -		;;; DE containing a word, and checks whether it can be
    -		;;; written with the blocks.
    -		;;; Returns: carry flag set if word is accepted.
    -		;;; Uses registers: A, B, D, E, H, L
    -blocks:		push	d		; Store string pointer
    -		lxi	h,blockslist	; At the start, all blocks are
    -		lxi	d,blocksavail	; available
    -		mvi	b,40
    -blocksinit:	mov	a,m
    -		stax	d
    -		inx	h
    -		inx	d
    -		dcr	b
    -		jnz	blocksinit
    -		pop	d		; Restore string pointer
    -blockschar:	ldax	d		; Get current character
    -		cpi	'$'		; End of string?
    -		stc			; Set carry flag (accept string)
    -		rz			; And then we're done
    -		ani	0DFh		; Make uppercase
    -		lxi	h,blocksavail	; Is it available?
    -		mvi	b,40
    -blockscheck:	cmp	m
    -		jz	blocksaccept	; Yes, we found it
    -		inx	h		; Try next available char
    -		dcr	b
    -		jnz	blockscheck
    -		ana	a		; Char unavailable, clear
    -		ret			; carry and stop.
    -blocksaccept:	mvi	m,0		; We've now used this char
    -		mov	a,l		; And its blockmate
    -		xri	1
    -		mov	l,a
    -		mvi	m,0
    -		inx	d		; Try next char in string
    -		jmp	blockschar
    -		;; Note: 'blocksavail' must not cross page boundary
    -blockslist:	db	'BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM'
    -blocksavail:	ds	40
    -		;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
    -		;;; Test code: run the subroutine on the given words.
    -test:		lxi	h,words
    -doword:		mov	e,m		; Get pointer to next word
    -		inx	h
    -		mov	d,m
    -		inx	h
    -		mov	a,e		; If zero, end of word list
    -		ora	d
    -		rz
    -		push	h		; Save pointer to list
    -		push	d		; Save pointer to word
    -		mvi	c,9		; Write word to console
    -		call	5
    -		pop	d		; Retrieve word ponter
    -		call	blocks		; Run the 'blocks' routine
    -		lxi	d,yes		; Say 'yes',
    -		jc	yesno		; if the carry is set.
    -		lxi	d,no		; Otherwise, say 'no'.
    -yesno:		mvi	c,9
    -		call	5
    -		pop	h		; Restore list pointer
    -		jmp	doword		; Do next word
    -yes:		db	': Yes',13,10,'$'
    -no:		db	': No',13,10,'$'
    -words:		dw	wrda,wrdbark,wrdbook,wrdtreat,wrdcommon
    -		dw	wrdsquad,wrdconfuse,0
    -wrda:		db	'A$'
    -wrdbark:	db	'BARK$'
    -wrdbook:	db	'BOOK$'
    -wrdtreat:	db	'TREAT$'
    -wrdcommon:	db	'COMMON$'
    -wrdsquad:	db	'SQUAD$'
    -wrdconfuse:	db	'CONFUSE$'
    +    org   100h
    +      jmp   test
    +      ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
    +      ;;; Subroutine 'blocks': takes a $-terminated string in
    +      ;;; DE containing a word, and checks whether it can be
    +      ;;; written with the blocks.
    +      ;;; Returns: carry flag set if word is accepted.
    +      ;;; Uses registers: A, B, D, E, H, L
    +blocks:     push  d     ; Store string pointer
    +      lxi   h,blockslist   ; At the start, all blocks are
    +      lxi   d,blocksavail  ; available
    +      mvi   b,40
    +blocksinit: mov   a,m
    +      stax  d
    +      inx   h
    +      inx   d
    +      dcr   b
    +      jnz   blocksinit
    +      pop   d     ; Restore string pointer
    +blockschar: ldax  d     ; Get current character
    +      cpi   '$'      ; End of string?
    +      stc         ; Set carry flag (accept string)
    +      rz       ; And then we're done
    +      ani   0DFh     ; Make uppercase
    +      lxi   h,blocksavail  ; Is it available?
    +      mvi   b,40
    +blockscheck:   cmp   m
    +      jz blocksaccept   ; Yes, we found it
    +      inx   h     ; Try next available char
    +      dcr   b
    +      jnz   blockscheck
    +      ana   a     ; Char unavailable, clear
    +      ret         ; carry and stop.
    +blocksaccept:  mvi   m,0      ; We've now used this char
    +      mov   a,l      ; And its blockmate
    +      xri   1
    +      mov   l,a
    +      mvi   m,0
    +      inx   d     ; Try next char in string
    +      jmp   blockschar
    +      ;; Note: 'blocksavail' must not cross page boundary
    +blockslist: db 'BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM'
    +blocksavail:   ds 40
    +      ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
    +      ;;; Test code: run the subroutine on the given words.
    +test:    lxi   h,words
    +doword:     mov   e,m      ; Get pointer to next word
    +      inx   h
    +      mov   d,m
    +      inx   h
    +      mov   a,e      ; If zero, end of word list
    +      ora   d
    +      rz
    +      push  h     ; Save pointer to list
    +      push  d     ; Save pointer to word
    +      mvi   c,9      ; Write word to console
    +      call  5
    +      pop   d     ; Retrieve word ponter
    +      call  blocks      ; Run the 'blocks' routine
    +      lxi   d,yes    ; Say 'yes',
    +      jc yesno    ; if the carry is set.
    +      lxi   d,no     ; Otherwise, say 'no'.
    +yesno:      mvi   c,9
    +      call  5
    +      pop   h     ; Restore list pointer
    +      jmp   doword      ; Do next word
    +yes:     db ': Yes',13,10,'$'
    +no:      db ': No',13,10,'$'
    +words:      dw wrda,wrdbark,wrdbook,wrdtreat,wrdcommon
    +      dw wrdsquad,wrdconfuse,0
    +wrda:    db 'A$'
    +wrdbark: db 'BARK$'
    +wrdbook: db 'BOOK$'
    +wrdtreat:   db 'TREAT$'
    +wrdcommon:  db 'COMMON$'
    +wrdsquad:   db 'SQUAD$'
    +wrdconfuse: db 'CONFUSE$'
    diff --git a/Task/ABC-problem/8086-Assembly/abc-problem.8086 b/Task/ABC-problem/8086-Assembly/abc-problem.8086
    index ca056dc17a..260f99738a 100644
    --- a/Task/ABC-problem/8086-Assembly/abc-problem.8086
    +++ b/Task/ABC-problem/8086-Assembly/abc-problem.8086
    @@ -1,63 +1,63 @@
    -	cpu	8086
    -	bits	16
    -	org	100h
    -section	.text
    -	jmp	demo
    -	;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
    -	;;; Subroutine "blocks": see if the $-terminated string in DS:BX
    -	;;; can be written with the blocks.
    -	;;; Returns: carry flag set if word is accepted.
    -	;;; Uses registers: AL, BX, CX, SI, DI
    -	;;; Assumes CS=DS=ES
    -blocks:	mov	si,.list	; Set all blocks available
    -	mov	di,.avail
    -	mov	cx,20
    -	rep	movsw
    -.char:	mov 	al,[bx]		; Get current character
    -	inc	bx
    -	cmp	al,'$'		; Are we at the end?
    -	je	.ok		; Then the string is accepted
    -	mov	cx,40		; If not, check if block is available
    -	mov	di,.avail
    -	repne	scasb
    -	test	cx,cx		; This clears the carry flag
    -	jz	.out		; If zero, block is not available
    -	dec	di		; Zero out the block we found
    -	mov	[di],ch		; CH is guaranteed 0 here
    -	xor	di,1		; Point at other character on block
    -	mov	[di],ch		; Zero out that one too.
    -	jmp	.char
    -.ok:	stc
    -.out:	ret
    -.list:	db	'BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM'
    -.avail:	db	'                                        '
    -	;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
    -	;;; Test code: run the subroutine on the given words
    -demo:	mov	bp,words
    -wrd:	mov	dx,[bp]		; Get word
    -	test	dx,dx		; End of words?
    -	jz	stop
    -	mov	ah,9		; Print word
    -	int	21h
    -	mov	bx,dx		; Run subroutine
    -	call	blocks
    -	mov	dx,yes		; Print yes or no depending on carry
    -	jc	print
    -	mov	dx,no
    -print:	mov	ah,9
    -	int	21h
    -	inc	bp
    -	inc	bp
    -	jmp	wrd
    -stop:	ret
    -section	.data
    -yes:	db	': Yes',13,10,'$'
    -no:	db	': No',13,10,'$'
    -words:	dw	.a,.bark,.book,.treat,.cmn,.squad,.confs,0
    -.a:	db	'A$'
    -.bark:	db	'BARK$'
    -.book:	db	'BOOK$'
    -.treat:	db	'TREAT$'
    -.cmn:	db	'COMMON$'
    -.squad:	db	'SQUAD$'
    -.confs:	db	'CONFUSE$'
    +  cpu   8086
    +   bits  16
    +   org   100h
    +section  .text
    +   jmp   demo
    +   ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
    +   ;;; Subroutine "blocks": see if the $-terminated string in DS:BX
    +   ;;; can be written with the blocks.
    +   ;;; Returns: carry flag set if word is accepted.
    +   ;;; Uses registers: AL, BX, CX, SI, DI
    +   ;;; Assumes CS=DS=ES
    +blocks:  mov   si,.list ; Set all blocks available
    +   mov   di,.avail
    +   mov   cx,20
    +   rep   movsw
    +.char:   mov   al,[bx]     ; Get current character
    +   inc   bx
    +   cmp   al,'$'      ; Are we at the end?
    +   je .ok      ; Then the string is accepted
    +   mov   cx,40    ; If not, check if block is available
    +   mov   di,.avail
    +   repne scasb
    +   test  cx,cx    ; This clears the carry flag
    +   jz .out     ; If zero, block is not available
    +   dec   di    ; Zero out the block we found
    +   mov   [di],ch     ; CH is guaranteed 0 here
    +   xor   di,1     ; Point at other character on block
    +   mov   [di],ch     ; Zero out that one too.
    +   jmp   .char
    +.ok:  stc
    +.out: ret
    +.list:   db 'BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM'
    +.avail:  db '                                        '
    +   ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
    +   ;;; Test code: run the subroutine on the given words
    +demo: mov   bp,words
    +wrd:  mov   dx,[bp]     ; Get word
    +   test  dx,dx    ; End of words?
    +   jz stop
    +   mov   ah,9     ; Print word
    +   int   21h
    +   mov   bx,dx    ; Run subroutine
    +   call  blocks
    +   mov   dx,yes      ; Print yes or no depending on carry
    +   jc print
    +   mov   dx,no
    +print:   mov   ah,9
    +   int   21h
    +   inc   bp
    +   inc   bp
    +   jmp   wrd
    +stop: ret
    +section  .data
    +yes:  db ': Yes',13,10,'$'
    +no:   db ': No',13,10,'$'
    +words:   dw .a,.bark,.book,.treat,.cmn,.squad,.confs,0
    +.a:   db 'A$'
    +.bark:   db 'BARK$'
    +.book:   db 'BOOK$'
    +.treat:  db 'TREAT$'
    +.cmn: db 'COMMON$'
    +.squad:  db 'SQUAD$'
    +.confs:  db 'CONFUSE$'
    diff --git a/Task/ABC-problem/8th/abc-problem.8th b/Task/ABC-problem/8th/abc-problem.8th
    index f5b7f80c51..6869fcd656 100644
    --- a/Task/ABC-problem/8th/abc-problem.8th
    +++ b/Task/ABC-problem/8th/abc-problem.8th
    @@ -171,8 +171,8 @@ var ix
       ' chkokpath s:each                          \ | path
       rdrop                                       \
       success @                                   \ success
    -	if                                          \
    -	  break                                     \
    +   if                                          \
    +     break                                     \
       then
       ;
     
    diff --git a/Task/ABC-problem/ALGOL-68/abc-problem.alg b/Task/ABC-problem/ALGOL-68/abc-problem.alg
    index 524af00c33..11c3a41ade 100644
    --- a/Task/ABC-problem/ALGOL-68/abc-problem.alg
    +++ b/Task/ABC-problem/ALGOL-68/abc-problem.alg
    @@ -1,21 +1,14 @@
    +# ABC problem:                                                               #
     # determine whether we can spell words with a set of blocks                  #
     
    -# construct the list of blocks                                               #
    -[][]STRING blocks = ( ( "B", "O" ), ( "X", "K" ), ( "D", "Q" ), ( "C", "P" )
    -                    , ( "N", "A" ), ( "G", "T" ), ( "R", "E" ), ( "T", "G" )
    -                    , ( "Q", "D" ), ( "F", "S" ), ( "J", "W" ), ( "H", "U" )
    -                    , ( "V", "I" ), ( "A", "N" ), ( "O", "B" ), ( "E", "R" )
    -                    , ( "F", "S" ), ( "L", "Y" ), ( "P", "C" ), ( "Z", "M" )
    -                    );
    -
     # Returns TRUE if we can spell the word using the blocks, FALSE otherwise    #
     # Returns TRUE for an empty string                                           #
    -PROC can spell = ( STRING word, [][]STRING blocks )BOOL:
    +PROC can spell = ( STRING word, [][]STRING block set )BOOL:
         BEGIN
     
             # construct a set of flags to indicate whether the blocks are used   #
             # or not                                                             #
    -        [ 1 LWB blocks : 1 UPB blocks ]BOOL used;
    +        [ 1 LWB block set : 1 UPB block set ]BOOL used;
             FOR block pos FROM LWB used TO UPB used
             DO
                 used[ block pos ] := FALSE
    @@ -34,11 +27,11 @@ PROC can spell = ( STRING word, [][]STRING blocks )BOOL:
     
                 # look through the unused blocks for the current letter          #
                 BOOL found := FALSE;
    -            FOR block pos FROM 1 LWB blocks TO 1 UPB blocks
    +            FOR block pos FROM 1 LWB block set TO 1 UPB block set
                 WHILE NOT found
                 DO
    -                IF  (  c = blocks[ block pos ][ 1 ][ 1 ]
    -                    OR c = blocks[ block pos ][ 2 ][ 1 ]
    +                IF  (  c = block set[ block pos ][ 1 ][ 1 ]
    +                    OR c = block set[ block pos ][ 2 ][ 1 ]
                         )
                     AND NOT used[ block pos ]
                     THEN
    @@ -56,25 +49,33 @@ PROC can spell = ( STRING word, [][]STRING blocks )BOOL:
         END; # can spell #
     
     
    -main: (
    +# main # (
    +
    +    [][]STRING abc blocks # construct the list of blocks                     #
    +                  = ( ( "B", "O" ), ( "X", "K" ), ( "D", "Q" ), ( "C", "P" )
    +                    , ( "N", "A" ), ( "G", "T" ), ( "R", "E" ), ( "T", "G" )
    +                    , ( "Q", "D" ), ( "F", "S" ), ( "J", "W" ), ( "H", "U" )
    +                    , ( "V", "I" ), ( "A", "N" ), ( "O", "B" ), ( "E", "R" )
    +                    , ( "F", "S" ), ( "L", "Y" ), ( "P", "C" ), ( "Z", "M" )
    +                    );
     
         # test the can spell procedure                                           #
    -    PROC test can spell = ( STRING word, [][]STRING blocks )VOID:
    +    PROC test can spell = ( STRING word, [][]STRING block set )VOID:
             write( ( ( "can spell: """
                      + word
                      + """ -> "
    -                 + IF can spell( word, blocks ) THEN "yes" ELSE "no" FI
    +                 + IF can spell( word, block set ) THEN "yes" ELSE "no" FI
                      )
                    , newline
                    )
                  );
     
    -    test can spell( "A",       blocks );
    -    test can spell( "BaRK",    blocks );
    -    test can spell( "BOOK",    blocks );
    -    test can spell( "TREAT",   blocks );
    -    test can spell( "COMMON",  blocks );
    -    test can spell( "SQUAD",   blocks );
    -    test can spell( "CONFUSE", blocks )
    +    test can spell( "A",       abc blocks );
    +    test can spell( "BaRK",    abc blocks );
    +    test can spell( "BOOK",    abc blocks );
    +    test can spell( "TREAT",   abc blocks );
    +    test can spell( "COMMON",  abc blocks );
    +    test can spell( "SQUAD",   abc blocks );
    +    test can spell( "CONFUSE", abc blocks )
     
     )
    diff --git a/Task/ABC-problem/Ada/abc-problem.ada b/Task/ABC-problem/Ada/abc-problem.adb
    similarity index 100%
    rename from Task/ABC-problem/Ada/abc-problem.ada
    rename to Task/ABC-problem/Ada/abc-problem.adb
    diff --git a/Task/ABC-problem/Arturo/abc-problem.arturo b/Task/ABC-problem/Arturo/abc-problem.arturo
    index 7ec68fd2ef..5365095039 100644
    --- a/Task/ABC-problem/Arturo/abc-problem.arturo
    +++ b/Task/ABC-problem/Arturo/abc-problem.arturo
    @@ -16,8 +16,8 @@ canMakeWord?: function [wrd][
         ref: new blocks
         loop split wrd 'chr [
             cib: charInBlock chr ref
    -        if? cib = ø [ return false ]
    -        else        [ ref: remove ref .index cib ]
    +        switch cib = ø [ return false ]
    +                       [ ref: remove ref .index cib ]
         ]
         return true
     ]
    diff --git a/Task/ABC-problem/AutoHotkey/abc-problem-1.ahk b/Task/ABC-problem/AutoHotkey/abc-problem-1.ahk
    index 448f692c2b..d92688964d 100644
    --- a/Task/ABC-problem/AutoHotkey/abc-problem-1.ahk
    +++ b/Task/ABC-problem/AutoHotkey/abc-problem-1.ahk
    @@ -1,24 +1,24 @@
     isWordPossible(blocks, word){
    -	o := {}
    -	loop, parse, blocks, `n, `r
    -		o.Insert(A_LoopField)
    -	loop, parse, word
    -		if !(r := isWordPossible_contains(o, A_LoopField, word))
    -			return 0
    -	return 1
    +   o := {}
    +   loop, parse, blocks, `n, `r
    +      o.Insert(A_LoopField)
    +   loop, parse, word
    +      if !(r := isWordPossible_contains(o, A_LoopField, word))
    +         return 0
    +   return 1
     }
     isWordPossible_contains(byref o, letter, word){
    -	loop 2 {
    -		for k,v in o
    -			if Instr(v,letter)
    -			{
    -				StringReplace, op, v,% letter
    -				if RegExMatch(op, "[" word "]")
    -					sap := k
    -				else added := 1 , sap := k
    -				if added
    -					return "1" o.remove(sap)
    -			}
    -		added := 1
    -	}
    +   loop 2 {
    +      for k,v in o
    +         if Instr(v,letter)
    +         {
    +            StringReplace, op, v,% letter
    +            if RegExMatch(op, "[" word "]")
    +               sap := k
    +            else added := 1 , sap := k
    +            if added
    +               return "1" o.remove(sap)
    +         }
    +      added := 1
    +   }
     }
    diff --git a/Task/ABC-problem/AutoHotkey/abc-problem-2.ahk b/Task/ABC-problem/AutoHotkey/abc-problem-2.ahk
    index dff93522ac..c68d69b1f4 100644
    --- a/Task/ABC-problem/AutoHotkey/abc-problem-2.ahk
    +++ b/Task/ABC-problem/AutoHotkey/abc-problem-2.ahk
    @@ -34,5 +34,5 @@ CONFUSE
     )"
     
     loop, parse, wordlist, `n
    -	out .= A_LoopField " - " isWordPossible(blocks, A_LoopField) "`n"
    +   out .= A_LoopField " - " isWordPossible(blocks, A_LoopField) "`n"
     msgbox % out
    diff --git a/Task/ABC-problem/BASIC256/abc-problem.basic b/Task/ABC-problem/BASIC256/abc-problem.basic
    index e448382b74..9458ea9532 100644
    --- a/Task/ABC-problem/BASIC256/abc-problem.basic
    +++ b/Task/ABC-problem/BASIC256/abc-problem.basic
    @@ -5,42 +5,42 @@ b         = int((length(blocks$) /3) +  1)
     dim blk$(b)
     
     for i = 1 to length(makeWord$)
    -	wrd$ = word$(makeWord$,i,",")
    -	dim hit(b)
    -	n = 0
    -	if wrd$ = "" then exit for
    -	for k = 1 to length(wrd$)
    -		w$ = upper(mid(wrd$,k,1))
    -		for j = 1 to b
    -			if hit[j] = 0 then
    -				if w$ = left(word$(blocks$,j,","),1) or w$ = right(word$(blocks$,j,","),1) then
    -					hit[j] = 1
    -					n += 1
    -					exit for
    -				end if
    -			end if
    -		next j
    -	next k
    -	print wrd$; chr(9);
    -	if n = length(wrd$) then print " True" else print " False"
    +   wrd$ = word$(makeWord$,i,",")
    +   dim hit(b)
    +   n = 0
    +   if wrd$ = "" then exit for
    +   for k = 1 to length(wrd$)
    +      w$ = upper(mid(wrd$,k,1))
    +      for j = 1 to b
    +         if hit[j] = 0 then
    +            if w$ = left(word$(blocks$,j,","),1) or w$ = right(word$(blocks$,j,","),1) then
    +               hit[j] = 1
    +               n += 1
    +               exit for
    +            end if
    +         end if
    +      next j
    +   next k
    +   print wrd$; chr(9);
    +   if n = length(wrd$) then print " True" else print " False"
     next i
     end
     
     function word$(sr$, wn, delim$)
    -	j = wn
    -	if j = 0 then j += 1
    -	res$ = "" : s$ = sr$ : d$ = delim$
    -	if d$ = "" then d$ = " "
    -	sd = length(d$) : sl = length(s$)
    -	while true
    -		n = instr(s$,d$) : j -= 1
    -		if j = 0 then
    -			if n = 0 then res$ = s$ else res$ = mid(s$,1,n-1)
    -			return res$
    -		end if
    -		if n = 0 then return res$
    -		if n = sl - sd then res$ = "" : return res$
    -		sl2 = sl-n : s$ = mid(s$,n+1,sl2) : sl = sl2
    -	end while
    -	return res$
    +   j = wn
    +   if j = 0 then j += 1
    +   res$ = "" : s$ = sr$ : d$ = delim$
    +   if d$ = "" then d$ = " "
    +   sd = length(d$) : sl = length(s$)
    +   while true
    +      n = instr(s$,d$) : j -= 1
    +      if j = 0 then
    +         if n = 0 then res$ = s$ else res$ = mid(s$,1,n-1)
    +         return res$
    +      end if
    +      if n = 0 then return res$
    +      if n = sl - sd then res$ = "" : return res$
    +      sl2 = sl-n : s$ = mid(s$,n+1,sl2) : sl = sl2
    +   end while
    +   return res$
     end function
    diff --git a/Task/ABC-problem/Ballerina/abc-problem.ballerina b/Task/ABC-problem/Ballerina/abc-problem.ballerina
    new file mode 100644
    index 0000000000..6210e2d24b
    --- /dev/null
    +++ b/Task/ABC-problem/Ballerina/abc-problem.ballerina
    @@ -0,0 +1,32 @@
    +import ballerina/io;
    +
    +function r(string word, string[] bl) returns boolean {
    +    if word == "" { return true; }
    +    int c = word[0].toBytes()[0] | 32;
    +   foreach int i in 0.. blocks =
    -	new List() { "bo", "xk", "dq", "cp", "na", "gt", "re", "tg", "qd", "fs",
    -		"jw", "hu", "vi", "an", "ob", "er", "fs", "ly", "pc", "zm" };
    -	List words = new List() {
    -		"A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE"};
    -	
    -	var solver = new ABC(blocks);
    -	
    -	foreach( var word in words)
    -	{
    -		Console.WriteLine("{0} :{1}", word, solver.CanMake(word));
    -	}
    +   List blocks =
    +   new List() { "bo", "xk", "dq", "cp", "na", "gt", "re", "tg", "qd", "fs",
    +      "jw", "hu", "vi", "an", "ob", "er", "fs", "ly", "pc", "zm" };
    +   List words = new List() {
    +      "A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE"};
    +
    +   var solver = new ABC(blocks);
    +
    +   foreach( var word in words)
    +   {
    +      Console.WriteLine("{0} :{1}", word, solver.CanMake(word));
    +   }
     }
     
     class ABC
     {
    -	readonly Dictionary> _blockDict = new Dictionary>();
    -	bool[] _used;
    -	int _nextBlock;
    +   readonly Dictionary> _blockDict = new Dictionary>();
    +   bool[] _used;
    +   int _nextBlock;
     
    -	readonly List _blocks;
    +   readonly List _blocks;
     
    -	private void AddBlockChar(char c)
    -	{
    -		if (!_blockDict.ContainsKey(c))
    -		{
    -			_blockDict[c] = new List();
    -		}
    -		_blockDict[c].Add(_nextBlock);
    -	}
    +   private void AddBlockChar(char c)
    +   {
    +      if (!_blockDict.ContainsKey(c))
    +      {
    +         _blockDict[c] = new List();
    +      }
    +      _blockDict[c].Add(_nextBlock);
    +   }
     
    -	private void AddBlock(string block)
    -	{
    -		AddBlockChar(block[0]);
    -		AddBlockChar(block[1]);
    -		_nextBlock++;
    -	}
    +   private void AddBlock(string block)
    +   {
    +      AddBlockChar(block[0]);
    +      AddBlockChar(block[1]);
    +      _nextBlock++;
    +   }
     
    -	public ABC(List blocks)
    -	{
    -		_blocks = blocks;
    -		foreach (var block in blocks)
    -		{
    -			AddBlock(block);
    -		}
    -	}
    +   public ABC(List blocks)
    +   {
    +      _blocks = blocks;
    +      foreach (var block in blocks)
    +      {
    +         AddBlock(block);
    +      }
    +   }
     
    -	public bool CanMake(string word)
    -	{
    -		word = word.ToLower();
    -		if (word.Length > _blockDict.Count)
    -		{
    -			return false;
    -		}
    -		_used = new bool[_blocks.Count];
    -		return TryMake(word);
    -	}
    +   public bool CanMake(string word)
    +   {
    +      word = word.ToLower();
    +      if (word.Length > _blockDict.Count)
    +      {
    +         return false;
    +      }
    +      _used = new bool[_blocks.Count];
    +      return TryMake(word);
    +   }
     
    -	public bool TryMake(string word)
    -	{
    -		if (word == string.Empty)
    -		{
    -			return true;
    -		}
    -		var blocks = _blockDict[word[0]].Where(b => !_used[b]);
    -		foreach (var block in blocks)
    -		{
    -			_used[block] = true;
    -			if (TryMake(word.Substring(1)))
    -			{
    -				return true;
    -			}
    -			_used[block] = false;
    -		}
    -		return false;
    -	}
    +   public bool TryMake(string word)
    +   {
    +      if (word == string.Empty)
    +      {
    +         return true;
    +      }
    +      var blocks = _blockDict[word[0]].Where(b => !_used[b]);
    +      foreach (var block in blocks)
    +      {
    +         _used[block] = true;
    +         if (TryMake(word.Substring(1)))
    +         {
    +            return true;
    +         }
    +         _used[block] = false;
    +      }
    +      return false;
    +   }
     }
    diff --git a/Task/ABC-problem/C/abc-problem.c b/Task/ABC-problem/C/abc-problem.c
    index 0a798cd2c4..6e248837a9 100644
    --- a/Task/ABC-problem/C/abc-problem.c
    +++ b/Task/ABC-problem/C/abc-problem.c
    @@ -3,39 +3,39 @@
     
     int can_make_words(char **b, char *word)
     {
    -	int i, ret = 0, c = toupper(*word);
    +   int i, ret = 0, c = toupper(*word);
     
     #define SWAP(a, b) if (a != b) { char * tmp = a; a = b; b = tmp; }
     
    -	if (!c) return 1;
    -	if (!b[0]) return 0;
    +   if (!c) return 1;
    +   if (!b[0]) return 0;
     
    -	for (i = 0; b[i] && !ret; i++) {
    -		if (b[i][0] != c && b[i][1] != c) continue;
    -		SWAP(b[i], b[0]);
    -		ret = can_make_words(b + 1, word + 1);
    -		SWAP(b[i], b[0]);
    -	}
    +   for (i = 0; b[i] && !ret; i++) {
    +      if (b[i][0] != c && b[i][1] != c) continue;
    +      SWAP(b[i], b[0]);
    +      ret = can_make_words(b + 1, word + 1);
    +      SWAP(b[i], b[0]);
    +   }
     
    -	return ret;
    +   return ret;
     }
     
     int main(void)
     {
    -	char* blocks[] = {
    -		"BO", "XK", "DQ", "CP", "NA",
    -		"GT", "RE", "TG", "QD", "FS",
    -		"JW", "HU", "VI", "AN", "OB",
    -		"ER", "FS", "LY", "PC", "ZM",
    -		0 };
    +   char* blocks[] = {
    +      "BO", "XK", "DQ", "CP", "NA",
    +      "GT", "RE", "TG", "QD", "FS",
    +      "JW", "HU", "VI", "AN", "OB",
    +      "ER", "FS", "LY", "PC", "ZM",
    +      0 };
     
    -	char *words[] = {
    -		"", "A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "Confuse", 0
    -	};
    +   char *words[] = {
    +      "", "A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "Confuse", 0
    +   };
     
    -	char **w;
    -	for (w = words; *w; w++)
    -		printf("%s\t%d\n", *w, can_make_words(blocks, *w));
    +   char **w;
    +   for (w = words; *w; w++)
    +      printf("%s\t%d\n", *w, can_make_words(blocks, *w));
     
    -	return 0;
    +   return 0;
     }
    diff --git a/Task/ABC-problem/COBOL/abc-problem.cob b/Task/ABC-problem/COBOL/abc-problem.cob
    new file mode 100644
    index 0000000000..7c1b0e20c6
    --- /dev/null
    +++ b/Task/ABC-problem/COBOL/abc-problem.cob
    @@ -0,0 +1,64 @@
    +       IDENTIFICATION DIVISION.
    +       PROGRAM-ID. ABC-PROBLEM.
    +
    +       DATA DIVISION.
    +       WORKING-STORAGE SECTION.
    +       01 INPUT-DATA.
    +          03 BLOCK-SET          PIC X(40) VALUE
    +                        'BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM'.
    +          03 WORD-DATA.
    +             05 FILLER          PIC X(7) VALUE 'A'.
    +             05 FILLER          PIC X(7) VALUE 'BARK'.
    +             05 FILLER          PIC X(7) VALUE 'BOOK'.
    +             05 FILLER          PIC X(7) VALUE 'TREAT'.
    +             05 FILLER          PIC X(7) VALUE 'COMMON'.
    +             05 FILLER          PIC X(7) VALUE 'SQUAD'.
    +             05 FILLER          PIC X(7) VALUE 'CONFUSE'.
    +          03 WORDS              PIC X(7) OCCURS 7 TIMES, INDEXED BY W,
    +                                REDEFINES WORD-DATA.
    +
    +       01 OUTPUT-LINE.
    +          03 OUT-WORD           PIC X(7).
    +          03 FILLER             PIC XX VALUE ': '.
    +          03 RESULT             PIC X(3).
    +          03 FOO                PIC 999.
    +
    +       01 VARIABLES.
    +          03 BLOCK-SET          PIC X(40).
    +          03 BLOCKS             OCCURS 20 TIMES, INDEXED BY B,
    +                                REDEFINES BLOCK-SET.
    +             05 FACE-A          PIC X.
    +             05 FACE-B          PIC X.
    +          03 WORD.
    +             05 LETTERS         PIC X OCCURS 7 TIMES, INDEXED BY L.
    +          03 FAIL-FLAG          PIC X.
    +             88 FAILED          VALUE 'X'.
    +
    +       PROCEDURE DIVISION.
    +       BEGIN.
    +           PERFORM CHECK-WORD VARYING W FROM 1 BY 1
    +           UNTIL W IS GREATER THAN 7.
    +           STOP RUN.
    +
    +       CHECK-WORD.
    +           MOVE BLOCK-SET OF INPUT-DATA TO BLOCK-SET OF VARIABLES.
    +
    +           MOVE WORDS(W) TO WORD.
    +           SET L TO 1.
    +           MOVE SPACE TO FAIL-FLAG.
    +           PERFORM CHECK-LETTER VARYING L FROM 1 BY 1
    +               UNTIL FAILED
    +               OR L IS GREATER THAN 7
    +               OR LETTERS(L) IS EQUAL TO SPACE.
    +
    +           MOVE WORDS(W) TO OUT-WORD.
    +           IF FAILED, MOVE 'NO' TO RESULT, ELSE MOVE 'YES' TO RESULT.
    +           DISPLAY OUTPUT-LINE.
    +
    +       CHECK-LETTER.
    +           SET B TO 1.
    +           SEARCH BLOCKS VARYING B
    +               AT END
    +                   MOVE 'X' TO FAIL-FLAG
    +               WHEN LETTERS(L) IS EQUAL TO FACE-A(B) OR FACE-B(B)
    +                   MOVE SPACES TO BLOCKS(B).
    diff --git a/Task/ABC-problem/Component-Pascal/abc-problem.pas b/Task/ABC-problem/Component-Pascal/abc-problem.pas
    index 1f278709b7..caa5e1d04f 100644
    --- a/Task/ABC-problem/Component-Pascal/abc-problem.pas
    +++ b/Task/ABC-problem/Component-Pascal/abc-problem.pas
    @@ -1,84 +1,84 @@
     MODULE ABCProblem;
     IMPORT
    -	StdLog, DevCommanders, TextMappers;
    +   StdLog, DevCommanders, TextMappers;
     CONST
    -	notfound = -1;
    -TYPE	
    -	String = ARRAY 3 OF CHAR;
    +   notfound = -1;
    +TYPE
    +   String = ARRAY 3 OF CHAR;
     VAR
    -	blocks : ARRAY 20 OF String;
    -	
    +   blocks : ARRAY 20 OF String;
    +
     PROCEDURE Check(s: ARRAY OF CHAR): BOOLEAN;
     VAR
    -	used: SET;
    -	i,blockIndex: INTEGER;
    -	
    -	PROCEDURE GetBlockFor(c: CHAR): INTEGER;
    -	VAR
    -		i: INTEGER;
    -	BEGIN
    -		c := CAP(c);
    -		i := 0;
    -		WHILE (i < LEN(blocks)) DO
    -			IF (c = blocks[i][0]) OR (c = blocks[i][1]) THEN
    -				IF ~(i IN used) THEN RETURN i END
    -			END;
    -			INC(i)
    -		END;
    -		RETURN notfound
    -	END GetBlockFor;
    -	
    +   used: SET;
    +   i,blockIndex: INTEGER;
    +
    +   PROCEDURE GetBlockFor(c: CHAR): INTEGER;
    +   VAR
    +      i: INTEGER;
    +   BEGIN
    +      c := CAP(c);
    +      i := 0;
    +      WHILE (i < LEN(blocks)) DO
    +         IF (c = blocks[i][0]) OR (c = blocks[i][1]) THEN
    +            IF ~(i IN used) THEN RETURN i END
    +         END;
    +         INC(i)
    +      END;
    +      RETURN notfound
    +   END GetBlockFor;
    +
     BEGIN
    -	used := {};
    -	FOR i := 0 TO LEN(s$) - 1 DO
    -		blockIndex := GetBlockFor(s[i]);
    -		IF blockIndex = notfound THEN
    -			RETURN FALSE
    -		ELSE
    -			INCL(used,blockIndex)
    -		END
    -	END;
    -	RETURN TRUE
    -END Check;	
    +   used := {};
    +   FOR i := 0 TO LEN(s$) - 1 DO
    +      blockIndex := GetBlockFor(s[i]);
    +      IF blockIndex = notfound THEN
    +         RETURN FALSE
    +      ELSE
    +         INCL(used,blockIndex)
    +      END
    +   END;
    +   RETURN TRUE
    +END Check;
     
     PROCEDURE CanMakeWord*;
     VAR
    -	s: TextMappers.Scanner;
    +   s: TextMappers.Scanner;
     BEGIN
    -	s.ConnectTo(DevCommanders.par.text);
    -	s.SetPos(DevCommanders.par.beg);
    -	s.Scan;
    -	WHILE (~s.rider.eot) DO
    -		IF (s.type = TextMappers.char) & (s.char = '~') THEN
    -			RETURN
    -		ELSIF (s.type = TextMappers.string) THEN
    -			StdLog.String(s.string);StdLog.String(":> ");
    -			StdLog.Bool(Check(s.string));StdLog.Ln
    -		END;
    -		s.Scan
    -	END
    +   s.ConnectTo(DevCommanders.par.text);
    +   s.SetPos(DevCommanders.par.beg);
    +   s.Scan;
    +   WHILE (~s.rider.eot) DO
    +      IF (s.type = TextMappers.char) & (s.char = '~') THEN
    +         RETURN
    +      ELSIF (s.type = TextMappers.string) THEN
    +         StdLog.String(s.string);StdLog.String(":> ");
    +         StdLog.Bool(Check(s.string));StdLog.Ln
    +      END;
    +      s.Scan
    +   END
     END CanMakeWord;
     
     BEGIN
    -	blocks[0] := "BO";
    -	blocks[1] := "XK";
    -	blocks[2] := "DQ";
    -	blocks[3] := "CP";
    -	blocks[4] := "NA";
    -	blocks[5] := "GT";
    -	blocks[6] := "RE";
    -	blocks[7] := "TG";
    -	blocks[8] := "QD";
    -	blocks[9] := "FS";
    -	blocks[10] := "JW";
    -	blocks[11] := "HU";
    -	blocks[12] := "VI";
    -	blocks[13] := "AN";
    -	blocks[14] := "OB";
    -	blocks[15] := "ER";
    -	blocks[16] := "FS";
    -	blocks[17] := "LY";
    -	blocks[18] := "PC";
    -	blocks[19] := "ZM";
    -	
    +   blocks[0] := "BO";
    +   blocks[1] := "XK";
    +   blocks[2] := "DQ";
    +   blocks[3] := "CP";
    +   blocks[4] := "NA";
    +   blocks[5] := "GT";
    +   blocks[6] := "RE";
    +   blocks[7] := "TG";
    +   blocks[8] := "QD";
    +   blocks[9] := "FS";
    +   blocks[10] := "JW";
    +   blocks[11] := "HU";
    +   blocks[12] := "VI";
    +   blocks[13] := "AN";
    +   blocks[14] := "OB";
    +   blocks[15] := "ER";
    +   blocks[16] := "FS";
    +   blocks[17] := "LY";
    +   blocks[18] := "PC";
    +   blocks[19] := "ZM";
    +
     END ABCProblem.
    diff --git a/Task/ABC-problem/Crystal/abc-problem.cr b/Task/ABC-problem/Crystal/abc-problem.cr
    new file mode 100644
    index 0000000000..5f3ec7d4ff
    --- /dev/null
    +++ b/Task/ABC-problem/Crystal/abc-problem.cr
    @@ -0,0 +1,17 @@
    +def can_make_word? (word, blocks, i=0)
    +  return true if word.empty?
    +  ch = word[0].upcase
    +  blocks.each_with_index do |block, idx|
    +    if ch.in? block.upcase
    +      return true if can_make_word? word[1..], blocks[...idx] + blocks[(idx+1)..], i+1
    +    end
    +  end
    +  false
    +end
    +
    +blocks = "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM".split
    +
    +["A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE"].each do |word|
    +  print word, " -> ", can_make_word?(word, blocks), "\n"
    +end
    +print "abba", " -> ", can_make_word?("abba", ["AB", "AB", "AC", "AC"]), "\n"
    diff --git a/Task/ABC-problem/Delphi/abc-problem.delphi b/Task/ABC-problem/Delphi/abc-problem.pas
    similarity index 100%
    rename from Task/ABC-problem/Delphi/abc-problem.delphi
    rename to Task/ABC-problem/Delphi/abc-problem.pas
    diff --git a/Task/ABC-problem/DuckDB/abc-problem.duckdb b/Task/ABC-problem/DuckDB/abc-problem.duckdb
    new file mode 100644
    index 0000000000..0856cd977f
    --- /dev/null
    +++ b/Task/ABC-problem/DuckDB/abc-problem.duckdb
    @@ -0,0 +1,45 @@
    +CREATE OR REPLACE FUNCTION matches(block, letter) as (
    +  block[1] = letter or block[2] = letter
    +);
    +
    +# permute(lst, n, word) generates sub-permutations, perm (of length n), of the list lst,
    +# that satisfy matches(perm[i], word[i]), for i in range(1, n+1).
    +# Normally n = length(word).
    +# The caller is responsible for ensuring appropriate adjustment of typographical case.
    +CREATE OR REPLACE FUNCTION permute(lst, n, word) as table (
    +  WITH RECURSIVE permute(perm, remaining) as (
    +    -- base case
    +    SELECT
    +        []::VARCHAR[] as perm,
    +        lst::VARCHAR[] as remaining
    +    UNION ALL
    +    -- recursive case: add one element from remaining to perm and remove it from remaining
    +    SELECT
    +        (perm || [element]) AS perm,
    +        (remaining[1:i-1] || remaining[i+1:]) AS remaining
    +    FROM (select *, unnest(remaining) AS element, generate_subscripts(remaining,1) as i
    +          FROM permute)
    +    WHERE length(perm) < n
    +          and matches(element, word[1 + length(perm)])
    +  )
    +  SELECT perm
    +  FROM permute
    +  WHERE length(perm) = n
    +);
    +
    +# All solutions
    +CREATE OR REPLACE FUNCTION solve(word) as table (
    +  from permute(
    +    ['BO', 'XK', 'DQ', 'CP', 'NA', 'GT', 'RE', 'TG', 'QD', 'FS',
    +     'JW', 'HU', 'VI', 'AN', 'OB', 'ER', 'FS', 'LY', 'PC', 'ZM'],
    +    length(word), upper(word) )
    +);
    +
    +CREATE OR REPLACE FUNCTION one_solution(word) as (
    +  from solve(word)
    +  limit 1
    +);
    +
    +# Examples
    +select word, one_solution(word)
    +from (select unnest(['','A','BarK','BOOK','TREAT','COMMON','SQUAD','Confuse','abba']) as word);
    diff --git a/Task/ABC-problem/EMal/abc-problem.emal b/Task/ABC-problem/EMal/abc-problem.emal
    new file mode 100644
    index 0000000000..66f28bfaa3
    --- /dev/null
    +++ b/Task/ABC-problem/EMal/abc-problem.emal
    @@ -0,0 +1,28 @@
    +List words ← text["", "A", "Bark", "book", "TREAT", "COMMON", "SQuAd", "CONFUSE"]
    +List checks ← logic[true, true, true, false, true, false, true, true]
    +fun canMakeWord ← logic by text word
    +  if word.length æ 0 do return true end
    +  List wblocks ← text[
    +    "BO", "XK", "DQ", "CP", "NA",
    +    "GT", "RE", "TG", "QD", "FS",
    +    "JW", "HU", "VI", "AN", "OB",
    +    "ER", "FS", "LY", "PC", "ZM"]
    +  for each text ch in word.upper().split()
    +    logic found ← false
    +    for each text wblock in wblocks
    +      if wblock.find(ch) ≥ 0
    +        wblocks[wblockIndex] ← Text.EMPTY
    +        found ← true
    +        break
    +      end
    +    end
    +    if not found do return false end
    +  end
    +  return true
    +end
    +writeLine("word".padEnd(11, " "), "|", "canMakeWord", "|", "isCorrect")
    +for each text word in words
    +  writeLine(word.padEnd(11, " "), "|",
    +    (text!canMakeWord(word)).padEnd(11, " "), "|",
    +   (canMakeWord(word) æ checks[wordIndex]))
    +end
    diff --git a/Task/ABC-problem/EasyLang/abc-problem.easy b/Task/ABC-problem/EasyLang/abc-problem.easy
    index 4f51ed99d3..3ce60e223b 100644
    --- a/Task/ABC-problem/EasyLang/abc-problem.easy
    +++ b/Task/ABC-problem/EasyLang/abc-problem.easy
    @@ -2,7 +2,7 @@ b$[][] = [ [ "B" "O" ] [ "X" "K" ] [ "D" "Q" ] [ "C" "P" ] [ "N" "A" ] [ "G" "T"
     len b[] len b$[][]
     global w$[] cnt .
     #
    -proc backtr wi . .
    +proc backtr wi .
        if wi > len w$[]
           cnt += 1
           return
    diff --git a/Task/ABC-problem/EchoLisp/abc-problem.l b/Task/ABC-problem/EchoLisp/abc-problem.l
    index 20f3578009..1eca19b9fd 100644
    --- a/Task/ABC-problem/EchoLisp/abc-problem.l
    +++ b/Task/ABC-problem/EchoLisp/abc-problem.l
    @@ -1,16 +1,15 @@
     (lib 'list) ;; list-delete
     
     (define BLOCKS '("BO" "XK" "DQ" "CP" "NA" "GT" "RE" "TG" "QD" "FS"
    -	     "JW" "HU" "VI" "AN" "OB" "ER" "FS" "LY" "PC" "ZM" ))
    -	
    +        "JW" "HU" "VI" "AN" "OB" "ER" "FS" "LY" "PC" "ZM" ))
    +
     (define WORDS '("A" "BARK" "BOOK" "TREAT" "COMMON" "SQUAD" "CONFUSE"))
    -	
    +
     (define (spell word blocks)
         (cond
    -	((string-empty? word) #t)
    -	((empty? blocks) #f)
    -	(else
    -	(for/or [(block blocks)]
    -		#:continue (not (string-match block (string-first word)))
    -		(spell (string-rest word) (list-delete blocks block))))))
    -				
    +   ((string-empty? word) #t)
    +   ((empty? blocks) #f)
    +   (else
    +   (for/or [(block blocks)]
    +      #:continue (not (string-match block (string-first word)))
    +      (spell (string-rest word) (list-delete blocks block))))))
    diff --git a/Task/ABC-problem/Elena/abc-problem.elena b/Task/ABC-problem/Elena/abc-problem.elena
    index 99216ac706..4b068c9957 100644
    --- a/Task/ABC-problem/Elena/abc-problem.elena
    +++ b/Task/ABC-problem/Elena/abc-problem.elena
    @@ -27,20 +27,20 @@ extension op
         }
     }
     
    -public program()
    +public Program()
     {
    -    var blocks := new string[]{"BO", "XK", "DQ", "CP", "NA",
    -		"GT", "RE", "TG", "QD", "FS",
    -		"JW", "HU", "VI", "AN", "OB",
    -		"ER", "FS", "LY", "PC", "ZM"};
    +    auto blocks := new const string[]{"BO", "XK", "DQ", "CP", "NA",
    +      "GT", "RE", "TG", "QD", "FS",
    +      "JW", "HU", "VI", "AN", "OB",
    +      "ER", "FS", "LY", "PC", "ZM"};
     
    -    var words := new string[]{"", "A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "Confuse"};
    +    auto words := new const string[]{"", "A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "Confuse"};
     
         Enumerator e := words.enumerator();
         e.next();
     
         words.forEach::(word)
         {
    -        console.printLine("can make '",word,"' : ",word.canMakeWordFrom(blocks));
    +        Console.printLine("can make '",word,"' : ",word.canMakeWordFrom(blocks));
         }
     }
    diff --git a/Task/ABC-problem/Elixir/abc-problem.elixir b/Task/ABC-problem/Elixir/abc-problem.ex
    similarity index 100%
    rename from Task/ABC-problem/Elixir/abc-problem.elixir
    rename to Task/ABC-problem/Elixir/abc-problem.ex
    diff --git a/Task/ABC-problem/Euphoria/abc-problem.eu b/Task/ABC-problem/Euphoria/abc-problem.eu
    new file mode 100644
    index 0000000000..be5498a568
    --- /dev/null
    +++ b/Task/ABC-problem/Euphoria/abc-problem.eu
    @@ -0,0 +1,35 @@
    +include std/text.e
    +
    +sequence blocks = {{'B','O'},{'X','K'},{'D','Q'},{'C','P'},{'N','A'},
    +                   {'G','T'},{'R','E'},{'T','G'},{'Q','D'},{'F','S'},
    +                   {'J','W'},{'H','U'},{'V','I'},{'A','N'},{'O','B'},
    +                   {'E','R'},{'F','S'},{'L','Y'},{'P','C'},{'Z','M'}}
    +sequence words = {"A","BarK","BOOK","TrEaT","COMMON","SQUAD","CONFUSE"}
    +
    +sequence current_word
    +sequence temp
    +integer matches
    +
    +for i = 1 to length(words) do
    +   current_word = upper(words[i])
    +   temp = blocks
    +   matches = 0
    +   for j = 1 to length(current_word) do
    +      for k = 1 to length(temp) do
    +         if find(current_word[j],temp[k]) then
    +            temp = remove(temp,k)
    +            matches += 1
    +            exit
    +         end if
    +      end for
    +      if length(current_word) = matches then
    +         printf(1,"%s: TRUE\n",{words[i]})
    +         exit
    +      end if
    +   end for
    +   if length(current_word) != matches then
    +      printf(1,"%s: FALSE\n",{words[i]})
    +   end if
    +end for
    +
    +if getc(0) then end if
    diff --git a/Task/ABC-problem/Euphoria/abc-problem.euphoria b/Task/ABC-problem/Euphoria/abc-problem.euphoria
    deleted file mode 100644
    index efa3352600..0000000000
    --- a/Task/ABC-problem/Euphoria/abc-problem.euphoria
    +++ /dev/null
    @@ -1,35 +0,0 @@
    -include std/text.e
    -
    -sequence blocks = {{'B','O'},{'X','K'},{'D','Q'},{'C','P'},{'N','A'},
    -                   {'G','T'},{'R','E'},{'T','G'},{'Q','D'},{'F','S'},
    -                   {'J','W'},{'H','U'},{'V','I'},{'A','N'},{'O','B'},
    -                   {'E','R'},{'F','S'},{'L','Y'},{'P','C'},{'Z','M'}}
    -sequence words = {"A","BarK","BOOK","TrEaT","COMMON","SQUAD","CONFUSE"}
    -
    -sequence current_word
    -sequence temp
    -integer matches
    -
    -for i = 1 to length(words) do
    -	current_word = upper(words[i])
    -	temp = blocks
    -	matches = 0
    -	for j = 1 to length(current_word) do
    -		for k = 1 to length(temp) do
    -			if find(current_word[j],temp[k]) then
    -				temp = remove(temp,k)
    -				matches += 1
    -				exit
    -			end if
    -		end for
    -		if length(current_word) = matches then
    -			printf(1,"%s: TRUE\n",{words[i]})
    -			exit
    -		end if
    -	end for
    -	if length(current_word) != matches then
    -		printf(1,"%s: FALSE\n",{words[i]})
    -	end if
    -end for
    -
    -if getc(0) then end if
    diff --git a/Task/ABC-problem/FBSL/abc-problem.fbsl b/Task/ABC-problem/FBSL/abc-problem.fbsl
    index 9c34a6ea72..1ef125fe0f 100644
    --- a/Task/ABC-problem/FBSL/abc-problem.fbsl
    +++ b/Task/ABC-problem/FBSL/abc-problem.fbsl
    @@ -1,44 +1,44 @@
     #APPTYPE CONSOLE
     SUB MAIN()
    -	BlockCheck("A")
    -	BlockCheck("BARK")
    -	BlockCheck("BooK")
    -	BlockCheck("TrEaT")
    -	BlockCheck("comMON")
    -	BlockCheck("sQuAd")
    -	BlockCheck("Confuse")
    -	pause
    +   BlockCheck("A")
    +   BlockCheck("BARK")
    +   BlockCheck("BooK")
    +   BlockCheck("TrEaT")
    +   BlockCheck("comMON")
    +   BlockCheck("sQuAd")
    +   BlockCheck("Confuse")
    +   pause
     END SUB
     
     FUNCTION BlockCheck(str)
    -	print str " " iif( Blockable( str ), "can", "cannot" ) " be spelled with blocks."
    +   print str " " iif( Blockable( str ), "can", "cannot" ) " be spelled with blocks."
     END FUNCTION
     
     FUNCTION Blockable(str AS STRING)
    -	DIM blocks AS STRING = "BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM"
    -	DIM C AS STRING = ""
    -	DIM POS AS INTEGER = 0
    -	
    -	FOR DIM I = 1 TO LEN(str)
    -		C = str{i}
    -		POS = INSTR(BLOCKS, C, 0, 1) 'case insensitive
    -		IF POS > 0 THEN
    -			'if the pos is odd, it's the first of the pair
    -			IF POS MOD 2 = 1 THEN
    -				'so clear the first and the second
    -				poke(@blocks + pos - 1," ")
    -				poke(@blocks + pos," ")
    -			'otherwise, it's the last of the pair	
    -			ELSE
    -				'clear the second and the first
    -				poke(@blocks + pos - 1," ")
    -				poke(@blocks + pos - 2," ")
    -			END IF
    -		ELSE
    -		'not found, so can't be spelled
    -		RETURN FALSE
    -		END IF
    -	NEXT
    -	'got thru to here, so can be spelled
    -	RETURN TRUE
    +   DIM blocks AS STRING = "BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM"
    +   DIM C AS STRING = ""
    +   DIM POS AS INTEGER = 0
    +
    +   FOR DIM I = 1 TO LEN(str)
    +      C = str{i}
    +      POS = INSTR(BLOCKS, C, 0, 1) 'case insensitive
    +      IF POS > 0 THEN
    +         'if the pos is odd, it's the first of the pair
    +         IF POS MOD 2 = 1 THEN
    +            'so clear the first and the second
    +            poke(@blocks + pos - 1," ")
    +            poke(@blocks + pos," ")
    +         'otherwise, it's the last of the pair
    +         ELSE
    +            'clear the second and the first
    +            poke(@blocks + pos - 1," ")
    +            poke(@blocks + pos - 2," ")
    +         END IF
    +      ELSE
    +      'not found, so can't be spelled
    +      RETURN FALSE
    +      END IF
    +   NEXT
    +   'got thru to here, so can be spelled
    +   RETURN TRUE
     END FUNCTION
    diff --git a/Task/ABC-problem/Fortran/abc-problem-2.f b/Task/ABC-problem/Fortran/abc-problem-2.f
    index 0c0d917d24..186802c418 100644
    --- a/Task/ABC-problem/Fortran/abc-problem-2.f
    +++ b/Task/ABC-problem/Fortran/abc-problem-2.f
    @@ -1,264 +1,264 @@
    -      MODULE PLAYPEN	!Messes with a set of alphabet blocks.
    -       INTEGER MSG		!Output unit number.
    -       PARAMETER (MSG = 6)	!Standard output.
    -       INTEGER MS		!I dislike unidentified constants...
    -       PARAMETER (MS = 2)	!So this is the maximum number of lettered sides.
    -       INTEGER LETTER(26),SUPPLY(26)	!For counting the alphabet.
    +      MODULE PLAYPEN !Messes with a set of alphabet blocks.
    +       INTEGER MSG      !Output unit number.
    +       PARAMETER (MSG = 6) !Standard output.
    +       INTEGER MS    !I dislike unidentified constants...
    +       PARAMETER (MS = 2)  !So this is the maximum number of lettered sides.
    +       INTEGER LETTER(26),SUPPLY(26)   !For counting the alphabet.
            CONTAINS
    -        SUBROUTINE SWAP(I,J)	!This really should be known to the compiler.
    -         INTEGER I,J,K		!Which could generate in-place code,
    -          K = I			!Using registers, maybe.
    -          I = J			!Or maybe, there are special op-codes.
    -          J = K			!Rather than this clunkiness.
    -        END SUBROUTINE SWAP	!And it should be for any type of thingy.
    +        SUBROUTINE SWAP(I,J)  !This really should be known to the compiler.
    +         INTEGER I,J,K     !Which could generate in-place code,
    +          K = I         !Using registers, maybe.
    +          I = J         !Or maybe, there are special op-codes.
    +          J = K         !Rather than this clunkiness.
    +        END SUBROUTINE SWAP   !And it should be for any type of thingy.
     
             INTEGER FUNCTION LSTNB(TEXT)  !Sigh. Last Not Blank.
     Concocted yet again by R.N.McLean (whom God preserve) December MM.
     Code checking reveals that the Compaq compiler generates a copy of the string and then finds the length of that when using the latter-day intrinsic LEN_TRIM. Madness!
    -Can't   DO WHILE (L.GT.0 .AND. TEXT(L:L).LE.' ')	!Control chars. regarded as spaces.
    +Can't   DO WHILE (L.GT.0 .AND. TEXT(L:L).LE.' ')   !Control chars. regarded as spaces.
     Curse the morons who think it good that the compiler MIGHT evaluate logical expressions fully.
     Crude GO TO rather than a DO-loop, because compilers use a loop counter as well as updating the index variable.
     Comparison runs of GNASH showed a saving of ~3% in its mass-data reading through the avoidance of DO in LSTNB alone.
     Crappy code for character comparison of varying lengths is avoided by using ICHAR which is for single characters only.
     Checking the indexing of CHARACTER variables for bounds evoked astounding stupidities, such as calculating the length of TEXT(L:L) by subtracting L from L!
     Comparison runs of GNASH showed a saving of ~25-30% in its mass data scanning for this, involving all its two-dozen or so single-character comparisons, not just in LSTNB.
    -         CHARACTER*(*),INTENT(IN):: TEXT	!The bumf. If there must be copy-in, at least there need not be copy back.
    -         INTEGER L		!The length of the bumf.
    -          L = LEN(TEXT)		!So, what is it?
    -    1     IF (L.LE.0) GO TO 2	!Are we there yet?
    -          IF (ICHAR(TEXT(L:L)).GT.ICHAR(" ")) GO TO 2	!Control chars are regarded as spaces also.
    -          L = L - 1		!Step back one.
    -          GO TO 1		!And try again.
    -    2     LSTNB = L		!The last non-blank, possibly zero.
    -         RETURN			!Unsafe to use LSTNB as a variable.
    -        END FUNCTION LSTNB	!Compilers can bungle it.
    +         CHARACTER*(*),INTENT(IN):: TEXT  !The bumf. If there must be copy-in, at least there need not be copy back.
    +         INTEGER L      !The length of the bumf.
    +          L = LEN(TEXT)    !So, what is it?
    +    1     IF (L.LE.0) GO TO 2 !Are we there yet?
    +          IF (ICHAR(TEXT(L:L)).GT.ICHAR(" ")) GO TO 2 !Control chars are regarded as spaces also.
    +          L = L - 1     !Step back one.
    +          GO TO 1    !And try again.
    +    2     LSTNB = L     !The last non-blank, possibly zero.
    +         RETURN         !Unsafe to use LSTNB as a variable.
    +        END FUNCTION LSTNB !Compilers can bungle it.
     
    -        SUBROUTINE LETTERCOUNT(TEXT)	!Count the occurrences of A-Z.
    -         CHARACTER*(*) TEXT	!The text to inspect.
    -         INTEGER I,K		!Assistants.
    -          DO I = 1,LEN(TEXT)		!Step through the text.
    -            K = ICHAR(TEXT(I:I)) - ICHAR("A") + 1	!This presumes that A-Z have contiguous codes!
    -            IF (K.GE.1 .AND. K.LE.26) LETTER(K) = LETTER(K) + 1	!Not so with EBCDIC!!
    -          END DO			!On to the next letter.
    -        END SUBROUTINE LETTERCOUNT	!Be careful with LETTER.
    +        SUBROUTINE LETTERCOUNT(TEXT)   !Count the occurrences of A-Z.
    +         CHARACTER*(*) TEXT   !The text to inspect.
    +         INTEGER I,K    !Assistants.
    +          DO I = 1,LEN(TEXT)     !Step through the text.
    +            K = ICHAR(TEXT(I:I)) - ICHAR("A") + 1  !This presumes that A-Z have contiguous codes!
    +            IF (K.GE.1 .AND. K.LE.26) LETTER(K) = LETTER(K) + 1   !Not so with EBCDIC!!
    +          END DO        !On to the next letter.
    +        END SUBROUTINE LETTERCOUNT  !Be careful with LETTER.
     
    -        SUBROUTINE UPCASE(TEXT)	!In the absence of an intrinsic...
    +        SUBROUTINE UPCASE(TEXT)  !In the absence of an intrinsic...
     Converts any lower case letters in TEXT to upper case...
     Concocted yet again by R.N.McLean (whom God preserve) December MM.
     Converting from a DO loop evades having both an iteration counter to decrement and an index variable to adjust.
    -         CHARACTER*(*) TEXT	!The stuff to be modified.
    -c        CHARACTER*26 LOWER,UPPER	!Tables. a-z may not be contiguous codes.
    +         CHARACTER*(*) TEXT   !The stuff to be modified.
    +c        CHARACTER*26 LOWER,UPPER   !Tables. a-z may not be contiguous codes.
     c        PARAMETER (LOWER = "abcdefghijklmnopqrstuvwxyz")
     c        PARAMETER (UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ")
     CAREFUL!! The below relies on a-z and A-Z being contiguous, as is NOT the case with EBCDIC.
    -         INTEGER I,L,IT		!Fingers.
    -          L = LEN(TEXT)		!Get a local value, in case LEN engages in oddities.
    -          I = L			!Start at the end and work back..
    -    1     IF (I.LE.0) RETURN 	!Are we there yet? Comparison against zero should not require a subtraction.
    -c         IT = INDEX(LOWER,TEXT(I:I))	!Well?
    -c         IF (IT .GT. 0) TEXT(I:I) = UPPER(IT:IT)	!One to convert?
    -          IT = ICHAR(TEXT(I:I)) - ICHAR("a")		!More symbols precede "a" than "A".
    -          IF (IT.GE.0 .AND. IT.LE.25) TEXT(I:I) = CHAR(IT + ICHAR("A"))	!In a-z? Convert!
    -          I = I - 1			!Back one.
    -          GO TO 1			!Inspect..
    -        END SUBROUTINE UPCASE	!Easy.
    +         INTEGER I,L,IT    !Fingers.
    +          L = LEN(TEXT)    !Get a local value, in case LEN engages in oddities.
    +          I = L         !Start at the end and work back..
    +    1     IF (I.LE.0) RETURN  !Are we there yet? Comparison against zero should not require a subtraction.
    +c         IT = INDEX(LOWER,TEXT(I:I))  !Well?
    +c         IF (IT .GT. 0) TEXT(I:I) = UPPER(IT:IT)  !One to convert?
    +          IT = ICHAR(TEXT(I:I)) - ICHAR("a")    !More symbols precede "a" than "A".
    +          IF (IT.GE.0 .AND. IT.LE.25) TEXT(I:I) = CHAR(IT + ICHAR("A")) !In a-z? Convert!
    +          I = I - 1        !Back one.
    +          GO TO 1       !Inspect..
    +        END SUBROUTINE UPCASE !Easy.
     
    -        SUBROUTINE ORDERSIDE(LETTER)	!Puts the letters into order.
    -         CHARACTER*(*) LETTER	!The letters.
    -         INTEGER I,N,H		!Assistants.
    -         CHARACTER*1 T		!A scratchpad.
    -         LOGICAL CURSE		!A bit.
    -          N = LEN(LETTER)	!So, how many letters?
    -          H = N - 1		!Last - First, and not +1.
    -          IF (H.LE.0) RETURN	!Ha ha.
    -    1     H = MAX(1,H*10/13)		!The special feature.
    -          IF (H.EQ.9 .OR. H.EQ.10) H = 11	!A twiddle.
    -          CURSE = .FALSE.		!So far, so good.
    -          DO I = N - H,1,-1		!If H = 1, this is a BubbleSort.
    -            IF (LETTER(I:I).LT.LETTER(I + H:I + H)) THEN	!One compare.
    -              T = LETTER(I:I)			!One swap.
    -              LETTER(I:I) = LETTER(I + H:I + H)	!Alas, no SWAP(A,B)
    -              LETTER(I + H:I + H) = T		!Is recognised by the compiler.
    -              CURSE = .TRUE.		!If once a tiger is seen...
    -            END IF			!So much for that comparison.
    -          END DO			!On to the next.
    +        SUBROUTINE ORDERSIDE(LETTER)   !Puts the letters into order.
    +         CHARACTER*(*) LETTER !The letters.
    +         INTEGER I,N,H     !Assistants.
    +         CHARACTER*1 T     !A scratchpad.
    +         LOGICAL CURSE     !A bit.
    +          N = LEN(LETTER)  !So, how many letters?
    +          H = N - 1     !Last - First, and not +1.
    +          IF (H.LE.0) RETURN  !Ha ha.
    +    1     H = MAX(1,H*10/13)     !The special feature.
    +          IF (H.EQ.9 .OR. H.EQ.10) H = 11 !A twiddle.
    +          CURSE = .FALSE.     !So far, so good.
    +          DO I = N - H,1,-1      !If H = 1, this is a BubbleSort.
    +            IF (LETTER(I:I).LT.LETTER(I + H:I + H)) THEN !One compare.
    +              T = LETTER(I:I)       !One swap.
    +              LETTER(I:I) = LETTER(I + H:I + H) !Alas, no SWAP(A,B)
    +              LETTER(I + H:I + H) = T     !Is recognised by the compiler.
    +              CURSE = .TRUE.     !If once a tiger is seen...
    +            END IF         !So much for that comparison.
    +          END DO        !On to the next.
               IF (CURSE .OR. H.GT.1) GO TO 1!Another pass?
    -        END SUBROUTINE ORDERSIDE	!Simple enough.
    -        SUBROUTINE ORDERBLOCKS(N,SOME)	!Puts the collection of blocks into order.
    -         INTEGER N		!The number of blocks.
    -         CHARACTER*(*) SOME(:)	!Their lists of letters.
    -         INTEGER I,H		!Assistants.
    -         CHARACTER*(LEN(SOME(1))) T	!A scratchpad matching an element of SOME.
    -         LOGICAL CURSE			!Since there is still no SWAP(SOME(I),SOME(I + H)).
    -          H = N - 1		!So here comes another CombSort.
    -          IF (H.LE.0) RETURN	!With standard suspicion.
    -    1     H = MAX(1,H*10/13)		!This is the outer loop.
    -          IF (H.EQ.9 .OR. H.EQ.10) H = 11	!This is a fiddle.
    -          CURSE = .FALSE.		!Start the next pass in hope.
    -          DO I = N - H,1,-1		!Going backwards, just for fun.
    -            IF (SOME(I).LT.SOME(I + H)) THEN	!So then?
    -              T = SOME(I)		!Disorder.
    -              SOME(I) = SOME(I + H)	!So once again,
    -              SOME(I + H) = T		!Swap the two miscreants.
    -              CURSE = .TRUE.		!And remember.
    -            END IF			!So much for that comparison.
    -          END DO			!On to the next.
    +        END SUBROUTINE ORDERSIDE !Simple enough.
    +        SUBROUTINE ORDERBLOCKS(N,SOME) !Puts the collection of blocks into order.
    +         INTEGER N      !The number of blocks.
    +         CHARACTER*(*) SOME(:)   !Their lists of letters.
    +         INTEGER I,H    !Assistants.
    +         CHARACTER*(LEN(SOME(1))) T !A scratchpad matching an element of SOME.
    +         LOGICAL CURSE        !Since there is still no SWAP(SOME(I),SOME(I + H)).
    +          H = N - 1     !So here comes another CombSort.
    +          IF (H.LE.0) RETURN  !With standard suspicion.
    +    1     H = MAX(1,H*10/13)     !This is the outer loop.
    +          IF (H.EQ.9 .OR. H.EQ.10) H = 11 !This is a fiddle.
    +          CURSE = .FALSE.     !Start the next pass in hope.
    +          DO I = N - H,1,-1      !Going backwards, just for fun.
    +            IF (SOME(I).LT.SOME(I + H)) THEN !So then?
    +              T = SOME(I)     !Disorder.
    +              SOME(I) = SOME(I + H) !So once again,
    +              SOME(I + H) = T    !Swap the two miscreants.
    +              CURSE = .TRUE.     !And remember.
    +            END IF         !So much for that comparison.
    +          END DO        !On to the next.
               IF (CURSE .OR. H.GT.1) GO TO 1!Are we there yet?
    -        END SUBROUTINE ORDERBLOCKS	!Not much code, but ringing the changes is still tedious.
    +        END SUBROUTINE ORDERBLOCKS  !Not much code, but ringing the changes is still tedious.
     
    -        SUBROUTINE PLAY(N,SOME)	!Mess about with the collection of blocks.
    -         INTEGER N		!Their number.
    -         CHARACTER*(*) SOME(:)	!Their letters.
    -         INTEGER NH,HIT(N)	!A list of blocks.
    -         INTEGER B,I,J,K,L,M	!Assistants.
    -         CHARACTER*1 C		!A letter of the moment.
    -          L = LEN(SOME(1))	!The maximum number of letters to any block.
    +        SUBROUTINE PLAY(N,SOME)  !Mess about with the collection of blocks.
    +         INTEGER N      !Their number.
    +         CHARACTER*(*) SOME(:)   !Their letters.
    +         INTEGER NH,HIT(N) !A list of blocks.
    +         INTEGER B,I,J,K,L,M  !Assistants.
    +         CHARACTER*1 C     !A letter of the moment.
    +          L = LEN(SOME(1)) !The maximum number of letters to any block.
     Cast the collection on to the floor.
    -          WRITE (MSG,1) N,L,SOME	!Announce the set as it is supplied.
    +          WRITE (MSG,1) N,L,SOME !Announce the set as it is supplied.
         1     FORMAT (I7," blocks, with at most",I2," letters:",66(1X,A))
     Change the "orientation" of some blocks.
    -          DO B = 1,N		!Step through each block.
    -            CALL UPCASE(SOME(B))	!Paranoia rules.
    -            CALL ORDERSIDE(SOME(B))	!Put its letter list into order.
    -          END DO		!On to the next block.
    -          WRITE (MSG,2) SOME	!Reveal the orderly array.
    +          DO B = 1,N    !Step through each block.
    +            CALL UPCASE(SOME(B)) !Paranoia rules.
    +            CALL ORDERSIDE(SOME(B)) !Put its letter list into order.
    +          END DO     !On to the next block.
    +          WRITE (MSG,2) SOME  !Reveal the orderly array.
         2     FORMAT (6X,"... the letters in reverse order:",66(1X,A))
     Collate the collection of blocks.
    -          CALL ORDERBLOCKS(N,SOME)	!Now order the blocks by their letters.
    -          WRITE (MSG,3) SOME		!Reveal them in neato order.
    +          CALL ORDERBLOCKS(N,SOME)  !Now order the blocks by their letters.
    +          WRITE (MSG,3) SOME     !Reveal them in neato order.
         3     FORMAT (7X,"... the blocks in reverse order:",66(1X,A))
     Count the appearances of the letters of the alphabet.
    -          LETTER = 0		!Enough of shuffling blocks around.
    -          DO B = 1,N		!Now inspect their collective letters.
    -            CALL LETTERCOUNT(SOME(B))	!A block's worth at a go.
    -          END DO		!On to the next block.
    -          SUPPLY = LETTER	!Save the counts of supplied letters.
    -          WRITE (MSG,4) (CHAR(ICHAR("A") + I - 1),I = 1,26),SUPPLY	!Results.
    -    4     FORMAT (15X,"Letters of the alphabet:",26A,/,	!First, a line with A ... Z.
    -     1     11X,"... number thereof supplied:",26I)	!Then a line of the associated counts.
    +          LETTER = 0    !Enough of shuffling blocks around.
    +          DO B = 1,N    !Now inspect their collective letters.
    +            CALL LETTERCOUNT(SOME(B))  !A block's worth at a go.
    +          END DO     !On to the next block.
    +          SUPPLY = LETTER  !Save the counts of supplied letters.
    +          WRITE (MSG,4) (CHAR(ICHAR("A") + I - 1),I = 1,26),SUPPLY   !Results.
    +    4     FORMAT (15X,"Letters of the alphabet:",26A,/,   !First, a line with A ... Z.
    +     1     11X,"... number thereof supplied:",26I)  !Then a line of the associated counts.
     Check for blocks with duplicated letters.
    -          WRITE (MSG,5)		!Announce.
    -    5     FORMAT (8X,"Blocks with duplicated letters:",$)	!Further output impends.
    -          M = 0			!No duplication found.
    -          DO B = 1,N		!So step through each block.
    -         JJ:DO J = 2,L			!Inspecting successive letters of the block,
    -              IF (SOME(B)(J:J).LE." ") EXIT JJ	!Provided they've not run out.
    -              DO K = 1,J - 1			!To see if it has appeared earlier.
    +          WRITE (MSG,5)    !Announce.
    +    5     FORMAT (8X,"Blocks with duplicated letters:",$)   !Further output impends.
    +          M = 0         !No duplication found.
    +          DO B = 1,N    !So step through each block.
    +         JJ:DO J = 2,L        !Inspecting successive letters of the block,
    +              IF (SOME(B)(J:J).LE." ") EXIT JJ  !Provided they've not run out.
    +              DO K = 1,J - 1        !To see if it has appeared earlier.
                     IF (SOME(B)(K:K).LE." ") EXIT JJ!Reverse order means that spaces will be at the end!
    -                IF (SOME(B)(J:J).EQ.SOME(B)(K:K)) THEN	!Well?
    -                  M = M + 1		!A match!
    -                  WRITE (MSG,6) SOME(B)	!Name the block.
    -    6             FORMAT (1X,A,$)	!With further output still impending,
    -                  EXIT JJ		!And give up on this block.
    -                END IF			!One duplicated letter is sufficient for its downfall.
    -              END DO			!Next letter up.
    -            END DO JJ			!On to the next letter of the block.
    -          END DO		!On to the next block.
    -          CALL HIC(M)		!Show the count and end the line.
    +                IF (SOME(B)(J:J).EQ.SOME(B)(K:K)) THEN   !Well?
    +                  M = M + 1      !A match!
    +                  WRITE (MSG,6) SOME(B)   !Name the block.
    +    6             FORMAT (1X,A,$)   !With further output still impending,
    +                  EXIT JJ     !And give up on this block.
    +                END IF        !One duplicated letter is sufficient for its downfall.
    +              END DO       !Next letter up.
    +            END DO JJ         !On to the next letter of the block.
    +          END DO     !On to the next block.
    +          CALL HIC(M)      !Show the count and end the line.
     Check for duplicate blocks, knowing that the array of blocks is ordered.
    -          WRITE (MSG,7)		!Announce.
    -    7     FORMAT (21X,"Duplicated blocks:",$)	!Again, leave the line dangling.
    -          K = 0			!No duplication found.
    -          B = 1			!Syncopation.
    -   70     B = B + 1		!Advance one.
    -          IF (B.GT.N) GO TO 72	!Are we there yet?
    -          IF (SOME(B).NE.SOME(B - 1)) GO TO 70	!No match? Search on.
    -          K = K + 1		!A match is counted.
    -          WRITE (MSG,6) SOME(B)	!Name it.
    -   71     B = B + 1		!And speed through continued matching.
    -          IF (B.GT.N) GO TO 72	!Unless we're of the end.
    -          IF (SOME(B).EQ.SOME(B - 1)) GO TO 71	!Continued matching?
    -          GO TO 70		!Mismatch: resume the normal scan.
    -   72     CALL HIC(K)		!So much for that.
    +          WRITE (MSG,7)    !Announce.
    +    7     FORMAT (21X,"Duplicated blocks:",$)   !Again, leave the line dangling.
    +          K = 0         !No duplication found.
    +          B = 1         !Syncopation.
    +   70     B = B + 1     !Advance one.
    +          IF (B.GT.N) GO TO 72   !Are we there yet?
    +          IF (SOME(B).NE.SOME(B - 1)) GO TO 70  !No match? Search on.
    +          K = K + 1     !A match is counted.
    +          WRITE (MSG,6) SOME(B)  !Name it.
    +   71     B = B + 1     !And speed through continued matching.
    +          IF (B.GT.N) GO TO 72   !Unless we're of the end.
    +          IF (SOME(B).EQ.SOME(B - 1)) GO TO 71  !Continued matching?
    +          GO TO 70      !Mismatch: resume the normal scan.
    +   72     CALL HIC(K)      !So much for that.
     Check for duplicated letters across different blocks.
    -          IF (ALL(SUPPLY.LE.1)) RETURN	!Unless there are no duplicated letters.
    -          WRITE (MSG,8)		!Announce.
    -    8     FORMAT ("Duplicated letters on different blocks:",$)	!More to come.
    -          K = 0		!Start another count.
    -          DO I = 1,26		!A well-known span.
    -            IF (SUPPLY(I).LE.1) CYCLE	!Any duplicated letters?
    +          IF (ALL(SUPPLY.LE.1)) RETURN !Unless there are no duplicated letters.
    +          WRITE (MSG,8)    !Announce.
    +    8     FORMAT ("Duplicated letters on different blocks:",$) !More to come.
    +          K = 0      !Start another count.
    +          DO I = 1,26      !A well-known span.
    +            IF (SUPPLY(I).LE.1) CYCLE  !Any duplicated letters?
                 C = CHAR(ICHAR("A") + I - 1)!Yes. This is the character.
    -            NH = 0		!So, how many blocks contribute?
    -            DO B = 1,N		!Find out.
    -              IF (INDEX(SOME(B),C).GT.0) THEN	!On this block?
    -                NH = NH + 1		!Yes.
    -                HIT(NH) = B		!Keep track of which.
    -              END IF			!So much for that block.
    -            END DO		!On to the next.
    -            IF (ANY(SOME(HIT(2:NH)) .NE. SOME(HIT(1)))) THEN	!All have the same collection of letters?
    -              K = K + 1			!No!
    -              WRITE (MSG,9) C		!Name the heterogenously supported letter.
    -    9         FORMAT (A,$)	!Use the same spacing even though one character only.
    -            END IF		!So much for that letter's search.
    -          END DO		!On to the next letter.
    -          CALL HIC(K)	!Finish the line with the count report.
    -         CONTAINS	!This is used often enough.
    -          SUBROUTINE HIC(N)	!But has very specific context.
    -           INTEGER N			!The count.
    -            IF (N.LE.0) WRITE (MSG,*) "None."	!Yes, we have no bananas.
    -            IF (N.GT.0) WRITE (MSG,*) N		!Either way, end the line.
    -          END SUBROUTINE HIC	!This service routine is not needed elsewhere.
    -        END SUBROUTINE PLAY	!Look mummy! All the blockses are neatened!
    +            NH = 0      !So, how many blocks contribute?
    +            DO B = 1,N     !Find out.
    +              IF (INDEX(SOME(B),C).GT.0) THEN   !On this block?
    +                NH = NH + 1      !Yes.
    +                HIT(NH) = B      !Keep track of which.
    +              END IF       !So much for that block.
    +            END DO      !On to the next.
    +            IF (ANY(SOME(HIT(2:NH)) .NE. SOME(HIT(1)))) THEN   !All have the same collection of letters?
    +              K = K + 1       !No!
    +              WRITE (MSG,9) C    !Name the heterogenously supported letter.
    +    9         FORMAT (A,$)  !Use the same spacing even though one character only.
    +            END IF      !So much for that letter's search.
    +          END DO     !On to the next letter.
    +          CALL HIC(K)   !Finish the line with the count report.
    +         CONTAINS !This is used often enough.
    +          SUBROUTINE HIC(N)   !But has very specific context.
    +           INTEGER N       !The count.
    +            IF (N.LE.0) WRITE (MSG,*) "None."   !Yes, we have no bananas.
    +            IF (N.GT.0) WRITE (MSG,*) N      !Either way, end the line.
    +          END SUBROUTINE HIC  !This service routine is not needed elsewhere.
    +        END SUBROUTINE PLAY   !Look mummy! All the blockses are neatened!
     
    -        LOGICAL FUNCTION CANBLOCK(WORD,N,SOME)	!Can the blocks spell out the word?
    +        LOGICAL FUNCTION CANBLOCK(WORD,N,SOME)  !Can the blocks spell out the word?
     Creates a move tree based on the letters of WORD and for each, the blocks available.
    -         CHARACTER*(*) WORD	!The word to spell out.
    -         INTEGER N		!The number of blocks.
    -         CHARACTER*(*) SOME(:)	!The blocks and their letters.
    -         INTEGER NA,AVAIL(N)	!Say not the struggle naught availeth!
    -         INTEGER NMOVE(LEN(WORD))	!I need a list of acceptable blocks,
    -         INTEGER MOVE(LEN(WORD),N)	!One list for each letter of WORD.
    -         INTEGER I,L,S		!Assistants.
    -         CHARACTER*1 C		!The letter of the moment.
    -          CANBLOCK = .FALSE.		!Initial pessimism.
    -          L = LSTNB(WORD)		!Ignore trailing spaces.
    -          IF (L.GT.N) RETURN		!Enough blocks?
    -          LETTER = 0				!To make rabbit stew,
    -          CALL LETTERCOUNT(WORD(1:L))		!First catch your rabbit.
    -          IF (ANY(SUPPLY .LT. LETTER)) RETURN	!The larder is lacking.
    -          NA = N			!Prepare a list.
    -          FORALL (I = 1:N) AVAIL(I) = I	!That fingers every block.
    -          I = 0		!Step through the letters of the WORD.
    +         CHARACTER*(*) WORD   !The word to spell out.
    +         INTEGER N      !The number of blocks.
    +         CHARACTER*(*) SOME(:)   !The blocks and their letters.
    +         INTEGER NA,AVAIL(N)  !Say not the struggle naught availeth!
    +         INTEGER NMOVE(LEN(WORD))   !I need a list of acceptable blocks,
    +         INTEGER MOVE(LEN(WORD),N)  !One list for each letter of WORD.
    +         INTEGER I,L,S     !Assistants.
    +         CHARACTER*1 C     !The letter of the moment.
    +          CANBLOCK = .FALSE.     !Initial pessimism.
    +          L = LSTNB(WORD)     !Ignore trailing spaces.
    +          IF (L.GT.N) RETURN     !Enough blocks?
    +          LETTER = 0          !To make rabbit stew,
    +          CALL LETTERCOUNT(WORD(1:L))     !First catch your rabbit.
    +          IF (ANY(SUPPLY .LT. LETTER)) RETURN   !The larder is lacking.
    +          NA = N        !Prepare a list.
    +          FORALL (I = 1:N) AVAIL(I) = I   !That fingers every block.
    +          I = 0      !Step through the letters of the WORD.
     Chug through the letters of the WORD.
    -    1     I = I + 1	!One letter after the other.
    -          IF (I.GT.L) GO TO 100	!Yay! We're through!
    -          C = WORD(I:I)		!The letter of the moment.
    -          NMOVE(I) = 0		!No moves known at this new level.
    -          DO S = 1,NA		!So, look for them amongst the available slots.
    -            IF (INDEX(SOME(AVAIL(S)),C) .GT. 0) THEN	!A hit?
    -              NMOVE(I) = NMOVE(I) + 1	!Yes! Count up another possible move.
    -              MOVE(I,NMOVE(I)) = S	!Remember its slot.
    -            END IF			!So much for that block.
    -          END DO		!On to the next.
    -    2     IF (NMOVE(I).GT.0) THEN	!Have we any moves?
    -            S = MOVE(I,NMOVE(I))	!Yes! Recover the last found.
    -            NMOVE(I) = NMOVE(I) - 1	!Uncount, as it is about to be used.
    -            IF (S.NE.NA) CALL SWAP(AVAIL(S),AVAIL(NA))	!This block is no longer available.
    -            NA = NA - 1			!Shift the boundary back.
    -            GO TO 1			!Try the next letter!
    -          END IF		!But if we can't find a move at that level...
    -          I = I - 1		!Retreat a level.
    -          IF (I.LE.0) RETURN	!Oh dear!
    -          S = MOVE(I,NMOVE(I) + 1)	!Undo the move that had been made at this level.
    -          NA = NA + 1			!And make its block is re-available.
    -          IF (S.NE.NA) CALL SWAP(AVAIL(S),AVAIL(NA))	!Move it back.
    -          GO TO 2		!See what moves remain at this level.
    +    1     I = I + 1  !One letter after the other.
    +          IF (I.GT.L) GO TO 100  !Yay! We're through!
    +          C = WORD(I:I)    !The letter of the moment.
    +          NMOVE(I) = 0     !No moves known at this new level.
    +          DO S = 1,NA      !So, look for them amongst the available slots.
    +            IF (INDEX(SOME(AVAIL(S)),C) .GT. 0) THEN  !A hit?
    +              NMOVE(I) = NMOVE(I) + 1  !Yes! Count up another possible move.
    +              MOVE(I,NMOVE(I)) = S  !Remember its slot.
    +            END IF         !So much for that block.
    +          END DO     !On to the next.
    +    2     IF (NMOVE(I).GT.0) THEN   !Have we any moves?
    +            S = MOVE(I,NMOVE(I)) !Yes! Recover the last found.
    +            NMOVE(I) = NMOVE(I) - 1 !Uncount, as it is about to be used.
    +            IF (S.NE.NA) CALL SWAP(AVAIL(S),AVAIL(NA))   !This block is no longer available.
    +            NA = NA - 1       !Shift the boundary back.
    +            GO TO 1        !Try the next letter!
    +          END IF     !But if we can't find a move at that level...
    +          I = I - 1     !Retreat a level.
    +          IF (I.LE.0) RETURN  !Oh dear!
    +          S = MOVE(I,NMOVE(I) + 1)  !Undo the move that had been made at this level.
    +          NA = NA + 1         !And make its block is re-available.
    +          IF (S.NE.NA) CALL SWAP(AVAIL(S),AVAIL(NA))  !Move it back.
    +          GO TO 2    !See what moves remain at this level.
     Completed!
    -  100     CANBLOCK = .TRUE.	!That's a relief.
    -        END FUNCTION CANBLOCK	!Some revisions might have been made.
    -      END MODULE PLAYPEN	!No sand here.
    +  100     CANBLOCK = .TRUE.   !That's a relief.
    +        END FUNCTION CANBLOCK !Some revisions might have been made.
    +      END MODULE PLAYPEN   !No sand here.
     
    -      USE PLAYPEN	!Just so.
    -      INTEGER HAVE,TESTS		!Parameters for the specified problem.
    -      PARAMETER (HAVE = 20, TESTS = 7)	!Number of blocks, number of tests.
    -      CHARACTER*(MS) BLOCKS(HAVE)	!Have blocks, will juggle.
    -      DATA BLOCKS/"BO","XK","DQ","CP","NA","GT","RE","TG","QD","FS",	!The specified set
    -     1            "JW","HU","VI","AN","OB","ER","FS","LY","PC","ZM"/	!Of letter blocks.
    -      CHARACTER*8 WORD(TESTS)		!Now for the specified test words.
    -      LOGICAL ANS(TESTS),T,F		!And the given results.
    -      PARAMETER (T = .TRUE., F = .FALSE.)	!Enable a more compact specification.
    -      DATA WORD/"A","BARK","BOOK","TREAT","COMMON","SQUAD","CONFUSE"/	!So that these
    -      DATA  ANS/ T ,    T ,    F ,     T ,      F ,     T ,       T /	!Can be aligned.
    +      USE PLAYPEN !Just so.
    +      INTEGER HAVE,TESTS      !Parameters for the specified problem.
    +      PARAMETER (HAVE = 20, TESTS = 7) !Number of blocks, number of tests.
    +      CHARACTER*(MS) BLOCKS(HAVE)   !Have blocks, will juggle.
    +      DATA BLOCKS/"BO","XK","DQ","CP","NA","GT","RE","TG","QD","FS", !The specified set
    +     1            "JW","HU","VI","AN","OB","ER","FS","LY","PC","ZM"/ !Of letter blocks.
    +      CHARACTER*8 WORD(TESTS)    !Now for the specified test words.
    +      LOGICAL ANS(TESTS),T,F     !And the given results.
    +      PARAMETER (T = .TRUE., F = .FALSE.) !Enable a more compact specification.
    +      DATA WORD/"A","BARK","BOOK","TREAT","COMMON","SQUAD","CONFUSE"/   !So that these
    +      DATA  ANS/ T ,    T ,    F ,     T ,      F ,     T ,       T /   !Can be aligned.
           LOGICAL YAY
           INTEGER I
     
    @@ -266,7 +266,7 @@ Completed!
         1 FORMAT ("Arranges alphabet blocks, attending only to the ",
          1 "letters on the blocks, and ignoring case and orientation.",/)
     
    -      CALL PLAY(HAVE,BLOCKS)	!Some fun first.
    +      CALL PLAY(HAVE,BLOCKS)  !Some fun first.
     
           WRITE (MSG,'(/"Now to see if some words can be spelled out.")')
           DO I = 1,TESTS
    diff --git a/Task/ABC-problem/FutureBasic/abc-problem-1.basic b/Task/ABC-problem/FutureBasic/abc-problem-1.basic
    index 5097485aa6..e9f8bea0fc 100644
    --- a/Task/ABC-problem/FutureBasic/abc-problem-1.basic
    +++ b/Task/ABC-problem/FutureBasic/abc-problem-1.basic
    @@ -1,30 +1,26 @@
    -include "NSLog.incl"
    -
     local fn CanBlocksSpell( w as CFStringRef ) as CFStringRef
    -NSUInteger  i, j
    -CFStringRef s = @"", t1, t2 : if fn StringIsEqual( w, @"" ) then exit fn = @"YES" else w = ucase(w)
    +  long        i, j
    +  CFStringRef s = @"", t1, t2 : if fn StringIsEqual( w, @"" ) then exit fn = @"YES" else w = ucase(w)
     
    -mda(0) = {@"BO",@"XK",@"DQ",@"CP",@"NA",@"GT",@"RE",@"TG",@"QD",¬
    -@"FS",@"JW",@"HU",@"VI",@"AN",@"OB",@"ER",@"FS",@"LY",@"PC",@"ZM"}
    +  mda(0) = {@"BO",@"XK",@"DQ",@"CP",@"NA",@"GT",@"RE",@"TG",@"QD",¬
    +  @"FS",@"JW",@"HU",@"VI",@"AN",@"OB",@"ER",@"FS",@"LY",@"PC",@"ZM"}
     
    -for i = 0 to len(w) - 1
    -for j = 0 to mda_count - 1
    -t1 = mid( mda(j), 0, 1 ) : t2 = mid( mda(j), 1, 1 )
    -if ( fn StringIsEqual( mid( w, i, 1 ), t1 ) ) then s = fn StringByAppendingString( s, t1 ) : mda(j) = @"  " : break
    -if ( fn StringIsEqual( mid( w, i, 1 ), t2 ) ) then s = fn StringByAppendingString( s, t2 ) : mda(j) = @"  " : break
    -next
    -next
    -if fn StringIsEqual( s, w ) then exit fn = @"YES"
    +  for i = 0 to len(w) - 1
    +    for j = 0 to mda_count - 1
    +      t1 = mid( mda(j), 0, 1 ) : t2 = mid( mda(j), 1, 1 )
    +      if ( fn StringIsEqual( mid( w, i, 1 ), t1 ) ) then s = fn StringByAppendingString( s, t1 ) : mda(j) = @"  " : break
    +      if ( fn StringIsEqual( mid( w, i, 1 ), t2 ) ) then s = fn StringByAppendingString( s, t2 ) : mda(j) = @"  " : break
    +    next
    +  next
    +  if fn StringIsEqual( s, w ) then exit fn = @"YES"
     end fn = @"NO"
     
    -NSUInteger  i
    +long        i
     CFArrayRef  words
     CFStringRef w
     words = @[@"", @"a",@"Bark",@"BOOK",@"TrEaT",@"COMMON",@"Squad",@"conFUse",@"ABBA",@"aUtO"]
     for w in words
    -printf @"Can blocks spell %7s : %@", fn StringUTF8String( w ), fn CanBlocksSpell( w )
    +  printf @"Can blocks spell %7s : %@", fn StringUTF8String( w ), fn CanBlocksSpell( w )
     next
     
    -NSLog( @"%@", fn WindowPrintViewString( 1 ) )
    -
     HandleEvents
    diff --git a/Task/ABC-problem/FutureBasic/abc-problem-2.basic b/Task/ABC-problem/FutureBasic/abc-problem-2.basic
    index 0919078013..76e7d3016f 100644
    --- a/Task/ABC-problem/FutureBasic/abc-problem-2.basic
    +++ b/Task/ABC-problem/FutureBasic/abc-problem-2.basic
    @@ -4,7 +4,7 @@ local fn blocks( wordList as str255 )
         found = instr$( 1, blocks, ch )
         select found
           case > 3: mid$( blocks, found and -2, 2 ) = "__" : text , , fn ColorYellow
    -        rect  fill ( x, y + 5.5, 15, 15 ), fn ColorBrown
    +        rect  fill ( x, y + 1, 15, 15 ), fn ColorBrown
           case   0: text , , fn ColorLightGray
           case < 4: blocks=" ,;BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM": x=3: y+=26: ch=""
         end select
    diff --git a/Task/ABC-problem/Go/abc-problem.go b/Task/ABC-problem/Go/abc-problem.go
    index 5ad1a85f59..0f28ef1f06 100644
    --- a/Task/ABC-problem/Go/abc-problem.go
    +++ b/Task/ABC-problem/Go/abc-problem.go
    @@ -1,39 +1,39 @@
     package main
     
     import (
    -	"fmt"
    -	"strings"
    +   "fmt"
    +   "strings"
     )
     
     func newSpeller(blocks string) func(string) bool {
    -	bl := strings.Fields(blocks)
    -	return func(word string) bool {
    -		return r(word, bl)
    -	}
    +   bl := strings.Fields(blocks)
    +   return func(word string) bool {
    +      return r(word, bl)
    +   }
     }
     
     func r(word string, bl []string) bool {
    -	if word == "" {
    -		return true
    -	}
    -	c := word[0] | 32
    -	for i, b := range bl {
    -		if c == b[0]|32 || c == b[1]|32 {
    -			bl[i], bl[0] = bl[0], b
    -			if r(word[1:], bl[1:]) == true {
    -				return true
    -			}
    -			bl[i], bl[0] = bl[0], bl[i]
    -		}
    -	}
    -	return false
    +   if word == "" {
    +      return true
    +   }
    +   c := word[0] | 32
    +   for i, b := range bl {
    +      if c == b[0]|32 || c == b[1]|32 {
    +         bl[i], bl[0] = bl[0], b
    +         if r(word[1:], bl[1:]) == true {
    +            return true
    +         }
    +         bl[i], bl[0] = bl[0], bl[i]
    +      }
    +   }
    +   return false
     }
     
     func main() {
    -	sp := newSpeller(
    -		"BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM")
    -	for _, word := range []string{
    -		"A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE"} {
    -		fmt.Println(word, sp(word))
    -	}
    +   sp := newSpeller(
    +      "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM")
    +   for _, word := range []string{
    +      "A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE"} {
    +      fmt.Println(word, sp(word))
    +   }
     }
    diff --git a/Task/ABC-problem/Insitux/abc-problem.insitux b/Task/ABC-problem/Insitux/abc-problem.insitux
    index aba0f2cc01..6dd31fc0b6 100644
    --- a/Task/ABC-problem/Insitux/abc-problem.insitux
    +++ b/Task/ABC-problem/Insitux/abc-problem.insitux
    @@ -7,5 +7,5 @@
       (.. and (map in-block? word)))
     
     (-> ["A" "bark" "Book" "TREAT" "Common" "squaD" "CoNFuSe"] ; Notice case insensitivity
    -    (map #(str % " => " (can-make-word %)))
    +    (map #"{%} => {can-make-word %}")
         (join ", "))
    diff --git a/Task/ABC-problem/Julia/abc-problem.julia b/Task/ABC-problem/Julia/abc-problem.jl
    similarity index 100%
    rename from Task/ABC-problem/Julia/abc-problem.julia
    rename to Task/ABC-problem/Julia/abc-problem.jl
    diff --git a/Task/ABC-problem/Kotlin/abc-problem.kotlin b/Task/ABC-problem/Kotlin/abc-problem.kts
    similarity index 100%
    rename from Task/ABC-problem/Kotlin/abc-problem.kotlin
    rename to Task/ABC-problem/Kotlin/abc-problem.kts
    diff --git a/Task/ABC-problem/Lang/abc-problem.lang b/Task/ABC-problem/Lang/abc-problem.lang
    index 0e8e9d7054..8444fcad66 100644
    --- a/Task/ABC-problem/Lang/abc-problem.lang
    +++ b/Task/ABC-problem/Lang/abc-problem.lang
    @@ -1,37 +1,37 @@
     fp.canMakeWord = ($word, $blocks) -> {
    -	if(!$word) {
    -		return 1
    -	}
    -	
    -	$word = fn.toLower($word)
    -	
    -	$c $= $word[0]
    -	$i = 0
    -	while($i < @$blocks) {
    -		$block $= fn.toLower($blocks[$i])
    -		
    -		if($block[0] != $c && $block[1] != $c) {	
    -			$i += 1
    -			
    -			con.continue
    -		}
    -		
    -		$blocksCopy $= ^$blocks
    -		fn.listRemoveAt($blocksCopy, $i)
    -		
    -		if(fp.canMakeWord(fn.substring($word, 1), $blocksCopy)) {
    -			return 1
    -		}
    -		
    -		$i += 1
    -	}
    -	
    -	return 0
    +   if(!$word) {
    +      return 1
    +   }
    +
    +   $word = fn.toLower($word)
    +
    +   $c $= $word[0]
    +   $i = 0
    +   while($i < @$blocks) {
    +      $block $= fn.toLower($blocks[$i])
    +
    +      if($block[0] != $c && $block[1] != $c) {
    +         $i += 1
    +
    +         con.continue
    +      }
    +
    +      $blocksCopy $= ^$blocks
    +      fn.listRemoveAt($blocksCopy, $i)
    +
    +      if(fp.canMakeWord(fn.substring($word, 1), $blocksCopy)) {
    +         return 1
    +      }
    +
    +      $i += 1
    +   }
    +
    +   return 0
     }
     
     $blocks = fn.listOf(BO, XK, DQ, CP, NA, GT, RE, TG, QD, FS, JW, HU, VI, AN, OB, ER, FS, LY, PC, ZM)
     
     $word
     foreach($[word], [\e, A, BARK, BOOK, TREAT, COMMON, SQUAD, CONFUSE, Treat, cOmMoN]) {
    -	fn.printf(%s: %s%n, $word, fp.canMakeWord($word, $blocks))
    +   fn.printf(%s: %s%n, $word, fp.canMakeWord($word, $blocks))
     }
    diff --git a/Task/ABC-problem/Lua/abc-problem.lua b/Task/ABC-problem/Lua/abc-problem.lua
    index 3e18d4914a..9effcd462c 100644
    --- a/Task/ABC-problem/Lua/abc-problem.lua
    +++ b/Task/ABC-problem/Lua/abc-problem.lua
    @@ -1,31 +1,31 @@
     blocks = {
    -	{"B","O"};	{"X","K"};	{"D","Q"};	{"C","P"};
    -	{"N","A"};	{"G","T"};	{"R","E"};	{"T","G"};
    -	{"Q","D"};	{"F","S"};	{"J","W"};	{"H","U"};
    -	{"V","I"};	{"A","N"};	{"O","B"};	{"E","R"};
    -	{"F","S"};	{"L","Y"};	{"P","C"};	{"Z","M"};
    -	};
    +   {"B","O"};  {"X","K"};  {"D","Q"};  {"C","P"};
    +   {"N","A"};  {"G","T"};  {"R","E"};  {"T","G"};
    +   {"Q","D"};  {"F","S"};  {"J","W"};  {"H","U"};
    +   {"V","I"};  {"A","N"};  {"O","B"};  {"E","R"};
    +   {"F","S"};  {"L","Y"};  {"P","C"};  {"Z","M"};
    +   };
     
     function canUse(table, letter)
    -	for i,v in pairs(blocks) do
    -		if (v[1] == letter:upper() or v[2] == letter:upper())  and table[i] then
    -			table[i] = false;
    -			return true;
    -		end
    -	end
    -	return false;
    +   for i,v in pairs(blocks) do
    +      if (v[1] == letter:upper() or v[2] == letter:upper())  and table[i] then
    +         table[i] = false;
    +         return true;
    +      end
    +   end
    +   return false;
     end
     
     function canMake(Word)
    -	local Taken = {};
    -	for i,v in pairs(blocks) do
    -		table.insert(Taken,true);
    -	end
    -	local found = true;
    -	for i = 1,#Word do
    -		if not canUse(Taken,Word:sub(i,i)) then
    -			found = false;
    -		end
    -	end
    -	print(found)
    +   local Taken = {};
    +   for i,v in pairs(blocks) do
    +      table.insert(Taken,true);
    +   end
    +   local found = true;
    +   for i = 1,#Word do
    +      if not canUse(Taken,Word:sub(i,i)) then
    +         found = false;
    +      end
    +   end
    +   print(found)
     end
    diff --git a/Task/ABC-problem/MAXScript/abc-problem-1.max b/Task/ABC-problem/MAXScript/abc-problem-1.max
    index c05646f32e..0da376fc34 100644
    --- a/Task/ABC-problem/MAXScript/abc-problem-1.max
    +++ b/Task/ABC-problem/MAXScript/abc-problem-1.max
    @@ -1,98 +1,98 @@
     -- This is the blocks array
     global GlobalBlocks = #("BO","XK","DQ","CP","NA", \
    -			"GT","RE","TG","QD","FS", \
    -			"JW","HU","VI","AN","OB", \
    -			"ER","FS","LY","PC","ZM")
    +         "GT","RE","TG","QD","FS", \
    +         "JW","HU","VI","AN","OB", \
    +         "ER","FS","LY","PC","ZM")
     
     -- This function returns true if "_str" is part of "_word", false otherwise
     fn occurs _str _word =
     (
    -	if _str != undefined and _word != undefined then
    -	(
    -	matchpattern _word pattern:("*"+_str+"*")
    -	) else return false
    +   if _str != undefined and _word != undefined then
    +   (
    +   matchpattern _word pattern:("*"+_str+"*")
    +   ) else return false
     )
     
     -- This is the main function
     fn isWordPossible word blocks: = -- blocks is a keyword argument
     (
    -	word = toupper word -- convert the string to upper case, to make it case insensitive
    -	if blocks == unsupplied do blocks = GlobalBlocks
    -	-- if blocks (keyword argument) is unsupplied, use the global blocks array (this is for recursion)
    -	
    -	blocks = deepcopy blocks
    +   word = toupper word -- convert the string to upper case, to make it case insensitive
    +   if blocks == unsupplied do blocks = GlobalBlocks
    +   -- if blocks (keyword argument) is unsupplied, use the global blocks array (this is for recursion)
     
    -	local pos = 1 -- start at the beginning of the word
    -	local solvedLetters = #() -- this array stores the indices of solved letters
    -	
    -	while pos <= word.count do -- loop through every character in the word
    -	(
    -		local possibleBlocks = #() -- this array stores the blocks which can be used to make that letter
    -		for b = 1 to Blocks.count do -- this loop finds all the possible blocks that can be used to make that letter
    -		(
    -			if occurs word[pos] blocks[b] do
    -			(
    -				appendifunique possibleBlocks b
    -			)
    -		)
    -		if possibleBlocks.count > 0 then -- if it found any blocks
    -		(
    -			if possibleBlocks.count == 1 then -- if it found one block, then continue
    -			(
    -				appendifunique solvedLetters pos
    -				deleteitem blocks possibleblocks[1]
    -				pos += 1
    -			)
    -			else -- if it found more than one
    -			(
    -				for b = 1 to possibleBlocks.count do -- loop through every possible block
    -				(
    -					local possibleBlock = blocks[possibleBlocks[b]]
    -					local blockFirstLetter = possibleBlock[1]
    -					local blockSecondLetter = possibleBlock[2]
    -					local matchingLetter = if blockFirstLetter == word[pos] then 1 else 2
    -					-- ^ this is the index of the matching letter on the block
    -					
    -					local notMatchingIndex = if matchingLetter == 1 then 2 else 1
    -					local notMatchingLetter = possibleBlock[notMatchingIndex]
    -					-- ^ this is the other letter on the block
    -					
    -					if occurs notMatchingLetter (substring word (pos+1) -1) then
    -					( -- if the other letter occurs in the rest of the word
    -						local removedBlocks = deepcopy blocks -- copy the current blocks array
    -						deleteitem removedBlocks possibleBlocks[b] -- remove the item from the copied array
    -						
    -						-- recursively check if the word is possible if that block is taken away from the array:
    -						if (isWordPossible (substring word (pos+1) -1) blocks:removedBlocks) then
    -						( -- if it is, then remove the block and move to next character
    -							appendifunique solvedLetters pos
    -							deleteitem blocks possibleblocks[1]
    -							pos += 1
    -							exit
    -						)
    -						else
    -						( -- if it isn't and it looped through every possible block, then the word is not possible
    -							if b == possibleBlocks.count do return false
    -						)
    -					)
    -					else
    -					( -- if the other letter on this block doesn't occur in the rest of the word, then the letter is solved, continue
    -							appendifunique solvedLetters pos
    -							deleteitem blocks possibleblocks[b]
    -							pos += 1
    -							exit
    -					)
    -				)
    -			)
    -		) else return false -- if it didn't find any blocks, then return false
    -	)
    +   blocks = deepcopy blocks
     
    -	makeuniquearray solvedLetters -- make sure there are no duplicates in the solved array
    -	if solvedLetters.count != word.count then return false -- if number of solved letters is not equal to word length
    -		else
    -			( -- this checks if all the solved letters are the same as the word
    -				check = ""
    -				for bit in solvedLetters do append check word[bit]
    -				if check == word then return true else return false
    -			)
    +   local pos = 1 -- start at the beginning of the word
    +   local solvedLetters = #() -- this array stores the indices of solved letters
    +
    +   while pos <= word.count do -- loop through every character in the word
    +   (
    +      local possibleBlocks = #() -- this array stores the blocks which can be used to make that letter
    +      for b = 1 to Blocks.count do -- this loop finds all the possible blocks that can be used to make that letter
    +      (
    +         if occurs word[pos] blocks[b] do
    +         (
    +            appendifunique possibleBlocks b
    +         )
    +      )
    +      if possibleBlocks.count > 0 then -- if it found any blocks
    +      (
    +         if possibleBlocks.count == 1 then -- if it found one block, then continue
    +         (
    +            appendifunique solvedLetters pos
    +            deleteitem blocks possibleblocks[1]
    +            pos += 1
    +         )
    +         else -- if it found more than one
    +         (
    +            for b = 1 to possibleBlocks.count do -- loop through every possible block
    +            (
    +               local possibleBlock = blocks[possibleBlocks[b]]
    +               local blockFirstLetter = possibleBlock[1]
    +               local blockSecondLetter = possibleBlock[2]
    +               local matchingLetter = if blockFirstLetter == word[pos] then 1 else 2
    +               -- ^ this is the index of the matching letter on the block
    +
    +               local notMatchingIndex = if matchingLetter == 1 then 2 else 1
    +               local notMatchingLetter = possibleBlock[notMatchingIndex]
    +               -- ^ this is the other letter on the block
    +
    +               if occurs notMatchingLetter (substring word (pos+1) -1) then
    +               ( -- if the other letter occurs in the rest of the word
    +                  local removedBlocks = deepcopy blocks -- copy the current blocks array
    +                  deleteitem removedBlocks possibleBlocks[b] -- remove the item from the copied array
    +
    +                  -- recursively check if the word is possible if that block is taken away from the array:
    +                  if (isWordPossible (substring word (pos+1) -1) blocks:removedBlocks) then
    +                  ( -- if it is, then remove the block and move to next character
    +                     appendifunique solvedLetters pos
    +                     deleteitem blocks possibleblocks[1]
    +                     pos += 1
    +                     exit
    +                  )
    +                  else
    +                  ( -- if it isn't and it looped through every possible block, then the word is not possible
    +                     if b == possibleBlocks.count do return false
    +                  )
    +               )
    +               else
    +               ( -- if the other letter on this block doesn't occur in the rest of the word, then the letter is solved, continue
    +                     appendifunique solvedLetters pos
    +                     deleteitem blocks possibleblocks[b]
    +                     pos += 1
    +                     exit
    +               )
    +            )
    +         )
    +      ) else return false -- if it didn't find any blocks, then return false
    +   )
    +
    +   makeuniquearray solvedLetters -- make sure there are no duplicates in the solved array
    +   if solvedLetters.count != word.count then return false -- if number of solved letters is not equal to word length
    +      else
    +         ( -- this checks if all the solved letters are the same as the word
    +            check = ""
    +            for bit in solvedLetters do append check word[bit]
    +            if check == word then return true else return false
    +         )
     )
    diff --git a/Task/ABC-problem/MAXScript/abc-problem-3.max b/Task/ABC-problem/MAXScript/abc-problem-3.max
    index 4681f1b686..3aeab87682 100644
    --- a/Task/ABC-problem/MAXScript/abc-problem-3.max
    +++ b/Task/ABC-problem/MAXScript/abc-problem-3.max
    @@ -1,30 +1,30 @@
     fn isWordPossible2 word =
     (
    -	Blocks = #("BO","XK","DQ","CP","NA", \
    -			   "GT","RE","TG","QD","FS", \
    -			   "JW","HU","VI","AN","OB", \
    -			   "ER","FS","LY","PC","ZM")
    +   Blocks = #("BO","XK","DQ","CP","NA", \
    +            "GT","RE","TG","QD","FS", \
    +            "JW","HU","VI","AN","OB", \
    +            "ER","FS","LY","PC","ZM")
             word = toupper word
    -	local pos = 1
    -	local solvedLetters = #()
    -	while pos <= word.count do
    -	(
    -		for i = 1 to blocks.count do
    -		(
    -			if (matchpattern blocks[i] pattern:("*"+word[pos]+"*")) then
    -				(
    -					deleteitem blocks i
    -					appendifunique solvedLetters pos
    -					pos +=1
    -					exit
    -				)
    -			else if i == blocks.count do return false
    -		)
    -	)
    -	if solvedLetters.count == word.count then
    -	(
    -		local check = ""
    -		for bit in solvedLetters do append check word[bit]
    -		if check == word then return true else return false
    -	) else return false
    +   local pos = 1
    +   local solvedLetters = #()
    +   while pos <= word.count do
    +   (
    +      for i = 1 to blocks.count do
    +      (
    +         if (matchpattern blocks[i] pattern:("*"+word[pos]+"*")) then
    +            (
    +               deleteitem blocks i
    +               appendifunique solvedLetters pos
    +               pos +=1
    +               exit
    +            )
    +         else if i == blocks.count do return false
    +      )
    +   )
    +   if solvedLetters.count == word.count then
    +   (
    +      local check = ""
    +      for bit in solvedLetters do append check word[bit]
    +      if check == word then return true else return false
    +   ) else return false
     )
    diff --git a/Task/ABC-problem/Maple/abc-problem.maple b/Task/ABC-problem/Maple/abc-problem.maple
    index 98312bccce..0937c92c58 100644
    --- a/Task/ABC-problem/Maple/abc-problem.maple
    +++ b/Task/ABC-problem/Maple/abc-problem.maple
    @@ -1,23 +1,23 @@
     canSpell := proc(w)
    -	local blocks, i, j, word, letterFound;
    -	blocks := Array([["B", "O"], ["X", "K"], ["D", "Q"], ["C", "P"], ["N", "A"], ["G", "T"], ["R", "E"], ["T", "G"],
    +   local blocks, i, j, word, letterFound;
    +   blocks := Array([["B", "O"], ["X", "K"], ["D", "Q"], ["C", "P"], ["N", "A"], ["G", "T"], ["R", "E"], ["T", "G"],
                              ["Q", "D"], ["F", "S"], ["J", "W"], ["H", "U"], ["V", "I"], ["A", "N"], ["O", "B"], ["E", "R"],
                              ["F", "S"], ["L", "Y"], ["P", "C"], ["Z", "M"]]);
    -	word := StringTools[UpperCase](convert(w, string));
    -	for i to length(word) do
    -		letterFound := false;
    -		for j to numelems(blocks)/2 do
    -			if not letterFound and (substring(word, i) = blocks[j,1] or substring(word, i) = blocks[j,2]) then
    -				blocks[j,1] := undefined;
    -				blocks[j,2] := undefined;
    -				letterFound := true;
    -			end if;
    -		end do;
    -		if not letterFound then
    -			return false;
    -		end if;
    -	end do;
    -	return true;
    +   word := StringTools[UpperCase](convert(w, string));
    +   for i to length(word) do
    +      letterFound := false;
    +      for j to numelems(blocks)/2 do
    +         if not letterFound and (substring(word, i) = blocks[j,1] or substring(word, i) = blocks[j,2]) then
    +            blocks[j,1] := undefined;
    +            blocks[j,2] := undefined;
    +            letterFound := true;
    +         end if;
    +      end do;
    +      if not letterFound then
    +         return false;
    +      end if;
    +   end do;
    +   return true;
     end proc:
     
     seq(printf("%a: %a\n", i, canSpell(i)), i in [a, Bark, bOok, treat, COMMON, squad, confuse]);
    diff --git a/Task/ABC-problem/OCaml/abc-problem.ocaml b/Task/ABC-problem/OCaml/abc-problem.ml
    similarity index 100%
    rename from Task/ABC-problem/OCaml/abc-problem.ocaml
    rename to Task/ABC-problem/OCaml/abc-problem.ml
    diff --git a/Task/ABC-problem/Pluto/abc-problem.pluto b/Task/ABC-problem/Pluto/abc-problem.pluto
    new file mode 100644
    index 0000000000..243a9a5f79
    --- /dev/null
    +++ b/Task/ABC-problem/Pluto/abc-problem.pluto
    @@ -0,0 +1,25 @@
    +function r(word, bl)
    +    if word == "" then return true end
    +    local c = word:byte(1) | 32
    +    for i = 1, #bl do
    +        local b = bl[i]
    +        if c == b:byte(1) | 32 or c == b:byte(2) | 32 then
    +            bl[i] = bl[1]
    +            bl[1] = b
    +            if r(word:sub(2), bl:slice(2)) then return true end
    +            bl[1], bl[i] = bl[i], bl[1]
    +        end
    +    end
    +    return false
    +end
    +
    +local function new_speller(blocks)
    +    local bl = blocks:split(" ")
    +    return |word| -> r(word, bl)
    +end
    +
    +local sp = new_speller("BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM")
    +local words = {"A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE"}
    +for words as word do
    +    print(string.format("%-7s %s", word, sp(word)))
    +end
    diff --git a/Task/ABC-problem/PowerBASIC/abc-problem.basic b/Task/ABC-problem/PowerBASIC/abc-problem.basic
    index ff524d89eb..4a29562c45 100644
    --- a/Task/ABC-problem/PowerBASIC/abc-problem.basic
    +++ b/Task/ABC-problem/PowerBASIC/abc-problem.basic
    @@ -20,7 +20,7 @@
     '1.Once a letter on a block is used that block cannot be used again
     '2.The function should be case-insensitive
     '3. Show your output on this page for the following words:
    -'	A, BARK, BOOK, TREAT, COMMON, SQUAD, CONFUSE
    +'  A, BARK, BOOK, TREAT, COMMON, SQUAD, CONFUSE
     '-----------------------------------------------------------------------------
     ' G l o b a l   C o n s t a n t s
     '
    diff --git a/Task/ABC-problem/PowerShell/abc-problem.ps1 b/Task/ABC-problem/PowerShell/abc-problem.ps1
    new file mode 100644
    index 0000000000..3c8a1239a4
    --- /dev/null
    +++ b/Task/ABC-problem/PowerShell/abc-problem.ps1
    @@ -0,0 +1,117 @@
    +<#
    +.Synopsis
    +  ABC Problem
    +.DESCRIPTION
    +   You are given a collection of ABC blocks. Just like the ones you had when you were a kid.
    +   There are twenty blocks with two letters on each block. You are guaranteed to have a
    +   complete alphabet amongst all sides of the blocks
    +   blocks = "BO","XK","DQ","CP","NA","GT","RE","TG","QD","FS","JW","HU","VI","AN","OB","ER","FS","LY","PC","ZM"
    +   The goal of this task is to write a function that takes a string and can determine whether
    +   you can spell the word with the given collection of blocks.
    +
    +   The rules are simple:
    +        1.Once a letter on a block is used that block cannot be used again
    +        2.The function should be case-insensitive
    +        3. Show your output on this page for the following words:
    +        >>> can_make_word("A")
    +        True
    +        >>> can_make_word("BARK")
    +        True
    +        >>> can_make_word("BOOK")
    +        False
    +        >>> can_make_word("TREAT")
    +        True
    +        >>> can_make_word("COMMON")
    +        False
    +        >>> can_make_word("SQUAD")
    +        True
    +        >>> can_make_word("CONFUSE")
    +        True
    +
    +   Using the examples below  you can either see just the value or
    +   status and the values using the verbose switch
    +
    +.EXAMPLE
    +   test-blocks -testword confuse
    +
    +.EXAMPLE
    +   test-blocks -testword confuse -verbose
    +
    +#>
    +
    +function test-blocks
    +{
    +   [CmdletBinding()]
    +   #  [OutputType([int])]
    +   Param
    +   (
    +      # word to test against blocks
    +      [Parameter(Mandatory = $true,
    +               ValueFromPipelineByPropertyName = $true)]
    +      $testword
    +
    +   )
    +
    +   $word = $testword
    +
    +   #define array of blocks
    +   [System.Collections.ArrayList]$blockarray = "BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS", "JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM"
    +
    +   #send word to chararray
    +   $chararray = $word.ToCharArray()
    +   $chars = $chararray
    +
    +   #get the character count
    +   $charscount = $chars.count
    +
    +   #get the initial count of the blocks
    +   $blockcount = $blockarray.Count
    +
    +   #find out how many blocks should be left from the difference
    +   #of the blocks and characters in the word - 1 letter/1 block
    +   $correctblockcount = $blockcount - $charscount
    +
    +   #loop through the characters in the word
    +   foreach ($char in $chars)
    +   {
    +
    +      #loop through the blocks
    +      foreach ($block in $blockarray)
    +      {
    +
    +         #check the current character against each letter on the current block
    +         #and break if found so the array can reload
    +         if ($char -in $block[0] -or $char -in $block[1])
    +         {
    +
    +            write-verbose "match for letter - $char - removing block $block"
    +            $blockarray.Remove($block)
    +            break
    +
    +         }
    +
    +      }
    +
    +   }
    +   #get final count of blocks left in array to determine if the word was
    +   #correctly made
    +   $finalblockcount = $blockarray.count
    +   if ($finalblockcount -ne $correctblockcount)
    +   {
    +      write-verbose "$word : $false "
    +      return $false
    +   }
    +   else
    +   {
    +      write-verbose "$word : $true "
    +      return $true
    +   }
    +
    +}
    +
    +#loop all the words and pass them to the function
    +$wordlist = "a", "bark", "book", "treat", "common", "squad", "confuse"
    +foreach ($word in $wordlist)
    +{
    +   test-blocks -testword $word -Verbose
    +}
    diff --git a/Task/ABC-problem/PowerShell/abc-problem.psh b/Task/ABC-problem/PowerShell/abc-problem.psh
    deleted file mode 100644
    index 9fd301dcac..0000000000
    --- a/Task/ABC-problem/PowerShell/abc-problem.psh
    +++ /dev/null
    @@ -1,117 +0,0 @@
    -<#
    -.Synopsis
    -  ABC Problem
    -.DESCRIPTION
    -   You are given a collection of ABC blocks. Just like the ones you had when you were a kid.
    -   There are twenty blocks with two letters on each block. You are guaranteed to have a
    -   complete alphabet amongst all sides of the blocks
    -   blocks = "BO","XK","DQ","CP","NA","GT","RE","TG","QD","FS","JW","HU","VI","AN","OB","ER","FS","LY","PC","ZM"
    -   The goal of this task is to write a function that takes a string and can determine whether
    -   you can spell the word with the given collection of blocks.
    -
    -   The rules are simple:
    -        1.Once a letter on a block is used that block cannot be used again
    -        2.The function should be case-insensitive
    -        3. Show your output on this page for the following words:
    -        >>> can_make_word("A")
    -        True
    -        >>> can_make_word("BARK")
    -        True
    -        >>> can_make_word("BOOK")
    -        False
    -        >>> can_make_word("TREAT")
    -        True
    -        >>> can_make_word("COMMON")
    -        False
    -        >>> can_make_word("SQUAD")
    -        True
    -        >>> can_make_word("CONFUSE")
    -        True
    -
    -   Using the examples below  you can either see just the value or
    -   status and the values using the verbose switch
    -
    -.EXAMPLE
    -   test-blocks -testword confuse
    -
    -.EXAMPLE
    -   test-blocks -testword confuse -verbose
    -
    -#>
    -
    -function test-blocks
    -{
    -	[CmdletBinding()]
    -	#  [OutputType([int])]
    -	Param
    -	(
    -		# word to test against blocks
    -		[Parameter(Mandatory = $true,
    -				   ValueFromPipelineByPropertyName = $true)]
    -		$testword
    -		
    -	)
    -
    -	$word = $testword
    -	
    -	#define array of blocks
    -	[System.Collections.ArrayList]$blockarray = "BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS", "JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM"
    -	
    -	#send word to chararray
    -	$chararray = $word.ToCharArray()
    -	$chars = $chararray
    -	
    -	#get the character count
    -	$charscount = $chars.count
    -	
    -	#get the initial count of the blocks
    -	$blockcount = $blockarray.Count
    -	
    -	#find out how many blocks should be left from the difference
    -	#of the blocks and characters in the word - 1 letter/1 block
    -	$correctblockcount = $blockcount - $charscount
    -	
    -	#loop through the characters in the word
    -	foreach ($char in $chars)
    -	{
    -		
    -		#loop through the blocks
    -		foreach ($block in $blockarray)
    -		{
    -			
    -			#check the current character against each letter on the current block
    -			#and break if found so the array can reload
    -			if ($char -in $block[0] -or $char -in $block[1])
    -			{
    -				
    -				write-verbose "match for letter - $char - removing block $block"
    -				$blockarray.Remove($block)
    -				break
    -				
    -			}
    -			
    -		}
    -		
    -	}
    -	#get final count of blocks left in array to determine if the word was
    -	#correctly made
    -	$finalblockcount = $blockarray.count
    -	if ($finalblockcount -ne $correctblockcount)
    -	{
    -		write-verbose "$word : $false "
    -		return $false
    -	}
    -	else
    -	{
    -		write-verbose "$word : $true "
    -		return $true
    -	}
    -	
    -}
    -
    -#loop all the words and pass them to the function
    -$wordlist = "a", "bark", "book", "treat", "common", "squad", "confuse"
    -foreach ($word in $wordlist)
    -{
    -	test-blocks -testword $word -Verbose
    -}
    diff --git a/Task/ABC-problem/Prolog/abc-problem-1.pro b/Task/ABC-problem/Prolog/abc-problem-1.pro
    index 99d543c21b..90c7559163 100644
    --- a/Task/ABC-problem/Prolog/abc-problem-1.pro
    +++ b/Task/ABC-problem/Prolog/abc-problem-1.pro
    @@ -1,22 +1,22 @@
     abc_problem :-
    -	maplist(abc_problem, ['', 'A', bark, bOOk, treAT, 'COmmon', sQuaD, 'CONFUSE']).
    +   maplist(abc_problem, ['', 'A', bark, bOOk, treAT, 'COmmon', sQuaD, 'CONFUSE']).
     
     
     abc_problem(Word) :-
    -	L = [[b,o],[x,k],[d,q],[c,p],[n,a],[g,t],[r,e],[t,g],[q,d],[f,s],
    -	     [j,w],[h,u],[v,i],[a,n],[o,b],[e,r],[f,s],[l,y],[p,c],[z,m]],
    +   L = [[b,o],[x,k],[d,q],[c,p],[n,a],[g,t],[r,e],[t,g],[q,d],[f,s],
    +        [j,w],[h,u],[v,i],[a,n],[o,b],[e,r],[f,s],[l,y],[p,c],[z,m]],
     
    -	(   abc_problem(L, Word)
    -	->  format('~w OK~n', [Word])
    -	;   format('~w KO~n', [Word])).
    +   (   abc_problem(L, Word)
    +   ->  format('~w OK~n', [Word])
    +   ;   format('~w KO~n', [Word])).
     
     abc_problem(L, Word) :-
    -	atom_chars(Word, C_Words),
    -	maplist(downcase_atom, C_Words, D_Words),
    -	can_makeword(L, D_Words).
    +   atom_chars(Word, C_Words),
    +   maplist(downcase_atom, C_Words, D_Words),
    +   can_makeword(L, D_Words).
     
     can_makeword(_L, []).
     
     can_makeword(L, [H | T]) :-
    -	(   select([H, _], L, L1); select([_, H], L, L1)),
    -	can_makeword(L1, T).
    +   (   select([H, _], L, L1); select([_, H], L, L1)),
    +   can_makeword(L1, T).
    diff --git a/Task/ABC-problem/Rebol/abc-problem.rebol b/Task/ABC-problem/Rebol/abc-problem.rebol
    new file mode 100644
    index 0000000000..fe63851d8f
    --- /dev/null
    +++ b/Task/ABC-problem/Rebol/abc-problem.rebol
    @@ -0,0 +1,38 @@
    +Rebol [
    +    title: "Rosetta code: ABC problem"
    +    file:  %ABC_problem.r3
    +    url:   https://rosettacode.org/wiki/ABC_problem
    +    needs: 3.10.0 ;; or something like that
    +    note:  "Based on Red language solution"
    +]
    +;; Define the function 'test' that takes a string argument 's'
    +test: function [s [string!]][
    +    ;; Make a copy of the input string to work on (avoid mutation of original)
    +    s: copy s
    +    ;; Initialize 'p' as a copy of a specific character sequence
    +    p: copy "BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM"
    +    ;; Start an infinite loop
    +    forever [
    +        ;; If 's' is empty, return true (all characters matched/removed)
    +        if 0 = length? s [return  true]
    +        ;; If 'p' is at the tail (all pairs tried), return false (no match)
    +        if tail? p       [return false]
    +        ;; Create a parsing rule of the current two characters in 'p'
    +        rule: reduce [first p  '| second p]
    +        ;; Try to parse 's' according to the current rule:
    +        ;; If parsing succeeds, remove that rule from the string
    +        p: either parse s [to rule remove rule to end ] [
    +            ;; If parsing succeeded, remove the current pair from 'p'
    +            head remove/part p 2
    +        ][
    +            ;; If parsing failed, skip the current pair in 'p' (move to next pair)
    +            skip p 2
    +        ]
    +    ]
    +]
    +
    +;; Test the 'test' function on each word split from a string (split by space).
    +foreach word split {A bark book TrEAT COmMoN SQUAD conFUsE} space [
    +    ;; Print the word and its result from 'test'
    +    printf [8 ": "] reduce [word test word]
    +]
    diff --git a/Task/ABC-problem/Rust/abc-problem.rust b/Task/ABC-problem/Rust/abc-problem.rs
    similarity index 100%
    rename from Task/ABC-problem/Rust/abc-problem.rust
    rename to Task/ABC-problem/Rust/abc-problem.rs
    diff --git a/Task/ABC-problem/SNOBOL4/abc-problem.sno b/Task/ABC-problem/SNOBOL4/abc-problem.sno
    index b8cb880ab1..0ed5f49e73 100644
    --- a/Task/ABC-problem/SNOBOL4/abc-problem.sno
    +++ b/Task/ABC-problem/SNOBOL4/abc-problem.sno
    @@ -4,46 +4,46 @@
     
     * Read in blocks to construct the blocks string
     in1
    -	line = replace(input,&lcase,&ucase) :f(in1end)
    -	line ? breakx(' ') . pre ' ' rem . post :f(in1end)
    -	blocks = blocks "," pre post
    -	:(in1)
    +   line = replace(input,&lcase,&ucase) :f(in1end)
    +   line ? breakx(' ') . pre ' ' rem . post :f(in1end)
    +   blocks = blocks "," pre post
    +   :(in1)
     in1end
     
     * Function to determine if a word can be constructed with the given blocks
    -	define('abc(blocks,word)s,i,let')
    -		abcpat = (breakx(',') ',') . pre (*let len(1) | len(1) *let) rem . post
    -	:(abc_end)
    +   define('abc(blocks,word)s,i,let')
    +      abcpat = (breakx(',') ',') . pre (*let len(1) | len(1) *let) rem . post
    +   :(abc_end)
     abc
    -	eq(size(word),0) :s(abc3)
    -	s = replace(word,&lcase,&ucase)
    -	i = 0
    +   eq(size(word),0) :s(abc3)
    +   s = replace(word,&lcase,&ucase)
    +   i = 0
     abc2
    -	i = lt(i,size(s)) i + 1 :f(abc4)
    -	let = substr(s,i,1)
    -	blocks ? abcpat = pre post :f(abc3)
    -	:(abc2)
    +   i = lt(i,size(s)) i + 1 :f(abc4)
    +   let = substr(s,i,1)
    +   blocks ? abcpat = pre post :f(abc3)
    +   :(abc2)
     abc3
    -	abc = 'False' :(abc5)
    +   abc = 'False' :(abc5)
     abc4
    -	abc = 'True'  :(abc5)
    +   abc = 'True'  :(abc5)
     abc5
    -	output = lpad('can_make_word("' word '"): ',26) abc
    -	abc = ""
    -	:(return)
    +   output = lpad('can_make_word("' word '"): ',26) abc
    +   abc = ""
    +   :(return)
     abc_end
     
     * Check words
    -*	output = abc(blocks,"")
    -*	output = abc(blocks," ")
    -	output = abc(blocks,'A')
    -	output = abc(blocks,'bark')
    -	output = abc(blocks,'BOOK')
    -	output = abc(blocks,'TrEAT')
    -	output = abc(blocks,'COMMON')
    -	output = abc(blocks,'SQUAD')
    -	output = abc(blocks,'CONFUSE')
    -	
    +*  output = abc(blocks,"")
    +*  output = abc(blocks," ")
    +   output = abc(blocks,'A')
    +   output = abc(blocks,'bark')
    +   output = abc(blocks,'BOOK')
    +   output = abc(blocks,'TrEAT')
    +   output = abc(blocks,'COMMON')
    +   output = abc(blocks,'SQUAD')
    +   output = abc(blocks,'CONFUSE')
    +
     * The blocks are entered below, after the following END label
     END
     b o
    diff --git a/Task/ABC-problem/Scheme/abc-problem.ss b/Task/ABC-problem/Scheme/abc-problem.scm
    similarity index 100%
    rename from Task/ABC-problem/Scheme/abc-problem.ss
    rename to Task/ABC-problem/Scheme/abc-problem.scm
    diff --git a/Task/ABC-problem/SenseTalk/abc-problem-1.sensetalk b/Task/ABC-problem/SenseTalk/abc-problem-1.sensetalk
    index abbfa87d9a..ca1dcb76f7 100644
    --- a/Task/ABC-problem/SenseTalk/abc-problem-1.sensetalk
    +++ b/Task/ABC-problem/SenseTalk/abc-problem-1.sensetalk
    @@ -1,41 +1,41 @@
     function CanMakeWord word
     
    -	put [
    -		("B", "O"),
    -		("X", "K"),
    -		("D", "Q"),
    -		("C", "P"),
    -		("N", "A"),
    -		("G", "T"),
    -		("R", "E"),
    -		("T", "G"),
    -		("Q", "D"),
    -		("F", "S"),
    -		("J", "W"),
    -		("H", "U"),
    -		("V", "I"),
    -		("A", "N"),
    -		("O", "B"),
    -		("E", "R"),
    -		("F", "S"),
    -		("L", "Y"),
    -		("P", "C"),
    -		("Z", "M")
    -	] into blocks
    -	
    -	repeat with each character letter of word
    -		put False into found
    -		repeat with each item block of blocks by reference
    -			if item 1 of block is letter ignoring case or item 2 of block is letter ignoring case
    -				delete block
    -				put True into found
    -				exit repeat
    -			end if
    -		end repeat
    -		if found is False
    -			return False
    -		end if
    -	end repeat
    -	return True
    -	
    +   put [
    +      ("B", "O"),
    +      ("X", "K"),
    +      ("D", "Q"),
    +      ("C", "P"),
    +      ("N", "A"),
    +      ("G", "T"),
    +      ("R", "E"),
    +      ("T", "G"),
    +      ("Q", "D"),
    +      ("F", "S"),
    +      ("J", "W"),
    +      ("H", "U"),
    +      ("V", "I"),
    +      ("A", "N"),
    +      ("O", "B"),
    +      ("E", "R"),
    +      ("F", "S"),
    +      ("L", "Y"),
    +      ("P", "C"),
    +      ("Z", "M")
    +   ] into blocks
    +
    +   repeat with each character letter of word
    +      put False into found
    +      repeat with each item block of blocks by reference
    +         if item 1 of block is letter ignoring case or item 2 of block is letter ignoring case
    +            delete block
    +            put True into found
    +            exit repeat
    +         end if
    +      end repeat
    +      if found is False
    +         return False
    +      end if
    +   end repeat
    +   return True
    +
     end CanMakeWord
    diff --git a/Task/ABC-problem/SenseTalk/abc-problem-2.sensetalk b/Task/ABC-problem/SenseTalk/abc-problem-2.sensetalk
    index 8949df06a2..7bbcd3910d 100644
    --- a/Task/ABC-problem/SenseTalk/abc-problem-2.sensetalk
    +++ b/Task/ABC-problem/SenseTalk/abc-problem-2.sensetalk
    @@ -1,11 +1,11 @@
     repeat with each item word in [
    -	"A",
    -	"BARK",
    -	"BOOK",
    -	"TREAT",
    -	"COMMON",
    -	"SQUAD",
    -	"CONFUSE"
    +   "A",
    +   "BARK",
    +   "BOOK",
    +   "TREAT",
    +   "COMMON",
    +   "SQUAD",
    +   "CONFUSE"
             ]
    -	put CanMakeWord(word)
    +   put CanMakeWord(word)
     end repeat
    diff --git a/Task/ABC-problem/SequenceL/abc-problem-1.sequencel b/Task/ABC-problem/SequenceL/abc-problem-1.sequencel
    index 57f03ba268..eabaaedc4f 100644
    --- a/Task/ABC-problem/SequenceL/abc-problem-1.sequencel
    +++ b/Task/ABC-problem/SequenceL/abc-problem-1.sequencel
    @@ -2,28 +2,28 @@ import ;
     import ;
     
     main(args(2)) :=
    -	let
    -		result[i] := args[i] ++ ": " ++ boolToString(can_make_word(args[i], InitBlocks));
    -	in
    -		delimit(result, '\n');
    +   let
    +      result[i] := args[i] ++ ": " ++ boolToString(can_make_word(args[i], InitBlocks));
    +   in
    +      delimit(result, '\n');
     
     InitBlocks :=  ["BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS", "JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM"];
    -			
    +
     can_make_word(word(1), blocks(2)) :=
    -	let
    -		choices[i] := i when some(blocks[i] = toUpper(head(word)));
    -		blocksAfterChoice[i] := blocks[(1 ... (choices[i] - 1)) ++ ((choices[i] + 1) ... size(blocks))];
    -	in
    -		true when size(word) = 0
    -	else
    -		false when size(choices) = 0
    -	else
    -		some(can_make_word(tail(word), blocksAfterChoice));
    -		
    +   let
    +      choices[i] := i when some(blocks[i] = toUpper(head(word)));
    +      blocksAfterChoice[i] := blocks[(1 ... (choices[i] - 1)) ++ ((choices[i] + 1) ... size(blocks))];
    +   in
    +      true when size(word) = 0
    +   else
    +      false when size(choices) = 0
    +   else
    +      some(can_make_word(tail(word), blocksAfterChoice));
    +
     toUpper(letter(0)) :=
    -	let
    -		ascii := asciiToInt(letter);
    -	in
    -		letter when ascii >= 65 and ascii <= 90
    -	else
    -		intToAscii(ascii -  32);
    +   let
    +      ascii := asciiToInt(letter);
    +   in
    +      letter when ascii >= 65 and ascii <= 90
    +   else
    +      intToAscii(ascii -  32);
    diff --git a/Task/ABC-problem/SequenceL/abc-problem-2.sequencel b/Task/ABC-problem/SequenceL/abc-problem-2.sequencel
    index a82214ee48..11b30e8581 100644
    --- a/Task/ABC-problem/SequenceL/abc-problem-2.sequencel
    +++ b/Task/ABC-problem/SequenceL/abc-problem-2.sequencel
    @@ -3,29 +3,29 @@ import ;
     import ;
     
     main(args(2)) :=
    -	let
    -		result[i] := args[i] ++ ": " ++ boolToString(can_make_word(args[i], InitBlocks));
    -	in
    -		delimit(result, '\n');
    +   let
    +      result[i] := args[i] ++ ": " ++ boolToString(can_make_word(args[i], InitBlocks));
    +   in
    +      delimit(result, '\n');
     
     InitBlocks :=  "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM";
    -			
    +
     can_make_word(word(1), blocks(1)) :=
    -	let
    -		regEx := "(\\a" ++ [toUpper(head(word))] ++ "|" ++ [toUpper(head(word))] ++ "\\a)";
    -		
    -		newBlocks := replaceFirst(blocks, regEx, "");
    -	in
    -		true when size(word) = 0
    -	else
    -		false when size(newBlocks) = size(blocks)
    -	else
    -		can_make_word(tail(word), newBlocks);
    +   let
    +      regEx := "(\\a" ++ [toUpper(head(word))] ++ "|" ++ [toUpper(head(word))] ++ "\\a)";
    +
    +      newBlocks := replaceFirst(blocks, regEx, "");
    +   in
    +      true when size(word) = 0
    +   else
    +      false when size(newBlocks) = size(blocks)
    +   else
    +      can_make_word(tail(word), newBlocks);
     
     toUpper(letter(0)) :=
    -	let
    -		ascii := asciiToInt(letter);
    -	in
    -		letter when ascii >= 65 and ascii <= 90
    -	else
    -		intToAscii(ascii -  32);
    +   let
    +      ascii := asciiToInt(letter);
    +   in
    +      letter when ascii >= 65 and ascii <= 90
    +   else
    +      intToAscii(ascii -  32);
    diff --git a/Task/ABC-problem/Smalltalk/abc-problem.st b/Task/ABC-problem/Smalltalk/abc-problem.st
    index d6a10f2fbe..3b23286677 100644
    --- a/Task/ABC-problem/Smalltalk/abc-problem.st
    +++ b/Task/ABC-problem/Smalltalk/abc-problem.st
    @@ -1,21 +1,21 @@
     ABCPuzzle>>test
    -	#('A' 'BARK' 'BOOK' 'TreaT' 'COMMON' 'sQUAD' 'CONFuSE') do: [ :each |
    -		Transcript crShow: each, ': ', (self solveFor: each) asString ]
    +   #('A' 'BARK' 'BOOK' 'TreaT' 'COMMON' 'sQUAD' 'CONFuSE') do: [ :each |
    +      Transcript crShow: each, ': ', (self solveFor: each) asString ]
     
     ABCPuzzle>>solveFor: letters
    -	| blocks |
    -	blocks := #('BO' 'XK' 'DQ' 'CP' 'NA' 'GT' 'RE' 'TG' 'QD' 'FS' 'JW' 'HU' 'VI' 'AN' 'OB' 'ER' 'FS' 'LY' 'PC' 'ZM').
    -	^ self solveFor: letters asUppercase with: blocks asOrderedCollection
    +   | blocks |
    +   blocks := #('BO' 'XK' 'DQ' 'CP' 'NA' 'GT' 'RE' 'TG' 'QD' 'FS' 'JW' 'HU' 'VI' 'AN' 'OB' 'ER' 'FS' 'LY' 'PC' 'ZM').
    +   ^ self solveFor: letters asUppercase with: blocks asOrderedCollection
     
     ABCPuzzle>>solveFor: letters with: blocks
    -	| l ldash matches |
    -	letters isEmpty ifTrue: [ ^ true ].
    -	l := letters first.
    -	ldash := letters allButFirst.
    -	matches := blocks select: [  :b | b includes: l ].
    -	matches isEmpty ifTrue: [ ^ false ].
    -	matches do: [  :m | | bdash |
    -		bdash := blocks copy.
    -		bdash remove: m.
    -		(self solveFor: ldash with: bdash) ifTrue: [ ^ true ] ].
    -	^ false
    +   | l ldash matches |
    +   letters isEmpty ifTrue: [ ^ true ].
    +   l := letters first.
    +   ldash := letters allButFirst.
    +   matches := blocks select: [  :b | b includes: l ].
    +   matches isEmpty ifTrue: [ ^ false ].
    +   matches do: [  :m | | bdash |
    +      bdash := blocks copy.
    +      bdash remove: m.
    +      (self solveFor: ldash with: bdash) ifTrue: [ ^ true ] ].
    +   ^ false
    diff --git a/Task/ABC-problem/Swift/abc-problem-2.swift b/Task/ABC-problem/Swift/abc-problem-2.swift
    index 026a22d936..be73620266 100644
    --- a/Task/ABC-problem/Swift/abc-problem-2.swift
    +++ b/Task/ABC-problem/Swift/abc-problem-2.swift
    @@ -1,20 +1,20 @@
     import Swift
     
     func canMake(word: String) -> Bool {
    -	var blocks = [
    -		"BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS",
    -		"JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM"
    -	]
    -	
    -	for letter in word.uppercased().characters {
    -		guard let index = blocks.index(where: { $0.characters.contains(letter) }) else {
    -			return false
    -		}
    -		
    -		blocks.remove(at: index)
    -	}
    -	
    -	return true
    +   var blocks = [
    +      "BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS",
    +      "JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM"
    +   ]
    +
    +   for letter in word.uppercased().characters {
    +      guard let index = blocks.index(where: { $0.characters.contains(letter) }) else {
    +         return false
    +      }
    +
    +      blocks.remove(at: index)
    +   }
    +
    +   return true
     }
     
     let words = ["a", "bARK", "boOK", "TreAt", "CoMmon", "SquAd", "CONFUse"]
    diff --git a/Task/ABC-problem/Tcl/abc-problem.tcl b/Task/ABC-problem/Tcl/abc-problem.tcl
    index d3f4b8f321..7dab1aa0e6 100644
    --- a/Task/ABC-problem/Tcl/abc-problem.tcl
    +++ b/Task/ABC-problem/Tcl/abc-problem.tcl
    @@ -2,16 +2,16 @@ package require Tcl 8.6
     
     proc abc {word {blocks {BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM}}} {
         set abc {{letters blocks abc} {
    -	set rest [lassign $letters ch]
    -	set i 0
    -	foreach blk $blocks {
    -	    if {$ch in $blk && (![llength $rest]
    -		    || [apply $abc $rest [lreplace $blocks $i $i] $abc])} {
    -		return true
    -	    }
    -	    incr i
    -	}
    -	return false
    +   set rest [lassign $letters ch]
    +   set i 0
    +   foreach blk $blocks {
    +       if {$ch in $blk && (![llength $rest]
    +          || [apply $abc $rest [lreplace $blocks $i $i] $abc])} {
    +      return true
    +       }
    +       incr i
    +   }
    +   return false
         }}
         return [apply $abc [split $word ""] [lmap b $blocks {split $b ""}] $abc]
     }
    diff --git a/Task/ABC-problem/Transd/abc-problem.transd b/Task/ABC-problem/Transd/abc-problem.transd
    index 3ac73650a8..b0bf878924 100644
    --- a/Task/ABC-problem/Transd/abc-problem.transd
    +++ b/Task/ABC-problem/Transd/abc-problem.transd
    @@ -2,7 +2,7 @@
     
     MainModule: {
         blocks: ["BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS",
    -		"JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM"],
    +      "JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM"],
         words: ["A","BARK","BOOK","TREAT","COMMON","SQUAD","CONFUSE"],
     
         testMake: Lambda Bool>(λ
    @@ -16,7 +16,7 @@ MainModule: {
             )
             (ret false)
         ),
    -	_start: (lambda
    +   _start: (lambda
             (for word in words do
                 (lout :boolalpha word " : "
                     (exec testMake word blocks))
    diff --git a/Task/ABC-problem/Uiua/abc-problem.uiua b/Task/ABC-problem/Uiua/abc-problem.uiua
    new file mode 100644
    index 0000000000..244ecba154
    --- /dev/null
    +++ b/Task/ABC-problem/Uiua/abc-problem.uiua
    @@ -0,0 +1,4 @@
    +s   ← "BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM"
    +Flt ← ⊂⊙↘₂⊃↙↘-⊸◿2⊸˜⨂ # remove block holding letter
    +{"A" "BARK" "BOOK" "TREAT" "COMMON" "SQUAD" "CONFUSE"}
    +≡⊂⟜⍚(◌◌⍥(⍥(⊙⊙⋅0)⊸≍⟜˜Flt⊙°⊂)◡⋅⧻ s ⊙1)
    diff --git a/Task/ABC-problem/Ultimate++/abc-problem.ultimate++ b/Task/ABC-problem/Ultimate++/abc-problem.ultimate++
    index 13a35283ad..fbfcebdcc0 100644
    --- a/Task/ABC-problem/Ultimate++/abc-problem.ultimate++
    +++ b/Task/ABC-problem/Ultimate++/abc-problem.ultimate++
    @@ -19,84 +19,84 @@ using namespace Upp;
     
     int can_make_words(char **b, char *word)
     {
    -	int i, ret = 0, c = toupper(*word);
    -	
    -	if (!c) return 1;
    -	if (!b[0]) return 0;
    -	
    -	for (i = 0; b[i] && !ret; i++) {
    -		if (b[i][0] != c && b[i][1] != c) continue;
    -		Swap(b[i], b[0]);  // It needs to be Swap and not SWAP
    -		ret = can_make_words(b + 1, word + 1);
    -		Swap(b[i], b[0]);  // It needs to be Swap instead of SWAP
    -	}
    -	return ret;
    +   int i, ret = 0, c = toupper(*word);
    +
    +   if (!c) return 1;
    +   if (!b[0]) return 0;
    +
    +   for (i = 0; b[i] && !ret; i++) {
    +      if (b[i][0] != c && b[i][1] != c) continue;
    +      Swap(b[i], b[0]);  // It needs to be Swap and not SWAP
    +      ret = can_make_words(b + 1, word + 1);
    +      Swap(b[i], b[0]);  // It needs to be Swap instead of SWAP
    +   }
    +   return ret;
     }
     
     
     //C++
     
     bool can_create_word(const std::string& w, const list_t& vals) {
    -	std::set used;
    -	while (used.size() < w.size()) {
    -		const char c = toupper(w[used.size()]);
    -		uint32_t x = used.size();
    -		for (uint32_t i = 0, ii = vals.size(); i < ii; ++i) {
    -			if (used.find(i) == used.end()) {
    -				if (toupper(vals[i].first) == c || toupper(vals[i].second) == c) {
    -					used.insert(i);
    -					break;
    -				}
    -			}
    -		}
    -		if (x == used.size()) break;
    -	}
    -	return used.size() == w.size();
    +   std::set used;
    +   while (used.size() < w.size()) {
    +      const char c = toupper(w[used.size()]);
    +      uint32_t x = used.size();
    +      for (uint32_t i = 0, ii = vals.size(); i < ii; ++i) {
    +         if (used.find(i) == used.end()) {
    +            if (toupper(vals[i].first) == c || toupper(vals[i].second) == c) {
    +               used.insert(i);
    +               break;
    +            }
    +         }
    +      }
    +      if (x == used.size()) break;
    +   }
    +   return used.size() == w.size();
     }
     
     
     // U++
     CONSOLE_APP_MAIN
     {
    -	// C
    -	char* blocks[] =
    -	{
    -		(char*)"BO", (char*)"XK", (char*)"DQ", (char*)"CP",
    -		(char*)"NA", (char*)"GT", (char*)"RE", (char*)"TG",
    -		(char*)"QD", (char*)"FS", (char*)"JW", (char*)"HU",
    -		(char*)"VI", (char*)"AN", (char*)"OB", (char*)"ER",
    -		(char*)"FS", (char*)"LY", (char*)"PC", (char*)"ZM", 0
    -	};
    +   // C
    +   char* blocks[] =
    +   {
    +      (char*)"BO", (char*)"XK", (char*)"DQ", (char*)"CP",
    +      (char*)"NA", (char*)"GT", (char*)"RE", (char*)"TG",
    +      (char*)"QD", (char*)"FS", (char*)"JW", (char*)"HU",
    +      (char*)"VI", (char*)"AN", (char*)"OB", (char*)"ER",
    +      (char*)"FS", (char*)"LY", (char*)"PC", (char*)"ZM", 0
    +   };
     
    -	char *words[] =
    -	{
    -		(char*)"", (char*)"A", (char*)"BARK", (char*)"BOOK",
    -		(char*)"TREAT", (char*)"COMMON", (char*)"SQUAD", (char*)"Confuse", 0
    -	};
    -	
    -	char **w;
    -	for (w = words; *w; w++)
    -		printf("%s\t%d\n", *w, can_make_words(blocks, *w));	
    -	
    -	printf("\n");
    -	
    -	// C++
    -	list_t vals{ {'B', 'O'}, {'X', 'K'}, {'D', 'Q'}, {'C', 'P'},
    -		{'N', 'A'}, {'G', 'T'}, {'R', 'E'}, {'T', 'G'}, {'Q', 'D'},
    -		{'F', 'S'}, {'J', 'W'}, {'H', 'U'}, {'V', 'I'}, {'A', 'N'},
    -		{'O', 'B'}, {'E', 'R'}, {'F', 'S'}, {'L', 'Y'}, {'P', 'C'},
    -		{'Z', 'M'}
    -	};
    -	std::vector wordsb{"A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "Confuse"};
    -	for (const std::string& w : wordsb) {
    -		std::cout << w << ": " << std::boolalpha << can_create_word(w, vals) << ".\n";
    -	}
    -	std::cout << "\n";
    -	
    +   char *words[] =
    +   {
    +      (char*)"", (char*)"A", (char*)"BARK", (char*)"BOOK",
    +      (char*)"TREAT", (char*)"COMMON", (char*)"SQUAD", (char*)"Confuse", 0
    +   };
     
    -	
    -	const Vector& cmdline = CommandLine();
    -	for(int i = 0; i < cmdline.GetCount(); i++) {
    -	}
    +   char **w;
    +   for (w = words; *w; w++)
    +      printf("%s\t%d\n", *w, can_make_words(blocks, *w));
    +
    +   printf("\n");
    +
    +   // C++
    +   list_t vals{ {'B', 'O'}, {'X', 'K'}, {'D', 'Q'}, {'C', 'P'},
    +      {'N', 'A'}, {'G', 'T'}, {'R', 'E'}, {'T', 'G'}, {'Q', 'D'},
    +      {'F', 'S'}, {'J', 'W'}, {'H', 'U'}, {'V', 'I'}, {'A', 'N'},
    +      {'O', 'B'}, {'E', 'R'}, {'F', 'S'}, {'L', 'Y'}, {'P', 'C'},
    +      {'Z', 'M'}
    +   };
    +   std::vector wordsb{"A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "Confuse"};
    +   for (const std::string& w : wordsb) {
    +      std::cout << w << ": " << std::boolalpha << can_create_word(w, vals) << ".\n";
    +   }
    +   std::cout << "\n";
    +
    +
    +
    +   const Vector& cmdline = CommandLine();
    +   for(int i = 0; i < cmdline.GetCount(); i++) {
    +   }
     
     }
    diff --git a/Task/ABC-problem/V-(Vlang)/abc-problem.v b/Task/ABC-problem/V-(Vlang)/abc-problem.v
    index fbda461417..f34fa80d4b 100644
    --- a/Task/ABC-problem/V-(Vlang)/abc-problem.v
    +++ b/Task/ABC-problem/V-(Vlang)/abc-problem.v
    @@ -1,29 +1,28 @@
    -const
    -(
    -	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"]
    -)
    +const blocks = ["BO","XK","DQ","CP","NA","GT","RE","TG","QD","FS",
    +"JW","HU","VI","AN","OB","ER","FS","LY","PC","ZM"]
    +
    +const words = ["A", "BARK","BOOK","TREAT","COMMON","SQUAD","CONFUSE"]
     
     fn main() {
    -	for word in words {
    -		println('>>> can_make_word("${word.to_upper()}"): ')
    -		if check_word(word, blocks) == true {println('True')} else {println('False')}
    -	}
    +   for word in words {
    +      println('>>> can_make_word("${word.to_upper()}"): ')
    +      if check_word(word, blocks) == true { println("True") } else { println("False") }
    +   }
     }
     
     fn check_word(word string, blocks []string) bool {
    -	mut tblocks := blocks.clone()
    -	mut found := false
    -	for chr in word {
    -		found = false
    -		for idx, _ in tblocks {
    -			if tblocks[idx].contains(chr.ascii_str()) == true {
    -				tblocks[idx] =''
    -				found = true
    -				break
    -			}
    -		}
    -		if found == false {return found}
    -	}
    -	return found
    +   mut tblocks := blocks.clone()
    +   mut found := false
    +   for chr in word {
    +      found = false
    +      for idx, _ in tblocks {
    +         if tblocks[idx].contains(chr.ascii_str()) == true {
    +            tblocks[idx] =""
    +            found = true
    +            break
    +         }
    +      }
    +      if found == false { return found }
    +   }
    +   return found
     }
    diff --git a/Task/ABC-problem/Yabasic/abc-problem.basic b/Task/ABC-problem/Yabasic/abc-problem.basic
    index c2e561b9f7..d7db87519a 100644
    --- a/Task/ABC-problem/Yabasic/abc-problem.basic
    +++ b/Task/ABC-problem/Yabasic/abc-problem.basic
    @@ -1,28 +1,28 @@
     letters$ = "BO,XK,DQ,CP,NA,GT,RE,TG,QD,FS,JW,HU,VI,AN,OB,ER,FS,LY,PC,ZM"
     
     sub canMake(letters$, word$)
    -	local i, j, p, n, pairs$(1)
    -	
    -	n = token(letters$, pairs$(), ",")
    -	word$ = upper$(word$)
    -	
    -	for i = 1 to len(word$)
    -		for j = 1 to n
    -			p = instr(pairs$(j), mid$(word$, i, 1))
    -			if p then
    -				pairs$(j) = ""
    -				break
    -			end if
    -		next j
    -		if not p return false
    -	next i
    -	return true
    +   local i, j, p, n, pairs$(1)
    +
    +   n = token(letters$, pairs$(), ",")
    +   word$ = upper$(word$)
    +
    +   for i = 1 to len(word$)
    +      for j = 1 to n
    +         p = instr(pairs$(j), mid$(word$, i, 1))
    +         if p then
    +            pairs$(j) = ""
    +            break
    +         end if
    +      next j
    +      if not p return false
    +   next i
    +   return true
     end sub
     
    -print "a = ", canMake(letters$, "a")	// 1 = true
    -print "bark = ", canMake(letters$, "Bark")	// 1
    -print "book = ", canMake(letters$, "BooK")	// 0 = false
    -print "treat = ", canMake(letters$, "TREAt")	// 1
    -print "common = ", canMake(letters$, "common")	// 0
    -print "squad = ", canMake(letters$, "squad")	// 1
    -print "confuse = ", canMake(letters$, "confuse")	// 1
    +print "a = ", canMake(letters$, "a")   // 1 = true
    +print "bark = ", canMake(letters$, "Bark")   // 1
    +print "book = ", canMake(letters$, "BooK")   // 0 = false
    +print "treat = ", canMake(letters$, "TREAt") // 1
    +print "common = ", canMake(letters$, "common")  // 0
    +print "squad = ", canMake(letters$, "squad") // 1
    +print "confuse = ", canMake(letters$, "confuse")   // 1
    diff --git a/Task/ABC-problem/Zig/abc-problem.zig b/Task/ABC-problem/Zig/abc-problem.zig
    new file mode 100644
    index 0000000000..ea586f7323
    --- /dev/null
    +++ b/Task/ABC-problem/Zig/abc-problem.zig
    @@ -0,0 +1,54 @@
    +const std = @import("std");
    +
    +const Block: type = struct { Char1: u8, Char2: u8 };
    +const BLOCK_SIZE: comptime_int = 20;
    +const blocks: [BLOCK_SIZE]Block = .{
    +    .{ .Char1 = 'B', .Char2 = 'O' }, .{ .Char1 = 'X', .Char2 = 'K' },
    +    .{ .Char1 = 'D', .Char2 = 'Q' }, .{ .Char1 = 'C', .Char2 = 'P' },
    +    .{ .Char1 = 'N', .Char2 = 'A' }, .{ .Char1 = 'G', .Char2 = 'T' },
    +    .{ .Char1 = 'R', .Char2 = 'E' }, .{ .Char1 = 'T', .Char2 = 'G' },
    +    .{ .Char1 = 'Q', .Char2 = 'D' }, .{ .Char1 = 'F', .Char2 = 'S' },
    +    .{ .Char1 = 'J', .Char2 = 'W' }, .{ .Char1 = 'H', .Char2 = 'U' },
    +    .{ .Char1 = 'V', .Char2 = 'I' }, .{ .Char1 = 'A', .Char2 = 'N' },
    +    .{ .Char1 = 'O', .Char2 = 'B' }, .{ .Char1 = 'E', .Char2 = 'R' },
    +    .{ .Char1 = 'F', .Char2 = 'S' }, .{ .Char1 = 'L', .Char2 = 'Y' },
    +    .{ .Char1 = 'P', .Char2 = 'C' }, .{ .Char1 = 'Z', .Char2 = 'M' },
    +};
    +
    +fn can_make_word(word: []const u8) bool {
    +    var marked: [BLOCK_SIZE]bool = [_]bool{false} ** BLOCK_SIZE;
    +
    +    for (word) |char| {
    +        var hasBlock: bool = false;
    +
    +        for (blocks, 0..) |block, index| {
    +            if ((block.Char1 == char or block.Char2 == char) and !marked[index]) {
    +                hasBlock = true;
    +                marked[index] = true;
    +                break;
    +            }
    +        }
    +
    +        if (!hasBlock) {
    +            return false;
    +        }
    +    }
    +
    +    return true;
    +}
    +
    +pub fn main() !void {
    +    const words: []const []const u8 = &.{
    +        "A",
    +        "BARK",
    +        "BOOK",
    +        "TREAT",
    +        "COMMON",
    +        "SQUAD",
    +        "CONFUSE",
    +    };
    +
    +    for (words) |word| {
    +        std.debug.print("{s}\t{any}\n", .{ word, can_make_word(word) });
    +    }
    +}
    diff --git a/Task/ABC-problem/Zkl/abc-problem.zkl b/Task/ABC-problem/Zkl/abc-problem.zkl
    index 66da4854fc..a34c775681 100644
    --- a/Task/ABC-problem/Zkl/abc-problem.zkl
    +++ b/Task/ABC-problem/Zkl/abc-problem.zkl
    @@ -1,14 +1,14 @@
     var blocks=T("BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS",
    -	     "JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM", );
    +        "JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM", );
     
     fcn can_make_word(word){
        fcn(blks,word){
           if (not word) return(True);  // bottom of recursion
           foreach b in (blks){ n:=__bWalker.idx;
    -	 if(not b.holds(word[0])) continue; // letter not on this block
    -	 blks.del(n);		// remove this block from pile
    -	 if (self.fcn(blks,word[1,*])) return(True);  // try remaining blocks
    -	 blks.insert(n,b);	// put block back in pile: backtracking
    +    if(not b.holds(word[0])) continue; // letter not on this block
    +    blks.del(n);     // remove this block from pile
    +    if (self.fcn(blks,word[1,*])) return(True);  // try remaining blocks
    +    blks.insert(n,b);   // put block back in pile: backtracking
           }
           False;   // out of blocks but not out of word
        }(blocks.copy(),word.toUpper())
    diff --git a/Task/ABC-problem/Zonnon/abc-problem.zonnon b/Task/ABC-problem/Zonnon/abc-problem.zonnon
    index c0dde3c245..731ebadcf1 100644
    --- a/Task/ABC-problem/Zonnon/abc-problem.zonnon
    +++ b/Task/ABC-problem/Zonnon/abc-problem.zonnon
    @@ -1,87 +1,87 @@
     module Main;
     type
    -	Block = record
    -		l,r: char;
    -		used: boolean;
    -	end Block;
    +   Block = record
    +      l,r: char;
    +      used: boolean;
    +   end Block;
     
     var
    -	blocks: array 20 of Block;
    +   blocks: array 20 of Block;
     
     procedure Exists(c: char): boolean;
     var
    -	i: integer;
    -	r: boolean;
    +   i: integer;
    +   r: boolean;
     begin
    -	r := false;i := 0;
    -	while ~r & (i < len(blocks)) do
    -		if ~(blocks[i].used) then
    -			r := (blocks[i].l = cap(c)) or (blocks[i].r = cap(c));
    -			blocks[i].used := r;
    -		end;
    -		inc(i)
    -	end;
    -	return r
    +   r := false;i := 0;
    +   while ~r & (i < len(blocks)) do
    +      if ~(blocks[i].used) then
    +         r := (blocks[i].l = cap(c)) or (blocks[i].r = cap(c));
    +         blocks[i].used := r;
    +      end;
    +      inc(i)
    +   end;
    +   return r
     end Exists;
     
     procedure CanMakeWord(s: string);
     var
    -	i: integer;
    -	made: boolean;
    +   i: integer;
    +   made: boolean;
     begin
    -	made := true;
    -	for i := 0 to len(s) - 1 do
    -		made := made & Exists(s[i])
    -	end;
    -	writeln(s:20,"?",made);
    -	Clean()	
    +   made := true;
    +   for i := 0 to len(s) - 1 do
    +      made := made & Exists(s[i])
    +   end;
    +   writeln(s:20,"?",made);
    +   Clean()
     end CanMakeWord;
     
     procedure Clean();
     var
    -	i: integer;
    +   i: integer;
     begin
    -	for i := 0 to len(blocks) - 1 do
    -		blocks[i].used := false
    -	end
    +   for i := 0 to len(blocks) - 1 do
    +      blocks[i].used := false
    +   end
     end Clean;
     
     procedure InitBlock(i:integer;l,r:char);
     begin
    -	blocks[i].l := l;blocks[i].r := r;
    -	blocks[i].used := false;
    +   blocks[i].l := l;blocks[i].r := r;
    +   blocks[i].used := false;
     end InitBlock;
     
     procedure Init;
     begin
    -	InitBlock(0,'B','O');
    -	InitBlock(1,'X','K');
    -	InitBlock(2,'D','Q');
    -	InitBlock(3,'C','Q');
    -	InitBlock(4,'N','A');
    -	InitBlock(5,'G','T');
    -	InitBlock(6,'R','E');
    -	InitBlock(7,'T','G');
    -	InitBlock(8,'Q','D');
    -	InitBlock(9,'F','S');
    -	InitBlock(10,'J','W');
    -	InitBlock(11,'H','U');
    -	InitBlock(12,'V','I');
    -	InitBlock(13,'A','N');
    -	InitBlock(14,'O','B');
    -	InitBlock(15,'E','R');
    -	InitBlock(16,'F','S');
    -	InitBlock(17,'L','Y');
    -	InitBlock(18,'P','C');
    -	InitBlock(19,'Z','M')
    +   InitBlock(0,'B','O');
    +   InitBlock(1,'X','K');
    +   InitBlock(2,'D','Q');
    +   InitBlock(3,'C','Q');
    +   InitBlock(4,'N','A');
    +   InitBlock(5,'G','T');
    +   InitBlock(6,'R','E');
    +   InitBlock(7,'T','G');
    +   InitBlock(8,'Q','D');
    +   InitBlock(9,'F','S');
    +   InitBlock(10,'J','W');
    +   InitBlock(11,'H','U');
    +   InitBlock(12,'V','I');
    +   InitBlock(13,'A','N');
    +   InitBlock(14,'O','B');
    +   InitBlock(15,'E','R');
    +   InitBlock(16,'F','S');
    +   InitBlock(17,'L','Y');
    +   InitBlock(18,'P','C');
    +   InitBlock(19,'Z','M')
     end Init;
     
     begin
    -	Init();
    -	CanMakeWord("A");
    -	CanMakeWord("BARK");
    -	CanMakeWord("BOOK");
    -	CanMakeWord("TREAT");
    -	CanMakeWord("COMMON");
    -	CanMakeWord("confuse");
    +   Init();
    +   CanMakeWord("A");
    +   CanMakeWord("BARK");
    +   CanMakeWord("BOOK");
    +   CanMakeWord("TREAT");
    +   CanMakeWord("COMMON");
    +   CanMakeWord("confuse");
     end Main.
    diff --git a/Task/ADFGVX-cipher/11l/adfgvx-cipher.11l b/Task/ADFGVX-cipher/11l/adfgvx-cipher.11l
    index e1dd671422..739e221d0a 100644
    --- a/Task/ADFGVX-cipher/11l/adfgvx-cipher.11l
    +++ b/Task/ADFGVX-cipher/11l/adfgvx-cipher.11l
    @@ -3,8 +3,8 @@ V adfgvx = ‘ADFGVX’
     F encrypt(plainText, polybius, key)
        V s = ‘’
        L(ch) plainText
    -      L(r) 6
    -         L(c) 6
    +      L(r) 0.<6
    +         L(c) 0.<6
                 I polybius[r][c] == ch
                    s ‘’= :adfgvx[r]‘’:adfgvx[c]
     
    @@ -43,8 +43,8 @@ F decrypt(cipherText, polybius, key)
     V polybius = [[Char("\0")] * 6] * 6
     V alphabet = ‘ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789’
     random:shuffle(&alphabet)
    -L(r) 6
    -   L(c) 6
    +L(r) 0.<6
    +   L(c) 0.<6
           polybius[r][c] = alphabet[6 * r + c]
     
     print("6 x 6 Polybius square:\n")
    diff --git a/Task/ADFGVX-cipher/APL/adfgvx-cipher.apl b/Task/ADFGVX-cipher/APL/adfgvx-cipher.apl
    new file mode 100644
    index 0000000000..93c8c07787
    --- /dev/null
    +++ b/Task/ADFGVX-cipher/APL/adfgvx-cipher.apl
    @@ -0,0 +1,39 @@
    +adfgvx←{
    +    n←⎕NS''
    +    n.split←↑{⍺≥⍴⍵:⊂⍵ ⋄ (⊂⍺↑⍵),⍺∇⍺↓⍵}
    +
    +    n.enc←⍺{
    +        t←∊(∘.,⍨'ADFGVX')[⊃∘⍸∘(⍺⍺∘=)¨⍵]
    +        w←↓⍉((⍴⍵⍵)split t)[;⍋⍵⍵]
    +        1↓∊' ',¨w~¨' '
    +    }⍵
    +
    +    n.dec←⍺{
    +        t←↓2 split (∊(⍉↑⍵⊆⍨' '≠⍵)[;⍋⍋⍵⍵])~' '
    +        ⍺⍺['ADFGVX'∘⍳¨t]
    +    }⍵
    +
    +    n
    +}
    +
    +adfgvx_test←{
    +    square←6 6⍴(⎕A,⎕D)[?⍨36]
    +    ⎕←'Polybius square:'
    +    ⎕←' ─ADFGVX','│┼││││││','A D F G V X' ⍪'─'⍪(11⍴1 0)\square
    +    ⎕←''
    +
    +    key←{
    +        file←'e:\unixdict.txt'
    +        dict←(~data∊⎕TC)⊆data←⊃⎕NGET file
    +        dict←(⍵{⍺=≢⍵}¨dict)/dict
    +        dict←({⍵≡∪⍵}¨dict)/dict
    +        1⎕C ⊃dict[?⍴dict]
    +    }9
    +    ⎕←'Key: ',key
    +
    +    a←square adfgvx key
    +
    +    ⎕←'Plaintext: ',plaintext←'ATTACKAT1200AM'
    +    ⎕←'Encrypted: ',encrypted←a.enc plaintext
    +    ⎕←'Decrypted: ',a.dec encrypted
    +}
    diff --git a/Task/ADFGVX-cipher/C-sharp/adfgvx-cipher.cs b/Task/ADFGVX-cipher/C-sharp/adfgvx-cipher.cs
    new file mode 100644
    index 0000000000..3f4f47932f
    --- /dev/null
    +++ b/Task/ADFGVX-cipher/C-sharp/adfgvx-cipher.cs
    @@ -0,0 +1,117 @@
    +using System.Diagnostics;
    +
    +const string cypher = "ADFGVX";
    +var N = cypher.Length;
    +var size = N * N;
    +const string symbols = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    +Debug.Assert(size == symbols.Length);
    +var square = new int[size];
    +
    +for (var i = 0; i < size; i++)
    +{
    +    var j = Random.Shared.Next(i + 1);
    +    square[i] = square[j];
    +    square[j] = i;
    +}
    +
    +Console.WriteLine($"{N} x {N} Polybius square:");
    +Console.WriteLine();
    +Console.WriteLine($"  | {string.Join(' ', cypher.AsEnumerable())}");
    +Console.WriteLine(new string('-', 2 * N + 3));
    +
    +for (var row = 0; row < N; row++)
    +{
    +    Console.Write($"{cypher[row]} |");
    +
    +    for (var col = 0; col < N; col++)
    +    {
    +        Console.Write($" {symbols[square[col + row * N]]}");
    +    }
    +
    +    Console.WriteLine();
    +}
    +
    +static bool IsSuitableTranspositionKey(string s) =>
    +    s.Length >= 7 && s.Length <= 12 && s.Length == s.Distinct().Count() && s.All(symbols.ToLowerInvariant().Contains);
    +
    +var keys = File.ReadAllLines("unixdict.txt").Where(IsSuitableTranspositionKey).ToArray();
    +var key = keys[Random.Shared.Next(keys.Length)].ToUpperInvariant();
    +Console.WriteLine();
    +Console.WriteLine($"The key is {key}");
    +var plaintext = "ATTACKAT1200AM";
    +Console.WriteLine($"Plaintext: {plaintext}");
    +
    +string Encrypt(string plaintext, string key, int[] square)
    +{
    +    // Create a lookup table from symbol to fragment
    +    var map = (from i in Enumerable.Range(0, size)
    +               let k = square[i]
    +               let code = cypher[i / N] + "" + cypher[i % N]
    +               select (k, code))
    +               .ToDictionary(kc => symbols[kc.k], kc => kc.code);
    +
    +    // Map the plaintext to fragments
    +    var e = string.Join("", plaintext.Select(c => map[c]));
    +
    +    // Determine number of rows
    +    var K = key.Length;
    +    var rows = (e.Length + K - 1) / K;
    +
    +    // Pad with spaces
    +    e += new string(' ', rows * K - e.Length);
    +
    +    // Sort the key
    +    var order = string.Join("", key.OrderBy(c => c)).Select(c => key.IndexOf(c)).ToArray();
    +
    +    // Reorder the fragments.
    +    e = string.Join("", Enumerable.Range(0, K * rows).Select(i => e[(i / K) * K + order[i % K]]));
    +
    +    // Transpose
    +    e = new([.. from col in Enumerable.Range(0, K)
    +                from row in Enumerable.Range(0, rows)
    +                select e[row * K + col]]);
    +
    +    // Read off each column.
    +    return string.Join(" ", Enumerable.Range(0, K).Select(col => e.Substring(col * rows, rows).Trim()));
    +}
    +
    +var encrypted = Encrypt(plaintext, key, square);
    +Console.WriteLine($"Encrypted: {encrypted}");
    +
    +string Decrypt(string encrypted, string key, int[] square)
    +{
    +    // Create a lookup table from fragment to symbol
    +    var map = (from i in Enumerable.Range(0, size)
    +               let k = square[i]
    +               let code = cypher[i / N] + "" + cypher[i % N]
    +               select (k, code))
    +               .ToDictionary(kc => kc.code, kc => symbols[kc.k]);
    +
    +    // Split into columns
    +    var cols = encrypted.Split(' ');
    +
    +    // Determine number of rows
    +    var K = key.Length;
    +    var rows = cols.Max(c => c.Length);
    +
    +    // Pad each column
    +    cols = [.. cols.Select(c => c.PadRight(rows))];
    +
    +    // Transpose
    +    string e = new([.. from row in Enumerable.Range(0, rows)
    +                       from col in Enumerable.Range(0, K)
    +                       select cols[col][row]]);
    +
    +    // Sort the key
    +    var sorted = string.Join("", key.OrderBy(c => c));
    +    var order = key.Select(c => sorted.IndexOf(c)).ToArray();
    +
    +    // Reorder the fragments
    +    e = string.Join("", Enumerable.Range(0, K * rows).Select(i => e[(i / K) * K + order[i % K]])).Trim();
    +
    +    // Map the fragments to plaintext
    +    return string.Join("", Enumerable.Range(0, e.Length / 2).Select(i => map[e.Substring(2 * i, 2)]));
    +}
    +
    +var decrypted = Decrypt(encrypted, key, square);
    +Console.WriteLine($"Decrypted: {decrypted}");
    diff --git a/Task/ADFGVX-cipher/Crystal/adfgvx-cipher.cr b/Task/ADFGVX-cipher/Crystal/adfgvx-cipher.cr
    new file mode 100644
    index 0000000000..3236abc45a
    --- /dev/null
    +++ b/Task/ADFGVX-cipher/Crystal/adfgvx-cipher.cr
    @@ -0,0 +1,62 @@
    +def make_square
    +  # it's a square at heart...
    +  (('A'..'Z').to_a + ('0'..'9').to_a).shuffle!
    +end
    +
    +def make_key (size)
    +  words = File.open("unixdict.txt") do |f|
    +    f.each_line.select {|w| w.size == size && w.chars.to_set.size == size }.to_a
    +  end
    +  raise "no suitable key found" if words.empty?
    +  words.sample
    +end
    +
    +def adfgvx_encrypt (message, square, key)
    +  h = "ADFGVX".chars
    +  message.chars.flat_map {|ch|
    +    row, col = square.index!(ch).divmod(6)
    +    [ h[row], h[col] ]
    +  }
    +    .in_groups_of(key.size)
    +    .transpose
    +    .zip(key.chars)
    +    .sort_by {|_, key| key }
    +    .map {|col, _| col.join }
    +    .join(" ")
    +end
    +
    +def adfgvx_decrypt (message, square, key)
    +  h = "ADFGVX".chars
    +  sorted_key = key.chars.sort!
    +  cols = message.split.map &.chars
    +  max_size = cols.max_of &.size
    +  cols.map {|col| col + [nil]*(max_size-col.size) }
    +    .zip(sorted_key)
    +    .sort_by {|_, ch| key.index! ch }
    +    .map {|col, _| col }
    +    .transpose
    +    .flatten.compact
    +    .in_slices_of(2)
    +    .map {|(row, col)| square[ h.index!(row)*6 + h.index!(col) ] }
    +    .join
    +end
    +
    +def show (title, message, square, key)
    +  encrypted = adfgvx_encrypt message, square, key
    +  decrypted = adfgvx_decrypt encrypted, square, key
    +  puts title
    +  puts " - Alphabet: #{square.join}"
    +  puts " - Key:      #{key}"
    +  puts " - Message:   #{message}"
    +  puts " - Encrypted: #{encrypted}"
    +  puts " - Decrypted: #{decrypted}"
    +  puts
    +end
    +
    +message = "ATTACKAT1200AM"
    +
    +wiki_square = "NA1C3H8TB2OME5WRPD4F6G7I9J0KLQSUVXYZ".chars
    +wiki_key = "PRIVACY"
    +
    +show "Wikipedia example:", message, wiki_square, wiki_key
    +show "Random square and key:", message, make_square, make_key(9)
    diff --git a/Task/ADFGVX-cipher/Fortran/adfgvx-cipher.f b/Task/ADFGVX-cipher/Fortran/adfgvx-cipher.f
    new file mode 100644
    index 0000000000..40af143af8
    --- /dev/null
    +++ b/Task/ADFGVX-cipher/Fortran/adfgvx-cipher.f
    @@ -0,0 +1,618 @@
    +!
    +! ADFGVX Cipher
    +! tested with Intel ifx (IFX) 2025.2.1 20250806             on Kubuntu 25.10
    +!             GNU Fortran (Ubuntu 15.2.0-4ubuntu4) 15.2.0   on Kubuntu 25.10
    +! VSI Fortran on VMS does not compile it because it cannot handle
    +! allocatable character strings.
    +! U.B., December 2025
    +!==============================================================================
    +
    +program ADFGVXCipher
    +
    +  implicit none
    +
    +  logical, parameter :: DEBUG = .false.     ! set to .true. for reproducable, not random results
    +  logical, parameter :: VERBOSE = .false.   ! set this to .true. to print some intermediate results
    +  integer, parameter :: maxLen=100          ! Maximum length of any test message (including extensions as 'X')
    +
    +  integer, parameter :: minPassLen=7, maxPassLen=12   ! Minimum and maximum password length
    +
    +  ! The complete alphabet of capital letters as used in most western languages, plus numbers 0...9
    +  character (len=36), parameter :: Alphabet ='ABCDEFGHIJKLMNOPQRSTUVWXYZ01234567879'
    +  character (len=*), parameter :: ADFGVX = 'ADFGVX'
    +
    +  character (len=maxLen)    :: MsgToEncrypt, DecryptedMsg
    +  character (len=2*maxLen) :: EncryptedMsg   ! encrypt makes 2 letters from 1
    +  character (len=25)        :: PassPhrase
    +  integer, parameter :: ColWidth = 6     ! depends on length of the used alphabet but we use only 36 letters
    +
    +  character (len=36) :: PolyAlphabet      ! Permutation of Alphabet to represent Polybius square
    +  integer :: i
    +
    +  ! Initialize random number generator once for the entire run-time of the program and all test cases
    +  call random_seed()
    +
    +
    +  ! The message to encrypt - for 1 test case
    +  ! the plain text message is from the task description
    +  MsgToEncrypt = 'ATTACKAT1200AM'
    +
    +  if (.not. DEBUG) then
    +    print  '("Init: DEBUG is .false., i.e. password and Polybius square are randomized.")'
    +    PassPhrase = getRandomPassPhrase()       ! select random password from unixdict.txt
    +  else
    +    ! for DEBUG only: force constant password for reproducible result:
    +    print  '("Init: DEBUG is .true., i.e. the code reproduces results of the NIM solution")'
    +    PassPhrase = 'EXCURSION'  ! Taken from the NIM solution
    +  endif
    +
    +  print '("Init: PassPhrase for encode and decode is ", A)' , PassPhrase
    +
    +  if (.not. DEBUG) then
    +    call createRandomPolybiusSquare ()       ! Create random Permutation of Alphabet to represent Polybius square
    +  else
    +    ! For DEBUG only: force constant string for reproducable results
    +    ! Both the Alphabet and the password are from the NIM solution.
    +    ! If DEBUG is .true., the result of the NIM solution is exactly reproduced.
    +    PolyAlphabet =   'XOFPD6VHC40ZJMKRU5IA9YBW3L21NGQTE78S'
    +  endif
    +
    +  call PrintSquare ("Init: Following Polybius square is used for encode/decode:", PolyAlphabet, ColWidth)
    +
    +  call encode (MsgToEncrypt , EncryptedMsg, PolyAlphabet, PassPhrase)
    +  call decode (EncryptedMsg, DecryptedMsg, PolyAlphabet, PassPhrase)
    +
    +  call printResult (MsgToEncrypt, EncryptedMsg, DecryptedMsg)
    +
    +contains
    +
    +
    +
    +! ==========================================================
    +! Find random length of the new password,
    +! then pick a random word of this length from the word list
    +! ==========================================================
    +function getRandomPassPhrase()   result (retval)
    +  character (len=maxPassLen) :: retval
    +  integer :: leng                                             ! required length of password to pick
    +
    +  leng = randominInterval (minPassLen, maxPassLen)
    +  retval = getRandomWord (leng)
    +
    +end function getRandomPassPhrase
    +
    +! ==================================================================================
    +! Read the wordlist unixdict.txt and select a random word  with the requested length
    +! ==================================================================================
    +function getRandomWord (leng) result (retval)
    +  integer, intent(in) :: leng
    +  character (len=maxPassLen) :: retval
    +
    +  character(len=100)  :: word                                     ! is longer than expected input word length
    +  character (len=maxPassLen), allocatable :: Candidates (:)
    +  integer:: capacity, content
    +  integer :: io_stat, l, idx, ii
    +
    +  ! Read all words from unixdict.txt having length "len" and no repeating letters
    +  open(unit=10, file='unixdict.txt', status='old', action='read', iostat=io_stat)
    +  if (io_stat .ne. 0) then      ! File open MUST be successful, otherwise total program failure.
    +     print *, "Error opening file"
    +     stop
    +  end if
    +  capacity = 128
    +  call resize (Candidates, maxPassLen, capacity)
    +  content = 0
    +  do
    +    read (10,'(A)', iostat=io_stat)   word               ! ok for both intel and GNU.
    +    l = len_trim (word)                                  ! use this instead of Q format
    +    if (io_stat < 0) exit    ! EOF: Normal end of this loop
    +    if (io_stat > 0) then
    +      print *, "Read error" ! ERROR: (never seen)
    +      exit
    +    end if
    +    if (l .ne. leng) cycle
    +    if (hasDuplicateChars(word)) cycle
    +    if (content .eq. capacity) then
    +      capacity = capacity * 2
    +      call resize (Candidates, maxPassLen, capacity)
    +    end if
    +    content = content + 1
    +    Candidates (content) = word
    +  enddo
    +  idx = randominInterval (1, content)
    +  retval = candidates (idx)
    +  do ii=1, leng
    +    if (retval(ii:ii) .ge. 'a' .and. retval(ii:ii) .le. 'z') then
    +      retval(ii:ii) = char (ichar(retval(ii:ii)) - ichar('a') + ichar('A'))
    +    endif
    +  end do
    +  close (10)
    +
    +end function getRandomWord
    +
    +! ========================================================================
    +! Return true if argument word contains duplicate letters, otherwise false.
    +! ========================================================================
    +function hasDuplicateChars (word) result (itHas)
    +  character (len=*), intent(in) :: word
    +  logical :: itHas
    +  integer :: ii, jj, l
    +  l = len_trim(word)
    +  do ii=1, l
    +    do jj=ii+1, l
    +      if (word(ii:ii) .eq. word(jj:jj)) then
    +        itHas = .true.
    +        return
    +      endif
    +    end do
    +  end do
    +  itHas = .false.
    +end function hasDuplicateChars
    +
    +
    +  !==============================================================
    +  ! Creating a random Polybius square is equivalent with creating
    +  ! a random permutation of the used alphabet
    +  ! Use the Sattolo algorithm to create such a permutation .
    +  !==============================================================
    +subroutine createRandomPolybiusSquare ()
    +
    +  character :: tmp                                      ! for swapping single letters
    +
    +  integer :: j, k, l                                    ! Helper variables: indices into words, words' length
    +
    +
    +  PolyAlphabet = Alphabet
    +  l = len (Alphabet)
    +  do j = l, 1, -1                                       ! For all letters from end down to begin
    +    k = randominInterval (1, j-1)                       ! Select random letters between 1 and j-1
    +    tmp = PolyAlphabet(j:j)                             ! then swap letter at pos j with letter at pos k
    +    PolyAlphabet (j:j) = PolyAlphabet (k:k)
    +    PolyAlphabet (k:k) = tmp
    +  end do
    +
    +end subroutine createRandomPolybiusSquare
    +
    +
    +
    +! =============================================
    +! Increase allocated size of string array 'var'
    +! =============================================
    +subroutine resize(var, sLen, newSize)
    +  integer, intent(in)                              :: sLen       ! LEngth of 1 element of string array
    +  character (len=sLen), allocatable, intent(inout) :: var(:)     ! The array to be increased
    +  integer, intent(in)                              :: newSize    ! The new size of var
    +  character (len=sLen), allocatable                :: tmp(:)     ! Temporary storage
    +  integer                                          :: oldSize    ! Current array size
    +  integer                                          :: ii         ! Loop index
    +
    +  ! Copy allocated values to temporary, then allocate var with
    +  ! new size and copy back saved values.
    +  ! Could be done with move_alloc but this would not be portable to OpenVMS Fortran
    +
    +  if (allocated(var)) then
    +    oldSize = size(var)
    +  else
    +    oldSize = 0
    +  end if
    +
    +  if (newSize .gt. oldSize) then           ! only increment
    +    if (oldSize .gt.0) then
    +      allocate(tmp (oldSize))
    +      tmp(:oldSize) = var(:oldSize)
    +      deallocate (var)
    +    end if
    +    allocate(var(newSize))
    +    if (allocated(tmp) .and. allocated (var) ) then
    +      oldSize = min(size(tmp, 1), size(var, 1))
    +      var(:oldSize) = tmp(:oldSize)
    +      deallocate (tmp)
    +    end if
    +  end if
    +end subroutine resize
    +
    +
    +  ! ===========================================================
    +  ! Generate random number between @lo and @hi (inclusive)
    +  ! Assume Random Number Generator has been initialized before.
    +  ! ===========================================================
    +function randominInterval (lo, hi) result (r)
    +  integer, intent(in) :: lo, hi                         ! the interval
    +  integer :: r                                          ! resultant (pseudo-)random number
    +  real :: rnd                                           ! Fortran random number generator generates float values
    +
    +  call random_number (rnd)
    +  r = lo + FLOOR((hi+1-lo)*rnd)                         ! We want to choose one between [lo,hi]
    +
    +end function randominInterval
    +
    +
    +
    +! =============================================
    +! Encode a given string using the ADFGVX Cipher
    +! =============================================
    +subroutine encode (argInString, outString, argAlphabet, argPassPhrase)
    +  character (len=*), intent(in)  :: argInString     ! The string to encode
    +  character (len=*), intent(out) :: outString       ! The resultant encoded text
    +  character (len=*), intent(in)  :: argAlphabet     ! The alphabet that makes the Polybius square
    +  character (len=*), intent(in) :: argPassPhrase    ! the password used for encode and also decode.
    +  integer :: nRow
    +  integer :: argLen, passLen, newlen, ii, jj, kk, row, col
    +  character(len=2*len(OutString)+len_trim(argPassPhrase))  newAlphabet
    +
    +  character, dimension(:,:), allocatable :: Matrix, expandedMatrix
    +
    +  argLen = len_trim (argInString)
    +  passLen = len_trim (argPassPhrase)
    +  newlen = len(OutString)+len_trim(argPassPhrase)
    +  ! 1st step: encode with the given alphabet (resp. the equivalent 6x6 square),
    +  ! the output string being the row/col of each letter, expressed in terms of ADFGVX
    +  outString = ' '
    +  jj = 1
    +  do ii=1,argLen
    +    call getRC (argInString(ii:ii),row,col, argAlphabet)
    +    outString (jj:jj) = ADFGVX (row:row)
    +    jj = jj + 1
    +    outString (jj:jj) = ADFGVX (col:col)
    +    jj = jj + 1
    +  end do
    +
    +  if (VERBOSE) then
    +    print '("Encode, first step: ")'
    +    do ii=1, arglen
    +      write (*,'(A3)', advance='no') ArgInString (ii:ii)
    +    end do
    +    print *, 'becomes'
    +
    +    do ii=1, 2*argLen, 2
    +      write (*,'(x,A2)', advance='no') outString (ii:ii+1)
    +    end do
    +    write (*,'(///)')
    +  endif
    +
    +  jj = 1
    +  kk = 1
    +  newAlphabet = argPassPhrase (:passLen) // outString(:len_trim(outString))
    +
    +  nRow = (len_trim (newAlphabet) + passLen - 1)/passLen ! Required net number of lines for the Matrix
    +  allocate (Matrix (passLen, nRow))
    +
    +  ! Without any complications: Just accept that last line might be incomplete - complete it with spaces.
    +  do row=1, nRow
    +    do col=1,passLen
    +      if (row .eq. 1 ) then                             ! Top row gets the password
    +        Matrix (col,row) = newAlphabet (jj:jj)
    +        jj = jj + 1
    +      else
    +        if (jj .gt. len_trim(newAlphabet)) then         ! Entire new alphabet copied to Matrix
    +          Matrix(col,row) = ' '                         ! remaining Matrix is all blank
    +        else
    +          Matrix (col,row) = newAlphabet (jj:jj)
    +          jj = jj + 1
    +        endif
    +      endif
    +    end do
    +    if (jj .gt. len_trim(newAlphabet)) exit
    +  end do
    +  jj = 1
    +  do row=1, nRow
    +    do col=1,passLen
    +      newAlphabet (jj:jj) = Matrix (col,row)
    +      jj = jj + 1
    +    end do
    +  end do
    +
    +  if (VERBOSE) &
    +    call printMatrix ('Encode: This results in a new matrix: ', Matrix, nRow, passLen)
    +  ! Sort columns
    +  call quicksort_matrix (Matrix, passLen, nRow, 1, passlen)
    +
    +  if (VERBOSE) &
    +    call printMatrix ('Encode: After sorting columns, this becomes: ', Matrix, nRow, passLen)
    +
    +  jj = 1
    +  do row=1, nRow
    +    do col=1,passLen
    +      newAlphabet (jj:jj) = Matrix (col,row)
    +      jj = jj + 1
    +    end do
    +  end do
    +
    +  allocate (expandedMatrix (passLen, nRow))
    +  ! Initialize al to blank
    +  do row=1, 2*kk
    +    do col=1,passLen
    +      expandedMatrix (col,row) = ' '
    +    end do
    +  end do
    +
    +  jj=1
    +  do row=1, nRow
    +    do col=1,passLen
    +      if (jj .le. len_trim(newAlphabet))  then
    +        expandedMatrix (col,row) = newAlphabet (jj:jj)
    +      else
    +        expandedMatrix (col,row) = ' '
    +      endif
    +      jj = jj + 1
    +    end do
    +  end do
    +
    +  outString = ' '
    +  jj = 1
    +  do col=1,passLen
    +    do row=2, nRow
    +      if (expandedMatrix (col,row) .ne. ' ') then
    +        outString (jj:jj) = expandedMatrix (col,row)
    +        jj = jj + 1
    +      end if
    +    end do
    +    outString (jj:jj) = ' '
    +    jj = jj + 1
    +  end do
    +
    +end subroutine encode
    +
    +
    +! ==================================================================================
    +! Sort columns of a Matrix, taking elements of top row as key to decide "lt" or ge".
    +! ==================================================================================
    +recursive subroutine quicksort_matrix (mat, ncols, nrows, low, high)
    +
    +  integer, intent(in) :: ncols,nrows
    +  character, dimension (ncols,nrows), intent(inout) :: mat
    +
    +  integer, intent(in) :: low, high
    +  integer :: pivot_index
    +  integer :: i, j, mid
    +  character :: pivot, temp
    +
    +  if (low .lt. high) then
    +    ! The list is already "almost sorted", so use midlle word as pivot.
    +    mid = low + (high-low) / 2
    +    pivot = mat (mid,1)
    +
    +    !Move pivot to the end
    +    call swapMat (mat,ncols,nrows,mid,high)
    +
    +    i = low - 1
    +    do j = low, high - 1
    +      if (mat(j,1) .le. pivot) then
    +        i = i + 1
    +        call swapMat (mat,ncols,nrows,i,j)
    +      end if
    +    end do
    +
    +    call swapMat (mat,ncols,nrows,i+1,high)
    +    pivot_index = i + 1
    +
    +    call quicksort_matrix (mat, ncols,nrows, low, pivot_index - 1)
    +    call quicksort_matrix (mat, ncols,nrows,  pivot_index + 1, high)
    +  end if
    +end subroutine quicksort_matrix
    +
    +! ===============================================
    +! Swap two columns of a Matrix (Used for sorting)
    +! ===============================================
    +subroutine swapMat (mat,ncols,nrows,col1,col2)
    +  integer, intent(in) :: ncols,nrows                        ! Size of ...
    +  character, dimension (ncols,nrows), intent(inout) :: mat  ! ... the matrix
    +  integer, intent(in) :: col1, col2                         ! The 2 columns to swap
    +
    +  character :: tmp                                    ! Helpers to swap 2 elements
    +  integer :: row
    +
    +  ! early return in trivial noop case
    +  if (col1 .eq. col2) return
    +
    +  do row=1, nrows                                    ! Swap all elements of col 1 and col 2
    +    tmp = mat (col1,row)
    +    mat (col1,row) = mat(col2,row)
    +    mat(col2,row) = tmp
    +  end do
    +
    +end subroutine swapMat
    +
    +! =======================================================
    +! Decode a given (encoded) string using the ADFGVX Cipher
    +! =======================================================
    +subroutine decode (argInString, outString, argAlphabet, argPassPhrase)
    +  character (len=*), intent(in)  :: argInString     ! The encoded string to decode
    +  character (len=*), intent(out) :: outString       ! Result of the decode
    +  character (len=*), intent(in)  :: argAlphabet     ! The Polybius Square to encode and decode
    +  character (len=*), intent(in) :: argPassPhrase    ! The Password used to encode and decode
    +  character (len=MaxLen) :: tmpString               ! Temporary torage for intermediate result
    +  character, allocatable :: Matrix (:,:)            ! Matrix to constructed from input string
    +  character (len=:),allocatable :: SortedPassPhrase ! The password after sorting its letters
    +  integer :: nRow, passLen                          ! NMUmbner of rows and columns of above Matrix
    +  integer :: inLen, col,row, ii, jj, idx            ! Length of input string, and some helpers
    +
    +  ! Estimate input string lengths
    +  inLen = len_trim (argInString)
    +  passLen = len_trim (argPassPhrase)
    +
    +  outString = ' '
    +  nRow = (inLen + (passLen-1)) / passLen  + 1     ! 1 extra for top row = password
    +
    +  allocate (Matrix (passLen, nRow))
    +
    +  ! Initialize entire matrix
    +  do col=1,passLen
    +    do row=1, nRow
    +      Matrix (col,row) = ' '
    +    end do
    +    ! Fill the column as far as required
    +  end do
    +
    +
    +  ! The columns of the result matrix are sorted as password letters and
    +  ! the sorted password letters makeup top row of th is matrix
    +  SortedPassPhrase = argPassPhrase
    +  call  quicksort_matrix (SortedPassPhrase, passlen,  1, 1, passlen)
    +
    +  row=1
    +  do col=1, passLen
    +    Matrix (col,row) = SortedPassPhrase(col:col)
    +  end do
    +
    +  ! Set rest ( row 2 ff.) of the Matrix: column by column
    +  jj = 1
    +  do col=1,passLen
    +    row = 2
    +    do while (argInString (jj:jj) .ne. ' ')
    +      Matrix (col,row) = argInString (jj:jj)
    +      jj = jj + 1
    +      row = row + 1
    +    enddo
    +    jj = jj + 1
    +  end do
    +
    +  if (VERBOSE) &
    +    call printMatrix ('Decode: the reconstructed Code matrix is ', Matrix, nROw, passLen)
    +
    +  ! We know the columns of this matrix are sorted together with the password
    +  !
    +  ! restore the correct order of thet sorted matrix
    +  call UndoSort (Matrix, passLen, nRow, argPassPhrase, passlen)
    +
    +  if (VERBOSE) &
    +    call printMatrix ('Decode: After Undo Sorting, this becomes', Matrix, nRow, passLen)
    +
    +  ! The matrix is in the correct order now, so its rows, one by one,  represent the first encoded string
    +  !
    +  jj = 1
    +  tmpString = ' '
    +  do row = 2, nRow          ! Skip top row (=Passwprd)
    +    do col=1,passLen
    +      tmpString (jj:jj) = Matrix(col,row)
    +      jj = jj + 1
    +    end do
    +  end do
    +
    +  ! Now we have the encoded string, each 2 letters are row/col in ADFGVX scheme
    +  jj = 1
    +  do ii=1, len_trim(tmpString), 2
    +    row = index (ADFGVX, tmpString(ii:ii))
    +    col = index (ADFGVX, tmpString((ii+1) : (ii+1)))
    +    outString (jj:jj) = getChar (row,col,argAlphabet)   ! Decode from row/col to clear text
    +    jj = jj + 1
    +  end do
    +end subroutine decode
    +
    +! =============================================================================
    +! Print all nRow x nCol elements of a Matrix, togehther with a descriptive text
    +! =============================================================================
    +subroutine printMatrix (comment, Matrix, nRow, nCol)
    +  integer, intent(in) :: nRow, nCol
    +  character (len=*), intent(in) :: Comment
    +  character , intent(in) :: Matrix (nCol, nRow)
    +  integer :: r, c
    +
    +  write (*,'(/A/)')  Comment
    +  do r=1, nROw
    +    do c=1, nCol
    +      write (*, '(A2)', advance='no')  Matrix(c,r)
    +    end do
    +    write (*,*)
    +  end do
    +end subroutine printMatrix
    +
    +!=============================================================
    +! Matrix has been sorted before, with top row as key elements.
    +! Here undo that sort operation
    +!=============================================================
    +subroutine UndoSort (Matrix, nCol, nRow, argPassPhrase, passLen)
    +  integer, intent(in) :: nCol, nRow, passLen
    +  character, intent(inout)  :: Matrix (nCol, nROw)
    +  character                 :: resultMatrix (nCol, nROw)
    +
    +  character (len=passLen), intent(in) :: argPassPhrase
    +
    +  integer :: ii, jj, kk
    +
    +  do ii=1, passLen
    +    ! find whatever letter should be at pos ii within the unscrambled string
    +    jj = index (argPassPhrase, Matrix(ii, 1) )
    +    ! so letter "PassPhrase(jj:jj)" should be at pos ii in line 1 of Matrix
    +    if (jj .ne. ii) then
    +      do kk=1, nRow
    +        resultMatrix (jj,kk) = Matrix(ii,kk)
    +      end do
    +    else
    +      do kk=1, nRow
    +        resultMatrix (jj,kk) = Matrix(jj,kk)
    +      end do
    +    endif
    +  end do
    +  matrix = resultMatrix
    +end subroutine UndoSort
    +
    +
    +! ======================================================
    +! Get Row and Column  of a letter in the Polybius square
    +! ======================================================
    +subroutine getRC (c,row,col, argAlphabet)
    +  character, intent(in) :: c
    +  integer, intent(out) :: row,col
    +  character (len=*), intent(in)  :: argAlphabet             ! Argument to use for encoding
    +  integer :: idx
    +
    +  idx = index (argAlphabet, c) - 1
    +
    +  row = 1 + idx / ColWidth
    +  col = 1 + mod (idx, ColWidth)
    +
    +end subroutine getRC
    +
    +! ==================================================
    +! Return letter in row column of the Polybius square
    +! ==================================================
    +function getChar (row,column,argAlphabet) result (chr)
    +  integer, intent(in) :: row, column
    +  character (len=*), intent(in)  :: argAlphabet             ! Argument to use for encoding
    +  character :: chr
    +  integer :: idx
    +
    +  idx = (row-1) * ColWidth + column
    +  chr = argAlphabet (idx:idx)
    +
    +end function getChar
    +
    +! ===========================================
    +! Print original, encoded and decoded strings
    +! ===========================================
    +subroutine printResult (m1,m2,m3)
    +  character (len=*), intent(in) :: m1,m2,m3
    +  write (*,'("Original:  ", A)')  m1(:len_trim(m1))
    +  write (*,'(" Encoded:  ", A)')  m2(:len_trim(m2))
    +  write (*,'(" Decoded:  ", A)')  m3(:len_trim(m3))
    +  print *
    +end subroutine printResult
    +
    +! ================================================================================
    +! Print the resulting Polybius square based on the alphabet used for encode/decode
    +! ================================================================================
    +subroutine PrintSquare (Comment, Alp, cw)
    +  character (len=*), intent(in) :: Comment
    +  character (len=*), intent(in)  :: Alp
    +  integer, intent(in) :: cw                                     ! column width for dormatted display
    +  integer:: ii, l
    +
    +  l = len_trim(alp)
    +  write (*,'(/A/)')  Comment
    +  Write (*, "('   A D F G V X', /,' +------------',/  A, '|')", advance='no') ADFGVX (1:1)
    +  do ii=1, l
    +    write (*, '(A2)', advance='no')  Alp(ii:ii)
    +    if (mod (ii, cw) .eq. 0) then
    +      if (ii .ne. l)  then
    +        write (*,'(/,A1,"|")', advance='no') ADFGVX (1 +  ii/cw:1 +  ii/cw)
    +      else
    +        write (*,*) ! just EOL
    +      endif
    +    endif
    +  end do
    +  print *                                                       ! one extra blank line
    +end subroutine PrintSquare
    +
    +
    +end program ADFGVXCipher
    diff --git a/Task/ADFGVX-cipher/Free-Pascal-Lazarus/adfgvx-cipher.pas b/Task/ADFGVX-cipher/Free-Pascal-Lazarus/adfgvx-cipher.pas
    new file mode 100644
    index 0000000000..b35f201644
    --- /dev/null
    +++ b/Task/ADFGVX-cipher/Free-Pascal-Lazarus/adfgvx-cipher.pas
    @@ -0,0 +1,198 @@
    +program adfgvxcipher;
    +
    +uses
    +  SysUtils,
    +  Classes;
    +
    +const
    +  ADFGVX = 'ADFGVX';
    +  ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    +  MESSAGE = 'ATTACKAT1200AM';
    +
    +type
    +  //tPolybiusarr = array[1..6,1..6] of string;
    +  tPolybiusarr = array[1..6, 1..6] of char;
    +
    +  procedure init_Polybius(var Polybius: tPolybiusarr);
    +
    +    procedure ShuffleString(var S: string);
    +    var
    +      i, j: integer;
    +      c: char;
    +    begin
    +      for i := Length(S) downto 2 do
    +      begin
    +        j := Random(i) + 1;  // 1..i
    +        c := S[i];
    +        S[i] := S[j];
    +        S[j] := c;
    +      end;
    +    end;
    +
    +  var
    +    ShuffledAlphabet: string;
    +    x, y, i: integer;
    +  begin
    +    ShuffledAlphabet := ALPHABET;
    +    ShuffleString(ShuffledAlphabet);
    +    i := 1;
    +    for x := 1 to 6 do
    +      for y := 1 to 6 do
    +      begin
    +        Polybius[x, y] := ShuffledAlphabet[i];
    +        Inc(i);
    +      end;
    +  end;
    +
    +  procedure PrintPolybius(Polybius: tPolybiusarr);
    +  var
    +    x, y: integer;
    +    ch: char;
    +  begin
    +    writeln('The 6 x 6 Polybius square:');
    +    writeln;
    +    Write('  |');
    +    for ch in ADFGVX do
    +      Write(ch: 2);
    +    writeln;
    +    writeln('---------------');
    +    for x := 1 to 6 do
    +    begin
    +      Write(ADFGVX[x], ' |');
    +      for y := 1 to 6 do
    +      begin
    +        Write(Polybius[x, y]: 2);
    +      end;
    +      writeln;
    +    end;
    +  end;
    +
    +  function CreateKey(size: integer): string;
    +
    +    procedure FilterList(var lst: TStringList; size: integer);
    +
    +      function HasRepeatedCharacters(const str: string): boolean;
    +      var
    +        seen: array[0..255] of boolean;
    +        i: integer;
    +        c: byte;
    +      begin
    +        FillChar(seen, SizeOf(seen), False);
    +        for i := 1 to Length(str) do
    +        begin
    +          c := Ord(str[i]);
    +          if seen[c] then
    +            Exit(True);    // repeated character found
    +          seen[c] := True;
    +        end;
    +        Result := False;   // no repeats
    +      end;
    +
    +    var
    +      x: integer;
    +    begin
    +      for x := lst.Count - 1 downto 0 do
    +        if (length(lst[x]) <> size) or HasRepeatedCharacters(lst[x]) then lst.Delete(x);
    +    end;
    +
    +  const
    +    FNAME = 'unixdict.txt';
    +  var
    +    list: TStringList;
    +  begin
    +    if (size < 7) or (size > 12) then
    +    begin
    +      writeln('Key should contain between 7 and 12 letters, both inclusive.');
    +      halt;
    +    end;
    +    list := TStringList.Create;
    +    list.LoadFromFile(FNAME);
    +    filterlist(list, size);
    +    Result := UpperCase(list[random(list.Count)]);
    +    list.Free;
    +  end;
    +
    +  function FindCharachter(ch: char; polybius: tPolybiusarr): string;
    +  var
    +    x, y: integer;
    +  begin
    +    for x := 1 to 6 do
    +      for y := 1 to 6 do
    +        if polybius[x, y] = ch then
    +          exit(ADFGVX[x] + ADFGVX[y]);
    +  end;
    +
    +  function Encrypt(plainText, key: string; Polybius: tPolybiusarr): string;
    +  var
    +    ch: char;
    +    str: string;
    +    lst: TStringList;
    +    x, keylength: integer;
    +  begin
    +    str := '';
    +    keylength := length(key);
    +    lst := TStringList.Create;
    +    for x := 1 to keylength do
    +      lst.Add(key[x]);
    +    x := 0;
    +    for ch in plainText do
    +    begin
    +      lst[x] := lst[x] + FindCharachter(ch, Polybius);
    +      Inc(x);
    +      if x = keylength then x := 0;
    +    end;
    +    lst.Sort;
    +    writeln;
    +    for x := 0 to keylength - 1 do
    +      str := str + lst[x] + ' ';
    +    Result := TrimRight(str);
    +    lst.Free;
    +  end;
    +
    +  function Decrypt(encryptedTex, key: string; polybius: tPolybiusarr): string;
    +    // Note: simplified decryption logic for demonstration purposes
    +    // need some work for longer messages
    +  var
    +    lst, tmp: TStringList;
    +    ch: char;
    +    s, str: string;
    +  begin
    +    lst := TStringList.Create;
    +    tmp := TStringList.Create;
    +    lst.AddDelimitedtext(encryptedTex, ' ', True);
    +    for ch in key do
    +      for str in lst do
    +        if str[1] = ch then
    +        begin
    +          tmp.Add(str);
    +          break;
    +        end;
    +    Result := '';
    +    s := '';
    +    for str in tmp do
    +    begin
    +      Result := Result + polybius[pos(str[2], ADFGVX), pos(str[3], ADFGVX)];
    +      if length(str) > 3 then s := s + polybius[pos(str[4], ADFGVX), pos(str[5], ADFGVX)];
    +    end;
    +    Result := Result + s;
    +    lst.Free;
    +    tmp.Free;
    +  end;
    +
    +var
    +  Polybius: tPolybiusarr;
    +  key, encryptedMessage, decryptedMessage: string;
    +
    +begin
    +  Randomize;
    +  init_Polybius(Polybius);
    +  PrintPolybius(Polybius);
    +  key := createkey(Random(12 - 7 + 1) + 7); //set length of word to 7 - 12
    +  encryptedMessage := Encrypt(MESSAGE, key, Polybius);
    +  decryptedMessage := Decrypt(encryptedMessage, key, polybius);
    +  writeln('The key is              : ', key);
    +  writeln('the plain message is    : ', MESSAGE);
    +  writeln('the encrypted message is: ', encryptedMessage);
    +  writeln('the decrypted message is: ', decryptedMessage);
    +
    +end.
    diff --git a/Task/ADFGVX-cipher/FreeBASIC/adfgvx-cipher.basic b/Task/ADFGVX-cipher/FreeBASIC/adfgvx-cipher.basic
    new file mode 100644
    index 0000000000..e2bd2cc64b
    --- /dev/null
    +++ b/Task/ADFGVX-cipher/FreeBASIC/adfgvx-cipher.basic
    @@ -0,0 +1,169 @@
    +Const ADFGVX As String = "ADFGVX"
    +Const ALPHABET As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    +
    +Function InitialisePolybiusSquare() As String
    +    Dim As Integer i, j
    +    Dim As String letters(35)
    +    For i = 0 To 35
    +        letters(i) = Mid(ALPHABET, i + 1, 1)
    +    Next
    +    Randomize Timer
    +    For i = 0 To 35
    +        j = Int(Rnd * 36)
    +        Swap letters(i), letters(j)
    +    Next
    +
    +    Dim As Integer row, column
    +    Dim As String result = ""
    +    For row = 0 To 5
    +        For column = 0 To 5
    +            result &= letters(6 * row + column)
    +        Next
    +    Next
    +
    +    Return result
    +End Function
    +
    +Function CreateKey(size As Integer) As String
    +    If size < 7 Or size > 12 Then
    +        Print "Key should contain between 7 and 12 letters, both inclusive."
    +        Exit Function
    +    End If
    +
    +    Dim As Integer i, j
    +    Dim As String word, candidates()
    +    Dim As Integer ff = Freefile
    +
    +    Open "i:\unixdict.txt" For Input As #ff
    +    While Not Eof(ff)
    +        Line Input #ff, word
    +
    +        Dim As String uniqueWord = ""
    +        For i = 1 To Len(word)
    +            If Instr(uniqueWord, Mid(word, i, 1)) = 0 Then
    +                uniqueWord &= Mid(word, i, 1)
    +            End If
    +        Next
    +
    +        If Len(word) = size And Len(word) = Len(uniqueWord) Then
    +            word = Ucase(word)
    +
    +            Dim isAlphanum As Boolean = TRue
    +            For i = 1 To Len(word)
    +                If Not (Mid(word, i, 1) >= "A" And Mid(word, i, 1) <= "Z") And Not (Mid(word, i, 1) >= "0" And Mid(word, i, 1) <= "9") Then
    +                    isAlphanum = False
    +                    Exit For
    +                End If
    +            Next
    +
    +            If isAlphanum Then
    +                Redim Preserve candidates(Ubound(candidates) + 1)
    +                candidates(Ubound(candidates)) = word
    +            End If
    +        End If
    +    Wend
    +    Close #ff
    +
    +    Randomize Timer
    +    For i = 0 To Ubound(candidates)
    +        j = Int(Rnd * (Ubound(candidates) + 1))
    +        Swap candidates(i), candidates(j)
    +    Next
    +
    +    Return candidates(0)
    +End Function
    +
    +Function Encrypt(plainText As String, polybius As String, key As String) As String
    +    Dim As Integer i, j, row, column
    +    Dim As String code, ch, encrypted
    +
    +    code = ""
    +    For i = 1 To Len(plainText)
    +        ch = Mid(plainText, i, 1)
    +        For row = 0 To 5
    +            For column = 0 To 5
    +                If Mid(polybius, row * 6 + column + 1, 1) = ch Then
    +                    code &= Mid(ADFGVX, row + 1, 1)
    +                    code &= Mid(ADFGVX, column + 1, 1)
    +                End If
    +            Next
    +        Next
    +    Next
    +
    +    encrypted = ""
    +    For i = 1 To Len(key)
    +        ch = Mid(key, i, 1)
    +        For j = Instr(key, ch) - 1 To Len(code) - 1 Step Len(key)
    +            encrypted &= Mid(code, j + 1, 1)
    +        Next
    +        encrypted &= " "
    +    Next
    +
    +    Return encrypted
    +End Function
    +
    +Function Decrypt(encryptedText As String, polybius As String, key As String) As String
    +    Dim As Integer i, j, row, column, spaceCount, codeSize
    +    Dim As String result, stream, word, code, plainText
    +    Dim As String blocks()
    +
    +    result = ""
    +    i = 1
    +    While i <= Len(encryptedText)
    +        If Mid(encryptedText, i, 1) = " " Then
    +            i += 1
    +        Else
    +            result += Mid(encryptedText, i, 1)
    +            i += 1
    +        End If
    +    Wend
    +    spaceCount = Len(encryptedText) - Len(result)
    +    codeSize = Len(encryptedText) - spaceCount
    +
    +    stream = encryptedText
    +    While Len(stream) > 0
    +        word = Left(stream, Instr(stream, " ") - 1)
    +        Redim Preserve blocks(Ubound(blocks) + 1)
    +        blocks(Ubound(blocks)) = word
    +        stream = Mid(stream, Instr(stream, " ") + 1)
    +    Wend
    +
    +    code = ""
    +    For i = 0 To codeSize - 1
    +        For j = 0 To Ubound(blocks)
    +            If Len(code) < codeSize Then code &= Mid(blocks(j), i + 1, 1)
    +        Next
    +    Next
    +
    +    plainText = ""
    +    For i = 1 To codeSize - 1 Step 2
    +        row = Instr(ADFGVX, Mid(code, i, 1)) - 1
    +        column = Instr(ADFGVX, Mid(code, i + 1, 1)) - 1
    +        plainText &= Mid(polybius, row * 6 + column + 1, 1)
    +    Next
    +
    +    Return plainText
    +End Function
    +
    +Dim As String polybius = InitialisePolybiusSquare()
    +Print "The 6 x 6 Polybius square:"
    +Print " | A D F G V X"
    +Print "--------------"
    +For row As Integer = 0 To 5
    +    Print Mid(ADFGVX, row + 1, 1); "|";
    +    For column As Integer = 0 To 5
    +        Print " "; Mid(polybius, row * 6 + column + 1, 1);
    +    Next
    +    Print
    +Next
    +
    +Dim As String key = CreateKey(9)
    +Print !"\nThe key is "; key
    +Dim As String plainText = "ATTACKAT1200AM"
    +Print !"\nPlain text: "; plainText
    +Dim As String encryptedText = Encrypt(plainText, polybius, key)
    +Print !"\nEncrypted: "; encryptedText
    +Dim As String decryptedText = Decrypt(encryptedText, polybius, key)
    +Print !"\nDecrypted: "; decryptedText
    +
    +Sleep
    diff --git a/Task/ADFGVX-cipher/FutureBasic/adfgvx-cipher.basic b/Task/ADFGVX-cipher/FutureBasic/adfgvx-cipher.basic
    new file mode 100644
    index 0000000000..3cbb6a7960
    --- /dev/null
    +++ b/Task/ADFGVX-cipher/FutureBasic/adfgvx-cipher.basic
    @@ -0,0 +1,208 @@
    +/*
    +ADFGVX cipher
    +https://rosettacode.org/wiki/ADFGVX_cipher
    +
    +Requires file, unixdict.txt to be on the desktop
    +https://github.com/quinnj/Rosetta-Julia/blob/master/unixdict.txt
    +
    +*/
    +
    +begin globals
    +
    +  str255 ADFGVX
    +  ADFGVX  = "ADFGVX"
    +  str255 ALPHABET
    +  ALPHABET  = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    +
    +end globals
    +
    +local fn InitialisePolybiusSquare As str255
    +  short i, j
    +
    +  str255 letters(36)
    +  For i = 0 To 35
    +    letters(i) = Mid$(ALPHABET, i + 1, 1)
    +  Next
    +
    +  For i = 0 To 35
    +    j = Int(rnd (36))
    +    Swap letters(i), letters(j)
    +  Next
    +
    +  short row, column
    +  str255 result
    +  result = ""
    +  For row = 0 To 5
    +    For column = 0 To 5
    +      result = result + letters(6 * row + column)
    +    Next
    +  Next
    +
    +End fn = result
    +
    +local fn CreateKey(size As short) As str255
    +  If size < 7 Or size > 12
    +    Print "Key should contain between 7 and 12 letters, both inclusive."
    +    Exit fn
    +  End If
    +
    +  short i, j
    +  str255 TheWord, candidates(1000)
    +  short ff = 1 // file number
    +
    +  short CandidatesCounter = 1
    +
    +  CFUrlRef ParentDirectory = fn FileManagerURLForDirectory( NSDesktopDirectory, NSUserDomainMask )
    +  CFUrlRef UnixDictURL = fn URLByAppendingPathComponent( ParentDirectory, @"unixdict.txt" )
    +
    +
    +  Open "I",ff, UnixDictURL
    +  While Eof(ff) = 0
    +    Line Input #ff, TheWord
    +
    +    str255 uniqueWord
    +    uniqueWord = ""
    +    For i = 1 To Len$(TheWord)
    +      If Instr$(1,uniqueWord, Mid$(TheWord, i, 1)) = 0
    +        uniqueWord = uniqueWord +  Mid$(TheWord, i, 1)
    +      End If
    +    Next
    +
    +    If Len$(TheWord) = size && Len$(TheWord) = Len$(uniqueWord)
    +      TheWord = Ucase$(TheWord)
    +
    +      bool isAlphanum = _true
    +      For i = 1 To Len$(TheWord)
    +        If (Mid$(TheWord, i, 1) < "A" && Mid$(TheWord, i, 1) <= "Z") && (Mid$(TheWord, i, 1) < "0" && Mid$(TheWord, i, 1) <= "9")
    +          isAlphanum = _false
    +          Exit For
    +        End If
    +      Next
    +
    +
    +      If isAlphanum
    +        //Redim Preserve candidates(Ubound(candidates) + 1)
    +        CandidatesCounter ++
    +        candidates(CandidatesCounter) = TheWord
    +      End If
    +    End If
    +  Wend
    +  Close #ff
    +
    +
    +
    +  For i = 0 To CandidatesCounter
    +    j = Int(Rnd (CandidatesCounter + 1))
    +    Swap candidates(i), candidates(j)
    +  Next
    +
    +End fn = candidates(0)
    +
    +local fn Encrypt(plainText As str255, polybius As str255, key As str255) As str255
    +  short i, j, row, column
    +  str255 code, ch, encrypted
    +
    +  code = ""
    +  For i = 1 To Len$(plainText)
    +    ch = Mid$(plainText, i, 1)
    +    For row = 0 To 5
    +      For column = 0 To 5
    +        If Mid$(polybius, row * 6 + column + 1, 1) = ch
    +          code = code +  Mid$(ADFGVX, row + 1, 1)
    +          code = code +  Mid$(ADFGVX, column + 1, 1)
    +        End If
    +      Next
    +    Next
    +  Next
    +
    +  encrypted = ""
    +  For i = 1 To Len$(key)
    +    ch = Mid$(key, i, 1)
    +    For j = Instr$(1,key, ch) - 1 To Len$(code) - 1 Step Len$(key)
    +      encrypted = encrypted +  Mid$(code, j + 1, 1)
    +    Next
    +    encrypted = encrypted +  " "
    +  Next
    +
    +
    +End fn = encrypted
    +
    +local fn Decrypt(encryptedText As str255, polybius As str255, key As str255) As str255
    +  short i, j, row, column, spaceCount, codeSize
    +  str255 result, stream, TheWord, code, plainText
    +  str255 blocks(200)
    +  short BlocksCounter = 1
    +  result = ""
    +  i = 1
    +  While i <= Len$(encryptedText)
    +    If Mid$(encryptedText, i, 1) = " "
    +      i += 1
    +    Else
    +      result += Mid$(encryptedText, i, 1)
    +      i += 1
    +    End If
    +  Wend
    +  spaceCount = Len$(encryptedText) - Len$(result)
    +  codeSize = Len$(encryptedText) - spaceCount
    +
    +
    +  stream = encryptedText
    +  While Len$(stream) > 0
    +    TheWord = Left$(stream, Instr$(1,stream, " ") - 1)
    +    //Redim Preserve blocks(Ubound(blocks) + 1)
    +    BlocksCounter ++
    +    blocks(BlocksCounter) = TheWord
    +    stream = Mid$(stream, Instr$(1,stream, " ") + 1)
    +  Wend
    +
    +  code = ""
    +  For i = 0 To codeSize - 1
    +    BlocksCounter ++
    +    For j = 0 To BlocksCounter
    +      If Len$(code) < codeSize Then code = code + Mid$(blocks(j), i + 1, 1)
    +    Next
    +  Next
    +
    +  plainText = ""
    +  For i = 1 To codeSize - 1 Step 2
    +    row = Instr$(1,ADFGVX, Mid$(code, i, 1)) - 1
    +    column = Instr$(1,ADFGVX, Mid$(code, i + 1, 1)) - 1
    +    plainText = plainText +  Mid$(polybius, row * 6 + column + 1, 1)
    +  Next
    +
    +
    +End fn = plainText
    +
    +str255 polybius
    +polybius = fn InitialisePolybiusSquare
    +Print "The 6 x 6 Polybius square:"
    +Print " | A D F G V X"
    +Print "--------------"
    +short row
    +For row = 0 To 5
    +  Print Mid$(ADFGVX, row + 1, 1); "|";
    +  short column
    +  For column  = 0 To 5
    +    Print " "; Mid$(polybius, row * 6 + column + 1, 1);
    +  Next
    +  Print
    +Next
    +
    +str255 key
    +key = fn CreateKey(9)
    +print
    +Print "The key is "; key
    +str255 plainText
    +plainText = "ATTACKAT1200AM"// 20241105
    +print
    +Print "Plain text: "; plainText
    +str255 encryptedText
    +encryptedText = fn Encrypt(plainText, polybius, key)
    +print
    +Print "Encrypted: "; encryptedText
    +str255 decryptedText
    +decryptedText = fn Decrypt(encryptedText, polybius, key)
    +print
    +Print "Decrypted: "; decryptedText
    +
    +handleevents
    diff --git a/Task/ADFGVX-cipher/JavaScript/adfgvx-cipher.js b/Task/ADFGVX-cipher/JavaScript/adfgvx-cipher.js
    new file mode 100644
    index 0000000000..0bdfe6eb1a
    --- /dev/null
    +++ b/Task/ADFGVX-cipher/JavaScript/adfgvx-cipher.js
    @@ -0,0 +1,134 @@
    +class ADFGVX {
    +    /** The WWI German ADFGVX cipher. */
    +    constructor(spoly, k, alph = 'ADFGVX') {
    +        this.polybius = spoly.toUpperCase().split('');
    +        this.pdim = Math.floor(Math.sqrt(this.polybius.length));
    +        this.key = k.toUpperCase().split('');
    +        this.keylen = this.key.length;
    +        this.alphabet = alph.split('');
    +        const pairs = [];
    +        for (let i = 0; i < this.alphabet.length; i++) {
    +            for (let j = 0; j < this.alphabet.length; j++) {
    +                pairs.push(this.alphabet[i] + this.alphabet[j]);
    +            }
    +        }
    +        this.encode = {};
    +        for (let i = 0; i < this.polybius.length; i++) {
    +            this.encode[this.polybius[i]] = pairs[i];
    +        }
    +        this.decode = {};
    +        for (const k in this.encode) {
    +            this.decode[this.encode[k]] = k;
    +        }
    +    }
    +
    +    encrypt(msg) {
    +        /** Encrypt with the ADFGVX cipher. */
    +        const chars = [];
    +        for (const c of msg.toUpperCase()) {
    +            if (this.polybius.includes(c)) {
    +                chars.push(this.encode[c]);
    +            }
    +        }
    +        const flatChars = chars.join('').split('');
    +        const colvecs = [];
    +        for (let i = 0; i < this.keylen; i++) {
    +            const currentCol = [];
    +            for (let j = i; j < flatChars.length; j += this.keylen) {
    +                currentCol.push(flatChars[j]);
    +            }
    +            colvecs.push([this.key[i], currentCol]);
    +        }
    +
    +        colvecs.sort((a, b) => a[0].localeCompare(b[0]));
    +
    +        let result = '';
    +        for (const a of colvecs) {
    +            result += a[1].join('');
    +        }
    +        return result;
    +    }
    +
    +    decrypt(cod) {
    +        /** Decrypt with the ADFGVX cipher. Does not depend on spacing of encoded text */
    +        const chars = [];
    +        for (const c of cod) {
    +            if (this.alphabet.includes(c)) {
    +                chars.push(c);
    +            }
    +        }
    +
    +        const sortedkey = [...this.key].sort();
    +        const order = [];
    +        for (const ch of sortedkey) {
    +            order.push(this.key.indexOf(ch));
    +        }
    +        const originalorder = [];
    +        for (const ch of this.key) {
    +            originalorder.push(sortedkey.indexOf(ch));
    +        }
    +
    +        const base = Math.floor(chars.length / this.keylen);
    +        const extra = chars.length % this.keylen;
    +        const strides = order.map((_, i) => base + (extra > i ? 1 : 0));
    +        const starts = [0];
    +        let sum = 0;
    +        for (let i = 0; i < strides.length - 1; i++) {
    +            sum += strides[i];
    +            starts.push(sum);
    +        }
    +        const ends = starts.map((start, i) => start + strides[i]);
    +        const cols = originalorder.map(i => chars.slice(starts[i], ends[i]));
    +
    +        const pairs = [];
    +        for (let i = 0; i < Math.floor((chars.length - 1) / this.keylen) + 1; i++) {
    +            for (let j = 0; j < this.keylen; j++) {
    +                if (i * this.keylen + j < chars.length) {
    +                    pairs.push(cols[j][i]);
    +                }
    +            }
    +        }
    +
    +        let decoded = '';
    +        for (let i = 0; i < pairs.length; i += 2) {
    +            decoded += this.decode[pairs[i] + pairs[i + 1]];
    +        }
    +        return decoded;
    +    }
    +}
    +
    +// Helper function to shuffle an array (Fisher-Yates shuffle)
    +function shuffle(array) {
    +    for (let i = array.length - 1; i > 0; i--) {
    +        const j = Math.floor(Math.random() * (i + 1));
    +        [array[i], array[j]] = [array[j], array[i]];
    +    }
    +    return array;
    +}
    +
    +
    +async function main() {
    +    const PCHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'.split('');
    +    shuffle(PCHARS);
    +    const POLYBIUS = PCHARS.join('');
    +
    +    // Simulate reading from unixdict.txt (replace with your actual file reading method if needed)
    +    // For demonstration purposes, using a hardcoded word list:
    +    const WORDS = ['ABDEFGHIK', 'JLMNOPQRS', 'TUVWXYZ01', '23456789'];
    +    const KEY = WORDS[Math.floor(Math.random() * WORDS.length)];
    +
    +
    +    const SECRET = new ADFGVX(POLYBIUS, KEY);
    +    const MESSAGE = 'ATTACKAT1200AM';
    +
    +    console.log(`Polybius: ${POLYBIUS}, key: ${KEY}`);
    +    console.log('Message: ', MESSAGE);
    +
    +    const ENCODED = SECRET.encrypt(MESSAGE);
    +    const DECODED = SECRET.decrypt(ENCODED);
    +
    +    console.log('Encoded: ', ENCODED);
    +    console.log('Decoded: ', DECODED);
    +}
    +
    +main();
    diff --git a/Task/ADFGVX-cipher/Julia/adfgvx-cipher.julia b/Task/ADFGVX-cipher/Julia/adfgvx-cipher.jl
    similarity index 100%
    rename from Task/ADFGVX-cipher/Julia/adfgvx-cipher.julia
    rename to Task/ADFGVX-cipher/Julia/adfgvx-cipher.jl
    diff --git a/Task/ADFGVX-cipher/M2000-Interpreter/adfgvx-cipher.m2000 b/Task/ADFGVX-cipher/M2000-Interpreter/adfgvx-cipher.m2000
    new file mode 100644
    index 0000000000..1cc6519280
    --- /dev/null
    +++ b/Task/ADFGVX-cipher/M2000-Interpreter/adfgvx-cipher.m2000
    @@ -0,0 +1,116 @@
    +Module CheckADFGVX_Cipher {
    +	Class cipher {
    +	Private:
    +		buffer a as byte*36
    +		b="ADFGVX"
    +		key="ABCDEFGHIJK"
    +		orderkey="ABCDEFGHIJK"
    +		map=list
    +		map2=list
    +		module preparemaps {
    +			for i=0 to 5
    +				jj=0
    +				for j=i*6 to j+5
    +					.map(chr$(.a[j]))=mid$(.b, i+1,1)+mid$(.b,jj+1, 1)
    +					.map2(mid$(.b, i+1,1)+mid$(.b,jj+1, 1))=chr$(.a[j])
    +					jj++
    +				next
    +			next			
    +		}
    +	Public:
    +		Module SetRandom (&returnvalue) {
    +			return .a, 0:=str$("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
    +			for i=1 to 100
    +				c=random(0, 35):d=c
    +				while c=d {d=random(0, 35)}
    +				 byte o=.a[c]
    +				.a[c]<=.a[d]
    +				.a[d]<=o
    +			next
    +			returnvalue=chr$(eval$(.a)) ' convert to UTF16LE
    +			.preparemaps	
    +		}
    +		Module SetSpecific (that$){
    +			return .a, 0:=str$(Ucase$(that$))
    +			.preparemaps		
    +		}
    +		Module SetKey (.key as string) {
    +			.key<=ucase$(.key)			
    +			if len(.key)<7 or len(.key)>12 then Error "Key has not proper length"
    +			if filter$(.key, "ABCDEFGHIJKLMNOPQRSTUVWXYZ")<>"" then
    +				Error "Key has bad letters"
    +			end if
    +			dim aa(1 to len(.key))
    +			for i=1 to len(.key):aa(i)=mid$(.key,i,1):next
    +			.orderkey<=aa()#sort()#str$("")				
    +		}
    +		Module Display {
    +			Print "The 6 x 6 Polybius square:"		
    +			Print "  | A D F G V X"
    +			Print "---------------"
    +			for i=0 to 5
    +				Print mid$(.b,i+1,1)+" | ";
    +				jj=0
    +				for j=i*6 to j+5
    +					print chr$(.a[j]);" ";
    +					jj++
    +				next
    +				print
    +			next
    +			Print "Key:";.key
    +		}
    +		Function Encrypt(p as string) {
    +			crypted=""
    +			for i=1 to len(p)	
    +				crypted+=.map$(mid$(p,i,1))
    +			next
    +			m=1
    +			encrypted=""
    +			For i = 1 To Len(.key)
    +				ch = Mid$(.orderkey, i, 1)			
    +				For j = Instr(.key, ch) - 1 To Len(crypted) - 1 Step Len(.key)
    +					encrypted += Mid$(crypted, j + 1, 1)
    +					if m mod 5=0 then encrypted += " "
    +					m++
    +				Next
    +			Next
    +			=encrypted
    +		}
    +		Function Decrypt(p as string) {
    +			p=filter$(p, " ")
    +			decrypted=""
    +			m=1
    +			dim b$(len(p))
    +			For i = 1 To Len(.key)
    +				ch = Mid$(.orderkey, i, 1)
    +				For j = Instr(.key, ch) - 1 To Len(p) - 1 Step Len(.key)
    +					b$(j)=mid$(p, m, 1)
    +					m++
    +				Next
    +			Next
    +			for i=0 to len(b$())-1 step 2
    +				decrypted+=.map2(b$(i)+b$(i+1))	
    +			next
    +			=decrypted	
    +		}
    +	}
    +	ADFGVX=cipher()
    +	for ADFGVX {
    +		.SetSpecific "A9GKMF1DQRSBVX8Z0WTEJLOPY5U4CN2H76I3"
    +		.SetKey "volcanism"
    +		.Display
    +		encode=.Encrypt("ATTACKAT1200AM")
    +		Print "Encoded: ";encode
    +		Print "Decoded: ";.Decrypt(encode)
    +		Rem { ' using randomblock
    +			thisblock=""
    +			.SetRandom	 &thisblock
    +			Print "Random Block:";thisblock
    +			.Display
    +			encode=.Encrypt("ATTACKAT1200AM")
    +			Print "Encoded: ";encode
    +			Print "Decoded: ";.Decrypt(encode)
    +		}	
    +	}
    +}
    +CheckADFGVX_Cipher
    diff --git a/Task/ADFGVX-cipher/Mathematica/adfgvx-cipher.math b/Task/ADFGVX-cipher/Mathematica/adfgvx-cipher.math
    new file mode 100644
    index 0000000000..b66c4cb9fc
    --- /dev/null
    +++ b/Task/ADFGVX-cipher/Mathematica/adfgvx-cipher.math
    @@ -0,0 +1,24 @@
    +encrypt[plaintext_, polybius_, key_] := Module[{fraction, fractioned},
    +   fraction = Thread[Characters[polybius] -> Tuples[Characters["ADFGVX"], 2]];
    +   fractioned = Partition[Flatten[Characters[plaintext] /. fraction], UpTo[StringLength[key]]];
    +   StringJoin[Flatten[Part[Flatten[fractioned, {2}], Ordering[Characters[key]]]]]];
    +
    +decrypt[encrypted_, polybius_, key_] := Module[{perm, colLengths, fractioned, defraction},
    +   perm = Ordering[Characters[key]];
    +   colLengths = Length /@ Part[Flatten[Partition[Characters[encrypted], UpTo[Length[perm]]], {2}], perm];
    +   fractioned = Flatten[Part[TakeList[Characters[encrypted], colLengths], InversePermutation[perm]], {2}];
    +   defraction = Thread[Tuples[Characters["ADFGVX"], 2] -> Characters[polybius]];
    +   StringJoin[Partition[Flatten[fractioned], 2] /. defraction]];
    +
    +words = ReadList["unixdict.txt", Word];
    +key = Select[words, StringLength[#] == 9 && DuplicateFreeQ[Characters[#]] &] // RandomChoice;
    +polybius = StringJoin@RandomSample@Characters["ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"];
    +plaintext = "ATTACKAT1200AM";
    +encrypted = encrypt[plaintext, polybius, key];
    +decrypted = decrypt[encrypted, polybius, key];
    +
    +Print["Key: ", key];
    +Print["Polybius: ", polybius];
    +Print["Plaintext: ", plaintext];
    +Print["Encrypted: ", encrypted];
    +Print["Decrypted: ", decrypted];
    diff --git a/Task/ADFGVX-cipher/R/adfgvx-cipher.r b/Task/ADFGVX-cipher/R/adfgvx-cipher.r
    new file mode 100644
    index 0000000000..87fc86e172
    --- /dev/null
    +++ b/Task/ADFGVX-cipher/R/adfgvx-cipher.r
    @@ -0,0 +1,173 @@
    +# The ADFGVX cipher.
    +# See also eg. https://www.nku.edu/~christensen/092hnr304%20ADFGVX.pdf
    +
    +# ADFGVX class using R6
    +library(R6)
    +
    +ADFGVX <- R6Class("ADFGVX",
    +  public = list(
    +    polybius = NULL,
    +    pdim = NULL,
    +    key = NULL,
    +    keylen = NULL,
    +    alphabet = NULL,
    +    encode = NULL,
    +    decode = NULL,
    +
    +    # Constructor
    +    initialize = function(s, k, alph = "ADFGVX") {
    +      self$polybius <- toupper(strsplit(s, "")[[1]])
    +      self$pdim <- floor(sqrt(length(self$polybius)))
    +      self$alphabet <- toupper(strsplit(alph, "")[[1]])
    +
    +      # Create encoding dictionary
    +      self$encode <- list()
    +      for (i in 1:self$pdim) {
    +        for (j in 1:self$pdim) {
    +          char <- self$polybius[(i - 1) * self$pdim + j]
    +          self$encode[[char]] <- c(self$alphabet[i], self$alphabet[j])
    +        }
    +      }
    +
    +      # Create decoding dictionary
    +      self$decode <- list()
    +      for (char in names(self$encode)) {
    +        key_str <- paste(self$encode[[char]], collapse = "")
    +        self$decode[[key_str]] <- char
    +      }
    +
    +      stopifnot(self$pdim^2 == length(self$polybius) &&
    +                self$pdim == length(self$alphabet))
    +
    +      self$key <- toupper(strsplit(k, "")[[1]])
    +      self$keylen <- length(self$key)
    +    },
    +
    +    # Encrypt with the ADFGVX cipher
    +    encrypt = function(s) {
    +      chars_upper <- toupper(strsplit(s, "")[[1]])
    +      chars_filtered <- chars_upper[chars_upper %in% self$polybius]
    +
    +      # Encode characters
    +      chars <- unlist(lapply(chars_filtered, function(c) self$encode[[c]]))
    +
    +      # Create column vectors
    +      colvecs <- list()
    +      for (i in 1:self$keylen) {
    +        indices <- seq(i, length(chars), by = self$keylen)
    +        colvecs[[self$key[i]]] <- chars[indices]
    +      }
    +
    +      # Sort by key
    +      sorted_names <- sort(names(colvecs))
    +      result <- unlist(lapply(sorted_names, function(name) colvecs[[name]]))
    +
    +      return(paste(result, collapse = ""))
    +    },
    +
    +    # Decrypt with the ADFGVX cipher
    +    decrypt = function(s) {
    +      chars <- toupper(strsplit(s, "")[[1]])
    +      chars <- chars[chars %in% self$alphabet]
    +
    +      sortedkey <- sort(self$key)
    +      order <- sapply(sortedkey, function(ch) which(self$key == ch)[1])
    +      originalorder <- sapply(self$key, function(ch) which(sortedkey == ch)[1])
    +
    +      # Calculate strides (column lengths)
    +      div_result <- length(chars) %/% self$keylen
    +      rem_result <- length(chars) %% self$keylen
    +      strides <- sapply(order, function(i) {
    +        div_result + ifelse(rem_result >= i, 1, 0)
    +      })
    +
    +      # Calculate starts and ends of columns
    +      starts <- c(1, cumsum(strides[-length(strides)]) + 1)
    +      ends <- starts + strides - 1
    +
    +      # Get reordered columns
    +      cols <- lapply(originalorder, function(i) {
    +        chars[starts[i]:ends[i]]
    +      })
    +
    +      # Recover the rows
    +      nrows <- (length(chars) - 1) %/% self$keylen + 1
    +      pairs <- c()
    +      for (i in 1:nrows) {
    +        for (j in 1:self$keylen) {
    +          if ((i - 1) * self$keylen + j > length(chars)) break
    +          pairs <- c(pairs, cols[[j]][i])
    +        }
    +      }
    +
    +      # Decode pairs
    +      result <- c()
    +      for (i in seq(1, length(pairs) - 1, by = 2)) {
    +        pair_str <- paste(pairs[i:(i+1)], collapse = "")
    +        result <- c(result, self$decode[[pair_str]])
    +      }
    +
    +      return(paste(result, collapse = ""))
    +    }
    +  )
    +)
    +
    +# Main execution
    +set.seed(123)  # For reproducibility
    +POLYBIUS <- paste(sample(strsplit("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", "")[[1]]),
    +                  collapse = "")
    +
    +# Get dictionary words - try multiple sources
    +get_valid_key <- function() {
    +  # Try to read unixdict.txt if it exists
    +  if (file.exists("unixdict.txt")) {
    +    dict_words <- readLines("unixdict.txt")
    +  } else {
    +    # Use sample words if file doesn't exist
    +    dict_words <- c("absolutes", "abruption", "abundance", "abysmally",
    +                    "acrobatic", "algorithm", "ambiguity", "amplitude",
    +                    "ancestory", "archetype", "asynchron", "auctioned",
    +                    "backbone", "backfired", "backlights", "bandwidth",
    +                    "benchmark", "biography", "birthplace", "blasphemy",
    +                    "boulevard", "bricklaying", "broadcast", "butchering",
    +                    "cauterize", "chemicals", "chromatic", "clipboard",
    +                    "completing", "conjugate", "copyright", "daughters",
    +                    "debuggers", "delimiters", "demograph", "dialyzing",
    +                    "dictionary", "education", "equations", "factorize",
    +                    "geography", "goshdarn", "graciously", "graphed",
    +                    "hampshire", "imploding", "indexable", "jeculates",
    +                    "keyboards", "labyrinth", "livestock", "logarithm",
    +                    "machinery", "molecules", "nightmare", "obscurity",
    +                    "particles", "quizboard", "racehorst", "reduction",
    +                    "savepoint", "sectional", "shipyard", "splatting",
    +                    "substance", "technology", "ulceration", "vineyard",
    +                    "warehouse", "workplace", "xanthopsy", "yachtsmen")
    +  }
    +
    +  # Filter for 9-letter words with unique characters
    +  valid_words <- dict_words[sapply(dict_words, function(w) {
    +    n <- nchar(w)
    +    n == 9 && length(unique(strsplit(w, "")[[1]])) == n
    +  })]
    +
    +  if (length(valid_words) == 0) {
    +    stop("No valid 9-letter words with unique characters found")
    +  }
    +
    +  return(toupper(sample(valid_words, 1)))
    +}
    +
    +KEY <- get_valid_key()
    +
    +# Create cipher and encrypt/decrypt
    +SECRETS <- ADFGVX$new(POLYBIUS, KEY)
    +message <- "ATTACKAT1200AM"
    +
    +cat("Polybius:", POLYBIUS, ", Key:", KEY, "\n")
    +cat("Message:", message, "\n")
    +
    +encoded <- SECRETS$encrypt(message)
    +decoded <- SECRETS$decrypt(encoded)
    +
    +cat("Encoded:", encoded, "\n")
    +cat("Decoded:", decoded, "\n")
    diff --git a/Task/ADFGVX-cipher/Rust/adfgvx-cipher.rust b/Task/ADFGVX-cipher/Rust/adfgvx-cipher.rs
    similarity index 100%
    rename from Task/ADFGVX-cipher/Rust/adfgvx-cipher.rust
    rename to Task/ADFGVX-cipher/Rust/adfgvx-cipher.rs
    diff --git a/Task/ADFGVX-cipher/Uiua/adfgvx-cipher.uiua b/Task/ADFGVX-cipher/Uiua/adfgvx-cipher.uiua
    new file mode 100644
    index 0000000000..d163a20723
    --- /dev/null
    +++ b/Task/ADFGVX-cipher/Uiua/adfgvx-cipher.uiua
    @@ -0,0 +1,11 @@
    +A ← ↯∞_2⊞⊟."ADFGVX"
    +P ← ⊏⍏[⍥⚂]⧻."ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
    +K ← "PACKHORSE"
    +Sw ← ⊜□≠" ".
    +Polybius ← setinv(/⊂⊡≡(⊚⌕):⊙:¤P A|⊏:P≡(⊢⊚⌕)⊙¤∩≡□↯∞_2:A)
    +SortByK ← setinv(⊏⍏⟜(⍉⬚" "↯⊟∞⧻)K|▽≠" "./⊂⍉⊏⍏⍏K)
    +Str ← setinv(/$"_ _"Sw/⊂≡(⊂:" ")|≡(⊢°□◇⬚" "↯⊟∞)/↥≡◇⧻.Sw)
    +Pt ← "ATTACKAT1200AM"
    +&p $"Key = _\nPolybius:\n_\nPlaintext = _"K↯⊟.√⧻.P Pt
    +&p$"Crypttext = _". Str SortByK Polybius Pt
    +&p$"Plaintext = _" °Polybius °SortByK °Str
    diff --git a/Task/AKS-test-for-primes/11l/aks-test-for-primes.11l b/Task/AKS-test-for-primes/11l/aks-test-for-primes.11l
    index 110ea6ed1e..dc2fcec555 100644
    --- a/Task/AKS-test-for-primes/11l/aks-test-for-primes.11l
    +++ b/Task/AKS-test-for-primes/11l/aks-test-for-primes.11l
    @@ -12,7 +12,7 @@ F aks_test(p)
        R !any(ex[0 .< (len)-1].map(mult -> mult % @p != 0))
     
     print(‘# p: (x-1)^p for small p’)
    -L(p) 12
    +L(p) 0.<12
        print(‘#3: #.’.format(p, enumerate(expand_x_1(p)).map((n, e) -> ‘#.#.#.’.format(‘+’ * (e >= 0), e, I n {(‘x^#.’.format(n))} E ‘’)).join(‘ ’)))
     
     print("\n# small primes using the aks test")
    diff --git a/Task/AKS-test-for-primes/ANSI-BASIC/aks-test-for-primes.basic b/Task/AKS-test-for-primes/ANSI-BASIC/aks-test-for-primes.basic
    new file mode 100644
    index 0000000000..547da20116
    --- /dev/null
    +++ b/Task/AKS-test-for-primes/ANSI-BASIC/aks-test-for-primes.basic
    @@ -0,0 +1,79 @@
    +100 REM AKS test for primes
    +110 DECLARE EXTERNAL SUB PascalTriangle
    +120 DECLARE EXTERNAL SUB ExpandPoly
    +130 DECLARE EXTERNAL FUNCTION IsPrime
    +140 FOR N = 0 TO 9
    +150    CALL ExpandPoly(N)
    +160 NEXT N
    +170 FOR N = 2 TO 50
    +180    IF IsPrime(N) <> 0 THEN PRINT USING("###"): N;
    +190 NEXT N
    +200 PRINT
    +210 END
    +220 REM **
    +230 EXTERNAL SUB PascalTriangle(N, PasTri())
    +240 REM Calculate t!he N'th line 0.. middle
    +250 LET N = INT(N)
    +260 LET PasTri(0) = 1
    +270 LET J = 1
    +280 DO WHILE J <= N
    +290    LET J = J + 1
    +300    LET K = INT(J / 2)
    +310    LET PasTri(K) = PasTri(K - 1)
    +320    FOR K = K TO 1 STEP -1
    +330       LET PasTri(K) = PasTri(K) + PasTri(K - 1)
    +340    NEXT K
    +350 LOOP
    +360 END SUB
    +370 REM **
    +380 EXTERNAL FUNCTION IsPrime(N)
    +390 LET N = INT(N)
    +400 DIM PasTri(0 TO 50)
    +410 LET PasTriMax = UBOUND(PasTri)
    +420 IF N > PasTriMax THEN
    +430    PRINT N; "is out of range"
    +440    STOP
    +450 END IF
    +460 CALL PascalTriangle(N, PasTri)
    +470 LET Res = 1
    +480 LET I = INT(N / 2)
    +490 DO WHILE (Res <> 0) AND (I > 1)
    +500    IF (Res <> 0) AND (MOD(PasTri(I), N) = 0) THEN LET Res = 1 ELSE LET Res = 0
    +510    LET I = I - 1
    +520 LOOP
    +530 LET IsPrime = Res
    +540 END FUNCTION
    +550 REM **
    +560 EXTERNAL SUB ExpandPoly(N)
    +570 LET N = INT(N)
    +580 DIM VZ$(0 TO 1)
    +590 LET VZ$(0) = "+"
    +600 LET VZ$(1) = "-"
    +610 DIM PasTri(0 TO 50)
    +620 LET PasTriMax = UBOUND(PasTri)
    +630 IF N > PasTriMax THEN
    +640    PRINT N; "is out of range"
    +650    STOP
    +660 END IF
    +670 SELECT CASE N
    +680 CASE 0
    +690    PRINT "(x - 1) ^ 0 = 1"
    +700 CASE 1
    +710    PRINT "(x - 1) ^ 1 = x - 1"
    +720 CASE ELSE
    +730    CALL PascalTriangle(N, PasTri)
    +740    PRINT "(x - 1) ^"; N; " = x ^"; N;
    +750    LET BVZ = 1
    +760    FOR J = N - 1 TO INT(N / 2) + 1 STEP -1
    +770       PRINT VZ$(BVZ); PasTri(N - J); "* x ^"; J;
    +780       LET BVZ = ABS(1 - BVZ)
    +790    NEXT J
    +800    FOR J = INT(N / 2) TO 2 STEP -1
    +810       PRINT VZ$(BVZ); PasTri(J); "* x ^"; J;
    +820       LET BVZ = ABS(1 - BVZ)
    +830    NEXT J
    +840    PRINT VZ$(BVZ); PasTri(1); "* x ";
    +850    LET BVZ = ABS(1 - BVZ)
    +860    PRINT VZ$(BVZ); PasTri(0)
    +870 END SELECT
    +880 END SUB
    diff --git a/Task/AKS-test-for-primes/Ada/aks-test-for-primes.ada b/Task/AKS-test-for-primes/Ada/aks-test-for-primes.adb
    similarity index 100%
    rename from Task/AKS-test-for-primes/Ada/aks-test-for-primes.ada
    rename to Task/AKS-test-for-primes/Ada/aks-test-for-primes.adb
    diff --git a/Task/AKS-test-for-primes/Agena/aks-test-for-primes.agena b/Task/AKS-test-for-primes/Agena/aks-test-for-primes.agena
    new file mode 100644
    index 0000000000..6589095e8f
    --- /dev/null
    +++ b/Task/AKS-test-for-primes/Agena/aks-test-for-primes.agena
    @@ -0,0 +1,89 @@
    +# AKS test for primes
    +
    +constant pas_tri_max := 50;
    +
    +proc pascal_triangle(n :: posint) is
    +# Calculate the n'th line 1.. middle
    +# For n = 1, 2, ..
    +  create register pas_tri((n + 1) \ 2);
    +  # pas_tri[0] always is 1
    +  j := 1;
    +  case n
    +    of 1, 2 then pas_tri[1] := 2
    +    else
    +      j := 3;
    +      pas_tri[1] := 2;
    +      while j <= n do
    +        j++;
    +        k := j \ 2; # middle
    +        pas_tri[k] := pas_tri[k - 1];
    +        while k >= 2 do
    +          pas_tri[k] +:= pas_tri[k - 1];
    +          k--
    +        od;
    +        pas_tri[1] +:= 1
    +      od
    +    esle
    +  esac
    +  return pas_tri
    +end;
    +
    +proc is_prime(n :: nonnegint) :: boolean is
    +  if n > pas_tri_max then
    +    printf("%d is out of range\n", n);
    +    os.exit(-1)
    +  fi;
    +  pas_tri := pascal_triangle(n);
    +  res := true;
    +  i := n \ 2;
    +  while res and (i > 1) do
    +    res := res and (pas_tri[i] symmod n = 0);
    +    i--
    +  od;
    +  return res
    +end;
    +
    +proc vz(b :: boolean) is
    +  return if b then '-' else '+' fi
    +end;
    +
    +proc expand_poly(n :: nonnegint) is
    +  if n > pas_tri_max then
    +    printf("%d is out of range\n", n);
    +    os.exit(-1)
    +  fi;
    +  case n
    +    of 0 then printf("(x-1)^0 = 1\n");
    +    of 1 then printf("(x-1)^1 = x-1\n");
    +    else
    +      pas_tri := pascal_triangle(n);
    +      printf("(x-1)^%d = x^%d", n, n);
    +      bvz := true;
    +      n_div_2 := n \ 2
    +      for j from n - 1 to n_div_2 + 1 by -1 do
    +        printf("%s%d*x^%d", vz(bvz), pas_tri[n - j], j);
    +        bvz := not bvz
    +      od;
    +      for j from n_div_2 to 2 by -1 do
    +        printf("%s%d*x^%d", vz(bvz), pas_tri[j], j);
    +        bvz := not bvz
    +      od;
    +      printf("%s%d*x", vz(bvz), pas_tri[1]);
    +      bvz := not bvz;
    +      printf("%s1\n", vz(bvz));
    +    esle
    +  esac
    +end;
    +
    +scope
    +  local n;
    +  for n from 0 to 9 do
    +    expand_poly(n)
    +  od;
    +  for n from 2 to pas_tri_max do
    +    if is_prime(n) then
    +      printf("%3d", n)
    +    fi
    +  od;
    +  printf("\n")
    +end
    diff --git a/Task/AKS-test-for-primes/Ballerina/aks-test-for-primes.ballerina b/Task/AKS-test-for-primes/Ballerina/aks-test-for-primes.ballerina
    new file mode 100644
    index 0000000000..575c645a5f
    --- /dev/null
    +++ b/Task/AKS-test-for-primes/Ballerina/aks-test-for-primes.ballerina
    @@ -0,0 +1,58 @@
    +import ballerina/io;
    +
    +int[] e = "²³⁴⁵⁶⁷".toCodePointInts();
    +
    +function bc(int p) returns int[] {
    +    int[] c = [];
    +    c.setLength(p + 1);
    +    int r = 1;
    +    int half = p / 2;
    +    foreach int i in 0...half {
    +        c[i] = r;
    +        c[p - i] = r;
    +        r = r * (p - i) / (i + 1);
    +    }
    +    foreach int i in int:range(p - 1, -1, -2) {
    +        c[i] = -c[i];
    +    }
    +    return c;
    +}
    +
    +function pp(int[] c) returns string|error {
    +    if c.length() == 1 { return c[0].toString(); }
    +    int p = c.length() - 1;
    +    string s = "";
    +    if c[p] != 1 { s = c[p].toString(); }
    +    foreach int i in int:range(p, 0, -1) {
    +        s += "x";
    +        if i != 1 { s += check string:fromCodePointInt(e[i - 2]); }
    +        int d = c[i - 1];
    +        if d < 0 {
    +            s += " - " + (-d).toString();
    +        } else {
    +            s += " + " + d.toString();
    +        }
    +    }
    +    return s;
    +}
    +
    +function aks(int p) returns boolean {
    +    int[] c = bc(p);
    +    c[p] -= 1;
    +    c[0] += 1;
    +    foreach int d in c {
    +        if d % p != 0 { return false; }
    +    }
    +    return true;
    +}
    +
    +public function main() {
    +    foreach int p in 0...7 {
    +        io:println(p, ":  ", pp(bc(p)));
    +    }
    +    io:println("\nAll primes under 50:");
    +    foreach int p in 2...49 {
    +        if aks(p) { io:print(p, " "); }
    +    }
    +    io:println();
    +}
    diff --git a/Task/AKS-test-for-primes/Clojure/aks-test-for-primes.clj b/Task/AKS-test-for-primes/Clojure/aks-test-for-primes.clj
    index 377a586076..47c637a9e0 100644
    --- a/Task/AKS-test-for-primes/Clojure/aks-test-for-primes.clj
    +++ b/Task/AKS-test-for-primes/Clojure/aks-test-for-primes.clj
    @@ -3,7 +3,7 @@
       [n k]
       (/ (apply *' (range n (- n k) -1))
          (apply *' (range k 0 -1))
    -     (if (and (even? k) (< k n)) -1 1)))
    +     (if (even? k) 1 -1)))
     
     (defn cs
       "coefficient series for (x - 1)^n, k=[0..n]"
    diff --git a/Task/AKS-test-for-primes/Crystal/aks-test-for-primes.crystal b/Task/AKS-test-for-primes/Crystal/aks-test-for-primes.cr
    similarity index 100%
    rename from Task/AKS-test-for-primes/Crystal/aks-test-for-primes.crystal
    rename to Task/AKS-test-for-primes/Crystal/aks-test-for-primes.cr
    diff --git a/Task/AKS-test-for-primes/EasyLang/aks-test-for-primes.easy b/Task/AKS-test-for-primes/EasyLang/aks-test-for-primes.easy
    new file mode 100644
    index 0000000000..10fa6635e4
    --- /dev/null
    +++ b/Task/AKS-test-for-primes/EasyLang/aks-test-for-primes.easy
    @@ -0,0 +1,43 @@
    +func[] coefs n .
    +   len list[] n + 2
    +   list[0] = 1
    +   for k = 0 to n : list[k + 1] = list[k] * (n - k) / (k + 1)
    +   for k = 1 step 2 to n : list[k] = -list[k]
    +   return list[]
    +.
    +func isprimeaks n .
    +   c[] = coefs n
    +   c[0] -= 1
    +   c[n] += 1
    +   for i = 0 to n
    +      if c[i] mod n <> 0 : return 0
    +   .
    +   return 1
    +.
    +proc pprintcoefs n list[] .
    +   for i = 0 to n
    +      s$ = ""
    +      if i > 0
    +         s$ = " + "
    +         if list[i] < 0 : s$ = " - "
    +      .
    +      c$ = abs list[i]
    +      e = n - i
    +      if c$ = "1" and e > 0 : c$ = ""
    +      x$ = ""
    +      if e <> 0
    +         x$ = "x"
    +         if e <> 1 : x$ &= "^" & e
    +      .
    +      r$ &= s$ & c$ & x$
    +   .
    +   print "(x-1)^" & n & " : " & r$
    +.
    +for i = 0 to 7
    +   pprintcoefs i coefs i
    +.
    +print ""
    +for i = 2 to 49
    +   if isprimeaks i = 1 : write i & " "
    +.
    +print ""
    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 d1ab382bf3..bda73a4cdf 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
    @@ -45,28 +45,28 @@ singleton AksTest
             while(i != 0)
             {
                 i -= 1;
    -            console.print("+",c[i],"x^",i)
    +            Console.print("+",c[i],"x^",i)
             }
         }
     }
     
    -public program()
    +public Program()
     {
         for (int n := 0; n < 10; n += 1) {
             AksTest.coef(n);
     
    -		console.print("(x-1)^",n," = ");
    +		Console.print("(x-1)^",n," = ");
     		AksTest.show(n);
    -        console.printLine()
    +        Console.printLine()
         };
     
    -    console.print("Primes:");
    +    Console.print("Primes:");
         for (int n := 1; n <= 63; n += 1) {
             if (AksTest.is_prime(n))
             {
    -            console.print(n," ")
    +            Console.print(n," ")
             }
         };
     
    -    console.printLine().readChar()
    +    Console.printLine().readChar()
     }
    diff --git a/Task/AKS-test-for-primes/Elixir/aks-test-for-primes.elixir b/Task/AKS-test-for-primes/Elixir/aks-test-for-primes.ex
    similarity index 100%
    rename from Task/AKS-test-for-primes/Elixir/aks-test-for-primes.elixir
    rename to Task/AKS-test-for-primes/Elixir/aks-test-for-primes.ex
    diff --git a/Task/AKS-test-for-primes/FutureBasic/aks-test-for-primes.basic b/Task/AKS-test-for-primes/FutureBasic/aks-test-for-primes.basic
    new file mode 100644
    index 0000000000..72bc4196df
    --- /dev/null
    +++ b/Task/AKS-test-for-primes/FutureBasic/aks-test-for-primes.basic
    @@ -0,0 +1,101 @@
    +// AKS Test for Primes task
    +// https://rosettacode.org/wiki/AKS_test_for_primes
    +
    +
    +#build ShowMoreWarnings NO
    +
    +begin globals
    +  sInt64 c(100)
    +  //double n
    +end globals
    +
    +local fn coef(nx as short)
    +  // out-by-1, ie coef(1)==^0, coef(2)==^1, coef(3)==^2 etc.
    +  c(nx) = 1
    +  short i
    +  for i = nx-1 to 2 step -1
    +    c(i) = c(i) + c(i-1)
    +  next
    +end fn
    +
    +local fn is_prime(nx as short) as boolean
    +  short i
    +  bool result = _false
    +  fn coef(nx+1) // (I said it was out-by-1)
    +  for i = 2 to nx-1   // (technically "to n" is more correct)
    +    if int(c(i)/nx) <> c(i)/nx
    +      return _false
    +    end if
    +  next
    +
    +  result = _true
    +end fn = result
    +
    +local fn show(nx as short)
    +  // (As per coef, this is (working) out-by-1)
    +
    +  double ci
    +  str255 cix
    +  short i
    +
    +  for i = nx to 1 step -1
    +    ci = c(i)
    +    if ci = 1
    +      if (nx-i) mod 2 = 0
    +        if i = 1
    +          if nx = 1
    +            cix = "    1"
    +          else
    +            cix = "+1"
    +          end if
    +        else
    +          cix = ""
    +        end if
    +      else
    +        cix = "-1"
    +      end if
    +    else
    +      if (nx-i) mod 2 = 0
    +        cix = "+" + str$(ci)
    +      else
    +        cix = "-" + str$(ci)
    +      end if
    +    end if
    +
    +    if i = 1 // ie ^0
    +      print cix;
    +    else
    +      if i = 2 then print cix, "x"; // ie ^1
    +      if i <> 2 then print cix, "x^", i-1;
    +    end if
    +
    +  next i
    +end fn
    +
    +local fn AKS_test_for_primes
    +  short nx
    +
    +  for nx = 1 to 10 // (0 to 9 really)
    +    fn coef(nx)
    +    print "(x-1)^" + str$(nx-1) +  " = ";
    +    fn show(nx)
    +    print
    +  next
    +
    +  print
    +  print "primes (<=53): ";
    +  short n
    +  c(2) = 1 // (this manages "", which is all that call did anyway...)
    +  for n = 2 to 53
    +    if fn is_prime(n)
    +      print " ", n;
    +    end if
    +  next
    +  print
    +end fn
    +
    +window 1,@"AKS test for Primes",fn CGRectMake(0, 0, 850, 200)
    +
    +fn AKS_test_for_primes
    +
    +handleevents
    diff --git a/Task/AKS-test-for-primes/Julia/aks-test-for-primes-1.julia b/Task/AKS-test-for-primes/Julia/aks-test-for-primes-1.jl
    similarity index 100%
    rename from Task/AKS-test-for-primes/Julia/aks-test-for-primes-1.julia
    rename to Task/AKS-test-for-primes/Julia/aks-test-for-primes-1.jl
    diff --git a/Task/AKS-test-for-primes/Julia/aks-test-for-primes-2.julia b/Task/AKS-test-for-primes/Julia/aks-test-for-primes-2.jl
    similarity index 100%
    rename from Task/AKS-test-for-primes/Julia/aks-test-for-primes-2.julia
    rename to Task/AKS-test-for-primes/Julia/aks-test-for-primes-2.jl
    diff --git a/Task/AKS-test-for-primes/Julia/aks-test-for-primes-3.julia b/Task/AKS-test-for-primes/Julia/aks-test-for-primes-3.jl
    similarity index 100%
    rename from Task/AKS-test-for-primes/Julia/aks-test-for-primes-3.julia
    rename to Task/AKS-test-for-primes/Julia/aks-test-for-primes-3.jl
    diff --git a/Task/AKS-test-for-primes/Julia/aks-test-for-primes-4.julia b/Task/AKS-test-for-primes/Julia/aks-test-for-primes-4.jl
    similarity index 100%
    rename from Task/AKS-test-for-primes/Julia/aks-test-for-primes-4.julia
    rename to Task/AKS-test-for-primes/Julia/aks-test-for-primes-4.jl
    diff --git a/Task/AKS-test-for-primes/Kotlin/aks-test-for-primes.kotlin b/Task/AKS-test-for-primes/Kotlin/aks-test-for-primes.kts
    similarity index 100%
    rename from Task/AKS-test-for-primes/Kotlin/aks-test-for-primes.kotlin
    rename to Task/AKS-test-for-primes/Kotlin/aks-test-for-primes.kts
    diff --git a/Task/AKS-test-for-primes/Loglan82/aks-test-for-primes.loglan82 b/Task/AKS-test-for-primes/Loglan82/aks-test-for-primes.loglan82
    new file mode 100644
    index 0000000000..73629f52ea
    --- /dev/null
    +++ b/Task/AKS-test-for-primes/Loglan82/aks-test-for-primes.loglan82
    @@ -0,0 +1,89 @@
    +program AKS;
    +(* AKS test for primes *)
    +
    +const
    +  Pas_tri_last = 33; (* 33 for 32-bit integer type; 17 for 16-bit integer *)
    +var
    +  n: integer;
    +
    +  (* Calculate the n'th line 0 .. middle *)
    +  unit Pascal_triangle: procedure (n: integer; Pas_tri: arrayof integer);
    +  var
    +    j, k: integer;
    +  begin
    +    Pas_tri(0) := 1;
    +    j := 1;
    +    while j <= n
    +    do
    +      j := j + 1;
    +      k := j div 2;
    +      Pas_tri(k) := Pas_tri(k - 1);
    +      while k >= 1
    +      do
    +        Pas_tri(k) := Pas_tri(k) + Pas_tri(k - 1);
    +        k := k - 1
    +      od;
    +    od;
    +  end Pascal_triangle;
    +
    +  unit is_prime: function (n: integer): boolean;
    +  var
    +    i: integer,
    +    Pas_tri: arrayof integer;
    +  begin
    +    array Pas_tri dim (0 : n);
    +    call Pascal_triangle(n, Pas_tri);
    +    result := true;
    +    i := n div 2;
    +    while result and (i > 1)
    +    do
    +      result := result and (Pas_tri(i) mod n = 0);
    +      i := i - 1;
    +    od;
    +  end is_prime;
    +
    +  unit vz: function (b: boolean): character;
    +  begin
    +    if b then result := '-' else result := '+' fi;
    +  end vz;
    +
    +  unit expand_poly: procedure (n: integer);
    +  var
    +    Pas_tri: arrayof integer,
    +    bvz: boolean,
    +    j: integer;
    +  begin
    +    array Pas_tri dim (0 : n);
    +    case n
    +      when 0: writeln("(x - 1) ^ 0 = 1")
    +      when 1: writeln("(x - 1) ^ 1 = x - 1")
    +      otherwise
    +        call Pascal_triangle(n, Pas_tri);
    +        write("(x - 1) ^ ", n: 1, " = x ^ ", n: 1, " ");
    +        bvz := true;
    +        for j := n - 1 downto (n div 2) + 1
    +        do
    +          write(vz(bvz), " ", Pas_tri(n - j): 1, " * x ^ ", j: 1, " ");
    +          bvz := not bvz;
    +        od;
    +        for j := (n div 2) downto 2
    +        do
    +          write(vz(bvz), " ", Pas_tri(j): 1, " * x ^ ", j: 1, " ");
    +          bvz := not bvz
    +        od;
    +        write(vz(bvz), " ", Pas_tri(1): 1, " * x ");
    +        bvz := not bvz;
    +        writeln(vz(bvz), " ", Pas_tri(0): 1);
    +    esac;
    +  end expand_poly;
    +
    +begin
    +  for n := 0 to 9
    +  do
    +    call expand_poly(n)
    +  od;
    +  for n := 2 to Pas_tri_last do
    +    if is_prime(n) then write(n: 1, " ") fi;
    +  od;
    +  writeln;
    +end
    diff --git a/Task/AKS-test-for-primes/Modula-2/aks-test-for-primes.mod2 b/Task/AKS-test-for-primes/Modula-2/aks-test-for-primes.mod2
    new file mode 100644
    index 0000000000..a138aea166
    --- /dev/null
    +++ b/Task/AKS-test-for-primes/Modula-2/aks-test-for-primes.mod2
    @@ -0,0 +1,119 @@
    +MODULE AKSTest;
    +(* AKS test for primes *)
    +
    +FROM STextIO IMPORT
    +  WriteLn, WriteString;
    +FROM SWholeIO IMPORT
    +  WriteInt;
    +
    +CONST
    +  PasTriMax = 33; (* for 32-bit integer type *)
    +
    +TYPE
    +  TPasTri = ARRAY [0 .. PasTriMax] OF CARDINAL;
    +
    +VAR
    +  N: CARDINAL;
    +
    +PROCEDURE PascalTriangle(N: CARDINAL; VAR PasTri: TPasTri);
    +(* Calculate the N'th line 0.. middle *)
    +VAR
    +  J, K: CARDINAL;
    +BEGIN
    +  PasTri[0] := 1;
    +  J := 1;
    +  WHILE J <= N DO
    +    J := J + 1;
    +    K := J DIV 2;
    +    PasTri[K] := PasTri[K - 1];
    +    FOR K := K TO 1 BY -1 DO
    +      PasTri[K] := PasTri[K] + PasTri[K - 1];
    +    END
    +  END
    +END PascalTriangle;
    +
    +PROCEDURE IsPrime(N: CARDINAL): BOOLEAN;
    +VAR
    +  Res   : BOOLEAN;
    +  I     : CARDINAL;
    +  PasTri: TPasTri;
    +BEGIN
    +  IF N > PasTriMax THEN
    +    WriteInt(N, 1);
    +    WriteString(" is out of range");
    +    WriteLn;
    +    HALT;
    +  END;
    +  PascalTriangle(N, PasTri);
    +  Res := TRUE;
    +  I := N DIV 2;
    +  WHILE Res AND (I > 1) DO
    +    Res := Res AND (PasTri[I] MOD N = 0);
    +    I := I - 1
    +  END;
    +  RETURN Res;
    +END IsPrime;
    +
    +PROCEDURE ExpandPoly(N: CARDINAL);
    +TYPE
    +  TVZ = ARRAY BOOLEAN OF CHAR;
    +CONST
    +  VZ = TVZ {'+', '-'};
    +VAR
    +  J     : CARDINAL;
    +  BVZ   : BOOLEAN;
    +  PasTri: TPasTri;
    +BEGIN
    +  IF N > PasTriMax THEN
    +    WriteInt(N, 1);
    +    WriteString(" is out of range");
    +    WriteLn;
    +    HALT
    +  END;
    +  CASE N OF
    +  | 0:
    +    WriteString("(x-1)^0 = 1"); WriteLn;
    +  | 1:
    +    WriteString("(x-1)^1 = x-1"); WriteLn;
    +  ELSE
    +    PascalTriangle(N, PasTri);
    +    WriteString("(x-1)^");
    +    WriteInt(N, 1);
    +    WriteString(" = x^");
    +    WriteInt(N, 1);
    +    BVZ := TRUE;
    +    FOR J := N - 1 TO N DIV 2 + 1 BY -1 DO
    +      WriteString(VZ[BVZ]);
    +      WriteInt(PasTri[N - J], 1);
    +      WriteString("*x^");
    +      WriteInt(J, 1);
    +      BVZ := NOT BVZ
    +    END;
    +    FOR J := N DIV 2 TO 2 BY -1 DO
    +      WriteString(VZ[BVZ]);
    +      WriteInt(PasTri[J], 1);
    +      WriteString("*x^");
    +      WriteInt(J, 1);
    +      BVZ := NOT BVZ
    +    END;
    +    WriteString(VZ[BVZ]);
    +    WriteInt(PasTri[1], 1);
    +    WriteString("*x");
    +    BVZ := NOT BVZ;
    +    WriteString(VZ[BVZ]);
    +    WriteInt(PasTri[0], 1);
    +    WriteLn;
    +  END;
    +END ExpandPoly;
    +
    +BEGIN
    +  FOR N := 0 TO 9 DO
    +    ExpandPoly(N)
    +  END;
    +  FOR N := 2 TO PasTriMax DO
    +    IF IsPrime(N) THEN
    +      WriteInt(N, 3)
    +    END
    +  END;
    +  WriteLn;
    +END AKSTest.
    diff --git a/Task/AKS-test-for-primes/OCaml/aks-test-for-primes.ocaml b/Task/AKS-test-for-primes/OCaml/aks-test-for-primes.ml
    similarity index 100%
    rename from Task/AKS-test-for-primes/OCaml/aks-test-for-primes.ocaml
    rename to Task/AKS-test-for-primes/OCaml/aks-test-for-primes.ml
    diff --git a/Task/AKS-test-for-primes/PHP/aks-test-for-primes.php b/Task/AKS-test-for-primes/PHP/aks-test-for-primes.php
    new file mode 100644
    index 0000000000..9b3e9bbaa4
    --- /dev/null
    +++ b/Task/AKS-test-for-primes/PHP/aks-test-for-primes.php
    @@ -0,0 +1,80 @@
    + PAS_TRI_MAX) {
    +    echo $n, " is out of range", PHP_EOL;
    +    exit;
    +  }
    +  switch ($n) {
    +    case 0:
    +      echo "(x-1)^0 = 1", PHP_EOL;
    +      break;
    +    case 1:
    +      echo "(x-1)^1 = x-1", PHP_EOL;
    +      break;
    +    default:
    +      $pas_tri = [];
    +      pascal_triangle($n, $pas_tri);
    +      echo "(x-1)^", $n, " = x^", $n;
    +      $bvz = true;
    +      $n_div_2 = intdiv($n, 2);
    +      for ($j = $n - 1; $j > $n_div_2; $j--) {
    +        echo vz($bvz), $pas_tri[$n - $j], "*x^", $j;
    +        $bvz = !$bvz;
    +      }
    +      for ($j = $n_div_2; $j >= 2; $j--) {
    +        echo vz($bvz), $pas_tri[$j], "*x^", $j;
    +        $bvz = !$bvz;
    +      }
    +      echo vz($bvz), $pas_tri[1], "*x";
    +      $bvz = !$bvz;
    +      echo vz($bvz), $pas_tri[0], PHP_EOL;
    +  }
    +}
    +
    +function pascal_triangle($n, &$pas_tri) {
    +// Calculate the $n'th line 0.. middle
    +  $pas_tri = array_fill(0, intdiv($n + 1, 2) + 1, 0);
    +  $pas_tri[0] = 1;
    +  $j = 1;
    +  while ($j <= $n) {
    +    $j++;
    +    $k = intdiv($j, 2);
    +    $pas_tri[$k] = $pas_tri[$k - 1];
    +    while ($k >= 1) {
    +      $pas_tri[$k] += $pas_tri[$k - 1];
    +      $k--;
    +    }
    +  }
    +}
    +
    +function is_prime($n):bool {
    +  if ($n > PAS_TRI_MAX) {
    +    echo $n, " is out of range", PHP_EOL;
    +    exit;
    +  }
    +  $pas_tri = [];
    +  pascal_triangle($n, $pas_tri);
    +  $res = true;
    +  $i = intdiv($n, 2);
    +  while ($res && ($i > 1)) {
    +    $res = $res && ($pas_tri[$i] % $n == 0);
    +    --$i;
    +  }
    +  return $res;
    +}
    +
    +for ($n = 0; $n <= 9; $n++)
    +  expand_poly($n);
    +for ($n = 2; $n <= PAS_TRI_MAX; $n++)
    +  if (is_prime($n))
    +    echo str_pad($n, 3, " ", STR_PAD_LEFT);
    +echo PHP_EOL;
    +?>
    diff --git a/Task/AKS-test-for-primes/Phix/aks-test-for-primes-1.phix b/Task/AKS-test-for-primes/Phix/aks-test-for-primes-1.phix
    new file mode 100644
    index 0000000000..da1bc84810
    --- /dev/null
    +++ b/Task/AKS-test-for-primes/Phix/aks-test-for-primes-1.phix
    @@ -0,0 +1,78 @@
    +-- demo/rosetta/AKSprimes.exw
    +-- Does not work for primes above 67 (56 on 32bit), which is actually beyond the original task anyway.
    +-- Translated from the C version (with all out-by-1 stuff now eradicated).
    +with javascript_semantics
    +constant limit = iff(machine_bits()=32?56:67)
    +sequence c = repeat(0,limit+1)
    +
    +procedure coef(integer n)
    +    c[n+1] = 1
    +    for i=n to 2 by -1 do
    +        c[i] += c[i-1]
    +    end for
    +end procedure
    +
    +function is_aks_prime(integer n)
    +    coef(n)
    +    for i=2 to n-1 do
    +        if remainder(c[i],n)!=0 then
    +            return false
    +        end if
    +    end for
    +    return true
    +end function
    +
    +procedure show(integer n)
    +    for i=n+1 to 1 by -1 do
    +        object ci = c[i]
    +        if ci=1 then
    +            if remainder(n-i+1,2)=0 then
    +                if i=1 then
    +                    if n=0 then
    +                        ci = "1"
    +                    else
    +                        ci = "+1"
    +                    end if
    +                else
    +                    ci = ""
    +                end if
    +            else
    +                ci = "-1"
    +            end if
    +        else
    +            if remainder(n-i+1,2)=0 then
    +                ci = sprintf("+%d",ci)
    +            else
    +                ci = sprintf("-%d",ci)
    +            end if
    +        end if
    +        if i=1 then -- ie ^0
    +            printf(1,"%s",{ci})
    +        elsif i=2 then -- ie ^1
    +            printf(1,"%sx",{ci})
    +        else
    +            printf(1,"%sx^%d",{ci,i-1})
    +        end if
    +    end for
    +end procedure
    +
    +procedure main()
    +    for n=0 to 9 do
    +        coef(n);
    +        printf(1,"(x-1)^%d = ", n);
    +        show(n);
    +        puts(1,'\n');
    +    end for
    +
    +    printf(1,"\nprimes (<=%d):",limit);
    +--  coef(1); -- (needed to reset c, if we want to avoid saying 1 is prime...)
    +    c[2] = 1 -- (this manages "", which is all that call did anyway...)
    +    for n=2 to limit do
    +        if is_aks_prime(n) then
    +            printf(1," %d", n);
    +        end if
    +    end for
    +    puts(1,'\n');
    +  wait_key()
    +end procedure
    +main()
    diff --git a/Task/AKS-test-for-primes/Phix/aks-test-for-primes-2.phix b/Task/AKS-test-for-primes/Phix/aks-test-for-primes-2.phix
    new file mode 100644
    index 0000000000..f8bd4ad4ab
    --- /dev/null
    +++ b/Task/AKS-test-for-primes/Phix/aks-test-for-primes-2.phix
    @@ -0,0 +1,27 @@
    +include mpfr.e
    +mpz z = mpz_init()
    +atom t0 = time(), t1 = t0+1
    +sequence p = {}
    +integer maxn = 0
    +for n=2 to 10000 do -- (more than we can manage in 10s)
    +    bool nprime = true
    +    for k=1 to n-1 do
    +        mpz_bin_uiui(z,n,k)
    +        if not mpz_divisible_ui_p(z,n) then
    +            nprime = false
    +            exit
    +        end if
    +    end for
    +    if nprime then
    +        p &= n
    +    end if
    +    maxn = n
    +    if time()>t1 then
    +        if time()>t0+10 then progress("") exit end if
    +        progress("checking %d",{n})
    +        t1 = time()+1
    +    end if
    +end for
    +sequence q = get_primes_le(maxn)
    +printf(1,"%d primes < %d found, correctly:%t, in %s\n",{length(p),maxn,p=q,elapsed(time()-t0)})
    +wait_key()
    diff --git a/Task/AKS-test-for-primes/Phix/aks-test-for-primes-3.phix b/Task/AKS-test-for-primes/Phix/aks-test-for-primes-3.phix
    new file mode 100644
    index 0000000000..bfa4d0b3d9
    --- /dev/null
    +++ b/Task/AKS-test-for-primes/Phix/aks-test-for-primes-3.phix
    @@ -0,0 +1,24 @@
    +atom t0 = time(), t1 = t0+1
    +sequence p = {}
    +integer maxn = 0
    +for n=2 to 10000 do -- (more than we can manage in 10s)
    +    sequence r = {1}
    +    for k=1 to n do
    +        r &= 1
    +        for l=k to 2 by -1 do
    +            r[l] = remainder(r[l]+r[l-1],n)
    +        end for
    +    end for
    +    if sum(r)=2 then -- ie {1,<==all 0s==>,1}
    +        p &= n
    +    end if
    +    maxn = n
    +    if time()>t1 then
    +        if time()>t0+10 then progress("") exit end if
    +        progress("checking %d",{n})
    +        t1 = time()+1
    +    end if
    +end for
    +sequence q = get_primes_le(maxn)
    +printf(1,"%d primes < %d found, correctly:%t, in %s\n",{length(p),maxn,p=q,elapsed(time()-t0)})
    +wait_key()
    diff --git a/Task/AKS-test-for-primes/Phix/aks-test-for-primes.phix b/Task/AKS-test-for-primes/Phix/aks-test-for-primes.phix
    deleted file mode 100644
    index 384e622777..0000000000
    --- a/Task/AKS-test-for-primes/Phix/aks-test-for-primes.phix
    +++ /dev/null
    @@ -1,82 +0,0 @@
    --->
    - -- demo/rosetta/AKSprimes.exw
    - -- Does not work for primes above 53, which is actually beyond the original task anyway.
    - -- Translated from the C version, just about everything is (working) out-by-1, what fun.
    -
    - sequence c = repeat(0,100)
    -
    - procedure coef(integer n)
    - -- out-by-1, ie coef(1)==^0, coef(2)==^1, coef(3)==^2 etc.
    -     c[n] = 1
    -     for i=n-1 to 2 by -1 do
    -         c[i] = c[i]+c[i-1]
    -     end for
    - end procedure
    -
    - function is_aks_prime(integer n)
    -     coef(n+1); -- (I said it was out-by-1)
    -     for i=2 to n-1 do   -- (technically "to n" is more correct)
    -         if remainder(c[i],n)!=0 then
    -             return 0
    -         end if
    -     end for
    -     return 1
    - end function
    -
    - procedure show(integer n)
    - -- (As per coef, this is (working) out-by-1)
    - object ci
    -     for i=n to 1 by -1 do
    -         ci = c[i]
    -         if ci=1 then
    -             if remainder(n-i,2)=0 then
    -                 if i=1 then
    -                     if n=1 then
    -                         ci = "1"
    -                     else
    -                         ci = "+1"
    -                     end if
    -                 else
    -                     ci = ""
    -                 end if
    -             else
    -                 ci = "-1"
    -             end if
    -         else
    -             if remainder(n-i,2)=0 then
    -                 ci = sprintf("+%d",ci)
    -             else
    -                 ci = sprintf("-%d",ci)
    -             end if
    -         end if
    -         if i=1 then -- ie ^0
    -             printf(1,"%s",{ci})
    -         elsif i=2 then -- ie ^1
    -             printf(1,"%sx",{ci})
    -         else
    -             printf(1,"%sx^%d",{ci,i-1})
    -         end if
    -     end for
    - end procedure
    -
    - procedure main()
    -     for n=1 to 10 do -- (0 to 9 really)
    -         coef(n);
    -         printf(1,"(x-1)^%d = ", n-1);
    -         show(n);
    -         puts(1,'\n');
    -     end for
    -
    -     puts(1,"\nprimes (<=53):");
    - --  coef(2); -- (needed to reset c, if we want to avoid saying 1 is prime...)
    -     c[2] = 1 -- (this manages "", which is all that call did anyway...)
    -     for n = 2 to 53 do
    -         if is_aks_prime(n) then
    -             printf(1," %d", n);
    -         end if
    -     end for
    -     puts(1,'\n');
    -     if getc(0) then end if
    - end procedure
    - main()
    -
    - function abundantOdd(integer n, done, lim, bool printAll)
    -     while done<lim do
    -         atom tot = sum(factors(n,-1))
    -         if tot>n then
    -             done += 1
    -             if printAll or done=lim then
    -                 string ln = iff(printAll?sprintf("%2d. ",done):"")
    -                 printf(1,"%s%,6d (proper sum:%,d)\n",{ln,n,tot})
    -             end if
    -         end if
    -         n += 2
    -     end while
    -     printf(1,"\n")
    -     return n
    - end function
    - printf(1,"The first 25 abundant odd numbers are:\n")
    - integer n = abundantOdd(1, 0, 25, true)
    - printf(1,"The one thousandth abundant odd number is:")
    - {} = abundantOdd(n, 25, 1000, false)
    - printf(1,"The first abundant odd number above one billion is:")
    - {} = abundantOdd(1e9+1, 0, 1, false)
    - iterator
        Walker.zero().tweak(fcn(rn){
           n:=rn.value;
           while(True){
    -	 sum:=0;
    -	 foreach d in ([3.. n.toFloat().sqrt().toInt(), 2]){
    -	    if( (y:=n/d) *d != n) continue;
    -	    sum += ((y==d) and y or y+d)
    -	 }
    -	 if(sum>n){ rn.set(n+2); return(n) }
    -	 n+=2;
    +     sum:=0;
    +     foreach d in ([3.. n.toFloat().sqrt().toInt(), 2]){
    +        if( (y:=n/d) *d != n) continue;
    +        sum += ((y==d) and y or y+d)
    +     }
    +     if(sum>n){ rn.set(n+2); return(n) }
    +     n+=2;
           }
        }.fp(Ref(startAt.isOdd and startAt or startAt+1)))
     }
    diff --git a/Task/Accumulator-factory/Ada/accumulator-factory-1.ada b/Task/Accumulator-factory/Ada/accumulator-factory-1.adb
    similarity index 100%
    rename from Task/Accumulator-factory/Ada/accumulator-factory-1.ada
    rename to Task/Accumulator-factory/Ada/accumulator-factory-1.adb
    diff --git a/Task/Accumulator-factory/Ada/accumulator-factory-2.ada b/Task/Accumulator-factory/Ada/accumulator-factory-2.adb
    similarity index 100%
    rename from Task/Accumulator-factory/Ada/accumulator-factory-2.ada
    rename to Task/Accumulator-factory/Ada/accumulator-factory-2.adb
    diff --git a/Task/Accumulator-factory/Ada/accumulator-factory-3.ada b/Task/Accumulator-factory/Ada/accumulator-factory-3.adb
    similarity index 100%
    rename from Task/Accumulator-factory/Ada/accumulator-factory-3.ada
    rename to Task/Accumulator-factory/Ada/accumulator-factory-3.adb
    diff --git a/Task/Accumulator-factory/Ballerina/accumulator-factory.ballerina b/Task/Accumulator-factory/Ballerina/accumulator-factory.ballerina
    new file mode 100644
    index 0000000000..a8f8252dea
    --- /dev/null
    +++ b/Task/Accumulator-factory/Ballerina/accumulator-factory.ballerina
    @@ -0,0 +1,38 @@
    +import ballerina/io;
    +
    +type numeric int|float|decimal;
    +
    +function accumulator(numeric acc) returns (function(numeric) returns numeric) {
    +    numeric sum = acc;
    +    return function(numeric n) returns numeric {
    +        numeric sum2 = sum;
    +        if sum2 is int && n is int {
    +            sum2 += n;
    +        } else if sum2 is float && n is float {
    +            sum2 += n;
    +        } else if sum2 is decimal && n is decimal {
    +            sum2 += n;
    +        } else if sum2 is int && n is float {
    +            sum2 = sum2 + n;
    +        } else if sum2 is int && n is decimal {
    +            sum2 = sum2 + n;
    +        } else if sum2 is float && n is int {
    +            sum2 += n;
    +        } else if sum2 is float && n is decimal {
    +            sum2 = sum2 + n;
    +        } else if sum2 is decimal && n is int {
    +            sum2 += n;
    +        } else if sum2 is decimal && n is float {
    +            sum2 += n;
    +        }
    +        sum = sum2;
    +        return sum;
    +   };
    +}
    +
    +public function main() {
    +    var x = accumulator(1);
    +    _ = x(5);
    +    _ = accumulator(2);
    +    io:println(x(2.3));
    +}
    diff --git a/Task/Accumulator-factory/Crystal/accumulator-factory.crystal b/Task/Accumulator-factory/Crystal/accumulator-factory.cr
    similarity index 100%
    rename from Task/Accumulator-factory/Crystal/accumulator-factory.crystal
    rename to Task/Accumulator-factory/Crystal/accumulator-factory.cr
    diff --git a/Task/Accumulator-factory/Delphi/accumulator-factory.delphi b/Task/Accumulator-factory/Delphi/accumulator-factory.pas
    similarity index 100%
    rename from Task/Accumulator-factory/Delphi/accumulator-factory.delphi
    rename to Task/Accumulator-factory/Delphi/accumulator-factory.pas
    diff --git a/Task/Accumulator-factory/EMal/accumulator-factory.emal b/Task/Accumulator-factory/EMal/accumulator-factory.emal
    index 7072fb070e..b0da805059 100644
    --- a/Task/Accumulator-factory/EMal/accumulator-factory.emal
    +++ b/Task/Accumulator-factory/EMal/accumulator-factory.emal
    @@ -7,9 +7,9 @@ in Org:RosettaCode
      |^
     type Number allows int, real
     type AccumulatorUsingNumber
    -fun foo = fun by Number n
    -  fun g = Number by Number i
    -    return n += i
    +fun foo ← fun by Number n
    +  fun g ← Number by Number i
    +    return n +← i
       end
       return g
     end
    @@ -17,16 +17,16 @@ type AccumulatorUsingVar
     ^|EMal has an universal supertype Variable (var) that can be used.
      |Some manual type checks are required.
      |^
    -fun checkType = void by var value
    -  if generic!value != real and generic!value != int
    -    Event.error(1, "Only real and int values can be used").raise()
    +fun checkType ← void by var value
    +  if generic!value ≠ real and generic!value ≠ int
    +    error(1, "Only real and int values can be used")
       end
     end
    -fun foo = fun by var n
    +fun foo ← fun by var n
       checkType(n)
    -  fun g = var by var i
    +  fun g ← var by var i
         checkType(i)
    -    return n += i
    +    return n +← i
       end
       return g
     end
    @@ -35,15 +35,15 @@ type Main
      |it is time to create a list holding both data types.
      |We iterate over the solutions in order to test them.
      |^
    -List solutions = generic[AccumulatorUsingNumber, AccumulatorUsingVar]
    -for int i = 0; i < solutions.length; ++i
    -  generic solution = solutions[i]
    -  writeLine("=== solution " + (i + 1) + " ===")
    -  fun x = :solution.foo(1)
    +List solutions ← generic[AccumulatorUsingNumber, AccumulatorUsingVar]
    +for int i ← 0; i < solutions.length; ++i
    +  generic solution ← solutions[i]
    +  writeLine("[ solution " + (i + 1) + " ]")
    +  fun x ← :solution.foo(1)
       x(5)
       :solution.foo(3)
       watch(x(2.3))
    -  fun y = :solution.foo(1)
    +  fun y ← :solution.foo(1)
       y(5)
       :solution.foo(3)
       watch(y(2))
    diff --git a/Task/Accumulator-factory/Elena/accumulator-factory.elena b/Task/Accumulator-factory/Elena/accumulator-factory.elena
    index be112e0585..16e02b3b7b 100644
    --- a/Task/Accumulator-factory/Elena/accumulator-factory.elena
    +++ b/Task/Accumulator-factory/Elena/accumulator-factory.elena
    @@ -1,16 +1,16 @@
     function(acc)
         = (n => acc.append(n));
     
    -accumulator(n)
    +Accumulator(n)
         = function(new Variable(n));
     
    -public program()
    +public Program()
     {
    -    var x := accumulator(1);
    +    var x := Accumulator(1);
     
         x(5);
     
    -    var y := accumulator(3);
    +    var y := Accumulator(3);
     
    -    console.write(x(2.3r))
    +    Console.write(x(2.3r))
     }
    diff --git a/Task/Accumulator-factory/Elixir/accumulator-factory-1.elixir b/Task/Accumulator-factory/Elixir/accumulator-factory-1.ex
    similarity index 100%
    rename from Task/Accumulator-factory/Elixir/accumulator-factory-1.elixir
    rename to Task/Accumulator-factory/Elixir/accumulator-factory-1.ex
    diff --git a/Task/Accumulator-factory/Elixir/accumulator-factory-2.elixir b/Task/Accumulator-factory/Elixir/accumulator-factory-2.ex
    similarity index 100%
    rename from Task/Accumulator-factory/Elixir/accumulator-factory-2.elixir
    rename to Task/Accumulator-factory/Elixir/accumulator-factory-2.ex
    diff --git a/Task/Accumulator-factory/Julia/accumulator-factory.julia b/Task/Accumulator-factory/Julia/accumulator-factory.jl
    similarity index 100%
    rename from Task/Accumulator-factory/Julia/accumulator-factory.julia
    rename to Task/Accumulator-factory/Julia/accumulator-factory.jl
    diff --git a/Task/Accumulator-factory/Kotlin/accumulator-factory.kotlin b/Task/Accumulator-factory/Kotlin/accumulator-factory.kts
    similarity index 100%
    rename from Task/Accumulator-factory/Kotlin/accumulator-factory.kotlin
    rename to Task/Accumulator-factory/Kotlin/accumulator-factory.kts
    diff --git a/Task/Accumulator-factory/M2000-Interpreter/accumulator-factory.m2000 b/Task/Accumulator-factory/M2000-Interpreter/accumulator-factory.m2000
    index 38c3698bc9..b9bdf82db9 100644
    --- a/Task/Accumulator-factory/M2000-Interpreter/accumulator-factory.m2000
    +++ b/Task/Accumulator-factory/M2000-Interpreter/accumulator-factory.m2000
    @@ -1,32 +1,33 @@
    -\\ M2000 Interpreter
    -\\ accumulator factory
    -foo=lambda acc=0 (n as double=0) -> {
    -      \\ interpreter place this: read n as double=0 as first line of lambda function
    -      if n=0 then =acc : exit
    -      acc+=n
    -      \\ acc passed as a closuer to lambda (a copy of acc in the result lambda function)
    -      =lambda acc -> {
    -            ' if stack of values is empty then return a copy of acc
    -            if empty then =acc : exit
    -            read x
    -            \\ x has no type here, can be any numeric type (also can be an object too)
    -            \\ accumulator is double, and is a closure (a copy of acc in foo)
    -            acc+=x
    -            \\ any variable in M2000 hold  first type
    -            \\ if x is an object then we get error, except if object use this operator
    -            x=acc
    -            \\ so we return x type
    -            =x
    -      }
    +Module CheckIt {
    +    Def VarType(n)=Type$(n)
    +    foo=lambda  (acc) -> {
    +          =lambda acc -> {
    +                if empty then =acc : exit
    +                read x
    +                acc+=x
    +                =acc
    +          }
    +    }
    +    Double a=1
    +    x = foo(a)
    +    call void x(5)  ' 	Without Void a non zero value count as Error.
    +    call  foo(3)
    +    print VarType(x())="Double", x(2.3)=8.3 ' Double literal
    +    Single m=1
    +    z=foo(m)
    +    long L=5
    +    ? VarType(z(L))="Single", z(2.3)=8.3~ ' Single literal
    +    Currency c=1
    +    zc=foo(c)
    +    ? VarType(zc(5))="Currency", zc(2.3)=8.3#  ' Currency literal
    +    Decimal d=1
    +    zd=foo(d)
    +    ? VarType(zd(5))="Decimal", zd(2.3)=8.3@  ' Decimal literal
    +    Date dt=1
    +    zdt=foo(dt)
    +    ? VarType(zdt(5))="Date", zdt(2.3)=8.3ud  ' Date literal
    +    Long Long LL=1
    +    zdt=foo(LL)
    +    ? VarType(zdt(5))="Long Long", zdt(2.3)=8&& ' Long Long literal
     }
    -x=foo(1&)   ' 1& is long type (32bit)
    -call void x(5) ' 5 is double type (the default type for M2000)
    -call void foo(3#)   ' void tell to interpreter to throw result, 3# is Currency type
    -print x(2.3@) ' print 8.3,   2.3@ is Decimal type
    -print foo()=4 ' print true
    -def ExpType$(z)=type$(z)
    -print ExpType$(foo())="Double"
    -print ExpType$(x(0&))="Long"
    -print ExpType$(x(0@))="Decimal"
    -print ExpType$(x())="Double"
    -print ExpType$(foo(20))="lambda"
    +CheckIt
    diff --git a/Task/Accumulator-factory/OCaml/accumulator-factory.ocaml b/Task/Accumulator-factory/OCaml/accumulator-factory.ml
    similarity index 100%
    rename from Task/Accumulator-factory/OCaml/accumulator-factory.ocaml
    rename to Task/Accumulator-factory/OCaml/accumulator-factory.ml
    diff --git a/Task/Accumulator-factory/PascalABC.NET/accumulator-factory.pas b/Task/Accumulator-factory/PascalABC.NET/accumulator-factory.pas
    new file mode 100644
    index 0000000000..86c0cbcc7d
    --- /dev/null
    +++ b/Task/Accumulator-factory/PascalABC.NET/accumulator-factory.pas
    @@ -0,0 +1,12 @@
    +function foo(n: real): real -> real :=
    +  i -> begin
    +    n += i;
    +    Result := n;
    +  end;
    +
    +begin
    +  var x := foo(1);
    +  x(5);
    +  foo(3);
    +  print(x(2.3));
    +end.
    diff --git a/Task/Accumulator-factory/Pluto/accumulator-factory.pluto b/Task/Accumulator-factory/Pluto/accumulator-factory.pluto
    new file mode 100644
    index 0000000000..5baa4348fd
    --- /dev/null
    +++ b/Task/Accumulator-factory/Pluto/accumulator-factory.pluto
    @@ -0,0 +1,11 @@
    +local function accumulator(acc)
    +    return |n| -> do
    +        acc += n
    +        return acc
    +    end
    +end
    +
    +local x = accumulator(1)
    +x(5)
    +accumulator(3)
    +print(x(2.3))
    diff --git a/Task/Accumulator-factory/PowerShell/accumulator-factory-1.psh b/Task/Accumulator-factory/PowerShell/accumulator-factory-1.ps1
    similarity index 100%
    rename from Task/Accumulator-factory/PowerShell/accumulator-factory-1.psh
    rename to Task/Accumulator-factory/PowerShell/accumulator-factory-1.ps1
    diff --git a/Task/Accumulator-factory/PowerShell/accumulator-factory-2.psh b/Task/Accumulator-factory/PowerShell/accumulator-factory-2.ps1
    similarity index 100%
    rename from Task/Accumulator-factory/PowerShell/accumulator-factory-2.psh
    rename to Task/Accumulator-factory/PowerShell/accumulator-factory-2.ps1
    diff --git a/Task/Accumulator-factory/REBOL/accumulator-factory.rebol b/Task/Accumulator-factory/REBOL/accumulator-factory.rebol
    deleted file mode 100644
    index 35b5392daf..0000000000
    --- a/Task/Accumulator-factory/REBOL/accumulator-factory.rebol
    +++ /dev/null
    @@ -1,8 +0,0 @@
    -make-acc-gen: func [start-val] [
    -    use [state] [
    -        state: start-val
    -        func [value] [
    -            state: state + value
    -        ]
    -    ]
    -]
    diff --git a/Task/Accumulator-factory/Rebol/accumulator-factory-1.rebol b/Task/Accumulator-factory/Rebol/accumulator-factory-1.rebol
    new file mode 100644
    index 0000000000..0738505b60
    --- /dev/null
    +++ b/Task/Accumulator-factory/Rebol/accumulator-factory-1.rebol
    @@ -0,0 +1,11 @@
    +make-acc-gen: func [start-val] [
    +    use [state] [
    +        state: start-val
    +        func [value] [
    +            state: state + value
    +        ]
    +    ]
    +]
    +gen: make-acc-gen 1
    +print gen 5   ;== 6
    +print gen 2.3 ;== 8.3
    diff --git a/Task/Accumulator-factory/Rebol/accumulator-factory-2.rebol b/Task/Accumulator-factory/Rebol/accumulator-factory-2.rebol
    new file mode 100644
    index 0000000000..02468d5450
    --- /dev/null
    +++ b/Task/Accumulator-factory/Rebol/accumulator-factory-2.rebol
    @@ -0,0 +1,25 @@
    +;; Define a generator function 'gen' with an optional refinement '/init'
    +;; - 'value' is a required number passed to the function
    +;; - '/init' is an optional refinement for initialization
    +gen: function/with [value [number!] /init] [
    +
    +    ;; If '/init' refinement is used, initialize state and exit immediately
    +    if init [
    +        state: value    ;; Set the initial state to the provided value
    +        exit            ;; Exit, so nothing else in the function is run
    +    ]
    +
    +    ;; If not initializing, add 'value' to 'state'
    +    state: state + value
    +
    +    ;; The function returns the new state each call
    +][state: 0]             ;; 'state' is a local variable, initialized once per definition (persistent closure)
    +
    +;; Initialize the 'state' value of gen to 1 by calling it with '/init'
    +gen/init 1
    +
    +;; Call gen with 5: Adds 5 to state and prints the result (should print 6)
    +print gen 5
    +
    +;; Call gen with 2.3: Adds 2.3 to state and prints the result (should print 8.3)
    +print gen 2.3
    diff --git a/Task/Accumulator-factory/Red/accumulator-factory.red b/Task/Accumulator-factory/Red/accumulator-factory.red
    new file mode 100644
    index 0000000000..9bceca4447
    --- /dev/null
    +++ b/Task/Accumulator-factory/Red/accumulator-factory.red
    @@ -0,0 +1,15 @@
    +Red [ "Accumulator factory - hinjolicious" ]
    +
    +; just a helper func to display informative output
    +demo: function [s b] [print ["^/==" s "==^/^/" mold/only b "^/>>"] do b]
    +
    +demo "Accumulator" [
    +foo: function [init] [
    +	acc: init
    +	closure [val][acc: acc + val]
    +]
    +x: foo 1
    +print x 5 ; 6
    +foo 3 ; no effect!
    +print x 2.3 ; 8.3
    +]
    diff --git a/Task/Accumulator-factory/Rust/accumulator-factory-1.rust b/Task/Accumulator-factory/Rust/accumulator-factory-1.rs
    similarity index 100%
    rename from Task/Accumulator-factory/Rust/accumulator-factory-1.rust
    rename to Task/Accumulator-factory/Rust/accumulator-factory-1.rs
    diff --git a/Task/Accumulator-factory/Rust/accumulator-factory-2.rust b/Task/Accumulator-factory/Rust/accumulator-factory-2.rs
    similarity index 100%
    rename from Task/Accumulator-factory/Rust/accumulator-factory-2.rust
    rename to Task/Accumulator-factory/Rust/accumulator-factory-2.rs
    diff --git a/Task/Accumulator-factory/Scheme/accumulator-factory.ss b/Task/Accumulator-factory/Scheme/accumulator-factory.scm
    similarity index 100%
    rename from Task/Accumulator-factory/Scheme/accumulator-factory.ss
    rename to Task/Accumulator-factory/Scheme/accumulator-factory.scm
    diff --git a/Task/Accumulator-factory/V-(Vlang)/accumulator-factory.v b/Task/Accumulator-factory/V-(Vlang)/accumulator-factory.v
    new file mode 100644
    index 0000000000..c799934393
    --- /dev/null
    +++ b/Task/Accumulator-factory/V-(Vlang)/accumulator-factory.v
    @@ -0,0 +1,23 @@
    +struct Generator {
    +	mut:
    +    a_n []f64
    +}
    +
    +fn (mut gen Generator) generator(ir f64) fn (f64) f64 {
    +    gen.a_n << ir
    +    id := gen.a_n.len - 1
    +    return fn (mut gen Generator, id int) fn (f64) f64 {
    +        return fn [mut gen, id] (d f64) f64 {
    +            gen.a_n[id] += d
    +            return gen.a_n[id]
    +        }
    +    }(mut gen, id)
    +}
    +
    +fn main() {
    +    mut o_generator := Generator{}
    +    accumulator := o_generator.generator(1)
    +    println(accumulator(5))
    +    o_generator.generator(3)
    +    println(accumulator(2.3))
    +}
    diff --git a/Task/Accumulator-factory/VBScript/accumulator-factory-1.vb b/Task/Accumulator-factory/VBScript/accumulator-factory-1.vbs
    similarity index 100%
    rename from Task/Accumulator-factory/VBScript/accumulator-factory-1.vb
    rename to Task/Accumulator-factory/VBScript/accumulator-factory-1.vbs
    diff --git a/Task/Accumulator-factory/VBScript/accumulator-factory-2.vb b/Task/Accumulator-factory/VBScript/accumulator-factory-2.vbs
    similarity index 100%
    rename from Task/Accumulator-factory/VBScript/accumulator-factory-2.vb
    rename to Task/Accumulator-factory/VBScript/accumulator-factory-2.vbs
    diff --git a/Task/Achilles-numbers/Ada/achilles-numbers.adb b/Task/Achilles-numbers/Ada/achilles-numbers.adb
    new file mode 100644
    index 0000000000..054f448da3
    --- /dev/null
    +++ b/Task/Achilles-numbers/Ada/achilles-numbers.adb
    @@ -0,0 +1,205 @@
    +pragma Ada_2022;
    +
    +with Ada.Text_IO;
    +with Ada.Numerics; use Ada.Numerics;
    +with Ada.Numerics.Long_Elementary_Functions;
    +use  Ada.Numerics.Long_Elementary_Functions;
    +with Ada.Strings; use Ada.Strings;
    +with Ada.Strings.Fixed; use Ada.Strings.Fixed;
    +with Prime_Numbers;
    +
    +procedure Achilles_Numbers is
    +
    +   package Long_Integer_Prime_Numbers is new Prime_Numbers
    +     (Integer, 0, 1, 2);
    +   use Long_Integer_Prime_Numbers;
    +
    +   --  A powerful number N is such that for every primer factor P of it
    +   --  P^2 also divides N
    +   --  Is_Powerful function decomposes the given number N in its prime factors
    +   --  and then it checks if each factor squared is a divisor of N
    +   function Is_Powerful (Number : Natural) return Boolean is
    +      List : constant Number_List  := Decompose (Integer (Number));
    +   begin
    +      for Index in List'Range loop
    +         declare
    +            N : constant Long_Long_Integer := Long_Long_Integer (Number);
    +            F : constant Long_Long_Integer := Long_Long_Integer (List (Index));
    +         begin
    +            if N mod (F * F) /= 0 then
    +               return False;
    +            end if;
    +         end;
    +      end loop;
    +
    +      return True;
    +   end Is_Powerful;
    +
    +   --  The Is_Power  function checks if a given number N can be written
    +   --  as a power of two integers that are > 1
    +   --  It makes use of the mathematical expression N = A^B
    +   --  taking Log(N) = Log (A^B) equals to B = Log (N) / Log (A)
    +   --  where the solutions are when B is an integer > 1
    +   function Is_Power (N : Integer) return Boolean is
    +
    +      function Is_Almost_Equal (A : Long_Float;
    +                                B : Long_Float) return Boolean is
    +         Epsilon : constant := 0.000_000_000_000_001;
    +      begin
    +         if abs (A - B) < Epsilon then
    +            return True;
    +         else
    +            return False;
    +         end if;
    +      end Is_Almost_Equal;
    +
    +      A       : Integer := 2;
    +      B       : Long_Float;
    +      Log_Of_N : constant Long_Float := Log (Long_Float (N), 2.0);
    +   begin
    +      if N = 1 then
    +         return True;
    +      end if;
    +
    +      while True loop
    +         B := Log_Of_N / Log (Long_Float (A), 2.0);
    +
    +         if Is_Almost_Equal (B, Long_Float (Integer (B)))
    +           and then Integer (B) > 1
    +         then
    +            return True;
    +         end if;
    +
    +         exit when A * A > N;
    +         A := @ + 1;
    +      end loop;
    +
    +      return False;
    +
    +   end Is_Power;
    +
    +   --  An Achilles number is a powerful number that can't be expressed
    +   --  as a power
    +   function Is_Achilles (N : Integer) return Boolean is
    +   begin
    +      if Is_Powerful (N) then
    +         if Is_Power (N) = False then
    +            return True;
    +         end if;
    +      end if;
    +
    +      return False;
    +   end Is_Achilles;
    +
    +   --  Calculates the Euler totient of a number
    +   function Totient (N : Integer) return Integer is
    +      Tot : Integer := N;
    +      I   : Integer;
    +      N2  : Integer := N;
    +   begin
    +      I := 2;
    +      while I * I <= N2 loop
    +         if N2 mod I = 0 then
    +            while N2 mod I = 0 loop
    +               N2 := N2 / I;
    +            end loop;
    +            Tot := Tot - Tot / I;
    +         end if;
    +
    +         if I = 2 then
    +            I := 1;
    +         end if;
    +         I := I + 2;
    +      end loop;
    +
    +      if N2 > 1 then
    +         Tot := Tot - Tot / N2;
    +      end if;
    +
    +      return Tot;
    +   end Totient;
    +
    +   --  A Strong Achilles number is an Achilles number whose Euler Totient
    +   --  is also an Achilles number
    +   function Is_Strong_Achilles (N : Integer) return Boolean is
    +   begin
    +      if Is_Achilles (N) then
    +         if Is_Achilles (Totient (N)) then
    +            return True;
    +         end if;
    +      end if;
    +
    +      return False;
    +   end Is_Strong_Achilles;
    +
    +   --  Counts the digits in a number by taking the string from
    +   --  its 'Image attribute, trimming it and counting the characters
    +   function Count_Digits (N : Integer) return Natural is
    +      Integer_Str : constant String := Trim (N'Image, Both);
    +   begin
    +      return Integer_Str'Length;
    +   end Count_Digits;
    +
    +begin
    +   --  Find the first 50 Achilles numbers
    +   declare
    +      N : Integer := 1;
    +      Count : Integer := 1;
    +   begin
    +      Ada.Text_IO.Put_Line ("First 50 Achilles numbers:");
    +
    +      while Count <= 50 loop
    +
    +         if Is_Achilles (N) then
    +            Count := @ + 1;
    +            Ada.Text_IO.Put (N'Image & " ");
    +         end if;
    +
    +         N := @ + 1;
    +      end loop;
    +
    +      Ada.Text_IO.New_Line;
    +   end;
    +
    +   --  Find the first 20 Strong Achilles numbers
    +   declare
    +      N : Integer := 1;
    +      Count : Integer := 1;
    +   begin
    +      Ada.Text_IO.Put_Line ("First 20 Strong Achilles numbers:");
    +
    +      while Count <= 20 loop
    +
    +         if Is_Strong_Achilles (N) then
    +            Count := @ + 1;
    +            Ada.Text_IO.Put (N'Image & " ");
    +         end if;
    +
    +         N := @ + 1;
    +      end loop;
    +
    +      Ada.Text_IO.New_Line;
    +   end;
    +
    +   --  Count numbers with digits
    +   declare
    +      Counts : array (2 .. 6) of Natural := [others => 0];
    +      N      : Integer := 1;
    +   begin
    +      Ada.Text_IO.Put_Line ("Number of Achilles numbers with:");
    +
    +      while Count_Digits (N) <= Counts'Last loop
    +
    +         --  Ada.Text_IO.Put_Line ("Testing: " & N'Image);
    +
    +         if Is_Achilles (N) then
    +            Counts (Count_Digits (N)) := @ + 1;
    +         end if;
    +         N := @ + 1;
    +      end loop;
    +
    +      for I in Counts'Range loop
    +         Ada.Text_IO.Put_Line (I'Image & " digits: " & Counts (I)'Image);
    +      end loop;
    +   end;
    +end Achilles_Numbers;
    diff --git a/Task/Achilles-numbers/Arturo/achilles-numbers.arturo b/Task/Achilles-numbers/Arturo/achilles-numbers.arturo
    new file mode 100644
    index 0000000000..939ef41b2a
    --- /dev/null
    +++ b/Task/Achilles-numbers/Arturo/achilles-numbers.arturo
    @@ -0,0 +1,36 @@
    +prettyPrint: function [res][
    +    res | split.every: 10
    +        | loop => [print map & 'x -> pad to :string x 7]
    +]
    +
    +achilles?: function [n][
    +    exps: values tally factors.prime n
    +    and? -> not? some? exps => one?
    +         -> 1 = fold exps [a b] -> gcd @[a b]
    +]
    +
    +phi: function [n][
    +    pf: tally factors.prime n
    +    fold.seed:1 keys pf [res pr][
    +        ipr: to :integer pr
    +        res * (ipr - 1) * ipr ^ dec to :integer pf\[ipr]
    +    ]
    +]
    +
    +n: 50
    +print ["First" n "Achilles numbers:"]
    +2..∞ | select.first: n => achilles?
    +     | prettyPrint
    +
    +print ""
    +print ["First" n "strong Achilles numbers:"]
    +2..∞ | select.first: n 'x -> and? [achilles? x][achilles? phi x]
    +     | prettyPrint
    +
    +print ""
    +counts: 2..1000000 | select => achilles?
    +                   | map => [size digits &]
    +                   | tally
    +
    +loop counts [k v]->
    +    print [k "digits:" v]
    diff --git a/Task/Achilles-numbers/Ballerina/achilles-numbers.ballerina b/Task/Achilles-numbers/Ballerina/achilles-numbers.ballerina
    new file mode 100644
    index 0000000000..ff31e0dfeb
    --- /dev/null
    +++ b/Task/Achilles-numbers/Ballerina/achilles-numbers.ballerina
    @@ -0,0 +1,92 @@
    +import ballerina/io;
    +
    +map pps = {};
    +
    +function getPerfectPowers(int maxExp) {
    +    int upper  = 10.0.pow(maxExp);
    +    int upper2 = 10.0.pow(maxExp).sqrt().floor();
    +    foreach int i in 2...upper2 {
    +        int p = i;
    +        while true {
    +            if p > int:MAX_VALUE / i { break; }
    +            p *= i;
    +            if p >= upper { break; }
    +            pps[p.toString()] = 1;
    +        }
    +    }
    +}
    +
    +function getAchilles(int minExp, int maxExp) returns map {
    +    int lower  = 10.0.pow(minExp);
    +    int upper  = 10.0.pow(maxExp);
    +    int upper2 = 10.0.pow(maxExp).cbrt().floor();
    +    int upper3 = 10.0.pow(maxExp).sqrt().floor();
    +    map achilles = {};
    +    foreach int b in 1...upper2 {
    +        int b3 = b * b * b;
    +        foreach int a in 1...upper3 {
    +            int p = b3 * a * a;
    +            if p >= upper { break; }
    +            if p >= lower {
    +                string ps = p.toString();
    +                if !pps.hasKey(ps) {
    +                    achilles[ps] = 1;
    +                }
    +            }
    +        }
    +    }
    +    return achilles;
    +}
    +
    +function totient(int m) returns int {
    +    if m < 1 { return 0; }
    +    int tot = m;
    +    int n = m;
    +    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 function main() returns error? {
    +    final int maxDigits = 14;
    +    getPerfectPowers(maxDigits);
    +    map achillesSet = getAchilles(1, 5); // enough for first 2 parts
    +    int[] achilles = achillesSet.keys().map(s => check int:fromString(s)).sort();
    +    io:println("First 50 Achilles numbers:");
    +    foreach int i in 0..<50 {
    +        string s = achilles[i].toString().padStart(4);
    +        io:print(s, " ");
    +        if (i + 1) % 10 == 0 { io:println(); }
    +    }
    +    io:println("\nFirst 30 strong Achilles numbers:");
    +    int[] strongAchilles = [];
    +    int count = 0;
    +    int n = 0;
    +    while count < 30 {
    +        int tot = totient(achilles[n]);
    +        if achillesSet.hasKey(tot.toString()) {
    +            strongAchilles.push(achilles[n]);
    +            count += 1;
    +        }
    +        n += 1;
    +    }
    +    foreach int j in 0..<30 {
    +        string t = strongAchilles[j].toString().padStart(5);
    +        io:print(t, " ");
    +        if (j + 1) % 10 == 0 { io:println(); }
    +    }
    +
    +    io:println("\nNumber of Achilles numbers with:");
    +    foreach int d in 2...maxDigits {
    +        int ac = getAchilles(d - 1, d).length();
    +        io:println(d.toString().padStart(2), " digits: ", ac);
    +    }
    +}
    diff --git a/Task/Achilles-numbers/C/achilles-numbers.c b/Task/Achilles-numbers/C/achilles-numbers.c
    new file mode 100644
    index 0000000000..f7ed293f8e
    --- /dev/null
    +++ b/Task/Achilles-numbers/C/achilles-numbers.c
    @@ -0,0 +1,105 @@
    +#include 
    +#include 
    +#include 
    +#include 
    +
    +bool is_prime(int n) {
    +    if (n < 2) return false;
    +    if (n % 2 == 0 && n != 2) return false;
    +    for (int i = 3; i <= sqrt(n); i += 2) {
    +        if (n % i == 0) return false;
    +    }
    +    return true;
    +}
    +
    +int phi(int n) {
    +    int result = n;
    +    for (int p = 2; p * p <= n; p++) {
    +        if (n % p == 0) {
    +            while (n % p == 0) n /= p;
    +            result -= result / p;
    +        }
    +    }
    +    if (n > 1) result -= result / n;
    +    return result;
    +}
    +
    +bool is_powerful(int n) {
    +    int m = n;
    +    for (int p = 2; p * p <= n; p++) {
    +        if (m % p == 0) {
    +            int exp = 0;
    +            while (m % p == 0) {
    +                m /= p;
    +                exp++;
    +            }
    +            if (exp < 2) return false;
    +        }
    +    }
    +    if (m > 1) return false;
    +    return true;
    +}
    +
    +bool is_perfect_power(int n) {
    +    for (int k = 2; k <= log2(n); k++) {
    +        double root = pow(n, 1.0 / k);
    +        int r = round(root);
    +        if (pow(r, k) == n) return true;
    +    }
    +    return false;
    +}
    +
    +bool is_achilles(int n) {
    +    return is_powerful(n) && !is_perfect_power(n);
    +}
    +
    +int main() {
    +    int *achilles = NULL, *strong = NULL;
    +    int a_count = 0, s_count = 0;
    +    int digit_counts[7] = {0};
    +
    +    for (int n = 2; a_count < 50 || s_count < 50; n++) {
    +        if (is_achilles(n)) {
    +            if (a_count < 50){
    +                achilles = realloc(achilles, (a_count+1)*sizeof(int));
    +                achilles[a_count++] = n;
    +            }
    +
    +            int ph = phi(n);
    +            if (is_achilles(ph)) {
    +                if (s_count < 50){
    +                    strong = realloc(strong, (s_count+1)*sizeof(int));
    +                    strong[s_count++] = n;
    +                }
    +            }
    +
    +        }
    +    }
    +
    +    for (int n = 2; n <= 1000000; n++) {
    +        if (is_achilles(n)) {
    +            int digits = floor(log10(n)) + 1;
    +            if (digits >= 2 && digits <= 15) {
    +                digit_counts[digits]++;
    +            }
    +        }
    +    }
    +
    +    printf("First 50 Achilles numbers:\n");
    +    for (int i = 0; i < 50; i++) {
    +        printf("%d ", achilles[i]);
    +    }
    +    printf("\n\n");
    +
    +    printf("First 50 Strong Achilles numbers:\n");
    +    for (int i = 0; i < 50; i++) {
    +        printf("%d ", strong[i]);
    +    }
    +    printf("\n\n");
    +
    +    for (int d = 2; d <= 6; d++) {
    +        printf("Achilles numbers with %d digits: %d\n", d, digit_counts[d]);
    +    }
    +
    +    return 0;
    +}
    diff --git a/Task/Achilles-numbers/COBOL/achilles-numbers.cob b/Task/Achilles-numbers/COBOL/achilles-numbers.cob
    new file mode 100644
    index 0000000000..f5fdc87beb
    --- /dev/null
    +++ b/Task/Achilles-numbers/COBOL/achilles-numbers.cob
    @@ -0,0 +1,257 @@
    +       IDENTIFICATION DIVISION.
    +       PROGRAM-ID. ACHILLES-NUMBERS.
    +
    +       DATA DIVISION.
    +       WORKING-STORAGE SECTION.
    +       01 CONSTANTS.
    +          05 MAX-LIMIT     PIC 9(10) COMP VALUE 100000000.
    +          05 MAX-LIMIT-SQR PIC 9(6) COMP VALUE 10000.
    +          05 MAX-LIMIT-CUB PIC 9(6) COMP VALUE 464.
    +
    +       01 PP-TEMP-DATA.
    +          05 PP-TEMP-COUNT PIC 9(6) COMP VALUE 0.
    +          05 PP-TEMP-TABLE.
    +             10 PP-TEMP OCCURS 1 TO 15000 TIMES DEPENDING ON PP-TEMP-COUNT
    +                            ASCENDING KEY IS PP-TEMP
    +                            PIC 9(10) COMP.
    +
    +       01 PP-FINAL-DATA.
    +          05 PP-COUNT      PIC 9(6) COMP VALUE 0.
    +          05 PP-TABLE.
    +             10 P-POWER    OCCURS 1 TO 15000 TIMES DEPENDING ON PP-COUNT
    +                            ASCENDING KEY IS P-POWER
    +                            INDEXED BY PP-IDX
    +                            PIC 9(10) COMP.
    +
    +       01 ACH-TEMP-DATA.
    +          05 ACH-TEMP-COUNT PIC 9(6) COMP VALUE 0.
    +          05 ACH-TEMP-TABLE.
    +             10 ACH-TEMP   OCCURS 1 TO 35000 TIMES DEPENDING ON ACH-TEMP-COUNT
    +                            ASCENDING KEY IS ACH-TEMP
    +                            PIC 9(10) COMP.
    +
    +       01 ACH-FINAL-DATA.
    +          05 ACH-COUNT     PIC 9(6) COMP VALUE 0.
    +          05 ACH-TABLE.
    +             10 ACHILLES   OCCURS 1 TO 15000 TIMES DEPENDING ON ACH-COUNT
    +                            ASCENDING KEY IS ACHILLES
    +                            INDEXED BY ACH-IDX
    +                            PIC 9(10) COMP.
    +
    +       01 LOOP-VARS.
    +          05 I             PIC 9(6) COMP.
    +          05 B             PIC 9(6) COMP.
    +          05 A             PIC 9(6) COMP.
    +          05 LAST-VAL      PIC 9(10) COMP.
    +
    +       01 CALC-VARS.
    +          05 P             PIC 9(18) COMP.
    +          05 B3            PIC 9(18) COMP.
    +          05 SEARCH-P      PIC 9(10) COMP.
    +
    +       01 TOT-VARS.
    +          05 TOTIENT-IN    PIC 9(10) COMP.
    +          05 TOTIENT-OUT   PIC 9(10) COMP.
    +          05 TOT-I         PIC 9(10) COMP.
    +          05 TOT-N         PIC 9(10) COMP.
    +          05 TOT-Q         PIC 9(10) COMP.
    +          05 TOT-R         PIC 9(10) COMP.
    +          05 SUB-VAL       PIC 9(10) COMP.
    +
    +       01 STRONG-ACH-VARS.
    +          05 FOUND-FLAG    PIC 9 VALUE 0.
    +          05 STRONG-COUNT  PIC 9(4) COMP VALUE 0.
    +          05 STRONG-ACH    OCCURS 30 TIMES PIC 9(10) COMP.
    +
    +       01 REPORT-VARS.
    +          05 DISP-4        PIC ZZZ9.
    +          05 DISP-5        PIC ZZZZ9.
    +          05 DISP-2        PIC Z9.
    +          05 DISP-NUM      PIC Z(9)9.
    +          05 FORMATTED-LINE PIC X(60) VALUE SPACES.
    +          05 LINE-POS      PIC 9(4) COMP VALUE 1.
    +          05 ROW-COUNT     PIC 9(4) COMP VALUE 0.
    +          05 DIGIT-COUNT   PIC 9(10) COMP.
    +          05 D             PIC 9(2) COMP.
    +          05 LOWER-BND     PIC 9(10) COMP.
    +          05 UPPER-BND     PIC 9(10) COMP.
    +
    +       PROCEDURE DIVISION.
    +       MAIN-PARA.
    +           PERFORM GENERATE-PERFECT-POWERS.
    +           PERFORM GENERATE-ACHILLES.
    +           PERFORM PRINT-FIRST-50.
    +           PERFORM PRINT-STRONG-30.
    +           PERFORM PRINT-DIGITS.
    +           STOP RUN.
    +
    +       GENERATE-PERFECT-POWERS.
    +           MOVE 0 TO PP-TEMP-COUNT.
    +           PERFORM VARYING I FROM 2 BY 1 UNTIL I > MAX-LIMIT-SQR
    +               COMPUTE P = I * I
    +               PERFORM UNTIL P >= MAX-LIMIT
    +                   ADD 1 TO PP-TEMP-COUNT
    +                   MOVE P TO PP-TEMP(PP-TEMP-COUNT)
    +                   COMPUTE P = P * I
    +               END-PERFORM
    +           END-PERFORM.
    +
    +           SORT PP-TEMP ON ASCENDING KEY PP-TEMP.
    +
    +           MOVE 0 TO PP-COUNT.
    +           MOVE 0 TO LAST-VAL.
    +           PERFORM VARYING I FROM 1 BY 1 UNTIL I > PP-TEMP-COUNT
    +               IF PP-TEMP(I) NOT = LAST-VAL THEN
    +                   ADD 1 TO PP-COUNT
    +                   MOVE PP-TEMP(I) TO P-POWER(PP-COUNT)
    +                   MOVE PP-TEMP(I) TO LAST-VAL
    +               END-IF
    +           END-PERFORM.
    +
    +       GENERATE-ACHILLES.
    +           MOVE 0 TO ACH-TEMP-COUNT.
    +           PERFORM VARYING B FROM 1 BY 1 UNTIL B > MAX-LIMIT-CUB
    +               COMPUTE B3 = B * B * B
    +               PERFORM VARYING A FROM 1 BY 1 UNTIL A > MAX-LIMIT-SQR
    +                   COMPUTE P = B3 * A * A
    +                   IF P >= MAX-LIMIT THEN
    +                       EXIT PERFORM
    +                   END-IF
    +
    +                   IF P > 1 THEN
    +                       MOVE P TO SEARCH-P
    +                       MOVE 0 TO FOUND-FLAG
    +                       SEARCH ALL P-POWER
    +                           AT END
    +                               MOVE 0 TO FOUND-FLAG
    +                           WHEN P-POWER(PP-IDX) = SEARCH-P
    +                               MOVE 1 TO FOUND-FLAG
    +                       END-SEARCH
    +
    +                       IF FOUND-FLAG = 0 THEN
    +                           ADD 1 TO ACH-TEMP-COUNT
    +                           MOVE P TO ACH-TEMP(ACH-TEMP-COUNT)
    +                       END-IF
    +                   END-IF
    +               END-PERFORM
    +           END-PERFORM.
    +
    +           SORT ACH-TEMP ON ASCENDING KEY ACH-TEMP.
    +
    +           MOVE 0 TO ACH-COUNT.
    +           MOVE 0 TO LAST-VAL.
    +           PERFORM VARYING I FROM 1 BY 1 UNTIL I > ACH-TEMP-COUNT
    +               IF ACH-TEMP(I) NOT = LAST-VAL THEN
    +                   ADD 1 TO ACH-COUNT
    +                   MOVE ACH-TEMP(I) TO ACHILLES(ACH-COUNT)
    +                   MOVE ACH-TEMP(I) TO LAST-VAL
    +               END-IF
    +           END-PERFORM.
    +
    +       CALC-TOTIENT.
    +           MOVE TOTIENT-IN TO TOT-N
    +           MOVE TOTIENT-IN TO TOTIENT-OUT
    +           MOVE 2 TO TOT-I
    +           PERFORM UNTIL TOT-I * TOT-I > TOT-N
    +               DIVIDE TOT-N BY TOT-I GIVING TOT-Q REMAINDER TOT-R
    +               IF TOT-R = 0 THEN
    +                   PERFORM UNTIL TOT-R NOT = 0
    +                       DIVIDE TOT-N BY TOT-I GIVING TOT-Q REMAINDER TOT-R
    +                       IF TOT-R = 0 THEN
    +                           MOVE TOT-Q TO TOT-N
    +                       END-IF
    +                   END-PERFORM
    +                   DIVIDE TOTIENT-OUT BY TOT-I GIVING SUB-VAL
    +                   SUBTRACT SUB-VAL FROM TOTIENT-OUT
    +               END-IF
    +               IF TOT-I = 2 THEN
    +                   MOVE 1 TO TOT-I
    +               END-IF
    +               ADD 2 TO TOT-I
    +           END-PERFORM.
    +           IF TOT-N > 1 THEN
    +               DIVIDE TOTIENT-OUT BY TOT-N GIVING SUB-VAL
    +               SUBTRACT SUB-VAL FROM TOTIENT-OUT
    +           END-IF.
    +
    +       PRINT-FIRST-50.
    +           DISPLAY "First 50 Achilles numbers:".
    +           MOVE SPACES TO FORMATTED-LINE.
    +           MOVE 1 TO LINE-POS.
    +           MOVE 0 TO ROW-COUNT.
    +           PERFORM VARYING I FROM 1 BY 1 UNTIL I > 50
    +               MOVE ACHILLES(I) TO DISP-4
    +               STRING DISP-4 " " DELIMITED BY SIZE
    +                      INTO FORMATTED-LINE WITH POINTER LINE-POS
    +               ADD 1 TO ROW-COUNT
    +               IF ROW-COUNT = 10 THEN
    +                   DISPLAY FORMATTED-LINE(1:LINE-POS - 1)
    +                   MOVE SPACES TO FORMATTED-LINE
    +                   MOVE 1 TO LINE-POS
    +                   MOVE 0 TO ROW-COUNT
    +               END-IF
    +           END-PERFORM.
    +
    +       PRINT-STRONG-30.
    +           DISPLAY " ".
    +           DISPLAY "First 30 strong Achilles numbers:".
    +           MOVE 0 TO STRONG-COUNT.
    +           PERFORM VARYING I FROM 1 BY 1 UNTIL STRONG-COUNT >= 30 OR I > ACH-COUNT
    +               MOVE ACHILLES(I) TO TOTIENT-IN
    +               PERFORM CALC-TOTIENT
    +
    +               MOVE TOTIENT-OUT TO SEARCH-P
    +               MOVE 0 TO FOUND-FLAG
    +               SEARCH ALL ACHILLES
    +                   AT END
    +                       MOVE 0 TO FOUND-FLAG
    +                   WHEN ACHILLES(ACH-IDX) = SEARCH-P
    +                       MOVE 1 TO FOUND-FLAG
    +               END-SEARCH
    +
    +               IF FOUND-FLAG = 1 THEN
    +                   ADD 1 TO STRONG-COUNT
    +                   MOVE ACHILLES(I) TO STRONG-ACH(STRONG-COUNT)
    +               END-IF
    +           END-PERFORM.
    +
    +           MOVE SPACES TO FORMATTED-LINE.
    +           MOVE 1 TO LINE-POS.
    +           MOVE 0 TO ROW-COUNT.
    +           PERFORM VARYING I FROM 1 BY 1 UNTIL I > 30
    +               MOVE STRONG-ACH(I) TO DISP-5
    +               STRING DISP-5 " " DELIMITED BY SIZE
    +                      INTO FORMATTED-LINE WITH POINTER LINE-POS
    +               ADD 1 TO ROW-COUNT
    +               IF ROW-COUNT = 10 THEN
    +                   DISPLAY FORMATTED-LINE(1:LINE-POS - 1)
    +                   MOVE SPACES TO FORMATTED-LINE
    +                   MOVE 1 TO LINE-POS
    +                   MOVE 0 TO ROW-COUNT
    +               END-IF
    +           END-PERFORM.
    +
    +       PRINT-DIGITS.
    +           DISPLAY " ".
    +           DISPLAY "Number of Achilles numbers with:".
    +           MOVE 10 TO LOWER-BND.
    +           COMPUTE UPPER-BND = 100.
    +           PERFORM VARYING D FROM 2 BY 1 UNTIL D > 8
    +               MOVE 0 TO DIGIT-COUNT
    +               PERFORM VARYING I FROM 1 BY 1 UNTIL I > ACH-COUNT
    +                   IF ACHILLES(I) >= UPPER-BND THEN
    +                       EXIT PERFORM
    +                   END-IF
    +                   IF ACHILLES(I) >= LOWER-BND THEN
    +                       ADD 1 TO DIGIT-COUNT
    +                   END-IF
    +               END-PERFORM
    +
    +               MOVE D TO DISP-2
    +               MOVE DIGIT-COUNT TO DISP-NUM
    +
    +               DISPLAY DISP-2 " digits: " FUNCTION TRIM(DISP-NUM)
    +
    +               MOVE UPPER-BND TO LOWER-BND
    +               COMPUTE UPPER-BND = UPPER-BND * 10
    +           END-PERFORM.
    diff --git a/Task/Achilles-numbers/Crystal/achilles-numbers.cr b/Task/Achilles-numbers/Crystal/achilles-numbers.cr
    new file mode 100644
    index 0000000000..2cb66173f9
    --- /dev/null
    +++ b/Task/Achilles-numbers/Crystal/achilles-numbers.cr
    @@ -0,0 +1,86 @@
    +struct Int
    +  def totient
    +    n = self
    +    return 0 if n < 1
    +    tot = n
    +    i = typeof(n).new(2)
    +    while i*i <= n
    +      if n % i == 0
    +        while n % i == 0
    +          n //= i
    +        end
    +        tot -= tot // i
    +      end
    +      if i == 2; i = 1 end
    +      i += 2
    +    end
    +    if n > 1
    +      tot -= tot // n
    +    end
    +    tot
    +  end
    +end
    +
    +def get_perfect_powers (max_exp)
    +  upper = 10_u64 ** max_exp
    +  pps = Set(UInt64).new
    +  (2_u64 .. Math.isqrt(upper)).each do |i|
    +    p = i
    +    while (p *= i) < upper
    +      pps << p
    +    end
    +  end
    +  pps
    +end
    +
    +def get_achilles (min_exp, max_exp, pps)
    +  lower = 10_u64 ** min_exp
    +  upper = 10_u64 ** max_exp
    +  achilles = Set(UInt64).new
    +  (1_u64 .. Math.cbrt(upper).to_u64).each do |b|
    +    b3 = b * b * b
    +    (1_u64 .. Math.isqrt(upper)).each do |a|
    +      p = b3 * a * a
    +      break if p >= upper
    +      if p >= lower
    +        achilles << p unless p.in? pps
    +      end
    +    end
    +  end
    +  achilles
    +end
    +
    +def tprint (fmt, seq, row_sz)
    +  seq.in_slices_of(row_sz).each do |slice|
    +    puts slice.map {|elt| fmt % { elt } }.join(" ")
    +  end
    +end
    +
    +max_digits = 12
    +pps = get_perfect_powers(max_digits)
    +
    +achilles_set = get_achilles(1, 5, pps)
    +achilles = achilles_set.to_a.sort!
    +
    +puts "First 50 Achilles numbers:"
    +tprint("%4d", achilles.first(50), 10)
    +
    +puts "\nFirst 30 strong Achilles numbers:"
    +strong_achilles = [] of UInt64
    +count = 0
    +n = 0
    +while count < 30
    +  tot = achilles[n].totient
    +  if tot.in? achilles_set
    +    strong_achilles << achilles[n]
    +    count += 1
    +  end
    +  n += 1
    +end
    +tprint("%5d", strong_achilles, 10)
    +
    +puts "\nNumber of Achilles numbers with:"
    +(2..max_digits).each do |d|
    +  ac = get_achilles(d-1, d, pps).size
    +  puts "%2d digits: %d" % { d, ac }
    +end
    diff --git a/Task/Achilles-numbers/Delphi/achilles-numbers.delphi b/Task/Achilles-numbers/Delphi/achilles-numbers.pas
    similarity index 100%
    rename from Task/Achilles-numbers/Delphi/achilles-numbers.delphi
    rename to Task/Achilles-numbers/Delphi/achilles-numbers.pas
    diff --git a/Task/Achilles-numbers/EasyLang/achilles-numbers.easy b/Task/Achilles-numbers/EasyLang/achilles-numbers.easy
    index ec0935dde9..c84b968a4a 100644
    --- a/Task/Achilles-numbers/EasyLang/achilles-numbers.easy
    +++ b/Task/Achilles-numbers/EasyLang/achilles-numbers.easy
    @@ -1,56 +1,41 @@
    -func gcd n d .
    -   if d = 0
    -      return n
    -   .
    +fastfunc 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
    -      .
    +fastfunc totient n .
    +   m = 1
    +   while m <= n
    +      if gcd m n = 1 : tot += 1
    +      m += 1
        .
        return tot
     .
    -func isPowerful m .
    +fastfunc isPowerful m .
        n = m
        f = 2
        l = sqrt m
    -   if m <= 1
    -      return 0
    -   .
    +   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
    -         .
    +         if m mod (f * f) <> 0 : return 0
    +         n = n div f
    +         if f > n : return 1
           else
              f += 1
              if f > l
    -            if m mod (n * n) <> 0
    -               return 0
    -            .
    +            if m mod (n * n) <> 0 : return 0
                 return 1
              .
           .
        .
     .
    -func isAchilles n .
    -   if isPowerful n = 0
    -      return 0
    -   .
    +fastfunc isAchilles n .
    +   if isPowerful n = 0 : return 0
        m = 2
        a = m * m
        repeat
           repeat
    -         if a = n
    -            return 0
    -         .
    +         if a = n : return 0
              a *= m
              until a > n
           .
    @@ -62,38 +47,34 @@ func isAchilles n .
     .
     print "First 50 Achilles numbers:"
     n = 1
    -repeat
    +while cnt < 50
        if isAchilles n = 1
           write n & " "
    -      num += 1
    +      cnt += 1
    +      if cnt mod 10 = 0 : print ""
        .
        n += 1
    -   until num >= 50
     .
     print ""
    -print ""
     print "First 20 strong Achilles numbers:"
    -num = 0
    +cnt = 0
     n = 1
    -repeat
    +while cnt < 20
        if isAchilles n = 1 and isAchilles totient n = 1
           write n & " "
    -      num += 1
    +      cnt += 1
    +      if cnt mod 10 = 0 : print ""
        .
        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
    -      .
    +      num += isAchilles n
        .
        write num & " "
        a = b
    diff --git a/Task/Achilles-numbers/FutureBasic/achilles-numbers.basic b/Task/Achilles-numbers/FutureBasic/achilles-numbers.basic
    new file mode 100644
    index 0000000000..194d6b3e21
    --- /dev/null
    +++ b/Task/Achilles-numbers/FutureBasic/achilles-numbers.basic
    @@ -0,0 +1,90 @@
    +NSInteger local fn GCD( n as NSInteger, d as NSInteger )
    +  if ( d == 0 ) then return n else return fn GCD( d, n % d )
    +end fn = 0
    +
    +NSInteger local fn Totient( n as NSInteger )
    +  NSInteger tot = 0
    +  for NSInteger m = 1 to n
    +    if fn GCD( m, n ) = 1 then tot++
    +  next
    +  return tot
    +end fn = 0
    +
    +BOOL local fn IsPowerful( m as NSInteger )
    +  int n = m
    +  int f = 2
    +  double l = sqr(m)
    +
    +  if m <= 1 then return NO
    +  while ( YES )
    +    NSInteger q = n / f
    +    if ( n % f ) == 0
    +      if ( m % (f * f) ) then return NO
    +      n = q
    +      if f > n then exit while
    +    else
    +      f++
    +      if ( f > l )
    +        if ( m % (n * n) ) then return NO
    +        exit while
    +      end if
    +    end if
    +  wend
    +end fn = YES
    +
    +BOOL local fn IsAchilles( n as NSInteger )
    +  if fn IsPowerful(n) == NO then return NO
    +  NSInteger m = 2
    +  NSInteger a = m * m
    +  do
    +    do
    +      if a == n then return NO
    +      a *= m
    +    until ( a > n )
    +    m++
    +    a = m * m
    +  until ( a > n )
    +end fn = YES
    +
    +local fn AchillesNumbers
    +  print "First 50 Achilles numbers:"
    +  NSInteger num = 0
    +  NSInteger n = 1
    +
    +  CFTimeInterval t : t = fn CACurrentMediaTime
    +  do
    +    if fn IsAchilles( n )
    +      printf @"%4d \b", n
    +      num++
    +      if ( num % 10 ) != 0 then printf @" \b" else print
    +    end if
    +    n++
    +  until ( num >= 50 )
    +
    +  printf @"\n\nFirst 20 strong Achilles numbers:"
    +  num = 0
    +  n = 1
    +  do
    +    if fn IsAchilles(n) && fn IsAchilles( fn Totient(n) )
    +      printf @"%5d \b", n
    +      num++
    +      if ( num % 5 ) != 0 then printf @" \b" else print
    +    end if
    +    n++
    +  until ( num >= 20 )
    +
    +  printf @"\n"
    +  for NSInteger i = 2 to 6
    +    NSInteger inicio = fix( 10.0 ^ (i-1) )
    +    num = 0
    +    for n = inicio to inicio * 10 -1
    +      if fn IsAchilles(n) then num++
    +    next
    +    printf @"Achilles numbers with %d digits: %d", i, num
    +  next
    +  printf @"\nCompute time: %.3f ms", (fn CACurrentMediaTime - t ) * 1000
    +end fn
    +
    +fn AchillesNumbers
    +
    +HandleEvents
    diff --git a/Task/Achilles-numbers/JavaScript/achilles-numbers.js b/Task/Achilles-numbers/JavaScript/achilles-numbers.js
    new file mode 100644
    index 0000000000..3f0113554c
    --- /dev/null
    +++ b/Task/Achilles-numbers/JavaScript/achilles-numbers.js
    @@ -0,0 +1,129 @@
    +class AchillesNumbers {
    +    constructor() {
    +        this.pps = new Map(); // Stores perfect powers
    +    }
    +
    +    // Euler's totient function
    +    totient(n) {
    +        let tot = n;
    +        let i = 2;
    +        while (i * i <= n) {
    +            if (n % i === 0) {
    +                // Remove all factors of i
    +                while (n % i === 0) {
    +                    n = Math.floor(n / i);
    +                }
    +                tot -= Math.floor(tot / i);
    +            }
    +            // Handle even/odd step correctly
    +            if (i === 2) {
    +                i = 1;
    +            }
    +            i += 2;
    +        }
    +        // If remaining n is a prime
    +        if (n > 1) {
    +            tot -= Math.floor(tot / n);
    +        }
    +        return tot;
    +    }
    +
    +    // Generate all perfect powers up to 10^maxExp
    +    getPerfectPowers(maxExp) {
    +        const upper = Math.pow(10, maxExp);
    +        const sqrtUpper = Math.floor(Math.sqrt(upper));
    +
    +        for (let i = 2; i <= sqrtUpper; i++) {
    +            let p = i;
    +            while (true) {
    +                p *= i;
    +                if (p >= upper) break;
    +                this.pps.set(Math.floor(p), true);
    +            }
    +        }
    +    }
    +
    +    // Generate all Achilles numbers between 10^minExp and 10^maxExp
    +    getAchilles(minExp, maxExp) {
    +        const lower = Math.pow(10, minExp);
    +        const upper = Math.pow(10, maxExp);
    +        const achilles = new Map();
    +
    +        const cbrtUpper = Math.floor(Math.cbrt(upper));
    +        for (let b = 1; b <= cbrtUpper; b++) {
    +            const b3 = b * b * b;
    +            const sqrtUpper = Math.floor(Math.sqrt(upper));
    +
    +            for (let a = 1; a <= sqrtUpper; a++) {
    +                const p = b3 * a * a;
    +                if (p >= upper) break;
    +
    +                if (p >= lower) {
    +                    if (!this.pps.has(p)) {
    +                        achilles.set(p, true);
    +                    }
    +                }
    +            }
    +        }
    +        return achilles;
    +    }
    +
    +    static main() {
    +        const an = new AchillesNumbers();
    +        const maxDigits = 8;
    +
    +        an.getPerfectPowers(maxDigits);
    +        const achillesSet = an.getAchilles(1, 5);
    +
    +        // Convert map keys to sorted array
    +        const achilles = Array.from(achillesSet.keys()).sort((a, b) => a - b);
    +
    +        // Print first 50 Achilles numbers
    +        console.log("First 50 Achilles numbers:");
    +        let output = "";
    +        for (let i = 0; i < 50; i++) {
    +            output += `${achilles[i].toString().padStart(4)} `;
    +            if ((i + 1) % 10 === 0) {
    +                console.log(output);
    +                output = "";
    +            }
    +        }
    +        if (output) console.log(output);
    +
    +        // Print first 30 strong Achilles numbers
    +        console.log("\nFirst 30 strong Achilles numbers:");
    +        const strongAchilles = [];
    +        let count = 0;
    +        let idx = 0;
    +
    +        while (count < 30 && idx < achilles.length) {
    +            const n = achilles[idx];
    +            const tot = an.totient(n);
    +            if (achillesSet.has(tot)) {
    +                strongAchilles.push(n);
    +                count++;
    +            }
    +            idx++;
    +        }
    +
    +        output = "";
    +        for (let i = 0; i < 30; i++) {
    +            output += `${strongAchilles[i].toString().padStart(5)} `;
    +            if ((i + 1) % 10 === 0) {
    +                console.log(output);
    +                output = "";
    +            }
    +        }
    +        if (output) console.log(output);
    +
    +        // Print counts per digit length
    +        console.log("\nNumber of Achilles numbers with:");
    +        for (let d = 2; d <= maxDigits; d++) {
    +            const ac = an.getAchilles(d - 1, d).size;
    +            console.log(`${d.toString().padStart(2)} digits: ${ac}`);
    +        }
    +    }
    +}
    +
    +// Execute the main method
    +AchillesNumbers.main();
    diff --git a/Task/Achilles-numbers/Julia/achilles-numbers.julia b/Task/Achilles-numbers/Julia/achilles-numbers.jl
    similarity index 100%
    rename from Task/Achilles-numbers/Julia/achilles-numbers.julia
    rename to Task/Achilles-numbers/Julia/achilles-numbers.jl
    diff --git a/Task/Achilles-numbers/PARI-GP/achilles-numbers.parigp b/Task/Achilles-numbers/PARI-GP/achilles-numbers.parigp
    new file mode 100644
    index 0000000000..44391a9b19
    --- /dev/null
    +++ b/Task/Achilles-numbers/PARI-GP/achilles-numbers.parigp
    @@ -0,0 +1,8 @@
    +is(n,f=factor(n))=gcd(f[,2])==1 && vecmin(f[,2])>1
    +first(n)=my(v=List()); forfactored(k=1,10^9, if(is(k[1],k[2]), listput(v,k[1]); if(#v==n, return(Vec(v)))))
    +firstStrong(n)=my(v=List()); forfactored(k=1,10^9, if(is(k[1],k[2]) && is(eulerphi(k)), listput(v,k[1]); if(#v==n, return(Vec(v)))))
    +countBetween(a,b)=my(s); forfactored(k=a,b, if(is(k[1],k[2]), s++)); s
    +countDigits(n)=countBetween(10^(n-1),10^n-1)
    +first(50)
    +firstStrong(20)
    +apply(countDigits, [2..5])
    diff --git a/Task/Achilles-numbers/Phix/achilles-numbers.phix b/Task/Achilles-numbers/Phix/achilles-numbers.phix
    index 933e7e375a..3ebdef5c6e 100644
    --- a/Task/Achilles-numbers/Phix/achilles-numbers.phix
    +++ b/Task/Achilles-numbers/Phix/achilles-numbers.phix
    @@ -1,62 +1,67 @@
    -(phixonline)-->
    - with javascript_semantics
    - requires("1.0.2") -- [join_by(fmt)]
    - atom t0 = time()
    - constant maxDigits = iff(platform()=JS?10:12)
    - integer pps = new_dict()
    +with javascript_semantics
    +requires("1.0.2") -- [join_by(fmt)]
    +atom t0 = time()
    +constant maxDigits = iff(platform()=JS?10:12)
    +integer pps = new_dict()
     
    - procedure getPerfectPowers(integer maxExp)
    -     atom hi = power(10, maxExp)
    -     integer imax = floor(sqrt(hi))
    -     for i=2 to imax do
    -         atom p = i
    -         while true do
    -             p *= i
    -             if p>=hi then exit end if
    -             setd(p,true,pps)
    -         end while
    -     end for
    - end procedure
    +procedure getPerfectPowers(integer maxExp)
    +    atom hi = power(10, maxExp), t1 = time()+1
    +    integer imax = floor(sqrt(hi))
    +    for i=2 to imax do
    +        atom p = i
    +        while true do
    +            p *= i
    +            if p>=hi then exit end if
    +            setd(p,true,pps)
    +        end while
    +        if time()>t1 then
    +            progress("getting perfect powers, %d/%d\r",{i,imax})
    +            t1 = time()+1
    +        end if
    +    end for
    +    progress("")
    +end procedure
     
    - function get_achilles(integer minExp, maxExp)
    -     atom lo10 = power(10,minExp),
    -          hi10 = power(10,maxExp)
    -     integer bmax = floor(power(hi10,1/3)),
    -             amax = floor(sqrt(hi10))
    -     sequence achilles = {}
    -     for b=2 to bmax do
    -         atom b3 = b * b * b
    -         for a=2 to amax do
    -             atom p = b3 * a * a
    -             if p>=hi10 then exit end if
    -             if p>=lo10 then
    -                 integer node = getd_index(p,pps)
    -                 if node=NULL then
    -                     achilles &= p
    -                 end if
    -             end if
    -         end for
    -     end for
    -     achilles = unique(achilles)
    -     return achilles
    - end function
    +function get_achilles(integer minExp, maxExp)
    +    atom lo10 = power(10,minExp),
    +         hi10 = power(10,maxExp)
    +    integer bmax = floor(power(hi10,1/3)),
    +            amax = floor(sqrt(hi10))
    +    sequence achilles = {}
    +    for b=2 to bmax do
    +        atom b3 = b * b * b
    +        for a=2 to amax do
    +            atom p = b3 * a * a
    +            if p>=hi10 then exit end if
    +            if p>=lo10 then
    +                integer node = getd_index(p,pps)
    +                if node=NULL then
    +                    achilles &= p
    +                end if
    +            end if
    +        end for
    +    end for
    +    achilles = unique(achilles)
    +    return achilles
    +end function
     
    - getPerfectPowers(maxDigits)
    - sequence achilles = get_achilles(1,5)
    +getPerfectPowers(maxDigits)
     
    - function strong_achilles(integer n)
    -     integer totient = sum(sq_eq(apply(true,gcd,{tagset(n),n}),1))
    -     return find(totient,achilles)
    - end function
    +sequence achilles = get_achilles(1,5),
    +         a = join_by(achilles[1..50],1,10," ",fmt:="%4d")
    +printf(1,"First 50 Achilles numbers:\n%s\n",{a})
     
    - sequence a = join_by(achilles[1..50],1,10," ",fmt:="%4d"),
    -          sa = filter(achilles,strong_achilles)[1..30],
    -          ssa = join_by(sa,1,10," ",fmt:="%5d")
    +function strong_achilles(integer n)
    +    integer totient = sum(sq_eq(apply(true,gcd,{tagset(n),n}),1))
    +    return find(totient,achilles)
    +end function
     
    - printf(1,"First 50 Achilles numbers:\n%s\n",{a})
    - printf(1,"First 30 strong Achilles numbers:\n%s\n",{ssa})
    - for d=2 to maxDigits do
    -     printf(1,"Achilles numbers with %d digits:%d\n",{d,length(get_achilles(d-1,d))})
    - end for
    - ?elapsed(time()-t0)
    -
    +(phixonline)--(notpygments)-->
      function ack(integer m, integer n)
          if m=0 then
              return n+1
    diff --git a/Task/Ackermann-function/Phix/ackermann-function-2.phix b/Task/Ackermann-function/Phix/ackermann-function-2.phix
    index 6080743529..3c54091afd 100644
    --- a/Task/Ackermann-function/Phix/ackermann-function-2.phix
    +++ b/Task/Ackermann-function/Phix/ackermann-function-2.phix
    @@ -1,4 +1,4 @@
    -(phixonline)-->
    +(phixonline)--(notpygments)-->
      -- demo\rosetta\Ackermann.exw
      include mpfr.e
     
    diff --git a/Task/Ackermann-function/Pluto/ackermann-function.pluto b/Task/Ackermann-function/Pluto/ackermann-function.pluto
    new file mode 100644
    index 0000000000..91075937c7
    --- /dev/null
    +++ b/Task/Ackermann-function/Pluto/ackermann-function.pluto
    @@ -0,0 +1,13 @@
    +function ack(m,n)
    +  if m==0 then
    +    return n+1
    +  elseif n == 0 then
    +    return ack(m-1,1)
    +  else return ack(m-1,ack(m,n-1)) end
    +end
    +
    +for i = 0,3 do
    +   for j = 0,8 do
    +      print($"A({i},{j})={ack(i,j)}")
    +   end
    +end
    diff --git a/Task/Ackermann-function/PowerShell/ackermann-function-1.psh b/Task/Ackermann-function/PowerShell/ackermann-function-1.ps1
    similarity index 100%
    rename from Task/Ackermann-function/PowerShell/ackermann-function-1.psh
    rename to Task/Ackermann-function/PowerShell/ackermann-function-1.ps1
    diff --git a/Task/Ackermann-function/PowerShell/ackermann-function-2.psh b/Task/Ackermann-function/PowerShell/ackermann-function-2.ps1
    similarity index 100%
    rename from Task/Ackermann-function/PowerShell/ackermann-function-2.psh
    rename to Task/Ackermann-function/PowerShell/ackermann-function-2.ps1
    diff --git a/Task/Ackermann-function/PowerShell/ackermann-function-3.psh b/Task/Ackermann-function/PowerShell/ackermann-function-3.ps1
    similarity index 100%
    rename from Task/Ackermann-function/PowerShell/ackermann-function-3.psh
    rename to Task/Ackermann-function/PowerShell/ackermann-function-3.ps1
    diff --git a/Task/Ackermann-function/PowerShell/ackermann-function-4.psh b/Task/Ackermann-function/PowerShell/ackermann-function-4.ps1
    similarity index 100%
    rename from Task/Ackermann-function/PowerShell/ackermann-function-4.psh
    rename to Task/Ackermann-function/PowerShell/ackermann-function-4.ps1
    diff --git a/Task/Ackermann-function/Python/ackermann-function-2.py b/Task/Ackermann-function/Python/ackermann-function-2.py
    index a2968422e0..b52f4e5e1e 100644
    --- a/Task/Ackermann-function/Python/ackermann-function-2.py
    +++ b/Task/Ackermann-function/Python/ackermann-function-2.py
    @@ -1,6 +1,6 @@
    -from functools import lru_cache
    +from functools import cache
     
    -@lru_cache(None)
    +@cache
     def ack2(M, N):
         if M == 0:
             return N + 1
    diff --git a/Task/Ackermann-function/REXX/ackermann-function-1.rexx b/Task/Ackermann-function/REXX/ackermann-function-1.rexx
    deleted file mode 100644
    index 4166968a81..0000000000
    --- a/Task/Ackermann-function/REXX/ackermann-function-1.rexx
    +++ /dev/null
    @@ -1,25 +0,0 @@
    -/*REXX program  calculates and displays  some values for the  Ackermann function.       */
    -            /*╔════════════════════════════════════════════════════════════════════════╗
    -              ║  Note:  the Ackermann function  (as implemented here)  utilizes deep   ║
    -              ║         recursive and is limited by the largest number that can have   ║
    -              ║         "1"  (unity) added to a number  (successfully and accurately). ║
    -              ╚════════════════════════════════════════════════════════════════════════╝*/
    -high=24
    -         do     j=0  to 3;                    say
    -             do k=0  to high % (max(1, j))
    -             call tell_Ack  j, k
    -             end   /*k*/
    -         end       /*j*/
    -exit                                             /*stick a fork in it,  we're all done. */
    -/*──────────────────────────────────────────────────────────────────────────────────────*/
    -tell_Ack:  parse arg mm,nn;   calls=0            /*display an echo message to terminal. */
    -           #=right(nn,length(high))
    -           say 'Ackermann('mm", "#')='right(ackermann(mm, nn), high),
    -                                      left('', 12)     'calls='right(calls, high)
    -           return
    -/*──────────────────────────────────────────────────────────────────────────────────────*/
    -ackermann: procedure expose calls                /*compute value of Ackermann function. */
    -           parse arg m,n;   calls=calls+1
    -           if m==0  then return n+1
    -           if n==0  then return ackermann(m-1, 1)
    -                         return ackermann(m-1, ackermann(m, n-1) )
    diff --git a/Task/Ackermann-function/REXX/ackermann-function-2.rexx b/Task/Ackermann-function/REXX/ackermann-function-2.rexx
    deleted file mode 100644
    index d489d6c82a..0000000000
    --- a/Task/Ackermann-function/REXX/ackermann-function-2.rexx
    +++ /dev/null
    @@ -1,21 +0,0 @@
    -/*REXX program  calculates and displays  some values for the  Ackermann function.       */
    -high=24
    -         do     j=0  to 3;                    say
    -             do k=0  to high % (max(1, j))
    -             call tell_Ack  j, k
    -             end   /*k*/
    -         end       /*j*/
    -exit                                             /*stick a fork in it,  we're all done. */
    -/*──────────────────────────────────────────────────────────────────────────────────────*/
    -tell_Ack:  parse arg mm,nn;   calls=0            /*display an echo message to terminal. */
    -           #=right(nn,length(high))
    -           say 'Ackermann('mm", "#')='right(ackermann(mm, nn), high),
    -                                      left('', 12)     'calls='right(calls, high)
    -           return
    -/*──────────────────────────────────────────────────────────────────────────────────────*/
    -ackermann: procedure expose calls                /*compute value of Ackermann function. */
    -           parse arg m,n;   calls=calls+1
    -           if m==0  then return n + 1
    -           if n==0  then return ackermann(m-1, 1)
    -           if m==2  then return n + 3 + n
    -                         return ackermann(m-1, ackermann(m, n-1) )
    diff --git a/Task/Ackermann-function/REXX/ackermann-function-3.rexx b/Task/Ackermann-function/REXX/ackermann-function-3.rexx
    deleted file mode 100644
    index 46a20892d0..0000000000
    --- a/Task/Ackermann-function/REXX/ackermann-function-3.rexx
    +++ /dev/null
    @@ -1,36 +0,0 @@
    -/*REXX program  calculates and displays  some values for the  Ackermann function.       */
    -numeric digits 100                               /*use up to 100 decimal digit integers.*/
    -                       /*╔═════════════════════════════════════════════════════════════╗
    -                         ║ When REXX raises a number to an integer power  (via the  ** ║
    -                         ║ operator,  the power can be positive, zero, or negative).   ║
    -                         ║ Ackermann(5,1)   is a bit impractical to calculate.         ║
    -                         ╚═════════════════════════════════════════════════════════════╝*/
    -high=24
    -         do     j=0  to 4;                   say
    -             do k=0  to high % (max(1, j))
    -             call tell_Ack  j, k
    -             if j==4 & k==2  then leave          /*there's no sense in going overboard. */
    -             end   /*k*/
    -         end       /*j*/
    -exit                                             /*stick a fork in it,  we're all done. */
    -/*──────────────────────────────────────────────────────────────────────────────────────*/
    -tell_Ack:  parse arg mm,nn;   calls=0            /*display an echo message to terminal. */
    -           #=right(nn,length(high))
    -           say 'Ackermann('mm", "#')='right(ackermann(mm, nn), high),
    -                                      left('', 12)     'calls='right(calls, high)
    -           return
    -/*──────────────────────────────────────────────────────────────────────────────────────*/
    -ackermann: procedure expose calls                /*compute value of Ackermann function. */
    -           parse arg m,n;   calls=calls+1
    -           if m==0  then return n + 1
    -           if m==1  then return n + 2
    -           if m==2  then return n + 3 + n
    -           if m==3  then return 2**(n+3) - 3
    -           if m==4  then do; #=2                 /* [↓]  Ugh!  ···  and still more ughs.*/
    -                                      do (n+3)-1 /*This is where the heavy lifting is.  */
    -                                      #=2**#
    -                                      end
    -                             return #-3
    -                         end
    -           if n==0  then return ackermann(m-1, 1)
    -                         return ackermann(m-1, ackermann(m, n-1) )
    diff --git a/Task/Ackermann-function/REXX/ackermann-function.rexx b/Task/Ackermann-function/REXX/ackermann-function.rexx
    new file mode 100644
    index 0000000000..5ef80aa39d
    --- /dev/null
    +++ b/Task/Ackermann-function/REXX/ackermann-function.rexx
    @@ -0,0 +1,83 @@
    +-- 27 Oct 2025
    +include Setting
    +numeric digits 310000
    +
    +say 'ACKERMANN FUNCTION'
    +say version
    +say
    +call Ackermann1
    +call Ackermann2
    +exit
    +
    +Ackermann1:
    +procedure expose glob.
    +say 'Using recursion...'
    +do i=0 to 3
    +   do j=0 to 10
    +      say 'Ackermann('i','j')' '=' Acker1(i,j) Elaps('r')'s'
    +   end
    +end
    +say
    +return
    +
    +Acker1:
    +procedure
    +arg xx,yy
    +select
    +   when xx = 0 then
    +      return yy+1
    +   when yy = 0 then
    +      return Acker1(xx-1,1)
    +   otherwise
    +      return Acker1(xx-1,Acker1(xx,yy-1))
    +end
    +
    +Ackermann2:
    +procedure expose glob.
    +say 'Using closed formulas...'
    +do i=0 to 3
    +   do j=0 to 10
    +      say 'Ackermann('i','j')' '=' Acker2(i,j) Elaps('r')'s'
    +   end
    +end
    +say 'Ackermann(3,100) =' Acker2(3,100) Elaps('r')'s'
    +say 'Ackermann(3,1000) has' Length(Acker2(3,1000)) 'digits' Elaps('r')'s'
    +say 'Ackermann(3,10000) has' Length(Acker2(3,10000)) 'digits' Elaps('r')'s'
    +say 'Ackermann(3,100000) has' Length(Acker2(3,100000)) 'digits' Elaps('r')'s'
    +say 'Ackermann(3,1000000) has' Length(Acker2(3,1000000)) 'digits' Elaps('r')'s'
    +say 'Ackermann(4,0) =' Acker2(4,0) Elaps('r')'s'
    +say 'Ackermann(4,1) =' Acker2(4,1) Elaps('r')'s'
    +say 'Ackermann(4,2) has' Length(Acker2(4,2)) 'digits' Elaps('r')'s'
    +return
    +
    +Acker2:
    +procedure
    +arg xx,yy
    +select
    +   when xx=0 then
    +      rr=yy+1
    +   when xx=1 then
    +      rr=yy+2
    +   when xx=2 then
    +      rr=yy+yy+3
    +   when xx=3 then
    +      rr=2**(yy+3)-3
    +   when xx=4 then
    +      select
    +         when yy=0 then
    +            rr=2**(2**2)-3
    +         when yy=1 then
    +            rr=2**(2**(2**2))-3
    +         when yy=2 then
    +            rr=2**(2**(2**(2**2)))-3
    +         otherwise
    +            rr=0
    +      end
    +   otherwise
    +      rr=0
    +end
    +return rr
    +
    +include Abend
    +-- Elaps
    +include Timer
    diff --git a/Task/Ackermann-function/ReScript/ackermann-function.re b/Task/Ackermann-function/ReScript/ackermann-function.res
    similarity index 100%
    rename from Task/Ackermann-function/ReScript/ackermann-function.re
    rename to Task/Ackermann-function/ReScript/ackermann-function.res
    diff --git a/Task/Ackermann-function/Rebol/ackermann-function-1.rebol b/Task/Ackermann-function/Rebol/ackermann-function-1.rebol
    new file mode 100644
    index 0000000000..52928c349e
    --- /dev/null
    +++ b/Task/Ackermann-function/Rebol/ackermann-function-1.rebol
    @@ -0,0 +1,7 @@
    +ackermann: func [m n] [
    +    case [
    +        m = 0 [n + 1]
    +        n = 0 [ackermann m - 1 1]
    +        true [ackermann m - 1 ackermann m n - 1]
    +    ]
    +]
    diff --git a/Task/Ackermann-function/Rebol/ackermann-function-2.rebol b/Task/Ackermann-function/Rebol/ackermann-function-2.rebol
    new file mode 100644
    index 0000000000..c6e294cb60
    --- /dev/null
    +++ b/Task/Ackermann-function/Rebol/ackermann-function-2.rebol
    @@ -0,0 +1,16 @@
    +ackermann: func [
    +    m [integer!]
    +    n [integer!]
    +] [
    +    ;; Small-m closed forms
    +    case [
    +        m = 0 [n + 1]
    +        m = 1 [n + 2]
    +        m = 2 [(2 * n) + 3]
    +        m = 3 [
    +            ;; 2^(n+3) - 3
    +            (to integer! power 2 (n + 3)) - 3
    +        ]
    +        ;; m >= 4 causes stack overflow
    +    ]
    +]
    diff --git a/Task/Ackermann-function/Coq/ackermann-function-1.coq b/Task/Ackermann-function/Rocq/ackermann-function-1.rocq
    similarity index 100%
    rename from Task/Ackermann-function/Coq/ackermann-function-1.coq
    rename to Task/Ackermann-function/Rocq/ackermann-function-1.rocq
    diff --git a/Task/Ackermann-function/Coq/ackermann-function-2.coq b/Task/Ackermann-function/Rocq/ackermann-function-2.rocq
    similarity index 100%
    rename from Task/Ackermann-function/Coq/ackermann-function-2.coq
    rename to Task/Ackermann-function/Rocq/ackermann-function-2.rocq
    diff --git a/Task/Ackermann-function/Rust/ackermann-function-1.rust b/Task/Ackermann-function/Rust/ackermann-function-1.rs
    similarity index 100%
    rename from Task/Ackermann-function/Rust/ackermann-function-1.rust
    rename to Task/Ackermann-function/Rust/ackermann-function-1.rs
    diff --git a/Task/Ackermann-function/Rust/ackermann-function-2.rust b/Task/Ackermann-function/Rust/ackermann-function-2.rs
    similarity index 100%
    rename from Task/Ackermann-function/Rust/ackermann-function-2.rust
    rename to Task/Ackermann-function/Rust/ackermann-function-2.rs
    diff --git a/Task/Ackermann-function/Scheme/ackermann-function-1.ss b/Task/Ackermann-function/Scheme/ackermann-function-1.scm
    similarity index 100%
    rename from Task/Ackermann-function/Scheme/ackermann-function-1.ss
    rename to Task/Ackermann-function/Scheme/ackermann-function-1.scm
    diff --git a/Task/Ackermann-function/Scheme/ackermann-function-2.ss b/Task/Ackermann-function/Scheme/ackermann-function-2.scm
    similarity index 100%
    rename from Task/Ackermann-function/Scheme/ackermann-function-2.ss
    rename to Task/Ackermann-function/Scheme/ackermann-function-2.scm
    diff --git a/Task/Ackermann-function/TAV/ackermann-function.tav b/Task/Ackermann-function/TAV/ackermann-function.tav
    new file mode 100644
    index 0000000000..f81000b3c8
    --- /dev/null
    +++ b/Task/Ackermann-function/TAV/ackermann-function.tav
    @@ -0,0 +1,11 @@
    +ackermann (n) (m) :
    +  ? n = 0
    +    :> m+1
    +  ? m = 0
    +    :> ackermann (n-1) 1
    +  :> ackermann (n-1) ackermann n (m-1) \ = ackermann (n-1) (ackermann n (m-1))
    +\ test it
    +main(params):+
    +  p1 =: string params[1] as integer else 3
    +  p2 =: string params[2] as integer else 5
    +  print "ackermann(" _ p1 _ "," _ p2 _ ") = " _ ackermann p1 p2
    diff --git a/Task/Ackermann-function/Uiua/ackermann-function.uiua b/Task/Ackermann-function/Uiua/ackermann-function.uiua
    new file mode 100644
    index 0000000000..cebcb838cb
    --- /dev/null
    +++ b/Task/Ackermann-function/Uiua/ackermann-function.uiua
    @@ -0,0 +1,7 @@
    +A ←|2.1 (
    +  ◡(×+1>0:>0)
    +  sw(+1pop|A-1:1pop:
    +    |A-1:off(A:-1:))
    +)
    +
    +A 1 1
    diff --git a/Task/Ackermann-function/VBScript/ackermann-function-1.vb b/Task/Ackermann-function/VBScript/ackermann-function-1.vbs
    similarity index 100%
    rename from Task/Ackermann-function/VBScript/ackermann-function-1.vb
    rename to Task/Ackermann-function/VBScript/ackermann-function-1.vbs
    diff --git a/Task/Ackermann-function/VBScript/ackermann-function-2.vb b/Task/Ackermann-function/VBScript/ackermann-function-2.vbs
    similarity index 100%
    rename from Task/Ackermann-function/VBScript/ackermann-function-2.vb
    rename to Task/Ackermann-function/VBScript/ackermann-function-2.vbs
    diff --git a/Task/Ackermann-function/ZED/ackermann-function.zed b/Task/Ackermann-function/ZED/ackermann-function.zed
    index a16fe385ad..af5d1c0f49 100644
    --- a/Task/Ackermann-function/ZED/ackermann-function.zed
    +++ b/Task/Ackermann-function/ZED/ackermann-function.zed
    @@ -1,29 +1,29 @@
    -(A) m n
    -comment:
    +(a) m n
    +M ZERO
     (=) m 0
     (add1) n
     
    -(A) m n
    -comment:
    +(a) m n
    +N ZERO
     (=) n 0
    -(A) (sub1) m 1
    +(a) (sub1) m 1
     
    -(A) m n
    -comment:
    +(a) m n
    +DEFAULT
     #true
    -(A) (sub1) m (A) m (sub1) n
    +(a) (sub1) m (a) m (sub1) n
     
     (add1) n
    -comment:
    +=========
     #true
     (003) "+" n 1
     
     (sub1) n
    -comment:
    +=========
     #true
     (003) "-" n 1
     
     (=) n1 n2
    -comment:
    +=========
     #true
     (003) "=" n1 n2
    diff --git a/Task/Active-Directory-Connect/AutoIt/active-directory-connect.autoit b/Task/Active-Directory-Connect/AutoIt/active-directory-connect.au3
    similarity index 100%
    rename from Task/Active-Directory-Connect/AutoIt/active-directory-connect.autoit
    rename to Task/Active-Directory-Connect/AutoIt/active-directory-connect.au3
    diff --git a/Task/Active-Directory-Connect/Julia/active-directory-connect.julia b/Task/Active-Directory-Connect/Julia/active-directory-connect.jl
    similarity index 100%
    rename from Task/Active-Directory-Connect/Julia/active-directory-connect.julia
    rename to Task/Active-Directory-Connect/Julia/active-directory-connect.jl
    diff --git a/Task/Active-Directory-Connect/Kotlin/active-directory-connect.kotlin b/Task/Active-Directory-Connect/Kotlin/active-directory-connect.kts
    similarity index 100%
    rename from Task/Active-Directory-Connect/Kotlin/active-directory-connect.kotlin
    rename to Task/Active-Directory-Connect/Kotlin/active-directory-connect.kts
    diff --git a/Task/Active-Directory-Connect/Rust/active-directory-connect.rust b/Task/Active-Directory-Connect/Rust/active-directory-connect.rs
    similarity index 100%
    rename from Task/Active-Directory-Connect/Rust/active-directory-connect.rust
    rename to Task/Active-Directory-Connect/Rust/active-directory-connect.rs
    diff --git a/Task/Active-Directory-Connect/VBScript/active-directory-connect.vb b/Task/Active-Directory-Connect/VBScript/active-directory-connect.vbs
    similarity index 100%
    rename from Task/Active-Directory-Connect/VBScript/active-directory-connect.vb
    rename to Task/Active-Directory-Connect/VBScript/active-directory-connect.vbs
    diff --git a/Task/Active-Directory-Search-for-a-user/Julia/active-directory-search-for-a-user.julia b/Task/Active-Directory-Search-for-a-user/Julia/active-directory-search-for-a-user.jl
    similarity index 100%
    rename from Task/Active-Directory-Search-for-a-user/Julia/active-directory-search-for-a-user.julia
    rename to Task/Active-Directory-Search-for-a-user/Julia/active-directory-search-for-a-user.jl
    diff --git a/Task/Active-Directory-Search-for-a-user/PowerShell/active-directory-search-for-a-user.psh b/Task/Active-Directory-Search-for-a-user/PowerShell/active-directory-search-for-a-user.ps1
    similarity index 100%
    rename from Task/Active-Directory-Search-for-a-user/PowerShell/active-directory-search-for-a-user.psh
    rename to Task/Active-Directory-Search-for-a-user/PowerShell/active-directory-search-for-a-user.ps1
    diff --git a/Task/Active-Directory-Search-for-a-user/VBScript/active-directory-search-for-a-user-1.vb b/Task/Active-Directory-Search-for-a-user/VBScript/active-directory-search-for-a-user-1.vbs
    similarity index 100%
    rename from Task/Active-Directory-Search-for-a-user/VBScript/active-directory-search-for-a-user-1.vb
    rename to Task/Active-Directory-Search-for-a-user/VBScript/active-directory-search-for-a-user-1.vbs
    diff --git a/Task/Active-Directory-Search-for-a-user/VBScript/active-directory-search-for-a-user-2.vb b/Task/Active-Directory-Search-for-a-user/VBScript/active-directory-search-for-a-user-2.vbs
    similarity index 100%
    rename from Task/Active-Directory-Search-for-a-user/VBScript/active-directory-search-for-a-user-2.vb
    rename to Task/Active-Directory-Search-for-a-user/VBScript/active-directory-search-for-a-user-2.vbs
    diff --git a/Task/Active-Directory-Search-for-a-user/VBScript/active-directory-search-for-a-user-3.vb b/Task/Active-Directory-Search-for-a-user/VBScript/active-directory-search-for-a-user-3.vbs
    similarity index 100%
    rename from Task/Active-Directory-Search-for-a-user/VBScript/active-directory-search-for-a-user-3.vb
    rename to Task/Active-Directory-Search-for-a-user/VBScript/active-directory-search-for-a-user-3.vbs
    diff --git a/Task/Active-object/Ada/active-object.ada b/Task/Active-object/Ada/active-object.adb
    similarity index 100%
    rename from Task/Active-object/Ada/active-object.ada
    rename to Task/Active-object/Ada/active-object.adb
    diff --git a/Task/Active-object/Crystal/active-object.crystal b/Task/Active-object/Crystal/active-object.cr
    similarity index 100%
    rename from Task/Active-object/Crystal/active-object.crystal
    rename to Task/Active-object/Crystal/active-object.cr
    diff --git a/Task/Active-object/Delphi/active-object.delphi b/Task/Active-object/Delphi/active-object.pas
    similarity index 100%
    rename from Task/Active-object/Delphi/active-object.delphi
    rename to Task/Active-object/Delphi/active-object.pas
    diff --git a/Task/Active-object/Julia/active-object.julia b/Task/Active-object/Julia/active-object.jl
    similarity index 100%
    rename from Task/Active-object/Julia/active-object.julia
    rename to Task/Active-object/Julia/active-object.jl
    diff --git a/Task/Active-object/Kotlin/active-object.kotlin b/Task/Active-object/Kotlin/active-object.kts
    similarity index 100%
    rename from Task/Active-object/Kotlin/active-object.kotlin
    rename to Task/Active-object/Kotlin/active-object.kts
    diff --git a/Task/Active-object/Rust/active-object.rust b/Task/Active-object/Rust/active-object.rs
    similarity index 100%
    rename from Task/Active-object/Rust/active-object.rust
    rename to Task/Active-object/Rust/active-object.rs
    diff --git a/Task/Add-a-variable-to-a-class-instance-at-runtime/Ada/add-a-variable-to-a-class-instance-at-runtime.ada b/Task/Add-a-variable-to-a-class-instance-at-runtime/Ada/add-a-variable-to-a-class-instance-at-runtime.adb
    similarity index 100%
    rename from Task/Add-a-variable-to-a-class-instance-at-runtime/Ada/add-a-variable-to-a-class-instance-at-runtime.ada
    rename to Task/Add-a-variable-to-a-class-instance-at-runtime/Ada/add-a-variable-to-a-class-instance-at-runtime.adb
    diff --git a/Task/Add-a-variable-to-a-class-instance-at-runtime/Arturo/add-a-variable-to-a-class-instance-at-runtime.arturo b/Task/Add-a-variable-to-a-class-instance-at-runtime/Arturo/add-a-variable-to-a-class-instance-at-runtime.arturo
    index c668c74160..1709ab334f 100644
    --- a/Task/Add-a-variable-to-a-class-instance-at-runtime/Arturo/add-a-variable-to-a-class-instance-at-runtime.arturo
    +++ b/Task/Add-a-variable-to-a-class-instance-at-runtime/Arturo/add-a-variable-to-a-class-instance-at-runtime.arturo
    @@ -1,4 +1,4 @@
    -define :myClass [name,surname][]
    +define :myClass [name, surname]
     
     myInstance: to :myClass ["John" "Doe"]
     print myInstance
    diff --git a/Task/Add-a-variable-to-a-class-instance-at-runtime/Ballerina/add-a-variable-to-a-class-instance-at-runtime.ballerina b/Task/Add-a-variable-to-a-class-instance-at-runtime/Ballerina/add-a-variable-to-a-class-instance-at-runtime.ballerina
    new file mode 100644
    index 0000000000..a4d319d761
    --- /dev/null
    +++ b/Task/Add-a-variable-to-a-class-instance-at-runtime/Ballerina/add-a-variable-to-a-class-instance-at-runtime.ballerina
    @@ -0,0 +1,23 @@
    +import ballerina/io;
    +
    +// Person is an 'open' record type which allows fields of 'anydata' type
    +// to be added at runtime.
    +type Person record {
    +    string name;
    +    int age;
    +};
    +
    +public function main() {
    +    // Create an instance of Person with an additional 'town' field.
    +    Person p = {
    +        name: "Fred",
    +        age: 40,
    +        "town": "Boston"  // extra field name needs to be in quotes
    +    };
    +
    +    // Print name and age fields - using standard '.' syntax.
    +    io:print(p.name, " is ", p.age);
    +
    +    // Print the additional field - using a map-like syntax.
    +    io:println(" and lives in ", p["town"], ".");
    +}
    diff --git a/Task/Add-a-variable-to-a-class-instance-at-runtime/C++/add-a-variable-to-a-class-instance-at-runtime.cpp b/Task/Add-a-variable-to-a-class-instance-at-runtime/C++/add-a-variable-to-a-class-instance-at-runtime.cpp
    new file mode 100644
    index 0000000000..1f83768ae0
    --- /dev/null
    +++ b/Task/Add-a-variable-to-a-class-instance-at-runtime/C++/add-a-variable-to-a-class-instance-at-runtime.cpp
    @@ -0,0 +1,34 @@
    +#include 
    +#include 
    +#include 
    +#include 
    +
    +class Demonstration {
    +public:
    +	Demonstration() {
    +		variables = { };
    +	}
    +
    +	std::map variables;
    +};
    +
    +int main() {
    +	Demonstration demo;
    +	std::cout << "Create two variables at runtime:" << std::endl;
    +	for ( uint32_t i = 1; i <= 2; ++i ) {
    +		std::cout << "    Variable number " << i << ":" << std::endl;
    +		std::cout << "        Enter name: " << std::endl;
    +		std::string name;
    +		std::cin >> name;
    +		std::cout << "        Enter value: " << std::endl;
    +		double value;
    +		std::cin >> value;
    +		demo.variables[name] = value;
    +	}
    +
    +	std::cout << std::endl;
    +	std::cout << "Two new runtime variables appear to have been created." << std::endl;
    +	for ( const auto &[key, value] : demo.variables ) {
    +		std::cout << "Variable " << key << " = " << value << std::endl;
    +	}
    +}
    diff --git a/Task/Add-a-variable-to-a-class-instance-at-runtime/Crystal/add-a-variable-to-a-class-instance-at-runtime.cr b/Task/Add-a-variable-to-a-class-instance-at-runtime/Crystal/add-a-variable-to-a-class-instance-at-runtime.cr
    new file mode 100644
    index 0000000000..9d091d3e04
    --- /dev/null
    +++ b/Task/Add-a-variable-to-a-class-instance-at-runtime/Crystal/add-a-variable-to-a-class-instance-at-runtime.cr
    @@ -0,0 +1,25 @@
    +class SuperDynamic
    +  @vars = {} of String => String | Int32
    +
    +  def set_vars (@vars)
    +  end
    +
    +  macro method_missing (call)
    +    {% name = call.name %}
    +    {% if name.ends_with? "=" %}
    +      {% name = name.gsub(/=$/, "") %}
    +      raise "unknown var" unless @vars.has_key? {{name.id.stringify}}
    +      @vars[{{name.id.stringify}}] = {{call.args[0].id}}
    +    {% else %}
    +      @vars[{{name.id.stringify}}]
    +    {% end %}
    +  end
    +end
    +
    +sd = SuperDynamic.new
    +
    +sd.set_vars({ "a" => 1, "b" => "2" })
    +
    +p! sd.a
    +sd.a = 99
    +p! sd.a
    diff --git a/Task/Add-a-variable-to-a-class-instance-at-runtime/Elena/add-a-variable-to-a-class-instance-at-runtime.elena b/Task/Add-a-variable-to-a-class-instance-at-runtime/Elena/add-a-variable-to-a-class-instance-at-runtime.elena
    index 9634046d11..07b19d327c 100644
    --- a/Task/Add-a-variable-to-a-class-instance-at-runtime/Elena/add-a-variable-to-a-class-instance-at-runtime.elena
    +++ b/Task/Add-a-variable-to-a-class-instance-at-runtime/Elena/add-a-variable-to-a-class-instance-at-runtime.elena
    @@ -10,7 +10,7 @@ class Extender : BaseExtender
        }
     }
     
    -public program()
    +public Program()
     {
        var object := 234;
     
    @@ -19,7 +19,7 @@ public program()
     
        object.foo := "bar";
     
    -   console.printLine(object,".foo=",object.foo);
    +   Console.printLine(object,".foo=",object.foo);
     
    -   console.readChar()
    +   Console.readChar()
     }
    diff --git a/Task/Add-a-variable-to-a-class-instance-at-runtime/Julia/add-a-variable-to-a-class-instance-at-runtime-1.julia b/Task/Add-a-variable-to-a-class-instance-at-runtime/Julia/add-a-variable-to-a-class-instance-at-runtime-1.jl
    similarity index 100%
    rename from Task/Add-a-variable-to-a-class-instance-at-runtime/Julia/add-a-variable-to-a-class-instance-at-runtime-1.julia
    rename to Task/Add-a-variable-to-a-class-instance-at-runtime/Julia/add-a-variable-to-a-class-instance-at-runtime-1.jl
    diff --git a/Task/Add-a-variable-to-a-class-instance-at-runtime/Julia/add-a-variable-to-a-class-instance-at-runtime-2.julia b/Task/Add-a-variable-to-a-class-instance-at-runtime/Julia/add-a-variable-to-a-class-instance-at-runtime-2.jl
    similarity index 100%
    rename from Task/Add-a-variable-to-a-class-instance-at-runtime/Julia/add-a-variable-to-a-class-instance-at-runtime-2.julia
    rename to Task/Add-a-variable-to-a-class-instance-at-runtime/Julia/add-a-variable-to-a-class-instance-at-runtime-2.jl
    diff --git a/Task/Add-a-variable-to-a-class-instance-at-runtime/Kotlin/add-a-variable-to-a-class-instance-at-runtime.kotlin b/Task/Add-a-variable-to-a-class-instance-at-runtime/Kotlin/add-a-variable-to-a-class-instance-at-runtime.kts
    similarity index 100%
    rename from Task/Add-a-variable-to-a-class-instance-at-runtime/Kotlin/add-a-variable-to-a-class-instance-at-runtime.kotlin
    rename to Task/Add-a-variable-to-a-class-instance-at-runtime/Kotlin/add-a-variable-to-a-class-instance-at-runtime.kts
    diff --git a/Task/Add-a-variable-to-a-class-instance-at-runtime/PascalABC.NET/add-a-variable-to-a-class-instance-at-runtime.pas b/Task/Add-a-variable-to-a-class-instance-at-runtime/PascalABC.NET/add-a-variable-to-a-class-instance-at-runtime.pas
    new file mode 100644
    index 0000000000..3a8fa42045
    --- /dev/null
    +++ b/Task/Add-a-variable-to-a-class-instance-at-runtime/PascalABC.NET/add-a-variable-to-a-class-instance-at-runtime.pas
    @@ -0,0 +1,19 @@
    +type
    +  MyClass = class
    +    private
    +      dict := new Dictionary;
    +    public
    +      procedure Add(name: string; value: object) := dict[name] := value;
    +      property Items[name: string]: object read dict[name]; default;
    +  end;
    +
    +begin
    +  var obj := new MyClass;
    +  obj.Add('Name','PascalABC.NET');
    +  obj.Add('Age',16);
    +  Println(obj['Name'],obj['Age']);
    +  var obj1 := new MyClass;
    +  obj1.Add('X',2.3);
    +  obj1.Add('Y',3.8);
    +  Println(obj1['X'],obj1['Y']);
    +end.
    diff --git a/Task/Add-a-variable-to-a-class-instance-at-runtime/Phix/add-a-variable-to-a-class-instance-at-runtime.phix b/Task/Add-a-variable-to-a-class-instance-at-runtime/Phix/add-a-variable-to-a-class-instance-at-runtime.phix
    index 4a5d383d43..7e559ea226 100644
    --- a/Task/Add-a-variable-to-a-class-instance-at-runtime/Phix/add-a-variable-to-a-class-instance-at-runtime.phix
    +++ b/Task/Add-a-variable-to-a-class-instance-at-runtime/Phix/add-a-variable-to-a-class-instance-at-runtime.phix
    @@ -1,10 +1,9 @@
    --->
    - class wobbly dynamic
    -     -- (pre-define a few fields/methods if you like)
    - end class
    - wobbly wobble = new()
    - ?wobble.jelly               -- 0
    - --?wobble["jelly"]          -- for dynamic names use []
    - wobble.jelly = "green"
    - ?wobble.jelly               -- "green"
    -
    - with javascript_semantics
    - function additive(string p) return is_prime(sum(sq_sub(p,'0'))) end function
    - sequence res = filter(apply(get_primes_le(500),sprint),additive)
    - printf(1,"%d additive primes found: %s\n",{length(res),join(shorten(res,"",6))})
    -
    - --
    - -- demo\rosetta\Pattern_matching.exw
    - -- =================================
    - --
    - -- 1). Lightly modified copy of demo\rosetta\VisualiseTree.exw
    +-- demo\rosetta\Pattern_matching.exw
    +--  Lightly modified copy of demo\rosetta\VisualiseTree.exw
    +with javascript_semantics
     
    - with javascript_semantics
    +-- To the theme tune of the Milk Tray Ad iyrt,
    +-- All because the Windows console hates utf8:
    +constant TL = '\#DA', -- aka '┌'
    +         VT = '\#B3', -- aka '│'
    +         BL = '\#C0', -- aka '└'
    +         HZ = '\#C4', -- aka '─'
    +         HS = "\#C4"  -- (string version of HZ)
     
    - -- To the theme tune of the Milk Tray Ad iyrt,
    - -- All because the Windows console hates utf8:
    - constant TL = '\#DA', -- aka '┌'
    -          VT = '\#B3', -- aka '│'
    -          BL = '\#C0', -- aka '└'
    -          HZ = '\#C4', -- aka '─'
    -          HS = "\#C4"  -- (string version of HZ)
    +function w1252_to_utf8(string s)
    +    if platform()!=WINDOWS then
    +        s = substitute_all(s,{ TL, VT, BL, HZ},
    +                             {"┌","│","└","─"})
    +    end if
    +    return s
    +end function
    +--
     
    - function w1252_to_utf8(string s)
    -     if platform()!=WINDOWS then
    -         s = substitute_all(s,{ TL, VT, BL, HZ},
    -                              {"┌","│","└","─"})
    -     end if
    -     return s
    - end function
    - --</hates utf8>
    +procedure visualise_tree(object tree, string root=HS)
    +    if atom(tree) then
    +        puts(1,"\n")
    +    else
    +        object {colour,left,v,right} = tree
    +        integer g = root[$]
    +        if sequence(left) then
    +            root[$] = iff(g=TL or g=HZ?' ':VT)
    +            visualise_tree(left,root&TL)
    +        end if
    +        root[$] = g
    +        printf(1,"%s%s%v\n",{w1252_to_utf8(root),colour,v})
    +        if sequence(right) then
    +            root[$] = iff(g=TL?VT:' ')
    +            visualise_tree(right,root&BL)
    +        end if
    +    end if
    +end procedure
    +--
     
    - procedure visualise_tree(object tree, string root=HS)
    -     if atom(tree) then
    -         puts(1,"<empty>\n")
    -     else
    -         object {colour,left,v,right} = tree
    -         integer g = root[$]
    -         if sequence(left) then
    -             root[$] = iff(g=TL or g=HZ?' ':VT)
    -             visualise_tree(left,root&TL)
    -         end if
    -         root[$] = g
    -         printf(1,"%s%s%v\n",{w1252_to_utf8(root),colour,v})
    -         if sequence(right) then
    -             root[$] = iff(g=TL?VT:' ')
    -             visualise_tree(right,root&BL)
    -         end if
    -     end if
    - end procedure
    - --</copy VisualiseTree>
    +-- 2). Imagine the following is in a file, say algebraic_data_types.e - not quite generic enough
    +--      for inclusion in builtins, but not exactly difficult to copy/maintain per-project either.
     
    - -- 2). Imagine the following is in a file, say algebraic_data_types.e - not quite generic enough
    - --      for inclusion in builtins, but not exactly difficult to copy/maintain per-project either.
    +function match_one(sequence key, object t)
    +    sequence res = {}
    +    if sequence(t)
    +    and length(key)==length(t) then
    +        for i=1 to length(key) do
    +            object ki = key[i], ti = t[i]
    +            if sequence(ki) and not string(ki) then
    +                sequence r2 = match_one(ki,ti)
    +                if r2={} then res = {} exit end if
    +                res &= r2
    +            else
    +                if ki=0 then
    +                    res = append(res,ti)
    +                else
    +                    if ki!=ti then res = {} exit end if
    +                end if
    +            end if
    +        end for
    +    end if
    +    return res
    +end function
     
    - function match_one(sequence key, object t)
    -     sequence res = {}
    -     if sequence(t)
    -     and length(key)==length(t) then
    -         for i=1 to length(key) do
    -             object ki = key[i], ti = t[i]
    -             if sequence(ki) and not string(ki) then
    -                 sequence r2 = match_one(ki,ti)
    -                 if r2={} then res = {} exit end if
    -                 res &= r2
    -             else
    -                 if ki=0 then
    -                     res = append(res,ti)
    -                 else
    -                     if ki!=ti then res = {} exit end if
    -                 end if
    -             end if
    -         end for
    -     end if
    -     return res
    - end function
    +/*global*/ function match_algebraic(sequence set, t)
    +    sequence s
    +    for i=1 to length(set) do
    +        s = match_one(set[i],t)
    +        if length(s) then exit end if
    +    end for
    +    return s
    +end function
    +--
     
    - /*global*/ function match_algebraic(sequence set, t)
    -     sequence s
    -     for i=1 to length(set) do
    -         s = match_one(set[i],t)
    -         if length(s) then exit end if
    -     end for
    -     return s
    - end function
    - --</algebraic_data_types.e>
    +-- 3). The actual task
     
    - -- 3). The actual task
    +constant B = "B", R = "R"
     
    - constant B = "B", R = "R"
    +function balance(sequence t)
    +    sequence s = match_algebraic({{B,{R,{R,0,0,0},0,0},0,0},
    +                                  {B,{R,0,0,{R,0,0,0}},0,0},
    +                                  {B,0,0,{R,{R,0,0,0},0,0}},
    +                                  {B,0,0,{R,0,0,{R,0,0,0}}}},t)
    +    if length(s) then
    +        object {a,x,b,y,c,z,d} = s
    +        t = {R,{B,a,x,b},y,{B,c,z,d}}
    +    end if
    +    return t
    +end function
     
    - function balance(sequence t)
    -     sequence s = match_algebraic({{B,{R,{R,0,0,0},0,0},0,0},
    -                                   {B,{R,0,0,{R,0,0,0}},0,0},
    -                                   {B,0,0,{R,{R,0,0,0},0,0}},
    -                                   {B,0,0,{R,0,0,{R,0,0,0}}}},t)
    -     if length(s) then
    -         object {a,x,b,y,c,z,d} = s
    -         t = {R,{B,a,x,b},y,{B,c,z,d}}
    -     end if
    -     return t
    - end function
    +function ins(object tree, object leaf)
    +    if tree=NULL then
    +        tree = {R,NULL,leaf,NULL}
    +    else
    +        object {c,l,k,r} = tree
    +        if leaf!=k then
    +            if leaffunction ins(object tree, object leaf)
    -     if tree=NULL then
    -         tree = {R,NULL,leaf,NULL}
    -     else
    -         object {c,l,k,r} = tree
    -         if leaf!=k then
    -             if leaf<k then l = ins(l,leaf)
    -                       else r = ins(r,leaf)
    -             end if
    -             tree = balance({c,l,k,r})
    -         end if
    -     end if
    -     return tree
    - end function
    +function tree_insert(object tree, object leaf)
    +    tree = ins(tree,leaf)
    +    tree[1] = B
    +    return tree
    +end function
     
    - function tree_insert(object tree, object leaf)
    -     tree = ins(tree,leaf)
    -     tree[1] = B
    -     return tree
    - end function
    +sequence stuff = shuffle(tagset(10))
    +object tree = NULL
    +for i=1 to length(stuff) do
    +    tree = tree_insert(tree,stuff[i])
    +end for
    +visualise_tree(tree)
     
    - sequence stuff = shuffle(tagset(10))
    - object tree = NULL
    - for i=1 to length(stuff) do
    -     tree = tree_insert(tree,stuff[i])
    - end for
    - visualise_tree(tree)
    -
    - ?"done"
    - {} = wait_key()
    -
    - with javascript_semantics
    - requires("1.0.0")
    - include mpfr.e
    - mpfr_set_default_precision(-70)
    +with javascript_semantics
    +requires("1.0.0")
    +include mpfr.e
    +mpfr_set_default_precision(-70)
     
    - function almkvistGiullera(integer n, bool bPrint)
    -     mpz {t1,t2,ip} = mpz_inits(3)
    -     mpz_fac_ui(t1,6*n)
    -     mpz_mul_si(t1,t1,32)                -- t1:=2^5*(6n)!
    -     mpz_fac_ui(t2,n)
    -     mpz_pow_ui(t2,t2,6)
    -     mpz_mul_si(t2,t2,3)                 -- t2:=3*(n!)^6
    -     mpz_mul_si(ip,t1,532*n*n+126*n+9)   -- ip:=t1*(532n^2+126n+9)
    -     mpz_fdiv_q(ip,ip,t2)                -- ip:=ip/t2
    -     integer pw := 6*n+3
    -     mpz_ui_pow_ui(t1,10,pw)             -- t1 := 10^(6n+3)
    -     mpq tm = mpq_init_set_z(ip,t1)      -- tm := rat(ip/t1)
    -     if bPrint then
    -         string ips = mpz_get_str(ip),
    -                tms = mpfr_get_fixed(mpfr_init_set_q(tm),50)
    -         tms = trim_tail(tms,"0")
    -         printf(1,"%d  %44s  %3d  %s\n", {n, ips, -pw, tms})
    -     end if
    -     return tm
    - end function
    +function almkvistGiullera(integer n, bool bPrint)
    +    mpz {t1,t2,ip} = mpz_inits(3)
    +    mpz_fac_ui(t1,6*n)
    +    mpz_mul_si(t1,t1,32)                -- t1:=2^5*(6n)!
    +    mpz_fac_ui(t2,n)
    +    mpz_pow_ui(t2,t2,6)
    +    mpz_mul_si(t2,t2,3)                 -- t2:=3*(n!)^6
    +    mpz_mul_si(ip,t1,532*n*n+126*n+9)   -- ip:=t1*(532n^2+126n+9)
    +    mpz_fdiv_q(ip,ip,t2)                -- ip:=ip/t2
    +    integer pw := 6*n+3
    +    mpz_ui_pow_ui(t1,10,pw)             -- t1 := 10^(6n+3)
    +    mpq tm = mpq_init_set_z(ip,t1)      -- tm := rat(ip/t1)
    +    if bPrint then
    +        string ips = mpz_get_str(ip),
    +               tms = mpfr_get_fixed(mpfr_init_set_q(tm),50)
    +        tms = trim_tail(tms,"0")
    +        printf(1,"%d  %44s  %3d  %s\n", {n, ips, -pw, tms})
    +    end if
    +    return tm
    +end function
     
    - constant hdr = "N --------------- Integer portion -------------  Pow  ----------------- Nth term (50 dp) -----------------"
    - printf(1,"%s\n%s\n",{hdr,repeat('-',length(hdr))})
    - for n=0 to 9 do
    -     {} = almkvistGiullera(n, true)
    - end for
    +constant hdr = "N --------------- Integer portion -------------  Pow  ----------------- Nth term (50 dp) -----------------"
    +printf(1,"%s\n%s\n",{hdr,repeat('-',length(hdr))})
    +for n=0 to 9 do
    +    {} = almkvistGiullera(n, true)
    +end for
     
    - mpq {res,prev,z} = mpq_inits(3),
    -     prec = mpq_init_set_str(sprintf("1/1%s",repeat('0',70)))
    - integer n = 0
    - while true do
    -     mpq term := almkvistGiullera(n, false)
    -     mpq_add(res,res,term)
    -     mpq_sub(z,res,prev)
    -     mpq_abs(z,z)
    -     if mpq_cmp(z,prec) < 0 then exit end if
    -     mpq_set(prev,res)
    -     n += 1
    - end while
    - mpq_inv(res,res)
    - mpfr pi = mpfr_init_set_q(res)
    - mpfr_sqrt(pi,pi)
    - printf(1,"\nCalculation of pi took %d iterations using the Almkvist-Giullera formula.\n\n",n)
    - printf(1,"Pi to 70 d.p.: %s\n",mpfr_get_fixed(pi,70))
    - mpfr_const_pi(pi)
    - printf(1,"Pi (builtin) : %s\n",mpfr_get_fixed(pi,70))
    -
    - sequence res = columnize({tagset(5)}) -- ie {{1},{2},{3},{4},{5}}
    - integer n = 2, found = 0
    - while found<50 do
    -     integer l = length(prime_factors(n,true))
    -     if l<=5 and length(res[l])<=10 then
    -         res[l] &= n
    -         found += 1
    -     end if
    -     n += 1
    - end while
    - string fmt = "k = %d: "&join(repeat("%4d",10))&"\n"
    - for i=1 to 5 do
    -     printf(1,fmt,res[i])
    - end for
    -
    - function amb1(sequence sets, object res=0, integer idx=1)
    -     integer ch = 0,
    -             pass = 0
    -     if idx>length(sets) then
    -         pass = 1
    -     else
    -         if res=0 then
    -             res = repeat(0,length(sets))
    -         else
    -             res = deep_copy(res)
    -             ch = sets[idx-1][res[idx-1]][$]
    -         end if
    -         for k=1 to length(sets[idx]) do
    -             if ch=0 or sets[idx][k][1]=ch then
    -                 res[idx] = k
    -                 {pass,res} = amb1(sets,res,idx+1)
    -                 if pass then exit end if
    -             end if
    -         end for
    -     end if
    -     return {pass,res}
    - end function
    +with javascript_semantics
     
    - sequence sets = {{"the","that","a"},
    -                  {"frog","elephant","thing"},
    -                  {"walked","treaded","grows"},
    -                  {"slowly","quickly"}}
    - {integer pass, sequence res} = amb1(sets)
    - if pass then
    -     puts(1,"success: ")
    -     for i=1 to length(sets) do
    -         res[i] = sets[i][res[i]]
    -     end for
    -     ?res
    - else
    -     puts(1,"failure\n")
    - end if
    -
    - function amb(sequence sets, integer testrid, integer resrid=-1, object res=0, integer idx=1)
    -     integer flag = (res==0),
    -             pass = 0
    -     if idx>length(sets) then
    -         pass = 1
    -         if resrid!=-1 then
    -             resrid(sets,res)
    -         end if
    -     else
    -         if flag then
    -             res = repeat(0,length(sets))
    -         end if
    -         for k=1 to length(sets[idx]) do
    -             res[idx] = k
    -             if flag or testrid(sets,deep_copy(res),idx) then
    -                 {pass,res} = amb(sets,testrid,resrid,deep_copy(res),idx+1)
    -                 if pass and resrid=-1 then exit end if
    -             end if
    -         end for
    -     end if
    -     return {pass,res}
    - end function
    +with javascript_semantics
    +function amb(sequence sets, integer testrid, resrid=-1, idx=1, object res=0)
    +    bool flag = (res==0),
    +         pass = false
    +    if idx>length(sets) then
    +        pass = true
    +        if resrid!=-1 then
    +            resrid(sets,res)
    +        end if
    +    else
    +        if flag then
    +            res = repeat(0,length(sets))
    +        end if
    +        for k=1 to length(sets[idx]) do
    +            res[idx] = k
    +            if flag or testrid(sets,deep_copy(res),idx) then
    +                {pass,res} = amb(sets,testrid,resrid,idx+1,deep_copy(res))
    +                if pass and resrid=-1 then exit end if
    +            end if
    +        end for
    +    end if
    +    return {pass,res}
    +end function
     
    - function pairable(sequence sets, sequence res, integer idx)
    -     return sets[idx-1][res[idx-1]][$] = sets[idx][res[idx]][1]
    - end function
    +function pairable(sequence sets, res, integer idx)
    +    return sets[idx-1][res[idx-1]][$] = sets[idx][res[idx]][1]
    +end function
     
    - procedure AMB_Show(sequence sets, sequence res)
    -     res = deep_copy(res)
    -     for i=1 to length(sets) do
    -         res[i] = sets[i][res[i]]
    -     end for
    -     printf(1,"success: %v\n",{res})
    - end procedure
    +procedure AMB_Show(sequence sets, res)
    +    res = deep_copy(res)
    +    for i=1 to length(sets) do
    +        res[i] = sets[i][res[i]]
    +    end for
    +    printf(1,"success: %v\n",{res})
    +end procedure
     
    - function pythagorean(sequence /*sets*/, sequence res, integer idx)
    - -- (note that res[idx]==sets[idx][res[idx]] in all cases)
    -     integer {x,y,z} = res
    -     return idx<3 or (x*x+y*y=z*z)
    - end function
    +function pythagorean(sequence /*sets*/, sequence res, integer idx)
    +-- (note that res[idx]==sets[idx][res[idx]] in all cases)
    +    integer {x,y,z} = res
    +    return idx<3 or (x*x+y*y=z*z)
    +end function
     
    - procedure pythag_show(sequence /*sets*/, sequence res)
    -     printf(1,"success: %v\n",{res})
    - end procedure
    +procedure pythag_show(sequence /*sets*/, sequence res)
    +    printf(1,"success: %v\n",{res})
    +end procedure
     
    - -- see http://www.randomhacks.net/articles/2005/10/11/amb-operator
    - function not8(sequence sets, sequence res, integer idx)
    - -- (note that idx==2 in all cases)
    - -- (at the last moment, I flipped the test, after realising that
    - --  someone had completely misunderstood the original article...
    - --  return sets[1][res[1]]*sets[idx][res[idx]]!=8
    -     return sets[1][res[1]]*sets[idx][res[idx]]=8
    - end function
    +-- see http://www.randomhacks.net/articles/2005/10/11/amb-operator
    +function not8(sequence sets, sequence res, integer idx)
    +-- (note that idx==2 in all cases)
    +-- (at the last moment, I flipped the test, after realising that
    +--  someone had completely misunderstood the original article...
    +--  return sets[1][res[1]]*sets[idx][res[idx]]!=8
    +    return sets[1][res[1]]*sets[idx][res[idx]]=8
    +end function
     
    - procedure not8_show(sequence sets, sequence res)
    -     puts(1,"success: ")
    -     ?{sets[1][res[1]],sets[2][res[2]]}
    - end procedure
    +procedure not8_show(sequence sets, sequence res)
    +    puts(1,"success: ")
    +    ?{sets[1][res[1]],sets[2][res[2]]}
    +end procedure
     
    - sequence sets = {{"the","that","a"},
    -                  {"frog","elephant","thing"},
    -                  {"walked","treaded","grows"},
    -                  {"slowly","quickly"}}
    - sequence sets2 = repeat(tagset(11),3)
    - sequence sets3 = {{1, 2, 3}, {4, 5, 6}}
    - puts(1,"\nThe original:\n")
    - {} = amb(sets,pairable,AMB_Show)
    - puts(1,"\nSmall Pythagorean triples problem:\n")
    - {} = amb(sets2,pythagorean,pythag_show)
    - puts(1,"\nSome strange not 8 problem:\n") -- (now fixed)
    - {} = amb(sets3,not8,not8_show)
    -
    - with javascript_semantics
    - for m=1 to 20000 do
    -     integer n = sum(factors(m,-1))
    -     if m<n and m=sum(factors(n,-1)) then ?{m,n} end if
    - end for
    -( (len,words), ...)
        if(ws.len()>1){ // two or more anagrams
           r:=List(); n:=ws[0].len(); // length of these anagrams
           foreach idx,w in (ws.enumerate()){
    -	 foreach w2 in (ws[idx+1,*]){
    -	    if(Utils.zipWith('!=,w,w2).filter().len()==n)
    -	       r.write(T(w,w2));
    -	 }
    +     foreach w2 in (ws[idx+1,*]){
    +        if(Utils.zipWith('!=,w,w2).filter().len()==n)
    +           r.write(T(w,w2));
    +     }
           }
           if(r) return(r.insert(0,n));
        }
    diff --git a/Task/Anagrams-Deranged-anagrams/Zkl/anagrams-deranged-anagrams-2.zkl b/Task/Anagrams-Deranged-anagrams/Zkl/anagrams-deranged-anagrams-2.zkl
    index ce697554b4..bca11af0eb 100644
    --- a/Task/Anagrams-Deranged-anagrams/Zkl/anagrams-deranged-anagrams-2.zkl
    +++ b/Task/Anagrams-Deranged-anagrams/Zkl/anagrams-deranged-anagrams-2.zkl
    @@ -3,7 +3,7 @@ nws:=words.values.pump(List,fcn(ws){ //-->( (len,words), ...)
           n:=ws[0].len(); // length of these anagrams
           r:=Utils.Helpers.permute(ws).filter('wrap(ws2){
                 n == Utils.zipWith('!=,ws2.xplode()).filter().len();
    -	 });
    +     });
           if(r) return(n,r[0]); // L(L("glove","vogel"))-->L(5,L("glove","vogel"))
        }
        Void.Skip
    diff --git a/Task/Anagrams/00-TASK.txt b/Task/Anagrams/00-TASK.txt
    index 1668245967..c66b1c36f9 100644
    --- a/Task/Anagrams/00-TASK.txt
    +++ b/Task/Anagrams/00-TASK.txt
    @@ -1,7 +1,7 @@
     When two or more words are composed of the same characters, but in a different order, they are called [[wp:Anagram|anagrams]]. 
     
     ;Task
    -Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, 
    +Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt or [https://raw.githubusercontent.com/thundergnat/rc-run/refs/heads/master/rc/resources/unixdict.txt here], 
     
    find the sets of words that share the same characters that contain the most words in them. ;Related tasks diff --git a/Task/Anagrams/ALGOL-68/anagrams.alg b/Task/Anagrams/ALGOL-68/anagrams.alg index 8fe12076cc..d652d3bd06 100644 --- a/Task/Anagrams/ALGOL-68/anagrams.alg +++ b/Task/Anagrams/ALGOL-68/anagrams.alg @@ -55,7 +55,6 @@ ELSE END ); REF AARRAY words := INIT LOC AARRAY; - STRING word; WHILE NOT at eof DO STRING word; diff --git a/Task/Anagrams/Ada/anagrams.ada b/Task/Anagrams/Ada/anagrams.adb similarity index 100% rename from Task/Anagrams/Ada/anagrams.ada rename to Task/Anagrams/Ada/anagrams.adb diff --git a/Task/Anagrams/Arturo/anagrams.arturo b/Task/Anagrams/Arturo/anagrams.arturo index 9d417293a0..c6c5181269 100644 --- a/Task/Anagrams/Arturo/anagrams.arturo +++ b/Task/Anagrams/Arturo/anagrams.arturo @@ -5,7 +5,7 @@ anagrams: #[] loop wordset 'word [ anagram: sort to [:char] word unless key? anagrams anagram -> - anagrams\[anagram]: new [] + anagrams\[anagram]: [] anagrams\[anagram]: anagrams\[anagram] ++ word ] diff --git a/Task/Anagrams/COBOL/anagrams.cobol b/Task/Anagrams/COBOL/anagrams.cob similarity index 100% rename from Task/Anagrams/COBOL/anagrams.cobol rename to Task/Anagrams/COBOL/anagrams.cob diff --git a/Task/Anagrams/Crystal/anagrams.crystal b/Task/Anagrams/Crystal/anagrams.cr similarity index 100% rename from Task/Anagrams/Crystal/anagrams.crystal rename to Task/Anagrams/Crystal/anagrams.cr diff --git a/Task/Anagrams/Delphi/anagrams.delphi b/Task/Anagrams/Delphi/anagrams.pas similarity index 100% rename from Task/Anagrams/Delphi/anagrams.delphi rename to Task/Anagrams/Delphi/anagrams.pas diff --git a/Task/Anagrams/DuckDB/anagrams.duckdb b/Task/Anagrams/DuckDB/anagrams.duckdb new file mode 100644 index 0000000000..aaa0f5aad8 --- /dev/null +++ b/Task/Anagrams/DuckDB/anagrams.duckdb @@ -0,0 +1,20 @@ +# The MAP giving the frequency counts of characters in the given string +create or replace function spectrum(str) as ( + select histogram(c) + from (select unnest(regexp_extract_all(str,'.')) as c) +); + +# Find the anagram groups having the most members. +# Each group is sorted, and the groups are sorted by first word in the group. +with words as (from read_csv('unixdict.txt', header=false) _(word)), + histograms as (select word, spectrum(word) as h from words), + groups as (select h, count(h) as c from histograms group by h order by c desc), + mx as (select max(c) as mx from groups), + maximals as (select h from groups, mx where c = mx.mx), + results as (select (select array_agg(word).list_sort() + from histograms + where histograms.h = maximals.h ) as anagrams + from maximals) + select anagrams + from results + order by anagrams[1] ; diff --git a/Task/Anagrams/EasyLang/anagrams.easy b/Task/Anagrams/EasyLang/anagrams.easy new file mode 100644 index 0000000000..2e5fcff599 --- /dev/null +++ b/Task/Anagrams/EasyLang/anagrams.easy @@ -0,0 +1,46 @@ +global name$[] cnt[] . +func n2id n$ . + for id to len name$[] : if name$[id] = n$ : return id + name$[] &= n$ + cnt[] &= 0 + return id +. +func norm s$ . + d$[] = strchars s$ + for i = 1 to len d$[] - 1 + for j = i + 1 to len d$[] + if strcode d$[j] < strcode d$[i] : swap d$[j] d$[i] + . + . + n$ = strjoin d$[] "" + return n2id n$ +. +repeat + s$ = input + until s$ = "" + id = norm s$ + cnt[id] += 1 + max = higher max cnt[id] + w$[] &= s$ + wid[] &= id +. +for id to len name$[] + if cnt[id] = max + for i to len w$[] + if wid[i] = id : write w$[i] & " " + . + print "" + . +. +# +# a few lines of unixdict.txt, also works with all +input_data +abe +abed +abel +ablaze +able +ablution +angel +angle +angles diff --git a/Task/Anagrams/Elena/anagrams.elena b/Task/Anagrams/Elena/anagrams.elena index 65bb59e28f..be3a530398 100644 --- a/Task/Anagrams/Elena/anagrams.elena +++ b/Task/Anagrams/Elena/anagrams.elena @@ -13,9 +13,9 @@ extension op = self.toArray().ascendant().summarize(new StringWriter()); } -public program() +public Program() { - var start := now; + var start := Now; auto dictionary := new Map(); @@ -35,13 +35,13 @@ public program() dictionary.Values .quickSort::(former,later => former.Item2.Length > later.Item2.Length ) .top(20) - .forEach::(pair){ console.printLine(pair.Item2) }; + .forEach::(pair){ Console.printLine(pair.Item2) }; - var end := now; + var end := Now; var diff := end - start; - console.printLine("Time elapsed in msec:",diff.Milliseconds); + Console.printLine("Time elapsed in msec:",diff.Milliseconds); - console.readChar() + Console.readChar() } diff --git a/Task/Anagrams/Elixir/anagrams-1.elixir b/Task/Anagrams/Elixir/anagrams-1.ex similarity index 100% rename from Task/Anagrams/Elixir/anagrams-1.elixir rename to Task/Anagrams/Elixir/anagrams-1.ex diff --git a/Task/Anagrams/Elixir/anagrams-2.elixir b/Task/Anagrams/Elixir/anagrams-2.ex similarity index 100% rename from Task/Anagrams/Elixir/anagrams-2.elixir rename to Task/Anagrams/Elixir/anagrams-2.ex diff --git a/Task/Anagrams/Emacs-Lisp/anagrams-1.el b/Task/Anagrams/Emacs-Lisp/anagrams-1.el new file mode 100644 index 0000000000..9920fae43d --- /dev/null +++ b/Task/Anagrams/Emacs-Lisp/anagrams-1.el @@ -0,0 +1,87 @@ +(defun code-letters (str) + "Sort STR into alphabetized list of individual letters." + (sort (split-string str "" t) #'string<)) + +(defun code-letters-to-string (str) + "Sort STR alphabetically and combine into one string." + (apply #'concat (code-letters str))) + +(defun remove-periods (str) + "Remove periods (full stops) from STR." + (string-replace "." "" str)) + +(defun list-pair (str) + "Create paired list from STR, STR (unchanged) and alphabetized order of STR." + ;; Remove periods from alphabetized order to make regex matching easier + (let ((letter-list (remove-periods (code-letters-to-string str)))) + (list letter-list str))) + +(defun pair-up (words) + "Make list of lists of paired words, one alphabetized one original." + (let ((paired-list) + (temp-pair)) + (dolist (word words) + (setq temp-pair (list-pair word)) + (push temp-pair paired-list)) + paired-list)) + +(defun create-list-of-numbers (my-list) + "Create list of numbers from MY-LIST." + (let ((list-of-numbers)) + (dolist (one-pair my-list) + (push (car one-pair) list-of-numbers)) + list-of-numbers)) + +(defun get-largest-number (my-list) + "Find largest number in MY-LIST." + (let ((list-of-numbers)) + (setq list-of-numbers (create-list-of-numbers my-list)) + (apply #'max list-of-numbers))) + +(defun make-list-matching-words (coded-word-and-original number-and-code-pair) + "List original words whose code matches code in NUMBER-AND-CODE-PAIR." + (dolist (word-pair coded-word-and-original) + ;; test if coded word in CODED-WORD-AND-ORIGINAL matches + ;; coded word in NUMBER-AND-CODE-PAIR + (when (string= (nth 0 word-pair) (nth 1 number-and-code-pair)) + ;; insert the original word + (insert (format "%s " (nth 1 word-pair))))) + (insert "\n")) + +(defun count-anagrams () + "Count the number of anagrams in file wordlist.txt" + (let ((coded-word-and-original) + (just-coded-words) + (unique-coded-words) + (count-and-code) + (number-of-anagrams) + (largest-number)) + ;; Path below needs to be adapted to individual case + (find-file "~/Documents/Elisp/wordlist.txt") + (beginning-of-buffer) + ;; create list of lists of coded words and originals + (setq coded-word-and-original (pair-up (split-string (buffer-string) "\n"))) + (find-file "temp-all-coded") + (erase-buffer) + (dolist (number-and-code-pair coded-word-and-original) + ;; make list of just the coded words + (push (nth 0 number-and-code-pair) just-coded-words)) + (dolist (one-word just-coded-words) + ;; write list of coded words to buffer for later processing + (insert (format "%s\n" one-word))) + ;; create a list of coded words with no repetitions + (setq unique-coded-words (seq-uniq just-coded-words)) + (dolist (one-code unique-coded-words) + (find-file "temp-all-coded") + (beginning-of-buffer) + ;; count the number of times ONE-CODE appears in buffer + (setq number-of-anagrams (how-many (format "^%s$" one-code))) + (if (>= number-of-anagrams 1) ; eliminate "words" of zero length + (push (list number-of-anagrams one-code) count-and-code))) + (find-file "anagram-listing") + (erase-buffer) + (setq largest-number (get-largest-number count-and-code)) + (dolist (number-and-code-pair count-and-code) + ;; when the number in NUMBER-AND-CODE-PAIR = largest number of anagrams + (when (= (nth 0 number-and-code-pair) largest-number) + (make-list-matching-words coded-word-and-original number-and-code-pair))))) diff --git a/Task/Anagrams/Emacs-Lisp/anagrams-2.el b/Task/Anagrams/Emacs-Lisp/anagrams-2.el new file mode 100644 index 0000000000..4a6a2b9b3d --- /dev/null +++ b/Task/Anagrams/Emacs-Lisp/anagrams-2.el @@ -0,0 +1,74 @@ +(defun code-letters (str) + "Sort STR into alphabetized list of individual letters." + (sort (split-string str "" t) #'string<)) + +(defun code-letters-to-string (str) + "Sort STR alphabetically and combine into one string." + (apply #'concat (code-letters str))) + +(defun add-to-hash (key value table) + "If KEY exists, add VALUE to list of values. +If KEY does not exist, associate value with KEY." + (let ((current-values)) + (if (gethash key table) + (progn + (setq current-values (gethash key table)) + (setq current-values (push value current-values)) + (puthash key current-values table)) + (puthash key (list value) table)))) + +(defun create-list-of-numbers (hash-table) + "Create a list of numbers from HASH-TABLE." + (let ((current-number) + (list-of-numbers)) + (setq list-of-numbers (list)) ; omit? + (maphash (lambda (key value) + (setq current-number (car (gethash key hash-table))) + (push current-number list-of-numbers)) + hash-table) + list-of-numbers)) + +(defun find-largest-number-in-hash (hash-table) + "Find largest number in HASH-TABLE." + (let ((list-of-numbers)) + (setq list-of-numbers (create-list-of-numbers hash-table)) + (apply #'max list-of-numbers))) + +(defun find-longest-lists-of-anagrams (&optional file) + "Find the set(s) of largest number of anagrams in file wordlist.txt" + (let ((largest-number) + (hash-key) + (dictionary-table (make-hash-table :test 'equal))) + ;; Path and filename below needs to be adapted to individual case if + ;; FILE is *not* passed to this function + (with-temp-buffer + (insert-file-contents (or file "~/Documents/Elisp/wordlist.txt")) + (beginning-of-buffer) + ;; set up hash table with key and word(s) + ;; key = letters of word, but with letters in + ;; alphabetical order. Create list word(s) associated + ;; with key. + (dolist (current-word (split-string (buffer-string) "\n")) + (setq hash-key (code-letters-to-string current-word)) + (add-to-hash hash-key current-word dictionary-table)) + ;; Count number of anagram words + (maphash (lambda (key value) + "Add number of anagram words to VALUE." + (add-to-hash key (length (gethash key dictionary-table)) dictionary-table)) + dictionary-table) + ;; find the size of the largest list(s) of anagrams + (setq largest-number (find-largest-number-in-hash dictionary-table))) + ;; set up empty buffer to show results + (with-current-buffer (pop-to-buffer "anagram-listing") + (erase-buffer) + ;; show results + (maphash (lambda (key value) + "Display longest lists of anagrams." + (when (= largest-number (car (gethash key dictionary-table))) + (mapc + (lambda (element) + "Insert ELEMENT followed by one space in buffer." + (insert (format "%s " element))) + (cdr (gethash key dictionary-table))) + (insert "\n"))) + dictionary-table)))) diff --git a/Task/Anagrams/Euphoria/anagrams.euphoria b/Task/Anagrams/Euphoria/anagrams.eu similarity index 100% rename from Task/Anagrams/Euphoria/anagrams.euphoria rename to Task/Anagrams/Euphoria/anagrams.eu diff --git a/Task/Anagrams/Julia/anagrams.julia b/Task/Anagrams/Julia/anagrams.jl similarity index 100% rename from Task/Anagrams/Julia/anagrams.julia rename to Task/Anagrams/Julia/anagrams.jl diff --git a/Task/Anagrams/Kotlin/anagrams.kotlin b/Task/Anagrams/Kotlin/anagrams.kts similarity index 100% rename from Task/Anagrams/Kotlin/anagrams.kotlin rename to Task/Anagrams/Kotlin/anagrams.kts diff --git a/Task/Anagrams/OCaml/anagrams.ocaml b/Task/Anagrams/OCaml/anagrams.ml similarity index 100% rename from Task/Anagrams/OCaml/anagrams.ocaml rename to Task/Anagrams/OCaml/anagrams.ml diff --git a/Task/Anagrams/PascalABC.NET/anagrams.pas b/Task/Anagrams/PascalABC.NET/anagrams.pas new file mode 100644 index 0000000000..937517fc8e --- /dev/null +++ b/Task/Anagrams/PascalABC.NET/anagrams.pas @@ -0,0 +1,7 @@ +begin + var s := System.Net.WebClient.Create.DownloadString('http://wiki.puzzlers.org/pub/wordlists/unixdict.txt'); + var words := s.Split; + var groups := words.GroupBy(word -> word.Order.JoinToString); + var maxCount := groups.Max(gr -> gr.Count); + groups.Where(gr -> gr.Count = maxCount).PrintLines; +end. diff --git a/Task/Anagrams/Pluto/anagrams.pluto b/Task/Anagrams/Pluto/anagrams.pluto new file mode 100644 index 0000000000..5a71e6cda7 --- /dev/null +++ b/Task/Anagrams/Pluto/anagrams.pluto @@ -0,0 +1,20 @@ +local fmt = require "fmt" + +local word_list = "unixdict.txt" -- local copy +local nl = os.platform == "windows" ? "\r\n" : "\n" +local words = io.contents(word_list):rstrip():split(nl):map(|w| -> w:strip()) +local word_map = {} +for words as word do + local letters = word:split("") + letters:sort() + local sorted_word = letters:concat("") + if word_map[sorted_word] then + word_map[sorted_word]:insert(word) + else + word_map[sorted_word] = {word} + end +end +local most = word_map:values():reduce(|max, v| -> #v > max ? #v : max, 0) +for key, val in word_map do + if #word_map[key] == most then fmt.lprint(val) end +end diff --git a/Task/Anagrams/PowerShell/anagrams-1.psh b/Task/Anagrams/PowerShell/anagrams-1.ps1 similarity index 100% rename from Task/Anagrams/PowerShell/anagrams-1.psh rename to Task/Anagrams/PowerShell/anagrams-1.ps1 diff --git a/Task/Anagrams/PowerShell/anagrams-2.psh b/Task/Anagrams/PowerShell/anagrams-2.ps1 similarity index 100% rename from Task/Anagrams/PowerShell/anagrams-2.psh rename to Task/Anagrams/PowerShell/anagrams-2.ps1 diff --git a/Task/Anagrams/Rebol/anagrams.rebol b/Task/Anagrams/Rebol/anagrams.rebol new file mode 100644 index 0000000000..b870201fcb --- /dev/null +++ b/Task/Anagrams/Rebol/anagrams.rebol @@ -0,0 +1,29 @@ +Rebol [ + title: "Rosetta code: Anagrams" + file: %Anagrams.r3 + url: https://rosettacode.org/wiki/Anagrams + note: "Based on Red language implementation!" +] +;; Build an anagram index from a local unix dictionary file and print the largest anagram families +m: make map! [] 25000 ;; pre-size a map for better performance (target ~25,000 keys) + +;; Ensure unixdict.txt exists locally; if not, download it +unless exists? %unixdict.txt [ + write %unixdict.txt read https://raw.githubusercontent.com/thundergnat/rc-run/refs/heads/master/rc/resources/unixdict.txt +] +;; Track the size of the largest anagram group found so far +maxx: 0 +;; Read the dictionary line-by-line +foreach word read/lines %unixdict.txt [ + sword: sort copy word ;; key = sorted letters of the word (anagram signature) + either find m sword [ ;; if we already have this signature + append m/:sword word ;; add the word to that anagram group + maxx: max maxx length? m/:sword ;; update maximum group size if needed + ][ ;; otherwise create a new group with this word + put m sword append copy [] word + ] +] +;; Print all groups that match the maximum size (i.e., largest anagram families) +foreach [k v] m [ + if maxx = length? v [print v] +] diff --git a/Task/Anagrams/Rust/anagrams-1.rust b/Task/Anagrams/Rust/anagrams-1.rs similarity index 100% rename from Task/Anagrams/Rust/anagrams-1.rust rename to Task/Anagrams/Rust/anagrams-1.rs diff --git a/Task/Anagrams/Rust/anagrams-2.rust b/Task/Anagrams/Rust/anagrams-2.rs similarity index 100% rename from Task/Anagrams/Rust/anagrams-2.rust rename to Task/Anagrams/Rust/anagrams-2.rs diff --git a/Task/Anagrams/Scheme/anagrams.ss b/Task/Anagrams/Scheme/anagrams.scm similarity index 100% rename from Task/Anagrams/Scheme/anagrams.ss rename to Task/Anagrams/Scheme/anagrams.scm diff --git a/Task/Anagrams/TAV/anagrams.tav b/Task/Anagrams/TAV/anagrams.tav new file mode 100644 index 0000000000..6b940f7f6e --- /dev/null +++ b/Task/Anagrams/TAV/anagrams.tav @@ -0,0 +1,38 @@ +\( Find anagrams (words with the same set of letters) + Words are the lines of an input file. + Sorting the letters of the word gives the key for a map + having a list (row) of all words so far. +\) +\+ stdlib +main(parms):+ + parms[1] =~ 'unixdict.txt' \ default input file + wordmap =: get words from parms[1] + maxw =: wordmap.maxlen + ?# idx =: map wordmap give keys ascending + words =: wordmap{idx} + ? maxw = words.count + print words::join values by ', ' + +\ read the file (infn) and return a map +get words from (infn): + res =: new map \ create the result map + res.maxlen =: 0 + ?# line =: file infn give lines \ or: infn::give lines + add line to res + :> res + +\ add a word to the map +add (word) to (amap): + idx =: sort characters of word::case to upper + row =: amap{idx} \ get indexed words + ? row = () \ new entry if void + row =: new row + amap{idx} =: row + row[] =: word \ add new entry + amap.maxlen =: maximum of amap.maxlen, row.count + +\ Sort the characters of a string +sort characters of (s): + sr =: string s as character row + row sr sort ascending + :> row sr join values as string \ without separator diff --git a/Task/Anagrams/Uiua/anagrams.uiua b/Task/Anagrams/Uiua/anagrams.uiua new file mode 100644 index 0000000000..8a388e72cb --- /dev/null +++ b/Task/Anagrams/Uiua/anagrams.uiua @@ -0,0 +1,12 @@ +# Experimental! +# The "Experimental!" comment above is required by the interpreter since &fetch is currently an experimental feature and is subject to change. + +# Grab the entire contents of the page as an array of bytes, then decode it into a string of text. +°utf₈ &fetch "https://raw.githubusercontent.com/thundergnat/rc-run/refs/heads/master/rc/resources/unixdict.txt" +°/$"_\n_" # Split the string into words by line breaks +# Group words that are anagrams together. +# This is done by first sorting the letters in each word to make a "key" and grouping words together that have the same key. +⊕□⊸(⊛⍚⍆) +# Count the number of words in each group, and keep only the groups that have the maximum number of words of any group. +▽⊸(=⊸/↥≡◇⧻) +≡&p # Print each group one at a time diff --git a/Task/Anagrams/Ursalang/anagrams.ursa b/Task/Anagrams/Ursalang/anagrams.ursa new file mode 100644 index 0000000000..54ebff6dac --- /dev/null +++ b/Task/Anagrams/Ursalang/anagrams.ursa @@ -0,0 +1,21 @@ +use js.fetch +let text = fetch("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt").text() +let words = text.split("\n") + +let anagrams = {} +for word in words.iter() { + let sorted = word.split("").sorted().join("") + if anagrams.get(sorted) == null { + anagrams.set(sorted, []) + } + anagrams.get(sorted).push(word) +} + +var most_anagrams = 0 +for ana in anagrams.values() { + if ana.len() > most_anagrams {most_anagrams := ana.len()} +} + +for ana in anagrams.values() { + if ana.len() == most_anagrams {print(ana)} +} diff --git a/Task/Anagrams/V-(Vlang)/anagrams.v b/Task/Anagrams/V-(Vlang)/anagrams.v index 599471f1fa..85e11f3fdb 100644 --- a/Task/Anagrams/V-(Vlang)/anagrams.v +++ b/Task/Anagrams/V-(Vlang)/anagrams.v @@ -1,26 +1,18 @@ import os fn main(){ - words := os.read_lines('unixdict.txt')? - + words := os.read_lines('unixdict.txt')! mut m := map[string][]string{} mut ma := 0 for word in words { mut letters := word.split('') letters.sort() sorted_word := letters.join('') - if sorted_word in m { - m[sorted_word] << word - } else { - m[sorted_word] = [word] - } - if m[sorted_word].len > ma { - ma = m[sorted_word].len - } + if sorted_word in m {m[sorted_word] << word} + else {m[sorted_word] = [word]} + if m[sorted_word].len > ma {ma = m[sorted_word].len} } for _, a in m { - if a.len == ma { - println(a) - } + if a.len == ma {println(a)} } } diff --git a/Task/Anagrams/VBScript/anagrams.vb b/Task/Anagrams/VBScript/anagrams.vbs similarity index 100% rename from Task/Anagrams/VBScript/anagrams.vb rename to Task/Anagrams/VBScript/anagrams.vbs diff --git a/Task/Angle-difference-between-two-bearings/8th/angle-difference-between-two-bearings.8th b/Task/Angle-difference-between-two-bearings/8th/angle-difference-between-two-bearings.8th new file mode 100644 index 0000000000..2c80bde6fe --- /dev/null +++ b/Task/Angle-difference-between-two-bearings/8th/angle-difference-between-two-bearings.8th @@ -0,0 +1,43 @@ +\ diff-bearings.8th +\ Rosetta Code -- angle difference between two bearings +\ by John I. Helmers 2026.04.04 +\ 8th version 26.02 Professional + +11 ## \ sets the precision to 11 decimal places + +\ data array +[ [ 20 , 45 ] , [ -45 , 45 ] , [ -85 , 90 ] , [ -95 , 90 ] , [ -45 , 125 ] , [ -45 , 145 ] , [ 29.4803 , -88.6381 ] , [ -78.3251 , -159.036 ] ] constant BEARINGS + +\ test array +[ [ -70099.74233810938 , 29840.67437876723 ] , [ -165313.6666297357 , 33693.9894517456 ] , [ 1174.8380510598456 , -154146.66490124757 ] , [ 60175.77306795546 , 42213.07192354373 ] ] constant TEST + +360 constant LIMIT \ sets circle limit to 360 degrees + +: make-big-floats \ [ a0, a1, a2 ... ] -- [ a'0, a'1, a'2 ... ] + ( ( n:bfloat ) a:map ) a:map ; + +: subtract-bearings \ [b1,b2] -- n + 0 a:@ swap 1 a:@ rot n:- ; + +: simplify LIMIT n:fmod ; + +: find-acute \ n -- n + dup 180 > if 360 n:- else dup -180 < if 360 n:+ then then ; + +: compute-angles \ a -- a' + ( subtract-bearings simplify find-acute 2 swap a:! drop ) a:each! ; + +: .table-header \ -- +" b1___________________ b2__________________ diff_________________" . cr ; + +: .lines \ a -- | print each line of table + ( ( "%>24.11f" s:strfmt . ) a:each! drop cr ) a:each! ; + +: .table .table-header .lines ; + +: process-data make-big-floats compute-angles ; + +: do-it BEARINGS process-data .table drop cr + TEST process-data .table drop cr ; + +do-it bye diff --git a/Task/Angle-difference-between-two-bearings/ANSI-BASIC/angle-difference-between-two-bearings.basic b/Task/Angle-difference-between-two-bearings/ANSI-BASIC/angle-difference-between-two-bearings.basic new file mode 100644 index 0000000000..9a7c6b0d99 --- /dev/null +++ b/Task/Angle-difference-between-two-bearings/ANSI-BASIC/angle-difference-between-two-bearings.basic @@ -0,0 +1,33 @@ +100 REM Angle difference between two bearings +110 DECLARE EXTERNAL FUNCTION GetDiff +120 REM +130 SUB PrintRow(B1, B2) +140 PRINT USING "#######.###### #######.###### #######.######": B1, B2, GetDiff(B1, B2) +150 END SUB +160 REM +170 print "Input in -180 to +180 range" +180 PRINT " Bearing 1 Bearing 2 Difference" +190 CALL PrintRow(20.0, 45.0) +200 CALL PrintRow(-45.0, 45.0) +210 CALL PrintRow(-85.0, 90.0) +220 CALL PrintRow(-95.0, 90.0) +230 CALL PrintRow(-45.0, 125.0) +240 CALL PrintRow(-45.0, 145.0) +250 CALL PrintRow(-45.0, 125.0) +260 CALL PrintRow(-45.0, 145.0) +270 CALL PrintRow(29.4803, -88.6381) +280 CALL PrintRow(-78.3251, -159.036) +290 PRINT +300 PRINT "Input in wider range" +310 PRINT " Bearing 1 Bearing 2 Difference" +320 CALL PrintRow(-70099.74233810938, 29840.67437876723) +330 CALL PrintRow(-165313.6666297357, 33693.9894517456) +340 CALL PrintRow(1174.8380510598456, -154146.66490124757) +350 CALL PrintRow(60175.77306795546, 42213.07192354373) +360 END +370 REM +380 EXTERNAL FUNCTION GetDiff (B1, B2) +390 LET R = MOD(B2 - B1, 360.0) +400 IF R >= 180.0 THEN LET R = R - 360.0 +410 LET GetDiff = R +420 END FUNCTION diff --git a/Task/Angle-difference-between-two-bearings/Ada/angle-difference-between-two-bearings.ada b/Task/Angle-difference-between-two-bearings/Ada/angle-difference-between-two-bearings.adb similarity index 100% rename from Task/Angle-difference-between-two-bearings/Ada/angle-difference-between-two-bearings.ada rename to Task/Angle-difference-between-two-bearings/Ada/angle-difference-between-two-bearings.adb diff --git a/Task/Angle-difference-between-two-bearings/Agena/angle-difference-between-two-bearings.agena b/Task/Angle-difference-between-two-bearings/Agena/angle-difference-between-two-bearings.agena new file mode 100644 index 0000000000..682112bf58 --- /dev/null +++ b/Task/Angle-difference-between-two-bearings/Agena/angle-difference-between-two-bearings.agena @@ -0,0 +1,34 @@ +# Angle difference between two bearings + +proc getdiff(b1, b2) is + r := (b2 - b1) symmod 360.0; + if r >= 180.0 then r -:= 360.0 fi; + if r < -180.0 then r +:= 360.0 fi; + return r +end; + +proc printrow(b1, b2) is + printf("%14.6f %14.6f %14.6f\n", b1, b2, getdiff(b1, b2)) +end; + +scope + print("Input in -180 to +180 range"); + print(" Bearing 1 Bearing 2 Difference"); + printrow(20.0, 45.0); + printrow(-45.0, 45.0); + printrow(-85.0, 90.0); + printrow(-95.0, 90.0); + printrow(-45.0, 125.0); + printrow(-45.0, 145.0); + printrow(-45.0, 125.0); + printrow(-45.0, 145.0); + printrow(29.4803, -88.6381); + printrow(-78.3251, -159.036); + print(); + print("Input in wider range"); + print(" Bearing 1 Bearing 2 Difference"); + printrow(-70099.74233810938, 29840.67437876723); + printrow(-165313.6666297357, 33693.9894517456); + printrow(1174.8380510598456, -154146.66490124757); + printrow(60175.77306795546, 42213.07192354373) +epocs diff --git a/Task/Angle-difference-between-two-bearings/AppleScript/angle-difference-between-two-bearings.applescript b/Task/Angle-difference-between-two-bearings/AppleScript/angle-difference-between-two-bearings.applescript new file mode 100644 index 0000000000..21f8f17583 --- /dev/null +++ b/Task/Angle-difference-between-two-bearings/AppleScript/angle-difference-between-two-bearings.applescript @@ -0,0 +1,18 @@ +on diff_bearing({b1, b2}) + set r to (b2 - b1) mod 360 + if r > 180 then + r - 360 + else if r < -180 then + r + 360 + else + r + end if +end diff_bearing + +set test_bearings to {{20, 45}, {-45, 45}, {-85, 90}, {-95, 90}, {-45, 125}, {-45, 145}, {29.4803, -88.6381}, {-78.3251, -159.036}} + +set big_bearings to {{-7.00997423381094E+4, 2.98406743787672E+4}, {-1.65313666629736E+5, 3.36939894517456E+4}, {1174.838051059846, -1.54146664901248E+5}, {6.01757730679555E+4, 4.22130719235437E+4}} + +repeat with b in test_bearings & big_bearings + log diff_bearing(b) +end repeat diff --git a/Task/Angle-difference-between-two-bearings/Ballerina/angle-difference-between-two-bearings.ballerina b/Task/Angle-difference-between-two-bearings/Ballerina/angle-difference-between-two-bearings.ballerina new file mode 100644 index 0000000000..213bb46d14 --- /dev/null +++ b/Task/Angle-difference-between-two-bearings/Ballerina/angle-difference-between-two-bearings.ballerina @@ -0,0 +1,34 @@ +import ballerina/io; + +function subtract(float b1, float b2) returns float { + float d = (b2 - b1) % 360.0; + if d < -180.0 { d += 360.0; } + if d >= 180.0 { d -= 360.0; } + return d.round(4); +} + +public function main() { + float[][] pairs = [ + [ 20, 45], + [-45, 45], + [-85, 90], + [-95, 90], + [-45, 125], + [-45, 145], + [ 29.4803, -88.6381], + [-78.3251, -159.036], + [-70099.74233810938, 29840.67437876723], + [-165313.6666297357, 33693.9894517456], + [1174.8380510598456, -154146.66490124757], + [60175.77306795546, 42213.07192354373] + ]; + + io:println("Differences (to 4dp) between these bearings:"); + foreach var pair in pairs { + float p0 = pair[0]; + float p1 = pair[1]; + float diff = subtract(p0, p1); + string offset = p0 < 0.0 ? " " : " "; + io:println(`${offset}${p0} and ${p1} -> ${diff}`); + } +} diff --git a/Task/Angle-difference-between-two-bearings/C++/angle-difference-between-two-bearings.cpp b/Task/Angle-difference-between-two-bearings/C++/angle-difference-between-two-bearings.cpp index af35a7815c..92cb3f68b7 100644 --- a/Task/Angle-difference-between-two-bearings/C++/angle-difference-between-two-bearings.cpp +++ b/Task/Angle-difference-between-two-bearings/C++/angle-difference-between-two-bearings.cpp @@ -2,34 +2,40 @@ #include using namespace std; -double getDifference(double b1, double b2) { - double r = fmod(b2 - b1, 360.0); - if (r < -180.0) - r += 360.0; - if (r >= 180.0) - r -= 360.0; - return r; +double getDifference(double b1, double b2) +{ + double r = fmod(b2 - b1, 360.0); + if (r < -180.0) + r += 360.0; + if (r >= 180.0) + r -= 360.0; + return r; +} + +inline void printRow(double b1, double b2) +{ + cout << getDifference(b1, b2) << endl; } int main() { - cout << "Input in -180 to +180 range" << endl; - cout << getDifference(20.0, 45.0) << endl; - cout << getDifference(-45.0, 45.0) << endl; - cout << getDifference(-85.0, 90.0) << endl; - cout << getDifference(-95.0, 90.0) << endl; - cout << getDifference(-45.0, 125.0) << endl; - cout << getDifference(-45.0, 145.0) << endl; - cout << getDifference(-45.0, 125.0) << endl; - cout << getDifference(-45.0, 145.0) << endl; - cout << getDifference(29.4803, -88.6381) << endl; - cout << getDifference(-78.3251, -159.036) << endl; - - cout << "Input in wider range" << endl; - cout << getDifference(-70099.74233810938, 29840.67437876723) << endl; - cout << getDifference(-165313.6666297357, 33693.9894517456) << endl; - cout << getDifference(1174.8380510598456, -154146.66490124757) << endl; - cout << getDifference(60175.77306795546, 42213.07192354373) << endl; + cout << "Input in -180 to +180 range" << endl; + printRow(20.0, 45.0); + printRow(-45.0, 45.0); + printRow(-85.0, 90.0); + printRow(-95.0, 90.0); + printRow(-45.0, 125.0); + printRow(-45.0, 145.0); + printRow(-45.0, 125.0); + printRow(-45.0, 145.0); + printRow(29.4803, -88.6381); + printRow(-78.3251, -159.036); - return 0; + cout << endl << "Input in wider range" << endl; + printRow(-70099.74233810938, 29840.67437876723); + printRow(-165313.6666297357, 33693.9894517456); + printRow(1174.8380510598456, -154146.66490124757); + printRow(60175.77306795546, 42213.07192354373); + + return 0; } diff --git a/Task/Angle-difference-between-two-bearings/COBOL/angle-difference-between-two-bearings.cobol b/Task/Angle-difference-between-two-bearings/COBOL/angle-difference-between-two-bearings.cob similarity index 100% rename from Task/Angle-difference-between-two-bearings/COBOL/angle-difference-between-two-bearings.cobol rename to Task/Angle-difference-between-two-bearings/COBOL/angle-difference-between-two-bearings.cob diff --git a/Task/Angle-difference-between-two-bearings/Crystal/angle-difference-between-two-bearings.cr b/Task/Angle-difference-between-two-bearings/Crystal/angle-difference-between-two-bearings.cr new file mode 100644 index 0000000000..24aa61f987 --- /dev/null +++ b/Task/Angle-difference-between-two-bearings/Crystal/angle-difference-between-two-bearings.cr @@ -0,0 +1,14 @@ +def angle_diff (a1, a2) + diff = (a2 - a1) % 360 + diff -= 360 if diff > +180 + diff +end + +rows = [{20, 45}, {-45, 45}, {-85, 90}, {-95, 90}, {-45, 125}, {-45, 145}, + {29.4803, -88.6381}, {-78.3251, -159.036}, + {-70099.74233810938, 29840.67437876723}, + {-165313.6666297357, 33693.9894517456}, + {1174.8380510598456, -154146.66490124757}, + {60175.77306795546, 42213.07192354373}].each do |b1, b2| + puts "Angle difference between %12.4f and %12.4f is %9.4f°" % { b1, b2, angle_diff(b1, b2) } +end diff --git a/Task/Angle-difference-between-two-bearings/EasyLang/angle-difference-between-two-bearings.easy b/Task/Angle-difference-between-two-bearings/EasyLang/angle-difference-between-two-bearings.easy index fbe96a9106..052ea0af48 100644 --- a/Task/Angle-difference-between-two-bearings/EasyLang/angle-difference-between-two-bearings.easy +++ b/Task/Angle-difference-between-two-bearings/EasyLang/angle-difference-between-two-bearings.easy @@ -7,7 +7,7 @@ func angdiff a b . . return r . -proc pd a b . . +proc pd a b . print b & " " & a & " -> " & angdiff a b . pd 20 45 diff --git a/Task/Angle-difference-between-two-bearings/Julia/angle-difference-between-two-bearings.julia b/Task/Angle-difference-between-two-bearings/Julia/angle-difference-between-two-bearings.jl similarity index 100% rename from Task/Angle-difference-between-two-bearings/Julia/angle-difference-between-two-bearings.julia rename to Task/Angle-difference-between-two-bearings/Julia/angle-difference-between-two-bearings.jl diff --git a/Task/Angle-difference-between-two-bearings/Kotlin/angle-difference-between-two-bearings.kotlin b/Task/Angle-difference-between-two-bearings/Kotlin/angle-difference-between-two-bearings.kts similarity index 100% rename from Task/Angle-difference-between-two-bearings/Kotlin/angle-difference-between-two-bearings.kotlin rename to Task/Angle-difference-between-two-bearings/Kotlin/angle-difference-between-two-bearings.kts diff --git a/Task/Angle-difference-between-two-bearings/Langur/angle-difference-between-two-bearings.langur b/Task/Angle-difference-between-two-bearings/Langur/angle-difference-between-two-bearings.langur new file mode 100644 index 0000000000..469a77ae69 --- /dev/null +++ b/Task/Angle-difference-between-two-bearings/Langur/angle-difference-between-two-bearings.langur @@ -0,0 +1,26 @@ +val diff = fn(b1 number, b2 number) { + val r = (b2 - b1) mod 360 + if r > 180 { r - 360 } else { r } +} + +val pairs = [ + [ 20, 45], + [-45, 45], + [-85, 90], + [-95, 90], + [-45, 125], + [-45, 145], + [ 29.4803, -88.6381], + [-78.3251, -159.036], + [-70099.74233810938, 29840.67437876723], + [-165313.6666297357, 33693.9894517456], + [1174.8380510598456, -154146.66490124757], + [60175.77306795546, 42213.07192354373], +] + +writeln " b1 b2 diff" +writeln "-" * 63 + +for b in pairs { + writeln "{{b[1] : 21}}{{b[2] : 21}}{{diff(b[1], b[2]) : 21}}" +} diff --git a/Task/Angle-difference-between-two-bearings/Maxima/angle-difference-between-two-bearings.maxima b/Task/Angle-difference-between-two-bearings/Maxima/angle-difference-between-two-bearings.maxima new file mode 100644 index 0000000000..343fb0dcaf --- /dev/null +++ b/Task/Angle-difference-between-two-bearings/Maxima/angle-difference-between-two-bearings.maxima @@ -0,0 +1,16 @@ +diff_bearing(b1, b2) := block( + r: mod(b2-b1, 360), + if r>180 then r-360 else r)$ + +test_bearings: [[20, 45], [-45, 45], [-85, 90], +[-95, 90], [-45, 125], [-45, 145], +[29.4803, -88.6381], [-78.3251, -159.036]]$ + +big_bearings: [[-70099.74233810938, 29840.67437876723], + [-165313.6666297357, 33693.9894517456], + [1174.8380510598456, -154146.66490124757], + [60175.77306795546, 42213.07192354373]]$ + +db_unary(list) := map(lambda([l], apply(diff_bearing, l)), list)$ +db_unary(test_bearings); +db_unary(big_bearings); diff --git a/Task/Angle-difference-between-two-bearings/OCaml/angle-difference-between-two-bearings.ocaml b/Task/Angle-difference-between-two-bearings/OCaml/angle-difference-between-two-bearings.ml similarity index 100% rename from Task/Angle-difference-between-two-bearings/OCaml/angle-difference-between-two-bearings.ocaml rename to Task/Angle-difference-between-two-bearings/OCaml/angle-difference-between-two-bearings.ml diff --git a/Task/Angle-difference-between-two-bearings/PHP/angle-difference-between-two-bearings.php b/Task/Angle-difference-between-two-bearings/PHP/angle-difference-between-two-bearings.php new file mode 100644 index 0000000000..0cec699805 --- /dev/null +++ b/Task/Angle-difference-between-two-bearings/PHP/angle-difference-between-two-bearings.php @@ -0,0 +1,38 @@ + 180.0) + $r -= 360.0; + if ($r < -180.0) + $r += 360.0; + return $r; + } + + function echo_row($b1, $b2) { + echo str_pad(number_format($b1, 6, ".", ""), 14, " ", STR_PAD_LEFT).' '; + echo str_pad(number_format($b2, 6, ".", ""), 14, " ", STR_PAD_LEFT).' '; + echo str_pad(number_format(get_diff($b1, $b2), 6), 14, " ", STR_PAD_LEFT); + echo "\n"; + } + + echo "Input in -180 to +180 range\n"; + echo " Bearing 1 Bearing 2 Difference\n"; + echo_row(20.0, 45.0); + echo_row(-45.0, 45.0); + echo_row(-85.0, 90.0); + echo_row(-95.0, 90.0); + echo_row(-45.0, 125.0); + echo_row(-45.0, 145.0); + echo_row(-45.0, 125.0); + echo_row(-45.0, 145.0); + echo_row(29.4803, -88.6381); + echo_row(-78.3251, -159.036); + echo "\nInput in wider range\n"; + echo " Bearing 1 Bearing 2 Difference\n"; + echo_row(-70099.74233810938, 29840.67437876723); + echo_row(-165313.6666297357, 33693.9894517456); + echo_row(1174.8380510598456, -154146.66490124757); + echo_row(60175.77306795546, 42213.07192354373); +?> diff --git a/Task/Angle-difference-between-two-bearings/Pascal-P/angle-difference-between-two-bearings.pas b/Task/Angle-difference-between-two-bearings/Pascal-P/angle-difference-between-two-bearings.pas new file mode 100644 index 0000000000..597ba6ee6b --- /dev/null +++ b/Task/Angle-difference-between-two-bearings/Pascal-P/angle-difference-between-two-bearings.pas @@ -0,0 +1,46 @@ +program anglebearings(output); + (* Angle difference between two bearings *) + + function rmod(x1, x2: real): real; + begin + rmod := x1 - trunc(x1 / x2) * x2; + end; + + function getdiff(b1, b2: real): real; + var + r: real; + begin + r := rmod((b2 - b1), 360.0); + if r >= 180.0 then + r := r - 360.0; + if r < -180.0 then + r := r + 360.0; + getdiff := r; + end; + + procedure writerow(b1, b2: real); + begin + writeln(b1: 14, ' ', b2: 14, ' ', getdiff(b1, b2):14); + end; + +begin + writeln('Input in -180 to +180 range'); + writeln(' Bearing 1 Bearing 2 Difference'); + writerow(20.0, 45.0); + writerow(-45.0, 45.0); + writerow(-85.0, 90.0); + writerow(-95.0, 90.0); + writerow(-45.0, 125.0); + writerow(-45.0, 145.0); + writerow(-45.0, 125.0); + writerow(-45.0, 145.0); + writerow(29.4803, -88.6381); + writerow(-78.3251, -159.036); + writeln; + writeln('Input in wider range'); + writeln(' Bearing 1 Bearing 2 Difference'); + writerow(-70099.74233810938, 29840.67437876723); + writerow(-165313.6666297357, 33693.9894517456); + writerow(1174.8380510598456, -154146.66490124757); + writerow(60175.77306795546, 42213.07192354373) +end. diff --git a/Task/Angle-difference-between-two-bearings/PascalABC.NET/angle-difference-between-two-bearings.pas b/Task/Angle-difference-between-two-bearings/PascalABC.NET/angle-difference-between-two-bearings.pas new file mode 100644 index 0000000000..7886d30040 --- /dev/null +++ b/Task/Angle-difference-between-two-bearings/PascalABC.NET/angle-difference-between-two-bearings.pas @@ -0,0 +1,16 @@ +function delta(b1, b2: real): real; +begin + result := (b2 - b1) - Trunc((b2 - b1) / 360.0) * 360.0; + if result < -180.0 then result += 360.0 + else if result >= 180.0 then result -= 360.0 +end; + +begin + var testVectors := + |(20.00, 45.00), (-45.00, 45.00), (-85.00, 90.00), + (-95.00, 90.00), (-45.00, 125.00), (-45.00, 145.00), + (29.48, -88.64), (-78.33, -159.04), (-70099.74, 29840.67), + (-165313.67, 33693.99), (1174.84, -154146.66), (60175.77, 42213.07)|; + foreach var vector in testVectors do + writeln(vector[0]:10:2, vector[1]:12:2, delta(vector[0], vector[1]):10:2); +end. diff --git a/Task/Angle-difference-between-two-bearings/Pluto/angle-difference-between-two-bearings.pluto b/Task/Angle-difference-between-two-bearings/Pluto/angle-difference-between-two-bearings.pluto new file mode 100644 index 0000000000..afb336106a --- /dev/null +++ b/Task/Angle-difference-between-two-bearings/Pluto/angle-difference-between-two-bearings.pluto @@ -0,0 +1,31 @@ +require "math2" + +local function subtract(b1, b2) + local d = (b2 - b1) % 360 + if d < -180 then d += 360 end + if d >= 180 then d -= 360 end + return math.toplaces(d, 4) +end + +local pairs = { + { 20, 45}, + {-45, 45}, + {-85, 90}, + {-95, 90}, + {-45, 125}, + {-45, 145}, + { 29.4803, -88.6381}, + {-78.3251, -159.036}, + {-70099.74233810938, 29840.67437876723}, + {-165313.6666297357, 33693.9894517456}, + {1174.8380510598456, -154146.66490124757}, + {60175.77306795546, 42213.07192354373} +} + +print("Differences (to 4dp) between these bearings:") +for pairs as pair do + local [p1, p2] = pair + local diff = subtract(p1, p2) + local offset = p1 < 0 ? " " : " " + print($"{offset}{p1} and {p2} -> {diff}") +end diff --git a/Task/Angle-difference-between-two-bearings/PowerShell/angle-difference-between-two-bearings-1.psh b/Task/Angle-difference-between-two-bearings/PowerShell/angle-difference-between-two-bearings-1.ps1 similarity index 100% rename from Task/Angle-difference-between-two-bearings/PowerShell/angle-difference-between-two-bearings-1.psh rename to Task/Angle-difference-between-two-bearings/PowerShell/angle-difference-between-two-bearings-1.ps1 diff --git a/Task/Angle-difference-between-two-bearings/PowerShell/angle-difference-between-two-bearings-2.psh b/Task/Angle-difference-between-two-bearings/PowerShell/angle-difference-between-two-bearings-2.ps1 similarity index 100% rename from Task/Angle-difference-between-two-bearings/PowerShell/angle-difference-between-two-bearings-2.psh rename to Task/Angle-difference-between-two-bearings/PowerShell/angle-difference-between-two-bearings-2.ps1 diff --git a/Task/Angle-difference-between-two-bearings/PowerShell/angle-difference-between-two-bearings-3.ps1 b/Task/Angle-difference-between-two-bearings/PowerShell/angle-difference-between-two-bearings-3.ps1 new file mode 100644 index 0000000000..ae4fb0c542 --- /dev/null +++ b/Task/Angle-difference-between-two-bearings/PowerShell/angle-difference-between-two-bearings-3.ps1 @@ -0,0 +1,39 @@ +# Angle difference between two bearings + +function Get-Diff([double]$B1, [double]$B2) { + $r = ($B2 - $B1) % 360.0 + if ($r -lt -180.0) { + $r += 360.0 + } + if ($r -ge 180.0) { + $r -= 360.0 + } + return [double]$r +} + +function Write-Row([double]$B1, [double]$B2) { + [string]$out = "$($B1.ToString('#######.000000').PadLeft(14,' '))" + $out += " $($B2.ToString('#######.000000').PadLeft(14,' '))" + $out += " $((Get-Diff $B1 $B2).ToString('#######.000000').PadLeft(14,' '))" + Write-Output $out +} + +Write-Output "Input in -180 to +180 range" +Write-Output " Bearing 1 Bearing 2 Difference" +Write-Row 20.0 45.0 +Write-Row -45.0 45.0 +Write-Row -85.0 90.0 +Write-Row -95.0 90.0 +Write-Row -45.0 125.0 +Write-Row -45.0 145.0 +Write-Row -45.0 125.0 +Write-Row -45.0 145.0 +Write-Row 29.4803 -88.6381 +Write-Row -78.3251 -159.036 +Write-Output "" +Write-Output "Input in wider range" +Write-Output " Bearing 1 Bearing 2 Difference" +Write-Row -70099.74233810938 29840.67437876723 +Write-Row -165313.6666297357 33693.9894517456 +Write-Row 1174.8380510598456 -154146.66490124757 +Write-Row 60175.77306795546 42213.07192354373 diff --git a/Task/Angle-difference-between-two-bearings/R/angle-difference-between-two-bearings.r b/Task/Angle-difference-between-two-bearings/R/angle-difference-between-two-bearings.r new file mode 100644 index 0000000000..b561b24310 --- /dev/null +++ b/Task/Angle-difference-between-two-bearings/R/angle-difference-between-two-bearings.r @@ -0,0 +1,17 @@ +diff_bearing <- function(b1, b2){ + r <- (b2-b1)%%360 + ifelse(r>180, r-360, r) +} + +test_bearings <- list(c(20, 45), c(-45, 45), c(-85, 90), + c(-95, 90), c(-45, 125), c(-45, 145), + c(29.4803, -88.6381), c(-78.3251, -159.036)) + +test_bigbearings <- list(c(-70099.74233810938, 29840.67437876723), + c(-165313.6666297357, 33693.9894517456), + c(1174.8380510598456, -154146.66490124757), + c(60175.77306795546, 42213.07192354373)) + +db_unary <- function(v) do.call(diff_bearing, as.list(v)) +sapply(test_bearings, db_unary) +sapply(test_bigbearings, db_unary) diff --git a/Task/Angle-difference-between-two-bearings/Red/angle-difference-between-two-bearings.red b/Task/Angle-difference-between-two-bearings/Red/angle-difference-between-two-bearings.red new file mode 100644 index 0000000000..ca3975359e --- /dev/null +++ b/Task/Angle-difference-between-two-bearings/Red/angle-difference-between-two-bearings.red @@ -0,0 +1,26 @@ +anglediff: func [b1 b2 /local r][ + r: mod (b2 - b1) 360 + either r >= 180 + [ r - 360 ] + [ r ] +] + +b1: 180 +b2: -180 + +test-list: [ + [20 45] + [-45 45] + [-85 90] + [-95 90] + [-45 125] + [-45 145] + [29.4803 -88.6381] + [-78.3251 -159.036] +] + +foreach test-case test-list [ + b1: test-case/1 + b2: test-case/2 + print [ "b1 : " b1 " b2 : " b2 "angle diff b2 - b1 : " (anglediff b1 b2)] +] diff --git a/Task/Angle-difference-between-two-bearings/Rust/angle-difference-between-two-bearings.rust b/Task/Angle-difference-between-two-bearings/Rust/angle-difference-between-two-bearings.rs similarity index 100% rename from Task/Angle-difference-between-two-bearings/Rust/angle-difference-between-two-bearings.rust rename to Task/Angle-difference-between-two-bearings/Rust/angle-difference-between-two-bearings.rs diff --git a/Task/Angle-difference-between-two-bearings/Scheme/angle-difference-between-two-bearings.ss b/Task/Angle-difference-between-two-bearings/Scheme/angle-difference-between-two-bearings.scm similarity index 100% rename from Task/Angle-difference-between-two-bearings/Scheme/angle-difference-between-two-bearings.ss rename to Task/Angle-difference-between-two-bearings/Scheme/angle-difference-between-two-bearings.scm diff --git a/Task/Angle-difference-between-two-bearings/Uiua/angle-difference-between-two-bearings.uiua b/Task/Angle-difference-between-two-bearings/Uiua/angle-difference-between-two-bearings.uiua new file mode 100644 index 0000000000..7d01db2c61 --- /dev/null +++ b/Task/Angle-difference-between-two-bearings/Uiua/angle-difference-between-two-bearings.uiua @@ -0,0 +1,7 @@ +Wrap ← ◌◌⍢(⊙⟜+|<⊙⋅∘)⊙◌⊢⟜(⍢(⊙⟜-|>⊙⋅∘)⊣)⟜/- +Diff ← Wrap [¯180 180]/- +[20_45 ¯45_45 ¯85_90 ¯95_90 ¯45_125 ¯45_145 29.4803_¯88.6381 ¯78.3251_¯159.036] +≡(⁅₃Diff) +[¯70099.7423_29840.6744 ¯165313.6666_33693.9895 + 1174.8381_¯154146.6649 60175.7731_42213.0719] +≡(⁅₃Diff) diff --git a/Task/Angles-geometric-normalization-and-conversion/Ada/angles-geometric-normalization-and-conversion.adb b/Task/Angles-geometric-normalization-and-conversion/Ada/angles-geometric-normalization-and-conversion.adb new file mode 100644 index 0000000000..b63341ec27 --- /dev/null +++ b/Task/Angles-geometric-normalization-and-conversion/Ada/angles-geometric-normalization-and-conversion.adb @@ -0,0 +1,226 @@ +-- Rosetta Code Task written in Ada +-- Angles (geometric), normalization and conversion +-- https://rosettacode.org/wiki/Angles_(geometric),_normalization_and_conversion +-- translation from C (conversion functions) and (loosely) Lua (output table formatting) +-- July 2024, R. B. E. + +-- To Do: +-- Specific float format/precision rather than generic? + +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; +with Ada.Float_Text_IO; use Ada.Float_Text_IO; +with Ada.Strings.Fixed; use Ada.Strings.Fixed; +with Ada.Numerics; + +procedure Angles_Geometric_Normalization_and_Conversion is + Pi : constant := Ada.Numerics.Pi; + Two_Pi : constant := 2.0 * Ada.Numerics.Pi; + + function Normalize_to_Deg (a : Float) return Float is + tmp : Float := a; + begin +-- while (tmp < 0.0) loop + while (tmp < -360.0) loop -- task description says to preserve negative input angles + tmp := tmp + 360.0; + end loop; + while (tmp >= 360.0) loop + tmp := tmp - 360.0; + end loop; + return tmp; + end Normalize_to_Deg; + + function Normalize_to_Grad (a : Float) return Float is + tmp : Float := a; + begin + while (tmp < 0.0) loop -- task description says to preserve negative input angles (punting) + tmp := tmp + 400.0; + end loop; + while (tmp >= 400.0) loop + tmp := tmp - 400.0; + end loop; + return tmp; + end Normalize_to_Grad; + + function Normalize_to_Mil (a : Float) return Float is + tmp : Float := a; + begin + while (tmp < 0.0) loop -- task description says to preserve negative input angles (punting) + tmp := tmp + 6400.0; + end loop; + while (tmp >= 6400.0) loop + tmp := tmp - 6400.0; + end loop; + return tmp; + end Normalize_to_Mil; + + function Normalize_to_Rad (a : Float) return Float is + tmp : Float := a; + begin + while (tmp < 0.0) loop -- task description says to preserve negative input angles (punting) + tmp := tmp + Two_Pi; + end loop; + while (tmp >= Two_Pi) loop + tmp := tmp - Two_Pi; + end loop; + return tmp; + end Normalize_to_Rad; + + function Deg_to_Grad (a : Float) return Float is + tmp : Float := a; + begin + tmp := a * (10.0 / 9.0); + return tmp; + end Deg_to_Grad; + + function Deg_to_Mil (a : Float) return Float is + tmp : Float := a; + begin + tmp := a * (160.0 / 9.0); + return tmp; + end Deg_to_Mil; + + function Deg_to_Rad (a : Float) return Float is + tmp : Float := a; + begin + tmp := a * (Pi / 180.0); + return tmp; + end Deg_to_Rad; + + function Grad_to_Deg (a : Float) return Float is + tmp : Float := a; + begin + tmp := a * (9.0 / 10.0); + return tmp; + end Grad_to_Deg; + + function Grad_to_Mil (a : Float) return Float is + tmp : Float := a; + begin + tmp := a * 16.0; + return tmp; + end Grad_to_Mil; + + function Grad_to_Rad (a : Float) return Float is + tmp : Float := a; + begin + tmp := a * (Pi / 200.0); + return tmp; + end Grad_to_Rad; + + function Mil_to_Deg (a : Float) return Float is + tmp : Float := a; + begin + tmp := a * (9.0 / 160.0); + return tmp; + end Mil_to_Deg; + + function Mil_to_Grad (a : Float) return Float is + tmp : Float := a; + begin + tmp := a / 16.0; + return tmp; + end Mil_to_Grad; + + function Mil_to_Rad (a : Float) return Float is + tmp : Float := a; + begin + tmp := a * (Pi / 3200.0); + return tmp; + end Mil_to_Rad; + + function Rad_to_Deg (a : Float) return Float is + tmp : Float := a; + begin + tmp := a * (180.0 / Pi); + return tmp; + end Rad_to_Deg; + + function Rad_to_Grad (a : Float) return Float is + tmp : Float := a; + begin + tmp := a * (200.0 / Pi); + return tmp; + end Rad_to_Grad; + + function Rad_to_Mil (a : Float) return Float is + tmp : Float := a; + begin + tmp := a * (3200.0 / Pi); + return tmp; + end Rad_to_Mil; + + Three_Spaces : constant String := 3 * " "; + + type Index is range 1 .. 12; + type Test_Values_Array is array (Index) of Float; + Test_Values : Test_Values_Array := + (Float (-2), Float (-1), Float (0), Float (1), Float (2), + 6.2831853, Float (16), 57.2957795, Float (359), + Float (399), Float (6399), Float (1000000)); + +begin + Put_Line (" DEGREES GRADIANS MILS RADIANS"); + Put_Line (" TEST VALUE Normalized Converted Converted Converted"); + for I in Index loop + Put (Test_Values (I), Exp => 0, Aft => 8, Fore => 8); + Put (Three_Spaces); + Put (Normalize_to_Deg (Test_Values (I)), Exp => 0, Aft => 8, Fore => 4); + Put (Three_Spaces); + Put (Deg_to_Grad (Normalize_to_Deg (Test_Values (I))), Exp => 0, Aft => 8, Fore => 4); + Put (Three_Spaces); + Put (Deg_to_Mil (Normalize_to_Deg (Test_Values (I))), Exp => 0, Aft => 8, Fore => 4); + Put (Three_Spaces); + Put (Deg_to_Rad (Normalize_to_Deg (Test_Values (I))), Exp => 0, Aft => 8, Fore => 2); + New_Line; + end loop; + + New_Line; + Put_Line (" GRADIANS MILS RADIANS DEGREES"); + Put_Line (" TEST VALUE Normalized Converted Converted Converted"); + for I in Index loop + Put (Test_Values (I), Exp => 0, Aft => 8, Fore => 8); + Put (Three_Spaces); + Put (Normalize_to_Grad (Test_Values (I)), Exp => 0, Aft => 8, Fore => 4); + Put (Three_Spaces); + Put (Grad_to_Mil (Normalize_to_Grad (Test_Values (I))), Exp => 0, Aft => 8, Fore => 4); + Put (Three_Spaces); + Put (Grad_to_Rad (Normalize_to_Grad (Test_Values (I))), Exp => 0, Aft => 8, Fore => 2); + Put (Three_Spaces); + Put (Grad_to_Deg (Normalize_to_Grad (Test_Values (I))), Exp => 0, Aft => 8, Fore => 4); + New_Line; + end loop; + + New_Line; + Put_Line (" MILS RADIANS DEGREES GRADIANS"); + Put_Line (" TEST VALUE Normalized Converted Converted Converted"); + for I in Index loop + Put (Test_Values (I), Exp => 0, Aft => 8, Fore => 8); + Put (Three_Spaces); + Put (Normalize_to_Mil (Test_Values (I)), Exp => 0, Aft => 8, Fore => 4); + Put (Three_Spaces); + Put (Mil_to_Rad (Normalize_to_Mil (Test_Values (I))), Exp => 0, Aft => 8, Fore => 2); + Put (Three_Spaces); + Put (Mil_to_Deg (Normalize_to_Mil (Test_Values (I))), Exp => 0, Aft => 8, Fore => 4); + Put (Three_Spaces); + Put (Mil_to_Grad (Normalize_to_Mil (Test_Values (I))), Exp => 0, Aft => 8, Fore => 4); + New_Line; + end loop; + + New_Line; + Put_Line (" RADIANS DEGREES GRADIANS MILS"); + Put_Line (" TEST VALUE Normalized Converted Converted Converted"); + for I in Index loop + Put (Test_Values (I), Exp => 0, Aft => 8, Fore => 8); + Put (Three_Spaces); + Put (Normalize_to_Rad (Test_Values (I)), Exp => 0, Aft => 8, Fore => 4); + Put (Three_Spaces); + Put (Rad_to_Deg (Normalize_to_Rad (Test_Values (I))), Exp => 0, Aft => 8, Fore => 4); + Put (Three_Spaces); + Put (Rad_to_Grad (Normalize_to_Rad (Test_Values (I))), Exp => 0, Aft => 8, Fore => 4); + Put (Three_Spaces); + Put (Rad_to_Mil (Normalize_to_Rad (Test_Values (I))), Exp => 0, Aft => 8, Fore => 4); + New_Line; + end loop; + +end Angles_Geometric_Normalization_and_Conversion; diff --git a/Task/Angles-geometric-normalization-and-conversion/Crystal/angles-geometric-normalization-and-conversion.cr b/Task/Angles-geometric-normalization-and-conversion/Crystal/angles-geometric-normalization-and-conversion.cr new file mode 100644 index 0000000000..e3f6f91d51 --- /dev/null +++ b/Task/Angles-geometric-normalization-and-conversion/Crystal/angles-geometric-normalization-and-conversion.cr @@ -0,0 +1,32 @@ +def d2d (a) a % 360 end +def g2g (a) a % 400 end +def m2m (a) a % 6400 end +def r2r (a) a.to_f % (2*Math::PI) end + +def d2g (a) d2d(a)/360 * 400 end +def d2m (a) d2d(a)/360 * 6400 end +def d2r (a) d2d(a)/360 * 2*Math::PI end + +def g2d (a) g2g(a)/400 * 360 end +def g2m (a) g2g(a)/400 * 6400 end +def g2r (a) g2g(a)/400 * 2*Math::PI end + +def m2d (a) m2m(a)/6400 * 360 end +def m2g (a) m2m(a)/6400 * 400 end +def m2r (a) m2m(a)/6400 * 2*Math::PI end + +def r2d (a) r2r(a)/(2*Math::PI) * 360 end +def r2g (a) r2r(a)/(2*Math::PI) * 400 end +def r2m (a) r2r(a)/(2*Math::PI) * 6400 end + +angles = [-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000] + +puts "%-12s %-8s %12s %12s %12s %12s" % {"Angle", "Unit", "Degrees", "Gradians", "Mils", "Radians"} +puts "-"*(12+8+12+12+12+12+5) +angles.each do |a| + puts "%-12g %-8s %12g %12g %12g %12g" % {a, "degrees", d2d(a), d2g(a), d2m(a), d2r(a) } + puts "%-12g %-8s %12g %12g %12g %12g" % {a, "gradians", g2d(a), g2g(a), g2m(a), g2r(a) } + puts "%-12g %-8s %12g %12g %12g %12g" % {a, "mils", m2d(a), m2g(a), m2m(a), m2r(a) } + puts "%-12g %-8s %12g %12g %12g %12g" % {a, "radians", r2d(a), r2g(a), r2m(a), r2r(a) } + puts +end diff --git a/Task/Angles-geometric-normalization-and-conversion/Delphi/angles-geometric-normalization-and-conversion.delphi b/Task/Angles-geometric-normalization-and-conversion/Delphi/angles-geometric-normalization-and-conversion.pas similarity index 100% rename from Task/Angles-geometric-normalization-and-conversion/Delphi/angles-geometric-normalization-and-conversion.delphi rename to Task/Angles-geometric-normalization-and-conversion/Delphi/angles-geometric-normalization-and-conversion.pas diff --git a/Task/Angles-geometric-normalization-and-conversion/EasyLang/angles-geometric-normalization-and-conversion.easy b/Task/Angles-geometric-normalization-and-conversion/EasyLang/angles-geometric-normalization-and-conversion.easy index 546d276c89..2a63ef3ad8 100644 --- a/Task/Angles-geometric-normalization-and-conversion/EasyLang/angles-geometric-normalization-and-conversion.easy +++ b/Task/Angles-geometric-normalization-and-conversion/EasyLang/angles-geometric-normalization-and-conversion.easy @@ -27,7 +27,7 @@ func$ fmt s$ . # scales$[] = [ "degree" "gradian" "mil" "radian" ] values[] = [ -2 -1 0 1 2 6.2831853 16 57.2957795 359 399 6399 1000000 ] -numfmt 3 10 +numfmt 10 3 for f$ in scales$[] write fmt f$ for t$ in scales$[] diff --git a/Task/Angles-geometric-normalization-and-conversion/FutureBasic/angles-geometric-normalization-and-conversion.basic b/Task/Angles-geometric-normalization-and-conversion/FutureBasic/angles-geometric-normalization-and-conversion.basic new file mode 100644 index 0000000000..df05b07e41 --- /dev/null +++ b/Task/Angles-geometric-normalization-and-conversion/FutureBasic/angles-geometric-normalization-and-conversion.basic @@ -0,0 +1,100 @@ +include "NSLog.incl" + +double local fn Normalize( f as double, n as double ) + double a = f + while ( a < -n ) : a += n : wend + while ( a >= n ) : a -= n : wend +end fn = a + +double local fn NormalizeToDegrees( f as double ) return fn Normalize( f, 360 ) end fn = 0.0 +double local fn NormalizeToGradians( f as double ) return fn Normalize( f, 400 ) end fn = 0.0 +double local fn NormalizeToMils( f as double ) return fn Normalize( f, 6400 ) end fn = 0.0 +double local fn NormalizeToRadians( f as double ) return fn Normalize( f, 2 * M_PI ) end fn = 0.0 + +double local fn d2g( f as double ) return f * 10 / 9 end fn = 0.0 +double local fn d2m( f as double ) return f * 160 / 9 end fn = 0.0 +double local fn d2r( f as double ) return f * M_PI / 180 end fn = 0.0 + +double local fn g2d( f as double ) return f * 9 / 10 end fn = 0.0 +double local fn g2m( f as double ) return f * 16 end fn = 0.0 +double local fn g2r( f as double ) return f * M_PI / 200 end fn = 0.0 + +double local fn m2d( f as double ) return f * 9 / 160 end fn = 0.0 +double local fn m2g( f as double ) return f / 16 end fn = 0.0 +double local fn m2r( f as double ) return f * M_PI / 3200 end fn = 0.0 + +double local fn r2d( f as double ) return f * 180 / M_PI end fn = 0.0 +double local fn r2g( f as double ) return f * 200 / M_PI end fn = 0.0 +double local fn r2m( f as double ) return f * 3200 / M_PI end fn = 0.0 + +local fn CalculateDegrees + CFArrayRef angles = @[@-2, @-1, @0, @1, @2, @6.2831853, @16, @57.2957795, @359, @6399, @1000000] + double angle, degrees, gradians, mils, radians + NSUInteger i + CFStringRef unit + CFStringRef dashpad = fn StringByPaddingToLength( @"", 73, @"-", 0 ) + + ptr anglePtr = fn StringUTF8String( @"Angle" ) + ptr unitPtr = fn StringUTF8String( @"Unit" ) + ptr normalPtr = fn StringUTF8String( @"Normalized" ) + ptr gradiansPtr = fn StringUTF8String( @"Gradians" ) + ptr milsPtr = fn StringUTF8String( @"Mils" ) + ptr radiansPtr = fn StringUTF8String( @"Radians" ) + + // Header + NSLog( @"\n%@", dashpad ) + NSLog( @"%13s %5s %15s %10s %7s %15s", anglePtr, unitPtr, normalPtr, gradiansPtr, milsPtr, radiansPtr ) + NSLog( @"%@", dashpad ) + + // Degrees + for i = 0 to fn ArrayCount( angles ) - 1 + angle = dblval( angles[i] ) + unit = @"Degrees" + degrees = fn NormalizeToDegrees( angle ) + gradians = fn NormalizeToGradians( fn d2g( degrees ) ) + mils = fn NormalizeToMils( fn d2m( degrees ) ) + radians = fn NormalizeToRadians( fn d2r( degrees ) ) + NSLog( @"%13.4f %-10s % -12.4f % -11.4f % -12.4f % -13.4f", angle, fn StringUTF8String( unit ), degrees, gradians, mils, radians ) + next + NSLog( @"" ) + + // Gradians + for i = 0 to fn ArrayCount( angles ) - 1 + angle = dblval( angles[i] ) + unit = @"Gradians" + gradians = fn NormalizeToGradians( angle ) + degrees = fn NormalizeToDegrees( fn g2d( gradians ) ) + mils = fn NormalizeToMils( fn g2m( gradians ) ) + radians = fn NormalizeToRadians( fn g2r( gradians ) ) + NSLog( @"%13.4f %-10s % -12.4f % -11.4f % -12.4f % -13.4f", angle, fn StringUTF8String( unit ), degrees, gradians, mils, radians ) + next + NSLog( @"" ) + + // Mils + for i = 0 to fn ArrayCount( angles ) - 1 + angle = dblval( angles[i] ) + unit = @"Mils" + mils = fn NormalizeToMils( angle ) + degrees = fn NormalizeToDegrees( fn m2d( mils ) ) + gradians = fn NormalizeToGradians( fn m2g( mils ) ) + radians = fn NormalizeToRadians( fn m2r( mils ) ) + NSLog( @"%13.4f %-10s % -12.4f % -11.4f % -12.4f % -13.4f", angle, fn StringUTF8String( unit ), degrees, gradians, mils, radians ) + next + NSLog( @"" ) + + // Radians + for i = 0 to fn ArrayCount( angles ) - 1 + angle = dblval( angles[i] ) + unit = @"Radians" + radians = fn NormalizeToRadians( angle ) + degrees = fn NormalizeToDegrees( fn r2d( radians ) ) + gradians = fn NormalizeToGradians( fn r2g( radians ) ) + mils = fn NormalizeToMils( fn r2m( radians ) ) + NSLog( @"%13.4f %-10s % -12.4f % -11.4f % -12.4f % -13.4f", angle, fn StringUTF8String( unit ), degrees, gradians, mils, radians ) + next + NSLog( @"%@", dashpad ) +end fn + +fn CalculateDegrees + +HandleEvents diff --git a/Task/Angles-geometric-normalization-and-conversion/Julia/angles-geometric-normalization-and-conversion.julia b/Task/Angles-geometric-normalization-and-conversion/Julia/angles-geometric-normalization-and-conversion.jl similarity index 100% rename from Task/Angles-geometric-normalization-and-conversion/Julia/angles-geometric-normalization-and-conversion.julia rename to Task/Angles-geometric-normalization-and-conversion/Julia/angles-geometric-normalization-and-conversion.jl diff --git a/Task/Angles-geometric-normalization-and-conversion/Kotlin/angles-geometric-normalization-and-conversion.kotlin b/Task/Angles-geometric-normalization-and-conversion/Kotlin/angles-geometric-normalization-and-conversion.kts similarity index 100% rename from Task/Angles-geometric-normalization-and-conversion/Kotlin/angles-geometric-normalization-and-conversion.kotlin rename to Task/Angles-geometric-normalization-and-conversion/Kotlin/angles-geometric-normalization-and-conversion.kts diff --git a/Task/Angles-geometric-normalization-and-conversion/PascalABC.NET/angles-geometric-normalization-and-conversion.pas b/Task/Angles-geometric-normalization-and-conversion/PascalABC.NET/angles-geometric-normalization-and-conversion.pas new file mode 100644 index 0000000000..a0c4a80b2e --- /dev/null +++ b/Task/Angles-geometric-normalization-and-conversion/PascalABC.NET/angles-geometric-normalization-and-conversion.pas @@ -0,0 +1,41 @@ +function fmod(x, y: real): real := x - trunc(x / y) * y; + +function d2d(x: real): real := fmod(x, 360); +function g2g(x: real): real := fmod(x, 400); +function m2m(x: real): real := fmod(x, 6400); +function r2r(x: real): real := fmod(x, 2 * Pi); +function d2g(x: real): real := d2d(x) * 10 / 9; +function d2m(x: real): real := d2d(x) * 160 / 9; +function d2r(x: real): real := d2d(x) * Pi / 180; +function g2d(x: real): real := g2g(x) * 9 / 10; +function g2m(x: real): real := g2g(x) * 16; +function g2r(x: real): real := g2g(x) * Pi / 200; +function m2d(x: real): real := m2m(x) * 9 / 160; +function m2g(x: real): real := m2m(x) / 16; +function m2r(x: real): real := m2m(x) * Pi / 3200; +function r2d(x: real): real := r2r(x) * 180 / Pi; +function r2g(x: real): real := r2r(x) * 200 / Pi; +function r2m(x: real): real := r2r(x) * 3200 / Pi; + +begin + var Values: array of real := (-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 399, 6399, 1000000); + writeln(' Degrees Normalized Gradians Mils Radians'); + writeln('———————————————————————————————————————————————————————————————————————————'); + foreach var val in Values do + writeln(val:15:7, d2d(val):15:7, d2g(val):15:7, d2m(val):15:7, d2r(val):15:7); + writeln; + writeln( ' Gradians Normalized Degrees Mils Radians'); + writeln( '———————————————————————————————————————————————————————————————————————————'); + foreach var val in Values do + writeln( val:15:7, g2g(val):15:7, g2d(val):15:7, g2m(val):15:7, g2r(val):15:7); + writeln; + writeln( ' Mils Normalized Degrees Gradians Radians'); + writeln( '———————————————————————————————————————————————————————————————————————————'); + foreach var val in Values do + writeln( val:15:7, m2m(val):15:7, m2d(val):15:7, m2g(val):15:7, m2r(val):15:7); + writeln; + writeln( ' Radians Normalized Degrees Gradians Mils'); + writeln( '———————————————————————————————————————————————————————————————————————————'); + foreach var val in Values do + writeln( val:15:7, r2r(val):15:7, r2d(val):15:7, r2g(val):15:7, r2m(val):15:7); +end. diff --git a/Task/Angles-geometric-normalization-and-conversion/Phix/angles-geometric-normalization-and-conversion.phix b/Task/Angles-geometric-normalization-and-conversion/Phix/angles-geometric-normalization-and-conversion.phix index 8bc44820c3..20520e7c70 100644 --- a/Task/Angles-geometric-normalization-and-conversion/Phix/angles-geometric-normalization-and-conversion.phix +++ b/Task/Angles-geometric-normalization-and-conversion/Phix/angles-geometric-normalization-and-conversion.phix @@ -1,21 +1,20 @@ ---> - constant units = {"degrees","gradians","mils","radians"}, - turns = {1/360,1/400,1/6400,0.5/PI} +with javascript_semantics +constant units = {"degrees","gradians","mils","radians"}, + turns = {1/360,1/400,1/6400,0.5/PI} - function convert(atom a, integer fdx, tdx) - return remainder(a*turns[fdx],1)/turns[tdx] - end function +function convert(atom a, unit, tgt) + return remainder(a*unit,1)/tgt +end function - constant tests = {-2,-1,0,1,2,2*PI,16,57.2957795,359,399,6399,1000000} - printf(1," angle unit %9s %9s %9s %9s\n",units) - for i=1 to length(tests) do - for fdx=1 to length(units) do - printf(1,"%9g %-8s",{tests[i],units[fdx]}) - for tdx=1 to length(units) do - printf(1," %9g",convert(tests[i],fdx,tdx)) - end for - puts(1,"\n") - end for - puts(1,"\n") - end for - count of proper divisors. 1-->1, wrong but OK here { [1.. (n + 1)/2 + 1].reduce('wrap(p,i){ p + (n%i==0 and n!=i) }) } -fcn antiPrimes{ // -->iterator +fcn antiPrimes{ // -->iterator Walker.chain([2..59],[60..*,30]).tweak(fcn(c,rlast){ last,mx := rlast.value, properDivsN(c); if(mx<=last) return(Void.Skip); rlast.set(mx); c - }.fp1(Ref(0))).push(1); // 1 has no proper divisors + }.fp1(Ref(0))).push(1); // 1 has no proper divisors } diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/Ada/append-a-record-to-the-end-of-a-text-file.ada b/Task/Append-a-record-to-the-end-of-a-text-file/Ada/append-a-record-to-the-end-of-a-text-file.adb similarity index 100% rename from Task/Append-a-record-to-the-end-of-a-text-file/Ada/append-a-record-to-the-end-of-a-text-file.ada rename to Task/Append-a-record-to-the-end-of-a-text-file/Ada/append-a-record-to-the-end-of-a-text-file.adb diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/COBOL/append-a-record-to-the-end-of-a-text-file.cobol b/Task/Append-a-record-to-the-end-of-a-text-file/COBOL/append-a-record-to-the-end-of-a-text-file.cob similarity index 100% rename from Task/Append-a-record-to-the-end-of-a-text-file/COBOL/append-a-record-to-the-end-of-a-text-file.cobol rename to Task/Append-a-record-to-the-end-of-a-text-file/COBOL/append-a-record-to-the-end-of-a-text-file.cob diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/Crystal/append-a-record-to-the-end-of-a-text-file.cr b/Task/Append-a-record-to-the-end-of-a-text-file/Crystal/append-a-record-to-the-end-of-a-text-file.cr new file mode 100644 index 0000000000..c4dd275431 --- /dev/null +++ b/Task/Append-a-record-to-the-end-of-a-text-file/Crystal/append-a-record-to-the-end-of-a-text-file.cr @@ -0,0 +1,36 @@ +record PasswdEntry, account : String, password : String, uid : Int32, gid : Int32, + gecos : Gecos, directory : String, shell : String do + def to_s (io) + io << account << ":" << password << ":" << uid.to_s << ":" << gid.to_s << ":" + gecos.to_s(io) + io << ":" << directory << ":" << shell + end +end + +record Gecos, fullname : String, office : String, extension : String, homephone : String, email : String do + def to_s (io) + io << fullname << "," << office << "," << extension << "," + io << homephone << "," << email + end +end + +filename = "rosetta.passwd" + +File.open(filename, "w") do |f| + f.puts PasswdEntry.new("jsmith", "x", 1001, 1000, + Gecos.new("Joe Smith", "Room 1007", "(234)555-8917", "(234)555-0077", "jsmith@rosettacode.org"), + "/home/jsmith", "/bin/bash") + f.puts PasswdEntry.new("jdoe", "x", 1002, 1000, + Gecos.new("Jane Doe", "Room 1004", "(234)555-8914", "(234)555-0044", "jdoe@rosettacode.org"), + "/home/jdoe", "/bin/bash") +end + +File.open(filename, "a") do |f| + f.puts PasswdEntry.new("xyz", "x", 1003, 1000, + Gecos.new("X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org"), + "/home/xyz", "/bin/bash") +end + +lines = File.read_lines(filename) + +puts "Appended record (##{lines.size}): " + lines.last diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/Ed/append-a-record-to-the-end-of-a-text-file.ed b/Task/Append-a-record-to-the-end-of-a-text-file/Ed/append-a-record-to-the-end-of-a-text-file.ed new file mode 100644 index 0000000000..596c084db6 --- /dev/null +++ b/Task/Append-a-record-to-the-end-of-a-text-file/Ed/append-a-record-to-the-end-of-a-text-file.ed @@ -0,0 +1,9 @@ +H +r append.input +,p +a +xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash +. +w +,p +q diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/Elixir/append-a-record-to-the-end-of-a-text-file.elixir b/Task/Append-a-record-to-the-end-of-a-text-file/Elixir/append-a-record-to-the-end-of-a-text-file.ex similarity index 100% rename from Task/Append-a-record-to-the-end-of-a-text-file/Elixir/append-a-record-to-the-end-of-a-text-file.elixir rename to Task/Append-a-record-to-the-end-of-a-text-file/Elixir/append-a-record-to-the-end-of-a-text-file.ex diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/Julia/append-a-record-to-the-end-of-a-text-file.julia b/Task/Append-a-record-to-the-end-of-a-text-file/Julia/append-a-record-to-the-end-of-a-text-file.jl similarity index 100% rename from Task/Append-a-record-to-the-end-of-a-text-file/Julia/append-a-record-to-the-end-of-a-text-file.julia rename to Task/Append-a-record-to-the-end-of-a-text-file/Julia/append-a-record-to-the-end-of-a-text-file.jl diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/Kotlin/append-a-record-to-the-end-of-a-text-file.kotlin b/Task/Append-a-record-to-the-end-of-a-text-file/Kotlin/append-a-record-to-the-end-of-a-text-file.kts similarity index 100% rename from Task/Append-a-record-to-the-end-of-a-text-file/Kotlin/append-a-record-to-the-end-of-a-text-file.kotlin rename to Task/Append-a-record-to-the-end-of-a-text-file/Kotlin/append-a-record-to-the-end-of-a-text-file.kts diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/PowerShell/append-a-record-to-the-end-of-a-text-file-1.psh b/Task/Append-a-record-to-the-end-of-a-text-file/PowerShell/append-a-record-to-the-end-of-a-text-file-1.ps1 similarity index 100% rename from Task/Append-a-record-to-the-end-of-a-text-file/PowerShell/append-a-record-to-the-end-of-a-text-file-1.psh rename to Task/Append-a-record-to-the-end-of-a-text-file/PowerShell/append-a-record-to-the-end-of-a-text-file-1.ps1 diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/PowerShell/append-a-record-to-the-end-of-a-text-file-2.psh b/Task/Append-a-record-to-the-end-of-a-text-file/PowerShell/append-a-record-to-the-end-of-a-text-file-2.ps1 similarity index 100% rename from Task/Append-a-record-to-the-end-of-a-text-file/PowerShell/append-a-record-to-the-end-of-a-text-file-2.psh rename to Task/Append-a-record-to-the-end-of-a-text-file/PowerShell/append-a-record-to-the-end-of-a-text-file-2.ps1 diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/PowerShell/append-a-record-to-the-end-of-a-text-file-3.psh b/Task/Append-a-record-to-the-end-of-a-text-file/PowerShell/append-a-record-to-the-end-of-a-text-file-3.ps1 similarity index 100% rename from Task/Append-a-record-to-the-end-of-a-text-file/PowerShell/append-a-record-to-the-end-of-a-text-file-3.psh rename to Task/Append-a-record-to-the-end-of-a-text-file/PowerShell/append-a-record-to-the-end-of-a-text-file-3.ps1 diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/PowerShell/append-a-record-to-the-end-of-a-text-file-4.psh b/Task/Append-a-record-to-the-end-of-a-text-file/PowerShell/append-a-record-to-the-end-of-a-text-file-4.ps1 similarity index 100% rename from Task/Append-a-record-to-the-end-of-a-text-file/PowerShell/append-a-record-to-the-end-of-a-text-file-4.psh rename to Task/Append-a-record-to-the-end-of-a-text-file/PowerShell/append-a-record-to-the-end-of-a-text-file-4.ps1 diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/PowerShell/append-a-record-to-the-end-of-a-text-file-5.psh b/Task/Append-a-record-to-the-end-of-a-text-file/PowerShell/append-a-record-to-the-end-of-a-text-file-5.ps1 similarity index 100% rename from Task/Append-a-record-to-the-end-of-a-text-file/PowerShell/append-a-record-to-the-end-of-a-text-file-5.psh rename to Task/Append-a-record-to-the-end-of-a-text-file/PowerShell/append-a-record-to-the-end-of-a-text-file-5.ps1 diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/PowerShell/append-a-record-to-the-end-of-a-text-file-6.psh b/Task/Append-a-record-to-the-end-of-a-text-file/PowerShell/append-a-record-to-the-end-of-a-text-file-6.ps1 similarity index 100% rename from Task/Append-a-record-to-the-end-of-a-text-file/PowerShell/append-a-record-to-the-end-of-a-text-file-6.psh rename to Task/Append-a-record-to-the-end-of-a-text-file/PowerShell/append-a-record-to-the-end-of-a-text-file-6.ps1 diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/PowerShell/append-a-record-to-the-end-of-a-text-file-7.psh b/Task/Append-a-record-to-the-end-of-a-text-file/PowerShell/append-a-record-to-the-end-of-a-text-file-7.ps1 similarity index 100% rename from Task/Append-a-record-to-the-end-of-a-text-file/PowerShell/append-a-record-to-the-end-of-a-text-file-7.psh rename to Task/Append-a-record-to-the-end-of-a-text-file/PowerShell/append-a-record-to-the-end-of-a-text-file-7.ps1 diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/PowerShell/append-a-record-to-the-end-of-a-text-file-8.psh b/Task/Append-a-record-to-the-end-of-a-text-file/PowerShell/append-a-record-to-the-end-of-a-text-file-8.ps1 similarity index 100% rename from Task/Append-a-record-to-the-end-of-a-text-file/PowerShell/append-a-record-to-the-end-of-a-text-file-8.psh rename to Task/Append-a-record-to-the-end-of-a-text-file/PowerShell/append-a-record-to-the-end-of-a-text-file-8.ps1 diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/PowerShell/append-a-record-to-the-end-of-a-text-file-9.psh b/Task/Append-a-record-to-the-end-of-a-text-file/PowerShell/append-a-record-to-the-end-of-a-text-file-9.ps1 similarity index 100% rename from Task/Append-a-record-to-the-end-of-a-text-file/PowerShell/append-a-record-to-the-end-of-a-text-file-9.psh rename to Task/Append-a-record-to-the-end-of-a-text-file/PowerShell/append-a-record-to-the-end-of-a-text-file-9.ps1 diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/Python/append-a-record-to-the-end-of-a-text-file.py b/Task/Append-a-record-to-the-end-of-a-text-file/Python/append-a-record-to-the-end-of-a-text-file.py index e21feece57..1951501c2c 100644 --- a/Task/Append-a-record-to-the-end-of-a-text-file/Python/append-a-record-to-the-end-of-a-text-file.py +++ b/Task/Append-a-record-to-the-end-of-a-text-file/Python/append-a-record-to-the-end-of-a-text-file.py @@ -1,48 +1,126 @@ -############################# -# Create a passwd text file -############################# -# note that UID & gid are of type "text" -passwd_list=[ - dict(account='jsmith', password='x', UID=1001, GID=1000, # UID and GID are type int - GECOS=dict(fullname='Joe Smith', office='Room 1007', extension='(234)555-8917', - homephone='(234)555-0077', email='jsmith@rosettacode.org'), - directory='/home/jsmith', shell='/bin/bash'), - dict(account='jdoe', password='x', UID=1002, GID=1000, - GECOS=dict(fullname='Jane Doe', office='Room 1004', extension='(234)555-8914', - homephone='(234)555-0044', email='jdoe@rosettacode.org'), - directory='/home/jdoe', shell='/bin/bash') +from __future__ import annotations + +import csv +from dataclasses import astuple +from dataclasses import dataclass +from io import StringIO +from pathlib import Path + +from filelock import FileLock + + +@dataclass +class Record: + account: str + password: str + UID: int + GID: int + GECOS: GECOS + directory: str + shell: str + + +@dataclass +class GECOS: + fullname: str + office: str + extension: str + homephone: str + email: str + + +PASSWDS = [ + Record( + "jsmith", + "x", + 1001, + 1000, + GECOS( + "Joe Smith", + "Room 1007", + "(234)555-8917", + "(234)555-0077", + "jsmith@rosettacode.org", + ), + "/home/jsmith", + "/bin/bash", + ), + Record( + "jdoe", + "x", + 1002, + 1000, + GECOS( + "Jane Doe", + "Room 1004", + "(234)555-8914", + "(234)555-0044", + "jdoe@rosettacode.org", + ), + "/home/jdoe", + "/bin/bash", + ), ] -passwd_fields="account password UID GID GECOS directory shell".split() -GECOS_fields="fullname office extension homephone email".split() -def passwd_text_repr(passwd_rec): -# convert individual fields to string type - passwd_rec["GECOS"]=",".join([ passwd_rec["GECOS"][field] for field in GECOS_fields]) - for field in passwd_rec: # convert "int" fields - if not isinstance(passwd_rec[field], str): - passwd_rec[field]=`passwd_rec[field]` - return ":".join([ passwd_rec[field] for field in passwd_fields ]) +class RecordDialect(csv.unix_dialect): + delimiter = ":" + quoting = csv.QUOTE_NONE -passwd_text=open("passwd.txt","w") -for passwd_rec in passwd_list: - print >> passwd_text,passwd_text_repr(passwd_rec) -passwd_text.close() -################################# -# Load text ready for appending -################################# -passwd_text=open("passwd.txt","a+") -new_rec=dict(account='xyz', password='x', UID=1003, GID=1000, - GECOS=dict(fullname='X Yz', office='Room 1003', extension='(234)555-8913', - homephone='(234)555-0033', email='xyz@rosettacode.org'), - directory='/home/xyz', shell='/bin/bash') -print >> passwd_text, passwd_text_repr(new_rec) -passwd_text.close() +class GECOSDialect(RecordDialect): + delimiter = "," + lineterminator = "" -############################################## -# Finally reopen and check record was appended -############################################## -passwd_list=list(open("passwd.txt","r")) -if "xyz" in passwd_list[-1]: - print "Appended record:",passwd_list[-1][:-1] + +def row(record: Record) -> list[str | int]: + gecos_buffer = StringIO() + gecos_writer = csv.writer(gecos_buffer, dialect=GECOSDialect) + gecos_writer.writerow(astuple(record.GECOS)) + + return [ + record.account, + record.password, + record.UID, + record.GID, + gecos_buffer.getvalue(), + record.directory, + record.shell, + ] + + +if __name__ == "__main__": + path = Path("passwd.txt") + lock = FileLock("passwd.txt.lock") + + with lock: + with path.open("w") as fd: + record_writer = csv.writer(fd, dialect=RecordDialect) + record_writer.writerows(row(r) for r in PASSWDS) + + with lock: + print(f"Before append:\n\n{path.read_text()}") + + new_record = Record( + "xyz", + "x", + 1003, + 1001, + GECOS( + "X Yz", + "Room 1003", + "(234)555-8913", + "(234)555-0033", + "xyz@rosettacode.org", + ), + "/home/xyz", + "/bin/bash", + ) + + with lock: + with path.open("a") as fd: + record_writer = csv.writer(fd, dialect=RecordDialect) + record_writer.writerow(row(new_record)) + + with lock: + print(f"After append:\n\n{path.read_text()}") diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/Rust/append-a-record-to-the-end-of-a-text-file.rust b/Task/Append-a-record-to-the-end-of-a-text-file/Rust/append-a-record-to-the-end-of-a-text-file.rs similarity index 100% rename from Task/Append-a-record-to-the-end-of-a-text-file/Rust/append-a-record-to-the-end-of-a-text-file.rust rename to Task/Append-a-record-to-the-end-of-a-text-file/Rust/append-a-record-to-the-end-of-a-text-file.rs diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/Scheme/append-a-record-to-the-end-of-a-text-file.ss b/Task/Append-a-record-to-the-end-of-a-text-file/Scheme/append-a-record-to-the-end-of-a-text-file.scm similarity index 100% rename from Task/Append-a-record-to-the-end-of-a-text-file/Scheme/append-a-record-to-the-end-of-a-text-file.ss rename to Task/Append-a-record-to-the-end-of-a-text-file/Scheme/append-a-record-to-the-end-of-a-text-file.scm diff --git a/Task/Apply-a-callback-to-an-array/Ada/apply-a-callback-to-an-array.ada b/Task/Apply-a-callback-to-an-array/Ada/apply-a-callback-to-an-array-1.adb similarity index 100% rename from Task/Apply-a-callback-to-an-array/Ada/apply-a-callback-to-an-array.ada rename to Task/Apply-a-callback-to-an-array/Ada/apply-a-callback-to-an-array-1.adb diff --git a/Task/Apply-a-callback-to-an-array/Ada/apply-a-callback-to-an-array-2.adb b/Task/Apply-a-callback-to-an-array/Ada/apply-a-callback-to-an-array-2.adb new file mode 100644 index 0000000000..bf1a1147a4 --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/Ada/apply-a-callback-to-an-array-2.adb @@ -0,0 +1,13 @@ +pragma Ada_2022; +with Ada.Text_IO; use Ada.Text_IO; + +procedure Array_Callback is + type Integer_Array is array (Positive range <>) of Integer; + A : constant Integer_Array := (for I in 1..10 => I); + B : constant Integer_Array := (for I in A'Range => A (I) ** 2); +begin + for I in B'Range loop + Put (B (I)'Image); + end loop; + New_Line; +end Array_Callback; diff --git a/Task/Apply-a-callback-to-an-array/ArkScript/apply-a-callback-to-an-array.ark b/Task/Apply-a-callback-to-an-array/ArkScript/apply-a-callback-to-an-array.ark new file mode 100644 index 0000000000..a264075a30 --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/ArkScript/apply-a-callback-to-an-array.ark @@ -0,0 +1,8 @@ +(import std.List :map) + +(let array [1 2 3 4 5 6 7 8 9 10]) +(let mapped (map array (fun (i) (* i i)))) + +(assert + (= mapped [1 4 9 16 25 36 49 64 81 100]) + "mapped is a list of squares") diff --git a/Task/Apply-a-callback-to-an-array/Ballerina/apply-a-callback-to-an-array.ballerina b/Task/Apply-a-callback-to-an-array/Ballerina/apply-a-callback-to-an-array.ballerina new file mode 100644 index 0000000000..a2d7fd5818 --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/Ballerina/apply-a-callback-to-an-array.ballerina @@ -0,0 +1,9 @@ +import ballerina/io; + +public function main() { + int[] a = from int i in 1...10 select i; + var square = function(int i) returns int { + return i * i; + }; + io:println(a.map(i => square(i))); +} diff --git a/Task/Apply-a-callback-to-an-array/Bracmat/apply-a-callback-to-an-array-1.bracmat b/Task/Apply-a-callback-to-an-array/Bracmat/apply-a-callback-to-an-array-1.bracmat new file mode 100644 index 0000000000..3ef3a60ead --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/Bracmat/apply-a-callback-to-an-array-1.bracmat @@ -0,0 +1,13 @@ +( (square=.!arg^2) +& 1 3 5 7:?numbers +& map$(square.!numbers):?squares2a { functional form } +& out$!squares2a +& map$((=.!arg^2).!numbers):?squares2b { functional form with `lambda` } +& out$!squares2b +& :?isquares1 +& whl + ' ( !numbers:#%?number ?numbers + & !isquares1 !number^2:?isquares1 + ) +& out$!isquares1 +); diff --git a/Task/Apply-a-callback-to-an-array/Bracmat/apply-a-callback-to-an-array-2.bracmat b/Task/Apply-a-callback-to-an-array/Bracmat/apply-a-callback-to-an-array-2.bracmat new file mode 100644 index 0000000000..77dc6ec596 --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/Bracmat/apply-a-callback-to-an-array-2.bracmat @@ -0,0 +1,22 @@ +( (square=.!arg^2) +& (1,3,5,7):?numbers +& mop + $ (square.!numbers.(=,).(=,)) + : ?squares2a +& out$!squares2a +& mop + $ ( (=.!arg^2) + . !numbers + . (=,) + . (=,) + ) + : ?squares2b +& out$!squares2b +& :?isquares1 +& whl + ' ( !numbers:(?number,?numbers) + & (!isquares1,!number^2):?isquares1 + ) +& (!isquares1,!numbers^2):(,?isquares1) +& out$!isquares1 +); diff --git a/Task/Apply-a-callback-to-an-array/Bracmat/apply-a-callback-to-an-array.bracmat b/Task/Apply-a-callback-to-an-array/Bracmat/apply-a-callback-to-an-array-3.bracmat similarity index 100% rename from Task/Apply-a-callback-to-an-array/Bracmat/apply-a-callback-to-an-array.bracmat rename to Task/Apply-a-callback-to-an-array/Bracmat/apply-a-callback-to-an-array-3.bracmat diff --git a/Task/Apply-a-callback-to-an-array/COBOL/apply-a-callback-to-an-array.cobol b/Task/Apply-a-callback-to-an-array/COBOL/apply-a-callback-to-an-array.cob similarity index 100% rename from Task/Apply-a-callback-to-an-array/COBOL/apply-a-callback-to-an-array.cobol rename to Task/Apply-a-callback-to-an-array/COBOL/apply-a-callback-to-an-array.cob diff --git a/Task/Apply-a-callback-to-an-array/Crystal/apply-a-callback-to-an-array-1.crystal b/Task/Apply-a-callback-to-an-array/Crystal/apply-a-callback-to-an-array-1.cr similarity index 100% rename from Task/Apply-a-callback-to-an-array/Crystal/apply-a-callback-to-an-array-1.crystal rename to Task/Apply-a-callback-to-an-array/Crystal/apply-a-callback-to-an-array-1.cr diff --git a/Task/Apply-a-callback-to-an-array/Crystal/apply-a-callback-to-an-array-2.crystal b/Task/Apply-a-callback-to-an-array/Crystal/apply-a-callback-to-an-array-2.cr similarity index 100% rename from Task/Apply-a-callback-to-an-array/Crystal/apply-a-callback-to-an-array-2.crystal rename to Task/Apply-a-callback-to-an-array/Crystal/apply-a-callback-to-an-array-2.cr diff --git a/Task/Apply-a-callback-to-an-array/Delphi/apply-a-callback-to-an-array.delphi b/Task/Apply-a-callback-to-an-array/Delphi/apply-a-callback-to-an-array.pas similarity index 100% rename from Task/Apply-a-callback-to-an-array/Delphi/apply-a-callback-to-an-array.delphi rename to Task/Apply-a-callback-to-an-array/Delphi/apply-a-callback-to-an-array.pas diff --git a/Task/Apply-a-callback-to-an-array/Elena/apply-a-callback-to-an-array.elena b/Task/Apply-a-callback-to-an-array/Elena/apply-a-callback-to-an-array.elena index fde9614ade..a36b6c9013 100644 --- a/Task/Apply-a-callback-to-an-array/Elena/apply-a-callback-to-an-array.elena +++ b/Task/Apply-a-callback-to-an-array/Elena/apply-a-callback-to-an-array.elena @@ -2,7 +2,7 @@ import system'routines; PrintSecondPower(n){ console.writeLine(n * n) } -public program() +public Program() { new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}.forEach(PrintSecondPower) } diff --git a/Task/Apply-a-callback-to-an-array/Elixir/apply-a-callback-to-an-array.elixir b/Task/Apply-a-callback-to-an-array/Elixir/apply-a-callback-to-an-array.ex similarity index 100% rename from Task/Apply-a-callback-to-an-array/Elixir/apply-a-callback-to-an-array.elixir rename to Task/Apply-a-callback-to-an-array/Elixir/apply-a-callback-to-an-array.ex diff --git a/Task/Apply-a-callback-to-an-array/Euphoria/apply-a-callback-to-an-array.euphoria b/Task/Apply-a-callback-to-an-array/Euphoria/apply-a-callback-to-an-array.eu similarity index 100% rename from Task/Apply-a-callback-to-an-array/Euphoria/apply-a-callback-to-an-array.euphoria rename to Task/Apply-a-callback-to-an-array/Euphoria/apply-a-callback-to-an-array.eu diff --git a/Task/Apply-a-callback-to-an-array/Gleam/apply-a-callback-to-an-array.gleam b/Task/Apply-a-callback-to-an-array/Gleam/apply-a-callback-to-an-array.gleam new file mode 100644 index 0000000000..90bce5ebb9 --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/Gleam/apply-a-callback-to-an-array.gleam @@ -0,0 +1,7 @@ +import gleam/list + +pub fn main() { + [1, 14, 99, 23] + |> list.map(fn(x) { x * 2 }) + |> echo +} diff --git a/Task/Apply-a-callback-to-an-array/Haxe/apply-a-callback-to-an-array.hx b/Task/Apply-a-callback-to-an-array/Haxe/apply-a-callback-to-an-array.hx new file mode 100644 index 0000000000..da0f9b93f7 --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/Haxe/apply-a-callback-to-an-array.hx @@ -0,0 +1,10 @@ +class Main { + static function main() { + var numbers = [1, 2, 3, 4, 5]; + + var squared = (i) -> i * i; + + trace(numbers); + trace(numbers.map(squared)); + } +} diff --git a/Task/Apply-a-callback-to-an-array/Insitux/apply-a-callback-to-an-array-6.insitux b/Task/Apply-a-callback-to-an-array/Insitux/apply-a-callback-to-an-array-6.insitux new file mode 100644 index 0000000000..0d22e445cf --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/Insitux/apply-a-callback-to-an-array-6.insitux @@ -0,0 +1,2 @@ +; apply an interpolated string closure +(map #"{%} + 1 = {+ 1 %}" [1 2 3 4]) diff --git a/Task/Apply-a-callback-to-an-array/Jactl/apply-a-callback-to-an-array-1.jactl b/Task/Apply-a-callback-to-an-array/Jactl/apply-a-callback-to-an-array-1.jactl new file mode 100644 index 0000000000..17b6f6636e --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/Jactl/apply-a-callback-to-an-array-1.jactl @@ -0,0 +1 @@ +println [1,2,3,4,5].map{ n -> n * n } diff --git a/Task/Apply-a-callback-to-an-array/Jactl/apply-a-callback-to-an-array-2.jactl b/Task/Apply-a-callback-to-an-array/Jactl/apply-a-callback-to-an-array-2.jactl new file mode 100644 index 0000000000..5d89e97a87 --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/Jactl/apply-a-callback-to-an-array-2.jactl @@ -0,0 +1 @@ +[1, 4, 9, 16, 25] diff --git a/Task/Apply-a-callback-to-an-array/Jactl/apply-a-callback-to-an-array-3.jactl b/Task/Apply-a-callback-to-an-array/Jactl/apply-a-callback-to-an-array-3.jactl new file mode 100644 index 0000000000..84acb1c3ac --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/Jactl/apply-a-callback-to-an-array-3.jactl @@ -0,0 +1 @@ +println [1,2,3,4,5].map{ it * it } diff --git a/Task/Apply-a-callback-to-an-array/Jactl/apply-a-callback-to-an-array-4.jactl b/Task/Apply-a-callback-to-an-array/Jactl/apply-a-callback-to-an-array-4.jactl new file mode 100644 index 0000000000..732e1e9933 --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/Jactl/apply-a-callback-to-an-array-4.jactl @@ -0,0 +1 @@ +println [[1,2],[2,3],[3,4],[4,5]].map{ a,b -> a * b } diff --git a/Task/Apply-a-callback-to-an-array/Jactl/apply-a-callback-to-an-array-5.jactl b/Task/Apply-a-callback-to-an-array/Jactl/apply-a-callback-to-an-array-5.jactl new file mode 100644 index 0000000000..74ad847b49 --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/Jactl/apply-a-callback-to-an-array-5.jactl @@ -0,0 +1 @@ +[2, 6, 12, 20] diff --git a/Task/Apply-a-callback-to-an-array/Julia/apply-a-callback-to-an-array.julia b/Task/Apply-a-callback-to-an-array/Julia/apply-a-callback-to-an-array.jl similarity index 100% rename from Task/Apply-a-callback-to-an-array/Julia/apply-a-callback-to-an-array.julia rename to Task/Apply-a-callback-to-an-array/Julia/apply-a-callback-to-an-array.jl diff --git a/Task/Apply-a-callback-to-an-array/Kotlin/apply-a-callback-to-an-array.kotlin b/Task/Apply-a-callback-to-an-array/Kotlin/apply-a-callback-to-an-array.kts similarity index 100% rename from Task/Apply-a-callback-to-an-array/Kotlin/apply-a-callback-to-an-array.kotlin rename to Task/Apply-a-callback-to-an-array/Kotlin/apply-a-callback-to-an-array.kts diff --git a/Task/Apply-a-callback-to-an-array/Langur/apply-a-callback-to-an-array.langur b/Task/Apply-a-callback-to-an-array/Langur/apply-a-callback-to-an-array.langur index d1c575957b..61d90f3fb8 100644 --- a/Task/Apply-a-callback-to-an-array/Langur/apply-a-callback-to-an-array.langur +++ b/Task/Apply-a-callback-to-an-array/Langur/apply-a-callback-to-an-array.langur @@ -1 +1 @@ -writeln map fn{^2}, 1..10 +writeln map(1..10, by=fn{^2}) diff --git a/Task/Apply-a-callback-to-an-array/MiniScript/apply-a-callback-to-an-array.mini b/Task/Apply-a-callback-to-an-array/MiniScript/apply-a-callback-to-an-array.mini new file mode 100644 index 0000000000..9438072140 --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/MiniScript/apply-a-callback-to-an-array.mini @@ -0,0 +1,8 @@ +import "listUtil" +sq = function (x) + return x * x +end function + +arr = range(1, 10) +arr.apply(@sq) +print(arr) diff --git a/Task/Apply-a-callback-to-an-array/OCaml/apply-a-callback-to-an-array-1.ocaml b/Task/Apply-a-callback-to-an-array/OCaml/apply-a-callback-to-an-array-1.ml similarity index 100% rename from Task/Apply-a-callback-to-an-array/OCaml/apply-a-callback-to-an-array-1.ocaml rename to Task/Apply-a-callback-to-an-array/OCaml/apply-a-callback-to-an-array-1.ml diff --git a/Task/Apply-a-callback-to-an-array/OCaml/apply-a-callback-to-an-array-2.ocaml b/Task/Apply-a-callback-to-an-array/OCaml/apply-a-callback-to-an-array-2.ml similarity index 100% rename from Task/Apply-a-callback-to-an-array/OCaml/apply-a-callback-to-an-array-2.ocaml rename to Task/Apply-a-callback-to-an-array/OCaml/apply-a-callback-to-an-array-2.ml diff --git a/Task/Apply-a-callback-to-an-array/OCaml/apply-a-callback-to-an-array-3.ocaml b/Task/Apply-a-callback-to-an-array/OCaml/apply-a-callback-to-an-array-3.ml similarity index 100% rename from Task/Apply-a-callback-to-an-array/OCaml/apply-a-callback-to-an-array-3.ocaml rename to Task/Apply-a-callback-to-an-array/OCaml/apply-a-callback-to-an-array-3.ml diff --git a/Task/Apply-a-callback-to-an-array/OCaml/apply-a-callback-to-an-array-4.ocaml b/Task/Apply-a-callback-to-an-array/OCaml/apply-a-callback-to-an-array-4.ml similarity index 100% rename from Task/Apply-a-callback-to-an-array/OCaml/apply-a-callback-to-an-array-4.ocaml rename to Task/Apply-a-callback-to-an-array/OCaml/apply-a-callback-to-an-array-4.ml diff --git a/Task/Apply-a-callback-to-an-array/OCaml/apply-a-callback-to-an-array-5.ocaml b/Task/Apply-a-callback-to-an-array/OCaml/apply-a-callback-to-an-array-5.ml similarity index 100% rename from Task/Apply-a-callback-to-an-array/OCaml/apply-a-callback-to-an-array-5.ocaml rename to Task/Apply-a-callback-to-an-array/OCaml/apply-a-callback-to-an-array-5.ml diff --git a/Task/Apply-a-callback-to-an-array/OCaml/apply-a-callback-to-an-array-6.ocaml b/Task/Apply-a-callback-to-an-array/OCaml/apply-a-callback-to-an-array-6.ml similarity index 100% rename from Task/Apply-a-callback-to-an-array/OCaml/apply-a-callback-to-an-array-6.ocaml rename to Task/Apply-a-callback-to-an-array/OCaml/apply-a-callback-to-an-array-6.ml diff --git a/Task/Apply-a-callback-to-an-array/OCaml/apply-a-callback-to-an-array-7.ocaml b/Task/Apply-a-callback-to-an-array/OCaml/apply-a-callback-to-an-array-7.ml similarity index 100% rename from Task/Apply-a-callback-to-an-array/OCaml/apply-a-callback-to-an-array-7.ocaml rename to Task/Apply-a-callback-to-an-array/OCaml/apply-a-callback-to-an-array-7.ml diff --git a/Task/Apply-a-callback-to-an-array/PascalABC.NET/apply-a-callback-to-an-array.pas b/Task/Apply-a-callback-to-an-array/PascalABC.NET/apply-a-callback-to-an-array.pas new file mode 100644 index 0000000000..c95fa7f852 --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/PascalABC.NET/apply-a-callback-to-an-array.pas @@ -0,0 +1,5 @@ +begin + var a := Arr(1..10); + a := a.Select(x -> x * x).ToArray; + a.ForEach(x -> Print(x)); +end. diff --git a/Task/Apply-a-callback-to-an-array/PowerShell/apply-a-callback-to-an-array-1.psh b/Task/Apply-a-callback-to-an-array/PowerShell/apply-a-callback-to-an-array-1.ps1 similarity index 100% rename from Task/Apply-a-callback-to-an-array/PowerShell/apply-a-callback-to-an-array-1.psh rename to Task/Apply-a-callback-to-an-array/PowerShell/apply-a-callback-to-an-array-1.ps1 diff --git a/Task/Apply-a-callback-to-an-array/PowerShell/apply-a-callback-to-an-array-2.psh b/Task/Apply-a-callback-to-an-array/PowerShell/apply-a-callback-to-an-array-2.ps1 similarity index 100% rename from Task/Apply-a-callback-to-an-array/PowerShell/apply-a-callback-to-an-array-2.psh rename to Task/Apply-a-callback-to-an-array/PowerShell/apply-a-callback-to-an-array-2.ps1 diff --git a/Task/Apply-a-callback-to-an-array/REXX/apply-a-callback-to-an-array.rexx b/Task/Apply-a-callback-to-an-array/REXX/apply-a-callback-to-an-array.rexx index a73f3a1322..916ed41e04 100644 --- a/Task/Apply-a-callback-to-an-array/REXX/apply-a-callback-to-an-array.rexx +++ b/Task/Apply-a-callback-to-an-array/REXX/apply-a-callback-to-an-array.rexx @@ -1,23 +1,38 @@ -/*REXX program applies a callback to an array (using factorials for a demonstration).*/ -numeric digits 100 /*be able to display some huge numbers.*/ -parse arg # . /*obtain an optional value from the CL.*/ -a.= /*initialize the array A to all nulls*/ -if #=='' | #=="," then #= 12 /*Not assigned? Then use default value*/ - do j=0 to #; a.j= j /*assign the integer J ───► A.j */ - end /*j*/ /*array A will have N values: 0 ──► #*/ +-- 31 Mar 2026 +include Setting +numeric digits 4 -call listA 'before callback' /*display A array before the callback*/ -say /*display a blank line for readability.*/ -say ' ··· applying callback to array A ···' /*display what is about to happen to B.*/ -say /*display a blank line for readability.*/ -call bangit 'a' /*factorialize (the values) of A array.*/ - /* store the results ───► array B.*/ -call listA ' after callback' /*display A array after the callback.*/ -exit 0 /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -bangit: do v=0; $= value(arg(1)'.'v); if $=='' then return /*No value? Then return*/ - call value arg(1)'.'v, fact($) /*assign a value (a factorial) to array*/ - end /*i*/ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -fact: procedure; arg x; != 1; do f=2 to x; != !*f; end; /*f*/; return ! -listA: do k=0 while a.k\==''; say arg(1) 'a.'k"=" a.k; end /*k*/; return +say 'APPLY A CALLBACK TO AN ARRAY' +say version +say +say 'Generate...' +call Struct2stem 'stem.','1 2 3 4 5 6 7 8 9 10' +call ShowSt 'stem.','1 to 10 ascending',,7 +call CopySt 'stem.','copy.' + +say 'Single function Square' +call MapSt 'stem.','square' +call ShowSt 'stem.','after square',,7 + +say 'Your own function Cubic...' +call CopySt 'copy.','stem.' +call MapSt 'stem.','cube' +call ShowSt 'stem.','after cube',,7 + +say 'Expression x^2+2x+3...' +call CopySt 'copy.','stem.' +call MapSt 'stem.','x**2+2*x+3' +call ShowSt 'stem.','after simple formula',,7 + +say 'Expression Sin(x)+Square(x)...' +call CopySt 'copy.','stem.' +call MapSt 'stem.','sin(x)+square(x)' +call ShowSt 'stem.','after more involved formula',,7 +exit + +Cubic: +arg xx +return xx**3 + +-- MapSt; Struct2stem; ShowSt; CopySt; Square; Sin +include Math diff --git a/Task/Apply-a-callback-to-an-array/REBOL/apply-a-callback-to-an-array.rebol b/Task/Apply-a-callback-to-an-array/Rebol/apply-a-callback-to-an-array.rebol similarity index 98% rename from Task/Apply-a-callback-to-an-array/REBOL/apply-a-callback-to-an-array.rebol rename to Task/Apply-a-callback-to-an-array/Rebol/apply-a-callback-to-an-array.rebol index ec06fa4564..62231cfcf9 100644 --- a/Task/Apply-a-callback-to-an-array/REBOL/apply-a-callback-to-an-array.rebol +++ b/Task/Apply-a-callback-to-an-array/Rebol/apply-a-callback-to-an-array.rebol @@ -1,4 +1,4 @@ -REBOL [ +Rebol [ Title: "Array Callback" URL: http://rosettacode.org/wiki/Apply_a_callback_to_an_Array ] diff --git a/Task/Apply-a-callback-to-an-array/Rust/apply-a-callback-to-an-array.rs b/Task/Apply-a-callback-to-an-array/Rust/apply-a-callback-to-an-array.rs new file mode 100644 index 0000000000..15fefb8314 --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/Rust/apply-a-callback-to-an-array.rs @@ -0,0 +1,9 @@ +fn echo(n: &i32) { + println!("{}", n); +} + +fn main() { + let a: [i32; 5]; + a = [1, 2, 3, 4, 5]; + let _: Vec<_> = a.iter().map(echo).collect(); +} diff --git a/Task/Apply-a-callback-to-an-array/Rust/apply-a-callback-to-an-array.rust b/Task/Apply-a-callback-to-an-array/Rust/apply-a-callback-to-an-array.rust deleted file mode 100644 index 8e67a487bf..0000000000 --- a/Task/Apply-a-callback-to-an-array/Rust/apply-a-callback-to-an-array.rust +++ /dev/null @@ -1,9 +0,0 @@ -fn echo(n: &i32) { - println!("{}", n); -} - -fn main() { - let a: [i32; 5]; - a = [1, 2, 3, 4, 5]; - let _: Vec<_> = a.into_iter().map(echo).collect(); -} diff --git a/Task/Apply-a-callback-to-an-array/SIL/apply-a-callback-to-an-array.sil b/Task/Apply-a-callback-to-an-array/SIL/apply-a-callback-to-an-array.sil new file mode 100644 index 0000000000..77284ec80d --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/SIL/apply-a-callback-to-an-array.sil @@ -0,0 +1,32 @@ +// avoid executing function definitions +GOTO body + +// our function to apply +funcsquare +x * x +return + +lblbody +// add some values to the memory buffer +set 256 1 +set 257 2 +set 258 3 +set 259 4 +set 260 5 + +// i is our array pointer +// in sil it's customary to place data in cells > 255 +// to avoid interference with ascii variables +i = 256 + +lblloop +// place value at i where square function expects it +x = get i +// call square function +GOSUB square +printInt x +// increment pointer; this is like i += 1 in C +i + 1 +a = 261 - i +// start another iteration if we are below cell 261 +if a loop diff --git a/Task/Apply-a-callback-to-an-array/Scheme/apply-a-callback-to-an-array-1.ss b/Task/Apply-a-callback-to-an-array/Scheme/apply-a-callback-to-an-array-1.scm similarity index 100% rename from Task/Apply-a-callback-to-an-array/Scheme/apply-a-callback-to-an-array-1.ss rename to Task/Apply-a-callback-to-an-array/Scheme/apply-a-callback-to-an-array-1.scm diff --git a/Task/Apply-a-callback-to-an-array/Scheme/apply-a-callback-to-an-array-2.ss b/Task/Apply-a-callback-to-an-array/Scheme/apply-a-callback-to-an-array-2.scm similarity index 100% rename from Task/Apply-a-callback-to-an-array/Scheme/apply-a-callback-to-an-array-2.ss rename to Task/Apply-a-callback-to-an-array/Scheme/apply-a-callback-to-an-array-2.scm diff --git a/Task/Apply-a-callback-to-an-array/Scheme/apply-a-callback-to-an-array-3.ss b/Task/Apply-a-callback-to-an-array/Scheme/apply-a-callback-to-an-array-3.scm similarity index 100% rename from Task/Apply-a-callback-to-an-array/Scheme/apply-a-callback-to-an-array-3.ss rename to Task/Apply-a-callback-to-an-array/Scheme/apply-a-callback-to-an-array-3.scm diff --git a/Task/Apply-a-callback-to-an-array/Tailspin/apply-a-callback-to-an-array.tailspin b/Task/Apply-a-callback-to-an-array/Tailspin/apply-a-callback-to-an-array-1.tailspin similarity index 100% rename from Task/Apply-a-callback-to-an-array/Tailspin/apply-a-callback-to-an-array.tailspin rename to Task/Apply-a-callback-to-an-array/Tailspin/apply-a-callback-to-an-array-1.tailspin diff --git a/Task/Apply-a-callback-to-an-array/Tailspin/apply-a-callback-to-an-array-2.tailspin b/Task/Apply-a-callback-to-an-array/Tailspin/apply-a-callback-to-an-array-2.tailspin new file mode 100644 index 0000000000..88a5af5f68 --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/Tailspin/apply-a-callback-to-an-array-2.tailspin @@ -0,0 +1,14 @@ +numbers is [1,3,7,10]; + +cube templates + $ * $ * $ ! +end cube + +-- Using lens transforms +$numbers(.. as i; -> $ * $i) ! +$numbers(..; -> $ * $) ! +$numbers(..; -> cube) ! + +-- Using array literal and deconstructor +[ $numbers... -> $ * $ ] ! +[ $numbers... -> cube ] ! diff --git a/Task/Apply-a-callback-to-an-array/Uiua/apply-a-callback-to-an-array.uiua b/Task/Apply-a-callback-to-an-array/Uiua/apply-a-callback-to-an-array.uiua new file mode 100644 index 0000000000..4a3c9d85d0 --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/Uiua/apply-a-callback-to-an-array.uiua @@ -0,0 +1 @@ +⍚&p⇡10 diff --git a/Task/Apply-a-callback-to-an-array/V-(Vlang)/apply-a-callback-to-an-array.v b/Task/Apply-a-callback-to-an-array/V-(Vlang)/apply-a-callback-to-an-array.v new file mode 100644 index 0000000000..84dd6e2ec5 --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/V-(Vlang)/apply-a-callback-to-an-array.v @@ -0,0 +1,5 @@ +fn main() { + mut arr := [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + new_arr := arr.map(fn (it int) int {return it * it}) + println(new_arr) +} diff --git a/Task/Apply-a-callback-to-an-array/VBScript/apply-a-callback-to-an-array-1.vb b/Task/Apply-a-callback-to-an-array/VBScript/apply-a-callback-to-an-array-1.vbs similarity index 100% rename from Task/Apply-a-callback-to-an-array/VBScript/apply-a-callback-to-an-array-1.vb rename to Task/Apply-a-callback-to-an-array/VBScript/apply-a-callback-to-an-array-1.vbs diff --git a/Task/Apply-a-callback-to-an-array/VBScript/apply-a-callback-to-an-array-2.vb b/Task/Apply-a-callback-to-an-array/VBScript/apply-a-callback-to-an-array-2.vbs similarity index 100% rename from Task/Apply-a-callback-to-an-array/VBScript/apply-a-callback-to-an-array-2.vb rename to Task/Apply-a-callback-to-an-array/VBScript/apply-a-callback-to-an-array-2.vbs diff --git a/Task/Apply-a-digital-filter-direct-form-II-transposed-/ALGOL-68/apply-a-digital-filter-direct-form-ii-transposed-.alg b/Task/Apply-a-digital-filter-direct-form-II-transposed-/ALGOL-68/apply-a-digital-filter-direct-form-ii-transposed-.alg index 4c7615c3bb..b5417588b2 100644 --- a/Task/Apply-a-digital-filter-direct-form-II-transposed-/ALGOL-68/apply-a-digital-filter-direct-form-ii-transposed-.alg +++ b/Task/Apply-a-digital-filter-direct-form-II-transposed-/ALGOL-68/apply-a-digital-filter-direct-form-ii-transposed-.alg @@ -1,5 +1,4 @@ BEGIN # apply a digital filter # - # the lower bounds of a, b, signal and result must all be equal # PROC filter = ( []REAL a, b, signal, REF[]REAL result )VOID: IF LWB a /= LWB b OR LWB a /= LWB signal OR LWB a /= LWB result THEN print( ( "Array lower bounds must be equal for filter", newline ) ); @@ -11,25 +10,27 @@ BEGIN # apply a digital filter # FOR j FROM LWB b TO IF i > UPB b THEN UPB b ELSE i FI DO tmp +:= b[ j ] * signal[ LWB signal + ( i - j ) ] OD; - FOR j FROM LWB a + 1 TO IF i > UPB a THEN UPB a ELSE i FI DO + FOR j FROM LWB a + 1 TO IF i > UPB a THEN UPB a ELSE i FI DO tmp -:= a[ j ] * result[ LWB result + ( i - j ) ] OD; result[ i ] := tmp / a[ LWB a ] OD FI # filter # ; - [ 4 ]REAL a := []REAL( 1, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17 ); - [ 4 ]REAL b := []REAL( 0.16666667, 0.5, 0.5, 0.16666667 ); - [ 20 ]REAL signal - := []REAL( -0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412 - , -0.662370894973, -1.00700480494, -0.404707073677, 0.800482325044 - , 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195 - , 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293 - , 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589 - ); - [ 20 ]REAL result; - filter( a, b, signal, result ); - FOR i FROM LWB result TO UPB result DO - print( ( " ", fixed( result[ i ], -9, 6 ) ) ); - IF i MOD 5 /= 0 THEN print( ( ", " ) ) ELSE print( ( newline ) ) FI - OD + BEGIN + [ 4 ]REAL a := []REAL( 1, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17 ); + [ 4 ]REAL b := []REAL( 0.16666667, 0.5, 0.5, 0.16666667 ); + [ 20 ]REAL signal + := []REAL( -0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412 + , -0.662370894973, -1.00700480494, -0.404707073677, 0.800482325044 + , 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195 + , 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293 + , 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589 + ); + [ 20 ]REAL result; + filter( a, b, signal, result ); + FOR i FROM LWB result TO UPB result DO + print( ( " ", fixed( result[ i ], -9, 6 ) ) ); + IF i MOD 5 /= 0 THEN print( ( ", " ) ) ELSE print( ( newline ) ) FI + OD + END END diff --git a/Task/Apply-a-digital-filter-direct-form-II-transposed-/Ada/apply-a-digital-filter-direct-form-ii-transposed-.ada b/Task/Apply-a-digital-filter-direct-form-II-transposed-/Ada/apply-a-digital-filter-direct-form-ii-transposed-.adb similarity index 100% rename from Task/Apply-a-digital-filter-direct-form-II-transposed-/Ada/apply-a-digital-filter-direct-form-ii-transposed-.ada rename to Task/Apply-a-digital-filter-direct-form-II-transposed-/Ada/apply-a-digital-filter-direct-form-ii-transposed-.adb diff --git a/Task/Apply-a-digital-filter-direct-form-II-transposed-/Crystal/apply-a-digital-filter-direct-form-ii-transposed-.cr b/Task/Apply-a-digital-filter-direct-form-II-transposed-/Crystal/apply-a-digital-filter-direct-form-ii-transposed-.cr new file mode 100644 index 0000000000..8758d38c65 --- /dev/null +++ b/Task/Apply-a-digital-filter-direct-form-II-transposed-/Crystal/apply-a-digital-filter-direct-form-ii-transposed-.cr @@ -0,0 +1,26 @@ +def filter (b, a, inp) + outp = Array.new(inp.size, 0.0) + (0...inp.size).each do |i| + tmp = 0.0 + (0...b.size).each do |j| + next if i - j < 0 + tmp += b[j] * inp[i-j] + end + (1...a.size).each do |j| + next if i - j < 0 + tmp -= a[j] * outp[i-j] + end + tmp /= a[0] + outp[i] = tmp + end + outp +end + +sig = [-0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412, -0.662370894973, + -1.00700480494, -0.404707073677 ,0.800482325044, 0.743500089861, 1.01090520172, + 0.741527555207, 0.277841675195, 0.400833448236, -0.2085993586, -0.172842103641, + -0.134316096293, 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589] +a = [1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17] +b = [0.16666667, 0.5, 0.5, 0.16666667] + +p filter(b, a, sig) diff --git a/Task/Apply-a-digital-filter-direct-form-II-transposed-/Fortran/apply-a-digital-filter-direct-form-ii-transposed-.f b/Task/Apply-a-digital-filter-direct-form-II-transposed-/Fortran/apply-a-digital-filter-direct-form-ii-transposed-.f new file mode 100644 index 0000000000..82aef332a6 --- /dev/null +++ b/Task/Apply-a-digital-filter-direct-form-II-transposed-/Fortran/apply-a-digital-filter-direct-form-ii-transposed-.f @@ -0,0 +1,42 @@ +module df2_filter + implicit none + real, parameter :: a(4) = [1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17] + real, parameter :: b(4) = [0.16666667, 0.5, 0.5, 0.16666667] + real :: w(4) = 0.0 ! State vector + +contains + function filter(x) result(y) + real, intent(in) :: x + real :: y + integer :: i + + y = x * b(1) + w(1) + + do i = 2, 4 + w(i-1) = x * b(i) - y * a(i) + w(i) + end do + end function filter +end module df2_filter + +program apply_filter + use df2_filter + implicit none + real, dimension(20) :: input = [ & + -0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412, & + -0.662370894973, -1.00700480494, -0.404707073677, 0.800482325044, & + 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195, & + 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293, & + 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589 ] + real, dimension(20) :: output + integer :: i + + do i = 1, 20 + output(i) = filter(input(i)) + end do + + print *, "Filtered signal:" + do i = 1,20 + write(*, '(f12.9,2x)',advance='no') output(i) + if(mod(i,5)==0)write(*,*) + end do +end program apply_filter diff --git a/Task/Apply-a-digital-filter-direct-form-II-transposed-/Julia/apply-a-digital-filter-direct-form-ii-transposed-.julia b/Task/Apply-a-digital-filter-direct-form-II-transposed-/Julia/apply-a-digital-filter-direct-form-ii-transposed-.jl similarity index 100% rename from Task/Apply-a-digital-filter-direct-form-II-transposed-/Julia/apply-a-digital-filter-direct-form-ii-transposed-.julia rename to Task/Apply-a-digital-filter-direct-form-II-transposed-/Julia/apply-a-digital-filter-direct-form-ii-transposed-.jl diff --git a/Task/Apply-a-digital-filter-direct-form-II-transposed-/Kotlin/apply-a-digital-filter-direct-form-ii-transposed-.kotlin b/Task/Apply-a-digital-filter-direct-form-II-transposed-/Kotlin/apply-a-digital-filter-direct-form-ii-transposed-.kts similarity index 100% rename from Task/Apply-a-digital-filter-direct-form-II-transposed-/Kotlin/apply-a-digital-filter-direct-form-ii-transposed-.kotlin rename to Task/Apply-a-digital-filter-direct-form-II-transposed-/Kotlin/apply-a-digital-filter-direct-form-ii-transposed-.kts diff --git a/Task/Apply-a-digital-filter-direct-form-II-transposed-/M2000-Interpreter/apply-a-digital-filter-direct-form-ii-transposed-.m2000 b/Task/Apply-a-digital-filter-direct-form-II-transposed-/M2000-Interpreter/apply-a-digital-filter-direct-form-ii-transposed-.m2000 new file mode 100644 index 0000000000..7cc823c84a --- /dev/null +++ b/Task/Apply-a-digital-filter-direct-form-II-transposed-/M2000-Interpreter/apply-a-digital-filter-direct-form-ii-transposed-.m2000 @@ -0,0 +1,49 @@ +module Checkit { + locale 1033 ' use of dot for decimals + window 12, window ' set 12pt for current display monitor + form 60 ' 60 chars width, any for heigh + Print $("0.00000000",12) ' 12 chars per tab + ' all data push to end of stack, so we use the stack of values as FIFO + Flush + ' a() + Data 1, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17 + ' b() + Data 0.16666667, 0.5, 0.5, 0.16666667 + ' signal() + Data -0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412 + Data -0.662370894973, -1.00700480494, -0.404707073677, 0.800482325044 + Data 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195 + Data 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293 + Data 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589 + Dim Base 0, a(4) as Double , b(4) as Double , signal(20) as Double + Integer i + For i = 0 To 3 : Read a(i) : Next i + For i = 0 To 3 : Read b(i) : Next i + For i = 0 To 19 : Read signal(i) : Next i + dim resp() + resp()=@Filter_a_b(&signal()) + k=each(resp()) + while k + Print array(k), + if pos>0 then if (k^+1) mod 5=0 then Print + end while + Function Filter_a_b(&c()) + Local Integer j, k + Local Double tmp + Local result(0 to len(c())-1) as Double + For j = 0 To Len(c())-1 + tmp = 0 + For k = 0 To Len(b())-1 + If (j-k < 0) Then Continue For + tmp += b(k) * c(j-k) + Next k + For k = 0 To Len(a())-1 + If (j-k < 0) Then Continue For + tmp -= a(k) * result(j-k) + Next k + result(j) = tmp/a(0) + Next j + =result() + End Function +} +Checkit diff --git a/Task/Apply-a-digital-filter-direct-form-II-transposed-/Phix/apply-a-digital-filter-direct-form-ii-transposed-.phix b/Task/Apply-a-digital-filter-direct-form-II-transposed-/Phix/apply-a-digital-filter-direct-form-ii-transposed-.phix index aa33f346b9..3c4df0029e 100644 --- a/Task/Apply-a-digital-filter-direct-form-II-transposed-/Phix/apply-a-digital-filter-direct-form-ii-transposed-.phix +++ b/Task/Apply-a-digital-filter-direct-form-II-transposed-/Phix/apply-a-digital-filter-direct-form-ii-transposed-.phix @@ -1,22 +1,20 @@ -(phixonline)--> - with javascript_semantics - function direct_form_II_transposed_filter(sequence a, b, signal) - sequence result = repeat(0,length(signal)) - for i=1 to length(signal) do - atom tmp = 0 - for j=1 to min(i,length(b)) do tmp += b[j]*signal[i-j+1] end for - for j=2 to min(i,length(a)) do tmp -= a[j]*result[i-j+1] end for - result[i] = tmp/a[1] - end for - return result - end function +with javascript_semantics +function direct_form_II_transposed_filter(sequence a, b, signal) + sequence result = repeat(0,length(signal)) + for i=1 to length(signal) do + atom tmp = 0 + for j=1 to min(i,length(b)) do tmp += b[j]*signal[i-j+1] end for + for j=2 to min(i,length(a)) do tmp -= a[j]*result[i-j+1] end for + result[i] = tmp/a[1] + end for + return result +end function - constant acoef = {1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17}, - bcoef = {0.16666667, 0.5, 0.5, 0.16666667}, - signal = {-0.917843918645,0.141984778794,1.20536903482,0.190286794412,-0.662370894973, - -1.00700480494,-0.404707073677,0.800482325044,0.743500089861,1.01090520172, - 0.741527555207,0.277841675195,0.400833448236,-0.2085993586,-0.172842103641, - -0.134316096293,0.0259303398477,0.490105989562,0.549391221511,0.9047198589} +constant acoef = {1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17}, + bcoef = {0.16666667, 0.5, 0.5, 0.16666667}, + signal = {-0.917843918645,0.141984778794,1.20536903482,0.190286794412,-0.662370894973, + -1.00700480494,-0.404707073677,0.800482325044,0.743500089861,1.01090520172, + 0.741527555207,0.277841675195,0.400833448236,-0.2085993586,-0.172842103641, + -0.134316096293,0.0259303398477,0.490105989562,0.549391221511,0.9047198589} - pp(direct_form_II_transposed_filter(acoef, bcoef, signal),{pp_FltFmt,"%9.6f",pp_Maxlen,110}) - - without js - atom mem = allocate(size,true) - - without js - sequence ap = {} - function ap_allocate(integer size) - -- allocate some memory and add it to the arena pool 'ap' for later release - atom res = allocate(size) - ap = append(ap,res) - return res - end function - procedure ap_free() - -- free all memory allocated in arena pool 'ap' - free(ap) - ap = {} - end procedure - - -- demo\rosetta\ArithComplex.exw - with javascript_semantics - include complex.e - complex a = complex_new(1,1), -- (or just {1,1}) - b = complex_new(3.14159,1.25), - c = complex_new(1,0), - d = complex_new(0,1) - printf(1,"a = %s\n",{complex_sprint(a)}) - printf(1,"b = %s\n",{complex_sprint(b)}) - printf(1,"c = %s\n",{complex_sprint(c)}) - printf(1,"d = %s\n",{complex_sprint(d)}) - printf(1,"a+b = %s\n",{complex_sprint(complex_add(a,b))}) - printf(1,"a*b = %s\n",{complex_sprint(complex_mul(a,b))}) - printf(1,"1/a = %s\n",{complex_sprint(complex_inv(a))}) - printf(1,"c/a = %s\n",{complex_sprint(complex_div(c,a))}) - printf(1,"c-a = %s\n",{complex_sprint(complex_sub(c,a))}) - printf(1,"d-a = %s\n",{complex_sprint(complex_sub(d,a))}) - printf(1,"-a = %s\n",{complex_sprint(complex_neg(a))}) - printf(1,"conj a = %s\n",{complex_sprint(complex_conjugate(a))}) - - -- demo\rosetta\Arithmetic_evaluation.exw - with javascript_semantics +-- demo\rosetta\Arithmetic_evaluation.exw +sequence opstack = {} -- atom elements are literals, + -- sequence elements are subexpressions + -- on completion length(opstack) should be 1 +object token - sequence opstack = {} -- atom elements are literals, - -- sequence elements are subexpressions - -- on completion length(opstack) should be 1 - object token +constant p_p_op = -1, -- expressions stored as p1,p2,op + p_op_p = 0, -- expressions stored as p1,op,p2 + op_p_p = +1, -- expressions stored as op,p1,p2 + opp = op_p_p - constant op_p_p = 1 -- 1: expressions stored as op,p1,p2 - -- p_op_p -- 0: expressions stored as p1,op,p2 - -- p_p_op -- -1: expressions stored as p1,p2,op +object op = 0 -- 0 if none, else "+", "-", "*", "/", "^", "%", or "u-" - object op = 0 -- 0 if none, else "+", "-", "*", "/", "^", "%", or "u-" +string s -- the expression being parsed +integer ch +integer sidx - string s -- the expression being parsed - integer ch - integer sidx +procedure err(string msg) + crash("%s\n%s^ %s\n\nPressEnter...",{s,repeat(' ',sidx-1),msg}) +end procedure - procedure err(string msg) - printf(1,"%s\n%s^ %s\n\nPressEnter...",{s,repeat(' ',sidx-1),msg}) - {} = wait_key() - abort(0) - end procedure +procedure nxtch(object msg="eof") + sidx += 1 + if sidx>length(s) then + if string(msg) then err(msg) end if + ch = -1 + else + ch = s[sidx] + end if +end procedure - procedure nxtch(object msg="eof") - sidx += 1 - if sidx>length(s) then - if string(msg) then err(msg) end if - ch = -1 - else - ch = s[sidx] - end if - end procedure +procedure skipspaces() + while find(ch," \t\r\n") do nxtch(0) end while +end procedure - procedure skipspaces() - while find(ch,{' ','\t','\r','\n'})!=0 do nxtch(0) end while - end procedure +procedure get_token() + skipspaces() + if ch=-1 then token = "eof" return end if + if ch>='0' and ch<='9' then + atom n = ch-'0' + while 1 do + nxtch(0) + if ch<'0' or ch>'9' then exit end if + n = n*10+(ch-'0') + end while + if ch='.' then + integer decimal = 1 + atom fraction = 0 + while true do + nxtch(0) + if ch<'0' or ch>'9' then exit end if + fraction = fraction*10 + (ch-'0') + decimal *= 10 + end while + n += fraction/decimal + end if +-- if find(ch,"eE") then -- you get the idea +-- end if + token = n + return + end if + if find(ch,"+-/*()^%")=0 then err("syntax error") end if + token = s[sidx..sidx] + nxtch(0) + return +end procedure - procedure get_token() - atom n, fraction - integer dec - skipspaces() - if ch=-1 then token = "eof" return end if - if ch>='0' and ch<='9' then - n = ch-'0' - while 1 do - nxtch(0) - if ch<'0' or ch>'9' then exit end if - n = n*10+ch-'0' - end while - if ch='.' then - dec = 1 - fraction = 0 - while 1 do - nxtch(0) - if ch<'0' or ch>'9' then exit end if - fraction = fraction*10 + ch-'0' - dec *= 10 - end while - n += fraction/dec - end if - -- if find(ch,"eE") then -- you get the idea - -- end if - token = n - return - end if - if find(ch,"+-/*()^%")=0 then err("syntax error") end if - token = s[sidx..sidx] - nxtch(0) - return - end procedure +procedure Match(string t) + if token!=t then err(t&" expected") end if + get_token() +end procedure - procedure Match(string t) - if token!=t then err(t&" expected") end if - get_token() - end procedure +procedure PopFactor() + object p1, p2 = opstack[$], f + if op="u-" then + p1 = 0 + else + opstack = opstack[1..$-1] + p1 = opstack[$] + end if + switch opp do + case op_p_p: f = {op,p1,p2} + case p_op_p: f = {p1,op,p2} + case p_p_op: f = {p1,p2,op} + end switch + opstack[$] = f + op = 0 +end procedure - procedure PopFactor() - object p1, p2 = opstack[$] - if op="u-" then - p1 = 0 - else - opstack = opstack[1..$-1] - p1 = opstack[$] - end if - if op_p_p=1 then - opstack[$] = {op,p1,p2} -- op_p_p - elsif op_p_p=0 then - opstack[$] = {p1,op,p2} -- p_op_p - else -- -1 - opstack[$] = {p1,p2,op} -- p_p_op - end if - op = 0 - end procedure +procedure PushFactor(atom t) + if op!=0 then PopFactor() end if + opstack = append(opstack,t) +end procedure - procedure PushFactor(atom t) - if op!=0 then PopFactor() end if - opstack = append(opstack,t) - end procedure +procedure PushOp(string t) + if op!=0 then PopFactor() end if + op = t +end procedure - procedure PushOp(string t) - if op!=0 then PopFactor() end if - op = t - end procedure +forward procedure Expr(integer p) - forward procedure Expr(integer p) +procedure Factor() + if atom(token) then + PushFactor(token) + if ch!=-1 then + get_token() + end if + elsif token="+" then -- (ignore) + nxtch() + Factor() + elsif token="-" then + get_token() +-- Factor() + Expr(3) -- makes "-3^2" yield -9 (ie -(3^2)) not 9 (ie (-3)^2). + if op!=0 then PopFactor() end if + if integer(opstack[$]) then + opstack[$] = -opstack[$] + else + PushOp("u-") + end if + elsif token="(" then + get_token() + Expr(0) + Match(")") + else + err("syntax error") + end if +end procedure - procedure Factor() - if atom(token) then - PushFactor(token) - if ch!=-1 then - get_token() - end if - elsif token="+" then -- (ignore) - nxtch() - Factor() - elsif token="-" then - get_token() - -- Factor() - Expr(3) -- makes "-3^2" yield -9 (ie -(3^2)) not 9 (ie (-3)^2). - if op!=0 then PopFactor() end if - if integer(opstack[$]) then - opstack[$] = -opstack[$] - else - PushOp("u-") - end if - elsif token="(" then - get_token() - Expr(0) - Match(")") - else - err("syntax error") - end if - end procedure +constant {operators, + precedence, + associativity} = columnize({{"^",3,0}, + {"%",2,1}, + {"*",2,1}, + {"/",2,1}, + {"+",1,1}, + {"-",1,1}, + $}) - constant {operators, - precedence, - associativity} = columnize({{"^",3,0}, - {"%",2,1}, - {"*",2,1}, - {"/",2,1}, - {"+",1,1}, - {"-",1,1}, - $}) +procedure Expr(integer p) +-- +-- Parse an expression, using precedence climbing. +-- +-- p is the precedence level we should parse to, eg/ie +-- 4: Factor only (may as well just call Factor) +-- 3: "" and ^ +-- 2: "" and *,/,% +-- 1: "" and +,- +-- 0: full expression (effectively the same as 1) +-- obviously, parentheses override any setting of p. +-- + Factor() + while 1 do + integer k = find(token,operators) -- *,/,+,- + if k=0 then exit end if + integer thisp = precedence[k] + if thisp

    procedure Expr(integer p) - -- - -- Parse an expression, using precedence climbing. - -- - -- p is the precedence level we should parse to, eg/ie - -- 4: Factor only (may as well just call Factor) - -- 3: "" and ^ - -- 2: "" and *,/,% - -- 1: "" and +,- - -- 0: full expression (effectively the same as 1) - -- obviously, parentheses override any setting of p. - -- - integer k, thisp - Factor() - while 1 do - k = find(token,operators) -- *,/,+,- - if k=0 then exit end if - thisp = precedence[k] - if thisp<p then exit end if - get_token() - Expr(thisp+associativity[k]) - PushOp(operators[k]) - end while - end procedure +function evaluate(object s) + object lhs, rhs + string op + if atom(s) then return s end if + switch opp do + case op_p_p: {op,lhs,rhs} = s + case p_op_p: {lhs,op,rhs} = s + case p_p_op: {lhs,rhs,op} = s + default: ?9/0 + end switch + if sequence(lhs) then lhs = evaluate(lhs) end if + if sequence(rhs) then rhs = evaluate(rhs) end if + if op="+" then return lhs+rhs + elsif op="-" then return lhs-rhs + elsif op="*" then return lhs*rhs + elsif op="/" then return lhs/rhs + elsif op="^" then return power(lhs,rhs) + elsif op="%" then return rmdr(lhs,rhs) + elsif op="u-" then return -rhs + else ?9/0 + end if +end function - function evaluate(object s) - object lhs, rhs - string op - if atom(s) then - return s - end if - if op_p_p=1 then -- op_p_p - {op,lhs,rhs} = s - elsif op_p_p=0 then -- p_op_p - {lhs,op,rhs} = s - else -- -1 -- p_p_op - {lhs,rhs,op} = s - end if - if sequence(lhs) then lhs = evaluate(lhs) end if - if sequence(rhs) then rhs = evaluate(rhs) end if - if op="+" then - return lhs+rhs - elsif op="-" then - return lhs-rhs - elsif op="*" then - return lhs*rhs - elsif op="/" then - return lhs/rhs - elsif op="^" then - return power(lhs,rhs) - elsif op="%" then - return remainder(lhs,rhs) - elsif op="u-" then - return -rhs - else - ?9/0 - end if - end function - - s = "3+4+5+6*7/1*5^2^3" -- 16406262 - sidx = 0 - nxtch() - get_token() - Expr(0) - if op!=0 then PopFactor() end if - if length(opstack)!=1 then err("some error") end if - printf(1,"expression: \"%s\"\n",{s}) - puts(1,"AST (flat): ") - ?opstack[1] - puts(1,"AST (tree):\n") - ppEx(opstack[1],{pp_Nest,9999}) - puts(1,"result: ") - ?evaluate(opstack[1]) - {} = wait_key() - - with javascript_semantics - sequence arithmetic = {1} - integer composite = 0 +with javascript_semantics +sequence arithmetic = {1} +integer composite = 0 - function get_arithmetic(integer nth) - integer n = arithmetic[$]+1 - while length(arithmetic)<nth do - sequence divs = factors(n,1) - if remainder(sum(divs),length(divs))=0 then - composite += length(divs)>2 - arithmetic &= n - end if - n += 1 - end while - return arithmetic[nth] - end function +procedure get_arithmetics(integer nth) + integer n = arithmetic[$]+1 + while length(arithmetic)2 + arithmetic &= n + end if + n += 1 + end while +end procedure - {} = get_arithmetic(100) - printf(1,"The first 100 arithmetic numbers are:\n%s\n", - {join_by(arithmetic,1,10," ",fmt:="%3d")}) - constant fmt = "The %,dth arithmetic number is %,d up to which %,d are composite.\n" - for n in {1e3,1e4,1e5,1e6} do - integer nth = get_arithmetic(n) - printf(1,fmt,{n,nth,composite}) - end for -(quotient,remainder) - if(r==0) return(self.fcn(q,k,acc.write(k),q.toFloat().sqrt())); - return(self.fcn(n,k+1+k.isOdd,acc,maxD)) + q,r:=n.divr(k); // divr-->(quotient,remainder) + if(r==0) return(self.fcn(q,k,acc.write(k),q.toFloat().sqrt())); + return(self.fcn(n,k+1+k.isOdd,acc,maxD)) } }(n,2,Sink(List),n.toFloat().sqrt()); m:=acc.reduce('*,1); // mulitply factors diff --git a/Task/Average-loop-length/Ada/average-loop-length.ada b/Task/Average-loop-length/Ada/average-loop-length.adb similarity index 100% rename from Task/Average-loop-length/Ada/average-loop-length.ada rename to Task/Average-loop-length/Ada/average-loop-length.adb diff --git a/Task/Average-loop-length/Crystal/average-loop-length.cr b/Task/Average-loop-length/Crystal/average-loop-length.cr new file mode 100644 index 0000000000..713284e441 --- /dev/null +++ b/Task/Average-loop-length/Crystal/average-loop-length.cr @@ -0,0 +1,26 @@ +struct Int + def factorial + raise "only positive" if self < 0 + (1_i64..self.to_i64).product + end +end + +def rand_until_rep (n) + rands = {} of Int32 => Bool + loop do + r = rand(1..n) + return rands.size if rands[r]? + rands[r] = true + end +end + +runs = 1_000_000 + +puts " N average exp. diff ", + "=== ======== ======== ===========" +(1..20).each do |n| + sum_of_runs = runs.times.sum(0_i64) { rand_until_rep(n) } + avg = sum_of_runs / runs + analytical = (1..n).sum(0.0) {|i| (n.factorial / (n.to_f**i) / (n-i).factorial) } + puts "%3d %8.4f %8.4f (%8.4f%%)" % {n, avg, analytical, (avg/analytical - 1)*100} +end diff --git a/Task/Average-loop-length/Delphi/average-loop-length.delphi b/Task/Average-loop-length/Delphi/average-loop-length.pas similarity index 100% rename from Task/Average-loop-length/Delphi/average-loop-length.delphi rename to Task/Average-loop-length/Delphi/average-loop-length.pas diff --git a/Task/Average-loop-length/EasyLang/average-loop-length.easy b/Task/Average-loop-length/EasyLang/average-loop-length.easy index 8440cfd706..d036ff7912 100644 --- a/Task/Average-loop-length/EasyLang/average-loop-length.easy +++ b/Task/Average-loop-length/EasyLang/average-loop-length.easy @@ -1,11 +1,11 @@ -func average n reps . +fastfunc average n reps . + len f[] n + len seen[] n for r to reps - f[] = [ ] - for i to n - f[] &= randint n + for i = 1 to n + f[i] = random 1 n + seen[i] = 0 . - seen[] = [ ] - len seen[] n x = 1 while seen[x] = 0 seen[x] = 1 @@ -15,7 +15,7 @@ func average n reps . . return count / reps . -func analytical n . +fastfunc analytical n . s = 1 t = 1 for i = n - 1 downto 1 @@ -30,8 +30,8 @@ for n to 20 avg = average n 1e6 ana = analytical n err = (avg - ana) / ana * 100 - numfmt 0 2 + numfmt 2 0 write n - numfmt 4 9 + numfmt 9 4 print avg & ana & err & "%" . diff --git a/Task/Average-loop-length/Elixir/average-loop-length.elixir b/Task/Average-loop-length/Elixir/average-loop-length.ex similarity index 100% rename from Task/Average-loop-length/Elixir/average-loop-length.elixir rename to Task/Average-loop-length/Elixir/average-loop-length.ex diff --git a/Task/Average-loop-length/JavaScript/average-loop-length.js b/Task/Average-loop-length/JavaScript/average-loop-length.js new file mode 100644 index 0000000000..68e1ae0b93 --- /dev/null +++ b/Task/Average-loop-length/JavaScript/average-loop-length.js @@ -0,0 +1,49 @@ +const MAX_N = 20 +const TIMES = 1000000 + +function factorial(n) { + let prod = 1; + for (let i = n; i > 1; i--) { + prod *= i; + } + return prod; +} + +function getRandomInt(min, max) { + min = Math.ceil(min); + max = Math.floor(max); + return Math.floor(Math.random() * (max - min + 1)) + min; +} + + +function analytical(n) { + let items = []; + + for (let i = 1; i < n+1; i++) { + items.push(factorial(n) / Math.pow(n, i) / factorial(n - i)); + } + + return items.reduce((p, v) => p + v, 0); +} + +function test(n, times) { + let count = 0; + for (let i = 0; i < times; i++) { + let x = 1, bits = 0; + + while (!(bits & x)) { + count += 1; + bits |= x; + x = 1 << getRandomInt(0, n-1); + } + } + return count / times; +} + +console.log(" n\tavg\texp.\tdiff\n-------------------------------"); +for(let n = 1; n < MAX_N+1; n++) { + const avg = test(n, TIMES); + const theory = analytical(n); + const diff = (avg / theory - 1) * 100; + console.log(`${n.toString().padStart(2)} ${avg.toFixed(4).padStart(8)} ${theory.toFixed(4).padStart(8)} ${diff.toFixed(3).padStart(6)}%`); +} diff --git a/Task/Average-loop-length/Julia/average-loop-length.julia b/Task/Average-loop-length/Julia/average-loop-length.jl similarity index 100% rename from Task/Average-loop-length/Julia/average-loop-length.julia rename to Task/Average-loop-length/Julia/average-loop-length.jl diff --git a/Task/Average-loop-length/Kotlin/average-loop-length.kotlin b/Task/Average-loop-length/Kotlin/average-loop-length.kts similarity index 100% rename from Task/Average-loop-length/Kotlin/average-loop-length.kotlin rename to Task/Average-loop-length/Kotlin/average-loop-length.kts diff --git a/Task/Average-loop-length/Phix/average-loop-length.phix b/Task/Average-loop-length/Phix/average-loop-length.phix index bb282fbcdf..275c4a1507 100644 --- a/Task/Average-loop-length/Phix/average-loop-length.phix +++ b/Task/Average-loop-length/Phix/average-loop-length.phix @@ -1,35 +1,31 @@ -(phixonline)--> - constant MAX = 20, - ITER = 1000000 +with javascript_semantics +constant MAX = 20, + ITER = 1000000 - function expected(integer n) - atom sum = 0 - for i=1 to n do - sum += factorial(n) / power(n,i) / factorial(n-i) - end for - return sum - end function +function expected(integer n) + atom res = 0 + for i=1 to n do + res += factorial(n)/power(n,i)/factorial(n-i) + end for + return res +end function - function test(integer n) - integer count = 0, x, bits - for i=1 to ITER do - x = 1 - bits = 0 - while not and_bits(bits,x) do - count += 1 - bits = or_bits(bits,x) - x = power(2,rand(n)-1) - end while - end for - return count/ITER - end function +function test(integer n) + integer count = 0 + for i=1 to ITER do + integer x = 1, bits = 0 + while not and_bits(bits,x) do + count += 1 + bits = or_bits(bits,x) + x = power(2,rand(n)-1) + end while + end for + return count/ITER +end function - atom av, ex - puts(1," n avg. exp. (error%)\n"); - puts(1,"== ====== ====== ========\n"); - for n=1 to MAX do - av = test(n) - ex = expected(n) - printf(1,"%2d %8.4f %8.4f (%5.3f%%)\n", {n,av,ex,abs(1-av/ex)*100}) - end for - - with javascript_semantics - function MeanAngle(sequence angles) - atom x = 0, y = 0 - for i=1 to length(angles) do - atom ai_rad = angles[i]*PI/180 - x += cos(ai_rad) - y += sin(ai_rad) - end for - if abs(x)<1e-16 then return "not meaningful" end if - return sprintf("%g",round(atan2(y,x)*180/PI,1e10)) - end function +with javascript_semantics +function MeanAngle(sequence angles) + atom x = 0, y = 0 + for a in sq_mul(angles,PI/180) do + x += cos(a) + y += sin(a) + end for + if abs(x)<1e-15 then return "not meaningful" end if + return sprintf("%g",round(atan2(y,x)*180/PI,1e10)) +end function - constant AngleLists = {{350,10},{90,180,270,360},{10,20,30},{180},{0,180}} - for i=1 to length(AngleLists) do - sequence ai = AngleLists[i] - printf(1,"%16V: Mean Angle is %s\n",{ai,MeanAngle(ai)}) - end for - - with javascript_semantics - function MeanAngle(sequence angles) - atom x = 0, y = 0 - for i=1 to length(angles) do - atom ai_rad = angles[i]*PI/180 - x += cos(ai_rad) - y += sin(ai_rad) - end for - if abs(x)<1e-16 then return "not meaningful" end if - return atan2(y,x)*180/PI - end function +with javascript_semantics +function MeanAngle(sequence angles) + atom x = 0, y = 0 + for i=1 to length(angles) do + atom ai_rad = angles[i]*PI/180 + x += cos(ai_rad) + y += sin(ai_rad) + end for + if abs(x)<1e-16 then return "not meaningful" end if + return atan2(y,x)*180/PI +end function - function toSecAngle(integer hours, integer minutes, integer seconds) - return ((hours*60+minutes)*60+seconds)/(24*60*60)*360 - end function +function toSecAngle(integer hours, integer minutes, integer seconds) + return ((hours*60+minutes)*60+seconds)/(24*60*60)*360 +end function - constant Times = {toSecAngle(23,00,17), - toSecAngle(23,40,20), - toSecAngle(00,12,45), - toSecAngle(00,17,19)} +constant Times = {toSecAngle(23,00,17), + toSecAngle(23,40,20), + toSecAngle(00,12,45), + toSecAngle(00,17,19)} - function toHMS(object s) - if not string(s) then - if s<0 then s+=360 end if - s = 24*60*60*s/360 - atom hours = floor(s/3600), - mins = floor(remainder(s,3600)/60), - secs = remainder(s,60) - s = sprintf("%02d:%02d:%02d",{hours,mins,secs}) - end if - return s - end function +function toHMS(object s) + if not string(s) then + if s<0 then s+=360 end if + s = 24*60*60*s/360 + atom hours = floor(s/3600), + mins = floor(remainder(s,3600)/60), + secs = remainder(s,60) + s = sprintf("%02d:%02d:%02d",{hours,mins,secs}) + end if + return s +end function - printf(1,"Mean Time is %s\n",{toHMS(MeanAngle(Times))}) - - function mode(sequence s) - -- returns a list of the most common values, each of which occurs the same number of times - integer nxt = 1, count = 1, maxc = 1 - sequence res = {} - if length(s)!=0 then - s = sort(s) - object prev = s[1] - for i=2 to length(s) do - if s[i]!=prev then - s[nxt] = {count,prev} - nxt += 1 - prev = s[i] - count = 1 - else - count += 1 - if count>maxc then - maxc = count - end if - end if - end for - s[nxt] = {count,prev} - res = "" - for i=1 to nxt do - if s[i][1]=maxc then - res = append(res,s[i][2]) - end if - end for - end if - return res - end function +with javascript_semantics +function mode(sequence s) +-- returns a list of the most common values, each of which occurs the same number of times + integer nxt = 1, count = 1, maxc = 1 + sequence res = {} + if length(s)!=0 then + s = sort(s) + object prev = s[1] + for i=2 to length(s) do + if s[i]!=prev then + s[nxt] = {count,prev} + nxt += 1 + prev = s[i] + count = 1 + else + count += 1 + if count>maxc then + maxc = count + end if + end if + end for + s[nxt] = {count,prev} + res = "" + for i=1 to nxt do + if s[i][1]=maxc then + res = append(res,s[i][2]) + end if + end for + end if + return res +end function - ?mode({1, 2, 5, -5, -9.5, 3.14159}) - ?mode({ 1, "blue", 2, 7.5, 5, "green", "red", 5, 2, "blue", "white" }) - ?mode({1, 2, 3, 1, 2, 4, 2, 5, 2, 3, 3, 1, 3, 6}) - ?mode({.2, .7, .1, .8, .2}) - ?mode({"two", 7, 1, 8, "two", 8}) - ?mode("Hello there world") - ?mode({}) - {} = wait_key() - - with javascript_semantics - sequence sma = {} -- ((period,history,circnxt)) (private to sma.e) - integer sma_free = 0 - - global function new_sma(integer period) - integer res - if sma_free then - res = sma_free - sma_free = sma[sma_free] - sma[res] = {period,{},0} - else - sma = append(sma,{period,{},0}) - res = length(sma) - end if - return res - end function - - global procedure add_sma(integer sidx, atom val) - integer period, circnxt - sequence history - {period,history,circnxt} = sma[sidx] - sma[sidx][2] = 0 -- (kill refcount) - if length(history)<period then - history = append(history,val) - else - circnxt += 1 - if circnxt>period then - circnxt = 1 - end if - sma[sidx][3] = circnxt - history[circnxt] = val - end if - sma[sidx][2] = history - end procedure - - global function get_sma_average(integer sidx) - sequence history = sma[sidx][2] - integer l = length(history) - if l=0 then return 0 end if - return sum(history)/l - end function - - global function moving_average(integer sidx, atom val) - add_sma(sidx,val) - return get_sma_average(sidx) - end function - - global procedure free_sma(integer sidx) - sma[sidx] = sma_free - sma_free = sidx - end procedure - - with javascript_semantics - include sma.e - - constant sma3 = new_sma(3) - constant sma5 = new_sma(5) - constant s = {1,2,3,4,5,5,4,3,2,1} - integer si - - for i=1 to length(s) do - si = s[i] - printf(1,"%2g: sma3=%8g, sma5=%8g\n",{si,moving_average(sma3,si),moving_average(sma5,si)}) - end for - - with javascript_semantics - for i=2 to 99736 by 2 do - if remainder(i*i,1000000)=269696 then ?i exit end if - end for - - with javascript_semantics - procedure solve_babbage_problem() -- (so that return quits 3 loops) - sequence cands = {0}, -- n-digit candidates (n initially 0) - nextc = {} -- n+1-digit candidates, aka next "" - integer p10 = 1, -- power of 10 for adding prefixes - r10 = 10, -- power of 10 for getting remainder - cc = 0 -- count of calculations - for digits=1 to 6 do -- aka 1..length("269696") - for prefix=0 to 9*p10 by p10 do - for cand in sq_add(prefix,cands) do - atom square = cand*cand - cc += 1 - if remainder(square,r10) = remainder(269696,r10) then - if digits=6 then - printf(1,"Solution: %d (%d calcs)\n",{cand,cc}) - return -- leave solve_babbage_problem() - end if - nextc &= cand -- add candidate for next iteration - end if - end for - end for - {cands,nextc} = {nextc,{}} - printf(1,"%d-digit candidates: %v\n",{digits,cands}) - p10 *= 10 - r10 *= 10 - end for - end procedure - solve_babbage_problem() - []. balanced_brackets --> - ['['], - balanced_brackets, - [']']. + ['['], + balanced_brackets, + [']']. balanced_brackets --> - ['[',']'], - balanced_brackets. + ['[',']'], + balanced_brackets. % generator of random brackets gen_bracket(0) --> []. gen_bracket(N) --> - {N1 is N - 1, - R is random(2)}, - bracket(R), - gen_bracket(N1). + {N1 is N - 1, + R is random(2)}, + bracket(R), + gen_bracket(N1). bracket(0) --> ['[']. bracket(1) --> [']']. diff --git a/Task/Balanced-brackets/Rebol/balanced-brackets.rebol b/Task/Balanced-brackets/Rebol/balanced-brackets.rebol new file mode 100644 index 0000000000..63f0bd4e48 --- /dev/null +++ b/Task/Balanced-brackets/Rebol/balanced-brackets.rebol @@ -0,0 +1,21 @@ +Rebol [ + title: "Rosetta code: Balanced brackets" + file: %Balanced_brackets.r3 + url: https://rosettacode.org/wiki/Balanced_brackets +] + +;; Returns TRUE if all square brackets in `str` are properly nested and balanced +balanced?: function/with [str][parse str rule][ + ;; Recursive rule: a balanced group is [ followed by any nested balanced groups, then ] + balanced-brackets: [#"[" any balanced-brackets #"]"] + ;; Full string must consist entirely of balanced groups with nothing left over + rule: [any balanced-brackets end] +] + +;; Test: generate 10 random substrings of bracket pairs and check each +random/seed 2 +repeat i 10 [ + str: random copy/part "[][][][][][][][][][]" i * 2 ;; shuffle first i*2 chars + res: pick ["balanced" "unbalanced"] balanced? str ;; label the result + printf [-2 ". " 11] reduce [i res mold str] ;; print index, verdict, string +] diff --git a/Task/Balanced-brackets/Red/balanced-brackets.red b/Task/Balanced-brackets/Red/balanced-brackets.red index a5fc247878..40d773a9f3 100644 --- a/Task/Balanced-brackets/Red/balanced-brackets.red +++ b/Task/Balanced-brackets/Red/balanced-brackets.red @@ -5,18 +5,18 @@ balanced?: func [str][parse str rule] ; Tests tests: [ - good: ["" "[]" "[][]" "[[]]" "[[][]]" "[[[[[]]][][[]]]]"] - bad: ["[" "]" "][" "[[]" "[]]" "[]][[]" "[[[[[[]]]]]]]"] + good: ["" "[]" "[][]" "[[]]" "[[][]]" "[[[[[]]][][[]]]]"] + bad: ["[" "]" "][" "[[]" "[]]" "[]][[]" "[[[[[[]]]]]]]"] ] foreach str tests/good [ - if not balanced? str [print [mold str "failed!"]] + if not balanced? str [print [mold str "failed!"]] ] foreach str tests/bad [ - if balanced? str [print [mold str "failed!"]] + if balanced? str [print [mold str "failed!"]] ] repeat i 10 [ - str: random copy/part "[][][][][][][][][][]" i * 2 - print [mold str "is" either balanced? str ["balanced"]["unbalanced"]] + str: random copy/part "[][][][][][][][][][]" i * 2 + print [mold str "is" either balanced? str ["balanced"]["unbalanced"]] ] diff --git a/Task/Balanced-brackets/Rust/balanced-brackets.rust b/Task/Balanced-brackets/Rust/balanced-brackets.rs similarity index 100% rename from Task/Balanced-brackets/Rust/balanced-brackets.rust rename to Task/Balanced-brackets/Rust/balanced-brackets.rs diff --git a/Task/Balanced-brackets/Scheme/balanced-brackets.ss b/Task/Balanced-brackets/Scheme/balanced-brackets.scm similarity index 100% rename from Task/Balanced-brackets/Scheme/balanced-brackets.ss rename to Task/Balanced-brackets/Scheme/balanced-brackets.scm diff --git a/Task/Balanced-brackets/Stata/balanced-brackets.stata b/Task/Balanced-brackets/Stata/balanced-brackets.stata index ce238f97e3..83eedcefc9 100644 --- a/Task/Balanced-brackets/Stata/balanced-brackets.stata +++ b/Task/Balanced-brackets/Stata/balanced-brackets.stata @@ -1,12 +1,12 @@ mata function random_brackets(n) { - return(invtokens(("[","]")[runiformint(1,2*n,1,2)],"")) + return(invtokens(("[","]")[runiformint(1,2*n,1,2)],"")) } function is_balanced(s) { - n = strlen(s) - if (n==0) return(1) - a = runningsum(92:-ascii(s)) - return(all(a:>=0) & a[n]==0) + n = strlen(s) + if (n==0) return(1) + a = runningsum(92:-ascii(s)) + return(all(a:>=0) & a[n]==0) } end diff --git a/Task/Balanced-brackets/Tcl/balanced-brackets-1.tcl b/Task/Balanced-brackets/Tcl/balanced-brackets-1.tcl index 82d7ece066..2e2beb8e8f 100644 --- a/Task/Balanced-brackets/Tcl/balanced-brackets-1.tcl +++ b/Task/Balanced-brackets/Tcl/balanced-brackets-1.tcl @@ -3,9 +3,9 @@ proc generate {n} { set l [lrepeat $n "\[" "\]"] set len [llength $l] while {$len} { - set tmp [lindex $l [set i [expr {int($len * rand())}]]] - lset l $i [lindex $l [incr len -1]] - lset l $len $tmp + set tmp [lindex $l [set i [expr {int($len * rand())}]]] + lset l $i [lindex $l [incr len -1]] + lset l $len $tmp } return [join $l ""] } @@ -13,11 +13,11 @@ proc generate {n} { proc balanced s { set n 0 foreach c [split $s ""] { - # Everything unmatched is ignored, which is what we want - switch -exact -- $c { - "\[" {incr n} - "\]" {if {[incr n -1] < 0} {return false}} - } + # Everything unmatched is ignored, which is what we want + switch -exact -- $c { + "\[" {incr n} + "\]" {if {[incr n -1] < 0} {return false}} + } } expr {!$n} } diff --git a/Task/Balanced-brackets/Tcl/balanced-brackets-2.tcl b/Task/Balanced-brackets/Tcl/balanced-brackets-2.tcl index f01beac2ea..e0e4f4a0b7 100644 --- a/Task/Balanced-brackets/Tcl/balanced-brackets-2.tcl +++ b/Task/Balanced-brackets/Tcl/balanced-brackets-2.tcl @@ -1,8 +1,8 @@ proc constructBalancedString {n} { set s "" for {set i 0} {$i < $n} {incr i} { - set x [expr {int(rand() * ([string length $s] + 1))}] - set s "[string range $s 0 [expr {$x-1}]]\[\][string range $s $x end]" + set x [expr {int(rand() * ([string length $s] + 1))}] + set s "[string range $s 0 [expr {$x-1}]]\[\][string range $s $x end]" } return $s } diff --git a/Task/Balanced-brackets/VBScript/balanced-brackets-1.vb b/Task/Balanced-brackets/VBScript/balanced-brackets-1.vb deleted file mode 100644 index 8a458a26f4..0000000000 --- a/Task/Balanced-brackets/VBScript/balanced-brackets-1.vb +++ /dev/null @@ -1,36 +0,0 @@ -For n = 1 To 10 - sequence = Generate_Sequence(n) - WScript.Echo sequence & " is " & Check_Balance(sequence) & "." -Next - -Function Generate_Sequence(n) - For i = 1 To n - j = Round(Rnd()) - If j = 0 Then - Generate_Sequence = Generate_Sequence & "[" - Else - Generate_Sequence = Generate_Sequence & "]" - End If - Next -End Function - -Function Check_Balance(s) - Set Stack = CreateObject("System.Collections.Stack") - For i = 1 To Len(s) - char = Mid(s,i,1) - If i = 1 Or char = "[" Then - Stack.Push(char) - ElseIf Stack.Count <> 0 Then - If char = "]" And Stack.Peek = "[" Then - Stack.Pop - End If - Else - Stack.Push(char) - End If - Next - If Stack.Count > 0 Then - Check_Balance = "Not Balanced" - Else - Check_Balance = "Balanced" - End If -End Function diff --git a/Task/Balanced-brackets/VBScript/balanced-brackets-1.vbs b/Task/Balanced-brackets/VBScript/balanced-brackets-1.vbs new file mode 100644 index 0000000000..d271076d80 --- /dev/null +++ b/Task/Balanced-brackets/VBScript/balanced-brackets-1.vbs @@ -0,0 +1,36 @@ +For n = 1 To 10 + sequence = Generate_Sequence(n) + WScript.Echo sequence & " is " & Check_Balance(sequence) & "." +Next + +Function Generate_Sequence(n) + For i = 1 To n + j = Round(Rnd()) + If j = 0 Then + Generate_Sequence = Generate_Sequence & "[" + Else + Generate_Sequence = Generate_Sequence & "]" + End If + Next +End Function + +Function Check_Balance(s) + Set Stack = CreateObject("System.Collections.Stack") + For i = 1 To Len(s) + char = Mid(s,i,1) + If i = 1 Or char = "[" Then + Stack.Push(char) + ElseIf Stack.Count <> 0 Then + If char = "]" And Stack.Peek = "[" Then + Stack.Pop + End If + Else + Stack.Push(char) + End If + Next + If Stack.Count > 0 Then + Check_Balance = "Not Balanced" + Else + Check_Balance = "Balanced" + End If +End Function diff --git a/Task/Balanced-brackets/VBScript/balanced-brackets-2.vb b/Task/Balanced-brackets/VBScript/balanced-brackets-2.vb deleted file mode 100644 index cb0beeaef5..0000000000 --- a/Task/Balanced-brackets/VBScript/balanced-brackets-2.vb +++ /dev/null @@ -1,40 +0,0 @@ -option explicit - -function do_brackets(bal) - dim s,i,cnt,r - if bal then s="[":cnt=1 else s="":cnt=0 - for i=1 to 20 - if (rnd>0.7) then r=not r - if not r then - s=s+"[" :cnt=cnt+1 - else - if not bal or (bal and cnt>0) then s=s+"]":cnt=cnt-1 - end if - next - if bal and cnt<>0 then s=s&string(cnt,"]") - if not bal and cnt=0 then s=s&"]" - do_brackets=s -end function - -function isbalanced(s) - dim s1,i,cnt: cnt=0 - for i=1 to len(s) - s1=mid(s,i,1) - if s1="[" then cnt=cnt+1 - if s1="]" then cnt=cnt-1 - if cnt<0 then isbalanced=false:exit function - next - isbalanced=(cnt=0) -end function - -function iif(a,b,c): if a then iif=b else iif=c end if : end function - -randomize timer -dim i,s,bal,bb -for i=1 to 10 - bal=(rnd>.5) - s=do_brackets(bal) - bb=isbalanced(s) - wscript.echo iif (bal,"","un")& "balanced string " &vbtab _ - & s & vbtab & " Checks as " & iif(bb,"","un")&"balanced" -next diff --git a/Task/Balanced-brackets/VBScript/balanced-brackets-2.vbs b/Task/Balanced-brackets/VBScript/balanced-brackets-2.vbs new file mode 100644 index 0000000000..674efc6e13 --- /dev/null +++ b/Task/Balanced-brackets/VBScript/balanced-brackets-2.vbs @@ -0,0 +1,40 @@ +option explicit + +function do_brackets(bal) + dim s,i,cnt,r + if bal then s="[":cnt=1 else s="":cnt=0 + for i=1 to 20 + if (rnd>0.7) then r=not r + if not r then + s=s+"[" :cnt=cnt+1 + else + if not bal or (bal and cnt>0) then s=s+"]":cnt=cnt-1 + end if + next + if bal and cnt<>0 then s=s&string(cnt,"]") + if not bal and cnt=0 then s=s&"]" + do_brackets=s +end function + +function isbalanced(s) + dim s1,i,cnt: cnt=0 + for i=1 to len(s) + s1=mid(s,i,1) + if s1="[" then cnt=cnt+1 + if s1="]" then cnt=cnt-1 + if cnt<0 then isbalanced=false:exit function + next + isbalanced=(cnt=0) +end function + +function iif(a,b,c): if a then iif=b else iif=c end if : end function + +randomize timer +dim i,s,bal,bb +for i=1 to 10 + bal=(rnd>.5) + s=do_brackets(bal) + bb=isbalanced(s) + wscript.echo iif (bal,"","un")& "balanced string " &vbtab _ + & s & vbtab & " Checks as " & iif(bb,"","un")&"balanced" +next diff --git a/Task/Balanced-brackets/XBS/balanced-brackets.xbs b/Task/Balanced-brackets/XBS/balanced-brackets.xbs index 3bccd7da4a..11305dd643 100644 --- a/Task/Balanced-brackets/XBS/balanced-brackets.xbs +++ b/Task/Balanced-brackets/XBS/balanced-brackets.xbs @@ -1,17 +1,17 @@ const Chars:[string] = ["[","]"]; func GenerateString(Amount:number=4):string{ - set Result:string = ""; - <|(*1..Amount)=>Result+=Chars[math.random(0,?Chars-1)]; - send Result; + set Result:string = ""; + <|(*1..Amount)=>Result+=Chars[math.random(0,?Chars-1)]; + send Result; } func IsBalanced(String:string):boolean{ - set Pairs:number = 0; - <|(*(0..(?String-1)))=>(String::at(_)=="[")?(Pairs<0)?=>send false,Pairs++,=>Pairs--; - send (Opens==Closes)&(Pairs==0); + set Pairs:number = 0; + <|(*(0..(?String-1)))=>(String::at(_)=="[")?(Pairs<0)?=>send false,Pairs++,=>Pairs--; + send (Opens==Closes)&(Pairs==0); } repeat 10 { - set s = GenerateString(math.random(2,4)*2); - log(`{s}: {IsBalanced(s)}`); + set s = GenerateString(math.random(2,4)*2); + log(`{s}: {IsBalanced(s)}`); } diff --git a/Task/Balanced-brackets/Ya/balanced-brackets.ya b/Task/Balanced-brackets/Ya/balanced-brackets.ya index 0b3e76f880..40698505e5 100644 --- a/Task/Balanced-brackets/Ya/balanced-brackets.ya +++ b/Task/Balanced-brackets/Ya/balanced-brackets.ya @@ -4,34 +4,34 @@ // definition of anything new is prefixed by \, like \MakeNew_[]s and \len // MakeNew_[]s is Ok ident in Ya: _ starts sign part of ident, which must be ended by _ or alphanum `Char[^] \MakeNew_[]s(`Int+ \len) // `Char[^] and `Char[=] are arrays that owns their items, like it's usally in other langs; - // yet in assignment of `Char[^] to `Char[=] the allocated memory is moved from old to new owner, and old string becomes empty - // there are tabs at starts of many lines; these tabs specify what in C++ is {} blocks, just like in Python - len & 1 ==0 ! // it's a call to postfix function '!' which is an assert: len must be even - `Char[=] \r(len) // allocate new string of length len - // most statements are analogous to C++ but written starting by capital letter: For If Switch Ret - For `Char[] \eye = r; eye // // `Char[] is a simplest array of chars, which does not hold a memory used by array items; inc part of For loop is missed: it's Ok, and condition and init could also be missed - *eye++ = '['; *eye++ = '[' // fill r by "[][][]...". The only place with ; as statement delemiter: required because the statement is not started at new line. - // below is a shuffle of "[][][]..." array - For `Char[] \eye = r; ++eye // var eye is already defined, but being the same `Char[] it's Ok by using already exisiting var. ++eye is used: it allows use of eye[-1] inside - `Int+ \at = Random(eye/Length) // `Int+ is C++'s unsigned int. eye/Length: / is used for access to field, like in file path - eye[-1],eye[at] = eye[at],eye[-1] // swap using tuples; eye[-1] accesses char that is out of current array, yet it's allowed - Ret r // Ret is C's return + // yet in assignment of `Char[^] to `Char[=] the allocated memory is moved from old to new owner, and old string becomes empty + // there are tabs at starts of many lines; these tabs specify what in C++ is {} blocks, just like in Python + len & 1 ==0 ! // it's a call to postfix function '!' which is an assert: len must be even + `Char[=] \r(len) // allocate new string of length len + // most statements are analogous to C++ but written starting by capital letter: For If Switch Ret + For `Char[] \eye = r; eye // // `Char[] is a simplest array of chars, which does not hold a memory used by array items; inc part of For loop is missed: it's Ok, and condition and init could also be missed + *eye++ = '['; *eye++ = '[' // fill r by "[][][]...". The only place with ; as statement delemiter: required because the statement is not started at new line. + // below is a shuffle of "[][][]..." array + For `Char[] \eye = r; ++eye // var eye is already defined, but being the same `Char[] it's Ok by using already exisiting var. ++eye is used: it allows use of eye[-1] inside + `Int+ \at = Random(eye/Length) // `Int+ is C++'s unsigned int. eye/Length: / is used for access to field, like in file path + eye[-1],eye[at] = eye[at],eye[-1] // swap using tuples; eye[-1] accesses char that is out of current array, yet it's allowed + Ret r // Ret is C's return `Bool \AreBalanced(`Char[] \brackets) - `Int+ \extra = 0 - For ;brackets ;++brackets - Switch *brackets - '[' // it's a C++'s 'case': both 'case' and ':' are skipped being of no value; but the code for a case should be in block, which is here specifyed by tabs at next line start - ++extra - ']' - If !!extra // '!!' is `Bool not, like all other `Bool ops: && || ^^ - Ret No // No and False are C's false; Yes and True are C's true - --extra - // There is no default case, which is written as ':' - so if no case is Ok then it will fail just like if being written as on the next line - // : { 0! } // C's default: assert(0); - Ret extra == 0 + `Int+ \extra = 0 + For ;brackets ;++brackets + Switch *brackets + '[' // it's a C++'s 'case': both 'case' and ':' are skipped being of no value; but the code for a case should be in block, which is here specifyed by tabs at next line start + ++extra + ']' + If !!extra // '!!' is `Bool not, like all other `Bool ops: && || ^^ + Ret No // No and False are C's false; Yes and True are C's true + --extra + // There is no default case, which is written as ':' - so if no case is Ok then it will fail just like if being written as on the next line + // : { 0! } // C's default: assert(0); + Ret extra == 0 // function ala 'main' is not used: all global code from all modules are executed; so below is what typically is in ala 'main' For `Int \n=10; n; --n - // below note that new var 'brackets' is created inside args of func call - //@Std/StdIO/ is used here to use Print function; else it maybe changed to Use @Std/StdIO at global level before this For loop - @Std/StdIO/Print(; "%s : %s\n" ;`Char[=] \brackets = MakeNew_[]s(10) /* all bracket strings are of length 10 */; AreBalanced(brackets) ? "Ok" : "bad") - // note that starting arg of Print is missed by using ';' - default arg value is allowed to use for any arg, even if next args are written + // below note that new var 'brackets' is created inside args of func call + //@Std/StdIO/ is used here to use Print function; else it maybe changed to Use @Std/StdIO at global level before this For loop + @Std/StdIO/Print(; "%s : %s\n" ;`Char[=] \brackets = MakeNew_[]s(10) /* all bracket strings are of length 10 */; AreBalanced(brackets) ? "Ok" : "bad") + // note that starting arg of Print is missed by using ';' - default arg value is allowed to use for any arg, even if next args are written diff --git a/Task/Balanced-brackets/Yabasic/balanced-brackets.basic b/Task/Balanced-brackets/Yabasic/balanced-brackets.basic index f92e2488aa..f318913bce 100644 --- a/Task/Balanced-brackets/Yabasic/balanced-brackets.basic +++ b/Task/Balanced-brackets/Yabasic/balanced-brackets.basic @@ -1,6 +1,6 @@ sub check_brackets(s$) local level, i - + for i = 1 to len(s$) switch mid$(s$, i, 1) case "[": level = level + 1 : break diff --git a/Task/Balanced-brackets/Zig/balanced-brackets.zig b/Task/Balanced-brackets/Zig/balanced-brackets.zig new file mode 100644 index 0000000000..5528f6e13e --- /dev/null +++ b/Task/Balanced-brackets/Zig/balanced-brackets.zig @@ -0,0 +1,41 @@ +const std = @import("std"); +const print = std.debug.print; + +const max_pairs = 256; + +pub fn is_balanced(buf: []u8) bool { + var count: usize = 0; + for (buf) |ch| switch (ch) { + '[' => count += 1, + ']' => { + if (count == 0) return false; + count -= 1; + }, + else => return false, + }; + return count == 0; +} + +pub fn main() !void { + for (0..10) |n_pairs| { + if (n_pairs > max_pairs) + return error.MaximumNumberOfPairsExceded; + + var buf: [2 * max_pairs]u8 = undefined; + for (0..n_pairs) |i| buf[i] = '['; + for (n_pairs..n_pairs * 2) |i| buf[i] = ']'; + + const rand = std.crypto.random; + const len = n_pairs * 2; + const reps = 2; + for (0..len * reps) |i_rep| { + const i = i_rep % len; + const j = rand.int(usize) % len; + const temp = buf[i]; + buf[i] = buf[j]; + buf[j] = temp; + } + const s = buf[0..len]; + print("'{s}': {}\n", .{ s, is_balanced(s) }); + } +} diff --git a/Task/Balanced-ternary/00-TASK.txt b/Task/Balanced-ternary/00-TASK.txt index 6b6f6bb48f..f548e4c8c0 100644 --- a/Task/Balanced-ternary/00-TASK.txt +++ b/Task/Balanced-ternary/00-TASK.txt @@ -10,13 +10,13 @@ Decimal 6 = 32 − 31 + 0 × 30, thus it can b ;Task: Implement balanced ternary representation of integers with the following: # Support arbitrarily large integers, both positive and negative; -# Provide ways to convert to and from text strings, using digits '+', '-' and '0' (unless you are already using strings to represent balanced ternary; but see requirement 5). +# Provide ways to convert to and from text strings, using digits '+', '−' and '0' (unless you are already using strings to represent balanced ternary; but see requirement 5). # Provide ways to convert to and from native integer type (unless, improbably, your platform's native integer type ''is'' balanced ternary). If your native integers can't support arbitrary length, overflows during conversion must be indicated. # Provide ways to perform addition, negation and multiplication directly on balanced ternary integers; do ''not'' convert to native integers first. # Make your implementation efficient, with a reasonable definition of "efficient" (and with a reasonable definition of "reasonable"). -'''Test case''' With balanced ternaries ''a'' from string "+-0++0+", ''b'' from native integer -436, ''c'' "+-++-": +'''Test case''' With balanced ternaries ''a'' from string "+−0++0+", ''b'' from native integer −436, ''c'' "+−++−": * write out ''a'', ''b'' and ''c'' in decimal notation; * calculate ''a'' × (''b'' − ''c''), write out the result in both ternary and decimal notations. diff --git a/Task/Balanced-ternary/Ada/balanced-ternary-1.ada b/Task/Balanced-ternary/Ada/balanced-ternary-1.adb similarity index 100% rename from Task/Balanced-ternary/Ada/balanced-ternary-1.ada rename to Task/Balanced-ternary/Ada/balanced-ternary-1.adb diff --git a/Task/Balanced-ternary/Ada/balanced-ternary-2.ada b/Task/Balanced-ternary/Ada/balanced-ternary-2.adb similarity index 100% rename from Task/Balanced-ternary/Ada/balanced-ternary-2.ada rename to Task/Balanced-ternary/Ada/balanced-ternary-2.adb diff --git a/Task/Balanced-ternary/Ada/balanced-ternary-3.ada b/Task/Balanced-ternary/Ada/balanced-ternary-3.adb similarity index 100% rename from Task/Balanced-ternary/Ada/balanced-ternary-3.ada rename to Task/Balanced-ternary/Ada/balanced-ternary-3.adb diff --git a/Task/Balanced-ternary/Elixir/balanced-ternary.elixir b/Task/Balanced-ternary/Elixir/balanced-ternary.ex similarity index 100% rename from Task/Balanced-ternary/Elixir/balanced-ternary.elixir rename to Task/Balanced-ternary/Elixir/balanced-ternary.ex diff --git a/Task/Balanced-ternary/JavaScript/balanced-ternary.js b/Task/Balanced-ternary/JavaScript/balanced-ternary.js new file mode 100644 index 0000000000..29ae058c1c --- /dev/null +++ b/Task/Balanced-ternary/JavaScript/balanced-ternary.js @@ -0,0 +1,203 @@ +class BTernary { + constructor(input) { + if (typeof input === 'string') { + let i = 0; + while (i < input.length && input.charAt(i) === '0') { + i++; + } + this.value = input.substring(i); + } else if (typeof input === 'number') { + this.value = this.convertToBT(input); + } + } + + convertToBT(v) { + if (v < 0) { + return this.flip(this.convertToBT(-v)); + } + if (v === 0) { + return ""; + } + const rem = this.mod3(v); + if (rem === 0) { + return this.convertToBT(Math.floor(v / 3)) + "0"; + } + if (rem === 1) { + return this.convertToBT(Math.floor(v / 3)) + "+"; + } + if (rem === 2) { + return this.convertToBT(Math.floor((v + 1) / 3)) + "-"; + } + return "You can't see me"; + } + + flip(s) { + let flip = ""; + for (let i = 0; i < s.length; i++) { + if (s.charAt(i) === '+') { + flip += '-'; + } else if (s.charAt(i) === '-') { + flip += '+'; + } else { + flip += '0'; + } + } + return flip; + } + + mod3(v) { + if (v > 0) { + return v % 3; + } + v = v % 3; + return (v + 3) % 3; + } + + intValue() { + let sum = 0; + const s = this.value; + for (let i = 0; i < s.length; i++) { + const c = s.charAt(s.length - i - 1); + let dig = 0; + if (c === '+') { + dig = 1; + } else if (c === '-') { + dig = -1; + } + sum += dig * Math.pow(3, i); + } + return sum; + } + + add(that) { + let a = this.value; + let b = that.value; + + const longer = a.length > b.length ? a : b; + let shorter = a.length > b.length ? b : a; + + while (shorter.length < longer.length) { + shorter = '0' + shorter; + } + + a = longer; + b = shorter; + + let carry = '0'; + let sum = ""; + for (let i = 0; i < a.length; i++) { + const place = a.length - i - 1; + const digisum = this.addDigitsWithCarry(a.charAt(place), b.charAt(place), carry); + if (digisum.length !== 1) { + carry = digisum.charAt(0); + } else { + carry = '0'; + } + sum = digisum.charAt(digisum.length - 1) + sum; + } + sum = carry + sum; + + return new BTernary(sum); + } + + addDigitsWithCarry(a, b, carry) { + const sum1 = this.addDigits(a, b); + const sum2 = this.addDigits(sum1.charAt(sum1.length - 1), carry); + + if (sum1.length === 1) { + return sum2; + } + if (sum2.length === 1) { + return sum1.charAt(0) + sum2; + } + return sum1.charAt(0) + ""; + } + + addDigits(a, b) { + let sum = ""; + if (a === '0') { + sum = b + ""; + } else if (b === '0') { + sum = a + ""; + } else if (a === '+') { + if (b === '+') { + sum = "+-"; + } else { + sum = "0"; + } + } else { + if (b === '+') { + sum = "0"; + } else { + sum = "-+"; + } + } + return sum; + } + + neg() { + return new BTernary(this.flip(this.value)); + } + + sub(that) { + return this.add(that.neg()); + } + + mul(that) { + const one = new BTernary(1); + const zero = new BTernary(0); + let mul = new BTernary(0); + + let flipflag = 0; + if (that.compareTo(zero) === -1) { + that = that.neg(); + flipflag = 1; + } + + for (let i = new BTernary(1); i.compareTo(that) < 1; i = i.add(one)) { + mul = mul.add(this); + } + + if (flipflag === 1) { + mul = mul.neg(); + } + return mul; + } + + equals(that) { + return this.value === that.value; + } + + compareTo(that) { + if (this.intValue() > that.intValue()) { + return 1; + } else if (this.equals(that)) { + return 0; + } + return -1; + } + + toString() { + return this.value; + } +} + +// Main execution +function main() { + const a = new BTernary("+-0++0+"); + const b = new BTernary(-436); + const c = new BTernary("+-++-"); + + console.log("a=" + a.intValue()); + console.log("b=" + b.intValue()); + console.log("c=" + c.intValue()); + console.log(); + + // result = a * (b - c) + const result = a.mul(b.sub(c)); + + console.log("result= " + result + " " + result.intValue()); +} + +// Run the main function +main(); diff --git a/Task/Balanced-ternary/Julia/balanced-ternary.julia b/Task/Balanced-ternary/Julia/balanced-ternary.jl similarity index 100% rename from Task/Balanced-ternary/Julia/balanced-ternary.julia rename to Task/Balanced-ternary/Julia/balanced-ternary.jl diff --git a/Task/Balanced-ternary/Kotlin/balanced-ternary.kotlin b/Task/Balanced-ternary/Kotlin/balanced-ternary.kts similarity index 100% rename from Task/Balanced-ternary/Kotlin/balanced-ternary.kotlin rename to Task/Balanced-ternary/Kotlin/balanced-ternary.kts diff --git a/Task/Balanced-ternary/OCaml/balanced-ternary.ocaml b/Task/Balanced-ternary/OCaml/balanced-ternary.ml similarity index 100% rename from Task/Balanced-ternary/OCaml/balanced-ternary.ocaml rename to Task/Balanced-ternary/OCaml/balanced-ternary.ml diff --git a/Task/Balanced-ternary/Quackery/balanced-ternary.quackery b/Task/Balanced-ternary/Quackery/balanced-ternary.quackery new file mode 100644 index 0000000000..f28cf0fdc1 --- /dev/null +++ b/Task/Balanced-ternary/Quackery/balanced-ternary.quackery @@ -0,0 +1,79 @@ + [ -1 1 clamp 1+ ]'[ swap peek do ] is sif ( n --> ) + + [ $ "" swap witheach + [ sif [ char - char 0 char + ] + swap join ] ] is t->$ ( t --> ) + + [ [] swap witheach + [ char - - sif [ 1 -1 0 ] + swap join ] ] is $->t ( $ --> t ) + + [ 0 swap reverse witheach [ swap 3 * + ] ] is t->n ( $ --> t ) + + [ [] swap + [ 3 /mod [ table 0 1 [ 1+ -1 ] ] do + swap dip join dup 0 = until ] + drop ] is n->t ( n --> t ) + + [ -1 peek ] is tsign ( t --> n ) + + [ ' [ 0 ] = ] is tzero ( t --> b ) + + [ tsign -1 = ] is tneg ( t --> b ) + + [ tsign 1 = ] is tpos ( t --> b ) + + [ [] swap witheach [ negate join ] ] is -t ( t --> t ) + + [ 0 over size times + [ 1 - 2dup peek if conclude ] + 1+ dup if split drop ] is tnorm ( t --> t ) + + [ [] 0 2swap + over size over size - dup 0 < + if [ dip swap negate ] + 0 swap of join temp put + witheach + [ temp share i^ peek + + + 3 + + [ table + [ 0 -1 ] [ 1 -1 ] [ -1 0 ] + [ 0 0 ] [ 1 0 ] [ -1 1 ] + [ 0 1 ] ] do + dip join ] + join tnorm + temp release ] is t+ ( t t --> t ) + + [ -t t+ ] is t- ( t t --> t ) + + [ t- tneg ] is t< ( t t --> b ) + + [ t- tpos ] is t> ( t t --> b ) + + [ behead swap witheach + [ 2dup t> if swap + drop ] ] is tmin ( [ --> t ) + + [ behead swap witheach + [ 2dup t< if swap + drop ] ] is tmax ( [ --> t ) + + [ dup t+ ] is twice ( t --> t ) + + [ 0 swap join ] is thrice ( t --> t ) + + [ ' [ 0 ] swap witheach + [ dip over + sif [ t- drop t+ ] + dip thrice ] + nip ] is t* ( t t --> t ) + + say "a: " $ "+-0++0+" dup echo$ say " = " $->t t->n echo cr + say "b: " -436 dup echo say " = " n->t t->$ echo$ cr + say "c: " $ "+-++-" dup echo$ say " = " $->t t->n echo cr + say "a*(b-c): = " + $ "+-0++0+" $->t + -436 n->t + $ "+-++-" $->t + t- t* + dup t->$ echo$ say " = " t->n echo cr diff --git a/Task/Balanced-ternary/R/balanced-ternary.r b/Task/Balanced-ternary/R/balanced-ternary.r new file mode 100644 index 0000000000..2c8f76dd35 --- /dev/null +++ b/Task/Balanced-ternary/R/balanced-ternary.r @@ -0,0 +1,138 @@ +## BalancedTernary in R (S3) + +## Constructor helpers ---- +new_BalancedTernary <- function(digits) { + # digits are least-significant first, values in {-1,0,1} + structure(list(digits = as.integer(digits)), class = "BalancedTernary") +} + +BalancedTernary <- function(x = 0L) { + if (inherits(x, "BalancedTernary")) return(x) + if (is.character(x)) return(BalancedTernary_from_string(x)) + if (length(x) != 1 || !is.finite(x)) stop("BalancedTernary: need a single finite number or a string.") + BalancedTernary_from_int(as.integer(x)) +} + +BalancedTernary_zero <- function() new_BalancedTernary(0L) + +## Conversions ---- +BalancedTernary_from_int <- function(n) { + n <- as.integer(n) + if (n == 0L) return(new_BalancedTernary(0L)) + digs <- integer(0) + while (n != 0L) { + r <- n %% 3L + if (r == 0L) { + digs <- c(digs, 0L); n <- n %/% 3L + } else if (r == 1L) { + digs <- c(digs, 1L); n <- n %/% 3L + } else { # r == 2 -> digit -1 and carry +1 (i.e., add 1 then divide) + digs <- c(digs, -1L); n <- (n + 1L) %/% 3L + } + } + new_BalancedTernary(digs) +} + +BalancedTernary_from_string <- function(s) { + # string is most-significant first with '-', '0', '+' + map <- c("-" = -1L, "0" = 0L, "+" = 1L) + chs <- strsplit(s, "", fixed = TRUE)[[1]] + if (!all(chs %in% names(map))) stop("String may only contain '-', '0', '+'.") + # reverse to least-significant first + new_BalancedTernary(unname(map[rev(chs)])) +} + +bt <- function(s) BalancedTernary_from_string(s) # macro-ish convenience + +## Printing & coercion ---- +print.BalancedTernary <- function(x, ...) { + cat(as.character(x), "\n", sep = "") + invisible(x) +} + +as.character.BalancedTernary <- function(x, ...) { + map <- c(`-1` = "-", `0` = "0", `1` = "+") + # display most-significant first + paste0(rev(map[as.character(x$digits)]), collapse = "") +} + +as.integer.BalancedTernary <- function(x, ...) { + s <- x$digits + if (length(s) == 1L && s[1] == 0L) return(0L) + ex <- seq_along(s) - 1L + # use double accumulate then coerce to integer (safe for moderate sizes) + val <- sum((3 ^ ex) * s) + as.integer(val) +} + +## Unary minus ---- +`-.BalancedTernary` <- function(e1) new_BalancedTernary(-e1$digits) + +## Core arithmetic helpers ---- +# Addition table for (a1 + b1 + c) -> (digit, carry), +# indexed by 4 + a1 + b1 + c where a1,b1,c in {-1,0,1} gives 1..7 +.bt_table_digit <- c( 0, 1, -1, 0, 1, -1, 0) # d +.bt_table_carry <- c(-1, -1, 0, 0, 0, 1, 1) # c + +.bt_add <- function(a, b, c = 0L) { + # a,b are integer vectors of digits (LSB first) in {-1,0,1} + if (length(a) == 0L || length(b) == 0L) { + if (c == 0L) return(if (length(a) == 0L) b else a) + return(.bt_add(c(c), if (length(a) == 0L) b else a)) + } else { + a1 <- a[1]; b1 <- b[1] + idx <- 4L + a1 + b1 + c + d <- .bt_table_digit[idx] + c2 <- .bt_table_carry[idx] + r <- .bt_add(a[-1], b[-1], c2) + if (length(r) != 0L || d != 0L) { + return(c(d, r)) # unshift + } else { + return(r) + } + } +} + +.bt_mul <- function(a, b) { + # schoolbook recursion with balanced digits + if (length(a) == 0L || length(b) == 0L) return(integer(0)) + a1 <- a[1] + if (a1 == -1L) x <- (-BalancedTernary(new_BalancedTernary(b)))$digits + else if (a1 == 0L) x <- integer(0) + else if (a1 == 1L) x <- b + # shift (multiply by 3) = prepend a 0 digit to recursive product + y <- c(0L, .bt_mul(a[-1], b)) + .bt_add(x, y) +} + +.normalize_zero <- function(v) if (length(v) == 0L) 0L else v + +## Binary operators ---- +`+.BalancedTernary` <- function(e1, e2) { + v <- .bt_add(e1$digits, e2$digits) + new_BalancedTernary(.normalize_zero(v)) +} + +`-.BalancedTernary` # already defined (unary) + +`%minus_bt%` <- function(a, b) a + (-b) # internal helper if needed + +`*.BalancedTernary` <- function(e1, e2) { + v <- .bt_mul(e1$digits, e2$digits) + new_BalancedTernary(.normalize_zero(v)) +} + +## Demo / tests ---- +a <- bt("+-0++0+") +cat("a: ", as.integer(a), ", ", as.character(a), "\n", sep = "") + +b <- BalancedTernary(-436L) +cat("b: ", as.integer(b), ", ", as.character(b), "\n", sep = "") + +c <- BalancedTernary("+-++-") +cat("c: ", as.integer(c), ", ", as.character(c), "\n", sep = "") + +r <- a * (b + (-c)) # a * (b - c) +cat("a * (b - c): ", as.integer(r), ", ", as.character(r), "\n", sep = "") + +stopifnot(as.integer(r) == as.integer(a) * (as.integer(b) - as.integer(c))) diff --git a/Task/Balanced-ternary/Rust/balanced-ternary.rust b/Task/Balanced-ternary/Rust/balanced-ternary.rs similarity index 100% rename from Task/Balanced-ternary/Rust/balanced-ternary.rust rename to Task/Balanced-ternary/Rust/balanced-ternary.rs diff --git a/Task/Balanced-ternary/Zig/balanced-ternary.zig b/Task/Balanced-ternary/Zig/balanced-ternary.zig new file mode 100644 index 0000000000..cf7423ff0a --- /dev/null +++ b/Task/Balanced-ternary/Zig/balanced-ternary.zig @@ -0,0 +1,297 @@ +const std = @import("std"); +const ArrayList = std.ArrayList; +const Allocator = std.mem.Allocator; + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + const allocator = gpa.allocator(); + + const stdout = std.io.getStdOut().writer(); + + var a = try BalancedTernary.fromString(allocator, "+-0++0+"); + defer a.deinit(); + const a_val = try a.toI128(); + const a_str = try a.toString(allocator); + defer allocator.free(a_str); + try stdout.print("a = {s} = {d}\n", .{ a_str, a_val }); + + var b = try BalancedTernary.fromI128(allocator, -436); + defer b.deinit(); + const b_val = try b.toI128(); + const b_str = try b.toString(allocator); + defer allocator.free(b_str); + try stdout.print("b = {s} = {d}\n", .{ b_str, b_val }); + + var c = try BalancedTernary.fromString(allocator, "+-++-"); + defer c.deinit(); + const c_val = try c.toI128(); + const c_str = try c.toString(allocator); + defer allocator.free(c_str); + try stdout.print("c = {s} = {d}\n", .{ c_str, c_val }); + + var c_neg = try c.clone(allocator); + defer c_neg.deinit(); + c_neg.negate(); + + var b_plus_neg_c = try b.add(allocator, c_neg); + defer b_plus_neg_c.deinit(); + + var d = try a.mul(allocator, b_plus_neg_c); + defer d.deinit(); + const d_val = try d.toI128(); + const d_str = try d.toString(allocator); + defer allocator.free(d_str); + try stdout.print("a * (b - c) = {s} = {d}\n", .{ d_str, d_val }); + + var e = try BalancedTernary.fromString(allocator, "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); + defer e.deinit(); + const e_result = e.toI128(); + try std.testing.expect(e_result == error.Overflow); +} + +const Trit = enum { + Zero, + Pos, + Neg, + + fn fromChar(c: u8) !Trit { + return switch (c) { + '0' => .Zero, + '+' => .Pos, + '-' => .Neg, + else => error.InvalidCharacter, + }; + } + + fn toChar(self: Trit) u8 { + return switch (self) { + .Zero => '0', + .Pos => '+', + .Neg => '-', + }; + } + + fn add(self: Trit, rhs: Trit) struct { carry: Trit, current: Trit } { + return switch (self) { + .Zero => .{ .carry = .Zero, .current = rhs }, + .Pos => switch (rhs) { + .Zero => .{ .carry = .Zero, .current = .Pos }, + .Neg => .{ .carry = .Zero, .current = .Zero }, + .Pos => .{ .carry = .Pos, .current = .Neg }, + }, + .Neg => switch (rhs) { + .Zero => .{ .carry = .Zero, .current = .Neg }, + .Pos => .{ .carry = .Zero, .current = .Zero }, + .Neg => .{ .carry = .Neg, .current = .Pos }, + }, + }; + } + + fn mul(self: Trit, rhs: Trit) Trit { + return switch (self) { + .Zero => .Zero, + .Pos => switch (rhs) { + .Zero => .Zero, + .Pos => .Pos, + .Neg => .Neg, + }, + .Neg => switch (rhs) { + .Zero => .Zero, + .Pos => .Neg, + .Neg => .Pos, + }, + }; + } + + fn negate(self: Trit) Trit { + return switch (self) { + .Zero => .Zero, + .Pos => .Neg, + .Neg => .Pos, + }; + } +}; + +const BalancedTernary = struct { + digits: ArrayList(Trit), + + fn deinit(self: *BalancedTernary) void { + self.digits.deinit(); + } + + fn clone(self: BalancedTernary, allocator: Allocator) !BalancedTernary { + var new_digits = try ArrayList(Trit).initCapacity(allocator, self.digits.items.len); + try new_digits.appendSlice(self.digits.items); + return BalancedTernary{ .digits = new_digits }; + } + + fn fromString(allocator: Allocator, s: []const u8) !BalancedTernary { + var digits = ArrayList(Trit).init(allocator); + errdefer digits.deinit(); + + var i: usize = s.len; + while (i > 0) { + i -= 1; + const trit = try Trit.fromChar(s[i]); + try digits.append(trit); + } + + return BalancedTernary{ .digits = digits }; + } + + fn fromI128(allocator: Allocator, x: i128) !BalancedTernary { + var digits = ArrayList(Trit).init(allocator); + errdefer digits.deinit(); + + var curr = x; + + while (true) { + const rem = @rem(curr, 3); + + const trit: Trit = switch (rem) { + 0 => .Zero, + 1, -2 => .Pos, + 2, -1 => .Neg, + else => unreachable, + }; + try digits.append(trit); + + const offset = @as(i128, @intFromFloat(@round(@as(f64, @floatFromInt(rem)) / 3.0))); + curr = @divTrunc(curr, 3) + offset; + + if (curr == 0) break; + } + + return BalancedTernary{ .digits = digits }; + } + + fn toString(self: BalancedTernary, allocator: Allocator) ![]const u8 { + var result = try ArrayList(u8).initCapacity(allocator, self.digits.items.len); + defer result.deinit(); + + var i: usize = self.digits.items.len; + while (i > 0) { + i -= 1; + try result.append(self.digits.items[i].toChar()); + } + + return result.toOwnedSlice(); + } + + fn toI128(self: BalancedTernary) !i128 { + var acc: i128 = 0; + + for (self.digits.items, 0..) |trit, i| { + const index: u32 = std.math.cast(u32, i) orelse return error.Overflow; + + switch (trit) { + .Zero => {}, + .Pos => { + const power = std.math.powi(i128, 3, index) catch return error.Overflow; + acc = std.math.add(i128, acc, power) catch return error.Overflow; + }, + .Neg => { + const power = std.math.powi(i128, 3, index) catch return error.Overflow; + acc = std.math.sub(i128, acc, power) catch return error.Overflow; + }, + } + } + + return acc; + } + + fn trim(digits: *ArrayList(Trit)) void { + while (digits.items.len > 0) { + const last = digits.items[digits.items.len - 1]; + if (last != .Zero) { + break; + } + _ = digits.pop(); + } + } + + fn add(self: BalancedTernary, allocator: Allocator, rhs: BalancedTernary) !BalancedTernary { + if (rhs.digits.items.len == 0) { + if (self.digits.items.len == 0) { + var digits = ArrayList(Trit).init(allocator); + try digits.append(.Zero); + return BalancedTernary{ .digits = digits }; + } + return try self.clone(allocator); + } + + const length = @min(self.digits.items.len, rhs.digits.items.len); + var sum = ArrayList(Trit).init(allocator); + errdefer sum.deinit(); + + var carry = ArrayList(Trit).init(allocator); + errdefer carry.deinit(); + try carry.append(.Zero); + + for (0..length) |i| { + const result = self.digits.items[i].add(rhs.digits.items[i]); + try sum.append(result.current); + try carry.append(result.carry); + } + + if (self.digits.items.len > length) { + try sum.appendSlice(self.digits.items[length..]); + } + if (rhs.digits.items.len > length) { + try sum.appendSlice(rhs.digits.items[length..]); + } + + trim(&sum); + trim(&carry); + + var sum_bt = BalancedTernary{ .digits = sum }; + const carry_bt = BalancedTernary{ .digits = carry }; + //defer carry_bt.deinit(); + + return try sum_bt.add(allocator, carry_bt); + } + + fn mul(self: BalancedTernary, allocator: Allocator, rhs: BalancedTernary) !BalancedTernary { + var results = ArrayList(BalancedTernary).init(allocator); + defer { + for (results.items) |*item| { + item.deinit(); + } + results.deinit(); + } + + for (rhs.digits.items, 0..) |rhs_trit, i| { + var digits = ArrayList(Trit).init(allocator); + errdefer digits.deinit(); + + for (0..i) |_| { + try digits.append(.Zero); + } + + for (self.digits.items) |self_trit| { + try digits.append(self_trit.mul(rhs_trit)); + } + + try results.append(BalancedTernary{ .digits = digits }); + } + + var acc_digits = ArrayList(Trit).init(allocator); + try acc_digits.append(.Zero); + var acc = BalancedTernary{ .digits = acc_digits }; + + for (results.items) |item| { + const new_acc = try acc.add(allocator, item); + acc.deinit(); + acc = new_acc; + } + + return acc; + } + + fn negate(self: *BalancedTernary) void { + for (self.digits.items) |*trit| { + trit.* = trit.negate(); + } + } +}; diff --git a/Task/Barnsley-fern/Ada/barnsley-fern.ada b/Task/Barnsley-fern/Ada/barnsley-fern.adb similarity index 100% rename from Task/Barnsley-fern/Ada/barnsley-fern.ada rename to Task/Barnsley-fern/Ada/barnsley-fern.adb diff --git a/Task/Barnsley-fern/Delphi/barnsley-fern.delphi b/Task/Barnsley-fern/Delphi/barnsley-fern.pas similarity index 100% rename from Task/Barnsley-fern/Delphi/barnsley-fern.delphi rename to Task/Barnsley-fern/Delphi/barnsley-fern.pas diff --git a/Task/Barnsley-fern/EasyLang/barnsley-fern.easy b/Task/Barnsley-fern/EasyLang/barnsley-fern.easy index 3d5e535c80..b326a0836e 100644 --- a/Task/Barnsley-fern/EasyLang/barnsley-fern.easy +++ b/Task/Barnsley-fern/EasyLang/barnsley-fern.easy @@ -1,21 +1,21 @@ -color 060 -for i = 1 to 200000 - r = randomf - if r < 0.01 - nx = 0 - ny = 0.16 * y - elif r < 0.08 - nx = 0.2 * x - 0.26 * y - ny = 0.23 * x + 0.22 * y + 1.6 - elif r < 0.15 - nx = -0.15 * x + 0.28 * y - ny = 0.26 * x + 0.24 * y + 0.44 - else - nx = 0.85 * x + 0.04 * y - ny = -0.04 * x + 0.85 * y + 1.6 - . - x = nx - y = ny - move 50 + x * 15 y * 10 - rect 0.3 0.3 +gbackground 000 +gcolor 263 +for i = 1 to 100000 + r = randomf + if r < 0.01 + nx = 0 + ny = 0.16 * y + elif r < 0.08 + nx = 0.2 * x - 0.26 * y + ny = 0.23 * x + 0.22 * y + 1.6 + elif r < 0.15 + nx = -0.15 * x + 0.28 * y + ny = 0.26 * x + 0.24 * y + 0.44 + else + nx = 0.85 * x + 0.04 * y + ny = -0.04 * x + 0.85 * y + 1.6 + . + x = nx + y = ny + grect 50 + x * 15 y * 10 0.3 0.3 . diff --git a/Task/Barnsley-fern/Emacs-Lisp/barnsley-fern.l b/Task/Barnsley-fern/Emacs-Lisp/barnsley-fern.el similarity index 100% rename from Task/Barnsley-fern/Emacs-Lisp/barnsley-fern.l rename to Task/Barnsley-fern/Emacs-Lisp/barnsley-fern.el diff --git a/Task/Barnsley-fern/FutureBasic/barnsley-fern.basic b/Task/Barnsley-fern/FutureBasic/barnsley-fern.basic new file mode 100644 index 0000000000..bf2badd71f --- /dev/null +++ b/Task/Barnsley-fern/FutureBasic/barnsley-fern.basic @@ -0,0 +1,34 @@ +void local fn BarnsleyFern( height as long ) + double x = 0, y = 0, xn, yn, f = height / 10.6 + long n, r, offsetX = height / 4 - height / 40 + + for n = 1 to height * 50 + r = rnd(100) - 1 + select + case r >= 0 && r <= 84 + xn = 0.85 * x + 0.04 * y + yn = -0.04 * x + 0.85 * y + 1.6 + case r >= 85 && r <= 91 + xn = 0.2 * x - 0.26 * y + yn = 0.23 * x + 0.22 * y + 1.6 + case r >= 92 && r <= 98 + xn = -0.15 * x + 0.28 * y + yn = 0.26 * x + 0.24 * y + 0.44 + case else + xn = 0 + yn = 0.16 * y + end select + + x = xn : y = yn + pen -1 + oval fill (offsetX + x * f, height - y * f, 1.5, 1.5), _zGreen + next + +end fn + +window 1, @"Barnsley fern", (0,0,300,600) +WindowSetBackgroundColor( 1, fn ColorBlack ) + +fn BarnsleyFern( 600 ) + +HandleEvents diff --git a/Task/Barnsley-fern/Julia/barnsley-fern.julia b/Task/Barnsley-fern/Julia/barnsley-fern.jl similarity index 100% rename from Task/Barnsley-fern/Julia/barnsley-fern.julia rename to Task/Barnsley-fern/Julia/barnsley-fern.jl diff --git a/Task/Barnsley-fern/Kotlin/barnsley-fern.kotlin b/Task/Barnsley-fern/Kotlin/barnsley-fern.kts similarity index 100% rename from Task/Barnsley-fern/Kotlin/barnsley-fern.kotlin rename to Task/Barnsley-fern/Kotlin/barnsley-fern.kts diff --git a/Task/Barnsley-fern/Pluto/barnsley-fern.pluto b/Task/Barnsley-fern/Pluto/barnsley-fern.pluto new file mode 100644 index 0000000000..fe97f4f1e1 --- /dev/null +++ b/Task/Barnsley-fern/Pluto/barnsley-fern.pluto @@ -0,0 +1,35 @@ +require "bitmap" + +local w, h = 640, 640 +local bmp = bitmap.of(w, h, color.black, "Barnsley Fern") +local n = 200_000 + +local function create_fern() + local x = 0 + local y = 0 + local c = bitmap.rgbColor(0x32, 0xcd, 0x32) + for i = 0, n - 1 do + local tx + local ty + local r = math.random() + if r <= 0.01 then + tx = 0 + ty = 0.16 * y + elseif r <= 0.86 then + tx = 0.85 * x + 0.04 * y + ty = -0.04 * x + 0.85 * y + 1.6 + elseif r <= 0.93 then + tx = 0.2 * x - 0.26 * y + ty = 0.23 * x + 0.22 * y + 1.6 + else + tx = -0.15 * x + 0.28 * y + ty = 0.26 * x + 0.24 * y + 0.44 + end + x = tx + y = ty + bmp:set(math.round(w / 2 + x * w / 11), math.round(h - y * h / 11), c) + end +end + +create_fern() +bmp:view() diff --git a/Task/Barnsley-fern/Rebol/barnsley-fern.rebol b/Task/Barnsley-fern/Rebol/barnsley-fern.rebol new file mode 100644 index 0000000000..b272eaf806 --- /dev/null +++ b/Task/Barnsley-fern/Rebol/barnsley-fern.rebol @@ -0,0 +1,35 @@ +Rebol [ + title: "Rosetta code: Barnsley Fern" + file: %Barnsley_fern.r3 + url: https://rosettacode.org/wiki/Barnsley_fern + needs: 3.0.0 +] +barnsley-fern: function [size [pair!]][ + img: make image! reduce [size 0.0.0] + width: size/x + height: size/y + + p: 0x0 x: y: 0.0 + repeat i 100000 [ + xt: yt: 0.0 + r: random 100 + case [ + r <= 1 [xt: 0.0 yt: 0.16 * y] + r <= 8 [xt: ( 0.20 * x) - (0.26 * y) yt: ( 0.23 * x) + (0.22 * y) + 1.60] + r <= 15 [xt: (-0.15 * x) + (0.28 * y) yt: ( 0.26 * x) + (0.24 * y) + 0.44] + 'else [xt: ( 0.85 * x) + (0.04 * y) yt: (-0.04 * x) + (0.85 * y) + 1.60] + ] + x: xt y: yt + p/x: round (width / 2 + (60 * x)) + p/y: height - round (60 * y) + change at img p green + ] +] + +img: barnsley-fern 640x640 +save %barnsley-fern.png img + +if cv: attempt [import 'opencv][ + cv/imshow/name img "Barnsley" + cv/waitKey 0 +] diff --git a/Task/Barnsley-fern/Rust/barnsley-fern.rs b/Task/Barnsley-fern/Rust/barnsley-fern.rs new file mode 100644 index 0000000000..fe8f6a528c --- /dev/null +++ b/Task/Barnsley-fern/Rust/barnsley-fern.rs @@ -0,0 +1,45 @@ +extern crate rand; +extern crate raster; + +use rand::Rng; + +fn main() { + let max_iterations = 200_000u32; + let height = 640i32; + let width = 640i32; + + let mut rng = rand::thread_rng(); + let mut image = raster::Image::blank(width, height); + raster::editor::fill(&mut image, raster::Color::white()).unwrap(); + + let mut x = 0.; + let mut y = 0.; + for _ in 0..max_iterations { + let r = rng.r#gen::(); + let cx: f64; + let cy: f64; + + if r <= 0.01 { + cx = 0f64; + cy = 0.16 * y as f64; + } else if r <= 0.08 { + cx = 0.2 * x as f64 - 0.26 * y as f64; + cy = 0.23 * x as f64 + 0.22 * y as f64 + 1.6; + } else if r <= 0.15 { + cx = -0.15 * x as f64 + 0.28 * y as f64; + cy = 0.26 * x as f64 + 0.26 * y as f64 + 0.44; + } else { + cx = 0.85 * x as f64 + 0.04 * y as f64; + cy = -0.04 * x as f64 + 0.85 * y as f64 + 1.6; + } + x = cx; + y = cy; + + let _ = image.set_pixel( + ((width as f64) / 2. + x * (width as f64) / 11.).round() as i32, + ((height as f64) - y * (height as f64) / 11.).round() as i32, + raster::Color::rgb(50, 205, 50)); + } + + raster::save(&image, "fractal.png").unwrap(); +} diff --git a/Task/Barnsley-fern/Rust/barnsley-fern.rust b/Task/Barnsley-fern/Rust/barnsley-fern.rust deleted file mode 100644 index d756f3ebee..0000000000 --- a/Task/Barnsley-fern/Rust/barnsley-fern.rust +++ /dev/null @@ -1,45 +0,0 @@ -extern crate rand; -extern crate raster; - -use rand::Rng; - -fn main() { - let max_iterations = 200_000u32; - let height = 640i32; - let width = 640i32; - - let mut rng = rand::thread_rng(); - let mut image = raster::Image::blank(width, height); - raster::editor::fill(&mut image, raster::Color::white()).unwrap(); - - let mut x = 0.; - let mut y = 0.; - for _ in 0..max_iterations { - let r = rng.gen::(); - let cx: f64; - let cy: f64; - - if r <= 0.01 { - cx = 0f64; - cy = 0.16 * y as f64; - } else if r <= 0.08 { - cx = 0.2 * x as f64 - 0.26 * y as f64; - cy = 0.23 * x as f64 + 0.22 * y as f64 + 1.6; - } else if r <= 0.15 { - cx = -0.15 * x as f64 + 0.28 * y as f64; - cy = 0.26 * x as f64 + 0.26 * y as f64 + 0.44; - } else { - cx = 0.85 * x as f64 + 0.04 * y as f64; - cy = -0.04 * x as f64 + 0.85 * y as f64 + 1.6; - } - x = cx; - y = cy; - - let _ = image.set_pixel( - ((width as f64) / 2. + x * (width as f64) / 11.).round() as i32, - ((height as f64) - y * (height as f64) / 11.).round() as i32, - raster::Color::rgb(50, 205, 50)); - } - - raster::save(&image, "fractal.png").unwrap(); -} diff --git a/Task/Barnsley-fern/Scheme/barnsley-fern.ss b/Task/Barnsley-fern/Scheme/barnsley-fern.scm similarity index 100% rename from Task/Barnsley-fern/Scheme/barnsley-fern.ss rename to Task/Barnsley-fern/Scheme/barnsley-fern.scm diff --git a/Task/Barnsley-fern/Uiua/barnsley-fern.uiua b/Task/Barnsley-fern/Uiua/barnsley-fern.uiua new file mode 100644 index 0000000000..a2d94aeac6 --- /dev/null +++ b/Task/Barnsley-fern/Uiua/barnsley-fern.uiua @@ -0,0 +1,11 @@ +Fs ← [[[0 0 0] [0 0.16 0]] + [[0.85 0.04 0] [¯0.04 0.85 1.6]] + [[0.2 ¯0.26 0] [0.23 0.22 1.6]] + [[¯0.15 0.28 0] [0.26 0.24 0.44]]] +Ps ← [1 86 93 100] +PickF ← (⊡:Fs⊢⊚/⊢)sym⊐⊢ + +B64Dec "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g=" diff --git a/Task/Base64-decode-data/Batch-File/base64-decode-data.bat b/Task/Base64-decode-data/Batch-File/base64-decode-data.bat new file mode 100644 index 0000000000..73b80ec78d --- /dev/null +++ b/Task/Base64-decode-data/Batch-File/base64-decode-data.bat @@ -0,0 +1,2 @@ +certutil -f -decodehex "%temp%\favicon.tmp" favicon1.ico 1 +fc /B favicon.ico favicon1.ico diff --git a/Task/Base64-decode-data/Crystal/base64-decode-data.crystal b/Task/Base64-decode-data/Crystal/base64-decode-data.cr similarity index 100% rename from Task/Base64-decode-data/Crystal/base64-decode-data.crystal rename to Task/Base64-decode-data/Crystal/base64-decode-data.cr diff --git a/Task/Base64-decode-data/Delphi/base64-decode-data.delphi b/Task/Base64-decode-data/Delphi/base64-decode-data.pas similarity index 100% rename from Task/Base64-decode-data/Delphi/base64-decode-data.delphi rename to Task/Base64-decode-data/Delphi/base64-decode-data.pas diff --git a/Task/Base64-decode-data/Ed/base64-decode-data.ed b/Task/Base64-decode-data/Ed/base64-decode-data.ed new file mode 100644 index 0000000000..177f09f0a1 --- /dev/null +++ b/Task/Base64-decode-data/Ed/base64-decode-data.ed @@ -0,0 +1,172 @@ +H +,p +g/.*/s/\B/ /g +g/\b=\b/s// 000000 /g +g/\bA\b/s// 000000 /g +g/\bB\b/s// 000001 /g +g/\bC\b/s// 000010 /g +g/\bD\b/s// 000011 /g +g/\bE\b/s// 000100 /g +g/\bF\b/s// 000101 /g +g/\bG\b/s// 000110 /g +g/\bH\b/s// 000111 /g +g/\bI\b/s// 001000 /g +g/\bJ\b/s// 001001 /g +g/\bK\b/s// 001010 /g +g/\bL\b/s// 001011 /g +g/\bM\b/s// 001100 /g +g/\bN\b/s// 001101 /g +g/\bO\b/s// 001110 /g +g/\bP\b/s// 001111 /g +g/\bQ\b/s// 010000 /g +g/\bR\b/s// 010001 /g +g/\bS\b/s// 010010 /g +g/\bT\b/s// 010011 /g +g/\bU\b/s// 010100 /g +g/\bV\b/s// 010101 /g +g/\bW\b/s// 010110 /g +g/\bX\b/s// 010111 /g +g/\bY\b/s// 011000 /g +g/\bZ\b/s// 011001 /g +g/\ba\b/s// 011010 /g +g/\bb\b/s// 011011 /g +g/\bc\b/s// 011100 /g +g/\bd\b/s// 011101 /g +g/\be\b/s// 011110 /g +g/\bf\b/s// 011111 /g +g/\bg\b/s// 100000 /g +g/\bh\b/s// 100001 /g +g/\bi\b/s// 100010 /g +g/\bj\b/s// 100011 /g +g/\bk\b/s// 100100 /g +g/\bl\b/s// 100101 /g +g/\bm\b/s// 100110 /g +g/\bn\b/s// 100111 /g +g/\bo\b/s// 101000 /g +g/\bp\b/s// 101001 /g +g/\bq\b/s// 101010 /g +g/\br\b/s// 101011 /g +g/\bs\b/s// 101100 /g +g/\bt\b/s// 101101 /g +g/\bu\b/s// 101110 /g +g/\bv\b/s// 101111 /g +g/\bw\b/s// 110000 /g +g/\bx\b/s// 110001 /g +g/\by\b/s// 110010 /g +g/\bz\b/s// 110011 /g +g/\b0\b/s// 110100 /g +g/\b1\b/s// 110101 /g +g/\b2\b/s// 110110 /g +g/\b3\b/s// 110111 /g +g/\b4\b/s// 111000 /g +g/\b5\b/s// 111001 /g +g/\b6\b/s// 111010 /g +g/\b7\b/s// 111011 /g +g/\b8\b/s// 111100 /g +g/\b9\b/s// 111101 /g +g/\b=\b/s// 000000 /g +g/\b\+\b/s// 111110 /g +g/\b\/\b/s// 111111 /g +g/[[:space:]]/s///g +g/[01]{8}/s// & /g +g/00000000/s///g +g/00001010/s//\ +/g +g/00100000/s// /g +g/00100001/s//!/g +g/00100010/s//"/g +g/00100011/s//#/g +g/00100100/s//$/g +g/00100101/s//%/g +g/00100110/s//&/g +g/00100111/s//'/g +g/00101000/s//(/g +g/00101001/s//)/g +g/00101010/s//*/g +g/00101011/s//+/g +g/00101100/s//,/g +g/00101101/s//-/g +g/00101110/s//./g +g/00101111/s////g +g/00110000/s//0/g +g/00110001/s//1/g +g/00110010/s//2/g +g/00110011/s//3/g +g/00110100/s//4/g +g/00110101/s//5/g +g/00110110/s//6/g +g/00110111/s//7/g +g/00111000/s//8/g +g/00111001/s//9/g +g/00111010/s//:/g +g/00111011/s//;/g +g/00111100/s///g +g/00111111/s//?/g +g/01000000/s//@/g +g/01000001/s//A/g +g/01000010/s//B/g +g/01000011/s//C/g +g/01000100/s//D/g +g/01000101/s//E/g +g/01000110/s//F/g +g/01000111/s//G/g +g/01001000/s//H/g +g/01001001/s//I/g +g/01001010/s//J/g +g/01001011/s//K/g +g/01001100/s//L/g +g/01001101/s//M/g +g/01001110/s//N/g +g/01001111/s//O/g +g/01010000/s//P/g +g/01010001/s//Q/g +g/01010010/s//R/g +g/01010011/s//S/g +g/01010100/s//T/g +g/01010101/s//U/g +g/01010110/s//V/g +g/01010111/s//W/g +g/01011000/s//X/g +g/01011001/s//Y/g +g/01011010/s//Z/g +g/01011011/s//[/g +g/01011100/s//\/g +g/01011101/s//]/g +g/01011110/s//^/g +g/01011111/s//_/g +g/01100000/s//`/g +g/01100001/s//a/g +g/01100010/s//b/g +g/01100011/s//c/g +g/01100100/s//d/g +g/01100101/s//e/g +g/01100110/s//f/g +g/01100111/s//g/g +g/01101000/s//h/g +g/01101001/s//i/g +g/01101010/s//j/g +g/01101011/s//k/g +g/01101100/s//l/g +g/01101101/s//m/g +g/01101110/s//n/g +g/01101111/s//o/g +g/01110000/s//p/g +g/01110001/s//q/g +g/01110010/s//r/g +g/01110011/s//s/g +g/01110100/s//t/g +g/01110101/s//u/g +g/01110110/s//v/g +g/01110111/s//w/g +g/01111000/s//x/g +g/01111001/s//y/g +g/01111010/s//z/g +g/01111011/s//{/g +g/01111100/s//|/g +g/01111101/s//}/g +g/01111110/s//~/g +g/[ ][ ](.)[ ][ ]/s//\1/g +,p +Q diff --git a/Task/Base64-decode-data/FutureBasic/base64-decode-data.basic b/Task/Base64-decode-data/FutureBasic/base64-decode-data.basic index 384292a93e..8837b09bef 100644 --- a/Task/Base64-decode-data/FutureBasic/base64-decode-data.basic +++ b/Task/Base64-decode-data/FutureBasic/base64-decode-data.basic @@ -20,7 +20,7 @@ originalString = @"This is a test string to be encoded as Base64 and then decode NSLog( @"This is the original string:\n\t%@\n", originalString ) encodedBase64String = fn EncodeStringAsBase64( originalString ) -NSLog( @"This is the original string encoded as Base84:\n\t%@\n", encodedBase64String ) +NSLog( @"This is the original string encoded as Base64:\n\t%@\n", encodedBase64String ) decodedBase64String = fn DecodeBase64String( encodedBase64String ) NSLog( @"This is the Base64 string decoded:\n\t%@", decodedBase64String ) diff --git a/Task/Base64-decode-data/Haxe/base64-decode-data.haxe b/Task/Base64-decode-data/Haxe/base64-decode-data.hx similarity index 100% rename from Task/Base64-decode-data/Haxe/base64-decode-data.haxe rename to Task/Base64-decode-data/Haxe/base64-decode-data.hx diff --git a/Task/Base64-decode-data/Julia/base64-decode-data.julia b/Task/Base64-decode-data/Julia/base64-decode-data.jl similarity index 100% rename from Task/Base64-decode-data/Julia/base64-decode-data.julia rename to Task/Base64-decode-data/Julia/base64-decode-data.jl diff --git a/Task/Base64-decode-data/Kotlin/base64-decode-data.kotlin b/Task/Base64-decode-data/Kotlin/base64-decode-data.kts similarity index 100% rename from Task/Base64-decode-data/Kotlin/base64-decode-data.kotlin rename to Task/Base64-decode-data/Kotlin/base64-decode-data.kts diff --git a/Task/Base64-decode-data/M2000-Interpreter/base64-decode-data-1.m2000 b/Task/Base64-decode-data/M2000-Interpreter/base64-decode-data-1.m2000 index 5ede834f8d..1229d1d3e8 100644 --- a/Task/Base64-decode-data/M2000-Interpreter/base64-decode-data-1.m2000 +++ b/Task/Base64-decode-data/M2000-Interpreter/base64-decode-data-1.m2000 @@ -5,7 +5,7 @@ uCiAgICAtLSBQYXVsIFIuIEVocmxpY2g= } tmp$=tempname$ open tmp$ for wide output as #f - print #f, string$(inp$ as decode64); + print #f, string$(inp$ as decode64); close #f document a$ load.doc a$, tmp$ diff --git a/Task/Base64-decode-data/Nu/base64-decode-data.nu b/Task/Base64-decode-data/Nu/base64-decode-data.nu new file mode 100644 index 0000000000..a55526dfa1 --- /dev/null +++ b/Task/Base64-decode-data/Nu/base64-decode-data.nu @@ -0,0 +1,2 @@ +'VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g=' +| decode base64 diff --git a/Task/Base64-decode-data/Pluto/base64-decode-data.pluto b/Task/Base64-decode-data/Pluto/base64-decode-data.pluto new file mode 100644 index 0000000000..b8359fd691 --- /dev/null +++ b/Task/Base64-decode-data/Pluto/base64-decode-data.pluto @@ -0,0 +1,4 @@ +local base64 = require("base64") + +local s = "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g=" +print(base64.decode(s)) diff --git a/Task/Base64-decode-data/PowerShell/base64-decode-data-1.ps1 b/Task/Base64-decode-data/PowerShell/base64-decode-data-1.ps1 new file mode 100644 index 0000000000..429bf1334a --- /dev/null +++ b/Task/Base64-decode-data/PowerShell/base64-decode-data-1.ps1 @@ -0,0 +1 @@ +[Text.Encoding]::ASCII.GetString([Convert]::FromBase64String("VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g=")) diff --git a/Task/Base64-decode-data/PowerShell/base64-decode-data-2.ps1 b/Task/Base64-decode-data/PowerShell/base64-decode-data-2.ps1 new file mode 100644 index 0000000000..8e3ff8d7a3 --- /dev/null +++ b/Task/Base64-decode-data/PowerShell/base64-decode-data-2.ps1 @@ -0,0 +1,2 @@ +$bytes=... +[IO.File]::WriteAllBytes('favicon.ico', [Convert]::FromBase64String($bytes)) diff --git a/Task/Base64-decode-data/REXX/base64-decode-data-1.rexx b/Task/Base64-decode-data/REXX/base64-decode-data-1.rexx new file mode 100644 index 0000000000..3d85bbec31 --- /dev/null +++ b/Task/Base64-decode-data/REXX/base64-decode-data-1.rexx @@ -0,0 +1,20 @@ +z= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' +do i=1 to 64 + bs.i=x2b(d2x(i-1)) + c=substr(z,i,1) + ds.c=right(bs.i,6,0) + End +e='YW55IGNhcm5hbCBwbGVhc3VyZS4' +r='' +ec=e +Do While ec<>'' + Parse Var ec c +1 ec + r=r||ds.c + End +res='' +Do while r<>'' + Parse Var r x +8 r + res=res||x2c(b2x(x)) + End +Say 'Input: >'e'<' +Say 'decoded: >'res'<' diff --git a/Task/Base64-decode-data/REXX/base64-decode-data-2.rexx b/Task/Base64-decode-data/REXX/base64-decode-data-2.rexx new file mode 100644 index 0000000000..90d8c0c1ce --- /dev/null +++ b/Task/Base64-decode-data/REXX/base64-decode-data-2.rexx @@ -0,0 +1,56 @@ +-- 3 Oct 2025 +include Setting +signal off notready + +say 'BASE64 DECODE DATA' +say version +say +call Task1 'TWFueSBoYW5kcyBtYWtlIGxpZ2h0IHdvcmsu' +call Task1 'TWFu' +call Task1 'TWE=' +call Task1 'TQ==' +call Task1 'YW55IGNhcm5hbCBwbGVhc3VyZS4=' +call Task2 +exit + +Task1: +procedure +parse arg xx +say 'Encoded ' xx +say 'Original' Decode64(xx) +say +return + +Task2: +procedure +in='favicon.dat'; out='favcopy.ico' +rr=Decode64(Charin(in,1,30000)) +call Charout out,rr,1 +return + +Decode64: +procedure +parse arg xx +-- Alphabet +a='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' +lx=Length(xx) +rr='' +-- Loop thru encoded characters +do i=1 to lx + c=Substr(xx,i,1) +-- If padding, discard 2 bits + if c='=' then do + rr=Left(rr,Length(rr)-2) + iterate i + end +-- Find position in alphabet + p=Pos(c,a)-1 +-- Convert to bits and take last 6 + b=Right(0000||X2b(D2x(p)),6) +-- Append + rr||=b +end +-- Convert to character +return X2c(B2x(rr)) + +include Abend diff --git a/Task/Base64-decode-data/Rebol/base64-decode-data.rebol b/Task/Base64-decode-data/Rebol/base64-decode-data.rebol new file mode 100644 index 0000000000..a921880d20 --- /dev/null +++ b/Task/Base64-decode-data/Rebol/base64-decode-data.rebol @@ -0,0 +1,3 @@ +print to string! debase { +VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIH +VwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLVBhdWwgUi5FaHJsaWNo} 64 diff --git a/Task/Base64-decode-data/Rust/base64-decode-data.rust b/Task/Base64-decode-data/Rust/base64-decode-data.rs similarity index 100% rename from Task/Base64-decode-data/Rust/base64-decode-data.rust rename to Task/Base64-decode-data/Rust/base64-decode-data.rs diff --git a/Task/Base64-decode-data/Swift/base64-decode-data.swift b/Task/Base64-decode-data/Swift/base64-decode-data.swift index 88b8b847f8..bc056552f2 100644 --- a/Task/Base64-decode-data/Swift/base64-decode-data.swift +++ b/Task/Base64-decode-data/Swift/base64-decode-data.swift @@ -6,5 +6,5 @@ VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29t if let decoded = Data(base64Encoded: input), let str = String(data: decoded, encoding: .utf8) { - print( str ) + print( str ) } diff --git a/Task/Base64-decode-data/YAMLScript/base64-decode-data.ys b/Task/Base64-decode-data/YAMLScript/base64-decode-data.ys new file mode 100644 index 0000000000..940785796f --- /dev/null +++ b/Task/Base64-decode-data/YAMLScript/base64-decode-data.ys @@ -0,0 +1,4 @@ +!YS-v0 + +defn main(str): + say: base64-decode(str) diff --git a/Task/Base64-decode-data/Zig/base64-decode-data.zig b/Task/Base64-decode-data/Zig/base64-decode-data.zig new file mode 100644 index 0000000000..cad232e18b --- /dev/null +++ b/Task/Base64-decode-data/Zig/base64-decode-data.zig @@ -0,0 +1,86 @@ +const std = @import("std"); +const print = std.debug.print; +const ArrayList = std.ArrayList; +const Allocator = std.mem.Allocator; + +const INPUT = "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLVBhdWwgUi5FaHJsaWNo"; +const UPPERCASE_OFFSET: i8 = -65; +const LOWERCASE_OFFSET: i8 = 26 - 97; +const NUM_OFFSET: i8 = 52 - 48; + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + const allocator = gpa.allocator(); + + print("Input: {s}\n", .{INPUT}); + + // Create a dynamic array to collect binary strings + var binary_strings = ArrayList([]const u8).init(allocator); + defer { + for (binary_strings.items) |item| { + allocator.free(item); + } + binary_strings.deinit(); + } + + // Process each character and convert to binary + for (INPUT) |ch| { + if (ch == '=') continue; // Filter '=' chars + + // Map char values using Base64 Characters Table + const ascii: i8 = @intCast(ch); + const convert: u8 = switch (ch) { + '0'...'9' => @intCast(ascii + NUM_OFFSET), + 'a'...'z' => @intCast(ascii + LOWERCASE_OFFSET), + 'A'...'Z' => @intCast(ascii + UPPERCASE_OFFSET), + '+' => 62, + '/' => 63, + else => { + print("Not a valid base64 encoded string\n", .{}); + return; + }, + }; + + // Convert to binary format (6 bits for base64) + const binary_str = try std.fmt.allocPrint(allocator, "{b:0>6}", .{convert}); + try binary_strings.append(binary_str); + } + + // Concatenate all binary strings + var total_len: usize = 0; + for (binary_strings.items) |item| { + total_len += item.len; + } + + const concatenated = try allocator.alloc(u8, total_len); + defer allocator.free(concatenated); + + var pos: usize = 0; + for (binary_strings.items) |item| { + @memcpy(concatenated[pos..pos + item.len], item); + pos += item.len; + } + + // Split into 8-character chunks and convert to bytes + var result_bytes = ArrayList(u8).init(allocator); + defer result_bytes.deinit(); + + var i: usize = 0; + while (i + 8 <= concatenated.len) : (i += 8) { + const chunk = concatenated[i..i + 8]; + const byte_value = std.fmt.parseInt(u8, chunk, 2) catch |err| { + print("Error parsing binary: {}\n", .{err}); + return; + }; + try result_bytes.append(byte_value); + } + + // Convert to UTF-8 string and print + const result_str = result_bytes.items; + if (std.unicode.utf8ValidateSlice(result_str)) { + print("Output: {s}\n", .{result_str}); + } else { + print("Invalid UTF-8 sequence\n", .{}); + } +} diff --git a/Task/Base64-decode-data/Zkl/base64-decode-data-1.zkl b/Task/Base64-decode-data/Zkl/base64-decode-data-1.zkl index d8d7d8dc96..365675c755 100644 --- a/Task/Base64-decode-data/Zkl/base64-decode-data-1.zkl +++ b/Task/Base64-decode-data/Zkl/base64-decode-data-1.zkl @@ -1,7 +1,7 @@ var [const] MsgHash=Import("zklMsgHash"), Curl=Import("zklCurl"); icon:=Curl().get("http://rosettacode.org/favicon.ico"); //-->(Data(4,331),693,0) -icon=icon[0][icon[1],*]; // remove header +icon=icon[0][icon[1],*]; // remove header iconEncoded:=MsgHash.base64encode(icon); iconDecoded:=MsgHash.base64decode(iconEncoded); File("rosettaCodeIcon.ico","wb").write(iconDecoded); # eyeball checking says good diff --git a/Task/Bell-numbers/ANSI-BASIC/bell-numbers.basic b/Task/Bell-numbers/ANSI-BASIC/bell-numbers.basic index f164dbfea7..b2d2b6c711 100644 --- a/Task/Bell-numbers/ANSI-BASIC/bell-numbers.basic +++ b/Task/Bell-numbers/ANSI-BASIC/bell-numbers.basic @@ -1,7 +1,7 @@ 100 REM Bell numbers -110 LET MaxN = 14 -120 OPTION BASE 0 -130 DIM A(13) ! i.e. DIM A(MaxN - 1), ANSI BASIC does not allow expressions in the bound arguments. +110 OPTION BASE 0 +120 DIM A(13) +130 LET MaxN = UBOUND(A) + 1 140 FOR I = 0 TO MaxN - 1 150 LET A(I) = 0 160 NEXT I diff --git a/Task/Bell-numbers/AWK/bell-numbers.awk b/Task/Bell-numbers/AWK/bell-numbers.awk new file mode 100644 index 0000000000..f304853fb9 --- /dev/null +++ b/Task/Bell-numbers/AWK/bell-numbers.awk @@ -0,0 +1,23 @@ +# syntax: GAWK --bignum -f BELL_NUMBERS.AWK +BEGIN { + arr[0,0] = 1 + printf(" 0: %10d\n",arr[0,0]) + printf(" 1: %10d\n",arr[0,0]) + for (i=1; i<50; i++) { + arr[i,0] = arr[i-1,i-1] + for (j=1; j<=i; j++) { + arr[i,j] = arr[i,j-1] + arr[i-1,j-1] + bt[i] = sprintf("%s%s ",bt[i],arr[i-1,j-1]) # build Bell's triangle + } + if (i <= 13) { + printf("%2d: %10d\n",i+1,arr[i,i]) + } + if (i == 49) { + printf("%2d: %d (%d digits)\n\n",i+1,arr[i,i],length(arr[i,i])) + } + } + for (i=1; i<=10; i++) { # show Bell's triangle + printf("%2d: %s\n",i,bt[i]) + } + exit(0) +} diff --git a/Task/Bell-numbers/Ada/bell-numbers.ada b/Task/Bell-numbers/Ada/bell-numbers.adb similarity index 100% rename from Task/Bell-numbers/Ada/bell-numbers.ada rename to Task/Bell-numbers/Ada/bell-numbers.adb diff --git a/Task/Bell-numbers/BQN/bell-numbers.bqn b/Task/Bell-numbers/BQN/bell-numbers.bqn new file mode 100644 index 0000000000..918f1357ad --- /dev/null +++ b/Task/Bell-numbers/BQN/bell-numbers.bqn @@ -0,0 +1,8 @@ +Bell ← {(+`⊢´⊸∾)⍟(↕𝕩)⋈1} + +•Out "First 15 Bell numbers:" +•Show ⊑¨ Bell 15 + +•Out "" +•Out "First 10 rows of the Bell triangle:" +•Show¨ Bell 10 diff --git a/Task/Bell-numbers/Berkeley-Logo/bell-numbers.logo b/Task/Bell-numbers/Berkeley-Logo/bell-numbers.logo new file mode 100644 index 0000000000..6a7e9966a9 --- /dev/null +++ b/Task/Bell-numbers/Berkeley-Logo/bell-numbers.logo @@ -0,0 +1,21 @@ +to bell.numbers :max.n + make "a (array :max.n 0) + make "n 0 + make "ubound.a :max.n - 1 + for [i 0 :ubound.a] [setitem :i :a 0] + setitem 0 :a 1 + type "|B(| + type form :n 2 0 + type "|) = | + print form item 0 :a 9 0 + while [:n < :max.n] ~ + [setitem :n :a item 0 :a + for [j :n 1 -1] ~ + [setitem :j - 1 :a (item :j - 1 :a) + (item :j :a)] + make "n :n + 1 + type "|B(| + type form :n 2 0 + type "|) = | + print form item 0 :a 9 0] + erase [[] [a] []] +end diff --git a/Task/Bell-numbers/C-sharp/bell-numbers.cs b/Task/Bell-numbers/C-sharp/bell-numbers-1.cs similarity index 100% rename from Task/Bell-numbers/C-sharp/bell-numbers.cs rename to Task/Bell-numbers/C-sharp/bell-numbers-1.cs diff --git a/Task/Bell-numbers/C-sharp/bell-numbers-2.cs b/Task/Bell-numbers/C-sharp/bell-numbers-2.cs new file mode 100644 index 0000000000..f2da84e2ba --- /dev/null +++ b/Task/Bell-numbers/C-sharp/bell-numbers-2.cs @@ -0,0 +1,25 @@ +using System.Numerics; + +foreach (var row in BellTriangle().Take(15)) +{ + Console.WriteLine(row[0]); +} + +Console.WriteLine(BellTriangle().ElementAt(49)[0]); + +foreach (var row in BellTriangle().Take(10)) +{ + Console.WriteLine(string.Join(", ", row)); +} + +IEnumerable> BellTriangle() +{ + List row = [1]; + + while (true) + { + yield return row; + var scan = row[^1]; + row = [scan, .. row.Select(r => scan += r) ]; + } +} diff --git a/Task/Bell-numbers/Crystal/bell-numbers.cr b/Task/Bell-numbers/Crystal/bell-numbers.cr new file mode 100644 index 0000000000..2ad901f5b0 --- /dev/null +++ b/Task/Bell-numbers/Crystal/bell-numbers.cr @@ -0,0 +1,12 @@ +require "big" + +row = [1.to_big_i] + +(1..50).each do |i| + puts "%2d: %s" % { i, i <= 10 ? row : row.first } if 1 <= i <= 15 || i == 50 + next_row = [row.last] + row.each do |n| + next_row << n + next_row.last + end + row = next_row +end diff --git a/Task/Bell-numbers/Delphi/bell-numbers.delphi b/Task/Bell-numbers/Delphi/bell-numbers.pas similarity index 100% rename from Task/Bell-numbers/Delphi/bell-numbers.delphi rename to Task/Bell-numbers/Delphi/bell-numbers.pas diff --git a/Task/Bell-numbers/EasyLang/bell-numbers.easy b/Task/Bell-numbers/EasyLang/bell-numbers.easy index e554895111..d4a9e3ac8c 100644 --- a/Task/Bell-numbers/EasyLang/bell-numbers.easy +++ b/Task/Bell-numbers/EasyLang/bell-numbers.easy @@ -10,5 +10,6 @@ func bell n . return list[n] . for i = 1 to 15 - print bell i + write bell i & " " . +print "" diff --git a/Task/Bell-numbers/Elixir/bell-numbers.elixir b/Task/Bell-numbers/Elixir/bell-numbers.ex similarity index 100% rename from Task/Bell-numbers/Elixir/bell-numbers.elixir rename to Task/Bell-numbers/Elixir/bell-numbers.ex diff --git a/Task/Bell-numbers/Forth/bell-numbers.fth b/Task/Bell-numbers/Forth/bell-numbers.fth new file mode 100644 index 0000000000..6b7c8259fa --- /dev/null +++ b/Task/Bell-numbers/Forth/bell-numbers.fth @@ -0,0 +1,51 @@ +: triangle-allocate ( u -- addr ) + dup 1+ * 2/ cells dup + allocate abort" out of memory" + tuck swap erase ; + +: triangle-deallocate ( addr -- ) + free abort" memory deallocation error" ; + +: triangle-row-address ( addr u -- addr ) + dup 1+ * 2/ cells + ; + +: bell-triangle-row ( addr u -- ) + tuck 1- triangle-row-address + 2dup swap cells + + dup 1 cells - @ over ! + rot 0 ?do + dup @ >r over @ r> + >r + cell+ r> over ! + swap cell+ swap + loop 2drop ; + +: bell-triangle ( u -- addr ) + dup triangle-allocate + dup 1 swap ! + swap 1 ?do + dup i bell-triangle-row + loop ; + +: print-bell-numbers ( addr u -- ) + 0 ?do + dup i triangle-row-address @ . cr + loop drop ; + +: print-bell-row ( addr u -- ) + tuck triangle-row-address swap + 1+ 0 ?do + dup @ . cell+ + loop drop cr ; + +: main ( -- ) + 15 bell-triangle + ." First 15 Bell numbers:" cr + dup 15 print-bell-numbers cr + ." First 10 rows of the Bell triangle:" cr + 10 0 do + dup i print-bell-row + loop + triangle-deallocate ; + +main +bye diff --git a/Task/Bell-numbers/Pascal/bell-numbers.pas b/Task/Bell-numbers/Free-Pascal-Lazarus/bell-numbers.pas similarity index 100% rename from Task/Bell-numbers/Pascal/bell-numbers.pas rename to Task/Bell-numbers/Free-Pascal-Lazarus/bell-numbers.pas diff --git a/Task/Bell-numbers/Haskell/bell-numbers-5.hs b/Task/Bell-numbers/Haskell/bell-numbers-5.hs new file mode 100644 index 0000000000..2574f2daa3 --- /dev/null +++ b/Task/Bell-numbers/Haskell/bell-numbers-5.hs @@ -0,0 +1,17 @@ +import Data.Ratio ((%), numerator) + +infixl 7 *. +(*.) :: Num a => a -> [a] -> [a] +x *. (p:ps) = x*p : x*.ps + +instance Num a => Num [a] where + negate = map negate + (+) = zipWith (+) + (*) (p:ps) (q:qs) = p*q : ((p*.qs) + ps*(q:qs)) + fromInteger n = fromInteger n:repeat 0 + +instance (Eq a, Fractional a) => Fractional [a] where + (/) (0:ps) (0:qs) = ps/qs + (/) (p:ps) (q:qs) = let r=p/q in r : (ps - r*.qs)/(q:qs) + + fromRational q = fromRational q:repeat 0 diff --git a/Task/Bell-numbers/Haskell/bell-numbers-6.hs b/Task/Bell-numbers/Haskell/bell-numbers-6.hs new file mode 100644 index 0000000000..1cccede973 --- /dev/null +++ b/Task/Bell-numbers/Haskell/bell-numbers-6.hs @@ -0,0 +1,2 @@ +expseq :: [Rational] -> [Rational] +expseq ps = zipWith (\p q -> p*fromInteger q) ps (scanl (*) 1 [1..]) diff --git a/Task/Bell-numbers/Haskell/bell-numbers-7.hs b/Task/Bell-numbers/Haskell/bell-numbers-7.hs new file mode 100644 index 0000000000..e6c2d50d9c --- /dev/null +++ b/Task/Bell-numbers/Haskell/bell-numbers-7.hs @@ -0,0 +1,3 @@ +infixr 9 |> +(|>) :: (Eq a, Num a) => [a] -> [a] -> [a] +(p:ps) |> (0:qs) = p : qs*(ps |> (0:qs)) diff --git a/Task/Bell-numbers/Haskell/bell-numbers-8.hs b/Task/Bell-numbers/Haskell/bell-numbers-8.hs new file mode 100644 index 0000000000..9cc115db88 --- /dev/null +++ b/Task/Bell-numbers/Haskell/bell-numbers-8.hs @@ -0,0 +1,11 @@ +exp1 :: [Rational] +exp1 = 0 : map (1%) factorials + where + factorials = scanl (*) 1 [2..] + +exps :: [Rational] +exps = 1 : zipWith (*) exps [ 1%n | n <- [1..] ] + +bell :: [Integer] +bell = map numerator + (expseq (exps |> exp1)) diff --git a/Task/Bell-numbers/Haskell/bell-numbers-9.hs b/Task/Bell-numbers/Haskell/bell-numbers-9.hs new file mode 100644 index 0000000000..11d50b5761 --- /dev/null +++ b/Task/Bell-numbers/Haskell/bell-numbers-9.hs @@ -0,0 +1,4 @@ +ghci> take 15 bell +[1,1,2,5,15,52,203,877,4140,21147,115975,678570,4213597,27644437,190899322] +ghci> bell !! 49 +10726137154573358400342215518590002633917247281 diff --git a/Task/Bell-numbers/JavaScript/bell-numbers.js b/Task/Bell-numbers/JavaScript/bell-numbers.js new file mode 100644 index 0000000000..d6982673f0 --- /dev/null +++ b/Task/Bell-numbers/JavaScript/bell-numbers.js @@ -0,0 +1,75 @@ +// --------------------------------------------------------------- +// Bell Triangle implementation (JavaScript) +// --------------------------------------------------------------- + +class BellTriangle { + /** + * @param {number} n – number of rows to generate + */ + constructor(n) { + // total number of elements in a triangular array of size n + const length = (n * (n + 1)) / 2; + // use a plain array, pre‑filled with zeros + this.arr = new Array(length).fill(0); + + // initialise first element (row 1, col 0) = 1 + this.set(1, 0, 1); + + // build the triangle row by row + for (let i = 2; i <= n; ++i) { + // first element of a row copies the last element of the previous row + this.set(i, 0, this.get(i - 1, i - 2)); + + // the remaining entries are sums of the element above‑left + // and the element to the left in the current row + for (let j = 1; j < i; ++j) { + const value = this.get(i, j - 1) + this.get(i - 1, j - 1); + this.set(i, j, value); + } + } + } + + /** Convert (row, col) into a linear index. Rows start at 1. */ + index(row, col) { + if (row > 0 && col >= 0 && col < row) { + // triangular number formula: sum_{k=1}^{row-1} k = row*(row-1)/2 + return (row * (row - 1)) / 2 + col; + } + throw new Error('Invalid row/col'); + } + + /** Return the value at (row, col). */ + get(row, col) { + const i = this.index(row, col); + return this.arr[i]; + } + + /** Store `value` at (row, col). */ + set(row, col, value) { + const i = this.index(row, col); + this.arr[i] = value; + } +} + +// --------------------------------------------------------------- +// Main program – reproduces the Java `main` method +// --------------------------------------------------------------- +(function main() { + const rows = 15; + const bt = new BellTriangle(rows); + + console.log('First fifteen Bell numbers:'); + for (let i = 0; i < rows; ++i) { + // the Bell number Bₙ is the first entry of row n (row index = n, col = 0) + console.log(`${i + 1}: ${bt.get(i + 1, 0)}`); + } + + // Print the whole triangle for the first 10 rows (exactly as Java did) + for (let i = 1; i <= 10; ++i) { + let line = `${bt.get(i, 0)}`; + for (let j = 1; j < i; ++j) { + line += `, ${bt.get(i, j)}`; + } + console.log(line); + } +})(); diff --git a/Task/Bell-numbers/Julia/bell-numbers.julia b/Task/Bell-numbers/Julia/bell-numbers.jl similarity index 100% rename from Task/Bell-numbers/Julia/bell-numbers.julia rename to Task/Bell-numbers/Julia/bell-numbers.jl diff --git a/Task/Bell-numbers/Kotlin/bell-numbers.kotlin b/Task/Bell-numbers/Kotlin/bell-numbers.kts similarity index 100% rename from Task/Bell-numbers/Kotlin/bell-numbers.kotlin rename to Task/Bell-numbers/Kotlin/bell-numbers.kts diff --git a/Task/Bell-numbers/Loglan82/bell-numbers.loglan82 b/Task/Bell-numbers/Loglan82/bell-numbers.loglan82 new file mode 100644 index 0000000000..141ec17f83 --- /dev/null +++ b/Task/Bell-numbers/Loglan82/bell-numbers.loglan82 @@ -0,0 +1,28 @@ +(* Bell numbers *) + +block +const + max_n = 13; +var + a: arrayof integer, + i, j, n: integer; +begin + array a dim (0 : max_n); + n := 0; + for i := 0 to max_n - 1 + do + a(i) := 0 + od; + a(0) := 1; + writeln("B(", n: 2, ") = ", a(0): 9); + while n < max_n + do + a(n) := a(0); + for j := n downto 1 + do + a(j - 1) := a(j - 1) + a(j) + od; + n := n + 1; + writeln("B(", n: 2, ") = ", a(0): 9); + od; +end; diff --git a/Task/Bell-numbers/Miranda/bell-numbers.miranda b/Task/Bell-numbers/Miranda/bell-numbers.miranda new file mode 100644 index 0000000000..67a573f599 --- /dev/null +++ b/Task/Bell-numbers/Miranda/bell-numbers.miranda @@ -0,0 +1,16 @@ +main :: [sys_message] +main = [Stdout "First 15 and 50th Bell numbers:\n", + Stdout (lay [(rjustify 2 (show i)) ++ ": " ++ show (bell_numbers ! i) + | i <- [1..15] ++ [50]]), + Stdout "\nFirst 10 rows of the Bell triangle:\n", + Stdout (lay [concat [rjustify 7 (show n) | n <- row] + | row <- take 10 bell_triangle]) + ] + + +bell_numbers :: [num] +bell_numbers = map last bell_triangle + +bell_triangle :: [[num]] +bell_triangle = iterate bell_step [1] + where bell_step row = scan (+) (last row) row diff --git a/Task/Bell-numbers/MoonRock/bell-numbers.moonrock b/Task/Bell-numbers/MoonRock/bell-numbers.moonrock new file mode 100644 index 0000000000..21caf0d119 --- /dev/null +++ b/Task/Bell-numbers/MoonRock/bell-numbers.moonrock @@ -0,0 +1,43 @@ +' Bell numbers + +BEGIN DEF +SUB PrintStr(S$, Width%) +%MaxN = 14 +DIM A&[%MaxN] + +BEGIN CODE +N% = 0 +FOR I% = 0 TO %MaxN -1 + A&[I%] = 0 +NEXT +A&[0] = 1 +PRINT "B(" +CALL PrintStr(STR(N%), 2) +PRINT ") = " +CALL PrintStr(STR(A&[0]), 9) +PRINT "\n" +WHILE N% < %MaxN + A&[N%] = A&[0] + J% = N% + WHILE J% >= 1 + JMin1% = J% - 1 + A&[JMin1%] = A&[JMin1%] + A&[J%] + J% = J% - 1 + WEND + N% = N% + 1 + PRINT "B(" + CALL PrintStr(STR(N%), 2) + PRINT ") = " + CALL PrintStr(STR(A&[0]), 9) + PRINT "\n" +WEND +END + +SUB PrintStr(S$, Width%) +IF LEN(S$) > Width% THEN + PRINT S$ +ELSE + S$ = SPACE(Width%) + S$ + PRINT RIGHT(S$, Width%) +ENDIF +END SUB diff --git a/Task/Bell-numbers/Oberon-07/bell-numbers.oberon b/Task/Bell-numbers/Oberon-07/bell-numbers.oberon new file mode 100644 index 0000000000..0d8ac34e3d --- /dev/null +++ b/Task/Bell-numbers/Oberon-07/bell-numbers.oberon @@ -0,0 +1,28 @@ +MODULE BellNumbers; + IMPORT Out; + + PROCEDURE showBellNumbers; + CONST maxBell = 15; + VAR a : ARRAY maxBell - 1 OF INTEGER; + i, n, j : INTEGER; + + PROCEDURE showOneBellNumber( n, bellNumber : INTEGER ); + BEGIN + Out.Int( n, 2 );Out.String( ": " );Out.Int( bellNumber, 0 );Out.Ln + END showOneBellNumber; + + BEGIN + FOR i := 1 TO LEN( a ) - 1 DO a[ i ] := 0 END; + a[ 0 ] := 1; + showOneBellNumber( 1, a[ 0 ] ); + FOR n := 0 TO maxBell - 2 DO + (* replace a with the next line of the triangle *) + a[ n ] := a[ 0 ]; + FOR j := n TO 1 BY -1 DO INC( a[ j - 1 ], a[ j ] ) END; + showOneBellNumber( n + 2, a[ 0 ] ) + END + END showBellNumbers; + +BEGIN + showBellNumbers +END BellNumbers. diff --git a/Task/Bell-numbers/PARI-GP/bell-numbers.parigp b/Task/Bell-numbers/PARI-GP/bell-numbers.parigp new file mode 100644 index 0000000000..f62bf25259 --- /dev/null +++ b/Task/Bell-numbers/PARI-GP/bell-numbers.parigp @@ -0,0 +1,4 @@ +genit(maxx=50)={bell=List(); +for(n=0,maxx,q=sum(k=0,n,stirling(n,k,2)); +listput(bell,q));bell} +END diff --git a/Task/Bell-numbers/PHP/bell-numbers.php b/Task/Bell-numbers/PHP/bell-numbers.php new file mode 100644 index 0000000000..ead13effb8 --- /dev/null +++ b/Task/Bell-numbers/PHP/bell-numbers.php @@ -0,0 +1,17 @@ += 1; $j--) + $a[$j - 1] += $a[$j]; + $n++; + echo 'B('.str_pad($n, 2, " ", STR_PAD_LEFT).') = '. + str_pad($a[0], 9, " ", STR_PAD_LEFT).PHP_EOL; +} +?> diff --git a/Task/Bell-numbers/PL-I/bell-numbers.pli b/Task/Bell-numbers/PL-I/bell-numbers.pli new file mode 100644 index 0000000000..f9386c59bf --- /dev/null +++ b/Task/Bell-numbers/PL-I/bell-numbers.pli @@ -0,0 +1,25 @@ +/* Bell numbers */ + +Bell_nums: + procedure options(main); + %replace nmax by 9; + declare + a(0 : nmax) fixed binary(15), + (i, j, n) fixed binary(15); + n = 0; + do i = 0 to nmax - 1; + a(i) = 0; + end; + a(0) = 1; + put list('B('); + put edit(n, ') = ', a(0))(f(2), a, f(9)); + do while (n < nmax); + a(n) = a(0); + do j = n to 1 by -1; + a(j - 1) = a(j - 1) + a(j); + end; + n = n + 1; + put skip list('B('); + put edit(n, ') = ', a(0))(f(2), a, f(9)); + end; +end Bell_nums; diff --git a/Task/Bell-numbers/Pascal-P/bell-numbers.pas b/Task/Bell-numbers/Pascal-P/bell-numbers.pas new file mode 100644 index 0000000000..4cfaf86cfc --- /dev/null +++ b/Task/Bell-numbers/Pascal-P/bell-numbers.pas @@ -0,0 +1,20 @@ +program bellnums(output); + (* Bell numbers *) +const + maxn = 14; (* with 32-bit integer *) +var + a: array[0..maxn - 1] of integer; + i, j, n: integer; +begin + n := 0; + for i := 0 to maxn - 1 do a[i] := 0; + a[0] := 1; + writeln('B(', n: 2, ') = ', a[0]: 9); + while n < maxn do + begin + a[n] := a[0]; + for j := n downto 1 do a[j - 1] := a[j - 1] + a[j]; + n := n + 1; + writeln('B(', n: 2, ') = ', a[0]: 9); + end; +end. diff --git a/Task/Bell-numbers/Pluto/bell-numbers.pluto b/Task/Bell-numbers/Pluto/bell-numbers.pluto new file mode 100644 index 0000000000..5cabc1baca --- /dev/null +++ b/Task/Bell-numbers/Pluto/bell-numbers.pluto @@ -0,0 +1,32 @@ +local bigint = require "bigint" +local fmt = require "fmt" + +local function bell_triangle(n) + local zero = bigint.new(0) + local tri = {} + for i = 1, n do + tri[i] = {} + for j = 1, i - 1 do tri[i][j] = zero end + end + tri[2][1] = bigint.new(1) + for i = 3, n do + tri[i][1] = tri[i - 1][i - 2] + for j = 2, i - 1 do + tri[i][j] = tri[i][j - 1] + tri[i - 1][j - 1] + end + end + return tri +end + +local bt = bell_triangle(51) +print("First fifteen and fiftieth Bell numbers:") +for i = 2, 16 do + local s = bt[i][1]:tostring() + fmt.print("%2d: %s", i - 1, fmt.int(s)) +end +local s50 = bt[51][1]:tostring() +fmt.print("%2d: %s", 50, fmt.int(s50)) +print("\nThe first ten rows of Bell's triangle:") +for i = 2, 11 do + fmt.tprint("%7s", bt[i]:map(|j| -> fmt.int(j:tostring())), #bt[i]) +end diff --git a/Task/Bell-numbers/PowerShell/bell-numbers.ps1 b/Task/Bell-numbers/PowerShell/bell-numbers.ps1 new file mode 100644 index 0000000000..2a173ea9e9 --- /dev/null +++ b/Task/Bell-numbers/PowerShell/bell-numbers.ps1 @@ -0,0 +1,19 @@ +# Bell numbers +[uint32]$script:MaxN = 14 +$a = [uint32[]]::new($script:MaxN) +foreach ($i in 0..($script:MaxN - 1)) { + $a[$i] = 0 +} +[uint32]$n = 0 +$a[0] = 1 +[string]$row = "B({0, 2}) = {1,9}" -f $n, $a[0] +Write-Output $row +while ($n -lt $script:MaxN) { + $a[$n] = $a[0] + foreach ($j in $n..1) { + $a[$j - 1] += $a[$j] + } + $n++ + [string]$row = "B({0, 2}) = {1,9}" -f $n, $a[0] + Write-Output $row +} diff --git a/Task/Bell-numbers/Refal/bell-numbers.refal b/Task/Bell-numbers/Refal/bell-numbers.refal new file mode 100644 index 0000000000..f65c59ce11 --- /dev/null +++ b/Task/Bell-numbers/Refal/bell-numbers.refal @@ -0,0 +1,41 @@ +$ENTRY Go { + , : e.Bell (e.B50) + , : (e.F15) e.Rest + = + + >; +} + +Show { + (e.X) = >; +}; + +BellNumbers { + s.N, : e.Rows = ; +}; + +BellTriangle { + s.N = ((1))>; + 0 e.T = e.T; + s.N e.Rs (e.R) = e.Rs (e.R) ()>; +}; + +BellStep { + e.Row, e.Row: e.X (e.Last) = ; +}; + +Rsum { + (Acc e.Acc) = ; + (Acc e.Acc) (e.N) e.Ns, : e.N2 = + (e.N2) ; + e.Ns = ; +}; + +Each { + (e.F) = ; + (e.F) (e.X) e.Xs = () ; +}; + +Head { + t.X e.Y = t.X; +}; diff --git a/Task/Bell-numbers/Rust/bell-numbers.rust b/Task/Bell-numbers/Rust/bell-numbers.rs similarity index 100% rename from Task/Bell-numbers/Rust/bell-numbers.rust rename to Task/Bell-numbers/Rust/bell-numbers.rs diff --git a/Task/Bell-numbers/SETL/bell-numbers.setl b/Task/Bell-numbers/SETL/bell-numbers.setl new file mode 100644 index 0000000000..83c7ca45d4 --- /dev/null +++ b/Task/Bell-numbers/SETL/bell-numbers.setl @@ -0,0 +1,31 @@ +program bell_numbers; + print("First 15 and 50th Bell numbers:"); + b := bell_nums(50); + loop for i in [1..15] with 50 do + print(lpad(str i, 2) + ": " + str b(i)); + end loop; + + print; + print("First 10 rows of the Bell triangle:"); + loop for row in bell_triangle(10) do + print(+/[lpad(str n, 7) : n in row]); + end loop; + + proc bell_nums(n); + tri := bell_triangle(n); + return [row(#row) : row in tri]; + end proc; + + proc bell_triangle(rows); + tri := [[1]]; + loop for i in [2..rows] do + row := tri(#tri); + nextrow := [row(#row)]; + loop for n in row do + nextrow with:= nextrow(#nextrow) + n; + end loop; + tri with:= nextrow; + end loop; + return tri; + end proc; +end program; diff --git a/Task/Bell-numbers/Scheme/bell-numbers.ss b/Task/Bell-numbers/Scheme/bell-numbers.scm similarity index 100% rename from Task/Bell-numbers/Scheme/bell-numbers.ss rename to Task/Bell-numbers/Scheme/bell-numbers.scm diff --git a/Task/Bell-numbers/Uiua/bell-numbers.uiua b/Task/Bell-numbers/Uiua/bell-numbers.uiua new file mode 100644 index 0000000000..c6d1180ce3 --- /dev/null +++ b/Task/Bell-numbers/Uiua/bell-numbers.uiua @@ -0,0 +1,12 @@ +# Generate Bell numbers. + +# Use Marcos' BigInt library. +~ "git: https://github.com/Marcos-cat/uiua-bigint" ~ Add New Str + +# Generate next row of the Bell triangle. +# Supply simple `+` for ints, or `⍜∩°□Add` for BigInts. +Next! ← ⊙◌⍢(⊂⊙^0⊓⟜⊣°⊂|>0⋅⧻)⊸[⊣] + +&p⍥⊃Next!+⊢15 [1] # First fifteen. +&pStr°□⊢⍥Next!⍜∩°□Add49[1] # Fiftieth. +≡&p⍥⊃Next!+□10 [1] # First ten lines of triangle. diff --git a/Task/Bell-numbers/VBA/bell-numbers.vba b/Task/Bell-numbers/VBA/bell-numbers.vba new file mode 100644 index 0000000000..35b134c90f --- /dev/null +++ b/Task/Bell-numbers/VBA/bell-numbers.vba @@ -0,0 +1,32 @@ +' Bell numbers + +Const MaxN As Integer = 14 + +Sub BellNumsMain() + Dim A(MaxN - 1) As Long + Dim N, J As Integer + For I = 0 To MaxN - 1 + A(I) = 0 + Next I + N = 0 + A(0) = 1 + Debug.Print "B(" & FormatLong(N, 2) & ") = " & FormatLong(A(0), 9) + Do While N < MaxN + A(N) = A(0) + For J = N To 1 Step -1 + A(J - 1) = A(J - 1) + A(J) + Next J + N = N + 1 + Debug.Print "B(" & FormatLong(N, 2) & ") = " & FormatLong(A(0), 9) + Loop +End Sub + +Function FormatLong(ByVal Num As Long, L As Integer) As String + Dim S As String + S = Trim(Str(Num)) + If Len(S) > L Then + FormatLong = String(L, "#") + Else + FormatLong = Right(String(L, " ") & S, L) + End If +End Function diff --git a/Task/Benfords-law/Ada/benfords-law-1.ada b/Task/Benfords-law/Ada/benfords-law-1.adb similarity index 100% rename from Task/Benfords-law/Ada/benfords-law-1.ada rename to Task/Benfords-law/Ada/benfords-law-1.adb diff --git a/Task/Benfords-law/Ada/benfords-law-2.ada b/Task/Benfords-law/Ada/benfords-law-2.adb similarity index 100% rename from Task/Benfords-law/Ada/benfords-law-2.ada rename to Task/Benfords-law/Ada/benfords-law-2.adb diff --git a/Task/Benfords-law/Crystal/benfords-law.crystal b/Task/Benfords-law/Crystal/benfords-law.cr similarity index 100% rename from Task/Benfords-law/Crystal/benfords-law.crystal rename to Task/Benfords-law/Crystal/benfords-law.cr diff --git a/Task/Benfords-law/Dart/benfords-law.dart b/Task/Benfords-law/Dart/benfords-law.dart new file mode 100644 index 0000000000..4182f28c03 --- /dev/null +++ b/Task/Benfords-law/Dart/benfords-law.dart @@ -0,0 +1,35 @@ +import 'dart:math'; + +digits(n) sync* { + double a = 0, b = 1; + for (var i = 0; i < n; i++) { + yield b.toString().codeUnitAt(0) - 48; + (a, b) = (b, a + b); + } +} + +lineout(s1, s2, s3) { + print( + s1.toString().padLeft(8) + + s2.toString().padLeft(12) + + s3.toString().padLeft(12), + ); +} + +main() { + var tally = List.filled(9, 0); + for (var d in digits(1000)) { + tally[d - 1] += 1; + } + + lineout("Digit", "Expected", "Actual"); + print("-" * 40); + + for (var d = 1; d < 10; d += 1) { + lineout( + d, + (log(1 + 1 / d) * log10e).toStringAsFixed(4), + (tally[d - 1] / 1000).toStringAsFixed(3), + ); + } +} diff --git a/Task/Benfords-law/DuckDB/benfords-law.duckdb b/Task/Benfords-law/DuckDB/benfords-law.duckdb new file mode 100644 index 0000000000..ec7d41aaa2 --- /dev/null +++ b/Task/Benfords-law/DuckDB/benfords-law.duckdb @@ -0,0 +1,22 @@ +with recursive fib (n1, n2) as ( + select + 1::double, 1::double + union all + select n2, n1+n2 + from fib + ), +lastdigits as ( + select format('{}', n1)[1]::int as digit + from fib + limit 1000 -- N.B. + ), +counts as ( + select digit, count() as actual + from lastdigits group by digit + ), +total as ( + select count() as total from lastdigits + ) +select digit, actual, (total * log(10, 1 + (1 / digit))) as expected + from counts, total + order by digit; diff --git a/Task/Benfords-law/EasyLang/benfords-law.easy b/Task/Benfords-law/EasyLang/benfords-law.easy index 56624832fb..7f84888fa7 100644 --- a/Task/Benfords-law/EasyLang/benfords-law.easy +++ b/Task/Benfords-law/EasyLang/benfords-law.easy @@ -1,19 +1,18 @@ func$ add a$ b$ . - for i to higher len a$ len b$ + if len a$ < len b$ : swap a$ b$ + for i to len a$ a = number substr a$ i 1 - b = number substr b$ i 1 + b = 0 + if i <= len b$ : b = number substr b$ i 1 r = a + b + c c = r div 10 r$ &= r mod 10 . - if c > 0 - r$ &= c - . + if c > 0 : r$ &= c return r$ . -# len fibdist[] 9 -proc mkfibdist . . +proc mkfibdist . # generate 1000 fibonacci numbers as # (reversed) strings, because 53 bit # integers are too small @@ -36,14 +35,14 @@ proc mkfibdist . . mkfibdist # len benfdist[] 9 -proc mkbenfdist . . +proc mkbenfdist . for i to 9 - benfdist[i] = log10 (1 + 1.0 / i) + benfdist[i] = log (1 + 1 / i) 10 . . mkbenfdist # -numfmt 3 0 +numfmt 0 3 print "Actual Expected" for i to 9 print fibdist[i] & " " & benfdist[i] diff --git a/Task/Benfords-law/Elixir/benfords-law.elixir b/Task/Benfords-law/Elixir/benfords-law.ex similarity index 100% rename from Task/Benfords-law/Elixir/benfords-law.elixir rename to Task/Benfords-law/Elixir/benfords-law.ex diff --git a/Task/Benfords-law/Fortran/benfords-law-3.f b/Task/Benfords-law/Fortran/benfords-law-3.f new file mode 100644 index 0000000000..5c2ca6d8b6 --- /dev/null +++ b/Task/Benfords-law/Fortran/benfords-law-3.f @@ -0,0 +1,33 @@ + PROGRAM benford + INTEGER counts(9) + + expected(d) = log10(1.0 + 1.0/d) + + CALL tally(counts) + + PRINT 100, 'Digit', 'Actual', 'Expected' + DO 10, i = 1, 9 +10 PRINT 101, i, counts(i)/1E3, expected(real(i)) + +100 FORMAT (A6, 1X, A9, 1X, A9) +101 FORMAT (I4, 3X, F9.3, 1X, F9.4) + END PROGRAM + + + SUBROUTINE tally(counts) + INTEGER counts(9) + CHARACTER*20 str + DOUBLE PRECISION a, b, c + INTEGER d + + counts = [(0, i = 1, 9)] + a = 0 + b = 1 + DO 10, i = 1, 1000 + WRITE (str, '(E12.6)') b + d = ichar(str(3:3)) - ichar('0') + counts(d) = counts(d) + 1 + c = a + b + a = b +10 b = c + END SUBROUTINE diff --git a/Task/Benfords-law/Julia/benfords-law.julia b/Task/Benfords-law/Julia/benfords-law.jl similarity index 100% rename from Task/Benfords-law/Julia/benfords-law.julia rename to Task/Benfords-law/Julia/benfords-law.jl diff --git a/Task/Benfords-law/K/benfords-law.k b/Task/Benfords-law/K/benfords-law.k new file mode 100644 index 0000000000..5418b93641 --- /dev/null +++ b/Task/Benfords-law/K/benfords-law.k @@ -0,0 +1,7 @@ +law: {(`ln 1 + 1%x) % `ln 10} +tally: #' = {*$x}' +\[1000; 0.0; 1.0] + +`0: (8$"digit"), (12$"Expected"), "Actual" + +row: {`0: (-3$$x), (-13$7#$law x), -10$"0.", $tally[*$x]} +nop: 9 {row x; x + 1}/ 1 diff --git a/Task/Benfords-law/Kotlin/benfords-law.kotlin b/Task/Benfords-law/Kotlin/benfords-law.kts similarity index 100% rename from Task/Benfords-law/Kotlin/benfords-law.kotlin rename to Task/Benfords-law/Kotlin/benfords-law.kts diff --git a/Task/Benfords-law/OCaml/benfords-law.ocaml b/Task/Benfords-law/OCaml/benfords-law.ml similarity index 100% rename from Task/Benfords-law/OCaml/benfords-law.ocaml rename to Task/Benfords-law/OCaml/benfords-law.ml diff --git a/Task/Benfords-law/Pluto/benfords-law.pluto b/Task/Benfords-law/Pluto/benfords-law.pluto new file mode 100644 index 0000000000..b5354c40ab --- /dev/null +++ b/Task/Benfords-law/Pluto/benfords-law.pluto @@ -0,0 +1,30 @@ +local bigint = require "pluto:bigint" +local fmt = require "fmt" +require "table2" + +local function fib1000() + local a = bigint.new(0) + local b = bigint.new(1) + local r = table.create(1000) + for i = 1, 1000 do + r[i] = b + a, b = b, b + a + end + return r +end + +local function show(c, title) + local f = table.rep(9, 0) + for c as v do + local t = v:tostring():byte() - 48 + f[t] += 1 + end + print(title) + print("Digit Observed Predicted") + for i = 1, #f do + local t = math.log(1 / i + 1, 10) + fmt.print(" %d %8.3f %8.3f", i, f[i] / #c, t) + end +end + +show(fib1000(), "First 1000 Fibonacci numbers:") diff --git a/Task/Benfords-law/PowerShell/benfords-law.psh b/Task/Benfords-law/PowerShell/benfords-law.ps1 similarity index 100% rename from Task/Benfords-law/PowerShell/benfords-law.psh rename to Task/Benfords-law/PowerShell/benfords-law.ps1 diff --git a/Task/Benfords-law/Quackery/benfords-law.quackery b/Task/Benfords-law/Quackery/benfords-law.quackery new file mode 100644 index 0000000000..c18ea50a99 --- /dev/null +++ b/Task/Benfords-law/Quackery/benfords-law.quackery @@ -0,0 +1,36 @@ + [ $ "bigrat.qky" loadfile ] now! + + [ ' [ 1 1 ] + swap 2 - times + [ dup -1 peek + over -2 peek + + join ] ] is fibonacci ( n --> [ ) + + [ 0 swap witheach + ] is sum ( [ --> n ) + + [ [ 10 /mod over while + drop again ] nip ] is msd ( n --> n ) + + [ 2dup peek 1+ unrot poke ] is tallydigit ( [ n --> [ ) + + [ 0 10 of swap + witheach + [ msd tallydigit ] ] is msdcount ( [ --> [ ) + + [ [ table + $ "0.30103" $ "0.17609" + $ "0.12494" $ "0.09691" + $ "0.07918" $ "0.06695" + $ "0.05799" $ "0.05115" + $ "0.04576" ] do echo$ ] is expected ( --> ) + + say "n expected counted" cr + 1000 fibonacci msdcount + behead drop + dup sum swap + witheach + [ i^ 1+ echo sp sp + i^ expected sp sp + over reduce + 5 point$ echo$ cr ] + drop diff --git a/Task/Benfords-law/Rust/benfords-law.rust b/Task/Benfords-law/Rust/benfords-law.rs similarity index 100% rename from Task/Benfords-law/Rust/benfords-law.rust rename to Task/Benfords-law/Rust/benfords-law.rs diff --git a/Task/Benfords-law/Scheme/benfords-law.ss b/Task/Benfords-law/Scheme/benfords-law.scm similarity index 100% rename from Task/Benfords-law/Scheme/benfords-law.ss rename to Task/Benfords-law/Scheme/benfords-law.scm diff --git a/Task/Benfords-law/Uiua/benfords-law.uiua b/Task/Benfords-law/Uiua/benfords-law.uiua new file mode 100644 index 0000000000..343c2304a9 --- /dev/null +++ b/Task/Benfords-law/Uiua/benfords-law.uiua @@ -0,0 +1,4 @@ +F ← |1 memo(⨬(+∩F-1.-1|⋅1)<2.) +Lim ← 1000 +&p$"Expected: _"⁅×Limₙ10+1÷:1↘1⇡10 +&p$"Got: _"⊕⧻⊛.≡(⊢°⋕F)⇡Lim diff --git a/Task/Bernoulli-numbers/ALGOL-68/bernoulli-numbers.alg b/Task/Bernoulli-numbers/ALGOL-68/bernoulli-numbers.alg index 915f596b5e..3f48297679 100644 --- a/Task/Bernoulli-numbers/ALGOL-68/bernoulli-numbers.alg +++ b/Task/Bernoulli-numbers/ALGOL-68/bernoulli-numbers.alg @@ -33,14 +33,7 @@ BEGIN num OF result//den OF result ); - OP - = (FRAC a, b)FRAC: a + -b, - * = (FRAC a, b)FRAC: ( - LONG LONG INT num = num OF a * num OF b, - den = den OF a * den OF b; - LONG LONG INT common = gcd(num, den); - (num OVER common) // (den OVER common) - ); - + OP - = (FRAC a, b)FRAC: a + -b; OP - = (FRAC frac)FRAC: (-num OF frac, den OF frac); # ============================================================== # @@ -71,7 +64,8 @@ BEGIN FRAC bn := bernoulli( n ); IF num OF bn /= 0 THEN # have a non-0 Bn # - print( ( "B(", whole( n, -2 ), ") ", whole( num OF bn, -50 ), " / ", whole( den OF bn, 0 ), newline ) ) + print( ( "B(", whole( n, -2 ), ") ", whole( num OF bn, -50 ) ) ); + print( ( " / ", whole( den OF bn, 0 ), newline ) ) FI OD END diff --git a/Task/Bernoulli-numbers/Ada/bernoulli-numbers.ada b/Task/Bernoulli-numbers/Ada/bernoulli-numbers-1.adb similarity index 100% rename from Task/Bernoulli-numbers/Ada/bernoulli-numbers.ada rename to Task/Bernoulli-numbers/Ada/bernoulli-numbers-1.adb diff --git a/Task/Bernoulli-numbers/Ada/bernoulli-numbers-2.adb b/Task/Bernoulli-numbers/Ada/bernoulli-numbers-2.adb new file mode 100644 index 0000000000..16ff6c98fa --- /dev/null +++ b/Task/Bernoulli-numbers/Ada/bernoulli-numbers-2.adb @@ -0,0 +1,45 @@ +with Ada.Text_IO; use Ada.Text_IO; +with Strings_Edit; use Strings_Edit; +with Strings_Edit.Integers; use Strings_Edit.Integers; +with Unbounded_Rationals; use Unbounded_Rationals; +with Unbounded_Unsigneds; use Unbounded_Unsigneds; + +with Strings_Edit.Unbounded_Unsigned_Edit; +use Strings_Edit.Unbounded_Unsigned_Edit; + +procedure Bernoulli is + function Bernoulli_Number (N : Natural) return Unbounded_Rational is + A : array (0..Half_Word (N)) of Unbounded_Rational; + begin + for M in 0..Half_Word (N) loop + A (M) := Unbounded_Rationals.One / (M + 1); + for J in reverse 1..M LOOP + A (J - 1) := J * (A (J - 1) - A (J)); + end loop; + end loop; + return A (0); + end Bernoulli_Number; + B : Unbounded_Rational; + Line : String (1..80); + Pointer : Integer; +begin + for I in 0..60 loop + if I mod 2 = 0 or else I = 1 then + B := Bernoulli_Number (I); + if not Is_Zero (B) then + Pointer := 1; + Put (Line, Pointer, "B("); + Put (Line, Pointer, I, 10, False, 2, Right); + Put (Line, Pointer, ") = "); + if Is_Negative (B) then + Put (Line, Pointer, '-' & Image (Get_Numerator (B)), 45, Right); + else + Put (Line, Pointer, Get_Numerator (B), 10, 45, Right); + end if; + Put (Line, Pointer, " / "); + Put (Line, Pointer, Get_Denominator (B)); + Put_Line (Line (1..Pointer - 1)); + end if; + end if; + end loop; +end Bernoulli; diff --git a/Task/Bernoulli-numbers/Crystal/bernoulli-numbers-1.crystal b/Task/Bernoulli-numbers/Crystal/bernoulli-numbers-1.cr similarity index 100% rename from Task/Bernoulli-numbers/Crystal/bernoulli-numbers-1.crystal rename to Task/Bernoulli-numbers/Crystal/bernoulli-numbers-1.cr diff --git a/Task/Bernoulli-numbers/Crystal/bernoulli-numbers-2.crystal b/Task/Bernoulli-numbers/Crystal/bernoulli-numbers-2.cr similarity index 100% rename from Task/Bernoulli-numbers/Crystal/bernoulli-numbers-2.crystal rename to Task/Bernoulli-numbers/Crystal/bernoulli-numbers-2.cr diff --git a/Task/Bernoulli-numbers/Crystal/bernoulli-numbers-3.crystal b/Task/Bernoulli-numbers/Crystal/bernoulli-numbers-3.cr similarity index 100% rename from Task/Bernoulli-numbers/Crystal/bernoulli-numbers-3.crystal rename to Task/Bernoulli-numbers/Crystal/bernoulli-numbers-3.cr diff --git a/Task/Bernoulli-numbers/Delphi/bernoulli-numbers.delphi b/Task/Bernoulli-numbers/Delphi/bernoulli-numbers.pas similarity index 100% rename from Task/Bernoulli-numbers/Delphi/bernoulli-numbers.delphi rename to Task/Bernoulli-numbers/Delphi/bernoulli-numbers.pas diff --git a/Task/Bernoulli-numbers/Elixir/bernoulli-numbers.elixir b/Task/Bernoulli-numbers/Elixir/bernoulli-numbers.ex similarity index 100% rename from Task/Bernoulli-numbers/Elixir/bernoulli-numbers.elixir rename to Task/Bernoulli-numbers/Elixir/bernoulli-numbers.ex diff --git a/Task/Bernoulli-numbers/FutureBasic/bernoulli-numbers.basic b/Task/Bernoulli-numbers/FutureBasic/bernoulli-numbers.basic new file mode 100644 index 0000000000..b0d0000ba4 --- /dev/null +++ b/Task/Bernoulli-numbers/FutureBasic/bernoulli-numbers.basic @@ -0,0 +1,93 @@ +// +// Bernoulli Number +// Using FutureBasic 7.0.35 +// +// September 2025, R.W +// + +include "gmp.incl" + +_kMaxN = 200 // max Bernoulli terms + +mpq_t tmp +dim a( _kMaxN ) as mpq_t // workspace a(0.._kMaxN) + +// Bernoulli: +// B_m = -(1 / (m+1)) * sum_{k=0..m-1} binomial(m+1, k) * B_k + +local fn Bernoulli( rop as mpq_t, n as long ) + long m, j + if n < 0 then n = 0 + if n > _kMaxN then n = _kMaxN + for m = 1 to n + 1 + mpq_set_si( a(m-1), 1, m ) + // j = m-1..1 + for j = m - 1 to 1 step -1 + // a[j] = a[j+1] - a[j] with 0-based mapping + mpq_sub( a(j-1), a(j), a(j-1) ) + // multiply by j + mpq_set_si( tmp, j, 1 ) + mpq_mul( a(j-1), a(j-1), tmp ) + next + next + mpq_set( rop, a(0) ) +end fn + + +//-------------- Main --------- + +Window 1, @"Bernoulli Numbers",(0,0,500,500) + +CFStringRef cfnum, cfden, pLine, filler,sp,sp2 +Int terms +long i + +terms = 60 + +mpq_init( tmp ) +for i = 0 to terms + mpq_init( a(i) ) +next +filler = @" " +mpq_t rop +mpz_t num, den + +mpq_init( rop ) +mpz_init( num ) +mpz_init( den ) +pLine = @"" +for i = 0 to 60 step 2 + if i = 2 then i-- + if i = 3 then i-- + fn Bernoulli( rop, i ) + mpq_get_num( num, rop ) + if i == 1 + mpz_neg( num, num ) + end if + if fn mpz_cmp_si( num, 0 ) // nonzero? + mpq_get_den( den, rop ) + cfnum = fn mpz_cf(10, num) + cfden = fn mpz_cf(10, den) + if i < 10 + sp = @" " + else + sp = @"" + end if + sp2 = left(filler,44 - len(cfnum)) + pLine = concat(sp, @"B(",mid(str(i),1),@") = ",sp2 ,cfnum, @" / ", cfden) + print@ pLine + end if +next + +// clean up +for i = 0 to terms + mpq_clear( a(i) ) +next +mpq_clear( tmp ) +mpz_clear( den ) +mpz_clear( num ) +mpq_clear( rop ) + +HandleEvents + +// diff --git a/Task/Bernoulli-numbers/Isabelle/bernoulli-numbers-1.isabelle b/Task/Bernoulli-numbers/Isabelle/bernoulli-numbers-1.isabelle new file mode 100644 index 0000000000..485cee8d92 --- /dev/null +++ b/Task/Bernoulli-numbers/Isabelle/bernoulli-numbers-1.isabelle @@ -0,0 +1,373 @@ +theory Mini_Bernoulli +imports Complex_Main + "HOL-Computational_Algebra.Computational_Algebra" + "HOL-Combinatorics.Stirling" + "HOL-Library.Stream" + "Coinductive.Coinductive_List" + "HOL-Library.Code_Target_Numeral" + "HOL-Library.Code_Lazy" + +begin + +subsection ‹Definition of Bernoulli numbers› + +(* We define Bernoulli numbers in the standard fashion as those numbers B_n whose exponential + generating function function is X / (1 - e^(-X)): *) + +definition bernoulli_fps :: "rat fps" + where "bernoulli_fps = fps_X / (1 - fps_exp (-1))" + +definition bernoulli :: "nat ⇒ rat" where + "bernoulli n = fps_nth bernoulli_fps n * fact n" + + +subsection ‹Stirling numbers of the 2nd kind› + +(* We use the Stirling numbers from the Isabelle library and prove a few additional things + about them. *) + +lemma Stirling_n_0: "Stirling n 0 = (if n = 0 then 1 else 0)" + by (cases n) simp_all + +lemma sum_Stirling_binomial: + "Stirling (Suc n) (Suc m) = (∑i=0..n. Stirling i m * (n choose i))" +proof - + have "real (Stirling (Suc n) (Suc m)) = real (∑i = 0..n. Stirling i m * (n choose i))" + proof (induction n arbitrary: m) + case (Suc n m) + have "real (∑i = 0..Suc n. Stirling i m * (Suc n choose i)) = + real (∑i = 0..n. Stirling (Suc i) m * (Suc n choose Suc i)) + real (Stirling 0 m)" + by (subst sum.atLeast0_atMost_Suc_shift) simp_all + also have "real (∑i = 0..n. Stirling (Suc i) m * (Suc n choose Suc i)) = + real (∑i = 0..n. (n choose i) * Stirling (Suc i) m) + + real (∑i = 0..n. (n choose Suc i) * Stirling (Suc i) m)" + by (simp add: algebra_simps sum.distrib) + also have "(∑i = 0..n. (n choose Suc i) * Stirling (Suc i) m) = + (∑i = Suc 0..Suc n. (n choose i) * Stirling i m)" + by (subst sum.shift_bounds_cl_Suc_ivl) simp_all + also have "… = (∑i = Suc 0..n. (n choose i) * Stirling i m)" + by (intro sum.mono_neutral_right) auto + also have "… = real (∑i = 0..n. Stirling i m * (n choose i)) - real (Stirling 0 m)" + by (simp add: sum.atLeast_Suc_atMost mult_ac) + also have "real (∑i = 0..n. Stirling i m * (n choose i)) = real (Stirling (Suc n) (Suc m))" + by (rule Suc.IH [symmetric]) + also have "real (∑i = 0..n. (n choose i) * Stirling (Suc i) m) = + real m * real (Stirling (Suc n) (Suc m)) + real (Stirling (Suc n) m)" + by (cases m; (simp only: Suc.IH, simp add: algebra_simps sum.distrib + sum_distrib_left sum_distrib_right)) + also have "… + (real (Stirling (Suc n) (Suc m)) - real (Stirling 0 m)) + real (Stirling 0 m) = + real (Suc m * Stirling (Suc n) (Suc m) + Stirling (Suc n) m)" + by (simp add: algebra_simps del: Stirling.simps) + also have "Suc m * Stirling (Suc n) (Suc m) + Stirling (Suc n) m = + Stirling (Suc (Suc n)) (Suc m)" + by (rule Stirling.simps(4) [symmetric]) + finally show ?case .. + qed simp_all + thus ?thesis by (subst (asm) of_nat_eq_iff) +qed + +(* The exponential generating function of the Stirling numbers (of the 2nd kind) with + fixed second argument $m$ is S_m(X) = (e^X - 1)^m / m!. + We use this fact to derive a closed form for them. *) +lemma Stirling_fps_aux: + "(fps_exp 1 - 1) ^ m $ n * fact n = (fact m * of_nat (Stirling n m) :: 'a :: field_char_0)" +proof (induction m arbitrary: n) + case 0 + thus ?case by (simp add: Stirling_n_0) +next + case (Suc m n) + show ?case + proof (cases n) + case 0 + thus ?thesis by simp + next + case (Suc n') + hence "(fps_exp 1 - 1 :: 'a fps) ^ Suc m $ n * fact n = + fps_deriv ((fps_exp 1 - 1) ^ Suc m) $ n' * fact n'" + by (simp_all add: algebra_simps del: power_Suc) + also have "fps_deriv ((fps_exp 1 - 1 :: 'a fps) ^ Suc m) = + fps_const (of_nat (Suc m)) * ((fps_exp 1 - 1) ^ m * fps_exp 1)" + by (subst fps_deriv_power) simp_all + also have "… $ n' * fact n' = + of_nat (Suc m) * ((∑i = 0..n'. (fps_exp 1 - 1) ^ m $ i / fact (n' - i)) * fact n')" + unfolding fps_mult_left_const_nth + by (simp add: fps_mult_nth Suc.IH sum_distrib_right del: of_nat_Suc) + also have "(∑i = 0..n'. (fps_exp 1 - 1 :: 'a fps) ^ m $ i / fact (n' - i)) * fact n' = + (∑i = 0..n'. (fps_exp 1 - 1) ^ m $ i * fact n' / fact (n' - i))" + by (subst sum_distrib_right, rule sum.cong) (simp_all add: divide_simps) + also have "… = (∑i = 0..n'. (fps_exp 1 - 1) ^ m $ i * fact i * of_nat (n' choose i))" + by (intro sum.cong refl) (simp_all add: binomial_fact) + also have "… = (∑i = 0..n'. fact m * of_nat (Stirling i m) * of_nat (n' choose i))" + by (simp only: Suc.IH) + also have "of_nat (Suc m) * … = (fact (Suc m) :: 'a) * + (∑i = 0..n'. of_nat (Stirling i m) * of_nat (n' choose i))" (is "_ = _ * ?S") + by (simp add: sum_distrib_left sum_distrib_right mult_ac del: of_nat_Suc) + also have "?S = of_nat (Stirling (Suc n') (Suc m))" + by (subst sum_Stirling_binomial) simp + also have "Suc n' = n" by (simp add: Suc) + finally show ?thesis . + qed +qed + +theorem Stirling_closed_form: + "(of_nat (Stirling n k) :: 'a :: field_char_0) = + (∑j≤k. (-1)^(k - j) * of_nat (k choose j) * of_nat j ^ n) / fact k" +proof - + have "(fps_exp 1 - 1 :: 'a fps) = (fps_exp 1 + (-1))" by simp + also have "… ^ k = (∑j≤k. of_nat (k choose j) * fps_exp 1 ^ j * (- 1) ^ (k - j))" + unfolding binomial_ring .. + also have "… = (∑j≤k. fps_const ((-1) ^ (k - j) * of_nat (k choose j)) * fps_exp (of_nat j))" + by (simp add: fps_const_mult [symmetric] fps_const_power [symmetric] + fps_const_neg [symmetric] mult_ac fps_of_nat fps_exp_power_mult + del: fps_const_mult fps_const_power fps_const_neg) + also have "fps_nth … n = (∑j≤k. (- 1) ^ (k - j) * of_nat (k choose j) * of_nat j ^ n) / fact n" + by (simp add: fps_sum_nth sum_divide_distrib) + also have "… * fact n = (∑j≤k. (- 1) ^ (k - j) * of_nat (k choose j) * of_nat j ^ n)" + by simp + also note Stirling_fps_aux[of k n] + finally show ?thesis by (simp add: atLeast0AtMost field_simps) +qed + + +(* + We now define a somewhat ad-hoc operator formal power series: XD' maps a formal power + series A(X) to the series (X - 1) A'(X). + + The relevance of this operator to us is that the n-fold iteration of this operator + is related to Stirling numbers. +*) +definition fps_XD' :: "'a :: field_char_0 fps ⇒ 'a fps" + where "fps_XD' = (λb. (fps_X - 1) * fps_deriv b)" + +lemma fps_XD'_0 [simp]: "fps_XD' 0 = 0" + and fps_XD'_1 [simp]: "fps_XD' 1 = 0" + and fps_XD'_add [simp]: "fps_XD' (b + c) = fps_XD' b + fps_XD' c" + and fps_XD'_mult: "fps_XD' (b * c) = fps_XD' b * c + b * fps_XD' c" + by (simp_all add: fps_XD'_def algebra_simps) + +lemma fps_XD'_power: "fps_XD' (b ^ n) = of_nat n * b ^ (n - 1) * fps_XD' b" + by (induction n) (simp_all add: algebra_simps fps_XD'_mult power_eq_if) + +lemma fps_XD'_sum: "fps_XD' (sum f A) = sum (λx. fps_XD' (f x)) A" + by (induction A rule: infinite_finite_induct) simp_all + +lemma fps_XD'_funpow: + defines "S ≡ λn i. fps_const (of_nat (Stirling n i))" + shows "(fps_XD' ^^ n) H = (∑m≤n. S n m * (fps_X - 1) ^ m * (fps_deriv ^^ m) H)" +proof (induction n arbitrary: H) + case 0 + thus ?case by (simp add: S_def) +next + case (Suc n H) + define G where "G = (fps_X - 1 :: 'a fps)" + have "(∑m≤Suc n. S (Suc n) m * G ^ m * (fps_deriv ^^ m) H) = + (∑i≤n. of_nat (Suc i) * S n (Suc i) * G ^ Suc i * (fps_deriv ^^ Suc i) H) + + (∑i≤n. S n i * G ^ Suc i * (fps_deriv ^^ Suc i) H)" + (is "_ = sum (λi. ?f (Suc i)) … + ?S2") + by (subst sum.atMost_Suc_shift) (simp_all add: sum.distrib algebra_simps fps_of_nat S_def + fps_const_add [symmetric] fps_const_mult [symmetric] del: fps_const_add fps_const_mult) + also have "sum (λi. ?f (Suc i)) {..n} = sum (λi. ?f (Suc i)) {..= 1; j--) { + A[j - 1] = A[j - 1].subtract(A[j]).multiply(new Fraction(j)); + } + } + return A[0]; +} + +// Main execution +const ZERO = new Fraction(0); +for (let n = 0; n <= 60; n++) { + const b = bernoulli(n); + if (!b.equals(ZERO)) { + console.log(`B(${n.toString().padEnd(2)}) = ${b}`); + } +} diff --git a/Task/Bernoulli-numbers/Julia/bernoulli-numbers.julia b/Task/Bernoulli-numbers/Julia/bernoulli-numbers.jl similarity index 100% rename from Task/Bernoulli-numbers/Julia/bernoulli-numbers.julia rename to Task/Bernoulli-numbers/Julia/bernoulli-numbers.jl diff --git a/Task/Bernoulli-numbers/Kotlin/bernoulli-numbers.kotlin b/Task/Bernoulli-numbers/Kotlin/bernoulli-numbers.kts similarity index 100% rename from Task/Bernoulli-numbers/Kotlin/bernoulli-numbers.kotlin rename to Task/Bernoulli-numbers/Kotlin/bernoulli-numbers.kts diff --git a/Task/Bernoulli-numbers/M2000-Interpreter/bernoulli-numbers.m2000 b/Task/Bernoulli-numbers/M2000-Interpreter/bernoulli-numbers.m2000 new file mode 100644 index 0000000000..8f39e733c1 --- /dev/null +++ b/Task/Bernoulli-numbers/M2000-Interpreter/bernoulli-numbers.m2000 @@ -0,0 +1,96 @@ +module Bernoulli_Numbers { + Class Rational { + numerator as decimal, denominator as decimal + gcd=lambda->0 + lcm=lambda->0 + operator "+" { + Read l + denom=.lcm(l.denominator, .denominator) + .numerator<=denom/l.denominator*l.numerator+denom/.denominator*.numerator + if .numerator==0 then denom=1 + .denominator<=denom + } + Operator Unary { + .numerator-! + } + Operator "-" { + Read l + Call Operator "+", -l + } + Group Real { + value { + link parent numerator, denominator to n, d + =n/d + } + } + Group ToString$ { + value { + link parent numerator, denominator to n, d + =Str$(n)+"/"+Str$(d,"") + } + } + class: + Module Rational (.numerator, .denominator) { + if .denominator=0 then .denominator<=1 + while frac(.numerator)<>0 { + .numerator*=10@ + .denominator*=10@ + } + sgn=Sgn(.numerator)*Sgn(.denominator) + .denominator<=abs(.denominator) + .numerator<=abs(.numerator)*sgn + gcd1=lambda (a as decimal, b as decimal) -> { + if a0 then + .denominator/=gdcval + .numerator/=gdcval + end if + .gcd<=gcd1 + .lcm<=lambda gcd=gcd1 (a as decimal, b as decimal) -> { + =a/gcd(a,b)*b + } + } + } + Open "out.txt" for output as #f + r1=Rational(1,1) + b=0 + nextBern() + b=1 + nextBern() + for b=2 to 28 step 2 + nextBern() + next + close #f + + sub nextBern() + local m=@bernoulli(b) + Print #F, format$("B({0::-2})={1}",b, m.tostring$) + end sub + function bernoulli(n as decimal) + Local a(1 to n+1)=Rational(1,1), z + local decimal m, j + for m=0 to n + a(m + 1) = Rational(1 , m + 1) + if m<1 then continue + for j = m to 1 + z= a(J) - a(j+1) + r1 + a(j)=z + nn=z.gcd(j, z.denominator) + a(j).numerator*=j/nn + a(j).denominator/=nn + next + for a(1) { + this=rational(.numerator, .denominator) + } + next + =a(1) + end function +} +Bernoulli_Numbers diff --git a/Task/Bernoulli-numbers/Pluto/bernoulli-numbers.pluto b/Task/Bernoulli-numbers/Pluto/bernoulli-numbers.pluto new file mode 100644 index 0000000000..2a23069296 --- /dev/null +++ b/Task/Bernoulli-numbers/Pluto/bernoulli-numbers.pluto @@ -0,0 +1,22 @@ +require "bignum" +local fmt = require "fmt" + +local function bernoulli(n) + assert(n >= 0, "Argument must be non-negative") + local a = table.create(n + 1) + for m = 0, n do + a[m + 1] = bigrat.recip(m + 1) + local j = m + while j >= 1 do + a[j] = (a[j] - a[j + 1]) * bigrat.int(j) + j -= 1 + end + end + return n != 1 ? a[1] : -a[1] --'first' Bernoulli number +end + +local zero = bigrat.int(0) +for n = 0, 60 do + local b = bernoulli(n) + if b != zero then fmt.print("B(%2d) = %44s / %s", n, b:getNum(), b:getDen()) end +end diff --git a/Task/Bernoulli-numbers/R/bernoulli-numbers.r b/Task/Bernoulli-numbers/R/bernoulli-numbers.r index e6c84acce2..71e908ffcf 100644 --- a/Task/Bernoulli-numbers/R/bernoulli-numbers.r +++ b/Task/Bernoulli-numbers/R/bernoulli-numbers.r @@ -1,8 +1,6 @@ -library(pracma) +library(gmp) -for (idx in c(1,2*0:30)) { - b <- bernoulli(idx) - d <- as.character(denominator(b)) - n <- as.character(numerator(b)) - cat("B(",idx,") = ",n,"/",d,"\n", sep = "") -} +indices <- c(0,1,2*(1:30)) +bnums <- sapply(indices, BernoulliQ) +names(bnums) <- paste0("B(", indices, ")") +print(bnums, initLine=FALSE) diff --git a/Task/Bernoulli-numbers/REXX/bernoulli-numbers.rexx b/Task/Bernoulli-numbers/REXX/bernoulli-numbers.rexx index a1673236bf..0fa77e3ed1 100644 --- a/Task/Bernoulli-numbers/REXX/bernoulli-numbers.rexx +++ b/Task/Bernoulli-numbers/REXX/bernoulli-numbers.rexx @@ -1,55 +1,125 @@ -/*REXX program calculates N number of Bernoulli numbers expressed as vulgar fractions.*/ -parse arg N .; if N=='' | N=="," then N= 60 /*Not specified? Then use the default.*/ -numeric digits max(9, n*2) /*increase the decimal digits if needed*/ -w= max(length(N), 4); Nw= N + w + N % 4 /*used for aligning (output) fractions.*/ -say 'B(n)' center("Bernoulli numbers expressed as vulgar fractions", max(78-w, Nw) ) -say copies('─',w) copies("─", max(78-w,Nw+2*w)) /*display 2nd line of title, separators*/ -!.= .; do #=0 to N /*process the numbers from 0 ──► N. */ - b= bern(#); if b==0 then iterate /*calculate Bernoulli number, skip if 0*/ - indent= max(0, nW - pos('/', b) ) /*calculate the alignment (indentation)*/ - say right(#, w) left('', indent) b /*display the indented Bernoulli number*/ - end /*#*/ /* [↑] align the Bernoulli fractions. */ -exit 0 /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -bern: parse arg x; if x==0 then return '1/1' /*handle the special case of zero. */ - if x==1 then return '-1/2' /* " " " " " one. */ - if x//2 then return 0 /* " " " " " odds > 1.*/ - do j=2 to x by 2; jp= j+1 /*process the positive integers up to X*/ - sn= 1 - j /*define the numerator. */ - sd= 2 /* " " denominator. */ - do k=2 to j-1 by 2 /*calculate a SN/SD sequence. */ - parse var @.k bn '/' ad /*get a previously calculated fraction.*/ - an= comb(jp, k) * bn /*use COMBination for the next term. */ - $lcm= LCM(sd, ad) /*use Least Common Denominator function*/ - sn= $lcm % sd * sn; sd= $lcm /*calculate the current numerator. */ - an= $lcm % ad * an /* " " next " */ - sn= sn + an /* " " current " */ - end /*k*/ /* [↑] calculate the SN/SD sequence.*/ - sn= -sn /*flip the sign for the numerator. */ - sd= sd * jp /*calculate the denominator. */ - if sn\==1 then do; _= GCD(sn, sd) /*get the Greatest Common Denominator.*/ - sn= sn%_; sd= sd%_ /*reduce the numerator and denominator.*/ - end /* [↑] done with the reduction(s). */ - @.j= sn'/'sd /*save the result for the next round. */ - end /*j*/ /* [↑] done calculating Bernoulli #'s.*/ - return sn'/'sd -/*──────────────────────────────────────────────────────────────────────────────────────*/ -comb: procedure expose !.; parse arg x,y; if x==y then return 1 - if !.C.x.y\==. then return !.C.x.y /*combination computed before?*/ - if x-y < y then y= x-y /*x-y < y? Then use a new Y.*/ - z= perm(x, y); do j=2 for y-1; z= z % j - end /*j*/ - !.C.x.y= z; return z /*assign memoization & return.*/ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -GCD: procedure; parse arg x,y; x= abs(x) - do until y==0; parse value x//y y with y x; end; return x -/*──────────────────────────────────────────────────────────────────────────────────────*/ -LCM: procedure; parse arg x,y /*X=ABS(X); Y=ABS(Y) not needed for Bernoulli #s.*/ - /*IF Y==0 THEN RETURN 0 " " " " " */ - $= x * y /*calculate part of the LCM here. */ - do until y==0; parse value x//y y with y x - end /*until*/ /* [↑] this is a short & fast GCD*/ - return $ % x /*divide the pre─calculated value.*/ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -perm: procedure expose !.; parse arg x,y; if !.P.x.y\==. then return !.P.x.y - z= 1; do j=x-y+1 to x; z= z*j; end; !.P.x.y= z; return z +-- 23 Aug 2025 +include Setting +numeric digits 16 +arg xx +if xx = '' then + xx=60 +ss=(xx>0); xx=Abs(xx) + +say 'BERNOULLI NUMBERS' +say version +say + +call Rational1 xx +if ss then + call ShowFractions xx +call Timer 'R' + +call Rational2 xx +if ss then + call ShowFractions xx +call Timer 'R' + +call Decimal1 xx +if ss then + call ShowDecimals xx +call Timer 'R' + +call Decimal2 xx +if ss then + call ShowDecimals xx +call Timer 'R' +exit + +Rational1: +procedure expose Memo. Bern. +arg xx +say 'Rational arithmetic' +say 'cf Generating function' +numeric digits Max(Digits(),3*xx) +Bern.=0; Bern.0='1 1'; Bern.1='-1 2' +do n = 2 by 2 to xx + s=0 + do k = 0 to n-1 + s=Addq(s,Scaleq(Bern.k,Comb(n+1,k))) + end k + Bern.n=Mulq(Negq(s),Invq(n+1)) +end n +return + +Rational2: +procedure expose Memo. Bern. +arg xx +say 'Numerator and denominator calculations' +say 'cf Double sum formula optimized' +numeric digits Max(Digits(),3*xx) +Bern.=0; Bern.0='1 1'; Bern.1='-1 2' +do j = 2 by 2 to xx + jp=j+1; sn=1-j; sd=2 + do k = 2 by 2 to j-1 + bn=bn.k; ad=ad.k; an=Comb(jp,k)*bn; tl=Lcm(sd,ad) + sn=tl%sd*sn; sd=tl; an=tl%ad*an; sn=sn+an + end k + sn=-sn; sd=sd*jp; bn.j=sn; ad.j=sd; g=Gcd(Abs(sn),sd) + Bern.j=sn/g sd/g +end j +return + +ShowFractions: +procedure expose Bern. +arg xx +w=Length(Word(Bern.xx,1))+2 +say ' Bn' Right('Num',w) '/' Left('Den',10) 'Decimal' +do i = 0 to xx + if Bern.i <> 0 then do + parse var Bern.i num den + say Right(i,3) Right(num,w) '/' Left(den,10) Digit(num/den,16) + end +end i +return + +Decimal1: +procedure expose Bern. Memo. +arg xx +say 'Floating point calculations' +say 'cf Generating function' +numeric digits Max(Digits(),2*xx) +Bern.=0; Bern.0=1; Bern.1='-0.5' +do n = 2 by 2 to xx + s=0 + do k = 0 to n-1 + s=s+Bern.k*Comb(n+1,k) + end k + Bern.n=-s/(n+1) +end n +return xx + +Decimal2: +procedure expose Bern. Memo. +arg xx +say 'Floating point calculations' +say 'cf Akiyama-Tanigawa' +numeric digits Max(Digits(),3*xx) +Bern.=0; Bern.0=1; Bern.1=-0.5 +do i = 2 by 2 to xx + do m = 0 to i + a.m=1/(m+1) + do j = m by -1 to 1 + j1=j-1; a.j1=j*(a.j1-a.j) + end + end m + Bern.i=a.0 +end i +return xx + +ShowDecimals: +procedure expose Bern. +arg xx +say ' Bn' 'Decimal' +do i = 0 to xx + if Bern.i <> 0 then + say Right(i,3) Digit(Bern.i,16) +end i +return + +include Math diff --git a/Task/Bernoulli-numbers/Rust/bernoulli-numbers.rust b/Task/Bernoulli-numbers/Rust/bernoulli-numbers.rs similarity index 100% rename from Task/Bernoulli-numbers/Rust/bernoulli-numbers.rust rename to Task/Bernoulli-numbers/Rust/bernoulli-numbers.rs diff --git a/Task/Bernoulli-numbers/Scheme/bernoulli-numbers.ss b/Task/Bernoulli-numbers/Scheme/bernoulli-numbers.scm similarity index 100% rename from Task/Bernoulli-numbers/Scheme/bernoulli-numbers.ss rename to Task/Bernoulli-numbers/Scheme/bernoulli-numbers.scm diff --git a/Task/Bernoulli-numbers/TAV/bernoulli-numbers-1.tav b/Task/Bernoulli-numbers/TAV/bernoulli-numbers-1.tav new file mode 100644 index 0000000000..b24fd56d97 --- /dev/null +++ b/Task/Bernoulli-numbers/TAV/bernoulli-numbers-1.tav @@ -0,0 +1,14 @@ +bernoulli (n): + a =: new row + for m =: from 0 upto n + a[m] =: 1 / (m + 1) + for j =: from m downto 1 + a[j-1] =: j * (a[j-1] - a[j]) + return a[0] + +main (p):+ + max =: string p.1 as integer else 60 \ max number as parameter + for i =: from 2 upto max step 2 + b =: bernoulli i + \ to align the slash, print numerator and denominator separately + print format "B(%2;) = %50; / %;" i, b.num, b.den diff --git a/Task/Bernoulli-numbers/TAV/bernoulli-numbers-2.tav b/Task/Bernoulli-numbers/TAV/bernoulli-numbers-2.tav new file mode 100644 index 0000000000..67e1634b4b --- /dev/null +++ b/Task/Bernoulli-numbers/TAV/bernoulli-numbers-2.tav @@ -0,0 +1,22 @@ +main (parms):+ + n =: string parms[1] as integer else 30 + print n bernoullis + +\ ierative version as used by Ada Lovelace +print (max) bernoullis: + b =: [] + b[1] =: 1/6 + print 'B[1]=' _ b[1] + ?# n =: from 2 upto max + k =: 2*n - 1 + n2 =: 2*n + a0 =: - (n2 - 1) / (n2 + 1) / 2 + a1 =: n2 / 2 + x =: a0 + (b[1] * a1) + aj =: a1 + ?# j =: from 3 upto k-1 step 2 + aj =* (n2 - (j-2)) / j + aj =* (n2 - (j-1)) / (j + 1) + x =+ b[j] * aj + b[k] =: -x + print format "B(%2;) = %50; / %;" k, b[k].num, b[k].den diff --git a/Task/Best-shuffle/Ada/best-shuffle.ada b/Task/Best-shuffle/Ada/best-shuffle.adb similarity index 100% rename from Task/Best-shuffle/Ada/best-shuffle.ada rename to Task/Best-shuffle/Ada/best-shuffle.adb diff --git a/Task/Best-shuffle/Crystal/best-shuffle.crystal b/Task/Best-shuffle/Crystal/best-shuffle.cr similarity index 100% rename from Task/Best-shuffle/Crystal/best-shuffle.crystal rename to Task/Best-shuffle/Crystal/best-shuffle.cr diff --git a/Task/Best-shuffle/Delphi/best-shuffle.delphi b/Task/Best-shuffle/Delphi/best-shuffle.pas similarity index 100% rename from Task/Best-shuffle/Delphi/best-shuffle.delphi rename to Task/Best-shuffle/Delphi/best-shuffle.pas diff --git a/Task/Best-shuffle/EasyLang/best-shuffle.easy b/Task/Best-shuffle/EasyLang/best-shuffle.easy index ef0e2ef7bf..4f6a5e338f 100644 --- a/Task/Best-shuffle/EasyLang/best-shuffle.easy +++ b/Task/Best-shuffle/EasyLang/best-shuffle.easy @@ -1,4 +1,4 @@ -proc best_shuffle s$ . r$ diff . +proc best_shuffle s$ &r$ &diff . l = len s$ for c$ in strchars s$ s[] &= strcode c$ diff --git a/Task/Best-shuffle/Elena/best-shuffle.elena b/Task/Best-shuffle/Elena/best-shuffle.elena index 99e99cba05..19abfc3e25 100644 --- a/Task/Best-shuffle/Elena/best-shuffle.elena +++ b/Task/Best-shuffle/Elena/best-shuffle.elena @@ -35,14 +35,14 @@ extension op } } -public program() +public Program() { 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/Best-shuffle/Factor/best-shuffle.factor b/Task/Best-shuffle/Factor/best-shuffle.factor new file mode 100644 index 0000000000..ac380801c1 --- /dev/null +++ b/Task/Best-shuffle/Factor/best-shuffle.factor @@ -0,0 +1,26 @@ +USING: arrays combinators.short-circuit formatting kernel random +sequences sequences.extras ; + +:: best-shuffle ( str -- str' ) + str clone :> new-str + str length :> n + n >array randomize :> range1 + n >array randomize :> range2 + + range1 [| i | + range2 [| j | + { + [ i j = ] + [ i new-str nth j new-str nth = ] + [ i str nth j new-str nth = ] + [ i new-str nth j str nth = ] + } 0|| [ + i j new-str exchange + ] unless + ] each + ] each + + new-str ; + +: best-shuffle. ( str -- ) + dup best-shuffle 2dup [ = ] 2count "%s, %s, (%d)\n" printf ; diff --git a/Task/Best-shuffle/Fortran/best-shuffle.f b/Task/Best-shuffle/Fortran/best-shuffle.f new file mode 100644 index 0000000000..8a02f8f4a4 --- /dev/null +++ b/Task/Best-shuffle/Fortran/best-shuffle.f @@ -0,0 +1,110 @@ +! +! Best Shuffle +! tested with Intel ifx (IFX) 2025.2.1 20250806 on Kubuntu 25.10 +! GNU Fortran (Ubuntu 15.2.0-4ubuntu4) 15.2.0 on Kubuntu 25.10 +! +! VSI Fortran on VMS does not compile this code because its current version +! cannot handle allocatable character strings +! +! U.B., October 2025 +!============================================================================== + +program bestShuffle + + implicit none + + integer, parameter :: MAXLEN = 100 ! Maximum length of strings to shuffle + character (len=MAXLEN), dimension(:),allocatable :: wordsToShuffle ! Test cases as in task description + character (len=MAXLEN) shuffledWord ! Result of a shuffle operation + integer :: ii, nWords, scr ! little helpers + integer:: longest ! Length of longest test string + character (len=50) :: vFormat ! Variable format for printing + + wordsToShuffle = & ! Preset test cases + [character(len=MAXLEN) :: 'abcdefghijk', & ! all letters different -> always score 0 + 'abracadabra', & ! The other test cases from task description + 'seesaw', & + 'elk', & + 'grrrrrrr', & + 'up', & + 'a'] ! This style makes both ifx AND gfortran happy. + nWords = size (wordsToShuffle) ! Number of test cases + longest = 0 + do ii=1, nWords ! Find length of longest test string + longest = max (longest, len_trim(wordsToShuffle(ii))) + end do + + ! Create a variable format depending on the length of the longest test string, + ! to print the original string, the shuffled string and the score in three columns + write (vFormat,'("(A", i0, ", x, A, T", i0,", i0)" )') longest, 2*longest+3 + + ! Initialize random number generator once for the entire run-time of the program and all test cases + call random_seed() + + do ii = 1, nWords + ! Using the Sattolo cycle guarantees that each and every letter will be moved from its original + ! position. However, duplicate letters within a word can lead to shuffled words that have a score >0 + ! If all letters aof the string are different, score will be 0 each time this program is run. + call sattolo_cycle (wordsToShuffle(ii), shuffledWord, scr) + print vFormat, trim(wordsToShuffle(ii)), trim(shuffledWord), scr + end do + + contains + + !============================================================= + ! shuffle using the Sattolo algorithm, and calculate the score + ! @win: word to shuffle, @wout: resultant string + ! @resultantscore: with the obvious meaning + !============================================================= + subroutine sattolo_cycle (win, wout, resultantscore) + + character (len=MAXLEN) , intent (in) :: win ! The word to shuffle + character (len=MAXLEN) , intent (out) :: wout ! The resultant word after shuffling + character :: tmp ! for swapping single letters + integer, intent(out) :: resultantscore ! the calculated score of the resultant string + + integer :: j, k, l ! Helper variables: indices into words, words' length + + wout = win + l = len_trim (wout) + do j = l, 1, -1 ! For all letters from end down to begin + k = randominInterval (1, j-1) ! Select random letters between 1 and j-1 + tmp = wout(j:j) ! then swap letter at pos j with letter at pos k + wout (j:j) = wout (k:k) + wout(k:k) = tmp + end do + + resultantscore = score (win,wout,l) ! Calculate score + end subroutine sattolo_cycle + + + ! =========================================================== + ! Generate random number between @lo and @hi (inclusive) + ! Assume Random Number Generator has been initialized before. + ! =========================================================== + function randominInterval (lo, hi) result (r) + integer, intent(in) :: lo, hi ! the interval + integer :: r ! resultant (pseudo-)random number + real :: rnd ! Fortran random number generator generates float values + + call random_number (rnd) + r = lo + FLOOR((hi+1-lo)*rnd) ! We want to choose one between [lo,hi] + + end function randominInterval + + !=============================================================================== + ! Calculate score: count positions that have the same letter as before shuffling + !=============================================================================== + function score (win, wout, l) result (scr) + character (len=MAXLEN) , intent (in) :: win, wout ! The two words to compare + integer , intent(in) :: l ! Length of the words to consider + integer :: scr ! Resultant score + integer :: jj ! Loop index + + scr = 0 + do jj=1,l + if (win(jj:jj) .eq. wout(jj:jj) ) scr = scr + 1 + enddo + end function score + +end program bestShuffle diff --git a/Task/Best-shuffle/Julia/best-shuffle.julia b/Task/Best-shuffle/Julia/best-shuffle.jl similarity index 100% rename from Task/Best-shuffle/Julia/best-shuffle.julia rename to Task/Best-shuffle/Julia/best-shuffle.jl diff --git a/Task/Best-shuffle/Kotlin/best-shuffle.kotlin b/Task/Best-shuffle/Kotlin/best-shuffle.kts similarity index 100% rename from Task/Best-shuffle/Kotlin/best-shuffle.kotlin rename to Task/Best-shuffle/Kotlin/best-shuffle.kts diff --git a/Task/Best-shuffle/OCaml/best-shuffle.ocaml b/Task/Best-shuffle/OCaml/best-shuffle.ml similarity index 100% rename from Task/Best-shuffle/OCaml/best-shuffle.ocaml rename to Task/Best-shuffle/OCaml/best-shuffle.ml diff --git a/Task/Best-shuffle/Pluto/best-shuffle.pluto b/Task/Best-shuffle/Pluto/best-shuffle.pluto new file mode 100644 index 0000000000..1f4a50c9bd --- /dev/null +++ b/Task/Best-shuffle/Pluto/best-shuffle.pluto @@ -0,0 +1,17 @@ +require "table2" +local fmt = require "fmt" + +local tests = {"abracadabra", "seesaw", "elk", "grrrrrr", "up", "a"} +for tests as s do + local t = s:split(""):shuffle() + for i = 1, #t do + for j = 1, #t do + if i != j and t[i] != s[j] and t[j] != s[i] then + t[i], t[j] = t[j], t[i] + break + end + end + end + local c = range(1, #s):count(|i| -> s[i] == t[i]) + fmt.print("%s, %s, (%d)\n", s, t:concat(""), c) +end diff --git a/Task/Best-shuffle/PowerShell/best-shuffle-1.psh b/Task/Best-shuffle/PowerShell/best-shuffle-1.ps1 similarity index 100% rename from Task/Best-shuffle/PowerShell/best-shuffle-1.psh rename to Task/Best-shuffle/PowerShell/best-shuffle-1.ps1 diff --git a/Task/Best-shuffle/PowerShell/best-shuffle-2.psh b/Task/Best-shuffle/PowerShell/best-shuffle-2.ps1 similarity index 100% rename from Task/Best-shuffle/PowerShell/best-shuffle-2.psh rename to Task/Best-shuffle/PowerShell/best-shuffle-2.ps1 diff --git a/Task/Best-shuffle/Rust/best-shuffle.rust b/Task/Best-shuffle/Rust/best-shuffle.rs similarity index 100% rename from Task/Best-shuffle/Rust/best-shuffle.rust rename to Task/Best-shuffle/Rust/best-shuffle.rs diff --git a/Task/Best-shuffle/SETL/best-shuffle.setl b/Task/Best-shuffle/SETL/best-shuffle.setl new file mode 100644 index 0000000000..0071908659 --- /dev/null +++ b/Task/Best-shuffle/SETL/best-shuffle.setl @@ -0,0 +1,20 @@ +program find_best_shuffle; + tests := ["tree", "abracadabra", "seesaw", "elk", "grrrrrr", "up", "a"]; + loop for test in tests do + print(test, '->', sh := best_shuffle(test), same(test, sh)); + end loop; + + proc best_shuffle(s); + r := s; + loop for i in [1..#s] do + loop for j in [1..#s] | i /= j and s(i) /= r(j) and s(j) /= r(i) do + [r(i), r(j)] := [r(j), r(i)]; + end loop; + end loop; + return r; + end proc; + + proc same(r, s); + return 0 +/[1 : i in [1..#s] | r(i) = s(i)]; + end proc; +end program; diff --git a/Task/Best-shuffle/Scheme/best-shuffle.ss b/Task/Best-shuffle/Scheme/best-shuffle.scm similarity index 100% rename from Task/Best-shuffle/Scheme/best-shuffle.ss rename to Task/Best-shuffle/Scheme/best-shuffle.scm diff --git a/Task/Best-shuffle/V-(Vlang)/best-shuffle.v b/Task/Best-shuffle/V-(Vlang)/best-shuffle.v new file mode 100644 index 0000000000..082b173897 --- /dev/null +++ b/Task/Best-shuffle/V-(Vlang)/best-shuffle.v @@ -0,0 +1,30 @@ +fn best_shuffle(s1 string) string { + mut s2 := s1.clone() + len_s2 := s2.len + mut s2_bytes := s2.bytes() + s1_bytes := s1.bytes() + for i in 0 .. len_s2 { + for j in 0 .. len_s2 { + if i != j && s2_bytes[i] != s1_bytes[j] && s2_bytes[j] != s1_bytes[i] { + i1 := if j < i { j } else { i } + j1 := if j < i { i } else { j } + // swap characters at i1 and j1 in s2_bytes + s2_bytes[i1], s2_bytes[j1] = s2_bytes[j1], s2_bytes[i1] + } + } + } + return s2_bytes.bytestr() +} + +fn main() { + lista := ["abracadabra", "seesaw", "pop", "grrrrrr", "up", "a"] + mut puntos := 0 + for palabra in lista { + bs := best_shuffle(palabra) + puntos = 0 + for i := 0; i < palabra.len; i++ { + if palabra[i] == bs[i] { puntos++ } + } + println("$palabra ==> $bs (puntuación: $puntos)") + } +} diff --git a/Task/Best-shuffle/VBScript/best-shuffle.vb b/Task/Best-shuffle/VBScript/best-shuffle.vbs similarity index 100% rename from Task/Best-shuffle/VBScript/best-shuffle.vb rename to Task/Best-shuffle/VBScript/best-shuffle.vbs diff --git a/Task/Best-shuffle/YAMLScript/best-shuffle.ys b/Task/Best-shuffle/YAMLScript/best-shuffle.ys new file mode 100644 index 0000000000..40b2a8e761 --- /dev/null +++ b/Task/Best-shuffle/YAMLScript/best-shuffle.ys @@ -0,0 +1,45 @@ +!YS-v0 + +defn main(*inputs): + each input inputs: !:say + apply format '%s, %s, (%d)': + best-shuffle(input) + +defn best-shuffle(s): + ref =: s:group-indices:cycles + prm =: concat.apply(map(partial(rotate 1) ref)) + ref =: concat(ref*) + + map(vector ref prm): + .sort-by(first _) + .map(second) + .map(partial(get s)) + .str(*) + .call(\([s _ s.score(_)]) _) + +defn score(before after): + map(== before after) + .filter(true?).# + +defn group-indices(s): + map-indexed(vector s) + .merge-vecs({}):vals + .sort-by(count _):reverse + +defn cycles(coll): + n =: coll.0.# + cycle =: range(n):cycle + coll =: concat(coll*) + map(vector coll cycle): + .merge-vecs([]) + +defn rotate(n coll): + c =: coll.# + n =: (c + n) % c + concat coll.drop(n): coll.take(n) + +defn merge-vecs(vecs init): + reduce _ init vecs: + fn(counts [index x]): + assoc counts x: + counts.$x.or([]).conj(index) diff --git a/Task/Bifid-cipher/00-TASK.txt b/Task/Bifid-cipher/00-TASK.txt index 867d98b92f..178c9d6429 100644 --- a/Task/Bifid-cipher/00-TASK.txt +++ b/Task/Bifid-cipher/00-TASK.txt @@ -58,4 +58,3 @@ Suggest a way in which the cipher could be modified so that ALL 26 letters can b ;Related task [[Playfair_cipher|Playfair cipher]]

    - diff --git a/Task/Bifid-cipher/AArch64-Assembly/bifid-cipher.aarch64 b/Task/Bifid-cipher/AArch64-Assembly/bifid-cipher.aarch64 new file mode 100644 index 0000000000..37aa0bd8b0 --- /dev/null +++ b/Task/Bifid-cipher/AArch64-Assembly/bifid-cipher.aarch64 @@ -0,0 +1,394 @@ +/* ARM assembly AARCH64 Raspberry PI 3B */ +/* program bifid64.s */ + +/*******************************************/ +/* Constantes */ +/*******************************************/ +/* for this file see task include a file in language AArch64 assembly*/ +.include "../includeConstantesARM64.inc" + +.equ MESSSIZE, 2000 +.equ BUFFERSIZE, 2000 +/*******************************************/ +/* Macros */ +/*******************************************/ +//.include "../../ficmacros64.inc" // for developer debugging + + +/*******************************************/ +/* Initialized data */ +/*******************************************/ +.data +szMessDebutPgm: .asciz "Program 64 bits start. \n" +szCarriageReturn: .asciz "\n" +szMessFinOK: .asciz "Program normal end. \n" +szMessError: .asciz "\nError Buffer too small!!!\n" +szMessString: .asciz "String :\n" +szMessEncrip: .asciz "\nEncrypted :\n" +szMessDecrip: .asciz "\nDecrypted :\n" +//szString1: .asciz "ABCDEFGHIJKLMNOPQRSTUVWXYZ!.?abcdefghijklmnopqrstuvwxyz" +//szString1: .asciz "attackatdawn" +szString1: .asciz "ATTACKATDAWN" +//szString1: .asciz "ABCD" +szString2: .asciz "FLEEATONCE" +szString3: .asciz "The invasion will start on the first of January" + +szPolybe1: .ascii "ABCDE" + .ascii "FGHIK" + .ascii "LMNOP" + .ascii "QRSTU" + .asciz "VWXYZ" + +szPolybe2: .ascii "BGWKZ" + .ascii "QPNDS" + .ascii "IOAXE" + .ascii "FCLUM" + .asciz "THYVR" + +/*******************************************/ +/* UnInitialized data */ +/*******************************************/ +.bss +.align 4 +tabiposX: .skip 8 * MESSSIZE +tabiposY: .skip 8 * MESSSIZE +sBuffex1: .skip BUFFERSIZE +sBuffex2: .skip BUFFERSIZE +/*******************************************/ +/* code section */ +/*******************************************/ +.text +.global main +main: + ldr x0,qAdrszMessDebutPgm + bl affichageMess + ldr x0,qAdrszMessString // display message + bl affichageMess + ldr x0,qAdrszString1 // display string + bl affichageMess + ldr x0,qAdrszString1 // string address + ldr x1,qAdrszPolybe1 // Polybe key + ldr x2,qAdrsBuffex1 // encrypted buffer result + bl encrypt + cmp x0,#0 + ble 99f + ldr x0,qAdrszMessEncrip + bl affichageMess + ldr x0,qAdrsBuffex1 // display encrypted buffer + bl affichageMess + + + ldr x0,qAdrsBuffex1 // encrypted buffer + ldr x1,qAdrszPolybe1 // Polybe key + ldr x2,qAdrsBuffex2 // decrypted buffer + bl decrypt + ldr x0,qAdrszMessDecrip + bl affichageMess + ldr x0,qAdrsBuffex2 // display decrypted buffer + bl affichageMess + ldr x0,qAdrszCarriageReturn + bl affichageMess + + ldr x0,qAdrszMessString // display message + bl affichageMess + ldr x0,qAdrszString2 // display string + bl affichageMess + ldr x0,qAdrszString2 // string address + ldr x1,qAdrszPolybe2 // Polybe key + ldr x2,qAdrsBuffex1 // encrypted buffer result + bl encrypt + cmp x0,#0 + ble 99f + ldr x0,qAdrszMessEncrip + bl affichageMess + ldr x0,qAdrsBuffex1 // display encrypted buffer + bl affichageMess + + + ldr x0,qAdrsBuffex1 // encrypted buffer + ldr x1,qAdrszPolybe2 // Polybe key + ldr x2,qAdrsBuffex2 // decrypted buffer + bl decrypt + ldr x0,qAdrszMessDecrip + bl affichageMess + ldr x0,qAdrsBuffex2 // display decrypted buffer + bl affichageMess + ldr x0,qAdrszCarriageReturn + bl affichageMess + + ldr x0,qAdrszMessString // display message + bl affichageMess + ldr x0,qAdrszString1 // display string + bl affichageMess + ldr x0,qAdrszString1 // string address + ldr x1,qAdrszPolybe2 // Polybe key + ldr x2,qAdrsBuffex1 // encrypted buffer result + bl encrypt + cmp x0,#0 + ble 99f + ldr x0,qAdrszMessEncrip + bl affichageMess + ldr x0,qAdrsBuffex1 // display encrypted buffer + bl affichageMess + + + ldr x0,qAdrsBuffex1 // encrypted buffer + ldr x1,qAdrszPolybe2 // Polybe key + ldr x2,qAdrsBuffex2 // decrypted buffer + bl decrypt + ldr x0,qAdrszMessDecrip + bl affichageMess + ldr x0,qAdrsBuffex2 // display decrypted buffer + bl affichageMess + ldr x0,qAdrszCarriageReturn + bl affichageMess + + ldr x0,qAdrszMessString // display message + bl affichageMess + ldr x0,qAdrszString3 // display string + bl affichageMess + ldr x0,qAdrszString3 // string address + ldr x1,qAdrszPolybe1 // Polybe key + ldr x2,qAdrsBuffex1 // encrypted buffer result + bl encrypt + cmp x0,#0 + ble 99f + ldr x0,qAdrszMessEncrip + bl affichageMess + ldr x0,qAdrsBuffex1 // display encrypted buffer + bl affichageMess + + + ldr x0,qAdrsBuffex1 // encrypted buffer + ldr x1,qAdrszPolybe1 // Polybe key + ldr x2,qAdrsBuffex2 // decrypted buffer + bl decrypt + ldr x0,qAdrszMessDecrip + bl affichageMess + ldr x0,qAdrsBuffex2 // display decrypted buffer + bl affichageMess + ldr x0,qAdrszCarriageReturn + bl affichageMess + + ldr x0,qAdrszMessFinOK + bl affichageMess + b 100f +99: + ldr x0,qAdrszMessError // error + bl affichageMess + mov x0, #1 +100: // standard end of the program + mov x0, #0 // return code + mov x8,EXIT + svc 0 // perform system call +qAdrszMessString: .quad szMessString +qAdrszMessDecrip: .quad szMessDecrip +qAdrszMessEncrip: .quad szMessEncrip +qAdrszString1: .quad szString1 +qAdrszPolybe1: .quad szPolybe1 +qAdrszString2: .quad szString2 +qAdrszString3: .quad szString3 +qAdrszPolybe2: .quad szPolybe2 +qAdrsBuffex1: .quad sBuffex1 +qAdrsBuffex2: .quad sBuffex2 +qAdrszMessDebutPgm: .quad szMessDebutPgm +qAdrszMessFinOK: .quad szMessFinOK +qAdrszCarriageReturn: .quad szCarriageReturn +qAdrszMessError: .quad szMessError +/******************************************************************/ +/* encrypt strings */ +/******************************************************************/ +/* r0 contains the address of the string1 */ +/* r1 contains Polybe area address +/* r2 contains the address of the encrypted string */ +/* r0 return buffer lenght */ +encrypt: + stp x1,lr,[sp,-16]! // save registers + stp x2,x3,[sp,-16]! // + stp x4,x5,[sp,-16]! // + stp x6,x7,[sp,-16]! // + stp x8,x9,[sp,-16]! // + stp x10,x11,[sp,-16]! // + mov x3,#0 // counter byte string 1 + mov x5,#0 // counter byte buffer +1: + ldrb w7,[x0,x3] // load byte string 1 + cmp x7,#0 // zero final ? + beq 4f + cmp x7,#65 // < A ? + cinc x3,x3,lt + blt 1b + cmp x7,#90 // > Z + ble 2f + + cmp x7,#97 // < a ? + cinc x3,x3,lt + blt 1b + cmp x7,#122 //> z + cinc x3,x3,gt + bgt 1b + sub x7,x7,#32 // convert minuscul to majuscule +2: + mov x11,'I' + cmp x7,#'J' // change J to I + csel x7,x11,x7,eq + ldr x11,qAdrtabiposX + ldr x12,qAdrtabiposY + mov x6,#0 + mov x9,#5 +3: // loop to search char in polybe square + ldrb w8,[x1,x6] // load byte polybe + cmp x8,x7 // equal ? + cinc x6,x6,ne + bne 3b + udiv x10,x6,x9 // compute coordonnés + msub x8,x10,x9,x6 + strb w10,[x11,x5] // save X position + strb w8,[x12,x5] // save Y position + add x5,x5,#1 // increment indice + add x3,x3,#1 + b 1b // and loop + +4: + mov x6,#0 + mov x8,x5 + mov x5,#0 + mov x3,#5 +5: // convert position line 1 in char + ldrb w9,[x11,x6] + add x6,x6,#1 + cmp x6,x8 // first line end ? + csel x6,xzr,x6,ge + bge 7f // jmp for second line + + ldrb w7,[x11,x6] // compute rank with position X and Y + mul x9,x3,x9 + add x9,x9,x7 + ldrb w9,[x1,x9] // load polybe char + strb w9,[x2,x5] + add x5,x5,#1 + + add x6,x6,#1 + cmp x6,x8 + blt 5b + + mov x6,#0 +6: // convert position line 2 in char + ldrb w9,[x12,x6] + add x6,x6,#1 +7: + ldrb w7,[x12,x6] // compute rank with position X and Y + mul x9,x3,x9 + add x9,x9,x7 + ldrb w9,[x1,x9] // load polybe char + strb w9,[x2,x5] + add x5,x5,#1 + add x6,x6,#1 + cmp x6,x8 + blt 6b + + mov x9,#0 // zero final + strb w9,[x2,x5] + mov x0,x5 +100: + ldp x10,x11,[sp],16 // restau registers + ldp x8,x9,[sp],16 // + ldp x6,x7,[sp],16 // + ldp x4,x5,[sp],16 // + ldp x2,x3,[sp],16 // + ldp x1,lr,[sp],16 // + ret +qAdrtabiposX: .quad tabiposX +qAdrtabiposY: .quad tabiposY +/******************************************************************/ +/* decrypt strings */ +/******************************************************************/ +/* r0 contains the address of the encrypted string1 */ +/* r1 contains Polybe area address +/* r2 contains the address of the decrypted string */ +/* r0 return buffer lenght */ +decrypt: + stp x1,lr,[sp,-16]! // save registers + stp x2,x3,[sp,-16]! // + stp x4,x5,[sp,-16]! // + stp x6,x7,[sp,-16]! // + stp x8,x9,[sp,-16]! // + stp x10,x11,[sp,-16]! // + mov x3,#0 // counter byte string 1 + mov x5,#0 // counter byte result buffer +1: + ldrb w7,[x0,x3] // load byte string 1 + cmp x7,#0 // zero final ? + csel x0,x5,x0,eq + beq 4f + + cmp x7,#65 // < A ? + cinc x3,x3,lt + blt 1b + cmp x7,#90 // > Z + ble 2f + + cmp x7,#97 // < a ? + cinc x3,x3,lt + blt 1b + cmp x7,#122 //> z + cinc x3,x3,gt + bgt 1b + sub x7,x7,#32 // convert minuscul to majuscule +2: + ldr x11,qAdrtabiposX + mov x6,#0 + mov x9,#5 +3: // loop to search char in polybe square + ldrb w8,[x1,x6] // load byte polybe + cmp x8,x7 + cinc x6,x6,ne + bne 3b + + udiv x10,x6,x9 + msub x8,x10,x9,x6 + strb w10,[x11,x5] + add x5,x5,#1 + strb w8,[x11,x5] + add x5,x5,#1 + + add x3,x3,#1 + b 1b + +4: + mov x6,#0 // start indice first line + lsr x8,x5,#1 + mov x10,x8 // start indice second line + mov x5,#0 + mov x3,#5 + +5: + ldrb w9,[x11,x6] // load position + ldrb w7,[x11,x10] + mul x9,x3,x9 // compute rank + add x9,x9,x7 + ldrb w9,[x1,x9] // load polybe byte + strb w9,[x2,x5] // and store to result + add x5,x5,#1 + add x10,x10,#1 + add x6,x6,#1 + cmp x6,x8 // end ? + blt 5b + + mov x9,#0 // 0 final + strb w9,[x2,x5] + mov x0,x5 +100: + ldp x10,x11,[sp],16 // restaur registers + ldp x8,x9,[sp],16 // + ldp x6,x7,[sp],16 // + ldp x4,x5,[sp],16 // + ldp x2,x3,[sp],16 // + ldp x1,lr,[sp],16 // + ret + +/***************************************************/ +/* ROUTINES INCLUDE */ +/***************************************************/ +/* for this file see task include a file in language AArch64 assembly*/ +.include "../includeARM64.inc" diff --git a/Task/Bifid-cipher/ALGOL-68/bifid-cipher.alg b/Task/Bifid-cipher/ALGOL-68/bifid-cipher.alg new file mode 100644 index 0000000000..67fdc9f82f --- /dev/null +++ b/Task/Bifid-cipher/ALGOL-68/bifid-cipher.alg @@ -0,0 +1,141 @@ +BEGIN # Bifid cipher # + + # mode to hold the details of a Bifid cipher # + MODE BIFID = STRUCT( STRING key # the Polybius square, linearised # + , STRING pre from # pre-translation, "from" string # + , STRING pre to # pre-tramslatiion "to" string # + ); + + # string utilities # + + # returns the length of s # + OP LENGTH = ( STRING s )INT: ( UPB s - LWB s ) + 1; + # returns the index of c in s, or LWB s - 1 if it is not present # + PRIO INDEXOF = 1; + OP INDEXOF = ( STRING s, CHAR c )INT: + BEGIN + INT index := LWB s - 1; + VOID( char in string( c, index, s ) ); # discard the result # + index + END # INDEXOF # ; + # returns text with the characters in from chars replaced with the # + # corresponding characters in to chars # + PROC translate = ( STRING text, from chars, to chars )STRING: + IF LWB from chars /= LWB to chars OR UPB from chars /= UPB to chars + THEN """from"" and ""to"" have different bounds (translate)" + ELIF from chars = "" + THEN text + ELSE # the from and to strings have the same bounds # + STRING result := text; + FOR r pos FROM LWB result TO UPB result DO + INT t pos = from chars INDEXOF result[ r pos ]; + IF t pos >= LWB from chars THEN result[ r pos ] := to chars[ t pos ] FI + OD; + result + FI # translate # ; + # end string utilities # + + # returns text encrypted according to cipher # + PRIO ENCRYPT = 9; + OP ENCRYPT = ( STRING text, BIFID cipher )STRING: + IF STRING key = ( key OF cipher )[ AT 1 ]; + INT key length = LENGTH key; + INT sq width = ENTIER sqrt( key length ); + sq width * sq width /= key length + THEN "**** Bifid key is not a square" + ELSE # the key is a square # + STRING msg1 = translate( text, pre from OF cipher, pre to OF cipher )[ AT 1 ]; + STRING msg := ""; + FOR m pos FROM LWB msg1 TO UPB msg1 DO + IF msg1[ m pos ] /= " " THEN msg +:= msg1[ m pos ] FI + OD; + INT m max = LENGTH msg; + [ 1 : 2 * m max ]INT coordinates; + FOR m pos TO m max DO + INT c index := key INDEXOF msg[ m pos ]; + IF c index >= LWB key THEN c index -:= 1 FI; + coordinates[ m pos ] := c index OVER sq width; + coordinates[ m pos + m max ] := c index MOD sq width + OD; + STRING result := ""; + FOR c pos BY 2 TO UPB coordinates DO + result +:= key[ ( coordinates[ c pos ] * sq width ) + + coordinates[ c pos + 1 ] + + 1 + ] + OD; + result + FI # ENCRYPT # ; + + # returns text decrypted according to cipher # + PRIO DECRYPT = 9; + OP DECRYPT = ( STRING text, BIFID cipher )STRING: + IF STRING key = ( key OF cipher )[ AT 1 ]; + INT key length = LENGTH key; + INT sq width = ENTIER sqrt( key length ); + sq width * sq width /= key length + THEN "**** Bifid key is not a square" + ELSE # the key is a square # + STRING msg = text[ AT 1 ]; + INT m max = LENGTH msg; + [ 1 : 2 * m max ]INT coordinates; + INT c pos := 0; + FOR m pos TO m max DO + INT c index := key INDEXOF msg[ m pos ]; + IF c index >= LWB key THEN c index -:= 1 FI; + coordinates[ c pos +:= 1 ] := c index OVER sq width; + coordinates[ c pos +:= 1 ] := c index MOD sq width + OD; + STRING result := ""; + FOR i TO m max DO + result +:= key[ ( coordinates[ i ] * sq width ) + + coordinates[ i + m max ] + + 1 + ] + OD; + result + FI # DECRYPT # ; + + # tests the ENCRYPT and DECRYPT operators # + PROC test bifid = ( BIFID cipher, STRING text )VOID: + BEGIN + STRING code = text ENCRYPT cipher; + print( ( text, " -> ", code, newline ) ); + print( ( code, " -> ", code DECRYPT cipher, newline ) ) + END # text bifid # ; + + # Bifid ciphers for tests # + + BIFID bifid 5 abc = ( "ABCDEFGHIKLMNOPQRSTUVWXYZ" + , "Jabcdefghijklmnopqrstuvwxyz" + , "IABCDEFGHIIKLMNOPQRSTUVWXYZ" + ); + BIFID bifid 5 bgw = ( "BGWKZQPNDSIOAXEFCLUMTHYVR" + , "Jabcdefghijklmnopqrstuvwxyz" + , "IABCDEFGHIIKLMNOPQRSTUVWXYZ" + ); + BIFID bifid 6 abc = ( "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" + , "abcdefghijklmnopqrstuvwxyz" + , "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + ); + BIFID bifid 8 abc = ( "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\/" + , " " + , "/" + ); + + # basic task - using 5x5 Polybius squares # + test bifid( bifid 5 abc, "ATTACKATDAWN" ); + print( ( newline ) ); + test bifid( bifid 5 bgw, "FLEEATONCE" ); + test bifid( bifid 5 bgw, "ATTACKATDAWN" ); + test bifid( bifid 5 bgw, "The invasion will begin on the first of January" ); + print( ( newline ) ); + + # bonus - using a 6x6 square # + test bifid( bifid 6 abc, "The invasion will begin on the first of January" ); + print( ( newline ) ); + + # bonus - using an 8x8 square # + test bifid( bifid 8 abc, "The invasion will begin on the first of January" ) + +END diff --git a/Task/Bifid-cipher/ARM-Assembly/bifid-cipher.arm b/Task/Bifid-cipher/ARM-Assembly/bifid-cipher.arm new file mode 100644 index 0000000000..f2ce9e6951 --- /dev/null +++ b/Task/Bifid-cipher/ARM-Assembly/bifid-cipher.arm @@ -0,0 +1,376 @@ +/* ARM assembly Raspberry PI */ +/* program bifid.s */ +/* REMARK 1 : this program use routines in a include file + see task Include a file language arm assembly + for the routine affichageMess conversion10 + see at end of this program the instruction include */ + +/*******************************************/ +/* Constantes */ +/*******************************************/ +.include "../constantes.inc" + +.equ MESSSIZE, 2000 +.equ BUFFERSIZE, 2000 +/*******************************************/ +/* Macros */ +/*******************************************/ +//.include "../../ficmacros32.inc" @ for developer debugging + + +/*******************************************/ +/* Initialized data */ +/*******************************************/ +.data +szMessDebutPgm: .asciz "Program 32 bits start. \n" +szCarriageReturn: .asciz "\n" +szMessFinOK: .asciz "Program normal end. \n" +szMessError: .asciz "\nError Buffer too small!!!\n" +szMessString: .asciz "String :\n" +szMessEncrip: .asciz "\nEncrypted :\n" +szMessDecrip: .asciz "\nDecrypted :\n" +//szString1: .asciz "ABCDEFGHIJKLMNOPQRSTUVWXYZ!.?abcdefghijklmnopqrstuvwxyz" +//szString1: .asciz "attackatdawn" +szString1: .asciz "ATTACKATDAWN" +//szString1: .asciz "ABCD" +szString2: .asciz "FLEEATONCE" +szString3: .asciz "L'invasion commencera le premier janvier" + +szPolybe1: .ascii "ABCDE" + .ascii "FGHIK" + .ascii "LMNOP" + .ascii "QRSTU" + .asciz "VWXYZ" + +szPolybe2: .ascii "BGWKZ" + .ascii "QPNDS" + .ascii "IOAXE" + .ascii "FCLUM" + .asciz "THYVR" + +/*******************************************/ +/* UnInitialized data */ +/*******************************************/ +.bss +.align 4 +tabiposX: .skip 4 * MESSSIZE +tabiposY: .skip 4 * MESSSIZE +sBuffer1: .skip BUFFERSIZE +sBuffer2: .skip BUFFERSIZE +/*******************************************/ +/* code section */ +/*******************************************/ +.text +.global main +main: + ldr r0,iAdrszMessDebutPgm + bl affichageMess + ldr r0,iAdrszMessString @ display message + bl affichageMess + ldr r0,iAdrszString1 @ display string + bl affichageMess + ldr r0,iAdrszString1 @ string address + ldr r1,iAdrszPolybe1 @ Polybe key + ldr r2,iAdrsBuffer1 @ encrypted buffer result + bl encrypt + cmp r0,#0 + ble 99f + ldr r0,iAdrszMessEncrip + bl affichageMess + ldr r0,iAdrsBuffer1 @ display encrypted buffer + bl affichageMess + + + ldr r0,iAdrsBuffer1 @ encrypted buffer + ldr r1,iAdrszPolybe1 @ Polybe key + ldr r2,iAdrsBuffer2 @ decrypted buffer + bl decrypt + ldr r0,iAdrszMessDecrip + bl affichageMess + ldr r0,iAdrsBuffer2 @ display decrypted buffer + bl affichageMess + ldr r0,iAdrszCarriageReturn + bl affichageMess + + ldr r0,iAdrszMessString @ display message + bl affichageMess + ldr r0,iAdrszString2 @ display string + bl affichageMess + ldr r0,iAdrszString2 @ string address + ldr r1,iAdrszPolybe2 @ Polybe key + ldr r2,iAdrsBuffer1 @ encrypted buffer result + bl encrypt + cmp r0,#0 + ble 99f + ldr r0,iAdrszMessEncrip + bl affichageMess + ldr r0,iAdrsBuffer1 @ display encrypted buffer + bl affichageMess + + + ldr r0,iAdrsBuffer1 @ encrypted buffer + ldr r1,iAdrszPolybe2 @ Polybe key + ldr r2,iAdrsBuffer2 @ decrypted buffer + bl decrypt + ldr r0,iAdrszMessDecrip + bl affichageMess + ldr r0,iAdrsBuffer2 @ display decrypted buffer + bl affichageMess + ldr r0,iAdrszCarriageReturn + bl affichageMess + + ldr r0,iAdrszMessString @ display message + bl affichageMess + ldr r0,iAdrszString1 @ display string + bl affichageMess + ldr r0,iAdrszString1 @ string address + ldr r1,iAdrszPolybe2 @ Polybe key + ldr r2,iAdrsBuffer1 @ encrypted buffer result + bl encrypt + cmp r0,#0 + ble 99f + ldr r0,iAdrszMessEncrip + bl affichageMess + ldr r0,iAdrsBuffer1 @ display encrypted buffer + bl affichageMess + + + ldr r0,iAdrsBuffer1 @ encrypted buffer + ldr r1,iAdrszPolybe2 @ Polybe key + ldr r2,iAdrsBuffer2 @ decrypted buffer + bl decrypt + ldr r0,iAdrszMessDecrip + bl affichageMess + ldr r0,iAdrsBuffer2 @ display decrypted buffer + bl affichageMess + ldr r0,iAdrszCarriageReturn + bl affichageMess + + ldr r0,iAdrszMessString @ display message + bl affichageMess + ldr r0,iAdrszString3 @ display string + bl affichageMess + ldr r0,iAdrszString3 @ string address + ldr r1,iAdrszPolybe1 @ Polybe key + ldr r2,iAdrsBuffer1 @ encrypted buffer result + bl encrypt + cmp r0,#0 + ble 99f + ldr r0,iAdrszMessEncrip + bl affichageMess + ldr r0,iAdrsBuffer1 @ display encrypted buffer + bl affichageMess + + + ldr r0,iAdrsBuffer1 @ encrypted buffer + ldr r1,iAdrszPolybe1 @ Polybe key + ldr r2,iAdrsBuffer2 @ decrypted buffer + bl decrypt + ldr r0,iAdrszMessDecrip + bl affichageMess + ldr r0,iAdrsBuffer2 @ display decrypted buffer + bl affichageMess + ldr r0,iAdrszCarriageReturn + bl affichageMess + + ldr r0,iAdrszMessFinOK + bl affichageMess + b 100f +99: + ldr r0,iAdrszMessError @ error + bl affichageMess + mov r0, #1 +100: @ standard end of the program + mov r0, #0 @ return code + mov r7, #EXIT @ request to exit program + svc 0 @ perform system call +iAdrszMessString: .int szMessString +iAdrszMessDecrip: .int szMessDecrip +iAdrszMessEncrip: .int szMessEncrip +iAdrszString1: .int szString1 +iAdrszPolybe1: .int szPolybe1 +iAdrszString2: .int szString2 +iAdrszString3: .int szString3 +iAdrszPolybe2: .int szPolybe2 +iAdrsBuffer1: .int sBuffer1 +iAdrsBuffer2: .int sBuffer2 +iAdrszMessDebutPgm: .int szMessDebutPgm +iAdrszMessFinOK: .int szMessFinOK +iAdrszCarriageReturn: .int szCarriageReturn +iAdrszMessError: .int szMessError +/******************************************************************/ +/* encrypt strings */ +/******************************************************************/ +/* r0 contains the address of the string1 */ +/* r1 contains Polybe area address +/* r2 contains the address of the encrypted string */ +/* r0 return buffer lenght */ +encrypt: + push {r3-r12,lr} @ save registers + mov r3,#0 @ counter byte string 1 + mov r5,#0 @ counter byte buffer + +1: + ldrb r7,[r0,r3] @ load byte string 1 + cmp r7,#0 @ zero final ? + beq 4f + cmp r7,#65 @ < A ? + addlt r3,#1 + blt 1b + cmp r7,#90 @ > Z + ble 2f + + cmp r7,#97 @ < a ? + addlt r3,#1 + blt 1b + cmp r7,#122 @> z + addgt r3,#1 + bgt 1b + sub r7,#32 @ convert minuscul to majuscule +2: + cmp r7,#'J' @ change J to I + moveq r7,#'I' + ldr r11,iAdrtabiposX + ldr r12,iAdrtabiposY + mov r6,#0 + mov r9,#5 +3: @ loop to search char in polybe square + ldrb r8,[r1,r6] @ load byte polybe + cmp r8,r7 @ equal ? + addne r6,#1 + bne 3b + udiv r10,r6,r9 @ compute coordonnés + mls r8,r10,r9,r6 + + strb r10,[r11,r5] @ save X position + strb r8,[r12,r5] @ save Y position + add r5,r5,#1 @ increment indice + add r3,r3,#1 + b 1b @ and loop + +4: + mov r6,#0 + mov r8,r5 + mov r5,#0 + mov r3,#5 +5: @ convert position line 1 in char + ldrb r9,[r11,r6] + add r6,r6,#1 + cmp r6,r8 @ first line end ? + movge r6,#0 + bge 7f @ jmp for second line + + ldrb r7,[r11,r6] @ compute rank with position X and Y + mul r9,r3,r9 + add r9,r9,r7 + ldrb r9,[r1,r9] @ load polybe char + strb r9,[r2,r5] + add r5,r5,#1 + + add r6,r6,#1 + cmp r6,r8 + blt 5b + + mov r6,#0 +6: @ convert position line 2 in char + ldrb r9,[r12,r6] + add r6,r6,#1 +7: + ldrb r7,[r12,r6] @ compute rank with position X and Y + mul r9,r3,r9 + add r9,r9,r7 + ldrb r9,[r1,r9] @ load polybe char + strb r9,[r2,r5] + add r5,r5,#1 + add r6,r6,#1 + cmp r6,r8 + blt 6b + + mov r9,#0 @ zero final + strb r9,[r2,r5] + mov r0,r5 +100: + pop {r3-r12,pc} @ restaur registers +iAdrtabiposX: .int tabiposX +iAdrtabiposY: .int tabiposY +/******************************************************************/ +/* decrypt strings */ +/******************************************************************/ +/* r0 contains the address of the encrypted string1 */ +/* r1 contains Polybe area address +/* r2 contains the address of the decrypted string */ +/* r0 return buffer lenght */ +decrypt: + push {r3-r11,lr} @ save registers + mov r3,#0 @ counter byte string 1 + mov r5,#0 @ counter byte result buffer +1: + ldrb r7,[r0,r3] @ load byte string 1 + cmp r7,#0 @ zero final ? + moveq r0,r5 + beq 4f + + cmp r7,#65 @ < A ? + addlt r3,#1 + blt 1b + cmp r7,#90 @ > Z + ble 2f + + cmp r7,#97 @ < a ? + addlt r3,#1 + blt 1b + cmp r7,#122 @> z + addgt r3,#1 + bgt 1b + sub r7,#32 @ convert minuscul to majuscule +2: + ldr r11,iAdrtabiposX + mov r6,#0 + mov r9,#5 +3: @ loop to search char in polybe square + ldrb r8,[r1,r6] @ load byte polybe + cmp r8,r7 + addne r6,#1 + bne 3b + + udiv r10,r6,r9 + mls r8,r10,r9,r6 + strb r10,[r11,r5] + add r5,r5,#1 + strb r8,[r11,r5] + add r5,r5,#1 + + add r3,#1 + b 1b + +4: + mov r6,#0 @ start indice first line + lsr r8,r5,#1 + mov r10,r8 @ start indice second line + mov r5,#0 + mov r3,#5 + +5: + ldrb r9,[r11,r6] @ load position + ldrb r7,[r11,r10] + mul r9,r3,r9 @ compute rank + add r9,r9,r7 + ldrb r9,[r1,r9] @ load polybe byte + strb r9,[r2,r5] @ and store to result + add r5,r5,#1 + add r10,r10,#1 + add r6,r6,#1 + cmp r6,r8 @ end ? + blt 5b + + mov r9,#0 @ 0 final + strb r9,[r2,r5] + mov r0,r5 +100: + pop {r3-r11,pc} @ restaur registers + + +/***************************************************/ +/* ROUTINES INCLUDE */ +/***************************************************/ +.include "../affichage.inc" diff --git a/Task/Bifid-cipher/Ada/bifid-cipher.ada b/Task/Bifid-cipher/Ada/bifid-cipher.adb similarity index 100% rename from Task/Bifid-cipher/Ada/bifid-cipher.ada rename to Task/Bifid-cipher/Ada/bifid-cipher.adb diff --git a/Task/Bifid-cipher/C++/bifid-cipher.cpp b/Task/Bifid-cipher/C++/bifid-cipher.cpp index 0e93a81f8a..411515802a 100644 --- a/Task/Bifid-cipher/C++/bifid-cipher.cpp +++ b/Task/Bifid-cipher/C++/bifid-cipher.cpp @@ -9,104 +9,104 @@ typedef std::pair point; class Bifid { public: - Bifid(const int32_t n, std::string_view text) { - if ( text.length() != n * n ) { - throw std::invalid_argument("Incorrect length of text"); - } + Bifid(const int32_t n, std::string_view text) { + if ( text.length() != n * n ) { + throw std::invalid_argument("Incorrect length of text"); + } - grid.resize(n); - for ( uint64_t i = 0; i < grid.size(); i++ ) { - grid[i].resize(n); - } + grid.resize(n); + for ( uint64_t i = 0; i < grid.size(); i++ ) { + grid[i].resize(n); + } - int32_t row = 0; - int32_t col = 0; - for ( const char& ch : text ) { - grid[row][col] = ch; - coordinates[ch] = point(row, col); - col += 1; - if ( col == n ) { - col = 0; - row += 1; - } - } + int32_t row = 0; + int32_t col = 0; + for ( const char& ch : text ) { + grid[row][col] = ch; + coordinates[ch] = point(row, col); + col += 1; + if ( col == n ) { + col = 0; + row += 1; + } + } - if ( n == 5 ) { - coordinates['J'] = coordinates['I']; - } - } + if ( n == 5 ) { + coordinates['J'] = coordinates['I']; + } + } - std::string encrypt(std::string_view text) { - std::vector row_one, row_two; - for ( const char& ch : text ) { - point coordinate = coordinates[ch]; - row_one.push_back(coordinate.first); - row_two.push_back(coordinate.second); - } + std::string encrypt(std::string_view text) { + std::vector row_one, row_two; + for ( const char& ch : text ) { + point coordinate = coordinates[ch]; + row_one.push_back(coordinate.first); + row_two.push_back(coordinate.second); + } - row_one.insert(row_one.end(), row_two.begin(), row_two.end()); - std::string result; - for ( uint64_t i = 0; i < row_one.size() - 1; i += 2 ) { - result += grid[row_one[i]][row_one[i + 1]]; - } - return result; - } + row_one.insert(row_one.end(), row_two.begin(), row_two.end()); + std::string result; + for ( uint64_t i = 0; i < row_one.size() - 1; i += 2 ) { + result += grid[row_one[i]][row_one[i + 1]]; + } + return result; + } - std::string decrypt(std::string_view text) { - std::vector row; - for ( const char& ch : text ) { - point coordinate = coordinates[ch]; - row.push_back(coordinate.first); - row.push_back(coordinate.second); - } + std::string decrypt(std::string_view text) { + std::vector row; + for ( const char& ch : text ) { + point coordinate = coordinates[ch]; + row.push_back(coordinate.first); + row.push_back(coordinate.second); + } - const int middle = row.size() / 2; - std::vector row_one = { row.begin(), row.begin() + middle }; - std::vector row_two = { row.begin() + middle, row.end() }; - std::string result; - for ( int32_t i = 0; i < middle; i++ ) { - result += grid[row_one[i]][row_two[i]]; - } - return result; - } + const int middle = row.size() / 2; + std::vector row_one = { row.begin(), row.begin() + middle }; + std::vector row_two = { row.begin() + middle, row.end() }; + std::string result; + for ( int32_t i = 0; i < middle; i++ ) { + result += grid[row_one[i]][row_two[i]]; + } + return result; + } - void display() const { - for ( const std::vector& row : grid ) { - for ( const char& ch : row ) { - std::cout << ch << " "; - } - std::cout << std::endl; - } - } + void display() const { + for ( const std::vector& row : grid ) { + for ( const char& ch : row ) { + std::cout << ch << " "; + } + std::cout << std::endl; + } + } private: - std::vector> grid; - std::unordered_map coordinates; + std::vector> grid; + std::unordered_map coordinates; }; void runTest(Bifid& bifid, std::string_view message) { - std::cout << "Using Polybius square:" << std::endl; - bifid.display(); - std::cout << "Message: " << message << std::endl; - std::string encrypted = bifid.encrypt(message); - std::cout << "Encrypted: " << encrypted << std::endl; - std::string decrypted = bifid.decrypt(encrypted); - std::cout << "Decrypted: " << decrypted << std::endl; - std::cout << std::endl; + std::cout << "Using Polybius square:" << std::endl; + bifid.display(); + std::cout << "Message: " << message << std::endl; + std::string encrypted = bifid.encrypt(message); + std::cout << "Encrypted: " << encrypted << std::endl; + std::string decrypted = bifid.decrypt(encrypted); + std::cout << "Decrypted: " << decrypted << std::endl; + std::cout << std::endl; } int main() { - const std::string_view message1 = "ATTACKATDAWN"; - const std::string_view message2 = "FLEEATONCE"; - const std::string_view message3 = "THEINVASIONWILLSTARTONTHEFIRSTOFJANUARY"; + const std::string_view message1 = "ATTACKATDAWN"; + const std::string_view message2 = "FLEEATONCE"; + const std::string_view message3 = "THEINVASIONWILLSTARTONTHEFIRSTOFJANUARY"; - Bifid bifid1(5, "ABCDEFGHIKLMNOPQRSTUVWXYZ"); - Bifid bifid2(5, "BGWKZQPNDSIOAXEFCLUMTHYVR"); + Bifid bifid1(5, "ABCDEFGHIKLMNOPQRSTUVWXYZ"); + Bifid bifid2(5, "BGWKZQPNDSIOAXEFCLUMTHYVR"); - runTest(bifid1, message1); - runTest(bifid2, message2); - runTest(bifid2, message1); - runTest(bifid1, message2); + runTest(bifid1, message1); + runTest(bifid2, message2); + runTest(bifid2, message1); + runTest(bifid1, message2); - Bifid bifid3(6, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"); - runTest(bifid3, message3); + Bifid bifid3(6, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"); + runTest(bifid3, message3); } diff --git a/Task/Bifid-cipher/Crystal/bifid-cipher.cr b/Task/Bifid-cipher/Crystal/bifid-cipher.cr new file mode 100644 index 0000000000..ce327b9dfa --- /dev/null +++ b/Task/Bifid-cipher/Crystal/bifid-cipher.cr @@ -0,0 +1,46 @@ +enum BifidOp + Encode + Decode +end + +def bifid_encode (message, alphabet, op : BifidOp = :encode) + square = alphabet.chars + side = Math.isqrt(square.size) + raise "alphabet not a square" unless side*side == square.size + chars = message.chars + raise "incomplete alphabet" unless chars.all?(&.in? square) + + coords = chars.flat_map {|ch| [*square.index!(ch).divmod(side)] } + + coords = if op.encode? + (0...coords.size).step(2).map {|i| coords[i] }.to_a + + (1...coords.size).step(2).map {|i| coords[i] }.to_a + else + half = coords.size//2 + coords[...half].zip(coords[half..]).map {|c1, c2| + [c1, c2] + }.flatten + end + coords.each_slice(2).map {|(row, col)| + square[row * side + col] + }.join +end + +poly1 = "ABCDEFGHIKLMNOPQRSTUVWXYZ" +poly2 = "BGWKZQPNDSIOAXEFCLUMTHYVR" +superpoly = (' '..'~').join + "¡éßñø" + +attack = "ATTACKATDAWN" +flee = "FLEEATONCE" +invasion = "The invasion will start on the first of January".upcase.tr("J", "I").delete("^A-Z") +ataque = "¡Attack on 1/1 at 23:59, señor!" + +[{attack, poly1}, {flee, poly2}, {attack, poly2}, + {invasion, poly1}, {ataque, superpoly}].each do |message, alphabet| + encoded = bifid_encode(message, alphabet) + decoded = bifid_encode(encoded, alphabet, :decode) + puts "Message: #{message} #{alphabet.size > 80 ? "\n" : " "}- Alphabet: #{alphabet}" + puts "Encoded: #{encoded}" + puts "Decoded: #{decoded}" + puts +end diff --git a/Task/Bifid-cipher/EMal/bifid-cipher.emal b/Task/Bifid-cipher/EMal/bifid-cipher.emal new file mode 100644 index 0000000000..786b4e3400 --- /dev/null +++ b/Task/Bifid-cipher/EMal/bifid-cipher.emal @@ -0,0 +1,82 @@ +type PolybiusSquare +model + Map map + List grid + new by int side, text symbols + me.map ← text%Pair[] + me.grid ← List[].with(side, = 97 @@ -36,13 +11,36 @@ func$ conv s$ . r$ &= strchar h . . - return r$ + swap s$ r$ . func$ encr msg$ key$ . - return crypt 1 conv msg$ key$ + prepare msg$ + len h[] len msg$ * 2 + for i to len msg$ + c$ = substr msg$ i 1 + j = strpos key$ c$ - 1 + h[i] = j div 5 + h[len msg$ + i] = j mod 5 + . + for i = 1 step 2 to len h[] - 1 + j = h[i] * 5 + h[i + 1] + 1 + r$ &= substr key$ j 1 + . + return r$ . func$ decr msg$ key$ . - return crypt 0 msg$ key$ + for i to len msg$ + c$ = substr msg$ i 1 + j = strpos key$ c$ - 1 + h[] &= j div 5 + h[] &= j mod 5 + . + mid = len h[] div 2 + for i = 1 to mid + j = h[i] * 5 + h[i + mid] + 1 + r$ &= substr key$ j 1 + . + return r$ . key$ = "ABCDEFGHIKLMNOPQRSTUVWXYZ" h$ = encr "ATTACKATDAWN" key$ @@ -59,7 +57,6 @@ h$ = encr "ATTACKATDAWN" key$ print h$ print decr h$ key$ print "" -# h$ = encr "The invasion will start on the first of January" key$ print h$ print decr h$ key$ diff --git a/Task/Bifid-cipher/F-Sharp/bifid-cipher.fs b/Task/Bifid-cipher/F-Sharp/bifid-cipher.fs new file mode 100644 index 0000000000..50904e931d --- /dev/null +++ b/Task/Bifid-cipher/F-Sharp/bifid-cipher.fs @@ -0,0 +1,17 @@ +// Bifid cipher. Nigel Galloway: September 17th., 2024 +let polybius alphabet n g=let ng=Seq.allPairs [1..n] [1..g] in (Seq.zip ng alphabet|>Map.ofSeq,Seq.zip alphabet ng|>Map.ofSeq) +let fN (i,g) (e:Map<(int*int),char>)=i@g|>List.chunkBySize 2|>List.map(fun n->e[(n[0],n[1])])|>Array.ofList|>System.String +let fG (n:Map) g=g|>Seq.map(fun g->n[g])|>List.ofSeq|>List.unzip +let encrypt (n:Map<(int * int),char>,g:Map) text=fN (fG g text) n +let decrypt (n:Map<(int * int),char>,g:Map) text= + let p,q=let p,q=fG g text in List.map2(fun p q->[p;q]) p q|>List.concat|>List.splitAt p.Length + List.zip p q |>List.map(fun g->n[g])|>Array.ofList|>System.String + +let p1=polybius "abcdefghiklmnopqrstuvwxyz" 5 5 +let s="attackatdawn" in let e=encrypt p1 s in printfn $"%s{s} -> %s{e} -> %s{decrypt p1 e}" +let s="fleeatonce" in let e=encrypt p1 s in printfn $"%s{s} -> %s{e} -> %s{decrypt p1 e}" +let p2=polybius "bgwkzqpndsioaxefclumthyvr" 5 5 +let s="attackatdawn" in let e=encrypt p2 s in printfn $"%s{s} -> %s{e} -> %s{decrypt p2 e}" +let s="fleeatonce" in let e=encrypt p2 s in printfn $"%s{s} -> %s{e} -> %s{decrypt p2 e}" +let p3=polybius "abcdefghijklmnopqrstuvwxyz0123456789" 6 6 +let s="theinvasionwillstarton1january2025" in let e=encrypt p3 s in printfn $"%s{s} -> %s{e} -> %s{decrypt p3 e}" diff --git a/Task/Bifid-cipher/Fortran/bifid-cipher.f b/Task/Bifid-cipher/Fortran/bifid-cipher.f new file mode 100644 index 0000000000..4d804626f9 --- /dev/null +++ b/Task/Bifid-cipher/Fortran/bifid-cipher.f @@ -0,0 +1,219 @@ +! +! Bifid cipher +! tested with Intel ifx (IFX) 2025.2.1 20250806 on Kubuntu 25.10 +! GNU Fortran (Ubuntu 15.2.0-4ubuntu4) 15.2.0 on Kubuntu 25.10 +! VSI Fortran x86-64 V8.6-001 on OpenVMS x86_64 V9.2-3 +! No Non-standard features used, should compile on any fairly recent Fortran. +! +! U.B., October 2025 +!============================================================================== + +program BifidCipher + +implicit none + +! Constants: + +integer, parameter :: nTests = 6 ! NUmber of different test messages +integer, parameter :: maxLen=100 ! Maximum length of any test message + +! Instead of drawing the Polybius squares, we only define the alphabet to applied and calculate +! row and column number on the fly when needed. +! If necessary, the Encrypt and Decrypt subroutines extend the alphabets using "SpareAlpha" +! until the total length of the extended alphabet is a square number. This is important because +! otherwise the enccrypt or decrypt algorithm may calculate a row/column combination that is +! not used by the actual alphabet. + +! The alphabet as shown in the task description has no J. +character (len=*), parameter :: Alphabet_no_J ='ABCDEFGHIKLMNOPQRSTUVWXYZ' + +! The alphabet of capital letters as used in most western languages +character (len=*), parameter :: Alphabet_With_J ='ABCDEFGHIJKLMNOPQRSTUVWXYZ' + +! The square in the wikipedia article in 1 long string: +character (len=*), parameter :: AlternateAlphabet = 'BGWKZQPNDSIOAXEFCLUMTHYVR' + +! Standard Alphabet with CAPITAL and small letters +character (len=*), parameter :: Alphabet_withSmallLetters = & + 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' + +! Printable spare characters to extend alphabets so the total length becomes the +! next larger square number > the alphabet's length +character (len=*), parameter :: SpareAlpha = '1234567890!"§$%&/()=' ! omitted ! and " + +! Variables: + +character (len=maxLen) :: MsgToEncrypt (nTests), EncryptedMsg (nTests), DecryptedMsg (nTests) + +integer :: ColWidth ! Is variable and depends on length of the used alphabet + +integer :: i, lx + +! The test strings: (1) is from the task description, (2) is from the Wikipedia Article, (3) is +! the additional message as presented in the task description +MsgToEncrypt(1) = 'ATTACKATDAWN' +MsgToEncrypt(2) = 'FLEEATONCE' +MsgToEncrypt(3) = 'THEINVASIONWILLSTARTONTHEFIRSTOFJANUARY' + +! Same text, with both small and capital letters, to be used with an extended Polybius square +MsgToEncrypt(4) = 'AttackAtDawn' +MsgToEncrypt(5) = 'FleeAtOnce' +MsgToEncrypt(6) = 'TheInvasionWillStartOnTheFirstOfJanuary' + +print '(A/)', 'Using the alphabet and Polybius square without "J"' +call PrintSquare (Alphabet_no_J) +do i=1, nTests/2 + lx = len_trim (MsgToEncrypt(i)) + call encrypt (MsgToEncrypt(i)(:lx) , EncryptedMsg (i) , Alphabet_no_J) + call decrypt (EncryptedMsg(i) (:lx), DecryptedMsg (i) , Alphabet_no_J) + print '(A, " => ", A, " => ", A)', MsgToEncrypt(i)(:lx), EncryptedMsg (i)(:lx), DecryptedMsg (i)(:lx) +enddo + +print '(/A/)', 'Using the extended alphabet and Polybius square that includes "J"' +call PrintSquare (Alphabet_with_J) +do i=1, nTests/2 + lx = len_trim (MsgToEncrypt(i)) + call encrypt (MsgToEncrypt(i)(:lx) , EncryptedMsg (i) , Alphabet_with_J) + call decrypt (EncryptedMsg(i) (:lx), DecryptedMsg (i) , Alphabet_with_J) + print '(A, " => ", A, " => ", A)', MsgToEncrypt(i)(:lx), EncryptedMsg (i)(:lx), DecryptedMsg (i)(:lx) +end do + +print '(/A/)', 'Using the alphabet and Polybius square as shown in the Wikipedia article (no J!)' +call PrintSquare (AlternateAlphabet) +do i=1, nTests/2 + lx = len_trim (MsgToEncrypt(i)) + call encrypt (MsgToEncrypt(i)(:lx) , EncryptedMsg (i) , AlternateAlphabet) + call decrypt (EncryptedMsg(i) (:lx), DecryptedMsg (i) , AlternateAlphabet) + print '(A, " => ", A, " => ", A)', MsgToEncrypt(i)(:lx), EncryptedMsg (i)(:lx), DecryptedMsg (i)(:lx) +end do + +print '(/A/)', 'Using the extended alphabet with both upper case and lower case letters, including J and j' +call PrintSquare (Alphabet_withSmallLetters) +do i=nTests/2+1, nTests + lx = len_trim (MsgToEncrypt(i)) + call encrypt (MsgToEncrypt(i)(:lx) , EncryptedMsg (i) , Alphabet_withSmallLetters) + call decrypt (EncryptedMsg(i) (:lx), DecryptedMsg (i) , Alphabet_withSmallLetters) + print '(A, " => ", A, " => ", A)', MsgToEncrypt(i)(:lx), EncryptedMsg (i)(:lx), DecryptedMsg (i)(:lx) +end do + +contains + +!====================== +! Encode a given string +! ====================== +subroutine encrypt (inString,outString, argAlphabet) +character (len=*), intent(in) :: argAlphabet +character (len=*), intent(in) :: inString +character (len=*), intent(out) :: outString +character (len=100) :: Alphabet + +integer :: idxLine(2*maxLen) +integer :: l, ii, idx, row, col + +! Calculate required column width: so that ColWidth^2 >= (length of Alphabet) +Alphabet = argAlphabet +l = len_trim(alphabet) +ColWidth = 1 +do while (ColWidth*ColWidth .lt. l) + ColWidth = ColWidth + 1 +end do +if (ColWidth .gt.8) stop 'ERROR: Cannot handle Alphabets with more than 64 characters.' +! Provide some printable chars until the length is a square number +Alphabet (l+1:) = SpareAlpha + +l = len_trim (inString) +if (l .gt. len(outString)) stop 'ERROR: not enough storage space for encrypt result string.' + +do ii=1, l +! print *, ' ii = ', ii, ' instring(ii) = ', inString(ii:ii) + idx = index (Alphabet, inString(ii:ii)) + if (idx .eq. 0) idx = index (Alphabet, char(ichar(instring(ii:ii))-1)) ! J=I, j=i, just in case + row = (idx+ColWidth-1) / ColWidth ! e.g. 'A' ...'E', idx=1...5, row=(5...9)/5 = 1, col = 1...5 + col = 1+mod (idx+ColWidth-1, ColWidth) ! e.g. 'F' ...'K', idx=6...10, row=(10...14)/5 = 2, col = 1...5 + idxLine (ii) = row + idxLine (ii+l) = col +end do + +do ii=1, l + idx = 10*idxLine(1+2*(ii-1)) + idxLine (2+2*(ii-1)) + row = idxLine(1+2*(ii-1)) + col = idxLine (2+2*(ii-1)) + idx = ColWidth*(row-1) + col + outString (ii:ii) = alphabet (idx:idx) +enddo +end subroutine encrypt + + +!====================== +! Decode a given string +!====================== +subroutine decrypt (inString,outString, argAlphabet) + +character (len=*), intent(in) :: inString +character (len=*), intent(out) :: outString +character (len=*), intent(in) :: argAlphabet + +character (len=100) :: Alphabet + +integer :: idxLine(2*maxLen) +integer :: l, ii, idx, row, col + +! Calculate required column width: so that ColWidth^2 >= (length of Alphabet) +Alphabet = argAlphabet +l = len_trim(alphabet) +ColWidth = 1 +do while (ColWidth*ColWidth .lt. l) + ColWidth = ColWidth + 1 +end do + +! Append some spare characters so that the square is completely filled without undefined fields +Alphabet (l+1:) = SpareAlpha + +l = len_trim (inString) +if (l .gt. len(outString)) stop 'ERROR: not enough storage space for decrypt result string.' + +do ii=1, l + idx = index (Alphabet, inString(ii:ii)) + row = (idx+ColWidth-1) / ColWidth ! idx 1...5 is row 1, 6...10 is row 2 etc + col = 1+mod (idx+ColWidth-1, ColWidth) ! so that 21...29 -> 1...9 etc. + idxLine (1+2*(ii-1)) = row + idxLine (2+2*(ii-1)) = col +end do + +do ii=1, l + row = idxLine (ii) + col = idxLine (ii+l) + idx = ColWidth*(row-1) + col + outString (ii:ii) = alphabet (idx:idx) +end do + +end subroutine decrypt + + +! ================================================================================ +! Print the resulting Polybius square based on the alphabet used for encode/decode +! ================================================================================ +subroutine PrintSquare (Alphabet) +character (len=*), intent(in) :: Alphabet +integer:: ii, l + +l = len_trim(alphabet) +ColWidth = 1 +do while (ColWidth*ColWidth .lt. l) + ColWidth = ColWidth + 1 +end do +print '("The alphabet has a length of ", I0, " so it requires the square size of ", I0, "x", I0 /)' , l, ColWidth, ColWidth + +do ii=1, ColWidth*ColWidth + if (ii .le. l) then + write (*, '(A2)', advance='no') Alphabet(ii:ii) + else + write (*, '(A2)', advance='no') SpareAlpha (ii-l:ii-l) ! Use spares to complete the square + endif + if (mod (ii, ColWidth) .eq. 0) print * ! End of line +end do +print * ! one extra blank line +end subroutine PrintSquare + + +end program BifidCipher diff --git a/Task/Bifid-cipher/FreeBASIC/bifid-cipher.basic b/Task/Bifid-cipher/FreeBASIC/bifid-cipher.basic new file mode 100644 index 0000000000..67b6e9ffad --- /dev/null +++ b/Task/Bifid-cipher/FreeBASIC/bifid-cipher.basic @@ -0,0 +1,81 @@ +Dim Shared As String encrypted, decrypted + +Sub BifidEncode(Byref polybius As String, Byref mensaje As String) + Dim As String filas, columas + Dim As Integer c, i, j, k, longi + + encrypted = Ucase(mensaje) + For i = 1 To Len(encrypted) + If Mid(encrypted, i, 1) = Chr(10) Then Mid(encrypted, i, 1) = Chr(9) + Next i + + + i = 0 : j = 0 + While i < Len(encrypted) + c = Asc(Mid(encrypted, i + 1, 1)) + i += 1 + k = Instr(polybius, Chr(c)) - 1 + If k >= 0 Then + filas &= Chr(k \ 5 + Asc("0")) + columas &= Chr(k Mod 5 + Asc("0")) + j += 1 + End If + Wend + + longi = j + filas &= columas + + encrypted = "" + For i = 0 To longi - 1 + k = (Asc(Mid(filas, i * 2 + 1, 1)) - Asc("0")) * 5 + (Asc(Mid(filas, i * 2 + 2, 1)) - Asc("0")) + encrypted &= Mid(polybius, k + 1, 1) + Next i +End Sub + +Sub BifidDecode(Byref polybius As String, Byref mensaje As String) + Dim As String filas, columas + Dim As Integer c, k, i, j, longi + + i = 0 : j = 0 + While i < Len(mensaje) + c = Asc(Mid(mensaje, i + 1, 1)) + i += 1 + k = Instr(polybius, Chr(c)) - 1 + filas &= Chr(k \ 5 + Asc("0")) + filas &= Chr(k Mod 5 + Asc("0")) + j += 2 + Wend + + longi = i + columas = Right(filas, longi) + filas = Left(filas, longi) + + decrypted = "" + For i = 0 To longi - 1 + k = (Asc(Mid(filas, i + 1, 1)) - Asc("0")) * 5 + (Asc(Mid(columas, i + 1, 1)) - Asc("0")) + decrypted &= Mid(polybius, k + 1, 1) + Next i +End Sub + +Dim As String polys(3), msgs(3) + +polys(0) = "ABCDEFGHIKLMNOPQRSTUVWXYZ" +polys(1) = "BGWKZQPNDSIOAXEFCLUMTHYVR" +polys(2) = "BGWKZQPNDSIOAXEFCLUMTHYVR" +polys(3) = "PLAYFIREXMBCDGHKNOQSTUVWZ" + +msgs(0) = "ATTACKATDAWN" +msgs(1) = "FLEEATONCE" +msgs(2) = "ATTACKATDAWN" +msgs(3) = "The invasion will start on the first of January" + +For i As Integer = 0 To Ubound(msgs) + BifidEncode(polys(i), msgs(i)) + BifidDecode(polys(i), encrypted) + Print "Mensaje : "; msgs(i) + Print "Encrypted : "; encrypted + Print "Decrypted : "; decrypted + If i < Ubound(msgs) Then Print +Next i + +Sleep diff --git a/Task/Bifid-cipher/Go/bifid-cipher.go b/Task/Bifid-cipher/Go/bifid-cipher.go new file mode 100644 index 0000000000..ad8846cf1b --- /dev/null +++ b/Task/Bifid-cipher/Go/bifid-cipher.go @@ -0,0 +1,180 @@ +/* + Only use ASCII letters between A and Z or the Characters in square... . If the row with 'J' is removed from the squares, + then the square is a 'Polybios square' and you must use removeSpaceI(text) to encrypt and decrypt +*/ +package main + +import ( + "fmt" + "strings" +) + +var ( + squareRosetta [][]byte = [][]byte{ //rosettacode + {'A', 'B', 'C', 'D', 'E'}, + {'F', 'G', 'H', 'I', 'K'}, + {'L', 'M', 'N', 'O', 'P'}, + {'Q', 'R', 'S', 'T', 'U'}, + {'V', 'W', 'X', 'Y', 'Z'}, + {'J', '1', '2', '3', '4'}, + } + + squareWikipedia [][]byte = [][]byte{ // wikipedia + + {'B', 'G', 'W', 'K', 'Z'}, + {'Q', 'P', 'N', 'D', 'S'}, + {'I', 'O', 'A', 'X', 'E'}, + {'F', 'C', 'L', 'U', 'M'}, + {'T', 'H', 'Y', 'V', 'R'}, + {'J', '1', '2', '3', '4'}, + } + + textRosetta string = "0ATTACKATDAWN" + textRosettaEncoded string = "DQBDAXDQPDQH" // only for test + textWikipedia string = "FLEEATONCE" + textWikipediaEncoded string = "UAEOLWRINS" // only for test + textTest string = "The invasion will start on the first of January" + textTextEncoded string = "RASOAQXFIOORXESXADETSWLTNIAZQOISBRGBALY" // only for test +) + +type koord struct { + X byte + Y byte +} + +func (k *koord) LessThen(other *koord) bool { + if k.Y > other.Y { + return false + } + if k.Y < other.Y { + return true + } + if k.X < other.X { + return true + } + return false +} + +func (k *koord) EqualTo(other koord) bool { + if k.X == other.X && k.Y == other.Y { + return true + } + return false +} + +var encryptMap map[byte]koord +var decryptMap map[koord]byte + +func squareToMaps(square [][]byte) (map[byte]koord, map[koord]byte) { + eMap := make(map[byte]koord) + dMap := make(map[koord]byte) + for x, col := range square { + for y, v := range col { + eMap[v] = koord{byte(x), byte(y)} + dMap[koord{byte(x), byte(y)}] = v + + } + } + return eMap, dMap +} + +func removeSpaceI(text string) string { + var n string + s := strings.ToUpper(text) + for _, b := range []byte(s) { + //use only ASCII Characters from A to Z + if b < 'A' || b > 'Z' { + continue + } + if b == 'J' { + b = 'I' + } + n = n + string(b) + } + return n +} + +func removeSpace(text string, square map[byte]koord) string { + var n string + //to UpperCase and then remove all Spaces an Characters witch are not in square + s := strings.ReplaceAll(strings.ToUpper(text), " ", "") + for _, b := range []byte(s) { + _, ok := square[b] + if ok { + n = n + string(b) + } + } + return n +} + +func encrypt(text string, emap map[byte]koord, dmap map[koord]byte) string { + text = removeSpace(text, emap) + var row0, row1 []byte + for _, b := range []byte(text) { + xy := emap[b] + row0 = append(row0, xy.X) + row1 = append(row1, xy.Y) + } + row0 = append(row0, row1...) + + var s string + for i := 0; i < len(row0); i += 2 { + s = s + string(dmap[koord{row0[i], row0[i+1]}]) + } + return s +} + +func decrypt(text string, emap map[byte]koord, dmap map[koord]byte) string { + text = removeSpace(text, emap) + k := make([]koord, len(text)) + + for i, b := range []byte(text) { + k[i] = emap[b] + } + + kl := make([]byte, len(k)*2) + i := int(0) + for _, ki := range k { + kl[i] = ki.X + kl[i+1] = ki.Y + i += 2 + } + l := len(kl) / 2 + k1 := kl[:l] + k2 := kl[l:] + var s string + + for i := 0; i < l; i++ { + s = s + string(dmap[koord{k1[i], k2[i]}]) + } + return s +} + +func main() { + + encryptMap, decryptMap = squareToMaps(squareRosetta) + fmt.Println("from Rosettacode") + fmt.Println("original:\t", textRosetta) + s := encrypt(textRosetta, encryptMap, decryptMap) + fmt.Println("codiert:\t", s) + s = decrypt(s, encryptMap, decryptMap) + fmt.Println("and back:\t", s) + + fmt.Println("from Wikipedia") + encryptMap, decryptMap = squareToMaps(squareWikipedia) + fmt.Println("original:\t", textWikipedia) + s = encrypt(textWikipedia, encryptMap, decryptMap) + fmt.Println("codiert:\t", s) + s = decrypt(s, encryptMap, decryptMap) + fmt.Println("and back:\t", s) + + encryptMap, decryptMap = squareToMaps(squareWikipedia) + fmt.Println("from Rosettacode long part") + fmt.Println("original:\t", textTest) + s = encrypt(textTest, encryptMap, decryptMap) + fmt.Println("codiert:\t", s) + // Wenn der Text eine ungerade Anzahl Buchstaben hat, funktioniert der Algorithmus nicht!!! + s = decrypt(s, encryptMap, decryptMap) + fmt.Println("and back:\t", s) + +} diff --git a/Task/Bifid-cipher/Haskell/bifid-cipher.hs b/Task/Bifid-cipher/Haskell/bifid-cipher.hs new file mode 100644 index 0000000000..9964f7aa9d --- /dev/null +++ b/Task/Bifid-cipher/Haskell/bifid-cipher.hs @@ -0,0 +1,60 @@ +import Data.List +import Data.Char + +-- Defining all the grids I'll be using in one go. + +rcBifid = [ + 'A','B','C','D','E', + 'F','G','H','I','K', + 'L','M','N','O','P', + 'Q','R','S','T','U', + 'V','W','X','Y','Z' + ] -- We will use strings here onwards. This was just a demonstration. + +wikiBifid = "POLYBIUSCHERADFGKMNQTVWXZ" +cmiBifid = "CMIHASKELQWRTYUOPDFGZXVBN" + +-- Convert a character to its grid coordinates (1-based index) +chr2pair square x = if x == 'J' then chr2pair square 'I' else case elemIndex x square of + Nothing -> error "char is not in cipher grid" + Just a -> (\(x,y) -> (x+1,y+1)) (divMod a 5) -- Convert flat index to (row, col) + +pair2chr square (x,y) = square !! ((x-1)*5+y-1) + +-- Pairs up elements from a list, used in Bifid encoding process +pairUp :: [a] -> [(a,a)] +pairUp [] = [] +pairUp [a] = error "Odd number of elements" +pairUp (x:y:ys) = (x,y):(pairUp ys) + +encrypt square message = map (pair2chr square) (pairUp (l ++ r)) where + (l,r) = unzip $ map (chr2pair square) message + +decrypt square message = map (pair2chr square) (zip u d) where + (u,d) = splitAt (length message) $ concatMap (\(x,y) -> [x,y]) $ map (chr2pair square) message + +main = do + let + message1 = "ATTACKATDAWN" + message2 = "FLEEATONCE" + encrypt1 = encrypt rcBifid message1 + encrypt2 = encrypt wikiBifid message2 + encrypt3 = encrypt wikiBifid message1 + myMessage = "The invasion will start on the first of January" + encrypt4 = encrypt cmiBifid $ map toUpper $ filter (/= ' ') myMessage -- Remove spaces, uppercase + + putStrLn $ "Message 1: " ++ message1 + putStrLn $ "Encryption wrt RC's square: " ++ encrypt1 + putStrLn $ "Decrypt: " ++ show (decrypt rcBifid encrypt1) + + putStrLn $ "Message 2: " ++ message2 + putStrLn $ "Encryption wrt Wiki's square: " ++ encrypt2 + putStrLn $ "Decrypt: " ++ show (decrypt wikiBifid encrypt2) + + putStrLn $ "Message 3: " ++ message1 + putStrLn $ "Encryption wrt Wiki's square: " ++ encrypt3 + putStrLn $ "Decrypt: " ++ show (decrypt wikiBifid encrypt3) + + putStrLn $ "Message 4: " ++ myMessage + putStrLn $ "Encryption wrt CMI square: " ++ encrypt4 + putStrLn $ "Decrypt: " ++ show (decrypt cmiBifid encrypt4) diff --git a/Task/Bifid-cipher/Java/bifid-cipher.java b/Task/Bifid-cipher/Java/bifid-cipher.java index a4a88f3db9..90b4f09174 100644 --- a/Task/Bifid-cipher/Java/bifid-cipher.java +++ b/Task/Bifid-cipher/Java/bifid-cipher.java @@ -7,101 +7,101 @@ import java.util.Map; public final class BifidCipher { - public static void main(String[] aArgs) { - final String message1 = "ATTACKATDAWN"; - final String message2 = "FLEEATONCE"; - final String message3 = "The invasion will start on the first of January".toUpperCase().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 aBifid, String aMessage) { - System.out.println("Using Polybius square:"); - aBifid.display(); - System.out.println("Message: " + aMessage); - String encrypted = aBifid.encrypt(aMessage); - System.out.println("Encrypted: " + encrypted); - String decrypted = aBifid.decrypt(encrypted); - System.out.println("Decrypted: " + decrypted); - System.out.println(); - } - + public static void main(String[] aArgs) { + final String message1 = "ATTACKATDAWN"; + final String message2 = "FLEEATONCE"; + final String message3 = "The invasion will start on the first of January".toUpperCase().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 aBifid, String aMessage) { + System.out.println("Using Polybius square:"); + aBifid.display(); + System.out.println("Message: " + aMessage); + String encrypted = aBifid.encrypt(aMessage); + System.out.println("Encrypted: " + encrypted); + String decrypted = aBifid.decrypt(encrypted); + System.out.println("Decrypted: " + decrypted); + System.out.println(); + } + } - + final class Bifid { - - public Bifid(int aN, String aText) { - if ( aText.length() != aN * aN ) { - throw new IllegalArgumentException("Incorrect length of text"); - } - - grid = new char[aN][aN]; - int row = 0; - int col = 0; - for ( char ch : aText.toCharArray() ) { - grid[row][col] = ch; - coordinates.put(ch, new Point(row, col) ); - col += 1; - if ( col == aN ) { - col = 0; - row += 1; - } - } - - if ( aN == 5 ) { - coordinates.put('J', coordinates.get('I')); - } - } - - public String encrypt(String aText) { - List rowOne = new ArrayList(); - List rowTwo = new ArrayList(); - for ( char ch : aText.toCharArray() ) { - Point coordinate = coordinates.get(ch); - rowOne.add(coordinate.x); - rowTwo.add(coordinate.y); - } - - rowOne.addAll(rowTwo); - StringBuilder result = new StringBuilder(); - for ( int i = 0; i < rowOne.size() - 1; i += 2 ) { - result.append(grid[rowOne.get(i)][rowOne.get(i + 1)]); - } - return result.toString(); - } - - public String decrypt(String aText) { - List row = new ArrayList(); - for ( char ch : aText.toCharArray() ) { - Point coordinate = coordinates.get(ch); - row.add(coordinate.x); - row.add(coordinate.y); - } - - final int middle = row.size() / 2; - List rowOne = row.subList(0, middle); - List rowTwo = row.subList(middle, row.size()); - StringBuilder result = new StringBuilder(); - for ( int i = 0; i < middle; i++ ) { - result.append(grid[rowOne.get(i)][rowTwo.get(i)]); - } - return result.toString(); - } + + public Bifid(int aN, String aText) { + if ( aText.length() != aN * aN ) { + throw new IllegalArgumentException("Incorrect length of text"); + } + + grid = new char[aN][aN]; + int row = 0; + int col = 0; + for ( char ch : aText.toCharArray() ) { + grid[row][col] = ch; + coordinates.put(ch, new Point(row, col) ); + col += 1; + if ( col == aN ) { + col = 0; + row += 1; + } + } + + if ( aN == 5 ) { + coordinates.put('J', coordinates.get('I')); + } + } + + public String encrypt(String aText) { + List rowOne = new ArrayList(); + List rowTwo = new ArrayList(); + for ( char ch : aText.toCharArray() ) { + Point coordinate = coordinates.get(ch); + rowOne.add(coordinate.x); + rowTwo.add(coordinate.y); + } + + rowOne.addAll(rowTwo); + StringBuilder result = new StringBuilder(); + for ( int i = 0; i < rowOne.size() - 1; i += 2 ) { + result.append(grid[rowOne.get(i)][rowOne.get(i + 1)]); + } + return result.toString(); + } + + public String decrypt(String aText) { + List row = new ArrayList(); + for ( char ch : aText.toCharArray() ) { + Point coordinate = coordinates.get(ch); + row.add(coordinate.x); + row.add(coordinate.y); + } + + final int middle = row.size() / 2; + List rowOne = row.subList(0, middle); + List rowTwo = row.subList(middle, row.size()); + StringBuilder result = new StringBuilder(); + for ( int i = 0; i < middle; i++ ) { + result.append(grid[rowOne.get(i)][rowTwo.get(i)]); + } + return result.toString(); + } public void display() { - Arrays.stream(grid).forEach( row -> System.out.println(Arrays.toString(row)) ); - } - - private char[][] grid; - private Map coordinates = new HashMap(); - + Arrays.stream(grid).forEach( row -> System.out.println(Arrays.toString(row)) ); + } + + private char[][] grid; + private Map coordinates = new HashMap(); + } diff --git a/Task/Bifid-cipher/JavaScript/bifid-cipher.js b/Task/Bifid-cipher/JavaScript/bifid-cipher.js new file mode 100644 index 0000000000..a4f210b4c0 --- /dev/null +++ b/Task/Bifid-cipher/JavaScript/bifid-cipher.js @@ -0,0 +1,199 @@ +// ADFGVX Cipher Implementation in JavaScript + +// Cipher squares +const squareRosetta = [ // from Rosetta Code + ['A', 'B', 'C', 'D', 'E'], + ['F', 'G', 'H', 'I', 'K'], + ['L', 'M', 'N', 'O', 'P'], + ['Q', 'R', 'S', 'T', 'U'], + ['V', 'W', 'X', 'Y', 'Z'], + ['J', '1', '2', '3', '4'] +]; + +const squareWikipedia = [ // from Wikipedia + ['B', 'G', 'W', 'K', 'Z'], + ['Q', 'P', 'N', 'D', 'S'], + ['I', 'O', 'A', 'X', 'E'], + ['F', 'C', 'L', 'U', 'M'], + ['T', 'H', 'Y', 'V', 'R'], + ['J', '1', '2', '3', '4'] +]; + +// Test text strings +const textRosetta = "0ATTACKATDAWN"; +const textRosettaEncoded = "DQBDAXDQPDQH"; // only for test +const textWikipedia = "FLEEATONCE"; +const textWikipediaEncoded = "UAEOLWRINS"; // only for test +const textTest = "The invasion will start on the first of January"; +const textTestEncoded = "RASOAQXFIOORXESXADETSWLTNIAZQOISBRGBALY"; // only for test + +// Coordinate class (equivalent to koord struct in Go) +class Coord { + constructor(x, y) { + this.x = x; + this.y = y; + } + + lessThan(other) { + if (this.y > other.y) { + return false; + } + if (this.y < other.y) { + return true; + } + if (this.x < other.x) { + return true; + } + return false; + } + + equalTo(other) { + return this.x === other.x && this.y === other.y; + } +} + +// Convert square to encryption and decryption maps +function squareToMaps(square) { + const encryptMap = new Map(); + const decryptMap = new Map(); + + for (let x = 0; x < square.length; x++) { + for (let y = 0; y < square[x].length; y++) { + const value = square[x][y]; + const coord = new Coord(x, y); + + // For encryption map, use character as key + encryptMap.set(value, coord); + + // For decryption map, use coordinate string as key + // (JavaScript Maps can't use objects as keys directly, so convert to string) + decryptMap.set(`${x},${y}`, value); + } + } + + return { encryptMap, decryptMap }; +} + +// Remove spaces and non-valid characters +function removeSpace(text, encryptMap) { + const upper = text.toUpperCase().replace(/\s/g, ''); + let result = ''; + + for (const char of upper) { + if (encryptMap.has(char)) { + result += char; + } + } + + return result; +} + +// Replace 'J' with 'I' (for specific Polybius square implementations) +function removeSpaceI(text) { + const upper = text.toUpperCase(); + let result = ''; + + for (const char of upper) { + // Use only ASCII characters from A to Z + if (char >= 'A' && char <= 'Z') { + result += char === 'J' ? 'I' : char; + } + } + + return result; +} + +// Encrypt using ADFGVX cipher +function encrypt(text, encryptMap, decryptMap) { + text = removeSpace(text, encryptMap); + + const row0 = []; + const row1 = []; + + // Get coordinates for each character + for (const char of text) { + const coord = encryptMap.get(char); + row0.push(coord.x); + row1.push(coord.y); + } + + // Combine coordinates + const combined = [...row0, ...row1]; + + let result = ''; + // Convert pairs of coordinates back to characters + for (let i = 0; i < combined.length; i += 2) { + const key = `${combined[i]},${combined[i+1]}`; + result += decryptMap.get(key); + } + + return result; +} + +// Decrypt using ADFGVX cipher +function decrypt(text, encryptMap, decryptMap) { + text = removeSpace(text, encryptMap); + + const coords = []; + + // Get coordinates for each character + for (const char of text) { + coords.push(encryptMap.get(char)); + } + + // Extract x and y values + const flatCoords = []; + for (const coord of coords) { + flatCoords.push(coord.x); + flatCoords.push(coord.y); + } + + const half = Math.floor(flatCoords.length / 2); + const firstHalf = flatCoords.slice(0, half); + const secondHalf = flatCoords.slice(half); + + let result = ''; + + // Recombine coordinates to get original text + for (let i = 0; i < firstHalf.length; i++) { + const key = `${firstHalf[i]},${secondHalf[i]}`; + result += decryptMap.get(key); + } + + return result; +} + +// Main function to test +function main() { + // Test with Rosetta square + let { encryptMap, decryptMap } = squareToMaps(squareRosetta); + + console.log("From Rosetta Code"); + console.log("original:\t", textRosetta); + let encoded = encrypt(textRosetta, encryptMap, decryptMap); + console.log("encoded:\t", encoded); + let decoded = decrypt(encoded, encryptMap, decryptMap); + console.log("and back:\t", decoded); + + // Test with Wikipedia square + ({ encryptMap, decryptMap } = squareToMaps(squareWikipedia)); + + console.log("\nFrom Wikipedia"); + console.log("original:\t", textWikipedia); + encoded = encrypt(textWikipedia, encryptMap, decryptMap); + console.log("encoded:\t", encoded); + decoded = decrypt(encoded, encryptMap, decryptMap); + console.log("and back:\t", decoded); + + // Test with longer text + console.log("\nFrom Rosetta Code (longer text)"); + console.log("original:\t", textTest); + encoded = encrypt(textTest, encryptMap, decryptMap); + console.log("encoded:\t", encoded); + // Note: If the text has an odd number of letters, the algorithm doesn't work! + decoded = decrypt(encoded, encryptMap, decryptMap); + console.log("and back:\t", decoded); +} + +// Run the main function +main(); diff --git a/Task/Bifid-cipher/Jq/bifid-cipher-2.jq b/Task/Bifid-cipher/Jq/bifid-cipher-2.jq index 9d4b6f076c..6eabe468da 100644 --- a/Task/Bifid-cipher/Jq/bifid-cipher-2.jq +++ b/Task/Bifid-cipher/Jq/bifid-cipher-2.jq @@ -48,7 +48,7 @@ def task: | ($encrypted | decrypt(polys[$i] )) as $decrypted | "Message : \(.)", "Encrypted : \($encrypted)", - "Decrypted : \($decrypted)" + "Decrypted : \($decrypted)", "" ; task diff --git a/Task/Bifid-cipher/Julia/bifid-cipher.julia b/Task/Bifid-cipher/Julia/bifid-cipher.jl similarity index 100% rename from Task/Bifid-cipher/Julia/bifid-cipher.julia rename to Task/Bifid-cipher/Julia/bifid-cipher.jl diff --git a/Task/Bifid-cipher/Kotlin/bifid-cipher.kotlin b/Task/Bifid-cipher/Kotlin/bifid-cipher.kts similarity index 100% rename from Task/Bifid-cipher/Kotlin/bifid-cipher.kotlin rename to Task/Bifid-cipher/Kotlin/bifid-cipher.kts diff --git a/Task/Bifid-cipher/M2000-Interpreter/bifid-cipher.m2000 b/Task/Bifid-cipher/M2000-Interpreter/bifid-cipher.m2000 new file mode 100644 index 0000000000..b0234f8353 --- /dev/null +++ b/Task/Bifid-cipher/M2000-Interpreter/bifid-cipher.m2000 @@ -0,0 +1,68 @@ +module Bifid_cipher (f, code$) { + n=sqrt(len(code$)) + print #f," "; + for i=1 to n + print #f, i+" "; + next + print #f + for i=0 to n-1 + Print #f, (i+1)+" "+STR$(mid$(code$,1+i*n, n),STRING$("@ ", 5)) + next + tables=lambda (a$)->{ + n=sqrt(len(a$)) + a=list + for i=1 to len(a$) + append a, mid$(a$,i, 1):=((i-1) mod n+1, (i-1) div n+1 ) + next + b=list + m=each(a) + while m + z=eval(m) + append b, z#val$(1)+z#val$(0):=eval$(m!) + end while + =a, b + }(code$) + encode= lambda (a, b)->{ + =lambda a,b (mess as string) -> { + document code$ + for n=1 to 0 + for i=1 to len(mess) + q=mid$(mess, i,1) + if not exist(a, q) then + if q="J" then q="I" else q="A" + end if + code$=a(q)#val$(n) + next + next + document final$ + for i=1 to len(code$) step 2 + final$=b$(mid$(code$, i, 2)) + next + = final$ + } + }(!tables) + decode= lambda (a, b)->{ + =lambda a,b (final as string) -> { + document code$, mess$ + for i=1 to len(final) + q=a(mid$(final, i, 1)) + code$=q#val$(1)+q#val$(0) + next + offset=len(code$) div 2 + for i=1 to offset + mess$=b$(mid$(code$,i,1)+mid$(code$,i+offset,1)) + next + = mess$ + } + }(!tables) + Print #f, encode("ATTACKATDAWN") + Print #f, decode(encode("ATTACKATDAWN"))="ATTACKATDAWN" + Print #f, encode(ucase$(filter$("The invasion will start on the first of January", " "))) + Print #f, decode(encode(ucase$(filter$("The invasion will start on the first of January", " ")))) +} +open "out.txt" for output as #a +Bifid_cipher a, "ABCDEFGHIKLMNOPQRSTUVWXYZ" +Bifid_cipher a, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" +Bifid_cipher a, "BGWKZQPNDSIOAXEFCLUMTHYVR" +close #a +win "out.txt" diff --git a/Task/Bifid-cipher/PascalABC.NET/bifid-cipher.pas b/Task/Bifid-cipher/PascalABC.NET/bifid-cipher.pas new file mode 100644 index 0000000000..4440353bf4 --- /dev/null +++ b/Task/Bifid-cipher/PascalABC.NET/bifid-cipher.pas @@ -0,0 +1,28 @@ +// Bifid cipher. Nigel Galloway: September 18th., 2024 +function polybius(alphabet:string;n,g:integer):(Dictionary,Dictionary<(integer,integer),char>); +begin + var ng:=Cartesian(1..n,1..g); + Result:=(Dict(Zip(alphabet,ng)),Dict(Zip(ng,alphabet))); +end; +function fN(e:Dictionary;n:string):(sequence of integer,sequence of integer):=(n.Substring(1).Scan(e[n[1]],(n,g)->e[g])).UnZipTuple; +function encrypt(e:(Dictionary,Dictionary<(integer,integer),char>);text:string):string; +begin + var fG:((sequence of integer,sequence of integer),Dictionary<(integer,integer),char>)->string:=(n,e)->(n[0]+n[1]).Batch(2).Aggregate('',(n,g)->n+e[(g[0],g[1])]); + Result:=fG(fN(e[0],text),e[1]); +end; +function decrypt(e:(Dictionary,Dictionary<(integer,integer),char>);text:string):string; +begin + var fG:(sequence of (integer,integer),Dictionary<(integer,integer),char>)->string:=(n,e)->n.Aggregate('',(n,g)->n+e[(g[0],g[1])]); + var t:=fN(e[0],text); var z:=t[0].Interleave(t[1]).SplitAt(t[0].count); + Result:=fG(z[0].ZipTuple(z[1]),e[1]); +end; +begin + var p:=polybius('abcdefghiklmnopqrstuvwxyz',5,5); var s,e:string; + s:='fleeatonce'; e:=encrypt(p,s); println($'{s} -> {e} -> {decrypt(p,e)}'); + s:='attackatdawn'; e:=encrypt(p,s); println($'{s} -> {e} -> {decrypt(p,e)}'); + p:=polybius('bgwkzqpndsioaxefclumthyvr',5,5); + e:=encrypt(p,s); println($'{s} -> {e} -> {decrypt(p,e)}'); + s:='fleeatonce'; e:=encrypt(p,s); println($'{s} -> {e} -> {decrypt(p,e)}'); + p:=polybius('abcdefghijklmnopqrstuvwxyz0123456789',6,6); + s:='theinvasionwillstarton1january2025'; e:=encrypt(p,s); println($'{s} -> {e} -> {decrypt(p,e)}'); +end. diff --git a/Task/Bifid-cipher/Phix/bifid-cipher.phix b/Task/Bifid-cipher/Phix/bifid-cipher.phix index 57af305806..e1aa112fda 100644 --- a/Task/Bifid-cipher/Phix/bifid-cipher.phix +++ b/Task/Bifid-cipher/Phix/bifid-cipher.phix @@ -1,41 +1,39 @@ -(phixonline)--> - with javascript_semantics - enum encrypt,decrypt - function bifid(string msg, polybius, sequence p, integer n, ed) - string res = "" - sequence dx = {}, dy = {}, dxy - for i=1 to length(msg) do - integer k = find(msg[i],polybius)-1 - dx &= floor(k/n)+1 - dy &= remainder(k,n)+1 - end for - if ed=encrypt then - dxy = split_by(dx&dy,2) - else - -- "simply reversing these steps" - yeah, right... - dxy = columnize(split_by(flatten(columnize({dx,dy})),length(dx))) - end if - for i=1 to length(dxy) do - integer {x,y} = dxy[i] - res &= p[x][y] - end for - return res - end function +with javascript_semantics +enum encrypt,decrypt +function bifid(string msg, polybius, sequence p, integer n, ed) + string res = "" + sequence dx = {}, dy = {}, dxy + for i=1 to length(msg) do + integer k = find(msg[i],polybius)-1 + dx &= floor(k/n)+1 + dy &= remainder(k,n)+1 + end for + if ed=encrypt then + dxy = split_by(dx&dy,2) + else + -- "simply reversing these steps" - yeah, right... + dxy = columnize(split_by(flatten(columnize({dx,dy})),length(dx))) + end if + for i=1 to length(dxy) do + integer {x,y} = dxy[i] + res &= p[x][y] + end for + return res +end function - procedure test(string msg, polybius) - integer n = sqrt(length(polybius)) - if n=5 then msg = substitute(upper(msg),"J","I") end if - sequence p = split_by(polybius,n) - string enc = bifid(msg,polybius,p,n,encrypt), - dec = bifid(enc,polybius,p,n,decrypt) - printf(1,"For %dx%d polybius %s\n\n",{n,n,join(p,"\n ")}) - printf(1,"Message : %s\nEncrypted: %s\nDecrypted: %s\n\n",{msg,enc,dec}) - end procedure +procedure test(string msg, polybius) + integer n = sqrt(length(polybius)) + if n=5 then msg = substitute(upper(msg),"J","I") end if + sequence p = split_by(polybius,n) + string enc = bifid(msg,polybius,p,n,encrypt), + dec = bifid(enc,polybius,p,n,decrypt) + printf(1,"For %dx%d polybius %s\n\n",{n,n,join(p,"\n ")}) + printf(1,"Message : %s\nEncrypted: %s\nDecrypted: %s\n\n",{msg,enc,dec}) +end procedure - constant polybii = {tagstart('A','J'-'A')&tagstart('K','Z'-'J'), - "BGWKZQPNDSIOAXEFCLUMTHYVR", - " ."&tagstart('A',26)&tagstart('a',26)&tagstart('0',10)}, - messages = {"ATTACKATDAWN","FLEEATONCE", - "The invasion will start on the first of January 2023."} - for t=1 to 3 do test(messages[t],polybii[t]) end for - - with javascript_semantics - function bin_it(sequence limits, data) - -- Bin data according to (ascending) limits. - sequence bins = repeat(0,length(limits)+1) -- adds under/over range bins too - for i=1 to length(data) do - integer bdx = binary_search(data[i],limits) - bdx = abs(bdx)+(bdx>0) - bins[bdx] += 1 - end for - return bins - end function +with javascript_semantics +function bin_it(sequence limits, data) + -- Bin data according to (ascending) limits. + sequence bins = repeat(0,length(limits)+1) -- adds under/over range bins too + for i=1 to length(data) do + integer bdx = binary_search(data[i],limits) + bdx = abs(bdx)+(bdx>0) + bins[bdx] += 1 + end for + return bins +end function - procedure bin_print(sequence limits, bins) - printf(1," < %3d := %3d\n",{limits[1],bins[1]}) - for i=2 to length(limits) do - printf(1,">= %3d and < %3d := %3d\n",{limits[i-1],limits[i],bins[i]}) - end for - printf(1,">= %3d := %3d\n\n",{limits[$],bins[$]}) - end procedure +procedure bin_print(sequence limits, bins) + printf(1," < %3d := %3d\n",{limits[1],bins[1]}) + for i=2 to length(limits) do + printf(1,">= %3d and < %3d := %3d\n",{limits[i-1],limits[i],bins[i]}) + end for + printf(1,">= %3d := %3d\n\n",{limits[$],bins[$]}) +end procedure - sequence limits, data - printf(1,"Example 1:\n") - limits = {23, 37, 43, 53, 67, 83} - data = {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} - bin_print(limits, bin_it(limits, data)) +sequence limits, data +printf(1,"Example 1:\n") +limits = {23, 37, 43, 53, 67, 83} +data = {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} +bin_print(limits, bin_it(limits, data)) - printf(1,"Example 2:\n") - limits = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720} - data = {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} - bin_print(limits, bin_it(limits, data)) - - with javascript_semantics - string s = "abc" - s = x"ef bb bf" -- explicit binary string (the utf8 BOM) - s[2] = 0 - s[3] = 'z' - if s="\#EF\0z" then puts(1,"ok\n") end if - string t = s - t[1..2] = "xy" -- s remains unaltered - ?t -- "xyz" - t = "food" ?t - t[2..3] = 'e' ?t -- "feed" - t[3..2] = "ast" ?t -- "feasted" - t[3..-2] = "" ?t -- "fed" - if length(t)=0 then puts(1,"t is empty\n") end if - if t!="" then puts(1,"t is not empty\n") end if - t = "be" - t &= 't' ?t -- bet - t = 'a'&t ?t -- abet - ?t[2..3] -- be - ?substitute(t,"be","bbo") -- abbot - ?substitute(t,"be","dep") -- adept - t = substitute(t,"be","dep") -- to actually modify t - ?join({"abc","def","ghi"}) -- "abc def ghi" - ?join({"abc","def","ghi"},"") -- "abcdefghi" - ?join({"abc","def","ghi"},"\n") -- "abc\ndef\nghi" - DNA - -{def base_count - {def base_count.r - {lambda {:dna :b :n :i :count} - {if {> :i :n} - then :count - else {base_count.r :dna :b :n {+ :i 1} - {if {W.equal? {W.get :i :dna} :b} - then {+ :count 1} - else :count}} }}} - {lambda {:dna :b} - {base_count.r :dna :b {- {W.length :dna} 1} 0 0} }} --> base_count - -{def S {S.map {base_count {DNA}}} A C G T}} --> S -[A C G T] = (129 97 119 155) - -A+C+G+T = {+ {S}} --> A+C+G+T = 500 diff --git a/Task/Bioinformatics-base-count/Lua/bioinformatics-base-count.lua b/Task/Bioinformatics-base-count/Lua/bioinformatics-base-count.lua deleted file mode 100644 index 13dc7d2a11..0000000000 --- a/Task/Bioinformatics-base-count/Lua/bioinformatics-base-count.lua +++ /dev/null @@ -1,27 +0,0 @@ -function prettyprint(seq) -- approx DDBJ format - seq = seq:gsub("%A",""):lower() - local sums, n = { a=0, c=0, g=0, t=0 }, 1 - seq:gsub("(%a)", function(c) sums[c]=sums[c]+1 end) - local function printf(s,...) io.write(s:format(...)) end - printf("LOCUS AB000000 %12d bp mRNA linear HUM 01-JAN-2001\n", #seq) - printf(" BASE COUNT %12d a %12d c %12d g %12d t\n", sums.a, sums.c, sums.g, sums.t) - printf("ORIGIN\n") - while n < #seq do - local sub60 = seq:sub(n,n+59) - printf("%9d %s\n", n, sub60:gsub("(..........)","%1 ")) - n = n + #sub60 - end -end - -prettyprint[[ -CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG -CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG -AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT -GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT -CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG -TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA -TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT -CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG -TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC -GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT -]] diff --git a/Task/Bioinformatics-base-count/MATLAB/bioinformatics-base-count.m b/Task/Bioinformatics-base-count/MATLAB/bioinformatics-base-count.m deleted file mode 100644 index 12c2f553f4..0000000000 --- a/Task/Bioinformatics-base-count/MATLAB/bioinformatics-base-count.m +++ /dev/null @@ -1,13 +0,0 @@ -function r = base_count(f) - fid = fopen(f,'r'); - nn=[0,0,0,0]; - while ~feof(fid) - s = fgetl(fid); - fprintf(1,'%5d :%s\n', sum(nn), s(s=='A'|s=='C'|s=='G'|s=='T')); - nn = nn+[sum(s=='A'),sum(s=='C'),sum(s=='G'),sum(s=='T')]; - end - fclose(fid); - - fprintf(1, '\nBases:\n\n A : %d\n C : %d\n G : %d\n T : %d\n', nn); - fprintf(1, '\nTotal: %d\n\n', sum(nn)); -end; diff --git a/Task/Bioinformatics-base-count/Mathematica/bioinformatics-base-count.math b/Task/Bioinformatics-base-count/Mathematica/bioinformatics-base-count.math deleted file mode 100644 index c4ace88df1..0000000000 --- a/Task/Bioinformatics-base-count/Mathematica/bioinformatics-base-count.math +++ /dev/null @@ -1,14 +0,0 @@ -seq = "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCA\ -ATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGC\ -AATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGA\ -TTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTC\ -TTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTT\ -AGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAA\ -TGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGT\ -TAAACTACGAACGTAAT"; -size = 70; -parts = StringPartition[seq, UpTo[size]]; -begins = Most[Accumulate[Prepend[StringLength /@ parts, 1]]]; -ends = Rest[Accumulate[Prepend[StringLength /@ parts, 0]]]; -StringRiffle[MapThread[ToString[#1] <> "-" <> ToString[#2] <> ": " <> #3 &, {begins, ends, parts}], "\n"] -StringRiffle[#1 <> ": " <> ToString[#2] & @@@ Tally[Characters[seq]], "\n"] diff --git a/Task/Bioinformatics-base-count/Nim/bioinformatics-base-count.nim b/Task/Bioinformatics-base-count/Nim/bioinformatics-base-count.nim deleted file mode 100644 index db0e61d7be..0000000000 --- a/Task/Bioinformatics-base-count/Nim/bioinformatics-base-count.nim +++ /dev/null @@ -1,59 +0,0 @@ -import strformat -import strutils - -const Source = "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" & - "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" & - "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" & - "GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" & - "CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" & - "TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" & - "TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" & - "CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" & - "TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" & - "GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT" - -# Enumeration type for bases. -type Base* {.pure.} = enum A, C, G, T, Other = "other" - -proc display*(dnaSeq: string) = - ## Display a DNA sequence using EMBL format. - - var counts: array[Base, Natural] # Count of bases. - for c in dnaSeq: - inc counts[parseEnum[Base]($c, Other)] # Use Other as default value. - - # Display the SQ line. - var sqline = fmt"SQ {dnaSeq.len} BP; " - for (base, count) in counts.pairs: - sqline &= fmt"{count} {base}; " - echo sqline - - # Display the sequence. - var idx = 0 - var row = newStringOfCap(80) - var remaining = dnaSeq.len - - while remaining > 0: - row.setLen(0) - row.add(" ") - - # Add groups of 10 bases. - for group in 1..6: - let nextIdx = idx + min(10, remaining) - row.add(dnaSeq[idx..8}") - echo row - - # Add termination. - echo "//" - - -when isMainModule: - Source.display() diff --git a/Task/Bioinformatics-base-count/Pascal/bioinformatics-base-count.pas b/Task/Bioinformatics-base-count/Pascal/bioinformatics-base-count.pas deleted file mode 100644 index 541e8e1eca..0000000000 --- a/Task/Bioinformatics-base-count/Pascal/bioinformatics-base-count.pas +++ /dev/null @@ -1,77 +0,0 @@ -program DNA_Base_Count; -{$IFDEF FPC} - {$MODE DELPHI}//String = AnsiString -{$ELSE} - {$APPTYPE CONSOLE} -{$ENDIF} -const - dna = - 'CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG' + - 'CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG' + - 'AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT' + - 'GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT' + - 'CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG' + - 'TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA' + - 'TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT' + - 'CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG' + - 'TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC' + - 'GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT'; -var - CntIdx : array of NativeUint; - DNABases : String; - SumBaseTotal : NativeInt; - -procedure OutFormatBase(var DNA: String;colWidth:NativeInt); -var - j: NativeInt; -Begin - j := 0; - Writeln(' DNA base sequence'); - While j) { - chomp; - printf "%4d: %s\n", $total+1, s/(.{10})/$1 /gr; - $total += length; - $cnt{$_}++ for split // -} - -say "\nTotal bases: $total"; -say "$_: " . ($cnt{$_}//0) for ; - -__DATA__ -CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG -CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG -AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT -GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT -CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG -TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA -TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT -CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG -TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC -GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT diff --git a/Task/Bioinformatics-base-count/Phix/bioinformatics-base-count.phix b/Task/Bioinformatics-base-count/Phix/bioinformatics-base-count.phix deleted file mode 100644 index ff060d39d4..0000000000 --- a/Task/Bioinformatics-base-count/Phix/bioinformatics-base-count.phix +++ /dev/null @@ -1,24 +0,0 @@ -(phixonline)--> - constant dna = substitute(""" - CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG - CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG - AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT - GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT - CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG - TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA - TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT - CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG - TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC - GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT - ""","\n","") - sequence acgt = repeat(0,5) - for i=1 to length(dna) do - acgt[find(dna[i],"ACGT")] += 1 - end for - acgt[$] = sum(acgt) - sequence s = split(trim(join_by(split(join_by(dna,1,10,""),"\n"),1,5," ")),"\n") - for i=1 to length(s) do - printf(1,"%3d: %s\n",{(i-1)*50+1,s[i]}) - end for - printf(1,"\nBase counts: A:%d, C:%d, G:%d, T:%d, total:%d\n",acgt) - $ ) - - [ 0 swap - [ dup $ "" != while - cr over number$ - 4 justify echo$ - 5 times - [ dup $ "" = iff - conclude done - sp - 10 split swap echo$ ] - dip [ 50 + ] again ] - 2drop ] is prettyprint ( $ --> ) - - [ stack ] is adenine ( --> s ) - [ stack ] is cytosine ( --> s ) - [ stack ] is guanine ( --> s ) - [ stack ] is thymine ( --> s ) - - [ table - adenine cytosine - guanine thymine ] is bases ( --> [ ) - - [ 4 times - [ 0 i^ bases put ] - witheach - [ $ "ACGT" find bases - 1 swap tally ] - 4 times - [ sp - i^ bases dup echo - sp share echo cr ] - 0 4 times - [ i^ bases take + ] - cr say " total " echo ] is tallybases ( [ --> ) - - $ "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" - $ "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" join - $ "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" join - $ "GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" join - $ "CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" join - $ "TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" join - $ "TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" join - $ "CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" join - $ "TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" join - $ "GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT" join - - dup prettyprint cr cr tallybases diff --git a/Task/Bioinformatics-base-count/R/bioinformatics-base-count.r b/Task/Bioinformatics-base-count/R/bioinformatics-base-count.r deleted file mode 100644 index 7a6b6c1221..0000000000 --- a/Task/Bioinformatics-base-count/R/bioinformatics-base-count.r +++ /dev/null @@ -1,42 +0,0 @@ -#Data -gene1 <- "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG -CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG -AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT -GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT -CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG -TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA -TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT -CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG -TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC -GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT" - -#Analysis: -gene2 <- gsub("\n", "", gene1) #remove \n chars -gene3 <- strsplit(gene2, split = character(0)) #split into list -gene4 <- gene3[[1]] #pull out character vector from list -basecounts <- as.data.frame(table(gene4)) #make table of base counts - -#quick helper function to print table results -print_row <- function(df, row){paste0(df$gene[row],": ", df$Freq[row])} - -#Print Function for Data with Results: -cat(" Data: \n", - " 1:",substring(gene2, 1, 50),"\n", - " 51:",substring(gene2, 51, 100),"\n", - "101:",substring(gene2, 101, 150),"\n", - "151:",substring(gene2, 151, 200),"\n", - "201:",substring(gene2, 201, 250),"\n", - "251:",substring(gene2, 251, 300),"\n", - "301:",substring(gene2, 301, 350),"\n", - "351:",substring(gene2, 351, 400),"\n", - "401:",substring(gene2, 401, 450),"\n", - "451:",substring(gene2, 451, 500),"\n", - "\n", - "Base Count Results: \n", - print_row(basecounts,1), "\n", - print_row(basecounts,2), "\n", - print_row(basecounts,3), "\n", - print_row(basecounts,4), "\n", - "\n", - "Total Base Count:", paste(length(gene4)) - ) diff --git a/Task/Bioinformatics-base-count/REXX/bioinformatics-base-count.rexx b/Task/Bioinformatics-base-count/REXX/bioinformatics-base-count.rexx deleted file mode 100644 index 99c88e767b..0000000000 --- a/Task/Bioinformatics-base-count/REXX/bioinformatics-base-count.rexx +++ /dev/null @@ -1,36 +0,0 @@ -/*REXX program finds the number of each base in a DNA string */ -/* (along with a total). */ -Parse Arg dna . -If dna==''|dna==',' Then - dna='cgtaaaaaattacaacgtcctttggctatctcttaaactcctgctaaatg', - 'ctcgtgctttccaattatgtaagcgttccgagacggggtggtcgattctg', - 'aggacaaaggtcaagatggagcgcatcgaacgcaataaggatcatttgat', - 'gggacgtttcgtcgacaaagtcttgtttcgagagtaacggctaccgtctt', - 'cgattctgcttataacactatgttcttatgaaatggatgttctgagttgg', - 'tcagtcccaatgtgcggggtttcttttagtacgtcgggagtggtattata', - 'tttaatttttctatatagcgatctgtatttaagcaattcatttaggttat', - 'cgccgcgatgctcggttcggaccgccaagcatctggctccactgctagtg', - 'tcctaaatttgaatggcaaacacaaataagatttagcaattcgtgtagac', - 'gaccggggacttgcatgatgggagcagctttgttaaactacgaacgtaat' -dna=translate(space(dna,0)) /* elide blanks from DNA; uppercas*/ -Say '--------length of the DNA string: ' length(dna) -count.=0 /* initialize the count for all bases*/ -w=1 /* the maximum width of a base count */ -names='' /* list of all names */ -Do j=1 To length(dna) /* traipse through the DNA string */ - name=substr(dna,j,1) /* obtain a base name from the DNA */ - If pos(name,names)==0 Then - names=names||name /* if not found, add it to the list */ - count.name=count.name+1 /* bump the count of this base. */ - w=max(w,length(count.name)) /* compute the maximum number width */ - End -Say -Do k=0 To 255 - z=d2c(k) /* traipse through all possibilities */ - If pos(z,names)>0 Then Do - Say ' base ' z ' has a basecount of: ' right(count.z,w) - count.tot=count.tot+count.z /* add to a grand total to verify */ - End - End -Say -Say '--------total for all basecounts:' right(count.tot,w+1) diff --git a/Task/Bioinformatics-base-count/Racket/bioinformatics-base-count.rkt b/Task/Bioinformatics-base-count/Racket/bioinformatics-base-count.rkt deleted file mode 100644 index b0614e6269..0000000000 --- a/Task/Bioinformatics-base-count/Racket/bioinformatics-base-count.rkt +++ /dev/null @@ -1,55 +0,0 @@ -#lang racket - -(define (fold-sequence seq kons #:finalise (finalise (λ x (apply values x))) . k0s) - (define (recur seq . ks) - (if (null? seq) - (call-with-values (λ () (apply finalise ks)) (λ vs (apply values vs))) - (call-with-values (λ () (apply kons (car seq) ks)) (λ ks+ (apply recur (cdr seq) ks+))))) - (apply recur (if (string? seq) (string->list (regexp-replace* #px"[^ACGT]" seq "")) seq) k0s)) - -(define (sequence->pretty-printed-string seq) - (define (fmt idx cs-rev) (format "~a: ~a" (~a idx #:width 3 #:align 'right) (list->string (reverse cs-rev)))) - (fold-sequence - seq - (λ (b n start-idx lns-rev cs-rev) - (if (zero? (modulo n 50)) - (values (+ n 1) n (if (pair? cs-rev) (cons (fmt start-idx cs-rev) lns-rev) lns-rev) (cons b null)) - (values (+ n 1) start-idx lns-rev (cons b cs-rev)))) - 0 0 null null - #:finalise (λ (n idx lns-rev cs-rev) - (string-join (reverse (if (null? cs-rev) lns-rev (cons (fmt idx cs-rev) lns-rev))) "\n")))) - -(define (count-bases b as cs gs ts n) - (values (+ as (if (eq? b #\A) 1 0)) - (+ cs (if (eq? b #\C) 1 0)) - (+ gs (if (eq? b #\T) 1 0)) - (+ ts (if (eq? b #\G) 1 0)) - (add1 n))) - -(define (bioinformatics-Base_count s) - (define-values (as cs gs ts n) (fold-sequence s count-bases 0 0 0 0 0)) - (printf "SEQUENCE:~%~%~a~%~%" (sequence->pretty-printed-string s)) - (printf "BASE COUNT:~%-----------~%~%~a~%~%" - (string-join (map (λ (c n) (format " ~a :~a" c (~a #:width 4 #:align 'right n))) - '(A T C G) - (list as ts cs gs)) "\n")) - (newline) - (printf "TOTAL: ~a~%" n)) - -(module+ - main - (define the-string - #< = base_count.iter().collect(); // HashMaps can't be sorted, so collect into Vec - base_count.sort_by_key(|bc| bc.0); // Sort bases alphabetically - for (base, count) in base_count.iter() { - println!(" {}: {:3}", base, count); - } - println!(); - println!("Total: {}", total_count); -} diff --git a/Task/Bioinformatics-base-count/Swift/bioinformatics-base-count.swift b/Task/Bioinformatics-base-count/Swift/bioinformatics-base-count.swift deleted file mode 100644 index 22b27dd044..0000000000 --- a/Task/Bioinformatics-base-count/Swift/bioinformatics-base-count.swift +++ /dev/null @@ -1,22 +0,0 @@ -import Foundation - -let dna = """ - CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG - CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG - AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT - GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT - CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG - TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA - TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT - CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG - TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC - GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT - """ - -print("input:\n\(dna)\n") - -let counts = - dna.replacingOccurrences(of: "\n", with: "").reduce(into: [:], { $0[$1, default: 0] += 1 }) - -print("Counts: \(counts)") -print("Total: \(counts.values.reduce(0, +))") diff --git a/Task/Bioinformatics-base-count/Tcl/bioinformatics-base-count.tcl b/Task/Bioinformatics-base-count/Tcl/bioinformatics-base-count.tcl deleted file mode 100644 index 0d691e71c8..0000000000 --- a/Task/Bioinformatics-base-count/Tcl/bioinformatics-base-count.tcl +++ /dev/null @@ -1,28 +0,0 @@ -namespace path ::tcl::mathop - -proc process {data {width 50}} { - set len [string length $data] - set addrwidth [string length [* [/ $len $width] $width]] - for {set i 0} {$i < $len} {incr i $width} { - puts "[format %${addrwidth}u $i] [string range $data $i $i+[- $width 1]]" - } - puts "\nBase count:" - foreach base {A C G T} { - puts "$base [regexp -all $base $data]" - } - puts "Total $len" -} - - -set test [string cat \ - CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG \ - CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG \ - AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT \ - GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT \ - CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG \ - TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA \ - TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT \ - CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG \ - TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC \ - GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT] -process $test 50 diff --git a/Task/Bioinformatics-base-count/V-(Vlang)/bioinformatics-base-count.v b/Task/Bioinformatics-base-count/V-(Vlang)/bioinformatics-base-count.v deleted file mode 100644 index 36e3777cd4..0000000000 --- a/Task/Bioinformatics-base-count/V-(Vlang)/bioinformatics-base-count.v +++ /dev/null @@ -1,37 +0,0 @@ -fn main() { - dna := "" + - "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" + - "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" + - "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" + - "GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" + - "CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" + - "TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" + - "TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" + - "CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" + - "TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" + - "GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT" - - println("SEQUENCE:") - le := dna.len - for i := 0; i < le; i += 50 { - mut k := i + 50 - if k > le { - k = le - } - println("${i:5}: ${dna[i..k]}") - } - mut base_map := map[byte]int{} // allows for 'any' base - for i in 0..le { - base_map[dna[i]]++ - } - mut bases := base_map.keys() - bases.sort() - - println("\nBASE COUNT:") - for base in bases { - println(" $base: ${base_map[base]:3}") - } - println(" ------") - println(" Σ: $le") - println(" ======") -} diff --git a/Task/Bioinformatics-base-count/VBScript/bioinformatics-base-count.vb b/Task/Bioinformatics-base-count/VBScript/bioinformatics-base-count.vb deleted file mode 100644 index 422d98cd55..0000000000 --- a/Task/Bioinformatics-base-count/VBScript/bioinformatics-base-count.vb +++ /dev/null @@ -1,31 +0,0 @@ -b=_ -"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" &_ -"CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" &_ -"AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" &_ -"GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" &_ -"CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" &_ -"TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" &_ -"TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" &_ -"CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" &_ -"TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" &_ -"GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT" - -s="SEQUENCE:" -acnt=0:ccnt=0:gcnt=0:tcnt=0 - -for i=0 to len(b)-1 - if (i mod 30)=0 then s = s & vbcrlf & right(" "& i+1,3)&": " - if (i mod 5)=0 then s=s& " " - m=mid(b,i+1,1) - s=s & m - select case m - case "A":acnt=acnt+1 - case "C":ccnt=ccnt+1 - case "G":gcnt=gcnt+1 - case "T":tcnt=tcnt+1 - case else - wscript.echo "error at ",i+1, m - end select -next -wscript.echo s & vbcrlf -wscript.echo "Count: A="&acnt & " C=" & ccnt & " G=" & gcnt & " T=" & tcnt diff --git a/Task/Bioinformatics-base-count/Wren/bioinformatics-base-count.wren b/Task/Bioinformatics-base-count/Wren/bioinformatics-base-count.wren deleted file mode 100644 index e8b0e06487..0000000000 --- a/Task/Bioinformatics-base-count/Wren/bioinformatics-base-count.wren +++ /dev/null @@ -1,38 +0,0 @@ -import "./fmt" for Fmt -import "./sort" for Sort -import "./iterate" for Stepped - -var dna = "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" + - "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" + - "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" + - "GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" + - "CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" + - "TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" + - "TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" + - "CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" + - "TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" + - "GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT" - -System.print("SEQUENCE:") -var le = dna.count -for (i in Stepped.new(0...le, 50)) { - var k = i + 50 - if (k > le) k = le - System.print("%(Fmt.d(5, i)): %(dna[i...k])") -} -var baseMap = {} // allows for 'any' base -for (i in 0...le) { - var d = dna[i] - var v = baseMap[d] - baseMap[d] = !v ? 1 : v + 1 -} -var bases = baseMap.keys.toList -Sort.quick(bases) - -System.print("\nBASE COUNT:") -for (base in bases) { - System.print(" %(base): %(Fmt.d(3, baseMap[base]))") -} -System.print(" ------") -System.print(" Σ: %(le)") -System.print(" ======") diff --git a/Task/Bioinformatics-base-count/XPL0/bioinformatics-base-count.xpl0 b/Task/Bioinformatics-base-count/XPL0/bioinformatics-base-count.xpl0 deleted file mode 100644 index 2f6adbf6f4..0000000000 --- a/Task/Bioinformatics-base-count/XPL0/bioinformatics-base-count.xpl0 +++ /dev/null @@ -1,35 +0,0 @@ -char Bases; -int Counts(256), Cnt, I, Ch; -[Bases:= " -CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG -CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG -AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT -GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT -CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG -TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA -TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT -CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG -TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC -GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAATx "; - -for I:= 0 to 255 do Counts(I):= 0; -Format(5, 0); -Cnt:= 0; -I:= 0; -loop [repeat Ch:= Bases(I); - I:= I+1; - if Ch = ^x then quit; - Counts(Ch):= Counts(Ch)+1; - ChOut(0, Ch); - until Ch = \LF\$0A; - RlOut(0, float(Cnt)); Text(0, ": "); - Cnt:= Cnt + 50; - ]; -CrLf(0); CrLf(0); -Text(0, "Base counts A: "); IntOut(0, Counts(^A)); -Text(0, " C: "); IntOut(0, Counts(^C)); -Text(0, " G: "); IntOut(0, Counts(^G)); -Text(0, " T: "); IntOut(0, Counts(^T)); -Text(0, " -Total: "); IntOut(0, Cnt); CrLf(0); -] diff --git a/Task/Bioinformatics-base-count/Zkl/bioinformatics-base-count.zkl b/Task/Bioinformatics-base-count/Zkl/bioinformatics-base-count.zkl deleted file mode 100644 index 51481d619d..0000000000 --- a/Task/Bioinformatics-base-count/Zkl/bioinformatics-base-count.zkl +++ /dev/null @@ -1,19 +0,0 @@ -bases:= -#<<<" -CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG -CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG -AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT -GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT -CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG -TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA -TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT -CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG -TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC -GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT" - " \n"; -#<<< - -[0..*,50].zipWith(fcn(n,bases){ println("%6d: %s".fmt(n,bases.concat())) }, - bases.walker().walk.fp(50)).pump(Void); // .pump forces the iterator - -println("\nBase Counts: ", bases.counts().pump(String,Void.Read,"%s: %d ".fmt)); -println("Total: ",bases.len()); diff --git a/Task/Biorhythms/11l/biorhythms.11l b/Task/Biorhythms/11l/biorhythms.11l index d38daa2837..5e64e6837e 100644 --- a/Task/Biorhythms/11l/biorhythms.11l +++ b/Task/Biorhythms/11l/biorhythms.11l @@ -21,7 +21,7 @@ F biorhythms(birthdate_str, targetdate_str) V cycle_lengths = [23, 28, 33] V quadrants = [(‘up and rising’, ‘peak’), (‘up but falling’, ‘transition’), (‘down and falling’, ‘valley’), (‘down but rising’, ‘transition’)] - L(i) 3 + L(i) 0.<3 V label = cycle_labels[i] V length = cycle_lengths[i] V position = days % length diff --git a/Task/Biorhythms/ALGOL-68/biorhythms.alg b/Task/Biorhythms/ALGOL-68/biorhythms.alg new file mode 100644 index 0000000000..9687f0aefa --- /dev/null +++ b/Task/Biorhythms/ALGOL-68/biorhythms.alg @@ -0,0 +1,76 @@ +BEGIN # biorythms # + + # code from the Day of the week of Christmas and New Year task # + []STRING day name = + []STRING( "SAT", "SUN", "MON", "TUE", "WED", "THU", "FRI" )[ AT 0 ]; + PROC day of week = ( INT y, m, d )INT: + BEGIN + INT mm := m; + INT yy := y; + IF mm <= 2 THEN + mm +:= 12; + yy -:= 1 + FI; + INT j = yy OVER 100; + INT k = yy MOD 100; + ( d + ( ( mm + 1 ) * 26 ) OVER 10 + k + k OVER 4 + j OVER 4 + 5 * j ) MOD 7 + END # day of week # ; + # end code from the Day of the week of Christmas and New Year task # + # code from the days between dates task # + PROC gregorian = ( INT y, m, d )INT: + BEGIN + INT n = ( m + 9 ) - ( ( ( m + 9 ) OVER 12 ) * 12 ); + INT w = y - ( n OVER 10 ); + ( 365 * w ) + ( w OVER 4 ) - ( w OVER 100 ) + ( w OVER 400 ) + + ( ( ( n * 306 ) + 5 ) OVER 10 ) + ( d - 1 ) + END # gregorian # ; + # end code from the days between dates task # + + BEGIN # main routine - translated from the Fortran sample's main program # + PROC double line = VOID: print( ( "=" * 75, newline ) ); + PROC in range = ( REAL v, INT low, high )INT: + IF v < low THEN low ELIF v > high THEN high ELSE ENTIER v FI; + + REAL pi2 = pi * 2; + + INT byear, bmon, bday, tyear, tmon, tday, nday; + print( ( "ENTER YOUR BIRTHDAY YYYY MM DD: " ) ); + read( ( byear, bmon, bday ) ); + print( ( "ENTER START DATE YYYY MM DD: " ) ); + read( ( tyear, tmon, tday ) ); + print( ( "ENTER NUMBER OF DAYS TO PLOT : " ) ); + read( ( nday ) ); + + INT jd0 = gregorian( tyear, 1, 1 ); + INT jd1 = gregorian( byear, bmon, bday ); + INT jd2 := gregorian( tyear, tmon, tday ); + INT dob = day of week( byear, bmon, bday ); + INT dow := day of week( tyear, tmon, tday ); + + double line; + print( ( "YOU WERE BORN ON A (", day name[ dob MOD 7 ], ") YOU WERE " ) ); + print( ( whole( jd2 - jd1, 0 ), " DAYS OLD ON THE START DATE.", newline ) ); + print( ( "-1", 31 * " ", "0", 30 * " ", "+1 DOY", newline ) ); + TO nday DO + INT dif = jd2 - jd1; + INT phy = in range( 3.3e1+3.2e1*sin( pi2 * dif / 2.3e1 ), 1, 65 ); + INT emd = in range( 3.3e1+3.2e1*sin( pi2 * dif / 2.8e1 ), 1, 65 ); + INT men = in range( 3.3e1+3.2e1*sin( pi2 * dif / 3.3e1 ), 1, 65 ); + STRING g row := 65 * IF day name[ dow ] = "SUN" THEN "." ELSE " " FI; + g row[ 1 ] := "|"; + g row[ 17 ] := ":"; + g row[ 33 ] := "|"; + g row[ 49 ] := ":"; + g row[ 65 ] := "|"; + g row[ phy ] := "P"; + g row[ emd ] := "E"; + g row[ men ] := "M"; + IF phy = emd OR phy = men THEN g row[ phy ] := "*" FI; + IF emd = men THEN g row[ emd ] := "*" FI; + print( ( " ", g row, " ", day name[ dow ], " ", whole( jd2 - jd0 + 1, -3 ), newline ) ); + jd2 +:= 1; + dow +:= 1 MODAB 7 + OD; + double line + END +END diff --git a/Task/Biorhythms/Ada/biorhythms.adb b/Task/Biorhythms/Ada/biorhythms.adb new file mode 100644 index 0000000000..8f1fb796b8 --- /dev/null +++ b/Task/Biorhythms/Ada/biorhythms.adb @@ -0,0 +1,65 @@ +with Ada.Calendar; +with Ada.Calendar.Arithmetic; +with Ada.Calendar.Formatting; +with Ada.Command_Line; +with Ada.Numerics; +with Ada.Numerics.Elementary_Functions; +with Ada.Text_IO; + +use Ada.Calendar; +use Ada.Calendar.Arithmetic; +use Ada.Calendar.Formatting; +use Ada.Command_Line; +use Ada.Numerics; +use Ada.Numerics.Elementary_Functions; +use Ada.Text_IO; + +procedure Biorhythms is + Birth_Date : Time := Value (Argument (1) & " 00:00:00"); + Target_Date : Time := Value (Argument (2) & " 00:00:00"); + Days : Day_Count := Target_Date - Birth_Date; + + -- There's not much point having types for these for such a short + -- problem, but in a big program this would be useful to prevent + -- accidentally assigning wrong values. + type Physical_Type is mod 23; + type Emotional_Type is mod 28; + type Mental_Type is mod 33; + type Biorhythm_Type is + record + Physical : Physical_Type; + Emotional : Emotional_Type; + Mental : Mental_Type; + end record; + + function To_Biorhythm (D : Day_Count) return Biorhythm_Type is + ( + Physical_Type (D mod Physical_Type'Modulus), + Emotional_Type (D mod Emotional_Type'Modulus), + Mental_Type (D mod Mental_Type'Modulus) + ); + + Biorhythm : Biorhythm_Type := To_Biorhythm (Days); + + package Float_IO is new Ada.Text_IO.Float_IO (Float); + use Float_IO; + + function To_Percent (F : Float) return Float is + (100.0 * Sin (2.0 * Pi * F)); + + procedure Report_Biorhythm (B : Biorhythm_Type) is + PFrac : Float := Float (B.Physical) / Float (Physical_Type'Modulus); + EFrac : Float := Float (B.Emotional) / Float (Emotional_Type'Modulus); + MFrac : Float := Float (B.Mental) / Float (Mental_Type'Modulus); + Physical : Float := To_Percent (PFrac); + Emotional : Float := To_Percent (EFrac); + Mental : Float := To_Percent (MFrac); + begin + Put_Line ("Age in days: " & Days'Image); + Put ("Physical cycle: "); Put (Physical, 3, 1, 0); Put ("%"); New_Line; + Put ("Emotional cycle: "); Put (Emotional, 3, 1, 0); Put ("%"); New_Line; + Put ("Mental cycle: "); Put (Mental, 3, 1, 0); Put ("%"); New_Line; + end Report_Biorhythm; +begin + Report_Biorhythm (Biorhythm); +end Biorhythms; diff --git a/Task/Biorhythms/C/biorhythms-2.c b/Task/Biorhythms/C/biorhythms-2.c index 3e2d9d0f69..ddd8256686 100644 --- a/Task/Biorhythms/C/biorhythms-2.c +++ b/Task/Biorhythms/C/biorhythms-2.c @@ -3,3 +3,4 @@ gcc -o cbio cbio.c -lm Age: 10717 days Physical cycle: -27% Emotional cycle: -100% +Intellectual cycle: -100% diff --git a/Task/Biorhythms/COBOL/biorhythms-1.cobol b/Task/Biorhythms/COBOL/biorhythms-1.cob similarity index 100% rename from Task/Biorhythms/COBOL/biorhythms-1.cobol rename to Task/Biorhythms/COBOL/biorhythms-1.cob diff --git a/Task/Biorhythms/COBOL/biorhythms-2.cobol b/Task/Biorhythms/COBOL/biorhythms-2.cob similarity index 100% rename from Task/Biorhythms/COBOL/biorhythms-2.cobol rename to Task/Biorhythms/COBOL/biorhythms-2.cob diff --git a/Task/Biorhythms/Crystal/biorhythms.cr b/Task/Biorhythms/Crystal/biorhythms.cr new file mode 100644 index 0000000000..b6c9cdba70 --- /dev/null +++ b/Task/Biorhythms/Crystal/biorhythms.cr @@ -0,0 +1,48 @@ +module BioRhythms + enum Cycle + Physical = 23 + Emotional = 28 + Mental = 33 + end + + Quadrants = [ {"up and raising", "peak"}, + {"up but falling", "transition"}, + {"down and falling", "valley"}, + {"down but raising", "transition"} ] + + def self.report (birthday, date = Time.utc) + # regularize to avoid fractional days difference + birthday, date = birthday.to_utc, date.to_utc + birthday -= birthday.time_of_day + date -= date.time_of_day + + days = (date - birthday).days + + puts "Born #{birthday.to_s("%F")}, Target #{date.to_s("%F")}" + puts "Day #{days}:" + Cycle.each do |kind, length| + position = days % length + quadrant = (position / length * 4).to_i + percentage = (Math.sin(position / length * 2 * Math::PI)*1000).to_i / 10 + description = if percentage > 95 + "peak" + elsif percentage < -95 + "valley" + elsif percentage.abs < 5 + "critical transition" + else + transition = date + ((quadrant + 1)/4 * length).to_i.days - position.days + trend, the_next = Quadrants[quadrant] + "#{percentage}% (#{trend}, next #{the_next} #{transition.to_s("%F")})" + end + puts "%-13s %2d: %s" % {kind.to_s + " day", position, description} + end + end +end + +[{"1943-03-09", "1972-07-11"}, + {"1809-01-12", "1863-11-19"}, + {"1809-02-12", "1863-11-19"}].each do |bd, target| + BioRhythms.report Time.parse_utc(bd, "%F"), Time.parse_utc(target, "%F") + puts +end diff --git a/Task/Biorhythms/Delphi/biorhythms.delphi b/Task/Biorhythms/Delphi/biorhythms.pas similarity index 100% rename from Task/Biorhythms/Delphi/biorhythms.delphi rename to Task/Biorhythms/Delphi/biorhythms.pas diff --git a/Task/Biorhythms/EasyLang/biorhythms.easy b/Task/Biorhythms/EasyLang/biorhythms.easy index ebb822d591..8307ee3761 100644 --- a/Task/Biorhythms/EasyLang/biorhythms.easy +++ b/Task/Biorhythms/EasyLang/biorhythms.easy @@ -8,36 +8,30 @@ func day d$ . d = number substr d$ 9 2 return 367 * y - 7 * (y + (m + 9) div 12) div 4 + 275 * m div 9 + d - 730530 . -textsize 4 +gtextsize 4 func init b$ d$ . - linewidth 0.2 - move 50 0 - line 50 100 - move 0 50 - line 100 50 + glinewidth 0.2 + gline 50 0 50 100 + gline 0 50 100 50 for d = -20 to 20 - move x 50 - circle 0.5 + gcircle x 50 0.5 x += 2.5 . - move 4 94 - text b$ - move 4 88 - text d$ + gtext 4 94 b$ + gtext 4 88 d$ days = day date$ - day birth$ - move 4 80 - text days & " days" + gtext 4 80 days & " days" return days . -proc cycle now cyc t$ col . . - color col - move 4 cyc * 1.2 - 20 - text t$ - linewidth 0.5 - for d = now - 20 to now + 20 - p = 20 * sin (360 * d / cyc) - line x 50 + p - x += 2.5 +proc cycle now cyc t$ col . + gcolor col + gtext 4 cyc * 1.2 - 20 t$ + glinewidth 0.5 + gpenup + for d = now - 20 step 0.2 to now + 20 + y = 50 + 20 * sin (360 * d / cyc) + glineto x y + x += 0.5 . . days = init birth$ date$ diff --git a/Task/Biorhythms/Emacs-Lisp/biorhythms.l b/Task/Biorhythms/Emacs-Lisp/biorhythms.el similarity index 100% rename from Task/Biorhythms/Emacs-Lisp/biorhythms.l rename to Task/Biorhythms/Emacs-Lisp/biorhythms.el diff --git a/Task/Biorhythms/FutureBasic/biorhythms.basic b/Task/Biorhythms/FutureBasic/biorhythms.basic new file mode 100644 index 0000000000..3c1d0ead45 --- /dev/null +++ b/Task/Biorhythms/FutureBasic/biorhythms.basic @@ -0,0 +1,112 @@ +/* +Biorhythms task for Rosetta Code +https://rosettacode.org/wiki/Biorhythms + +Translated from FreeBASIC to FutureBasic +Rich Love May 24, 2024 + +Oct 16, 2024 fixed the percentage amounts + +*/ + + + +local fn Gregorian(db As str255) As short + short M, Y, D + Y = val(Left$(db,4)) : M = Val(Mid$(db,6,2)) : D = Val(Right$(db,2)) + short N = (M+9) - Int((M+9)/12) * 12 + short W = Y - Int(N/10) + short G = 365 * W + Int(W/4) - Int(W/100) + Int(W/400) + G += Int((N*306+5)/10)+(D-1) +end fn = G + + +void local fn Biorhythm(Birthdate As str255, Targetdate As str255) + + str255 TextArray(4,2) + TextArray(0,0) = "up and rising" + TextArray(1,0) = "up but falling" + TextArray(2,0) = "down and falling" + TextArray(3,0) = "down but rising" + TextArray(0,1) = "peak" + TextArray(1,1) = "transition" + TextArray(2,1) = "valley" + TextArray(3,1) = "transition" + + + short DaysBetween = fn Gregorian(Targetdate) - fn Gregorian(Birthdate) + 1 + short positionP = DaysBetween Mod 23 + short positionE = DaysBetween Mod 28 + short positionM = DaysBetween Mod 33 + short quadrantP = Int(4 * positionP / 23) + short quadrantE = Int(4 * positionE / 28) + short quadrantM = Int(4 * positionM / 33) + short percentageP = int(100 * Sin(2 * (pi * positionP) / 23)) + short percentageE = int(100 * Sin(2 * (pi * positionE) / 28)) + short percentageM = int(100 * Sin(2 * (pi * positionM) / 33)) + + str255 textP, textE, textM, Header1Text, Header2Text + + + Select Case percentageP + Case > 95 + textP = "Physical day " + str$(positionP) + " : " + "peak" + Case < -95 + textP = "Physical day " + str$(positionP) + " : " + "valley" + Case -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5 + textP = "Physical day " + str$(positionP) + " : " + "critical transition" + Case Else + textP = "Physical day " + str$(positionP) + " : " + str$(percentageP) + "% (" + TextArray(quadrantP,0) + ")" + End Select + + Select Case percentageE + Case > 95 + textE = "Emotional day " + STR$(positionE) + " : " + "peak" + Case < -95 + textE = "Emotional day " + STR$(positionE) + " : " + "valley" + Case -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5 + textE = "Emotional day " + STR$(positionE) + " : " + "critical transition" + Case Else + textE = "Emotional day " + STR$(positionE) + " : " + str$(percentageE) + "% (" + TextArray(quadrantE,0) + ")" + End Select + + Select Case percentageM + Case > 95 + textM = "Mental day " + str$(positionM)+ " : " + "peak" + Case < - 95 + textM = "Mental day " + str$(positionM) + " : " + "valley" + Case -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5 + textM = "Mental day " + str$(positionM) + " : " + "critical transition" + Case Else + textM = "Mental day " + str$(positionM) + " : " + str$(percentageM) + "% (" + TextArray(quadrantM,0) + ")" + End Select + + Header1Text = "Born " + Birthdate + ", Target " + Targetdate + Header2Text = "Day " + str$(DaysBetween) + + Print Header1Text + Print Header2Text + Print textP + Print textE + Print textM + Print +end fn + +window 1, @"Biorhythms" +windowcenter(1) +WindowSetBackgroundColor(1,fn ColorBlack) + +print + +// Lets do four different birthdates and target dates +text ,,fn colorCyan +fn Biorhythm("1943-03-09", "1972-07-11") +text ,,fn colorGreen +fn Biorhythm("1809-02-12", "1863-11-19") // DOB for Abraham Lincoln +text ,,fn colorYellow +fn Biorhythm("1809-01-12", "1863-11-19") +text ,,fn colorWhite +fn Biorhythm("1943-03-09", "1972-07-11") // Bobby Fisher Chess Tournament + + +handleevents diff --git a/Task/Biorhythms/Julia/biorhythms.julia b/Task/Biorhythms/Julia/biorhythms.jl similarity index 100% rename from Task/Biorhythms/Julia/biorhythms.julia rename to Task/Biorhythms/Julia/biorhythms.jl diff --git a/Task/Biorhythms/Kotlin/biorhythms.kotlin b/Task/Biorhythms/Kotlin/biorhythms.kts similarity index 100% rename from Task/Biorhythms/Kotlin/biorhythms.kotlin rename to Task/Biorhythms/Kotlin/biorhythms.kts diff --git a/Task/Biorhythms/M2000-Interpreter/biorhythms.m2000 b/Task/Biorhythms/M2000-Interpreter/biorhythms.m2000 index 04f46aedc7..732e4e600f 100644 --- a/Task/Biorhythms/M2000-Interpreter/biorhythms.m2000 +++ b/Task/Biorhythms/M2000-Interpreter/biorhythms.m2000 @@ -1,24 +1,21 @@ -Module Biorhythms { - form 80 - enum bio {Physical=23, Emotional=28,Mental=33} - quadrants=(("up and rising", "peak"), ("up but falling", "transition"), ("down and falling", "valley"), ("down but rising", "transition")) - date birth="1943-03-09" - date bioDay="1972-07-11", transition - for k=1 to 1 +Module Biorhythms (birth, bioDay, N as long = 1) { + date birth, bioDay, transition + enum bio {Physical=23, Emotional=28, Mental=33} + dim quadrants(4) + quadrants(0):=("up and rising", "peak"), ("up but falling", "transition"), ("down and falling", "valley"), ("down but rising", "transition") + if N<1 then N=1 + for k=1 to N long Days=bioDay-birth - Print "Day "+Days+":" - + Print "Day "+bioDay+" | Age in days: "+Days string frm="{0:-20} : {1}", pword, dfmt="YYYY-MM-DD" - long position, percentage, length, targetday + long position, percentage, length k=each(bio) while k - length=eval(k) - + length=eval(k) position=days mod length quadrant=int(4*position/length) - targetday=bioDay // get the long value of day from date type percentage=100*sin(360*position/length) - transition=bioDay+floor((quadrant+1)/4*23)-position + transition=bioDay+floor((quadrant+1)/4*length)-position select case percentage case >95 pword="peak" @@ -27,14 +24,15 @@ Module Biorhythms { case -5 to 5 pword="critical " case else - { - pword=percentage+"% ("+quadrants#val(quadrant)#val$(0)+", next " - pword+=quadrants#val(quadrant)#val$(1)+" "+str$(transition,dfmt)+")" - } + { + pword=percentage+"% ("+quadrants(quadrant)#val$(0)+", next " + pword+=quadrants(quadrant)#val$(1)+" "+str$(transition, dfmt)+")" + } end select print format$(frm, eval$(k)+" day "+(days mod length), pword) End while bioDay++ next k } -Biorhythms +form 80 +Biorhythms "1943-03-09", "1972-07-11" diff --git a/Task/Biorhythms/Phix/biorhythms.phix b/Task/Biorhythms/Phix/biorhythms.phix index e88bb994b4..d4c003fc47 100644 --- a/Task/Biorhythms/Phix/biorhythms.phix +++ b/Task/Biorhythms/Phix/biorhythms.phix @@ -1,44 +1,42 @@ -(phixonline)--> - with javascript_semantics - include timedate.e +with javascript_semantics +include timedate.e - constant cycles = {"Physical day ", "Emotional day", "Mental day "}, - lengths = {23, 28, 33}, - quadrants = {{"up and rising", "peak"}, - {"up but falling", "transition"}, - {"down and falling", "valley"}, - {"down but rising", "transition"}} +constant cycles = {"Physical day ", "Emotional day", "Mental day "}, + lengths = {23, 28, 33}, + quadrants = {{"up and rising", "peak"}, + {"up but falling", "transition"}, + {"down and falling", "valley"}, + {"down but rising", "transition"}} - procedure biorhythms(string birthDate, targetDate) - timedate bd = parse_date_string(birthDate,{"YYYY-MM-DD"}), - td = parse_date_string(targetDate,{"YYYY-MM-DD"}) - integer days = floor(timedate_diff(bd, td, DT_DAY)/(60*60*24)) - printf(1,"Born %s, Target %s\n",{birthDate,targetDate}) - printf(1,"Day %d\n",days) - for i=1 to 3 do - integer len = lengths[i], - posn = remainder(days,len), - quadrant = floor(posn/len*4)+1 - atom percent = floor(sin(2*PI*posn/len)*1000)/10 - string cycle = cycles[i], - desc = iff(percent>95 ? " peak" : - iff(percent<-95 ? " valley" : - iff(abs(percent)<5 ? " critical transition" : "other"))) - if desc == "other" then - timedate t = adjust_timedate(td,timedelta(days:=floor(quadrant/4*len)-posn)) - string transition = format_timedate(t,"YYYY-MM-DD"), - {trend,next} = quadrants[quadrant] - desc = sprintf("%5.1f%% (%s, next %s %s)", {percent, trend, next, transition}) - end if - printf(1,"%s %2d : %s\n", {cycle, posn, desc}) - end for - printf(1,"\n") - end procedure +procedure biorhythms(string birthDate, targetDate) + timedate bd = parse_date_string(birthDate,{"YYYY-MM-DD"}), + td = parse_date_string(targetDate,{"YYYY-MM-DD"}) + integer days = floor(timedate_diff(bd, td, DT_DAY)/(60*60*24)) + printf(1,"Born %s, Target %s\n",{birthDate,targetDate}) + printf(1,"Day %d\n",days) + for i=1 to 3 do + integer len = lengths[i], + posn = remainder(days,len), + quadrant = floor(posn/len*4)+1 + atom percent = floor(sin(2*PI*posn/len)*1000)/10 + string cycle = cycles[i], + desc = iff(percent>95 ? " peak" : + iff(percent<-95 ? " valley" : + iff(abs(percent)<5 ? " critical transition" : "other"))) + if desc == "other" then + timedate t = adjust_timedate(td,timedelta(days:=floor(quadrant/4*len)-posn)) + string transition = format_timedate(t,"YYYY-MM-DD"), + {trend,next} = quadrants[quadrant] + desc = sprintf("%5.1f%% (%s, next %s %s)", {percent, trend, next, transition}) + end if + printf(1,"%s %2d : %s\n", {cycle, posn, desc}) + end for + printf(1,"\n") +end procedure - constant datePairs = { - {"1943-03-09", "1972-07-11"}, - {"1809-01-12", "1863-11-19"}, - {"1809-02-12", "1863-11-19"} // correct DOB for Abraham Lincoln - } - for i=1 to length(datePairs) do biorhythms(datePairs[i][1], datePairs[i][2]) end for - Data (byte bucket) out:=Data().fill(0,25); @@ -9,7 +9,7 @@ fcn unbase58(str){ // --> Data (byte bucket) [24..0,-1].reduce('wrap(c,idx){ c+=58*out[idx]; // throws if not enough data out[idx]=c; - c/256; // should be zero when done + c/256; // should be zero when done },n) : if(_) throw(Exception.ValueError("address too long")); }); out; diff --git a/Task/Bitcoin-public-point-to-address/C++/bitcoin-public-point-to-address.cpp b/Task/Bitcoin-public-point-to-address/C++/bitcoin-public-point-to-address.cpp new file mode 100644 index 0000000000..3a5ee44ffc --- /dev/null +++ b/Task/Bitcoin-public-point-to-address/C++/bitcoin-public-point-to-address.cpp @@ -0,0 +1,103 @@ +#include +#include +#include +#include +#include + +#include "SHA256.cpp" +#include "RIPEMD160.cpp" +SHA256 sha256{ }; +RIPEMD160 ripemd160{ }; + +const std::string BITCOIN_SPECIAL_VALUE = "04"; +const std::string BITCOIN_VERSION_NUMBER = "00"; + +std::map base_map = + { { '0', 0 }, { '1', 1 }, { '2', 2 }, { '3', 3 }, { '4', 4 }, { '5', 5 }, { '6', 6 }, { '7', 7 }, + { '8', 8 }, { '9', 9 }, { 'a', 10 }, { 'b', 11 }, { 'c', 12 }, { 'd', 13 }, { 'e', 14 }, { 'f', 15 }, + { 'A', 10 }, { 'B', 11 }, { 'C', 12 }, { 'D', 13 }, { 'E', 14 }, { 'F', 15 } }; + +std::vector hex_to_bytes(const std::string& text) { + std::vector bytes(text.size() / 2, 0); + for ( uint64_t i = 0; i < text.size(); i += 2 ) { + const uint32_t first_digit = base_map[text[i]]; + const uint32_t second_digit = base_map[text[i + 1]]; + bytes[i / 2] = ( first_digit << 4 ) + second_digit; + } + return bytes; +} + +std::string vector_to_ascii_string(const std::vector& bytes) { + std::string result = ""; + for ( uint64_t i = 0; i < bytes.size(); ++i ) { + result += static_cast(bytes[i]); + } + return result; +} + +std::vector compute_message_bytes(const std::string& text) { + // Convert the hexadecimal string 'text' into a suitable ASCII string for the SHA256 hash + std::vector bytes_1 = hex_to_bytes(text); + std::string ascii_1 = vector_to_ascii_string(bytes_1); + std::string hexSHA256 = sha256.message_digest(ascii_1); + // Convert the hexadecimal string 'hexSHA256' into a suitable ASCII string for the RIPEMD160 hash + std::vector bytes_2 = hex_to_bytes(hexSHA256); + std::string ascii_2 = vector_to_ascii_string(bytes_2); + std::string hexRIPEMD160 = BITCOIN_VERSION_NUMBER + ripemd160.message_digest(ascii_2); + return hex_to_bytes(hexRIPEMD160); +} + +std::vector compute_checksum(const std::vector& bytes) { + // Convert the given byte array into a suitable ASCII string for the first SHA256 hash + std::string ascii_1 = vector_to_ascii_string(bytes); + std::string hex_1 = sha256.message_digest(ascii_1); + // Convert the hexadecimal string 'hex1' into a suitable ASCII string for the second SHA256 hash + std::vector bytes_1 = hex_to_bytes(hex_1); + std::string ascii_2 = vector_to_ascii_string(bytes_1); + std::string hex_2 = sha256.message_digest(ascii_2); + std::vector bytes_2 = hex_to_bytes(hex_2); + std::vector result(bytes_2.begin(), bytes_2.begin() + 4); + return result; +} + +// Return the given byte array encoded into a base58 starting with most one '1' +std::string encode_base_58(std::vector bytes) { + const std::string ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; + const uint32_t ALPHABET_SIZE = ALPHABET.size(); + + std::string result(34, ' '); + for ( int64_t n = result.size() - 1; n >= 0; --n ) { + uint32_t c = 0; + for ( uint64_t i = 0; i < bytes.size(); ++i ) { + c = c * 256 + bytes[i]; + bytes[i] = c / ALPHABET_SIZE; + c %= ALPHABET_SIZE; + } + result[n] = ALPHABET[c]; + } + + while ( result.starts_with("11") ) { + result = result.substr(1); + } + return result; +} + +// Return the encoded address of the given coordinates. +std::string encode_address(const std::string& x, const std::string& y) { + std::string public_point = BITCOIN_SPECIAL_VALUE + x + y; + if ( public_point.size() != 130 ) { + throw std::invalid_argument("Invalid public point string"); + } + + std::vector message_bytes = compute_message_bytes(public_point); + std::vector checksum = compute_checksum(message_bytes); + message_bytes.insert(message_bytes.end(), checksum.begin(), checksum.end()); + return encode_base_58(message_bytes); +} + +int main() { + std::string x = "50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352"; + std::string y = "2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6"; + + std::cout << encode_address(x, y) << std::endl; +} diff --git a/Task/Bitcoin-public-point-to-address/Delphi/bitcoin-public-point-to-address.delphi b/Task/Bitcoin-public-point-to-address/Delphi/bitcoin-public-point-to-address.pas similarity index 100% rename from Task/Bitcoin-public-point-to-address/Delphi/bitcoin-public-point-to-address.delphi rename to Task/Bitcoin-public-point-to-address/Delphi/bitcoin-public-point-to-address.pas diff --git a/Task/Bitcoin-public-point-to-address/FreeBASIC/bitcoin-public-point-to-address.basic b/Task/Bitcoin-public-point-to-address/FreeBASIC/bitcoin-public-point-to-address.basic new file mode 100644 index 0000000000..902427a908 --- /dev/null +++ b/Task/Bitcoin-public-point-to-address/FreeBASIC/bitcoin-public-point-to-address.basic @@ -0,0 +1,142 @@ +#include "SHA_256.bas" +#include "RIPEMD_160.bas" + +Const BITCOIN_SPECIAL_VALUE As String = "04" +Const BITCOIN_VERSION_NUMBER As String = "00" + +Dim Shared base_map(255) As Integer + +Sub init_base_map() + Dim As Integer i + For i = 0 To 255 + base_map(i) = -1 + Next + For i = 0 To 9 + base_map(Asc("0") + i) = i + Next + For i = 0 To 5 + base_map(Asc("a") + i) = 10 + i + base_map(Asc("A") + i) = 10 + i + Next + For i = 6 To 15 + base_map(Asc("a") + i) = 10 + i + base_map(Asc("A") + i) = 10 + i + Next +End Sub + +Sub hex_to_bytes(text As String, bytes() As Integer) + Dim As Integer first_digit, second_digit + Dim As Integer n = Len(text) \ 2 + Redim bytes(n - 1) + + For i As Integer = 0 To n - 1 + first_digit = base_map(Asc(Mid(text, 2 * i + 1, 1))) + second_digit = base_map(Asc(Mid(text, 2 * i + 2, 1))) + bytes(i) = (first_digit Shl 4) + second_digit + Next +End Sub + +Function vector_to_ascii_string(bytes() As Integer) As String + Dim As String result = "" + + For i As Integer = 0 To Ubound(bytes) + result &= Chr(bytes(i)) + Next + + Return result +End Function + +Sub compute_message_bytes(text As String, out_bytes() As Integer) + Dim As Integer bytes_1() + hex_to_bytes(text, bytes_1()) + + Dim As String ascii_1 = vector_to_ascii_string(bytes_1()) + Dim As String hexSHA_256 = SHA_256(ascii_1) + Dim As Integer bytes_2() + hex_to_bytes(hexSHA_256, bytes_2()) + + Dim As String ascii_2 = vector_to_ascii_string(bytes_2()) + Dim As String hexRIPEMD_160 = BITCOIN_VERSION_NUMBER & RIPEMD_160(ascii_2) + hex_to_bytes(hexRIPEMD_160, out_bytes()) +End Sub + +Sub compute_checksum(bytes() As Integer, out_checksum() As Integer) + Dim As String ascii_1 = vector_to_ascii_string(bytes()) + Dim As String hex_1 = SHA_256(ascii_1) + Dim As Integer bytes_1() + hex_to_bytes(hex_1, bytes_1()) + + Dim As String ascii_2 = vector_to_ascii_string(bytes_1()) + Dim As String hex_2 = SHA_256(ascii_2) + Dim As Integer bytes_2() + hex_to_bytes(hex_2, bytes_2()) + Redim out_checksum(3) + + For i As Integer = 0 To 3 + out_checksum(i) = bytes_2(i) + Next +End Sub + +Function encode_base_58(bytes() As Integer) As String + Const As String ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" + Const As Integer ALPHABET_SIZE = 58 + Dim As String result = String(34, " ") + Dim As Integer i, j, n, c + Dim As Integer temp() + + Redim As Integer bytes_copy(Ubound(bytes)) + For i = 0 To Ubound(bytes) + bytes_copy(i) = bytes(i) + Next + + For n = Len(result) - 1 To 0 Step -1 + c = 0 + For i = 0 To Ubound(bytes_copy) + c = c * 256 + bytes_copy(i) + bytes_copy(i) = c \ ALPHABET_SIZE + c Mod= ALPHABET_SIZE + Next + Mid(result, n + 1, 1) = Mid(ALPHABET, c + 1, 1) + Next + + ' Quitar los '1' iniciales extra + While Left(result, 2) = "11" + result = Mid(result, 2) + Wend + Return result +End Function + +Function encode_address(x As String, y As String) As String + Dim As String public_point = BITCOIN_SPECIAL_VALUE & x & y + If Len(public_point) <> 130 Then + Print "Invalid public point string" + Exit Function + End If + Dim As Integer message_bytes() + compute_message_bytes(public_point, message_bytes()) + + Dim As Integer checksum() + compute_checksum(message_bytes(), checksum()) + + Dim As Integer i + Dim As Integer full_bytes() + Redim full_bytes(Ubound(message_bytes) + 4) + For i = 0 To Ubound(message_bytes) + full_bytes(i) = message_bytes(i) + Next + For i = 0 To 3 + full_bytes(Ubound(message_bytes) + 1 + i) = checksum(i) + Next + + Return encode_base_58(full_bytes()) +End Function + +' Test Program +init_base_map() + +Dim As String x = "50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352" +Dim As String y = "2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6" + +Print encode_address(x, y) + +Sleep diff --git a/Task/Bitcoin-public-point-to-address/Java/bitcoin-public-point-to-address.java b/Task/Bitcoin-public-point-to-address/Java/bitcoin-public-point-to-address.java new file mode 100644 index 0000000000..6f28ff3d99 --- /dev/null +++ b/Task/Bitcoin-public-point-to-address/Java/bitcoin-public-point-to-address.java @@ -0,0 +1,99 @@ +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.stream.Collectors; + +public final class BitcoinPublicPointToAddess { + + public static void main(String[] args) { + String x = "50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352"; + String y = "2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6"; + + if ( areValidCoordinates(x, y) ) { + System.out.println(encodeAddress(x, y)); + } else { + System.out.println("Invalid Bitcoin public point coordinates"); + } + } + + // Return the encoded address of the given coordinates. + private static String encodeAddress(String x, String y) { + String publicPoint = BITCOIN_SPECIAL_VALUE + x + y; + if ( publicPoint.length() != 130 ) { + throw new AssertionError("Invalid public point string: " + publicPoint); + } + + byte[] messageBytes = computeMessageBytes(publicPoint); + byte[] checksum = computeChecksum(messageBytes); + messageBytes = Arrays.copyOf(messageBytes, messageBytes.length + 4); + System.arraycopy(checksum, 0, messageBytes, 21, checksum.length); + return encodeBase58(messageBytes); + } + + // Return the given byte array encoded into a base58 starting with most one '1' + private static String encodeBase58(byte[] bytes) { + final String ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; + final int ALPHABET_SIZE = ALPHABET.length(); + + String[] temp = new String[34]; + for ( int n = temp.length - 1; n >= 0; n-- ) { + int c = 0; + for ( int i = 0; i < bytes.length; i++ ) { + c = c * 256 + (int) ( bytes[i] & 0xFF ); + bytes[i] = (byte) ( c / ALPHABET_SIZE ); + c %= ALPHABET_SIZE; + } + temp[n] = ALPHABET.substring(c, c + 1); + } + + String result = Arrays.stream(temp).collect(Collectors.joining("")); + while ( result.startsWith("11") ) { + result = result.substring(1); + } + return result; + } + + // Return whether the given coordinates are those of a point on the secp256k1 elliptic curve + private static boolean areValidCoordinates(String x, String y) { + BigInteger modulus = new BigInteger("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F", 16); + BigInteger X = new BigInteger(x, 16); + BigInteger Y = new BigInteger(y, 16); + return Y.multiply(Y).mod(modulus).equals(X.multiply(X).multiply(X).add(BigInteger.valueOf(7)).mod(modulus)); + } + + private static byte[] computeMessageBytes(String text) { + // Convert the hexadecimal string 'text' into a suitable ASCII string for the SHA256 hash + byte[] bytesOne = hexToBytes(text); + String asciiOne = new String(bytesOne, StandardCharsets.ISO_8859_1); + String hexSHA256 = SHA256.messageDigest(asciiOne); + // Convert the hexadecimal string 'hexSHA256' into a suitable ASCII string for the RIPEMD160 hash + byte[] bytesTwo = hexToBytes(hexSHA256); + String asciiTwo = new String(bytesTwo, StandardCharsets.ISO_8859_1); + String hexRIPEMD160 = BITCOIN_VERSION_NUMBER + RIPEMD160.messageDigest(asciiTwo); + return hexToBytes(hexRIPEMD160); + } + + private static byte[] computeChecksum(byte[] bytes) { + // Convert the given byte array into a suitable ASCII string for the first SHA256 hash + String asciiOne = new String(bytes, StandardCharsets.ISO_8859_1); + String hexOne = SHA256.messageDigest(asciiOne); + // Convert the hexadecimal string 'hex1' into a suitable ASCII string for the second SHA256 hash + byte[] bytesOne = hexToBytes(hexOne); + String asciiTwo = new String(bytesOne, StandardCharsets.ISO_8859_1); + String hexTwo = SHA256.messageDigest(asciiTwo); + return Arrays.copyOfRange(hexToBytes(hexTwo), 0, 4); + } + + private static byte[] hexToBytes(String text) { + byte[] bytes = new byte[text.length() / 2]; + for ( int i = 0; i < text.length(); i += 2 ) { + final int firstDigit = Character.digit(text.charAt(i), 16); + final int secondDigit = Character.digit(text.charAt(i + 1), 16); + bytes[i / 2] = (byte) ( ( firstDigit << 4 ) + secondDigit );; + } + return bytes; + } + + private static final String BITCOIN_SPECIAL_VALUE = "04"; + private static final String BITCOIN_VERSION_NUMBER = "00"; +} diff --git a/Task/Bitcoin-public-point-to-address/JavaScript/bitcoin-public-point-to-address.js b/Task/Bitcoin-public-point-to-address/JavaScript/bitcoin-public-point-to-address.js new file mode 100644 index 0000000000..1076901568 --- /dev/null +++ b/Task/Bitcoin-public-point-to-address/JavaScript/bitcoin-public-point-to-address.js @@ -0,0 +1,52 @@ +const crypto = require('crypto'); + +const digits58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; + +function b58(n) { + if (n === 0n) return ''; + return b58(n / 58n) + digits58[Number(n % 58n)]; +} + +function publicPointToAddress(x, y) { + // Convert hex strings to buffers + const xBuffer = Buffer.from(x, 'hex'); + const yBuffer = Buffer.from(y, 'hex'); + + // Create uncompressed public key format (0x04 + x + y) + const publicKey = Buffer.concat([Buffer.from([0x04]), xBuffer, yBuffer]); + + // SHA256 hash + const sha256Hash = crypto.createHash('sha256').update(publicKey).digest(); + + // RIPEMD160 hash + const ripemd160Hash = crypto.createHash('ripemd160').update(sha256Hash).digest(); + + // Add version byte (0x00 for mainnet) + const versionedHash = Buffer.concat([Buffer.from([0x00]), ripemd160Hash]); + + // Double SHA256 for checksum + const checksum = crypto.createHash('sha256') + .update(crypto.createHash('sha256').update(versionedHash).digest()) + .digest() + .slice(0, 4); + + // Combine versioned hash with checksum + const addressBytes = Buffer.concat([versionedHash, checksum]); + + // Convert to BigInt for base58 encoding + let n = 0n; + for (let i = 0; i < addressBytes.length; i++) { + n = (n << 8n) | BigInt(addressBytes[i]); + } + + return b58(n); +} + +// Test with the provided values +if (require.main === module) { + const address = publicPointToAddress( + '50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352', + '2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6' + ); + console.log(address); +} diff --git a/Task/Bitcoin-public-point-to-address/Julia/bitcoin-public-point-to-address-1.julia b/Task/Bitcoin-public-point-to-address/Julia/bitcoin-public-point-to-address-1.jl similarity index 100% rename from Task/Bitcoin-public-point-to-address/Julia/bitcoin-public-point-to-address-1.julia rename to Task/Bitcoin-public-point-to-address/Julia/bitcoin-public-point-to-address-1.jl diff --git a/Task/Bitcoin-public-point-to-address/Julia/bitcoin-public-point-to-address-2.julia b/Task/Bitcoin-public-point-to-address/Julia/bitcoin-public-point-to-address-2.jl similarity index 100% rename from Task/Bitcoin-public-point-to-address/Julia/bitcoin-public-point-to-address-2.julia rename to Task/Bitcoin-public-point-to-address/Julia/bitcoin-public-point-to-address-2.jl diff --git a/Task/Bitcoin-public-point-to-address/Rust/bitcoin-public-point-to-address.rs b/Task/Bitcoin-public-point-to-address/Rust/bitcoin-public-point-to-address.rs new file mode 100644 index 0000000000..57c7e6ba02 --- /dev/null +++ b/Task/Bitcoin-public-point-to-address/Rust/bitcoin-public-point-to-address.rs @@ -0,0 +1,65 @@ +use ring::digest::{digest, SHA256}; +use ripemd::{Digest, Ripemd160}; + +use hex::FromHex; + +static X: &str = "50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352"; +static Y: &str = "2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6"; +static ALPHABET: [char; 58] = [ + '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', + 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', + 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', + 'z', +]; + +fn base58_encode(bytes: &mut [u8]) -> String { + let base = ALPHABET.len(); + if bytes.is_empty() { + return String::from(""); + } + let mut output: Vec = Vec::new(); + let mut num: usize; + for _ in 0..33 { + num = 0; + for byte in bytes.iter_mut() { + num = num * 256 + *byte as usize; + *byte = (num / base) as u8; + num %= base; + } + output.push(num as u8); + } + let mut string = String::new(); + for b in output.iter().rev() { + string.push(ALPHABET[*b as usize]); + } + string +} + +// stolen from address-validation/src/main.rs +/// Hashes the input with the SHA-256 algorithm twice, and returns the output. +fn double_sha256(bytes: &[u8]) -> Vec { + let digest_1 = digest(&SHA256, bytes); + + let digest_2 = digest(&SHA256, digest_1.as_ref()); + digest_2.as_ref().to_vec() +} + +fn point_to_address(x: &str, y: &str) -> String { + let mut addrv: Vec = Vec::with_capacity(65); + addrv.push(4u8); + addrv.append(&mut >::from_hex(x).unwrap()); + addrv.append(&mut >::from_hex(y).unwrap()); + // hash the addresses first using SHA256 + let sha_digest = digest(&SHA256, &addrv); + let mut ripemd_digest = Ripemd160::digest(&sha_digest.as_ref()).as_slice().to_vec(); + // prepend a 0 to the vector + ripemd_digest.insert(0, 0); + // calculate checksum of extended ripemd digest + let checksum = double_sha256(&ripemd_digest); + ripemd_digest.extend_from_slice(&checksum[..4]); + base58_encode(&mut ripemd_digest) +} + +fn main() { + println!("{}", point_to_address(X, Y)); +} diff --git a/Task/Bitcoin-public-point-to-address/Rust/bitcoin-public-point-to-address.rust b/Task/Bitcoin-public-point-to-address/Rust/bitcoin-public-point-to-address.rust deleted file mode 100644 index e9c6c90584..0000000000 --- a/Task/Bitcoin-public-point-to-address/Rust/bitcoin-public-point-to-address.rust +++ /dev/null @@ -1,65 +0,0 @@ -use ring::digest::{digest, SHA256}; -use ripemd160::{Digest, Ripemd160}; - -use hex::FromHex; - -static X: &str = "50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352"; -static Y: &str = "2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6"; -static ALPHABET: [char; 58] = [ - '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', - 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', - 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', - 'z', -]; - -fn base58_encode(bytes: &mut [u8]) -> String { - let base = ALPHABET.len(); - if bytes.is_empty() { - return String::from(""); - } - let mut output: Vec = Vec::new(); - let mut num: usize; - for _ in 0..33 { - num = 0; - for byte in bytes.iter_mut() { - num = num * 256 + *byte as usize; - *byte = (num / base) as u8; - num %= base; - } - output.push(num as u8); - } - let mut string = String::new(); - for b in output.iter().rev() { - string.push(ALPHABET[*b as usize]); - } - string -} - -// stolen from address-validation/src/main.rs -/// Hashes the input with the SHA-256 algorithm twice, and returns the output. -fn double_sha256(bytes: &[u8]) -> Vec { - let digest_1 = digest(&SHA256, bytes); - - let digest_2 = digest(&SHA256, digest_1.as_ref()); - digest_2.as_ref().to_vec() -} - -fn point_to_address(x: &str, y: &str) -> String { - let mut addrv: Vec = Vec::with_capacity(65); - addrv.push(4u8); - addrv.append(&mut >::from_hex(x).unwrap()); - addrv.append(&mut >::from_hex(y).unwrap()); - // hash the addresses first using SHA256 - let sha_digest = digest(&SHA256, &addrv); - let mut ripemd_digest = Ripemd160::digest(&sha_digest.as_ref()).as_slice().to_vec(); - // prepend a 0 to the vector - ripemd_digest.insert(0, 0); - // calculate checksum of extended ripemd digest - let checksum = double_sha256(&ripemd_digest); - ripemd_digest.extend_from_slice(&checksum[..4]); - base58_encode(&mut ripemd_digest) -} - -fn main() { - println!("{}", point_to_address(X, Y)); -} diff --git a/Task/Bitmap-B-zier-curves-Cubic/11l/bitmap-b-zier-curves-cubic.11l b/Task/Bitmap-B-zier-curves-Cubic/11l/bitmap-b-zier-curves-cubic.11l index 7d538ce4eb..4d73742931 100644 --- a/Task/Bitmap-B-zier-curves-Cubic/11l/bitmap-b-zier-curves-cubic.11l +++ b/Task/Bitmap-B-zier-curves-Cubic/11l/bitmap-b-zier-curves-cubic.11l @@ -1,13 +1,4 @@ -T Colour - Byte r, g, b - - F ==(other) - R .r == other.r & .g == other.g & .b == other.b - - F (r, g, b) - .r = r - .g = g - .b = b +T Colour = BVec3 V black = Colour(0, 0, 0) V white = Colour(255, 255, 255) diff --git a/Task/Bitmap-B-zier-curves-Cubic/ALGOL-68/bitmap-b-zier-curves-cubic-2.alg b/Task/Bitmap-B-zier-curves-Cubic/ALGOL-68/bitmap-b-zier-curves-cubic-2.alg index e19cad1f9b..64efe22d15 100644 --- a/Task/Bitmap-B-zier-curves-Cubic/ALGOL-68/bitmap-b-zier-curves-cubic-2.alg +++ b/Task/Bitmap-B-zier-curves-Cubic/ALGOL-68/bitmap-b-zier-curves-cubic-2.alg @@ -1,12 +1,12 @@ #!/usr/bin/a68g --script # # -*- coding: utf-8 -*- # -PR READ "prelude/Bitmap.a68" PR; # c.f. [[rc:Bitmap]] # -PR READ "prelude/Bitmap/Bresenhams_line_algorithm.a68" PR; # c.f. [[rc:Bitmap/Bresenhams_line_algorithm]] # +PR READ "prelude/Bitmap.a68" PR; +PR READ "prelude/Bitmap/Bresenhams_line_algorithm.a68" PR; PR READ "prelude/Bitmap/Bezier_curves/Cubic.a68" PR; -# The following test # -test:( +### test program ### +( REF IMAGE x = INIT LOC[16,16]PIXEL; (fill OF class image)(x, (white OF class image)); (cubic bezier OF class image)(x, (16, 1), (1, 4), (3, 16), (15, 11), (black OF class image), EMPTY); diff --git a/Task/Bitmap-B-zier-curves-Cubic/Ada/bitmap-b-zier-curves-cubic-1.ada b/Task/Bitmap-B-zier-curves-Cubic/Ada/bitmap-b-zier-curves-cubic-1.adb similarity index 100% rename from Task/Bitmap-B-zier-curves-Cubic/Ada/bitmap-b-zier-curves-cubic-1.ada rename to Task/Bitmap-B-zier-curves-Cubic/Ada/bitmap-b-zier-curves-cubic-1.adb diff --git a/Task/Bitmap-B-zier-curves-Cubic/Ada/bitmap-b-zier-curves-cubic-2.ada b/Task/Bitmap-B-zier-curves-Cubic/Ada/bitmap-b-zier-curves-cubic-2.adb similarity index 100% rename from Task/Bitmap-B-zier-curves-Cubic/Ada/bitmap-b-zier-curves-cubic-2.ada rename to Task/Bitmap-B-zier-curves-Cubic/Ada/bitmap-b-zier-curves-cubic-2.adb diff --git a/Task/Bitmap-B-zier-curves-Cubic/Delphi/bitmap-b-zier-curves-cubic.delphi b/Task/Bitmap-B-zier-curves-Cubic/Delphi/bitmap-b-zier-curves-cubic.pas similarity index 100% rename from Task/Bitmap-B-zier-curves-Cubic/Delphi/bitmap-b-zier-curves-cubic.delphi rename to Task/Bitmap-B-zier-curves-Cubic/Delphi/bitmap-b-zier-curves-cubic.pas diff --git a/Task/Bitmap-B-zier-curves-Cubic/FutureBasic/bitmap-b-zier-curves-cubic.basic b/Task/Bitmap-B-zier-curves-Cubic/FutureBasic/bitmap-b-zier-curves-cubic.basic new file mode 100644 index 0000000000..e947c6024f --- /dev/null +++ b/Task/Bitmap-B-zier-curves-Cubic/FutureBasic/bitmap-b-zier-curves-cubic.basic @@ -0,0 +1,31 @@ +void local fn BuildWindow + window 1, @"Cubic Bezier Curve", ( 0, 0, 300, 300 ), NSWindowStyleMaskTitled + NSWindowStyleMaskClosable + WindowSetBackgroundColor( 1, fn ColorBlack ) + WindowSubclassContentView(1) + ViewSetNeedsDisplay( _windowContentViewTag ) +end fn + +void local fn DrawInView( tag as NSInteger ) + ColorSetStroke( fn ColorYellow ) + BezierPathRef path = fn BezierPathInit + BezierPathMoveToPoint( path, fn CGPointMake( 50, 50 ) ) + CGPoint controlPoint1 = fn CGPointMake( 120, 200 ) + CGPoint controlPoint2 = fn CGPointMake( 180, 0 ) + CGPoint endPoint = fn CGPointMake( 260, 100 ) + BezierPathRelativeCurveToPoint( path, controlPoint1, controlPoint2, endPoint ) + BezierPathSetLineWidth( path, 4.0 ) + BezierPathStroke( path ) +end fn + +void local fn DoDialog( ev as long, tag as long ) + select ( ev ) + case _viewDrawRect : fn DrawInView(tag) + case _windowWillClose : end + end select +end fn + +fn BuildWindow + +on dialog fn DoDialog + +HandleEvents diff --git a/Task/Bitmap-B-zier-curves-Cubic/Julia/bitmap-b-zier-curves-cubic.julia b/Task/Bitmap-B-zier-curves-Cubic/Julia/bitmap-b-zier-curves-cubic.jl similarity index 100% rename from Task/Bitmap-B-zier-curves-Cubic/Julia/bitmap-b-zier-curves-cubic.julia rename to Task/Bitmap-B-zier-curves-Cubic/Julia/bitmap-b-zier-curves-cubic.jl diff --git a/Task/Bitmap-B-zier-curves-Cubic/Kotlin/bitmap-b-zier-curves-cubic.kotlin b/Task/Bitmap-B-zier-curves-Cubic/Kotlin/bitmap-b-zier-curves-cubic.kts similarity index 100% rename from Task/Bitmap-B-zier-curves-Cubic/Kotlin/bitmap-b-zier-curves-cubic.kotlin rename to Task/Bitmap-B-zier-curves-Cubic/Kotlin/bitmap-b-zier-curves-cubic.kts diff --git a/Task/Bitmap-B-zier-curves-Cubic/OCaml/bitmap-b-zier-curves-cubic.ocaml b/Task/Bitmap-B-zier-curves-Cubic/OCaml/bitmap-b-zier-curves-cubic.ml similarity index 100% rename from Task/Bitmap-B-zier-curves-Cubic/OCaml/bitmap-b-zier-curves-cubic.ocaml rename to Task/Bitmap-B-zier-curves-Cubic/OCaml/bitmap-b-zier-curves-cubic.ml diff --git a/Task/Bitmap-B-zier-curves-Quadratic/ALGOL-68/bitmap-b-zier-curves-quadratic.alg b/Task/Bitmap-B-zier-curves-Quadratic/ALGOL-68/bitmap-b-zier-curves-quadratic.alg new file mode 100644 index 0000000000..c06ba96d7a --- /dev/null +++ b/Task/Bitmap-B-zier-curves-Quadratic/ALGOL-68/bitmap-b-zier-curves-quadratic.alg @@ -0,0 +1,41 @@ +BEGIN # draw a quadratic curve using Bresenham's line algoritm # + + PR READ "prelude/Bitmap.a68" PR; + PR READ "prelude/Bitmap/Bresenhams_line_algorithm.a68" PR; + + PROC quadratic bezier = ( REF IMAGE bm, INT x1, y1, x2, y2, x3, y3, nseg, REAL scale )VOID: + BEGIN + INT prevx := 0, prevy := 0; + FOR i FROM 0 TO nseg DO + REAL t = i / nseg; + REAL t1 = 1 - t; + REAL a = t1 * t1; + REAL b = 2 * t * t1; + REAL c = t * t; + INT currx = ENTIER ( scale * ( a * x1 + b * x2 + c * x3 + 0.5 ) ); + INT curry = ENTIER ( scale * ( a * y1 + b * y2 + c * y3 + 0.5 ) ); + IF i > 0 THEN + ( line OF class image )( bm + , ( prevx, prevy ) + , ( currx, curry ) + , black OF class image + ) + FI; + prevx := currx; + prevy := curry + OD + END # quadratic bezier # ; + + BEGIN + REF IMAGE bm = INIT LOC[ 1 : 60, 1 : 40 ]PIXEL; + ( fill OF class image )( bm, white OF class image ); + quadratic bezier( bm, 10, 100, 250, 270, 150, 20, 20, 70 / 300 ); + # print in monochrome # + FOR y FROM 2 UPB bm BY -1 TO 2 LWB bm DO + FOR x FROM 1 LWB bm TO 1 UPB bm DO + print( ( IF PIXEL( bm[ x, y ] ) /= white OF class image THEN "##" ELSE " " FI ) ) + OD; + print( ( newline ) ) + OD + END +END diff --git a/Task/Bitmap-B-zier-curves-Quadratic/Ada/bitmap-b-zier-curves-quadratic-1.ada b/Task/Bitmap-B-zier-curves-Quadratic/Ada/bitmap-b-zier-curves-quadratic-1.adb similarity index 100% rename from Task/Bitmap-B-zier-curves-Quadratic/Ada/bitmap-b-zier-curves-quadratic-1.ada rename to Task/Bitmap-B-zier-curves-Quadratic/Ada/bitmap-b-zier-curves-quadratic-1.adb diff --git a/Task/Bitmap-B-zier-curves-Quadratic/Ada/bitmap-b-zier-curves-quadratic-2.ada b/Task/Bitmap-B-zier-curves-Quadratic/Ada/bitmap-b-zier-curves-quadratic-2.adb similarity index 100% rename from Task/Bitmap-B-zier-curves-Quadratic/Ada/bitmap-b-zier-curves-quadratic-2.ada rename to Task/Bitmap-B-zier-curves-Quadratic/Ada/bitmap-b-zier-curves-quadratic-2.adb diff --git a/Task/Bitmap-B-zier-curves-Quadratic/Delphi/bitmap-b-zier-curves-quadratic.delphi b/Task/Bitmap-B-zier-curves-Quadratic/Delphi/bitmap-b-zier-curves-quadratic.pas similarity index 100% rename from Task/Bitmap-B-zier-curves-Quadratic/Delphi/bitmap-b-zier-curves-quadratic.delphi rename to Task/Bitmap-B-zier-curves-Quadratic/Delphi/bitmap-b-zier-curves-quadratic.pas diff --git a/Task/Bitmap-B-zier-curves-Quadratic/EasyLang/bitmap-b-zier-curves-quadratic.easy b/Task/Bitmap-B-zier-curves-Quadratic/EasyLang/bitmap-b-zier-curves-quadratic.easy new file mode 100644 index 0000000000..4d1203c99e --- /dev/null +++ b/Task/Bitmap-B-zier-curves-Quadratic/EasyLang/bitmap-b-zier-curves-quadratic.easy @@ -0,0 +1,16 @@ +sysconf topleft +proc quadraticbezier x1 y1 x2 y2 x3 y3 nseg . + gpenup + for i = 0 to nseg + t = i / nseg + t1 = 1 - t + a = t1 * t1 + b = 2 * t * t1 + c = t * t + x = a * x1 + b * x2 + c * x3 + 0.5 + y = a * y1 + b * y2 + c * y3 + 0.5 + glineto x y + . +. +glinewidth 0.5 +quadraticbezier 1 1 30 37 59 1 100 diff --git a/Task/Bitmap-B-zier-curves-Quadratic/Kotlin/bitmap-b-zier-curves-quadratic.kotlin b/Task/Bitmap-B-zier-curves-Quadratic/Kotlin/bitmap-b-zier-curves-quadratic.kts similarity index 100% rename from Task/Bitmap-B-zier-curves-Quadratic/Kotlin/bitmap-b-zier-curves-quadratic.kotlin rename to Task/Bitmap-B-zier-curves-Quadratic/Kotlin/bitmap-b-zier-curves-quadratic.kts diff --git a/Task/Bitmap-B-zier-curves-Quadratic/M2000-Interpreter/bitmap-b-zier-curves-quadratic.m2000 b/Task/Bitmap-B-zier-curves-Quadratic/M2000-Interpreter/bitmap-b-zier-curves-quadratic.m2000 new file mode 100644 index 0000000000..a5b02611cc --- /dev/null +++ b/Task/Bitmap-B-zier-curves-Quadratic/M2000-Interpreter/bitmap-b-zier-curves-quadratic.m2000 @@ -0,0 +1,191 @@ +module bezier { + Function Bitmap { + def x as long, y as long, Import as boolean + If match("NN") then + Read x, y + else.if Match("N") Then + \\ is a file? + Read f as long + byte whitespace[0] + if not Eof(f) then + get #f, whitespace :P6$=chr$(whitespace[0]) + get #f, whitespace : P6$+=chr$(whitespace[0]) + boolean getW=true, getH=true, getV=true + long v + If p6$="P6" Then + do + get #f, whitespace + select case whitespace[0] + case 35 + {do get #f, whitespace + until whitespace[0]=10 + } + case 32, 9, 13, 10 + { if getW and x<>0 then + getW=false + else.if getH and y<>0 then + getH=false + else.if getV and v<>0 then + getV=false + end if + } + case 48 to 57 + {if getW then + x*=10 + x+=whitespace[0]-48 + else.if getH then + y*=10 + y+=whitespace[0]-48 + else.if getV then + v*=10 + v+=whitespace[0]-48 + end if + } + End Select + iF eof(f) then Error "Not a ppm file" + until getV=false + else + Error "Not a P6 ppm" + end if + Import=True + end if + else + Error "No proper arguments" + end if + if x<1 or y<1 then Error "Wrong dimensions" + structure rgb { + red as byte + green as byte + blue as byte + } + m=len(rgb)*x mod 4 + if m>0 then m=4-m ' add some bytes to raster line + m+=len(rgb) *x + Structure rasterline { + { + pad as byte*m + } + hline as rgb*x + } + Structure Raster { + magic as integer*4 + w as integer*4 + h as integer*4 + { + linesB as byte*len(rasterline)*y + } + lines as rasterline*y + } + Buffer Clear Image1 as Raster + Return Image1, 0!magic:="cDIB", 0!w:=Hex$(x,2), 0!h:=Hex$(y, 2) + if not Import then Return Image1, 0!lines:=String$(chrcode$(0xffff), Len(rasterline)*y div 2) + Buffer Clear Pad as Byte*4 + SetPixel=Lambda Image1, Pad, aLines=Len(Raster)-Len(Rasterline), blines=-Len(Rasterline) (x, y, c) ->{ + where=alines+3*x+blines*y + if c>0 then c=color(c) + c-! + Return Pad, 0:=c as long + Return Image1, 0!where:=Eval(Pad, 2) as byte, 0!where+1:=Eval(Pad, 1) as byte, 0!where+2:=Eval(Pad, 0) as byte + } + GetPixel=Lambda Image1,aLines=Len(Raster)-Len(Rasterline), blines=-Len(Rasterline) (x,y) ->{ + where=alines+3*x+blines*y + =color(Eval(image1, where+2 as byte), Eval(image1, where+1 as byte), Eval(image1, where as byte)) + } + StrDib$=Lambda$ Image1, Raster -> { + =Eval$(Image1, 0, Len(Raster)) + } + CopyImage=Lambda Image1 (image$) -> { + if left$(image$,12)=Eval$(Image1, 0, 24 ) Then { + Return Image1, 0:=Image$ + } Else Error "Can't Copy Image" + } + Export2File=Lambda Image1, x, y (f) -> { + Print #f, "P6";chr$(10);"# Created using M2000 Interpreter";chr$(10); + Print #f, x;" ";y;" 255";chr$(10); + x2=x-1 : where=0 + x0=x*3 + structure rgbP6 { + r as byte + g as byte + b as byte + } + buffer Pad as rgbP6*x*y + For y1=y-1 to 0 { + Return pad, x*y1:=eval$(image1, 0!linesB!where, x0) + where+=x0 + m=where mod 4 : if m<>0 then where+=4-m + } + For x1=0 to x*y-1 { + Push Eval(pad, x1!b) : Return pad, x1!b:=Eval(pad, x1!r), x1!r:=Number + } + Put #f, pad + } + if Import then { + x0=x-1 : where=0 + structure rgbP6 { + r as byte, g as byte, b as byte + } + buffer Pad1 as rgbP6*x*y + Get #f, Pad1 + For x1=0 to x*y-1 { + Push Eval(pad1, x1!b) : Return pad1, x1!b:=Eval(pad1, x1!r), x1!r:=Number + } + x1=x*3 + For y1=y-1 to 0 { + Return Image1, 0!linesB!where:=Eval$(Pad1, y1*x, x1) + where+=3*(x0+1) + m=where mod 4 : if m<>0 then where+=4-m + } + } + Group Bitmap { + type:Bitmap + SetPixel=SetPixel + GetPixel=GetPixel + Image$=StrDib$ + Copy=CopyImage + ToFile=Export2File + } + =Bitmap + } + module bezier (&ppm as Bitmap, x1, y1, x2, y2, x3, y3, n, col=0){ + Group point_ { + long x,y + } + Long i + Double t, t1, a, b, c, d + Dim p(n+1)=point_ + For i = 0 To n + t = i / n + t1 = 1 - t + a = t1 ^ 2 + b = t * t1 * 2 + c = t ^ 2 + p(i).x = Int(a * x1 + b * x2 + c * x3 + .5) + p(i).y = Int(a * y1 + b * y2 + c * y3 + .5) + Next + + For i = 0 To n -1 + Br_line(p(i).x, p(i).y, p(i +1).x, p(i +1).y, col) + Next + sub Br_line(x0 As Long, y0 As Long, x1 As Long, y1 As Long, Col=0) + Local Long dx = Abs(x1 - x0), dy = Abs(y1 - y0) + Local Long sx = If(x0 < x1-> 1, -1) + Local Long sy = If(y0 < y1-> 1, -1) + Local Long er = If(dx > dy-> dx, -dy) div 2, e2 + Do + Call ppm.SetPixel(x0, y0, Col) + If x0=x1 And y0=y1 Then Exit + e2 = er + If e2 > -dx Then Er -= dy : x0 += sx + If e2 < dy Then Er += dx : y0 += sy + Always + end sub + } + A=Bitmap(250, 250) + bezier &A, 10, 100, 220, 310, 150, 20, 20 + move 3000,3000 : image A.Image$() + Open "curve.ppm" for output as #f + Call A.tofile(f) + close #f +} +bezier diff --git a/Task/Bitmap-B-zier-curves-Quadratic/OCaml/bitmap-b-zier-curves-quadratic.ocaml b/Task/Bitmap-B-zier-curves-Quadratic/OCaml/bitmap-b-zier-curves-quadratic.ml similarity index 100% rename from Task/Bitmap-B-zier-curves-Quadratic/OCaml/bitmap-b-zier-curves-quadratic.ocaml rename to Task/Bitmap-B-zier-curves-Quadratic/OCaml/bitmap-b-zier-curves-quadratic.ml diff --git a/Task/Bitmap-Bresenhams-line-algorithm/11l/bitmap-bresenhams-line-algorithm.11l b/Task/Bitmap-Bresenhams-line-algorithm/11l/bitmap-bresenhams-line-algorithm.11l index 3c00cb16f4..928f45dde9 100644 --- a/Task/Bitmap-Bresenhams-line-algorithm/11l/bitmap-bresenhams-line-algorithm.11l +++ b/Task/Bitmap-Bresenhams-line-algorithm/11l/bitmap-bresenhams-line-algorithm.11l @@ -1,13 +1,4 @@ -T Colour - Byte r, g, b - - F (r, g, b) - .r = r - .g = g - .b = b - - F ==(other) - R .r == other.r & .g == other.g & .b == other.b +T Colour = BVec3 V black = Colour(0, 0, 0) V white = Colour(255, 255, 255) diff --git a/Task/Bitmap-Bresenhams-line-algorithm/ALGOL-68/bitmap-bresenhams-line-algorithm-1.alg b/Task/Bitmap-Bresenhams-line-algorithm/ALGOL-68/bitmap-bresenhams-line-algorithm-1.alg deleted file mode 100644 index 71ca3c026d..0000000000 --- a/Task/Bitmap-Bresenhams-line-algorithm/ALGOL-68/bitmap-bresenhams-line-algorithm-1.alg +++ /dev/null @@ -1,42 +0,0 @@ -# -*- coding: utf-8 -*- # - -line OF class image := (REF IMAGE picture, POINT start, stop, PIXEL color)VOID: -BEGIN - REAL dx = ABS (x OF stop - x OF start), - dy = ABS (y OF stop - y OF start); - REAL err; - POINT here := start, - step := (1, 1); - IF x OF start > x OF stop THEN - x OF step := -1 - FI; - IF y OF start > y OF stop THEN - y OF step := -1 - FI; - IF dx > dy THEN - err := dx / 2; - WHILE x OF here /= x OF stop DO - picture[x OF here, y OF here] := color; - err -:= dy; - IF err < 0 THEN - y OF here +:= y OF step; - err +:= dx - FI; - x OF here +:= x OF step - OD - ELSE - err := dy / 2; - WHILE y OF here /= y OF stop DO - picture[x OF here, y OF here] := color; - err -:= dx; - IF err < 0 THEN - x OF here +:= x OF step; - err +:= dy - FI; - y OF here +:= y OF step - OD - FI; - picture[x OF here, y OF here] := color # ensure dots to be drawn # -END # line #; - -SKIP diff --git a/Task/Bitmap-Bresenhams-line-algorithm/ALGOL-68/bitmap-bresenhams-line-algorithm-2.alg b/Task/Bitmap-Bresenhams-line-algorithm/ALGOL-68/bitmap-bresenhams-line-algorithm-2.alg deleted file mode 100644 index d1ba6015a9..0000000000 --- a/Task/Bitmap-Bresenhams-line-algorithm/ALGOL-68/bitmap-bresenhams-line-algorithm-2.alg +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/a68g --script # -# -*- coding: utf-8 -*- # - -PR READ "prelude/Bitmap.a68" PR; # c.f. [[rc:Bitmap]] # -PR READ "prelude/Bitmap/Bresenhams_line_algorithm.a68" PR; - -### The test program: ### -test:( - REF IMAGE x = INIT LOC[1:16, 1:16]PIXEL; - (fill OF class image)(x, white OF class image); - (line OF class image)(x, ( 1, 8), ( 8,16), black OF class image); - (line OF class image)(x, ( 8,16), (16, 8), black OF class image); - (line OF class image)(x, (16, 8), ( 8, 1), black OF class image); - (line OF class image)(x, ( 8, 1), ( 1, 8), black OF class image); - (print OF class image)(x) -) diff --git a/Task/Bitmap-Bresenhams-line-algorithm/ALGOL-68/bitmap-bresenhams-line-algorithm.alg b/Task/Bitmap-Bresenhams-line-algorithm/ALGOL-68/bitmap-bresenhams-line-algorithm.alg new file mode 100644 index 0000000000..223c635fd0 --- /dev/null +++ b/Task/Bitmap-Bresenhams-line-algorithm/ALGOL-68/bitmap-bresenhams-line-algorithm.alg @@ -0,0 +1,16 @@ +#!/usr/bin/a68g --script # +# -*- coding: utf-8 -*- # + +PR READ "prelude/Bitmap.a68" PR; +PR READ "prelude/Bitmap/Bresenhams_line_algorithm.a68" PR; + +### The test program: ### +( + REF IMAGE x = INIT LOC[1:16, 1:16]PIXEL; + (fill OF class image)(x, white OF class image); + (line OF class image)(x, ( 1, 8), ( 8,16), black OF class image); + (line OF class image)(x, ( 8,16), (16, 8), black OF class image); + (line OF class image)(x, (16, 8), ( 8, 1), black OF class image); + (line OF class image)(x, ( 8, 1), ( 1, 8), black OF class image); + (print OF class image)(x) +) diff --git a/Task/Bitmap-Bresenhams-line-algorithm/Ada/bitmap-bresenhams-line-algorithm-1.ada b/Task/Bitmap-Bresenhams-line-algorithm/Ada/bitmap-bresenhams-line-algorithm-1.adb similarity index 100% rename from Task/Bitmap-Bresenhams-line-algorithm/Ada/bitmap-bresenhams-line-algorithm-1.ada rename to Task/Bitmap-Bresenhams-line-algorithm/Ada/bitmap-bresenhams-line-algorithm-1.adb diff --git a/Task/Bitmap-Bresenhams-line-algorithm/Ada/bitmap-bresenhams-line-algorithm-2.ada b/Task/Bitmap-Bresenhams-line-algorithm/Ada/bitmap-bresenhams-line-algorithm-2.adb similarity index 100% rename from Task/Bitmap-Bresenhams-line-algorithm/Ada/bitmap-bresenhams-line-algorithm-2.ada rename to Task/Bitmap-Bresenhams-line-algorithm/Ada/bitmap-bresenhams-line-algorithm-2.adb diff --git a/Task/Bitmap-Bresenhams-line-algorithm/Arturo/bitmap-bresenhams-line-algorithm.arturo b/Task/Bitmap-Bresenhams-line-algorithm/Arturo/bitmap-bresenhams-line-algorithm.arturo new file mode 100644 index 0000000000..874b30a87e --- /dev/null +++ b/Task/Bitmap-Bresenhams-line-algorithm/Arturo/bitmap-bresenhams-line-algorithm.arturo @@ -0,0 +1,67 @@ +; Bitmap object definition +define :bitmap [ + init: method [width :integer height :integer][ + \width: width + \height: height + \grid: array.of:@[width height] false + ] + + setOn: method [x :integer y :integer][ + \grid\[y]\[x]: true + ] + + line: method [x0 :integer y0 :integer x1 :integer y1 :integer][ + [dx,dy]: @[abs x1 - x0, abs y1 - y0] + [x,y]: @[x0, y0] + sx: (x0 > x1) ? -> neg 1 -> 1 + sy: (y0 > y1) ? -> neg 1 -> 1 + + switch dx > dy [ + err: dx // 2 + while [x <> x1][ + \setOn x y + if negative? err: <= err - dy -> + [y, err]: @[y + sy, err + dx] + + x: x + sx + ] + ][ + err: dy // 2 + while [y <> y1][ + \setOn x y + if negative? err: <= err - dx -> + [x, err]: @[x + sx, err + dy] + y: y + sy + ] + ] + \setOn x y + ] + + string: method [][ + join.with:"\n" @[ + "+" ++ (repeat "-" \width) ++ "+" + join.with:"\n" map 0..dec \height 'y [ + "|" ++ (join.with:"" map 0..dec \width 'x -> + \grid\[dec \height-y]\[x] ? -> "@" -> " " + ) ++ "|" + ] + "+" ++ (repeat "-" \width) ++ "+" + ] + ] +] + +; Create bitmap +bitmap: to :bitmap @[17 17]! + +; and... draw a diamond shape +points: @[ + [1 8 8 16] + [8 16 16 8] + [16 8 8 1] + [8 1 1 8] +] + +loop points 'p -> + bitmap\line p\0 p\1 p\2 p\3 + +print bitmap diff --git a/Task/Bitmap-Bresenhams-line-algorithm/AutoIt/bitmap-bresenhams-line-algorithm.autoit b/Task/Bitmap-Bresenhams-line-algorithm/AutoIt/bitmap-bresenhams-line-algorithm.au3 similarity index 100% rename from Task/Bitmap-Bresenhams-line-algorithm/AutoIt/bitmap-bresenhams-line-algorithm.autoit rename to Task/Bitmap-Bresenhams-line-algorithm/AutoIt/bitmap-bresenhams-line-algorithm.au3 diff --git a/Task/Bitmap-Bresenhams-line-algorithm/Crystal/bitmap-bresenhams-line-algorithm-1.cr b/Task/Bitmap-Bresenhams-line-algorithm/Crystal/bitmap-bresenhams-line-algorithm-1.cr new file mode 100644 index 0000000000..f0a7e50bb0 --- /dev/null +++ b/Task/Bitmap-Bresenhams-line-algorithm/Crystal/bitmap-bresenhams-line-algorithm-1.cr @@ -0,0 +1,17 @@ +require "./pixmap" + +class Pixmap + def line (x0, y0, x1, y1, color) + dx, sx = (x1-x0).abs, x0dy ? dx : -dy) // 2 + + loop do + self[x0, y0] = color + break if x0 == x1 && y0 == y1 + e2 = err + (err -= dy; x0 += sx) if e2 >-dx + (err += dx; y0 += sy) if e2 < dy + end + end +end diff --git a/Task/Bitmap-Bresenhams-line-algorithm/Crystal/bitmap-bresenhams-line-algorithm-2.cr b/Task/Bitmap-Bresenhams-line-algorithm/Crystal/bitmap-bresenhams-line-algorithm-2.cr new file mode 100644 index 0000000000..fa74ba9af7 --- /dev/null +++ b/Task/Bitmap-Bresenhams-line-algorithm/Crystal/bitmap-bresenhams-line-algorithm-2.cr @@ -0,0 +1,7 @@ +require "./bresenham" + +img = Pixmap.new 10, 5, Color::WHITE + +img.line 0, 3, 9, 0, Color::RED + +img.write STDOUT diff --git a/Task/Bitmap-Bresenhams-line-algorithm/Delphi/bitmap-bresenhams-line-algorithm.delphi b/Task/Bitmap-Bresenhams-line-algorithm/Delphi/bitmap-bresenhams-line-algorithm.pas similarity index 100% rename from Task/Bitmap-Bresenhams-line-algorithm/Delphi/bitmap-bresenhams-line-algorithm.delphi rename to Task/Bitmap-Bresenhams-line-algorithm/Delphi/bitmap-bresenhams-line-algorithm.pas diff --git a/Task/Bitmap-Bresenhams-line-algorithm/EasyLang/bitmap-bresenhams-line-algorithm.easy b/Task/Bitmap-Bresenhams-line-algorithm/EasyLang/bitmap-bresenhams-line-algorithm.easy index 536d330933..b0a250c7ec 100644 --- a/Task/Bitmap-Bresenhams-line-algorithm/EasyLang/bitmap-bresenhams-line-algorithm.easy +++ b/Task/Bitmap-Bresenhams-line-algorithm/EasyLang/bitmap-bresenhams-line-algorithm.easy @@ -1,8 +1,7 @@ -proc pset x y . . - move x / 4 y / 4 - rect 0.25 0.25 +proc pset x y . + grect x / 4 y / 4 0.25 0.25 . -proc drawline x0 y0 x1 y1 . . +proc drawline x0 y0 x1 y1 . dx = abs (x1 - x0) sx = -1 if x0 < x1 diff --git a/Task/Bitmap-Bresenhams-line-algorithm/Euphoria/bitmap-bresenhams-line-algorithm.euphoria b/Task/Bitmap-Bresenhams-line-algorithm/Euphoria/bitmap-bresenhams-line-algorithm.eu similarity index 100% rename from Task/Bitmap-Bresenhams-line-algorithm/Euphoria/bitmap-bresenhams-line-algorithm.euphoria rename to Task/Bitmap-Bresenhams-line-algorithm/Euphoria/bitmap-bresenhams-line-algorithm.eu diff --git a/Task/Bitmap-Bresenhams-line-algorithm/Julia/bitmap-bresenhams-line-algorithm.julia b/Task/Bitmap-Bresenhams-line-algorithm/Julia/bitmap-bresenhams-line-algorithm.jl similarity index 100% rename from Task/Bitmap-Bresenhams-line-algorithm/Julia/bitmap-bresenhams-line-algorithm.julia rename to Task/Bitmap-Bresenhams-line-algorithm/Julia/bitmap-bresenhams-line-algorithm.jl diff --git a/Task/Bitmap-Bresenhams-line-algorithm/M2000-Interpreter/bitmap-bresenhams-line-algorithm.m2000 b/Task/Bitmap-Bresenhams-line-algorithm/M2000-Interpreter/bitmap-bresenhams-line-algorithm.m2000 new file mode 100644 index 0000000000..5ed0c0f987 --- /dev/null +++ b/Task/Bitmap-Bresenhams-line-algorithm/M2000-Interpreter/bitmap-bresenhams-line-algorithm.m2000 @@ -0,0 +1,20 @@ +' using Twips +' twipsX is 15 twips. So for 96 dpi, we have 1440/96=15 twips/pixel +Module Bresenham_s_line_algorithm { + Module Br_line(x0 As Long, y0 As Long, x1 As Long, y1 As Long, Col=15) { + Long dx = Abs(x1 - x0), dy = Abs(y1 - y0) + Long sx = If(x0 < x1-> TWIPSX, -TWIPSX) + Long sy = If(y0 < y1-> TWIPSY, -TWIPSY) + Long er = If(dx > dy-> dx, -dy) div 2, e2 + Do + PSet col, x0, y0 + If abs(x0-x1)<=TWIPSX And abs(y0-y1)<=TWIPSY Then Exit + e2 = er + If e2 > -dx Then Er -= dy : x0 += sx + If e2 < dy Then Er += dx : y0 += sy + Always + } + cls ,0 + Br_line scale.x*.2, scale.y*.2, scale.x*.8, scale.y*.8 , #FFbb77 +} +Bresenham_s_line_algorithm diff --git a/Task/Bitmap-Bresenhams-line-algorithm/OCaml/bitmap-bresenhams-line-algorithm.ocaml b/Task/Bitmap-Bresenhams-line-algorithm/OCaml/bitmap-bresenhams-line-algorithm.ml similarity index 100% rename from Task/Bitmap-Bresenhams-line-algorithm/OCaml/bitmap-bresenhams-line-algorithm.ocaml rename to Task/Bitmap-Bresenhams-line-algorithm/OCaml/bitmap-bresenhams-line-algorithm.ml diff --git a/Task/Bitmap-Bresenhams-line-algorithm/Pluto/bitmap-bresenhams-line-algorithm-1.pluto b/Task/Bitmap-Bresenhams-line-algorithm/Pluto/bitmap-bresenhams-line-algorithm-1.pluto new file mode 100644 index 0000000000..8ab23127e7 --- /dev/null +++ b/Task/Bitmap-Bresenhams-line-algorithm/Pluto/bitmap-bresenhams-line-algorithm-1.pluto @@ -0,0 +1,27 @@ +local canvas = require "canvas" + +local function line(c, x0, y0, x1, y1, col) + local dx = math.abs(x1 - x0) + local dy = math.abs(y1 - y0) + local sx = (x0 < x1) ? 1 : -1 + local sy = (y0 < y1) ? 1 : -1 + local err = (dx > dy ? dx : - dy) // 2 + while true do + c:set(x0, y0, col) + if x0 == x1 and y0 == y1 then break end + local e2 = err + if e2 > -dx then + err -= dy + x0 += sx + end + if e2 < dy then + err += dx + y0 += sy + end + end +end + +local c = canvas.new(400, 400) +c:fill(0xffffff) -- white background +line(c, 0, 0, 399, 399, 0x0000ff) -- draw a red diagonal +io.contents("mybmp.bmp", c:tobmp()) -- save to a bitmap file diff --git a/Task/Bitmap-Bresenhams-line-algorithm/Pluto/bitmap-bresenhams-line-algorithm-2.pluto b/Task/Bitmap-Bresenhams-line-algorithm/Pluto/bitmap-bresenhams-line-algorithm-2.pluto new file mode 100644 index 0000000000..a3504b25b4 --- /dev/null +++ b/Task/Bitmap-Bresenhams-line-algorithm/Pluto/bitmap-bresenhams-line-algorithm-2.pluto @@ -0,0 +1,6 @@ +require "bitmap" + +local bmp = bitmap.of(400, 400, color.white, "mybmp") +bmp:line(0, 0, 399, 399, color.red) +bmp:view() +bmp:save() -- if required diff --git a/Task/Bitmap-Bresenhams-line-algorithm/Rust/bitmap-bresenhams-line-algorithm.rust b/Task/Bitmap-Bresenhams-line-algorithm/Rust/bitmap-bresenhams-line-algorithm.rs similarity index 100% rename from Task/Bitmap-Bresenhams-line-algorithm/Rust/bitmap-bresenhams-line-algorithm.rust rename to Task/Bitmap-Bresenhams-line-algorithm/Rust/bitmap-bresenhams-line-algorithm.rs diff --git a/Task/Bitmap-Bresenhams-line-algorithm/VBScript/bitmap-bresenhams-line-algorithm.vb b/Task/Bitmap-Bresenhams-line-algorithm/VBScript/bitmap-bresenhams-line-algorithm.vbs similarity index 100% rename from Task/Bitmap-Bresenhams-line-algorithm/VBScript/bitmap-bresenhams-line-algorithm.vb rename to Task/Bitmap-Bresenhams-line-algorithm/VBScript/bitmap-bresenhams-line-algorithm.vbs diff --git a/Task/Bitmap-Flood-fill/Ada/bitmap-flood-fill-1.ada b/Task/Bitmap-Flood-fill/Ada/bitmap-flood-fill-1.adb similarity index 100% rename from Task/Bitmap-Flood-fill/Ada/bitmap-flood-fill-1.ada rename to Task/Bitmap-Flood-fill/Ada/bitmap-flood-fill-1.adb diff --git a/Task/Bitmap-Flood-fill/Ada/bitmap-flood-fill-2.ada b/Task/Bitmap-Flood-fill/Ada/bitmap-flood-fill-2.adb similarity index 100% rename from Task/Bitmap-Flood-fill/Ada/bitmap-flood-fill-2.ada rename to Task/Bitmap-Flood-fill/Ada/bitmap-flood-fill-2.adb diff --git a/Task/Bitmap-Flood-fill/AutoHotkey/bitmap-flood-fill-2.ahk b/Task/Bitmap-Flood-fill/AutoHotkey/bitmap-flood-fill-2.ahk index 9ff5334cf8..ab321c5681 100644 --- a/Task/Bitmap-Flood-fill/AutoHotkey/bitmap-flood-fill-2.ahk +++ b/Task/Bitmap-Flood-fill/AutoHotkey/bitmap-flood-fill-2.ahk @@ -1,55 +1,55 @@ #NoEnv #SingleInstance, Force - SetBatchLines, -1 - CoordMode, Mouse - CoordMode, Pixel + SetBatchLines, -1 + CoordMode, Mouse + CoordMode, Pixel return CapsLock:: - KeyWait, CapsLock - MouseGetPos, X, Y - PixelGetColor, color, X, Y - FloodFill(x, y, color, 0x000000, 1, "Esc") - MsgBox Done! + KeyWait, CapsLock + MouseGetPos, X, Y + PixelGetColor, color, X, Y + FloodFill(x, y, color, 0x000000, 1, "Esc") + MsgBox Done! Return FloodFill( 0x, 0y, target, replacement, mode=1, key="" ) { - VarSetCapacity(Rect, 16, 0) - hDC := DllCall("GetDC", UInt, 0) - hBrush := DllCall("CreateSolidBrush", UInt, replacement) - - l := 0 - while l >= 0 - { - if getkeystate(key, "P") - return - x := %l%x, y := %l%y - %l%p++ - p := %l%p - PixelGetColor, color, x, y - if (color = target) - { - NumPut(x, Rect, 0) - NumPut(y, Rect, 4) - NumPut(x+1, Rect, 8) - NumPut(y+1, Rect, 12) - DllCall("FillRect", UInt, hDC, Str, Rect, UInt, hBrush) - } - else if (p = 1) - { - %l%x := %l%y := %l%p := "", l-- - continue - } - if (p < 5) - ol := l++ - , %l%x := %ol%x + (p = 1 ? 1 : p = 2 ? -1 : 0) - , %l%y := %ol%y + (p = 3 ? 1 : p = 4 ? -1 : 0) - else - %l%x := %l%y := %l%p := "", l-- - } - - DllCall("ReleaseDC", UInt, 0, UInt, hDC) - DllCall("DeleteObject", UInt, hBrush) + VarSetCapacity(Rect, 16, 0) + hDC := DllCall("GetDC", UInt, 0) + hBrush := DllCall("CreateSolidBrush", UInt, replacement) + + l := 0 + while l >= 0 + { + if getkeystate(key, "P") + return + x := %l%x, y := %l%y + %l%p++ + p := %l%p + PixelGetColor, color, x, y + if (color = target) + { + NumPut(x, Rect, 0) + NumPut(y, Rect, 4) + NumPut(x+1, Rect, 8) + NumPut(y+1, Rect, 12) + DllCall("FillRect", UInt, hDC, Str, Rect, UInt, hBrush) + } + else if (p = 1) + { + %l%x := %l%y := %l%p := "", l-- + continue + } + if (p < 5) + ol := l++ + , %l%x := %ol%x + (p = 1 ? 1 : p = 2 ? -1 : 0) + , %l%y := %ol%y + (p = 3 ? 1 : p = 4 ? -1 : 0) + else + %l%x := %l%y := %l%p := "", l-- + } + + DllCall("ReleaseDC", UInt, 0, UInt, hDC) + DllCall("DeleteObject", UInt, hBrush) } diff --git a/Task/Bitmap-Flood-fill/C++/bitmap-flood-fill-2.cpp b/Task/Bitmap-Flood-fill/C++/bitmap-flood-fill-2.cpp index 3518acceab..1791da5b87 100644 --- a/Task/Bitmap-Flood-fill/C++/bitmap-flood-fill-2.cpp +++ b/Task/Bitmap-Flood-fill/C++/bitmap-flood-fill-2.cpp @@ -16,25 +16,25 @@ void FloodFillAlgorithm::flood(Point startPoint, Mat* tgtMat) { if (image->at(startPoint) == srcColor) { queue pointQueue; - pointQueue.push(startPoint); + pointQueue.push(startPoint); - while (!pointQueue.empty()) { - Point p = pointQueue.front(); - pointQueue.pop(); + while (!pointQueue.empty()) { + Point p = pointQueue.front(); + pointQueue.pop(); - if (insideImage(p)) { + if (insideImage(p)) { - if ((image->at(p) == srcColor)) { - image->at(p) = tgtMat->at(p); + if ((image->at(p) == srcColor)) { + image->at(p) = tgtMat->at(p); - pointQueue.push(Point(p.x + 1, p.y)); - pointQueue.push(Point(p.x - 1, p.y)); - pointQueue.push(Point(p.x, p.y + 1)); - pointQueue.push(Point(p.x, p.y - 1)); - } - } + pointQueue.push(Point(p.x + 1, p.y)); + pointQueue.push(Point(p.x - 1, p.y)); + pointQueue.push(Point(p.x, p.y + 1)); + pointQueue.push(Point(p.x, p.y - 1)); + } + } - } + } } } diff --git a/Task/Bitmap-Flood-fill/C/bitmap-flood-fill-3.c b/Task/Bitmap-Flood-fill/C/bitmap-flood-fill-3.c index 9e3b20b4a1..69c8175bc1 100644 --- a/Task/Bitmap-Flood-fill/C/bitmap-flood-fill-3.c +++ b/Task/Bitmap-Flood-fill/C/bitmap-flood-fill-3.c @@ -5,5 +5,5 @@ typedef struct { typedef rgb_color *rgb_color_p; void floodfill(image img, int px, int py, - rgb_color_p bankscolor, - rgb_color_p rcolor); + rgb_color_p bankscolor, + rgb_color_p rcolor); diff --git a/Task/Bitmap-Flood-fill/C/bitmap-flood-fill-4.c b/Task/Bitmap-Flood-fill/C/bitmap-flood-fill-4.c index 8e9134edf6..453c999fed 100644 --- a/Task/Bitmap-Flood-fill/C/bitmap-flood-fill-4.c +++ b/Task/Bitmap-Flood-fill/C/bitmap-flood-fill-4.c @@ -29,8 +29,8 @@ inline void _ffill_enqueue(_ffill_queue *q, int px, int py) inline double color_distance( rgb_color_p a, rgb_color_p b ) { return sqrt( (double)(a->red - b->red)*(a->red - b->red) + - (double)(a->green - b->green)*(a->green - b->green) + - (double)(a->blue - b->blue)*(a->blue - b->blue) ) / (256.0*sqrt(3.0)); + (double)(a->green - b->green)*(a->green - b->green) + + (double)(a->blue - b->blue)*(a->blue - b->blue) ) / (256.0*sqrt(3.0)); } inline void _ffill_rgbcolor(image img, rgb_color_p tc, int px, int py) @@ -41,25 +41,25 @@ inline void _ffill_rgbcolor(image img, rgb_color_p tc, int px, int py) } -#define NSOE(X,Y) do { \ - if ( ((X)>=0)&&((Y)>=0) && ((X)width)&&((Y)height)) { \ - _ffill_rgbcolor(img, &thisnode, (X), (Y)); \ - if ( color_distance(&thisnode, bankscolor) > tolerance ) { \ - if (color_distance(&thisnode, rcolor) > 0.0) { \ - put_pixel_unsafe(img, (X), (Y), rcolor->red, \ - rcolor->green, \ - rcolor->blue); \ - _ffill_enqueue(&head, (X), (Y)); \ - pixelcount++; \ - } \ - } \ - } \ +#define NSOE(X,Y) do { \ + if ( ((X)>=0)&&((Y)>=0) && ((X)width)&&((Y)height)) { \ + _ffill_rgbcolor(img, &thisnode, (X), (Y)); \ + if ( color_distance(&thisnode, bankscolor) > tolerance ) { \ + if (color_distance(&thisnode, rcolor) > 0.0) { \ + put_pixel_unsafe(img, (X), (Y), rcolor->red, \ + rcolor->green, \ + rcolor->blue); \ + _ffill_enqueue(&head, (X), (Y)); \ + pixelcount++; \ + } \ + } \ + } \ } while(0) unsigned int floodfill(image img, int px, int py, - rgb_color_p bankscolor, - rgb_color_p rcolor) + rgb_color_p bankscolor, + rgb_color_p rcolor) { _ffill_queue head; rgb_color thisnode; diff --git a/Task/Bitmap-Flood-fill/Crystal/bitmap-flood-fill-1.cr b/Task/Bitmap-Flood-fill/Crystal/bitmap-flood-fill-1.cr new file mode 100644 index 0000000000..1a294cd573 --- /dev/null +++ b/Task/Bitmap-Flood-fill/Crystal/bitmap-flood-fill-1.cr @@ -0,0 +1,37 @@ +require "./pixmap" + +class Pixmap + def flood_fill (x, y, color) + old_color = self[x, y] + queue = Deque(Int32).new + width = @width + size = @data.size + idx = y * width + x + queue << idx + + until queue.empty? + idx = queue.shift + next unless @data[idx] == old_color + start = idx + # go left + limit = start // width * width + while idx >= limit && @data[idx] == old_color + @data[idx] = color + up, dn = idx - width, idx + width + queue << up if up >= 0 && @data[up] == old_color + queue << dn if dn < size && @data[dn] == old_color + idx -= 1 + end + # go right + limit = (start + width) // width * width + idx = start + 1 + while idx < limit && @data[idx] == old_color + @data[idx] = color + up, dn = idx - width, idx + width + queue << up if up >= 0 && @data[up] == old_color + queue << dn if dn < size && @data[dn] == old_color + idx += 1 + end + end + end +end diff --git a/Task/Bitmap-Flood-fill/Crystal/bitmap-flood-fill-2.cr b/Task/Bitmap-Flood-fill/Crystal/bitmap-flood-fill-2.cr new file mode 100644 index 0000000000..eb33ea7d5d --- /dev/null +++ b/Task/Bitmap-Flood-fill/Crystal/bitmap-flood-fill-2.cr @@ -0,0 +1,22 @@ +require "./circle" +require "./flood_fill" +require "./write_ppm" +require "./load_ppm" + +img = Pixmap.new 120, 80, Color::WHITE +img.circle 60, 40, 35, Color::BLACK +img.circle 100, 20, 18, Color::RED + +img.flood_fill 10, 10, Color.new(210, 230, 0) +img.flood_fill 60, 40, Color.new(255, 128, 76) + +img.write "crystal_flood_fill.ppm" + + +img = Pixmap.load "Unfilledcirc.ppm" +img.flood_fill 10, 10, Color.new(0, 128, 240) +img.flood_fill img.width-1, img.height-1, Color.new(0, 128, 240) +img.flood_fill 10, img.height//2, Color.new(240, 180, 10) +img.flood_fill 100, 100, Color.new(255, 60, 10) + +img.write "crystal_filledcirc.ppm" diff --git a/Task/Bitmap-Flood-fill/FBSL/bitmap-flood-fill.fbsl b/Task/Bitmap-Flood-fill/FBSL/bitmap-flood-fill.fbsl index 2cc3085c3c..b359ffe534 100644 --- a/Task/Bitmap-Flood-fill/FBSL/bitmap-flood-fill.fbsl +++ b/Task/Bitmap-Flood-fill/FBSL/bitmap-flood-fill.fbsl @@ -15,23 +15,23 @@ FBSL.GETCLIENTRECT(ME, 0, 0, Breadth, Height) DrawCircles() ' Initialize circles BEGIN EVENTS - SELECT CASE CBMSG - CASE WM_LBUTTONDOWN: FillCircles() ' Flood fill circles - CASE WM_CLOSE: FBSL.RELEASEDC(ME, FBSL.GETDC) ' Clean up - END SELECT + SELECT CASE CBMSG + CASE WM_LBUTTONDOWN: FillCircles() ' Flood fill circles + CASE WM_CLOSE: FBSL.RELEASEDC(ME, FBSL.GETDC) ' Clean up + END SELECT END EVENTS SUB FillCircles() - FILL(FBSL.GETDC, Breadth / 2, Height / 2, &HFFFF) ' Yellow: flood fill using intrinsics - FOR DIM x = 0 TO Breadth / 2 ' Red: flood fill iteratively - FOR DIM y = 0 TO Height / 2 - IF NOT POINT(FBSL.GETDC, x, y) THEN PSET(FBSL.GETDC, x, y, &HFF) - NEXT - NEXT - FBSLSETTEXT(ME, "After Flood Fill") ' Reset form caption + FILL(FBSL.GETDC, Breadth / 2, Height / 2, &HFFFF) ' Yellow: flood fill using intrinsics + FOR DIM x = 0 TO Breadth / 2 ' Red: flood fill iteratively + FOR DIM y = 0 TO Height / 2 + IF NOT POINT(FBSL.GETDC, x, y) THEN PSET(FBSL.GETDC, x, y, &HFF) + NEXT + NEXT + FBSLSETTEXT(ME, "After Flood Fill") ' Reset form caption END SUB SUB DrawCircles() ' Concatenate function calls - CIRCLE(FBSL.GETDC, Breadth / 2, Height / 2, 85, &HFFFFFF, 0, 360, 1, TRUE) _ ' White - (FBSL.GETDC, Breadth / 3, Height / 3, 30, 0, 0, 360, 1, TRUE) ' Black + CIRCLE(FBSL.GETDC, Breadth / 2, Height / 2, 85, &HFFFFFF, 0, 360, 1, TRUE) _ ' White + (FBSL.GETDC, Breadth / 3, Height / 3, 30, 0, 0, 360, 1, TRUE) ' Black END SUB diff --git a/Task/Bitmap-Flood-fill/Julia/bitmap-flood-fill.julia b/Task/Bitmap-Flood-fill/Julia/bitmap-flood-fill.jl similarity index 100% rename from Task/Bitmap-Flood-fill/Julia/bitmap-flood-fill.julia rename to Task/Bitmap-Flood-fill/Julia/bitmap-flood-fill.jl diff --git a/Task/Bitmap-Flood-fill/Kotlin/bitmap-flood-fill.kotlin b/Task/Bitmap-Flood-fill/Kotlin/bitmap-flood-fill.kts similarity index 100% rename from Task/Bitmap-Flood-fill/Kotlin/bitmap-flood-fill.kotlin rename to Task/Bitmap-Flood-fill/Kotlin/bitmap-flood-fill.kts diff --git a/Task/Bitmap-Flood-fill/MiniScript/bitmap-flood-fill.mini b/Task/Bitmap-Flood-fill/MiniScript/bitmap-flood-fill.mini index ea71b8be0a..e4a6dfa8d6 100644 --- a/Task/Bitmap-Flood-fill/MiniScript/bitmap-flood-fill.mini +++ b/Task/Bitmap-Flood-fill/MiniScript/bitmap-flood-fill.mini @@ -1,18 +1,18 @@ floodFill = function(bmp, x, y, targetColor, replacementColor) - // Check if pixel is outside the bounds - if not(0 < x < bmp.width) or not(0 < y < bmp.height) then return - - // Check the current pixel color - currentColor = bmp.pixel(x, y) - if currentColor != targetColor then return - - // Replace the color - bmp.setPixel x, y, replacementColor - // Recursively apply to adjacent pixels - floodFill(bmp, x + 1, y, targetColor, replacementColor) - floodFill(bmp, x - 1, y, targetColor, replacementColor) - floodFill(bmp, x, y + 1, targetColor, replacementColor) - floodFill(bmp, x, y - 1, targetColor, replacementColor) + // Check if pixel is outside the bounds + if not(0 < x < bmp.width) or not(0 < y < bmp.height) then return + + // Check the current pixel color + currentColor = bmp.pixel(x, y) + if currentColor != targetColor then return + + // Replace the color + bmp.setPixel x, y, replacementColor + // Recursively apply to adjacent pixels + floodFill(bmp, x + 1, y, targetColor, replacementColor) + floodFill(bmp, x - 1, y, targetColor, replacementColor) + floodFill(bmp, x, y + 1, targetColor, replacementColor) + floodFill(bmp, x, y - 1, targetColor, replacementColor) end function clear img = file.loadImage("Unfilledcirc.png") diff --git a/Task/Bitmap-Flood-fill/OCaml/bitmap-flood-fill.ocaml b/Task/Bitmap-Flood-fill/OCaml/bitmap-flood-fill.ml similarity index 100% rename from Task/Bitmap-Flood-fill/OCaml/bitmap-flood-fill.ocaml rename to Task/Bitmap-Flood-fill/OCaml/bitmap-flood-fill.ml diff --git a/Task/Bitmap-Flood-fill/Perl/bitmap-flood-fill-2.pl b/Task/Bitmap-Flood-fill/Perl/bitmap-flood-fill-2.pl index 049af58478..dae6942463 100644 --- a/Task/Bitmap-Flood-fill/Perl/bitmap-flood-fill-2.pl +++ b/Task/Bitmap-Flood-fill/Perl/bitmap-flood-fill-2.pl @@ -23,20 +23,20 @@ sub floodfill if ( colordistance(\@tcol, \@col) > $distparameter ) { return; } push @queue, [$x, $y]; while ( @queue ) { - my $pointref = shift(@queue); - ( $x, $y ) = @$pointref; - if ( ($x < 0) || ($y < 0) || ( $x >= $img->width ) || ( $y >= $img->height ) ) { next; } - if ( ! exists($visited{"$x,$y"}) ) { - @col = $img->query_pixel($x, $y); - if ( colordistance(\@tcol, \@col) <= $distparameter ) { - $img->draw_point($x, $y); - $visited{"$x,$y"} = 1; - push @queue, [$x+1, $y]; - push @queue, [$x-1, $y]; - push @queue, [$x, $y+1]; - push @queue, [$x, $y-1]; - } - } + my $pointref = shift(@queue); + ( $x, $y ) = @$pointref; + if ( ($x < 0) || ($y < 0) || ( $x >= $img->width ) || ( $y >= $img->height ) ) { next; } + if ( ! exists($visited{"$x,$y"}) ) { + @col = $img->query_pixel($x, $y); + if ( colordistance(\@tcol, \@col) <= $distparameter ) { + $img->draw_point($x, $y); + $visited{"$x,$y"} = 1; + push @queue, [$x+1, $y]; + push @queue, [$x-1, $y]; + push @queue, [$x, $y+1]; + push @queue, [$x, $y-1]; + } + } } } diff --git a/Task/Bitmap-Flood-fill/Raku/bitmap-flood-fill.raku b/Task/Bitmap-Flood-fill/Raku/bitmap-flood-fill.raku index fa29c20997..7cafc0de1d 100644 --- a/Task/Bitmap-Flood-fill/Raku/bitmap-flood-fill.raku +++ b/Task/Bitmap-Flood-fill/Raku/bitmap-flood-fill.raku @@ -4,16 +4,16 @@ class Bitmap { has Pixel @.data; method pixel( - $i where ^$!width, - $j where ^$!height - --> Pixel + $i where ^$!width, + $j where ^$!height + --> Pixel ) is rw { @!data[$i + $j * $!width] } } role PPM { method P6 returns Blob { - "P6\n{self.width} {self.height}\n255\n".encode('ascii') - ~ Blob.new: flat map { .R, .G, .B }, self.data + "P6\n{self.width} {self.height}\n255\n".encode('ascii') + ~ Blob.new: flat map { .R, .G, .B }, self.data } } diff --git a/Task/Bitmap-Flood-fill/Rebol/bitmap-flood-fill.rebol b/Task/Bitmap-Flood-fill/Rebol/bitmap-flood-fill.rebol new file mode 100644 index 0000000000..f5deeabdf5 --- /dev/null +++ b/Task/Bitmap-Flood-fill/Rebol/bitmap-flood-fill.rebol @@ -0,0 +1,64 @@ +Rebol [ + title: "Rosetta code: Bitmap/Flood fill" + file: %Bitmap-Flood_fill.r3 + url: https://rosettacode.org/wiki/Bitmap/Bitmap-Flood_fill +] + +flood-fill: function [ + image [image! file! url!] + position [pair!] "Start position" + color1 [tuple!] "Target color to replace" + color2 [tuple!] "Replacement color" +][ + unless image? image [image: load image] ;; Load image if not already loaded + xsize: image/size/x + ysize: image/size/y + + color2/4: color1/4: 255 ;; Ensure both colors are fully opaque + + que: copy [] + if image/:position != color1 [return image] ;; Bail if seed pixel isn't target color + + append que position + while [not empty? que][ + position: take que ;; Dequeue next position to process + if image/:position == color1 [ ;; Skip if already recolored + W: position + ;; Scan west, recoloring pixels until we leave the target-color region + while [image/:W == color1][ + image/:W: color2 + next: W + 0x1 ;; Pixel south of W + if all [next/y < ysize color1 == image/:next][append que next] + next: W - 0x1 ;; Pixel north of W + if all [next/y > 0 color1 == image/:next][append que next] + next: W - 1x0 ;; Step west + either next/x > 1 [W: next][break] ;; Stop at left edge + ] + E: position + 1x0 ;; Start east scan one step right of seed + if E/x < xsize [ + ;; Scan east, recoloring pixels until we leave the target-color region + while [image/:E == color1][ + image/:E: color2 + next: E + 0x1 ;; Pixel south of E + if all [next/y < ysize color1 == image/:next][append que next] + next: E - 0x1 ;; Pixel north of E + if all [next/y > 0 color1 == image/:next][append que next] + next: E + 1x0 ;; Step east + either next/x < xsize [E: next][break] ;; Stop at right edge + ] + ] + ] + ] + image ;; Return the modified image +] + +;; Download the test image if not already cached locally +unless exists? file: %Unfilledcirc.png [ + write file read https://static.wikitide.net/rosettacodewiki/0/0f/Unfilledcirc.png +] + +img: load %Unfilledcirc.png +img: flood-fill img 200x200 white red +img: flood-fill img 100x100 black blue + +browse save %Filledcirc.png img ;; Save result and open in browser diff --git a/Task/Bitmap-Flood-fill/Rust/bitmap-flood-fill.rust b/Task/Bitmap-Flood-fill/Rust/bitmap-flood-fill.rs similarity index 100% rename from Task/Bitmap-Flood-fill/Rust/bitmap-flood-fill.rust rename to Task/Bitmap-Flood-fill/Rust/bitmap-flood-fill.rs diff --git a/Task/Bitmap-Flood-fill/Uiua/bitmap-flood-fill.uiua b/Task/Bitmap-Flood-fill/Uiua/bitmap-flood-fill.uiua new file mode 100644 index 0000000000..0808eee12c --- /dev/null +++ b/Task/Bitmap-Flood-fill/Uiua/bitmap-flood-fill.uiua @@ -0,0 +1,12 @@ +# Drop a png onto this pane, then Run. +&p$"Found a _" °img&frab "image.png" +≡≡⊢ # Convert to greyscale. +Sensitivity ← 0.3 # Lower is finer. +N₄ ← [1_0 0_1 ¯ 1_0 0_¯1] +[40_40]⊙0.8 # Starting point, fill colour. +Good ← >Sensitivity⌵-⬚0.5⊡⊢ # Needs filling. Simple edges-check. +# Take first of list. If needs fill, do so and then add +# its four neighbours into queue. Repeat until queue is empty. +⍢(⨬(↘1|◴⊂+N₄¤°⊂ ⊃(⋅∘|∘|⋅⋅⋅∘)◡(⍜(⊡|⋅∘)⊢))◡Good +| >0⧻) +⋅⊙⋅ diff --git a/Task/Bitmap-Flood-fill/Zkl/bitmap-flood-fill-1.zkl b/Task/Bitmap-Flood-fill/Zkl/bitmap-flood-fill-1.zkl index ccd3c7df5a..24f859e0a8 100644 --- a/Task/Bitmap-Flood-fill/Zkl/bitmap-flood-fill-1.zkl +++ b/Task/Bitmap-Flood-fill/Zkl/bitmap-flood-fill-1.zkl @@ -4,11 +4,11 @@ fcn flood(pixmap, x,y, repl){ // slow! while(stack){ x,y:=stack.pop(); if((0<=y hist(j) Then + Swap hist(i), hist(j) + Swap idx(i), idx(j) + End If + Next +Next + +' Encontrar la mediana +total = 0 +For i = 0 To 255 + total += hist(i) +Next + +half = 0 +For i = 0 To 255 + half += hist(i) + If half >= total \ 2 Then + median = idx(i) + Exit For + End If +Next + +'Windowtitle("Histogram") +Windowtitle "Original vs Black and White" + +' Mostrar versión en blanco y negro en la mitad derecha +For y = 0 To alto - 1 + For x = 0 To ancho - 1 + l = Point(x, y) And &HFF + If l > median Then + Pset (x + ancho, y), Rgb(255, 255, 255) + Else + Pset (x + ancho, y), Rgb(0, 0, 0) + End If + Next +Next + +' Guardar la imagen resultante (ambas imágenes juntas) +Bsave "Lena_Original_and_BW.bmp", 0 + +Sleep diff --git a/Task/Bitmap-Histogram/Julia/bitmap-histogram.julia b/Task/Bitmap-Histogram/Julia/bitmap-histogram.jl similarity index 100% rename from Task/Bitmap-Histogram/Julia/bitmap-histogram.julia rename to Task/Bitmap-Histogram/Julia/bitmap-histogram.jl diff --git a/Task/Bitmap-Histogram/Kotlin/bitmap-histogram.kotlin b/Task/Bitmap-Histogram/Kotlin/bitmap-histogram.kts similarity index 100% rename from Task/Bitmap-Histogram/Kotlin/bitmap-histogram.kotlin rename to Task/Bitmap-Histogram/Kotlin/bitmap-histogram.kts diff --git a/Task/Bitmap-Histogram/OCaml/bitmap-histogram-1.ocaml b/Task/Bitmap-Histogram/OCaml/bitmap-histogram-1.ml similarity index 100% rename from Task/Bitmap-Histogram/OCaml/bitmap-histogram-1.ocaml rename to Task/Bitmap-Histogram/OCaml/bitmap-histogram-1.ml diff --git a/Task/Bitmap-Histogram/OCaml/bitmap-histogram-2.ocaml b/Task/Bitmap-Histogram/OCaml/bitmap-histogram-2.ml similarity index 100% rename from Task/Bitmap-Histogram/OCaml/bitmap-histogram-2.ocaml rename to Task/Bitmap-Histogram/OCaml/bitmap-histogram-2.ml diff --git a/Task/Bitmap-Histogram/OCaml/bitmap-histogram-3.ocaml b/Task/Bitmap-Histogram/OCaml/bitmap-histogram-3.ml similarity index 100% rename from Task/Bitmap-Histogram/OCaml/bitmap-histogram-3.ocaml rename to Task/Bitmap-Histogram/OCaml/bitmap-histogram-3.ml diff --git a/Task/Bitmap-Histogram/PHP/bitmap-histogram.php b/Task/Bitmap-Histogram/PHP/bitmap-histogram.php index 631623d041..f2e10b03ca 100644 --- a/Task/Bitmap-Histogram/PHP/bitmap-histogram.php +++ b/Task/Bitmap-Histogram/PHP/bitmap-histogram.php @@ -1,11 +1,11 @@ -define('src_name', 'input.jpg'); // source image -define('dest_name', 'output.jpg'); // destination image +define('src_name', 'input.jpg'); // source image +define('dest_name', 'output.jpg'); // destination image -$img = imagecreatefromjpeg(src_name); // read image +$img = imagecreatefromjpeg(src_name); // read image if(empty($img)){ - echo 'Image could not be loaded!'; - exit; + echo 'Image could not be loaded!'; + exit; } $black = imagecolorallocate($img, 0, 0, 0); @@ -13,42 +13,42 @@ $white = imagecolorallocate($img, 255, 255, 255); $width = imagesx($img); $height = imagesy($img); -$array_lum = array(); // for storage of luminosity of each pixel -$sum_lum = 0; // total sum of luminosity -$average_lum = 0; // average luminosity of whole image +$array_lum = array(); // for storage of luminosity of each pixel +$sum_lum = 0; // total sum of luminosity +$average_lum = 0; // average luminosity of whole image -for($x = 0; $x < $width; $x++){ - for($y = 0; $y < $height; $y++){ - // read pixel value - $color = imagecolorat($img, $x, $y); - $r = ($color >> 16) & 0xFF; - $g = ($color >> 8) & 0xFF; - $b = $color & 0xFF; - // save pixel luminosity in temporary array - $array_lum[$x][$y] = ($r + $g + $b); - // add pixel luminosity to sum - $sum_lum += $array_lum[$x][$y]; - } +for($x = 0; $x < $width; $x++){ + for($y = 0; $y < $height; $y++){ + // read pixel value + $color = imagecolorat($img, $x, $y); + $r = ($color >> 16) & 0xFF; + $g = ($color >> 8) & 0xFF; + $b = $color & 0xFF; + // save pixel luminosity in temporary array + $array_lum[$x][$y] = ($r + $g + $b); + // add pixel luminosity to sum + $sum_lum += $array_lum[$x][$y]; + } } // calculate average luminosity $average_lum = $sum_lum / ($width * $height); -for($x = 0; $x < $width; $x++){ - for($y = 0; $y < $height; $y++){ - // pixel is brighter than average -> set white - // else -> set black - if($array_lum[$x][$y] > $average_lum){ - imagesetpixel($img, $x, $y, $white); - } - else{ - imagesetpixel($img, $x, $y, $black); - } - } +for($x = 0; $x < $width; $x++){ + for($y = 0; $y < $height; $y++){ + // pixel is brighter than average -> set white + // else -> set black + if($array_lum[$x][$y] > $average_lum){ + imagesetpixel($img, $x, $y, $white); + } + else{ + imagesetpixel($img, $x, $y, $black); + } + } } // save black and white image to dest_name imagejpeg($img, dest_name); if(!file_exists(dest_name)){ - echo 'Image not saved! Check permission!'; + echo 'Image not saved! Check permission!'; } diff --git a/Task/Bitmap-Histogram/Raku/bitmap-histogram.raku b/Task/Bitmap-Histogram/Raku/bitmap-histogram.raku index fa9a0b9efc..e94fea18fb 100644 --- a/Task/Bitmap-Histogram/Raku/bitmap-histogram.raku +++ b/Task/Bitmap-Histogram/Raku/bitmap-histogram.raku @@ -7,8 +7,8 @@ class Bitmap { role PBM { has @.BM; method P4 returns Blob { - "P4\n{self.width} {self.height}\n".encode('ascii') - ~ Blob.new: self.BM + "P4\n{self.width} {self.height}\n".encode('ascii') + ~ Blob.new: self.BM } } diff --git a/Task/Bitmap-Histogram/Rebol/bitmap-histogram-1.rebol b/Task/Bitmap-Histogram/Rebol/bitmap-histogram-1.rebol new file mode 100644 index 0000000000..94755e279b --- /dev/null +++ b/Task/Bitmap-Histogram/Rebol/bitmap-histogram-1.rebol @@ -0,0 +1,27 @@ +Rebol [ + title: "Rosetta code: Bitmap/Histogram" + file: %Bitmap-Histogram.r3 + url: https://rosettacode.org/wiki/Bitmap/Bitmap-Histogram + needs: 3.21.9 +] + +;; Load source image from file +img: load %Lenna50.jpg +;; Extract luminosity as vector for statistical operations +vec: to vector! img/luminosity +;; Compute median brightness threshold +med: vec/median +;; Allocate 256-bucket uint32 histogram (one bucket per brightness level) +histogram: make vector! [uint32! 255] +;; In a single pass: build brightness histogram and threshold each pixel +forall vec [ + val: vec/1 + histogram/:val: histogram/:val + 1 ;; tally pixel's brightness bucket + vec/1: either val < med [0][255] ;; binarize: black or white +] +;; Inspect histogram distribution +? histogram +;; Write thresholded grayscale data back to image +img/gray: vec +;; Save result as PNG and open in browser +browse save %Lenna50-bw.png img diff --git a/Task/Bitmap-Histogram/Rebol/bitmap-histogram-2.rebol b/Task/Bitmap-Histogram/Rebol/bitmap-histogram-2.rebol new file mode 100644 index 0000000000..2586976144 --- /dev/null +++ b/Task/Bitmap-Histogram/Rebol/bitmap-histogram-2.rebol @@ -0,0 +1,8 @@ +img: load %Lenna50.jpg +foreach channel [red green blue] [ + vec: to vector! img/:channel + med: vec/median + forall vec [vec/1: either vec/1 < med [0][255]] + img/:channel: vec +] +browse save %Lenna50-rgb.png img diff --git a/Task/Bitmap-Histogram/Rust/bitmap-histogram.rust b/Task/Bitmap-Histogram/Rust/bitmap-histogram.rs similarity index 100% rename from Task/Bitmap-Histogram/Rust/bitmap-histogram.rust rename to Task/Bitmap-Histogram/Rust/bitmap-histogram.rs diff --git a/Task/Bitmap-Histogram/Scala/bitmap-histogram-1.scala b/Task/Bitmap-Histogram/Scala/bitmap-histogram-1.scala index 4646774d80..2d5144c867 100644 --- a/Task/Bitmap-Histogram/Scala/bitmap-histogram-1.scala +++ b/Task/Bitmap-Histogram/Scala/bitmap-histogram-1.scala @@ -27,6 +27,6 @@ object BitmapOps { val c2=Color.WHITE for(x <- 0 until bm.width; y <- 0 until bm.height; l=luminosity(bm.getPixel(x,y))) image.setPixel(x, y, if(l>threshold) c2 else c1) - image + image } } diff --git a/Task/Bitmap-Histogram/Vedit-macro-language/bitmap-histogram.vedit b/Task/Bitmap-Histogram/Vedit-macro-language/bitmap-histogram.vedit index df0380645d..8018fff516 100644 --- a/Task/Bitmap-Histogram/Vedit-macro-language/bitmap-histogram.vedit +++ b/Task/Bitmap-Histogram/Vedit-macro-language/bitmap-histogram.vedit @@ -1,10 +1,10 @@ :HISTOGRAM: -#30 = Buf_Free // #30 = buffer to store histogram data +#30 = Buf_Free // #30 = buffer to store histogram data for (#9=0; #9<256; #9++) { - Out_Reg(21) TC(#9) Out_Reg(Clear) // @21 = intensity value to be counted - Buf_Switch(#15) // switch to image buffer - #8 = Search(@21, CASE+BEGIN+ALL+NOERR) // count intensity values - Buf_Switch(#30) // switch to histogram buffer - Num_Ins(#8, FILL) // store count + Out_Reg(21) TC(#9) Out_Reg(Clear) // @21 = intensity value to be counted + Buf_Switch(#15) // switch to image buffer + #8 = Search(@21, CASE+BEGIN+ALL+NOERR) // count intensity values + Buf_Switch(#30) // switch to histogram buffer + Num_Ins(#8, FILL) // store count } Return diff --git a/Task/Bitmap-Histogram/Zkl/bitmap-histogram-1.zkl b/Task/Bitmap-Histogram/Zkl/bitmap-histogram-1.zkl index 5d99339833..69d94f35f3 100644 --- a/Task/Bitmap-Histogram/Zkl/bitmap-histogram-1.zkl +++ b/Task/Bitmap-Histogram/Zkl/bitmap-histogram-1.zkl @@ -1,5 +1,5 @@ fcn histogram(image){ - hist:=List.createLong(256,0); // array[256] of zero + hist:=List.createLong(256,0); // array[256] of zero image.data.howza(0).pump(Void,'wrap(c){ hist[c]+=1 }); // byte by byte loop hist; } @@ -8,7 +8,7 @@ fcn histogramMedian(hist){ left,right:=hist[from],hist[to]; while(from!=to){ if(left=y - plot( x + x0, y + y0) - plot( y + x0, x + y0) - plot(-x + x0, y + y0) - plot(-y + x0, x + y0) - plot(-x + x0, -y + y0) - plot(-y + x0, -x + y0) - plot( x + x0, -y + y0) - plot( y + x0, -x + y0) + while x>=y + plot( x + x0, y + y0) + plot( y + x0, x + y0) + plot(-x + x0, y + y0) + plot(-y + x0, x + y0) + plot(-x + x0, -y + y0) + plot(-y + x0, -x + y0) + plot( x + x0, -y + y0) + plot( y + x0, -x + y0) - y++ + y++ - if decisionOver2<=0 then - decisionOver2+=2*y+1 - else - x-- - decisionOver2+=2*(y-x)+1 - end if - end while - return 0 + if decisionOver2<=0 then + decisionOver2+=2*y+1 + else + x-- + decisionOver2+=2*(y-x)+1 + end if + end while + return 0 End Function diff --git a/Task/Bitmap-Midpoint-circle-algorithm/Batch-File/bitmap-midpoint-circle-algorithm.bat b/Task/Bitmap-Midpoint-circle-algorithm/Batch-File/bitmap-midpoint-circle-algorithm.bat index 45665a2733..ba0ddcb5fe 100644 --- a/Task/Bitmap-Midpoint-circle-algorithm/Batch-File/bitmap-midpoint-circle-algorithm.bat +++ b/Task/Bitmap-Midpoint-circle-algorithm/Batch-File/bitmap-midpoint-circle-algorithm.bat @@ -1,7 +1,7 @@ @echo off setlocal enabledelayedexpansion - %== Initializations ==% + %== Initializations ==% set width=50 set height=30 @@ -11,62 +11,62 @@ echo Rendering... set "outp=" for /l %%i in (1,1,%height%) do ( - for /l %%j in (1,1,%width%) do ( - set "c[%%i][%%j]= " - ) + for /l %%j in (1,1,%width%) do ( + set "c[%%i][%%j]= " + ) ) - %== Set the parameters for making circle ==% + %== Set the parameters for making circle ==% call :DrawCircle 20 20 10 call :DrawCircle 10 30 15 - %== Output result ==% + %== Output result ==% for /l %%i in (1,1,%height%) do ( - for /l %%j in (1,1,%width%) do ( - set "outp=!outp!!c[%%i][%%j]!" - ) + for /l %%j in (1,1,%width%) do ( + set "outp=!outp!!c[%%i][%%j]!" + ) ) cls echo !outp! pause>nul exit /b - %== The main function ==% + %== The main function ==% :DrawCircle - set x0=%1 - set y0=%2 - set radius=%3 + set x0=%1 + set y0=%2 + set radius=%3 - set x=!radius! - set y=0 - set /a decisionOver2 = 1 - !x! + set x=!radius! + set y=0 + set /a decisionOver2 = 1 - !x! - :circle_loop - if !x! geq !y! ( - set /a "hor=x + x0","ver=y + y0" - set "c[!hor!][!ver!]=Û" - set /a "hor=y + x0","ver=x + y0" - set "c[!hor!][!ver!]=Û" - set /a "hor=-x + x0","ver=y + y0" - set "c[!hor!][!ver!]=Û" - set /a "hor=-y + x0","ver=x + y0" - set "c[!hor!][!ver!]=Û" - set /a "hor=-x + x0","ver=-y + y0" - set "c[!hor!][!ver!]=Û" - set /a "hor=-y + x0","ver=-x + y0" - set "c[!hor!][!ver!]=Û" - set /a "hor=x + x0","ver=-y + y0" - set "c[!hor!][!ver!]=Û" - set /a "hor=y + x0","ver=-x + y0" - set "c[!hor!][!ver!]=Û" + :circle_loop + if !x! geq !y! ( + set /a "hor=x + x0","ver=y + y0" + set "c[!hor!][!ver!]=Û" + set /a "hor=y + x0","ver=x + y0" + set "c[!hor!][!ver!]=Û" + set /a "hor=-x + x0","ver=y + y0" + set "c[!hor!][!ver!]=Û" + set /a "hor=-y + x0","ver=x + y0" + set "c[!hor!][!ver!]=Û" + set /a "hor=-x + x0","ver=-y + y0" + set "c[!hor!][!ver!]=Û" + set /a "hor=-y + x0","ver=-x + y0" + set "c[!hor!][!ver!]=Û" + set /a "hor=x + x0","ver=-y + y0" + set "c[!hor!][!ver!]=Û" + set /a "hor=y + x0","ver=-x + y0" + set "c[!hor!][!ver!]=Û" - set /a y+=1 - if !decisionOver2! leq 0 ( - set /a "decisionOver2 = !decisionOver2! + (2 * y^) + 1" - ) else ( - set /a x-=1 - set /a "decisionOver2 = !decisionOver2! + 2 * (y - x^) + 1" - ) - goto circle_loop - ) + set /a y+=1 + if !decisionOver2! leq 0 ( + set /a "decisionOver2 = !decisionOver2! + (2 * y^) + 1" + ) else ( + set /a x-=1 + set /a "decisionOver2 = !decisionOver2! + 2 * (y - x^) + 1" + ) + goto circle_loop + ) goto :EOF diff --git a/Task/Bitmap-Midpoint-circle-algorithm/Crystal/bitmap-midpoint-circle-algorithm-1.cr b/Task/Bitmap-Midpoint-circle-algorithm/Crystal/bitmap-midpoint-circle-algorithm-1.cr new file mode 100644 index 0000000000..662403d75a --- /dev/null +++ b/Task/Bitmap-Midpoint-circle-algorithm/Crystal/bitmap-midpoint-circle-algorithm-1.cr @@ -0,0 +1,40 @@ +require "./pixmap" +require "./bresenham" + +class Pixmap + def circle (cx, cy, r, color, fill = false) + f = 1 - r + ddF_X = 0 + ddF_Y = -2 * r + x = 0 + y = r + self[cx, cy + r] = color + self[cx, cy - r] = color + p1, p2 = {cx + r, cy}, {cx - r, cy} + if fill + line(*p1, *p2, color) + else + self[*p1] = self[*p2] = color + end + while x < y + if f >= 0 + y -= 1 + ddF_Y += 2 + f += ddF_Y + end + x += 1 + ddF_X += 2 + f += ddF_X + 1 + [{cx - x, cy - y}, {cx + x, cy - y}, + {cx - x, cy + y}, {cx + x, cy + y}, + {cx - y, cy - x}, {cx + y, cy - x}, + {cx - y, cy + x}, {cx + y, cy + x}].each_slice(2, reuse: true) do |(p1, p2)| + if fill + line(*p1, *p2, color) + else + self[*p1] = self[*p2] = color + end + end + end + end +end diff --git a/Task/Bitmap-Midpoint-circle-algorithm/Crystal/bitmap-midpoint-circle-algorithm-2.cr b/Task/Bitmap-Midpoint-circle-algorithm/Crystal/bitmap-midpoint-circle-algorithm-2.cr new file mode 100644 index 0000000000..821729bbd3 --- /dev/null +++ b/Task/Bitmap-Midpoint-circle-algorithm/Crystal/bitmap-midpoint-circle-algorithm-2.cr @@ -0,0 +1,12 @@ +require "./circle" +require "./write_ppm" + +img = Pixmap.new 100, 100, Color::WHITE + +img.circle 50, 50, 40, Color::RED, true +img.circle 70, 60, 15, Color::BLUE, true +img.circle 40, 20, 20, Color::BLACK +img.circle 40, 20, 19, Color.new(255, 144, 0) +img.circle 40, 20, 18, Color::BLACK + +img.write "crystal_circles.ppm" diff --git a/Task/Bitmap-Midpoint-circle-algorithm/Delphi/bitmap-midpoint-circle-algorithm.delphi b/Task/Bitmap-Midpoint-circle-algorithm/Delphi/bitmap-midpoint-circle-algorithm.delphi deleted file mode 100644 index a27d5aad00..0000000000 --- a/Task/Bitmap-Midpoint-circle-algorithm/Delphi/bitmap-midpoint-circle-algorithm.delphi +++ /dev/null @@ -1,50 +0,0 @@ -procedure DrawCircle(Image: TImage; Radius: integer; Center: TPoint); -var T1,T2: integer; -var X,Y: integer; -var Cnt: integer; - - procedure DrawPixels(X,Y: integer); - {Draw pixel into all 8 octents} - begin - Image.Canvas.Pixels[Center.X + x, Center.Y + y]:=clRed; - Image.Canvas.Pixels[Center.X - X, Center.Y + Y]:=clRed; - Image.Canvas.Pixels[Center.X + X, Center.Y - Y]:=clRed; - Image.Canvas.Pixels[Center.X - X, Center.Y - Y]:=clRed; - Image.Canvas.Pixels[Center.X + Y, Center.Y + X]:=clRed; - Image.Canvas.Pixels[Center.X - Y, Center.Y + X]:=clRed; - Image.Canvas.Pixels[Center.X + y, Center.Y - X]:=clRed; - Image.Canvas.Pixels[Center.X - Y, Center.Y - X]:=clRed; - end; - -begin -Cnt:=0; -T1:= Radius div 32; -{Start on X-axis} -X:= Radius; Y:= 0; -repeat - begin - DrawPixels(X, Y); - Y:=Y + 1; - T1:=T1 + Y; - T2:=T1 - X; - if T2 >= 0 then - begin - T1:=T2; - X:=X - 1; - end; - Inc(Cnt); - end -until x < y; -Form1.Caption:=IntToStr(Cnt); -end; - - - -procedure ShowBrezCircle(Image: TImage); -begin -{Draw three times to make line thicker} -DrawCircle(Image,100,Point(200,200)); -DrawCircle(Image,99,Point(200,200)); -DrawCircle(Image,98,Point(200,200)); -Image.Invalidate; -end; diff --git a/Task/Bitmap-Midpoint-circle-algorithm/Delphi/bitmap-midpoint-circle-algorithm.pas b/Task/Bitmap-Midpoint-circle-algorithm/Delphi/bitmap-midpoint-circle-algorithm.pas new file mode 100644 index 0000000000..70e6487fce --- /dev/null +++ b/Task/Bitmap-Midpoint-circle-algorithm/Delphi/bitmap-midpoint-circle-algorithm.pas @@ -0,0 +1,50 @@ +procedure DrawCircle(Image: TImage; Radius: integer; Center: TPoint); +var T1,T2: integer; +var X,Y: integer; +var Cnt: integer; + + procedure DrawPixels(X,Y: integer); + {Draw pixel into all 8 octents} + begin + Image.Canvas.Pixels[Center.X + x, Center.Y + y]:=clRed; + Image.Canvas.Pixels[Center.X - X, Center.Y + Y]:=clRed; + Image.Canvas.Pixels[Center.X + X, Center.Y - Y]:=clRed; + Image.Canvas.Pixels[Center.X - X, Center.Y - Y]:=clRed; + Image.Canvas.Pixels[Center.X + Y, Center.Y + X]:=clRed; + Image.Canvas.Pixels[Center.X - Y, Center.Y + X]:=clRed; + Image.Canvas.Pixels[Center.X + y, Center.Y - X]:=clRed; + Image.Canvas.Pixels[Center.X - Y, Center.Y - X]:=clRed; + end; + +begin +Cnt:=0; +T1:= Radius div 32; +{Start on X-axis} +X:= Radius; Y:= 0; +repeat + begin + DrawPixels(X, Y); + Y:=Y + 1; + T1:=T1 + Y; + T2:=T1 - X; + if T2 >= 0 then + begin + T1:=T2; + X:=X - 1; + end; + Inc(Cnt); + end +until x < y; +Form1.Caption:=IntToStr(Cnt); +end; + + + +procedure ShowBrezCircle(Image: TImage); +begin +{Draw three times to make line thicker} +DrawCircle(Image,100,Point(200,200)); +DrawCircle(Image,99,Point(200,200)); +DrawCircle(Image,98,Point(200,200)); +Image.Invalidate; +end; diff --git a/Task/Bitmap-Midpoint-circle-algorithm/EasyLang/bitmap-midpoint-circle-algorithm.easy b/Task/Bitmap-Midpoint-circle-algorithm/EasyLang/bitmap-midpoint-circle-algorithm.easy new file mode 100644 index 0000000000..2e0418ae0b --- /dev/null +++ b/Task/Bitmap-Midpoint-circle-algorithm/EasyLang/bitmap-midpoint-circle-algorithm.easy @@ -0,0 +1,27 @@ +proc pix x y . + grect x / 5 y / 5 0.25 0.25 +. +proc circ x0 y0 r . + t1 = r div 16 + x = r + while x >= y + pix x0 - x, y0 + y + pix x0 - x, y0 - y + pix x0 - y, y0 + x + pix x0 - y, y0 - x + pix x0 + x, y0 + y + pix x0 + x, y0 - y + pix x0 + y, y0 + x + pix x0 + y, y0 - x + y += 1 + t1 += y + t2 = t1 - x + if t2 >= 0 + t1 = t2 + x -= 1 + . + . +. +for r = 20 step 20 to 240 + circ 250 250 r +. diff --git a/Task/Bitmap-Midpoint-circle-algorithm/FBSL/bitmap-midpoint-circle-algorithm.fbsl b/Task/Bitmap-Midpoint-circle-algorithm/FBSL/bitmap-midpoint-circle-algorithm.fbsl index 4ab0e557c9..c26d8ea33c 100644 --- a/Task/Bitmap-Midpoint-circle-algorithm/FBSL/bitmap-midpoint-circle-algorithm.fbsl +++ b/Task/Bitmap-Midpoint-circle-algorithm/FBSL/bitmap-midpoint-circle-algorithm.fbsl @@ -13,29 +13,29 @@ DIM Breadth AS INTEGER, Height AS INTEGER FBSL.GETCLIENTRECT(ME, 0, 0, Breadth, Height) BEGIN EVENTS ' Main message loop - SELECT CASE CBMSG - CASE WM_LBUTTONDOWN: MidpointCircle() ' Draw - CASE WM_CLOSE: FBSL.RELEASEDC(ME, FBSL.GETDC) ' Clean up - END SELECT + SELECT CASE CBMSG + CASE WM_LBUTTONDOWN: MidpointCircle() ' Draw + CASE WM_CLOSE: FBSL.RELEASEDC(ME, FBSL.GETDC) ' Clean up + END SELECT END EVENTS SUB MidpointCircle() - BresenhamCircle(Breadth \ 2, Height \ 2, 80, &HFF) ' Red: Windows stores colors in BGR order - BresenhamCircle(Breadth \ 2, Height \ 2, 40, 0) ' Black - - SUB BresenhamCircle(cx, cy, radius, colour) - DIM x = 0, y = radius, f = 1 - radius, dx = 0, dy = -2 * radius - - PSET(FBSL.GETDC, cx, cy + radius, colour)(FBSL.GETDC, cx, cy - radius, colour) - PSET(FBSL.GETDC, cx + radius, cy, colour)(FBSL.GETDC, cx - radius, cy, colour) - - WHILE x < y - IF f >= 0 THEN: DECR(y): INCR(dy, 2)(f, dy): END IF ' Try also "IF f THEN" :) - INCR(x)(dx, 2)(f, dx + 1) - PSET(FBSL.GETDC, cx + x, cy + y, colour)(FBSL.GETDC, cx - x, cy + y, colour) - PSET(FBSL.GETDC, cx + x, cy - y, colour)(FBSL.GETDC, cx - x, cy - y, colour) - PSET(FBSL.GETDC, cx + y, cy + x, colour)(FBSL.GETDC, cx - y, cy + x, colour) - PSET(FBSL.GETDC, cx + y, cy - x, colour)(FBSL.GETDC, cx - y, cy - x, colour) - WEND - END SUB + BresenhamCircle(Breadth \ 2, Height \ 2, 80, &HFF) ' Red: Windows stores colors in BGR order + BresenhamCircle(Breadth \ 2, Height \ 2, 40, 0) ' Black + + SUB BresenhamCircle(cx, cy, radius, colour) + DIM x = 0, y = radius, f = 1 - radius, dx = 0, dy = -2 * radius + + PSET(FBSL.GETDC, cx, cy + radius, colour)(FBSL.GETDC, cx, cy - radius, colour) + PSET(FBSL.GETDC, cx + radius, cy, colour)(FBSL.GETDC, cx - radius, cy, colour) + + WHILE x < y + IF f >= 0 THEN: DECR(y): INCR(dy, 2)(f, dy): END IF ' Try also "IF f THEN" :) + INCR(x)(dx, 2)(f, dx + 1) + PSET(FBSL.GETDC, cx + x, cy + y, colour)(FBSL.GETDC, cx - x, cy + y, colour) + PSET(FBSL.GETDC, cx + x, cy - y, colour)(FBSL.GETDC, cx - x, cy - y, colour) + PSET(FBSL.GETDC, cx + y, cy + x, colour)(FBSL.GETDC, cx - y, cy + x, colour) + PSET(FBSL.GETDC, cx + y, cy - x, colour)(FBSL.GETDC, cx - y, cy - x, colour) + WEND + END SUB END SUB diff --git a/Task/Bitmap-Midpoint-circle-algorithm/Java/bitmap-midpoint-circle-algorithm.java b/Task/Bitmap-Midpoint-circle-algorithm/Java/bitmap-midpoint-circle-algorithm.java index 9019b3a968..67697a0840 100644 --- a/Task/Bitmap-Midpoint-circle-algorithm/Java/bitmap-midpoint-circle-algorithm.java +++ b/Task/Bitmap-Midpoint-circle-algorithm/Java/bitmap-midpoint-circle-algorithm.java @@ -1,35 +1,35 @@ import java.awt.Color; public class MidPointCircle { - private BasicBitmapStorage image; + private BasicBitmapStorage image; - public MidPointCircle(final int imageWidth, final int imageHeight) { - this.image = new BasicBitmapStorage(imageWidth, imageHeight); - } + public MidPointCircle(final int imageWidth, final int imageHeight) { + this.image = new BasicBitmapStorage(imageWidth, imageHeight); + } - private void drawCircle(final int centerX, final int centerY, final int radius) { - int d = (5 - radius * 4)/4; - int x = 0; - int y = radius; - Color circleColor = Color.white; + private void drawCircle(final int centerX, final int centerY, final int radius) { + int d = (5 - radius * 4)/4; + int x = 0; + int y = radius; + Color circleColor = Color.white; - do { - image.setPixel(centerX + x, centerY + y, circleColor); - image.setPixel(centerX + x, centerY - y, circleColor); - image.setPixel(centerX - x, centerY + y, circleColor); - image.setPixel(centerX - x, centerY - y, circleColor); - image.setPixel(centerX + y, centerY + x, circleColor); - image.setPixel(centerX + y, centerY - x, circleColor); - image.setPixel(centerX - y, centerY + x, circleColor); - image.setPixel(centerX - y, centerY - x, circleColor); - if (d < 0) { - d += 2 * x + 1; - } else { - d += 2 * (x - y) + 1; - y--; - } - x++; - } while (x <= y); + do { + image.setPixel(centerX + x, centerY + y, circleColor); + image.setPixel(centerX + x, centerY - y, circleColor); + image.setPixel(centerX - x, centerY + y, circleColor); + image.setPixel(centerX - x, centerY - y, circleColor); + image.setPixel(centerX + y, centerY + x, circleColor); + image.setPixel(centerX + y, centerY - x, circleColor); + image.setPixel(centerX - y, centerY + x, circleColor); + image.setPixel(centerX - y, centerY - x, circleColor); + if (d < 0) { + d += 2 * x + 1; + } else { + d += 2 * (x - y) + 1; + y--; + } + x++; + } while (x <= y); - } + } } diff --git a/Task/Bitmap-Midpoint-circle-algorithm/Julia/bitmap-midpoint-circle-algorithm.jl b/Task/Bitmap-Midpoint-circle-algorithm/Julia/bitmap-midpoint-circle-algorithm.jl new file mode 100644 index 0000000000..1295233abb --- /dev/null +++ b/Task/Bitmap-Midpoint-circle-algorithm/Julia/bitmap-midpoint-circle-algorithm.jl @@ -0,0 +1,31 @@ +using Images, ImageView + +function drawcircle!(img::Matrix{T}, col::T, x0::Int, y0::Int, radius::Int) where T + x = radius - 1 + y = 0 + δx = δy = 1 + er = δx - (radius << 1) + + s = x + y + while x ≥ y + for opx in (+, -), opy in (+, -), el in (x, y) + @inbounds img[opx(x0, el) + 1, opy(y0, s - el) + 1] = col + end + if er ≤ 0 + y += 1 + er += δy + δy += 2 + end + if er > 0 + x -= 1 + δx += 2 + er += (-radius << 1) + δx + end + s = x + y + end + return img +end + +img = fill(Gray(255.0), 25, 25); +drawcircle!(img, Gray(0.0), 12, 12, 12) +imshow(img) diff --git a/Task/Bitmap-Midpoint-circle-algorithm/Julia/bitmap-midpoint-circle-algorithm.julia b/Task/Bitmap-Midpoint-circle-algorithm/Julia/bitmap-midpoint-circle-algorithm.julia deleted file mode 100644 index 5b1e33d063..0000000000 --- a/Task/Bitmap-Midpoint-circle-algorithm/Julia/bitmap-midpoint-circle-algorithm.julia +++ /dev/null @@ -1,31 +0,0 @@ -function drawcircle!(img::Matrix{T}, col::T, x0::Int, y0::Int, radius::Int) where T - x = radius - 1 - y = 0 - δx = δy = 1 - er = δx - (radius << 1) - - s = x + y - while x ≥ y - for opx in (+, -), opy in (+, -), el in (x, y) - @inbounds img[opx(x0, el) + 1, opy(y0, s - el) + 1] = col - end - if er ≤ 0 - y += 1 - er += δy - δy += 2 - end - if er > 0 - x -= 1 - δx += 2 - er += (-radius << 1) + δx - end - s = x + y - end - return img -end - -# Test -using Images - -img = fill(Gray(255.0), 25, 25); -drawcircle!(img, Gray(0.0), 12, 12, 12) diff --git a/Task/Bitmap-Midpoint-circle-algorithm/Kotlin/bitmap-midpoint-circle-algorithm.kotlin b/Task/Bitmap-Midpoint-circle-algorithm/Kotlin/bitmap-midpoint-circle-algorithm.kts similarity index 100% rename from Task/Bitmap-Midpoint-circle-algorithm/Kotlin/bitmap-midpoint-circle-algorithm.kotlin rename to Task/Bitmap-Midpoint-circle-algorithm/Kotlin/bitmap-midpoint-circle-algorithm.kts diff --git a/Task/Bitmap-Midpoint-circle-algorithm/Pluto/bitmap-midpoint-circle-algorithm-1.pluto b/Task/Bitmap-Midpoint-circle-algorithm/Pluto/bitmap-midpoint-circle-algorithm-1.pluto new file mode 100644 index 0000000000..c0d4f3ed9c --- /dev/null +++ b/Task/Bitmap-Midpoint-circle-algorithm/Pluto/bitmap-midpoint-circle-algorithm-1.pluto @@ -0,0 +1,33 @@ +local canvas = require "canvas" + +local function trunc(x) return x >= 0 ? math.floor(x) : math.ceil(x) end + +local function circle(c, cx, cy, r, col) + local d = trunc((5 - r * 4) / 4) + local x = 0 + local y = r + repeat + c:set(cx + x, cy + y, col) + c:set(cx + x, cy - y, col) + c:set(cx - x, cy + y, col) + c:set(cx - x, cy - y, col) + c:set(cx + y, cy + x, col) + c:set(cx + y, cy - x, col) + c:set(cx - y, cy + x, col) + c:set(cx - y, cy - x, col) + if d < 0 then + d += 2 * x + 1 + else + d += 2 * (x - y) + 1 + y -= 1 + end + ++x + until x > y +end + +local c = canvas.new(400, 400) +c:fill(0xffffff) -- white background + +-- Draw a blue circle with centre at (200, 200) and radius 100. +circle(c, 200, 200, 100, 0xff0000) +io.contents("mybmp.bmp", c:tobmp()) -- save to a bitmap file diff --git a/Task/Bitmap-Midpoint-circle-algorithm/Pluto/bitmap-midpoint-circle-algorithm-2.pluto b/Task/Bitmap-Midpoint-circle-algorithm/Pluto/bitmap-midpoint-circle-algorithm-2.pluto new file mode 100644 index 0000000000..97f3494948 --- /dev/null +++ b/Task/Bitmap-Midpoint-circle-algorithm/Pluto/bitmap-midpoint-circle-algorithm-2.pluto @@ -0,0 +1,6 @@ +require "bitmap" + +local bmp = bitmap.of(400, 400, color.white, "mybmp") +bmp:circle(200, 200, 100, color.blue) +bmp:view() +bmp:save() -- if required diff --git a/Task/Bitmap-Midpoint-circle-algorithm/Rebol/bitmap-midpoint-circle-algorithm.rebol b/Task/Bitmap-Midpoint-circle-algorithm/Rebol/bitmap-midpoint-circle-algorithm.rebol new file mode 100644 index 0000000000..fe3a8f7661 --- /dev/null +++ b/Task/Bitmap-Midpoint-circle-algorithm/Rebol/bitmap-midpoint-circle-algorithm.rebol @@ -0,0 +1,49 @@ +Rebol [ + title: "Rosetta code: Bitmap/Midpoint circle algorithm" + file: %Bitmap-Midpoint_circle_algorithm.r3 + url: https://rosettacode.org/wiki/Bitmap/Midpoint_circle_algorithm +] + +draw-circle: func [ + "Draw a circle on an image using the Midpoint Circle Algorithm." + bitmap [image!] center [pair!] radius [integer!] color [tuple!] +][ + x: center/x ;; unpack center coords from pair for arithmetic + y: center/y + dx: radius dy: 0 + err: 1 - radius ;; initial error term for midpoint decision + + while [dx >= dy] [ ;; iterate through the first octant only + ;; Mirror the single computed point into all 8 octants at once, + ;; exploiting the 8-fold symmetry of the circle. + bitmap/(as-pair x + dx y + dy): color ; octant 1 + bitmap/(as-pair x - dx y + dy): color ; octant 2 + bitmap/(as-pair x + dx y - dy): color ; octant 8 + bitmap/(as-pair x - dx y - dy): color ; octant 7 + bitmap/(as-pair x + dy y + dx): color ; octant 3 + bitmap/(as-pair x - dy y + dx): color ; octant 4 (swapped dx/dy) + bitmap/(as-pair x + dy y - dx): color ; octant 5 + bitmap/(as-pair x - dy y - dx): color ; octant 6 + + dy: dy + 1 ;; advance one step along the minor axis + + ;; Update the error term and conditionally step inward on dx. + ;; err < 0 means we are still inside the circle boundary + either err < 0 [ + err: err + (2 * dy) + 1 ;; correct error for dy step + ][ + dx: dx - 1 ;; step inward on major axis + err: err + (2 * (dy - dx)) + 1 ;; correct error for both steps + ] + ] +] + +img: make image! 29x29 ;; create a blank 29x29 canvas (white by default) +draw-circle img 15x15 5 black ;; small inner circle +draw-circle img 15x15 10 red ;; mid-size red ring +draw-circle img 15x15 14 green ;; large green ring, nearly fills the canvas + +;; scale up 10x with nearest-neighbour (Box) to keep pixel edges sharp +img: resize/filter img 290 'Box +save %midpoint-circles.png img +try [view img] diff --git a/Task/Bitmap-Midpoint-circle-algorithm/Scala/bitmap-midpoint-circle-algorithm.scala b/Task/Bitmap-Midpoint-circle-algorithm/Scala/bitmap-midpoint-circle-algorithm.scala index a9a9542002..1cb33f2446 100644 --- a/Task/Bitmap-Midpoint-circle-algorithm/Scala/bitmap-midpoint-circle-algorithm.scala +++ b/Task/Bitmap-Midpoint-circle-algorithm/Scala/bitmap-midpoint-circle-algorithm.scala @@ -22,7 +22,7 @@ object BitmapOps { x+=1 ddF_x+=2 f+=ddF_x - + bm.setPixel(x0+x, y0+y, c) bm.setPixel(x0-x, y0+y, c) bm.setPixel(x0+x, y0-y, c) diff --git a/Task/Bitmap-Midpoint-circle-algorithm/UNIX-Shell/bitmap-midpoint-circle-algorithm.sh b/Task/Bitmap-Midpoint-circle-algorithm/UNIX-Shell/bitmap-midpoint-circle-algorithm.sh index c11e2e9da6..e4db4df45c 100644 --- a/Task/Bitmap-Midpoint-circle-algorithm/UNIX-Shell/bitmap-midpoint-circle-algorithm.sh +++ b/Task/Bitmap-Midpoint-circle-algorithm/UNIX-Shell/bitmap-midpoint-circle-algorithm.sh @@ -13,10 +13,10 @@ function drawcircle { for y in $( seq $((y0-radius)) $((y0+radius)) ) do echo -en "\e[${y}H" - for x in $( seq $((x0+radius)) ) - do - echo -n "-" - done + for x in $( seq $((x0+radius)) ) + do + echo -n "-" + done done x=$((radius-1)) @@ -38,12 +38,12 @@ function drawcircle { if [ $err -le 0 ] then - ((++y)) + ((++y)) ((err+=dy)) ((dy+=2)) fi if [ $err -gt 0 ] - then + then ((--x)) ((dx+=2)) ((err+=dx-(radius<<1))) diff --git a/Task/Bitmap-Midpoint-circle-algorithm/Vedit-macro-language/bitmap-midpoint-circle-algorithm.vedit b/Task/Bitmap-Midpoint-circle-algorithm/Vedit-macro-language/bitmap-midpoint-circle-algorithm.vedit index 3a37522166..96c740f247 100644 --- a/Task/Bitmap-Midpoint-circle-algorithm/Vedit-macro-language/bitmap-midpoint-circle-algorithm.vedit +++ b/Task/Bitmap-Midpoint-circle-algorithm/Vedit-macro-language/bitmap-midpoint-circle-algorithm.vedit @@ -2,11 +2,11 @@ // #21 = center x, #22 = center y; #23 = radius :DRAW_CIRCLE: -#30 = 1 - #23 // f -#31 = 0 // ddF_x -#32 = -2 * #23 // ddF_y -#41 = 0 // x -#42 = #23 // y +#30 = 1 - #23 // f +#31 = 0 // ddF_x +#32 = -2 * #23 // ddF_y +#41 = 0 // x +#42 = #23 // y while (#41 <= #42) { #1 = #21+#41; #2 = #22+#42; Call("DRAW_PIXEL") @@ -18,9 +18,9 @@ while (#41 <= #42) { #1 = #21+#42; #2 = #22-#41; Call("DRAW_PIXEL") #1 = #21-#42; #2 = #22-#41; Call("DRAW_PIXEL") if (#30 >= 0) { - #42-- - #32 += 2 - #30 += #32 + #42-- + #32 += 2 + #30 += #32 } #41++ #31 += 2 diff --git a/Task/Bitmap-Midpoint-circle-algorithm/Zkl/bitmap-midpoint-circle-algorithm-1.zkl b/Task/Bitmap-Midpoint-circle-algorithm/Zkl/bitmap-midpoint-circle-algorithm-1.zkl index f651983a78..82685d593e 100644 --- a/Task/Bitmap-Midpoint-circle-algorithm/Zkl/bitmap-midpoint-circle-algorithm-1.zkl +++ b/Task/Bitmap-Midpoint-circle-algorithm/Zkl/bitmap-midpoint-circle-algorithm-1.zkl @@ -2,15 +2,15 @@ x:=r; y:=0; radiusError:=1-x; while(x >= y){ __sSet(rgb, x + x0, y + y0); - __sSet(rgb, y + x0, x + y0); - __sSet(rgb,-x + x0, y + y0); - __sSet(rgb,-y + x0, x + y0); - self[-x + x0, -y + y0]=rgb; // or do it this way, __sSet gets called as above - self[-y + x0, -x + y0]=rgb; - self[ x + x0, -y + y0]=rgb; - self[ y + x0, -x + y0]=rgb; - y+=1; - if (radiusError<0) radiusError+=2*y + 1; - else{ x-=1; radiusError+=2*(y - x + 1); } + __sSet(rgb, y + x0, x + y0); + __sSet(rgb,-x + x0, y + y0); + __sSet(rgb,-y + x0, x + y0); + self[-x + x0, -y + y0]=rgb; // or do it this way, __sSet gets called as above + self[-y + x0, -x + y0]=rgb; + self[ x + x0, -y + y0]=rgb; + self[ y + x0, -x + y0]=rgb; + y+=1; + if (radiusError<0) radiusError+=2*y + 1; + else{ x-=1; radiusError+=2*(y - x + 1); } } } diff --git a/Task/Bitmap-PPM-conversion-through-a-pipe/FreeBASIC/bitmap-ppm-conversion-through-a-pipe.basic b/Task/Bitmap-PPM-conversion-through-a-pipe/FreeBASIC/bitmap-ppm-conversion-through-a-pipe.basic new file mode 100644 index 0000000000..5633823dd7 --- /dev/null +++ b/Task/Bitmap-PPM-conversion-through-a-pipe/FreeBASIC/bitmap-ppm-conversion-through-a-pipe.basic @@ -0,0 +1,64 @@ +Const ancho = 400 +Const alto = 300 +Dim As Integer i, x, y +Dim As Ulong kolor + +' Set up graphics +Screenres ancho, alto, 32 +Windowtitle "Pattern Generator" + +' A little extravagant, this draws a design of dots and lines +' Fill background with color Rgb(&h40, &h80, &hc0) +Line (0, 0)-(ancho-1, alto-1), Rgb(64, 128, 192), BF + +' Draw random dots Rgb(&h20, &h40, &h80) +For i = 1 To 2000 + Pset (Rnd * (ancho-1), Rnd * (alto-1)), Rgb(32, 64, 128) +Next + +' Draw horizontal lines +For x = 0 To ancho-1 + For y = 240 To 244 + Pset (x, y), Rgb(32, 64, 128) + Next + For y = 260 To 264 + Pset (x, y), Rgb(32, 64, 128) + Next +Next + +' Draw vertical lines +For y = 0 To alto-1 + For x = 80 To 84 + Pset (x, y), Rgb(32, 64, 128) + Next + For x = 95 To 99 + Pset (x, y), Rgb(32, 64, 128) + Next +Next + +' Open PPM file to write +Dim As Integer ff = Freefile +Open "noutput.ppm" For Binary As #ff +If Err > 0 Then Print "Error opening output file": End + +' Write PPM header +Put #ff, , "P6" & Chr(10) +Put #ff, , Str(ancho) & " " & Str(alto) & Chr(10) +Put #ff, , "255" & Chr(10) + +' Write pixel data +For y = 0 To alto - 1 + For x = 0 To ancho - 1 + kolor = Point(x, y) + Put #ff, , Cbyte(kolor Shr 16) ' Blue + Put #ff, , Cbyte(kolor Shr 8) ' Green + Put #ff, , Cbyte(kolor) ' Red + Next +Next + +Close #ff + +' Convert to JPG using ImageMagick (pipe logic) +Shell "magick.exe noutput.ppm noutput.jpg" + +Sleep diff --git a/Task/Bitmap-PPM-conversion-through-a-pipe/Julia/bitmap-ppm-conversion-through-a-pipe.julia b/Task/Bitmap-PPM-conversion-through-a-pipe/Julia/bitmap-ppm-conversion-through-a-pipe.jl similarity index 100% rename from Task/Bitmap-PPM-conversion-through-a-pipe/Julia/bitmap-ppm-conversion-through-a-pipe.julia rename to Task/Bitmap-PPM-conversion-through-a-pipe/Julia/bitmap-ppm-conversion-through-a-pipe.jl diff --git a/Task/Bitmap-PPM-conversion-through-a-pipe/Kotlin/bitmap-ppm-conversion-through-a-pipe.kotlin b/Task/Bitmap-PPM-conversion-through-a-pipe/Kotlin/bitmap-ppm-conversion-through-a-pipe.kts similarity index 100% rename from Task/Bitmap-PPM-conversion-through-a-pipe/Kotlin/bitmap-ppm-conversion-through-a-pipe.kotlin rename to Task/Bitmap-PPM-conversion-through-a-pipe/Kotlin/bitmap-ppm-conversion-through-a-pipe.kts diff --git a/Task/Bitmap-Read-a-PPM-file/11l/bitmap-read-a-ppm-file.11l b/Task/Bitmap-Read-a-PPM-file/11l/bitmap-read-a-ppm-file.11l index eb8c2c11c4..93aeb15ba7 100644 --- a/Task/Bitmap-Read-a-PPM-file/11l/bitmap-read-a-ppm-file.11l +++ b/Task/Bitmap-Read-a-PPM-file/11l/bitmap-read-a-ppm-file.11l @@ -1,13 +1,4 @@ -T Colour - Byte r, g, b - - F (r, g, b) - .r = r - .g = g - .b = b - - F ==(other) - R .r == other.r & .g == other.g & .b == other.b +T Colour = BVec3 V black = Colour(0, 0, 0) V white = Colour(255, 255, 255) diff --git a/Task/Bitmap-Read-a-PPM-file/Ada/bitmap-read-a-ppm-file-1.ada b/Task/Bitmap-Read-a-PPM-file/Ada/bitmap-read-a-ppm-file-1.adb similarity index 100% rename from Task/Bitmap-Read-a-PPM-file/Ada/bitmap-read-a-ppm-file-1.ada rename to Task/Bitmap-Read-a-PPM-file/Ada/bitmap-read-a-ppm-file-1.adb diff --git a/Task/Bitmap-Read-a-PPM-file/Ada/bitmap-read-a-ppm-file-2.ada b/Task/Bitmap-Read-a-PPM-file/Ada/bitmap-read-a-ppm-file-2.adb similarity index 100% rename from Task/Bitmap-Read-a-PPM-file/Ada/bitmap-read-a-ppm-file-2.ada rename to Task/Bitmap-Read-a-PPM-file/Ada/bitmap-read-a-ppm-file-2.adb diff --git a/Task/Bitmap-Read-a-PPM-file/AutoHotkey/bitmap-read-a-ppm-file.ahk b/Task/Bitmap-Read-a-PPM-file/AutoHotkey/bitmap-read-a-ppm-file.ahk index 13ce33a881..df5682b996 100644 --- a/Task/Bitmap-Read-a-PPM-file/AutoHotkey/bitmap-read-a-ppm-file.ahk +++ b/Task/Bitmap-Read-a-PPM-file/AutoHotkey/bitmap-read-a-ppm-file.ahk @@ -46,11 +46,11 @@ loop % width * height if (j == width) { - j := 1 - i += 1 + j := 1 + i += 1 } else - j++ + j++ } return bitmap } diff --git a/Task/Bitmap-Read-a-PPM-file/Common-Lisp/bitmap-read-a-ppm-file-1.lisp b/Task/Bitmap-Read-a-PPM-file/Common-Lisp/bitmap-read-a-ppm-file-1.lisp index 511eba41d7..c68f4c654d 100644 --- a/Task/Bitmap-Read-a-PPM-file/Common-Lisp/bitmap-read-a-ppm-file-1.lisp +++ b/Task/Bitmap-Read-a-PPM-file/Common-Lisp/bitmap-read-a-ppm-file-1.lisp @@ -13,59 +13,59 @@ (defun read-ppm-file-header (file) (with-open-file (s file :direction :input) (do ((failure-count 0 (1+ failure-count)) - (tokens nil (let ((t1 (read-header-chars s))) - (if (> (length t1) 0) - (cons t1 tokens) - tokens)))) - ((>= (length tokens) 4) (values (nreverse tokens) - (file-position s))) + (tokens nil (let ((t1 (read-header-chars s))) + (if (> (length t1) 0) + (cons t1 tokens) + tokens)))) + ((>= (length tokens) 4) (values (nreverse tokens) + (file-position s))) (when (>= failure-count 10) - (error (format nil "File ~a does not seem to be a proper ppm file - maybe too many comment lines" file))) + (error (format nil "File ~a does not seem to be a proper ppm file - maybe too many comment lines" file))) (when (= (length tokens) 1) - (when (not (or (string= (first tokens) "P6") (string= (first tokens) "P3"))) - (error (format nil "File ~a is not a ppm file - wrong magic-number. Read ~a instead of P6 or P3 " file (first tokens)))))))) + (when (not (or (string= (first tokens) "P6") (string= (first tokens) "P3"))) + (error (format nil "File ~a is not a ppm file - wrong magic-number. Read ~a instead of P6 or P3 " file (first tokens)))))))) (defun read-ppm-image (file) (flet ((image-data-reader (stream start-position width height image-build-function read-function) - (file-position stream start-position) - (dotimes (row height) - (dotimes (col width) - (funcall image-build-function row col (funcall read-function stream)))))) + (file-position stream start-position) + (dotimes (row height) + (dotimes (col width) + (funcall image-build-function row col (funcall read-function stream)))))) (multiple-value-bind (header file-pos) (read-ppm-file-header file) (let* ((image-type (first header)) - (width (parse-integer (second header) :junk-allowed t)) - (height (parse-integer (third header) :junk-allowed t)) - (max-value (parse-integer (fourth header) :junk-allowed t)) - (image (make-rgb-pixel-buffer width height))) - (when (> max-value 255) - (error "unsupported depth - convert to 1byte depth with pamdepth")) - (cond ((string= "P6" image-type) - (with-open-file (stream file :direction :input :element-type '(unsigned-byte 8)) - (image-data-reader stream - file-pos - width - height - #'(lambda (w h val) - (setf (rgb-pixel image w h) val)) - #'(lambda (stream) - (make-rgb-pixel (read-byte stream) - (read-byte stream) - (read-byte stream)))) - image)) - ((string= "P3" image-type) - (with-open-file (stream file :direction :input) - (image-data-reader stream - file-pos - width - height - #'(lambda (w h val) - (setf (rgb-pixel image w h) val)) - #'(lambda (stream) - (make-rgb-pixel (read stream) - (read stream) - (read stream)))) - image)) - (t 'unsupported)) + (width (parse-integer (second header) :junk-allowed t)) + (height (parse-integer (third header) :junk-allowed t)) + (max-value (parse-integer (fourth header) :junk-allowed t)) + (image (make-rgb-pixel-buffer width height))) + (when (> max-value 255) + (error "unsupported depth - convert to 1byte depth with pamdepth")) + (cond ((string= "P6" image-type) + (with-open-file (stream file :direction :input :element-type '(unsigned-byte 8)) + (image-data-reader stream + file-pos + width + height + #'(lambda (w h val) + (setf (rgb-pixel image w h) val)) + #'(lambda (stream) + (make-rgb-pixel (read-byte stream) + (read-byte stream) + (read-byte stream)))) + image)) + ((string= "P3" image-type) + (with-open-file (stream file :direction :input) + (image-data-reader stream + file-pos + width + height + #'(lambda (w h val) + (setf (rgb-pixel image w h) val)) + #'(lambda (stream) + (make-rgb-pixel (read stream) + (read stream) + (read stream)))) + image)) + (t 'unsupported)) image)))) (export 'read-ppm-image) diff --git a/Task/Bitmap-Read-a-PPM-file/Crystal/bitmap-read-a-ppm-file.cr b/Task/Bitmap-Read-a-PPM-file/Crystal/bitmap-read-a-ppm-file.cr new file mode 100644 index 0000000000..4b8e3b6639 --- /dev/null +++ b/Task/Bitmap-Read-a-PPM-file/Crystal/bitmap-read-a-ppm-file.cr @@ -0,0 +1,51 @@ +require "./pixmap" + +class Pixmap + def self.load_ppm (io) + blanks = StaticArray[9, 10, 11, 12, 13, 32] + magic = Bytes.new(3) + io.read magic + raise "Invalid format" unless magic[0] == 'P'.ord && + magic[1] == '6'.ord && + magic[2].in? blanks + data = io.getb_to_end + pos = 0 + get_number = -> : Int32 { + start = pos + loop do # skip blanks and comments + case data[start] + when .in? blanks then start += 1 + when '#'.ord + while data[start] != 10 + start += 1 + end + else break + end + end + stop = start + until data[stop].in? blanks + stop += 1 + end + pos = stop + String.new(data[start..stop]).to_i + } + begin + width = get_number.call + height = get_number.call + maxval = get_number.call + rescue ex + raise "Bad P6 file" + end + raise "Unsupported color depth" unless maxval = 255 + pos += 1 + raise "Invalid data" unless (data.size - pos) % 3 == 0 + len = (data.size - pos) // 3 + raise "Bad bounds" unless len == width * height + pixels = Array(Color).new(len) { |i| + Color.new(data[i*3 + pos], data[i*3 + pos + 1], data[i*3 + pos + 2]) + } + Pixmap.new width, height, pixels + end + + register_loader ".ppm", load_ppm +end diff --git a/Task/Bitmap-Read-a-PPM-file/Delphi/bitmap-read-a-ppm-file.delphi b/Task/Bitmap-Read-a-PPM-file/Delphi/bitmap-read-a-ppm-file.pas similarity index 100% rename from Task/Bitmap-Read-a-PPM-file/Delphi/bitmap-read-a-ppm-file.delphi rename to Task/Bitmap-Read-a-PPM-file/Delphi/bitmap-read-a-ppm-file.pas diff --git a/Task/Bitmap-Read-a-PPM-file/Euphoria/bitmap-read-a-ppm-file-1.euphoria b/Task/Bitmap-Read-a-PPM-file/Euphoria/bitmap-read-a-ppm-file-1.eu similarity index 100% rename from Task/Bitmap-Read-a-PPM-file/Euphoria/bitmap-read-a-ppm-file-1.euphoria rename to Task/Bitmap-Read-a-PPM-file/Euphoria/bitmap-read-a-ppm-file-1.eu diff --git a/Task/Bitmap-Read-a-PPM-file/Euphoria/bitmap-read-a-ppm-file-2.euphoria b/Task/Bitmap-Read-a-PPM-file/Euphoria/bitmap-read-a-ppm-file-2.eu similarity index 100% rename from Task/Bitmap-Read-a-PPM-file/Euphoria/bitmap-read-a-ppm-file-2.euphoria rename to Task/Bitmap-Read-a-PPM-file/Euphoria/bitmap-read-a-ppm-file-2.eu diff --git a/Task/Bitmap-Read-a-PPM-file/FBSL/bitmap-read-a-ppm-file.fbsl b/Task/Bitmap-Read-a-PPM-file/FBSL/bitmap-read-a-ppm-file.fbsl index b2d7f3528e..188aa0caa2 100644 --- a/Task/Bitmap-Read-a-PPM-file/FBSL/bitmap-read-a-ppm-file.fbsl +++ b/Task/Bitmap-Read-a-PPM-file/FBSL/bitmap-read-a-ppm-file.fbsl @@ -8,11 +8,11 @@ blobsize = INSTR(FILEGET, "\n255\n") + 4 ' Get sizeof PPM header head = @FILEGET + blobsize: tail = @FILEGET + FILELEN ' Set loop bounds FOR ptr = head TO tail STEP 3 ' Transform color triplets - r = PEEK(ptr + 0, 1) ' Read colors stored in RGB order - g = PEEK(ptr + 1, 1) - b = PEEK(ptr + 2, 1) - l = 0.2126 * r + 0.7152 * g + 0.0722 * b ' Derive luminance - POKE(ptr + 0, CHR(l))(ptr + 1, CHR)(ptr + 2, CHR) ' Write grayscale + r = PEEK(ptr + 0, 1) ' Read colors stored in RGB order + g = PEEK(ptr + 1, 1) + b = PEEK(ptr + 2, 1) + l = 0.2126 * r + 0.7152 * g + 0.0722 * b ' Derive luminance + POKE(ptr + 0, CHR(l))(ptr + 1, CHR)(ptr + 2, CHR) ' Write grayscale NEXT FILEPUT(FILEOPEN(grayscale, BINARY_NEW), FILEGET): FILECLOSE(FILEOPEN) ' Save buffer diff --git a/Task/Bitmap-Read-a-PPM-file/Forth/bitmap-read-a-ppm-file.fth b/Task/Bitmap-Read-a-PPM-file/Forth/bitmap-read-a-ppm-file.fth index 20b30e7793..28824390fc 100644 --- a/Task/Bitmap-Read-a-PPM-file/Forth/bitmap-read-a-ppm-file.fth +++ b/Task/Bitmap-Read-a-PPM-file/Forth/bitmap-read-a-ppm-file.fth @@ -3,7 +3,7 @@ s" P6" compare abort" Only P6 supported." pad dup 80 fid read-line throw 0= abort" Partial line" 0. 2swap >number - 1 /string \ skip space + 1 /string \ skip space 0. 2swap >number 2drop drop nip ( w h ) bitmap { bmp } diff --git a/Task/Bitmap-Read-a-PPM-file/Java/bitmap-read-a-ppm-file.java b/Task/Bitmap-Read-a-PPM-file/Java/bitmap-read-a-ppm-file.java index 6d1e33c878..9670723d2d 100644 --- a/Task/Bitmap-Read-a-PPM-file/Java/bitmap-read-a-ppm-file.java +++ b/Task/Bitmap-Read-a-PPM-file/Java/bitmap-read-a-ppm-file.java @@ -12,32 +12,32 @@ import javax.imageio.ImageIO; public class ReadPPMFile { - public static void main(String[] aArgs) throws IOException { + public static void main(String[] aArgs) throws IOException { // Using the file created in the Bitmap task - String filePath = "output.ppm"; - - reader = new BufferedInputStream( new FileInputStream(filePath) ); - final char header1 = (char) reader.read(); + String filePath = "output.ppm"; + + reader = new BufferedInputStream( new FileInputStream(filePath) ); + final char header1 = (char) reader.read(); final char header2 = (char) reader.read(); final char header3 = (char) reader.read(); if ( header1 != 'P' || header2 != '6' || header3 != END_OF_LINE) { - reader.close(); - throw new IllegalArgumentException("Not a valid P6 PPM file"); + reader.close(); + throw new IllegalArgumentException("Not a valid P6 PPM file"); } final int width = processCharacters(SPACE_CHARACTER); final int height = processCharacters(END_OF_LINE); final int maxColorValue = processCharacters(END_OF_LINE); if ( maxColorValue < 0 || maxColorValue > 255 ) { - reader.close(); - throw new IllegalArgumentException("Maximum color value is outside the range 0..255"); + reader.close(); + throw new IllegalArgumentException("Maximum color value is outside the range 0..255"); } // Remove any comments before reading data reader.mark(1); while ( reader.read() == START_OF_COMMENT ) { - while ( reader.read() != END_OF_LINE ); - reader.mark(1); + while ( reader.read() != END_OF_LINE ); + reader.mark(1); } reader.reset(); @@ -47,10 +47,10 @@ public class ReadPPMFile { byte[] buffer = new byte[width * 3]; for ( int y = 0; y < height; y++ ) { reader.read(buffer, 0, buffer.length); - for ( int x = 0; x < width; x++ ) { + for ( int x = 0; x < width; x++ ) { Color color = new Color(Byte.toUnsignedInt(buffer[x * 3]), - Byte.toUnsignedInt(buffer[x * 3 + 1]), - Byte.toUnsignedInt(buffer[x * 3 + 2])); + Byte.toUnsignedInt(buffer[x * 3 + 1]), + Byte.toUnsignedInt(buffer[x * 3 + 2])); bitmap.setPixel(x, y, color); } } @@ -60,29 +60,29 @@ public class ReadPPMFile { // Convert to gray scale and save to a file bitmap.convertToGrayscale(); File grayFile = new File("outputGray.jpg"); - ImageIO.write((RenderedImage) bitmap.getImage(), "jpg", grayFile); - } - - private static int processCharacters(char aChar) throws IOException { - StringBuilder characters = new StringBuilder(); - char ch; - while ( ( ch = (char) reader.read() ) != aChar ) { - if ( ch == START_OF_COMMENT ) { - while ( reader.read() != END_OF_LINE ); - continue; - } - characters.append(ch); - } - return Integer.valueOf(characters.toString()); - } - - private static BufferedInputStream reader; - - private static final char START_OF_COMMENT = '#'; - private static final char SPACE_CHARACTER = ' '; - private static final char END_OF_LINE = '\n'; + ImageIO.write((RenderedImage) bitmap.getImage(), "jpg", grayFile); + } -} + private static int processCharacters(char aChar) throws IOException { + StringBuilder characters = new StringBuilder(); + char ch; + while ( ( ch = (char) reader.read() ) != aChar ) { + if ( ch == START_OF_COMMENT ) { + while ( reader.read() != END_OF_LINE ); + continue; + } + characters.append(ch); + } + return Integer.valueOf(characters.toString()); + } + + private static BufferedInputStream reader; + + private static final char START_OF_COMMENT = '#'; + private static final char SPACE_CHARACTER = ' '; + private static final char END_OF_LINE = '\n'; + +} final class BasicBitmapStorage { @@ -105,12 +105,12 @@ final class BasicBitmapStorage { } public Image getImage() { - return image; + return image; } public void convertToGrayscale() { for ( int y = 0; y < image.getHeight(); y++ ) { - for ( int x = 0; x < image.getWidth(); x++ ) { + for ( int x = 0; x < image.getWidth(); x++ ) { int color = image.getRGB(x, y); int alpha = ( color >> 24 ) & 255; diff --git a/Task/Bitmap-Read-a-PPM-file/Julia/bitmap-read-a-ppm-file.julia b/Task/Bitmap-Read-a-PPM-file/Julia/bitmap-read-a-ppm-file.jl similarity index 100% rename from Task/Bitmap-Read-a-PPM-file/Julia/bitmap-read-a-ppm-file.julia rename to Task/Bitmap-Read-a-PPM-file/Julia/bitmap-read-a-ppm-file.jl diff --git a/Task/Bitmap-Read-a-PPM-file/Kotlin/bitmap-read-a-ppm-file.kotlin b/Task/Bitmap-Read-a-PPM-file/Kotlin/bitmap-read-a-ppm-file.kts similarity index 100% rename from Task/Bitmap-Read-a-PPM-file/Kotlin/bitmap-read-a-ppm-file.kotlin rename to Task/Bitmap-Read-a-PPM-file/Kotlin/bitmap-read-a-ppm-file.kts diff --git a/Task/Bitmap-Read-a-PPM-file/OCaml/bitmap-read-a-ppm-file-1.ocaml b/Task/Bitmap-Read-a-PPM-file/OCaml/bitmap-read-a-ppm-file-1.ml similarity index 100% rename from Task/Bitmap-Read-a-PPM-file/OCaml/bitmap-read-a-ppm-file-1.ocaml rename to Task/Bitmap-Read-a-PPM-file/OCaml/bitmap-read-a-ppm-file-1.ml diff --git a/Task/Bitmap-Read-a-PPM-file/OCaml/bitmap-read-a-ppm-file-2.ocaml b/Task/Bitmap-Read-a-PPM-file/OCaml/bitmap-read-a-ppm-file-2.ml similarity index 100% rename from Task/Bitmap-Read-a-PPM-file/OCaml/bitmap-read-a-ppm-file-2.ocaml rename to Task/Bitmap-Read-a-PPM-file/OCaml/bitmap-read-a-ppm-file-2.ml diff --git a/Task/Bitmap-Read-a-PPM-file/Oz/bitmap-read-a-ppm-file-1.oz b/Task/Bitmap-Read-a-PPM-file/Oz/bitmap-read-a-ppm-file-1.oz index 5d3fd1c6e4..33b5a7e6ef 100644 --- a/Task/Bitmap-Read-a-PPM-file/Oz/bitmap-read-a-ppm-file-1.oz +++ b/Task/Bitmap-Read-a-PPM-file/Oz/bitmap-read-a-ppm-file-1.oz @@ -10,31 +10,31 @@ define F = {New Open.file init(name:Filename)} fun {ReadColor8 _} - Bytes = {F read(list:$ size:3)} + Bytes = {F read(list:$ size:3)} in - {List.toTuple color Bytes} + {List.toTuple color Bytes} end fun {ReadColor16 _} - Bytes = {F read(list:$ size:6)} + Bytes = {F read(list:$ size:6)} in - {List.toTuple color {Map {PairUp Bytes} FromBytes}} + {List.toTuple color {Map {PairUp Bytes} FromBytes}} end in try - Magic = {F read(size:2 list:$)} - if Magic \= "P6" then raise bitmapIO(read unsupportedFormat(Magic)) end end - Width = {ReadNumber F} - Height = {ReadNumber F} - MaxVal = {ReadNumber F} - MaxVal =< 0xffff = true - Reader = if MaxVal =< 0xff then ReadColor8 else ReadColor16 end - B = {Bitmap.new Width Height} + Magic = {F read(size:2 list:$)} + if Magic \= "P6" then raise bitmapIO(read unsupportedFormat(Magic)) end end + Width = {ReadNumber F} + Height = {ReadNumber F} + MaxVal = {ReadNumber F} + MaxVal =< 0xffff = true + Reader = if MaxVal =< 0xff then ReadColor8 else ReadColor16 end + B = {Bitmap.new Width Height} in - {Bitmap.transform B Reader} - B + {Bitmap.transform B Reader} + B finally - {F close} + {F close} end end @@ -43,12 +43,12 @@ define in {SkipWS F} Ds = for collect:Collect break:Break do - [C] = {F read(list:$ size:1)} - in - if {Char.isDigit C} then {Collect C} - else {Break} - end - end + [C] = {F read(list:$ size:1)} + in + if {Char.isDigit C} then {Collect C} + else {Break} + end + end {SkipWS F} {String.toInt Ds} end @@ -58,9 +58,9 @@ define in if {Char.isSpace C} then {SkipWS F} elseif C == &# then - {SkipLine F} + {SkipLine F} else - {F seek(whence:current offset:~1)} + {F seek(whence:current offset:~1)} end end diff --git a/Task/Bitmap-Read-a-PPM-file/Raku/bitmap-read-a-ppm-file.raku b/Task/Bitmap-Read-a-PPM-file/Raku/bitmap-read-a-ppm-file.raku index 5f77cfb471..395d55219b 100644 --- a/Task/Bitmap-Read-a-PPM-file/Raku/bitmap-read-a-ppm-file.raku +++ b/Task/Bitmap-Read-a-PPM-file/Raku/bitmap-read-a-ppm-file.raku @@ -7,8 +7,8 @@ class Bitmap { role PGM { has @.GS; method P5 returns Blob { - "P5\n{self.width} {self.height}\n255\n".encode('ascii') - ~ Blob.new: self.GS + "P5\n{self.width} {self.height}\n255\n".encode('ascii') + ~ Blob.new: self.GS } } diff --git a/Task/Bitmap-Read-a-PPM-file/Rebol/bitmap-read-a-ppm-file.rebol b/Task/Bitmap-Read-a-PPM-file/Rebol/bitmap-read-a-ppm-file.rebol new file mode 100644 index 0000000000..7c8de98fa0 --- /dev/null +++ b/Task/Bitmap-Read-a-PPM-file/Rebol/bitmap-read-a-ppm-file.rebol @@ -0,0 +1,50 @@ +Rebol [ + title: "Rosetta code: Bitmap/Read a PPM file" + file: %Bitmap-Read_a_PPM_file.r3 + url: https://rosettacode.org/wiki/Bitmap/Read_a_PPM_file +] + +decode-ppm: function[ppm [string! file! url!]][ + ;; Load source into a string if a file or URL was given + unless string? ppm [ppm: read/string ppm] + if all [ + ;; Strip the "P3" magic header and any comment lines + parse/case ppm ["P3" any [LF | #"#" to LF skip] ppm: to end] + ;; Lex the remaining text into Rebol values + try [ppm: transcode ppm] + ;; Extract image dimensions, colour depth, and raw RGB values + parse ppm [ + set width: integer! + set height: integer! + set depth: integer! + rgb: to end + ] + ][ + img: make image! as-pair width height + i: 1 clr: 0.0.0 + foreach [r g b] rgb [ + ;; Normalise each channel to 0–255 + clr/1: 255 * (r / depth) + clr/2: 255 * (g / depth) + clr/3: 255 * (b / depth) + img/:i: clr + ++ i + ] + ;; Return the completed image + img + ] +] + +img: decode-ppm {P3 +# feep.ppm +4 4 +15 +0 0 0 0 0 0 0 0 0 15 0 15 +0 0 0 0 15 7 0 0 0 0 0 0 +0 0 0 0 0 0 0 15 7 0 0 0 +15 0 15 0 0 0 0 0 0 0 0 0} + +print "Source image:" +print img +print "Grayscale PPM output:" +print to-ppm grayscale img ;@@ https://rosettacode.org/wiki/Bitmap/Write_a_PPM_file diff --git a/Task/Bitmap-Read-a-PPM-file/Rust/bitmap-read-a-ppm-file.rust b/Task/Bitmap-Read-a-PPM-file/Rust/bitmap-read-a-ppm-file.rs similarity index 100% rename from Task/Bitmap-Read-a-PPM-file/Rust/bitmap-read-a-ppm-file.rust rename to Task/Bitmap-Read-a-PPM-file/Rust/bitmap-read-a-ppm-file.rs diff --git a/Task/Bitmap-Read-a-PPM-file/Scala/bitmap-read-a-ppm-file-1.scala b/Task/Bitmap-Read-a-PPM-file/Scala/bitmap-read-a-ppm-file-1.scala index 672dee049f..c97a82aeab 100644 --- a/Task/Bitmap-Read-a-PPM-file/Scala/bitmap-read-a-ppm-file-1.scala +++ b/Task/Bitmap-Read-a-PPM-file/Scala/bitmap-read-a-ppm-file-1.scala @@ -6,7 +6,7 @@ import javax.swing.ImageIcon object Pixmap { private case class PpmHeader(format:String, width:Int, height:Int, maxColor:Int) - + def load(filename:String):Option[RgbBitmap]={ implicit val in=new BufferedInputStream(new FileInputStream(filename)) val header=readHeader @@ -22,7 +22,7 @@ object Pixmap { private def readHeader(implicit in:InputStream)={ var format=readLine - + var line=readLine while(line.startsWith("#")) //skip comments line=readLine @@ -31,7 +31,7 @@ object Pixmap { val width=parts(0).toInt val height=parts(1).toInt val maxColor=readLine.toInt - + new PpmHeader(format, width, height, maxColor) } diff --git a/Task/Bitmap-Read-a-PPM-file/Vedit-macro-language/bitmap-read-a-ppm-file-1.vedit b/Task/Bitmap-Read-a-PPM-file/Vedit-macro-language/bitmap-read-a-ppm-file-1.vedit index c5de2d216f..4e7dbe614d 100644 --- a/Task/Bitmap-Read-a-PPM-file/Vedit-macro-language/bitmap-read-a-ppm-file-1.vedit +++ b/Task/Bitmap-Read-a-PPM-file/Vedit-macro-language/bitmap-read-a-ppm-file-1.vedit @@ -7,11 +7,11 @@ :LOAD_PPM: File_Open(@10) BOF -Search("|X", ADVANCE) // skip "P6" -#11 = Num_Eval(ADVANCE) // #11 = width -Match("|X", ADVANCE) // skip separator -#12 = Num_Eval(ADVANCE) // #12 = height +Search("|X", ADVANCE) // skip "P6" +#11 = Num_Eval(ADVANCE) // #11 = width +Match("|X", ADVANCE) // skip separator +#12 = Num_Eval(ADVANCE) // #12 = height Match("|X", ADVANCE) -Search("|X", ADVANCE) // skip maxval (assume 255) -Del_Block(0,CP) // remove the header +Search("|X", ADVANCE) // skip maxval (assume 255) +Del_Block(0,CP) // remove the header Return diff --git a/Task/Bitmap-Read-a-PPM-file/Yabasic/bitmap-read-a-ppm-file.basic b/Task/Bitmap-Read-a-PPM-file/Yabasic/bitmap-read-a-ppm-file.basic index 6252db3926..4bf6e89591 100644 --- a/Task/Bitmap-Read-a-PPM-file/Yabasic/bitmap-read-a-ppm-file.basic +++ b/Task/Bitmap-Read-a-PPM-file/Yabasic/bitmap-read-a-ppm-file.basic @@ -1,27 +1,27 @@ sub readPPM(f$) - local ff, x, y, t$, dcol$, wid, hei + local ff, x, y, t$, dcol$, wid, hei - if f$ = "" print "No PPM file name indicate." : return false + if f$ = "" print "No PPM file name indicate." : return false - ff = open (f$, "rb") - if not ff print "File ", f$, " not found." : return false + ff = open (f$, "rb") + if not ff print "File ", f$, " not found." : return false - input #ff t$, wid, hei, dcol$ + input #ff t$, wid, hei, dcol$ - if t$ = "P6" then - open window wid, hei - - for x = 0 to hei - 1 - for y = 0 to wid - 1 - color peek(#ff), peek(#ff), peek(#ff) - dot y, x - next y - next x - - close #ff - else - print "File is NOT PPM P6 type." : return false - end if - - return true + if t$ = "P6" then + open window wid, hei + + for x = 0 to hei - 1 + for y = 0 to wid - 1 + color peek(#ff), peek(#ff), peek(#ff) + dot y, x + next y + next x + + close #ff + else + print "File is NOT PPM P6 type." : return false + end if + + return true end sub diff --git a/Task/Bitmap-Read-an-image-through-a-pipe/FreeBASIC/bitmap-read-an-image-through-a-pipe.basic b/Task/Bitmap-Read-an-image-through-a-pipe/FreeBASIC/bitmap-read-an-image-through-a-pipe.basic new file mode 100644 index 0000000000..532b629312 --- /dev/null +++ b/Task/Bitmap-Read-an-image-through-a-pipe/FreeBASIC/bitmap-read-an-image-through-a-pipe.basic @@ -0,0 +1,65 @@ +Type IMAGE + w As Integer + h As Integer + bpp As Integer + dato(Any) As Ubyte +End Type + +Function readImageFile(filename As String, img As IMAGE) As Boolean + ' First convert image to PPM using temp file + Dim As String cmd = "magick.exe " & filename & " temp.ppm" + Shell(cmd) + + Dim As Integer ff = Freefile + Open "temp.ppm" For Binary As #ff + + ' Read PPM header + Dim As String linea + Line Input #ff, linea ' P6 + If Left(linea, 2) <> "P6" Then Return True + + ' Skip comments + Do + Line Input #ff, linea + If Left(linea, 1) <> "#" Then Exit Do + Loop + + img.w = Val(Left(linea, Instr(linea, " "))) + img.h = Val(Mid(linea, Instr(linea, " "))) + + ' Allocate memory for image data + Redim img.dato(img.w * img.h * 3 - 1) + + ' Read binary pixel data + Get #ff, , img.dato() + + Close #ff + Kill("temp.ppm") ' Clean up temp file + Return False +End Function + +Function writePPM(filename As String, img As IMAGE) As Boolean + Dim As Integer ff = Freefile + Open filename For Binary As #ff + + ' Write PPM header + Put #ff, , "P6" & Chr(10) + Put #ff, , Str(img.w) & " " & Str(img.h) & Chr(10) + Put #ff, , "255" & Chr(10) + + ' Write image data + For i As Integer = 0 To (img.w * img.h * 3 - 1) Step 3 + Put #ff, , img.dato(i + 1) ' Green + Put #ff, , img.dato(i + 2) ' Blue + Put #ff, , img.dato(i) ' Red + Next + + Close #ff + Return False +End Function + +' Main program +Dim As IMAGE img + +If readImageFile("example.png", img) Then Print "Error reading input file" +If writePPM("output.ppm", img) Then Print "i:\Error writing PPM file" diff --git a/Task/Bitmap-Read-an-image-through-a-pipe/Julia/bitmap-read-an-image-through-a-pipe.julia b/Task/Bitmap-Read-an-image-through-a-pipe/Julia/bitmap-read-an-image-through-a-pipe.jl similarity index 100% rename from Task/Bitmap-Read-an-image-through-a-pipe/Julia/bitmap-read-an-image-through-a-pipe.julia rename to Task/Bitmap-Read-an-image-through-a-pipe/Julia/bitmap-read-an-image-through-a-pipe.jl diff --git a/Task/Bitmap-Read-an-image-through-a-pipe/Kotlin/bitmap-read-an-image-through-a-pipe.kotlin b/Task/Bitmap-Read-an-image-through-a-pipe/Kotlin/bitmap-read-an-image-through-a-pipe.kts similarity index 100% rename from Task/Bitmap-Read-an-image-through-a-pipe/Kotlin/bitmap-read-an-image-through-a-pipe.kotlin rename to Task/Bitmap-Read-an-image-through-a-pipe/Kotlin/bitmap-read-an-image-through-a-pipe.kts diff --git a/Task/Bitmap-Read-an-image-through-a-pipe/OCaml/bitmap-read-an-image-through-a-pipe.ocaml b/Task/Bitmap-Read-an-image-through-a-pipe/OCaml/bitmap-read-an-image-through-a-pipe.ml similarity index 100% rename from Task/Bitmap-Read-an-image-through-a-pipe/OCaml/bitmap-read-an-image-through-a-pipe.ocaml rename to Task/Bitmap-Read-an-image-through-a-pipe/OCaml/bitmap-read-an-image-through-a-pipe.ml diff --git a/Task/Bitmap-Write-a-PPM-file/11l/bitmap-write-a-ppm-file.11l b/Task/Bitmap-Write-a-PPM-file/11l/bitmap-write-a-ppm-file.11l index 31e28a4f57..ab83896090 100644 --- a/Task/Bitmap-Write-a-PPM-file/11l/bitmap-write-a-ppm-file.11l +++ b/Task/Bitmap-Write-a-PPM-file/11l/bitmap-write-a-ppm-file.11l @@ -1,13 +1,4 @@ -T Colour - Byte r, g, b - - F (r, g, b) - .r = r - .g = g - .b = b - - F ==(other) - R .r == other.r & .g == other.g & .b == other.b +T Colour = BVec3 V black = Colour(0, 0, 0) V white = Colour(255, 255, 255) diff --git a/Task/Bitmap-Write-a-PPM-file/Ada/bitmap-write-a-ppm-file.ada b/Task/Bitmap-Write-a-PPM-file/Ada/bitmap-write-a-ppm-file.ada deleted file mode 100644 index 8eb4b7a790..0000000000 --- a/Task/Bitmap-Write-a-PPM-file/Ada/bitmap-write-a-ppm-file.ada +++ /dev/null @@ -1,26 +0,0 @@ -with Ada.Characters.Latin_1; -with Ada.Streams.Stream_IO; use Ada.Streams.Stream_IO; - -procedure Put_PPM (File : File_Type; Picture : Image) is - use Ada.Characters.Latin_1; - Size : constant String := Integer'Image (Picture'Length (2)) & Integer'Image (Picture'Length (1)); - Buffer : String (1..Picture'Length (2) * 3); - Color : Pixel; - Index : Positive; -begin - String'Write (Stream (File), "P6" & LF); - String'Write (Stream (File), Size (2..Size'Last) & LF); - String'Write (Stream (File), "255" & LF); - for I in Picture'Range (1) loop - Index := Buffer'First; - for J in Picture'Range (2) loop - Color := Picture (I, J); - Buffer (Index) := Character'Val (Color.R); - Buffer (Index + 1) := Character'Val (Color.G); - Buffer (Index + 2) := Character'Val (Color.B); - Index := Index + 3; - end loop; - String'Write (Stream (File), Buffer); - end loop; - Character'Write (Stream (File), LF); -end Put_PPM; diff --git a/Task/Bitmap-Write-a-PPM-file/Ada/bitmap-write-a-ppm-file.adb b/Task/Bitmap-Write-a-PPM-file/Ada/bitmap-write-a-ppm-file.adb new file mode 100644 index 0000000000..c3611189b3 --- /dev/null +++ b/Task/Bitmap-Write-a-PPM-file/Ada/bitmap-write-a-ppm-file.adb @@ -0,0 +1,29 @@ +with Ada.Characters.Latin_1; +with Ada.Streams.Stream_IO; use Ada.Streams.Stream_IO; + +with Bitmap_Store; use Bitmap_Store; +-- This package is defined in the Bitmap task. + +procedure Put_PPM (File : File_Type; Picture : Image) is + use Ada.Characters.Latin_1; + Size : constant String := Integer'Image (Picture'Length (2)) & Integer'Image (Picture'Length (1)); + Buffer : String (1..Picture'Length (2) * 3); + Color : Pixel; + Index : Positive; +begin + String'Write (Stream (File), "P6" & LF); + String'Write (Stream (File), Size (2..Size'Last) & LF); + String'Write (Stream (File), "255" & LF); + for I in Picture'Range (1) loop + Index := Buffer'First; + for J in Picture'Range (2) loop + Color := Picture (I, J); + Buffer (Index) := Character'Val (Color.R); + Buffer (Index + 1) := Character'Val (Color.G); + Buffer (Index + 2) := Character'Val (Color.B); + Index := Index + 3; + end loop; + String'Write (Stream (File), Buffer); + end loop; + Character'Write (Stream (File), LF); +end Put_PPM; diff --git a/Task/Bitmap-Write-a-PPM-file/Common-Lisp/bitmap-write-a-ppm-file.lisp b/Task/Bitmap-Write-a-PPM-file/Common-Lisp/bitmap-write-a-ppm-file.lisp index d922a0db8d..d4046e677b 100644 --- a/Task/Bitmap-Write-a-PPM-file/Common-Lisp/bitmap-write-a-ppm-file.lisp +++ b/Task/Bitmap-Write-a-PPM-file/Common-Lisp/bitmap-write-a-ppm-file.lisp @@ -1,28 +1,28 @@ (defun write-rgb-buffer-to-ppm-file (filename buffer) (with-open-file (stream filename - :element-type '(unsigned-byte 8) - :direction :output - :if-does-not-exist :create - :if-exists :supersede) + :element-type '(unsigned-byte 8) + :direction :output + :if-does-not-exist :create + :if-exists :supersede) (let* ((dimensions (array-dimensions buffer)) - (width (first dimensions)) - (height (second dimensions)) - (header (format nil "P6~A~D ~D~A255~A" - #\newline - width height #\newline - #\newline))) + (width (first dimensions)) + (height (second dimensions)) + (header (format nil "P6~A~D ~D~A255~A" + #\newline + width height #\newline + #\newline))) (loop - :for char :across header - :do (write-byte (char-code char) stream)) #| Assumes char-codes match ASCII |# + :for char :across header + :do (write-byte (char-code char) stream)) #| Assumes char-codes match ASCII |# (loop - :for x :upfrom 0 :below width - :do (loop :for y :upfrom 0 :below height - :do (let ((pixel (rgb-pixel buffer x y))) - (let ((red (rgb-pixel-red pixel)) - (green (rgb-pixel-green pixel)) - (blue (rgb-pixel-blue pixel))) - (write-byte red stream) - (write-byte green stream) - (write-byte blue stream))))))) + :for x :upfrom 0 :below width + :do (loop :for y :upfrom 0 :below height + :do (let ((pixel (rgb-pixel buffer x y))) + (let ((red (rgb-pixel-red pixel)) + (green (rgb-pixel-green pixel)) + (blue (rgb-pixel-blue pixel))) + (write-byte red stream) + (write-byte green stream) + (write-byte blue stream))))))) filename) diff --git a/Task/Bitmap-Write-a-PPM-file/Crystal/bitmap-write-a-ppm-file-1.cr b/Task/Bitmap-Write-a-PPM-file/Crystal/bitmap-write-a-ppm-file-1.cr new file mode 100644 index 0000000000..24affee476 --- /dev/null +++ b/Task/Bitmap-Write-a-PPM-file/Crystal/bitmap-write-a-ppm-file-1.cr @@ -0,0 +1,13 @@ +require "./pixmap" + +class Pixmap + def write_ppm (io) + io.print "P6\n# Visit Rosetta code!\n#{width} #{height}\n255\n" + @data.each do |c| + io.write_byte c.r + io.write_byte c.g + io.write_byte c.b + end + end + register_writer ".ppm", write_ppm +end diff --git a/Task/Bitmap-Write-a-PPM-file/Crystal/bitmap-write-a-ppm-file-2.cr b/Task/Bitmap-Write-a-PPM-file/Crystal/bitmap-write-a-ppm-file-2.cr new file mode 100644 index 0000000000..1e3919cea7 --- /dev/null +++ b/Task/Bitmap-Write-a-PPM-file/Crystal/bitmap-write-a-ppm-file-2.cr @@ -0,0 +1,14 @@ +require "./write_ppm" + +img = Pixmap.new 3, 2, Color::WHITE + +[[0xFF0000, 0x00FF00, 0x0000FF], + [0xFFFF00, 0x00FFFF, 0xFF00FF]].each_with_index do |row, y| + row.each_with_index do |color, x| + img[x, y] = Color.new color + end +end + +img.write "mini.ppm" + +File.read("mini.ppm").unsafe_byte_slice(0).hexdump(STDOUT) diff --git a/Task/Bitmap-Write-a-PPM-file/Delphi/bitmap-write-a-ppm-file.delphi b/Task/Bitmap-Write-a-PPM-file/Delphi/bitmap-write-a-ppm-file.pas similarity index 100% rename from Task/Bitmap-Write-a-PPM-file/Delphi/bitmap-write-a-ppm-file.delphi rename to Task/Bitmap-Write-a-PPM-file/Delphi/bitmap-write-a-ppm-file.pas diff --git a/Task/Bitmap-Write-a-PPM-file/Euphoria/bitmap-write-a-ppm-file-1.euphoria b/Task/Bitmap-Write-a-PPM-file/Euphoria/bitmap-write-a-ppm-file-1.eu similarity index 100% rename from Task/Bitmap-Write-a-PPM-file/Euphoria/bitmap-write-a-ppm-file-1.euphoria rename to Task/Bitmap-Write-a-PPM-file/Euphoria/bitmap-write-a-ppm-file-1.eu diff --git a/Task/Bitmap-Write-a-PPM-file/Euphoria/bitmap-write-a-ppm-file-2.euphoria b/Task/Bitmap-Write-a-PPM-file/Euphoria/bitmap-write-a-ppm-file-2.eu similarity index 100% rename from Task/Bitmap-Write-a-PPM-file/Euphoria/bitmap-write-a-ppm-file-2.euphoria rename to Task/Bitmap-Write-a-PPM-file/Euphoria/bitmap-write-a-ppm-file-2.eu diff --git a/Task/Bitmap-Write-a-PPM-file/FBSL/bitmap-write-a-ppm-file.fbsl b/Task/Bitmap-Write-a-PPM-file/FBSL/bitmap-write-a-ppm-file.fbsl index 2c7f0057d2..6db33e290f 100644 --- a/Task/Bitmap-Write-a-PPM-file/FBSL/bitmap-write-a-ppm-file.fbsl +++ b/Task/Bitmap-Write-a-PPM-file/FBSL/bitmap-write-a-ppm-file.fbsl @@ -12,12 +12,12 @@ DIM head = @ppmdata + STRLEN, tail = @FILEGET + FILELEN - breadth * 3 - 2 ' Star ppmdata = ppmheader ' Copy PPM file header WHILE tail >= @FILEGET + bmpblob ' Flip upside down - FOR DIM w = 0 TO (breadth - 1) * 3 STEP 3 - POKE(head + 0 + w, CHR(PEEK(tail + 2 + w, 1))) ' Swap R - POKE(head + 1 + w, CHR(PEEK(tail + 1 + w, 1))) ' Keep G - POKE(head + 2 + w, CHR(PEEK(tail + 0 + w, 1))) ' Swap B - NEXT - INCR(head, breadth * 3): DECR(tail, breadth * 3) ' Next scanline + FOR DIM w = 0 TO (breadth - 1) * 3 STEP 3 + POKE(head + 0 + w, CHR(PEEK(tail + 2 + w, 1))) ' Swap R + POKE(head + 1 + w, CHR(PEEK(tail + 1 + w, 1))) ' Keep G + POKE(head + 2 + w, CHR(PEEK(tail + 0 + w, 1))) ' Swap B + NEXT + INCR(head, breadth * 3): DECR(tail, breadth * 3) ' Next scanline WEND FILEPUT(FILEOPEN(ppmout, BINARY_NEW), ppmdata): FILECLOSE(FILEOPEN) diff --git a/Task/Bitmap-Write-a-PPM-file/FreeBASIC/bitmap-write-a-ppm-file.basic b/Task/Bitmap-Write-a-PPM-file/FreeBASIC/bitmap-write-a-ppm-file.basic new file mode 100644 index 0000000000..d658dc3b0d --- /dev/null +++ b/Task/Bitmap-Write-a-PPM-file/FreeBASIC/bitmap-write-a-ppm-file.basic @@ -0,0 +1,37 @@ +Dim As Integer ancho, alto +ancho = 150: alto = 200 +Dim As Integer x, y ' width, height +Dim As Ulong kolor +Screenres ancho, alto, 32 + +' Draw circles +Screenlock +Circle (75, 100), 50, Rgb(255, 0, 0),,,, F +Circle (75, 100), 35, Rgb(0, 255, 0),,,, F +Circle (75, 100), 20, Rgb(0, 0, 255),,,, F +Screenunlock + +' Open PPM file to write +Dim As Integer ff = Freefile +Open "example.ppm" For Binary As #ff +If Err > 0 Then Print "Error opening output file": End + +' Create PPM file header +Print #ff, "P6" +Print #ff, "# Created using FreeBASIC" +Print #ff, ancho & " " & alto +Print #ff, "255" + +' Write image data to PPM file +For y = 0 To alto - 1 + For x = 0 To ancho - 1 + kolor = Point(x, y) + Put #ff, , Cbyte(kolor Shr 8) ' Green + Put #ff, , Cbyte(kolor) ' Blue + Put #ff, , Cbyte(kolor Shr 16) ' Red + Next +Next + +Close #ff + +Sleep diff --git a/Task/Bitmap-Write-a-PPM-file/Julia/bitmap-write-a-ppm-file.julia b/Task/Bitmap-Write-a-PPM-file/Julia/bitmap-write-a-ppm-file.jl similarity index 100% rename from Task/Bitmap-Write-a-PPM-file/Julia/bitmap-write-a-ppm-file.julia rename to Task/Bitmap-Write-a-PPM-file/Julia/bitmap-write-a-ppm-file.jl diff --git a/Task/Bitmap-Write-a-PPM-file/Kotlin/bitmap-write-a-ppm-file.kotlin b/Task/Bitmap-Write-a-PPM-file/Kotlin/bitmap-write-a-ppm-file.kts similarity index 100% rename from Task/Bitmap-Write-a-PPM-file/Kotlin/bitmap-write-a-ppm-file.kotlin rename to Task/Bitmap-Write-a-PPM-file/Kotlin/bitmap-write-a-ppm-file.kts diff --git a/Task/Bitmap-Write-a-PPM-file/M2000-Interpreter/bitmap-write-a-ppm-file-1.m2000 b/Task/Bitmap-Write-a-PPM-file/M2000-Interpreter/bitmap-write-a-ppm-file-1.m2000 index c2892cc958..b3c4b9607b 100644 --- a/Task/Bitmap-Write-a-PPM-file/M2000-Interpreter/bitmap-write-a-ppm-file-1.m2000 +++ b/Task/Bitmap-Write-a-PPM-file/M2000-Interpreter/bitmap-write-a-ppm-file-1.m2000 @@ -50,26 +50,28 @@ Module Checkit { Return Image1, 0:=Image$ } Else Error "Can't Copy Image" } - Export2File=Lambda Image1, x, y (f) -> { + Export2File=Lambda Image1, x, y, r=len(rasterline) (f) -> { \\ use this between open and close Print #f, "P3" Print #f,"# Created using M2000 Interpreter" Print #f, x;" ";y Print #f, 255 x2=x-1 - where=24 - For y1= 0 to y-1 { + For y1= y-1 to 0 { a$="" - For x1=0 to x2 { - Print #f, a$;Eval(Image1, where +2 as byte);" "; + where=24+r*y1 + x1=0 + Print #f, Eval(Image1, where +2 as byte);" "; + Print #f, Eval(Image1, where+1 as byte);" "; + Print #f, Eval(Image1, where as byte); + where+=3 + For x1=1 to x2 { + Print #f, " ";Eval(Image1, where +2 as byte);" "; Print #f, Eval(Image1, where+1 as byte);" "; Print #f, Eval(Image1, where as byte); where+=3 - a$=" " } Print #f - m=where mod 4 - if m<>0 then where+=4-m } } Group Bitmap { @@ -81,31 +83,10 @@ Module Checkit { } =Bitmap } - A=Bitmap(10, 10) Call A.SetPixel(5,5, color(128,0,255)) Open "A2.PPM" for Output as #F Call A.ToFile(F) Close #f - ' is the same as this one - Try { - Open "A.PPM" for Output as #F - Print #f, "P3" - Print #f,"# Created using M2000 Interpreter" - Print #f, 10;" ";10 - Print #f, 255 - For y=10-1 to 0 { - a$="" - For x=0 to 10-1 { - rgb=-A.GetPixel(x, y) - Print #f, a$;Binary.And(rgb, 0xFF); " "; - Print #f, Binary.And(Binary.Shift(rgb, -8), 0xFF); " "; - Print #f, Binary.Shift(rgb, -16); - a$=" " - } - Print #f - } - Close #f - } } Checkit diff --git a/Task/Bitmap-Write-a-PPM-file/M2000-Interpreter/bitmap-write-a-ppm-file-2.m2000 b/Task/Bitmap-Write-a-PPM-file/M2000-Interpreter/bitmap-write-a-ppm-file-2.m2000 index f65d2af1b7..0cc430b1ff 100644 --- a/Task/Bitmap-Write-a-PPM-file/M2000-Interpreter/bitmap-write-a-ppm-file-2.m2000 +++ b/Task/Bitmap-Write-a-PPM-file/M2000-Interpreter/bitmap-write-a-ppm-file-2.m2000 @@ -1,177 +1,180 @@ -Module PPMbinaryP6 { - If Version<9.4 then 1000 - If Version=9.4 Then if Revision<19 then 1000 - Module Checkit { - Function Bitmap { - def x as long, y as long - If match("NN") then { - Read x, y - } else.if Match("N") Then { - E$="Not a ppm file" - Read f as long - buffer whitespace as byte - if not Eof(f) then { - get #f, whitespace : iF eof(f) then Error E$ - P6$=eval$(whitespace) - get #f, whitespace : iF eof(f) then Error E$ - P6$+=eval$(whitespace) - def boolean getW=true, getH=true, getV=true - def long v - \\ str$("P6") has 2 bytes. "P6" has 4 bytes - If p6$=str$("P6") Then { - do { - get #f, whitespace - if Eval$(whitespace)=str$("#") then { - do { - iF eof(f) then Error E$ - get #f, whitespace - } until eval(whitespace)=10 - } else { - select case eval(whitespace) - case 32, 9, 13, 10 - { - if getW and x<>0 then { - getW=false - } else.if getH and y<>0 then { - getH=false - } else.if getV and v<>0 then { - getV=false - } - } - case 48 to 57 - { - if getW then { - x*=10 - x+=eval(whitespace, 0)-48 - } else.if getH then { - y*=10 - y+=eval(whitespace, 0)-48 - } else.if getV then { - v*=10 - v+=eval(whitespace, 0)-48 - } - } - End Select - } - iF eof(f) then Error E$ - } until getV=false - } else Error "Not a P6 ppm" - } - } else Error "No proper arguments" - if x<1 or y<1 then Error "Wrong dimensions" - structure rgb { - red as byte - green as byte - blue as byte - } - m=len(rgb)*x mod 4 - if m>0 then m=4-m ' add some bytes to raster line - m+=len(rgb) *x - Structure rasterline { - { - pad as byte*m - } - \\ union pad+hline - hline as rgb*x - } - \\ we use union linesB and lines - \\ so we can address linesb as bytes - Structure Raster { - magic as integer*4 - w as integer*4 - h as integer*4 - { - linesB as byte*len(rasterline)*y - } - lines as rasterline*y - } - Buffer Clear Image1 as Raster - \\ 24 chars as header to be used from bitmap render build in functions - Return Image1, 0!magic:="cDIB", 0!w:=Hex$(x,2), 0!h:=Hex$(y, 2) - \\ fill white (all 255) - \\ Str$(string) convert to ascii, so we get all characters from words width to byte width - if not valid(f) then Return Image1, 0!lines:=Str$(String$(chrcode$(255), Len(rasterline)*y)) - Buffer Clear Pad as Byte*4 - SetPixel=Lambda Image1, Pad,aLines=Len(Raster)-Len(Rasterline), blines=-Len(Rasterline) (x, y, c) ->{ - where=alines+3*x+blines*y - if c>0 then c=color(c) - c-! - Return Pad, 0:=c as long - Return Image1, 0!where:=Eval(Pad, 2) as byte, 0!where+1:=Eval(Pad, 1) as byte, 0!where+2:=Eval(Pad, 0) as byte - } - GetPixel=Lambda Image1,aLines=Len(Raster)-Len(Rasterline), blines=-Len(Rasterline) (x,y) ->{ - where=alines+3*x+blines*y - =color(Eval(image1, where+2 as byte), Eval(image1, where+1 as byte), Eval(image1, where as byte)) - } - StrDib$=Lambda$ Image1, Raster -> { - =Eval$(Image1, 0, Len(Raster)) - } - CopyImage=Lambda Image1 (image$) -> { - if left$(image$,12)=Eval$(Image1, 0, 24 ) Then { - Return Image1, 0:=Image$ - } Else Error "Can't Copy Image" - } - Export2File=Lambda Image1, x, y (f) -> { - \\ use this between open and close - Print #f, "P6";chr$(10); - Print #f,"# Created using M2000 Interpreter";chr$(10); - Print #f, x;" ";y;" 255";chr$(10); - x2=x-1 - where=0 - Buffer pad as byte*3 - For y1= 0 to y-1 { - For x1=0 to x2 { - \\ use linesB which is array of bytes - Return pad, 0:=eval$(image1, 0!linesB!where, 3) - Push Eval(pad, 2) - Return pad, 2:=Eval(pad, 0), 0:=Number - Put #f, pad - where+=3 - } - m=where mod 4 - if m<>0 then where+=4-m - } - } - if valid(F) then { - x0=x-1 - where=0 - Buffer Pad1 as byte*3 - For y1=y-1 to 0 { - For x1=0 to x0 { - Get #f, Pad1 ' Read binary - \\ reverse rgb - Push Eval(pad1, 2) - Return pad1, 2:=Eval(pad1, 0), 0:=Number - Return Image1, 0!linesB!where:=Eval$(Pad1) - where+=3 +Module P6 { + Function Bitmap { + def x as long, y as long, Import as boolean + If match("NN") then + Read x, y + else.if Match("N") Then + \\ is a file? + Read f as long + byte whitespace[0] + if not Eof(f) then + get #f, whitespace :P6$=chr$(whitespace[0]) + get #f, whitespace : P6$+=chr$(whitespace[0]) + boolean getW=true, getH=true, getV=true + long v + If p6$="P6" Then + do + get #f, whitespace + select case whitespace[0] + case 35 + {do get #f, whitespace + until whitespace[0]=10 } - m=where mod 4 - if m<>0 then where+=4-m - } - } - Group Bitmap { - SetPixel=SetPixel - GetPixel=GetPixel - Image$=StrDib$ - Copy=CopyImage - ToFile=Export2File - } - =Bitmap + case 32, 9, 13, 10 + { if getW and x<>0 then + getW=false + else.if getH and y<>0 then + getH=false + else.if getV and v<>0 then + getV=false + end if + } + case 48 to 57 + {if getW then + x*=10 + x+=whitespace[0]-48 + else.if getH then + y*=10 + y+=whitespace[0]-48 + else.if getV then + v*=10 + v+=whitespace[0]-48 + end if + } + End Select + iF eof(f) then Error "Not a ppm file" + until getV=false + else + Error "Not a P6 ppm" + end if + Import=True + end if + else + Error "No proper arguments" + end if + if x<1 or y<1 then Error "Wrong dimensions" + structure rgb { + red as byte + green as byte + blue as byte } - A=Bitmap(10, 10) - Call A.SetPixel(5,5, color(128,0,255)) - Open "A.PPM" for Output as #F - Call A.ToFile(F) - Close #f - - Print "Saved" - Open "A.PPM" for Input as #F - C=Bitmap(f) - Copy 400*twipsx,200*twipsy use C.Image$() - Close #f - } - Checkit - End - 1000 Error "Need Version 9.4, Revision 19 or higher" + m=len(rgb)*x mod 4 + if m>0 then m=4-m ' add some bytes to raster line + m+=len(rgb) *x + Structure rasterline { + { + pad as byte*m + } + hline as rgb*x + } + Structure Raster { + magic as integer*4 + w as integer*4 + h as integer*4 + { + linesB as byte*len(rasterline)*y + } + lines as rasterline*y + } + Buffer Clear Image1 as Raster + Return Image1, 0!magic:="cDIB", 0!w:=Hex$(x,2), 0!h:=Hex$(y, 2) + if not Import then Return Image1, 0!lines:=Str$(String$(chrcode$(255), Len(rasterline)*y)) + Buffer Clear Pad as Byte*4 + SetPixel=Lambda Image1, Pad, aLines=Len(Raster)-Len(Rasterline), blines=-Len(Rasterline) (x, y, c) ->{ + where=alines+3*x+blines*y + if c>0 then c=color(c) + c-! + Return Pad, 0:=c as long + Return Image1, 0!where:=Eval(Pad, 2) as byte, 0!where+1:=Eval(Pad, 1) as byte, 0!where+2:=Eval(Pad, 0) as byte + } + GetPixel=Lambda Image1,aLines=Len(Raster)-Len(Rasterline), blines=-Len(Rasterline) (x,y) ->{ + where=alines+3*x+blines*y + =color(Eval(image1, where+2 as byte), Eval(image1, where+1 as byte), Eval(image1, where as byte)) + } + StrDib$=Lambda$ Image1, Raster -> { + =Eval$(Image1, 0, Len(Raster)) + } + CopyImage=Lambda Image1 (image$) -> { + if left$(image$,12)=Eval$(Image1, 0, 24 ) Then { + Return Image1, 0:=Image$ + } Else Error "Can't Copy Image" + } + Export2File=Lambda Image1, x, y (f) -> { + Print #f, "P6";chr$(10);"# Created using M2000 Interpreter";chr$(10); + Print #f, x;" ";y;" 255";chr$(10); + x2=x-1 : where=0 + x0=x*3 + structure rgbP6 { + r as byte + g as byte + b as byte + } + buffer Pad as rgbP6*x*y + For y1=y-1 to 0 { + Return pad, x*y1:=eval$(image1, 0!linesB!where, x0) + where+=x0 + m=where mod 4 : if m<>0 then where+=4-m + } + For x1=0 to x*y-1 { + Push Eval(pad, x1!b) : Return pad, x1!b:=Eval(pad, x1!r), x1!r:=Number + } + Put #f, pad + } + if Import then { + x0=x-1 : where=0 + structure rgbP6 { + r as byte + g as byte + b as byte + } + buffer Pad1 as rgbP6*x*y + Get #f, Pad1 + For x1=0 to x*y-1 { + Push Eval(pad1, x1!b) : Return pad1, x1!b:=Eval(pad1, x1!r), x1!r:=Number + } + x1=x*3 + For y1=y-1 to 0 { + Return Image1, 0!linesB!where:=Eval$(Pad1, y1*x, x1) + where+=3*(x0+1) + m=where mod 4 : if m<>0 then where+=4-m + } + } + Group Bitmap { + SetPixel=SetPixel + GetPixel=GetPixel + Image$=StrDib$ + Copy=CopyImage + ToFile=Export2File + } + =Bitmap + } + A=Bitmap(150,100) + For i=0 to 98 { + Call A.SetPixel(i, i, 0) + Call A.SetPixel(99, i, 0) + } + Call A.SetPixel(i,i,0) + Copy 200*twipsx, 100*twipsy use A.Image$() + Profiler + Open "a.ppm" for output as #F + Call A.tofile(f) + Close #f + Print Filelen("a.ppm") + Print Timecount/1000;"sec" + Profiler + exit + Image A.Image$() Export "a.jpg", 100 ' per cent quality + Print Filelen("a.jpg") + Image A.Image$() Export "a1.jpg", 10 ' per cent quality + Print Filelen("a1.jpg") + Image A.Image$() Export "a.bmp" + Print Filelen("a.bmp") ' no compression + Print Timecount/1000;"sec" + Move 5000,5000 ' twips + Image "a.jpg" + Move 5000,8000 + Image "a1.jpg" + Move 8000, 5000 + Image "a.bmp" } -PPMbinaryP6 +p6 diff --git a/Task/Bitmap-Write-a-PPM-file/Oz/bitmap-write-a-ppm-file.oz b/Task/Bitmap-Write-a-PPM-file/Oz/bitmap-write-a-ppm-file.oz index dca6a5e19e..c05f456d0a 100644 --- a/Task/Bitmap-Write-a-PPM-file/Oz/bitmap-write-a-ppm-file.oz +++ b/Task/Bitmap-Write-a-PPM-file/Oz/bitmap-write-a-ppm-file.oz @@ -12,28 +12,28 @@ define F = {New Open.file init(name:Filename flags:[write create truncate binary])} proc {WriteColor8 color(R G B)} - {F write(vs:[R G B])} + {F write(vs:[R G B])} end fun {ToBytes C} - [C div 0x100 C mod 0x100] + [C div 0x100 C mod 0x100] end proc {WriteColor16 color(R G B)} - {F write(vs:{Flatten {Map [R G B] ToBytes}})} + {F write(vs:{Flatten {Map [R G B] ToBytes}})} end MaxCol = {Bitmap.maxValue B} MaxVal#Writer = if MaxCol =< 0xff then 0xff#WriteColor8 - else 0xffff#WriteColor16 - end + else 0xffff#WriteColor16 + end Header = "P6\n"#W#" "#H#" "#MaxVal#"\n" in try - {F write(vs:Header)} - {Bitmap.forAllPixels B Writer} + {F write(vs:Header)} + {Bitmap.forAllPixels B Writer} finally - {F close} + {F close} end end end diff --git a/Task/Bitmap-Write-a-PPM-file/Prolog/bitmap-write-a-ppm-file-1.pro b/Task/Bitmap-Write-a-PPM-file/Prolog/bitmap-write-a-ppm-file-1.pro index c10545d911..7b7fd228ad 100644 --- a/Task/Bitmap-Write-a-PPM-file/Prolog/bitmap-write-a-ppm-file-1.pro +++ b/Task/Bitmap-Write-a-PPM-file/Prolog/bitmap-write-a-ppm-file-1.pro @@ -1,16 +1,16 @@ :- module(bitmapIO, [ - write_ppm_p6/2]). + write_ppm_p6/2]). :- use_module(library(lists)). %write_ppm_p6(File,Bitmap) write_ppm_p6(Filename,[[X,Y],Pixels]):- - open(Filename,write,Output,[encoding(octet)]), - %write p6 header - writeln(Output, 'P6'), - atomic_list_concat([X, Y], ' ', Dimensions), - writeln(Output, Dimensions), - writeln(Output, '255'), - %write bytes - maplist(maplist(maplist(put_byte(Output))),Pixels), - close(Output). + open(Filename,write,Output,[encoding(octet)]), + %write p6 header + writeln(Output, 'P6'), + atomic_list_concat([X, Y], ' ', Dimensions), + writeln(Output, Dimensions), + writeln(Output, '255'), + %write bytes + maplist(maplist(maplist(put_byte(Output))),Pixels), + close(Output). diff --git a/Task/Bitmap-Write-a-PPM-file/Prolog/bitmap-write-a-ppm-file-2.pro b/Task/Bitmap-Write-a-PPM-file/Prolog/bitmap-write-a-ppm-file-2.pro index 6c3b784711..63e26ab585 100644 --- a/Task/Bitmap-Write-a-PPM-file/Prolog/bitmap-write-a-ppm-file-2.pro +++ b/Task/Bitmap-Write-a-PPM-file/Prolog/bitmap-write-a-ppm-file-2.pro @@ -2,6 +2,6 @@ :- use_module(bitmapIO). write :- - new_bitmap(AllBlack,[50,50],[0,0,0]), - set_pixel0(AlmostAllBlack,AllBlack,[25,25],[255,255,255]), - write_ppm_p6('AlmostAllBlack.ppm',AlmostAllBlack). + new_bitmap(AllBlack,[50,50],[0,0,0]), + set_pixel0(AlmostAllBlack,AllBlack,[25,25],[255,255,255]), + write_ppm_p6('AlmostAllBlack.ppm',AlmostAllBlack). diff --git a/Task/Bitmap-Write-a-PPM-file/Raku/bitmap-write-a-ppm-file.raku b/Task/Bitmap-Write-a-PPM-file/Raku/bitmap-write-a-ppm-file.raku index 3efa08e181..7739ea243e 100644 --- a/Task/Bitmap-Write-a-PPM-file/Raku/bitmap-write-a-ppm-file.raku +++ b/Task/Bitmap-Write-a-PPM-file/Raku/bitmap-write-a-ppm-file.raku @@ -7,9 +7,9 @@ class Bitmap { @!data = $p.clone xx ($!width*$!height) } method pixel( - $i where ^$!width, - $j where ^$!height - --> Pixel + $i where ^$!width, + $j where ^$!height + --> Pixel ) is rw { @!data[$i*$!height + $j] } method data { @!data } @@ -17,8 +17,8 @@ class Bitmap { role PPM { method P6 returns Blob { - "P6\n{self.width} {self.height}\n255\n".encode('ascii') - ~ Blob.new: flat map { .R, .G, .B }, self.data + "P6\n{self.width} {self.height}\n255\n".encode('ascii') + ~ Blob.new: flat map { .R, .G, .B }, self.data } } diff --git a/Task/Bitmap-Write-a-PPM-file/Rebol/bitmap-write-a-ppm-file.rebol b/Task/Bitmap-Write-a-PPM-file/Rebol/bitmap-write-a-ppm-file.rebol new file mode 100644 index 0000000000..fd0ef3b840 --- /dev/null +++ b/Task/Bitmap-Write-a-PPM-file/Rebol/bitmap-write-a-ppm-file.rebol @@ -0,0 +1,57 @@ +Rebol [ + title: "Rosetta code: Bitmap/Write a PPM file" + file: %Bitmap-Write_a_PPM_file.r3 + url: https://rosettacode.org/wiki/Bitmap/Write_a_PPM_file +] + +to-ppm: function [ + "Converts an image to a PPM (Portable Pixmap) format string" + ;; This function is using padding in the output. + ;; In the real life usage it could be removed. + img [image!] +][ + ;; Extract image dimensions as integers + wide: to integer! img/size/x + high: to integer! img/size/y + + ;; Build the PPM header: + ;; P3 = plain RGB text format + ;; wide/high = pixel dimensions + ;; 255 = max color value (8-bit per channel) + out: rejoin ["P3^/" wide SP high "^/255^/"] + + ;; Iterate over every pixel in the image + n: 0 ;; Pixel counter, used to detect end of each row + foreach clr img [ + ++ n + ;; Append R, G, B channel values, right-aligned in fixed-width columns + ;; pad ... -5/-4 = right-align in field of 5 or 4 characters + append out ajoin [ + pad clr/1 -5 ;R + pad clr/2 -4 ;G + pad clr/3 -4 ;B + ;; After the last pixel in each row, insert a newline + if zero? n % wide [ newline ] + ] + ] + out +] + +; --- Demo --- +; Create a 2x2 image and set pixels 1 (top-left) and 4 (bottom-right) to black +img: make image! 2x2 +img/1: img/4: black +print to-ppm img + +;; It is also possible to register a PPM codec +register-codec [ + name: 'ppm + type: 'image + title: "Portable Pixmap (PPM) File Format" + suffixes: [%.ppm] + encode: :to-ppm +] +;; Then use it as: +ppm-data: encode 'ppm img +;; or +save %image.ppm img diff --git a/Task/Bitmap-Write-a-PPM-file/Rust/bitmap-write-a-ppm-file.rust b/Task/Bitmap-Write-a-PPM-file/Rust/bitmap-write-a-ppm-file.rs similarity index 100% rename from Task/Bitmap-Write-a-PPM-file/Rust/bitmap-write-a-ppm-file.rust rename to Task/Bitmap-Write-a-PPM-file/Rust/bitmap-write-a-ppm-file.rs diff --git a/Task/Bitmap-Write-a-PPM-file/Scheme/bitmap-write-a-ppm-file-1.ss b/Task/Bitmap-Write-a-PPM-file/Scheme/bitmap-write-a-ppm-file-1.scm similarity index 100% rename from Task/Bitmap-Write-a-PPM-file/Scheme/bitmap-write-a-ppm-file-1.ss rename to Task/Bitmap-Write-a-PPM-file/Scheme/bitmap-write-a-ppm-file-1.scm diff --git a/Task/Bitmap-Write-a-PPM-file/Scheme/bitmap-write-a-ppm-file-2.ss b/Task/Bitmap-Write-a-PPM-file/Scheme/bitmap-write-a-ppm-file-2.scm similarity index 100% rename from Task/Bitmap-Write-a-PPM-file/Scheme/bitmap-write-a-ppm-file-2.ss rename to Task/Bitmap-Write-a-PPM-file/Scheme/bitmap-write-a-ppm-file-2.scm diff --git a/Task/Bitmap-Write-a-PPM-file/Stata/bitmap-write-a-ppm-file.stata b/Task/Bitmap-Write-a-PPM-file/Stata/bitmap-write-a-ppm-file.stata index 62077b718a..23beb00d54 100644 --- a/Task/Bitmap-Write-a-PPM-file/Stata/bitmap-write-a-ppm-file.stata +++ b/Task/Bitmap-Write-a-PPM-file/Stata/bitmap-write-a-ppm-file.stata @@ -1,16 +1,16 @@ mata void writeppm(name, r, g, b) { - n = rows(r) - p = cols(r) - f = fopen(name, "w") - fput(f, "P3") - fput(f, strofreal(p) + " " + strofreal(n) + " 255") - for (i = 1; i <= n; i++) { - for (j = 1; j <= p; j++) { - fput(f, strofreal(r[i,j]) + " " + strofreal(g[i,j]) + " " + strofreal(b[i,j])) - } - } - fclose(f) + n = rows(r) + p = cols(r) + f = fopen(name, "w") + fput(f, "P3") + fput(f, strofreal(p) + " " + strofreal(n) + " 255") + for (i = 1; i <= n; i++) { + for (j = 1; j <= p; j++) { + fput(f, strofreal(r[i,j]) + " " + strofreal(g[i,j]) + " " + strofreal(b[i,j])) + } + } + fclose(f) } r = J(1, 6, (0::5) * 51) diff --git a/Task/Bitmap-Write-a-PPM-file/Yabasic/bitmap-write-a-ppm-file.basic b/Task/Bitmap-Write-a-PPM-file/Yabasic/bitmap-write-a-ppm-file.basic index 3d5929176a..9f907661eb 100644 --- a/Task/Bitmap-Write-a-PPM-file/Yabasic/bitmap-write-a-ppm-file.basic +++ b/Task/Bitmap-Write-a-PPM-file/Yabasic/bitmap-write-a-ppm-file.basic @@ -18,12 +18,12 @@ fn = open("exmaple.PPM", "wb") print #fn header$ for x = 0 to hei - 1 - for y = 0 to wid - 1 - c$ = right$(getbit$(y, x, y, x), 6) - poke #fn, dec(left$(c$, 2)) - poke #fn, dec(right$(c$, 2)) - poke #fn, dec(mid$(c$, 3, 2)) - next y + for y = 0 to wid - 1 + c$ = right$(getbit$(y, x, y, x), 6) + poke #fn, dec(left$(c$, 2)) + poke #fn, dec(right$(c$, 2)) + poke #fn, dec(mid$(c$, 3, 2)) + next y next x poke #fn, asc("\n") diff --git a/Task/Bitmap/11l/bitmap.11l b/Task/Bitmap/11l/bitmap.11l index 1c27ab573c..66ed317106 100644 --- a/Task/Bitmap/11l/bitmap.11l +++ b/Task/Bitmap/11l/bitmap.11l @@ -1,13 +1,4 @@ -T Colour - Byte r, g, b - - F (r, g, b) - .r = r - .g = g - .b = b - - F ==(other) - R .r == other.r & .g == other.g & .b == other.b +T Colour = Vec3b V black = Colour(0, 0, 0) V white = Colour(255, 255, 255) diff --git a/Task/Bitmap/ALGOL-68/bitmap-1.alg b/Task/Bitmap/ALGOL-68/bitmap-1.alg deleted file mode 100644 index 896165161a..0000000000 --- a/Task/Bitmap/ALGOL-68/bitmap-1.alg +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- # - -MODE PIXEL = STRUCT(#SHORT# BITS red,green,blue); -MODE POINT = STRUCT(INT x,y); - -MODE IMAGE = [0,0]PIXEL; # instance attributes # - -MODE CLASSIMAGE = STRUCT ( # class attributes # - PIXEL black, red, green, blue, white, - PROC (REF IMAGE)REF IMAGE init, - PROC (REF IMAGE, PIXEL)VOID fill, - PROC (REF IMAGE)VOID print, -# virtual: # - REF PROC (REF IMAGE, POINT, POINT, PIXEL)VOID line, - REF PROC (REF IMAGE, POINT, INT, PIXEL)VOID circle, - REF PROC (REF IMAGE, POINT, POINT, POINT, POINT, PIXEL, UNION(INT, VOID))VOID cubic bezier -); - -CLASSIMAGE class image = ( - # black = # (#SHORTEN# 16r00, #SHORTEN# 16r00, #SHORTEN# 16r00), - # red = # (#SHORTEN# 16rff, #SHORTEN# 16r00, #SHORTEN# 16r00), - # green = # (#SHORTEN# 16r00, #SHORTEN# 16rff, #SHORTEN# 16r00), - # blue = # (#SHORTEN# 16r00, #SHORTEN# 16r00, #SHORTEN# 16rff), - # white = # (#SHORTEN# 16rff, #SHORTEN# 16rff, #SHORTEN# 16rff), - # PROC init = # (REF IMAGE self)REF IMAGE: - BEGIN - (fill OF class image)(self, black OF class image); - self - END, - - # PROC fill = # (REF IMAGE self, PIXEL color)VOID: - FOR x FROM 1 LWB self TO 1 UPB self DO - FOR y FROM 2 LWB self TO 2 UPB self DO - self[x,y] := color - OD - OD, - # PROC print = # (REF IMAGE self)VOID: - printf(($n(UPB self)(3(16r2d))l$, self)), -# virtual: # - # REF PROC line = # LOC PROC (REF IMAGE, POINT, POINT, PIXEL)VOID, - # REF PROC circle = # LOC PROC (REF IMAGE, POINT, INT, PIXEL)VOID, - # REF PROC cubic bezier = # LOC PROC (REF IMAGE, POINT, POINT, POINT, POINT, PIXEL, UNION(INT, VOID))VOID -); - -OP CLASSOF = (IMAGE image)CLASSIMAGE: class image; -OP INIT = (REF IMAGE image)REF IMAGE: (init OF (CLASSOF image))(image); - -SKIP diff --git a/Task/Bitmap/ALGOL-68/bitmap-2.alg b/Task/Bitmap/ALGOL-68/bitmap.alg similarity index 100% rename from Task/Bitmap/ALGOL-68/bitmap-2.alg rename to Task/Bitmap/ALGOL-68/bitmap.alg diff --git a/Task/Bitmap/ARM-Assembly/bitmap.arm b/Task/Bitmap/ARM-Assembly/bitmap.arm index a10f4f2666..a547d1f0c9 100644 --- a/Task/Bitmap/ARM-Assembly/bitmap.arm +++ b/Task/Bitmap/ARM-Assembly/bitmap.arm @@ -1,51 +1,51 @@ Bitmap_FloodFill: - ;input: - ;r0 = color to fill screen with (15-bit color) - STMFD sp!,{r0-r12,lr} - - MOV R2,#160 - MOV R4,#0x06000000 + ;input: + ;r0 = color to fill screen with (15-bit color) + STMFD sp!,{r0-r12,lr} + + MOV R2,#160 + MOV R4,#0x06000000 outerloop_floodfill: - MOV R1,#240 ;restore inner loop counter + MOV R1,#240 ;restore inner loop counter innerloop_floodfill: - strH r0,[r4] - add r4,r4,#2 ;next pixel - subs r1,r1,#1 ;decrement loop counter - bne innerloop_floodfill - subs r2,r2,#1 - bne outerloop_floodfill - - LDMFD sp!,{r0-r12,pc} - + strH r0,[r4] + add r4,r4,#2 ;next pixel + subs r1,r1,#1 ;decrement loop counter + bne innerloop_floodfill + subs r2,r2,#1 + bne outerloop_floodfill + + LDMFD sp!,{r0-r12,pc} + Bitmap_Locate: ;given x and y coordinates, offsets vram addr to that pixel on screen. - ;input: - ;r0 = x - ;r1 = y - ;output: r2 = vram area - STMFD sp!,{r4-r12,lr} - mov r2,#0x06000000 ;vram base + ;input: + ;r0 = x + ;r1 = y + ;output: r2 = vram area + STMFD sp!,{r4-r12,lr} + mov r2,#0x06000000 ;vram base + + + mov r4,#240*2 ;240 pixels across, 2 bytes per pixel + mul r1,r4,r1 + add r2,r2,r1 ;add y*480 + add r2,r2,r0,lsl #1 ;add x*2 + LDMFD sp!,{r4-r12,pc} - - mov r4,#240*2 ;240 pixels across, 2 bytes per pixel - mul r1,r4,r1 - add r2,r2,r1 ;add y*480 - add r2,r2,r0,lsl #1 ;add x*2 - LDMFD sp!,{r4-r12,pc} - Bitmap_StorePixel: - ;input: r3 = color - ;r0 = x - ;r1 = y - bl Bitmap_Locate - strH r3,[r2] ;store the pixel color in video memory - bx lr - + ;input: r3 = color + ;r0 = x + ;r1 = y + bl Bitmap_Locate + strH r3,[r2] ;store the pixel color in video memory + bx lr + Bitmap_GetPixel: ;retrieves the color of the pixel at [r2] and stores its color value in r3. - ;r0 = x - ;r1 = y - ;output in r3 - bl Bitmap_Locate - ldrH r3,[r2] - bx lr + ;r0 = x + ;r1 = y + ;output in r3 + bl Bitmap_Locate + ldrH r3,[r2] + bx lr diff --git a/Task/Bitmap/Ada/bitmap-1.ada b/Task/Bitmap/Ada/bitmap-1.adb similarity index 100% rename from Task/Bitmap/Ada/bitmap-1.ada rename to Task/Bitmap/Ada/bitmap-1.adb diff --git a/Task/Bitmap/Ada/bitmap-2.ada b/Task/Bitmap/Ada/bitmap-2.adb similarity index 100% rename from Task/Bitmap/Ada/bitmap-2.ada rename to Task/Bitmap/Ada/bitmap-2.adb diff --git a/Task/Bitmap/Ada/bitmap-3.ada b/Task/Bitmap/Ada/bitmap-3.adb similarity index 100% rename from Task/Bitmap/Ada/bitmap-3.ada rename to Task/Bitmap/Ada/bitmap-3.adb diff --git a/Task/Bitmap/AutoHotkey/bitmap.ahk b/Task/Bitmap/AutoHotkey/bitmap.ahk index 791a7d7bc8..2c8ccd888f 100644 --- a/Task/Bitmap/AutoHotkey/bitmap.ahk +++ b/Task/Bitmap/AutoHotkey/bitmap.ahk @@ -21,13 +21,13 @@ background := black if !BitmapType BitmapType := Object("fill", "Bitmap_Fill" - ,"write", "Bitmap_write_ppm3") + ,"write", "Bitmap_write_ppm3") - img := Object("width", width + img := Object("width", width ,"height", height , "base" , BitmapType) - img._SetCapacity(height) ; an array of rows + img._SetCapacity(height) ; an array of rows img.fill(background) Return img } diff --git a/Task/Bitmap/C/bitmap-1.c b/Task/Bitmap/C/bitmap-1.c index 44b484cea5..0ff4592b18 100644 --- a/Task/Bitmap/C/bitmap-1.c +++ b/Task/Bitmap/C/bitmap-1.c @@ -24,14 +24,14 @@ void fill_img(image img, color_component g, color_component b ); void put_pixel_unsafe( - image img, + image img, unsigned int x, unsigned int y, color_component r, color_component g, color_component b ); void put_pixel_clip( - image img, + image img, unsigned int x, unsigned int y, color_component r, diff --git a/Task/Bitmap/C/bitmap-2.c b/Task/Bitmap/C/bitmap-2.c index 22756034b3..b8b6167bce 100644 --- a/Task/Bitmap/C/bitmap-2.c +++ b/Task/Bitmap/C/bitmap-2.c @@ -31,7 +31,7 @@ void fill_img( } void put_pixel_unsafe( - image img, + image img, unsigned int x, unsigned int y, color_component r, @@ -46,7 +46,7 @@ void put_pixel_unsafe( } void put_pixel_clip( - image img, + image img, unsigned int x, unsigned int y, color_component r, diff --git a/Task/Bitmap/Clojure/bitmap.clj b/Task/Bitmap/Clojure/bitmap.clj index b447f4462c..d2bba0e538 100644 --- a/Task/Bitmap/Clojure/bitmap.clj +++ b/Task/Bitmap/Clojure/bitmap.clj @@ -1,5 +1,5 @@ (import '[java.awt Color Graphics Image] - '[java.awt.image BufferedImage]) + '[java.awt.image BufferedImage]) (defn blank-bitmap [width height] (BufferedImage. width height BufferedImage/TYPE_3BYTE_BGR)) diff --git a/Task/Bitmap/Common-Lisp/bitmap-2.lisp b/Task/Bitmap/Common-Lisp/bitmap-2.lisp index c50a1e9e8a..926118a474 100644 --- a/Task/Bitmap/Common-Lisp/bitmap-2.lisp +++ b/Task/Bitmap/Common-Lisp/bitmap-2.lisp @@ -59,11 +59,11 @@ (declare (type rgb-pixel-buffer buffer)) (declare (type rgb-pixel pixel)) (let* ((dimensions (array-dimensions buffer)) - (width (first dimensions)) - (height (second dimensions))) + (width (first dimensions)) + (height (second dimensions))) (loop :for y :of-type fixnum :upfrom 0 :below height :do (loop - :for x :of-type fixnum :upfrom 0 :below width - :do (setf (rgb-pixel buffer x y) pixel))) + :for x :of-type fixnum :upfrom 0 :below width + :do (setf (rgb-pixel buffer x y) pixel))) buffer)) diff --git a/Task/Bitmap/Crystal/bitmap-1.cr b/Task/Bitmap/Crystal/bitmap-1.cr new file mode 100644 index 0000000000..ad7043f36d --- /dev/null +++ b/Task/Bitmap/Crystal/bitmap-1.cr @@ -0,0 +1,105 @@ +record Color, r : UInt8, g : UInt8, b : UInt8 do + def self.new (r : Int32, g : Int32, b : Int32) + self.new r.to_u8, g.to_u8, b.to_u8 + end + + def self.new (hex : Int32) + self.new (hex >> 16 & 0xFF).to_u8, (hex >> 8 & 0xFF).to_u8, (hex & 0xFF).to_u8 + end + + def to_i + (r.to_i << 16) + (g.to_i << 8) + b.to_i + end + + def == (other : Color) + self.to_i == other.to_i + end + + WHITE = new 0xFFFFFF + BLACK = new 0x000000 + RED = new 0xFF0000 + GREEN = new 0x00FF00 + BLUE = new 0x0000FF +end + +class Pixmap + getter width, height + @data : Array(Color) + + def initialize (@width : Int32, @height : Int32, bg_color = Color::BLACK) + @data = Array.new(@width * @height, bg_color) + end + + def initialize (@width : Int32, @height : Int32, @data : Array(Color), copy = false) + raise "Wrong bounds" unless @width * @height == @data.size + @data = @data.dup if copy + end + + def initialize (other : self) + @width = other.@width + @height = other.@height + @data = other.@data.dup + end + + def fill (color) + @data.fill color + end + + def [] (x, y) + raise "Outside bounds" unless 0 <= x < @width && 0 <= y < @height + @data[y * @width + x] + end + + def []= (x, y, color) + if 0 <= x < @width && 0 <= y < @height + @data[y * @width + x] = color + end + color + end + + @@loaders = {} of String => Proc(IO, Pixmap) + @@writers = {} of String | Nil => Proc(Pixmap, IO, Nil) + + macro register_loader (ext, method) + @@loaders[{{ext}}] = ->(io : IO) { {{method.id}}(io) } + end + + macro register_writer (ext, method) + @@writers[{{ext}}] = ->(img : Pixmap, io : IO) { img.{{method.id}}(io) } + end + + def self.load (filename) + ext = File.extname(filename) + loader = @@loaders[ext]? || raise "No loader for '.#{ext}'" + File.open(filename) do |f| + loader.call(f) + end + end + + def write (filename_or_io : Path | String | IO) + if filename_or_io.is_a?(IO) + writer = @@writers[nil]? || raise "No console writer" + writer.call(self, filename_or_io) + else + ext = File.extname(filename_or_io) + writer = @@writers[ext]? || raise "No writer for '#{ext}'" + File.open(filename_or_io, "w") do |f| + writer.call(self, f) + end + end + end + + def write_poor_text (io) + (0...@height).each do |y| + (0...@width).each do |x| + print case self[x, y] + when Color::BLACK then '#' + when Color::WHITE then ' ' + else 'X' + end + end + puts + end + end + register_writer nil, write_poor_text +end diff --git a/Task/Bitmap/Crystal/bitmap-2.cr b/Task/Bitmap/Crystal/bitmap-2.cr new file mode 100644 index 0000000000..99b21e439e --- /dev/null +++ b/Task/Bitmap/Crystal/bitmap-2.cr @@ -0,0 +1,9 @@ +require "./pixmap" + +img = Pixmap.new(10, 5) +(0...10).each do |x| + img[x, x // 2] = Color::WHITE + img[9-x, x // 2] = Color::RED +end + +img.write(STDOUT) diff --git a/Task/Bitmap/Crystal/bitmap.crystal b/Task/Bitmap/Crystal/bitmap.crystal deleted file mode 100644 index fb4b8d9952..0000000000 --- a/Task/Bitmap/Crystal/bitmap.crystal +++ /dev/null @@ -1,36 +0,0 @@ -class RGBColor - getter red, green, blue - - def initialize(@red = 0_u8, @green = 0_u8, @blue = 0_u8) - end - - RED = new(red: 255_u8) - GREEN = new(green: 255_u8) - BLUE = new(blue: 255_u8) - BLACK = new - WHITE = new(255_u8, 255_u8, 255_u8) -end - -class Pixmap - getter width, height - @data : Array(Array(RGBColor)) - - def initialize(@width : Int32, @height : Int32) - @data = Array.new(@width) { Array.new(@height, RGBColor::WHITE) } - end - - def fill(color) - @data.each &.fill(color) - end - - def [](x, y) - @data[x][y] - end - - def []=(x, y, color) - @data[x][y] = color - end -end - -bmap = Pixmap.new(5, 5) -pp bmap diff --git a/Task/Bitmap/Delphi/bitmap.delphi b/Task/Bitmap/Delphi/bitmap.delphi deleted file mode 100644 index 70def79db7..0000000000 --- a/Task/Bitmap/Delphi/bitmap.delphi +++ /dev/null @@ -1,43 +0,0 @@ -procedure ShowBitmapFunctions(Image: TImage); -{Code to demonstrate some of the main features the Delphi "TCanvas" object} -var I,X,Y: integer; -var C: TColor; -begin -{Draw red rectangle with 3 pixels wide lines} -Image.Canvas.Pen.Color:=clRed; -Image.Canvas.Pen.Width:=3; -Image.Canvas.Rectangle(50,50,500,300); -{Flood fill rectangle blue} -Image.Canvas.Brush.Color:=clBlue; -Image.Canvas.FloodFill(55,55,clRed,fsBorder); -{Draw random dots on the screen} -for I:=1 to 1000 do - begin - X:=trunc((Random * 450) + 50); - Y:=trunc((Random * 250) + 50); - C:=RGB(Random(255),Random(255),Random(255)); - {draw 9 pixels for each point to make dots more visible} - Image.Canvas.Pixels[X-1,Y-1]:=C; - Image.Canvas.Pixels[X ,Y-1]:=C; - Image.Canvas.Pixels[X+1,Y-1]:=C; - Image.Canvas.Pixels[X-1,Y ]:=C; - Image.Canvas.Pixels[X ,Y ]:=C; - Image.Canvas.Pixels[X+1,Y ]:=C; - Image.Canvas.Pixels[X-1,Y+1]:=C; - Image.Canvas.Pixels[X ,Y+1]:=C; - Image.Canvas.Pixels[X+1,Y+1]:=C; - end; -{Draw lime-green line from corner to cornder} -Image.Canvas.Pen.Color:=clLime; -Image.Canvas.MoveTo(50,50); -Image.Canvas.LineTo(500,300); -{Sample pixel color at 51,51} -C:=Image.Canvas.Pixels[51,51]; -{Display the color value } -Image.Canvas.Brush.Color:=clAqua; -Image.Canvas.Font.Size:=25; -Image.Canvas.Font.Color:=clRed; -Image.Canvas.TextOut(5,5,IntToHex(C,8)); -{Tell Delphi to update the Window} -Image.Repaint; -end; diff --git a/Task/Bitmap/Delphi/bitmap.pas b/Task/Bitmap/Delphi/bitmap.pas new file mode 100644 index 0000000000..7f6926a01d --- /dev/null +++ b/Task/Bitmap/Delphi/bitmap.pas @@ -0,0 +1,43 @@ +procedure ShowBitmapFunctions(Image: TImage); +{Code to demonstrate some of the main features the Delphi "TCanvas" object} +var I,X,Y: integer; +var C: TColor; +begin +{Draw red rectangle with 3 pixels wide lines} +Image.Canvas.Pen.Color:=clRed; +Image.Canvas.Pen.Width:=3; +Image.Canvas.Rectangle(50,50,500,300); +{Flood fill rectangle blue} +Image.Canvas.Brush.Color:=clBlue; +Image.Canvas.FloodFill(55,55,clRed,fsBorder); +{Draw random dots on the screen} +for I:=1 to 1000 do + begin + X:=trunc((Random * 450) + 50); + Y:=trunc((Random * 250) + 50); + C:=RGB(Random(255),Random(255),Random(255)); + {draw 9 pixels for each point to make dots more visible} + Image.Canvas.Pixels[X-1,Y-1]:=C; + Image.Canvas.Pixels[X ,Y-1]:=C; + Image.Canvas.Pixels[X+1,Y-1]:=C; + Image.Canvas.Pixels[X-1,Y ]:=C; + Image.Canvas.Pixels[X ,Y ]:=C; + Image.Canvas.Pixels[X+1,Y ]:=C; + Image.Canvas.Pixels[X-1,Y+1]:=C; + Image.Canvas.Pixels[X ,Y+1]:=C; + Image.Canvas.Pixels[X+1,Y+1]:=C; + end; +{Draw lime-green line from corner to cornder} +Image.Canvas.Pen.Color:=clLime; +Image.Canvas.MoveTo(50,50); +Image.Canvas.LineTo(500,300); +{Sample pixel color at 51,51} +C:=Image.Canvas.Pixels[51,51]; +{Display the color value } +Image.Canvas.Brush.Color:=clAqua; +Image.Canvas.Font.Size:=25; +Image.Canvas.Font.Color:=clRed; +Image.Canvas.TextOut(5,5,IntToHex(C,8)); +{Tell Delphi to update the Window} +Image.Repaint; +end; diff --git a/Task/Bitmap/Elixir/bitmap.elixir b/Task/Bitmap/Elixir/bitmap.ex similarity index 100% rename from Task/Bitmap/Elixir/bitmap.elixir rename to Task/Bitmap/Elixir/bitmap.ex diff --git a/Task/Bitmap/Euphoria/bitmap.euphoria b/Task/Bitmap/Euphoria/bitmap.eu similarity index 100% rename from Task/Bitmap/Euphoria/bitmap.euphoria rename to Task/Bitmap/Euphoria/bitmap.eu diff --git a/Task/Bitmap/FBSL/bitmap.fbsl b/Task/Bitmap/FBSL/bitmap.fbsl index 910530fbc6..dccbf2fbf5 100644 --- a/Task/Bitmap/FBSL/bitmap.fbsl +++ b/Task/Bitmap/FBSL/bitmap.fbsl @@ -11,12 +11,12 @@ CENTER(ME) SHOW(ME) BEGIN EVENTS - SELECT CASE CBMSG - CASE WM_LBUTTONDOWN ' Set color at current coords as hex literal - PSET(FBSL.GETDC, LOWORD(CBLPARAM), HIWORD(CBLPARAM), &H0000FF) ' Red: Windows stores colors in BGR order - CASE WM_RBUTTONDOWN ' Get color at current coords as hex literal - FBSLSETTEXT(ME, "&H" & HEX(POINT(FBSL.GETDC, LOWORD(CBLPARAM), HIWORD(CBLPARAM)))) - CASE WM_CLOSE ' Clean up - FBSL.RELEASEDC(ME, FBSL.GETDC) - END SELECT + SELECT CASE CBMSG + CASE WM_LBUTTONDOWN ' Set color at current coords as hex literal + PSET(FBSL.GETDC, LOWORD(CBLPARAM), HIWORD(CBLPARAM), &H0000FF) ' Red: Windows stores colors in BGR order + CASE WM_RBUTTONDOWN ' Get color at current coords as hex literal + FBSLSETTEXT(ME, "&H" & HEX(POINT(FBSL.GETDC, LOWORD(CBLPARAM), HIWORD(CBLPARAM)))) + CASE WM_CLOSE ' Clean up + FBSL.RELEASEDC(ME, FBSL.GETDC) + END SELECT END EVENTS diff --git a/Task/Bitmap/FutureBasic/bitmap.basic b/Task/Bitmap/FutureBasic/bitmap.basic new file mode 100644 index 0000000000..3f1e55672d --- /dev/null +++ b/Task/Bitmap/FutureBasic/bitmap.basic @@ -0,0 +1,59 @@ +include "NSLog.incl" +/* + +This task creates an image with a background filled with red pixels. +Then sets one pixel to blue in the center of the image. +Then gets the RGB color values at that pixel position. +Then saves the image as a jpg to the desktop. + +*/ + +_Window = 1 +_Horz = 300 +_Vert = 100 +_X = 150 +_Y = 50 + +window _Window, @"Bitmap window with blue dot",(0,0,_Horz, _Vert) +WindowSetBackgroundColor(_Window,fn colorwhite) + + +local fn DrawImage as ImageRef + ImageRef image = fn ImageWithSize( fn CGSizeMake(_Horz,_Vert ) ) // create blank image + + ImageLockFocus( image ) // lock image during drawing + + CFIndex i + + for i = 0 to _Horz // fill all horizontal pixels with red dots + BezierPathStrokeLine( fn CGPointMake( i, 0 ), fn CGPointMake( i, _Vert ), 1, fn Colorred ) + next + + BezierPathStrokeRect( fn CGRectMake( _X,_Y,1,1), 1.0, fn ColorBlue) // Draw a blue dot in the center. + + ImageUnlockFocus( image ) // unlock image afer drawing + +end fn = image + + +// Draw the image +ImageRef theImage +theImage = fn DrawImage + +// Display the image +imageview 1,, theImage, (0,0,_Horz, _Vert) + +// Get the color of the pixel at horizontal position X and vertical position Y +colorref color +color = fn ViewColorAtXY( _Window, _X, _Y ) +NSLog( @"RGB Color values at pixel position X,Y are %@", color) + +// Save the image as a jpg +CFURLRef DesktopDirectory,url +DesktopDirectory = fn FileManagerURLForDirectory( NSDesktopDirectory, NSUserDomainMask ) +url = fn URLByAppendingPathComponent( DesktopDirectory, @"Bitmap Image.jpg" ) +bool err +err = fn ImageWriteToURL( theImage, url, NSBitmapImageFileTypeJPEG, _true ) // save image as jpg + + +handleevents diff --git a/Task/Bitmap/Go/bitmap-1.go b/Task/Bitmap/Go/bitmap-1.go index d6dd1a630b..f275d34761 100644 --- a/Task/Bitmap/Go/bitmap-1.go +++ b/Task/Bitmap/Go/bitmap-1.go @@ -1,57 +1,57 @@ package main import ( - "bytes" - "fmt" - "image" - "image/color" - "image/draw" - "image/png" + "bytes" + "fmt" + "image" + "image/color" + "image/draw" + "image/png" ) func main() { - // A rectangle from 0,0 to 300,240. - r := image.Rect(0, 0, 300, 240) + // A rectangle from 0,0 to 300,240. + r := image.Rect(0, 0, 300, 240) - // Create an image - im := image.NewNRGBA(r) + // Create an image + im := image.NewNRGBA(r) - // set some color variables for convience - var ( - red = color.RGBA{0xff, 0x00, 0x00, 0xff} - blue = color.RGBA{0x00, 0x00, 0xff, 0xff} - ) + // set some color variables for convience + var ( + red = color.RGBA{0xff, 0x00, 0x00, 0xff} + blue = color.RGBA{0x00, 0x00, 0xff, 0xff} + ) - // Fill with a uniform color - draw.Draw(im, r, &image.Uniform{red}, image.ZP, draw.Src) + // Fill with a uniform color + draw.Draw(im, r, &image.Uniform{red}, image.ZP, draw.Src) - // Set individual pixels - im.Set(10, 20, blue) - im.Set(20, 30, color.Black) - im.Set(30, 40, color.RGBA{0x10, 0x20, 0x30, 0xff}) + // Set individual pixels + im.Set(10, 20, blue) + im.Set(20, 30, color.Black) + im.Set(30, 40, color.RGBA{0x10, 0x20, 0x30, 0xff}) - // Get the values of specific pixels as color.Color types. - // The color will be in the color.Model of the image (in this - // case color.NRGBA) but color models can convert their values - // to other models. - c1 := im.At(0, 0) - c2 := im.At(10, 20) + // Get the values of specific pixels as color.Color types. + // The color will be in the color.Model of the image (in this + // case color.NRGBA) but color models can convert their values + // to other models. + c1 := im.At(0, 0) + c2 := im.At(10, 20) - // or directly as RGB components (scaled values) - redc, greenc, bluec, _ := c1.RGBA() - redc, greenc, bluec, _ = im.At(30, 40).RGBA() + // or directly as RGB components (scaled values) + redc, greenc, bluec, _ := c1.RGBA() + redc, greenc, bluec, _ = im.At(30, 40).RGBA() - // Images can be read and writen in various formats - var buf bytes.Buffer - err := png.Encode(&buf, im) - if err != nil { - fmt.Println(err) - } + // Images can be read and writen in various formats + var buf bytes.Buffer + err := png.Encode(&buf, im) + if err != nil { + fmt.Println(err) + } - fmt.Println("Image size:", im.Bounds().Dx(), "×", im.Bounds().Dy()) - fmt.Println(buf.Len(), "bytes when encoded as PNG.") - fmt.Printf("Pixel at %7v is %v\n", image.Pt(0, 0), c1) - fmt.Printf("Pixel at %7v is %#v\n", image.Pt(10, 20), c2) // %#v shows type details - fmt.Printf("Pixel at %7v has R=%d, G=%d, B=%d\n", - image.Pt(30, 40), redc, greenc, bluec) + fmt.Println("Image size:", im.Bounds().Dx(), "×", im.Bounds().Dy()) + fmt.Println(buf.Len(), "bytes when encoded as PNG.") + fmt.Printf("Pixel at %7v is %v\n", image.Pt(0, 0), c1) + fmt.Printf("Pixel at %7v is %#v\n", image.Pt(10, 20), c2) // %#v shows type details + fmt.Printf("Pixel at %7v has R=%d, G=%d, B=%d\n", + image.Pt(30, 40), redc, greenc, bluec) } diff --git a/Task/Bitmap/Julia/bitmap.julia b/Task/Bitmap/Julia/bitmap.jl similarity index 100% rename from Task/Bitmap/Julia/bitmap.julia rename to Task/Bitmap/Julia/bitmap.jl diff --git a/Task/Bitmap/Kotlin/bitmap.kotlin b/Task/Bitmap/Kotlin/bitmap.kts similarity index 100% rename from Task/Bitmap/Kotlin/bitmap.kotlin rename to Task/Bitmap/Kotlin/bitmap.kts diff --git a/Task/Bitmap/M2000-Interpreter/bitmap-1.m2000 b/Task/Bitmap/M2000-Interpreter/bitmap-1.m2000 index 905292d6cb..ebd64b552a 100644 --- a/Task/Bitmap/M2000-Interpreter/bitmap-1.m2000 +++ b/Task/Bitmap/M2000-Interpreter/bitmap-1.m2000 @@ -1,72 +1,102 @@ -\ Bitmap width in pixels, height in pixels -\ Return a group object with some lambda as members: SetPixel, GetPixel, Image$ -\ copyimage -\ using Copy x, y Use Image$ we can display image$ to x, y as twips -\ we can use x*twipsx, y*twipsy for x,y as pixels -Function Bitmap (x as long, y as long) { - if x<1 or y<1 then Error "Wrong dimensions" - structure rgb { - red as byte - green as byte - blue as byte - } - m=len(rgb)*x mod 4 - if m>0 then m=4-m ' add some bytes to raster line - m+=len(rgb) *x - Structure rasterline { - { - pad as byte*m +Module Checkit { + Function Bitmap (x as long, y as long) { + if x<1 or y<1 then Error "Wrong dimensions" + structure rgb { + red as byte + green as byte + blue as byte + } + m=len(rgb)*x mod 4 + if m>0 then m=4-m ' add some bytes to raster line + m+=len(rgb) *x + Structure rasterline { + { + pad as byte*m + } + \\ union pad+hline + hline as rgb*x } - \\ union pad+hline - hline as rgb*x - } - Structure Raster { - magic as integer*4 - w as integer*4 - h as integer*4 - lines as rasterline*y - } - Buffer Clear Image1 as Raster - \\ 24 chars as header to be used from bitmap render build in functions - Return Image1, 0!magic:="cDIB", 0!w:=Hex$(x,2), 0!h:=Hex$(y, 2) - \\ fill white (all 255) - \\ Str$(string) convert to ascii, so we get all characters from words width to byte width - Return Image1, 0!lines:=Str$(String$(chrcode$(255), Len(rasterline)*y)) - Buffer Clear Pad as Byte*4 - SetPixel=Lambda Image1, Pad,aLines=Len(Raster)-Len(Rasterline), blines=-Len(Rasterline) (x, y, c) ->{ - where=alines+3*x+blines*y - if c>0 then c=color(c) - c-! - Return Pad, 0:=c as long - Return Image1, 0!where:=Eval(Pad, 2) as byte, 0!where+1:=Eval(Pad, 1) as byte, 0!where+2:=Eval(Pad, 0) as byte + Structure Raster { + magic as integer*4 + w as integer*4 + h as integer*4 + lines as rasterline*y + } + Buffer Clear Image1 as Raster + \\ 24 chars as header to be used from bitmap render build in functions + Return Image1, 0!magic:="cDIB", 0!w:=Hex$(x,2), 0!h:=Hex$(y, 2) + \\ fill white (all 255) + \\ Str$(string) convert to ascii, so we get all characters from words width to byte width + Return Image1, 0!lines:=Str$(String$(chrcode$(255), Len(rasterline)*y)) + Buffer Clear Pad as Byte*4 + SetPixel=Lambda Image1, Pad,aLines=Len(Raster)-Len(Rasterline), blines=-Len(Rasterline) (x, y, c) ->{ + where=alines+3*x+blines*y + if c>0 then c=color(c) + c-! + Return Pad, 0:=c as long + Return Image1, 0!where:=Eval(Pad, 2) as byte, 0!where+1:=Eval(Pad, 1) as byte, 0!where+2:=Eval(Pad, 0) as byte + } + GetPixel=Lambda Image1,aLines=Len(Raster)-Len(Rasterline), blines=-Len(Rasterline) (x,y) ->{ + where=alines+3*x+blines*y + =color(Eval(image1, where+2 as byte), Eval(image1, where+1 as byte), Eval(image1, where as byte)) + } + StrDib$=Lambda$ Image1, Raster -> { + =Eval$(Image1, 0, Len(Raster)) + } + CopyImage=Lambda Image1 (image$) -> { + if left$(image$,12)=Eval$(Image1, 0, 24 ) Then { + Return Image1, 0:=Image$ + } Else Error "Can't Copy Image" + } + Export2File=Lambda Image1, x, y, r=len(rasterline) (f) -> { + \\ use this between open and close + Print #f, "P3" + Print #f,"# Created using M2000 Interpreter" + Print #f, x;" ";y + Print #f, 255 + x2=x-1 + For y1= y-1 to 0 { + a$="" + where=24+r*y1 + x1=0 + Print #f, Eval(Image1, where +2 as byte);" "; + Print #f, Eval(Image1, where+1 as byte);" "; + Print #f, Eval(Image1, where as byte); + where+=3 + For x1=1 to x2 { + Print #f, " ";Eval(Image1, where +2 as byte);" "; + Print #f, Eval(Image1, where+1 as byte);" "; + Print #f, Eval(Image1, where as byte); + where+=3 + } + Print #f + } + } + Group Bitmap { + SetPixel=SetPixel + GetPixel=GetPixel + Image$=StrDib$ + Copy=CopyImage + ToFile=Export2File + } + =Bitmap } - GetPixel=Lambda Image1,aLines=Len(Raster)-Len(Rasterline), blines=-Len(Rasterline) (x,y) ->{ - where=alines+3*x+blines*y - =color(Eval(image1, where+2 as byte), Eval(image1, where+1 as byte), Eval(image1, where as byte)) + A=Bitmap(150,100) + For i=0 to 98 { + Call A.SetPixel(i, i, 5) + Call A.SetPixel(99, i, color(128,0,255)) } - StrDib$=Lambda$ Image1, Raster -> { - =Eval$(Image1, 0, Len(Raster)) - } - CopyImage=Lambda Image1 (image$) -> { - if left$(image$,12)=Eval$(Image1, 0, 24 ) Then { - Return Image1, 0:=Image$ - } Else Error "Can't Copy Image" - } - Group Bitmap { - SetPixel=SetPixel - GetPixel=GetPixel - Image$=StrDib$ - Copy=CopyImage - } - =Bitmap + Call A.SetPixel(i,i,0) + Call A.SetPixel(30,50, color(128,0,255)) + Print A.GetPixel(30,50)=color(128,0,255) + move 3000, 3000 + Image A.image$() + profiler + Open "A2.PPM" for Output as #F + Call A.ToFile(F) + Close #f + print timecount } -A=Bitmap(100,100) -Call A.SetPixel(50,50, color(128,0,255)) -Print A.GetPixel(50,50)=color(128,0,255) -\\ display image to screen at 100, 50 pixel -copy 100*twipsx,50*twipsy use A.Image$() -A1=Bitmap(100,100) -Call A1.copy(A.Image$()) -copy 500*twipsx,50*twipsy use A1.Image$() +Checkit diff --git a/Task/Bitmap/M2000-Interpreter/bitmap-2.m2000 b/Task/Bitmap/M2000-Interpreter/bitmap-2.m2000 index 562ea41c5b..bae307643e 100644 --- a/Task/Bitmap/M2000-Interpreter/bitmap-2.m2000 +++ b/Task/Bitmap/M2000-Interpreter/bitmap-2.m2000 @@ -1,55 +1,57 @@ Module P6 { Function Bitmap { def x as long, y as long, Import as boolean - - If match("NN") then { + If match("NN") then Read x, y - } else.if Match("N") Then { + else.if Match("N") Then \\ is a file? Read f as long - buffer whitespace as byte - if not Eof(f) then { - get #f, whitespace :P6$=eval$(whitespace) - get #f, whitespace : P6$+=eval$(whitespace) - def boolean getW=true, getH=true, getV=true - def long v - \\ str$("P6") has 2 bytes. "P6" has 4 bytes - If p6$=str$("P6") Then { - do { + byte whitespace[0] + if not Eof(f) then + get #f, whitespace :P6$=chr$(whitespace[0]) + get #f, whitespace : P6$+=chr$(whitespace[0]) + boolean getW=true, getH=true, getV=true + long v + If p6$="P6" Then + do get #f, whitespace - if Eval$(whitespace)=str$("#") then { - do {get #f, whitespace} until eval(whitespace)=10 - } else { - select case eval(whitespace) - case 32, 9, 13, 10 - { if getW and x<>0 then { - getW=false - } else.if getH and y<>0 then { - getH=false - } else.if getV and v<>0 then { - getV=false - } - } - case 48 to 57 - {if getW then { - x*=10 - x+=eval(whitespace, 0)-48 - } else.if getH then { - y*=10 - y+=eval(whitespace, 0)-48 - } else.if getV then { - v*=10 - v+=eval(whitespace, 0)-48 - } - } - End Select + select case whitespace[0] + case 35 + {do get #f, whitespace + until whitespace[0]=10 } + case 32, 9, 13, 10 + { if getW and x<>0 then + getW=false + else.if getH and y<>0 then + getH=false + else.if getV and v<>0 then + getV=false + end if + } + case 48 to 57 + {if getW then + x*=10 + x+=whitespace[0]-48 + else.if getH then + y*=10 + y+=whitespace[0]-48 + else.if getV then + v*=10 + v+=whitespace[0]-48 + end if + } + End Select iF eof(f) then Error "Not a ppm file" - } until getV=false - } else Error "Not a P6 ppm" + until getV=false + else + Error "Not a P6 ppm" + end if Import=True - } - } else Error "No proper arguments" + end if + else + Error "No proper arguments" + end if if x<1 or y<1 then Error "Wrong dimensions" structure rgb { red as byte @@ -78,7 +80,7 @@ Module P6 { Return Image1, 0!magic:="cDIB", 0!w:=Hex$(x,2), 0!h:=Hex$(y, 2) if not Import then Return Image1, 0!lines:=Str$(String$(chrcode$(255), Len(rasterline)*y)) Buffer Clear Pad as Byte*4 - SetPixel=Lambda Image1, Pad,aLines=Len(Raster)-Len(Rasterline), blines=-Len(Rasterline) (x, y, c) ->{ + SetPixel=Lambda Image1, Pad, aLines=Len(Raster)-Len(Rasterline), blines=-Len(Rasterline) (x, y, c) ->{ where=alines+3*x+blines*y if c>0 then c=color(c) c-! @@ -101,23 +103,41 @@ Module P6 { Print #f, "P6";chr$(10);"# Created using M2000 Interpreter";chr$(10); Print #f, x;" ";y;" 255";chr$(10); x2=x-1 : where=0 - Buffer pad as byte*3 - For y1= 0 to y-1 { - For x1=0 to x2 { - Return pad, 0:=eval$(image1, 0!linesB!where, 3) - Push Eval(pad, 2) : Return pad, 2:=Eval(pad, 0), 0:=Number - Put #f, pad : where+=3 - } + x0=x*3 + structure rgbP6 { + r as byte + g as byte + b as byte + } + buffer Pad as rgbP6*x*y + For y1=y-1 to 0 { + Return pad, x*y1:=eval$(image1, 0!linesB!where, x0) + where+=x0 m=where mod 4 : if m<>0 then where+=4-m } + For x1=0 to x*y-1 { + Push Eval(pad, x1!b) : Return pad, x1!b:=Eval(pad, x1!r), x1!r:=Number + } + Put #f, pad } if Import then { - x0=x-1 : where=0 - Buffer Pad1 as byte*3 - For y1=y-1 to 0 { - For x1=0 to x0 {Get #f, Pad1 : Push Eval(pad1, 2) : Return pad1, 2:=Eval(pad1, 0), 0:=Number - Return Image1, 0!linesB!where:=Eval$(Pad1) : where+=3} - m=where mod 4 : if m<>0 then where+=4-m} + x0=x-1 : where=0 + structure rgbP6 { + r as byte + g as byte + b as byte + } + buffer Pad1 as rgbP6*x*y + Get #f, Pad1 + For x1=0 to x*y-1 { + Push Eval(pad1, x1!b) : Return pad1, x1!b:=Eval(pad1, x1!r), x1!r:=Number + } + x1=x*3 + For y1=y-1 to 0 { + Return Image1, 0!linesB!where:=Eval$(Pad1, y1*x, x1) + where+=3*(x0+1) + m=where mod 4 : if m<>0 then where+=4-m + } } Group Bitmap { SetPixel=SetPixel diff --git a/Task/Bitmap/Maple/bitmap.maple b/Task/Bitmap/Maple/bitmap.maple index c09fcaa799..5182a05be3 100644 --- a/Task/Bitmap/Maple/bitmap.maple +++ b/Task/Bitmap/Maple/bitmap.maple @@ -1,23 +1,23 @@ allocateImg := proc(width, height) - return Array(1..width, 1..height, 1..3); + return Array(1..width, 1..height, 1..3); end proc: fillColor := proc(img, rgb::list) - local i; - for i from 1 to 3 do - img[..,..,i] := map(x->rgb[i], img[..,..,i]): - end do: + local i; + for i from 1 to 3 do + img[..,..,i] := map(x->rgb[i], img[..,..,i]): + end do: end proc: setColor := proc(x, y, img, rgb::list) - local i: - for i from 1 to 3 do - img[x,y,i] := rgb[i]: - end do: + local i: + for i from 1 to 3 do + img[x,y,i] := rgb[i]: + end do: end proc: getColor := proc(x,y,img) - local rgb,i: - rgb := Array(1..3): - for i from 1 to 3 do - rgb(i) := img[x,y,i]: - end do: - return rgb: + local rgb,i: + rgb := Array(1..3): + for i from 1 to 3 do + rgb(i) := img[x,y,i]: + end do: + return rgb: end proc: diff --git a/Task/Bitmap/MiniScript/bitmap.mini b/Task/Bitmap/MiniScript/bitmap.mini index b9f2eed398..28cfdc4c47 100644 --- a/Task/Bitmap/MiniScript/bitmap.mini +++ b/Task/Bitmap/MiniScript/bitmap.mini @@ -12,7 +12,7 @@ img = Image.create(width, height, colr) // Create a diagonal line of multiple colors. Uses // Cartesian coordinates so (0, 0) is lower left corner. for i in range(0, 255) - img.setPixel i, i, color.rgb(i, i, i) + img.setPixel i, i, color.rgb(i, i, i) end for // Get pixel color as RGBA hex values diff --git a/Task/Bitmap/OCaml/bitmap-1.ocaml b/Task/Bitmap/OCaml/bitmap-1.ml similarity index 100% rename from Task/Bitmap/OCaml/bitmap-1.ocaml rename to Task/Bitmap/OCaml/bitmap-1.ml diff --git a/Task/Bitmap/OCaml/bitmap-2.ocaml b/Task/Bitmap/OCaml/bitmap-2.ml similarity index 100% rename from Task/Bitmap/OCaml/bitmap-2.ocaml rename to Task/Bitmap/OCaml/bitmap-2.ml diff --git a/Task/Bitmap/OCaml/bitmap-3.ocaml b/Task/Bitmap/OCaml/bitmap-3.ml similarity index 100% rename from Task/Bitmap/OCaml/bitmap-3.ocaml rename to Task/Bitmap/OCaml/bitmap-3.ml diff --git a/Task/Bitmap/OCaml/bitmap-4.ocaml b/Task/Bitmap/OCaml/bitmap-4.ml similarity index 100% rename from Task/Bitmap/OCaml/bitmap-4.ocaml rename to Task/Bitmap/OCaml/bitmap-4.ml diff --git a/Task/Bitmap/OCaml/bitmap-5.ocaml b/Task/Bitmap/OCaml/bitmap-5.ml similarity index 100% rename from Task/Bitmap/OCaml/bitmap-5.ocaml rename to Task/Bitmap/OCaml/bitmap-5.ml diff --git a/Task/Bitmap/OCaml/bitmap-6.ocaml b/Task/Bitmap/OCaml/bitmap-6.ml similarity index 100% rename from Task/Bitmap/OCaml/bitmap-6.ocaml rename to Task/Bitmap/OCaml/bitmap-6.ml diff --git a/Task/Bitmap/OCaml/bitmap-7.ocaml b/Task/Bitmap/OCaml/bitmap-7.ml similarity index 100% rename from Task/Bitmap/OCaml/bitmap-7.ocaml rename to Task/Bitmap/OCaml/bitmap-7.ml diff --git a/Task/Bitmap/Oz/bitmap-1.oz b/Task/Bitmap/Oz/bitmap-1.oz index 894345a7e0..e7394ba62c 100644 --- a/Task/Bitmap/Oz/bitmap-1.oz +++ b/Task/Bitmap/Oz/bitmap-1.oz @@ -9,12 +9,12 @@ define C = {Array.new 1 Height unit} in for Row in 1..Height do - C.Row := {Array.new 1 Width Init} + C.Row := {Array.new 1 Width Init} end array2d(width:Width - height:Height - contents:C) + height:Height + contents:C) end fun {Get array2d(contents:C ...) X Y} @@ -27,9 +27,9 @@ define proc {Transform array2d(contents:C width:W height:H ...) Fun} for Y in 1..H do - for X in 1..W do - C.Y.X := {Fun C.Y.X} - end + for X in 1..W do + C.Y.X := {Fun C.Y.X} + end end end diff --git a/Task/Bitmap/POV-Ray/bitmap.povray b/Task/Bitmap/POV-Ray/bitmap.povray new file mode 100644 index 0000000000..2578b0aa32 --- /dev/null +++ b/Task/Bitmap/POV-Ray/bitmap.povray @@ -0,0 +1,74 @@ +//cmd: +w300 +h300 +am2 +a0.01 + +#version 3.7; + +#global_settings {assumed_gamma 1} +#default{ finish{ ambient 0.1 diffuse 0.9 }} +background {rgb 0} + + +#macro mapInit(DimX, DimY) + #local Map = array[DimX][DimY]; + mapFillSolid(Map, rgb<0,0,0>) + Map +#end + + +#macro mapFillSolid(Map, Colour) + mapFillRect(Map,<0,0>,, Colour) +#end + + +#macro mapFillRect(Map, RectLowerLeft, RectUpperRight, Colour) + #for (X, RectLowerLeft.x, RectUpperRight.x - 1) + #for (Y, RectLowerLeft.y, RectUpperRight.y - 1) + #local Map[X][Y] = Colour; + #end + #end +#end + + +#macro mapSetPixel(Map, Pixel, Colour) + #local Map[Pixel.x][Pixel.y] = Colour; +#end + + +#macro mapGetPixel(Map, Pixel) + Map[Pixel.x][Pixel.y] +#end + + +#macro mapObject(Map) + // to visualize the map, each pixel is rendered as a sphere + #for (X,0,dimension_size(Map,1)-1) + #for (Y,0,dimension_size(Map,2)-1) + sphere{ + , 0.5 + pigment{colour Map[X][Y]} + } + #end + #end +#end + +//== Scene + +#declare DimX = 100; +#declare DimY = 100; +#declare ImgMap = mapInit(DimX, DimY); +mapFillSolid(ImgMap, rgb<1, 0, 0>) +mapSetPixel(ImgMap, <25,25>, rgb<1,1,1>) +mapFillRect(ImgMap, <50,50>, <75,75>, rgb<0,0,1>) + +#debug concat("Colour at: <", vstr(2,<25,25>,", ",0,0),"> is: <", vstr(3, mapGetPixel(ImgMap, <25,25>),", ",0,0),">\n") + +mapObject(ImgMap) + +camera{ + location + look_at + right x*image_width/image_height +} +light_source{ + + rgb 1 +} diff --git a/Task/Bitmap/Pascal/bitmap.pas b/Task/Bitmap/Pascal/bitmap.pas index 09867f7945..d588e54d4e 100644 --- a/Task/Bitmap/Pascal/bitmap.pas +++ b/Task/Bitmap/Pascal/bitmap.pas @@ -117,14 +117,14 @@ Procedure CreateBmpFile32(directory: string; FileName: string; { fill the pixel data area } for y := (height - 1) downto 0 do begin - for x := 0 to (width - 1) do - begin { Pixel(x,y) } - color32.Blue := 255; - color32.Green := 0; - color32.Red := 0; - color32.Alfa := 0; - BlockWrite(bmpFile, color32, 4); - end; { for x ... } + for x := 0 to (width - 1) do + begin { Pixel(x,y) } + color32.Blue := 255; + color32.Green := 0; + color32.Red := 0; + color32.Alfa := 0; + BlockWrite(bmpFile, color32, 4); + end; { for x ... } end; { for y ... } Close(bmpFile); end; { with bmpInfoHeader, bmpFileHeader } diff --git a/Task/Bitmap/Pluto/bitmap-1.pluto b/Task/Bitmap/Pluto/bitmap-1.pluto new file mode 100644 index 0000000000..8901f27d06 --- /dev/null +++ b/Task/Bitmap/Pluto/bitmap-1.pluto @@ -0,0 +1,23 @@ +local canvas = require "canvas" + +-- Create a new canvas object: 400 pixels wide and 400 pixels high. +local c = canvas.new(400, 400) + +-- Color the whole canvas blue. +c:fill(0xff0000) + +-- Draw a red square in the middle. +for i = 1, 51 do + for j = 1, 51 do + c:set(174 + i, 174 + j, 0x0000ff) + end +end + +-- Print to the terminal the color (as an integer) of a pixel. +print(c:get(200, 200)) -- 255 + +-- Convert the canvas to a BMP image. +local image = c:tobmp() + +-- Save the image to a file. +io.contents("mybmp.bmp", image) diff --git a/Task/Bitmap/Pluto/bitmap-2.pluto b/Task/Bitmap/Pluto/bitmap-2.pluto new file mode 100644 index 0000000000..bee038a9ef --- /dev/null +++ b/Task/Bitmap/Pluto/bitmap-2.pluto @@ -0,0 +1,16 @@ +require "bitmap" + +-- Create a new bitmap object: 400 pixels wide and 400 pixels high +local bmp = bitmap.of(400, 400, color.blue, "mybmp") + +-- Draw a red square in the middle. +bmp:square(200, 200, 50, color.red, 0, true) + +-- Print to the terminal the color (as an integer) of a pixel. +print(bmp:get(200, 200)) -- 255 + +-- View the image using the default viewer for the platform. +bmp:view() + +-- Save the image to the file mybmp.bmp in the current directory. +bmp:save() diff --git a/Task/Bitmap/Prolog/bitmap.pro b/Task/Bitmap/Prolog/bitmap.pro index 1ea949bb5f..13b5e3511d 100644 --- a/Task/Bitmap/Prolog/bitmap.pro +++ b/Task/Bitmap/Prolog/bitmap.pro @@ -1,20 +1,20 @@ :- module(bitmap, [ - new_bitmap/3, - fill_bitmap/3, - get_pixel0/3, - set_pixel0/4 ]). + new_bitmap/3, + fill_bitmap/3, + get_pixel0/3, + set_pixel0/4 ]). :- use_module(library(lists)). %-----------------------------------------------------------------------------% % Convenience Predicates replicate(Term,Times,L):- - length(L,Times), - maplist(=(Term),L). + length(L,Times), + maplist(=(Term),L). replace0(N,OL,E,NL):- - nth0(N,OL,_,TL), - nth0(N,NL,E,TL). + nth0(N,OL,_,TL), + nth0(N,NL,E,TL). %-----------------------------------------------------------------------------% % Bitmap Utilities % @@ -25,27 +25,27 @@ replace0(N,OL,E,NL):- % in other bitmap tasks it is assumed to be a list [R,G,B] where % each is an int between 0 and 255, in code: rgb_pixel(RGB):- - length(RGB,3), - maplist(integer,RGB), - maplist(between(0,255),RGB). + length(RGB,3), + maplist(integer,RGB), + maplist(between(0,255),RGB). %new_bitmap(Bitmap,Dimensions,RGB) new_bitmap([[X,Y],Pixels],[X,Y],RGB) :- - replicate(RGB,X,Row), - replicate(Row,Y,Pixels). - + replicate(RGB,X,Row), + replicate(Row,Y,Pixels). + %fill_bitmap(New_Bitmap,Bitmap,RGB) fill_bitmap(New_Bitmap,[[X,Y],_],RGB) :- - new_bitmap(New_Bitmap,[X,Y],RGB). + new_bitmap(New_Bitmap,[X,Y],RGB). %here get and set use 0 based indexing %get_pixel0(Bitmap,Coordinates,RGB) get_pixel0([[_DimX,_DimY],Pixels],[X,Y],RGB) :- - nth0(Y,Pixels,Row), - nth0(X,Row,RGB). + nth0(Y,Pixels,Row), + nth0(X,Row,RGB). %set_pixel0(New Bitmap, Bitmap, Coordinates, RGB) set_pixel0([[DimX,DimY],New_Pixels],[[DimX,DimY],Pixels],[X,Y],RGB) :- - nth0(Y,Pixels,Row), - replace0(X,Row,RGB,New_Row), - replace0(Y,Pixels,New_Row,New_Pixels). + nth0(Y,Pixels,Row), + replace0(X,Row,RGB,New_Row), + replace0(Y,Pixels,New_Row,New_Pixels). diff --git a/Task/Bitmap/Raku/bitmap.raku b/Task/Bitmap/Raku/bitmap.raku index 1bf117941a..e2a0e66931 100644 --- a/Task/Bitmap/Raku/bitmap.raku +++ b/Task/Bitmap/Raku/bitmap.raku @@ -7,16 +7,16 @@ class Bitmap { @!data = $p.clone xx ($!width*$!height) } method pixel( - $i where ^$!width, - $j where ^$!height - --> Pixel + $i where ^$!width, + $j where ^$!height + --> Pixel ) is rw { @!data[$i + $j * $!width] } method set-pixel ($i, $j, Pixel $p) { - self.pixel($i, $j) = $p.clone; + self.pixel($i, $j) = $p.clone; } method get-pixel ($i, $j) returns Pixel { - self.pixel($i, $j); + self.pixel($i, $j); } } diff --git a/Task/Bitmap/RapidQ/bitmap.rapidq b/Task/Bitmap/RapidQ/bitmap.rapidq index ad4ebfe355..71baea5c92 100644 --- a/Task/Bitmap/RapidQ/bitmap.rapidq +++ b/Task/Bitmap/RapidQ/bitmap.rapidq @@ -5,8 +5,8 @@ CREATE form AS QForm Height = 480 CREATE canvas AS QCanvas Height = form.ClientHeight - Width = form.ClientWidth - OnPaint = PaintCanvas + Width = form.ClientWidth + OnPaint = PaintCanvas END CREATE END CREATE diff --git a/Task/Bitmap/Rebol/bitmap.rebol b/Task/Bitmap/Rebol/bitmap.rebol new file mode 100644 index 0000000000..f4d893806b --- /dev/null +++ b/Task/Bitmap/Rebol/bitmap.rebol @@ -0,0 +1,58 @@ +;; make image using pair +img: make image! 2x2 +;; make image using pair and RGB tuple +img: make image! [2x2 255.0.0] +;; make image using pair and RGBA tuple" +img: make image! [2x2 255.0.0.10] + +;; Rebol3's construction syntax +img1: #(image! 4x4) ;; white by default +img2: #(image! 2x2 0.0.0) ;; black image + +;; Raw binary access: +probe img1/rgb +;== #{ +;== FFFFFFFFFFFFFFFFFFFFFFFF +;== FFFFFFFFFFFFFFFFFFFFFFFF +;== FFFFFFFFFFFFFFFFFFFFFFFF +;== FFFFFFFFFFFFFFFFFFFFFFFF} + +;; Blit image to image +change at img1 2x2 img2 +probe img1/rgb +;== #{ +;== FFFFFFFFFFFFFFFFFFFFFFFF +;== FFFFFF000000000000FFFFFF +;== FFFFFF000000000000FFFFFF +;== FFFFFFFFFFFFFFFFFFFFFFFF} + +;; Pixel access +img1/1 ;== 255.255.255.255 +img2/1 ;== 0.0.0.255 +img1/2x2 ;== 0.0.0.255 + +;; Other binary accessors: +img: #(image! 2x1) +img/1: 1.2.3.100 +img/2: 4.5.6.200 +img/rgba ;== #{01020364040506C8} +img/rgbo ;== #{0102039B04050637} +img/argb ;== #{64010203C8040506} +img/orgb ;== #{9B01020337040506} +img/bgra ;== #{03020164060504C8} +img/bgro ;== #{0302019B06050437} +img/abgr ;== #{64030201C8060504} +img/obgr ;== #{9B03020137060504} +img/opacity ;== #{9B37} +img/alpha ;== #{64C8} + +;; Drawing may be done using extensions like Blend2D +import blend2d ;@@ https://github.com/Siskin-framework/Rebol-Blend2D +img: draw 100x100 [ + fill red + pen black + line-width 10 + circle 50x50 20 + fill none + line 0x0 100x100 +] diff --git a/Task/Bitmap/Rust/bitmap.rust b/Task/Bitmap/Rust/bitmap.rs similarity index 100% rename from Task/Bitmap/Rust/bitmap.rust rename to Task/Bitmap/Rust/bitmap.rs diff --git a/Task/Bitmap/Scheme/bitmap-1.ss b/Task/Bitmap/Scheme/bitmap-1.scm similarity index 100% rename from Task/Bitmap/Scheme/bitmap-1.ss rename to Task/Bitmap/Scheme/bitmap-1.scm diff --git a/Task/Bitmap/Scheme/bitmap-2.ss b/Task/Bitmap/Scheme/bitmap-2.scm similarity index 100% rename from Task/Bitmap/Scheme/bitmap-2.ss rename to Task/Bitmap/Scheme/bitmap-2.scm diff --git a/Task/Bitmap/Scheme/bitmap-3.ss b/Task/Bitmap/Scheme/bitmap-3.scm similarity index 100% rename from Task/Bitmap/Scheme/bitmap-3.ss rename to Task/Bitmap/Scheme/bitmap-3.scm diff --git a/Task/Bitmap/Scheme/bitmap-4.ss b/Task/Bitmap/Scheme/bitmap-4.scm similarity index 100% rename from Task/Bitmap/Scheme/bitmap-4.ss rename to Task/Bitmap/Scheme/bitmap-4.scm diff --git a/Task/Bitmap/Scheme/bitmap-5.ss b/Task/Bitmap/Scheme/bitmap-5.scm similarity index 100% rename from Task/Bitmap/Scheme/bitmap-5.ss rename to Task/Bitmap/Scheme/bitmap-5.scm diff --git a/Task/Bitmap/SequenceL/bitmap.sequencel b/Task/Bitmap/SequenceL/bitmap.sequencel index 5facc762fe..ba7a4ffd42 100644 --- a/Task/Bitmap/SequenceL/bitmap.sequencel +++ b/Task/Bitmap/SequenceL/bitmap.sequencel @@ -2,37 +2,37 @@ RGB ::= (R: int(0), G: int(0), B: int(0)); newBitmap: int * int -> RGB(2); newBitmap(width, height)[y, x] := - (R: 0, G: 0, B: 0) - foreach y within 1 ... height, - x within 1 ... width; + (R: 0, G: 0, B: 0) + foreach y within 1 ... height, + x within 1 ... width; fill: RGB(2) * RGB -> RGB(2); fill(bitmap(2), color)[y, x] := - color - foreach y within 1 ... size(bitmap), - x within 1 ... size(bitmap[y]); + color + foreach y within 1 ... size(bitmap), + x within 1 ... size(bitmap[y]); setColorAt: RGB(2) * int * int * RGB -> RGB(2); setColorAt(bitmap(2), x, y, color)[Y, X] := - color when Y = y and X = x - else - bitmap[Y, X]; - -getColorAt: RGB(2) * int * int -> RGB; + color when Y = y and X = x + else + bitmap[Y, X]; + +getColorAt: RGB(2) * int * int -> RGB; getColorAt(bitmap(2), x, y) := bitmap[y, x]; lightGreen := (R: 51, G: 255, B: 51); lightRed := (R: 255, G: 51, B: 51); main(args(2)) := - let - width := 1920; - height := 1200; - - cleanImage := newBitmap(width, height); - - filledGreen := fill(cleanImage, lightGreen); - - redCenter := setColorAt(filledGreen, width / 2, height / 2, lightRed); - in - getColorAt(redCenter, width / 2, height / 2); + let + width := 1920; + height := 1200; + + cleanImage := newBitmap(width, height); + + filledGreen := fill(cleanImage, lightGreen); + + redCenter := setColorAt(filledGreen, width / 2, height / 2, lightRed); + in + getColorAt(redCenter, width / 2, height / 2); diff --git a/Task/Bitmap/Uiua/bitmap.uiua b/Task/Bitmap/Uiua/bitmap.uiua new file mode 100644 index 0000000000..3e952126ca --- /dev/null +++ b/Task/Bitmap/Uiua/bitmap.uiua @@ -0,0 +1,3 @@ +↯ 50_50_3 Red # Fill with red. +⍜(⊡25_25|⋅White) # Add white spot. +⊸⊡0_0 # Get pixel [0 0]. diff --git a/Task/Bitmap/Vedit-macro-language/bitmap.vedit b/Task/Bitmap/Vedit-macro-language/bitmap.vedit index 616c17071b..56f41c3f72 100644 --- a/Task/Bitmap/Vedit-macro-language/bitmap.vedit +++ b/Task/Bitmap/Vedit-macro-language/bitmap.vedit @@ -1,5 +1,5 @@ -#11 = 400 // Width of the image -#12 = 300 // Height of the image +#11 = 400 // Width of the image +#12 = 300 // Height of the image // Create an empty RGB image and fill it with black color // @@ -13,16 +13,16 @@ Repeat(#11 * #12) { // Fill the image with dark blue color // -#5 = 0 // Red -#6 = 0 // Green -#7 = 64 // Blue +#5 = 0 // Red +#6 = 0 // Green +#7 = 64 // Blue Call("FILL_IMAGE") // Draw one pixel in orange color // -#1 = 100 // x -#2 = 50 // y -#5 = 255 #6 = 128 #7 = 0 // Orange color +#1 = 100 // x +#2 = 50 // y +#5 = 255 #6 = 128 #7 = 0 // Orange color Call("DRAW_PIXEL") // Get the color of a pixel diff --git a/Task/Bitmap/Yabasic/bitmap.basic b/Task/Bitmap/Yabasic/bitmap.basic index cad0519374..0dbe5417f2 100644 --- a/Task/Bitmap/Yabasic/bitmap.basic +++ b/Task/Bitmap/Yabasic/bitmap.basic @@ -6,8 +6,8 @@ backcolor 255, 0, 0 // red clear window -color 0, 255, 0 // green +color 0, 255, 0 // green dot 100, 100 -c$ = getbit$(100, 100, 100, 100) // get color area 1x1 pixel +c$ = getbit$(100, 100, 100, 100) // get color area 1x1 pixel print c$ diff --git a/Task/Bitmap/Zig/bitmap.zig b/Task/Bitmap/Zig/bitmap.zig new file mode 100644 index 0000000000..08b57964ef --- /dev/null +++ b/Task/Bitmap/Zig/bitmap.zig @@ -0,0 +1,96 @@ +const std = @import("std"); + +pub const Rgb = struct { + r: u8, + g: u8, + b: u8, +}; + +pub const PixelOutOfBounds = error{PixelOutOfBounds}; + +pub const Bitmap = struct { + width: usize, + height: usize, + pixels: []Rgb, + + // The ! next to the return type communicates that the function may return an error + pub fn new(allocator: std.mem.Allocator, width: usize, height: usize) !Bitmap { + // In Zig libraries that allocate receive an allocator + // instead of choosing one themselves + var pixels = try allocator.alloc(Rgb, width * height); + + for (0..width*height) | i | { + pixels[i] = Rgb { .r = 0, .g = 0, .b = 0 }; + } + + return Bitmap { + .width = width, + .height = height, + .pixels = pixels, + }; + } + + pub fn free(self: Bitmap, allocator: std.mem.Allocator) void { + allocator.free(self.pixels); + } + + pub fn fill(self: *Bitmap, color: Rgb) void { + for (0..self.width*self.height) | i | { + self.pixels[i] = color; + } + } + + pub fn get_pixel_unchecked(self: Bitmap, x: usize, y: usize) Rgb { + return self.pixels[self.height * y + x]; + } + + pub fn get_pixel(self: Bitmap, x: usize, y: usize) !Rgb { + if (self.width <= x or self.height <= y) { + return error.PixelOutOfBounds; + } + + return self.get_pixel_unchecked(x, y); + } + + pub fn set_pixel_unchecked(self: *Bitmap, x: usize, y: usize, color: Rgb) void { + self.pixels[self.height * y + x] = color; + } + + pub fn set_pixel(self: *Bitmap, x: usize, y: usize, color: Rgb) !void { + if (self.width <= x or self.height <= y) { + return error.PixelOutOfBounds; + } + + return self.set_pixel_unchecked(x, y, color); + } +}; + +test "putting a pixel gets the pixel" { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + const allocator = gpa.allocator(); + + var bm = try Bitmap.new(allocator, 10, 10); + defer bm.free(allocator); + + try bm.set_pixel(4, 4, Rgb {.r=255, .g=0, .b=0}); + + const pixel = try bm.get_pixel(4, 4); + + try std.testing.expectEqual(255, pixel.r); +} + +test "filling a pixel gets all the pixels" { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + const allocator = gpa.allocator(); + + var bm = try Bitmap.new(allocator, 10, 10); + defer bm.free(allocator); + + bm.fill(Rgb {.r=255, .g=0, .b=0}); + + for (0..10) | x | { + for (0..10) | y | { + try std.testing.expectEqual(255, bm.get_pixel_unchecked(x, y).r); + } + } +} diff --git a/Task/Bitmap/Zkl/bitmap-1.zkl b/Task/Bitmap/Zkl/bitmap-1.zkl index b0784bda52..684616c368 100644 --- a/Task/Bitmap/Zkl/bitmap-1.zkl +++ b/Task/Bitmap/Zkl/bitmap-1.zkl @@ -1,16 +1,16 @@ -class PPM{ // (0,0) is logically bottom left +class PPM{ // (0,0) is logically bottom left fcn init(width,height){ sz:=width*height*3; var [const] data=sz.pump(Data(sz),0), // initialize to Black (RGB=000) - w=width, h=height; + w=width, h=height; } fcn fill(rgb){ sz:=data.len()/3; data.clear(); sz.pump(data,T(Void,rgb.toBigEndian(3))); } fcn __sGet(x,y) { data.toBigEndian(3*y*w + 3*x,3); } //ppm[x,y] - fcn __sSet(rbg,x,y){ data[3*y*w + 3*x,3]=rbg.toBigEndian(3); } //ppm[x,y]=rgb + fcn __sSet(rbg,x,y){ data[3*y*w + 3*x,3]=rbg.toBigEndian(3); } //ppm[x,y]=rgb fcn write(out){ // write bottom to top to move (0,0) from bottom left to bottom left out.write("P6\n#rosettacode PPM\n%d %d\n255\n".fmt(w,h)); [h-1..0, -1].pump(out,'wrap(h){ data.seek(3*h*w); data.read(3*w) }); diff --git a/Task/Bitwise-IO/Ada/bitwise-io-1.ada b/Task/Bitwise-IO/Ada/bitwise-io-1.adb similarity index 100% rename from Task/Bitwise-IO/Ada/bitwise-io-1.ada rename to Task/Bitwise-IO/Ada/bitwise-io-1.adb diff --git a/Task/Bitwise-IO/Ada/bitwise-io-2.ada b/Task/Bitwise-IO/Ada/bitwise-io-2.adb similarity index 100% rename from Task/Bitwise-IO/Ada/bitwise-io-2.ada rename to Task/Bitwise-IO/Ada/bitwise-io-2.adb diff --git a/Task/Bitwise-IO/Ada/bitwise-io-3.ada b/Task/Bitwise-IO/Ada/bitwise-io-3.adb similarity index 100% rename from Task/Bitwise-IO/Ada/bitwise-io-3.ada rename to Task/Bitwise-IO/Ada/bitwise-io-3.adb diff --git a/Task/Bitwise-IO/C++/bitwise-io.cpp b/Task/Bitwise-IO/C++/bitwise-io.cpp new file mode 100644 index 0000000000..70fcad159c --- /dev/null +++ b/Task/Bitwise-IO/C++/bitwise-io.cpp @@ -0,0 +1,114 @@ +#include +#include +#include +#include + +class BitFilter { +public: + BitFilter(const std::string& filePath) { + writer.open(filePath, std::ios_base::binary); + reader.open(filePath, std::ios_base::binary); + accumulator = 0; + bits = 0; + } + + void write(const std::vector& chars, const uint32_t& startIndex, + uint32_t bitCount, uint32_t bitsOmittedCount) { + uint32_t index = startIndex + bitsOmittedCount / 8; + bitsOmittedCount %= 8; + + while ( bitCount > 0 || bits >= 8 ) { + while ( bits >= 8 ) { + bits -= 8; + writer.put(accumulator >> bits); + accumulator &= ( 1 << bits ) - 1; + } + + while ( bits < 8 && bitCount > 0 ) { + accumulator = ( accumulator << 1 ) | + ( ( ( 128 >> bitsOmittedCount ) & chars[index] ) >> ( 7 - bitsOmittedCount ) ); + bitCount -= 1; + bits += 1; + if ( ++bitsOmittedCount == 8 ) { + bitsOmittedCount = 0; + index += 1; + } + } + } + } + + void read(std::vector& chars, const uint32_t& startIndex, + uint32_t bitCount, uint32_t bitsOmittedCount) { + uint32_t index = startIndex + bitsOmittedCount / 8; + bitsOmittedCount %= 8; + + while ( bitCount > 0 ) { + while ( bits > 0 && bitCount > 0 ) { + const uint32_t mask = 128 >> bitsOmittedCount; + if ( ( accumulator & ( 1 << ( bits - 1 ) ) ) > 0 ) { + chars[index] = chars[index] | mask; + } else { + chars[index] = chars[index] & ( ~mask & 0xff ); + } + + bitCount -= 1; + bits -= 1; + if ( ++bitsOmittedCount >= 8 ) { + bitsOmittedCount = 0; + index += 1; + } + } + + if ( bitCount > 0 ) { + char qq; + reader.read((&qq), 1); + accumulator = ( accumulator << 8 ) | qq; + bits += 8; + } + } + } + + void close_writer() { + if ( bits != 0 ) { + accumulator <<= 8 - bits; + writer.put(accumulator); + } + + writer.close(); + accumulator = 0; + bits = 0; + } + + void close_reader() { + reader.close(); + accumulator = 0; + bits = 0; + } + +private: + uint32_t accumulator, bits; + std::ofstream writer; + std::ifstream reader; +}; + +int main() { + BitFilter bitFilter("BitwiseIO.dat"); + std::string source = "abcde12345"; + std::vector chars(source.begin(), source.end()); + + // For each char in 'chars', write 7 bits omitting the most significant bit + for ( uint32_t i = 0; i < chars.size(); ++i ) { + bitFilter.write(chars, i, 7, 1); + } + bitFilter.close_writer(); + + // Read 7 bits and expand to a char of 'destination' by reconstructing the most significant bit + std::vector destination(chars.size()); + for ( uint32_t i = 0; i < destination.size(); ++i ) { + bitFilter.read(destination, i, 7, 1); + } + bitFilter.close_reader(); + + std::string result(destination.data()); + std::cout << result << std::endl; +} diff --git a/Task/Bitwise-IO/Delphi/bitwise-io.delphi b/Task/Bitwise-IO/Delphi/bitwise-io.pas similarity index 100% rename from Task/Bitwise-IO/Delphi/bitwise-io.delphi rename to Task/Bitwise-IO/Delphi/bitwise-io.pas diff --git a/Task/Bitwise-IO/DuckDB/bitwise-io-1.duckdb b/Task/Bitwise-IO/DuckDB/bitwise-io-1.duckdb new file mode 100644 index 0000000000..df8d7f60c4 --- /dev/null +++ b/Task/Bitwise-IO/DuckDB/bitwise-io-1.duckdb @@ -0,0 +1,8 @@ +# s should be a bitstring. +# Right-pad s with 0s so that the length of the output string is a multiple of 8. +CREATE OR REPLACE FUNCTION print_bits(s) as ( + format('{:0<{}}', s, (ceil(length(s) / 8) * 8)::INT) +); + +# Example: +select print_bits('101'::BITSTRING); diff --git a/Task/Bitwise-IO/DuckDB/bitwise-io-2.duckdb b/Task/Bitwise-IO/DuckDB/bitwise-io-2.duckdb new file mode 100644 index 0000000000..57ab55eb4d --- /dev/null +++ b/Task/Bitwise-IO/DuckDB/bitwise-io-2.duckdb @@ -0,0 +1,13 @@ +# "Compress" a string by printing it as a bitstring without the left-most bit of each byte +CREATE OR REPLACE FUNCTION sevenbits(str) as ( + select string_agg(format('{}', ascii(s)::BITSTRING)[-7:], '') + from (select unnest(regexp_extract_all(str, '.')) as s) +); + +# Undo sevenbits() +CREATE OR REPLACE FUNCTION from_sevenbits(str) as ( + select string_agg(chr(s::BIT::INT), '') + from (select unnest(regexp_extract_all(str, '.......')) as s) +); + +select from_sevenbits(sevenbits('abracadabra')); diff --git a/Task/Bitwise-IO/Java/bitwise-io.java b/Task/Bitwise-IO/Java/bitwise-io.java new file mode 100644 index 0000000000..06a000098b --- /dev/null +++ b/Task/Bitwise-IO/Java/bitwise-io.java @@ -0,0 +1,112 @@ +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.nio.charset.StandardCharsets; + +public final class BitwiseIO { + + public static void main(String[] args) throws IOException { + BitFilter bitFilter = new BitFilter("BitwiseIO.dat"); + byte[] source = "abcde12345".getBytes(StandardCharsets.ISO_8859_1); + + // For each byte in 'source', write 7 bits omitting the most significant bit + for ( int i = 0; i < source.length; i++ ) { + bitFilter.write(source, i, 7, 1); + } + bitFilter.closeWriter(); + + // Read 7 bits and expand to a byte of 'destination' by reconstructing the most significant bit + byte[] destination = new byte[source.length]; + for ( int i = 0; i < destination.length; i++ ) { + bitFilter.read(destination, i, 7, 1); + } + bitFilter.closeReader(); + + System.out.println( new String(destination) ); + } + +} + +final class BitFilter { + + public BitFilter(String filePath) throws IOException { + bufferedWriter = new BufferedWriter( new FileWriter(filePath) ); + bufferedReader = new BufferedReader( new FileReader(filePath) ); + } + + public void write(byte[] bytes, int startIndex, int bitCount, int bitsOmittedCount) throws IOException { + int index = startIndex + bitsOmittedCount / 8; + bitsOmittedCount %= 8; + + while ( bitCount > 0 || bits >= 8 ) { + while ( bits >= 8 ) { + bits -= 8; + bufferedWriter.write(accumulator >>> bits); + accumulator &= ( 1 << bits ) - 1; + } + + while ( bits < 8 && bitCount > 0 ) { + accumulator = ( accumulator << 1 ) | + ( ( ( 128 >>> bitsOmittedCount ) & bytes[index] ) >>> ( 7 - bitsOmittedCount ) ); + bitCount -= 1; + bits += 1; + if ( ++bitsOmittedCount == 8 ) { + bitsOmittedCount = 0; + index += 1; + } + } + } + } + + public void read(byte[] bytes, int startIndex, int bitCount, int bitsOmittedCount) throws IOException { + int index = startIndex + bitsOmittedCount / 8; + bitsOmittedCount %= 8; + + while ( bitCount > 0 ) { + while ( bits > 0 && bitCount > 0 ) { + final int mask = 128 >>> bitsOmittedCount; + if ( ( accumulator & ( 1 << ( bits - 1 ) ) ) > 0 ) { + bytes[index] = (byte) ( bytes[index] | mask ); + } else { + bytes[index] = (byte) ( bytes[index] & ( ~mask & 0xff ) ); + } + + bitCount -= 1; + bits -= 1; + if ( ++bitsOmittedCount >= 8 ) { + bitsOmittedCount = 0; + index += 1; + } + } + + if ( bitCount > 0 ) { + accumulator = ( accumulator << 8 ) | bufferedReader.read(); + bits += 8; + } + } + } + + public void closeWriter() throws IOException { + if ( bits != 0 ) { + accumulator <<= 8 - bits; + bufferedWriter.write(accumulator); + } + + bufferedWriter.close(); + accumulator = 0; + bits = 0; + } + + public void closeReader() throws IOException { + bufferedReader.close(); + accumulator = 0; + bits = 0; + } + + private int accumulator, bits; + private BufferedWriter bufferedWriter; + private BufferedReader bufferedReader; + +} diff --git a/Task/Bitwise-IO/Julia/bitwise-io.julia b/Task/Bitwise-IO/Julia/bitwise-io.jl similarity index 100% rename from Task/Bitwise-IO/Julia/bitwise-io.julia rename to Task/Bitwise-IO/Julia/bitwise-io.jl diff --git a/Task/Bitwise-IO/Kotlin/bitwise-io.kotlin b/Task/Bitwise-IO/Kotlin/bitwise-io.kts similarity index 100% rename from Task/Bitwise-IO/Kotlin/bitwise-io.kotlin rename to Task/Bitwise-IO/Kotlin/bitwise-io.kts diff --git a/Task/Bitwise-IO/OCaml/bitwise-io-1.ocaml b/Task/Bitwise-IO/OCaml/bitwise-io-1.ml similarity index 100% rename from Task/Bitwise-IO/OCaml/bitwise-io-1.ocaml rename to Task/Bitwise-IO/OCaml/bitwise-io-1.ml diff --git a/Task/Bitwise-IO/OCaml/bitwise-io-2.ocaml b/Task/Bitwise-IO/OCaml/bitwise-io-2.ml similarity index 100% rename from Task/Bitwise-IO/OCaml/bitwise-io-2.ocaml rename to Task/Bitwise-IO/OCaml/bitwise-io-2.ml diff --git a/Task/Bitwise-IO/Rebol/bitwise-io.rebol b/Task/Bitwise-IO/Rebol/bitwise-io.rebol new file mode 100644 index 0000000000..80dccaaf08 --- /dev/null +++ b/Task/Bitwise-IO/Rebol/bitwise-io.rebol @@ -0,0 +1,59 @@ +Rebol [ + title: "Rosetta code: Bitwise IO" + file: %Bitwise_IO.r3 + url: https://rosettacode.org/wiki/Bitwise_IO + note: "Based on Vasyl Zubko's Red language implementation!" +] + +compress-7bit: function [ + "Pack 8-bit bytes into 7-bit chunks (lossless for 7-bit ASCII)" + str [string! binary!] +][ + buf: clear "" ;; string buffer for 7-bit bitstream + bits: enbase/flat str 2 ;; convert input to a flat binary string "0101..." + while [not tail? bits][ ;; take 7 bits out of every 8 + append buf copy/part next bits 7 ;; append bits 2..8 (skip the first bit of each byte) + bits: skip bits 8 ;; move to next 8-bit group + ] + ;; Pad to multiple of 8 bits so it can be debased to bytes + unless zero? (pad-bits: (length? buf) // 8) [ + append/dup buf #"0" 8 - pad-bits + ] + debase buf 2 ;; turn the 7-bit stream (padded) back into binary bytes +] + +decompress-7bit: function [ + "Unpack 7-bit chunks back to 8-bit by re-inserting the leading zero bit per group of 7" + bin [binary!] +][ + bits: enbase/flat bin 2 ;; bitstring of the compressed bytes + filled: 0 ;; counter within a 7-bit group + buf: clear #{} ;; output binary buffer + acc: clear "" ;; accumulator for 7 bits + + foreach bit bits [ + append acc bit ;; collect one bit + filled: filled + 1 + if filled = 7 [ + ;; Prepend a '0' to restore 8th bit, debase to a byte, append to output + append buf debase join #"0" acc 2 + clear acc + filled: 0 + ] + ] + ;; If padding produced a final 0 byte, drop it + if 0 == last buf [take/last buf] + to string! buf ;; return original as string +] + +;- DEMO: +in-string: "Rebol is not dead!" +compressed: compress-7bit in-string ;; compress to 7-bit packed binary +expanded: decompress-7bit compressed ;; decompress back to original + +print [ + "^/in-string :" in-string + "^/in-binary :" to binary! in-string + "^/compressed:" compressed + "^/expanded :" expanded +] diff --git a/Task/Bitwise-IO/Rust/bitwise-io.rust b/Task/Bitwise-IO/Rust/bitwise-io.rs similarity index 100% rename from Task/Bitwise-IO/Rust/bitwise-io.rust rename to Task/Bitwise-IO/Rust/bitwise-io.rs diff --git a/Task/Bitwise-IO/Seed7/bitwise-io.seed7 b/Task/Bitwise-IO/Seed7/bitwise-io.seed7 index a5764cfc78..413c230ed9 100644 --- a/Task/Bitwise-IO/Seed7/bitwise-io.seed7 +++ b/Task/Bitwise-IO/Seed7/bitwise-io.seed7 @@ -1,14 +1,7 @@ $ include "seed7_05.s7i"; include "bitdata.s7i"; - include "strifile.s7i"; -const proc: initWriteAscii (inout file: outFile, inout integer: bitPos) is func - begin - outFile.bufferChar := '\0;'; - bitPos := 0; - end func; - -const proc: writeAscii (inout file: outFile, inout integer: bitPos, in string: ascii) is func +const proc: writeAscii (inout msbOutBitStream: outStream, in string: ascii) is func local var char: ch is ' '; begin @@ -16,42 +9,38 @@ const proc: writeAscii (inout file: outFile, inout integer: bitPos, in string: a if ch > '\127;' then raise RANGE_ERROR; else - putBitsMsb(outFile, bitPos, ord(ch), 7); + putBits(outStream, ord(ch), 7); end if; end for; end func; -const proc: finishWriteAscii (inout file: outFile, inout integer: bitPos) is func +const proc: finishWriteAscii (inout msbOutBitStream: outStream) is func begin - putBitsMsb(outFile, bitPos, 0, 7); # Write a terminating NUL char. - write(outFile, chr(ord(outFile.bufferChar))); + putBits(outStream, 0, 7); # Write a terminating NUL char. + flush(outStream); end func; -const func string: readAscii (inout msbBitStream: aBitStream) is func +const func string: readAscii (inout msbInBitStream: inStream) is func result var string: stri is ""; local var char: ch is ' '; begin - while ch <> '\0;' do - ch := chr(getBits(aBitStream, 7)); + repeat + ch := chr(getBits(inStream, 7)); if ch <> '\0;' then stri &:= ch; end if; - end while; + until ch = '\0;'; end func; const proc: main is func local - var file: aFile is STD_NULL; - var integer: bitPos is 0; - var msbBitStream: aBitStream is msbBitStream.value; + var msbOutBitStream: outStream is msbOutBitStream.value; + var msbInBitStream: inStream is msbInBitStream.value; begin - aFile := openStriFile; - initWriteAscii(aFile, bitPos); - writeAscii(aFile, bitPos, "Hello, Rosetta Code!"); - finishWriteAscii(aFile, bitPos); - seek(aFile, 1); - aBitStream := openMsbBitStream(aFile); - writeln(literal(readAscii(aBitStream))); + writeAscii(outStream, "Hello, Rosetta Code!"); + finishWriteAscii(outStream); + inStream := openMsbInBitStream(getBytes(outStream)); + writeln(literal(readAscii(inStream))); end func; diff --git a/Task/Bitwise-operations/ALGOL-68/bitwise-operations-1.alg b/Task/Bitwise-operations/ALGOL-68/bitwise-operations-1.alg index 7fdf9b8d88..ea11b79d5f 100644 --- a/Task/Bitwise-operations/ALGOL-68/bitwise-operations-1.alg +++ b/Task/Bitwise-operations/ALGOL-68/bitwise-operations-1.alg @@ -1,8 +1,13 @@ -main:( +BEGIN + + BITS all bits mask = NOT 16r0; + LONG BITS long bits mask = LENG all bits mask; PRIO SLC = 8, SRC = 8; # SLC and SRC are not built in, define and overload them here # OP SLC = (BITS b, INT rotate) BITS: b SHL rotate OR b SHR ( bits width - rotate ); - OP SRC = (BITS b, INT rotate) BITS: b SHR rotate OR b SHL ( bits width - rotate ); + OP SRC = (BITS b, INT rotate) BITS: b SHR rotate OR SHORTEN ( long bits mask + AND ( LENG b SHL ( bits width - rotate ) ) + ); # SRC and SRL are non-standard, but versions are built in to ALGOL 68R's standard prelude # PRIO XOR = 2; @@ -10,7 +15,10 @@ main:( # XOR is non-standard, but a version is built in to ALGOL 68G's standard prelude # # ALGOL 68 has 5 different ways of representing a BINary BITS - Bases: 2, 4, 8, 16 and flip/flop # - FORMAT b5 = $"2r"2r32d," 4r"4r16d," 8r"8r11d," 16r"16r8d," "gl$; + FORMAT b5 = IF bits width > 32 + THEN $"2r"2r64d," 4r"4r32d,l" 8r"8r22d," 16r"16r16d,l" "gl$ + ELSE $"2r"2r32d," 4r"4r16d," 8r"8r11d," 16r"16r8d,l" "gl$ + FI; OP BBBBB = (BITS b)[]BITS: (b,b,b,b,b); PROC bitwise = (BITS a, BITS b, INT shift)VOID: @@ -61,4 +69,4 @@ CO bitwise(8r377,8r252,5); bitwise(16rff,16raa,5) END CO -) +END diff --git a/Task/Bitwise-operations/Ada/bitwise-operations.ada b/Task/Bitwise-operations/Ada/bitwise-operations.adb similarity index 100% rename from Task/Bitwise-operations/Ada/bitwise-operations.ada rename to Task/Bitwise-operations/Ada/bitwise-operations.adb diff --git a/Task/Bitwise-operations/AutoIt/bitwise-operations.autoit b/Task/Bitwise-operations/AutoIt/bitwise-operations.au3 similarity index 100% rename from Task/Bitwise-operations/AutoIt/bitwise-operations.autoit rename to Task/Bitwise-operations/AutoIt/bitwise-operations.au3 diff --git a/Task/Bitwise-operations/COBOL/bitwise-operations-1.cobol b/Task/Bitwise-operations/COBOL/bitwise-operations-1.cob similarity index 100% rename from Task/Bitwise-operations/COBOL/bitwise-operations-1.cobol rename to Task/Bitwise-operations/COBOL/bitwise-operations-1.cob diff --git a/Task/Bitwise-operations/COBOL/bitwise-operations-2.cobol b/Task/Bitwise-operations/COBOL/bitwise-operations-2.cob similarity index 100% rename from Task/Bitwise-operations/COBOL/bitwise-operations-2.cobol rename to Task/Bitwise-operations/COBOL/bitwise-operations-2.cob diff --git a/Task/Bitwise-operations/Crystal/bitwise-operations.cr b/Task/Bitwise-operations/Crystal/bitwise-operations.cr new file mode 100644 index 0000000000..3fa0470d8a --- /dev/null +++ b/Task/Bitwise-operations/Crystal/bitwise-operations.cr @@ -0,0 +1,9 @@ +def operations (x, y) + p! x, y, + x & y, x | y, x ^ y, + ~x, + x << y, x >> y, + x.rotate_left(y), x.rotate_right(y) +end + +operations 10, 2 diff --git a/Task/Bitwise-operations/Delphi/bitwise-operations.delphi b/Task/Bitwise-operations/Delphi/bitwise-operations.pas similarity index 100% rename from Task/Bitwise-operations/Delphi/bitwise-operations.delphi rename to Task/Bitwise-operations/Delphi/bitwise-operations.pas diff --git a/Task/Bitwise-operations/DuckDB/bitwise-operations-1.duckdb b/Task/Bitwise-operations/DuckDB/bitwise-operations-1.duckdb new file mode 100644 index 0000000000..d81bf307e5 --- /dev/null +++ b/Task/Bitwise-operations/DuckDB/bitwise-operations-1.duckdb @@ -0,0 +1,5 @@ +create or replace function task(a,b) as table ( + select a, b, a&b, a|b, xor(a, b), ~a, a << b, a >> b +); + +from task(10, 2); diff --git a/Task/Bitwise-operations/DuckDB/bitwise-operations-2.duckdb b/Task/Bitwise-operations/DuckDB/bitwise-operations-2.duckdb new file mode 100644 index 0000000000..2e48fb4dd1 --- /dev/null +++ b/Task/Bitwise-operations/DuckDB/bitwise-operations-2.duckdb @@ -0,0 +1,5 @@ +select 10 as v, + ~(v::BITSTRING), + ~(v::INT) as "~INT", + ~(v::BIGINT) as "~BIGINT", + ~(10::UINTEGER) as "~UINTEGER"; diff --git a/Task/Bitwise-operations/EasyLang/bitwise-operations.easy b/Task/Bitwise-operations/EasyLang/bitwise-operations.easy index 433a6625bb..800e7fa354 100644 --- a/Task/Bitwise-operations/EasyLang/bitwise-operations.easy +++ b/Task/Bitwise-operations/EasyLang/bitwise-operations.easy @@ -1,9 +1,10 @@ -# numbers are doubles, bit operations use 32 bits and are unsigned -x = 11 -y = 2 -print bitnot x -print bitand x y -print bitor x y -print bitxor x y -print bitshift x y -print bitshift x -y +# numbers are doubles, bit operations are unsigned, truncate +# the fractional part and use 53 integer bits +a = 14 +b = 3 +print bitand a b +print bitor a b +print bitxor a b +print bitshift a b +print bitshift a -b +print bitand a bitnot b diff --git a/Task/Bitwise-operations/Elena/bitwise-operations.elena b/Task/Bitwise-operations/Elena/bitwise-operations.elena index 941e955022..d176f667cd 100644 --- a/Task/Bitwise-operations/Elena/bitwise-operations.elena +++ b/Task/Bitwise-operations/Elena/bitwise-operations.elena @@ -2,18 +2,18 @@ import extensions; extension testOp { - bitwiseTest(y) - { - console.printLine(self," and ",y," = ",self & y); - console.printLine(self," or ",y," = ",self | y); - console.printLine(self," xor ",y," = ",self ^ y); - console.printLine("not ",self," = ",self.BInverted); - console.printLine(self," shr ",y," = ",self.shiftRight(y)); - console.printLine(self," shl ",y," = ",self.shiftLeft(y)); - } + bitwiseTest(y) + { + Console.printLine(self," and ",y," = ",self.band(y)); + Console.printLine(self," or ",y," = ",self.bor(y)); + Console.printLine(self," xor ",y," = ",self.bxor(y)); + Console.printLine("not ",self," = ",self.BInverted); + Console.printLine(self," shr ",y," = ",self.shiftRight(y)); + Console.printLine(self," shl ",y," = ",self.shiftLeft(y)); + } } -public program() +public Program() { - console.loadLineTo(new Integer()).bitwiseTest(console.loadLineTo(new Integer())) + Console.loadLineTo(new Integer()).bitwiseTest(Console.loadLineTo(new Integer())) } diff --git a/Task/Bitwise-operations/Elixir/bitwise-operations.elixir b/Task/Bitwise-operations/Elixir/bitwise-operations.ex similarity index 100% rename from Task/Bitwise-operations/Elixir/bitwise-operations.elixir rename to Task/Bitwise-operations/Elixir/bitwise-operations.ex diff --git a/Task/Bitwise-operations/Icon/bitwise-operations.icon b/Task/Bitwise-operations/Icon/bitwise-operations.icon index 4bcace1afa..92610583bb 100644 --- a/Task/Bitwise-operations/Icon/bitwise-operations.icon +++ b/Task/Bitwise-operations/Icon/bitwise-operations.icon @@ -1,3 +1,5 @@ +link bitint # for int2bit + procedure main() bitdemo(255,2) bitdemo(-15,3) diff --git a/Task/Bitwise-operations/Jq/bitwise-operations.jq b/Task/Bitwise-operations/Jq/bitwise-operations.jq new file mode 100644 index 0000000000..4724c12f65 --- /dev/null +++ b/Task/Bitwise-operations/Jq/bitwise-operations.jq @@ -0,0 +1,32 @@ +include "bitwise" {search: "."}; # adjust as required + +def leftshift($n; $width): + [(range(0,$n)| 0), limit($width - $n; bitwise)][:$width] | to_int; + +# Using a width of $width bits: x << n | x >> ($width-n) +def rotateLeft($x; $n; $width): + $x | bitwise_or(leftshift($n; $width); rightshift($width-$n)); + +# Using a width of $width bits: x << n | x >> ($width-n) +def rotateRight($x; $n; $width): + $x | bitwise_or(rightshift($n); leftshift($width-$n; $width) ); + +def task($x; $y): + def isInteger: type == "number" and . == round; + if ($x|isInteger|not) or ($y|isInteger|not) or + $x < 0 or $y < 0 or $x > 4294967295 or $y > 4294967295 + then "Operands must be in the range of a 32-bit unsigned integer" | error + else + " x = \($x)", + " y = \($y)", + " x & y = \(bitwise_and($x; $y))", + " x | y = \(bitwise_or($x; $y))", + " x ^ y = \(null | xor(x; $y))", + "~x = \(32 | flip($x))", + " x << y = \($x | leftshift($y))", + " x >> y = \($x | rightshift($y))", + " x rl y = \(rotateLeft($x; $y; 32))", + " x rr y = \(rotateRight($x; $y; 32))" + end; + +task(10; 2) diff --git a/Task/Bitwise-operations/Julia/bitwise-operations.julia b/Task/Bitwise-operations/Julia/bitwise-operations.jl similarity index 100% rename from Task/Bitwise-operations/Julia/bitwise-operations.julia rename to Task/Bitwise-operations/Julia/bitwise-operations.jl diff --git a/Task/Bitwise-operations/Kotlin/bitwise-operations.kotlin b/Task/Bitwise-operations/Kotlin/bitwise-operations.kts similarity index 100% rename from Task/Bitwise-operations/Kotlin/bitwise-operations.kotlin rename to Task/Bitwise-operations/Kotlin/bitwise-operations.kts diff --git a/Task/Bitwise-operations/M2000-Interpreter/bitwise-operations.m2000 b/Task/Bitwise-operations/M2000-Interpreter/bitwise-operations.m2000 new file mode 100644 index 0000000000..7185314544 --- /dev/null +++ b/Task/Bitwise-operations/M2000-Interpreter/bitwise-operations.m2000 @@ -0,0 +1,43 @@ +module binary_ops{ + select case random(1, 6) + case 1 + Double x=10, y=2 + case 2 + Decimal x=10, y=2 + case 3 + Integer x=10, y=2 + case 4 + Long x=10, y=2 + case 5 ' byte from 0 to 255 (unsigned) + Byte x=10, y=2 + case else + Long Long x=10, y=2 + end select + print type$(x) + //x & y values from 0 to 4294967295 + print binary.not(x)=4294967285, sint(binary.not(x))=-11 + print binary.and(x, y)=2 + print binary.or(x, y)=10 + // y values -31 to 31 + print binary.xor(x, y)=8 + print binary.shift(x, y)=40 + print binary.shift(x, -y)=2 + print binary.rotate(x, y)=40 + print binary.rotate(x, -y)=2147483650, sint(binary.rotate(x, -y))=-2147483646 + // Binary.Neg return Unsigned from signed values: -2147483648 (0x8000_0000&) to 2147483647 (0x7FFF_FFFF&) + // values>2147483647 return 2147483648 + // values <-2147483648 return 2147483647 + // 0xFFFF_ABCD& (signed value), 0xFFFF_ABCD unsinged value same bits + print 0xFFFF_ABCD&=-21555, 0xFFFF_ABCD=4294945741, sint(0xFFFF_ABCD)=-21555 + print Binary.Neg(0xFFFF_ABCD&)=21554, Binary.Not(0xFFFF_ABCD)=21554 + print sint(Binary.Neg(0xFFFF_ABCD&)+ uint(0xFFFF_ABCD&))=sint(Binary.Neg(0)) + // signed 0xFFFF_ABCD& has same bits as unsigned 0xFFFF_ABCD, + // but have different value as used in calculations + print Binary.Neg(0xFFFF_ABCD&)=Binary.Not(0xFFFF_ABCD), 0xFFFF_ABCD&<>0xFFFF_ABCD + print Binary.Neg(0x0FFF_ABCD&)=Binary.Not(0x0FFF_ABCD), 0xFFFF_ABCD&<>0xFFFF_ABCD + // Add (modulo 32), x unsigned and add a negate signed (converted to unsigned) + print binary.add(x, binary.neg(y), 1)=8 ' 10 - 2 =12 + print binary.add(x, binary.neg(-y), 1)=12 ' 10 - - 2 = 12 + print sint(binary.neg(x))=-11, binary.neg(x)=binary.not(x) +} +binary_ops diff --git a/Task/Bitwise-operations/Nim/bitwise-operations.nim b/Task/Bitwise-operations/Nim/bitwise-operations.nim index 6932b12574..d831e18c5f 100644 --- a/Task/Bitwise-operations/Nim/bitwise-operations.nim +++ b/Task/Bitwise-operations/Nim/bitwise-operations.nim @@ -1,4 +1,4 @@ -proc bitwise(a, b) = +proc bitwise[T: SomeInteger](a, b: T) = echo "a and b: " , a and b echo "a or b: ", a or b echo "a xor b: ", a xor b diff --git a/Task/Bitwise-operations/OCaml/bitwise-operations.ocaml b/Task/Bitwise-operations/OCaml/bitwise-operations.ml similarity index 100% rename from Task/Bitwise-operations/OCaml/bitwise-operations.ocaml rename to Task/Bitwise-operations/OCaml/bitwise-operations.ml diff --git a/Task/Bitwise-operations/PascalABC.NET/bitwise-operations.pas b/Task/Bitwise-operations/PascalABC.NET/bitwise-operations.pas new file mode 100644 index 0000000000..b1805c5213 --- /dev/null +++ b/Task/Bitwise-operations/PascalABC.NET/bitwise-operations.pas @@ -0,0 +1,9 @@ +begin + var (a,b) := ReadInteger2; + Println($'not {a} = {not a}'); + Println($'{a} and {b} = {a and b}'); + Println($'{a} or {b} = {a or b}'); + Println($'{a} xor {b} = {a xor b}'); + Println($'{a} shl {b} = {a shl b}'); + Println($'{a} shr {b} = {a shr b}'); +end. diff --git a/Task/Bitwise-operations/Pluto/bitwise-operations.pluto b/Task/Bitwise-operations/Pluto/bitwise-operations.pluto new file mode 100644 index 0000000000..a42f1b211c --- /dev/null +++ b/Task/Bitwise-operations/Pluto/bitwise-operations.pluto @@ -0,0 +1,20 @@ +-- Rotate left and right are not built-in but we use the +-- same 32-bit substitutes as in the Lua 5.3+ example. +local function rl(x, y) return ((x << y) & 0xffffffff) | (x >> (32 - y)) end + +local function rr(x, y) return (x >> y) | ((x << (32 - y)) & 0xffffffff) end + +local function bitwise(x, y) + print($" x = {x}") + print($" y = {y}") + print($" x & y = {x & y}") + print($" x | y = {x | y}") + print($" x ~ y = {x ~ y}") + print($"~x = {~x}") + print($" x << y = {x << y}") + print($" x >> y = {x >> y}") + print($" x rl y = {rl(x, y)}") + print($" x rr y = {rr(x, y)}") +end + +bitwise(10, 2) diff --git a/Task/Bitwise-operations/PowerShell/bitwise-operations-1.psh b/Task/Bitwise-operations/PowerShell/bitwise-operations-1.ps1 similarity index 100% rename from Task/Bitwise-operations/PowerShell/bitwise-operations-1.psh rename to Task/Bitwise-operations/PowerShell/bitwise-operations-1.ps1 diff --git a/Task/Bitwise-operations/PowerShell/bitwise-operations-2.psh b/Task/Bitwise-operations/PowerShell/bitwise-operations-2.ps1 similarity index 100% rename from Task/Bitwise-operations/PowerShell/bitwise-operations-2.psh rename to Task/Bitwise-operations/PowerShell/bitwise-operations-2.ps1 diff --git a/Task/Bitwise-operations/RISC-V-Assembly/bitwise-operations.asm b/Task/Bitwise-operations/RISC-V-Assembly/bitwise-operations.asm new file mode 100644 index 0000000000..a3766dfca1 --- /dev/null +++ b/Task/Bitwise-operations/RISC-V-Assembly/bitwise-operations.asm @@ -0,0 +1,295 @@ + # riscv assembly raspberry pico2 rp2350 +# program bitwise.s +# connexion putty com3 +/*********************************************/ +/* CONSTANTES */ +/********************************************/ +/* for this file see risc-v task include a file */ +.include "../../constantesRiscv.inc" + +/*******************************************/ +/* INITIALED DATAS */ +/*******************************************/ +.data +szMessStart: .asciz "Program riscv start.\r\n" +szCariageReturn: .asciz "\r\n" +szMessReg0: .asciz "Register s0:\r\n" +szMessReg1: .asciz "Register s1:\r\n" +szMessAnd: .asciz "And result:\r\n" +szMessOr: .asciz "Or result :\r\n" +szMessXor: .asciz "Xor result :\r\n" +szMessNot: .asciz "Not result :\r\n" +szMessNeg: .asciz "Neg result :\r\n" +szMessBset: .asciz "Set single bit result :\r\n" +szMessSll: .asciz "Shift left result :\r\n" +szMessSrl: .asciz "Shift right result :\r\n" +szMessSra: .asciz "Shift right arithmetic result :\r\n" +szMessRol: .asciz "Rotation left result :\r\n" +szMessRor: .asciz "Rotation right result :\r\n" +szMessBclr: .asciz "Clear single bit result :\r\n" +szMessBext: .asciz "Extraction single bit result :\r\n" +szMessBinv: .asciz "Inversion single bit result :\r\n" +szMessBrev: .asciz "Bit-reverse within each byte result :\r\n" +szMessClz: .asciz "Count leading zeroes result :\r\n" +szMessCtz: .asciz "Count trailing zeroes result :\r\n" +szMessCpop: .asciz "Population count result :\r\n" +szMessPack: .asciz "Pack two halfwords into one word result :\r\n" +szMessPackh: .asciz "Pack two byte into one halfword result :\r\n" +szMessZip: .asciz "Zip result :\r\n" +szMessUnzip: .asciz "Unzip result :\r\n" +.align 2 + +/*******************************************/ +/* UNINITIALED DATA */ +/*******************************************/ +.bss +.align 2 +sConvArea: .skip 24 +sConvBinaire: .skip 36 +/**********************************************/ +/* SECTION CODE */ +/**********************************************/ +.text +.global main + +main: + call stdio_init_all # général init +1: # start loop connexion + li a0,0 # raz argument register + call tud_cdc_n_connected # waiting for USB connection + beqz a0,1b # return code = zero ? + + la a0,szMessStart # message address + call writeString # display message + + la a0,szMessReg0 # message address + call writeString # display message + li s0,0b1100 + mv a0,s0 + call displayResult + + la a0,szMessReg1 # message address + call writeString # display message + li s1,0b1001 + mv a0,s1 + call displayResult + + la a0,szMessAnd # and + call writeString # display message + andi a0,s0,0b1001 # and immediat value + call displayResult + and a0,s0,s1 # register and + call displayResult + andn a0,s0,s1 # register and and not + call displayResult + + la a0,szMessOr # or + call writeString # display message + ori a0,s0,0b1001 # or immediat value + call displayResult + or a0,s0,s1 # or register + call displayResult + orn a0,s0,s1 # or and not register + call displayResult + orc.b a0,s0 # OR-combine of bits within each byte. Generates a mask of nonzero bytes + call displayResult + + + la a0,szMessXor # xor + call writeString # display message + xori a0,s0,0b1001 # xor immediat value + call displayResult + xor a0,s0,s1 # xor register + call displayResult + xnor a0,s0,s1 # Bitwise XOR with inverted operand. Equivalently, bitwise NOT of bitwise XOR + call displayResult + + la a0,szMessNot # not + call writeString # display message + not a0,s0 # not + call displayResult + + la a0,szMessNeg # negation + call writeString # display message + neg a0,s0 # negation + call displayResult + + la a0,szMessSll # shift left + call writeString # display message + slli a0,s0,11 # shift left immediat value + call displayResult + li t0,5 + sll a0,s0,t0 # shift left register + call displayResult + + la a0,szMessSrl # shift right + call writeString # display message + srli a0,s0,1 # shift right immediat value + call displayResult + li t0,5 + srl a0,s0,t0 # shift right register + call displayResult + + la a0,szMessSra # Shift right, arithmetic + call writeString # display message + srai a0,s0,1 # shift right arithmetic immediat value + call displayResult + li t0,5 + li t1,0b10000000000000001100000000000000 + sra a0,t1,t0 # shift right arithmetic register + call displayResult + + la a0,szMessRol # rotation left + call writeString # display message + li t0,5 + rol a0,s0,t0 # rotation left register + call displayResult + + la a0,szMessRor # rotation right + call writeString # display message + rori a0,s0,10 # rotation right immediat value + call displayResult + li t0,5 + ror a0,s0,t0 # rotation right register + call displayResult + + la a0,szMessBclr # Clear single bit. + call writeString # display message + bclri a0,s0,3 # Clear single bit. immediat value + call displayResult + li t0,2 + bclr a0,s0,t0 # Clear single bit. register + call displayResult + + la a0,szMessBext # Extraction single bit. + call writeString # display message + bexti a0,s0,3 # Extraction single bit. immediat value + call displayResult + li t0,2 + bext a0,s0,t0 # Extraction single bit. register + call displayResult + + la a0,szMessBinv # Inversion single bit. + call writeString # display message + binvi a0,s0,3 # Inversion bit. immediat value + call displayResult + li t0,2 + binv a0,s0,t0 # Inversion single bit. register + call displayResult + + la a0,szMessBset # Set single bit + call writeString # display message + bseti a0,s0,8 # Set single bit (immediate). + call displayResult + li t0,17 + bset a0,s0,t0 # Set single bit + call displayResult + + la a0,szMessClz # Count leading zeroes (starting from MSB, searching LSB-ward). + call writeString # display message + clz a0,s0 # + call displayResultD + + la a0,szMessCtz # Count trailing zeroes (starting from LSB, searching MSB-ward). + call writeString # display message + ctz a0,s0 # + call displayResultD + + la a0,szMessCpop # Population count + call writeString # display message + cpop a0,s0 # + call displayResultD + + la a0,szMessBrev # Bit-reverse within each byte + call writeString # display message + brev8 a0,s0 # + call displayResult + + la a0,szMessPack # Pack two halfwords into one word + call writeString # display message + li t0,0x1234 + li t1,0x5678 + pack a0,t1,t0 # + call displayResultHex + + la a0,szMessPackh # Pack two halfwords into one word + call writeString # display message + li t0,0x12 + li t1,0x34 + packh a0,t1,t0 # + call displayResultHex + + la a0,szMessZip # Interleave upper/lower half of register into odd/even bits of result + call writeString # display message + zip s2,s0 + mv a0,s2 # + call displayResult + + la a0,szMessUnzip # Deinterleave odd/even bits of register into upper/lower half of result + call writeString # display message + unzip a0,s2 # + call displayResult + call getchar +100: # final loop + j 100b + +/**********************************************/ +/* display binary Result */ +/**********************************************/ +/* a0 value */ +.equ LGZONECONV, 20 +displayResult: + addi sp, sp, -4 # reserve stack + sw ra, 0(sp) + la a1,sConvBinaire # conversion result address + call conversion2 # binary conversion + la a0,sConvBinaire # message address + call writeString # display message + la a0,szCariageReturn + call writeString +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret +/**********************************************/ +/* display Result décimal */ +/**********************************************/ +/* a0 value */ +.equ LGZONECONV, 20 +displayResultD: + addi sp, sp, -4 # reserve stack + sw ra, 0(sp) + la a1,sConvArea # conversion result address + call conversion10 # binary conversion + la a0,sConvArea # message address + call writeString # display message + la a0,szCariageReturn + call writeString +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret +/**********************************************/ +/* display hexadecimal result */ +/**********************************************/ +/* a0 value */ +.equ LGZONECONV, 20 +displayResultHex: + addi sp, sp, -4 # reserve stack + sw ra, 0(sp) + la a1,sConvArea # conversion result address + call conversion16 # conversion decimal + la a0,sConvArea # message address + call writeString # display message + la a0,szCariageReturn + call writeString +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret + +/************************************/ +/* file include Fonctions */ +/***********************************/ +/* for this file see risc-v task include a file */ +.include "../../includeFunctions.s" diff --git a/Task/Bitwise-operations/Raku/bitwise-operations.raku b/Task/Bitwise-operations/Raku/bitwise-operations.raku index a7596faadb..7cbeacac55 100644 --- a/Task/Bitwise-operations/Raku/bitwise-operations.raku +++ b/Task/Bitwise-operations/Raku/bitwise-operations.raku @@ -9,7 +9,8 @@ sub int-bits (Int $a, Int $b) { say ''; say_bit "$a", $a; say ''; - say_bit "2's complement $a", +^$a; + say_bit "1's complement (not) $a", +^$a; + say_bit "2's complement $a", +^$a + 1; say_bit "$a and $b", $a +& $b; say_bit "$a or $b", $a +| $b; say_bit "$a xor $b", $a +^ $b; diff --git a/Task/Bitwise-operations/Rebol/bitwise-operations.rebol b/Task/Bitwise-operations/Rebol/bitwise-operations.rebol new file mode 100644 index 0000000000..13a05d8bd0 --- /dev/null +++ b/Task/Bitwise-operations/Rebol/bitwise-operations.rebol @@ -0,0 +1,32 @@ +Rebol [ + title: "Rosetta code: Bitwise operations" + file: %Bitwise_operations.r3 + url: https://rosettacode.org/wiki/Bitwise_operations + needs: 3.10.0 +] + +do-test: function [code][ + res: try code + case [ + error? res [res: join "error: " res/id] + integer? res [res: enbase to-binary res 2] + ] + printf [-21 " == "] reduce [form code res] +] +foreach test [ + [10] + [2] + [10 AND 2] + [10 & 2] + [10 OR 2] + [10 | 2] + [10 XOR 2] + [10 >> 2] + [10 << 2] + [-65432] + [complement -65432] + [255] + [shift 255 -2] + [shift 255 56] + [shift/logical 255 56] +][ do-test test ] diff --git a/Task/Bitwise-operations/Rust/bitwise-operations.rust b/Task/Bitwise-operations/Rust/bitwise-operations.rs similarity index 100% rename from Task/Bitwise-operations/Rust/bitwise-operations.rust rename to Task/Bitwise-operations/Rust/bitwise-operations.rs diff --git a/Task/Bitwise-operations/Scheme/bitwise-operations-1.ss b/Task/Bitwise-operations/Scheme/bitwise-operations-1.scm similarity index 100% rename from Task/Bitwise-operations/Scheme/bitwise-operations-1.ss rename to Task/Bitwise-operations/Scheme/bitwise-operations-1.scm diff --git a/Task/Bitwise-operations/Scheme/bitwise-operations-2.ss b/Task/Bitwise-operations/Scheme/bitwise-operations-2.scm similarity index 100% rename from Task/Bitwise-operations/Scheme/bitwise-operations-2.ss rename to Task/Bitwise-operations/Scheme/bitwise-operations-2.scm diff --git a/Task/Bitwise-operations/Uiua/bitwise-operations.uiua b/Task/Bitwise-operations/Uiua/bitwise-operations.uiua new file mode 100644 index 0000000000..3b42c9fbd9 --- /dev/null +++ b/Task/Bitwise-operations/Uiua/bitwise-operations.uiua @@ -0,0 +1,9 @@ +a ← 10 +b ← 2 +# Experimental! +¬a # bitwise NOT +°⋯ /× ⋯ ⊟ a b # bitwise AND +°⋯ /∨ ⋯ ⊟ a b # bitwise OR +°⋯ /≠ ⋯ ⊟ a b # bitwise XOR +* a ⁿ:2 b # SHL +⌊÷: a ⁿ:2 b # ASR diff --git a/Task/Bitwise-operations/Uxntal/bitwise-operations.uxnatl b/Task/Bitwise-operations/Uxntal/bitwise-operations.uxnatl index 9e4335844f..695abf3123 100644 --- a/Task/Bitwise-operations/Uxntal/bitwise-operations.uxnatl +++ b/Task/Bitwise-operations/Uxntal/bitwise-operations.uxnatl @@ -1,67 +1,73 @@ -|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 ] +%\n { 0a } %\s { 20 } %\0 { 00 } +%newline { [ LIT2 \n -Console/write ] DEO } + +%not { #ff EOR } +%and { AND } +%or { ORA } +%xor { EOR } +%shl { #40 SFT SFT } +%shr { SFT } +%rol { #40 SFT #00 ROT ROT SFT2 ORA } +%ror { SWP #00 ROT SFT2 ORA } + +|18 @Console/write + +|100 + +#0a02 +DUP2 SWP ;msgs/a print/arg ;msgs/b print/arg +bitwise -( 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 + ;msgs/not print/str ;msgs/a print/str + ;msgs/equ print/str OVR not print/result + ;msgs/and print/label DUP2 and print/result + ;msgs/or print/label DUP2 or print/result + ;msgs/xor print/label DUP2 xor print/result + ;msgs/shl print/label DUP2 shl print/result + ;msgs/shr print/label DUP2 shr print/result + ;msgs/rol print/label DUP2 rol print/result + ;msgs/ror print/label ror !print/result -@halt ( -- ) - #01 .System/halt DEO - BRK +@print/label ( label* -- ) + ;msgs/a /str + /str + ;msgs/b /str + ;msgs/equ !/str -@ ( a name* -- ) - ;Labels/equ - JMP2r - -@ ( a -- ) - ;Labels/newline - JMP2r - -@ ( label* -- ) - ;Labels/a - - ;Labels/b - ;Labels/equ - JMP2r - -@ ( byte -- ) +@print/byte ( 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 + DUP #04 SFT /nibble + ( >> ) + +@print/nibble ( -- ) + #0f AND DUP #09 GTH #27 MUL ADD [ LIT "0 ] ADD .Console/write DEO + JMP2r -@ ( str* -- ) - &while ( -- ) - LDAk .Console/write DEO - INC2 LDAk ?&while +@print/arg ( a name* -- ) + /str ;msgs/equ /str + ( >> ) + +@print/result ( a -- ) + /byte newline + JMP2r + +@print/str ( str* -- ) + LDAk .Console/write DEO + INC2 LDAk ?/str 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 +@msgs [ + &a "a \s \0 + &b "b \s \0 + &equ "= \s \0 + ¬ "NOT \s \0 + &and "AND \s \0 + &or "OR \s \0 + &xor "XOR \s \0 + &shl "SHL \s \0 + &shr "SHR \s \0 + &rol "ROL \s \0 + &ror "ROR \s \0 ] diff --git a/Task/Bitwise-operations/V-(Vlang)/bitwise-operations.v b/Task/Bitwise-operations/V-(Vlang)/bitwise-operations.v new file mode 100644 index 0000000000..9f8b2187cb --- /dev/null +++ b/Task/Bitwise-operations/V-(Vlang)/bitwise-operations.v @@ -0,0 +1,9 @@ +fn bitwise(a int, b int) { + println("a AND b: ${a & b}") + println("a OR b: ${a | b}") + println("a XOR b: ${a ^ b}") + println("NOT a: ${~a}") + println("a SHL b: ${a << b}") // left shift + println("a SHR b: ${a >> b}") // right shift + println("a USHR b: ${a >>> b}") // unsigned right shift +} diff --git a/Task/Blum-integer/AWK/blum-integer.awk b/Task/Blum-integer/AWK/blum-integer.awk new file mode 100644 index 0000000000..a50028c636 --- /dev/null +++ b/Task/Blum-integer/AWK/blum-integer.awk @@ -0,0 +1,53 @@ +# syntax: GAWK -f BLUM_INTEGER.AWK +# converted from FutureBasic +# +# sorting: +# PROCINFO["sorted_in"] is used by GAWK +# SORTTYPE is used by Thompson Automation's TAWK +# +BEGIN { + n = 3 + prime2 = 0 + print("The first 50 Blum integers:") + while (1) { + if (is_semiprime(n)) { + if (prime1 % 4 == 3) { + prime2 = n / prime1 + if ((prime2 != prime1) && (prime2 % 4 == 3)) { + arr[substr(n,length(n),1)]++ + total++ + if (++count <= 50) { + printf("%4d%s",n,count%10?"":"\n") + } + if (count ~ /^(26828|[1-4]00000)$/) { + printf("\nThe %6dth Blum integer: %7d",count,n) + if (count >= 400000) { + break + } + } + } + } + } + n += 2 + } + PROCINFO["sorted_in"] = "@ind_num_asc" ; SORTTYPE = 1 + printf("\n\nFor Blum integers up to %d:\n",count) + for (i in arr) { + printf("%7.3f%% end in %d\n",arr[i]/total*100,i) + } + exit(0) +} +function is_semiprime(n, c,d) { + c = 0 + d = 3 + while (d * d <= n) { + while (n % d == 0) { + if (c == 2) { return(0) } + n /= d + c++ + } + d += 2 + } + prime1 = n + return(c == 1) +} diff --git a/Task/Blum-integer/Ada/blum-integer.adb b/Task/Blum-integer/Ada/blum-integer.adb new file mode 100644 index 0000000000..5c8e2c59ca --- /dev/null +++ b/Task/Blum-integer/Ada/blum-integer.adb @@ -0,0 +1,89 @@ +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; +with Ada.Float_Text_IO; use Ada.Float_Text_IO; + +procedure Blum is + + Inc : Constant array (1 .. 8) of Integer := (4, 2, 4, 2, 4, 6, 2, 6); + + function Is_Prime (N : Integer) return Boolean is + D : Integer := 5; + begin + if N < 2 then return False; end if; + if N mod 2 = 0 then return N = 2; end if; + if N mod 3 = 0 then return N = 3; end if; + + while D * D <= N loop + if N mod D = 0 then return False; end if; + D := D + 2; + if N mod D = 0 then return False; end if; + D := D + 4; + end loop; + + return True; + end Is_Prime; + + function First_Prime_Factor (N : Integer) return Integer is + D : Integer := 7; + I : Integer := 1; + begin + if N = 1 then return 1; end if; + if N mod 3 = 0 then return 3; end if; + if N mod 5 = 0 then return 5; end if; + + while D * D <= N loop + if N mod D = 0 then + return D; + end if; + D := D + Inc(I); + I := (I mod 8) + 1; + end loop; + + return N; + end First_Prime_Factor; + + I, Blum_Count : Integer := 1; + J, P, Q : Integer; + Blums : Array (1 .. 50) of Integer; + Counts : Array (1 .. 4) of Integer := (others => 0); + Final_Digits : Array (1 .. 4) of Integer := (1, 3, 7, 9); + +begin + loop + P := First_Prime_Factor(I); + if P mod 4 = 3 then + Q := I / P; + if Q /= P and Q mod 4 = 3 and Is_Prime(Q) then + if Blum_Count < 51 then Blums(Blum_Count) := I; end if; + Counts(((I mod 10) / 3) + 1) := Counts(((I mod 10) / 3) + 1) + 1; + Blum_Count := Blum_Count + 1; + if Blum_Count = 51 then + Put("First 50 Blum Integers:"); New_Line; + for J in Integer range 1 .. 50 loop + Put(Item => Blums(J), Width => 3); Put(" "); + if J mod 10 = 0 then New_Line; end if; + end loop; + New_Line; + elsif Blum_Count = 26829 or Blum_Count mod 100000 = 1 then + Put("The "); Put(Item => Blum_Count, Width => 7); + Put("th Blum Integer is: "); Put(Item => I, Width => 9); + New_Line; + if Blum_Count = 400001 then + New_Line; Put("% Distribution of the First 400,000 Blum Integers:"); New_Line; + for J in Integer range 1 .. 4 loop + Put(" "); Put(Item => Float(Counts(J)) / 4000.0, Fore => 2, Aft => 3, Exp => 0); + Put("% end in "); Put(Item => Final_Digits(J), Width => 1); + New_Line; + end loop; + exit; + end if; + end if; + end if; + end if; + if I mod 5 = 3 then + I := I + 4; + else + I := I + 2; + end if; + end loop; +end Blum; diff --git a/Task/Blum-integer/Arturo/blum-integer.arturo b/Task/Blum-integer/Arturo/blum-integer.arturo new file mode 100644 index 0000000000..2ca6df51a1 --- /dev/null +++ b/Task/Blum-integer/Arturo/blum-integer.arturo @@ -0,0 +1,17 @@ +blum?: function [n][ + if any? @[n < 21, even? n, zero? n % 5] + -> return false + + f: factors.prime n + if or? [2 <> size f][f\0 = f\1] + -> return false + + every? f => [3 = & % 4] +] + +print "First 50 Blum numbers:" +1..∞ | select.first: 50 => blum? + | split.every: 10 + | loop => [print map & 'x -> pad to :string x 4] + +print ["\n26828th Blum number:" select.n:26828 1..∞ => blum?] diff --git a/Task/Blum-integer/C++/blum-integer.cpp b/Task/Blum-integer/C++/blum-integer.cpp index 6e85a93099..ffa52d38cd 100644 --- a/Task/Blum-integer/C++/blum-integer.cpp +++ b/Task/Blum-integer/C++/blum-integer.cpp @@ -4,24 +4,24 @@ #include #include -bool is_prime_type_3(const int32_t number) { +bool is_prime_type_3(const uint32_t& number) { if ( number < 2 ) return false; if ( number % 2 == 0 ) return false; if ( number % 3 == 0 ) return number == 3; - for ( int divisor = 5; divisor * divisor <= number; divisor += 2 ) { + for ( uint32_t divisor = 5; divisor * divisor <= number; divisor += 2 ) { if ( number % divisor == 0 ) { return false; } } return number % 4 == 3; } -int32_t least_prime_factor(const int32_t number) { +uint32_t least_prime_factor(const uint32_t& number) { if ( number == 1 ) { return 1; } if ( number % 3 == 0 ) { return 3; } if ( number % 5 == 0 ) { return 5; } - for ( int divisor = 7; divisor * divisor <= number; divisor += 2 ) { + for ( uint32_t divisor = 7; divisor * divisor <= number; divisor += 2 ) { if ( number % divisor == 0 ) { return divisor; } } @@ -29,15 +29,15 @@ int32_t least_prime_factor(const int32_t number) { } int main() { - int32_t blums[50]; - int32_t blum_count = 0; - int32_t last_digit_counts[10] = {}; - int32_t number = 1; + uint32_t blums[50]; + uint32_t blum_count = 0; + uint32_t last_digit_counts[10] = {}; + uint32_t number = 1; while ( blum_count < 400'000 ) { - const int32_t prime = least_prime_factor(number); + const uint32_t prime = least_prime_factor(number); if ( prime % 4 == 3 ) { - const int32_t quotient = number / prime; + const uint32_t quotient = number / prime; if ( quotient != prime && is_prime_type_3(quotient) ) { if ( blum_count < 50 ) { blums[blum_count] = number; @@ -46,7 +46,7 @@ int main() { blum_count += 1; if ( blum_count == 50 ) { std::cout << "The first 50 Blum integers:" << std::endl; - for ( int32_t i = 0; i < 50; ++i ) { + for ( uint32_t i = 0; i < 50; ++i ) { std::cout << std::setw(3) << blums[i] << ( ( i % 10 == 9 ) ? "\n" : " " ); } std::cout << std::endl; @@ -54,7 +54,8 @@ int main() { std::cout << "The " << std::setw(6) << blum_count << "th Blum integer is: " << std::setw(7) << number << std::endl; if ( blum_count == 400'000 ) { - std::cout << "\nPercent distribution of the first 400000 Blum integers:" << std::endl; + std::cout << "\n" << "Percent distribution of the first 400000 Blum integers:" + << std::endl; for ( const int32_t& i : { 1, 3, 7, 9 } ) { std::cout << " " << std::setw(6) << std::setprecision(5) << (double) last_digit_counts[i] / 4'000 << "% end in " << i << std::endl; diff --git a/Task/Blum-integer/Common-Lisp/blum-integer.lisp b/Task/Blum-integer/Common-Lisp/blum-integer.lisp new file mode 100644 index 0000000000..6f3c559ebb --- /dev/null +++ b/Task/Blum-integer/Common-Lisp/blum-integer.lisp @@ -0,0 +1,47 @@ +(defun is-factor (x y) + (zerop (mod x y))) + +(defun is-congruent (num a n) + (= (mod num n) a)) + +(defun is-prime (n) + (cond ((< n 4) (or (= n 2) (= n 3))) + ((or (zerop (mod n 2)) (zerop (mod n 3))) nil) + (t (loop for i from 5 to (floor (sqrt n)) by 6 + never (or (is-factor n i) + (is-factor n (+ i 2))))))) + +(defun first-factor (n) + (loop for i from 2 to (floor (sqrt n)) + thereis (if (is-factor n i) i nil))) + +(defun is-blum (n) + (let ((factor (first-factor n))) + (and factor + (is-congruent factor 3 4) + (/= factor (/ n factor)) + (is-congruent (/ n factor) 3 4) + (is-prime factor) + (is-prime (/ n factor))))) + +(defun main () + (let ((n 0) + (i 1) + (blums '()) + (counts '())) + (dotimes (i 10) (push (cons i 0) counts)) + (loop while (<= n 400000) + do (setf i (+ i 2)) + (when (is-blum i) + (incf n) + (incf (cdr (assoc (mod i 10) counts))) + (when (<= n 50) + (push i blums) + (when (= n 50) + (format t "First 50 Blum integers:~%") + (format t "~{~5d~5d~5d~5d~5d~5d~5d~5d~5d~5d~%~}~%" (reverse blums)))) + (if (find n '(26828 100000 200000 300000 400000)) + (format t "The ~7:dth Blum integer is: ~9:d~%" n i)))) + (format t "~%% distribution of the first 400,000 Blum integers:~%") + (dolist (x '(1 3 7 9)) + (format t "~3$% end in ~a~%" (/ (cdr (assoc x counts)) 4000) x)))) diff --git a/Task/Blum-integer/EasyLang/blum-integer.easy b/Task/Blum-integer/EasyLang/blum-integer.easy index 7b73286f92..603f83fb51 100644 --- a/Task/Blum-integer/EasyLang/blum-integer.easy +++ b/Task/Blum-integer/EasyLang/blum-integer.easy @@ -2,32 +2,27 @@ fastfunc semiprim n . d = 3 while d * d <= n while n mod d = 0 - if c = 2 - return 0 - . + if c = 2 : return 0 n /= d c += 1 . d += 2 . - if c = 1 - return n - . + if c = 1 : return n + return 0 . print "The first 50 Blum integers:" n = 3 -numfmt 0 4 +numfmt 4 0 repeat prim1 = semiprim n - if prim1 <> 0 - if prim1 mod 4 = 3 - prim2 = n div prim1 - if prim2 <> prim1 and prim2 mod 4 = 3 - c += 1 - if c <= 50 - write n - if c mod 10 = 0 ; print "" ; . - . + if prim1 <> 0 and prim1 mod 4 = 3 + prim2 = n div prim1 + if prim2 <> prim1 and prim2 mod 4 = 3 + c += 1 + if c <= 50 + write n + if c mod 10 = 0 : print "" . . . diff --git a/Task/Blum-integer/Fortran/blum-integer.f b/Task/Blum-integer/Fortran/blum-integer.f new file mode 100644 index 0000000000..1108cc2fbe --- /dev/null +++ b/Task/Blum-integer/Fortran/blum-integer.f @@ -0,0 +1,158 @@ +program BlumInteger + use, intrinsic :: iso_fortran_env, only: int32, int64 + implicit none + + integer(int32), parameter :: LIMIT = 10*1000*1000 + integer(int32), allocatable :: BlumPrimes(:) + integer(int32), allocatable :: BlumPrimes2(:) + logical :: BlumField(0:LIMIT) + integer(int32) :: EndDigit(0:9) + integer(int64) :: k + integer(int32) :: n, idx, j, P4n3Cnt,xx,yy + call system_clock(count=xx) + call Sieve4n_3_Primes(LIMIT, BlumPrimes2) +! allocate(blumprimes(0:size(BlumPrimes2)-1)) +! The blumprimes2 array is allocated in the subroutine as a zero based array +! but, the main program doesn't know that and assumes it's 1 based so we allocate +! a zero based array then use move_alloc to correctly resize it a transfer the data + allocate(blumprimes(0:1)) + call move_alloc(blumprimes2,blumprimes) + P4n3Cnt = size(BlumPrimes) -1 + print *, 'There are ', CommaUint(int(P4n3Cnt, int64)), ' needed primes 4*n+3 to Limit ', CommaUint(int(LIMIT, int64)) + P4n3Cnt = P4n3Cnt - 1 + print * + + ! Generate Blum-Integers + BlumField = .false. + do idx = 0, P4n3Cnt + n = BlumPrimes(idx) + do j = idx+1, P4n3Cnt + k = int(n, int64) * int(BlumPrimes(j), int64) + if (k > LIMIT) exit + BlumField(k) = .true. + end do + end do + call system_clock(count=yy) + print *, 'First 50 Blum-Integers ' + idx = 0 + j = 0 + do + do while (idx < LIMIT .and. .not. BlumField(idx)) + idx = idx + 1 + end do + if (idx == LIMIT) exit + if (mod(j, 10) == 0 .and. j /= 0) print * + write(*, '(I5)', advance='no') idx + j = j + 1 + idx = idx + 1 + if (j >= 50) exit + end do + print '(//)' + + print *, ' relative occurence of digit' + print *, ' n.th |BlumInteger|Digit: 1 3 7 9' + idx = 0 + j = 0 + n = 0 + k = 26828 + EndDigit = 0 + do + do while (idx < LIMIT .and. .not. BlumField(idx)) + idx = idx + 1 + end do + if (idx == LIMIT) exit + ! Count last decimal digit + EndDigit(mod(idx, 10)) = EndDigit(mod(idx, 10)) + 1 + j = j + 1 + if (j == k) then + write(*, '(A10,A1,A11,A1)', advance='no') CommaUint(int(j, int64)), '|', CommaUint(int(idx, int64)), '|' + write(*, '(F7.3,A4)', advance='no') real(EndDigit(1))/j*100, '% |' + write(*, '(F7.3,A4)', advance='no') real(EndDigit(3))/j*100, '% |' + write(*, '(F7.3,A4)', advance='no') real(EndDigit(7))/j*100, '% |' + write(*, '(F7.3,A2)') real(EndDigit(9))/j*100, '%' + if (k < 100000) then + k = 100000 + else + k = k + 100000 + end if + end if + idx = idx + 1 + if (j >= 400000) exit + end do + print '(/,a,f8.6,1x,a)', 'Elapsed time = ',(yy-xx)/1000.0,'seconds' +contains + + subroutine Sieve4n_3_Primes(Limit, P4n3) + use iso_fortran_env + integer(int32), intent(in) :: Limit + integer(int32), allocatable, intent(out) :: P4n3(:) + integer(kind=1), allocatable :: sieve(:) + integer(int32) :: BlPrCnt, idx, n, j, sieve_size + + sieve_size = (Limit / 3 - 3) / 4 + 1 + allocate(sieve(0:sieve_size-1)) + allocate(P4n3(0:sieve_size-1)) + + sieve = 0 + BlPrCnt = 0 + idx = 0 + do + if (sieve(idx) == 0) then + n = idx*4 + 3 + P4n3(BlPrCnt) = n + BlPrCnt = BlPrCnt + 1 + j = idx + n + if (j > ubound(sieve, 1)) exit + do while (j <= ubound(sieve, 1)) + sieve(j) = 1 + j = j + n + end do + end if + idx = idx + 1 + if (idx > ubound(sieve, 1)) exit + end do + ! Collect the rest + do idx = idx, ubound(sieve, 1) + if (sieve(idx) == 0) then + P4n3(BlPrCnt) = idx*4 + 3 + BlPrCnt = BlPrCnt + 1 + end if + end do + P4n3 = P4n3(0:BlPrCnt-1) + end subroutine Sieve4n_3_Primes + + function CommaUint(n) result(res) + integer, parameter :: sizer = 30 + integer(int64), intent(in) :: n + character(:), allocatable :: res + character(len=sizer) :: temp + integer :: fromIdx, toIdx, i + character :: pRes(sizer) + + write(temp, '(I0)') n + fromIdx = len_trim(temp) + toIdx = fromIdx - 1 + if (toIdx < 3) then + res = temp(1:fromIdx) + return + end if + allocate(res, mold=repeat(' ',sizer)) + toIdx = 4*(toIdx / 3) + mod(toIdx, 3) + 1 + pRes = ' ' + + do i = 1, fromIdx + pRes(toIdx) = temp(fromIdx-i+1:fromIdx-i+1) + toIdx = toIdx - 1 + if (mod(i, 3) == 0 .and. i /= fromIdx) then + pRes(toIdx) = ',' + toIdx = toIdx - 1 + end if + end do + do i = 1,sizer ! Go from character array to string + res(I:I) = pRes(i) + end do +! + res = trim(adjustl(Res)) + end function CommaUint + +end program BlumInteger diff --git a/Task/Blum-integer/FreeBASIC/blum-integer.basic b/Task/Blum-integer/FreeBASIC/blum-integer.basic index 8b1bdd7df5..4f8b7da16f 100644 --- a/Task/Blum-integer/FreeBASIC/blum-integer.basic +++ b/Task/Blum-integer/FreeBASIC/blum-integer.basic @@ -1,39 +1,76 @@ -Dim Shared As Uinteger Prime1 -Dim As Uinteger n = 3, c = 0, Prime2 +#include "isprime.bas" -Function isSemiprime(n As Uinteger) As Boolean - Dim As Uinteger d = 3, c = 0 - While d*d <= n - While n Mod d = 0 - If c = 2 Then Return False - n /= d - c += 1 - Wend - d += 2 - Wend - Prime1 = n - Return c = 1 +Type PrimeHelper + inc(7) As Integer + idx As Integer +End Type + +Function initPrimeHelper() As PrimeHelper + Dim helper As PrimeHelper + helper.inc(0) = 4 : helper.inc(1) = 2 : helper.inc(2) = 4 + helper.inc(3) = 2 : helper.inc(4) = 4 : helper.inc(5) = 6 + helper.inc(6) = 2 : helper.inc(7) = 6 + helper.idx = 0 + Return helper End Function -Print "The first 50 Blum integers:" -Do - If isSemiprime(n) Then - If Prime1 Mod 4 = 3 Then - Prime2 = n / Prime1 - If (Prime2 <> Prime1) And (Prime2 Mod 4 = 3) Then - c += 1 - If c <= 50 Then - Print Using "####"; n; - If c Mod 10 = 0 Then Print - End If - If c >= 26828 Then - Print !"\nThe 26828th Blum integer is: " ; n - Exit Do +Function firstPrimeFactor(n As Integer) As Integer + If n = 1 Then Return 1 + If n Mod 3 = 0 Then Return 3 + If n Mod 5 = 0 Then Return 5 + + Dim helper As PrimeHelper = initPrimeHelper() + Dim k As Integer = 7 + + While k * k <= n + If n Mod k = 0 Then Return k + k += helper.inc(helper.idx) + helper.idx = (helper.idx + 1) Mod 8 + Wend + + Return n +End Function + +Sub main() + Dim As Integer blum(49), counts(9) + Dim As Integer bc = 0, i = 1, p, q + Dim As Integer j + + Dim As Double t0 = Timer + Do + p = firstPrimeFactor(i) + If p Mod 4 = 3 Then + q = i \ p + If q <> p Andalso q Mod 4 = 3 Andalso isPrime(q) Then + If bc < 50 Then blum(bc) = i + counts(i Mod 10) += 1 + bc += 1 + + If bc = 50 Then + Print "First 50 Blum integers:" + For j = 0 To 49 + Print Using "####"; blum(j); + If (j + 1) Mod 10 = 0 Then Print + Next + Print + Elseif bc = 26828 Orelse bc Mod 100000 = 0 Then + Print Using "The ###,###th Blum integer is: #,###,###"; bc; i + + If bc = 400000 Then + Print !"\n% distribution of the first 400,000 Blum integers:" + For j = 1 To 9 Step 2 + If j <> 5 Then Print Using " ##.###% end in #"; (counts(j)/4000); j + Next + Exit Do + End If End If End If End If - End If - n += 2 -Loop + i += Iif(i Mod 5 = 3, 4, 2) + Loop + Print Chr(10); Timer - t0; " sec." +End Sub + +main() Sleep diff --git a/Task/Blum-integer/Frink/blum-integer.frink b/Task/Blum-integer/Frink/blum-integer.frink new file mode 100644 index 0000000000..7f566d6cf6 --- /dev/null +++ b/Task/Blum-integer/Frink/blum-integer.frink @@ -0,0 +1,27 @@ +isBlum = {|x| + f = factorFlat[x] + if length[f] != 2 + return false + + f1 = first[f] + f2 = last[f] + return (f1 != f2) and (first[f] mod 4 == 3) and (last[f] mod 4 == 3) +} + +println["First 50:"] +println[first[select[count[1], isBlum], 50]] + +ret = new array +for n = [26828, 100000, 200000, 300000, 400000] + ret.push[["${n}th is: ", nth1[select[count[1], isBlum], n]]] + +println[formatTable[ret, "right"]] + +d = new dict +for n = first[select[count[1], isBlum], 400000] + d.increment[right[toString[n],1]] + +println["Distribution of the first 400000 Blum integers:"] +sum = sum[d.values[]] +for k = sort[d.keys[]] + println[formatFix[d@k / sum, "percent", 3] + " end in $k"] diff --git a/Task/Blum-integer/FutureBasic/blum-integer.basic b/Task/Blum-integer/FutureBasic/blum-integer.basic new file mode 100644 index 0000000000..86d825bda9 --- /dev/null +++ b/Task/Blum-integer/FutureBasic/blum-integer.basic @@ -0,0 +1,47 @@ +begin globals +UInt32 gPrime1 +end globals + +local fn IsSemiprime( n as UInt32 ) as BOOL + BOOL result = NO + UInt32 d = 3, c = 0 + while d * d <= n + while ( n % d = 0 ) + if ( c == 2 ) then return NO + n /= d + c += 1 + wend + d += 2 + wend + gPrime1 = n + result = ( c == 1 ) +end fn = result + +void local fn BlumIntegers + UInt32 prime2 = 0, n = 3, c = 0 + + print @"The first 50 Blum integers:" + while ( 1 ) + if ( fn IsSemiprime( n ) ) + if ( gPrime1 % 4 == 3 ) + prime2 = n / gPrime1 + if ( prime2 != gPrime1 ) && ( prime2 % 4 == 3 ) + c++ + if ( c <= 50 ) + printf @"%4d\b",n + if ( c % 10 == 0 ) then print + end if + if ( c >= 26828 ) + print : print @"The 26828th Blum integer is: "; n + break + end if + end if + end if + end if + n += 2 + wend +end fn + +fn BlumIntegers + +HandleEvents diff --git a/Task/Blum-integer/Gambas/blum-integer.gambas b/Task/Blum-integer/Gambas/blum-integer.gambas index 027cc6a610..ce94e9d661 100644 --- a/Task/Blum-integer/Gambas/blum-integer.gambas +++ b/Task/Blum-integer/Gambas/blum-integer.gambas @@ -1,44 +1,67 @@ -Public Prime1 As Integer +Use "isprime.bas" -Public Sub Main() +Private inc As Integer[] = [4, 2, 4, 2, 4, 6, 2, 6] - Dim n As Integer = 3, c As Integer = 0, Prime2 As Integer +Private Function FirstPrimeFactor(n As Long) As Long - Print "The first 50 Blum integers:" - Do - If isSemiprime(n) Then - If Prime1 Mod 4 = 3 Then - Prime2 = n / Prime1 - If (Prime2 <> Prime1) And (Prime2 Mod 4 = 3) Then - c += 1 - If c <= 50 Then - Print Format$(n, "####"); - If c Mod 10 = 0 Then Print - End If - If c >= 26828 Then - Print "\nThe 26828th Blum integer is: "; n - Break - End If - End If - End If - End If - n += 2 - Loop + If n = 1 Then Return 1 + If n Mod 3 = 0 Then Return 3 + If n Mod 5 = 0 Then Return 5 + + Dim k As Long = 7 + Dim i As Integer = 0 + + While k * k <= n + If n Mod k = 0 Then Return k + k += inc[i] + i = (i + 1) Mod 8 + Wend + + Return n End -Function isSemiprime(n As Integer) As Boolean +Public Sub Main() - Dim d As Integer = 3, c As Integer = 0 - While d * d <= n - While n Mod d = 0 - If c = 2 Then Return False - n /= d - c += 1 - Wend - d += 2 + Dim blum As New Long[50] + Dim counts As New Collection + + counts[1] = 0 + counts[3] = 0 + counts[7] = 0 + counts[9] = 0 + + Dim bc As Long = 0, i As Long = 1 + + While True + Dim p As Long = FirstPrimeFactor(i) + If p Mod 4 = 3 Then + Dim q As Long = i \ p + If q <> p And q Mod 4 = 3 And IsPrime(q) Then + If bc < 50 Then blum[bc] = i + counts[i Mod 10] += 1 + bc += 1 + + If bc = 50 Then + Print "First 50 Blum integers:" + For j As Integer = 0 To 49 + Print Format(blum[j], "####"); " "; + If (j + 1) Mod 10 = 0 Then Print + Next + Print + Else If bc = 26828 Or bc Mod 100000 = 0 Then + Print "The "; Format(bc, " ###,###"); "th Blum integer is: "; Format(i, " #,###,###") + If bc = 400000 Then + Print Chr(10); "% distribution of the first 400,000 Blum integers:" + For Each j As Integer In [1, 3, 7, 9] + Print Format(counts[j] / 4000, " ##.###"); "% end in "; j + Next + Return + Endif + Endif + Endif + Endif + i += If(i Mod 5 = 3, 4, 2) Wend - Prime1 = n - Return c = 1 -End Function +End diff --git a/Task/Blum-integer/Julia/blum-integer.julia b/Task/Blum-integer/Julia/blum-integer.jl similarity index 100% rename from Task/Blum-integer/Julia/blum-integer.julia rename to Task/Blum-integer/Julia/blum-integer.jl diff --git a/Task/Blum-integer/OxygenBasic/blum-integer.basic b/Task/Blum-integer/OxygenBasic/blum-integer.basic new file mode 100644 index 0000000000..50ba04d0a0 --- /dev/null +++ b/Task/Blum-integer/OxygenBasic/blum-integer.basic @@ -0,0 +1,78 @@ +#include "isprime.bas" +uses console + +dim inc(7) as integer +inc(0) = 4: inc(1) = 2: inc(2) = 4 +inc(3) = 2: inc(4) = 4: inc(5) = 6 +inc(6) = 2: inc(7) = 6 + +function firstPrimeFactor(n as long) as long + if n = 1 then return 1 + if n mod 3 = 0 then return 3 + if n mod 5 = 0 then return 5 + + long k = 7 + int idx = 0 + + while k * k <= n + if mod(n, k) = 0 then return k + k += inc(idx) + idx = mod((idx + 1), 8) + wend + return n +end function + +sub main() + dim as long blum(49), counts(9) + long bc = 0, i = 1, pct, p, q + int j + string s, t + + do + p = firstPrimeFactor(i) + if p mod 4 = 3 then + q = i \ p + if q <> p and q mod 4 = 3 and isPrime(q) then + if bc < 50 then blum(bc) = i + counts(i mod 10) = counts(i mod 10) + 1 + bc += 1 + + if bc = 50 then + printl "First 50 Blum integers:" + for j = 0 to 49 + s = str(blum(j)) + while len(s) < 4: s = " " + s: wend + print s; + if mod((j + 1), 10) = 0 then printl + next + printl + elseif bc = 26828 or bc mod 100000 = 0 then + s = str(bc) + while len(s) < 6: s = " " + s: wend + t = str(i) + while len(t) < 7: t = " " + t: wend + printl "The " + s + "th Blum integer is: " + t + if bc = 400000 then + printl cr "% distribution of the first 400,000 Blum integers:" + + for j = 1 to 9 step 2 + if j <> 5 then + pct = counts(j)/4000 + s = str(pct) + while len(s) < 5: s = " " + s: wend + printl s + "% end in " + str(j) + end if + next + end + end if + end if + end if + end if + if mod(i, 5) = 3 then i += 4 else i += 2 + end do +end sub + +main() + +printl cr "Enter ..." +waitkey diff --git a/Task/Blum-integer/Pluto/blum-integer.pluto b/Task/Blum-integer/Pluto/blum-integer.pluto new file mode 100644 index 0000000000..1f47fd7135 --- /dev/null +++ b/Task/Blum-integer/Pluto/blum-integer.pluto @@ -0,0 +1,53 @@ +local int = require "int" +local fmt = require "fmt" + +local inc = {4, 2, 4, 2, 4, 6, 2, 6} + +-- Assumes n is odd. +local function first_prime_factor(n) + if n == 1 then return 1 end + if n % 3 == 0 then return 3 end + if n % 5 == 0 then return 5 end + local k = 7 + local i = 1 + while k * k <= n do + if n % k == 0 then + return k + else + k = k + inc[i] + i = i % 8 + 1 + end + end + return n +end + +local blum = {} +local bc = 0 +local counts = { [1] = 0, [3] = 0, [7] = 0, [9] = 0 } +local i = 1 +while true do + local p = first_prime_factor(i) + if p % 4 == 3 then + local q = i // p + if q != p and q % 4 == 3 and int.isprime(q) then + if bc < 50 then blum:insert(i) end + counts[i % 10] += 1 + bc += 1 + if bc == 50 then + print("First 50 Blum integers:") + fmt.tprint("%3d ", blum, 10) + print() + elseif bc == 26828 or bc % 100_000 == 0 then + fmt.print("The %9s Blum integer is: %9s", fmt.ord(bc, true), fmt.int(i)) + if bc == 400_000 then + print("\n% distribution of the first 400,000 Blum integers:") + for {1, 3, 7, 9} as j do + fmt.print(" %6.3f%% end in %d", counts[j] / 4000, j) + end + return + end + end + end + end + i = (i % 5 == 3) ? i + 4 : i + 2 +end diff --git a/Task/Blum-integer/PureBasic/blum-integer.basic b/Task/Blum-integer/PureBasic/blum-integer.basic new file mode 100644 index 0000000000..191ab6d065 --- /dev/null +++ b/Task/Blum-integer/PureBasic/blum-integer.basic @@ -0,0 +1,69 @@ +XIncludeFile "isprime.pb" + +Structure PrimeHelper + inc.i[8] + index.i +EndStructure + +Procedure.i firstPrimeFactor(n.q) + If n = 1 : ProcedureReturn 1 : EndIf + If n % 3 = 0 : ProcedureReturn 3 : EndIf + If n % 5 = 0 : ProcedureReturn 5 : EndIf + + Define helper.PrimeHelper + helper\inc[0] = 4 : helper\inc[1] = 2 : helper\inc[2] = 4 + helper\inc[3] = 2 : helper\inc[4] = 4 : helper\inc[5] = 6 + helper\inc[6] = 2 : helper\inc[7] = 6 + + Define k.q = 7 + While k * k <= n + If n % k = 0 : ProcedureReturn k : EndIf + k + helper\inc[helper\index] + helper\index = (helper\index + 1) % 8 + Wend + ProcedureReturn n +EndProcedure + +OpenConsole() +Define Dim blum.q(49) +Define.q bc = 0, i = 1 +Define Dim counts.q(9) + +Repeat + Define p.q = firstPrimeFactor(i) + If p % 4 = 3 + Define q.q = i / p + If q <> p And q % 4 = 3 And isPrime(q) + If bc < 50 : blum(bc) = i : EndIf + counts(i % 10) + 1 + bc + 1 + + If bc = 50 + PrintN("First 50 Blum integers:") + For j = 0 To 49 + Print(" " + RSet(Str(blum(j)), 3)) + If (j + 1) % 10 = 0 : PrintN("") : EndIf + Next + PrintN("") + ElseIf bc = 26828 Or bc % 100000 = 0 + PrintN("The " + RSet(Str(bc), 6) + "th Blum integer is: " + RSet(Str(i), 7)) + If bc = 400000 + PrintN(#CRLF$ + "% distribution of the first 400,000 Blum integers:") + For j = 1 To 9 Step 2 + If j <> 5 + PrintN(RSet(StrF(counts(j)/4000, 3), 5) + "% end in " + Str(j)) + EndIf + Next + Break + EndIf + EndIf + EndIf + EndIf + If i % 5 = 3 + i + 4 + Else + i + 2 + EndIf +ForEver + +PrintN(#CRLF$ + "Press ENTER to exit"): Input() diff --git a/Task/Blum-integer/QB64/blum-integer.qb64 b/Task/Blum-integer/QB64/blum-integer.qb64 new file mode 100644 index 0000000000..9b3a0be158 --- /dev/null +++ b/Task/Blum-integer/QB64/blum-integer.qb64 @@ -0,0 +1,73 @@ +Dim Shared inc(7) As Integer +inc(0) = 4: inc(1) = 2: inc(2) = 4 +inc(3) = 2: inc(4) = 4: inc(5) = 6 +inc(6) = 2: inc(7) = 6 + +Dim blum(49) As Long +Dim counts(9) As Long +Dim bc As Long, i As Long, p As Long, q As Long, j As Integer +i = 1 + +Do + p = firstPrimeFactor(i) + If p Mod 4 = 3 Then + q = i \ p + If q <> p And q Mod 4 = 3 And isPrime(q) Then + If bc < 50 Then blum(bc) = i + counts(i Mod 10) = counts(i Mod 10) + 1 + bc = bc + 1 + + If bc = 50 Then + Print "First 50 Blum integers:" + For j = 0 To 49 + Print Using "####"; blum(j); + If (j + 1) Mod 10 = 0 Then Print + Next + Print + ElseIf bc = 26828 Or bc Mod 100000 = 0 Then + Print Using "The ###,###th Blum integer is: #,###,###"; bc; i + If bc = 400000 Then + Print Chr$(10); "% distribution of the first 400,000 Blum integers:" + For j = 1 To 9 Step 2 + If j <> 5 Then + Print Using " ##.###% end in #"; (counts(j%) / 4000); j% + End If + Next + End + End If + End If + End If + End If + If i Mod 5 = 3 Then i = i + 4 Else i = i + 2 +Loop +End + +Function firstPrimeFactor& (n As Long) + Dim k As Long, idx As Integer + If n = 1 Then firstPrimeFactor& = 1: Exit Function + If n Mod 3 = 0 Then firstPrimeFactor& = 3: Exit Function + If n Mod 5 = 0 Then firstPrimeFactor& = 5: Exit Function + k = 7: idx = 0 + Do While k * k <= n + If n Mod k = 0 Then + firstPrimeFactor& = k + Exit Function + End If + k = k + inc(idx) + idx = (idx + 1) Mod 8 + Loop + firstPrimeFactor& = n +End Function + +Function isPrime% (n As Long) + Dim i As Long + If n <= 1 Then Exit Function + If n <= 3 Then isPrime% = 1: Exit Function + If n Mod 2 = 0 Or n Mod 3 = 0 Then Exit Function + i = 5 + While i * i <= n + If n Mod i = 0 Or n Mod (i + 2) = 0 Then Exit Function + i = i + 6 + Wend + isPrime% = 1 +End Function diff --git a/Task/Blum-integer/REXX/blum-integer-1.rexx b/Task/Blum-integer/REXX/blum-integer-1.rexx new file mode 100644 index 0000000000..f2ec8d05b6 --- /dev/null +++ b/Task/Blum-integer/REXX/blum-integer-1.rexx @@ -0,0 +1,59 @@ +include Setting + +Say Time() +Call Time 'R' +blumCount = 0 +blums.=0 +lastDigitCounts.=0 +Do number=5 By 4 While blumCount < 400000 + Prime=leastPrimeFactor(number) + If Prime // 4=3 Then Do + quotient=number / Prime; + If quotient <> Prime & isPrimeType3(quotient) Then Do + blumCount+=1 + If blumCount<=50 Then Do + blums.blumCount=number + End + lastdigit=Right(number,1) + lastDigitCounts.lastdigit+=1 + If blumCount=50 Then Do + Say "The first 50 Blum integers:" + Do i=1 To 50 + If Right(i,1)=1 Then + l=Format(blums.i,3) + Else + l=l Format(blums.i,3) + If i//10=0 Then + Say l + End + Say '' + End + Else Do + If blumCount=26828 | blumCount // 100000 = 0 Then Do + Say "The " Format(blumCount,7)"th Blum Integer is:" Format(number,7) Time() + If blumCount=400000 Then Do + Say '' + Say "Percent distribution of the first 400000 Blum integers:" + Do i=0 To 9 + If lastDigitCounts.i>0 Then + Say Format(lastDigitCounts.i/4000,6,3)'% end in' i + End + End + End + End + End + End + End +Say Time() +say Time('E') 'seconds' +Exit + +isPrimeType3: Procedure expose Memo. + Parse Arg number + Return Prime(number) & (number//4=3) + +leastPrimeFactor: Procedure expose Memo. + Parse Arg number + Return FFactor(number) + +include Math diff --git a/Task/Blum-integer/REXX/blum-integer-2.rexx b/Task/Blum-integer/REXX/blum-integer-2.rexx new file mode 100644 index 0000000000..9c5598e2ee --- /dev/null +++ b/Task/Blum-integer/REXX/blum-integer-2.rexx @@ -0,0 +1,89 @@ +-- 28 Aug 2025 +include Setting +arg count +if count = '' then + count = 400000 +threshold=25*count + +say 'BLUM INTEGER' +say version +say +say 'Parameters...' +say 'Threshold' threshold 'Count' count +say +say 'Collect primes...' +say Primes(threshold) 'found'; say +say 'Filter primes 3 modulo 4...' +say Filter3Mod4() 'found'; say +say 'Generate Blum integers...' +say GenerateBlum(threshold) 'found'; say +say 'Blum integers...'; say +call Results threshold,count +call Timer +exit + +Filter3Mod4: +procedure expose Prim. +n=0 +do i = 1 to Prim.0 + if Prim.i//4 = 3 then + n=n+1 + else + Prim.i=0 +end +return n + +GenerateBlum: +procedure expose Prim. Blum. +arg threshold +Blum.=0; n=0 +do i = 1 to Prim.0 + if Prim.i <> 0 then do + do j = i+1 to Prim.0 + if Prim.j <> 0 then do + p=Prim.i*Prim.j + if p > threshold then + leave j + n=n+1; Blum.p=1 + end + end + end +end +return n + +Results: +procedure expose Blum. +arg threshold,count +n=0; digs.=0 +do i = 5 by 4 to threshold + if \ Blum.i then + iterate i + n=n+1 + if n > count then + leave i + d=Right(i,1); digs.d=digs.d+1 + if n < 51 then do + if n = 1 then + say 'The first 50 are' + call CharOut ,Right(i,4) + if n//10 = 0 then + say + if n = 50 then + say + iterate i + end + if n = 26828 | n//100000 = 0 then + say 'The' n'th is' i + if n = count then do + say + say 'Percent distribution of the first' count + do i = 1 to 9 + if digs.i > 0 then + say format(digs.i*100/count,2,3)'% ends in' i + end + end +end +say +return 0 + +include Math diff --git a/Task/Blum-integer/Rust/blum-integer.rs b/Task/Blum-integer/Rust/blum-integer.rs new file mode 100644 index 0000000000..59feb1041f --- /dev/null +++ b/Task/Blum-integer/Rust/blum-integer.rs @@ -0,0 +1,91 @@ +fn is_prime_mod4(n: u32) -> bool { + match n { + 0..3 => false, + _ if n % 2 == 0 => false, + _ if n % 3 == 0 => n == 3, + _ if n % 4 == 3 => { + for d in (5..).step_by(2).take_while(|&d| d * d <= n) { + if n % d == 0 { + return false; + } + } + + true + } + _ => false, + } +} + +fn least_prime_factor(n: u32) -> u32 { + match n { + 1 => 1, + _ if n % 3 == 0 => 3, + _ if n % 5 == 0 => 5, + _ => { + for d in (7..).step_by(2).take_while(|&d| d * d <= n) { + if n % d == 0 { + return d; + } + } + + n + } + } +} + +fn blums() -> Blum { + Blum { number: 1 } +} + +struct Blum { + number: u32, +} + +impl Iterator for Blum { + type Item = u32; + + fn next(&mut self) -> Option { + loop { + let number = self.number; + let p = least_prime_factor(number); + + self.number = number.checked_add(if number % 5 == 3 { 4 } else { 2 })?; + + if p % 4 == 3 { + let q = number / p; + + if p != q && is_prime_mod4(q) { + return Some(number); + } + } + } + } +} + +fn main() { + println!("First 50 Blum integers:"); + + let last_digit_counts = blums() + .zip(1..=400_000) + .inspect(|&(blum, i)| match i { + 1..=50 => print!("{blum:>3}{}", if i % 10 != 0 { " " } else { "\n" }), + 51 => println!(), + 26_828 | 100_000 | 200_000 | 300_000 | 400_000 => { + println!("The {i:>6}th Blum integer is: {blum:>7}"); + } + _ => {} + }) + .fold([0; 10], |mut acc, (blum, _)| { + acc[blum as usize % 10] += 1; + + acc + }); + + println!("\nPercent distribution of the first 400000 Blum integers:"); + for i in [1, 3, 7, 9] { + println!( + "\t{:2.3}% end in {i}", + last_digit_counts[i] as f64 / 4_000.0 + ); + } +} diff --git a/Task/Boolean-values/Ada/boolean-values.ada b/Task/Boolean-values/Ada/boolean-values.adb similarity index 100% rename from Task/Boolean-values/Ada/boolean-values.ada rename to Task/Boolean-values/Ada/boolean-values.adb diff --git a/Task/Boolean-values/ArkScript/boolean-values.ark b/Task/Boolean-values/ArkScript/boolean-values.ark new file mode 100644 index 0000000000..d92c5993bd --- /dev/null +++ b/Task/Boolean-values/ArkScript/boolean-values.ark @@ -0,0 +1,14 @@ +(let test (fun (v) { + (puts v ": ") + (if v (print true) (print false)) })) + + +(test 1) +(test 0) +(test true) +(test false) +(test "hello") +(test "") +(test [1 2 3]) +(test []) +(test nil) diff --git a/Task/Boolean-values/Arturo/boolean-values.arturo b/Task/Boolean-values/Arturo/boolean-values.arturo index 9a3129bc14..aa612af29c 100644 --- a/Task/Boolean-values/Arturo/boolean-values.arturo +++ b/Task/Boolean-values/Arturo/boolean-values.arturo @@ -1,7 +1,7 @@ a: true b: false -if? a [ print "yep" ] else [ print "nope" ] +switch a [ print "yep" ][ print "nope" ] -if? b -> print "nope" -else -> print "yep" +switch b -> print "nope" + -> print "yep" diff --git a/Task/Boolean-values/Ballerina/boolean-values.ballerina b/Task/Boolean-values/Ballerina/boolean-values.ballerina new file mode 100644 index 0000000000..637f05cfc0 --- /dev/null +++ b/Task/Boolean-values/Ballerina/boolean-values.ballerina @@ -0,0 +1,12 @@ +import ballerina/io; + +public function main() { + boolean markova = true; + boolean keys = false; + if markova { + io:println("Alicia Markova was a famous ballerina."); + } + if !keys { + io:println("Alicia Keys is a famous singer."); + } +} diff --git a/Task/Boolean-values/COBOL/boolean-values-1.cobol b/Task/Boolean-values/COBOL/boolean-values-1.cob similarity index 100% rename from Task/Boolean-values/COBOL/boolean-values-1.cobol rename to Task/Boolean-values/COBOL/boolean-values-1.cob diff --git a/Task/Boolean-values/COBOL/boolean-values-2.cobol b/Task/Boolean-values/COBOL/boolean-values-2.cob similarity index 100% rename from Task/Boolean-values/COBOL/boolean-values-2.cobol rename to Task/Boolean-values/COBOL/boolean-values-2.cob diff --git a/Task/Boolean-values/COBOL/boolean-values-3.cobol b/Task/Boolean-values/COBOL/boolean-values-3.cob similarity index 100% rename from Task/Boolean-values/COBOL/boolean-values-3.cobol rename to Task/Boolean-values/COBOL/boolean-values-3.cob diff --git a/Task/Boolean-values/Crystal/boolean-values.cr b/Task/Boolean-values/Crystal/boolean-values.cr new file mode 100644 index 0000000000..02755b55d3 --- /dev/null +++ b/Task/Boolean-values/Crystal/boolean-values.cr @@ -0,0 +1,9 @@ +if false + puts "false" +elsif nil + puts "nil" +elsif Pointer(Nil).new 0_u64 + puts "null pointer" +elsif true && "any other value" + puts "finally true!" +end diff --git a/Task/Boolean-values/Crystal/boolean-values.crystal b/Task/Boolean-values/Crystal/boolean-values.crystal deleted file mode 100644 index e07aedd7a8..0000000000 --- a/Task/Boolean-values/Crystal/boolean-values.crystal +++ /dev/null @@ -1,9 +0,0 @@ -if false - puts "false" -elsif nil - puts "nil" -elsif Pointer(Nil).new 0 - puts "null pointer" -elsif true && "any other value" - puts "finally true!" -end diff --git a/Task/Boolean-values/EMal/boolean-values.emal b/Task/Boolean-values/EMal/boolean-values.emal index 27d6cfd42e..62f10187ce 100644 --- a/Task/Boolean-values/EMal/boolean-values.emal +++ b/Task/Boolean-values/EMal/boolean-values.emal @@ -3,15 +3,15 @@ |There are no implicit conversions, but explicit conversions |from/to int (0,1) or text ("⊥", "⊤") are allowed. |^ -logic booleanTrue = true -logic booleanFalse = false +logic booleanTrue ← true +logic booleanFalse ← false if 2 > 1 and true and not false - writeLine("true: " + true + ", false: " + false) + writeLine("true: ", true, ", false: ", false) end -if false == logic!0 +if false æ logic!0 writeLine("explicit conversion from integer") end -if true == logic!"⊤" +if true æ logic!"⊤" writeLine("explicit conversion from text") end writeLine(int!true) # is one diff --git a/Task/Boolean-values/Elixir/boolean-values-1.elixir b/Task/Boolean-values/Elixir/boolean-values-1.ex similarity index 100% rename from Task/Boolean-values/Elixir/boolean-values-1.elixir rename to Task/Boolean-values/Elixir/boolean-values-1.ex diff --git a/Task/Boolean-values/Elixir/boolean-values-2.elixir b/Task/Boolean-values/Elixir/boolean-values-2.ex similarity index 100% rename from Task/Boolean-values/Elixir/boolean-values-2.elixir rename to Task/Boolean-values/Elixir/boolean-values-2.ex diff --git a/Task/Boolean-values/Haxe/boolean-values.hx b/Task/Boolean-values/Haxe/boolean-values.hx new file mode 100644 index 0000000000..c2f8a2ed4c --- /dev/null +++ b/Task/Boolean-values/Haxe/boolean-values.hx @@ -0,0 +1,8 @@ +class Main { + static public function main():Void { + var t = true; + var f = false; + $type(t); + $type(f); + } +} diff --git a/Task/Boolean-values/Julia/boolean-values-1.julia b/Task/Boolean-values/Julia/boolean-values-1.jl similarity index 100% rename from Task/Boolean-values/Julia/boolean-values-1.julia rename to Task/Boolean-values/Julia/boolean-values-1.jl diff --git a/Task/Boolean-values/Julia/boolean-values-2.julia b/Task/Boolean-values/Julia/boolean-values-2.jl similarity index 100% rename from Task/Boolean-values/Julia/boolean-values-2.julia rename to Task/Boolean-values/Julia/boolean-values-2.jl diff --git a/Task/Boolean-values/LOLCODE/boolean-values.lol b/Task/Boolean-values/LOLCODE/boolean-values.lol new file mode 100644 index 0000000000..5e3e1bc953 --- /dev/null +++ b/Task/Boolean-values/LOLCODE/boolean-values.lol @@ -0,0 +1,15 @@ +HAI 1.3 + + FAIL, O RLY?, YA RLY, VISIBLE " 0"!, NO WAI, VISIBLE " -0"!, OIC BTW GET -0 + WIN, O RLY?, YA RLY, VISIBLE " 1"!, NO WAI, VISIBLE " -1"!, OIC BTW GET 1 + "", O RLY?, YA RLY, VISIBLE " 2"!, NO WAI, VISIBLE " -2"!, OIC BTW GET -2 + ".", O RLY?, YA RLY, VISIBLE " 3"!, NO WAI, VISIBLE " -3"!, OIC BTW GET 3 + 0, O RLY?, YA RLY, VISIBLE " 4"!, NO WAI, VISIBLE " -4"!, OIC BTW GET -4 + 1, O RLY?, YA RLY, VISIBLE " 5"!, NO WAI, VISIBLE " -5"!, OIC BTW GET 5 + 0.0, O RLY?, YA RLY, VISIBLE " 6"!, NO WAI, VISIBLE " -6"!, OIC BTW GET -6 + 1.0, O RLY?, YA RLY, VISIBLE " 7"!, NO WAI, VISIBLE " -7"!, OIC BTW GET 7 + + I HAS A N0 ITZ A NOOB + N0, O RLY?, YA RLY, VISIBLE " 8"!, NO WAI, VISIBLE " -8"!, OIC BTW GET -8 + +KTHXBYE diff --git a/Task/Boolean-values/OCaml/boolean-values.ocaml b/Task/Boolean-values/OCaml/boolean-values.ml similarity index 100% rename from Task/Boolean-values/OCaml/boolean-values.ocaml rename to Task/Boolean-values/OCaml/boolean-values.ml diff --git a/Task/Boolean-values/PowerShell/boolean-values.psh b/Task/Boolean-values/PowerShell/boolean-values.ps1 similarity index 100% rename from Task/Boolean-values/PowerShell/boolean-values.psh rename to Task/Boolean-values/PowerShell/boolean-values.ps1 diff --git a/Task/Boolean-values/Prolog/boolean-values.pro b/Task/Boolean-values/Prolog/boolean-values.pro new file mode 100644 index 0000000000..361f023ab6 --- /dev/null +++ b/Task/Boolean-values/Prolog/boolean-values.pro @@ -0,0 +1,2 @@ +?- ( Bool = true ; Bool = false ), + ( Bool -> bool_is_true ; bool_is_false ). diff --git a/Task/Boolean-values/Red/boolean-values.red b/Task/Boolean-values/Red/boolean-values.red new file mode 100644 index 0000000000..8ed1e79643 --- /dev/null +++ b/Task/Boolean-values/Red/boolean-values.red @@ -0,0 +1,8 @@ +;- 3 ways to declare true in a variable named a +a: true +a: on +a: yes +;- 3 ways to declare false in a variable named b +b: false +b: off +b: no diff --git a/Task/Boolean-values/Rust/boolean-values.rust b/Task/Boolean-values/Rust/boolean-values.rs similarity index 100% rename from Task/Boolean-values/Rust/boolean-values.rust rename to Task/Boolean-values/Rust/boolean-values.rs diff --git a/Task/Boolean-values/Uiua/boolean-values.uiua b/Task/Boolean-values/Uiua/boolean-values.uiua new file mode 100644 index 0000000000..769ce8a2eb --- /dev/null +++ b/Task/Boolean-values/Uiua/boolean-values.uiua @@ -0,0 +1,4 @@ += 4 4 # --> 1 += 4 5 # --> 1 +↧ 1 0 # --> 0 +↥ 0 1 # --> 1 diff --git a/Task/Boolean-values/VBScript/boolean-values.vb b/Task/Boolean-values/VBScript/boolean-values.vbs similarity index 100% rename from Task/Boolean-values/VBScript/boolean-values.vb rename to Task/Boolean-values/VBScript/boolean-values.vbs diff --git a/Task/Boolean-values/Zig/boolean-values.zig b/Task/Boolean-values/Zig/boolean-values.zig new file mode 100644 index 0000000000..f7b10d4ab0 --- /dev/null +++ b/Task/Boolean-values/Zig/boolean-values.zig @@ -0,0 +1,15 @@ +const std = @import("std"); + +pub fn main() !void { + const stdout = std.io.getStdOut().writer(); + + const bool1: bool = true; + const bool2: bool = false; + const bool3 = 2 + 2 == 4; + const bool4 = 2 + 2 == 5; + + try stdout.print("{any}\n", .{bool1}); + try stdout.print("{any}\n", .{bool2}); + try stdout.print("{any} {any}\n", .{@TypeOf(bool3), bool3}); + try stdout.print("{any} {any}\n", .{@TypeOf(bool4), bool4}); +} diff --git a/Task/Box-the-compass/11l/box-the-compass.11l b/Task/Box-the-compass/11l/box-the-compass.11l index 7ff6f201ec..ff86715b26 100644 --- a/Task/Box-the-compass/11l/box-the-compass.11l +++ b/Task/Box-the-compass/11l/box-the-compass.11l @@ -17,7 +17,7 @@ F degrees2compasspoint(=d) R q[minorindex].replace(‘N’, p1).replace(‘E’, p2).capitalize() :start: -L(i) 33 +L(i) 0.<33 V d = i * 11.25 S i % 3 1 diff --git a/Task/Box-the-compass/Ada/box-the-compass.ada b/Task/Box-the-compass/Ada/box-the-compass.adb similarity index 100% rename from Task/Box-the-compass/Ada/box-the-compass.ada rename to Task/Box-the-compass/Ada/box-the-compass.adb diff --git a/Task/Box-the-compass/AutoIt/box-the-compass.autoit b/Task/Box-the-compass/AutoIt/box-the-compass.au3 similarity index 100% rename from Task/Box-the-compass/AutoIt/box-the-compass.autoit rename to Task/Box-the-compass/AutoIt/box-the-compass.au3 diff --git a/Task/Box-the-compass/COBOL/box-the-compass.cobol b/Task/Box-the-compass/COBOL/box-the-compass.cob similarity index 100% rename from Task/Box-the-compass/COBOL/box-the-compass.cobol rename to Task/Box-the-compass/COBOL/box-the-compass.cob diff --git a/Task/Box-the-compass/EasyLang/box-the-compass.easy b/Task/Box-the-compass/EasyLang/box-the-compass.easy index 03c6aa33d7..0bb02b538d 100644 --- a/Task/Box-the-compass/EasyLang/box-the-compass.easy +++ b/Task/Box-the-compass/EasyLang/box-the-compass.easy @@ -17,7 +17,7 @@ func$ expand cp$ . h$ = strchar (strcode substr r$ 1 1 - 32) return h$ & substr r$ 2 999 . -proc main . . +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 "----- ------- -------------" diff --git a/Task/Box-the-compass/Elixir/box-the-compass.elixir b/Task/Box-the-compass/Elixir/box-the-compass.ex similarity index 100% rename from Task/Box-the-compass/Elixir/box-the-compass.elixir rename to Task/Box-the-compass/Elixir/box-the-compass.ex diff --git a/Task/Box-the-compass/Euphoria/box-the-compass.euphoria b/Task/Box-the-compass/Euphoria/box-the-compass.eu similarity index 100% rename from Task/Box-the-compass/Euphoria/box-the-compass.euphoria rename to Task/Box-the-compass/Euphoria/box-the-compass.eu diff --git a/Task/Box-the-compass/FutureBasic/box-the-compass.basic b/Task/Box-the-compass/FutureBasic/box-the-compass.basic new file mode 100644 index 0000000000..44c7b8dca8 --- /dev/null +++ b/Task/Box-the-compass/FutureBasic/box-the-compass.basic @@ -0,0 +1,32 @@ +window 1,@"Box the Compass" +_Name = 0 +_Degrees = 1 + + +// mda defaults to mda _Name +mda(0)=@"North":mda(1)=@"North by east":mda(2)=@"North-northeast" +mda(3)=@"Northeast by north":mda(4)=@"Northeast":mda(5)=@"Northeast by east":mda(6)=@"East-northeast" +mda(7)=@"East by north":mda(8)=@"East":mda(9)=@"East by south":mda(10)=@"East-southeast" +mda(11)=@"Southeast by east":mda(12)=@"Southeast":mda(13)=@"Southeast by south":mda(14)=@"South-southeast" +mda(15)=@"South by east":mda(16)= @"South":mda(17)= @"South by west":mda(18)= @"South-southwest" +mda(19)=@"Southwest by south":mda(20)=@"Southwest":mda(21)=@"Southwest by west":mda(22)=@"West-southwest" +mda(23)=@"West by south":mda(24)=@"West":mda(25)=@"West by north":mda(26)=@"West-northwest" +mda(27)=@"Northwest by west":mda(28)=@"Northwest":mda(29)=@"Northwest by north":mda(30)=@"North-northwest" +mda(31)=@"North by west":mda(32)=@"North" + +mda _Degrees (0) = { 0, 16.87, 16.88, 33.75, 50.62, 50.63,¬ +67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135, 151.87, 151.88, 168.75,¬ +185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270,¬ +286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38 } + +unsigned Long i, j + +For i = 0 To 32 + j = fix((mda_double _Degrees(i) + 5.625) / 11.25) + If j > 31 Then j = j - 32 + Print Using "###.## "; (mda_double _Degrees(i)); + Print Using "## "; j; + Print mda _Name(j) +Next + +handleevents diff --git a/Task/Box-the-compass/Icon/box-the-compass.icon b/Task/Box-the-compass/Icon/box-the-compass.icon index c1f1f16e6a..f9d3562942 100644 --- a/Task/Box-the-compass/Icon/box-the-compass.icon +++ b/Task/Box-the-compass/Icon/box-the-compass.icon @@ -7,7 +7,7 @@ every heading := 11.25 * (i := 0 to 32) do { 1: heading +:= 5.62 2: heading -:= 5.62 } - write(right(i+1,3)," ",left(direction(heading),20)," ",fix(heading,,7,2)) + write(right(i%32+1,3)," ",left(direction(heading),20)," ",fix(heading,,7,2)) } end @@ -17,10 +17,10 @@ initial { every put(dirs := [], replacem(!["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"], + "S","SbW","S-SW","SWbS","SW","SWbW","W-SW","WbS", + "W","WbN","W-NW","NWbW","NW","NWbN","N-NW","NbW"], "N","north","E","east","W","west","S","south","b"," by ")) } - return dirs[round(((((d%360)+360)%360)/11.25)%32 + 1)] + return dirs[round(((((d%360)+360)%360)/11.25))%32 + 1] end diff --git a/Task/Box-the-compass/Julia/box-the-compass.julia b/Task/Box-the-compass/Julia/box-the-compass.jl similarity index 100% rename from Task/Box-the-compass/Julia/box-the-compass.julia rename to Task/Box-the-compass/Julia/box-the-compass.jl diff --git a/Task/Box-the-compass/Kotlin/box-the-compass.kotlin b/Task/Box-the-compass/Kotlin/box-the-compass.kts similarity index 100% rename from Task/Box-the-compass/Kotlin/box-the-compass.kotlin rename to Task/Box-the-compass/Kotlin/box-the-compass.kts diff --git a/Task/Box-the-compass/Langur/box-the-compass.langur b/Task/Box-the-compass/Langur/box-the-compass.langur index d0f6962819..997f98881a 100644 --- a/Task/Box-the-compass/Langur/box-the-compass.langur +++ b/Task/Box-the-compass/Langur/box-the-compass.langur @@ -1,4 +1,4 @@ -val .box = ["North", "North by east", "North-northeast", "Northeast by north", +val box = ["North", "North by east", "North-northeast", "Northeast by north", "Northeast", "Northeast by east", "East-northeast", "East by north", "East", "East by south", "East-southeast", "Southeast by east", "Southeast", "Southeast by south", "South-southeast", "South by east", @@ -7,7 +7,7 @@ val .box = ["North", "North by east", "North-northeast", "Northeast by north", "West", "West by north", "West-northwest", "Northwest by west", "Northwest", "Northwest by north", "North-northwest", "North by west"] -val .angles = [ +val angles = [ 0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, @@ -16,7 +16,7 @@ val .angles = [ writeln "index degrees compass point" writeln "----- ------- -------------" -for .phi in .angles { - val .i = trunc(.phi * 32 / 360 + 0.5) rem 32 + 1 - writeln $"\{.i:5} \{.phi:r2:6} \{.box[.i]}" +for phi in angles { + val i = trunc(phi * 32 / 360 + 0.5) rem 32 + 1 + writeln "{{i:5}} {{phi:r2:6}} {{box[i]}}" } diff --git a/Task/Box-the-compass/OCaml/box-the-compass.ocaml b/Task/Box-the-compass/OCaml/box-the-compass.ml similarity index 100% rename from Task/Box-the-compass/OCaml/box-the-compass.ocaml rename to Task/Box-the-compass/OCaml/box-the-compass.ml diff --git a/Task/Box-the-compass/Phix/box-the-compass-1.phix b/Task/Box-the-compass/Phix/box-the-compass-1.phix index 4377ed54b4..8710cca852 100644 --- a/Task/Box-the-compass/Phix/box-the-compass-1.phix +++ b/Task/Box-the-compass/Phix/box-the-compass-1.phix @@ -1,48 +1,46 @@ -(phixonline)--> - with javascript_semantics - function get225(integer d, string p1, string p2, string p4) - string p3 = p1&'-'&lower(p2) - p2 &= " by "&lower(p1) - p1 &= " by "&lower(p4) - if d then - return {p1,p3,p2} -- eg {North by east,North-northeast,Northeast by north} - else - return {p2,p3,p1} -- eg {Northeast by east,East-northeast,East by north} - end if - end function +with javascript_semantics +function get225(integer d, string p1, string p2, string p4) + string p3 = p1&'-'&lower(p2) + p2 &= " by "&lower(p1) + p1 &= " by "&lower(p4) + if d then + return {p1,p3,p2} -- eg {North by east,North-northeast,Northeast by north} + else + return {p2,p3,p1} -- eg {Northeast by east,East-northeast,East by north} + end if +end function - function get45(sequence res, integer d, string p1, string p2) - string p3 - res = append(res,p1) -- North/East/South/West - if d then - p3 = p1&lower(p2) -- Northeast/Southwest - else - p3 = p2&lower(p1) -- Southeast/Northwest - end if - res &= get225(1,p1,p3,p2) -- eg get225(1,North,Northeast,East) - -- -> {North by east,North-northeast,Northeast by north} - res = append(res,p3) -- Northeast/Southeast/Southwest/Northwest - res &= get225(0,p2,p3,p1) -- eg get225(0,East,Northeast,North) - -- -> {Northeast by east,East-northeast,East by north} - return res - end function +function get45(sequence res, integer d, string p1, string p2) + string p3 + res = append(res,p1) -- North/East/South/West + if d then + p3 = p1&lower(p2) -- Northeast/Southwest + else + p3 = p2&lower(p1) -- Southeast/Northwest + end if + res &= get225(1,p1,p3,p2) -- eg get225(1,North,Northeast,East) + -- -> {North by east,North-northeast,Northeast by north} + res = append(res,p3) -- Northeast/Southeast/Southwest/Northwest + res &= get225(0,p2,p3,p1) -- eg get225(0,East,Northeast,North) + -- -> {Northeast by east,East-northeast,East by north} + return res +end function - function get90(sequence points) - sequence res = {} - for i=1 to length(points) do - res = get45(res,remainder(i,2),points[i],points[remainder(i,4)+1]) - end for -- ie get45(1,North,East) - -- get45(0,East,South) - -- get45(1,South,West) - -- get45(0,West,North) - return res - end function +function get90(sequence points) + sequence res = {} + for i=1 to length(points) do + res = get45(res,remainder(i,2),points[i],points[remainder(i,4)+1]) + end for -- ie get45(1,North,East) + -- get45(0,East,South) + -- get45(1,South,West) + -- get45(0,West,North) + return res +end function - constant compass_points = get90({"North","East","South","West"}) +constant compass_points = get90({"North","East","South","West"}) - for i = 1 to 33 do - atom test_point = (i-1)*11.25 + 5.62*(remainder(i,3)-1) - integer compass_point = remainder(floor(test_point*32/360+0.5),32)+1 - printf(1, "%2d %-22s %6.2f\n", {compass_point, compass_points[compass_point], test_point}) - end for - - with javascript_semantics - constant compass_points = { "North", "North by east", "North-northeast", "Northeast by north", - "Northeast", "Northeast by east", "East-northeast", "East by north", - "East", "East by south", "East-southeast", "Southeast by east", - "Southeast", "Southeast by south", "South-southeast", "South by east", - "South", "South by west", "South-southwest", "Southwest by south", - "Southwest", "Southwest by west", "West-southwest", "West by south", - "West", "West by north", "West-northwest", "Northwest by west", - "Northwest", "Northwest by north", "North-northwest", "North by west"}, - test_points = { 0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, - 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, - 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38} - for i=1 to length(test_points) do - integer compass_point = remainder(floor(test_points[i]*32/360+0.5),32)+1 - printf(1, "%2d %-22s %6.2f\n", {compass_point, compass_points[compass_point], test_points[i]}) - end for - - -- - -- demo\rosetta\BoyerMoore.exw - -- =========================== - -- - -- based on https://www-igm.univ-mlv.fr/~lecroq/string/node14.html - -- - with javascript_semantics - function preBmBc(string pat) - integer m = length(pat) - sequence bmBc = repeat(m,255) - for i=1 to m-1 do - bmBc[pat[i]] = m - i - end for - return bmBc - end function +-- demo\rosetta\BoyerMoore.exw +-- based on https://www-igm.univ-mlv.fr/~lecroq/string/node14.html +with javascript_semantics +function preBmBc(string pat) + integer m = length(pat) + sequence bmBc = repeat(m,255) + for i=1 to m-1 do + bmBc[pat[i]] = m - i + end for + return bmBc +end function - function suffixes(string pat) - integer m = length(pat), g = m, f - sequence suff = repeat(0,m) - suff[m] = m; - for i=m-1 to 1 by -1 do - if i > g and suff[i + m - f] < i - g then - suff[i] = suff[i + m - f] - else - if i < g then g = i end if - f = i - while g >= 1 and pat[g] == pat[g + m - f] do - g -= 1; - end while - suff[i] = f - g - end if - end for - return suff - end function +function suffixes(string pat) + integer m = length(pat), g = m, f + sequence suff = repeat(0,m) + suff[m] = m; + for i=m-1 to 1 by -1 do + if i > g and suff[i + m - f] < i - g then + suff[i] = suff[i + m - f] + else + if i < g then g = i end if + f = i + while g >= 1 and pat[g] == pat[g + m - f] do + g -= 1; + end while + suff[i] = f - g + end if + end for + return suff +end function - function preBmGs(string pat) - integer m = length(pat), j = 1 - sequence suff = suffixes(pat), - bmGs = repeat(m,m) - for i=m to 1 by -1 do - if (suff[i] == i) then - while j < m - i do - if (bmGs[j] == m) then - bmGs[j] = m - i; - end if - j += 1 - end while - end if - end for - for i=1 to m-1 do - bmGs[m - suff[i]] = m - i; - end for - return bmGs - end function +function preBmGs(string pat) + integer m = length(pat), j = 1 + sequence suff = suffixes(pat), + bmGs = repeat(m,m) + for i=m to 1 by -1 do + if (suff[i] == i) then + while j < m - i do + if (bmGs[j] == m) then + bmGs[j] = m - i; + end if + j += 1 + end while + end if + end for + for i=1 to m-1 do + bmGs[m - suff[i]] = m - i; + end for + return bmGs +end function - procedure BM(string pat, s, bool case_insensitive = false) - string pins = sprintf("`%s` in `%s`",{pat,shorten(s,"characters",10)}) - if case_insensitive then - pat = lower(pat) - s = lower(s) - end if - /* Preprocessing */ - sequence bmGs = preBmGs(pat), - bmBc = preBmBc(pat) - /* Searching */ - sequence res = {} - integer i, j = 0, - n = length(s), - m = length(pat), - cc = 0 - while j <= n - m do - for i=m to 1 by -1 do - cc += 1 - if pat[i]!=s[i+j] then exit end if - end for - if i<1 then - res &= j+1 - j += bmGs[1]; - else - j += max(bmGs[i], bmBc[s[i + j]] - m + i); - end if - end while - string ccs = sprintf("(%d character comparisons)",cc) - if length(res) then - string many = ordinant(length(res)) - printf(1,"Found %s %s at %v %s\n",{pins,many,res,ccs}) - else - printf(1,"No %s %s\n",{pins,ccs}) - end if - end procedure +procedure BM(string pat, s, bool case_insensitive = false) + string pins = sprintf("`%s` in `%s`",{pat,shorten(s,"characters",10)}) + if case_insensitive then + pat = lower(pat) + s = lower(s) + end if + /* Preprocessing */ + sequence bmGs = preBmGs(pat), + bmBc = preBmBc(pat) + /* Searching */ + sequence res = {} + integer i, j = 0, + n = length(s), + m = length(pat), + cc = 0 + while j <= n - m do + for i=m to 1 by -1 do + cc += 1 + if pat[i]!=s[i+j] then exit end if + end for + if i<1 then + res &= j+1 + j += bmGs[1]; + else + j += max(bmGs[i], bmBc[s[i + j]] - m + i); + end if + end while + string ccs = sprintf("(%d character comparisons)",cc) + if length(res) then + string many = ordinant(length(res)) + printf(1,"Found %s %s at %v %s\n",{pins,many,res,ccs}) + else + printf(1,"No %s %s\n",{pins,ccs}) + end if +end procedure - BM("GCAGAGAG","GCATCGCAGAGAGTATACAGTACG") - BM("TCTA","GCTAGCTCTACGAGTCTA") - BM("TAATAAA","GGCTATAATGCGTA") - BM("word","there would have been a time for such a word") - BM("needle","needle need noodle needle") - constant book = "InhisbookseriesTheArtofComputerProgrammingpublishedbyAddisonWesley"& - "DKnuthusesanimaginarycomputertheMIXanditsassociatedmachinecodeand"& - "assemblylanguagestoillustratetheconceptsandalgorithmsastheyarepresented" - BM("put",book) - BM("and",book) - constant farm = "Nearby farms grew a half acre of alfalfa on the dairy's behalf, with "& - "bales of all that alfalfa exchanged for milk." - BM("alfalfa",farm) - --BM("aLfAlfa",farm) -- none - --BM("aLfAlfa",farm,true) -- as -2 - - with javascript_semantics - function same_digits(integer n, b) - integer f = remainder(n,b) - n = floor(n/b) - while n>0 do - if remainder(n,b)!=f then return false end if - n = floor(n/b) - end while - return true - end function +with javascript_semantics +function same_digits(integer n, b) + integer f = remainder(n,b) + n = floor(n/b) + while n>0 do + if remainder(n,b)!=f then return false end if + n = floor(n/b) + end while + return true +end function - function is_brazilian(integer n) - if n>=7 then - if remainder(n,2)=0 then return true end if - for b=2 to n-2 do - if same_digits(n,b) then return true end if - end for - end if - return false - end function +function is_brazilian(integer n) + if n>=7 then + if remainder(n,2)=0 then return true end if + for b=2 to n-2 do + if same_digits(n,b) then return true end if + end for + end if + return false +end function - constant kinds = {" ", " odd ", " prime "} - for i=1 to length(kinds) do - printf(1,"First 20%sBrazilian numbers:\n", {kinds[i]}) - integer c = 0, n = 7, p = 4 - while true do - if is_brazilian(n) then - printf(1,"%d ",n) - c += 1 - if c==20 then - printf(1,"\n\n") - exit - end if - end if - switch i - case 1: n += 1 - case 2: n += 2 - case 3: p += 1; n = get_prime(p) - end switch - end while - end for +constant kinds = {" ", " odd ", " prime "} +for i=1 to length(kinds) do + printf(1,"First 20%sBrazilian numbers:\n", {kinds[i]}) + integer c = 0, n = 7, p = 4 + while true do + if is_brazilian(n) then + printf(1,"%d ",n) + c += 1 + if c==20 then + printf(1,"\n\n") + exit + end if + end if + switch i + case 1: n += 1 + case 2: n += 2 + case 3: p += 1; n = get_prime(p) + end switch + end while +end for - integer n = 7, c = 0 - atom t0 = time(), t1 = time()+1 - while c<100000 do - if platform()!=JS and time()>t1 then - printf(1,"checking %d [count:%d]...\r",{n,c}) - t1 = time()+1 - end if - c += is_brazilian(n) - n += 1 - end while - printf(1,"The %,dth Brazilian number: %d\n", {c,n-1}) - ?elapsed(time()-t0) - - without js -- (no class under p2js) - class test - private string msg = "this is a test" - procedure show() ?this.msg end procedure - end class - test t = new() - t.show() - --?t.msg -- illegal - --t.msg = "this is broken" -- illegal - include builtins\structs.e as structs - constant ctx = routine_id("test") -- magic/context - --constant ctx = "test" -- also works - --constant ctx = test -- also works - ?structs:fetch_field(t,"msg",ctx)&" (with some magic)" - structs:store_field(t,"msg","this breaks privacy",ctx) - t.show() - - -- - -- demo\rosetta\BrilliantNumbers.exw - -- ================================= - -- - with javascript_semantics - requires("1.0.2") -- (for in) - atom t0 = time() +with javascript_semantics +requires("1.0.2") -- (for in) +atom t0 = time() - function get_primes_by_digits(integer limit) - sequence primes = get_primes_le(power(10,limit)), - primes_by_digits = {} - integer p = 10 - while length(primes) do - integer pi = abs(binary_search(p,primes))-1 - primes_by_digits &= {primes[1..pi]} - primes = primes[pi+1..$] - p*= 10 - end while - return primes_by_digits - end function - sequence primes_by_digits = get_primes_by_digits(8) +function get_primes_by_digits(integer limit) + sequence primes = get_primes_le(power(10,limit)), + primes_by_digits = {} + integer p = 10 + while length(primes) do + integer pi = abs(binary_search(p,primes))-1 + primes_by_digits &= {primes[1..pi]} + primes = primes[pi+1..$] + p*= 10 + end while + return primes_by_digits +end function +sequence primes_by_digits = get_primes_by_digits(8) - procedure first100() - sequence brilliant_numbers = {} - for primes in primes_by_digits do - for i=1 to length(primes) do - --see talk page - -- for j=i to length(primes) do - for j=1 to i do - brilliant_numbers &= primes[i]*primes[j] - end for - end for - if length(brilliant_numbers)>=100 then exit end if - end for - brilliant_numbers = sort(brilliant_numbers)[1..100] - sequence j100 = join_by(brilliant_numbers,1,10," ","\n","%,5d") - printf(1,"First 100 brilliant numbers:\n%s\n\n",{j100}) - end procedure - first100() +procedure first100() + sequence brilliant_numbers = {} + for primes in primes_by_digits do + for i=1 to length(primes) do +--see talk page +-- for j=i to length(primes) do + for j=1 to i do + brilliant_numbers &= primes[i]*primes[j] + end for + end for + if length(brilliant_numbers)>=100 then exit end if + end for + brilliant_numbers = sort(brilliant_numbers)[1..100] + sequence j100 = join_by(brilliant_numbers,1,10," ","\n","%,5d") + printf(1,"First 100 brilliant numbers:\n%s\n\n",{j100}) +end procedure +first100() - atom pwr = 10, count = 0 - for p=1 to 2*length(primes_by_digits)-1 do - sequence primes = primes_by_digits[floor(p/2)+1] - atom pos = count+1, - min_product = 0 - for i=1 to length(primes) do - integer p1 = primes[i], - j = abs(binary_search(floor((pwr+p1-1)/p1),primes,i)) - if j<=length(primes) then -- (always is, I think) - integer p2 = primes[j] - atom prod = p1*p2 - if min_product=0 or prod<min_product then - min_product = prod - end if - pos += j-i - if p1>=p2 then exit end if - end if - end for - printf(1,"First brilliant number >= 10^%d is %,d at position %,d\n", {p, min_product, pos}) - pwr *= 10; - if odd(p) then - integer size = length(primes) - count += size * (size + 1) / 2; - end if - end for - ?elapsed(time()-t0) - {} = wait_key() - ", encoded + print *, " index = ", index + decoded = Decode(encoded, index) + print *, "---> ", decoded + deallocate(encoded) + end subroutine Test + +end program BurrowsWheeler diff --git a/Task/Burrows-Wheeler-transform/JavaScript/burrows-wheeler-transform.js b/Task/Burrows-Wheeler-transform/JavaScript/burrows-wheeler-transform.js new file mode 100644 index 0000000000..dc7efff102 --- /dev/null +++ b/Task/Burrows-Wheeler-transform/JavaScript/burrows-wheeler-transform.js @@ -0,0 +1,76 @@ +class BWT { + static STX = "\u0002"; + static ETX = "\u0003"; + + static bwt(s) { + if (s.includes(BWT.STX) || s.includes(BWT.ETX)) { + throw new Error("String cannot contain STX or ETX"); + } + + const ss = BWT.STX + s + BWT.ETX; + const table = []; + for (let i = 0; i < ss.length; i++) { + const before = ss.substring(i); + const after = ss.substring(0, i); + table.push(before + after); + } + table.sort(); + + let sb = ""; + for (const str of table) { + sb += str.charAt(str.length - 1); + } + return sb; + } + + static ibwt(r) { + const len = r.length; + const table = []; + for (let i = 0; i < len; ++i) { + table.push(""); + } + for (let j = 0; j < len; ++j) { + for (let i = 0; i < len; ++i) { + table[i] = r.charAt(i) + table[i]; + } + table.sort(); + } + for (const row of table) { + if (row.endsWith(BWT.ETX)) { + return row.substring(1, len - 1); + } + } + return ""; + } + + static makePrintable(s) { + // substitute ^ for STX and | for ETX to print results + return s.replace(BWT.STX, "^").replace(BWT.ETX, "|"); + } + + static main() { + const 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 (const test of tests) { + console.log(BWT.makePrintable(test)); + process.stdout.write(" --> "); + let t = ""; + try { + t = BWT.bwt(test); + console.log(BWT.makePrintable(t)); + } catch (e) { + console.log("ERROR: " + e.message); + } + const r = BWT.ibwt(t); + console.log(` --> ${r}\n`); + } + } +} + +BWT.main(); diff --git a/Task/Burrows-Wheeler-transform/Jq/burrows-wheeler-transform-1.jq b/Task/Burrows-Wheeler-transform/Jq/burrows-wheeler-transform-1.jq index 1f34d0aec0..4151d553f4 100644 --- a/Task/Burrows-Wheeler-transform/Jq/burrows-wheeler-transform-1.jq +++ b/Task/Burrows-Wheeler-transform/Jq/burrows-wheeler-transform-1.jq @@ -20,6 +20,6 @@ def ibwt: | length as $len | reduce range(0;$len) as $i ([]; reduce range(0; $len) as $j (.; - .[$j] = $r[$j:$j+1] + .[$j]) | sort) + .[$j] = $r[$j:$j+1] + .[$j]) | sort) | first( .[] | select(endswith("\u0003"))) | .[1:-1] ; diff --git a/Task/Burrows-Wheeler-transform/Julia/burrows-wheeler-transform.julia b/Task/Burrows-Wheeler-transform/Julia/burrows-wheeler-transform.jl similarity index 100% rename from Task/Burrows-Wheeler-transform/Julia/burrows-wheeler-transform.julia rename to Task/Burrows-Wheeler-transform/Julia/burrows-wheeler-transform.jl diff --git a/Task/Burrows-Wheeler-transform/Kotlin/burrows-wheeler-transform.kotlin b/Task/Burrows-Wheeler-transform/Kotlin/burrows-wheeler-transform.kts similarity index 100% rename from Task/Burrows-Wheeler-transform/Kotlin/burrows-wheeler-transform.kotlin rename to Task/Burrows-Wheeler-transform/Kotlin/burrows-wheeler-transform.kts diff --git a/Task/Burrows-Wheeler-transform/Ksh/burrows-wheeler-transform.ksh b/Task/Burrows-Wheeler-transform/Ksh/burrows-wheeler-transform.ksh index 97c9efba0f..dd2d4c0c0b 100644 --- a/Task/Burrows-Wheeler-transform/Ksh/burrows-wheeler-transform.ksh +++ b/Task/Burrows-Wheeler-transform/Ksh/burrows-wheeler-transform.ksh @@ -2,12 +2,12 @@ # Burrows–Wheeler transform -# # Variables: +# # Variables: # export LC_COLLATE=POSIX -STX=\^ # start marker -ETX=\| # end marker +STX=\^ # start marker +ETX=\| # end marker typeset -a str str[0]='BANANA' @@ -17,75 +17,75 @@ str[3]='TO BE OR NOT TO BE OR WANT TO BE OR NOT?' str[4]='SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES' str[5]='|ABC^' -# # Functions: +# # Functions: # -# # Function _bwt(str, arr, lc) - sort all circular shifts of arr, return last col +# # Function _bwt(str, arr, lc) - sort all circular shifts of arr, return last col # function _bwt { - typeset _str ; _str="$1" - typeset _arr ; nameref _arr="$2" - typeset _lastcol ; nameref _lastcol="$3" - typeset _i _j _newstr ; integer _i _j + typeset _str ; _str="$1" + typeset _arr ; nameref _arr="$2" + typeset _lastcol ; nameref _lastcol="$3" + typeset _i _j _newstr ; integer _i _j - [[ ${_str} == *+("$STX"|"$ETX")* ]] && return 1 - - _str="$STX${_str}$ETX" - for ((_i=0; _i<${#_str}; _i++)); do - _newstr=${_str:${#_str}-1:1} - for ((_j=0; _j<${#_str}-1; _j++)); do - _newstr+=${_str:${_j}:1} - done - _arr+=( "${_newstr}" ) - _str="${_newstr}" - done + [[ ${_str} == *+("$STX"|"$ETX")* ]] && return 1 - set -sA arr # Sort arr + _str="$STX${_str}$ETX" + for ((_i=0; _i<${#_str}; _i++)); do + _newstr=${_str:${#_str}-1:1} + for ((_j=0; _j<${#_str}-1; _j++)); do + _newstr+=${_str:${_j}:1} + done + _arr+=( "${_newstr}" ) + _str="${_newstr}" + done - for ((_i=0; _i<${#_arr[*]}; _i++)); do - _lastcol+=${_arr[_i]:${#_arr[_i]}-1:1} - done + set -sA arr # Sort arr + + for ((_i=0; _i<${#_arr[*]}; _i++)); do + _lastcol+=${_arr[_i]:${#_arr[_i]}-1:1} + done } -# # Function _ibwt(str) - inverse bwt +# # Function _ibwt(str) - inverse bwt # function _ibwt { - typeset _str ; _str="$1" - typeset _arr _vec _ret _i ; typeset -a _arr _vec ; integer _i + typeset _str ; _str="$1" + typeset _arr _vec _ret _i ; typeset -a _arr _vec ; integer _i - _intovec "${_str}" _vec - for ((_i=1; _i<${#_str}; _i++)); do - _intoarr _vec _arr - set -sA _arr - done + _intovec "${_str}" _vec + for ((_i=1; _i<${#_str}; _i++)); do + _intoarr _vec _arr + set -sA _arr + done - for ((_i=0; _i<${#arr[*]}; _i++)); do - [[ "${arr[_i]}" == ${STX}*${ETX} ]] && echo "${arr[_i]}" && return - done + for ((_i=0; _i<${#arr[*]}; _i++)); do + [[ "${arr[_i]}" == ${STX}*${ETX} ]] && echo "${arr[_i]}" && return + done } -# # Function _intovec(str, vec) - trans str into vec[] +# # Function _intovec(str, vec) - trans str into vec[] # function _intovec { - typeset _str ; _str="$1" - typeset _vec ; nameref _vec="$2" - typeset _i ; integer _i + typeset _str ; _str="$1" + typeset _vec ; nameref _vec="$2" + typeset _i ; integer _i - for ((_i=0; _i<${#_str}; _i++)); do - _vec+=( "${_str:${_i}:1}" ) - done + for ((_i=0; _i<${#_str}; _i++)); do + _vec+=( "${_str:${_i}:1}" ) + done } -# # Function _intoarr(i, vec, arr) - insert vec into arr +# # Function _intoarr(i, vec, arr) - insert vec into arr # function _intoarr { - typeset _vec ; nameref _vec="$1" - typeset _arr ; nameref _arr="$2" - typeset _j ; integer _j + typeset _vec ; nameref _vec="$1" + typeset _arr ; nameref _arr="$2" + typeset _j ; integer _j - for ((_j=0; _j<${#_vec[*]}; _j++)); do - _arr="${_vec[_j]}${_arr[_j]}" - done + for ((_j=0; _j<${#_vec[*]}; _j++)); do + _arr="${_vec[_j]}${_arr[_j]}" + done } ###### @@ -93,14 +93,14 @@ function _intoarr { ###### for ((i=0; i<${#str[*]}; i++)); do - unset arr lastcol result ; typeset -a arr + unset arr lastcol result ; typeset -a arr - print -- "${str[i]}" - _bwt "${str[i]}" arr lastcol - (( $? )) && print "ERROR: string cannot contain $STX or $ETX" && continue + print -- "${str[i]}" + _bwt "${str[i]}" arr lastcol + (( $? )) && print "ERROR: string cannot contain $STX or $ETX" && continue - print -- "${lastcol}" - result=$(_ibwt "${lastcol}") - print -- "${result}" - echo + print -- "${lastcol}" + result=$(_ibwt "${lastcol}") + print -- "${result}" + echo done diff --git a/Task/Burrows-Wheeler-transform/Phix/burrows-wheeler-transform.phix b/Task/Burrows-Wheeler-transform/Phix/burrows-wheeler-transform.phix index 24245c2262..cd5ab9b110 100644 --- a/Task/Burrows-Wheeler-transform/Phix/burrows-wheeler-transform.phix +++ b/Task/Burrows-Wheeler-transform/Phix/burrows-wheeler-transform.phix @@ -1,147 +1,145 @@ -(phixonline)--> - -- demo\rosetta\burrows_wheeler.exw - --/* - The traditional method: +-- demo\rosetta\burrows_wheeler.exw +--/* +The traditional method: - 7 banana$ $banana 6 - 6 $banana ===> a$banan 5 - 5 a$banan ana$ban 3 - 4 na$bana sort anana$b 1 - 3 ana$ban banana$ 7 - 2 nana$ba ===> na$bana 4 - 1 anana$b nana$ba 2 - ^ desired answer == "annb$aa" + 7 banana$ $banana 6 + 6 $banana ===> a$banan 5 + 5 a$banan ana$ban 3 + 4 na$bana sort anana$b 1 + 3 ana$ban banana$ 7 + 2 nana$ba ===> na$bana 4 + 1 anana$b nana$ba 2 + ^ desired answer == "annb$aa" - First ignore the numbers: the desired answer is found by creating a table of all - rotations of "banana$", sorting it, and then extracting the right-hand column. +First ignore the numbers: the desired answer is found by creating a table of all +rotations of "banana$", sorting it, and then extracting the right-hand column. - However, there is no need to actually create such a table, which could be very - expensive for long strings, instead just number them logically (admittedly that - was somewhat arbitrarily chosen to get the indexes to work out nicely, I picked - the original index of the last character), and perform a custom sort on those. +However, there is no need to actually create such a table, which could be very +expensive for long strings, instead just number them logically (admittedly that +was somewhat arbitrarily chosen to get the indexes to work out nicely, I picked +the original index of the last character), and perform a custom sort on those. - The latter effectively just recreates the rotations one character at a time until - there is a mismatch (which there always will be since there is only one $). - The left hand column is my arbitrary numbering scheme and the right hand column - is those sorted into order, which is also the indexes to the original string of - the characters that we want. +The latter effectively just recreates the rotations one character at a time until +there is a mismatch (which there always will be since there is only one $). +The left hand column is my arbitrary numbering scheme and the right hand column +is those sorted into order, which is also the indexes to the original string of +the characters that we want. - The code below uses $ as the terminator, but eg 1 (== '\#01') should be fine, - except of course for the display of that on a console. - --*/ - with javascript_semantics - constant terminator = '$' +The code below uses $ as the terminator, but eg 1 (== '\#01') should be fine, +except of course for the display of that on a console. +--*/ +with javascript_semantics +constant terminator = '$' - function rot_sort(integer i,j, sequence s) - -- i,j are indexes of the last character, so bump before first compare. - -- eg/ie rot_sort(i,j,s) should yield compare(rotate(s,i),rotate(s,j)), - -- as in rot_sort(7,6,"banana$") == compare("banana$","$banana") - -- - but one character at a time rather than constructing both. - integer l = length(s) - while true do - i = mod(i,l)+1 - j = mod(j,l)+1 - integer c = compare(s[i],s[j]) - if c!=0 then return c end if - end while - end function +function rot_sort(integer i,j, sequence s) +-- i,j are indexes of the last character, so bump before first compare. +-- eg/ie rot_sort(i,j,s) should yield compare(rotate(s,i),rotate(s,j)), +-- as in rot_sort(7,6,"banana$") == compare("banana$","$banana") +-- - but one character at a time rather than constructing both. + integer l = length(s) + while true do + i = mod(i,l)+1 + j = mod(j,l)+1 + integer c = compare(s[i],s[j]) + if c!=0 then return c end if + end while +end function - function burrows_wheeler_transform(string s) - if find(terminator,s) then return "error" end if - s &= terminator - integer l = length(s) - sequence t = custom_sort(routine_id("rot_sort"),tagset(l),{s}) - string res = repeat(' ',l) - for i=1 to l do - res[i] = s[t[i]] - end for - return res - end function +function burrows_wheeler_transform(string s) + if find(terminator,s) then return "error" end if + s &= terminator + integer l = length(s) + sequence t = custom_sort(routine_id("rot_sort"),tagset(l),{s}) + string res = repeat(' ',l) + for i=1 to l do + res[i] = s[t[i]] + end for + return res +end function - --/* - Inversion. The traditional method is add column and sort, seven times, - to reconstruct the table above, then pick the entry that ends with the - marker. Showing that technique in full detail here is not helpful, and - like above that would be hideously inefficient for large strings. +--/* +Inversion. The traditional method is add column and sort, seven times, +to reconstruct the table above, then pick the entry that ends with the +marker. Showing that technique in full detail here is not helpful, and +like above that would be hideously inefficient for large strings. - $banana 1 $ (1 ) a 2 - a$banan 2 a ( 1) n 6 - ana$ban 3 a ( 2) n 7 - anana$b 4 a ( 3) b 5 - banana$ 5 b $ 1 - na$bana 6 n (2 ) a 3 - nana$ba 7 n (3 ) a 4 - ^ ^ ^ ^ ^ - f l f l t + $banana 1 $ (1 ) a 2 + a$banan 2 a ( 1) n 6 + ana$ban 3 a ( 2) n 7 + anana$b 4 a ( 3) b 5 + banana$ 5 b $ 1 + na$bana 6 n (2 ) a 3 + nana$ba 7 n (3 ) a 4 + ^ ^ ^ ^ ^ + f l f l t - However, we already have the last column, and the first is just that - sorted alphabetically, and with just those two, we have all possible - character pairings of the original message. The trick is in figuring - out how to stitch them together in the right order. If you carefully - study the three that end in a, and the three that start in a, notice - the $banan,na$ban,nana$b parts are sorted in the same order, whether - they are prefixed with a or not. That is, the middle (parenthesised) - matching numbers are both 123, not 123 and say 231. It is quite hard - to see that being useful, but eventually the penny should drop. The - right-hand 1 with an a rotated right gives the left-hand 1, and the - same goes for 2 and 3: they are in fact links to the prior pairing. +However, we already have the last column, and the first is just that +sorted alphabetically, and with just those two, we have all possible +character pairings of the original message. The trick is in figuring +out how to stitch them together in the right order. If you carefully +study the three that end in a, and the three that start in a, notice +the $banan,na$ban,nana$b parts are sorted in the same order, whether +they are prefixed with a or not. That is, the middle (parenthesised) +matching numbers are both 123, not 123 and say 231. It is quite hard +to see that being useful, but eventually the penny should drop. The +right-hand 1 with an a rotated right gives the left-hand 1, and the +same goes for 2 and 3: they are in fact links to the prior pairing. - In other words the first a in l always corresponds to the first in f, - the second to the second, and so on, and that (amazingly) forms the - order in which the pairings need to be daisy-chained together. +In other words the first a in l always corresponds to the first in f, +the second to the second, and so on, and that (amazingly) forms the +order in which the pairings need to be daisy-chained together. - Try following (1->)2a->6n->3a->7n->4a->5b->$, == reverse("banana"), - in the above f and t tables. +Try following (1->)2a->6n->3a->7n->4a->5b->$, == reverse("banana"), +in the above f and t tables. - The code below builds a queue of 'a' ({1,6,7}, built backwards) then - we pop {2,3,4} into those slots in t as we find 'a' in f, likewise - for all other letters, forming the links for each pairing as shown. - See the trivial step 3 scan below, then go back and stare at f and - t as shown above, and once again, eventually the penny should drop. - I will admit I had to read ten or so explanations before I got it. - --*/ +The code below builds a queue of 'a' ({1,6,7}, built backwards) then +we pop {2,3,4} into those slots in t as we find 'a' in f, likewise +for all other letters, forming the links for each pairing as shown. +See the trivial step 3 scan below, then go back and stare at f and +t as shown above, and once again, eventually the penny should drop. +I will admit I had to read ten or so explanations before I got it. +--*/ - function inverse_burrows_wheeler(string s) - if find('\0',s) then ?9/0 end if -- (doable, but needs some +1s) - integer l = length(s), c - string f = sort(s) - sequence q = repeat(0,256), -- queue heads (per char) - x = repeat(0,l), -- queue links - t = repeat(0,l) -- reformed/pairing links - -- Step 1. discover/build queues (backwards) - for i=l to 1 by -1 do - c = s[i] - x[i] = q[c] - q[c] = i - end for - -- Step 2. reform/pop char queues into pairing links - for i=1 to l do - c = f[i] - t[q[c]] = i - q[c] = x[q[c]] - end for - -- Step 3. rebuild (backwards) - c = find(terminator,f) - if c=0 then return "error" end if - string res = repeat(' ',l-1) - for i=l-1 to 1 by -1 do - c = t[c] -- (first time in, skip the end marker) - res[i] = f[c] - end for - return res - end function +function inverse_burrows_wheeler(string s) + if find('\0',s) then ?9/0 end if -- (doable, but needs some +1s) + integer l = length(s), c + string f = sort(s) + sequence q = repeat(0,256), -- queue heads (per char) + x = repeat(0,l), -- queue links + t = repeat(0,l) -- reformed/pairing links + -- Step 1. discover/build queues (backwards) + for i=l to 1 by -1 do + c = s[i] + x[i] = q[c] + q[c] = i + end for + -- Step 2. reform/pop char queues into pairing links + for i=1 to l do + c = f[i] + t[q[c]] = i + q[c] = x[q[c]] + end for + -- Step 3. rebuild (backwards) + c = find(terminator,f) + if c=0 then return "error" end if + string res = repeat(' ',l-1) + for i=l-1 to 1 by -1 do + c = t[c] -- (first time in, skip the end marker) + res[i] = f[c] + end for + return res +end function - procedure test(string src) - string enc = burrows_wheeler_transform(src), - dec = inverse_burrows_wheeler(enc) - src = shorten(src,"characters") - enc = shorten(enc,"characters") - dec = shorten(dec,"characters") - printf(1,"original: %s --> %s\n inverse: %s\n",{src,enc,dec}) - end procedure +procedure test(string src) +string enc = burrows_wheeler_transform(src), + dec = inverse_burrows_wheeler(enc) + src = shorten(src,"characters") + enc = shorten(enc,"characters") + dec = shorten(dec,"characters") + printf(1,"original: %s --> %s\n inverse: %s\n",{src,enc,dec}) +end procedure - test("banana") - test("dogwood") - test("TO BE OR NOT TO BE OR WANT TO BE OR NOT?") - test("SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES") - ") + local t = bwt(test) + if !t then + print("ERROR: String can't contain STX or ETX") + t = "" + else + print(make_printable(t)) + end + local r = ibwt(t) + print($" --> {r}\n") +end diff --git a/Task/Burrows-Wheeler-transform/Rebol/burrows-wheeler-transform.rebol b/Task/Burrows-Wheeler-transform/Rebol/burrows-wheeler-transform.rebol new file mode 100644 index 0000000000..c9d62158d6 --- /dev/null +++ b/Task/Burrows-Wheeler-transform/Rebol/burrows-wheeler-transform.rebol @@ -0,0 +1,80 @@ +Rebol [ + title: "Rosetta code: Burrows–Wheeler transform" + file: %Burrows–Wheeler_transform.r3 + url: https://rosettacode.org/wiki/Burrows–Wheeler_transform +] + +bwt: function [ + "Burrows–Wheeler Transform" + input [string!] "The original text to encode" +][ + ;; Add sentinel markers: + ;; STX (^(02)) at the front to mark the start + ;; ETX (^(03)) at the end to mark the terminus + ;; These ensure unambiguous reconstruction and a fixed sort position. + input: rejoin [#"^(02)" input #"^(03)"] + len: length? input ;; Length of the sentinel-marked string + rotations: clear [] ;; Will hold all cyclic rotations of the string + ;; Generate all cyclic rotations: + repeat i len [ + append rotations rejoin [ + copy at input i ;; from position i to end + copy/part input i - 1 ;; then from start up to (i-1) + ] + ] + ;; Sort all rotations lexicographically + rotations: sort rotations + transformed: copy "" ;; This will be the BWT output (last column) + ;; Take the last character from each sorted rotation and accumulate + foreach r rotations [ + append transformed last r + ] + ;; Return the "last column" as the BWT-transformed string + transformed +] + + +ibwt: function [ + "Inverse Burrows–Wheeler Transform" + input [string!] "The BWT-produced last column string" +][ + ;; Make a copy so we preserve the original argument + input: copy input + len: length? input ;; Number of rows/characters + ;; Initialise a table (block of strings), initially containing `len` empty strings + table: make block! len + loop len [append table copy ""] + ;; Rebuild rotation table iteratively: + ;; Each iteration: + ;; 1. Prepend each character of last column to corresponding row + ;; 2. Sort the rows + repeat j len [ + repeat i len [ + insert table/:i input/:i ;; insert char from last column at row start + ] + table: sort table ;; keep table lexicographically sorted + ] + ;; After len iterations, table contains all sorted rotations. + ;; The original rotation is the one starting with STX and ending with ETX. + ;; With STX as the smallest char, it will always be the first row (table/1). + if table/1/1 == #"^(02)" [ + ;; Skip STX, copy the rest minus ETX. + ;; `next table/1` skips first char (STX) + ;; `len - 2` excludes both sentinels + copy/part next table/1 len - 2 + ] +] + +; Example usage +foreach text [ + "banana" + "appellee" + "abracadabra" + "TO BE OR NOT TO BE OR WANT TO BE OR NOT?" + "SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES" +][ + print ["Original text: " mold text] + print ["After transformation: " mold a: bwt text] + print ["After inverse transformation:" mold b: ibwt a lf] + assert [b == text] +] diff --git a/Task/Burrows-Wheeler-transform/Rust/burrows-wheeler-transform.rust b/Task/Burrows-Wheeler-transform/Rust/burrows-wheeler-transform.rs similarity index 100% rename from Task/Burrows-Wheeler-transform/Rust/burrows-wheeler-transform.rust rename to Task/Burrows-Wheeler-transform/Rust/burrows-wheeler-transform.rs diff --git a/Task/Burrows-Wheeler-transform/Uiua/burrows-wheeler-transform.uiua b/Task/Burrows-Wheeler-transform/Uiua/burrows-wheeler-transform.uiua new file mode 100644 index 0000000000..e3b6984a28 --- /dev/null +++ b/Task/Burrows-Wheeler-transform/Uiua/burrows-wheeler-transform.uiua @@ -0,0 +1,5 @@ +# Apply Burrows–Wheeler transform + +Bwt ← ⌅(⊣⍉⍆≡⌟↻⇡⊸⧻$"\x02_\x03"|↘₁↘₋₁⊢⊙◌⍥(⍆⊸≡˜⊂)⤙˜↯""⊸⧻) +{"banana" "appellee" "abracadabra" "Unusual Uiua"} +≡(&p$"_ > _ > _"⊸°Bwt⊸Bwt) diff --git a/Task/Burrows-Wheeler-transform/V-(Vlang)/burrows-wheeler-transform.v b/Task/Burrows-Wheeler-transform/V-(Vlang)/burrows-wheeler-transform.v new file mode 100644 index 0000000000..cc21976c5e --- /dev/null +++ b/Task/Burrows-Wheeler-transform/V-(Vlang)/burrows-wheeler-transform.v @@ -0,0 +1,65 @@ +const tests = [ + "banana", + "appellee", + "dogwood", + "TO BE OR NOT TO BE OR WANT TO BE OR NOT?", + "SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES", + "\x02ABC\x03" +] + +struct BWT { + mut: + stx string = "\x02" + etx string = "\x03" +} + +fn (bwt BWT) bwt(sg string) !string { + if sg.contains(bwt.stx) || sg.contains(bwt.etx) { + return error("FormatException: String cannot contain STX or ETX") + } + ss := bwt.stx + sg + bwt.etx + mut table := []string{} + for ial in 0 .. ss.len { + before := ss[ial..] + after := ss[..ial] + table << before + after + } + table.sort() + return table.map(it[it.len - 1].ascii_str()).join("") +} + +fn (bwt BWT) ibwt(r string) string { + len := r.len + mut table := []string{len: len, init: ""} + for _ in 0 .. len { + for ial in 0 .. len { + table[ial] = r[ial].ascii_str() + table[ial] + } + table.sort() + } + for row in table { + if row.ends_with(bwt.etx) { return row[1..len - 1] } + } + return "" +} + +fn (bwt BWT) make_printable(sg string) string { + return sg.replace(bwt.stx, "^").replace(bwt.etx, "|") +} + +fn main() { + mut bwt_inst := BWT{} + mut tsg := "" + for idx, test in tests { + println(bwt_inst.make_printable(test)) + print(" --> ") + tsg = bwt_inst.bwt(test) or { + println("ERROR: {$err}") + tsg = "" + continue + } + println(bwt_inst.make_printable(tsg)) + rsg := bwt_inst.ibwt(tsg) + if idx < tests.len { println(" --> $rsg\n") } else { println(" --> $rsg") } + } +} diff --git a/Task/Burrows-Wheeler-transform/Zkl/burrows-wheeler-transform-1.zkl b/Task/Burrows-Wheeler-transform/Zkl/burrows-wheeler-transform-1.zkl index c99add158b..cc528094ee 100644 --- a/Task/Burrows-Wheeler-transform/Zkl/burrows-wheeler-transform-1.zkl +++ b/Task/Burrows-Wheeler-transform/Zkl/burrows-wheeler-transform-1.zkl @@ -4,13 +4,13 @@ class BurrowsWheelerTransform{ _assert_(not str.holds(special), "String cannot contain char \"%s\"".fmt(special) ); str=str.append(special); str.len().pump(List().merge,'wrap(n){ String(str[n,*],str[0,n]) }) - .pump(String,T("get",-1)); // last char of each "permutation" + .pump(String,T("get",-1)); // last char of each "permutation" } fcn decode(str){ - table:=List.createLong(str.len(),""); // ("",""..), mutable + table:=List.createLong(str.len(),""); // ("",""..), mutable do(str.len()){ - foreach n in (str.len()){ table[n]=str[n] + table[n] } - table.sort(); + foreach n in (str.len()){ table[n]=str[n] + table[n] } + table.sort(); } // --> ("$dogwood","d$dogwoo","dogwood$",...) table.filter1("%s*".fmt(special).glob)[1,*]; // str[0]==$, often first element } diff --git a/Task/CRC-32/11l/crc-32.11l b/Task/CRC-32/11l/crc-32.11l index c73b4661a0..62304e3579 100644 --- a/Task/CRC-32/11l/crc-32.11l +++ b/Task/CRC-32/11l/crc-32.11l @@ -1,5 +1,5 @@ V crc_table = [0] * 256 -L(i) 256 +L(i) 0.<256 UInt32 rem = i L 8 I rem [&] 1 != 0 diff --git a/Task/CRC-32/ALGOL-68/crc-32.alg b/Task/CRC-32/ALGOL-68/crc-32.alg index 6e949b4d94..3020332f39 100644 --- a/Task/CRC-32/ALGOL-68/crc-32.alg +++ b/Task/CRC-32/ALGOL-68/crc-32.alg @@ -32,7 +32,7 @@ PROC update_crc = (BITS crc, STRING buf) BITS: PROC hex = (BITS x) STRING : BEGIN - PROC hexdig = (BITS x) CHAR: REPR (IF ABS x ≤ 9 THEN ABS x + ABS "0" + PROC hexdig = (BITS x) CHAR: REPR (IF ABS x <= 9 THEN ABS x + ABS "0" ELSE ABS x - 10 + ABS "a" FI); STRING h := ""; @@ -40,7 +40,7 @@ PROC update_crc = (BITS crc, STRING buf) BITS: h := "0" ELSE BITS n := x; - WHILE h := hexdig (n AND 16rf) + h; n ≠ 16r0 DO + WHILE h := hexdig (n AND 16rf) + h; n /= 16r0 DO n := n SHR 4 OD FI; diff --git a/Task/CRC-32/Ada/crc-32.ada b/Task/CRC-32/Ada/crc-32.adb similarity index 100% rename from Task/CRC-32/Ada/crc-32.ada rename to Task/CRC-32/Ada/crc-32.adb diff --git a/Task/CRC-32/COBOL/crc-32.cobol b/Task/CRC-32/COBOL/crc-32.cob similarity index 100% rename from Task/CRC-32/COBOL/crc-32.cobol rename to Task/CRC-32/COBOL/crc-32.cob diff --git a/Task/CRC-32/Crystal/crc-32.crystal b/Task/CRC-32/Crystal/crc-32.cr similarity index 100% rename from Task/CRC-32/Crystal/crc-32.crystal rename to Task/CRC-32/Crystal/crc-32.cr diff --git a/Task/CRC-32/Delphi/crc-32.delphi b/Task/CRC-32/Delphi/crc-32.pas similarity index 100% rename from Task/CRC-32/Delphi/crc-32.delphi rename to Task/CRC-32/Delphi/crc-32.pas diff --git a/Task/CRC-32/EasyLang/crc-32.easy b/Task/CRC-32/EasyLang/crc-32.easy new file mode 100644 index 0000000000..35d2803aa5 --- /dev/null +++ b/Task/CRC-32/EasyLang/crc-32.easy @@ -0,0 +1,25 @@ +global table[] . +proc mktable . + for i = 0 to 0xff + rem = i + for j to 8 + if bitand rem 1 = 1 + rem = bitxor bitshift rem -1 0xedb88320 + else + rem = bitshift rem -1 + . + . + table[] &= rem + . +. +func crc32 s$ . + crc = 0xffffffff + for c$ in strchars s$ + c = strcode c$ + crb = bitxor bitand crc 0xff c + crc = bitxor (bitshift crc -8) table[crb + 1] + . + return bitand bitnot crc 0xffffffff +. +mktable +print crc32 "The quick brown fox jumps over the lazy dog" diff --git a/Task/CRC-32/Elixir/crc-32.elixir b/Task/CRC-32/Elixir/crc-32.ex similarity index 100% rename from Task/CRC-32/Elixir/crc-32.elixir rename to Task/CRC-32/Elixir/crc-32.ex diff --git a/Task/CRC-32/FutureBasic/crc-32.basic b/Task/CRC-32/FutureBasic/crc-32.basic new file mode 100644 index 0000000000..3ca9fab1e9 --- /dev/null +++ b/Task/CRC-32/FutureBasic/crc-32.basic @@ -0,0 +1,46 @@ +// +// CRC_32 Checksum +// +// FutureBasic 7.0.34, August 2025 R.W +//---------------------------------------------- + +// Get CRC_32 checksum from a CFstring +// using the standard bits reversed 0x04C11DB7 + +// Verified accuracy using the site +// https://codeshack.io/crc32-checksum-generator/ + +local fn getCRC_32 (textStr As CFStringRef) As UInt32 + UInt32 i, j, crc, byte + crc = 0xFFFFFFFF + + for i = 0 to len(textStr) -1 + byte = ucc(textStr, i) + crc = crc XOR byte + for j = 0 to 7 + if ( crc AND 1 ) + crc = (crc >> 1) XOR 0xEDB88320 + else + crc = crc >> 1 + end if + next + next + crc = crc XOR 0xFFFFFFFF +end fn = crc + + +window 1,@"CRC checksum" + +CFStringRef testString +testString = @"The quick brown fox jumps over the lazy dog" + +UInt32 checksum +checksum = fn getCRC_32(testString) + +print +print @" ";testString +print @" has a checksum of ";hex(checksum) + +handleEvents + +// diff --git a/Task/CRC-32/Haxe/crc-32.haxe b/Task/CRC-32/Haxe/crc-32.hx similarity index 100% rename from Task/CRC-32/Haxe/crc-32.haxe rename to Task/CRC-32/Haxe/crc-32.hx diff --git a/Task/CRC-32/Jq/crc-32-1.jq b/Task/CRC-32/Jq/crc-32-1.jq new file mode 100644 index 0000000000..38abfc0ed9 --- /dev/null +++ b/Task/CRC-32/Jq/crc-32-1.jq @@ -0,0 +1,2 @@ +def div($j): + ((. - (. % $j)) / $j) | round; diff --git a/Task/CRC-32/Jq/crc-32-2.jq b/Task/CRC-32/Jq/crc-32-2.jq new file mode 100644 index 0000000000..20a741ca65 --- /dev/null +++ b/Task/CRC-32/Jq/crc-32-2.jq @@ -0,0 +1,34 @@ +include "bitwise" {search: "."}; # see above + +# non-negative decimal integer to hex string +def hex: + def stream: + recurse(if . >= 16 then ./16|floor else empty end) | . % 16 ; + [stream] | reverse + | map(if . < 10 then 48 + . else . + 87 end) | implode ; + +### CRC-32 + +def crc32Table: + reduce range(0; 256) as $i ([]; + . + [reduce range(0; 8) as $j ($i; + if bitwise_and(.;1) == 1 + then bitwise_xor(rightshift(1); 3988292384) # 0xedb88320 + else rightshift( 1 ) + end) ] ); + +# Input: an ASCII string +# Output: its CRC-32 +def crc32: + explode as $s + | crc32Table as $table + | reduce range(0; $s|length) as $i (4294967295 ; # ~0 + # 0xff is 255 + bitwise_and(.; 255 ) as $crb + | bitwise_xor( $table[bitwise_xor($crb; $s[$i])] ; rightshift(8)) ) + | flip(32) ; + +def task: + crc32 | hex; + +"The quick brown fox jumps over the lazy dog" | task diff --git a/Task/CRC-32/Julia/crc-32-1.julia b/Task/CRC-32/Julia/crc-32-1.jl similarity index 100% rename from Task/CRC-32/Julia/crc-32-1.julia rename to Task/CRC-32/Julia/crc-32-1.jl diff --git a/Task/CRC-32/Julia/crc-32-2.jl b/Task/CRC-32/Julia/crc-32-2.jl new file mode 100644 index 0000000000..0c99a75649 --- /dev/null +++ b/Task/CRC-32/Julia/crc-32-2.jl @@ -0,0 +1,31 @@ +function crc32(crc::Int, str::String) + table = zeros(UInt32, 256) + + for i in 0:255 + tmp = i + for j in 0:7 + if tmp & 1 == 1 + tmp >>= 1 + tmp ⊻= 0xedb88320 + else + tmp >>= 1 + end + end + + table[i+1] = tmp + end + + crc ⊻= 0xffffffff + + for i in UInt32.(collect(str)) + crc = (crc >> 8) ⊻ table[(crc&0xff)⊻i+1] + end + + crc ⊻ 0xffffffff +end + +str = "The quick brown fox jumps over the lazy dog" +crc = crc32(0, str) +@assert(crc == 0x414fa339) +println("Message: ", str) +println("Checksum: ", string(crc, base = 16)) diff --git a/Task/CRC-32/Julia/crc-32-2.julia b/Task/CRC-32/Julia/crc-32-2.julia deleted file mode 100644 index fb6e0e6953..0000000000 --- a/Task/CRC-32/Julia/crc-32-2.julia +++ /dev/null @@ -1,31 +0,0 @@ -function crc32(crc::Int, str::String) - table = zeros(UInt32, 256) - - for i in 0:255 - tmp = i - for j in 0:7 - if tmp & 1 == 1 - tmp >>= 1 - tmp ⊻= 0xedb88320 - else - tmp >>= 1 - end - end - - table[i + 1] = tmp - end - - crc ⊻= 0xffffffff - - for i in UInt32.(collect(str)) - crc = (crc >> 8) ⊻ table[(crc & 0xff) ⊻ i + 1] - end - - crc ⊻ 0xffffffff -end - -str = "The quick brown fox jumps over the lazy dog" -crc = crc32(0, str) -assert(crc == 0x414fa339) -println("Message: ", str) -println("Checksum: ", hex(crc)) diff --git a/Task/CRC-32/Kotlin/crc-32.kotlin b/Task/CRC-32/Kotlin/crc-32.kts similarity index 100% rename from Task/CRC-32/Kotlin/crc-32.kotlin rename to Task/CRC-32/Kotlin/crc-32.kts diff --git a/Task/CRC-32/M2000-Interpreter/crc-32-1.m2000 b/Task/CRC-32/M2000-Interpreter/crc-32-1.m2000 index 52eb55078b..c6073ef05e 100644 --- a/Task/CRC-32/M2000-Interpreter/crc-32-1.m2000 +++ b/Task/CRC-32/M2000-Interpreter/crc-32-1.m2000 @@ -1,25 +1,30 @@ -Module CheckIt { - Function PrepareTable { - Dim Base 0, table(256) - For i = 0 To 255 { - k = i - For j = 0 To 7 { - If binary.and(k,1)=1 Then { - k =binary.Xor(binary.shift(k, -1) , 0xEDB88320) - } Else k=binary.shift(k, -1) - } - table(i) = k - } - =table() - } - crctable=PrepareTable() - crc32= lambda crctable (buf$) -> { - crc =0xFFFFFFFF - For i = 0 To Len(buf$) -1 - crc = binary.xor(binary.shift(crc, -8), array(crctable, binary.xor(binary.and(crc, 0xff), asc(mid$(buf$, i+1, 1))))) - Next i - =0xFFFFFFFF-crc - } - Print crc32("The quick brown fox jumps over the lazy dog")=0x414fa339 +odule CheckIt { + crc32 = lambda ->{ + Function PrepareTable { + buffer t as long * 256 + For i = 0 To 255 + k = i + For j = 0 To 7 + If binary.and(k,1)=1 Then + k =binary.Xor(binary.shift(k, -1) , 0xEDB88320) + Else + k=binary.shift(k, -1) + End If + Next + Return t, i:=k + Next + =t + } + = lambda crctable=PrepareTable() (c, buf$) -> { + crc=0xFFFFFFFF-c + For i = 1 To Len(buf$) + crc = binary.xor(binary.shift(crc, -8), eval(crctable, binary.xor(binary.and(crc, 0xff), asc(mid$(buf$, i, 1))))) + Next i + =0xFFFFFFFF-crc + } + }() ' execute now + Print crc32(0, "The quick brown fox jumps over the lazy dog")=0x414fa339& + Print crc32(crc32(0, "The quick brown fox jumps"), " over the lazy dog")=0x414fa339& + Print crc32(crc32(crc32(0, "The qu"), "ick brown"), " fox jumps over the lazy dog")=0x414fa339& } CheckIt diff --git a/Task/CRC-32/OCaml/crc-32.ocaml b/Task/CRC-32/OCaml/crc-32.ml similarity index 100% rename from Task/CRC-32/OCaml/crc-32.ocaml rename to Task/CRC-32/OCaml/crc-32.ml diff --git a/Task/CRC-32/PascalABC.NET/crc-32.pas b/Task/CRC-32/PascalABC.NET/crc-32.pas new file mode 100644 index 0000000000..de5a336f00 --- /dev/null +++ b/Task/CRC-32/PascalABC.NET/crc-32.pas @@ -0,0 +1,29 @@ +type + TCrc32 = array[0..255] of longword; + +function CreateCrcTable(): TCrc32; +begin + for var i: longword := 0 to 255 do + begin + var rem := i; + for var j := 0 to 7 do + if (rem and 1) > 0 then rem := (rem shr 1) xor $edb88320 + else rem := rem shr 1; + result[i] := rem + end; +end; + +const + Crc32Table = CreateCrcTable; + +function Crc32(s: string): longword; +begin + result := $ffffffff; + foreach var c in s do + result := (result shr 8) xor Crc32Table[(result and $ff) xor byte(c)]; + result := not result +end; + +begin + writeln('crc32 = ', crc32('The quick brown fox jumps over the lazy dog').ToString('X')); +end. diff --git a/Task/CRC-32/Pluto/crc-32.pluto b/Task/CRC-32/Pluto/crc-32.pluto new file mode 100644 index 0000000000..310616ad92 --- /dev/null +++ b/Task/CRC-32/Pluto/crc-32.pluto @@ -0,0 +1,5 @@ +local crypto = require "crypto" +local fmt = require "fmt" + +local str = "The quick brown fox jumps over the lazy dog" +print(fmt.hex(crypto.crc32(str))) diff --git a/Task/CRC-32/Python/crc-32-1.py b/Task/CRC-32/Python/crc-32-1.py index 5cc64560d7..ff585a4368 100644 --- a/Task/CRC-32/Python/crc-32-1.py +++ b/Task/CRC-32/Python/crc-32-1.py @@ -1,8 +1,8 @@ >>> s = 'The quick brown fox jumps over the lazy dog' >>> import zlib ->>> hex(zlib.crc32(s)) +>>> hex(zlib.crc32(s.encode())) '0x414fa339' >>> import binascii ->>> hex(binascii.crc32(s)) +>>> hex(binascii.crc32(s.encode())) '0x414fa339' diff --git a/Task/CRC-32/R/crc-32.r b/Task/CRC-32/R/crc-32.r index a8bdc5c253..36236927d7 100644 --- a/Task/CRC-32/R/crc-32.r +++ b/Task/CRC-32/R/crc-32.r @@ -1 +1,2 @@ +library(digest) digest("The quick brown fox jumps over the lazy dog","crc32", serialize=F) diff --git a/Task/CRC-32/Rebol/crc-32.rebol b/Task/CRC-32/Rebol/crc-32.rebol new file mode 100644 index 0000000000..ac677bfc59 --- /dev/null +++ b/Task/CRC-32/Rebol/crc-32.rebol @@ -0,0 +1,4 @@ +sum: checksum "The quick brown fox jumps over the lazy dog" 'crc32 +;== 1095738169 +enbase sum 16 ;; available since 3.19.5 +;== "414FA339" diff --git a/Task/CRC-32/Rust/crc-32.rust b/Task/CRC-32/Rust/crc-32.rs similarity index 100% rename from Task/CRC-32/Rust/crc-32.rust rename to Task/CRC-32/Rust/crc-32.rs diff --git a/Task/CRC-32/Sidef/crc-32.sidef b/Task/CRC-32/Sidef/crc-32.sidef new file mode 100644 index 0000000000..5cd1cdb40c --- /dev/null +++ b/Task/CRC-32/Sidef/crc-32.sidef @@ -0,0 +1,27 @@ +func create_crc32_table { + 256.of {|k| + 8.times { + if (k & 1) { + k >>= 1 + k ^= 0xedb88320 + } + else { + k >>= 1 + } + } + k + } +} + +func crc32(str, crc = 0) { + static crc_table = create_crc32_table() + crc &= 0xffffffff + crc ^= 0xffffffff + str.codes.each {|c| + crc = ((crc >> 8) ^ crc_table[(crc & 0xff) ^ c]) + } + return ((crc & 0xffffffff) ^ 0xffffffff) +} + +say crc32("The quick brown fox jumps over the lazy dog").as_hex +say crc32("over the lazy dog", crc32("The quick brown fox jumps ")).as_hex diff --git a/Task/CRC-32/UNIX-Shell/crc-32-1.sh b/Task/CRC-32/UNIX-Shell/crc-32-1.sh new file mode 100644 index 0000000000..d3f1b53f48 --- /dev/null +++ b/Task/CRC-32/UNIX-Shell/crc-32-1.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +declare -i -a CRC32_LOOKUP_TABLE + +__generate_crc_lookup_table() { + local -i -r LSB_CRC32_POLY=0xEDB88320 # The CRC32 polynomal LSB order + local -i index byte lsb + for index in {0..255}; do + ((byte = 255 - index)) + for _ in {0..7}; do # 8-bit lsb shift + ((lsb = byte & 0x01, byte = ((byte >> 1) & 0x7FFFFFFF) ^ (lsb == 0 ? LSB_CRC32_POLY : 0))) + done + ((CRC32_LOOKUP_TABLE[index] = byte)) + done +} +__generate_crc_lookup_table +typeset -r CRC32_LOOKUP_TABLE + +crc32_string() { + [[ ${#} -eq 1 ]] || return + local -i i byte crc=0xFFFFFFFF index + for ((i = 0; i < ${#1}; i++)); do + byte=$(printf '%d' "'${1:i:1}") # Get byte value of character at i + ((index = (crc ^ byte) & 0xFF, crc = (CRC32_LOOKUP_TABLE[index] ^ (crc >> 8)) & 0xFFFFFFFF)) + done + echo $((crc ^ 0xFFFFFFFF)) +} + +printf 'The CRC32 of: %s\nis: 0x%08x\n' "${1}" "$(crc32_string "${1}")" + +# crc32_string "The quick brown fox jumps over the lazy dog" +# yields 414fa339 diff --git a/Task/CRC-32/UNIX-Shell/crc-32-2.sh b/Task/CRC-32/UNIX-Shell/crc-32-2.sh new file mode 100644 index 0000000000..79918e4f81 --- /dev/null +++ b/Task/CRC-32/UNIX-Shell/crc-32-2.sh @@ -0,0 +1,52 @@ +#!/usr/bin/env sh +# POSIX Shell CRC32 of string +# @Name: crc32.sh +# @Version: 1.0.1 +# @Author: Léa Gris +# @Date: Wed, 27 Mar 2019 +# @License: WTFPL http://www.wtfpl.net/ + +# POSIX Shell has no array or string index +# Implementing a pre-computed CRC32 byte indexed look-up table +# would cost more CPU cycles calling external tools like +# awk or tr to index records from a string. + +# Computes the CRC32 of the input data stream +# <&1: The input data stream +# >&1: The CRC32 integer of the input data stream +crc32_stream() { + crc=0xFFFFFFFF # The Initial CRC32 value + p=0xedb88320 # The CRC32 polynomial + r=0 # The polynomial reminder + c='' # The current character + byte=0 # The byte value of the current character + # Iterates each character of the input stream + while c="$(dd bs=1 count=1 2>/dev/null)" && [ -n "$c" ]; do + byte=$(printf '%d' "'$c") # Converts the character into its byte value + r=$(((crc & 0xff) ^ byte)) # XOR LSB of CRC with current byte + # 8-bit lsb shift with XOR polynomial reminder when odd + for _ in _ _ _ _ _ _ _ _; do + t=$((r >> 1)) + r=$(((r & 1) ? t ^ p : t)) + done + crc=$(((crc >> 8) ^ r)) # XOR MSB of CRC with Reminder + done + + # Output CRC32 integer XOR mask 32 bits + echo $((crc ^ 0xFFFFFFFF)) +} + +# Computes the CRC32 of the argument string +# 1: The argument string +# >&1: The CRC32 integer of the argument string +crc32_string() { + [ $# -eq 1 ] || return # argument required + # Streams with printf to prevent suffixing the string + # with a newline, since echo -n is not available in POSIX Shell + printf '%s' "$1" | crc32_stream +} + +printf 'The CRC32 of: %s\nis: %08x\n' "$1" "$(crc32_string "$1")" + +# crc32_string "The quick brown fox jumps over the lazy dog" +# yields 414fa339 diff --git a/Task/CRC-32/Uiua/crc-32.uiua b/Task/CRC-32/Uiua/crc-32.uiua new file mode 100644 index 0000000000..c43fd20584 --- /dev/null +++ b/Task/CRC-32/Uiua/crc-32.uiua @@ -0,0 +1,8 @@ +String ← "The quick brown fox jumps over the lazy dog" +Key ← ⋕₁₆"1db710640" +InitCRC ← ⋕₁₆"ffffffff" +Xor ← °⋯⬚0≡≠∩⋯ +ShR ← ⍜⋯(⬚0˜↻)⊃⋅∘∘ +Table ← ≡⍥₈(ShR1 ⍥(Xor Key)⊸◿2)⇡256 +⍢(Xor⊃(ShR8|˜⊡Table Xor◿256)⊙°⊂|>0⧻◌) InitCRC -@\0String +°⋕₁₆⍜⋯¬⊙◌ diff --git a/Task/CRC-32/VBScript/crc-32.vb b/Task/CRC-32/VBScript/crc-32.vbs similarity index 100% rename from Task/CRC-32/VBScript/crc-32.vb rename to Task/CRC-32/VBScript/crc-32.vbs diff --git a/Task/CRC-32/Zig/crc-32.zig b/Task/CRC-32/Zig/crc-32.zig index 10a6bf31c1..629dbde918 100644 --- a/Task/CRC-32/Zig/crc-32.zig +++ b/Task/CRC-32/Zig/crc-32.zig @@ -2,6 +2,6 @@ const std = @import("std"); const Crc32Ieee = std.hash.Crc32; pub fn main() !void { - var res: u32 = Crc32Ieee.hash("The quick brown fox jumps over the lazy dog"); + const res: u32 = Crc32Ieee.hash("The quick brown fox jumps over the lazy dog"); std.debug.print("{x}\n", .{res}); } diff --git a/Task/CSV-data-manipulation/00-TASK.txt b/Task/CSV-data-manipulation/00-TASK.txt index 325ca57c4b..f419b925c2 100644 --- a/Task/CSV-data-manipulation/00-TASK.txt +++ b/Task/CSV-data-manipulation/00-TASK.txt @@ -21,5 +21,7 @@ For this task we will use the following CSV file:

  • Show how to add a column, headed 'SUM', of the sums of the rows.
  • If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files. +
    +;Related tasks: +* [[Convert_CSV_records_to_TSV]]

    - diff --git a/Task/CSV-data-manipulation/ALGOL-68/csv-data-manipulation.alg b/Task/CSV-data-manipulation/ALGOL-68/csv-data-manipulation.alg index 749c7da413..97c2d04278 100644 --- a/Task/CSV-data-manipulation/ALGOL-68/csv-data-manipulation.alg +++ b/Task/CSV-data-manipulation/ALGOL-68/csv-data-manipulation.alg @@ -3,8 +3,8 @@ PROC char count = (CHAR c, STRING str) INT: BEGIN INT count := 0; FOR i TO UPB str DO - IF c = str[i] THEN count +:= 1 - FI + IF c = str[i] THEN count +:= 1 + FI OD; count END; @@ -17,9 +17,9 @@ PROC char split = (STRING str, CHAR sep) FLEX[]STRING : INT start := 1; [char count (sep, str) + 1] STRING list; WHILE start <= strlen ANDF char in string (sep, p, str[start:]) DO - p +:= start - 1; - list[cnt +:= 1] := str[start:p-1]; - start := p + 1 + p +:= start - 1; + list[cnt +:= 1] := str[start:p-1]; + start := p + 1 OD; IF cnt = 0 THEN list[cnt +:= 1] := str ELIF start <= UPB str + 1 THEN list[cnt +:= 1] := str[start:] @@ -31,7 +31,7 @@ PROC join = ([]STRING words, STRING sep) STRING: IF UPB words > 0 THEN STRING str := words [1]; FOR i FROM 2 TO UPB words DO - str +:= sep + words[i] + str +:= sep + words[i] OD; str ELSE @@ -60,10 +60,10 @@ OP TOINT = (STRING str) INT: BEGIN INT n := 0, sign := 1; FOR i TO UPB str WHILE sign /= 0 DO - IF is digit (str[i]) THEN n := n * 10 + ABS str[i] - ABS "0" - ELIF i = 1 AND str[i] = "-" THEN sign := -1 - ELIF i /= 1 OR str[i] /= "+" THEN sign := 0 - FI + IF is digit (str[i]) THEN n := n * 10 + ABS str[i] - ABS "0" + ELIF i = 1 AND str[i] = "-" THEN sign := -1 + ELIF i /= 1 OR str[i] /= "+" THEN sign := 0 + FI OD; n * sign END; diff --git a/Task/CSV-data-manipulation/AWK/csv-data-manipulation.awk b/Task/CSV-data-manipulation/AWK/csv-data-manipulation.awk index f45946981e..5f148a16dd 100644 --- a/Task/CSV-data-manipulation/AWK/csv-data-manipulation.awk +++ b/Task/CSV-data-manipulation/AWK/csv-data-manipulation.awk @@ -6,7 +6,7 @@ NR==1 { } { sum = 0 - for (i=1; i<=NF; i++) { + for (i=1; i<=NF; i++) { sum += $i } print $0, sum diff --git a/Task/CSV-data-manipulation/Ada/csv-data-manipulation-1.ada b/Task/CSV-data-manipulation/Ada/csv-data-manipulation-1.adb similarity index 100% rename from Task/CSV-data-manipulation/Ada/csv-data-manipulation-1.ada rename to Task/CSV-data-manipulation/Ada/csv-data-manipulation-1.adb diff --git a/Task/CSV-data-manipulation/Ada/csv-data-manipulation-2.ada b/Task/CSV-data-manipulation/Ada/csv-data-manipulation-2.adb similarity index 100% rename from Task/CSV-data-manipulation/Ada/csv-data-manipulation-2.ada rename to Task/CSV-data-manipulation/Ada/csv-data-manipulation-2.adb diff --git a/Task/CSV-data-manipulation/Ada/csv-data-manipulation-3.ada b/Task/CSV-data-manipulation/Ada/csv-data-manipulation-3.adb similarity index 100% rename from Task/CSV-data-manipulation/Ada/csv-data-manipulation-3.ada rename to Task/CSV-data-manipulation/Ada/csv-data-manipulation-3.adb diff --git a/Task/CSV-data-manipulation/C/csv-data-manipulation-1.c b/Task/CSV-data-manipulation/C/csv-data-manipulation-1.c index 060dd21931..6f6b83c3bc 100644 --- a/Task/CSV-data-manipulation/C/csv-data-manipulation-1.c +++ b/Task/CSV-data-manipulation/C/csv-data-manipulation-1.c @@ -16,10 +16,10 @@ typedef struct { - char * delim; - unsigned int rows; - unsigned int cols; - char ** table; + char * delim; + unsigned int rows; + unsigned int cols; + char ** table; } CSV; @@ -27,28 +27,28 @@ typedef struct { * Utility function to trim whitespaces from left & right of a string */ int trim(char ** str) { - int trimmed; - int n; - int len; - - len = strlen(*str); - n = len - 1; - /* from right */ - while((n>=0) && isspace((*str)[n])) { - (*str)[n] = '\0'; - trimmed += 1; - n--; - } + int trimmed; + int n; + int len; - /* from left */ - n = 0; - while((n < len) && (isspace((*str)[0]))) { - (*str)[0] = '\0'; - *str = (*str)+1; - trimmed += 1; - n++; - } - return trimmed; + len = strlen(*str); + n = len - 1; + /* from right */ + while((n>=0) && isspace((*str)[n])) { + (*str)[n] = '\0'; + trimmed += 1; + n--; + } + + /* from left */ + n = 0; + while((n < len) && (isspace((*str)[0]))) { + (*str)[0] = '\0'; + *str = (*str)+1; + trimmed += 1; + n++; + } + return trimmed; } @@ -56,11 +56,11 @@ int trim(char ** str) { * De-allocate csv structure */ int csv_destroy(CSV * csv) { - if (csv == NULL) { return 0; } - if (csv->table != NULL) { free(csv->table); } - if (csv->delim != NULL) { free(csv->delim); } - free(csv); - return 0; + if (csv == NULL) { return 0; } + if (csv->table != NULL) { free(csv->table); } + if (csv->delim != NULL) { free(csv->delim); } + free(csv); + return 0; } @@ -68,23 +68,23 @@ int csv_destroy(CSV * csv) { * Allocate memory for a CSV structure */ CSV * csv_create(unsigned int cols, unsigned int rows) { - CSV * csv; - - csv = malloc(sizeof(CSV)); - csv->rows = rows; - csv->cols = cols; - csv->delim = strdup(","); + CSV * csv; - csv->table = malloc(sizeof(char *) * cols * rows); - if (csv->table == NULL) { goto error; } + csv = malloc(sizeof(CSV)); + csv->rows = rows; + csv->cols = cols; + csv->delim = strdup(","); - memset(csv->table, 0, sizeof(char *) * cols * rows); + csv->table = malloc(sizeof(char *) * cols * rows); + if (csv->table == NULL) { goto error; } - return csv; + memset(csv->table, 0, sizeof(char *) * cols * rows); + + return csv; error: - csv_destroy(csv); - return NULL; + csv_destroy(csv); + return NULL; } @@ -92,9 +92,9 @@ error: * Get value in CSV table at COL, ROW */ char * csv_get(CSV * csv, unsigned int col, unsigned int row) { - unsigned int idx; - idx = col + (row * csv->cols); - return csv->table[idx]; + unsigned int idx; + idx = col + (row * csv->cols); + return csv->table[idx]; } @@ -102,84 +102,84 @@ char * csv_get(CSV * csv, unsigned int col, unsigned int row) { * Set value in CSV table at COL, ROW */ int csv_set(CSV * csv, unsigned int col, unsigned int row, char * value) { - unsigned int idx; - idx = col + (row * csv->cols); - csv->table[idx] = value; - return 0; + unsigned int idx; + idx = col + (row * csv->cols); + csv->table[idx] = value; + return 0; } void csv_display(CSV * csv) { - int row, col; - char * content; - if ((csv->rows == 0) || (csv->cols==0)) { - printf("[Empty table]\n"); - return ; - } + int row, col; + char * content; + if ((csv->rows == 0) || (csv->cols==0)) { + printf("[Empty table]\n"); + return ; + } - printf("\n[Table cols=%d rows=%d]\n", csv->cols, csv->rows); - for (row=0; rowrows; row++) { - printf("[|"); - for (col=0; colcols; col++) { - content = csv_get(csv, col, row); + printf("\n[Table cols=%d rows=%d]\n", csv->cols, csv->rows); + for (row=0; rowrows; row++) { + printf("[|"); + for (col=0; colcols; col++) { + content = csv_get(csv, col, row); printf("%s\t|", content); - } + } printf("]\n"); - } - printf("\n"); + } + printf("\n"); } /** * Resize CSV table */ int csv_resize(CSV * old_csv, unsigned int new_cols, unsigned int new_rows) { - unsigned int cur_col, - cur_row, - max_cols, - max_rows; - CSV * new_csv; - char * content; - bool in_old, in_new; + unsigned int cur_col, + cur_row, + max_cols, + max_rows; + CSV * new_csv; + char * content; + bool in_old, in_new; - /* Build a new (fake) csv */ - new_csv = csv_create(new_cols, new_rows); - if (new_csv == NULL) { goto error; } + /* Build a new (fake) csv */ + new_csv = csv_create(new_cols, new_rows); + if (new_csv == NULL) { goto error; } - new_csv->rows = new_rows; - new_csv->cols = new_cols; + new_csv->rows = new_rows; + new_csv->cols = new_cols; - max_cols = (new_cols > old_csv->cols)? new_cols : old_csv->cols; - max_rows = (new_rows > old_csv->rows)? new_rows : old_csv->rows; + max_cols = (new_cols > old_csv->cols)? new_cols : old_csv->cols; + max_rows = (new_rows > old_csv->rows)? new_rows : old_csv->rows; - for (cur_col=0; cur_colcols) && (cur_row < old_csv->rows); - in_new = (cur_col < new_csv->cols) && (cur_row < new_csv->rows); + for (cur_col=0; cur_colcols) && (cur_row < old_csv->rows); + in_new = (cur_col < new_csv->cols) && (cur_row < new_csv->rows); - if (in_old && in_new) { - /* re-link data */ - content = csv_get(old_csv, cur_col, cur_row); - csv_set(new_csv, cur_col, cur_row, content); - } else if (in_old) { - /* destroy data */ - content = csv_get(old_csv, cur_col, cur_row); - free(content); - } else { /* skip */ } - } - } - /* on rows */ - free(old_csv->table); - old_csv->rows = new_rows; - old_csv->cols = new_cols; - old_csv->table = new_csv->table; - new_csv->table = NULL; - csv_destroy(new_csv); + if (in_old && in_new) { + /* re-link data */ + content = csv_get(old_csv, cur_col, cur_row); + csv_set(new_csv, cur_col, cur_row, content); + } else if (in_old) { + /* destroy data */ + content = csv_get(old_csv, cur_col, cur_row); + free(content); + } else { /* skip */ } + } + } + /* on rows */ + free(old_csv->table); + old_csv->rows = new_rows; + old_csv->cols = new_cols; + old_csv->table = new_csv->table; + new_csv->table = NULL; + csv_destroy(new_csv); - return 0; + return 0; error: - printf("Unable to resize CSV table: error %d - %s\n", errno, strerror(errno)); - return -1; + printf("Unable to resize CSV table: error %d - %s\n", errno, strerror(errno)); + return -1; } @@ -187,42 +187,42 @@ error: * Open CSV file and load its content into provided CSV structure **/ int csv_open(CSV * csv, char * filename) { - FILE * fp; - unsigned int m_rows; - unsigned int m_cols, cols; - char line[2048]; - char * lineptr; - char * token; + FILE * fp; + unsigned int m_rows; + unsigned int m_cols, cols; + char line[2048]; + char * lineptr; + char * token; - fp = fopen(filename, "r"); - if (fp == NULL) { goto error; } + fp = fopen(filename, "r"); + if (fp == NULL) { goto error; } - m_rows = 0; - m_cols = 0; - while(fgets(line, sizeof(line), fp) != NULL) { - m_rows += 1; - cols = 0; - lineptr = line; - while ((token = strtok(lineptr, csv->delim)) != NULL) { - lineptr = NULL; - trim(&token); + m_rows = 0; + m_cols = 0; + while(fgets(line, sizeof(line), fp) != NULL) { + m_rows += 1; + cols = 0; + lineptr = line; + while ((token = strtok(lineptr, csv->delim)) != NULL) { + lineptr = NULL; + trim(&token); cols += 1; - if (cols > m_cols) { m_cols = cols; } + if (cols > m_cols) { m_cols = cols; } csv_resize(csv, m_cols, m_rows); csv_set(csv, cols-1, m_rows-1, strdup(token)); } - } + } - fclose(fp); - csv->rows = m_rows; - csv->cols = m_cols; - return 0; + fclose(fp); + csv->rows = m_rows; + csv->cols = m_cols; + return 0; error: - fclose(fp); - printf("Unable to open %s for reading.", filename); - return -1; + fclose(fp); + printf("Unable to open %s for reading.", filename); + return -1; } @@ -230,22 +230,22 @@ error: * Open CSV file and save CSV structure content into it **/ int csv_save(CSV * csv, char * filename) { - FILE * fp; - int row, col; - char * content; + FILE * fp; + int row, col; + char * content; - fp = fopen(filename, "w"); - for (row=0; rowrows; row++) { - for (col=0; colcols; col++) { - content = csv_get(csv, col, row); + fp = fopen(filename, "w"); + for (row=0; rowrows; row++) { + for (col=0; colcols; col++) { + content = csv_get(csv, col, row); fprintf(fp, "%s%s", content, - ((col == csv->cols-1) ? "" : csv->delim) ); - } + ((col == csv->cols-1) ? "" : csv->delim) ); + } fprintf(fp, "\n"); - } + } - fclose(fp); - return 0; + fclose(fp); + return 0; } @@ -253,23 +253,23 @@ int csv_save(CSV * csv, char * filename) { * Test */ int main(int argc, char ** argv) { - CSV * csv; + CSV * csv; - printf("%s\n%s\n\n",TITLE, URL); + printf("%s\n%s\n\n",TITLE, URL); - csv = csv_create(0, 0); - csv_open(csv, "fixtures/csv-data-manipulation.csv"); - csv_display(csv); + csv = csv_create(0, 0); + csv_open(csv, "fixtures/csv-data-manipulation.csv"); + csv_display(csv); - csv_set(csv, 0, 0, "Column0"); - csv_set(csv, 1, 1, "100"); - csv_set(csv, 2, 2, "200"); - csv_set(csv, 3, 3, "300"); - csv_set(csv, 4, 4, "400"); - csv_display(csv); + csv_set(csv, 0, 0, "Column0"); + csv_set(csv, 1, 1, "100"); + csv_set(csv, 2, 2, "200"); + csv_set(csv, 3, 3, "300"); + csv_set(csv, 4, 4, "400"); + csv_display(csv); - csv_save(csv, "tmp/csv-data-manipulation.result.csv"); - csv_destroy(csv); + csv_save(csv, "tmp/csv-data-manipulation.result.csv"); + csv_destroy(csv); - return 0; + return 0; } diff --git a/Task/CSV-data-manipulation/COBOL/csv-data-manipulation.cobol b/Task/CSV-data-manipulation/COBOL/csv-data-manipulation.cob similarity index 100% rename from Task/CSV-data-manipulation/COBOL/csv-data-manipulation.cobol rename to Task/CSV-data-manipulation/COBOL/csv-data-manipulation.cob diff --git a/Task/CSV-data-manipulation/Delphi/csv-data-manipulation.delphi b/Task/CSV-data-manipulation/Delphi/csv-data-manipulation.pas similarity index 100% rename from Task/CSV-data-manipulation/Delphi/csv-data-manipulation.delphi rename to Task/CSV-data-manipulation/Delphi/csv-data-manipulation.pas diff --git a/Task/CSV-data-manipulation/DuckDB/csv-data-manipulation-1.duckdb b/Task/CSV-data-manipulation/DuckDB/csv-data-manipulation-1.duckdb new file mode 100644 index 0000000000..dd05c0680d --- /dev/null +++ b/Task/CSV-data-manipulation/DuckDB/csv-data-manipulation-1.duckdb @@ -0,0 +1,5 @@ +create or replace table csv as +from read_csv_auto('rc-csv-data-manipulation.csv'); + +# View the first row of the table: +from csv limit 1; diff --git a/Task/CSV-data-manipulation/DuckDB/csv-data-manipulation-2.duckdb b/Task/CSV-data-manipulation/DuckDB/csv-data-manipulation-2.duckdb new file mode 100644 index 0000000000..5078ee97a4 --- /dev/null +++ b/Task/CSV-data-manipulation/DuckDB/csv-data-manipulation-2.duckdb @@ -0,0 +1,4 @@ +copy + (select *, (C1 + C2 + C3 + C4 + C5) as sum + from csv) + to 'junk.csv'; diff --git a/Task/CSV-data-manipulation/DuckDB/csv-data-manipulation-3.duckdb b/Task/CSV-data-manipulation/DuckDB/csv-data-manipulation-3.duckdb new file mode 100644 index 0000000000..b3c1bedcf5 --- /dev/null +++ b/Task/CSV-data-manipulation/DuckDB/csv-data-manipulation-3.duckdb @@ -0,0 +1,6 @@ +ALTER TABLE csv ADD COLUMN sum integer; + +UPDATE csv +SET sum = C1 + C2 + C3 + C4 + C5; + +copy csv to 'junk2.csv'; diff --git a/Task/CSV-data-manipulation/ECL/csv-data-manipulation.ecl b/Task/CSV-data-manipulation/ECL/csv-data-manipulation.ecl index b69c763781..1e1feac64c 100644 --- a/Task/CSV-data-manipulation/ECL/csv-data-manipulation.ecl +++ b/Task/CSV-data-manipulation/ECL/csv-data-manipulation.ecl @@ -5,7 +5,7 @@ STRING Field2; STRING Field3; STRING Field4; STRING Field5; -END; +END; MyDataset := DATASET ('~Rosetta::myCSVFile', MyFileLayout,CSV(SEPARATOR(','))); diff --git a/Task/CSV-data-manipulation/EchoLisp/csv-data-manipulation-1.l b/Task/CSV-data-manipulation/EchoLisp/csv-data-manipulation-1.l index 9afa63c6bb..d621e254ba 100644 --- a/Task/CSV-data-manipulation/EchoLisp/csv-data-manipulation-1.l +++ b/Task/CSV-data-manipulation/EchoLisp/csv-data-manipulation-1.l @@ -10,12 +10,10 @@ (define (task file) (let* - ((table (csv->table file)) - (header (first table)) - (rows (rest table))) - - (table->csv - (append header "SUM") ;; add last column - (for/list ((row rows)) (append row (apply + row)))))) + ((table (csv->table file)) + (header (first table)) + (rows (rest table))) - + (table->csv + (append header "SUM") ;; add last column + (for/list ((row rows)) (append row (apply + row)))))) diff --git a/Task/CSV-data-manipulation/Elixir/csv-data-manipulation.elixir b/Task/CSV-data-manipulation/Elixir/csv-data-manipulation.ex similarity index 100% rename from Task/CSV-data-manipulation/Elixir/csv-data-manipulation.elixir rename to Task/CSV-data-manipulation/Elixir/csv-data-manipulation.ex diff --git a/Task/CSV-data-manipulation/Euphoria/csv-data-manipulation.eu b/Task/CSV-data-manipulation/Euphoria/csv-data-manipulation.eu new file mode 100644 index 0000000000..66f5a8b1dd --- /dev/null +++ b/Task/CSV-data-manipulation/Euphoria/csv-data-manipulation.eu @@ -0,0 +1,91 @@ +--- Read CSV file and add columns headed with 'SUM' +--- with trace +-- trace(0) + +include get.e +include std/text.e + +function split(sequence s, integer c) + sequence removables = " \t\n\r\x05\u0234\" " + sequence out + integer first, delim + out = {} + first = 1 + while first <= length(s) do + delim = find_from(c,s,first) + if delim = 0 then + delim = length(s)+1 + end if + out = append(out,trim(s[first..delim-1],removables)) + first = delim + 1 + end while + return out +end function + +procedure main() + integer fn -- the file number + integer fn2 -- the output file number + integer e -- the number of lines read + object line -- the next line from the file + sequence data = {} -- parsed csv data row + sequence headerNames = {} -- array saving column names + atom sum = 0.0 -- sum for each row + sequence var -- holds numerical data read + + -- First we try to open the file called "data.csv". + fn = open("data.csv", "r") + if fn = -1 then + puts(1, "Can't open data.csv\n") + -- abort(); + end if + + -- Then we create an output file for processed data. + fn2 = open("newdata.csv", "w") + if fn2 = -1 then + puts(1, "Can't create newdata.csv\n") + end if + + -- By successfully opening the file we have established that + -- the file exists, and open() gives us a file number (or "handle") + -- that we can use to perform operations on the file. + + e = 1 + while 1 do + line = gets(fn) + if atom(line) then + exit + end if + data = split(line, ',') + + if (e=1) then + -- Save the header labels and + -- write them to output file. + headerNames = data + for i=1 to length(headerNames) do + printf(fn2, "%s,", {headerNames[i]}) + end for + printf(fn2, "SUM\n") + end if + + -- Run a sum for the numerical data. + if (e >= 2) then + for i=1 to length(data) do + printf(fn2, "%s,", {data[i]}) + var = value(data[i]) + if var[1] = 0 then + -- data read is numerical + -- add to sum + sum = sum + var[2] + end if + end for + printf(fn2, "%g\n", {sum}) + sum = 0.0 + end if + e = e + 1 + end while + + close(fn) + close(fn2) +end procedure + +main() diff --git a/Task/CSV-data-manipulation/Euphoria/csv-data-manipulation.euphoria b/Task/CSV-data-manipulation/Euphoria/csv-data-manipulation.euphoria deleted file mode 100644 index 85ed288be0..0000000000 --- a/Task/CSV-data-manipulation/Euphoria/csv-data-manipulation.euphoria +++ /dev/null @@ -1,91 +0,0 @@ ---- Read CSV file and add columns headed with 'SUM' ---- with trace --- trace(0) - -include get.e -include std/text.e - -function split(sequence s, integer c) - sequence removables = " \t\n\r\x05\u0234\" " - sequence out - integer first, delim - out = {} - first = 1 - while first <= length(s) do - delim = find_from(c,s,first) - if delim = 0 then - delim = length(s)+1 - end if - out = append(out,trim(s[first..delim-1],removables)) - first = delim + 1 - end while - return out -end function - -procedure main() - integer fn -- the file number - integer fn2 -- the output file number - integer e -- the number of lines read - object line -- the next line from the file - sequence data = {} -- parsed csv data row - sequence headerNames = {} -- array saving column names - atom sum = 0.0 -- sum for each row - sequence var -- holds numerical data read - - -- First we try to open the file called "data.csv". - fn = open("data.csv", "r") - if fn = -1 then - puts(1, "Can't open data.csv\n") - -- abort(); - end if - - -- Then we create an output file for processed data. - fn2 = open("newdata.csv", "w") - if fn2 = -1 then - puts(1, "Can't create newdata.csv\n") - end if - - -- By successfully opening the file we have established that - -- the file exists, and open() gives us a file number (or "handle") - -- that we can use to perform operations on the file. - - e = 1 - while 1 do - line = gets(fn) - if atom(line) then - exit - end if - data = split(line, ',') - - if (e=1) then - -- Save the header labels and - -- write them to output file. - headerNames = data - for i=1 to length(headerNames) do - printf(fn2, "%s,", {headerNames[i]}) - end for - printf(fn2, "SUM\n") - end if - - -- Run a sum for the numerical data. - if (e >= 2) then - for i=1 to length(data) do - printf(fn2, "%s,", {data[i]}) - var = value(data[i]) - if var[1] = 0 then - -- data read is numerical - -- add to sum - sum = sum + var[2] - end if - end for - printf(fn2, "%g\n", {sum}) - sum = 0.0 - end if - e = e + 1 - end while - - close(fn) - close(fn2) -end procedure - -main() diff --git a/Task/CSV-data-manipulation/Fortran/csv-data-manipulation-2.f b/Task/CSV-data-manipulation/Fortran/csv-data-manipulation-2.f index ef63969cbc..6e400d25ef 100644 --- a/Task/CSV-data-manipulation/Fortran/csv-data-manipulation-2.f +++ b/Task/CSV-data-manipulation/Fortran/csv-data-manipulation-2.f @@ -1,20 +1,20 @@ Copies a file with 5 comma-separated values to a line, appending a column holding their sum. - INTEGER N !Instead of littering the source with "5" - PARAMETER (N = 5) !Provide some provenance. - CHARACTER*6 HEAD(N) !A perfect size? - INTEGER X(N) !Integers suffice. - INTEGER LINPR,IN !I/O unit numbers. - LINPR = 6 !Standard output via this unit number. - IN = 10 !Some unit number for the input file. - OPEN (IN,FILE="CSVtest.csv",STATUS="OLD",ACTION="READ") !For formatted input. + INTEGER N !Instead of littering the source with "5" + PARAMETER (N = 5) !Provide some provenance. + CHARACTER*6 HEAD(N) !A perfect size? + INTEGER X(N) !Integers suffice. + INTEGER LINPR,IN !I/O unit numbers. + LINPR = 6 !Standard output via this unit number. + IN = 10 !Some unit number for the input file. + OPEN (IN,FILE="CSVtest.csv",STATUS="OLD",ACTION="READ") !For formatted input. - READ (IN,*) HEAD !The first line has texts as column headings. - WRITE (LINPR,1) (TRIM(HEAD(I)), I = 1,N),"Sum" !Append a "Sum" column. - 1 FORMAT (666(A:",")) !The : sez "stop if no list element awaits". - 2 READ (IN,*,END = 10) X !Read a line's worth of numbers, separated by commas or spaces. - WRITE (LINPR,3) X,SUM(X) !Write, with a total appended. - 3 FORMAT (666(I0:",")) !I0 editing uses only as many columns as are needed. - GO TO 2 !Do it again. + READ (IN,*) HEAD !The first line has texts as column headings. + WRITE (LINPR,1) (TRIM(HEAD(I)), I = 1,N),"Sum" !Append a "Sum" column. + 1 FORMAT (666(A:",")) !The : sez "stop if no list element awaits". + 2 READ (IN,*,END = 10) X !Read a line's worth of numbers, separated by commas or spaces. + WRITE (LINPR,3) X,SUM(X) !Write, with a total appended. + 3 FORMAT (666(I0:",")) !I0 editing uses only as many columns as are needed. + GO TO 2 !Do it again. - 10 CLOSE (IN) !All done. - END !That's all. + 10 CLOSE (IN) !All done. + END !That's all. diff --git a/Task/CSV-data-manipulation/FunL/csv-data-manipulation.funl b/Task/CSV-data-manipulation/FunL/csv-data-manipulation.funl index 17cee74435..2bb6312e7a 100644 --- a/Task/CSV-data-manipulation/FunL/csv-data-manipulation.funl +++ b/Task/CSV-data-manipulation/FunL/csv-data-manipulation.funl @@ -34,7 +34,7 @@ def updateRow( header, row, updates ) = updates( r ) vector( r(f) | f <- header ) -def update( table, updates ) = +def update( table, updates ) = Table( table.header, (updateRow(table.header, r, updates) | r <- table.rows).toList() ) def addColumn( table, column, updates ) = diff --git a/Task/CSV-data-manipulation/Go/csv-data-manipulation.go b/Task/CSV-data-manipulation/Go/csv-data-manipulation.go index d6adc29b82..b893656760 100644 --- a/Task/CSV-data-manipulation/Go/csv-data-manipulation.go +++ b/Task/CSV-data-manipulation/Go/csv-data-manipulation.go @@ -1,58 +1,58 @@ package main import ( - "encoding/csv" - "log" - "os" - "strconv" + "encoding/csv" + "log" + "os" + "strconv" ) func main() { - rows := readSample() - appendSum(rows) - writeChanges(rows) + rows := readSample() + appendSum(rows) + writeChanges(rows) } func readSample() [][]string { - f, err := os.Open("sample.csv") - if err != nil { - log.Fatal(err) - } - rows, err := csv.NewReader(f).ReadAll() - f.Close() - if err != nil { - log.Fatal(err) - } - return rows + f, err := os.Open("sample.csv") + if err != nil { + log.Fatal(err) + } + rows, err := csv.NewReader(f).ReadAll() + f.Close() + if err != nil { + log.Fatal(err) + } + return rows } func appendSum(rows [][]string) { - rows[0] = append(rows[0], "SUM") - for i := 1; i < len(rows); i++ { - rows[i] = append(rows[i], sum(rows[i])) - } + rows[0] = append(rows[0], "SUM") + for i := 1; i < len(rows); i++ { + rows[i] = append(rows[i], sum(rows[i])) + } } func sum(row []string) string { - sum := 0 - for _, s := range row { - x, err := strconv.Atoi(s) - if err != nil { - return "NA" - } - sum += x - } - return strconv.Itoa(sum) + sum := 0 + for _, s := range row { + x, err := strconv.Atoi(s) + if err != nil { + return "NA" + } + sum += x + } + return strconv.Itoa(sum) } func writeChanges(rows [][]string) { - f, err := os.Create("output.csv") - if err != nil { - log.Fatal(err) - } - err = csv.NewWriter(f).WriteAll(rows) - f.Close() - if err != nil { - log.Fatal(err) - } + f, err := os.Create("output.csv") + if err != nil { + log.Fatal(err) + } + err = csv.NewWriter(f).WriteAll(rows) + f.Close() + if err != nil { + log.Fatal(err) + } } diff --git a/Task/CSV-data-manipulation/Julia/csv-data-manipulation.julia b/Task/CSV-data-manipulation/Julia/csv-data-manipulation.jl similarity index 100% rename from Task/CSV-data-manipulation/Julia/csv-data-manipulation.julia rename to Task/CSV-data-manipulation/Julia/csv-data-manipulation.jl diff --git a/Task/CSV-data-manipulation/Kotlin/csv-data-manipulation.kotlin b/Task/CSV-data-manipulation/Kotlin/csv-data-manipulation.kts similarity index 100% rename from Task/CSV-data-manipulation/Kotlin/csv-data-manipulation.kotlin rename to Task/CSV-data-manipulation/Kotlin/csv-data-manipulation.kts diff --git a/Task/CSV-data-manipulation/Logo/csv-data-manipulation-1.logo b/Task/CSV-data-manipulation/Logo/csv-data-manipulation-1.logo index f04a62f4a7..c8936190c7 100644 --- a/Task/CSV-data-manipulation/Logo/csv-data-manipulation-1.logo +++ b/Task/CSV-data-manipulation/Logo/csv-data-manipulation-1.logo @@ -1,19 +1,19 @@ to csv.data.manipulation :in :out local [header line list sum] - openread :in - setread :in - openwrite :out - setwrite :out - make "header readword + openread :in + setread :in + openwrite :out + setwrite :out + make "header readword print word :header ",SUM - while [not eofp] [ - make "line readword - make "list parse map [ifelse equalp ? ", ["\ ] [?]] :line - make "sum apply "sum :list - print (word :line "\, :sum) - ] - close :in - setread [] - close :out - setwrite [] + while [not eofp] [ + make "line readword + make "list parse map [ifelse equalp ? ", ["\ ] [?]] :line + make "sum apply "sum :list + print (word :line "\, :sum) + ] + close :in + setread [] + close :out + setwrite [] end diff --git a/Task/CSV-data-manipulation/Lua/csv-data-manipulation-1.lua b/Task/CSV-data-manipulation/Lua/csv-data-manipulation-1.lua new file mode 100644 index 0000000000..8296349d52 --- /dev/null +++ b/Task/CSV-data-manipulation/Lua/csv-data-manipulation-1.lua @@ -0,0 +1,11 @@ +-- Lua has no built in methods to handle csv files. +-- it does have string.gmatch, which we use to global.match whatever isn't a comma + +print(io.read"l" .. ",SUM") +for line in io.lines() do + local sum = 0 + for field in line:gmatch"[^,]+" do + sum = sum + field + end + print(line .. "," .. sum) +end diff --git a/Task/CSV-data-manipulation/Lua/csv-data-manipulation-2.lua b/Task/CSV-data-manipulation/Lua/csv-data-manipulation-2.lua new file mode 100644 index 0000000000..0469930ba1 --- /dev/null +++ b/Task/CSV-data-manipulation/Lua/csv-data-manipulation-2.lua @@ -0,0 +1,26 @@ +local csv={} + +-- read csv file, save records and fields into table +for line in io.lines('file.csv') do + local fields = {} + for field in line:gmatch"[^,]+" do + table.insert(fields, tonumber(field) or field) + end + table.insert(csv, fields) +end + +-- change csv values +table.insert(csv[1], 'SUM') +for i=2,#csv do + local sum=0 + for _, val in ipairs(csv[i]) do + sum = sum + val + end + table.insert(csv[i], sum) +end + +-- Save +local fileHandler = io.open('file.csv', 'w') +for NR, fields in ipairs(csv) do + fileHandler:write(table.concat(fields,","), "\n") +end diff --git a/Task/CSV-data-manipulation/Lua/csv-data-manipulation.lua b/Task/CSV-data-manipulation/Lua/csv-data-manipulation.lua deleted file mode 100644 index 26ddaeabc9..0000000000 --- a/Task/CSV-data-manipulation/Lua/csv-data-manipulation.lua +++ /dev/null @@ -1,31 +0,0 @@ -local csv={} -for line in io.lines('file.csv') do - table.insert(csv, {}) - local i=1 - for j=1,#line do - if line:sub(j,j) == ',' then - table.insert(csv[#csv], line:sub(i,j-1)) - i=j+1 - end - end - table.insert(csv[#csv], line:sub(i,j)) -end - -table.insert(csv[1], 'SUM') -for i=2,#csv do - local sum=0 - for j=1,#csv[i] do - sum=sum + tonumber(csv[i][j]) - end - if sum>0 then - table.insert(csv[i], sum) - end -end - -local newFileData = '' -for i=1,#csv do - newFileData=newFileData .. table.concat(csv[i], ',') .. '\n' -end - -local file=io.open('file.csv', 'w') -file:write(newFileData) diff --git a/Task/CSV-data-manipulation/M2000-Interpreter/csv-data-manipulation.m2000 b/Task/CSV-data-manipulation/M2000-Interpreter/csv-data-manipulation.m2000 index 7ef687eccb..ebca3c0383 100644 --- a/Task/CSV-data-manipulation/M2000-Interpreter/csv-data-manipulation.m2000 +++ b/Task/CSV-data-manipulation/M2000-Interpreter/csv-data-manipulation.m2000 @@ -1,6 +1,7 @@ +Locale 1032 Module Checkit { Function Sum { - Long c=0 + DECIMAL c=0 while not empty { c+=number } @@ -8,7 +9,7 @@ Module Checkit { } Document CSV$ = {C1,C2,C3,C4,C5 1,5,9,13,17 - 2,6,10,14,18 + 2,6,10.3,14,18 3,7,11,15,19 4,8,12,16,20 } @@ -19,13 +20,13 @@ Module Checkit { \\ use standard decimal point char \\ use standard (non json style string) \\ True = use bare strings (without "") - Input With "",,,true - Write With"",,,true + Input With "","",,true + Write With chr$(9),locale$(0xE),,true \\ for excel csv use Input With chr$(9),,true, true Open "data1.csv" for Wide Input as #M Open "data2.csv" for Wide Output as #M1 Input #M, h1$, h2$, h3$, h4$, h5$ - Write #M1, h1$, h2$, h3$, h4$, h5$ + Write #M1, h1$, h2$, h3$, h4$, h5$, "SUM" Print h1$, h2$, h3$, h4$, h5$ While not Eof(#M) { @@ -35,13 +36,15 @@ Module Checkit { } close #M1 Close #M + Input With chr$(9),locale$(0xE),,true Open "data2.csv" for Wide Input as #M - Input #M, h1$, h2$, h3$, h4$, h5$ - Print h1$, h2$, h3$, h4$, h5$ + Input #M, h1$, h2$, h3$, h4$, h5$, h6$ + Print h1$, h2$, h3$, h4$, h5$, h6$ While not Eof(#M) { Input #M, A1, A2, A3, A4, A5, Sum Print A1, A2, A3, A4, A5, Sum } Close #M + Win "Excel", dir$+"data2.csv" } Checkit diff --git a/Task/CSV-data-manipulation/MATLAB/csv-data-manipulation-1.m b/Task/CSV-data-manipulation/MATLAB/csv-data-manipulation-1.m index 16512a1db4..ad5d27aed9 100644 --- a/Task/CSV-data-manipulation/MATLAB/csv-data-manipulation-1.m +++ b/Task/CSV-data-manipulation/MATLAB/csv-data-manipulation-1.m @@ -7,7 +7,7 @@ X = dlmread(filename,',',1,0); fid = fopen('data.out.csv','w+'); fprintf(fid,'%s,sum\n',header); for k=1:size(X,1), - fprintf(fid,"%i,",X(k,:)); - fprintf(fid,"%i\n",sum(X(k,:))); + fprintf(fid,"%i,",X(k,:)); + fprintf(fid,"%i\n",sum(X(k,:))); end; fclose(fid); diff --git a/Task/CSV-data-manipulation/Nu/csv-data-manipulation-1.nu b/Task/CSV-data-manipulation/Nu/csv-data-manipulation-1.nu new file mode 100644 index 0000000000..d137dc1b65 --- /dev/null +++ b/Task/CSV-data-manipulation/Nu/csv-data-manipulation-1.nu @@ -0,0 +1,5 @@ +open 'test_in.csv' | + each { |row| + let sum = ($row | values | math sum); + $row | insert Sum $sum + } diff --git a/Task/CSV-data-manipulation/Nu/csv-data-manipulation-2.nu b/Task/CSV-data-manipulation/Nu/csv-data-manipulation-2.nu new file mode 100644 index 0000000000..82640ab976 --- /dev/null +++ b/Task/CSV-data-manipulation/Nu/csv-data-manipulation-2.nu @@ -0,0 +1 @@ +open 'test_in.csv' | upsert Sum {|row| $row | values | math sum } diff --git a/Task/CSV-data-manipulation/OCaml/csv-data-manipulation.ocaml b/Task/CSV-data-manipulation/OCaml/csv-data-manipulation.ml similarity index 100% rename from Task/CSV-data-manipulation/OCaml/csv-data-manipulation.ocaml rename to Task/CSV-data-manipulation/OCaml/csv-data-manipulation.ml diff --git a/Task/CSV-data-manipulation/PascalABC.NET/csv-data-manipulation.pas b/Task/CSV-data-manipulation/PascalABC.NET/csv-data-manipulation.pas new file mode 100644 index 0000000000..c2a30c8cee --- /dev/null +++ b/Task/CSV-data-manipulation/PascalABC.NET/csv-data-manipulation.pas @@ -0,0 +1,9 @@ +begin + var lines := ReadLines('data.csv').Select((line,i) -> begin + if i = 0 then + Result := line + ',SUM' + else Result := line + ',' + line.Split(',').Sum(x -> x.ToInteger); + end); + WriteLines('outdata.csv',lines); + lines.PrintLines; +end. diff --git a/Task/CSV-data-manipulation/PowerShell/csv-data-manipulation.psh b/Task/CSV-data-manipulation/PowerShell/csv-data-manipulation.ps1 similarity index 100% rename from Task/CSV-data-manipulation/PowerShell/csv-data-manipulation.psh rename to Task/CSV-data-manipulation/PowerShell/csv-data-manipulation.ps1 diff --git a/Task/CSV-data-manipulation/Prolog/csv-data-manipulation.pro b/Task/CSV-data-manipulation/Prolog/csv-data-manipulation.pro index 028345fd11..4f86884d47 100644 --- a/Task/CSV-data-manipulation/Prolog/csv-data-manipulation.pro +++ b/Task/CSV-data-manipulation/Prolog/csv-data-manipulation.pro @@ -2,21 +2,21 @@ test :- augment('test.csv', 'test.out.csv'). % augment( +InFileName, +OutFileName) augment(InFile, OutFile) :- - open(OutFile, write, OutStream), - ( ( csv_read_file_row(InFile, Row, [line(Line)]), - % Row is of the form row( Item1, Item2, ....). - addrow(Row, Out), - csv_write_stream(OutStream, [Out], []), - fail - ) - ; close(OutStream) - ). + open(OutFile, write, OutStream), + ( ( csv_read_file_row(InFile, Row, [line(Line)]), + % Row is of the form row( Item1, Item2, ....). + addrow(Row, Out), + csv_write_stream(OutStream, [Out], []), + fail + ) + ; close(OutStream) + ). % If the first item in a row is an integer, then append the sum; % otherwise append 'SUM': addrow( Term, NewTerm ) :- - Term =.. [F | List], - List = [X|_], - (integer(X) -> sum_list(List, Sum) ; Sum = 'SUM'), - append(List, [Sum], NewList), - NewTerm =.. [F | NewList]. + Term =.. [F | List], + List = [X|_], + (integer(X) -> sum_list(List, Sum) ; Sum = 'SUM'), + append(List, [Sum], NewList), + NewTerm =.. [F | NewList]. diff --git a/Task/CSV-data-manipulation/Python/csv-data-manipulation-4.py b/Task/CSV-data-manipulation/Python/csv-data-manipulation-4.py new file mode 100644 index 0000000000..a35b14ce8d --- /dev/null +++ b/Task/CSV-data-manipulation/Python/csv-data-manipulation-4.py @@ -0,0 +1,9 @@ +import polars as pl + +filepath = "data.csv" + +( + pl.scan_csv(filepath) + .with_columns(pl.sum_horizontal(pl.all()).alias("SUM")) + .sink_csv(filepath) +) diff --git a/Task/CSV-data-manipulation/Rebol/csv-data-manipulation.rebol b/Task/CSV-data-manipulation/Rebol/csv-data-manipulation.rebol new file mode 100644 index 0000000000..5f0eab3980 --- /dev/null +++ b/Task/CSV-data-manipulation/Rebol/csv-data-manipulation.rebol @@ -0,0 +1,35 @@ +Rebol [ + title: "Rosetta code: CSV data manipulation" + file: %CSV_data_manipulation.r3 + url: https://rosettacode.org/wiki/CSV_data_manipulation +] + +write %test.csv {C1,C2,C3,C4,C5 +1,5,9,13,17 +2,6,10,14,18 +3,7,11,15,19 +4,8,12,16,20} ;; create a sample CSV file on disk + +probe-csv: func [data][ + foreach row data [probe row] ;; helper: print each parsed CSV row using probe +] + +import csv ;; enable CSV codec for load/save of CSV files + +data: load %test.csv ;; load CSV into a block of rows (row 1 is header) +print "^/Original:" probe-csv data ;; show original data + +;; Add SUM column: +append data/1 "SUM" ;; extend header with a new column "SUM" +foreach row next data [ ;; iterate over data rows (skip header) + sum: 0 + forall row [ ;; walk each cell in the row in place + change row to integer! row/1 ;; convert current cell to integer (mutates row) + sum: sum + row/1 ;; accumulate the running total + ] + append row sum ;; append the computed sum at the end of the row +] +print "^/Modified:" probe-csv data ;; show data after adding the SUM column + +save %new.csv data ;; save the modified data to a new CSV file +print "^/Reloaded:" probe-csv load %new.csv ;; reload and display to verify persistence diff --git a/Task/CSV-data-manipulation/Red/csv-data-manipulation-2.red b/Task/CSV-data-manipulation/Red/csv-data-manipulation-2.red index caf8b0fc9d..c48fba572d 100644 --- a/Task/CSV-data-manipulation/Red/csv-data-manipulation-2.red +++ b/Task/CSV-data-manipulation/Red/csv-data-manipulation-2.red @@ -1,6 +1,6 @@ >>forall data [either (index? data) = 1[ - append data/1 "SUM" + append data/1 "SUM" ][ - append data/1 to string! - (to integer! data/1/1) + (to integer! data/1/2) + (to integer! data/1/3) + (to integer! data/1/4) + (to integer! data/1/5) + append data/1 to string! + (to integer! data/1/1) + (to integer! data/1/2) + (to integer! data/1/3) + (to integer! data/1/4) + (to integer! data/1/5) ]] diff --git a/Task/CSV-data-manipulation/Rust/csv-data-manipulation.rust b/Task/CSV-data-manipulation/Rust/csv-data-manipulation.rs similarity index 100% rename from Task/CSV-data-manipulation/Rust/csv-data-manipulation.rust rename to Task/CSV-data-manipulation/Rust/csv-data-manipulation.rs diff --git a/Task/CSV-data-manipulation/Scala/csv-data-manipulation.scala b/Task/CSV-data-manipulation/Scala/csv-data-manipulation.scala index 634a37b191..2abe9cda6f 100644 --- a/Task/CSV-data-manipulation/Scala/csv-data-manipulation.scala +++ b/Task/CSV-data-manipulation/Scala/csv-data-manipulation.scala @@ -3,10 +3,10 @@ import scala.io.Source object parseCSV extends App { val rawData = """|C1,C2,C3,C4,C5 - |1,5,9,13,17 - |2,6,10,14,18 - |3,7,11,15,19 - |20,21,22,23,24""".stripMargin + |1,5,9,13,17 + |2,6,10,14,18 + |3,7,11,15,19 + |20,21,22,23,24""".stripMargin val data = Seq((Source.fromString(rawData).getLines()).map(_.split(",")).toSeq: _*) diff --git a/Task/CSV-data-manipulation/SenseTalk/csv-data-manipulation.sensetalk b/Task/CSV-data-manipulation/SenseTalk/csv-data-manipulation.sensetalk index da0e4ef1f9..8278882de7 100644 --- a/Task/CSV-data-manipulation/SenseTalk/csv-data-manipulation.sensetalk +++ b/Task/CSV-data-manipulation/SenseTalk/csv-data-manipulation.sensetalk @@ -14,7 +14,7 @@ insert "SUM" into item 1 of csvData -- add a new column heading // Go through all of the data rows to add the sum repeat with rowNum= 2 to the number of items in csvData - insert the sum of item rowNum of csvData into item rowNum of csvData + insert the sum of item rowNum of csvData into item rowNum of csvData end repeat put csvData -- see the modified data as a list of lists diff --git a/Task/CSV-data-manipulation/Tcl/csv-data-manipulation-1.tcl b/Task/CSV-data-manipulation/Tcl/csv-data-manipulation-1.tcl index 9d26066be0..ad39da5984 100644 --- a/Task/CSV-data-manipulation/Tcl/csv-data-manipulation-1.tcl +++ b/Task/CSV-data-manipulation/Tcl/csv-data-manipulation-1.tcl @@ -13,9 +13,9 @@ proc addSumColumn {filename {title "SUM"}} { set sumcol [$m columns] $m add column $title for {set i 1} {$i < [$m rows]} {incr i} { - # Fill out a dummy value - $m set cell $sumcol $i 0 - $m set cell $sumcol $i [tcl::mathop::+ {*}[$m get row $i]] + # Fill out a dummy value + $m set cell $sumcol $i 0 + $m set cell $sumcol $i [tcl::mathop::+ {*}[$m get row $i]] } # Write the CSV out diff --git a/Task/CSV-data-manipulation/Tcl/csv-data-manipulation-2.tcl b/Task/CSV-data-manipulation/Tcl/csv-data-manipulation-2.tcl index e863925092..328e7512b6 100644 --- a/Task/CSV-data-manipulation/Tcl/csv-data-manipulation-2.tcl +++ b/Task/CSV-data-manipulation/Tcl/csv-data-manipulation-2.tcl @@ -1,6 +1,6 @@ set f [open example.csv r] puts "[gets $f],SUM" while { [gets $f row] > 0 } { - puts "$row,[expr [string map {, +} $row]]" + puts "$row,[expr [string map {, +} $row]]" } close $f diff --git a/Task/CSV-data-manipulation/Uiua/csv-data-manipulation.uiua b/Task/CSV-data-manipulation/Uiua/csv-data-manipulation.uiua new file mode 100644 index 0000000000..e6b7e04c7f --- /dev/null +++ b/Task/CSV-data-manipulation/Uiua/csv-data-manipulation.uiua @@ -0,0 +1,11 @@ +# Simple CSV manipulation + +# Effect of running `&fras "example.csv"` +$ C1,C2,C3,C4,C5 +$ 1,5,9,13,17 +$ 2,6,10,14,18 +$ 3,7,11,15,19 +$ 4,8,12,16,20 + +&p⍜°csv(⍜⍉˜⊂⊂□"SUM"≡(□⍜⋕/+)⊸↘1) +# Save using `&fwa "example.csv"` diff --git a/Task/CSV-data-manipulation/VBScript/csv-data-manipulation.vb b/Task/CSV-data-manipulation/VBScript/csv-data-manipulation.vb deleted file mode 100644 index da5502ec55..0000000000 --- a/Task/CSV-data-manipulation/VBScript/csv-data-manipulation.vb +++ /dev/null @@ -1,35 +0,0 @@ -'Instatiate FSO. -Set objFSO = CreateObject("Scripting.FileSystemObject") -'Open the CSV file for reading. The file is in the same folder as the script and named csv_sample.csv. -Set objInCSV = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) & "\csv_sample.csv",1,False) -'Set header status to account for the first line as the column headers. -IsHeader = True -'Initialize the var for the output string. -OutTxt = "" -'Read each line of the file. -Do Until objInCSV.AtEndOfStream - line = objInCSV.ReadLine - If IsHeader Then - OutTxt = OutTxt & line & ",SUM" & vbCrLf - IsHeader = False - Else - OutTxt = OutTxt & line & "," & AddElements(line) & vbCrLf - End If -Loop -'Close the file. -objInCSV.Close -'Open the same file for writing. -Set objOutCSV = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) & "\csv_sample.csv",2,True) -'Write the var OutTxt to the file overwriting existing contents. -objOutCSV.Write OutTxt -'Close the file. -objOutCSV.Close -Set objFSO = Nothing - -'Routine to add each element in a row. -Function AddElements(s) - arr = Split(s,",") - For i = 0 To UBound(arr) - AddElements = AddElements + CInt(arr(i)) - Next -End Function diff --git a/Task/CSV-data-manipulation/VBScript/csv-data-manipulation.vbs b/Task/CSV-data-manipulation/VBScript/csv-data-manipulation.vbs new file mode 100644 index 0000000000..00e334063a --- /dev/null +++ b/Task/CSV-data-manipulation/VBScript/csv-data-manipulation.vbs @@ -0,0 +1,35 @@ +'Instatiate FSO. +Set objFSO = CreateObject("Scripting.FileSystemObject") +'Open the CSV file for reading. The file is in the same folder as the script and named csv_sample.csv. +Set objInCSV = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) & "\csv_sample.csv",1,False) +'Set header status to account for the first line as the column headers. +IsHeader = True +'Initialize the var for the output string. +OutTxt = "" +'Read each line of the file. +Do Until objInCSV.AtEndOfStream + line = objInCSV.ReadLine + If IsHeader Then + OutTxt = OutTxt & line & ",SUM" & vbCrLf + IsHeader = False + Else + OutTxt = OutTxt & line & "," & AddElements(line) & vbCrLf + End If +Loop +'Close the file. +objInCSV.Close +'Open the same file for writing. +Set objOutCSV = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) & "\csv_sample.csv",2,True) +'Write the var OutTxt to the file overwriting existing contents. +objOutCSV.Write OutTxt +'Close the file. +objOutCSV.Close +Set objFSO = Nothing + +'Routine to add each element in a row. +Function AddElements(s) + arr = Split(s,",") + For i = 0 To UBound(arr) + AddElements = AddElements + CInt(arr(i)) + Next +End Function diff --git a/Task/CSV-to-HTML-translation/Ada/csv-to-html-translation-1.ada b/Task/CSV-to-HTML-translation/Ada/csv-to-html-translation-1.adb similarity index 100% rename from Task/CSV-to-HTML-translation/Ada/csv-to-html-translation-1.ada rename to Task/CSV-to-HTML-translation/Ada/csv-to-html-translation-1.adb diff --git a/Task/CSV-to-HTML-translation/Ada/csv-to-html-translation-2.ada b/Task/CSV-to-HTML-translation/Ada/csv-to-html-translation-2.adb similarity index 100% rename from Task/CSV-to-HTML-translation/Ada/csv-to-html-translation-2.ada rename to Task/CSV-to-HTML-translation/Ada/csv-to-html-translation-2.adb diff --git a/Task/CSV-to-HTML-translation/Ada/csv-to-html-translation-3.ada b/Task/CSV-to-HTML-translation/Ada/csv-to-html-translation-3.adb similarity index 100% rename from Task/CSV-to-HTML-translation/Ada/csv-to-html-translation-3.ada rename to Task/CSV-to-HTML-translation/Ada/csv-to-html-translation-3.adb diff --git a/Task/CSV-to-HTML-translation/AutoIt/csv-to-html-translation.au3 b/Task/CSV-to-HTML-translation/AutoIt/csv-to-html-translation.au3 new file mode 100644 index 0000000000..050b3b68a8 --- /dev/null +++ b/Task/CSV-to-HTML-translation/AutoIt/csv-to-html-translation.au3 @@ -0,0 +1,28 @@ + Local $ascarray[4] = [34,38,60,62] + $String = "Character,Speech" & @CRLF + $String &= "The multitude,The messiah! Show us the messiah!" & @CRLF + $String &= "Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!" & @CRLF + $String &= "The multitude,Who are you?" & @CRLF + $String &= "Brians mother,I'm his mother; that's who!" & @CRLF + $String &= "The multitude,Behold his mother! Behold his mother!" + For $i = 0 To UBound($ascarray) -1 + $String = Stringreplace($String, chr($ascarray[$i]), "&#"&$ascarray[$i]&";") + Next + $newstring = "" & @CRLF + $crlfsplit = StringSplit($String, @CRLF, 1) + For $i = 1 To $crlfsplit[0] + If $i = 1 Then $newstring &= "" & @CRLF + $newstring &= "" & @CRLF + $komsplit = StringSplit($crlfsplit[$i], ",") + For $k = 1 To $komsplit[0] + If $i = 1 Then + $newstring &= "" & @CRLF + Else + $newstring &= "" & @CRLF + EndIf + Next + $newstring &= "" & @CRLF + If $i = 1 Then $newstring &= "" & @CRLF + Next + $newstring &= "
    " &$komsplit[$k] & "" &$komsplit[$k] & "
    " + ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $newstring = ' & $newstring & @crlf & '>Error code: ' & @error & @crlf) ;### Debug Console diff --git a/Task/CSV-to-HTML-translation/AutoIt/csv-to-html-translation.autoit b/Task/CSV-to-HTML-translation/AutoIt/csv-to-html-translation.autoit deleted file mode 100644 index a7f613cb1e..0000000000 --- a/Task/CSV-to-HTML-translation/AutoIt/csv-to-html-translation.autoit +++ /dev/null @@ -1,28 +0,0 @@ - Local $ascarray[4] = [34,38,60,62] - $String = "Character,Speech" & @CRLF - $String &= "The multitude,The messiah! Show us the messiah!" & @CRLF - $String &= "Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!" & @CRLF - $String &= "The multitude,Who are you?" & @CRLF - $String &= "Brians mother,I'm his mother; that's who!" & @CRLF - $String &= "The multitude,Behold his mother! Behold his mother!" - For $i = 0 To UBound($ascarray) -1 - $String = Stringreplace($String, chr($ascarray[$i]), "&#"&$ascarray[$i]&";") - Next - $newstring = "" & @CRLF - $crlfsplit = StringSplit($String, @CRLF, 1) - For $i = 1 To $crlfsplit[0] - If $i = 1 Then $newstring &= "" & @CRLF - $newstring &= "" & @CRLF - $komsplit = StringSplit($crlfsplit[$i], ",") - For $k = 1 To $komsplit[0] - If $i = 1 Then - $newstring &= "" & @CRLF - Else - $newstring &= "" & @CRLF - EndIf - Next - $newstring &= "" & @CRLF - If $i = 1 Then $newstring &= "" & @CRLF - Next - $newstring &= "
    " &$komsplit[$k] & "" &$komsplit[$k] & "
    " - ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $newstring = ' & $newstring & @crlf & '>Error code: ' & @error & @crlf) ;### Debug Console diff --git a/Task/CSV-to-HTML-translation/C++/csv-to-html-translation-1.cpp b/Task/CSV-to-HTML-translation/C++/csv-to-html-translation-1.cpp index aa156642cd..3d37c4ac15 100644 --- a/Task/CSV-to-HTML-translation/C++/csv-to-html-translation-1.cpp +++ b/Task/CSV-to-HTML-translation/C++/csv-to-html-translation-1.cpp @@ -7,10 +7,10 @@ std::string csvToHTML( const std::string & ) ; int main( ) { std::string text = "Character,Speech\n" "The multitude,The messiah! Show us the messiah!\n" - "Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!\n" - "The multitude,Who are you?\n" - "Brians mother,I'm his mother; that's who!\n" - "The multitude,Behold his mother! Behold his mother!\n" ; + "Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!\n" + "The multitude,Who are you?\n" + "Brians mother,I'm his mother; that's who!\n" + "The multitude,Behold his mother! Behold his mother!\n" ; std::cout << csvToHTML( text ) ; return 0 ; } diff --git a/Task/CSV-to-HTML-translation/C-sharp/csv-to-html-translation-4.cs b/Task/CSV-to-HTML-translation/C-sharp/csv-to-html-translation-4.cs index 57a1a95782..0f5c4a0ec4 100644 --- a/Task/CSV-to-HTML-translation/C-sharp/csv-to-html-translation-4.cs +++ b/Task/CSV-to-HTML-translation/C-sharp/csv-to-html-translation-4.cs @@ -1,26 +1,26 @@ - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + +
    CharacterSpeech
    The multitudeThe messiah! Show us the messiah!
    Brians mother<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
    The multitudeWho are you?
    Brians motherI'm his mother; that's who!
    The multitudeBehold his mother! Behold his mother!
    CharacterSpeech
    The multitudeThe messiah! Show us the messiah!
    Brians mother<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
    The multitudeWho are you?
    Brians motherI'm his mother; that's who!
    The multitudeBehold his mother! Behold his mother!
    diff --git a/Task/CSV-to-HTML-translation/C/csv-to-html-translation-1.c b/Task/CSV-to-HTML-translation/C/csv-to-html-translation-1.c index 226784fac0..a4931a238c 100644 --- a/Task/CSV-to-HTML-translation/C/csv-to-html-translation-1.c +++ b/Task/CSV-to-HTML-translation/C/csv-to-html-translation-1.c @@ -1,29 +1,29 @@ #include const char *input = - "Character,Speech\n" - "The multitude,The messiah! Show us the messiah!\n" - "Brians mother,Now you listen here! He's not the messiah; " - "he's a very naughty boy! Now go away!\n" - "The multitude,Who are you?\n" - "Brians mother,I'm his mother; that's who!\n" - "The multitude,Behold his mother! Behold his mother!"; + "Character,Speech\n" + "The multitude,The messiah! Show us the messiah!\n" + "Brians mother,Now you listen here! He's not the messiah; " + "he's a very naughty boy! Now go away!\n" + "The multitude,Who are you?\n" + "Brians mother,I'm his mother; that's who!\n" + "The multitude,Behold his mother! Behold his mother!"; int main() { - const char *s; - printf("\n\n\n
    "); - for (s = input; *s; s++) { - switch(*s) { - case '\n': printf("
    "); break; - case ',': printf(""); break; - case '<': printf("<"); break; - case '>': printf(">"); break; - case '&': printf("&"); break; - default: putchar(*s); - } - } - puts("
    "); + const char *s; + printf("\n\n\n
    "); + for (s = input; *s; s++) { + switch(*s) { + case '\n': printf("
    "); break; + case ',': printf(""); break; + case '<': printf("<"); break; + case '>': printf(">"); break; + case '&': printf("&"); break; + default: putchar(*s); + } + } + puts("
    "); - return 0; + return 0; } diff --git a/Task/CSV-to-HTML-translation/CoffeeScript/csv-to-html-translation-1.coffee b/Task/CSV-to-HTML-translation/CoffeeScript/csv-to-html-translation-1.coffee index ed257aadae..3d1193f8f7 100644 --- a/Task/CSV-to-HTML-translation/CoffeeScript/csv-to-html-translation-1.coffee +++ b/Task/CSV-to-HTML-translation/CoffeeScript/csv-to-html-translation-1.coffee @@ -1,8 +1,8 @@ String::__defineGetter__ 'escaped', () -> - this.replace(/&/g, '&') - .replace(//g, '>') - .replace(/"/g, '"') // rosettacode doesn't like " + this.replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') // rosettacode doesn't like " text = ''' Character,Speech @@ -19,21 +19,21 @@ header = lines.shift() console.log """ - - - - - + + + + + """ for line in lines - [character, speech] = line - console.log """ - - - """ + [character, speech] = line + console.log """ + + + """ console.log """ - +
    #{header[0]}#{header[1]}
    #{header[0]}#{header[1]}
    #{character}#{speech.escaped}#{character}#{speech.escaped}
    - """ + """ diff --git a/Task/CSV-to-HTML-translation/Common-Lisp/csv-to-html-translation-1.lisp b/Task/CSV-to-HTML-translation/Common-Lisp/csv-to-html-translation-1.lisp index db8c7f95f8..b61d81aa92 100644 --- a/Task/CSV-to-HTML-translation/Common-Lisp/csv-to-html-translation-1.lisp +++ b/Task/CSV-to-HTML-translation/Common-Lisp/csv-to-html-translation-1.lisp @@ -8,9 +8,9 @@ The multitude,Behold his mother! Behold his mother!") (defun split-string (string delim-char) (let ((result '())) (do* ((start 0 (1+ end)) - (end (position delim-char string) - (position delim-char string :start start))) - ((not end) (reverse (cons (subseq string start) result))) + (end (position delim-char string) + (position delim-char string :start start))) + ((not end) (reverse (cons (subseq string start) result))) (push (subseq string start end) result)))) ;;; HTML escape code modified from: @@ -27,27 +27,27 @@ The multitude,Behold his mother! Behold his mother!") (let ((to-escape "<>&")) (flet ((needs-escape-p (char) (find char to-escape))) (with-output-to-string (out) - (loop for start = 0 then (1+ pos) - for pos = (position-if #'needs-escape-p in :start start) - do (write-sequence in out :start start :end pos) - when pos do (write-sequence (escape-char (char in pos)) out) - while pos))))) + (loop for start = 0 then (1+ pos) + for pos = (position-if #'needs-escape-p in :start start) + do (write-sequence in out :start start :end pos) + when pos do (write-sequence (escape-char (char in pos)) out) + while pos))))) (defun html-row (values headerp) (let ((tag (if headerp "th" "td"))) (with-output-to-string (out) (write-string "" out) (dolist (val values) - (format out "<~A>~A" tag (escape val) tag)) + (format out "<~A>~A" tag (escape val) tag)) (write-string "" out)))) (defun csv->html (csv) (let* ((lines (split-string csv #\Newline)) - (cols (split-string (first lines) #\,)) - (rows (mapcar (lambda (row) (split-string row #\,)) (rest lines)))) + (cols (split-string (first lines) #\,)) + (rows (mapcar (lambda (row) (split-string row #\,)) (rest lines)))) (with-output-to-string (html) (format html "~C" #\Newline) (format html "~C~A~C" #\Tab (html-row cols t) #\Newline) (dolist (row rows) - (format html "~C~A~C" #\Tab (html-row row nil) #\Newline)) + (format html "~C~A~C" #\Tab (html-row row nil) #\Newline)) (write-string "
    " html)))) diff --git a/Task/CSV-to-HTML-translation/Common-Lisp/csv-to-html-translation-2.lisp b/Task/CSV-to-HTML-translation/Common-Lisp/csv-to-html-translation-2.lisp index 66cb3587a8..06570481c8 100644 --- a/Task/CSV-to-HTML-translation/Common-Lisp/csv-to-html-translation-2.lisp +++ b/Task/CSV-to-HTML-translation/Common-Lisp/csv-to-html-translation-2.lisp @@ -1,8 +1,8 @@ - - - - - - + + + + + +
    CharacterSpeech
    The multitudeThe messiah! Show us the messiah!
    Brians mother<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
    The multitudeWho are you?
    Brians motherI'm his mother; that's who!
    The multitudeBehold his mother! Behold his mother!
    CharacterSpeech
    The multitudeThe messiah! Show us the messiah!
    Brians mother<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
    The multitudeWho are you?
    Brians motherI'm his mother; that's who!
    The multitudeBehold his mother! Behold his mother!
    diff --git a/Task/CSV-to-HTML-translation/Delphi/csv-to-html-translation-1.delphi b/Task/CSV-to-HTML-translation/Delphi/csv-to-html-translation-1.pas similarity index 100% rename from Task/CSV-to-HTML-translation/Delphi/csv-to-html-translation-1.delphi rename to Task/CSV-to-HTML-translation/Delphi/csv-to-html-translation-1.pas diff --git a/Task/CSV-to-HTML-translation/Delphi/csv-to-html-translation-2.delphi b/Task/CSV-to-HTML-translation/Delphi/csv-to-html-translation-2.pas similarity index 100% rename from Task/CSV-to-HTML-translation/Delphi/csv-to-html-translation-2.delphi rename to Task/CSV-to-HTML-translation/Delphi/csv-to-html-translation-2.pas diff --git a/Task/CSV-to-HTML-translation/Delphi/csv-to-html-translation-3.delphi b/Task/CSV-to-HTML-translation/Delphi/csv-to-html-translation-3.pas similarity index 100% rename from Task/CSV-to-HTML-translation/Delphi/csv-to-html-translation-3.delphi rename to Task/CSV-to-HTML-translation/Delphi/csv-to-html-translation-3.pas diff --git a/Task/CSV-to-HTML-translation/EchoLisp/csv-to-html-translation-1.l b/Task/CSV-to-HTML-translation/EchoLisp/csv-to-html-translation-1.l index a7a16c05df..d19889b08f 100644 --- a/Task/CSV-to-HTML-translation/EchoLisp/csv-to-html-translation-1.l +++ b/Task/CSV-to-HTML-translation/EchoLisp/csv-to-html-translation-1.l @@ -5,25 +5,25 @@ ;; LISTS->HTML (define html 'html) (define (emit-tag tag html-proc content ) - (if (style tag) - (push html (format "<%s style='%a'>" tag (style tag))) - (push html (format "<%s>" tag ))) - (html-proc content) - (push html (format " " tag ))) - + (if (style tag) + (push html (format "<%s style='%a'>" tag (style tag))) + (push html (format "<%s>" tag ))) + (html-proc content) + (push html (format " " tag ))) + ;; html procs : 1 tag, 1 proc (define (h-raw content) - (push html (format "%s" content))) + (push html (format "%s" content))) (define (h-header headers) - (for ((h headers)) (emit-tag 'th h-raw h))) + (for ((h headers)) (emit-tag 'th h-raw h))) (define (h-row row) - (for ((item row)) (emit-tag 'td h-raw item))) + (for ((item row)) (emit-tag 'td h-raw item))) (define (h-table table ) - (emit-tag 'tr h-header (first table)) - (for ((row (rest table))) (emit-tag 'tr h-row row))) - + (emit-tag 'tr h-header (first table)) + (for ((row (rest table))) (emit-tag 'tr h-row row))) + (define (html-dump) (string-join (stack->list html) " ")) - + ;; STYLES (style 'td "text-align:left") (style 'table "border-spacing: 10px;border:28px ridge orange") ;; special biblical border diff --git a/Task/CSV-to-HTML-translation/EchoLisp/csv-to-html-translation-2.l b/Task/CSV-to-HTML-translation/EchoLisp/csv-to-html-translation-2.l index 777daf9665..72ca8f6071 100644 --- a/Task/CSV-to-HTML-translation/EchoLisp/csv-to-html-translation-2.l +++ b/Task/CSV-to-HTML-translation/EchoLisp/csv-to-html-translation-2.l @@ -9,9 +9,9 @@ >>#) (define (task speech) - (define table (csv->table speech)) - (stack html) - (emit-tag 'table h-table table) - (html-dump)) - + (define table (csv->table speech)) + (stack html) + (emit-tag 'table h-table table) + (html-dump)) + (task MontyPython) diff --git a/Task/CSV-to-HTML-translation/Ed/csv-to-html-translation.ed b/Task/CSV-to-HTML-translation/Ed/csv-to-html-translation.ed new file mode 100644 index 0000000000..88664bdb10 --- /dev/null +++ b/Task/CSV-to-HTML-translation/Ed/csv-to-html-translation.ed @@ -0,0 +1,15 @@ +H +g/&/s//\&/g +g//s//\>/g +g/"/s//\"e;/g +g/^/s// /g +g/,/s//<\/td>/g +g/$/s//<\/td>\ + <\/tr>/ +1s/^/\ +/ +$s/$/\ +<\/table>/ +,p +Q diff --git a/Task/CSV-to-HTML-translation/Erlang/csv-to-html-translation.erl b/Task/CSV-to-HTML-translation/Erlang/csv-to-html-translation.erl index b319341dbb..31bfd905e1 100644 --- a/Task/CSV-to-HTML-translation/Erlang/csv-to-html-translation.erl +++ b/Task/CSV-to-HTML-translation/Erlang/csv-to-html-translation.erl @@ -3,9 +3,9 @@ -export( [table_translation/1, task/0] ). table_translation( CSV ) -> - [Headers | Contents] = [string:tokens(X, ",") || X <- string:tokens( CSV, "\n")], - Table = create_html_table:html_table( [{border, "1"}, {cellpadding, "10"}], Headers, Contents ), - create_html_table:external_format( Table ). + [Headers | Contents] = [string:tokens(X, ",") || X <- string:tokens( CSV, "\n")], + Table = create_html_table:html_table( [{border, "1"}, {cellpadding, "10"}], Headers, Contents ), + create_html_table:external_format( Table ). task() -> table_translation( csv() ). diff --git a/Task/CSV-to-HTML-translation/Euphoria/csv-to-html-translation-1.euphoria b/Task/CSV-to-HTML-translation/Euphoria/csv-to-html-translation-1.eu similarity index 100% rename from Task/CSV-to-HTML-translation/Euphoria/csv-to-html-translation-1.euphoria rename to Task/CSV-to-HTML-translation/Euphoria/csv-to-html-translation-1.eu diff --git a/Task/CSV-to-HTML-translation/Euphoria/csv-to-html-translation-2.euphoria b/Task/CSV-to-HTML-translation/Euphoria/csv-to-html-translation-2.eu similarity index 100% rename from Task/CSV-to-HTML-translation/Euphoria/csv-to-html-translation-2.euphoria rename to Task/CSV-to-HTML-translation/Euphoria/csv-to-html-translation-2.eu diff --git a/Task/CSV-to-HTML-translation/Forth/csv-to-html-translation-1.fth b/Task/CSV-to-HTML-translation/Forth/csv-to-html-translation-1.fth index b59459c399..9bf8d4b906 100644 --- a/Task/CSV-to-HTML-translation/Forth/csv-to-html-translation-1.fth +++ b/Task/CSV-to-HTML-translation/Forth/csv-to-html-translation-1.fth @@ -5,18 +5,18 @@ : END-ROW END-COLUMN ." " CR ; : CSV2HTML - ."
    " CR BEGIN-ROW - BEGIN KEY DUP #EOF <> WHILE - CASE - 10 OF END-ROW BEGIN-ROW ENDOF - [CHAR] , OF END-COLUMN BEGIN-COLUMN ENDOF - [CHAR] < OF ." <" ENDOF - [CHAR] > OF ." >" ENDOF - [CHAR] & OF ." &" ENDOF - DUP EMIT - ENDCASE - REPEAT - END-ROW ."
    " CR + ." " CR BEGIN-ROW + BEGIN KEY DUP #EOF <> WHILE + CASE + 10 OF END-ROW BEGIN-ROW ENDOF + [CHAR] , OF END-COLUMN BEGIN-COLUMN ENDOF + [CHAR] < OF ." <" ENDOF + [CHAR] > OF ." >" ENDOF + [CHAR] & OF ." &" ENDOF + DUP EMIT + ENDCASE + REPEAT + END-ROW ."
    " CR ; CSV2HTML BYE diff --git a/Task/CSV-to-HTML-translation/Fortran/csv-to-html-translation.f b/Task/CSV-to-HTML-translation/Fortran/csv-to-html-translation.f index 73683283d8..99aae70f36 100644 --- a/Task/CSV-to-HTML-translation/Fortran/csv-to-html-translation.f +++ b/Task/CSV-to-HTML-translation/Fortran/csv-to-html-translation.f @@ -1,71 +1,71 @@ - SUBROUTINE CSVTEXT2HTML(FNAME,HEADED) !Does not recognise quoted strings. + SUBROUTINE CSVTEXT2HTML(FNAME,HEADED) !Does not recognise quoted strings. Converts without checking field counts, or noting special characters. - CHARACTER*(*) FNAME !Names the input file. - LOGICAL HEADED !Perhaps its first line is to be a heading. - INTEGER MANY !How long is a piece of string? - PARAMETER (MANY=666) !This should suffice. - CHARACTER*(MANY) ALINE !A scratchpad for the input. - INTEGER MARK(0:MANY + 1) !Fingers the commas on a line. - INTEGER I,L,N !Assistants. - CHARACTER*2 WOT(2) !I don't see why a "table datum" could not be for either. - PARAMETER (WOT = (/"th","td"/)) !A table heding or a table datum - INTEGER IT !But, one must select appropriately. - INTEGER KBD,MSG,IN !A selection. - COMMON /IOUNITS/ KBD,MSG,IN !The caller thus avoids collisions. - OPEN(IN,FILE=FNAME,STATUS="OLD",ACTION="READ",ERR=661) !Go for the file. - WRITE (MSG,1) !Start the blather. - 1 FORMAT ("") !By stating that a table follows. - MARK(0) = 0 !Syncopation for the comma fingers. - N = 0 !No records read. + CHARACTER*(*) FNAME !Names the input file. + LOGICAL HEADED !Perhaps its first line is to be a heading. + INTEGER MANY !How long is a piece of string? + PARAMETER (MANY=666) !This should suffice. + CHARACTER*(MANY) ALINE !A scratchpad for the input. + INTEGER MARK(0:MANY + 1) !Fingers the commas on a line. + INTEGER I,L,N !Assistants. + CHARACTER*2 WOT(2) !I don't see why a "table datum" could not be for either. + PARAMETER (WOT = (/"th","td"/)) !A table heding or a table datum + INTEGER IT !But, one must select appropriately. + INTEGER KBD,MSG,IN !A selection. + COMMON /IOUNITS/ KBD,MSG,IN !The caller thus avoids collisions. + OPEN(IN,FILE=FNAME,STATUS="OLD",ACTION="READ",ERR=661) !Go for the file. + WRITE (MSG,1) !Start the blather. + 1 FORMAT ("
    ") !By stating that a table follows. + MARK(0) = 0 !Syncopation for the comma fingers. + N = 0 !No records read. - 10 READ (IN,11,END = 20) L,ALINE(1:MIN(L,MANY)) !Carefully acquire some text. - 11 FORMAT (Q,A) !Q = number of characters yet to read, A = characters. - N = N + 1 !So, a record has been read. - IF (L.GT.MANY) THEN !Perhaps it is rather long? - WRITE (MSG,12) N,L,MANY !Alas! - 12 FORMAT ("Line ",I0," has length ",I0,"! My limit is ",I0) !Squawk/ - L = MANY !The limit actually read. - END IF !So much for paranoia. - IF (N.EQ.1 .AND. HEADED) THEN !Is the first line to be treated specially? - WRITE (MSG,*) "" !Yep. Nominate a heading. - IT = 1 !And select "th" rather than "td". - ELSE !But mostly, - IT = 2 !Just another row for the table. - END IF !So much for the first line. - NCOLS = 0 !No commas have been seen. - DO I = 1,L !So scan the text for them. - IF (ICHAR(ALINE(I:I)).EQ.ICHAR(",")) THEN !Here? - NCOLS = NCOLS + 1 !Yes! - MARK(NCOLS) = I !The texts are between commas. - END IF !So much for that character. - END DO !On to the next. - NCOLS = NCOLS + 1 !This is why the + 1 for the size of MARK. - MARK(NCOLS) = L + 1 !End-of-line is as if a comma was one further along. - WRITE (MSG,13) !Now roll all the texts. - 1 (WOT(IT), !This starting a cell, - 2 ALINE(MARK(I - 1) + 1:MARK(I) - 1), !This being the text between the commas, - 3 WOT(IT), !And this ending each cell. - 4 I = 1,NCOLS), !For this number of columns. - 5 "/tr" !And this ends the row. - 13 FORMAT (" ",666("<",A,">",A,"")) !How long is a piece of string? - IF (N.EQ.1 .AND. HEADED) WRITE (MSG,*) "" !Finish the possible header. - GO TO 10 !And try for another record. + 10 READ (IN,11,END = 20) L,ALINE(1:MIN(L,MANY)) !Carefully acquire some text. + 11 FORMAT (Q,A) !Q = number of characters yet to read, A = characters. + N = N + 1 !So, a record has been read. + IF (L.GT.MANY) THEN !Perhaps it is rather long? + WRITE (MSG,12) N,L,MANY !Alas! + 12 FORMAT ("Line ",I0," has length ",I0,"! My limit is ",I0) !Squawk/ + L = MANY !The limit actually read. + END IF !So much for paranoia. + IF (N.EQ.1 .AND. HEADED) THEN !Is the first line to be treated specially? + WRITE (MSG,*) "" !Yep. Nominate a heading. + IT = 1 !And select "th" rather than "td". + ELSE !But mostly, + IT = 2 !Just another row for the table. + END IF !So much for the first line. + NCOLS = 0 !No commas have been seen. + DO I = 1,L !So scan the text for them. + IF (ICHAR(ALINE(I:I)).EQ.ICHAR(",")) THEN !Here? + NCOLS = NCOLS + 1 !Yes! + MARK(NCOLS) = I !The texts are between commas. + END IF !So much for that character. + END DO !On to the next. + NCOLS = NCOLS + 1 !This is why the + 1 for the size of MARK. + MARK(NCOLS) = L + 1 !End-of-line is as if a comma was one further along. + WRITE (MSG,13) !Now roll all the texts. + 1 (WOT(IT), !This starting a cell, + 2 ALINE(MARK(I - 1) + 1:MARK(I) - 1), !This being the text between the commas, + 3 WOT(IT), !And this ending each cell. + 4 I = 1,NCOLS), !For this number of columns. + 5 "/tr" !And this ends the row. + 13 FORMAT (" ",666("<",A,">",A,"")) !How long is a piece of string? + IF (N.EQ.1 .AND. HEADED) WRITE (MSG,*) "" !Finish the possible header. + GO TO 10 !And try for another record. - 20 CLOSE (IN) !Finished with input. - WRITE (MSG,21) !And finished with output. - 21 FORMAT ("
    ") !This writes starting at column one. - RETURN !Done! + 20 CLOSE (IN) !Finished with input. + WRITE (MSG,21) !And finished with output. + 21 FORMAT ("") !This writes starting at column one. + RETURN !Done! Confusions. - 661 WRITE (MSG,*) "Can't open file ",FNAME !Alas. - END !So much for the conversion. + 661 WRITE (MSG,*) "Can't open file ",FNAME !Alas. + END !So much for the conversion. INTEGER KBD,MSG,IN COMMON /IOUNITS/ KBD,MSG,IN - KBD = 5 !Standard input. - MSG = 6 !Standard output. - IN = 10 !Some unspecial number. + KBD = 5 !Standard input. + MSG = 6 !Standard output. + IN = 10 !Some unspecial number. - CALL CSVTEXT2HTML("Text.csv",.FALSE.) !The first line is not special. + CALL CSVTEXT2HTML("Text.csv",.FALSE.) !The first line is not special. WRITE (MSG,*) - CALL CSVTEXT2HTML("Text.csv",.TRUE.) !The first line is a heading. + CALL CSVTEXT2HTML("Text.csv",.TRUE.) !The first line is a heading. END diff --git a/Task/CSV-to-HTML-translation/Haskell/csv-to-html-translation-2.hs b/Task/CSV-to-HTML-translation/Haskell/csv-to-html-translation-2.hs index e1a1189b39..19062de634 100644 --- a/Task/CSV-to-HTML-translation/Haskell/csv-to-html-translation-2.hs +++ b/Task/CSV-to-HTML-translation/Haskell/csv-to-html-translation-2.hs @@ -6,6 +6,6 @@ main = interact (\csv -> "\n" ++ (unlines $ map ((\cols -> "\n" ++ (concatMap (\x -> " \n") cols) ++ "") . split (==',')) $ lines csv) ++ "
    " ++ concatMap (\c -> case c of {'<' -> "<"; '>' -> ">"; - '&' -> "&"; '"' -> """; _ -> [c]}) x + '&' -> "&"; '"' -> """; _ -> [c]}) x ++ "
    ") diff --git a/Task/CSV-to-HTML-translation/Java/csv-to-html-translation-2.java b/Task/CSV-to-HTML-translation/Java/csv-to-html-translation-2.java index 348dee6b96..854a68e627 100644 --- a/Task/CSV-to-HTML-translation/Java/csv-to-html-translation-2.java +++ b/Task/CSV-to-HTML-translation/Java/csv-to-html-translation-2.java @@ -4,83 +4,83 @@ import java.io.PrintStream; class Csv2Html { - public static String escapeChars(String lineIn) { - StringBuilder sb = new StringBuilder(); - int lineLength = lineIn.length(); - for (int i = 0; i < lineLength; i++) { - char c = lineIn.charAt(i); - switch (c) { - case '"': - sb.append("""); - break; - case '&': - sb.append("&"); - break; - case '\'': - sb.append("'"); - break; - case '<': - sb.append("<"); - break; - case '>': - sb.append(">"); - break; - default: sb.append(c); - } - } - return sb.toString(); - } + public static String escapeChars(String lineIn) { + StringBuilder sb = new StringBuilder(); + int lineLength = lineIn.length(); + for (int i = 0; i < lineLength; i++) { + char c = lineIn.charAt(i); + switch (c) { + case '"': + sb.append("""); + break; + case '&': + sb.append("&"); + break; + case '\'': + sb.append("'"); + break; + case '<': + sb.append("<"); + break; + case '>': + sb.append(">"); + break; + default: sb.append(c); + } + } + return sb.toString(); + } - public static void tableHeader(PrintStream ps, String[] columns) { - ps.print(""); - for (int i = 0; i < columns.length; i++) { - ps.print(""); - ps.print(columns[i]); - ps.print(""); - } - ps.println(""); - } - - public static void tableRow(PrintStream ps, String[] columns) { - ps.print(""); - for (int i = 0; i < columns.length; i++) { - ps.print(""); - ps.print(columns[i]); - ps.print(""); - } - ps.println(""); - } - - public static void main(String[] args) throws Exception { - boolean withTableHeader = (args.length != 0); - - InputStreamReader isr = new InputStreamReader(System.in); - BufferedReader br = new BufferedReader(isr); - PrintStream stdout = System.out; - - stdout.println(""); - stdout.println(""); - stdout.println(""); - stdout.println("Csv2Html"); - stdout.println(""); - stdout.println("

    Csv2Html

    "); + public static void tableHeader(PrintStream ps, String[] columns) { + ps.print(""); + for (int i = 0; i < columns.length; i++) { + ps.print(""); + ps.print(columns[i]); + ps.print(""); + } + ps.println(""); + } - stdout.println(""); - String stdinLine; - boolean firstLine = true; - while ((stdinLine = br.readLine()) != null) { - String[] columns = escapeChars(stdinLine).split(","); - if (withTableHeader == true && firstLine == true) { - tableHeader(stdout, columns); - firstLine = false; - } else { - tableRow(stdout, columns); - } - } - stdout.println("
    "); - } + public static void tableRow(PrintStream ps, String[] columns) { + ps.print(""); + for (int i = 0; i < columns.length; i++) { + ps.print(""); + ps.print(columns[i]); + ps.print(""); + } + ps.println(""); + } + + public static void main(String[] args) throws Exception { + boolean withTableHeader = (args.length != 0); + + InputStreamReader isr = new InputStreamReader(System.in); + BufferedReader br = new BufferedReader(isr); + PrintStream stdout = System.out; + + stdout.println(""); + stdout.println(""); + stdout.println(""); + stdout.println("Csv2Html"); + stdout.println(""); + stdout.println("

    Csv2Html

    "); + + stdout.println(""); + String stdinLine; + boolean firstLine = true; + while ((stdinLine = br.readLine()) != null) { + String[] columns = escapeChars(stdinLine).split(","); + if (withTableHeader == true && firstLine == true) { + tableHeader(stdout, columns); + firstLine = false; + } else { + tableRow(stdout, columns); + } + } + stdout.println("
    "); + } } diff --git a/Task/CSV-to-HTML-translation/JavaScript/csv-to-html-translation-1.js b/Task/CSV-to-HTML-translation/JavaScript/csv-to-html-translation-1.js index 216911471c..c3c985804f 100644 --- a/Task/CSV-to-HTML-translation/JavaScript/csv-to-html-translation-1.js +++ b/Task/CSV-to-HTML-translation/JavaScript/csv-to-html-translation-1.js @@ -1,9 +1,9 @@ var csv = "Character,Speech\n" + - "The multitude,The messiah! Show us the messiah!\n" + - "Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!\n" + - "The multitude,Who are you?\n" + - "Brians mother,I'm his mother; that's who!\n" + - "The multitude,Behold his mother! Behold his mother!"; + "The multitude,The messiah! Show us the messiah!\n" + + "Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!\n" + + "The multitude,Who are you?\n" + + "Brians mother,I'm his mother; that's who!\n" + + "The multitude,Behold his mother! Behold his mother!"; var lines = csv.replace(/&/g, '&') .replace(/ - - CharacterSpeech - - - The multitudeThe messiah! Show us the messiah! - Brians mother<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry> - The multitudeWho are you? - Brians motherI'm his mother; that's who! - The multitudeBehold his mother! Behold his mother! + + CharacterSpeech + + + The multitudeThe messiah! Show us the messiah! + Brians mother<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry> + The multitudeWho are you? + Brians motherI'm his mother; that's who! + The multitudeBehold his mother! Behold his mother! diff --git a/Task/CSV-to-HTML-translation/JavaScript/csv-to-html-translation-4.js b/Task/CSV-to-HTML-translation/JavaScript/csv-to-html-translation-4.js new file mode 100644 index 0000000000..1124a5e5d1 --- /dev/null +++ b/Task/CSV-to-HTML-translation/JavaScript/csv-to-html-translation-4.js @@ -0,0 +1,40 @@ +function csvToHtml(input) { + if (!input || typeof input !== 'string') { + throw new Error('Invalid input!'); + } + + function _createTableCell(cellContents, index) { + if (!cellContents || typeof cellContents !== 'string') { + throw new Error('Invalid data!'); + } + + const tableCell = document.createElement( + (index === 0) ? 'th' : 'td' + ); + + tableCell.textContent = cellContents.trim(); + return tableCell; + } + + const rows = input.split('\n'); + const table = document.createElement('table'); + + rows.forEach((row, index) => { + const tableRow = document.createElement('tr'); + const tableCells = row.split(','); + + tableCells.forEach((cell) => { + try { + tableRow.appendChild( + _createTableCell(cell, index), + ); + } catch (error) { + console.error(error); + } + }); + + table.appendChild(tableRow); + }); + + return table; +} diff --git a/Task/CSV-to-HTML-translation/JavaScript/csv-to-html-translation-5.js b/Task/CSV-to-HTML-translation/JavaScript/csv-to-html-translation-5.js new file mode 100644 index 0000000000..986924331b --- /dev/null +++ b/Task/CSV-to-HTML-translation/JavaScript/csv-to-html-translation-5.js @@ -0,0 +1,14 @@ +const inputData = `Character,Speech +The multitude,The messiah! Show us the messiah! +Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away! +The multitude,Who are you? +Brians mother,I'm his mother; that's who! +The multitude,Behold his mother! Behold his mother!`; + +try { + document.body.append( + csvToHtml(inputData), + ); +} catch (error) { + console.error(error) +} diff --git a/Task/CSV-to-HTML-translation/Julia/csv-to-html-translation-1.julia b/Task/CSV-to-HTML-translation/Julia/csv-to-html-translation-1.jl similarity index 100% rename from Task/CSV-to-HTML-translation/Julia/csv-to-html-translation-1.julia rename to Task/CSV-to-HTML-translation/Julia/csv-to-html-translation-1.jl diff --git a/Task/CSV-to-HTML-translation/Julia/csv-to-html-translation-2.julia b/Task/CSV-to-HTML-translation/Julia/csv-to-html-translation-2.jl similarity index 100% rename from Task/CSV-to-HTML-translation/Julia/csv-to-html-translation-2.julia rename to Task/CSV-to-HTML-translation/Julia/csv-to-html-translation-2.jl diff --git a/Task/CSV-to-HTML-translation/Kotlin/csv-to-html-translation-1.kotlin b/Task/CSV-to-HTML-translation/Kotlin/csv-to-html-translation-1.kts similarity index 100% rename from Task/CSV-to-HTML-translation/Kotlin/csv-to-html-translation-1.kotlin rename to Task/CSV-to-HTML-translation/Kotlin/csv-to-html-translation-1.kts diff --git a/Task/CSV-to-HTML-translation/Kotlin/csv-to-html-translation-2.kotlin b/Task/CSV-to-HTML-translation/Kotlin/csv-to-html-translation-2.kts similarity index 100% rename from Task/CSV-to-HTML-translation/Kotlin/csv-to-html-translation-2.kotlin rename to Task/CSV-to-HTML-translation/Kotlin/csv-to-html-translation-2.kts diff --git a/Task/CSV-to-HTML-translation/M2000-Interpreter/csv-to-html-translation.m2000 b/Task/CSV-to-HTML-translation/M2000-Interpreter/csv-to-html-translation.m2000 index af515e282b..446db07183 100644 --- a/Task/CSV-to-HTML-translation/M2000-Interpreter/csv-to-html-translation.m2000 +++ b/Task/CSV-to-HTML-translation/M2000-Interpreter/csv-to-html-translation.m2000 @@ -1,72 +1,72 @@ module csv2html { - nl$={ - } - Repl$=lambda$ (a$) ->{ - a$=replace$("&", "&",a$) - a$=replace$(">", ">",a$) - a$=replace$("""", """,a$) - // add any other replacement here - =replace$("<", "<",a$) - } - Tag$=lambda$ nl$, repl$ (a$, b$, n=4)->{ - if n>0 then - a$=rtrim$(replace$(nl$, nl$+string$(" ", n), nl$+a$)) - if right$(a$,2)<>nl$ then a$+=nl$ - else - if right$(a$, 2)=nl$ then if left$(a$,2)<>nl$ then a$=nl$+a$ - end if - prop=(,) : Read ? prop // forth parameter optional (we have to initalize first with an empty array) - p=each(prop) : prop$="" // p is an iteration object. - while p - prop$+=" "+repl$(prop#val$(p^))+"="+quote$(repl$(prop#val$(p^+1))) - p=each(prop,p^+2) // start new from p^+2 (p^ is the internal counter) - end while - ="<"+b$+prop$+">"+a$+""+nl$ - } - - // Prepare FILE csv - tofile$={Character,Speech - The multitude,The messiah! Show us the messiah! - Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away! - The multitude,Who are you? - Brians mother,I'm his mother; that's who! - The multitude,Behold his mother! Behold his mother! - } - open "forHtml.csv" for wide output as #f - Print #f, tofile$; - close #f - // prepare the input style for Input from file statement - // "," - we use comma between fields - // "." - for numbers we use dot for decimal separator - // false - we didn't read json style strings to normal strings (so \n convert to code 13, \t to code 9) - // true - we read strings unquote - input with ",",".",false, true - - // Read csv file - i=1 - document export$="" - Open "forHtml.csv" for wide input as #f - while not eof(#f) - input #f, a$, b$ - a$=repl$(a$) - b$=repl$(b$) - if i=1 then - export$+=tag$(tag$(a$, "th", 0)+tag$(b$,"th", 0), "tr", 4) - else - export$+=tag$(tag$(a$, "td", 0)+tag$(b$,"td", 0), "tr", 4) - end if - i++ - end while - close #f - style$=tag$({TD {background-color:#ddddff; } - thead TD {background-color:#ddffdd; text-align:center; } - },"style",4,("type", "text/css")) - title$= tag$("CSV to HTML translation - Extra Credit","title",0) - Head$= tag$(title$+ style$,"head") - html$={}+nl$+tag$(head$+tag$(tag$(export$, "table"), "body"), "html") - clipboard html$ - Report html$ - Print "Press Esc to exit browser" - browser "about: "+html$ + nl$={ + } + Repl$=lambda$ (a$) ->{ + a$=replace$("&", "&",a$) + a$=replace$(">", ">",a$) + a$=replace$("""", """,a$) + // add any other replacement here + =replace$("<", "<",a$) + } + Tag$=lambda$ nl$, repl$ (a$, b$, n=4)->{ + if n>0 then + a$=rtrim$(replace$(nl$, nl$+string$(" ", n), nl$+a$)) + if right$(a$,2)<>nl$ then a$+=nl$ + else + if right$(a$, 2)=nl$ then if left$(a$,2)<>nl$ then a$=nl$+a$ + end if + prop=(,) : Read ? prop // forth parameter optional (we have to initalize first with an empty array) + p=each(prop) : prop$="" // p is an iteration object. + while p + prop$+=" "+repl$(prop#val$(p^))+"="+quote$(repl$(prop#val$(p^+1))) + p=each(prop,p^+2) // start new from p^+2 (p^ is the internal counter) + end while + ="<"+b$+prop$+">"+a$+""+nl$ + } + + // Prepare FILE csv + tofile$={Character,Speech + The multitude,The messiah! Show us the messiah! + Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away! + The multitude,Who are you? + Brians mother,I'm his mother; that's who! + The multitude,Behold his mother! Behold his mother! + } + open "forHtml.csv" for wide output as #f + Print #f, tofile$; + close #f + // prepare the input style for Input from file statement + // "," - we use comma between fields + // "." - for numbers we use dot for decimal separator + // false - we didn't read json style strings to normal strings (so \n convert to code 13, \t to code 9) + // true - we read strings unquote + input with ",",".",false, true + + // Read csv file + i=1 + document export$="" + Open "forHtml.csv" for wide input as #f + while not eof(#f) + input #f, a$, b$ + a$=repl$(a$) + b$=repl$(b$) + if i=1 then + export$+=tag$(tag$(a$, "th", 0)+tag$(b$,"th", 0), "tr", 4) + else + export$+=tag$(tag$(a$, "td", 0)+tag$(b$,"td", 0), "tr", 4) + end if + i++ + end while + close #f + style$=tag$({TD {background-color:#ddddff; } + thead TD {background-color:#ddffdd; text-align:center; } + },"style",4,("type", "text/css")) + title$= tag$("CSV to HTML translation - Extra Credit","title",0) + Head$= tag$(title$+ style$,"head") + html$={}+nl$+tag$(head$+tag$(tag$(export$, "table"), "body"), "html") + clipboard html$ + Report html$ + Print "Press Esc to exit browser" + browser "about: "+html$ } csv2html diff --git a/Task/CSV-to-HTML-translation/MATLAB/csv-to-html-translation-3.m b/Task/CSV-to-HTML-translation/MATLAB/csv-to-html-translation-3.m index fc8d987cac..26001f6ada 100644 --- a/Task/CSV-to-HTML-translation/MATLAB/csv-to-html-translation-3.m +++ b/Task/CSV-to-HTML-translation/MATLAB/csv-to-html-translation-3.m @@ -1,25 +1,25 @@ - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + +
    CharacterSpeech
    The multitudeThe messiah! Show us the messiah!
    Brians mother<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
    The multitudeWho are you?
    Brians motherI'm his mother; that's who!
    The multitudeBehold his mother! Behold his mother!
    CharacterSpeech
    The multitudeThe messiah! Show us the messiah!
    Brians mother<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
    The multitudeWho are you?
    Brians motherI'm his mother; that's who!
    The multitudeBehold his mother! Behold his mother!
    diff --git a/Task/CSV-to-HTML-translation/Maple/csv-to-html-translation.maple b/Task/CSV-to-HTML-translation/Maple/csv-to-html-translation.maple index 5b6d65d7eb..0203f01f0d 100644 --- a/Task/CSV-to-HTML-translation/Maple/csv-to-html-translation.maple +++ b/Task/CSV-to-HTML-translation/Maple/csv-to-html-translation.maple @@ -1,10 +1,10 @@ #A translation of the C code posted html_table := proc(str) - local char; + local char; printf("\n\n\n\n" + htmlrow = "\t\n" - // loop through the values in the current csv row - for i in range(1, len(record)) - htmlrow = htmlrow + "\t\t<" + tag + ">" + (record ~ i) + "\n" - end for + // loop through the values in the current csv row + for i in range(1, len(record)) + htmlrow = htmlrow + "\t\t<" + tag + ">" + (record ~ i) + "\n" + end for - return htmlrow + "\t\n" + return htmlrow + "\t\n" end def // get the name of the csv file then open it @@ -23,7 +23,7 @@ htmltable = (htmltable + toHtmlRow(#0, "th")) // add all other rows to the table for i in range(1, $dbsize) - htmltable = (htmltable + toHtmlRow(#i, "td")) + htmltable = (htmltable + toHtmlRow(#i, "td")) end for // close the html table diff --git a/Task/CSV-to-HTML-translation/Nom/csv-to-html-translation-1.num b/Task/CSV-to-HTML-translation/Nom/csv-to-html-translation-1.num new file mode 100644 index 0000000000..c250b2c016 --- /dev/null +++ b/Task/CSV-to-HTML-translation/Nom/csv-to-html-translation-1.num @@ -0,0 +1,85 @@ +#* +(this is a multiline comment in Nom) + +GRAMMAR OR PARSE TOKENS + nl* - new line, end of line + field* - one csv field + fieldset* - a number of fields + record* - one record (line) or a set of csv fields + recordset* - +*# + + # using the empty recordset trick + begin { + add "recordset*"; push; + } + read; + # ignore whitespace outside of quotes + " " { while [ ]; clear; .restart } + "\n" { put; clear; add "nl*"; push; .reparse } + '"' { + until '"'; clip; clop; unescape '"'; + whilenot [\n,]; + replace "&" "&"; replace "<" "<"; replace ">" ">"; + put; clear; add ""; put; clear; + add "field*"; push; + clear; .reparse + } + "," { clear; } + + whilenot [\n,]; + replace "&" "&"; replace "<" "<"; replace ">" ">"; + put; clear; add ""; put; clear; + add "field*"; push; + +parse> + # useful for debugging + #add "line "; lines; add " char "; chars; add ": "; print; clear; + #add "\n"; unstack; print; clip; stack; + + # 1 token + pop; + # a record may be terminated by the end of input + (eof)."fieldset*" { + clear; add ""; get; add "\n"; put; clear; + add "record*"; push; .reparse + } + # 2 tokens + pop; + "recordset*field*" { + replace "field" "fieldset"; push; push; .reparse + } + # ignore blank lines + "recordset*nl*" { + clip; clip; clip; push; .reparse + } + "fieldset*field*" { + clear; get; ++; get; --; put; clear; + add "fieldset*"; push; .reparse + } + "fieldset*nl*" { + clear; add "\n "; get; add "\n"; put; clear; + add "record*"; push; .reparse + } + "recordset*record*" { + clear; a+; get; + ++; get; --; put; clear; + # if the count is 1, then this is the 1st + # record and should be marked up as a table header. + count; "1" { + clear; get; replace "tr>" "thead>"; put; + } + clear; add "recordset*"; push; .reparse + } + + (eof) { + !"recordset*" { + clear; add "[invalid csv]\nThe parse stack was: "; print; + clear; unstack; add "\n"; print; quit; + } + clear; + add "
    "); for char in str do if char = "\n" then - printf("
    ") + printf("
    ") elif char = "," then printf("") elif char = "<" then @@ -12,7 +12,7 @@ html_table := proc(str) elif char = ">" then printf(">") elif char = "&" then - printf("&") + printf("&") else printf(char) end if; diff --git a/Task/CSV-to-HTML-translation/Nanoquery/csv-to-html-translation.nanoquery b/Task/CSV-to-HTML-translation/Nanoquery/csv-to-html-translation.nanoquery index 1421fc83b6..7af517fddc 100644 --- a/Task/CSV-to-HTML-translation/Nanoquery/csv-to-html-translation.nanoquery +++ b/Task/CSV-to-HTML-translation/Nanoquery/csv-to-html-translation.nanoquery @@ -1,13 +1,13 @@ // a method that converts a csv row into a html table row as a string def toHtmlRow(record, tag) - htmlrow = "\t
    "; get; add ""; get; add "
    \n"; get; add "
    \n"; + add "[valid csv!] Found "; count; add " records.\n"; + print; quit; + } + push; push; diff --git a/Task/CSV-to-HTML-translation/Nom/csv-to-html-translation-2.num b/Task/CSV-to-HTML-translation/Nom/csv-to-html-translation-2.num new file mode 100644 index 0000000000..fa64e7c50e --- /dev/null +++ b/Task/CSV-to-HTML-translation/Nom/csv-to-html-translation-2.num @@ -0,0 +1,14 @@ + + + + + + + + + + + + + +
    CharacterSpeech
    The multitudeThe messiah! Show us the messiah!
    Brians mother<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
    The multitudeWho are you?
    Brians motherI'm his mother; that's who!
    The multitudeBehold his mother! Behold his mother!
    diff --git a/Task/CSV-to-HTML-translation/OCaml/csv-to-html-translation-1.ocaml b/Task/CSV-to-HTML-translation/OCaml/csv-to-html-translation-1.ml similarity index 100% rename from Task/CSV-to-HTML-translation/OCaml/csv-to-html-translation-1.ocaml rename to Task/CSV-to-HTML-translation/OCaml/csv-to-html-translation-1.ml diff --git a/Task/CSV-to-HTML-translation/OCaml/csv-to-html-translation-2.ocaml b/Task/CSV-to-HTML-translation/OCaml/csv-to-html-translation-2.ml similarity index 100% rename from Task/CSV-to-HTML-translation/OCaml/csv-to-html-translation-2.ocaml rename to Task/CSV-to-HTML-translation/OCaml/csv-to-html-translation-2.ml diff --git a/Task/CSV-to-HTML-translation/OCaml/csv-to-html-translation-3.ocaml b/Task/CSV-to-HTML-translation/OCaml/csv-to-html-translation-3.ml similarity index 100% rename from Task/CSV-to-HTML-translation/OCaml/csv-to-html-translation-3.ocaml rename to Task/CSV-to-HTML-translation/OCaml/csv-to-html-translation-3.ml diff --git a/Task/CSV-to-HTML-translation/OCaml/csv-to-html-translation-4.ocaml b/Task/CSV-to-HTML-translation/OCaml/csv-to-html-translation-4.ml similarity index 100% rename from Task/CSV-to-HTML-translation/OCaml/csv-to-html-translation-4.ocaml rename to Task/CSV-to-HTML-translation/OCaml/csv-to-html-translation-4.ml diff --git a/Task/CSV-to-HTML-translation/OmniMark/csv-to-html-translation-1.xom b/Task/CSV-to-HTML-translation/OmniMark/csv-to-html-translation-1.xom new file mode 100644 index 0000000000..10f9ee5923 --- /dev/null +++ b/Task/CSV-to-HTML-translation/OmniMark/csv-to-html-translation-1.xom @@ -0,0 +1,73 @@ +global switch thead initial {true} +global switch tbody-first initial {true} + +define function process-tr (value stream line) as + do when thead + output '%n' + else when tbody-first + output '%n' + output '%n' + deactivate tbody-first + else + output '' + done + repeat scan line + match ',' any-text => char + output '' when thead + output '' unless thead + using group ents submit char + match any-text => char + using group ents submit char + again + output '' unless thead + output '' when thead + output '' + deactivate thead + + +process-start + output '%n' || + '%n' || + '%n' || + '%n' || + 'Monty Python’s Life of Brian (1979). Scene 20 (extract).%n' || + '%n' || + '%n' || + '%n' || + '%n' || + '%n' || + '%n' || + '%n' + +process-end + output '%n' || + '
    %n' || + '%n' || + '%n' + ; Output validates to XHTML 1.0 - https://validator.w3.org/check + +process + local stream s + set s to "Character,Speech%n" || + "The multitude,The messiah! Show us the messiah!%n" || + "Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!%n" || + "The multitude,Who are you?%n" || + "Brians mother,I'm his mother; that's who!%n" || + "The multitude,Behold his mother! Behold his mother!%n" + using group line submit s + +group ents + + find '<' + output '<' + + find '>' + output '>' + + find "'" + output ''' + +group line + + find line-start any-text+ => line + process-tr(line) diff --git a/Task/CSV-to-HTML-translation/OmniMark/csv-to-html-translation-2.xom b/Task/CSV-to-HTML-translation/OmniMark/csv-to-html-translation-2.xom new file mode 100644 index 0000000000..92ff6b135c --- /dev/null +++ b/Task/CSV-to-HTML-translation/OmniMark/csv-to-html-translation-2.xom @@ -0,0 +1,27 @@ + + + + +Monty Python’s Life of Brian (1979). Scene 20 (extract). + + + + + + + + + + + + + + + + + +
    CharacterSpeech
    The multitudeThe messiah! Show us the messiah!
    Brians mother<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
    The multitudeWho are you?
    Brians motherI'm his mother; that's who!
    The multitudeBehold his mother! Behold his mother!
    + + diff --git a/Task/CSV-to-HTML-translation/OpenEdge-Progress/csv-to-html-translation-2.openedge b/Task/CSV-to-HTML-translation/OpenEdge-Progress/csv-to-html-translation-2.openedge index 0a1dc0c135..5d586a5912 100644 --- a/Task/CSV-to-HTML-translation/OpenEdge-Progress/csv-to-html-translation-2.openedge +++ b/Task/CSV-to-HTML-translation/OpenEdge-Progress/csv-to-html-translation-2.openedge @@ -1,28 +1,28 @@ - - - - - - - - - - - - - - - - - - - - - - - - - -
    CharacterSpeech
    The multitudeThe messiah! Show us the messiah!
    Brians mother<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
    The multitudeWho are you?
    Brians motherI'm his mother; that's who!
    The multitudeBehold his mother! Behold his mother!
    + + + + + + + + + + + + + + + + + + + + + + + + + +
    CharacterSpeech
    The multitudeThe messiah! Show us the messiah!
    Brians mother<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
    The multitudeWho are you?
    Brians motherI'm his mother; that's who!
    The multitudeBehold his mother! Behold his mother!
    diff --git a/Task/CSV-to-HTML-translation/PowerShell/csv-to-html-translation-1.psh b/Task/CSV-to-HTML-translation/PowerShell/csv-to-html-translation-1.ps1 similarity index 100% rename from Task/CSV-to-HTML-translation/PowerShell/csv-to-html-translation-1.psh rename to Task/CSV-to-HTML-translation/PowerShell/csv-to-html-translation-1.ps1 diff --git a/Task/CSV-to-HTML-translation/PowerShell/csv-to-html-translation-2.psh b/Task/CSV-to-HTML-translation/PowerShell/csv-to-html-translation-2.ps1 similarity index 100% rename from Task/CSV-to-HTML-translation/PowerShell/csv-to-html-translation-2.psh rename to Task/CSV-to-HTML-translation/PowerShell/csv-to-html-translation-2.ps1 diff --git a/Task/CSV-to-HTML-translation/PowerShell/csv-to-html-translation-3.psh b/Task/CSV-to-HTML-translation/PowerShell/csv-to-html-translation-3.ps1 similarity index 100% rename from Task/CSV-to-HTML-translation/PowerShell/csv-to-html-translation-3.psh rename to Task/CSV-to-HTML-translation/PowerShell/csv-to-html-translation-3.ps1 diff --git a/Task/CSV-to-HTML-translation/PowerShell/csv-to-html-translation-4.psh b/Task/CSV-to-HTML-translation/PowerShell/csv-to-html-translation-4.ps1 similarity index 100% rename from Task/CSV-to-HTML-translation/PowerShell/csv-to-html-translation-4.psh rename to Task/CSV-to-HTML-translation/PowerShell/csv-to-html-translation-4.ps1 diff --git a/Task/CSV-to-HTML-translation/Prolog/csv-to-html-translation-1.pro b/Task/CSV-to-HTML-translation/Prolog/csv-to-html-translation-1.pro index 06bf8c825f..735abd10f0 100644 --- a/Task/CSV-to-HTML-translation/Prolog/csv-to-html-translation-1.pro +++ b/Task/CSV-to-HTML-translation/Prolog/csv-to-html-translation-1.pro @@ -1,52 +1,52 @@ csv_html :- - L = "Character,Speech + L = "Character,Speech The multitude,The messiah! Show us the messiah! Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away! The multitude,Who are you? Brians mother,I'm his mother; that's who! The multitude,Behold his mother! Behold his mother!", - csv_html(L, Out, []), - string_to_list(Str, Out), - writeln(Str). + csv_html(L, Out, []), + string_to_list(Str, Out), + writeln(Str). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % simple HTML % csv_html(L) --> - "\n", - csv_tr(L), - "
    ". + "\n", + csv_tr(L), + "
    ". csv_tr([]) --> []. csv_tr(L) --> - "\n", - csv_td(L, S), - "\n\n", - csv_tr(S). + "\n", + csv_td(L, S), + "\n\n", + csv_tr(S). csv_td(L, S) --> - "", - csv_td_in(L, S), - "". + "", + csv_td_in(L, S), + "". csv_td_in([], []) --> []. csv_td_in([10|L], L) --> []. csv_td_in([44|L], S) --> - "", - csv_td_in(L,S). + "", + csv_td_in(L,S). csv_td_in([60|T], S) --> - "<", - csv_td_in(T, S). + "<", + csv_td_in(T, S). csv_td_in([62|T], S) --> - ">", - csv_td_in(T, S). + ">", + csv_td_in(T, S). csv_td_in([H|T], S) --> - [H], - csv_td_in(T, S). + [H], + csv_td_in(T, S). diff --git a/Task/CSV-to-HTML-translation/Prolog/csv-to-html-translation-3.pro b/Task/CSV-to-HTML-translation/Prolog/csv-to-html-translation-3.pro index c5c27aeaa0..317040a50e 100644 --- a/Task/CSV-to-HTML-translation/Prolog/csv-to-html-translation-3.pro +++ b/Task/CSV-to-HTML-translation/Prolog/csv-to-html-translation-3.pro @@ -1,5 +1,5 @@ csv_html_plus :- - L = + L = "Character,Speech The multitude,The messiah! Show us the messiah! Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away! @@ -7,84 +7,84 @@ The multitude,Who are you? Brians mother,I'm his mother; that's who! The multitude,Behold his mother! Behold his mother!", - csv_html_plus(L, Out1, []), - string_to_list(Str1, Out1), - writeln(Str1). + csv_html_plus(L, Out1, []), + string_to_list(Str1, Out1), + writeln(Str1). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % HTML + % csv_html_plus(L) --> - "\n", - csv_head(L, R), - csv_body(R), - "
    ". + "\n", + csv_head(L, R), + csv_body(R), + "
    ". csv_head(L, R) --> - "\n", - csv_head_tr(L, R), - "\n". + "\n", + csv_head_tr(L, R), + "\n". csv_head_tr(L, R) --> - "\n", - csv_head_th(L, R), - "\n\n". + "\n", + csv_head_th(L, R), + "\n\n". csv_head_th(L, S) --> - "", - csv_head_th_in(L, S), - "". + "", + csv_head_th_in(L, S), + "". csv_head_th_in([], []) --> []. csv_head_th_in([10|L], L) --> []. csv_head_th_in([44|L], S) --> - "", - csv_head_th_in(L,S). + "", + csv_head_th_in(L,S). csv_head_th_in([H|T], S) --> - [H], - csv_head_th_in(T, S). + [H], + csv_head_th_in(T, S). csv_body(L) --> - "\n", - csv_body_tr(L), - "\n". + "\n", + csv_body_tr(L), + "\n". csv_body_tr([]) --> []. csv_body_tr(L) --> - "\n", - csv_body_td(L, S), - "\n\n", - csv_body_tr(S). + "\n", + csv_body_td(L, S), + "\n\n", + csv_body_tr(S). csv_body_td(L, S) --> - "", - csv_body_td_in(L, S), - "". + "", + csv_body_td_in(L, S), + "". csv_body_td_in([], []) --> []. csv_body_td_in([10|L], L) --> []. csv_body_td_in([44|L], S) --> - "", - csv_body_td_in(L,S). + "", + csv_body_td_in(L,S). csv_body_td_in([60|T], S) --> - "<", - csv_body_td_in(T, S). + "<", + csv_body_td_in(T, S). csv_body_td_in([62|T], S) --> - ">", - csv_body_td_in(T, S). + ">", + csv_body_td_in(T, S). csv_body_td_in([H|T], S) --> - [H], - csv_body_td_in(T, S). + [H], + csv_body_td_in(T, S). diff --git a/Task/CSV-to-HTML-translation/Raku/csv-to-html-translation-1.raku b/Task/CSV-to-HTML-translation/Raku/csv-to-html-translation-1.raku index c171689eae..f6bfab0ad8 100644 --- a/Task/CSV-to-HTML-translation/Raku/csv-to-html-translation-1.raku +++ b/Task/CSV-to-HTML-translation/Raku/csv-to-html-translation-1.raku @@ -25,4 +25,4 @@ printf # that / at the end is just an unspace, you can omit it, but then you have to delete # all whitespace and comments between split(…) and .map .map({tag 'td', $^cell}))})\ # map those cells as td - .join("\n"); # append a newline for nicer output + .join("\n"); # append a newline for nicer output diff --git a/Task/CSV-to-HTML-translation/Rebol/csv-to-html-translation-1.rebol b/Task/CSV-to-HTML-translation/Rebol/csv-to-html-translation-1.rebol new file mode 100644 index 0000000000..406c067313 --- /dev/null +++ b/Task/CSV-to-HTML-translation/Rebol/csv-to-html-translation-1.rebol @@ -0,0 +1,53 @@ +Rebol [ + title: "Rosetta code: CSV to HTML translation" + file: %CSV_to_HTML_translation.r3 + url: https://rosettacode.org/wiki/CSV_to_HTML_translation + needs: 3.15.0 ;; or something like that +] +import csv + +csv-to-html: function/with [ + "Generate string with html table from csv data file" + csv [string! file!] "input .csv data" +][ + escape-html csv + + data: decode 'csv csv + html: copy "^/" + + emit-row/head data/1 + foreach row next data [ emit-row row ] + emit
    +][ + html: none + emit: func [val][ + if block? val [val: ajoin val] + append html val + ] + emit-row: func[row /head][ + emit [""] + foreach col row [ + emit-tag either head ['th]['td] col + ] + emit "^/" + ] + emit-tag: func [tag content][ + emit [#"<" tag #">" content ""] + ] + escape-html: function/with [str][ + parse str [any[ + to esc [ + change #"<" "<" + | change #">" ">" + | change #"&" "&" + ] + ]] + ][ esc: charset "<>&" ] +] + +print csv-to-html {Character,Speech +The multitude,The messiah! Show us the messiah! +Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away! +The multitude,Who are you? +Brians mother,I'm his mother; that's who! +The multitude,Behold his mother! Behold his mother!} diff --git a/Task/CSV-to-HTML-translation/Rebol/csv-to-html-translation-2.rebol b/Task/CSV-to-HTML-translation/Rebol/csv-to-html-translation-2.rebol new file mode 100644 index 0000000000..dfebcd13ff --- /dev/null +++ b/Task/CSV-to-HTML-translation/Rebol/csv-to-html-translation-2.rebol @@ -0,0 +1,8 @@ + + + + + + + +
    CharacterSpeech
    The multitudeThe messiah! Show us the messiah!
    Brians mother<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
    The multitudeWho are you?
    Brians motherI'm his mother; that's who!
    The multitudeBehold his mother! Behold his mother!
    diff --git a/Task/CSV-to-HTML-translation/Run-BASIC/csv-to-html-translation.basic b/Task/CSV-to-HTML-translation/Run-BASIC/csv-to-html-translation.basic index 4fa25a5ea3..41e53b8200 100644 --- a/Task/CSV-to-HTML-translation/Run-BASIC/csv-to-html-translation.basic +++ b/Task/CSV-to-HTML-translation/Run-BASIC/csv-to-html-translation.basic @@ -5,7 +5,7 @@ The multitude,Who are you? Brians mother,I'm his mother; that's who! The multitude,Behold his mother! Behold his mother!" -k = instr(csv$,",") ' 2 exra lines to get heading +k = instr(csv$,",") ' 2 exra lines to get heading csv$ = left$(csv$,k - 1) + " + mid$(csv$,k + 1) csv$ = strRep$(csv$,",","") @@ -15,10 +15,10 @@ wait ' string replace rep str with ' -------------------------------- FUNCTION strRep$(strRep$,rep$,with$) -ln = len(rep$) -k = instr(strRep$,rep$) +ln = len(rep$) +k = instr(strRep$,rep$) while k - strRep$ = left$(strRep$,k - 1) + with$ + mid$(strRep$,k + ln) - k = instr(strRep$,rep$) + strRep$ = left$(strRep$,k - 1) + with$ + mid$(strRep$,k + ln) + k = instr(strRep$,rep$) WEND END FUNCTION diff --git a/Task/CSV-to-HTML-translation/Rust/csv-to-html-translation-1.rust b/Task/CSV-to-HTML-translation/Rust/csv-to-html-translation-1.rs similarity index 100% rename from Task/CSV-to-HTML-translation/Rust/csv-to-html-translation-1.rust rename to Task/CSV-to-HTML-translation/Rust/csv-to-html-translation-1.rs diff --git a/Task/CSV-to-HTML-translation/Rust/csv-to-html-translation-2.rust b/Task/CSV-to-HTML-translation/Rust/csv-to-html-translation-2.rs similarity index 100% rename from Task/CSV-to-HTML-translation/Rust/csv-to-html-translation-2.rust rename to Task/CSV-to-HTML-translation/Rust/csv-to-html-translation-2.rs diff --git a/Task/CSV-to-HTML-translation/Tcl/csv-to-html-translation-1.tcl b/Task/CSV-to-HTML-translation/Tcl/csv-to-html-translation-1.tcl index 6b41ae0db4..2761df41e6 100644 --- a/Task/CSV-to-HTML-translation/Tcl/csv-to-html-translation-1.tcl +++ b/Task/CSV-to-HTML-translation/Tcl/csv-to-html-translation-1.tcl @@ -18,7 +18,7 @@ html::init puts [subst { [html::openTag table {summary="csv2html program output"}] [html::while {[rows size]} { - [html::row {*}[html::quoteFormValue [rows get]]] + [html::row {*}[html::quoteFormValue [rows get]]] }] [html::closeTag] }] diff --git a/Task/CSV-to-HTML-translation/Tcl/csv-to-html-translation-2.tcl b/Task/CSV-to-HTML-translation/Tcl/csv-to-html-translation-2.tcl index 748d62eea4..18c6bcdfff 100644 --- a/Task/CSV-to-HTML-translation/Tcl/csv-to-html-translation-2.tcl +++ b/Task/CSV-to-HTML-translation/Tcl/csv-to-html-translation-2.tcl @@ -37,9 +37,9 @@ foreach line [split $csvData "\n"] { # Generate the output puts [subst { [table { - [tr [html::quoteFormValue [rows get]] {bgcolor="yellow"}] - [html::while {[rows size]} { - [tr [html::quoteFormValue [rows get]]] - }] + [tr [html::quoteFormValue [rows get]] {bgcolor="yellow"}] + [html::while {[rows size]} { + [tr [html::quoteFormValue [rows get]]] + }] }] }] diff --git a/Task/CSV-to-HTML-translation/Uiua/csv-to-html-translation.uiua b/Task/CSV-to-HTML-translation/Uiua/csv-to-html-translation.uiua new file mode 100644 index 0000000000..8b7fe76408 --- /dev/null +++ b/Task/CSV-to-HTML-translation/Uiua/csv-to-html-translation.uiua @@ -0,0 +1,9 @@ +$ Character,Speech +$ The multitude,The messiah! Show us the messiah! +$ Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away! +$ The multitude,Who are you? +$ Brians mother,I'm his mother; that's who! +$ The multitude,Behold his mother! Behold his mother! +⊜(□$"_"/◇⊂⊜(□$"_")⊸≠@,)⊸≠@\n +/◇$"_\n_" +&p$"\n\n_\n
    CharacterSpeech
    " diff --git a/Task/CSV-to-HTML-translation/VBScript/csv-to-html-translation.vb b/Task/CSV-to-HTML-translation/VBScript/csv-to-html-translation.vb deleted file mode 100644 index 2eadb9ed6f..0000000000 --- a/Task/CSV-to-HTML-translation/VBScript/csv-to-html-translation.vb +++ /dev/null @@ -1,33 +0,0 @@ -Set objfso = CreateObject("Scripting.FileSystemObject") - -parent_folder = objfso.GetParentFolderName(WScript.ScriptFullName) & "\" - -Set objcsv = objfso.OpenTextFile(parent_folder & "in.csv",1,False) -Set objhtml = objfso.OpenTextFile(paren_folder & "out.html",2,True) - -objhtml.Write(csv_to_html(objcsv.ReadAll)) - -objcsv.Close -objhtml.Close -Set objfso = Nothing - -Function csv_to_html(s) - row = Split(s,vbCrLf) - 'write the header - tmp = "" - For i = 0 To UBound(row) - field = Split(row(i),",") - If i = 0 Then - tmp = tmp & "" - Else - tmp = tmp & "" - End If - Next - 'write the footer - tmp = tmp & "
    " & replace_chars(field(0)) & "" & replace_chars(field(1)) & "
    " & replace_chars(field(0)) & "" & replace_chars(field(1)) & "
    " - csv_to_html = tmp -End Function - -Function replace_chars(s) - replace_chars = Replace(Replace(s,"<","<"),">",">") -End Function diff --git a/Task/CSV-to-HTML-translation/VBScript/csv-to-html-translation.vbs b/Task/CSV-to-HTML-translation/VBScript/csv-to-html-translation.vbs new file mode 100644 index 0000000000..33894748ed --- /dev/null +++ b/Task/CSV-to-HTML-translation/VBScript/csv-to-html-translation.vbs @@ -0,0 +1,33 @@ +Set objfso = CreateObject("Scripting.FileSystemObject") + +parent_folder = objfso.GetParentFolderName(WScript.ScriptFullName) & "\" + +Set objcsv = objfso.OpenTextFile(parent_folder & "in.csv",1,False) +Set objhtml = objfso.OpenTextFile(paren_folder & "out.html",2,True) + +objhtml.Write(csv_to_html(objcsv.ReadAll)) + +objcsv.Close +objhtml.Close +Set objfso = Nothing + +Function csv_to_html(s) + row = Split(s,vbCrLf) + 'write the header + tmp = "" + For i = 0 To UBound(row) + field = Split(row(i),",") + If i = 0 Then + tmp = tmp & "" + Else + tmp = tmp & "" + End If + Next + 'write the footer + tmp = tmp & "
    " & replace_chars(field(0)) & "" & replace_chars(field(1)) & "
    " & replace_chars(field(0)) & "" & replace_chars(field(1)) & "
    " + csv_to_html = tmp +End Function + +Function replace_chars(s) + replace_chars = Replace(Replace(s,"<","<"),">",">") +End Function diff --git a/Task/CUSIP/11l/cusip.11l b/Task/CUSIP/11l/cusip.11l index 3728e24945..c3bafa6306 100644 --- a/Task/CUSIP/11l/cusip.11l +++ b/Task/CUSIP/11l/cusip.11l @@ -4,7 +4,7 @@ F cusip_check(=cusip) cusip = cusip.uppercase() V total = 0 - L(i) 8 + L(i) 0.<8 V v = 0 V c = cusip[i] I c.is_digit() diff --git a/Task/CUSIP/ALGOL-68/cusip.alg b/Task/CUSIP/ALGOL-68/cusip.alg index 32d1c0bad0..95cae39ff8 100644 --- a/Task/CUSIP/ALGOL-68/cusip.alg +++ b/Task/CUSIP/ALGOL-68/cusip.alg @@ -1,44 +1,35 @@ -BEGIN - # returns TRUE if cusip is a valid CUSIP code # - OP ISCUSIP = ( STRING cusip )BOOL: - IF ( UPB cusip - LWB cusip ) /= 8 - THEN - # code is wrong length # - FALSE - ELSE - # string is 9 characters long - check it is valid # - STRING cusip digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ*@#"[ AT 0 ]; - INT check digit := 0; - IF NOT char in string( cusip[ UPB cusip ], check digit, cusip digits ) - THEN - # invalid check digit # - FALSE - ELSE - # OK so far compare the calculated check sum to the supplied one # - INT sum := 0; - INT c pos := LWB cusip - 1; - FOR i TO 8 DO - INT digit := 0; - IF NOT char in string( cusip[ i + c pos ], digit, cusip digits ) - THEN - # invalid digit # - digit := -999 - FI; - IF NOT ODD i - THEN - # even digit # - digit *:= 2 - FI; - sum +:= ( digit OVER 10 ) + ( digit MOD 10 ) - OD; - ( 10 - ( sum MOD 10 ) ) MOD 10 = check digit - FI - FI ; # ISCUSIP # +BEGIN # validate CUSIP codes # + + # returns TRUE if cusip string is a valid CUSIP code, FALSE otherwise # + OP ISCUSIP = ( STRING cusip string )BOOL: + IF UPB cusip string - LWB cusip string /= 8 + THEN FALSE # CUSIP code is not 9 characters long # + ELSE # CUSIP code has the correct length # + + # returns the base 39 digit corresponding to a character of a CUSIP code # + PROC cusip digit = ( CHAR c char )INT: + IF STRING cusip digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ*@#"[ AT 0 ]; + INT digit := 0; + char in string( c char, digit, cusip digits ) + THEN digit + ELSE -999 # invalid digit # + FI # cusip digit # ; + + []CHAR cusip = cusip string[ AT 1 ]; + INT sum := 0; + INT check digit = cusip digit( cusip[ UPB cusip ] ); + FOR c pos TO UPB cusip - 1 DO + INT digit := cusip digit( cusip[ c pos ] ); + IF NOT ODD c pos THEN digit *:= 2 FI; + sum +:= ( digit OVER 10 ) + ( digit MOD 10 ) + OD; + ( 10 - ( sum MOD 10 ) ) MOD 10 = check digit + FI # is cusip # ; # task test cases # PROC test cusip = ( STRING cusip )VOID: - print( ( cusip, IF ISCUSIP cusip THEN " valid" ELSE " invalid" FI, newline ) ); + print( ( cusip, IF ISCUSIP cusip THEN " valid" ELSE " invalid" FI, newline ) ); test cusip( "037833100" ); test cusip( "17275R102" ); diff --git a/Task/CUSIP/ANSI-BASIC/cusip.basic b/Task/CUSIP/ANSI-BASIC/cusip.basic new file mode 100644 index 0000000000..13e8080304 --- /dev/null +++ b/Task/CUSIP/ANSI-BASIC/cusip.basic @@ -0,0 +1,63 @@ +100 REM CUSIP +110 DECLARE EXTERNAL SUB PrintVerdict +120 DECLARE EXTERNAL FUNCTION CusipCheckDigit +130 DECLARE EXTERNAL FUNCTION IsValidCusip +140 PRINT "CUSIP Verdict" +150 CALL PrintVerdict("037833100") +160 CALL PrintVerdict("17275R102") +170 CALL PrintVerdict("38259P508") +180 CALL PrintVerdict("594918104") +190 CALL PrintVerdict("68389X106") +200 CALL PrintVerdict("68389X105") +210 END +220 REM ** +230 EXTERNAL FUNCTION CusipCheckDigit(Cusip$) +240 LET I = 1 +250 LET Sum = 0 +260 LET L = LEN(Cusip$) +270 DO WHILE I < L +280 LET C$ = Cusip$(I:I) +290 IF ("0" <= C$) AND (C$ <= "9") THEN +300 LET V = VAL(C$) +310 ELSEIF ("A" <= C$) AND (C$ <= "Z") THEN +320 LET V = ORD(C$) - 65 + 10 +330 ELSEIF C$ = "*" THEN +340 LET V = 36 +350 ELSEIF C$ = "@" THEN +360 LET V = 37 +370 ELSEIF C$ = "#" THEN +380 LET V = 38 +390 ELSE +400 LET CusipCheckDigit = -1 +410 EXIT FUNCTION +420 END IF +430 IF MOD(I - 1, 2) = 1 THEN LET V = 2 * V +440 IF I <= 8 THEN LET Sum = Sum + INT(V / 10) + MOD(V, 10) +450 LET I = I + 1 +460 LOOP +470 IF I <> 9 THEN +480 LET CusipCheckDigit = -1 +490 ELSE +500 LET CusipCheckDigit = MOD(10 - MOD(Sum, 10), 10) +510 END IF +520 END FUNCTION +530 REM ** +540 EXTERNAL FUNCTION IsValidCusip (Cusip$) +550 LET Check = CusipCheckDigit(Cusip$) +560 IF Check < 0 THEN +570 LET IsValidCusip = 0 +580 ELSEIF Cusip$(9:9) = CHR$(48 + Check) THEN +590 LET IsValidCusip = -1 +600 ELSE +610 LET IsValidCusip = 0 +620 END IF +630 END FUNCTION +640 REM ** +650 EXTERNAL SUB PrintVerdict (Cusip$) +660 PRINT Cusip$; +670 IF IsValidCusip(Cusip$) <>0 THEN +680 PRINT " : Valid" +690 ELSE +700 PRINT " : Invalid" +710 END IF +720 END SUB diff --git a/Task/CUSIP/Ada/cusip.ada b/Task/CUSIP/Ada/cusip.adb similarity index 100% rename from Task/CUSIP/Ada/cusip.ada rename to Task/CUSIP/Ada/cusip.adb diff --git a/Task/CUSIP/Arturo/cusip.arturo b/Task/CUSIP/Arturo/cusip.arturo index b8615d3d49..bde0bd1ddc 100644 --- a/Task/CUSIP/Arturo/cusip.arturo +++ b/Task/CUSIP/Arturo/cusip.arturo @@ -1,17 +1,17 @@ validCUSIP?: function [cusip][ s: 0 - alpha: `A`..`Z` + alpha: 'A'..'Z' loop.with:'i chop cusip 'c [ v: 0 - case ø - when? [numeric? c] -> v: to :integer to :string c - when? [in? c alpha] -> v: (index alpha c) + 1 + 9 - when? [c = `*`] -> v: 36 - when? [c = `@`] -> v: 37 - when? [c = `#`] -> v: 38 - else [] + when.has: c [ + [|numeric?] -> v: to :integer to :string c + [|in? alpha] -> v: (index alpha c) + 1 + 9 + [= '*'] -> v: 36 + [= '@'] -> v: 37 + [= '#'] -> v: 38 + ] if odd? i -> v: 2 * v diff --git a/Task/CUSIP/BQN/cusip.bqn b/Task/CUSIP/BQN/cusip.bqn new file mode 100644 index 0000000000..dd8bf31a89 --- /dev/null +++ b/Task/CUSIP/BQN/cusip.bqn @@ -0,0 +1,5 @@ +d ← ∾"0A*@#"+⟜↕¨10‿26‿1‿1‿1 +m ← 8⥊1‿2 +Check ← ¯1(⊑=10|0-˜´10(|+⌊∘÷˜)m×↓)d⊐⊢ + +Check¨ "037833100"‿"17275R102"‿"38259P508"‿"594918104"‿"68389X106"‿"68389X105" diff --git a/Task/CUSIP/Crystal/cusip.cr b/Task/CUSIP/Crystal/cusip.cr new file mode 100644 index 0000000000..f601d4b0cf --- /dev/null +++ b/Task/CUSIP/Crystal/cusip.cr @@ -0,0 +1,28 @@ +def cusip_check (input) + return false unless input.size == 9 + sum = 0 + input.chars.each_with_index do |c, i| + break if i == 8 + v = case c + when .ascii_number? then c.to_i + when .ascii_uppercase? then c.ord - 'A'.ord + 10 + when '*' then 36 + when '@' then 37 + when '#' then 38 + else return false + end + v *= 2 if (i+1).even? + + sum += v // 10 + v % 10 + end + input[-1].to_i? == (10 - sum % 10) % 10 +end + +["037833100", + "17275R102", + "38259P508", + "594918104", + "68389X106", + "68389X105"].each do |cusip| + print cusip, ": ", cusip_check(cusip) ? "valid" : "invalid", "\n" +end diff --git a/Task/CUSIP/Delphi/cusip.delphi b/Task/CUSIP/Delphi/cusip.pas similarity index 100% rename from Task/CUSIP/Delphi/cusip.delphi rename to Task/CUSIP/Delphi/cusip.pas diff --git a/Task/CUSIP/EasyLang/cusip.easy b/Task/CUSIP/EasyLang/cusip.easy index f9ebc73bfc..574de473d0 100644 --- a/Task/CUSIP/EasyLang/cusip.easy +++ b/Task/CUSIP/EasyLang/cusip.easy @@ -12,12 +12,10 @@ func check inp$ . elif c = 35 v = 38 . - if i mod 2 = 0 - v *= 2 - . + if i mod 2 = 0 : v *= 2 sum += v div 10 + v mod 10 . - return if (10 - (sum mod 10)) mod 10 = number substr inp$ 9 1 + return if (10 - sum mod 10) mod 10 = number substr inp$ 9 1 . for s$ in [ "037833100" "17275R102" "38259P508" "594918104" "68389X106" "68389X105" ] write s$ & " is " diff --git a/Task/CUSIP/Julia/cusip.julia b/Task/CUSIP/Julia/cusip.jl similarity index 100% rename from Task/CUSIP/Julia/cusip.julia rename to Task/CUSIP/Julia/cusip.jl diff --git a/Task/CUSIP/Kotlin/cusip.kotlin b/Task/CUSIP/Kotlin/cusip.kts similarity index 100% rename from Task/CUSIP/Kotlin/cusip.kotlin rename to Task/CUSIP/Kotlin/cusip.kts diff --git a/Task/CUSIP/Langur/cusip-1.langur b/Task/CUSIP/Langur/cusip-1.langur index 7153ac3e7b..69451c3430 100644 --- a/Task/CUSIP/Langur/cusip-1.langur +++ b/Task/CUSIP/Langur/cusip-1.langur @@ -1,23 +1,21 @@ -val .isCusip = fn(.s) { - if .s is not string or len(.s) != 9 { - return false +val isCusip = fn(s string) { + if len(s) != 9 : return false + + val basechars = '0'..'9' ~ 'A'..'Z' ~ "*@#" + + val sum = for[=0] i of 8 { + var v = index(basechars, by=s2s(s, of=i)) + if not v: return false + v = v[1]-1 + if i div 2: v *= 2 + _for += v \ 10 + v rem 10 } - val .basechars = '0'..'9' ~ 'A'..'Z' ~ "*@#" - - val .sum = for[=0] .i of 8 { - var .v = index(s2s(.s, .i), .basechars) - if not .v: return false - .v = .v[1]-1 - if .i div 2: .v *= 2 - _for += .v \ 10 + .v rem 10 - } - - .s[9]-'0' == (10-(.sum rem 10)) rem 10 + s[9]-'0' == (10-(sum rem 10)) rem 10 } -val .candidates = fw/037833100 17275R102 38259P508 594918104 68389X106 68389X105/ +val candidates = fw/037833100 17275R102 38259P508 594918104 68389X106 68389X105/ -for .c in .candidates { - writeln .c, ": ", if(.isCusip(.c): "good" ; "bad") +for c in candidates { + writeln c, ": ", if(isCusip(c): "good" ; "bad") } diff --git a/Task/CUSIP/Langur/cusip-2.langur b/Task/CUSIP/Langur/cusip-2.langur index 792cec79d2..ed2dd39a3f 100644 --- a/Task/CUSIP/Langur/cusip-2.langur +++ b/Task/CUSIP/Langur/cusip-2.langur @@ -1,35 +1,35 @@ -val .isCusip = fn(.s) { - if .s is not string or len(.s) != 9 { - return false - } +val isCusip = fn(s string) { + if len(s) != 9 : return false - val .sum = for[=0] .i of 8 { - val .c = .s[.i] - var .v = 0 + val basechars = '0'..'9' ~ 'A'..'Z' ~ "*@#" - switch[and] .c { + val sum = for[=0] i of 8 { + val c = s[i] + var v = 0 + + switch[and] c { case >= '0', <= '9': - .v = .c-'0' + v = c-'0' case >= 'A', <= 'Z': - .v = .c-55 # .c-'A'+10 + v = c-55 # c-'A'+10 - case '*': .v = 36 - case '@': .v = 37 - case '#': .v = 38 + case '*': v = 36 + case '@': v = 37 + case '#': v = 38 default: return false } - if .i div 2: .v *= 2 - _for += .v \ 10 + .v rem 10 + if i div 2: v *= 2 + _for += v \ 10 + v rem 10 } - .s[9]-'0' == (10-(.sum rem 10)) rem 10 + s[9]-'0' == (10-(sum rem 10)) rem 10 } -val .candidates = w/037833100 17275R102 38259P508 594918104 68389X106 68389X105/ +val candidates = fw/037833100 17275R102 38259P508 594918104 68389X106 68389X105/ -for .c in .candidates { - writeln .c, ": ", if(.isCusip(.c): "good" ; "bad") +for c in candidates { + writeln c, ": ", if(isCusip(c): "good" ; "bad") } diff --git a/Task/CUSIP/Loglan82/cusip.loglan82 b/Task/CUSIP/Loglan82/cusip.loglan82 new file mode 100644 index 0000000000..7a3a1210de --- /dev/null +++ b/Task/CUSIP/Loglan82/cusip.loglan82 @@ -0,0 +1,89 @@ +(* CUSIP *) + +block + + unit check_digit: function (cusip: string): integer; + var + sum, v, i_first, i_last, i: integer, + c: character, + check_needed: boolean, + ccusip: arrayof character; + begin + sum := 0; + ccusip := unpack(cusip); + i, i_first := lower(ccusip); + i_last := upper(ccusip); + check_needed := true; + while (i < i_last) and check_needed + do + c := ccusip(i); + if ord(c) >= ord('0') and ord(c) <= ord('9') + then + v := ord(c) - ord('0') + else + if ord('A') <= ord(c) and ord(c) <= ord('Z') + then + v := ord(c) - ord('A') + 10 + else + case c + when '*': v := 36; + when '@': v := 37; + when '#': v := 38; + otherwise + result := -1; + check_needed := false + esac + fi + fi; + if check_needed + then + if (i - i_first) mod 2 = 1 then v := 2 * v fi; + if i - i_first <= 7 then sum := sum + v div 10 + v mod 10 fi; + i := i + 1 + fi; + od; + if check_needed + then + if i - i_first =/= 8 + then + result := -1 + else + result := (10 - sum mod 10) mod 10 + fi; + fi; + end check_digit; + + unit is_valid: function (cusip: string): boolean; + var + check: integer, + ccusip: arrayof character; + begin + check := check_digit(cusip); + if check < 0 + then + result := false + else + ccusip := unpack(cusip); + result := ord(ccusip(lower(ccusip) + 8)) = ord('0') + check + fi; + end is_valid; + + unit write_verdict: procedure (cusip: string); + begin + if is_valid(cusip) + then + writeln(cusip, " : Valid") + else + writeln(cusip, " : Invalid") + fi + end write_verdict; + +begin + writeln("CUSIP Verdict"); + call write_verdict("037833100"); + call write_verdict("17275R102"); + call write_verdict("38259P508"); + call write_verdict("594918104"); + call write_verdict("68389X106"); + call write_verdict("68389X105"); +end; diff --git a/Task/CUSIP/Oberon-07/cusip.oberon b/Task/CUSIP/Oberon-07/cusip.oberon new file mode 100644 index 0000000000..23d635fd12 --- /dev/null +++ b/Task/CUSIP/Oberon-07/cusip.oberon @@ -0,0 +1,60 @@ +MODULE Cusip; (* validate CUSIP codes *) + IMPORT Strings, Out; + + CONST cusipBase = 39; + cusipLength = 9; + VAR cusipDigits : ARRAY cusipBase + 1 OF CHAR; (* 39 digits + trailing nul *) + + (* returns TRUE if cusip is a valid CUSIP code, FALSE otherwise *) + PROCEDURE isCusip( cusip : ARRAY OF CHAR ) : BOOLEAN; + VAR sum, digit, cPos, checkDigit : INTEGER; + isValid : BOOLEAN; + + (* returns the base 39 digit corresponding to a character of a CUSIP code *) + PROCEDURE cusipDigit( cChar : CHAR ) : INTEGER; + VAR digit, dPos : INTEGER; + BEGIN + digit := -999; + dPos := 0; + WHILE ( dPos <= cusipBase ) & ( digit < 0 ) DO + IF cusipDigits[ dPos ] = cChar THEN digit := dPos END; + INC( dPos ) + END + RETURN digit + END cusipDigit ; + + BEGIN + IF Strings.Length( cusip ) # cusipLength THEN + isValid := FALSE (* invalid length code *) + ELSE + (* CUSIP code has the correct length *) + sum := 0; + checkDigit := cusipDigit( cusip[ cusipLength - 1 ] ); + FOR cPos := 0 TO cusipLength - 2 DO + digit := cusipDigit( cusip[ cPos ] ); + IF ODD( cPos ) THEN digit := digit * 2 END; + INC( sum, ( digit DIV 10 ) + ( digit MOD 10 ) ) + END; + isValid := ( 10 - ( sum MOD 10 ) ) MOD 10 = checkDigit + END + RETURN isValid + END isCusip ; + + PROCEDURE testCusip( cusip : ARRAY OF CHAR ) ; + BEGIN + Out.String( cusip ); + IF isCusip( cusip ) THEN Out.String( " valid" ) ELSE Out.String( " invalid" ) END; + Out.Ln + END testCusip; + +BEGIN + + cusipDigits := "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ*@#"; + + testCusip( "037833100" ); + testCusip( "17275R102" ); + testCusip( "38259P508" ); + testCusip( "594918104" ); + testCusip( "68389X106" ); + testCusip( "68389X105" ) +END Cusip. diff --git a/Task/CUSIP/Pascal-P/cusip.pas b/Task/CUSIP/Pascal-P/cusip.pas new file mode 100644 index 0000000000..34d081a34a --- /dev/null +++ b/Task/CUSIP/Pascal-P/cusip.pas @@ -0,0 +1,70 @@ +program cusip(output); + +const + cusiplen = 9; + +type + tcusip = array [1 .. cusiplen] of char; + + function cusipcheckdigit(cusip: tcusip): integer; + (* Check digit *) + var + i, sum, v: integer; + c: char; + contcheck: boolean; (* Continue checking? *) + begin + i := 1; + sum := 0; + contcheck := true; + while (i <= cusiplen) and contcheck do + begin + c := cusip[i]; + if ('0' <= c) and (c <= '9') then v := ord(c) - 48 + else if ('A' <= c) and (c <= 'Z') then v := ord(c) - 65 + 10 + else if c = '*' then v := 36 + else if c = '@' then v := 37 + else if c = '#' then v := 38 + else + begin + cusipcheckdigit := -1; + contcheck := false; + end; + if contcheck then + begin + if (i - 1) mod 2 = 1 then v := 2 * v; + if i <= 8 then sum := sum + (v div 10) + (v mod 10); + i := i + 1; + end; + end; + if contcheck then + if i <> 10 then cusipcheckdigit := -1 + else cusipcheckdigit := (10 - (sum mod 10)) mod 10; + end; + + function isvalidcusip(cusip: tcusip): boolean; + var + check: integer; + begin + check := cusipcheckdigit(cusip); + if check < 0 then isvalidcusip := false + else isvalidcusip := (ord(cusip[9]) = ord(48 + check)); + end; + + procedure writeverdict(cusip: tcusip); + (* Write the verdict *) + begin + write(cusip); + if isvalidcusip(cusip) then writeln(' : Valid') + else writeln(' : Invalid'); + end; + +begin + writeln('CUSIP Verdict'); + writeverdict('037833100'); + writeverdict('17275R102'); + writeverdict('38259P508'); + writeverdict('594918104'); + writeverdict('68389X106'); + writeverdict('68389X105'); + (* readln; *) +end. diff --git a/Task/CUSIP/PascalABC.NET/cusip.pas b/Task/CUSIP/PascalABC.NET/cusip.pas new file mode 100644 index 0000000000..30d756c32e --- /dev/null +++ b/Task/CUSIP/PascalABC.NET/cusip.pas @@ -0,0 +1,32 @@ +function IsCusip(s: string): boolean; +begin + result := false; + if (s.Length <> 9) then exit; + var sum := 0; + var v := 0; + for var i := 1 to 8 do + begin + var c := s[i]; + if c.isdigit then + v := c.todigit + else if (c >= 'A') and (c <= 'Z') then + v := ord(c) - ord('A') + 10 + else if c = '*' then + v := 36 + else if c = '@' then + v := 37 + else if c = '#' then + v := 38; + if (i mod 2) = 0 then + v := v * 2; + sum += (v div 10) + (v mod 10); + end; + var check := (10 - (sum mod 10)) mod 10; + result := s[9].todigit = check; +end; + +begin + var candidates := |'037833100', '17275R102', '38259P508', '594918104', '68389X106', '68389X105'|; + foreach var candidate in candidates do + println(candidate, if IsCusip(candidate) then 'correct' else 'incorrect'); +end. diff --git a/Task/CUSIP/Phix/cusip.phix b/Task/CUSIP/Phix/cusip.phix index 4db8980c3d..e0bfdfac32 100644 --- a/Task/CUSIP/Phix/cusip.phix +++ b/Task/CUSIP/Phix/cusip.phix @@ -1,42 +1,40 @@ -(phixonline)--> - sequence cch = {} +sequence cch = {} - function CusipCheckDigit(string cusip) - integer s = 0, c, v - if length(cch)=0 then - cch = repeat(-1,256) - for i='0' to '9' do - cch[i] = i-'0' - end for - for i='A' to 'Z' do - cch[i] = i-55 - end for - cch['*'] = 36 - cch['@'] = 37 - cch['#'] = 38 - end if - if length(cusip)!=9 or find('\0',cusip) then return 0 end if - for i=1 to 8 do - c := cusip[i] - v := cch[c] - if v=-1 then return 0 end if - if remainder(i,2)=0 then - v *= 2 - end if - s += floor(v/10)+mod(v,10) - end for - return cusip[9]=mod(10-mod(s,10),10)+'0' - end function +function CusipCheckDigit(string cusip) +integer s = 0, c, v + if length(cch)=0 then + cch = repeat(-1,256) + for i='0' to '9' do + cch[i] = i-'0' + end for + for i='A' to 'Z' do + cch[i] = i-55 + end for + cch['*'] = 36 + cch['@'] = 37 + cch['#'] = 38 + end if + if length(cusip)!=9 or find('\0',cusip) then return 0 end if + for i=1 to 8 do + c := cusip[i] + v := cch[c] + if v=-1 then return 0 end if + if remainder(i,2)=0 then + v *= 2 + end if + s += floor(v/10)+mod(v,10) + end for + return cusip[9]=mod(10-mod(s,10),10)+'0' +end function - sequence tests = {"037833100", -- Apple Incorporated - "17275R102", -- Cisco Systems - "38259P508", -- Google Incorporated - "594918104", -- Microsoft Corporation - "68389X106", -- Oracle Corporation (incorrect) - "68389X105"} -- Oracle Corporation +sequence tests = {"037833100", -- Apple Incorporated + "17275R102", -- Cisco Systems + "38259P508", -- Google Incorporated + "594918104", -- Microsoft Corporation + "68389X106", -- Oracle Corporation (incorrect) + "68389X105"} -- Oracle Corporation - for i=1 to length(tests) do - string ti = tests[i] - printf(1,"%s : %s\n",{ti,{"invalid","valid"}[CusipCheckDigit(ti)+1]}) - end for - - with javascript_semantics - requires("1.0.2") -- (builtin constant E renamed as EULER) - atom e0 = 0, e = 2, n = 0, fact = 1 - while abs(e-e0)>=1e-15 do - e0 = e - n += 1 - fact *= 2*n*(2*n+1) - e += (2*n+2)/fact - end while - printf(1,"Computed e = %.15f\n",e) - printf(1," Real e = %.15f\n",EULER) - printf(1," Error = %g\n",EULER-e) - printf(1,"Number of iterations = %d\n",n) - - without js -- not from a browser, mate! - string {libname,funcname} = iff(platform()=WINDOWS?{"user32","CharLowerA"}:{"libc","tolower"}) - atom lib = open_dll(libname) - integer func = define_c_func(lib,funcname,{C_INT},C_INT) - if func=-1 then - ?{{lower('A')}} -- (you don't //have// to crash!) - else - ?c_func(func,{'A'}) -- ('A'==65) - end if - - without js -- (no class in p2js) - class test - string msg = "this is a test" - procedure show() ?this.msg end procedure - procedure inst() ?"this is dynamic" end procedure - end class - test t = new() - t.show() -- prints "this is a test" - t.inst() -- prints "this is dynamic" - t.inst = t.show - t.inst() -- prints "this is a test" - {ToSnakeCase(text)}"); + } + + Console.WriteLine(); + Console.WriteLine($"{"=== To camelCase ===",48}"); + foreach (string text in variableNames) + { + Console.WriteLine($"{text,34} --> {ToCamelCase(text)}"); + } + } + + private static string ToSnakeCase(string aCamel) + { + aCamel = aCamel.Trim().Replace(SPACE, UNDERSCORE).Replace(HYPHEN, UNDERSCORE); + StringBuilder snake = new StringBuilder(); + bool first = true; + foreach (char ch in aCamel) + { + if (first) + { + snake.Append(ch); + first = false; + } + else if (!first && char.IsUpper(ch)) + { + if (snake.ToString().EndsWith(UNDERSCORE)) + { + snake.Append(char.ToLower(ch)); + } + else + { + snake.Append(UNDERSCORE + char.ToLower(ch)); + } + } + else + { + snake.Append(ch); + } + } + return snake.ToString(); + } + + private static string ToCamelCase(string aSnake) + { + aSnake = aSnake.Trim().Replace(SPACE, UNDERSCORE).Replace(HYPHEN, UNDERSCORE); + StringBuilder camel = new StringBuilder(); + bool underscore = false; + foreach (char ch in aSnake) + { + if (ch.ToString().Equals(UNDERSCORE)) + { + underscore = true; + } + else if (underscore) + { + camel.Append(char.ToUpper(ch)); + underscore = false; + } + else + { + camel.Append(ch); + } + } + return camel.ToString(); + } + + private static readonly string SPACE = " "; + private static readonly string UNDERSCORE = "_"; + private static readonly string HYPHEN = "-"; +} diff --git a/Task/Camel-case-and-snake-case/Crystal/camel-case-and-snake-case.cr b/Task/Camel-case-and-snake-case/Crystal/camel-case-and-snake-case.cr new file mode 100644 index 0000000000..38a8fc567f --- /dev/null +++ b/Task/Camel-case-and-snake-case/Crystal/camel-case-and-snake-case.cr @@ -0,0 +1,6 @@ +["snakeCase", "snake_case", "variable_10_case", "variable10Case", "ɛrgo rE tHis", + "hurry-up-joe!", "c://my-docs/happy_Flag-Day/12.doc", " spaces "].each do |ident| + print ident, " => " + print ident.strip.gsub(/[ -]/, "_").camelcase, ", " + puts ident.strip.gsub(/[ -]/, "_").underscore +end diff --git a/Task/Camel-case-and-snake-case/Delphi/camel-case-and-snake-case.delphi b/Task/Camel-case-and-snake-case/Delphi/camel-case-and-snake-case.pas similarity index 100% rename from Task/Camel-case-and-snake-case/Delphi/camel-case-and-snake-case.delphi rename to Task/Camel-case-and-snake-case/Delphi/camel-case-and-snake-case.pas diff --git a/Task/Camel-case-and-snake-case/Ed/camel-case-and-snake-case.ed b/Task/Camel-case-and-snake-case/Ed/camel-case-and-snake-case.ed new file mode 100644 index 0000000000..cd21f1e1b7 --- /dev/null +++ b/Task/Camel-case-and-snake-case/Ed/camel-case-and-snake-case.ed @@ -0,0 +1,7 @@ +# by Artyom Bologov +H +g/.*/s/\([A-Z]\)/_&/g +g/^\<_*/s/// +g/^_*\>/s/// +,p +Q diff --git a/Task/Camel-case-and-snake-case/Fortran/camel-case-and-snake-case.f b/Task/Camel-case-and-snake-case/Fortran/camel-case-and-snake-case.f new file mode 100644 index 0000000000..8d54399adc --- /dev/null +++ b/Task/Camel-case-and-snake-case/Fortran/camel-case-and-snake-case.f @@ -0,0 +1,291 @@ +! Camel case and snake case +! +! tested with Intel ifx (IFX) 2025.2.1 20250806 on Kubuntu 25.04 +! GNU Fortran (Ubuntu 14.2.0-19ubuntu2) 14.2.0 on Kubuntu 25.04 +! +! +! U.B., August 2025 +! +program CaseConverter + +implicit none + +! sep is a marker to separate words within given strings. +! Selected "§" because this is never part of a legit text. +! +character, parameter :: sep='§' + +character (len=:), allocatable :: testWord + + +print *, ' ***** Converting test strings to Snake Case *****' + +testWord = 'snakeCase' +call printResult (testWord, toSnakeCase (testWord)) + +testWord = 'snake_case' +call printResult (testWord, toSnakeCase (testWord)) + +testWord = 'variable_10_case' +call printResult (testWord, toSnakeCase (testWord)) + +testWord = 'variable10Case' +call printResult (testWord, toSnakeCase (testWord)) + +testWord = 'ɛrgo rE tHis' +call printResult (testWord, toSnakeCase (testWord)) + +testWord = 'hurry-up-joe!' +call printResult (testWord, toSnakeCase (testWord)) + +testWord = 'c://my-docs/happy_Flag-Day/12.doc' +call printResult (testWord, toSnakeCase (testWord)) + +testWord = ' spaces ' +call printResult (testWord, toSnakeCase (testWord)) + +print * +print *, ' ***** Converting test strings to Camel Case *****' + +testWord = 'snakeCase' +call printResult ( testWord, toCamelCase (testWord) ) + +testWord = 'snake_case' +call printResult ( testWord, toCamelCase (testWord) ) + +testWord = 'variable_10_case' +call printResult ( testWord, toCamelCase (testWord) ) + +testWord = 'variable10Case' +call printResult ( testWord, toCamelCase (testWord) ) + +testWord = 'ɛrgo rE tHis' +call printResult (testWord, toCamelCase(testWord)) + +testWord = 'hurry-up-joe!' +call printResult ( testWord, toCamelCase (testWord) ) + +testWord = 'c://my-docs/happy_Flag-Day/12.doc' +call printResult ( testWord, toCamelCase (testWord) ) + +testWord = ' spaces ' +call printResult ( testWord, toCamelCase (testWord) ) + + + + +contains + + +! ---------------------------------------------------------- +! print with variable format to display the greek "ɛ" +! and the following text positioned correctly. +! Letter "ɛ" uses 2 bytes so len("ɛ") = 2 but ulen("ɛ") = 1 +! ---------------------------------------------------------- + +subroutine printResult (a,b) +character*(*), intent(in) :: a,b +character (len=100) ::fmt +write (fmt, *) '(A', 34+ (len(a)-ulen(a)) ,', " => ",A)' +print fmt, a, b + +end subroutine printResult + + +!--------------------------------------- +! change ASCII a...z to upper case a...z +!--------------------------------------- +function toupper (c) result(retc) + +character ::c +character :: retc + +if (c >='a' .and. c <= 'z') then + retc = achar (iachar('A') + (iachar(c)-iachar('a'))) +else + retc = c +end if + +end function toupper + +!--------------------------------------- +! change ASCII A...Z to lower case a...z +!--------------------------------------- +function tolower (c) result(retc) + +character ::c +character :: retc + +if (c >='A' .and. c <= 'Z') then ! is upper case + retc = achar (iachar('a') + (iachar(c)-iachar('A'))) +else + retc = c +end if + +end function tolower + +!--------------------------------------------------------------------------------- +! Scan input text, mark all positions between distinct words within the text +! so that later in the actual conversion these points can be rewritten accordingly. +!--------------------------------------------------------------------------------- +function prepare (txt) result (newtext) + +character (len=*), intent (in) :: txt +character (len=:), allocatable :: text, newtext +integer :: ip1, ip2, ip3, l +character :: beginword + + +newtext=''; + +! First remove leading and trailing spaces +text = trim (txt) +text = adjustl (text) +text = trim (text) +l = len_trim(text) + +ip1 = 1 +ip2 = 2 +ip3 = 1 +do while (ip2 <= l) + if (text(ip2:ip2) >= 'A' .and. text(ip2:ip2) <='Z' ) then ! upcase letter indicates beginning of a word + newtext = newtext(:len_trim(newtext)) // text(ip1:ip2-1) // sep + ip1 = ip2 + ip2 = ip1+1 + else if (text(ip2:ip2) .eq. '_' & + .or. text(ip2:ip2) .eq. '-' & + .or. text(ip2:ip2) .eq. ' ' ) then ! Separator is behind current word, new word following. + if (ip2 .lt. l) then ! ip2+1 still inside text + beginword = tolower (text(ip2+1:ip2+1)) + newtext = newtext(:len_trim(newtext)) // text (ip1:ip2-1) // sep // beginword + else + ! separator at ip2 is last character of text. Just drop it. + newtext = newtext(:len_trim(newtext)) // text (ip1:ip2-1) + endif + ip1 = ip2+2 ! skip separator and begin of next word + ip2 = ip1 + else + ip2 = ip2 + 1 + end if +end do + +newtext = newtext(:len_trim(newtext)) // text(ip1:) + +end function prepare + +!----------------------------------- +! Convert prepared text to CamelCase +!----------------------------------- +function toCamelCase (txt) result(newtext) +! +! 1st char is lowercase, all spaces removed and word beginnings upperCase +! +character (len=*), intent (in) :: txt +character (:), allocatable :: text, newtext +integer :: ip, l +character :: beginword + +newtext = '' +text = prepare (txt) + +l = len_trim(text) +newtext = newtext(:len_trim(newtext)) // tolower (text(1:1)) + +ip = 2 + +do while (ip <= l) + if (text(ip:ip) .eq. sep) then + ip = ip + 1 ! skip the separator + if (ip ( int(Z'C0') + 1)) .and. ( ich < int(Z'E0') )) THEN + retlen=2 + else if ( ich < int(Z'F0') ) THEN + retlen=3 + else if ( ich <= int(Z'F4') ) THEN + retlen=4 + else + retlen=1 !assume we process larger seqences, 1 by 1 bytes + end if +end function + + +end program diff --git a/Task/Camel-case-and-snake-case/Go/camel-case-and-snake-case.go b/Task/Camel-case-and-snake-case/Go/camel-case-and-snake-case.go new file mode 100644 index 0000000000..143ef584c5 --- /dev/null +++ b/Task/Camel-case-and-snake-case/Go/camel-case-and-snake-case.go @@ -0,0 +1,104 @@ +package main + +import ( + "fmt" + "strings" + "unicode" +) + +func snakeCaseToCamelCase(word string, sep rune) string { + var sb strings.Builder + + wordRunes := []rune(strings.TrimSpace(word)) + wordLen := len(wordRunes) + + for i := 0; i < wordLen; i++ { + c := wordRunes[i] + + if c == sep { + if i+1 < wordLen && wordRunes[i+1] != sep { + sb.WriteRune(unicode.ToUpper(wordRunes[i+1])) + i++ + } + } else { + if i == 0 { + c = unicode.ToLower(c) + } + sb.WriteRune(c) + } + } + + return sb.String() +} + +func camelCaseToSnakeCase(word string, sep rune) string { + word = strings.TrimSpace(word) + var sb strings.Builder + var lastRune rune + + for i, c := range word { + if i != 0 && unicode.IsUpper(c) { + if lastRune != sep { + sb.WriteRune(sep) + } + } + sb.WriteRune(unicode.ToLower(c)) + lastRune = c + } + + return sb.String() +} + +func main() { + words := []string{ + "snakeCase", + "snake_case", + "variable_10_case", + "variable10Case", + "ɛrgo rE tHis", + "hurry-up-joe!", + "c://my-docs/happy_Flag-Day/12.doc", + " spaces ", + } + + fmt.Print("snake_case to camelCase:\n\n") + + for _, word := range words { + fmt.Println(word, "=>", snakeCaseToCamelCase(word, '_')) + } + + fmt.Println() + fmt.Print("kebab-case to camelCase:\n\n") + + for _, word := range words { + fmt.Println(word, "=>", snakeCaseToCamelCase(word, '-')) + } + + fmt.Println() + fmt.Print("space case to camelCase:\n\n") + + for _, word := range words { + fmt.Println(word, "=>", snakeCaseToCamelCase(word, ' ')) + } + + fmt.Println() + fmt.Print("camelCase to snake_case:\n\n") + + for _, word := range words { + fmt.Println(word, "=>", camelCaseToSnakeCase(word, '_')) + } + + fmt.Println() + fmt.Print("camelCase to kebab-case:\n\n") + + for _, word := range words { + fmt.Println(word, "=>", camelCaseToSnakeCase(word, '-')) + } + + fmt.Println() + fmt.Print("camelCase to space case:\n\n") + + for _, word := range words { + fmt.Println(word, "=>", camelCaseToSnakeCase(word, ' ')) + } +} diff --git a/Task/Camel-case-and-snake-case/JavaScript/camel-case-and-snake-case.js b/Task/Camel-case-and-snake-case/JavaScript/camel-case-and-snake-case.js new file mode 100644 index 0000000000..73b10c2641 --- /dev/null +++ b/Task/Camel-case-and-snake-case/JavaScript/camel-case-and-snake-case.js @@ -0,0 +1,82 @@ +const HYPHEN = '-'; +const SPACE = ' '; +const UNDERSCORE = '_'; +const WHITESPACE = " \n\r\t\f\v"; + +function leftTrim(text) { + const start = text.search(/\S/); // Find the index of the first non-whitespace character + return start === -1 ? "" : text.substring(start); +} + +function rightTrim(text) { + const end = text.search(/\S(?![\s\S]*\S)/); // Find the index of the last non-whitespace character + return end === -1 ? "" : text.substring(0, end + 1); +} + +function trim(text) { + return leftTrim(rightTrim(text)); +} + +function prepareForConversion(text) { + text = trim(text); + text = text.replace(new RegExp(SPACE, 'g'), UNDERSCORE); + text = text.replace(new RegExp(HYPHEN, 'g'), UNDERSCORE); + return text; // Return the modified text +} + +function toSnakeCase(camel) { + camel = prepareForConversion(camel); + let snake = ""; + let first = true; + for (const ch of camel) { + if (first) { + snake += ch; + first = false; + } else if (!first && ch >= 'A' && ch <= 'Z') { + if (snake.slice(-1) === UNDERSCORE) { + snake += ch.toLowerCase(); + } else { + snake += UNDERSCORE; + snake += ch.toLowerCase(); + } + } else { + snake += ch; + } + } + return snake; +} + +function toCamelCase(snake) { + snake = prepareForConversion(snake); + let camel = ""; + let underscore = false; + for (const ch of snake) { + if (ch === UNDERSCORE) { + underscore = true; + } else if (underscore) { + camel += ch.toUpperCase(); + underscore = false; + } else { + camel += ch; + } + } + return camel; +} + +function main() { + const variableNames = ["snakeCase", "snake_case", "variable_10_case", + "variable10Case", "ergo rE tHis", "hurry-up-joe!", "c://my-docs/happy_Flag-Day/12.doc", " spaces "]; + + console.log("".padEnd(48, " ") + "=== To snake_case ==="); + for (const text of variableNames) { + console.log("".padEnd(34, " ") + text + " --> " + toSnakeCase(text)); + } + + console.log("\n"); + console.log("".padEnd(48, " ") + "=== To camelCase ==="); + for (const text of variableNames) { + console.log("".padEnd(34, " ") + text + " --> " + toCamelCase(text)); + } +} + +main(); diff --git a/Task/Camel-case-and-snake-case/Julia/camel-case-and-snake-case.julia b/Task/Camel-case-and-snake-case/Julia/camel-case-and-snake-case.jl similarity index 100% rename from Task/Camel-case-and-snake-case/Julia/camel-case-and-snake-case.julia rename to Task/Camel-case-and-snake-case/Julia/camel-case-and-snake-case.jl diff --git a/Task/Camel-case-and-snake-case/Kotlin/camel-case-and-snake-case.kotlin b/Task/Camel-case-and-snake-case/Kotlin/camel-case-and-snake-case.kts similarity index 100% rename from Task/Camel-case-and-snake-case/Kotlin/camel-case-and-snake-case.kotlin rename to Task/Camel-case-and-snake-case/Kotlin/camel-case-and-snake-case.kts diff --git a/Task/Camel-case-and-snake-case/Mathematica/camel-case-and-snake-case.math b/Task/Camel-case-and-snake-case/Mathematica/camel-case-and-snake-case.math new file mode 100644 index 0000000000..ecae1a970d --- /dev/null +++ b/Task/Camel-case-and-snake-case/Mathematica/camel-case-and-snake-case.math @@ -0,0 +1,85 @@ +(* String case conversion functions in Mathematica *) + +snakeToCamelCase[nam_String, sep_String : "[_]+", lcmiddle_ : False] := Module[{words}, + If[nam == "", Return[nam]]; + words = StringSplit[StringTrim[nam], RegularExpression[sep]]; + If[lcmiddle, words = ToLowerCase /@ words]; + words[[2 ;;]] = StringJoin[ToUpperCase[StringTake[#, 1]], StringDrop[#, 1]] & /@ Select[words[[2 ;;]], StringLength[#] > 0 &]; + StringJoin[words] +] + +spaceToCamelCase[nam_String] := snakeToCamelCase[nam, "\\s+"] + +kebabToCamelCase[nam_String] := snakeToCamelCase[nam, "[\\-]+"] + +periodToCamelCase[nam_String] := snakeToCamelCase[nam, "[\\.]+"] + +allsepToCamelCase[nam_String] := snakeToCamelCase[nam, "[ \\-_\\.]+"] + +lowermiddleAllsepToCamelCase[nam_String] := snakeToCamelCase[nam, "[ \\-_\\.]+", True] + +camelToSnakeCase[nam_String, sep_String : "_", allsep_String : "[_]+", lcmiddle_ : True] := Module[{result, sep1, words}, + result = StringReplace[StringTrim[nam], RegularExpression["([A-Z]+)"] -> sep <> "$1"]; + sep1 = If[sep == ".", "\\.", sep]; + If[lcmiddle, + words = Select[StringSplit[result, sep1], StringLength[#] > 0 &]; + result = StringRiffle[ToLowerCase /@ words, sep], + words = Select[StringSplit[result, sep1], StringLength[#] > 0 &]; + result = StringRiffle[StringJoin[ToLowerCase[StringTake[#, 1]], StringDrop[#, 1]] & /@ words, sep] + ]; + StringReplace[result, RegularExpression[allsep] -> sep] +] + +preserveMidcapsCamelToSnakeCase[nam_String] := camelToSnakeCase[nam, "_", "[_]+", False] + +allsepToSnakeCase[nam_String] := camelToSnakeCase[nam, "_", "[ \\-\\._]+"] + +allsepToKebabCase[nam_String] := camelToSnakeCase[nam, "-", "[ \\-\\._]+"] + +allsepToSpaceCase[nam_String] := camelToSnakeCase[nam, " ", "[ \\-\\._]+"] + +allsepToPeriodCase[nam_String] := camelToSnakeCase[nam, ".", "[ \\-\\._]+"] + +allsepToSlashCase[nam_String] := camelToSnakeCase[nam, "/", "[ \\-\\._]+"] + +(* Test the functions *) +testFunctions = { + snakeToCamelCase, + spaceToCamelCase, + kebabToCamelCase, + periodToCamelCase, + allsepToCamelCase, + lowermiddleAllsepToCamelCase, + camelToSnakeCase, + preserveMidcapsCamelToSnakeCase, + allsepToSnakeCase, + allsepToKebabCase, + allsepToSpaceCase, + allsepToPeriodCase, + allsepToSlashCase +}; + +testStrings = { + "snakeCase", + "snake_case", + "snake-case", + "snake case", + "snake CASE", + "snake.case", + "variable_10_case", + "variable10Case", + "ɛrgo rE tHis", + "hurry-up-joe!", + "c://my-docs/happy_Flag-Day/12.doc", + " spaces " +}; + +Do[ + Print["Testing function ", f, ":"]; + Do[ + Print[StringPadLeft[testString, 36], " => ", f[testString]], + {testString, testStrings} + ]; + Print[""], + {f, testFunctions} +] diff --git a/Task/Camel-case-and-snake-case/OmniMark/camel-case-and-snake-case.xom b/Task/Camel-case-and-snake-case/OmniMark/camel-case-and-snake-case.xom new file mode 100644 index 0000000000..69c54a13fc --- /dev/null +++ b/Task/Camel-case-and-snake-case/OmniMark/camel-case-and-snake-case.xom @@ -0,0 +1,58 @@ +define stream function to_snake_case (value stream txt) as + local stream ls + open ls as buffer + repeat scan txt + match white-space* value-end + ; "trailing whitespace may be ignored" + match value-start white-space* + ; "leading ... whitespace may be ignored" + match (lc | digit) => char1 uc => char2 + put ls '%x(char1)_%lx(char2)' + match ('_' | space | "-" | '.') + ; normalise to underscore and lowercase letter + put ls '_' + match any => char + ; all other characters are lowercase + put ls '%lx(char)' + again + close ls + return ls + +define stream function toCamelCase (value stream txt) as + local stream ls + open ls as buffer + repeat scan txt + match white-space* value-end + ; "trailing whitespace may be ignored" + match value-start white-space* letter+ => word1 + ; "leading ... whitespace may be ignored" + put ls word1 + match ('_' | space | "-" | '.') any => makeUpper + ; consume dividing underscore, space, hyphen or full stop + put ls '%ux(makeUpper)' + match ([digit] letter) => chars + ; a letter preceded by a numeral should be uppercase + put ls '%ux(chars)' + match any => char + ; all other characters are lowercase + put ls '%lx(char)' + again + close ls + return ls + +process + local stream ls variable initial {"snakeCase", "snake_case", + "variable_10_case", "variable10Case", + "ɛrgo rE tHis", "hurry-up-joe!", "c://my-docs/happy_Flag-Day/12.doc", + " spaces "} + output 'to_snake_case%n' + output '=============%n' + repeat over ls + output ls || ' => ' || to_snake_case(ls) || '%n' + again + output '%n' + output 'toCamelCase%n' + output '===========%n' + repeat over ls + output ls || ' => ' || toCamelCase(ls) || '%n' + again diff --git a/Task/Camel-case-and-snake-case/Phix/camel-case-and-snake-case.phix b/Task/Camel-case-and-snake-case/Phix/camel-case-and-snake-case.phix index c9a701e73d..ff87c84e3a 100644 --- a/Task/Camel-case-and-snake-case/Phix/camel-case-and-snake-case.phix +++ b/Task/Camel-case-and-snake-case/Phix/camel-case-and-snake-case.phix @@ -1,33 +1,31 @@ -(phixonline)--> - with javascript_semantics - function to_snake_case(string s) - string snake = substitute(trim(s)," ","_") - for i=length(snake) to 1 by -1 do - if isupper(snake[i]) then - snake[i..i] = '_'&lower(snake[i]) - end if - end for - return snake - end function +with javascript_semantics +function to_snake_case(string s) + string snake = substitute(trim(s)," ","_") + for i=length(snake) to 1 by -1 do + if isupper(snake[i]) then + snake[i..i] = '_'&lower(snake[i]) + end if + end for + return snake +end function - function toCamelCase(string s) - string camel = substitute_all(trim(s),"- ","__") - for i=length(camel)-1 to 1 by -1 do - if camel[i]='_' then - camel[i..i+1] = upper(camel[i+1..i+1]) - end if - end for - return camel - end function +function toCamelCase(string s) + string camel = substitute_all(trim(s),"- ","__") + for i=length(camel)-1 to 1 by -1 do + if camel[i]='_' then + camel[i..i+1] = upper(camel[i+1..i+1]) + end if + end for + return camel +end function - constant tests = {"snakeCase", "snake_case", "variable_10_case", "variable10Case", "ergo rE tHis", - "hurry-up-joe!", "c://my-docs/happy_Flag-Day/12.doc", " spaces "} - procedure test(string title, integer fn) - printf(1,title) - for i=1 to length(tests) do - printf(1,"%33s ===> %s\n", {tests[i], fn(tests[i])}) - end for - end procedure - test(" === to_snake_case ===\n",to_snake_case) - test("\n === toCamelCase ===\n",toCamelCase) - {}", text, to_snake_case(text)); + } + + println!(); + println!("{:>48}", "=== To camelCase ==="); + for text in &variable_names { + println!("{:>34} --> {}", text, to_camel_case(text)); + } +} diff --git a/Task/Camel-case-and-snake-case/Zig/camel-case-and-snake-case.zig b/Task/Camel-case-and-snake-case/Zig/camel-case-and-snake-case.zig new file mode 100644 index 0000000000..faee5b8822 --- /dev/null +++ b/Task/Camel-case-and-snake-case/Zig/camel-case-and-snake-case.zig @@ -0,0 +1,134 @@ +const std = @import("std"); +const print = std.debug.print; +const ArrayList = std.ArrayList; + +const HYPHEN: u8 = '-'; +const SPACE: u8 = ' '; +const UNDERSCORE: u8 = '_'; +const WHITESPACE = " \n\r\t\x0C\x0B"; + +fn isWhitespace(ch: u8) bool { + for (WHITESPACE) |ws| { + if (ch == ws) return true; + } + return false; +} + +fn leftTrim(text: []const u8) []const u8 { + var start: usize = 0; + while (start < text.len and isWhitespace(text[start])) { + start += 1; + } + return text[start..]; +} + +fn rightTrim(text: []const u8) []const u8 { + var end: usize = text.len; + while (end > 0 and isWhitespace(text[end - 1])) { + end -= 1; + } + return text[0..end]; +} + +fn trim(text: []const u8) []const u8 { + return rightTrim(leftTrim(text)); +} + +fn prepareForConversion(allocator: std.mem.Allocator, text: []const u8) ![]u8 { + const trimmed = trim(text); + var result = try ArrayList(u8).initCapacity(allocator, trimmed.len); + defer result.deinit(); + + for (trimmed) |ch| { + if (ch == SPACE or ch == HYPHEN) { + try result.append(UNDERSCORE); + } else { + try result.append(ch); + } + } + + return result.toOwnedSlice(); +} + +fn toSnakeCase(allocator: std.mem.Allocator, camel: []const u8) ![]u8 { + const text = try prepareForConversion(allocator, camel); + defer allocator.free(text); + + var snake = ArrayList(u8).init(allocator); + defer snake.deinit(); + + var first = true; + + for (text) |ch| { + if (first) { + try snake.append(ch); + first = false; + } else if (std.ascii.isUpper(ch)) { + if (snake.items.len > 0 and snake.items[snake.items.len - 1] == UNDERSCORE) { + try snake.append(std.ascii.toLower(ch)); + } else { + try snake.append(UNDERSCORE); + try snake.append(std.ascii.toLower(ch)); + } + } else { + try snake.append(ch); + } + } + + return snake.toOwnedSlice(); +} + +fn toCamelCase(allocator: std.mem.Allocator, snake: []const u8) ![]u8 { + const text = try prepareForConversion(allocator, snake); + defer allocator.free(text); + + var camel = ArrayList(u8).init(allocator); + defer camel.deinit(); + + var underscore = false; + + for (text) |ch| { + if (ch == UNDERSCORE) { + underscore = true; + } else if (underscore) { + try camel.append(std.ascii.toUpper(ch)); + underscore = false; + } else { + try camel.append(ch); + } + } + + return camel.toOwnedSlice(); +} + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + const allocator = gpa.allocator(); + + const variable_names = [_][]const u8{ + "snakeCase", + "snake_case", + "variable_10_case", + "variable10Case", + "ergo rE tHis", + "hurry-up-joe!", + "c://my-docs/happy_Flag-Day/12.doc", + " spaces " + }; + + print("{s:>48}\n", .{"=== To snake_case ==="}); + for (variable_names) |text| { + const snake = try toSnakeCase(allocator, text); + defer allocator.free(snake); + print("{s:>34} --> {s}\n", .{ text, snake }); + } + + print("\n", .{}); + print("{s:>48}\n", .{"=== To camelCase ==="}); + for (variable_names) |text| { + const camel = try toCamelCase(allocator, text); + defer allocator.free(camel); + print("{s:>34} --> {s}\n", .{ text, camel }); + } +} diff --git a/Task/Canny-edge-detector/FreeBASIC/canny-edge-detector.basic b/Task/Canny-edge-detector/FreeBASIC/canny-edge-detector.basic new file mode 100644 index 0000000000..947ea3deca --- /dev/null +++ b/Task/Canny-edge-detector/FreeBASIC/canny-edge-detector.basic @@ -0,0 +1,116 @@ +#define MIN(a, b) iif((a) < (b), (a), (b)) +#define MAX(a, b) iif((a) > (b), (a), (b)) + +Const MaxBrightness = 255 + +' Función para leer un archivo PPM +Function readPPM(nombre As String, Byref ancho As Integer, Byref alto As Integer, image() As Ubyte) As Boolean + Dim As Integer ff + Dim As String t, dcol + + If nombre = "" Then + Print "No PPM file name indicated." + Return False + End If + + ff = Freefile + Open nombre For Binary As #ff + If Err Then + Print "File "; nombre; " not found." + Return False + End If + + Line Input #ff, t + If t <> "P6" Then + Print "File is NOT PPM P6 type." + Close #ff + Return False + End If + + Do + Line Input #ff, t + Loop While Left(t, 1) = "#" + + Dim As Integer posic = 1 + While Mid(t, posic, 1) = " " + posic += 1 + Wend + ancho = Val(Mid(t, posic)) + + While Mid(t, posic, 1) <> " " + posic += 1 + Wend + While Mid(t, posic, 1) = " " + posic += 1 + Wend + alto = Val(Mid(t, posic)) + + Line Input #ff, dcol + + Redim image(0 To ancho * alto * 3 - 1) + Get #ff, , image() + + Close #ff + Return True +End Function + +Dim As Integer ancho, alto +Dim image() As Ubyte + +If readPPM("i:\Lena.ppm", ancho, alto, image()) Then + Dim As Integer newAncho = ancho, newAlto = alto + Dim pixelsGray(newAncho - 1, newAlto - 1) As Integer + Dim C_E_D(2, 2) As Integer + + ' Define edge detection filter + Dim As Integer dato(8) => {-1, -1, -1, -1, 8, -1, -1, -1, -1} + Dim As Integer i, j + For i = 0 To 2 + For j = 0 To 2 + C_E_D(i, j) = dato(i * 3 + j) + Next j + Next i + + ' Convert image to grayscale + Dim As Integer x, y, r, g, b, lumin, k + For y = 0 To newAlto - 1 + For x = 0 To newAncho - 1 + r = image((y * newAncho + x) * 3) + g = image((y * newAncho + x) * 3 + 1) + b = image((y * newAncho + x) * 3 + 2) + lumin = Int(0.2126 * r + 0.7152 * g + 0.0722 * b) + pixelsGray(x, y) = lumin + Next x + Next y + + Dim new_image(newAncho - 1, newAlto - 1) As Integer + Dim As Integer divisor = 1 + + ' Apply edge detection filter + Dim As Integer newRGB + For y = 1 To newAlto - 2 + For x = 1 To newAncho - 2 + newRGB = 0 + For i = -1 To 1 + For j = -1 To 1 + newRGB += C_E_D(i + 1, j + 1) * pixelsGray(x + i, y + j) + Next j + Next i + new_image(x, y) = Max(Min(newRGB / divisor, 255), 0) + Next x + Next y + + ' Show the result + Screenres newAncho, newAlto, 32 + Windowtitle ("Canny edge detector") + For y = 0 To newAlto - 1 + For x = 0 To newAncho - 1 + k = new_image(x, y) + Pset (x, y), Rgb(k, k, k) + Next x + Next y +Else + Print "Error loading PPM file." +End If + +Sleep diff --git a/Task/Canny-edge-detector/Julia/canny-edge-detector.julia b/Task/Canny-edge-detector/Julia/canny-edge-detector.jl similarity index 100% rename from Task/Canny-edge-detector/Julia/canny-edge-detector.julia rename to Task/Canny-edge-detector/Julia/canny-edge-detector.jl diff --git a/Task/Canonicalize-CIDR/ALGOL-68/canonicalize-cidr.alg b/Task/Canonicalize-CIDR/ALGOL-68/canonicalize-cidr.alg index 7befa0b1eb..6a3f49135f 100644 --- a/Task/Canonicalize-CIDR/ALGOL-68/canonicalize-cidr.alg +++ b/Task/Canonicalize-CIDR/ALGOL-68/canonicalize-cidr.alg @@ -1,22 +1,22 @@ BEGIN # show IPv4 addresses in CIDR notation in canonical form # # mode to hold an IPv4 address in CIDR notation # - MODE CIDR = STRUCT( BITS address - , INT network bits - , BOOL valid - , STRING error + MODE CIDR = STRUCT( LONG BITS address + , INT network bits + , BOOL valid + , STRING error ); # returns a CIDR parsed from address # OP TOCIDR = ( STRING address text )CIDR: BEGIN - STRING addr = "." + address text + "$"; - STRING error := ""; - BITS address := 16r0; - INT bits count := 0; - INT dot count := 0; - INT slash count := 0; - BOOL valid := TRUE; - INT s pos := LWB addr; - INT s max = UPB addr; + STRING addr = "." + address text + "$"; + STRING error := ""; + LONG BITS address := 16r0; + INT bits count := 0; + INT dot count := 0; + INT slash count := 0; + BOOL valid := TRUE; + INT s pos := LWB addr; + INT s max = UPB addr; WHILE s pos < s max AND valid DO IF addr[ s pos ] = "." THEN # must have an octet next # @@ -70,7 +70,7 @@ BEGIN # show IPv4 addresses in CIDR notation in canonical form # address ELSE # valid address - retain the top most bits # - CIDR( address OF address AND ( 16rffffffff + CIDR( address OF address AND ( LONG 16rffffffff SHL ( 32 - network bits OF address ) ) , network bits OF address @@ -82,9 +82,9 @@ BEGIN # show IPv4 addresses in CIDR notation in canonical form # OP TOSTRING = ( CIDR address )STRING: BEGIN [ 1 : 4 ]INT octet; - BITS addr := address OF address; + LONG BITS addr := address OF address; FOR o pos FROM UPB octet BY -1 TO LWB octet DO - octet[ o pos ] := ABS ( addr AND 16rff ); + octet[ o pos ] := SHORTEN ABS ( addr AND 16rff ); addr := addr SHR 8 OD; STRING result := whole( octet[ LWB octet ], 0 ); diff --git a/Task/Canonicalize-CIDR/Ada/canonicalize-cidr.adb b/Task/Canonicalize-CIDR/Ada/canonicalize-cidr.adb new file mode 100644 index 0000000000..a138a754ae --- /dev/null +++ b/Task/Canonicalize-CIDR/Ada/canonicalize-cidr.adb @@ -0,0 +1,105 @@ +with Ada.Strings; +with Ada.Strings.Fixed; +with Ada.Strings.Maps; +with Ada.Text_IO; + +use Ada.Strings; +use Ada.Strings.Fixed; +use Ada.Strings.Maps; +use Ada.Text_IO; + +procedure Canonicalize_CIDR is + type IP_Octet_Type is mod 256; + + type IP_Record_Type is record + A, B, C, D : IP_Octet_Type; + end record + with Size => 32; + + for IP_Record_Type use record + -- Use little-endian ordering to match bit array + D at 0 range 0 .. 7; + C at 1 range 0 .. 7; + B at 2 range 0 .. 7; + A at 3 range 0 .. 7; + end record; + + type IP_Bitarray_Type is array (0 .. 31) of Boolean + with Component_Size => 1; + + subtype IP_Mask_Type is Natural range 0 .. 32; + + type IP_CIDR_Type is record + IP : IP_Record_Type; + Mask : IP_Mask_Type; + end record; + + function Parse_IP_CIDR (S : String) return IP_CIDR_Type is + IP_Record : IP_CIDR_Type; + Digit_Range : Character_Range := ('0', '9'); + Digit_Set : Character_Set := To_Set (Digit_Range); + Octets : array (1 .. 4) of IP_Octet_Type; + First : Positive; + Last : Natural := 0; + begin + for I in Octets'Range loop + Find_Token (S, Digit_Set, Last + 1, Inside, First, Last); + Octets (I) := IP_Octet_Type'Value (S (First .. Last)); + end loop; + IP_Record.IP.A := Octets (1); + IP_Record.IP.B := Octets (2); + IP_Record.IP.C := Octets (3); + IP_Record.IP.D := Octets (4); + + Find_Token (S, Digit_Set, Last + 1, Inside, First, Last); + IP_Record.Mask := IP_Mask_Type'Value (S (First .. Last)); + + return IP_Record; + end Parse_IP_CIDR; + + procedure Canonicalize_IP_CIDR (Addr : in out IP_CIDR_Type) is + -- Fun part. I can overlay different types over the same bits. + Bit_Overlay : IP_Bitarray_Type with Address => Addr.IP'Address; + begin + for I in Bit_Overlay'First .. Bit_Overlay'Last - Addr.Mask loop + Bit_Overlay (I) := False; + end loop; + end Canonicalize_IP_CIDR; + + procedure Put_IP_CIDR (Addr : IP_CIDR_TYPE) is + package Octet_IO is new Ada.Text_IO.Modular_IO (IP_Octet_Type); + package Mask_IO is new Ada.Text_IO.Integer_IO (IP_Mask_Type); + begin + Octet_IO.Put (Addr.IP.A, 0); + Put ("."); + Octet_IO.Put (Addr.IP.B, 0); + Put ("."); + Octet_IO.Put (Addr.IP.C, 0); + Put ("."); + Octet_IO.Put (Addr.IP.D, 0); + Put ("/"); + Mask_IO.Put (Addr.Mask, 0); + end Put_IP_CIDR; + + procedure Show_IP_Canonicalize (S : String) is + Canon : IP_CIDR_Type := Parse_IP_CIDR (S); + begin + Canonicalize_IP_Cidr (Canon); + Put (S & " -> "); + Put_IP_CIDR (Canon); + New_Line; + end Show_IP_Canonicalize; + + Test_IPs : array (1 .. 5) of String (1 .. 18) := + ( + "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" + ); +begin + for I of Test_IPs loop + Show_IP_Canonicalize (I); + end loop; +end Canonicalize_CIDR; diff --git a/Task/Canonicalize-CIDR/EasyLang/canonicalize-cidr.easy b/Task/Canonicalize-CIDR/EasyLang/canonicalize-cidr.easy index 64d7aae038..7c1c9054e8 100644 --- a/Task/Canonicalize-CIDR/EasyLang/canonicalize-cidr.easy +++ b/Task/Canonicalize-CIDR/EasyLang/canonicalize-cidr.easy @@ -1,23 +1,15 @@ func$ can_cidr s$ . - n[] = number strsplit s$ "./" - if len n[] <> 5 - return "" - . + n[] = number strtok s$ "./" + if len n[] <> 5 : return "" for i to 4 - if n[i] < 0 or n[i] > 255 - return "" - . + if n[i] < 0 or n[i] > 255 : return "" ad = ad * 256 + n[i] . - if n[5] > 31 or n[5] < 1 - return "" - . + 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$ - . + if r$ <> "" : r$ = "." & r$ r$ = ad mod 256 & r$ ad = ad div 256 . diff --git a/Task/Canonicalize-CIDR/FreeBASIC/canonicalize-cidr.basic b/Task/Canonicalize-CIDR/FreeBASIC/canonicalize-cidr.basic index 97b62bc879..bd4af5e919 100644 --- a/Task/Canonicalize-CIDR/FreeBASIC/canonicalize-cidr.basic +++ b/Task/Canonicalize-CIDR/FreeBASIC/canonicalize-cidr.basic @@ -1,54 +1,99 @@ -#lang "qb" +Const MAX_OCTET = 255 +Const MIN_NETWORK = 1 +Const MAX_NETWORK = 32 +Const OCTET_BITS = 8 -REM THE Binary OPS ONLY WORK On SIGNED 16-Bit NUMBERS -REM SO WE STORE THE IP ADDRESS As AN ARRAY OF FOUR OCTETS -Cls -Dim IP(3) -Do - REM Read DEMO Data - 140 Read CI$ - If CI$ = "" Then Exit Do 'Sleep: End - REM FIND / - SL = 0 - For I = Len(CI$) To 1 Step -1 - If Mid$(CI$,I,1) = "/" Then SL = I : I = 1 - Next I - If SL = 0 Then Print "INVALID CIDR STRING: '"; CI$; "'": Goto 140 - NW = Val(Mid$(CI$,SL+1)) - If NW < 1 Or NW > 32 Then Print "INVALID NETWORK WIDTH:"; NW: Goto 140 - REM PARSE OCTETS INTO IP ARRAY - BY = 0 : N = 0 - For I = 1 To SL-1 - C$ = Mid$(CI$,I,1) - If Not (C$ <> ".") Then - IP(N) = BY : N = N + 1 - BY = 0 - If IP(N-1) < 256 Then 310 - Print "INVALID OCTET VALUE:"; IP(N-1): Goto 140 - Else C = Val(C$):If C Or (C$="0") Then BY = BY*10+C +Type IPAddress + octets(3) As Integer +End Type + +Function isDigit(Byval ch As String) As Boolean + Return (Asc(ch) >= Asc("0")) And (Asc(ch) <= Asc("9")) +End Function + +Function ParseIPAddress(cidr As String, Byref networkWidth As Integer) As IPAddress + Dim As IPAddress ip + Dim As Integer slashPos = Instr(cidr, "/") + Dim As String ipPart = Left(cidr, slashPos - 1) + + networkWidth = Val(Mid(cidr, slashPos + 1)) + + Dim As Integer i, currentOctet = 0, octetValue = 0 + For i = 1 To Len(ipPart) + If Mid(ipPart, i, 1) = "." Then + ip.octets(currentOctet) = octetValue + currentOctet += 1 + octetValue = 0 + Elseif IsDigit(Mid(ipPart, i, 1)) Then + octetValue = octetValue * 10 + Val(Mid(ipPart, i, 1)) End If - 310 ' - Next I - IP(N) = BY : N = N + 1 - If IP(N-1) > 255 Then Print "INVALID OCTET VALUE:"; IP(N-1): Goto 140 - REM NUMBER OF COMPLETE OCTETS IN NETWORK PART - NB = Int(NW/8) - REM NUMBER OF NETWORK BITS IN PARTIAL OCTET - XB = NW And 7 - REM ZERO Out HOST BITS IN PARTIAL OCTET - IP(NB) = IP(NB) And (255 - 2^(8-XB) + 1) - REM And SET Any ALL-HOST OCTETS To 0 - If NB < 3 Then For I = NB +1 To 3 : IP(I) = 0 : Next I - REM Print Out THE RESULT - Print Mid$(Str$(IP(0)),2); - For I = 1 To 3 - Print "."; Mid$(Str$(IP( I)),2); - Next I - Print Mid$(CI$,SL) -Loop -Data "87.70.141.1/22", "36.18.154.103/12", "62.62.197.11/29" -Data "67.137.119.181/4", "161.214.74.21/24", "184.232.176.184/18" -REM SOME INVALID INPUTS -Data "127.0.0.1", "123.45.67.89/0", "98.76.54.32/100", "123.456.789.0/12" + Next + ip.octets(currentOctet) = octetValue + + Return ip +End Function + +Function ApplyNetworkMask(ip As IPAddress, networkWidth As Integer) As IPAddress + Dim As IPAddress result = ip + Dim As Integer completeOctets = networkWidth \ OCTET_BITS + Dim As Integer remainingBits = networkWidth And 7 + + ' Apply mask to partial octet + If completeOctets < 4 Then + result.octets(completeOctets) And= (MAX_OCTET - 2^(OCTET_BITS-remainingBits) + 1) + ' Zero remaining octets + For i As Integer = completeOctets + 1 To 3 + result.octets(i) = 0 + Next + End If + + Return result +End Function + +Function ValidateInput(ip As IPAddress, networkWidth As Integer, cidr As String) As Boolean + If Instr(cidr, "/") = 0 Then + Print "INVALID CIDR STRING: '"; cidr; "'" + Return False + End If + + If networkWidth < MIN_NETWORK Or networkWidth > MAX_NETWORK Then + Print "INVALID NETWORK WIDTH:"; networkWidth + Return False + End If + + For i As Integer = 0 To 3 + If ip.octets(i) > MAX_OCTET Then + Print "INVALID OCTET VALUE:"; ip.octets(i) + Return False + End If + Next + + Return True +End Function + +Sub ProcessCIDR(cidr As String) + Dim As Integer networkWidth + Dim As IPAddress ip = ParseIPAddress(cidr, networkWidth) + + If Not ValidateInput(ip, networkWidth, cidr) Then Exit Sub + + ip = ApplyNetworkMask(ip, networkWidth) + + Dim As String result = Str(ip.octets(0)) + For i As Integer = 1 To 3 + result &= "." & Str(ip.octets(i)) + Next + Print result & "/" & networkWidth +End Sub + +' Main program +Dim As String cidr(9) = { _ +"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", _ +"127.0.0.1", "123.45.67.89/0", "98.76.54.32/100", "123.456.789.0/12" } + +For i As Integer = 0 To 9 + ProcessCIDR(cidr(i)) +Next Sleep diff --git a/Task/Canonicalize-CIDR/FutureBasic/canonicalize-cidr.basic b/Task/Canonicalize-CIDR/FutureBasic/canonicalize-cidr.basic new file mode 100644 index 0000000000..8594d42eb7 --- /dev/null +++ b/Task/Canonicalize-CIDR/FutureBasic/canonicalize-cidr.basic @@ -0,0 +1,132 @@ +// +// Canonicalize CIDR +// +// Using FutureBasic 7.0.34 +// August 25, R.W +// +// Given a Classless Inter-Domain Routing (CIDR) +// IPv4 address, returns the canonical form. +// + +Int networkWidth // network width in bits +CFStringRef errorCode // global err and CCIDR +CFStringRef CCIDR // canonical CIDR IPv4 + +// Type for IP address +begin record IPv4_Address + Int octets[3] // xxx.xxx.xxx.xx/xx +end record + +// Validate CIDR string +local fn ValidateCIDR(ip as IPv4_Address, SnetworkWidth as Int, cidr as CFStringRef) as Boolean + Int i + boolean result + result = _True + if instr(0, cidr, @"/") == NSNotFound + errorCode = concat(@"Bad CIDR ",cidr) + result = _False + return result + end if + if SnetworkWidth < 1 || SnetworkWidth > 32 //validate network width + errorCode = concat(@"Bad Net Width",str(networkWidth)) + result = _False + return result + end if + for i = 0 to 3 + if ip.octets[i] > 255 + errorCode = concat(@"Bad Octet ",str(ip.octets[i])) + result = _False + return result + end if + next +end fn = result + +// Check if a character is a digit +local fn IsDigit(ch as CFStringRef) as boolean + Boolean IsDigit + IsDigit = (ucc(ch) > 47) && (ucc(ch) < 58) +end fn = IsDigit + +// Parse CIDR string into IP structure and network width +local fn ParseIPv4_Address(cidr as CFStringRef) as IPv4_Address + IPv4_Address ip + Int i, slashPos, currentOctet, octetValue + CFStringRef ipPart + ipPart = @"" + slashPos = instr(0, cidr, @"/") + if slashPos > 0 + ipPart = left(cidr, slashPos) + networkWidth = Intval(mid(cidr, slashPos + 1)) + else + ipPart = cidr + networkWidth = -1 + end if + currentOctet = 0: octetValue = 0 + for i = 0 to len(ipPart)-1 + select case mid(ipPart, i, 1) + case @"." + ip.octets[currentOctet] = octetValue + currentOctet ++ + octetValue = 0 + case else + if fn IsDigit(mid(ipPart, i, 1)) + octetValue = octetValue * 10 + Intval(mid(ipPart, i, 1)) + end if + end select + next + ip.octets[currentOctet] = octetValue +end fn = ip + +// Apply network mask to IP +local fn ApplyNetworkMask(ip as IPv4_Address, SnetworkWidth as Int) as IPv4_Address + IPv4_Address result + Int completeOctets, remainingBits, i + result = ip + completeOctets = SnetworkWidth \ 8 //octet bits + remainingBits = SnetworkWidth AND 7 + if completeOctets < 4 + result.octets[completeOctets] = result.octets[completeOctets] AND (255 - 2^(8 - remainingBits) + 1) + for i = completeOctets + 1 to 3 + result.octets[i] = 0 + next + end if +end fn = result + +// Process a CIDR string, sets global CCIDR +local fn ProcessCIDR(cidr as CFStringRef) as CFStringRef + IPv4_Address ip + CFStringRef result + Int i + result = @"" + ip = fn ParseIPv4_Address(cidr) + if fn ValidateCIDR(ip, networkWidth, cidr) // validate + ip = fn ApplyNetworkMask(ip, networkWidth) + result = mid(str(ip.octets[0]),1) + for i = 1 to 3 + result = concat(result,@".",mid(str(ip.octets[i]),1)) + next + result = concat(result,@"/",mid(str(networkWidth),1)) + else + print@ errorCode + end if + CCIDR = result +end fn = result + +// +// Main + +Window 1,@"Canonicalize CIDR" +print@ + +// Test data from the Rosetta Stone task + +CFStringRef cidr(5) = {@"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"} + +for Int i = 0 to 5 + print@ fn ProcessCIDR(cidr(i)) +next + +HandleEvents + +// diff --git a/Task/Canonicalize-CIDR/Julia/canonicalize-cidr.julia b/Task/Canonicalize-CIDR/Julia/canonicalize-cidr.jl similarity index 100% rename from Task/Canonicalize-CIDR/Julia/canonicalize-cidr.julia rename to Task/Canonicalize-CIDR/Julia/canonicalize-cidr.jl diff --git a/Task/Canonicalize-CIDR/OCaml/canonicalize-cidr.ocaml b/Task/Canonicalize-CIDR/OCaml/canonicalize-cidr.ml similarity index 100% rename from Task/Canonicalize-CIDR/OCaml/canonicalize-cidr.ocaml rename to Task/Canonicalize-CIDR/OCaml/canonicalize-cidr.ml diff --git a/Task/Canonicalize-CIDR/Phix/canonicalize-cidr.phix b/Task/Canonicalize-CIDR/Phix/canonicalize-cidr.phix index 187988d1b3..aca9dd0ac3 100644 --- a/Task/Canonicalize-CIDR/Phix/canonicalize-cidr.phix +++ b/Task/Canonicalize-CIDR/Phix/canonicalize-cidr.phix @@ -1,35 +1,31 @@ -(phixonline)--> - with javascript_semantics -- (not likely useful) - function canonicalize_cidr(string cidr) - cidr = substitute(cidr,"."," ") -- (else %d eats 0.0 etc) - if not find('/',cidr) then cidr &= "/32" end if - sequence res = scanf(cidr,"%d %d %d %d/%d") - if length(res)=1 then - integer {a,b,c,d,m} = res[1] - if a>=0 and a<=255 - and b>=0 and b<=255 - and c>=0 and c<=255 - and d>=0 and d<=255 - and m>=1 and m<=32 then - atom mask = power(2,32-m)-1, - addr = bytes_to_int({d,c,b,a}) - addr -= and_bits(addr,mask) - {d,c,b,a} = int_to_bytes(addr) - return sprintf("%d.%d.%d.%d/%d",{a,b,c,d,m}) - end if - end if - return "???" - end function +with javascript_semantics +function canonicalize_cidr(string cidr) + cidr = substitute(cidr,"."," ") -- (else %d eats 0.0 etc) + if not find('/',cidr) then cidr &= "/32" end if + sequence res = scanf(cidr,"%d %d %d %d/%d") + if length(res)=1 then + integer {a,b,c,d,m} = res[1] + if a>=0 and a<=255 + and b>=0 and b<=255 + and c>=0 and c<=255 + and d>=0 and d<=255 + and m>=1 and m<=32 then + atom mask = power(2,32-m)-1, + addr = bytes_to_int({d,c,b,a}) + addr -= and_bits(addr,mask) + {d,c,b,a} = int_to_bytes(addr) + return sprintf("%d.%d.%d.%d/%d",{a,b,c,d,m}) + end if + end if + return "???" +end function - constant tests = {"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"} - - for i=1 to length(tests) do - string ti = tests[i] - printf(1,"%-18s -> %s\n",{ti,canonicalize_cidr(ti)}) - end for - - integer n = 5, - w = power(3,n-1), - len = w - string line = repeat('#',w)&"\n" - - while 1 do - puts(1,line) - if len=1 then exit end if - len /= 3 - integer pos = 1 - while pos<(w-len) do - pos += len - line[pos..pos+len-1] = ' ' - pos += len - end while - end while - - with javascript_semantics - integer count = 0 - for p1=1 to 61 do - if is_prime(p1) then - for h3=1 to p1 do - atom h3p1 = h3 + p1 - for d=1 to h3p1-1 do - if mod(h3p1*(p1-1),d)=0 - and mod(-(p1*p1),h3) = mod(d,h3) then - atom p2 := 1 + floor(((p1-1)*h3p1)/d), - p3 := 1 +floor(p1*p2/h3) - if is_prime(p2) - and is_prime(p3) - and mod(p2*p3,p1-1)=1 then - if count<5 or count>65 then - printf(1,"%d * %d * %d = %d\n",{p1,p2,p3,p1*p2*p3}) - elsif count=35 then puts(1,"...\n") end if - count += 1 - end if - end if - end for - end for - end if - end for - printf(1,"%d Carmichael numbers found\n",count) - [ ) + [ [] temp put + over witheach + [ dip dup join + nested temp gather ] + drop temp take + temp gather ] + drop temp take ] is cart ( [ [ --> [ ) - ' [ 1 2 ] ' [ 3 4 ] cartprod echo cr - ' [ 3 4 ] ' [ 1 2 ] cartprod echo cr - ' [ 1 2 ] ' [ ] cartprod echo cr - ' [ ] ' [ 1 2 ] cartprod echo cr + [ behead swap witheach cart ] is n-cart ( [ --> [ ) + + ' [ 1 2 ] ' [ 3 4 ] cart echo cr cr + ' [ 1 2 ] ' [ ] cart echo cr cr + ' [ ] ' [ 1 2 ] cart echo cr cr + + ' [ [ 1776 1789 ] [ 7 12 ] [ 4 14 23 ] [ 0 1 ] ] n-cart + say "[ " + witheach + [ i^ 0 != if [ say " " ] + echo + i 0 = if [ say " ]" ] cr ] + cr + + ' [ [ 1 2 3 ] [ 30 ] [ 500 100 ] ] n-cart echo cr cr + ' [ [ 1 2 3 ] [ ] [ 500 100 ] ] n-cart echo cr cr diff --git a/Task/Cartesian-product-of-two-or-more-lists/Rust/cartesian-product-of-two-or-more-lists-1.rs b/Task/Cartesian-product-of-two-or-more-lists/Rust/cartesian-product-of-two-or-more-lists-1.rs new file mode 100644 index 0000000000..4bde4f9f43 --- /dev/null +++ b/Task/Cartesian-product-of-two-or-more-lists/Rust/cartesian-product-of-two-or-more-lists-1.rs @@ -0,0 +1,42 @@ +fn cartesian_product<'a, T>(lists: &[&'a [T]]) -> Vec> { + let mut res = vec![vec![]]; + + for &list in lists { + let mut tmp = Vec::new(); + + for r in res { + for item in list { + let mut r = r.clone(); + r.push(item); + tmp.push(r); + } + } + + res = tmp; + } + + res +} + +fn main() { + let cases: [&[&[u32]]; 7] = [ + &[&[1, 2], &[3, 4]], + &[&[3, 4], &[1, 2]], + &[&[1, 2], &[]], + &[&[], &[1, 2]], + &[&[1776, 1789], &[7, 12], &[4, 14, 23], &[0, 1]], + &[&[1, 2, 3], &[30], &[500, 100]], + &[&[1, 2, 3], &[], &[500, 100]], + ]; + + for case in cases { + println!( + "{}\n{:?}\n", + case.iter() + .map(|c| format!("{:?}", c)) + .collect::>() + .join(" × "), + cartesian_product(case) + ) + } +} diff --git a/Task/Cartesian-product-of-two-or-more-lists/Rust/cartesian-product-of-two-or-more-lists-2.rs b/Task/Cartesian-product-of-two-or-more-lists/Rust/cartesian-product-of-two-or-more-lists-2.rs new file mode 100644 index 0000000000..88f569f91f --- /dev/null +++ b/Task/Cartesian-product-of-two-or-more-lists/Rust/cartesian-product-of-two-or-more-lists-2.rs @@ -0,0 +1,2 @@ +[dependencies] +itertools = { version = "0.14.0", features = ["use_alloc"] } diff --git a/Task/Cartesian-product-of-two-or-more-lists/Rust/cartesian-product-of-two-or-more-lists-3.rs b/Task/Cartesian-product-of-two-or-more-lists/Rust/cartesian-product-of-two-or-more-lists-3.rs new file mode 100644 index 0000000000..e8d4eff8e3 --- /dev/null +++ b/Task/Cartesian-product-of-two-or-more-lists/Rust/cartesian-product-of-two-or-more-lists-3.rs @@ -0,0 +1,28 @@ +use itertools::{Itertools, MultiProduct}; + +fn cartesian_product<'a, T>(inputs: &[&'a [T]]) -> MultiProduct> { + inputs + .iter() + .map(|slice| slice.iter()) + .multi_cartesian_product() +} + +fn main() { + let cases: [&[&[u32]]; 7] = [ + &[&[1, 2], &[3, 4]], + &[&[3, 4], &[1, 2]], + &[&[1, 2], &[]], + &[&[], &[1, 2]], + &[&[1776, 1789], &[7, 12], &[4, 14, 23], &[0, 1]], + &[&[1, 2, 3], &[30], &[500, 100]], + &[&[1, 2, 3], &[], &[500, 1000]], + ]; + + for case in cases { + println!( + "{:?}\n[{:?}]\n", + case.iter().format(" × "), + cartesian_product(case).format(", ") + ); + } +} diff --git a/Task/Cartesian-product-of-two-or-more-lists/Rust/cartesian-product-of-two-or-more-lists.rust b/Task/Cartesian-product-of-two-or-more-lists/Rust/cartesian-product-of-two-or-more-lists.rust deleted file mode 100644 index 9345a4ad79..0000000000 --- a/Task/Cartesian-product-of-two-or-more-lists/Rust/cartesian-product-of-two-or-more-lists.rust +++ /dev/null @@ -1,41 +0,0 @@ -fn cartesian_product(lists: &Vec>) -> Vec> { - let mut res = vec![]; - - let mut list_iter = lists.iter(); - if let Some(first_list) = list_iter.next() { - for &i in first_list { - res.push(vec![i]); - } - } - for l in list_iter { - let mut tmp = vec![]; - for r in res { - for &el in l { - let mut tmp_el = r.clone(); - tmp_el.push(el); - tmp.push(tmp_el); - } - } - res = tmp; - } - res -} - -fn main() { - let cases = vec![ - vec![vec![1, 2], vec![3, 4]], - vec![vec![3, 4], vec![1, 2]], - vec![vec![1, 2], vec![]], - vec![vec![], vec![1, 2]], - vec![vec![1776, 1789], vec![7, 12], vec![4, 14, 23], vec![0, 1]], - vec![vec![1, 2, 3], vec![30], vec![500, 100]], - vec![vec![1, 2, 3], vec![], vec![500, 100]], - ]; - for case in cases { - println!( - "{}\n{:?}\n", - case.iter().map(|c| format!("{:?}", c)).collect::>().join(" × "), - cartesian_product(&case) - ) - } -} diff --git a/Task/Cartesian-product-of-two-or-more-lists/Scheme/cartesian-product-of-two-or-more-lists.ss b/Task/Cartesian-product-of-two-or-more-lists/Scheme/cartesian-product-of-two-or-more-lists.scm similarity index 100% rename from Task/Cartesian-product-of-two-or-more-lists/Scheme/cartesian-product-of-two-or-more-lists.ss rename to Task/Cartesian-product-of-two-or-more-lists/Scheme/cartesian-product-of-two-or-more-lists.scm diff --git a/Task/Cartesian-product-of-two-or-more-lists/Uiua/cartesian-product-of-two-or-more-lists.uiua b/Task/Cartesian-product-of-two-or-more-lists/Uiua/cartesian-product-of-two-or-more-lists.uiua new file mode 100644 index 0000000000..2895add665 --- /dev/null +++ b/Task/Cartesian-product-of-two-or-more-lists/Uiua/cartesian-product-of-two-or-more-lists.uiua @@ -0,0 +1,9 @@ +# Cartesian products + +☇1⊞⊂[1 2] [3 4] +☇1⊞⊂[3 4] [1 2] +☇1⊞⊂[3 4] [] +C ← /◇(☇1⊞⊂) +≡⍚C{{[1776 1789] [7 12] [4 14 23] [0 1]} + {[1 2 3] [30] [500 100]} + {[1 2 3] [] [500 100]}} diff --git a/Task/Case-sensitivity-of-identifiers/ALGOL-M/case-sensitivity-of-identifiers.alg b/Task/Case-sensitivity-of-identifiers/ALGOL-M/case-sensitivity-of-identifiers.alg new file mode 100644 index 0000000000..5e25c79838 --- /dev/null +++ b/Task/Case-sensitivity-of-identifiers/ALGOL-M/case-sensitivity-of-identifiers.alg @@ -0,0 +1,13 @@ +begin + +string dog; +comment + An attempt to declare Dog or DOG after declaring + dog will result in a compile-time error ("Doubly + Declared identifier"); +dog := "Benjamin"; +Dog := "Samba"; +DOG := "Bernie"; +write("There is just one dog named ", dog); + +end diff --git a/Task/Case-sensitivity-of-identifiers/Ada/case-sensitivity-of-identifiers.ada b/Task/Case-sensitivity-of-identifiers/Ada/case-sensitivity-of-identifiers.adb similarity index 100% rename from Task/Case-sensitivity-of-identifiers/Ada/case-sensitivity-of-identifiers.ada rename to Task/Case-sensitivity-of-identifiers/Ada/case-sensitivity-of-identifiers.adb diff --git a/Task/Case-sensitivity-of-identifiers/Ballerina/case-sensitivity-of-identifiers.ballerina b/Task/Case-sensitivity-of-identifiers/Ballerina/case-sensitivity-of-identifiers.ballerina new file mode 100644 index 0000000000..6b87eea744 --- /dev/null +++ b/Task/Case-sensitivity-of-identifiers/Ballerina/case-sensitivity-of-identifiers.ballerina @@ -0,0 +1,8 @@ +import ballerina/io; + +public function main() { + string dog = "Benjamin"; + string Dog = "Samba"; + string DOG = "Bernie"; + io:println(`The three dogs are named ${dog}, ${Dog} and ${DOG}.`); +} diff --git a/Task/Case-sensitivity-of-identifiers/COBOL/case-sensitivity-of-identifiers.cobol b/Task/Case-sensitivity-of-identifiers/COBOL/case-sensitivity-of-identifiers.cob similarity index 100% rename from Task/Case-sensitivity-of-identifiers/COBOL/case-sensitivity-of-identifiers.cobol rename to Task/Case-sensitivity-of-identifiers/COBOL/case-sensitivity-of-identifiers.cob diff --git a/Task/Case-sensitivity-of-identifiers/Crystal/case-sensitivity-of-identifiers.crystal b/Task/Case-sensitivity-of-identifiers/Crystal/case-sensitivity-of-identifiers.cr similarity index 100% rename from Task/Case-sensitivity-of-identifiers/Crystal/case-sensitivity-of-identifiers.crystal rename to Task/Case-sensitivity-of-identifiers/Crystal/case-sensitivity-of-identifiers.cr diff --git a/Task/Case-sensitivity-of-identifiers/D/case-sensitivity-of-identifiers.d b/Task/Case-sensitivity-of-identifiers/D/case-sensitivity-of-identifiers.d index c140100011..549512886a 100644 --- a/Task/Case-sensitivity-of-identifiers/D/case-sensitivity-of-identifiers.d +++ b/Task/Case-sensitivity-of-identifiers/D/case-sensitivity-of-identifiers.d @@ -5,6 +5,6 @@ void main() { // identifiers that start with capital letters are type names string Dog = "Samba"; string DOG = "Bernie"; - writefln("There are three dogs named ", - dog, ", ", Dog, ", and ", DOG, "'"); + writeln("There are three dogs named ", + dog, ", ", Dog, ", and ", DOG, "."); } diff --git a/Task/Case-sensitivity-of-identifiers/Delphi/case-sensitivity-of-identifiers.delphi b/Task/Case-sensitivity-of-identifiers/Delphi/case-sensitivity-of-identifiers.pas similarity index 100% rename from Task/Case-sensitivity-of-identifiers/Delphi/case-sensitivity-of-identifiers.delphi rename to Task/Case-sensitivity-of-identifiers/Delphi/case-sensitivity-of-identifiers.pas diff --git a/Task/Case-sensitivity-of-identifiers/DuckDB/case-sensitivity-of-identifiers-1.duckdb b/Task/Case-sensitivity-of-identifiers/DuckDB/case-sensitivity-of-identifiers-1.duckdb new file mode 100644 index 0000000000..0b9cd57834 --- /dev/null +++ b/Task/Case-sensitivity-of-identifiers/DuckDB/case-sensitivity-of-identifiers-1.duckdb @@ -0,0 +1,3 @@ +create or replace function task(dog, Dog, DOG) as ( + format('The three dogs are named {:s}, {:s} and {:s}.', dog, Dog, DOG) +); diff --git a/Task/Case-sensitivity-of-identifiers/DuckDB/case-sensitivity-of-identifiers-2.duckdb b/Task/Case-sensitivity-of-identifiers/DuckDB/case-sensitivity-of-identifiers-2.duckdb new file mode 100644 index 0000000000..d7c7d9bd1c --- /dev/null +++ b/Task/Case-sensitivity-of-identifiers/DuckDB/case-sensitivity-of-identifiers-2.duckdb @@ -0,0 +1,2 @@ +select format('The three dogs are named {:s}, {:s} and {:s}.', dog, Dog, DOG) as example +from (select 'Benjamin' as dog, 'Samba' as Dog, 'Bernie' as DOG); diff --git a/Task/Case-sensitivity-of-identifiers/Elena/case-sensitivity-of-identifiers.elena b/Task/Case-sensitivity-of-identifiers/Elena/case-sensitivity-of-identifiers.elena index b33d071054..2deacb71ce 100644 --- a/Task/Case-sensitivity-of-identifiers/Elena/case-sensitivity-of-identifiers.elena +++ b/Task/Case-sensitivity-of-identifiers/Elena/case-sensitivity-of-identifiers.elena @@ -1,9 +1,9 @@ import extensions; -public program() +public Program() { var dog := "Benjamin"; var Dog := "Samba"; var DOG := "Bernie"; - console.printLineFormatted("The three dogs are named {0}, {1} and {2}", dog, Dog, DOG) + Console.printLineFormatted("The three dogs are named {0}, {1} and {2}", dog, Dog, DOG) } diff --git a/Task/Case-sensitivity-of-identifiers/Elixir/case-sensitivity-of-identifiers.elixir b/Task/Case-sensitivity-of-identifiers/Elixir/case-sensitivity-of-identifiers.ex similarity index 100% rename from Task/Case-sensitivity-of-identifiers/Elixir/case-sensitivity-of-identifiers.elixir rename to Task/Case-sensitivity-of-identifiers/Elixir/case-sensitivity-of-identifiers.ex diff --git a/Task/Case-sensitivity-of-identifiers/Euphoria/case-sensitivity-of-identifiers.euphoria b/Task/Case-sensitivity-of-identifiers/Euphoria/case-sensitivity-of-identifiers.eu similarity index 100% rename from Task/Case-sensitivity-of-identifiers/Euphoria/case-sensitivity-of-identifiers.euphoria rename to Task/Case-sensitivity-of-identifiers/Euphoria/case-sensitivity-of-identifiers.eu diff --git a/Task/Case-sensitivity-of-identifiers/GW-BASIC/case-sensitivity-of-identifiers.basic b/Task/Case-sensitivity-of-identifiers/GW-BASIC/case-sensitivity-of-identifiers.basic deleted file mode 100644 index 33a43f9953..0000000000 --- a/Task/Case-sensitivity-of-identifiers/GW-BASIC/case-sensitivity-of-identifiers.basic +++ /dev/null @@ -1,5 +0,0 @@ -10 dog$ = "Benjamin" -20 dog$ = "Smokey" -30 dog$ = "Samba" -40 dog$ = "Bernie" -50 print "There is just one dog, named ";dog$ diff --git a/Task/Case-sensitivity-of-identifiers/Joy/case-sensitivity-of-identifiers.joy b/Task/Case-sensitivity-of-identifiers/Joy/case-sensitivity-of-identifiers.joy new file mode 100644 index 0000000000..5e074a15e6 --- /dev/null +++ b/Task/Case-sensitivity-of-identifiers/Joy/case-sensitivity-of-identifiers.joy @@ -0,0 +1,17 @@ +DEFINE dog == "Benjamin". +DEFINE Dog == "Samba". +DEFINE DOG == "Bernie". +"The three dogs are named" +"." DOG "and" Dog "," dog "The three dogs are named" +. +"The three dogs are named" +. +"Benjamin" +. +"," +. +"Samba" +. +"and" +. +"Bernie" diff --git a/Task/Case-sensitivity-of-identifiers/Julia/case-sensitivity-of-identifiers.julia b/Task/Case-sensitivity-of-identifiers/Julia/case-sensitivity-of-identifiers.jl similarity index 100% rename from Task/Case-sensitivity-of-identifiers/Julia/case-sensitivity-of-identifiers.julia rename to Task/Case-sensitivity-of-identifiers/Julia/case-sensitivity-of-identifiers.jl diff --git a/Task/Case-sensitivity-of-identifiers/Kotlin/case-sensitivity-of-identifiers.kotlin b/Task/Case-sensitivity-of-identifiers/Kotlin/case-sensitivity-of-identifiers.kts similarity index 100% rename from Task/Case-sensitivity-of-identifiers/Kotlin/case-sensitivity-of-identifiers.kotlin rename to Task/Case-sensitivity-of-identifiers/Kotlin/case-sensitivity-of-identifiers.kts diff --git a/Task/Case-sensitivity-of-identifiers/LOLCODE/case-sensitivity-of-identifiers.lol b/Task/Case-sensitivity-of-identifiers/LOLCODE/case-sensitivity-of-identifiers.lol new file mode 100644 index 0000000000..bbf2bc3047 --- /dev/null +++ b/Task/Case-sensitivity-of-identifiers/LOLCODE/case-sensitivity-of-identifiers.lol @@ -0,0 +1,12 @@ +HAI 1.3 + +I HAS A dog ITZ "Benjamin" +I HAS A Dog ITZ "Samba" +I HAS A DOG ITZ "Bernie" + +EITHER OF DIFFRINT dog AN Dog AN DIFFRINT Dog AN DOG, O RLY? + YA RLY, VISIBLE "TEH 3 DOGZ R NAEMD :{dog}, :{Dog}, AN :{DOG}." + NO WAI, VISIBLE "THERE IZ JUST 1 DOG NAEMD :{DOG}." +OIC + +KTHXBYE diff --git a/Task/Case-sensitivity-of-identifiers/Nim/case-sensitivity-of-identifiers.nim b/Task/Case-sensitivity-of-identifiers/Nim/case-sensitivity-of-identifiers.nim index 6968431516..37894e4681 100644 --- a/Task/Case-sensitivity-of-identifiers/Nim/case-sensitivity-of-identifiers.nim +++ b/Task/Case-sensitivity-of-identifiers/Nim/case-sensitivity-of-identifiers.nim @@ -3,7 +3,7 @@ var dog, Dog: string if dog == Dog: if dog == DOG: - echo "There is only one dog, ", DOG) + echo "There is only one dog, ", DOG else: echo "There are two dogs: ", dog, " and ", DOG elif Dog == DOG : diff --git a/Task/Case-sensitivity-of-identifiers/OCaml/case-sensitivity-of-identifiers.ocaml b/Task/Case-sensitivity-of-identifiers/OCaml/case-sensitivity-of-identifiers.ml similarity index 100% rename from Task/Case-sensitivity-of-identifiers/OCaml/case-sensitivity-of-identifiers.ocaml rename to Task/Case-sensitivity-of-identifiers/OCaml/case-sensitivity-of-identifiers.ml diff --git a/Task/Case-sensitivity-of-identifiers/PascalABC.NET/case-sensitivity-of-identifiers.pas b/Task/Case-sensitivity-of-identifiers/PascalABC.NET/case-sensitivity-of-identifiers.pas new file mode 100644 index 0000000000..d697568ba5 --- /dev/null +++ b/Task/Case-sensitivity-of-identifiers/PascalABC.NET/case-sensitivity-of-identifiers.pas @@ -0,0 +1,8 @@ +var + dog: string; +begin + dog := 'Benjamin'; + Dog := 'Samba'; + DOG := 'Bernie'; + Writeln('There is just one dog named ' + dog); +end. diff --git a/Task/Case-sensitivity-of-identifiers/Pluto/case-sensitivity-of-identifiers.pluto b/Task/Case-sensitivity-of-identifiers/Pluto/case-sensitivity-of-identifiers.pluto new file mode 100644 index 0000000000..79d19b3417 --- /dev/null +++ b/Task/Case-sensitivity-of-identifiers/Pluto/case-sensitivity-of-identifiers.pluto @@ -0,0 +1,13 @@ +do + local dog = "Benjamin"; + do + local Dog = "Samba"; + do + local DOG = "Bernie"; + if DOG != Dog or DOG != dog + then print( $"The three dogs are named: {dog}, {Dog} and {DOG}" ) + else print( $"There is just one dog named: {DOG}" ) + end + end + end +end diff --git a/Task/Case-sensitivity-of-identifiers/PowerShell/case-sensitivity-of-identifiers.psh b/Task/Case-sensitivity-of-identifiers/PowerShell/case-sensitivity-of-identifiers.ps1 similarity index 100% rename from Task/Case-sensitivity-of-identifiers/PowerShell/case-sensitivity-of-identifiers.psh rename to Task/Case-sensitivity-of-identifiers/PowerShell/case-sensitivity-of-identifiers.ps1 diff --git a/Task/Case-sensitivity-of-identifiers/Red/case-sensitivity-of-identifiers.red b/Task/Case-sensitivity-of-identifiers/Red/case-sensitivity-of-identifiers.red new file mode 100644 index 0000000000..5d1432eea1 --- /dev/null +++ b/Task/Case-sensitivity-of-identifiers/Red/case-sensitivity-of-identifiers.red @@ -0,0 +1,8 @@ +dog: "Benjamin" +Dog: "Samba" +DOG: "Bernie" + +print [ "The three dogs are " dog "," Dog "," DOG ] + +;- as Red is not case sensitive, will ouput +;- The three dogs are Bernie , Bernie , Bernie diff --git a/Task/Case-sensitivity-of-identifiers/Refal/case-sensitivity-of-identifiers.refal b/Task/Case-sensitivity-of-identifiers/Refal/case-sensitivity-of-identifiers.refal new file mode 100644 index 0000000000..11adce0813 --- /dev/null +++ b/Task/Case-sensitivity-of-identifiers/Refal/case-sensitivity-of-identifiers.refal @@ -0,0 +1,6 @@ +$ENTRY Go { + , 'Benjamin': e.dog + , 'Samba': e.Dog + , 'Bernie': e.DOG + = ; +}; diff --git a/Task/Case-sensitivity-of-identifiers/Rust/case-sensitivity-of-identifiers-1.rust b/Task/Case-sensitivity-of-identifiers/Rust/case-sensitivity-of-identifiers-1.rs similarity index 100% rename from Task/Case-sensitivity-of-identifiers/Rust/case-sensitivity-of-identifiers-1.rust rename to Task/Case-sensitivity-of-identifiers/Rust/case-sensitivity-of-identifiers-1.rs diff --git a/Task/Case-sensitivity-of-identifiers/Rust/case-sensitivity-of-identifiers-2.rust b/Task/Case-sensitivity-of-identifiers/Rust/case-sensitivity-of-identifiers-2.rs similarity index 100% rename from Task/Case-sensitivity-of-identifiers/Rust/case-sensitivity-of-identifiers-2.rust rename to Task/Case-sensitivity-of-identifiers/Rust/case-sensitivity-of-identifiers-2.rs diff --git a/Task/Case-sensitivity-of-identifiers/Rust/case-sensitivity-of-identifiers-3.rust b/Task/Case-sensitivity-of-identifiers/Rust/case-sensitivity-of-identifiers-3.rs similarity index 100% rename from Task/Case-sensitivity-of-identifiers/Rust/case-sensitivity-of-identifiers-3.rust rename to Task/Case-sensitivity-of-identifiers/Rust/case-sensitivity-of-identifiers-3.rs diff --git a/Task/Case-sensitivity-of-identifiers/S-BASIC/case-sensitivity-of-identifiers.basic b/Task/Case-sensitivity-of-identifiers/S-BASIC/case-sensitivity-of-identifiers.basic new file mode 100644 index 0000000000..de5524ecca --- /dev/null +++ b/Task/Case-sensitivity-of-identifiers/S-BASIC/case-sensitivity-of-identifiers.basic @@ -0,0 +1,13 @@ +var dog = string +comment + An attempt to declare Dog or DOG after declaring dog + will result in a compile-time error ("One of these VAR + names in use") +end + +dog = "Benjamin" +Dog = "Samba" +DOG = "Bernie" +print "There is just one dog named "; dog + +end diff --git a/Task/Case-sensitivity-of-identifiers/Scheme/case-sensitivity-of-identifiers.ss b/Task/Case-sensitivity-of-identifiers/Scheme/case-sensitivity-of-identifiers.scm similarity index 100% rename from Task/Case-sensitivity-of-identifiers/Scheme/case-sensitivity-of-identifiers.ss rename to Task/Case-sensitivity-of-identifiers/Scheme/case-sensitivity-of-identifiers.scm diff --git a/Task/Case-sensitivity-of-identifiers/Swift/case-sensitivity-of-identifiers.swift b/Task/Case-sensitivity-of-identifiers/Swift/case-sensitivity-of-identifiers.swift index b027c8aadd..e0af4e9df0 100644 --- a/Task/Case-sensitivity-of-identifiers/Swift/case-sensitivity-of-identifiers.swift +++ b/Task/Case-sensitivity-of-identifiers/Swift/case-sensitivity-of-identifiers.swift @@ -1,4 +1,4 @@ let dog = "Benjamin" let Dog = "Samba" let DOG = "Bernie" -println("The three dogs are named \(dog), \(Dog), and \(DOG).") +print("The three dogs are named \(dog), \(Dog), and \(DOG).") diff --git a/Task/Casting-out-nines/Fortran/casting-out-nines.f b/Task/Casting-out-nines/Fortran/casting-out-nines.f new file mode 100644 index 0000000000..a2e0705db8 --- /dev/null +++ b/Task/Casting-out-nines/Fortran/casting-out-nines.f @@ -0,0 +1,220 @@ +program main + implicit none + + type :: test_case + integer :: base + character(len=10) :: begin, end_ + character(len=10), dimension(5) :: kaprekar + integer :: nkap + end type test_case + + type(test_case), dimension(2) :: testcases + type(test_case) :: tc + integer :: it, i, j + character(len=20), allocatable :: s(:) + logical :: found + + ! Initialize test cases + testcases(1)%base = 10 + testcases(1)%begin = '1' + testcases(1)%end_ = '100' + testcases(1)%kaprekar(1:5) = (/'1 ', '9 ', '45 ', '55 ', '99 '/) + testcases(1)%nkap = 5 + + testcases(2)%base = 17 + testcases(2)%begin = '10' + testcases(2)%end_ = 'gg' + testcases(2)%kaprekar(1:3) = (/'3d', 'd4', 'gg'/) + testcases(2)%nkap = 3 + + do it = 1, 2 + tc = testcases(it) + write(*, *) '' + write(*, '(A, I0, A, A, A, A)') 'Test case base = ', tc%base, ', begin = ', trim(tc%begin), ', end = ', trim(tc%end_) + call subset(tc%base, tc%begin, tc%end_, s) + write(*, '(A)', advance='no') 'Subset: ' + do i = 1, size(s) + write(*, '(A, A)', advance='no') trim(s(i)), ' ' + end do + write(*, *) + write(*, '(A)', advance='no') 'Kaprekar: ' + do i = 1, tc%nkap + write(*, '(A, A)', advance='no') trim(tc%kaprekar(i)), ' ' + end do + write(*, *) + + ! Check if all Kaprekar are in subset + j = 1 + do i = 1, tc%nkap + found = .false. + do while (j <= size(s)) + if (trim(s(j)) == trim(tc%kaprekar(i))) then + found = .true. + j = j + 1 + exit + end if + j = j + 1 + end do + if (.not. found) then + write(*, '(A, A, A)') 'Fail: ', trim(tc%kaprekar(i)), ' not in subset' + stop + end if + end do + write(*, *) 'Valid subset.' + if (allocated(s)) deallocate(s) + end do + +contains + + subroutine subset(base, begin, end_, s) + integer, intent(in) :: base + character(len=*), intent(in) :: begin, end_ + character(len=20), allocatable, intent(out) :: s(:) + integer(8) :: begin64, end64, k, kk + character(len=20) :: ks, kks + character(1) :: rk, rk2 + + begin64 = str_to_int(base, begin) + end64 = str_to_int(base, end_) + + allocate(s(0)) ! Start empty + + do k = begin64, end64 + ks = int_to_str(base, k) + rk = check_digit(base, ks) + kk = k * k + kks = int_to_str(base, kk) + rk2 = check_digit(base, kks) + if (rk == rk2) then + call append_str(s, ks) + end if + end do + end subroutine subset + + subroutine append_str(list, val) + character(len=20), allocatable, intent(inout) :: list(:) + character(len=*), intent(in) :: val + character(len=20), allocatable :: tmp(:) + + if (allocated(list)) then + allocate(tmp(size(list))) + tmp = list + deallocate(list) + allocate(list(size(tmp) + 1)) + list(1:size(tmp)) = tmp + list(size(tmp) + 1) = val + else + allocate(list(1)) + list(1) = val + end if + end subroutine append_str + + recursive function check_digit(base, n) result(r) + integer, intent(in) :: base + character(len=*), intent(in) :: n + character(1) :: r + character(1) :: d, b9 + character(len=20) :: s, s9 + integer :: i, v9 + + v9 = base - 1 + s9 = int_to_str(base, int(v9, 8)) + b9 = s9(1:1) ! Single digit + + r = '0' + do i = 1, len_trim(n) + d = n(i:i) + if (d == b9) cycle + if (r == '0') then + r = d + cycle + end if + s = add_digits(base, r, d) + if (trim(s) == trim(s9)) then + r = '0' + cycle + end if + if (len_trim(s) == 1) then + r = s(1:1) + cycle + end if + ! Recurse on two-digit sum + r = check_digit(base, trim(s)) + end do + end function check_digit + + function add_digits(base, a, b) result(res) + integer, intent(in) :: base + character(1), intent(in) :: a, b + character(len=20) :: res + integer :: ai, bi + + ai = digit_value(a, base) + bi = digit_value(b, base) + res = int_to_str(base, int(ai + bi, 8)) + end function add_digits + + function digit_value(c, base) result(v) + character(1), intent(in) :: c + integer, intent(in) :: base + integer :: v + + if (c >= '0' .and. c <= '9') then + v = iachar(c) - iachar('0') + else if (c >= 'a' .and. c <= 'z') then + v = 10 + iachar(c) - iachar('a') + else + stop 'invalid digit' + end if + if (v < 0 .or. v >= base) stop 'invalid digit for base' + end function digit_value + + function value_to_digit(v) result(c) + integer, intent(in) :: v + character(1) :: c + + if (v < 10) then + c = achar(iachar('0') + v) + else + c = achar(iachar('a') + v - 10) + end if + end function value_to_digit + + function int_to_str(base, k) result(s) + integer, intent(in) :: base + integer(8), intent(in) :: k + character(len=20) :: s + integer(8) :: kk + integer :: digit + + kk = k + if (kk < 0) kk = -kk ! But not handling negatives in this context + s = '' + if (kk == 0) then + s = '0' + return + end if + do while (kk > 0) + digit = mod(kk, int(base, 8)) + s = value_to_digit(digit) // s + kk = kk / int(base, 8) + end do + end function int_to_str + + function str_to_int(base, s) result(val) + integer, intent(in) :: base + character(len=*), intent(in) :: s + integer(8) :: val + integer :: i, lens, v + character(len=20) :: ss + + ss = adjustl(s) + lens = len_trim(ss) + val = 0 + do i = 1, lens + v = digit_value(ss(i:i), base) + val = val * int(base, 8) + int(v, 8) + end do + end function str_to_int + +end program main diff --git a/Task/Casting-out-nines/Julia/casting-out-nines.julia b/Task/Casting-out-nines/Julia/casting-out-nines.jl similarity index 100% rename from Task/Casting-out-nines/Julia/casting-out-nines.julia rename to Task/Casting-out-nines/Julia/casting-out-nines.jl diff --git a/Task/Casting-out-nines/Kotlin/casting-out-nines.kotlin b/Task/Casting-out-nines/Kotlin/casting-out-nines.kts similarity index 100% rename from Task/Casting-out-nines/Kotlin/casting-out-nines.kotlin rename to Task/Casting-out-nines/Kotlin/casting-out-nines.kts diff --git a/Task/Casting-out-nines/PascalABC.NET/casting-out-nines.pas b/Task/Casting-out-nines/PascalABC.NET/casting-out-nines.pas new file mode 100644 index 0000000000..3c185151a6 --- /dev/null +++ b/Task/Casting-out-nines/PascalABC.NET/casting-out-nines.pas @@ -0,0 +1,16 @@ +## +function co9(x: integer): integer; +begin + if x = 9 then result := 0 + else if x < 9 then result := x + else result := co9(x.ToString.select(x -> StrToInt(x)).sum); +end; + +var kaprekars := [1, 9, 45, 55, 99, 297, 703, 999]; + +Print('Checksums: '); (1..20).Select(x -> co9(x)).Println; +Print('co9(k) = co9(k*k): '); +Println((1..1000).Where(x -> co9(x) = co9(x * x))); +var part2 := (1..1000).Where(x -> co9(x) = co9(x * x)).ToSet; +Println('Kaprekars: ', kaprekars); +if kaprekars <= part2 then Println('Kaprekars are included.', part2.Count, 'numbers in range 1000'); diff --git a/Task/Casting-out-nines/Pluto/casting-out-nines.pluto b/Task/Casting-out-nines/Pluto/casting-out-nines.pluto new file mode 100644 index 0000000000..123bf40ebc --- /dev/null +++ b/Task/Casting-out-nines/Pluto/casting-out-nines.pluto @@ -0,0 +1,30 @@ +local function cast_out(base, start, finish) + local b = base - 1 + local ran = range(0, b - 1):filter(|n| -> n % b == (n * n) % b) + local x = start // b + local result = {} + while true do + for ran as n do + local k = b * x + n + if k >= start then + if k > finish then return result end + result:insert(k) + end + end + ++x + end +end + +local function print_array(a, w = 3, n = 10) + for i = 1, #a do + io.write(string.format($"%{w}d ", a[i])) + if i % n == 0 then print() end + end + if #a % 10 != n then print() end +end + +print_array(cast_out(16, 1, 255)) +print() +print_array(cast_out(10, 1, 99)) +print() +print_array(cast_out(17, 1, 288)) diff --git a/Task/Casting-out-nines/Rust/casting-out-nines.rust b/Task/Casting-out-nines/Rust/casting-out-nines.rs similarity index 100% rename from Task/Casting-out-nines/Rust/casting-out-nines.rust rename to Task/Casting-out-nines/Rust/casting-out-nines.rs diff --git a/Task/Catalan-numbers-Pascals-triangle/360-Assembly/catalan-numbers-pascals-triangle.360 b/Task/Catalan-numbers-Pascals-triangle/360-Assembly/catalan-numbers-pascals-triangle.360 index a0cc83dae1..633d55d35e 100644 --- a/Task/Catalan-numbers-Pascals-triangle/360-Assembly/catalan-numbers-pascals-triangle.360 +++ b/Task/Catalan-numbers-Pascals-triangle/360-Assembly/catalan-numbers-pascals-triangle.360 @@ -68,7 +68,7 @@ ENLOOP2J EQU * MVC C,Z OI C+L'C-1,X'F0' MVC WTOBUF(8),C+8 - WTO MF=(E,WTOMSG) + WTO MF=(E,WTOMSG) B LOOPI ENDLOOPI EQU * * ---- END CODE diff --git a/Task/Catalan-numbers-Pascals-triangle/Ada/catalan-numbers-pascals-triangle.ada b/Task/Catalan-numbers-Pascals-triangle/Ada/catalan-numbers-pascals-triangle.adb similarity index 100% rename from Task/Catalan-numbers-Pascals-triangle/Ada/catalan-numbers-pascals-triangle.ada rename to Task/Catalan-numbers-Pascals-triangle/Ada/catalan-numbers-pascals-triangle.adb diff --git a/Task/Catalan-numbers-Pascals-triangle/AutoHotkey/catalan-numbers-pascals-triangle.ahk b/Task/Catalan-numbers-Pascals-triangle/AutoHotkey/catalan-numbers-pascals-triangle.ahk index 4921c4ed98..67ce3c01c6 100644 --- a/Task/Catalan-numbers-Pascals-triangle/AutoHotkey/catalan-numbers-pascals-triangle.ahk +++ b/Task/Catalan-numbers-Pascals-triangle/AutoHotkey/catalan-numbers-pascals-triangle.ahk @@ -6,25 +6,25 @@ Array := [], Array[2,1] := Array[2,2] := 1 ; Array inititated and 2nd row of pas INI := 3 ; starts with calculating the 3rd row and as such the value Loop, 31 ; every odd row is taken for calculating catalan number as such to obtain 15 we need 2n+1 { - if ( A_index > 2 ) - { - Loop, % A_INDEX - { - old := ini-1, index := A_index, index_1 := A_index + 1 - Array[ini, index_1] := Array[old, index] + Array[old, index_1] - Array[ini, 1] := Array[ini, ini] := 1 - line .= Array[ini, A_index] " " - } - ;~ MsgBox % line ; gives rows of pascal's triangle - ; calculating every odd row starting from 1st so as to obtain catalan's numbers - if ( mod(ini,2) != 0) - { - StringSplit, res, line, %A_Space% - ans := res0//2, ans_1 := ans++ - result := result . res%ans_1% - res%ans% " " - } - line := - ini++ - } + if ( A_index > 2 ) + { + Loop, % A_INDEX + { + old := ini-1, index := A_index, index_1 := A_index + 1 + Array[ini, index_1] := Array[old, index] + Array[old, index_1] + Array[ini, 1] := Array[ini, ini] := 1 + line .= Array[ini, A_index] " " + } + ;~ MsgBox % line ; gives rows of pascal's triangle + ; calculating every odd row starting from 1st so as to obtain catalan's numbers + if ( mod(ini,2) != 0) + { + StringSplit, res, line, %A_Space% + ans := res0//2, ans_1 := ans++ + result := result . res%ans_1% - res%ans% " " + } + line := + ini++ + } } MsgBox % result diff --git a/Task/Catalan-numbers-Pascals-triangle/Batch-File/catalan-numbers-pascals-triangle.bat b/Task/Catalan-numbers-Pascals-triangle/Batch-File/catalan-numbers-pascals-triangle.bat index 707de0dc95..9c096844a1 100644 --- a/Task/Catalan-numbers-Pascals-triangle/Batch-File/catalan-numbers-pascals-triangle.bat +++ b/Task/Catalan-numbers-Pascals-triangle/Batch-File/catalan-numbers-pascals-triangle.bat @@ -8,15 +8,15 @@ for /L %%i in (1,1,%n%) do ( set /A ip=%%i+1 for /L %%j in (%%i,-1,1) do ( set /A jm=%%j-1 - set /A t.%%j=t.%%j+t.!jm! - ) - set /A t.!ip!=t.%%i + set /A t.%%j=t.%%j+t.!jm! + ) + set /A t.!ip!=t.%%i for /L %%j in (!ip!,-1,1) do ( set /A jm=%%j-1 - set /A t.%%j=t.%%j+t.!jm! - ) + set /A t.%%j=t.%%j+t.!jm! + ) set /A ci=t.!ip!-t.%%i - echo !ci! + echo !ci! ) ) pause diff --git a/Task/Catalan-numbers-Pascals-triangle/DuckDB/catalan-numbers-pascals-triangle-1.duckdb b/Task/Catalan-numbers-Pascals-triangle/DuckDB/catalan-numbers-pascals-triangle-1.duckdb new file mode 100644 index 0000000000..90833b9fbe --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/DuckDB/catalan-numbers-pascals-triangle-1.duckdb @@ -0,0 +1,20 @@ +# Compute nCr naively using UHUGEINT +# The caller should ensure 2r < n +create or replace function nCr_(n, r) as + (with recursive cte as + (SELECT 1::UHUGEINT as c, n as numerator, 1::UHUGEINT as m + UNION ALL + SELECT (c * numerator / m) as c, + (numerator - 1) as numerator, + (m + 1) as m + FROM cte + WHERE m <= r) + SELECT last(c order by m) + FROM cte +); + +create or replace function nCr(n,r) as ( + if( n - N2=N*(S+S), - D2=D*S, - K = N2 div D2 ; + N2=N*(S+S), + D2=D*S, + K = N2 div D2 ; mul(N,D,S,L)-> - N2=N*(S+L), - D2=D*L, - K = mul(N2,D2,S,L+1). - + N2=N*(S+L), + D2=D*L, + K = mul(N2,D2,S,L+1). + catl(Ans,16) -> Ans; catl(D,S)-> - C=mul(1,1,S,2), - catl([D|C],S+1). + C=mul(1,1,S,2), + catl([D|C],S+1). main()-> - Ans=catl(1,2). + Ans=catl(1,2). diff --git a/Task/Catalan-numbers-Pascals-triangle/Fortran/catalan-numbers-pascals-triangle.f b/Task/Catalan-numbers-Pascals-triangle/Fortran/catalan-numbers-pascals-triangle.f new file mode 100644 index 0000000000..aeb18b829c --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/Fortran/catalan-numbers-pascals-triangle.f @@ -0,0 +1,64 @@ + ! Catalan numbers/Pascal's triangle + ! + ! tested with Intel ifx (IFX) 2025.2.0 20250605 on Kubuntu 25.04 + ! GNU Fortran (Ubuntu 14.2.0-19ubuntu2) 14.2.0 on Kubuntu 25.04 + ! VSI Fortran x86-64 V8.6-001 on OpenVMS x86_64 V9.2-3 + ! Note that VMS requires switch $Fortran/ccdefault=LIST + ! otherwise 1st character of each output line is interpreted as + ! Carriage Control character. + ! U.B., July 2025 + + program calc_catalan + implicit none + + integer, parameter :: nMax=15 ! Number of catalan numbers to print + integer :: catalan ! result of calculation + integer :: i, j ! Loop indices + integer :: t(nMax+3) ! 1 line of pascal's triangle + + ! straight copy of the algorithm presented in the C++ solution + ! + ! Try to explain what we are doing: + ! + ! Pascal's Triangle + ! # 1: 1 + ! # 2: 1 2 1 C1 = 2-1 = 1 + ! # 3: 1 3 3 1 + ! # 4: 1 4 6 4 1 C2 = 6-4 = 2 + ! # 5: 1 5 10 10 5 1 + ! # 6: 1 6 15 20 15 6 1 C3 = 20 - 15 = 5 + ! # 7: 1 7 21 35 35 21 7 1 + ! # 8: 1 8 28 56 70 56 28 8 1 C4 = 70 - 56 = 14 + ! t1 2 3 4 5 ... + ! etc. Note for Cn we need even row #(2*n) up to index n+1. + ! and we dont need to store all values, just go from row to row. + t(1) = 0 + t(2) = 1 ! first odd row (i.e. row #1) will be t(2)+t(1) + + do i=2, nMax+1 ! to calculate C(1)... C(nMax) + ! get entries of next odd row (at index 2...i). + ! currently t has values of previous even row + do j = i, 2, -1 + t(j) = t(j) + t(j-1) + end do + ! Now t has values of next odd row. + + ! shift index by 1 so that soon "t" will carry values of next even row + t(i+1) = t(i) + + ! combine values of previously odd row to become values of even row + do j=i+1, 2, -1 + t(j) = t(j) + t(j-1) + end do + ! Now t has values 1...n+1 of 2n'th row of pascals triangle. + + ! Result: catalan number is center number - (left of center)number + ! e. g. for C4 its t(5)-t(4) = 70-56 = 14 + ! (remember i is 5 to calculate C4.) + catalan = t(i+1) - t(i) + + write (*, '(I0,x) ', ADVANCE='NO') catalan ! all in 1 line + end do + + write (*,*) ' ' ! Terminate output line + end program calc_catalan diff --git a/Task/Catalan-numbers-Pascals-triangle/FutureBasic/catalan-numbers-pascals-triangle.basic b/Task/Catalan-numbers-Pascals-triangle/FutureBasic/catalan-numbers-pascals-triangle.basic new file mode 100644 index 0000000000..f8d7a51702 --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/FutureBasic/catalan-numbers-pascals-triangle.basic @@ -0,0 +1,20 @@ + local fn CatalanNumbers( levels as int ) + int k, n + double num, den, cat + + printf @"1" + + for n = 2 to levels + num = 1 : den = 1 + for k = 2 to n + num *= ( n + k ) + den *= k + cat = num / den + next + printf @"%.f", cat + next +end fn + +fn CatalanNumbers( 30 ) + +HandleEvents diff --git a/Task/Catalan-numbers-Pascals-triangle/Julia/catalan-numbers-pascals-triangle.julia b/Task/Catalan-numbers-Pascals-triangle/Julia/catalan-numbers-pascals-triangle.jl similarity index 100% rename from Task/Catalan-numbers-Pascals-triangle/Julia/catalan-numbers-pascals-triangle.julia rename to Task/Catalan-numbers-Pascals-triangle/Julia/catalan-numbers-pascals-triangle.jl diff --git a/Task/Catalan-numbers-Pascals-triangle/Kotlin/catalan-numbers-pascals-triangle.kotlin b/Task/Catalan-numbers-Pascals-triangle/Kotlin/catalan-numbers-pascals-triangle.kts similarity index 100% rename from Task/Catalan-numbers-Pascals-triangle/Kotlin/catalan-numbers-pascals-triangle.kotlin rename to Task/Catalan-numbers-Pascals-triangle/Kotlin/catalan-numbers-pascals-triangle.kts diff --git a/Task/Catalan-numbers-Pascals-triangle/OCaml/catalan-numbers-pascals-triangle.ocaml b/Task/Catalan-numbers-Pascals-triangle/OCaml/catalan-numbers-pascals-triangle.ml similarity index 100% rename from Task/Catalan-numbers-Pascals-triangle/OCaml/catalan-numbers-pascals-triangle.ocaml rename to Task/Catalan-numbers-Pascals-triangle/OCaml/catalan-numbers-pascals-triangle.ml diff --git a/Task/Catalan-numbers-Pascals-triangle/Objeck/catalan-numbers-pascals-triangle.objeck b/Task/Catalan-numbers-Pascals-triangle/Objeck/catalan-numbers-pascals-triangle.objeck new file mode 100644 index 0000000000..37ecabb22c --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/Objeck/catalan-numbers-pascals-triangle.objeck @@ -0,0 +1,23 @@ +class Test { + function : Main(args : String[]) ~ Nil { + N := 15; + t := Int->New[N + 2]; + t[1] := 1; + + for(i := 1; i <= N; i++) { + + for(j := i; j > 1; j--){ + t[j] := t[j] + t[j - 1]; + }; + + t[i + 1] := t[i]; + + for(j := i + 1; j > 1; j--) { + t[j] := t[j] + t[j - 1]; + }; + + v := t[i + 1] - t[i]; + "{$v} "->Print(); + }; + } +} diff --git a/Task/Catalan-numbers-Pascals-triangle/PascalABC.NET/catalan-numbers-pascals-triangle.pas b/Task/Catalan-numbers-Pascals-triangle/PascalABC.NET/catalan-numbers-pascals-triangle.pas new file mode 100644 index 0000000000..f031c01feb --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/PascalABC.NET/catalan-numbers-pascals-triangle.pas @@ -0,0 +1,14 @@ +const + n = 15; + +begin + var t: array[0..n + 1] of integer; + t[1] := 1; + for var i := 1 to n do + begin + for var j := i downto 1 do t[j] += t[j - 1]; + t[i + 1] := t[i]; + for var j := i + 1 downto 1 do t[j] += t[j - 1]; + print(t[i + 1] - t[i]); + end; +end. diff --git a/Task/Catalan-numbers-Pascals-triangle/Phix/catalan-numbers-pascals-triangle-1.phix b/Task/Catalan-numbers-Pascals-triangle/Phix/catalan-numbers-pascals-triangle-1.phix index 636407e5ea..9df9e2a484 100644 --- a/Task/Catalan-numbers-Pascals-triangle/Phix/catalan-numbers-pascals-triangle-1.phix +++ b/Task/Catalan-numbers-Pascals-triangle/Phix/catalan-numbers-pascals-triangle-1.phix @@ -1,16 +1,12 @@ -(phixonline)--> - constant N = 15 -- accurate to 30, nan/inf for anything over 514 (gmp version is below). - sequence catalan = {}, -- (>=1 only) - p = repeat(1,N+1) - atom p1 - for i=1 to N do - p1 = p[1]*2 - catalan = append(catalan,p1-p[2]) - for j=1 to N-i+1 do - p1 += p[j+1] - p[j] = p1 - end for - -- ?p[1..N-i+1] - end for - ?catalan - - with javascript_semantics - include builtins\mpfr.e +with javascript_semantics +include builtins\mpfr.e - function catalanB(integer n) -- very very fast! - sequence catalan = mpz_inits(n), - p = mpz_inits(n+1,1) - mpz p1 = mpz_init(1) - if n=0 then return p1 end if - for i=1 to n do - mpz_mul_si(p1,p[1],2) - mpz_sub(catalan[i],p1,p[2]) - for j=1 to n-i+1 do - mpz_add(p1,p1,p[j+1]) - mpz_set(p[j],p1) - end for - end for - return catalan[n] - end function +function catalanB(integer n) -- very very fast! +sequence catalan = mpz_inits(n), + p = mpz_inits(n+1,1) +mpz p1 = mpz_init(1) + if n=0 then return p1 end if + for i=1 to n do + mpz_mul_si(p1,p[1],2) + mpz_sub(catalan[i],p1,p[2]) + for j=1 to n-i+1 do + mpz_add(p1,p1,p[j+1]) + mpz_set(p[j],p1) + end for + end for + return catalan[n] +end function - printf(1,"%d: %s\n",{100,shorten(mpz_get_str(catalanB(100)))}) - printf(1,"%d: %s\n",{250,shorten(mpz_get_str(catalanB(250)))}) - - with javascript_semantics - -- returns inf/-nan for n>85, and needs the rounding for n>=14, accurate to n=29 - function catalan1(integer n) - return floor(factorial(2*n)/(factorial(n+1)*factorial(n))+0.5) - end function +with javascript_semantics +-- returns inf/-nan for n>85, and needs the rounding for n>=14, accurate to n=29 +function catalan1(integer n) + return round(factorial(2*n)/(factorial(n+1)*factorial(n))) +end function - -- returns inf for n>519, accurate to n=30: - function catalan2(integer n) -- NB: very slow! - atom res = not n - n -= 1 - for i=0 to n do - res += catalan2(i)*catalan2(n-i) - end for - return res - end function +-- returns inf for n>519, accurate to n=30: +function catalan2(integer n) -- NB: very slow! +atom res = not n + n -= 1 + for i=0 to n do + res += catalan2(i)*catalan2(n-i) + end for + return res +end function - -- returns inf for n>514, accurate to n=30: - function catalan3(integer n) - if n=0 then return 1 end if - return 2*(2*n-1)/(1+n)*catalan3(n-1) - end function +-- returns inf for n>514, accurate to n=30: +function catalan3(integer n) + if n=0 then return 1 end if + return 2*(2*n-1)/(1+n)*catalan3(n-1) +end function - sequence res = repeat(repeat(0,4),16), - times = repeat(0,3) - for t=1 to 4 do - atom t0 = time() - for i=0 to 15 do - switch t do - case 1: res[i+1][2] = catalan1(i) - case 2: res[i+1][3] = catalan2(i) - case 3: res[i+1][4] = catalan3(i) - case 4: res[i+1][1] = i; printf(1,"%2d: %10d %10d %10d\n",res[i+1]) - end switch - end for - if t=4 then exit end if - times[t] = elapsed(time()-t0) - end for - printf(1,"times:%8s %10s %10s\n",times) - - with javascript_semantics - include builtins\mpfr.e +with javascript_semantics +include builtins\mpfr.e - sequence c2cache = {} +sequence c2cache = {} - function catalan2m(integer n) -- very fast! - object r -- result (a [cached/shared] mpz) - -- (nb: modifying result will mess up cache) - if n<=0 then return mpz_init(1) end if - if n<=length(c2cache) then - r = c2cache[n] - if r!=0 then return r end if - else - c2cache &= repeat(0,n-length(c2cache)) - end if - r = mpz_init(0) - mpz t = mpz_init() - for i=0 to n-1 do - mpz_mul(t,catalan2m(i),catalan2m(n-1-i)) - mpz_add(r,r,t) - end for - t = mpz_free(t) - c2cache[n] = r - return r - end function +function catalan2m(integer n) -- very fast! +object r -- result (a [cached/shared] mpz) + -- (nb: modifying result will mess up cache) + if n<=0 then return mpz_init(1) end if + if n<=length(c2cache) then + r = c2cache[n] + if r!=0 then return r end if + else + c2cache &= repeat(0,n-length(c2cache)) + end if + r = mpz_init(0) + mpz t = mpz_init() + for i=0 to n-1 do + mpz_mul(t,catalan2m(i),catalan2m(n-1-i)) + mpz_add(r,r,t) + end for + t = mpz_free(t) + c2cache[n] = r + return r +end function - sequence s = {} - for i=0 to 15 do s = append(s,mpz_get_str(catalan2m(i))) end for - printf(1,"0..15: %s\n",join(s,",")) - printf(1,"100: %s\n",{mpz_get_str(catalan2m(100))}) - int32) is native($glutlib) {*} + +# OpenGL Bindings +constant $gllib = 'GL'; +sub glClear(int32) is native($gllib) {*} +sub glClearColor(num32, num32, num32, num32) is native($gllib) {*} +sub glClearDepth(num64) is native($gllib) {*} +sub glEnable(int32) is native($gllib) {*} +sub glDisable(int32) is native($gllib) {*} +sub glViewport(int32, int32, int32, int32) is native($gllib) {*} +sub glMatrixMode(int32) is native($gllib) {*} +sub glLoadIdentity() is native($gllib) {*} +sub glBegin(int32) is native($gllib) {*} +sub glEnd() is native($gllib) {*} +sub glVertex3f(num32, num32, num32) is native($gllib) {*} +sub glVertex3fv(CArray[num32]) is native($gllib) {*} +sub glNormal3fv(CArray[num32]) is native($gllib) {*} +sub glColor3f(num32, num32, num32) is native($gllib) {*} +sub glPushAttrib(int32) is native($gllib) {*} +sub glPopAttrib() is native($gllib) {*} +sub glMaterialfv(int32, int32, CArray[num32]) is native($gllib) {*} +sub glLightfv(int32, int32, CArray[num32]) is native($gllib) {*} +sub glPolygonMode(int32, int32) is native($gllib) {*} +sub glFrustum(num64, num64, num64, num64, num64, num64) is native($gllib) {*} +sub glTranslatef(num32, num32, num32) is native($gllib) {*} +sub glRotatef(num32, num32, num32, num32) is native($gllib) {*} +sub glScalef(num32, num32, num32) is native($gllib) {*} + +# Vector Math +class Vec3 { has num32 ($.x, $.y, $.z); + method new(num32 $x = 0e0, num32 $y = 0e0, num32 $z = 0e0) { + self.bless(:$x, :$y, :$z) + } + method copy() { Vec3.new: $!x, $!y, $!z } + method add(Vec3 $v) { Vec3.new: $!x + $v.x, $!y + $v.y, $!z + $v.z } + method sub(Vec3 $v) { Vec3.new: $!x - $v.x, $!y - $v.y, $!z - $v.z } + method mul(num32 $s) { Vec3.new: $!x * $s, $!y * $s, $!z * $s } + method dot(Vec3 $v) { $!x * $v.x + $!y * $v.y + $!z * $v.z } + method len() { sqrt(self.dot(self)).Num } + method normalize() { do given self { .len > 0 ?? .mul(1e0/.len) !! .copy } } + method cross(Vec3 $v) { + Vec3.new: $!y*$v.z - $!z*$v.y, $!z*$v.x - $!x*$v.z, $!x*$v.y - $!y*$v.x + } + method to-array() { CArray[num32].new: $!x, $!y, $!z } +} + +# Mesh Data Structures +class Vertex { + has (@.edges, @.faces) is rw; + has Vec3 ($.pos, $.newpos) is rw; + method new(Vec3 :$pos!) { self.bless(:$pos, newpos => $pos.copy) } +} + +class Face { + has @.verts is rw; + has Int $.fvert is rw; +} + +class Edge { has Int ($.v0, $.v1, $.f0, $.f1, $.evert) is rw } + +class Mesh { has (@.vertices, @.normals, @.faces); + method add-vertex(Vec3 $v) { @!vertices.push($v) } + method add-normal(Vec3 $n) { @!normals.push($n) } + method add-face(@verts) { @!faces.push: Face.new(:verts(@verts),:fvert(-1)) } + + method compute-normals() { + @!normals = Vec3.new xx @!vertices.elems; + for @!faces -> $face { + for ^$face.verts.elems -> \j { + my $v0=@!vertices[$face.verts[j]]; + my $v1=@!vertices[$face.verts[(j+1) % +$face.verts]]; + my $v2=@!vertices[$face.verts[(j+ +$face.verts-1) % +$face.verts]]; + given $v1.sub($v0).cross($v2.sub($v0)) { + @!normals[$face.verts[j]] .= add: $_ + } + } + } + $_ .= normalize for @!normals + } +} + +# Subdivision +class SubdivMesh { has (@.verts, @.faces, @.edges); + method find-edge(Int $v0, Int $v1) { + for @!verts[$v0].edges -> $ei { + my $e = @!edges[$ei]; + return $ei if $e.v0==$v0 && $e.v1==$v1 or $e.v0==$v1 && $e.v1==$v0 + } + return -1; + } + + method update-links() { + for @!verts { ( .faces, .edges ) = | [] xx 2 } + @!edges = []; + for @!faces.kv -> $fi, $face { + for ^$face.verts.elems -> $j { + @!verts[ my $v0 = $face.verts[$j] ].faces.push: $fi; + my $v1 = $face.verts[ ($j+1) % $face.verts.elems ]; + if ( my $ei = self.find-edge($v0, $v1) ) == -1 { + @!edges.push: Edge.new( :v0($v0), :v1($v1), + :f0($fi), :f1(-1), :evert(-1)); + given $ei=+@!edges-1 { @!verts[$_].edges.push($ei) for $v0,$v1 } + } else { + @!edges[$ei].f1 = $fi + } + } + } + } + + method subdivide() { + my ($V, $F, $E) = [ @!verts, @!faces, @!edges].map: *.elems; + for @!faces -> $face { # Create face vertices + my $p = Vec3.new; + for $face.verts -> $vi { $p .= add: @!verts[$vi].pos } + @!verts.push: Vertex.new(pos => $p.mul(1e0 / $face.verts.elems)); + $face.fvert = @!verts.elems - 1 + } + for @!edges -> $edge { # Create edge vertices + my $p = Vec3.new; + $p .= add(@!verts[$edge.v0].pos); + $p .= add(@!verts[$edge.v1].pos); + $p .= add(@!verts[@!faces[$edge.f0].fvert].pos); + $p .= add(@!verts[@!faces[$edge.f1].fvert].pos); + @!verts.push: Vertex.new(pos => $p.mul(0.25e0)); + $edge.evert = @!verts.elems - 1 + } + for ^$V -> $vi { # Update original vertices + my $n = (my $v = @!verts[$vi]).faces.elems; + my ($newp,$p1) = $v.pos.mul(($n-2e0)/$n), Vec3.new; + + for $v.faces -> $fi { $p1 .= add(@!verts[@!faces[$fi].fvert].pos) } + $newp .= add($p1.mul(1e0 / ($n * $n))); + my $p2 = Vec3.new; + for $v.edges -> $ei { + given @!edges[$ei] { $p2 .= add(@!verts[.v0==$vi??.v1!!.v0].pos) } + } + $v.newpos = $newp .= add($p2.mul(1e0 / ($n * $n))) + } + for ^$V -> $vi { @!verts[$vi].pos = @!verts[$vi].newpos.copy } + + @!faces = gather for @!faces -> $face { # Create new faces + for ^$face.verts.elems -> $j { + my $v0 = $face.verts[($j-1+$face.verts.elems) % $face.verts.elems]; + my $v = $face.verts[$j]; + my $v1 = $face.verts[($j + 1) % $face.verts.elems]; + my $e0 = @!edges[self.find-edge($v0, $v)]; + my $e1 = @!edges[self.find-edge($v, $v1)]; + take Face.new(:verts($e0.evert,$v,$e1.evert,$face.fvert),:fvert(-1)) + } + } + self.update-links(); + } + + method to-mesh() { + my $mesh = Mesh.new; + for @!verts -> $v { $mesh.add-vertex($v.pos) } + for @!faces -> $face { $mesh.add-face($face.verts) } + $mesh.compute-normals; + return $mesh + } +} + +sub load-cube() { # Load Cube OBJ + my $mesh = Mesh.new; + for (-1,-1,1,1,-1,1,-1,1,1,1,1,1,-1,1,-1,1,1,-1,-1,-1,-1,1,-1,-1).rotor(3) { + $mesh.add-vertex(Vec3.new: | ($_ X* 0.5e0)) # 8 Corner vertices + } + for [0,1,3,2], [2,3,5,4], [4,5,7,6], [6,7,1,0], [1,7,5,3], [6,0,2,4] { + $mesh.add-face: $_ # 6 Faces + } + $mesh.compute-normals; + return $mesh +} + +sub create-subdivision-levels(Mesh $base, Int $levels) { + my @meshes = $base; + my $sd = SubdivMesh.new; + + for $base.vertices -> $v { $sd.verts.push(Vertex.new(pos => $v)) } + for $base.faces -> $face { + $sd.faces.push(Face.new(verts => $face.verts, fvert => -1)) + } + $sd.update-links; + return @meshes.append: ^($levels - 1) .map: { + $sd.subdivide; + $sd.to-mesh + } +} + +sub render-mesh(Mesh $mesh) { + for $mesh.faces -> $face { + glBegin(GL_POLYGON); + for $face.verts -> $vi { + glNormal3fv($mesh.normals[$vi].to-array); + glVertex3fv($mesh.vertices[$vi].to-array); + } + glEnd + } +} + +sub draw-xyz() { # Draw XYZ Axis Lines + glPushAttrib(GL_LIGHTING_BIT +| GL_ENABLE_BIT); + glDisable(GL_LIGHTING); + glBegin(GL_LINES); + for (1e0,0e0,0e0), (0e0,1e0,0e0), (0e0,0e0,1e0) -> @color { # XYZ <-> RGB + glColor3f(|@color); + glVertex3f(0e0, 0e0, 0e0); + glVertex3f(|@color) + } + glEnd; + glPopAttrib +} + +# Global State +my ( $auto-phase, $auto-dir, $auto-level, $cur-level, $y-rot, $x-rot ) = + 0, 1, 0, 0, 0e0, 0e0 ; +my ($wireframe, @meshes) = False; + +sub display() { + glClear(GL_COLOR_BUFFER_BIT +| GL_DEPTH_BUFFER_BIT); + + # Setup projection + glMatrixMode(GL_PROJECTION); + glLoadIdentity; + my ( $fovy, $near, $far, $aspect ) = + 60e0, 0.1e0, 1000e0, WIN-WIDTH.Num / WIN-HEIGHT.Num ; + my $top = $near * tan($fovy * pi / 360e0); + glFrustum(-$top * $aspect, $top * $aspect, -$top, $top, $near, 1000e0); + + # Setup modelview + glMatrixMode(GL_MODELVIEW); + glLoadIdentity; + + # Headlamp Lighting + glEnable(GL_LIGHTING); + glEnable(GL_LIGHT0); + glLightfv(GL_LIGHT0, GL_DIFFUSE, CArray[num32].new(1e0, 1e0, 1e0, 1e0)); + glLightfv(GL_LIGHT0, GL_POSITION, CArray[num32].new(0e0, 0e0, 0e0, 1e0)); + + # Transformations + glTranslatef(0e0, 0e0, -5e0); # Move back from camera + glRotatef($x-rot, 1e0, 0e0, 0e0); # Rotate around X + glRotatef($y-rot, 0e0, 1e0, 0e0); # Rotate around Y + + # Scale Object + glScalef(OBJ-SCALE, OBJ-SCALE, OBJ-SCALE); + + # Render mesh + glPushAttrib(GL_LIGHTING_BIT +| GL_POLYGON_BIT); + glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, CArray[num32].new(1e0, 1e0, 1e0, 1e0)); + + if $wireframe { + glDisable(GL_LIGHTING); + glColor3f(0e0, 1e0, 0e0); + glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) + } + render-mesh(@meshes[$cur-level]); + glPopAttrib; + draw-xyz(); + glutSwapBuffers; +} + +sub reshape(int32 $w, int32 $h) { + glViewport(0, 0, $w, $h); + glClearDepth(1e0); + glClearColor(0e0, 0e0, 0e0, 0e0); + glEnable(GL_DEPTH_TEST) +} + +sub keyboard(uint8 $key, int32 $x, int32 $y) { + given $key.chr { when 'q' | 'Q' | "\x1b" { exit(0) } } # q, Q, or Esc +} + +sub auto-step() { + return unless @meshes.Bool; + ($wireframe, $cur-level) = ($auto-phase == 0), $auto-level; + + if $auto-dir > 0 { + $auto-level >= @meshes.elems - 1 ?? ( $auto-dir = -1 ) !! $auto-level++ + } else { + $auto-level <= 0 ?? (($auto-phase,$auto-dir) = ($auto-phase + 1) % 2, 1) + !! $auto-level-- + } +} + +sub idle() { + state ($last-ms, $last-auto-ms) = -1, -1; + my $now = glutGet(GLUT_ELAPSED_TIME); + if $last-ms < 0 { ($last-ms, $last-auto-ms) = $now xx 2 } + + given my $dt = ($now - $last-ms) / 1000e0 { + $last-ms = $now; + $y-rot += 35e0 * $dt; + $x-rot = 15e0 * sin($now * X-ROT-FREQ); + } + if ($now - $last-auto-ms) >= 500 { + auto-step(); + $last-auto-ms = $now; + } + glutPostRedisplay +} + +# Main +glutInit(CArray[uint32].new, CArray[Str].new); +glutInitDisplayMode(0x0000 +| 0x0002 +| 0x0010); +glutInitWindowSize(WIN-WIDTH, WIN-HEIGHT); +glutCreateWindow("Catmull-Clark (Raku)"); +glutReshapeFunc(&reshape); +glutDisplayFunc(&display); +glutKeyboardFunc(&keyboard); +glutIdleFunc(&idle); + +say "Generating meshes..."; +@meshes = create-subdivision-levels(load-cube(), 5); +say "Starting loop.\nPress , or to quit."; + +glutMainLoop; diff --git a/Task/Catmull-Clark-subdivision-surface/Rust/catmull-clark-subdivision-surface.rust b/Task/Catmull-Clark-subdivision-surface/Rust/catmull-clark-subdivision-surface.rs similarity index 100% rename from Task/Catmull-Clark-subdivision-surface/Rust/catmull-clark-subdivision-surface.rust rename to Task/Catmull-Clark-subdivision-surface/Rust/catmull-clark-subdivision-surface.rs diff --git a/Task/Chaocipher/00-TASK.txt b/Task/Chaocipher/00-TASK.txt index 8c2723b21f..d328256b71 100644 --- a/Task/Chaocipher/00-TASK.txt +++ b/Task/Chaocipher/00-TASK.txt @@ -1,7 +1,7 @@ ;Description: The [[wp:Chaocipher|Chaocipher]] was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010. -The algorithm is described in [http://www.mountainvistasoft.com/chaocipher/ActualChaocipher/Chaocipher-Revealed-Algorithm.pdf this paper] by M.Rubin in 2010 and there is a C# implementation [https://www.c-sharpcorner.com/UploadFile/b942f9/implementing-the-chaocipher-in-C-Sharp/ here]. +The algorithm is described in [http://www.chaocipher.com/ActualChaocipher/Chaocipher-Revealed-Algorithm.pdf this paper] by M.Rubin in 2010 and there is a C# implementation [https://www.c-sharpcorner.com/UploadFile/b942f9/implementing-the-chaocipher-in-C-Sharp/ here]. ;Task: diff --git a/Task/Chaocipher/ALGOL-68/chaocipher.alg b/Task/Chaocipher/ALGOL-68/chaocipher.alg new file mode 100644 index 0000000000..ceaedc0ca8 --- /dev/null +++ b/Task/Chaocipher/ALGOL-68/chaocipher.alg @@ -0,0 +1,75 @@ +BEGIN # Chaocipher, translated from the Kotlin with permutations as in Ada # + + STRING lalphabet = "HXUCZVAMDSLKPEFJRIGTWOBNYQ"; + STRING ralphabet = "PTLNBQDEOYSFAVZKGJRIHWXUMC"; + + PROC chaocipher = ( STRING text in, BOOL encrypt, show steps )STRING: + BEGIN + STRING left := lalphabet[ AT 1 ]; + STRING right := ralphabet[ AT 1 ]; + STRING text = text in [ AT 1 ]; + OP LENGTH = ( STRING s )INT: UPB s - LWB s + 1; + [ 1 : LENGTH text ]CHAR e text; + [ 1 : LENGTH left ]CHAR temp; + + FOR i TO UPB text DO + IF show steps THEN print( ( left, " ", right, newline ) ) FI; + INT index; + IF encrypt THEN + VOID( char in string( text[ i ], index, right ) ); + e text[ i ] := IF index >= LWB left AND index <= UPB left + THEN left[ index ] + ELSE "?" + FI + ELSE + VOID( char in string( text[ i ], index, left ) ); + e text[ i ] := IF index >= LWB right AND index <= UPB right + THEN right[ index ] + ELSE "?" + FI + FI; + IF index > 1 THEN + CHAR store; + + # the permutations are performed using array slices # + # rather than explicit loops # + + # permute left # + + INT offset = 26 - index; + temp[ 1 : offset + 1 ] := left[ index : index + offset ]; + temp[ offset + 2 : 26 ] := left[ 1 : index - 1 ]; + store := temp[ 2 ]; + + temp[ 2 : 13 ] := temp[ 3 : 14 ]; + temp[ 14 ] := store; + left := temp; + + # permute right # + + temp[ 1 : offset + 1 ] := right[ index : index + offset ]; + temp[ offset + 2 : 26 ] := right[ 1 : index - 1 ]; + store := temp[ 1 ]; + + temp[ 1 : 25 ] := temp[ 2 : 26 ]; + temp[ 26 ] := store; + store := temp[ 3 ]; + + temp[ 3 : 13 ] := temp[ 4 : 14 ]; + temp[ 14 ] := store; + right := temp + FI + OD; + e text + END # chaocipher # ; + + STRING plaintext = "WELLDONEISBETTERTHANWELLSAID"; + print( ( "The original plaintext is : ", plaintext, newline ) ); + print( ( newline, "The left and right alphabets after each permutation" ) ); + print( ( " during encryption are :", newline, newline ) ); + STRING ciphertext = chaocipher( plaintext, TRUE, TRUE ); + print( ( newline, "The ciphertext is : ", ciphertext, newline ) ); + STRING plaintext2 = chaocipher( ciphertext, FALSE, FALSE ); + print( ( newline, "The recovered plaintext is : ", plaintext2 ) ); + print( ( " ", IF plaintext = plaintext2 THEN "" ELSE "NOT " FI, "as expected", newline ) ) +END diff --git a/Task/Chaocipher/Ada/chaocipher.ada b/Task/Chaocipher/Ada/chaocipher.adb similarity index 100% rename from Task/Chaocipher/Ada/chaocipher.ada rename to Task/Chaocipher/Ada/chaocipher.adb diff --git a/Task/Chaocipher/Crystal/chaocipher.cr b/Task/Chaocipher/Crystal/chaocipher.cr new file mode 100644 index 0000000000..452e1edf99 --- /dev/null +++ b/Task/Chaocipher/Crystal/chaocipher.cr @@ -0,0 +1,40 @@ +enum Chaoperation + Encode + Decode +end + +class Array + # useful method to work on parts of the array + def slice (start, length) + start = size - start if start < 0 + raise "Out of bounds" unless start >= 0 && length >= 0 && start + length <= size + Slice.new(to_unsafe + start, length) + end +end + +def chaocipher (message : String, left : String, right : String, + op : Chaoperation = Chaoperation::Encode) + ct = left.chars + pt = right.chars + String.build do |s| + message.each_char do |ch| + idx = (op == Chaoperation::Encode ? pt : ct).index! ch + s << (op == Chaoperation::Encode ? ct : pt)[idx] + # permute left + ct.rotate! idx + ct.slice(1, 13).rotate! 1 + # permute right + pt.rotate! idx+1 + pt.slice(2, 12).rotate! 1 + end + end +end + +left = "HXUCZVAMDSLKPEFJRIGTWOBNYQ" +right = "PTLNBQDEOYSFAVZKGJRIHWXUMC" +message = "WELLDONEISBETTERTHANWELLSAID" + +encoded = chaocipher(message, left, right) +decoded = chaocipher(encoded, left, right, Chaoperation::Decode) + +print message, " -> ", encoded, " -> ", decoded, "\n" diff --git a/Task/Chaocipher/Delphi/chaocipher.delphi b/Task/Chaocipher/Delphi/chaocipher.pas similarity index 100% rename from Task/Chaocipher/Delphi/chaocipher.delphi rename to Task/Chaocipher/Delphi/chaocipher.pas diff --git a/Task/Chaocipher/EMal/chaocipher.emal b/Task/Chaocipher/EMal/chaocipher.emal index 5409bcda5d..968427b1f1 100644 --- a/Task/Chaocipher/EMal/chaocipher.emal +++ b/Task/Chaocipher/EMal/chaocipher.emal @@ -3,49 +3,49 @@ enum int ENCRYPT, DECRYPT end type Chaocipher -text L_ALPHABET = "HXUCZVAMDSLKPEFJRIGTWOBNYQ" -text R_ALPHABET = "PTLNBQDEOYSFAVZKGJRIHWXUMC" -fun exec = text by text value, Chaocipher:Mode mode, logic showSteps +text L_ALPHABET ← "HXUCZVAMDSLKPEFJRIGTWOBNYQ" +text R_ALPHABET ← "PTLNBQDEOYSFAVZKGJRIHWXUMC" +fun exec ← text by text value, Chaocipher:Mode mode, logic showSteps ^|since texts are mutable, we can operate directly on them without the need of Lists|^ - text left = *L_ALPHABET # by using the valueOf operator we are sure that the string is copied - text right = *R_ALPHABET - text eText = text(" ", value.length) - text temp = text(" ", 26) - for int i = 0; i < value.length; ++i + text left ← *L_ALPHABET # by using the valueOf operator we are sure that the string is copied + text right ← *R_ALPHABET + text eText ← text(" ", value.length) + text temp ← text(" ", 26) + for int i ← 0; i < value.length; ++i if showSteps do writeLine(left + " " + right) end - int index = 0 - if mode == Chaocipher:Mode.ENCRYPT - index = right.find(value[i]) - eText[i] = left[index] + int index ← 0 + if mode æ Chaocipher:Mode.ENCRYPT + index ← right.find(value[i]) + eText[i] ← left[index] else - index = left.find(value[i]) - eText[i] = right[index] + index ← left.find(value[i]) + eText[i] ← right[index] end - if i == value.length - 1 do break end + if i æ value.length - 1 do break end # permute left - for int j = index; j < 26; ++j do temp[j - index] = left[j] end - for int j = 0; j < index; ++j do temp[26 - index + j] = left[j] end - var store = temp[1] - for int j = 2; j < 14; ++j do temp[j - 1] = temp[j] end - temp[13] = store - left = *temp + for int j ← index; j < 26; ++j do temp[j - index] ← left[j] end + for int j ← 0; j < index; ++j do temp[26 - index + j] ← left[j] end + var store ← temp[1] + for int j ← 2; j < 14; ++j do temp[j - 1] ← temp[j] end + temp[13] ← store + left ← *temp # permute right - for int j = index; j < 26; ++j do temp[j - index] = right[j] end - for int j = 0; j < index; ++j do temp[26 - index + j] = right[j] end - store = temp[0] - for int j = 1; j < 26; ++j do temp[j - 1] = temp[j] end - temp[25] = store - store = temp[2] - for int j = 3; j < 14; ++j do temp[j - 1] = temp[j] end - temp[13] = store - right = *temp + for int j ← index; j < 26; ++j do temp[j - index] ← right[j] end + for int j ← 0; j < index; ++j do temp[26 - index + j] ← right[j] end + store ← temp[0] + for int j ← 1; j < 26; ++j do temp[j - 1] ← temp[j] end + temp[25] ← store + store ← temp[2] + for int j ← 3; j < 14; ++j do temp[j - 1] ← temp[j] end + temp[13] ← store + right ← *temp end return eText end -var plainText = "WELLDONEISBETTERTHANWELLSAID" -writeLine("The original plaintext is : " + plainText) -writeLine(EOL + "The left and right alphabets after each permutation during encryption are :" + EOL) -var cipherText = exec(plainText, Chaocipher:Mode.ENCRYPT, true) -writeLine(EOL + "The ciphertext is : " + cipherText) -var plainText2 = exec(cipherText, Chaocipher:Mode.DECRYPT, false) -writeLine(EOL + "The recovered plaintext is : " + plainText2) +var plainText ← "WELLDONEISBETTERTHANWELLSAID" +writeLine("The original plaintext is : ", plainText) +writeLine(EOL, "The left and right alphabets after each permutation during encryption are :", EOL) +var cipherText ← exec(plainText, Chaocipher:Mode.ENCRYPT, true) +writeLine(EOL, "The ciphertext is : ", cipherText) +var plainText2 ← exec(cipherText, Chaocipher:Mode.DECRYPT, false) +writeLine(EOL, "The recovered plaintext is : ", plainText2) diff --git a/Task/Chaocipher/EasyLang/chaocipher.easy b/Task/Chaocipher/EasyLang/chaocipher.easy index f748565f29..f2eb029db7 100644 --- a/Task/Chaocipher/EasyLang/chaocipher.easy +++ b/Task/Chaocipher/EasyLang/chaocipher.easy @@ -1,10 +1,8 @@ -proc index c$ . a$[] ind . +func index a$[] c$ . for ind = 1 to len a$[] - if a$[ind] = c$ - return - . + if a$[ind] = c$ : return ind . - ind = 0 + return 0 . left$ = "HXUCZVAMDSLKPEFJRIGTWOBNYQ" right$ = "PTLNBQDEOYSFAVZKGJRIHWXUMC" @@ -14,15 +12,12 @@ func$ chao txt$ mode . right$[] = strchars right$ len tmp$[] 26 for c$ in strchars txt$ - # print strjoin left$[] & " " & strjoin right$[] if mode = 1 - index c$ right$[] ind - if ind = 0 - return "" - . + ind = index right$[] c$ + if ind = 0 : return "" r$ &= left$[ind] else - index c$ left$[] ind + ind = index left$[] c$ if ind = 0 print c$ return "" diff --git a/Task/Chaocipher/Forth/chaocipher.fth b/Task/Chaocipher/Forth/chaocipher.fth new file mode 100644 index 0000000000..630e902613 --- /dev/null +++ b/Task/Chaocipher/Forth/chaocipher.fth @@ -0,0 +1,77 @@ + \ triple words +: 3drop drop drop drop ; ( n1 n2 n3 ---) +: 3dup >r over over r@ rot rot r> ; ( n1 n2 n3 -- n1 n2 n3 n1 n2 n3) + \ ASCIIZ string words +: zstring create chars allot ; ( a1 -- a1 n1) +: zcount dup begin dup c@ while char+ repeat over - ; +: zplace over chars over + >r swap cmove 0 r> c! ; +: +zplace zcount chars + zplace ; ( a1 n1 a2 --) + \ find character in string +: where? ( c a1 n1 -- n2) + 0 ?do over over i chars + c@ = if drop i negate leave then loop nip negate ; + +64 constant /str \ size of input/output string +27 constant /alpha \ size of alphabet + +/str zstring {i} \ input string +/str zstring {o} \ output string + +/alpha zstring l \ left alphabet +/alpha zstring r \ right alphabet +/alpha zstring t \ temporary alphabet + +: [] chars + ; ( a n -- a+n) +: .tab 9 emit ; ( --) +: .list cr .tab zcount type cr ; ( a --) + +: PermuteLeft ( index --) + 26 over ?do t over negate i + [] l i [] c@ swap c! loop + dup 0 ?do t over negate 26 i + + [] l i [] c@ swap c! loop drop + t char+ c@ >r t 2 [] dup char- 12 cmove r> t 13 [] c! t zcount l zplace +; + +: PermuteRight ( index --) + 26 over ?do t over negate i + [] r i [] c@ swap c! loop + dup 0 ?do t over negate 26 i + + [] r i [] c@ swap c! loop drop + t c@ >r t char+ dup char- 25 cmove r> t 25 [] c! + t 2 [] c@ >r t 3 [] dup char- 11 cmove r> t 13 [] c! t zcount r zplace +; + +: Encrypt ( input output index1 -- index2) + >r swap r@ [] c@ r /alpha where? dup 0< abort" Corrupt right alphabet" + l over [] c@ rot r> [] c! +; + +: Decrypt ( input output index1 -- index2) + >r swap r@ [] c@ l /alpha where? dup 0< abort" Corrupt left alphabet" + r over [] c@ rot r> [] c! +; + +: chao ( i o xt f --) + s" HXUCZVAMDSLKPEFJRIGTWOBNYQ" l zplace + s" PTLNBQDEOYSFAVZKGJRIHWXUMC" r zplace + t /alpha erase >r \ erase temporary string + ( i o xt R: f) + r@ if cr ." The left and right alphabets after each permutation:" cr then + >r over r> swap zcount 1- nip >r ( i o xt R: f len) + + 0 begin ( i o xt 0 R: f len) + r> r@ if l zcount type 2 spaces r zcount type cr then >r + >r 3dup r@ swap execute r> dup r@ < + while ( i o xt 0 R: f len) + >r dup PermuteLeft PermuteRight r> 1+ + repeat rdrop rdrop drop drop 3drop +; + +: main + s" WELLDONEISBETTERTHANWELLSAID" {i} zplace + {o} /str erase \ initialize output string + + ." The original plaintext is :" {i} .list + {i} {o} ['] Encrypt true chao + cr ." The ciphertext is :" {o} .list + {o} {i} ['] Decrypt false chao + cr ." The recovered plaintext is :" {i} .list +; + +main diff --git a/Task/Chaocipher/Fortran/chaocipher.f b/Task/Chaocipher/Fortran/chaocipher.f new file mode 100644 index 0000000000..ef2f081da9 --- /dev/null +++ b/Task/Chaocipher/Fortran/chaocipher.f @@ -0,0 +1,190 @@ +! +!This program implements the **Chaocipher encryption algorithm** in FORTRAN, extended to handle all printable ASCII characters (32-127). +! The Chaocipher is a polyalphabetic cipher invented by John F. Byrne in 1918, which dynamically permutes two alphabets after +! processing each character, making it highly secure and resistant to cryptanalysis. +! +!#### Key Features: +!1. **Initialization**: +! - Two alphabets (`left` and `right`) are initialized with shuffled ASCII characters (32-127). +! - The `plaintext` is set to "WELLDONEISBETTERTHANWELLSAID". +! +!2. **Enciphering**: +! - For each character in the plaintext: +! - Locate the character in the `right` alphabet. +! - Find the corresponding ciphertext character in the `left` alphabet. +! - Permute both alphabets based on the Chaocipher rules: +! - The `left` alphabet is rotated to bring the ciphertext character to the top, and a specific character is moved to a new position. +! - The `right` alphabet is similarly rotated, with an additional rotation step. +! +!3. **Deciphering**: +! - The ciphertext is decrypted back into plaintext using the reverse process: +! - Locate the ciphertext character in the `left` alphabet. +! - Find the corresponding plaintext character in the `right` alphabet. +! - Permute both alphabets identically as in enciphering. +! +!4. **Verification**: +! - After enciphering and deciphering, the program compares the original plaintext with the decrypted text to ensure correctness. +! +!#### Output: +!The program prints: +!- Initial left and right alphabets. +!- Enciphered ciphertext. +!- Deciphered plaintext. +!- A success message if decryption matches the original plaintext. +! +!#### Example Execution: +!For input plaintext "WELLDONEISBETTERTHANWELLSAID", the program outputs: +!- Ciphertext: `OAHQHCNYNXTSZJRRHJBYHQKSOUJY` +!- Decrypted Text: `WELLDONEISBETTERTHANWELLSAID` +!- Verification: "Decryption successful: plaintext matches decrypted text." +! +!This implementation demonstrates both encryption and decryption processes while adhering to Chaocipher's dynamic permutation rules, +!extended for modern ASCII characters. +! +! +PROGRAM Chaocipher + IMPLICIT NONE + CHARACTER(LEN=96) :: left, right, left_orig, right_orig + CHARACTER(LEN=1000) :: plaintext, ciphertext, decrypted + INTEGER :: i, len, ascii_start + LOGICAL :: trace + + ! Initialize alphabets and input + CALL initialize_alphabets(left, right) + left_orig = left + right_orig = right + plaintext = 'Well, when I was in Egypt, I had a conversation with the Sphinx! She taught me how to sew.' + ciphertext = '' + decrypted = '' + trace = .FALSE. + ascii_start = 32 ! ASCII start at space character + + len = LEN_TRIM(plaintext) + + PRINT *, 'Initial Left: ', left + PRINT *, 'Initial Right:', right + PRINT *, 'Plaintext: ', TRIM(plaintext) + + ! Encipher + DO i = 1, len + CALL encipher(plaintext(i:i), ciphertext(i:i), left, right, ascii_start) + IF (trace) THEN + PRINT *, 'Step ', i + PRINT *, 'Left: ', left + PRINT *, 'Right: ', right + END IF + END DO + + PRINT *, 'Ciphertext: ', TRIM(ciphertext) + + ! Reset alphabets for deciphering + left = left_orig + right = right_orig + + ! Decipher + DO i = 1, len + CALL decipher(ciphertext(i:i), decrypted(i:i), left, right, ascii_start) + END DO + + PRINT *, 'Decrypted: ', TRIM(decrypted) + + ! Check for correctness + IF (plaintext == decrypted) THEN + PRINT *, 'Decryption successful: plaintext matches decrypted text' + ELSE + PRINT *, 'Decryption failed: plaintext does not match decrypted text' + END IF + +CONTAINS + + SUBROUTINE initialize_alphabets(left, right) + CHARACTER(LEN=96), INTENT(OUT) :: left, right + INTEGER :: i, j + CHARACTER :: temp + REAL :: r + + ! Initialize alphabets with ASCII characters 32-127 + DO i = 1, 96 + left(i:i) = CHAR(i + 31) + right(i:i) = CHAR(i + 31) + END DO + + ! Fisher-Yates shuffle for left alphabet + DO i = 96, 2, -1 + CALL RANDOM_NUMBER(r) + j = 1 + FLOOR(i * r) + temp = left(i:i) + left(i:i) = left(j:j) + left(j:j) = temp + END DO + + ! Fisher-Yates shuffle for right alphabet + DO i = 96, 2, -1 + CALL RANDOM_NUMBER(r) + j = 1 + FLOOR(i * r) + temp = right(i:i) + right(i:i) = right(j:j) + right(j:j) = temp + END DO +END SUBROUTINE initialize_alphabets + + SUBROUTINE encipher(p, c, left, right, ascii_start) + CHARACTER(LEN=1), INTENT(IN) :: p + CHARACTER(LEN=1), INTENT(OUT) :: c + CHARACTER(LEN=96), INTENT(INOUT) :: left, right + INTEGER, INTENT(IN) :: ascii_start + INTEGER :: pos + + pos = INDEX(right, p) + c = left(pos:pos) + + CALL permute_left(left, c, ascii_start) + CALL permute_right(right, p, ascii_start) + END SUBROUTINE encipher + + SUBROUTINE decipher(c, p, left, right, ascii_start) + CHARACTER(LEN=1), INTENT(IN) :: c + CHARACTER(LEN=1), INTENT(OUT) :: p + CHARACTER(LEN=96), INTENT(INOUT) :: left, right + INTEGER, INTENT(IN) :: ascii_start + INTEGER :: pos + + pos = INDEX(left, c) + p = right(pos:pos) + + CALL permute_left(left, c, ascii_start) + CALL permute_right(right, p, ascii_start) + END SUBROUTINE decipher + + SUBROUTINE permute_left(alphabet, pivot, ascii_start) + CHARACTER(LEN=96), INTENT(INOUT) :: alphabet + CHARACTER(LEN=1), INTENT(IN) :: pivot + INTEGER, INTENT(IN) :: ascii_start + INTEGER :: pos + CHARACTER(LEN=1) :: temp + + pos = INDEX(alphabet, pivot) + alphabet = alphabet(pos:) // alphabet(:pos-1) + + temp = alphabet(2:2) + alphabet(2:49) = alphabet(3:50) + alphabet(50:50) = temp + END SUBROUTINE permute_left + + SUBROUTINE permute_right(alphabet, pivot, ascii_start) + CHARACTER(LEN=96), INTENT(INOUT) :: alphabet + CHARACTER(LEN=1), INTENT(IN) :: pivot + INTEGER, INTENT(IN) :: ascii_start + INTEGER :: pos + CHARACTER(LEN=1) :: temp + + pos = INDEX(alphabet, pivot) + alphabet = alphabet(pos:) // alphabet(:pos-1) + alphabet = alphabet(2:) // alphabet(1:1) + + temp = alphabet(3:3) + alphabet(3:49) = alphabet(4:50) + alphabet(50:50) = temp + END SUBROUTINE permute_right + +END PROGRAM Chaocipher diff --git a/Task/Chaocipher/Jq/chaocipher.jq b/Task/Chaocipher/Jq/chaocipher.jq new file mode 100644 index 0000000000..8035df93a1 --- /dev/null +++ b/Task/Chaocipher/Jq/chaocipher.jq @@ -0,0 +1,58 @@ +# If using jaq, then see remark above regarding `inform/1` +# Convenience function for emitting progress messages: +def inform(msg): + (msg | tostring | stderr | empty), .; + +# $encrypt should be one of true (for encryption) or false (for decryption) +def Chao($encrypt; $showSteps): + . as $text + | length as $len + | if any(explode[]; . > 128) + then "Text contains non-ASCII characters." | error + else {left: "HXUCZVAMDSLKPEFJRIGTWOBNYQ", + right: "PTLNBQDEOYSFAVZKGJRIHWXUMC", + eText: "", + temp: [range(0;26) | ""] + } + | reduce range(0; $len) as $i (.; + if $showSteps then inform("\(.left) \(.right)\n") end + + | if $encrypt + then .index = (.left|index($text[$i:$i+1])) + | .eText += .right[.index:.index+1] + else .index = (.right|index($text[$i:$i+1])) + | .eText += .left[.index:.index+1] + end + + | if $i == $len - 1 then . + else # permute left + reduce range(.index; 26) as $j (.; .temp[$j-.index] = .left[$j:$j+1]) + | reduce range(0; .index) as $j (.; .temp[26-.index+$j] = .left[$j:$j+1]) + | .store = .temp[1] + | reduce range(2; 14) as $j (.; .temp[$j-1] = .temp[$j]) + | .temp[13] = .store + | .left = (.temp | join("")) + + # permute right + | reduce range(.index; 26) as $j (.; .temp[$j-.index] = .right[$j:$j+1]) + | reduce range(0; .index) as $j (.; .temp[26-.index+$j] = .right[$j:$j+1]) + | .store = .temp[0] + | reduce range(1; 26) as $j (.; .temp[$j-1] = .temp[$j]) + | .temp[25] = .store + | .store = .temp[2] + | reduce range(3; 14) as $j (.; .temp[$j-1] = .temp[$j]) + | .temp[13] = .store + | .right = (.temp | join("")) + end ) + | .eText + end ; + +# Input: plaintext +def task: + "The original plaintext is : \(.)", + "The left and right alphabets after each permutation during encryption are:", + (Chao(true; true) + | "The ciphertext is : \(.)", + "The recovered plaintext is : \(Chao(false; false))" ); + +"WELLDONEISBETTERTHANWELLSAID" | task diff --git a/Task/Chaocipher/Julia/chaocipher.julia b/Task/Chaocipher/Julia/chaocipher.jl similarity index 100% rename from Task/Chaocipher/Julia/chaocipher.julia rename to Task/Chaocipher/Julia/chaocipher.jl diff --git a/Task/Chaocipher/Kotlin/chaocipher.kotlin b/Task/Chaocipher/Kotlin/chaocipher.kts similarity index 100% rename from Task/Chaocipher/Kotlin/chaocipher.kotlin rename to Task/Chaocipher/Kotlin/chaocipher.kts diff --git a/Task/Chaocipher/Pluto/chaocipher.pluto b/Task/Chaocipher/Pluto/chaocipher.pluto new file mode 100644 index 0000000000..92add48042 --- /dev/null +++ b/Task/Chaocipher/Pluto/chaocipher.pluto @@ -0,0 +1,55 @@ +require "table2" + +enum chao begin + encrypt, + decrypt +end + +local function exec(text, mode, show_steps) + local len = #text + local left = "HXUCZVAMDSLKPEFJRIGTWOBNYQ" + local right = "PTLNBQDEOYSFAVZKGJRIHWXUMC" + local etext = table.rep(len, 0) + local temp = table.rep(26, "") + for i = 1, len do + if show_steps then print($"{left} {right}") end + local index + if mode == chao.encrypt then + index = right:find(text[i], 1, true) + etext[i] = left[index] + else + index = left:find(text[i], 1, true) + etext[i] = right[index] + end + if i == len then break end + + -- Permute left. + for j = index, 26 do temp[j - index + 1] = left[j] end + for j = 1, index - 1 do temp[27 - index + j] = left[j] end + local store = temp[2] + for j = 3, 14 do temp[j - 1] = temp[j] end + temp[14] = store + left = temp:concat("") + + -- Permute right. + for j = index, 26 do temp[j - index + 1] = right[j] end + for j = 1, index - 1 do temp[27 - index + j] = right[j] end + store = temp[1] + for j = 2, 26 do temp[j - 1] = temp[j] end + temp[26] = store + store = temp[3] + for j = 4, 14 do temp[j - 1] = temp[j] end + temp[14] = store + right = temp:concat("") + end + return etext:concat("") +end + +local plain_text = "WELLDONEISBETTERTHANWELLSAID" +print($"The original plaintext is : {plain_text}") +io.write("\nThe left and right alphabets after each permutation ") +print("during encryption are :\n") +local cipher_text = exec(plain_text, chao.encrypt, true) +print($"\nThe ciphertext is : {cipher_text}") +local plain_text2 = exec(cipher_text, chao.decrypt, false) +print($"\nThe recovered plaintext is : {plain_text2}") diff --git a/Task/Chaocipher/Rust/chaocipher.rust b/Task/Chaocipher/Rust/chaocipher.rs similarity index 100% rename from Task/Chaocipher/Rust/chaocipher.rust rename to Task/Chaocipher/Rust/chaocipher.rs diff --git a/Task/Chaocipher/Swift/chaocipher.swift b/Task/Chaocipher/Swift/chaocipher.swift new file mode 100644 index 0000000000..ae0cc62b27 --- /dev/null +++ b/Task/Chaocipher/Swift/chaocipher.swift @@ -0,0 +1,84 @@ +enum Mode { + case encrypt + case decrypt +} + +class Chaocipher { + private static let L_ALPHABET = "HXUCZVAMDSLKPEFJRIGTWOBNYQ" + private static let R_ALPHABET = "PTLNBQDEOYSFAVZKGJRIHWXUMC" + + private static func indexOf(array: [Character], char: Character) -> Int { + for i in 0.. String { + var left = Array(L_ALPHABET) + var right = Array(R_ALPHABET) + var eText = [Character](repeating: " ", count: text.count) + var temp = [Character](repeating: " ", count: 26) + + let textChars = Array(text) + + for i in 0.. String { + return exec(text: text, mode: .encrypt, showSteps: showSteps) + } + + static func decrypt(text: String, showSteps: Bool = false) -> String { + return exec(text: text, mode: .decrypt, showSteps: showSteps) + } +} + +// Main program +let plainText = "WELLDONEISBETTERTHANWELLSAID" +print("The original plaintext is : \(plainText)") +print("\nThe left and right alphabets after each permutation during encryption are:") +let cipherText = Chaocipher.encrypt(text: plainText, showSteps: true) +print("\nThe cipher text is : \(cipherText)") +let plainText2 = Chaocipher.decrypt(text: cipherText) +print("\nThe recovered plaintext is : \(plainText2)") diff --git a/Task/Chaocipher/Tcl/chaocipher.tcl b/Task/Chaocipher/Tcl/chaocipher.tcl new file mode 100644 index 0000000000..a0fc593619 --- /dev/null +++ b/Task/Chaocipher/Tcl/chaocipher.tcl @@ -0,0 +1,160 @@ +#!/usr/bin/env tclsh + +# Tcl implementation of Chaocipher +# (John F. Byrne, 1918) +# +# from paper "CHAOCIPHER REVEALED: THE ALGORITHM" +# (Moshe Rubin, 2010) +# http://www.mountainvistasoft.com/chaocipher/ActualChaocipher/Chaocipher-Revealed-Algorithm.pdf +# + +# ============ globals "wheels" ============ +variable l_key {HXUCZVAMDSLKPEFJRIGTWOBNYQ} +variable r_key {PTLNBQDEOYSFAVZKGJRIHWXUMC} + + + +# ============ procedures ================== + + +# swap range of n letters from end to front +proc permute {alpha n } { + + set A [string range $alpha 0 $n-1 ] + set B [string range $alpha $n end ] + + return "${B}${A}" +} + + +# rotate based on key in right alphabet +# (permute each by same amnount) +proc rotate { left right key } { + + set idx [string first $key $right] + + set L [permute $left $idx ] + + set R [permute $right $idx] + + return [list $L $R] +} + + +# split and rearrange each alphabet +# according to recipe +proc cycle { left right } { + + # (0)(2-13)(1)(14-25) + set l1 [string index $left 0 ] + set l2 [string range $left 2 13 ] + set l3 [string index $left 1 ] + set l4 [string range $left 14 end] + + set L [join [list $l1 $l2 $l3 $l4] ""] + + # (1-2)(4-14)(3)(15-25)(0) + set r1 [string range $right 1 2 ] + set r2 [string range $right 4 14 ] + set r3 [string index $right 3 ] + set r4 [string range $right 15 end] + set r5 [string index $right 0 ] + + set R [join [list $r1 $r2 $r3 $r4 $r5] ""] + + return [list $L $R] +} + + +# rotate wheels and generate cipher text or +# recover plain text +proc chao { input left right mode verbose } { + + set out {} + + set wheels {} + + set len [string length $input] + + if { $verbose } { + puts stdout "input\t$input\tLENGTH $len" + + set s [format "%-${len}s\t|\t%-${len}s" $left $right] + + puts stdout "keys:\t$s" + + puts stdout "\ncycled keys:" + } + + # string -> list + set input_list [split $input ""] + + set count 0 + # iterate each letter + foreach letter $input_list { + + incr count + + if {$mode eq "encrypt" } { + # encrypt + + # rotate and permute + set wheels [rotate $left $right $letter] + lassign $wheels left right + + # ciphered letter to output (left[0]) + lappend out [string index $left 0] + + } else { + + # decrypt + + # rotate and permute + set wheels [rotate $right $left $letter] + lassign $wheels right left + + # deciphered letter to output (right[0]) + lappend out [string index $right 0] + } + + # cycle the alphabets + set cycled [cycle $left $right] + lassign $cycled left right + + if {$verbose} { puts stderr "${count}\t${left}\t|\t${right}" } + + + } ; # foreach letter + + # list -> string + set out [join $out ""] + + return $out +} + + +# ============= main ================= +if { [info script] eq $::argv0 } { + + # --------- init ------------------ + set left $l_key + set right $r_key + set plain_text "WELLDONEISBETTERTHANWELLSAID" + + # ---------- encipher ------------- + + set cipher_text [chao $plain_text $left $right encrypt 1] + + # ---------- decipher ------------- + + set decrypted_text [chao $cipher_text $left $right decrypt 0] + # ----------- output -------------- + + puts stdout "\nplain text: \t ${plain_text}" + puts stdout "\ncipher text: \t ${cipher_text}" + puts stdout "\ndecrypted: \t ${decrypted_text}" + + return 0 +} + +# end diff --git a/Task/Chaos-game/Ada/chaos-game.adb b/Task/Chaos-game/Ada/chaos-game.adb new file mode 100644 index 0000000000..fe213c85fc --- /dev/null +++ b/Task/Chaos-game/Ada/chaos-game.adb @@ -0,0 +1,45 @@ +pragma Ada_2022; +with Ada.Numerics; use Ada.Numerics; +with Ada.Numerics.Discrete_Random; +with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions; +with Easy_Graphics; use Easy_Graphics; + +procedure Chaos_Game is + Img : Easy_Image := New_Image ((1, 1), (512, 512), WHITE); + + procedure Chaos (Image : in out Easy_Image; + Vertex_Count : Positive; + Radius : Float; + Iters : Positive) is + type Vertex_Array is array (1 .. Vertex_Count) of Point; + Vertices : Vertex_Array; + subtype Vertex_Range is Integer range 1 .. Vertex_Count; + package Rand_V is new Ada.Numerics.Discrete_Random (Vertex_Range); + use Rand_V; + Gen : Generator; + Half_X : constant Integer := X_Last (Image) / 2; + Half_Y : constant Integer := Y_Last (Image) / 2; + Half_Pi : constant Float := Float (Pi) / 2.0; + Two_Pi : constant Float := Float (Pi) * 2.0; + V : Integer; + X : Integer := Half_X; + Y : Integer := Half_Y; + begin + for V in 1 .. Vertex_Count loop + Vertices (V).X := Half_X + Integer (Float (Half_X) * + Cos (Half_Pi + (Float (V - 1)) * Two_Pi / Float (Vertex_Count))); + Vertices (V).Y := Half_Y - Integer (Float (Half_Y) * + Sin (Half_Pi + (Float (V - 1)) * Two_Pi / Float (Vertex_Count))); + end loop; + for I in 1 .. Iters loop + V := Random (Gen); + X := X + Integer (Radius * Float (Vertices (V).X - X)); + Y := Y + Integer (Radius * Float (Vertices (V).Y - Y)); + Plot (Image, (X, Y), BLACK); + end loop; + end Chaos; + +begin + Chaos (Img, 3, 0.5, 250_000); + Write_GIF (Img, "chaos_game.gif"); +end Chaos_Game; diff --git a/Task/Chaos-game/AmigaBASIC/chaos-game.basic b/Task/Chaos-game/AmigaBASIC/chaos-game.basic new file mode 100644 index 0000000000..637e89a1da --- /dev/null +++ b/Task/Chaos-game/AmigaBASIC/chaos-game.basic @@ -0,0 +1,28 @@ +DEFINT a-z +w=600:h=180:w2=300 +x=w*RND:y=h*RND + +FOR i=1 TO 32000 + v=2*RND+1 + ON v GOTO One, Two, Three + +One: + x=x/2 + y=y/2 + GOTO Draw + +Two: + x=w2+(w2-x)/2 + y=h-(h-y)/2 + GOTO Draw + +Three: + x=w-(w-x)/2 + y=y/2 + +Draw: + PSET (x,y),v +NEXT + +loop: + GOTO loop diff --git a/Task/Chaos-game/Atari-BASIC/chaos-game.basic b/Task/Chaos-game/Atari-BASIC/chaos-game.basic new file mode 100644 index 0000000000..b612f7a348 --- /dev/null +++ b/Task/Chaos-game/Atari-BASIC/chaos-game.basic @@ -0,0 +1,18 @@ +10 GRAPHICS 7+16 +20 W=159:H=95:W2=79 +30 X=INT(W*RND(0)) +40 Y=INT(H*RND(0)) +50 FOR I=1 TO 5000 +60 V=INT(3*RND(0))+1 +70 GOTO 100*V +100 X=X/2:Y=Y/2 +110 GOTO 500 +200 X=W2+(W2-X)/2 +210 Y=H-(H-Y)/2 +220 GOTO 500 +300 X=W-(W-X)/2 +310 Y=Y/2 +500 COLOR V +510 PLOT X,Y +520 NEXT I +530 GOTO 530 diff --git a/Task/Chaos-game/Delphi/chaos-game.delphi b/Task/Chaos-game/Delphi/chaos-game.pas similarity index 100% rename from Task/Chaos-game/Delphi/chaos-game.delphi rename to Task/Chaos-game/Delphi/chaos-game.pas diff --git a/Task/Chaos-game/EasyLang/chaos-game.easy b/Task/Chaos-game/EasyLang/chaos-game.easy index 1981fc43a7..ae10673f1b 100644 --- a/Task/Chaos-game/EasyLang/chaos-game.easy +++ b/Task/Chaos-game/EasyLang/chaos-game.easy @@ -1,12 +1,11 @@ -color 900 +gcolor 900 x[] = [ 0 100 50 ] -y[] = [ 7 7 93 ] +y[] = [ 14 14 100 ] x = randomf * 100 y = randomf * 100 for i = 1 to 100000 - move x y - rect 0.3 0.3 - h = randint 3 + grect x y 0.3 0.3 + h = random 1 3 x = (x + x[h]) / 2 y = (y + y[h]) / 2 . diff --git a/Task/Chaos-game/Emacs-Lisp/chaos-game.l b/Task/Chaos-game/Emacs-Lisp/chaos-game.el similarity index 100% rename from Task/Chaos-game/Emacs-Lisp/chaos-game.l rename to Task/Chaos-game/Emacs-Lisp/chaos-game.el diff --git a/Task/Chaos-game/J/chaos-game.j b/Task/Chaos-game/J/chaos-game.j index bdf828c34e..bad0f35b60 100644 --- a/Task/Chaos-game/J/chaos-game.j +++ b/Task/Chaos-game/J/chaos-game.j @@ -1,33 +1,6 @@ -Note 'plan, Working in complex plane' - Make an equilateral triangle. - Make a list of N targets - Starting with a random point near the triangle, - iteratively generate new points. - plot the new points. - - j has a particularly rich notation for numbers. - - 1ad_90 specifies a complex number with radius 1 - at an angle of negative 90 degrees. - - 2p1 is 2 times (pi raised to the first power). -) - -N=: 3000 - require'plot' -TAU=: 2p1 NB. tauday.com -mean=: +/ % # - -NB. equilateral triangle with vertices on unit circle -NB. rotated for fun. -TRIANGLE=: *(j./2 1 o.(TAU%6)*?0)*1ad_90 1ad150 1ad30 - -TARGETS=: (N ?@:# 3) { TRIANGLE - -NB. start on unit circle -START=: j./2 1 o.TAU*?0 - -NEW_POINTS=: (mean@:(, {.) , ])/ TARGETS , START - -'marker'plot NEW_POINTS +NB. equilateral triangle with vertices on unit circle. rotated for fun. +Triangle=: *1ad_90 1ad150 1ad30*j./2 1 o.(2p1%6)*?0 +Targets=: (?3000#3) { Triangle +Start=: j./2 1 o.2p1*?0 NB. start on unit circle +'marker' plot ((+/%#)@(,{.) , ])/Targets,Start diff --git a/Task/Chaos-game/Julia/chaos-game.julia b/Task/Chaos-game/Julia/chaos-game.jl similarity index 100% rename from Task/Chaos-game/Julia/chaos-game.julia rename to Task/Chaos-game/Julia/chaos-game.jl diff --git a/Task/Chaos-game/Kotlin/chaos-game.kotlin b/Task/Chaos-game/Kotlin/chaos-game.kts similarity index 100% rename from Task/Chaos-game/Kotlin/chaos-game.kotlin rename to Task/Chaos-game/Kotlin/chaos-game.kts diff --git a/Task/Chaos-game/Rust/chaos-game.rust b/Task/Chaos-game/Rust/chaos-game.rs similarity index 100% rename from Task/Chaos-game/Rust/chaos-game.rust rename to Task/Chaos-game/Rust/chaos-game.rs diff --git a/Task/Chaos-game/Uxntal/chaos-game.uxnatl b/Task/Chaos-game/Uxntal/chaos-game.uxnatl new file mode 100644 index 0000000000..13873818ad --- /dev/null +++ b/Task/Chaos-game/Uxntal/chaos-game.uxnatl @@ -0,0 +1,82 @@ +|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 +|c0 @DateTime &year $2 &month $1 &day $1 &hour $1 &minute $1 &second $1 &dotw $1 &doty $2 &isdst $1 + +|00 + @State &x $2 &y $2 + +|0100 +@on-reset ( -> ) + .DateTime/minute DEI2 SWP #20 SFT2 lcg/ + + #0f0f DUP2k + .System/r DEO2 + .System/g DEO2 + .System/b DEO2 + + ( 256 x 222 fits all three reference points ) + #0100 .Screen/width DEO2 + #00de .Screen/height DEO2 + + start-point + .State/x STZ2 + .State/y STZ2 + + ;on-frame .Screen/vector DEO2 + BRK + +@on-frame ( -> ) + [ LIT2 00 -State/x ] LDZ .Screen/x DEO2 + [ LIT2 00 -State/y ] LDZ .Screen/y DEO2 + [ LIT2 01 -Screen/pixel ] DEO + + next-point + .State/x STZ2 + .State/y STZ2 + BRK + +@start-point ( -- y* x* ) + ( pick a random point in a square ) + lcg/next lcg/next + ( mirror point if needed to move point to top left triangle ) + ADD2k OVR2 GTH2 ?{ + #0000 SWP2 SUB2 SWP2 + #0000 SWP2 SUB2 + } + ( skew points so triangle has a point in the bottom middle ) + SWP2 OVR2 #01 SFT2 ADD2 + ( mirror points vertically to make the triangle point up ) + STH2 #0000 SWP2 SUB2 + ( fixed point multiply y by cos 30deg to make it equilateral ) + ( hi * hi ) OVR #00 SWP #00dd MUL2 STH2 + ( hi * lo ) SWP #00 SWP #00b4 MUL2 STH2 + ( lo * hi ) #00 SWP #00dd MUL2 + ( add low bytes ) STH2r ADD2 #08 SFT2 + ( add to high product ) STH2r ADD2 + STH2r + + JMP2r + +@next-point ( -- y* x* ) + ( midpoint of previous State and a random corner ) + random-corner + #01 SFT2 .State/x LDZ2 #01 SFT2 ADD2 + STH2 + #01 SFT2 .State/y LDZ2 #01 SFT2 ADD2 + STH2r JMP2r + +@random-corner ( -- y* x* ) + ( randomly pick one of the three corners ) + lcg/next + #0003 DIV2k INC2 MUL2 SUB2 NIP + INC DUP ?{ POP #0000 #8000 JMP2r } + INC DUP ?{ POP #ddb4 #0000 JMP2r } + POP #ddb4 #ffff JMP2r + +@lcg/ ( seed* -- ) + ,&State STR2 JMP2r + +@lcg/next ( -- x* ) + [ LIT2 &State $2 ] + #0815 MUL2 #1419 ADD2 DUP2 ,&State STR2 + JMP2r diff --git a/Task/Character-codes/Ada/character-codes.ada b/Task/Character-codes/Ada/character-codes.adb similarity index 100% rename from Task/Character-codes/Ada/character-codes.ada rename to Task/Character-codes/Ada/character-codes.adb diff --git a/Task/Character-codes/Agena/character-codes.agena b/Task/Character-codes/Agena/character-codes.agena new file mode 100644 index 0000000000..a1410f30ad --- /dev/null +++ b/Task/Character-codes/Agena/character-codes.agena @@ -0,0 +1,2 @@ +print( abs "a" ); # prints the character code of a (97 in ASCII) +print( char( 97 ) ); # prints the character corresponding to code 97 ("a" in ASCII) diff --git a/Task/Character-codes/ArkScript/character-codes.ark b/Task/Character-codes/ArkScript/character-codes.ark new file mode 100644 index 0000000000..d96abc35c4 --- /dev/null +++ b/Task/Character-codes/ArkScript/character-codes.ark @@ -0,0 +1,4 @@ +(import std.String) + +(print (string:ord "a")) +(print (string:chr 97)) diff --git a/Task/Character-codes/Arturo/character-codes.arturo b/Task/Character-codes/Arturo/character-codes.arturo index e98e2586e9..f9ac1ae91b 100644 --- a/Task/Character-codes/Arturo/character-codes.arturo +++ b/Task/Character-codes/Arturo/character-codes.arturo @@ -1,3 +1,3 @@ print to :integer first "a" -print to :integer `a` +print to :integer 'a' print to :char 97 diff --git a/Task/Character-codes/Ballerina/character-codes.ballerina b/Task/Character-codes/Ballerina/character-codes.ballerina new file mode 100644 index 0000000000..c16ce85fc2 --- /dev/null +++ b/Task/Character-codes/Ballerina/character-codes.ballerina @@ -0,0 +1,15 @@ +import ballerina/io; + +public function main() returns error? { + int[] cps = []; + foreach string c in ["a", "π", "字", "🐘"] { + int cp = c[0].toCodePointInt(); + cps.push(cp); + io:println(`${c} = ${cp}`); + } + io:println(); + foreach int i in cps { + var c = check string:fromCodePointInt(i); + io:println(`${i} = ${c}`); + } +} diff --git a/Task/Character-codes/COBOL/character-codes.cobol b/Task/Character-codes/COBOL/character-codes.cob similarity index 100% rename from Task/Character-codes/COBOL/character-codes.cobol rename to Task/Character-codes/COBOL/character-codes.cob diff --git a/Task/Character-codes/Crystal/character-codes.cr b/Task/Character-codes/Crystal/character-codes.cr new file mode 100644 index 0000000000..5fb1cfa9e7 --- /dev/null +++ b/Task/Character-codes/Crystal/character-codes.cr @@ -0,0 +1,2 @@ +'Ω'.ord # => 937 +937.chr # => 'Ω' diff --git a/Task/Character-codes/Dart/character-codes.dart b/Task/Character-codes/Dart/character-codes.dart new file mode 100644 index 0000000000..b1b602f4bd --- /dev/null +++ b/Task/Character-codes/Dart/character-codes.dart @@ -0,0 +1,6 @@ +void main() { + const string = 'D'; + print(string.runes.first); + var out = String.fromCharCode(67); + print(out); +} diff --git a/Task/Character-codes/Delphi/character-codes.delphi b/Task/Character-codes/Delphi/character-codes.pas similarity index 100% rename from Task/Character-codes/Delphi/character-codes.delphi rename to Task/Character-codes/Delphi/character-codes.pas diff --git a/Task/Character-codes/EMal/character-codes.emal b/Task/Character-codes/EMal/character-codes.emal index d5b9bb52d9..f7b1fe0929 100644 --- a/Task/Character-codes/EMal/character-codes.emal +++ b/Task/Character-codes/EMal/character-codes.emal @@ -4,14 +4,11 @@ writeLine(chr(97)) # prints "a" writeLine(ord("π")) # prints "960" writeLine(chr(960)) # prints "π" writeLine() -var cps = int[] +var cps ← int[] for each var c in text["a", "π", "字", "🐘"] - var cp = ord(c) + var cp ← ord(c) cps.append(cp) - writeLine(c + " = " + cp) + writeLine(c, " = ", cp) end writeLine() -for each int i in cps - var c = chr(i) - writeLine(i + " = " + c) -end +cps.list(",ASC("a") + PRINT "97 ->",CHR$(97) + GET +ENDP diff --git a/Task/Character-codes/Odin/character-codes.odin b/Task/Character-codes/Odin/character-codes.odin new file mode 100644 index 0000000000..0acc50a345 --- /dev/null +++ b/Task/Character-codes/Odin/character-codes.odin @@ -0,0 +1,11 @@ +package main + +import "core:fmt" + +main :: proc() { + // No difference between chracters and ints + a:int=97 + fmt.println(rune(a)) + number:int='a' + fmt.println(number) +} diff --git a/Task/Character-codes/PL-I-80/character-codes.pli b/Task/Character-codes/PL-I-80/character-codes.pli new file mode 100644 index 0000000000..e41644b762 --- /dev/null +++ b/Task/Character-codes/PL-I-80/character-codes.pli @@ -0,0 +1,8 @@ +char_codes: procedure options (main); + dcl ch char(1); + dcl n fixed bin; + ch = 'a'; + n = 97; + put skip edit (ch,' = ',rank(ch)) (a, a, f(2)); + put skip edit (n,' = ',ascii(n)) (f(2), a, a); +end char_codes; diff --git a/Task/Character-codes/PascalABC.NET/character-codes.pas b/Task/Character-codes/PascalABC.NET/character-codes.pas new file mode 100644 index 0000000000..deacfdd34e --- /dev/null +++ b/Task/Character-codes/PascalABC.NET/character-codes.pas @@ -0,0 +1,6 @@ +begin + var c := 'a'; + var i := c.Code; + Println(i); + Println(Chr(i)) +end. diff --git a/Task/Character-codes/PowerShell/character-codes-1.psh b/Task/Character-codes/PowerShell/character-codes-1.ps1 similarity index 100% rename from Task/Character-codes/PowerShell/character-codes-1.psh rename to Task/Character-codes/PowerShell/character-codes-1.ps1 diff --git a/Task/Character-codes/PowerShell/character-codes-2.psh b/Task/Character-codes/PowerShell/character-codes-2.ps1 similarity index 100% rename from Task/Character-codes/PowerShell/character-codes-2.psh rename to Task/Character-codes/PowerShell/character-codes-2.ps1 diff --git a/Task/Character-codes/PowerShell/character-codes-3.psh b/Task/Character-codes/PowerShell/character-codes-3.ps1 similarity index 100% rename from Task/Character-codes/PowerShell/character-codes-3.psh rename to Task/Character-codes/PowerShell/character-codes-3.ps1 diff --git a/Task/Character-codes/PowerShell/character-codes-4.psh b/Task/Character-codes/PowerShell/character-codes-4.ps1 similarity index 100% rename from Task/Character-codes/PowerShell/character-codes-4.psh rename to Task/Character-codes/PowerShell/character-codes-4.ps1 diff --git a/Task/Character-codes/PowerShell/character-codes-5.psh b/Task/Character-codes/PowerShell/character-codes-5.ps1 similarity index 100% rename from Task/Character-codes/PowerShell/character-codes-5.psh rename to Task/Character-codes/PowerShell/character-codes-5.ps1 diff --git a/Task/Character-codes/Rebol/character-codes.rebol b/Task/Character-codes/Rebol/character-codes.rebol new file mode 100644 index 0000000000..8566b5bd09 --- /dev/null +++ b/Task/Character-codes/Rebol/character-codes.rebol @@ -0,0 +1,7 @@ +print to integer! first "a" ;; == 97 +print to integer! #"a" ;; == 97 +print to binary! "a" ;; == #{61} +print to char! 97 ;; == a +print to char! 0#61 ;; == a ;; available only in Rebol3 +print #"^(61)" ;; == a +print to-hex #"a" ;; == 61 ;; since Rebol 3.20.0 diff --git a/Task/Character-codes/Retro/character-codes.retro b/Task/Character-codes/Retro/character-codes.retro index 2272064c6f..783d9773d1 100644 --- a/Task/Character-codes/Retro/character-codes.retro +++ b/Task/Character-codes/Retro/character-codes.retro @@ -1 +1,2 @@ -'c putc +$a n:put nl +#97 c:put nl diff --git a/Task/Character-codes/Rust/character-codes.rust b/Task/Character-codes/Rust/character-codes.rs similarity index 100% rename from Task/Character-codes/Rust/character-codes.rust rename to Task/Character-codes/Rust/character-codes.rs diff --git a/Task/Character-codes/S-BASIC/character-codes.basic b/Task/Character-codes/S-BASIC/character-codes.basic new file mode 100644 index 0000000000..c3a772f23b --- /dev/null +++ b/Task/Character-codes/S-BASIC/character-codes.basic @@ -0,0 +1,14 @@ +var ch = char +var n = integer + +ch = 'a' +n = ch +print ch; " = "; n +print ch; " = "; asc(ch) + +n = 97 +ch = n +print n; " = "; ch +print n; " = "; chr$(n) + +end diff --git a/Task/Character-codes/Scheme/character-codes.ss b/Task/Character-codes/Scheme/character-codes.scm similarity index 100% rename from Task/Character-codes/Scheme/character-codes.ss rename to Task/Character-codes/Scheme/character-codes.scm diff --git a/Task/Character-codes/TAV/character-codes.tav b/Task/Character-codes/TAV/character-codes.tav new file mode 100644 index 0000000000..727bf15da6 --- /dev/null +++ b/Task/Character-codes/TAV/character-codes.tav @@ -0,0 +1,2 @@ + print string 'a' code point at 1 \ print 'a'.Codepoint + print integer 97 code point as string \ print 97.Character diff --git a/Task/Character-codes/Tcl/character-codes.tcl b/Task/Character-codes/Tcl/character-codes.tcl deleted file mode 100644 index 949c5ff094..0000000000 --- a/Task/Character-codes/Tcl/character-codes.tcl +++ /dev/null @@ -1,6 +0,0 @@ -# ASCII -puts [scan "a" %c] ;# ==> 97 -puts [format %c 97] ;# ==> a -# Unicode is the same -puts [scan "π" %c] ;# ==> 960 -puts [format %c 960] ;# ==> π diff --git a/Task/Character-codes/Uiua/character-codes.uiua b/Task/Character-codes/Uiua/character-codes.uiua new file mode 100644 index 0000000000..75f72c71f7 --- /dev/null +++ b/Task/Character-codes/Uiua/character-codes.uiua @@ -0,0 +1,2 @@ +-@\0@a ++@\097 diff --git a/Task/Character-codes/Uxntal/character-codes.uxnatl b/Task/Character-codes/Uxntal/character-codes.uxnatl index 0429ace25f..f2fd52e587 100644 --- a/Task/Character-codes/Uxntal/character-codes.uxnatl +++ b/Task/Character-codes/Uxntal/character-codes.uxnatl @@ -1,26 +1,19 @@ -( uxnasm char-codes.tal char-codes.rom && uxncli char-codes.rom ) +%\n { 0a } +%newline { [ LIT2 \n -Console/write ] DEO } -|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 +|18 @Console/write -|0100 - [ LIT "a ] print-hex - newline - #61 .Console/write DEO - newline +|100 + +[ LIT "a ] print/byte newline +#61 .Console/write DEO newline - ( exit ) - #80 .System/state DEO BRK -@print-hex - DUP #04 SFT print-digit #0f AND print-digit -JMP2r - -@print-digit - DUP #09 GTH #27 MUL ADD #30 ADD .Console/write DEO -JMP2r - -@newline - #0a .Console/write DEO -JMP2r +@print/byte ( byte -- ) + DUP #04 SFT /nibble + ( >> ) + +@print/nibble ( byte -- ) + #0f AND DUP #09 GTH #27 MUL ADD [ LIT "0 ] ADD .Console/write DEO + JMP2r diff --git a/Task/Character-codes/VBScript/character-codes.vb b/Task/Character-codes/VBScript/character-codes.vbs similarity index 100% rename from Task/Character-codes/VBScript/character-codes.vb rename to Task/Character-codes/VBScript/character-codes.vbs diff --git a/Task/Chat-server/Ada/chat-server.ada b/Task/Chat-server/Ada/chat-server.adb similarity index 100% rename from Task/Chat-server/Ada/chat-server.ada rename to Task/Chat-server/Ada/chat-server.adb diff --git a/Task/Chat-server/FreeBASIC/chat-server.basic b/Task/Chat-server/FreeBASIC/chat-server.basic new file mode 100644 index 0000000000..4070f9e3cd --- /dev/null +++ b/Task/Chat-server/FreeBASIC/chat-server.basic @@ -0,0 +1,122 @@ +#include once "windows.bi" +#include once "win/winsock2.bi" + +Type SOCKET As Ulongint +Type ThreadCallback As Sub(Byval As Any Ptr) + +Const MAX_CLIENTS = 10 +Const CRLF = Chr(13) & Chr(10) +Const BUFFER_SIZE = 256 + +Dim Shared clients(MAX_CLIENTS) As SOCKET +Dim Shared nicknames(MAX_CLIENTS) As String +Dim Shared clientCount As Integer = 0 + +' Initialize Winsock +Dim As WSADATA wsaData +If WSAStartup(&h0202, @wsaData) Then + Print "Error initializing Winsock" + End 1 +End If + +' Create server socket +Dim As SOCKET serverSocket = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, 0) +If serverSocket = INVALID_SOCKET Then + Print "Error creating socket" + WSACleanup() + End 1 +End If + +' Configure server address +Dim As sockaddr_in serverAddr +With serverAddr + .sin_family = AF_INET + .sin_addr.s_addr = INADDR_ANY + .sin_port = htons(8080) +End With + +' Bind socket +If bind(serverSocket, Cast(sockaddr Ptr, @serverAddr), Sizeof(sockaddr_in)) = SOCKET_ERROR Then + Print "Error binding socket" + closesocket(serverSocket) + WSACleanup() + End 1 +End If + +' Listen for incoming connections +If listen(serverSocket, SOMAXCONN) = SOCKET_ERROR Then + Print "Error listening on socket" + closesocket(serverSocket) + WSACleanup() + End 1 +End If + +Print "Chat server is running on port 8080" + +Sub broadcastMessage(message As String) + Dim As String fullMsg = message + For i As Integer = 0 To clientCount - 1 + If clients(i) <> 0 Then + send(clients(i), Strptr(fullMsg), Len(fullMsg), 0) + End If + Next i +End Sub + +Sub handleClient(Byval param As Any Ptr) + Dim As Integer clientIndex = Cast(Integer, param) + Dim As SOCKET clientSocket = clients(clientIndex) + Dim As String nickname + Dim As ZString * BUFFER_SIZE buffer + Dim As Long bytesReceived + + ' Get nickname + Dim As String welcomeMsg = "Enter your nickname: " + send(clientSocket, Strptr(welcomeMsg), Len(welcomeMsg), 0) + bytesReceived = recv(clientSocket, @buffer, BUFFER_SIZE-1, 0) + If bytesReceived > 0 Then + nickname = Left(buffer, bytesReceived - 2) + nicknames(clientIndex) = nickname + + ' Announce new user + broadcastMessage(nickname & " has joined the chat." & CRLF) + + ' Message loop + Do + bytesReceived = recv(clientSocket, @buffer, BUFFER_SIZE-1, 0) + If bytesReceived <= 0 Then Exit Do + buffer[bytesReceived] = 0 + broadcastMessage(nickname & ": " & *Cast(ZString Ptr, @buffer) & CRLF) + Loop + + ' Announce departure + broadcastMessage(nickname & " has left the chat." & CRLF) + End If + + ' Cleanup + closesocket(clientSocket) + clients(clientIndex) = 0 + nicknames(clientIndex) = "" +End Sub + +' Main server loop +Do + Dim As sockaddr_in clientAddr + Dim As Long clientAddrLen = Sizeof(sockaddr_in) + + Dim As SOCKET clientSocket = accept(serverSocket, Cast(sockaddr Ptr, @clientAddr), @clientAddrLen) + If clientSocket <> INVALID_SOCKET Then + If clientCount < MAX_CLIENTS Then + clients(clientCount) = clientSocket + clientCount += 1 + Threadcreate(Cast(ThreadCallback, @handleClient), Cast(Any Ptr, clientCount - 1)) + Else + Dim As String fullMsg = "Server is full." & CRLF + send(clientSocket, Strptr(fullMsg), Len(fullMsg), 0) + closesocket(clientSocket) + End If + End If +Loop + +' Final cleaning +closesocket(serverSocket) +WSACleanup() diff --git a/Task/Chat-server/Julia/chat-server.julia b/Task/Chat-server/Julia/chat-server.jl similarity index 100% rename from Task/Chat-server/Julia/chat-server.julia rename to Task/Chat-server/Julia/chat-server.jl diff --git a/Task/Chat-server/Kotlin/chat-server.kotlin b/Task/Chat-server/Kotlin/chat-server.kts similarity index 100% rename from Task/Chat-server/Kotlin/chat-server.kotlin rename to Task/Chat-server/Kotlin/chat-server.kts diff --git a/Task/Chat-server/Rust/chat-server.rust b/Task/Chat-server/Rust/chat-server.rs similarity index 100% rename from Task/Chat-server/Rust/chat-server.rust rename to Task/Chat-server/Rust/chat-server.rs diff --git a/Task/Check-Machin-like-formulas/00-TASK.txt b/Task/Check-Machin-like-formulas/00-TASK.txt index d6db6e1191..c28978d512 100644 --- a/Task/Check-Machin-like-formulas/00-TASK.txt +++ b/Task/Check-Machin-like-formulas/00-TASK.txt @@ -35,7 +35,7 @@ These identities are useful in calculating the values:
    You can store the equations in any convenient data structure, but for extra credit parse them from human-readable [[Check_Machin-like_formulas/text_equations|text input]]. -Note: to formally prove the formula correct, it would have to be shown that ''{-3 pi \over 4} < right hand side < {5 pi \over 4}'' due to ''\tan()'' periodicity. +Note: to formally prove the formula correct, it would have to be shown that ''{-3 \pi \over 4} < right hand side < {5 \pi \over 4}'' due to ''\tan()'' periodicity.

    diff --git a/Task/Check-Machin-like-formulas/Julia/check-machin-like-formulas.julia b/Task/Check-Machin-like-formulas/Julia/check-machin-like-formulas.jl similarity index 100% rename from Task/Check-Machin-like-formulas/Julia/check-machin-like-formulas.julia rename to Task/Check-Machin-like-formulas/Julia/check-machin-like-formulas.jl diff --git a/Task/Check-Machin-like-formulas/Kotlin/check-machin-like-formulas.kotlin b/Task/Check-Machin-like-formulas/Kotlin/check-machin-like-formulas.kts similarity index 100% rename from Task/Check-Machin-like-formulas/Kotlin/check-machin-like-formulas.kotlin rename to Task/Check-Machin-like-formulas/Kotlin/check-machin-like-formulas.kts diff --git a/Task/Check-Machin-like-formulas/OCaml/check-machin-like-formulas.ocaml b/Task/Check-Machin-like-formulas/OCaml/check-machin-like-formulas.ml similarity index 100% rename from Task/Check-Machin-like-formulas/OCaml/check-machin-like-formulas.ocaml rename to Task/Check-Machin-like-formulas/OCaml/check-machin-like-formulas.ml diff --git a/Task/Check-input-device-is-a-terminal/Ada/check-input-device-is-a-terminal.ada b/Task/Check-input-device-is-a-terminal/Ada/check-input-device-is-a-terminal.adb similarity index 100% rename from Task/Check-input-device-is-a-terminal/Ada/check-input-device-is-a-terminal.ada rename to Task/Check-input-device-is-a-terminal/Ada/check-input-device-is-a-terminal.adb diff --git a/Task/Check-input-device-is-a-terminal/Batch-File/check-input-device-is-a-terminal.bat b/Task/Check-input-device-is-a-terminal/Batch-File/check-input-device-is-a-terminal.bat new file mode 100644 index 0000000000..8fcd2d94e2 --- /dev/null +++ b/Task/Check-input-device-is-a-terminal/Batch-File/check-input-device-is-a-terminal.bat @@ -0,0 +1 @@ +(timeout /t 0 >nul 2>nul && echo Stdin is a terminal || echo Stdin is not a terminal) b.out will write to b.out, and this contains unit 5 is a terminal but unit 6 ism't +! ./checktty < a.out >b.out will write to b.out, and both units 5 and 6 are not terminals. +! +! Check units 1...10 if they are connected to a terminal. +do unit=1,10 + if (isatty (unit)) then + write (*, '("Unit ", i2, " is a Terminal")') unit + else + write (*, '("Unit ", i2, " is NOT a Terminal")') unit + endif +enddo + +end program checkTTY diff --git a/Task/Check-input-device-is-a-terminal/Janet/check-input-device-is-a-terminal.janet b/Task/Check-input-device-is-a-terminal/Janet/check-input-device-is-a-terminal.janet new file mode 100644 index 0000000000..f0fb90c650 --- /dev/null +++ b/Task/Check-input-device-is-a-terminal/Janet/check-input-device-is-a-terminal.janet @@ -0,0 +1,3 @@ +(if (os/isatty stdin) + (print "The input device is a terminal.") + (print "The input device is not a terminal.")) diff --git a/Task/Check-input-device-is-a-terminal/Julia/check-input-device-is-a-terminal.julia b/Task/Check-input-device-is-a-terminal/Julia/check-input-device-is-a-terminal.jl similarity index 100% rename from Task/Check-input-device-is-a-terminal/Julia/check-input-device-is-a-terminal.julia rename to Task/Check-input-device-is-a-terminal/Julia/check-input-device-is-a-terminal.jl diff --git a/Task/Check-input-device-is-a-terminal/Kotlin/check-input-device-is-a-terminal.kotlin b/Task/Check-input-device-is-a-terminal/Kotlin/check-input-device-is-a-terminal.kts similarity index 100% rename from Task/Check-input-device-is-a-terminal/Kotlin/check-input-device-is-a-terminal.kotlin rename to Task/Check-input-device-is-a-terminal/Kotlin/check-input-device-is-a-terminal.kts diff --git a/Task/Check-input-device-is-a-terminal/Lua/check-input-device-is-a-terminal.lua b/Task/Check-input-device-is-a-terminal/Lua/check-input-device-is-a-terminal.lua new file mode 100644 index 0000000000..53aa2d1991 --- /dev/null +++ b/Task/Check-input-device-is-a-terminal/Lua/check-input-device-is-a-terminal.lua @@ -0,0 +1,6 @@ +local posix = require"posix" +print( + posix.unistd.isatty(posix.stdio.fileno(io.stdin)) + and "stdin is a terminal" + or "stdin is not a terminal" +) diff --git a/Task/Check-input-device-is-a-terminal/Nu/check-input-device-is-a-terminal.nu b/Task/Check-input-device-is-a-terminal/Nu/check-input-device-is-a-terminal.nu new file mode 100644 index 0000000000..0a1e81828c --- /dev/null +++ b/Task/Check-input-device-is-a-terminal/Nu/check-input-device-is-a-terminal.nu @@ -0,0 +1 @@ +$'stdin is a terminal: (is-terminal -i)' diff --git a/Task/Check-input-device-is-a-terminal/OCaml/check-input-device-is-a-terminal.ocaml b/Task/Check-input-device-is-a-terminal/OCaml/check-input-device-is-a-terminal.ml similarity index 100% rename from Task/Check-input-device-is-a-terminal/OCaml/check-input-device-is-a-terminal.ocaml rename to Task/Check-input-device-is-a-terminal/OCaml/check-input-device-is-a-terminal.ml diff --git a/Task/Check-input-device-is-a-terminal/PascalABC.NET/check-input-device-is-a-terminal.pas b/Task/Check-input-device-is-a-terminal/PascalABC.NET/check-input-device-is-a-terminal.pas new file mode 100644 index 0000000000..0c5e7e3fdb --- /dev/null +++ b/Task/Check-input-device-is-a-terminal/PascalABC.NET/check-input-device-is-a-terminal.pas @@ -0,0 +1,3 @@ +## +uses system; +system.Console.IsInputRedirected.println; diff --git a/Task/Check-input-device-is-a-terminal/Phix/check-input-device-is-a-terminal.phix b/Task/Check-input-device-is-a-terminal/Phix/check-input-device-is-a-terminal.phix index a8e739efdc..8f2a7843e3 100644 --- a/Task/Check-input-device-is-a-terminal/Phix/check-input-device-is-a-terminal.phix +++ b/Task/Check-input-device-is-a-terminal/Phix/check-input-device-is-a-terminal.phix @@ -1,4 +1,2 @@ -(notonline)--> - without js -- (no input redirection in a browser!) - printf(1,"stdin:%t, stdout:%t, stderr:%t\n",{isatty(0),isatty(1),isatty(2)}) - - without js -- (no input or output redirection in a browser!) - printf(1,"stdin:%t, stdout:%t, stderr:%t\n",{isatty(0),isatty(1),isatty(2)}) - - without js -- (file i/o) - procedure check(string name) - bool bExists = file_exists(name), - bDir = get_file_type(name)=FILETYPE_DIRECTORY - string exists = iff(bExists?"exists":"does not exist"), - dfs = iff(bExists?iff(bDir?"directory ":"file "):"") - printf(1,"%s%s %s.\n",{dfs,name,exists}) - end procedure +without js -- (file i/o) +procedure check(string name) + bool bExists = file_exists(name), + bDir = get_file_type(name)=FILETYPE_DIRECTORY + string exists = iff(bExists?"exists":"does not exist"), + dfs = iff(bExists?iff(bDir?"directory ":"file "):"") + printf(1,"%s%s %s.\n",{dfs,name,exists}) +end procedure - check("input.txt") - check("docs") - check("/input.txt") - check("/docs") - check("/pagefile.sys") - check("/Program Files (x86)") - - with javascript_semantics - function chernick_carmichael_factors(integer n, m) - sequence res = {6*m + 1, 12*m + 1} - for i=1 to n-2 do - res &= power(2,i) * 9*m + 1 - end for - return res - end function - - include mpfr.e - mpz p = mpz_init() - - function m_prime(atom a) - mpz_set_d(p,a) - return mpz_prime(p) - end function - - function is_chernick_carmichael(integer n, m) - return iff(n==2 ? m_prime(6*m + 1) and m_prime(12*m + 1) - : m_prime(power(2,n-2) * 9*m + 1) and - is_chernick_carmichael(n-1, m)) - end function - - function chernick_carmichael_number(integer n) - integer m = iff(n>4 ? power(2,n-4) : 1), mm = m - while not is_chernick_carmichael(n, mm) do mm += m end while - return {chernick_carmichael_factors(n, mm),mm} - end function - - for n=3 to 9 do - {sequence f, integer m} = chernick_carmichael_number(n) - mpz_set_si(p,1) - for i=1 to length(f) do - mpz_mul_d(p,p,f[i]) - f[i] = sprintf("%d",f[i]) - end for - printf(1,"U(%d,%d): %s = %s\n",{n,m,mpz_get_str(p),join(f," * ")}) - end for - - with javascript_semantics - include mpfr.e - sequence ppp = {3,5,7,11,13,17,19,23} - function primality_pretest(atom k) - for i=1 to length(ppp) do - if remainder(k,ppp[i])=0 then return (k<=23) end if - end for - return true - end function - - function probprime(atom k, mpz n) - mpz_set_d(n, k) - return mpz_prime(n) - end function - - function is_chernick(integer n, atom m, mpz z) - atom t = 9 * m; - if primality_pretest(6 * m + 1) == false then return false end if - if primality_pretest(12 * m + 1) == false then return false end if - for i=1 to n-3 do - if primality_pretest(t*power(2,i) + 1) == false then return false end if - end for - if probprime(6 * m + 1, z) == false then return false end if - if probprime(12 * m + 1, z) == false then return false end if - for i=1 to n-2 do - if probprime(t*power(2,i) + 1, z) == false then return false end if - end for - return true - end function - - procedure main() - atom t0 = time() - mpz z = mpz_init(0) - - for n=3 to 10 do - atom multiplier = iff(n>4 ? power(2,n-4) : 1), k = 1 - if n>5 then multiplier *= 5 end if - - while true do - if n=10 then k += 12564168 end if -- cheat! - atom m = k * multiplier; - if is_chernick(n, m, z) then - printf(1,"a(%d) has m = %d\n", {n, m}) - exit - end if - k += 1 - end while - end for - ?elapsed(time()-t0) - end procedure - main() - - -- demo\rosetta\Cheryls_Birthday.exw - with javascript_semantics - sequence choices = {{5, 15}, {5, 16}, {5, 19}, {6, 17}, {6, 18}, - {7, 14}, {7, 16}, {8, 14}, {8, 15}, {8, 17}} +-- demo\rosetta\Cheryls_Birthday.exw +with javascript_semantics +sequence choices = {{5, 15}, {5, 16}, {5, 19}, {6, 17}, {6, 18}, + {7, 14}, {7, 16}, {8, 14}, {8, 15}, {8, 17}} - sequence mwud = repeat(false,12) -- months with unique days +sequence mwud = repeat(false,12) -- months with unique days - for step=1 to 4 do - sequence {months,days} = columnize(choices) - bool impossible = false - for i=length(choices) to 1 by -1 do - integer {m,d} = choices[i] - switch step do - case 1: mwud[m] += (sum(sq_eq(days,d))=1) - case 2: impossible = mwud[m] - case 3: impossible = (sum(sq_eq(days,d))!=1) - case 4: impossible = (sum(sq_eq(months,m))!=1) - end switch - if impossible then - choices[i..i] = {} - end if - end for - end for - ?choices - - with javascript_semantics - enum MONTH, DAY +with javascript_semantics +enum MONTH, DAY - function unique_month(sequence si, months) - return sum(sq_eq(months,si[MONTH]))=1 - end function +function unique_month(sequence si, months) + return sum(sq_eq(months,si[MONTH]))=1 +end function - function unique_day(sequence si, days) - return sum(sq_eq(days,si[DAY]))=1 - end function +function unique_day(sequence si, days) + return sum(sq_eq(days,si[DAY]))=1 +end function - function month_without_unique_day(sequence si, months_with_unique_day) - return not find(si[MONTH],months_with_unique_day) - end function +function month_without_unique_day(sequence si, months_with_unique_day) + return not find(si[MONTH],months_with_unique_day) +end function - sequence choices = {{5, 15}, {5, 16}, {5, 19}, {6, 17}, {6, 18}, - {7, 14}, {7, 16}, {8, 14}, {8, 15}, {8, 17}} +sequence choices = {{5, 15}, {5, 16}, {5, 19}, {6, 17}, {6, 18}, + {7, 14}, {7, 16}, {8, 14}, {8, 15}, {8, 17}} - -- Albert knows the month but does not know the day. - -- So the month cannot be unique within the choices. - -- However this step would change nothing, hence omit it. - -- (obvs. non_unique_month() would be as above, but !=1) - --choices = filter(choices,non_unique_month,vslice(choices,MONTH)) +-- Albert knows the month but does not know the day. +-- So the month cannot be unique within the choices. +-- However this step would change nothing, hence omit it. +-- (obvs. non_unique_month() would be as above, but !=1) +--choices = filter(choices,non_unique_month,vslice(choices,MONTH)) - -- Albert also knows that Bernard doesn't know the answer. - -- So the month cannot have a unique day. - sequence unique_days = filter(choices,unique_day,vslice(choices,DAY)) - sequence months_with_unique_day = unique(vslice(unique_days,MONTH)) +-- Albert also knows that Bernard doesn't know the answer. +-- So the month cannot have a unique day. +sequence unique_days = filter(choices,unique_day,vslice(choices,DAY)) +sequence months_with_unique_day = unique(vslice(unique_days,MONTH)) - choices = filter(choices,month_without_unique_day,months_with_unique_day) +choices = filter(choices,month_without_unique_day,months_with_unique_day) - -- Bernard now knows the answer. - -- So the day must be unique within the remaining choices. - choices = filter(choices,unique_day,vslice(choices,DAY)) +-- Bernard now knows the answer. +-- So the day must be unique within the remaining choices. +choices = filter(choices,unique_day,vslice(choices,DAY)) - -- Albert now knows the answer too. - -- So the month must be unique within the remaining choices. - choices = filter(choices,unique_month,vslice(choices,MONTH)) +-- Albert now knows the answer too. +-- So the month must be unique within the remaining choices. +choices = filter(choices,unique_month,vslice(choices,MONTH)) - if length(choices)!=1 then crash("Something went wrong!") end if +if length(choices)!=1 then crash("Something went wrong!") end if - include builtins\timedate.e - timedate td = repeat(0,6) - {td[DT_MONTH],td[DT_DAY]} = choices[1] - printf(1,"Cheryl's birthday is %s\n", {format_timedate(td,"Mmmm ddth")}) - - with javascript_semantics - constant animals = {"Rat","Ox","Tiger","Rabbit","Dragon","Snake","Horse","Goat","Monkey","Rooster","Dog","Pig"}, - elements = {"Wood","Fire","Earth","Metal","Water"}, - yinyang = {"yang","yin"}, - years = {1935,1938,1968,1972,1976,2018} +with javascript_semantics +constant animals = {"Rat","Ox","Tiger","Rabbit","Dragon","Snake","Horse","Goat","Monkey","Rooster","Dog","Pig"}, + elements = {"Wood","Fire","Earth","Metal","Water"}, + yinyang = {"yang","yin"}, + years = {1935,1938,1968,1972,1976,2018} - for i=1 to length(years) do - integer year = years[i], - cycle = mod(year-4,60) - string element = elements[floor(mod(cycle,10)/2)+1], - animal = animals[mod(cycle,12)+1], - yy = yinyang[mod(cycle,2)+1] - printf(1,"%d: %s %s; %s, year %d of the cycle.\n", - {year,element,animal,yy,cycle+1}) - end for - list of strings +fcn ceToChineseZodiac(ce_year){ // --> list of strings # encoding: utf-8 var [const] pinyin=SD( // create some static variables, SD is small fixed dictionary "甲","jiă", "乙","yĭ", "丙","bĭng", "丁","dīng", "戊","wù", "己","jĭ", @@ -11,7 +11,7 @@ fcn ceToChineseZodiac(ce_year){ // --> list of strings celestial =T("甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"), terrestrial=T("子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"), animals =T("Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake", - "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig"), + "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig"), elements =T("Wood", "Fire", "Earth", "Metal", "Water"), aspects =T("yang","yin"), ; @@ -28,5 +28,5 @@ fcn ceToChineseZodiac(ce_year){ // --> list of strings branch_han,branch_pinyin := terrestrial[branch_number], pinyin[branch_han]; return(stem_han,branch_han, - stem_pinyin,branch_pinyin, element,animal,aspect) + stem_pinyin,branch_pinyin, element,animal,aspect) } diff --git a/Task/Cholesky-decomposition/Ada/cholesky-decomposition-1.ada b/Task/Cholesky-decomposition/Ada/cholesky-decomposition-1.adb similarity index 100% rename from Task/Cholesky-decomposition/Ada/cholesky-decomposition-1.ada rename to Task/Cholesky-decomposition/Ada/cholesky-decomposition-1.adb diff --git a/Task/Cholesky-decomposition/Ada/cholesky-decomposition-2.ada b/Task/Cholesky-decomposition/Ada/cholesky-decomposition-2.adb similarity index 100% rename from Task/Cholesky-decomposition/Ada/cholesky-decomposition-2.ada rename to Task/Cholesky-decomposition/Ada/cholesky-decomposition-2.adb diff --git a/Task/Cholesky-decomposition/Ada/cholesky-decomposition-3.ada b/Task/Cholesky-decomposition/Ada/cholesky-decomposition-3.adb similarity index 100% rename from Task/Cholesky-decomposition/Ada/cholesky-decomposition-3.ada rename to Task/Cholesky-decomposition/Ada/cholesky-decomposition-3.adb diff --git a/Task/Cholesky-decomposition/EasyLang/cholesky-decomposition.easy b/Task/Cholesky-decomposition/EasyLang/cholesky-decomposition.easy new file mode 100644 index 0000000000..f06a3216a5 --- /dev/null +++ b/Task/Cholesky-decomposition/EasyLang/cholesky-decomposition.easy @@ -0,0 +1,19 @@ +func[][] cholesky a[][] . + n = len a[][] + len r[][] n + for i to n + len r[i][] n + for j to i + s = 0 + for k to j : s += r[i][k] * r[j][k] + if i = j + r[i][j] = sqrt (a[i][i] - s) + else + r[i][j] = 1 / r[j][j] * (a[i][j] - s) + . + . + . + return r[][] +. +print cholesky [ [ 25 15 -5 ] [ 15 18 0 ] [ -5 0 11 ] ] +print cholesky [ [ 18 22 54 42 ] [ 22 70 86 62 ] [ 54 86 174 134 ] [ 42 62 134 106 ] ] diff --git a/Task/Cholesky-decomposition/Excel/cholesky-decomposition.excel b/Task/Cholesky-decomposition/Excel/cholesky-decomposition.excel new file mode 100644 index 0000000000..1586be05f1 --- /dev/null +++ b/Task/Cholesky-decomposition/Excel/cholesky-decomposition.excel @@ -0,0 +1,38 @@ +=LAMBDA(A, + LET( + r, ROWS(A), + sqa, SQRT(INDEX(A,1,1)), + IF( + r=1, + sqa, + REDUCE( + VSTACK(sqa, DROP(TAKE(A,,1),1)/sqa), + SEQUENCE(r-1,,2), + LAMBDA(s, t, + LET( + diag, SQRT(INDEX(A,t,t) - SUMSQ(INDEX(s,t))), + HSTACK( + s, + VSTACK( + EXPAND(0,t-1,1,0), + IF( + t=r, + diag, + REDUCE( + diag, + SEQUENCE(r-t,1,t+1), + LAMBDA(x,y, + VSTACK( + x, + (INDEX(A,y,t) - SUM(INDEX(s,t)*INDEX(s,y))) / diag + ) + ) + ) + ) + ) + ) + ) + ) + ) + ) +) diff --git a/Task/Cholesky-decomposition/Julia/cholesky-decomposition.julia b/Task/Cholesky-decomposition/Julia/cholesky-decomposition.jl similarity index 100% rename from Task/Cholesky-decomposition/Julia/cholesky-decomposition.julia rename to Task/Cholesky-decomposition/Julia/cholesky-decomposition.jl diff --git a/Task/Cholesky-decomposition/Kotlin/cholesky-decomposition.kotlin b/Task/Cholesky-decomposition/Kotlin/cholesky-decomposition.kts similarity index 100% rename from Task/Cholesky-decomposition/Kotlin/cholesky-decomposition.kotlin rename to Task/Cholesky-decomposition/Kotlin/cholesky-decomposition.kts diff --git a/Task/Cholesky-decomposition/OCaml/cholesky-decomposition.ocaml b/Task/Cholesky-decomposition/OCaml/cholesky-decomposition.ml similarity index 100% rename from Task/Cholesky-decomposition/OCaml/cholesky-decomposition.ocaml rename to Task/Cholesky-decomposition/OCaml/cholesky-decomposition.ml diff --git a/Task/Cholesky-decomposition/PascalABC.NET/cholesky-decomposition.pas b/Task/Cholesky-decomposition/PascalABC.NET/cholesky-decomposition.pas new file mode 100644 index 0000000000..94dfe940b1 --- /dev/null +++ b/Task/Cholesky-decomposition/PascalABC.NET/cholesky-decomposition.pas @@ -0,0 +1,51 @@ +function Cholesky(a: array of real): array of real; +begin + var n := Round(Sqrt(a.Length)); + Result := new real[n * n]; + for var i := 0 to n - 1 do + begin + for var j := 0 to i do + begin + var s := 0.0; + for var k := 0 to j - 1 do + s += Result[i * n + k] * Result[j * n + k]; + if i = j then + Result[i * n + j] := Sqrt(a[i * n + i] - s) + else Result[i * n + j] := 1 / Result[j * n + j] * (a[i * n + j] - s); + end; + end; +end; + +procedure ShowMatrix(a: array of real); +begin + var n := Round(Sqrt(a.Length)); + for var i := 0 to n - 1 do + begin + for var j := 0 to n - 1 do + write(a[i * n + j]:10:5); + PrintLn(''); + end; +end; + +begin + var m1 := new real[9]; + m1 := |25.0, 15.0, -5.0, + 15.0, 18.0, 0.0, + -5.0, 0.0, 11.0 |; + var c1 := Cholesky(m1); + ShowMatrix(m1); + println('=>'); + ShowMatrix(c1); + + PrintLn(''); + + var m2: array of real := + |18.0, 22.0, 54.0, 42.0, + 22.0, 70.0, 86.0, 62.0, + 54.0, 86.0, 174.0, 134.0, + 42.0, 62.0, 134.0, 106.0 |; + var c2 := Cholesky(m2); + Showmatrix(m2); + println('=>'); + ShowMatrix(c2); +end. diff --git a/Task/Cholesky-decomposition/Pluto/cholesky-decomposition.pluto b/Task/Cholesky-decomposition/Pluto/cholesky-decomposition.pluto new file mode 100644 index 0000000000..5a31f92f26 --- /dev/null +++ b/Task/Cholesky-decomposition/Pluto/cholesky-decomposition.pluto @@ -0,0 +1,21 @@ +require "matrix" + +local arrays = { + { {25, 15, -5}, + {15, 18, 0}, + {-5, 0, 11} }, + + { {18, 22, 54, 42}, + {22, 70, 86, 62}, + {54, 86, 174, 134}, + {42, 62, 134, 106} } +} + +for arrays as array do + local m = matrix.from(array) + print("Original:") + print(m) + print("\nLower Cholesky factor:") + print(m:cholesky():format("%8.5f")) + print() +end diff --git a/Task/Cholesky-decomposition/PowerShell/cholesky-decomposition.psh b/Task/Cholesky-decomposition/PowerShell/cholesky-decomposition.ps1 similarity index 100% rename from Task/Cholesky-decomposition/PowerShell/cholesky-decomposition.psh rename to Task/Cholesky-decomposition/PowerShell/cholesky-decomposition.ps1 diff --git a/Task/Cholesky-decomposition/Rust/cholesky-decomposition.rust b/Task/Cholesky-decomposition/Rust/cholesky-decomposition.rs similarity index 100% rename from Task/Cholesky-decomposition/Rust/cholesky-decomposition.rust rename to Task/Cholesky-decomposition/Rust/cholesky-decomposition.rs diff --git a/Task/Cholesky-decomposition/Scheme/cholesky-decomposition.scm b/Task/Cholesky-decomposition/Scheme/cholesky-decomposition.scm new file mode 100644 index 0000000000..fbe516a678 --- /dev/null +++ b/Task/Cholesky-decomposition/Scheme/cholesky-decomposition.scm @@ -0,0 +1,55 @@ +(import srfi/231) + +(define (Cholesky A) + ;; Assumes the domain of A is [0,n)\\times [0,n) + (let ((n (interval-upper-bound (array-domain A) 0)) + (A_ (array-getter A)) + (A! (array-setter A))) + (do ((i 0 (+ i 1))) + ((= i n) A) + (let* ((pivot (sqrt (A_ i i))) + (column/row-domain + ;; both will be one-dimensional + (make-interval (vector (+ i 1)) (vector n))) + (column + ;; the column below the (i,i) entry + (specialized-array-share A + column/row-domain + (lambda (k) (values k i)))) + (row + ;; the row to the right of the (i,i) entry + (specialized-array-share A + column/row-domain + (lambda (k) (values i k)))) + (subarray + ;; the subarray to the right and below the (i,i) entry + (array-extract A (make-interval (vector (+ i 1) (+ i 1)) (vector n n))))) + ;; set diagonal value + (A! pivot i i) + ;; compute multipliers + (array-assign! column (array-map (lambda (x) (/ x pivot)) column)) + ;; zero the rest of the ith row, preserving exactness + (array-assign! row (make-array column/row-domain + ;; a zero with the same exactness as pivot + (lambda (j) (- pivot pivot)))) + ;; subtract the outer product of i'th + ;; row and column from the subarray + (array-assign! subarray + (array-map - + subarray + (array-outer-product * column column))))))) + +(define Example-1 + (list*->array 2 '((25 15 -5) + (15 18 0) + (-5 0 11)))) + +(define Example-2 + (list*->array 2 '((18 22 54 42) + (22 70 86 62) + (54 86 174 134) + (42 62 134 106)))) + +(pretty-print (array->list* (Cholesky Example-1))) +(newline) +(pretty-print (array->list* (Cholesky Example-2))) diff --git a/Task/Cholesky-decomposition/Zig/cholesky-decomposition.zig b/Task/Cholesky-decomposition/Zig/cholesky-decomposition.zig new file mode 100644 index 0000000000..39a4ebad30 --- /dev/null +++ b/Task/Cholesky-decomposition/Zig/cholesky-decomposition.zig @@ -0,0 +1,64 @@ +const std = @import("std"); + +fn cholesky(mat: []const f64, n: usize, allocator: std.mem.Allocator) ![]f64 { + const res = try allocator.alloc(f64, mat.len); + @memset(res, 0.0); + + for (0..n) |i| { + for (0..i+1) |j| { + var s: f64 = 0.0; + for (0..j) |k| { + s += res[i * n + k] * res[j * n + k]; + } + + res[i * n + j] = if (i == j) + std.math.sqrt(mat[i * n + i] - s) + else + (1.0 / res[j * n + j] * (mat[i * n + j] - s)); + } + } + return res; +} + +fn showMatrix(matrix: []const f64, n: usize) void { + for (0..n) |i| { + for (0..n) |j| { + std.debug.print("{d:.4}\t", .{matrix[i * n + j]}); + } + std.debug.print("\n", .{}); + } + std.debug.print("\n", .{}); +} + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + const allocator = gpa.allocator(); + defer _ = gpa.deinit(); + + { + const dimension: usize = 3; + const m1 = [_]f64{ + 25.0, 15.0, -5.0, + 15.0, 18.0, 0.0, + -5.0, 0.0, 11.0 + }; + + const res1 = try cholesky(&m1, dimension, allocator); + defer allocator.free(res1); + showMatrix(res1, dimension); + } + + { + const dimension: usize = 4; + const m2 = [_]f64{ + 18.0, 22.0, 54.0, 42.0, + 22.0, 70.0, 86.0, 62.0, + 54.0, 86.0, 174.0, 134.0, + 42.0, 62.0, 134.0, 106.0 + }; + + const res2 = try cholesky(&m2, dimension, allocator); + defer allocator.free(res2); + showMatrix(res2, dimension); + } +} diff --git a/Task/Chowla-numbers/ALGOL-68/chowla-numbers.alg b/Task/Chowla-numbers/ALGOL-68/chowla-numbers.alg index 641726dfd2..6fefcfb901 100644 --- a/Task/Chowla-numbers/ALGOL-68/chowla-numbers.alg +++ b/Task/Chowla-numbers/ALGOL-68/chowla-numbers.alg @@ -1,16 +1,33 @@ BEGIN # find some Chowla numbers ( Chowla n = sum of divisors of n exclusing n and 1 ) # + + # returns the divisor sums of [1 n], the sums exclude 1 and n # + PROC sum divisors = ( INT n )[]INT: + BEGIN + [ 1 : n ]INT sums; + FOR i TO n DO sums[ i ] := 0 OD; + FOR i FROM 2 TO n DO + FOR j FROM i + i BY i TO n DO sums[ j ] +:= i OD + OD; + sums + END # sum divisors # ; + + []INT ds = sum divisors( 10 000 000 ); # get a table of divisor sums for 1..n # + # returs the Chowla number of n # PROC chowla = ( INT n )INT: - BEGIN - INT sum := 0; - FOR i FROM 2 WHILE i * i <= n DO - IF n MOD i = 0 THEN - INT j = n OVER i; - sum +:= i + IF i = j THEN 0 ELSE j FI - FI - OD; - sum - END # chowla # ; + IF n < 2 + THEN 0 + ELIF n <= UPB ds - LWB ds + 1 + THEN ds[ n ] + ELSE INT sum := 0; + FOR i FROM 2 WHILE i * i <= n DO + IF n MOD i = 0 THEN + INT j = n OVER i; + sum +:= i + IF i = j THEN 0 ELSE j FI + FI + OD; + sum + FI # chowla # ; FOR n TO 37 DO print( ( "chowla(", whole( n, 0 ), ") = ", whole( chowla( n ), 0 ), newline ) ) OD; @@ -23,7 +40,7 @@ BEGIN # find some Chowla numbers ( Chowla n = sum of divisors of n exclusing n a FI OD; count := 0; - INT limit = 350 000 000; + INT limit = 35 000 000; INT k := 2, kk := 3; WHILE INT p = k * kk; p <= limit diff --git a/Task/Chowla-numbers/Ada/chowla-numbers.ada b/Task/Chowla-numbers/Ada/chowla-numbers.ada deleted file mode 100644 index 8b9451b145..0000000000 --- a/Task/Chowla-numbers/Ada/chowla-numbers.ada +++ /dev/null @@ -1,70 +0,0 @@ -with Ada.Text_IO; - -procedure Chowla_Numbers is - - function Chowla (N : Positive) return Natural is - Sum : Natural := 0; - I : Positive := 2; - J : Positive; - begin - while I * I <= N loop - if N mod I = 0 then - J := N / I; - Sum := Sum + I + (if I = J then 0 else J); - end if; - I := I + 1; - end loop; - return Sum; - end Chowla; - - procedure Put_37_First is - use Ada.Text_IO; - begin - for A in Positive range 1 .. 37 loop - Put_Line ("chowla(" & A'Image & ") = " & Chowla (A)'Image); - end loop; - end Put_37_First; - - procedure Put_Prime is - use Ada.Text_IO; - Count : Natural := 0; - Power : Positive := 100; - begin - for N in Positive range 2 .. 10_000_000 loop - if Chowla (N) = 0 then - Count := Count + 1; - end if; - if N mod Power = 0 then - Put_Line ("There is " & Count'Image & " primes < " & Power'Image); - Power := Power * 10; - end if; - end loop; - end Put_Prime; - - procedure Put_Perfect is - use Ada.Text_IO; - Count : Natural := 0; - Limit : constant := 350_000_000; - K : Natural := 2; - Kk : Natural := 3; - P : Natural; - begin - loop - P := K * Kk; - exit when P > Limit; - - if Chowla (P) = P - 1 then - Put_Line (P'Image & " is a perfect number"); - Count := Count + 1; - end if; - K := Kk + 1; - Kk := Kk + K; - end loop; - Put_Line ("There are " & Count'Image & " perfect numbers < " & Limit'Image); - end Put_Perfect; - -begin - Put_37_First; - Put_Prime; - Put_Perfect; -end Chowla_Numbers; diff --git a/Task/Chowla-numbers/Ada/chowla-numbers.adb b/Task/Chowla-numbers/Ada/chowla-numbers.adb new file mode 100644 index 0000000000..4f48ba270c --- /dev/null +++ b/Task/Chowla-numbers/Ada/chowla-numbers.adb @@ -0,0 +1,70 @@ +with Ada.Text_IO; + +procedure Chowla_Numbers is + + function Chowla (N : Positive) return Natural is + Sum : Natural := 0; + I : Positive := 2; + J : Positive; + begin + while I * I <= N loop + if N mod I = 0 then + J := N / I; + Sum := Sum + I + (if I = J then 0 else J); + end if; + I := I + 1; + end loop; + return Sum; + end Chowla; + + procedure Put_37_First is + use Ada.Text_IO; + begin + for A in Positive range 1 .. 37 loop + Put_Line ("chowla(" & A'Image & ") = " & Chowla (A)'Image); + end loop; + end Put_37_First; + + procedure Put_Prime is + use Ada.Text_IO; + Count : Natural := 0; + Power : Positive := 100; + begin + for N in Positive range 2 .. 10_000_000 loop + if Chowla (N) = 0 then + Count := Count + 1; + end if; + if N mod Power = 0 then + Put_Line ("There are " & Count'Image & " primes < " & Power'Image); + Power := Power * 10; + end if; + end loop; + end Put_Prime; + + procedure Put_Perfect is + use Ada.Text_IO; + Count : Natural := 0; + Limit : constant := 350_000_000; + K : Natural := 2; + Kk : Natural := 3; + P : Natural; + begin + loop + P := K * Kk; + exit when P > Limit; + + if Chowla (P) = P - 1 then + Put_Line (P'Image & " is a perfect number"); + Count := Count + 1; + end if; + K := Kk + 1; + Kk := Kk + K; + end loop; + Put_Line ("There are " & Count'Image & " perfect numbers < " & Limit'Image); + end Put_Perfect; + +begin + Put_37_First; + Put_Prime; + Put_Perfect; +end Chowla_Numbers; diff --git a/Task/Chowla-numbers/Agena/chowla-numbers.agena b/Task/Chowla-numbers/Agena/chowla-numbers.agena new file mode 100644 index 0000000000..f483192c9a --- /dev/null +++ b/Task/Chowla-numbers/Agena/chowla-numbers.agena @@ -0,0 +1,57 @@ +scope # find some Chowla numbers ( Chowla n = sum of divisors of n exclusing n and 1 ) + + # returns the divisor sums of [1 n], the sums exclude 1 and n + local proc sumDivisors( n :: number ) :: sequence + local constant sums := seq(); + for i to n do sums[ i ] := 0 od; + for i from 2 to n do + for j from i + i to n by i do sums[ j ] +:= i od + od; + return sums + end; + + local constant ds := sumDivisors( 10_000_000 ); + + local proc chowla( n :: number ) :: number # returns the Chowla number of n + local sum := 0; + if n > 0 then + if n <= size ds then + sum := ds[ n ] + else + for i from 2 while i * i <= n do + if n mod i = 0 then + local constant j := n \ i; + sum +:= i + if i = j then 0 else j fi + fi + od + fi + fi; + return sum + end; + + # first 37 chowla numbers + for n to 37 do printf( "chowla(%d) = %d\n", n, chowla( n ) ) od; + + # number of primes up to 10_000_000 + local count, power := 0, 100; + for n from 2 to 10_000_000 do + if chowla( n ) = 0 then count +:= 1 fi; + if n mod power = 0 then + printf( "There are %6d primes < %d\n", count, power ); + power *:= 10 + fi + od; + + # perfect numbers to 35_000_000 + local constant perfectMax := 35_000_000; + count := 0; + local k, kk, p := 2, 3, 6; # p is k * kk; + while p <= perfectMax do + if chowla( p ) = p - 1 then + printf( " %8d is a perfect number\n", p ); + count +:= 1 + fi; + k := kk + 1; kk +:= k; p := k * kk + od; + printf( "There are %d perfect numbers < %d\n", count, perfectMax ) +end diff --git a/Task/Chowla-numbers/EMal/chowla-numbers.emal b/Task/Chowla-numbers/EMal/chowla-numbers.emal index ae58e913ba..cd3aa6dcee 100644 --- a/Task/Chowla-numbers/EMal/chowla-numbers.emal +++ b/Task/Chowla-numbers/EMal/chowla-numbers.emal @@ -1,44 +1,44 @@ -fun chowla = int by int n - int sum = 0 - int j = 0 - for int i = 2; i * i <= n; i++ do - if n % i == 0 do sum += i + when(i == (j = n / i), 0, j) end +fun chowla ← int by int n + int sum ← 0 + int j ← 0 + for int i ← 2; i * i ≤ n; ++i do + if n % i æ 0 do sum += i + when(i æ (j ← n / i), 0, j) end end return sum end -fun sieve = List by int limit - List c = logic[].with(limit) - for int i = 3; i * 3 < limit; i += 2 - if c[i] or chowla(i) != 0 do continue end - for int j = 3 * i; j < limit; j += 2 * i do c[j] = true end +fun sieve ← List by int limit + List c ← logic[].with(limit) + for int i ← 3; i * 3 < limit; i += 2 + if c[i] or chowla(i) ≠ 0 do continue end + for int j ← 3 * i; j < limit; j += 2 * i do c[j] ← true end end return c end # find and display (1 per line) for the 1st 37 integers -for int i = 1; i <= 37; i++ do writeLine("chowla(" + i + ") = " + chowla(i)) end -int count = 1 -int limit = 10000000 -int power = 100 -List c = sieve(limit) -for int i = 3; i < limit; i += 2 - if not c[i] do count++ end - if i == power - 1 - writeLine("Count of primes up to " + power + " = " + count) +for int i ← 1; i ≤ 37; ++i do writeLine("chowla(" + i + ") = ", chowla(i)) end +int count ← 1 +int limit ← 10000000 +int power ← 100 +List c ← sieve(limit) +for int i ← 3; i < limit; i += 2 + if not c[i] do ++count end + if i æ power - 1 + writeLine("Count of primes up to ", power, " = ", count) power *= 10 end end -count = 0 -limit = 35000000 -int k = 2 -int kk = 3 +count ← 0 +limit ← 35000000 +int k ← 2 +int kk ← 3 int p -for int i = 2; ; i++ - if (p = k * kk) > limit do break end - if chowla(p) == p - 1 - writeLine(p + " is a number that is perfect") - count++ +for int i ← 2; ; ++i + if (p ← k * kk) > limit do break end + if chowla(p) æ p - 1 + writeLine(p, " is a number that is perfect") + ++count end - k = kk + 1 + k ← kk + 1 kk += k end -writeLine("There are " + count + " perfect numbers <= 35,000,000") +writeLine("There are ", count, " perfect numbers ≤ 35,000,000") diff --git a/Task/Chowla-numbers/EasyLang/chowla-numbers.easy b/Task/Chowla-numbers/EasyLang/chowla-numbers.easy index 612642b535..3cecf7520f 100644 --- a/Task/Chowla-numbers/EasyLang/chowla-numbers.easy +++ b/Task/Chowla-numbers/EasyLang/chowla-numbers.easy @@ -1,5 +1,4 @@ fastfunc chowla n . - sum = 0 i = 2 while i * i <= n if n mod i = 0 @@ -14,7 +13,7 @@ fastfunc chowla n . . return sum . -proc sieve . c[] . +proc sieve &c[] . i = 3 while i * 3 <= len c[] if c[i] = 0 @@ -29,23 +28,22 @@ proc sieve . c[] . i += 2 . . -proc commatize n . s$ . +func$ comma n . s$[] = strchars n s$ = "" l = len s$[] for i = 1 to len s$[] - if i > 1 and l mod 3 = 0 - s$ &= "," - . + if i > 1 and l mod 3 = 0 : s$ &= "," l -= 1 s$ &= s$[i] . + return s$ . print "chowla number from 1 to 37" for i = 1 to 37 print " " & i & ": " & chowla i . -proc main . . +proc main . print "" len c[] 10000000 count = 1 @@ -53,13 +51,9 @@ proc main . . power = 100 i = 3 while i <= len c[] - if c[i] = 0 - count += 1 - . + if c[i] = 0 : count += 1 if i = power - 1 - commatize power p$ - commatize count c$ - print "There are " & c$ & " primes up to " & p$ + print "There are " & comma count & " primes up to " & comma power power *= 10 . i += 2 @@ -74,15 +68,13 @@ proc main . . p = k * kk until p > limit if chowla p = p - 1 - commatize p s$ - print s$ & " is a perfect number" + print comma p & " is a perfect number" count += 1 . k = kk + 1 kk += k i += 1 . - commatize limit s$ - print "There are " & count & " perfect mumbers up to " & s$ + print "There are " & count & " perfect mumbers up to " & comma limit . main diff --git a/Task/Chowla-numbers/Fennel/chowla-numbers.fennel b/Task/Chowla-numbers/Fennel/chowla-numbers.fennel new file mode 100644 index 0000000000..5bfb4bd8c4 --- /dev/null +++ b/Task/Chowla-numbers/Fennel/chowla-numbers.fennel @@ -0,0 +1,61 @@ +(do ;;; find some Chowla numbers ( Chowla n = sum of divisors of n exclusing n and 1 ) + + (fn sum-divisors [n] + (local sums {}) + (for [i 1 n] (tset sums i 0)) + (for [i 2 n] + (for [j (+ i i) n i] (tset sums j (+ (. sums j) i))) + ) + sums + ) + + (local ds (sum-divisors 10_000_000)) + + (fn chowla [n] ; returns the Chowla number of n + (var sum 0) + (when (> n 0) + (if (<= n (length ds)) + (set sum (. ds n)) + ;else + (for [i 2 (math.floor (math.sqrt n))] + (when (= 0 (% n i)) + (local j (math.floor (/ n i))) + (set sum (+ sum i (if (= i j) 0 j))) + ) + ) + ) + ) + sum + ) + + + ; first 37 chowla numbers + (for [n 1 37] (print (.. "chowla(" n ") = " (chowla n)))) + + ; number of primes up to 10_000_000 + (var (count power) (values 0 100)) + (for [n 2 10_000_000] + (when (= 0 (chowla n)) + (set count (+ count 1)) + ) + (when (= 0 (% n power)) + (print (string.format "There are %6d primes < %d" count power)) + (set power (* power 10)) + ) + ) + + ; perfect numbers to 35_000_000 + (local perfect-max 35_000_000) + (set count 0) + (var (k kk p) (values 2 3 6)) ; p is k * kk + (while (<= p perfect-max) + (when (= (chowla p) (- p 1)) + (print (string.format " %8d is a perfect number" p)) + (set count (+ count 1)) + ) + (set k (+ kk 1)) + (set kk (+ kk k)) + (set p (* kk k)) + ) + (print (.. "There are " count " perfect numbers < " perfect-max)) +) diff --git a/Task/Chowla-numbers/JavaScript/chowla-numbers.js b/Task/Chowla-numbers/JavaScript/chowla-numbers.js new file mode 100644 index 0000000000..1ff725b65f --- /dev/null +++ b/Task/Chowla-numbers/JavaScript/chowla-numbers.js @@ -0,0 +1,79 @@ +// Chowla function: calculates sum of proper divisors of n (excluding n itself) +function chowla(n) { + let sum = 0; + for (let i = 2; i * i <= n; i++) { + if (n % i === 0) { + const j = n / i; + sum += i + (i === j ? 0 : j); + } + } + return sum; +} + +// Sieve function: returns array where true denotes composite, false denotes prime +// Only interested in odd numbers >= 3 +function sieve(limit) { + // True denotes composite, false denotes prime + const c = new Array(limit).fill(false); + + for (let i = 3; i * 3 < limit; i += 2) { + if (!c[i] && chowla(i) === 0) { + for (let j = 3 * i; j < limit; j += 2 * i) { + c[j] = true; + } + } + } + return c; +} + +// Main execution +function main() { + // Part 1: Print chowla values for 1-37 + console.log("Chowla function values for 1-37:"); + for (let i = 1; i <= 37; i++) { + console.log(`chowla(${i}) = ${chowla(i)}`); + } + console.log("\n"); + + // Part 2: Count primes up to powers of 10 + console.log("Prime counting using Chowla's sieve:"); + let count = 1; + const limit = 10000000; // 1e7 + let power = 100; + + const c = sieve(limit); + + for (let i = 3; i < limit; i += 2) { + if (!c[i]) count++; + + if (i === power - 1) { + console.log(`Count of primes up to ${power.toLocaleString()} = ${count.toLocaleString()}`); + power *= 10; + } + } + console.log("\n"); + + // Part 3: Find perfect numbers + console.log("Perfect numbers <= 35,000,000:"); + count = 0; + const perfectLimit = 35000000; + + let k = 2, kk = 3, p; + for (let i = 2; ; i++) { + p = k * kk; + if (p > perfectLimit) break; + + if (chowla(p) === p - 1) { + console.log(`${p.toLocaleString()} is a perfect number`); + count++; + } + + k = kk + 1; + kk += k; + } + + console.log(`\nThere are ${count} perfect numbers <= 35,000,000`); +} + +// Execute the main function +main(); diff --git a/Task/Chowla-numbers/Julia/chowla-numbers.jl b/Task/Chowla-numbers/Julia/chowla-numbers.jl new file mode 100644 index 0000000000..1402756727 --- /dev/null +++ b/Task/Chowla-numbers/Julia/chowla-numbers.jl @@ -0,0 +1,40 @@ +using Primes, Format + +function chowla(n) + if n < 1 + throw("Chowla function argument must be positive") + elseif n < 4 + return zero(n) + else + f = [one(n)] + for (p,e) in factor(n) + f = reduce(vcat, [f*p^j for j in 1:e], init=f) + end + return sum(f) - one(n) - n + end +end + +function countchowlas(n, asperfect=false, verbose=false) + count = 0 + for i in 2:n # 1 is not prime or perfect so skip + chow = chowla(i) + if (asperfect && chow == i - 1) || (!asperfect && chow == 0) + count += 1 + verbose && println("The number $(format(i, commas=true)) is ", asperfect ? "perfect." : "prime.") + end + end + count +end + +function testchowla() + println("The first 37 chowla numbers are:") + for i in 1:37 + println("Chowla($i) is ", chowla(i)) + end + for i in [100, 1000, 10000, 100000, 1000000, 10000000] + println("The count of the primes up to $(format(i, commas=true)) is $(format(countchowlas(i), commas=true))") + end + println("The count of perfect numbers up to 35,000,000 is $(countchowlas(35000000, true, true)).") +end + +testchowla() diff --git a/Task/Chowla-numbers/Julia/chowla-numbers.julia b/Task/Chowla-numbers/Julia/chowla-numbers.julia deleted file mode 100644 index cc27df514d..0000000000 --- a/Task/Chowla-numbers/Julia/chowla-numbers.julia +++ /dev/null @@ -1,40 +0,0 @@ -using Primes, Formatting - -function chowla(n) - if n < 1 - throw("Chowla function argument must be positive") - elseif n < 4 - return zero(n) - else - f = [one(n)] - for (p,e) in factor(n) - f = reduce(vcat, [f*p^j for j in 1:e], init=f) - end - return sum(f) - one(n) - n - end -end - -function countchowlas(n, asperfect=false, verbose=false) - count = 0 - for i in 2:n # 1 is not prime or perfect so skip - chow = chowla(i) - if (asperfect && chow == i - 1) || (!asperfect && chow == 0) - count += 1 - verbose && println("The number $(format(i, commas=true)) is ", asperfect ? "perfect." : "prime.") - end - end - count -end - -function testchowla() - println("The first 37 chowla numbers are:") - for i in 1:37 - println("Chowla($i) is ", chowla(i)) - end - for i in [100, 1000, 10000, 100000, 1000000, 10000000] - println("The count of the primes up to $(format(i, commas=true)) is $(format(countchowlas(i), commas=true))") - end - println("The count of perfect numbers up to 35,000,000 is $(countchowlas(35000000, true, true)).") -end - -testchowla() diff --git a/Task/Chowla-numbers/Kotlin/chowla-numbers.kotlin b/Task/Chowla-numbers/Kotlin/chowla-numbers.kts similarity index 100% rename from Task/Chowla-numbers/Kotlin/chowla-numbers.kotlin rename to Task/Chowla-numbers/Kotlin/chowla-numbers.kts diff --git a/Task/Chowla-numbers/Maxima/chowla-numbers.maxima b/Task/Chowla-numbers/Maxima/chowla-numbers.maxima new file mode 100644 index 0000000000..be58f3e5ab --- /dev/null +++ b/Task/Chowla-numbers/Maxima/chowla-numbers.maxima @@ -0,0 +1,13 @@ +chowla(n) := if(n=1) then 0 else divsum(n)-n-1$ +chowla_seq(n, start) := map(chowla, makelist(i,i,start,n))$ +chowla_seq(37, 1); + +chowla_numprimes(n) := length(sublist_indices(chowla_seq(n, 2), lambda([x], x=0)))$ +map(chowla_numprimes, makelist(10^i, i, 2, 7)); + +chowla_perfects(n) := block( + chowla_list: chowla_seq(n, 1), + is_perfect(x) := if(x>n or x=0) then false else x=chowla_list[x+1], + unique(sublist(chowla_list, is_perfect)+1))$ + +chowla_perfects(10000); diff --git a/Task/Chowla-numbers/PascalABC.NET/chowla-numbers.pas b/Task/Chowla-numbers/PascalABC.NET/chowla-numbers.pas new file mode 100644 index 0000000000..7274f05fc9 --- /dev/null +++ b/Task/Chowla-numbers/PascalABC.NET/chowla-numbers.pas @@ -0,0 +1,54 @@ +function chowla(n: Integer): Integer; +begin + result := 0; + var i := 2; + while i * i <= n do + begin + if n mod i = 0 then + result += i + (if i = n div i then 0 else n div i); + i += 1 + end; +end; + +function sieve(limit: Integer): array of Boolean; +begin + result := new Boolean[limit]; + for var i := 3 to limit div 3 step 2 do + if not result[i] and (chowla(i) = 0) Then + for var j := 3 * i to limit step 2 * i do + result[j] := true; +end; + +begin + for var i := 1 To 37 do + WriteLn('chowla(', i, ') = ', chowla(i)); + + var count := 1; + var limit := 10_000_000; + var power := 100; + var c := sieve(limit); + for var i := 3 To limit Step 2 do + begin + if not c[i] Then count += 1; + if i = power - 1 Then begin + WriteLn('Count of primes up to ', power:8, ' = ', count); + power *= 10; + end; + end; + + count := 0; + limit := 35_000_000; + var k := 2; var kk := 3; + while True do + begin + var p := k * kk; + if p > limit Then break; + if chowla(p) = p - 1 Then begin + WriteLn(p:8, ' is a number that is perfect'); + count += 1; + end; + k := kk + 1; + kk += k; + end; + WriteLn('There are ', count, ' perfect numbers <= 35,000,000') +end. diff --git a/Task/Chowla-numbers/Pluto/chowla-numbers.pluto b/Task/Chowla-numbers/Pluto/chowla-numbers.pluto new file mode 100644 index 0000000000..7170013ac8 --- /dev/null +++ b/Task/Chowla-numbers/Pluto/chowla-numbers.pluto @@ -0,0 +1,57 @@ +do -- find some Chowla numbers ( Chowla n = sum of divisors of n exclusing n and 1 ) + + -- returns the divisor sums of [1 n], the sums exclude 1 and n + local function sumDivisors( n : number ) : table + local sums = {} + for i = 1, n do sums[ i ] = 0 end + for i = 2, n do + for j = i + i, n, i do sums[ j ] += i end + end + return sums + end + + local ds = sumDivisors( 10_000_000 ) + + local function chowla( n : number ) : number -- returns the Chowla number of n + local sum = 0 + if n > 0 then + if n <= # ds then + sum = ds[ n ] + else + for i = 2, math.floor( math.sqrt( n ) ) do + if n % i == 0 then + local j = n // i + sum += i + if i == j then 0 else j end + end + end + end + end + return sum + end + + -- first 37 chowla numbers + for n = 1, 37 do print( $"chowla({n}) = {chowla(n)}" ) end + + -- number of primes up to 10_000_000 + local count, power = 0, 100 + for n = 2, 10_000_000 do + if chowla( n ) == 0 then count += 1 end + if n % power == 0 then + print( string.format( "There are %6d primes < %d", count, power ) ) + power *= 10 + end + end + + -- perfect numbers to 35_000_000 + local perfectMax = 35_000_000 + count = 0 + local k, kk, p = 2, 3, 6 -- p is k * kk + while p <= perfectMax do + if chowla( p ) == p - 1 then + print( string.format( " %8d is a perfect number", p ) ) + count += 1 + end + k = kk + 1; kk += k; p = k * kk + end + print( $"There are {count} perfect numbers < {perfectMax}" ) +end diff --git a/Task/Chowla-numbers/Quackery/chowla-numbers.quackery b/Task/Chowla-numbers/Quackery/chowla-numbers.quackery new file mode 100644 index 0000000000..6fc47e0c39 --- /dev/null +++ b/Task/Chowla-numbers/Quackery/chowla-numbers.quackery @@ -0,0 +1,31 @@ + [ 2 max + dup sqrt+ + iff 0 else [ dup negate ] + unrot + times + [ dup i^ 1+ /mod + 0 = iff + [ i^ 1+ + + swap dip + ] + else drop ] + 1+ - ] is chowla ( n --> n ) + + 37 times + [ say "chowla(" + i^ 1+ dup echo + say ")= " + chowla echo cr ] + cr + ' [ 100 1000 10000 100000 1000000 10000000 ] + witheach + [ 0 over 2 - times + [ i^ 2 + chowla 0 = + ] + say "There are " echo + say " primes less than " + echo cr ] + cr + 35000000 2 - times + [ i^ 2 + dup chowla 1+ = if + [ i^ 2 + echo + say " is perfect" + cr ] ] diff --git a/Task/Chowla-numbers/REXX/chowla-numbers.rexx b/Task/Chowla-numbers/REXX/chowla-numbers.rexx index 54447064f1..7f52a942e8 100644 --- a/Task/Chowla-numbers/REXX/chowla-numbers.rexx +++ b/Task/Chowla-numbers/REXX/chowla-numbers.rexx @@ -1,29 +1,73 @@ -/*REXX program computes/displays chowla numbers (and may count primes & perfect numbers.*/ -parse arg LO HI . /*obtain optional arguments from the CL*/ -if LO=='' | LO=="," then LO= 1 /*Not specified? Then use the default.*/ -perf= LO<0; LO= abs(LO) /*Negative? Then determine if perfect.*/ -if HI=='' | HI=="," then HI= LO /*Not specified? Then use the default.*/ -prim= HI<0; HI= abs(HI) /*Negative? Then determine if a prime.*/ -numeric digits max(9, length(HI) + 1 ) /*use enough decimal digits for // */ -w= length( commas(HI) ) /*W: used in aligning output numbers.*/ -tell= \(prim | perf) /*set boolean value for showing chowlas*/ -p= 0 /*the number of primes found (so far).*/ - do j=LO to HI; #= chowla(j) /*compute the cholwa number for J. */ - if tell then say right('chowla('commas(j)")", w+9) ' = ' right( commas(#), w) - else if #==0 then if j>1 then p= p+1 - if perf then if j-1==# & j>1 then say right(commas(j), w) ' is a perfect number.' - end /*j*/ +-- 21 Feb 2026 +include Setting +numeric digits 12 -if prim & \perf then say 'number of primes found for the range ' commas(LO) " to " , - commas(HI) " (inclusive) is: " commas(p) -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -chowla: procedure; parse arg x; if x<2 then return 0; odd= x // 2 - s=0 /* [↓] use EVEN or ODD integers. ___*/ - do k=2+odd by 1+odd while k*k d then do + say Right(10**e,8) Right(n,8) + d = e + end + if work.i = 0 then + iterate i + if Chowla(i) = 0 then do + n = n+1 + if i > 1 then do + j = i+i + do while j < m + work.j = 0; j = j+i + end + end + end +end +say sep +return + +PerfectNumbers: +procedure expose Divi. Memo. +sep = Copies('-',12) +say sep; say Right('Perfect',12); say sep +k = 2; kk = 3; m = 140e9; n = 0 +do forever + p = k * kk + if p > 140e9 then + leave + if Chowla(p) = p-1 then do + n = n+1 + say Right(p,12) + end + k = kk+1; kk = kk+k +end +say sep +say n 'perfect numbers found below 140e9' +return + +-- Chowla; Xpon; Timer +include Math diff --git a/Task/Chowla-numbers/Rust/chowla-numbers.rust b/Task/Chowla-numbers/Rust/chowla-numbers.rs similarity index 100% rename from Task/Chowla-numbers/Rust/chowla-numbers.rust rename to Task/Chowla-numbers/Rust/chowla-numbers.rs diff --git a/Task/Chowla-numbers/Zig/chowla-numbers.zig b/Task/Chowla-numbers/Zig/chowla-numbers.zig new file mode 100644 index 0000000000..2aac5c07f3 --- /dev/null +++ b/Task/Chowla-numbers/Zig/chowla-numbers.zig @@ -0,0 +1,77 @@ +const std = @import("std"); + +/// Calculates the sum of proper divisors of n (excluding n itself) +fn chowla(n: usize) usize { + var sum: usize = 0; + var i: usize = 2; + while (i * i <= n) : (i += 1) { + if (n % i == 0) { + const j = n / i; + sum += i; + if (i != j) sum += j; + } + } + return sum; +} + +/// Creates a sieve of Eratosthenes for finding primes +/// Returns a slice where true denotes composite, false denotes prime +fn sieve(limit: usize) []bool { + const allocator = std.heap.page_allocator; + const c = allocator.alloc(bool, limit) catch unreachable; + @memset(c, false); + + var i: usize = 3; + while (i * 3 < limit) : (i += 2) { + if (!c[i] and chowla(i) == 0) { + var j: usize = 3 * i; + while (j < limit) : (j += 2 * i) { + c[j] = true; + } + } + } + return c; +} + +pub fn main() void { + // Demonstrate chowla function for numbers 1-37 + var i: usize = 1; + while (i <= 37) : (i += 1) { + std.debug.print("chowla({}) = {}\n", .{ i, chowla(i) }); + } + + // Count primes up to 10 million + const limit = 10_000_000; + const c = sieve(limit); + var count: usize = 1; + var power: usize = 100; + + i = 3; + while (i < limit) : (i += 2) { + if (!c[i]) count += 1; + if (i == power - 1) { + std.debug.print("Count of primes up to {} = {}\n", .{ power, count }); + power *= 10; + } + } + + // Find perfect numbers using the formula: p = k * (k+1) / 2 where + // p is perfect if and only if 2^k - 1 is prime (Mersenne prime) + const perfect_limit = 35_000_000; + var perfect_count: usize = 0; + var k: usize = 2; + var kk: usize = 3; + + while (true) { + const p = k * kk; + if (p > perfect_limit) break; + if (chowla(p) == p - 1) { + std.debug.print("{} is a number that is perfect\n", .{p}); + perfect_count += 1; + } + k = kk + 1; + kk += k; + } + + std.debug.print("There are {} perfect numbers <= 35,000,000\n", .{perfect_count}); +} diff --git a/Task/Church-numerals/Applesoft-BASIC/church-numerals.basic b/Task/Church-numerals/Applesoft-BASIC/church-numerals.basic new file mode 100644 index 0000000000..954ef14625 --- /dev/null +++ b/Task/Church-numerals/Applesoft-BASIC/church-numerals.basic @@ -0,0 +1,29 @@ + 0 DIM OP(13),N(13),X(13,1):READ OP(ZERO),N(ZERO),X(ZERO,0),X(ZERO,1):CN = CN + 1:DATA1,0,0,1 + 1 C = ZERO:GOSUB 10:C=R:GOSUB 10:C=R:GOSUB 10:THREE = R + 2 C = THREE :GOSUB 10:FOUR = R + 3 C = THREE :GOSUB 80:PRINT "THREE -> "R + 4 C = FOUR :GOSUB 80:PRINT "FOUR -> "R + 5 C = THREE:D = FOUR :GOSUB 50:C = R:GOSUB 80:PRINT "THREE + FOUR -> "R + 6 C = THREE:D = FOUR :GOSUB 60:C = R:GOSUB 80:PRINT "THREE * FOUR -> "R + 7 C = THREE:D = FOUR :GOSUB 70:C = R:GOSUB 80:PRINT "THREE ^ FOUR -> "R + 8 C = FOUR :D = THREE:GOSUB 70:C = R:GOSUB 80:PRINT "FOUR ^ THREE -> "R + 9 I = 5 :GOSUB 90:C = R:GOSUB 80:PRINT "5 -> FIVE -> "R;:END +REM SUCC + 10 R = CN:OP(R) = OP(C):N(R) = N(C) + 1:X(R,0) = X(C,0):X(R,1) = X(C,1):CN = CN + 1:RETURN +REM SUM + 20 FOR I = 1 TO N:A = A + B:NEXT I:R = A:RETURN +REM MUL + 30 FOR I = 1 TO N:A = A * B:NEXT I:R = A:RETURN +REM POW + 40 FOR I = 1 TO N:A = A ^ B:NEXT I:R = INT (A):RETURN +REM CHURCH SUM + 50 RES = CN:OP(RES) = 1:N(RES) = 1:X(RES,0) = N(C):X(RES,1) = N(D):CN = CN + 1:R = RES:RETURN +REM CHURCH MUL + 60 RES = CN:OP(RES) = 2:N(RES) = 1:X(RES,0) = N(C):X(RES,1) = N(D):CN = CN + 1:R = RES:RETURN +REM CHURCH POW + 70 RES = CN:OP(RES) = 3:N(RES) = 1:X(RES,0) = N(C):X(RES,1) = N(D):CN = CN + 1:R = RES:RETURN +REM CHURCH TO NUM + 80 N = N(C):A = X(C,0):B = X(C,1):ON OP(C) GOTO 20,30,40:STOP +REM NUM TO CHURCH + 90 R = ZERO:IF I = 0 THEN RETURN + 91 I = I - 1:GOSUB 90:C = R:GOTO 10"SUCC diff --git a/Task/Church-numerals/Binary-Lambda-Calculus/church-numerals.blc b/Task/Church-numerals/Binary-Lambda-Calculus/church-numerals.blc new file mode 100644 index 0000000000..d228e6480d --- /dev/null +++ b/Task/Church-numerals/Binary-Lambda-Calculus/church-numerals.blc @@ -0,0 +1,27 @@ +(let ((zero 0) + (succ (lambda (n f x) + (f (n f x)))) + (one (succ zero)) + (two (succ one)) + (three (succ two)) + (four (succ three)) + (plus (lambda (m n f x) + (m f (n f x)))) + (times (lambda (m n f) + (m (n f)))) + (power (lambda (m n) + (n m))) + (cons (lambda (x y f) + (f x y)))) + (lambda (in) + (cons + (plus three four) + (cons + (times three four) + (cons + (power three four) + (cons + (power four three) + (cons + (power (power two two) (plus two one)) + nil))))))) diff --git a/Task/Church-numerals/Chapel/church-numerals.chapel b/Task/Church-numerals/Chapel/church-numerals.chpl similarity index 100% rename from Task/Church-numerals/Chapel/church-numerals.chapel rename to Task/Church-numerals/Chapel/church-numerals.chpl diff --git a/Task/Church-numerals/Crystal/church-numerals.crystal b/Task/Church-numerals/Crystal/church-numerals.cr similarity index 100% rename from Task/Church-numerals/Crystal/church-numerals.crystal rename to Task/Church-numerals/Crystal/church-numerals.cr diff --git a/Task/Church-numerals/Julia/church-numerals-1.julia b/Task/Church-numerals/Julia/church-numerals-1.jl similarity index 100% rename from Task/Church-numerals/Julia/church-numerals-1.julia rename to Task/Church-numerals/Julia/church-numerals-1.jl diff --git a/Task/Church-numerals/Julia/church-numerals-2.julia b/Task/Church-numerals/Julia/church-numerals-2.jl similarity index 100% rename from Task/Church-numerals/Julia/church-numerals-2.julia rename to Task/Church-numerals/Julia/church-numerals-2.jl diff --git a/Task/Church-numerals/OCaml/church-numerals.ocaml b/Task/Church-numerals/OCaml/church-numerals.ml similarity index 100% rename from Task/Church-numerals/OCaml/church-numerals.ocaml rename to Task/Church-numerals/OCaml/church-numerals.ml diff --git a/Task/Church-numerals/Phix/church-numerals.phix b/Task/Church-numerals/Phix/church-numerals.phix index 3765569a3c..3f885e80e9 100644 --- a/Task/Church-numerals/Phix/church-numerals.phix +++ b/Task/Church-numerals/Phix/church-numerals.phix @@ -1,91 +1,86 @@ -(phixonline)--> - with javascript_semantics +with javascript_semantics - type church(object c) - -- eg {r_add,1,{a,b}} - return sequence(c) and length(c)=3 - and integer(c[1]) and integer(c[2]) - and sequence(c[3]) and length(c[3])=2 - end type +type church(object c) +-- eg {r_add,1,{a,b}} + return sequence(c) and length(c)=3 + and integer(c[1]) and integer(c[2]) + and sequence(c[3]) and length(c[3])=2 +end type - function succ(church c) - -- eg {r_add,1,{a,b}} => {r_add,2,{a,b}} aka a+b -> a+b+b - c = deep_copy(c) - c[2] += 1 - return c - end function +function succ(church c) +-- eg {add,1,{a,b}} => {add,2,{a,b}} aka a+b => a+b+b + c = deep_copy(c) + c[2] += 1 + return c +end function - -- three normal integer-handling routines... - function add(integer n, a, b) - for i=1 to n do - a += b - end for - return a - end function - constant r_add = routine_id("add") +-- three normal integer-handling routines... +function add(integer n, a, b) + for i=1 to n do + a += b + end for + return a +end function - function mul(integer n, a, b) - for i=1 to n do - a *= b - end for - return a - end function - constant r_mul = routine_id("mul") +function mul(integer n, a, b) + for i=1 to n do + a *= b + end for + return a +end function - function pow(integer n, a, b) - for i=1 to n do - a = power(a,b) - end for - return a - end function - constant r_pow = routine_id("pow") +function pow(integer n, a, b) + for i=1 to n do + a = power(a,b) + end for + return a +end function - -- ...and three church constructors to match - -- (no maths here, just pure static data) - function addch(church c, d) - church res = {r_add,1,{c,d}} - return res - end function +-- ...and three church constructors to match +-- (no maths here, just pure static data) +function addch(church c, d) + church res = {add,1,{c,d}} + return res +end function - function mulch(church c, d) - church res = {r_mul,1,{c,d}} - return res - end function +function mulch(church c, d) + church res = {mul,1,{c,d}} + return res +end function - function powch(church c, d) - church res = {r_pow,1,{c,d}} - return res - end function +function powch(church c, d) + church res = {pow,1,{c,d}} + return res +end function - function tointch(church c) - -- note this is where the bulk of any processing happens - {integer rid, integer n, object x} = c - x = deep_copy(x) - for i=1 to length(x) do - if church(x[i]) then x[i] = tointch(x[i]) end if - end for - -- return call_func(rid,n&x) - x = deep_copy({n})&deep_copy(x) - return call_func(rid,x) - end function +function tointch(church c) +-- note this is where the bulk of any processing happens + {integer rid, integer n, object x} = c + x = deep_copy(x) + for i=1 to length(x) do + if church(x[i]) then x[i] = tointch(x[i]) end if + end for +-- return call_func(rid,n&x) + x = deep_copy({n})&deep_copy(x) + return call_func(rid,x) +end function - constant church zero = {r_add,0,{0,1}} +constant church zero = {add,0,{0,1}} - function inttoch(integer i) - if i=0 then - return zero - else - return succ(inttoch(i-1)) - end if - end function +function inttoch(integer i) + if i=0 then + return zero + else + return succ(inttoch(i-1)) + end if +end function - church three = succ(succ(succ(zero))), - four = succ(three) - printf(1,"three -> %d\n",tointch(three)) - printf(1,"four -> %d\n",tointch(four)) - printf(1,"three + four -> %d\n",tointch(addch(three,four))) - printf(1,"three * four -> %d\n",tointch(mulch(three,four))) - printf(1,"three ^ four -> %d\n",tointch(powch(three,four))) - printf(1,"four ^ three -> %d\n",tointch(powch(four,three))) - printf(1,"5 -> five -> %d\n",tointch(inttoch(5))) - - with javascript_semantics - constant tests = {{0.1234, 0.9876, 0.8765, 0.2345, 2.0}, - {0.0000, 2.0000, 0.0000, 0.0000, 1.0}, - {0.1234, 0.9876, 0.1234, 0.9876, 2.0}, - {0.1234, 0.9876, 0.8765, 0.2345, 0.5}, - {0.1234, 0.9876, 0.1234, 0.9876, 0.0}} - for i=1 to length(tests) do - atom {x1,y1,x2,y2,r} = tests[i], - xd = x2-x1, yd = y1-y2, - s2 = xd*xd+yd*yd, sep = sqrt(s2), - xh = (x1+x2)/2, yh = (y1+y2)/2 - string txt - if sep=0 then - txt = "same points/"&iff(r=0?"radius is zero":"infinite solutions") - elsif sep=2*r then - txt = sprintf("opposite ends of diameter with centre {%.4f,%.4f}",{xh,yh}) - elsif sep>2*r then - txt = sprintf("too far apart (%.4f > %.4f)",{sep,2*r}) - else - atom md = sqrt(r*r-s2/4), xs = md*xd/sep, ys = md*yd/sep - txt = sprintf("{%.4f,%.4f} and {%.4f,%.4f}",{xh+ys,yh+xs,xh-ys,yh-xs}) - end if - printf(1,"points {%.4f,%.4f}, {%.4f,%.4f} with radius %.1f ==> %s\n",{x1,y1,x2,y2,r,txt}) - end for - - with javascript_semantics - function circular(integer p) - integer len = length(sprintf("%d",p)), - pow = power(10,len-1), - p0 = p - for i=1 to len-1 do - p = pow*remainder(p,10)+floor(p/10) - if p<p0 or not is_prime(p) then return false end if - end for - return true - end function +with javascript_semantics +function circular(integer p) + integer len = length(sprintf("%d",p)), + pow = power(10,len-1), + p0 = p + for i=1 to len-1 do + p = pow*remainder(p,10)+floor(p/10) + if psequence c = {} - integer n = 1 - while length(c)<19 do - integer p = get_prime(n) - if circular(p) then c &= p end if - n += 1 - end while - printf(1,"The first 19 circular primes are:\n%v\n\n",{c}) +sequence c = {} +integer n = 1 +while length(c)<19 do + integer p = get_prime(n) + if circular(p) then c &= p end if + n += 1 +end while +printf(1,"The first 19 circular primes are:\n%v\n\n",{c}) - include mpfr.e - procedure repunit(mpz z, integer n) - mpz_set_str(z,repeat('1',n)) - end procedure - - c = {} - n = 7 - mpz z = mpz_init() - while length(c)<4 do - repunit(z,n) - if mpz_prime(z) then - c = append(c,sprintf("R(%d)",n)) - end if - n += 1 - end while - printf(1,"The next 4 circular primes, in repunit format, are:\n%s\n\n",{join(c)}) - - constant t = {5003, 9887, 15073, 25031, 35317, 49081} - printf(1,"The following repunits are probably circular primes:\n") - for i=1 to length(t) do - integer ti = t[i] - atom t0 = time() - repunit(z,ti) - bool bPrime = mpz_prime(z,1) - printf(1,"R(%d) : %t (%s)\n", {ti, bPrime, elapsed(time()-t0)}) - end for - - with javascript_semantics - function bruteForceClosestPair(sequence s) - atom {x1,y1} = s[1], {x2,y2} = s[2], - dx = x1-x2, dy = y1-y2, - mind = dx*dx+dy*dy - sequence minp = s[1..2] - for i=1 to length(s)-1 do - {x1,y1} = s[i] - for j=i+1 to length(s) do - {x2,y2} = s[j] - dx = x1-x2 - dx = dx*dx - if dx<mind then - dy = y1-y2 - dx += dy*dy - if dx<mind then - mind = dx - minp = {s[i],s[j]} - end if - end if - end for - end for - return {sqrt(mind),minp} - end function +with javascript_semantics +function bruteForceClosestPair(sequence s) + atom {x1,y1} = s[1], {x2,y2} = s[2], + dx = x1-x2, dy = y1-y2, + mind = dx*dx+dy*dy + sequence minp = s[1..2] + for i,si in s to length(s)-1 do + {x1,y1} = si + for sj in s from i+1 do + {x2,y2} = sj + dx = x1-x2 + dx = dx*dx + if dxsequence testset = sq_rnd(repeat({1,1},10000)) - atom t0 = time() - {atom d, sequence points} = bruteForceClosestPair(testset) - -- (Sorting the final point pair makes brute/dc more likely to tally. Note however - -- when >1 equidistant pairs exist, brute and dc may well return different pairs; - -- it is only a problem if they decide to return different minimum distances.) - atom {{x1,y1},{x2,y2}} = sort(deep_copy(points)) - printf(1,"Closest pair: {%f,%f} {%f,%f}, distance=%f (%3.2fs)\n",{x1,y2,x2,y2,d,time()-t0}) +sequence testset = sq_rnd(repeat({1,1},10000)) +atom t0 = time() +atom {d, {{x1,y1},{x2,y2}}} = bruteForceClosestPair(testset) +-- (Sorting the final point pair makes brute/dc more likely to tally. Note however +-- when >1 equidistant pairs exist, brute and dc may well return different pairs; +-- it is only a problem if they decide to return different minimum distances.) +printf(1,"Closest pair: {%f,%f} {%f,%f}, distance=%f (%3.2fs)\n",{x1,y2,x2,y2,d,time()-t0}) - t0 = time() - constant X = 1, Y = 2 - sequence xP = sort(deep_copy(testset)) +t0 = time() +constant X = 1, Y = 2 +sequence xP = sort(deep_copy(testset)), + yP = sort_columns(deep_copy(testset),{Y}) - function byY(sequence p1, p2) - return compare(p1[Y],p2[Y]) - end function - sequence yP = custom_sort(routine_id("byY"),deep_copy(testset)) +function distsq(sequence p1,p2) + atom {x1,y1} = p1, {x2,y2} = p2 + x1 -= x2 + y1 -= y2 + return x1*x1 + y1*y1 +end function - function distsq(sequence p1,p2) - atom {x1,y1} = p1, {x2,y2} = p2 - x1 -= x2 - y1 -= y2 - return x1*x1 + y1*y1 - end function +function closestPair(sequence xP, yP) +-- where xP is P(1) .. P(N) sorted by x coordinate, and +-- yP is P(1) .. P(N) sorted by y coordinate (ascending order) + integer N = length(xP), + midN = floor(N/2) + assert(length(yP)=N) + if N<=3 then + return bruteForceClosestPair(xP) + end if + sequence xL = xP[1..midN], + xR = xP[midN+1..N], + yL = {}, + yR = {} + atom xm = xP[midN][X] + for yi in yP do + if yi[X]<=xm then + yL = append(yL,yi) + else + yR = append(yR,yi) + end if + end for + {atom dmin, sequence pairMin} = min(closestPair(xL, yL), + closestPair(xR, yR)) + sequence yS = {} + for yi in yP do + if abs(xm-yi[X])=dmin then exit end if + d = distsq(yk,yi) + if dfunction closestPair(sequence xP, yP) - -- where xP is P(1) .. P(N) sorted by x coordinate, and - -- yP is P(1) .. P(N) sorted by y coordinate (ascending order) - integer N = length(xP), - midN = floor(N/2) - assert(length(yP)=N) - if N<=3 then - return bruteForceClosestPair(xP) - end if - sequence xL = xP[1..midN], - xR = xP[midN+1..N], - yL = {}, - yR = {} - atom xm = xP[midN][X] - for i=1 to N do - if yP[i][X]<=xm then - yL = append(yL,yP[i]) - else - yR = append(yR,yP[i]) - end if - end for - {atom dL, sequence pairL} = closestPair(xL, yL) - {atom dR, sequence pairR} = closestPair(xR, yR) - {atom dmin, sequence pairMin} = min({dL, pairL},{dR, pairR}) - sequence yS = {} - for i=1 to length(yP) do - if abs(xm-yP[i][X])<dmin then - yS = append(yS,yP[i]) - end if - end for - integer nS = length(yS) - {atom closest, sequence cPair} = {dmin*dmin, pairMin} - for i=1 to nS-1 do - integer k = i + 1 - while k<=nS and (yS[k][Y]-yS[i][Y])<dmin do - d = distsq(yS[k],yS[i]) - if d<closest then - {closest, cPair} = {d, {yS[k], yS[i]}} - end if - k += 1 - end while - end for - return {sqrt(closest), cPair} - end function - - {d,points} = closestPair(xP,yP) - {{x1,y1},{x2,y2}} = sort(deep_copy(points)) -- (see note above) - printf(1,"Closest pair: {%f,%f} {%f,%f}, distance=%f (%3.2fs)\n",{x1,y2,x2,y2,d,time()-t0}) - +(phixonline) with javascript_semantics sequence collection = {} collection = append(collection,"one") collection = prepend(collection,2) ? collection -- {2,"one"} - +(phixonline) with javascript_semantics setd("one",0) setd(2,0) @@ -7,4 +7,3 @@ return 1 end function traverse_dict(routine_id("visitor")) -- shows 2, "one" - - with javascript_semantics - function colourful(integer n) - if n<10 then return n>=0 end if - sequence digits = sq_sub(sprintf("%d",n),'0'), - ud = unique(deep_copy(digits)) - integer ln = length(digits) - if ud[1]<=1 or length(ud)!=ln then return false end if - for i=1 to ln-1 do - for j=i+1 to ln do - atom prod = product(digits[i..j]) - if find(prod,ud) then return false end if - ud &= prod - end for - end for - return true - end function +with javascript_semantics +function colourful(integer n) + if n<10 then return n>=0 end if + sequence digits = sq_sub(sprintf("%d",n),'0'), + ud = unique(deep_copy(digits)) + integer ln = length(digits) + if ud[1]<=1 or length(ud)!=ln then return false end if + for i=1 to ln-1 do + for j=i+1 to ln do + atom prod = product(digits[i..j]) + if find(prod,ud) then return false end if + ud &= prod + end for + end for + return true +end function - atom t0 = time() - sequence cn = apply(true,sprintf,{{"%2d"},filter(tagset(100,0),colourful)}) - printf(1,"The %d colourful numbers less than 100 are:\n%s\n", - {length(cn),join_by(cn,1,10," ")}) +atom t0 = time() +sequence cn = apply(true,sprintf,{{"%2d"},filter(tagset(100,0),colourful)}) +printf(1,"The %d colourful numbers less than 100 are:\n%s\n", + {length(cn),join_by(cn,1,10," ")}) - sequence count = repeat(0,8), - used = repeat(false,10) - integer largestcn = 0 +sequence count = repeat(0,8), + used = repeat(false,10) +integer largestcn = 0 - procedure count_colourful(integer taken=0, string n="") - if taken=0 then - for digit='0' to '9' do - integer dx = digit-'0'+1 - used[dx] = true - count_colourful(iff(digit<'2'?9:1),""&digit) - used[dx] = false - end for - else - integer nn = to_integer(n) - if colourful(nn) then - integer ln = length(n) - count[ln] += 1 - if nn>largestcn then largestcn = nn end if - end if - if taken<9 then - for digit='2' to '9' do - integer dx = digit-'0'+1 - if not used[dx] then - used[dx] = true - count_colourful(taken+1,n&digit) - used[dx] = false - end if - end for - end if - end if - end procedure - count_colourful() - printf(1,"The largest possible colourful number is: %,d\n\n",largestcn) - atom pow = 10 - for dc=1 to length(count) do - printf(1," %d digit colourful number count: %,6d - %7.3f%%\n", - {dc, count[dc], 100*count[dc]/pow}) - pow = iff(pow=10?90:pow*10) - end for - printf(1,"\nTotal colourful numbers: %,d\n", sum(count)) - ?elapsed(time()-t0) - n ) + + [ dip dup - ! dip ! / ] is p ( n n --> n ) + + [ tuck p swap ! / ] is c ( n n --> n ) + + ' [ [ 1 0 ] [ 12 4 ] [ 60 20 ] [ 105 103 ] [ 15000 333 ] ] + witheach + [ unpack 2dup + say " P(" + swap echo say "," echo + say ") = " + p shorten echo$ cr ] + cr + ' [ [ 10 5 ] [ 60 30 ] [ 50 48 ] [ 900 675 ] [ 970 730 ] ] + witheach + [ unpack 2dup + say " C(" + swap echo say "," echo + say ") = " + c shorten echo$ cr ] diff --git a/Task/Combinations-and-permutations/Rust/combinations-and-permutations.rust b/Task/Combinations-and-permutations/Rust/combinations-and-permutations.rs similarity index 100% rename from Task/Combinations-and-permutations/Rust/combinations-and-permutations.rust rename to Task/Combinations-and-permutations/Rust/combinations-and-permutations.rs diff --git a/Task/Combinations-and-permutations/Scheme/combinations-and-permutations.ss b/Task/Combinations-and-permutations/Scheme/combinations-and-permutations.scm similarity index 100% rename from Task/Combinations-and-permutations/Scheme/combinations-and-permutations.ss rename to Task/Combinations-and-permutations/Scheme/combinations-and-permutations.scm diff --git a/Task/Combinations-and-permutations/Uiua/combinations-and-permutations.uiua b/Task/Combinations-and-permutations/Uiua/combinations-and-permutations.uiua new file mode 100644 index 0000000000..ec81fca266 --- /dev/null +++ b/Task/Combinations-and-permutations/Uiua/combinations-and-permutations.uiua @@ -0,0 +1,15 @@ +P ← /×+1˜↙⇡⊙¯ # Simple Perm calc. +C ← ÷/×+1⇡⤙P # Simple Comb calc. +# Better version: casts out common factors first. +C ← ( + AllFactors ← map⊕(⊃⊢⧻)⊸⊛▽⊸>₁/⊂(°/×) + ⊃(+1⇡◌|+1˜↙⇡⊙¯) # Collect numerator, denominator terms. + ⍆◴⊂◡∩(⊙◌°map)∩AllFactors # Identify common factors. + /×ⁿ⤚(-∩⌞≡⬚0get⊙¤⊙⊙¤) # Cast out, mult +) +≡⌞P 12 ↘1⇡12 +≡⌞C 60 ×10↘1⇡6 + +P 105 103 +P 15000 333 +C 900 674 diff --git a/Task/Combinations-and-permutations/VBScript/combinations-and-permutations.vb b/Task/Combinations-and-permutations/VBScript/combinations-and-permutations.vbs similarity index 100% rename from Task/Combinations-and-permutations/VBScript/combinations-and-permutations.vb rename to Task/Combinations-and-permutations/VBScript/combinations-and-permutations.vbs diff --git a/Task/Combinations-with-repetitions/Ada/combinations-with-repetitions.ada b/Task/Combinations-with-repetitions/Ada/combinations-with-repetitions.adb similarity index 100% rename from Task/Combinations-with-repetitions/Ada/combinations-with-repetitions.ada rename to Task/Combinations-with-repetitions/Ada/combinations-with-repetitions.adb diff --git a/Task/Combinations-with-repetitions/Crystal/combinations-with-repetitions.crystal b/Task/Combinations-with-repetitions/Crystal/combinations-with-repetitions.cr similarity index 100% rename from Task/Combinations-with-repetitions/Crystal/combinations-with-repetitions.crystal rename to Task/Combinations-with-repetitions/Crystal/combinations-with-repetitions.cr diff --git a/Task/Combinations-with-repetitions/DuckDB/combinations-with-repetitions.duckdb b/Task/Combinations-with-repetitions/DuckDB/combinations-with-repetitions.duckdb new file mode 100644 index 0000000000..b2312e949b --- /dev/null +++ b/Task/Combinations-with-repetitions/DuckDB/combinations-with-repetitions.duckdb @@ -0,0 +1,49 @@ +create or replace function choose(lst,k) as table ( + with recursive cte as ( + select 0 as ix, + lst[0:0] as combination -- i.e. an empty array of the correct type + union all + select ix+1, combination || [ lst[j] ] + from cte, range(ix+1, 1+length(lst) ) _(j) + where length(combination) < k + ) + select combination + from cte + where ix = k +); + +# Assume 0 0 s$ = "" @@ -14,7 +14,7 @@ proc output . . print s$ . . -proc combine pos val . . +proc combine pos val . if pos > k output else diff --git a/Task/Combinations-with-repetitions/Elixir/combinations-with-repetitions.elixir b/Task/Combinations-with-repetitions/Elixir/combinations-with-repetitions.ex similarity index 100% rename from Task/Combinations-with-repetitions/Elixir/combinations-with-repetitions.elixir rename to Task/Combinations-with-repetitions/Elixir/combinations-with-repetitions.ex diff --git a/Task/Combinations-with-repetitions/Jq/combinations-with-repetitions-1.jq b/Task/Combinations-with-repetitions/Jq/combinations-with-repetitions-1.jq index 3972206ac5..bb25c96913 100644 --- a/Task/Combinations-with-repetitions/Jq/combinations-with-repetitions-1.jq +++ b/Task/Combinations-with-repetitions/Jq/combinations-with-repetitions-1.jq @@ -6,3 +6,5 @@ def pick(n): else ([.[m]] + pick(n-1; m)), pick(n; m+1) end; pick(n;0) ; + +def count(s): reduce s as $_ (0; .+1); diff --git a/Task/Combinations-with-repetitions/Jq/combinations-with-repetitions-2.jq b/Task/Combinations-with-repetitions/Jq/combinations-with-repetitions-2.jq index 6c2692b448..50f06bd1e4 100644 --- a/Task/Combinations-with-repetitions/Jq/combinations-with-repetitions-2.jq +++ b/Task/Combinations-with-repetitions/Jq/combinations-with-repetitions-2.jq @@ -1,4 +1,4 @@ - "Pick 2:", +"Pick 2:", (["iced", "jam", "plain"] | pick(2)), - ([[range(0;10)] | pick(3)] | length) as $n - | "There are \($n) ways to pick 3 objects with replacement from 10." + (count( [range(0;10)] | pick(3)) as $n + | "There are \($n) ways to pick 3 objects with replacement from 10.") diff --git a/Task/Combinations-with-repetitions/Julia/combinations-with-repetitions.julia b/Task/Combinations-with-repetitions/Julia/combinations-with-repetitions.jl similarity index 100% rename from Task/Combinations-with-repetitions/Julia/combinations-with-repetitions.julia rename to Task/Combinations-with-repetitions/Julia/combinations-with-repetitions.jl diff --git a/Task/Combinations-with-repetitions/Kotlin/combinations-with-repetitions.kotlin b/Task/Combinations-with-repetitions/Kotlin/combinations-with-repetitions.kts similarity index 100% rename from Task/Combinations-with-repetitions/Kotlin/combinations-with-repetitions.kotlin rename to Task/Combinations-with-repetitions/Kotlin/combinations-with-repetitions.kts diff --git a/Task/Combinations-with-repetitions/OCaml/combinations-with-repetitions-1.ocaml b/Task/Combinations-with-repetitions/OCaml/combinations-with-repetitions-1.ml similarity index 100% rename from Task/Combinations-with-repetitions/OCaml/combinations-with-repetitions-1.ocaml rename to Task/Combinations-with-repetitions/OCaml/combinations-with-repetitions-1.ml diff --git a/Task/Combinations-with-repetitions/OCaml/combinations-with-repetitions-2.ocaml b/Task/Combinations-with-repetitions/OCaml/combinations-with-repetitions-2.ml similarity index 100% rename from Task/Combinations-with-repetitions/OCaml/combinations-with-repetitions-2.ocaml rename to Task/Combinations-with-repetitions/OCaml/combinations-with-repetitions-2.ml diff --git a/Task/Combinations-with-repetitions/PascalABC.NET/combinations-with-repetitions.pas b/Task/Combinations-with-repetitions/PascalABC.NET/combinations-with-repetitions.pas new file mode 100644 index 0000000000..be42b9c098 --- /dev/null +++ b/Task/Combinations-with-repetitions/PascalABC.NET/combinations-with-repetitions.pas @@ -0,0 +1,8 @@ +## +var t:=|'iced', 'jam', 'plain'|; +var p:=t.CartesianPower(2).Where(t->t[0]<=t[1]); +write($'{p.Count}'); +Print(':'); +p.Println; +write((1..10).CartesianPower(3).Where(t->(t[0]<=t[1])and(t[1]<=t[2])).count); +Print(': Choices of 3 from 10'); diff --git a/Task/Combinations-with-repetitions/Pluto/combinations-with-repetitions.pluto b/Task/Combinations-with-repetitions/Pluto/combinations-with-repetitions.pluto new file mode 100644 index 0000000000..a5fb293809 --- /dev/null +++ b/Task/Combinations-with-repetitions/Pluto/combinations-with-repetitions.pluto @@ -0,0 +1,15 @@ +require "perm" +local fmt = require "fmt" + +local function rep(a, multiple) + local aa = {} + for i = 1, #a do + for _ = 1, multiple do aa:insert(a[i]) end + end + return aa +end + +local a = {"iced", "jam", "plain"} +fmt.lprint(comb.list(rep(a, 2), 2, true)) +a = range(1, 10) +print(#comb.list(rep(a, 3), 3, true)) diff --git a/Task/Combinations-with-repetitions/Rust/combinations-with-repetitions.rust b/Task/Combinations-with-repetitions/Rust/combinations-with-repetitions.rs similarity index 100% rename from Task/Combinations-with-repetitions/Rust/combinations-with-repetitions.rust rename to Task/Combinations-with-repetitions/Rust/combinations-with-repetitions.rs diff --git a/Task/Combinations-with-repetitions/Scheme/combinations-with-repetitions-1.ss b/Task/Combinations-with-repetitions/Scheme/combinations-with-repetitions-1.scm similarity index 100% rename from Task/Combinations-with-repetitions/Scheme/combinations-with-repetitions-1.ss rename to Task/Combinations-with-repetitions/Scheme/combinations-with-repetitions-1.scm diff --git a/Task/Combinations-with-repetitions/Scheme/combinations-with-repetitions-2.ss b/Task/Combinations-with-repetitions/Scheme/combinations-with-repetitions-2.scm similarity index 100% rename from Task/Combinations-with-repetitions/Scheme/combinations-with-repetitions-2.ss rename to Task/Combinations-with-repetitions/Scheme/combinations-with-repetitions-2.scm diff --git a/Task/Combinations-with-repetitions/VBScript/combinations-with-repetitions.vb b/Task/Combinations-with-repetitions/VBScript/combinations-with-repetitions.vbs similarity index 100% rename from Task/Combinations-with-repetitions/VBScript/combinations-with-repetitions.vb rename to Task/Combinations-with-repetitions/VBScript/combinations-with-repetitions.vbs diff --git a/Task/Combinations/APL/combinations-1.apl b/Task/Combinations/APL/combinations-1.apl new file mode 100644 index 0000000000..1fde8720bc --- /dev/null +++ b/Task/Combinations/APL/combinations-1.apl @@ -0,0 +1,7 @@ + comb←{(⍺=0)∨⍺=⍵:⌷⍉⍪⍳⍺ ⋄ (0,1+(⍺-1)∇ ⍵-1)⍪1+⍺ ∇ ⍵-1} + 4 comb 5 +0 1 2 3 +0 1 2 5 +0 1 4 5 +0 3 4 5 +2 3 4 5 diff --git a/Task/Combinations/APL/combinations-2.apl b/Task/Combinations/APL/combinations-2.apl new file mode 100644 index 0000000000..c0eebd9932 --- /dev/null +++ b/Task/Combinations/APL/combinations-2.apl @@ -0,0 +1,7 @@ +comb←{ + ⍺{ + 0=⍺:⊂⍬ + 0=≢⍵:⍬ + ((⊃⍵),¨(⍺-1)∇r),⍺∇r←1↓⍵ + }⍳⍵ +} diff --git a/Task/Combinations/Ada/combinations-1.ada b/Task/Combinations/Ada/combinations-1.adb similarity index 100% rename from Task/Combinations/Ada/combinations-1.ada rename to Task/Combinations/Ada/combinations-1.adb diff --git a/Task/Combinations/Ada/combinations-2.ada b/Task/Combinations/Ada/combinations-2.adb similarity index 100% rename from Task/Combinations/Ada/combinations-2.ada rename to Task/Combinations/Ada/combinations-2.adb diff --git a/Task/Combinations/Crystal/combinations-1.crystal b/Task/Combinations/Crystal/combinations-1.cr similarity index 100% rename from Task/Combinations/Crystal/combinations-1.crystal rename to Task/Combinations/Crystal/combinations-1.cr diff --git a/Task/Combinations/Crystal/combinations-2.crystal b/Task/Combinations/Crystal/combinations-2.cr similarity index 100% rename from Task/Combinations/Crystal/combinations-2.crystal rename to Task/Combinations/Crystal/combinations-2.cr diff --git a/Task/Combinations/DuckDB/combinations.duckdb b/Task/Combinations/DuckDB/combinations.duckdb new file mode 100644 index 0000000000..714f42167e --- /dev/null +++ b/Task/Combinations/DuckDB/combinations.duckdb @@ -0,0 +1,22 @@ +CREATE OR REPLACE FUNCTION combinations(n, k) as table ( + WITH RECURSIVE cte(current, remaining) AS ( + -- start with empty combination and the full list + SELECT + [], + range(1, n + 1) + UNION ALL + -- recursive case: add one item to the current combination + SELECT + current || remaining[j:j], + remaining[j+1:] + FROM cte, range(1, length(remaining)+1) _(j) + WHERE length(current) < k + ) + SELECT current AS combination + FROM cte + WHERE length(current) = k +); + +## Example: +FROM combinations(5,3) +ORDER BY combination; diff --git a/Task/Combinations/EasyLang/combinations.easy b/Task/Combinations/EasyLang/combinations.easy index 17b909ce4a..34c4b35b4d 100644 --- a/Task/Combinations/EasyLang/combinations.easy +++ b/Task/Combinations/EasyLang/combinations.easy @@ -2,14 +2,14 @@ n = 5 m = 3 len result[] m # -proc combinations pos val . . - if pos <= m - for i = val to n - m - result[pos] = pos + i - combinations pos + 1 i - . - else +proc combinations pos val . + if pos > m print result[] + return + . + for i = val to pos + n - m + result[pos] = i + combinations pos + 1 i + 1 . . -combinations 1 0 +combinations 1 1 diff --git a/Task/Combinations/Elena/combinations.elena b/Task/Combinations/Elena/combinations.elena index c4903032f5..2cd24012e3 100644 --- a/Task/Combinations/Elena/combinations.elena +++ b/Task/Combinations/Elena/combinations.elena @@ -10,13 +10,13 @@ Numbers(n) ^ Array.allocate(n).populate::(int n => n) } -public program() +public Program() { var numbers := Numbers(N); Combinator.new(M, numbers).forEach::(row) { - console.printLine(row.toString()) + Console.printLine(row.toString()) }; - console.readChar() + Console.readChar() } diff --git a/Task/Combinations/Elixir/combinations.elixir b/Task/Combinations/Elixir/combinations.ex similarity index 100% rename from Task/Combinations/Elixir/combinations.elixir rename to Task/Combinations/Elixir/combinations.ex diff --git a/Task/Combinations/Emacs-Lisp/combinations.l b/Task/Combinations/Emacs-Lisp/combinations.el similarity index 100% rename from Task/Combinations/Emacs-Lisp/combinations.l rename to Task/Combinations/Emacs-Lisp/combinations.el diff --git a/Task/Combinations/Euphoria/combinations.eu b/Task/Combinations/Euphoria/combinations.eu new file mode 100644 index 0000000000..522f4df73e --- /dev/null +++ b/Task/Combinations/Euphoria/combinations.eu @@ -0,0 +1,32 @@ +sequence combinations = {} + +procedure recurse(sequence remaining, /* digits remaining to compute */ + integer ne, /* number of digits expected for a valid combination */ + sequence selected = {}) /* digits already selected for a potential combination */ + integer nr = length(remaining) -- number of digits remaining to compute + integer ns = length(selected) -- number of digits already selected for a potential combination + if ns+nr = ne then + combinations = append(combinations, selected & remaining) + return + end if + if nr = 1 or ns = ne then + combinations = append(combinations, selected) + return + end if + -- select next + recurse(remove(remaining, 1), ne, selected & remaining[1]) + -- skip next + recurse(remove(remaining, 1), ne, selected) +end procedure + +function get_combinations(sequence s, integer lg) + combinations = {} + recurse(s, lg) + return combinations +end function + +constant TEST_SEQUENCE = {0,1,2,3,4} + +combinations = {} +recurse(TEST_SEQUENCE, 3) +? combinations diff --git a/Task/Combinations/FOCAL/combinations.focal b/Task/Combinations/FOCAL/combinations.focal new file mode 100644 index 0000000000..9a95a01740 --- /dev/null +++ b/Task/Combinations/FOCAL/combinations.focal @@ -0,0 +1,17 @@ +01.10 S M=3 +01.20 S N=5 +01.30 D 2 +01.40 Q + +02.10 F I=1,M;S C(I)=I-1 +02.20 D 3 +02.30 S I=M +02.40 S C(I)=C(I)+1 +02.50 I (C(I)-N+M-I)2.8 +02.60 S I=I-1 +02.70 I (-I)2.4;R +02.80 F J=I+1,M;S C(J)=C(J-1)+1 +02.90 G 2.2 + +03.10 F I=1,M;T %3,C(I) +03.20 T ! diff --git a/Task/Combinations/Frink/combinations.frink b/Task/Combinations/Frink/combinations.frink new file mode 100644 index 0000000000..16a86a5857 --- /dev/null +++ b/Task/Combinations/Frink/combinations.frink @@ -0,0 +1,7 @@ +combinations[m, n] := +{ + a = toArray[0 to n-1] + return lexicalSort[a.combinations[m]] +} + +println[formatTable[combinations[3,5]]] diff --git a/Task/Combinations/FutureBasic/combinations.basic b/Task/Combinations/FutureBasic/combinations.basic new file mode 100644 index 0000000000..6953e2870c --- /dev/null +++ b/Task/Combinations/FutureBasic/combinations.basic @@ -0,0 +1,16 @@ +void local fn Combinations( currStr as CFStringRef, start as int, stp as int, depth as int ) + int i + + for i = start to stp + if depth = 0 then printf @"%@ %d", currStr, i + fn Combinations( fn StringWithFormat( @"%@ %d", currStr, i ), i+1, stp, depth-1 ) + next +end fn + +int n : n = 3 +int m : m = 5 + +printf @" %d combinations of integers 0 through %d are:", n, m-1 +fn Combinations( @"", 0, m-1, n-1 ) + +HandleEvents diff --git a/Task/Combinations/J/combinations-10.j b/Task/Combinations/J/combinations-10.j new file mode 100644 index 0000000000..13e4c36a64 --- /dev/null +++ b/Task/Combinations/J/combinations-10.j @@ -0,0 +1 @@ +combb=: (#~ ((-:/:~)>/:~-:\:~)"1)@(# #: [: i. ^~) diff --git a/Task/Combinations/J/combinations-5.j b/Task/Combinations/J/combinations-5.j index b3a630bb1f..c026f8839f 100644 --- a/Task/Combinations/J/combinations-5.j +++ b/Task/Combinations/J/combinations-5.j @@ -1,3 +1 @@ -combr=: dyad define M. - if. (x>:y)+.0=x do. i.(x<:y),x else. (0,.x combr&.<: y),1+x combr y-1 end. -) +combr=: ((0,.$:&.<:),1+($:<:))` (<:i.@,[) @.(>:+.0=[)M. diff --git a/Task/Combinations/J/combinations-6.j b/Task/Combinations/J/combinations-6.j index 980099ca22..b3a630bb1f 100644 --- a/Task/Combinations/J/combinations-6.j +++ b/Task/Combinations/J/combinations-6.j @@ -1,7 +1,3 @@ - combr=: dyad define - if.(x=#y) +. x=1 do. - y - else. - (({.y) ,. (x-1) combr (}.y)) , (x combr }.y) - end. +combr=: dyad define M. + if. (x>:y)+.0=x do. i.(x<:y),x else. (0,.x combr&.<: y),1+x combr y-1 end. ) diff --git a/Task/Combinations/J/combinations-7.j b/Task/Combinations/J/combinations-7.j index 13e4c36a64..e1c75813ab 100644 --- a/Task/Combinations/J/combinations-7.j +++ b/Task/Combinations/J/combinations-7.j @@ -1 +1 @@ -combb=: (#~ ((-:/:~)>/:~-:\:~)"1)@(# #: [: i. ^~) +combr1=: (({.@],.<:@[$:}.@]),($:}.))` ] @.((= #)+.1=[) diff --git a/Task/Combinations/J/combinations-8.j b/Task/Combinations/J/combinations-8.j new file mode 100644 index 0000000000..399595ae74 --- /dev/null +++ b/Task/Combinations/J/combinations-8.j @@ -0,0 +1,7 @@ + combr1=: dyad define + if.(x=#y) +. x=1 do. + y + else. + (({.y) ,. (x-1) combr (}.y)) , (x combr }.y) + end. +) diff --git a/Task/Combinations/J/combinations-9.j b/Task/Combinations/J/combinations-9.j new file mode 100644 index 0000000000..b5d40efaeb --- /dev/null +++ b/Task/Combinations/J/combinations-9.j @@ -0,0 +1 @@ +comb3=: ((= +/"1) |.@:I.@# ]) #:@i.@(2&^) diff --git a/Task/Combinations/Java/combinations.java b/Task/Combinations/Java/combinations-1.java similarity index 100% rename from Task/Combinations/Java/combinations.java rename to Task/Combinations/Java/combinations-1.java diff --git a/Task/Combinations/Java/combinations-2.java b/Task/Combinations/Java/combinations-2.java new file mode 100644 index 0000000000..7a9bfe00d0 --- /dev/null +++ b/Task/Combinations/Java/combinations-2.java @@ -0,0 +1,29 @@ +import java.util.ArrayList; +import java.util.List; + +public final class Combinations { + + public static void main(String[] args) { + System.out.println(createCombinations(List.of( 0, 1, 2, 3, 4 ), 3)); + System.out.println(createCombinations(List.of( "Crosby", "Nash", "Stills", "Young" ), 3)); + } + + private static List> createCombinations(List elements, int k) { + List> combinations = new ArrayList>(); + createCombinations(elements, k, new ArrayList(), combinations, 0); + return combinations; + } + + private static void createCombinations( + List elements, int k, List accumulator, List> combinations, int index) { + if ( accumulator.size() == k ) { + combinations.addFirst( new ArrayList(accumulator) ); + } else if ( k - accumulator.size() <= elements.size() - index ) { + createCombinations(elements, k, accumulator, combinations, index + 1); + accumulator.add(elements.get(index)); + createCombinations(elements, k, accumulator, combinations, index + 1); + accumulator.removeLast(); + } + } + +} diff --git a/Task/Combinations/Julia/combinations-1.julia b/Task/Combinations/Julia/combinations-1.jl similarity index 100% rename from Task/Combinations/Julia/combinations-1.julia rename to Task/Combinations/Julia/combinations-1.jl diff --git a/Task/Combinations/Julia/combinations-2.julia b/Task/Combinations/Julia/combinations-2.jl similarity index 100% rename from Task/Combinations/Julia/combinations-2.julia rename to Task/Combinations/Julia/combinations-2.jl diff --git a/Task/Combinations/Julia/combinations-3.julia b/Task/Combinations/Julia/combinations-3.jl similarity index 100% rename from Task/Combinations/Julia/combinations-3.julia rename to Task/Combinations/Julia/combinations-3.jl diff --git a/Task/Combinations/Kotlin/combinations-1.kotlin b/Task/Combinations/Kotlin/combinations-1.kts similarity index 100% rename from Task/Combinations/Kotlin/combinations-1.kotlin rename to Task/Combinations/Kotlin/combinations-1.kts diff --git a/Task/Combinations/Kotlin/combinations-2.kotlin b/Task/Combinations/Kotlin/combinations-2.kts similarity index 100% rename from Task/Combinations/Kotlin/combinations-2.kotlin rename to Task/Combinations/Kotlin/combinations-2.kts diff --git a/Task/Combinations/M2000-Interpreter/combinations-1.m2000 b/Task/Combinations/M2000-Interpreter/combinations-1.m2000 index a5f1f5bb7e..47e46a34ce 100644 --- a/Task/Combinations/M2000-Interpreter/combinations-1.m2000 +++ b/Task/Combinations/M2000-Interpreter/combinations-1.m2000 @@ -1,41 +1,32 @@ Module Checkit { - Global a$ - Document a$ - Module Combinations (m as long, n as long){ + Function Combinations (m as long, n as long){ + Global a$ + Document a$ Module Level (n, s, h) { - If n=1 then { - while Len(s) { - Print h, car(s) - ToClipBoard() + If n=1 then + while Len(s) + a$<=h#str$("-")+"-"+car(s)#str$()+{ + } s=cdr(s) - } - } Else { - While len(s) { + End While + Else + While len(s) call Level n-1, cdr(s), cons(h, car(s)) s=cdr(s) - } - } - Sub ToClipBoard() - local m=each(h) - Local b$="" - While m { - b$+=If$(Len(b$)<>0->" ","")+Format$("{0::-10}",Array(m)) - } - b$+=If$(Len(b$)<>0->" ","")+Format$("{0::-10}",Array(s,0))+{ - } - a$<=b$ ' assign to global need <= - End Sub + End While + End if } If m<1 or n<1 then Error s=(,) - for i=0 to n-1 { - s=cons(s, (i,)) - } + for i=0 to n-1 + Append s, (i,) + next + s=s#sort() Head=(,) Call Level m, s, Head + =a$ } - Clear a$ - Combinations 3, 5 - ClipBoard a$ + ClipBoard Combinations( 3, 5) + report clipboard$ } Checkit diff --git a/Task/Combinations/M2000-Interpreter/combinations-2.m2000 b/Task/Combinations/M2000-Interpreter/combinations-2.m2000 index 96566c892d..9d851f853b 100644 --- a/Task/Combinations/M2000-Interpreter/combinations-2.m2000 +++ b/Task/Combinations/M2000-Interpreter/combinations-2.m2000 @@ -1,45 +1,55 @@ Module StepByStep { - Function CombinationsStep (a, nn) { - c1=lambda (&f, &a) ->{ - =car(a) : a=cdr(a) : f=len(a)=0 - } - m=len(a) + Function CombinationsStep (a, nn) { + c1=lambda (&f, &a) ->{ + =car(a) : a=cdr(a) : f=len(a)=0 + } + m=len(a) + c=c1 + n=m-nn+1 + p=2 + While m>n + c1=lambda c2=c,n=p, z=(,) (&f, &m) ->{ + if len(z)=0 then z=cdr(m) + =cons(car(m),c2(&f, &z)) + if f then z=(,) : m=cdr(m) : f=len(m)+len(z)n { - c1=lambda c2=c,n=p, z=(,) (&f, &m) ->{ - if len(z)=0 then z=cdr(m) - =cons(car(m),c2(&f, &z)) - if f then z=(,) : m=cdr(m) : f=len(m)+len(z) { + =c(&f, &a) } - =lambda c, a (&f) -> { - =c(&f, &a) - } - } - k=false - StepA=CombinationsStep((1, 2, 3, 4,5), 3) - while not k { - Print StepA(&k) - } - k=false - StepA=CombinationsStep((0, 1, 2, 3, 4), 3) - while not k { - Print StepA(&k) - } - k=false - StepA=CombinationsStep(("A", "B", "C", "D","E"), 3) - while not k { - Print StepA(&k) - } - k=false - StepA=CombinationsStep(("CAT", "DOG", "BAT"), 2) - while not k { - Print StepA(&k) - } + } + enum out {screen="", file="out.txt"} + m=each(out) + while m + open eval(m) for output as #f + k=false + StepA=CombinationsStep((1, 2, 3, 4,5), 3) + While not k + Print #f, StepA(&k)#str$() + End While + Print #f + k=false + StepA=CombinationsStep((0, 1, 2, 3, 4), 3) + While not k + Print #f, StepA(&k)#str$() + End While + Print #f + k=false + StepA=CombinationsStep(("A", "B", "C", "D","E"), 3) + While not k + Print #f, StepA(&k)#str$("-") + End While + Print #f + k=false + StepA=CombinationsStep(("CAT", "DOG", "BAT"), 2) + While not k + Print #f, StepA(&k)#str$("-") + End While + close #f + end while + win "notepad", dir$+file } StepByStep diff --git a/Task/Combinations/Miranda/combinations.miranda b/Task/Combinations/Miranda/combinations.miranda new file mode 100644 index 0000000000..eecb62e799 --- /dev/null +++ b/Task/Combinations/Miranda/combinations.miranda @@ -0,0 +1,8 @@ +main :: [sys_message] +main = [Stdout (lay (map show (comb 3 5)))] + +comb :: num->num->[[num]] +comb m n = comb' m [0..n-1] + where comb' 0 xs = [[]] + comb' m [] = [] + comb' m (x:xs) = map (x:) (comb' (m-1) xs) ++ comb' m xs diff --git a/Task/Combinations/OCaml/combinations.ocaml b/Task/Combinations/OCaml/combinations.ml similarity index 100% rename from Task/Combinations/OCaml/combinations.ocaml rename to Task/Combinations/OCaml/combinations.ml diff --git a/Task/Combinations/PascalABC.NET/combinations.pas b/Task/Combinations/PascalABC.NET/combinations.pas new file mode 100644 index 0000000000..c57e1ec639 --- /dev/null +++ b/Task/Combinations/PascalABC.NET/combinations.pas @@ -0,0 +1,2 @@ +## +(0..4).combinations(3).printlines; diff --git a/Task/Combinations/Pluto/combinations.pluto b/Task/Combinations/Pluto/combinations.pluto new file mode 100644 index 0000000000..7ce223467b --- /dev/null +++ b/Task/Combinations/Pluto/combinations.pluto @@ -0,0 +1,10 @@ +require "perm" +local fmt = require "fmt" + +local a = range(0, 4) +local co = coroutine.create(comb.generate) +while true do + local _, res = coroutine.resume(co, a, 3) + if !res then break end + fmt.lprint(res) +end diff --git a/Task/Combinations/PowerShell/combinations.psh b/Task/Combinations/PowerShell/combinations.ps1 similarity index 100% rename from Task/Combinations/PowerShell/combinations.psh rename to Task/Combinations/PowerShell/combinations.ps1 diff --git a/Task/Combinations/Pyret/combinations.pyret b/Task/Combinations/Pyret/combinations.arr similarity index 100% rename from Task/Combinations/Pyret/combinations.pyret rename to Task/Combinations/Pyret/combinations.arr diff --git a/Task/Combinations/Quackery/combinations-1.quackery b/Task/Combinations/Quackery/combinations-1.quackery index 697808559d..ccf881afbe 100644 --- a/Task/Combinations/Quackery/combinations-1.quackery +++ b/Task/Combinations/Quackery/combinations-1.quackery @@ -1,48 +1,21 @@ - [ 0 swap - [ dup 0 != while - dup 1 & if - [ dip 1+ ] - 1 >> again ] - drop ] is bits ( n --> n ) - - [ [] unrot - bit times - [ i bits - over = if - [ dip - [ i join ] ] ] - drop ] is combnums ( n n --> [ ) - - [ [] 0 rot - [ dup 0 != while - dup 1 & if - [ dip - [ dup dip join ] ] - dip 1+ - 1 >> - again ] - 2drop ] is makecomb ( n --> [ ) - [ over 0 = iff - [ 2drop [] ] done - combnums - [] swap witheach - [ makecomb - nested join ] ] is comb ( n n --> [ ) + [ 2drop ' [ [ ] ] ] + done + dup [] = iff nip done + 1 split rot tuck + 1 - over recurse + dip [ rot [] ] + witheach + [ dip over join + nested join ] + nip unrot recurse join ] is comb ( n [ --> [ ) - [ behead swap witheach max ] is largest ( [ --> n ) + [ [] swap times + [ i^ join ] + comb + witheach + [ witheach + [ echo sp ] + cr ] ] is task ( n n --> ) - [ 0 rot witheach - [ [ dip [ over * ] ] + ] - nip ] is comborder ( [ n --> n ) - - [ dup [] != while - sortwith - [ 2dup join - largest 1+ dup dip - [ comborder swap ] - comborder < ] ] is sortcombs ( [ --> [ ) - - 3 5 comb - sortcombs - witheach [ witheach [ echo sp ] cr ] + 3 5 task diff --git a/Task/Combinations/Quackery/combinations-2.quackery b/Task/Combinations/Quackery/combinations-2.quackery index 5626470d75..697808559d 100644 --- a/Task/Combinations/Quackery/combinations-2.quackery +++ b/Task/Combinations/Quackery/combinations-2.quackery @@ -1,31 +1,48 @@ - [ stack ] is comb.stack - [ stack ] is comb.items - [ stack ] is comb.required - [ stack ] is comb.result + [ 0 swap + [ dup 0 != while + dup 1 & if + [ dip 1+ ] + 1 >> again ] + drop ] is bits ( n --> n ) - [ 1 - comb.items put - 1+ comb.required put - 0 comb.stack put - [] comb.result put - [ comb.required share - comb.stack size = if - [ comb.result take - comb.stack behead - drop nested join - comb.result put ] - comb.stack take - dup comb.items share - = iff - [ drop - comb.stack size 1 > iff - [ 1 comb.stack tally ] ] - else - [ dup comb.stack put - 1+ comb.stack put ] - comb.stack size 1 = until ] - comb.items release - comb.required release - comb.result take ] is comb ( n n --> ) + [ [] unrot + bit times + [ i bits + over = if + [ dip + [ i join ] ] ] + drop ] is combnums ( n n --> [ ) + + [ [] 0 rot + [ dup 0 != while + dup 1 & if + [ dip + [ dup dip join ] ] + dip 1+ + 1 >> + again ] + 2drop ] is makecomb ( n --> [ ) + + [ over 0 = iff + [ 2drop [] ] done + combnums + [] swap witheach + [ makecomb + nested join ] ] is comb ( n n --> [ ) + + [ behead swap witheach max ] is largest ( [ --> n ) + + [ 0 rot witheach + [ [ dip [ over * ] ] + ] + nip ] is comborder ( [ n --> n ) + + [ dup [] != while + sortwith + [ 2dup join + largest 1+ dup dip + [ comborder swap ] + comborder < ] ] is sortcombs ( [ --> [ ) 3 5 comb + sortcombs witheach [ witheach [ echo sp ] cr ] diff --git a/Task/Combinations/Quackery/combinations-3.quackery b/Task/Combinations/Quackery/combinations-3.quackery index 721a651555..5626470d75 100644 --- a/Task/Combinations/Quackery/combinations-3.quackery +++ b/Task/Combinations/Quackery/combinations-3.quackery @@ -1,16 +1,31 @@ - [ dup size dip - [ witheach - [ over swap peek swap ] ] - nip pack ] is arrange ( [ [ --> [ ) + [ stack ] is comb.stack + [ stack ] is comb.items + [ stack ] is comb.required + [ stack ] is comb.result + + [ 1 - comb.items put + 1+ comb.required put + 0 comb.stack put + [] comb.result put + [ comb.required share + comb.stack size = if + [ comb.result take + comb.stack behead + drop nested join + comb.result put ] + comb.stack take + dup comb.items share + = iff + [ drop + comb.stack size 1 > iff + [ 1 comb.stack tally ] ] + else + [ dup comb.stack put + 1+ comb.stack put ] + comb.stack size 1 = until ] + comb.items release + comb.required release + comb.result take ] is comb ( n n --> ) - ' [ 10 20 30 40 50 ] 3 5 comb - witheach - [ dip dup arrange - witheach [ echo sp ] - cr ] - drop - cr - $ "zero one two three four" nest$ - ' [ 4 3 1 0 1 4 3 ] arrange - witheach [ echo$ sp ] + witheach [ witheach [ echo sp ] cr ] diff --git a/Task/Combinations/Quackery/combinations-4.quackery b/Task/Combinations/Quackery/combinations-4.quackery new file mode 100644 index 0000000000..721a651555 --- /dev/null +++ b/Task/Combinations/Quackery/combinations-4.quackery @@ -0,0 +1,16 @@ + [ dup size dip + [ witheach + [ over swap peek swap ] ] + nip pack ] is arrange ( [ [ --> [ ) + + ' [ 10 20 30 40 50 ] + 3 5 comb + witheach + [ dip dup arrange + witheach [ echo sp ] + cr ] + drop + cr + $ "zero one two three four" nest$ + ' [ 4 3 1 0 1 4 3 ] arrange + witheach [ echo$ sp ] diff --git a/Task/Combinations/Refal/combinations.refal b/Task/Combinations/Refal/combinations.refal new file mode 100644 index 0000000000..8b8d5ce984 --- /dev/null +++ b/Task/Combinations/Refal/combinations.refal @@ -0,0 +1,23 @@ +$ENTRY Go { + = >; +}; + +Comb { + s.M s.N = >>; +}; + +Comb1 { + 0 e.X = (); + s.M = ; + s.M s.X e.X = e.X>> ; +}; + +PfxEach { + s.X = ; + s.X (e.X) e.Y = (s.X e.X) ; +}; + +Iota { + s.E s.E = s.E; + s.S s.E = s.S s.E>; +}; diff --git a/Task/Combinations/Rust/combinations-1.rust b/Task/Combinations/Rust/combinations-1.rs similarity index 100% rename from Task/Combinations/Rust/combinations-1.rust rename to Task/Combinations/Rust/combinations-1.rs diff --git a/Task/Combinations/Rust/combinations-2.rust b/Task/Combinations/Rust/combinations-2.rs similarity index 100% rename from Task/Combinations/Rust/combinations-2.rust rename to Task/Combinations/Rust/combinations-2.rs diff --git a/Task/Combinations/Rust/combinations-3.rust b/Task/Combinations/Rust/combinations-3.rs similarity index 100% rename from Task/Combinations/Rust/combinations-3.rust rename to Task/Combinations/Rust/combinations-3.rs diff --git a/Task/Combinations/Scheme/combinations.ss b/Task/Combinations/Scheme/combinations.scm similarity index 100% rename from Task/Combinations/Scheme/combinations.ss rename to Task/Combinations/Scheme/combinations.scm diff --git a/Task/Combinations/Tailspin/combinations.tailspin b/Task/Combinations/Tailspin/combinations.tailspin new file mode 100644 index 0000000000..9f728e50c4 --- /dev/null +++ b/Task/Combinations/Tailspin/combinations.tailspin @@ -0,0 +1,7 @@ +operator (m comb n) + [by 0..~$n] -> # + when <[](..~$m)> do [$..., by $(last)~..~$n] -> # + otherwise $! +end comb + +(3 comb 5) -> !OUT::write diff --git a/Task/Combinations/Uiua/combinations.uiua b/Task/Combinations/Uiua/combinations.uiua new file mode 100644 index 0000000000..e0d299cce6 --- /dev/null +++ b/Task/Combinations/Uiua/combinations.uiua @@ -0,0 +1,3 @@ +3 5 # 3 combo 5 +⊙⇡ # Create the array of numbers +⧅< # Get the permutations diff --git a/Task/Combinations/VBScript/combinations.vb b/Task/Combinations/VBScript/combinations.vbs similarity index 100% rename from Task/Combinations/VBScript/combinations.vb rename to Task/Combinations/VBScript/combinations.vbs diff --git a/Task/Comma-quibbling/00-TASK.txt b/Task/Comma-quibbling/00-TASK.txt index 4e431d60f7..6e334a374a 100644 --- a/Task/Comma-quibbling/00-TASK.txt +++ b/Task/Comma-quibbling/00-TASK.txt @@ -1,4 +1,4 @@ -Comma quibbling is a task originally set by Eric Lippert in his [http://blogs.msdn.com/b/ericlippert/archive/2009/04/15/comma-quibbling.aspx blog]. +Comma quibbling is a task originally set by Eric Lippert in his [https://web.archive.org/web/20190202111812/https://blogs.msdn.microsoft.com/ericlippert/2009/04/15/comma-quibbling/ blog]. ;Task: @@ -11,12 +11,15 @@ Write a function to generate a string output which is the concatenation of input
    Test your function with the following series of inputs showing your output here on this page: -* [] # (No input words). +* [] # (No input words). * ["ABC"] * ["ABC", "DEF"] * ["ABC", "DEF", "G", "H"]
    Note: Assume words are non-empty strings of uppercase characters for this task. + + +{{Template:Strings}}

    diff --git a/Task/Comma-quibbling/AArch64-Assembly/comma-quibbling.aarch64 b/Task/Comma-quibbling/AArch64-Assembly/comma-quibbling.aarch64 new file mode 100644 index 0000000000..50ff3b829d --- /dev/null +++ b/Task/Comma-quibbling/AArch64-Assembly/comma-quibbling.aarch64 @@ -0,0 +1,270 @@ +/* ARM assembly AARCH64 Raspberry PI 3B */ +/* program Comma quibbling */ + +/*******************************************/ +/* Constantes */ +/*******************************************/ +/* for this file see task include a file in language AArch64 assembly*/ +.include "../includeConstantesARM64.inc" +.equ BUFFERSIZE, 80 + +/*******************************************/ +/* macros */ +/*******************************************/ +//.include "../../ficmacros64.inc" // for developper debugging + +/*********************************/ +/* Initialized data */ +/*********************************/ +.data +szMessDebutPgm: .asciz "Program 64 bits start. \n" +szCarriageReturn: .asciz "\n" +szMessFinOK: .asciz "Program normal end. \n" +szMessStringError: .asciz "Error : Empty string !!!\n" +szMessBufferError: .asciz "Error : Buffer too small !!\n" +szMessEndStringError: .asciz "Error: End string, not ].\n" +szMessWordErr: .asciz "Error word empty.\n" +szAnd: .asciz " and " +szString1: .asciz "[]" +szString2: .asciz "[\"ABC\"]" +szString3: .asciz "[\"ABC\",\"DEF\"]" +szString4: .asciz "[\"ABC\",\"DEF\",\"G\",\"H\"]" +szString5: .asciz "[\"AB" +szString6: .asciz "[\"ABC\",,\"DEF\"]" + +.align 4 +/*********************************/ +/* UnInitialized data */ +/*********************************/ +.bss +sBuffer: .skip BUFFERSIZE +.align 4 + +/*********************************/ +/* code section */ +/*********************************/ +.text +.global main +main: + ldr x0,qAdrszMessDebutPgm + bl affichageMess // start message + + ldr x0,qAdrszString1 + bl execTest + ldr x0,qAdrszString2 + bl execTest + ldr x0,qAdrszString3 + bl execTest + ldr x0,qAdrszString4 + bl execTest + ldr x0,qAdrszString5 + bl execTest + ldr x0,qAdrszString6 + bl execTest + + ldr x0,qAdrszMessFinOK + bl affichageMess + +100: + mov x8,EXIT + svc #0 // system call +qAdrszMessDebutPgm: .quad szMessDebutPgm +qAdrszMessFinOK: .quad szMessFinOK +qAdrszCarriageReturn: .quad szCarriageReturn +qAdrszString1: .quad szString1 +qAdrszString2: .quad szString2 +qAdrszString3: .quad szString3 +qAdrszString4: .quad szString4 +qAdrszString5: .quad szString5 +qAdrszString6: .quad szString6 +qAdrsBuffer: .quad sBuffer +/******************************************************************/ +/* test execution */ +/******************************************************************/ +/* x0 contains string address */ +execTest: + stp x1,lr,[sp,-16]! + stp x2,x4,[sp,-16]! + mov x4,x0 + bl affichageMess // display start string + ldr x0,qAdrszCarriageReturn + bl affichageMess + mov x0,x4 // string address + ldr x1,qAdrsBuffer // buffer address + mov x2,#BUFFERSIZE + bl stringAnalyse + cmp x0,#-1 // error ? + beq 100f + ldr x0,qAdrsBuffer // buffer display + bl affichageMess + ldr x0,qAdrszCarriageReturn + bl affichageMess +100: + ldp x2,x4,[sp],16 + ldp x1,lr,[sp],16 + ret +/******************************************************************/ +/* string conversion */ +/******************************************************************/ +/* x0 contains string address */ +/* x1 contains buffer address */ +/* x2 contains buffer length */ +stringAnalyse: + stp x1,lr,[sp,-16]! + stp x2,x3,[sp,-16]! + stp x4,x5,[sp,-16]! + stp x6,x7,[sp,-16]! + stp x8,x9,[sp,-16]! + sub sp,sp,#BUFFERSIZE // reserve area on stack for temporary buffer + mov fp,sp + mov x7,#0 // indice write buffer + mov x5,#0 // word counter + mov x6,#0 // word char count + + mov x3,#0 // indice string +1: + ldrb w4,[x0,x3] // load string char + cmp x4,#0 // end ? + bne 2f + cmp x3,#0 // first char ? + beq 97f // error empty string + b 97f // end string error +2: + cmp x4,#'[' // first symbol ? + bne 3f + mov x4,#'{' // write symbol + strb w4,[x1,x7] + add x7,x7,#1 + cmp x7,x2 + bge 99f // buffer error + add x3,x3,#1 // increment indice + b 1b // and loop + 3: + cmp x4,#']' // end symbol ? + bne 8f + cmp x5,#0 // no word ? + beq 7f + cmp x5,#1 + beq 5f // last and first word + + mov x9,#0 + ldr x12,qAdrszAnd +4: // loop write and + ldrb w4,[x12,x9] + strb w4,[x1,x7] + add x7,x7,#1 + cmp x7,x2 + bge 99f // buffer error + add x9,x9,#1 + cmp x9,#5 + blt 4b + +5: // last word + mov x9,#0 +6: // loop write temporary buffer + ldrb w4,[fp,x9] + strb w4,[x1,x7] + add x7,x7,#1 + cmp x7,x2 + bge 99f // buffer error + add x9,x9,#1 + cmp x9,x6 + blt 6b + mov x6,#0 // raz indice temporary buffer +7: + mov x4,#'}' + strb w4,[x1,x7] + add x7,x7,#1 + cmp x7,x2 + bge 99f // buffer error + mov x4,#0 + strb w4,[x1,x7] // final 0 + b 100f +8: + cmp x4,#',' // comma ? + beq 9f + cmp x6,#0 + cinc x5,x5,eq // new word increment word counter + //addeq x5,x5,#1 // new word increment word counter + strb w4,[fp,x6] // store char in temporary buffer + add x6,x6,#1 + add x3,x3,#1 + b 1b // loop + +9: + cmp x6,#0 // word empty ? + beq 96f + cmp x5,#1 // first word ? + bne 11f + // first word, write only the word + mov x9,#0 +10: // loop write temporary buffer + ldrb w4,[fp,x9] + strb w4,[x1,x7] + add x7,x7,#1 + cmp x7,x2 + bge 99f // buffer error + add x9,x9,#1 + cmp x9,x6 + blt 10b + mov x6,#0 // raz indice temporary buffer + add x3,x3,#1 + b 1b // loop +11: + mov x4,#',' + strb w4,[x1,x7] + add x7,x7,#1 + cmp x7,x2 + bge 99f // buffer error + + mov x9,#0 +12: // loop write temporary buffer + ldrb w4,[fp,x9] + strb w4,[x1,x7] + add x7,x7,#1 + cmp x7,x2 + bge 99f // buffer error + add x9,x9,#1 + cmp x9,x6 + blt 12b + mov x6,#0 // raz indice temporary buffer + add x3,x3,#1 + b 1b // loop + +96: // errors messages + ldr x0,qAdrszMessWordErr + bl affichageMess + mov x0,#-1 + b 100f +97: + ldr x0,qAdrszMessEndStringErr + bl affichageMess + mov x0,#-1 + b 100f +98: + ldr x0,qAdrszMessStringError + bl affichageMess + mov x0,#-1 + b 100f +99: + ldr x0,qAdrszMessBufferError + bl affichageMess + mov x0,#-1 +100: + add sp,sp,#BUFFERSIZE + ldp x8,x9,[sp],16 + ldp x6,x7,[sp],16 + ldp x4,x5,[sp],16 + ldp x2,x3,[sp],16 + ldp x1,lr,[sp],16 + ret +qAdrszMessStringError: .quad szMessStringError +qAdrszMessBufferError: .quad szMessBufferError +qAdrszMessEndStringErr: .quad szMessEndStringError +qAdrszMessWordErr: .quad szMessWordErr +qAdrszAnd: .quad szAnd +/***************************************************/ +/* ROUTINES INCLUDE */ +/***************************************************/ +/* for this file see task include a file in language AArch64 assembly*/ +.include "../includeARM64.inc" diff --git a/Task/Comma-quibbling/ARM-Assembly/comma-quibbling.arm b/Task/Comma-quibbling/ARM-Assembly/comma-quibbling.arm new file mode 100644 index 0000000000..ebbae869ca --- /dev/null +++ b/Task/Comma-quibbling/ARM-Assembly/comma-quibbling.arm @@ -0,0 +1,260 @@ +/* ARM assembly Raspberry PI */ +/* program Comma quibbling */ + +/* REMARK 1 : this program use routines in a include file + see task Include a file language arm assembly + for the routine affichageMess conversion10 + see at end of this program the instruction include */ + +/*******************************************/ +/* Constantes */ +/*******************************************/ +.include "../constantes.inc" +.equ BUFFERSIZE, 80 + +/*******************************************/ +/* macros */ +/*******************************************/ +//.include "../../ficmacros32.inc" @ for developper debugging + +/*********************************/ +/* Initialized data */ +/*********************************/ +.data +szMessDebutPgm: .asciz "Program 32 bits start. \n" +szCarriageReturn: .asciz "\n" +szMessFinOK: .asciz "Program normal end. \n" +szMessStringError: .asciz "Error : Empty string !!!\n" +szMessBufferError: .asciz "Error : Buffer too small !!\n" +szMessEndStringError: .asciz "Error: End string, not ].\n" +szMessWordErr: .asciz "Error word empty.\n" +szAnd: .asciz " and " +szString1: .asciz "[]" +szString2: .asciz "[\"ABC\"]" +szString3: .asciz "[\"ABC\",\"DEF\"]" +szString4: .asciz "[\"ABC\",\"DEF\",\"G\",\"H\"]" +szString5: .asciz "[\"AB" +szString6: .asciz "[\"ABC\",,\"DEF\"]" + +.align 4 +/*********************************/ +/* UnInitialized data */ +/*********************************/ +.bss +sBuffer: .skip BUFFERSIZE +.align 4 + +/*********************************/ +/* code section */ +/*********************************/ +.text +.global main +main: + ldr r0,iAdrszMessDebutPgm + bl affichageMess @ start message + + ldr r0,iAdrszString1 + bl execTest + ldr r0,iAdrszString2 + bl execTest + ldr r0,iAdrszString3 + bl execTest + ldr r0,iAdrszString4 + bl execTest + ldr r0,iAdrszString5 + bl execTest + ldr r0,iAdrszString6 + bl execTest + + ldr r0,iAdrszMessFinOK + bl affichageMess + +100: + mov r7,#EXIT @ program end + svc #0 @ system call +iAdrszMessDebutPgm: .int szMessDebutPgm +iAdrszMessFinOK: .int szMessFinOK +iAdrszCarriageReturn: .int szCarriageReturn +iAdrszString1: .int szString1 +iAdrszString2: .int szString2 +iAdrszString3: .int szString3 +iAdrszString4: .int szString4 +iAdrszString5: .int szString5 +iAdrszString6: .int szString6 +iAdrsBuffer: .int sBuffer +/******************************************************************/ +/* test execution */ +/******************************************************************/ +/* r0 contains string address */ +execTest: + push {r1-r4,lr} @ save registers + mov r4,r0 + bl affichageMess @ display start string + ldr r0,iAdrszCarriageReturn + bl affichageMess + mov r0,r4 @ string address + ldr r1,iAdrsBuffer @ buffer address + mov r2,#BUFFERSIZE + bl stringAnalyse + cmp r0,#-1 @ error ? + beq 100f + ldr r0,iAdrsBuffer @ buffer display + bl affichageMess + ldr r0,iAdrszCarriageReturn + bl affichageMess +100: + pop {r1-r4,pc} +/******************************************************************/ +/* string conversion */ +/******************************************************************/ +/* r0 contains string address */ +/* r1 contains buffer address */ +/* r2 contains buffer length */ +stringAnalyse: + push {r1-r9,fp,lr} @ save registers + sub sp,sp,#BUFFERSIZE @ reserve area on stack for temporary buffer + mov fp,sp + mov r7,#0 @ indice write buffer + mov r5,#0 @ word counter + mov r6,#0 @ word char count + + mov r3,#0 @ indice string +1: + ldrb r4,[r0,r3] @ load string char + cmp r4,#0 @ end ? + bne 2f + cmp r3,#0 @ first char ? + beq 97f @ error empty string + b 97f @ end string error +2: + cmp r4,#'[' @ first symbol ? + bne 3f + mov r4,#'{' @ write symbol + strb r4,[r1,r7] + add r7,r7,#1 + cmp r7,r2 + bge 99f @ buffer error + add r3,r3,#1 @ increment indice + b 1b @ and loop + 3: + cmp r4,#']' @ end symbol ? + bne 8f + cmp r5,#0 @ no word ? + beq 7f + cmp r5,#1 + beq 5f @ last and first word + + mov r9,#0 + ldr r12,iAdrszAnd +4: @ loop write and + ldrb r4,[r12,r9] + strb r4,[r1,r7] + add r7,r7,#1 + cmp r7,r2 + bge 99f @ buffer error + add r9,r9,#1 + cmp r9,#5 + blt 4b + +5: @ last word + mov r9,#0 +6: @ loop write temporary buffer + ldrb r4,[fp,r9] + strb r4,[r1,r7] + add r7,r7,#1 + cmp r7,r2 + bge 99f @ buffer error + add r9,r9,#1 + cmp r9,r6 + blt 6b + mov r6,#0 @ raz indice temporary buffer +7: + mov r4,#'}' + strb r4,[r1,r7] + add r7,r7,#1 + cmp r7,r2 + bge 99f @ buffer error + mov r4,#0 + strb r4,[r1,r7] @ final 0 + b 100f +8: + cmp r4,#',' @ comma ? + beq 9f + cmp r6,#0 + addeq r5,r5,#1 @ new word increment word counter + strb r4,[fp,r6] @ store char in temporary buffer + add r6,r6,#1 + add r3,r3,#1 + b 1b @ loop + +9: + cmp r6,#0 @ word empty ? + beq 96f + cmp r5,#1 @ first word ? + bne 11f + @ first word, write only the word + mov r9,#0 +10: @ loop write temporary buffer + ldrb r4,[fp,r9] + strb r4,[r1,r7] + add r7,r7,#1 + cmp r7,r2 + bge 99f @ buffer error + add r9,r9,#1 + cmp r9,r6 + blt 10b + mov r6,#0 @ raz indice temporary buffer + add r3,r3,#1 + b 1b @ loop +11: + mov r4,#',' + strb r4,[r1,r7] + add r7,r7,#1 + cmp r7,r2 + bge 99f @ buffer error + + mov r9,#0 +12: @ loop write temporary buffer + ldrb r4,[fp,r9] + strb r4,[r1,r7] + add r7,r7,#1 + cmp r7,r2 + bge 99f @ buffer error + add r9,r9,#1 + cmp r9,r6 + blt 12b + mov r6,#0 @ raz indice temporary buffer + add r3,r3,#1 + b 1b @ loop + +96: @ errors messages + ldr r0,iAdrszMessWordErr + bl affichageMess + mov r0,#-1 + b 100f +97: + ldr r0,iAdrszMessEndStringErr + bl affichageMess + mov r0,#-1 + b 100f +98: + ldr r0,iAdrszMessStringError + bl affichageMess + mov r0,#-1 + b 100f +99: + ldr r0,iAdrszMessBufferError + bl affichageMess + mov r0,#-1 +100: + add sp,sp,#BUFFERSIZE + pop {r1-r9,fp,pc} +iAdrszMessStringError: .int szMessStringError +iAdrszMessBufferError: .int szMessBufferError +iAdrszMessEndStringErr: .int szMessEndStringError +iAdrszMessWordErr: .int szMessWordErr +iAdrszAnd: .int szAnd +/***************************************************/ +/* ROUTINES INCLUDE */ +/***************************************************/ +.include "../affichage.inc" diff --git a/Task/Comma-quibbling/Ada/comma-quibbling.ada b/Task/Comma-quibbling/Ada/comma-quibbling.adb similarity index 100% rename from Task/Comma-quibbling/Ada/comma-quibbling.ada rename to Task/Comma-quibbling/Ada/comma-quibbling.adb diff --git a/Task/Comma-quibbling/Arturo/comma-quibbling.arturo b/Task/Comma-quibbling/Arturo/comma-quibbling.arturo index e34a1676ac..a427253a6f 100644 --- a/Task/Comma-quibbling/Arturo/comma-quibbling.arturo +++ b/Task/Comma-quibbling/Arturo/comma-quibbling.arturo @@ -1,9 +1,9 @@ quibble: $[sequence :block][ - if? 0 = size sequence - -> return "{}" + if 0 = size sequence + -> return "{}" - if? 1 = size sequence - -> return ~"{|sequence\0|}" + if 1 = size sequence + -> return ~"{|sequence\0|}" last: pop 'sequence return ~« {|join.with: ", " sequence| and |last|} diff --git a/Task/Comma-quibbling/COBOL/comma-quibbling.cobol b/Task/Comma-quibbling/COBOL/comma-quibbling.cob similarity index 100% rename from Task/Comma-quibbling/COBOL/comma-quibbling.cobol rename to Task/Comma-quibbling/COBOL/comma-quibbling.cob diff --git a/Task/Comma-quibbling/Crystal/comma-quibbling.cr b/Task/Comma-quibbling/Crystal/comma-quibbling.cr new file mode 100644 index 0000000000..c9464e6016 --- /dev/null +++ b/Task/Comma-quibbling/Crystal/comma-quibbling.cr @@ -0,0 +1,19 @@ +def comma_quibble (arr) + "{" + + case arr.size + when 0 + "" + when 1 + arr[0] + else + arr[..-2].join(", ") + " and #{arr[-1]}" + end + "}" +end + +[[] of String, # (No input words). + ["ABC"], + ["ABC", "DEF"], + ["ABC", "DEF", "G", "H"], +].each do |input| + puts comma_quibble(input) +end diff --git a/Task/Comma-quibbling/EasyLang/comma-quibbling.easy b/Task/Comma-quibbling/EasyLang/comma-quibbling.easy index b3d7618ce4..9241769aeb 100644 --- a/Task/Comma-quibbling/EasyLang/comma-quibbling.easy +++ b/Task/Comma-quibbling/EasyLang/comma-quibbling.easy @@ -2,13 +2,9 @@ func$ tolist s$ . s$[] = strsplit s$ " " r$ = "{" n = len s$[] - for i = 1 to n - 2 - r$ &= s$[i] & ", " - . + for i = 1 to n - 2 : r$ &= s$[i] & ", " if n > 0 - if n > 1 - r$ &= s$[n - 1] & " and " - . + if n > 1 : r$ &= s$[n - 1] & " and " r$ &= s$[n] . r$ &= "}" diff --git a/Task/Comma-quibbling/Ed/comma-quibbling.ed b/Task/Comma-quibbling/Ed/comma-quibbling.ed new file mode 100644 index 0000000000..ac9da0cba8 --- /dev/null +++ b/Task/Comma-quibbling/Ed/comma-quibbling.ed @@ -0,0 +1,8 @@ +# by Artyom Bologov +H +,p +g/.*/s/ /, /g +g/[,]/s/,\([^,]*\)$/ and\1/ +g/.*/s//{&}/ +,p +Q diff --git a/Task/Comma-quibbling/Elena/comma-quibbling-1.elena b/Task/Comma-quibbling/Elena/comma-quibbling-1.elena new file mode 100644 index 0000000000..7d110e9b1f --- /dev/null +++ b/Task/Comma-quibbling/Elena/comma-quibbling-1.elena @@ -0,0 +1,23 @@ +import system'routines; +import extensions; +import extensions'text; + +public extension QuibbleOp : Array +{ + string quibble() + { + ^ self.zipBy( + self.Length.coundDown().selectBy::(n => (n == self.Length) ? EmptyString : ((n == 1) ? " and " : ", ") ), + (word, prefix => prefix + word) + ) + .summarize(StringWriter.load("{")) + "}" + } +} + +public Program() +{ + Console.printLine(new string[] { }.quibble()); + Console.printLine(new string[] { "ABC" }.quibble()); + Console.printLine(new string[] { "ABC", "ADF" }.quibble()); + Console.printLine(new string[] { "ABC", "DEF", "G", "H" }.quibble()) +} diff --git a/Task/Comma-quibbling/Elena/comma-quibbling-2.elena b/Task/Comma-quibbling/Elena/comma-quibbling-2.elena new file mode 100644 index 0000000000..f59b89451f --- /dev/null +++ b/Task/Comma-quibbling/Elena/comma-quibbling-2.elena @@ -0,0 +1,31 @@ +import extensions; +import textgen; + +const string Script = "<={{=>for (var i := 0; i < self.Length; i := i + 1) { + if (i > 0) { + if (i == self.Length - 1) { + <= and => + } + else { + <=, => + } + }; + + <={self[i]}=> + }; <=}}=>"; + +public extension QuibbleOp : Array +{ + string quibble() + { + ^ self.generateFrom(Script); + } +} + +public Program() +{ + Console.printLine(new string[] { }.quibble()); + Console.printLine(new string[] { "ABC" }.quibble()); + Console.printLine(new string[] { "ABC", "ADF" }.quibble()); + Console.printLine(new string[] { "ABC", "DEF", "G", "H" }.quibble()) +} diff --git a/Task/Comma-quibbling/Elixir/comma-quibbling.elixir b/Task/Comma-quibbling/Elixir/comma-quibbling.ex similarity index 100% rename from Task/Comma-quibbling/Elixir/comma-quibbling.elixir rename to Task/Comma-quibbling/Elixir/comma-quibbling.ex diff --git a/Task/Comma-quibbling/FutureBasic/comma-quibbling-3.basic b/Task/Comma-quibbling/FutureBasic/comma-quibbling-3.basic new file mode 100644 index 0000000000..aca32cb04f --- /dev/null +++ b/Task/Comma-quibbling/FutureBasic/comma-quibbling-3.basic @@ -0,0 +1,16 @@ +local fn Quibble( string as CFStringRef ) as CFStringRef + CfArrayRef arr = fn StringComponentsSeparatedByString( string, @" " ) + CFStringRef rst + if ( len(arr) == 0 ) then rst = @"" else rst = fn StringWithFormat( @"%@", fn ArrayLastObject( arr ) ) + if ( len(arr) > 1 ) + CFArrayRef subArray = fn ArraySubarrayWithRange( arr, fn CFRangeMake( 0, len(arr) - 1 ) ) + rst = fn StringWithFormat( @"%@ and %@", fn ArrayComponentsJoinedByString( subArray, @", " ), rst ) + end if +end fn = fn StringWithFormat( @"{%@}", rst ) + +print fn Quibble( @"" ) +print fn Quibble( @"ABC") +print fn Quibble( @"ABC DEF" ) +print fn Quibble( @"ABC DEF G H" ) + +HandleEvents diff --git a/Task/Comma-quibbling/Julia/comma-quibbling.julia b/Task/Comma-quibbling/Julia/comma-quibbling.jl similarity index 100% rename from Task/Comma-quibbling/Julia/comma-quibbling.julia rename to Task/Comma-quibbling/Julia/comma-quibbling.jl diff --git a/Task/Comma-quibbling/Kotlin/comma-quibbling.kotlin b/Task/Comma-quibbling/Kotlin/comma-quibbling.kts similarity index 100% rename from Task/Comma-quibbling/Kotlin/comma-quibbling.kotlin rename to Task/Comma-quibbling/Kotlin/comma-quibbling.kts diff --git a/Task/Comma-quibbling/Nu/comma-quibbling.nu b/Task/Comma-quibbling/Nu/comma-quibbling.nu new file mode 100644 index 0000000000..1af48327db --- /dev/null +++ b/Task/Comma-quibbling/Nu/comma-quibbling.nu @@ -0,0 +1,13 @@ +def quibble [] { + if ($in | length) < 3 { $in } else [($in | drop | str join ', ') ($in | last)] + | $'{($in | str join " and ")}' +} + +# test +[ + [] + [ABC] + [ABC DEF] + [ABC DEF G H] +] +| each { quibble } diff --git a/Task/Comma-quibbling/OCaml/comma-quibbling-1.ocaml b/Task/Comma-quibbling/OCaml/comma-quibbling-1.ml similarity index 100% rename from Task/Comma-quibbling/OCaml/comma-quibbling-1.ocaml rename to Task/Comma-quibbling/OCaml/comma-quibbling-1.ml diff --git a/Task/Comma-quibbling/OCaml/comma-quibbling-2.ocaml b/Task/Comma-quibbling/OCaml/comma-quibbling-2.ml similarity index 100% rename from Task/Comma-quibbling/OCaml/comma-quibbling-2.ocaml rename to Task/Comma-quibbling/OCaml/comma-quibbling-2.ml diff --git a/Task/Comma-quibbling/Pluto/comma-quibbling.pluto b/Task/Comma-quibbling/Pluto/comma-quibbling.pluto new file mode 100644 index 0000000000..ae82288a57 --- /dev/null +++ b/Task/Comma-quibbling/Pluto/comma-quibbling.pluto @@ -0,0 +1,10 @@ +local function quibbling(w) + local c = #w + if c == 0 then return "{}" end + if c == 1 then return $"\{{w[1]}}" end + if c == 2 then return $"\{{w[1]} and {w[2]}}" end + return $"\{{w:slice(1, #w - 1):concat(", ")} and {w[#w]}}" +end + +local words = { {}, {"ABC"}, {"ABC", "DEF"}, {"ABC", "DEF", "G", "H"} } +for words as w do print(quibbling(w)) end diff --git a/Task/Comma-quibbling/PowerShell/comma-quibbling-1.psh b/Task/Comma-quibbling/PowerShell/comma-quibbling-1.ps1 similarity index 100% rename from Task/Comma-quibbling/PowerShell/comma-quibbling-1.psh rename to Task/Comma-quibbling/PowerShell/comma-quibbling-1.ps1 diff --git a/Task/Comma-quibbling/PowerShell/comma-quibbling-2.psh b/Task/Comma-quibbling/PowerShell/comma-quibbling-2.ps1 similarity index 100% rename from Task/Comma-quibbling/PowerShell/comma-quibbling-2.psh rename to Task/Comma-quibbling/PowerShell/comma-quibbling-2.ps1 diff --git a/Task/Comma-quibbling/PowerShell/comma-quibbling-3.psh b/Task/Comma-quibbling/PowerShell/comma-quibbling-3.ps1 similarity index 100% rename from Task/Comma-quibbling/PowerShell/comma-quibbling-3.psh rename to Task/Comma-quibbling/PowerShell/comma-quibbling-3.ps1 diff --git a/Task/Comma-quibbling/REBOL/comma-quibbling-2.rebol b/Task/Comma-quibbling/REBOL/comma-quibbling-2.rebol deleted file mode 100644 index 42c9c25002..0000000000 --- a/Task/Comma-quibbling/REBOL/comma-quibbling-2.rebol +++ /dev/null @@ -1,24 +0,0 @@ -Rebol [] - -; builds string instead of using an intermediate block - -comma-quibbling: func [block /oxford /local s length] [ - length: length? block - rejoin [ - "^{" - - either length < 2 [to-string block] [ - s: to-string block/1 - for n 2 (length - 1) 1 [repend s [", " pick block n]] - if all [oxford (length > 2)] [append s ","] - repend s [" and " last block] - ] - - "^}" - ] -] - -test: [[] [ABC] [ABC DEF] [ABC DEF G H]] -foreach t test [print comma-quibbling t] -print "Now with Oxford comma" -foreach t test [print comma-quibbling/oxford t] diff --git a/Task/Comma-quibbling/Rebol/comma-quibbling-1.rebol b/Task/Comma-quibbling/Rebol/comma-quibbling-1.rebol new file mode 100644 index 0000000000..9adf877190 --- /dev/null +++ b/Task/Comma-quibbling/Rebol/comma-quibbling-1.rebol @@ -0,0 +1,2 @@ +head change/part find/last combine/with [ABC DEF G H] ", " #"," " and" 1 +;== "ABC, DEF, G and H" diff --git a/Task/Comma-quibbling/REBOL/comma-quibbling-1.rebol b/Task/Comma-quibbling/Rebol/comma-quibbling-2.rebol similarity index 100% rename from Task/Comma-quibbling/REBOL/comma-quibbling-1.rebol rename to Task/Comma-quibbling/Rebol/comma-quibbling-2.rebol diff --git a/Task/Comma-quibbling/Rebol/comma-quibbling-3.rebol b/Task/Comma-quibbling/Rebol/comma-quibbling-3.rebol new file mode 100644 index 0000000000..1680b96b7d --- /dev/null +++ b/Task/Comma-quibbling/Rebol/comma-quibbling-3.rebol @@ -0,0 +1,24 @@ +Rebol [] + +; builds string instead of using an intermediate block + +comma-quibbling: func [block /oxford /local s length] [ + length: length? block + rejoin [ + "^{" + + either length < 2 [to string! block] [ + s: to string! block/1 + for n 2 (length - 1) 1 [repend s [", " pick block n]] + if all [oxford (length > 2)] [append s ","] + repend s [" and " last block] + ] + + "^}" + ] +] + +test: [[] [ABC] [ABC DEF] [ABC DEF G H]] +foreach t test [print comma-quibbling t] +print "Now with Oxford comma" +foreach t test [print comma-quibbling/oxford t] diff --git a/Task/Comma-quibbling/Rust/comma-quibbling.rust b/Task/Comma-quibbling/Rust/comma-quibbling.rs similarity index 100% rename from Task/Comma-quibbling/Rust/comma-quibbling.rust rename to Task/Comma-quibbling/Rust/comma-quibbling.rs diff --git a/Task/Comma-quibbling/Scheme/comma-quibbling.ss b/Task/Comma-quibbling/Scheme/comma-quibbling.scm similarity index 100% rename from Task/Comma-quibbling/Scheme/comma-quibbling.ss rename to Task/Comma-quibbling/Scheme/comma-quibbling.scm diff --git a/Task/Comma-quibbling/Uiua/comma-quibbling.uiua b/Task/Comma-quibbling/Uiua/comma-quibbling.uiua index 4a39d94b1f..318a769baa 100644 --- a/Task/Comma-quibbling/Uiua/comma-quibbling.uiua +++ b/Task/Comma-quibbling/Uiua/comma-quibbling.uiua @@ -2,7 +2,5 @@ Tests ← {{} {"ABC"} {"ABC" "DEF"} {"ABC" "DEF" "G" "H"}} -Jam ← ◇⊂◇⊂:□ -Quibble ← |1 ⟨""◌|°□⊢|Jam" and "°⊟|Quibble⊂⊃(□Jam", "°⊟↙2)(↘2)⟩↧3⧻. -Wrap ← ⊂⊂"{" : "}" Quibble -⍚(&pWrap) Tests +Quibble ← |1 ⨬(⋅""|°□⊢|$"_ and _"°⊟|Quibble⊂⊃(□$"_, _"°⊟↙2)↘₂)↧3⊸⧻ +⍚(&p$"{_}"Quibble) Tests diff --git a/Task/Comma-quibbling/V-(Vlang)/comma-quibbling.v b/Task/Comma-quibbling/V-(Vlang)/comma-quibbling.v index dbfb561110..6d8c5779ea 100644 --- a/Task/Comma-quibbling/V-(Vlang)/comma-quibbling.v +++ b/Task/Comma-quibbling/V-(Vlang)/comma-quibbling.v @@ -1,23 +1,15 @@ fn q(s []string) string { match s.len { - 0 { - return '{}' - } - 1 { - return '{${s[0]}}' - } - 2 { - return '{${s[0]} and ${s[1]}}' - } - else{ - return '{${s[0..s.len-1].join(', ')} and ${s[s.len-1]}}' - } + 0 { return "{}" } + 1 { return "{${s[0]}}" } + 2 { return "{${s[0]} and ${s[1]}}" } + else { return "{${s[0..s.len-1].join(", ")} and ${s[s.len-1]}}" } } } fn main(){ println(q([])) - println(q(['ABC'])) - println(q(['ABC','DEF'])) - println(q(['ABC','DEF','G','H'])) + println(q(["ABC"])) + println(q(["ABC","DEF"])) + println(q(["ABC","DEF","G","H"])) } diff --git a/Task/Comma-quibbling/VBScript/comma-quibbling.vb b/Task/Comma-quibbling/VBScript/comma-quibbling.vbs similarity index 100% rename from Task/Comma-quibbling/VBScript/comma-quibbling.vb rename to Task/Comma-quibbling/VBScript/comma-quibbling.vbs diff --git a/Task/Command-line-arguments/AArch64-Assembly/command-line-arguments.aarch64 b/Task/Command-line-arguments/AArch64-Assembly/command-line-arguments-1.aarch64 similarity index 100% rename from Task/Command-line-arguments/AArch64-Assembly/command-line-arguments.aarch64 rename to Task/Command-line-arguments/AArch64-Assembly/command-line-arguments-1.aarch64 diff --git a/Task/Command-line-arguments/AArch64-Assembly/command-line-arguments-2.aarch64 b/Task/Command-line-arguments/AArch64-Assembly/command-line-arguments-2.aarch64 new file mode 100644 index 0000000000..134551fb07 --- /dev/null +++ b/Task/Command-line-arguments/AArch64-Assembly/command-line-arguments-2.aarch64 @@ -0,0 +1,26 @@ +.global _start +.text +_start: + mov x9, sp // move stack pointer to x9 + 0: ldr x0, [x9, #8]! // add 8 to x9, load long int value at x9 into x0 + cbz x0, 9f // if x0 is zero (null pointer) jump forward to 9: + bl writez // call our function that prints a null terminated string + adr x0, lfz // load address of lfz (line feed, zero) into x0 + bl writez // print it + b 0b // jump backward to label 0: + 9: mov x8, #93 // 93 is exit + mov x0, xzr // return (0); + svc #0 // syscall + // If using as a function in C declare it as +writez: // extern long writez(char *str); + mov x1, x0 // address of str needs to be in x1 for syscall + sub x0, x0, #1 // decrement x0, because the next statement increments it first. + 0: ldrb w2, [x0, #1]! // increment x0, load byte value at x0 in w2 + cbnz w2, 0b // if w2 is not zero jump back to 0: label + sub x2, x0, x1 // subtract x1 from x0, load into x2. length of str + mov x0, #1 // mov into x0 1. stdout + mov x8, #64 // mov into x8 64. write + svc #0 // syscall + ret // return from function. + // return value is number of characters written. +lfz: .byte 10, 0 // line feed (0x0a), zero (null character) diff --git a/Task/Command-line-arguments/Ada/command-line-arguments-1.ada b/Task/Command-line-arguments/Ada/command-line-arguments-1.adb similarity index 100% rename from Task/Command-line-arguments/Ada/command-line-arguments-1.ada rename to Task/Command-line-arguments/Ada/command-line-arguments-1.adb diff --git a/Task/Command-line-arguments/Ada/command-line-arguments-2.ada b/Task/Command-line-arguments/Ada/command-line-arguments-2.adb similarity index 100% rename from Task/Command-line-arguments/Ada/command-line-arguments-2.ada rename to Task/Command-line-arguments/Ada/command-line-arguments-2.adb diff --git a/Task/Command-line-arguments/ArkScript/command-line-arguments.ark b/Task/Command-line-arguments/ArkScript/command-line-arguments.ark new file mode 100644 index 0000000000..c7a36a1db6 --- /dev/null +++ b/Task/Command-line-arguments/ArkScript/command-line-arguments.ark @@ -0,0 +1,2 @@ +(import std.Sys) +(print sys:args) diff --git a/Task/Command-line-arguments/COBOL/command-line-arguments-1.cobol b/Task/Command-line-arguments/COBOL/command-line-arguments-1.cob similarity index 100% rename from Task/Command-line-arguments/COBOL/command-line-arguments-1.cobol rename to Task/Command-line-arguments/COBOL/command-line-arguments-1.cob diff --git a/Task/Command-line-arguments/COBOL/command-line-arguments-2.cobol b/Task/Command-line-arguments/COBOL/command-line-arguments-2.cob similarity index 100% rename from Task/Command-line-arguments/COBOL/command-line-arguments-2.cobol rename to Task/Command-line-arguments/COBOL/command-line-arguments-2.cob diff --git a/Task/Command-line-arguments/COBOL/command-line-arguments-3.cobol b/Task/Command-line-arguments/COBOL/command-line-arguments-3.cob similarity index 100% rename from Task/Command-line-arguments/COBOL/command-line-arguments-3.cobol rename to Task/Command-line-arguments/COBOL/command-line-arguments-3.cob diff --git a/Task/Command-line-arguments/Delphi/command-line-arguments.delphi b/Task/Command-line-arguments/Delphi/command-line-arguments.pas similarity index 100% rename from Task/Command-line-arguments/Delphi/command-line-arguments.delphi rename to Task/Command-line-arguments/Delphi/command-line-arguments.pas diff --git a/Task/Command-line-arguments/Elena/command-line-arguments.elena b/Task/Command-line-arguments/Elena/command-line-arguments.elena index 538889e4e8..5fc9385721 100644 --- a/Task/Command-line-arguments/Elena/command-line-arguments.elena +++ b/Task/Command-line-arguments/Elena/command-line-arguments.elena @@ -1,8 +1,8 @@ import system'routines; import extensions; -public program() +public Program() { - program_arguments.forEvery::(int i) - { console.printLine("Argument ",i," is ",program_arguments[i]) } + Program_arguments.forEvery::(int i) + { Console.printLine("Argument ",i," is ",Program_arguments[i]) } } diff --git a/Task/Command-line-arguments/Elixir/command-line-arguments-1.elixir b/Task/Command-line-arguments/Elixir/command-line-arguments-1.ex similarity index 100% rename from Task/Command-line-arguments/Elixir/command-line-arguments-1.elixir rename to Task/Command-line-arguments/Elixir/command-line-arguments-1.ex diff --git a/Task/Command-line-arguments/Elixir/command-line-arguments-2.elixir b/Task/Command-line-arguments/Elixir/command-line-arguments-2.ex similarity index 100% rename from Task/Command-line-arguments/Elixir/command-line-arguments-2.elixir rename to Task/Command-line-arguments/Elixir/command-line-arguments-2.ex diff --git a/Task/Command-line-arguments/Emacs-Lisp/command-line-arguments.l b/Task/Command-line-arguments/Emacs-Lisp/command-line-arguments.el similarity index 100% rename from Task/Command-line-arguments/Emacs-Lisp/command-line-arguments.l rename to Task/Command-line-arguments/Emacs-Lisp/command-line-arguments.el diff --git a/Task/Command-line-arguments/Euphoria/command-line-arguments.euphoria b/Task/Command-line-arguments/Euphoria/command-line-arguments.eu similarity index 100% rename from Task/Command-line-arguments/Euphoria/command-line-arguments.euphoria rename to Task/Command-line-arguments/Euphoria/command-line-arguments.eu diff --git a/Task/Command-line-arguments/FutureBasic/command-line-arguments.basic b/Task/Command-line-arguments/FutureBasic/command-line-arguments.basic new file mode 100644 index 0000000000..ed30014088 --- /dev/null +++ b/Task/Command-line-arguments/FutureBasic/command-line-arguments.basic @@ -0,0 +1,14 @@ +include "NSLog.incl" + +void local fn DoCommandLineArguments + CFArrayRef args = fn ProcessInfoArguments + NSLog(@"This program is named %@.",args[0]) + NSLog(@"There are %d arguments.",len(args)-1) + for long i = 1 to len(args)-1 + NSLog(@"the argument #%d is %@", i, args[i]) + next +end fn + +fn DoCommandLineArguments + +HandleEvents diff --git a/Task/Command-line-arguments/Julia/command-line-arguments.julia b/Task/Command-line-arguments/Julia/command-line-arguments.jl similarity index 100% rename from Task/Command-line-arguments/Julia/command-line-arguments.julia rename to Task/Command-line-arguments/Julia/command-line-arguments.jl diff --git a/Task/Command-line-arguments/Kotlin/command-line-arguments.kotlin b/Task/Command-line-arguments/Kotlin/command-line-arguments.kts similarity index 100% rename from Task/Command-line-arguments/Kotlin/command-line-arguments.kotlin rename to Task/Command-line-arguments/Kotlin/command-line-arguments.kts diff --git a/Task/Command-line-arguments/LDPL/command-line-arguments-1.ldpl b/Task/Command-line-arguments/LDPL/command-line-arguments-1.ldpl new file mode 100644 index 0000000000..26aa218485 --- /dev/null +++ b/Task/Command-line-arguments/LDPL/command-line-arguments-1.ldpl @@ -0,0 +1,10 @@ +DATA: + argument_count IS NUMBER + +PROCEDURE: + GET LENGTH OF argv IN argument_count + IF argument_count IS EQUAL TO 0 THEN + DISPLAY "No arguments!" CRLF + ELSE + DISPLAY argv:0 CRLF + END IF diff --git a/Task/Command-line-arguments/LDPL/command-line-arguments-2.ldpl b/Task/Command-line-arguments/LDPL/command-line-arguments-2.ldpl new file mode 100644 index 0000000000..6cc4b9df78 --- /dev/null +++ b/Task/Command-line-arguments/LDPL/command-line-arguments-2.ldpl @@ -0,0 +1,6 @@ +$ ldpl argv.ldpl +* Loading argv.ldpl +* Compiling argv.ldpl +* Building argv-bin +* Saved as argv-bin +* File(s) compiled successfully. diff --git a/Task/Command-line-arguments/LDPL/command-line-arguments-3.ldpl b/Task/Command-line-arguments/LDPL/command-line-arguments-3.ldpl new file mode 100644 index 0000000000..ff51e1fe0c --- /dev/null +++ b/Task/Command-line-arguments/LDPL/command-line-arguments-3.ldpl @@ -0,0 +1,4 @@ +$ ./argv-bin test +test +$ ./argv-bin +No arguments! diff --git a/Task/Command-line-arguments/OCaml/command-line-arguments-1.ocaml b/Task/Command-line-arguments/OCaml/command-line-arguments-1.ml similarity index 100% rename from Task/Command-line-arguments/OCaml/command-line-arguments-1.ocaml rename to Task/Command-line-arguments/OCaml/command-line-arguments-1.ml diff --git a/Task/Command-line-arguments/OCaml/command-line-arguments-2.ocaml b/Task/Command-line-arguments/OCaml/command-line-arguments-2.ml similarity index 100% rename from Task/Command-line-arguments/OCaml/command-line-arguments-2.ocaml rename to Task/Command-line-arguments/OCaml/command-line-arguments-2.ml diff --git a/Task/Command-line-arguments/PascalABC.NET/command-line-arguments.pas b/Task/Command-line-arguments/PascalABC.NET/command-line-arguments.pas new file mode 100644 index 0000000000..657c2b12b1 --- /dev/null +++ b/Task/Command-line-arguments/PascalABC.NET/command-line-arguments.pas @@ -0,0 +1,4 @@ +begin + for var i:=1 to ParamCount do + Print(ParamStr(i)); +end. diff --git a/Task/Command-line-arguments/Pluto/command-line-arguments.pluto b/Task/Command-line-arguments/Pluto/command-line-arguments.pluto new file mode 100644 index 0000000000..b002fdaeb6 --- /dev/null +++ b/Task/Command-line-arguments/Pluto/command-line-arguments.pluto @@ -0,0 +1 @@ +arg:slice(1):foreach(print) diff --git a/Task/Command-line-arguments/PowerShell/command-line-arguments.psh b/Task/Command-line-arguments/PowerShell/command-line-arguments.ps1 similarity index 100% rename from Task/Command-line-arguments/PowerShell/command-line-arguments.psh rename to Task/Command-line-arguments/PowerShell/command-line-arguments.ps1 diff --git a/Task/Command-line-arguments/REXX/command-line-arguments-1.rexx b/Task/Command-line-arguments/REXX/command-line-arguments-1.rexx index 2355afa823..7d8785a1c8 100644 --- a/Task/Command-line-arguments/REXX/command-line-arguments-1.rexx +++ b/Task/Command-line-arguments/REXX/command-line-arguments-1.rexx @@ -1,2 +1,32 @@ -say 'command arguments:' -say arg(1) +-- 12 Sep 2025 +include Setting + +-- Use arguments -c "alpha beta" -h "gamma" +say 'COMMAND-LINE ARGUMENTS (SPACE SEPARATED)' +say version +say +say 'parse arg xx:' +parse arg xx; say 'xx='xx +say +say 'arg xx:' +arg xx; say 'xx='xx +say +say 'arg x1 x2 x3 x4 x5:' +arg x1 x2 x3 x4 x5; say 'x1='x1 'x2='x2 'x3='x3 'x4='x4 'x5='x5 +say +say 'parse arg x1 x2 x3 x4 x5:' +parse arg x1 x2 x3 x4 x5; say 'x1='x1 'x2='x2 'x3='x3 'x4='x4 'x5='x5 +say +say 'arg x1 . x3 (placeholder):' +arg x1 . x3; say 'x1='x1 'x3='x3 +say +say 'Arg(1):' +say Arg(1) +say +say 'Words:' +do n = 1 to Words(Arg(1)) + say 'n='n 'Word(Arg(1),n)='Word(Arg(1),n) +end +exit + +include Abend diff --git a/Task/Command-line-arguments/REXX/command-line-arguments-2.rexx b/Task/Command-line-arguments/REXX/command-line-arguments-2.rexx index bd43c95964..3b97099b75 100644 --- a/Task/Command-line-arguments/REXX/command-line-arguments-2.rexx +++ b/Task/Command-line-arguments/REXX/command-line-arguments-2.rexx @@ -1,22 +1,27 @@ -parse arg aaa /*get the arguments. */ - /*another version: */ - /* aaa=arg(1) */ -say 'command arguments:' -say aaa +-- 12 Sep 2025 +include Setting -opts='' /*placeholder for options. */ -data='' /*placeholder for data. */ - - do j=1 to words(aaa) - x=word(aaa,j) - if left(x,1)=='-' then opts=opts x /*Option? Then add to opts.*/ - else data=data x /*Must be data. Add to data.*/ - end - - /*the above process adds a leading blank to OPTS and DATA*/ - -opts=strip(opts,'L') /*strip leading blanks. */ -data=strip(data,'l') /*strip leading blanks. */ +-- Use arguments -c,alpha beta,-h,gamma +say 'COMMAND-LINE ARGUMENTS (COMMA SEPARATED)' +say version say -say 'options='opts -say ' data='data +say 'parse arg xx:' +parse arg xx; say xx +say +say 'arg xx:' +arg xx; say xx +say +say 'parse arg x1,x2,x3,x4:' +parse arg x1','x2','x3','x4; say 'x1' x1 'x2' x2 'x3' x3 'x4' x4 +say +say 'arg x1,x2,x3,x4:' +arg x1','x2','x3','x4; say 'x1' x1 'x2' x2 'x3' x3 'x4' x4 +say +say 'parse arg x1,.,x3 (placeholder):' +parse arg x1','.','x3; say 'x1' x1 'x3' x3 +say +say 'arg(1):' +say arg(1) +exit + +include Abend diff --git a/Task/Command-line-arguments/Rust/command-line-arguments-1.rust b/Task/Command-line-arguments/Rust/command-line-arguments-1.rs similarity index 100% rename from Task/Command-line-arguments/Rust/command-line-arguments-1.rust rename to Task/Command-line-arguments/Rust/command-line-arguments-1.rs diff --git a/Task/Command-line-arguments/Rust/command-line-arguments-2.rust b/Task/Command-line-arguments/Rust/command-line-arguments-2.rs similarity index 100% rename from Task/Command-line-arguments/Rust/command-line-arguments-2.rust rename to Task/Command-line-arguments/Rust/command-line-arguments-2.rs diff --git a/Task/Command-line-arguments/Scheme/command-line-arguments.ss b/Task/Command-line-arguments/Scheme/command-line-arguments.scm similarity index 100% rename from Task/Command-line-arguments/Scheme/command-line-arguments.ss rename to Task/Command-line-arguments/Scheme/command-line-arguments.scm diff --git a/Task/Command-line-arguments/TAV/command-line-arguments.tav b/Task/Command-line-arguments/TAV/command-line-arguments.tav new file mode 100644 index 0000000000..9586ed1181 --- /dev/null +++ b/Task/Command-line-arguments/TAV/command-line-arguments.tav @@ -0,0 +1,3 @@ +main (parms):+ + ?# i =: give keys parms + print i __ parms[i] diff --git a/Task/Command-line-arguments/Tcl/command-line-arguments-1.tcl b/Task/Command-line-arguments/Tcl/command-line-arguments-1.tcl new file mode 100644 index 0000000000..3e39085837 --- /dev/null +++ b/Task/Command-line-arguments/Tcl/command-line-arguments-1.tcl @@ -0,0 +1,3 @@ +if { $argc >= 1 } { + puts [lindex $argv 0] +} diff --git a/Task/Command-line-arguments/Tcl/command-line-arguments-2.tcl b/Task/Command-line-arguments/Tcl/command-line-arguments-2.tcl new file mode 100644 index 0000000000..8db1f98495 --- /dev/null +++ b/Task/Command-line-arguments/Tcl/command-line-arguments-2.tcl @@ -0,0 +1,2 @@ +$ tclsh file.tcl test +test diff --git a/Task/Command-line-arguments/Tcl/command-line-arguments.tcl b/Task/Command-line-arguments/Tcl/command-line-arguments.tcl deleted file mode 100644 index 0827817f9e..0000000000 --- a/Task/Command-line-arguments/Tcl/command-line-arguments.tcl +++ /dev/null @@ -1,3 +0,0 @@ -if { $argc > 1 } { - puts [lindex $argv 1] -} diff --git a/Task/Command-line-arguments/Uiua/command-line-arguments.uiua b/Task/Command-line-arguments/Uiua/command-line-arguments.uiua new file mode 100644 index 0000000000..6d3c8fe5b3 --- /dev/null +++ b/Task/Command-line-arguments/Uiua/command-line-arguments.uiua @@ -0,0 +1 @@ +&args diff --git a/Task/Command-line-arguments/VBScript/command-line-arguments.vb b/Task/Command-line-arguments/VBScript/command-line-arguments.vbs similarity index 100% rename from Task/Command-line-arguments/VBScript/command-line-arguments.vb rename to Task/Command-line-arguments/VBScript/command-line-arguments.vbs diff --git a/Task/Command-line-arguments/X86-64-Assembly/command-line-arguments.x86-64 b/Task/Command-line-arguments/X86-64-Assembly/command-line-arguments.x86-64 new file mode 100644 index 0000000000..42af33fb12 --- /dev/null +++ b/Task/Command-line-arguments/X86-64-Assembly/command-line-arguments.x86-64 @@ -0,0 +1,58 @@ +format ELF64 executable 3 +entry start + +segment executable readable +start: + pop rax ; pop argc off stack. It should be at least 1 + .loop0: + pop rdi ; pop the pointer to argument string off stack + call prints ; call a function to print a string + mov rdi, 0x0a ; parameter to next function. 0x0a = line feed = 10 + call printc ; call a function to print a single character + dec rax ; decrement RAX. + jnz .loop0 ; get next argument if RAX is not yet 0 + .exit: + mov rax, 60 + mov rdi, 0 + syscall + +prints: ; function that prints a zero terminated string + push rax + push rdi + push rsi + push rdx + xor rdx, rdx + cmp byte [rdi + rdx], 0 + je .return + .stloop: + cmp byte [rdi + rdx], 0 + je .printit + inc rdx + jmp .stloop + .printit: + mov rax, 1 + mov rsi, rdi + mov rdi, 1 + syscall + .return: + pop rdx + pop rsi + pop rdi + pop rax + ret + +printc: ;function that prints a single character in rdi (dil). + push rax + push rsi + push rdx + push rdi + mov rax, 1 + mov rdi, 1 + mov rsi, rsp + mov rdx, 1 + syscall + pop rdi + pop rdx + pop rsi + pop rax + ret diff --git a/Task/Command-line-arguments/Zig/command-line-arguments.zig b/Task/Command-line-arguments/Zig/command-line-arguments.zig new file mode 100644 index 0000000000..5b35ff255c --- /dev/null +++ b/Task/Command-line-arguments/Zig/command-line-arguments.zig @@ -0,0 +1,13 @@ +const std = @import("std"); + +pub fn main() !void { + const stdout = std.io.getStdOut().writer(); + + var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); + defer arena.deinit(); + const allocator = arena.allocator(); + + const args = try std.process.argsAlloc(allocator); + + try stdout.print("{s}\n", .{args}); +} diff --git a/Task/Commatizing-numbers/ALGOL-68/commatizing-numbers.alg b/Task/Commatizing-numbers/ALGOL-68/commatizing-numbers.alg index 290bfb3719..161b62d233 100644 --- a/Task/Commatizing-numbers/ALGOL-68/commatizing-numbers.alg +++ b/Task/Commatizing-numbers/ALGOL-68/commatizing-numbers.alg @@ -53,35 +53,48 @@ PROC commatize = ( STRING text, INT location, INT period, STRING separator )STRI # commatizing procedure # MODE COMMATIZINGOPTIONS = STRUCT( STRING text, INT location, INT period, STRING separator ); PRIO LOCATION = 9; -OP LOCATION = ( STRING text, INT location )COMMATIZINGOPTIONS: COMMATIZINGOPTIONS( text, location, 0, "" ); +OP LOCATION = ( STRING text, INT location )COMMATIZINGOPTIONS: + COMMATIZINGOPTIONS( text, location, 0, "" ); PRIO PERIOD = 9; -OP PERIOD = ( STRING text, INT period )COMMATIZINGOPTIONS: COMMATIZINGOPTIONS( text, 0, period, "" ); +OP PERIOD = ( STRING text, INT period )COMMATIZINGOPTIONS: + COMMATIZINGOPTIONS( text, 0, period, "" ); PRIO SEPARATOR = 9; -OP SEPARATOR = ( STRING text, CHAR separator )COMMATIZINGOPTIONS: COMMATIZINGOPTIONS( text, 0, 0, separator ); -OP SEPARATOR = ( STRING text, STRING separator )COMMATIZINGOPTIONS: COMMATIZINGOPTIONS( text, 0, 0, separator ); +OP SEPARATOR = ( STRING text, CHAR separator )COMMATIZINGOPTIONS: + COMMATIZINGOPTIONS( text, 0, 0, separator ); +OP SEPARATOR = ( STRING text, STRING separator )COMMATIZINGOPTIONS: + COMMATIZINGOPTIONS( text, 0, 0, separator ); OP LOCATION = ( COMMATIZINGOPTIONS opts, INT location )COMMATIZINGOPTIONS: - COMMATIZINGOPTIONS( text OF opts, location, period OF opts, separator OF opts ); + COMMATIZINGOPTIONS( text OF opts, location, period OF opts, separator OF opts ); OP PERIOD = ( COMMATIZINGOPTIONS opts, INT period )COMMATIZINGOPTIONS: - COMMATIZINGOPTIONS( text OF opts, location OF opts, period, separator OF opts ); + COMMATIZINGOPTIONS( text OF opts, location OF opts, period, separator OF opts ); OP SEPARATOR = ( COMMATIZINGOPTIONS opts, CHAR separator )COMMATIZINGOPTIONS: - COMMATIZINGOPTIONS( text OF opts, location OF opts, period OF opts, separator ); + COMMATIZINGOPTIONS( text OF opts, location OF opts, period OF opts, separator ); OP SEPARATOR = ( COMMATIZINGOPTIONS opts, STRING separator )COMMATIZINGOPTIONS: - COMMATIZINGOPTIONS( text OF opts, location OF opts, period OF opts, separator ); + COMMATIZINGOPTIONS( text OF opts, location OF opts, period OF opts, separator ); OP COMMATIZE = ( STRING text )STRING: commatize( text, 0, 0, "" ); OP COMMATIZE = ( COMMATIZINGOPTIONS opts )STRING: - commatize( text OF opts, location OF opts, period OF opts, separator OF opts ); + commatize( text OF opts, location OF opts, period OF opts, separator OF opts ); # test the commatization procedure and operators # -print( ( COMMATIZE( "pi=3.14159265358979323846264338327950288419716939937510582097494459231" PERIOD 5 SEPARATOR " " LOCATION 6 ), - newline ) ); -print( ( COMMATIZE( "The author has two Z$100000000000000 Zimbabwe notes (100 trillion)." SEPARATOR "." ), newline ) ); -print( ( COMMATIZE """-in Aus$+1411.8millions""", newline ) ); -print( ( COMMATIZE "===US$0017440 millions=== (in 2000 dollars)", newline ) ); -print( ( COMMATIZE "123.e8000 is pretty big.", newline ) ); -print( ( COMMATIZE "The land area of the earth is 57268900(29% of the surface) square miles.", newline ) ); -print( ( COMMATIZE "Ain't no numbers in this here words, nohow, no way, Jose.", newline ) ); -print( ( COMMATIZE "James was never known as 0000000007", newline ) ); -print( ( COMMATIZE "Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.", - newline ) ); -print( ( COMMATIZE " $-140000±100 millions.", newline ) ); -print( ( COMMATIZE "6/9/1946 was a good year for some.", newline ) ) +print( ( COMMATIZE( "pi=3.14159265358979323846264338327950288419716939937510582097494459231" + PERIOD 5 SEPARATOR " " LOCATION 6 ), newline ) ); +print( ( COMMATIZE( "The author has two Z$100000000000000 Zimbabwe notes (100 trillion)." + SEPARATOR "." ), newline ) ); +print( ( COMMATIZE( "The author has two Z$100000000000000 Zimbabwe notes (100 trillion)." + SEPARATOR "." PERIOD 6 ), newline ) ); +print( ( COMMATIZE( "The author has two Z$100000000000000 Zimbabwe notes (100 trillion)." + SEPARATOR "__" ), newline ) ); +print( ( COMMATIZE( "The author has two Z$100000000000000 Zimbabwe notes (100 trillion)." + LOCATION 26 PERIOD 1 SEPARATOR "::" ), newline ) ); +print( ( COMMATIZE """-in Aus$+1411.8millions""", newline ) ); +print( ( COMMATIZE "===US$0017440 millions=== (in 2000 dollars)", newline ) ); +print( ( COMMATIZE "123.e8000 is pretty big.", newline ) ); +print( ( COMMATIZE "The land area of the earth is 57268900(29% of the surface) square miles.", newline ) ); +print( ( COMMATIZE "Ain't no numbers in this here words, nohow, no way, Jose.", newline ) ); +print( ( COMMATIZE "James was never known as 0000000007", newline ) ); +print( ( COMMATIZE ( "Arthur Eddington wrote: I believe there are " + + "15747724136275002577605653961181555468044717914527116709366231425076185631031296 " + + "protons in the universe." + ), newline ) ); +print( ( COMMATIZE " $-140000±100 millions.", newline ) ); +print( ( COMMATIZE "6/9/1946 was a good year for some.", newline ) ) diff --git a/Task/Commatizing-numbers/Ballerina/commatizing-numbers.ballerina b/Task/Commatizing-numbers/Ballerina/commatizing-numbers.ballerina new file mode 100644 index 0000000000..9b5aaf9eca --- /dev/null +++ b/Task/Commatizing-numbers/Ballerina/commatizing-numbers.ballerina @@ -0,0 +1,90 @@ +import ballerina/io; + +function commatize(string s, int begin = 0, int step = 3, string sep = ",") { + var invert = function(string n) returns string { + string t = ""; + foreach int i in int:range(n.length() - 1, -1, -1) { t += n[i]; } + return t; + }; + + var addSeps = function(string nn, boolean dp) returns string { + string n = nn; + string lz = ""; + if !dp && n.startsWith("0") && n != "0" { + string:RegExp pattern = re `^0+`; + string k = pattern.replace(n, ""); + if k == "" { k = "0"; } + foreach int i in 1 ... n.length() - k.length() { lz += "0"; } + n = k; + } + if dp { n = invert(n); } // invert if after decimal point + int i = n.length() - step; + while i >= 1 { + n = n.substring(0, i) + sep + n.substring(i); + i -= step; + } + if dp { n = invert(n); } // invert back + return lz + n; + }; + + var isExponent = function(string:Char c) returns boolean { + return "eEdDpP^∙x↑*⁰¹²³⁴⁵⁶⁷⁸⁹".includes(c); + }; + + string t = s; + string acc = (begin == 0) ? "" : t.substring(0, begin); + string n = ""; + boolean dp = false; + foreach int j in begin ..< t.length() { + string:Char c = t[j]; + if c >= "0" && c <= "9" { + n += t[j]; + if j == t.length() - 1 { + if acc != "" && isExponent(acc[acc.length() - 1]) { + acc = s; + } else { + acc += addSeps(n, dp); + } + } + } else if n != "" { + if acc != "" && isExponent(acc[acc.length() - 1]) { + acc = s; + break; + } else if t[j] != "." { + acc += addSeps(n, dp) + t.substring(j); + break; + } else { + acc += addSeps(n, dp) + t[j]; + dp = true; + n = ""; + } + } else { + acc += t[j]; + } + } + io:println(s); + io:println(acc); + io:println(); +} + +public function main() { + commatize("123456789.123456789", 0, 2, "*"); + commatize(".123456789", 0, 3, "-"); + commatize("57256.1D-4", 0, 4, "__"); + commatize("pi=3.14159265358979323846264338327950288419716939937510582097494459231", 0, 5, " "); + commatize("The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", 0, 3, "."); + + string[] defaults = [ + "\"-in Aus$+1411.8millions\"", + "===US$0017440 millions=== (in 2000 dollars)", + "123.e8000 is pretty big.", + "The land area of the earth is 57268900(29% of the surface) square miles.", + "Ain't no numbers in this here words, nohow, no way, Jose.", + "James was never known as 0000000007", + "Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.", + " $-140000±100 millions.", + "6/9/1946 was a good year for some." + ]; + + foreach string d in defaults { commatize(d); } +} diff --git a/Task/Commatizing-numbers/C++/commatizing-numbers.cpp b/Task/Commatizing-numbers/C++/commatizing-numbers.cpp new file mode 100644 index 0000000000..f9e7ce9e09 --- /dev/null +++ b/Task/Commatizing-numbers/C++/commatizing-numbers.cpp @@ -0,0 +1,46 @@ +#include +#include +#include +#include + +bool contains(const std::string& haystack, const char needle) { + return haystack.find(needle) != std::string::npos; +} + +void commatize(std::string text, const int32_t& start_index = 0, + const int32_t& step = 3, const std::string& separator = ",") { + std::cout << "Before: " << text << std::endl; + const int32_t size = text.size(); + + for ( int32_t i = start_index; i < size; ++i ) { + if ( contains("123456789", text[i]) ) { + for ( int32_t j = i + 1; j <= size; ++j ) { + if ( j > size || ! contains("0123456789", text[j]) ) { + for ( int32_t k = j - 1 - step; k >= i; k -= step ) { + text.insert(k + 1, separator); + } + break; + } + } + break; + } + } + + std::cout << " After: " << text << std::endl << std::endl; +} + +int main() { + commatize("pi=3.14159265358979323846264338327950288419716939937510582097494459231", 6, 5, " "); + commatize("The author has two Z$100000000000000 Zimbabwe notes (100 trillion)."); + commatize("\"-in Aus$+1411.8millions\""); + commatize("===US$0017440 millions=== (in 2000 dollars)"); + commatize("123.e8000 is pretty big."); + commatize("The land area of the earth is 57268900(29% of the surface) square miles."); + commatize("Ain't no numbers in this here words, nohow, no way, Jose."); + commatize("James was never known as 0000000007"); + commatize("Arthur Eddington wrote: I believe there are " + "15747724136275002577605653961181555468044717914527116709366231425076185631031296" + " protons in the universe."); + commatize(" $-140000±100 millions."); + commatize("6/9/1946 was a good year for some."); +} diff --git a/Task/Commatizing-numbers/Delphi/commatizing-numbers.delphi b/Task/Commatizing-numbers/Delphi/commatizing-numbers.pas similarity index 100% rename from Task/Commatizing-numbers/Delphi/commatizing-numbers.delphi rename to Task/Commatizing-numbers/Delphi/commatizing-numbers.pas diff --git a/Task/Commatizing-numbers/Fortran/commatizing-numbers.f b/Task/Commatizing-numbers/Fortran/commatizing-numbers.f new file mode 100644 index 0000000000..626b9ccf8f --- /dev/null +++ b/Task/Commatizing-numbers/Fortran/commatizing-numbers.f @@ -0,0 +1,207 @@ +! Commatizing numbers +! +! tested with Intel ifx (IFX) 2025.2.1 20250806 on Kubuntu 25.04 +! GNU Fortran (Ubuntu 14.2.0-19ubuntu2) 14.2.0 on Kubuntu 25.04 +! Note that VSI Fortran on VMS does not compile this code because its current version +! cannot handle allocatable character strings +! +! U.B., August 2025 +! +program commatisator + +implicit none + +logical, parameter ::DEBUG=.false. + + +call commatize("pi=3.14159265358979323846264338327950288419716939937510582097494459231", 3, 5) +call commatize("The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", 1,3, '.') ! Use decimal point as separator +call commatize('"-in Aus$+1411.8millions"') ! Here the double quotes (") are part of the text. +call commatize("===US$0017440 millions=== (in 2000 dollars)") +call commatize("123.e8000 is pretty big.") +call commatize("The land area of the earth is 57268900(29% of the surface) square miles.") +call commatize("Ain't no numbers in this here words, nohow, no way, Jose.") +call commatize("James was never known as 0000000007", 0,3) +call commatize("Arthur Eddington wrote: I believe there are " // & + "15747724136275002577605653961181555468044717914527116709366231425076185631031296" // & + " protons in the universe.") +call commatize(" $-140000±100 millions.") +call commatize("6/9/1946 was a good year for some.") + +contains + +subroutine commatize (text, astartIdx, agroupSize, aseparator) + ! Arguments + character(*), intent(in) :: text + integer, intent(in), optional :: astartIdx + integer, intent(in), optional :: agroupSize + character, intent(in), optional :: aseparator + + ! These variables are there even if optional args are omitted. + integer :: startIdx + integer :: groupSize + character :: separator + + integer :: sz, ii + integer :: ipBegin, ipPoint, ipEnd + + character(:), allocatable :: newtext + ! + ! Defaults for optional arguments + ! and protect against invalid arguments + if (present (astartIdx)) then + startIDx = max (1, astartidx) + else + startIdx = 1 + endif + if (present (agroupSize)) then + groupsize = max(1, agroupsize) + else + groupsize = 3 + endif + if (present (aseparator)) then + separator = aseparator + else + separator = ',' + endif + + sz = len (text) + ipBegin = 0 + ipPoint = 0 + ipEnd = 0 + + ! Find beginning and end of the first numeric part of the string + do ii=startidx,sz + if (isadigit (text(ii:ii), '1','9')) then ! ignoring leading zeroes + ipBegin = ii + exit ! Only the very first number is of any interest. + else if (text(ii:ii) .eq. '.') then ! Leading Decimal point + if (ii .lt. sz) then + if (isadigit (text(ii+1:ii+1), '0','9')) then ! must be followed by a valid digit + ! Entire number starts here, it is something valid like ".123" + if (DEBUG) print *, 'Decimal point detected at ii,sz= ', ii, sz + ipBegin = ii + ipPoint = ii + exit + endif + endif + end if + end do + + ! Any number detected? Search for the end and, if necessary, the decimal point + if (ipBegin .gt. 0 .and. ipBegin .le. sz) then + do ii=ipBegin+1, sz+1 + if (ii > sz) then + ipEnd = sz + else if (text(ii:ii) .eq. '.' .and. ipPoint .eq. 0 .and. ii .lt. sz ) then + if (isadigit (text(ii+1:ii+1), '0','9')) then ! Decimal point must be followed by valid digit + ipPoint = ii + else + ipEnd = ii-1 ! Might be valid decimal point, but terminates the number. + exit ! no need to continue, have found the end. + endif + else if (.not. isadigit (text(ii:ii), '0','9')) then ! Anything other than a digit or point terminated the number. + ipEnd = ii-1 + exit + end if + enddo + end if + + ! Found a number? + ! Three possibe cases: real number (>=1) with decimal point and digits before and after + ! real number (<1) starting with decimal point such as .71 + ! integer number without decimal point. + if (ipBegin .ne. 0) then ! Any nmumber + if (ipPoint .gt. ipbegin) then ! Not starting with a decimal point but decimal point inside + if (ipBegin .gt. 1) then + newtext = text (:ipBegin-1) ! copy entire text before the numeric + else + newtext = '' ! In any case variable 'newtext' must be initialized + end if + newtext = newtext // setSeparators (text, ipPoint-1, ipBegin, & + groupsize, separator , requiredSize (ipPoint-1, ipBegin, groupsize)) // '.' + newtext = newtext // setSeparators (text, ipPoint+1, ipEnd, & + groupsize, separator, requiredSize (ipPoint+1, ipEnd ,groupsize)) + else if (ipPoint .ne. 0 .and. ipPoint .lt. sz) then ! Starting with decimal point + newtext = '.' // setSeparators (text, ipPoint+1, ipEnd, & + groupsize, separator, requiredSize (ipPoint+1, ipEnd,groupsize) ) + else ! Integer number + newtext = text (:ipBegin-1) // setSeparators (text, ipEnd, ipBegin, & + groupsize, separator, requiredSize (ipEnd, ipBegin, groupsize) ) + endif + if (ipEnd .lt. sz) then + newtext = newtext // text (ipend+1:) ! Append alltext behind the number + endif + else ! No number, just print straight copy + newtext = text + endif + + print '("Before: ", A)' , text + print '(" After: ", A/)', newtext + + +end subroutine commatize + + ! estimate how many separators wii be needed in a given range of digits + ! and calculate the new tring length therefrom. + function requiredSize (i0,i1,step) result (size) + integer, intent(in) :: i0, i1, step + integer :: size + integer :: l,c + + l = iabs (i1-i0) + 1 ! Length of the string to be considered + c = (l-1) / step ! Number of separators to insert + + size = l + c + end function requiredSize + + ! Insert separators into a numerical string + function setSeparators (text, i0, i1, step, separator, resSize ) result (ntext ) + character(*), intent(in) :: text ! entire text + integer, intent(in) :: i0,i1 ! The numeric part goes from i0 to i1 (incl) + integer, intent(in) :: step ! the group size between separators + character, intent(in) :: separator ! the separator character + integer, intent(in) :: resSize ! New size of result string + character(len=resSize) :: ntext ! The resultant string, including th e separators + integer :: ii, jj, cnt, direction ! Helpers + + ! character-wise copy the old text into new text + ! Loop index can go into either direction + if (i0 .gt. i1 ) then + direction = -1 + else + direction = 1 + end if + + ! Position of text(ii:ii) inside the resultant text + if (i0 .lt. i1) then + jj = 1 + else + jj = resSize + end if + + cnt = 0 + do ii = i0, i1, direction + ntext (jj:jj) = text (ii:ii) ! Copy characters + jj = jj + direction + cnt = cnt + 1 ! count copied characters + ! Group complete? Insert separator + if (cnt .eq. step .and. jj .gt. 0 .and. jj .lt. resSize) then + ntext(jj:jj) = separator + jj = jj + direction + cnt = 0 + end if + end do + end function setSeparators + +! Decide if a given character c is a digit in the range from "from" to "to". +function isadigit (c, from, to) result (YN) + character, intent(in) :: c, from, to + logical :: YN + + YN = c>= from .and. c<=to +end function isadigit + + + +end program commatisator diff --git a/Task/Commatizing-numbers/JavaScript/commatizing-numbers.js b/Task/Commatizing-numbers/JavaScript/commatizing-numbers.js new file mode 100644 index 0000000000..ab6c8185ab --- /dev/null +++ b/Task/Commatizing-numbers/JavaScript/commatizing-numbers.js @@ -0,0 +1,42 @@ +function contains(haystack, needle) { + return haystack.indexOf(needle) !== -1; +} + +function commatize(text, start_index = 0, step = 3, separator = ",") { + console.log("Before: " + text); + const size = text.length; + + for (let i = start_index; i < size; ++i) { + if (contains("123456789", text[i])) { + for (let j = i + 1; j <= size; ++j) { + if (j > size || !contains("0123456789", text[j])) { + for (let k = j - 1 - step; k >= i; k -= step) { + text = text.slice(0, k + 1) + separator + text.slice(k + 1); + } + break; + } + } + break; + } + } + + console.log(" After: " + text + "\n"); +} + +function main() { + commatize("pi=3.14159265358979323846264338327950288419716939937510582097494459231", 6, 5, " "); + commatize("The author has two Z$100000000000000 Zimbabwe notes (100 trillion)."); + commatize("\"-in Aus$+1411.8millions\""); + commatize("===US$0017440 millions=== (in 2000 dollars)"); + commatize("123.e8000 is pretty big."); + commatize("The land area of the earth is 57268900(29% of the surface) square miles."); + commatize("Ain't no numbers in this here words, nohow, no way, Jose."); + commatize("James was never known as 0000000007"); + commatize("Arthur Eddington wrote: I believe there are " + + "15747724136275002577605653961181555468044717914527116709366231425076185631031296" + + " protons in the universe."); + commatize(" $-140000±100 millions."); + commatize("6/9/1946 was a good year for some."); +} + +main(); diff --git a/Task/Commatizing-numbers/Julia/commatizing-numbers.julia b/Task/Commatizing-numbers/Julia/commatizing-numbers.jl similarity index 100% rename from Task/Commatizing-numbers/Julia/commatizing-numbers.julia rename to Task/Commatizing-numbers/Julia/commatizing-numbers.jl diff --git a/Task/Commatizing-numbers/Kotlin/commatizing-numbers.kotlin b/Task/Commatizing-numbers/Kotlin/commatizing-numbers.kts similarity index 100% rename from Task/Commatizing-numbers/Kotlin/commatizing-numbers.kotlin rename to Task/Commatizing-numbers/Kotlin/commatizing-numbers.kts diff --git a/Task/Commatizing-numbers/Pluto/commatizing-numbers.pluto b/Task/Commatizing-numbers/Pluto/commatizing-numbers.pluto new file mode 100644 index 0000000000..a364a0fa06 --- /dev/null +++ b/Task/Commatizing-numbers/Pluto/commatizing-numbers.pluto @@ -0,0 +1,78 @@ +require "uchar" + +local function commatize(s, start = 1, step = 3, sep = ",") + local function add_seps(n, dp) + local lz = "" + if !dp and n:startswith("0") and n != "0" then + local k = n:lstrip("0") + if k == "" then k = "0" end + lz = "0":rep(#n - #k) + n = k + end + if dp then n = n:reverse() end -- invert if after decimal point + local i = #n - step + 1 + while i >= 2 do + n = n:sub(1, i - 1) .. sep .. n:sub(i) + i -= step + end + if dp then n = n:reverse() end -- invert back + return lz .. n + end + + local function is_exponent(c) return c in "eEdDpP^∙x↑*⁰¹²³⁴⁵⁶⁷⁸⁹" end + + local t = uchar.of(s) + local acc = start == 1 ? "" : t:sub(1, start - 1) + local n = "" + local dp = false + for j = start, t:len() do + local c = t:get(j) + if c >= "0" and c <= "9" then + n ..= t:get(j) + if j == t:len() do + if acc != "" and is_exponent(acc[-1]) then + acc = s + else + acc ..= add_seps(n, dp) + end + end + elseif n != "" then + if acc != "" and is_exponent(acc[-1]) then + acc = s + break + elseif t:get(j) != "." then + acc ..= add_seps(n, dp) .. t:sub(j) + break + else + acc ..= add_seps(n, dp) .. t:get(j) + dp = true + n = "" + end + else + acc ..= t:get(j) + end + end + print(s); + print(acc); + print() +end + +commatize("123456789.123456789", 1, 2, "*") +commatize(".123456789", 1, 3, "-") +commatize("57256.1D-4", 1, 4, "__") +commatize("pi=3.14159265358979323846264338327950288419716939937510582097494459231", 1, 5, " ") +commatize("The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", 1, 3, ".") + +local defaults = { + "\"-in Aus$+1411.8millions\"", + "===US$0017440 millions=== (in 2000 dollars)", + "123.e8000 is pretty big.", + "The land area of the earth is 57268900(29% of the surface) square miles.", + "Ain't no numbers in this here words, nohow, no way, Jose.", + "James was never known as 0000000007", + "Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.", + " $-140000±100 millions.", + "6/9/1946 was a good year for some." +} + +for defaults as d do commatize(d) end diff --git a/Task/Commatizing-numbers/Rust/commatizing-numbers.rs b/Task/Commatizing-numbers/Rust/commatizing-numbers.rs new file mode 100644 index 0000000000..cc7751fc9f --- /dev/null +++ b/Task/Commatizing-numbers/Rust/commatizing-numbers.rs @@ -0,0 +1,45 @@ +use itertools::Itertools; + +fn commatize(old_text: &str, start_index: usize, step: usize, sep: &str) -> String { + let mut text = old_text.to_string(); + let len = text.len(); + let textchars = text.chars().collect_vec(); + for i in start_index..len { + if "123456789".contains(textchars[i]) { + for j in i + 1..=len { + if j >= len || !"0123456789".contains(textchars[j]) { //start at end + if step <= j - i { + for k in (i..j - step).rev().step_by(step) { + text.insert_str(k + 1, sep); + } + break; + } + } + } + break; + } + } + return text; +} + +fn main() { + let tests = [ + ("pi=3.14159265358979323846264338327950288419716939937510582097494459231", 6, 5, " "), + ("The author has two Z$100000000000000 Zimbabwe notes (100 trillion).", 0, 3, ","), + ("\"-in Aus$+1411.8millions\"", 0, 3, ","), + ("===US$0017440 millions=== (in 2000 dollars)", 0, 3, ","), + ("123.e8000 is pretty big.", 0, 3, ","), + ("The land area of the earth is 57268900(29% of the surface) square miles.", 0, 3, ","), + ("Ain't no numbers in this here words, nohow, no way, Jose.", 0, 3, ","), + ("James was never known as 0000000007", 0, 3, ","), + ("Arthur Eddington wrote: I believe there are 15747724136275002577605653961181555468044717914527116709366231425076185631031296 protons in the universe.", 0, 3, ","), + (" $-140000±100 millions.", 0, 3, ","), + ("6/9/1946 was a good year for some.", 0, 3, ","),]; + for t in tests { + println!( + "Before: {}\nAfter: {}\n", + t.0, + commatize(t.0, t.1, t.2, t.3) + ); + } +} diff --git a/Task/Commatizing-numbers/VBScript/commatizing-numbers.vb b/Task/Commatizing-numbers/VBScript/commatizing-numbers.vbs similarity index 100% rename from Task/Commatizing-numbers/VBScript/commatizing-numbers.vb rename to Task/Commatizing-numbers/VBScript/commatizing-numbers.vbs diff --git a/Task/Comments/Ada/comments.ada b/Task/Comments/Ada/comments.adb similarity index 100% rename from Task/Comments/Ada/comments.ada rename to Task/Comments/Ada/comments.adb diff --git a/Task/Comments/ArkScript/comments.ark b/Task/Comments/ArkScript/comments.ark new file mode 100644 index 0000000000..3c09c8229b --- /dev/null +++ b/Task/Comments/ArkScript/comments.ark @@ -0,0 +1,4 @@ +# this is a comment + +# another comment +# with another below diff --git a/Task/Comments/AutoIt/comments.au3 b/Task/Comments/AutoIt/comments.au3 new file mode 100644 index 0000000000..3fcfacc68f --- /dev/null +++ b/Task/Comments/AutoIt/comments.au3 @@ -0,0 +1,5 @@ +#cs +Everything between the cs and the ce is commented. +Commented code is not used by the computer. +#ce +;individual lines after a semicolon are commented. diff --git a/Task/Comments/AutoIt/comments.autoit b/Task/Comments/AutoIt/comments.autoit deleted file mode 100644 index 260be4b084..0000000000 --- a/Task/Comments/AutoIt/comments.autoit +++ /dev/null @@ -1,5 +0,0 @@ -#cs -Everything between the cs and and the ce is commented. -Commented code is not used by the computer. -#ce -;individual lines after a semicolon are commented. diff --git a/Task/Comments/Ballerina/comments.ballerina b/Task/Comments/Ballerina/comments.ballerina new file mode 100644 index 0000000000..42158b75f2 --- /dev/null +++ b/Task/Comments/Ballerina/comments.ballerina @@ -0,0 +1,10 @@ +// This is a single-line comment +int x = 10; // This is an inline comment + +# Represents a user record. +type User record { + # User's ID. + int id; + # User's name. + string name; +}; diff --git a/Task/Comments/Brainf---/comments.bf b/Task/Comments/Brainf---/comments-1.bf similarity index 100% rename from Task/Comments/Brainf---/comments.bf rename to Task/Comments/Brainf---/comments-1.bf diff --git a/Task/Comments/Brainf---/comments-2.bf b/Task/Comments/Brainf---/comments-2.bf new file mode 100644 index 0000000000..9b682b9f35 --- /dev/null +++ b/Task/Comments/Brainf---/comments-2.bf @@ -0,0 +1,3 @@ +[ This is a header comment ] + +++++++++[->++++++++<]>. diff --git a/Task/Comments/COBOL/comments-1.cobol b/Task/Comments/COBOL/comments-1.cob similarity index 100% rename from Task/Comments/COBOL/comments-1.cobol rename to Task/Comments/COBOL/comments-1.cob diff --git a/Task/Comments/COBOL/comments-2.cobol b/Task/Comments/COBOL/comments-2.cob similarity index 100% rename from Task/Comments/COBOL/comments-2.cobol rename to Task/Comments/COBOL/comments-2.cob diff --git a/Task/Comments/COBOL/comments-3.cobol b/Task/Comments/COBOL/comments-3.cob similarity index 100% rename from Task/Comments/COBOL/comments-3.cobol rename to Task/Comments/COBOL/comments-3.cob diff --git a/Task/Comments/COBOL/comments-4.cobol b/Task/Comments/COBOL/comments-4.cob similarity index 100% rename from Task/Comments/COBOL/comments-4.cobol rename to Task/Comments/COBOL/comments-4.cob diff --git a/Task/Comments/COBOL/comments-5.cobol b/Task/Comments/COBOL/comments-5.cob similarity index 100% rename from Task/Comments/COBOL/comments-5.cobol rename to Task/Comments/COBOL/comments-5.cob diff --git a/Task/Comments/COBOL/comments-6.cobol b/Task/Comments/COBOL/comments-6.cob similarity index 100% rename from Task/Comments/COBOL/comments-6.cobol rename to Task/Comments/COBOL/comments-6.cob diff --git a/Task/Comments/Chapel/comments.chapel b/Task/Comments/Chapel/comments.chpl similarity index 100% rename from Task/Comments/Chapel/comments.chapel rename to Task/Comments/Chapel/comments.chpl diff --git a/Task/Comments/Crystal/comments.crystal b/Task/Comments/Crystal/comments.cr similarity index 100% rename from Task/Comments/Crystal/comments.crystal rename to Task/Comments/Crystal/comments.cr diff --git a/Task/Comments/Delphi/comments.delphi b/Task/Comments/Delphi/comments.pas similarity index 100% rename from Task/Comments/Delphi/comments.delphi rename to Task/Comments/Delphi/comments.pas diff --git a/Task/Comments/Dragonstone/comments.dragonstone b/Task/Comments/Dragonstone/comments.dragonstone new file mode 100644 index 0000000000..e8359c75d5 --- /dev/null +++ b/Task/Comments/Dragonstone/comments.dragonstone @@ -0,0 +1,19 @@ +#[ + Multi-Line Comment. +]# + +#[ + Nested Multi-Line Comment. + #[ + Inner comment. + #[ + It can go deep. + ]# + ]# + Outer comment. +]# + +# Single Line Comment + +#[ Multi-Line Comment on line ]# message = "Hello!" #[ Inside or Outside ]# +echo message # Another Trailing Comment. diff --git a/Task/Comments/Ed/comments.ed b/Task/Comments/Ed/comments.ed new file mode 100644 index 0000000000..8ae6029f77 --- /dev/null +++ b/Task/Comments/Ed/comments.ed @@ -0,0 +1,3 @@ +# A single-line comment. +# The only type of comment, really. +# No block comments in ed diff --git a/Task/Comments/Elixir/comments.elixir b/Task/Comments/Elixir/comments.ex similarity index 100% rename from Task/Comments/Elixir/comments.elixir rename to Task/Comments/Elixir/comments.ex diff --git a/Task/Comments/Emacs-Lisp/comments-1.l b/Task/Comments/Emacs-Lisp/comments-1.el similarity index 100% rename from Task/Comments/Emacs-Lisp/comments-1.l rename to Task/Comments/Emacs-Lisp/comments-1.el diff --git a/Task/Comments/Emacs-Lisp/comments-2.l b/Task/Comments/Emacs-Lisp/comments-2.el similarity index 100% rename from Task/Comments/Emacs-Lisp/comments-2.l rename to Task/Comments/Emacs-Lisp/comments-2.el diff --git a/Task/Comments/Emacs-Lisp/comments-3.l b/Task/Comments/Emacs-Lisp/comments-3.el similarity index 100% rename from Task/Comments/Emacs-Lisp/comments-3.l rename to Task/Comments/Emacs-Lisp/comments-3.el diff --git a/Task/Comments/Euphoria/comments-1.euphoria b/Task/Comments/Euphoria/comments-1.eu similarity index 100% rename from Task/Comments/Euphoria/comments-1.euphoria rename to Task/Comments/Euphoria/comments-1.eu diff --git a/Task/Comments/Euphoria/comments-2.euphoria b/Task/Comments/Euphoria/comments-2.eu similarity index 100% rename from Task/Comments/Euphoria/comments-2.euphoria rename to Task/Comments/Euphoria/comments-2.eu diff --git a/Task/Comments/FutureBasic/comments.basic b/Task/Comments/FutureBasic/comments.basic index d05a6c06d6..52cd38da36 100644 --- a/Task/Comments/FutureBasic/comments.basic +++ b/Task/Comments/FutureBasic/comments.basic @@ -1,5 +1,4 @@ // Single line comment -' Single line comment rem Single line comment /* Single line comment */ diff --git a/Task/Comments/Gleam/comments.gleam b/Task/Comments/Gleam/comments.gleam new file mode 100644 index 0000000000..cc85cea83d --- /dev/null +++ b/Task/Comments/Gleam/comments.gleam @@ -0,0 +1 @@ +// comments start with "//" and continue to the end of the line. diff --git a/Task/Comments/Haxe/comments.haxe b/Task/Comments/Haxe/comments.hx similarity index 100% rename from Task/Comments/Haxe/comments.haxe rename to Task/Comments/Haxe/comments.hx diff --git a/Task/Comments/Idris/comments.idris b/Task/Comments/Idris/comments.idris new file mode 100644 index 0000000000..6494468b7c --- /dev/null +++ b/Task/Comments/Idris/comments.idris @@ -0,0 +1,9 @@ +(according to Gemini AI): + +Idris2 uses comment characters similar to Haskell: + +Single-line comments: Start with -- (two hyphens). Everything from -- to the end of the line is a comment. + +Multi-line comments: Enclosed by {- and -}. These can span multiple lines and can also be nested. + +Additionally, Idris2 supports inline documentation comments which begin with ||| (three pipe symbols). These are parsed by the compiler and can be used to generate documentation. diff --git a/Task/Comments/Janet/comments.janet b/Task/Comments/Janet/comments.janet new file mode 100644 index 0000000000..c72e9ad78b --- /dev/null +++ b/Task/Comments/Janet/comments.janet @@ -0,0 +1,7 @@ +(according to Gemini AI): + +The Janet programming language uses the # character for comments. + +Single-line comments: Everything from # to the end of the line is treated as a comment. + +Janet does not have built-in multi-line comments in the same way some other languages do (like {- ... -} in Idris2 or /* ... */ in C-like languages). However, because Janet is expression-oriented, you can often use multi-line strings as a form of "comment" if you put them in a context where their value isn't used. diff --git a/Task/Comments/Julia/comments.julia b/Task/Comments/Julia/comments.jl similarity index 100% rename from Task/Comments/Julia/comments.julia rename to Task/Comments/Julia/comments.jl diff --git a/Task/Comments/Kotlin/comments.kotlin b/Task/Comments/Kotlin/comments.kts similarity index 100% rename from Task/Comments/Kotlin/comments.kotlin rename to Task/Comments/Kotlin/comments.kts diff --git a/Task/Comments/Modula-2/comments.mod2 b/Task/Comments/Modula-2/comments.mod2 index 0d7a59997a..c6c4b9311c 100644 --- a/Task/Comments/Modula-2/comments.mod2 +++ b/Task/Comments/Modula-2/comments.mod2 @@ -1,3 +1,4 @@ -(* Comments (* can nest *) +(* Modula-2/Modula-3 use the same style of comments *) +(* ...and comments (* can nest *) and they can span multiple lines. *) diff --git a/Task/Comments/Modula-3/comments.mod3 b/Task/Comments/Modula-3/comments.mod3 deleted file mode 100644 index 0d7a59997a..0000000000 --- a/Task/Comments/Modula-3/comments.mod3 +++ /dev/null @@ -1,3 +0,0 @@ -(* Comments (* can nest *) - and they can span multiple lines. - *) diff --git a/Task/Comments/OCaml/comments.ocaml b/Task/Comments/OCaml/comments.ml similarity index 100% rename from Task/Comments/OCaml/comments.ocaml rename to Task/Comments/OCaml/comments.ml diff --git a/Task/Comments/OPL/comments.opl b/Task/Comments/OPL/comments.opl new file mode 100644 index 0000000000..901aa3e30b --- /dev/null +++ b/Task/Comments/OPL/comments.opl @@ -0,0 +1,2 @@ +REM This is a comment. +PAUSE 20 REM Can be placed behind statements, too. diff --git a/Task/Comments/Oberon/comments.oberon b/Task/Comments/Oberon/comments.oberon index 0af8c335d3..1177dbb75c 100644 --- a/Task/Comments/Oberon/comments.oberon +++ b/Task/Comments/Oberon/comments.oberon @@ -1,4 +1,4 @@ -(* this is a comment *) +(* Oberon-07/Oberon-2 use the same style of comments as Modula-2: this is a comment *) (* and this is a multiline comment diff --git a/Task/Comments/Odin/comments.odin b/Task/Comments/Odin/comments.odin new file mode 100644 index 0000000000..f8e21d0d05 --- /dev/null +++ b/Task/Comments/Odin/comments.odin @@ -0,0 +1,17 @@ +(According to Gemini AI): + +The Odin programming language supports two types of comment characters: + +Single-line comments: Begin with //. + +Code snippet +// This is a single-line comment +my_variable: int // A comment for documentation +Multi-line comments: Begin with /* and end with */. Multi-line comments can also be nested. + +Code snippet +/* +This is a multi-line comment. +/* NOTE: comments can be nested! */ +You can have any text or code here and have it be commented. +*/ diff --git a/Task/Comments/PascalABC.NET/comments.pas b/Task/Comments/PascalABC.NET/comments.pas new file mode 100644 index 0000000000..3af3369dfc --- /dev/null +++ b/Task/Comments/PascalABC.NET/comments.pas @@ -0,0 +1,7 @@ +(* This is a + multiline comment *) + +{ This is also a + multiline comment } + +// This is a single line comment diff --git a/Task/Comments/Pluto/comments.pluto b/Task/Comments/Pluto/comments.pluto new file mode 100644 index 0000000000..357b06dcd5 --- /dev/null +++ b/Task/Comments/Pluto/comments.pluto @@ -0,0 +1,9 @@ +-- Single line comment + +--[[ Multi-line + comment ]] + +--[===[ + Another syntax + [[ which may contain square brackets ]] +]===] diff --git a/Task/Comments/PowerShell/comments-1.psh b/Task/Comments/PowerShell/comments-1.ps1 similarity index 100% rename from Task/Comments/PowerShell/comments-1.psh rename to Task/Comments/PowerShell/comments-1.ps1 diff --git a/Task/Comments/PowerShell/comments-2.psh b/Task/Comments/PowerShell/comments-2.ps1 similarity index 100% rename from Task/Comments/PowerShell/comments-2.psh rename to Task/Comments/PowerShell/comments-2.ps1 diff --git a/Task/Comments/REBOL/comments-1.rebol b/Task/Comments/Rebol/comments-1.rebol similarity index 100% rename from Task/Comments/REBOL/comments-1.rebol rename to Task/Comments/Rebol/comments-1.rebol diff --git a/Task/Comments/REBOL/comments-2.rebol b/Task/Comments/Rebol/comments-2.rebol similarity index 100% rename from Task/Comments/REBOL/comments-2.rebol rename to Task/Comments/Rebol/comments-2.rebol diff --git a/Task/Comments/Rust/comments.rust b/Task/Comments/Rust/comments.rs similarity index 100% rename from Task/Comments/Rust/comments.rust rename to Task/Comments/Rust/comments.rs diff --git a/Task/Comments/Scheme/comments.ss b/Task/Comments/Scheme/comments.scm similarity index 100% rename from Task/Comments/Scheme/comments.ss rename to Task/Comments/Scheme/comments.scm diff --git a/Task/Comments/Uiua/comments.uiua b/Task/Comments/Uiua/comments.uiua new file mode 100644 index 0000000000..7dd15c1854 --- /dev/null +++ b/Task/Comments/Uiua/comments.uiua @@ -0,0 +1 @@ +# This is a comment diff --git a/Task/Comments/Uxntal/comments.uxnatl b/Task/Comments/Uxntal/comments.uxnatl new file mode 100644 index 0000000000..74169c1755 --- /dev/null +++ b/Task/Comments/Uxntal/comments.uxnatl @@ -0,0 +1,31 @@ +( + Print a hex byte to decimal. +) + +( macros ) +%\n { 0a } +%newline { [ LIT2 \n -Console/write ] DEO } + +( devices ) +|10 @Console/vector $2 &read $1 ( &pad is unused ) &pad $5 &write $1 &error $1 + +( main program ) +|100 + +@on-reset ( -> ) + #42 print/dec newline + BRK + +( library ) +@print/dec ( dec -- ) + DUP #64 DIV /dec/try + DUP #0a DIV /dec/try + ( >> ) + + &dec/num ( num -- ) + #0a DIVk MUL SUB [ LIT "0 ] ADD .Console/write DEO + JMP2r + + &dec/try ( num -- ) + DUP ?/dec/num + POP JMP2r diff --git a/Task/Comments/VBScript/comments.vb b/Task/Comments/VBScript/comments.vbs similarity index 100% rename from Task/Comments/VBScript/comments.vb rename to Task/Comments/VBScript/comments.vbs diff --git a/Task/Comments/VHDL/comments.vhdl b/Task/Comments/VHDL/comments.vhd similarity index 100% rename from Task/Comments/VHDL/comments.vhdl rename to Task/Comments/VHDL/comments.vhd diff --git a/Task/Compare-a-list-of-strings/Ada/compare-a-list-of-strings-1.ada b/Task/Compare-a-list-of-strings/Ada/compare-a-list-of-strings-1.adb similarity index 100% rename from Task/Compare-a-list-of-strings/Ada/compare-a-list-of-strings-1.ada rename to Task/Compare-a-list-of-strings/Ada/compare-a-list-of-strings-1.adb diff --git a/Task/Compare-a-list-of-strings/Ada/compare-a-list-of-strings-2.ada b/Task/Compare-a-list-of-strings/Ada/compare-a-list-of-strings-2.adb similarity index 100% rename from Task/Compare-a-list-of-strings/Ada/compare-a-list-of-strings-2.ada rename to Task/Compare-a-list-of-strings/Ada/compare-a-list-of-strings-2.adb diff --git a/Task/Compare-a-list-of-strings/Ada/compare-a-list-of-strings-3.ada b/Task/Compare-a-list-of-strings/Ada/compare-a-list-of-strings-3.adb similarity index 100% rename from Task/Compare-a-list-of-strings/Ada/compare-a-list-of-strings-3.ada rename to Task/Compare-a-list-of-strings/Ada/compare-a-list-of-strings-3.adb diff --git a/Task/Compare-a-list-of-strings/Ada/compare-a-list-of-strings-4.ada b/Task/Compare-a-list-of-strings/Ada/compare-a-list-of-strings-4.adb similarity index 100% rename from Task/Compare-a-list-of-strings/Ada/compare-a-list-of-strings-4.ada rename to Task/Compare-a-list-of-strings/Ada/compare-a-list-of-strings-4.adb diff --git a/Task/Compare-a-list-of-strings/Applesoft-BASIC/compare-a-list-of-strings-1.basic b/Task/Compare-a-list-of-strings/Applesoft-BASIC/compare-a-list-of-strings-1.basic new file mode 100644 index 0000000000..421239e7bb --- /dev/null +++ b/Task/Compare-a-list-of-strings/Applesoft-BASIC/compare-a-list-of-strings-1.basic @@ -0,0 +1,2 @@ +EQ = 1:N = VAL (S7$(0)): IF N > 1 THEN FOR I = 2 TO N:EQ = S7$(I - 1) = S7$(I): IF EQ THEN NEXT +LT = 1:N = VAL (S7$(0)): IF N > 1 THEN FOR I = 2 TO N:LT = S7$(I - 1) < S7$(I): IF LT THEN NEXT diff --git a/Task/Compare-a-list-of-strings/Applesoft-BASIC/compare-a-list-of-strings-2.basic b/Task/Compare-a-list-of-strings/Applesoft-BASIC/compare-a-list-of-strings-2.basic new file mode 100644 index 0000000000..1f1d5f90b0 --- /dev/null +++ b/Task/Compare-a-list-of-strings/Applesoft-BASIC/compare-a-list-of-strings-2.basic @@ -0,0 +1,12 @@ + 0 GOSUB 4"PRINT & READ + 1 EQ = 1: IF N > 1 THEN FOR I = 2 TO N:EQ = S7$(I - 1) = S7$(I): IF EQ THEN NEXT : REMALL EQUAL + 2 LT = 1: IF N > 1 THEN FOR I = 2 TO N:LT = S7$(I - 1) < S7$(I): IF LT THEN NEXT : REMSTRICTLY ASCENDING + 3 FOR I = 0 TO 0: NEXT : END : GOTO : REMCLEAR ANY "FOR I" LOOP, QUIT & ALLOW "CONT" TO CONTINUE + 4 N = VAL (S7RING$(0)): IF N THEN FOR I = 1 TO N: PRINT MID$ (",",1,I > 1)S7RING$(I);: NEXT : REM​PRINT STRINGS + 5 READ S7RING$(0):N = VAL (S7RING$(0)): IF N THEN FOR I = 1 TO N: READ S7RING$(I): NEXT : REMREAD STRINGS + 6 RETURN + 160 DATA3,AA,BB,CC + 170 DATA3,AA,AA,AA + 180 DATA3,AA,CC,BB + 190 DATA4,AA,ACB,BB,CC + 200 DATA1,SINGLE ELEMENT diff --git a/Task/Compare-a-list-of-strings/Applesoft-BASIC/compare-a-list-of-strings-3.basic b/Task/Compare-a-list-of-strings/Applesoft-BASIC/compare-a-list-of-strings-3.basic new file mode 100644 index 0000000000..1e3c7bc6e9 --- /dev/null +++ b/Task/Compare-a-list-of-strings/Applesoft-BASIC/compare-a-list-of-strings-3.basic @@ -0,0 +1,2 @@ +RUN +FOR J = 160 TO 200 STEP 10: PRINT EQ" "LT" ";: CONT diff --git a/Task/Compare-a-list-of-strings/Applesoft-BASIC/compare-a-list-of-strings-4.basic b/Task/Compare-a-list-of-strings/Applesoft-BASIC/compare-a-list-of-strings-4.basic new file mode 100644 index 0000000000..5bba4099eb --- /dev/null +++ b/Task/Compare-a-list-of-strings/Applesoft-BASIC/compare-a-list-of-strings-4.basic @@ -0,0 +1 @@ +NEXT diff --git a/Task/Compare-a-list-of-strings/Applesoft-BASIC/compare-a-list-of-strings-5.basic b/Task/Compare-a-list-of-strings/Applesoft-BASIC/compare-a-list-of-strings-5.basic new file mode 100644 index 0000000000..5bba4099eb --- /dev/null +++ b/Task/Compare-a-list-of-strings/Applesoft-BASIC/compare-a-list-of-strings-5.basic @@ -0,0 +1 @@ +NEXT diff --git a/Task/Compare-a-list-of-strings/Applesoft-BASIC/compare-a-list-of-strings-6.basic b/Task/Compare-a-list-of-strings/Applesoft-BASIC/compare-a-list-of-strings-6.basic new file mode 100644 index 0000000000..5bba4099eb --- /dev/null +++ b/Task/Compare-a-list-of-strings/Applesoft-BASIC/compare-a-list-of-strings-6.basic @@ -0,0 +1 @@ +NEXT diff --git a/Task/Compare-a-list-of-strings/Applesoft-BASIC/compare-a-list-of-strings-7.basic b/Task/Compare-a-list-of-strings/Applesoft-BASIC/compare-a-list-of-strings-7.basic new file mode 100644 index 0000000000..5bba4099eb --- /dev/null +++ b/Task/Compare-a-list-of-strings/Applesoft-BASIC/compare-a-list-of-strings-7.basic @@ -0,0 +1 @@ +NEXT diff --git a/Task/Compare-a-list-of-strings/Arturo/compare-a-list-of-strings.arturo b/Task/Compare-a-list-of-strings/Arturo/compare-a-list-of-strings.arturo index 647d6bb6be..e019d6165f 100644 --- a/Task/Compare-a-list-of-strings/Arturo/compare-a-list-of-strings.arturo +++ b/Task/Compare-a-list-of-strings/Arturo/compare-a-list-of-strings.arturo @@ -1,4 +1,4 @@ -allEqual?: function [lst] -> 1 = size unique lst +allEqual?: function [lst] -> one? unique lst ascending?: function [lst] -> lst = sort lst lists: [ diff --git a/Task/Compare-a-list-of-strings/BQN/compare-a-list-of-strings-1.bqn b/Task/Compare-a-list-of-strings/BQN/compare-a-list-of-strings-1.bqn index 513bc811cf..a840cab418 100644 --- a/Task/Compare-a-list-of-strings/BQN/compare-a-list-of-strings-1.bqn +++ b/Task/Compare-a-list-of-strings/BQN/compare-a-list-of-strings-1.bqn @@ -1,8 +1 @@ -AllEq ← ⍋≡⍒ -Asc ← ¬∘AllEq∧∧≡⊢ - -•Show AllEq ⟨"AA", "AA", "AA", "AA"⟩ -•Show Asc ⟨"AA", "AA", "AA", "AA"⟩ - -•Show AllEq ⟨"AA", "ACB", "BB", "CC"⟩ -•Show Asc ⟨"AA", "ACB", "BB", "CC"⟩ +⊣` diff --git a/Task/Compare-a-list-of-strings/BQN/compare-a-list-of-strings-2.bqn b/Task/Compare-a-list-of-strings/BQN/compare-a-list-of-strings-2.bqn index 680eb502aa..51394587b4 100644 --- a/Task/Compare-a-list-of-strings/BQN/compare-a-list-of-strings-2.bqn +++ b/Task/Compare-a-list-of-strings/BQN/compare-a-list-of-strings-2.bqn @@ -1,4 +1,8 @@ -1 -0 -0 -1 +AllEq ← ⍋≡⍒ # or ⊣`⊸≡ +Asc ← ⍷∘∧⊸≡ + +•Show AllEq ⟨"AA", "AA", "AA", "AA"⟩ +•Show Asc ⟨"AA", "AA", "AA", "AA"⟩ + +•Show AllEq ⟨"AA", "ACB", "BB", "CC"⟩ +•Show Asc ⟨"AA", "ACB", "BB", "CC"⟩ diff --git a/Task/Compare-a-list-of-strings/BQN/compare-a-list-of-strings-3.bqn b/Task/Compare-a-list-of-strings/BQN/compare-a-list-of-strings-3.bqn new file mode 100644 index 0000000000..680eb502aa --- /dev/null +++ b/Task/Compare-a-list-of-strings/BQN/compare-a-list-of-strings-3.bqn @@ -0,0 +1,4 @@ +1 +0 +0 +1 diff --git a/Task/Compare-a-list-of-strings/COBOL/compare-a-list-of-strings.cobol b/Task/Compare-a-list-of-strings/COBOL/compare-a-list-of-strings.cob similarity index 100% rename from Task/Compare-a-list-of-strings/COBOL/compare-a-list-of-strings.cobol rename to Task/Compare-a-list-of-strings/COBOL/compare-a-list-of-strings.cob diff --git a/Task/Compare-a-list-of-strings/Crystal/compare-a-list-of-strings.cr b/Task/Compare-a-list-of-strings/Crystal/compare-a-list-of-strings.cr new file mode 100644 index 0000000000..d01e7aac6e --- /dev/null +++ b/Task/Compare-a-list-of-strings/Crystal/compare-a-list-of-strings.cr @@ -0,0 +1,14 @@ +def all_equal? (strings) + strings.all? {|elt| elt == strings[0] } +end + +def ascending? (strings) + strings.each.cons_pair.all? {|a, b| a < b } +end + +puts "strings all_equal? ascending?" +puts "-------------------------------" +["a a a a", "", "a", "a b c", "a c a"].each do |s| + ss = s.split + printf "%-10s %-5s %-5s\n", "["+ss.join(" ")+"]", all_equal?(ss), ascending?(ss) +end diff --git a/Task/Compare-a-list-of-strings/Delphi/compare-a-list-of-strings.delphi b/Task/Compare-a-list-of-strings/Delphi/compare-a-list-of-strings.pas similarity index 100% rename from Task/Compare-a-list-of-strings/Delphi/compare-a-list-of-strings.delphi rename to Task/Compare-a-list-of-strings/Delphi/compare-a-list-of-strings.pas diff --git a/Task/Compare-a-list-of-strings/DuckDB/compare-a-list-of-strings-1.duckdb b/Task/Compare-a-list-of-strings/DuckDB/compare-a-list-of-strings-1.duckdb new file mode 100644 index 0000000000..1d1f8d16c8 --- /dev/null +++ b/Task/Compare-a-list-of-strings/DuckDB/compare-a-list-of-strings-1.duckdb @@ -0,0 +1,2 @@ +select true = all (select coalesce( (lag(s) over ()) = s, true) + from t); diff --git a/Task/Compare-a-list-of-strings/DuckDB/compare-a-list-of-strings-2.duckdb b/Task/Compare-a-list-of-strings/DuckDB/compare-a-list-of-strings-2.duckdb new file mode 100644 index 0000000000..42fd797832 --- /dev/null +++ b/Task/Compare-a-list-of-strings/DuckDB/compare-a-list-of-strings-2.duckdb @@ -0,0 +1,2 @@ +select true = all (select coalesce(lag(s) over () <= s, true) + from t); diff --git a/Task/Compare-a-list-of-strings/DuckDB/compare-a-list-of-strings-3.duckdb b/Task/Compare-a-list-of-strings/DuckDB/compare-a-list-of-strings-3.duckdb new file mode 100644 index 0000000000..4ad4d70f8b --- /dev/null +++ b/Task/Compare-a-list-of-strings/DuckDB/compare-a-list-of-strings-3.duckdb @@ -0,0 +1,16 @@ +create or replace function all_equal(lst) as ( + with l as (select unnest(lst) as s) + select true = all (select coalesce( (lag(s) over ()) = s, true) + from l) +); + +create or replace function monotonic_non_decreasing(lst) as ( + with l as (select unnest(lst) as s) + select true = all (select coalesce(lag(s) over () <= s, true) + from l) +); + +# Examples + +select l, all_equal(l), monotonic_non_decreasing(l) +from (select ['a','b'] as l union all select [] as l); diff --git a/Task/Compare-a-list-of-strings/EasyLang/compare-a-list-of-strings.easy b/Task/Compare-a-list-of-strings/EasyLang/compare-a-list-of-strings.easy index 86039c73d8..a451eb048b 100644 --- a/Task/Compare-a-list-of-strings/EasyLang/compare-a-list-of-strings.easy +++ b/Task/Compare-a-list-of-strings/EasyLang/compare-a-list-of-strings.easy @@ -1,22 +1,14 @@ -proc test s$[] . . +proc test s$[] . ident = 1 ascend = 1 for i = 2 to len s$[] h = strcmp s$[i] s$[i - 1] - if h <> 0 - ident = 0 - . - if h <= 0 - ascend = 0 - . + if h <> 0 : ident = 0 + if h <= 0 : ascend = 0 . print s$[] - if ident = 1 - print "all equal" - . - if ascend = 1 - print "ascending" - . + if ident = 1 : print "all equal" + if ascend = 1 : print "ascending" print "" . test [ "AA" "BB" "CC" ] 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 b6c8ab0d12..6329a3c522 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 @@ -26,13 +26,13 @@ testCases new string[]{"AA","ACB","BB","CC"}, new string[]{"single_element"}}; -public program() +public Program() { testCases.forEach::(list) { - console.printLine(list.asEnumerable()," all equal - ",list.isEqual()); - console.printLine(list.asEnumerable()," ascending - ",list.isAscending()) + Console.printLine(list.asEnumerable()," all equal - ",list.isEqual()); + Console.printLine(list.asEnumerable()," ascending - ",list.isAscending()) }; - console.readChar() + Console.readChar() } diff --git a/Task/Compare-a-list-of-strings/Elixir/compare-a-list-of-strings.elixir b/Task/Compare-a-list-of-strings/Elixir/compare-a-list-of-strings.ex similarity index 100% rename from Task/Compare-a-list-of-strings/Elixir/compare-a-list-of-strings.elixir rename to Task/Compare-a-list-of-strings/Elixir/compare-a-list-of-strings.ex diff --git a/Task/Compare-a-list-of-strings/Gleam/compare-a-list-of-strings.gleam b/Task/Compare-a-list-of-strings/Gleam/compare-a-list-of-strings.gleam new file mode 100644 index 0000000000..501b6bb6ed --- /dev/null +++ b/Task/Compare-a-list-of-strings/Gleam/compare-a-list-of-strings.gleam @@ -0,0 +1,12 @@ +pub fn all_equal(strs: List(String)) -> Bool { + all_fulfill(fn(s1, s2) { s1 == s2 }, strs) +} + +pub fn all_increasing(strs: List(String)) -> Bool { + all_fulfill(fn(s1, s2) { string.compare(s1, s2) == order.Lt }, strs) +} + +fn all_fulfill(check: fn(String, String) -> Bool, strings: List(String)) -> Bool { + let pairs = list.zip(strings, list.drop(strings, 1)) + list.all(pairs, fn(pair) { check(pair.0, pair.1) }) +} diff --git a/Task/Compare-a-list-of-strings/Go/compare-a-list-of-strings.go b/Task/Compare-a-list-of-strings/Go/compare-a-list-of-strings.go index 5c7546426d..920341f797 100644 --- a/Task/Compare-a-list-of-strings/Go/compare-a-list-of-strings.go +++ b/Task/Compare-a-list-of-strings/Go/compare-a-list-of-strings.go @@ -11,7 +11,7 @@ func AllEqual(strings []string) bool { func AllLessThan(strings []string) bool { for i := 1; i < len(strings); i++ { - if !(strings[i - 1] < s) { + if strings[i - 1] >= strings[i] { return false } } diff --git a/Task/Compare-a-list-of-strings/Icon/compare-a-list-of-strings.icon b/Task/Compare-a-list-of-strings/Icon/compare-a-list-of-strings-1.icon similarity index 100% rename from Task/Compare-a-list-of-strings/Icon/compare-a-list-of-strings.icon rename to Task/Compare-a-list-of-strings/Icon/compare-a-list-of-strings-1.icon diff --git a/Task/Compare-a-list-of-strings/Icon/compare-a-list-of-strings-2.icon b/Task/Compare-a-list-of-strings/Icon/compare-a-list-of-strings-2.icon new file mode 100644 index 0000000000..05598811ee --- /dev/null +++ b/Task/Compare-a-list-of-strings/Icon/compare-a-list-of-strings-2.icon @@ -0,0 +1,9 @@ +# test for all identical +procedure allequal(L) + if *L >= 2 & !L ~== L[1] then fail else return +end + +# test for strictly ascending +procedure ascending(L) + if *L >= 2 & i := 1 to *L-1 & L[i] >>= L[i+1] then fail else return +end diff --git a/Task/Compare-a-list-of-strings/Icon/compare-a-list-of-strings-3.icon b/Task/Compare-a-list-of-strings/Icon/compare-a-list-of-strings-3.icon new file mode 100644 index 0000000000..14327c0456 --- /dev/null +++ b/Task/Compare-a-list-of-strings/Icon/compare-a-list-of-strings-3.icon @@ -0,0 +1 @@ +writes(if allequal(L) then "true" else "false") diff --git a/Task/Compare-a-list-of-strings/Icon/compare-a-list-of-strings-4.icon b/Task/Compare-a-list-of-strings/Icon/compare-a-list-of-strings-4.icon new file mode 100644 index 0000000000..bfd62b39e8 --- /dev/null +++ b/Task/Compare-a-list-of-strings/Icon/compare-a-list-of-strings-4.icon @@ -0,0 +1 @@ +writes(if *L >= 2 & !L ~== L[1] then "false" else "true") diff --git a/Task/Compare-a-list-of-strings/Jq/compare-a-list-of-strings-1.jq b/Task/Compare-a-list-of-strings/Jq/compare-a-list-of-strings-1.jq index 9d9694486b..9a73ae5c6f 100644 --- a/Task/Compare-a-list-of-strings/Jq/compare-a-list-of-strings-1.jq +++ b/Task/Compare-a-list-of-strings/Jq/compare-a-list-of-strings-1.jq @@ -1,11 +1,11 @@ # Are the strings all equal? def lexically_equal: - . as $in - | reduce range(0;length-1) as $i - (true; if . then $in[$i] == $in[$i + 1] else false end); + if length <= 1 then true + else . as $in + | all( range(0;length-1); $in[0] == $in[. + 1]) + end; -# Are the strings in strictly ascending order? +# Are the elements in strictly ascending order? def lexically_ascending: . as $in - | reduce range(0;length-1) as $i - (true; if . then $in[$i] < $in[$i + 1] else false end); + | all( range(0;length-1); $in[.] < $in[. + 1]); diff --git a/Task/Compare-a-list-of-strings/Julia/compare-a-list-of-strings.julia b/Task/Compare-a-list-of-strings/Julia/compare-a-list-of-strings.jl similarity index 100% rename from Task/Compare-a-list-of-strings/Julia/compare-a-list-of-strings.julia rename to Task/Compare-a-list-of-strings/Julia/compare-a-list-of-strings.jl diff --git a/Task/Compare-a-list-of-strings/K/compare-a-list-of-strings.k b/Task/Compare-a-list-of-strings/K/compare-a-list-of-strings.k new file mode 100644 index 0000000000..94f07991ed --- /dev/null +++ b/Task/Compare-a-list-of-strings/K/compare-a-list-of-strings.k @@ -0,0 +1,2 @@ +alleq:&/1_~': +asc:&/(*<,)':,:' diff --git a/Task/Compare-a-list-of-strings/Kotlin/compare-a-list-of-strings.kotlin b/Task/Compare-a-list-of-strings/Kotlin/compare-a-list-of-strings.kts similarity index 100% rename from Task/Compare-a-list-of-strings/Kotlin/compare-a-list-of-strings.kotlin rename to Task/Compare-a-list-of-strings/Kotlin/compare-a-list-of-strings.kts diff --git a/Task/Compare-a-list-of-strings/M2000-Interpreter/compare-a-list-of-strings.m2000 b/Task/Compare-a-list-of-strings/M2000-Interpreter/compare-a-list-of-strings.m2000 index 14627c3e47..b02abbc166 100644 --- a/Task/Compare-a-list-of-strings/M2000-Interpreter/compare-a-list-of-strings.m2000 +++ b/Task/Compare-a-list-of-strings/M2000-Interpreter/compare-a-list-of-strings.m2000 @@ -37,3 +37,38 @@ Module CheckIt { Print LessThan(A$())=False } Checkit +MODULE UsingLambdaFunctionAndFold { + equ=LAMBDA ->{ + =LAMBDA p$, c=0 -> { + IF c=0 THEN + p$=LETTER$: PUSH 1=1 : c++ + ELSE + READ q$ + IF STACKITEM() THEN + DROP + PUSH p$=q$ + p$=q$ + END IF + END IF + } + } + LessThan=LAMBDA ->{ + =LAMBDA p$, c=0 -> { + IF c=0 THEN + p$=LETTER$: PUSH 1=1 : c++ + ELSE + READ q$ + IF STACKITEM() THEN + DROP + PUSH p$ lst.First = x); + +function IsStrictAscending(lst: sequence of string): boolean + := lst.Pairwise.All(x -> x[0] < x[1]); + +begin + var strings := |'abc','abc','abc','abc'|; + Print(AllEqual(strings)); + var strings1 := |'abc','abd','ade','aef'|; + Print(IsStrictAscending(strings1)); +end. diff --git a/Task/Compare-a-list-of-strings/Phix/compare-a-list-of-strings.phix b/Task/Compare-a-list-of-strings/Phix/compare-a-list-of-strings.phix index 4faabce3f2..05991641e5 100644 --- a/Task/Compare-a-list-of-strings/Phix/compare-a-list-of-strings.phix +++ b/Task/Compare-a-list-of-strings/Phix/compare-a-list-of-strings.phix @@ -1,26 +1,24 @@ -(phixonline)--> - with javascript_semantics - function allsame(sequence s) - for i=2 to length(s) do - if s[i]!=s[1] then return false end if - end for - return true - end function +with javascript_semantics +function allsame(sequence s) + for i=2 to length(s) do + if s[i]!=s[1] then return false end if + end for + return true +end function - function strict_order(sequence s) - for i=2 to length(s) do - if s[i]<=s[i-1] then return false end if - end for - return true - end function +function strict_order(sequence s) + for i=2 to length(s) do + if s[i]<=s[i-1] then return false end if + end for + return true +end function - procedure test(sequence s) - printf(1,"%-22V allsame:%5t, strict_order:%5t\n",{s,allsame(s),strict_order(s)}) - end procedure +procedure test(sequence s) + printf(1,"%-22V allsame:%5t, strict_order:%5t\n",{s,allsame(s),strict_order(s)}) +end procedure - test({"AA","BB","CC"}) - test({"AA","AA","AA"}) - test({"AA","CC","BB"}) - test({"AA","ACB","BB","CC"}) - test({"single_element"}) - - integer a,b - a = 10*9*8*7*6*5*4*3*2*1 - b = factorial(10) - ?{a,b} - - -- - -- demo\rosetta\Compiler\interp.exw - -- ================================ - -- - with javascript_semantics - include parse.e +-- demo\rosetta\Compiler\interp.exw +with javascript_semantics +include parse.e - sequence vars = {}, - vals = {} +sequence vars = {}, + vals = {} - function var_idx(sequence inode) - if inode[1]!=tk_Identifier then ?9/0 end if - string ident = inode[2] - integer n = find(ident,vars) - if n=0 then - vars = append(vars,ident) - vals = append(vals,0) - n = length(vars) - end if - return n - end function +function var_idx(sequence inode) + if inode[1]!=tk_Identifier then ?9/0 end if + string ident = inode[2] + integer n = find(ident,vars) + if n=0 then + vars = append(vars,ident) + vals = append(vals,0) + n = length(vars) + end if + return n +end function - function interp(object t) - if t!=NULL then - integer ntype = t[1] - object t2 = t[2], - t3 = iff(length(t)=3?t[3]:0) - switch ntype do - case tk_Sequence: {} = interp(t2) {} = interp(t3) - case tk_assign: vals[var_idx(t2)] = interp(t3) - case tk_Identifier: return vals[var_idx(t)] - case tk_Integer: return t2 - case tk_String: return t2 - case tk_lt: return interp(t2) < interp(t3) - case tk_add: return interp(t2) + interp(t3) - case tk_sub: return interp(t2) - interp(t3) - case tk_while: while interp(t2) do {} = interp(t3) end while - case tk_Prints: puts(1,interp(t2)) - case tk_Printi: printf(1,"%d",interp(t2)) - case tk_putc: printf(1,"%c",interp(t2)) - case tk_and: return interp(t2) and interp(t3) - case tk_or: return interp(t2) or interp(t3) - case tk_le: return interp(t2) <= interp(t3) - case tk_ge: return interp(t2) >= interp(t3) - case tk_ne: return interp(t2) != interp(t3) - case tk_gt: return interp(t2) > interp(t3) - case tk_mul: return interp(t2) * interp(t3) - case tk_div: return trunc(interp(t2)/interp(t3)) - case tk_mod: return remainder(interp(t2),interp(t3)) - case tk_if: {} = interp(t3[iff(interp(t2)?2:3)]) - case tk_not: return not interp(t2) - case tk_neg: return - interp(t2) - else - error("unknown node type") - end switch - end if - return NULL - end function +function interp(object t) + if t!=NULL then + integer ntype = t[1] + object t2 = t[2], + t3 = iff(length(t)=3?t[3]:0) + switch ntype do + case tk_Sequence: {} = interp(t2) {} = interp(t3) + case tk_assign: vals[var_idx(t2)] = interp(t3) + case tk_Identifier: return vals[var_idx(t)] + case tk_Integer: return t2 + case tk_String: return t2 + case tk_lt: return interp(t2) < interp(t3) + case tk_add: return interp(t2) + interp(t3) + case tk_sub: return interp(t2) - interp(t3) + case tk_while: while interp(t2) do {} = interp(t3) end while + case tk_Prints: puts(1,interp(t2)) + case tk_Printi: printf(1,"%d",interp(t2)) + case tk_putc: printf(1,"%c",interp(t2)) + case tk_and: return interp(t2) and interp(t3) + case tk_or: return interp(t2) or interp(t3) + case tk_le: return interp(t2) <= interp(t3) + case tk_ge: return interp(t2) >= interp(t3) + case tk_ne: return interp(t2) != interp(t3) + case tk_gt: return interp(t2) > interp(t3) + case tk_mul: return interp(t2) * interp(t3) + case tk_div: return trunc(interp(t2)/interp(t3)) + case tk_mod: return remainder(interp(t2),interp(t3)) + case tk_if: {} = interp(t3[iff(interp(t2)?2:3)]) + case tk_not: return not interp(t2) + case tk_neg: return - interp(t2) + else + error("unknown node type") + end switch + end if + return NULL +end function - procedure main(sequence cl) - open_files(cl) - toks = lex() - object t = parse() - {} = interp(t) - close_files() - end procedure +procedure main(sequence cl) + open_files(cl) + toks = lex() + object t = parse() + {} = interp(t) + close_files() +end procedure - --main(command_line()) - main({0,0,"primes.c"}) - - -- - -- demo\rosetta\Compiler\cgen.e - -- ============================ - -- - -- The reusable part of cgen.exw - -- - without js -- (machine code!) - include parse.e +-- demo\rosetta\Compiler\cgen.e +-- The reusable part of cgen.exw +without js -- (machine code!) +include parse.e - global sequence vars = {}, - strings = {}, - stringptrs = {} +global sequence vars = {}, + strings = {}, + stringptrs = {} - global integer chain = 0 - global sequence code = {} +global integer chain = 0 +global sequence code = {} - function var_idx(sequence inode) - if inode[1]!=tk_Identifier then ?9/0 end if - string ident = inode[2] - integer n = find(ident,vars) - if n=0 then - vars = append(vars,ident) - n = length(vars) - end if - return n - end function +function var_idx(sequence inode) + if inode[1]!=tk_Identifier then ?9/0 end if + string ident = inode[2] + integer n = find(ident,vars) + if n=0 then + vars = append(vars,ident) + n = length(vars) + end if + return n +end function - function string_idx(sequence inode) - if inode[1]!=tk_String then ?9/0 end if - string s = inode[2] - integer n = find(s,strings) - if n=0 then - strings = append(strings,s) - stringptrs = append(stringptrs,0) - n = length(strings) - end if - return n - end function +function string_idx(sequence inode) + if inode[1]!=tk_String then ?9/0 end if + string s = inode[2] + integer n = find(s,strings) + if n=0 then + strings = append(strings,s) + stringptrs = append(stringptrs,0) + n = length(strings) + end if + return n +end function - function gen_size(object t) - -- note: must be kept precisely in sync with gen_rec! - -- (relentlessly tested via estsize/actsize) - integer size = 0 - if t!=NULL then - integer n_type = t[1] - string node_type = tkNames[n_type] - switch n_type do - case tk_Sequence: - size += gen_size(t[2]) - size += gen_size(t[3]) - case tk_assign: - size += gen_size(t[3])+6 - case tk_Integer: - size += 5 - case tk_Identifier: - size += 6 - case tk_String: - size += 5 - case tk_while: - -- emit: @@:<condition><topjmp(@f)><body><tailjmp(@b)>@@: - size += gen_size(t[2])+3 - integer body = gen_size(t[3]) - integer stail = iff(size+body+2>128?5:2) - integer stop = iff(body+stail >127?6:2) - size += stop+body+stail - case tk_lt: - case tk_le: - case tk_ne: - case tk_eq: - case tk_gt: - case tk_ge: - size += gen_size(t[2]) - size += gen_size(t[3]) - size += 10 - case tk_and: - case tk_or: - size += gen_size(t[2]) - size += gen_size(t[3]) - size += 15 - case tk_add: - case tk_sub: - size += gen_size(t[2]) - size += gen_size(t[3]) - size += 4 - case tk_mul: - size += gen_size(t[2]) - size += gen_size(t[3]) - size += 5 - case tk_div: - case tk_mod: - size += gen_size(t[2]) - size += gen_size(t[3]) - size += 6 - case tk_putc: - case tk_Printi: - case tk_Prints: - size += gen_size(t[2]) - size += 5 - case tk_if: - size += gen_size(t[2])+3 - if t[3][1]!=tk_if then ?9/0 end if - integer truesize = gen_size(t[3][2]) - integer falsesize = gen_size(t[3][3]) - integer elsejmp = iff(falsesize=0?0:iff(falsesize>127?5:2)) - integer mainjmp = iff(truesize+elsejmp>127?6:2) - size += mainjmp+truesize+elsejmp+falsesize - case tk_not: - size += gen_size(t[2]) - size += 9 - case tk_neg: - size += gen_size(t[2]) - size += 4 - else: - ?9/0 - end switch - end if - return size - end function +function gen_size(object t) +-- note: must be kept precisely in sync with gen_rec! +-- (relentlessly tested via estsize/actsize) +integer size = 0 + if t!=NULL then + integer n_type = t[1] + string node_type = tkNames[n_type] + switch n_type do + case tk_Sequence: + size += gen_size(t[2]) + size += gen_size(t[3]) + case tk_assign: + size += gen_size(t[3])+6 + case tk_Integer: + size += 5 + case tk_Identifier: + size += 6 + case tk_String: + size += 5 + case tk_while: + -- emit: @@:@@: + size += gen_size(t[2])+3 + integer body = gen_size(t[3]) + integer stail = iff(size+body+2>128?5:2) + integer stop = iff(body+stail >127?6:2) + size += stop+body+stail + case tk_lt: + case tk_le: + case tk_ne: + case tk_eq: + case tk_gt: + case tk_ge: + size += gen_size(t[2]) + size += gen_size(t[3]) + size += 10 + case tk_and: + case tk_or: + size += gen_size(t[2]) + size += gen_size(t[3]) + size += 15 + case tk_add: + case tk_sub: + size += gen_size(t[2]) + size += gen_size(t[3]) + size += 4 + case tk_mul: + size += gen_size(t[2]) + size += gen_size(t[3]) + size += 5 + case tk_div: + case tk_mod: + size += gen_size(t[2]) + size += gen_size(t[3]) + size += 6 + case tk_putc: + case tk_Printi: + case tk_Prints: + size += gen_size(t[2]) + size += 5 + case tk_if: + size += gen_size(t[2])+3 + if t[3][1]!=tk_if then ?9/0 end if + integer truesize = gen_size(t[3][2]) + integer falsesize = gen_size(t[3][3]) + integer elsejmp = iff(falsesize=0?0:iff(falsesize>127?5:2)) + integer mainjmp = iff(truesize+elsejmp>127?6:2) + size += mainjmp+truesize+elsejmp+falsesize + case tk_not: + size += gen_size(t[2]) + size += 9 + case tk_neg: + size += gen_size(t[2]) + size += 4 + else: + ?9/0 + end switch + end if + return size +end function - procedure gen_rec(object t) - -- the recursive part of code_gen - if t!=NULL then - integer initsize = length(code) - integer estsize = gen_size(t) -- (test the gen_size function) - integer n_type = t[1] - string node_type = tkNames[n_type] - switch n_type do - case tk_Sequence: - gen_rec(t[2]) - gen_rec(t[3]) - case tk_assign: - integer n = var_idx(t[2]) - gen_rec(t[3]) - code &= {0o217,0o005,chain,1,n,0} -- pop [i] - chain = length(code)-3 - case tk_Integer: - integer n = t[2] - code &= 0o150&int_to_bytes(n) -- push imm32 - case tk_while: - -- emit: @@:<condition><topjmp(@f)><body><tailjmp(@b)>@@: - integer looptop = length(code) - gen_rec(t[2]) - code &= {0o130, -- pop eax - 0o205,0o300} -- test eax,eax - integer bodysize = gen_size(t[3]) - -- can we use short jumps? - -- disclaimer: size calcs are not heavily tested; if in - -- doubt reduce 128/7 by 8, and if that works - -- then yep, you just found a boundary case. - integer stail = iff(length(code)+bodysize+4-looptop>128?5:2) - integer offset = bodysize+stail - integer stop = iff(offset>127?6:2) - if stop=2 then - code &= {0o164,offset} -- jz (short) end - else - code &= {0o017,0o204}&int_to_bytes(offset) -- jz (long) end - end if - gen_rec(t[3]) - offset = looptop-(length(code)+stail) - if stail=2 then - code &= 0o353&offset -- jmp looptop (short) - else - code &= 0o351&int_to_bytes(offset) -- jmp looptop (long) - end if - case tk_lt: - case tk_le: - case tk_gt: - case tk_ge: - case tk_ne: - case tk_eq: - gen_rec(t[2]) - gen_rec(t[3]) - integer xrm - if n_type=tk_ne then xrm = 0o225 -- (#95) - elsif n_type=tk_lt then xrm = 0o234 -- (#9C) - elsif n_type=tk_ge then xrm = 0o235 -- (#9D) - elsif n_type=tk_le then xrm = 0o236 -- (#9E) - elsif n_type=tk_gt then xrm = 0o237 -- (#9F) - else ?9/0 - end if - code &= { 0o061,0o300, -- xor eax,eax - 0o132, -- pop edx - 0o131, -- pop ecx - 0o071,0o321, -- cmp ecx,edx - 0o017,xrm,0o300, -- setcc al - 0o120} -- push eax - case tk_or: - case tk_and: - gen_rec(t[2]) - gen_rec(t[3]) - integer op = find(n_type,{tk_or,0,0,tk_and}) - op *= 0o010 - code &= { 0o130, -- pop eax - 0o131, -- pop ecx - 0o205,0o300, -- test eax,eax - 0o017,0o225,0o300, -- setne al - 0o205,0o311, -- test ecx,ecx - 0o017,0o225,0o301, -- setne cl - op,0o310, -- or/and al,cl - 0o120} -- push eax - case tk_add: - case tk_sub: - gen_rec(t[2]) - gen_rec(t[3]) - integer op = find(n_type,{tk_add,0,0,0,0,tk_sub}) - op = 0o001 + (op-1)*0o010 - code &= { 0o130, -- pop eax - op,0o004,0o044} -- add/or/and/sub [esp],eax - case tk_mul: - gen_rec(t[2]) - gen_rec(t[3]) - code &= { 0o131, -- pop ecx - 0o130, -- pop eax - 0o367,0o341, -- mul ecx - 0o120} -- push eax - case tk_div: - case tk_mod: - gen_rec(t[2]) - gen_rec(t[3]) - integer push = 0o120+(n_type=tk_mod)*2 - code &= { 0o131, -- pop ecx - 0o130, -- pop eax - 0o231, -- cdq (eax -> edx:eax) - 0o367,0o371, -- idiv ecx - push} -- push eax|edx - case tk_Identifier: - integer n = var_idx(t) - code &= {0o377,0o065,chain,1,n,0} -- push [n] - chain = length(code)-3 - case tk_putc: - case tk_Printi: - case tk_Prints: - gen_rec(t[2]) - integer n = find(n_type,{tk_putc,tk_Printi,tk_Prints}) - code &= {0o350,chain,3,n,0} -- call :printc/i/s - chain = length(code)-3 - case tk_String: - integer n = string_idx(t) - code &= {0o150,chain,2,n,0} -- push RawStringPtr(string) - chain = length(code)-3 - case tk_if: - -- emit: <condition><mainjmp><truepart>[<elsejmp><falsepart>] - gen_rec(t[2]) - code &= {0o130, -- pop eax - 0o205,0o300} -- test eax,eax - if t[3][1]!=tk_if then ?9/0 end if - integer truesize = gen_size(t[3][2]) - integer falsesize = gen_size(t[3][3]) - integer elsejmp = iff(falsesize=0?0:iff(falsesize>127?5:2)) - integer offset = truesize+elsejmp - integer mainjmp = iff(offset>127?6:2) - if mainjmp=2 then - code &= {0o164,offset} -- jz (short) else/end - else - code &= {0o017,0o204}&int_to_bytes(offset) -- jz (long) else/end - end if - gen_rec(t[3][2]) - if falsesize!=0 then - offset = falsesize - if elsejmp=2 then - code &= 0o353&offset -- jmp end if (short) - else - code &= 0o351&int_to_bytes(offset) -- jmp end if (long) - end if - gen_rec(t[3][3]) - end if - case tk_not: - gen_rec(t[2]) - code &= {0o132, -- pop edx - 0o061,0o300, -- xor eax,eax - 0o205,0o322, -- test edx,edx - 0o017,0o224,0o300, -- setz al - 0o120} -- push eax - case tk_neg: - gen_rec(t[2]) - code &= {0o130, -- pop eax - 0o367,0o330, -- neg eax - 0o120} -- push eax - else: - error("error in code generator - found %d, expecting operator\n", {n_type}) - end switch - integer actsize = length(code) - if initsize+estsize!=actsize then ?"9/0" end if -- (test gen_size) - end if - end procedure +procedure gen_rec(object t) +-- the recursive part of code_gen + if t!=NULL then + integer initsize = length(code) + integer estsize = gen_size(t) -- (test the gen_size function) + integer n_type = t[1] + string node_type = tkNames[n_type] + switch n_type do + case tk_Sequence: + gen_rec(t[2]) + gen_rec(t[3]) + case tk_assign: + integer n = var_idx(t[2]) + gen_rec(t[3]) + code &= {0o217,0o005,chain,1,n,0} -- pop [i] + chain = length(code)-3 + case tk_Integer: + integer n = t[2] + code &= 0o150&int_to_bytes(n) -- push imm32 + case tk_while: + -- emit: @@:@@: + integer looptop = length(code) + gen_rec(t[2]) + code &= {0o130, -- pop eax + 0o205,0o300} -- test eax,eax + integer bodysize = gen_size(t[3]) + -- can we use short jumps? + -- disclaimer: size calcs are not heavily tested; if in + -- doubt reduce 128/7 by 8, and if that works + -- then yep, you just found a boundary case. + integer stail = iff(length(code)+bodysize+4-looptop>128?5:2) + integer offset = bodysize+stail + integer stop = iff(offset>127?6:2) + if stop=2 then + code &= {0o164,offset} -- jz (short) end + else + code &= {0o017,0o204}&int_to_bytes(offset) -- jz (long) end + end if + gen_rec(t[3]) + offset = looptop-(length(code)+stail) + if stail=2 then + code &= 0o353&offset -- jmp looptop (short) + else + code &= 0o351&int_to_bytes(offset) -- jmp looptop (long) + end if + case tk_lt: + case tk_le: + case tk_gt: + case tk_ge: + case tk_ne: + case tk_eq: + gen_rec(t[2]) + gen_rec(t[3]) + integer xrm + if n_type=tk_ne then xrm = 0o225 -- (#95) + elsif n_type=tk_lt then xrm = 0o234 -- (#9C) + elsif n_type=tk_ge then xrm = 0o235 -- (#9D) + elsif n_type=tk_le then xrm = 0o236 -- (#9E) + elsif n_type=tk_gt then xrm = 0o237 -- (#9F) + else ?9/0 + end if + code &= { 0o061,0o300, -- xor eax,eax + 0o132, -- pop edx + 0o131, -- pop ecx + 0o071,0o321, -- cmp ecx,edx + 0o017,xrm,0o300, -- setcc al + 0o120} -- push eax + case tk_or: + case tk_and: + gen_rec(t[2]) + gen_rec(t[3]) + integer op = find(n_type,{tk_or,0,0,tk_and}) + op *= 0o010 + code &= { 0o130, -- pop eax + 0o131, -- pop ecx + 0o205,0o300, -- test eax,eax + 0o017,0o225,0o300, -- setne al + 0o205,0o311, -- test ecx,ecx + 0o017,0o225,0o301, -- setne cl + op,0o310, -- or/and al,cl + 0o120} -- push eax + case tk_add: + case tk_sub: + gen_rec(t[2]) + gen_rec(t[3]) + integer op = find(n_type,{tk_add,0,0,0,0,tk_sub}) + op = 0o001 + (op-1)*0o010 + code &= { 0o130, -- pop eax + op,0o004,0o044} -- add/or/and/sub [esp],eax + case tk_mul: + gen_rec(t[2]) + gen_rec(t[3]) + code &= { 0o131, -- pop ecx + 0o130, -- pop eax + 0o367,0o341, -- mul ecx + 0o120} -- push eax + case tk_div: + case tk_mod: + gen_rec(t[2]) + gen_rec(t[3]) + integer push = 0o120+(n_type=tk_mod)*2 + code &= { 0o131, -- pop ecx + 0o130, -- pop eax + 0o231, -- cdq (eax -> edx:eax) + 0o367,0o371, -- idiv ecx + push} -- push eax|edx + case tk_Identifier: + integer n = var_idx(t) + code &= {0o377,0o065,chain,1,n,0} -- push [n] + chain = length(code)-3 + case tk_putc: + case tk_Printi: + case tk_Prints: + gen_rec(t[2]) + integer n = find(n_type,{tk_putc,tk_Printi,tk_Prints}) + code &= {0o350,chain,3,n,0} -- call :printc/i/s + chain = length(code)-3 + case tk_String: + integer n = string_idx(t) + code &= {0o150,chain,2,n,0} -- push RawStringPtr(string) + chain = length(code)-3 + case tk_if: + -- emit: [] + gen_rec(t[2]) + code &= {0o130, -- pop eax + 0o205,0o300} -- test eax,eax + if t[3][1]!=tk_if then ?9/0 end if + integer truesize = gen_size(t[3][2]) + integer falsesize = gen_size(t[3][3]) + integer elsejmp = iff(falsesize=0?0:iff(falsesize>127?5:2)) + integer offset = truesize+elsejmp + integer mainjmp = iff(offset>127?6:2) + if mainjmp=2 then + code &= {0o164,offset} -- jz (short) else/end + else + code &= {0o017,0o204}&int_to_bytes(offset) -- jz (long) else/end + end if + gen_rec(t[3][2]) + if falsesize!=0 then + offset = falsesize + if elsejmp=2 then + code &= 0o353&offset -- jmp end if (short) + else + code &= 0o351&int_to_bytes(offset) -- jmp end if (long) + end if + gen_rec(t[3][3]) + end if + case tk_not: + gen_rec(t[2]) + code &= {0o132, -- pop edx + 0o061,0o300, -- xor eax,eax + 0o205,0o322, -- test edx,edx + 0o017,0o224,0o300, -- setz al + 0o120} -- push eax + case tk_neg: + gen_rec(t[2]) + code &= {0o130, -- pop eax + 0o367,0o330, -- neg eax + 0o120} -- push eax + else: + error("error in code generator - found %d, expecting operator\n", {n_type}) + end switch + integer actsize = length(code) + if initsize+estsize!=actsize then ?"9/0" end if -- (test gen_size) + end if +end procedure - global procedure code_gen(object t) - -- - -- Generates proper machine code. - -- - -- Example: i=10; print "\n"; print i; print "\n" - -- Result in vars, strings, chain, code (declared above) - -- where vars is: {"i"}, - -- strings is {"\n"}, - -- code is { 0o150,#0A,#00,#00,#00, -- 1: push 10 - -- 0o217,0o005,0,1,1,0 -- 6: pop [i] - -- 0o150,8,2,1,0, -- 12: push ("\n") - -- 0o350,13,3,3,0, -- 17: call :prints - -- 0o377,0o065,18,1,1,0, -- 22: push [i] - -- 0o350,24,3,2,0, -- 28: call :printi - -- 0o150,29,2,1,0, -- 33: push ("\n") - -- 0o350,34,3,3,0, -- 38: call :prints - -- 0o303} -- 43: ret - -- and chain is 39 (->34->29->24->18->13->8->0) - -- The chain connects all places where we need an actual address before - -- the code is executed, with the byte after the link differentiating - -- between var(1), string(2), and builtin(3), and the byte after that - -- determining the instance of the given type - not that any of them - -- are actually limited to a byte in the above intermediate form, and - -- of course the trailing 0 of each {link,type,id,0} is just there to - -- reserve the space we will need. - -- - gen_rec(t) - code = append(code,0o303) -- ret (0o303=#C3) - end procedure +global procedure code_gen(object t) +-- +-- Generates proper machine code. +-- +-- Example: i=10; print "\n"; print i; print "\n" +-- Result in vars, strings, chain, code (declared above) +-- where vars is: {"i"}, +-- strings is {"\n"}, +-- code is { 0o150,#0A,#00,#00,#00, -- 1: push 10 +-- 0o217,0o005,0,1,1,0 -- 6: pop [i] +-- 0o150,8,2,1,0, -- 12: push ("\n") +-- 0o350,13,3,3,0, -- 17: call :prints +-- 0o377,0o065,18,1,1,0, -- 22: push [i] +-- 0o350,24,3,2,0, -- 28: call :printi +-- 0o150,29,2,1,0, -- 33: push ("\n") +-- 0o350,34,3,3,0, -- 38: call :prints +-- 0o303} -- 43: ret +-- and chain is 39 (->34->29->24->18->13->8->0) +-- The chain connects all places where we need an actual address before +-- the code is executed, with the byte after the link differentiating +-- between var(1), string(2), and builtin(3), and the byte after that +-- determining the instance of the given type - not that any of them +-- are actually limited to a byte in the above intermediate form, and +-- of course the trailing 0 of each {link,type,id,0} is just there to +-- reserve the space we will need. +-- + gen_rec(t) + code = append(code,0o303) -- ret (0o303=#C3) +end procedure - include builtins/VM/puts1.e -- low-level console i/o routines +include builtins/VM/puts1.e -- low-level console i/o routines - function setbuiltins() - atom printc,printi,prints - #ilASM{ - jmp :setbuiltins - ::printc - lea edi,[esp+4] - mov esi,1 - call :%puts1ediesi -- (edi=raw text, esi=length) - ret 4 - ::printi - mov eax,[esp+4] - push 0 -- no cr - call :%putsint -- (nb limited to +/-9,999,999,999) - ret 4 - ::prints - mov edi,[esp+4] - mov esi,[edi-12] - call :%puts1ediesi -- (edi=raw text, esi=length) - ret 4 - ::setbuiltins - mov eax,:printc - lea edi,[printc] - call :%pStoreMint - mov eax,:printi - lea edi,[printi] - call :%pStoreMint - mov eax,:prints - lea edi,[prints] - call :%pStoreMint - } - return {printc,printi,prints} - end function +function setbuiltins() +atom printc,printi,prints + #ilASM{ + jmp :setbuiltins + ::printc + lea edi,[esp+4] + mov esi,1 + call :%puts1ediesi -- (edi=raw text, esi=length) + ret 4 + ::printi + mov eax,[esp+4] + push 0 -- no cr + call :%putsint -- (nb limited to +/-9,999,999,999) + ret 4 + ::prints + mov edi,[esp+4] + mov esi,[edi-12] + call :%puts1ediesi -- (edi=raw text, esi=length) + ret 4 + ::setbuiltins + mov eax,:printc + lea edi,[printc] + call :%pStoreMint + mov eax,:printi + lea edi,[printi] + call :%pStoreMint + mov eax,:prints + lea edi,[prints] + call :%pStoreMint + } + return {printc,printi,prints} +end function - global constant builtin_names = {"printc","printi","prints"} - global constant builtins = setbuiltins() +global constant builtin_names = {"printc","printi","prints"} +global constant builtins = setbuiltins() - global atom var_mem, code_mem +global atom var_mem, code_mem - function RawStringPtr(integer n) -- (based on IupRawStringPtr from pGUI.e) - -- - -- Returns a raw string pointer for s, somewhat like allocate_string(s), but using the existing memory. - -- NOTE: The return is only valid as long as the value passed as the parameter remains in existence. - -- - atom res - string s = strings[n] - #ilASM{ - mov eax,[s] - lea edi,[res] - shl eax,2 - call :%pStoreMint - } - stringptrs[n] = res - return res - end function +function RawStringPtr(integer n) -- (based on IupRawStringPtr from pGUI.e) +-- +-- Returns a raw string pointer for s, somewhat like allocate_string(s), but using the existing memory. +-- NOTE: The return is only valid as long as the value passed as the parameter remains in existence. +-- +atom res + string s = strings[n] + #ilASM{ + mov eax,[s] + lea edi,[res] + shl eax,2 + call :%pStoreMint + } + stringptrs[n] = res + return res +end function - global procedure fixup() - var_mem = allocate(length(vars)*4) - mem_set(var_mem,0,length(vars)*4) - code_mem = allocate(length(code)) - poke(code_mem,code) - while chain!=0 do - integer this = chain - chain = code[this] - integer ftype = code[this+1] - integer id = code[this+2] - switch ftype do - case 1: -- vars - poke4(code_mem+this-1,var_mem+(id-1)*4) - case 2: -- strings - poke4(code_mem+this-1,RawStringPtr(id)) - case 3: -- builtins - poke4(code_mem+this-1,builtins[id]-(code_mem+this+3)) - end switch - end while - end procedure - - -- - -- demo\rosetta\Compiler\cgen.exw - -- ============================== - -- - -- Generates 32-bit machine code (see note in vm.exw) - -- - without js -- (machine code!) - include cgen.e +-- demo\rosetta\Compiler\cgen.exw +-- Generates 32-bit machine code (see note in vm.exw) +without js -- (machine code!) +include cgen.e - function get_var_name(atom addr) - integer n = (addr-var_mem)/4+1 - if n<1 or n>length(vars) then ?9/0 end if - return vars[n] - end function +function get_var_name(atom addr) + integer n = (addr-var_mem)/4+1 + if n<1 or n>length(vars) then ?9/0 end if + return vars[n] +end function - function hxl(integer pc, object oh, string fmt, sequence args={}) - -- helper routine to display the octal/hex bytes just decoded, - -- along with the code offset and the human-readable text. - if length(args) then fmt = sprintf(fmt,args) end if - sequence octhex = {} - atom base = code_mem+pc - integer len = 0 - if integer(oh) then -- all octal - for i=1 to oh do - octhex = append(octhex,sprintf("0o%03o",peek(base))) - base += 1 - end for - len = oh - else -- some octal and some hex - for i=1 to length(oh) by 2 do - for j=1 to oh[i] do - octhex = append(octhex,sprintf("0o%03o",peek(base))) - base += 1 - end for - len += oh[i] - for j=1 to oh[i+1] do - octhex = append(octhex,sprintf("#%02x",peek(base))) - base += 1 - end for - len += oh[i+1] - end for - end if - printf(output_file,"%4d: %-30s %s\n",{pc+1,join(octhex,","),fmt}) - return len - end function +function hxl(integer pc, object oh, string fmt, sequence args={}) +-- helper routine to display the octal/hex bytes just decoded, +-- along with the code offset and the human-readable text. + if length(args) then fmt = sprintf(fmt,args) end if + sequence octhex = {} + atom base = code_mem+pc + integer len = 0 + if integer(oh) then -- all octal + for i=1 to oh do + octhex = append(octhex,sprintf("0o%03o",peek(base))) + base += 1 + end for + len = oh + else -- some octal and some hex + for i=1 to length(oh) by 2 do + for j=1 to oh[i] do + octhex = append(octhex,sprintf("0o%03o",peek(base))) + base += 1 + end for + len += oh[i] + for j=1 to oh[i+1] do + octhex = append(octhex,sprintf("#%02x",peek(base))) + base += 1 + end for + len += oh[i+1] + end for + end if + printf(output_file,"%4d: %-30s %s\n",{pc+1,join(octhex,","),fmt}) + return len +end function - constant cccodes = {"o?" ,"no?","b?" ,"ae?","z" ,"ne" ,"be?","a?", - -- 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , - "s?" ,"ns?","pe?","po?","l" ,"ge" ,"le" ,"g" } - -- 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 +constant cccodes = {"o?" ,"no?","b?" ,"ae?","z" ,"ne" ,"be?","a?", +-- 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , + "s?" ,"ns?","pe?","po?","l" ,"ge" ,"le" ,"g" } +-- 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 - constant regs = {"eax","ecx","edx"} -- (others as/when needed) +constant regs = {"eax","ecx","edx"} -- (others as/when needed) - procedure decode() - -- for a much more complete (and better organised) disassembler, see p2asm.e - integer pc = 0, -- nb 0-based - opcode, xrm +procedure decode() +-- for a much more complete (and better organised) disassembler, see p2asm.e +integer pc = 0, -- nb 0-based + opcode, xrm - while pc<length(code) do - opcode = peek(code_mem+pc) - xrm = -1 - switch opcode do - case 0o150: - atom vaddr = peek4s(code_mem+pc+1) - integer n = find(vaddr,stringptrs) - object arg = iff(n?enquote(strings[n]) - :sprintf("%d",vaddr)) - pc += hxl(pc,{1,4},"push %s",{arg}) - case 0o217: - case 0o377: - integer n = find(opcode,{0o217,0o377}) - string op = {"pop","push"}[n] - xrm = peek(code_mem+pc+1) - if n!=find(xrm,{0o005,0o065}) then exit end if - atom addr = peek4u(code_mem+pc+2) - pc += hxl(pc,{2,4},"%s [%s]",{op,get_var_name(addr)}) - case 0o061: - case 0o071: - case 0o205: - integer n = find(opcode,{0o061,0o071,0o205}) - string op = {"xor","cmp","test"}[n] - xrm = peek(code_mem+pc+1) - if and_bits(xrm,0o300)!=0o300 then exit end if - string r1 = regs[and_bits(xrm,0o070)/0o010+1] - string r2 = regs[and_bits(xrm,0o007)+1] - pc += hxl(pc,2,"%s %s,%s",{op,r1,r2}) - case 0o017: - xrm = peek(code_mem+pc+1) - switch xrm do - case 0o224: - case 0o225: - case 0o234: - case 0o235: - case 0o236: - case 0o237: - string cc = cccodes[and_bits(xrm,0o017)+1] - xrm = peek(code_mem+pc+2) - if xrm=0o300 then - pc += hxl(pc,3,"set%s al",{cc}) - elsif xrm=0o301 then - pc += hxl(pc,3,"set%s cl",{cc}) - else - exit - end if - case 0o204: - integer offset = peek4s(code_mem+pc+2) - pc += hxl(pc,{2,4},"jz %d",{pc+6+offset+1}) - else - exit - end switch - case 0o010: - case 0o040: - xrm = peek(code_mem+pc+1) - if xrm=0o310 then - string lop = {"or","and"}[find(opcode,{0o010,0o040})] - pc += hxl(pc,2,"%s al,cl",{lop}) - else - exit - end if - case 0o120: - case 0o122: - case 0o130: - case 0o131: - case 0o132: - string op = {"push","pop"}[find(and_bits(opcode,0o070),{0o020,0o030})] - string reg = regs[and_bits(opcode,0o007)+1] - pc += hxl(pc,1,"%s %s",{op,reg}) - case 0o231: - pc += hxl(pc,1,"cdq") - case 0o164: - case 0o353: - string jop = iff(opcode=0o164?"jz":"jmp") - integer offset = peek1s(code_mem+pc+1) - pc += hxl(pc,{1,1},"%s %d",{jop,pc+2+offset+1}) - case 0o351: - integer offset = peek4s(code_mem+pc+1) - pc += hxl(pc,{1,4},"jmp %d",{pc+5+offset+1}) - case 0o303: - pc += hxl(pc,1,"ret") - case 0o350: - integer offset = peek4s(code_mem+pc+1) - atom addr = offset+code_mem+pc+5 - integer n = find(addr,builtins) - pc += hxl(pc,{1,4},"call :%s",{builtin_names[n]}) - case 0o001: - case 0o041: - case 0o051: - integer n = find(opcode,{0o001,0o041,0o051}) - string op = {"add","and","sub"}[n] - xrm = peek(code_mem+pc+1) - switch xrm do - case 0o004: - if peek(code_mem+pc+2)=0o044 then - pc += hxl(pc,3,"%s [esp],eax",{op}) - else - exit - end if - else - exit - end switch - case 0o367: - xrm = peek(code_mem+pc+1) - if and_bits(xrm,0o300)!=0o300 then exit end if - integer n = find(and_bits(xrm,0o070),{0o030,0o040,0o070}) - if n=0 then exit end if - string op = {"neg","mul","idiv"}[n] - string reg = regs[and_bits(xrm,0o007)+1] - pc += hxl(pc,2,"%s %s",{op,reg}) - else - exit - end switch - end while - if pc<length(code) then - ?"incomplete:" - if xrm=-1 then - ?{pc+1,sprintf("0o%03o",opcode)} - else - ?{pc+1,sprintf("0o%03o 0o%03o",{opcode,xrm})} - end if - end if - end procedure + while pcprocedure main(sequence cl) - open_files(cl) - toks = lex() - object t = parse() - code_gen(t) - fixup() - decode() - free({var_mem,code_mem}) - close_files() - end procedure +procedure main(sequence cl) + open_files(cl) + toks = lex() + object t = parse() + code_gen(t) + fixup() + decode() + free({var_mem,code_mem}) + close_files() +end procedure - --main(command_line()) - main({0,0,"gcd.c"}) - - -- - -- demo\rosetta\Compiler\core.e - -- ============================ - -- - -- Standard declarations and routines used by lex.exw, parse.exw, cgen.exw, and interp.exw - -- (included in distribution as above, which contains some additional sanity checks) - -- - with javascript_semantics - global constant EOF = -1, STDIN = 0, STDOUT = 1 +-- demo\rosetta\Compiler\core.e +-- Standard declarations and routines used by lex.exw, parse.exw, cgen.exw, and interp.exw +-- (included in distribution as above, which contains some additional sanity checks) +with javascript_semantics +global constant EOF = -1, STDIN = 0, STDOUT = 1 - global enum NONE=0, UNARY=1, BINARY=2 - global type nary(integer n) return n=NONE or n=UNARY or n=BINARY end type +global enum NONE=0, UNARY=1, BINARY=2 +global type nary(integer n) return n=NONE or n=UNARY or n=BINARY end type - global sequence tkNames = {} -- eg/ie {"Op_multiply","Op_divide",..} - global sequence precedences = {} - global sequence narys = {} -- NONE/UNARY/BINARY - global sequence operators = {} -- eg/ie {"*","/","+","-","<","<=",..} - global sequence opcodes = {} -- idx to tkNames, matching operators +global sequence tkNames = {} -- eg/ie {"Op_multiply","Op_divide",..} +global sequence precedences = {} +global sequence narys = {} -- NONE/UNARY/BINARY +global sequence operators = {} -- eg/ie {"*","/","+","-","<","<=",..} +global sequence opcodes = {} -- idx to tkNames, matching operators - global constant KEYWORDS = new_dict() -- eg/ie {"if"=>idx to tkNames} +global constant KEYWORDS = new_dict() -- eg/ie {"if"=>idx to tkNames} - global enum OPERATOR=1, DIGIT, LETTER -- character classes +global enum OPERATOR=1, DIGIT, LETTER -- character classes - global sequence charmap = repeat(0,255) - charmap['0'..'9'] = DIGIT - charmap['A'..'Z'] = LETTER - charmap['a'..'z'] = LETTER - charmap['_'] = LETTER +global sequence charmap = repeat(0,255) + charmap['0'..'9'] = DIGIT + charmap['A'..'Z'] = LETTER + charmap['a'..'z'] = LETTER + charmap['_'] = LETTER - function tkName(string s, nary n = NONE, integer precedence = -1) - tkNames = append(tkNames,s) - narys = append(narys,n) - precedences = append(precedences,precedence) - return length(tkNames) - end function +function tkName(string s, nary n = NONE, integer precedence = -1) + tkNames = append(tkNames,s) + narys = append(narys,n) + precedences = append(precedences,precedence) + return length(tkNames) +end function - function tkOp(string s, string op, nary n, integer precedence) - integer res = tkName(s, n, precedence) - operators = append(operators,op) - opcodes = append(opcodes,res) - for i=1 to length(op) do - charmap[op[i]] = OPERATOR - end for - return res - end function +function tkOp(string s, string op, nary n, integer precedence) + integer res = tkName(s, n, precedence) + operators = append(operators,op) + opcodes = append(opcodes,res) + for i=1 to length(op) do + charmap[op[i]] = OPERATOR + end for + return res +end function - function tkKw(string s, string keyword) - integer res = tkName(s) - putd(keyword, res, KEYWORDS) - return res - end function +function tkKw(string s, string keyword) + integer res = tkName(s) + putd(keyword, res, KEYWORDS) + return res +end function - global constant - tk_EOI = tkName("End_of_input"), --1 - tk_mul = tkOp("Op_multiply", "*", BINARY,13), --2 - tk_div = tkOp("Op_divide", "/", BINARY,13), --3 - tk_mod = tkOp("Op_mod", "%", BINARY,13), --4 - tk_add = tkOp("Op_add", "+", BINARY,12), --5 - tk_sub = tkOp("Op_subtract", "-", BINARY,12), --6 - tk_neg = tkName("Op_negate", UNARY, 14), --7 - tk_not = tkOp("Op_not", "!", UNARY, 14), --8 - tk_lt = tkOp("Op_less", "<", BINARY,10), --9 - tk_le = tkOp("Op_lessequal", "<=",BINARY,10), --10 - tk_gt = tkOp("Op_greater", ">", BINARY,10), --11 - tk_ge = tkOp("Op_greaterequal", ">=",BINARY,10), --12 - tk_eq = tkOp("Op_equal", "==",BINARY, 9), --13 - tk_ne = tkOp("Op_notequal", "!=",BINARY, 9), --14 - tk_assign = tkOp("Op_assign", "=", NONE, -1), --15 - tk_and = tkOp("Op_and", "&&",BINARY, 5), --16 - tk_or = tkOp("Op_or", "||",BINARY, 4), --17 - tk_if = tkKw("Keyword_if", "if"), --18 - tk_else = tkKw("Keyword_else", "else"), --19 - tk_while = tkKw("Keyword_while","while"), --20 - tk_print = tkKw("Keyword_print","print"), --21 - tk_putc = tkKw("Keyword_putc", "putc"), --22 - tk_LeftParen = tkOp("LeftParen", "(", NONE, -1), --23 - tk_RightParen = tkOp("RightParen", ")", NONE, -1), --24 - tk_LeftBrace = tkOp("LeftBrace", "{", NONE, -1), --25 - tk_RightBrace = tkOp("RightBrace", "}", NONE, -1), --26 - tk_Semicolon = tkOp("Semicolon", ";", NONE, -1), --27 - tk_Comma = tkOp("Comma", ",", NONE, -1), --28 - tk_Identifier = tkName("Identifier"), --29 - tk_Integer = tkName("Integer"), --30 - tk_String = tkName("String"), --31 - tk_Sequence = tkName("Sequence"), --32 - tk_Prints = tkName("tk_Prints"), --33 - tk_Printi = tkName("tk_Printi") --34 +global constant + tk_EOI = tkName("End_of_input"), --1 + tk_mul = tkOp("Op_multiply", "*", BINARY,13), --2 + tk_div = tkOp("Op_divide", "/", BINARY,13), --3 + tk_mod = tkOp("Op_mod", "%", BINARY,13), --4 + tk_add = tkOp("Op_add", "+", BINARY,12), --5 + tk_sub = tkOp("Op_subtract", "-", BINARY,12), --6 + tk_neg = tkName("Op_negate", UNARY, 14), --7 + tk_not = tkOp("Op_not", "!", UNARY, 14), --8 + tk_lt = tkOp("Op_less", "<", BINARY,10), --9 + tk_le = tkOp("Op_lessequal", "<=",BINARY,10), --10 + tk_gt = tkOp("Op_greater", ">", BINARY,10), --11 + tk_ge = tkOp("Op_greaterequal", ">=",BINARY,10), --12 + tk_eq = tkOp("Op_equal", "==",BINARY, 9), --13 + tk_ne = tkOp("Op_notequal", "!=",BINARY, 9), --14 + tk_assign = tkOp("Op_assign", "=", NONE, -1), --15 + tk_and = tkOp("Op_and", "&&",BINARY, 5), --16 + tk_or = tkOp("Op_or", "||",BINARY, 4), --17 + tk_if = tkKw("Keyword_if", "if"), --18 + tk_else = tkKw("Keyword_else", "else"), --19 + tk_while = tkKw("Keyword_while","while"), --20 + tk_print = tkKw("Keyword_print","print"), --21 + tk_putc = tkKw("Keyword_putc", "putc"), --22 + tk_LeftParen = tkOp("LeftParen", "(", NONE, -1), --23 + tk_RightParen = tkOp("RightParen", ")", NONE, -1), --24 + tk_LeftBrace = tkOp("LeftBrace", "{", NONE, -1), --25 + tk_RightBrace = tkOp("RightBrace", "}", NONE, -1), --26 + tk_Semicolon = tkOp("Semicolon", ";", NONE, -1), --27 + tk_Comma = tkOp("Comma", ",", NONE, -1), --28 + tk_Identifier = tkName("Identifier"), --29 + tk_Integer = tkName("Integer"), --30 + tk_String = tkName("String"), --31 + tk_Sequence = tkName("Sequence"), --32 + tk_Prints = tkName("tk_Prints"), --33 + tk_Printi = tkName("tk_Printi") --34 - global integer input_file = STDIN, - output_file = STDOUT +global integer input_file = STDIN, + output_file = STDOUT - type strint(object o) - return string(o) or integer(o) - end type +type strint(object o) + return string(o) or integer(o) +end type - global strint tok_line, -- save of line/col at the start of - tok_col -- token/comment, for result/errors +global strint tok_line, -- save of line/col at the start of + tok_col -- token/comment, for result/errors - global object oneline = "" +global object oneline = "" - constant errfmt = "Line %s column %s:\n%s%s" +constant errfmt = "Line %s column %s:\n%s%s" - function errline() - oneline = substitute(trim(oneline,"\r\n"),'\t',' ') - string padding = repeat(' ',tok_col) - return sprintf("%s\n%s^ ",{oneline,padding}) - end function +function errline() + oneline = substitute(trim(oneline,"\r\n"),'\t',' ') + string padding = repeat(' ',tok_col) + return sprintf("%s\n%s^ ",{oneline,padding}) +end function - global procedure error(sequence msg, sequence args={}) - if length(args) then - msg = sprintf(msg,args) - end if - string el = iff(atom(oneline)?"":errline()) - if integer(tok_line) then tok_line = sprintf("%d",tok_line) end if - if integer(tok_col) then tok_col = sprintf("%d",tok_col) end if - printf(STDOUT,errfmt,{tok_line,tok_col,el,msg}) - {} = wait_key() - abort(1) - end procedure +global procedure error(sequence msg, sequence args={}) + if length(args) then + msg = sprintf(msg,args) + end if + string el = iff(atom(oneline)?"":errline()) + if integer(tok_line) then tok_line = sprintf("%d",tok_line) end if + if integer(tok_col) then tok_col = sprintf("%d",tok_col) end if + printf(STDOUT,errfmt,{tok_line,tok_col,el,msg}) + {} = wait_key() + abort(1) +end procedure - include js_io.e -- fake file i/o for running under pwa/p2js +include js_io.e -- fake file i/o for running under pwa/p2js - function open_file(string file_name, string mode) - integer fn = iff(platform()=JS?js_open(file_name) - :open(file_name, mode)) - if fn<=0 then - printf(STDOUT, "Could not open %s", {file_name}) - {} = wait_key() - abort(1) - end if - return fn - end function +function open_file(string file_name, string mode) + integer fn = iff(platform()=JS?js_open(file_name) + :open(file_name, mode)) + if fn<=0 then + printf(STDOUT, "Could not open %s", {file_name}) + {} = wait_key() + abort(1) + end if + return fn +end function - global procedure open_files(sequence cl) - if length(cl)>2 then - input_file = open_file(cl[3],"r") - if length(cl)>3 then - output_file = open_file(cl[4],"w") - end if - end if - end procedure +global procedure open_files(sequence cl) + if length(cl)>2 then + input_file = open_file(cl[3],"r") + if length(cl)>3 then + output_file = open_file(cl[4],"w") + end if + end if +end procedure - global procedure close_files() - if platform()!=JS then - if input_file!=STDIN then close(input_file) end if - if output_file!=STDOUT then close(output_file) end if - end if - end procedure +global procedure close_files() + if platform()!=JS then + if input_file!=STDIN then close(input_file) end if + if output_file!=STDOUT then close(output_file) end if + end if +end procedure - global function enquote(string s) - return sprintf(`"%s"`,substitute(s,"\n","\\n")) - end function +global function enquote(string s) + return sprintf(`"%s"`,substitute(s,"\n","\\n")) +end function - global function unquote(string s) - if s[1]!='\"' then ?9/0 end if - if s[$]!='\"' then ?9/0 end if - s = substitute(s[2..-2],"\\n","\n") - return s - end function - - -- - -- demo\rosetta\Compiler\js_io.e - -- ============================= - -- - -- Fake file i/o for running under pwa/p2js in a browser - -- Does not cover the human readable reload parts of extra.e - -- - with javascript_semantics - sequence {known_files,kfc} = columnize({ - {"test3.c",split(""" - /* - All lexical tokens - not syntactically correct, but that will - have to wait until syntax analysis - */ - /* Print */ print /* Sub */ - - /* Putc */ putc /* Lss */ < - /* If */ if /* Gtr */ > - /* Else */ else /* Leq */ <= - /* While */ while /* Geq */ >= - /* Lbrace */ { /* Eq */ == - /* Rbrace */ } /* Neq */ != - /* Lparen */ ( /* And */ && - /* Rparen */ ) /* Or */ || - /* Uminus */ - /* Semi */ ; - /* Not */ ! /* Comma */ , - /* Mul */ * /* Assign */ = - /* Div */ / /* Integer */ 42 - /* Mod */ % /* String */ "String literal" - /* Add */ + /* Ident */ variable_name - /* character literal */ '\n' - /* character literal **/ '\\' - /* character literal */ ' ' - ""","\n")}, - {"test4.c",split(""" - /*** test printing, embedded \n and comments with lots of '*' ***/ - print(42); - print("\nHello World\nGood Bye\nok\n"); - print("Print a slash n - \\n.\n"); - ""","\n")}, - {"primes.c",split(""" - /* - Simple prime number generator - */ - count = 1; - n = 1; - limit = 100; - while (n < limit) { - k=3; - p=1; - n=n+2; - while ((k*k<=n) && (p)) { - p=n/k*k!=n; - k=k+2; - } - if (p) { - print(n, " is prime\n"); - count = count + 1; - } - } - print("Total primes found: ", count, "\n"); - ""","\n")}, - {"gcd.c",split(""" - /* Compute the gcd of 1071, 1029: 21 */ +-- demo\rosetta\Compiler\js_io.e +-- Fake file i/o for running under pwa/p2js in a browser +-- Does not cover the human readable reload parts of extra.e +with javascript_semantics +sequence {known_files,kfc} = columnize({ +{"test3.c",split(` +/* + All lexical tokens - not syntactically correct, but that will + have to wait until syntax analysis + */ +/* Print */ print /* Sub */ - +/* Putc */ putc /* Lss */ < +/* If */ if /* Gtr */ > +/* Else */ else /* Leq */ <= +/* While */ while /* Geq */ >= +/* Lbrace */ { /* Eq */ == +/* Rbrace */ } /* Neq */ != +/* Lparen */ ( /* And */ && +/* Rparen */ ) /* Or */ || +/* Uminus */ - /* Semi */ ; +/* Not */ ! /* Comma */ , +/* Mul */ * /* Assign */ = +/* Div */ / /* Integer */ 42 +/* Mod */ % /* String */ "String literal" +/* Add */ + /* Ident */ variable_name +/* character literal */ '\n' +/* character literal **/ '\\' +/* character literal */ ' ' +`,"\n")}, +{"test4.c",split(` +/*** test printing, embedded \n and comments with lots of '*' ***/ +print(42); +print("\nHello World\nGood Bye\nok\n"); +print("Print a slash n - \\n.\n"); +`,"\n")}, +{"primes.c",split(` +/* + Simple prime number generator + */ +count = 1; +n = 1; +limit = 100; +while (n < limit) { + k=3; + p=1; + n=n+2; + while ((k*k<=n) && (p)) { + p=n/k*k!=n; + k=k+2; + } + if (p) { + print(n, " is prime\n"); + count = count + 1; + } +} +print("Total primes found: ", count, "\n"); +`,"\n")}, +{"gcd.c",split(` +/* Compute the gcd of 1071, 1029: 21 */ - a = 1071; - b = 1029; +a = 1071; +b = 1029; - while (b != 0) { - new_a = b; - b = a % b; - a = new_a; - } - print(a); - ""","\n")}, - {"Header.h",split(""" - #define area(h, w) h * w - ""","\n")}, - {"Source.t",split(""" - #include "Header.h" - #define width 5 - #define height 6 - area = #area(height, width)#; - ""","\n")}}) +while (b != 0) { + new_a = b; + b = a % b; + a = new_a; +} +print(a); +`,"\n")}, +{"Header.h",split(` +#define area(h, w) h * w +`,"\n")}, +{"Source.t",split(` +#include "Header.h" +#define width 5 +#define height 6 +area = #area(height, width)#; +`,"\n")}}) - sequence linenos = repeat(-1,length(known_files)) +sequence linenos = repeat(-1,length(known_files)) - global function js_open(string filename) - integer fn = find(filename,known_files) - assert(fn!=0) - linenos[fn] = 0 - return fn - end function +global function js_open(string filename) + integer fn = find(filename,known_files) + assert(fn!=0) + linenos[fn] = 0 + return fn +end function - global function js_gets(integer fn) - integer lineno = linenos[fn]+1 - if lineno<=length(kfc[fn]) then - linenos[fn] = lineno - return kfc[fn][lineno] - end if - return EOF - end function - - -- - -- demo\\rosetta\\Compiler\\lex.e - -- ============================== - -- - -- The reusable part of lex.exw - -- This is only kept separate from core.e for consistency with later modules. +-- demo\\rosetta\\Compiler\\lex.e +-- The reusable part of lex.exw +-- This is only kept separate from core.e for consistency with later modules. +with javascript_semantics +include core.e - with javascript_semantics - include core.e +integer ch = ' ', + line = 0, + col = 0 - integer ch = ' ', - line = 0, - col = 0 +procedure eof(string s) + error("%s in %s literal",{iff(ch=EOF?"EOF":"EOL"),s}) +end procedure - procedure eof(string s) - error("%s in %s literal",{iff(ch=EOF?"EOF":"EOL"),s}) - end procedure +function next_ch() + while 1 do + col += 1 + if oneline=EOF then + ch = EOF + exit + elsif col>length(oneline) then + line += 1 + col = 0 + oneline = iff(platform()=JS?js_gets(input_file) + :gets(input_file)) + else + ch = oneline[col] + exit + end if + end while + return ch +end function - function next_ch() - while 1 do - col += 1 - if oneline=EOF then - ch = EOF - exit - elsif col>length(oneline) then - line += 1 - col = 0 - oneline = iff(platform()=JS?js_gets(input_file) - :gets(input_file)) - else - ch = oneline[col] - exit - end if - end while - return ch - end function +-- for pwa/p2js (JavaScript *really* dislikes tabs in strings): +--constant whitespace = " \t\r\n\x0B\xA0" +constant whitespace = {' ','\t','\r','\n',#0B,#A0} +-- (0x0B is Vertical Tab, 0xA0 is Non-breaking space) - -- for pwa/p2js (JavaScript *really* dislikes tabs in strings): - --constant whitespace = " \t\r\n\x0B\xA0" - constant whitespace = {' ','\t','\r','\n',#0B,#A0} - -- (0x0B is Vertical Tab, 0xA0 is Non-breaking space) +procedure skipspacesandcomments() + while 1 do + if not find(ch,whitespace) then + if ch='/' and colprocedure skipspacesandcomments() - while 1 do - if not find(ch,whitespace) then - if ch='/' and col<length(oneline) and oneline[col+1]='*' then - tok_line = line -- (in case of EOF error) - tok_col = col - ch = next_ch() -- (can be EOF) - ch = next_ch() -- ( "" ) - while 1 do - if ch='*' then - ch = next_ch() - if ch='/' then exit end if - elsif ch=EOF then - error("EOF in comment") - else - ch = next_ch() - end if - end while - else - exit - end if - end if - ch = next_ch() - end while - end procedure +function escape_char(string s) + ch = next_ch() -- (discard the '\\') + if ch='n' then + ch = '\n' + elsif ch='\\' then + ch = '\\' + elsif ch=EOF + or ch='\n' then + eof(s) + else + error(`unknown escape sequence \%c`, {ch}) + end if + return ch +end function - function escape_char(string s) - ch = next_ch() -- (discard the '\\') - if ch='n' then - ch = '\n' - elsif ch='\\' then - ch = '\\' - elsif ch=EOF - or ch='\n' then - eof(s) - else - error(`unknown escape sequence \%c`, {ch}) - end if - return ch - end function +function char_lit() + integer startch = ch, + res = next_ch() -- (skip opening quote, save res) + if ch=startch then + error("empty character constant") + elsif ch='\\' then + res = escape_char("character") + end if + ch = next_ch() + if ch=EOF + or ch='\n' then + eof("character") + elsif ch!=startch then + error("multi-character constant") + end if + ch = next_ch() + return {tk_Integer, res} +end function - function char_lit() - integer startch = ch, - res = next_ch() -- (skip opening quote, save res) - if ch=startch then - error("empty character constant") - elsif ch='\\' then - res = escape_char("character") - end if - ch = next_ch() - if ch=EOF - or ch='\n' then - eof("character") - elsif ch!=startch then - error("multi-character constant") - end if - ch = next_ch() - return {tk_Integer, res} - end function +function string_lit() + integer startch = ch + string text = "" + while next_ch()!=startch do + if ch=EOF + or ch='\n' then + eof("string") + elsif ch='\\' then + ch = escape_char("string") + end if + text &= ch + end while + ch = next_ch() + return {tk_String, text} +end function - function string_lit() - integer startch = ch - string text = "" - while next_ch()!=startch do - if ch=EOF - or ch='\n' then - eof("string") - elsif ch='\\' then - ch = escape_char("string") - end if - text &= ch - end while - ch = next_ch() - return {tk_String, text} - end function +function get_op() +-- sequence operator = {ch} + string operator = ""&ch + ch = next_ch() + while charmap[ch]=OPERATOR + and find(operator&ch,operators) do + -- (^ ie/eg merge ">=", but not ");") + operator &= ch + ch = next_ch() + end while + integer k = find(operator,operators) + if k=0 then error("unknown operator") end if + return {opcodes[k], 0} -- (0 unused) +end function - function get_op() - -- sequence operator = {ch} - string operator = ""&ch - ch = next_ch() - while charmap[ch]=OPERATOR - and find(operator&ch,operators) do - -- (^ ie/eg merge ">=", but not ");") - operator &= ch - ch = next_ch() - end while - integer k = find(operator,operators) - if k=0 then error("unknown operator") end if - return {opcodes[k], 0} -- (0 unused) - end function +function get_int() + integer i = 0 + while charmap[ch]=DIGIT do + i = i*10 + (ch-'0') + ch = next_ch() + end while + if charmap[ch]=LETTER then + error("invalid number") + end if + return {tk_Integer, i} +end function - function get_int() - integer i = 0 - while charmap[ch]=DIGIT do - i = i*10 + (ch-'0') - ch = next_ch() - end while - if charmap[ch]=LETTER then - error("invalid number") - end if - return {tk_Integer, i} - end function +function get_ident() + string text = "" + while find(charmap[ch],{LETTER,DIGIT}) do + text &= ch + ch = next_ch() + end while + integer keyword = getd(text,KEYWORDS) + if keyword!=NULL then + return {keyword, 0} -- (0 unused) + end if + return {tk_Identifier, text} +end function - function get_ident() - string text = "" - while find(charmap[ch],{LETTER,DIGIT}) do - text &= ch - ch = next_ch() - end while - integer keyword = getd(text,KEYWORDS) - if keyword!=NULL then - return {keyword, 0} -- (0 unused) - end if - return {tk_Identifier, text} - end function +function get_token() + skipspacesandcomments() + tok_line = line + tok_col = col + switch ch do + case EOF then return {tk_EOI, 0} -- (0 unused) + case '\'' then return char_lit() + case '"' then return string_lit() + else + switch charmap[ch] do + case OPERATOR then return get_op() + case DIGIT then return get_int() + case LETTER then return get_ident() + else error("unrecognized character: (%d)", {ch}) + end switch + end switch +end function - function get_token() - skipspacesandcomments() - tok_line = line - tok_col = col - switch ch do - case EOF then return {tk_EOI, 0} -- (0 unused) - case '\'' then return char_lit() - case '"' then return string_lit() - else - switch charmap[ch] do - case OPERATOR then return get_op() - case DIGIT then return get_int() - case LETTER then return get_ident() - else error("unrecognized character: (%d)", {ch}) - end switch - end switch - end function - - global function lex() - sequence toks = {} - integer tok = -1 - object v - while tok!=tk_EOI do - {tok,v} = get_token() - toks = append(toks,{tok_line,tok_col,tok,v}) - end while - return toks - end function - - -- - -- demo\rosetta\Compiler\extra.e - -- ============================= - -- - -- Routines to reload human-readable files (deviation from task requirement) - -- - without js -- (file i/o) +-- demo\rosetta\Compiler\extra.e +-- Routines to reload human-readable files (deviation from task requirement) +without js -- (file i/o) - --The following can be used to load .lex files, as created by lex.exw: - -- (in place of the existing get_tok() in parse.e) - function get_tok() - string line = trim(gets(input_file)) - sequence tok = split(line,' ',limit:=4,no_empty:=1) - integer k = find(tok[3],tkNames) - if k=0 then ?9/0 end if - tok[3] = k - return tok - end function +--The following can be used to load .lex files, as created by lex.exw: +-- (in place of the existing get_tok() in parse.e) +function get_tok() + string line = trim(gets(input_file)) + sequence tok = split(line,' ',limit:=4,no_empty:=1) + integer k = find(tok[3],tkNames) + if k=0 then ?9/0 end if + tok[3] = k + return tok +end function - --The following can be used to load .ast files, as created by parse.exw: - -- (in place of the existing lex()/parse() pairs in cgen.exw and interp.exw) - function load_ast() - string line = trim(gets(input_file)) - -- Each line has at least one token - sequence node = split(line,' ',limit:=2,no_empty:=1) +--The following can be used to load .ast files, as created by parse.exw: +-- (in place of the existing lex()/parse() pairs in cgen.exw and interp.exw) +function load_ast() + string line = trim(gets(input_file)) + -- Each line has at least one token + sequence node = split(line,' ',limit:=2,no_empty:=1) - string node_type = node[1] + string node_type = node[1] - if node_type == ";" then -- a terminal node - return NULL - end if + if node_type == ";" then -- a terminal node + return NULL + end if - integer n_type = find(node_type,tkNames) - if n_type=0 then ?9/0 end if + integer n_type = find(node_type,tkNames) + if n_type=0 then ?9/0 end if - -- A line with two tokens is a leaf node - -- Leaf nodes are: Identifier, Integer, String - -- The 2nd token is the value - if length(node)>1 then - node[1] = n_type - if n_type=tk_Integer then - node[2] = to_integer(node[2]) - elsif n_type=tk_String then - node[2] = unquote(node[2]) - end if - return node - end if - object left = load_ast() - object right = load_ast() - return {n_type, left, right} - end function - - -- - -- demo\rosetta\Compiler\lex.exw - -- ============================= - -- - with javascript_semantics - include lex.e +-- demo\rosetta\Compiler\lex.exw +with javascript_semantics +include lex.e - procedure main(sequence cl) - open_files(cl) - sequence toks = lex() - integer tok - object v - for i=1 to length(toks) do - {tok_line,tok_col,tok,v} = toks[i] - switch tok do - case tk_Identifier: v = sprintf(" %s",v) - case tk_Integer: v = sprintf(" %5d",v) - case tk_String: v = sprintf(" %s",enquote(v)) - else v = "" - end switch - printf(output_file, "%5d %5d %-10s%s\n", {tok_line,tok_col,tkNames[tok],v}) - end for - close_files() - end procedure +procedure main(sequence cl) + open_files(cl) + sequence toks = lex() + integer tok + object v + for i=1 to length(toks) do + {tok_line,tok_col,tok,v} = toks[i] + switch tok do + case tk_Identifier: v = sprintf(" %s",v) + case tk_Integer: v = sprintf(" %5d",v) + case tk_String: v = sprintf(" %s",enquote(v)) + else v = "" + end switch + printf(output_file, "%5d %5d %-10s%s\n", {tok_line,tok_col,tkNames[tok],v}) + end for + close_files() +end procedure - --main(command_line()) - main({0,0,"test4.c"}) - - -- - -- demo\rosetta\Compiler\parse.e - -- ============================= - -- - -- The reusable part of parse.exw - -- - with javascript_semantics - include lex.e +-- demo\rosetta\Compiler\parse.e +-- The reusable part of parse.exw +with javascript_semantics +include lex.e - sequence tok +sequence tok - procedure errd(sequence msg, sequence args={}) - {tok_line,tok_col} = tok - error(msg,args) - end procedure +procedure errd(sequence msg, sequence args={}) + {tok_line,tok_col} = tok + error(msg,args) +end procedure - global sequence toks - integer next_tok = 1 +global sequence toks +integer next_tok = 1 - function get_tok() - sequence tok = toks[next_tok] - next_tok += 1 - return tok - end function +function get_tok() + sequence tok = toks[next_tok] + next_tok += 1 + return tok +end function - procedure expect(string msg, integer s) - integer tk = tok[3] - if tk!=s then - errd("%s: Expecting '%s', found '%s'\n", {msg, tkNames[s], tkNames[tk]}) - end if - tok = get_tok() - end procedure +procedure expect(string msg, integer s) + integer tk = tok[3] + if tk!=s then + errd("%s: Expecting '%s', found '%s'\n", {msg, tkNames[s], tkNames[tk]}) + end if + tok = get_tok() +end procedure - function expr(integer p) - object x = NULL, node - integer op = tok[3] +function expr(integer p) + object x = NULL, node + integer op = tok[3] - switch op do - case tk_LeftParen: - tok = get_tok() - x = expr(0) - expect("expr",tk_RightParen) - case tk_sub: - case tk_add: - tok = get_tok() - node = expr(precedences[tk_neg]); - x = iff(op==tk_sub?{tk_neg, node, NULL}:node) - case tk_not: - tok = get_tok(); - x = {tk_not, expr(precedences[tk_not]), NULL} - case tk_Identifier: - x = {tk_Identifier, tok[4]} - tok = get_tok(); - case tk_Integer: - x = {tk_Integer, tok[4]} - tok = get_tok(); - default: - errd("Expecting a primary, found: %s\n", tkNames[op]) - end switch + switch op do + case tk_LeftParen: + tok = get_tok() + x = expr(0) + expect("expr",tk_RightParen) + case tk_sub: + case tk_add: + tok = get_tok() + node = expr(precedences[tk_neg]); + x = iff(op==tk_sub?{tk_neg, node, NULL}:node) + case tk_not: + tok = get_tok(); + x = {tk_not, expr(precedences[tk_not]), NULL} + case tk_Identifier: + x = {tk_Identifier, tok[4]} + tok = get_tok(); + case tk_Integer: + x = {tk_Integer, tok[4]} + tok = get_tok(); + default: + errd("Expecting a primary, found: %s\n", tkNames[op]) + end switch - op = tok[3] - while narys[op]=BINARY - and precedences[op]>=p do - tok = get_tok() - x = {op, x, expr(precedences[op]+1)} - op = tok[3] - end while - return x; - end function + op = tok[3] + while narys[op]=BINARY + and precedences[op]>=p do + tok = get_tok() + x = {op, x, expr(precedences[op]+1)} + op = tok[3] + end while + return x; +end function - function paren_expr(string msg) - expect(msg, tk_LeftParen); - object t = expr(0) - expect(msg, tk_RightParen); - return t - end function +function paren_expr(string msg) + expect(msg, tk_LeftParen); + object t = expr(0) + expect(msg, tk_RightParen); + return t +end function - function stmt() - object t = NULL, e, s +function stmt() + object t = NULL, e, s - switch tok[3] do - case tk_if: - tok = get_tok(); - object condition = paren_expr("If-cond"); - object ifblock = stmt(); - object elseblock = NULL; - if tok[3] == tk_else then - tok = get_tok(); - elseblock = stmt(); - end if - t = {tk_if, condition, {tk_if, ifblock, elseblock}} - case tk_putc: - tok = get_tok(); - e = paren_expr("Prtc") - t = {tk_putc, e, NULL} - expect("Putc", tk_Semicolon); - case tk_print: - tok = get_tok(); - expect("Print",tk_LeftParen) - while 1 do - if tok[3] == tk_String then - e = {tk_Prints, {tk_String, tok[4]}, NULL} - tok = get_tok(); - else - e = {tk_Printi, expr(0), NULL} - end if - t = {tk_Sequence, t, e} - if tok[3]!=tk_Comma then exit end if - expect("Print", tk_Comma) - end while - expect("Print", tk_RightParen); - expect("Print", tk_Semicolon); - case tk_Semicolon: - tok = get_tok(); - case tk_Identifier: - object v - v = {tk_Identifier, tok[4]} - tok = get_tok(); - expect("assign", tk_assign); - e = expr(0); - t = {tk_assign, v, e} - expect("assign", tk_Semicolon); - case tk_while: - tok = get_tok(); - e = paren_expr("while"); - s = stmt(); - t = {tk_while, e, s} - case tk_LeftBrace: /* {stmt} */ - expect("LeftBrace", tk_LeftBrace) - while not find(tok[3],{tk_RightBrace,tk_EOI}) do - t = {tk_Sequence, t, stmt()} - end while - expect("LeftBrace", tk_RightBrace); - break; - case tk_EOI: - break; - default: - errd("expecting start of statement, found '%s'\n", tkNames[tok[3]]); - end switch - return t - end function + switch tok[3] do + case tk_if: + tok = get_tok(); + object condition = paren_expr("If-cond"); + object ifblock = stmt(); + object elseblock = NULL; + if tok[3] == tk_else then + tok = get_tok(); + elseblock = stmt(); + end if + t = {tk_if, condition, {tk_if, ifblock, elseblock}} + case tk_putc: + tok = get_tok(); + e = paren_expr("Prtc") + t = {tk_putc, e, NULL} + expect("Putc", tk_Semicolon); + case tk_print: + tok = get_tok(); + expect("Print",tk_LeftParen) + while 1 do + if tok[3] == tk_String then + e = {tk_Prints, {tk_String, tok[4]}, NULL} + tok = get_tok(); + else + e = {tk_Printi, expr(0), NULL} + end if + t = {tk_Sequence, t, e} + if tok[3]!=tk_Comma then exit end if + expect("Print", tk_Comma) + end while + expect("Print", tk_RightParen); + expect("Print", tk_Semicolon); + case tk_Semicolon: + tok = get_tok(); + case tk_Identifier: + object v + v = {tk_Identifier, tok[4]} + tok = get_tok(); + expect("assign", tk_assign); + e = expr(0); + t = {tk_assign, v, e} + expect("assign", tk_Semicolon); + case tk_while: + tok = get_tok(); + e = paren_expr("while"); + s = stmt(); + t = {tk_while, e, s} + case tk_LeftBrace: /* {stmt} */ + expect("LeftBrace", tk_LeftBrace) + while not find(tok[3],{tk_RightBrace,tk_EOI}) do + t = {tk_Sequence, t, stmt()} + end while + expect("LeftBrace", tk_RightBrace); + break; + case tk_EOI: + break; + default: + errd("expecting start of statement, found '%s'\n", tkNames[tok[3]]); + end switch + return t +end function - global function parse() - object t = NULL - tok = get_tok() - while 1 do - object s = stmt() - if s=NULL then exit end if - t = {tk_Sequence, t, s} - end while - return t - end function - - -- - -- demo\rosetta\Compiler\parse.exw - -- =============================== - -- - with javascript_semantics - include parse.e +-- demo\rosetta\Compiler\parse.exw +with javascript_semantics +include parse.e - procedure print_ast(object t) - if t == NULL then - printf(output_file,";\n") - else - integer ttype = t[1] - printf(output_file,tkNames[ttype]) - if ttype=tk_Identifier then - printf(output_file," %s\n",t[2]) - elsif ttype=tk_Integer then - printf(output_file," %d\n",t[2]) - elsif ttype=tk_String then - printf(output_file," %s\n",enquote(t[2])) - else - printf(output_file,"\n") - print_ast(t[2]) - print_ast(t[3]) - end if - end if - end procedure +procedure print_ast(object t) + if t == NULL then + printf(output_file,";\n") + else + integer ttype = t[1] + printf(output_file,tkNames[ttype]) + if ttype=tk_Identifier then + printf(output_file," %s\n",t[2]) + elsif ttype=tk_Integer then + printf(output_file," %d\n",t[2]) + elsif ttype=tk_String then + printf(output_file," %s\n",enquote(t[2])) + else + printf(output_file,"\n") + print_ast(t[2]) + print_ast(t[3]) + end if + end if +end procedure - function ptree(object t) - if sequence(t) then - integer t1 = t[1] - t = deep_copy(t) - t[1] = tkNames[t1] - if not find(t1,{tk_Identifier,tk_String}) then - for i=2 to length(t) do - if t1=tk_Sequence and t[i]=NULL then - t[i] = "NULL" - else - t[i] = ptree(t[i]) - end if - end for - end if - end if - return t - end function +function ptree(object t) + if sequence(t) then + integer t1 = t[1] + t = deep_copy(t) + t[1] = tkNames[t1] + if not find(t1,{tk_Identifier,tk_String}) then + for i=2 to length(t) do + if t1=tk_Sequence and t[i]=NULL then + t[i] = "NULL" + else + t[i] = ptree(t[i]) + end if + end for + end if + end if + return t +end function - procedure main(sequence cl) - open_files(cl) - toks = lex() - object t = parse() - print_ast(t) - pp(ptree(t),{pp_Nest,10,pp_Pause,0,pp_IntCh,false}) - close_files() - end procedure +procedure main(sequence cl) + open_files(cl) + toks = lex() + object t = parse() + print_ast(t) +pp(ptree(t),{pp_Nest,10,pp_Pause,0,pp_IntCh,false}) + close_files() +end procedure - --main(command_line()) - main({0,0,"test3.c"}) -- not parseable! - --main({0,0,"primes.c"}) -- as Algol, C, Python (apart from spacing) - --main({0,0,"count.c"}) -- as AWK ( "" ) - - -- - -- demo\rosetta\Compiler\vm.exw - -- ============================ - -- - -- Since we have generated executable machine code, the virtual machine, such as it is, is just - -- the higher level implementations of printc/i/s, see setbuiltins() in cgen.e - -- Otherwise the only difference between this and cgen.exw is call(code_mem) instead of decode(). - -- - -- A quick test (calculating fib(44) 10^6 times) suggests ~500 times faster than interp.exw - - -- which is to be expected given that a single add instruction (1 clock) here is implemented as - -- at least three (and quite possibly five!) resursive calls to interp() in the other. +-- demo\rosetta\Compiler\vm.exw +-- Since we have generated executable machine code, the virtual machine, such as it is, is just +-- the higher level implementations of printc/i/s, see setbuiltins() in cgen.e +-- Otherwise the only difference between this and cgen.exw is call(code_mem) instead of decode(). +-- A quick test (calculating fib(44) 10^6 times) suggests ~500 times faster than interp.exw - +-- which is to be expected given that a single add instruction (1 clock) here is implemented as +-- at least three (and quite possibly five!) resursive calls to interp() in the other. +format PE32 +--format ELF32 +-- Note: cgen generates 32-bit machine code, which cannot be executed directly from a 64-bit interpreter. +-- You can however, via the magic of either the above format directives, use a 64-bit version of +-- Phix to compile this (just add a -c command line option) to a 32-bit executable, which can. +-- It would not be particularly difficult to emit 32 or 64 bit code, but some source code files +-- would, fairly obviously, then be very nearly twice as long, and a fair bit harder to read. +without js -- (machine code!) +include cgen.e - format PE32 - --format ELF32 - -- Note: cgen generates 32-bit machine code, which cannot be executed directly from a 64-bit interpreter. - -- You can however, via the magic of either the above format directives, use a 64-bit version of - -- Phix to compile this (just add a -c command line option) to a 32-bit executable, which can. - -- It would not be particularly difficult to emit 32 or 64 bit code, but some source code files - -- would, fairly obviously, then be very nearly twice as long, and a fair bit harder to read. +procedure main(sequence cl) + open_files(cl) + toks = lex() + object t = parse() + code_gen(t) + fixup() + if machine_bits()=32 then + -- ^ as per note above + call(code_mem) + end if + free({var_mem,code_mem}) + close_files() +end procedure - without js -- (machine code!) - include cgen.e - - procedure main(sequence cl) - open_files(cl) - toks = lex() - object t = parse() - code_gen(t) - fixup() - if machine_bits()=32 then - -- ^ as per note above - call(code_mem) - end if - free({var_mem,code_mem}) - close_files() - end procedure - - --main(command_line()) - main({0,0,"count.c"}) - - with javascript_semantics - integer count = 0, n = 11*11, - limit = iff(platform()=JS?10:20) - atom t0 = time(), t1 = time() - while count<limit do - if gcd(n,3*5*7)=1 then - sequence f = prime_factors(n,true,-1) - if length(f)>1 then - string s = sprintf("%d",n) - bool valid = true - for i=1 to length(f) do - if (i=1 or f[i]!=f[i-1]) - and not match(sprintf("%d",f[i]),s) then - valid = false - exit - end if - end for - if valid then - count += 1 - string t = join(apply(f,sprint),"x"), - e = elapsed(time()-t1) - printf(1,"%2d: %,10d = %-17s (%s)\n",{count,n,t,e}) - t1 = time() - end if - end if - end if - n += 2 - end while - printf(1,"Total time:%s\n",{elapsed(time()-t0)}) - - with javascript_semantics - integer count = 0, n = 11*11, - limit = iff(platform()=JS?10:20) - atom t0 = time(), t1 = time() - while count<limit do - string s = sprintf("%d",n) - integer l = floor(sqrt(n)), k = n, f = 3 - bool valid = true - while true do - if remainder(k,f)=0 then - if f<10 or not match(sprintf("%d",f),s) then - valid = false - exit - end if - if f=k then exit end if - k /= f - else - f += 2 - if f>l then - if k=n or not match(sprintf("%d",k),s) then - valid = false - end if - exit - end if - end if - end while - if valid then - count += 1; - string t = join(apply(prime_factors(n,true,-1),sprint),"x"), - e = elapsed(time()-t1) - printf(1,"%2d: %,10d = %-17s (%s)\n",{count,n,t,e}) - t1 = time() - end if - n += 2 - end while - printf(1,"Total time:%s\n",{elapsed(time()-t0)}) - - without js -- (threads) - procedure echo(string s) - sleep(rand(100)/100) - enter_cs() - puts(1,s) - puts(1,'\n') - leave_cs() - end procedure +without js -- (threads) +procedure echo(string s) + sleep(rand(100)/100) + enter_cs() + puts(1,s) + puts(1,'\n') + leave_cs() +end procedure - constant threads = {create_thread(routine_id("echo"),{"Enjoy"}), - create_thread(routine_id("echo"),{"Rosetta"}), - create_thread(routine_id("echo"),{"Code"})} +constant threads = {create_thread(routine_id("echo"),{"Enjoy"}), + create_thread(routine_id("echo"),{"Rosetta"}), + create_thread(routine_id("echo"),{"Code"})} - wait_thread(threads) - puts(1,"done") - {} = wait_key() - - with javascript_semantics - constant precision = 10000 +with javascript_semantics +constant precision = 10000 - function continued_fraction(integer f, steps=precision) - atom a, b, res = 0 - for n=steps to 1 by -1 do - {a, b} = f(n) - res := b / (a + res) - end for - {a} = f(0) - return a + res - end function +function continued_fraction(integer f, steps=precision) + atom a, b, res = 0 + for n=steps to 1 by -1 do + {a, b} = f(n) + res := b / (a + res) + end for + {a} = f(0) + return a + res +end function - function sqr2(integer n) return {iff(n=0?1:2),1} end function +function sqr2(integer n) return {iff(n=0?1:2),1} end function - function nap(integer n) return {iff(n=0?2:n),iff(n=1?1:n-1)} end function +function nap(integer n) return {iff(n=0?2:n),iff(n=1?1:n-1)} end function - function pi(integer n) return {iff(n=0?3:6),power(2*n-1,2)} end function +function pi(integer n) return {iff(n=0?3:6),power(2*n-1,2)} end function - printf(1,"Precision: %d\n", {precision}) - printf(1,"Sqr(2): %.10g\n", {continued_fraction(sqr2)}) - printf(1,"Napier: %.10g\n", {continued_fraction(nap)}) - printf(1,"Pi: %.10g\n", {continued_fraction(pi)}) - - with javascript_semantics - function decrat(string s) - integer nom = 0, - denom = 1 - assert(s[1..2]="0.") - for i=3 to length(s) do - integer ch = s[i] - assert(ch>='0' and ch<='9') - nom = nom*10 + ch-'0' - denom *= 10 - end for - return sq_div({nom,denom},gcd(nom,denom)) - end function +with javascript_semantics +function decrat(string s) + integer nom = 0, + denom = 1 + assert(s[1..2]="0.") + for i=3 to length(s) do + integer ch = s[i] + assert(ch>='0' and ch<='9') + nom = nom*10 + ch-'0' + denom *= 10 + end for + return sq_div({nom,denom},gcd(nom,denom)) +end function - ?decrat("0.9054054") - ?decrat("0.518518") - ?decrat("0.75") - - with javascript_semantics - ?elapsed(7259) - ?elapsed(86400) - ?elapsed(6000000) - - with javascript_semantics - include timedate.e - ?elapsed(6000000-timedelta(days:=6,hours:=10)) - stable + all [s = 0 n = 3] [00.00.127] ; new birth + true [black] ; barren + ] + xy: map-to-pixels x y + append draws compose [fill-pen (color) circle (xy) (rad)] + + ; process next generation + nxt/:x/:y: either any [ + all [mat/:x/:y = 1 n > 1 n < 4] ; lives on + all [mat/:x/:y = 0 n = 3] ; birth + ][1][0] + ] + ] + ; swap matrix + t: mat mat: nxt nxt: t + if (gen: gen + 1) > maxgen [init] + ] ; changer +] + +matrix-rand: func [a b][collect [loop a [keep/only collect [loop b [keep random/only [0 1]]]]]] +matrix-zero: func [a b][collect [loop a [keep/only collect [loop b [keep 0]]]]] + +; neighbour counting in a wrapped world! +nb: func [x y][ + xm1: x - 1 if xm1 < 1 [xm1: xmax] + xp1: x + 1 if xp1 > xmax [xp1: 1] + ym1: y - 1 if ym1 < 1 [ym1: ymax] + yp1: y + 1 if yp1 > ymax [yp1: 1] + mat/:xm1/:ym1 + mat/:xm1/:y + mat/:xm1/:yp1 + + mat/:x/:ym1 + mat/:x/:yp1 + + mat/:xp1/:ym1 + mat/:xp1/:y + mat/:xp1/:yp1 +] + +xmax: 100 ; number of cells, horiz +ymax: 100 ; vert +dispx: xmax * 10 ; display size for 10 pixels cell size +dispy: ymax * 10 ; vert +rad: 0 ; radial size for cells (calculated) + +; matrixes for generations: +mat: matrix-rand xmax ymax +nxt: matrix-zero xmax ymax + +; counters: +gen: 0 +maxgen: 500 + +init: does [ + mat: matrix-rand xmax ymax + nxt: matrix-zero xmax ymax + gen: 0 +] + +main: func [/local p][ + p: make plotter [] + p/header "Conway's Game of Life" + p/display-size: to-pair reduce [dispx dispy] ; display size regardless for x and y range + p/x1: 1 p/x2: xmax + p/y1: 1 p/y2: ymax + p/fn: func [x][x] ; dummy, not used + rad: (min (dispx / xmax) (dispy / ymax)) / 2 + p/draw ; generate drawing + p/draws/line-width: 0 + ;p/draws/pen: white + p/show ; display it +] +main diff --git a/Task/Conways-Game-of-Life/Red/conways-game-of-life.red b/Task/Conways-Game-of-Life/Red/conways-game-of-life.red deleted file mode 100644 index e72164f9bc..0000000000 --- a/Task/Conways-Game-of-Life/Red/conways-game-of-life.red +++ /dev/null @@ -1,56 +0,0 @@ -Red [ - Purpose: "Conway's Game of Life" - Author: "Joe Smith" -] - -neigh: [[0 1] [0 -1] [1 0] [-1 0] [1 1] [1 -1] [-1 1] [-1 -1]] -conway: function [petri] [ - new-petri: copy/deep petri - repeat row length? petri [ - repeat col length? petri [ - live-neigh: 0 - foreach cell neigh [ - try [ - if petri/(:row + cell/1)/(:col + cell/2) = 1 [live-neigh: live-neigh + 1] - ] - ] - switch petri/:row/:col [ - 1 [if any [live-neigh < 2 live-neigh > 3] - [new-petri/:row/:col: 0] - ] - 0 [if live-neigh = 3 [new-petri/:row/:col: 1]] - ]]] - clear insert petri new-petri -] - -*3-3: [ - [0 1 0] - [0 1 0] - [0 1 0] -] - -*8-8: [ - [0 0 1 0 0 0 0 0] - [0 0 0 1 0 0 0 0] - [0 1 1 1 0 0 0 0] - [0 0 0 0 0 0 0 0] - [0 0 0 0 0 0 0 0] - [0 0 0 0 0 0 0 0] - [0 0 0 0 0 0 0 0] - [0 0 0 0 0 0 0 0] -] - -display: function [table] [ - foreach row table [ - print replace/all (replace/all to-string row "0" "_") "1" "#" - ] print "" -] - -loop 5 [ - display *3-3 - conway *3-3 -] -loop 23 [ - display *8-8 - conway *8-8 -] diff --git a/Task/Conways-Game-of-Life/Rust/conways-game-of-life.rust b/Task/Conways-Game-of-Life/Rust/conways-game-of-life.rs similarity index 100% rename from Task/Conways-Game-of-Life/Rust/conways-game-of-life.rust rename to Task/Conways-Game-of-Life/Rust/conways-game-of-life.rs diff --git a/Task/Conways-Game-of-Life/Scheme/conways-game-of-life.ss b/Task/Conways-Game-of-Life/Scheme/conways-game-of-life-1.scm similarity index 100% rename from Task/Conways-Game-of-Life/Scheme/conways-game-of-life.ss rename to Task/Conways-Game-of-Life/Scheme/conways-game-of-life-1.scm diff --git a/Task/Conways-Game-of-Life/Scheme/conways-game-of-life-2.scm b/Task/Conways-Game-of-Life/Scheme/conways-game-of-life-2.scm new file mode 100644 index 0000000000..b692b693b0 --- /dev/null +++ b/Task/Conways-Game-of-Life/Scheme/conways-game-of-life-2.scm @@ -0,0 +1,62 @@ +(import (srfi 231)) + +(define (pad-array-with-zeros a N) + + ;; Pad two-dimensional array with N rows and columns of zeros, + ;; top and bottom, left and right. + ;; Assumes that the domain of a has zero lower bounds. + + (let* ((domain (array-domain a)) + (m (interval-upper-bound domain 0)) + (n (interval-upper-bound domain 1)) + (a_ (array-getter a))) + (make-array (interval-dilate domain (vector (- N) (- N)) (vector N N)) + (lambda (i j) + (or (and (< -1 i m) (< -1 j n) (a_ i j)) + 0))))) + +(define (neighbor-count a) + + ;; Returns a generalized array that contains the number + ;; of 1s in the 8 cells surrounding each cell in the original array. + + (let* ((big-a (array-copy! (pad-array-with-zeros a 1) + (array-storage-class a))) + (domain (array-domain a)) + (translates (map (lambda (translation) + (array-extract (array-translate big-a translation) domain)) + '(#(1 0) #(0 1) #(-1 0) #(0 -1) + #(1 1) #(1 -1) #(-1 1) #(-1 -1))))) + (apply array-map + translates))) + +(define (game-rules a neighbor-count) + + ;; a is the value in a single cell, neighbor-count is the count of 1s in + ;; its 8 neighboring cells. + + (if (zero? a) + (if (eqv? neighbor-count 3) 1 0) + (if (<= 2 neighbor-count 3) 1 0))) + +(define (advance a) + (array-copy! (array-map game-rules a (neighbor-count a)) + (array-storage-class a))) + +(define life-storage-class u1-storage-class) + +(define glider + (list*->array + 2 + '((0 0 0 0 0 0) + (0 0 1 0 0 0) + (0 0 0 1 0 0) + (0 1 1 1 0 0) + (0 0 0 0 0 0) + (0 0 0 0 0 0)) + life-storage-class)) + +(do ((i 0 (+ i 1)) + (pattern glider (advance pattern))) + ((= i 5)) + (pretty-print (array->list* pattern)) + (newline)) diff --git a/Task/Conways-Game-of-Life/SequenceL/conways-game-of-life-1.sequencel b/Task/Conways-Game-of-Life/SequenceL/conways-game-of-life-1.sequencel index 3307c338b7..f4b1ca088b 100644 --- a/Task/Conways-Game-of-Life/SequenceL/conways-game-of-life-1.sequencel +++ b/Task/Conways-Game-of-Life/SequenceL/conways-game-of-life-1.sequencel @@ -1,21 +1,21 @@ life(Cells(2))[I, J] := - let - numNeighbors := Cells[I-1,J-1] + Cells[I-1,J] + Cells[I-1,J+1] + - Cells[I,J-1] +/*current cell*/Cells[I,J+1] + - Cells[I+1,J-1] + Cells[I+1,J] + Cells[I+1,J+1]; - in - 0 when I=1 or J=1 or I=size(Cells) or J=size(Cells[I]) //On Border - else - 0 when numNeighbors < 2 or numNeighbors > 3 //Cell Dies - else - 1 when Cells[I,J] = 1 and numNeighbors = 2 or numNeighbors = 3 //Cell lives on or is born. - else - Cells[I,J]; //No Change - - + let + numNeighbors := Cells[I-1,J-1] + Cells[I-1,J] + Cells[I-1,J+1] + + Cells[I,J-1] +/*current cell*/Cells[I,J+1] + + Cells[I+1,J-1] + Cells[I+1,J] + Cells[I+1,J+1]; + in + 0 when I=1 or J=1 or I=size(Cells) or J=size(Cells[I]) //On Border + else + 0 when numNeighbors < 2 or numNeighbors > 3 //Cell Dies + else + 1 when Cells[I,J] = 1 and numNeighbors = 2 or numNeighbors = 3 //Cell lives on or is born. + else + Cells[I,J]; //No Change + + stressTestInput(n(0))[y,x] := - 0 when not y = n / 2 - else - 1 - foreach y within 1 ... n, - x within 1 ... n; + 0 when not y = n / 2 + else + 1 + foreach y within 1 ... n, + x within 1 ... n; diff --git a/Task/Conways-Game-of-Life/SequenceL/conways-game-of-life-2.sequencel b/Task/Conways-Game-of-Life/SequenceL/conways-game-of-life-2.sequencel index 5c10981d9f..54e33fabc0 100644 --- a/Task/Conways-Game-of-Life/SequenceL/conways-game-of-life-2.sequencel +++ b/Task/Conways-Game-of-Life/SequenceL/conways-game-of-life-2.sequencel @@ -17,150 +17,150 @@ std::string get_file_contents(const char*); int main(int argc, char ** argv) { - int cores = 0; - int maxSize = 700; + int cores = 0; + int maxSize = 700; - int drawSkip = 1; - int drawWait = 0; + int drawSkip = 1; + int drawWait = 0; - string inputFile = "test"; + string inputFile = "test"; - if(argc > 1) - { - inputFile = argv[1]; - } - if(argc > 2) - { - cores = atoi(argv[2]); - } + if(argc > 1) + { + inputFile = argv[1]; + } + if(argc > 2) + { + cores = atoi(argv[2]); + } - if(argc > 3) - { - maxSize = atoi(argv[3]); - } + if(argc > 3) + { + maxSize = atoi(argv[3]); + } - if(argc > 4) - { - drawSkip = atoi(argv[4]); + if(argc > 4) + { + drawSkip = atoi(argv[4]); - if(drawSkip < 0) - { - drawWait = abs(drawSkip); - drawSkip = 1; - } - } + if(drawSkip < 0) + { + drawWait = abs(drawSkip); + drawSkip = 1; + } + } - sl_init(cores); + sl_init(cores); - SLTimer drawTimer; + SLTimer drawTimer; - sprintf(titleBuffer, "Conway's Game of Life in SequenceL: %d Cores", cores); + sprintf(titleBuffer, "Conway's Game of Life in SequenceL: %d Cores", cores); - int width = 0; - int height = 0; + int width = 0; + int height = 0; - //Read input file-------------- - Sequence> initialGrid; + //Read input file-------------- + Sequence> initialGrid; - if(inputFile != "test") - { - stringstream ss(get_file_contents(inputFile.c_str())); - string stringItem; - vector elems; - char delim = ','; + if(inputFile != "test") + { + stringstream ss(get_file_contents(inputFile.c_str())); + string stringItem; + vector elems; + char delim = ','; - getline(ss, stringItem, delim); - width = atoi(stringItem.c_str()); - getline(ss, stringItem, delim); - height = atoi(stringItem.c_str()); + getline(ss, stringItem, delim); + width = atoi(stringItem.c_str()); + getline(ss, stringItem, delim); + height = atoi(stringItem.c_str()); - while(getline(ss, stringItem, delim)) - { - elems.push_back(atoi(stringItem.c_str())); - } + while(getline(ss, stringItem, delim)) + { + elems.push_back(atoi(stringItem.c_str())); + } - //Sequence Pointer Constructor---- - int gridDims[] = {height, width, 0}; - Sequence> tempGrid( (void*)&elems[0], gridDims); - initialGrid.hard_copy(tempGrid, 0); - //----------------------------- - } - else - { - width = maxSize; - height = maxSize; - sl_stressTestInput(maxSize, cores, initialGrid); - } - //-------- + //Sequence Pointer Constructor---- + int gridDims[] = {height, width, 0}; + Sequence> tempGrid( (void*)&elems[0], gridDims); + initialGrid.hard_copy(tempGrid, 0); + //----------------------------- + } + else + { + width = maxSize; + height = maxSize; + sl_stressTestInput(maxSize, cores, initialGrid); + } + //-------- - Sequence> result; + Sequence> result; - const unsigned char black[] = {0}; + const unsigned char black[] = {0}; - CImg visu(width * 4, height * 4, 1, 1, 0); - CImgDisplay draw_disp(visu, titleBuffer); - cout << "Conway's Game of Life in SequenceL" << endl << "Cores: " << cores << endl; + CImg visu(width * 4, height * 4, 1, 1, 0); + CImgDisplay draw_disp(visu, titleBuffer); + cout << "Conway's Game of Life in SequenceL" << endl << "Cores: " << cores << endl; - int generations = 0; - double compTime = 0; - double drawTime = 0; - SLTimer t; + int generations = 0; + double compTime = 0; + double drawTime = 0; + SLTimer t; - while(!draw_disp.is_closed()) - { - t.start(); - sl_life(initialGrid, cores, result); - generations++; - initialGrid.hard_copy(result, 0); - t.stop(); - compTime += t.getTime(); + while(!draw_disp.is_closed()) + { + t.start(); + sl_life(initialGrid, cores, result); + generations++; + initialGrid.hard_copy(result, 0); + t.stop(); + compTime += t.getTime(); - drawTimer.start(); + drawTimer.start(); - if(drawSkip > 0 && generations % drawSkip == 0) - { + if(drawSkip > 0 && generations % drawSkip == 0) + { - visu.fill(255); + visu.fill(255); - for(int i = 1; i <= result.size(); i++) - { - for(int j = 1; j <= result[i].size(); j++) - { - if(result[i][j] == 1) visu.draw_circle((j-1) * 4, (i - 1) * 4, 2, black, 1); - } - } + for(int i = 1; i <= result.size(); i++) + { + for(int j = 1; j <= result[i].size(); j++) + { + if(result[i][j] == 1) visu.draw_circle((j-1) * 4, (i - 1) * 4, 2, black, 1); + } + } - visu.display(draw_disp); + visu.display(draw_disp); - int drawWidth = maxSize; - int drawHeight = maxSize; + int drawWidth = maxSize; + int drawHeight = maxSize; - if(width < height) - { - drawWidth = ((double)drawHeight * ((double)width / (double)height)); - } - else - { - drawHeight = ((double)drawWidth * ((double)height / (double)width)); - } + if(width < height) + { + drawWidth = ((double)drawHeight * ((double)width / (double)height)); + } + else + { + drawHeight = ((double)drawWidth * ((double)height / (double)width)); + } - draw_disp.resize(drawWidth, drawHeight, false); + draw_disp.resize(drawWidth, drawHeight, false); - draw_disp.wait(drawWait); - drawTimer.stop(); - drawTime += drawTimer.getTime(); - } - } + draw_disp.wait(drawWait); + drawTimer.stop(); + drawTime += drawTimer.getTime(); + } + } - cout << "Total Generations: " << generations << endl; + cout << "Total Generations: " << generations << endl; - cout << "Average Compute Time: " << compTime / generations << " seconds" << endl; + cout << "Average Compute Time: " << compTime / generations << " seconds" << endl; - cout << "Average Draw Time: " << drawTime / generations << " seconds" << endl; + cout << "Average Draw Time: " << drawTime / generations << " seconds" << endl; - sl_done(); + sl_done(); - return 0; + return 0; } std::string get_file_contents(const char *filename) diff --git a/Task/Conways-Game-of-Life/Smalltalk/conways-game-of-life-2.st b/Task/Conways-Game-of-Life/Smalltalk/conways-game-of-life-2.st index 2819d03b89..444c414241 100644 --- a/Task/Conways-Game-of-Life/Smalltalk/conways-game-of-life-2.st +++ b/Task/Conways-Game-of-Life/Smalltalk/conways-game-of-life-2.st @@ -9,7 +9,7 @@ GameOfLife class>>withAliveCells: aCollectionOfCells ofSize: aBoardSize ^self new initializeWithAliveCells: aCollectionOfCells ofSize: aBoardSize GameOfLife class>>assertAll: aCollectionOfAliveCells areInside: aSize - | origin | + | origin | origin := 0@0. aCollectionOfAliveCells do: [:aCell | (aCell between: origin and: aSize) ifFalse: [ self error: 'Cell ', aCell printString,' out of range' ]] diff --git a/Task/Conways-Game-of-Life/Smalltalk/conways-game-of-life-4.st b/Task/Conways-Game-of-Life/Smalltalk/conways-game-of-life-4.st index dcdbda1181..aec636a5e2 100644 --- a/Task/Conways-Game-of-Life/Smalltalk/conways-game-of-life-4.st +++ b/Task/Conways-Game-of-Life/Smalltalk/conways-game-of-life-4.st @@ -12,7 +12,7 @@ GameOfLifeView class>>openFor: aGameOfLife GameOfLifeView class>>blinker ^GameOfLife withAliveCells: { 4@2. 4@3. 4@4. 3@3. 4@3. 5@3 } ofSize: 10@10 - + GameOfLifeView class>>toad ^GameOfLife withAliveCells: { 2@4. 3@4. 4@4. 3@3. 4@3. 5@3 } ofSize: 10@10 @@ -20,7 +20,7 @@ GameOfLifeView class>>openBlinker ^self openFor: self blinker GameOfLifeView class>>openToad - ^self openFor: self toad + ^self openFor: self toad initializeFor: aGameOfLife game := aGameOfLife. diff --git a/Task/Conways-Game-of-Life/Uiua/conways-game-of-life.uiua b/Task/Conways-Game-of-Life/Uiua/conways-game-of-life.uiua new file mode 100644 index 0000000000..fe9d89fede --- /dev/null +++ b/Task/Conways-Game-of-Life/Uiua/conways-game-of-life.uiua @@ -0,0 +1,4 @@ +Life ← ↥⊙↧∩=3⊃⋅∘⊙∘2⊸˜-/+≡↻♭₂-1⇡3_3⊸¤ +⁅×0.6 ≡₀⋅⚂ ↯⟜⊚ 50 # Init +⇌◌⍥(⟜⊂Life)300⟜¤ # Run +≡(▽⟜≡▽4) # Upscale diff --git a/Task/Conways-Game-of-Life/V-(Vlang)/conways-game-of-life.v b/Task/Conways-Game-of-Life/V-(Vlang)/conways-game-of-life.v index 5406961503..bb952499d4 100644 --- a/Task/Conways-Game-of-Life/V-(Vlang)/conways-game-of-life.v +++ b/Task/Conways-Game-of-Life/V-(Vlang)/conways-game-of-life.v @@ -4,95 +4,95 @@ import time struct Field { mut: - s [][]bool - w int - h int + s [][]bool + w int + h int } fn new_field(w int, h int) Field { - s := [][]bool{len: h, init: []bool{len: w}} - return Field{s, w, h} + s := [][]bool{len: h, init: []bool{len: w}} + return Field{s, w, h} } fn (mut f Field) set(x int, y int, b bool) { - f.s[y][x] = b + f.s[y][x] = b } fn (f Field) next(x int, y int) bool { - mut on := 0 - for i := -1; i <= 1; i++ { - for j := -1; j <= 1; j++ { - if f.state(x+i, y+j) && !(j == 0 && i == 0) { - on++ - } - } - } - return on == 3 || (on == 2 && f.state(x, y)) + mut on := 0 + for i := -1; i <= 1; i++ { + for j := -1; j <= 1; j++ { + if f.state(x+i, y+j) && !(j == 0 && i == 0) { + on++ + } + } + } + return on == 3 || (on == 2 && f.state(x, y)) } fn (f Field) state(xx int, yy int) bool { - mut x, mut y := xx, yy - for y < 0 { - y += f.h - } - for x < 0 { - x += f.w - } - return f.s[y%f.h][x%f.w] + mut x, mut y := xx, yy + for y < 0 { + y += f.h + } + for x < 0 { + x += f.w + } + return f.s[y%f.h][x%f.w] } struct Life { mut: - w int - h int - a Field - b Field + w int + h int + a Field + b Field } fn new_life(w int, h int) Life { - mut a := new_field(w, h) - for _ in 0..(w * h / 2) { - a.set(rand.intn(w) or {0}, rand.intn(h) or {0}, true) - } - return Life{ - a: a, - b: new_field(w, h), - w: w - h: h, - } + mut a := new_field(w, h) + for _ in 0..(w * h / 2) { + a.set(rand.intn(w) or {0}, rand.intn(h) or {0}, true) + } + return Life{ + a: a, + b: new_field(w, h), + w: w + h: h, + } } fn (mut l Life) step() { - for y in 0..l.h { - for x in 0.. l.w { - l.b.set(x, y, l.a.next(x, y)) - } - } - l.a, l.b = l.b, l.a + for y in 0..l.h { + for x in 0.. l.w { + l.b.set(x, y, l.a.next(x, y)) + } + } + l.a, l.b = l.b, l.a } fn (l Life) str() string { - mut buf := strings.new_builder(128) - for y in 0..l.h { - for x in 0..l.w { - mut b := ' ' - if l.a.state(x, y) { - b = '*' - } - buf.write_string(b) - } - buf.write_string('\n') - } - return buf.str() + mut buf := strings.new_builder(128) + for y in 0..l.h { + for x in 0..l.w { + mut b := ' ' + if l.a.state(x, y) { + b = '*' + } + buf.write_string(b) + } + buf.write_string('\n') + } + return buf.str() } fn main() { - mut l := new_life(80, 15) - for i := 0; i < 300; i++ { - l.step() - //println("------------------------------------------------") - print('\x0c') - println(l) - time.sleep(time.second / 30) - } + mut l := new_life(80, 15) + for i := 0; i < 300; i++ { + l.step() + //println("------------------------------------------------") + print('\x0c') + println(l) + time.sleep(time.second / 30) + } } diff --git a/Task/Conways-Game-of-Life/VBScript/conways-game-of-life-1.vb b/Task/Conways-Game-of-Life/VBScript/conways-game-of-life-1.vb deleted file mode 100644 index 3f97b566c7..0000000000 --- a/Task/Conways-Game-of-Life/VBScript/conways-game-of-life-1.vb +++ /dev/null @@ -1,85 +0,0 @@ -option explicit -const tlcr=3, tlcc=3 -const maxdim=15 - -dim a(15,15) -dim b(15,15) -dim ans0:ans0=chr(27)&"[" -dim gen,n - -erase a -'glider -a(0,1)=true:a(1,2)=true:a(2,0)=true:a(2,1)=true:a(2,2)=true -'blinker -a(3,13)=true:a(4,13)=true:a(5,13)=true -'beacon -a(11,1)=true:a(11,2)=true: a(12,1)=true:a(12,2)=true -a(13,3)=true:a(13,4)=true: a(14,3)=true:a(14,4)=true - -gen=0 -doframe - -do - display - wscript.sleep(100) - n=newgen -loop until n=0 -display - -sub cls() wscript.StdOut.Write ans0 &"2J"&ans0 &"?25l":end sub 'hide cursor too -sub toxy(r,c,s) wscript.StdOut.Write ans0 & r & ";" & c & "f" & s :end sub -function iif(a,b,c) if a then iif=b else iif=c end if :end function - -sub doframe - dim r,c,s - const frame="@" - cls - toxy 1,tlcc-1, "Conway's Game of Life" - toxy tlcr-1,tlcc-1,string(maxdim+3,frame) - s=frame&space(maxdim+1)&frame - for r=0 to maxdim - toxy tlcr+r,tlcc-1,s - next - toxy tlcr+maxdim+1,tlcc-1,string(maxdim+3,frame) -end sub - -sub display -dim r,c -const pix="#" -for r=0 to maxdim - for c=0 to maxdim - toxy tlcr+r,tlcc+c,iif (a(r,c),pix," ") - next -next -toxy tlcr+maxdim+2,tlcc-1,gen & " " & n -toxy tlcr+maxdim+3,tlcc-1,"" -gen=gen+1 -end sub - -function newgen - dim r,c,cnt,cp,cm,rp,rm - for r=0 to maxdim - for c=0 to maxdim - cp=(c+1) and maxdim 'wrap around - cm=(c-1) and maxdim - rp=(r+1) and maxdim - rm=(r-1) and maxdim - cnt=0 - cnt=- a(rp,cp) - a(rp,c) - a(rp,cm) 'true =-1 - cnt=cnt- a(r,cp)- a(r,cm) - cnt=cnt- a(rm,cp)- a(rm,c) - a(rm,cm) - - if a(r,c) then - b(r,c)=iif (cnt=2 or cnt=3,true,false) - else - b(r,c)=iif (cnt=3,true,false) - end if - next - next - for r=0 to maxdim - for c=0 to maxdim - a(r,c)=b(r,c) - newgen=newgen- b(r,c) - next - next -end function diff --git a/Task/Conways-Game-of-Life/VBScript/conways-game-of-life-1.vbs b/Task/Conways-Game-of-Life/VBScript/conways-game-of-life-1.vbs new file mode 100644 index 0000000000..66315d235d --- /dev/null +++ b/Task/Conways-Game-of-Life/VBScript/conways-game-of-life-1.vbs @@ -0,0 +1,85 @@ +option explicit +const tlcr=3, tlcc=3 +const maxdim=15 + +dim a(15,15) +dim b(15,15) +dim ans0:ans0=chr(27)&"[" +dim gen,n + +erase a +'glider +a(0,1)=true:a(1,2)=true:a(2,0)=true:a(2,1)=true:a(2,2)=true +'blinker +a(3,13)=true:a(4,13)=true:a(5,13)=true +'beacon +a(11,1)=true:a(11,2)=true: a(12,1)=true:a(12,2)=true +a(13,3)=true:a(13,4)=true: a(14,3)=true:a(14,4)=true + +gen=0 +doframe + +do + display + wscript.sleep(100) + n=newgen +loop until n=0 +display + +sub cls() wscript.StdOut.Write ans0 &"2J"&ans0 &"?25l":end sub 'hide cursor too +sub toxy(r,c,s) wscript.StdOut.Write ans0 & r & ";" & c & "f" & s :end sub +function iif(a,b,c) if a then iif=b else iif=c end if :end function + +sub doframe + dim r,c,s + const frame="@" + cls + toxy 1,tlcc-1, "Conway's Game of Life" + toxy tlcr-1,tlcc-1,string(maxdim+3,frame) + s=frame&space(maxdim+1)&frame + for r=0 to maxdim + toxy tlcr+r,tlcc-1,s + next + toxy tlcr+maxdim+1,tlcc-1,string(maxdim+3,frame) +end sub + +sub display +dim r,c +const pix="#" +for r=0 to maxdim + for c=0 to maxdim + toxy tlcr+r,tlcc+c,iif (a(r,c),pix," ") + next +next +toxy tlcr+maxdim+2,tlcc-1,gen & " " & n +toxy tlcr+maxdim+3,tlcc-1,"" +gen=gen+1 +end sub + +function newgen + dim r,c,cnt,cp,cm,rp,rm + for r=0 to maxdim + for c=0 to maxdim + cp=(c+1) and maxdim 'wrap around + cm=(c-1) and maxdim + rp=(r+1) and maxdim + rm=(r-1) and maxdim + cnt=0 + cnt=- a(rp,cp) - a(rp,c) - a(rp,cm) 'true =-1 + cnt=cnt- a(r,cp)- a(r,cm) + cnt=cnt- a(rm,cp)- a(rm,c) - a(rm,cm) + + if a(r,c) then + b(r,c)=iif (cnt=2 or cnt=3,true,false) + else + b(r,c)=iif (cnt=3,true,false) + end if + next + next + for r=0 to maxdim + for c=0 to maxdim + a(r,c)=b(r,c) + newgen=newgen- b(r,c) + next + next +end function diff --git a/Task/Conways-Game-of-Life/VBScript/conways-game-of-life-2.vb b/Task/Conways-Game-of-Life/VBScript/conways-game-of-life-2.vbs similarity index 100% rename from Task/Conways-Game-of-Life/VBScript/conways-game-of-life-2.vb rename to Task/Conways-Game-of-Life/VBScript/conways-game-of-life-2.vbs diff --git a/Task/Conways-Game-of-Life/Vedit-macro-language/conways-game-of-life.vedit b/Task/Conways-Game-of-Life/Vedit-macro-language/conways-game-of-life.vedit index c1f5784b3a..069dd75cfb 100644 --- a/Task/Conways-Game-of-Life/Vedit-macro-language/conways-game-of-life.vedit +++ b/Task/Conways-Game-of-Life/Vedit-macro-language/conways-game-of-life.vedit @@ -3,7 +3,7 @@ IT(".O.") IN IT(".O.") IN IT(".O.") -#9 = 2 // number of generations to calculate +#9 = 2 // number of generations to calculate #10 = Cur_Line #11 = Cur_Col-1 for (#2 = 1; #2 <= #9; #2++) { @@ -20,24 +20,24 @@ Return :calculate: Goto_Line(2) While (At_EOF == 0) { - Search("|A",ERRBREAK) // find next living cell + Search("|A",ERRBREAK) // find next living cell #3 = Cur_Line #4 = #7 = #8 = Cur_Col - if (#4 > 1) { // increment cell at left + if (#4 > 1) { // increment cell at left #7 = #4-1 Goto_Col(#7) Ins_Char(Cur_Char+1,OVERWRITE) } - if (#4 < #11) { // increment cell at right + if (#4 < #11) { // increment cell at right #8 = #4+1 Goto_Col(#8) Ins_Char(Cur_Char+1,OVERWRITE) } - if (#3 > 2) { // increment 3 cells above + if (#3 > 2) { // increment 3 cells above Goto_Line(#3-1) Call("inc_3") } - if (#3 < #10) { // increment 3 cells below + if (#3 < #10) { // increment 3 cells below Goto_Line(#3+1) Call("inc_3") } @@ -45,7 +45,7 @@ While (At_EOF == 0) { Goto_Col(#4+1) } -Replace("[1QR]", "O", REGEXP+BEGIN+ALL) // these cells alive +Replace("[1QR]", "O", REGEXP+BEGIN+ALL) // these cells alive Replace("[/-7P-X]", ".", REGEXP+BEGIN+ALL) // these cells dead Return diff --git a/Task/Conways-Game-of-Life/YAMLScript/conways-game-of-life.ys b/Task/Conways-Game-of-Life/YAMLScript/conways-game-of-life.ys new file mode 100644 index 0000000000..ae2f9357d5 --- /dev/null +++ b/Task/Conways-Game-of-Life/YAMLScript/conways-game-of-life.ys @@ -0,0 +1,42 @@ +!YS-v0 + +glider =: \{[1 0] [2 1] [0 2] [1 2] [2 2]} +blinker =: \{[1 2] [2 2] [3 2]} + +defn main(): + game-of-life 10 40: glider + +defn game-of-life(size steps cells): + loop s steps, cells cells: + shell:: clear + print-world: cells size + sleep: 0.25 + when 0 < s: + recur s.--: step(cells) + +defn print-world: + (cells): + print-world: cells 10 + + (cells size): + each y (0 .. size): + row =: + join: + for x (0 .. size): + cells([x y]).if('* ' ' ') + say: "| $row|" + +defn step(cells): + set: + ? for [cell count] + neighborhood.mapcat(cells):frequencies + :when ((3 == count) || + ((2 == count) && + cell.in?(cells))) + : cell + +defn neighborhood([x y]): + ? for dx [-1 0 1] + dy [-1 0 1] + :when [dx dy].ne([0 0]) + : vector: (x + dx) (y + dy) diff --git a/Task/Conways-Game-of-Life/Zig/conways-game-of-life.zig b/Task/Conways-Game-of-Life/Zig/conways-game-of-life.zig new file mode 100644 index 0000000000..524afe1ece --- /dev/null +++ b/Task/Conways-Game-of-Life/Zig/conways-game-of-life.zig @@ -0,0 +1,85 @@ +const std = @import("std"); +const mem = std.mem; + +pub fn main() !void { + // ---------------------------- pseudo random number generator + var prng = std.Random.DefaultPrng.init(blk: { + var seed: u64 = undefined; + std.posix.getrandom(mem.asBytes(&seed)) catch unreachable; + break :blk seed; + }); + const random = prng.random(); + // ---------------------------------------------------------- + const stdout = std.io.getStdOut(); + var bw = std.io.bufferedWriter(stdout.writer()); + const writer = bw.writer(); + // ---------------------------------------------------------- + var life = Life(80, 15).init(random); + for (0..300) |_| { + life.step(); + try writer.writeByte('\x0c'); + try writer.print("{}", .{life}); + try bw.flush(); + std.time.sleep(comptime (1_000_000_000 / 30)); // 1/30th second + } +} +fn Life(comptime w: usize, comptime h: usize) type { + return struct { + const Self = @This(); + a: Field(w, h), + b: Field(w, h), + + fn init(random: std.Random) Self { + var life = Self{ + .a = Field(w, h).init(), + .b = Field(w, h).init(), + }; + for (0..w * h / 2) |_| { + const x = random.uintLessThan(usize, w); + const y = random.uintLessThan(usize, h); + life.a.set(x, y, true); + } + return life; + } + fn step(self: *Self) void { + for (0..h) |y| + for (0..w) |x| + self.b.set(x, y, self.a.next(x, y)); + mem.swap(Field(w, h), &self.a, &self.b); + } + pub fn format(self: *const Self, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void { + for (0..h) |y| { + for (0..w) |x| + try writer.writeByte(if (self.a.state(x, y)) '*' else ' '); + try writer.writeByte('\n'); + } + } + }; +} +fn Field(comptime w: usize, comptime h: usize) type { + return struct { + const Self = @This(); + s: std.StaticBitSet(w * h), + + fn init() Self { + return .{ .s = std.StaticBitSet(w * h).initEmpty() }; + } + fn set(self: *Self, x: usize, y: usize, b: bool) void { + self.s.setValue(y * w + x, b); + } + fn next(self: *const Self, x_: usize, y_: usize) bool { + var on: usize = 0; + // Use wraparound arithmetic, i.e. -% + inline for ([3]usize{ x_ -% 1, x_, x_ + 1 }) |x| + inline for ([3]usize{ y_ -% 1, y_, y_ + 1 }) |y| + if (self.state(x, y)) { + on += 1; + }; + return on == 3 or on == 2 and self.state(x_, y_); + } + fn state(self: *const Self, x: usize, y: usize) bool { + if (x >= w or y >= h) return false; + return self.s.isSet(y * w + x); + } + }; +} diff --git a/Task/Conways-Game-of-Life/Zkl/conways-game-of-life-1.zkl b/Task/Conways-Game-of-Life/Zkl/conways-game-of-life-1.zkl index da3f4350f4..73b0d9723d 100644 --- a/Task/Conways-Game-of-Life/Zkl/conways-game-of-life-1.zkl +++ b/Task/Conways-Game-of-Life/Zkl/conways-game-of-life-1.zkl @@ -3,7 +3,7 @@ class Life{ var N=n, cells=Data(n*n), tmp=Data(n*n), ds=T(T(-1,-1),T(-1,0),T(-1,1), T(0,-1),T(0,1), T(1,-1),T(1,0),T(1,1)); icells:=vm.arglist[1,*]; - (N*N).pump(Void,cells.append.fpM("1-",0)); // clear board + (N*N).pump(Void,cells.append.fpM("1-",0)); // clear board icells.pump(Void,Void.Read,fcn(row,col){ cells[row*N+col]=1 }); } fcn get(row,col){ diff --git a/Task/Conways-Game-of-Life/Zkl/conways-game-of-life-2.zkl b/Task/Conways-Game-of-Life/Zkl/conways-game-of-life-2.zkl index 7d59e7b5c2..ca7561ab4d 100644 --- a/Task/Conways-Game-of-Life/Zkl/conways-game-of-life-2.zkl +++ b/Task/Conways-Game-of-Life/Zkl/conways-game-of-life-2.zkl @@ -1,4 +1,4 @@ -cells:=Life(4, 0,1, 1,1, 2,1); // blinker +cells:=Life(4, 0,1, 1,1, 2,1); // blinker do(3){ cells.println("="*4); cells.cycle(); } cells:=Life(30, 0,1, 1,2, 2,0, 2,1, 2,2); // glider diff --git a/Task/Copy-a-string/68000-Assembly/copy-a-string-2.68000 b/Task/Copy-a-string/68000-Assembly/copy-a-string-2.68000 index 7f91645c39..10041191cb 100644 --- a/Task/Copy-a-string/68000-Assembly/copy-a-string-2.68000 +++ b/Task/Copy-a-string/68000-Assembly/copy-a-string-2.68000 @@ -7,10 +7,7 @@ LEA myString,A3 LEA StringRam,A4 CopyString: -MOVE.B (A3)+,D0 -MOVE.B D0,(A4)+ ;we could have used "MOVE.B (A3)+,(A4)+" but this makes it easier to check for the terminator. -BEQ Terminated -BRA CopyString +MOVE.B (A3)+,(A4)+ ;Copy one byte. +BNE CopyString ;Not zero, do more bytes. -Terminated: ;the null terminator is already stored along with the string itself, so we are done. ;program ends here. diff --git a/Task/Copy-a-string/ALGOL-W/copy-a-string.alg b/Task/Copy-a-string/ALGOL-W/copy-a-string.alg deleted file mode 100644 index 24bae16956..0000000000 --- a/Task/Copy-a-string/ALGOL-W/copy-a-string.alg +++ /dev/null @@ -1,9 +0,0 @@ -begin - % strings are (fixed length) values in algol W. Assignment makes a copy % - string(10) a, copyOfA; - a := "some text"; - copyOfA := a; - % assignment to a will not change copyOfA % - a := "new value"; - write( a, copyOfA ) -end. diff --git a/Task/Copy-a-string/Ada/copy-a-string-1.ada b/Task/Copy-a-string/Ada/copy-a-string-1.adb similarity index 100% rename from Task/Copy-a-string/Ada/copy-a-string-1.ada rename to Task/Copy-a-string/Ada/copy-a-string-1.adb diff --git a/Task/Copy-a-string/Ada/copy-a-string-2.ada b/Task/Copy-a-string/Ada/copy-a-string-2.adb similarity index 100% rename from Task/Copy-a-string/Ada/copy-a-string-2.ada rename to Task/Copy-a-string/Ada/copy-a-string-2.adb diff --git a/Task/Copy-a-string/Ada/copy-a-string-3.ada b/Task/Copy-a-string/Ada/copy-a-string-3.adb similarity index 100% rename from Task/Copy-a-string/Ada/copy-a-string-3.ada rename to Task/Copy-a-string/Ada/copy-a-string-3.adb diff --git a/Task/Copy-a-string/Ada/copy-a-string-4.ada b/Task/Copy-a-string/Ada/copy-a-string-4.adb similarity index 100% rename from Task/Copy-a-string/Ada/copy-a-string-4.ada rename to Task/Copy-a-string/Ada/copy-a-string-4.adb diff --git a/Task/Copy-a-string/BaCon/copy-a-string-1.bacon b/Task/Copy-a-string/Applesoft-BASIC/copy-a-string-4.basic similarity index 100% rename from Task/Copy-a-string/BaCon/copy-a-string-1.bacon rename to Task/Copy-a-string/Applesoft-BASIC/copy-a-string-4.basic diff --git a/Task/Copy-a-string/BaCon/copy-a-string-2.bacon b/Task/Copy-a-string/Applesoft-BASIC/copy-a-string-5.basic similarity index 100% rename from Task/Copy-a-string/BaCon/copy-a-string-2.bacon rename to Task/Copy-a-string/Applesoft-BASIC/copy-a-string-5.basic diff --git a/Task/Copy-a-string/ArkScript/copy-a-string.ark b/Task/Copy-a-string/ArkScript/copy-a-string.ark new file mode 100644 index 0000000000..4ceafe0b2d --- /dev/null +++ b/Task/Copy-a-string/ArkScript/copy-a-string.ark @@ -0,0 +1,7 @@ +(mut str "hello world") +(mut copy str) + +(set copy "clone destroyed") + +(print str) +(print copy) diff --git a/Task/Copy-a-string/Arturo/copy-a-string.arturo b/Task/Copy-a-string/Arturo/copy-a-string.arturo index 41cb6efd44..0001140d7d 100644 --- a/Task/Copy-a-string/Arturo/copy-a-string.arturo +++ b/Task/Copy-a-string/Arturo/copy-a-string.arturo @@ -1,4 +1,4 @@ -a: new "Hello" +a: "Hello" b: a ; reference the same string ; changing one string in-place diff --git a/Task/Copy-a-string/AutoIt/copy-a-string.autoit b/Task/Copy-a-string/AutoIt/copy-a-string.au3 similarity index 100% rename from Task/Copy-a-string/AutoIt/copy-a-string.autoit rename to Task/Copy-a-string/AutoIt/copy-a-string.au3 diff --git a/Task/Copy-a-string/Ballerina/copy-a-string.ballerina b/Task/Copy-a-string/Ballerina/copy-a-string.ballerina new file mode 100644 index 0000000000..ed5f916660 --- /dev/null +++ b/Task/Copy-a-string/Ballerina/copy-a-string.ballerina @@ -0,0 +1,7 @@ +import ballerina/io; + +public function main() { + string s = "ballerina"; + string t = s; + io:println(`Are s and t equal? ${t == s}`); +} diff --git a/Task/Copy-a-string/COBOL/copy-a-string.cobol b/Task/Copy-a-string/COBOL/copy-a-string.cob similarity index 100% rename from Task/Copy-a-string/COBOL/copy-a-string.cobol rename to Task/Copy-a-string/COBOL/copy-a-string.cob diff --git a/Task/Copy-a-string/Crystal/copy-a-string.crystal b/Task/Copy-a-string/Crystal/copy-a-string.cr similarity index 100% rename from Task/Copy-a-string/Crystal/copy-a-string.crystal rename to Task/Copy-a-string/Crystal/copy-a-string.cr diff --git a/Task/Copy-a-string/Delphi/copy-a-string.delphi b/Task/Copy-a-string/Delphi/copy-a-string.pas similarity index 100% rename from Task/Copy-a-string/Delphi/copy-a-string.delphi rename to Task/Copy-a-string/Delphi/copy-a-string.pas diff --git a/Task/Copy-a-string/DuckDB/copy-a-string.duckdb b/Task/Copy-a-string/DuckDB/copy-a-string.duckdb new file mode 100644 index 0000000000..b039bd2ade --- /dev/null +++ b/Task/Copy-a-string/DuckDB/copy-a-string.duckdb @@ -0,0 +1,40 @@ +D create or replace table t as (select 'This is a string' as s); + +D from t; +┌──────────────────┐ +│ s │ +│ varchar │ +├──────────────────┤ +│ This is a string │ +└──────────────────┘ + +# Now make two copies. +D create or replace table tt as (select s as s1, s as s2 from t); + +D from tt; +┌──────────────────┬──────────────────┐ +│ s1 │ s2 │ +│ varchar │ varchar │ +├──────────────────┼──────────────────┤ +│ This is a string │ This is a string │ +└──────────────────┴──────────────────┘ + +# Change s2 and then verify that s1 is unaltered +D UPDATE tt SET s2 = s2[1]; + +D from tt; +┌──────────────────┬─────────┐ +│ s1 │ s2 │ +│ varchar │ varchar │ +├──────────────────┼─────────┤ +│ This is a string │ T │ +└──────────────────┴─────────┘ + +# Check that s and s1 are also still equal +D select s = s1 from t positional join tt; +┌──────────┐ +│ (s = s1) │ +│ boolean │ +├──────────┤ +│ true │ +└──────────┘ diff --git a/Task/Copy-a-string/EMal/copy-a-string.emal b/Task/Copy-a-string/EMal/copy-a-string.emal index c7d403d343..81e78bf2e8 100644 --- a/Task/Copy-a-string/EMal/copy-a-string.emal +++ b/Task/Copy-a-string/EMal/copy-a-string.emal @@ -1,11 +1,10 @@ -text original = "Yellow world" -text ref = original # copying the reference -text copied = *original # copying the content -original[0] = "H" # texts are indexable and mutable -original[5] = "," +^|in EMal strings are mutable|^ +text original ← "Yellow world" +text ref ← original # copying the reference +text copied ← *original # copying the content +original[0] ← "H" # texts are indexable and mutable +original[5] ← "," ref.append("!") # texts are coercible and growable copied += "?" -^| - | original == ref == "Hello, world!" - | copied == "Yellow world?" - |^ +writeLine(original æ ref and original æ "Hello, world!") +writeLine(copied æ "Yellow world?") diff --git a/Task/Copy-a-string/EasyLang/copy-a-string.easy b/Task/Copy-a-string/EasyLang/copy-a-string.easy index dbe2fe3be1..17fa4c005b 100644 --- a/Task/Copy-a-string/EasyLang/copy-a-string.easy +++ b/Task/Copy-a-string/EasyLang/copy-a-string.easy @@ -1,3 +1,5 @@ a$ = "hello" b$ = a$ +a$ &= " a" +print a$ print b$ diff --git a/Task/Copy-a-string/Ed/copy-a-string.ed b/Task/Copy-a-string/Ed/copy-a-string.ed new file mode 100644 index 0000000000..a2732d422d --- /dev/null +++ b/Task/Copy-a-string/Ed/copy-a-string.ed @@ -0,0 +1 @@ +,t diff --git a/Task/Copy-a-string/Elixir/copy-a-string.elixir b/Task/Copy-a-string/Elixir/copy-a-string.ex similarity index 100% rename from Task/Copy-a-string/Elixir/copy-a-string.elixir rename to Task/Copy-a-string/Elixir/copy-a-string.ex diff --git a/Task/Copy-a-string/Emacs-Lisp/copy-a-string.l b/Task/Copy-a-string/Emacs-Lisp/copy-a-string.el similarity index 100% rename from Task/Copy-a-string/Emacs-Lisp/copy-a-string.l rename to Task/Copy-a-string/Emacs-Lisp/copy-a-string.el diff --git a/Task/Copy-a-string/Euphoria/copy-a-string.euphoria b/Task/Copy-a-string/Euphoria/copy-a-string.eu similarity index 100% rename from Task/Copy-a-string/Euphoria/copy-a-string.euphoria rename to Task/Copy-a-string/Euphoria/copy-a-string.eu diff --git a/Task/Copy-a-string/Extended-Color-BASIC/copy-a-string.basic b/Task/Copy-a-string/Extended-Color-BASIC/copy-a-string.basic new file mode 100644 index 0000000000..5f6527cb7a --- /dev/null +++ b/Task/Copy-a-string/Extended-Color-BASIC/copy-a-string.basic @@ -0,0 +1,7 @@ +10 A$ = "HELLO" +20 REM COPY CONTENTS OF A$ TO B$ +30 B$ = A$ +40 REM CHANGE CONTENTS OF A$ +50 A$ = "WORLD" +60 REM DISPLAY CONTENTS +70 PRINT A$, B$ diff --git a/Task/Copy-a-string/Gleam/copy-a-string.gleam b/Task/Copy-a-string/Gleam/copy-a-string.gleam new file mode 100644 index 0000000000..cfe412774e --- /dev/null +++ b/Task/Copy-a-string/Gleam/copy-a-string.gleam @@ -0,0 +1,2 @@ +let src = "Hello" +let dest = src diff --git a/Task/Copy-a-string/Julia/copy-a-string.julia b/Task/Copy-a-string/Julia/copy-a-string.jl similarity index 100% rename from Task/Copy-a-string/Julia/copy-a-string.julia rename to Task/Copy-a-string/Julia/copy-a-string.jl diff --git a/Task/Copy-a-string/Kotlin/copy-a-string.kotlin b/Task/Copy-a-string/Kotlin/copy-a-string.kts similarity index 100% rename from Task/Copy-a-string/Kotlin/copy-a-string.kotlin rename to Task/Copy-a-string/Kotlin/copy-a-string.kts diff --git a/Task/Copy-a-string/LOLCODE/copy-a-string.lol b/Task/Copy-a-string/LOLCODE/copy-a-string.lol new file mode 100644 index 0000000000..eaa7cf013b --- /dev/null +++ b/Task/Copy-a-string/LOLCODE/copy-a-string.lol @@ -0,0 +1,10 @@ +HAI 1.3 + + I HAS A FRANK ITZ "Hello," + I HAS A PAUL ITZ "World!" + VISIBLE FRANK " " PAUL + + FRANK R PAUL + VISIBLE FRANK " " PAUL + +KTHXBYE diff --git a/Task/Copy-a-string/OCaml/copy-a-string-1.ocaml b/Task/Copy-a-string/OCaml/copy-a-string-1.ml similarity index 100% rename from Task/Copy-a-string/OCaml/copy-a-string-1.ocaml rename to Task/Copy-a-string/OCaml/copy-a-string-1.ml diff --git a/Task/Copy-a-string/OCaml/copy-a-string-2.ocaml b/Task/Copy-a-string/OCaml/copy-a-string-2.ml similarity index 100% rename from Task/Copy-a-string/OCaml/copy-a-string-2.ocaml rename to Task/Copy-a-string/OCaml/copy-a-string-2.ml diff --git a/Task/Copy-a-string/OCaml/copy-a-string-3.ocaml b/Task/Copy-a-string/OCaml/copy-a-string-3.ml similarity index 100% rename from Task/Copy-a-string/OCaml/copy-a-string-3.ocaml rename to Task/Copy-a-string/OCaml/copy-a-string-3.ml diff --git a/Task/Copy-a-string/OCaml/copy-a-string-4.ocaml b/Task/Copy-a-string/OCaml/copy-a-string-4.ml similarity index 100% rename from Task/Copy-a-string/OCaml/copy-a-string-4.ocaml rename to Task/Copy-a-string/OCaml/copy-a-string-4.ml diff --git a/Task/Copy-a-string/OPL/copy-a-string.opl b/Task/Copy-a-string/OPL/copy-a-string.opl new file mode 100644 index 0000000000..db34e40a63 --- /dev/null +++ b/Task/Copy-a-string/OPL/copy-a-string.opl @@ -0,0 +1,8 @@ +PROC main: + LOCAL src$(6),dst$(5) + src$="Hello" + dst$=src$ + src$="world!" + PRINT dst$,src$ + GET +ENDP diff --git a/Task/Copy-a-string/PascalABC.NET/copy-a-string.pas b/Task/Copy-a-string/PascalABC.NET/copy-a-string.pas new file mode 100644 index 0000000000..92afc0925c --- /dev/null +++ b/Task/Copy-a-string/PascalABC.NET/copy-a-string.pas @@ -0,0 +1,4 @@ +begin + var s: string := 'Hello'; + var s1 := s; +end. diff --git a/Task/Copy-a-string/PowerShell/copy-a-string-1.psh b/Task/Copy-a-string/PowerShell/copy-a-string-1.ps1 similarity index 100% rename from Task/Copy-a-string/PowerShell/copy-a-string-1.psh rename to Task/Copy-a-string/PowerShell/copy-a-string-1.ps1 diff --git a/Task/Copy-a-string/PowerShell/copy-a-string-2.psh b/Task/Copy-a-string/PowerShell/copy-a-string-2.ps1 similarity index 100% rename from Task/Copy-a-string/PowerShell/copy-a-string-2.psh rename to Task/Copy-a-string/PowerShell/copy-a-string-2.ps1 diff --git a/Task/Copy-a-string/REXX/copy-a-string.rexx b/Task/Copy-a-string/REXX/copy-a-string.rexx index 6d7223de5c..9db0cf1336 100644 --- a/Task/Copy-a-string/REXX/copy-a-string.rexx +++ b/Task/Copy-a-string/REXX/copy-a-string.rexx @@ -1,2 +1,16 @@ -src = "this is a string" -dst = src +-- 8 Nov 2025 +include Setting + +say 'COPY A STRING' +say version +say +say 'Just assign the string variable to a new one.' +a='This is a string.' +b=a +say a b +c="This is also a string." +d=c +say d c +exit + +include Abend diff --git a/Task/Copy-a-string/REBOL/copy-a-string.rebol b/Task/Copy-a-string/Rebol/copy-a-string.rebol similarity index 98% rename from Task/Copy-a-string/REBOL/copy-a-string.rebol rename to Task/Copy-a-string/Rebol/copy-a-string.rebol index 07ad9d7e8b..02d96fc778 100644 --- a/Task/Copy-a-string/REBOL/copy-a-string.rebol +++ b/Task/Copy-a-string/Rebol/copy-a-string.rebol @@ -1,4 +1,4 @@ -REBOL [ +Rebol [ Title: "String Copy" URL: http://rosettacode.org/wiki/Copy_a_string ] diff --git a/Task/Copy-a-string/Rust/copy-a-string-1.rust b/Task/Copy-a-string/Rust/copy-a-string-1.rs similarity index 100% rename from Task/Copy-a-string/Rust/copy-a-string-1.rust rename to Task/Copy-a-string/Rust/copy-a-string-1.rs diff --git a/Task/Copy-a-string/Rust/copy-a-string-2.rust b/Task/Copy-a-string/Rust/copy-a-string-2.rs similarity index 100% rename from Task/Copy-a-string/Rust/copy-a-string-2.rust rename to Task/Copy-a-string/Rust/copy-a-string-2.rs diff --git a/Task/Copy-a-string/Rye/copy-a-string.rye b/Task/Copy-a-string/Rye/copy-a-string.rye new file mode 100644 index 0000000000..39ec8eac96 --- /dev/null +++ b/Task/Copy-a-string/Rye/copy-a-string.rye @@ -0,0 +1,8 @@ +str:: "Hello" +;Returns [String: Hello] +str2:: str +;Returns [String: Hello] +str:: "World" +;Returns [String: World] +str2 +;Returns [String: Hello] diff --git a/Task/Copy-a-string/S-BASIC/copy-a-string.basic b/Task/Copy-a-string/S-BASIC/copy-a-string.basic new file mode 100644 index 0000000000..81d04da265 --- /dev/null +++ b/Task/Copy-a-string/S-BASIC/copy-a-string.basic @@ -0,0 +1,23 @@ +var original, copy = string +based referenced = string +var strloc = integer + +rem - position referenced string on top of original string +location var strloc = original +base referenced at strloc + +original = "Hello, World" +copy = original + +print "Original : ", original +print "Copy : ", copy +print "Referenced: ", referenced +print + +original = "Goodbye, World" + +print "Original : ", original rem - changed +print "Copy : ", copy rem - unchanged +print "Referenced: ", referenced rem - changed + +end diff --git a/Task/Copy-a-string/Scheme/copy-a-string.ss b/Task/Copy-a-string/Scheme/copy-a-string.scm similarity index 100% rename from Task/Copy-a-string/Scheme/copy-a-string.ss rename to Task/Copy-a-string/Scheme/copy-a-string.scm diff --git a/Task/Copy-a-string/TAV/copy-a-string.tav b/Task/Copy-a-string/TAV/copy-a-string.tav new file mode 100644 index 0000000000..c885d727e1 --- /dev/null +++ b/Task/Copy-a-string/TAV/copy-a-string.tav @@ -0,0 +1,6 @@ + s =: "hello" + print s.Usecount + t =: s \ reference copy + print s.Usecount + u =: string (s _ 'x') clip upto -2 + print (quote u), u.Usecount, s.Usecount diff --git a/Task/Copy-a-string/Tcl/copy-a-string.tcl b/Task/Copy-a-string/Tcl/copy-a-string-1.tcl similarity index 100% rename from Task/Copy-a-string/Tcl/copy-a-string.tcl rename to Task/Copy-a-string/Tcl/copy-a-string-1.tcl diff --git a/Task/Copy-a-string/Tcl/copy-a-string-2.tcl b/Task/Copy-a-string/Tcl/copy-a-string-2.tcl new file mode 100644 index 0000000000..2b6c1980c5 --- /dev/null +++ b/Task/Copy-a-string/Tcl/copy-a-string-2.tcl @@ -0,0 +1,28 @@ +set A "a string" + +set B $A ; # B is a reference to the string + +Set C "$A" ; # a new string is created + +set D "This is $C" ; # the string bound to C is copied into a new string. + + +# the append command is internally optimized +# for adding to the end of a string or list +# as is string index for returning a letter + +# reverse a string +proc reverse {s} { + set len [string length $s] + set r "" + for { set i $len} { $i >= 0} {incr i -1} { + append r [string index $s $i] + } + return $r +} + +set a 12345 + +set b [reverse $a] + +puts stdout "b: $b" diff --git a/Task/Copy-a-string/Tcl/copy-a-string-3.tcl b/Task/Copy-a-string/Tcl/copy-a-string-3.tcl new file mode 100644 index 0000000000..cfbdcf9402 --- /dev/null +++ b/Task/Copy-a-string/Tcl/copy-a-string-3.tcl @@ -0,0 +1,4 @@ +# replace substrings in a string + +set rep [string map {"apple" "orange"} "I like apples."] +puts stdout $rep diff --git a/Task/Copy-a-string/Uiua/copy-a-string.uiua b/Task/Copy-a-string/Uiua/copy-a-string.uiua new file mode 100644 index 0000000000..be6db2389c --- /dev/null +++ b/Task/Copy-a-string/Uiua/copy-a-string.uiua @@ -0,0 +1,2 @@ +."hello" +first diff --git a/Task/Copy-a-string/Uxntal/copy-a-string.uxnatl b/Task/Copy-a-string/Uxntal/copy-a-string.uxnatl new file mode 100644 index 0000000000..0b7adb7b1a --- /dev/null +++ b/Task/Copy-a-string/Uxntal/copy-a-string.uxnatl @@ -0,0 +1,25 @@ +%\n { 0a } %\0 { 00 } + +|18 @Console/write + +|100 + +;str2 ;str1 copy-str +;str2 print-str + +BRK + +@copy/str ( dest* src* -: ) + STH2 + &loop + LDAkr STH2k STAr INC2 LDAkr STHr INC2r ?/loop + POP2 POP2r + JMP2r + +@print/str_ ( str* -: ) + LDAk .Console/write DEO + INC2 @print/str LDAk ?/str_ + POP2 JMP2r + +@str1 "Uxntal \n \0 +@str2 diff --git a/Task/Copy-stdin-to-stdout/Ada/copy-stdin-to-stdout.ada b/Task/Copy-stdin-to-stdout/Ada/copy-stdin-to-stdout.adb similarity index 100% rename from Task/Copy-stdin-to-stdout/Ada/copy-stdin-to-stdout.ada rename to Task/Copy-stdin-to-stdout/Ada/copy-stdin-to-stdout.adb diff --git a/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-1.bat b/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-1.bat new file mode 100644 index 0000000000..c395545bf5 --- /dev/null +++ b/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-1.bat @@ -0,0 +1 @@ +findstr ^^ diff --git a/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-2.bat b/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-2.bat new file mode 100644 index 0000000000..4993fe87a3 --- /dev/null +++ b/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-2.bat @@ -0,0 +1 @@ +findstr "^" diff --git a/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-3.bat b/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-3.bat new file mode 100644 index 0000000000..b4d82224f4 --- /dev/null +++ b/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-3.bat @@ -0,0 +1 @@ +findstr $ diff --git a/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-4.bat b/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-4.bat new file mode 100644 index 0000000000..e45275e17e --- /dev/null +++ b/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-4.bat @@ -0,0 +1 @@ +find/v "" diff --git a/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-5.bat b/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-5.bat new file mode 100644 index 0000000000..ef49dd86a6 --- /dev/null +++ b/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-5.bat @@ -0,0 +1 @@ +more diff --git a/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-6.bat b/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-6.bat new file mode 100644 index 0000000000..6482121afa --- /dev/null +++ b/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-6.bat @@ -0,0 +1 @@ +copy con[:] con[:] diff --git a/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-7.bat b/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-7.bat new file mode 100644 index 0000000000..bd13d6aad4 --- /dev/null +++ b/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-7.bat @@ -0,0 +1 @@ +type con[:] diff --git a/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-8.bat b/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-8.bat new file mode 100644 index 0000000000..2cc3128981 --- /dev/null +++ b/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-8.bat @@ -0,0 +1,2 @@ +@setlocal enabledelayedexpansion +@ -int main(){ - char c; - while ( (c=getchar()) != EOF ){ +int main() { + int c; + while ((c = getchar()) != EOF) { putchar(c); } return 0; diff --git a/Task/Copy-stdin-to-stdout/Crystal/copy-stdin-to-stdout.crystal b/Task/Copy-stdin-to-stdout/Crystal/copy-stdin-to-stdout.cr similarity index 100% rename from Task/Copy-stdin-to-stdout/Crystal/copy-stdin-to-stdout.crystal rename to Task/Copy-stdin-to-stdout/Crystal/copy-stdin-to-stdout.cr diff --git a/Task/Copy-stdin-to-stdout/Fortran/copy-stdin-to-stdout-1.f b/Task/Copy-stdin-to-stdout/Fortran/copy-stdin-to-stdout-1.f new file mode 100644 index 0000000000..892373388e --- /dev/null +++ b/Task/Copy-stdin-to-stdout/Fortran/copy-stdin-to-stdout-1.f @@ -0,0 +1,20 @@ +! Copy stdin to stdout +! tested with GNU Fortran (Ubuntu 15.2.0-4ubuntu4) 15.2.0 on Kubuntu 25.10 +! uses non-standard function fget and gput, both are available in gfortran only. +! ------------------------------------------------------------------------------------------ +! +program cp + +implicit none + +character :: c ! The chcaracter to read +integer :: ios ! IO Status + + +do + ios = fget (c) ! gfortran only + if (ios .ne. 0) exit + call fput(c) ! gfortran only +end do + +end program cp diff --git a/Task/Copy-stdin-to-stdout/Fortran/copy-stdin-to-stdout-2.f b/Task/Copy-stdin-to-stdout/Fortran/copy-stdin-to-stdout-2.f new file mode 100644 index 0000000000..8a0d0d80df --- /dev/null +++ b/Task/Copy-stdin-to-stdout/Fortran/copy-stdin-to-stdout-2.f @@ -0,0 +1,20 @@ +! Copy stdin to stdout +! tested with Intel ifx (IFX) 2025.2.1 20250806 on Kubuntu 25.10 +! +! can also be compiled with gfortran but fails at run-time because it cannot change the access parameter +! ------------------------------------------------------------------------------------------------------- +! +program cp +character :: c +integer:: ios + +open (unit=5, form='unformatted', access='stream', action ='read') +open (unit=6, form='unformatted', access='stream', action ='write') + +do + read (5, iostat=ios) c + if (ios .ne. 0) exit + write (6) c +end do + +end program cp diff --git a/Task/Copy-stdin-to-stdout/FutureBasic/copy-stdin-to-stdout.basic b/Task/Copy-stdin-to-stdout/FutureBasic/copy-stdin-to-stdout.basic new file mode 100644 index 0000000000..277e5331b6 --- /dev/null +++ b/Task/Copy-stdin-to-stdout/FutureBasic/copy-stdin-to-stdout.basic @@ -0,0 +1,13 @@ +// Create file handles for standard input and output +FileHandleRef stdIn = fn FileHandleWithStandardInput +FileHandleRef stdOut = fn FileHandleWithStandardOutput + +// Continuously read from standard input… +while (YES) + CFDataRef availableData = fn FileHandleAvailableData( stdIn ) + if ( fn DataLength( availableData ) == 0 ) + break // End of input + end if + // … and write to standard output + fn FileHandleWriteData( stdOut, availableData, NULL ) +wend diff --git a/Task/Copy-stdin-to-stdout/Icon/copy-stdin-to-stdout.icon b/Task/Copy-stdin-to-stdout/Icon/copy-stdin-to-stdout.icon new file mode 100644 index 0000000000..ceec19034b --- /dev/null +++ b/Task/Copy-stdin-to-stdout/Icon/copy-stdin-to-stdout.icon @@ -0,0 +1,3 @@ +procedure main() + every write(!&input) +end diff --git a/Task/Copy-stdin-to-stdout/Java/copy-stdin-to-stdout.java b/Task/Copy-stdin-to-stdout/Java/copy-stdin-to-stdout-1.java similarity index 100% rename from Task/Copy-stdin-to-stdout/Java/copy-stdin-to-stdout.java rename to Task/Copy-stdin-to-stdout/Java/copy-stdin-to-stdout-1.java diff --git a/Task/Copy-stdin-to-stdout/Java/copy-stdin-to-stdout-2.java b/Task/Copy-stdin-to-stdout/Java/copy-stdin-to-stdout-2.java new file mode 100644 index 0000000000..df4b2adbe3 --- /dev/null +++ b/Task/Copy-stdin-to-stdout/Java/copy-stdin-to-stdout-2.java @@ -0,0 +1,5 @@ +public class CopyStdinToStdout { + public static void main(String[] args) throws java.io.IOException { + System.in.transferTo(System.out); + } +} diff --git a/Task/Copy-stdin-to-stdout/Julia/copy-stdin-to-stdout.julia b/Task/Copy-stdin-to-stdout/Julia/copy-stdin-to-stdout.jl similarity index 100% rename from Task/Copy-stdin-to-stdout/Julia/copy-stdin-to-stdout.julia rename to Task/Copy-stdin-to-stdout/Julia/copy-stdin-to-stdout.jl diff --git a/Task/Copy-stdin-to-stdout/Kotlin/copy-stdin-to-stdout.kotlin b/Task/Copy-stdin-to-stdout/Kotlin/copy-stdin-to-stdout.kts similarity index 100% rename from Task/Copy-stdin-to-stdout/Kotlin/copy-stdin-to-stdout.kotlin rename to Task/Copy-stdin-to-stdout/Kotlin/copy-stdin-to-stdout.kts diff --git a/Task/Copy-stdin-to-stdout/OCaml/copy-stdin-to-stdout.ocaml b/Task/Copy-stdin-to-stdout/OCaml/copy-stdin-to-stdout.ml similarity index 100% rename from Task/Copy-stdin-to-stdout/OCaml/copy-stdin-to-stdout.ocaml rename to Task/Copy-stdin-to-stdout/OCaml/copy-stdin-to-stdout.ml diff --git a/Task/Copy-stdin-to-stdout/Oberon-07/copy-stdin-to-stdout.oberon b/Task/Copy-stdin-to-stdout/Oberon-07/copy-stdin-to-stdout.oberon new file mode 100644 index 0000000000..32bc3ee1b1 --- /dev/null +++ b/Task/Copy-stdin-to-stdout/Oberon-07/copy-stdin-to-stdout.oberon @@ -0,0 +1,10 @@ +MODULE CopyStdinToStdout; + IMPORT In, Out; + VAR c : CHAR; +BEGIN + In.Char( c ); + WHILE In.Done DO + Out.Char( c ); + In.Char( c ) + END +END CopyStdinToStdout. diff --git a/Task/Copy-stdin-to-stdout/Objeck/copy-stdin-to-stdout.objeck b/Task/Copy-stdin-to-stdout/Objeck/copy-stdin-to-stdout.objeck new file mode 100644 index 0000000000..05e460ff31 --- /dev/null +++ b/Task/Copy-stdin-to-stdout/Objeck/copy-stdin-to-stdout.objeck @@ -0,0 +1,9 @@ +class StdInToOut { + function : Main(args : String[]) ~ Nil { + do { + input := System.IO.Console->ReadLine(); + System.IO.Console->PrintLine(input); + } + while(<>input->IsEmpty()); + } +} diff --git a/Task/Copy-stdin-to-stdout/PascalABC.NET/copy-stdin-to-stdout.pas b/Task/Copy-stdin-to-stdout/PascalABC.NET/copy-stdin-to-stdout.pas new file mode 100644 index 0000000000..1b297471d0 --- /dev/null +++ b/Task/Copy-stdin-to-stdout/PascalABC.NET/copy-stdin-to-stdout.pas @@ -0,0 +1,2 @@ +## +Console.OpenStandardInput().CopyTo(Console.OpenStandardOutput()); diff --git a/Task/Copy-stdin-to-stdout/Phix/copy-stdin-to-stdout.phix b/Task/Copy-stdin-to-stdout/Phix/copy-stdin-to-stdout.phix index 6d08a056ab..f1b2eaf38c 100644 --- a/Task/Copy-stdin-to-stdout/Phix/copy-stdin-to-stdout.phix +++ b/Task/Copy-stdin-to-stdout/Phix/copy-stdin-to-stdout.phix @@ -1,8 +1,6 @@ -(notonline)--> - without js - while true do - integer ch = wait_key() - if ch=#1B then exit end if - puts(1,ch) - end while - - with javascript_semantics - procedure factorise(integer n) - sequence res = prime_factors(n,true) - res = join(apply(res,sprint)," x ") - printf(1,"%2d: %s\n",{n,res}) - end procedure +with javascript_semantics +procedure factorise(integer n) + sequence res = prime_factors(n,true,-1) + printf(1,"%2d: %s\n",{n,join(res," x ",fmt:="%d")}) +end procedure - papply(tagset(10)&{2144,1000000000},factorise) - - sequence tests = {{"the three truths","th"}, - {"ababababab","abab"}, - {"ababababab","aba"}, - {"ababababab","ab"}, - {"ababababab","a"}, - {"ababababab",""}} - integer start, count - string test, substring - for i=1 to length(tests) do - start = 1 - count = 0 - {test, substring} = tests[i] - while 1 do - start = match(substring,test,start) - if start=0 then exit end if - start += length(substring) - count += 1 - end while - printf(1,"The string \"%s\" occurs as a non-overlapping substring %d times in \"%s\"\n",{substring,count,test}) - end for -') !Disclaiming responsibility... - INDEEP = 1 !Finishing the content of the header. - CALL HTML("") !Enough of that. - CALL HTML("") !A fresh line seems polite. - INDEEP = 2 !Its content follows.. - END SUBROUTINE HTMLSTART !Others will follow on. Hopefully, correctly. - SUBROUTINE HTMLSTOP !And hopefully, this will be a good closure. + CALL HTML('') !But said to be worthy. + CALL HTML(METAH//'Description" Content="'//DESC//'">') !Hopefully, helpful. + CALL HTML(METAH//'Generator" Content="'//I AM//'">') !I said. + CALL DATE_AND_TIME(DATE = D,TIME = T) !Not assignments, but attachments. + CALL HTML(METAH//'Created" Content="' !Convert the timestamp + 1 //D(1:4)//"-"//D(5:6)//"-"//D(7:8) !Into an international standard. + 2 //" "//T(1:2)//":"//T(3:4)//":"//T(5:10)//'">') !For date and time. + IF (LUSERCODE.GT.0) CALL HTML(METAH !Possibly, the user's code is known. + 1 //'Author" Content="'//USERCODE(1:LUSERCODE) !If so, reveal. + 2 //'"> ') !Disclaiming responsibility... + INDEEP = 1 !Finishing the content of the header. + CALL HTML("") !Enough of that. + CALL HTML("") !A fresh line seems polite. + INDEEP = 2 !Its content follows.. + END SUBROUTINE HTMLSTART !Others will follow on. Hopefully, correctly. + SUBROUTINE HTMLSTOP !And hopefully, this will be a good closure. Could be more sophisticated and track the stack via INDEEP+- and names, to enable a desperate close-off if INDEEP is not 2. - IF (INDEEP.NE.2) CALL ECART("Misclosure! InDeep not 2 but" !But, - 1 //I8FMT(INDEEP)) !It may not be. - INDEEP = 1 !Retreat to the first level. - CALL HTML("") !End the "body". - INDEEP = 0 !Retreat to the start level. - CALL HTML("") !End the whole thing. - END SUBROUTINE HTMLSTOP !Ah... + IF (INDEEP.NE.2) CALL ECART("Misclosure! InDeep not 2 but" !But, + 1 //I8FMT(INDEEP)) !It may not be. + INDEEP = 1 !Retreat to the first level. + CALL HTML("") !End the "body". + INDEEP = 0 !Retreat to the start level. + CALL HTML("") !End the whole thing. + END SUBROUTINE HTMLSTOP !Ah... - SUBROUTINE HTMLTSTART(B,SUMMARY) !Start a table. - INTEGER B !Border thickness. - CHARACTER*(*) SUMMARY !Some well-chosen words. - CALL HTML("') !Not displayed, but potentially used by non-display agencies... - INDEEP = INDEEP + 1 !Another level dug. + SUBROUTINE HTMLTSTART(B,SUMMARY) !Start a table. + INTEGER B !Border thickness. + CHARACTER*(*) SUMMARY !Some well-chosen words. + CALL HTML("
    ') !Not displayed, but potentially used by non-display agencies... + INDEEP = INDEEP + 1 !Another level dug. END SUBROUTINE HTMLTSTART!That part was easy. - SUBROUTINE HTMLTSTOP !And the ending is easy too. - INDEEP = INDEEP - 1 !Withdraw a level. - CALL HTML("
    ") !Hopefully, aligning. - END SUBROUTINE HTMLTSTOP !The bounds are easy. + SUBROUTINE HTMLTSTOP !And the ending is easy too. + INDEEP = INDEEP - 1 !Withdraw a level. + CALL HTML("") !Hopefully, aligning. + END SUBROUTINE HTMLTSTOP !The bounds are easy. - SUBROUTINE HTMLTHEADSTART !Start a table's heading. - CALL HTML("") !Thus. - INDEEP = INDEEP + 1 !Dig deeper. - END SUBROUTINE HTMLTHEADSTART !Content should follow. - SUBROUTINE HTMLTHEADSTOP !And now, enough. - INDEEP = INDEEP - 1 !Retreat a level. - CALL HTML("") !And end the head. - END SUBROUTINE HTMLTHEADSTOP !At the neck of the body? + SUBROUTINE HTMLTHEADSTART !Start a table's heading. + CALL HTML("") !Thus. + INDEEP = INDEEP + 1 !Dig deeper. + END SUBROUTINE HTMLTHEADSTART !Content should follow. + SUBROUTINE HTMLTHEADSTOP !And now, enough. + INDEEP = INDEEP - 1 !Retreat a level. + CALL HTML("") !And end the head. + END SUBROUTINE HTMLTHEADSTOP !At the neck of the body? - SUBROUTINE HTMLTHEAD(N,TEXT) !Cast forth a whole-span table heading. - INTEGER N !The count of columns to be spanned. - CHARACTER*(*) TEXT !A brief description to place there. - CALL HTML3("',"") !Start the specification. - CALL HTML3("",TEXT(1:LSTNB(TEXT)),"") !This text, possibly verbose. - END SUBROUTINE HTMLTHEAD !Thus, all contained on one line. + SUBROUTINE HTMLTHEAD(N,TEXT) !Cast forth a whole-span table heading. + INTEGER N !The count of columns to be spanned. + CHARACTER*(*) TEXT !A brief description to place there. + CALL HTML3("',"") !Start the specification. + CALL HTML3("",TEXT(1:LSTNB(TEXT)),"") !This text, possibly verbose. + END SUBROUTINE HTMLTHEAD !Thus, all contained on one line. - SUBROUTINE HTMLTBODYSTART !Start on the table body. - CALL HTML(' ') !And I don't think much of the "comment" formalism, either. - INDEEP = INDEEP + 1 !Anyway, we're ready with the alignment. - END SUBROUTINE HTMLTBODYSTART !Others will provide the body. - SUBROUTINE HTMLTBODYSTOP !And, they've had enough. - INDEEP = INDEEP - 1 !So, up out of the hole. - CALL HTML("") !Take a breath. - END SUBROUTINE HTMLTBODYSTOP !And wander off. - SUBROUTINE HTMLTROWTEXT(TEXT,N) !Roll a row of column headings. - CHARACTER*(*) TEXT(:) !The headings. - INTEGER N !Their number. - INTEGER I,L !Assistants. - CALL HTML3("","","") !Start a row of headings-to-come, and don't end the line. - DO I = 1,N !Step through the headings. - L = LSTNB(TEXT(I)) !Trailing spaces are to be ignored. - IF (L.LE.0) THEN !Thus discovering blank texts. - CALL HTML3(""," ","") !This prevents the cell being collapsed. - ELSE !But for those with text, - CALL HTML3("",""//TEXT(I)(1:L)//"","") !Roll it. - END IF !So much for that text. - END DO !On to the next. - CALL HTML3("","","") !Finish the row, and thus the line. - END SUBROUTINE HTMLTROWTEXT !So much for texts. - SUBROUTINE HTMLTROWINTEGER(V,N) !Now for all integers. - INTEGER V(:) !The integers. - INTEGER N !Their number. - INTEGER I !A stepper. - CALL HTML3('',"","") !Start a row of entries. - DO I = 1,N !Work through the row's values. - CALL HTML3("",""//I8FMT(V(I))//"","") !One by one. - END DO !On to the next. - CALL HTML3("","","") !Finish the row, and thus the line. - END SUBROUTINE HTMLTROWINTEGER !All the same type is not troublesome. - END MODULE HTMLSTUFF !Enough already. + SUBROUTINE HTMLTBODYSTART !Start on the table body. + CALL HTML(' ') !And I don't think much of the "comment" formalism, either. + INDEEP = INDEEP + 1 !Anyway, we're ready with the alignment. + END SUBROUTINE HTMLTBODYSTART !Others will provide the body. + SUBROUTINE HTMLTBODYSTOP !And, they've had enough. + INDEEP = INDEEP - 1 !So, up out of the hole. + CALL HTML("") !Take a breath. + END SUBROUTINE HTMLTBODYSTOP !And wander off. + SUBROUTINE HTMLTROWTEXT(TEXT,N) !Roll a row of column headings. + CHARACTER*(*) TEXT(:) !The headings. + INTEGER N !Their number. + INTEGER I,L !Assistants. + CALL HTML3("","","") !Start a row of headings-to-come, and don't end the line. + DO I = 1,N !Step through the headings. + L = LSTNB(TEXT(I)) !Trailing spaces are to be ignored. + IF (L.LE.0) THEN !Thus discovering blank texts. + CALL HTML3(""," ","") !This prevents the cell being collapsed. + ELSE !But for those with text, + CALL HTML3("",""//TEXT(I)(1:L)//"","") !Roll it. + END IF !So much for that text. + END DO !On to the next. + CALL HTML3("","","") !Finish the row, and thus the line. + END SUBROUTINE HTMLTROWTEXT !So much for texts. + SUBROUTINE HTMLTROWINTEGER(V,N) !Now for all integers. + INTEGER V(:) !The integers. + INTEGER N !Their number. + INTEGER I !A stepper. + CALL HTML3('',"","") !Start a row of entries. + DO I = 1,N !Work through the row's values. + CALL HTML3("",""//I8FMT(V(I))//"","") !One by one. + END DO !On to the next. + CALL HTML3("","","") !Finish the row, and thus the line. + END SUBROUTINE HTMLTROWINTEGER !All the same type is not troublesome. + END MODULE HTMLSTUFF !Enough already. PROGRAM MAKETABLE USE PARAMETERS USE ASSISTANCE USE HTMLSTUFF INTEGER KBD,MSG - INTEGER NCOLS !The usage of V must conform to this! - PARAMETER (NCOLS = 4) !Specified number of columns. - CHARACTER*3 COLNAME(NCOLS) !And they have names. - PARAMETER (COLNAME = (/"","X","Y","Z"/)) !As specified. - INTEGER V(NCOLS) !A scratchpad for a line's worth. - COMMON KBD,MSG !I/O units. - KBD = 5 !Keyboard. - MSG = 6 !Screen. - CALL GETLOG(USERCODE) !Who has poked me into life? - LUSERCODE = LSTNB(USERCODE) !Ah, text gnashing. + INTEGER NCOLS !The usage of V must conform to this! + PARAMETER (NCOLS = 4) !Specified number of columns. + CHARACTER*3 COLNAME(NCOLS) !And they have names. + PARAMETER (COLNAME = (/"","X","Y","Z"/)) !As specified. + INTEGER V(NCOLS) !A scratchpad for a line's worth. + COMMON KBD,MSG !I/O units. + KBD = 5 !Keyboard. + MSG = 6 !Screen. + CALL GETLOG(USERCODE) !Who has poked me into life? + LUSERCODE = LSTNB(USERCODE) !Ah, text gnashing. - CALL HTMLSTART(MSG,"Powers","Table of integer powers") !Output to the screen will do. - CALL HTMLTSTART(1,"Successive powers of successive integers") !Start the table. - CALL HTMLTHEADSTART !The table heading. - CALL HTMLTHEAD(NCOLS,"Successive powers") !A full-width heading. - CALL HTMLTROWTEXT(COLNAME,NCOLS) !Headings for each column. - CALL HTMLTHEADSTOP !So much for the heading. - CALL HTMLTBODYSTART !Now for the content. - DO I = 1,10 !This should be enough. - V(1) = I !The unheaded row number. - V(2) = I**2 !Its square. - V(3) = I**3 !Cube. - V(4) = I**4 !Fourth power. - CALL HTMLTROWINTEGER(V,NCOLS) !Show a row's worth.. - END DO !On to the next line. - CALL HTMLTBODYSTOP !No more content. - CALL HTMLTSTOP !End the table. + CALL HTMLSTART(MSG,"Powers","Table of integer powers") !Output to the screen will do. + CALL HTMLTSTART(1,"Successive powers of successive integers") !Start the table. + CALL HTMLTHEADSTART !The table heading. + CALL HTMLTHEAD(NCOLS,"Successive powers") !A full-width heading. + CALL HTMLTROWTEXT(COLNAME,NCOLS) !Headings for each column. + CALL HTMLTHEADSTOP !So much for the heading. + CALL HTMLTBODYSTART !Now for the content. + DO I = 1,10 !This should be enough. + V(1) = I !The unheaded row number. + V(2) = I**2 !Its square. + V(3) = I**3 !Cube. + V(4) = I**4 !Fourth power. + CALL HTMLTROWINTEGER(V,NCOLS) !Show a row's worth.. + END DO !On to the next line. + CALL HTMLTBODYSTOP !No more content. + CALL HTMLTSTOP !End the table. CALL HTMLSTOP END diff --git a/Task/Create-an-HTML-table/Java/create-an-html-table-3.java b/Task/Create-an-HTML-table/Java/create-an-html-table-3.java index f5306aa7ac..3c85302f31 100644 --- a/Task/Create-an-HTML-table/Java/create-an-html-table-3.java +++ b/Task/Create-an-HTML-table/Java/create-an-html-table-3.java @@ -1,25 +1,25 @@ public class HTML { - public static String array2HTML(Object[][] array){ - StringBuilder html = new StringBuilder( - ""); - for(Object elem:array[0]){ - html.append(""); - } - for(int i = 1; i < array.length; i++){ - Object[] row = array[i]; - html.append(""); - for(Object elem:row){ - html.append(""); - } - html.append(""); - } - html.append("
    " + elem.toString() + "
    " + elem.toString() + "
    "); - return html.toString(); - } - - public static void main(String[] args){ - Object[][] ints = {{"","X","Y","Z"},{1,1,2,3},{2,4,5,6},{3,7,8,9},{4,10,11,12}}; - System.out.println(array2HTML(ints)); - } + public static String array2HTML(Object[][] array){ + StringBuilder html = new StringBuilder( + ""); + for(Object elem:array[0]){ + html.append(""); + } + for(int i = 1; i < array.length; i++){ + Object[] row = array[i]; + html.append(""); + for(Object elem:row){ + html.append(""); + } + html.append(""); + } + html.append("
    " + elem.toString() + "
    " + elem.toString() + "
    "); + return html.toString(); + } + + public static void main(String[] args){ + Object[][] ints = {{"","X","Y","Z"},{1,1,2,3},{2,4,5,6},{3,7,8,9},{4,10,11,12}}; + System.out.println(array2HTML(ints)); + } } diff --git a/Task/Create-an-HTML-table/JavaScript/create-an-html-table-1.js b/Task/Create-an-HTML-table/JavaScript/create-an-html-table-1.js index 02d28e0f6d..9ba8c08860 100644 --- a/Task/Create-an-HTML-table/JavaScript/create-an-html-table-1.js +++ b/Task/Create-an-HTML-table/JavaScript/create-an-html-table-1.js @@ -4,32 +4,32 @@ Node.prototype.a = function (e) { this.appendChild(e); return this } function ce(tag, txt) { - var x = document.createElement(tag); - x.textContent = (txt === undefined) ? '' : txt; - return x; + var x = document.createElement(tag); + x.textContent = (txt === undefined) ? '' : txt; + return x; } function make_table(cols, rows) { - var tbl = ce('table', ''), tr = ce('tr'), th; + var tbl = ce('table', ''), tr = ce('tr'), th; - tbl.a(tr.a(ce('th'))); + tbl.a(tr.a(ce('th'))); - var z = 'Z'.charCodeAt(0); - for (var l = z - cols + 1; l <= z; l++) - tr.a(ce('th', String.fromCharCode(l))); + var z = 'Z'.charCodeAt(0); + for (var l = z - cols + 1; l <= z; l++) + tr.a(ce('th', String.fromCharCode(l))); - for (var r = 1; r <= rows; r++) { - tbl.a(tr = ce('tr').a(ce('th', r))); - for (var c = 0; c < cols; c++) - tr.a(ce('td', Math.floor(Math.random() * 10000))); - } + for (var r = 1; r <= rows; r++) { + tbl.a(tr = ce('tr').a(ce('th', r))); + for (var c = 0; c < cols; c++) + tr.a(ce('td', Math.floor(Math.random() * 10000))); + } - document.body - .a(ce('style', - 'td, th {border: 1px solid #696;' + - 'padding:.4ex} td {text-align: right }' + - 'table { border-collapse: collapse}')) - .a(tbl); + document.body + .a(ce('style', + 'td, th {border: 1px solid #696;' + + 'padding:.4ex} td {text-align: right }' + + 'table { border-collapse: collapse}')) + .a(tbl); } diff --git a/Task/Create-an-HTML-table/Julia/create-an-html-table-1.julia b/Task/Create-an-HTML-table/Julia/create-an-html-table-1.jl similarity index 100% rename from Task/Create-an-HTML-table/Julia/create-an-html-table-1.julia rename to Task/Create-an-HTML-table/Julia/create-an-html-table-1.jl diff --git a/Task/Create-an-HTML-table/Julia/create-an-html-table-2.julia b/Task/Create-an-HTML-table/Julia/create-an-html-table-2.jl similarity index 100% rename from Task/Create-an-HTML-table/Julia/create-an-html-table-2.julia rename to Task/Create-an-HTML-table/Julia/create-an-html-table-2.jl diff --git a/Task/Create-an-HTML-table/Kotlin/create-an-html-table-1.kotlin b/Task/Create-an-HTML-table/Kotlin/create-an-html-table-1.kts similarity index 100% rename from Task/Create-an-HTML-table/Kotlin/create-an-html-table-1.kotlin rename to Task/Create-an-HTML-table/Kotlin/create-an-html-table-1.kts diff --git a/Task/Create-an-HTML-table/Kotlin/create-an-html-table-2.kotlin b/Task/Create-an-HTML-table/Kotlin/create-an-html-table-2.kts similarity index 100% rename from Task/Create-an-HTML-table/Kotlin/create-an-html-table-2.kotlin rename to Task/Create-an-HTML-table/Kotlin/create-an-html-table-2.kts diff --git a/Task/Create-an-HTML-table/Lasso/create-an-html-table.lasso b/Task/Create-an-HTML-table/Lasso/create-an-html-table.lasso index 738052d5ac..bac8e0748f 100644 --- a/Task/Create-an-HTML-table/Lasso/create-an-html-table.lasso +++ b/Task/Create-an-HTML-table/Lasso/create-an-html-table.lasso @@ -1,20 +1,20 @@ define rand4dig => integer_random(9999, 1) local( - output = '\n' + output = '
    \n' ) with el in (' ,X,Y,Z') -> split(',') do { - #output -> append('') + #output -> append('') } #output -> append('\n') loop(5) => { - #output -> append('\n') - loop(3) => { - #output -> append('') - } - #output -> append('\n') + #output -> append('\n') + loop(3) => { + #output -> append('') + } + #output -> append('\n') } #output -> append('
    ' + #el + '' + #el + '
    ' + loop_count + '' + rand4dig + '
    ' + loop_count + '' + rand4dig + '
    \n') diff --git a/Task/Create-an-HTML-table/M2000-Interpreter/create-an-html-table.m2000 b/Task/Create-an-HTML-table/M2000-Interpreter/create-an-html-table.m2000 index a4f9c77305..e212abd32f 100644 --- a/Task/Create-an-HTML-table/M2000-Interpreter/create-an-html-table.m2000 +++ b/Task/Create-an-HTML-table/M2000-Interpreter/create-an-html-table.m2000 @@ -1,36 +1,36 @@ MODULE HtmlTable { - tag$=LAMBDA$ (a$)-> { - =LAMBDA$ a$ -> { - IF ISNUM THEN w$=STR$(NUMBER,0) ELSE w$=LETTER$ - READ ? part$ - ="<"+a$+IF$(LEN(part$)>0->" "+part$,"")+">"+w$+""+CHR$(13)+CHR$(10) - } - } - INVENTORY Fun - STACK NEW { - DATA "html", "head", "body", "table", "tr", "th", "td" - WHILE NOT EMPTY - OVER ' duplicate top of stack - APPEND Fun, LETTER$:=tag$(LETTER$) - END WHILE - } - DEF body0$="",body$="" - STACK NEW { - DATA "", "X", "Y", "Z" - FOR i=1 TO 4 - body0$+=Fun$("th")(LETTER$) - z$="" - FOR j=1 TO 3 : z$+=Fun$("td")(RANDOM(0, 9999), {align="right"}) : NEXT j - body$+=Fun$("tr")(Fun$("th")(i)+z$) - NEXT i - } - table$=fun$("table")(fun$("tr")(body0$)+body$,"border=1 cellpadding=10 cellspacing=0") - DOCUMENT final$=""+CHR$(13)+CHR$(10) - final$=fun$("html")(fun$("head")("")+fun$("body")(table$), {lang="en"}) - file$="c:\doc.html" - REPORT final$ - CLIPBOARD final$ - SAVE.DOC final$, file$ - WIN file$ ' execute, no wait + tag$=LAMBDA$ (a$)-> { + =LAMBDA$ a$ -> { + IF ISNUM THEN w$=STR$(NUMBER,0) ELSE w$=LETTER$ + READ ? part$ + ="<"+a$+IF$(LEN(part$)>0->" "+part$,"")+">"+w$+""+CHR$(13)+CHR$(10) + } + } + INVENTORY Fun + STACK NEW { + DATA "html", "head", "body", "table", "tr", "th", "td" + WHILE NOT EMPTY + OVER ' duplicate top of stack + APPEND Fun, LETTER$:=tag$(LETTER$) + END WHILE + } + DEF body0$="",body$="" + STACK NEW { + DATA "", "X", "Y", "Z" + FOR i=1 TO 4 + body0$+=Fun$("th")(LETTER$) + z$="" + FOR j=1 TO 3 : z$+=Fun$("td")(RANDOM(0, 9999), {align="right"}) : NEXT j + body$+=Fun$("tr")(Fun$("th")(i)+z$) + NEXT i + } + table$=fun$("table")(fun$("tr")(body0$)+body$,"border=1 cellpadding=10 cellspacing=0") + DOCUMENT final$=""+CHR$(13)+CHR$(10) + final$=fun$("html")(fun$("head")("")+fun$("body")(table$), {lang="en"}) + file$="c:\doc.html" + REPORT final$ + CLIPBOARD final$ + SAVE.DOC final$, file$ + WIN file$ ' execute, no wait } HtmlTable diff --git a/Task/Create-an-HTML-table/Modula-3/create-an-html-table.mod3 b/Task/Create-an-HTML-table/Modula-3/create-an-html-table.mod3 index 86b0df0df1..a78a020685 100644 --- a/Task/Create-an-HTML-table/Modula-3/create-an-html-table.mod3 +++ b/Task/Create-an-HTML-table/Modula-3/create-an-html-table.mod3 @@ -5,16 +5,16 @@ FROM Fmt IMPORT Int, F; BEGIN IO.Put("" - & "" + & "" - & "", - Int(I), - Int(rand.integer(0, 1000)), - Int(rand.integer(0, 1000)), - Int(rand.integer(0, 1000)))); - END; + FOR I := 0 TO 3 DO + IO.Put(F("" + & "", + Int(I), + Int(rand.integer(0, 1000)), + Int(rand.integer(0, 1000)), + Int(rand.integer(0, 1000)))); + END; END; END Table. diff --git a/Task/Create-an-HTML-table/Nanoquery/create-an-html-table.nanoquery b/Task/Create-an-HTML-table/Nanoquery/create-an-html-table.nanoquery index e3c367c973..b5ff55121d 100644 --- a/Task/Create-an-HTML-table/Nanoquery/create-an-html-table.nanoquery +++ b/Task/Create-an-HTML-table/Nanoquery/create-an-html-table.nanoquery @@ -9,11 +9,11 @@ println "" // generate five rows for i in range(1, 5) - println "" - println "" - println "" - println "" - println "" + println "" + println "" + println "" + println "" + println "" end for println "
    XY"); + & "border: 1px solid\">XY"); WITH rand = NEW(Random.Default).init() DO - FOR I := 0 TO 3 DO - IO.Put(F("
    %s%s%s%s
    %s%s%s%s
    XYZ
    " + i + "" + int($random.getInt(8999) + 1000) + "" + int($random.getInt(8999) + 1000) + "" + int($random.getInt(8999) + 1000) + "
    " + i + "" + int($random.getInt(8999) + 1000) + "" + int($random.getInt(8999) + 1000) + "" + int($random.getInt(8999) + 1000) + "
    " diff --git a/Task/Create-an-HTML-table/OCaml/create-an-html-table-1.ocaml b/Task/Create-an-HTML-table/OCaml/create-an-html-table-1.ml similarity index 100% rename from Task/Create-an-HTML-table/OCaml/create-an-html-table-1.ocaml rename to Task/Create-an-HTML-table/OCaml/create-an-html-table-1.ml diff --git a/Task/Create-an-HTML-table/OCaml/create-an-html-table-2.ocaml b/Task/Create-an-HTML-table/OCaml/create-an-html-table-2.ml similarity index 100% rename from Task/Create-an-HTML-table/OCaml/create-an-html-table-2.ocaml rename to Task/Create-an-HTML-table/OCaml/create-an-html-table-2.ml diff --git a/Task/Create-an-HTML-table/OCaml/create-an-html-table-3.ocaml b/Task/Create-an-HTML-table/OCaml/create-an-html-table-3.ml similarity index 100% rename from Task/Create-an-HTML-table/OCaml/create-an-html-table-3.ocaml rename to Task/Create-an-HTML-table/OCaml/create-an-html-table-3.ml diff --git a/Task/Create-an-HTML-table/OCaml/create-an-html-table-4.ocaml b/Task/Create-an-HTML-table/OCaml/create-an-html-table-4.ml similarity index 100% rename from Task/Create-an-HTML-table/OCaml/create-an-html-table-4.ocaml rename to Task/Create-an-HTML-table/OCaml/create-an-html-table-4.ml diff --git a/Task/Create-an-HTML-table/Oz/create-an-html-table.oz b/Task/Create-an-HTML-table/Oz/create-an-html-table.oz index 8d353080da..e7695d8b19 100644 --- a/Task/Create-an-HTML-table/Oz/create-an-html-table.oz +++ b/Task/Create-an-HTML-table/Oz/create-an-html-table.oz @@ -5,30 +5,30 @@ declare fun {Table Session} html( head(title("Show a table with row and column headings") - style(type:"text/css" - css(td 'text-align':center) - )) + style(type:"text/css" + css(td 'text-align':center) + )) body( - {TagFromList table - tr(th th("X") th("Y") th("Z")) - | - {CreateRows 3 5} - })) + {TagFromList table + tr(th th("X") th("Y") th("Z")) + | + {CreateRows 3 5} + })) end fun {CreateRows NumCols NumRows} {List.map {List.number 1 NumRows 1} fun {$ Row} {TagFromList tr - td( {Int.toString Row} ) - | - {List.map {List.number 1 NumCols 1} - fun {$ Col} - SequentialNumber = (Row-1)*NumCols + Col - in - td( {Int.toString SequentialNumber} ) - end - }} + td( {Int.toString Row} ) + | + {List.map {List.number 1 NumCols 1} + fun {$ Col} + SequentialNumber = (Row-1)*NumCols + Col + in + td( {Int.toString SequentialNumber} ) + end + }} end } end diff --git a/Task/Create-an-HTML-table/PHP/create-an-html-table-1.php b/Task/Create-an-HTML-table/PHP/create-an-html-table-1.php index f7fc655559..78ddb2115b 100644 --- a/Task/Create-an-HTML-table/PHP/create-an-html-table-1.php +++ b/Task/Create-an-HTML-table/PHP/create-an-html-table-1.php @@ -9,27 +9,27 @@ $rows = 3; $html = ''; foreach($cols as $col) { - $html .= ''; + $html .= ''; } unset($col); $html .= ''; foreach($cols as $col) { - $html .= ""; + $html .= ""; } unset($col); $html .= ''; for($r = 1; $r <= $rows; $r++) { - $html .= ''; - foreach($cols as $key => $col) - { - $html .= ''; - } - unset($col); - $html .= ''; + $html .= ''; + foreach($cols as $key => $col) + { + $html .= ''; + } + unset($col); + $html .= ''; } $html .= '
    {$col}{$col}
    ' . (($key > 0) ? rand(1, 9999) : $r) . '
    ' . (($key > 0) ? rand(1, 9999) : $r) . '
    '; diff --git a/Task/Create-an-HTML-table/PHP/create-an-html-table-2.php b/Task/Create-an-HTML-table/PHP/create-an-html-table-2.php index a13b5fb1b9..3abf9fd3ee 100644 --- a/Task/Create-an-HTML-table/PHP/create-an-html-table-2.php +++ b/Task/Create-an-HTML-table/PHP/create-an-html-table-2.php @@ -9,27 +9,27 @@ $rows = 3; - - - - - - - - - - - - - - - - $col): ?> - - - - - + + + + + + + + + + + + + + + + $col): ?> + + + + +
    0) ? rand(1, 9999) : $r ?>
    0) ? rand(1, 9999) : $r ?>
    diff --git a/Task/Create-an-HTML-table/Peloton/create-an-html-table.peloton b/Task/Create-an-HTML-table/Peloton/create-an-html-table.peloton index 45b01ab02e..37ba932a85 100644 --- a/Task/Create-an-HTML-table/Peloton/create-an-html-table.peloton +++ b/Task/Create-an-HTML-table/Peloton/create-an-html-table.peloton @@ -1,17 +1,17 @@ <@ SDCLIT> - <@ DTBLIT> - <@ DTRLITLIT> - <@ DTDLITLIT>|[style]background-color:white - <@ DTD>X - <@ DTD>Y - <@ DTD>Z|[style]width:100%; background-color:brown;color:white; text-align:center - <@ ITEFORLIT>10| - <@ DTRLITCAP> - <@ DTDPOSFORLIT>...|[style]background-color:Brown; color:white; text-align:right - <@ DTDCAPLIT><@ SAYR!ILI2>1|9999|[style]width:50;text-align:right - <@ DTDCAPLIT><@ SAYR!ILI2>1|9999|[style]width:50;text-align:right - <@ DTDCAPLIT><@ SAYR!ILI2>1|9999|[style]width:50;text-align:right - |[style]background-color:white;color:black - - + <@ DTBLIT> + <@ DTRLITLIT> + <@ DTDLITLIT>|[style]background-color:white + <@ DTD>X + <@ DTD>Y + <@ DTD>Z|[style]width:100%; background-color:brown;color:white; text-align:center + <@ ITEFORLIT>10| + <@ DTRLITCAP> + <@ DTDPOSFORLIT>...|[style]background-color:Brown; color:white; text-align:right + <@ DTDCAPLIT><@ SAYR!ILI2>1|9999|[style]width:50;text-align:right + <@ DTDCAPLIT><@ SAYR!ILI2>1|9999|[style]width:50;text-align:right + <@ DTDCAPLIT><@ SAYR!ILI2>1|9999|[style]width:50;text-align:right + |[style]background-color:white;color:black + + |Number Table diff --git a/Task/Create-an-HTML-table/PowerShell/create-an-html-table-1.psh b/Task/Create-an-HTML-table/PowerShell/create-an-html-table-1.ps1 similarity index 100% rename from Task/Create-an-HTML-table/PowerShell/create-an-html-table-1.psh rename to Task/Create-an-HTML-table/PowerShell/create-an-html-table-1.ps1 diff --git a/Task/Create-an-HTML-table/PowerShell/create-an-html-table-2.psh b/Task/Create-an-HTML-table/PowerShell/create-an-html-table-2.ps1 similarity index 100% rename from Task/Create-an-HTML-table/PowerShell/create-an-html-table-2.psh rename to Task/Create-an-HTML-table/PowerShell/create-an-html-table-2.ps1 diff --git a/Task/Create-an-HTML-table/PowerShell/create-an-html-table-3.psh b/Task/Create-an-HTML-table/PowerShell/create-an-html-table-3.ps1 similarity index 100% rename from Task/Create-an-HTML-table/PowerShell/create-an-html-table-3.psh rename to Task/Create-an-HTML-table/PowerShell/create-an-html-table-3.ps1 diff --git a/Task/Create-an-HTML-table/Prolog/create-an-html-table-1.pro b/Task/Create-an-HTML-table/Prolog/create-an-html-table-1.pro index b84bdb97ae..cac87a0a7f 100644 --- a/Task/Create-an-HTML-table/Prolog/create-an-html-table-1.pro +++ b/Task/Create-an-HTML-table/Prolog/create-an-html-table-1.pro @@ -5,12 +5,12 @@ trows([],_) --> []. trows([R|T], N) --> html(tr([td(N),\trow(R)])), { N1 is N + trow([]) --> []. trow([E|T]) --> html(td(E)), trow(T). table :- - Header = ['X','Y','Z'], - Rows = [ - [7055,5334,5795], - [2895,3019,7747], - [140,7607,8144], - [7090,475,4140] - ], - phrase(html(table([tr(\theader(Header)), \trows(Rows,1)])), Out, []), - print_html(Out). + Header = ['X','Y','Z'], + Rows = [ + [7055,5334,5795], + [2895,3019,7747], + [140,7607,8144], + [7090,475,4140] + ], + phrase(html(table([tr(\theader(Header)), \trows(Rows,1)])), Out, []), + print_html(Out). diff --git a/Task/Create-an-HTML-table/R/create-an-html-table.r b/Task/Create-an-HTML-table/R/create-an-html-table.r new file mode 100644 index 0000000000..4818c382a0 --- /dev/null +++ b/Task/Create-an-HTML-table/R/create-an-html-table.r @@ -0,0 +1,15 @@ +html_table <- function(headings, nrows){ + ncols <- length(headings) + pad_table <- function(s, char2="d"){ + pad <- paste0("", s, "", collapse="") + paste0("", pad, "", collapse="") + } + theader <- pad_table(c("", headings), char2="h") + gen_row <- function(n) c(n, sample(9999, ncols)) + tbody <- lapply(1:nrows, gen_row) |> sapply(pad_table) + cat("", theader, sep="\n") + writeLines(tbody) + cat("
    \n") +} + +html_table(c("X", "Y", "Z"), 3) diff --git a/Task/Create-an-HTML-table/Rascal/create-an-html-table-1.rascal b/Task/Create-an-HTML-table/Rascal/create-an-html-table-1.rascal index 6d7cfdfdd8..47f6edacf3 100644 --- a/Task/Create-an-HTML-table/Rascal/create-an-html-table-1.rascal +++ b/Task/Create-an-HTML-table/Rascal/create-an-html-table-1.rascal @@ -8,11 +8,11 @@ str tr(str content) = item("tr", content); str td(str content) = item("td", content); public str generateTable(int rows){ - int i(){return arbInt(10000);}; - rows = (tr(td("")+td("X")+td("Y")+td("Z")) - | it + tr(td("")+td("")+td("")+td("")) - | x <- [1..rows]); - writeFile(|file:///location|, - html("Rosetta Code Table", table(rows))); - return "written"; + int i(){return arbInt(10000);}; + rows = (tr(td("")+td("X")+td("Y")+td("Z")) + | it + tr(td("")+td("")+td("")+td("")) + | x <- [1..rows]); + writeFile(|file:///location|, + html("Rosetta Code Table", table(rows))); + return "written"; } diff --git a/Task/Create-an-HTML-table/Rebol/create-an-html-table-1.rebol b/Task/Create-an-HTML-table/Rebol/create-an-html-table-1.rebol new file mode 100644 index 0000000000..6460883556 --- /dev/null +++ b/Task/Create-an-HTML-table/Rebol/create-an-html-table-1.rebol @@ -0,0 +1,37 @@ +Rebol [ + title: "Rosetta code: Create an HTML table" + file: %Create_an_HTML_table.r3 + url: https://rosettacode.org/wiki/Create_an_HTML_table + note: "Based on Red language implementation!" +] +table-rows: func [][rejoin [ + first-tr newline + rand-tr 1 newline + rand-tr 2 newline + rand-tr 3 newline + rand-tr 4 newline + rand-tr 5 newline +]] +td-data: does [999 + random 9000] +rand-td: does [form-tag 'td td-data] +rand-tr: func [i][rejoin [ + form-tag 'tr + rejoin [(form-tag 'td i) rand-td rand-td rand-td] +]] +first-tr: func[][rejoin [ + form-tag 'tr rejoin [ + form-tag 'th "" + form-tag 'th "X" + form-tag 'th "Y" + form-tag 'th "Z" + ] +]] +form-tag: func [tag contents /attr a][ + ajoin [ + "<" tag (if attr [ajoin [" " a/1 "=" {"} a/2 {"}]]) ">" + contents + "" + ] +] + +print form-tag 'table table-rows diff --git a/Task/Create-an-HTML-table/Rebol/create-an-html-table-2.rebol b/Task/Create-an-HTML-table/Rebol/create-an-html-table-2.rebol new file mode 100644 index 0000000000..c3c7cbc8af --- /dev/null +++ b/Task/Create-an-HTML-table/Rebol/create-an-html-table-2.rebol @@ -0,0 +1,7 @@ + + + + + + +
    XYZ
    1209634429408
    2967939177056
    3215143569440
    4274197384967
    5237771907304
    diff --git a/Task/Create-an-HTML-table/Rust/create-an-html-table-1.rust b/Task/Create-an-HTML-table/Rust/create-an-html-table-1.rs similarity index 100% rename from Task/Create-an-HTML-table/Rust/create-an-html-table-1.rust rename to Task/Create-an-HTML-table/Rust/create-an-html-table-1.rs diff --git a/Task/Create-an-HTML-table/Rust/create-an-html-table-2.rust b/Task/Create-an-HTML-table/Rust/create-an-html-table-2.rs similarity index 100% rename from Task/Create-an-HTML-table/Rust/create-an-html-table-2.rust rename to Task/Create-an-HTML-table/Rust/create-an-html-table-2.rs diff --git a/Task/Create-an-HTML-table/SNOBOL4/create-an-html-table.sno b/Task/Create-an-HTML-table/SNOBOL4/create-an-html-table.sno index df2ca8af52..496e49d4ba 100644 --- a/Task/Create-an-HTML-table/SNOBOL4/create-an-html-table.sno +++ b/Task/Create-an-HTML-table/SNOBOL4/create-an-html-table.sno @@ -1,12 +1,12 @@ * HTML Table - output = "" - output = " " - i = 1 -o1 output = "" - j = 1 -o2 output = "" - j = lt(j,3) j + 1 :s(o2) - output = "" - i = lt(i,3) i + 1 :s(o1) - output = "
    XYZ
    " i "" i j "
    " + output = "" + output = " " + i = 1 +o1 output = "" + j = 1 +o2 output = "" + j = lt(j,3) j + 1 :s(o2) + output = "" + i = lt(i,3) i + 1 :s(o1) + output = "
    XYZ
    " i "" i j "
    " end diff --git a/Task/Create-an-HTML-table/Scheme/create-an-html-table.ss b/Task/Create-an-HTML-table/Scheme/create-an-html-table.scm similarity index 100% rename from Task/Create-an-HTML-table/Scheme/create-an-html-table.ss rename to Task/Create-an-HTML-table/Scheme/create-an-html-table.scm diff --git a/Task/Create-an-HTML-table/Standard-ML/create-an-html-table.ml b/Task/Create-an-HTML-table/Standard-ML/create-an-html-table.ml index 9ffc1b1e25..4446dc7c10 100644 --- a/Task/Create-an-HTML-table/Standard-ML/create-an-html-table.ml +++ b/Task/Create-an-HTML-table/Standard-ML/create-an-html-table.ml @@ -1,34 +1,34 @@ (* * val mkHtmlTable : ('a list * 'b list) -> ('a -> string * 'b -> string) - * -> (('a * 'b) -> string) -> string + * -> (('a * 'b) -> string) -> string * The int list is list of colums, the function returns the values * at a given colum and row. * returns the HTML code of the generated table. *) fun mkHtmlTable (columns, rows) (rowToStr, colToStr) values = - let - val text = ref "\n" - in - (* Add headers *) - map (fn colum => text := !text ^ "") columns; + let + val text = ref "
    " ^ (colToStr colum) ^ "
    \n" + in + (* Add headers *) + map (fn colum => text := !text ^ "") columns; - text := !text ^ "\n"; - (* Add data rows *) - map (fn row => - (* row name *) - (text := !text ^ ""; - (* data *) - map (fn col => text := !text ^ "") columns; - text := !text ^ "\n") - ) rows; - !text ^ "
    " ^ (colToStr colum) ^ "
    " ^ (rowToStr row) ^ "" ^ (values (row, col)) ^ "
    " - end + text := !text ^ "\n"; + (* Add data rows *) + map (fn row => + (* row name *) + (text := !text ^ "" ^ (rowToStr row) ^ ""; + (* data *) + map (fn col => text := !text ^ "" ^ (values (row, col)) ^ "") columns; + text := !text ^ "\n") + ) rows; + !text ^ "" + end fun mkHtmlWithBody (title, body) = "\n\n" ^ title ^ "\n\n\n" ^ body ^ "\n\n\n" fun samplePage () = mkHtmlWithBody ("Sample Page", - mkHtmlTable ([1.0,2.0,3.0,4.0,5.0], [1.0,2.0,3.0,4.0]) - (Real.toString, Real.toString) - (fn (a, b) => Real.toString (Math.pow (a, b)))) + mkHtmlTable ([1.0,2.0,3.0,4.0,5.0], [1.0,2.0,3.0,4.0]) + (Real.toString, Real.toString) + (fn (a, b) => Real.toString (Math.pow (a, b)))) val _ = print (samplePage ()) diff --git a/Task/Create-an-HTML-table/Stata/create-an-html-table-1.stata b/Task/Create-an-HTML-table/Stata/create-an-html-table-1.stata index e0aac840d1..0bca7e1ec7 100644 --- a/Task/Create-an-HTML-table/Stata/create-an-html-table-1.stata +++ b/Task/Create-an-HTML-table/Stata/create-an-html-table-1.stata @@ -16,19 +16,19 @@ file write `f' `""' _n file write `f' "" _n file write `f' "" _n forv j = 1/`nc' { - local s `: word `j' of `cn'' - file write `f' `""' _n + local s `: word `j' of `cn'' + file write `f' `""' _n } file write `f' "" _n * write row names & data forv i = 1/`nr' { - file write `f' "" _n - local s `: word `i' of `rn'' - file write `f' `""' _n - forv j = 1/`nc' { - file write `f' `""' _n - } - file write `f' "" _n + file write `f' "" _n + local s `: word `i' of `rn'' + file write `f' `""' _n + forv j = 1/`nc' { + file write `f' `""' _n + } + file write `f' "" _n } file write `f' "
    `s'`s'
    `s'`=el(`1',`i',`j')'
    `s'`=el(`1',`i',`j')'
    " _n file write `f' "" _n diff --git a/Task/Create-an-HTML-table/Tcl/create-an-html-table.tcl b/Task/Create-an-HTML-table/Tcl/create-an-html-table.tcl index 0a25494ed2..0c28ec5b37 100644 --- a/Task/Create-an-HTML-table/Tcl/create-an-html-table.tcl +++ b/Task/Create-an-HTML-table/Tcl/create-an-html-table.tcl @@ -3,7 +3,7 @@ proc TAG {name args} { set body [lindex $args end] set result "<$name" foreach {t v} [lrange $args 0 end-1] { - append result " $t=\"" $v "\"" + append result " $t=\"" $v "\"" } append result ">" [string trim [uplevel 1 [list subst $body]]] "" } @@ -21,21 +21,21 @@ set data {} for {set x 0} {$x < 4} {incr x} { # Inspired by the Go solution, but with extra arbitrary digits to show 4-char wide values lappend data [list \ - [expr {$x+1}] [expr {$x*3010}] [expr {$x*3+1298}] [expr {$x*2579+2182}]] + [expr {$x+1}] [expr {$x*3010}] [expr {$x*3+1298}] [expr {$x*2579+2182}]] } # Write the table to standard out puts [TAG table border 1 { [TAG tr bgcolor #f0f0f0 { - [FOREACH head $titles { - [TAG th {$head}] - }] + [FOREACH head $titles { + [TAG th {$head}] + }] }] [FOREACH row $data { - [TAG tr bgcolor #ffffff { - [FOREACH col $row { - [TAG td align right {$col}] - }] - }] + [TAG tr bgcolor #ffffff { + [FOREACH col $row { + [TAG td align right {$col}] + }] + }] }] }] diff --git a/Task/Create-an-HTML-table/VBScript/create-an-html-table.vb b/Task/Create-an-HTML-table/VBScript/create-an-html-table.vb deleted file mode 100644 index 35deed3f02..0000000000 --- a/Task/Create-an-HTML-table/VBScript/create-an-html-table.vb +++ /dev/null @@ -1,40 +0,0 @@ -Set objFSO = CreateObject("Scripting.FileSystemObject") - -'Open the input csv file for reading. The file is in the same folder as the script. -Set objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ - "\in.csv",1) - -'Create the output html file. -Set objOutHTML = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ - "\out.html",2,True) - -'Write the html opening tags. -objOutHTML.Write "" & vbCrLf - -'Declare table properties. -objOutHTML.Write "" & vbCrLf - -'Write column headers. -objOutHTML.Write "" & vbCrLf - -'Go through each line of the input csv file and write to the html output file. -n = 1 -Do Until objInFile.AtEndOfStream - line = objInFile.ReadLine - If Len(line) > 0 Then - token = Split(line,",") - objOutHTML.Write "" - For i = 0 To UBound(token) - objOutHTML.Write "" - Next - objOutHTML.Write "" & vbCrLf - End If - n = n + 1 -Loop - -'Write the html closing tags. -objOutHTML.Write "
    XYZ
    " & n & "" & token(i) & "
    " - -objInFile.Close -objOutHTML.Close -Set objFSO = Nothing diff --git a/Task/Create-an-HTML-table/VBScript/create-an-html-table.vbs b/Task/Create-an-HTML-table/VBScript/create-an-html-table.vbs new file mode 100644 index 0000000000..488b88273f --- /dev/null +++ b/Task/Create-an-HTML-table/VBScript/create-an-html-table.vbs @@ -0,0 +1,40 @@ +Set objFSO = CreateObject("Scripting.FileSystemObject") + +'Open the input csv file for reading. The file is in the same folder as the script. +Set objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ + "\in.csv",1) + +'Create the output html file. +Set objOutHTML = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ + "\out.html",2,True) + +'Write the html opening tags. +objOutHTML.Write "" & vbCrLf + +'Declare table properties. +objOutHTML.Write "" & vbCrLf + +'Write column headers. +objOutHTML.Write "" & vbCrLf + +'Go through each line of the input csv file and write to the html output file. +n = 1 +Do Until objInFile.AtEndOfStream + line = objInFile.ReadLine + If Len(line) > 0 Then + token = Split(line,",") + objOutHTML.Write "" + For i = 0 To UBound(token) + objOutHTML.Write "" + Next + objOutHTML.Write "" & vbCrLf + End If + n = n + 1 +Loop + +'Write the html closing tags. +objOutHTML.Write "
    XYZ
    " & n & "" & token(i) & "
    " + +objInFile.Close +objOutHTML.Close +Set objFSO = Nothing diff --git a/Task/Create-an-HTML-table/X86-64-Assembly/create-an-html-table.x86-64 b/Task/Create-an-HTML-table/X86-64-Assembly/create-an-html-table.x86-64 new file mode 100644 index 0000000000..1df6b26b15 --- /dev/null +++ b/Task/Create-an-HTML-table/X86-64-Assembly/create-an-html-table.x86-64 @@ -0,0 +1,323 @@ +; creating html table +; assembly X86 window +; download and install visual studio 2022 free site microsoft +; search and open X64 native tools command prompt +; compil and link program with this command : +; ml64 .asm /link /ENTRY:main /SUBSYSTEM:console kernel32.lib user32.lib Shell32.lib +; this program respects the 64-bit calling convention : +; registers arguments : rcx rdx r8 r9 and stack +; registers saved : rbx,rbp,rdi,rsi, r12-r15 +; ATTENTION les registres rax,rcx,rdx,r8-r11 peuvent être +; perdus lors d'un appel de fonction +;********************************* +; constantes +;********************************* +STD_OUTPUT_HANDLE equ -11 + +NBLIGNES equ 5 +BUFFERSIZE equ 200 + +;********************************* +; MACROS +;********************************* +afficherLib MACRO messa +local mess1,LGMESS1C +.data + mess1 db messa,10,0 + LGMESS1C equ $ - mess1 +.code + push rax + push rcx + push rdx + push r8 + push r9 + push r10 + push r11 + mov rcx, offset mess1 + mov rdx,LGMESS1C + call afficherConsole + pop r11 + pop r10 + pop r9 + pop r8 + pop rdx + pop rcx + pop rax + +ENDM + +;********************************* +; user data +;********************************* +.data +szarrayheader db " ",10,0 +LGSZARRAYHEADER equ $ - szarrayheader -1 +szarrayend db "
    ",10,0 +LGSZARRAYEND equ $ - szarrayend -1 +szLine1 db "XYZ",10,0 +LGSZLINE1 equ $ - szLine1 - 1 +szDebLine db "",0 +LGSZDEBLINE equ $ - szDebLine - 1 +szEndLine db "",10,0 +LGSZENDLINE equ $ - szEndLine - 1 +szEndCol db "",0 +LGSZENDCOL equ $ - szEndCol - 1 + +sBuffer db BUFFERSIZE dup (' ') + +szRetourLigne db 10,0 +sZoneConv db 24 dup (' ') +sZoneConv1 db 24 dup (' ') +sZoneConv2 db 24 dup (' ') +sZoneConv3 db 24 dup (' ') + +align 8 +qgraine dq 123456789 +qNbDep1 dq 0019660dh +qNbDep2 dq 3c6ef35fh +hConsole dq 0 + +;********************************* +; user code fonction principale +;********************************* +.code + +extern WriteFile : proc, GetStdHandle : proc, ExitProcess : proc +extern GetLastError : proc + +main PROC public + afficherLib "Program start." + mov rcx, offset szarrayheader + mov rdx,LGSZARRAYHEADER + call afficherConsole + + mov rcx, offset szLine1 + mov rdx,LGSZLINE1 + call afficherConsole + + mov rbx,1 ; indice loop +lineLoop: ; line loop begin + mov rcx,rbx + mov rdx,offset sZoneConv + call conversion10 + mov rax, offset szDebLine + push rax + mov rax,LGSZDEBLINE + push rax + mov rax,offset sZoneConv + push rax + push 1 + mov rax,offset szEndCol + push rax + mov rax,LGSZENDCOL + push rax + mov rcx,10000 + call randomNumber + mov rcx,rax + mov rdx,offset sZoneConv1 + call conversion10 + mov rcx,offset sZoneConv1 + push rcx + push rax + mov rax,offset szEndCol + push rax + mov rax,LGSZENDCOL + push rax + mov rcx,10000 + call randomNumber + mov rcx,rax + mov rdx,offset sZoneConv2 + call conversion10 + mov rcx,offset sZoneConv2 + push rcx + push rax + + mov rax,offset szEndCol + push rax + mov rax,LGSZENDCOL + push rax + mov rcx,10000 + call randomNumber + mov rcx,rax + mov rdx,offset sZoneConv3 + call conversion10 + mov rcx,offset sZoneConv3 + push rcx + push rax + + mov rax, offset szEndLine + push rax + mov rax,LGSZENDLINE + push rax + mov rcx, offset sBuffer + mov rdx,BUFFERSIZE + mov r8,9 + call grouperChaines + add rsp,8 * 2 * 9 + + mov rcx, offset sBuffer + mov rdx,rax + call afficherConsole + + inc rbx + cmp rbx,NBLIGNES + jle lineLoop + + mov rcx, offset szarrayend + mov rdx,LGSZARRAYEND + call afficherConsole + + + mov rcx, offset szRetourLigne + mov rdx,1 + call afficherConsole + + +finProgramme: + afficherLib "Programm end." + sub rsp,28h + mov rcx,0 ; return code + call ExitProcess +main ENDP + +;************************************** +; console display +;************************************** +; rcx : string address +; rdx : length string +afficherConsole: + push rbx + push r12 + sub rsp,28h ; 40 bytes on stack (shadow variables) + mov rbx,rcx ; string address + mov r12,rdx ; size string + + cmp QWORD ptr hConsole,0 ; console handle ? + jne @B3 + mov rcx,STD_OUTPUT_HANDLE + call GetStdHandle ; load console handle + mov hConsole, rax ; save in data +@B3: + mov rcx,hconsole ; handle + mov rdx,rbx ; string address + mov r8,r12 ; string length + mov r9,0 ; + + sub rsp,8 ; stack alignement (one push) + push 0 + sub rsp,20h ; stack for shadow variable + call WriteFile ; winapi function + add rsp,20h + add rsp,10h ; 1 push and alignement + add rsp,28h ; stack alignement + pop r12 + pop rbx + ret +;*************************************************** +;conversion to unsigned base 10 +;with removal of unnecessary zeros +;and left shift +;**************************************************** +; rcx : value to convert +; rdx : conversion area address length > 22 +LONGUEUR equ 24 +conversion10: + push rbx + push rdi + mov rdi,rdx ; conversion area address + mov BYTE ptr [rdi+LONGUEUR],0 ; 0 final conversion area + mov rax,rcx ; value + mov rcx,LONGUEUR-1 + mov rbx ,10 +CA1: ; loop begin + mov rdx,0 ; division rax by 10 + div rbx + add rdx,'0' ; remainder conversion ascii + mov byte ptr [rdi+rcx],dl + dec rcx + cmp rax,0 ; end ? + jne CA1 + xor rax,rax + inc rcx +CA5: ; copy loop + mov dl,[rdi+rcx] ; load a result character + mov byte ptr [rdi+rax],dl ; and store at conversion area begin + inc rcx + inc rax + cmp rcx,LONGUEUR ; loop if not zero final + jle CA5 + pop rdi + pop rbx + ret +;************************************** +; generate random number +;************************************** +; rcx number limit +randomNumber: + mov rax,0 + cmp rcx,0 + je randfin + mov rax, qGraine ; load seed + mov r8,qNbDep1 + mov rdx,qNbDep2 + mul r8 + add rax,rdx + mov qGraine,rax ; store new seed + inc rcx + mov rdx,0 + div rcx + mov rax,rdx ; result = remainder +randfin: + ret +;*************************************************** +; string concatenation +;************************************************** +; rcx destination area address +; rdx destination area length +; r8 strings number +; r9 0 +; on stack address and length of each string +; in order of insertion +grouperChaines: + enter 0,0 + push rbx + push r12 + push r13 + cmp r8,0 + je fingrp + mov r12,rdx + mov r9,0 ; indice strings + mov r10,0 ; number of characters inserted +bouclezone: + mov r13,r8 + shl r13,1 + mov rbx,[rbp+8+(r13 * 8)] ; string address + mov rax,[rbp+(r13 * 8)] ; sring length + mov r11,0 +bouclecopie: ; loop string copy + mov dl,byte ptr[rbx+r11] + mov byte ptr[rcx+r10],dl + inc r11 + cmp r11,rax + jg finbouclecopie + inc r10 ;number of characters inserted + cmp r10,r12 ; max? + jge erreur + jmp bouclecopie +finbouclecopie: + dec r8 ; other string + jnz bouclezone + + mov rax,r10 ; return size final string + jmp fingrp +erreur: + afficherLib "reception area too small" + mov rax,0 +fingrp: + pop r13 + pop r12 + pop rbx + leave + ret + +end diff --git a/Task/Create-an-object-at-a-given-address/Ada/create-an-object-at-a-given-address-1.ada b/Task/Create-an-object-at-a-given-address/Ada/create-an-object-at-a-given-address-1.adb similarity index 100% rename from Task/Create-an-object-at-a-given-address/Ada/create-an-object-at-a-given-address-1.ada rename to Task/Create-an-object-at-a-given-address/Ada/create-an-object-at-a-given-address-1.adb diff --git a/Task/Create-an-object-at-a-given-address/Ada/create-an-object-at-a-given-address-2.ada b/Task/Create-an-object-at-a-given-address/Ada/create-an-object-at-a-given-address-2.adb similarity index 100% rename from Task/Create-an-object-at-a-given-address/Ada/create-an-object-at-a-given-address-2.ada rename to Task/Create-an-object-at-a-given-address/Ada/create-an-object-at-a-given-address-2.adb diff --git a/Task/Create-an-object-at-a-given-address/COBOL/create-an-object-at-a-given-address.cobol b/Task/Create-an-object-at-a-given-address/COBOL/create-an-object-at-a-given-address.cob similarity index 100% rename from Task/Create-an-object-at-a-given-address/COBOL/create-an-object-at-a-given-address.cobol rename to Task/Create-an-object-at-a-given-address/COBOL/create-an-object-at-a-given-address.cob diff --git a/Task/Create-an-object-at-a-given-address/Delphi/create-an-object-at-a-given-address.delphi b/Task/Create-an-object-at-a-given-address/Delphi/create-an-object-at-a-given-address.pas similarity index 100% rename from Task/Create-an-object-at-a-given-address/Delphi/create-an-object-at-a-given-address.delphi rename to Task/Create-an-object-at-a-given-address/Delphi/create-an-object-at-a-given-address.pas diff --git a/Task/Create-an-object-at-a-given-address/Julia/create-an-object-at-a-given-address.julia b/Task/Create-an-object-at-a-given-address/Julia/create-an-object-at-a-given-address.jl similarity index 100% rename from Task/Create-an-object-at-a-given-address/Julia/create-an-object-at-a-given-address.julia rename to Task/Create-an-object-at-a-given-address/Julia/create-an-object-at-a-given-address.jl diff --git a/Task/Create-an-object-at-a-given-address/Kotlin/create-an-object-at-a-given-address.kotlin b/Task/Create-an-object-at-a-given-address/Kotlin/create-an-object-at-a-given-address.kts similarity index 100% rename from Task/Create-an-object-at-a-given-address/Kotlin/create-an-object-at-a-given-address.kotlin rename to Task/Create-an-object-at-a-given-address/Kotlin/create-an-object-at-a-given-address.kts diff --git a/Task/Create-an-object-at-a-given-address/PascalABC.NET/create-an-object-at-a-given-address.pas b/Task/Create-an-object-at-a-given-address/PascalABC.NET/create-an-object-at-a-given-address.pas new file mode 100644 index 0000000000..1feef12947 --- /dev/null +++ b/Task/Create-an-object-at-a-given-address/PascalABC.NET/create-an-object-at-a-given-address.pas @@ -0,0 +1,12 @@ +begin + var pi: ^integer; + New(pi); + pi^ := 3; + Writeln(pi,' ',pi^); + pi^ := 5; + Writeln(pi,' ',pi^); + var pi1: ^integer := pi; + pi1^ := 666; + Writeln(pi1,' ',pi1^); + Writeln(pi,' ',pi^); +end. diff --git a/Task/Create-an-object-at-a-given-address/Rust/create-an-object-at-a-given-address.rust b/Task/Create-an-object-at-a-given-address/Rust/create-an-object-at-a-given-address.rs similarity index 100% rename from Task/Create-an-object-at-a-given-address/Rust/create-an-object-at-a-given-address.rust rename to Task/Create-an-object-at-a-given-address/Rust/create-an-object-at-a-given-address.rs diff --git a/Task/Create-an-object-at-a-given-address/V-(Vlang)/create-an-object-at-a-given-address.v b/Task/Create-an-object-at-a-given-address/V-(Vlang)/create-an-object-at-a-given-address.v new file mode 100644 index 0000000000..f0895f2e33 --- /dev/null +++ b/Task/Create-an-object-at-a-given-address/V-(Vlang)/create-an-object-at-a-given-address.v @@ -0,0 +1,22 @@ +fn main() { + // create an integer object + + mut target := 42 + mut target_ref := &target + + println("Here is an integer: ${target}") + + // print the machine address of the object + + println("And its reference is: ${target_ref}") + + // take the address of the object and create another integer object at this address + + unsafe{(*target_ref) = 69} + + println("Newly assigned value is: ${*target_ref}") + + // print the value of this object to verify that it is same as one of the origin + + println("Compared with referent: ${target}") +} diff --git a/Task/Create-an-object-at-a-given-address/XPL0/create-an-object-at-a-given-address.xpl0 b/Task/Create-an-object-at-a-given-address/XPL0/create-an-object-at-a-given-address.xpl0 new file mode 100644 index 0000000000..fd3ff6cb00 --- /dev/null +++ b/Task/Create-an-object-at-a-given-address/XPL0/create-an-object-at-a-given-address.xpl0 @@ -0,0 +1,15 @@ +int Obj; \create an integer object +char Addr; +[HexOut(0, @Obj); \print the machine address of the object (relative to some base) +CrLf(0); +Addr:= @Obj; \take the address of the object and +Addr(0):= $78; \ create another integer object at this address +Addr(1):= $56; +Addr(2):= $34; +Addr(3):= $12; +HexOut(0, Obj); \print the value of this object to verify that +CrLf(0); \ it is same as one of the origin +Obj:= $DEADBEEF; \change the value of the origin and verify it again +HexOut(0, Obj); +CrLf(0); +] diff --git a/Task/Cuban-primes/AWK/cuban-primes.awk b/Task/Cuban-primes/AWK/cuban-primes.awk new file mode 100644 index 0000000000..93acddba9e --- /dev/null +++ b/Task/Cuban-primes/AWK/cuban-primes.awk @@ -0,0 +1,28 @@ +# syntax: GAWK -f CUBAN_PRIMES.AWK +# converted from EasyLang +BEGIN { + limit = 200 + printf("The first %d cuban primes are:\n",limit) + while (count < 10000 ) { + i++ + di = 3 * i * (i + 1) + 1 + if (is_prime(di) == 1) { + if (++count <= limit) { + printf("%8d%s",di,count%10?"":"\n") + } + } + } + printf("\ncuban prime # %d is: %'d\n",count,di) + exit(0) +} +function is_prime(x, i) { + if (x <= 1) { + return(0) + } + for (i=2; i<=int(sqrt(x)); i++) { + if (x % i == 0) { + return(0) + } + } + return(1) +} diff --git a/Task/Cuban-primes/Ada/cuban-primes.adb b/Task/Cuban-primes/Ada/cuban-primes.adb new file mode 100644 index 0000000000..d824856bc4 --- /dev/null +++ b/Task/Cuban-primes/Ada/cuban-primes.adb @@ -0,0 +1,136 @@ +-- Rosetta Code Task written in Ada +-- Cuban primes (related to "Cubes", not "Cubans") +-- https://rosettacode.org/wiki/Cuban_primes +-- July 2024, R. B. E. + +-- Using this Cuban Primes Definition: primes of the form: n^3 - (n-1)^3. + +-- ToDo: +-- Commatize the results (an advanced subtask) +-- Could replace the "activity dots" generated during the big calculations with a spinner + +-- NOTE: Using GNAT Big_Numbers package. +-- Takes a very long time to generate the 100_000th cuban prime: about 75 minutes on a M1 Mac Mini. + +pragma Ada_2022; +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; +with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions; +with Ada.Numerics.Big_Numbers.Big_Integers; use Ada.Numerics.Big_Numbers.Big_Integers; +with Ada.Strings; use Ada.Strings; +with Ada.Strings.Fixed; use Ada.Strings.Fixed; +with Ada.Strings.Maps; use Ada.Strings.Maps; +with Ada.Real_Time; use Ada.Real_Time; + +procedure Cuban_Primes is + + function Is_Prime (A : Positive) return Boolean is + D : Positive; + begin + if A < 2 then + return False; + end if; + if A in 2 .. 3 then + return True; + end if; + if A mod 2 = 0 then + return False; + end if; + if A mod 3 = 0 then + return False; + end if; + D := 5; + while D * D <= A loop + if A mod D = 0 then + return False; + end if; + D := D + 2; + if A mod D = 0 then + return False; + end if; + D := D + 4; + end loop; + return True; + end Is_Prime; + + function Is_Prime (A : Big_Natural) return Boolean is + D : Big_Natural; + B0 : constant Big_Natural := To_Big_Integer (0); + B1 : constant Big_Natural := To_Big_Integer (1); + B2 : constant Big_Natural := To_Big_Integer (2); + B3 : constant Big_Natural := To_Big_Integer (3); + B4 : constant Big_Natural := To_Big_Integer (4); + B5 : constant Big_Natural := To_Big_Integer (5); + begin + if A < B2 then + return False; + end if; + if (A = B2) or (A = B3) then + return True; + end if; + if A mod B2 = B0 then + return False; + end if; + if A mod B3 = B0 then + return False; + end if; + D := B5; + while D * D <= A loop + if A mod D = B0 then + return False; + end if; + D := D + B2; + if A mod D = B0 then + return False; + end if; + D := D + B4; + end loop; + return True; + end Is_Prime; + + Cuban_Count : Natural := 1; + Candidate : Natural; + Big_Candidate : Big_Natural; + Max_Cuban_for_the_Table : constant Integer := 200; + Max_Cuban_below_the_Table : constant Integer := 100_000; + Start_Time, Stop_Time : Time; + Elapsed_Time : Time_Span; + +begin + Put ("The first "); + Put (Max_Cuban_for_the_Table, 1); + Put_Line (" Cuban Primes..."); + for I in 1 .. Integer'Last loop + Candidate := ((I + 1) ** 3) - (I ** 3); + if Is_Prime (Candidate) then + Put (Candidate, 8); + if ((Cuban_Count rem 14) = 0) then + New_Line; + end if; + Cuban_Count := Cuban_Count + 1; + end if; + exit when Cuban_Count > Max_Cuban_for_the_Table; + end loop; + New_Line (2); + Cuban_Count := 1; + Start_Time := Clock; + Put ("The "); + Put (Max_Cuban_below_the_Table, 1); + Put ("th Cuban Prime is: "); + for I in 1 .. Integer'Last loop + Big_Candidate := (((To_Big_Integer (I) + 1) ** 3) - (To_Big_Integer (I) ** 3)); + if Is_Prime (Big_Candidate) then + Cuban_Count := Cuban_Count + 1; + if (Cuban_Count rem 10_000) = 0 then + Put ("."); + end if; + end if; + exit when Cuban_Count = Max_Cuban_below_the_Table; + end loop; + New_Line; + Put (Trim (To_String (Big_Candidate), Right)); + Stop_Time := Clock; + Elapsed_Time := Stop_Time - Start_Time; + New_Line; + Put_Line ("Elapsed time to calculate: " & Duration'Image (To_Duration (Elapsed_Time)) & " seconds"); +end Cuban_Primes; diff --git a/Task/Cuban-primes/EasyLang/cuban-primes.easy b/Task/Cuban-primes/EasyLang/cuban-primes.easy index 69a869b15b..8140fa46a5 100644 --- a/Task/Cuban-primes/EasyLang/cuban-primes.easy +++ b/Task/Cuban-primes/EasyLang/cuban-primes.easy @@ -1,27 +1,24 @@ -fastfunc isprim_odd num . - i = 3 +fastfunc isprim num . + if num mod 2 = 0 : return 0 + if num mod 3 = 0 : return 0 + i = 5 while i <= sqrt num - if num mod i = 0 - return 0 - . + if num mod i = 0 : return 0 i += 2 + if num mod i = 0 : return 0 + i += 4 . return 1 . -numfmt 0 7 i = 1 -while cnt < 100000 +while cnt < 50000 di = 3 * i * (i + 1) + 1 - if isprim_odd di = 1 + if isprim di = 1 cnt += 1 - if cnt <= 200 - write di & " " - if cnt mod 5 = 0 - print "" - . - . + if cnt <= 200 : write di & " " . i += 1 . print "" +print "" print di diff --git a/Task/Cuban-primes/Fortran/cuban-primes.f b/Task/Cuban-primes/Fortran/cuban-primes.f new file mode 100644 index 0000000000..d2dcee4458 --- /dev/null +++ b/Task/Cuban-primes/Fortran/cuban-primes.f @@ -0,0 +1,201 @@ +! Cuban Prime Numbers +! tested with GNU Fortran (Ubuntu 14.2.0-19ubuntu2) 14.2.0 on Kubuntu 25.04 +! +! Note that both intel ifx and VSI Fortran do not compile this code because they do not +! support 16-byte-integers. +! +! U.B., September 2025 +! + +program CubanPrimes + implicit none + + integer, parameter :: llint=16 + integer, parameter ::strLen = 20 + + integer (kind=llint) :: nc = 0, i=0, di + character (len=strLen) :: sdi ! for formatted output of di + + write (*, *) 'The first 200 cuban prime numbers are:' + do while (nc .lt. 100001) + di = diff_cubes(i) + if (isprime(di)) then + nc = nc + 1 + if (nc .le. 200) then + sdi = GroupedDigits (di, 10) + write (*, '(A10)', advance='no') sdi + if (mod (nc,10) .eq. 0 ) then + write (*,*) + end if + end if + if (nc .eq. 100000) then + sdi = GroupedDigits (di, 18) + write (*,'(//"The 100000th cuban prime number is: ", A)') sdi + exit + end if + end if + i = i + 1 + end do + + + contains + + !------------------------------------------------ + ! Calculate difference (n+1)³ - n³ = 3n² + 3n + 1 + !------------------------------------------------ + function diff_cubes( n ) result (n3) + integer (kind=llint),intent(in) ::n + integer (kind=llint) :: n3 + n3 = 3*n*(n+1) + 1 + end function + + + ! ---------------------------------------------------------------- + ! Fortran does not have a way to use locales for output. + ! Manual insert of separating commas such as 1,345,678 for 1345678 + ! ---------------------------------------------------------------- + function GroupedDigits (n, width) result (outStr) + integer(kind=llint), intent (in) :: n + integer :: width + character (len=width) :: outStr + character (len=2*strLen) :: workStr + integer :: ii, jj, cnt, trueLen + + + ! Write n into a string, then copy the digits to a second string, + ! inserting separater after every 3 digits. + write (workStr, '(i0)') n + ! Adjust left, then cutoff trailing blanks + workstr = adjustl (workstr) + trueLen = len_trim (workStr) + + outStr = ' ' + jj = width + cnt = 0 + do ii=trueLen, 1, -1 ! Copy backwards for correct grouping. + outStr (jj:jj) = workStr (ii:ii) + jj = jj -1 + cnt = cnt + 1 + ! Insert comma after 3 digits, but only if more digits follow. + if (mod (cnt, 3) .eq. 0 .and. ii .gt. 1 .and. workStr(ii-1:ii-1) .ne. ' ') then + outStr (jj:jj) = ',' + jj = jj - 1 + endif + end do + + end function GroupedDigits + + + + + + + ! ---------------------------------------- + ! Miller-Rabin test if n is a prime number + ! ---------------------------------------- + function isPrime(n) result (YN) + + integer(kind=llint), intent(in) ::n + logical :: YN + integer (kind=llint) :: ar (5), i + + ! Early return in most trivial cases + if (n .le. 1) then ! Too small + YN=.false. + return + endif + if (n .eq. 2) then ! 2 is prime + YN=.true. + return + endif + if (mod (n , 2) .eq. 0) then ! all other even number are not prime + YN=.false. + return + endif + if (n .lt. 9) then ! all odd numbers < 9 are prime + YN=.true. + return + endif + if (mod (n , 3) .eq. 0) then ! multiples of 3 aren't prime + YN=.false. + return + endif + if (mod (n , 5) .eq. 0) then ! multiples of 5 aren't prime + YN=.false. + return + endif + + ! these 5 bases are required and sufficient to test numbers up to 2,152,302,898,747 + ar(1) = 2 + ar(2) = 3 + ar(3) = 5 + ar(4) = 7 + ar(5) = 11 + do i = 1, 5 + if (Witness(ar(i), n)) then + YN=.false. ! Not prime + return + endif + end do + YN= .true. ! prime + + end function isPrime + + ! ------------------------------------- + ! helper function for Miller Rabin test + ! ------------------------------------- + function Witness(a, n) result (YN) + + integer (kind=llint) , intent(in) :: a + integer (kind=llint) , intent(in) :: n + + + integer (kind=llint) :: t, u, i + logical :: YN + integer (kind=llint) :: xi1, xi2 + + t = 0 + u = n - 1 + do while (iand(u , 1_llint) .eq. 0) + t = t + 1 + u = u / 2 + end do + + xi1 = ModularExp(a, u, n); + do i = 0, t-1 + xi2 = mod (xi1 * xi1 , n) + if ((xi2 .eq. 1) .and. (xi1 .ne. 1) .and. (xi1 .ne. (n - 1))) then + YN = .true. + return + endif + xi1 = xi2 + end do + if (xi1 .ne. 1) then + YN=.true. + else + YN = .false. + endif + end function Witness + + ! ------------------------------------- + ! helper function for Miller Rabin test + ! ------------------------------------- + function ModularExp(a, b, n) result(d) + + integer(kind=llint) , intent(in) :: a,b,n + integer (kind=llint) :: d + integer (kind=llint) :: i, k + d = 1 + k = 0 + do while (ishft (b, -k) .gt. 0) + k = k + 1 + end do + do i = k - 1, 0, -1 + d = mod (d*d, n) + if (iand (ishft (b, -i) , 1_llint) .gt. 0) d = mod (d*a ,n); + end do + + end function ModularExp + + +end program diff --git a/Task/Cuban-primes/FutureBasic/cuban-primes.basic b/Task/Cuban-primes/FutureBasic/cuban-primes.basic new file mode 100644 index 0000000000..3bbad2af09 --- /dev/null +++ b/Task/Cuban-primes/FutureBasic/cuban-primes.basic @@ -0,0 +1,40 @@ +BBOOL local fn IsPrime( p as UInt64 ) + if ( p < 2 ) then return NO + if ( p % 2 == 0 ) then return ( p == 2 ) + UInt64 limit = fn sqrt( (double)p ) + for UInt64 i = 3 to limit step 2 + if ( p % i == 0 ) then return NO + next +end fn = YES + +local fn CubanPrimes( howMany as NSUInteger ) + CFMutableArrayRef cubanPrimes = fn MutableArrayNew + UInt64 n = 1 + + while ( fn ArrayCount( cubanPrimes ) < howMany ) + UInt64 p = 3 * n * n + 3 * n + 1 + if ( fn IsPrime( p ) ) + MutableArrayAddObject( cubanPrimes, @(p) ) + end if + n++ + wend + + printf @"\nFirst 200 Cuban primes:\n" + for NSUInteger i = 0 to fn ArrayCount( cubanPrimes ) - 1 + printf @"%7lu\b", fn NumberUnsignedLongValue( cubanPrimes[i] ) + if ( i < fn ArrayCount( cubanPrimes ) - 1 ) + if ( i % 8 == 7 ) + print + else + print @"\t" + end if + end if + next + print +end fn + +window 1, @"cuban Primes", ( 0, 0, 630, 440 ) + +fn CubanPrimes( 200 ) + +HandleEvents diff --git a/Task/Cuban-primes/JavaScript/cuban-primes.js b/Task/Cuban-primes/JavaScript/cuban-primes.js new file mode 100644 index 0000000000..86fd7b9358 --- /dev/null +++ b/Task/Cuban-primes/JavaScript/cuban-primes.js @@ -0,0 +1,68 @@ +const MAX = 1400000; +const primes = new Array(MAX); + +function preCompute() { + // Initialize sieve + for (let i = 2; i < MAX; i++) { + primes[i] = true; + } + + // Sieve of Eratosthenes + for (let i = 2; i < MAX; i++) { + if (primes[i]) { + for (let j = 2 * i; j < MAX; j += i) { + primes[j] = false; + } + } + } +} + +function isPrime(n) { + if (n < MAX) { + return primes[n]; + } + const max = Math.floor(Math.sqrt(n)); + for (let i = 3; i <= max; i++) { + if (primes[i] && n % i === 0) { + return false; + } + } + return true; +} + +function cubanPrime(n, display) { + let count = 0; + let result = 0; + let output = ''; + + for (let i = 0; count < n; i++) { + const test = 1 + 3 * i * (i + 1); + if (isPrime(test)) { + count++; + result = test; + if (display) { + const formatted = test.toLocaleString('en-US').padStart(10); + output += formatted + (count % 10 === 0 ? '\n' : ''); + } + } + } + + if (display) { + console.log(output); + } + return result; +} + +// Main execution +preCompute(); + +// First 200 Cuban primes +cubanPrime(200, true); +console.log(); + +// Specific Cuban primes +for (let i = 1; i <= 5; i++) { + const max = Math.pow(10, i); + const prime = cubanPrime(max, false); + console.log(`${max.toLocaleString('en-US')}-th cuban prime = ${prime.toLocaleString('en-US')}`); +} diff --git a/Task/Cuban-primes/Julia/cuban-primes.julia b/Task/Cuban-primes/Julia/cuban-primes.jl similarity index 100% rename from Task/Cuban-primes/Julia/cuban-primes.julia rename to Task/Cuban-primes/Julia/cuban-primes.jl diff --git a/Task/Cuban-primes/Kotlin/cuban-primes.kotlin b/Task/Cuban-primes/Kotlin/cuban-primes.kts similarity index 100% rename from Task/Cuban-primes/Kotlin/cuban-primes.kotlin rename to Task/Cuban-primes/Kotlin/cuban-primes.kts diff --git a/Task/Cuban-primes/OCaml/cuban-primes.ml b/Task/Cuban-primes/OCaml/cuban-primes.ml new file mode 100644 index 0000000000..af8c106059 --- /dev/null +++ b/Task/Cuban-primes/OCaml/cuban-primes.ml @@ -0,0 +1,51 @@ +let is_prime (n : int) : bool = + if n = 2 then true else if n < 2 || n mod 2 = 0 then false else + let lim = (n |> float_of_int |> sqrt |> int_of_float) + 1 in + let rec loop = function + | i when i > lim -> true + | i when n mod i = 0 -> false + | i -> loop (i + 2) + in loop 3 + +let char_list_of_string s = List.init (String.length s) (String.get s) + +let commatize (str : string) : string = + let revchars = List.rev (char_list_of_string str) in + let rec take_threes = function + | s, c1 :: c2 :: c3 :: rest -> + take_threes ([c3; c2; c1] :: s, rest) + | ss, rest -> if rest = [] then ss else List.rev rest :: ss + in take_threes ([], List.map Char.escaped revchars) + |> List.map (String.concat "") |> String.concat "," + +let cube (n: int) : int = n * n * n + +let scan_for_cubans (num : int) : int list = + let rec loop = function + | n, ps when List.length ps >= num -> ps + | n, ps -> + let c = cube (n + 1) - cube n in + if is_prime c then loop (n + 1, c :: ps) + else loop (n + 1, ps) in + loop (1, []) |> List.rev + +let nth_cuban (n : int) : int = + let rec loop = function + | i, c, p when c = n -> p + | i, c, p -> + let k = cube (i + 1) - cube i in + if is_prime k then loop (i + 1, c + 1, k) + else loop (i + 1, c, p) in + loop (0, 0, 0) + +let () = + print_endline "The first 200 cuban primes are: "; + scan_for_cubans 200 + |> List.map string_of_int + |> List.map commatize + |> String.concat " | " + |> Printf.printf "[%s]\n\n"; + nth_cuban 100_000 + |> string_of_int + |> commatize + |> Printf.printf "The 100,000th cuban prime is %s\n" diff --git a/Task/Cuban-primes/PascalABC.NET/cuban-primes.pas b/Task/Cuban-primes/PascalABC.NET/cuban-primes.pas new file mode 100644 index 0000000000..f54de0f00f --- /dev/null +++ b/Task/Cuban-primes/PascalABC.NET/cuban-primes.pas @@ -0,0 +1,67 @@ +const + cutOff = 200; + bigUn = 100000; + chunks = 50; + little = bigUn div chunks; + +begin + writeln('The first ', cutOff, ' cuban primes:'); + var primes := |int64(3), int64(5)|.ToList; + var c := 0; + var u: int64 := 0; + var v: int64 := 1; + var showEach := true; + while true do + begin + var found := false; + u += 6; + v += u; + var mx := real(v).sqrt.ceil; + foreach var item in primes do + begin + if item > mx then break; + if v mod item = 0 then + begin + found := true; + break + end; + end; + if not found then + begin + c += 1; + if showEach then + begin + for var z := primes.last + 2 to v - 2 step 2 do + begin + var fnd := false; + foreach var item in primes do + begin + if item > mx then break; + if z mod item = 0 then + begin + fnd := true; + break + end; + end; + if not fnd then primes.Add(z); + end; + primes.Add(v); + write(v:9); + if c mod 10 = 0 then writeln; + if c = cutOff then + begin + showEach := false; + write('Progress to the ', bigUn, 'th cuban prime: ') + end; + end; + if c mod little = 0 then + begin + write('.'); + if c = bigUn then break; + end; + end; + end; + writeln(); + writeln('The ', c, 'th cuban prime is ', v); + writeln('Computation time was ', milliseconds / 1000, ' seconds'); +end. diff --git a/Task/Cuban-primes/Phix/cuban-primes.phix b/Task/Cuban-primes/Phix/cuban-primes.phix index 29da36d962..7aa90398b7 100644 --- a/Task/Cuban-primes/Phix/cuban-primes.phix +++ b/Task/Cuban-primes/Phix/cuban-primes.phix @@ -1,34 +1,32 @@ -(phixonline)--> - with javascript_semantics - include mpfr.e - integer np = 0, - i = 2 - mpz p3 = mpz_init(1*1*1), - i3 = mpz_init(), - p = mpz_init(), - pn = mpz_init() +with javascript_semantics +include mpfr.e +integer np = 0, + i = 2 +mpz p3 = mpz_init(1*1*1), + i3 = mpz_init(), + p = mpz_init(), + pn = mpz_init() - printf(1,"The first 200 cuban primes are:\n") - sequence first200 = {} - atom t0 = time() - constant lim = iff(platform()=JS?10000:100000) - while np<lim do - mpz_ui_pow_ui(i3,i,3) - mpz_sub(p,i3,p3) - if mpz_prime(p) then - mpz_set(pn,p) - np += 1 - if np<=200 then - first200 = append(first200,sprintf("%,9d",mpz_get_integer(pn))) - if mod(np,10)=0 then - printf(1,"%s\n",join(first200[-10..-1])) - end if - end if - end if - mpz_set(p3,i3) - i += 1 - end while - printf(1,"\nThe %,dth cuban prime is %s\n",{np,mpz_get_str(pn,comma_fill:=true)}) - {p3,i3,p} = mpz_free({p3,i3,p}) - ?elapsed(time()-t0) - - with javascript_semantics - - atom sdn = 0, sdsum = 0, sdsumsq = 0 - - procedure sdadd(atom n) - sdn += 1 - sdsum += n - sdsumsq += n*n - end procedure - - function sdavg() - return sdsum/sdn - end function - - function sddev() - return sqrt(sdsumsq/sdn - power(sdsum/sdn,2)) - end function - - --test code: - constant testset = {2, 4, 4, 4, 5, 5, 7, 9} - integer ti - for i=1 to length(testset) do - ti = testset[i] - sdadd(ti) - printf(1,"N=%d Item=%d Avg=%5.3f StdDev=%5.3f\n",{i,ti,sdavg(),sddev()}) - end for - - with javascript_semantics - atom t0 = time() - function bump(sequence half) - -- add a digit to valid halves - -- eg {0} --> {1..9} (no zeroes) - -- --> {11..99} ("") - -- --> {111..999}, etc - sequence res = {} - for i=1 to length(half) do - integer hi = half[i]*10 - for digit=1 to 9 do - res &= hi+digit - end for - end for - return res - end function +with javascript_semantics +atom t0 = time() +function bump(sequence half) + -- add a digit to valid halves + -- eg {0} --> {1..9} (no zeroes) + -- --> {11..99} ("") + -- --> {111..999}, etc + sequence res = {} + for i=1 to length(half) do + integer hi = half[i]*10 + for digit=1 to 9 do + res &= hi+digit + end for + end for + return res +end function - procedure cyclops(string s="") - sequence res = {}, - half = {0} -- valid digits, see bump() - integer left = 1, -- half[] before the 0 - right = 0, -- half[] after the 0 - hlen = 1, -- length(half) - cpow = 10, -- cyclops power (of 10) - bcpow = 1, -- blind cyclops power - cn = 0 -- cyclops number (scratch) - bool valid = false, - bPrime = match("prime",s), - bBlind = match("blind",s), - bPalin = match("palindromic",s) - while length(res)<50 or cn<=1e7 or not valid do - right += 1 - if right>hlen then - right = 1 - left += 1 - if left>hlen then - half = bump(half) - hlen = length(half) - cpow *= 10 - bcpow *= 10 - left = 1 - end if - end if - integer lh = half[left], - rh = half[right] - cn = lh*cpow+rh -- cyclops number - valid = not bPrime or is_prime(cn) - if valid and bBlind then - valid = is_prime(lh*bcpow+rh) - end if - if valid and bPalin then - valid = sprintf("%d",lh) == reverse(sprintf("%d",rh)) - end if - if valid then - res = append(res,sprintf("%7d",cn)) - end if - end while - printf(1,"First 50 %scyclops numbers:\n%s\n",{s,join_by(res[1..50],1,10)}) - printf(1,"First %scyclops number > 10,000,000: %s at (one based) index: %d\n\n", - {s,res[$],length(res)}) - end procedure +procedure cyclops(string s="") + sequence res = {}, + half = {0} -- valid digits, see bump() + integer left = 1, -- half[] before the 0 + right = 0, -- half[] after the 0 + hlen = 1, -- length(half) + cpow = 10, -- cyclops power (of 10) + bcpow = 1, -- blind cyclops power + cn = 0 -- cyclops number (scratch) + bool valid = false, + bPrime = match("prime",s), + bBlind = match("blind",s), + bPalin = match("palindromic",s) + while length(res)<50 or cn<=1e7 or not valid do + right += 1 + if right>hlen then + right = 1 + left += 1 + if left>hlen then + half = bump(half) + hlen = length(half) + cpow *= 10 + bcpow *= 10 + left = 1 + end if + end if + integer lh = half[left], + rh = half[right] + cn = lh*cpow+rh -- cyclops number + valid = not bPrime or is_prime(cn) + if valid and bBlind then + valid = is_prime(lh*bcpow+rh) + end if + if valid and bPalin then + valid = sprintf("%d",lh) == reverse(sprintf("%d",rh)) + end if + if valid then + res = append(res,sprintf("%7d",cn)) + end if + end while + printf(1,"First 50 %scyclops numbers:\n%s\n",{s,join_by(res[1..50],1,10)}) + printf(1,"First %scyclops number > 10,000,000: %s at (one based) index: %d\n\n", + {s,res[$],length(res)}) +end procedure - cyclops() - cyclops("prime ") - cyclops("blind prime ") - cyclops("palindromic prime ") - ?elapsed(time()-t0) - - with javascript_semantics - atom t0 = time() - function bump(sequence half) -- (exactly the same as above) - -- add a digit to valid halves - -- eg {0} --> {1..9} (no zeroes) - -- --> {11..99} ("") - -- --> {111..999}, etc - sequence res = {} - for i=1 to length(half) do - integer hi = half[i]*10 - for digit=1 to 9 do - res &= hi+digit - end for - end for - return res - end function +with javascript_semantics +atom t0 = time() - sequence half = {0} -- valid digits, see bump() - integer hlen = 1, - cpow = 10 -- cyclops power (of 10) - integer n = 1_000_000_000 - atom hlen2 = 1 - while n>hlen2 do - n -= hlen2 - half = bump(half) - hlen = length(half) - hlen2 = power(hlen,2) - cpow *= 10 - end while - integer left = floor(n/hlen)+1, -- half[] before the 0 - right = remainder(n,hlen)+1 -- half[] after the 0 - string fmt = "The 1,000,000,000th cyclops number is %d (%s)\n", - e = elapsed(time()-t0) - printf(1,fmt,{half[left]*cpow+half[right],e}) - - without js - include builtins\cffi.e +without js +include builtins\cffi.e - constant AF_UNSPEC = 0, - -- AF_INET = 2, - -- AF_INET6 = 23, - -- SOCK_STREAM = 1, - SOCK_DGRAM = 2, - -- IPPROTO_TCP = 6, - NI_MAXHOST = 1025, - NI_NUMERICHOST = iff(platform()=LINUX?1:2) +constant AF_UNSPEC = 0, +-- AF_INET = 2, +-- AF_INET6 = 23, +-- SOCK_STREAM = 1, + SOCK_DGRAM = 2, +-- IPPROTO_TCP = 6, + NI_MAXHOST = 1025, + NI_NUMERICHOST = iff(platform()=LINUX?1:2) - constant tWAD = """ - typedef struct WSAData { - WORD wVersion; - WORD wHighVersion; - char szDescription[257]; - char szSystemStatus[129]; - unsigned short iMaxSockets; - unsigned short iMaxUdpDg; - char *lpVendorInfo; - } WSADATA, *LPWSADATA; - """, - tWAS = """ - int WSAStartup( - _In_ WORD wVersionRequested, - _Out_ LPWSADATA lpWSAData - ); - """, - tWAC = """ - int WSACleanup(void); - """, - tAI_W=""" - typedef struct addrinfo { - int ai_flags; - int ai_family; - int ai_socktype; - int ai_protocol; - size_t ai_addrlen; - char *ai_canonname; - struct sockaddr *ai_addr; - struct addrinfo *ai_next; - } ADDRINFOA, *PADDRINFOA; - """, - tAI_L=""" - typedef struct addrinfo { - int ai_flags; - int ai_family; - int ai_socktype; - int ai_protocol; - int ai_addrlen; - struct sockaddr *ai_addr; - char *ai_canonname; - struct addrinfo *ai_next; - }; - """, - tGAI = """ - int getaddrinfo( - _In_opt_ PCSTR pNodeName, - _In_opt_ PCSTR pServiceName, - _In_opt_ const ADDRINFOA *pHints, - _Out_ PADDRINFOA *ppResult - ); - """, - --int getaddrinfo(const char *node, const char *service, - -- const struct addrinfo *hints, - -- struct addrinfo **res); - tGNI = """ - int getnameinfo( - _In_ sockaddr *sa, - _In_ int salen, - _Out_ char *host, - _In_ DWORD hostlen, - _Out_ char *serv, - _In_ DWORD servlen, - _In_ int flags - ); - """, - --int getnameinfo(const struct sockaddr *addr, socklen_t addrlen, - -- char *host, socklen_t hostlen, - -- char *serv, socklen_t servlen, int flags); - tFAI = """ - void freeaddrinfo( - _In_ struct addrinfo *ai - ); - """ - --void freeaddrinfo(struct addrinfo *res); +constant tWAD = """ +typedef struct WSAData { + WORD wVersion; + WORD wHighVersion; + char szDescription[257]; + char szSystemStatus[129]; + unsigned short iMaxSockets; + unsigned short iMaxUdpDg; + char *lpVendorInfo; +} WSADATA, *LPWSADATA; +""", +tWAS = """ +int WSAStartup( + _In_ WORD wVersionRequested, + _Out_ LPWSADATA lpWSAData +); +""", +tWAC = """ +int WSACleanup(void); +""", +tAI_W=""" +typedef struct addrinfo { + int ai_flags; + int ai_family; + int ai_socktype; + int ai_protocol; + size_t ai_addrlen; + char *ai_canonname; + struct sockaddr *ai_addr; + struct addrinfo *ai_next; +} ADDRINFOA, *PADDRINFOA; +""", +tAI_L=""" +typedef struct addrinfo { + int ai_flags; + int ai_family; + int ai_socktype; + int ai_protocol; + int ai_addrlen; + struct sockaddr *ai_addr; + char *ai_canonname; + struct addrinfo *ai_next; +}; +""", +tGAI = """ +int getaddrinfo( + _In_opt_ PCSTR pNodeName, + _In_opt_ PCSTR pServiceName, + _In_opt_ const ADDRINFOA *pHints, + _Out_ PADDRINFOA *ppResult +); +""", +--int getaddrinfo(const char *node, const char *service, +-- const struct addrinfo *hints, +-- struct addrinfo **res); +tGNI = """ +int getnameinfo( + _In_ sockaddr *sa, + _In_ int salen, + _Out_ char *host, + _In_ DWORD hostlen, + _Out_ char *serv, + _In_ DWORD servlen, + _In_ int flags +); +""", +--int getnameinfo(const struct sockaddr *addr, socklen_t addrlen, +-- char *host, socklen_t hostlen, +-- char *serv, socklen_t servlen, int flags); +tFAI = """ +void freeaddrinfo( + _In_ struct addrinfo *ai +); +""" +--void freeaddrinfo(struct addrinfo *res); - integer xgetaddrinfo = NULL, xgetnameinfo, xfreeaddrinfo, idAI, - xwsastartup, xwsacleanup, error +integer xgetaddrinfo = NULL, xgetnameinfo, xfreeaddrinfo, idAI, + xwsastartup, xwsacleanup, error - function get_name_info(string fqdn) - if xgetaddrinfo=NULL then - atom lib - if platform()=WINDOWS then - integer idWAD = define_struct(tWAD) - atom pWAD = allocate_struct(idWAD,cleanup:=true) - lib = open_dll("Ws2_32.dll") - xwsastartup = define_cffi_func(lib,tWAS) - xwsacleanup = define_cffi_func(lib,tWAC) - error = c_func(xwsastartup,{#00020002,pWAD}) - if error then ?9/0 end if - idAI = define_struct(tAI_W) - elsif platform()=LINUX then - lib = open_dll("libc.so.6") - idAI = define_struct(tAI_L) - end if - xgetaddrinfo = define_cffi_func(lib,tGAI) - xgetnameinfo = define_cffi_func(lib,tGNI) - xfreeaddrinfo = define_cffi_proc(lib,tFAI) - end if - atom hints = allocate_struct(idAI,cleanup:=true), - res = allocate(machine_word(),cleanup:=true), - host = allocate(NI_MAXHOST,cleanup:=true) - set_struct_field(idAI,hints,"ai_family",AF_UNSPEC) - -- set_struct_field(idAI,hints,"ai_socktype",SOCK_STREAM) - set_struct_field(idAI,hints,"ai_socktype",SOCK_DGRAM) - error = c_func(xgetaddrinfo,{fqdn,NULL,hints,res}) - if error then ?9/0 end if - res = peekNS(res,machine_word(),false) - atom ptr = res - sequence results = {} - while ptr!=NULL do - atom addr = get_struct_field(idAI,ptr,"ai_addr") - integer len = get_struct_field(idAI,ptr,"ai_addrlen") - error = c_func(xgetnameinfo,{addr, len, host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST}) - if error then ?9/0 end if - results = append(results,peek_string(host)) - ptr = get_struct_field(idAI,ptr,"ai_next") - end while - c_proc(xfreeaddrinfo,{res}) - return results - end function +function get_name_info(string fqdn) + if xgetaddrinfo=NULL then + atom lib + if platform()=WINDOWS then + integer idWAD = define_struct(tWAD) + atom pWAD = allocate_struct(idWAD,cleanup:=true) + lib = open_dll("Ws2_32.dll") + xwsastartup = define_cffi_func(lib,tWAS) + xwsacleanup = define_cffi_func(lib,tWAC) + error = c_func(xwsastartup,{#00020002,pWAD}) + if error then ?9/0 end if + idAI = define_struct(tAI_W) + elsif platform()=LINUX then + lib = open_dll("libc.so.6") + idAI = define_struct(tAI_L) + end if + xgetaddrinfo = define_cffi_func(lib,tGAI) + xgetnameinfo = define_cffi_func(lib,tGNI) + xfreeaddrinfo = define_cffi_proc(lib,tFAI) + end if + atom hints = allocate_struct(idAI,cleanup:=true), + res = allocate(machine_word(),cleanup:=true), + host = allocate(NI_MAXHOST,cleanup:=true) + set_struct_field(idAI,hints,"ai_family",AF_UNSPEC) +-- set_struct_field(idAI,hints,"ai_socktype",SOCK_STREAM) + set_struct_field(idAI,hints,"ai_socktype",SOCK_DGRAM) + error = c_func(xgetaddrinfo,{fqdn,NULL,hints,res}) + if error then ?9/0 end if + res = peekNS(res,machine_word(),false) + atom ptr = res + sequence results = {} + while ptr!=NULL do + atom addr = get_struct_field(idAI,ptr,"ai_addr") + integer len = get_struct_field(idAI,ptr,"ai_addrlen") + error = c_func(xgetnameinfo,{addr, len, host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST}) + if error then ?9/0 end if + results = append(results,peek_string(host)) + ptr = get_struct_field(idAI,ptr,"ai_next") + end while + c_proc(xfreeaddrinfo,{res}) + return results +end function - procedure WSACleanup() - if platform()=WINDOWS then - error = c_func(xwsacleanup,{}) - if error then crash("WSACleanup failed: %d\n",{error}) end if - end if - end procedure +procedure WSACleanup() + if platform()=WINDOWS then + error = c_func(xwsacleanup,{}) + if error then crash("WSACleanup failed: %d\n",{error}) end if + end if +end procedure - ?get_name_info("www.kame.net") - WSACleanup() - - with javascript_semantics - include builtins\timedate.e - ?format_timedate(date(),"YYYY-MM-DD") - ?format_timedate(date(),"Dddd, Mmmm d, YYYY") - - include builtins\timedate.e - set_timedate_formats({"Mmmm d yyyy h:mmpm tz"}) - timedate td = parse_date_string("March 7 2009 7:30pm EST") - atom twelvehours = timedelta(hours:=12) - td = adjust_timedate(td,twelvehours) - ?format_timedate(td) - td = change_timezone(td,"ACDT") -- extra credit - ?format_timedate(td) - td = adjust_timedate(td,timedelta(days:=31*4)) - ?format_timedate(td) - - string deBruijn = "" - for n=0 to 99 do - string a = sprintf("%02d",n) - integer a1 = a[1], - a2 = a[2] - if a2>=a1 then - deBruijn &= iff(a1=a2?a1:a) - for m=n+1 to 99 do - string ms = sprintf("%02d",m) - if ms[2]>a1 then - deBruijn &= a&ms - end if - end for - end if - end for - deBruijn &= "000" - printf(1,"de Bruijn sequence length: %d\n\n",length(deBruijn)) - printf(1,"First 130 characters:\n%s\n\n",deBruijn[1..130]) - printf(1,"Last 130 characters:\n%s\n\n",deBruijn[-130..-1]) +string deBruijn = "" +for n=0 to 99 do + string a = sprintf("%02d",n) + integer a1 = a[1], + a2 = a[2] + if a2>=a1 then + deBruijn &= iff(a1=a2?a1:a) + for m=n+1 to 99 do + string ms = sprintf("%02d",m) + if ms[2]>a1 then + deBruijn &= a&ms + end if + end for + end if +end for +deBruijn &= "000" +printf(1,"de Bruijn sequence length: %d\n\n",length(deBruijn)) +printf(1,"First 130 characters:\n%s\n\n",deBruijn[1..130]) +printf(1,"Last 130 characters:\n%s\n\n",deBruijn[-130..-1]) - function check(string text) - sequence res = {} - sequence found = repeat(0,10000) - integer k - for i=1 to length(text)-3 do - k = to_integer(text[i..i+3],-1)+1 - if k!=0 then found[k] += 1 end if - end for - for i=1 to 10000 do - k = found[i] - if k!=1 then - string e = sprintf("Pin number %04d ",i-1) - e &= iff(k=0?"missing":sprintf("occurs %d times",k)) - res = append(res,e) - end if - end for - k = length(res) - if k=0 then - res = "No errors found" - else - string s = iff(k=1?"":"s") - res = sprintf("%d error%s found:\n ",{k,s})&join(res,"\n ") - end if - return res - end function +function check(string text) + sequence res = {} + sequence found = repeat(0,10000) + integer k + for i=1 to length(text)-3 do + k = to_integer(text[i..i+3],-1)+1 + if k!=0 then found[k] += 1 end if + end for + for i=1 to 10000 do + k = found[i] + if k!=1 then + string e = sprintf("Pin number %04d ",i-1) + e &= iff(k=0?"missing":sprintf("occurs %d times",k)) + res = append(res,e) + end if + end for + k = length(res) + if k=0 then + res = "No errors found" + else + string s = iff(k=1?"":"s") + res = sprintf("%d error%s found:\n ",{k,s})&join(res,"\n ") + end if + return res +end function - printf(1,"Missing 4 digit PINs in this sequence: %s\n", check(deBruijn)) - printf(1,"Missing 4 digit PINs in the reversed sequence: %s\n",check(reverse(deBruijn))) - printf(1,"4444th digit in the sequence: %c (setting it to .)\n", deBruijn[4444]) - deBruijn[4444] = '.' - printf(1,"Re-running checks: %s\n",check(deBruijn)) - - object a, b - a = {1,{2,3},"four",{5.6,7,{8.9}}} - b = a - b[3] = 4 - ?a - ?b - - function deep_copy(object o) - object res - if atom(o) then - res = o - else - res = repeat(' ',length(o)) - for i=1 to length(o) do - res[i] = deep_copy(o[i]) - end for - end if - return res - end function +function deep_copy(object o) + object res + if atom(o) then + res = o + else + res = repeat(' ',length(o)) + for i=1 to length(o) do + res[i] = deep_copy(o[i]) + end for + end if + return res +end function - object c = deep_copy(b) - ?c - - include builtins\serialize.e - object d = deserialize(serialize(a)) - ?d - - with javascript_semantics - function descending_primes(sequence res, atom p=0, max_digit=9) - for d=1 to max_digit do - atom np = p*10+d - if odd(d) and is_prime(np) then res &= np end if - res = descending_primes(res,np,d-1) - end for - return res - end function +with javascript_semantics +function descending_primes(sequence res, atom p=0, max_digit=9) + for d=1 to max_digit do + atom np = p*10+d + if odd(d) and is_prime(np) then res &= np end if + res = descending_primes(res,np,d-1) + end for + return res +end function - sequence r = sort(descending_primes({2})), - --sequence r = descending_primes({2}), - j = join_by(r,1,11," ","\n","%8d") - printf(1,"There are %,d descending primes:\n%s\n",{length(r),j}) - - with javascript_semantics - function descending_primes() - sequence powerset = tagset(9), - res = {} - while length(powerset) do - res &= filter(powerset,is_prime) - sequence next = {} - for i=1 to length(powerset) do - for d=1 to remainder(powerset[i],10)-1 do - next &= powerset[i]*10+d - end for - end for - powerset = next - end while - return res - end function +with javascript_semantics +function descending_primes() + sequence powerset = tagset(9), res = {} + do + res &= filter(powerset,is_prime) + sequence next = {} + for p in powerset do + for d=1 to remainder(p,10)-1 do + next &= p*10+d + end for + end for + powerset = next + until length(powerset)=0 + return res +end function - sequence r = descending_primes(), - j = join_by(r,1,11," ","\n","%8d") - printf(1,"There are %,d descending primes:\n%s\n",{length(r),j}) - - try - integer i = 1/0 - catch e - ?e[E_USER] - end try - puts(1,"still running...\n") - - with javascript_semantics - procedure samechar(sequence s) - string msg = "all characters are the same" - integer l = length(s) - if l>=2 then - integer ch = s[1] - for i=2 to l do - integer si = s[i] - if si!=ch then - string su = utf32_to_utf8({si}) - msg = sprintf(`first different character "%s"(#%02x) at position %d`,{su,si,i}) - exit - end if - end for - end if - printf(1,"\"%s\" (length %d): %s\n",{utf32_to_utf8(s),l,msg}) - end procedure +with javascript_semantics +procedure samechar(sequence s) + string msg = "all characters are the same" + integer l = length(s) + if l>=2 then + integer ch = s[1] + for i=2 to l do + integer si = s[i] + if si!=ch then + string su = utf32_to_utf8({si}) + msg = sprintf(`first different character "%s"(#%02x) at position %d`,{su,si,i}) + exit + end if + end for + end if + printf(1,"\"%s\" (length %d): %s\n",{utf32_to_utf8(s),l,msg}) +end procedure - constant tests = {""," ","2","333",".55","tttTTT","4444 444k", - utf8_to_utf32("🐶🐶🐺🐶"),utf8_to_utf32("🎄🎄🎄🎄")} - for i=1 to length(tests) do samechar(tests[i]) end for - - procedure all_uniq(sequence s) - string chars = "" - sequence posns = {}, - multi = {} - integer lm = 0 - for i=1 to length(s) do - integer si = s[i], - k = find(si,chars) - if k=0 then - chars &= si - posns &= {{i}} - else - posns[k] &= i - if length(posns[k])=2 then - multi &= k - lm += 1 - end if - end if - end for - string msg = sprintf("\"%s\" (length %d): ",{s,length(s)}), - nod = ordinal(lm,true), - ess = "s"[1..lm>1], - res = iff(lm=0?"all characters are unique" - :sprintf("contains %s duplicate%s:",{nod,ess})) - printf(1,"%s %s\n",{msg,res}) - res = repeat(' ',length(msg)) - for i=1 to length(multi) do - integer mi = multi[i], - ci = chars[mi] - printf(1,"%s '%c'(#%02x) at %V\n",{res,ci,ci,posns[mi]}) - end for - printf(1,"\n") - end procedure +with javascript_semantics +procedure all_uniq(sequence s) + string chars = "" + sequence posns = {}, + multi = {} + integer lm = 0 + for i=1 to length(s) do + integer si = s[i], + k = find(si,chars) + if k=0 then + chars &= si + posns &= {{i}} + else + posns[k] &= i + if length(posns[k])=2 then + multi &= k + lm += 1 + end if + end if + end for + string msg = sprintf("\"%s\" (length %d): ",{s,length(s)}), + nod = ordinal(lm,true), + ess = "s"[1..lm>1], + res = iff(lm=0?"all characters are unique" + :sprintf("contains %s duplicate%s:",{nod,ess})) + printf(1,"%s %s\n",{msg,res}) + res = repeat(' ',length(msg)) + for i=1 to length(multi) do + integer mi = multi[i], + ci = chars[mi] + printf(1,"%s '%c'(#%02x) at %V\n",{res,ci,ci,posns[mi]}) + end for + printf(1,"\n") +end procedure - constant tests = {"",".","abcABC","XYZ ZYX","1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ", - "01234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ0X", - " ","2","333","55","tttTTT","tTTTtt","4444 444k"} - papply(tests,all_uniq) - - function isNumber(string s) - return scanf(s,"%f")!={} - -- Alt: isNumberString(object s) and - -- return string(s) and scanf(s,"%f")!={}, or even - -- return string(s) and scanf(substitute(trim(s),",",""),"%f")!={} - end function +function isNumber(string s) + return scanf(s,"%f")!={} +-- Alt: isNumberString(object s) and +-- return string(s) and scanf(s,"%f")!={}, or even +-- return string(s) and scanf(substitute(trim(s),",",""),"%f")!={} +end function - constant tests = {"#a","#A","0xA","0(16)A","#FF","255","0", - "0.","0.0","000.000","0e0","0e-2000"," ", - ".14",".05","-5.2","0xf","ten","1B","#1B", - " 12 ",trim(" 12 "),"1","0o16","0o18", - "0b10101111_11110000_11110000_00110011", - "1_000","50e","+123","+ 123","-0b10101", - "NaN","+.345","12..34","12e3.4","0-2", - "192.168.0.1","1.2e","1 2","12.34","", - "beef","#beef","1,000,000","Inf","1/2", - "1.5e+27","0x10.5","1."} +constant tests = {"#a","#A","0xA","0(16)A","#FF","255","0", + "0.","0.0","000.000","0e0","0e-2000"," ", + ".14",".05","-5.2","0xf","ten","1B","#1B", + " 12 ",trim(" 12 "),"1","0o16","0o18", + "0b10101111_11110000_11110000_00110011", + "1_000","50e","+123","+ 123","-0b10101", + "NaN","+.345","12..34","12e3.4","0-2", + "192.168.0.1","1.2e","1 2","12.34","", + "beef","#beef","1,000,000","Inf","1/2", + "1.5e+27","0x10.5","1."} - sequence numeric = {}, - notnumb = {} - for i=1 to length(tests) do - string ti = tests[i] - if isNumber(ti) then - numeric = append(numeric,ti) - else - notnumb = append(notnumb,ti) - end if - end for - puts(1,"numeric: ") - pp(numeric,{pp_Indent,9}) - puts(1,"\nnot numeric: ") - pp(notnumb,{pp_Indent,13}) - n ) + +[ 4 pack 0 swap + ' [ roll dip roll > ] join + 10000 times + [ dup do swap dip + ] drop + say "0." echo cr ] is prob ( a b c d --> ) + +randomise +9 4 6 6 prob +5 10 6 7 prob diff --git a/Task/Dice-game-probabilities/Rust/dice-game-probabilities.rust b/Task/Dice-game-probabilities/Rust/dice-game-probabilities.rs similarity index 100% rename from Task/Dice-game-probabilities/Rust/dice-game-probabilities.rust rename to Task/Dice-game-probabilities/Rust/dice-game-probabilities.rs diff --git a/Task/Digital-root-Multiplicative-digital-root/Ada/digital-root-multiplicative-digital-root.ada b/Task/Digital-root-Multiplicative-digital-root/Ada/digital-root-multiplicative-digital-root.adb similarity index 100% rename from Task/Digital-root-Multiplicative-digital-root/Ada/digital-root-multiplicative-digital-root.ada rename to Task/Digital-root-Multiplicative-digital-root/Ada/digital-root-multiplicative-digital-root.adb diff --git a/Task/Digital-root-Multiplicative-digital-root/Crystal/digital-root-multiplicative-digital-root.cr b/Task/Digital-root-Multiplicative-digital-root/Crystal/digital-root-multiplicative-digital-root.cr new file mode 100644 index 0000000000..dac178580a --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/Crystal/digital-root-multiplicative-digital-root.cr @@ -0,0 +1,33 @@ +struct Int + def mdr + n, p = self, 0 + return {0, 0} unless n > 0 + while n >= 10 + n = n.digits.product + p += 1 + end + { n, p } + end +end + +puts <<-EOH + n MDR MP +------------- +EOH +[123321, 7739, 893, 899998].each do |n| + printf "%6d %d %d\n", n, *n.mdr +end +puts +puts <<-EOH +MDR: [n0..n4] +=== ======== +EOH +buckets = Array(Array(Int32)).new(10) { [] of Int32 } +(0..).each do |n| + mdr, _ = n.mdr + buckets[mdr] << n + break if buckets.all? {|b| b.size >= 5 } +end +buckets.each_with_index do |b, i| + printf "%3d: %s\n", i, b.first(5) +end diff --git a/Task/Digital-root-Multiplicative-digital-root/EasyLang/digital-root-multiplicative-digital-root.easy b/Task/Digital-root-Multiplicative-digital-root/EasyLang/digital-root-multiplicative-digital-root.easy index 1e560243bc..1037d26810 100644 --- a/Task/Digital-root-Multiplicative-digital-root/EasyLang/digital-root-multiplicative-digital-root.easy +++ b/Task/Digital-root-Multiplicative-digital-root/EasyLang/digital-root-multiplicative-digital-root.easy @@ -1,7 +1,5 @@ -proc _mdr n . md mp . - if n > 0 - r = 1 - . +proc _mdr n &md &mp . + if n > 0 : r = 1 while n > 0 r *= n mod 10 n = n div 10 @@ -13,11 +11,11 @@ proc _mdr n . md mp . md = r . . -proc mdr n . md mp . +proc mdr n &md &mp . mp = 0 _mdr n md mp . -numfmt 0 6 +numfmt 6 0 print "Number MDR MP" for v in [ 123321 7739 893 899998 ] mdr v md mp @@ -25,9 +23,7 @@ for v in [ 123321 7739 893 899998 ] . width = 5 len table[] 10 * width -arrbase table[] 0 len tfill[] 10 -arrbase tfill[] 0 numfmt 0 0 while total < 10 * width mdr i md mp @@ -43,9 +39,7 @@ for i = 0 to 9 write i & ": [" for j = 0 to width - 1 write table[i * width + j] - if j < width - 1 - write "," - . + if j < width - 1 : write "," . print "]" . diff --git a/Task/Digital-root-Multiplicative-digital-root/Elixir/digital-root-multiplicative-digital-root.elixir b/Task/Digital-root-Multiplicative-digital-root/Elixir/digital-root-multiplicative-digital-root.ex similarity index 100% rename from Task/Digital-root-Multiplicative-digital-root/Elixir/digital-root-multiplicative-digital-root.elixir rename to Task/Digital-root-Multiplicative-digital-root/Elixir/digital-root-multiplicative-digital-root.ex diff --git a/Task/Digital-root-Multiplicative-digital-root/JavaScript/digital-root-multiplicative-digital-root.js b/Task/Digital-root-Multiplicative-digital-root/JavaScript/digital-root-multiplicative-digital-root.js new file mode 100644 index 0000000000..fb6df86d65 --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/JavaScript/digital-root-multiplicative-digital-root.js @@ -0,0 +1,31 @@ +function digmul(n) { + return [...String(n)].reduce((x, y) => Number(x) * Number(y)); +} + +function mdr_mp(n) { + let m = n, i = 0; + while (m > 9) { + m = digmul(m); + i++; + } + return {"MDR": m, "MP": i}; +} + +for (const n of [123321, 7739, 893, 899998]) { + console.log(`${n} has MDR ${mdr_mp(n)["MDR"]} and MP ${mdr_mp(n)["MP"]}`); +} + +function first5mdr(n) { + let m = 0, nums = []; + while (nums.length < 5) { + if (mdr_mp(m)["MDR"] == n) { + nums.push(m); + } + m++; + } + return `First 5 numbers with MDR ${n}: ${nums.join(", ")}`; +} + +for (let i = 0; i < 10; i++) { + console.log(first5mdr(i)); +} diff --git a/Task/Digital-root-Multiplicative-digital-root/Julia/digital-root-multiplicative-digital-root-1.julia b/Task/Digital-root-Multiplicative-digital-root/Julia/digital-root-multiplicative-digital-root-1.jl similarity index 100% rename from Task/Digital-root-Multiplicative-digital-root/Julia/digital-root-multiplicative-digital-root-1.julia rename to Task/Digital-root-Multiplicative-digital-root/Julia/digital-root-multiplicative-digital-root-1.jl diff --git a/Task/Digital-root-Multiplicative-digital-root/Julia/digital-root-multiplicative-digital-root-2.julia b/Task/Digital-root-Multiplicative-digital-root/Julia/digital-root-multiplicative-digital-root-2.jl similarity index 100% rename from Task/Digital-root-Multiplicative-digital-root/Julia/digital-root-multiplicative-digital-root-2.julia rename to Task/Digital-root-Multiplicative-digital-root/Julia/digital-root-multiplicative-digital-root-2.jl diff --git a/Task/Digital-root-Multiplicative-digital-root/Kotlin/digital-root-multiplicative-digital-root.kotlin b/Task/Digital-root-Multiplicative-digital-root/Kotlin/digital-root-multiplicative-digital-root.kts similarity index 100% rename from Task/Digital-root-Multiplicative-digital-root/Kotlin/digital-root-multiplicative-digital-root.kotlin rename to Task/Digital-root-Multiplicative-digital-root/Kotlin/digital-root-multiplicative-digital-root.kts diff --git a/Task/Digital-root-Multiplicative-digital-root/PascalABC.NET/digital-root-multiplicative-digital-root.pas b/Task/Digital-root-Multiplicative-digital-root/PascalABC.NET/digital-root-multiplicative-digital-root.pas new file mode 100644 index 0000000000..dfe2204da1 --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/PascalABC.NET/digital-root-multiplicative-digital-root.pas @@ -0,0 +1,33 @@ +## +function MulDigitalRoot(num: int64): (integer, integer); +begin + var mulpersistence := 0; + while num > 9 do + begin + num := num.ToString.ToCharArray.Select(x -> x.ToDigit).Aggregate((x, y) -> x * y); + mulpersistence += 1; + end; + result := (mulpersistence, integer(num)); +end; + +var nums := |123321, 7739, 893, 899998|; +foreach var num in nums do +begin + var t := MulDigitalRoot(num); + Writeln(num, ' has multiplicative persistence ', t[0], ' and multiplicative digital root ', t[1]) +end; + +var twidth := 5; +var table := new List[10]; +for var i := 0 to 9 do + table[i] := new List(); +var number := -1; +while (table.Any(x -> x.Count < twidth)) do +begin + number += 1; + var t := MulDigitalRoot(number); + if (table[t[1]].Count < twidth) then + table[t[1]].Add(number); +end; +for var i := 0 to 9 do + WriteLn(i, ' : [', string.Join(', ', table[i]), ']'); diff --git a/Task/Digital-root-Multiplicative-digital-root/Phix/digital-root-multiplicative-digital-root-1.phix b/Task/Digital-root-Multiplicative-digital-root/Phix/digital-root-multiplicative-digital-root-1.phix index cc996c596b..16ee10b968 100644 --- a/Task/Digital-root-Multiplicative-digital-root/Phix/digital-root-multiplicative-digital-root-1.phix +++ b/Task/Digital-root-Multiplicative-digital-root/Phix/digital-root-multiplicative-digital-root-1.phix @@ -1,46 +1,44 @@ -(phixonline)--> - with javascript_semantics - function mdr_mp(integer m) - integer mp = 0 - while m>9 do - integer newm = 1 - while m do - newm *= remainder(m,10) - m = floor(m/10) - end while - m = newm - mp += 1 - end while - return {m,mp} - end function +with javascript_semantics +function mdr_mp(integer m) + integer mp = 0 + while m>9 do + integer newm = 1 + while m do + newm *= remainder(m,10) + m = floor(m/10) + end while + m = newm + mp += 1 + end while + return {m,mp} +end function - constant tests = {123321, 7739, 893, 899998} - printf(1,"Number MDR MP\n") - printf(1,"====== === ==\n") - for i=1 to length(tests) do - integer ti = tests[i] - printf(1,"%6d %6d %6d\n",ti&mdr_mp(ti)) - end for +constant tests = {123321, 7739, 893, 899998} +printf(1,"Number MDR MP\n") +printf(1,"====== === ==\n") +for i=1 to length(tests) do + integer ti = tests[i] + printf(1,"%6d %6d %6d\n",ti&mdr_mp(ti)) +end for - integer i=0, found = 0 - sequence res = columnize({tagset(9,0)}) - -- (ie {{0},{1},..,{9}}) - while found<50 do -- (ie the full 10*5) - integer mdr1 = mdr_mp(i)[1]+1 - sequence m1 = res[mdr1] - if length(m1)<6 then - res[mdr1] = 0 -- (avoid p2js violation) - m1 &= i - res[mdr1] = m1 - found += 1 - end if - i += 1 - end while +integer i=0, found = 0 +sequence res = columnize({tagset(9,0)}) + -- (ie {{0},{1},..,{9}}) +while found<50 do -- (ie the full 10*5) + integer mdr1 = mdr_mp(i)[1]+1 + sequence m1 = res[mdr1] + if length(m1)<6 then + res[mdr1] = 0 -- (avoid p2js violation) + m1 &= i + res[mdr1] = m1 + found += 1 + end if + i += 1 +end while - printf(1,"\nMDR 1 2 3 4 5") - printf(1,"\n=== ===========================\n") +printf(1,"\nMDR 1 2 3 4 5") +printf(1,"\n=== ===========================\n") - for i=1 to 10 do - printf(1,"%2d %5d %5d %5d %5d %5d\n",res[i]) - end for - - with javascript_semantics - function pdd(integer n) return sprintf("%2d",product(sq_sub(sprint(n),'0'))) end function - printf(1,"Product of the decimal digits of 1..100:\n%s\n", {join_by(apply(tagset(100),pdd),1,10)}) - s ) + + [ temp share 0 peek ] is baker ( --> n ) + [ temp share 1 peek ] is cooper ( --> n ) + [ temp share 2 peek ] is fletcher ( --> n ) + [ temp share 3 peek ] is miller ( --> n ) + [ temp share 4 peek ] is smith ( --> n ) + + [ temp share size = ] is top ( n --> b ) + [ 1 = ] is bottom ( n --> b ) + [ > ] is higher ( n n --> b ) + [ - abs 1 = ] is adjacent ( n n --> b ) + + [ if ]done[ ] is exclude ( b --> ) + [ not if ]done[ ] is require ( b --> ) + [ temp share nested join ] is include ( [ --> [ ) + + [ ]'[ ' include join + problem put + [] + ' [ 1 2 3 4 5 ] + permutations + witheach + [ temp put + problem share do + temp release ] + problem release + say " B C F M S" cr + witheach [ echo cr ] ] is solve ( --> ) + + solve + [ baker top exclude + cooper bottom exclude + fletcher top + fletcher bottom or exclude + miller cooper higher require + smith fletcher adjacent exclude + fletcher cooper adjacent exclude ] diff --git a/Task/Dinesmans-multiple-dwelling-problem/Rust/dinesmans-multiple-dwelling-problem.rust b/Task/Dinesmans-multiple-dwelling-problem/Rust/dinesmans-multiple-dwelling-problem.rs similarity index 100% rename from Task/Dinesmans-multiple-dwelling-problem/Rust/dinesmans-multiple-dwelling-problem.rust rename to Task/Dinesmans-multiple-dwelling-problem/Rust/dinesmans-multiple-dwelling-problem.rs diff --git a/Task/Dinesmans-multiple-dwelling-problem/Tailspin/dinesmans-multiple-dwelling-problem-2.tailspin b/Task/Dinesmans-multiple-dwelling-problem/Tailspin/dinesmans-multiple-dwelling-problem-2.tailspin index e4eaad513f..0fe1190c3f 100644 --- a/Task/Dinesmans-multiple-dwelling-problem/Tailspin/dinesmans-multiple-dwelling-problem-2.tailspin +++ b/Task/Dinesmans-multiple-dwelling-problem/Tailspin/dinesmans-multiple-dwelling-problem-2.tailspin @@ -1,24 +1,29 @@ -// We add a zero to be able to express e.g. "not top floor" -def floors: [0..5 -> (floor:$)]; -def names: [['Ground', 'Baker', 'Cooper', 'Fletcher', 'Miller', 'Smith']... -> (name:$)]; +permutations templates + when <|=1> do [1] ! + otherwise + n is $; + expand templates + p is $; + 1..$n -> templates + k is $; + [$p(..$k - 1)..., $n, $p($k..)...] ! + end ! + end expand + $n - 1 -> # -> expand ! +end permutations -def dwellings: [$floors, $names] -> \( - def solver: $ -> EinsteinSolver; +names is ['Baker', 'Cooper', 'Fletcher', 'Miller', 'Smith']; - {name: 'Ground', floor: 0} -> !solver::isFact - ({name: 'Ground'} solver::nextTo&{byField: :(floor:), bMinusA: [1..4]} {name: 'Baker'}) -> !VOID - ({name: 'Ground'} solver::nextTo&{byField: :(floor:), bMinusA: [2..5]} {name: 'Cooper'}) -> !VOID - ({name: 'Ground'} solver::nextTo&{byField: :(floor:), bMinusA: [2..4]} {name: 'Fletcher'}) -> !VOID - ({name: 'Cooper'} solver::nextTo&{byField: :(floor:), bMinusA: [1..4]} {name: 'Miller'}) -> !VOID - ({name: 'Fletcher'} solver::nextTo&{byField: :(floor:), bMinusA: [-4..-2, 2..4]} {name: 'Smith'}) -> !VOID - ({name: 'Fletcher'} solver::nextTo&{byField: :(floor:), bMinusA: [-4..-2, 2..4]} {name: 'Cooper'}) -> !VOID - - [$solver::solutions&{required: 6} ... -> ($ notMatching {| {name: 'Ground'} |})]! -\); - -$dwellings -> \[i]('Solution $i;: -$... -> '$; -'; -'! \)... -> !OUT::write -'No more solutions -' -> !OUT::write +5 -> permutations -> $names($) + -> if <|?($(.. as i; -> if <|='Baker'> -> $i)... matches <~|=5>)> + -> if <|?($(.. as i; -> if <|='Cooper'> -> $i)... matches <~|=1>)> + -> if <|?($(.. as i; -> if <|='Fletcher'> -> $i)... matches <~|=1|=5>)> + -> templates + miller is $(.. as i; -> if <|='Miller'> -> $i)...; + $ -> if <|?($(.. as i; -> if <|='Cooper'> -> $i)... matches <|..$miller>)> ! + end + -> if <|?(($(.. as i; -> if <|='Smith'> -> $i)...) - ($(.. as i; -> if <|='Fletcher'> -> $i)...) matches <~|=1|=-1>)> + -> if <|?(($(.. as i; -> if <|='Cooper'> -> $i)...) - ($(.. as i; -> if <|='Fletcher'> -> $i)...) matches <~|=1|=-1>)> + -> $(.. as i; -> '$i;:$;$#10;') + -> $(..:-1) + -> '$...;$#10;' ! diff --git a/Task/Dinesmans-multiple-dwelling-problem/Tailspin/dinesmans-multiple-dwelling-problem-3.tailspin b/Task/Dinesmans-multiple-dwelling-problem/Tailspin/dinesmans-multiple-dwelling-problem-3.tailspin new file mode 100644 index 0000000000..e4eaad513f --- /dev/null +++ b/Task/Dinesmans-multiple-dwelling-problem/Tailspin/dinesmans-multiple-dwelling-problem-3.tailspin @@ -0,0 +1,24 @@ +// We add a zero to be able to express e.g. "not top floor" +def floors: [0..5 -> (floor:$)]; +def names: [['Ground', 'Baker', 'Cooper', 'Fletcher', 'Miller', 'Smith']... -> (name:$)]; + +def dwellings: [$floors, $names] -> \( + def solver: $ -> EinsteinSolver; + + {name: 'Ground', floor: 0} -> !solver::isFact + ({name: 'Ground'} solver::nextTo&{byField: :(floor:), bMinusA: [1..4]} {name: 'Baker'}) -> !VOID + ({name: 'Ground'} solver::nextTo&{byField: :(floor:), bMinusA: [2..5]} {name: 'Cooper'}) -> !VOID + ({name: 'Ground'} solver::nextTo&{byField: :(floor:), bMinusA: [2..4]} {name: 'Fletcher'}) -> !VOID + ({name: 'Cooper'} solver::nextTo&{byField: :(floor:), bMinusA: [1..4]} {name: 'Miller'}) -> !VOID + ({name: 'Fletcher'} solver::nextTo&{byField: :(floor:), bMinusA: [-4..-2, 2..4]} {name: 'Smith'}) -> !VOID + ({name: 'Fletcher'} solver::nextTo&{byField: :(floor:), bMinusA: [-4..-2, 2..4]} {name: 'Cooper'}) -> !VOID + + [$solver::solutions&{required: 6} ... -> ($ notMatching {| {name: 'Ground'} |})]! +\); + +$dwellings -> \[i]('Solution $i;: +$... -> '$; +'; +'! \)... -> !OUT::write +'No more solutions +' -> !OUT::write diff --git a/Task/Dining-philosophers/Ada/dining-philosophers-1.ada b/Task/Dining-philosophers/Ada/dining-philosophers-1.adb similarity index 100% rename from Task/Dining-philosophers/Ada/dining-philosophers-1.ada rename to Task/Dining-philosophers/Ada/dining-philosophers-1.adb diff --git a/Task/Dining-philosophers/Ada/dining-philosophers-2.ada b/Task/Dining-philosophers/Ada/dining-philosophers-2.adb similarity index 100% rename from Task/Dining-philosophers/Ada/dining-philosophers-2.ada rename to Task/Dining-philosophers/Ada/dining-philosophers-2.adb diff --git a/Task/Dining-philosophers/Ada/dining-philosophers-3.ada b/Task/Dining-philosophers/Ada/dining-philosophers-3.adb similarity index 100% rename from Task/Dining-philosophers/Ada/dining-philosophers-3.ada rename to Task/Dining-philosophers/Ada/dining-philosophers-3.adb diff --git a/Task/Dining-philosophers/Delphi/dining-philosophers.delphi b/Task/Dining-philosophers/Delphi/dining-philosophers.pas similarity index 100% rename from Task/Dining-philosophers/Delphi/dining-philosophers.delphi rename to Task/Dining-philosophers/Delphi/dining-philosophers.pas diff --git a/Task/Dining-philosophers/Elixir/dining-philosophers.elixir b/Task/Dining-philosophers/Elixir/dining-philosophers.ex similarity index 100% rename from Task/Dining-philosophers/Elixir/dining-philosophers.elixir rename to Task/Dining-philosophers/Elixir/dining-philosophers.ex diff --git a/Task/Dining-philosophers/Euphoria/dining-philosophers.euphoria b/Task/Dining-philosophers/Euphoria/dining-philosophers.eu similarity index 100% rename from Task/Dining-philosophers/Euphoria/dining-philosophers.euphoria rename to Task/Dining-philosophers/Euphoria/dining-philosophers.eu diff --git a/Task/Dining-philosophers/Fortran/dining-philosophers.f b/Task/Dining-philosophers/Fortran/dining-philosophers.f new file mode 100644 index 0000000000..25b8a072a6 --- /dev/null +++ b/Task/Dining-philosophers/Fortran/dining-philosophers.f @@ -0,0 +1,86 @@ +!Deadlock prevented by making one philosopher "left-handed" +!and making orderly use of omp locks which protect forks by ensuring that only one philosopher can use each fork at a time + program dining_philosophers + use omp_lib + implicit none + + integer, parameter :: N = 5 + integer(omp_lock_kind) :: forks(N) + character(len=20), dimension(N) :: names = [character(len=20) :: & + "Aristotle", "Kant", "Spinoza", "Marx", "Russell"] + integer :: i + integer :: next_thread = 0 ! Shared sequencing variable + + ! Initialize forks (mutexes) + do i = 1, N + call omp_init_lock(forks(i)) + end do + + ! Parallel region with N threads + !$omp parallel num_threads(N) private(i) shared(next_thread, forks, names) + i = omp_get_thread_num() + 1 ! Philosopher IDs: 1 to N + call philosopher(i, next_thread, forks, names) + !$omp end parallel + + ! Destroy locks + do i = 1, N + call omp_destroy_lock(forks(i)) + end do + +contains + + subroutine philosopher(id, next_thread, forks, names) + integer, intent(in) :: id + integer, intent(inout) :: next_thread + integer(omp_lock_kind), intent(inout) :: forks(:) + character(len=20), intent(in) :: names(:) + integer :: left, right, meals + + left = id + right = mod(id, size(forks)) + 1 ! Wrap around for right fork + !$omp barrier + ! Wait for turn to start + do while (id - 1 /= next_thread) + !$omp flush(next_thread) + end do + + print *, trim(names(id)), " sits down at the table." + + !$omp atomic + next_thread = next_thread + 1 + !$omp flush(next_thread) + + ! Philosopher's meal loop + do meals = 1, 20 +! print *, trim(names(id)), " is thinking." +! call sleep(1) + + ! Asymmetric fork acquisition to prevent deadlock + if (id < size(forks)) then + call omp_set_lock(forks(left)) + print *, trim(names(id)), " picked up left fork ", left + call omp_set_lock(forks(right)) + print *, trim(names(id)), " picked up right fork ", right + else + call omp_set_lock(forks(right)) + print *, trim(names(id)), " picked up right fork ", right + call omp_set_lock(forks(left)) + print *, trim(names(id)), " picked up left fork ", left + end if + + print *, trim(names(id)), " is eating." + call sleep(1) + + call omp_unset_lock(forks(left)) + call omp_unset_lock(forks(right)) + print *, trim(names(id)), " put down forks." + print *, trim(names(id)), " is thinking." + call sleep(1) + print *, trim(names(id)), " returns to the table." + + end do + + print *, trim(names(id)), " leaves the table." + end subroutine philosopher + +end program dining_philosophers diff --git a/Task/Dining-philosophers/FreeBASIC/dining-philosophers.basic b/Task/Dining-philosophers/FreeBASIC/dining-philosophers.basic new file mode 100644 index 0000000000..4909077304 --- /dev/null +++ b/Task/Dining-philosophers/FreeBASIC/dining-philosophers.basic @@ -0,0 +1,108 @@ +Const NUM_PHILOSOPHERS = 5 +Const HUNGER = 3 +Const THINK_TIME = 1000 +Const EAT_TIME = 1000 + +Type Fork + mutex As Any Ptr + available As Boolean +End Type + +Type Philosopher + nombre As String + leftFork As Fork Ptr + rightFork As Fork Ptr + hunger As Integer +End Type + +Dim Shared As Philosopher philosophers(NUM_PHILOSOPHERS-1) +Dim Shared As Fork forks(NUM_PHILOSOPHERS-1) +Dim Shared As Any Ptr printMutex + +Function threadSafePrint(text As String) As Integer + Mutexlock(printMutex) + Print text + Mutexunlock(printMutex) + Return 0 +End Function + +Sub delay(ms As Integer) + Dim As Double t = Timer + While (Timer - t) * 1000 < ms + Sleep 1, 1 + Wend +End Sub + +Function philosopherThread(param As Any Ptr) As Any Ptr + Dim As Philosopher Ptr phil = param + + threadSafePrint(phil->nombre + " seated") + + While phil->hunger > 0 + threadSafePrint(phil->nombre + " hungry") + + Mutexlock(phil->leftFork->mutex) + Mutexlock(phil->rightFork->mutex) + + threadSafePrint(phil->nombre + " eating") + delay(EAT_TIME) + + Mutexunlock(phil->leftFork->mutex) + Mutexunlock(phil->rightFork->mutex) + + threadSafePrint(phil->nombre + " thinking") + delay(THINK_TIME) + + phil->hunger -= 1 + Wend + + threadSafePrint(phil->nombre + " satisfied") + threadSafePrint(phil->nombre + " left the table") + + Return 0 +End Function + +' Main program +Dim As Integer i +Dim As String names(NUM_PHILOSOPHERS-1) = {"Aristotle", "Kant", "Spinoza", "Marx", "Russell"} +Print "Table empty" + +printMutex = Mutexcreate() + +' Initialize forks +For i = 0 To NUM_PHILOSOPHERS-1 + forks(i).mutex = Mutexcreate() + forks(i).available = True +Next + +' Initialize philosophers +For i = 0 To NUM_PHILOSOPHERS-1 + philosophers(i).nombre = names(i) + philosophers(i).hunger = HUNGER + philosophers(i).leftFork = @forks(i) + philosophers(i).rightFork = @forks((i + 1) Mod NUM_PHILOSOPHERS) +Next + +' Make last philosopher left-handed +Swap philosophers(NUM_PHILOSOPHERS-1).leftFork, philosophers(NUM_PHILOSOPHERS-1).rightFork + +' Create threads +Dim As Any Ptr threads(NUM_PHILOSOPHERS-1) +For i = 0 To NUM_PHILOSOPHERS-1 + threads(i) = Threadcreate(Cast(Sub(As Any Ptr), @philosopherThread), @philosophers(i)) +Next + +' Wait for all threads +For i = 0 To NUM_PHILOSOPHERS-1 + Threadwait(threads(i)) +Next + +' Cleanup +For i = 0 To NUM_PHILOSOPHERS-1 + Mutexdestroy(forks(i).mutex) +Next + +Mutexdestroy(printMutex) +Print "Table empty" + +Sleep diff --git a/Task/Dining-philosophers/Julia/dining-philosophers.julia b/Task/Dining-philosophers/Julia/dining-philosophers.jl similarity index 100% rename from Task/Dining-philosophers/Julia/dining-philosophers.julia rename to Task/Dining-philosophers/Julia/dining-philosophers.jl diff --git a/Task/Dining-philosophers/Kotlin/dining-philosophers.kotlin b/Task/Dining-philosophers/Kotlin/dining-philosophers.kts similarity index 100% rename from Task/Dining-philosophers/Kotlin/dining-philosophers.kotlin rename to Task/Dining-philosophers/Kotlin/dining-philosophers.kts diff --git a/Task/Dining-philosophers/Rust/dining-philosophers.rust b/Task/Dining-philosophers/Rust/dining-philosophers.rs similarity index 100% rename from Task/Dining-philosophers/Rust/dining-philosophers.rust rename to Task/Dining-philosophers/Rust/dining-philosophers.rs diff --git a/Task/Disarium-numbers/Ada/disarium-numbers.ada b/Task/Disarium-numbers/Ada/disarium-numbers.adb similarity index 100% rename from Task/Disarium-numbers/Ada/disarium-numbers.ada rename to Task/Disarium-numbers/Ada/disarium-numbers.adb diff --git a/Task/Disarium-numbers/Agena/disarium-numbers.agena b/Task/Disarium-numbers/Agena/disarium-numbers.agena new file mode 100644 index 0000000000..8f83231d93 --- /dev/null +++ b/Task/Disarium-numbers/Agena/disarium-numbers.agena @@ -0,0 +1,34 @@ +scope # find some Disarium numbers - numbers whose digit position-power sums + # are equal to the number, e.g. 135 = 1^1 + 3^2 + 5^3 + + # compute the nth powers of 0-9 + local constant power := seq( [], [], [], [], [], [], [], [], [] ); + for d from 0 to 9 do power[ 1, d ] := d od; + for n from 2 to 9 do + power[ n, 0 ] := 0; + for d to 9 do + power[ n, d ] := power[ n - 1, d ] * d + od + od; + # print the first few Disarium numbers + local constant maxDisarium := 19; + local count, powerOfTen, length := 0, 10, 1; + for n from 0 while count < maxDisarium do + if n = powerOfTen then + # the number of digits just increased + powerOfTen *:= 10; + length +:= 1 + fi; + # form the digit power sum + local v, dps := n, 0; + for p from length to 1 by -1 do + dps +:= power[ p, v mod 10 ]; + v \:= 10 + od; + if dps = n then + # n is Disarium + count +:= 1; + printf( " %d", n ) + fi + od +end diff --git a/Task/Disarium-numbers/COBOL/disarium-numbers.cobol b/Task/Disarium-numbers/COBOL/disarium-numbers.cob similarity index 100% rename from Task/Disarium-numbers/COBOL/disarium-numbers.cobol rename to Task/Disarium-numbers/COBOL/disarium-numbers.cob diff --git a/Task/Disarium-numbers/Delphi/disarium-numbers.delphi b/Task/Disarium-numbers/Delphi/disarium-numbers.pas similarity index 100% rename from Task/Disarium-numbers/Delphi/disarium-numbers.delphi rename to Task/Disarium-numbers/Delphi/disarium-numbers.pas diff --git a/Task/Disarium-numbers/EasyLang/disarium-numbers.easy b/Task/Disarium-numbers/EasyLang/disarium-numbers.easy index b321c158ab..08d03576da 100644 --- a/Task/Disarium-numbers/EasyLang/disarium-numbers.easy +++ b/Task/Disarium-numbers/EasyLang/disarium-numbers.easy @@ -1,18 +1,21 @@ -func disarium x . - h = x - while h > 0 - d[] &= h mod 10 - h = h div 10 +fastfunc disarium n . + n0 = n + ndig = floor log n 10 + 1 + for i = ndig downto 1 + h += pow (n mod 10) i + n = n div 10 . - for i = 1 to len d[] - h += pow d[i] (len d[] - i + 1) - . - return if h = x + if h = n0 : return 1 . -while count < 19 - if disarium n = 1 - count += 1 - print n +fastfunc nextdisarium n . + repeat + n += 1 + until disarium n = 1 . - n += 1 + return n . +for i to 18 + n = nextdisarium n + write n & " " +. +print "" diff --git a/Task/Disarium-numbers/Fortran/disarium-numbers.f b/Task/Disarium-numbers/Fortran/disarium-numbers.f new file mode 100644 index 0000000000..5839193fc7 --- /dev/null +++ b/Task/Disarium-numbers/Fortran/disarium-numbers.f @@ -0,0 +1,112 @@ +! Disarium numbers +! +! tested with Intel ifx (IFX) 2025.2.0 20250605 on Kubuntu 25.04 +! GNU Fortran (Ubuntu 14.2.0-19ubuntu2) 14.2.0 on Kubuntu 25.04 +! VSI Fortran x86-64 V8.6-001 on OpenVMS x86_64 V9.2-3 +! Note that VMS requires switch $Fortran/ccdefault=LIST +! otherwise 1st character of each output line is interpreted as +! Carriage Control character. +! U.B., July 2025 + +program progDisarium + +implicit none + +! Others have already shown: 20th Disarium number has 20 digits +! This will not fit in signed 8-byte-integer. Current Fortran does +! not have unsigned integers of any size, so we can only calculate 19 Disarium numbers +! (unless we start to fiddle with homegrown extended precision integers) +! These 19 numbers all fit in 4 byte integers, so we can limit ourselves to +! signed 4-byte integers, with maximum possible number of digits is 10. + + integer, parameter :: maxDigs = 10 ! Maximum number of digits + integer , parameter :: nMax = 19 ! Number of Disarim numbers to print + integer :: ii ! loop index + integer :: count ! result counter + + ii=0 + count=0 + + do while (count .lt. nMax) ! finish when count is nMax. + if (isDisarium (ii)) then ! found another result + count = count + 1 + write (6,'(i0, x)', advance='no') ii ! print one by one, but all in 1 line + end if + ii = ii + 1 + end do + write (6,*) ! terminate line only + + contains + + function isDisarium (n) result(yn) + + integer, intent(in) :: n ! decide if n is disarium number + logical :: yn ! return value, true or false + integer :: numD, sum ! number of digits, sum of pow(digits,loc) + integer :: theDigits (maxDigs) ! vector with the numD digits of n + integer :: jj ! loop index + sum = 0 + + numD = getDigits (n, theDigits) ! Decompose n into numD Digits + + do jj=1, numD + if (theDigits(jj) .ne. 0) then + sum = sum + ipow(theDigits(jj), jj) + endif + end do + yn = (sum .eq. n) + end function isDisarium + + + function getDigits (n, d) result (ndigs) + + integer, intent(in) :: n ! decompose this into its digits + integer, intent(out) :: d(maxDigs) ! result: digits of n + integer :: ndigs ! return value: number of digits + integer :: ii ! loop index + integer :: localN ! Local copy of n to work with + + if (n .lt. 10) then ! Do the trivial case without further calculation + ndigs = 1 + d(1) = n + return + endif + + ndigs = 0 + localN = n + ! store them right-justified in array d + do while (localN .gt. 0) + d(maxDigs - ndigs) = mod(localN, 10) + ndigs = ndigs + 1 + localN = localN / 10 + end do + + ! Need to shift so that most significant digit appears at d (1) + do ii = 1, ndigs + d (ii) = d (maxDigs-ndigs+ii) + end do + + end function getDigits + + + ! Integer power: calculate n ^ pw + function ipow (n,pw) result (p) + integer, intent(in) :: n ! take this... + integer, intent(in) :: pw ! ... to the power of that + integer :: p ! Return value + integer :: ii ! Loop index + + p = 1 + + if (pw .lt. 0 .or. n.le. 0) then + print *, "function ipow(n,p) is only defined for values n,p both >0" + return + end if + + do ii=1, pw + p = p * n + end do + + end function ipow + +end program progDisarium diff --git a/Task/Disarium-numbers/Frink/disarium-numbers.frink b/Task/Disarium-numbers/Frink/disarium-numbers.frink new file mode 100644 index 0000000000..82f3f23e70 --- /dev/null +++ b/Task/Disarium-numbers/Frink/disarium-numbers.frink @@ -0,0 +1,12 @@ +isDisarium = {|n| + s = 0 + p = 1 + for d = integerDigits[n] + { + s = s + d^p + p = p + 1 + } + return n==s +} + +println[first[select[count[0], isDisarium], 19]] diff --git a/Task/Disarium-numbers/Icon/disarium-numbers.icon b/Task/Disarium-numbers/Icon/disarium-numbers.icon new file mode 100644 index 0000000000..86618f4a21 --- /dev/null +++ b/Task/Disarium-numbers/Icon/disarium-numbers.icon @@ -0,0 +1,11 @@ +procedure main(A) + limit := \A[1] | 18 + every writes(" ",disarium(seq(0)))\limit + write() +end + +procedure disarium(n) + ns := string(n) # Avoid redundant conversions later + every ((s := i := 0), j := !ns, i +:= 1) do s +:= ns[i]^i + return s = n +end diff --git a/Task/Disarium-numbers/Julia/disarium-numbers.julia b/Task/Disarium-numbers/Julia/disarium-numbers.jl similarity index 100% rename from Task/Disarium-numbers/Julia/disarium-numbers.julia rename to Task/Disarium-numbers/Julia/disarium-numbers.jl diff --git a/Task/Disarium-numbers/Kotlin/disarium-numbers.kotlin b/Task/Disarium-numbers/Kotlin/disarium-numbers.kts similarity index 100% rename from Task/Disarium-numbers/Kotlin/disarium-numbers.kotlin rename to Task/Disarium-numbers/Kotlin/disarium-numbers.kts diff --git a/Task/Disarium-numbers/OCaml/disarium-numbers.ocaml b/Task/Disarium-numbers/OCaml/disarium-numbers.ml similarity index 100% rename from Task/Disarium-numbers/OCaml/disarium-numbers.ocaml rename to Task/Disarium-numbers/OCaml/disarium-numbers.ml diff --git a/Task/Disarium-numbers/Objeck/disarium-numbers.objeck b/Task/Disarium-numbers/Objeck/disarium-numbers.objeck new file mode 100644 index 0000000000..f79e3d6f25 --- /dev/null +++ b/Task/Disarium-numbers/Objeck/disarium-numbers.objeck @@ -0,0 +1,29 @@ +class DisariumNumbers { + function : Main(args : String[]) ~ Nil { + i := 0; + count := 0; + while(count <= 18) { + if(IsDisarium(i)) { + "{$i} "->Print(); + count++; + }; + + i++; + }; + '\n'->Print(); + } + + function : IsDisarium(num : Int) ~ Bool { + n := num; + len := n->ToString()->Size(); + sum := 0; + i := 1; + while (n > 0) { + sum += Int->Pow(n % 10, len - i + 1); + n /= 10; + i ++; + }; + + return sum = num; + } +} diff --git a/Task/Disarium-numbers/PARI-GP/disarium-numbers.parigp b/Task/Disarium-numbers/PARI-GP/disarium-numbers.parigp new file mode 100644 index 0000000000..2f0215c66a --- /dev/null +++ b/Task/Disarium-numbers/PARI-GP/disarium-numbers.parigp @@ -0,0 +1,20 @@ +/* Function to check if a number is a Disarium number */ +IsDisarium(n) = { + my(digs = digits(n)); /* Get digits of n */ + my(mypowers = vector(#digs, i, digs[i]^i)); /* Raise each digit to its position */ + sum(i=1, #digs, mypowers[i]) == n /* Return 1 if sum equals original number */ +} + +/* Function to find Disarium numbers up to a limit */ +find_disarium(limit) = { + my(result = [], n = 0); + while(#result < limit, + if(IsDisarium(n), result = concat(result, n)); + n++; + ); + return(result); +} + +/* Main execution */ +disariumNumbers = find_disarium(19); +print("The first 19 Disarium numbers: ", disariumNumbers); diff --git a/Task/Disarium-numbers/PascalABC.NET/disarium-numbers.pas b/Task/Disarium-numbers/PascalABC.NET/disarium-numbers.pas new file mode 100644 index 0000000000..6e4ae6f80d --- /dev/null +++ b/Task/Disarium-numbers/PascalABC.NET/disarium-numbers.pas @@ -0,0 +1,15 @@ +## +function disariums: sequence of integer; +begin + var n := 0; + while true do + begin + var sum := 0.0; + foreach var x in n.ToString.ToCharArray index i do + sum := sum + power((x.todigit), i + 1); + if sum = n then yield (n); + n += 1; + end; +end; + +disariums.Take(19).Println; diff --git a/Task/Disarium-numbers/Pluto/disarium-numbers.pluto b/Task/Disarium-numbers/Pluto/disarium-numbers.pluto new file mode 100644 index 0000000000..4952e62669 --- /dev/null +++ b/Task/Disarium-numbers/Pluto/disarium-numbers.pluto @@ -0,0 +1,29 @@ +do -- find some Disarium numbers, numbers that are equal to their digit position power sums + + -- compute the nth powers of 0-9 # + local power = { { [0] = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, {}, {}, {}, {}, {}, {}, {}, {}, {} } + for n = 2, 9 do + power[n][0] = 0 + for d = 1, 9 do + power[n][d] = power[n - 1][d] * d + end + end + + local function isDisarium (x) + local str, sum = tostring(x), 0 + for pos = 1, #str do + local digit = tonumber(str[pos]) + sum += power[pos][digit] + end + return sum == x + end + + local count, n = 0, 0 + while count < 19 do + if isDisarium( n ) then + ++ count + io.write( " ", n ) + end + ++ n + end +end diff --git a/Task/Disarium-numbers/R/disarium-numbers.r b/Task/Disarium-numbers/R/disarium-numbers.r new file mode 100644 index 0000000000..bee77272bc --- /dev/null +++ b/Task/Disarium-numbers/R/disarium-numbers.r @@ -0,0 +1,12 @@ +disarium_sum <- function(n, i=ceiling(log10(n))){ + ifelse(n>9, (n%%10)^i+disarium_sum(n%/%10, i-1), n) +} + +count <- num <- 0 +while(count<19){ + if(num==disarium_sum(num)){ + print(num) + count <- count+1 + } + num <- num+1 +} diff --git a/Task/Disarium-numbers/Refal/disarium-numbers.refal b/Task/Disarium-numbers/Refal/disarium-numbers.refal new file mode 100644 index 0000000000..24e17b740b --- /dev/null +++ b/Task/Disarium-numbers/Refal/disarium-numbers.refal @@ -0,0 +1,32 @@ +$ENTRY Go { + = ; +}; + +Digits { + 0 = ; + s.N, : (s.R) s.D = s.D; +}; + +Pow { + s.N 0 = 1; + s.N s.P = <* s.N >>; +}; + +PowSum { + () e.P = 0; + (s.I e.X) e.P = <+ >>; + e.X = ; +}; + +Disarium { + e.N, >: e.N = True; + e.N = False; +}; + +FindDisarium { + 0 s.N = ; + s.I s.N, : { + True = <+ s.N 1>>; + False = >; + }; +}; diff --git a/Task/Disarium-numbers/Rust/disarium-numbers.rust b/Task/Disarium-numbers/Rust/disarium-numbers.rs similarity index 100% rename from Task/Disarium-numbers/Rust/disarium-numbers.rust rename to Task/Disarium-numbers/Rust/disarium-numbers.rs diff --git a/Task/Disarium-numbers/Uiua/disarium-numbers.uiua b/Task/Disarium-numbers/Uiua/disarium-numbers.uiua new file mode 100644 index 0000000000..37dbf6e7ff --- /dev/null +++ b/Task/Disarium-numbers/Uiua/disarium-numbers.uiua @@ -0,0 +1,2 @@ +IsDis ← =⊸(/+≡ⁿ+1⇡⊸⧻≡₀⋕°⋕) +⍜now(⋅⇌⍢(+1⍥⟜⊂⊸IsDis|<19⋅⧻)0[]) diff --git a/Task/Discordian-date/ALGOL-68/discordian-date.alg b/Task/Discordian-date/ALGOL-68/discordian-date.alg index ebf5dda235..11d03d007b 100644 --- a/Task/Discordian-date/ALGOL-68/discordian-date.alg +++ b/Task/Discordian-date/ALGOL-68/discordian-date.alg @@ -1,9 +1,11 @@ BEGIN # DISCORDIAN DATE CALCULATION - TRANSLATION OF MAD VIA ALGOL W # - INT greg, gmonth, gday, gyear; + INT gmonth, gday, gyear; []STRING holys = []STRING( "MUNG", "MOJO", "SYA", "ZARA", "MALA" )[ AT 0 ]; []STRING holys0 = []STRING( "CHAO", "DISCO", "CONFU", "BURE", "AF" )[ AT 0 ]; - []STRING disday = []STRING( "SWEETMORN", "BOOMTIME", "PUNGENday", "PRICKLE-PRICKLE", "SETTING ORANGE" )[ AT 0 ]; - []STRING disssn = []STRING( "CHAOS", "DISCORD", "CONFUSION", "BUREAUCRACY", "THE AFTERMATH" )[ AT 0 ]; + []STRING disday = + []STRING( "SWEETMORN", "BOOMTIME", "PUNGENDAY", "PRICKLE-PRICKLE", "SETTING ORANGE" )[ AT 0 ]; + []STRING disssn = + []STRING( "CHAOS", "DISCORD", "CONFUSION", "BUREAUCRACY", "THE AFTERMATH" )[ AT 0 ]; []INT mlengt = []INT( 0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 )[ AT 0 ]; CHAR slash1, slash2; diff --git a/Task/Discordian-date/Ada/discordian-date.ada b/Task/Discordian-date/Ada/discordian-date.adb similarity index 100% rename from Task/Discordian-date/Ada/discordian-date.ada rename to Task/Discordian-date/Ada/discordian-date.adb diff --git a/Task/Discordian-date/Delphi/discordian-date.delphi b/Task/Discordian-date/Delphi/discordian-date.pas similarity index 100% rename from Task/Discordian-date/Delphi/discordian-date.delphi rename to Task/Discordian-date/Delphi/discordian-date.pas diff --git a/Task/Discordian-date/EasyLang/discordian-date.easy b/Task/Discordian-date/EasyLang/discordian-date.easy index b619721dea..600746ed03 100644 --- a/Task/Discordian-date/EasyLang/discordian-date.easy +++ b/Task/Discordian-date/EasyLang/discordian-date.easy @@ -12,9 +12,7 @@ func day_of_year y m d . m -= 1 until m = 0 d += days[m] - if m = 2 and leap y = 1 - d += 1 - . + if m = 2 and leap y = 1 : d += 1 . return d . @@ -24,9 +22,7 @@ func$ ddate y m d . if leap y = 1 and m = 2 and d = 29 return "St. Tib's Day, in the YOLD " & dyear . - if leap y = 1 and doy >= 60 - doy -= 1 - . + if leap y = 1 and doy >= 60 : doy -= 1 dsday = doy mod1 73 dseason = doy div1 73 r$ = weekday$[doy mod1 5] & ", day " & dsday & " of " & seasons$[dseason] @@ -38,7 +34,7 @@ func$ ddate y m d . . return r$ . -proc show d$ . . +proc show d$ . a[] = number strsplit d$ "-" write d$ & " --> " print ddate a[1] a[2] a[3] diff --git a/Task/Discordian-date/Euphoria/discordian-date.euphoria b/Task/Discordian-date/Euphoria/discordian-date.eu similarity index 100% rename from Task/Discordian-date/Euphoria/discordian-date.euphoria rename to Task/Discordian-date/Euphoria/discordian-date.eu diff --git a/Task/Discordian-date/Julia/discordian-date.julia b/Task/Discordian-date/Julia/discordian-date.jl similarity index 100% rename from Task/Discordian-date/Julia/discordian-date.julia rename to Task/Discordian-date/Julia/discordian-date.jl diff --git a/Task/Discordian-date/Kotlin/discordian-date.kotlin b/Task/Discordian-date/Kotlin/discordian-date.kts similarity index 100% rename from Task/Discordian-date/Kotlin/discordian-date.kotlin rename to Task/Discordian-date/Kotlin/discordian-date.kts diff --git a/Task/Discordian-date/Phix/discordian-date.phix b/Task/Discordian-date/Phix/discordian-date.phix index 2a44d313c0..9404c2065d 100644 --- a/Task/Discordian-date/Phix/discordian-date.phix +++ b/Task/Discordian-date/Phix/discordian-date.phix @@ -1,43 +1,41 @@ -(phixonline)--> - with javascript_semantics - constant seasons = {"Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"}, - weekday = {"Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle", "Setting Orange"}, - apostle = {"Mungday", "Mojoday", "Syaday", "Zaraday", "Maladay"}, - holiday = {"Chaoflux", "Discoflux", "Confuflux", "Bureflux", "Afflux"} +with javascript_semantics +constant seasons = {"Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"}, + weekday = {"Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle", "Setting Orange"}, + apostle = {"Mungday", "Mojoday", "Syaday", "Zaraday", "Maladay"}, + holiday = {"Chaoflux", "Discoflux", "Confuflux", "Bureflux", "Afflux"} - function discordianDate(sequence dt) - integer {y,m,d} = dt, - leap = is_leap_year(y), - doy = day_of_year(y,m,d)-1 - string dyear = sprintf("%d",y+1166) - if leap and m=2 and d=29 then - return "St. Tib's Day, in the YOLD " & dyear - end if - if leap and doy>=60 then - doy -= 1 - end if - integer dsday = remainder(doy,73)+1, - dseason = floor(doy/73+1) - if dsday=5 then - return apostle[dseason] & ", in the YOLD " & dyear - elsif dsday=50 then - return holiday[dseason] & ", in the YOLD " & dyear - end if - string dseas = seasons[dseason], - dwday = weekday[remainder(doy,5)+1] - return sprintf("%s, day %d of %s in the YOLD %s", {dwday, dsday, dseas, dyear}) - end function +function discordianDate(sequence dt) + integer {y,m,d} = dt, + leap = is_leap_year(y), + doy = day_of_year(y,m,d)-1 + string dyear = sprintf("%d",y+1166) + if leap and m=2 and d=29 then + return "St. Tib's Day, in the YOLD " & dyear + end if + if leap and doy>=60 then + doy -= 1 + end if + integer dsday = remainder(doy,73)+1, + dseason = floor(doy/73+1) + if dsday=5 then + return apostle[dseason] & ", in the YOLD " & dyear + elsif dsday=50 then + return holiday[dseason] & ", in the YOLD " & dyear + end if + string dseas = seasons[dseason], + dwday = weekday[remainder(doy,5)+1] + return sprintf("%s, day %d of %s in the YOLD %s", {dwday, dsday, dseas, dyear}) +end function - -- test code +-- test code - sequence dt = {2015,1,1,0,0,0,0,0} - include timedate.e - atom oneday = timedelta(days:=1) - set_timedate_formats({"DD/MM/YYYY"}) - for i=1 to 5 do - printf(1,"%s: %s\n",{format_timedate(dt),discordianDate(dt)}) - dt = adjust_timedate(dt,oneday*72) - printf(1,"%s: %s\n",{format_timedate(dt),discordianDate(dt)}) - dt = adjust_timedate(dt,oneday) - end for - - with javascript_semantics - function linear_combination(sequence f) - string res = "" - for e=1 to length(f) do - integer fe = f[e] - if fe!=0 then - if fe=1 then - if length(res) then res &= "+" end if - elsif fe=-1 then - res &= "-" - elsif fe>0 and length(res) then - res &= sprintf("+%d*",fe) - else - res &= sprintf("%d*",fe) - end if - res &= sprintf("e(%d)",e) - end if - end for - if res="" then res = "0" end if - return res - end function +with javascript_semantics +function linear_combination(sequence f) + string res = "", fmt + for i,e in f do + if e!=0 then + integer l = length(res) + if abs(e)=1 then + res &= iff(e<0?"-":iff(l?"+":"")) + else + fmt = iff(e>0 and l?"+%d*":"%d*") + res &= sprintf(fmt,e) + end if + res &= sprintf("e(%d)",i) + end if + end for + if res="" then res = "0" end if + return res +end function - constant tests = {{1,2,3}, - {0,1,2,3}, - {1,0,3,4}, - {1,2,0}, - {0,0,0}, - {0}, - {1,1,1}, - {-1,-1,-1}, - {-1,-2,0,-3}, - {-1}} - for i=1 to length(tests) do - sequence ti = tests[i] - printf(1,"%12s -> %s\n",{sprint(ti), linear_combination(ti)}) - end for - - without js -- file i/o - enum Airport_ID, Name, City, Country, IATA, ICAO, Latitude, Longitude, Altitude, Timezone, DST, Tz_Olson, Type, Source - function tabulate(sequence s) - s = split(trim(s),"\n") - for i,ri in s do - ri = split(ri,',') - if length(ri)!=14 then - ri[2] &= ","&ri[3] - ri[3..3] = {} - end if - for j in {Airport_ID, Latitude, Longitude, Altitude} do - ri[j] = to_number(ri[j]) - end for - for j in {Name,City,Country,ICAO} do - ri[j] = trim(ri[j],`"`) - end for - s[i] = ri - end for - return s - end function +without js -- file i/o +enum Airport_ID, Name, City, Country, IATA, ICAO, Latitude, Longitude, Altitude, Timezone, DST, Tz_Olson, Type, Source +function tabulate(sequence s) + s = split(trim(s),"\n") + for i,ri in s do + ri = split(ri,',') + if length(ri)!=14 then + ri[2] &= ","&ri[3] + ri[3..3] = {} + end if + for j in {Airport_ID, Latitude, Longitude, Altitude} do + ri[j] = to_number(ri[j]) + end for + for j in {Name,City,Country,ICAO} do + ri[j] = trim(ri[j],`"`) + end for + s[i] = ri + end for + return s +end function - constant airports = tabulate(get_text("airports.dat")) +constant airports = tabulate(get_text("airports.dat")) - function distance(atom lat1, lon1, lat2, lon2, integer units) - atom dist = 0 - if lat1!=lat2 or lon1!=lon2 then - atom radlat1 = lat1*PI/180, - radlat2 = lat2*PI/180, - radtheta = (lon1-lon2)*PI/180 - dist = sin(radlat1)*sin(radlat2) + cos(radlat1)*cos(radlat2)*cos(radtheta) - dist = arccos(min(dist,1))*180/PI * 60*1.1515576 -- in Statute Miles - if units = 'K' then dist *= 1.609344 end if -- in Kilometres - if units = 'N' then dist *= 0.868976 end if -- in Nautical Miles - end if - return dist - end function +function distance(atom lat1, lon1, lat2, lon2, integer units) + atom dist = 0 + if lat1!=lat2 or lon1!=lon2 then + atom radlat1 = lat1*PI/180, + radlat2 = lat2*PI/180, + radtheta = (lon1-lon2)*PI/180 + dist = sin(radlat1)*sin(radlat2) + cos(radlat1)*cos(radlat2)*cos(radtheta) + dist = arccos(min(dist,1))*180/PI * 60*1.1515576 -- in Statute Miles + if units = 'K' then dist *= 1.609344 end if -- in Kilometres + if units = 'N' then dist *= 0.868976 end if -- in Nautical Miles + end if + return dist +end function - function bearing(atom lat1, lon1, lat2, lon2) - atom bear = NULL - if lat1!=lat2 or lon1!=lon2 then - atom radlat1 = lat1*PI/180, - radlat2 = lat2*PI/180, - raddlon = (lon2-lon1)*PI/180, - y = sin(raddlon)*cos(radlat2), - x = cos(radlat1)*sin(radlat2) - sin(radlat1)*cos(radlat2)*cos(raddlon) - bear = remainder(atan2(y, x)*180/PI+360,360) - end if - return bear; - end function +function bearing(atom lat1, lon1, lat2, lon2) + atom bear = NULL + if lat1!=lat2 or lon1!=lon2 then + atom radlat1 = lat1*PI/180, + radlat2 = lat2*PI/180, + raddlon = (lon2-lon1)*PI/180, + y = sin(raddlon)*cos(radlat2), + x = cos(radlat1)*sin(radlat2) - sin(radlat1)*cos(radlat2)*cos(raddlon) + bear = remainder(atan2(y, x)*180/PI+360,360) + end if + return bear; +end function - procedure query(atom lat,lon, integer rows=20) - sequence r = {} - for a in airports do - atom lat2 = a[Latitude], - lon2 = a[Longitude], - dist = round(distance(lat,lon,lat2,lon2,'N'),10), - bear = round(bearing(lat,lon,lat2,lon2)) - r = append(r,{a[Name],a[Country],a[ICAO],dist,bear}) - end for - r = sort_columns(r,{4})[1..rows] - printf(1," Name | Country | ICAO | Distance in NM | Bearing in ° \n") - printf(1,"-------------------------------------+----------------+------+----------------+--------------\n") - printf(1,"%s\n",{join(r,"\n",fmt:=" %-36s| %-15s| %4s | %4.1f | %3d")}) - printf(1,"(%d rows)\n",rows) - end procedure +procedure query(atom lat,lon, integer rows=20) + sequence r = {} + for a in airports do + atom lat2 = a[Latitude], + lon2 = a[Longitude], + dist = round(distance(lat,lon,lat2,lon2,'N'),10), + bear = round(bearing(lat,lon,lat2,lon2)) + r = append(r,{a[Name],a[Country],a[ICAO],dist,bear}) + end for + r = sort_columns(r,{4})[1..rows] + printf(1," Name | Country | ICAO | Distance in NM | Bearing in ° \n") + printf(1,"-------------------------------------+----------------+------+----------------+--------------\n") + printf(1,"%s\n",{join(r,"\n",fmt:=" %-36s| %-15s| %4s | %4.1f | %3d")}) + printf(1,"(%d rows)\n",rows) +end procedure - query(51.514669, 2.198581) - - with javascript_semantics - sequence rfs = {1} -- reverse factorial(1) in base 1000 +with javascript_semantics +sequence rfs = {1} -- reverse factorial(1) in base 1000 - function init_zc() - sequence zc = repeat(0,999) - for x=1 to 9 do - zc[x] = 2 -- 00x - zc[10*x] = 2 -- 0x0 - zc[100*x] = 2 -- x00 - for y=10 to 90 by 10 do - zc[y+x] = 1 -- 0yx - zc[10*y+x] = 1 -- y0x - zc[10*(y+x)] = 1 -- yx0 - end for - end for - return zc - end function - constant zc = init_zc() +function init_zc() + sequence zc = repeat(0,999) + for x=1 to 9 do + zc[x] = 2 -- 00x + zc[10*x] = 2 -- 0x0 + zc[100*x] = 2 -- x00 + for y=10 to 90 by 10 do + zc[y+x] = 1 -- 0yx + zc[10*y+x] = 1 -- y0x + zc[10*(y+x)] = 1 -- yx0 + end for + end for + return zc +end function +constant zc = init_zc() - atom t0 = time(), - total = 0 - integer trail = 1, - first = 0 - for f=2 to iff(platform()=JS?10000:50000) do - integer carry = 0, d999, - zeroes = (trail-1)*3, - j = trail, l = length(rfs) - while j<=l or carry do - if j<=l then - carry = (rfs[j])*f+carry - end if - d999 = remainder(carry,1000) - if j<=l then - rfs[j] = d999 - else - rfs &= d999 - end if - zeroes += iff(d999=0?3:zc[d999]) - carry = floor(carry/1000) - j += 1 - end while - while rfs[trail]=0 do trail += 1 end while - -- d999 := quick correction for length and zeroes: - d999 = rfs[$] - d999 = iff(d999<100?iff(d999<10?2:1):0) - zeroes -= d999 - integer digits = length(rfs)*3-d999 +atom t0 = time(), + total = 0 +integer trail = 1, + first = 0 +for f=2 to iff(platform()=JS?10000:50000) do + integer carry = 0, d999, + zeroes = (trail-1)*3, + j = trail, l = length(rfs) + while j<=l or carry do + if j<=l then + carry = (rfs[j])*f+carry + end if + d999 = remainder(carry,1000) + if j<=l then + rfs[j] = d999 + else + rfs &= d999 + end if + zeroes += iff(d999=0?3:zc[d999]) + carry = floor(carry/1000) + j += 1 + end while + while rfs[trail]=0 do trail += 1 end while + -- d999 := quick correction for length and zeroes: + d999 = rfs[$] + d999 = iff(d999<100?iff(d999<10?2:1):0) + zeroes -= d999 + integer digits = length(rfs)*3-d999 - total += zeroes/digits - atom ratio = total/f - if ratio>=0.16 then - first = 0 - elsif first=0 then - first = f - end if - if find(f,{100,1000,10000}) then - string e = elapsed(time()-t0) - printf(1,"Mean proportion of zero digits in factorials to %d is %.10f (%s)\n",{f,ratio,e}) - end if - end for - if platform()!=JS then - string e = elapsed(time()-t0) - printf(1,"The mean proportion dips permanently below 0.16 at %d. (%s)\n",{first,e}) - end if - - with javascript_semantics - atom t0 = time(), - f10 = log10(1), - total = 0 - integer first = 0 - for f=2 to 50000 do - f10 += log10(f) - integer digits = ceil(f10), - zeroes = 0, - v = 5 - while v<=f do - zeroes += floor(f/v) - v *= 5 - end while - total += zeroes/digits - atom ratio = total/f - if ratio>=0.07 then - first = 0 - elsif first=0 then - first = f - end if - if find(f,{100,1000,10000}) then - printf(1,"Mean proportion of trailing zeroes in factorials to %d is %f\n",{f,ratio}) - end if - end for - string e = elapsed(time()-t0) - printf(1,"The mean proportion dips permanently below 0.07 at %d. (%s)\n",{first,e}) - s ) + [ stack ] is zeroes ( --> s ) + + [ 0 digits put + 0 zeroes put + [ 1 digits tally + 10 /mod 0 = + zeroes tally + dup 0 = until ] + drop + zeroes take + digits take + reduce ] is zeroprop ( n --> n/d ) + + [ dup dip + [ 0 n->v + 1 ] + times + [ i^ 1+ * + dup zeroprop + rot dip v+ ] + drop + rot n->v v/ ] is distribution ( n --> n/d ) + + 100 distribution 10 point$ echo$ cr + 1000 distribution 10 point$ echo$ cr + 10000 distribution 10 point$ echo$ cr diff --git a/Task/Distribution-of-0-digits-in-factorial-series/Rust/distribution-of-0-digits-in-factorial-series.rust b/Task/Distribution-of-0-digits-in-factorial-series/Rust/distribution-of-0-digits-in-factorial-series.rs similarity index 100% rename from Task/Distribution-of-0-digits-in-factorial-series/Rust/distribution-of-0-digits-in-factorial-series.rust rename to Task/Distribution-of-0-digits-in-factorial-series/Rust/distribution-of-0-digits-in-factorial-series.rs diff --git a/Task/Diversity-prediction-theorem/ANSI-BASIC/diversity-prediction-theorem.basic b/Task/Diversity-prediction-theorem/ANSI-BASIC/diversity-prediction-theorem.basic index 1bffb0d693..fc652fbb06 100644 --- a/Task/Diversity-prediction-theorem/ANSI-BASIC/diversity-prediction-theorem.basic +++ b/Task/Diversity-prediction-theorem/ANSI-BASIC/diversity-prediction-theorem.basic @@ -1,12 +1,12 @@ 100 PROGRAM DiversityPredictionTheorem 110 OPTION BASE 0 -120 DIM Estimates(1, 4) +120 DIM test(1, 4) 130 FOR I = 0 TO 1 140 LET J = 0 -150 READ Estimates(I, J) -160 DO WHILE Estimates(I, J) <> 0 +150 READ test(I, J) +160 DO WHILE test(I, J) <> 0 170 LET J = J + 1 -180 READ Estimates(I, J) +180 READ test(I, J) 190 LOOP 200 NEXT I 210 DATA 48.0, 47.0, 51.0, 0.0 @@ -15,16 +15,16 @@ 240 FOR I = 0 TO 1 250 LET Sum = 0 260 LET J = 0 -270 DO WHILE Estimates(I, J) <> 0 -280 LET Sum = Sum + (Estimates(I, J) - TrueVal) ^ 2 +270 DO WHILE test(I, J) <> 0 +280 LET Sum = Sum + (test(I, J) - TrueVal) ^ 2 290 LET J = J + 1 300 LOOP 310 LET AvgErr = Sum / J 320 PRINT USING "Average error : ##.###": AvgErr 330 LET Sum = 0 340 LET J = 0 -350 DO WHILE Estimates(I, J) <> 0 -360 LET Sum = Sum + Estimates(I, J) +350 DO WHILE test(I, J) <> 0 +360 LET Sum = Sum + test(I, J) 370 LET J = J + 1 380 LOOP 390 LET Avg = Sum / J diff --git a/Task/Diversity-prediction-theorem/Ada/diversity-prediction-theorem.ada b/Task/Diversity-prediction-theorem/Ada/diversity-prediction-theorem.adb similarity index 100% rename from Task/Diversity-prediction-theorem/Ada/diversity-prediction-theorem.ada rename to Task/Diversity-prediction-theorem/Ada/diversity-prediction-theorem.adb diff --git a/Task/Diversity-prediction-theorem/Asymptote/diversity-prediction-theorem.asymptote b/Task/Diversity-prediction-theorem/Asymptote/diversity-prediction-theorem.asymptote new file mode 100644 index 0000000000..d76b741bc3 --- /dev/null +++ b/Task/Diversity-prediction-theorem/Asymptote/diversity-prediction-theorem.asymptote @@ -0,0 +1,31 @@ +import math; + +real[][] estimates = { + {48, 47, 51}, + {48, 47, 51, 42} +}; + +real trueVal = 49; + +for (int i = 0; i < estimates.length; ++i) { + + real vari = 0; + real sum = 0; + + for (int j = 0; j < estimates[i].length; ++j) { + real d = estimates[i][j] - trueVal; + vari += d*d; + sum += estimates[i][j]; + } + + real n = estimates[i].length; + real avgErr = vari / n; + real refAvg = sum / n; + real crowdErr = (trueVal - refAvg)^2; + real div = avgErr - crowdErr; + + write("Average error : ", avgErr); + write(" Crowd error : ", crowdErr); + write(" Diversity : ", div); + write(""); +} diff --git a/Task/Diversity-prediction-theorem/Chipmunk-Basic/diversity-prediction-theorem.basic b/Task/Diversity-prediction-theorem/Chipmunk-Basic/diversity-prediction-theorem.basic new file mode 100644 index 0000000000..6c9a24f887 --- /dev/null +++ b/Task/Diversity-prediction-theorem/Chipmunk-Basic/diversity-prediction-theorem.basic @@ -0,0 +1,28 @@ +100 cls +110 dim estimates(1,5) +120 estimates(0,0) = 48 +130 estimates(0,1) = 47 +140 estimates(0,2) = 51 +150 estimates(1,0) = 48 +160 estimates(1,1) = 47 +170 estimates(1,2) = 51 +180 estimates(1,3) = 42 +190 trueval = 49 +200 for i = 0 to 1 +210 vari = 0 +220 sum = 0 +230 c = 0 +240 while estimates(i,c) <> 0 +250 vari = vari+(estimates(i,c)-trueval)^2 +260 sum = sum+estimates(i,c) +270 c = c+1 +280 wend +290 avgerr = vari/c +300 refavg = sum/c +310 crowderr = (trueval-refavg)^2 +320 print using "Average error : ###.###";avgerr +330 print using " Crowd error : ###.###";crowderr +340 print using " Diversity : ###.###";avgerr-crowderr +350 print +360 next i +370 end diff --git a/Task/Diversity-prediction-theorem/Crystal/diversity-prediction-theorem.cr b/Task/Diversity-prediction-theorem/Crystal/diversity-prediction-theorem.cr new file mode 100644 index 0000000000..e0d89e569a --- /dev/null +++ b/Task/Diversity-prediction-theorem/Crystal/diversity-prediction-theorem.cr @@ -0,0 +1,22 @@ +module Enumerable + def average + sum / size + end +end + +def get_values (true_value, crowd_estimates) + avg_individual_error = crowd_estimates.map {|e| (e - true_value)**2 }.average + collective_error = (crowd_estimates.average - true_value)**2 + crowd_avg = crowd_estimates.average + prediction_diversity = crowd_estimates.map {|e| (e - crowd_avg)**2 }.average + + { avg_individual_error, collective_error, prediction_diversity } +end + +puts "Value Crowd estimates Average error Crowd error Prediction diversity" +puts "---------------------------------------------------------------------------" + +[{49, [48, 47, 51]}, {49, [48, 47, 51, 42]}].each do |true_value, crowd_estimates| + printf " %2d %-20s %9.5f %9.5f %9.5f\n", true_value, crowd_estimates, + *get_values(true_value, crowd_estimates) +end diff --git a/Task/Diversity-prediction-theorem/Dart/diversity-prediction-theorem.dart b/Task/Diversity-prediction-theorem/Dart/diversity-prediction-theorem.dart new file mode 100644 index 0000000000..bd5382f318 --- /dev/null +++ b/Task/Diversity-prediction-theorem/Dart/diversity-prediction-theorem.dart @@ -0,0 +1,33 @@ +double sum(List array) { + double s = 0; + for (var x in array) s += x; + return s; +} + +double square(double x) => x * x; + +double mean(List array) => sum(array) / array.length; + +double averageSquareDiff(double a, List predictions) { + List results = []; + for (var x in predictions) { + results.add(square(x - a)); + } + return mean(results); +} + +void diversityTheorem(double truth, List predictions) { + double avgErr = averageSquareDiff(truth, predictions); + double avg = mean(predictions); + double crowdErr = square(truth - avg); + double diversity = averageSquareDiff(avg, predictions); + + print("Average error: ${avgErr.toStringAsFixed(4)}"); + print(" Crowd error: ${crowdErr.toStringAsFixed(4)}"); + print(" Diversity: ${diversity.toStringAsFixed(4)}\n"); +} + +void main() { + diversityTheorem(49, [48, 47, 51]); + diversityTheorem(49, [48, 47, 51, 42]); +} diff --git a/Task/Diversity-prediction-theorem/Delphi/diversity-prediction-theorem.delphi b/Task/Diversity-prediction-theorem/Delphi/diversity-prediction-theorem.pas similarity index 100% rename from Task/Diversity-prediction-theorem/Delphi/diversity-prediction-theorem.delphi rename to Task/Diversity-prediction-theorem/Delphi/diversity-prediction-theorem.pas diff --git a/Task/Diversity-prediction-theorem/DuckDB/diversity-prediction-theorem.duckdb b/Task/Diversity-prediction-theorem/DuckDB/diversity-prediction-theorem.duckdb new file mode 100644 index 0000000000..2cb2f486dd --- /dev/null +++ b/Task/Diversity-prediction-theorem/DuckDB/diversity-prediction-theorem.duckdb @@ -0,0 +1,31 @@ +create or replace function mean(lst) as ( + list_sum(lst)::DOUBLE / length(lst) +); + +# average absolute deviation relative to value +create or replace function aad(lst, value) as + list_transform(lst, x -> @(x-value)).list_sum() / length(lst) ; + +# average sum of squares +create or replace function ass(lst) as + list_transform(lst, x -> x ^ 2).list_sum() / length(lst); + +# Average sum of squared deviations relative to value +create or replace function asd(lst, value) as + list_transform(lst, x -> x - value).ass(); + +create or replace function diversitytheorem(actual, estimates) as table ( + select length(estimates) as "sample size", + actual as actual, + mean(estimates)::DECIMAL(4,2) as mean, + aad(estimates, actual)::DECIMAL(4,2) as "aad about actual", + aad(estimates, mean)::DECIMAL(4,2) as "aad about mean", + asd(estimates, actual)::DECIMAL(4,2) as "asd about actual", + asd(estimates, mean)::DECIMAL(4,2) as "asd about mean", + ((mean - actual) ^ 2)::DECIMAL(4,2) as "(mean-actual)^2" +); + +# The tasks: +from diversitytheorem(49, [48, 47, 51]) +union all +from diversitytheorem(49, [48, 47, 51, 42]); diff --git a/Task/Diversity-prediction-theorem/EasyLang/diversity-prediction-theorem.easy b/Task/Diversity-prediction-theorem/EasyLang/diversity-prediction-theorem.easy index 5ebd3731b8..2993d3082c 100644 --- a/Task/Diversity-prediction-theorem/EasyLang/diversity-prediction-theorem.easy +++ b/Task/Diversity-prediction-theorem/EasyLang/diversity-prediction-theorem.easy @@ -1,4 +1,4 @@ -proc calc TrueVal test[] . . +proc calc TrueVal test[] . for test in test[] h = (test - TrueVal) Vari += h * h @@ -10,8 +10,8 @@ proc calc TrueVal test[] . . h = (TrueVal - RefAvg) CrowdErr = h * h print "Average error : " & AvgErr - print " Crowd error : " & CrowdErr - print " Diversity : " & AvgErr - CrowdErr + print "Crowd error : " & CrowdErr + print "Diversity : " & AvgErr - CrowdErr print "" . calc 49 [ 48 47 51 ] diff --git a/Task/Diversity-prediction-theorem/Fortran/diversity-prediction-theorem.f b/Task/Diversity-prediction-theorem/Fortran/diversity-prediction-theorem.f new file mode 100644 index 0000000000..1de6707869 --- /dev/null +++ b/Task/Diversity-prediction-theorem/Fortran/diversity-prediction-theorem.f @@ -0,0 +1,58 @@ +! Diversity prediction theorem +! tested with Intel ifx (IFX) 2025.2.1 20250806 on Kubuntu 25.10 +! GNU gfortran (Ubuntu 15.2.0-4ubuntu4) 15.2.0 on Kubuntu 25.10 +! VSI Fortran x86-64 V8.7-001 on OpenVMS V9.2-3 +program DivTheo + +implicit none +integer, parameter :: DP = 8 ! Kind for double precision Reals + +real (kind=DP), dimension(3), parameter :: Case1 =[48._DP,47._DP,51._DP] +real (kind=DP), dimension(4), parameter :: Case2 =[48._DP,47._DP,51._DP,42._DP] + + +call diversityTheorem (49._DP, case1, size(Case1)) +write (*,*) +call diversityTheorem (49._DP, case2, size(Case2)) + +contains +subroutine diversityTheorem (trueValue, predictions, n) +real (kind=DP), intent(in) :: trueValue +integer, intent(in) :: n +integer :: i +real (kind=DP), dimension(n), intent(in) :: predictions + +real (kind=DP) :: avPred + +avPred = sum(predictions,n) / n +! From the task desciption: +! show... +! the true value and the crowd estimates +! the average error +! the crowd error +! the prediction diversity +write (*, '("true value :", F4.0)') trueValue +write (*, '("crowd''s estimate :", 8F4.0)') (predictions(i),i=1,n) +write (*, '("average error :", F8.4 )') avSqDiff (trueValue, predictions, n) +write (*, '("crowd error :", F8.4 )') (trueValue - avPred) ** 2 +write (*, '("diversity :", F8.4 )') avSqDiff (avPred, predictions, n) +end subroutine diversityTheorem + + + +function avSqDiff (av, pred, n) result (sqDiff) + +integer, intent(in) :: n +real (kind=DP), intent(in) :: av +real (kind=DP), dimension(n), intent(in) :: pred +real (kind=DP) sqDiff +integer :: ii +sqDiff = 0 +do ii=1,n + sqdiff = sqdiff + (av-pred(ii))**2 +enddo +sqDiff = sqDiff / n + +end function avSqDiff + +end program DivTheo diff --git a/Task/Diversity-prediction-theorem/FreeBASIC/diversity-prediction-theorem.basic b/Task/Diversity-prediction-theorem/FreeBASIC/diversity-prediction-theorem.basic index 2b67d7c69a..43b33a4ac2 100644 --- a/Task/Diversity-prediction-theorem/FreeBASIC/diversity-prediction-theorem.basic +++ b/Task/Diversity-prediction-theorem/FreeBASIC/diversity-prediction-theorem.basic @@ -18,9 +18,9 @@ For i = 0 To 1 RefAvg = Sum / c CrowdErr = (TrueVal - RefAvg) ^2 - Print Using "Average error : ###.###"; AvgErr - Print Using " Crowd error : ###.###"; CrowdErr - Print Using " Diversity : ###.###"; AvgErr - CrowdErr + Print Using "Average error : ##.####"; AvgErr + Print Using " Crowd error : ##.####"; CrowdErr + Print Using " Diversity : ##.####"; AvgErr - CrowdErr Print Sleep diff --git a/Task/Diversity-prediction-theorem/FutureBasic/diversity-prediction-theorem.basic b/Task/Diversity-prediction-theorem/FutureBasic/diversity-prediction-theorem.basic new file mode 100644 index 0000000000..33e8b12ae8 --- /dev/null +++ b/Task/Diversity-prediction-theorem/FutureBasic/diversity-prediction-theorem.basic @@ -0,0 +1,28 @@ +include "NSLog.incl" + +double local fn Square( d as double ) +end fn = d * d + +double local fn AverageSquareDiff( d as double, predictions as CFArrayRef ) + double sum = 0.0 + for CFNumberRef num in predictions + sum += fn Square( fn NumberDoubleValue( num ) - d ) + next + return sum / fn ArrayCount( predictions ) +end fn = 0.0 + +CFStringRef local fn DiversityTheorem( truth as double, predictions as CFArrayRef ) + double average = fn NumberDoubleValue( fn ObjectValueForKeyPath( predictions, @"@avg.self" ) ) + CFStringRef avgErr = fn StringWithFormat( @"%4.5f", fn AverageSquareDiff( truth, predictions ) ) + CFStringRef crowdErr = fn StringWithFormat( @"%6.5f", fn Square( truth - average ) ) + CFStringRef diversity = fn StringWithFormat( @"%6.5f", fn AverageSquareDiff( average, predictions ) ) + return fn StringWithFormat( @"Average error : %@\nCrowd error : %@\nDiversity : %@\n", avgErr, crowdErr, diversity ) +end fn = NULL + +NSLog( @"Diversity prediction with crowd estimates of 48, 47 and 51:" ) +NSLog( @"%@\n", fn DiversityTheorem( 49.0, @[@48.0, @47.0, @51.0] ) ) + +NSLog( @"Diversity prediction with crowd estimates of 48, 47, 51 and 42:" ) +NSLog( @"%@\n", fn DiversityTheorem( 49.0, @[@48.0, @47.0, @51.0, @42.0] ) ) + +HandleEvents diff --git a/Task/Diversity-prediction-theorem/Gambas/diversity-prediction-theorem.gambas b/Task/Diversity-prediction-theorem/Gambas/diversity-prediction-theorem.gambas new file mode 100644 index 0000000000..0c4b0f6e73 --- /dev/null +++ b/Task/Diversity-prediction-theorem/Gambas/diversity-prediction-theorem.gambas @@ -0,0 +1,39 @@ +Public Sub Main() + + Dim test As New Float[2, 5] + + test[0, 0] = 48 + test[0, 1] = 47 + test[0, 2] = 51 + test[1, 0] = 48 + test[1, 1] = 47 + test[1, 2] = 51 + test[1, 3] = 42 + + Dim TrueVal As Float = 49 + Dim AvgErr As Float, CrowdErr As Float, RefAvg As Float + Dim Vari As Float, Sum As Float + Dim i As Integer, c As Integer + + For i = 0 To 1 + Vari = 0 + Sum = 0 + c = 0 + + While test[i, c] <> 0 + Vari += (test[i, c] - TrueVal) ^ 2 + Sum += test[i, c] + c += 1 + Wend + + AvgErr = Vari / c + RefAvg = Sum / c + CrowdErr = (TrueVal - RefAvg) ^ 2 + + Print "Average error : "; Format$(AvgErr, "##.###0") + Print " Crowd error : "; Format$(CrowdErr, "##.###0") + Print " Diversity : "; Format$(AvgErr - CrowdErr, "##.###0") + Print + Next + +End diff --git a/Task/Diversity-prediction-theorem/Julia/diversity-prediction-theorem.julia b/Task/Diversity-prediction-theorem/Julia/diversity-prediction-theorem.jl similarity index 100% rename from Task/Diversity-prediction-theorem/Julia/diversity-prediction-theorem.julia rename to Task/Diversity-prediction-theorem/Julia/diversity-prediction-theorem.jl diff --git a/Task/Diversity-prediction-theorem/Kotlin/diversity-prediction-theorem.kotlin b/Task/Diversity-prediction-theorem/Kotlin/diversity-prediction-theorem.kts similarity index 100% rename from Task/Diversity-prediction-theorem/Kotlin/diversity-prediction-theorem.kotlin rename to Task/Diversity-prediction-theorem/Kotlin/diversity-prediction-theorem.kts diff --git a/Task/Diversity-prediction-theorem/Loglan82/diversity-prediction-theorem.loglan82 b/Task/Diversity-prediction-theorem/Loglan82/diversity-prediction-theorem.loglan82 new file mode 100644 index 0000000000..076c7fc72c --- /dev/null +++ b/Task/Diversity-prediction-theorem/Loglan82/diversity-prediction-theorem.loglan82 @@ -0,0 +1,53 @@ +program diverspredict; +(* Diversity prediction theorem *) + +var + true_val: real, + estims: arrayof arrayof real, + sum, avg, avg_err, crowd_err, diff: real, + i, j: integer; +begin + array estims dim (0 : 1); + for i := 0 to 1 + do + array estims(i) dim (0 : 4) + od; + + estims(0, 0) := 48.0; + estims(0, 1) := 47.0; + estims(0, 2) := 51.0; + estims(0, 3) := 0.0; + estims(0, 4) := 0.0; + estims(1, 0) := 48.0; + estims(1, 1) := 47.0; + estims(1, 2) := 51.0; + estims(1, 3) := 42.0; + estims(1, 4) := 0.0; + true_val := 49.0; + for i := 0 to 1 + do + sum := 0.0; + j := 0; + while estims(i, j) =/= 0 + do + diff := estims(i, j) - true_val; + sum := sum + diff * diff; + j := j + 1; + od; + avg_err := sum / j; + writeln("Average error : ", avg_err: 7: 3); + sum := 0; + j := 0; + while estims(i, j) =/= 0 + do + sum := sum + estims(i, j); + j := j + 1; + od; + avg := sum / j; + diff := true_val - avg; + crowd_err := diff * diff; + writeln("Crowd error : ", crowd_err: 7: 3); + writeln("Diversity : ", avg_err - crowd_err: 7: 3); + writeln; + od +end diff --git a/Task/Diversity-prediction-theorem/MSX-Basic/diversity-prediction-theorem.basic b/Task/Diversity-prediction-theorem/MSX-Basic/diversity-prediction-theorem.basic new file mode 100644 index 0000000000..6884ab01b3 --- /dev/null +++ b/Task/Diversity-prediction-theorem/MSX-Basic/diversity-prediction-theorem.basic @@ -0,0 +1,33 @@ +100 CLS +110 DIM TS!(1,4) +120 TS!(0,0) = 48 +130 TS!(0,1) = 47 +140 TS!(0,2) = 51 +170 TS!(1,0) = 48 +180 TS!(1,1) = 47 +190 TS!(1,2) = 51 +200 TS!(1,3) = 42 +220 EV! = 49 +230 FOR I = 0 TO 1 +240 VA! = 0 +250 SM! = 0 +260 N = 0 +270 C = 0 +280 IF TS!(I,C) = 0 THEN 340 +290 DF! = TS!(I,C) - EV! +300 VA! = VA! + EXP(LOG(ABS(DF!)) * 2) +310 SM! = SM! + TS!(I,C) +320 N = N + 1 +330 C = C + 1 : GOTO 280 +340 C = C - 1 +350 IF N = 0 THEN 440 ' por si acaso +360 AV! = VA!/N +370 RV! = SM!/N +380 DF! = EV!-RV! +390 CR! = EXP(LOG(ABS(DF!))*2) +400 PRINT USING "Average error : ##.####";AV! +410 PRINT USING " Crowd error : ##.####";CR! +420 PRINT USING " Diversity : ##.####";AV!-CR! +430 PRINT +440 NEXT +350 END diff --git a/Task/Diversity-prediction-theorem/Maxima/diversity-prediction-theorem.maxima b/Task/Diversity-prediction-theorem/Maxima/diversity-prediction-theorem.maxima new file mode 100644 index 0000000000..d25d8de345 --- /dev/null +++ b/Task/Diversity-prediction-theorem/Maxima/diversity-prediction-theorem.maxima @@ -0,0 +1,10 @@ +diversityprediction(obs, ests) := block( + sprint("True value:", obs), newline(), + apply(sprint, cons("Estimates:", ests)), newline(), + sprint("Average error:", mean((obs-ests)^2)), newline(), + sprint("Crowd error:", (obs-mean(ests))^2), newline(), + sprint("Prediction diversity:", mean((mean(ests)-ests)^2)) +)$ + +diversityprediction(49, [48, 47, 51])$ +diversityprediction(49, [48, 47, 51, 42])$ diff --git a/Task/Diversity-prediction-theorem/Modula-2/diversity-prediction-theorem.mod2 b/Task/Diversity-prediction-theorem/Modula-2/diversity-prediction-theorem.mod2 new file mode 100644 index 0000000000..38528dab9d --- /dev/null +++ b/Task/Diversity-prediction-theorem/Modula-2/diversity-prediction-theorem.mod2 @@ -0,0 +1,48 @@ +MODULE DiversPredict; +(* Diversity prediction theorem *) + +FROM STextIO IMPORT + WriteLn, WriteString; +FROM SRealIO IMPORT + WriteFixed; + +TYPE + TEstims = ARRAY [0 .. 1], [0 .. 4] OF REAL; +VAR + Estims: TEstims; + TrueVal, Sum, AvgErr, Avg, CrowdErr, Diff: REAL; + I, J: CARDINAL; +BEGIN + Estims := TEstims{{48.0, 47.0, 51.0, 0.0, 0.0}, + {48.0, 47.0, 51.0, 42.0, 0.0}}; + TrueVal := 49.0; + FOR I := 0 TO 1 DO + Sum := 0.0; + J := 0; + WHILE Estims[I, J] <> 0.0 DO + Diff := Estims[I, J] - TrueVal; + Sum := Sum + Diff * Diff; + J := J + 1; + END; + AvgErr := Sum / FLOAT(J); + WriteString("Average error: "); + WriteFixed(AvgErr, 3, 7); + WriteLn; + Sum := 0.0; + J := 0; + WHILE Estims[I, J] <> 0.0 DO + Sum := Sum + Estims[I, J]; + J := J + 1; + END; + Avg := Sum / FLOAT(J); + Diff := TrueVal - Avg; + CrowdErr := Diff * Diff; + WriteString("Crowd error : "); + WriteFixed(CrowdErr, 3, 7); + WriteLn; + WriteString("Diversity : "); + WriteFixed(AvgErr - CrowdErr, 3, 7); + WriteLn; + WriteLn; + END; +END DiversPredict. diff --git a/Task/Diversity-prediction-theorem/Nascom-BASIC/diversity-prediction-theorem.basic b/Task/Diversity-prediction-theorem/Nascom-BASIC/diversity-prediction-theorem.basic index 3136029ccc..a934c0e988 100644 --- a/Task/Diversity-prediction-theorem/Nascom-BASIC/diversity-prediction-theorem.basic +++ b/Task/Diversity-prediction-theorem/Nascom-BASIC/diversity-prediction-theorem.basic @@ -1,5 +1,5 @@ 10 REM Diversity prediction theorem -20 DIM EST(1,4):REM Estimates +20 DIM EST(1,4):REM test 30 FOR I=0 TO 1 40 J=0:READ EST(I,J) 50 IF EST(I,J)=0 THEN 80 diff --git a/Task/Diversity-prediction-theorem/OxygenBasic/diversity-prediction-theorem.basic b/Task/Diversity-prediction-theorem/OxygenBasic/diversity-prediction-theorem.basic new file mode 100644 index 0000000000..6c4feeb2c1 --- /dev/null +++ b/Task/Diversity-prediction-theorem/OxygenBasic/diversity-prediction-theorem.basic @@ -0,0 +1,37 @@ +uses console + +dim float test(1, 4) +test(0,0) = 48 +test(0,1) = 47 +test(0,2) = 51 +test(1,0) = 48 +test(1,1) = 47 +test(1,2) = 51 +test(1,3) = 42 +test(1,4) = 0 + +dim float TrueVal = 49 +dim float AvgErr, CrowdErr, RefAvg, Vari, Sum +int i, c + +for i = 0 to 1 + Vari = 0 + Sum = 0 + c = 0 + while test(i,c) <> 0 + Vari += pow(test(i,c) - TrueVal) + Sum += test(i,c) + c += 1 + wend + AvgErr = Vari / c + RefAvg = Sum / c + CrowdErr = pow(TrueVal - RefAvg) + + printl "Average error : " AvgErr + printl " Crowd error : " CrowdErr + printl " Diversity : " AvgErr - CrowdErr + printl +next i + +printl cr "Enter ..." +waitkey diff --git a/Task/Diversity-prediction-theorem/PHP/diversity-prediction-theorem.php b/Task/Diversity-prediction-theorem/PHP/diversity-prediction-theorem.php new file mode 100644 index 0000000000..fb7d657c1f --- /dev/null +++ b/Task/Diversity-prediction-theorem/PHP/diversity-prediction-theorem.php @@ -0,0 +1,33 @@ + diff --git a/Task/Diversity-prediction-theorem/PL-I/diversity-prediction-theorem.pli b/Task/Diversity-prediction-theorem/PL-I/diversity-prediction-theorem.pli new file mode 100644 index 0000000000..3dcf57be5b --- /dev/null +++ b/Task/Diversity-prediction-theorem/PL-I/diversity-prediction-theorem.pli @@ -0,0 +1,36 @@ +/* Diversity prediction theorem */ + +diversity_predict: + procedure options(main); + declare + true_val float binary(15) static initial(49.0), + estims(0 : 1, 0 : 4) float binary(15) + static initial(48.0, 47.0, 51.0, 0.0, 0.0, + 48.0, 47.0, 51.0, 42.0, 0.0), + (sum, avg, avg_err, crowd_err) float binary(24), + (i, j) fixed binary(15); + do i = 0 to 1; + sum = 0.0; + j = 0; + do while (estims(i, j) ~= 0); + sum = sum + ((estims(i, j) - true_val) * (estims(i, j) - true_val)); + j = j + 1; + end; + avg_err = sum / j; + put skip list('Average error : '); + put edit(avg_err)(f(6, 3)); + sum = 0; + j = 0; + do while (estims(i, j) ~= 0); + sum = sum + estims(i, j); + j = j + 1; + end; + avg = sum / j; + crowd_err = (true_val - avg) * (true_val - avg); + put skip list('Crowd error : '); + put edit(crowd_err)(f(6, 3)); + put skip list('Diversity : '); + put edit(avg_err - crowd_err)(f(6, 3)); + put skip list(''); + end; +end diversity_predict; diff --git a/Task/Diversity-prediction-theorem/Pascal-P/diversity-prediction-theorem.pas b/Task/Diversity-prediction-theorem/Pascal-P/diversity-prediction-theorem.pas new file mode 100644 index 0000000000..b473430016 --- /dev/null +++ b/Task/Diversity-prediction-theorem/Pascal-P/diversity-prediction-theorem.pas @@ -0,0 +1,46 @@ +program diverspred(output); + + (* Diversity prediction theorem *) + +var + trueval, sum, avg, avgerr, crowderr: real; + estims: array [0 .. 1, 0 .. 4] of real; + i, j: integer; +begin + estims[0, 0] := 48.0; + estims[0, 1] := 47.0; + estims[0, 2] := 51.0; + estims[0, 3] := 0.0; + estims[0, 4] := 0.0; + estims[1, 0] := 48.0; + estims[1, 1] := 47.0; + estims[1, 2] := 51.0; + estims[1, 3] := 42.0; + estims[1, 4] := 0.0; + trueval := 49.0; + for i := 0 to 1 do + begin + sum := 0.0; + j := 0; + while estims[i, j] <> 0 do + begin + sum := sum + sqr(estims[i, j] - trueval); + j := j + 1; + end; + avgerr := sum / j; + writeln('Average error : ', avgerr: 10); + sum := 0; + j := 0; + while estims[i, j] <> 0 do + begin + sum := sum + estims[i, j]; + j := j + 1; + end; + avg := sum / j; + crowderr := sqr(trueval - avg); + writeln('Crowd error : ', crowderr: 10); + writeln('Diversity : ', avgerr - crowderr: 10); + writeln; + end; + (* readln; *) +end. diff --git a/Task/Diversity-prediction-theorem/PascalABC.NET/diversity-prediction-theorem.pas b/Task/Diversity-prediction-theorem/PascalABC.NET/diversity-prediction-theorem.pas new file mode 100644 index 0000000000..972e2e8c39 --- /dev/null +++ b/Task/Diversity-prediction-theorem/PascalABC.NET/diversity-prediction-theorem.pas @@ -0,0 +1,14 @@ +## +function AverageSquareDiff(a: real; predictions: array of real) := + predictions.Select(x -> (x - a).Sqr).Average; + +procedure DiversityTheorem(truth: real; predictions: array of real); +begin + var average := predictions.Average; + WriteLn('average-error: ', AverageSquareDiff(truth, predictions)); + WriteLn('crowd-error: ', (truth - average).Sqr); + WriteLn('diversity: ', AverageSquareDiff(average, predictions)); +end; + +DiversityTheorem(49.0, [48.0, 47.0, 51.0]); +DiversityTheorem(49.0, [48.0, 47.0, 51.0, 42.0]) diff --git a/Task/Diversity-prediction-theorem/Pluto/diversity-prediction-theorem.pluto b/Task/Diversity-prediction-theorem/Pluto/diversity-prediction-theorem.pluto new file mode 100644 index 0000000000..1d972f1fd2 --- /dev/null +++ b/Task/Diversity-prediction-theorem/Pluto/diversity-prediction-theorem.pluto @@ -0,0 +1,25 @@ +local fmt = require "fmt" +require "table2" + +local function average_square_diff(f, preds) + local av = 0 + for preds as pred do av += (pred - f) * (pred - f) end + return av / #preds +end + +local function diversity_theorem(truth, preds) + local av = preds:mean() + local av_err = average_square_diff(truth, preds) + local crowd_err = (truth - av) * (truth - av) + local div = average_square_diff(av, preds) + return av_err, crowd_err, div +end + +local preds_list = { {48, 47, 51}, {48, 47, 51, 42} } +local truth = 49 +for preds_list as preds do + local av_err, crowd_err, div = diversity_theorem(truth, preds) + fmt.print("Average-error : %6.3f", av_err) + fmt.print("Crowd-error : %6.3f", crowd_err) + fmt.print("Diversity : %6.3f\n", div) +end diff --git a/Task/Diversity-prediction-theorem/Python/diversity-prediction-theorem-1.py b/Task/Diversity-prediction-theorem/Python/diversity-prediction-theorem-1.py new file mode 100644 index 0000000000..e4b11515ad --- /dev/null +++ b/Task/Diversity-prediction-theorem/Python/diversity-prediction-theorem-1.py @@ -0,0 +1,15 @@ +def mean(lst): + return sum(lst)/len(lst) + +def squarediffs(x, lst): + return [(x-y)**2 for y in lst] + +def diversityprediction(obs, ests): + print("True value:", obs) + print("Estimates:", *ests) + print("Average error:", mean(squarediffs(obs, ests))) + print("Crowd error:", (obs-mean(ests))**2) + print("Prediction diversity:", mean(squarediffs(mean(ests), ests))) + +diversityprediction(49, [48, 47, 51]) +diversityprediction(49, [48, 47, 51, 42]) diff --git a/Task/Diversity-prediction-theorem/Python/diversity-prediction-theorem.py b/Task/Diversity-prediction-theorem/Python/diversity-prediction-theorem-2.py similarity index 100% rename from Task/Diversity-prediction-theorem/Python/diversity-prediction-theorem.py rename to Task/Diversity-prediction-theorem/Python/diversity-prediction-theorem-2.py diff --git a/Task/Diversity-prediction-theorem/QBasic/diversity-prediction-theorem.basic b/Task/Diversity-prediction-theorem/QBasic/diversity-prediction-theorem.basic new file mode 100644 index 0000000000..874655f894 --- /dev/null +++ b/Task/Diversity-prediction-theorem/QBasic/diversity-prediction-theorem.basic @@ -0,0 +1,29 @@ +DIM test(0 TO 1, 0 TO 4) AS DOUBLE +test(0, 0) = 48! +test(0, 1) = 47! +test(0, 2) = 51! +test(1, 0) = 48! +test(1, 1) = 47! +test(1, 2) = 51! +test(1, 3) = 42! + +TrueVal = 49! + +FOR i = 0 TO 1 + Vari = 0! + Sum = 0! + c = 0 + WHILE test(i, c) <> 0 + Vari = Vari + (test(i, c) - TrueVal) ^ 2 + Sum = Sum + test(i, c) + c = c + 1 + WEND + AvgErr = Vari / c + RefAvg = Sum / c + CrowdErr = (TrueVal - RefAvg) ^ 2 + + PRINT USING "Average error : ##.####"; AvgErr + PRINT USING " Crowd error : ##.####"; CrowdErr + PRINT USING " Diversity : ##.####"; AvgErr - CrowdErr + PRINT +NEXT i diff --git a/Task/Diversity-prediction-theorem/QuickBASIC/diversity-prediction-theorem.basic b/Task/Diversity-prediction-theorem/QuickBASIC/diversity-prediction-theorem.basic index 99ab57b239..e35a3355d0 100644 --- a/Task/Diversity-prediction-theorem/QuickBASIC/diversity-prediction-theorem.basic +++ b/Task/Diversity-prediction-theorem/QuickBASIC/diversity-prediction-theorem.basic @@ -1,11 +1,11 @@ REM Diversity prediction theorem -DIM Estimates(1, 4) +DIM test(1, 4) FOR I% = 0 TO 1 J% = 0 - READ Estimates(I%, J%) - WHILE Estimates(I%, J%) <> 0! + READ test(I%, J%) + WHILE test(I%, J%) <> 0! J% = J% + 1 - READ Estimates(I%, J%) + READ test(I%, J%) WEND NEXT I% DATA 48.0, 47.0, 51.0, 0.0 @@ -13,14 +13,14 @@ DATA 48.0, 47.0, 51.0, 42.0, 0.0 TrueVal = 49! FOR I% = 0 TO 1 Sum = 0!: J% = 0 - WHILE Estimates(I%, J%) <> 0! - Sum = Sum + (Estimates(I%, J%) - TrueVal) ^ 2: J% = J% + 1 + WHILE test(I%, J%) <> 0! + Sum = Sum + (test(I%, J%) - TrueVal) ^ 2: J% = J% + 1 WEND AvgErr = Sum / J% PRINT USING "Average error : ##.###"; AvgErr Sum = 0!: J% = 0 - WHILE Estimates(I%, J%) <> 0! - Sum = Sum + Estimates(I%, J%): J% = J% + 1 + WHILE test(I%, J%) <> 0! + Sum = Sum + test(I%, J%): J% = J% + 1 WEND Avg = Sum / J% CrowdErr = (TrueVal - Avg) ^ 2 diff --git a/Task/Diversity-prediction-theorem/Ruby/diversity-prediction-theorem.rb b/Task/Diversity-prediction-theorem/Ruby/diversity-prediction-theorem.rb index 5916702ef5..fb07cc9e10 100644 --- a/Task/Diversity-prediction-theorem/Ruby/diversity-prediction-theorem.rb +++ b/Task/Diversity-prediction-theorem/Ruby/diversity-prediction-theorem.rb @@ -1,5 +1,5 @@ def mean(a) = a.sum(0.0) / a.size -def mean_square_diff(a, predictions) = mean(predictions.map { |x| square(x - a)**2 }) +def mean_square_diff(a, predictions) = mean(predictions.map { |x| (x - a)**2 }) def diversity_theorem(truth, predictions) average = mean(predictions) diff --git a/Task/Diversity-prediction-theorem/True-BASIC/diversity-prediction-theorem.basic b/Task/Diversity-prediction-theorem/True-BASIC/diversity-prediction-theorem.basic new file mode 100644 index 0000000000..0ca506e3ca --- /dev/null +++ b/Task/Diversity-prediction-theorem/True-BASIC/diversity-prediction-theorem.basic @@ -0,0 +1,27 @@ +DIM test(0 to 1, 0 to 4) +LET test(0, 0) = 48.0 +LET test(0, 1) = 47.0 +LET test(0, 2) = 51.0 +LET test(1, 0) = 48.0 +LET test(1, 1) = 47.0 +LET test(1, 2) = 51.0 +LET test(1, 3) = 42.0 +LET trueval = 49.0 +FOR i = 0 to 1 + LET vari = 0.0 + LET sum = 0.0 + LET c = 0 + DO while test(i, c) <> 0 + LET vari = vari+(test(i, c)-trueval)^2 + LET sum = sum+test(i, c) + LET c = c+1 + LOOP + LET avgerr = vari/c + LET refavg = sum/c + LET crowderr = (trueval-refavg)^2 + PRINT using "Average error : ###.###": avgerr + PRINT using " Crowd error : ###.###": crowderr + PRINT using " Diversity : ###.###": avgerr-crowderr + PRINT +NEXT i +END diff --git a/Task/Diversity-prediction-theorem/XBasic/diversity-prediction-theorem.basic b/Task/Diversity-prediction-theorem/XBasic/diversity-prediction-theorem.basic new file mode 100644 index 0000000000..b96d40c2e3 --- /dev/null +++ b/Task/Diversity-prediction-theorem/XBasic/diversity-prediction-theorem.basic @@ -0,0 +1,36 @@ +PROGRAM "Diversity prediction theorem" +VERSION "0.0000" + +DECLARE FUNCTION Entry () + +FUNCTION Entry () + DIM test![1,4] + test![0, 0] = 48.0 + test![0, 1] = 47.0 + test![0, 2] = 51.0 + test![1, 0] = 48.0 + test![1, 1] = 47.0 + test![1, 2] = 51.0 + test![1, 3] = 42.0 + TrueVal! = 49.0 + + FOR i = 0 TO 1 + Vari! = 0.0 + Sum! = 0.0 + c = 0 + DO WHILE test![i, c] <> 0 + Vari! = Vari! + (test![i, c] - TrueVal!) ** 2 + Sum! = Sum! + test![i, c] + INC c + LOOP + AvgErr! = Vari! / c + RefAvg! = Sum! / c + CrowdErr! = (TrueVal! - RefAvg!) ** 2 + + PRINT "Average error : "; FORMAT$(STR$(AvgErr!), "##.###") + PRINT " Crowd error : "; FORMAT$(STR$(CrowdErr!), "##.###") + PRINT " Diversity : "; FORMAT$(STR$(AvgErr! - CrowdErr!), "##.###") + PRINT + NEXT i +END FUNCTION +END PROGRAM diff --git a/Task/Diversity-prediction-theorem/Yabasic/diversity-prediction-theorem.basic b/Task/Diversity-prediction-theorem/Yabasic/diversity-prediction-theorem.basic new file mode 100644 index 0000000000..55f6e04847 --- /dev/null +++ b/Task/Diversity-prediction-theorem/Yabasic/diversity-prediction-theorem.basic @@ -0,0 +1,30 @@ +dim test(1,4) +test(0,0) = 48.0 +test(0,1) = 47.0 +test(0,2) = 51.0 + +test(1,0) = 48.0 +test(1,1) = 47.0 +test(1,2) = 51.0 +test(1,3) = 42.0 + +TrueVal = 49.0 + +for i = 0 to 1 + Vari = 0.0 + Sum = 0.0 + c = 0 + while test(i,c) <> 0.0 + Vari = Vari + (test(i,c) - TrueVal) ^2 + Sum = Sum + test(i,c) + c = c + 1 + wend + AvgErr = Vari / c + RefAvg = Sum / c + CrowdErr = (TrueVal - RefAvg) ^2 + + print "Average error : ", AvgErr using("##.###") + print " Crowd error : ", CrowdErr using("##.###") + print " Diversity : ", AvgErr - CrowdErr using("##.###") + print +next i diff --git a/Task/Documentation/AWK/documentation.awk b/Task/Documentation/AWK/documentation.awk new file mode 100644 index 0000000000..f12f3545a5 --- /dev/null +++ b/Task/Documentation/AWK/documentation.awk @@ -0,0 +1,2 @@ +# AWK doesn't support this construct, you will have to use comments. +# The hash symbol # starts a comment. It ends at EOL. diff --git a/Task/Documentation/Ada/documentation.ada b/Task/Documentation/Ada/documentation.adb similarity index 100% rename from Task/Documentation/Ada/documentation.ada rename to Task/Documentation/Ada/documentation.adb diff --git a/Task/Documentation/C++/documentation.cpp b/Task/Documentation/C++/documentation.cpp new file mode 100644 index 0000000000..5298cffd6d --- /dev/null +++ b/Task/Documentation/C++/documentation.cpp @@ -0,0 +1,28 @@ +/* + * Program Title: Rosetta Code, Documentation + * Author : John Doe + * Version : 0.1 + * Date : 2023/12/31 + * Copyright : Public domain + * Description : An example of C++ program documentation +*/ +#include +#include + +/* + * Calculates the area of a circle with the given radius + */ +double area_circle(const double& radius) { + return (std::numbers::pi * radius * radius); +} + +// Controls the program +int main() { + // Obtain the users input + double radius; + std::cout << "Enter the radius of a circle in centimetres: "; + std::cin >> radius; + + // Display the result + std::cout << "The area of the circle is " << area_circle(radius) << " cm\u00b2" << "\n"; +} diff --git a/Task/Documentation/COBOL/documentation-1.cobol b/Task/Documentation/COBOL/documentation-1.cob similarity index 100% rename from Task/Documentation/COBOL/documentation-1.cobol rename to Task/Documentation/COBOL/documentation-1.cob diff --git a/Task/Documentation/COBOL/documentation-2.cobol b/Task/Documentation/COBOL/documentation-2.cob similarity index 100% rename from Task/Documentation/COBOL/documentation-2.cobol rename to Task/Documentation/COBOL/documentation-2.cob diff --git a/Task/Documentation/Crystal/documentation.crystal b/Task/Documentation/Crystal/documentation.cr similarity index 100% rename from Task/Documentation/Crystal/documentation.crystal rename to Task/Documentation/Crystal/documentation.cr diff --git a/Task/Documentation/Delphi/documentation.delphi b/Task/Documentation/Delphi/documentation.pas similarity index 100% rename from Task/Documentation/Delphi/documentation.delphi rename to Task/Documentation/Delphi/documentation.pas diff --git a/Task/Documentation/DuckDB/documentation-1.duckdb b/Task/Documentation/DuckDB/documentation-1.duckdb new file mode 100644 index 0000000000..6c629e36b7 --- /dev/null +++ b/Task/Documentation/DuckDB/documentation-1.duckdb @@ -0,0 +1,4 @@ +CREATE TABLE t AS (SELECT unnest([])); +COMMENT ON TABLE t IS /* this is just an example */ 'foo bar'; -- ignore me + +select comment from duckdb_tables where table_name = 't'; diff --git a/Task/Documentation/DuckDB/documentation-2.duckdb b/Task/Documentation/DuckDB/documentation-2.duckdb new file mode 100644 index 0000000000..4a22932f1c --- /dev/null +++ b/Task/Documentation/DuckDB/documentation-2.duckdb @@ -0,0 +1 @@ +COMMENT ON MACRO TABLE is ; diff --git a/Task/Documentation/DuckDB/documentation-3.duckdb b/Task/Documentation/DuckDB/documentation-3.duckdb new file mode 100644 index 0000000000..09ed87c083 --- /dev/null +++ b/Task/Documentation/DuckDB/documentation-3.duckdb @@ -0,0 +1,3 @@ +COMMENT ON TABLE main.test_table IS 'very nice table'; + +COMMENT ON COLUMN test_table.test_table_column IS 'very nice column'; diff --git a/Task/Documentation/Elixir/documentation-1.elixir b/Task/Documentation/Elixir/documentation-1.ex similarity index 100% rename from Task/Documentation/Elixir/documentation-1.elixir rename to Task/Documentation/Elixir/documentation-1.ex diff --git a/Task/Documentation/Elixir/documentation-2.elixir b/Task/Documentation/Elixir/documentation-2.ex similarity index 100% rename from Task/Documentation/Elixir/documentation-2.elixir rename to Task/Documentation/Elixir/documentation-2.ex diff --git a/Task/Documentation/Emacs-Lisp/documentation-1.l b/Task/Documentation/Emacs-Lisp/documentation-1.el similarity index 100% rename from Task/Documentation/Emacs-Lisp/documentation-1.l rename to Task/Documentation/Emacs-Lisp/documentation-1.el diff --git a/Task/Documentation/Emacs-Lisp/documentation-2.l b/Task/Documentation/Emacs-Lisp/documentation-2.el similarity index 100% rename from Task/Documentation/Emacs-Lisp/documentation-2.l rename to Task/Documentation/Emacs-Lisp/documentation-2.el diff --git a/Task/Documentation/Julia/documentation-1.julia b/Task/Documentation/Julia/documentation-1.jl similarity index 100% rename from Task/Documentation/Julia/documentation-1.julia rename to Task/Documentation/Julia/documentation-1.jl diff --git a/Task/Documentation/Julia/documentation-2.julia b/Task/Documentation/Julia/documentation-2.jl similarity index 100% rename from Task/Documentation/Julia/documentation-2.julia rename to Task/Documentation/Julia/documentation-2.jl diff --git a/Task/Documentation/Kotlin/documentation.kotlin b/Task/Documentation/Kotlin/documentation.kts similarity index 100% rename from Task/Documentation/Kotlin/documentation.kotlin rename to Task/Documentation/Kotlin/documentation.kts diff --git a/Task/Documentation/Phix/documentation.phix b/Task/Documentation/Phix/documentation.phix index d6302271c7..fcc24396b9 100644 --- a/Task/Documentation/Phix/documentation.phix +++ b/Task/Documentation/Phix/documentation.phix @@ -1,12 +1,10 @@ -(phixonline)--> - procedure StoreVar(integer N, integer NTyp) - -- - -- Store a variable, applying any final operator as needed. - -- If N is zero, PopFactor (ie store in a new temporary variable of - -- the specified type). Otherwise N should be an index to symtab. - -- If storeConst is 1, NTyp is ignored/overridden, otherwise it - -- should usually be the declared or local type of N. - -- - ... - end procedure - Bool ) { + die unless @sol.all eq .any; + my BagHash $b .= new; + for @sol.keys -> $p1 { + given @sol[$p1] { + when 'L' { my $p2 = $p1+1; die unless @sol[$p2] eq 'R'; $b{ domino( @tab[$p1,$p2].join ) }++; } + when 'D' { my $p2 = $p1+$cols; die unless @sol[$p2] eq 'U'; $b{ domino( @tab[$p1,$p2].join ) }++; } + } + } + die unless $b.values.max == 1 and $b.elems == $rows * $cols / 2; + return True; +} +for @tests -> ( $rows, $cols, $flat_table ) { + my @solutions = solve($rows, $cols, $flat_table.comb); + say 'Solutions found: ', +@solutions; + + # Confirm that every solution is valid. + solution_works($rows, $cols, $flat_table.comb, $_) or die for @solutions; + + # Print first solution + say .join.trans( [] => [<╼ ╾ ╽ ╿>]) for @solutions[0].batch($cols); + + if ++$ == 1 { + say 'Bonus:'; + say .value.fmt("%45d "), .key.tclc for bonus($rows, $cols); + say ''; + } +} diff --git a/Task/Dominoes/Uiua/dominoes.uiua b/Task/Dominoes/Uiua/dominoes.uiua new file mode 100644 index 0000000000..fc73e2f14a --- /dev/null +++ b/Task/Dominoes/Uiua/dominoes.uiua @@ -0,0 +1,29 @@ +GridOne ← ↯7_∞"05132231055052464303662006235126113002452143346664515414" +GridTwo ← ↯7_∞"64220650162341432102355113505610426040114420536366525334" # 2025 solutions + +Offsets ← [1_0 0_1] +FirstFreeCell ← ⊢⬚1▽⤚(¬°⊚⨂)⊙◌↯∞_2°⊡⊃(⋅∘|∘) +# Get pair of cells for down- and right- facing dominos. +CandDoms ← ≡⌞⊂⟜(≡˜⊟⊸+Offsets˙⊟ FirstFreeCell) +# Is the tail-cell of each domino in bounds and not visited? +ValidDoms ← ↧⊃(¬˜∊°⊂⇌|≠@_⬚@_⊡⊣) +# Has this domino already been 'played'? +NotDupeDom ← ⨬(¬˜∊°⊂≡⍆↯∞_2⇌⊡|⋅1) ⊸(=2⧻) +# Find two possible next doms, check them, and step. +Nexts ← ▽⤚≡NotDupeDom▽◡≡ValidDoms⊙¤ ⊸CandDoms +Done ← =∩⧻⊙♭ + +# Add spaces to a solution grid, for MarkDominos to fill. +SpacedGrid ← ↘1↯[∞ ∘]÷2⧻⊸⊢≡⊂˜↯@\s⊸△≡/(⊂$"_ ") +MarkDominos ← ∧(⍜⊡⋅@+)≡(/+↯∞_2) ↯∞_4 + +Solve ← ( + ⟜SpacedGrid + °□⊣⊢path(≡□Nexts°□|Done°□)□[] # Show first solution. + MarkDominos +) +&p"Only solution for first grid:" +&s Solve GridOne +Count ← ⧻path(≡□Nexts°□|Done°□)□[] # Count all solutions. +&p"Count of solutions for second grid:" +Count GridTwo diff --git a/Task/Doomsday-rule/00-TASK.txt b/Task/Doomsday-rule/00-TASK.txt index cfd6e09909..75b51e7e72 100644 --- a/Task/Doomsday-rule/00-TASK.txt +++ b/Task/Doomsday-rule/00-TASK.txt @@ -6,7 +6,7 @@ The algorithm was based on calculating the distance of a given date from certain "anchor days" which follow a pattern for the day of the week upon which they fall. ; Algorithm -The formula is calculated assuming that Sunday is 0, Monday 1, and so forth with Saturday 7, and +The formula is calculated assuming that Sunday is 0, Monday 1, and so forth up to Saturday 6, and doomsday = (Tuesday(or 2) + 5(y mod 4) + 4(y mod 100) + 6(y mod 400)) % 7 diff --git a/Task/Doomsday-rule/C/doomsday-rule.c b/Task/Doomsday-rule/C/doomsday-rule.c index 01166bb55b..66b4f73d16 100644 --- a/Task/Doomsday-rule/C/doomsday-rule.c +++ b/Task/Doomsday-rule/C/doomsday-rule.c @@ -13,7 +13,7 @@ bool leap(uint16_t year) { } const char *weekday(Date date) { - static const uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5}; + static const uint8_t leapdoom[] = {4,1,7,4,2,6,4,1,5,3,7,5}; static const uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5}; static const char *days[] = { "Sunday", "Monday", "Tuesday", "Wednesday", diff --git a/Task/Doomsday-rule/Draco/doomsday-rule.draco b/Task/Doomsday-rule/Draco/doomsday-rule.draco new file mode 100644 index 0000000000..73e8211a33 --- /dev/null +++ b/Task/Doomsday-rule/Draco/doomsday-rule.draco @@ -0,0 +1,50 @@ +type Date = struct { + word year; + byte month; + byte day; +}; + +proc leap_year(word y) bool: + y%4 = 0 and (y%100 /= 0 or y % 400 = 0) +corp + +proc weekday(Date date) *char: + [12]byte leapdoom = (4,1,7,4,2,6,4,1,5,3,7,5); + [12]byte normdoom = (3,7,7,4,2,6,4,1,5,3,7,5); + word c, r, s, t, c_anchor, doom, anchor; + + c := date.year / 100; + r := date.year % 100; + s := r / 12; + t := r % 12; + + c_anchor := (5 * (c % 4) + 2) % 7; + doom := (s + t + (t/4) + c_anchor) % 7; + anchor := if leap_year(date.year) + then leapdoom[date.month-1] + else normdoom[date.month-1] + fi; + + case (doom+date.day-anchor+7)%7 + incase 0: "Sunday" + incase 1: "Monday" + incase 2: "Tuesday" + incase 3: "Wednesday" + incase 4: "Thursday" + incase 5: "Friday" + incase 6: "Saturday" + esac +corp + +proc main() void: + [7]Date dates = ( + (1800,1,6), (1875,3,29), (1915,12,7), (1970,12,23), (2043,5,14), + (2077,2,12), (2101,4,2) + ); + + word d; + for d from 0 upto 6 do + writeln(dates[d].month:2, '/', dates[d].day:2, '/', dates[d].year:4, + ": ", weekday(dates[d])) + od +corp diff --git a/Task/Doomsday-rule/JavaScript/doomsday-rule.js b/Task/Doomsday-rule/JavaScript/doomsday-rule.js new file mode 100644 index 0000000000..bd59065f59 --- /dev/null +++ b/Task/Doomsday-rule/JavaScript/doomsday-rule.js @@ -0,0 +1,52 @@ +// doom.js +const LEAP_DOOM = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]; +const NORM_DOOM = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]; +const WEEKDAYS = [ + 'Sunday', 'Monday', 'Tuesday', 'Wednesday', + 'Thursday', 'Friday', 'Saturday' +]; + +class Date { + constructor(year, month, day) { + this.year = year; + this.month = month; // 1-based + this.day = day; + } + + isLeapYear() { + const y = this.year; + return y % 4 === 0 && (y % 100 !== 0 || y % 400 === 0); + } + + format() { + const { month, day, year } = this; + return `${String(month).padStart(2, '0')}/${String(day).padStart(2, '0')}/${year}`; + } + + weekday() { + const { year, month, day } = this; + const c = Math.floor(year / 100); + const r = year % 100; + const s = Math.floor(r / 12); + const t = r % 12; + + const cAnchor = (5 * (c % 4) + 2) % 7; + const doom = (s + t + Math.floor(t / 4) + cAnchor) % 7; + const anchor = (this.isLeapYear() ? LEAP_DOOM : NORM_DOOM)[month - 1]; + + return WEEKDAYS[(doom + day - anchor + 7) % 7]; + } +} + +/* ---------- demo ---------- */ +const 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) +]; + +dates.forEach(d => console.log(`${d.format()}: ${d.weekday()}`)); diff --git a/Task/Doomsday-rule/Julia/doomsday-rule.julia b/Task/Doomsday-rule/Julia/doomsday-rule.jl similarity index 100% rename from Task/Doomsday-rule/Julia/doomsday-rule.julia rename to Task/Doomsday-rule/Julia/doomsday-rule.jl diff --git a/Task/Doomsday-rule/M2000-Interpreter/doomsday-rule.m2000 b/Task/Doomsday-rule/M2000-Interpreter/doomsday-rule.m2000 new file mode 100644 index 0000000000..bc2bab76ac --- /dev/null +++ b/Task/Doomsday-rule/M2000-Interpreter/doomsday-rule.m2000 @@ -0,0 +1,60 @@ +' MAKE USING("FORMAT STRING", PAR1, PAR2, ...PARN) +' WE USE READ V TO READ MORE PARAMETERS. +FUNCTION USING(A$) { + VARIANT V : LONG D, S, E, I=1: S$="" + WHILE I<=LEN(A$) + IF S THEN + IF MID$(A$,I,1)<>"#" THEN + IF MID$(A$,I,1)="." THEN D=I ELSE E=I + END IF + ELSE + IF MID$(A$,I,1)="#" THEN S=I + END IF + IF S AND E THEN + IF S>1 THEN S$+=LEFT$(A$, S-1) + A$=MID$(A$, E) + G() + S=0:E=0:D=0 + I=1 + END IF + I++ + END WHILE + IF S THEN + IF S>1 THEN S$+=LEFT$(A$, S-1):E=I-S+1: S=1 ELSE E=I + G() + =S$ + ELSE + =S$+A$ + END IF + SUB G() + IF ISNUM THEN + READ V + IF D>0 THEN + S$+=STR$(V, STRING$("#",E-D-1)+"0."+STRING$("0",D-S+1)) + ELSE + S$+=STR$(V, STRING$("0",E-S-1)+"0") + END IF + ELSE + V="" + READ V + S$+=LEFT$(V+STRING$(" ", E-S), E-S) + END IF + END SUB +} +05 FLUSH : GOSUB 110 +10 DIM D$(1 TO 7): FOR I=1 TO 7: READ D$(I): NEXT I +20 DIM D(1 TO 12, 0 TO 1): FOR I=0 TO 1: FOR J=1 TO 12: READ D(J, I): NEXT J : NEXT I +30 READ Y: IF Y=0 THEN BREAK ELSE READ M,D +40 PRINT USING("##/##/#### ", M, D, Y); +50 C=Y DIV 100: R=Y MOD 100 +60 S=R DIV 12: T=R MOD 12 +70 A=(5*BINARY.AND(C, 3)+2) MOD 7 +80 B=(S+T+(T DIV 4)+A) MOD 7 +90 PRINT D$((B+D-D(M,-(Y MOD 4=0 AND (Y MOD 100<>0 OR Y MOD 400=0)))+7) MOD 7+1) +100 GOTO 30 +110 DATA "Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday" +120 DATA 3,7,7,4,2,6,4,1,5,3,7,5 +130 DATA 4,1,7,4,2,6,4,1,5,3,7,5 +140 DATA 1800,1,6,1875,3,29,1915,12,7,1970,12,23 +150 DATA 2043,5,14,2077,2,12,2101,4,2,0 +160 RETURN diff --git a/Task/Doomsday-rule/Mathematica/doomsday-rule.math b/Task/Doomsday-rule/Mathematica/doomsday-rule.math new file mode 100644 index 0000000000..45a6d46d9e --- /dev/null +++ b/Task/Doomsday-rule/Mathematica/doomsday-rule.math @@ -0,0 +1,13 @@ +doomsday[year_Integer?Positive] := Mod[2 + 5 Mod[year, 4] + 4 Mod[year, 100] + 6 Mod[year, 400], 7]; + +firstDoomsday[month_Integer /; 1 <= month <= 2, year_Integer?Positive /; LeapYearQ[{year}]] := {4, 1}[[month]]; +firstDoomsday[month_Integer /; 1 <= month <= 2, year_Integer?Positive] := {3, 7}[[month]]; +firstDoomsday[month_Integer /; 3 <= month <= 12, year_Integer?Positive] := {7, 4, 2, 6, 4, 1, 5, 3, 7, 5}[[month - 2]]; + +weekday[{year_Integer?Positive, month_Integer?Positive /; 1 <= month <= 12, day_Integer?Positive /; 1 <= day <= 31}] := Mod[doomsday[year] + 7 + day - firstDoomsday[month, year], 7]; + +weekdayName[weekday_Integer /; 0 <= weekday <= 6] := {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}[[weekday + 1]]; + +dates = {{1800, 1, 6}, {1875, 3, 29}, {1915, 12, 7}, {1970, 12, 23}, {2043, 5, 14}, {2077, 2, 12}, {2101, 4, 2}}; + +weekdayName /@ weekday /@ dates diff --git a/Task/Doomsday-rule/Maxima/doomsday-rule.maxima b/Task/Doomsday-rule/Maxima/doomsday-rule.maxima new file mode 100644 index 0000000000..1fd7bccc28 --- /dev/null +++ b/Task/Doomsday-rule/Maxima/doomsday-rule.maxima @@ -0,0 +1,15 @@ +daynames: ["Sunday", "Monday", "Tuesday", + "Wednesday", "Thursday", "Friday", "Saturday"]$ + +isleapyear(y) := mod(y, 4)=0 and (mod(y, 100)#0 or mod(y, 400)=0)$ +anchors(y) := [if isleapyear(y) then 4 else 3, + if isleapyear(y) then 1 else 7, + 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]$ + +doomsday(y) := mod(2+5*mod(y, 4)+4*mod(y, 100)+6*mod(y, 400), 7)$ +wd(y, m, d) := mod(doomsday(y)+d-anchors(y)[m], 7)$ + +test_dates: [[1800, 1, 6], [1875, 3, 29], [1915, 12, 7], [1970, 12, 23], [2043, 5, 14], [2077, 2, 12], [2101, 4, 2]]$ + +raw_wds: map(lambda([l], apply(wd, l)), test_dates)$ +for i in raw_wds do(sprint(daynames[i+1]))$ diff --git a/Task/Doomsday-rule/Miranda/doomsday-rule.miranda b/Task/Doomsday-rule/Miranda/doomsday-rule.miranda new file mode 100644 index 0000000000..de3b570449 --- /dev/null +++ b/Task/Doomsday-rule/Miranda/doomsday-rule.miranda @@ -0,0 +1,29 @@ +main :: [sys_message] +main = [Stdout (lay [showdate d ++ ": " ++ weekday d | d<-tests])] + +date ::= Date (num,num,num) + +showdate :: date->[char] +showdate (Date (y,m,d)) = show m ++ "/" ++ show d ++ "/" ++ show y + +tests :: [date] +tests = map Date [ + (1800,1,6), (1875,3,29), (1915,12,7), (1970,12,23), (2043,5,14), + (2077,2,12), (2101,4,2)] + +weekday :: date->[char] +weekday (Date (year,month,day)) + = weekdays ! daynum + where weekdays = ["Sunday","Monday","Tuesday","Wednesday","Thursday", + "Friday","Saturday"] + doomtab = leapdoom, if leapyear + = normdoom, otherwise + leapdoom = [4,1,7,2,4,6,4,1,5,3,7,5] + normdoom = [3,7,7,4,2,6,4,1,5,3,7,5] + leapyear = year mod 4=0 & (year mod 100~=0 \/ year mod 400=0) + (c, r) = (year div 100, year mod 100) + (s, t) = (r div 12, r mod 12) + c_anchor = (5 * (c mod 4) + 2) mod 7 + doom = (s + t + t div 4 + c_anchor) mod 7 + anchor = doomtab ! (month - 1) + daynum = (doom + day - anchor + 7) mod 7 diff --git a/Task/Doomsday-rule/PascalABC.NET/doomsday-rule.pas b/Task/Doomsday-rule/PascalABC.NET/doomsday-rule.pas new file mode 100644 index 0000000000..2f45724a97 --- /dev/null +++ b/Task/Doomsday-rule/PascalABC.NET/doomsday-rule.pas @@ -0,0 +1,26 @@ +const + days: array of string = ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'); + dooms: array of array of integer = ((3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5), + (4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5)); + +function isleap(year: integer) := (year mod 4 = 0) and ((year mod 100 <> 0) or (year mod 400 = 0)); + +function weekday(year, month, day: integer): string; +begin + var c := year div 100; + var r := year mod 100; + var s := r div 12; + var t := r mod 12; + var c_anchor := (5 * (c mod 4) + 2) mod 7; + var doomsday := (s + t + (t div 4) + c_anchor) mod 7; + var anchorday := dooms[if isleap(year) then 1 else 0][month - 1]; + var weekday := (doomsday + day - anchorday + 7) mod 7; + result := days[weekday]; +end; + +begin + var dates := |(1800, 1, 6), (1875, 3, 29), (1915, 12, 7), (1970, 12, 23), + (2043, 5, 14), (2077, 2, 12), (2101, 4, 2)|; + foreach var d in dates do + writeln(d[0], '-', d[1]:2, '-', d[2]:2, ' -> ', weekday(d[0], d[1], d[2])); +end. diff --git a/Task/Doomsday-rule/Pluto/doomsday-rule.pluto b/Task/Doomsday-rule/Pluto/doomsday-rule.pluto new file mode 100644 index 0000000000..8ce12b27df --- /dev/null +++ b/Task/Doomsday-rule/Pluto/doomsday-rule.pluto @@ -0,0 +1,42 @@ +local fmt = require "fmt" + +local anchor_day = |y| -> (2 + 5 * (y % 4) + 4 *(y % 100) + 6 * (y % 400)) % 7 + +local is_leap_year = |y| -> y % 4 == 0 and (y % 100 != 0 or y % 400 == 0) + +local first_days_common = {3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5} +local first_days_leap = {4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5} + +local dates = { + "1800-01-06", + "1875-03-29", + "1915-12-07", + "1970-12-23", + "2043-05-14", + "2077-02-12", + "2101-04-02" +} + +local function parse(date) + local y = tonumber(date:sub(1, 4)) + local m = tonumber(date:sub(6, 7)) + local d = tonumber(date:sub(9, 10)) + return y, m, d +end + +print("Days of week given by Doomsday rule:") +for dates as date do + local y, m, d = parse(date) + local a = anchor_day(y) + local w = d - (is_leap_year(y) ? first_days_leap[m] : first_days_common[m]) + if w < 0 then w += 7 end + local dow = (a + w) % 7 + print($"{date} -> {fmt.weekday(dow)}") +end + +print("\nDays of week given by standard library functions:") +for dates as date do + local y, m, d = parse(date) + local t = os.time({year = y, month = m, day = d}) + print($"{date} -> {os.date("%A", t)}") +end diff --git a/Task/Doomsday-rule/Quackery/doomsday-rule.quackery b/Task/Doomsday-rule/Quackery/doomsday-rule.quackery new file mode 100644 index 0000000000..5dfa5b0e1d --- /dev/null +++ b/Task/Doomsday-rule/Quackery/doomsday-rule.quackery @@ -0,0 +1,26 @@ + [ dup 400 mod 0 = iff [ drop true ] done + dup 100 mod 0 = iff [ drop false ] done + 4 mod 0 = ] is leap ( y --> b ) + + [ dup 4 mod 5 * + over 100 mod 4 * + + swap 400 mod 6 * + 2 + 7 mod ] is doomsday ( y --> n ) + + [ leap iff [ ' [ table 0 4 1 ] ] + else [ ' [ table 0 3 7 ] ] + ' [ 7 4 2 6 4 1 5 3 7 5 ] join do ] is close ( m y --> n ) + + [ dup doomsday unrot close - + 7 mod ] is weekday ( d m y --> n ) + + [ [ table $ "Sunday" $ "Monday" + $ "Tuesday" $ "Wednesday" $ "Thursday" + $ "Friday" $ "Saturday" ] do echo$ ] is echoday ( d --> ) + + ' [ [ 6 1 1800 ] + [ 29 3 1875 ] + [ 7 12 1915 ] + [ 23 12 1970 ] + [ 14 5 2043 ] + [ 12 2 2077 ] + [ 2 4 2101 ] ] + witheach [ unpack weekday echoday cr ] diff --git a/Task/Doomsday-rule/R/doomsday-rule.r b/Task/Doomsday-rule/R/doomsday-rule.r new file mode 100644 index 0000000000..9106214930 --- /dev/null +++ b/Task/Doomsday-rule/R/doomsday-rule.r @@ -0,0 +1,22 @@ +daynames <- c("Sunday", "Monday", "Tuesday", "Wednesday", + "Thursday", "Friday", "Saturday") + +isleapyear <- function(y) (y%%4==0)&((y%%100!=0)|(y%%400==0)) + +anchors <- function(y) c(ifelse(isleapyear(y), 4, 3), + ifelse(isleapyear(y), 1, 7), + 7, 4, 2, 6, 4, 1, 5, 3, 7, 5) + +doomsday <- function(y) (2+5*(y%%4)+4*(y%%100)+6*(y%%400))%%7 +wd <- function(y, m, d) (doomsday(y)+d-anchors(y)[m])%%7 + +test_dates <- list(c(1800, 1, 6), + c(1875, 3, 29), + c(1915, 12, 7), + c(1970, 12, 23), + c(2043, 5, 14), + c(2077, 2, 12), + c(2101, 4, 2)) + +raw_wds <- sapply(test_dates, function(v) do.call(wd, as.list(v))) +cat(daynames[raw_wds+1], "\n") diff --git a/Task/Doomsday-rule/Refal/doomsday-rule.refal b/Task/Doomsday-rule/Refal/doomsday-rule.refal new file mode 100644 index 0000000000..611e530466 --- /dev/null +++ b/Task/Doomsday-rule/Refal/doomsday-rule.refal @@ -0,0 +1,43 @@ +$ENTRY Go { + , (1800 1 6) (1875 3 29) (1915 12 7) (1970 12 23) + (2043 5 14) (2077 2 12) (2101 4 2): e.Tests + = ; +}; + +Test { + e.Test = >; +}; + +LeapYear { + s.Year = > + > + >>>; +}; + +Weekday { + s.Year s.Month s.Day, + 4 1 7 4 2 6 4 1 5 3 7 5: e.LeapDoom, + 3 7 7 4 2 6 4 1 5 3 7 5: e.NormDoom, + Sunday Monday Tuesday Wednesday Thursday Friday Saturday: e.Days, + : (s.C) s.R, + : (s.S) s.T, + >> 7>: s.CAn, + >>> 7>: s.Doom, + (e.LeapDoom) (e.NormDoom)>: (e.DoomTab), + e.DoomTab>: e.Anchor, + e.Anchor>> 7>: s.Weekday + = ; +}; + +Item { + 0 s.X e.XS = s.X; + s.N s.X e.XS = e.XS>; +}; + +If { True t.T t.F = t.T; False t.T t.F = t.F; }; +Eq { t.X t.X = True; t.X t.Y = False; }; +Or { True s.Y = True; False s.Y = s.Y; }; +And { False s.Y = False; True s.Y = s.Y; }; +Not { True = False; False = True; }; +Neq { t.X t.Y = >; }; +Each { (e.F) = ; (e.F) (e.X) e.XS = ; }; diff --git a/Task/Doomsday-rule/Rust/doomsday-rule.rust b/Task/Doomsday-rule/Rust/doomsday-rule.rs similarity index 100% rename from Task/Doomsday-rule/Rust/doomsday-rule.rust rename to Task/Doomsday-rule/Rust/doomsday-rule.rs diff --git a/Task/Doomsday-rule/SETL/doomsday-rule.setl b/Task/Doomsday-rule/SETL/doomsday-rule.setl new file mode 100644 index 0000000000..cf225f497f --- /dev/null +++ b/Task/Doomsday-rule/SETL/doomsday-rule.setl @@ -0,0 +1,29 @@ +program doomsday; + tests := [[1800,1,6], [1875,3,29], [1915,12,7], [1970,12,23], + [2043,5,14], [2077,2,12], [2101,4,2]]; + + loop for [year, month, day] in tests do + print(str day + "/" + str month + "/" + str year + ": " + + weekday(year, month, day)); + end loop; + + proc leap(y); + return y mod 4 = 0 and (y mod 100 /= 0 or y mod 400 = 0); + end proc; + + proc weekday(year, month, day); + leapdoom := [4,1,7,4,2,6,4,1,5,3,7,5]; + normdoom := [3,7,7,4,2,6,4,1,5,3,7,5]; + weekdays := ["Sunday","Monday","Tuesday","Wednesday","Thursday", + "Friday","Saturday"]; + + c := year div 100; + r := year mod 100; + s := r div 12; + t := r mod 12; + c_anchor := (5 * (c mod 4) + 2) mod 7; + doom := (s + t + (t div 4) + c_anchor) mod 7; + anchor := if leap(year) then leapdoom else normdoom end(month); + return weekdays((doom+day-anchor+7) mod 7+1); + end proc; +end program; diff --git a/Task/Doomsday-rule/UNIX-Shell/doomsday-rule.sh b/Task/Doomsday-rule/UNIX-Shell/doomsday-rule.sh index 10334c8be4..891530b914 100644 --- a/Task/Doomsday-rule/UNIX-Shell/doomsday-rule.sh +++ b/Task/Doomsday-rule/UNIX-Shell/doomsday-rule.sh @@ -5,14 +5,14 @@ day-of-the-week() then local -ra names=({Sun,Mon,Tues,Wednes,Thurs,Fri,Satur}day) doomsday=({37,41}7426415375) local -i i c s t a b - local -i {year,month,day}=${BASH_REMATCH[++i]} + local -i {y,m,d}=${BASH_REMATCH[++i]} echo ${names[ - c=year/100, - s=(year%100)/12, - t=(year % 100) % 12, + c=y/100, + s=(y%100)/12, + t=(y % 100) % 12, a=(5*(c%4)+2) % 7, b=(s + t + (t / 4) + a ) % 7, - (b + day - ${doomsday[(year%4 == 0) && ((year%100) || (year%400 == 0))]:month-1:1} + 7) % 7 + (b + d - ${doomsday[(y%4 == 0) && ((y%100) || (y%400 == 0))]:m-1:1} + 7) % 7 ]} else return 1 fi diff --git a/Task/Doomsday-rule/Uiua/doomsday-rule.uiua b/Task/Doomsday-rule/Uiua/doomsday-rule.uiua new file mode 100644 index 0000000000..e8c760542c --- /dev/null +++ b/Task/Doomsday-rule/Uiua/doomsday-rule.uiua @@ -0,0 +1,7 @@ +Ds ← [3 7 7 4 2 6 4 1 5 3 7 5] +Ly ← ↧↥⊃(=0◿400|≠0◿100|=0◿4) +D ← ◿7+⊃(Ly|+2++⊃(×5◿4|×4◿100|×6◿400)) +Wd ← ["Sun" "Mon" "Tue" "Wed" "Thu" "Fri" "Sat" "Sun"] +DoW ← ⊡:Wd◿7+D⊙(-⊡-1:Ds)°[⊙⊙∘] +[[1800 1 6][1875 3 29][1915 12 7][1970 12 23][2043 5 14][2077 2 12][2101 4 2]] +≡(&p$"_\t_"/$"_-_"°⋕⇌⟜DoW) diff --git a/Task/Doomsday-rule/V-(Vlang)/doomsday-rule.v b/Task/Doomsday-rule/V-(Vlang)/doomsday-rule.v index bc6194f84e..002a8b84fc 100644 --- a/Task/Doomsday-rule/V-(Vlang)/doomsday-rule.v +++ b/Task/Doomsday-rule/V-(Vlang)/doomsday-rule.v @@ -1,5 +1,4 @@ -const -( +const ( days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] first_days_common = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] first_days_leap = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] @@ -24,15 +23,11 @@ fn main() { d = date[8..10].int() a = anchor_day(y) f = first_days_common[m] - if is_leap_year(y) { - f = first_days_leap[m] - } + if is_leap_year(y) {f = first_days_leap[m]} w = d - f - if w < 0 { - w = 7 + w - } + if w < 0 {w = 7 + w} dow = (a + w) % 7 - println('$date -> ${days[dow]}') + println("$date -> ${days[dow]}") } } diff --git a/Task/Dot-product/00-TASK.txt b/Task/Dot-product/00-TASK.txt index e3ca21eba5..40361afe8d 100644 --- a/Task/Dot-product/00-TASK.txt +++ b/Task/Dot-product/00-TASK.txt @@ -15,7 +15,7 @@ If implementing the dot product of two vectors directly: :::*   sum the products   (to produce the answer) -;Related task: -*   [[Vector products]] +;Related tasks: +* [[Arrays]], [[Vector]], [[Dot product]], [[Vector products]], [[Matrices]], [[Bivector]], [[Antivector]], [[Tensor]], [[Quaternion]], [[Rotor]], [[Motor]], [[Sedenion]], [[Octonion]]

    diff --git a/Task/Dot-product/ANSI-BASIC/dot-product.basic b/Task/Dot-product/ANSI-BASIC/dot-product.basic new file mode 100644 index 0000000000..1f3bf387b2 --- /dev/null +++ b/Task/Dot-product/ANSI-BASIC/dot-product.basic @@ -0,0 +1,45 @@ +100 REM Dot product +110 DECLARE EXTERNAL FUNCTION DotProduct +120 OPTION BASE 0 +130 DIM Zero3D(2), X(2), Y(2), Z(2), Q(2), R(2) ! some example vectors +140 LET Zero3D(0) = 0 +150 LET Zero3D(1) = 0 +160 LET Zero3D(2) = 0 +170 ! +180 LET X(0) = 1 +190 LET X(1) = 0 +200 LET X(2) = 0 +210 ! +220 LET Y(0) = 0 +230 LET Y(1) = 1 +240 LET Y(2) = 0 +250 ! +260 LET Z(0) = 0 +270 LET Z(1) = 0 +280 LET Z(2) = 1 +290 ! +300 LET Q(0) = 1 +310 LET Q(1) = 1 +320 LET Q(2) = 3.14159 +330 ! +340 LET R(0) = -1 +350 LET R(1) = 2.618033989 +360 LET R(2) = 3 +370 ! +380 PRINT " Q dot R ="; DotProduct(Q, R) +390 PRINT " Zero3D dot X ="; DotProduct(Zero3D, X) +400 PRINT " Z dot Z ="; DotProduct(Z, Z) +410 PRINT " Y dot Z ="; DotProduct(Y, Z) +420 END +430 ! +440 EXTERNAL FUNCTION DotProduct(A(), B()) +450 IF UBOUND(A) <> UBOUND(B) THEN +460 PRINT "Sizes of arrays should be equal." +470 STOP +480 END IF +490 LET DP = 0 +500 FOR I = 0 TO UBOUND(A) +510 LET DP = DP + (A(I) * B(I)) +520 NEXT I +530 LET DotProduct = DP +540 END FUNCTION diff --git a/Task/Dot-product/Ada/dot-product.ada b/Task/Dot-product/Ada/dot-product.adb similarity index 100% rename from Task/Dot-product/Ada/dot-product.ada rename to Task/Dot-product/Ada/dot-product.adb diff --git a/Task/Dot-product/Apple/dot-product.apple b/Task/Dot-product/Apple/dot-product.apple new file mode 100644 index 0000000000..8f7bb17fb2 --- /dev/null +++ b/Task/Dot-product/Apple/dot-product.apple @@ -0,0 +1 @@ +[(+)/(*)`(x::Vec n float) y] ⟨1,3,_5⟩ ⟨4,_2,_1::float⟩ diff --git a/Task/Dot-product/ArkScript/dot-product.ark b/Task/Dot-product/ArkScript/dot-product.ark new file mode 100644 index 0000000000..f59407ce57 --- /dev/null +++ b/Task/Dot-product/ArkScript/dot-product.ark @@ -0,0 +1,12 @@ +(let dotProduct (fun (v1 v2) { + (assert (= (len v1) (len v2)) "vectors should have the same length") + + (mut result 0) + (mut i 0) + (while (< i (len v1)) { + (set result (+ result (* (@ v1 i) (@ v2 i)))) + (set i (+ 1 i)) }) + + result })) + +(print (dotProduct [1 3 -5] [4 -2 -1])) diff --git a/Task/Dot-product/Ballerina/dot-product.ballerina b/Task/Dot-product/Ballerina/dot-product.ballerina new file mode 100644 index 0000000000..230674a31a --- /dev/null +++ b/Task/Dot-product/Ballerina/dot-product.ballerina @@ -0,0 +1,13 @@ +import ballerina/io; + +function dot(float[] a, float[] b) returns float { + float sum = 0.0; + foreach any[] [idx, val] in a.enumerate() { + sum += val * b[idx]; + } + return sum; +} + +public function main() { + io:println(dot([1, 3, -5], [4, -2, -1])); +} diff --git a/Task/Dot-product/C++/dot-product-1.cpp b/Task/Dot-product/C++/dot-product-1.cpp deleted file mode 100644 index cb26a2e3a5..0000000000 --- a/Task/Dot-product/C++/dot-product-1.cpp +++ /dev/null @@ -1,12 +0,0 @@ -#include -#include - -int main() -{ - int a[] = { 1, 3, -5 }; - int b[] = { 4, -2, -1 }; - - std::cout << std::inner_product(a, a + sizeof(a) / sizeof(a[0]), b, 0) << std::endl; - - return 0; -} diff --git a/Task/Dot-product/C++/dot-product-2.cpp b/Task/Dot-product/C++/dot-product-2.cpp deleted file mode 100644 index 476a7f64a5..0000000000 --- a/Task/Dot-product/C++/dot-product-2.cpp +++ /dev/null @@ -1,14 +0,0 @@ -#include -#include - -int main() -{ - std::valarray xs = {1,3,-5}; - std::valarray ys = {4,-2,-1}; - - double result = (xs * ys).sum(); - - std::cout << result << '\n'; - - return 0; -} diff --git a/Task/Dot-product/C++/dot-product-3.cpp b/Task/Dot-product/C++/dot-product-3.cpp deleted file mode 100644 index 69af05bce8..0000000000 --- a/Task/Dot-product/C++/dot-product-3.cpp +++ /dev/null @@ -1,11 +0,0 @@ -#include -#include -#include - -int main() { - std::vector v1 { 1, 3, -5, }; - std::vector v2 { 4, -2, -1, }; - auto dp = std::inner_product(v1.cbegin(), v1.cend(), v2.cbegin(), 0); - std::cout << "dot.product of {1,3,-5} and {4,-2,-1}: " << dp << std::endl; - return 0; -} diff --git a/Task/Dot-product/C++/dot-product.cpp b/Task/Dot-product/C++/dot-product.cpp new file mode 100644 index 0000000000..18d21a5a35 --- /dev/null +++ b/Task/Dot-product/C++/dot-product.cpp @@ -0,0 +1,47 @@ +#include +#include +#include +#include +#include + +#if defined(__clang__) +#pragma clang diagnostic ignored "-Wgnu-alignof-expression" +#endif + +#ifdef _MSC_VER +#define INLINE __force_inline __flatten __declspec(nothrow) __declspec(noalias) inline +#else +#define INLINE __attribute__((always_inline)) __attribute__((flatten)) __attribute__((nothrow)) __attribute__((const)) inline +#endif + +template(N)> +struct alignas((N == N_POW2 ? N_POW2 : 1) * alignof(T)) vec : std::array +{ +}; + +/* n-dimensional dot/scalar product */ +template +INLINE T dot(const vec& a, const vec& b, T dst = (T)0) +{ + #pragma omp simd reduction(+:dst) + for(size_t i = 0; i < N; i++) dst += a[i] * b[i]; + return dst; +} + +int main() +{ + vec a = { 1, 3, -5 }; + vec b = { 4, -2, -1 }; + vec c = { 1, 2, 3, 4 }; + vec,3> d = { a, b, a }; + vec,4> e = { c, c, c, c }; + + printf("dot.product of {1,3,-5} and {4,-2,-1}: %d", dot(a,b)); puts(""); + printf("type align/size"); puts(""); + printf("vec %4zu/%-4zu",alignof(a), sizeof(a)); puts(""); + printf("vec %4zu/%-4zu",alignof(c), sizeof(c)); puts(""); + printf("vec,3> %4zu/%-4zu",alignof(d), sizeof(d)); puts(""); + printf("vec,4> %4zu/%-4zu",alignof(e), sizeof(e)); puts(""); + + exit(EXIT_SUCCESS); +} diff --git a/Task/Dot-product/C/dot-product-1.c b/Task/Dot-product/C/dot-product-1.c new file mode 100644 index 0000000000..e56b20f598 --- /dev/null +++ b/Task/Dot-product/C/dot-product-1.c @@ -0,0 +1,37 @@ +#include "array.h" + +#define dot(a,b,t,n,i) \ +({ \ + static_assert((isarray(a) || isvector(a)), \ + "ERROR: dot - a is not of array or vector type!"); \ + static_assert((isarray(b) || isvector(b)), \ + "ERROR: dot - b is not of array or vector type!"); \ + t _dst = (t)i; \ + size_t len = (size_t)llabs((ssize_t)n); \ + len = MIN(MIN(!isarray(a) ? vec_countof(a) : countof(a), \ + !isarray(b) ? vec_countof(b) : countof(b)), \ + (ssize_t)n>0?len:0); \ + _Pragma("omp simd reduction(+:_dst)") \ + for(size_t j = 0; j < len; j++) \ + _dst += (t)((a)[j]) * (t)((b)[j]); \ + _dst; \ +}) + +typedef double real; + +#define dot3(a,b) dot(a,b,real,3,0) +#define dot4(a,b) dot(a,b,real,4,0) + +#define out_eol puts("") +#define fout_num(stream,prefix,number,suffix) fprintf(stream, "%s%+e%s", prefix, (double)number, suffix) +#define out_num(number) fout_num(stdout,"",number,"") + +int main(int argc, char** argv) +{ + vec(real,3) a = { 1, 3, -5}; + arr(real,3) b = { 4, -2, -1}; + + out_num(dot3(a, b)); out_eol; + + exit(EXIT_SUCCESS); +} diff --git a/Task/Dot-product/C/dot-product-2.c b/Task/Dot-product/C/dot-product-2.c new file mode 100644 index 0000000000..a0b238ba51 --- /dev/null +++ b/Task/Dot-product/C/dot-product-2.c @@ -0,0 +1,78 @@ +/************************************************************************************************* + * C preprocessor macro vector/array types * + * * + * vec(T,N) - padded to bitceil(N) with operators/accessors * + * * + * arr(T,N) - alignas((N == bitceil(N) ? N : 1) * alignof(T)) * + * * + * vla(T) - flexible/variable length default alignment * + * * + * CFLAGS=" * + * -march=native * + * -O3 * + * -std=23 * + * -mfpmath= * + * -ftree-vectorize * + * -fopenmp * + * -fopenmp-simd" * + * * + * For MSVC see: https://learn.microsoft.com/en-us/cpp/parallel/openmp/openmp-simd?view=msvc-180 * + *************************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include +#include +#include + +#if defined(__clang__) +#pragma clang diagnostic ignored "-Wgnu-alignof-expression" +#endif + +#ifdef _MSC_VER +#define INLINE __force_inline __flatten __declspec(nothrow) __declspec(noalias) inline +#else +#define INLINE __attribute__((always_inline,flatten,nothrow,const)) inline +#endif + +#define BITOP_RUP01__(x) ( (x) | ( (x) >> 1)) +#define BITOP_RUP02__(x) (BITOP_RUP01__(x) | (BITOP_RUP01__(x) >> 2)) +#define BITOP_RUP04__(x) (BITOP_RUP02__(x) | (BITOP_RUP02__(x) >> 4)) +#define BITOP_RUP08__(x) (BITOP_RUP04__(x) | (BITOP_RUP04__(x) >> 8)) +#define BITOP_RUP16__(x) (BITOP_RUP08__(x) | (BITOP_RUP08__(x) >> 16)) + +#define bitceil(x) (const uint32_t)(BITOP_RUP16__(((uint32_t)(x)) - 1) + 1) + +/* arr(T,N) aligned array type */ +#define arr(t,n) alignas((n == bitceil(n) ? n : 1) * alignof(t)) typeof(t[n]) +#define countof(a) sizeof((a))/sizeof(typeof((a)[0])) +#define isarray(a) __builtin_choose_expr(__builtin_types_compatible_p(typeof((a)[0]) [], typeof((a))), true, false) + +#define rc_arr(src,n) (*(arr(typeof((src)[0]),n)*)&src) +#define rc_vec(src,n) (*(vec(typeof((src)[0]),n)*)&src) + +/* vec(T,N) for LLVM SIMD Vector Extension */ +#if defined(__clang__) +#define vec(T,N) typeof(T __attribute__((ext_vector_type(N)))) +#define vec_countof(a) __builtin_vectorelements(rc_vec(a,countof(a))) +#define isvector(a) !isarray(a) && \ +__builtin_choose_expr( \ +bitceil(vec_countof(a)) == countof(a),true,false) + +/* vec(T,N) for GCC SIMD Vector Extension */ +#elif defined(__GNUC__) +#define vec(T,N) typeof(T __attribute__((vector_size(bitceil(N) * alignof(T))))) +#define vec_countof(a) countof(a) +#define isvector(a) !isarray(a) && \ +_Generic(__builtin_convertvector(rc_vec(a,vec_countof(a)), \ + vec(float,bitceil(vec_countof(a)))), \ + vec(float,bitceil(vec_countof(a))): true, \ + default: false) +/* vec_ext(T,N) for other compilers */ +#else +#define vec(T,N) arr(T,N) +#warn "Your compiler doens't support vector extensions." +#warn "Using aligned arrays without operators instead." +#endif diff --git a/Task/Dot-product/C/dot-product.c b/Task/Dot-product/C/dot-product.c deleted file mode 100644 index 4825c675e3..0000000000 --- a/Task/Dot-product/C/dot-product.c +++ /dev/null @@ -1,28 +0,0 @@ -#include -#include - -int dot_product(int *, int *, size_t); - -int -main(void) -{ - int a[3] = {1, 3, -5}; - int b[3] = {4, -2, -1}; - - printf("%d\n", dot_product(a, b, sizeof(a) / sizeof(a[0]))); - - return EXIT_SUCCESS; -} - -int -dot_product(int *a, int *b, size_t n) -{ - int sum = 0; - size_t i; - - for (i = 0; i < n; i++) { - sum += a[i] * b[i]; - } - - return sum; -} diff --git a/Task/Dot-product/Crystal/dot-product.crystal b/Task/Dot-product/Crystal/dot-product.cr similarity index 100% rename from Task/Dot-product/Crystal/dot-product.crystal rename to Task/Dot-product/Crystal/dot-product.cr diff --git a/Task/Dot-product/Delphi/dot-product.delphi b/Task/Dot-product/Delphi/dot-product.pas similarity index 100% rename from Task/Dot-product/Delphi/dot-product.delphi rename to Task/Dot-product/Delphi/dot-product.pas diff --git a/Task/Dot-product/DuckDB/dot-product-1.duckdb b/Task/Dot-product/DuckDB/dot-product-1.duckdb new file mode 100644 index 0000000000..d7683fd5f7 --- /dev/null +++ b/Task/Dot-product/DuckDB/dot-product-1.duckdb @@ -0,0 +1 @@ +select list_dot_product( [1, 3, -5], [4, -2, -1]); diff --git a/Task/Dot-product/DuckDB/dot-product-2.duckdb b/Task/Dot-product/DuckDB/dot-product-2.duckdb new file mode 100644 index 0000000000..ac8ab5ae33 --- /dev/null +++ b/Task/Dot-product/DuckDB/dot-product-2.duckdb @@ -0,0 +1,3 @@ +SELECT sum(A.N*B.N) as '.' +FROM A JOIN B +ON A.rowid=B.rowid; diff --git a/Task/Dot-product/DuckDB/dot-product-3.duckdb b/Task/Dot-product/DuckDB/dot-product-3.duckdb new file mode 100644 index 0000000000..ecbeac52c6 --- /dev/null +++ b/Task/Dot-product/DuckDB/dot-product-3.duckdb @@ -0,0 +1,7 @@ +CREATE OR REPLACE TABLE A AS + SELECT rowid, N + FROM (select [1, 3, -5] as l, unnest(l) as N, generate_subscripts(l, 1) AS rowid); + +CREATE OR REPLACE TABLE B AS + SELECT rowid, N + FROM (select [4, -2, -1] as l, unnest(l) as N, generate_subscripts(l, 1) AS rowid); diff --git a/Task/Dot-product/DuckDB/dot-product-4.duckdb b/Task/Dot-product/DuckDB/dot-product-4.duckdb new file mode 100644 index 0000000000..31a7b61cad --- /dev/null +++ b/Task/Dot-product/DuckDB/dot-product-4.duckdb @@ -0,0 +1,13 @@ +# Define innerProduct/2 as a scalar function; +# the names of the columns are however fixed. +create or replace function innerProduct(TableA, TableB) as ( + (select * from + (with + AT as (from query_table(TableA)), + BT as (from query_table(TableB)) + select sum(AT.N * BT.N) + from AT join BT + on AT.rowid=BT.rowid ) +)); + +select innerProduct('A', 'B'); diff --git a/Task/Dot-product/Elena/dot-product.elena b/Task/Dot-product/Elena/dot-product.elena index c705cf4014..33f37c0614 100644 --- a/Task/Dot-product/Elena/dot-product.elena +++ b/Task/Dot-product/Elena/dot-product.elena @@ -7,7 +7,7 @@ extension op = self.zipBy(array, (x,y => x * y)).summarize(); } -public program() +public Program() { - console.printLine(new int[]{1, 3, -5}.dotProduct(new int[]{4, -2, -1})) + Console.printLine(new int[]{1, 3, -5}.dotProduct(new int[]{4, -2, -1})) } diff --git a/Task/Dot-product/Elixir/dot-product.elixir b/Task/Dot-product/Elixir/dot-product.ex similarity index 100% rename from Task/Dot-product/Elixir/dot-product.elixir rename to Task/Dot-product/Elixir/dot-product.ex diff --git a/Task/Dot-product/Emacs-Lisp/dot-product.l b/Task/Dot-product/Emacs-Lisp/dot-product.el similarity index 100% rename from Task/Dot-product/Emacs-Lisp/dot-product.l rename to Task/Dot-product/Emacs-Lisp/dot-product.el diff --git a/Task/Dot-product/Euphoria/dot-product-1.euphoria b/Task/Dot-product/Euphoria/dot-product-1.eu similarity index 100% rename from Task/Dot-product/Euphoria/dot-product-1.euphoria rename to Task/Dot-product/Euphoria/dot-product-1.eu diff --git a/Task/Dot-product/Euphoria/dot-product-2.euphoria b/Task/Dot-product/Euphoria/dot-product-2.eu similarity index 100% rename from Task/Dot-product/Euphoria/dot-product-2.euphoria rename to Task/Dot-product/Euphoria/dot-product-2.eu diff --git a/Task/Dot-product/Fennel/dot-product.fennel b/Task/Dot-product/Fennel/dot-product.fennel new file mode 100644 index 0000000000..adc1d7ecd1 --- /dev/null +++ b/Task/Dot-product/Fennel/dot-product.fennel @@ -0,0 +1,11 @@ +(fn dotProduct [v1 v2] + (assert (= (length v1) (length v2)) "vectors should have the same length") + + (var result 0) + (for [i 1 (length v1)] + (set result (+ result (* (. v1 i) (. v2 i)))) + ) + result +) + +(print (dotProduct [1 3 -5] [4 -2 -1])) diff --git a/Task/Dot-product/Gleam/dot-product.gleam b/Task/Dot-product/Gleam/dot-product.gleam new file mode 100644 index 0000000000..646cd40690 --- /dev/null +++ b/Task/Dot-product/Gleam/dot-product.gleam @@ -0,0 +1,18 @@ +pub fn main() { + let _ = echo dot_product([1, 3, -5], [4, -2, -1]) + let _ = echo dot_product([1, 3, -5], [4, -2]) +} + +pub fn dot_product(u: List(Int), v: List(Int)) -> Result(Int, String) { + dot_product_loop(u, v, 0) +} + +fn dot_product_loop(u: List(Int), v: List(Int), sum: Int) -> Result(Int, String) { + case u, v { + [], [_, ..] -> Error("Inputs must have the same length.") + [_, ..], [] -> Error("Inputs must have the same length.") + [x, ..rest_u], [y, ..rest_v] -> + dot_product_loop(rest_u, rest_v, x * y + sum) + [], [] -> Ok(sum) + } +} diff --git a/Task/Dot-product/Julia/dot-product.julia b/Task/Dot-product/Julia/dot-product.jl similarity index 100% rename from Task/Dot-product/Julia/dot-product.julia rename to Task/Dot-product/Julia/dot-product.jl diff --git a/Task/Dot-product/Kotlin/dot-product.kotlin b/Task/Dot-product/Kotlin/dot-product.kts similarity index 100% rename from Task/Dot-product/Kotlin/dot-product.kotlin rename to Task/Dot-product/Kotlin/dot-product.kts diff --git a/Task/Dot-product/LFE/dot-product.lfe b/Task/Dot-product/LFE/dot-product.lfe index 4936a177ac..6208adb21f 100644 --- a/Task/Dot-product/LFE/dot-product.lfe +++ b/Task/Dot-product/LFE/dot-product.lfe @@ -1,3 +1,2 @@ (defun dot-product (a b) - (: lists foldl #'+/2 0 - (: lists zipwith #'*/2 a b))) + (lists:foldl #'+/2 0 (lists:zipwith #'*/2 a b))) diff --git a/Task/Dot-product/LOLCODE/dot-product.lol b/Task/Dot-product/LOLCODE/dot-product.lol new file mode 100644 index 0000000000..97687f6b7d --- /dev/null +++ b/Task/Dot-product/LOLCODE/dot-product.lol @@ -0,0 +1,23 @@ +HAI 1.3 BTW DOT PRODUKT + + OBTW FIND DOT PRODUKT OF AV AN BV + - AV AN BV MUST BE BUKKITS WITH LENGTH AN SRS 0, SRS 1, ... SRS DIFF OF LENGTH AN 1 + BOTH SAEM AV'Z LENGTH AN BV'Z LENGTH MUST BE WIN + TLDR + HOW IZ I DOTTIN YR AV AN YR BV + I HAS A REZULT ITZ 0 + IM IN YR INNERPRODUKT UPPIN YR I TIL BOTH SAEM I AN BIGGR OF I AN AV'Z LENGTH + REZULT R SUM OF REZULT AN PRODUKT OF AV'Z SRS I AN BV'Z SRS I + IM OUTTA YR INNERPRODUKT + FOUND YR REZULT + IF U SAY SO + + BTW MAEK AV AN BV BE 3 ELEMENT VEKTORS + I HAS A AV ITZ A BUKKIT, AV HAS A LENGTH ITZ 3 + AV HAS A SRS 0 ITZ 1, AV HAS A SRS 1 ITZ 3, AV HAS A SRS 2 ITZ -5 + I HAS A BV ITZ A BUKKIT, BV HAS A LENGTH ITZ 3 + BV HAS A SRS 0 ITZ 4, BV HAS A SRS 1 ITZ -2, BV HAS A SRS 2 ITZ -1 + + VISIBLE I IZ DOTTIN YR AV AN YR BV MKAY + +KTHXBYE diff --git a/Task/Dot-product/Loglan82/dot-product.loglan82 b/Task/Dot-product/Loglan82/dot-product.loglan82 new file mode 100644 index 0000000000..58d21b8f35 --- /dev/null +++ b/Task/Dot-product/Loglan82/dot-product.loglan82 @@ -0,0 +1,17 @@ +(* Dot product *) + +block + unit vector: class (x, y, z: real); + end vector; + + unit dot_product: function (u, v: vector) : real; + begin + result := u.x * v.x + u.y * v.y + u.z * v.z + end dot_product; + +var + dp: real; +begin + dp := dot_product(new vector(1.0, 3.0, -5.0), new vector(4.0, -2.0, -1.0)); + writeln(dp) +end diff --git a/Task/Dot-product/Nu/dot-product.nu b/Task/Dot-product/Nu/dot-product.nu new file mode 100644 index 0000000000..655132cc4e --- /dev/null +++ b/Task/Dot-product/Nu/dot-product.nu @@ -0,0 +1,5 @@ +def 'math dot' [v] { + zip $v | each { math product } | math sum +} + +[1 3 -5] | math dot [4 -2 -1] diff --git a/Task/Dot-product/OCaml/dot-product-1.ocaml b/Task/Dot-product/OCaml/dot-product-1.ml similarity index 100% rename from Task/Dot-product/OCaml/dot-product-1.ocaml rename to Task/Dot-product/OCaml/dot-product-1.ml diff --git a/Task/Dot-product/OCaml/dot-product-2.ocaml b/Task/Dot-product/OCaml/dot-product-2.ml similarity index 100% rename from Task/Dot-product/OCaml/dot-product-2.ocaml rename to Task/Dot-product/OCaml/dot-product-2.ml diff --git a/Task/Dot-product/Pascal-P/dot-product.pas b/Task/Dot-product/Pascal-P/dot-product.pas new file mode 100644 index 0000000000..db1cfeb348 --- /dev/null +++ b/Task/Dot-product/Pascal-P/dot-product.pas @@ -0,0 +1,29 @@ +program dotproduct(output); + (* Dot product *) + +const + maxi = 2; + +type + realarray = array [0 .. maxi] of real; + +var + x, y: realarray; + + function dotproduct(a, b: realarray): real; + var + i: integer; + res: real; + begin + res := 0; + for i := 0 to maxi do + res := res + (a[i] * b[i]); + dotproduct := res; + end; + +begin + x[0] := 1; x[1] := 3; x[2] := -5; + y[0] := 4; y[1] := -2; y[2] := -1; + writeln(dotproduct(x, y)); + (* readln; *) +end. diff --git a/Task/Dot-product/PascalABC.NET/dot-product.pas b/Task/Dot-product/PascalABC.NET/dot-product.pas new file mode 100644 index 0000000000..71d0c2418d --- /dev/null +++ b/Task/Dot-product/PascalABC.NET/dot-product.pas @@ -0,0 +1,4 @@ +## +function DotProduct(a, b: array of real) := a.Zip(b, (x, y) -> x * y).Sum; + +DotProduct(|1.0, 3, -5|, |4.0, -2, -1|).println; diff --git a/Task/Dot-product/Perl/dot-product.pl b/Task/Dot-product/Perl/dot-product-1.pl similarity index 100% rename from Task/Dot-product/Perl/dot-product.pl rename to Task/Dot-product/Perl/dot-product-1.pl diff --git a/Task/Dot-product/Perl/dot-product-2.pl b/Task/Dot-product/Perl/dot-product-2.pl new file mode 100644 index 0000000000..3ee16d9b23 --- /dev/null +++ b/Task/Dot-product/Perl/dot-product-2.pl @@ -0,0 +1,12 @@ +#!/usr/bin/perl + +use strict; # https://rosettacode.org/wiki/Dot_product +use warnings; +use List::AllUtils qw( sum zip_by product ); + +sub dotprod { return sum zip_by { product @_ } @_ } + +my @vec_a = (1,3,-5); +my @vec_b = (4,-2,-1); + +print dotprod(\@vec_a, \@vec_b), "\n"; diff --git a/Task/Dot-product/PowerShell/dot-product.psh b/Task/Dot-product/PowerShell/dot-product.ps1 similarity index 100% rename from Task/Dot-product/PowerShell/dot-product.psh rename to Task/Dot-product/PowerShell/dot-product.ps1 diff --git a/Task/Dot-product/REBOL/dot-product.rebol b/Task/Dot-product/REBOL/dot-product.rebol deleted file mode 100644 index a2d960f24d..0000000000 --- a/Task/Dot-product/REBOL/dot-product.rebol +++ /dev/null @@ -1,16 +0,0 @@ -REBOL [] - -a: [1 3 -5] -b: [4 -2 -1] - -dot-product: function [v1 v2] [sum] [ - if (length? v1) != (length? v2) [ - make error! "error: vector sizes must match" - ] - sum: 0 - repeat i length? v1 [ - sum: sum + ((pick v1 i) * (pick v2 i)) - ] -] - -dot-product a b diff --git a/Task/Dot-product/Rebol/dot-product.rebol b/Task/Dot-product/Rebol/dot-product.rebol new file mode 100644 index 0000000000..f8299d6371 --- /dev/null +++ b/Task/Dot-product/Rebol/dot-product.rebol @@ -0,0 +1,16 @@ +Rebol [] +a: [1 3 -5] +b: [4 -2 -1] + +dot-product: func [v1 v2 /local len sum] [ + len: length? v1 + if len <> length? v2 [ + make error! "error: vector sizes must match" + ] + sum: 0 + repeat i len [ + sum: sum + (v1/:i * v2/:i) + ] +] + +dot-product a b diff --git a/Task/Dot-product/Red/dot-product.red b/Task/Dot-product/Red/dot-product.red new file mode 100644 index 0000000000..1996c9335e --- /dev/null +++ b/Task/Dot-product/Red/dot-product.red @@ -0,0 +1,10 @@ +Red [ "Dot product - hinjolicious" ] + +#include %mylib/pipe-map.red +#include %mylib/transpose-zip.Red + +demo "Dot product" [ +a: [1 3 -5] +b: [4 -2 -1] +(reduce [a b]) |> zip ==> [_m/1 * _m/2] |> sum |> probe ; 3 +] diff --git a/Task/Dot-product/Rust/dot-product-1.rust b/Task/Dot-product/Rust/dot-product-1.rs similarity index 100% rename from Task/Dot-product/Rust/dot-product-1.rust rename to Task/Dot-product/Rust/dot-product-1.rs diff --git a/Task/Dot-product/Rust/dot-product-2.rust b/Task/Dot-product/Rust/dot-product-2.rs similarity index 100% rename from Task/Dot-product/Rust/dot-product-2.rust rename to Task/Dot-product/Rust/dot-product-2.rs diff --git a/Task/Dot-product/Rye/dot-product.rye b/Task/Dot-product/Rye/dot-product.rye new file mode 100644 index 0000000000..28deb83a66 --- /dev/null +++ b/Task/Dot-product/Rye/dot-product.rye @@ -0,0 +1 @@ +print dot-product vector { 1 3 -5 } vector { 4 -2 -1 } diff --git a/Task/Dot-product/Scheme/dot-product.ss b/Task/Dot-product/Scheme/dot-product.scm similarity index 100% rename from Task/Dot-product/Scheme/dot-product.ss rename to Task/Dot-product/Scheme/dot-product.scm diff --git a/Task/Dot-product/Uiua/dot-product.uiua b/Task/Dot-product/Uiua/dot-product.uiua new file mode 100644 index 0000000000..f0af9bb367 --- /dev/null +++ b/Task/Dot-product/Uiua/dot-product.uiua @@ -0,0 +1,2 @@ +[4 ¯2 ¯1] [1 3 ¯5] +/+× diff --git a/Task/Dot-product/VBScript/dot-product.vb b/Task/Dot-product/VBScript/dot-product.vbs similarity index 100% rename from Task/Dot-product/VBScript/dot-product.vb rename to Task/Dot-product/VBScript/dot-product.vbs diff --git a/Task/Dot-product/Zig/dot-product.zig b/Task/Dot-product/Zig/dot-product.zig index 82ecb11802..1118520c95 100644 --- a/Task/Dot-product/Zig/dot-product.zig +++ b/Task/Dot-product/Zig/dot-product.zig @@ -1,10 +1,9 @@ const std = @import("std"); -const Vector = std.meta.Vector; pub fn main() !void { - const a: Vector(3, i32) = [_]i32{1, 3, -5}; - const b: Vector(3, i32) = [_]i32{4, -2, -1}; - var dot: i32 = @reduce(.Add, a*b); + const a = @Vector(3, i32){ 1, 3, -5 }; + const b = @Vector(3, i32){ 4, -2, -1 }; + const dot: i32 = @reduce(.Add, a * b); try std.io.getStdOut().writer().print("{d}\n", .{dot}); } diff --git a/Task/Doubly-linked-list-Definition/Delphi/doubly-linked-list-definition.delphi b/Task/Doubly-linked-list-Definition/Delphi/doubly-linked-list-definition.pas similarity index 100% rename from Task/Doubly-linked-list-Definition/Delphi/doubly-linked-list-definition.delphi rename to Task/Doubly-linked-list-Definition/Delphi/doubly-linked-list-definition.pas diff --git a/Task/Doubly-linked-list-Definition/FutureBasic/doubly-linked-list-definition.basic b/Task/Doubly-linked-list-Definition/FutureBasic/doubly-linked-list-definition.basic new file mode 100644 index 0000000000..32155d51d0 --- /dev/null +++ b/Task/Doubly-linked-list-Definition/FutureBasic/doubly-linked-list-definition.basic @@ -0,0 +1,67 @@ +begin globals + str255 List(8) //create a new list of strings (List(0) not used +end globals + + +local fn ShowList(title As str255) + //display all elements from list of string + short j + Print title; + For j = 1 to 7 + Print List(j); " "; + Next j + Print "" +End fn + + +/////////// MAIN PROGRAM //////////// + +Dim As str255 item //items to add to the list +Dim As short i,j, c = 0 + +//the list of data that will be added to the list +data: +Data "One", "Two", "Three", "Four", "Five", "Six", "EndOfData" + +Restore +c = 0 +Do + Read item + If item <> "EndOfData" Then List(c) = item + c ++ +Until item = "EndOfData" + +str255 ListTMP(7) + +For j = 1 To 7 + ListTMP(7-j) = List(j) +Next j +For j = 1 To 7 + Swap List(j), ListTMP(j) +Next j +fn ShowList("Insertion at Head: ") + +for i = 1 to 7 : List(i) = "" : next i // clear list +Restore +c = 0 +Do + Read item //: c += 1 + If item <> "EndOfData" Then List(c) = item + c ++ +Until item = "EndOfData" +fn ShowList("Insertion at Tail: ") + +for i = 1 to 7 : List(i) = "" : next i // clear list +Restore +c = 0 +Do + Read item //: c += 1 + If item <> "EndOfData" Then List(c) = item + c ++ +Until item = "EndOfData" + +Swap List(3), List(6) +fn ShowList("Insertion in Middle: ") + + +handleevents diff --git a/Task/Doubly-linked-list-Definition/Julia/doubly-linked-list-definition-1.julia b/Task/Doubly-linked-list-Definition/Julia/doubly-linked-list-definition-1.jl similarity index 100% rename from Task/Doubly-linked-list-Definition/Julia/doubly-linked-list-definition-1.julia rename to Task/Doubly-linked-list-Definition/Julia/doubly-linked-list-definition-1.jl diff --git a/Task/Doubly-linked-list-Definition/Julia/doubly-linked-list-definition-2.julia b/Task/Doubly-linked-list-Definition/Julia/doubly-linked-list-definition-2.jl similarity index 100% rename from Task/Doubly-linked-list-Definition/Julia/doubly-linked-list-definition-2.julia rename to Task/Doubly-linked-list-Definition/Julia/doubly-linked-list-definition-2.jl diff --git a/Task/Doubly-linked-list-Definition/Kotlin/doubly-linked-list-definition.kotlin b/Task/Doubly-linked-list-Definition/Kotlin/doubly-linked-list-definition.kts similarity index 100% rename from Task/Doubly-linked-list-Definition/Kotlin/doubly-linked-list-definition.kotlin rename to Task/Doubly-linked-list-Definition/Kotlin/doubly-linked-list-definition.kts diff --git a/Task/Doubly-linked-list-Definition/PascalABC.NET/doubly-linked-list-definition.pas b/Task/Doubly-linked-list-Definition/PascalABC.NET/doubly-linked-list-definition.pas new file mode 100644 index 0000000000..a97277863b --- /dev/null +++ b/Task/Doubly-linked-list-Definition/PascalABC.NET/doubly-linked-list-definition.pas @@ -0,0 +1,75 @@ +type Node = auto class + data: T; + prev,next: Node; +end; + +type + MyLinkedList = class + first, last: Node; + procedure AddFirst(x: T); + begin + if first = nil then + begin + first := new Node(x,nil,nil); + last := first + end + else + begin + var p := new Node(x,nil,first); + first.prev := p; + first := p; + end; + end; + procedure AddLast(x: T); + begin + if first = nil then + begin + first := new Node(x,nil,nil); + last := first + end + else + begin + var p := new Node(x,last,nil); + last.next := p; + last := p; + end; + end; + procedure AddAfter(p: Node; x: T); + begin + if last = p then + AddLast(x) + else begin + var pp := new Node(x,p,p.next); + p.next := pp; + pp.next.prev := pp; + end + end; + procedure PrintList(); + begin + var p := first; + while p<>nil do + begin + Print(p.data); + p := p.next; + end; + end; + procedure PrintBack(); + begin + var p := last; + while p<>nil do + begin + Print(p.data); + p := p.prev; + end; + end; + end; + +begin + var lst := new MyLinkedList; + lst.AddFirst(2); lst.AddFirst(3); + lst.AddLast(5); + lst.AddAfter(lst.first,555); + lst.PrintList; + Println; + lst.PrintBack; +end. diff --git a/Task/Doubly-linked-list-Definition/Pluto/doubly-linked-list-definition.pluto b/Task/Doubly-linked-list-Definition/Pluto/doubly-linked-list-definition.pluto new file mode 100644 index 0000000000..c165dcf1c8 --- /dev/null +++ b/Task/Doubly-linked-list-Definition/Pluto/doubly-linked-list-definition.pluto @@ -0,0 +1,18 @@ +require "list" + +local d = dlist.of("A", "B") +print(d) +-- Add an element at the head. +d:prepend("C") +-- Add an element in the middle. +d:insert(2, "D") +-- Add an element at the tail. +d:push("E") +print(d) + +-- Remove an element by index (indexing is 1 based). +d:remove(2) +print(d) +-- Remove an element by value. +d:erase("A") +print(d) diff --git a/Task/Doubly-linked-list-Definition/PowerShell/doubly-linked-list-definition-1.psh b/Task/Doubly-linked-list-Definition/PowerShell/doubly-linked-list-definition-1.ps1 similarity index 100% rename from Task/Doubly-linked-list-Definition/PowerShell/doubly-linked-list-definition-1.psh rename to Task/Doubly-linked-list-Definition/PowerShell/doubly-linked-list-definition-1.ps1 diff --git a/Task/Doubly-linked-list-Definition/PowerShell/doubly-linked-list-definition-2.psh b/Task/Doubly-linked-list-Definition/PowerShell/doubly-linked-list-definition-2.ps1 similarity index 100% rename from Task/Doubly-linked-list-Definition/PowerShell/doubly-linked-list-definition-2.psh rename to Task/Doubly-linked-list-Definition/PowerShell/doubly-linked-list-definition-2.ps1 diff --git a/Task/Doubly-linked-list-Definition/PowerShell/doubly-linked-list-definition-3.psh b/Task/Doubly-linked-list-Definition/PowerShell/doubly-linked-list-definition-3.ps1 similarity index 100% rename from Task/Doubly-linked-list-Definition/PowerShell/doubly-linked-list-definition-3.psh rename to Task/Doubly-linked-list-Definition/PowerShell/doubly-linked-list-definition-3.ps1 diff --git a/Task/Doubly-linked-list-Definition/PowerShell/doubly-linked-list-definition-4.psh b/Task/Doubly-linked-list-Definition/PowerShell/doubly-linked-list-definition-4.ps1 similarity index 100% rename from Task/Doubly-linked-list-Definition/PowerShell/doubly-linked-list-definition-4.psh rename to Task/Doubly-linked-list-Definition/PowerShell/doubly-linked-list-definition-4.ps1 diff --git a/Task/Doubly-linked-list-Definition/RISC-V-Assembly/doubly-linked-list-definition.asm b/Task/Doubly-linked-list-Definition/RISC-V-Assembly/doubly-linked-list-definition.asm new file mode 100644 index 0000000000..e3c89ff6db --- /dev/null +++ b/Task/Doubly-linked-list-Definition/RISC-V-Assembly/doubly-linked-list-definition.asm @@ -0,0 +1,347 @@ +# riscv assembly raspberry pico2 rp2350 +# program dbllinkedlist.s +# connexion putty com3 +/*********************************************/ +/* CONSTANTES */ +/********************************************/ +/* for this file see risc-v task include a file */ +.include "../../../constantesRiscv.inc" +.equ HEAPSIZE, 50000 +/****************************************************/ +/* MACROS */ +/****************************************************/ +#.include "../ficmacrosriscv.inc" # only for debugging + +/*******************************************/ +/* STRUCTURE */ +/*******************************************/ +/* structure Doublylinkedlist*/ + .struct 0 +dllist_head: # head node + .struct dllist_head + 4 +dllist_tail: # tail node + .struct dllist_tail + 4 +dllist_end: +/* structure Node Doublylinked List*/ + .struct 0 +NDlist_next: # next element + .struct NDlist_next + 4 +NDlist_prev: # previous element + .struct NDlist_prev + 4 +NDlist_value: # element value or key + .struct NDlist_value + 4 +NDlist_end: +/*******************************************/ +/* INITIALED DATAS */ +/*******************************************/ +.data +szMessStart: .asciz "Program riscv start.\r\n" +szMessEndOk: .asciz "Program riscv end OK.\r\n" +szCariageReturn: .asciz "\r\n" + +szMessInitListe: .asciz "List initialized.\n" +szMessErreur: .asciz "Error detected.\n" +szMessResult: .asciz "Element No :" +szMessResultValue: .asciz " value : " +szMessInverse: .asciz "\nList inverse : \n" +.align 2 +ptHeapReserve: .int heapReserve +/*******************************************/ +/* UNINITIALED DATA */ +/*******************************************/ +.bss +sConvArea: .skip 24 +.align 2 +dlList1: .skip dllist_end # list memory place +heapReserve: .skip HEAPSIZE + +/**********************************************/ +/* SECTION CODE */ +/**********************************************/ +.text +.global main + +main: + call stdio_init_all # général init +1: # start loop connexion + li a0,0 # raz argument register + call tud_cdc_n_connected # waiting for USB connection + beqz a0,1b # return code = zero ? yes -> loop + + la a0,szMessStart # message address + call writeString # display message + + la a0,dlList1 + call newDList # create new list + la a0,szMessInitListe + call writeString + + + + la a0,dlList1 # list address + li a1,5000 # value to insert + call insertTail # insertion at head + bgez a0,2f # error ? + la a0,szMessErreur + call writeString + j 10f +2: + la a0,dlList1 # list address + li a1,42 # value to insert + call insertHead # insertion at head + bgez a0,3f # error ? + la a0,szMessErreur + call writeString + j 10f + +3: + la a0,dlList1 # list address + li a1,42 # search value + li a2,1234567 # value to insert + call insertAfter # insertion after node contains search value + bgez a0,4f # error ? + la a0,szMessErreur + call writeString + j 10f +4: + + la s0,dlList1 # list address + lw s0,dllist_head(s0) + beqz s0,10f # empty list + li s1,1 # n0 element +5: + lw s2,NDlist_value(s0) # load pointer + #beqz s2,10f # end list ? + la a0,szMessResult + call writeString + mv a0,s1 # conversion and display N° element + la a1,sConvArea + call conversion10 + la a0,sConvArea + call writeString + + la a0,szMessResultValue + call writeString + mv a0,s2 # conversion and display value element + la a1,sConvArea + call conversion10 + la a0,sConvArea + call writeString + la a0,szCariageReturn + call writeString + addi s1,s1,1 + lw s0,NDlist_next(s0) # load next pointer + bnez s0,5b # not null pointer -> loop + + la a0,szMessInverse + call writeString + la s0,dlList1 # list address + lw s0,dllist_tail(s0) + beqz s0,10f # empty list + li s1,1 # n0 element +6: + lw s2,NDlist_value(s0) # load pointer + #beqz s2,10f # end list ? + la a0,szMessResult + call writeString + mv a0,s1 # conversion and display N° element + la a1,sConvArea + call conversion10 + la a0,sConvArea + call writeString + + la a0,szMessResultValue + call writeString + mv a0,s2 # conversion and display value element + la a1,sConvArea + call conversion10 + la a0,sConvArea + call writeString + la a0,szCariageReturn + call writeString + addi s1,s1,1 + lw s0,NDlist_prev(s0) # load next pointer + bnez s0,6b # not null pointer -> loop + +10: + la a0,szMessEndOk # message address + call writeString # display message + call getchar +100: # final loop + j 100b + +/**********************************************/ +/* create new double linked list */ +/**********************************************/ +/* a0 linked list address */ +newDList: # INFO: newDList + addi sp, sp, -4 + sw ra, 0(sp) + + sw x0,dllist_tail(a0) # raz pointer + sw x0,dllist_head(a0) # raz pointer + + lw ra, 0(sp) + addi sp, sp, 4 + ret +/**********************************************/ +/* insertion value in head */ +/**********************************************/ +/* a0 double linked list address */ +/* a1 contains the value of element */ +/* a0 returns address of element or - 1 if error */ +insertHead: # INFO: insertTail + addi sp, sp, -8 + sw ra, 0(sp) + sw s0, 4(sp) + mv s0,a0 # save address + mv a0,a1 # value + call createNode # create new node + bltz a0,100f # error ? + + lw t0,dllist_head(s0) # load address first node + sw t0,NDlist_next(a0) # store in next pointer on new node + sw x0,NDlist_prev(a0) # store null on prev pointer + sw a0,dllist_head(s0) # store address new node on list head + beqz t0,1f # address last node is null ? + sw a0,NDlist_prev(t0) # no store address new node in next pointer + j 2f +1: + sw a0,dllist_tail(s0) # else store in head list +2: + +100: + lw ra, 0(sp) + lw s0, 4(sp) + addi sp, sp, 8 + ret + +/**********************************************/ +/* insertion value in Tail */ +/**********************************************/ +/* a0 double linked list address */ +/* a1 contains the value of element */ +/* a0 returns address of element or - 1 if error */ +insertTail: # INFO: insertTail + addi sp, sp, -8 + sw ra, 0(sp) + sw s0, 4(sp) + mv s0,a0 # save address + mv a0,a1 # value + call createNode # create new node + bltz a0,100f # error ? + + lw t0,dllist_tail(s0) # load address last node + sw t0,NDlist_prev(a0) # store in previous pointer on new node + sw x0,NDlist_next(a0) # store null un next pointer + sw a0,dllist_tail(s0) # store address new node on list tail + beqz t0,1f # address last node is null ? + sw a0,NDlist_next(t0) # no store address new node in next pointer + j 2f +1: + sw a0,dllist_head(s0) # else store in head list +2: + +100: + lw ra, 0(sp) + lw s0, 4(sp) + addi sp, sp, 8 + ret +/**********************************************/ +/* insertion value in after search value */ +/**********************************************/ +/* a0 double linked list address */ +/* a1 contains the search value after that insert */ +/* a2 contains the value of element */ +/* a0 returns address of element or - 1 if error */ +insertAfter: # INFO: insertAfter + addi sp, sp, -12 + sw ra, 0(sp) + sw s0, 4(sp) + sw s1, 8(sp) + mv s0,a0 # save address + call searchValue + bltz a0,100f # error ? + mv s1,a0 # save address find node + mv a0,a2 # value + call createNode # create new node + bltz a0,100f # error ? + + lw t0,NDlist_next(s1) # load pointer next of find node + sw a0,NDlist_next(s1) # store new node in pointer next + sw s1,NDlist_prev(a0) # store address find node in previous pointer on new node + sw t0,NDlist_next(a0) # store pointer next of find node on pointer next on new node + + beqz t0,1f # address next node null ? + sw a0,NDlist_prev(t0) # no store address new node in previous pointer + j 2f +1: + sw a0,dllist_tail(s0) # else store in tail list +2: + +100: + lw ra, 0(sp) + lw s0, 4(sp) + lw s1, 8(sp) + addi sp, sp, 12 + ret + +/**********************************************/ +/* search value in double linked list */ +/**********************************************/ +/* a0 contains the address of the list structure */ +/* a1 contains the value to search */ +/* a0 return address of node or -1 if not found */ +searchValue: # INFO: searchValue + addi sp, sp, -4 + sw ra, 0(sp) + lw t0,dllist_head(a0) # load first node +1: + bnez t0,2f # equal zero ? + li a0,-1 # yes -> not found -> end + j 100f +2: + lw t1,NDlist_value(t0) # load node value + bne t1,a1,3f # equal search value ? + mv a0,t0 # yes -> end + j 100f +3: + lw t0,NDlist_next(t0) # load address nex node + j 1b # and loop + +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret +/**********************************************/ +/* create node on heap */ +/**********************************************/ +/* a0 value */ +/* a0 return node address or -1 if error */ +createNode: # INFO: createNode + addi sp, sp, -4 + sw ra, 0(sp) + la t0,ptHeapReserve + lw t1,(t0) # free heap address + addi t2,t1,NDlist_end # reserve area on heap + la t3,heapReserve + li t4,HEAPSIZE + add t3,t3,t4 + blt t2,t3,2f + li a0,-1 + j 100f +2: + sw t2,(t0) # save new value heap used + sw a0,NDlist_value(t1) # store value on heap + sw x0,NDlist_next(t1) # raz pointer next + sw x0,NDlist_prev(t1) # raz pointer previous + mv a0,t1 # return node address +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret +/************************************/ +/* file include Fonctions */ +/***********************************/ +/* for this file see risc-v task include a file */ +.include "../../../includeFunctions.s" diff --git a/Task/Doubly-linked-list-Definition/Raku/doubly-linked-list-definition.raku b/Task/Doubly-linked-list-Definition/Raku/doubly-linked-list-definition.raku index 5ee1919518..ba49db0aee 100644 --- a/Task/Doubly-linked-list-Definition/Raku/doubly-linked-list-definition.raku +++ b/Task/Doubly-linked-list-Definition/Raku/doubly-linked-list-definition.raku @@ -4,29 +4,29 @@ role DLElem[::T] { has T $.payload = T; method pre-insert(T $payload) { - die "Can't insert before beginning" unless $!prev; - my $elem = ::?CLASS.new(:$payload); - $!prev.next = $elem; - $elem.prev = $!prev; - $elem.next = self; - $!prev = $elem; - $elem; + die "Can't insert before beginning" unless $!prev; + my $elem = ::?CLASS.new(:$payload); + $!prev.next = $elem; + $elem.prev = $!prev; + $elem.next = self; + $!prev = $elem; + $elem; } method post-insert(T $payload) { - die "Can't insert after end" unless $!next; - my $elem = ::?CLASS.new(:$payload); - $!next.prev = $elem; - $elem.next = $!next; - $elem.prev = self; - $!next = $elem; - $elem; + die "Can't insert after end" unless $!next; + my $elem = ::?CLASS.new(:$payload); + $!next.prev = $elem; + $elem.next = $!next; + $elem.prev = self; + $!next = $elem; + $elem; } method delete { - die "Can't delete a sentinel" unless $!prev and $!next; - $!next.prev = $!prev; - $!prev.next = $!next; # conveniently returns next element + die "Can't delete a sentinel" unless $!prev and $!next; + $!next.prev = $!prev; + $!prev.next = $!next; # conveniently returns next element } } @@ -35,10 +35,10 @@ role DLList[::DLE] { has DLE $.last; submethod BUILD { - $!first = DLE.new; - $!last = DLE.new; - $!first.next = $!last; - $!last.prev = $!first; + $!first = DLE.new; + $!last = DLE.new; + $!first.next = $!last; + $!last.prev = $!first; } method list { ($!first.next, *.next ...^ !*.next).map: *.payload } diff --git a/Task/Doubly-linked-list-Definition/Rust/doubly-linked-list-definition-1.rs b/Task/Doubly-linked-list-Definition/Rust/doubly-linked-list-definition-1.rs new file mode 100644 index 0000000000..2dbdcfbc18 --- /dev/null +++ b/Task/Doubly-linked-list-Definition/Rust/doubly-linked-list-definition-1.rs @@ -0,0 +1,7 @@ +// We are ommitting the allocator for these examples +pub struct LinkedList { + head: Option>>, + tail: Option>>, + len: usize, + marker: PhantomData>>, // We logically hold an owned pointer to Node +} diff --git a/Task/Doubly-linked-list-Definition/Rust/doubly-linked-list-definition-2.rs b/Task/Doubly-linked-list-Definition/Rust/doubly-linked-list-definition-2.rs new file mode 100644 index 0000000000..c0e18e5933 --- /dev/null +++ b/Task/Doubly-linked-list-Definition/Rust/doubly-linked-list-definition-2.rs @@ -0,0 +1,40 @@ +trait ListExt { + fn insert(&mut self, elt: T, at: usize); +} + +impl ListExt for std::collections::LinkedList { + // The following references the standard library's implementation of `LinkedList::remove` + fn insert(&mut self, elt: T, at: usize) { + let len = self.len(); + assert!( + at <= len, + "The given index must be a valid index after insertion", + ); + + let offset_from_end = len - at; + if at < offset_from_end { + let mut cursor = self.cursor_front_mut(); + for _ in 0..at { + cursor.move_next(); + } + cursor.insert_before(elt); + } else { + let mut cursor = self.cursor_back_mut(); + for _ in 0..offset_from_end { + cursor.move_prev(); + } + cursor.insert_after(elt); + } + } +} + +fn definition() { + use std::collections::LinkedList; + + let mut list = LinkedList::new(); + list.push_back('B'); + list.push_front('A'); + list.insert('C', 1); + + assert_eq!(list, ['A', 'C', 'B'].into()); +} diff --git a/Task/Doubly-linked-list-Definition/Scheme/doubly-linked-list-definition.ss b/Task/Doubly-linked-list-Definition/Scheme/doubly-linked-list-definition.scm similarity index 100% rename from Task/Doubly-linked-list-Definition/Scheme/doubly-linked-list-definition.ss rename to Task/Doubly-linked-list-Definition/Scheme/doubly-linked-list-definition.scm diff --git a/Task/Doubly-linked-list-Element-definition/Ada/doubly-linked-list-element-definition-1.ada b/Task/Doubly-linked-list-Element-definition/Ada/doubly-linked-list-element-definition-1.adb similarity index 100% rename from Task/Doubly-linked-list-Element-definition/Ada/doubly-linked-list-element-definition-1.ada rename to Task/Doubly-linked-list-Element-definition/Ada/doubly-linked-list-element-definition-1.adb diff --git a/Task/Doubly-linked-list-Element-definition/Ada/doubly-linked-list-element-definition-2.ada b/Task/Doubly-linked-list-Element-definition/Ada/doubly-linked-list-element-definition-2.adb similarity index 100% rename from Task/Doubly-linked-list-Element-definition/Ada/doubly-linked-list-element-definition-2.ada rename to Task/Doubly-linked-list-Element-definition/Ada/doubly-linked-list-element-definition-2.adb diff --git a/Task/Doubly-linked-list-Element-definition/Ada/doubly-linked-list-element-definition-3.ada b/Task/Doubly-linked-list-Element-definition/Ada/doubly-linked-list-element-definition-3.adb similarity index 100% rename from Task/Doubly-linked-list-Element-definition/Ada/doubly-linked-list-element-definition-3.ada rename to Task/Doubly-linked-list-Element-definition/Ada/doubly-linked-list-element-definition-3.adb diff --git a/Task/Doubly-linked-list-Element-definition/Delphi/doubly-linked-list-element-definition.delphi b/Task/Doubly-linked-list-Element-definition/Delphi/doubly-linked-list-element-definition.pas similarity index 100% rename from Task/Doubly-linked-list-Element-definition/Delphi/doubly-linked-list-element-definition.delphi rename to Task/Doubly-linked-list-Element-definition/Delphi/doubly-linked-list-element-definition.pas diff --git a/Task/Doubly-linked-list-Element-definition/Julia/doubly-linked-list-element-definition.julia b/Task/Doubly-linked-list-Element-definition/Julia/doubly-linked-list-element-definition.jl similarity index 100% rename from Task/Doubly-linked-list-Element-definition/Julia/doubly-linked-list-element-definition.julia rename to Task/Doubly-linked-list-Element-definition/Julia/doubly-linked-list-element-definition.jl diff --git a/Task/Doubly-linked-list-Element-definition/Kotlin/doubly-linked-list-element-definition.kotlin b/Task/Doubly-linked-list-Element-definition/Kotlin/doubly-linked-list-element-definition.kts similarity index 100% rename from Task/Doubly-linked-list-Element-definition/Kotlin/doubly-linked-list-element-definition.kotlin rename to Task/Doubly-linked-list-Element-definition/Kotlin/doubly-linked-list-element-definition.kts diff --git a/Task/Doubly-linked-list-Element-definition/OCaml/doubly-linked-list-element-definition-1.ocaml b/Task/Doubly-linked-list-Element-definition/OCaml/doubly-linked-list-element-definition-1.ml similarity index 100% rename from Task/Doubly-linked-list-Element-definition/OCaml/doubly-linked-list-element-definition-1.ocaml rename to Task/Doubly-linked-list-Element-definition/OCaml/doubly-linked-list-element-definition-1.ml diff --git a/Task/Doubly-linked-list-Element-definition/OCaml/doubly-linked-list-element-definition-2.ocaml b/Task/Doubly-linked-list-Element-definition/OCaml/doubly-linked-list-element-definition-2.ml similarity index 100% rename from Task/Doubly-linked-list-Element-definition/OCaml/doubly-linked-list-element-definition-2.ocaml rename to Task/Doubly-linked-list-Element-definition/OCaml/doubly-linked-list-element-definition-2.ml diff --git a/Task/Doubly-linked-list-Element-definition/OCaml/doubly-linked-list-element-definition-3.ocaml b/Task/Doubly-linked-list-Element-definition/OCaml/doubly-linked-list-element-definition-3.ml similarity index 100% rename from Task/Doubly-linked-list-Element-definition/OCaml/doubly-linked-list-element-definition-3.ocaml rename to Task/Doubly-linked-list-Element-definition/OCaml/doubly-linked-list-element-definition-3.ml diff --git a/Task/Doubly-linked-list-Element-definition/OCaml/doubly-linked-list-element-definition-4.ocaml b/Task/Doubly-linked-list-Element-definition/OCaml/doubly-linked-list-element-definition-4.ml similarity index 100% rename from Task/Doubly-linked-list-Element-definition/OCaml/doubly-linked-list-element-definition-4.ocaml rename to Task/Doubly-linked-list-Element-definition/OCaml/doubly-linked-list-element-definition-4.ml diff --git a/Task/Doubly-linked-list-Element-definition/OCaml/doubly-linked-list-element-definition-5.ocaml b/Task/Doubly-linked-list-Element-definition/OCaml/doubly-linked-list-element-definition-5.ml similarity index 100% rename from Task/Doubly-linked-list-Element-definition/OCaml/doubly-linked-list-element-definition-5.ocaml rename to Task/Doubly-linked-list-Element-definition/OCaml/doubly-linked-list-element-definition-5.ml diff --git a/Task/Doubly-linked-list-Element-definition/PascalABC.NET/doubly-linked-list-element-definition.pas b/Task/Doubly-linked-list-Element-definition/PascalABC.NET/doubly-linked-list-element-definition.pas new file mode 100644 index 0000000000..41706415b2 --- /dev/null +++ b/Task/Doubly-linked-list-Element-definition/PascalABC.NET/doubly-linked-list-element-definition.pas @@ -0,0 +1,4 @@ +type Node = auto class + data: T; + prev,next: Node; +end; diff --git a/Task/Doubly-linked-list-Element-definition/Pluto/doubly-linked-list-element-definition.pluto b/Task/Doubly-linked-list-Element-definition/Pluto/doubly-linked-list-element-definition.pluto new file mode 100644 index 0000000000..6172bb682a --- /dev/null +++ b/Task/Doubly-linked-list-Element-definition/Pluto/doubly-linked-list-element-definition.pluto @@ -0,0 +1,9 @@ +require "list" + +local s = dlist.of(1, 2, 3) +local n1 = s:node(1) +local n2 = s:node(2) +local n3 = s:node(3) +print($"node 1: value = {n1.value}, next = {tostring(n1.next?.value)}, prev = {tostring(n1.prev?.value)}") +print($"node 2: value = {n2.value}, next = {tostring(n2.next?.value)}, prev = {tostring(n2.prev?.value)}") +print($"node 3: value = {n3.value}, next = {tostring(n3.next?.value)}, prev = {tostring(n3.prev?.value)}") diff --git a/Task/Doubly-linked-list-Element-definition/Rust/doubly-linked-list-element-definition-1.rust b/Task/Doubly-linked-list-Element-definition/Rust/doubly-linked-list-element-definition-1.rust deleted file mode 100644 index 14f822a8eb..0000000000 --- a/Task/Doubly-linked-list-Element-definition/Rust/doubly-linked-list-element-definition-1.rust +++ /dev/null @@ -1,5 +0,0 @@ -use std::collections::LinkedList; -fn main() { - // Doubly linked list containing 32-bit integers - let list = LinkedList::::new(); -} diff --git a/Task/Doubly-linked-list-Element-definition/Rust/doubly-linked-list-element-definition-2.rust b/Task/Doubly-linked-list-Element-definition/Rust/doubly-linked-list-element-definition-2.rust deleted file mode 100644 index f05fe72380..0000000000 --- a/Task/Doubly-linked-list-Element-definition/Rust/doubly-linked-list-element-definition-2.rust +++ /dev/null @@ -1,12 +0,0 @@ -pub struct LinkedList { - head: Option>>, - tail: Option>>, - len: usize, - marker: PhantomData>>, // Indicates that we logically own a boxed (owned pointer) Node> -} - -struct Node { - next: Option>>, - prev: Option>>, - element: T, -} diff --git a/Task/Doubly-linked-list-Element-definition/Rust/doubly-linked-list-element-definition.rs b/Task/Doubly-linked-list-Element-definition/Rust/doubly-linked-list-element-definition.rs new file mode 100644 index 0000000000..235ae6bd30 --- /dev/null +++ b/Task/Doubly-linked-list-Element-definition/Rust/doubly-linked-list-element-definition.rs @@ -0,0 +1,5 @@ +struct Node { + next: Option>>, + prev: Option>>, + element: T, +} diff --git a/Task/Doubly-linked-list-Element-insertion/Ada/doubly-linked-list-element-insertion-1.ada b/Task/Doubly-linked-list-Element-insertion/Ada/doubly-linked-list-element-insertion-1.adb similarity index 100% rename from Task/Doubly-linked-list-Element-insertion/Ada/doubly-linked-list-element-insertion-1.ada rename to Task/Doubly-linked-list-Element-insertion/Ada/doubly-linked-list-element-insertion-1.adb diff --git a/Task/Doubly-linked-list-Element-insertion/Ada/doubly-linked-list-element-insertion-2.ada b/Task/Doubly-linked-list-Element-insertion/Ada/doubly-linked-list-element-insertion-2.adb similarity index 100% rename from Task/Doubly-linked-list-Element-insertion/Ada/doubly-linked-list-element-insertion-2.ada rename to Task/Doubly-linked-list-Element-insertion/Ada/doubly-linked-list-element-insertion-2.adb diff --git a/Task/Doubly-linked-list-Element-insertion/Ada/doubly-linked-list-element-insertion-3.ada b/Task/Doubly-linked-list-Element-insertion/Ada/doubly-linked-list-element-insertion-3.adb similarity index 100% rename from Task/Doubly-linked-list-Element-insertion/Ada/doubly-linked-list-element-insertion-3.ada rename to Task/Doubly-linked-list-Element-insertion/Ada/doubly-linked-list-element-insertion-3.adb diff --git a/Task/Doubly-linked-list-Element-insertion/Delphi/doubly-linked-list-element-insertion.delphi b/Task/Doubly-linked-list-Element-insertion/Delphi/doubly-linked-list-element-insertion.pas similarity index 100% rename from Task/Doubly-linked-list-Element-insertion/Delphi/doubly-linked-list-element-insertion.delphi rename to Task/Doubly-linked-list-Element-insertion/Delphi/doubly-linked-list-element-insertion.pas diff --git a/Task/Doubly-linked-list-Element-insertion/Julia/doubly-linked-list-element-insertion.julia b/Task/Doubly-linked-list-Element-insertion/Julia/doubly-linked-list-element-insertion.jl similarity index 100% rename from Task/Doubly-linked-list-Element-insertion/Julia/doubly-linked-list-element-insertion.julia rename to Task/Doubly-linked-list-Element-insertion/Julia/doubly-linked-list-element-insertion.jl diff --git a/Task/Doubly-linked-list-Element-insertion/Kotlin/doubly-linked-list-element-insertion.kotlin b/Task/Doubly-linked-list-Element-insertion/Kotlin/doubly-linked-list-element-insertion.kts similarity index 100% rename from Task/Doubly-linked-list-Element-insertion/Kotlin/doubly-linked-list-element-insertion.kotlin rename to Task/Doubly-linked-list-Element-insertion/Kotlin/doubly-linked-list-element-insertion.kts diff --git a/Task/Doubly-linked-list-Element-insertion/OCaml/doubly-linked-list-element-insertion-1.ocaml b/Task/Doubly-linked-list-Element-insertion/OCaml/doubly-linked-list-element-insertion-1.ml similarity index 100% rename from Task/Doubly-linked-list-Element-insertion/OCaml/doubly-linked-list-element-insertion-1.ocaml rename to Task/Doubly-linked-list-Element-insertion/OCaml/doubly-linked-list-element-insertion-1.ml diff --git a/Task/Doubly-linked-list-Element-insertion/OCaml/doubly-linked-list-element-insertion-2.ocaml b/Task/Doubly-linked-list-Element-insertion/OCaml/doubly-linked-list-element-insertion-2.ml similarity index 100% rename from Task/Doubly-linked-list-Element-insertion/OCaml/doubly-linked-list-element-insertion-2.ocaml rename to Task/Doubly-linked-list-Element-insertion/OCaml/doubly-linked-list-element-insertion-2.ml diff --git a/Task/Doubly-linked-list-Element-insertion/OCaml/doubly-linked-list-element-insertion-3.ocaml b/Task/Doubly-linked-list-Element-insertion/OCaml/doubly-linked-list-element-insertion-3.ml similarity index 100% rename from Task/Doubly-linked-list-Element-insertion/OCaml/doubly-linked-list-element-insertion-3.ocaml rename to Task/Doubly-linked-list-Element-insertion/OCaml/doubly-linked-list-element-insertion-3.ml diff --git a/Task/Doubly-linked-list-Element-insertion/OCaml/doubly-linked-list-element-insertion-4.ocaml b/Task/Doubly-linked-list-Element-insertion/OCaml/doubly-linked-list-element-insertion-4.ml similarity index 100% rename from Task/Doubly-linked-list-Element-insertion/OCaml/doubly-linked-list-element-insertion-4.ocaml rename to Task/Doubly-linked-list-Element-insertion/OCaml/doubly-linked-list-element-insertion-4.ml diff --git a/Task/Doubly-linked-list-Element-insertion/PascalABC.NET/doubly-linked-list-element-insertion.pas b/Task/Doubly-linked-list-Element-insertion/PascalABC.NET/doubly-linked-list-element-insertion.pas new file mode 100644 index 0000000000..3b2f5422ce --- /dev/null +++ b/Task/Doubly-linked-list-Element-insertion/PascalABC.NET/doubly-linked-list-element-insertion.pas @@ -0,0 +1,33 @@ +type Node = auto class + data: T; + prev,next: Node; +end; + +type + MyLinkedList = class + first, last: Node; + procedure AddLast(x: T); + begin + if first = nil then + begin + first := new Node(x,nil,nil); + last := first + end + else + begin + var p := new Node(x,last,nil); + last.next := p; + last := p; + end; + end; + procedure AddAfter(p: Node; x: T); + begin + if last = p then + AddLast(x) + else begin + var pp := new Node(x,p,p.next); + p.next := pp; + pp.prev.next := pp; + end + end; + end; diff --git a/Task/Doubly-linked-list-Element-insertion/Pluto/doubly-linked-list-element-insertion.pluto b/Task/Doubly-linked-list-Element-insertion/Pluto/doubly-linked-list-element-insertion.pluto new file mode 100644 index 0000000000..8b25ea3df0 --- /dev/null +++ b/Task/Doubly-linked-list-Element-insertion/Pluto/doubly-linked-list-element-insertion.pluto @@ -0,0 +1,5 @@ +require "list" + +local dll = dlist.of("A", "B") +dll:insert(2, "C") +print(dll) diff --git a/Task/Doubly-linked-list-Element-insertion/Rust/doubly-linked-list-element-insertion-1.rs b/Task/Doubly-linked-list-Element-insertion/Rust/doubly-linked-list-element-insertion-1.rs new file mode 100644 index 0000000000..3c28daad17 --- /dev/null +++ b/Task/Doubly-linked-list-Element-insertion/Rust/doubly-linked-list-element-insertion-1.rs @@ -0,0 +1,13 @@ +#![feature(linked_list_cursors)] + +pub struct Cursor<'a, T: 'a> { + index: usize, + current: Option>>, + list: &'a LinkedList, +} + +pub struct CursorMut<'a, T: 'a> { + index: usize, + current: Option>>, + list: &'a mut LinkedList, +} diff --git a/Task/Doubly-linked-list-Element-insertion/Rust/doubly-linked-list-element-insertion-1.rust b/Task/Doubly-linked-list-Element-insertion/Rust/doubly-linked-list-element-insertion-1.rust deleted file mode 100644 index 6846a0b845..0000000000 --- a/Task/Doubly-linked-list-Element-insertion/Rust/doubly-linked-list-element-insertion-1.rust +++ /dev/null @@ -1,5 +0,0 @@ -use std::collections::LinkedList; -fn main() { - let mut list = LinkedList::new(); - list.push_front(8); -} diff --git a/Task/Doubly-linked-list-Element-insertion/Rust/doubly-linked-list-element-insertion-2.rs b/Task/Doubly-linked-list-Element-insertion/Rust/doubly-linked-list-element-insertion-2.rs new file mode 100644 index 0000000000..7f29f65ef6 --- /dev/null +++ b/Task/Doubly-linked-list-Element-insertion/Rust/doubly-linked-list-element-insertion-2.rs @@ -0,0 +1,63 @@ +#![feature(linked_list_cursors)] + +trait CursorExt { + fn insert_between(&mut self, l: &T, elt: T, r: &T); + fn rinsert_between(&mut self, l: &T, elt: T, r: &T); +} + +impl CursorExt for std::collections::linked_list::CursorMut<'_, T> { + fn insert_between(&mut self, l: &T, elt: T, r: &T) { + // Pointing at the sentinel, move to head + if self.current().is_none() { + self.move_next(); + } + + let next = |cursor: &mut Self| { + let left = cursor.current()? == a; + let right = cursor.peek_next()? == b; + + Some(left && right) + }; + + while let Some(found) = next(self) { + if found { + self.insert_after(elt); + + return; + } + } + } + + fn rinsert_between(&mut self, l: &T, elt: T, r: &T) { + // Pointing at the sentinel, move to tail + if self.current().is_none() { + self.move_prev(); + } + + let prev = |cursor: &mut Self| { + let left = cursor.peek_prev()? == a; + let right = cursor.current()? == b; + + Some(left && right) + }; + + while let Some(found) = prev(self) { + if found { + self.insert_before(elt); + + return; + } + } + } +} + +fn element_insertion() { + use std::collections::LinkedList; + + let mut list = LinkedList::from(['A', 'B']); + + list.cursor_front_mut().insert_between(&'A', 'C', &'B'); + // list.cursor_back_mut().rinsert_between(&'A', 'C', &'B'); + + assert_eq!(list, ['A', 'C', 'B'].into()); +} diff --git a/Task/Doubly-linked-list-Element-insertion/Rust/doubly-linked-list-element-insertion-2.rust b/Task/Doubly-linked-list-Element-insertion/Rust/doubly-linked-list-element-insertion-2.rust deleted file mode 100644 index 3b478b7869..0000000000 --- a/Task/Doubly-linked-list-Element-insertion/Rust/doubly-linked-list-element-insertion-2.rust +++ /dev/null @@ -1,52 +0,0 @@ -impl Node { - fn new(v: T) -> Node { - Node {value: v, next: None, prev: Rawlink::none()} - } -} - -impl Rawlink { - fn none() -> Self { - Rawlink {p: ptr::null_mut()} - } - - fn some(n: &mut T) -> Rawlink { - Rawlink{p: n} - } -} - -impl<'a, T> From<&'a mut Link> for Rawlink> { - fn from(node: &'a mut Link) -> Self { - match node.as_mut() { - None => Rawlink::none(), - Some(ptr) => Rawlink::some(ptr) - } - } -} - - -fn link_no_prev(mut next: Box>) -> Link { - next.prev = Rawlink::none(); - Some(next) -} - -impl LinkedList { - #[inline] - fn push_front_node(&mut self, mut new_head: Box>) { - match self.list_head { - None => { - self.list_head = link_no_prev(new_head); - self.list_tail = Rawlink::from(&mut self.list_head); - } - Some(ref mut head) => { - new_head.prev = Rawlink::none(); - head.prev = Rawlink::some(&mut *new_head); - mem::swap(head, &mut new_head); - head.next = Some(new_head); - } - } - self.length += 1; - } - pub fn push_front(&mut self, elt: T) { - self.push_front_node(Box::new(Node::new(elt))); - } -} diff --git a/Task/Doubly-linked-list-Traversal/Ada/doubly-linked-list-traversal.ada b/Task/Doubly-linked-list-Traversal/Ada/doubly-linked-list-traversal.adb similarity index 100% rename from Task/Doubly-linked-list-Traversal/Ada/doubly-linked-list-traversal.ada rename to Task/Doubly-linked-list-Traversal/Ada/doubly-linked-list-traversal.adb diff --git a/Task/Doubly-linked-list-Traversal/Delphi/doubly-linked-list-traversal.delphi b/Task/Doubly-linked-list-Traversal/Delphi/doubly-linked-list-traversal.pas similarity index 100% rename from Task/Doubly-linked-list-Traversal/Delphi/doubly-linked-list-traversal.delphi rename to Task/Doubly-linked-list-Traversal/Delphi/doubly-linked-list-traversal.pas diff --git a/Task/Doubly-linked-list-Traversal/Julia/doubly-linked-list-traversal.julia b/Task/Doubly-linked-list-Traversal/Julia/doubly-linked-list-traversal.jl similarity index 100% rename from Task/Doubly-linked-list-Traversal/Julia/doubly-linked-list-traversal.julia rename to Task/Doubly-linked-list-Traversal/Julia/doubly-linked-list-traversal.jl diff --git a/Task/Doubly-linked-list-Traversal/Kotlin/doubly-linked-list-traversal.kotlin b/Task/Doubly-linked-list-Traversal/Kotlin/doubly-linked-list-traversal.kts similarity index 100% rename from Task/Doubly-linked-list-Traversal/Kotlin/doubly-linked-list-traversal.kotlin rename to Task/Doubly-linked-list-Traversal/Kotlin/doubly-linked-list-traversal.kts diff --git a/Task/Doubly-linked-list-Traversal/PascalABC.NET/doubly-linked-list-traversal.pas b/Task/Doubly-linked-list-Traversal/PascalABC.NET/doubly-linked-list-traversal.pas new file mode 100644 index 0000000000..5e67b3187f --- /dev/null +++ b/Task/Doubly-linked-list-Traversal/PascalABC.NET/doubly-linked-list-traversal.pas @@ -0,0 +1,9 @@ +begin + var lst := new LinkedList(1..10); + var current := lst.First; + while current <> nil do + begin + Print(current.Value); + current := current.Next; + end; +end. diff --git a/Task/Doubly-linked-list-Traversal/Pluto/doubly-linked-list-traversal.pluto b/Task/Doubly-linked-list-Traversal/Pluto/doubly-linked-list-traversal.pluto new file mode 100644 index 0000000000..17ae6ed4d6 --- /dev/null +++ b/Task/Doubly-linked-list-Traversal/Pluto/doubly-linked-list-traversal.pluto @@ -0,0 +1,24 @@ +require "list" +local fmt = require "fmt" + +-- Create a doubly-linked list containing the first 50 positive integers. +local d = dlist.of(range(1, 50):unpack()) + +-- Now traverse from beginning to end and print them in tabular form. +local node = d:node(1) +local count = 0 +while node do + fmt.write("%4d ", node.value) + node = node.next + if ++count % 10 == 0 then print() end +end +print() + +-- Now traverse them in the opposite direction and print then in tabular form. +node = d:node(d:size()) +count = 0 +while node do + fmt.write("%4d ", node.value) + node = node.prev + if ++count % 10 == 0 then print() end +end diff --git a/Task/Doubly-linked-list-Traversal/Rust/doubly-linked-list-traversal.rs b/Task/Doubly-linked-list-Traversal/Rust/doubly-linked-list-traversal.rs new file mode 100644 index 0000000000..05a8db2f1a --- /dev/null +++ b/Task/Doubly-linked-list-Traversal/Rust/doubly-linked-list-traversal.rs @@ -0,0 +1,15 @@ +fn traversal() { + use std::collections::LinkedList; + + let numbers = LinkedList::from([1, 5, 7, 0, 3, 2]); + + for i in &numbers { + print!("{i} "); + } + println!(); + + for i in numbers.iter().rev() { + print!("{i} "); + } + println!(); +} diff --git a/Task/Dragon-curve/ALGOL-68/dragon-curve-4.alg b/Task/Dragon-curve/ALGOL-68/dragon-curve-4.alg index 55d2235f9e..4d180563f7 100644 --- a/Task/Dragon-curve/ALGOL-68/dragon-curve-4.alg +++ b/Task/Dragon-curve/ALGOL-68/dragon-curve-4.alg @@ -53,7 +53,7 @@ BEGIN # Dragon Curve in SVG # put( svg file, ( "'/>", newline, "", newline ) ); close( svg file ) - FI # sierpinski square # ; + FI # dragon curve # ; dragon curve( "dragon.svg", 1200, 5, 12, 400, 200 ) diff --git a/Task/Dragon-curve/ASIC/dragon-curve.asic b/Task/Dragon-curve/ASIC/dragon-curve.asic new file mode 100644 index 0000000000..5697f69b99 --- /dev/null +++ b/Task/Dragon-curve/ASIC/dragon-curve.asic @@ -0,0 +1,130 @@ +REM Dragon curve +DIM S@(7) +DIM C@(7) +DIM R(27) +REM SIN, COS in arrays for PI/4 multipl. +DATA 0@, 0.70711@, 1@, 0.70711@, 0@, -0.70711@, -1@, -0.70711@ +DATA 1@, 0.70711@, 0@, -0.70711@, -1@, -0.70711@, 0@, 0.70711@ +Sqrt2@ = 1.41421@ +FOR I = 0 TO 7 + READ S@(I) +NEXT I +FOR I = 0 TO 7 + READ C@(I) +NEXT I +Level = 17 +Insize@ = 256 +REM Insize@ = 2^WHOLE_NUM looks fine +X@ = 224 +Y@ = 124 +RotQPi = 0 +RQ = 1 +SCREEN 9 +GOSUB Dragon: +LOCATE 20, 1 +PRINT "Press any key to exit." +Loop: + X$=INKEY$ + IF X$="" THEN Loop: +SCREEN 0 +END + +Dragon: +RotQPi = RotQPi MOD 8 +WHILE RotQPi < 0 + RotQPi = RotQPi + 8 +WEND +IF Level <= 1 THEN + YN@ = S@(RotQPi) * Insize@ + YN@ = YN@ + Y@ + XN@ = C@(RotQPi) * Insize@ + XN@ = XN@ + X@ + GOSUB DrawLine: + X@ = XN@ + Y@ = YN@ +ELSE + Insize@ = Insize@ * Sqrt2@ + Insize@ = Insize@ / 2@ + RotQPi = RotQPi + RQ + RotQPi = RotQPi MOD 8 + WHILE RotQPi < 0 + RotQPi = RotQPi + 8 + WEND + Level = Level - 1 + R(Level) = RQ + RQ = 1 + GOSUB Dragon: + RLevelM2 = R(Level) * 2 + RotQPi = RotQPi - RLevelM2 + RotQPi = RotQPi MOD 8 + WHILE RotQPi < 0 + RotQPi = RotQPi + 8 + WEND + RQ = -1 + GOSUB Dragon: + RQ = R(Level) + RotQPi = RotQPi + RQ + RotQPi = RotQPi MOD 8 + WHILE RotQPi < 0 + RotQPi = RotQPi + 8 + WEND + Level = Level + 1 + Insize@ = Insize@ * Sqrt2@ +ENDIF +RETURN + +DrawLine: +REM Draw a line from (X@, Y@) to (XN@, YN@) +REM Coordinates decimal, but converted in PSET. +DX@ = XN@ - X@ +DY@ = YN@ - Y@ +AbsDX@ = ABS(DX@) +AbsDY@ = ABS(DY@) +IF AbsDX@ <= AbsDY@ THEN + REM More vertical line + IF AbsDY@ <= 1@ THEN + REM The same pixel or neighboring ones, because AbsDX@ <= AbsDY@ <= 1. + PSET (Y@, X@), 10 + PSET (YN@, XN@), 10 + ELSE + REM There are pixels in between. + A@ = DX@ / DY@ + IF YN@ >= Y@ THEN + D@ = 1@ + ELSE + D@ = -1@ + ENDIF + CoordY@ = Y@ + WHILE CoordY@ <= YN@ + CoordX@ = CoordY@ - Y@ + CoordX@ = A@ * CoordX@ + CoordX@ = X@ + CoordX@ + PSET (CoordY@, CoordX@), 10 + CoordY@ = CoordY@ + D@ + WEND + ENDIF +ELSE + REM More horizontal line + IF AbsDX@ <= 1@ THEN + REM The same pixel or neighboring ones, because AbsDY@ < AbsDX@ <= 1. + PSET (Y@, X@), 10 + PSET (YN@, XN@), 10 + ELSE + REM There are pixels in between. + A@ = DY@ / DX@ + IF XN@ >= X@ THEN + D@ = 1@ + ELSE + D@ = -1@ + ENDIF + CoordX@ = X@ + WHILE CoordX@ <= XN@ + CoordY@ = CoordX@ - X@ + CoordY@ = A@ * CoordY@ + CoordY@ = Y@ + CoordY@ + PSET (CoordY@, CoordX@), 10 + CoordX@ = CoordX@ + D@ + WEND + ENDIF +ENDIF +RETURN diff --git a/Task/Dragon-curve/Ada/dragon-curve-1.ada b/Task/Dragon-curve/Ada/dragon-curve-1.adb similarity index 100% rename from Task/Dragon-curve/Ada/dragon-curve-1.ada rename to Task/Dragon-curve/Ada/dragon-curve-1.adb diff --git a/Task/Dragon-curve/Ada/dragon-curve-2.ada b/Task/Dragon-curve/Ada/dragon-curve-2.adb similarity index 100% rename from Task/Dragon-curve/Ada/dragon-curve-2.ada rename to Task/Dragon-curve/Ada/dragon-curve-2.adb diff --git a/Task/Dragon-curve/Ada/dragon-curve-3.ada b/Task/Dragon-curve/Ada/dragon-curve-3.adb similarity index 100% rename from Task/Dragon-curve/Ada/dragon-curve-3.ada rename to Task/Dragon-curve/Ada/dragon-curve-3.adb diff --git a/Task/Dragon-curve/Ada/dragon-curve-4.ada b/Task/Dragon-curve/Ada/dragon-curve-4.adb similarity index 100% rename from Task/Dragon-curve/Ada/dragon-curve-4.ada rename to Task/Dragon-curve/Ada/dragon-curve-4.adb diff --git a/Task/Dragon-curve/Applesoft-BASIC/dragon-curve.basic b/Task/Dragon-curve/Applesoft-BASIC/dragon-curve.basic new file mode 100644 index 0000000000..b9f8bff709 --- /dev/null +++ b/Task/Dragon-curve/Applesoft-BASIC/dragon-curve.basic @@ -0,0 +1,37 @@ +10 REM Dragon curve +20 DEF FN MOD(M) = M - INT(M / 8) * 8 +30 REM SIN, COS in arrays for PI/4 multipl. +40 DIM S(7), C(7) +50 QPI = ATN(1): SQ = SQR(2) +60 FOR I = 0 TO 7 +70 S(I) = SIN(I * QPI): C(I) = COS(I * QPI) +80 NEXT I +90 LEVEL = 15 +100 INSIZE = 128: REM 2^WHOLE_NUM (looks better) +110 X = 98: Y = 68 +120 ROTQPI = 0: RQ = 1 +130 DIM R(LEVEL) +140 HGR2: HCOLOR = 1 +150 GOSUB 170 +160 END +170 REM ** Dragon +180 ROTQPI = FN MOD8(ROTQPI) +190 IF LEVEL > 1 THEN GOTO 250 +200 YN = S(ROTQPI) * INSIZE + Y +210 XN = C(ROTQPI) * INSIZE + X +220 HPLOT X, Y TO XN, YN +230 X = XN: Y = YN +240 RETURN +250 INSIZE = INSIZE * SQ / 2 +260 ROTQPI = FN MOD8(ROTQPI + RQ) +270 LEVEL = LEVEL - 1 +280 R(LEVEL) = RQ: RQ = 1 +290 GOSUB 170 +300 ROTQPI = FN MOD8(ROTQPI - R(LEVEL) * 2) +310 RQ = -1 +320 GOSUB 170 +330 RQ = R(LEVEL) +340 ROTQPI = FN MOD8(ROTQPI + RQ) +350 LEVEL = LEVEL + 1 +360 INSIZE = INSIZE * SQ +370 RETURN diff --git a/Task/Dragon-curve/BASIC/dragon-curve.basic b/Task/Dragon-curve/BASIC/dragon-curve.basic index 249e1fcd18..7b94fc271c 100644 --- a/Task/Dragon-curve/BASIC/dragon-curve.basic +++ b/Task/Dragon-curve/BASIC/dragon-curve.basic @@ -12,11 +12,11 @@ SUB dragon (length AS Double, split AS Integer, d AS Double) IF split=0 THEN forward length ELSE - turn d*45 - dragon length/1.4142136, split-1, 1 - turn -d*90 - dragon length/1.4142136, split-1, -1 - turn d*45 + turn d*45 + dragon length/1.4142136, split-1, 1 + turn -d*90 + dragon length/1.4142136, split-1, -1 + turn d*45 END IF END SUB diff --git a/Task/Dragon-curve/BASIC256/dragon-curve.basic b/Task/Dragon-curve/BASIC256/dragon-curve.basic index 25b1b0983a..03e75f4098 100644 --- a/Task/Dragon-curve/BASIC256/dragon-curve.basic +++ b/Task/Dragon-curve/BASIC256/dragon-curve.basic @@ -2,15 +2,15 @@ graphsize 390,270 -level = 18 : insize = 247 # initial values -x = 92 : y = 94 # +level = 18 : insize = 247 # initial values +x = 92 : y = 94 # -iters = 2^level # total number of iterations -qiter = 510/iters # constant for computing colors -SQ = sqrt(2) : QPI = pi/4 # constants +iters = 2^level # total number of iterations +qiter = 510/iters # constant for computing colors +SQ = sqrt(2) : QPI = pi/4 # constants -rotation = 0 : iter = 0 : rq = 1.0 # state variables -dim rqs(level) # stack for rq (rotation coefficient) +rotation = 0 : iter = 0 : rq = 1.0 # state variables +dim rqs(level) # stack for rq (rotation coefficient) color white fastgraphics @@ -22,29 +22,29 @@ imgsave "Dragon_curve_BASIC-256.png", "PNG" end dragon: - if level<=0 then - yn = sin(rotation)*insize + y - xn = cos(rotation)*insize + x - if iter*2r += c; p->g += X; return; - case 1: p->r += X; p->g += c; return; - case 2: p->g += c; p->b += X; return; - case 3: p->g += X; p->b += c; return; - case 4: p->r += X; p->b += c; return; - default: - p->r += c; p->b += X; - } + switch((int)h) { + case 0: p->r += c; p->g += X; return; + case 1: p->r += X; p->g += c; return; + case 2: p->g += c; p->b += X; return; + case 3: p->g += X; p->b += c; return; + case 4: p->r += X; p->b += c; return; + default: + p->r += c; p->b += X; + } } /* string rewriting. No need to keep the string itself, just execute @@ -53,16 +53,16 @@ void h_rgb(long long x, long long y) */ void iter_string(const char * str, int d) { - long tmp; -# define LEFT tmp = -dy; dy = dx; dx = tmp -# define RIGHT tmp = dy; dy = -dx; dx = tmp - while (*str != '\0') { - switch(*(str++)) { - case 'X': if (d) iter_string("X+YF+", d - 1); continue; - case 'Y': if (d) iter_string("-FX-Y", d - 1); continue; - case '+': RIGHT; continue; - case '-': LEFT; continue; - case 'F': + long tmp; +# define LEFT tmp = -dy; dy = dx; dx = tmp +# define RIGHT tmp = dy; dy = -dx; dx = tmp + while (*str != '\0') { + switch(*(str++)) { + case 'X': if (d) iter_string("X+YF+", d - 1); continue; + case 'Y': if (d) iter_string("-FX-Y", d - 1); continue; + case '+': RIGHT; continue; + case '-': LEFT; continue; + case 'F': /* draw: increment path length; add color; move. Here * is why the code does not allow user to choose arbitrary * image size: if it's not a power of two, aliasing will @@ -71,59 +71,59 @@ void iter_string(const char * str, int d) * involves computing multiplicative order and would be a huge * bore. */ - clen ++; - h_rgb(x/scale, y/scale); - x += dx; y += dy; - continue; - } - } + clen ++; + h_rgb(x/scale, y/scale); + x += dx; y += dy; + continue; + } + } } void dragon(long leng, int depth) { - long i, d = leng / 3 + 1; - long h = leng + 3, w = leng + d * 3 / 2 + 2; + long i, d = leng / 3 + 1; + long h = leng + 3, w = leng + d * 3 / 2 + 2; - /* allocate pixel buffer */ - rgb *buf = malloc(sizeof(rgb) * w * h); - pix = malloc(sizeof(rgb *) * h); - for (i = 0; i < h; i++) - pix[i] = buf + w * i; - memset(buf, 0, sizeof(rgb) * w * h); + /* allocate pixel buffer */ + rgb *buf = malloc(sizeof(rgb) * w * h); + pix = malloc(sizeof(rgb *) * h); + for (i = 0; i < h; i++) + pix[i] = buf + w * i; + memset(buf, 0, sizeof(rgb) * w * h); /* init coords; scale up to desired; exec string */ - x = y = d; dx = leng; dy = 0; scale = 1; clen = 0; - for (i = 0; i < depth; i++) sc_up(); - iter_string("FX", depth); + x = y = d; dx = leng; dy = 0; scale = 1; clen = 0; + for (i = 0; i < depth; i++) sc_up(); + iter_string("FX", depth); - /* write color PNM file */ - unsigned char *fpix = malloc(w * h * 3); - double maxv = 0, *dbuf = (double*)buf; + /* write color PNM file */ + unsigned char *fpix = malloc(w * h * 3); + double maxv = 0, *dbuf = (double*)buf; /* find highest value among pixels; normalize image according * to it. Highest value would be at points most travelled, so * this ends up giving curve edge a nice fade -- it's more apparaent * if we increase iteration depth by one or two. */ - for (i = 3 * w * h - 1; i >= 0; i--) - if (dbuf[i] > maxv) maxv = dbuf[i]; - for (i = 3 * h * w - 1; i >= 0; i--) - fpix[i] = 255 * dbuf[i] / maxv; + for (i = 3 * w * h - 1; i >= 0; i--) + if (dbuf[i] > maxv) maxv = dbuf[i]; + for (i = 3 * h * w - 1; i >= 0; i--) + fpix[i] = 255 * dbuf[i] / maxv; - printf("P6\n%ld %ld\n255\n", w, h); - fflush(stdout); /* printf and fwrite may treat buffer differently */ - fwrite(fpix, h * w * 3, 1, stdout); + printf("P6\n%ld %ld\n255\n", w, h); + fflush(stdout); /* printf and fwrite may treat buffer differently */ + fwrite(fpix, h * w * 3, 1, stdout); } int main(int c, char ** v) { - int size, depth; + int size, depth; - depth = (c > 1) ? atoi(v[1]) : 10; - size = 1 << depth; + depth = (c > 1) ? atoi(v[1]) : 10; + size = 1 << depth; - fprintf(stderr, "size: %d depth: %d\n", size, depth); - dragon(size, depth * 2); + fprintf(stderr, "size: %d depth: %d\n", size, depth); + dragon(size, depth * 2); - return 0; + return 0; } diff --git a/Task/Dragon-curve/COBOL/dragon-curve.cobol b/Task/Dragon-curve/COBOL/dragon-curve.cob similarity index 100% rename from Task/Dragon-curve/COBOL/dragon-curve.cobol rename to Task/Dragon-curve/COBOL/dragon-curve.cob diff --git a/Task/Dragon-curve/Delphi/dragon-curve.delphi b/Task/Dragon-curve/Delphi/dragon-curve.pas similarity index 100% rename from Task/Dragon-curve/Delphi/dragon-curve.delphi rename to Task/Dragon-curve/Delphi/dragon-curve.pas diff --git a/Task/Dragon-curve/EasyLang/dragon-curve.easy b/Task/Dragon-curve/EasyLang/dragon-curve.easy index 81f64de949..c789f92105 100644 --- a/Task/Dragon-curve/EasyLang/dragon-curve.easy +++ b/Task/Dragon-curve/EasyLang/dragon-curve.easy @@ -1,15 +1,14 @@ -color 050 -linewidth 0.5 +gcolor 050 +glinewidth 0.5 x = 25 y = 60 -move x y angle = 0 # -proc dragon size lev d . . +proc dragon size lev d . if lev = 0 x -= cos angle * size y += sin angle * size - line x y + glineto x y else dragon size / sqrt 2 lev - 1 1 angle -= d * 90 diff --git a/Task/Dragon-curve/Emacs-Lisp/dragon-curve.l b/Task/Dragon-curve/Emacs-Lisp/dragon-curve.el similarity index 100% rename from Task/Dragon-curve/Emacs-Lisp/dragon-curve.l rename to Task/Dragon-curve/Emacs-Lisp/dragon-curve.el diff --git a/Task/Dragon-curve/Haskell/dragon-curve-2.hs b/Task/Dragon-curve/Haskell/dragon-curve-2.hs index 797d72b985..ddb5a8b72a 100644 --- a/Task/Dragon-curve/Haskell/dragon-curve-2.hs +++ b/Task/Dragon-curve/Haskell/dragon-curve-2.hs @@ -4,8 +4,8 @@ y 0 = "" y n = " - f"++(x$n-1)++" -"++(y$n-1) dragon n = - concat ["0 setlinewidth 300 400 moveto", - "/f{2 0 rlineto}def/+{90 rotate}def/-{-90 rotate}def\n", - "f", x n, " stroke showpage"] + concat ["0 setlinewidth 300 400 moveto", + "/f{2 0 rlineto}def/+{90 rotate}def/-{-90 rotate}def\n", + "f", x n, " stroke showpage"] main = putStrLn $ dragon 14 diff --git a/Task/Dragon-curve/Julia/dragon-curve.julia b/Task/Dragon-curve/Julia/dragon-curve.jl similarity index 100% rename from Task/Dragon-curve/Julia/dragon-curve.julia rename to Task/Dragon-curve/Julia/dragon-curve.jl diff --git a/Task/Dragon-curve/Kotlin/dragon-curve.kotlin b/Task/Dragon-curve/Kotlin/dragon-curve.kts similarity index 100% rename from Task/Dragon-curve/Kotlin/dragon-curve.kotlin rename to Task/Dragon-curve/Kotlin/dragon-curve.kts diff --git a/Task/Dragon-curve/Locomotive-Basic/dragon-curve.basic b/Task/Dragon-curve/Locomotive-Basic/dragon-curve.basic new file mode 100644 index 0000000000..6cf4caa101 --- /dev/null +++ b/Task/Dragon-curve/Locomotive-Basic/dragon-curve.basic @@ -0,0 +1,29 @@ +100 MODE 2 +110 DIM s(7),c(7) +120 qpi=ATN(1):sq2=SQR(2) +130 FOR i=0 TO 7 +140 s(i)=SIN(i*qpi) +150 c(i)=COS(i*qpi) +160 NEXT +170 level=11 +180 DIM r(level) +190 insize=128*2 +200 MOVE 200,150 +210 rotqpi=0:rq=1 +220 GOSUB 250 +230 END +240 ' +250 IF level=1 THEN DRAWR c(rotqpi)*insize,s(rotqpi)*insize:RETURN +260 insize=insize*sq2/2 +270 rotqpi=(rotqpi+rq) AND 7 +280 level=level-1 +290 r(level)=rq:rq=1 +300 GOSUB 250 +310 rotqpi=(rotqpi-r(level)*2) AND 7 +320 rq=-1 +330 GOSUB 250 +340 rq=r(level) +350 rotqpi=(rotqpi+rq) AND 7 +360 level=level+1 +370 insize=insize*sq2 +380 RETURN diff --git a/Task/Dragon-curve/Metafont/dragon-curve.metafont b/Task/Dragon-curve/Metafont/dragon-curve.metafont index a2061d786f..446a318703 100644 --- a/Task/Dragon-curve/Metafont/dragon-curve.metafont +++ b/Task/Dragon-curve/Metafont/dragon-curve.metafont @@ -7,10 +7,10 @@ beginchar("D", 25pt#, 25pt#, 0pt#); for i = 1 upto dragoniter: for v = 1 step mstep until (2-mstep): if unknown z[v+mstep]: - pair t; - t := .7071[ z[v], z[v+2mstep] ]; - z[v+mstep] = t rotatedaround(z[v], 45sg); - sg := -1*sg; + pair t; + t := .7071[ z[v], z[v+2mstep] ]; + z[v+mstep] = t rotatedaround(z[v], 45sg); + sg := -1*sg; fi endfor mstep := mstep/2; diff --git a/Task/Dragon-curve/Nascom-BASIC/dragon-curve.basic b/Task/Dragon-curve/Nascom-BASIC/dragon-curve.basic new file mode 100644 index 0000000000..2f42679f86 --- /dev/null +++ b/Task/Dragon-curve/Nascom-BASIC/dragon-curve.basic @@ -0,0 +1,54 @@ +10 REM Dragon curve +20 REM SIN, COS in arrays for PI/4 multipl. +30 DIM S(7), C(7) +40 QPI=ATN(1):SQ=SQR(2) +50 FOR I=0 TO 7 +60 S(I)=SIN(I*QPI):C(I)=COS(I*QPI) +70 NEXT I +80 LEVEL=15 +90 INSIZE=32:REM 2^WHOLE_NUM (looks better) +100 X=34:Y=16 +110 ROTQPI=0:RQ=1 +120 DIM R(LEVEL) +130 CLS +140 GOSUB 160 +150 END +160 REM ** Dragon +170 ROTQPI=ROTQPI AND 7 +180 IF LEVEL>1 THEN GOTO 240 +190 YN=S(ROTQPI)*INSIZE+Y +200 XN=C(ROTQPI)*INSIZE+X +210 GOSUB 370 +220 X=XN:Y=YN +230 RETURN +240 INSIZE=INSIZE*SQ/2 +250 ROTQPI=(ROTQPI+RQ)AND 7 +260 LEVEL=LEVEL-1 +270 R(LEVEL)=RQ:RQ=1 +280 GOSUB 160 +290 ROTQPI=(ROTQPI-R(LEVEL)*2)AND 7 +300 RQ=-1 +310 GOSUB 160 +320 RQ=R(LEVEL) +330 ROTQPI=(ROTQPI+RQ)AND 7 +340 LEVEL=LEVEL+1 +350 INSIZE=INSIZE*SQ +360 RETURN +370 REM ** Draw a line from (X, Y) to (XN, YN) +380 IF ABS(XN-X)>1 OR ABS(YN-Y)>1 THEN 400 +390 SET(X,Y):SET(XN,YN):RETURN +400 IF ABS(XN-X)>ABS(YN-Y) THEN 480 +410 REM More vertical line +420 A=(XN-X)/(YN-Y) +430 IF YN>Y THEN D=1 ELSE D=-1 +440 FOR YC=Y TO YN STEP D +450 SET(X+A*(YC-Y),YC) +460 NEXT YC +470 RETURN +480 REM More horizontal line +490 A=(YN-Y)/(XN-X) +500 IF XN>X THEN D=1 ELSE D=-1 +510 FOR XC=X TO XN STEP D +520 SET(XC,Y+A*(XC-X)) +530 NEXT XC +540 RETURN diff --git a/Task/Dragon-curve/OCaml/dragon-curve-1.ocaml b/Task/Dragon-curve/OCaml/dragon-curve-1.ml similarity index 100% rename from Task/Dragon-curve/OCaml/dragon-curve-1.ocaml rename to Task/Dragon-curve/OCaml/dragon-curve-1.ml diff --git a/Task/Dragon-curve/OCaml/dragon-curve-2.ocaml b/Task/Dragon-curve/OCaml/dragon-curve-2.ml similarity index 100% rename from Task/Dragon-curve/OCaml/dragon-curve-2.ocaml rename to Task/Dragon-curve/OCaml/dragon-curve-2.ml diff --git a/Task/Dragon-curve/PascalABC.NET/dragon-curve.pas b/Task/Dragon-curve/PascalABC.NET/dragon-curve.pas new file mode 100644 index 0000000000..7ac53bfab2 --- /dev/null +++ b/Task/Dragon-curve/PascalABC.NET/dragon-curve.pas @@ -0,0 +1,34 @@ +uses Turtle; + +var + Atom,FStr,XStr,YStr: string; + angle,len,x0,y0: real; + n: integer; + +procedure Init1; // Dragon +begin + (Atom,FStr,XStr,YStr) := ('fx','f','x+yf+','-fx-y'); + (angle,len,n,x0,y0) := (90,3,15,300,450); +end; + +procedure RunStr(s: string; n: integer); +begin + foreach var c in s do + case c of + '+': Turn(angle); + '-': Turn(-angle); + 'f','F': if n>0 then RunStr(FStr,n-1) else Forw(len); + 'x','X': if n>0 then RunStr(XStr,n-1); + 'y','Y': if n>0 then RunStr(YStr,n-1); + else Print('error') + end; +end; + +begin + Init1; + ToPoint(x0,y0); + SetWidth(0.5); + Down; + RunStr(Atom,n); + Up; +end. diff --git a/Task/Dragon-curve/Pluto/dragon-curve.pluto b/Task/Dragon-curve/Pluto/dragon-curve.pluto new file mode 100644 index 0000000000..52840da6b5 --- /dev/null +++ b/Task/Dragon-curve/Pluto/dragon-curve.pluto @@ -0,0 +1,43 @@ +require "bitmap" +require "table2" + +local bmp = bitmap.of(800, 600, color.black, "Dragon curve") + +local function get_sequence(iterations) + local turn_sequence = {} + for _ = 1, iterations do + local copy = {} + copy:join(turn_sequence) + if #copy > 1 then copy:reverse() end + turn_sequence:insert(1) + copy:foreach(|i| -> turn_sequence:insert(-i)) + end + return turn_sequence +end + +local function dragon(turns, starting_angle, side) + local col = pico.blue + local angle = starting_angle + local x1 = 230 + local y1 = 350 + local x2 = x1 + math.trunc(math.cos(angle) * side) + local y2 = y1 + math.trunc(math.sin(angle) * side) + bmp:line(x1, y1, x2, y2, col) + x1 = x2 + y1 = y2 + for turns as turn do + angle += turn * math.pi / 2 + x2 = x1 + math.trunc(math.cos(angle) * side) + y2 = y1 + math.trunc(math.sin(angle) * side) + bmp:line(x1, y1, x2, y2, col) + x1 = x2 + y1 = y2 + end +end + +local iter = 14 +local turns = get_sequence(iter) +local starting_angle = -iter * math.pi / 4 +local side = 400 / (2 ^ (iter / 2)) +dragon(turns, starting_angle, side) +bmp:view() diff --git a/Task/Dragon-curve/Prolog/dragon-curve.pro b/Task/Dragon-curve/Prolog/dragon-curve.pro index cca7a2d174..fa667e6ce7 100644 --- a/Task/Dragon-curve/Prolog/dragon-curve.pro +++ b/Task/Dragon-curve/Prolog/dragon-curve.pro @@ -1,60 +1,60 @@ dragonCurve(N) :- - dcg_dg(N, [left], DCL, []), - Side = 4, - Angle is -N * (pi/4), - dcg_computePath(Side, Angle, DCL, point(180,400), P, []), - new(D, window('Dragon Curve')), - send(D, size, size(800,600)), - new(Path, path(poly)), - send_list(Path, append, P), - send(D, display, Path), - send(D, open). + dcg_dg(N, [left], DCL, []), + Side = 4, + Angle is -N * (pi/4), + dcg_computePath(Side, Angle, DCL, point(180,400), P, []), + new(D, window('Dragon Curve')), + send(D, size, size(800,600)), + new(Path, path(poly)), + send_list(Path, append, P), + send(D, display, Path), + send(D, open). % compute the list of points of the Dragon Curve dcg_computePath(Side, Angle, [left | DCT], point(X1, Y1)) --> - [point(X1, Y1)], - { X2 is X1 + Side * cos(Angle), - Y2 is Y1 + Side * sin(Angle), - Angle1 is Angle + pi / 2 - }, - dcg_computePath(Side, Angle1, DCT, point(X2, Y2)). + [point(X1, Y1)], + { X2 is X1 + Side * cos(Angle), + Y2 is Y1 + Side * sin(Angle), + Angle1 is Angle + pi / 2 + }, + dcg_computePath(Side, Angle1, DCT, point(X2, Y2)). dcg_computePath(Side, Angle, [right | DCT], point(X1, Y1)) --> - [point(X1, Y1)], - { X2 is X1 + Side * cos(Angle), - Y2 is Y1 + Side * sin(Angle), - Angle1 is Angle - pi / 2 - }, - dcg_computePath(Side, Angle1, DCT, point(X2, Y2)). + [point(X1, Y1)], + { X2 is X1 + Side * cos(Angle), + Y2 is Y1 + Side * sin(Angle), + Angle1 is Angle - pi / 2 + }, + dcg_computePath(Side, Angle1, DCT, point(X2, Y2)). dcg_computePath(_Side, _Angle, [], point(X1, Y1)) --> - [ point(X1, Y1)]. + [ point(X1, Y1)]. % compute the list of the "turns" of the Dragon Curve dcg_dg(1, L) --> L. dcg_dg(N, L) --> - {dcg_dg(L, L1, []), - N1 is N - 1}, - dcg_dg(N1, L1). + {dcg_dg(L, L1, []), + N1 is N - 1}, + dcg_dg(N1, L1). % one interation of the process dcg_dg(L) --> - L, - [left], - inverse(L). + L, + [left], + inverse(L). inverse([H | T]) --> - inverse(T), - inverse(H). + inverse(T), + inverse(H). inverse([]) --> []. inverse(left) --> - [right]. + [right]. inverse(right) --> - [left]. + [left]. diff --git a/Task/Dragon-curve/Raku/dragon-curve.raku b/Task/Dragon-curve/Raku/dragon-curve.raku index 65d40f60b8..09ffdd7994 100644 --- a/Task/Dragon-curve/Raku/dragon-curve.raku +++ b/Task/Dragon-curve/Raku/dragon-curve.raku @@ -3,7 +3,7 @@ use SVG; role Lindenmayer { has %.rules; method succ { - self.comb.map( { %!rules{$^c} // $c } ).join but Lindenmayer(%!rules) + self.comb.map( { %!rules{$^c} // $c } ).join but Lindenmayer(%!rules) } } diff --git a/Task/Dragon-curve/Rebol/dragon-curve.rebol b/Task/Dragon-curve/Rebol/dragon-curve.rebol new file mode 100644 index 0000000000..43e3817fca --- /dev/null +++ b/Task/Dragon-curve/Rebol/dragon-curve.rebol @@ -0,0 +1,67 @@ +Rebol [ + title: "Rosetta code: Dragon curve" + file: %Dragon_curve.r3 + url: https://rosettacode.org/wiki/Dragon_curve + needs: 3.0.0 +] + +bit-count: function [n [integer!]] [ + count: 0 + while [n > 0] [ + count: count + (n & 1) ;; add lowest bit + n: n >> 1 ;; logical right-shift by 1 + ] + count +] + +dragon-curve: function [steps [integer!]][ + ;; Initialize state + x: y: minx: maxx: miny: maxy: 0 + data: make map! [] + + ;; Loop for each step + for i 0 steps 1 [ + ;; Convert iteration number to direction using Gray code modulo 4 + dir: (bit-count (i xor (i >> 1))) % 4 + + ;; Compute next coordinates + nx: x + pickz [1 0 -1 0] dir + ny: y + pickz [0 1 0 -1] dir + + ;; Determine outbound/inbound bits + set [ob: ib:] pickz [[8 4] [2 1] [4 8] [1 2]] dir + + ;; Update cell at current position + key-cur: as-pair y x + data/:key-cur: ob or any [data/:key-cur 0] + + ;; Update cell at next position + key-nxt: as-pair ny nx + data/:key-nxt: ib or any [data/:key-nxt 0] + + ;; Update bounding box + minx: min minx nx + maxx: max maxx nx + miny: min miny ny + maxy: max maxy ny + + ;; Advance position + x: nx + y: ny + ] + + ;; Draw the result + chars: " ╵╷│╴┘┐┤╶└┌├─┴┬┼" + for y miny maxy 1 [ + line: clear "" + for x minx maxx 1 [ + key: as-pair y x + val: 1 + any [data/:key 0] + append line chars/:val + ] + print line + ] +] + +;; Draw result: +dragon-curve 511 diff --git a/Task/Dragon-curve/Rust/dragon-curve.rust b/Task/Dragon-curve/Rust/dragon-curve.rs similarity index 100% rename from Task/Dragon-curve/Rust/dragon-curve.rust rename to Task/Dragon-curve/Rust/dragon-curve.rs diff --git a/Task/Dragon-curve/SequenceL/dragon-curve-1.sequencel b/Task/Dragon-curve/SequenceL/dragon-curve-1.sequencel index fe187b5084..e1905a0651 100644 --- a/Task/Dragon-curve/SequenceL/dragon-curve-1.sequencel +++ b/Task/Dragon-curve/SequenceL/dragon-curve-1.sequencel @@ -4,35 +4,35 @@ import ; initPoints := [[0,0],[1,0]]; f1(point(1)) := - let - matrix := [[cos(45 * (pi/180)), -sin(45 * (pi/180))], - [sin(45 * (pi/180)), cos(45 * (pi/180))]]; - in - head(transpose((1/sqrt(2)) * matmul(matrix, transpose([point])))); - + let + matrix := [[cos(45 * (pi/180)), -sin(45 * (pi/180))], + [sin(45 * (pi/180)), cos(45 * (pi/180))]]; + in + head(transpose((1/sqrt(2)) * matmul(matrix, transpose([point])))); + f2(point(1)) := - let - matrix := [[cos(135 * (pi/180)), -sin(135 * (pi/180))], - [sin(135 * (pi/180)), cos(135 * (pi/180))]]; - in - head(transpose((1/sqrt(2)) * matmul(matrix, transpose([point])))) + initPoints[2]; + let + matrix := [[cos(135 * (pi/180)), -sin(135 * (pi/180))], + [sin(135 * (pi/180)), cos(135 * (pi/180))]]; + in + head(transpose((1/sqrt(2)) * matmul(matrix, transpose([point])))) + initPoints[2]; matmul(X(2),Y(2))[i,j] := sum(X[i,all]*Y[all,j]); entry(steps(0), maxX(0), maxY(0)) := - let - scaleX := maxX / 1.5; - scaleY := maxY; - - shiftX := maxX / 3.0 / 1.5; - shiftY := maxY / 3.0; - in - round(run(steps, initPoints) * [scaleX, scaleY] + [shiftX, shiftY]); + let + scaleX := maxX / 1.5; + scaleY := maxY; + + shiftX := maxX / 3.0 / 1.5; + shiftY := maxY / 3.0; + in + round(run(steps, initPoints) * [scaleX, scaleY] + [shiftX, shiftY]); run(steps(0), result(2)) := - let - next := f1(result) ++ f2(result); - in - result when steps <= 0 - else - run(steps - 1, next); + let + next := f1(result) ++ f2(result); + in + result when steps <= 0 + else + run(steps - 1, next); diff --git a/Task/Dragon-curve/SequenceL/dragon-curve-2.sequencel b/Task/Dragon-curve/SequenceL/dragon-curve-2.sequencel index f60e233fdc..aa6cb2eec4 100644 --- a/Task/Dragon-curve/SequenceL/dragon-curve-2.sequencel +++ b/Task/Dragon-curve/SequenceL/dragon-curve-2.sequencel @@ -9,66 +9,66 @@ using namespace std; int main(int argc, char** argv) { - int threads = 0; - if(argc > 1) threads = atoi(argv[1]); - Sequence< Sequence > result; + int threads = 0; + if(argc > 1) threads = atoi(argv[1]); + Sequence< Sequence > result; - sl_init(threads); + sl_init(threads); - int width = 500; - if(argc > 2) width = atoi(argv[2]); - int height = width; - if(argc > 3) height = atoi(argv[3]); + int width = 500; + if(argc > 2) width = atoi(argv[2]); + int height = width; + if(argc > 3) height = atoi(argv[3]); - CImg visu(width, height, 1, 3, 0); - CImgDisplay draw_disp(visu); + CImg visu(width, height, 1, 3, 0); + CImgDisplay draw_disp(visu); - SLTimer compTimer; - SLTimer drawTimer; + SLTimer compTimer; + SLTimer drawTimer; - int steps = 0; - int maxSteps = 18; - if(argc > 4) maxSteps = atoi(argv[4]); - int waitTime = 200; - if(argc > 5) waitTime = atoi(argv[5]); - bool adding = true; - while(!draw_disp.is_closed()) - { - compTimer.start(); - sl_entry(steps, width, height, threads, result); - compTimer.stop(); + int steps = 0; + int maxSteps = 18; + if(argc > 4) maxSteps = atoi(argv[4]); + int waitTime = 200; + if(argc > 5) waitTime = atoi(argv[5]); + bool adding = true; + while(!draw_disp.is_closed()) + { + compTimer.start(); + sl_entry(steps, width, height, threads, result); + compTimer.stop(); - drawTimer.start(); - visu.fill(0); + drawTimer.start(); + visu.fill(0); - double thirdSize = ((result.size() / 2.0) / 3.0); - thirdSize = (int)thirdSize == 0 ? 1 : thirdSize; + double thirdSize = ((result.size() / 2.0) / 3.0); + thirdSize = (int)thirdSize == 0 ? 1 : thirdSize; - for(int i = 1; i <= result.size(); i+=2) - { - unsigned char shade = (unsigned char)(255 * ((((i / 2) % (int)thirdSize) / thirdSize)) + 0.5); + for(int i = 1; i <= result.size(); i+=2) + { + unsigned char shade = (unsigned char)(255 * ((((i / 2) % (int)thirdSize) / thirdSize)) + 0.5); - unsigned char r = i / 2 <= thirdSize ? shade : 255/2; - unsigned char g = thirdSize < i / 2 && i / 2 <= thirdSize * 2 ? shade : 255/2; - unsigned char b = thirdSize * 2 < i / 2 && i / 2 <= thirdSize * 3 ? shade : 255/2; - const unsigned char color[] = {r,g,b}; + unsigned char r = i / 2 <= thirdSize ? shade : 255/2; + unsigned char g = thirdSize < i / 2 && i / 2 <= thirdSize * 2 ? shade : 255/2; + unsigned char b = thirdSize * 2 < i / 2 && i / 2 <= thirdSize * 3 ? shade : 255/2; + const unsigned char color[] = {r,g,b}; - visu.draw_line(result[i][1], result[i][2], 0, result[i + 1][1], result[i + 1][2], 0, color); - } - visu.display(draw_disp); - drawTimer.stop(); + visu.draw_line(result[i][1], result[i][2], 0, result[i + 1][1], result[i + 1][2], 0, color); + } + visu.display(draw_disp); + drawTimer.stop(); - draw_disp.set_title("Dragon Curve in SequenceL: %d Threads | Steps: %d | CompTime: %f Seconds | Draw Time: %f Seconds", threads, steps, drawTimer.getTime(), compTimer.getTime()); + draw_disp.set_title("Dragon Curve in SequenceL: %d Threads | Steps: %d | CompTime: %f Seconds | Draw Time: %f Seconds", threads, steps, drawTimer.getTime(), compTimer.getTime()); - if(adding) steps++; - else steps--; + if(adding) steps++; + else steps--; - if(steps <= 0) adding = true; - else if(steps >= maxSteps) adding = false; + if(steps <= 0) adding = true; + else if(steps >= maxSteps) adding = false; - draw_disp.wait(waitTime); - } + draw_disp.wait(waitTime); + } - sl_done(); - return 0; + sl_done(); + return 0; } diff --git a/Task/Dragon-curve/Tcl/dragon-curve.tcl b/Task/Dragon-curve/Tcl/dragon-curve.tcl index 1dcd79c6ad..e662357b4b 100644 --- a/Task/Dragon-curve/Tcl/dragon-curve.tcl +++ b/Task/Dragon-curve/Tcl/dragon-curve.tcl @@ -15,14 +15,14 @@ proc forward {len} { proc dragon {len split {d 1}} { global r2 coords if {$split == 0} { - forward $len - return + forward $len + return } # This next part is only necessary to allow the illustration of progress if {$split == 10 && [llength $::coords]>2} { - .c coords dragon $::coords - update + .c coords dragon $::coords + update } incr split -1 diff --git a/Task/Dragon-curve/V-(Vlang)/dragon-curve.v b/Task/Dragon-curve/V-(Vlang)/dragon-curve.v new file mode 100644 index 0000000000..eeb9bfa2ce --- /dev/null +++ b/Task/Dragon-curve/V-(Vlang)/dragon-curve.v @@ -0,0 +1,78 @@ +import gg +import gx +import math + +struct App { + mut: + iter int + turns []int + start_angle f64 + side f64 + angle f64 + x1 int + y1 int + x2 int + y2 int + col gx.Color + ctx gg.Context +} + +fn get_sequence(iterations int) []int { + mut turn_sequence := []int{} + for _ in 0 .. iterations { + mut copy := turn_sequence.clone() + if copy.len > 1 { copy = copy.reverse() } + turn_sequence << 1 + for i in copy { + turn_sequence << -i + } + } + return turn_sequence +} + +fn (mut app App) dragon() { + app.angle = app.start_angle + app.x1 = 230 + app.y1 = 350 + app.x2 = app.x1 + int(math.cos(app.angle) * app.side) + app.y2 = app.y1 + int(math.sin(app.angle) * app.side) + app.ctx.draw_line(app.x1, app.y1, app.x2, app.y2, app.col) + app.x1 = app.x2 + app.y1 = app.y2 + for turn in app.turns { + app.angle += f64(turn) * math.pi / 2 + app.x2 = app.x1 + int(math.cos(app.angle) * app.side) + app.y2 = app.y1 + int(math.sin(app.angle) * app.side) + app.ctx.draw_line(app.x1, app.y1, app.x2, app.y2, app.col) + app.x1 = app.x2 + app.y1 = app.y2 + } +} + +fn (mut app App) init() { + app.iter = 14 + app.turns = get_sequence(app.iter) + app.start_angle = -f64(app.iter) * math.pi / 4 + app.side = 400.0 / math.pow(2, f64(app.iter) / 2) + app.col = gx.blue +} + +fn frame(mut app App) { + app.ctx.begin() + app.dragon() + app.ctx.end() +} + +fn main() { + mut app := App{} + mut context := gg.new_context( + width: 800 + height: 600 + window_title: 'Dragon curve' + user_data: &app + frame_fn: frame + bg_color: gx.white + ) + app.init() + context.run() +} diff --git a/Task/Dragon-curve/VBScript/dragon-curve.vb b/Task/Dragon-curve/VBScript/dragon-curve.vbs similarity index 100% rename from Task/Dragon-curve/VBScript/dragon-curve.vb rename to Task/Dragon-curve/VBScript/dragon-curve.vbs diff --git a/Task/Dragon-curve/Vedit-macro-language/dragon-curve.vedit b/Task/Dragon-curve/Vedit-macro-language/dragon-curve.vedit index 45025fd0ee..f8755cfac0 100644 --- a/Task/Dragon-curve/Vedit-macro-language/dragon-curve.vedit +++ b/Task/Dragon-curve/Vedit-macro-language/dragon-curve.vedit @@ -1,16 +1,16 @@ File_Open("|(USER_MACRO)\dragon.bmp", OVERWRITE+NOEVENT) BOF Del_Char(ALL) -#11 = 640 // width of the image -#12 = 480 // height of the image +#11 = 640 // width of the image +#12 = 480 // height of the image Call("CREATE_BMP") -#1 = 384 // dx -#2 = 0 // dy -#3 = 6 // depth of recursion -#4 = 1 // flip -#5 = 150 // x -#6 = 300 // y +#1 = 384 // dx +#2 = 0 // dy +#3 = 6 // depth of recursion +#4 = 1 // flip +#5 = 150 // x +#6 = 300 // y Call("DRAGON") Buf_Close(NOMSG) @@ -29,15 +29,15 @@ if (#3 == 0) { #2 /= 2 #3-- if (#4) { - Num_Push(1,4) #4=1; #7=#1; #1=#2; #2=-#7; Call("DRAGON") Num_Pop(1,4) - Num_Push(1,4) #4=0; Call("DRAGON") Num_Pop(1,4) - Num_Push(1,4) #4=1; #7=#1; #1=-#2; #2=#7; Call("DRAGON") Num_Pop(1,4) - Num_Push(1,4) #4=0; Call("DRAGON") Num_Pop(1,4) + Num_Push(1,4) #4=1; #7=#1; #1=#2; #2=-#7; Call("DRAGON") Num_Pop(1,4) + Num_Push(1,4) #4=0; Call("DRAGON") Num_Pop(1,4) + Num_Push(1,4) #4=1; #7=#1; #1=-#2; #2=#7; Call("DRAGON") Num_Pop(1,4) + Num_Push(1,4) #4=0; Call("DRAGON") Num_Pop(1,4) } else { - Num_Push(1,4) #4=1; Call("DRAGON") Num_Pop(1,4) - Num_Push(1,4) #4=0; #7=#1; #1=-#2; #2=#7; Call("DRAGON") Num_Pop(1,4) - Num_Push(1,4) #4=1; Call("DRAGON") Num_Pop(1,4) - Num_Push(1,4) #4=0; #7=#1; #1=#2; #2=-#7; Call("DRAGON") Num_Pop(1,4) + Num_Push(1,4) #4=1; Call("DRAGON") Num_Pop(1,4) + Num_Push(1,4) #4=0; #7=#1; #1=-#2; #2=#7; Call("DRAGON") Num_Pop(1,4) + Num_Push(1,4) #4=1; Call("DRAGON") Num_Pop(1,4) + Num_Push(1,4) #4=0; #7=#1; #1=#2; #2=-#7; Call("DRAGON") Num_Pop(1,4) } } return @@ -53,7 +53,7 @@ while (#1 || #2 ) { #5 += #21; #1 -= #21 #6 += #22; #2 -= #22 Goto_Pos(1078 + #5 + #6*#11) - IC(255, OVERWRITE) // plot a pixel + IC(255, OVERWRITE) // plot a pixel } return @@ -64,19 +64,19 @@ return :CREATE_BMP: // BITMAPFILEHEADER: -IT("BM") // bfType -#10 = 1078+#11*#12 // file size +IT("BM") // bfType +#10 = 1078+#11*#12 // file size Call("INS_4BYTES") -IC(0, COUNT, 4) // reserved -#10 = 1078; Call("INS_4BYTES") // offset to bitmap data +IC(0, COUNT, 4) // reserved +#10 = 1078; Call("INS_4BYTES") // offset to bitmap data // BITMAPINFOHEADER: -#10 = 40; Call("INS_4BYTES") // size of BITMAPINFOHEADER -#10 = #11; Call("INS_4BYTES") // width of image -#10 = #12; Call("INS_4BYTES") // height of image -IC(1) IC(0) // number of bitplanes = 1 -IC(8) IC(0) // bits/pixel = 8 -IC(0, COUNT, 24) // compression, number of colors etc. +#10 = 40; Call("INS_4BYTES") // size of BITMAPINFOHEADER +#10 = #11; Call("INS_4BYTES") // width of image +#10 = #12; Call("INS_4BYTES") // height of image +IC(1) IC(0) // number of bitplanes = 1 +IC(8) IC(0) // bits/pixel = 8 +IC(0, COUNT, 24) // compression, number of colors etc. // Color table - create greyscale palette for (#1 = 0; #1 < 256; #1++) { @@ -96,5 +96,5 @@ return for (#1 = 0; #1 < 4; #1++) { Ins_Char(#10 & 0xff) #10 = #10 >> 8 -} +} return diff --git a/Task/Dragon-curve/YAMLScript/dragon-curve.ys b/Task/Dragon-curve/YAMLScript/dragon-curve.ys new file mode 100644 index 0000000000..a2d4b04861 --- /dev/null +++ b/Task/Dragon-curve/YAMLScript/dragon-curve.ys @@ -0,0 +1,29 @@ +!YS-v0 + +defn main(steps=511): + data [minx maxx miny maxy] =: + loop i 0 [x y], [0 0], data {}, [minx maxx miny maxy] [0 0 0 0]: + dir =: i-to-dir(i) + nx ny =: + + [(x + condp(== dir 0 1 2 -1 0)) + (y + condp(== dir 1 1 3 -1 0))] + ob ib =: dir.nth([[8 4][2 1][4 8][1 2]]) + data =: update-in(data [y x] safe-bit-or ob) + .update-in([ny nx] safe-bit-or ib) + bbox =: + + [min(minx nx) max(maxx nx) + min(miny ny) max(maxy ny)] + if i < steps: + recur: i.++, [nx ny], data, bbox + vector: data bbox + + each y (miny .. maxy): + say: !:join + each x (minx .. maxx): + get-in(data [y x] 0).nth(" ╵╷│╴┘┐┤╶└┌├─┴┬┼") + +defn i-to-dir(n): + n.bit-xor(bit-shift-right(n 1)):Long/bitCount % 4 + +defn safe-bit-or(v bit): + (v || 0).bit-or(bit) diff --git a/Task/Dragon-curve/Yabasic/dragon-curve-1.basic b/Task/Dragon-curve/Yabasic/dragon-curve-1.basic index 1d6082d45d..9d47421a36 100644 --- a/Task/Dragon-curve/Yabasic/dragon-curve-1.basic +++ b/Task/Dragon-curve/Yabasic/dragon-curve-1.basic @@ -15,30 +15,30 @@ clear window dragon() sub dragon() - if level<=0 then - yn = sin(rotation)*insize + y - xn = cos(rotation)*insize + x - if iter*20 THEN 230 +210 PLOT XC,YC:DRAWTO HX,HY +220 PLOT XC,YC:DRAWTO MX,MY +230 PLOT XC,YC:DRAWTO SX,SY +240 GOSUB 500 +250 COLOR 2 +260 PLOT XC,YC:DRAWTO HX,HY +270 PLOT XC,YC:DRAWTO MX,MY +280 COLOR 1 +290 PLOT XC,YC:DRAWTO SX,SY +300 JIFFIES=256*PEEK(19)+PEEK(20) +310 NSEC=INT(JIFFIES/FPS):IF NSEC=60 THEN GOSUB 400:GOTO 100 +320 IF NSEC>SS THEN SS=NSEC:GOTO 2OO +330 GOTO 300 +400 REM INCREASE MINUTE AND HOUR +410 MM=MM+1 +420 IF MM=60 THEN MM=0:HH=HH+1 +430 IF HH=24 THEN HH=0 +440 REM DISABLE SCREEN SAVER/ATTRACT MODE +450 POKE 77,0 +460 RETURN +500 IF SS>0 THEN 550:REM CALCULATE X AND Y POSITIONS OF HANDS +510 HX=XC+R*SIN(30*HH+MM/2)*0.5 +520 HY=YC-R*COS(30*HH+MM/2)*0.5 +530 MX=XC+R*SIN(6*MM) +540 MY=YC-R*COS(6*MM) +550 SX=XC+R*SIN(6*SS) +560 SY=YC-R*COS(6*SS) +570 RETURN +800 REM DRAW CLOCK FACE +810 COLOR 3 +820 FOR I=30 TO 360 STEP 30 +830 PLOT XC+RF*SIN(I),YC-RF*COS(I) +840 NEXT I +850 RETURN diff --git a/Task/Draw-a-clock/Batch-File/draw-a-clock.bat b/Task/Draw-a-clock/Batch-File/draw-a-clock.bat index 42149ed54e..ae8d23ce99 100644 --- a/Task/Draw-a-clock/Batch-File/draw-a-clock.bat +++ b/Task/Draw-a-clock/Batch-File/draw-a-clock.bat @@ -7,7 +7,7 @@ title Sample Batch Clock setlocal enabledelayedexpansion chcp 65001 - ::Set the characters... + ::Set the characters... set "#0_1=█████" set "#0_2=█ █" set "#0_3=█ █" @@ -75,26 +75,26 @@ set "#C_4=█" set "#C_5= " :clock_loop - ::Clear display [leaving a whitespace]... + ::Clear display [leaving a whitespace]... for /l %%C in (1,1,5) do set "display%%C= " - ::Get current time [all spaces will be replaced to zero]... - ::Also, all colons will be replaced to "C" because colon has a function in variables... + ::Get current time [all spaces will be replaced to zero]... + ::Also, all colons will be replaced to "C" because colon has a function in variables... set "curr_time=%time: =0%" set "curr_time=%curr_time::=C%" - ::Process the numbers to display [we will now use the formats we SET above]... + ::Process the numbers to display [we will now use the formats we SET above]... for /l %%T in (0,1,7) do ( - ::Check for each number and colons... - for %%N in (0 1 2 3 4 5 6 7 8 9 C) do ( - if "!curr_time:~%%T,1!"=="%%N" ( - ::Now, barbeque each formatted char in 5 rows... - for /l %%D in (1,1,5) do set "display%%D=!display%%D!!#%%N_%%D! " - ) - ) + ::Check for each number and colons... + for %%N in (0 1 2 3 4 5 6 7 8 9 C) do ( + if "!curr_time:~%%T,1!"=="%%N" ( + ::Now, barbeque each formatted char in 5 rows... + for /l %%D in (1,1,5) do set "display%%D=!display%%D!!#%%N_%%D! " + ) + ) ) - ::Refresh the clock... + ::Refresh the clock... cls echo. echo.[%display1%] diff --git a/Task/Draw-a-clock/C++/draw-a-clock.cpp b/Task/Draw-a-clock/C++/draw-a-clock.cpp index 95f8885642..176b1c771b 100644 --- a/Task/Draw-a-clock/C++/draw-a-clock.cpp +++ b/Task/Draw-a-clock/C++/draw-a-clock.cpp @@ -19,15 +19,15 @@ public: void set( int a, int b ) { x = a; y = b; } void rotate( float angle_r ) { - float _x = static_cast( x ), - _y = static_cast( y ), - s = sinf( angle_r ), - c = cosf( angle_r ), - a = _x * c - _y * s, - b = _x * s + _y * c; + float _x = static_cast( x ), + _y = static_cast( y ), + s = sinf( angle_r ), + c = cosf( angle_r ), + a = _x * c - _y * s, + b = _x * s + _y * c; - x = static_cast( a ); - y = static_cast( b ); + x = static_cast( a ); + y = static_cast( b ); } int x, y; }; @@ -38,94 +38,94 @@ public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { - DeleteObject( pen ); - DeleteObject( brush ); - DeleteDC( hdc ); - DeleteObject( bmp ); + DeleteObject( pen ); + DeleteObject( brush ); + DeleteDC( hdc ); + DeleteObject( bmp ); } bool create( int w, int h ) { - BITMAPINFO bi; - ZeroMemory( &bi, sizeof( bi ) ); - bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); - bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; - bi.bmiHeader.biCompression = BI_RGB; - bi.bmiHeader.biPlanes = 1; - bi.bmiHeader.biWidth = w; - bi.bmiHeader.biHeight = -h; + BITMAPINFO bi; + ZeroMemory( &bi, sizeof( bi ) ); + bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); + bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; + bi.bmiHeader.biCompression = BI_RGB; + bi.bmiHeader.biPlanes = 1; + bi.bmiHeader.biWidth = w; + bi.bmiHeader.biHeight = -h; - HDC dc = GetDC( GetConsoleWindow() ); - bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); - if( !bmp ) return false; + HDC dc = GetDC( GetConsoleWindow() ); + bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); + if( !bmp ) return false; - hdc = CreateCompatibleDC( dc ); - SelectObject( hdc, bmp ); - ReleaseDC( GetConsoleWindow(), dc ); + hdc = CreateCompatibleDC( dc ); + SelectObject( hdc, bmp ); + ReleaseDC( GetConsoleWindow(), dc ); - width = w; height = h; - return true; + width = w; height = h; + return true; } void clear( BYTE clr = 0 ) { - memset( pBits, clr, width * height * sizeof( DWORD ) ); + memset( pBits, clr, width * height * sizeof( DWORD ) ); } void setBrushColor( DWORD bClr ) { - if( brush ) DeleteObject( brush ); - brush = CreateSolidBrush( bClr ); - SelectObject( hdc, brush ); + if( brush ) DeleteObject( brush ); + brush = CreateSolidBrush( bClr ); + SelectObject( hdc, brush ); } void setPenColor( DWORD c ) { - clr = c; - createPen(); + clr = c; + createPen(); } void setPenWidth( int w ) { - wid = w; - createPen(); + wid = w; + createPen(); } void saveBitmap( string path ) { - BITMAPFILEHEADER fileheader; - BITMAPINFO infoheader; - BITMAP bitmap; - DWORD wb; + BITMAPFILEHEADER fileheader; + BITMAPINFO infoheader; + BITMAP bitmap; + DWORD wb; + + GetObject( bmp, sizeof( bitmap ), &bitmap ); + DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; - GetObject( bmp, sizeof( bitmap ), &bitmap ); - DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; - ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); - ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); - ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) ); + ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); + ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) ); - infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; - infoheader.bmiHeader.biCompression = BI_RGB; - infoheader.bmiHeader.biPlanes = 1; - infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); - infoheader.bmiHeader.biHeight = bitmap.bmHeight; - infoheader.bmiHeader.biWidth = bitmap.bmWidth; - infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ); + infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; + infoheader.bmiHeader.biCompression = BI_RGB; + infoheader.bmiHeader.biPlanes = 1; + infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); + infoheader.bmiHeader.biHeight = bitmap.bmHeight; + infoheader.bmiHeader.biWidth = bitmap.bmWidth; + infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ); - fileheader.bfType = 0x4D42; - fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); - fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; + fileheader.bfType = 0x4D42; + fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); + fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; - GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS ); + GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS ); - HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); - WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); - WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); - WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); - CloseHandle( file ); + HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); + WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); + WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); + WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); + CloseHandle( file ); - delete [] dwpBits; + delete [] dwpBits; } HDC getDC() const { return hdc; } @@ -135,9 +135,9 @@ public: private: void createPen() { - if( pen ) DeleteObject( pen ); - pen = CreatePen( PS_SOLID, wid, clr ); - SelectObject( hdc, pen ); + if( pen ) DeleteObject( pen ); + pen = CreatePen( PS_SOLID, wid, clr ); + SelectObject( hdc, pen ); } HBITMAP bmp; @@ -154,16 +154,16 @@ class clock public: clock() { - _bmp.create( BMP_SIZE, BMP_SIZE ); - _bmp.clear( 100 ); - _bmp.setPenWidth( 2 ); - _ang = DegToRadian( 6 ); + _bmp.create( BMP_SIZE, BMP_SIZE ); + _bmp.clear( 100 ); + _bmp.setPenWidth( 2 ); + _ang = DegToRadian( 6 ); } - + void setNow() { - GetLocalTime( &_sysTime ); - draw(); + GetLocalTime( &_sysTime ); + draw(); } float DegToRadian( float degree ) { return degree * ( PI / 180.0f ); } @@ -173,70 +173,70 @@ public: private: void drawTicks( HDC dc ) { - vector2 line; - _bmp.setPenWidth( 1 ); - for( int x = 0; x < 60; x++ ) - { - line.set( 0, 50 ); - line.rotate( static_cast( x + 30 ) * _ang ); - MoveToEx( dc, CENTER - static_cast( 2.5f * static_cast( line.x ) ), CENTER - static_cast( 2.5f * static_cast( line.y ) ), NULL ); - LineTo( dc, CENTER - static_cast( 2.81f * static_cast( line.x ) ), CENTER - static_cast( 2.81f * static_cast( line.y ) ) ); - } + vector2 line; + _bmp.setPenWidth( 1 ); + for( int x = 0; x < 60; x++ ) + { + line.set( 0, 50 ); + line.rotate( static_cast( x + 30 ) * _ang ); + MoveToEx( dc, CENTER - static_cast( 2.5f * static_cast( line.x ) ), CENTER - static_cast( 2.5f * static_cast( line.y ) ), NULL ); + LineTo( dc, CENTER - static_cast( 2.81f * static_cast( line.x ) ), CENTER - static_cast( 2.81f * static_cast( line.y ) ) ); + } - _bmp.setPenWidth( 3 ); - for( int x = 0; x < 60; x += 5 ) - { - line.set( 0, 50 ); - line.rotate( static_cast( x + 30 ) * _ang ); - MoveToEx( dc, CENTER - static_cast( 2.5f * static_cast( line.x ) ), CENTER - static_cast( 2.5f * static_cast( line.y ) ), NULL ); - LineTo( dc, CENTER - static_cast( 2.81f * static_cast( line.x ) ), CENTER - static_cast( 2.81f * static_cast( line.y ) ) ); - } + _bmp.setPenWidth( 3 ); + for( int x = 0; x < 60; x += 5 ) + { + line.set( 0, 50 ); + line.rotate( static_cast( x + 30 ) * _ang ); + MoveToEx( dc, CENTER - static_cast( 2.5f * static_cast( line.x ) ), CENTER - static_cast( 2.5f * static_cast( line.y ) ), NULL ); + LineTo( dc, CENTER - static_cast( 2.81f * static_cast( line.x ) ), CENTER - static_cast( 2.81f * static_cast( line.y ) ) ); + } } void drawHands( HDC dc ) { - float hp = DegToRadian( ( 30.0f * static_cast( _sysTime.wMinute ) ) / 60.0f ); - int h = ( _sysTime.wHour > 12 ? _sysTime.wHour - 12 : _sysTime.wHour ) * 5; - - _bmp.setPenWidth( 3 ); - _bmp.setPenColor( RGB( 0, 0, 255 ) ); - drawHand( dc, HOUR_LEN, ( _ang * static_cast( 30 + h ) ) + hp ); + float hp = DegToRadian( ( 30.0f * static_cast( _sysTime.wMinute ) ) / 60.0f ); + int h = ( _sysTime.wHour > 12 ? _sysTime.wHour - 12 : _sysTime.wHour ) * 5; - _bmp.setPenColor( RGB( 0, 128, 0 ) ); - drawHand( dc, MIN_LEN, _ang * static_cast( 30 + _sysTime.wMinute ) ); + _bmp.setPenWidth( 3 ); + _bmp.setPenColor( RGB( 0, 0, 255 ) ); + drawHand( dc, HOUR_LEN, ( _ang * static_cast( 30 + h ) ) + hp ); - _bmp.setPenWidth( 2 ); - _bmp.setPenColor( RGB( 255, 0, 0 ) ); - drawHand( dc, SEC_LEN, _ang * static_cast( 30 + _sysTime.wSecond ) ); + _bmp.setPenColor( RGB( 0, 128, 0 ) ); + drawHand( dc, MIN_LEN, _ang * static_cast( 30 + _sysTime.wMinute ) ); + + _bmp.setPenWidth( 2 ); + _bmp.setPenColor( RGB( 255, 0, 0 ) ); + drawHand( dc, SEC_LEN, _ang * static_cast( 30 + _sysTime.wSecond ) ); } void drawHand( HDC dc, int len, float ang ) { - vector2 line; - line.set( 0, len ); - line.rotate( ang ); - MoveToEx( dc, CENTER, CENTER, NULL ); - LineTo( dc, line.x + CENTER, line.y + CENTER ); + vector2 line; + line.set( 0, len ); + line.rotate( ang ); + MoveToEx( dc, CENTER, CENTER, NULL ); + LineTo( dc, line.x + CENTER, line.y + CENTER ); } void draw() { - HDC dc = _bmp.getDC(); + HDC dc = _bmp.getDC(); - _bmp.setBrushColor( RGB( 250, 250, 250 ) ); - Ellipse( dc, 0, 0, BMP_SIZE, BMP_SIZE ); - _bmp.setBrushColor( RGB( 230, 230, 230 ) ); - Ellipse( dc, 10, 10, BMP_SIZE - 10, BMP_SIZE - 10 ); + _bmp.setBrushColor( RGB( 250, 250, 250 ) ); + Ellipse( dc, 0, 0, BMP_SIZE, BMP_SIZE ); + _bmp.setBrushColor( RGB( 230, 230, 230 ) ); + Ellipse( dc, 10, 10, BMP_SIZE - 10, BMP_SIZE - 10 ); - drawTicks( dc ); - drawHands( dc ); + drawTicks( dc ); + drawHands( dc ); - _bmp.setPenColor( 0 ); _bmp.setBrushColor( 0 ); - Ellipse( dc, CENTER - 5, CENTER - 5, CENTER + 5, CENTER + 5 ); + _bmp.setPenColor( 0 ); _bmp.setBrushColor( 0 ); + Ellipse( dc, CENTER - 5, CENTER - 5, CENTER + 5, CENTER + 5 ); - _wdc = GetDC( _hwnd ); - BitBlt( _wdc, 0, 0, BMP_SIZE, BMP_SIZE, dc, 0, 0, SRCCOPY ); - ReleaseDC( _hwnd, _wdc ); + _wdc = GetDC( _hwnd ); + BitBlt( _wdc, 0, 0, BMP_SIZE, BMP_SIZE, dc, 0, 0, SRCCOPY ); + ReleaseDC( _hwnd, _wdc ); } myBitmap _bmp; @@ -252,67 +252,67 @@ public: wnd() { _inst = this; } int wnd::Run( HINSTANCE hInst ) { - _hInst = hInst; - _hwnd = InitAll(); - SetTimer( _hwnd, MY_TIMER, 1000, NULL ); - _clock.setHWND( _hwnd ); + _hInst = hInst; + _hwnd = InitAll(); + SetTimer( _hwnd, MY_TIMER, 1000, NULL ); + _clock.setHWND( _hwnd ); - ShowWindow( _hwnd, SW_SHOW ); - UpdateWindow( _hwnd ); + ShowWindow( _hwnd, SW_SHOW ); + UpdateWindow( _hwnd ); - MSG msg; - ZeroMemory( &msg, sizeof( msg ) ); - while( msg.message != WM_QUIT ) - { - if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) - { - TranslateMessage( &msg ); - DispatchMessage( &msg ); - } - } - return UnregisterClass( "_MY_CLOCK_", _hInst ); + MSG msg; + ZeroMemory( &msg, sizeof( msg ) ); + while( msg.message != WM_QUIT ) + { + if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) + { + TranslateMessage( &msg ); + DispatchMessage( &msg ); + } + } + return UnregisterClass( "_MY_CLOCK_", _hInst ); } private: void wnd::doPaint( HDC dc ) { _clock.setNow(); } void wnd::doTimer() { _clock.setNow(); } static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) { - switch( msg ) - { - case WM_DESTROY: PostQuitMessage( 0 ); break; - case WM_PAINT: - { - PAINTSTRUCT ps; - HDC dc = BeginPaint( hWnd, &ps ); - _inst->doPaint( dc ); - EndPaint( hWnd, &ps ); - return 0; - } - case WM_TIMER: _inst->doTimer(); break; - default: - return DefWindowProc( hWnd, msg, wParam, lParam ); - } - return 0; + switch( msg ) + { + case WM_DESTROY: PostQuitMessage( 0 ); break; + case WM_PAINT: + { + PAINTSTRUCT ps; + HDC dc = BeginPaint( hWnd, &ps ); + _inst->doPaint( dc ); + EndPaint( hWnd, &ps ); + return 0; + } + case WM_TIMER: _inst->doTimer(); break; + default: + return DefWindowProc( hWnd, msg, wParam, lParam ); + } + return 0; } HWND InitAll() { - WNDCLASSEX wcex; - ZeroMemory( &wcex, sizeof( wcex ) ); - wcex.cbSize = sizeof( WNDCLASSEX ); - wcex.style = CS_HREDRAW | CS_VREDRAW; - wcex.lpfnWndProc = ( WNDPROC )WndProc; - wcex.hInstance = _hInst; - wcex.hCursor = LoadCursor( NULL, IDC_ARROW ); - wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 ); - wcex.lpszClassName = "_MY_CLOCK_"; + WNDCLASSEX wcex; + ZeroMemory( &wcex, sizeof( wcex ) ); + wcex.cbSize = sizeof( WNDCLASSEX ); + wcex.style = CS_HREDRAW | CS_VREDRAW; + wcex.lpfnWndProc = ( WNDPROC )WndProc; + wcex.hInstance = _hInst; + wcex.hCursor = LoadCursor( NULL, IDC_ARROW ); + wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 ); + wcex.lpszClassName = "_MY_CLOCK_"; - RegisterClassEx( &wcex ); + RegisterClassEx( &wcex ); - RECT rc = { 0, 0, BMP_SIZE, BMP_SIZE }; - AdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE ); - int w = rc.right - rc.left, h = rc.bottom - rc.top; - return CreateWindow( "_MY_CLOCK_", ".: Clock -- PJorente :.", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL ); + RECT rc = { 0, 0, BMP_SIZE, BMP_SIZE }; + AdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE ); + int w = rc.right - rc.left, h = rc.bottom - rc.top; + return CreateWindow( "_MY_CLOCK_", ".: Clock -- PJorente :.", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL ); } static wnd* _inst; diff --git a/Task/Draw-a-clock/C/draw-a-clock-1.c b/Task/Draw-a-clock/C/draw-a-clock-1.c index 197d668b3d..90f51a7d51 100644 --- a/Task/Draw-a-clock/C/draw-a-clock-1.c +++ b/Task/Draw-a-clock/C/draw-a-clock-1.c @@ -9,85 +9,85 @@ const char * shades = " .:-*ca&#%@"; /* distance of (x, y) from line segment (0, 0)->(x0, y0) */ double dist(double x, double y, double x0, double y0) { - double l = (x * x0 + y * y0) / (x0 * x0 + y0 * y0); + double l = (x * x0 + y * y0) / (x0 * x0 + y0 * y0); - if (l > 1) { - x -= x0; - y -= y0; - } else if (l >= 0) { - x -= l * x0; - y -= l * y0; - } - return sqrt(x * x + y * y); + if (l > 1) { + x -= x0; + y -= y0; + } else if (l >= 0) { + x -= l * x0; + y -= l * y0; + } + return sqrt(x * x + y * y); } enum { sec = 0, min, hur }; // for subscripts void draw(int size) { -# define for_i for(int i = 0; i < size; i++) -# define for_j for(int j = 0; j < size * 2; j++) +# define for_i for(int i = 0; i < size; i++) +# define for_j for(int j = 0; j < size * 2; j++) - double angle, cx = size / 2.; - double sx[3], sy[3], sw[3]; - double fade[] = { 1, .35, .35 }; /* opacity of each arm */ - struct timeval tv; - struct tm *t; + double angle, cx = size / 2.; + double sx[3], sy[3], sw[3]; + double fade[] = { 1, .35, .35 }; /* opacity of each arm */ + struct timeval tv; + struct tm *t; - /* set width of each arm */ - sw[sec] = size * .02; - sw[min] = size * .03; - sw[hur] = size * .05; + /* set width of each arm */ + sw[sec] = size * .02; + sw[min] = size * .03; + sw[hur] = size * .05; every_second: - gettimeofday(&tv, 0); - t = localtime(&tv.tv_sec); + gettimeofday(&tv, 0); + t = localtime(&tv.tv_sec); - angle = t->tm_sec * PI / 30; - sy[sec] = -cx * cos(angle); - sx[sec] = cx * sin(angle); + angle = t->tm_sec * PI / 30; + sy[sec] = -cx * cos(angle); + sx[sec] = cx * sin(angle); - angle = (t->tm_min + t->tm_sec / 60.) / 30 * PI; - sy[min] = -cx * cos(angle) * .8; - sx[min] = cx * sin(angle) * .8; + angle = (t->tm_min + t->tm_sec / 60.) / 30 * PI; + sy[min] = -cx * cos(angle) * .8; + sx[min] = cx * sin(angle) * .8; - angle = (t->tm_hour + t->tm_min / 60.) / 6 * PI; - sy[hur] = -cx * cos(angle) * .6; - sx[hur] = cx * sin(angle) * .6; + angle = (t->tm_hour + t->tm_min / 60.) / 6 * PI; + sy[hur] = -cx * cos(angle) * .6; + sx[hur] = cx * sin(angle) * .6; - printf("\033[s"); /* save cursor position */ - for_i { - printf("\033[%d;0H", i); /* goto row i, col 0 */ - double y = i - cx; - for_j { - double x = (j - 2 * cx) / 2; + printf("\033[s"); /* save cursor position */ + for_i { + printf("\033[%d;0H", i); /* goto row i, col 0 */ + double y = i - cx; + for_j { + double x = (j - 2 * cx) / 2; - int pix = 0; - /* calcs how far the "pixel" is from each arm and set - * shade, with some anti-aliasing. It's ghetto, but much - * easier than a real scanline conversion. - */ - for (int k = hur; k >= sec; k--) { - double d = dist(x, y, sx[k], sy[k]); - if (d < sw[k] - .5) - pix = 10 * fade[k]; - else if (d < sw[k] + .5) - pix = (5 + (sw[k] - d) * 10) * fade[k]; - } - putchar(shades[pix]); - } - } - printf("\033[u"); /* restore cursor pos so you can bg the job -- value unclear */ + int pix = 0; + /* calcs how far the "pixel" is from each arm and set + * shade, with some anti-aliasing. It's ghetto, but much + * easier than a real scanline conversion. + */ + for (int k = hur; k >= sec; k--) { + double d = dist(x, y, sx[k], sy[k]); + if (d < sw[k] - .5) + pix = 10 * fade[k]; + else if (d < sw[k] + .5) + pix = (5 + (sw[k] - d) * 10) * fade[k]; + } + putchar(shades[pix]); + } + } + printf("\033[u"); /* restore cursor pos so you can bg the job -- value unclear */ - fflush(stdout); - sleep(1); /* sleep 1 can at times miss a second, but will catch up next update */ - goto every_second; + fflush(stdout); + sleep(1); /* sleep 1 can at times miss a second, but will catch up next update */ + goto every_second; } int main(int argc, char *argv[]) { - int s; - if (argc <= 1 || (s = atoi(argv[1])) <= 0) s = 20; - draw(s); - return 0; + int s; + if (argc <= 1 || (s = atoi(argv[1])) <= 0) s = 20; + draw(s); + return 0; } diff --git a/Task/Draw-a-clock/ContextFree/draw-a-clock.cf b/Task/Draw-a-clock/ContextFree/draw-a-clock.cf index a03d242674..95b5690c00 100644 --- a/Task/Draw-a-clock/ContextFree/draw-a-clock.cf +++ b/Task/Draw-a-clock/ContextFree/draw-a-clock.cf @@ -3,12 +3,12 @@ startshape START TIME_IN_SECONDS = 60 shape START { - SECOND_HAND[r (TIME_IN_SECONDS*-6)] - CIRCLE[s 50 50] + SECOND_HAND[r (TIME_IN_SECONDS*-6)] + CIRCLE[s 50 50] } shape SECOND_HAND { - TRIANGLE [[z 1 s 1 30 y 0.26 b 1]] + TRIANGLE [[z 1 s 1 30 y 0.26 b 1]] } diff --git a/Task/Draw-a-clock/Delphi/draw-a-clock-1.delphi b/Task/Draw-a-clock/Delphi/draw-a-clock-1.pas similarity index 100% rename from Task/Draw-a-clock/Delphi/draw-a-clock-1.delphi rename to Task/Draw-a-clock/Delphi/draw-a-clock-1.pas diff --git a/Task/Draw-a-clock/Delphi/draw-a-clock-2.delphi b/Task/Draw-a-clock/Delphi/draw-a-clock-2.pas similarity index 100% rename from Task/Draw-a-clock/Delphi/draw-a-clock-2.delphi rename to Task/Draw-a-clock/Delphi/draw-a-clock-2.pas diff --git a/Task/Draw-a-clock/EasyLang/draw-a-clock.easy b/Task/Draw-a-clock/EasyLang/draw-a-clock.easy index 7d2dc2ddee..f53a4939f8 100644 --- a/Task/Draw-a-clock/EasyLang/draw-a-clock.easy +++ b/Task/Draw-a-clock/EasyLang/draw-a-clock.easy @@ -1,38 +1,32 @@ -proc draw hour min sec . . +proc draw hour min sec . # dial - color 333 - move 50 50 - circle 45 - color 797 - circle 44 - color 333 + gcolor 333 + gcircle 50 50 45 + gcolor 797 + gcircle 50 50 44 + gcolor 333 for i range0 60 a = i * 6 - move 50 + sin a * 40 50 + cos a * 40 - circle 0.25 - . - for i range0 12 - a = i * 30 - move 50 + sin a * 40 50 + cos a * 40 - circle 1 + if i mod 5 = 0 + gcircle 50 + sin a * 40 50 + cos a * 40 1 + else + gcircle 50 + sin a * 40 50 + cos a * 40 0.25 + . . # hour - linewidth 2 - color 000 + glinewidth 2 + gcolor 000 a = (hour * 60 + min) / 2 - move 50 50 - line 50 + sin a * 32 50 + cos a * 32 + gline 50 50 50 + sin a * 32 50 + cos a * 32 # min - linewidth 1.5 + glinewidth 1.5 a = (sec + min * 60) / 10 - move 50 50 - line 50 + sin a * 40 50 + cos a * 40 + gline 50 50 50 + sin a * 40 50 + cos a * 40 # sec - linewidth 1 - color 700 + glinewidth 1 + gcolor 700 a = sec * 6 - move 50 50 - line 50 + sin a * 40 50 + cos a * 40 + gline 50 50 50 + sin a * 40 50 + cos a * 40 . on timer if t <> floor systime @@ -41,11 +35,9 @@ on timer sec = number substr h$ 18 2 min = number substr h$ 15 2 hour = number substr h$ 12 2 - if hour > 12 - hour -= 12 - . + if hour > 12 : hour -= 12 draw hour min sec . - timer 0.1 + timer 0.05 . timer 0 diff --git a/Task/Draw-a-clock/Go/draw-a-clock-1.go b/Task/Draw-a-clock/Go/draw-a-clock-1.go index 3b45a2348f..1dcf2cd406 100644 --- a/Task/Draw-a-clock/Go/draw-a-clock-1.go +++ b/Task/Draw-a-clock/Go/draw-a-clock-1.go @@ -1,88 +1,88 @@ package main import ( - "golang.org/x/net/websocket" - "flag" - "fmt" - "html/template" - "io" - "math" - "net/http" - "time" + "golang.org/x/net/websocket" + "flag" + "fmt" + "html/template" + "io" + "math" + "net/http" + "time" ) var ( - Portnum string - Hostsite string + Portnum string + Hostsite string ) type PageSettings struct { - Host string - Port string + Host string + Port string } const ( - Canvaswidth = 512 - Canvasheight = 512 - //color constants - HourColor = "#ff7373" // pinkish - MinuteColor = "#00b7e4" //light blue - SecondColor = "#b58900" //gold + Canvaswidth = 512 + Canvasheight = 512 + //color constants + HourColor = "#ff7373" // pinkish + MinuteColor = "#00b7e4" //light blue + SecondColor = "#b58900" //gold ) func main() { - flag.StringVar(&Portnum, "Port", "1234", "Port to host server.") - flag.StringVar(&Hostsite, "Site", "localhost", "Site hosting server") - flag.Parse() - http.HandleFunc("/", webhandler) - http.Handle("/ws", websocket.Handler(wshandle)) - err := http.ListenAndServe(Hostsite+":"+Portnum, nil) - if err != nil { - fmt.Println(err) - } - fmt.Println("server running") + flag.StringVar(&Portnum, "Port", "1234", "Port to host server.") + flag.StringVar(&Hostsite, "Site", "localhost", "Site hosting server") + flag.Parse() + http.HandleFunc("/", webhandler) + http.Handle("/ws", websocket.Handler(wshandle)) + err := http.ListenAndServe(Hostsite+":"+Portnum, nil) + if err != nil { + fmt.Println(err) + } + fmt.Println("server running") } func webhandler(w http.ResponseWriter, r *http.Request) { - wsurl := PageSettings{Host: Hostsite, Port: Portnum} - template, _ := template.ParseFiles("clock.html") - template.Execute(w, wsurl) + wsurl := PageSettings{Host: Hostsite, Port: Portnum} + template, _ := template.ParseFiles("clock.html") + template.Execute(w, wsurl) } //Given a websocket connection, //serves updating time function func wshandle(ws *websocket.Conn) { - for { - hour, min, sec := time.Now().Clock() - hourx, houry := HourCords(hour, Canvasheight/2) - minx, miny := MinSecCords(min, Canvasheight/2) - secx, secy := MinSecCords(sec, Canvasheight/2) - msg := "CLEAR\n" - msg += fmt.Sprintf("HOUR %d %d %s\n", hourx, houry, HourColor) - msg += fmt.Sprintf("MIN %d %d %s\n", minx, miny, MinuteColor) - msg += fmt.Sprintf("SEC %d %d %s", secx, secy, SecondColor) - io.WriteString(ws, msg) - time.Sleep(time.Second / 60.0) - } + for { + hour, min, sec := time.Now().Clock() + hourx, houry := HourCords(hour, Canvasheight/2) + minx, miny := MinSecCords(min, Canvasheight/2) + secx, secy := MinSecCords(sec, Canvasheight/2) + msg := "CLEAR\n" + msg += fmt.Sprintf("HOUR %d %d %s\n", hourx, houry, HourColor) + msg += fmt.Sprintf("MIN %d %d %s\n", minx, miny, MinuteColor) + msg += fmt.Sprintf("SEC %d %d %s", secx, secy, SecondColor) + io.WriteString(ws, msg) + time.Sleep(time.Second / 60.0) + } } //Given current minute or second time(i.e 30 min, 60 minutes) //and the radius, returns pair of cords to draw line to func MinSecCords(ctime int, radius int) (int, int) { - //converts min/sec to angle and then to radians + //converts min/sec to angle and then to radians - theta := ((float64(ctime)*6 - 90) * (math.Pi / 180)) - x := float64(radius) * math.Cos(theta) - y := float64(radius) * math.Sin(theta) - return int(x) + 256, int(y) + 256 + theta := ((float64(ctime)*6 - 90) * (math.Pi / 180)) + x := float64(radius) * math.Cos(theta) + y := float64(radius) * math.Sin(theta) + return int(x) + 256, int(y) + 256 } //Given current hour time(i.e. 12, 8) and the radius, //returns pair of cords to draw line to func HourCords(ctime int, radius int) (int, int) { - //converts hours to angle and then to radians - theta := ((float64(ctime)*30 - 90) * (math.Pi / 180)) - x := float64(radius) * math.Cos(theta) - y := float64(radius) * math.Sin(theta) - return int(x) + 256, int(y) + 256 + //converts hours to angle and then to radians + theta := ((float64(ctime)*30 - 90) * (math.Pi / 180)) + x := float64(radius) * math.Cos(theta) + y := float64(radius) * math.Sin(theta) + return int(x) + 256, int(y) + 256 } diff --git a/Task/Draw-a-clock/Go/draw-a-clock-2.go b/Task/Draw-a-clock/Go/draw-a-clock-2.go index 5dad3296a3..fd18474571 100644 --- a/Task/Draw-a-clock/Go/draw-a-clock-2.go +++ b/Task/Draw-a-clock/Go/draw-a-clock-2.go @@ -10,10 +10,10 @@ var hourhand; function wsConnect() { - //get contexts for drawing + //get contexts for drawing //var canvas = document.getElementById( "canvas" ); //ctx = canvas.getContext( '2d' ); - var canvas = document.getElementById("rim"); + var canvas = document.getElementById("rim"); //draw circle for rim rim = canvas.getContext('2d'); rim.beginPath(); @@ -83,19 +83,19 @@

    Clock

    - + Sorry, your browser does not support Canvas - + Sorry, your browser does not support Canvas - + Sorry, your browser does not support Canvas - + Sorry, your browser does not support Canvas - + diff --git a/Task/Draw-a-clock/JavaScript/draw-a-clock-1.js b/Task/Draw-a-clock/JavaScript/draw-a-clock-1.js index 4a3b8b27f0..62e1f5b9f7 100644 --- a/Task/Draw-a-clock/JavaScript/draw-a-clock-1.js +++ b/Task/Draw-a-clock/JavaScript/draw-a-clock-1.js @@ -1,47 +1,47 @@ var sec_old = 0; function update_clock() { - var t = new Date(); - var arms = [t.getHours(), t.getMinutes(), t.getSeconds()]; - if (arms[2] == sec_old) return; - sec_old = arms[2]; + var t = new Date(); + var arms = [t.getHours(), t.getMinutes(), t.getSeconds()]; + if (arms[2] == sec_old) return; + sec_old = arms[2]; - var c = document.getElementById('clock'); - var ctx = c.getContext('2d'); - ctx.fillStyle = "rgb(0,200,200)"; - ctx.fillRect(0, 0, c.width, c.height); - ctx.fillStyle = "white"; - ctx.fillRect(3, 3, c.width - 6, c.height - 6); - ctx.lineCap = 'round'; + var c = document.getElementById('clock'); + var ctx = c.getContext('2d'); + ctx.fillStyle = "rgb(0,200,200)"; + ctx.fillRect(0, 0, c.width, c.height); + ctx.fillStyle = "white"; + ctx.fillRect(3, 3, c.width - 6, c.height - 6); + ctx.lineCap = 'round'; - var orig = { x: c.width / 2, y: c.height / 2 }; - arms[1] += arms[2] / 60; - arms[0] += arms[1] / 60; - draw_arm(ctx, orig, arms[0] * 30, c.width/2.5 - 15, c.width / 20, "green"); - draw_arm(ctx, orig, arms[1] * 6, c.width/2.2 - 10, c.width / 30, "navy"); - draw_arm(ctx, orig, arms[2] * 6, c.width/2.0 - 6, c.width / 100, "maroon"); + var orig = { x: c.width / 2, y: c.height / 2 }; + arms[1] += arms[2] / 60; + arms[0] += arms[1] / 60; + draw_arm(ctx, orig, arms[0] * 30, c.width/2.5 - 15, c.width / 20, "green"); + draw_arm(ctx, orig, arms[1] * 6, c.width/2.2 - 10, c.width / 30, "navy"); + draw_arm(ctx, orig, arms[2] * 6, c.width/2.0 - 6, c.width / 100, "maroon"); } function draw_arm(ctx, orig, deg, len, w, style) { - ctx.save(); - ctx.lineWidth = w; - ctx.lineCap = 'round'; - ctx.translate(orig.x, orig.y); - ctx.rotate((deg - 90) * Math.PI / 180); - ctx.strokeStyle = style; - ctx.beginPath(); - ctx.moveTo(-len / 10, 0); - ctx.lineTo(len, 0); - ctx.stroke(); - ctx.restore(); + ctx.save(); + ctx.lineWidth = w; + ctx.lineCap = 'round'; + ctx.translate(orig.x, orig.y); + ctx.rotate((deg - 90) * Math.PI / 180); + ctx.strokeStyle = style; + ctx.beginPath(); + ctx.moveTo(-len / 10, 0); + ctx.lineTo(len, 0); + ctx.stroke(); + ctx.restore(); } function init_clock() { - var clock = document.createElement('canvas'); - clock.width = 100; - clock.height = 100; - clock.id = "clock"; - document.body.appendChild(clock); + var clock = document.createElement('canvas'); + clock.width = 100; + clock.height = 100; + clock.id = "clock"; + document.body.appendChild(clock); - window.setInterval(update_clock, 200); + window.setInterval(update_clock, 200); } diff --git a/Task/Draw-a-clock/Julia/draw-a-clock.julia b/Task/Draw-a-clock/Julia/draw-a-clock.jl similarity index 100% rename from Task/Draw-a-clock/Julia/draw-a-clock.julia rename to Task/Draw-a-clock/Julia/draw-a-clock.jl diff --git a/Task/Draw-a-clock/Kotlin/draw-a-clock.kotlin b/Task/Draw-a-clock/Kotlin/draw-a-clock.kts similarity index 100% rename from Task/Draw-a-clock/Kotlin/draw-a-clock.kotlin rename to Task/Draw-a-clock/Kotlin/draw-a-clock.kts diff --git a/Task/Draw-a-clock/M2000-Interpreter/draw-a-clock.m2000 b/Task/Draw-a-clock/M2000-Interpreter/draw-a-clock.m2000 index 365ce205dd..8d8e6c0c7b 100644 --- a/Task/Draw-a-clock/M2000-Interpreter/draw-a-clock.m2000 +++ b/Task/Draw-a-clock/M2000-Interpreter/draw-a-clock.m2000 @@ -5,89 +5,89 @@ cls, 0 window 6, window Module Led_Clock{ - Escape Off - Smooth off - Dim D(-1 to 9) - D(-1)=(0,0,0,0,0,0,0) - D(0)=(1,1,1,0,1,1,1) - D(1)=(0,0,1,0,0,1,0) - D(2)=(1,0,1,1,1,0,1) - D(3)=(1,0,1,1,0,1,1) - D(4)=(0,1,1,1,0,1,0) - D(5)=(1,1,0,1,0,1,1) - D(6)=(1,1,0,1,1,1,1) - D(7)=(1,0,1,0,0,1,0) - D(8)=(1,1,1,1,1,1,1) - D(9)=(1,1,1,1,0,1,1) - N=240 - XX=(scale.x-N*75) div 2 - YY=scale.y-N*22 - NN=N - BackColor=0 - CLS BackColor, 0 - Back {CLS BackColor,0} - desktop 255, BackColor - Forecolor=12 - C=BackColor-Forecolor - pen BackColor - for i=0 to 9: cc=d(i): cc*=c:next - m=1 - move XX+N*23.2, YY+N*5.2 - polygon BackColor-C, N,-N, N,N, -N, N, -N, -N - move XX+N*23.2,YY+N*13.2 - polygon BackColor-C, N,-N, N,N, -N, N, -N, -N - move XX+N*49.2,YY+N*5.2 - polygon BackColor-C, N,-N, N,N, -N, N, -N, -N - move XX+N*49.2,YY+N*13.2 - polygon BackColor-C, N,-N, N,N, -N, N, -N, -N - dsk=True - every 1000/2 { - k=now - k1=val(str$(k, "hh")) - k2=val(str$(k, "nn")) - k3=val(str$(k, "ss")) - LED(XX, D(k1 div 10)) - LED(XX+N*12, D(k1 mod 10)) - LED(XX+N*26, D(k2 div 10)) - LED(XX+N*38, D(k2 mod 10)) - LED(XX+N*52, D(k3 div 10)) - LED(XX+N*64, D(k3 mod 10)) - refresh 1000 - if keypress(32) then - dsk~ - if dsk then desktop 255 else desktop 255, BackColor - end if - if keypress(27) or mouse=2 then exit - } - desktop 255 - pen 14 - refresh 50 - mode 16 - wait 1000 - Escape On + Escape Off + Smooth off + Dim D(-1 to 9) + D(-1)=(0,0,0,0,0,0,0) + D(0)=(1,1,1,0,1,1,1) + D(1)=(0,0,1,0,0,1,0) + D(2)=(1,0,1,1,1,0,1) + D(3)=(1,0,1,1,0,1,1) + D(4)=(0,1,1,1,0,1,0) + D(5)=(1,1,0,1,0,1,1) + D(6)=(1,1,0,1,1,1,1) + D(7)=(1,0,1,0,0,1,0) + D(8)=(1,1,1,1,1,1,1) + D(9)=(1,1,1,1,0,1,1) + N=240 + XX=(scale.x-N*75) div 2 + YY=scale.y-N*22 + NN=N + BackColor=0 + CLS BackColor, 0 + Back {CLS BackColor,0} + desktop 255, BackColor + Forecolor=12 + C=BackColor-Forecolor + pen BackColor + for i=0 to 9: cc=d(i): cc*=c:next + m=1 + move XX+N*23.2, YY+N*5.2 + polygon BackColor-C, N,-N, N,N, -N, N, -N, -N + move XX+N*23.2,YY+N*13.2 + polygon BackColor-C, N,-N, N,N, -N, N, -N, -N + move XX+N*49.2,YY+N*5.2 + polygon BackColor-C, N,-N, N,N, -N, N, -N, -N + move XX+N*49.2,YY+N*13.2 + polygon BackColor-C, N,-N, N,N, -N, N, -N, -N + dsk=True + every 1000/2 { + k=now + k1=val(str$(k, "hh")) + k2=val(str$(k, "nn")) + k3=val(str$(k, "ss")) + LED(XX, D(k1 div 10)) + LED(XX+N*12, D(k1 mod 10)) + LED(XX+N*26, D(k2 div 10)) + LED(XX+N*38, D(k2 mod 10)) + LED(XX+N*52, D(k3 div 10)) + LED(XX+N*64, D(k3 mod 10)) + refresh 1000 + if keypress(32) then + dsk~ + if dsk then desktop 255 else desktop 255, BackColor + end if + if keypress(27) or mouse=2 then exit + } + desktop 255 + pen 14 + refresh 50 + mode 16 + wait 1000 + Escape On - sub LED(XX, S()) - move XX+N*1.2, YY+NN - \\ LED - UPPER - polygon BackColor-S(0), N,-N,N*6,0, N,N, -N, N,-N*6,0, -N, -N - \\ LED | LEFT UPPER - move XX+N*1.2-N*1.2, YY+N*1.2+NN - polygon BackColor-S(1), N,-N,N,N,0,N*6,-N, N, -N, -N, 0, -N*6 - move XX+N*1.2+N*7.2, YY+N*1.2+NN - \\ LED | RIGHT UPPER - polygon BackColor-S(2), N,-N,N,N,0,N*6,-N, N, -N, -N, 0, -N*6 - move XX+N*1.2, YY+N*8.4+NN - \\ LED - MIDDLE - polygon BackColor-S(3), N,-N,N*6,0, N,N, -N, N,-N*6,0, -N, -N - \\ LED | LEFT BOTTOM - move XX+N*1.2-N*1.2, YY+N*9.6+NN - polygon BackColor-S(4), N,-N,N,N,0,N*6,-N, N, -N, -N, 0, -N*6 - \\ LED | RIGHT BOTTOM - move XX+N*1.2+N*7.2, YY+N*9.6+NN - polygon BackColor-S(5), N,-N,N,N,0,N*6,-N, N, -N, -N, 0, -N*6 - \\ LED - BOTTOM - move XX+N*1.2, YY+N*16.8+NN - polygon BackColor-S(6), N,-N,N*6,0, N,N, -N, N,-N*6,0, -N, -N - end sub + sub LED(XX, S()) + move XX+N*1.2, YY+NN + \\ LED - UPPER + polygon BackColor-S(0), N,-N,N*6,0, N,N, -N, N,-N*6,0, -N, -N + \\ LED | LEFT UPPER + move XX+N*1.2-N*1.2, YY+N*1.2+NN + polygon BackColor-S(1), N,-N,N,N,0,N*6,-N, N, -N, -N, 0, -N*6 + move XX+N*1.2+N*7.2, YY+N*1.2+NN + \\ LED | RIGHT UPPER + polygon BackColor-S(2), N,-N,N,N,0,N*6,-N, N, -N, -N, 0, -N*6 + move XX+N*1.2, YY+N*8.4+NN + \\ LED - MIDDLE + polygon BackColor-S(3), N,-N,N*6,0, N,N, -N, N,-N*6,0, -N, -N + \\ LED | LEFT BOTTOM + move XX+N*1.2-N*1.2, YY+N*9.6+NN + polygon BackColor-S(4), N,-N,N,N,0,N*6,-N, N, -N, -N, 0, -N*6 + \\ LED | RIGHT BOTTOM + move XX+N*1.2+N*7.2, YY+N*9.6+NN + polygon BackColor-S(5), N,-N,N,N,0,N*6,-N, N, -N, -N, 0, -N*6 + \\ LED - BOTTOM + move XX+N*1.2, YY+N*16.8+NN + polygon BackColor-S(6), N,-N,N*6,0, N,N, -N, N,-N*6,0, -N, -N + end sub } Led_Clock diff --git a/Task/Draw-a-clock/MiniScript/draw-a-clock.mini b/Task/Draw-a-clock/MiniScript/draw-a-clock.mini index f9d7b1464c..9233919be6 100644 --- a/Task/Draw-a-clock/MiniScript/draw-a-clock.mini +++ b/Task/Draw-a-clock/MiniScript/draw-a-clock.mini @@ -21,6 +21,6 @@ display(4).sprites.push hand // main loop while true - hand.rotation = 90 - floor(time) % 60 * 6 - wait + hand.rotation = 90 - floor(time) % 60 * 6 + wait end while diff --git a/Task/Draw-a-clock/OCaml/draw-a-clock-1.ocaml b/Task/Draw-a-clock/OCaml/draw-a-clock-1.ml similarity index 100% rename from Task/Draw-a-clock/OCaml/draw-a-clock-1.ocaml rename to Task/Draw-a-clock/OCaml/draw-a-clock-1.ml diff --git a/Task/Draw-a-clock/OCaml/draw-a-clock-2.ocaml b/Task/Draw-a-clock/OCaml/draw-a-clock-2.ml similarity index 100% rename from Task/Draw-a-clock/OCaml/draw-a-clock-2.ocaml rename to Task/Draw-a-clock/OCaml/draw-a-clock-2.ml diff --git a/Task/Draw-a-clock/OPL/draw-a-clock.opl b/Task/Draw-a-clock/OPL/draw-a-clock.opl new file mode 100644 index 0000000000..fbb6eccc6e --- /dev/null +++ b/Task/Draw-a-clock/OPL/draw-a-clock.opl @@ -0,0 +1,6 @@ +REM Series 3a and Series 5 use different modes. This version runs on Series 3a. For Series 5, remove the "2" in the gCLOCK line. + +PROC main: + gCLOCK ON,$29 + GET +ENDP diff --git a/Task/Draw-a-clock/Odin/draw-a-clock.odin b/Task/Draw-a-clock/Odin/draw-a-clock.odin new file mode 100644 index 0000000000..f1fd0e6408 --- /dev/null +++ b/Task/Draw-a-clock/Odin/draw-a-clock.odin @@ -0,0 +1,87 @@ +package clock + +import rl "vendor:raylib" +import "core:time" +import "core:time/datetime" +import "core:time/timezone" +import "core:os" +import "core:math" + +TimePeriod :: enum { + AM, + PM +} + +DistanceAngle :: proc(distance: f32, angle: f32) -> (vector: rl.Vector2) { + vector.x = math.sin_f32(angle) + vector.y = -math.cos_f32(angle) + vector *= distance + + return +} + +main :: proc() { + tz, ok := timezone.region_load("local") + + rl.SetConfigFlags({.MSAA_4X_HINT}) + rl.InitWindow(640, 480, "Rosetta Code - draw a clock") + + screen_center := rl.Vector2 {f32(rl.GetScreenWidth()) / 2, f32(rl.GetScreenHeight()) / 2} + + for !rl.WindowShouldClose() { + rl.BeginDrawing() + + rl.ClearBackground(rl.RAYWHITE) + + conversion_succeeded: bool = true + date_time: datetime.DateTime + date_time, ok = time.time_to_datetime(time.now()) + if !ok do conversion_succeeded = false + + date_time, ok = timezone.datetime_to_tz(date_time, tz) + if !ok do conversion_succeeded = false + + regular_time: time.Time + regular_time, ok = time.datetime_to_time(date_time) + if !ok do conversion_succeeded = false + + if !conversion_succeeded do os.exit(1) + + period: TimePeriod + hour, min, sec := time.clock_from_time(regular_time) + if hour > 12 { + hour -= 12 + period = .PM + } + + radius := f32(rl.GetScreenHeight()) / 2.5 + + rl.DrawCircleV(screen_center, radius, rl.LIGHTGRAY) + + rl.DrawLineEx(screen_center, screen_center + DistanceAngle(radius * .75, (f32(hour) / 12) * math.TAU), 4, rl.BLACK) + rl.DrawLineEx(screen_center, screen_center + DistanceAngle(radius * .7, (f32(min) / 60) * math.TAU), 4, rl.DARKGREEN) + rl.DrawLineEx(screen_center, screen_center + DistanceAngle(radius * .5, (f32(sec) / 60) * math.TAU), 4, rl.RED) + + for i := 0; i < 60; i += 1 { + angle := (f32(i) / 60) * math.TAU + + inside_distance: f32 = .8 + thickness: f32 = 1.5 + + if i % 5 == 0 { + inside_distance = .775 + thickness = 3 + } + + rl.DrawLineEx(screen_center + DistanceAngle(radius * inside_distance, angle), screen_center + DistanceAngle(radius * .95, angle), thickness, rl.DARKGRAY) + } + + //fmt.printfln("%2d:%2d:%2d %s", hour, min, sec, period) + + rl.EndDrawing() + } + + rl.CloseWindow() + + timezone.region_destroy(tz) +} diff --git a/Task/Draw-a-clock/Perl/draw-a-clock.pl b/Task/Draw-a-clock/Perl/draw-a-clock-1.pl similarity index 100% rename from Task/Draw-a-clock/Perl/draw-a-clock.pl rename to Task/Draw-a-clock/Perl/draw-a-clock-1.pl diff --git a/Task/Draw-a-clock/Perl/draw-a-clock-2.pl b/Task/Draw-a-clock/Perl/draw-a-clock-2.pl new file mode 100644 index 0000000000..3cf966a4c3 --- /dev/null +++ b/Task/Draw-a-clock/Perl/draw-a-clock-2.pl @@ -0,0 +1,22 @@ +#!/usr/bin/perl + +use strict; # https://rosettacode.org/wiki/Draw_a_clock +use warnings; +use Tk; + +my $halfsize = 200; +my $twopi = 2 * atan2 0, -1; +my $mw = MainWindow->new; +my $c = $mw->Canvas( -width => 2 * $halfsize, -height => 2 * $halfsize)->pack; +$mw->repeat(1000 => \&draw); +MainLoop; + +sub draw + { + $c->delete('all'); + my $angle = time % 60 / 60 * $twopi; + $c->createLine( $halfsize, $halfsize, + $halfsize * (1 + sin $angle), + $halfsize * (1 - cos $angle), + -width => 5); + } diff --git a/Task/Draw-a-clock/Rebol/draw-a-clock.rebol b/Task/Draw-a-clock/Rebol/draw-a-clock.rebol new file mode 100644 index 0000000000..6c3403e1bd --- /dev/null +++ b/Task/Draw-a-clock/Rebol/draw-a-clock.rebol @@ -0,0 +1,26 @@ +Rebol [ + title: "Rosetta code: Draw a clock (CLI)" + file: %Draw_a_clock.r3 + url: https://rosettacode.org/wiki/Draw_a_clock +] + +;; two spaced-separated blocks of Braille-like glyphs (top and bottom halves for digits 0-9 and separator) +s: join { ⡎⢉⢵ ⠀⢺⠀ ⠊⠉⡱ ⠊⣉⡱ ⢀⠔⡇ ⣏⣉⡉ ⣎⣉⡁ ⠊⢉⠝ ⢎⣉⡱ ⡎⠉⢱ ⠀⠶ } + { ⢗⣁⡸ ⢀⣸⣀ ⣔⣉⣀ ⢄⣀⡸ ⠉⠉⡏ ⢄⣀⡸ ⢇⣀⡸ ⢰⠁⠀ ⢇⣀⡸ ⢈⣉⡹ ⠀⠶ } +;; split the big string every 4 chars to get a block of 22 glyph cells (11 top + 11 bottom) +s: split s 4 + +forever [ ;; loop to update the clock every second + tm: format-date-time now "hh:mm:ss" ;; current time string, e.g., "12:34:56" + l1: clear "" ;; buffer for the top line of the big digits + l2: clear "" ;; buffer for the bottom line of the big digits + foreach c tm [ ;; for each character in the time string + i: 1 + c - #"0" ;; convert digit char to 1-based index + append l1 s/(i) ;; append top-half glyph for the digit (for ":" this will intentionally pick the separator at index 11) + append l2 s/(i + 11) ;; append bottom-half glyph (offset by 11 to access the lower row set) + ] + print l1 ;; print top line of large digits + print l2 ;; print bottom line of large digits + wait 1 ;; pause one second + prin "^[[2A" ;; move cursor up 2 lines (ANSI escape) to overwrite in place next iteration +] diff --git a/Task/Draw-a-clock/Red/draw-a-clock-2.red b/Task/Draw-a-clock/Red/draw-a-clock-2.red index 7d9f1c70e7..54e7b08da4 100644 --- a/Task/Draw-a-clock/Red/draw-a-clock-2.red +++ b/Task/Draw-a-clock/Red/draw-a-clock-2.red @@ -1,6 +1,6 @@ Red [ - Needs: 'View - Purpose: {simple analog clock based on Nenad Rakocevic's eve-clock.red, + Needs: 'View + Purpose: {simple analog clock based on Nenad Rakocevic's eve-clock.red, see http://www.red-lang.org/2016/07/eve-style-clock-demo-in-red-livecoded.html} ] diff --git a/Task/Draw-a-clock/Ring/draw-a-clock.ring b/Task/Draw-a-clock/Ring/draw-a-clock.ring new file mode 100644 index 0000000000..2423676512 --- /dev/null +++ b/Task/Draw-a-clock/Ring/draw-a-clock.ring @@ -0,0 +1,96 @@ +# Author: Gal Zsolt (CalmoSoft) +load "libsdl.ring" +load "stdlibcore.ring" + +# Settings +screen_w = 640 +screen_h = 480 +xp = screen_w/2 +yp = screen_h/2 +size = 200 +pi = 3.14159265 + +sdl_init(SDL_INIT_EVERYTHING) +window = sdl_createwindow("Analog Clock - CalmoSoft", 100, 100, screen_w, screen_h, SDL_WINDOW_SHOWN) +render = sdl_createrenderer(window, -1, SDL_RENDERER_ACCELERATED) +ev = sdl_new_sdl_event() + +while true + # Event handling + sdl_pollevent(ev) + if sdl_get_sdl_event_type(ev) = SDL_QUIT exit ok + + # Get system time + t = time() + h = 0 + substr(t,1,2) + m = 0 + substr(t,4,2) + s = 0 + substr(t,7,2) + + # Clear background (Black) + sdl_setrenderdrawcolor(render, 0, 0, 0, 255) + sdl_renderclear(render) + + # Draw the clock components + draw_clock(render, xp, yp, size, h, m, s, pi) + + sdl_renderpresent(render) + sdl_delay(100) +end + +# Clean up +sdl_destroyrenderer(render) +sdl_destroywindow(window) +sdl_quit() + +func draw_clock render, x, y, r, h, m, s, pi + # 1. Draw Clock Face (White circle outline) + sdl_setrenderdrawcolor(render, 255, 255, 255, 255) + for i = 0 to 360 step 1 + angle = i * pi / 180 + sdl_renderdrawpoint(render, x + r * cos(angle), y + r * sin(angle)) + next + + # 2. Draw Hour Markers (Ticks) + sdl_setrenderdrawcolor(render, 255, 255, 255, 255) + for i = 1 to 12 + angle = i * 30 * pi / 180 + x1 = x + r * 0.95 * sin(angle) + y1 = y - r * 0.95 * cos(angle) + x2 = x + r * 0.85 * sin(angle) + y2 = y - r * 0.85 * cos(angle) + sdl_renderdrawline(render, x1, y1, x2, y2) + next + + # Calculate angles for hands + s_angle = (s / 60) * 2 * pi + m_angle = ((m + s/60) / 60) * 2 * pi + h_angle = ((h % 12 + m/60) / 12) * 2 * pi + + # 3. Draw Hands (Thickened) + + # Hour Hand (Green - thickest: 5px) + sdl_setrenderdrawcolor(render, 0, 255, 0, 255) + for i = -2 to 2 + sdl_renderdrawline(render, x+i, y+i, x + r*0.5*sin(h_angle)+i, y - r*0.5*cos(h_angle)+i) + next + + # Minute Hand (Blue - medium: 3px) + sdl_setrenderdrawcolor(render, 0, 100, 255, 255) + for i = -1 to 1 + sdl_renderdrawline(render, x+i, y+i, x + r*0.8*sin(m_angle)+i, y - r*0.8*cos(m_angle)+i) + next + + # Second Hand (Red - 2px) + sdl_setrenderdrawcolor(render, 255, 0, 0, 255) + for i = 0 to 1 + sdl_renderdrawline(render, x+i, y+i, x + r*0.9*sin(s_angle)+i, y - r*0.9*cos(s_angle)+i) + next + + # 4. Center Cap (Axis) + sdl_setrenderdrawcolor(render, 200, 200, 200, 255) + for i = 0 to 360 step 10 + angle = i * pi / 180 + for radius = 0 to 5 + sdl_renderdrawpoint(render, x + radius * cos(angle), y + radius * sin(angle)) + next + next diff --git a/Task/Draw-a-clock/Run-BASIC/draw-a-clock.basic b/Task/Draw-a-clock/Run-BASIC/draw-a-clock.basic index ba1d79746f..db2e14893c 100644 --- a/Task/Draw-a-clock/Run-BASIC/draw-a-clock.basic +++ b/Task/Draw-a-clock/Run-BASIC/draw-a-clock.basic @@ -1,10 +1,10 @@ ' -------------------------------------------- ' clock. I got nothing but time ' --------------------------------------------- -n = 12 ' num of points -r = 95 ' radius -pi = 22/7 -alpha = pi * 2 / n +n = 12 ' num of points +r = 95 ' radius +pi = 22/7 +alpha = pi * 2 / n dim points(n) graphic #g2, 200, 200 ' -------------------------------------- @@ -22,58 +22,58 @@ graphic #g2, 200, 200 #g2 place(90,185) #g2 "\6" for i = 0 to n - 1 - theta = alpha * i - px = cos( theta ) * r - py = sin( theta ) * r - px = px + 100 - py = py + 100 - #g2 place(px,py) - #g2 circle(2) + theta = alpha * i + px = cos( theta ) * r + py = sin( theta ) * r + px = px + 100 + py = py + 100 + #g2 place(px,py) + #g2 circle(2) next i [shoTime] ' ------------------------- ' clear previous sec,min,hr ' ------------------------- -r = 63 -p = se +r = 63 +p = se #g2 color("white") gosub [h2Dot] -r = 50 -p = mi +r = 50 +p = mi #g2 color("white") gosub [h2Dot] -r = 30 ' radius -p = hr * 5 +r = 30 ' radius +p = hr * 5 #g2 color("white") gosub [h2Dot] ' ------------------------- ' Show new time ' ------------------------- -a$ = time$() -hr = val(word$(a$,1,":")) -mi = val(word$(a$,2,":")) -se = val(word$(a$,3,":")) +a$ = time$() +hr = val(word$(a$,1,":")) +mi = val(word$(a$,2,":")) +se = val(word$(a$,3,":")) ' put time on the clock - gimme a hand #g2 size(4) ' second hand -n = 60 -r = 63 -p = se +n = 60 +r = 63 +p = se #g2 color("blue") gosub [h2Dot] ' minute hand -r = 50 -p = mi +r = 50 +p = mi #g2 color("green") gosub [h2Dot] ' hour hand -r = 30 ' radius -p = hr * 5 +r = 30 ' radius +p = hr * 5 #g2 color("red") gosub [h2Dot] @@ -82,13 +82,13 @@ end ' a one liner [h2Dot] -alpha = pi * 2 / n -i = p - 15 -theta = alpha * i -px = cos( theta ) * r -py = sin( theta ) * r -px = px + 100 -py = py + 100 +alpha = pi * 2 / n +i = p - 15 +theta = alpha * i +px = cos( theta ) * r +py = sin( theta ) * r +px = px + 100 +py = py + 100 #g2 place(px,py) #g2 circle(2) #g2 line(100,100,px,py) diff --git a/Task/Draw-a-clock/Rust/draw-a-clock.rust b/Task/Draw-a-clock/Rust/draw-a-clock.rs similarity index 100% rename from Task/Draw-a-clock/Rust/draw-a-clock.rust rename to Task/Draw-a-clock/Rust/draw-a-clock.rs diff --git a/Task/Draw-a-clock/Scheme/draw-a-clock.ss b/Task/Draw-a-clock/Scheme/draw-a-clock.scm similarity index 100% rename from Task/Draw-a-clock/Scheme/draw-a-clock.ss rename to Task/Draw-a-clock/Scheme/draw-a-clock.scm diff --git a/Task/Draw-a-clock/Tcl/draw-a-clock.tcl b/Task/Draw-a-clock/Tcl/draw-a-clock.tcl index 9facb5b050..807543cf21 100644 --- a/Task/Draw-a-clock/Tcl/draw-a-clock.tcl +++ b/Task/Draw-a-clock/Tcl/draw-a-clock.tcl @@ -13,9 +13,9 @@ proc updateClock t { set m [expr {$m + $s/60.0}] set h [expr {($h % 12 + $m/60.0) * 5}] foreach tag {hour minute second} value [list $h $m $s] len {50 80 80} { - .c coords $tag 100 100 \ - [expr {100 + $len*sin($value/30.0*3.14159)}] \ - [expr {100 - $len*cos($value/30.0*3.14159)}] + .c coords $tag 100 100 \ + [expr {100 + $len*sin($value/30.0*3.14159)}] \ + [expr {100 - $len*cos($value/30.0*3.14159)}] } } @@ -26,8 +26,8 @@ proc ticker {} { set t [clock seconds] after 250 ticker if {$t != $time} { - set time $t - updateClock $t + set time $t + updateClock $t } } ticker diff --git a/Task/Draw-a-clock/V-(Vlang)/draw-a-clock.v b/Task/Draw-a-clock/V-(Vlang)/draw-a-clock.v index dc23e77300..f09fa7b1a3 100644 --- a/Task/Draw-a-clock/V-(Vlang)/draw-a-clock.v +++ b/Task/Draw-a-clock/V-(Vlang)/draw-a-clock.v @@ -7,164 +7,164 @@ import math import time const ( - // All coordinates are designed for a clock size of this many pixel. - // You cannot change the size of the clock by adjusting this value. - design_size = 700 - center = 350 + // All coordinates are designed for a clock size of this many pixel. + // You cannot change the size of the clock by adjusting this value. + design_size = 700 + center = 350 - // Half the width of a tic-mark. - tw = 9 - // Height of a minute tic-mark. (hour is twice, 3-hour is thrice) - th = 25 - // Padding of tic-mark to window border - tp = 10 + // Half the width of a tic-mark. + tw = 9 + // Height of a minute tic-mark. (hour is twice, 3-hour is thrice) + th = 25 + // Padding of tic-mark to window border + tp = 10 - tic_color = gx.Color{ - r: 50 - g: 50 - b: 50 - } - hand_color = gx.black - second_hand_color = gx.red + tic_color = gx.Color{ + r: 50 + g: 50 + b: 50 + } + hand_color = gx.black + second_hand_color = gx.red ) struct App { - minutes_tic []f32 = [f32(center - tw), tp, center + tw, tp, center + tw, tp, center + tw, - tp + 1 * th, center - tw, tp + 1 * th] - hours_tic []f32 = [f32(center - tw), tp, center + tw, tp, center + tw, tp, center + tw, tp + 2 * th, - center - tw, tp + 2 * th] - hours3_tic []f32 = [f32(center - tw), tp, center + tw, tp, center + tw, tp, center + tw, tp + 3 * th, - center - tw, tp + 3 * th] + minutes_tic []f32 = [f32(center - tw), tp, center + tw, tp, center + tw, tp, center + tw, + tp + 1 * th, center - tw, tp + 1 * th] + hours_tic []f32 = [f32(center - tw), tp, center + tw, tp, center + tw, tp, center + tw, tp + 2 * th, + center - tw, tp + 2 * th] + hours3_tic []f32 = [f32(center - tw), tp, center + tw, tp, center + tw, tp, center + tw, tp + 3 * th, + center - tw, tp + 3 * th] - hour_hand []f32 = [f32(329), 161, 350, 140, 371, 161, 371, 413, 329, 413] - minute_hand []f32 = [f32(334.25), 40.25, 350, 24.5, 365.75, 40.25, 365.75, 427, 334.25, 427] - second_hand []f32 = [f32(345.8), 38.5, 350, 34.3, 354.2000, 38.5, 358.75, 427, 341.25, 427] - mut: - gg &gg.Context = unsafe { nil } - draw_flag bool = true - dpi_scale f32 = 1.0 + hour_hand []f32 = [f32(329), 161, 350, 140, 371, 161, 371, 413, 329, 413] + minute_hand []f32 = [f32(334.25), 40.25, 350, 24.5, 365.75, 40.25, 365.75, 427, 334.25, 427] + second_hand []f32 = [f32(345.8), 38.5, 350, 34.3, 354.2000, 38.5, 358.75, 427, 341.25, 427] + mut: + gg &gg.Context = unsafe { nil } + draw_flag bool = true + dpi_scale f32 = 1.0 } fn on_frame(mut app App) { - if !app.draw_flag { - return - } - app.gg.begin() + if !app.draw_flag { + return + } + app.gg.begin() - for i in 0 .. 60 { // draw minute tics - draw_convex_poly_rotate(mut app.gg, app.dpi_scale, app.minutes_tic, tic_color, - i * 6) - } - for i in 0 .. 12 { // hours - draw_convex_poly_rotate(mut app.gg, app.dpi_scale, app.hours_tic, tic_color, i * 30) - } - for i in 0 .. 4 { // 3 hours - draw_convex_poly_rotate(mut app.gg, app.dpi_scale, app.hours3_tic, tic_color, - i * 90) - } + for i in 0 .. 60 { // draw minute tics + draw_convex_poly_rotate(mut app.gg, app.dpi_scale, app.minutes_tic, tic_color, + i * 6) + } + for i in 0 .. 12 { // hours + draw_convex_poly_rotate(mut app.gg, app.dpi_scale, app.hours_tic, tic_color, i * 30) + } + for i in 0 .. 4 { // 3 hours + draw_convex_poly_rotate(mut app.gg, app.dpi_scale, app.hours3_tic, tic_color, + i * 90) + } - n := time.now() + n := time.now() - // draw hour hand - i := f32(n.hour) + f32(n.minute) / 60.0 - draw_convex_poly_rotate(mut app.gg, app.dpi_scale, app.hour_hand, hand_color, i * 30) + // draw hour hand + i := f32(n.hour) + f32(n.minute) / 60.0 + draw_convex_poly_rotate(mut app.gg, app.dpi_scale, app.hour_hand, hand_color, i * 30) - // draw minute hand - mut j := f32(n.minute) - if n.second == 59 { // make minute hand move smoothly - j += f32(math.sin(f32(n.microsecond) / 1e6 * math.pi / 2.0)) - } - draw_convex_poly_rotate(mut app.gg, app.dpi_scale, app.minute_hand, hand_color, j * 6) + // draw minute hand + mut j := f32(n.minute) + if n.second == 59 { // make minute hand move smoothly + j += f32(math.sin(f32(n.microsecond) / 1e6 * math.pi / 2.0)) + } + draw_convex_poly_rotate(mut app.gg, app.dpi_scale, app.minute_hand, hand_color, j * 6) - // draw second hand with smooth transition - k := f32(n.second) + f32(math.sin(f32(n.microsecond) / 1e6 * math.pi / 2.0)) - draw_convex_poly_rotate(mut app.gg, app.dpi_scale, app.second_hand, second_hand_color, - 0 + k * 6) + // draw second hand with smooth transition + k := f32(n.second) + f32(math.sin(f32(n.microsecond) / 1e6 * math.pi / 2.0)) + draw_convex_poly_rotate(mut app.gg, app.dpi_scale, app.second_hand, second_hand_color, + 0 + k * 6) - app.gg.end() + app.gg.end() } // Rotate a polygon round the centerpoint [manualfree] fn draw_convex_poly_rotate(mut ctx gg.Context, dpi_scale f32, points []f32, c gx.Color, angle f32) { - sa := math.sin(math.pi * angle / 180.0) - ca := math.cos(math.pi * angle / 180.0) + sa := math.sin(math.pi * angle / 180.0) + ca := math.cos(math.pi * angle / 180.0) - mut rotated_points := []f32{cap: points.len} - for i := 0; i < points.len / 2; i++ { - x := points[2 * i] - y := points[2 * i + 1] - xn := f32((x - center) * ca - (y - center) * sa) - yn := f32((x - center) * sa + (y - center) * ca) - rotated_points << (xn + center) * dpi_scale - rotated_points << (yn + center) * dpi_scale - } - ctx.draw_convex_poly(rotated_points, c) - unsafe { rotated_points.free() } + mut rotated_points := []f32{cap: points.len} + for i := 0; i < points.len / 2; i++ { + x := points[2 * i] + y := points[2 * i + 1] + xn := f32((x - center) * ca - (y - center) * sa) + yn := f32((x - center) * sa + (y - center) * ca) + rotated_points << (xn + center) * dpi_scale + rotated_points << (yn + center) * dpi_scale + } + ctx.draw_convex_poly(rotated_points, c) + unsafe { rotated_points.free() } } fn (mut app App) resize() { - size := gg.window_size() - // avoid calls when minimized - if size.width < 2 && size.height < 2 { - return - } - w := f32(size.width) / design_size - h := f32(size.height) / design_size - app.dpi_scale = if w < h { w } else { h } + size := gg.window_size() + // avoid calls when minimized + if size.width < 2 && size.height < 2 { + return + } + w := f32(size.width) / design_size + h := f32(size.height) / design_size + app.dpi_scale = if w < h { w } else { h } } fn on_event(e &gg.Event, mut app App) { - match e.typ { - .resized, .resumed { - app.resize() - } - .iconified { - app.draw_flag = false - } - .restored { - app.draw_flag = true - app.resize() - } - else { - if e.typ == .key_down { - match e.key_code { - .q { - println('Good bye.') - // do we need to free anything here? - app.gg.quit() - } - else {} - } - } - } - } + match e.typ { + .resized, .resumed { + app.resize() + } + .iconified { + app.draw_flag = false + } + .restored { + app.draw_flag = true + app.resize() + } + else { + if e.typ == .key_down { + match e.key_code { + .q { + println('Good bye.') + // do we need to free anything here? + app.gg.quit() + } + else {} + } + } + } + } } fn on_init(mut app App) { - app.resize() + app.resize() } fn main() { - println("Press 'q' to quit.") - mut font_path := os.resource_abs_path(os.join_path('..', 'assets', 'fonts', 'RobotoMono-Regular.ttf')) - $if android { - font_path = 'fonts/RobotoMono-Regular.ttf' - } + println("Press 'q' to quit.") + mut font_path := os.resource_abs_path(os.join_path('..', 'assets', 'fonts', 'RobotoMono-Regular.ttf')) + $if android { + font_path = 'fonts/RobotoMono-Regular.ttf' + } - mut app := &App{} + mut app := &App{} - app.gg = gg.new_context( - width: design_size - height: design_size - window_title: 'Clock!' - bg_color: gx.white - user_data: app - frame_fn: on_frame - event_fn: on_event - init_fn: on_init - font_path: font_path - ) + app.gg = gg.new_context( + width: design_size + height: design_size + window_title: 'Clock!' + bg_color: gx.white + user_data: app + frame_fn: on_frame + event_fn: on_event + init_fn: on_init + font_path: font_path + ) - app.gg.run() + app.gg.run() } diff --git a/Task/Draw-a-clock/VBScript/draw-a-clock.vb b/Task/Draw-a-clock/VBScript/draw-a-clock.vbs similarity index 100% rename from Task/Draw-a-clock/VBScript/draw-a-clock.vb rename to Task/Draw-a-clock/VBScript/draw-a-clock.vbs diff --git a/Task/Draw-a-clock/XPL0/draw-a-clock.xpl0 b/Task/Draw-a-clock/XPL0/draw-a-clock.xpl0 new file mode 100644 index 0000000000..bc2a9acaa1 --- /dev/null +++ b/Task/Draw-a-clock/XPL0/draw-a-clock.xpl0 @@ -0,0 +1,48 @@ +include xpllib; \for DrawCircle, DrawLine, LineWidth, MovePen, Deg2Rad +def X0=400, Y0=300; \center coordinate +int Hour, Minute, Second; + +proc DrawHand(Angle, Length, Width, Color); +real Angle, Length; +int Width, Color; +int X, Y; +[X:= fix(Length*Sin(Angle)); + Y:= fix(Length*Cos(Angle)); +LineWidth:= Width; +MovePen(X0, Y0); +DrawLine(X0+X, Y0-Y, Color); +]; + +proc DrawClock; \Show analog clock with current time +real Angle; +int N, X, Y; +[DrawCircle(X0, Y0, 299, LCyan, true); +Angle:= 0.; +for N:= 0 to 59 do \draw tick marks + [X:= fix(260.*Cos(Angle)); + Y:= fix(260.*Sin(Angle)); + DrawCircle(X+X0, Y+Y0, if rem(N/5) then 4 else 8, Black, true); + Angle:= Angle + 6.*Deg2Rad; + ]; +Angle:= float((Hour*60+Minute)/2) * Deg2Rad; +DrawHand(Angle, 210., 8, Black); +Angle:= float((Minute*60+Second)/10) * Deg2Rad; +DrawHand(Angle, 240., 5, Black); +Angle:= float(Second*6) * Deg2Rad; +DrawHand(Angle, 260., 3, LRed); +DrawCircle(X0, Y0, 8, Black, true); +]; + +int Second0; +char Time; +[SetVid($103); \800x600x8 +InitDraw; +repeat Time:= GetDateTime; + Hour:= Time(3); + if Hour>=12 then Hour:= Hour-12; + Minute:= Time(4); + Second:= Time(5); + if Second # Second0 then + [Second0:= Second; DrawClock]; +until KeyHit; +] diff --git a/Task/Draw-a-clock/Yabasic/draw-a-clock-2.basic b/Task/Draw-a-clock/Yabasic/draw-a-clock-2.basic index fa5e883c66..b45d5ff708 100644 --- a/Task/Draw-a-clock/Yabasic/draw-a-clock-2.basic +++ b/Task/Draw-a-clock/Yabasic/draw-a-clock-2.basic @@ -27,142 +27,142 @@ clockface() do - hour = val(mid$(time$,1,2)) - mins = val(mid$(time$,4,2)) - sec = val(mid$(time$,7,2)) - - updatehand("sec") - updatehand("mins") - updatehand("hour") + hour = val(mid$(time$,1,2)) + mins = val(mid$(time$,4,2)) + sec = val(mid$(time$,7,2)) - pause .25 + updatehand("sec") + updatehand("mins") + updatehand("hour") + + pause .25 loop sub updatehand(hand$) - - switch(hand$) - case "sec" - h_len = shand - angle = sec * 6 - width = 6 - color 255,0,0 - ox = osx - oy = osy - oxm1 = osxm1 - oxm2 = osxm2 - oym1 = osym1 - oym2 = osym2 - break - case "mins" - h_len = mhand - angle = mins * 6 + int(sec/10) - width = 12 - color 0,255,0 - ox = omx - oy = omy - oxm1 = omxm1 - oxm2 = omxm2 - oym1 = omym1 - oym2 = omym2 - break - case "hour" - h_len = hhand - angle = ((hour * 30) + (minutes / 12) * 6) + int(mins/2) - width = 15 - color 0,0,255 - ox = ohx - oy = ohy - oxm1 = ohxm1 - oxm2 = ohxm2 - oym1 = ohym1 - oym2 = ohym2 - break - end switch - h_angle1 = angle - width - if h_angle1 < 0 then - h_angle1 = h_angle1 + 360 - endif - h_angle1 = h_angle1 / DEG_PER_RAD - - h_angle2 = angle + width - if h_angle2 > 360 then - h_angle2 = h_angle2 - 360 - endif - h_angle2 = h_angle2 / DEG_PER_RAD - - angle = angle / DEG_PER_RAD - - x = (hx + (sin(angle) * h_len)) - xm1 = (hx + (sin(h_angle1) * int(h_len * .2))) - xm2 = (hx + (sin(h_angle2) * int(h_len * .2))) + switch(hand$) + case "sec" + h_len = shand + angle = sec * 6 + width = 6 + color 255,0,0 + ox = osx + oy = osy + oxm1 = osxm1 + oxm2 = osxm2 + oym1 = osym1 + oym2 = osym2 + break + case "mins" + h_len = mhand + angle = mins * 6 + int(sec/10) + width = 12 + color 0,255,0 + ox = omx + oy = omy + oxm1 = omxm1 + oxm2 = omxm2 + oym1 = omym1 + oym2 = omym2 + break + case "hour" + h_len = hhand + angle = ((hour * 30) + (minutes / 12) * 6) + int(mins/2) + width = 15 + color 0,0,255 + ox = ohx + oy = ohy + oxm1 = ohxm1 + oxm2 = ohxm2 + oym1 = ohym1 + oym2 = ohym2 + break + end switch - y = (hy - (cos(angle) * h_len)) - ym1 = (hy - (cos(h_angle1) * int(h_len * .2))) - ym2 = (hy - (cos(h_angle2) * int(h_len * .2))) + h_angle1 = angle - width + if h_angle1 < 0 then + h_angle1 = h_angle1 + 360 + endif + h_angle1 = h_angle1 / DEG_PER_RAD - clear line hx,hy,oxm1,oym1 - clear line hx,hy,oxm2,oym2 - clear line oxm1,oym1,ox,oy - clear line oxm2,oym2,ox,oy - line hx,hy,xm1,ym1 - line hx,hy,xm2,ym2 - line xm1,ym1,x,y - line xm2,ym2,x,y - - REM save off the old vals - switch(hand$) - case "sec" - osx = x - osy = y - osxm1 = xm1 - osxm2 = xm2 - osym1 = ym1 - osym2 = ym2 - break - case "mins" - omx = x - omy = y - omxm1 = xm1 - omxm2 = xm2 - omym1 = ym1 - omym2 = ym2 - break - case "hour" - ohx = x - ohy = y - ohxm1 = xm1 - ohxm2 = xm2 - ohym1 = ym1 - ohym2 = ym2 - break - end switch + h_angle2 = angle + width + if h_angle2 > 360 then + h_angle2 = h_angle2 - 360 + endif + h_angle2 = h_angle2 / DEG_PER_RAD + + angle = angle / DEG_PER_RAD + + x = (hx + (sin(angle) * h_len)) + xm1 = (hx + (sin(h_angle1) * int(h_len * .2))) + xm2 = (hx + (sin(h_angle2) * int(h_len * .2))) + + y = (hy - (cos(angle) * h_len)) + ym1 = (hy - (cos(h_angle1) * int(h_len * .2))) + ym2 = (hy - (cos(h_angle2) * int(h_len * .2))) + + clear line hx,hy,oxm1,oym1 + clear line hx,hy,oxm2,oym2 + clear line oxm1,oym1,ox,oy + clear line oxm2,oym2,ox,oy + line hx,hy,xm1,ym1 + line hx,hy,xm2,ym2 + line xm1,ym1,x,y + line xm2,ym2,x,y + + REM save off the old vals + switch(hand$) + case "sec" + osx = x + osy = y + osxm1 = xm1 + osxm2 = xm2 + osym1 = ym1 + osym2 = ym2 + break + case "mins" + omx = x + omy = y + omxm1 = xm1 + omxm2 = xm2 + omym1 = ym1 + omym2 = ym2 + break + case "hour" + ohx = x + ohy = y + ohxm1 = xm1 + ohxm2 = xm2 + ohym1 = ym1 + ohym2 = ym2 + break + end switch end sub sub clockface() - circle hx,hy,radius - - htick = radius / 10 - mtick = htick / 2 - - for z=0 to 360 step 6 - REM Begin at zero deg and stop before 360 deg + circle hx,hy,radius - REM draw the hour markers - angle = z - angle = angle / DEG_PER_RAD - x2 = (hx + (sin(angle) * radius)) - y2 = (hy - (cos(angle) * radius)) - if mod(z,30) = 0 then - tick = htick - else - tick = mtick - endif - x3 = (hx + (sin(angle) * (radius - tick))) - y3 = (hy - (cos(angle) * (radius - tick))) - color 255,0,0 - line x2,y2,x3,y3 - color 0,0,0 - next z + htick = radius / 10 + mtick = htick / 2 + + for z=0 to 360 step 6 + REM Begin at zero deg and stop before 360 deg + + REM draw the hour markers + angle = z + angle = angle / DEG_PER_RAD + x2 = (hx + (sin(angle) * radius)) + y2 = (hy - (cos(angle) * radius)) + if mod(z,30) = 0 then + tick = htick + else + tick = mtick + endif + x3 = (hx + (sin(angle) * (radius - tick))) + y3 = (hy - (cos(angle) * (radius - tick))) + color 255,0,0 + line x2,y2,x3,y3 + color 0,0,0 + next z end sub diff --git a/Task/Draw-a-clock/Zkl/draw-a-clock.zkl b/Task/Draw-a-clock/Zkl/draw-a-clock.zkl index 9819c7b3a4..50f06ab266 100644 --- a/Task/Draw-a-clock/Zkl/draw-a-clock.zkl +++ b/Task/Draw-a-clock/Zkl/draw-a-clock.zkl @@ -4,7 +4,7 @@ var while(True){ x:=Time.Date.ctime()[11,8] // or Time.Date.to24HString() (no seconds) .pump(List,fcn(n){ n.toAsc() - 0x30 }); //-->L(2,3,10,4,3,10,5,2) - print("\e[H\e[J"); // home and clear screen on ANSI terminals + print("\e[H\e[J"); // home and clear screen on ANSI terminals println(x.pump(String,t.get),"\n",x.pump(String,b.get)); Atomic.sleep(1); } diff --git a/Task/Draw-a-cuboid/ALGOL-68/draw-a-cuboid.alg b/Task/Draw-a-cuboid/ALGOL-68/draw-a-cuboid.alg new file mode 100644 index 0000000000..a10b794b17 --- /dev/null +++ b/Task/Draw-a-cuboid/ALGOL-68/draw-a-cuboid.alg @@ -0,0 +1,58 @@ +BEGIN # draw some cuboids using ASCII art # + + # draws a cuboid standing on one edge using ASCII art # + PROC aa cuboid = ( INT h, w, l )VOID: + BEGIN + # top line # + TO l DO print( ( " " ) ) OD; + TO w + 1 DO print( ( "_" ) ) OD; + print( ( newline ) ); + # rest of the top face and part of the visible side # + INT face width := 0; + INT edge pos := 0; + FOR i TO l DO + TO l - i DO print( ( " " ) ) OD; + print( ( "/" ) ); + TO w DO print( ( IF i = l THEN "_" ELSE " " FI ) ) OD; + print( ( "/" ) ); + edge pos +:= 1; + IF edge pos <= h THEN + # drsw the back edge # + face width := 2 * ( edge pos - 1 ); + TO face width DO print( ( " " ) ) OD; + print( ( "\" ) ) + ELSE + # draw the bottom edge # + TO face width + 1 DO print( ( " " ) ) OD; + print( ( "/" ) ) + FI; + print( ( newline ) ) + OD; + # other vidible face # + FOR i TO h DO + TO i - 1 DO print( ( " " ) ) OD; + print( ( "\" ) ); + TO w DO print( ( IF i = h THEN "_" ELSE " " FI ) ) OD; + print( ( "\" ) ); + edge pos +:= 1; + IF edge pos <= h THEN + # drsw the back edge # + TO face width + 1 DO print( ( " " ) ) OD; + print( ( "\" ) ) + ELSE + # draw the bottom edge # + TO face width DO print( ( " " ) ) OD; + face width -:= 2; + print( ( "/" ) ) + FI; + print( ( newline ) ) + OD + + END # aa cuboid # ; + + aa cuboid( 3, 2, 4 ); + aa cuboid( 4, 3, 2 ); + aa cuboid( 2, 4, 3 ); + aa cuboid( 2, 3, 4 ) + +END diff --git a/Task/Draw-a-cuboid/Ada/draw-a-cuboid.ada b/Task/Draw-a-cuboid/Ada/draw-a-cuboid.adb similarity index 100% rename from Task/Draw-a-cuboid/Ada/draw-a-cuboid.ada rename to Task/Draw-a-cuboid/Ada/draw-a-cuboid.adb diff --git a/Task/Draw-a-cuboid/Delphi/draw-a-cuboid.delphi b/Task/Draw-a-cuboid/Delphi/draw-a-cuboid.pas similarity index 100% rename from Task/Draw-a-cuboid/Delphi/draw-a-cuboid.delphi rename to Task/Draw-a-cuboid/Delphi/draw-a-cuboid.pas diff --git a/Task/Draw-a-cuboid/EasyLang/draw-a-cuboid.easy b/Task/Draw-a-cuboid/EasyLang/draw-a-cuboid.easy index 7a8d34b01a..382a35c46e 100644 --- a/Task/Draw-a-cuboid/EasyLang/draw-a-cuboid.easy +++ b/Task/Draw-a-cuboid/EasyLang/draw-a-cuboid.easy @@ -1,14 +1,12 @@ node[][] = [ [ -1 -2 -2 ] [ -1 -2 1 ] [ -1 2 -2 ] [ -1 2 1 ] [ 1 -2 -2 ] [ 1 -2 1 ] [ 1 2 -2 ] [ 1 2 1 ] ] edge[][] = [ [ 1 2 ] [ 2 4 ] [ 4 3 ] [ 3 1 ] [ 5 6 ] [ 6 8 ] [ 8 7 ] [ 7 5 ] [ 1 5 ] [ 2 6 ] [ 3 7 ] [ 4 8 ] ] # -proc scale f . . - for i = 1 to len node[][] - for d = 1 to 3 - node[i][d] *= f - . +proc scale f . + for i = 1 to len node[][] : for d = 1 to 3 + node[i][d] *= f . . -proc rotate angx angy . . +proc rotate angx angy . sinx = sin angx cosx = cos angx siny = sin angy @@ -24,10 +22,9 @@ proc rotate angx angy . . . . len nd[] 3 -proc draw . . - clear - move 2 2 - text "Arrow keys to rotate" +proc draw . + gclear + gtext 2 2 "Arrow keys to rotate" m = 99999 mi = -1 for i = 1 to len node[][] @@ -46,24 +43,21 @@ proc draw . . ix += 1 . . - for ni = 1 to len nd[] - for i = 1 to len edge[][] - if edge[i][1] = nd[ni] or edge[i][2] = nd[ni] - x1 = node[edge[i][1]][1] - y1 = node[edge[i][1]][2] - x2 = node[edge[i][2]][1] - y2 = node[edge[i][2]][2] - move x1 + 50 y1 + 50 - line x2 + 50 y2 + 50 - . + for ni = 1 to len nd[] : for i = 1 to len edge[][] + if edge[i][1] = nd[ni] or edge[i][2] = nd[ni] + x1 = node[edge[i][1]][1] + y1 = node[edge[i][1]][2] + x2 = node[edge[i][2]][1] + y2 = node[edge[i][2]][2] + gline x1 + 50 y1 + 50 x2 + 50 y2 + 50 . . . -textsize 3 +gtextsize 3 scale 15 rotate 45 45 draw -on key +on key_down if keybkey = "ArrowUp" rotate 0 1 elif keybkey = "ArrowDown" diff --git a/Task/Draw-a-cuboid/Elixir/draw-a-cuboid.elixir b/Task/Draw-a-cuboid/Elixir/draw-a-cuboid.ex similarity index 100% rename from Task/Draw-a-cuboid/Elixir/draw-a-cuboid.elixir rename to Task/Draw-a-cuboid/Elixir/draw-a-cuboid.ex diff --git a/Task/Draw-a-cuboid/Jq/draw-a-cuboid.jq b/Task/Draw-a-cuboid/Jq/draw-a-cuboid.jq new file mode 100644 index 0000000000..6f59cbd05c --- /dev/null +++ b/Task/Draw-a-cuboid/Jq/draw-a-cuboid.jq @@ -0,0 +1,27 @@ +def cubLine($n; $dx; $dy; $cde): + def s: if . == 0 then "" else . * " " end; # for jaq + reduce range(1; 9*$dx) as $d ("\($n|s)\($cde[0:1])"; + . + $cde[1:2] ) + + $cde[0:1] + + ("\($dy|s)\($cde[2:])"); + +def cuboid($dx; $dy; $dz): + "cuboid \($dx) \($dy) \($dz):", + # top + cubLine($dy+1; $dx; 0; "+-"), + # top and side + (range(1; 1+$dy) as $i | cubLine($dy-$i+1; $dx; $i-1; "/ |")), + cubLine(0; $dx; $dy; "+-|"), + # front and side + (range(1; 4*$dz -$dy-2) as $i | cubLine(0; $dx; $dy; "| |")), + cubLine(0; $dx; $dy; "| +"), + # front and bottom + (range(1; 1+$dy) as $i | cubLine(0; $dx; $dy-$i; "| /")), + # bottom + cubLine(0; $dx; 0; "+-\n"); + +cuboid(2; 3; 4), +"", +cuboid(1; 1; 1), +"", +cuboid(6; 2; 1) diff --git a/Task/Draw-a-cuboid/Julia/draw-a-cuboid.julia b/Task/Draw-a-cuboid/Julia/draw-a-cuboid.jl similarity index 100% rename from Task/Draw-a-cuboid/Julia/draw-a-cuboid.julia rename to Task/Draw-a-cuboid/Julia/draw-a-cuboid.jl diff --git a/Task/Draw-a-cuboid/Kotlin/draw-a-cuboid.kotlin b/Task/Draw-a-cuboid/Kotlin/draw-a-cuboid.kts similarity index 100% rename from Task/Draw-a-cuboid/Kotlin/draw-a-cuboid.kotlin rename to Task/Draw-a-cuboid/Kotlin/draw-a-cuboid.kts diff --git a/Task/Draw-a-cuboid/Locomotive-Basic/draw-a-cuboid.basic b/Task/Draw-a-cuboid/Locomotive-Basic/draw-a-cuboid.basic new file mode 100644 index 0000000000..c7b41f6d6b --- /dev/null +++ b/Task/Draw-a-cuboid/Locomotive-Basic/draw-a-cuboid.basic @@ -0,0 +1,6 @@ +10 mode 2: origin 100,0: w=120: height=w*1.5: depth=w*2 +20 x=80: y=10 +30 plot x,y +40 drawr 0,height: drawr w,0: drawr 0,-height: drawr -w,0: rem front +50 plot x,y+height: drawr depth/2,height: drawr w,0: drawr 0,-height: drawr -w,-height +60 plot x+w,y+height: drawr depth/2,height diff --git a/Task/Draw-a-cuboid/Odin/draw-a-cuboid.odin b/Task/Draw-a-cuboid/Odin/draw-a-cuboid.odin new file mode 100644 index 0000000000..aa3dcf8563 --- /dev/null +++ b/Task/Draw-a-cuboid/Odin/draw-a-cuboid.odin @@ -0,0 +1,35 @@ +package cuboid + +import rl "vendor:raylib" + +main :: proc() { + rl.InitWindow(640, 480, "Rosetta Code - draw a cuboid") + + camera: rl.Camera3D + camera.fovy = 45 + camera.position = {0, 5, 10} + camera.up = {0, 1, 0} + + for !rl.WindowShouldClose() { + rl.UpdateCamera(&camera, .ORBITAL) + + rl.BeginDrawing() + + rl.ClearBackground(rl.RAYWHITE) + + rl.BeginMode3D(camera) + + rl.DrawGrid(25, .5) + + cube := rl.Vector3 {2, 3, 4} + + rl.DrawCubeV({}, cube, rl.LIME) + rl.DrawCubeWiresV({}, cube, rl.DARKGREEN) + + rl.EndMode3D() + + rl.EndDrawing() + } + + rl.CloseWindow() +} diff --git a/Task/Draw-a-cuboid/PL-M/draw-a-cuboid.plm b/Task/Draw-a-cuboid/PL-M/draw-a-cuboid.plm new file mode 100644 index 0000000000..09220af2ea --- /dev/null +++ b/Task/Draw-a-cuboid/PL-M/draw-a-cuboid.plm @@ -0,0 +1,81 @@ +100H: /* DRAW SOME CUBOIDS USING ASCII ART */ + + /* 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$NL: PROCEDURE; CALL PR$CHAR( 0DH ); CALL PR$CHAR( 0AH ); END; + + /* TASK */ + + /* DRAWS A CUBOID STANDING ON ONE EDGE USING ASCII ART */ + DRAW$CUBOID: PROCEDURE( H, W, L ); + DECLARE ( H, W, L ) BYTE; + DECLARE ( I, J, FACE$WIDTH, EDGE$POS ) BYTE; + + BACKSLASH: PROCEDURE; CALL PR$CHAR( 92 ); END; /* PRINTS A BACKSLASH */ + REPEAT$CHAR: PROCEDURE( CH, COUNT ); /* PRINTS CH COUNT TIMES */ + DECLARE ( CH, COUNT ) BYTE; + DECLARE I BYTE; + IF COUNT > 0 THEN DO; + DO I = 1 TO COUNT; CALL PR$CHAR( CH ); END; + END; + END REPEAT$CHAR; + UNDERSCORES: PROCEDURE( COUNT ); /* PRINTS COUNT UNDERSCORES */ + DECLARE COUNT BYTE; + CALL REPEAT$CHAR( 95, COUNT ); + END UNDERSCORES; + + /* TOP LINE */ + CALL REPEAT$CHAR( ' ', L ); CALL UNDERSCORES( W + 1 ); CALL PR$NL; + /* REST OF THE TOP FACE AND PART OF THE VISIBLE SIDE */ + FACE$WIDTH = 0; + EDGE$POS = 0; + DO I = 1 TO L; + CALL REPEAT$CHAR( ' ', L - I ); + CALL PR$CHAR( '/' ); + IF I = L THEN CALL UNDERSCORES( W ); + ELSE CALL REPEAT$CHAR( ' ', W ); + CALL PR$CHAR( '/' ); + EDGE$POS = EDGE$POS + 1; + IF EDGE$POS <= H THEN DO; + /* DRAW THE BACK EDGE */ + FACE$WIDTH = 2 * ( EDGE$POS - 1 ); + CALL REPEAT$CHAR( ' ', FACE$WIDTH ); + CALL BACKSLASH; + END; + ELSE DO; + /* DRAW THE BOTTOM EDGE AND THE MORE OF THE VISIBLE SIDE */ + CALL REPEAT$CHAR( ' ', FACE$WIDTH + 1 ); + CALL PR$CHAR( '/' ); + END; + CALL PR$NL; + END; + /* OTHER VISIBLE FACE */ + DO I = 1 TO H; + CALL REPEAT$CHAR( ' ', I - 1 ); + CALL BACKSLASH; + IF I = H THEN CALL UNDERSCORES( W ); + ELSE CALL REPEAT$CHAR( ' ', W ); + CALL BACKSLASH; + EDGE$POS = EDGE$POS + 1; + IF EDGE$POS <= H THEN DO; + /* DRAW THE BACK EDGE */ + CALL REPEAT$CHAR( ' ', FACE$WIDTH + 1 ); + CALL BACKSLASH; + END; + ELSE DO; + /* DRAW THE BOTTOM EDGE */ + CALL REPEAT$CHAR( ' ', FACE$WIDTH ); + FACE$WIDTH = FACE$WIDTH - 2; + CALL PR$CHAR( '/' ); + END; + CALL PR$NL; + END; + END DRAW$CUBOID; + + CALL DRAW$CUBOID( 3, 2, 4 ); + CALL DRAW$CUBOID( 4, 3, 2 ); + CALL DRAW$CUBOID( 2, 4, 3 ); + CALL DRAW$CUBOID( 2, 3, 4 ); + +EOF diff --git a/Task/Draw-a-cuboid/R/draw-a-cuboid.r b/Task/Draw-a-cuboid/R/draw-a-cuboid.r new file mode 100644 index 0000000000..ea0ab1b2f8 --- /dev/null +++ b/Task/Draw-a-cuboid/R/draw-a-cuboid.r @@ -0,0 +1,14 @@ +cuboid <- function(w, h, d){ + plot(x=NA, xlim=c(0,(w+d)*sqrt(3)/2), ylim=c(0,h+(w+d)/2), xlab=NA, ylab=NA, asp=1) + polygon(x=c(0, w*sqrt(3)/2, w*sqrt(3)/2, 0), + y=c(w/2, 0, h, h+w/2), + col="red") + polygon(x=c(0, w*sqrt(3)/2, (w+d)*sqrt(3)/2, d*sqrt(3)/2), + y=c(h+w/2, h, h+d/2, h+(w+d)/2), + col="blue") + polygon(x=c(w*sqrt(3)/2, (w+d)*sqrt(3)/2, (w+d)*sqrt(3)/2, w*sqrt(3)/2), + y=c(0, d/2, h+d/2, h), + col="yellow") +} + +cuboid(2, 3, 4) diff --git a/Task/Draw-a-cuboid/V-(Vlang)/draw-a-cuboid.v b/Task/Draw-a-cuboid/V-(Vlang)/draw-a-cuboid.v new file mode 100644 index 0000000000..19ec039f32 --- /dev/null +++ b/Task/Draw-a-cuboid/V-(Vlang)/draw-a-cuboid.v @@ -0,0 +1,32 @@ +fn cuboid(dx int, dy int, dz int) { + println("cuboid $dx $dy $dz:") + cub_line(dy + 1, dx, 0, "+-|") + for i in 1 .. dy + 1 { + cub_line(dy - i + 1, dx, i - 1, "/ |") + } + cub_line(0, dx, dy, "+-|") + for _ in 0 .. (4 * dz - dy - 2) { + cub_line(0, dx, dy, "| |") + } + cub_line(0, dx, dy, "| +") + for i in 1 .. dy + 1 { + cub_line(0, dx, dy - i, "| /") + } + last_line := "+-" + print("".repeat(1) + last_line[0].ascii_str()) + println(last_line[1].ascii_str().repeat(9 * dx - 1) + last_line[0].ascii_str()) +} + +fn cub_line(nir int, dx int, dy int, cde string) { + if cde.len < 3 { return } + print(" ".repeat(nir + 1) + cde[0].ascii_str()) + print(cde[1].ascii_str().repeat(9 * dx - 1)) + print(cde[0].ascii_str()) + println(" ".repeat(dy + 1) + cde[2].ascii_str()) +} + +fn main() { + cuboid(2, 3, 4) + cuboid(1, 1, 1) + cuboid(6, 2, 1) +} diff --git a/Task/Draw-a-cuboid/VBScript/draw-a-cuboid.vb b/Task/Draw-a-cuboid/VBScript/draw-a-cuboid.vbs similarity index 100% rename from Task/Draw-a-cuboid/VBScript/draw-a-cuboid.vb rename to Task/Draw-a-cuboid/VBScript/draw-a-cuboid.vbs diff --git a/Task/Draw-a-pixel/ARM-Assembly/draw-a-pixel.arm b/Task/Draw-a-pixel/ARM-Assembly/draw-a-pixel.arm index 78039d03f4..1e582d7d8b 100644 --- a/Task/Draw-a-pixel/ARM-Assembly/draw-a-pixel.arm +++ b/Task/Draw-a-pixel/ARM-Assembly/draw-a-pixel.arm @@ -47,7 +47,7 @@ szTexte2: .asciz "Press q for close window or clic X in system me szLibDW: .asciz "WM_DELETE_WINDOW" @ special label for correct close error /*************************************************/ -szMessErr: .ascii "Error code hexa : " +szMessErr: .ascii "Error code hexa : " sHexa: .space 9,' ' .ascii " decimal : " sDeci: .space 15,' ' @@ -441,7 +441,7 @@ conversion16: and r0,r3,r4 @value register and mask lsr r0,r2 @ move right cmp r0,#10 @ compare value - addlt r0,#48 @ <10 ->digit + addlt r0,#48 @ <10 ->digit addge r0,#55 @ >10 ->letter A-F strb r0,[r1],#1 @ store digit on area and + 1 in area address lsr r4,#4 @ shift mask 4 positions @@ -507,7 +507,7 @@ divisionpar10U: sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) pop {r2,r3,r4,lr} bx lr @ leave function -iMagicNumber: .int 0xCCCCCCCD +iMagicNumber: .int 0xCCCCCCCD /***************************************************/ /* integer division unsigned */ /***************************************************/ diff --git a/Task/Draw-a-pixel/Ada/draw-a-pixel.ada b/Task/Draw-a-pixel/Ada/draw-a-pixel.adb similarity index 100% rename from Task/Draw-a-pixel/Ada/draw-a-pixel.ada rename to Task/Draw-a-pixel/Ada/draw-a-pixel.adb diff --git a/Task/Draw-a-pixel/AutoHotkey/draw-a-pixel.ahk b/Task/Draw-a-pixel/AutoHotkey/draw-a-pixel.ahk index 86bccdddd4..aa35877040 100644 --- a/Task/Draw-a-pixel/AutoHotkey/draw-a-pixel.ahk +++ b/Task/Draw-a-pixel/AutoHotkey/draw-a-pixel.ahk @@ -4,9 +4,9 @@ Gui, Show, w320 h240, Example return CreatePixel(Color, Handle) { - VarSetCapacity(BMBITS, 4, 0), Numput("0x" . Color, &BMBITS, 0, "UInt") - hBM := DllCall("Gdi32.dll\CreateBitmap", "Int", 1, "Int", 1, "UInt", 1, "UInt", 24, "Ptr", 0, "Ptr") - hBM := DllCall("User32.dll\CopyImage", "Ptr", hBM, "UInt", 0, "Int", 0, "Int", 0, "UInt", 0x2008, "Ptr") - DllCall("Gdi32.dll\SetBitmapBits", "Ptr", hBM, "UInt", 3, "Ptr", &BMBITS) - DllCall("User32.dll\SendMessage", "Ptr", Handle, "UInt", 0x172, "Ptr", 0, "Ptr", hBM) + VarSetCapacity(BMBITS, 4, 0), Numput("0x" . Color, &BMBITS, 0, "UInt") + hBM := DllCall("Gdi32.dll\CreateBitmap", "Int", 1, "Int", 1, "UInt", 1, "UInt", 24, "Ptr", 0, "Ptr") + hBM := DllCall("User32.dll\CopyImage", "Ptr", hBM, "UInt", 0, "Int", 0, "Int", 0, "UInt", 0x2008, "Ptr") + DllCall("Gdi32.dll\SetBitmapBits", "Ptr", hBM, "UInt", 3, "Ptr", &BMBITS) + DllCall("User32.dll\SendMessage", "Ptr", Handle, "UInt", 0x172, "Ptr", 0, "Ptr", hBM) } diff --git a/Task/Draw-a-pixel/C/draw-a-pixel-1.c b/Task/Draw-a-pixel/C/draw-a-pixel-1.c index a9ce8075bf..3bbd254b80 100644 --- a/Task/Draw-a-pixel/C/draw-a-pixel-1.c +++ b/Task/Draw-a-pixel/C/draw-a-pixel-1.c @@ -2,11 +2,11 @@ int main() { - initwindow(320,240,"Red Pixel"); - - putpixel(100,100,RED); - - getch(); - - return 0; + initwindow(320,240,"Red Pixel"); + + putpixel(100,100,RED); + + getch(); + + return 0; } diff --git a/Task/Draw-a-pixel/C/draw-a-pixel-2.c b/Task/Draw-a-pixel/C/draw-a-pixel-2.c index e6e3a806bd..41626fc1f6 100644 --- a/Task/Draw-a-pixel/C/draw-a-pixel-2.c +++ b/Task/Draw-a-pixel/C/draw-a-pixel-2.c @@ -6,66 +6,66 @@ int main(void) - { - Atom wm_both_protocols[1]; - Atom wm_delete; - Atom wm_protocols; - Display *display; - GC gc; - Window root; - Window window; - XEvent event; - XSetWindowAttributes attr; - int more = 1; + { + Atom wm_both_protocols[1]; + Atom wm_delete; + Atom wm_protocols; + Display *display; + GC gc; + Window root; + Window window; + XEvent event; + XSetWindowAttributes attr; + int more = 1; - display = XOpenDisplay(NULL); - if(display == NULL) - { - fprintf(stderr,"Error: The display cannot be opened\n"); - exit(1); - } - root = DefaultRootWindow(display); - wm_delete = XInternAtom(display, "WM_DELETE_WINDOW", False); - wm_protocols = XInternAtom(display, "WM_PROTOCOLS", False); - attr.background_pixel = 0x000000; - attr.event_mask = ExposureMask; - window = XCreateWindow(display, root, - 0, 0, 320, 240, 0, - CopyFromParent, InputOutput, CopyFromParent, - CWBackPixel | CWEventMask, - &attr - ); - XStoreName(display, window, "Draw a Pixel"); - wm_both_protocols[0] = wm_delete; - XSetWMProtocols(display, window, wm_both_protocols, 1); - gc = XCreateGC(display, window, 0, NULL); - XSetForeground(display, gc, 0xFF0000); - XMapWindow(display, window); + display = XOpenDisplay(NULL); + if(display == NULL) + { + fprintf(stderr,"Error: The display cannot be opened\n"); + exit(1); + } + root = DefaultRootWindow(display); + wm_delete = XInternAtom(display, "WM_DELETE_WINDOW", False); + wm_protocols = XInternAtom(display, "WM_PROTOCOLS", False); + attr.background_pixel = 0x000000; + attr.event_mask = ExposureMask; + window = XCreateWindow(display, root, + 0, 0, 320, 240, 0, + CopyFromParent, InputOutput, CopyFromParent, + CWBackPixel | CWEventMask, + &attr + ); + XStoreName(display, window, "Draw a Pixel"); + wm_both_protocols[0] = wm_delete; + XSetWMProtocols(display, window, wm_both_protocols, 1); + gc = XCreateGC(display, window, 0, NULL); + XSetForeground(display, gc, 0xFF0000); + XMapWindow(display, window); - while(more) - { - XNextEvent(display, &event); - switch(event.type) - { - case Expose: - XDrawPoint(display, window, gc, 100, 100); - break; + while(more) + { + XNextEvent(display, &event); + switch(event.type) + { + case Expose: + XDrawPoint(display, window, gc, 100, 100); + break; - case ClientMessage: // for close request from WM - if(event.xclient.window == window && - event.xclient.message_type == wm_protocols && - event.xclient.format == 32 && - event.xclient.data.l[0] == wm_delete) - { - more = 0; - } - break; + case ClientMessage: // for close request from WM + if(event.xclient.window == window && + event.xclient.message_type == wm_protocols && + event.xclient.format == 32 && + event.xclient.data.l[0] == wm_delete) + { + more = 0; + } + break; - default: - printf("unexpected event.type %d\n", event.type);; - } - } + default: + printf("unexpected event.type %d\n", event.type);; + } + } - XCloseDisplay(display); - exit(0); - } + XCloseDisplay(display); + exit(0); + } diff --git a/Task/Draw-a-pixel/Delphi/draw-a-pixel.delphi b/Task/Draw-a-pixel/Delphi/draw-a-pixel.pas similarity index 100% rename from Task/Draw-a-pixel/Delphi/draw-a-pixel.delphi rename to Task/Draw-a-pixel/Delphi/draw-a-pixel.pas diff --git a/Task/Draw-a-pixel/EasyLang/draw-a-pixel.easy b/Task/Draw-a-pixel/EasyLang/draw-a-pixel.easy index cb12f03975..cba3accc14 100644 --- a/Task/Draw-a-pixel/EasyLang/draw-a-pixel.easy +++ b/Task/Draw-a-pixel/EasyLang/draw-a-pixel.easy @@ -1,3 +1,2 @@ -color 900 -move 50 50 -rect 0.5 0.5 +gcolor 900 +grect 50 50 0.5 0.5 diff --git a/Task/Draw-a-pixel/Forth/draw-a-pixel.fth b/Task/Draw-a-pixel/Forth/draw-a-pixel.fth index 5df2b5490a..5d6ed34ccc 100644 --- a/Task/Draw-a-pixel/Forth/draw-a-pixel.fth +++ b/Task/Draw-a-pixel/Forth/draw-a-pixel.fth @@ -1,13 +1,13 @@ \ Bindings to SDL2 functions s" SDL2" add-lib \c #include -c-function sdl-init SDL_Init n -- n -c-function sdl-quit SDL_Quit -- void -c-function sdl-createwindow SDL_CreateWindow a n n n n n -- a -c-function sdl-createrenderer SDL_CreateRenderer a n n -- a -c-function sdl-setdrawcolor SDL_SetRenderDrawColor a n n n n -- n -c-function sdl-drawpoint SDL_RenderDrawPoint a n n -- n -c-function sdl-renderpresent SDL_RenderPresent a -- void +c-function sdl-init SDL_Init n -- n +c-function sdl-quit SDL_Quit -- void +c-function sdl-createwindow SDL_CreateWindow a n n n n n -- a +c-function sdl-createrenderer SDL_CreateRenderer a n n -- a +c-function sdl-setdrawcolor SDL_SetRenderDrawColor a n n n n -- n +c-function sdl-drawpoint SDL_RenderDrawPoint a n n -- n +c-function sdl-renderpresent SDL_RenderPresent a -- void c-function sdl-delay SDL_Delay n -- void : pixel ( -- ) diff --git a/Task/Draw-a-pixel/GML/draw-a-pixel.gml b/Task/Draw-a-pixel/GML/draw-a-pixel.gml index cf522016a3..e29266b1f2 100644 --- a/Task/Draw-a-pixel/GML/draw-a-pixel.gml +++ b/Task/Draw-a-pixel/GML/draw-a-pixel.gml @@ -1 +1,2 @@ -draw_point(100, 100); +draw_set_color(c_red) +draw_point(100, 100) diff --git a/Task/Draw-a-pixel/Go/draw-a-pixel-2.go b/Task/Draw-a-pixel/Go/draw-a-pixel-2.go index 89d068dd45..7a083d1030 100644 --- a/Task/Draw-a-pixel/Go/draw-a-pixel-2.go +++ b/Task/Draw-a-pixel/Go/draw-a-pixel-2.go @@ -1,22 +1,22 @@ package main import ( - "image" - "image/color" - "image/draw" - "image/png" - "os" + "image" + "image/color" + "image/draw" + "image/png" + "os" ) func main() { - // Create a 320 x 240 image - img := image.NewRGBA(image.Rect(0, 0, 320, 240)) - // fill img in white - draw.Draw(img, img.Bounds(), &image.Uniform{color.RGBA{0, 0, 0, 0}}, image.ZP, draw.Src) - // Draw a red dot at (100, 100) - img.Set(100, 100, color.RGBA{255, 0, 0, 255}) - // Save to new.png - w, _ := os.OpenFile("new.png", os.O_WRONLY|os.O_CREATE, 0600) - defer w.Close() - png.Encode(w, img) + // Create a 320 x 240 image + img := image.NewRGBA(image.Rect(0, 0, 320, 240)) + // fill img in white + draw.Draw(img, img.Bounds(), &image.Uniform{color.RGBA{0, 0, 0, 0}}, image.ZP, draw.Src) + // Draw a red dot at (100, 100) + img.Set(100, 100, color.RGBA{255, 0, 0, 255}) + // Save to new.png + w, _ := os.OpenFile("new.png", os.O_WRONLY|os.O_CREATE, 0600) + defer w.Close() + png.Encode(w, img) } diff --git a/Task/Draw-a-pixel/Go/draw-a-pixel-3.go b/Task/Draw-a-pixel/Go/draw-a-pixel-3.go index 9fb62304ea..f6bc3aace1 100644 --- a/Task/Draw-a-pixel/Go/draw-a-pixel-3.go +++ b/Task/Draw-a-pixel/Go/draw-a-pixel-3.go @@ -4,7 +4,7 @@ package main import "github.com/zserge/webview" func main() { - // Open wikipedia in a 320*240 resizable window - webview.Open("Minimal webview example", - "https://en.m.wikipedia.org/wiki/Main_Page", 320, 240, true) + // Open wikipedia in a 320*240 resizable window + webview.Open("Minimal webview example", + "https://en.m.wikipedia.org/wiki/Main_Page", 320, 240, true) } diff --git a/Task/Draw-a-pixel/Java/draw-a-pixel-1.java b/Task/Draw-a-pixel/Java/draw-a-pixel-1.java index 51805bb233..7636004f0b 100644 --- a/Task/Draw-a-pixel/Java/draw-a-pixel-1.java +++ b/Task/Draw-a-pixel/Java/draw-a-pixel-1.java @@ -3,18 +3,18 @@ import java.awt.Graphics; import javax.swing.JFrame; public class DrawAPixel extends JFrame{ - public DrawAPixel() { - super("Red Pixel"); - setSize(320, 240); - setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - setVisible(true); - } - @Override - public void paint(Graphics g) { - g.setColor(new Color(255, 0, 0)); - g.drawRect(100, 100, 1, 1); - } - public static void main(String[] args) { - new DrawAPixel(); - } + public DrawAPixel() { + super("Red Pixel"); + setSize(320, 240); + setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + setVisible(true); + } + @Override + public void paint(Graphics g) { + g.setColor(new Color(255, 0, 0)); + g.drawRect(100, 100, 1, 1); + } + public static void main(String[] args) { + new DrawAPixel(); + } } diff --git a/Task/Draw-a-pixel/Java/draw-a-pixel-2.java b/Task/Draw-a-pixel/Java/draw-a-pixel-2.java index c4f07a05b8..ecb25f50b5 100644 --- a/Task/Draw-a-pixel/Java/draw-a-pixel-2.java +++ b/Task/Draw-a-pixel/Java/draw-a-pixel-2.java @@ -4,30 +4,30 @@ import java.awt.image.BufferedImage; import javax.swing.JFrame; import javax.swing.JPanel; -public class DrawAPixel extends JPanel{ - private BufferedImage puffer; - private JFrame window; - private Graphics g; - public DrawAPixel() { - window = new JFrame("Red Pixel"); - window.setSize(320, 240); - window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - window.setLayout(null); - setBounds(0, 0, 320, 240); - window.add(this); - window.setVisible(true); - } - @Override - public void paint(Graphics gr) { - if(g == null) { - puffer = (BufferedImage) createImage(getWidth(), getHeight()); - g = puffer.getGraphics(); - } - g.setColor(new Color(255, 0, 0)); - g.drawRect(100, 100, 1, 1); - gr.drawImage(puffer, 0, 0, this); - } - public static void main(String[] args) { - new DrawAPixel(); - } +public class DrawAPixel extends JPanel{ + private BufferedImage puffer; + private JFrame window; + private Graphics g; + public DrawAPixel() { + window = new JFrame("Red Pixel"); + window.setSize(320, 240); + window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + window.setLayout(null); + setBounds(0, 0, 320, 240); + window.add(this); + window.setVisible(true); + } + @Override + public void paint(Graphics gr) { + if(g == null) { + puffer = (BufferedImage) createImage(getWidth(), getHeight()); + g = puffer.getGraphics(); + } + g.setColor(new Color(255, 0, 0)); + g.drawRect(100, 100, 1, 1); + gr.drawImage(puffer, 0, 0, this); + } + public static void main(String[] args) { + new DrawAPixel(); + } } diff --git a/Task/Draw-a-pixel/Julia/draw-a-pixel.julia b/Task/Draw-a-pixel/Julia/draw-a-pixel.jl similarity index 100% rename from Task/Draw-a-pixel/Julia/draw-a-pixel.julia rename to Task/Draw-a-pixel/Julia/draw-a-pixel.jl diff --git a/Task/Draw-a-pixel/Kotlin/draw-a-pixel.kotlin b/Task/Draw-a-pixel/Kotlin/draw-a-pixel.kts similarity index 100% rename from Task/Draw-a-pixel/Kotlin/draw-a-pixel.kotlin rename to Task/Draw-a-pixel/Kotlin/draw-a-pixel.kts diff --git a/Task/Draw-a-pixel/Lua/draw-a-pixel.lua b/Task/Draw-a-pixel/Lua/draw-a-pixel.lua index 525421de1f..7050f8b22d 100644 --- a/Task/Draw-a-pixel/Lua/draw-a-pixel.lua +++ b/Task/Draw-a-pixel/Lua/draw-a-pixel.lua @@ -2,9 +2,9 @@ local SDL = require "SDL" local ret = SDL.init { SDL.flags.Video } local window = SDL.createWindow { - title = "Pixel", - height = 320, - width = 240 + title = "Pixel", + height = 320, + width = 240 } local renderer = SDL.createRenderer(window, 0, 0) diff --git a/Task/Draw-a-pixel/OCaml/draw-a-pixel-1.ocaml b/Task/Draw-a-pixel/OCaml/draw-a-pixel-1.ml similarity index 100% rename from Task/Draw-a-pixel/OCaml/draw-a-pixel-1.ocaml rename to Task/Draw-a-pixel/OCaml/draw-a-pixel-1.ml diff --git a/Task/Draw-a-pixel/OCaml/draw-a-pixel-2.ocaml b/Task/Draw-a-pixel/OCaml/draw-a-pixel-2.ml similarity index 100% rename from Task/Draw-a-pixel/OCaml/draw-a-pixel-2.ocaml rename to Task/Draw-a-pixel/OCaml/draw-a-pixel-2.ml diff --git a/Task/Draw-a-pixel/OPL/draw-a-pixel.opl b/Task/Draw-a-pixel/OPL/draw-a-pixel.opl new file mode 100644 index 0000000000..f880013ec3 --- /dev/null +++ b/Task/Draw-a-pixel/OPL/draw-a-pixel.opl @@ -0,0 +1,11 @@ +REM Psion devices up to Series 5 have no colour, so the pixel is black. The Series 7 and later do have colour, but I don't own any of those, so I can neither test it nor am I familiar with OPL beyond Series 5. +REM The Series 3 also has a resolution of only 480x160, so the window falls off the screen. + +PROC main: + LOCAL wndw% + wndw%=gCREATE(80,0,320,240,1,1) + gXBORDER 1,1 + gAT 100,100 + gLINEBY 0,0 + GET +ENDP diff --git a/Task/Draw-a-pixel/Oberon/draw-a-pixel.oberon b/Task/Draw-a-pixel/Oberon/draw-a-pixel.oberon index 8a9cf70323..12a93b93a9 100644 --- a/Task/Draw-a-pixel/Oberon/draw-a-pixel.oberon +++ b/Task/Draw-a-pixel/Oberon/draw-a-pixel.oberon @@ -1,9 +1,9 @@ MODULE pixel; - IMPORT XYplane; - + IMPORT XYplane; + BEGIN - XYplane.Open; - XYplane.Dot(100, 100, XYplane.draw); - REPEAT UNTIL XYplane.Key() = "q" + XYplane.Open; + XYplane.Dot(100, 100, XYplane.draw); + REPEAT UNTIL XYplane.Key() = "q" END pixel. diff --git a/Task/Draw-a-pixel/Odin/draw-a-pixel.odin b/Task/Draw-a-pixel/Odin/draw-a-pixel-1.odin similarity index 100% rename from Task/Draw-a-pixel/Odin/draw-a-pixel.odin rename to Task/Draw-a-pixel/Odin/draw-a-pixel-1.odin diff --git a/Task/Draw-a-pixel/Odin/draw-a-pixel-2.odin b/Task/Draw-a-pixel/Odin/draw-a-pixel-2.odin new file mode 100644 index 0000000000..ee0880c648 --- /dev/null +++ b/Task/Draw-a-pixel/Odin/draw-a-pixel-2.odin @@ -0,0 +1,19 @@ +package main + +import rl "vendor:raylib" + +main :: proc() { + rl.InitWindow(320, 240, "Rosetta Code - Draw a pixel") + + for !rl.WindowShouldClose() { + rl.BeginDrawing() + + rl.ClearBackground(rl.BLACK) + + rl.DrawPixelV({100, 100}, {255, 0, 0, 255}) + + rl.EndDrawing() + } + + rl.CloseWindow() +} diff --git a/Task/Draw-a-pixel/PascalABC.NET/draw-a-pixel.pas b/Task/Draw-a-pixel/PascalABC.NET/draw-a-pixel.pas new file mode 100644 index 0000000000..caaee3cf72 --- /dev/null +++ b/Task/Draw-a-pixel/PascalABC.NET/draw-a-pixel.pas @@ -0,0 +1,6 @@ +uses GraphWPF; + +begin + Window.SetSize(320,240); + SetPixel(100,100,Colors.Red); +end. diff --git a/Task/Draw-a-pixel/Perl/draw-a-pixel-3.pl b/Task/Draw-a-pixel/Perl/draw-a-pixel-3.pl index 7d859637e7..37bdd615b4 100644 --- a/Task/Draw-a-pixel/Perl/draw-a-pixel-3.pl +++ b/Task/Draw-a-pixel/Perl/draw-a-pixel-3.pl @@ -6,39 +6,39 @@ use X11::Protocol; my $x = new X11::Protocol or die "X11 connection failed"; $x->CreateWindow(my $id = $x->new_rsrc, $x->root, 'InputOutput', - $x->root_depth, 'CopyFromParent', - 0, 0, 320, 240, 0, - background_pixel => 0x000000, - event_mask => $x->pack_event_mask( qw( Exposure )), - ); + $x->root_depth, 'CopyFromParent', + 0, 0, 320, 240, 0, + background_pixel => 0x000000, + event_mask => $x->pack_event_mask( qw( Exposure )), + ); $x->ChangeProperty($id, $x->atom('WM_NAME'), $x->atom('STRING'), - 8, 'Replace', 'Draw a Pixel'); + 8, 'Replace', 'Draw a Pixel'); $x->ChangeProperty($id, $x->atom('WM_PROTOCOLS'), $x->atom('ATOM'), - 32, 'Replace', pack('L', $x->atom('WM_DELETE_WINDOW'))); + 32, 'Replace', pack('L', $x->atom('WM_DELETE_WINDOW'))); $x->CreateGC(my $gc = $x->new_rsrc, $id, foreground => 0xff0000); $x->MapWindow($id); $x->event_handler('queue'); my ($more, $name, %e) = 1; while($more) - { - %e = $x->next_event; - $name = $e{name}; - EVENT->$name; - } + { + %e = $x->next_event; + $name = $e{name}; + EVENT->$name; + } sub EVENT::Expose { $x->PolyPoint($id, $gc, 'ORIGIN', 100, 100) } sub EVENT::ConfigureNotify { } sub EVENT::ClientMessage - { - if($e{type} == $x->atom('WM_PROTOCOLS') && - unpack('L', $e{data}) == $x->atom('WM_DELETE_WINDOW')) - { - $more = 0; - } - else - { - warn "Unknown $name, $e{type}\n"; - } - } + { + if($e{type} == $x->atom('WM_PROTOCOLS') && + unpack('L', $e{data}) == $x->atom('WM_DELETE_WINDOW')) + { + $more = 0; + } + else + { + warn "Unknown $name, $e{type}\n"; + } + } sub EVENT::AUTOLOAD { die "Sorry, no handler for $name\n" } diff --git a/Task/Draw-a-pixel/R/draw-a-pixel.r b/Task/Draw-a-pixel/R/draw-a-pixel.r new file mode 100644 index 0000000000..4fd8762de5 --- /dev/null +++ b/Task/Draw-a-pixel/R/draw-a-pixel.r @@ -0,0 +1,9 @@ +disp_h <- 240 +disp_w <- 320 +mat <- matrix(0, nrow = disp_w, ncol = disp_h) +mat[100, 100] <- 1 +png("DrawPixel-R.png", disp_w, disp_h) +op <- par(mar = rep(0, 4), mai = rep(0, 4)) +image(mat, col = c("white", "red"), useRaster = TRUE, axes = FALSE) +par(op) +dev.off() diff --git a/Task/Draw-a-pixel/ReScript/draw-a-pixel-1.re b/Task/Draw-a-pixel/ReScript/draw-a-pixel-1.res similarity index 100% rename from Task/Draw-a-pixel/ReScript/draw-a-pixel-1.re rename to Task/Draw-a-pixel/ReScript/draw-a-pixel-1.res diff --git a/Task/Draw-a-pixel/ReScript/draw-a-pixel-2.re b/Task/Draw-a-pixel/ReScript/draw-a-pixel-2.res similarity index 100% rename from Task/Draw-a-pixel/ReScript/draw-a-pixel-2.re rename to Task/Draw-a-pixel/ReScript/draw-a-pixel-2.res diff --git a/Task/Draw-a-pixel/Rebol/draw-a-pixel.rebol b/Task/Draw-a-pixel/Rebol/draw-a-pixel.rebol new file mode 100644 index 0000000000..657fa8b619 --- /dev/null +++ b/Task/Draw-a-pixel/Rebol/draw-a-pixel.rebol @@ -0,0 +1,10 @@ +Rebol [ + title: "Rosetta code: Draw a pixel" + file: %Draw_a_pixel.r3 + url: https://rosettacode.org/wiki/Draw_a_pixel +] + +img: make image! 320x240 ;; Create a new image of size 320x240 pixels +img/(100x100): 255.0.0 ;; Set the pixel at position 100x100 to pure red +save %test.png img ;; Save the image to a PNG file named "test.png" +browse %test.png ;; Open the saved image file using the default browser diff --git a/Task/Draw-a-pixel/Rust/draw-a-pixel.rust b/Task/Draw-a-pixel/Rust/draw-a-pixel.rs similarity index 100% rename from Task/Draw-a-pixel/Rust/draw-a-pixel.rust rename to Task/Draw-a-pixel/Rust/draw-a-pixel.rs diff --git a/Task/Draw-a-pixel/Uxntal/draw-a-pixel.uxnatl b/Task/Draw-a-pixel/Uxntal/draw-a-pixel.uxnatl deleted file mode 100644 index 26c8170b96..0000000000 --- a/Task/Draw-a-pixel/Uxntal/draw-a-pixel.uxnatl +++ /dev/null @@ -1,22 +0,0 @@ -( $ 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-pixel/V-(Vlang)/draw-a-pixel.v b/Task/Draw-a-pixel/V-(Vlang)/draw-a-pixel.v index f8ec8e887e..80701bae65 100644 --- a/Task/Draw-a-pixel/V-(Vlang)/draw-a-pixel.v +++ b/Task/Draw-a-pixel/V-(Vlang)/draw-a-pixel.v @@ -1,5 +1,4 @@ import gg -import gx fn main() { mut context := gg.new_context( @@ -12,6 +11,6 @@ fn main() { fn frame(mut ctx gg.Context) { ctx.begin() - ctx.draw_pixel(100, 100, gx.red) + ctx.draw_pixel(100, 100, gg.red) ctx.end() } diff --git a/Task/Draw-a-rotating-cube/Ada/draw-a-rotating-cube.ada b/Task/Draw-a-rotating-cube/Ada/draw-a-rotating-cube.adb similarity index 100% rename from Task/Draw-a-rotating-cube/Ada/draw-a-rotating-cube.ada rename to Task/Draw-a-rotating-cube/Ada/draw-a-rotating-cube.adb diff --git a/Task/Draw-a-rotating-cube/Delphi/draw-a-rotating-cube-1.delphi b/Task/Draw-a-rotating-cube/Delphi/draw-a-rotating-cube-1.pas similarity index 100% rename from Task/Draw-a-rotating-cube/Delphi/draw-a-rotating-cube-1.delphi rename to Task/Draw-a-rotating-cube/Delphi/draw-a-rotating-cube-1.pas diff --git a/Task/Draw-a-rotating-cube/Delphi/draw-a-rotating-cube-2.delphi b/Task/Draw-a-rotating-cube/Delphi/draw-a-rotating-cube-2.pas similarity index 100% rename from Task/Draw-a-rotating-cube/Delphi/draw-a-rotating-cube-2.delphi rename to Task/Draw-a-rotating-cube/Delphi/draw-a-rotating-cube-2.pas diff --git a/Task/Draw-a-rotating-cube/EasyLang/draw-a-rotating-cube.easy b/Task/Draw-a-rotating-cube/EasyLang/draw-a-rotating-cube.easy index 4b30030a05..09df71826d 100644 --- a/Task/Draw-a-rotating-cube/EasyLang/draw-a-rotating-cube.easy +++ b/Task/Draw-a-rotating-cube/EasyLang/draw-a-rotating-cube.easy @@ -1,14 +1,12 @@ node[][] = [ [ -1 -1 -1 ] [ -1 -1 1 ] [ -1 1 -1 ] [ -1 1 1 ] [ 1 -1 -1 ] [ 1 -1 1 ] [ 1 1 -1 ] [ 1 1 1 ] ] edge[][] = [ [ 1 2 ] [ 2 4 ] [ 4 3 ] [ 3 1 ] [ 5 6 ] [ 6 8 ] [ 8 7 ] [ 7 5 ] [ 1 5 ] [ 2 6 ] [ 3 7 ] [ 4 8 ] ] # -proc scale f . . - for i = 1 to len node[][] - for d = 1 to 3 - node[i][d] *= f - . +proc scale f . + for i = 1 to len node[][] : for d = 1 to 3 + node[i][d] *= f . . -proc rotate angx angy . . +proc rotate angx angy . sinx = sin angx cosx = cos angx siny = sin angy @@ -24,8 +22,8 @@ proc rotate angx angy . . . . len nd[] 3 -proc draw . . - clear +proc draw . + gclear m = 999 mi = -1 for i = 1 to len node[][] @@ -44,16 +42,13 @@ proc draw . . ix += 1 . . - for ni = 1 to len nd[] - for i = 1 to len edge[][] - if edge[i][1] = nd[ni] or edge[i][2] = nd[ni] - x1 = node[edge[i][1]][1] - y1 = node[edge[i][1]][2] - x2 = node[edge[i][2]][1] - y2 = node[edge[i][2]][2] - move x1 + 50 y1 + 50 - line x2 + 50 y2 + 50 - . + for ni = 1 to len nd[] : for i = 1 to len edge[][] + if edge[i][1] = nd[ni] or edge[i][2] = nd[ni] + x1 = node[edge[i][1]][1] + y1 = node[edge[i][1]][2] + x2 = node[edge[i][2]][1] + y2 = node[edge[i][2]][2] + gline x1 + 50 y1 + 50 x2 + 50 y2 + 50 . . . diff --git a/Task/Draw-a-rotating-cube/Julia/draw-a-rotating-cube.julia b/Task/Draw-a-rotating-cube/Julia/draw-a-rotating-cube.jl similarity index 100% rename from Task/Draw-a-rotating-cube/Julia/draw-a-rotating-cube.julia rename to Task/Draw-a-rotating-cube/Julia/draw-a-rotating-cube.jl diff --git a/Task/Draw-a-rotating-cube/Kotlin/draw-a-rotating-cube.kotlin b/Task/Draw-a-rotating-cube/Kotlin/draw-a-rotating-cube.kts similarity index 100% rename from Task/Draw-a-rotating-cube/Kotlin/draw-a-rotating-cube.kotlin rename to Task/Draw-a-rotating-cube/Kotlin/draw-a-rotating-cube.kts diff --git a/Task/Draw-a-rotating-cube/PascalABC.NET/draw-a-rotating-cube.pas b/Task/Draw-a-rotating-cube/PascalABC.NET/draw-a-rotating-cube.pas new file mode 100644 index 0000000000..37d716f15c --- /dev/null +++ b/Task/Draw-a-rotating-cube/PascalABC.NET/draw-a-rotating-cube.pas @@ -0,0 +1,6 @@ +uses Graph3D; + +begin + var Cube := Box(Origin,Sz3D(3,3,3),Colors.Green); + Cube.AnimRotate(OrtZ,180).Forever.Begin +end. diff --git a/Task/Draw-a-rotating-cube/Python/draw-a-rotating-cube.py b/Task/Draw-a-rotating-cube/Python/draw-a-rotating-cube-1.py similarity index 100% rename from Task/Draw-a-rotating-cube/Python/draw-a-rotating-cube.py rename to Task/Draw-a-rotating-cube/Python/draw-a-rotating-cube-1.py diff --git a/Task/Draw-a-rotating-cube/Python/draw-a-rotating-cube-2.py b/Task/Draw-a-rotating-cube/Python/draw-a-rotating-cube-2.py new file mode 100644 index 0000000000..f7a42efcbe --- /dev/null +++ b/Task/Draw-a-rotating-cube/Python/draw-a-rotating-cube-2.py @@ -0,0 +1,14 @@ +import bpy +import math +bpy.context.preferences.edit.keyframe_new_interpolation_type="LINEAR" +bpy.ops.object.select_all(action="SELECT") +bpy.ops.object.delete() +bpy.ops.mesh.primitive_cube_add() +bpy.context.active_object.name="spinningcube" +spinningcube=bpy.data.objects["spinningcube"] +spinningcube.rotation_euler=(math.radians(45),math.radians(35.264),math.radians(0)) +spinningcube.keyframe_insert(data_path="rotation_euler",frame=1) +spinningcube.rotation_euler=(math.radians(45),math.radians(35.264),math.radians(2700)) +spinningcube.keyframe_insert(data_path="rotation_euler",frame=250) +bpy.context.scene.frame_set(1) +bpy.ops.screen.animation_play() diff --git a/Task/Draw-a-rotating-cube/V-(Vlang)/draw-a-rotating-cube.v b/Task/Draw-a-rotating-cube/V-(Vlang)/draw-a-rotating-cube.v new file mode 100644 index 0000000000..597f4f3661 --- /dev/null +++ b/Task/Draw-a-rotating-cube/V-(Vlang)/draw-a-rotating-cube.v @@ -0,0 +1,122 @@ +import gg +import gx +import math + +struct RotatingCube { + mut: + width int + height int + fore gx.Color + nodes [][]f64 + edges [][]int + scale_f f64 +} + +fn new_rotating_cube(width int, height int) RotatingCube { + mut nodes := [ + [f64(-1.0), -1, -1], + [f64(-1.0), -1, 1], + [f64(-1.0), 1, -1], + [f64(-1.0), 1, 1], + [f64(1.0), -1, -1], + [f64(1.0), -1, 1], + [f64(1.0), 1, -1], + [f64(1.0), 1, 1], + ] + mut edges := [ + [0, 1], + [1, 3], + [3, 2], + [2, 0], + [4, 5], + [5, 7], + [7, 6], + [6, 4], + [0, 4], + [1, 5], + [2, 6], + [3, 7], + ] + mut cube := RotatingCube{ + width: width + height: height + fore: gx.blue + nodes: nodes + edges: edges + scale_f: 100.0 + } + cube.scale(cube.scale_f) + cube.rotate_cube(math.pi / 4, math.sqrt(math.atan(2.0))) + return cube +} + +fn (mut rc RotatingCube) scale(s f64) { + for i in 0 .. rc.nodes.len { + for j in 0 .. 3 { + rc.nodes[i][j] = rc.nodes[i][j] * s + } + } +} + +fn (mut rc RotatingCube) rotate_cube(angle_x f64, angle_y f64) { + sin_x := math.sin(angle_x) + cos_x := math.cos(angle_x) + sin_y := math.sin(angle_y) + cos_y := math.cos(angle_y) + for i in 0 .. rc.nodes.len { + x := rc.nodes[i][0] + y := rc.nodes[i][1] + z := rc.nodes[i][2] + rc.nodes[i][0] = x * cos_x - z * sin_x + rc.nodes[i][2] = z * cos_x + x * sin_x + z_new := rc.nodes[i][2] + rc.nodes[i][1] = y * cos_y - z_new * sin_y + rc.nodes[i][2] = z_new * cos_y + y * sin_y + } +} + +fn (mut rc RotatingCube) draw_cube(mut ctx gg.Context) { + ctx.begin() + cx := f32(rc.width / 2) + cy := f32(rc.height / 2) + for edge in rc.edges { + n1 := rc.nodes[edge[0]] + n2 := rc.nodes[edge[1]] + x1 := f32(n1[0]) + cx + y1 := f32(n1[1]) + cy + x2 := f32(n2[0]) + cx + y2 := f32(n2[1]) + cy + ctx.draw_line(x1, y1, x2, y2, rc.fore) + } + for node in rc.nodes { + x := f32(node[0]) + cx - 4 + y := f32(node[1]) + cy - 4 + ctx.draw_rect_filled(x, y, 8, 8, rc.fore) + } + ctx.end() +} + +fn (mut rc RotatingCube) update() { + rc.rotate_cube(math.pi / 180, 0) +} + +fn frame(mut cube RotatingCube) { + mut ctx := gg.Context{} + cube.update() + cube.draw_cube(mut ctx) +} + +fn main() { + width := 640 + height := 640 + mut cube := new_rotating_cube(width, height) + mut context := gg.new_context( + width: width + height: height + window_title: "Rotating cube" + bg_color: gx.white + frame_fn: frame + user_data: &cube + ) + context.run() +} diff --git a/Task/Draw-a-sphere/Ada/draw-a-sphere-1.ada b/Task/Draw-a-sphere/Ada/draw-a-sphere-1.adb similarity index 100% rename from Task/Draw-a-sphere/Ada/draw-a-sphere-1.ada rename to Task/Draw-a-sphere/Ada/draw-a-sphere-1.adb diff --git a/Task/Draw-a-sphere/Ada/draw-a-sphere-2.ada b/Task/Draw-a-sphere/Ada/draw-a-sphere-2.adb similarity index 100% rename from Task/Draw-a-sphere/Ada/draw-a-sphere-2.ada rename to Task/Draw-a-sphere/Ada/draw-a-sphere-2.adb diff --git a/Task/Draw-a-sphere/Delphi/draw-a-sphere.delphi b/Task/Draw-a-sphere/Delphi/draw-a-sphere.pas similarity index 100% rename from Task/Draw-a-sphere/Delphi/draw-a-sphere.delphi rename to Task/Draw-a-sphere/Delphi/draw-a-sphere.pas diff --git a/Task/Draw-a-sphere/EasyLang/draw-a-sphere.easy b/Task/Draw-a-sphere/EasyLang/draw-a-sphere.easy new file mode 100644 index 0000000000..972b539b5d --- /dev/null +++ b/Task/Draw-a-sphere/EasyLang/draw-a-sphere.easy @@ -0,0 +1,25 @@ +func vdot a[] b[] . + for i to len a[] : r += a[i] * b[i] + return r +. +func[] norm v[] . + d = vdot v[] v[] + invl = 1 / sqrt d + for i to 3 : r[] &= v[i] * invl + return r[] +. +proc sphere r k amb dir[] . + for x = -r to r : for y = -r to r + z = r * r - x * x - y * y + if z >= 0 + s = vdot dir[] norm [ x y sqrt z ] + if s < 0 : s = 0 + lum = (pow s k + amb) / (1 + amb) + gcolor3 lum lum lum + grect 50 + x / 5, 50 + y / 5, 0.3 0.3 + . + . +. +gbackground 000 +gclear +sphere 200 1.5 0.2 norm [ -30 30 50 ] diff --git a/Task/Draw-a-sphere/Emacs-Lisp/draw-a-sphere.l b/Task/Draw-a-sphere/Emacs-Lisp/draw-a-sphere.el similarity index 100% rename from Task/Draw-a-sphere/Emacs-Lisp/draw-a-sphere.l rename to Task/Draw-a-sphere/Emacs-Lisp/draw-a-sphere.el diff --git a/Task/Draw-a-sphere/Julia/draw-a-sphere-1.julia b/Task/Draw-a-sphere/Julia/draw-a-sphere-1.jl similarity index 100% rename from Task/Draw-a-sphere/Julia/draw-a-sphere-1.julia rename to Task/Draw-a-sphere/Julia/draw-a-sphere-1.jl diff --git a/Task/Draw-a-sphere/Julia/draw-a-sphere-2.julia b/Task/Draw-a-sphere/Julia/draw-a-sphere-2.jl similarity index 100% rename from Task/Draw-a-sphere/Julia/draw-a-sphere-2.julia rename to Task/Draw-a-sphere/Julia/draw-a-sphere-2.jl diff --git a/Task/Draw-a-sphere/Kotlin/draw-a-sphere.kotlin b/Task/Draw-a-sphere/Kotlin/draw-a-sphere.kts similarity index 100% rename from Task/Draw-a-sphere/Kotlin/draw-a-sphere.kotlin rename to Task/Draw-a-sphere/Kotlin/draw-a-sphere.kts diff --git a/Task/Draw-a-sphere/Locomotive-Basic/draw-a-sphere.basic b/Task/Draw-a-sphere/Locomotive-Basic/draw-a-sphere-1.basic similarity index 100% rename from Task/Draw-a-sphere/Locomotive-Basic/draw-a-sphere.basic rename to Task/Draw-a-sphere/Locomotive-Basic/draw-a-sphere-1.basic diff --git a/Task/Draw-a-sphere/Locomotive-Basic/draw-a-sphere-2.basic b/Task/Draw-a-sphere/Locomotive-Basic/draw-a-sphere-2.basic new file mode 100644 index 0000000000..c343edc95d --- /dev/null +++ b/Task/Draw-a-sphere/Locomotive-Basic/draw-a-sphere-2.basic @@ -0,0 +1,32 @@ +10 MODE 2:ORIGIN 320,200:INK 0,0:INK 1,26 +20 DIM v(2),vec(2) +30 v(0)=30:v(1)=30:v(2)=-50 +40 lung=SQR(v(0)*v(0)+v(1)*v(1)+v(2)*v(2)) +50 v(0)=v(0)/lung +60 v(1)=v(1)/lung +70 v(2)=v(2)/lung +80 r=180:k=1.5:ambient=0.03 +90 FOR i=INT(-r) TO INT(r) +100 x=i +110 FOR j=INT(-2*r) TO INT(2*r) +120 y=j/2 +130 IF (x*x+y*y<=r*r) THEN GOSUB 1000 +140 NEXT j +160 NEXT i +170 END +1000 vec(0)=x +1010 vec(1)=y +1020 vec(2)=SQR(r*r-x*x-y*y) +1030 GOSUB 2000 +1040 GOSUB 3000 +1050 b=(d^k+ambient)/(1+ambient) +1060 IF b>rnd THEN PLOT x,-y +1100 RETURN +2000 lung=SQR(vec(0)*vec(0)+vec(1)*vec(1)+vec(2)*vec(2)) +2010 vec(0)=vec(0)/lung +2020 vec(1)=vec(1)/lung +2030 vec(2)=vec(2)/lung +2040 RETURN +3000 d=v(0)*vec(0)+v(1)*vec(1)+v(2)*vec(2) +3010 IF d<0 THEN d=-d ELSE d=0 +3020 RETURN diff --git a/Task/Draw-a-sphere/Odin/draw-a-sphere.odin b/Task/Draw-a-sphere/Odin/draw-a-sphere.odin new file mode 100644 index 0000000000..394ba7fcef --- /dev/null +++ b/Task/Draw-a-sphere/Odin/draw-a-sphere.odin @@ -0,0 +1,32 @@ +package sphere + +import rl "vendor:raylib" + +main :: proc() { + rl.InitWindow(640, 480, "Rosetta Code - draw a sphere") + + camera: rl.Camera3D + camera.fovy = 45 + camera.position = {0, 2.5, 5} + camera.up = {0, 1, 0} + + for !rl.WindowShouldClose() { + rl.UpdateCamera(&camera, .ORBITAL) + + rl.BeginDrawing() + + rl.ClearBackground(rl.RAYWHITE) + + rl.BeginMode3D(camera) + + rl.DrawGrid(10, .5) + + rl.DrawSphere({}, .5, rl.LIME) + + rl.EndMode3D() + + rl.EndDrawing() + } + + rl.CloseWindow() +} diff --git a/Task/Draw-a-sphere/Pluto/draw-a-sphere.pluto b/Task/Draw-a-sphere/Pluto/draw-a-sphere.pluto new file mode 100644 index 0000000000..2c693f9de4 --- /dev/null +++ b/Task/Draw-a-sphere/Pluto/draw-a-sphere.pluto @@ -0,0 +1,8 @@ +require "bitmap" + +local bmp = bitmap.of(400, 400, color.white, "Draw a sphere") +for n = 1, 100 do + local clr = bitmap.rgbColor(2 * n, 2 * n, 2 * n) + bmp:circle(math.round(150-2 * n / 3) + 50, math.round(150 - n / 2) + 50, 150 - n, clr) +end +bmp:view() diff --git a/Task/Draw-a-sphere/R/draw-a-sphere.r b/Task/Draw-a-sphere/R/draw-a-sphere.r new file mode 100644 index 0000000000..c6f8e5fbd1 --- /dev/null +++ b/Task/Draw-a-sphere/R/draw-a-sphere.r @@ -0,0 +1,12 @@ +library(lattice) +theta <- seq(0, pi, length.out=100) +phi <- seq(0, 2*pi, length.out=100) +x <- outer(sin(theta), cos(phi)) +y <- outer(sin(theta), sin(phi)) +z <- sqrt(1-x^2-y^2) +xx <- kronecker(matrix(1, 2, 2), x) +yy <- kronecker(matrix(1, 2, 2), y) +zz <- kronecker(matrix(c(1, -1, -1, 1), 2, 2), z) +png(filename="Sphere-R.png", width=1000, height=1000) +wireframe(zz ~ xx*yy) +dev.off() diff --git a/Task/Draw-a-sphere/Rust/draw-a-sphere.rust b/Task/Draw-a-sphere/Rust/draw-a-sphere.rs similarity index 100% rename from Task/Draw-a-sphere/Rust/draw-a-sphere.rust rename to Task/Draw-a-sphere/Rust/draw-a-sphere.rs diff --git a/Task/Draw-a-sphere/VBScript/draw-a-sphere.vb b/Task/Draw-a-sphere/VBScript/draw-a-sphere.vbs similarity index 100% rename from Task/Draw-a-sphere/VBScript/draw-a-sphere.vb rename to Task/Draw-a-sphere/VBScript/draw-a-sphere.vbs diff --git a/Task/Duffinian-numbers/Arturo/duffinian-numbers.arturo b/Task/Duffinian-numbers/Arturo/duffinian-numbers.arturo index 5aca5135af..67e076411f 100644 --- a/Task/Duffinian-numbers/Arturo/duffinian-numbers.arturo +++ b/Task/Duffinian-numbers/Arturo/duffinian-numbers.arturo @@ -5,7 +5,7 @@ duffinian?: function [n]-> [1] = intersection factors sum fn fn ] -first50: new [] +first50: [] i: 0 while [50 > size first50][ if duffinian? i -> 'first50 ++ i @@ -17,7 +17,7 @@ loop split.every: 10 first50 'row [ print map to [:string] row 'item -> pad item 3 ] -first15: new [] +first15: [] i: 0 while [15 > size first15][ if every? i..i+2 => duffinian? [ @@ -30,5 +30,5 @@ while [15 > size first15][ print "" print "The first 15 Duffinian triplets:" loop split.every: 5 first15 'row [ - print map row 'item -> pad.right as.code item 17 + print map row 'item -> pad.right express item 17 ] diff --git a/Task/Duffinian-numbers/Delphi/duffinian-numbers.delphi b/Task/Duffinian-numbers/Delphi/duffinian-numbers.pas similarity index 100% rename from Task/Duffinian-numbers/Delphi/duffinian-numbers.delphi rename to Task/Duffinian-numbers/Delphi/duffinian-numbers.pas diff --git a/Task/Duffinian-numbers/EasyLang/duffinian-numbers.easy b/Task/Duffinian-numbers/EasyLang/duffinian-numbers.easy index 6cc97d01fb..b50d820e3d 100644 --- a/Task/Duffinian-numbers/EasyLang/duffinian-numbers.easy +++ b/Task/Duffinian-numbers/EasyLang/duffinian-numbers.easy @@ -1,9 +1,7 @@ fastfunc isprim num . i = 2 while i <= sqrt num - if num mod i = 0 - return 0 - . + if num mod i = 0 : return 0 i += 1 . return 1 @@ -23,9 +21,7 @@ func sumdiv num . until d > quot if num mod d = 0 sum += d - if d <> quot - sum += quot - . + if d <> quot : sum += quot . d += 1 . @@ -37,7 +33,7 @@ func isduff n . . return 0 . -proc duffs . . +proc duffs . print "First 50 Duffinian numbers:" n = 4 repeat diff --git a/Task/Duffinian-numbers/Forth/duffinian-numbers.fth b/Task/Duffinian-numbers/Forth/duffinian-numbers.fth new file mode 100644 index 0000000000..264737eeb8 --- /dev/null +++ b/Task/Duffinian-numbers/Forth/duffinian-numbers.fth @@ -0,0 +1,61 @@ +: gcd ( u1 u2 -- u3 ) + dup 0= if drop exit then + tuck mod recurse ; + +: duffinian? ( u -- ? ) + dup 2 = if drop false exit then + 1 >r dup 2 + begin + over 2 mod 0= + while + dup r> + >r 2* swap 2/ swap + repeat + drop 3 + begin + 2dup dup * >= + while + dup 1 >r + begin + 2 pick 2 pick mod 0= + while + dup r> + >r over * >r tuck / swap r> + repeat + 2r> * >r drop 2 + + repeat + drop + 2dup = if 2drop rdrop false exit then + dup 1 > if 1+ r> * else drop r> then + gcd 1 = ; + +: main + ." First 50 Duffinian numbers:" cr + 0 1 + begin + over 50 < + while + dup duffinian? if + dup 3 .r + swap 1+ swap + over 10 mod 0= if cr else space then + then + 1+ + repeat + 2drop + cr ." First 30 Duffinian triplets:" cr + 0 >r 0 1 + begin + r@ 30 < + while + dup duffinian? if swap 1+ swap else nip 0 swap then + over 3 = if + r> 1+ >r + dup 2 - 5 .r space + dup 1- 5 .r space + dup 5 .r cr + then + 1+ + repeat + rdrop 2drop ; + +main +bye diff --git a/Task/Duffinian-numbers/Free-Pascal-Lazarus/duffinian-numbers.pas b/Task/Duffinian-numbers/Free-Pascal-Lazarus/duffinian-numbers.pas new file mode 100644 index 0000000000..17e3029649 --- /dev/null +++ b/Task/Duffinian-numbers/Free-Pascal-Lazarus/duffinian-numbers.pas @@ -0,0 +1,79 @@ +program DuffinianNumbers; + +CONST + MaxSigma = 10000; + +VAR + seen, cur: CARDINAL; + sigma: ARRAY [1..MaxSigma] OF CARDINAL; + +PROCEDURE CalculateSigmaTable; + VAR i, j: CARDINAL; +BEGIN + FOR i := 1 TO MaxSigma DO + BEGIN + sigma[i] := 0 + END; + FOR i := 1 TO MaxSigma DO + BEGIN + j := i;//2*i -> sigma(n)-n + WHILE j <= MaxSigma DO + Begin + INC(sigma[j], i); + INC(j, i); + END + END +END;// CalculateSigmaTable; + +FUNCTION GCD(a, b: CARDINAL): CARDINAL; +VAR c: CARDINAL; +BEGIN + WHILE b <>0 DO + Begin + c := a MOD b; + a := b; + b := c + END; + EXIT(A) +END;// GCD; + +function IsDuffinian(n: CARDINAL): BOOLEAN; +BEGIN + EXIT( (sigma[n] > n+1) AND (GCD(n, sigma[n]) = 1)) +END;// IsDuffinian; + +FUNCTION IsDuffinianTriple(n: CARDINAL): BOOLEAN; +BEGIN + EXIT(IsDuffinian(n) AND IsDuffinian(n+1) AND IsDuffinian(n+2)); +END;// IsDuffinianTriple; + +BEGIN + CalculateSigmaTable; + Writeln('First 50 Duffinian numbers:'); + WriteLn; + cur := 0; + FOR seen := 1 TO 50 DO + Begin + REPEAT + INC(cur) + UNTIL IsDuffinian(cur); + Write(cur:4); + IF seen MOD 10 = 0 THEN + WriteLn; + END; + + WriteLn; + WriteLn('First 15 Duffinian triples:'); + WriteLn; + cur := 0; + FOR seen := 1 TO 15 DO + BEGIN + REPEAT + INC(cur) + UNTIL IsDuffinianTriple(cur); + Write(cur:6); + Write(cur+1:6); + Write(cur+2:6); + WriteLn; + END +END.// DuffinianNumbers. diff --git a/Task/Duffinian-numbers/Haskell/duffinian-numbers.hs b/Task/Duffinian-numbers/Haskell/duffinian-numbers.hs new file mode 100644 index 0000000000..9bc2ce04f3 --- /dev/null +++ b/Task/Duffinian-numbers/Haskell/duffinian-numbers.hs @@ -0,0 +1,50 @@ +import Data.List ( tail ) +import qualified Data.Set as S +import Data.List.Split ( divvy ) + +divisors :: Int -> [Int] +divisors n = [d | d <- [1..n] , mod n d == 0] + +primeFactors :: Int -> [Int] +primeFactors n = snd $ until ( (== 1 ) . fst ) step (n , [] ) + where + step :: (Int , [Int]) -> (Int , [Int]) + step ( aNumber , factors ) = ( div aNumber smallest , factors ++ + [smallest] ) + where + smallest :: Int + smallest = head $ tail $ divisors aNumber + +isRelativelyPrime :: Int -> Int -> Bool +isRelativelyPrime a b = S.null $ S.intersection ( S.fromList $ + primeFactors a ) ( S.fromList $ primeFactors b ) + +isDuffinian :: Int -> Bool +isDuffinian n = and [(length $ primeFactors n ) > 1 , isRelativelyPrime + ( sum $ divisors n ) n] + +solution :: [Int] +solution = take 50 $ filter isDuffinian [1..] + +findTriplets :: [[Int]] +findTriplets = take 15 $ filter condition $ divvy 3 1 $ filter + isDuffinian [1..] + where + condition :: [Int] -> Bool + condition [a , b , c] = b == a + 1 && c == b + 1 + +outputTriplet :: [Int] -> String +outputTriplet [a , b , c] = "(" ++ replicate ( 6 - length sa ) ' ' ++ + sa ++ replicate (6 - length sb) ' ' ++ sb ++ replicate (6 - length sc ) + ' ' ++ sc ++ " )" + where + sa = show a + sb = show b + sc = show c + +main :: IO ( ) +main = do + putStrLn "The first 50 Duffinian numbers are :" + print solution + putStrLn "The first 15 Duffinian triplets are:" + mapM_ (\t -> putStrLn $ outputTriplet t ) findTriplets diff --git a/Task/Duffinian-numbers/Icon/duffinian-numbers.icon b/Task/Duffinian-numbers/Icon/duffinian-numbers.icon new file mode 100644 index 0000000000..5ca26be44f --- /dev/null +++ b/Task/Duffinian-numbers/Icon/duffinian-numbers.icon @@ -0,0 +1,28 @@ +procedure main(A) + write("The first 50 Duffian numbers:") + every writes(" ",isduffinian(seq())\50) + write("\n") + limit := 15 + write("The first ",limit," Duffian triples:") + every (isduffinian(n := seq()),isduffinian(n+1),isduffinian(n+2))\limit do + write("\t(",n,",",n+1,",",n+2,")") +end + +procedure isduffinian(n) + x := \cfact(n)**\afact(sumfactors(n)) + return (*\x = 1, !x = 1, n) +end + +procedure cfact(n) # all factors of n if n is a composite number + return (*(f := afact(n)) > 2, f) +end + +procedure afact(n) # all factors of n + every (f := set(), i := 1 to n, n%i = 0,insert(f,i)) + return f +end + +procedure sumfactors(n) + every (s := 0, i := 1 to n, n%i = 0) do s +:= i + return s +end diff --git a/Task/Duffinian-numbers/JavaScript/duffinian-numbers.js b/Task/Duffinian-numbers/JavaScript/duffinian-numbers.js new file mode 100644 index 0000000000..1c0331bc11 --- /dev/null +++ b/Task/Duffinian-numbers/JavaScript/duffinian-numbers.js @@ -0,0 +1,49 @@ +'use strict'; + +// ---------- helpers ---------- +const gcd = (a, b) => { + while (b !== 0) [a, b] = [b, a % b]; + return a; +}; + +// ---------- core logic ---------- +function createDuffians(limit) { + // divisor-sum table: divSum[i] = σ(i) + const divSum = new Array(limit).fill(1); + for (let i = 2; i < limit; ++i) { + for (let j = i; j < limit; j += i) divSum[j] += i; + } + + // mark non-Duffinians with 0 + divSum[1] = 0; // 1 is not Duffinian + for (let n = 2; n < limit; ++n) { + const s = divSum[n]; + if (s === n + 1 || gcd(n, s) !== 1) divSum[n] = 0; + } + return divSum; +} + +// ---------- main ---------- +const duffians = createDuffians(11_000); + +console.log('The first 50 Duffinian numbers:'); +let count = 0, n = 1; +while (count < 50) { + if (duffians[n] > 0) { + process.stdout.write(String(n).padStart(4) + (++count % 25 ? '' : '\n')); + } + ++n; +} +console.log(); + +console.log('The first 16 Duffinian triplets:'); +count = 0; +n = 3; +while (count < 16) { + if (duffians[n - 2] && duffians[n - 1] && duffians[n]) { + const triplet = `(${n - 2}, ${n - 1}, ${n})`; + process.stdout.write(triplet.padStart(22) + (++count % 4 ? '' : '\n')); + } + ++n; +} +console.log(); diff --git a/Task/Duffinian-numbers/Julia/duffinian-numbers.julia b/Task/Duffinian-numbers/Julia/duffinian-numbers.jl similarity index 100% rename from Task/Duffinian-numbers/Julia/duffinian-numbers.julia rename to Task/Duffinian-numbers/Julia/duffinian-numbers.jl diff --git a/Task/Duffinian-numbers/Lua/duffinian-numbers.lua b/Task/Duffinian-numbers/Lua/duffinian-numbers.lua new file mode 100644 index 0000000000..a8422b4049 --- /dev/null +++ b/Task/Duffinian-numbers/Lua/duffinian-numbers.lua @@ -0,0 +1,58 @@ +function gcd(a, b) + while b ~= 0 do + a, b = b, a % b + end + return a +end + +function duffinian(n) + if n == 2 then return false end + local total = 1 + local power = 2 + local m = n + while (n & 1) == 0 do + total = total + power + power = power << 1 + n = n >> 1 + end + local p = 3 + while p * p <= n do + local sum = 1 + local power = p + while n % p == 0 do + sum = sum + power + power = power * p + n = n / p + end + total = total * sum + p = p + 2 + end + if m == n then return false end + if n > 1 then total = total * (n + 1) end + return gcd(total, m) == 1 +end + +print("First 50 Duffinian numbers:") +count = 0 +n = 1 +while count < 50 do + if duffinian(n) then + count = count + 1 + if count % 10 == 0 then space = 10 else space = 32 end + io.write(string.format('%3d%c', n, space)) + end + n = n + 1 +end + +print("\nFirst 30 Duffinian triplets:") +n = 1 +m = 0 +count = 0 +while count < 30 do + if duffinian(n) then m = m + 1 else m = 0 end + if m == 3 then + count = count + 1 + print(string.format('%d, %d, %d', n - 2, n - 1, n)) + end + n = n + 1 +end diff --git a/Task/Duffinian-numbers/PascalABC.NET/duffinian-numbers.pas b/Task/Duffinian-numbers/PascalABC.NET/duffinian-numbers.pas new file mode 100644 index 0000000000..e0d2dd58cb --- /dev/null +++ b/Task/Duffinian-numbers/PascalABC.NET/duffinian-numbers.pas @@ -0,0 +1,36 @@ +uses school; + +function is_duffinian(x: integer) := + (gcd(x, divisors(x).Sum) = 1) and + (divisors(x).ToArray.Length > 2); + +begin + var count := 0; + var i := 0; + writeln('First 50 Duffinian numbers:'); + while count < 50 do + begin + if is_duffinian(i) then + begin + write(i:4); + count += 1; + if count mod 10 = 0 then writeln; + end; + i += 1 + end; + + count := 0; + i := 0; + writeln; + writeln('First 15 Duffinian triplets:'); + while count < 15 do + begin + if is_duffinian(i) and is_duffinian(i + 1) and is_duffinian(i + 2) then + begin + writeln(i:6, i + 1:6, i + 2:6); + count += 1; + i += 3; + end; + i += 1; + end; +end. diff --git a/Task/Duffinian-numbers/Refal/duffinian-numbers.refal b/Task/Duffinian-numbers/Refal/duffinian-numbers.refal new file mode 100644 index 0000000000..576fa3f49d --- /dev/null +++ b/Task/Duffinian-numbers/Refal/duffinian-numbers.refal @@ -0,0 +1,76 @@ +$ENTRY Go { + = + >> + + + >; +}; + +ShowTriple { + s.N = >; +}; + +Each { + s.F = ; + s.F t.I e.X = ; +}; + +Group { + s.N = ; + s.N e.X, : (e.1) e.2 = (e.1) ; +}; + +Gen { + s.N s.F = ; + 0 s.F s.I = ; + s.N s.F s.I, : { + True = s.I s.F >; + False = >; + }; +}; + +DuffinianTriple { + s.N, + > + >: True True True = True; + s.N = False; +}; + +Duffinian { + s.N, : s.S, + : s.P, + s.S : { + s.P s.1 = False; + s.Q 1 = True; + s.1 s.2 = False; + }; +}; + +Gcd { + s.A 0 = s.A; + s.A s.B = >; +}; + +SigmaSum { + s.N = 2 >; + s.N s.Sum s.D s.Max, : '+' = s.Sum; + s.N s.Sum s.D s.Max, : s.N = ; + s.N s.Sum s.D s.Max, : 0 = + >> + s.Max>; + s.N s.Sum s.D s.Max = s.Max>; +}; + +Sqrt { + 0 = 1; + 1 = 1; + s.N = >; + s.N s.X0, +
    > 2>: s.X1, + : { + '+' = ; + s.C = s.X0; + }; +}; diff --git a/Task/Duffinian-numbers/Ring/duffinian-numbers.ring b/Task/Duffinian-numbers/Ring/duffinian-numbers.ring new file mode 100644 index 0000000000..c7de980c3e --- /dev/null +++ b/Task/Duffinian-numbers/Ring/duffinian-numbers.ring @@ -0,0 +1,97 @@ +Load "stdlibcore.ring" + +nr = 0 +num = 0 +sig1 = 0 +cmp = 0 + +see "FIRST 50 DUFFINIAN NUMBERS:" + nl + +while nr < 50 + num = num + 1 + sigma = 0 + cmp = comp(num) + if cmp = 1 + sgm = sigm1(num) + relat1prim() + ok +end + +nr = 0 +fok = 0 +numc = 1 +sig1 = 0 +sig2 = 0 +sig3 = 0 + +see nl + "FIRST 15 DUFFINIAN TRIPLETS:" + nl + +while nr < 15 + + num1 = numc + num2 = num1 + 1 + num3 = num2 + 1 + cmp1 = comp(num1) + cmp2 = comp(num2) + cmp3 = comp(num3) + if (cmp1 = 1) and (cmp2 = 1) and (cmp3 = 1) + sigm1(num1) + sigm2(num2) + sigm3(num3) + ok + numc = numc + 1 +end + +func comp(nm) + fok = 0 + flag = 0 + for n = 1 to nm + if nm%n = 0 + flag = flag + 1 + ok + if flag > 2 + fok = 1 + exit + ok + next + return fok + +func sigm1(num1) + sig1 = 0 + for n = 1 to num1 + if num1%n = 0 + sig1 = sig1 + n + ok + next + +func sigm2(num2) + sig2 = 0 + for n = 1 to num2 + if num2%n = 0 + sig2 = sig2 + n + ok + next + +func sigm3(num3) + sig3 = 0 + for n = 1 to num3 + if num3%n = 0 + sig3 = sig3 + n + ok + next + + relat2prim() + +func relat1prim() + if (gcd(num,sig1) = 1) + nr = nr + 1 + see "" + num + " " + ok + return nr + +func relat2prim() + if ((gcd(num1,sig1) = 1) and (gcd(num2,sig2) = 1) and (gcd(num3,sig3) = 1)) + nr = nr + 1 + see "" + num1 + "-" + num3 + " " + ok + return nr diff --git a/Task/Duffinian-numbers/Rust/duffinian-numbers.rs b/Task/Duffinian-numbers/Rust/duffinian-numbers.rs new file mode 100644 index 0000000000..e6b44a1472 --- /dev/null +++ b/Task/Duffinian-numbers/Rust/duffinian-numbers.rs @@ -0,0 +1,97 @@ +fn gcd(mut a: i32, mut b: i32) -> i32 { + while b != 0 { + let temp = b; + b = a % b; + a = temp; + } + a +} + +fn duffinian(n: i32) -> bool { + if n == 2 { + return false; + } + + let mut total = 1; + let mut power = 2; + let m = n; + let mut n = n; + + // Handle powers of 2 + while (n & 1) == 0 { + total += power; + power <<= 1; + n >>= 1; + } + + // Handle odd prime factors + let mut p = 3; + while p * p <= n { + let mut sum = 1; + power = p; + while n % p == 0 { + sum += power; + power *= p; + n /= p; + } + total *= sum; + p += 2; + } + + // Check if n is composite + if m == n { + return false; + } + + // Handle remaining prime factor + if n > 1 { + total *= n + 1; + } + + gcd(total, m) == 1 +} + +fn main() { + println!("First 50 Duffinian numbers:"); + let mut count = 0; + let mut n = 1; + + while count < 50 { + if duffinian(n) { + print!("{:3}", n); + count += 1; + if count % 10 == 0 { + println!(); + } else { + print!(" "); + } + } + n += 1; + } + + println!("\nFirst 50 Duffinian triplets:"); + let mut n = 1; + let mut m = 0; + let mut count = 0; + + while count < 50 { + if duffinian(n) { + m += 1; + } else { + m = 0; + } + + if m == 3 { + let triplet = format!("({}, {}, {})", n - 2, n - 1, n); + print!("{:<24}", triplet); + count += 1; + if count % 3 == 0 { + println!(); + } else { + print!(" "); + } + } + n += 1; + } + println!(); +} diff --git a/Task/Duffinian-numbers/SETL/duffinian-numbers.setl b/Task/Duffinian-numbers/SETL/duffinian-numbers.setl new file mode 100644 index 0000000000..792e5adddc --- /dev/null +++ b/Task/Duffinian-numbers/SETL/duffinian-numbers.setl @@ -0,0 +1,48 @@ +program duffinian_numbers; + init sigma := divisor_sum_table(20000); + + print("First 50 Duffinian numbers:"); + loop for n in first(50, routine is_duffinian) do + nprint(lpad(str n, 6)); + if (col +:= 1) mod 10 = 0 then print; end if; + end loop; + + print; + print("First 15 Duffinian triplets:"); + loop for n in first(15, routine is_duffinian_triplet) do + print(+/[lpad(str i, 6) : i in [n,n+1,n+2]]); + end loop; + + proc first(num, pred); + ls := []; + loop while #ls < num do + loop until call(pred, n) do + n +:= 1; + end loop; + ls with:= n; + end loop; + return ls; + end proc; + + proc is_duffinian_triplet(n); + return and/[is_duffinian(i) : i in [n,n+1,n+2]]; + end proc; + + proc is_duffinian(n); + return sigma(n) > n+1 and gcd(n, sigma(n)) = 1; + end proc; + + proc gcd(a,b); + return if b=0 then a else gcd(b, a mod b) end; + end proc; + + proc divisor_sum_table(sz); + ds := [0] * sz; + loop for i in [1..sz] do + loop for j in [i,i+i..sz] do + ds(j) +:= i; + end loop; + end loop; + return ds; + end proc; +end program; diff --git a/Task/Dutch-national-flag-problem/ANSI-BASIC/dutch-national-flag-problem.basic b/Task/Dutch-national-flag-problem/ANSI-BASIC/dutch-national-flag-problem.basic new file mode 100644 index 0000000000..1c951186b3 --- /dev/null +++ b/Task/Dutch-national-flag-problem/ANSI-BASIC/dutch-national-flag-problem.basic @@ -0,0 +1,59 @@ +100 REM Dutch national flag problem +110 DECLARE EXTERNAL SUB PrintColorSeq +120 DECLARE EXTERNAL SUB SortByColor +130 REM 0: blue, 1: while, 2: red +140 DIM T(0 TO 19) +150 LET UP = UBOUND(T) +160 REM Set colors +170 RANDOMIZE +180 FOR I = 0 TO UP +190 LET T(I) = INT(RND * 3) +200 NEXT I +210 PRINT "Unsorted:" +220 CALL PrintColorSeq(T) +230 CALL SortByColor(T) +240 PRINT +250 PRINT "Sorted:" +260 CALL PrintColorSeq(T) +270 END +280 ! +290 EXTERNAL SUB PrintColorSeq (T()) +300 FOR I = 0 TO UBOUND(T) +310 SELECT CASE T(I) +320 CASE 0 +330 PRINT "B"; +340 CASE 1 +350 PRINT "W"; +360 CASE 2 +370 PRINT "R"; +380 END SELECT +390 NEXT I +400 PRINT +410 END SUB +420 ! +430 EXTERNAL SUB SortByColor (T()) +440 DECLARE EXTERNAL SUB Swap +450 LET B = 0 +460 LET W = 0 +470 LET R = UBOUND(T) +480 DO WHILE W <= R +490 SELECT CASE T(W) +500 CASE 1 +510 LET W = W + 1 +520 CASE 0 +530 CALL Swap(T(B), T(W)) +540 LET B = B + 1 +550 LET W = W + 1 +560 CASE 2 +570 call Swap(T(W), T(R)) +580 LET R = R - 1 +590 END SELECT +600 LOOP +610 END SUB +620 ! +630 EXTERNAL SUB Swap(A, B) +640 REM Some implementations have the SWAP statement, but it is not standard +650 LET Tmp = A +660 LET A = B +670 LET B = Tmp +680 END SUB diff --git a/Task/Dutch-national-flag-problem/Ada/dutch-national-flag-problem.ada b/Task/Dutch-national-flag-problem/Ada/dutch-national-flag-problem.adb similarity index 100% rename from Task/Dutch-national-flag-problem/Ada/dutch-national-flag-problem.ada rename to Task/Dutch-national-flag-problem/Ada/dutch-national-flag-problem.adb diff --git a/Task/Dutch-national-flag-problem/AutoIt/dutch-national-flag-problem.autoit b/Task/Dutch-national-flag-problem/AutoIt/dutch-national-flag-problem.au3 similarity index 100% rename from Task/Dutch-national-flag-problem/AutoIt/dutch-national-flag-problem.autoit rename to Task/Dutch-national-flag-problem/AutoIt/dutch-national-flag-problem.au3 diff --git a/Task/Dutch-national-flag-problem/BQN/dutch-national-flag-problem.bqn b/Task/Dutch-national-flag-problem/BQN/dutch-national-flag-problem.bqn new file mode 100644 index 0000000000..bfa3b6664a --- /dev/null +++ b/Task/Dutch-national-flag-problem/BQN/dutch-national-flag-problem.bqn @@ -0,0 +1,5 @@ +Make ← •rand.Range⟜≠⊏⊢ +IsSorted ← ∧´·≤˝˘2↕⊐ +Arrange ← /⁼∘⊐/⊣ + +20(⊢(⊢⋈IsSorted)⎉1⊢(⊢≍Arrange)Make)"RWB" diff --git a/Task/Dutch-national-flag-problem/C-sharp/dutch-national-flag-problem.cs b/Task/Dutch-national-flag-problem/C-sharp/dutch-national-flag-problem-1.cs similarity index 100% rename from Task/Dutch-national-flag-problem/C-sharp/dutch-national-flag-problem.cs rename to Task/Dutch-national-flag-problem/C-sharp/dutch-national-flag-problem-1.cs diff --git a/Task/Dutch-national-flag-problem/C-sharp/dutch-national-flag-problem-2.cs b/Task/Dutch-national-flag-problem/C-sharp/dutch-national-flag-problem-2.cs new file mode 100644 index 0000000000..4a1787555d --- /dev/null +++ b/Task/Dutch-national-flag-problem/C-sharp/dutch-national-flag-problem-2.cs @@ -0,0 +1,76 @@ +// Dutch national flag problem +using System; + +class DutchFlagProblem +{ + enum Color {Blue, White, Red}; + + static void WriteColorSeq(Color[] t) + { + uint n = (uint)t.Length; + for (uint i = 0; i < n; i++) + { + switch (t[i]) + { + case Color.Blue: + Console.Write("B"); + break; + case Color.White: + Console.Write("W"); + break; + case Color.Red: + Console.Write("R"); + break; + }; + } + Console.WriteLine(); + } + + static void Swap(ref Color x, ref Color y) + { + Color temp = x; + x = y; + y = temp; + } + + static void SortByColor(Color[] t) + { + uint b = 0, w = 0, r = (uint)t.Length - 1; + while (w <= r) + { + switch (t[w]) + { + case Color.White: + w++; + break; + case Color.Blue: + Swap(ref t[b], ref t[w]); + b++; + w++; + break; + case Color.Red: + Swap(ref t[w], ref t[r]); + r--; + break; + } + } + } + + static void Main() + { + const uint N = 20; + Color[] t = new Color[N]; + + // Set colors + Random rand = new Random(); + for (uint i = 0; i < N; i++) + t[i] = (Color)(rand.Next(3)); + + Console.WriteLine("Unsorted:"); + WriteColorSeq(t); + SortByColor(t); + Console.WriteLine(); + Console.WriteLine("Sorted:"); + WriteColorSeq(t); + } +} diff --git a/Task/Dutch-national-flag-problem/Crystal/dutch-national-flag-problem.cr b/Task/Dutch-national-flag-problem/Crystal/dutch-national-flag-problem.cr new file mode 100644 index 0000000000..3bbbfee1f8 --- /dev/null +++ b/Task/Dutch-national-flag-problem/Crystal/dutch-national-flag-problem.cr @@ -0,0 +1,34 @@ +enum FlagColor + Red + White + Blue + + def to_s + ["🔴", "⚪", "🔵"][value] + end +end + +module Indexable + def sorted? + (1...size).each do |i| + if self[i] < self[i-1] + return false + end + end + true + end +end + +balls = loop do + arr = Array.new(20) { FlagColor.values.sample } + break arr unless arr.sorted? +end + +puts balls.join +puts "Sorted: #{balls.sorted?}" +puts + +balls.sort! + +puts balls.join +puts "Sorted: #{balls.sorted?}" diff --git a/Task/Dutch-national-flag-problem/D/dutch-national-flag-problem-1.d b/Task/Dutch-national-flag-problem/D/dutch-national-flag-problem-1.d index afeef682f4..bed0a7a25d 100644 --- a/Task/Dutch-national-flag-problem/D/dutch-national-flag-problem-1.d +++ b/Task/Dutch-national-flag-problem/D/dutch-national-flag-problem-1.d @@ -3,7 +3,7 @@ import std.stdio, std.random, std.algorithm, std.traits, std.array; enum DutchColors { red, white, blue } void dutchNationalFlagSort(DutchColors[] items) pure nothrow @nogc { - int lo, mid, hi = items.length - 1; + ulong lo, mid, hi = items.length - 1; while (mid <= hi) final switch (items[mid]) { diff --git a/Task/Dutch-national-flag-problem/D/dutch-national-flag-problem-2.d b/Task/Dutch-national-flag-problem/D/dutch-national-flag-problem-2.d index 03a077347b..f6ba27017a 100644 --- a/Task/Dutch-national-flag-problem/D/dutch-national-flag-problem-2.d +++ b/Task/Dutch-national-flag-problem/D/dutch-national-flag-problem-2.d @@ -62,7 +62,7 @@ void main() { // More tests: foreach (i; 0 .. 100_000) { - int n = uniform(0, balls.length); + ulong n = uniform(0, balls.length); foreach (ref ball; balls[0 .. n]) ball = [EnumMembers!DutchColors][uniform(0, $)]; balls[0 .. n].dutchNationalFlagSort(DutchColors.red, diff --git a/Task/Dutch-national-flag-problem/Delphi/dutch-national-flag-problem.delphi b/Task/Dutch-national-flag-problem/Delphi/dutch-national-flag-problem.pas similarity index 100% rename from Task/Dutch-national-flag-problem/Delphi/dutch-national-flag-problem.delphi rename to Task/Dutch-national-flag-problem/Delphi/dutch-national-flag-problem.pas 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 97bf8d02eb..10f3b5828a 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,12 +1,10 @@ col$[] = [ "red" "white" "blue" ] for i to 8 - b[] &= randint 3 + b[] &= random 1 3 . for b in b[] write col$[b] & " " - if b < b0 - not_sorted = 1 - . + if b < b0 : not_sorted = 1 b0 = b . print "" @@ -16,9 +14,7 @@ if not_sorted = 0 else for i = 1 to len b[] - 1 for j = i + 1 to len b[] - if b[j] < b[i] - swap b[j] b[i] - . + if b[j] < b[i] : swap b[j] b[i] . . for b in b[] diff --git a/Task/Dutch-national-flag-problem/Elixir/dutch-national-flag-problem.elixir b/Task/Dutch-national-flag-problem/Elixir/dutch-national-flag-problem.ex similarity index 100% rename from Task/Dutch-national-flag-problem/Elixir/dutch-national-flag-problem.elixir rename to Task/Dutch-national-flag-problem/Elixir/dutch-national-flag-problem.ex diff --git a/Task/Dutch-national-flag-problem/Erlang/dutch-national-flag-problem-1.erl b/Task/Dutch-national-flag-problem/Erlang/dutch-national-flag-problem-1.erl index 53fef5d216..4015d07d23 100644 --- a/Task/Dutch-national-flag-problem/Erlang/dutch-national-flag-problem-1.erl +++ b/Task/Dutch-national-flag-problem/Erlang/dutch-national-flag-problem-1.erl @@ -5,7 +5,7 @@ ball(red) -> 1; ball(white) -> 2; ball(blue) -> 3. -random_ball() -> lists:nth(random:uniform(3), [red, white, blue]). +random_ball() -> lists:nth(rand:uniform(3), [red, white, blue]). random_balls(N) -> random_balls(N,[]). random_balls(0,L) -> L; diff --git a/Task/Dutch-national-flag-problem/Free-Pascal-Lazarus/dutch-national-flag-problem.pas b/Task/Dutch-national-flag-problem/Free-Pascal-Lazarus/dutch-national-flag-problem.pas new file mode 100644 index 0000000000..8745222d90 --- /dev/null +++ b/Task/Dutch-national-flag-problem/Free-Pascal-Lazarus/dutch-national-flag-problem.pas @@ -0,0 +1,74 @@ +program DutchF; + + { Dutch national flag problem } + +type + TColor = (Blue, White, Red); + +const + N = 20; + +var + T: array [0 .. N - 1] of TColor; + I: cardinal; + + procedure Swap(var A, B: TColor); + var + Tmp: TColor; + begin + Tmp := A; + A := B; + B := Tmp; + end; + + procedure WriteColorSeq(T: array of TColor); + var + I: cardinal; + begin + for I := low(T) to high(T) do + case T[I] of + Blue: Write('B'); + White: Write('W'); + Red: Write('R'); + end; + WriteLn; + end; + + procedure SortByColor(var T: array of TColor); + var + B, W, R: cardinal; + begin + B := Low(T); + W := Low(T); + R := High(T); + while W <= R do + case T[W] of + White: + Inc(W); + Blue: + begin + Swap(T[B], T[W]); + Inc(B); + Inc(W); + end; + Red: + begin + Swap(T[W], T[R]); + Dec(R); + end; + end; + end; + +begin + { Set colors } + Randomize; + for I := 0 to N - 1 do + T[I] := TColor(Random(3)); + writeln('Unsorted:'); + WriteColorSeq(T); + SortByColor(T); + WriteLn; + writeln('Sorted:'); + WriteColorSeq(T); + {readln;} +end. diff --git a/Task/Dutch-national-flag-problem/FutureBasic/dutch-national-flag-problem.basic b/Task/Dutch-national-flag-problem/FutureBasic/dutch-national-flag-problem.basic new file mode 100644 index 0000000000..f7c621a282 --- /dev/null +++ b/Task/Dutch-national-flag-problem/FutureBasic/dutch-national-flag-problem.basic @@ -0,0 +1,43 @@ +void local fn DrawBalls( y as long, balls as CFArrayRef, sort as BOOL ) + long col, prevCol = 0, x = 10 + CFArrayRef cols = @[fn ColorWithSRGB(.78,.06,.18,1.0),fn ColorWhite,fn ColorWithSRGB(0,.24,.65,1.0)] + if ( sort ) then balls = fn ArraySortedArrayUsingSelector( balls, @"compare:" ) + + pen -1 + for long i = 0 to len(balls) - 1 + col = intval(balls[i]) + if ( sort == YES ) + if ( col != prevCol ) then y += 30 : x = 10 + else + if ( i > 0 && i % 15 == 0 ) then y += 30 : x = 10 + end if + oval fill (x,y,30,30), cols[col] + x += 30 + prevCol = col + next +end fn + +void local fn DutchNationalFlagProblem + window 1, @"Dutch national flag problem", (0,0,470,230) + WindowSetBackgroundColor( 1, fn ColorWithSRGB(1.0,.61,0,1.0) ) + + CFMutableArrayRef balls = fn MutableArrayNew + + text @"Menlo-Bold",, fn ColorWhite + + for long i = 0 to 29 + balls[i] = @(rnd(3)-1) + next + + print @"Unsorted:" + fn DrawBalls( 20, balls, NO ) + + print %(3,100)@"Sorted:" + fn DrawBalls( 120, balls, YES ) +end fn + +random + +fn DutchNationalFlagProblem + +HandleEvents diff --git a/Task/Dutch-national-flag-problem/GW-BASIC/dutch-national-flag-problem.basic b/Task/Dutch-national-flag-problem/GW-BASIC/dutch-national-flag-problem.basic new file mode 100644 index 0000000000..d0fd2bce6a --- /dev/null +++ b/Task/Dutch-national-flag-problem/GW-BASIC/dutch-national-flag-problem.basic @@ -0,0 +1,42 @@ +100 REM Dutch national flag problem +110 REM 0: blue, 1: while, 2: red +120 OPTION BASE 0 +130 N% = 20 +140 UP% = N% - 1 +150 DIM T%(UP%) +160 REM Set colors +170 RANDOMIZE +180 FOR I% = 0 TO UP% +190 T%(I%) = INT(RND * 3) +200 NEXT I% +210 PRINT "Unsorted:" +220 GOSUB 1000 +230 GOSUB 2000 +240 PRINT +250 PRINT "Sorted:" +260 GOSUB 1000 +270 END +1000 REM ** Print color sequence +1010 FOR I% = 0 TO UP% +1020 IF T%(I%) = 0 THEN PRINT "B"; ELSE IF T%(I%) = 1 THEN PRINT "W"; ELSE PRINT "R"; +1030 NEXT I% +1040 PRINT +1050 RETURN +2000 REM ** Sort by color +2010 B% = 0: W% = 0: R% = UP% +2020 WHILE W% <= R% +2030 IF T%(W%) <> 1 THEN 2070 +2040 REM white +2050 W% = W% + 1 +2060 GOTO 2160 +2070 IF T%(W%) <> 0 THEN 2130 +2080 REM blue +2090 SWAP T%(B%), T%(W%) +2100 B% = B% + 1 +2110 W% = W% + 1 +2120 GOTO 2160 +2130 REM red +2140 SWAP T%(W%), T%(R%) +2150 R% = R% - 1 +2160 WEND +2170 RETURN diff --git a/Task/Dutch-national-flag-problem/Java/dutch-national-flag-problem.java b/Task/Dutch-national-flag-problem/Java/dutch-national-flag-problem-1.java similarity index 100% rename from Task/Dutch-national-flag-problem/Java/dutch-national-flag-problem.java rename to Task/Dutch-national-flag-problem/Java/dutch-national-flag-problem-1.java diff --git a/Task/Dutch-national-flag-problem/Java/dutch-national-flag-problem-2.java b/Task/Dutch-national-flag-problem/Java/dutch-national-flag-problem-2.java new file mode 100644 index 0000000000..3c8b7d46da --- /dev/null +++ b/Task/Dutch-national-flag-problem/Java/dutch-national-flag-problem-2.java @@ -0,0 +1,79 @@ +// Dutch national flag problem + +public class Main { + + enum Color {BLUE, WHITE, RED}; + + static final int N = 20; + + static void printColorSeq(Color[] t) { + int n = t.length; + for (int i = 0; i < n; i++) { + switch (t[i]) { + case BLUE: + System.out.print("B"); + break; + case WHITE: + System.out.print("W"); + break; + case RED: + System.out.print("R"); + break; + } + } + System.out.println(); + } + + static void swapElems(Color[] arr, int i, int j) { + Color temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + + static void sortByColor(Color[] t) { + int b = 0, w = 0, r = t.length - 1; + while (w <= r) { + switch (t[w]) { + case WHITE: + w++; + break; + case BLUE: + swapElems(t, b, w); + b++; + w++; + break; + case RED: + swapElems(t, w, r); + r--; + break; + } + } + } + + public static void main(String[] args) { + Color[] t = new Color[N]; + + // Set colors + for (int i = 0; i < N; i++) { + int ci = (int)(Math.random() * 3); + switch (ci) { + case 0: + t[i] = Color.BLUE; + break; + case 1: + t[i] = Color.WHITE; + break; + case 2: + t[i] = Color.RED; + break; + } + } + + System.out.println("Unsorted:"); + printColorSeq(t); + sortByColor(t); + System.out.println(); + System.out.println("Sorted:"); + printColorSeq(t); + } +} diff --git a/Task/Dutch-national-flag-problem/Julia/dutch-national-flag-problem-1.jl b/Task/Dutch-national-flag-problem/Julia/dutch-national-flag-problem-1.jl new file mode 100644 index 0000000000..5aa84ff6c8 --- /dev/null +++ b/Task/Dutch-national-flag-problem/Julia/dutch-national-flag-problem-1.jl @@ -0,0 +1,26 @@ +using Printf + +const COLORS = ["red", "white", "blue"] + +function dutchsort!(a::AbstractVector, lo=COLORS[1], hi=COLORS[end]) + i = 1 + j = 1 + n = length(a) + while j <= n + if a[j] == lo + a[i], a[j] = a[j], a[i] + i += 1 + j += 1 + elseif a[j] == hi + a[j], a[n] = a[n], a[j] + n -= 1 + else + j += 1 + end + end + return a +end + +function dutchsort(a::AbstractVector, lo=COLORS[1], hi=COLORS[end]) + dutchsort!(copy(a), lo, hi) +end diff --git a/Task/Dutch-national-flag-problem/Julia/dutch-national-flag-problem-1.julia b/Task/Dutch-national-flag-problem/Julia/dutch-national-flag-problem-1.julia deleted file mode 100644 index 6ac9875975..0000000000 --- a/Task/Dutch-national-flag-problem/Julia/dutch-national-flag-problem-1.julia +++ /dev/null @@ -1,24 +0,0 @@ -const COLORS = ["red", "white", "blue"] - -function dutchsort!(a::Array{ASCIIString,1}, lo=COLORS[1], hi=COLORS[end]) - i = 1 - j = 1 - n = length(a) - while j <= n - if a[j] == lo - a[i], a[j] = a[j], a[i] - i += 1 - j += 1 - elseif a[j] == hi - a[j], a[n] = a[n], a[j] - n -= 1 - else - j += 1 - end - end - return a -end - -function dutchsort(a::Array{ASCIIString,1}, lo=COLORS[1], hi=COLORS[end]) - dutchsort!(copy(a), lo, hi) -end diff --git a/Task/Dutch-national-flag-problem/Julia/dutch-national-flag-problem-2.jl b/Task/Dutch-national-flag-problem/Julia/dutch-national-flag-problem-2.jl new file mode 100644 index 0000000000..fc37d7ec80 --- /dev/null +++ b/Task/Dutch-national-flag-problem/Julia/dutch-national-flag-problem-2.jl @@ -0,0 +1,30 @@ +function formatdf(a::AbstractVector) + i = 0 + s = " " + for c in a + s *= @sprintf "%6s" c + i += 1 + i %= 8 + if i == 0 + s *= "\n " + end + end + return s +end + +const cnum = 20 +const d = [COLORS[rand(1:3)] for i in 1:cnum] +while d == dutchsort(d) + d .= [COLORS[rand(1:3)] for i in 1:cnum] +end + +println("The original list is:") +println(formatdf(d)) + +print("Sorting with dutchsort, after") +@time e = dutchsort(d) +println(formatdf(e)) + +print("Sorting conventionally, after") +@time e = sort(d, by = x -> findfirst(==(x), COLORS)) +println(formatdf(e)) diff --git a/Task/Dutch-national-flag-problem/Julia/dutch-national-flag-problem-2.julia b/Task/Dutch-national-flag-problem/Julia/dutch-national-flag-problem-2.julia deleted file mode 100644 index d597551c58..0000000000 --- a/Task/Dutch-national-flag-problem/Julia/dutch-national-flag-problem-2.julia +++ /dev/null @@ -1,30 +0,0 @@ -function formatdf(a::Array{ASCIIString,1}) - i = 0 - s = " " - for c in a - s *= @sprintf "%6s" c - i += 1 - i %= 8 - if i == 0 - s *= "\n " - end - end - return s -end - -cnum = 20 -d = [COLORS[rand(1:3)] for i in 1:cnum] -while d == dutchsort(d) - d = [COLORS[rand(1:3)] for i in 1:cnum] -end - -println("The original list is:") -println(formatdf(d)) - -print("Sorting with dutchsort, ") -@time e = dutchsort(d) -println(formatdf(e)) - -print("Sorting conventionally, ") -@time e = sort(d, by=x->findfirst(COLORS, x)) -println(formatdf(e)) diff --git a/Task/Dutch-national-flag-problem/Kotlin/dutch-national-flag-problem.kotlin b/Task/Dutch-national-flag-problem/Kotlin/dutch-national-flag-problem.kts similarity index 100% rename from Task/Dutch-national-flag-problem/Kotlin/dutch-national-flag-problem.kotlin rename to Task/Dutch-national-flag-problem/Kotlin/dutch-national-flag-problem.kts diff --git a/Task/Dutch-national-flag-problem/Loglan82/dutch-national-flag-problem.loglan82 b/Task/Dutch-national-flag-problem/Loglan82/dutch-national-flag-problem.loglan82 new file mode 100644 index 0000000000..dee8475b53 --- /dev/null +++ b/Task/Dutch-national-flag-problem/Loglan82/dutch-national-flag-problem.loglan82 @@ -0,0 +1,71 @@ +(* Dutch national flag problem *) + +block +const + c_blue = 0, c_white = 1, c_red = 2, + n = 20; +var + i: integer, + t: arrayof integer; + + unit writeln_color_seq: procedure (t: arrayof integer); + var + i: integer; + begin + for i := lower(t) to upper(t) + do + case t(i) + when c_blue: + write("B"); + when c_white: + write("W"); + when c_red: + write("R"); + esac; + od; + writeln; + end writeln_color_seq; + + unit swap: procedure (inout a, b: integer); + var + tmp: integer; + begin + tmp := a; + a := b; + b := tmp + end swap; + + unit sort_by_color: procedure (t: arrayof integer); + var + b, w, r: integer; + begin + b, w := lower(t); + r := upper(t); + while (w <= r) + do + case t(w) + when c_white: + w := w + 1; + when c_blue: + call swap(t(b), t(w)); + b := b + 1; + w := w + 1; + when c_red: + call swap(t(w), t(r)); + r := r - 1; + esac + od; + end sort_by_color; + +begin + array t dim (0 : n - 1); + + (* Set colors *) + for i := 0 to n - 1 do t(i) := entier(random * 3) od; + writeln("Unsorted:"); + call writeln_color_seq(t); + call sort_by_color(t); + writeln; + writeln("Sorted:"); + call writeln_color_seq(t); +end; diff --git a/Task/Dutch-national-flag-problem/M2000-Interpreter/dutch-national-flag-problem-1.m2000 b/Task/Dutch-national-flag-problem/M2000-Interpreter/dutch-national-flag-problem-1.m2000 new file mode 100644 index 0000000000..12e0137b20 --- /dev/null +++ b/Task/Dutch-national-flag-problem/M2000-Interpreter/dutch-national-flag-problem-1.m2000 @@ -0,0 +1,23 @@ + SortElse=lambda white (a(), &swaps, &compares)->{ + long mid=white + long i, j, k=len(a())-1 + while j<=k + + if a(j)mid then + compares+=2 + swap a(j), a(k) + swaps++ + k-- + else + compares+=2 + j++ + end if + end while + =a() + } diff --git a/Task/Dutch-national-flag-problem/M2000-Interpreter/dutch-national-flag-problem-2.m2000 b/Task/Dutch-national-flag-problem/M2000-Interpreter/dutch-national-flag-problem-2.m2000 new file mode 100644 index 0000000000..acaf408117 --- /dev/null +++ b/Task/Dutch-national-flag-problem/M2000-Interpreter/dutch-national-flag-problem-2.m2000 @@ -0,0 +1,88 @@ +function Dutch_national_flag_problem { + enum bands {red=1, white, blue} + s=red + check_in_order=lambda s, (a as array) ->{ + boolean true=@true, false + k=each(a) + m=s + Z=S + =true + while k + z=array(k) + if m=z else + if m=blue then + =false + break + else + m++ + if m=z else =false : break + end if + end if + end while + } + SortElse=lambda (m(), &swaps, &compares)->{ + long t=len(m()) + dim c(1 to 3)=t + c=1 + for i=0 to len(m())-1 + rem ? "pos:";i;" "; + w=m(i) + if w0 + if c(k)=t then k-- : continue + if m(j)c(k) then c(m(j))=c(k) + rem ? "swap:";m(j);" at pos "+j;" with ";m(c(k)); " at pos ";c(k) + swap m(j), m(c(k)) + rem ? "just swapped array :", m()#str$() + rem ? "c()", c()#str$() + swaps++ + j=c(k) + c(k)++ + end if + k-- + rem ? "k=";k, c(k) + end while + else.if w>c then + c=w + if i-c(c)>1 else c(c)=i + end if + next + =m() + } + random_band=lambda->random(1, 3) + n=random(10, 20) + if n<3 then exit ' need at least 3 colors for the flag - although n now didn't get value 3 we place it to remember it later + do + do + dim balls(n)< { - if size<1 then size=1 - randomitem=lambda a->a#val(random(0,2)) - dim a(size)<{ - Document r$=eval$(array(s)) - if len(s)>1 then - For i=1 to len(s)-1 { - r$=", "+eval$(array(s,i)) - } - end if - =r$ -} -TestSort$=lambda$ (s as array)-> { - ="unsorted: " - x=array(s) - for i=1 to len(s)-1 { - k=array(s,i) - if x>k then break - swap x, k - } - ="sorted: " -} -Positions=lambda mid=White (a as array) ->{ - m=len(a) - dim Base 0, b(m)=-1 - low=-1 - high=m - m-- - i=0 - medpos=stack - link a to a() - for i=m to 0 { - if a(i)<=mid then exit - high-- - b(high)=high - } - for i=0 to m { - if a(i)>=mid then exit - low++ - b(low)=low - } - if high-low>1 then - for i=low+1 to high-1 { - select case a(i)<=>Mid - case -1 - low++ : b(low)=i - case 1 - { - high-- :b(high)=i - if High0 then - dim c() - c()=array(medpos) - stock c(0) keep len(c()), b(low+1) - for i=low+1 to high-1 - if b(i)>low and b(i)i then swap b(b(i)), b(i) - next i - end if - if low>0 then - for i=0 to low - if b(i)<=low and b(i)<>i then swap b(b(i)), b(i) - next - end if - if High=High and b(i)<>i then swap b(b(i)), b(i) - next - end if - =b() -} -InPlace=Lambda (&p(), &Final()) ->{ - def i=0, j=-1, k=-1, many=0 - for i=0 to len(p())-1 - if p(i)<>i then - j=i - z=final(j) - do - final(j)=final(p(j)) - k=j - j=p(j) - p(k)=k - many++ - until j=i - final(k)=z - end if - next - =many -} - - -Dim final(), p(), second(), p1() -Rem final()=(White,Red,Blue,White,Red, Red, Blue) -Rem final()=(white, blue, red, blue, white) - -final()=fillarray(30) -Print "Items: ";len(final()) -Report TestSort$(final())+Display$(final()) -\\ backup for final() for second example -second()=final() -p()=positions(final()) -\\ backup p() to p1() for second example -p1()=p() - - -Report Center, "InPlace" -rem Print p() ' show array items -many=InPlace(&p(), &final()) -rem print p() ' show array items -Report TestSort$(final())+Display$(final()) -print "changes: "; many - - -Report Center, "Using another array to make the changes" -final()=second() -\\ using a second array to place only the changes -item=each(p1()) -many=0 -While item { - if item^=array(item) else final(item^)=second(array(item)) : many++ -} -Report TestSort$(final())+Display$(final()) -print "changes: "; many -Module three_way_partition (A as array, mid as balls, &swaps) { - Def i, j, k - k=Len(A) - Link A to A() - While j < k - if A(j) < mid Then - Swap A(i), A(j) - swaps++ - i++ - j++ - Else.if A(j) > mid Then - k-- - Swap A(j), A(k) - swaps++ - Else - j++ - End if - End While -} -Many=0 -Z=second() -Print -Report center, {Three Way Partition -} -Report TestSort$(Z)+Display$(Z) -three_way_partition Z, White, &many -Print -Report TestSort$(Z)+Display$(Z) -Print "changes: "; many diff --git a/Task/Dutch-national-flag-problem/Modula-2/dutch-national-flag-problem.mod2 b/Task/Dutch-national-flag-problem/Modula-2/dutch-national-flag-problem.mod2 new file mode 100644 index 0000000000..2802b39ad3 --- /dev/null +++ b/Task/Dutch-national-flag-problem/Modula-2/dutch-national-flag-problem.mod2 @@ -0,0 +1,80 @@ +MODULE DutchF; +(* Dutch national flag problem *) + +FROM RandomNumbers IMPORT + Rnd; +FROM STextIO IMPORT + WriteLn, WriteString; + +TYPE + TColor = (Blue, White, Red); + +CONST + N = 20; + +VAR + T: ARRAY [0 .. N - 1] OF TColor; + I: CARDINAL; + +PROCEDURE Swap(VAR A, B: TColor); +VAR + Tmp: TColor; +BEGIN + Tmp := A; + A := B; + B := Tmp +END Swap; + +PROCEDURE WriteColorSeq(T: ARRAY OF TColor); +VAR + I: CARDINAL; +BEGIN + FOR I := 0 TO HIGH(T) DO + CASE T[I] OF + | Blue: + WriteString("B"); + | White: + WriteString("W"); + | Red: + WriteString("R"); + END + END; + WriteLn; +END WriteColorSeq; + +PROCEDURE SortByColor(VAR T: ARRAY OF TColor); +VAR + B, W, R: CARDINAL; +BEGIN + B := 0; + W := 0; + R := HIGH(T); + WHILE W <= R DO + CASE T[W] OF + | White: + W := W + 1; + | Blue: + Swap(T[B], T[W]); + B := B + 1; + W := W + 1; + | Red: + Swap(T[W], T[R]); + R := R - 1; + END; + END; +END SortByColor; + +BEGIN + (* Set colors *) + FOR I := 0 TO N - 1 DO + T[I] := VAL(TColor, Rnd(3)); + END; + WriteString("Unsorted:"); + WriteLn; + WriteColorSeq(T); + SortByColor(T); + WriteLn; + WriteString("Sorted:"); + WriteLn; + WriteColorSeq(T); +END DutchF. diff --git a/Task/Dutch-national-flag-problem/PascalABC.NET/dutch-national-flag-problem.pas b/Task/Dutch-national-flag-problem/PascalABC.NET/dutch-national-flag-problem.pas new file mode 100644 index 0000000000..eaa7d1319a --- /dev/null +++ b/Task/Dutch-national-flag-problem/PascalABC.NET/dutch-national-flag-problem.pas @@ -0,0 +1,33 @@ +type + colors = (red, white, blue); + +procedure threeWayPartition(a: array of colors; mid: colors); +begin + var (i, j) := (0, 0); + var k := a.High; + while j <= k do + if a[j] < mid then + begin + swap(a[i], a[j]); + i += 1; + j += 1; + end + else if a[j] > mid then + begin + swap(a[j], a[k]); + k -= 1; + end + else j += 1; +end; + +begin + var balls: array of colors; + repeat + balls := ArrGen(10, i -> |red, white, blue|.randomelement); + until balls <> balls.Sorted; + + println('Original ball order:', balls); + threewaypartition(balls, white); + println('Sorted ball order: ', balls); + assert(balls <> balls.sorted, 'Not sorted!'); +end. diff --git a/Task/Dutch-national-flag-problem/Phix/dutch-national-flag-problem.phix b/Task/Dutch-national-flag-problem/Phix/dutch-national-flag-problem.phix index a0357d6a9b..6167e25ead 100644 --- a/Task/Dutch-national-flag-problem/Phix/dutch-national-flag-problem.phix +++ b/Task/Dutch-national-flag-problem/Phix/dutch-national-flag-problem.phix @@ -1,41 +1,39 @@ -(phixonline)--> - with javascript_semantics - function three_way_partition(sequence s, integer mid) - integer i=1, j=1, n = length(s) - while j <= n do - if s[j] < mid then - {s[i],s[j]} = {s[j],s[i]} - i += 1 - j += 1 - elsif s[j] > mid then - {s[j],s[n]} = {s[n],s[j]} - n -= 1 - else - j += 1 - end if - end while - return s - end function +with javascript_semantics +function three_way_partition(sequence s, integer mid) + integer i=1, j=1, n = length(s) + while j <= n do + if s[j] < mid then + {s[i],s[j]} = {s[j],s[i]} + i += 1 + j += 1 + elsif s[j] > mid then + {s[j],s[n]} = {s[n],s[j]} + n -= 1 + else + j += 1 + end if + end while + return s +end function - constant colours = {"red","white","blue"} - enum /*red,*/ white = 2, blue, maxc = blue +constant colours = {"red","white","blue"} +enum /*red,*/ white = 2, blue, maxc = blue - procedure show(string msg, sequence s) - sequence t = repeat(0,length(s)) - for i=1 to length(s) do - t[i] = colours[s[i]] - end for - printf(1,"%s: %s\n",{msg,join(t)}) - end procedure +procedure show(string msg, sequence s) + sequence t = repeat(0,length(s)) + for i=1 to length(s) do + t[i] = colours[s[i]] + end for + printf(1,"%s: %s\n",{msg,join(t)}) +end procedure - sequence unsorted, sorted - while 1 do - unsorted = sq_rand(repeat(maxc,12)) - -- sorted = sort(deep_copy(unsorted)) -- (works just as well) - sorted = three_way_partition(deep_copy(unsorted), white) - if unsorted!=sorted then exit end if - ?"oops" - end while - show("Unsorted",unsorted) - show("Sorted",sorted) - n ) + [ 2 ] is white ( --> n ) + [ 3 ] is blue ( --> n ) + + randomise + + [] ' [ red white blue ] + witheach + [ nested swap + 5 random times [ over join ] + swap join ] + + dup [ shuffle 2dup != until ] nip + + say "Before sorting: " dup echo cr + say " After sorting: " sortwith [ dip do do > ] echo cr diff --git a/Task/Dutch-national-flag-problem/QuickBASIC/dutch-national-flag-problem.basic b/Task/Dutch-national-flag-problem/QuickBASIC/dutch-national-flag-problem.basic new file mode 100644 index 0000000000..cca5c51dbe --- /dev/null +++ b/Task/Dutch-national-flag-problem/QuickBASIC/dutch-national-flag-problem.basic @@ -0,0 +1,57 @@ +' Dutch national flag problem +DECLARE SUB PrintColorSeq (T() AS INTEGER) +DECLARE SUB SortByColor (T() AS INTEGER) + +CONST CBLUE% = 0, CWHITE% = 1, CRED% = 2 +CONST N% = 20 +DIM T(0 TO N% - 1) AS INTEGER +DIM I AS INTEGER + +' Set colors +RANDOMIZE TIMER +FOR I = 0 TO N% - 1 + T(I) = INT(RND * 3) +NEXT I + +PRINT "Unsorted:" +CALL PrintColorSeq(T()) +CALL SortByColor(T()) +PRINT +PRINT "Sorted:" +CALL PrintColorSeq(T()) +END + +SUB PrintColorSeq (T() AS INTEGER) + DIM I AS INTEGER + FOR I = 0 TO UBOUND(T) + SELECT CASE T(I) + CASE CBLUE% + PRINT "B"; + CASE CWHITE% + PRINT "W"; + CASE CRED% + PRINT "R"; + END SELECT + NEXT I + PRINT +END SUB + +SUB SortByColor (T() AS INTEGER) + DIM B AS INTEGER, W AS INTEGER, R AS INTEGER + B = 0 + W = 0 + R = UBOUND(T) + DO WHILE W <= R + SELECT CASE T(W) + CASE CWHITE% + W = W + 1 + CASE CBLUE% + SWAP T(B), T(W) + B = B + 1 + W = W + 1 + CASE CRED% + SWAP T(W), T(R) + R = R - 1 + END SELECT + LOOP +END SUB diff --git a/Task/Dutch-national-flag-problem/R/dutch-national-flag-problem.r b/Task/Dutch-national-flag-problem/R/dutch-national-flag-problem.r new file mode 100644 index 0000000000..bf63f230ae --- /dev/null +++ b/Task/Dutch-national-flag-problem/R/dutch-national-flag-problem.r @@ -0,0 +1,26 @@ +colours <- c("Red", "White", "Blue") + +rand_balls <- function(v, f){ + repeat{ + balls <- sample(v, sample(10:20, 1), replace=TRUE) + balls_sorted <- f(balls) + if(!identical(balls, balls_sorted)){ + print(list("Unsorted"=balls, "Sorted"=balls_sorted), quote=FALSE) + break + } + } +} + +#Method 1: converting the vector of colours to a factor and using the built-in sort() function + +colours_ordered <- factor(1:3, labels=colours) +rand_balls(colours_ordered, sort) + +#Method 2: simple counting sort (showcasing the conciseness of R's rep() function) + +counting_sort <- function(v){ + counts <- sapply(1:3, function(n) sum(v==colours[n])) + rep(colours, times=counts) +} + +rand_balls(colours, counting_sort) diff --git a/Task/Dutch-national-flag-problem/Rust/dutch-national-flag-problem.rs b/Task/Dutch-national-flag-problem/Rust/dutch-national-flag-problem.rs new file mode 100644 index 0000000000..325af2792e --- /dev/null +++ b/Task/Dutch-national-flag-problem/Rust/dutch-national-flag-problem.rs @@ -0,0 +1,43 @@ +extern crate rand; // 0.10.0 used + +use rand::prelude::*; + +// Color enums will be sorted by their top-to-bottom declaration order +#[derive(Eq,Ord,PartialOrd,PartialEq,Debug)] +enum Color { + Red, + White, + Blue +} + +fn is_sorted(list: &Vec) -> bool { + let mut state = &Color::Red; + for current in list.iter() { + if current < state { return false; } + if current > state { state = current; } + } + true +} + +fn main() { + let mut rng = rand::rng(); + let mut colors: Vec = Vec::new(); + + for _ in 1..10 { + let r = rng.random_range(0..3); + if r == 0 { colors.push(Color::Red); } + else if r == 1 { colors.push(Color::White); } + else if r == 2 { colors.push(Color::Blue); } + } + + while is_sorted(&colors) { + colors.shuffle(&mut rng); + } + + println!("Before: {:?}", colors); + colors.sort(); + println!("After: {:?}", colors); + if !is_sorted(&colors) { + println!("Oops, did not sort colors correctly!"); + } +} diff --git a/Task/Dutch-national-flag-problem/Rust/dutch-national-flag-problem.rust b/Task/Dutch-national-flag-problem/Rust/dutch-national-flag-problem.rust deleted file mode 100644 index 0a6e2a4972..0000000000 --- a/Task/Dutch-national-flag-problem/Rust/dutch-national-flag-problem.rust +++ /dev/null @@ -1,44 +0,0 @@ -extern crate rand; - -use rand::Rng; - -// Color enums will be sorted by their top-to-bottom declaration order -#[derive(Eq,Ord,PartialOrd,PartialEq,Debug)] -enum Color { - Red, - White, - Blue -} - -fn is_sorted(list: &Vec) -> bool { - let mut state = &Color::Red; - for current in list.iter() { - if current < state { return false; } - if current > state { state = current; } - } - true -} - - -fn main() { - let mut rng = rand::thread_rng(); - let mut colors: Vec = Vec::new(); - - for _ in 1..10 { - let r = rng.gen_range(0, 3); - if r == 0 { colors.push(Color::Red); } - else if r == 1 { colors.push(Color::White); } - else if r == 2 { colors.push(Color::Blue); } - } - - while is_sorted(&colors) { - rng.shuffle(&mut colors); - } - - println!("Before: {:?}", colors); - colors.sort(); - println!("After: {:?}", colors); - if !is_sorted(&colors) { - println!("Oops, did not sort colors correctly!"); - } -} diff --git a/Task/Dutch-national-flag-problem/Uiua/dutch-national-flag-problem.uiua b/Task/Dutch-national-flag-problem/Uiua/dutch-national-flag-problem.uiua new file mode 100644 index 0000000000..354f52209c --- /dev/null +++ b/Task/Dutch-national-flag-problem/Uiua/dutch-national-flag-problem.uiua @@ -0,0 +1,3 @@ +&p.[⍥(⊡⌊×3⚂"RWB")30] # Build it. +&p.⊏▽⊸>2⍏⊛.⊂"RWB" # Sort it, providing model for sort order. +&p⨬("oops"|"good")≍⊏⊸⍏.⊛ # Confirm it's sorted. diff --git a/Task/Dutch-national-flag-problem/V-(Vlang)/dutch-national-flag-problem.v b/Task/Dutch-national-flag-problem/V-(Vlang)/dutch-national-flag-problem.v new file mode 100644 index 0000000000..7f5ba932b3 --- /dev/null +++ b/Task/Dutch-national-flag-problem/V-(Vlang)/dutch-national-flag-problem.v @@ -0,0 +1,25 @@ +import rand + +fn main() { + flag := ["Red","White","Blue"] + mut balls := [10]string{} + mut color :="" + mut number := 0 + + print("Random: |") + for idx in 0..10 { + number = rand.int_in_range(0, 3) or {println("Error: invalid number") exit(1)} + balls[idx] = flag[number] + print("${balls[idx]}" + " |") + } + println("") + + print("Sorted: |") + for idx in 0..3 { + color = flag[idx] + for jdx in 0..10 { + if balls[jdx] == color {print("${balls[jdx]}" + " |")} + } + } + println("") +} diff --git a/Task/Dutch-national-flag-problem/VBScript/dutch-national-flag-problem.vb b/Task/Dutch-national-flag-problem/VBScript/dutch-national-flag-problem.vbs similarity index 100% rename from Task/Dutch-national-flag-problem/VBScript/dutch-national-flag-problem.vb rename to Task/Dutch-national-flag-problem/VBScript/dutch-national-flag-problem.vbs diff --git a/Task/Dynamic-variable-names/ALGOL-68/dynamic-variable-names.alg b/Task/Dynamic-variable-names/ALGOL-68/dynamic-variable-names.alg index 793b3d5407..7a8a5853f6 100644 --- a/Task/Dynamic-variable-names/ALGOL-68/dynamic-variable-names.alg +++ b/Task/Dynamic-variable-names/ALGOL-68/dynamic-variable-names.alg @@ -2,7 +2,8 @@ BEGIN # Simulate dynamic variables using an array, translation of the FreeBASIC MODE DYNAMICVARIABLE = STRUCT( STRING name, value ); - OP LCASE = ( CHAR c )CHAR: IF c >= "A" AND c <= "Z" THEN REPR( ( ABS c - ABS "A" ) + ABS "a" ) ELSE c FI; + OP LCASE = ( CHAR c )CHAR: + IF c >= "A" AND c <= "Z" THEN REPR( ( ABS c - ABS "A" ) + ABS "a" ) ELSE c FI; OP LCASE = ( STRING s )STRING: BEGIN STRING lc := s; @@ -17,13 +18,13 @@ BEGIN # Simulate dynamic variables using an array, translation of the FreeBASIC s[ left : right ] END # TRIM # ; - PROC find variable index = ( []DYNAMICVARIABLE a, STRING v, INT n elements )INT: + PROC find variable index = ( []DYNAMICVARIABLE dyvar, STRING v, INT n elements )INT: BEGIN STRING name = LCASE TRIM v; - INT index := LWB a - 1; + INT index := LWB dyvar - 1; INT max index = index + n elements; - FOR i FROM LWB a TO max index WHILE index < LWB a DO - IF name OF a[ i ] = name THEN index := i FI + FOR i FROM LWB dyvar TO max index WHILE index < LWB dyvar DO + IF name OF dyvar[ i ] = name THEN index := i FI OD; index END # find variable index # ; diff --git a/Task/Dynamic-variable-names/Ballerina/dynamic-variable-names.ballerina b/Task/Dynamic-variable-names/Ballerina/dynamic-variable-names.ballerina new file mode 100644 index 0000000000..6019bb031b --- /dev/null +++ b/Task/Dynamic-variable-names/Ballerina/dynamic-variable-names.ballerina @@ -0,0 +1,16 @@ +import ballerina/io; + +public function main() returns error? { + map nvs = {}; + io:println("Enter three variables:"); + foreach var _ in 0...2 { + string name = io:readln("\n name : "); + string value = io:readln(" value : "); + nvs[name] = check int:fromString(value); + } + + io:println("\nYour variables are:\n"); + foreach string name in nvs.keys() { + io:println(` ${name} = ${nvs[name]}`); + } +} diff --git a/Task/Dynamic-variable-names/C/dynamic-variable-names.c b/Task/Dynamic-variable-names/C/dynamic-variable-names.c new file mode 100644 index 0000000000..d48225edc0 --- /dev/null +++ b/Task/Dynamic-variable-names/C/dynamic-variable-names.c @@ -0,0 +1,135 @@ +#include +#include +#include +#include +#include +#include +#include + +static inline uint64_t hash(void const *cp, size_t n) { + uint64_t h = 0; + uint64_t const e = UINT64_C(2718281828459045235); // e * 10**18 + for(uint8_t const *cb = cp; n > 0; n--) { + h = ((h + n) * e) ^ ((*cb++ & 0xFF) * e); + } + return h; +} + +static void *dup(void const *cp, size_t n) { + void *p = malloc(n); + return memcpy(p, cp, n); +} + +static void *nodup(void const *cp, size_t n) { + return (void*)cp; +} + +#define MAPPED struct mapped_s +MAPPED { + size_t n; + char const *s; +}; +#define MAP struct map_s +MAP { + size_t u; + size_t w; + size_t m; + char a[]; +}; + +static MAP *map_alloc(size_t m, size_t z) { + const size_t N = (((m * z) + (sizeof(MAP)-1)) / sizeof(MAP)) + 1; + MAP *t = calloc(N, sizeof(MAP)); + t->m = m; + t->w = 3 * m / 4; + return t; +} + +static void *map(MAP **t, size_t z, char const *s, size_t n, void *(*dup)(void const *, size_t)) { + if(!*t) { + *t = map_alloc(sizeof(size_t) * CHAR_BIT, z); + } + MAP *f = *t; + uint64_t const h = hash(s, n); + size_t x = (h / f->m) % f->m; + size_t const k = x + !x; + size_t const l = f->m - k; + size_t const y = h % f->m; + x = y; + do { + MAPPED *p = (MAPPED *)&f->a[x*z]; + if((p->n == n) && (memcmp(p->s, s, n) == 0)) { + return p; + } + if((p->n == 0) && dup) { + if(f->u == f->w) { + *t = map_alloc(2 * f->m, z); + for(size_t i = 0; f->u < f->w; i++) { + MAPPED *q = (MAPPED *)&f->a[i*z]; + if(q->n > 0) { + (void)map(t, z, q->s, q->n, nodup); + } + } + free(f); + return map(t, z, s, n, dup); + } + f->u++; + p->n = n; + p->s = dup(s, n); + return p; + } + x = (x >= l) ? ((x + 1) % k) : (x + k); + } while(x != y) + ; + return NULL; +} + +static double mapf(char const *s, double v, void *(*dup)(void const *, size_t)) { + static MAP *t = NULL; + struct { + MAPPED; + double v; + } *p = map(&t, sizeof(*p), s, strlen(s), dup); + if(p) { + if(dup) p->v = v; + return p->v; + } + return NAN; +} + +static inline double assignf(char const *s, double v) { + return mapf(s, v, dup); +} + +static inline double valuef(char const *s) { + return mapf(s, 0, 0); +} + +static char *enter(char const *prompt) { + static char buf[256]; + fputs(prompt, stdout); fflush(stdout); + fgets(buf, sizeof(buf), stdin); + char *s = buf; + for(; *s && !isgraph(*s); s++) + ; + char *t = s + strlen(s); + for(; (t > s) && !isgraph(*(t-1)); t--) + ; + *t = '\0'; + return s; +} + +int main(int argc, char **argv) { + for(;;) { + char const *name = enter("Enter: "); + if(!*name) break; + char *val = strchr(name, '='); + if(val) { + *val++ = '\0'; + assignf(name, strtod(val, NULL)); + } else { + printf("%s = %F\n", name, valuef(name)); + } + } + return 0; +} diff --git a/Task/Dynamic-variable-names/DuckDB/dynamic-variable-names.duckdb b/Task/Dynamic-variable-names/DuckDB/dynamic-variable-names.duckdb new file mode 100644 index 0000000000..e5e9804bf2 --- /dev/null +++ b/Task/Dynamic-variable-names/DuckDB/dynamic-variable-names.duckdb @@ -0,0 +1 @@ +select COLUMNS(x -> x = getenv('variablename')) from t; diff --git a/Task/Dynamic-variable-names/EMal/dynamic-variable-names.emal b/Task/Dynamic-variable-names/EMal/dynamic-variable-names.emal new file mode 100644 index 0000000000..f55c9b8919 --- /dev/null +++ b/Task/Dynamic-variable-names/EMal/dynamic-variable-names.emal @@ -0,0 +1,37 @@ +^|EMal doesn't support the creation of user-defined variable names. + |It can manage symbolic references to existing variables. + |It can use Records to dynamically create fields. + |^ +Record data ← [] +fun fillData ← void by block + for ever + ^|we ask for key/value pairs|^ + text key ← ask(text, "Enter the key or press Enter to quit: ") + if key æ Text.EMPTY do break end + text value ← ask(text, "Enter the value: ") + data[key] ← value ^|here we set the user-defined key field + |on the record data, with the provided value + |^ + end + writeLine() +end +^|here we show how symbolic reference works by using var("variableName")|^ +fun dumpData ← void by text recordName + writeLine("dumping the fields for the record named '", recordName, "'") + Record.keys(var(recordName)).list( 5 { + n = strconv.atoi(os.input("Integer variables (max 5): ")) or { + println("Invalid input!") + continue + } + } + for i <= n { + println("OK, enter the variable names and their values, below:") + println("Variable ${i}") + name = os.input_opt(" Name: ") or { panic("Invalid input!") } + for { + value = strconv.atoi(os.input(" Value: ")) or { + println("Must be a valid number!") + continue + } + break + } + vars[name] += value + i++ + } + println("\n" + "Enter q to quit") + for { + name = os.input_opt("Which variable do you want to inspect: ") or { panic("Invalid input!") } + if name.to_lower() == "q" { break } + if name !in vars { println("Sorry there's no variable of that name, try again!") } + else { println("Its value is ${vars[name]}") } + } +} diff --git a/Task/EKG-sequence-convergence/Ada/ekg-sequence-convergence.ada b/Task/EKG-sequence-convergence/Ada/ekg-sequence-convergence.adb similarity index 100% rename from Task/EKG-sequence-convergence/Ada/ekg-sequence-convergence.ada rename to Task/EKG-sequence-convergence/Ada/ekg-sequence-convergence.adb diff --git a/Task/EKG-sequence-convergence/Arturo/ekg-sequence-convergence.arturo b/Task/EKG-sequence-convergence/Arturo/ekg-sequence-convergence.arturo new file mode 100644 index 0000000000..6f6c56d98c --- /dev/null +++ b/Task/EKG-sequence-convergence/Arturo/ekg-sequence-convergence.arturo @@ -0,0 +1,37 @@ +ekg: function [start, limit][ + result: @[1 start] + + while [limit > size result][ + candidate: 2 + while ø [ + if and? [not? contains? result candidate] + [1 < gcd @[last result candidate]][ + 'result ++ candidate + break + ] + inc 'candidate + ] + ] + + return result +] + +loop [2 5 7 9 10] 'n -> + print ["EKG(" ++ (to :string n) ++ "):" join.with:", " ekg n 10] + +print "" +ekg5: ekg 5 100 +ekg7: ekg 7 100 + +converged?: false +loop 2..99 'i [ + if and? -> ekg5\[i] = ekg7\[i] + -> equal? sort slice ekg5 0 i sort slice ekg7 0 i [ + print ["EKG(5) and EKG(7) converge at term" i+1] + converged?: true + break + ] +] + +unless converged? -> + print "EKG(5) and EKG(7) do not converge within 100 terms" diff --git a/Task/EKG-sequence-convergence/EasyLang/ekg-sequence-convergence.easy b/Task/EKG-sequence-convergence/EasyLang/ekg-sequence-convergence.easy new file mode 100644 index 0000000000..3c42057e99 --- /dev/null +++ b/Task/EKG-sequence-convergence/EasyLang/ekg-sequence-convergence.easy @@ -0,0 +1,22 @@ +func contains a[] b . + for a in a[] : if a = b : return 1 + return 0 +. +func gcd a b . + if b = 0 : return a + return gcd b (a mod b) +. +starts[] = [ 2 5 7 9 10 ] +len ekg[][] 5 +for s to 5 + ekg[s][] = [ 1 starts[s] ] + for n = 2 to 10 + for i = 2 to 1 / 0 + if contains ekg[s][] i = 0 and gcd ekg[s][n], i > 1 + ekg[s][] &= i + break 1 + . + . + . + print ekg[s][] +. diff --git a/Task/EKG-sequence-convergence/Fortran/ekg-sequence-convergence.f b/Task/EKG-sequence-convergence/Fortran/ekg-sequence-convergence.f new file mode 100644 index 0000000000..fddf573531 --- /dev/null +++ b/Task/EKG-sequence-convergence/Fortran/ekg-sequence-convergence.f @@ -0,0 +1,168 @@ + ! EKG sequence convergence + ! tested with Intel ifx (IFX) 2025.2.0 20250605 on Kubuntu 25.04 + ! GNU Fortran (Ubuntu 14.2.0-19ubuntu2) 14.2.0 on Kubuntu 25.04 + ! VSI Fortran x86-64 V8.6-001 on OpenVMS x86_64 V9.2-3 + ! Note that VMS requires switch $Fortran/ccdefault=LIST + ! otherwise 1st character of each output line is interpreted as + ! Carriage Control character. + ! +module EKG +implicit none + +integer, parameter :: nElementsToPrint=10 + + +contains + +subroutine ekgSequence (secondElm, nElm, isq) + ! + ! Construct first 'nElm' elements of the EKG Sequence that has 'secondElm' + ! as second element, knowing first element ios always 1. + ! + + integer, intent(in) :: secondElm + integer, intent(in) :: nElm + + integer, intent(out) :: isq (*) + + integer :: candidate=2 + integer :: ncurrent + + isq(1) = 1 ! 1st element always 1 + isq(2) = secondElm ! 2nd element from argument + ncurrent = 2 ! index to highest known element of sequence isq + + do while (ncurrent .le. nElm) + ! 'candidate' is next element of isq if it is not already in this sequence AND + ! if it shares at least 1 prime factor with highest known element if isq + ! which means GCD(candidate, highest element of isq) is >1 + if ( (.not. containsElement (isq, ncurrent, candidate)) & + .and. gcd(isq(ncurrent), candidate) > 1 ) then + ! found next element of isq + ncurrent = ncurrent + 1 + isq(ncurrent) = candidate + candidate = 2; ! start over again + else + ! Not a candidate: try next one. + candidate= candidate + 1 + end if + end do +end subroutine ekgSequence + +function containsElement (isq, nElm, elm) result (yes) + ! + ! return .true. if number 'elm' can be found within + ! first 'nElm' elements of sequence 'isq' . + ! + integer, intent(in) :: nElm + integer, intent(in) :: isq (nElm) + integer, intent(in) :: elm + logical :: yes + integer :: ii + + ! Straightforward: Loop until elm found or + ! last element reached + do ii = 1, nElm + if (isq(ii) == elm) then + yes=.true. + return + end if + end do + yes=.false. + return +end function containsElement + + +function gcd (n,m) result (rgcd) + ! + ! euclid's algorithm + ! to find greatest common divisor + ! + integer, intent(in) :: n,m + integer :: rgcd + integer :: a + integer :: b + + a=n + b=m + + if (a .eq. 0) then + rgcd = 0 + else + do while (b .ne. 0) + if ( a .gt. b ) then + a = a - b + else + b = b - a; + end if + end do + rgcd =a + end if +end function gcd + + +subroutine printThem (isq) +! +! Print the pedefined number of elements of sequence isq +! +integer, intent(in) :: isq(nElementsToPrint) +integer :: ii + +! print the Introduction like EKG(2) and first elemment +write (6, '("EKG(", I2,") = [", i1,x)', advance='no') isq(2), isq(1) + +! print remaining elements except the last +do ii = 2, nElementsToPrint-1 + write (6,'(i2, x)', advance = 'no' ) isq(ii) +end do + +! Terminate output line: last element and close "]" +write (6,'(I2, "]")') isq(nElementsToPrint) + +end subroutine printThem + +end module EKG + + +program EKGMain + + use EKG + + implicit none + + integer :: myekg(100) + integer :: ekg5 (100) + integer :: ekg7 (100) + integer :: nx(5) = [2,5,7,9,10] + integer :: match + integer:: ii, jj + ! + ! Produce and print first 10 elements of first 5 sequences + ! + do ii=1,5 + call ekgSequence (nx(ii), nElementsToPrint, myekg) + call printThem (myekg) + end do + ! + ! Produce 100 elements of EKG(5) and EKG(7) + ! + call ekgSequence (5, 100, ekg5) + call ekgSequence (7, 100, ekg7) + ! + ! see where they converge + ! + match = -1 + do ii=2, 100 + if (ekg5(ii) .eq. ekg7(ii)) then + ! Memoize first identical elements and + ! see if all following elements are identical as well. + if (match .lt. 0) match = ii + do jj=ii+1,100 + if (ekg5(jj) .ne. ekg7(jj)) then + match = -1 ! Not same + endif + end do + end if + end do + write (6, "( /'EKG(5) and EKG(7) converge at index ', i0, '.')") match +end program EKGMain diff --git a/Task/EKG-sequence-convergence/JavaScript/ekg-sequence-convergence.js b/Task/EKG-sequence-convergence/JavaScript/ekg-sequence-convergence.js new file mode 100644 index 0000000000..8ffa394a5c --- /dev/null +++ b/Task/EKG-sequence-convergence/JavaScript/ekg-sequence-convergence.js @@ -0,0 +1,71 @@ +// Calculate and show here the first 10 members of EKG[2], EKG[5], EKG[7], EKG[9] and EKG[10] +for (const i of [2, 5, 7, 9, 10]) { + console.log(`EKG[${i}] = [${ekg(i, 10).join(', ')}]`); +} + +console.log("Calculate and show here at which term EKG[5] and EKG[7] converge."); +const ekg5 = ekg(5, 100); +const ekg7 = ekg(7, 100); + +for (let i = 1; i < ekg5.length; i++) { + if (ekg5[i] === ekg7[i] && sameSeq(ekg5, ekg7, i)) { + console.log(`EKG[5](${i + 1}) = EKG[7](${i + 1}) = ${ekg5[i]}, and are identical from this term on`); + break; + } +} + +// Same last element, and all elements in sequence are identical +function sameSeq(seq1, seq2, n) { + const list1 = seq1.slice(0, n).sort((a, b) => a - b); + const list2 = seq2.slice(0, n).sort((a, b) => a - b); + + for (let i = 0; i < n; i++) { + if (list1[i] !== list2[i]) { + return false; + } + } + return true; +} + +// Without Map to identify seen terms, need to examine list. +// Calculating 3000 terms in this manner takes 10 seconds +// With Map to identify the seen terms, calculating 3000 terms takes .1 sec. +function ekg(two, maxN) { + const result = []; + result.push(1); + result.push(two); + + const seen = new Map(); + seen.set(1, 1); + seen.set(two, 1); + + let minUnseen = two === 2 ? 3 : 2; + let prev = two; + + for (let n = 3; n <= maxN; n++) { + let test = minUnseen - 1; + while (true) { + test++; + if (!seen.has(test) && gcd(test, prev) > 1) { + result.push(test); + seen.set(test, n); + prev = test; + + if (minUnseen === test) { + do { + minUnseen++; + } while (seen.has(minUnseen)); + } + break; + } + } + } + return result; +} + +function gcd(a, b) { + if (b === 0) { + return a; + } + return gcd(b, a % b); +} diff --git a/Task/EKG-sequence-convergence/Julia/ekg-sequence-convergence.julia b/Task/EKG-sequence-convergence/Julia/ekg-sequence-convergence.jl similarity index 100% rename from Task/EKG-sequence-convergence/Julia/ekg-sequence-convergence.julia rename to Task/EKG-sequence-convergence/Julia/ekg-sequence-convergence.jl diff --git a/Task/EKG-sequence-convergence/Kotlin/ekg-sequence-convergence.kotlin b/Task/EKG-sequence-convergence/Kotlin/ekg-sequence-convergence.kts similarity index 100% rename from Task/EKG-sequence-convergence/Kotlin/ekg-sequence-convergence.kotlin rename to Task/EKG-sequence-convergence/Kotlin/ekg-sequence-convergence.kts diff --git a/Task/EKG-sequence-convergence/Pluto/ekg-sequence-convergence.pluto b/Task/EKG-sequence-convergence/Pluto/ekg-sequence-convergence.pluto new file mode 100644 index 0000000000..e2e276d6ff --- /dev/null +++ b/Task/EKG-sequence-convergence/Pluto/ekg-sequence-convergence.pluto @@ -0,0 +1,38 @@ +require "table2" +local int = require "int" +local fmt = require "fmt" + +local limit = 100 +local starts = {2, 5, 7, 9, 10} +local ekg = {} +for i = 1, 5 do ekg[i] = table.rep(limit, 0) end +local s = 1 +for starts as start do + ekg[s][1] = 1 + ekg[s][2] = start + for n = 3, limit do + local i = 2 + while true do + -- A potential sequence member cannot already have been used + -- and must have a factor in common with previous member. + if !ekg[s]:slice(1, n):contains(i) and int.gcd(ekg[s][n - 1], i) > 1 then + ekg[s][n] = i + break + end + i += 1 + end + end + fmt.write("EKG(%2d): ", start) + fmt.tprint("%2d", ekg[s]:slice(1, 30), 30) + s += 1 +end + +-- Now compare EKG5 and EKG7 for convergence. +for i = 3, limit do + if ekg[2][i] == ekg[3][i] and + table.same(ekg[2]:slice(1, i - 1):sort(), ekg[3]:slice(1, i - 1):sort()) then + print($"\nEKG(5) and EKG(7) converge at term {i}.") + os.exit() + end +end +print($"\nEKG5(5) and EKG(7) do not converge within {limit} terms.") diff --git a/Task/EKG-sequence-convergence/Rust/ekg-sequence-convergence.rust b/Task/EKG-sequence-convergence/Rust/ekg-sequence-convergence.rs similarity index 100% rename from Task/EKG-sequence-convergence/Rust/ekg-sequence-convergence.rust rename to Task/EKG-sequence-convergence/Rust/ekg-sequence-convergence.rs diff --git a/Task/Earliest-difference-between-prime-gaps/EasyLang/earliest-difference-between-prime-gaps.easy b/Task/Earliest-difference-between-prime-gaps/EasyLang/earliest-difference-between-prime-gaps.easy new file mode 100644 index 0000000000..c91415599e --- /dev/null +++ b/Task/Earliest-difference-between-prime-gaps/EasyLang/earliest-difference-between-prime-gaps.easy @@ -0,0 +1,41 @@ +fastfunc nextPrimeOdd n . + i = n + 2 + repeat + j = 3 + while j <= sqrt i and i mod j <> 0 + j += 2 + . + until j > sqrt i + i += 2 + . + return i +. +lastPrime = 3 +len gapStarts[] 1e7 +# +func findGapStart gap . + if gapStarts[gap] <> 0 : return gapStarts[gap] + repeat + prev = lastPrime + lastPrime = nextPrimeOdd lastPrime + diff = lastPrime - prev + if gapStarts[diff] = 0 : gapStarts[diff] = prev + until gap = diff + . + return prev +. +# +gap = 2 +pm = 10 +repeat + start1 = findGapStart gap + start2 = findGapStart (gap + 2) + diff = abs (start2 - start1) + if diff > pm + print "> " & pm & ": gaps " & gap & "/" & gap + 2 & " range " & start1 & "-" & start2 & " (" & diff & ")" + pm *= 10 + else + gap += 2 + . + until pm = 1e7 +. 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 index 0b2a1db241..a20865e78c 100644 --- 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 @@ -21,7 +21,7 @@ Function findGapStart(Byref pg As PrimeGaps, gap As Ulongint) As Ulongint prev = pg.lastPrime pg.lastPrime = NextPrime(pg.lastPrime) diff = pg.lastPrime - prev - pg.gapStarts(diff) = prev + If pg.gapStarts(diff) = 0 Then pg.gapStarts(diff) = prev If gap = diff Then Return prev Loop End Function diff --git a/Task/Earliest-difference-between-prime-gaps/Julia/earliest-difference-between-prime-gaps.julia b/Task/Earliest-difference-between-prime-gaps/Julia/earliest-difference-between-prime-gaps.jl similarity index 100% rename from Task/Earliest-difference-between-prime-gaps/Julia/earliest-difference-between-prime-gaps.julia rename to Task/Earliest-difference-between-prime-gaps/Julia/earliest-difference-between-prime-gaps.jl diff --git a/Task/Earliest-difference-between-prime-gaps/Phix/earliest-difference-between-prime-gaps.phix b/Task/Earliest-difference-between-prime-gaps/Phix/earliest-difference-between-prime-gaps.phix index 330c9e14e2..6db651adc0 100644 --- a/Task/Earliest-difference-between-prime-gaps/Phix/earliest-difference-between-prime-gaps.phix +++ b/Task/Earliest-difference-between-prime-gaps/Phix/earliest-difference-between-prime-gaps.phix @@ -1,35 +1,33 @@ -(phixonline)--> - with javascript_semantics - constant limit = iff(platform()=JS?1e7:1e8), - gslim = 250 - sequence primes = get_primes_le(limit*4), - gapstarts = repeat(0,gslim) - for i=2 to length(primes) do - integer gap = primes[i]-primes[i-1] - if gapstarts[gap]=0 then - gapstarts[gap] = primes[i-1] - end if - end for +with javascript_semantics +constant limit = iff(platform()=JS?1e7:1e8), + gslim = 250 +sequence primes = get_primes_le(limit*4), + gapstarts = repeat(0,gslim) +for i=2 to length(primes) do + integer gap = primes[i]-primes[i-1] + if gapstarts[gap]=0 then + gapstarts[gap] = primes[i-1] + end if +end for - integer pm = 10, gap1 = 2 - while true do - while gapstarts[gap1]=0 do gap1 += 2 end while - integer start1 = gapstarts[gap1], - gap2 = gap1 + 2 - if gapstarts[gap2]=0 then - gap1 = gap2 + 2 - else - integer start2 = gapstarts[gap2], - diff = abs(start2 - start1) - if diff>pm then - printf(1,"Earliest difference >%,d between adjacent prime gap starting primes:\n",{pm}) - printf(1,"Gap %d starts at %,d, gap %d starts at %,d, difference is %,d.\n\n", - {gap1, start1, gap2, start2, diff}) - if pm=limit then exit end if - pm *= 10 - else - gap1 = gap2 - end if - end if - end while - - requires(64) - enum X, Y -- rational ec point - enum A, B, N, G, R -- elliptic curve parameters - -- also signature pair(A,B) +requires(64) +enum X, Y -- rational ec point +enum A, B, N, G, R -- elliptic curve parameters + -- also signature pair(A,B) - constant mxN = 1073741789 -- maximum modulus - constant mxr = 1073807325 -- max order G = mxN + 65536 - constant inf = -2147483647 -- symbolic infinity +constant mxN = 1073741789 -- maximum modulus +constant mxr = 1073807325 -- max order G = mxN + 65536 +constant inf = -2147483647 -- symbolic infinity - sequence e = {0,0,0,{0,0},0} -- single global curve - constant zerO = {inf,0} -- point at infinity zerO +sequence e = {0,0,0,{0,0},0} -- single global curve +constant zerO = {inf,0} -- point at infinity zerO - bool inverr -- impossible inverse mod N +bool inverr -- impossible inverse mod N - function exgcd(atom v, u) - -- return mod(v^-1, u) - atom q, t, r = 0, s = 1 - if v<0 then v += u end if +function exgcd(atom v, u) +-- return mod(v^-1, u) +atom q, t, r = 0, s = 1 + if v<0 then v += u end if - while v do - q = floor(u/v) - t = u-q*v - u = v - v = t - t = r-q*s - r = s - s = t - end while + while v do + q = floor(u/v) + t = u-q*v + u = v + v = t + t = r-q*s + r = s + s = t + end while - if u!=1 then - printf(1," impossible inverse mod N, gcd = %d\n",{u}) - inverr = true - end if + if u!=1 then + printf(1," impossible inverse mod N, gcd = %d\n",{u}) + inverr = true + end if - return r - end function + return r +end function - function modn(atom a) - -- return mod(a, N) - a = mod(a,e[N]) - if a<0 then a += e[N] end if - return a - end function +function modn(atom a) +-- return mod(a, N) + a = mod(a,e[N]) + if a<0 then a += e[N] end if + return a +end function - function modr(atom a) - -- return mod(a, r) - a = mod(a,e[R]) - if a<0 then a += e[R] end if - return a - end function +function modr(atom a) +-- return mod(a, r) + a = mod(a,e[R]) + if a<0 then a += e[R] end if + return a +end function - function disc() - -- return the discriminant of E - atom a = e[A], b = e[B], - c = 4*modn(a*modn(a*a)) - return modn(-16*(c+27*modn(b*b))) - end function +function disc() +-- return the discriminant of E + atom a = e[A], b = e[B], + c = 4*modn(a*modn(a*a)) + return modn(-16*(c+27*modn(b*b))) +end function - function isO(sequence p) - -- return true if P = zerO - return (p[X]=inf and p[Y]=0) - end function +function isO(sequence p) +-- return true if P = zerO + return (p[X]=inf and p[Y]=0) +end function - function ison(sequence p) - -- return true if P is on curve E - atom r = 0, s = 0 - if not isO(p) then - r = modn(e[B]+p[X]*modn(e[A]+p[X]*p[X])) - s = modn(p[Y]*p[Y]) - end if - return (r=s) - end function +function ison(sequence p) +-- return true if P is on curve E + atom r = 0, s = 0 + if not isO(p) then + r = modn(e[B]+p[X]*modn(e[A]+p[X]*p[X])) + s = modn(p[Y]*p[Y]) + end if + return (r=s) +end function - procedure pprint(string f, sequence p) - -- print point P with prefix f - if isO(p) then - printf(1,"%s (0)\n",{f}) - else - atom y = p[Y] - if y>e[N]-y then y -= e[N] end if - printf(1,"%s (%d,%d)\n",{f,p[X],y}) - end if - end procedure +procedure pprint(string f, sequence p) +-- print point P with prefix f + if isO(p) then + printf(1,"%s (0)\n",{f}) + else + atom y = p[Y] + if y>e[N]-y then y -= e[N] end if + printf(1,"%s (%d,%d)\n",{f,p[X],y}) + end if +end procedure - function padd(sequence p, q) - -- full ec point addition - atom la, t +function padd(sequence p, q) +-- full ec point addition +atom la, t - if isO(p) then return q end if - if isO(q) then return p end if + if isO(p) then return q end if + if isO(q) then return p end if - if p[X]!=q[X] then -- R := P + Q - t = p[Y]-q[Y] - la = modn(t*exgcd(p[X]-q[X], e[N])) + if p[X]!=q[X] then -- R := P + Q + t = p[Y]-q[Y] + la = modn(t*exgcd(p[X]-q[X], e[N])) - else -- P = Q, R := 2P - if (p[Y]=q[Y]) and (p[Y]!=0) then - t = modn(3*modn(p[X]*p[X])+e[A]) - la = modn(t*exgcd(2*p[Y], e[N])) - else - return zerO -- P = -Q, R := O - end if - end if + else -- P = Q, R := 2P + if (p[Y]=q[Y]) and (p[Y]!=0) then + t = modn(3*modn(p[X]*p[X])+e[A]) + la = modn(t*exgcd(2*p[Y], e[N])) + else + return zerO -- P = -Q, R := O + end if + end if - t = modn(la*la-p[X]-q[X]) - sequence r = deep_copy(zerO) - r[Y] = modn(la*(p[X]-t)-p[Y]) - r[X] = t - if inverr then r = zerO end if - return r - end function + t = modn(la*la-p[X]-q[X]) + sequence r = deep_copy(zerO) + r[Y] = modn(la*(p[X]-t)-p[Y]) + r[X] = t + if inverr then r = zerO end if + return r +end function - function pmul(sequence p, atom k) - -- R:= multiple kP - sequence s = zerO, q = p +function pmul(sequence p, atom k) +-- R:= multiple kP + sequence s = zerO, q = p - while k do - if and_bits(k,1) then - s = padd(s, q) - end if - if inverr then s = zerO; exit end if - k = floor(k/2) - q = padd(q, q) - end while - return s - end function + while k do + if and_bits(k,1) then + s = padd(s, q) + end if + if inverr then s = zerO; exit end if + k = floor(k/2) + q = padd(q, q) + end while + return s +end function - function ellinit(sequence i) - -- initialize elliptic curve - atom a = i[1], b = i[2] - inverr = false - e[N] = i[3] +function ellinit(sequence i) +-- initialize elliptic curve +atom a = i[1], b = i[2] + inverr = false + e[N] = i[3] - if (e[N]<5) or (e[N]>mxN) then return 0 end if + if (e[N]<5) or (e[N]>mxN) then return 0 end if - e[A] = modn(a) - e[B] = modn(b) - e[G][X] = modn(i[4]) - e[G][Y] = modn(i[5]) - e[R] = i[6] + e[A] = modn(a) + e[B] = modn(b) + e[G][X] = modn(i[4]) + e[G][Y] = modn(i[5]) + e[R] = i[6] - if (e[R]<5) or (e[R]>mxr) then return 0 end if + if (e[R]<5) or (e[R]>mxr) then return 0 end if - printf(1,"E: y^2 = x^3 + %dx + %d (mod %d)\n",{a,b,e[N]}) - pprint("base point G", e[G]) - printf(1,"order(G, E) = %d\n",{e[R]}) + printf(1,"E: y^2 = x^3 + %dx + %d (mod %d)\n",{a,b,e[N]}) + pprint("base point G", e[G]) + printf(1,"order(G, E) = %d\n",{e[R]}) - return -1 - end function + return -1 +end function - function signature(atom s, f) - -- signature primitive - atom c, d, u, u1 - sequence V +function signature(atom s, f) +-- signature primitive +atom c, d, u, u1 +sequence V - printf(1,"signature computation\n") - while true do - while true do - -- u = rand(e[R]-1) - u = 571533488 -- match FreeBASIC output - -- u = 605163545 -- match C output - V = pmul(e[G], u) - c = modr(V[X]) - if c!=0 then exit end if - end while + printf(1,"signature computation\n") + while true do + while true do +-- u = rand(e[R]-1) + u = 571533488 -- match FreeBASIC output +-- u = 605163545 -- match C output + V = pmul(e[G], u) + c = modr(V[X]) + if c!=0 then exit end if + end while - u1 = exgcd(u, e[R]) - d = modr(u1*(f+modr(s*c))) - if d!=0 then exit end if - end while - printf(1,"one-time u = %d\n",u) - pprint("V = uG", V) - return {c,d} - end function + u1 = exgcd(u, e[R]) + d = modr(u1*(f+modr(s*c))) + if d!=0 then exit end if + end while + printf(1,"one-time u = %d\n",u) + pprint("V = uG", V) + return {c,d} +end function - function verify(sequence W, atom f, sequence sg) - -- verification primitive - atom c = sg[A], d = sg[B], - t, c1, h1, h2, h - sequence V, V2 +function verify(sequence W, atom f, sequence sg) +-- verification primitive +atom c = sg[A], d = sg[B], + t, c1, h1, h2, h +sequence V, V2 - --domain check - t = (c>0) and (c<e[R]) - t = t and (d>0) and (d<e[R]) - if not t then return 0 end if + --domain check + t = (c>0) and (c0) and (dprintf(1,"\nsignature verification\n") - h = exgcd(d, e[R]) - h1 = modr(f*h) - h2 = modr(c*h) - printf(1,"h1,h2 = %d,%d\n",{h1,h2}) - V = pmul(e[G], h1) - V2 = pmul(W, h2) - pprint("h1G", V) - pprint("h2W", V2) - V = padd(V, V2) - pprint("+ =", V) - if isO(V) then return 0 end if - c1 = modr(V[X]) - printf(1,"c' = %d\n",c1) + printf(1,"\nsignature verification\n") + h = exgcd(d, e[R]) + h1 = modr(f*h) + h2 = modr(c*h) + printf(1,"h1,h2 = %d,%d\n",{h1,h2}) + V = pmul(e[G], h1) + V2 = pmul(W, h2) + pprint("h1G", V) + pprint("h2W", V2) + V = padd(V, V2) + pprint("+ =", V) + if isO(V) then return 0 end if + c1 = modr(V[X]) + printf(1,"c' = %d\n",c1) - return (c1=c) - end function + return (c1=c) +end function - procedure errmsg() - printf(1,"invalid parameter set\n") - printf(1,"_____________________\n") - end procedure +procedure errmsg() + printf(1,"invalid parameter set\n") + printf(1,"_____________________\n") +end procedure - procedure ec_dsa(atom f, d) - -- digital signature on message hash f, error bit d - atom i, s, t - sequence sg, W +procedure ec_dsa(atom f, d) +-- digital signature on message hash f, error bit d +atom i, s, t +sequence sg, W - --parameter check - t = (disc()=0) - t = t or isO(e[G]) - W = pmul(e[G], e[R]) - t = t or not isO(W) - t = t or not ison(e[G]) - if t then errmsg() return end if + --parameter check + t = (disc()=0) + t = t or isO(e[G]) + W = pmul(e[G], e[R]) + t = t or not isO(W) + t = t or not ison(e[G]) + if t then errmsg() return end if - puts(1,"\nkey generation\n") - -- s = rand(e[R] - 1) - s = 509100772 -- match FreeBASIC output - -- s = 1343570 -- match C output - W = pmul(e[G], s) - printf(1,"private key s = %d\n",{s}) - pprint("public key W = sG", W) + puts(1,"\nkey generation\n") +-- s = rand(e[R] - 1) + s = 509100772 -- match FreeBASIC output +-- s = 1343570 -- match C output + W = pmul(e[G], s) + printf(1,"private key s = %d\n",{s}) + pprint("public key W = sG", W) - --next highest power of 2 - 1 - t = e[R] - i = 1 - while i<32 do - t = or_bits(t,floor(t/power(2,i))) - i *= 2 - end while - while f>t do - f = floor(f/2) - end while - printf(1,"\naligned hash %x\n\n",{f}) + --next highest power of 2 - 1 + t = e[R] + i = 1 + while i<32 do + t = or_bits(t,floor(t/power(2,i))) + i *= 2 + end while + while f>t do + f = floor(f/2) + end while + printf(1,"\naligned hash %x\n\n",{f}) - sg = signature(s, f) - if inverr then errmsg() return end if - printf(1,"signature c,d = %d,%d\n",sg) + sg = signature(s, f) + if inverr then errmsg() return end if + printf(1,"signature c,d = %d,%d\n",sg) - if d>0 then - while d>t do - d = floor(d/2) - end while - f = xor_bits(f,d) - printf(1,"corrupted hash %x\n",{f}) - end if + if d>0 then + while d>t do + d = floor(d/2) + end while + f = xor_bits(f,d) + printf(1,"corrupted hash %x\n",{f}) + end if - t = verify(W, f, sg) - if inverr then errmsg() return end if - if t then - printf(1,"Valid\n_____\n") - else - printf(1,"invalid\n_______\n") - end if - end procedure + t = verify(W, f, sg) + if inverr then errmsg() return end if + if t then + printf(1,"Valid\n_____\n") + else + printf(1,"invalid\n_______\n") + end if +end procedure - --Test vectors: elliptic curve domain parameters, - --short Weierstrass model y^2 = x^3 + ax + b (mod N) +--Test vectors: elliptic curve domain parameters, +--short Weierstrass model y^2 = x^3 + ax + b (mod N) - constant tests = { - -- a, b, modulus N, base point G, order(G, E), cofactor - {355, 671, 1073741789, 13693, 10088, 1073807281}, - { 0, 7, 67096021, 6580, 779, 16769911}, -- 4 - { -3, 1, 877073, 0, 1, 878159}, - { 0, 14, 22651, 63, 30, 151}, -- 151 - { 3, 2, 5, 2, 1, 5}, +constant tests = { +-- a, b, modulus N, base point G, order(G, E), cofactor + {355, 671, 1073741789, 13693, 10088, 1073807281}, + { 0, 7, 67096021, 6580, 779, 16769911}, -- 4 + { -3, 1, 877073, 0, 1, 878159}, + { 0, 14, 22651, 63, 30, 151}, -- 151 + { 3, 2, 5, 2, 1, 5}, - --ecdsa may fail if... - --the base point is of composite order - { 0, 7, 67096021, 2402, 6067, 33539822}, -- 2 - --the given order is a multiple of the true order - { 0, 7, 67096021, 6580, 779, 67079644}, -- 1 - --the modulus is not prime (deceptive example) - { 0, 7, 877069, 3, 97123, 877069}, - --fails if the modulus divides the discriminant - { 39, 387, 22651, 95, 27, 22651}} + --ecdsa may fail if... + --the base point is of composite order + { 0, 7, 67096021, 2402, 6067, 33539822}, -- 2 + --the given order is a multiple of the true order + { 0, 7, 67096021, 6580, 779, 67079644}, -- 1 + --the modulus is not prime (deceptive example) + { 0, 7, 877069, 3, 97123, 877069}, + --fails if the modulus divides the discriminant + { 39, 387, 22651, 95, 27, 22651}} - --Digital signature on message hash f, - --set d > 0 to simulate corrupted data - atom f = #789ABCDE, - d = 0 +--Digital signature on message hash f, +--set d > 0 to simulate corrupted data +atom f = #789ABCDE, + d = 0 - --for i=1 to length(tests) do - for i=1 to 1 do - if not ellinit(tests[i]) then exit end if - ec_dsa(f, d) - end for - - with javascript_semantics - constant X=1, Y=2, bCoeff=7, INF = 1e300*1e300 +with javascript_semantics +constant X=1, Y=2, bCoeff=7, INF = 1e300*1e300 - type point(object pt) - return sequence(pt) and length(pt)=2 and atom(pt[X]) and atom(pt[Y]) - end type +type point(object pt) + return sequence(pt) and length(pt)=2 and atom(pt[X]) and atom(pt[Y]) +end type - function zero() - point pt = {INF, INF} - return pt - end function +function zero() + point pt = {INF, INF} + return pt +end function - function is_zero(point p) - return p[X]>1e20 or p[X]<-1e20 - end function +function is_zero(point p) + return p[X]>1e20 or p[X]<-1e20 +end function - function neg(point p) - p = {p[X], -p[Y]} - return p - end function +function neg(point p) + p = {p[X], -p[Y]} + return p +end function - function dbl(point p) - point r = p - if not is_zero(p) then - atom L = (3*p[X]*p[X])/(2*p[Y]) - atom x = L*L-2*p[X] - r = {x, L*(p[X]-x)-p[Y]} - end if - return r - end function +function dbl(point p) + point r = p + if not is_zero(p) then + atom L = (3*p[X]*p[X])/(2*p[Y]) + atom x = L*L-2*p[X] + r = {x, L*(p[X]-x)-p[Y]} + end if + return r +end function - function add(point p, point q) - if p==q then return dbl(p) end if - if is_zero(p) then return q end if - if is_zero(q) then return p end if - atom L = (q[Y]-p[Y])/(q[X]-p[X]) - atom x = L*L-p[X]-q[X] - point r = {x, L*(p[X]-x)-p[Y]} - return r - end function +function add(point p, point q) + if p==q then return dbl(p) end if + if is_zero(p) then return q end if + if is_zero(q) then return p end if + atom L = (q[Y]-p[Y])/(q[X]-p[X]) + atom x = L*L-p[X]-q[X] + point r = {x, L*(p[X]-x)-p[Y]} + return r +end function - function mul(point p, integer n) - point r = zero() - integer i = 1 - while i<=n do - if and_bits(i, n) then r = add(r, p) end if - p = dbl(p) - i = i*2 - end while - return r - end function +function mul(point p, integer n) + point r = zero() + integer i = 1 + while i<=n do + if and_bits(i, n) then r = add(r, p) end if + p = dbl(p) + i = i*2 + end while + return r +end function - procedure show(string s, point p) - puts(1, s&iff(is_zero(p)?"Zero\n":sprintf("(%.3f, %.3f)\n", p))) - end procedure +procedure show(string s, point p) + puts(1, s&iff(is_zero(p)?"Zero\n":sprintf("(%.3f, %.3f)\n", p))) +end procedure - function cbrt(atom c) - return iff(c>=0?power(c,1/3):-power(-c,1/3)) - end function +function cbrt(atom c) + return iff(c>=0?power(c,1/3):-power(-c,1/3)) +end function - function from_y(atom y) - point r = {cbrt(y*y-bCoeff), y} - return r - end function +function from_y(atom y) + point r = {cbrt(y*y-bCoeff), y} + return r +end function - point a, b, c, d +point a, b, c, d - a = from_y(1) - b = from_y(2) - c = add(a, b) - d = neg(c) +a = from_y(1) +b = from_y(2) +c = add(a, b) +d = neg(c) - show("a = ", a) - show("b = ", b) - show("c = a + b = ", c) - show("d = -c = ", d) - show("c + d = ", add(c, d)) - show("a + b + d = ", add(a, add(b, d))) - show("a * 12345 = ", mul(a, 12345)) - - with javascript_semantics - sequence emirps = {} +with javascript_semantics +sequence emirps = {} - function rev(integer n) - integer res = 0 - while n do - res = res*10+remainder(n,10) - n = floor(n/10) - end while - return res - end function +function rev(integer n) + integer res = 0 + while n do + res = res*10+remainder(n,10) + n = floor(n/10) + end while + return res +end function - function emirp(integer n) - if is_prime(n) then - integer r = rev(n) - if r!=n and is_prime(r) then - return true - end if - end if - return false - end function +function emirp(integer n) + if is_prime(n) then + integer r = rev(n) + if r!=n and is_prime(r) then + return true + end if + end if + return false +end function - procedure usage() - printf(1,"use a single command line argument, with no spaces, eg \"1-20\" (first 20), \n") - printf(1,"\"7700..8000\" (between 7700 and 8000), or \"10000\" (the 10,000th).\n") - {} = wait_key() - abort(0) - end procedure +procedure usage() + printf(1,"use a single command line argument, with no spaces, eg \"1-20\" (first 20), \n") + printf(1,"\"7700..8000\" (between 7700 and 8000), or \"10000\" (the 10,000th).\n") + {} = wait_key() + abort(0) +end procedure - procedure main(string arg3) - sequence args - integer n,m - if find('-',arg3) then -- nth to mth emirp range - args = scanf(arg3,"%d-%d") - if length(args)!=1 then usage() end if - {{n,m}} = args - integer k = 1 - while length(emirps)<m do - if emirp(k) then emirps &= k end if - k += 1 - end while - printf(1,"emirps %d to %d: %v\n",{n,m,emirps[n..m]}) - elsif match("..",arg3) then -- emirps between n amd m - args = scanf(arg3,"%d..%d") - if length(args)!=1 then usage() end if - {{n,m}} = args - integer k = 1 - while length(emirps)=0 or emirps[$]<m do - if emirp(k) then emirps &= k end if - k += 1 - end while - sequence s = {} - for i=1 to length(emirps) do - if emirps[i]>n then - for j=i to length(emirps) do - if emirps[j]>m then - printf(1,"emirps between %d and %d: %v\n",{n,m,emirps[i..j-1]}) - exit - end if - end for - exit - end if - end for - else -- nth emirp - args = scanf(arg3,"%d") - if length(args)!=1 then usage() end if - {{n}} = args - integer k = 1 - while length(emirps)<n do - if emirp(k) then emirps &= k end if - k += 1 - end while - printf(1,"emirp %d: %d\n",{n,emirps[n]}) - end if - end procedure +procedure main(string arg3) + sequence args + integer n,m + emirps = {} + if find('-',arg3) then -- nth to mth emirp range + args = scanf(arg3,"%d-%d") + if length(args)!=1 then usage() end if + {{n,m}} = args + integer k = 1 + while length(emirps)n then + for j=i to length(emirps) do + if emirps[j]>m then + printf(1,"emirps between %d and %d: %v\n",{n,m,emirps[i..j-1]}) + exit + end if + end for + exit + end if + end for + else -- nth emirp + args = scanf(arg3,"%d") + if length(args)!=1 then usage() end if + {{n}} = args + integer k = 1 + while length(emirps)sequence cl = command_line() - if length(cl)=2 then - main("1-20") - main("7700..8000") - main("10000") - elsif length(cl)=3 then - main(cl[3]) - else - usage() - end if - - without js -- command_line, file i/o - function entropy(sequence s) - sequence symbols = {}, - counts = {} - integer N = length(s) - for i=1 to N do - object si = s[i] - integer k = find(si,symbols) - if k=0 then - symbols = append(symbols,si) - counts = append(counts,1) - else - counts[k] += 1 - end if - end for - atom H = 0 - for i=1 to length(counts) do - atom ci = counts[i]/N - H -= ci*log2(ci) - end for - return H - end function +without js -- command_line, file i/o +function entropy(sequence s) + sequence symbols = {}, + counts = {} + integer N = length(s) + for i=1 to N do + object si = s[i] + integer k = find(si,symbols) + if k=0 then + symbols = append(symbols,si) + counts = append(counts,1) + else + counts[k] += 1 + end if + end for + atom H = 0 + for i=1 to length(counts) do + atom ci = counts[i]/N + H -= ci*log2(ci) + end for + return H +end function - ?entropy(get_text(open(substitute(command_line()[2],".exe",".exw")),"rb")) - - enum apple, banana, orange - enum apple=5, banana=10, orange= - - without js -- none such in a browser, that I know of - ?getenv("PATH") - - with javascript_semantics - atom t0 = time() - atom ps = 2, -- current prime sum - cs = 4 -- current composite sum - integer psn = 1, npi = 1, -- (see below) - csn = 1, nci = 3, nc = 4, ncp = 5, - found = 0 - constant limit = iff(platform()=JS?10:11) - while found<limit do - integer c = compare(ps,cs) -- {-1,0,+1} - if c=0 then - printf(1,"%,21d - %,10d%s prime sum, %,10d%s composite sum (%s)\n", - {ps, psn, ord(psn), csn, ord(csn), elapsed(time()-t0)}) - found += 1 - end if - if c<=0 then - psn += 1 -- prime sum number - npi += 1 -- next prime index - ps += get_prime(npi) - end if - if c>=0 then - csn += 1 -- composite sum number - nc += 1 -- next composite? - if nc=ncp then -- "", erm no - nci += 1 -- next prime index - ncp = get_prime(nci) - nc += 1 -- next composite (even!) - end if - cs += nc - end if - end while - - with javascript_semantics - function equilibrium(sequence s) - atom lower_sum = 0, - higher_sum = sum(s) - sequence res = {} - for i=1 to length(s) do - higher_sum -= s[i] - if lower_sum=higher_sum then - res &= i - end if - lower_sum += s[i] - end for - return res - end function +with javascript_semantics +function equilibrium(sequence s) + atom lower_sum = 0, + higher_sum = sum(s) + sequence res = {} + for i,si in s do + higher_sum -= si + if lower_sum=higher_sum then + res &= i + end if + lower_sum += si + end for + return res +end function - ?equilibrium({-7,1,5,2,-4,3,0}) - - with javascript_semantics - sequence escache = {} +with javascript_semantics +sequence escache = {} - function es_cat(integer p) - if p>length(escache) and platform()!=JS then - escache &= repeat(0,p-length(escache)) - end if - integer category = escache[p] - if not category then - sequence f = filter(prime_factors(p+1,false,-1),">",3) - category = 1 - if length(f) then - category += max(apply(f,es_cat)) - end if - escache[p] = category - end if - return category - end function +function es_cat(integer p) + if p>length(escache) and platform()!=JS then + escache &= repeat(0,p-length(escache)) + end if + integer category = escache[p] + if not category then + sequence f = filter(prime_factors(p+1,false,-1),">",3) + category = 1 + if length(f) then + category += max(apply(f,es_cat)) + end if + escache[p] = category + end if + return category +end function - procedure categorise(integer n) - sequence p = get_primes(n) - printf(1,"First %,d primes:\n",n) - atom t1 = time() - sequence es = {} - for i=1 to n do - if time()>t1 then - progress("categorising %d/%d...",{i,n}) - t1 = time()+1 - end if - integer category = es_cat(p[i]) - while length(es)<category do - es = append(es,{}) - end while - es[category] &= p[i] - end for - progress("") - for c=1 to length(es) do - sequence e = es[c] - if n=200 then - printf(1,"Category %d: %s\n",{c,join(shorten(e,"primes",5,"%d"),",")}) - else - printf(1,"Category %2d: %7d .. %-8d Count: %d\n",{c,e[1],e[$],length(e)}) - end if - end for - printf(1,"\n") - end procedure +procedure categorise(integer n) + sequence p = get_primes(n) + printf(1,"First %,d primes:\n",n) + atom t1 = time() + sequence es = {} + for i=1 to n do + if time()>t1 then + progress("categorising %d/%d...",{i,n}) + t1 = time()+1 + end if + integer category = es_cat(p[i]) + while length(es)atom t0 = time() - categorise(200) - categorise(1e6) - ?elapsed(time()-t0) - - constant aleph = "0123456789ABCDEF" +with javascript_semantics +constant aleph = "0123456789ABCDEF" - function efill(string s, integer ch, i) - -- min-fill, like 10101 or 54321 or 32101 - s[i] = ch - for j=i+1 to length(s) do - ch = iff(ch>='1'?iff(ch='A'?'9':ch-1):'1') - s[j] = ch - end for - return s - end function +function efill(string s, integer ch, i) + -- min-fill, like 10101 or 54321 or 32101 + s[i] = ch + for j=i+1 to length(s) do + ch = iff(ch>='1'?iff(ch='A'?'9':ch-1):'1') + s[j] = ch + end for + return s +end function - function esthetic(string s, integer base = 10) - -- generate the next esthetic number after s - -- (nb unpredictable results if s is not esthetic, or "") - for i=length(s) to 1 by -1 do - integer ch = s[i], cp = iff(i>1?s[i-1]:'0') - if ch<cp and cp<aleph[base] then - return efill(s,aleph[find(ch,aleph)+2],i) - elsif i=1 and ch<aleph[base] then - return efill(s,iff(ch='9'?'A':ch+1),i) - end if - end for - return efill("1"&s,'1',1) - end function +function esthetic(string s, integer base = 10) + -- generate the next esthetic number after s + -- the special case of s="" always yields "1" + -- (nb otherwise s is assumed to be esthetic) + for i=length(s) to 1 by -1 do + integer ch = s[i], cp = iff(i>1?s[i-1]:'0') + if chstring s - sequence res - for base=2 to 16 do - integer hi = base*6, - lo = base*4 - {s,res} = {"",{}} - for i=1 to hi do - s = esthetic(s, base) - if i>=lo then - res = append(res,s) - end if - end for - res = join(shorten(res,"numbers",4)) - printf(1,"Base %d esthetic numbers[%d..%d]: %s\n",{base,lo,hi,res}) - end for +string s +sequence res +for base=2 to 16 do + integer hi = base*6, + lo = base*4 + {s,res} = {"",{}} + for i=1 to hi do + s = esthetic(s, base) + if i>=lo then + res = append(res,s) + end if + end for + res = join(shorten(res,"numbers",4)) + printf(1,"Base %d esthetic numbers[%d..%d]: %s\n",{base,lo,hi,res}) +end for - {s,res} = {efill("1000",'1',1),{}} - while length(s)=4 do - res = append(res,s) - s = esthetic(s) - end while - res = {join(shorten(res,"numbers",5))} - printf(1,"\nBase 10 esthetic numbers between 1,000 and 9,999: %s\n\n",res) +{s,res} = {efill("1000",'1',1),{}} +while length(s)=4 do + res = append(res,s) + s = esthetic(s) +end while +res = {join(shorten(res,"numbers",5))} +printf(1,"\nBase 10 esthetic numbers between 1,000 and 9,999: %s\n\n",res) - function comma(string s) - for i=length(s)-2 to 2 by -3 do - s[i..i-1] = "," - end for - return s - end function +function comma(string s) + for i=length(s)-2 to 2 by -3 do + s[i..i-1] = "," + end for + return s +end function - for k=7 to 19 by 3 do - string f = "10"&repeat('0',k), - t = "13"&repeat('0',k) - {s,res} = {efill(f,'1',1),{}} - while s<t do - res = append(res,s) - s = esthetic(s) - end while - res = join(shorten(res,"numbers",1)) - printf(1,"Base 10 esthetic numbers between %s and %s: %s\n", - {comma(f),comma(t),res}) - end for - - function count_esthetic(integer len, start=0) - -- a start digit of 0 means sum all 1..9 - sequence dc = repeat(repeat(1,10),len) -- nb 0..9 logically - for i=2 to len do - for d=0 to 9 do - dc[i][d+1] = iff(d=0?0:dc[i-1][d]) + iff(d=9?0:dc[i-1][d+2]) - end for - end for - if start=0 then return sum(dc[len][1..9]) end if -- (see note) - return dc[len][start+1] - end function +function count_esthetic(integer len, start=0) + -- a start digit of 0 means sum all 1..9 + sequence dc = repeat(repeat(1,10),len) -- nb 0..9 logically + for i=2 to len do + for d=0 to 9 do + dc[i][d+1] = iff(d=0?0:dc[i-1][d]) + iff(d=9?0:dc[i-1][d+2]) + end for + end for + if start=0 then return sum(dc[len][1..9]) end if -- (see note) + return dc[len][start+1] +end function - sequence t = tagset(iff(machine_bits()=64?63:57),9,3), - r = columnize({apply(true,count_esthetic,{t,1}),t}) - papply(true,printf,{1,{"There are %,26d %2d-digit esthetic numbers beginning with 1\n"},r}) - if machine_bits()=64 then - printf(1,"There are %,26d 64-digit esthetic numbers\n",{count_esthetic(64)}) - printf(1,"There are %,26d esthetic numbers with max 65 digits\n",{sum(apply(tagset(64),count_esthetic))}) - end if - stdout // $0 is a temp register - LDA str,BUF+19 % points after the end of the string -2H SUB str,str,1 % update buffer pointer - DIV acc,acc,10 % do a divide and mod - GET $0,rR % get digit from special purpose reg. rR - % containing the remainder of the division - INCL $0,'0' % convert to ascii - STBU $0,str % place digit in buffer - PBNZ acc,2B % next - % 'str' points to the start of the result - TRAP 0,Fputs,StdOut % output answer to stdout - TRAP 0,Halt,0 % exit + LDA str,BUF+19 % points after the end of the string +2H SUB str,str,1 % update buffer pointer + DIV acc,acc,10 % do a divide and mod + GET $0,rR % get digit from special purpose reg. rR + % containing the remainder of the division + INCL $0,'0' % convert to ascii + STBU $0,str % place digit in buffer + PBNZ acc,2B % next + % 'str' points to the start of the result + TRAP 0,Fputs,StdOut % output answer to stdout + TRAP 0,Halt,0 % exit diff --git a/Task/Ethiopian-multiplication/MoonRock/ethiopian-multiplication.moonrock b/Task/Ethiopian-multiplication/MoonRock/ethiopian-multiplication.moonrock new file mode 100644 index 0000000000..4a1893471c --- /dev/null +++ b/Task/Ethiopian-multiplication/MoonRock/ethiopian-multiplication.moonrock @@ -0,0 +1,54 @@ +' Ethiopian multiplication +BEGIN DEF +pointer word PtrA~ +pointer word PtrIsEven~ +SUB Double(PtrA~) +SUB Halve(PtrA~) +SUB CheckIfEven(PtrA~, PtrIsEven~) +SUB PrintStr(S$, Width%) + +BEGIN CODE +X% = 17 +Y% = 34 +Tot% = 0 +WHILE X% >= 1 + CALL PrintStr(STR(X%), 6) + PRINT " " + CALL CheckIfEven(X%, VARPTR(IsEven%)) + IF IsEven% = FALSE THEN + Tot% = Tot% + Y% + CALL PrintStr(STR(Y%), 6) + ENDIF + PRINT "\n" + CALL Halve(VARPTR(X%)) + CALL Double(VARPTR(Y%)) +WEND +PRINT "= " +CALL PrintStr(STR(Tot%), 6) +PRINT "\n" +END + +' Subroutines are required, though +' they complicate the code + +SUB Double(PtrA~) +[PtrA~] = 2 * [PtrA~] +END SUB + +SUB Halve(PtrA~) +[PtrA~] = [PtrA~] \ 2 +END SUB + +SUB CheckIfEven(A%, PtrIsEven~) +[PtrIsEven~] = A% MOD 2 +[PtrIsEven~] = [PtrIsEven~] - 1 +END SUB + +SUB PrintStr(S$, Width%) +IF LEN(S$) > Width% THEN + PRINT S$ +ELSE + S$ = SPACE(Width%) + S$ + PRINT RIGHT(S$, Width%) +ENDIF +END SUB diff --git a/Task/Ethiopian-multiplication/OCaml/ethiopian-multiplication.ocaml b/Task/Ethiopian-multiplication/OCaml/ethiopian-multiplication.ml similarity index 100% rename from Task/Ethiopian-multiplication/OCaml/ethiopian-multiplication.ocaml rename to Task/Ethiopian-multiplication/OCaml/ethiopian-multiplication.ml diff --git a/Task/Ethiopian-multiplication/Oberon-07/ethiopian-multiplication.oberon b/Task/Ethiopian-multiplication/Oberon-07/ethiopian-multiplication.oberon new file mode 100644 index 0000000000..c6fe2e64c9 --- /dev/null +++ b/Task/Ethiopian-multiplication/Oberon-07/ethiopian-multiplication.oberon @@ -0,0 +1,42 @@ +MODULE EthopianMultiplication; (* translation of Loglan82 *) + IMPORT Out; + + VAR x, y, outp : INTEGER; + multiplying : BOOLEAN; + + PROCEDURE half( a : INTEGER ) : INTEGER; + BEGIN + RETURN a DIV 2 + END half; + + PROCEDURE doub( a : INTEGER ) : INTEGER; + BEGIN + RETURN a * 2 + END doub; + + PROCEDURE isEven( a : INTEGER ) : BOOLEAN; + BEGIN + RETURN ~ ODD( a ) + END isEven; + +BEGIN + x := 17; + y := 34; + outp := 0; + multiplying := TRUE; + WHILE multiplying DO + Out.Int( x, 6 );Out.String( " " ); + IF ~ isEven(x) THEN + outp := outp + y; + Out.Int( y, 6 ) + END; + Out.Ln; + IF x < 2 THEN + multiplying := FALSE + ELSE + x := half(x); + y := doub(y) + END + END; + Out.String( " = " );Out.Int( outp, 6 );Out.Ln +END EthopianMultiplication. diff --git a/Task/Ethiopian-multiplication/Octave/ethiopian-multiplication.octave b/Task/Ethiopian-multiplication/Octave/ethiopian-multiplication.octave index 18d3a0af83..c6a81160b1 100644 --- a/Task/Ethiopian-multiplication/Octave/ethiopian-multiplication.octave +++ b/Task/Ethiopian-multiplication/Octave/ethiopian-multiplication.octave @@ -18,12 +18,12 @@ function r = ethiopicmult(plier, plicand, tutor=false) while(plier >= 1) if ( iseven(plier) ) if (tutor) - printf("%4d %6d struck\n", plier, plicand); + printf("%4d %6d struck\n", plier, plicand); endif else r = r + plicand; if (tutor) - printf("%4d %6d kept\n", plier, plicand); + printf("%4d %6d kept\n", plier, plicand); endif endif plier = halve(plier); diff --git a/Task/Ethiopian-multiplication/Oz/ethiopian-multiplication.oz b/Task/Ethiopian-multiplication/Oz/ethiopian-multiplication.oz index 4eaecb27c7..2c5a6825bd 100644 --- a/Task/Ethiopian-multiplication/Oz/ethiopian-multiplication.oz +++ b/Task/Ethiopian-multiplication/Oz/ethiopian-multiplication.oz @@ -10,9 +10,9 @@ declare L in X; L>0; {Halve L} %% C-like iterator: "Init; While; Next" R in Y; true; {Double R} collect:Collect - do - {Collect L#R} - end + do + {Collect L#R} + end OddRows = {Filter Rows LeftIsOdd} RightColumn = {Map OddRows SelectRight} diff --git a/Task/Ethiopian-multiplication/Pascal-P/ethiopian-multiplication.pas b/Task/Ethiopian-multiplication/Pascal-P/ethiopian-multiplication.pas new file mode 100644 index 0000000000..1046cc6565 --- /dev/null +++ b/Task/Ethiopian-multiplication/Pascal-P/ethiopian-multiplication.pas @@ -0,0 +1,47 @@ +program ethiopian(output); + (* Ethiopian multiplication *) +var + x, y, outp: integer; + + function doub(a: integer): integer; + begin + doub := a * 2; + end; + + function half(a: integer): integer; + begin + half := a div 2; + end; + + function iseven(a: integer): boolean; + begin + iseven := a mod 2 = 0; + end; + +begin + x := 17; + y := 34; + write(x: 6); + if not (iseven(x)) then + begin + outp := outp + y; + writeln(' ', y: 6); + end + else + writeln; + while x >= 2 do + begin + x := half(x); + y := doub(y); + write(x: 6); + if not (iseven(x)) then + begin + outp := outp + y; + writeln(' ', y: 6); + end + else + writeln; + end; + writeln(' = ', outp: 6); + (* readln; *) +end. diff --git a/Task/Ethiopian-multiplication/Pascal/ethiopian-multiplication.pas b/Task/Ethiopian-multiplication/Pascal/ethiopian-multiplication.pas deleted file mode 100644 index 826258d7fd..0000000000 --- a/Task/Ethiopian-multiplication/Pascal/ethiopian-multiplication.pas +++ /dev/null @@ -1,34 +0,0 @@ -program EthiopianMultiplication; - {$IFDEF FPC} - {$MODE DELPHI} - {$ENDIF} - function Double(Number: Integer): Integer; - begin - Result := Number * 2 - end; - - function Halve(Number: Integer): Integer; - begin - Result := Number div 2 - end; - - function Even(Number: Integer): Boolean; - begin - Result := Number mod 2 = 0 - end; - - function Ethiopian(NumberA, NumberB: Integer): Integer; - begin - Result := 0; - while NumberA >= 1 do - begin - if not Even(NumberA) then - Result := Result + NumberB; - NumberA := Halve(NumberA); - NumberB := Double(NumberB) - end - end; - -begin - Write(Ethiopian(17, 34)) -end. diff --git a/Task/Ethiopian-multiplication/PascalABC.NET/ethiopian-multiplication.pas b/Task/Ethiopian-multiplication/PascalABC.NET/ethiopian-multiplication.pas new file mode 100644 index 0000000000..64d7022701 --- /dev/null +++ b/Task/Ethiopian-multiplication/PascalABC.NET/ethiopian-multiplication.pas @@ -0,0 +1,17 @@ +function halve(x: integer): integer := x div 2; +function double(x: integer): integer := x * 2; +function odd(x: integer): boolean := x mod 2 <> 0; + +function ethiopian(x, y: integer): integer; +begin + while x >= 1 do + begin + if odd(x) then result += y; + x := halve(x); + y := double(y); + end; +end; + +begin + ethiopian(17, 34).println; +end. diff --git a/Task/Ethiopian-multiplication/Perl/ethiopian-multiplication.pl b/Task/Ethiopian-multiplication/Perl/ethiopian-multiplication.pl index 9ffe136ab9..85d7454124 100644 --- a/Task/Ethiopian-multiplication/Perl/ethiopian-multiplication.pl +++ b/Task/Ethiopian-multiplication/Perl/ethiopian-multiplication.pl @@ -11,12 +11,12 @@ sub ethiopicmult my $r = 0; while ($plier >= 1) { - $r += $plicand unless iseven($plier); - if ($tutor) { - print "$plier, $plicand ", (iseven($plier) ? " struck" : " kept"), "\n"; - } - $plier = halve($plier); - $plicand = double($plicand); + $r += $plicand unless iseven($plier); + if ($tutor) { + print "$plier, $plicand ", (iseven($plier) ? " struck" : " kept"), "\n"; + } + $plier = halve($plier); + $plicand = double($plicand); } return $r; } diff --git a/Task/Ethiopian-multiplication/Pluto/ethiopian-multiplication.pluto b/Task/Ethiopian-multiplication/Pluto/ethiopian-multiplication.pluto new file mode 100644 index 0000000000..a0528544e6 --- /dev/null +++ b/Task/Ethiopian-multiplication/Pluto/ethiopian-multiplication.pluto @@ -0,0 +1,18 @@ +local function halve(n) return n // 2 end + +local function double(n) return n * 2 end + +local function is_even(n) return n % 2 == 0 end + +local function ethiopian(x, y) + local sum = 0 + while x >= 1 do + if !is_even(x) then sum += y end + x = halve(x) + y = double(y) + end + return sum +end + +print($"17 x 34 = {ethiopian(17, 34)}") +print($"99 x 99 = {ethiopian(99, 99)}") diff --git a/Task/Ethiopian-multiplication/PowerShell/ethiopian-multiplication-1.ps1 b/Task/Ethiopian-multiplication/PowerShell/ethiopian-multiplication-1.ps1 new file mode 100644 index 0000000000..7aea5a622d --- /dev/null +++ b/Task/Ethiopian-multiplication/PowerShell/ethiopian-multiplication-1.ps1 @@ -0,0 +1,35 @@ +function isEven { + param ([int]$value) + return [bool]($value % 2 -eq 0) +} + +function doubleValue { + param ([int]$value) + return [int]($value * 2) +} + +function halveValue { + param ([int]$value) + return [int]($value / 2) +} + +function multiplyValues { + param ( + [int]$plier, + [int]$plicand, + [int]$temp = 0 + ) + + while ($plier -ge 1) + { + if (!(isEven $plier)) { + $temp += $plicand + } + $plier = halveValue $plier + $plicand = doubleValue $plicand + } + +return $temp +} + +multiplyValues 17 34 diff --git a/Task/Ethiopian-multiplication/PowerShell/ethiopian-multiplication-1.psh b/Task/Ethiopian-multiplication/PowerShell/ethiopian-multiplication-1.psh deleted file mode 100644 index 04e4e45546..0000000000 --- a/Task/Ethiopian-multiplication/PowerShell/ethiopian-multiplication-1.psh +++ /dev/null @@ -1,35 +0,0 @@ -function isEven { - param ([int]$value) - return [bool]($value % 2 -eq 0) -} - -function doubleValue { - param ([int]$value) - return [int]($value * 2) -} - -function halveValue { - param ([int]$value) - return [int]($value / 2) -} - -function multiplyValues { - param ( - [int]$plier, - [int]$plicand, - [int]$temp = 0 - ) - - while ($plier -ge 1) - { - if (!(isEven $plier)) { - $temp += $plicand - } - $plier = halveValue $plier - $plicand = doubleValue $plicand - } - -return $temp -} - -multiplyValues 17 34 diff --git a/Task/Ethiopian-multiplication/PowerShell/ethiopian-multiplication-2.ps1 b/Task/Ethiopian-multiplication/PowerShell/ethiopian-multiplication-2.ps1 new file mode 100644 index 0000000000..1e797c3ed7 --- /dev/null +++ b/Task/Ethiopian-multiplication/PowerShell/ethiopian-multiplication-2.ps1 @@ -0,0 +1,29 @@ +function halveInt( [int] $rhs ) +{ + [math]::floor( $rhs / 2 ) +} + +function doubleInt( [int] $rhs ) +{ + $rhs*2 +} + +function isEven( [int] $rhs ) +{ + -not ( $_ % 2 ) +} + +function Ethiopian( [int] $lhs , [int] $rhs ) +{ + $scratch = @{} + 1..[math]::floor( [math]::log( $lhs , 2 ) + 1 ) | + ForEach-Object { + $scratch[$lhs] = $rhs + $lhs + $lhs = halveInt( $lhs ) + $rhs = doubleInt( $rhs ) } | + Where-Object { -not ( isEven $_ ) } | + ForEach-Object { $sum = 0 } { $sum += $scratch[$_] } { $sum } +} + +Ethiopian 17 34 diff --git a/Task/Ethiopian-multiplication/PowerShell/ethiopian-multiplication-2.psh b/Task/Ethiopian-multiplication/PowerShell/ethiopian-multiplication-2.psh deleted file mode 100644 index 5ba27a7a0e..0000000000 --- a/Task/Ethiopian-multiplication/PowerShell/ethiopian-multiplication-2.psh +++ /dev/null @@ -1,29 +0,0 @@ -function halveInt( [int] $rhs ) -{ - [math]::floor( $rhs / 2 ) -} - -function doubleInt( [int] $rhs ) -{ - $rhs*2 -} - -function isEven( [int] $rhs ) -{ - -not ( $_ % 2 ) -} - -function Ethiopian( [int] $lhs , [int] $rhs ) -{ - $scratch = @{} - 1..[math]::floor( [math]::log( $lhs , 2 ) + 1 ) | - ForEach-Object { - $scratch[$lhs] = $rhs - $lhs - $lhs = halveInt( $lhs ) - $rhs = doubleInt( $rhs ) } | - Where-Object { -not ( isEven $_ ) } | - ForEach-Object { $sum = 0 } { $sum += $scratch[$_] } { $sum } -} - -Ethiopian 17 34 diff --git a/Task/Ethiopian-multiplication/Powerbuilder/ethiopian-multiplication.powerbuilder b/Task/Ethiopian-multiplication/Powerbuilder/ethiopian-multiplication.powerbuilder index 119c89c29a..af6a22f8fb 100644 --- a/Task/Ethiopian-multiplication/Powerbuilder/ethiopian-multiplication.powerbuilder +++ b/Task/Ethiopian-multiplication/Powerbuilder/ethiopian-multiplication.powerbuilder @@ -11,13 +11,13 @@ public function long wf_ethiopianmultiplication (long al_multiplicand, long al_m long ll_product DO WHILE al_multiplicand >= 1 - IF wf_iseven(al_multiplicand) THEN - // do nothing - ELSE - ll_product += al_multiplier - END IF - al_multiplicand = wf_halve(al_multiplicand) - al_multiplier = wf_double(al_multiplier) + IF wf_iseven(al_multiplicand) THEN + // do nothing + ELSE + ll_product += al_multiplier + END IF + al_multiplicand = wf_halve(al_multiplicand) + al_multiplier = wf_double(al_multiplier) LOOP return ll_product diff --git a/Task/Ethiopian-multiplication/QuickBASIC/ethiopian-multiplication.basic b/Task/Ethiopian-multiplication/QuickBASIC/ethiopian-multiplication.basic new file mode 100644 index 0000000000..6fdbb1e5c2 --- /dev/null +++ b/Task/Ethiopian-multiplication/QuickBASIC/ethiopian-multiplication.basic @@ -0,0 +1,33 @@ +' Ethiopian multiplication +DECLARE FUNCTION Half% (A AS INTEGER) +DECLARE FUNCTION Doub% (A AS INTEGER) +DECLARE FUNCTION IsEven% (A AS INTEGER) + +DIM X AS INTEGER, Y AS INTEGER, OutP AS INTEGER +X = 17 +Y = 34 +DO + PRINT X, + IF NOT (IsEven(X)) THEN + OutP = OutP + Y + PRINT Y + ELSE + PRINT + END IF + IF X < 2 THEN EXIT DO + X = Half(X) + Y = Doub(Y) +LOOP +PRINT " =", OutP + +FUNCTION Doub% (A AS INTEGER) + Doub% = A * 2 +END FUNCTION + +FUNCTION Half% (A AS INTEGER) + Half% = A \ 2 +END FUNCTION + +FUNCTION IsEven% (A AS INTEGER) + IsEven% = (A MOD 2) - 1 +END FUNCTION diff --git a/Task/Ethiopian-multiplication/R/ethiopian-multiplication-2.r b/Task/Ethiopian-multiplication/R/ethiopian-multiplication-2.r index d105b32b1d..5c2f395556 100644 --- a/Task/Ethiopian-multiplication/R/ethiopian-multiplication-2.r +++ b/Task/Ethiopian-multiplication/R/ethiopian-multiplication-2.r @@ -3,13 +3,13 @@ double <- function(a) a*2 iseven <- function(a) (a%%2)==0 ethiopicmult<-function(x,y){ - res<-ifelse(iseven(y),0,x) - while(!y==1){ - x<-double(x) - y<-halve(y) - if(!iseven(y)) res<-res+x - } - return(res) + res<-ifelse(iseven(y),0,x) + while(!y==1){ + x<-double(x) + y<-halve(y) + if(!iseven(y)) res<-res+x + } + return(res) } print(ethiopicmult(17,34)) diff --git a/Task/Ethiopian-multiplication/Raku/ethiopian-multiplication-1.raku b/Task/Ethiopian-multiplication/Raku/ethiopian-multiplication-1.raku index 1fb06da87d..00d9e4165a 100644 --- a/Task/Ethiopian-multiplication/Raku/ethiopian-multiplication-1.raku +++ b/Task/Ethiopian-multiplication/Raku/ethiopian-multiplication-1.raku @@ -5,9 +5,9 @@ sub even (Int $n --> Bool) { $n %% 2 } sub ethiopic-mult (Int $a is copy, Int $b is copy --> Int) { my Int $r = 0; while $a { - even $a or $r += $b; - halve $a; - double $b; + even $a or $r += $b; + halve $a; + double $b; } return $r; } diff --git a/Task/Ethiopian-multiplication/Rascal/ethiopian-multiplication.rascal b/Task/Ethiopian-multiplication/Rascal/ethiopian-multiplication.rascal index 7efe02722d..63ddce167b 100644 --- a/Task/Ethiopian-multiplication/Rascal/ethiopian-multiplication.rascal +++ b/Task/Ethiopian-multiplication/Rascal/ethiopian-multiplication.rascal @@ -7,12 +7,12 @@ public int double(int n) = n*2; public bool uneven(int n) = (n % 2) != 0); public int ethiopianMul(int n, int m) { - result = 0; - while(n >= 1) { - if(uneven(n)) - result += m; - n = halve(n); - m = double(m); - } - return result; + result = 0; + while(n >= 1) { + if(uneven(n)) + result += m; + n = halve(n); + m = double(m); + } + return result; } diff --git a/Task/Ethiopian-multiplication/Rebol/ethiopian-multiplication.rebol b/Task/Ethiopian-multiplication/Rebol/ethiopian-multiplication.rebol new file mode 100644 index 0000000000..6d70881ef7 --- /dev/null +++ b/Task/Ethiopian-multiplication/Rebol/ethiopian-multiplication.rebol @@ -0,0 +1,31 @@ +Rebol [ + title: "Rosetta code: Ethiopian multiplication" + file: %Ethiopian_multiplication.r3 + url: https://rosettacode.org/wiki/Ethiopian_multiplication +] + +halve: function [n][n >> 1] +double: function [n][n << 1] + +ethiopian-multiply: function [ + "Returns the product of two integers using Ethiopian multiplication, with a printed trace" + a [integer!] "The multiplicand (column halved)" + b [integer!] "The multiplier (column doubled)" +][ + result: 0 + while [a <> 0][ + prin pad a -7 + either odd? a [ + result: result + b + print [as-green pad b -5 "(keep)"] + ][ print pad b -5] + a: halve a + b: double b + ] + print "-------------" + print as-yellow pad result -12 + result +] + +; Example: should print the layout shown for input 17 and 34 +ethiopian-multiply 17 34 diff --git a/Task/Ethiopian-multiplication/Rust/ethiopian-multiplication.rust b/Task/Ethiopian-multiplication/Rust/ethiopian-multiplication.rs similarity index 100% rename from Task/Ethiopian-multiplication/Rust/ethiopian-multiplication.rust rename to Task/Ethiopian-multiplication/Rust/ethiopian-multiplication.rs diff --git a/Task/Ethiopian-multiplication/SNOBOL4/ethiopian-multiplication.sno b/Task/Ethiopian-multiplication/SNOBOL4/ethiopian-multiplication.sno index 143f93f2f2..1486374343 100644 --- a/Task/Ethiopian-multiplication/SNOBOL4/ethiopian-multiplication.sno +++ b/Task/Ethiopian-multiplication/SNOBOL4/ethiopian-multiplication.sno @@ -1,21 +1,21 @@ - define('halve(num)') :(halve_end) -halve eq(num,1) :s(freturn) - halve = num / 2 :(return) + define('halve(num)') :(halve_end) +halve eq(num,1) :s(freturn) + halve = num / 2 :(return) halve_end - define('double(num)') :(double_end) -double double = num * 2 :(return) + define('double(num)') :(double_end) +double double = num * 2 :(return) double_end - define('odd(num)') :(odd_end) -odd eq(num,1) :s(return) - eq(num,double(halve(num))) :s(freturn)f(return) + define('odd(num)') :(odd_end) +odd eq(num,1) :s(return) + eq(num,double(halve(num))) :s(freturn)f(return) -odd_end l = trim(input) - r = trim(input) - s = 0 -next s = odd(l) s + r - r = double(r) - l = halve(l) :s(next) -stop output = s +odd_end l = trim(input) + r = trim(input) + s = 0 +next s = odd(l) s + r + r = double(r) + l = halve(l) :s(next) +stop output = s end diff --git a/Task/Ethiopian-multiplication/Scheme/ethiopian-multiplication.ss b/Task/Ethiopian-multiplication/Scheme/ethiopian-multiplication.scm similarity index 100% rename from Task/Ethiopian-multiplication/Scheme/ethiopian-multiplication.ss rename to Task/Ethiopian-multiplication/Scheme/ethiopian-multiplication.scm diff --git a/Task/Ethiopian-multiplication/Smalltalk/ethiopian-multiplication-1.st b/Task/Ethiopian-multiplication/Smalltalk/ethiopian-multiplication-1.st index 2d25a1a5cf..9a607ae2c2 100644 --- a/Task/Ethiopian-multiplication/Smalltalk/ethiopian-multiplication-1.st +++ b/Task/Ethiopian-multiplication/Smalltalk/ethiopian-multiplication-1.st @@ -20,7 +20,7 @@ Number extend [ ifTrue: [ tutor ifTrue: [ ('%1, %2 struck' % { multiplier. multiplicand }) - displayNl + displayNl ] ]. multiplier := multiplier halve. diff --git a/Task/Ethiopian-multiplication/Tcl/ethiopian-multiplication-1.tcl b/Task/Ethiopian-multiplication/Tcl/ethiopian-multiplication-1.tcl index 5f594c4172..873c47d443 100644 --- a/Task/Ethiopian-multiplication/Tcl/ethiopian-multiplication-1.tcl +++ b/Task/Ethiopian-multiplication/Tcl/ethiopian-multiplication-1.tcl @@ -9,22 +9,22 @@ function even n {($n & 1) == 0} function mult {a b} { $a < 1 ? 0 : even($a) ? [logmult STRUCK] + mult(halve($a), double($b)) - : [logmult KEPT] + mult(halve($a), double($b)) + $b + : [logmult KEPT] + mult(halve($a), double($b)) + $b } # Wrapper to set up the logging proc ethiopianMultiply {a b {tutor false}} { if {$tutor} { - set wa [expr {[string length $a]+1}] - set wb [expr {$wa+[string length $b]-1}] - puts stderr "Ethiopian multiplication of $a and $b" - interp alias {} logmult {} apply {{wa wb msg} { - upvar 1 a a b b - puts stderr [format "%*d %*d %s" $wa $a $wb $b $msg] - return 0 - }} $wa $wb + set wa [expr {[string length $a]+1}] + set wb [expr {$wa+[string length $b]-1}] + puts stderr "Ethiopian multiplication of $a and $b" + interp alias {} logmult {} apply {{wa wb msg} { + upvar 1 a a b b + puts stderr [format "%*d %*d %s" $wa $a $wb $b $msg] + return 0 + }} $wa $wb } else { - proc logmult args {return 0} + proc logmult args {return 0} } return [expr {mult($a,$b)}] } diff --git a/Task/Ethiopian-multiplication/True-BASIC/ethiopian-multiplication.basic b/Task/Ethiopian-multiplication/True-BASIC/ethiopian-multiplication.basic index 2e096710f7..938dbf5dca 100644 --- a/Task/Ethiopian-multiplication/True-BASIC/ethiopian-multiplication.basic +++ b/Task/Ethiopian-multiplication/True-BASIC/ethiopian-multiplication.basic @@ -1,29 +1,29 @@ !RosettaCode: Ethiopian Multiplication ! True BASIC v6.007 PROGRAM EthiopianMultiplication - DECLARE DEF FNdouble - DECLARE DEF FNhalve - DECLARE DEF FNeven - - LET x = 17 - LET y = 34 - - DO - IF FNeven(x) = 0 THEN - LET p = p + y - PRINT x,y - ELSE - PRINT x," ---" - END IF - - LET x = FNhalve(x) - LET y = FNdouble(y) - LOOP UNTIL x = 0 - PRINT " ", " ===" - PRINT " ", p - GET KEY done - - DEF FNdouble(A) = A * 2 - DEF FNhalve(A) = INT(A / 2) - DEF FNeven(A) = MOD(A+1,2) + DECLARE DEF FNdouble + DECLARE DEF FNhalve + DECLARE DEF FNeven + + LET x = 17 + LET y = 34 + + DO + IF FNeven(x) = 0 THEN + LET p = p + y + PRINT x,y + ELSE + PRINT x," ---" + END IF + + LET x = FNhalve(x) + LET y = FNdouble(y) + LOOP UNTIL x = 0 + PRINT " ", " ===" + PRINT " ", p + GET KEY done + + DEF FNdouble(A) = A * 2 + DEF FNhalve(A) = INT(A / 2) + DEF FNeven(A) = MOD(A+1,2) END diff --git a/Task/Ethiopian-multiplication/UNIX-Shell/ethiopian-multiplication-1.sh b/Task/Ethiopian-multiplication/UNIX-Shell/ethiopian-multiplication-1.sh index 21f4a8aaaf..f9a0dc4ee0 100644 --- a/Task/Ethiopian-multiplication/UNIX-Shell/ethiopian-multiplication-1.sh +++ b/Task/Ethiopian-multiplication/UNIX-Shell/ethiopian-multiplication-1.sh @@ -19,9 +19,9 @@ ethiopicmult() plicand=$2 r=0 while [ "$plier" -ge 1 ]; do - is_even "$plier" || r=`expr $r + "$plicand"` - plier=`halve "$plier"` - plicand=`double "$plicand"` + is_even "$plier" || r=`expr $r + "$plicand"` + plier=`halve "$plier"` + plicand=`double "$plicand"` done echo $r } diff --git a/Task/Ethiopian-multiplication/Uiua/ethiopian-multiplication.uiua b/Task/Ethiopian-multiplication/Uiua/ethiopian-multiplication.uiua new file mode 100644 index 0000000000..8f809a29aa --- /dev/null +++ b/Task/Ethiopian-multiplication/Uiua/ethiopian-multiplication.uiua @@ -0,0 +1,10 @@ +Halve ← ⌊÷2 +Double ← ×2 +Odd ← ◿2 +EMul ← ◌◌⍢(⊓Halve Double⍥⊙⟜+⊸Odd)±⊙⊙0 + +┌─╴test + ⍤⤙≍ 578 EMul 17 34 + ⍤⤙≍ 0 EMul 17 0 + ⍤⤙≍ 6 EMul 2 3 +└─╴ diff --git a/Task/Ethiopian-multiplication/VBScript/ethiopian-multiplication-1.vb b/Task/Ethiopian-multiplication/VBScript/ethiopian-multiplication-1.vb deleted file mode 100644 index 0746c78f8e..0000000000 --- a/Task/Ethiopian-multiplication/VBScript/ethiopian-multiplication-1.vb +++ /dev/null @@ -1,89 +0,0 @@ -option explicit - -class List - private theList - private nOccupiable - private nTop - - sub class_initialize - nTop = 0 - nOccupiable = 100 - redim theList( nOccupiable ) - end sub - - public sub store( x ) - if nTop >= nOccupiable then - nOccupiable = nOccupiable + 100 - redim preserve theList( nOccupiable ) - end if - theList( nTop ) = x - nTop = nTop + 1 - end sub - - public function recall( n ) - if n >= 0 and n <= nOccupiable then - recall = theList( n ) - else - err.raise vbObjectError + 1000,,"Recall bounds error" - end if - end function - - public sub replace( n, x ) - if n >= 0 and n <= nOccupiable then - theList( n ) = x - else - err.raise vbObjectError + 1001,,"Replace bounds error" - end if - end sub - - public property get listCount - listCount = nTop - end property - -end class - -function halve( n ) - halve = int( n / 2 ) -end function - -function twice( n ) - twice = int( n * 2 ) -end function - -function iseven( n ) - iseven = ( ( n mod 2 ) = 0 ) -end function - - -function multiply( n1, n2 ) - dim LL - set LL = new List - - dim RR - set RR = new List - - LL.store n1 - RR.store n2 - - do while n1 <> 1 - n1 = halve( n1 ) - LL.store n1 - n2 = twice( n2 ) - RR.store n2 - loop - - dim i - for i = 0 to LL.listCount - if iseven( LL.recall( i ) ) then - RR.replace i, 0 - end if - next - - dim total - total = 0 - for i = 0 to RR.listCount - total = total + RR.recall( i ) - next - - multiply = total -end function diff --git a/Task/Ethiopian-multiplication/VBScript/ethiopian-multiplication-1.vbs b/Task/Ethiopian-multiplication/VBScript/ethiopian-multiplication-1.vbs new file mode 100644 index 0000000000..ff896c9b1a --- /dev/null +++ b/Task/Ethiopian-multiplication/VBScript/ethiopian-multiplication-1.vbs @@ -0,0 +1,89 @@ +option explicit + +class List + private theList + private nOccupiable + private nTop + + sub class_initialize + nTop = 0 + nOccupiable = 100 + redim theList( nOccupiable ) + end sub + + public sub store( x ) + if nTop >= nOccupiable then + nOccupiable = nOccupiable + 100 + redim preserve theList( nOccupiable ) + end if + theList( nTop ) = x + nTop = nTop + 1 + end sub + + public function recall( n ) + if n >= 0 and n <= nOccupiable then + recall = theList( n ) + else + err.raise vbObjectError + 1000,,"Recall bounds error" + end if + end function + + public sub replace( n, x ) + if n >= 0 and n <= nOccupiable then + theList( n ) = x + else + err.raise vbObjectError + 1001,,"Replace bounds error" + end if + end sub + + public property get listCount + listCount = nTop + end property + +end class + +function halve( n ) + halve = int( n / 2 ) +end function + +function twice( n ) + twice = int( n * 2 ) +end function + +function iseven( n ) + iseven = ( ( n mod 2 ) = 0 ) +end function + + +function multiply( n1, n2 ) + dim LL + set LL = new List + + dim RR + set RR = new List + + LL.store n1 + RR.store n2 + + do while n1 <> 1 + n1 = halve( n1 ) + LL.store n1 + n2 = twice( n2 ) + RR.store n2 + loop + + dim i + for i = 0 to LL.listCount + if iseven( LL.recall( i ) ) then + RR.replace i, 0 + end if + next + + dim total + total = 0 + for i = 0 to RR.listCount + total = total + RR.recall( i ) + next + + multiply = total +end function diff --git a/Task/Ethiopian-multiplication/VBScript/ethiopian-multiplication-2.vb b/Task/Ethiopian-multiplication/VBScript/ethiopian-multiplication-2.vbs similarity index 100% rename from Task/Ethiopian-multiplication/VBScript/ethiopian-multiplication-2.vb rename to Task/Ethiopian-multiplication/VBScript/ethiopian-multiplication-2.vbs diff --git a/Task/Ethiopian-multiplication/X86-Assembly/ethiopian-multiplication-1.x86 b/Task/Ethiopian-multiplication/X86-Assembly/ethiopian-multiplication-1.x86 index 3d078eced9..ff6e3762ae 100644 --- a/Task/Ethiopian-multiplication/X86-Assembly/ethiopian-multiplication-1.x86 +++ b/Task/Ethiopian-multiplication/X86-Assembly/ethiopian-multiplication-1.x86 @@ -1,109 +1,109 @@ - extern printf - global main + extern printf + global main - section .text + section .text halve - shr ebx, 1 - ret + shr ebx, 1 + ret double - shl ebx, 1 - ret + shl ebx, 1 + ret iseven - and ebx, 1 - cmp ebx, 0 - ret ; ret preserves flags + and ebx, 1 + cmp ebx, 0 + ret ; ret preserves flags main - push 1 ; tutor = true - push 34 ; 2nd operand - push 17 ; 1st operand - call ethiopicmult - add esp, 12 + push 1 ; tutor = true + push 34 ; 2nd operand + push 17 ; 1st operand + call ethiopicmult + add esp, 12 - push eax ; result of 17*34 - push fmt - call printf - add esp, 8 + push eax ; result of 17*34 + push fmt + call printf + add esp, 8 - ret + ret %define plier 8 %define plicand 12 %define tutor 16 - + ethiopicmult - enter 0, 0 - cmp dword [ebp + tutor], 0 - je .notut0 - push dword [ebp + plicand] - push dword [ebp + plier] - push preamblefmt - call printf - add esp, 12 + enter 0, 0 + cmp dword [ebp + tutor], 0 + je .notut0 + push dword [ebp + plicand] + push dword [ebp + plier] + push preamblefmt + call printf + add esp, 12 .notut0 - xor eax, eax ; eax -> result - mov ecx, [ebp + plier] ; ecx -> plier - mov edx, [ebp + plicand] ; edx -> plicand + xor eax, eax ; eax -> result + mov ecx, [ebp + plier] ; ecx -> plier + mov edx, [ebp + plicand] ; edx -> plicand .whileloop - cmp ecx, 1 - jl .multend - cmp dword [ebp + tutor], 0 - je .notut1 - call tutorme + cmp ecx, 1 + jl .multend + cmp dword [ebp + tutor], 0 + je .notut1 + call tutorme .notut1 - mov ebx, ecx - call iseven - je .iseven - add eax, edx ; result += plicand + mov ebx, ecx + call iseven + je .iseven + add eax, edx ; result += plicand .iseven - mov ebx, ecx ; plier >>= 1 - call halve - mov ecx, ebx + mov ebx, ecx ; plier >>= 1 + call halve + mov ecx, ebx - mov ebx, edx ; plicand <<= 1 - call double - mov edx, ebx - - jmp .whileloop + mov ebx, edx ; plicand <<= 1 + call double + mov edx, ebx + + jmp .whileloop .multend - leave - ret + leave + ret tutorme - push eax - push strucktxt - mov ebx, ecx - call iseven - je .nostruck - mov dword [esp], kepttxt + push eax + push strucktxt + mov ebx, ecx + call iseven + je .nostruck + mov dword [esp], kepttxt .nostruck - push edx - push ecx - push tutorfmt - call printf - add esp, 4 - pop ecx - pop edx - add esp, 4 - pop eax - ret + push edx + push ecx + push tutorfmt + call printf + add esp, 4 + pop ecx + pop edx + add esp, 4 + pop eax + ret - section .data + section .data fmt - db "%d", 10, 0 + db "%d", 10, 0 preamblefmt - db "ethiopic multiplication of %d and %d", 10, 0 + db "ethiopic multiplication of %d and %d", 10, 0 tutorfmt - db "%4d %6d %s", 10, 0 + db "%4d %6d %s", 10, 0 strucktxt - db "struck", 0 + db "struck", 0 kepttxt - db "kept", 0 + db "kept", 0 diff --git a/Task/Ethiopian-multiplication/Yabasic/ethiopian-multiplication.basic b/Task/Ethiopian-multiplication/Yabasic/ethiopian-multiplication.basic index 38ab4861d9..345137d134 100644 --- a/Task/Ethiopian-multiplication/Yabasic/ethiopian-multiplication.basic +++ b/Task/Ethiopian-multiplication/Yabasic/ethiopian-multiplication.basic @@ -3,28 +3,28 @@ x = 17 y = 34 do - print x, chr$(09); - if not (isEven(x)) then - outP = outP + y - print y - else - print - fi - if x < 2 break - x = half(x) - y = doub(y) + print x, chr$(09); + if not (isEven(x)) then + outP = outP + y + print y + else + print + fi + if x < 2 break + x = half(x) + y = doub(y) loop print "=", chr$(09), outP end sub doub (a) - return a * 2 + return a * 2 end sub sub half (a) - return int(a / 2) + return int(a / 2) end sub sub isEven (a) - return mod(a, 2) - 1 + return mod(a, 2) - 1 end sub diff --git a/Task/Ethiopian-multiplication/Z80-Assembly/ethiopian-multiplication.z80 b/Task/Ethiopian-multiplication/Z80-Assembly/ethiopian-multiplication.z80 index cbc6ebf0a0..5641a4f8c2 100644 --- a/Task/Ethiopian-multiplication/Z80-Assembly/ethiopian-multiplication.z80 +++ b/Task/Ethiopian-multiplication/Z80-Assembly/ethiopian-multiplication.z80 @@ -1,114 +1,114 @@ - org &8000 + org &8000 - ld hl,17 - call Halve_Until_1 - - push bc - ld hl,34 - call Double_Until_1 - pop bc - - call SumOddEntries - ;returns Ethiopian product in IX. - - call NewLine - - call Primm - byte "0x",0 - - push ix - pop hl - - ld a,H - call ShowHex - ;Output should be in decimal but hex is easier. - ld a,L - call ShowHex - - ret + ld hl,17 + call Halve_Until_1 + + push bc + ld hl,34 + call Double_Until_1 + pop bc + + call SumOddEntries + ;returns Ethiopian product in IX. + + call NewLine + + call Primm + byte "0x",0 + + push ix + pop hl + + ld a,H + call ShowHex + ;Output should be in decimal but hex is easier. + ld a,L + call ShowHex + + ret Halve_Until_1: - ;input: HL = number you wish to halve. HL is unsigned. - ld de,Column_1 - ld a,1 - ld (Column_1),HL - inc de - inc de + ;input: HL = number you wish to halve. HL is unsigned. + ld de,Column_1 + ld a,1 + ld (Column_1),HL + inc de + inc de loop_HalveUntil_1: - SRL H - RR L - inc b - push af - ld a,L - ld (de),a - inc de - ld a,H - ld (de),a - inc de - pop af - CP L - jr nz,loop_HalveUntil_1 - ;b tracks how many times to double the second factor. - ret - + SRL H + RR L + inc b + push af + ld a,L + ld (de),a + inc de + ld a,H + ld (de),a + inc de + pop af + CP L + jr nz,loop_HalveUntil_1 + ;b tracks how many times to double the second factor. + ret + Double_Until_1: - ;doubles second factor B times. B is calculated by Halve_until_1 - ld de,Column_2 - ld (Column_2),HL - inc de - inc de + ;doubles second factor B times. B is calculated by Halve_until_1 + ld de,Column_2 + ld (Column_2),HL + inc de + inc de loop_double_until_1: - SLA L - RL H - PUSH AF - LD A,L - LD (DE),A - INC DE - LD A,H - LD (DE),A - INC DE - POP AF - DJNZ loop_double_until_1 - ret + SLA L + RL H + PUSH AF + LD A,L + LD (DE),A + INC DE + LD A,H + LD (DE),A + INC DE + POP AF + DJNZ loop_double_until_1 + ret + - SumOddEntries: - sla b ;double loop counter, this is also the offset to the "last" entry of - ;each table - ld h,>Column_1 - ld d,>Column_2 ;aligning the tables lets us get away with this. - ld l,b - ld e,b - ld ix,0 + sla b ;double loop counter, this is also the offset to the "last" entry of + ;each table + ld h,>Column_1 + ld d,>Column_2 ;aligning the tables lets us get away with this. + ld l,b + ld e,b + ld ix,0 loop: - ld a,(hl) - rrca ;we only need the result of the odd/even test. - jr nc,skipEven - push hl - push de - ld a,(de) - ld L,a - inc de - ld a,(de) - ld H,a - ex de,hl - add ix,de - pop de - pop hl + ld a,(hl) + rrca ;we only need the result of the odd/even test. + jr nc,skipEven + push hl + push de + ld a,(de) + ld L,a + inc de + ld a,(de) + ld H,a + ex de,hl + add ix,de + pop de + pop hl skipEven: - dec de - dec de - dec hl - dec hl - djnz loop - ret ;ix should contain the answer + dec de + dec de + dec hl + dec hl + djnz loop + ret ;ix should contain the answer - - align 8 ;aligns Column_1 to the nearest 256 byte boundary. This makes offsetting easier. + + align 8 ;aligns Column_1 to the nearest 256 byte boundary. This makes offsetting easier. Column_1: - ds 16,0 - - align 8 ;aligns Column_2 to the nearest 256 byte boundary. This makes offsetting easier. + ds 16,0 + + align 8 ;aligns Column_2 to the nearest 256 byte boundary. This makes offsetting easier. Column_2: - ds 16,0 + ds 16,0 diff --git a/Task/Euclid-Mullin-sequence/C++/euclid-mullin-sequence.cpp b/Task/Euclid-Mullin-sequence/C++/euclid-mullin-sequence.cpp new file mode 100644 index 0000000000..11e98dc402 --- /dev/null +++ b/Task/Euclid-Mullin-sequence/C++/euclid-mullin-sequence.cpp @@ -0,0 +1,30 @@ +#include +#include + +uint64_t product = 2; + +uint64_t smallest_prime_factor(const uint64_t& number) { + if ( number % 3 == 0 ) { return 3; } + if ( number % 5 == 0 ) { return 5; } + + for ( uint64_t divisor = 7; divisor * divisor <= number; divisor += 2 ) { + if ( number % divisor == 0 ) { return divisor; } + } + + return number; +} + +uint64_t next_euclid_mullin() { + const uint64_t smallest_prime = smallest_prime_factor(product + 1); + product *= smallest_prime; + return smallest_prime; +} + +int main() { + std::cout << "The first 9 terms of the Euclid-Mullin sequence:" << "\n"; + std::cout << 2 << " "; + for ( uint32_t i = 1; i < 9; ++i ) { + std::cout << next_euclid_mullin() << " "; + } + std::cout << "\n"; +} diff --git a/Task/Euclid-Mullin-sequence/EasyLang/euclid-mullin-sequence.easy b/Task/Euclid-Mullin-sequence/EasyLang/euclid-mullin-sequence.easy index 961b4a0430..0bbed926a2 100644 --- a/Task/Euclid-Mullin-sequence/EasyLang/euclid-mullin-sequence.easy +++ b/Task/Euclid-Mullin-sequence/EasyLang/euclid-mullin-sequence.easy @@ -1,17 +1,17 @@ -limit = 8 arr[] = [ 2 ] -write 2 & " " -for i = 2 to limit - k = 3 - repeat - em = 1 - for j = 1 to i - 1 - em = em * arr[j] mod k +fastproc . + for i = 2 to 8 + k = 3 + repeat + em = 1 + for j = 1 to i - 1 + em = em * arr[j] mod k + . + em = (em + 1) mod k + until em = 0 + k += 2 . - em = (em + 1) mod k - until em = 0 - k += 2 + arr[] &= k . - arr[] &= k - write k & " " . +print arr[] diff --git a/Task/Euclid-Mullin-sequence/Fennel/euclid-mullin-sequence.fennel b/Task/Euclid-Mullin-sequence/Fennel/euclid-mullin-sequence.fennel new file mode 100644 index 0000000000..5f18e0534c --- /dev/null +++ b/Task/Euclid-Mullin-sequence/Fennel/euclid-mullin-sequence.fennel @@ -0,0 +1,18 @@ +(do ;;; find elements of the Euclid-Mullin sequence: starting from 2, + ;;; the next element is the smallest prime factor of 1 + the product + ;;; of the previous elements + + (io.write "2") + (var product 2) + (for [i 2 9] + (var (nextV p found) (values (+ product 1) 3 false)) + ; find the first prime factor of nextV + (while (and (<= (* p p) nextV) (not found)) + (set found (= 0 (% nextV p))) + (when (not found) (set p (+ p 2))) + ) + (when found (set nextV p)) + (io.write (.. " " nextV)) + (set product (* product nextV)) + ) +) diff --git a/Task/Euclid-Mullin-sequence/FutureBasic/euclid-mullin-sequence.basic b/Task/Euclid-Mullin-sequence/FutureBasic/euclid-mullin-sequence.basic new file mode 100644 index 0000000000..f6c83a34f6 --- /dev/null +++ b/Task/Euclid-Mullin-sequence/FutureBasic/euclid-mullin-sequence.basic @@ -0,0 +1,57 @@ +// +// Euclid-Mullin Sequence +// Using FutureBasic 7.0.35 +// +// September 2025, R.W. +// + +include "gmp.incl" + +_TERMS = 16 // first 16 Euclid–Mullin Sequence + +// Return a non-trivial factor of n using Pollard-Rho + +void local fn PollardRho( n as mpz_t, out as mpz_t ) + mpz_t x,y,c,d,absDiff + mpz_inits( x, y, c, d, absDiff, 0 ) + mpz_set_ui( x, 2 ) : mpz_set_ui( y, 2 ) : mpz_set_ui( c, 1 ) + mpz_set_ui( d, 1 ) + while fn mpz_cmp_ui( d, 1 ) == 0 + // x = (x*x + c) mod n + mpz_mul( x, x, x ) : mpz_add( x, x, c ) : mpz_mod( x, x, n ) + // y = f(f(y)) + mpz_mul( y, y, y ) : mpz_add( y, y, c ) : mpz_mod( y, y, n ) + mpz_mul( y, y, y ) : mpz_add( y, y, c ) : mpz_mod( y, y, n ) + // d = gcd(|x-y|, n) + mpz_sub( absDiff, x, y ) : mpz_abs( absDiff, absDiff ) + fn mpz_gcd( d, absDiff, n ) + wend + mpz_set( out, d ) + mpz_clears( x,y,c,d,absDiff,0 ) +end fn + +void local fn EuclidMullin( terms as long ) + CFStringRef result + mpz_t total, tmp, factor + mpz_inits( total, tmp, factor, 0 ) + mpz_set_ui( total, 1 ) + print @ + print @"First ";terms;" numbers of Euclid-Mullin sequence" + print @ + long k + for k = 1 to _TERMS + mpz_add_ui( tmp, total, 1 ) // tmp = total + 1 + fn PollardRho( tmp, factor ) // factor = some factor of tmp + result = fn mpz_cf2( factor ) + print result + mpz_mul( total, total, factor ) // total *= factor + next + + mpz_clears( total, tmp, factor, 0 ) +end fn + +window 1, @"Euclid-Mullin Sequence" + +fn EuclidMullin(_TERMS ) + +handleEvents diff --git a/Task/Euclid-Mullin-sequence/Java/euclid-mullin-sequence.java b/Task/Euclid-Mullin-sequence/Java/euclid-mullin-sequence.java index 0acc583224..6c4836716f 100644 --- a/Task/Euclid-Mullin-sequence/Java/euclid-mullin-sequence.java +++ b/Task/Euclid-Mullin-sequence/Java/euclid-mullin-sequence.java @@ -12,7 +12,8 @@ public final class EuclidMullinSequence { System.out.println("The first 27 terms of the Euclid-Mullin sequence:"); System.out.print(2 + " "); for ( int i = 1; i < 27; i++ ) { - System.out.print(String.format("%s%s", nextEuclidMullin(), ( i == 14 || i == 27 ) ? "\n" : " ")); + System.out.print( + String.format("%s%s", nextEuclidMullin(), ( i == 14 || i == 27 ) ? "\n" : " ")); } } @@ -67,7 +68,7 @@ public final class EuclidMullinSequence { sieve.set(2, aLimit + 1); for ( int i = 2; i * i <= aLimit; i = sieve.nextSetBit(i + 1) ) { - for ( int j = i * i; j <= aLimit; j = j + i ) { + for ( int j = i * i; j <= aLimit; j += i ) { sieve.clear(j); } } diff --git a/Task/Euclid-Mullin-sequence/JavaScript/euclid-mullin-sequence.js b/Task/Euclid-Mullin-sequence/JavaScript/euclid-mullin-sequence.js new file mode 100644 index 0000000000..05dfefc61c --- /dev/null +++ b/Task/Euclid-Mullin-sequence/JavaScript/euclid-mullin-sequence.js @@ -0,0 +1,20 @@ + let product = 2n; + function smallestPrimeFactor(number) { + if (number % 3n === 0n) { return 3n; } + if (number % 5n === 0n) { return 5n; } + for (let divisor = 7n; divisor * divisor <= number; divisor += 2n) { + if (number % divisor === 0n) { return divisor; } + } + return number; + } + function nextEuclidMullin() { + const smallestPrime = smallestPrimeFactor(product + 1n); + product *= smallestPrime; + return smallestPrime; + } + console.log("The first 9 terms of the Euclid-Mullin sequence:"); + process.stdout.write(2 + " "); + for (let i = 1; i < 9; ++i) { + process.stdout.write(nextEuclidMullin() + " "); + } + console.log("\n"); diff --git a/Task/Euclid-Mullin-sequence/Julia/euclid-mullin-sequence.julia b/Task/Euclid-Mullin-sequence/Julia/euclid-mullin-sequence.jl similarity index 100% rename from Task/Euclid-Mullin-sequence/Julia/euclid-mullin-sequence.julia rename to Task/Euclid-Mullin-sequence/Julia/euclid-mullin-sequence.jl diff --git a/Task/Euclid-Mullin-sequence/Lua/euclid-mullin-sequence-1.lua b/Task/Euclid-Mullin-sequence/Lua/euclid-mullin-sequence-1.lua index 6213d7fddf..d8ed7d4919 100644 --- a/Task/Euclid-Mullin-sequence/Lua/euclid-mullin-sequence-1.lua +++ b/Task/Euclid-Mullin-sequence/Lua/euclid-mullin-sequence-1.lua @@ -4,11 +4,9 @@ do io.write( "2" ) local product = 2 - for i = 2, 8 do - local nextV = product + 1 + for i = 2, 9 do + local nextV, p, found = product + 1, 3, false -- find the first prime factor of nextV - local p = 3 - local found = false while p * p <= nextV and not found do found = nextV % p == 0 if not found then p = p + 2 end diff --git a/Task/Euclid-Mullin-sequence/Oberon-07/euclid-mullin-sequence.oberon b/Task/Euclid-Mullin-sequence/Oberon-07/euclid-mullin-sequence.oberon new file mode 100644 index 0000000000..178ae1c826 --- /dev/null +++ b/Task/Euclid-Mullin-sequence/Oberon-07/euclid-mullin-sequence.oberon @@ -0,0 +1,29 @@ +MODULE EuclidMullinSequence; (* find elements of the Euclid-Mullin sequence: *) + IMPORT Out; (* starting from 2, the next element is the smallest *) + (* prime factor of 1 + the product of the previous *) + (* elements *) + + (* assuming INTEGER is 32-bit, we should be able to *) + (* find 8 elements, before the product overflows *) + + VAR product, i, nextV, p : INTEGER; + found : BOOLEAN; + +BEGIN + + Out.String( "2" ); + product := 2; + FOR i := 2 TO 8 DO + nextV := product + 1; + (* find the first prime factor of nextV *) + p := 3; + found := FALSE; + WHILE ~ found & ( p * p <= nextV ) DO + found := nextV MOD p = 0; + IF ~ found THEN INC( p, 2 ) END + END; + IF found THEN nextV := p END; + Out.String( " " );Out.Int( nextV, 0 ); + product := product * nextV + END +END EuclidMullinSequence. diff --git a/Task/Euclid-Mullin-sequence/Oberon/euclid-mullin-sequence.oberon b/Task/Euclid-Mullin-sequence/Oberon/euclid-mullin-sequence.oberon new file mode 100644 index 0000000000..b735a6b4c2 --- /dev/null +++ b/Task/Euclid-Mullin-sequence/Oberon/euclid-mullin-sequence.oberon @@ -0,0 +1,29 @@ +MODULE EuclidMullinSequence; (* find elements of the Euclid-Mullin sequence: *) + IMPORT Out; (* starting from 2, the next element is the smallest *) + (* prime factor of 1 + the product of the previous *) + (* elements *) + + (* assuming LONGINT is 64-bit, we should be able to *) + (* find 9 elements, before the product overflows *) + + VAR product, i, nextV, p : LONGINT; + found : BOOLEAN; + +BEGIN + + Out.String( "2" ); + product := 2; + FOR i := 2 TO 9 DO + nextV := product + 1; + (* find the first prime factor of nextV *) + p := 3; + found := FALSE; + WHILE ~ found & ( p * p <= nextV ) DO + found := nextV MOD p = 0; + IF ~ found THEN INC( p, 2 ) END + END; + IF found THEN nextV := p END; + Out.String( " " );Out.Int( nextV, 0 ); + product := product * nextV + END +END EuclidMullinSequence. diff --git a/Task/Euclid-Mullin-sequence/PascalABC.NET/euclid-mullin-sequence.pas b/Task/Euclid-Mullin-sequence/PascalABC.NET/euclid-mullin-sequence.pas new file mode 100644 index 0000000000..38999023a9 --- /dev/null +++ b/Task/Euclid-Mullin-sequence/PascalABC.NET/euclid-mullin-sequence.pas @@ -0,0 +1,29 @@ +function smallest_prime_factor(number: biginteger): biginteger; +begin + var divisor := 3bi; + repeat + if (number mod divisor) = 0 then + begin + result := divisor; + exit + end; + divisor += 2; + until divisor * divisor > number; + result := number; +end; + +function euclid_mullin(): sequence of biginteger; +begin + var product := 2bi; + yield product; + while true do + begin + var smallest_prime := smallest_prime_factor(product + 1); + product *= smallest_prime; + yield smallest_prime; + end; +end; + +begin + euclid_mullin.take(16).println; +end. diff --git a/Task/Euclid-Mullin-sequence/Pluto/euclid-mullin-sequence.pluto b/Task/Euclid-Mullin-sequence/Pluto/euclid-mullin-sequence.pluto new file mode 100644 index 0000000000..9e6b45651e --- /dev/null +++ b/Task/Euclid-Mullin-sequence/Pluto/euclid-mullin-sequence.pluto @@ -0,0 +1,22 @@ +-- find elements of the Euclid-Mullin sequence: starting from 2, +-- the next element is the smallest prime factor of 1 + the product +-- of the previous elements +do + local bigint = require( "pluto:bigint" ) -- use the standard bigint library + + io.write( "2" ) + local b0 , b1 , b2 , b3 + = new bigint( 0 ), new bigint( 1 ), new bigint( 2 ), new bigint( 3 ) + local product = new bigint( 2 ) + for _ = 2, 16 do + local nextV, p, found = product + b1, b3, false + -- find the first prime factor of nextV + while p * p <= nextV and not found do + found = nextV % p == b0 + if not found then p += b2 end + end + if found then nextV = p end + io.write( $" { nextV:tostring() }" ) + product *= nextV + end +end diff --git a/Task/Euclid-Mullin-sequence/R/euclid-mullin-sequence.r b/Task/Euclid-Mullin-sequence/R/euclid-mullin-sequence.r new file mode 100644 index 0000000000..d81fa0cb94 --- /dev/null +++ b/Task/Euclid-Mullin-sequence/R/euclid-mullin-sequence.r @@ -0,0 +1,10 @@ +library(gmp) + +next_term <- function(v) min(factorize(prod(v)+1)) +euclid_mullin <- function(n){ + v <- as.bigz(2) + replicate(n-1, v <<- c(v, next_term(v))) + print(v, initLine=FALSE) +} + +euclid_mullin(16) diff --git a/Task/Euclid-Mullin-sequence/REXX/euclid-mullin-sequence.rexx b/Task/Euclid-Mullin-sequence/REXX/euclid-mullin-sequence.rexx new file mode 100644 index 0000000000..c681066ff1 --- /dev/null +++ b/Task/Euclid-Mullin-sequence/REXX/euclid-mullin-sequence.rexx @@ -0,0 +1,22 @@ +-- 23 Aug 2025 +include Setting + +say 'EUCLID-MULLIN SEQUENCE' +say version +say +numeric digits 100 +call Euclids 16 +call Task 16 +say Format(Time('e'),,3) 'seconds' +exit + +Task: +arg xx +say 'The first' xx 'Euclid-Mullin numbers are:' +do i = 1 to xx + call Charout ,eucl.i' ' +end +say +return + +include Math diff --git a/Task/Euler-method/Ada/euler-method-1.ada b/Task/Euler-method/Ada/euler-method-1.adb similarity index 100% rename from Task/Euler-method/Ada/euler-method-1.ada rename to Task/Euler-method/Ada/euler-method-1.adb diff --git a/Task/Euler-method/Ada/euler-method-2.ada b/Task/Euler-method/Ada/euler-method-2.adb similarity index 100% rename from Task/Euler-method/Ada/euler-method-2.ada rename to Task/Euler-method/Ada/euler-method-2.adb diff --git a/Task/Euler-method/Ada/euler-method-3.ada b/Task/Euler-method/Ada/euler-method-3.adb similarity index 100% rename from Task/Euler-method/Ada/euler-method-3.ada rename to Task/Euler-method/Ada/euler-method-3.adb diff --git a/Task/Euler-method/BASIC256/euler-method.basic b/Task/Euler-method/BASIC256/euler-method.basic index 5ff323099b..54074d0bd6 100644 --- a/Task/Euler-method/BASIC256/euler-method.basic +++ b/Task/Euler-method/BASIC256/euler-method.basic @@ -1,17 +1,17 @@ print "Time "; tiempo = 0.0 while tiempo <= 100.1 - print rjust(string(tiempo), 5); " "; - tiempo += 10.0 + print rjust(string(tiempo), 5); " "; + tiempo += 10.0 end while print print "Dif eq "; tiempo = 0.0 while tiempo <= 100.1 - temperatura = 20.0 + (100.0-20.0) * exp(-0.07*tiempo) - print rjust(left(string(temperatura), 5), 5); " "; - tiempo += 10.0 + temperatura = 20.0 + (100.0-20.0) * exp(-0.07*tiempo) + print rjust(left(string(temperatura), 5), 5); " "; + tiempo += 10.0 end while print @@ -21,14 +21,14 @@ call Euler(10) end subroutine Euler(paso) - tiempo = 0 - temperatura = 100.0 - print "Step "; rjust(string(paso), 2); " "; + tiempo = 0 + temperatura = 100.0 + print "Step "; rjust(string(paso), 2); " "; - while tiempo <= 100 - if (tiempo mod 10) = 0 then print rjust(left(string(temperatura), 5), 5); " "; - temperatura += float(paso) * (-0.07*(temperatura-20.0)) - tiempo += paso - end while - print + while tiempo <= 100 + if (tiempo mod 10) = 0 then print rjust(left(string(temperatura), 5), 5); " "; + temperatura += float(paso) * (-0.07*(temperatura-20.0)) + tiempo += paso + end while + print end subroutine diff --git a/Task/Euler-method/C-sharp/euler-method.cs b/Task/Euler-method/C-sharp/euler-method.cs index 9b7d1f041f..0491640ac8 100644 --- a/Task/Euler-method/C-sharp/euler-method.cs +++ b/Task/Euler-method/C-sharp/euler-method.cs @@ -2,37 +2,37 @@ using System; namespace prog { - class MainClass - { - const float T0 = 100f; - const float TR = 20f; - const float k = 0.07f; - readonly static float[] delta_t = {2.0f,5.0f,10.0f}; - const int n = 100; - - public delegate float func(float t); - static float NewtonCooling(float t) - { - return -k * (t-TR); - } - - public static void Main (string[] args) - { - func f = new func(NewtonCooling); - for(int i=0; i x2 and x_start > x2) + ) + from cte +); + +create or replace function euler(x_start, y_start, x2, h) as ( + select last(y order by x) from euler_method(x_start, y_start, x2, h) +); + +## Example: +create or replace function cooling(x,y) as + -0.07 * (y - 20); + +select h, euler(0,100, 100, h) from unnest([1,2,5,10,20]) _(h); diff --git a/Task/Euler-method/EasyLang/euler-method.easy b/Task/Euler-method/EasyLang/euler-method.easy index 2103cb54ff..db168de994 100644 --- a/Task/Euler-method/EasyLang/euler-method.easy +++ b/Task/Euler-method/EasyLang/euler-method.easy @@ -1,39 +1,38 @@ TR = 20 K = -0.07 -func analytic T0 t . - return TR + (T0 - TR) * pow 2.71828 (K * t) -. ytxt = 95 -proc draw_analytic a b . . - color 009 - move 80 ytxt - ytxt -= 5 - text "analytic" - for t = a to b - line t analytic 100 t - . -. drawgrid -linewidth 0.3 -textsize 3 -draw_analytic 0 100 +glinewidth 0.3 +gtextsize 3 # func newton_cooling temp . return K * (temp - TR) . -proc draw_euler y0 a b step col . . - color col - move 80 ytxt +proc draw_euler y t t2 step col . + gcolor col + gtext 80 ytxt "step: " & step ytxt -= 5 - text "step: " & step - t = a - y = y0 - while t < b - line t y + gpenup + while t <= t2 + glineto t y t += step y += step * newton_cooling y . . +func analytic T0 t . + return TR + (T0 - TR) * pow 2.71828 (K * t) +. +proc draw_analytic a b . + gcolor 009 + gtext 80 ytxt "analytic" + ytxt -= 5 + gpenup + for t = a to b + y = analytic 100 t + glineto t y + . +. draw_euler 100 0 100 10 900 draw_euler 100 0 100 5 555 draw_euler 100 0 100 2 090 +draw_analytic 0 100 diff --git a/Task/Euler-method/Elixir/euler-method.elixir b/Task/Euler-method/Elixir/euler-method.ex similarity index 100% rename from Task/Euler-method/Elixir/euler-method.elixir rename to Task/Euler-method/Elixir/euler-method.ex diff --git a/Task/Euler-method/Erlang/euler-method.erl b/Task/Euler-method/Erlang/euler-method.erl index 4f1549d0c4..4bf8857e9e 100644 --- a/Task/Euler-method/Erlang/euler-method.erl +++ b/Task/Euler-method/Erlang/euler-method.erl @@ -2,37 +2,37 @@ -export([main/0, euler/5]). cooling(_Time, Temperature) -> - (-0.07)*(Temperature-20). + (-0.07)*(Temperature-20). euler(_, Y, T, _, End) when End == T -> - io:fwrite("\n"), - Y; + io:fwrite("\n"), + Y; euler(Func, Y, T, Step, End) -> - if - T rem 10 == 0 -> - io:fwrite("~.3f ",[float(Y)]); - true -> - ok - end, - euler(Func, Y + Step * Func(T, Y), T + Step, Step, End). + if + T rem 10 == 0 -> + io:fwrite("~.3f ",[float(Y)]); + true -> + ok + end, + euler(Func, Y + Step * Func(T, Y), T + Step, Step, End). analytic(T, End) when T == End -> - io:fwrite("\n"), - T; + io:fwrite("\n"), + T; analytic(T, End) -> - Y = (20 + 80 * math:exp(-0.07 * T)), - io:fwrite("~.3f ", [Y]), - analytic(T+10, End). + Y = (20 + 80 * math:exp(-0.07 * T)), + io:fwrite("~.3f ", [Y]), + analytic(T+10, End). main() -> - io:fwrite("Analytic:\n"), - analytic(0, 100), - io:fwrite("Step 2:\n"), - euler(fun cooling/2, 100, 0, 2, 100), - io:fwrite("Step 5:\n"), - euler(fun cooling/2, 100, 0, 5, 100), - io:fwrite("Step 10:\n"), - euler(fun cooling/2, 100, 0, 10, 100), - ok. + io:fwrite("Analytic:\n"), + analytic(0, 100), + io:fwrite("Step 2:\n"), + euler(fun cooling/2, 100, 0, 2, 100), + io:fwrite("Step 5:\n"), + euler(fun cooling/2, 100, 0, 5, 100), + io:fwrite("Step 10:\n"), + euler(fun cooling/2, 100, 0, 10, 100), + ok. diff --git a/Task/Euler-method/FutureBasic/euler-method.basic b/Task/Euler-method/FutureBasic/euler-method.basic new file mode 100644 index 0000000000..dfb5d86659 --- /dev/null +++ b/Task/Euler-method/FutureBasic/euler-method.basic @@ -0,0 +1,33 @@ +include "NSLog.incl" + +double local fn Cooling( t as double, temp as double ) + return -0.07 * (temp - 20 ) +end fn = 0.0 + +void local fn Euler( y as double, stepSize as int, endTime as double ) + int t = 0 + NSLog( @"\n Step %2d: \b", stepSize ) + while ( t <= endTime ) + if ( t % 10 == 0 ) then NSLog( @" %7.3f \b", y ) + y += stepSize * fn Cooling( t, y ) + t += stepSize + wend +end fn + +void local fn Analytic + NSLog( @" Time: \b" ) + for int t1 = 0 to 100 step 10 + NSLog( @" %8d\b", t1 ) + next + NSLog( @"\nAnalytic: \b" ) + for int t2 = 0 to 100 step 10 + NSLog( @"%9.3f\b", 20 + 80 * exp(-0.07 * t2 ) ) + next +end fn + +fn Analytic +fn Euler( 100.0, 2.0, 100.0 ) +fn Euler( 100.0, 5.0, 100.0 ) +fn Euler( 100.0, 10.0, 100.0 ) + +HandleEvents diff --git a/Task/Euler-method/JavaScript/euler-method.js b/Task/Euler-method/JavaScript/euler-method.js index 69666fe2e1..edff7b850d 100644 --- a/Task/Euler-method/JavaScript/euler-method.js +++ b/Task/Euler-method/JavaScript/euler-method.js @@ -1,29 +1,29 @@ // Function that takes differential-equation, initial condition, // ending x, and step size as parameters function eulersMethod(f, x1, y1, x2, h) { - // Header - console.log("\tX\t|\tY\t"); - console.log("------------------------------------"); + // Header + console.log("\tX\t|\tY\t"); + console.log("------------------------------------"); - // Initial Variables - var x=x1, y=y1; + // Initial Variables + var x=x1, y=y1; - // While we're not done yet - // Both sides of the OR let you do Euler's Method backwards - while ((xx2 && x1>x2)) { - // Print what we have - console.log("\t" + x + "\t|\t" + y); + // While we're not done yet + // Both sides of the OR let you do Euler's Method backwards + while ((xx2 && x1>x2)) { + // Print what we have + console.log("\t" + x + "\t|\t" + y); - // Calculate the next values - y += h*f(x, y) - x += h; - } + // Calculate the next values + y += h*f(x, y) + x += h; + } - return y; + return y; } function cooling(x, y) { - return -0.07 * (y-20); + return -0.07 * (y-20); } eulersMethod(cooling, 0, 100, 100, 10); diff --git a/Task/Euler-method/Jq/euler-method-1.jq b/Task/Euler-method/Jq/euler-method-1.jq index 4036e91460..3121a16965 100644 --- a/Task/Euler-method/Jq/euler-method-1.jq +++ b/Task/Euler-method/Jq/euler-method-1.jq @@ -7,7 +7,7 @@ def euler_method(df; x1; y1; x2; h): | [x1, y1] | recurse( if ((.[0] < x2 and x1 < x2) or (.[0] > x2 and x1 > x2)) then - [ (.[0] + $h), (.[1] + $h*df) ] + [ (.[0] + $h), (.[1] + $h*df) ] else empty end ) | .[1] ; diff --git a/Task/Euler-method/Jq/euler-method-2.jq b/Task/Euler-method/Jq/euler-method-2.jq index cbb1cefb18..dad3672557 100644 --- a/Task/Euler-method/Jq/euler-method-2.jq +++ b/Task/Euler-method/Jq/euler-method-2.jq @@ -4,7 +4,7 @@ def euler_solution(df; x1; y1; x2; h): | [x1, y1] | recursion( if ((.[0] < x2 and x1 < x2) or (.[0] > x2 and x1 > x2)) then - [ (.[0] + $h), (.[1] + $h*df) ] + [ (.[0] + $h), (.[1] + $h*df) ] else empty end ) | .[1] ; diff --git a/Task/Euler-method/Julia/euler-method.julia b/Task/Euler-method/Julia/euler-method.jl similarity index 100% rename from Task/Euler-method/Julia/euler-method.julia rename to Task/Euler-method/Julia/euler-method.jl diff --git a/Task/Euler-method/K/euler-method.k b/Task/Euler-method/K/euler-method.k new file mode 100644 index 0000000000..1bb3a2cd8c --- /dev/null +++ b/Task/Euler-method/K/euler-method.k @@ -0,0 +1,15 @@ +// make global variables with :: because while is only locally scoped +tn1::100 +tn::100 +// to store solution +sol::() +// these are constant, so only local scope +k:-0.07 +time:100 +steps:10 +h:time%steps +tr:20 +// applying x+h to 0 outside to end while loop +// bind to a variable to surpress output +var: {x<100}{tn1::tn+h*k*(tn-tr);sol::sol,tn;tn::tn1;x+h}\0 +sol diff --git a/Task/Euler-method/Kotlin/euler-method.kotlin b/Task/Euler-method/Kotlin/euler-method.kts similarity index 100% rename from Task/Euler-method/Kotlin/euler-method.kotlin rename to Task/Euler-method/Kotlin/euler-method.kts diff --git a/Task/Euler-method/Lambdatalk/euler-method.lambdatalk b/Task/Euler-method/Lambdatalk/euler-method.lambdatalk index 62f2efe8fb..8f70a445a6 100644 --- a/Task/Euler-method/Lambdatalk/euler-method.lambdatalk +++ b/Task/Euler-method/Lambdatalk/euler-method.lambdatalk @@ -14,14 +14,14 @@ {eulersMethod cooling 100 0 100 10} -> - 0 100 - 10 44 - 20 27.2 - 30 22.16 - 40 20.648 - 50 20.194 - 60 20.058 - 70 20.017 - 80 20.005 - 90 20.002 - 100 20 + 0 100 + 10 44 + 20 27.2 + 30 22.16 + 40 20.648 + 50 20.194 + 60 20.058 + 70 20.017 + 80 20.005 + 90 20.002 + 100 20 diff --git a/Task/Euler-method/Lua/euler-method.lua b/Task/Euler-method/Lua/euler-method.lua index bd34fd6cc1..e72469b893 100644 --- a/Task/Euler-method/Lua/euler-method.lua +++ b/Task/Euler-method/Lua/euler-method.lua @@ -10,8 +10,8 @@ NewtonCooling = function( t ) return -k * ( t - TR ) end function Euler( f, y0, n, h ) local y = y0 for x = 0, n, h do - print( "", x, y ) - y = y + h * f( y ) + print( "", x, y ) + y = y + h * f( y ) end end diff --git a/Task/Euler-method/Maple/euler-method-2.maple b/Task/Euler-method/Maple/euler-method-2.maple index 491e6ef422..3c782c1955 100644 --- a/Task/Euler-method/Maple/euler-method-2.maple +++ b/Task/Euler-method/Maple/euler-method-2.maple @@ -1,16 +1,16 @@ f := y -> (-0.07) * (y - 20): EulerMethod := proc(f, start_time, end_time, y0, h) # y0: initial value #h: step size - local cur, y, rate: - cur := start_time; - y := y0; - while cur <= end_time do - printf("%g %g\n", cur, y); - cur := cur + h; - rate := f(y); - y := y + h * rate; - end do; - return y; + local cur, y, rate: + cur := start_time; + y := y0; + while cur <= end_time do + printf("%g %g\n", cur, y); + cur := cur + h; + rate := f(y); + y := y + h * rate; + end do; + return y; end proc: # step size = 2 diff --git a/Task/Euler-method/OCaml/euler-method-1.ocaml b/Task/Euler-method/OCaml/euler-method-1.ml similarity index 100% rename from Task/Euler-method/OCaml/euler-method-1.ocaml rename to Task/Euler-method/OCaml/euler-method-1.ml diff --git a/Task/Euler-method/OCaml/euler-method-2.ocaml b/Task/Euler-method/OCaml/euler-method-2.ml similarity index 100% rename from Task/Euler-method/OCaml/euler-method-2.ocaml rename to Task/Euler-method/OCaml/euler-method-2.ml diff --git a/Task/Euler-method/Odin/euler-method.odin b/Task/Euler-method/Odin/euler-method.odin new file mode 100644 index 0000000000..b8f110cd72 --- /dev/null +++ b/Task/Euler-method/Odin/euler-method.odin @@ -0,0 +1,36 @@ +package main + +import "core:fmt" +import "core:math" + +ivp_euler ::proc(y:f32,step:i32,end:i32){ + + y:=y + t:=i32(0) + + for ;t<=end;t+=step{ + if(t%10==0){fmt.printfln("%.3f", y)} + y+=f32(step)*cooling(f32(t),y) + } +} + +cooling :: proc(t:f32,temp:f32)-> f32{ + return -0.07* (temp-20.0) +} + +analytic :: proc(){ + for t := 0; t <= 100; t += 10{ + fmt.printfln("%.3f",20+80*math.exp_f32(f32(-0.07)*f32(t))) + } +} + +main :: proc() { + fmt.println("Step: 2 Seconds") + ivp_euler(100.0, 2,100) + fmt.println("Step: 5 Seconds") + ivp_euler(100.0, 5, 100) + fmt.println("Step: 10 Seconds") + ivp_euler(100.0, 10, 100) + fmt.println("Analytic") + analytic() +} diff --git a/Task/Euler-method/Pascal/euler-method.pas b/Task/Euler-method/Pascal/euler-method.pas index 52a98641e0..598e3d480b 100644 --- a/Task/Euler-method/Pascal/euler-method.pas +++ b/Task/Euler-method/Pascal/euler-method.pas @@ -3,47 +3,47 @@ PROGRAM Euler; TYPE TNewtonCooling = FUNCTION (t: REAL) : REAL; -CONST T0 : REAL = 100.0; -CONST TR : REAL = 20.0; -CONST k : REAL = 0.07; -CONST time : INTEGER = 100; -CONST step : INTEGER = 10; -CONST dt : ARRAY[0..3] of REAL = (1.0,2.0,5.0,10.0); +CONST T0 : REAL = 100.0; +CONST TR : REAL = 20.0; +CONST k : REAL = 0.07; +CONST time : INTEGER = 100; +CONST step : INTEGER = 10; +CONST dt : ARRAY[0..3] of REAL = (1.0,2.0,5.0,10.0); -VAR i : INTEGER; +VAR i : INTEGER; FUNCTION NewtonCooling(t: REAL) : REAL; - BEGIN - NewtonCooling := -k * (t-TR); - END; - + BEGIN + NewtonCooling := -k * (t-TR); + END; + PROCEDURE Euler(F: TNewtonCooling; y, h : REAL; n: INTEGER); - VAR i: INTEGER = 0; - BEGIN - WRITE('dt=',trunc(h):2,':'); - REPEAT - IF (i mod 10 = 0) THEN WRITE(' ',y:2:3); - INC(i,trunc(h)); - y := y + h * F(y); - UNTIL (i >= n); - WRITELN; - END; + VAR i: INTEGER = 0; + BEGIN + WRITE('dt=',trunc(h):2,':'); + REPEAT + IF (i mod 10 = 0) THEN WRITE(' ',y:2:3); + INC(i,trunc(h)); + y := y + h * F(y); + UNTIL (i >= n); + WRITELN; + END; PROCEDURE Sigma; - VAR t: INTEGER = 0; - BEGIN - WRITE('Sigma:'); - REPEAT - WRITE(' ',(20 + 80 * exp(-0.07 * t)):2:3); - INC(t,step); - UNTIL (t>=time); - WRITELN; - END; + VAR t: INTEGER = 0; + BEGIN + WRITE('Sigma:'); + REPEAT + WRITE(' ',(20 + 80 * exp(-0.07 * t)):2:3); + INC(t,step); + UNTIL (t>=time); + WRITELN; + END; BEGIN - WRITELN('Newton cooling function: Analytic solution (Sigma) with 3 Euler approximations.'); - WRITELN('Time: ',0:7,10:7,20:7,30:7,40:7,50:7,60:7,70:7,80:7,90:7); - Sigma; - FOR i := 1 to 3 DO - Euler(NewtonCooling,T0,dt[i],time); + WRITELN('Newton cooling function: Analytic solution (Sigma) with 3 Euler approximations.'); + WRITELN('Time: ',0:7,10:7,20:7,30:7,40:7,50:7,60:7,70:7,80:7,90:7); + Sigma; + FOR i := 1 to 3 DO + Euler(NewtonCooling,T0,dt[i],time); END. diff --git a/Task/Euler-method/PascalABC.NET/euler-method.pas b/Task/Euler-method/PascalABC.NET/euler-method.pas new file mode 100644 index 0000000000..474986e8f7 --- /dev/null +++ b/Task/Euler-method/PascalABC.NET/euler-method.pas @@ -0,0 +1,31 @@ +procedure euler(f: (real) -> real; y0, a, b, h: real); +begin + var (t, y) := (a, y0); + write(' Step', h:3, ':'); + while t <= b do + begin + if integer(t) mod 10 = 0 then write(y:8:3); + t += h; + y += h * f(y); + end; + writeln; +end; + +procedure analytic(); +begin + write(' Time:'); + for var t := 0 to 100 step 10 do write(t:8); + writeln; + write('Analytic:'); + for var t := 0 to 100 step 10 do + write(20.0 + 80.0 * exp(-0.07 * t):8:3); + println(); +end; + +function newtoncooling(temp: real): real := -0.07 * (temp - 20); + +begin +analytic; +foreach var i in |2, 5, 10| do + euler(newtoncooling, 100.0, 0.0, 100.0, i) +end. diff --git a/Task/Euler-method/Pluto/euler-method.pluto b/Task/Euler-method/Pluto/euler-method.pluto new file mode 100644 index 0000000000..f0d8207f4e --- /dev/null +++ b/Task/Euler-method/Pluto/euler-method.pluto @@ -0,0 +1,25 @@ +local fmt = require "fmt" + +local function euler(f, y, step, finish) + fmt.write(" Step %2d: ", step) + for t = 0, finish, step do + if t % 10 == 0 then fmt.write(" %7.3f", y) end + y += step * f(y) + end + print() +end + +local function analytic() + io.write(" Time: ") + for t = 0, 100, 10 do fmt.write(" %7d", t) end + io.write("\nAnalytic: ") + for t = 0, 100, 10 do + fmt.write(" %7.3f", 20 + 80 * math.exp(-0.07 * t)) + end + print() +end + +local cooling = |temp| -> -0.07 * (temp - 20) + +analytic() +for {2, 5, 10} as i do euler(cooling, 100, i, 100) end diff --git a/Task/Euler-method/PowerShell/euler-method.psh b/Task/Euler-method/PowerShell/euler-method.ps1 similarity index 100% rename from Task/Euler-method/PowerShell/euler-method.psh rename to Task/Euler-method/PowerShell/euler-method.ps1 diff --git a/Task/Euler-method/Python/euler-method.py b/Task/Euler-method/Python/euler-method.py index 1c00e47cfe..ff0bcc8723 100644 --- a/Task/Euler-method/Python/euler-method.py +++ b/Task/Euler-method/Python/euler-method.py @@ -1,11 +1,11 @@ def euler(f,y0,a,b,h): - t,y = a,y0 - while t <= b: - print "%6.3f %6.3f" % (t,y) - t += h - y += h * f(t,y) + t,y = a,y0 + while t <= b: + print "%6.3f %6.3f" % (t,y) + t += h + y += h * f(t,y) def newtoncooling(time, temp): - return -0.07 * (temp - 20) + return -0.07 * (temp - 20) euler(newtoncooling,100,0,100,10) diff --git a/Task/Euler-method/Q/euler-method.q b/Task/Euler-method/Q/euler-method.q new file mode 100644 index 0000000000..a788e246d6 --- /dev/null +++ b/Task/Euler-method/Q/euler-method.q @@ -0,0 +1,10 @@ +t:0 +time:100 +k:-0.07 +tr:20 +sol:() +steps:10 +h:time%steps +tn:100 +while [t.5 then ix=ix+sign(x); x= x-ix; z=1 - _=1; w=1; do j=1; _= _*x/j; z= (z+_)/1; if z==w then leave; w=z - end /*j*/; if z\==0 then z= e**ix * z; return z +-- 18 Sep 2025 +include Setting + +say "EULER METHOD FOR ODE y'=-0.07(y-20)" +say version +say +call Task 0,100,2,100 +call Task 0,100,5,100 +call Task 0,100,10,100 +call Timer +exit + +Task: +-- Euler method +procedure expose Memo. +arg x0,xn,dx,y0 +say 'From' x0 'to' xn 'step' dx +say ' x Calc y True y Abs error Rel error' +x=x0; y=y0 +do until x > xn + if x//10 = 0 then + call Show x,y + y+=dx*Dy(y); x+=dx +end +say +return + +Show: +-- Display a line +procedure expose Memo. +arg xx,yy +yt=True(xx) +say Format(xx,3,0) Format(yy,3,7) Format(yt,3,7), + Left(Std(Abs(yy-yt)),9) Left(Std(Abs(yy/yt-1)),9) +return + +Dy: +-- Differential equation +procedure +arg yy +return -0.07*(yy-20) + +True: +-- Real solution +procedure expose Memo. +arg xx +return 20+(100-20)*Exp(-0.07*xx) + +include Math diff --git a/Task/Euler-method/Rebol/euler-method.rebol b/Task/Euler-method/Rebol/euler-method.rebol new file mode 100644 index 0000000000..3fbd56d1cc --- /dev/null +++ b/Task/Euler-method/Rebol/euler-method.rebol @@ -0,0 +1,34 @@ +Rebol [ + title: "Rosetta code: Euler method" + file: %Euler_method.r3 + url: https://rosettacode.org/wiki/Euler_method +] + +euler: func[ + "Euler's method for Newton's cooling law, with formatted comparison" + step [integer!] "time step in seconds" + precision [decimal!] "rounding granularity for printed numbers" +][ + print ["^/STEP:" step] + print "Time Euler Analytic" + print "-------------------------" + + ;; Initialize: + ;; b: upper time bound (seconds) — here we reuse the initial temperature value 100 + ;; y: the current Euler-approximated temperature; initial condition T(0) = 100 + b: y: 100 + for time 0 b step [ + printf [-3 " | " 9 "| "] reduce [ + time + round/to y precision + round/to (20 + (80 * exp (-0.07 * time))) precision + ] + ;; Euler step update: + ;; This applies the discrete forward Euler update using the ODE's RHS + y: y + (step * (-0.07 * (y - 20))) + ] +] +;; Run three experiments with different step sizes +euler 2 0.0001 +euler 5 0.0001 +euler 10 0.0001 diff --git a/Task/Euler-method/Rust/euler-method.rust b/Task/Euler-method/Rust/euler-method.rs similarity index 100% rename from Task/Euler-method/Rust/euler-method.rust rename to Task/Euler-method/Rust/euler-method.rs diff --git a/Task/Euler-method/SequenceL/euler-method.sequencel b/Task/Euler-method/SequenceL/euler-method.sequencel index 8c3703f0a3..c795f7cb74 100644 --- a/Task/Euler-method/SequenceL/euler-method.sequencel +++ b/Task/Euler-method/SequenceL/euler-method.sequencel @@ -6,20 +6,20 @@ TR := 20.0; k := 0.07; main(args(2)) := - let - results[i] := euler(newtonCooling, T0, 100, stringToInt(args[i]), 0, "delta_t = " ++ args[i]); - in - delimit(results, '\n'); + let + results[i] := euler(newtonCooling, T0, 100, stringToInt(args[i]), 0, "delta_t = " ++ args[i]); + in + delimit(results, '\n'); newtonCooling(t) := -k * (t - TR); euler: (float -> float) * float * int * int * int * char(1) -> char(1); euler(f, y, n, h, x, output(1)) := - let - newOutput := output ++ "\n\t" ++ intToString(x) ++ "\t" ++ floatToString(y, 3); - newY := y + h * f(y); - newX := x + h; - in - output when x > n - else - euler(f, newY, n, h, newX, newOutput); + let + newOutput := output ++ "\n\t" ++ intToString(x) ++ "\t" ++ floatToString(y, 3); + newY := y + h * f(y); + newX := x + h; + in + output when x > n + else + euler(f, newY, n, h, newX, newOutput); diff --git a/Task/Euler-method/Smalltalk/euler-method.st b/Task/Euler-method/Smalltalk/euler-method.st index 7dd18f966b..52f6dd908b 100644 --- a/Task/Euler-method/Smalltalk/euler-method.st +++ b/Task/Euler-method/Smalltalk/euler-method.st @@ -1,13 +1,13 @@ ODESolver>>eulerOf: f init: y0 from: a to: b step: h - | t y | - t := a. - y := y0. - [ t < b ] - whileTrue: [ - Transcript - show: t asString, ' ' , (y printShowingDecimalPlaces: 3); - cr. - t := t + h. - y := y + (h * (f value: t value: y)) ] + | t y | + t := a. + y := y0. + [ t < b ] + whileTrue: [ + Transcript + show: t asString, ' ' , (y printShowingDecimalPlaces: 3); + cr. + t := t + h. + y := y + (h * (f value: t value: y)) ] ODESolver new eulerOf: [:time :temp| -0.07 * (temp - 20)] init: 100 from: 0 to: 100 step: 10 diff --git a/Task/Euler-method/Tcl/euler-method-1.tcl b/Task/Euler-method/Tcl/euler-method-1.tcl index 6073ea9839..a7854e5399 100644 --- a/Task/Euler-method/Tcl/euler-method-1.tcl +++ b/Task/Euler-method/Tcl/euler-method-1.tcl @@ -2,8 +2,8 @@ proc euler {f y0 a b h} { puts "computing $f over \[$a..$b\], step $h" set y [expr {double($y0)}] for {set t [expr {double($a)}]} {$t < $b} {set t [expr {$t + $h}]} { - puts [format "%.3f\t%.3f" $t $y] - set y [expr {$y + $h * double([$f $t $y])}] + puts [format "%.3f\t%.3f" $t $y] + set y [expr {$y + $h * double([$f $t $y])}] } puts "done" } diff --git a/Task/Euler-method/XBasic/euler-method.basic b/Task/Euler-method/XBasic/euler-method.basic new file mode 100644 index 0000000000..ad06196e05 --- /dev/null +++ b/Task/Euler-method/XBasic/euler-method.basic @@ -0,0 +1,43 @@ +PROGRAM "Euclidean rhythm" +VERSION "0.0001" +IMPORT "xma" + +DECLARE FUNCTION Entry () +DECLARE FUNCTION Euler (paso) + +FUNCTION Entry () + PRINT "Time "; + tiempo! = 0.0 + DO WHILE tiempo! <= 100.1 + PRINT FORMAT$ ("#######", tiempo!); + tiempo! = tiempo! + 10.0 + LOOP + PRINT + + PRINT "Dif eq "; + tiempo! = 0.0 + DO WHILE tiempo! <= 100.1 + temperatura! = 20.0 + (100.0 - 20.0) * EXP(-0.07 * tiempo!) + PRINT FORMAT$ ("####.##", temperatura!); + tiempo! = tiempo! + 10.0 + LOOP + PRINT + + Euler(2) + Euler(5) + Euler(10) +END FUNCTION + +FUNCTION Euler (paso) + tiempo! = 0 + temperatura! = 100.0 + PRINT FORMAT$ ("Step ## ", paso); + + DO WHILE tiempo! <= 100 + IF (tiempo! MOD 10) = 0 THEN PRINT FORMAT$ ("####.##", temperatura!); + temperatura! = temperatura! + SINGLE(paso) * (-0.07 * (temperatura! - 20.0)) + tiempo! = tiempo! + paso + LOOP + PRINT +END FUNCTION +END PROGRAM diff --git a/Task/Eulers-constant-0.5772.../ALGOL-W/eulers-constant-0.5772....alg b/Task/Eulers-constant-0.5772.../ALGOL-W/eulers-constant-0.5772....alg new file mode 100644 index 0000000000..4b49f4d0c2 --- /dev/null +++ b/Task/Eulers-constant-0.5772.../ALGOL-W/eulers-constant-0.5772....alg @@ -0,0 +1,89 @@ +begin % calculate Euler's constant, translated from the XPL0 sample % + % which is translated from the C sample % + + long real A, B, H, N2, R, U, V; + long real array S ( 0 :: 1 ); + long real array B2( 0 :: 9 ); + long real Epsilon; + integer K, K2, M, N; + + Epsilon := 1'-6; + + % set output format % + i_w := 1; s_w := 0; r_w := 18; r_d := 15; r_format := "A"; + + write( "From the definition, error 3e-10" ); + N := 400; H := 1.0; + for K1 := 2 until N do H := H + 1.0 / K1; + comment Faster convergence: Negoi, 1997 ; + A := Ln( N + 0.5 + 1.0/( 24.0 * N ) ); + write( "Hn ", H ); + write( "gamma ", H - A ); write( "K = ", N ); write(); + + write( "Sweeney, 1963, error 3e-10" ); + N := 21; S( 0 ) := 0; S( 1 ) := N; + R := N; K:= 1; + while begin K := K + 1; + R := R * N / K; + S( K rem 2 ) := S( K rem 2 ) + R / K; + R > Epsilon + end + do begin end; + write( "gamma ", S( 1 ) - S( 0 ) - ln( N ) );write( "K = ", K ); write(); + + write( "Bailey, 1988" ); + N := 5; A := 1; H := 1; + N2 := 2 ** N; + R := 1; K := 1; + while begin K := K + 1; + R := R * N2 / K; + H := H + 1 / K; + B := A; A := A + R * H; + abs( B - A ) > Epsilon + end + do begin end; + A := A * N2 / Exp(N2); + write( "gamma ", A - N * Ln( 2 ) ); write( "K = ", K ); write(); + + write( "Brent-McMillan, 1980" ); + N := 13; A := -Ln( N ); + B := 1; U := A; V := B; + N2 := N * N; K2 := 0; K := 0; + while begin K2 := K2 + 2 * K + 1; + K := K + 1; + A := A * N2 / K; + B := B * N2 / K2; + A := ( A + B ) / K; + U := U + A; + V := V + B; + abs( A ) > Epsilon + end + do begin end; + write( "gamma ", U / V ); write( "K = ", K ); write(); + + write( "How Euler did it in 1735" ); + comment Bernoulli numbers with even indices; + + B2( 0 ) := 1; B2( 1 ) := 1 / 6; B2( 2 ) := -1 / 30; + B2( 3 ) := 1 / 42; B2( 4 ) := -1 / 30; B2( 5 ) := 5 / 66; + B2( 6 ) := -691 / 2730; B2( 7 ) := 7 / 6; B2( 8 ) := -3617 / 510; + B2( 9 ) := 43867 / 98; + M := 7; N := 10; + comment Nth harmonic number; + H := 1; + for K1 := 2 until N do H := H + 1 / K1; + write( "Hn ", H ); + H := H - Ln( N ); + write( " -ln ", H ); + comment Expansion C:= -digamma(1); + A := -1 / ( 2 * N ); + N2 := N * N; + R := 1; + for K1 := 1 until M do begin + R := R * N2; + A := A + B2( K1 ) / (2 * K1 * R ) + end for_K1; + write( "err ", A ); write( "gamma ", H + A ); write( "K = ", N + M ); + write(); + write( "C = 0.57721566490153286..." ); write() +end. diff --git a/Task/Eulers-constant-0.5772.../AWK/eulers-constant-0.5772....awk b/Task/Eulers-constant-0.5772.../AWK/eulers-constant-0.5772....awk new file mode 100644 index 0000000000..cb7e954b31 --- /dev/null +++ b/Task/Eulers-constant-0.5772.../AWK/eulers-constant-0.5772....awk @@ -0,0 +1,12 @@ +# syntax: GAWK -f EULERS_CONSTANT.AWK +# converted from LUA +BEGIN { + Hn = 1 + n = 10^8 + for (i=2; i<=n; i++) { + Hn += (1/i) + } + gamma = Hn - log(n) + printf("%.8f\n",gamma) + exit(0) +} diff --git a/Task/Eulers-constant-0.5772.../Ada/eulers-constant-0.5772....adb b/Task/Eulers-constant-0.5772.../Ada/eulers-constant-0.5772....adb new file mode 100644 index 0000000000..b27ada83d7 --- /dev/null +++ b/Task/Eulers-constant-0.5772.../Ada/eulers-constant-0.5772....adb @@ -0,0 +1,47 @@ +with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions; +with Ada.Numerics.Long_Elementary_Functions; use Ada.Numerics.Long_Elementary_Functions; +with Ada.Text_IO; use Ada.Text_IO; + +procedure Eulers_Constant is + + function Euler_Vacca (Iterations : Integer) return Long_Float is + Gamma : Long_Float := 1.0; + Term : Long_Float; + Power : Long_Integer; + Sign : Long_Float; + begin + Gamma := 0.5 - (1.0 / 3.0); + for I in 2 .. Iterations loop + Power := 2 ** Natural (I); + Sign := -1.0; + Term := 0.0; + for Domin in Power .. (2 * Power - 1) loop + Sign := - (Sign); + Term := Term + Sign / Long_Float (Domin); + end loop; + Gamma := Gamma + (Long_Float (I) * Term); + end loop; + return Gamma; + end Euler_Vacca; + + -- Ada Float type is IEEE 754 32-bit, giving 9 decimal digits of precision + Euler_Castellanos_Float : constant Float := + (((80.0 ** 3) + 92.0) / + (61.0 ** 4)) ** (1.0 / 6.0); + + -- Ada Long_Float type is IEEE 754 32-bit, giving 14 decimal digits of precision + Euler_Castellanos_Long_Float : constant Long_Float := + (990.0 ** 3 - 55.0 ** 3 - 79.0 ** 2 - 16.0) / + 70.0 ** 5; + + Iters : Integer; +begin + Put_Line ("Its. Vacca"); + Iters := 2; + while Iters <= 32 loop + Put_Line (Iters'Image & " " & Euler_Vacca (Iters)'Image); + Iters := Iters + 2; + end loop; + Put_Line ("Castellanos approximation for standard Float (9 digits): " & Euler_Castellanos_Float'Image); + Put_Line ("Castellanos approximation for Long Float (14 digits): " & Euler_Castellanos_Long_Float'Image); +end Eulers_Constant; diff --git a/Task/Eulers-constant-0.5772.../Delphi/eulers-constant-0.5772....delphi b/Task/Eulers-constant-0.5772.../Delphi/eulers-constant-0.5772....delphi deleted file mode 100644 index d9e8de7c73..0000000000 --- a/Task/Eulers-constant-0.5772.../Delphi/eulers-constant-0.5772....delphi +++ /dev/null @@ -1,39 +0,0 @@ -function ComputeEuler(N: int64): double; -{Compute Eurler number with N-number of iterations} -var I: integer; -var A: double; -begin -Result:=0; -for I:=1 to N-1 do - Result:=Result + 1 / I; -A:=Ln(N + 0.5 + 1/(24.0*N)); -Result:=Result-A; -end; - - - -procedure ShowEulersNumber(Memo: TMemo); -{Show Euler numbers at various levels of precision} -var Euler,G,A,Error: double; -var N: integer; -const Correct =0.57721566490153286060651209008240243104215933593992; - - procedure ShowEulerError(N: int64); - {Show Euler number and Error} - begin - Euler:=ComputeEuler(N); - Error:=Correct-Euler; - Memo.Lines.Add('N = '+FloatToStrF(N,ffNumber,18,0)); - Memo.Lines.Add('Euler='+FloatToStrF(Euler,ffFixed,18,18)); - Memo.Lines.Add('Error='+FloatToStrF(Error,ffFixed,18,18)); - Memo.Lines.Add(''); - end; - -begin -{Compute Euler number with iterations ranging 10 to 10^9} -for N:=1 to 9 do - begin - ShowEulerError(Trunc(Power(10,N))); - end; - -end; diff --git a/Task/Eulers-constant-0.5772.../Delphi/eulers-constant-0.5772....pas b/Task/Eulers-constant-0.5772.../Delphi/eulers-constant-0.5772....pas new file mode 100644 index 0000000000..3f1952a8f7 --- /dev/null +++ b/Task/Eulers-constant-0.5772.../Delphi/eulers-constant-0.5772....pas @@ -0,0 +1,39 @@ +function ComputeEuler(N: int64): double; +{Compute Eurler number with N-number of iterations} +var I: integer; +var A: double; +begin +Result:=0; +for I:=1 to N-1 do + Result:=Result + 1 / I; +A:=Ln(N + 0.5 + 1/(24.0*N)); +Result:=Result-A; +end; + + + +procedure ShowEulersNumber(Memo: TMemo); +{Show Euler numbers at various levels of precision} +var Euler,G,A,Error: double; +var N: integer; +const Correct =0.57721566490153286060651209008240243104215933593992; + + procedure ShowEulerError(N: int64); + {Show Euler number and Error} + begin + Euler:=ComputeEuler(N); + Error:=Correct-Euler; + Memo.Lines.Add('N = '+FloatToStrF(N,ffNumber,18,0)); + Memo.Lines.Add('Euler='+FloatToStrF(Euler,ffFixed,18,18)); + Memo.Lines.Add('Error='+FloatToStrF(Error,ffFixed,18,18)); + Memo.Lines.Add(''); + end; + +begin +{Compute Euler number with iterations ranging 10 to 10^9} +for N:=1 to 9 do + begin + ShowEulerError(Trunc(Power(10,N))); + end; + +end; diff --git a/Task/Eulers-constant-0.5772.../DuckDB/eulers-constant-0.5772....duckdb b/Task/Eulers-constant-0.5772.../DuckDB/eulers-constant-0.5772....duckdb new file mode 100644 index 0000000000..fd6a135180 --- /dev/null +++ b/Task/Eulers-constant-0.5772.../DuckDB/eulers-constant-0.5772....duckdb @@ -0,0 +1,21 @@ +# Bailey, 1988 +create or replace function bailey(n, eps) as ( + with recursive n2 as (select pow(2, n) as n2), + cte as ( + select 1 as k, 1.0::DOUBLE as r, 1.0::DOUBLE as h, 0.0::DOUBLE as b, 1.0::DOUBLE as a + union all + select + k + 1 as k, + r * (n2 / (k+1)) as r, + h + (1.0 / (k+1)) as h, + a as b, + a + (r * (n2 / (k+1)) * (h + (1.0 / (k+1)))) as a + from cte, n2 + where @(b - a) > eps + ), + a as (select last(a order by k) as a from cte) + select (a * n2 / exp(n2) ) - (n * ln(2)) + from a, n2 +); + +select bailey(5, 1E-6) as gamma; 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 index 343c268ced..16bd541d9a 100644 --- a/Task/Eulers-constant-0.5772.../EasyLang/eulers-constant-0.5772....easy +++ b/Task/Eulers-constant-0.5772.../EasyLang/eulers-constant-0.5772....easy @@ -6,7 +6,6 @@ fastfunc gethn n . . return hn . -e = 2.718281828459045235 n = 10e8 -numfmt 9 0 -print gethn n - log10 n / log10 e +numfmt 0 9 +print gethn n - log n 0 diff --git a/Task/Eulers-constant-0.5772.../Fortran/eulers-constant-0.5772....f b/Task/Eulers-constant-0.5772.../Fortran/eulers-constant-0.5772....f new file mode 100644 index 0000000000..868106567d --- /dev/null +++ b/Task/Eulers-constant-0.5772.../Fortran/eulers-constant-0.5772....f @@ -0,0 +1,131 @@ +program euler_constant + implicit none + ! Define constants and variables + real(16), parameter :: EULER_GAMMA = 0.57721566490153286_16 + real(16), parameter :: eps = epsilon(1.0e-6_16) + real(16) :: a, b, h, n2, r, u, v + integer :: k, k2, m, n + real(16) :: s(0:1), B2(0:9) + real(16), parameter :: eps_high = eps !1.0e-12_16 + + ! Method 1: From the definition (Negoi, 1997) + write(*, '(a)') "From the definition, err. 3e-10" + n = 400 + h = 1.0_16 + do k = 2, n + h = h + 1.0_16 / k + end do + a = log(real(n, 16) + 0.5_16 + 1.0_16 / (24.0_16 * n)) + write(*, '(a, f18.16)') "Hn ", h + write(*, '(a, f18.16, /, a, i0, /)') "gamma ", h - a, "k = ", n + write(*, '(a, f18.16, /)') "error ", abs(h - a - EULER_GAMMA) + + ! Method 2: Sweeney, 1963 + write(*, '(a)') "Sweeney, 1963, err. idem" + n = 21 + s = [0.0_16, real(n, 16)] + r = real(n, 16) + k = 1 + do + k = k + 1 + r = r * real(n, 16) / k + s(mod(k, 2)) = s(mod(k, 2)) + r / k + if (r <= eps) exit + end do + write(*, '(a, f18.16, /, a, i0, /)') "gamma ", s(1) - s(0) - log(real(n, 16_16)), "k = ", k + write(*, '(a, f18.16, /)') "error ", abs(s(1) - s(0) - log(real(n, 16)) - EULER_GAMMA) + + ! Method 3: Bailey, 1988 + write(*, '(a)') "Bailey, 1988" + n = 5 + a = 1.0_16 + h = 1.0_16 + n2 = 2.0_16 ** n + r = 1.0_16 + k = 1 + do + k = k + 1 + r = r * n2 / k + h = h + 1.0_16 / k + b = a + a = a + r * h + if (abs(b - a) <= eps) exit + end do + a = a * n2 / exp(n2) + write(*, '(a, f18.16, /, a, i0, /)') "gamma ", a - n * log(2.0_16), "k = ", k + write(*, '(a, f18.16, /)') "error ", abs(a - n * log(2.0_16) - EULER_GAMMA) + + ! Method 4: Brent-McMillan, 1980 (original) + write(*, '(a)') "Brent-McMillan, 1980 (original)" + n = 13 + a = -log(real(n, 16)) + b = 1.0_16 + u = a + v = b + n2 = real(n, 16) * n + k2 = 0 + k = 0 + do + k2 = k2 + 2 * k + 1 + k = k + 1 + a = a * n2 / k + b = b * n2 / k2 + a = (a + b) / k + u = u + a + v = v + b + if (abs(a) <= eps) exit + end do + write(*, '(a, f18.16, /, a, i0, /)') "gamma ", u / v, "k = ", k + write(*, '(a, f18.16, /)') "error ", abs(u / v - EULER_GAMMA) + + ! Method 5: Brent-McMillan, 1980 (enhanced for higher precision) + write(*, '(a)') "Brent-McMillan, 1980 (enhanced)" + n = 50 + a = -log(real(n, 16)) + b = 1.0_16 + u = a + v = b + n2 = real(n, 16) * n + k2 = 0 + k = 0 + do + k2 = k2 + 2 * k + 1 + k = k + 1 + a = a * n2 / k + b = b * n2 / k2 + a = (a + b) / k + u = u + a + v = v + b + if (abs(a) <= eps_high) exit + end do + write(*, '(a, f18.16, /, a, i0, /)') "gamma ", u / v, "k = ", k + write(*, '(a, f18.16, /)') "error ", abs(u / v - EULER_GAMMA) + + ! Method 6: Euler's method, 1735 + write(*, '(a)') "How Euler did it in 1735" + B2 = [1.0_16, 1.0_16/6, -1.0_16/30, 1.0_16/42, -1.0_16/30, & + 5.0_16/66, -691.0_16/2730, 7.0_16/6, -3617.0_16/510, 43867.0_16/798] + m = 7 + if (m > 9) stop + n = 10 + h = 1.0_16 + do k = 2, n + h = h + 1.0_16 / k + end do + write(*, '(a, f18.16)') "Hn ", h + h = h - log(real(n, 16)) + write(*, '(a, f18.16)') " -ln ", h + a = -1.0_16 / (2.0_16 * n) + n2 = real(n, 16) * n + r = 1.0_16 + do k = 1, m + r = r * n2 + a = a + B2(k) / (2.0_16 * k * r) + end do + write(*, '(a, f18.16, /, a, f18.16, /, a, i0)') & + "err ", a, "gamma ", h + a, "k = ", n + m + write(*, '(a, f18.16, /)') "error ", abs(h + a - EULER_GAMMA) + + ! Reference value + write(*, '(a, f18.16, /)') "C = ", EULER_GAMMA +end program euler_constant diff --git a/Task/Eulers-constant-0.5772.../Java/eulers-constant-0.5772....java b/Task/Eulers-constant-0.5772.../Java/eulers-constant-0.5772....java index dbab8b5182..ab644548fd 100644 --- a/Task/Eulers-constant-0.5772.../Java/eulers-constant-0.5772....java +++ b/Task/Eulers-constant-0.5772.../Java/eulers-constant-0.5772....java @@ -5,20 +5,20 @@ */ public class EulerConstant { - public static void main(String[] args) { - System.out.println(gamma(1_000_000)); - } + public static void main(String[] args) { + System.out.println(gamma(1_000_000)); + } private static double gamma(int N) { - double gamma = 0.0; - - for ( int n = 1; n <= N; n++ ) { - gamma += 1.0 / n; - } - - gamma -= Math.log(N) + 1.0 / ( 2 * N ); - - return gamma; - } - + double gamma = 0.0; + + for ( int n = 1; n <= N; n++ ) { + gamma += 1.0 / n; + } + + gamma -= Math.log(N) + 1.0 / ( 2 * N ); + + return gamma; + } + } diff --git a/Task/Eulers-constant-0.5772.../JavaScript/eulers-constant-0.5772....js b/Task/Eulers-constant-0.5772.../JavaScript/eulers-constant-0.5772....js new file mode 100644 index 0000000000..42188fb06e --- /dev/null +++ b/Task/Eulers-constant-0.5772.../JavaScript/eulers-constant-0.5772....js @@ -0,0 +1,45 @@ +function ByVaccaSeries(numTerms) { + // this method is simple but converges slowly + // calculate gamma by: + // 1 * (1/2 - 1/3) + + // 2 * (1/4 - 1/5 + 1/6 - 1/7) + + // 3 * (1/8 - 1/9 + 1/10 - 1/11 + 1/12 - 1/13 + 1/14 - 1/15) + + // 4 * ( . . . ) + + // . . . + let gamma = 0; + let next = 4; + for (let numerator = 1; numerator < numTerms; ++numerator) { + let delta = 0; + for (let denominator = next / 2; denominator < next; denominator += 2) { + // calculate terms two at a time + delta += 1.0 / denominator - 1.0 / (denominator + 1); + } + gamma += numerator * delta; + next *= 2; + } + return gamma; +} +// based on the C entry +function ByEulersMethod() { + //Bernoulli numbers with even indices + const B2 = [1.0, 1.0 / 6, -1.0 / 30, 1.0 / 42, -1.0 / 30, + 5.0 / 66, -691.0 / 2730, 7.0 / 6]; + const n = 10; + //n-th harmonic number + const h = (() => // immediately invoked function expression + { + let sum = 1; + for (let k = 2; k <= n; k++) { sum += 1.0 / k; } + return sum - Math.log(n); + })(); + //expansion C = -digamma(1) + let a = -1.0 / (2 * n); + let r = 1; + for (let k = 1; k < B2.length; k++) { + r *= n * n; + a += B2[k] / (2 * k * r); + } + return h + a; +} +console.log("Vacca series: " + ByVaccaSeries(32).toPrecision(16)); +console.log("Eulers method: " + ByEulersMethod().toPrecision(16)); diff --git a/Task/Eulers-constant-0.5772.../Julia/eulers-constant-0.5772....julia b/Task/Eulers-constant-0.5772.../Julia/eulers-constant-0.5772....jl similarity index 100% rename from Task/Eulers-constant-0.5772.../Julia/eulers-constant-0.5772....julia rename to Task/Eulers-constant-0.5772.../Julia/eulers-constant-0.5772....jl diff --git a/Task/Eulers-constant-0.5772.../PascalABC.NET/eulers-constant-0.5772....pas b/Task/Eulers-constant-0.5772.../PascalABC.NET/eulers-constant-0.5772....pas new file mode 100644 index 0000000000..d0df6f507a --- /dev/null +++ b/Task/Eulers-constant-0.5772.../PascalABC.NET/eulers-constant-0.5772....pas @@ -0,0 +1,9 @@ +const + n = 1_000_000; + +begin + var result := 1.0; + for var i := 2 to n do + result += 1 / i; + writeln(result - ln(n)); +end. diff --git a/Task/Eulers-constant-0.5772.../Phix/eulers-constant-0.5772...-1.phix b/Task/Eulers-constant-0.5772.../Phix/eulers-constant-0.5772...-1.phix index 72fb81b799..1840979093 100644 --- a/Task/Eulers-constant-0.5772.../Phix/eulers-constant-0.5772...-1.phix +++ b/Task/Eulers-constant-0.5772.../Phix/eulers-constant-0.5772...-1.phix @@ -1,6 +1,4 @@ -(phixonline)--> - -- demo\rosetta\Eulers_constant.exw - with javascript_semantics - constant C = sum(sq_div(1,tagset(1e6)))-log(1e6) - printf(1,"gamma %.12f (max 12d.p. of accuracy)\n",C) - - without js -- no mpfr_get_d_2exp() in mpfr.js as yet - requires("1.0.2") -- mpfr_get_d_2exp(), mpfr_addmul_si() - include mpfr.e - mpfr u, v, k2; - integer e, e10, e2 - atom f +without js -- no mpfr_get_d_2exp() in mpfr.js as yet +requires("1.0.2") -- mpfr_get_d_2exp(), mpfr_addmul_si() +include mpfr.e +mpfr u, v, k2; +integer e, e10, e2 +atom f - //log(x/y) with the Taylor series for atanh(x-y/x+y) - procedure ln(mpfr s, integer x, y) - mpfr d = u, q = v; - assert((x-y)==1) - mpfr_set_si(s, x+y) - mpfr_si_div(s, 1, s) // s = 1 / (x + y) - mpfr_mul(k2, s, s) // k2 = s * s - mpfr_set(d, s) - integer k = 1 - while true do - k += 2; - mpfr_mul(d, d, k2) // d *= k2 - mpfr_div_si(q, d, k) // q = d / k - mpfr_add(s, s, q) // s += q - {f,e} = mpfr_get_d_2exp(q) - if abs(e)>=e2 then exit end if - end while - mpfr_mul_si(s, s, 2) //s *= 2 - end procedure +//log(x/y) with the Taylor series for atanh(x-y/x+y) +procedure ln(mpfr s, integer x, y) + mpfr d = u, q = v; + assert((x-y)==1) + mpfr_set_si(s, x+y) + mpfr_si_div(s, 1, s) // s = 1 / (x + y) + mpfr_mul(k2, s, s) // k2 = s * s + mpfr_set(d, s) + integer k = 1 + while true do + k += 2; + mpfr_mul(d, d, k2) // d *= k2 + mpfr_div_si(q, d, k) // q = d / k + mpfr_add(s, s, q) // s += q + {f,e} = mpfr_get_d_2exp(q) + if abs(e)>=e2 then exit end if + end while + mpfr_mul_si(s, s, 2) //s *= 2 +end procedure - mpfr a, b - integer k, - n = 60, -- (required precision in decimal dp *6/10) - n2, - r = 41, - s = 30, - t = 18; +mpfr a, b +integer k, + n = 60, -- (required precision in decimal dp *6/10) + n2, + r = 41, + s = 30, + t = 18; - // n = 2^i * 3^j * 5^k +// n = 2^i * 3^j * 5^k - // log(n) = r * log(16/15) + s * log(25/24) + t * log(81/80) +// log(n) = r * log(16/15) + s * log(25/24) + t * log(81/80) - // solve linear system for r, s, t - // 4 -3 -4| i - // -1 -1 4| j - // -1 2 -1| k +// solve linear system for r, s, t +// 4 -3 -4| i +// -1 -1 4| j +// -1 2 -1| k - //decimal precision - e10 = floor(n/0.6) - //binary precision - e2 = floor((1 + e10) / 0.30103) +//decimal precision +e10 = floor(n/0.6) +//binary precision +e2 = floor((1 + e10) / 0.30103) - mpfr_set_default_precision(e2) - {a, b, u, v, k2} = mpfr_inits(5) +mpfr_set_default_precision(e2) +{a, b, u, v, k2} = mpfr_inits(5) - //Compute log terms - ln(b, 16, 15) mpfr_mul_si(a, b, r) // a = r * b - ln(b, 25, 24) mpfr_addmul_si(a, b, s) // a += s * b - ln(b, 81, 80) mpfr_addmul_si(a, b, t) // a += t * b +//Compute log terms +ln(b, 16, 15) mpfr_mul_si(a, b, r) // a = r * b +ln(b, 25, 24) mpfr_addmul_si(a, b, s) // a += s * b +ln(b, 81, 80) mpfr_addmul_si(a, b, t) // a += t * b - mpfr_neg(a, a) // a = -a - mpfr_set_si(b, 1) // b = 1 - mpfr_set (u, a) - mpfr_set (v, b) +mpfr_neg(a, a) // a = -a +mpfr_set_si(b, 1) // b = 1 +mpfr_set (u, a) +mpfr_set (v, b) - k = 0; - n2 = n * n; - mpfr_set_si(k2, 0) // k2 = k * k (as below) - while true do - mpfr_add_si(k2, k2, k*2+1) // k2 += 2k + 1 - k += 1; +k = 0; +n2 = n * n; +mpfr_set_si(k2, 0) // k2 = k * k (as below) +while true do + mpfr_add_si(k2, k2, k*2+1) // k2 += 2k + 1 + k += 1; - mpfr_div(b, b, k2) - mpfr_mul_si(b, b, n2) // b = b * n2 / k2 + mpfr_div(b, b, k2) + mpfr_mul_si(b, b, n2) // b = b * n2 / k2 - mpfr_div_si(a, a, k) - mpfr_mul_si(a, a, n2) - mpfr_add (a, a, b) - mpfr_div_si(a, a, k) // a = (a * n2 / k + b) / k + mpfr_div_si(a, a, k) + mpfr_mul_si(a, a, n2) + mpfr_add (a, a, b) + mpfr_div_si(a, a, k) // a = (a * n2 / k + b) / k - mpfr_add(u, u, a) // u += a - mpfr_add(v, v, b) // v += b + mpfr_add(u, u, a) // u += a + mpfr_add(v, v, b) // v += b - {f,e} = mpfr_get_d_2exp (a) - if abs(e)>=e2 then exit end if - end while + {f,e} = mpfr_get_d_2exp (a) + if abs(e)>=e2 then exit end if +end while - mpfr_div(u, u, v) - string su = mpfr_get_fixed(u,e10) - printf(1,"gamma %s (maxerr. 1e-%d)\n", {su, e10}) - - without js -- no mpfr_const_euler() in mpfr.js as yet - requires("1.0.1") -- mpfr_const_euler() - include mpfr.e - mpfr gamma = mpfr_init(0,-100) - mpfr_const_euler(gamma) - printf(1,"gamma %s (mpfr_const_euler)\n",{mpfr_get_fixed(gamma,100)}) - - with javascript_semantics - include builtins\complex.e - complex i = complex_new(0,1), - res = complex_add(complex_exp(complex_mul(PI,i)),1) - ?complex_sprint(res,both:=true) - ?complex_sprint(complex_round(res,1e16),true) - ?complex_sprint(complex_round(res,1e15),true) - - with javascript_semantics - procedure reduce(string s) - constant rules = {{"-1+1","0"}, - {"-1+0","-1"}, - {"i*0","0"}, - {"sin(pi)","0"}, - {"cos(pi)","-1"}, - {"exp(i*pi)","cos(pi)+i*sin(pi)"}} - string t = s - sequence seen = {} -- (be safe and avoid infinite loops) - while not find(t,seen) -- "" re-treading - and length(t)<10000 do -- "" ever-growing - seen = append(seen,t) - bool found = false - for i=1 to length(rules) do - string {r,e} = rules[i] - if match(r,t) then - found = true - t = substitute(t,r,e) - end if - end for - if not found then exit end if - printf(1,"%s = %s\n",{s,t}) - s = repeat(' ',length(s)) - end while - end procedure +with javascript_semantics +constant rules = {{"-1+1","0"}, + {"-1+0","-1"}, + {"i*0","0"}, + {"sin(pi)","0"}, + {"cos(pi)","-1"}, + {"exp(i*pi)","cos(pi)+i*sin(pi)"}} - reduce("exp(i*pi)+1") - - with javascript_semantics - constant MAX = 250 +with javascript_semantics +constant MAX = 250 - constant p5 = new_dict(), - sum2 = new_dict() +constant p5 = new_dict(), + sum2 = new_dict() - atom t0 = time() - for i=1 to MAX do - atom i5 = power(i,5) - setd(i5,i,p5) - for j=1 to i-1 do - atom j5 = power(j,5) - setd(j5+i5,{j,i},sum2) - end for - end for +atom t0 = time() +for i=1 to MAX do + atom i5 = power(i,5) + setd(i5,i,p5) + for j=1 to i-1 do + atom j5 = power(j,5) + setd(j5+i5,{i,j},sum2) + end for +end for - ?time()-t0 +printf(1,"created %d + %d dictionary entries (%gs)\n", + {dict_size(p5),dict_size(sum2),time()-t0}) - function forsum2(object s, object data, object p) - if p<=s then return 0 end if - integer k = getd_index(p-s,sum2) - if k!=NULL then - ?getd(p,p5)&data&getd_by_index(k,sum2) - return 0 -- (show one solution per p) - end if - return 1 - end function +bool found = false +function forsum2(object s, data, p) + if p<=s then return 0 end if + integer k = getd_index(p-s,sum2) + if k!=NULL then + printf(1,"%d^5 + %d^5 + %d^5 +%d^5 = %d^5 (%gs)\n", + getd_by_index(k,sum2)&data&getd(p,p5)&(time()-t0)) + found = true + return 0 -- (show one solution per p) + end if + return 1 +end function - function forp5(object key, object /*data*/, object /*user_data*/) - traverse_dict(forsum2,key,sum2) - return 1 - end function +function forp5(object key, /*data*/, /*user_data*/) + traverse_dict(forsum2,key,sum2) + return not found +end function - traverse_dict(forp5,0,p5) - - ?time()-t0 - - global function choose(integer n, k) - atom res = 1 - for i=1 to k do - res = (res*(n-i+1))/i - end for - return res - end function - - ?choose(5,3) - - with javascript_semantics - include builtins\mpfr.e - sequence tests = {{5,3},{100,50},{60,30},{1200,120}} - mpz r = mpz_init() - for i=1 to length(tests) do - integer {n,k} = tests[i] - mpz_bin_uiui(r,n,k) - ?mpz_get_str(r) - end for - ) + [ i 1+ / ] ] is binomial ( n n --> n ) 5 3 binomial echo diff --git a/Task/Evaluate-binomial-coefficients/Rust/evaluate-binomial-coefficients-1.rust b/Task/Evaluate-binomial-coefficients/Rust/evaluate-binomial-coefficients-1.rs similarity index 100% rename from Task/Evaluate-binomial-coefficients/Rust/evaluate-binomial-coefficients-1.rust rename to Task/Evaluate-binomial-coefficients/Rust/evaluate-binomial-coefficients-1.rs diff --git a/Task/Evaluate-binomial-coefficients/Rust/evaluate-binomial-coefficients-2.rust b/Task/Evaluate-binomial-coefficients/Rust/evaluate-binomial-coefficients-2.rs similarity index 100% rename from Task/Evaluate-binomial-coefficients/Rust/evaluate-binomial-coefficients-2.rust rename to Task/Evaluate-binomial-coefficients/Rust/evaluate-binomial-coefficients-2.rs diff --git a/Task/Evaluate-binomial-coefficients/Scheme/evaluate-binomial-coefficients-1.ss b/Task/Evaluate-binomial-coefficients/Scheme/evaluate-binomial-coefficients-1.scm similarity index 100% rename from Task/Evaluate-binomial-coefficients/Scheme/evaluate-binomial-coefficients-1.ss rename to Task/Evaluate-binomial-coefficients/Scheme/evaluate-binomial-coefficients-1.scm diff --git a/Task/Evaluate-binomial-coefficients/Scheme/evaluate-binomial-coefficients-2.ss b/Task/Evaluate-binomial-coefficients/Scheme/evaluate-binomial-coefficients-2.scm similarity index 100% rename from Task/Evaluate-binomial-coefficients/Scheme/evaluate-binomial-coefficients-2.ss rename to Task/Evaluate-binomial-coefficients/Scheme/evaluate-binomial-coefficients-2.scm diff --git a/Task/Evaluate-binomial-coefficients/True-BASIC/evaluate-binomial-coefficients-1.basic b/Task/Evaluate-binomial-coefficients/True-BASIC/evaluate-binomial-coefficients-1.basic new file mode 100644 index 0000000000..1e8fe03440 --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/True-BASIC/evaluate-binomial-coefficients-1.basic @@ -0,0 +1,35 @@ +FUNCTION factorial(n) + IF n < 1 THEN LET factorial = 1 + + LET product = 1 + FOR i = 2 TO n + LET product = product*i + NEXT i + + LET factorial = product +END FUNCTION + +FUNCTION binomial(n, k) + ! Special cases + IF k = 0 OR k = n THEN LET binomial = 1 + IF k < 0 OR k > n THEN LET binomial = 0 + + ! For efficiency, we use the smallest value of k or (n-k) + IF k > n-k THEN LET k = n-k + LET product = 1 + + FOR i = 1 TO k + LET product = product*(n-k+i)/i + NEXT i + + LET binomial = INT(product+0.5) +END FUNCTION + +FOR n = 0 TO 14 + FOR k = 0 TO n + PRINT USING " ####": binomial(n,k); + NEXT k + PRINT +NEXT n + +END diff --git a/Task/Evaluate-binomial-coefficients/True-BASIC/evaluate-binomial-coefficients-2.basic b/Task/Evaluate-binomial-coefficients/True-BASIC/evaluate-binomial-coefficients-2.basic new file mode 100644 index 0000000000..f3d149d7c5 --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/True-BASIC/evaluate-binomial-coefficients-2.basic @@ -0,0 +1,25 @@ + REM PASCAL'S TRIANGLE + LET N=0 + 10 LET K=0 + 20 GOSUB 30 + PRINT B," " + LET K=K+1 + IF K<=N THEN GOTO 20 + PRINT "" + LET N=N+1 + IF N<=10 THEN GOTO 10 + END + 30 REM BINOMIAL + IF K=0 THEN GOTO 50 + IF K=N THEN GOTO 50 + LET P=1 + LET I=1 + 40 LET T=N-K+I + LET P=P*T/I + LET I=I+1 + IF I<=K THEN GOTO 40 + LET B=P + RETURN + 50 LET B=1 + RETURN + diff --git a/Task/Evaluate-binomial-coefficients/VBScript/evaluate-binomial-coefficients.vb b/Task/Evaluate-binomial-coefficients/VBScript/evaluate-binomial-coefficients.vbs similarity index 100% rename from Task/Evaluate-binomial-coefficients/VBScript/evaluate-binomial-coefficients.vb rename to Task/Evaluate-binomial-coefficients/VBScript/evaluate-binomial-coefficients.vbs diff --git a/Task/Evaluate-binomial-coefficients/Yabasic/evaluate-binomial-coefficients.basic b/Task/Evaluate-binomial-coefficients/Yabasic/evaluate-binomial-coefficients.basic new file mode 100644 index 0000000000..b4066edf86 --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/Yabasic/evaluate-binomial-coefficients.basic @@ -0,0 +1,33 @@ +for n = 0 to 14 + for k = 0 to n + print binomial(n, k) using "####"; + next k + print +next n +end + +sub factorial(n) + local product, i + + if n < 1 return 1 + + product = 1 + for i = 2 to n + product = product * i + next + + return product +end sub + +sub binomial(n, k) + local product, i + + if n < 0 or k < 0 or n <= k return 1 + + product = 1 + for i = n - k + 1 to n + product = product * i + next + + return int(product / factorial(k)) +end sub diff --git a/Task/Even-or-odd/ALGOL-60/even-or-odd.alg b/Task/Even-or-odd/ALGOL-60/even-or-odd.alg new file mode 100644 index 0000000000..314105fd32 --- /dev/null +++ b/Task/Even-or-odd/ALGOL-60/even-or-odd.alg @@ -0,0 +1,21 @@ +begin + +integer i; + +boolean procedure even(n); + value n; integer n; +begin + even := (n = entier(n/2) * 2); +end; + +comment - exercise the function; +for i := 1 step 3 until 12 do + begin + outinteger(1,i); + if even(i) then + outstring(1,"is even\n") + else + outstring(1,"is odd\n"); + end; + +end diff --git a/Task/Even-or-odd/Ada/even-or-odd.ada b/Task/Even-or-odd/Ada/even-or-odd.adb similarity index 100% rename from Task/Even-or-odd/Ada/even-or-odd.ada rename to Task/Even-or-odd/Ada/even-or-odd.adb diff --git a/Task/Even-or-odd/Adina/even-or-odd-1.adina b/Task/Even-or-odd/Adina/even-or-odd-1.adina new file mode 100644 index 0000000000..07565c1f09 --- /dev/null +++ b/Task/Even-or-odd/Adina/even-or-odd-1.adina @@ -0,0 +1,4 @@ +чётное число = + число % 2 == 0 +нечётное число = + число % 2 == 1 diff --git a/Task/Even-or-odd/Adina/even-or-odd-2.adina b/Task/Even-or-odd/Adina/even-or-odd-2.adina new file mode 100644 index 0000000000..e700193dbc --- /dev/null +++ b/Task/Even-or-odd/Adina/even-or-odd-2.adina @@ -0,0 +1,4 @@ +even x = + x % 2 == 0 +odd x = + x % 2 == 1 diff --git a/Task/Even-or-odd/ArkScript/even-or-odd.ark b/Task/Even-or-odd/ArkScript/even-or-odd.ark new file mode 100644 index 0000000000..76058b09e1 --- /dev/null +++ b/Task/Even-or-odd/ArkScript/even-or-odd.ark @@ -0,0 +1,5 @@ +(let is_even (fun (i) + (= 0 (mod i 2)))) + +(let is_odd (fun (i) + (= 1 (mod i 2)))) diff --git a/Task/Even-or-odd/Arturo/even-or-odd.arturo b/Task/Even-or-odd/Arturo/even-or-odd.arturo index 7dfd05748b..eb282edf42 100644 --- a/Task/Even-or-odd/Arturo/even-or-odd.arturo +++ b/Task/Even-or-odd/Arturo/even-or-odd.arturo @@ -1,4 +1,4 @@ loop (neg 5)..5 [x][ - if? even? x -> print [pad to :string x 4 ": even"] - else -> print [pad to :string x 4 ": odd"] + switch even? x -> print [pad to :string x 4 ": even"] + -> print [pad to :string x 4 ": odd"] ] diff --git a/Task/Even-or-odd/Ballerina/even-or-odd.ballerina b/Task/Even-or-odd/Ballerina/even-or-odd.ballerina new file mode 100644 index 0000000000..28dfdbd94a --- /dev/null +++ b/Task/Even-or-odd/Ballerina/even-or-odd.ballerina @@ -0,0 +1,13 @@ +import ballerina/io; + +function isEven(int n) returns boolean { + return n % 2 == 0; +} + +public function main() { + int i = -3; + io:println(`isEven(${i}): ${isEven(i)}`); + foreach int t in -2...4 { + io:println(`isEven(${t}): ${isEven(t)}`); + } +} diff --git a/Task/Even-or-odd/Batch-File/even-or-odd.bat b/Task/Even-or-odd/Batch-File/even-or-odd.bat index 808359977b..4f48361e73 100644 --- a/Task/Even-or-odd/Batch-File/even-or-odd.bat +++ b/Task/Even-or-odd/Batch-File/even-or-odd.bat @@ -1,14 +1,12 @@ @echo off +setlocal set /p i=Insert number: ::bitwise and set /a "test1=%i%&1" -::divide last character by 2 -set /a test2=%i:~-1%/2 - ::modulo -set /a test3=%i% %% 2 +set /a test2=%i% %% 2 set test pause>nul diff --git a/Task/Even-or-odd/COBOL/even-or-odd.cobol b/Task/Even-or-odd/COBOL/even-or-odd.cob similarity index 100% rename from Task/Even-or-odd/COBOL/even-or-odd.cobol rename to Task/Even-or-odd/COBOL/even-or-odd.cob diff --git a/Task/Even-or-odd/Crystal/even-or-odd.cr b/Task/Even-or-odd/Crystal/even-or-odd.cr new file mode 100644 index 0000000000..fbc489e27d --- /dev/null +++ b/Task/Even-or-odd/Crystal/even-or-odd.cr @@ -0,0 +1,40 @@ +#Using bitwise shift + def isEven_bShift(n) + n == ((n >> 1) << 1) + end + def isOdd_bShift(n) + n != ((n >> 1) << 1) + end +#Using modulo operator + def isEven_mod(n) + (n % 2) == 0 + end + def isOdd_mod(n) + (n % 2) != 0 + end +# Using bitwise "and" + def isEven_bAnd(n) + (n & 1) == 0 + end + def isOdd_bAnd(n) + (n & 1) != 0 + end +# Using integer predicates + def isEven_even(n) + n.even? + end + def isOdd_odd(n) + n.odd? + end + +puts isEven_bShift(7) +puts isOdd_bShift(7) + +puts isEven_mod(12) +puts isOdd_mod(12) + +puts isEven_bAnd(21) +puts isOdd_bAnd(21) + +puts isEven_even(32) +puts isOdd_odd(32) diff --git a/Task/Even-or-odd/Crystal/even-or-odd.crystal b/Task/Even-or-odd/Crystal/even-or-odd.crystal deleted file mode 100644 index b214424476..0000000000 --- a/Task/Even-or-odd/Crystal/even-or-odd.crystal +++ /dev/null @@ -1,30 +0,0 @@ -#Using bitwise shift - def isEven_bShift(n) - n == ((n >> 1) << 1) - end - def isOdd_bShift(n) - n != ((n >> 1) << 1) - end -#Using modulo operator - def isEven_mod(n) - (n % 2) == 0 - end - def isOdd_mod(n) - (n % 2) != 0 - end -# Using bitwise "and" - def isEven_bAnd(n) - (n & 1) == 0 - end - def isOdd_bAnd(n) - (n & 1) != 0 - end - -puts isEven_bShift(7) -puts isOdd_bShift(7) - -puts isEven_mod(12) -puts isOdd_mod(12) - -puts isEven_bAnd(21) -puts isOdd_bAnd(21) diff --git a/Task/Even-or-odd/Delphi/even-or-odd.delphi b/Task/Even-or-odd/Delphi/even-or-odd.pas similarity index 100% rename from Task/Even-or-odd/Delphi/even-or-odd.delphi rename to Task/Even-or-odd/Delphi/even-or-odd.pas diff --git a/Task/Even-or-odd/DuckDB/even-or-odd-1.duckdb b/Task/Even-or-odd/DuckDB/even-or-odd-1.duckdb new file mode 100644 index 0000000000..fc23a91ef4 --- /dev/null +++ b/Task/Even-or-odd/DuckDB/even-or-odd-1.duckdb @@ -0,0 +1,3 @@ +create or replace function evenp(i) as ( + i = trunc(i) and i%2 = 0 +); diff --git a/Task/Even-or-odd/DuckDB/even-or-odd-2.duckdb b/Task/Even-or-odd/DuckDB/even-or-odd-2.duckdb new file mode 100644 index 0000000000..f59859511f --- /dev/null +++ b/Task/Even-or-odd/DuckDB/even-or-odd-2.duckdb @@ -0,0 +1 @@ +select i, evenp(i), evenp(i::DOUBLE + 0.1) from range(-1,3) _(i); diff --git a/Task/Even-or-odd/EMal/even-or-odd.emal b/Task/Even-or-odd/EMal/even-or-odd.emal index 0292abacd4..ee2b7e1cd8 100644 --- a/Task/Even-or-odd/EMal/even-or-odd.emal +++ b/Task/Even-or-odd/EMal/even-or-odd.emal @@ -1,20 +1,16 @@ -List evenCheckers = fun[ - logic by int i do return i % 2 == 0 end, - logic by int i do return i & 1 == 0 end] -List oddCheckers = fun[ - logic by int i do return i % 2 != 0 end, - logic by int i do return i & 1 == 1 end] -writeLine("integer".padStart(10, " ") + "|is_even" + "|is_odd |") +List evenCheckers ← fun[ + int.is_odd + |> bool.to_string + |> io.println + + 2 + |> int.is_even + |> bool.to_string + |> io.println +} diff --git a/Task/Even-or-odd/Julia/even-or-odd.julia b/Task/Even-or-odd/Julia/even-or-odd.jl similarity index 100% rename from Task/Even-or-odd/Julia/even-or-odd.julia rename to Task/Even-or-odd/Julia/even-or-odd.jl diff --git a/Task/Even-or-odd/Kotlin/even-or-odd.kotlin b/Task/Even-or-odd/Kotlin/even-or-odd.kts similarity index 100% rename from Task/Even-or-odd/Kotlin/even-or-odd.kotlin rename to Task/Even-or-odd/Kotlin/even-or-odd.kts diff --git a/Task/Even-or-odd/Nom/even-or-odd.num b/Task/Even-or-odd/Nom/even-or-odd.num new file mode 100644 index 0000000000..b67372cd5e --- /dev/null +++ b/Task/Even-or-odd/Nom/even-or-odd.num @@ -0,0 +1,8 @@ +# Least signficant digit method + read; + ![:space:] { + whilenot [:space:]; + [0-9] { E"1",E"3",E"5",E"7",E"9" { add " *ODD!*"; } } + print; clear; + } + [:space:] { while [:space:]; print; clear; } diff --git a/Task/Even-or-odd/Nu/even-or-odd.nu b/Task/Even-or-odd/Nu/even-or-odd.nu new file mode 100644 index 0000000000..df29fd8256 --- /dev/null +++ b/Task/Even-or-odd/Nu/even-or-odd.nu @@ -0,0 +1,7 @@ +def is-even [x: int] { + ($x bit-and 1) == 0 +} + +def is-odd [x: int] { + ($x bit-and 1) == 1 +} diff --git a/Task/Even-or-odd/OCaml/even-or-odd-1.ocaml b/Task/Even-or-odd/OCaml/even-or-odd-1.ml similarity index 100% rename from Task/Even-or-odd/OCaml/even-or-odd-1.ocaml rename to Task/Even-or-odd/OCaml/even-or-odd-1.ml diff --git a/Task/Even-or-odd/OCaml/even-or-odd-2.ocaml b/Task/Even-or-odd/OCaml/even-or-odd-2.ml similarity index 100% rename from Task/Even-or-odd/OCaml/even-or-odd-2.ocaml rename to Task/Even-or-odd/OCaml/even-or-odd-2.ml diff --git a/Task/Even-or-odd/OCaml/even-or-odd-3.ocaml b/Task/Even-or-odd/OCaml/even-or-odd-3.ml similarity index 100% rename from Task/Even-or-odd/OCaml/even-or-odd-3.ocaml rename to Task/Even-or-odd/OCaml/even-or-odd-3.ml diff --git a/Task/Even-or-odd/Oberon/even-or-odd.oberon b/Task/Even-or-odd/Oberon/even-or-odd.oberon deleted file mode 100644 index e010e2ed06..0000000000 --- a/Task/Even-or-odd/Oberon/even-or-odd.oberon +++ /dev/null @@ -1,21 +0,0 @@ -MODULE EvenOrOdd; -IMPORT - S := SYSTEM, - Out; -VAR - x: INTEGER; - s: SET; - -BEGIN - x := 10;Out.Int(x,0); - IF ODD(x) THEN Out.String(" odd") ELSE Out.String(" even") END; - Out.Ln; - - x := 11;s := S.VAL(SET,LONG(x));Out.Int(x,0); - IF 0 IN s THEN Out.String(" odd") ELSE Out.String(" even") END; - Out.Ln; - - x := 12;Out.Int(x,0); - IF x MOD 2 # 0 THEN Out.String(" odd") ELSE Out.String(" even") END; - Out.Ln -END EvenOrOdd. diff --git a/Task/Even-or-odd/PascalABC.NET/even-or-odd.pas b/Task/Even-or-odd/PascalABC.NET/even-or-odd.pas new file mode 100644 index 0000000000..d3cc8e5417 --- /dev/null +++ b/Task/Even-or-odd/PascalABC.NET/even-or-odd.pas @@ -0,0 +1,14 @@ +function IsOddRemainder(x: integer) := x mod 2 <> 0; + +function IsEvenRemainder(x: integer) := x mod 2 = 0; + +function IsOddBitwise(x: integer) := x and 1 = 1; + +function IsEvenBitwise(x: integer) := x and 1 = 0; + +begin + var x := 3; + Println(x.IsEven,x.IsOdd); // Standard Predicates + Println(IsEvenRemainder(x),IsOddRemainder(x)); + Println(IsEvenBitwise(x),IsOddBitwise(x)); +end. diff --git a/Task/Even-or-odd/Pluto/even-or-odd.pluto b/Task/Even-or-odd/Pluto/even-or-odd.pluto new file mode 100644 index 0000000000..670ade3ec5 --- /dev/null +++ b/Task/Even-or-odd/Pluto/even-or-odd.pluto @@ -0,0 +1,4 @@ +local n = 123 +if n % 2 == 0 do + print('even') +else print('odd') end diff --git a/Task/Even-or-odd/PowerShell/even-or-odd-1.psh b/Task/Even-or-odd/PowerShell/even-or-odd-1.ps1 similarity index 100% rename from Task/Even-or-odd/PowerShell/even-or-odd-1.psh rename to Task/Even-or-odd/PowerShell/even-or-odd-1.ps1 diff --git a/Task/Even-or-odd/PowerShell/even-or-odd-2.psh b/Task/Even-or-odd/PowerShell/even-or-odd-2.ps1 similarity index 100% rename from Task/Even-or-odd/PowerShell/even-or-odd-2.psh rename to Task/Even-or-odd/PowerShell/even-or-odd-2.ps1 diff --git a/Task/Even-or-odd/PowerShell/even-or-odd-3.psh b/Task/Even-or-odd/PowerShell/even-or-odd-3.ps1 similarity index 100% rename from Task/Even-or-odd/PowerShell/even-or-odd-3.psh rename to Task/Even-or-odd/PowerShell/even-or-odd-3.ps1 diff --git a/Task/Even-or-odd/ReScript/even-or-odd.re b/Task/Even-or-odd/ReScript/even-or-odd.res similarity index 100% rename from Task/Even-or-odd/ReScript/even-or-odd.re rename to Task/Even-or-odd/ReScript/even-or-odd.res diff --git a/Task/Even-or-odd/Rust/even-or-odd-1.rust b/Task/Even-or-odd/Rust/even-or-odd-1.rs similarity index 100% rename from Task/Even-or-odd/Rust/even-or-odd-1.rust rename to Task/Even-or-odd/Rust/even-or-odd-1.rs diff --git a/Task/Even-or-odd/Rust/even-or-odd-2.rust b/Task/Even-or-odd/Rust/even-or-odd-2.rs similarity index 100% rename from Task/Even-or-odd/Rust/even-or-odd-2.rust rename to Task/Even-or-odd/Rust/even-or-odd-2.rs diff --git a/Task/Even-or-odd/Rye/even-or-odd.rye b/Task/Even-or-odd/Rye/even-or-odd.rye new file mode 100644 index 0000000000..c1822096c6 --- /dev/null +++ b/Task/Even-or-odd/Rye/even-or-odd.rye @@ -0,0 +1,2 @@ +print is-even 2 +print is-odd 2 diff --git a/Task/Even-or-odd/Scheme/even-or-odd.ss b/Task/Even-or-odd/Scheme/even-or-odd.scm similarity index 100% rename from Task/Even-or-odd/Scheme/even-or-odd.ss rename to Task/Even-or-odd/Scheme/even-or-odd.scm diff --git a/Task/Even-or-odd/VBScript/even-or-odd.vb b/Task/Even-or-odd/VBScript/even-or-odd.vbs similarity index 100% rename from Task/Even-or-odd/VBScript/even-or-odd.vb rename to Task/Even-or-odd/VBScript/even-or-odd.vbs diff --git a/Task/Even-or-odd/YAMLScript/even-or-odd.ys b/Task/Even-or-odd/YAMLScript/even-or-odd.ys new file mode 100644 index 0000000000..36ee519cd2 --- /dev/null +++ b/Task/Even-or-odd/YAMLScript/even-or-odd.ys @@ -0,0 +1,7 @@ +!YS-v0 + +defn main(*xs): + each x xs: + if x:even?: + say: "$x is even" + say: "$x is odd" diff --git a/Task/Events/Ada/events-1.ada b/Task/Events/Ada/events-1.adb similarity index 100% rename from Task/Events/Ada/events-1.ada rename to Task/Events/Ada/events-1.adb diff --git a/Task/Events/Ada/events-2.ada b/Task/Events/Ada/events-2.adb similarity index 100% rename from Task/Events/Ada/events-2.ada rename to Task/Events/Ada/events-2.adb diff --git a/Task/Events/Ada/events-3.ada b/Task/Events/Ada/events-3.adb similarity index 100% rename from Task/Events/Ada/events-3.ada rename to Task/Events/Ada/events-3.adb diff --git a/Task/Events/Delphi/events.delphi b/Task/Events/Delphi/events.pas similarity index 100% rename from Task/Events/Delphi/events.delphi rename to Task/Events/Delphi/events.pas diff --git a/Task/Events/EasyLang/events.easy b/Task/Events/EasyLang/events.easy index 0206f41f44..18092d262e 100644 --- a/Task/Events/EasyLang/events.easy +++ b/Task/Events/EasyLang/events.easy @@ -1,10 +1,8 @@ on timer - move randomf * 100 randomf * 100 - circle 2 + gcircle randomf * 100 randomf * 100 2 timer 1 . on mouse_down - move mouse_x mouse_y - circle 2 + gcircle mouse_x mouse_y 2 . timer 0 diff --git a/Task/Events/Elixir/events.elixir b/Task/Events/Elixir/events.ex similarity index 100% rename from Task/Events/Elixir/events.elixir rename to Task/Events/Elixir/events.ex diff --git a/Task/Events/Java/events.java b/Task/Events/Java/events.java new file mode 100644 index 0000000000..67effa5bba --- /dev/null +++ b/Task/Events/Java/events.java @@ -0,0 +1,18 @@ +import java.util.Timer; +import java.util.TimerTask; +import java.util.Date; + +public class Main { + public static void main(String[] args) { + Timer timer = new Timer(); + TimerTask task = new TimerTask() { + @Override + public void run() { + System.out.println(new Date()); + timer.cancel(); + } + }; + System.out.println(new Date()); + timer.schedule(task, 1000); + } +} diff --git a/Task/Events/Julia/events.julia b/Task/Events/Julia/events.jl similarity index 100% rename from Task/Events/Julia/events.julia rename to Task/Events/Julia/events.jl diff --git a/Task/Events/PascalABC.NET/events.pas b/Task/Events/PascalABC.NET/events.pas new file mode 100644 index 0000000000..7f24ba7e63 --- /dev/null +++ b/Task/Events/PascalABC.NET/events.pas @@ -0,0 +1,13 @@ +procedure OnElapsed(sender: object; eventArgs: System.Timers.ElapsedEventArgs); +begin + Writeln(eventArgs.SignalTime); + system.Timers.Timer(sender).Stop; +end; + +begin + var timer := System.Timers.Timer.Create(1000); + timer.Elapsed += OnElapsed; + Writeln(DateTime.Now); + timer.Start; + Console.ReadLine; +end. diff --git a/Task/Events/PowerShell/events.psh b/Task/Events/PowerShell/events.ps1 similarity index 100% rename from Task/Events/PowerShell/events.psh rename to Task/Events/PowerShell/events.ps1 diff --git a/Task/Events/Rust/events.rust b/Task/Events/Rust/events.rs similarity index 100% rename from Task/Events/Rust/events.rust rename to Task/Events/Rust/events.rs diff --git a/Task/Evolutionary-algorithm/8080-Assembly/evolutionary-algorithm.8080 b/Task/Evolutionary-algorithm/8080-Assembly/evolutionary-algorithm.8080 index dafadfb1b4..bebda07f74 100644 --- a/Task/Evolutionary-algorithm/8080-Assembly/evolutionary-algorithm.8080 +++ b/Task/Evolutionary-algorithm/8080-Assembly/evolutionary-algorithm.8080 @@ -1,162 +1,162 @@ -MRATE: equ 26 ; Chance of mutation (MRATE/256) -COPIES: equ 100 ; Amount of copies to make -fname1: equ 5Dh ; First filename on command line (used for RNG seed) -fname2: equ 6Dh ; Second filename (also used for RNG seed) - org 100h - ;;; Make random seed from the two CP/M 'filenames' - lxi b,rnddat - lxi h,fname1 - xra a - call seed ; First four bytes from fn1 make X - call seed ; Second four bytes from fn1 make A - mvi l,fname2 - call seed ; First four bytes from fn2 make B - call seed ; Second four bytes from fn2 make C - ;;; Create the first parent (random string) - lxi h,parent - mvi e,tgtsz-1 -genchr: call rndchr ; Get random character - mov m,a ; Store it - inx h - dcr e - jnz genchr - mvi m,'$' ; CP/M string terminator - ;;; Main loop -loop: lxi d,parent - push d - call puts ; Print current parent - pop h ; Calculate fitness - call fitnes - xra a ; If it is 0, all characters match, - ora d - rz ; So we stop. - lxi h,kids ; Otherwise, set HL to start of children, - mvi a,0FFh ; Initialize maximum fitness value - sta maxfit - mvi a,COPIES ; Initialize copy counter - sta copies - ;;; Make copies -copy: push h ; Store the place where the copy will go - call mutcpy ; Make a mutated copy of the parent - pop h ; Get the place where the copy went - push h ; But keep it on the stack - call fitnes ; Calculate the fitness of that copy - pop h ; Get place where copy went - lda maxfit ; Get current best fitness - cmp d ; Compare to fitness of current copy - jc next ; If it wasn't better, next copy - shld maxptr ; If it was better, store pointer - mov a,d - sta maxfit ; And new max fitness -next: lxi b,tgtsz ; Get place for next copy - dad b - xchg ; Keep in DE - lxi h,copies - dcr m ; Any copies left to make? - xchg - jnz copy ; Then make another copy - lhld maxptr ; Otherwise, get location of copy with best fitness - lxi b,parent ; Make that the new parent -pcopy: mov a,m ; Get character from copy - inx h - stax b ; Store into location of parent - inx b - cpi '$' ; Check for string terminator - jnz pcopy ; If it isn't, copy next character - jmp loop ; Otherwise, mutate new parent - ;;; Make a copy of the parent, mutate it, and store it at [HL]. -mutcpy: lxi b,parent -mcloop: ldax b ; Get current character - inx b - mov m,a ; Write it to new location - inx h - cpi '$' ; Was it the string terminator? - rz ; Then stop - call rand ; Otherwise, get random value - cpi MRATE ; Should we mutate this character? - jnc mcloop ; If not, just copy next character - call rndchr ; Otherwise, get a random character - dcx h ; And store it instead of the character we had - mov m,a - inx h - jmp mcloop - ;;; Calculate fitness of candidate under [HL], fitness is - ;;; returned in D. Fitness is "inverted", i.e. a fitness of 0 - ;;; means everything matches. -fitnes: lxi b,target - lxi d,tgtsz ; E=counter, D=fitness -floop: dcr e ; Done yet? - rz ; If so, return. - ldax b ; Get target character - inx b - cmp m ; Compare to current character - inx h - jz floop ; If they match, don't do anything - inr d ; If they don't match, count this - jmp floop - ;;; Generate a random uppercase letter, or a space - ;;; Return in A, other registers preserved -rndchr: call rand ; Get a random value - ani 31 ; from 0 to 31 - cpi 28 ; If 28 or higher, - jnc rndchr ; get another value - adi 'A' ; Make uppercase letter - cpi 'Z'+1 ; If the result is 'Z' or lower, - rc ; then return it, - mvi a,' ' ; otherwise return a space - ret - ;;; Load 4 bytes from [HL] and use them, plus A, as part of seed - ;;; in [BC] -seed: mvi e,4 ; 4 bytes -sloop: xra m - inx h - dcr e - jnz sloop - stax b - inx b - ret - ;;; Random number generator using XABC algorithm -rand: push h - lxi h,rnddat - inr m ; X++ - mov a,m ; X - inx h - xra m ; ^ C - inx h - xra m ; ^ A - mov m,a ; -> A - inx h - add m ; + B - mov m,a ; -> B - rar ; >>1 (ish) - dcx h - xra m ; ^ A - dcx h - add m ; + C - mov m,a ; -> C - pop h - ret - ;;; Print string to console using CP/M, saving all registers -puts: push h - push d - push b - push psw - mvi c,9 ; CP/M print string - call 5 - lxi d,nl ; Print a newline as well - mvi c,9 - call 5 - pop b - pop d - pop h - pop psw - ret -nl: db 13,10,'$' -target: db 'METHINKS IT IS LIKE A WEASEL$' -tgtsz: equ $-target -rnddat: ds 4 ; RNG state -copies: ds 1 ; Copies left to make -maxfit: ds 1 ; Best fitness seen -maxptr: ds 2 ; Pointer to copy with best fitness -parent: equ $ ; Store current parent here -kids: equ $+tgtsz ; Store mutated copies here +MRATE: equ 26 ; Chance of mutation (MRATE/256) +COPIES: equ 100 ; Amount of copies to make +fname1: equ 5Dh ; First filename on command line (used for RNG seed) +fname2: equ 6Dh ; Second filename (also used for RNG seed) + org 100h + ;;; Make random seed from the two CP/M 'filenames' + lxi b,rnddat + lxi h,fname1 + xra a + call seed ; First four bytes from fn1 make X + call seed ; Second four bytes from fn1 make A + mvi l,fname2 + call seed ; First four bytes from fn2 make B + call seed ; Second four bytes from fn2 make C + ;;; Create the first parent (random string) + lxi h,parent + mvi e,tgtsz-1 +genchr: call rndchr ; Get random character + mov m,a ; Store it + inx h + dcr e + jnz genchr + mvi m,'$' ; CP/M string terminator + ;;; Main loop +loop: lxi d,parent + push d + call puts ; Print current parent + pop h ; Calculate fitness + call fitnes + xra a ; If it is 0, all characters match, + ora d + rz ; So we stop. + lxi h,kids ; Otherwise, set HL to start of children, + mvi a,0FFh ; Initialize maximum fitness value + sta maxfit + mvi a,COPIES ; Initialize copy counter + sta copies + ;;; Make copies +copy: push h ; Store the place where the copy will go + call mutcpy ; Make a mutated copy of the parent + pop h ; Get the place where the copy went + push h ; But keep it on the stack + call fitnes ; Calculate the fitness of that copy + pop h ; Get place where copy went + lda maxfit ; Get current best fitness + cmp d ; Compare to fitness of current copy + jc next ; If it wasn't better, next copy + shld maxptr ; If it was better, store pointer + mov a,d + sta maxfit ; And new max fitness +next: lxi b,tgtsz ; Get place for next copy + dad b + xchg ; Keep in DE + lxi h,copies + dcr m ; Any copies left to make? + xchg + jnz copy ; Then make another copy + lhld maxptr ; Otherwise, get location of copy with best fitness + lxi b,parent ; Make that the new parent +pcopy: mov a,m ; Get character from copy + inx h + stax b ; Store into location of parent + inx b + cpi '$' ; Check for string terminator + jnz pcopy ; If it isn't, copy next character + jmp loop ; Otherwise, mutate new parent + ;;; Make a copy of the parent, mutate it, and store it at [HL]. +mutcpy: lxi b,parent +mcloop: ldax b ; Get current character + inx b + mov m,a ; Write it to new location + inx h + cpi '$' ; Was it the string terminator? + rz ; Then stop + call rand ; Otherwise, get random value + cpi MRATE ; Should we mutate this character? + jnc mcloop ; If not, just copy next character + call rndchr ; Otherwise, get a random character + dcx h ; And store it instead of the character we had + mov m,a + inx h + jmp mcloop + ;;; Calculate fitness of candidate under [HL], fitness is + ;;; returned in D. Fitness is "inverted", i.e. a fitness of 0 + ;;; means everything matches. +fitnes: lxi b,target + lxi d,tgtsz ; E=counter, D=fitness +floop: dcr e ; Done yet? + rz ; If so, return. + ldax b ; Get target character + inx b + cmp m ; Compare to current character + inx h + jz floop ; If they match, don't do anything + inr d ; If they don't match, count this + jmp floop + ;;; Generate a random uppercase letter, or a space + ;;; Return in A, other registers preserved +rndchr: call rand ; Get a random value + ani 31 ; from 0 to 31 + cpi 28 ; If 28 or higher, + jnc rndchr ; get another value + adi 'A' ; Make uppercase letter + cpi 'Z'+1 ; If the result is 'Z' or lower, + rc ; then return it, + mvi a,' ' ; otherwise return a space + ret + ;;; Load 4 bytes from [HL] and use them, plus A, as part of seed + ;;; in [BC] +seed: mvi e,4 ; 4 bytes +sloop: xra m + inx h + dcr e + jnz sloop + stax b + inx b + ret + ;;; Random number generator using XABC algorithm +rand: push h + lxi h,rnddat + inr m ; X++ + mov a,m ; X + inx h + xra m ; ^ C + inx h + xra m ; ^ A + mov m,a ; -> A + inx h + add m ; + B + mov m,a ; -> B + rar ; >>1 (ish) + dcx h + xra m ; ^ A + dcx h + add m ; + C + mov m,a ; -> C + pop h + ret + ;;; Print string to console using CP/M, saving all registers +puts: push h + push d + push b + push psw + mvi c,9 ; CP/M print string + call 5 + lxi d,nl ; Print a newline as well + mvi c,9 + call 5 + pop b + pop d + pop h + pop psw + ret +nl: db 13,10,'$' +target: db 'METHINKS IT IS LIKE A WEASEL$' +tgtsz: equ $-target +rnddat: ds 4 ; RNG state +copies: ds 1 ; Copies left to make +maxfit: ds 1 ; Best fitness seen +maxptr: ds 2 ; Pointer to copy with best fitness +parent: equ $ ; Store current parent here +kids: equ $+tgtsz ; Store mutated copies here diff --git a/Task/Evolutionary-algorithm/8086-Assembly/evolutionary-algorithm.8086 b/Task/Evolutionary-algorithm/8086-Assembly/evolutionary-algorithm.8086 index 9b3c1c704f..e38567385b 100644 --- a/Task/Evolutionary-algorithm/8086-Assembly/evolutionary-algorithm.8086 +++ b/Task/Evolutionary-algorithm/8086-Assembly/evolutionary-algorithm.8086 @@ -1,123 +1,123 @@ - bits 16 - cpu 8086 -MRATE: equ 26 ; Mutation rate (MRATE/256) -COPIES: equ 100 ; Amount of copies to make -gettim: equ 02Ch ; MS-DOS get time function -pstr: equ 9 ; MS-DOS print string -section .text - org 100h - ;;; Use MS-DOS time to set random seed - mov ah,gettim - int 21h - mov [rnddat],cx - mov [rnddat+2],dx - ;;; Make first parent (random characters) - mov di,parent - mov cx,target.size-1 -getchr: call rndchr ; Get random character - stosb ; Store in parent - loop getchr - mov al,'$' ; Write string terminator - stosb - ;;; Main loop. -loop: mov bx,parent ; Print current parent - mov dx,bx - call puts - call fitnes ; Check fitness - test cl,cl ; If zero, we're done - jnz nxmut ; If not, do another mutation - ret ; Quit to DOS -nxmut: mov dl,0FFh ; DL = best fitness yet - mov di,kids ; Set DI to start of memory for children - mov ch,COPIES ; CH = amount of copies to make - xor bp,bp - ;;; Make copy, mutate, and test fitness -copy: mov bx,di ; Let BX = where next copy will go - call mutcpy ; Make the copy (and adjust DI) - call fitnes ; Check fitness - cmp cl,dl ; Is it better than the previous best one? - ja next ; If not, just do the next one, - mov dl,cl ; Otherwise, this is now the best one - lea bp,[di-target.size] ; Store a pointer to it in BP -next: dec ch ; One copy less - jnz copy ; Make another copy if we need to - mov si,bp ; We're done, the best child becomes - mov di,parent ; the parent for the next generation - mov cx,target.size - rep movsb - jmp loop ; Next generation - ;;; Make copy of parent, mutating as we go, and store at [DI] -mutcpy: mov si,parent -.loop: lodsb ; Get byte from parent - stosb ; Store in copy - cmp al,'$' ; Is it '$'? - je .out ; Then we're done - call rand ; Otherwise, should we mutate? - cmp al,MRATE - ja .loop ; If not, do next character - call rndchr ; But if so, get random character, - mov [di-1],al ; and overwrite the current character. - jmp .loop ; Then do the next character. -.out: ret - ;;; Get fitness of character in [BX] -fitnes: mov si,target - xor cl,cl ; Fitness -.loop: lodsb ; Get target character - cmp al,'$' ; Done? - je .out ; Then stop - cmp al,[bx] ; Equal to character under [BX]? - lahf ; Keep flags - inc bx ; Increment BX - sahf ; Restore flags (was al=[bx]?) - je .loop ; If equal, do next character - inc cx ; Otherwise, count this as a mismatch - jmp .loop -.out: ret - ;;; Generate random character, [A-Z] or space. -rndchr: call rand ; Get random number - and al,31 ; Lower five bits - cmp al,27 ; One of 27 characters? - jae rndchr ; If not, get new random number - add al,'A' ; Make uppercase letter - cmp al,'Z' ; More than 'Z'? - jbe .out ; If not, it's OK - mov al,' ' ; Otherwise, give a space -.out: ret - ;;; Random number generator using XABC algorithm - ;;; Returns random byte in AL -rand: push cx - push dx - mov cx,[rnddat] ; CH=X CL=A - mov dx,[rnddat+2] ; DH=B DL=C - inc ch ; X++ - xor cl,ch ; A ^= X - xor cl,dl ; A ^= C - add dh,cl ; B += A - mov al,dh ; C' = B - shr al,1 ; C' >>= 1 - xor al,cl ; C' ^= A - add al,dl ; C' += C - mov dl,al ; C = C' - mov [rnddat],cx - mov [rnddat+2],dx - pop dx - pop cx - ret - ;;; Print string in DX, plus a newline, saving registers -puts: push ax - push dx - mov ah,pstr - int 21h - mov dx,nl - int 21h - pop dx - pop ax - ret -section .data -nl: db 13,10,'$' -target: db 'METHINKS IT IS LIKE A WEASEL$' -.size: equ $-target -section .bss -rnddat: resb 4 ; RNG state -parent: resb target.size ; Place to store current parent -kids: resb COPIES*target.size ; Place to store children + bits 16 + cpu 8086 +MRATE: equ 26 ; Mutation rate (MRATE/256) +COPIES: equ 100 ; Amount of copies to make +gettim: equ 02Ch ; MS-DOS get time function +pstr: equ 9 ; MS-DOS print string +section .text + org 100h + ;;; Use MS-DOS time to set random seed + mov ah,gettim + int 21h + mov [rnddat],cx + mov [rnddat+2],dx + ;;; Make first parent (random characters) + mov di,parent + mov cx,target.size-1 +getchr: call rndchr ; Get random character + stosb ; Store in parent + loop getchr + mov al,'$' ; Write string terminator + stosb + ;;; Main loop. +loop: mov bx,parent ; Print current parent + mov dx,bx + call puts + call fitnes ; Check fitness + test cl,cl ; If zero, we're done + jnz nxmut ; If not, do another mutation + ret ; Quit to DOS +nxmut: mov dl,0FFh ; DL = best fitness yet + mov di,kids ; Set DI to start of memory for children + mov ch,COPIES ; CH = amount of copies to make + xor bp,bp + ;;; Make copy, mutate, and test fitness +copy: mov bx,di ; Let BX = where next copy will go + call mutcpy ; Make the copy (and adjust DI) + call fitnes ; Check fitness + cmp cl,dl ; Is it better than the previous best one? + ja next ; If not, just do the next one, + mov dl,cl ; Otherwise, this is now the best one + lea bp,[di-target.size] ; Store a pointer to it in BP +next: dec ch ; One copy less + jnz copy ; Make another copy if we need to + mov si,bp ; We're done, the best child becomes + mov di,parent ; the parent for the next generation + mov cx,target.size + rep movsb + jmp loop ; Next generation + ;;; Make copy of parent, mutating as we go, and store at [DI] +mutcpy: mov si,parent +.loop: lodsb ; Get byte from parent + stosb ; Store in copy + cmp al,'$' ; Is it '$'? + je .out ; Then we're done + call rand ; Otherwise, should we mutate? + cmp al,MRATE + ja .loop ; If not, do next character + call rndchr ; But if so, get random character, + mov [di-1],al ; and overwrite the current character. + jmp .loop ; Then do the next character. +.out: ret + ;;; Get fitness of character in [BX] +fitnes: mov si,target + xor cl,cl ; Fitness +.loop: lodsb ; Get target character + cmp al,'$' ; Done? + je .out ; Then stop + cmp al,[bx] ; Equal to character under [BX]? + lahf ; Keep flags + inc bx ; Increment BX + sahf ; Restore flags (was al=[bx]?) + je .loop ; If equal, do next character + inc cx ; Otherwise, count this as a mismatch + jmp .loop +.out: ret + ;;; Generate random character, [A-Z] or space. +rndchr: call rand ; Get random number + and al,31 ; Lower five bits + cmp al,27 ; One of 27 characters? + jae rndchr ; If not, get new random number + add al,'A' ; Make uppercase letter + cmp al,'Z' ; More than 'Z'? + jbe .out ; If not, it's OK + mov al,' ' ; Otherwise, give a space +.out: ret + ;;; Random number generator using XABC algorithm + ;;; Returns random byte in AL +rand: push cx + push dx + mov cx,[rnddat] ; CH=X CL=A + mov dx,[rnddat+2] ; DH=B DL=C + inc ch ; X++ + xor cl,ch ; A ^= X + xor cl,dl ; A ^= C + add dh,cl ; B += A + mov al,dh ; C' = B + shr al,1 ; C' >>= 1 + xor al,cl ; C' ^= A + add al,dl ; C' += C + mov dl,al ; C = C' + mov [rnddat],cx + mov [rnddat+2],dx + pop dx + pop cx + ret + ;;; Print string in DX, plus a newline, saving registers +puts: push ax + push dx + mov ah,pstr + int 21h + mov dx,nl + int 21h + pop dx + pop ax + ret +section .data +nl: db 13,10,'$' +target: db 'METHINKS IT IS LIKE A WEASEL$' +.size: equ $-target +section .bss +rnddat: resb 4 ; RNG state +parent: resb target.size ; Place to store current parent +kids: resb COPIES*target.size ; Place to store children diff --git a/Task/Evolutionary-algorithm/Ada/evolutionary-algorithm.ada b/Task/Evolutionary-algorithm/Ada/evolutionary-algorithm.adb similarity index 100% rename from Task/Evolutionary-algorithm/Ada/evolutionary-algorithm.ada rename to Task/Evolutionary-algorithm/Ada/evolutionary-algorithm.adb diff --git a/Task/Evolutionary-algorithm/Arturo/evolutionary-algorithm.arturo b/Task/Evolutionary-algorithm/Arturo/evolutionary-algorithm.arturo index 06f157c7f5..a816314b35 100644 --- a/Task/Evolutionary-algorithm/Arturo/evolutionary-algorithm.arturo +++ b/Task/Evolutionary-algorithm/Arturo/evolutionary-algorithm.arturo @@ -1,5 +1,5 @@ target: "METHINKS IT IS LIKE A WEASEL" -alphabet: [` `] ++ @`A`..`Z` +alphabet: [' '] ++ @'A'..'Z' p: 0.05 c: 100 diff --git a/Task/Evolutionary-algorithm/AutoHotkey/evolutionary-algorithm.ahk b/Task/Evolutionary-algorithm/AutoHotkey/evolutionary-algorithm.ahk index 003524e349..f38f1ef32d 100644 --- a/Task/Evolutionary-algorithm/AutoHotkey/evolutionary-algorithm.ahk +++ b/Task/Evolutionary-algorithm/AutoHotkey/evolutionary-algorithm.ahk @@ -2,55 +2,55 @@ output := "" target := "METHINKS IT IS LIKE A WEASEL" targetLen := StrLen(target) Loop, 26 - possibilities_%A_Index% := Chr(A_Index+64) ; A-Z + possibilities_%A_Index% := Chr(A_Index+64) ; A-Z possibilities_27 := " " C := 100 parent := "" Loop, %targetLen% { - Random, randomNum, 1, 27 + Random, randomNum, 1, 27 parent .= possibilities_%randomNum% } Loop, { - If (target = parent) - Break - If (Mod(A_Index,10) = 0) - output .= A_Index ": " parent ", fitness: " fitness(parent, target) "`n" - bestFit := 0 - Loop, %C% - If ((fitness := fitness(spawn := mutate(parent), target)) > bestFit) - bestSpawn := spawn , bestFit := fitness - parent := bestFit > fitness(parent, target) ? bestSpawn : parent - iter := A_Index + If (target = parent) + Break + If (Mod(A_Index,10) = 0) + output .= A_Index ": " parent ", fitness: " fitness(parent, target) "`n" + bestFit := 0 + Loop, %C% + If ((fitness := fitness(spawn := mutate(parent), target)) > bestFit) + bestSpawn := spawn , bestFit := fitness + parent := bestFit > fitness(parent, target) ? bestSpawn : parent + iter := A_Index } output .= parent ", " iter MsgBox, % output ExitApp mutate(parent) { - local output, replaceChar, newChar - output := "" - Loop, %targetLen% - { - Random, replaceChar, 0, 9 - If (replaceChar != 0) - output .= SubStr(parent, A_Index, 1) - else - { - Random, newChar, 1, 27 - output .= possibilities_%newChar% - } - } - Return output + local output, replaceChar, newChar + output := "" + Loop, %targetLen% + { + Random, replaceChar, 0, 9 + If (replaceChar != 0) + output .= SubStr(parent, A_Index, 1) + else + { + Random, newChar, 1, 27 + output .= possibilities_%newChar% + } + } + Return output } fitness(string, target) { - totalFit := 0 - Loop, % StrLen(string) - If (SubStr(string, A_Index, 1) = SubStr(target, A_Index, 1)) - totalFit++ - Return totalFit + totalFit := 0 + Loop, % StrLen(string) + If (SubStr(string, A_Index, 1) = SubStr(target, A_Index, 1)) + totalFit++ + Return totalFit } diff --git a/Task/Evolutionary-algorithm/C/evolutionary-algorithm-1.c b/Task/Evolutionary-algorithm/C/evolutionary-algorithm-1.c index 1cf726bc37..682c8e6ae6 100644 --- a/Task/Evolutionary-algorithm/C/evolutionary-algorithm-1.c +++ b/Task/Evolutionary-algorithm/C/evolutionary-algorithm-1.c @@ -12,56 +12,56 @@ const char tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ "; /* returns random integer from 0 to n - 1 */ int irand(int n) { - int r, rand_max = RAND_MAX - (RAND_MAX % n); - while((r = rand()) >= rand_max); - return r / (rand_max / n); + int r, rand_max = RAND_MAX - (RAND_MAX % n); + while((r = rand()) >= rand_max); + return r / (rand_max / n); } /* number of different chars between a and b */ int unfitness(const char *a, const char *b) { - int i, sum = 0; - for (i = 0; a[i]; i++) - sum += (a[i] != b[i]); - return sum; + int i, sum = 0; + for (i = 0; a[i]; i++) + sum += (a[i] != b[i]); + return sum; } /* each char of b has 1/MUTATE chance of differing from a */ void mutate(const char *a, char *b) { - int i; - for (i = 0; a[i]; i++) - b[i] = irand(MUTATE) ? a[i] : tbl[irand(CHOICE)]; + int i; + for (i = 0; a[i]; i++) + b[i] = irand(MUTATE) ? a[i] : tbl[irand(CHOICE)]; - b[i] = '\0'; + b[i] = '\0'; } int main() { - int i, best_i, unfit, best, iters = 0; - char specimen[COPIES][sizeof(target) / sizeof(char)]; + int i, best_i, unfit, best, iters = 0; + char specimen[COPIES][sizeof(target) / sizeof(char)]; - /* init rand string */ - for (i = 0; target[i]; i++) - specimen[0][i] = tbl[irand(CHOICE)]; - specimen[0][i] = 0; + /* init rand string */ + for (i = 0; target[i]; i++) + specimen[0][i] = tbl[irand(CHOICE)]; + specimen[0][i] = 0; - do { - for (i = 1; i < COPIES; i++) - mutate(specimen[0], specimen[i]); + do { + for (i = 1; i < COPIES; i++) + mutate(specimen[0], specimen[i]); - /* find best fitting string */ - for (best_i = i = 0; i < COPIES; i++) { - unfit = unfitness(target, specimen[i]); - if(unfit < best || !i) { - best = unfit; - best_i = i; - } - } + /* find best fitting string */ + for (best_i = i = 0; i < COPIES; i++) { + unfit = unfitness(target, specimen[i]); + if(unfit < best || !i) { + best = unfit; + best_i = i; + } + } - if (best_i) strcpy(specimen[0], specimen[best_i]); - printf("iter %d, score %d: %s\n", iters++, best, specimen[0]); - } while (best); + if (best_i) strcpy(specimen[0], specimen[best_i]); + printf("iter %d, score %d: %s\n", iters++, best, specimen[0]); + } while (best); - return 0; + return 0; } diff --git a/Task/Evolutionary-algorithm/COBOL/evolutionary-algorithm.cobol b/Task/Evolutionary-algorithm/COBOL/evolutionary-algorithm.cob similarity index 100% rename from Task/Evolutionary-algorithm/COBOL/evolutionary-algorithm.cobol rename to Task/Evolutionary-algorithm/COBOL/evolutionary-algorithm.cob diff --git a/Task/Evolutionary-algorithm/Ceylon/evolutionary-algorithm.ceylon b/Task/Evolutionary-algorithm/Ceylon/evolutionary-algorithm.ceylon index 2c501ca07d..4ff54da5dd 100644 --- a/Task/Evolutionary-algorithm/Ceylon/evolutionary-algorithm.ceylon +++ b/Task/Evolutionary-algorithm/Ceylon/evolutionary-algorithm.ceylon @@ -1,49 +1,49 @@ import ceylon.random { - - DefaultRandom + + DefaultRandom } shared void run() { - - value mutationRate = 0.05; - value childrenPerGeneration = 100; - value target = "METHINKS IT IS LIKE A WEASEL"; - value alphabet = {' ', *('A'..'Z')}; - value random = DefaultRandom(); - - value randomLetter => random.nextElement(alphabet); - - function fitness(String a, String b) => - count {for([c1, c2] in zipPairs(a, b)) c1 == c2}; - - function mutate(String string) => - String { - for(letter in string) - if(random.nextFloat() < mutationRate) - then randomLetter - else letter - }; - - function makeCopies(String string) => - {for(i in 1..childrenPerGeneration) mutate(string)}; - - function chooseFittest(String+ children) => - children - .map((String element) => element->fitness(element, target)) - .max(increasingItem) - .key; - - variable value parent = String {for(i in 1..target.size) randomLetter}; - variable value generationCount = 0; - function display() => print("``generationCount``: ``parent``"); - - display(); - while(parent != target) { - parent = chooseFittest(parent, *makeCopies(parent)); - generationCount++; - display(); - } - - print("mutated into target in ``generationCount`` generations!"); - + + value mutationRate = 0.05; + value childrenPerGeneration = 100; + value target = "METHINKS IT IS LIKE A WEASEL"; + value alphabet = {' ', *('A'..'Z')}; + value random = DefaultRandom(); + + value randomLetter => random.nextElement(alphabet); + + function fitness(String a, String b) => + count {for([c1, c2] in zipPairs(a, b)) c1 == c2}; + + function mutate(String string) => + String { + for(letter in string) + if(random.nextFloat() < mutationRate) + then randomLetter + else letter + }; + + function makeCopies(String string) => + {for(i in 1..childrenPerGeneration) mutate(string)}; + + function chooseFittest(String+ children) => + children + .map((String element) => element->fitness(element, target)) + .max(increasingItem) + .key; + + variable value parent = String {for(i in 1..target.size) randomLetter}; + variable value generationCount = 0; + function display() => print("``generationCount``: ``parent``"); + + display(); + while(parent != target) { + parent = chooseFittest(parent, *makeCopies(parent)); + generationCount++; + display(); + } + + print("mutated into target in ``generationCount`` generations!"); + } diff --git a/Task/Evolutionary-algorithm/Common-Lisp/evolutionary-algorithm-2.lisp b/Task/Evolutionary-algorithm/Common-Lisp/evolutionary-algorithm-2.lisp index 0d38dbc62d..838aa4eaa5 100644 --- a/Task/Evolutionary-algorithm/Common-Lisp/evolutionary-algorithm-2.lisp +++ b/Task/Evolutionary-algorithm/Common-Lisp/evolutionary-algorithm-2.lisp @@ -1,23 +1,23 @@ (defun unfit (s1 s2) (loop for a across s1 - for b across s2 count(char/= a b))) + for b across s2 count(char/= a b))) (defun mutate (str alp n) ; n: number of chars to mutate (let ((out (copy-seq str))) (dotimes (i n) (setf (char out (random (length str))) - (char alp (random (length alp))))) + (char alp (random (length alp))))) out)) (defun evolve (changes alpha target) (loop for gen from 1 - with f2 with s2 - with str = (mutate target alpha 100) - with fit = (unfit target str) - while (plusp fit) do - (setf s2 (mutate str alpha changes) - f2 (unfit target s2)) - (when (> fit f2) - (setf str s2 fit f2) - (format t "~5d: ~a (~d)~%" gen str fit)))) + with f2 with s2 + with str = (mutate target alpha 100) + with fit = (unfit target str) + while (plusp fit) do + (setf s2 (mutate str alpha changes) + f2 (unfit target s2)) + (when (> fit f2) + (setf str s2 fit f2) + (format t "~5d: ~a (~d)~%" gen str fit)))) (evolve 1 " ABCDEFGHIJKLMNOPQRSTUVWXYZ" "METHINKS IT IS LIKE A WEASEL") diff --git a/Task/Evolutionary-algorithm/Crystal/evolutionary-algorithm.cr b/Task/Evolutionary-algorithm/Crystal/evolutionary-algorithm.cr new file mode 100644 index 0000000000..b38ba00a51 --- /dev/null +++ b/Task/Evolutionary-algorithm/Crystal/evolutionary-algorithm.cr @@ -0,0 +1,33 @@ +TARGET = "METHINKS IT IS LIKE A WEASEL".chars +ALPHABET = ('A'..'Z').to_a << ' ' +C = 200 +RATE = 0.05 + +def fitness (current, target) + current.zip(target).count {|a, b| a == b } / current.size +end + +def mutate (current, rate) + current.map {|ch| Random.rand < rate ? ALPHABET.sample : ch } +end + +def next_parent (current, target, c, rate) + candidate = current + candidate_fitness = fitness(current, target) + c.times do + child = mutate(current, rate) + child_fitness = fitness(child, target) + if child_fitness > candidate_fitness + candidate, candidate_fitness = child, child_fitness + end + end + candidate +end + +parent = TARGET.map { ALPHABET.sample } + +(1..).each do |gen| + printf "%4d %s\n", gen, parent.join + break if parent == TARGET + parent = next_parent(parent, TARGET, C, RATE) +end diff --git a/Task/Evolutionary-algorithm/EasyLang/evolutionary-algorithm.easy b/Task/Evolutionary-algorithm/EasyLang/evolutionary-algorithm.easy index 1b22da0ea7..c7b8c72d26 100644 --- a/Task/Evolutionary-algorithm/EasyLang/evolutionary-algorithm.easy +++ b/Task/Evolutionary-algorithm/EasyLang/evolutionary-algorithm.easy @@ -11,7 +11,7 @@ func fitness trial$ . func$ mutate parent$ . for c$ in strchars parent$ if randomf < P - res$ &= abc$[randint len abc$[]] + res$ &= abc$[random 1 len abc$[]] else res$ &= c$ . @@ -19,7 +19,7 @@ func$ mutate parent$ . return res$ . for i to len target$ - parent$ &= abc$[randint len abc$[]] + parent$ &= abc$[random 1 len abc$[]] . while fitness parent$ > 0 copies$[] = [ ] diff --git a/Task/Evolutionary-algorithm/EchoLisp/evolutionary-algorithm.l b/Task/Evolutionary-algorithm/EchoLisp/evolutionary-algorithm.l index 33ebb8503a..5dcec7d3ee 100644 --- a/Task/Evolutionary-algorithm/EchoLisp/evolutionary-algorithm.l +++ b/Task/Evolutionary-algorithm/EchoLisp/evolutionary-algorithm.l @@ -3,36 +3,36 @@ (vector-push ALPHABET " ") (define (fitness source target) ;; score >=0, best is 0 - (for/sum [(s source)(t target)] - (if (= s t) 0 1))) - + (for/sum [(s source)(t target)] + (if (= s t) 0 1))) + (define (mutate source rate) - (for/string [(s source)] - (if (< (random) rate) [ALPHABET (random 27)] s))) - + (for/string [(s source)] + (if (< (random) rate) [ALPHABET (random 27)] s))) + (define (select parent target rate copies (copy) (score)) - (define best (fitness parent target)) - (define selected parent) - (for [(i copies)] - (set! copy (mutate parent rate)) - (set! score (fitness copy target)) - (when (< score best) - (set! selected copy) - (set! best score))) - selected ) - + (define best (fitness parent target)) + (define selected parent) + (for [(i copies)] + (set! copy (mutate parent rate)) + (set! score (fitness copy target)) + (when (< score best) + (set! selected copy) + (set! best score))) + selected ) + (define MUTATION_RATE 0.05) ;; 5% chances to change (define COPIES 100) (define TARGET "METHINKS IT IS LIKE A WEASEL") (define (task (rate MUTATION_RATE) (copies COPIES) (target TARGET) (score)) - (define parent ;; random source - (for/string + (define parent ;; random source + (for/string [(i (string-length target))] [ALPHABET (random 27)])) - - (for [(i (in-naturals))] - (set! score (fitness parent target)) - (writeln i parent 'score score) - #:break (zero? score) - (set! parent (select parent target rate copies)) - )) + + (for [(i (in-naturals))] + (set! score (fitness parent target)) + (writeln i parent 'score score) + #:break (zero? score) + (set! parent (select parent target rate copies)) + )) diff --git a/Task/Evolutionary-algorithm/Elena/evolutionary-algorithm.elena b/Task/Evolutionary-algorithm/Elena/evolutionary-algorithm.elena index 39a52319eb..b26b81a6d0 100644 --- a/Task/Evolutionary-algorithm/Elena/evolutionary-algorithm.elena +++ b/Task/Evolutionary-algorithm/Elena/evolutionary-algorithm.elena @@ -8,7 +8,7 @@ const string AllowedCharacters = " ABCDEFGHIJKLMNOPQRSTUVWXYZ"; const int C = 100; const real P = 0.05r; -rnd = randomGenerator; +rnd = Random; randomChar = AllowedCharacters[rnd.nextInt(AllowedCharacters.Length)]; @@ -19,17 +19,17 @@ extension evoHelper = 0.repeatTill(self).selectBy::(x => randomChar).summarize(new StringWriter()); fitnessOf(s) - = self.zipBy(s, (a,b => a==b ? 1 : 0)).summarize(new Integer()).toInt(); + = 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 { - object _target; - object _current; - object _variantCount; + object _target; + object? _current; + object _variantCount; constructor new(s,count) { @@ -62,15 +62,15 @@ class EvoAlgorithm : Enumerator enumerable() => _target; } -public program() +public Program() { var attempt := new Integer(); EvoAlgorithm.new(Target,C).forEach::(current) { - console + Console .printPaddingLeft(10,"#",attempt.append(1)) .printLine(" ",current," fitness: ",current.fitnessOf(Target)) }; - console.readChar() + Console.readChar() } diff --git a/Task/Evolutionary-algorithm/Elixir/evolutionary-algorithm.elixir b/Task/Evolutionary-algorithm/Elixir/evolutionary-algorithm.ex similarity index 100% rename from Task/Evolutionary-algorithm/Elixir/evolutionary-algorithm.elixir rename to Task/Evolutionary-algorithm/Elixir/evolutionary-algorithm.ex diff --git a/Task/Evolutionary-algorithm/Euphoria/evolutionary-algorithm.euphoria b/Task/Evolutionary-algorithm/Euphoria/evolutionary-algorithm.eu similarity index 100% rename from Task/Evolutionary-algorithm/Euphoria/evolutionary-algorithm.euphoria rename to Task/Evolutionary-algorithm/Euphoria/evolutionary-algorithm.eu diff --git a/Task/Evolutionary-algorithm/Fortran/evolutionary-algorithm-1.f b/Task/Evolutionary-algorithm/Fortran/evolutionary-algorithm-1.f index e16722f652..4cbf77fb0d 100644 --- a/Task/Evolutionary-algorithm/Fortran/evolutionary-algorithm-1.f +++ b/Task/Evolutionary-algorithm/Fortran/evolutionary-algorithm-1.f @@ -1,135 +1,135 @@ !*************************************************************************************************** - module evolve_routines + module evolve_routines !*************************************************************************************************** - implicit none - - !the target string: - character(len=*),parameter :: targ = 'METHINKS IT IS LIKE A WEASEL' - - contains + implicit none + + !the target string: + character(len=*),parameter :: targ = 'METHINKS IT IS LIKE A WEASEL' + + contains !*************************************************************************************************** - + !******************************************************************** - pure elemental function fitness(member) result(n) + pure elemental function fitness(member) result(n) !******************************************************************** ! The fitness function. The lower the value, the better the match. ! It is zero if they are identical. !******************************************************************** - - implicit none - integer :: n - character(len=*),intent(in) :: member - - integer :: i - - n=0 - do i=1,len(targ) - n = n + abs( ichar(targ(i:i)) - ichar(member(i:i)) ) - end do - + + implicit none + integer :: n + character(len=*),intent(in) :: member + + integer :: i + + n=0 + do i=1,len(targ) + n = n + abs( ichar(targ(i:i)) - ichar(member(i:i)) ) + end do + !******************************************************************** - end function fitness + end function fitness !******************************************************************** - + !******************************************************************** - pure elemental subroutine mutate(member,factor) + pure elemental subroutine mutate(member,factor) !******************************************************************** ! mutate a member of the population. !******************************************************************** - - implicit none - character(len=*),intent(inout) :: member !population member - real,intent(in) :: factor !mutation factor - - integer,parameter :: n_chars = 27 !number of characters in set - character(len=n_chars),parameter :: chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ ' - - real :: rnd_val - integer :: i,j,n - - n = len(member) - - do i=1,n - rnd_val = rand() - if (rnd_val<=factor) then !mutate this element - rnd_val = rand() - j = int(rnd_val*n_chars)+1 !an integer between 1 and n_chars - member(i:i) = chars(j:j) - end if - end do - + + implicit none + character(len=*),intent(inout) :: member !population member + real,intent(in) :: factor !mutation factor + + integer,parameter :: n_chars = 27 !number of characters in set + character(len=n_chars),parameter :: chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ ' + + real :: rnd_val + integer :: i,j,n + + n = len(member) + + do i=1,n + rnd_val = rand() + if (rnd_val<=factor) then !mutate this element + rnd_val = rand() + j = int(rnd_val*n_chars)+1 !an integer between 1 and n_chars + member(i:i) = chars(j:j) + end if + end do + !******************************************************************** - end subroutine mutate + end subroutine mutate !******************************************************************** !*************************************************************************************************** - end module evolve_routines + end module evolve_routines !*************************************************************************************************** !*************************************************************************************************** - program evolve + program evolve !*************************************************************************************************** ! The main program !*************************************************************************************************** - use evolve_routines - - implicit none - - !Tuning parameters: - integer,parameter :: seed = 12345 !random number generator seed - integer,parameter :: max_iter = 10000 !maximum number of iterations - integer,parameter :: population_size = 200 !size of the population - real,parameter :: factor = 0.04 ![0,1] mutation factor - integer,parameter :: iprint = 5 !print every iprint iterations - - !local variables: - integer :: i,iter - integer,dimension(1) :: i_best - character(len=len(targ)),dimension(population_size) :: population - - !initialize random number generator: - call srand(seed) - - !create initial population: - ! [the first element of the population will hold the best member] - population(1) = 'PACQXJB CQPWEYKSVDCIOUPKUOJY' !initial guess - iter=0 - - write(*,'(A10,A30,A10)') 'iter','best','fitness' - write(*,'(I10,A30,I10)') iter,population(1),fitness(population(1)) - - do - - iter = iter + 1 !iteration counter - - !write the iteration: - if (mod(iter,iprint)==0) write(*,'(I10,A30,I10)') iter,population(1),fitness(population(1)) - - !check exit conditions: - if ( iter>max_iter .or. fitness(population(1))==0 ) exit - - !copy best member and mutate: - population = population(1) - do i=2,population_size - call mutate(population(i),factor) - end do - - !select the new best population member: - ! [the best has the lowest value] - i_best = minloc(fitness(population)) - population(1) = population(i_best(1)) - - end do - - !write the last iteration: - if (mod(iter,iprint)/=0) write(*,'(I10,A30,I10)') iter,population(1),fitness(population(1)) - - if (iter>max_iter) then - write(*,*) 'No solution found.' - else - write(*,*) 'Solution found.' - end if - + use evolve_routines + + implicit none + + !Tuning parameters: + integer,parameter :: seed = 12345 !random number generator seed + integer,parameter :: max_iter = 10000 !maximum number of iterations + integer,parameter :: population_size = 200 !size of the population + real,parameter :: factor = 0.04 ![0,1] mutation factor + integer,parameter :: iprint = 5 !print every iprint iterations + + !local variables: + integer :: i,iter + integer,dimension(1) :: i_best + character(len=len(targ)),dimension(population_size) :: population + + !initialize random number generator: + call srand(seed) + + !create initial population: + ! [the first element of the population will hold the best member] + population(1) = 'PACQXJB CQPWEYKSVDCIOUPKUOJY' !initial guess + iter=0 + + write(*,'(A10,A30,A10)') 'iter','best','fitness' + write(*,'(I10,A30,I10)') iter,population(1),fitness(population(1)) + + do + + iter = iter + 1 !iteration counter + + !write the iteration: + if (mod(iter,iprint)==0) write(*,'(I10,A30,I10)') iter,population(1),fitness(population(1)) + + !check exit conditions: + if ( iter>max_iter .or. fitness(population(1))==0 ) exit + + !copy best member and mutate: + population = population(1) + do i=2,population_size + call mutate(population(i),factor) + end do + + !select the new best population member: + ! [the best has the lowest value] + i_best = minloc(fitness(population)) + population(1) = population(i_best(1)) + + end do + + !write the last iteration: + if (mod(iter,iprint)/=0) write(*,'(I10,A30,I10)') iter,population(1),fitness(population(1)) + + if (iter>max_iter) then + write(*,*) 'No solution found.' + else + write(*,*) 'Solution found.' + end if + !*************************************************************************************************** - end program evolve + end program evolve !*************************************************************************************************** diff --git a/Task/Evolutionary-algorithm/FutureBasic/evolutionary-algorithm.basic b/Task/Evolutionary-algorithm/FutureBasic/evolutionary-algorithm.basic new file mode 100644 index 0000000000..36c9824034 --- /dev/null +++ b/Task/Evolutionary-algorithm/FutureBasic/evolutionary-algorithm.basic @@ -0,0 +1,80 @@ +include "NSLog.incl" + +begin globals + CFStringRef target + CFStringRef alphabet + NSInteger c + CGFloat p +end globals + +target = @"METHINKS IT IS LIKE A WEASEL" +alphabet = @"ABCDEFGHIJKLMNOPQRSTUVWXYZ " +c = 100 +p = 0.06 + +toolbox fn arc4random_uniform( UInt32 upperbound ) = UInt32 + +local fn Fitness( s as CFStringRef ) as NSInteger + NSInteger score = len(target) + for NSInteger i = 0 to len(target) -1 + if ( ucc(s,i) == ucc(target,i) ) then score-- + next +end fn = score + +local fn Mutate( s as CFStringRef, rate as CGFloat ) as CFStringRef + CFMutableStringRef result = fn MutableStringWithString( @"" ) + for NSInteger i = 0 to len(s) -1 + if ( ( fn arc4random_uniform(100) / 100.0) < rate ) + NSInteger idx = fn arc4random_uniform( (UInt32)len(alphabet) ) + MutableStringAppendFormat( result, @"%C", ucc( alphabet, idx ) ) + else + MutableStringAppendFormat( result, @"%C", ucc( s, i ) ) + end if + next +end fn = result + +local fn RandomString( length as NSInteger ) as CFStringRef + CFMutableStringRef result = fn MutableStringWithString( @"" ) + for NSInteger i = 0 to length -1 + NSInteger idx = fn arc4random_uniform( (UInt32)len(alphabet) ) + MutableStringAppendFormat( result, @"%C", ucc( alphabet, idx ) ) + next +end fn = result + +void local fn PrintStep( stepNum as NSInteger, s as CFStringRef, fit as NSInteger, result as CFMutableStringRef ) + MutableStringAppendFormat( result, @"%3ld: %@ Distance: %ld\n", (long)stepNum, s, (long)fit ) +end fn + +local fn EvolveString as CFStringRef + CFMutableStringRef result = fn MutableStringNew + CFStringRef parent = fn RandomString( len(target) ) + fn PrintStep( 0, parent, fn Fitness(parent), result ) + + NSInteger stepNum = 0 + while ( fn StringIsEqual( parent, target ) == NO ) + NSInteger bestFitness = len(target) + 1 + CFStringRef bestChild = @"" + CFStringRef child + NSInteger fit + + for NSInteger i = 0 to c -1 + child = fn Mutate( parent, p ) + fit = fn Fitness( child ) + if ( fit < bestFitness ) + bestFitness = fit + bestChild = child + end if + next + parent = bestChild + stepNum++ + fn PrintStep( stepNum, parent, bestFitness, result ) + wend +end fn = result + +CFTimeInterval t : t = fn CACurrentMediaTime +CFStringRef result : result = fn EvolveString +NSLog( @"\nCompute time: %.3f ms\n",(fn CACurrentMediaTime-t)*1000 ) +NSLog( @"%@", result ) +NSLogScrollToTop + +HandleEvents diff --git a/Task/Evolutionary-algorithm/Icon/evolutionary-algorithm-1.icon b/Task/Evolutionary-algorithm/Icon/evolutionary-algorithm-1.icon index 039ac0694b..b601df08e4 100644 --- a/Task/Evolutionary-algorithm/Icon/evolutionary-algorithm-1.icon +++ b/Task/Evolutionary-algorithm/Icon/evolutionary-algorithm-1.icon @@ -1,51 +1,51 @@ global target, chars, parent, C, M, current_fitness procedure fitness(s) - fit := 0 - #Increment the fitness for every position in the string s that matches the target - every i := 1 to *target & s[i] == target[i] do fit +:= 1 - return fit + fit := 0 + #Increment the fitness for every position in the string s that matches the target + every i := 1 to *target & s[i] == target[i] do fit +:= 1 + return fit end procedure mutate(s) - #If a random number between 0 and 1 is inside the bounds of mutation randomly alter a character in the string - if (?0 <= M) then ?s := ?chars - return s + #If a random number between 0 and 1 is inside the bounds of mutation randomly alter a character in the string + if (?0 <= M) then ?s := ?chars + return s end procedure generation() - population := [ ] - next_parent := "" - next_fitness := -1 + population := [ ] + next_parent := "" + next_fitness := -1 - #Create the next population - every 1 to C do push(population, mutate(parent)) - #Find the member of the population with highest fitness, or use the last one inspected - every x := !population & (xf := fitness(x)) > next_fitness do { - next_parent := x - next_fitness := xf - } - - parent := next_parent - - return next_fitness + #Create the next population + every 1 to C do push(population, mutate(parent)) + #Find the member of the population with highest fitness, or use the last one inspected + every x := !population & (xf := fitness(x)) > next_fitness do { + next_parent := x + next_fitness := xf + } + + parent := next_parent + + return next_fitness end procedure main() - target := "METHINKS IT IS LIKE A WEASEL" #Our target string - chars := &ucase ++ " " #Set of usable characters - parent := "" & every 1 to *target do parent ||:= ?chars #The universal common ancestor! - current_fitness := fitness(parent) #The best fitness we have so far + target := "METHINKS IT IS LIKE A WEASEL" #Our target string + chars := &ucase ++ " " #Set of usable characters + parent := "" & every 1 to *target do parent ||:= ?chars #The universal common ancestor! + current_fitness := fitness(parent) #The best fitness we have so far - C := 50 #Population size in each generation - M := 0.5 #Mutation rate per individual in a generation - - gen := 1 - #Until current fitness reaches a score of perfect match with the target string keep generating new populations - until ((current_fitness := generation()) = *target) do { + C := 50 #Population size in each generation + M := 0.5 #Mutation rate per individual in a generation + + gen := 1 + #Until current fitness reaches a score of perfect match with the target string keep generating new populations + until ((current_fitness := generation()) = *target) do { write(gen || " " || current_fitness || " " || parent) gen +:= 1 - } - write("At generation " || gen || " we found a string with perfect fitness at " || current_fitness || " reading: " || parent) + } + write("At generation " || gen || " we found a string with perfect fitness at " || current_fitness || " reading: " || parent) end diff --git a/Task/Evolutionary-algorithm/Icon/evolutionary-algorithm-2.icon b/Task/Evolutionary-algorithm/Icon/evolutionary-algorithm-2.icon index f80f1d6a42..543e63dbd6 100644 --- a/Task/Evolutionary-algorithm/Icon/evolutionary-algorithm-2.icon +++ b/Task/Evolutionary-algorithm/Icon/evolutionary-algorithm-2.icon @@ -1,7 +1,7 @@ -(var c 100) ;number of children in each generation -(var p 0.05) ;mutation probability +(var c 100 ;number of children in each generation + p 0.05) ;mutation probability -(var target "METHINKS IT IS LIKE A WEASEL") -(var tsize (len target)) +(var target "METHINKS IT IS LIKE A WEASEL" + tsize (len target)) (var alphabet (to-vec " ABCDEFGHIJLKLMNOPQRSTUVWXYZ")) diff --git a/Task/Evolutionary-algorithm/JavaScript/evolutionary-algorithm-1.js b/Task/Evolutionary-algorithm/JavaScript/evolutionary-algorithm-1.js index 42c57caec0..3162d81a5a 100644 --- a/Task/Evolutionary-algorithm/JavaScript/evolutionary-algorithm-1.js +++ b/Task/Evolutionary-algorithm/JavaScript/evolutionary-algorithm-1.js @@ -68,8 +68,8 @@ if (!Array.prototype.map) { /* ------------------------------------- Generator ------------------------------------- * Generates a fixed length gene sequence via a gene strategy object. * The gene strategy object must have two functions: - * - "create": returns create a new gene - * - "mutate(existingGene)": returns mutation of an existing gene + * - "create": returns create a new gene + * - "mutate(existingGene)": returns mutation of an existing gene */ function Generator(length, mutationRate, geneStrategy) { this.size = length; @@ -119,9 +119,9 @@ Population.prototype.spawn = function (parent) { /* ------------------------------------- Evolver ------------------------------------- * Attempts to converge a population based a fitness strategy object. * The fitness strategy object must have three function - * - "score(individual)": returns a score for an individual. - * - "compare(scoreA, scoreB)": return true if scoreA is better (ie more fit) then scoreB - * - "done( score )": return true if score is acceptable (ie we have successfully converged). + * - "score(individual)": returns a score for an individual. + * - "compare(scoreA, scoreB)": return true if scoreA is better (ie more fit) then scoreB + * - "done( score )": return true if score is acceptable (ie we have successfully converged). */ function Evolver(size, generator, fitness) { this.done = false; diff --git a/Task/Evolutionary-algorithm/Julia/evolutionary-algorithm.julia b/Task/Evolutionary-algorithm/Julia/evolutionary-algorithm.jl similarity index 100% rename from Task/Evolutionary-algorithm/Julia/evolutionary-algorithm.julia rename to Task/Evolutionary-algorithm/Julia/evolutionary-algorithm.jl diff --git a/Task/Evolutionary-algorithm/Kotlin/evolutionary-algorithm.kotlin b/Task/Evolutionary-algorithm/Kotlin/evolutionary-algorithm.kts similarity index 100% rename from Task/Evolutionary-algorithm/Kotlin/evolutionary-algorithm.kotlin rename to Task/Evolutionary-algorithm/Kotlin/evolutionary-algorithm.kts diff --git a/Task/Evolutionary-algorithm/Lua/evolutionary-algorithm.lua b/Task/Evolutionary-algorithm/Lua/evolutionary-algorithm.lua index 2d3d272d00..7d955f14ff 100644 --- a/Task/Evolutionary-algorithm/Lua/evolutionary-algorithm.lua +++ b/Task/Evolutionary-algorithm/Lua/evolutionary-algorithm.lua @@ -3,37 +3,37 @@ local alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ " local c, p = 100, 0.06 local function fitness(s) - local score = #target - for i = 1,#target do - if s:sub(i,i) == target:sub(i,i) then score = score - 1 end - end - return score + local score = #target + for i = 1,#target do + if s:sub(i,i) == target:sub(i,i) then score = score - 1 end + end + return score end local function mutate(s, rate) - local result, idx = "" - for i = 1,#s do - if math.random() < rate then - idx = math.random(#alphabet) - result = result .. alphabet:sub(idx,idx) - else - result = result .. s:sub(i,i) - end - end - return result, fitness(result) + local result, idx = "" + for i = 1,#s do + if math.random() < rate then + idx = math.random(#alphabet) + result = result .. alphabet:sub(idx,idx) + else + result = result .. s:sub(i,i) + end + end + return result, fitness(result) end local function randomString(len) - local result, idx = "" - for i = 1,len do - idx = math.random(#alphabet) - result = result .. alphabet:sub(idx,idx) - end - return result + local result, idx = "" + for i = 1,len do + idx = math.random(#alphabet) + result = result .. alphabet:sub(idx,idx) + end + return result end local function printStep(step, s, fit) - print(string.format("%04d: ", step) .. s .. " [" .. fit .."]") + print(string.format("%04d: ", step) .. s .. " [" .. fit .."]") end math.randomseed(os.time()) @@ -42,11 +42,11 @@ printStep(0, parent, fitness(parent)) local step = 0 while parent ~= target do - local bestFitness, bestChild, child, fitness = #target + 1 - for i = 1,c do - child, fitness = mutate(parent, p) - if fitness < bestFitness then bestFitness, bestChild = fitness, child end - end - parent, step = bestChild, step + 1 - printStep(step, parent, bestFitness) + local bestFitness, bestChild, child, fitness = #target + 1 + for i = 1,c do + child, fitness = mutate(parent, p) + if fitness < bestFitness then bestFitness, bestChild = fitness, child end + end + parent, step = bestChild, step + 1 + printStep(step, parent, bestFitness) end diff --git a/Task/Evolutionary-algorithm/MATLAB/evolutionary-algorithm-4.m b/Task/Evolutionary-algorithm/MATLAB/evolutionary-algorithm-4.m index 8fbb9f76e6..4bafdb7261 100644 --- a/Task/Evolutionary-algorithm/MATLAB/evolutionary-algorithm-4.m +++ b/Task/Evolutionary-algorithm/MATLAB/evolutionary-algorithm-4.m @@ -5,7 +5,7 @@ Gen: 4 | Fitness: 322 | KI8M5LAS�GJ�IS�SP�@)D�V@ JCP Gen: 5 | Fitness: 295 | UAUR08AS�GJ�IS�8HG*�+�=C?UB( Gen: 6 | Fitness: 259 | VCUQH35S�HR4.L�ISJQ%J�OC*T=E -Gen: 7 | Fitness: 226 | LFB8GPET(LODKQ�KQBQGF Gen: 9 | Fitness: 159 | N8R7?SOU�NO$OK O?K?!;�MB?QHG Gen: 10 | Fitness: 146 | TGN@EQR4)PS%IS#TFJQ%A!U>BVLI diff --git a/Task/Evolutionary-algorithm/Nanoquery/evolutionary-algorithm.nanoquery b/Task/Evolutionary-algorithm/Nanoquery/evolutionary-algorithm.nanoquery index d695b42ab6..d022b35839 100644 --- a/Task/Evolutionary-algorithm/Nanoquery/evolutionary-algorithm.nanoquery +++ b/Task/Evolutionary-algorithm/Nanoquery/evolutionary-algorithm.nanoquery @@ -8,77 +8,77 @@ rand = new(Random) // returns a random string of the specified length def rand_string(length) - global tbl - global rand + global tbl + global rand - ret = "" + ret = "" - for i in range(1, length) - ret += tbl[rand.getInt(len(tbl))] - end + for i in range(1, length) + ret += tbl[rand.getInt(len(tbl))] + end - return ret + return ret end // gets the fitness of a given string def fitness(string) - global target - fit = 0 + global target + fit = 0 - for i in range(0, len(string) - 1) - if string[i] != target[i] - fit -= 1 - end - end + for i in range(0, len(string) - 1) + if string[i] != target[i] + fit -= 1 + end + end - return fit + return fit end // mutates the specified string with a chance of 0.09 by default def mutate(string) - global chance - global rand - global tbl - mutated = string + global chance + global rand + global tbl + mutated = string - for i in range(0, len(mutated) - 1) - if rand.getFloat() <= chance - mutated[i] = tbl[rand.getInt(len(tbl))] - end - end + for i in range(0, len(mutated) - 1) + if rand.getFloat() <= chance + mutated[i] = tbl[rand.getInt(len(tbl))] + end + end - return mutated + return mutated end // a function to find the index of the string with the best fitness def most_fit(strlist) - global target - - best_score = -(len(target) + 1) - best_index = 0 - - for j in range(0, len(strlist) - 1) - fit = fitness(strlist[j]) - if fit > best_score - best_index = j - best_score = fit - end - end + global target - return {best_index, best_score} + best_score = -(len(target) + 1) + best_index = 0 + + for j in range(0, len(strlist) - 1) + fit = fitness(strlist[j]) + if fit > best_score + best_index = j + best_score = fit + end + end + + return {best_index, best_score} end parent = rand_string(len(target)); iter = 1 while parent != target - children = {} + children = {} - for i in range(1, 30) - children.append(mutate(parent)) - end + for i in range(1, 30) + children.append(mutate(parent)) + end - fit = most_fit(children) - parent = children[fit[0]] - print format("iter %d, score %d: %s\n", iter, fit[1], parent) + fit = most_fit(children) + parent = children[fit[0]] + print format("iter %d, score %d: %s\n", iter, fit[1], parent) - iter += 1 + iter += 1 end diff --git a/Task/Evolutionary-algorithm/OCaml/evolutionary-algorithm.ocaml b/Task/Evolutionary-algorithm/OCaml/evolutionary-algorithm.ml similarity index 100% rename from Task/Evolutionary-algorithm/OCaml/evolutionary-algorithm.ocaml rename to Task/Evolutionary-algorithm/OCaml/evolutionary-algorithm.ml diff --git a/Task/Evolutionary-algorithm/PARI-GP/evolutionary-algorithm.parigp b/Task/Evolutionary-algorithm/PARI-GP/evolutionary-algorithm.parigp index e33c81e794..8fbb6b82fa 100644 --- a/Task/Evolutionary-algorithm/PARI-GP/evolutionary-algorithm.parigp +++ b/Task/Evolutionary-algorithm/PARI-GP/evolutionary-algorithm.parigp @@ -4,43 +4,43 @@ dist(u,v)=sum(i=1,min(#u,#v),u[i]!=v[i])+abs(#u-#v); letter()=my(r=random(27)); if(r==26, " ", Strchr(r+65)); insert(v,x=letter())= { - my(r=random(#v+1)); - if(r==0, return(concat([x],v))); - if(r==#v, return(concat(v,[x]))); - concat(concat(v[1..r],[x]),v[r+1..#v]); + my(r=random(#v+1)); + if(r==0, return(concat([x],v))); + if(r==#v, return(concat(v,[x]))); + concat(concat(v[1..r],[x]),v[r+1..#v]); } delete(v)= { - if(#v<2, return([])); - my(r=random(#v)+1); - if(r==1, return(v[2..#v])); - if(r==#v, return(v[1..#v-1])); - concat(v[1..r-1],v[r+1..#v]); + if(#v<2, return([])); + my(r=random(#v)+1); + if(r==1, return(v[2..#v])); + if(r==#v, return(v[1..#v-1])); + concat(v[1..r-1],v[r+1..#v]); } mutate(s,rateM,rateI,rateD)= { - my(v=Vec(s)); - if(random(1.)best, best=t; parent=v[i]) - ); - ct++ - ); - print(parent" "fitness(parent)); - ct; + my(parent=concat(vector(#target,i,letter())),ct=0); + while(parent != target, + print(parent" "fitness(parent)); + my(v=vector(C,i,mutate(parent,rate,0,0)),best,t); + best=fitness(parent=v[1]); + for(i=2,C, + t=fitness(v[i]); + if(t>best, best=t; parent=v[i]) + ); + ct++ + ); + print(parent" "fitness(parent)); + ct; } evolve(35,.05) diff --git a/Task/Evolutionary-algorithm/Pascal/evolutionary-algorithm.pas b/Task/Evolutionary-algorithm/Pascal/evolutionary-algorithm.pas index 97f638a700..821c4a0a6d 100644 --- a/Task/Evolutionary-algorithm/Pascal/evolutionary-algorithm.pas +++ b/Task/Evolutionary-algorithm/Pascal/evolutionary-algorithm.pas @@ -1,108 +1,108 @@ PROGRAM EVOLUTION (OUTPUT); CONST - TARGET = 'METHINKS IT IS LIKE A WEASEL'; - COPIES = 100; (* 100 children in each generation. *) - RATE = 1000; (* About one character in 1000 will be a mutation. *) + TARGET = 'METHINKS IT IS LIKE A WEASEL'; + COPIES = 100; (* 100 children in each generation. *) + RATE = 1000; (* About one character in 1000 will be a mutation. *) TYPE - STRLIST = ARRAY [1..COPIES] OF STRING; + STRLIST = ARRAY [1..COPIES] OF STRING; FUNCTION RANDCHAR : CHAR; (* Generate a random letter or space. *) VAR RANDNUM : INTEGER; BEGIN - RANDNUM := RANDOM(27); - IF RANDNUM = 26 THEN - RANDCHAR := ' ' - ELSE - RANDCHAR := CHR(RANDNUM + ORD('A')) + RANDNUM := RANDOM(27); + IF RANDNUM = 26 THEN + RANDCHAR := ' ' + ELSE + RANDCHAR := CHR(RANDNUM + ORD('A')) END; FUNCTION RANDSTR (SIZE : INTEGER) : STRING; (* Generate a random string. *) VAR - N : INTEGER; - S : STRING; + N : INTEGER; + S : STRING; BEGIN - S := ''; - FOR N := 1 TO SIZE DO - INSERT(RANDCHAR, S, 1); - RANDSTR := S + S := ''; + FOR N := 1 TO SIZE DO + INSERT(RANDCHAR, S, 1); + RANDSTR := S END; FUNCTION FITNESS (CANDIDATE, GOAL : STRING) : INTEGER; (* Count the number of correct letters in the correct places *) VAR N, MATCHES : INTEGER; BEGIN - MATCHES := 0; - FOR N := 1 TO LENGTH(GOAL) DO - IF CANDIDATE[N] = GOAL[N] THEN - MATCHES := MATCHES + 1; - FITNESS := MATCHES + MATCHES := 0; + FOR N := 1 TO LENGTH(GOAL) DO + IF CANDIDATE[N] = GOAL[N] THEN + MATCHES := MATCHES + 1; + FITNESS := MATCHES END; FUNCTION MUTATE (RATE : INTEGER; S : STRING) : STRING; (* Randomly alter a string. Characters change with probability 1/RATE. *) VAR - N : INTEGER; - CHANGE : BOOLEAN; + N : INTEGER; + CHANGE : BOOLEAN; BEGIN - FOR N := 1 TO LENGTH(TARGET) DO - BEGIN - CHANGE := RANDOM(RATE) = 0; - IF CHANGE THEN - S[N] := RANDCHAR - END; - MUTATE := S + FOR N := 1 TO LENGTH(TARGET) DO + BEGIN + CHANGE := RANDOM(RATE) = 0; + IF CHANGE THEN + S[N] := RANDCHAR + END; + MUTATE := S END; PROCEDURE REPRODUCE (RATE : INTEGER; PARENT : STRING; VAR CHILDREN : STRLIST); (* Generate children with random mutations. *) VAR N : INTEGER; BEGIN - FOR N := 1 TO COPIES DO - CHILDREN[N] := MUTATE(RATE, PARENT) + FOR N := 1 TO COPIES DO + CHILDREN[N] := MUTATE(RATE, PARENT) END; FUNCTION FITTEST(CHILDREN : STRLIST; GOAL : STRING) : STRING; (* Measure the fitness of each child and return the fittest. *) (* If multiple children equally match the target, then return the first. *) VAR - MATCHES, MOST_MATCHES, BEST_INDEX, N : INTEGER; + MATCHES, MOST_MATCHES, BEST_INDEX, N : INTEGER; BEGIN - MOST_MATCHES := 0; - BEST_INDEX := 1; - FOR N := 1 TO COPIES DO - BEGIN - MATCHES := FITNESS(CHILDREN[N], GOAL); - IF MATCHES > MOST_MATCHES THEN - BEGIN - MOST_MATCHES := MATCHES; - BEST_INDEX := N - END - END; - FITTEST := CHILDREN[BEST_INDEX] + MOST_MATCHES := 0; + BEST_INDEX := 1; + FOR N := 1 TO COPIES DO + BEGIN + MATCHES := FITNESS(CHILDREN[N], GOAL); + IF MATCHES > MOST_MATCHES THEN + BEGIN + MOST_MATCHES := MATCHES; + BEST_INDEX := N + END + END; + FITTEST := CHILDREN[BEST_INDEX] END; VAR - PARENT, BEST_CHILD : STRING; - CHILDREN : STRLIST; - GENERATIONS : INTEGER; + PARENT, BEST_CHILD : STRING; + CHILDREN : STRLIST; + GENERATIONS : INTEGER; BEGIN - RANDOMIZE; - GENERATIONS := 0; - PARENT := RANDSTR(LENGTH(TARGET)); - WHILE NOT (PARENT = TARGET) DO - BEGIN - IF (GENERATIONS MOD 100) = 0 THEN WRITELN(PARENT); - GENERATIONS := GENERATIONS + 1; - REPRODUCE(RATE, PARENT, CHILDREN); - BEST_CHILD := FITTEST(CHILDREN, TARGET); - IF FITNESS(PARENT, TARGET) < FITNESS(BEST_CHILD, TARGET) THEN - PARENT := BEST_CHILD - END; - WRITE('The string was matched in '); - WRITELN(GENERATIONS, ' generations.') + RANDOMIZE; + GENERATIONS := 0; + PARENT := RANDSTR(LENGTH(TARGET)); + WHILE NOT (PARENT = TARGET) DO + BEGIN + IF (GENERATIONS MOD 100) = 0 THEN WRITELN(PARENT); + GENERATIONS := GENERATIONS + 1; + REPRODUCE(RATE, PARENT, CHILDREN); + BEST_CHILD := FITTEST(CHILDREN, TARGET); + IF FITNESS(PARENT, TARGET) < FITNESS(BEST_CHILD, TARGET) THEN + PARENT := BEST_CHILD + END; + WRITE('The string was matched in '); + WRITELN(GENERATIONS, ' generations.') END. diff --git a/Task/Evolutionary-algorithm/PascalABC.NET/evolutionary-algorithm.pas b/Task/Evolutionary-algorithm/PascalABC.NET/evolutionary-algorithm.pas new file mode 100644 index 0000000000..9b763a6711 --- /dev/null +++ b/Task/Evolutionary-algorithm/PascalABC.NET/evolutionary-algorithm.pas @@ -0,0 +1,24 @@ +const + Target = 'METHINKS IT IS LIKE A WEASEL'; + Alphabet = ' ABCDEFGHIJLKLMNOPQRSTUVWXYZ'; + P = 0.05; + C = 100; + +function negFitness(trial: string) := + trial.Zip(Target, (x, y) -> (if x = y then 0 else 1)).Sum; + +function mutate(parent: string) := + parent.Aggregate('', (mut, ch) -> mut + (if Random(1.0) < P then Alphabet.RandomElement else ch)); + +begin + var parent := (1..Target.Length).Aggregate('', (p, x)-> p + Alphabet.RandomElement); + var i := 0; + while parent <> Target do + begin + var copies := ArrGen(C, x -> mutate(parent)); + parent := copies.Aggregate((p, x) -> (if negFitness(x) < negFitness(p) then x else p)); + if i mod 10 = 0 then Println(i, ' ', parent); + i += 1; + end; + Println(i, ' ', parent) +end. diff --git a/Task/Evolutionary-algorithm/Pony/evolutionary-algorithm-1.pony b/Task/Evolutionary-algorithm/Pony/evolutionary-algorithm-1.pony index 0c7a28f78e..5a092513f6 100644 --- a/Task/Evolutionary-algorithm/Pony/evolutionary-algorithm-1.pony +++ b/Task/Evolutionary-algorithm/Pony/evolutionary-algorithm-1.pony @@ -2,10 +2,10 @@ use "random" actor Main let _env: Env - let _rand: MT = MT // Mersenne Twister + let _rand: MT = MT // Mersenne Twister let _target: String = "METHINKS IT IS LIKE A WEASEL" let _possibilities: String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ " - let _c: U16 = 100 // number of spawn per generation + let _c: U16 = 100 // number of spawn per generation let _min_mutate_rate: F64 = 0.09 let _perfect_fitness: USize = _target.size() var _parent: String = "" diff --git a/Task/Evolutionary-algorithm/Prolog/evolutionary-algorithm.pro b/Task/Evolutionary-algorithm/Prolog/evolutionary-algorithm.pro index 2733079aa6..d3f325a38f 100644 --- a/Task/Evolutionary-algorithm/Prolog/evolutionary-algorithm.pro +++ b/Task/Evolutionary-algorithm/Prolog/evolutionary-algorithm.pro @@ -1,7 +1,7 @@ target("METHINKS IT IS LIKE A WEASEL"). rndAlpha(64, 32). % Generate a single random character -rndAlpha(P, P). % 32 is a space, and 65->90 are upper case +rndAlpha(P, P). % 32 is a space, and 65->90 are upper case rndAlpha(Ch) :- random(N), P is truncate(64+(N*27)), !, rndAlpha(P, Ch). rndTxt(0, []). % Generate some random text (fixed length) @@ -17,16 +17,16 @@ mutate(P, [H|Txt], [H|Mut]) :- random(R), R < P, !, mutate(P, Txt, Mut). mutate(P, [_|Txt], [M|Mut]) :- rndAlpha(M), !, mutate(P, Txt, Mut). weasel(Tries, _, _, mutation(0, Result)) :- % No differences=success - format('~w~4|:~w~3| - ~s\n', [Tries, 0, Result]). -weasel(Tries, Chance, Target, mutation(S, Value)) :- % output progress - format('~w~4|:~w~3| - ~s\n', [Tries, S, Value]), !, % and call again - weasel(Tries, Chance, Target, Value). + format('~w~4|:~w~3| - ~s\n', [Tries, 0, Result]). +weasel(Tries, Chance, Target, mutation(S, Value)) :- % output progress + format('~w~4|:~w~3| - ~s\n', [Tries, S, Value]), !, % and call again + weasel(Tries, Chance, Target, Value). weasel(Tries, Chance, Target, Start) :- - findall(mutation(S,M), % Generate 30 mutations, select the best. - (between(1, 30, _), mutate(Chance, Start, M), score(M,S,Target)), - Mutations), % List of 30 mutations and their scores - sort(Mutations, [Best|_]), succ(Tries, N), - !, weasel(N, Chance, Target, Best). + findall(mutation(S,M), % Generate 30 mutations, select the best. + (between(1, 30, _), mutate(Chance, Start, M), score(M,S,Target)), + Mutations), % List of 30 mutations and their scores + sort(Mutations, [Best|_]), succ(Tries, N), + !, weasel(N, Chance, Target, Best). weasel :- % Chance->probability for a mutation, T=Target, Start=initial text - target(T), length(T, Len), rndTxt(Len, Start), Chance is 1 - (1/(Len+1)), - !, weasel(0, Chance, T, Start). + target(T), length(T, Len), rndTxt(Len, Start), Chance is 1 - (1/(Len+1)), + !, weasel(0, Chance, T, Start). diff --git a/Task/Evolutionary-algorithm/Rebol/evolutionary-algorithm.rebol b/Task/Evolutionary-algorithm/Rebol/evolutionary-algorithm.rebol new file mode 100644 index 0000000000..a2ce3d5ab3 --- /dev/null +++ b/Task/Evolutionary-algorithm/Rebol/evolutionary-algorithm.rebol @@ -0,0 +1,65 @@ +Rebol [ + title: "Rosetta code: Evolutionary algorithm" + file: %Evolutionary_algorithm.r3 + url: https://rosettacode.org/wiki/Evolutionary_algorithm + note: "Based on Red language solution" +] + +evolve: function/with [ + target [string!] "target phrase to evolve toward" + childs [integer!] "number of offspring per generation" + rate [number!] "per-character mutation probability (0.0..1.0)" +][ + ;; create initial random parent of same length as target + parent: clear "" + repeat i length? target [ + append parent random/only alphabet + ] + ;; main loop: generate children, select fittest, repeat until exact match + mutations: 0 + while [parent != target] [ + clear children + repeat i childs [ + append children mutate parent rate ;; produce a mutated child from parent + ] + sort/compare children :sort-fitness ;; sort children by fitness (best first) + parent: first children ;; select best child as new parent + ++ mutations + prin #"^M" ;; carriage return to overwrite line + prin parent + ] + prin #"^M" ;; move to line start + print parent ;; final perfect match + mutations +][ + alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ " ;; allowed gene pool (uppercase letters + space) + children: copy [] ;; reusable buffer for a generation's children + + ;; compute closeness of 'string' to 'target' as Hamming distance (lower is better) + fitness: function [string] [ + sum: 0 + repeat i length? string [ + if string/:i <> target/:i [ ++ sum ] ;; count mismatched positions + ] + sum + ] + + ;; return a mutated copy of 'string'; each position mutates with probability 'rate' + mutate: function [string rate] [ + result: copy string + repeat i length? result [ + if rate > random 1.0 [ + result/:i: random/only alphabet ;; replace char with random from alphabet + ] + ] + result + ] + + ;; comparison function for sorting: a < b if fitness(a) < fitness(b) + sort-fitness: function [a b] [lesser? fitness a fitness b] +] + +;; run the evolution demo +random/seed 1 +m: evolve "METHINKS IT IS LIKE A WEASEL" 20 0.05 +print ["Target found using" as-yellow m "mutations."] diff --git a/Task/Evolutionary-algorithm/Rust/evolutionary-algorithm.rust b/Task/Evolutionary-algorithm/Rust/evolutionary-algorithm.rs similarity index 100% rename from Task/Evolutionary-algorithm/Rust/evolutionary-algorithm.rust rename to Task/Evolutionary-algorithm/Rust/evolutionary-algorithm.rs diff --git a/Task/Evolutionary-algorithm/Scheme/evolutionary-algorithm.ss b/Task/Evolutionary-algorithm/Scheme/evolutionary-algorithm.scm similarity index 100% rename from Task/Evolutionary-algorithm/Scheme/evolutionary-algorithm.ss rename to Task/Evolutionary-algorithm/Scheme/evolutionary-algorithm.scm diff --git a/Task/Evolutionary-algorithm/SequenceL/evolutionary-algorithm-1.sequencel b/Task/Evolutionary-algorithm/SequenceL/evolutionary-algorithm-1.sequencel index 836c3aba77..e1ab201b68 100644 --- a/Task/Evolutionary-algorithm/SequenceL/evolutionary-algorithm-1.sequencel +++ b/Task/Evolutionary-algorithm/SequenceL/evolutionary-algorithm-1.sequencel @@ -5,19 +5,19 @@ AllowedChars := " ABCDEFGHIJKLMNOPQRSTUVWXYZ"; initializeParent(randChars(1)) := AllowedChars[randChars]; Fitness(target(1), current(1)) := - let - fit[i] := true when target[i] = current[i]; - in - size(fit); - + let + fit[i] := true when target[i] = current[i]; + in + size(fit); + Mutate(letter(0), rate(0), randRate(0), randChar(0)) := - letter when randRate > rate - else - AllowedChars[randChar]; + letter when randRate > rate + else + AllowedChars[randChar]; evolve(target(1), parent(1), C(0), P(0), rateRands(2), charRands(2)) := - let - mutations[i] := Mutate(parent, P, rateRands[i], charRands[i]) foreach i within 1 ... C; - fitnesses := Fitness(target, mutations); - in - mutations[firstIndexOf(fitnesses, vectorMax(fitnesses))]; + let + mutations[i] := Mutate(parent, P, rateRands[i], charRands[i]) foreach i within 1 ... C; + fitnesses := Fitness(target, mutations); + in + mutations[firstIndexOf(fitnesses, vectorMax(fitnesses))]; diff --git a/Task/Evolutionary-algorithm/SequenceL/evolutionary-algorithm-2.sequencel b/Task/Evolutionary-algorithm/SequenceL/evolutionary-algorithm-2.sequencel index 3dc141f523..75782dae66 100644 --- a/Task/Evolutionary-algorithm/SequenceL/evolutionary-algorithm-2.sequencel +++ b/Task/Evolutionary-algorithm/SequenceL/evolutionary-algorithm-2.sequencel @@ -6,45 +6,45 @@ using namespace std; int main(int argc, char** argv) { - int threads = 0; + int threads = 0; - char* targetString = "METHINKS IT IS LIKE A WEASEL"; - if(argc > 1) targetString = argv[1]; - int C = 100; - if(argc > 2) C = atoi(argv[2]); - SL_FLOAT P = 0.05; - if(argc > 3) P = atof(argv[3]); - int seed = time(NULL); - if(argc > 4) seed = atoi(argv[4]); + char* targetString = "METHINKS IT IS LIKE A WEASEL"; + if(argc > 1) targetString = argv[1]; + int C = 100; + if(argc > 2) C = atoi(argv[2]); + SL_FLOAT P = 0.05; + if(argc > 3) P = atof(argv[3]); + int seed = time(NULL); + if(argc > 4) seed = atoi(argv[4]); - int targetDims[] = {strlen(targetString), 0}; - Sequence target((void*)targetString, targetDims); + int targetDims[] = {strlen(targetString), 0}; + Sequence target((void*)targetString, targetDims); - sl_init(threads); + sl_init(threads); - Sequence parent; - Sequence newParent; - Sequence parentRands; - sl_create(seed++, 1, 27, target.size(), threads, parentRands); - sl_initializeParent(parentRands, threads, parent); + Sequence parent; + Sequence newParent; + Sequence parentRands; + sl_create(seed++, 1, 27, target.size(), threads, parentRands); + sl_initializeParent(parentRands, threads, parent); - Sequence< Sequence > charRands; - Sequence< Sequence > rateRands; + Sequence< Sequence > charRands; + Sequence< Sequence > rateRands; - cout << "Start:\t" << parent << endl; - for(int i = 1; !(parent == target); i++) - { - sl_create(seed++, 1, 27, C, target.size(), threads, charRands); - sl_create(seed++, 0.0, 1.0, C, target.size(), threads, rateRands); + cout << "Start:\t" << parent << endl; + for(int i = 1; !(parent == target); i++) + { + sl_create(seed++, 1, 27, C, target.size(), threads, charRands); + sl_create(seed++, 0.0, 1.0, C, target.size(), threads, rateRands); - sl_evolve(target, parent, C, P, rateRands, charRands, threads, newParent); - parent = newParent; + sl_evolve(target, parent, C, P, rateRands, charRands, threads, newParent); + parent = newParent; - cout << "#" << i << ":\t" << parent << endl; - } - cout << "End:\t" << parent << endl; + cout << "#" << i << ":\t" << parent << endl; + } + cout << "End:\t" << parent << endl; - sl_done(); + sl_done(); - return 0; + return 0; } diff --git a/Task/Evolutionary-algorithm/Tcl/evolutionary-algorithm-1.tcl b/Task/Evolutionary-algorithm/Tcl/evolutionary-algorithm-1.tcl index 30d954617d..98e4050b03 100644 --- a/Task/Evolutionary-algorithm/Tcl/evolutionary-algorithm-1.tcl +++ b/Task/Evolutionary-algorithm/Tcl/evolutionary-algorithm-1.tcl @@ -21,7 +21,7 @@ proc fitness s { global target set count 0 foreach c1 $s c2 $target { - if {$c1 eq $c2} {incr count} + if {$c1 eq $c2} {incr count} } return [expr {$count/double([llength $target])}] } @@ -32,14 +32,14 @@ proc mutateRate {parent} { proc mutate {rate} { global charset parent foreach c $parent { - lappend result [expr {rand() <= $rate ? randchar($charset) : $c}] + lappend result [expr {rand() <= $rate ? randchar($charset) : $c}] } return $result } proc que {} { global iterations parent puts [format "#%-4i, fitness %4.1f%%, '%s'" \ - $iterations [expr {[fitness $parent]*100}] [join $parent {}]] + $iterations [expr {[fitness $parent]*100}] [join $parent {}]] } while {$parent ne $target} { @@ -47,7 +47,7 @@ while {$parent ne $target} { if {!([incr iterations] % 100)} que set copies [list [list $parent [fitness $parent]]] for {set i 0} {$i < $C} {incr i} { - lappend copies [list [set copy [mutate $rate]] [fitness $copy]] + lappend copies [list [set copy [mutate $rate]] [fitness $copy]] } set parent [lindex [lsort -real -decreasing -index 1 $copies] 0 0] } diff --git a/Task/Evolutionary-algorithm/Tcl/evolutionary-algorithm-2.tcl b/Task/Evolutionary-algorithm/Tcl/evolutionary-algorithm-2.tcl index 0a794b47c6..c6f4858a44 100644 --- a/Task/Evolutionary-algorithm/Tcl/evolutionary-algorithm-2.tcl +++ b/Task/Evolutionary-algorithm/Tcl/evolutionary-algorithm-2.tcl @@ -13,7 +13,7 @@ set C 100 proc fitnessByEquality {target s} { set count 0 foreach c1 $s c2 $target { - if {$c1 eq $c2} {incr count} + if {$c1 eq $c2} {incr count} } return [expr {$count / double([llength $target])}] } @@ -29,7 +29,7 @@ proc mutationRate {individual} { # Mutate a string at a particular rate (per character) proc mutate {parent rate} { foreach c $parent { - lappend child [expr {rand() <= $rate ? randchar() : $c}] + lappend child [expr {rand() <= $rate ? randchar() : $c}] } return $child } @@ -37,7 +37,7 @@ proc mutate {parent rate} { # Pretty printer proc prettyPrint {iterations parent} { puts [format "#%-4i, fitness %5.1f%%, '%s'" $iterations \ - [expr {[fitness $parent]*100}] [join $parent {}]] + [expr {[fitness $parent]*100}] [join $parent {}]] } # The evolutionary algorithm itself @@ -48,18 +48,18 @@ proc evolve {initialString} { set parent [split $initialString {}] for {set iterations 0} {[fitness $parent] < 1} {incr iterations} { - set rate [mutationRate $parent] + set rate [mutationRate $parent] - if {$iterations % 100 == 0} { - prettyPrint $iterations $parent - } + if {$iterations % 100 == 0} { + prettyPrint $iterations $parent + } - set copies [list [list $parent [fitness $parent]]] - for {set i 0} {$i < $C} {incr i} { - lappend copies [list \ - [set copy [mutate $parent $rate]] [fitness $copy]] - } - set parent [lindex [lsort -real -decreasing -index 1 $copies] 0 0] + set copies [list [list $parent [fitness $parent]]] + for {set i 0} {$i < $C} {incr i} { + lappend copies [list \ + [set copy [mutate $parent $rate]] [fitness $copy]] + } + set parent [lindex [lsort -real -decreasing -index 1 $copies] 0 0] } puts "" prettyPrint $iterations $parent diff --git a/Task/Evolutionary-algorithm/VBScript/evolutionary-algorithm.vb b/Task/Evolutionary-algorithm/VBScript/evolutionary-algorithm.vbs similarity index 100% rename from Task/Evolutionary-algorithm/VBScript/evolutionary-algorithm.vb rename to Task/Evolutionary-algorithm/VBScript/evolutionary-algorithm.vbs diff --git a/Task/Evolutionary-algorithm/Zig/evolutionary-algorithm.zig b/Task/Evolutionary-algorithm/Zig/evolutionary-algorithm.zig new file mode 100644 index 0000000000..46c9e63f24 --- /dev/null +++ b/Task/Evolutionary-algorithm/Zig/evolutionary-algorithm.zig @@ -0,0 +1,114 @@ +const std = @import("std"); +const math = std.math; +const print = std.debug.print; + +pub fn main() !void { + const target = "METHINKS IT IS LIKE A WEASEL"; + const copies: usize = 100; + const mutation_rate: u32 = 20; // 1/20 = 0.05 = 5% + + var prng = std.Random.DefaultPrng.init(@as(u64, @intCast(std.time.milliTimestamp()))); + const rng = prng.random(); + + // Generate first sentence, mutating each character + const start = try mutate(rng, target, 1, std.heap.page_allocator); // 1/1 = 1 = 100% + + print("{s}\n", .{target}); + print("{s}\n", .{start}); + + _ = try evolve(rng, target, start, copies, mutation_rate, std.heap.page_allocator); +} + +/// Evolution algorithm +/// +/// Evolves `parent` to match `target`. Returns the number of evolutions performed. +fn evolve( + rng: std.Random, + target: []const u8, + parent: []const u8, + copies: usize, + mutation_rate: u32, + allocator: std.mem.Allocator, +) !usize { + var counter: usize = 0; + var parent_fitness: usize = target.len + 1; + var current_parent = try allocator.dupe(u8, parent); + defer allocator.free(current_parent); + + while (true) { + counter += 1; + + var best_fitness: usize = std.math.maxInt(usize); + const best_sentence = try allocator.alloc(u8, target.len); + + for (0..copies) |_| { + // Copy and mutate a new sentence + const sentence = try mutate(rng, current_parent, mutation_rate, allocator); + defer allocator.free(sentence); + + // Find the fitness of the new mutation + const current_fitness = fitness(target, sentence); + + if (current_fitness < best_fitness) { + best_fitness = current_fitness; + @memcpy( best_sentence, sentence); + } + } + + // If the best mutation of this generation is better than `parent` then "the fittest + // survives" and the next parent becomes the best of this generation. + if (best_fitness < parent_fitness) { + allocator.free(current_parent); + current_parent = best_sentence; + parent_fitness = best_fitness; + print("{s} : generation {} with fitness {}\n", .{ current_parent, counter, best_fitness }); + + if (best_fitness == 0) { + return counter; + } + } else { + allocator.free(best_sentence); + } + } +} + +/// Computes the fitness of a sentence against a target string, returning the number of +/// incorrect characters. +fn fitness(target: []const u8, sentence: []const u8) usize { + var count: usize = 0; + for (sentence, 0..) |c, i| { + if (c != target[i]) { + count += 1; + } + } + return count; +} + +/// Mutation algorithm. +/// +/// It mutates each character of a string, according to a `mutation_rate`. +fn mutate( + rng: std.Random, + sentence: []const u8, + mutation_rate: u32, + allocator: std.mem.Allocator, +) ![]u8 { + var result = try allocator.alloc(u8, sentence.len); + + for (sentence, 0..) |c, i| { + if (rng.int(u32) % mutation_rate == 0) { + result[i] = randomChar(rng); + } else { + result[i] = c; + } + } + + return result; +} + +/// Generates a random letter or space. +fn randomChar(rng: std.Random) u8 { + // Returns a value in the range [A, Z] + an extra slot for the space character. + const c = rng.intRangeAtMost(u8, 'A', 'Z' + 1); + return if (c == 'Z' + 1) ' ' else c; +} diff --git a/Task/Evolutionary-algorithm/Zkl/evolutionary-algorithm.zkl b/Task/Evolutionary-algorithm/Zkl/evolutionary-algorithm.zkl index 67c2e69115..0b9d38526e 100644 --- a/Task/Evolutionary-algorithm/Zkl/evolutionary-algorithm.zkl +++ b/Task/Evolutionary-algorithm/Zkl/evolutionary-algorithm.zkl @@ -9,6 +9,6 @@ fcn mutate(s){ s.apply(fcn(c){ if((0.0).random(1) < P) rnd() else c }) } parent := target.len().pump(String,rnd); // random string of "A..Z " gen:=0; do{ // mutate C copies of parent and pick the fittest parent = (0).pump(C,List,T(Void,parent),mutate) - .reduce(fcn(a,b){ if(fitness(a) - constant U0 = 0, - U1 = 1 +constant U0 = 0, + U1 = 1 - integer count = 0 +integer count = 0 - procedure baz() - count += 1 - if count=1 then - throw(U0,{{"any",{{"thing"},"you"}},"like"}) - else - throw(U1) - end if - end procedure +procedure baz() + count += 1 + if count=1 then + throw(U0,{{"any",{{"thing"},"you"}},"like"}) + else + throw(U1) + end if +end procedure - procedure bar() - baz() - end procedure +procedure bar() + baz() +end procedure - procedure foo() - for i=1 to 2 do - try - bar() - catch e - if e[E_CODE]=U0 then - ?e[E_USER] - else - throw(e) -- (terminates) - end if - end try - puts(1,"still running...\n") - end for - puts(1,"not still running...\n") - end procedure +procedure foo() + for i=1 to 2 do + try + bar() + catch e + if e[E_CODE]=U0 then + ?e[E_USER] + else + throw(e) -- (terminates) + end if + end try + puts(1,"still running...\n") + end for + puts(1,"not still running...\n") +end procedure - foo() - + print obj + print @"no exception" + end try + + catch ( e ) // handle exception + print : print @"" + print e + end catch + + finally // finally is always executed + print : print @"" + + // ... cleanup + + end finally +end fn + +fn DoSomething + +HandleEvents diff --git a/Task/Exceptions/FutureBasic/exceptions-2.basic b/Task/Exceptions/FutureBasic/exceptions-2.basic new file mode 100644 index 0000000000..203d2eb6c3 --- /dev/null +++ b/Task/Exceptions/FutureBasic/exceptions-2.basic @@ -0,0 +1,15 @@ +void local fn ThrowException + ExceptionRef e = fn ExceptionWithName( @"Oops!", @"Something went wrong", NULL ) + + try + throw e + end try + + catch (e) + print fn ExceptionName( e ), fn ExceptionReason( e ) + end catch +end fn + +fn ThrowException + +HandleEvents diff --git a/Task/Exceptions/Julia/exceptions.julia b/Task/Exceptions/Julia/exceptions.jl similarity index 100% rename from Task/Exceptions/Julia/exceptions.julia rename to Task/Exceptions/Julia/exceptions.jl diff --git a/Task/Exceptions/Kotlin/exceptions.kotlin b/Task/Exceptions/Kotlin/exceptions.kts similarity index 100% rename from Task/Exceptions/Kotlin/exceptions.kotlin rename to Task/Exceptions/Kotlin/exceptions.kts diff --git a/Task/Exceptions/Langur/exceptions-1.langur b/Task/Exceptions/Langur/exceptions-1.langur index a61a70b482..d9858c6b98 100644 --- a/Task/Exceptions/Langur/exceptions-1.langur +++ b/Task/Exceptions/Langur/exceptions-1.langur @@ -1,7 +1,7 @@ throw "not a math exception" -catch[.e] { - if .e'cat == "math" { +catch[e] { + if e'cat == "math" { # change result... } else { # rethrow the exception diff --git a/Task/Exceptions/Langur/exceptions-3.langur b/Task/Exceptions/Langur/exceptions-3.langur index e3e28e19f6..6a5d424c46 100644 --- a/Task/Exceptions/Langur/exceptions-3.langur +++ b/Task/Exceptions/Langur/exceptions-3.langur @@ -1,3 +1,3 @@ -val .safediv = fn(.x, .y) { .x / .y ; catch : 0 } -.safediv(7, 7) # 1 -.safediv(7, 0) # 0 +val safediv = fn(x number, y number) { x / y ; catch : 0 } +safediv(7, 7) # 1 +safediv(7, 0) # 0 diff --git a/Task/Exceptions/Lua/exceptions-2.lua b/Task/Exceptions/Lua/exceptions-2.lua index 9590ae5df0..064945f28b 100644 --- a/Task/Exceptions/Lua/exceptions-2.lua +++ b/Task/Exceptions/Lua/exceptions-2.lua @@ -6,6 +6,8 @@ end -- 'status' is false if 'throw_error' threw an error -- otherwise, when everything went well, it will be true. --- 'errmsg' contains the error message, plus filename and line number of where the error occured -status, errmsg = pcall(throw_error) +-- 'errmsg' contains the error message, plus filename +-- and line number of where the error occurred + +local status, errmsg = pcall(throw_error) print("errmsg = ", errmsg) diff --git a/Task/Exceptions/Lua/exceptions-3.lua b/Task/Exceptions/Lua/exceptions-3.lua index b2db587ba0..ed58b6092d 100644 --- a/Task/Exceptions/Lua/exceptions-3.lua +++ b/Task/Exceptions/Lua/exceptions-3.lua @@ -1,8 +1,10 @@ -function throw_error_with_argment(argument) - error(string.format("Whoops! argument = %s", argument)) +function throw_error_with_arg(arg) + error(string.format("Whoops! argument = %s", arg)) -- won't ever appear, due to previous error() call return "hello!" end -status, errmsg = pcall(throw_error_with_argment, "foobar 123") -print("errmsg = ", errmsg) +local status, errmsg = pcall(throw_error_with_arg, "foobar 123") +if (status ~= 0) then + print("errmsg = ", errmsg) +end diff --git a/Task/Exceptions/Lua/exceptions-4.lua b/Task/Exceptions/Lua/exceptions-4.lua index f182968d75..fc6c18b0d0 100644 --- a/Task/Exceptions/Lua/exceptions-4.lua +++ b/Task/Exceptions/Lua/exceptions-4.lua @@ -1,6 +1,10 @@ -function throw_error_with_argment(argument) +function throw_error_with_arg(arg) return "hello!" end -status, errmsg = pcall(throw_error_with_argment, "foobar 123") -print("errmsg = ", errmsg) +local status, result = pcall(throw_error_with_arg, "foobar 123") +if (status ~= 0) + print("function returned ", result, ", but had errors.") +else + print("result = ", result) +end diff --git a/Task/Exceptions/OCaml/exceptions-1.ocaml b/Task/Exceptions/OCaml/exceptions-1.ml similarity index 100% rename from Task/Exceptions/OCaml/exceptions-1.ocaml rename to Task/Exceptions/OCaml/exceptions-1.ml diff --git a/Task/Exceptions/OCaml/exceptions-2.ocaml b/Task/Exceptions/OCaml/exceptions-2.ml similarity index 100% rename from Task/Exceptions/OCaml/exceptions-2.ocaml rename to Task/Exceptions/OCaml/exceptions-2.ml diff --git a/Task/Exceptions/OCaml/exceptions-3.ocaml b/Task/Exceptions/OCaml/exceptions-3.ml similarity index 100% rename from Task/Exceptions/OCaml/exceptions-3.ocaml rename to Task/Exceptions/OCaml/exceptions-3.ml diff --git a/Task/Exceptions/PascalABC.NET/exceptions-1.pas b/Task/Exceptions/PascalABC.NET/exceptions-1.pas new file mode 100644 index 0000000000..3234ceef1c --- /dev/null +++ b/Task/Exceptions/PascalABC.NET/exceptions-1.pas @@ -0,0 +1 @@ +type MyException = class(Exception) end; diff --git a/Task/Exceptions/PascalABC.NET/exceptions-2.pas b/Task/Exceptions/PascalABC.NET/exceptions-2.pas new file mode 100644 index 0000000000..d48f94c6ed --- /dev/null +++ b/Task/Exceptions/PascalABC.NET/exceptions-2.pas @@ -0,0 +1 @@ +raise new MyException; diff --git a/Task/Exceptions/PascalABC.NET/exceptions-3.pas b/Task/Exceptions/PascalABC.NET/exceptions-3.pas new file mode 100644 index 0000000000..15454868bd --- /dev/null +++ b/Task/Exceptions/PascalABC.NET/exceptions-3.pas @@ -0,0 +1,6 @@ +try + ... +except + on e: MyException do + statement +end; diff --git a/Task/Empty-program/BootBASIC/empty-program.basic b/Task/Exceptions/Phix/exceptions-3.phix similarity index 100% rename from Task/Empty-program/BootBASIC/empty-program.basic rename to Task/Exceptions/Phix/exceptions-3.phix diff --git a/Task/Exceptions/Pluto/exceptions.pluto b/Task/Exceptions/Pluto/exceptions.pluto new file mode 100644 index 0000000000..654a1a1a78 --- /dev/null +++ b/Task/Exceptions/Pluto/exceptions.pluto @@ -0,0 +1,22 @@ +local function get_day_no(day) + -- Throws an error if day is invalid. + return switch day:lower() do + case "monday" -> 1 + case "tuesday" -> 2 + case "wednesday" -> 3 + case "thursday" -> 4 + case "friday" -> 5 + case "saturday" -> 6 + case "sunday" -> 7 + default -> error($"'{day}' is not a valid day in English.") + end +end + +for {"thursday", "jeudi"} as day do + local ok, res = pcall(get_day_no, day) + if ok then + print($"'{day}' is day number {res}") + else + print(res) + end +end diff --git a/Task/Exceptions/PowerShell/exceptions-1.psh b/Task/Exceptions/PowerShell/exceptions-1.ps1 similarity index 100% rename from Task/Exceptions/PowerShell/exceptions-1.psh rename to Task/Exceptions/PowerShell/exceptions-1.ps1 diff --git a/Task/Exceptions/PowerShell/exceptions-2.psh b/Task/Exceptions/PowerShell/exceptions-2.ps1 similarity index 100% rename from Task/Exceptions/PowerShell/exceptions-2.psh rename to Task/Exceptions/PowerShell/exceptions-2.ps1 diff --git a/Task/Exceptions/PowerShell/exceptions-3.psh b/Task/Exceptions/PowerShell/exceptions-3.ps1 similarity index 100% rename from Task/Exceptions/PowerShell/exceptions-3.psh rename to Task/Exceptions/PowerShell/exceptions-3.ps1 diff --git a/Task/Exceptions/PowerShell/exceptions-4.psh b/Task/Exceptions/PowerShell/exceptions-4.ps1 similarity index 100% rename from Task/Exceptions/PowerShell/exceptions-4.psh rename to Task/Exceptions/PowerShell/exceptions-4.ps1 diff --git a/Task/Exceptions/REXX/exceptions.rexx b/Task/Exceptions/REXX/exceptions.rexx index 836b4ea7b9..50931581b8 100644 --- a/Task/Exceptions/REXX/exceptions.rexx +++ b/Task/Exceptions/REXX/exceptions.rexx @@ -1,13 +1,13 @@ -/*REXX program demonstrates handling an exception (negative #); catching is via a label.*/ - do j=9 by -5 - say 'the square root of ' j " is " sqrt(j) - end /*j*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); h=d+6; m.=9 - numeric digits; numeric form; if x<0 then signal .sqrtNeg - parse value format(x, 2, 1, , 0) 'E0' with g 'E' _ .; g=g * .5'e'_ % 2 - do j=0 while h>9; m.j=h; h=h%2 + 1; end /*j*/ - do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g) * .5; end /*k*/ - numeric digits d; return g/1 -.sqrtNeg: say 'illegal SQRT argument (argument is negative):' x; exit 13 +-- 25 Apr 2026 +include Setting + +say 'EXCEPTIONS' +say version +say +say 'Square root of 10 is' SqRt(10)/1 +say 'Square root of 0 is' SqRt(0) +say 'Square root of -1 is' SqRt(-1) +exit + +-- Abend; Sqrt +include Math diff --git a/Task/Exceptions/Rust/exceptions.rust b/Task/Exceptions/Rust/exceptions.rs similarity index 100% rename from Task/Exceptions/Rust/exceptions.rust rename to Task/Exceptions/Rust/exceptions.rs diff --git a/Task/Exceptions/Rye/exceptions.rye b/Task/Exceptions/Rye/exceptions.rye new file mode 100644 index 0000000000..2e2e54c6b4 --- /dev/null +++ b/Task/Exceptions/Rye/exceptions.rye @@ -0,0 +1,4 @@ +str: "abc" +num: 5 +try { 123 + str } |is-error .either { "error" } { print str } +try { 123 + num } |is-error .either { "error" } { print num } diff --git a/Task/Exceptions/Scheme/exceptions.ss b/Task/Exceptions/Scheme/exceptions.scm similarity index 100% rename from Task/Exceptions/Scheme/exceptions.ss rename to Task/Exceptions/Scheme/exceptions.scm diff --git a/Task/Exceptions/Tcl/exceptions.tcl b/Task/Exceptions/Tcl/exceptions-1.tcl similarity index 100% rename from Task/Exceptions/Tcl/exceptions.tcl rename to Task/Exceptions/Tcl/exceptions-1.tcl diff --git a/Task/Exceptions/Tcl/exceptions-2.tcl b/Task/Exceptions/Tcl/exceptions-2.tcl new file mode 100644 index 0000000000..5086244b35 --- /dev/null +++ b/Task/Exceptions/Tcl/exceptions-2.tcl @@ -0,0 +1,26 @@ +set f "non-existent-file.txt" + +try { + puts "try begin" + + set fd [open $f "r" ] + + set contents [read $fd] + + puts "try end" + +} on error { results options } { + puts stderr "results: $results" + + foreach {opt val} $options { + puts stderr "options:\t$opt $val" + + } +} +puts "after try block" + +if {[info exists contents] } { + puts "$contents" +} else { + puts stderr "no contents read" +} diff --git a/Task/Exceptions/Uiua/exceptions.uiua b/Task/Exceptions/Uiua/exceptions.uiua new file mode 100644 index 0000000000..20d6fd1c37 --- /dev/null +++ b/Task/Exceptions/Uiua/exceptions.uiua @@ -0,0 +1,2 @@ +⍣(⋕|0) "123" # parses okay +⍣(⋕|0) "notanumber" # supplies 0 on error diff --git a/Task/Executable-library/Ada/executable-library-1.ada b/Task/Executable-library/Ada/executable-library-1.adb similarity index 100% rename from Task/Executable-library/Ada/executable-library-1.ada rename to Task/Executable-library/Ada/executable-library-1.adb diff --git a/Task/Executable-library/Ada/executable-library-2.ada b/Task/Executable-library/Ada/executable-library-2.adb similarity index 100% rename from Task/Executable-library/Ada/executable-library-2.ada rename to Task/Executable-library/Ada/executable-library-2.adb diff --git a/Task/Executable-library/Ada/executable-library-3.ada b/Task/Executable-library/Ada/executable-library-3.adb similarity index 100% rename from Task/Executable-library/Ada/executable-library-3.ada rename to Task/Executable-library/Ada/executable-library-3.adb diff --git a/Task/Executable-library/Ada/executable-library-4.ada b/Task/Executable-library/Ada/executable-library-4.adb similarity index 100% rename from Task/Executable-library/Ada/executable-library-4.ada rename to Task/Executable-library/Ada/executable-library-4.adb diff --git a/Task/Executable-library/FreeBASIC/executable-library-1.basic b/Task/Executable-library/FreeBASIC/executable-library-1.basic new file mode 100644 index 0000000000..9999f103b4 --- /dev/null +++ b/Task/Executable-library/FreeBASIC/executable-library-1.basic @@ -0,0 +1,37 @@ +Function hailstone(number As Uinteger) As Uinteger + Dim As Uinteger count = 1 + + While number <> 1 + If (number And 1) = 1 Then + number += number Shr 1 + 1 + count += 2 + Else + number Shr= 1 + count += 1 + End If + Wend + Return count +End Function + +Sub Main() + Dim As Uinteger seqlen + seqlen = hailstone(27) + Print "Sequence length for 27 is "; seqlen + + Dim maxlen As uInteger = 0 + Dim maxnum As uInteger = 0 + For number As Uinteger = 2 To 100000 + seqlen = hailstone(number) + If seqlen > maxlen Then + maxlen = seqlen + maxnum = number + End If + Next + Print "The number with the longest hailstone sequence is "; maxnum + Print "Its sequence length is "; maxlen + Print +End Sub + +Main() + +Sleep diff --git a/Task/Executable-library/FreeBASIC/executable-library-2.basic b/Task/Executable-library/FreeBASIC/executable-library-2.basic new file mode 100644 index 0000000000..3a5a72c7a9 --- /dev/null +++ b/Task/Executable-library/FreeBASIC/executable-library-2.basic @@ -0,0 +1,23 @@ +Declare Function hailstone Alias "hailstone" (Byval arg As Uinteger) As Uinteger + +Dim Shared freq(351) As Uinteger + +For number As Uinteger = 2 To 100000 + Dim seqlen As Uinteger = hailstone(number) + freq(seqlen) += 1 +Next + +Dim max As Uinteger = 0 +Dim mostcommon As Uinteger + +For i As Uinteger = 0 To 351 + If freq(i) > max Then + max = freq(i) + mostcommon = i + End If +Next + +Print "The most common sequence length is "; mostcommon +Print "It occurs "; max; " times" + +Sleep diff --git a/Task/Executable-library/J/executable-library-1.j b/Task/Executable-library/J/executable-library-1.j index 715f13ff13..d81fc19c6d 100644 --- a/Task/Executable-library/J/executable-library-1.j +++ b/Task/Executable-library/J/executable-library-1.j @@ -3,10 +3,10 @@ hailseq=: -:`(1 3&p.)@.(2&|) ^:(1 ~: ]) ^:a:"0 9!:29]1 9!:27'main 0' main=:3 :0 - smoutput 'Hailstone sequence for the number 27' - smoutput hailseq 27 - smoutput '' - smoutput 'Finding number with longest hailstone sequence which is' - smoutput 'less than 100000 (and finding that sequence length):' - smoutput (I.@(= >./),>./) #@hailseq i.1e5 + echo 'Hailstone sequence for the number 27' + echo hailseq 27 + echo '' + echo 'Finding number with longest hailstone sequence which is' + echo 'less than 100000 (and finding that sequence length):' + echo (I.@(= >./),>./) #@hailseq i.1e5 ) diff --git a/Task/Executable-library/J/executable-library-3.j b/Task/Executable-library/J/executable-library-3.j index 2bb186622c..4f77a3c89e 100644 --- a/Task/Executable-library/J/executable-library-3.j +++ b/Task/Executable-library/J/executable-library-3.j @@ -2,7 +2,7 @@ require '~temp/hailseq.ijs' 9!:29]1 9!:27'main 0' main=:3 :0 - smoutput 'Finding most frequent hailstone sequence length for' - smoutput 'Hailstone sequences for whole numbers less than 100000:' - smoutput {:{.\:~ (#/.~,.~.) #@hailseq }.i.1e5 + echo 'Finding most frequent hailstone sequence length for' + echo 'Hailstone sequences for whole numbers less than 100000:' + echo {:{.\:~ (#/.~,.~.) #@hailseq }.i.1e5 ) diff --git a/Task/Executable-library/Julia/executable-library.julia b/Task/Executable-library/Julia/executable-library.jl similarity index 100% rename from Task/Executable-library/Julia/executable-library.julia rename to Task/Executable-library/Julia/executable-library.jl diff --git a/Task/Execute-Brain-/ALGOL-68/execute-brain--1.alg b/Task/Execute-Brain-/ALGOL-68/execute-brain--1.alg index c74c21fd7b..6f36b9cea2 100644 --- a/Task/Execute-Brain-/ALGOL-68/execute-brain--1.alg +++ b/Task/Execute-Brain-/ALGOL-68/execute-brain--1.alg @@ -86,11 +86,10 @@ BEGIN # Brain**** -> Algol 68 transpiler # # get the code to transpile and output it as a comment at the start # # of the code # print( ( "CO BF> " ) ); - STRING code list; - read( ( code list, newline ) ); - print( ( newline, code list, newline, "CO", newline ) ); + STRING bf code; + read( ( bf code, newline ) ); + print( ( newline, bf code, newline, "CO", newline ) ); # transpile the code # - generate( code list ) - + generate( bf code ) END diff --git a/Task/Execute-Brain-/Agena/execute-brain-.agena b/Task/Execute-Brain-/Agena/execute-brain-.agena index becfb717b7..626b19af9e 100644 --- a/Task/Execute-Brain-/Agena/execute-brain-.agena +++ b/Task/Execute-Brain-/Agena/execute-brain-.agena @@ -1,89 +1,27 @@ -# Brain**** interpreter +scope # Simple BF interpreter, based on the Lua sample: "Simple meta-implementation using load" + # reads the BF code from stdin, builds an equivalent Agena program and executes it -# execute the Brain**** program in the code string -bf := proc( code :: string ) is - local address := 1; # current data address - local pc := 1; # current position in code - local data := []; # data - initially empty - local input := ""; # user input - initially empty - local bfOperations := # table of operations and their implemntations - [ ">" ~ proc() is inc address, 1 end - , "<" ~ proc() is dec address, 1 end - , "+" ~ proc() is inc data[ address ], 1 end - , "-" ~ proc() is dec data[ address ], 1 end - , "." ~ proc() is io.write( char( data[ address ] ) ) end - , "," ~ proc() is - # get next input character, converted to an integer - while input = "" - do - # no input left - get the next line - input := io.read() - od; - data[ address ] := abs( input[ 1 ] ); - # remove the latest character from the input - if size input < 2 - then - input := "" - else - input := input[ 2 to -1 ] - fi - end - , "[" ~ proc() is - if data[ address ] = 0 - then - # skip to the end of the loop - local depth := 0; - do - inc pc, 1; - if code[ pc ] = "[" - then - inc depth, 1 - elif code[ pc ] = "]" - then - dec depth, 1 - fi - until depth < 0 - fi - end - , "]" ~ proc() is - if data[ address ] <> 0 - then - # skip to the start of the loop - local depth := 0; - do - dec pc, 1; - if code[ pc ] = "[" - then - dec depth, 1 - elif code[ pc ] = "]" - then - inc depth, 1 - fi - until depth < 0 - fi - end - ]; - # execute the operations - ignore anything invalid - while pc <= size code - do - if data[ address ] = null - then - data[ address ] := 0 - fi; - if bfOperations[ code[ pc ] ] <> null - then - bfOperations[ code[ pc ] ]() - fi; - inc pc, 1 - od -end; + local constant bfOp := [ '>' ~ 'ptr +:= 1; ' + , '<' ~ 'ptr -:= 1; ' + , '+' ~ 'mem[ptr] +:= 1; ' + , '-' ~ 'mem[ptr] -:= 1; ' + , '[' ~ 'while mem[ptr] <> 0 do ' + , ']' ~ 'od; ' + , '.' ~ 'io.write(char(mem[ptr])); ' + , ',' ~ 'mem[ptr] := abs(io.read(io.stdin,1) or "\\0"); ' + ]; -# prompt for Brain**** code and execute it, repeating until an empty code string is entered -scope - local code; - do - io.write( "BF> " ); - code := io.read(); - bf( code ) - until code = "" -epocs; + local bfProgram := "local mem := setmetatable([], [ '__index' ~ proc() return 0 end ]);\n" + & "local ptr := 1;\n" + ; + + for line in io.lines() do + for p to size line do + local snippet := bfOp[ line[ p ] ]; + if snippet then bfProgram &:= snippet & "\n" fi + od + od; + + loadstring( bfProgram, "bfCode" )() + +end diff --git a/Task/Execute-Brain-/Arturo/execute-brain--1.arturo b/Task/Execute-Brain-/Arturo/execute-brain--1.arturo index d84f05f32a..b30648cc5a 100644 --- a/Task/Execute-Brain-/Arturo/execute-brain--1.arturo +++ b/Task/Execute-Brain-/Arturo/execute-brain--1.arturo @@ -4,21 +4,21 @@ ; Tape: [0] -DataPointer: new 0 -InstructionPointer: new 0 +DataPointer: 0 +InstructionPointer: 0 ; Look for jumps in Code an register them ; in the Jumps table precomputeJumps: function [][ - vstack: new [] - jumphash: new #[] + vstack: [] + jumphash: #[] instrPointer: 0 while [instrPointer 'vstack ++ instrPointer - else [ + switch command="[" -> 'vstack ++ instrPointer + [ if command="]" [ target: last vstack chop 'vstack @@ -47,36 +47,37 @@ StateIsValid: function [][ interpret: function [].export:[DataPointer,InstructionPointer,Tape][ while [StateIsValid][ command: get split Code InstructionPointer - case [command=] - when? ["+"] -> Tape\[DataPointer]: Tape\[DataPointer]+1 - when? ["-"] -> Tape\[DataPointer]: Tape\[DataPointer]-1 - when? [">"] [ + case command [ + "+" -> Tape\[DataPointer]: Tape\[DataPointer]+1 + "-" -> Tape\[DataPointer]: Tape\[DataPointer]-1 + ">" [ inc 'DataPointer if DataPointer = size Tape -> Tape: Tape ++ 0 ] - when? ["<"] -> dec 'DataPointer - when? ["."] -> prints to :string to :char Tape\[DataPointer] - when? [","][ + "<" -> dec 'DataPointer + "." -> prints to :string to :char Tape\[DataPointer] + "," [ inp: to :integer input "" if inp=13 -> inp: 10 if inp=3 -> panic "something went wrong!" set Tape DataPointer inp ] - when? ["["] -> - if 0 = get Tape DataPointer [ InstructionPointer: new get Jumps InstructionPointer ] + "[" -> + if 0 = get Tape DataPointer [ InstructionPointer: new Jumps\[InstructionPointer] ] - when? ["]"] -> + "]" -> if 0 <> get Tape DataPointer [ - InstructionPointer: new get Jumps InstructionPointer + InstructionPointer: new Jumps\[InstructionPointer] ] + ] inc 'InstructionPointer ] ] Code: "" -if? 1>size arg -> Code: "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>." -else -> Code: read arg\0 +switch 1>size arg -> Code: "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>." + -> Code: read arg\0 CodeLength: size Code Jumps: precomputeJumps diff --git a/Task/Execute-Brain-/AutoIt/execute-brain-.autoit b/Task/Execute-Brain-/AutoIt/execute-brain-.au3 similarity index 100% rename from Task/Execute-Brain-/AutoIt/execute-brain-.autoit rename to Task/Execute-Brain-/AutoIt/execute-brain-.au3 diff --git a/Task/Execute-Brain-/Crystal/execute-brain-.cr b/Task/Execute-Brain-/Crystal/execute-brain-.cr new file mode 100644 index 0000000000..355443e3a0 --- /dev/null +++ b/Task/Execute-Brain-/Crystal/execute-brain-.cr @@ -0,0 +1,33 @@ +def bfrun (code) + code = code.chars + data = Hash(Int32, Int32).new(0) + dp = ip = 0 + jump_to_matching = ->(dir : Int32) { + nest = 0 + while 0 <= ip < code.size + case code[ip] + when '[' then nest += dir + when ']' then nest -= dir + end + break if nest == 0 + ip += dir + end + } + while 0 <= ip < code.size + case code[ip] + when '>' then dp += 1 + when '<' then dp -= 1 + when '+' then data[dp] += 1 + when '-' then data[dp] -= 1 + when '.' then print(data[dp].chr) + when ',' then data[dp] = STDIN.read_char.not_nil!.ord + when '[' then jump_to_matching.call(1) if data[dp] == 0 + when ']' then jump_to_matching.call(-1) if data[dp] != 0 + end + ip += 1 + end +end + +hello = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++." + +bfrun(hello) diff --git a/Task/Execute-Brain-/Delphi/execute-brain-.delphi b/Task/Execute-Brain-/Delphi/execute-brain-.pas similarity index 100% rename from Task/Execute-Brain-/Delphi/execute-brain-.delphi rename to Task/Execute-Brain-/Delphi/execute-brain-.pas diff --git a/Task/Execute-Brain-/EasyLang/execute-brain-.easy b/Task/Execute-Brain-/EasyLang/execute-brain-.easy index 9888328243..35eabaabb8 100644 --- a/Task/Execute-Brain-/EasyLang/execute-brain-.easy +++ b/Task/Execute-Brain-/EasyLang/execute-brain-.easy @@ -1,4 +1,4 @@ -proc exec code$ . . +proc exec code$ . len mem[] 100 dp = 1 code$[] = strchars code$ @@ -54,9 +54,7 @@ func syntax code$ . elif h$ = "]" br -= 1 . - if br < 0 - return 0 - . + if br < 0 : return 0 . return if br = 0 . diff --git a/Task/Execute-Brain-/Factor/execute-brain-.factor b/Task/Execute-Brain-/Factor/execute-brain-.factor index 513f3d3667..2e31e5ce88 100644 --- a/Task/Execute-Brain-/Factor/execute-brain-.factor +++ b/Task/Execute-Brain-/Factor/execute-brain-.factor @@ -1,3 +1,3 @@ -USE: brainf*** +USE: brainfuck -"++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++." run-brainf*** +"++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++." run-brainfuck diff --git a/Task/Execute-Brain-/Fennel/execute-brain-.fennel b/Task/Execute-Brain-/Fennel/execute-brain-.fennel new file mode 100644 index 0000000000..570e80ccae --- /dev/null +++ b/Task/Execute-Brain-/Fennel/execute-brain-.fennel @@ -0,0 +1,34 @@ +(do ;;; Simple BF interpreter, based on the Lua sample: "Simple meta-implementation using load" + ;;; reads the BF code from stdin, builds an equivalent Pluto program and executes it + + (local bf-op { ">" "ptr = ptr + 1" + "<" "ptr = ptr - 1" + "+" "mem[ptr] = mem[ptr] + 1" + "-" "mem[ptr] = mem[ptr] - 1" + "[" "while mem[ptr] ~= 0 do" + "]" "end" + "." "io.write(string.char(mem[ptr]))" + "," "mem[ptr] = string.byte(io.read(1) or \"\\0\")" + } + ) + + (var bf-program (.. "local mem = setmetatable({}, { __index = function() return 0 end })\n" + "local ptr = 1\n" + ) + ) + (each [line (io.lines)] + (for [p 1 (length line)] + (local op (. bf-op (line:sub p p))) + (when op + (set bf-program (.. bf-program op "\n")) + ) + ) + ) + (local (bf-code msg) (load bf-program)) + (if bf-code + (bf-code) + ;else + (error msg) + ) + +) diff --git a/Task/Execute-Brain-/Hare/execute-brain-.hare b/Task/Execute-Brain-/Hare/execute-brain-.hare new file mode 100644 index 0000000000..05d315b116 --- /dev/null +++ b/Task/Execute-Brain-/Hare/execute-brain-.hare @@ -0,0 +1,74 @@ +use fmt; +use fs; +use io; +use os; + +export fn main() void = { + if (len(os::args) != 2) { + fmt::print("Please provide a parameter pointing to a brain**** file.\n")!; + return; + }; + + let program = slurp(os::args[1])!; + let tape: [30000]u8 = [0...]; + let tp: u16 = 0; + defer free(program); + + let matches_k: []size = []; + let matches_v: []size = []; + defer free(matches_k); + defer free(matches_v); + + for (let pp: size = 0; pp < len(program); pp += 1) { + switch (program[pp]) { + case '>' => tp += 1; + case '<' => tp -= 1; + case '+' => tape[tp] += 1; + case '-' => tape[tp] -= 1; + case '.' => io::write(os::stdout, tape[tp..tp+1])!; + case ',' => io::read(os::stdin, tape[tp..tp+1])!; + case '[' => if (tape[tp] == 0) pp = find_match(pp, program, matches_k, matches_v)!; + case ']' => if (tape[tp] != 0) pp = find_match(pp, program, matches_k, matches_v)!; + case => continue; + }; + }; +}; + +fn find_match(pos: size, program: []u8, matches_k: []size, matches_v: []size) (size | !void) = { + for (let i: u16 = 0; i < len(matches_k); i += 1) + if (pos == matches_k[i]) + return matches_v[i]; + let r = pos; + switch (program[pos]) { + case '[' => { + r += 1; + for (let level = 1; level > 0; r += 1) { + switch (program[r]) { + case '[' => level += 1; + case ']' => level -= 1; + case => continue; + }; + }; + }; + case ']' => { + r -= 1; + for (let level = 1; level > 0; r -= 1) { + switch (program[r]) { + case ']' => level += 1; + case '[' => level -= 1; + case => continue; + }; + }; + }; + case => return; + }; + append(matches_k, pos)!; + append(matches_v, r)!; + return r; +}; + +fn slurp(filename: str) ([]u8 | fs::error | io::error) = { + const file = os::open(filename)?; + defer io::close(file)!; + return io::drain(file)?; +}; diff --git a/Task/Execute-Brain-/Julia/execute-brain-.julia b/Task/Execute-Brain-/Julia/execute-brain-.jl similarity index 100% rename from Task/Execute-Brain-/Julia/execute-brain-.julia rename to Task/Execute-Brain-/Julia/execute-brain-.jl diff --git a/Task/Execute-Brain-/Kotlin/execute-brain-.kotlin b/Task/Execute-Brain-/Kotlin/execute-brain-.kts similarity index 100% rename from Task/Execute-Brain-/Kotlin/execute-brain-.kotlin rename to Task/Execute-Brain-/Kotlin/execute-brain-.kts diff --git a/Task/Execute-Brain-/Lua/execute-brain-.lua b/Task/Execute-Brain-/Lua/execute-brain-.lua index 8f2aec0651..422ea849d3 100644 --- a/Task/Execute-Brain-/Lua/execute-brain-.lua +++ b/Task/Execute-Brain-/Lua/execute-brain-.lua @@ -1,24 +1,22 @@ -local funs = { -['>'] = 'ptr = ptr + 1; ', -['<'] = 'ptr = ptr - 1; ', -['+'] = 'mem[ptr] = mem[ptr] + 1; ', -['-'] = 'mem[ptr] = mem[ptr] - 1; ', -['['] = 'while mem[ptr] ~= 0 do ', -[']'] = 'end; ', -['.'] = 'io.write(string.char(mem[ptr])); ', -[','] = 'mem[ptr] = (io.read(1) or "\\0"):byte(); ', +local repl = { + ['>'] = 'ptr = ptr + 1', + ['<'] = 'ptr = ptr - 1', + ['+'] = 'mem[ptr] = mem[ptr] + 1', + ['-'] = 'mem[ptr] = mem[ptr] - 1', + ['['] = 'while mem[ptr] ~= 0 do', + [']'] = 'end', + ['.'] = 'io.write(string.char(mem[ptr]))', + [','] = 'mem[ptr] = (io.read(1) or "\\0"):byte()', } -local prog = [[ +local prog = {[[ local mem = setmetatable({}, { __index = function() return 0 end}) local ptr = 1 -]] +]]} -local source = io.read('*all') - -for p = 1, #source do - local snippet = funs[source:sub(p,p)] - if snippet then prog = prog .. snippet end +local source, i = io.read('*all'), 1 +for char in source:gmatch"[<>+.,%[%]%-]" do + i, prog[i] = i+1, repl[char] end -load(prog)() +load( table.concat(prog, " ") )() diff --git a/Task/Execute-Brain-/Miranda/execute-brain-.miranda b/Task/Execute-Brain-/Miranda/execute-brain-.miranda new file mode 100644 index 0000000000..e1686c7e26 --- /dev/null +++ b/Task/Execute-Brain-/Miranda/execute-brain-.miranda @@ -0,0 +1,83 @@ +#!/usr/bin/mira -exec +main :: [sys_message] +main = (interpret . read . hd . tl) $* + +interpret :: [char]->[sys_message] +interpret prog = msgs where (tape, inp, msgs) = run empty_tape $- (parse prog) + +instr ::= Left | Right | Inc | Dec | Read | Write | Loop [instr] + +run :: tape->[char]->[instr]->(tape,[char],[sys_message]) +run tape inp [] = (tape, inp, []) +run tape inp (instr:instrs) + = (tape'', inp'', sysmsg ++ sysmsgs) + where (tape', inp', sysmsg) = step tape inp instr + (tape'', inp'', sysmsgs) = run tape' inp' instrs + +step :: tape->[char]->instr->(tape,[char],[sys_message]) +step tape inp Left = (left tape, inp, []) +step tape inp Right = (right tape, inp, []) +step tape inp Inc = (apply (+1) tape, inp, []) +step tape inp Dec = (apply (+-1) tape, inp, []) +step tape inp Read = (setval ch tape, inp', []) + where (ch, inp') = getchar inp +step tape inp Write = (tape, inp, [Stdout (decode (val tape):[])]) +step tape inp (Loop prog) = (tape, inp, []), if val tape = 0 + = (tape'', inp'', sysmsgs ++ sysmsgs'), otherwise + where (tape', inp', sysmsgs) = run tape inp prog + (tape'', inp'', sysmsgs') = step tape' inp' (Loop prog) + +getchar :: [char]->(num,[char]) +getchar [] = (0, []) +getchar (x:xs) = (code x, xs) + +parse :: [char] -> [instr] +parse [] = [] +parse instrs + = Left : rest, if tok="<" + = Right : rest, if tok=">" + = Inc : rest, if tok="+" + = Dec : rest, if tok="-" + = Read : rest, if tok="," + = Write : rest, if tok="." + = Loop loop : rest, if hd tok='[' + = rest, otherwise + where (tok, next) = token instrs + rest = parse next + loop = parse (init (tl tok)) + +token :: [char] -> ([char],[char]) +token [] = ([],[]) +token (']':xs) = error "] without [" +token ('[':xs) = ('[':l, rs) where (l, rs) = getloop xs +token (x:xs) = (x:[], xs) + +getloop :: [char] -> ([char],[char]) +getloop = g 0 + where g 0 (']':xs) = ("]", xs) + g n ('[':xs) = ('[':l,rs) where (l,rs) = g (n+1) xs + g n (']':xs) = (']':l,rs) where (l,rs) = g (n-1) xs + g n (x:xs) = (x:l,rs) where (l,rs) = g n xs + g n [] = error "[ without ]" + +tape ::= Tape [num] num [num] + +empty_tape :: tape +empty_tape = Tape [] 0 [] + +left :: tape->tape +left (Tape ls c []) = Tape (c:ls) 0 [] +left (Tape ls c (r:rs)) = Tape (c:ls) r rs + +right :: tape->tape +right (Tape [] c rs) = Tape [] 0 (c:rs) +right (Tape (l:ls) c rs) = Tape ls l (c:rs) + +apply :: (num->num)->tape->tape +apply fn (Tape ls c rs) = Tape ls (fn c mod 256) rs + +val :: tape->num +val (Tape ls c rs) = c + +setval :: num->tape->tape +setval v (Tape ls c rs) = Tape ls v rs diff --git a/Task/Execute-Brain-/Odin/execute-brain-.odin b/Task/Execute-Brain-/Odin/execute-brain-.odin new file mode 100644 index 0000000000..e2898826a1 --- /dev/null +++ b/Task/Execute-Brain-/Odin/execute-brain-.odin @@ -0,0 +1,126 @@ +package bf + +import "core:fmt" +import "core:c/libc" +import "core:os" + +cells_size :: 2000 +getinp : i32 +inp : u8 +main :: proc() { + + // comment out to give a file from command line + // data, ok := os.read_entire_file(os.args[1]) + // assert(ok, "Could not open file") + // defer delete(data) + // input := string(data) + + input := ">+++++++++[<++++++++>-]<.>+++++++[<++++>-]<+.+++++++..+++.[-]>++++++++[<++++>-] <.>+++++++++++[<++++++++>-]<-.--------.+++.------.--------.[-]>++++++++[<++++>- ]<+.[-]++++++++++." + size_input := len(input) + cells : [cells_size]i32 + pointer:=0 + i:=0 + direction := 1 + // moving past non matching [ ] + depth:= 0 + // loop i over input + mainloop: for ; (i <= (size_input - 1) && i >=0); { + inp = input[i] + //fmt.println(i) + switch inp{ + // move pointer right + case '>': + pointer +=1 + if (pointer>cells_size-1){ + pointer=cells_size-1 + } + i += 1 + // move pointer left + case '<': + pointer -=1 + if (pointer<0){ + pointer=0 + } + i += 1 + // increase cells at pointer + case '+': + cells[pointer] = (cells[pointer] + 1) % 256 + i += 1 + // decrease cell at pointer + case '-': + cells[pointer] = (cells[pointer] - 1) % 256 + i += 1 + // output value from cell at pointer + case '.': + res := cells[pointer] + libc.putchar(res) + i += 1 + // input value in cell at pointer + case ',': + getinp= libc.getchar() + fmt.println("input:") + cells[pointer] = getinp + i += 1 + // Jump past the matching ] if the cell at the pointer is 0 + case '[': + // if cell at pointer = 0 + if cells[pointer] == 0 { + // loop until ] + + loop1: for (inp != ']' && depth == 0) { + i +=1 + inp = input[i] + if (i > (size_input-1)){ + // if i > size input [ is unbalanced + fmt.printf("unbalanced loop ") + break mainloop + } + else if (inp == '[') { + depth += 1 + } + else if (inp == ']' && depth != 0) { + depth -= 1 + } + + fmt.println(i) + } + + } // else ignore + else { + i +=1 + } + + case ']': + // Jump back to the matching [ if the cell at the pointer is nonzero + if cells[pointer] != 0 { + + loop2: for (inp!= '[' && depth == 0) { + i -= 1 + inp = input[i] + if (i < 0) + { + fmt.printf("unbalanced loop ") + break mainloop + } + else if (inp == ']') { + depth += 1 + } + else if (inp == '[' && depth != 0) { + depth -= 1 + } + //fmt.println(input[i]) + } + + } + else { + i+=1 + } + // default: move pointer + case : + i +=1 + + } + + } + +} diff --git a/Task/Execute-Brain-/Phix/execute-brain-.phix b/Task/Execute-Brain-/Phix/execute-brain-.phix index c35807b1ce..a59f95828d 100644 --- a/Task/Execute-Brain-/Phix/execute-brain-.phix +++ b/Task/Execute-Brain-/Phix/execute-brain-.phix @@ -1,54 +1,51 @@ -(phixonline)--> - procedure bfi(string pgm) - sequence jumptable = repeat(0,length(pgm)), - loopstack = {}, - data = repeat(0,10) -- size?? - integer skip = 0, ch, loopstart, pc, dp - -- - -- compile (pack/strip comments and link jumps) - -- - for i=1 to length(pgm) do - ch = pgm[i] - switch ch do - case '[': loopstack = append(loopstack,i-skip); - pgm[i-skip] = ch; - case ']': loopstart = loopstack[$]; - loopstack = loopstack[1..-2]; - jumptable[i-skip] = loopstart; - jumptable[loopstart] = i-skip; - fallthrough - case '+','-','<','>',',','.': pgm[i-skip] = ch; - default: skip += 1 - end switch - end for - if length(loopstack) then ?9/0 end if - pgm = pgm[1..-1-skip] +procedure bfi(string pgm) + sequence jumptable = repeat(0,length(pgm)), + loopstack = {}, + data = repeat(0,10) -- size?? + integer skip = 0, ch + -- + -- compile (pack/strip comments and link jumps) + -- + for i=1 to length(pgm) do + ch = pgm[i] + switch ch do + case '[': loopstack = append(loopstack,i-skip); + pgm[i-skip] = ch; + case ']': integer loopstart = loopstack[$]; + loopstack = loopstack[1..-2]; + jumptable[i-skip] = loopstart; + jumptable[loopstart] = i-skip; + fallthrough + case '+','-','<','>',',','.': pgm[i-skip] = ch; + default: skip += 1 + end switch + end for + if length(loopstack) then ?9/0 end if + pgm = pgm[1..-1-skip] - -- - -- main execution loop - -- - pc = 1 - dp = 1 - while pc<=length(pgm) do - ch = pgm[pc] - switch ch do - case '>': dp += 1 if dp>length(data) then dp = 1 end if - case '<': dp -= 1 if dp<1 then dp = length(data) end if - case '+': data[dp] += 1 - case '-': data[dp] -= 1 - case ',': data[dp] = iff(platform()=JS?'?':getc(0)) - case '.': puts(1,data[dp]) - case '[': if data[dp]=0 then pc = jumptable[pc] end if - case ']': if data[dp]!=0 then pc = jumptable[pc] end if - default: ?9/0 - end switch - pc += 1 - end while - end procedure + -- + -- main execution loop + -- + integer pc = 1, dp = 1 + while pc<=length(pgm) do + ch = pgm[pc] + switch ch do + case '>': dp += 1 if dp>length(data) then dp = 1 end if + case '<': dp -= 1 if dp<1 then dp = length(data) end if + case '+': data[dp] += 1 + case '-': data[dp] -= 1 + case ',': data[dp] = iff(platform()=JS?'?':getc(0)) + case '.': puts(1,data[dp]) + case '[': if data[dp]=0 then pc = jumptable[pc] end if + case ']': if data[dp]!=0 then pc = jumptable[pc] end if + default: ?9/0 + end switch + pc += 1 + end while +end procedure - constant bf="++++++++[>++++[>++>++++>+++>+<<<<-]>++>->+>>+[<]<-]>>.>>.+.<.>>.<<<++.>---------.>------.<----.++++++++.>>+.>++.+++." - constant fb="++++++++[>++++[>++>++++>+++>+<<<<-]>++>->+>>+[<]<-]>>.>>.+.<.>>.<<<+++.>---.>------.++++++++.<--.>>+.>++.+++.," +constant bf="++++++++[>++++[>++>++++>+++>+<<<<-]>++>->+>>+[<]<-]>>.>>.+.<.>>.<<<++.>---------.>------.<----.++++++++.>>+.>++.+++." +constant fb="++++++++[>++++[>++>++++>+++>+<<<<-]>++>->+>>+[<]<-]>>.>>.+.<.>>.<<<+++.>---.>------.++++++++.<--.>>+.>++.+++.," - bfi(bf) - bfi(fb) - - with javascript_semantics - constant NOP = 0b000_00000, -- no operation - LDA = 0b001_00000, -- load accumulator, a := memory [xxxxx] - STA = 0b010_00000, -- store accumulator, memory [xxxxx] := a - ADD = 0b011_00000, -- add, a := a + memory [xxxxx] - SUB = 0b100_00000, -- subtract, a := a – memory [xxxxx] - BRZ = 0b101_00000, -- branch on zero, if a = 0 then goto xxxxx - JMP = 0b110_00000, -- jump, goto xxxxx - STP = 0b111_00000, -- stop - OP = 0b111_00000, -- operator mask - ARG = 0b000_11111 -- memory location (0 based) +with javascript_semantics +constant NOP = 0b000_00000, -- no operation + LDA = 0b001_00000, -- load accumulator, a := memory [xxxxx] + STA = 0b010_00000, -- store accumulator, memory [xxxxx] := a + ADD = 0b011_00000, -- add, a := a + memory [xxxxx] + SUB = 0b100_00000, -- subtract, a := a – memory [xxxxx] + BRZ = 0b101_00000, -- branch on zero, if a = 0 then goto xxxxx + JMP = 0b110_00000, -- jump, goto xxxxx + STP = 0b111_00000, -- stop + OP = 0b111_00000, -- operator mask + ARG = 0b000_11111 -- memory location (0 based) - procedure execute(string name, sequence program) - sequence memory = deep_copy(program) - integer pc = 1, a = 0 - while true do - integer ppc = memory[pc], - op = and_bitsu(ppc,OP), - arg = and_bits(ppc,ARG)+1 - pc += 1 - switch op do - case NOP: break - case LDA: a = memory[arg] - case STA: memory[arg] = a - case ADD: a = and_bitsu(a+memory[arg],#FF) - case SUB: a = and_bitsu(a-memory[arg],#FF) - case BRZ: if a=0 then pc = arg end if - case JMP: pc = arg - case STP: printf(1,"%12s: %3d\n",{name,a}) - return - end switch - end while - end procedure +procedure execute(string name, sequence program) + sequence memory = deep_copy(program) + integer pc = 1, a = 0 + while true do + integer ppc = memory[pc], + op = and_bitsu(ppc,OP), + arg = and_bits(ppc,ARG)+1 + pc += 1 + switch op do + case NOP: break + case LDA: a = memory[arg] + case STA: memory[arg] = a + case ADD: a = and_bitsu(a+memory[arg],#FF) + case SUB: a = and_bitsu(a-memory[arg],#FF) + case BRZ: if a=0 then pc = arg end if + case JMP: pc = arg + case STP: printf(1,"%12s: %3d\n",{name,a}) + return + end switch + end while +end procedure - execute("2+2",{LDA+3, ADD+4, STP, 2,2}) - execute("7*8",{LDA+12, ADD+10, STA+12, LDA+11, SUB+13, STA+11, BRZ+8, JMP+0, - LDA+12, STP, 8,7,0,1}) - execute("fibonacci",{LDA+14, STA+15, ADD+13, STA+14, LDA+15, STA+13, LDA+16, - SUB+17, BRZ+11, STA+16, JMP+0, LDA+14, STP, 1,1,0,8,1}) - execute("linkedList",{LDA+13, ADD+15, STA+5, ADD+16, STA+7, NOP, STA+14, NOP, - BRZ+11, STA+15, JMP+0, LDA+14, STP, LDA+0, 0,28,1,0,0, - 0,6,0,2,26,5,20,3,30,1,22,4,24}) - execute("prisoner",{NOP, NOP, STP, 0, LDA+3, SUB+29, BRZ+18, LDA+3, STA+29, - BRZ+14, LDA+1, ADD+31, STA+1, JMP+2, LDA+0, ADD+31, STA+0, - JMP+2, LDA+3, STA+29, LDA+1, ADD+30, ADD+3, STA+1, LDA+0, - ADD+30, ADD+3, STA+0, JMP+2, 0, 1, 3}) - -- subtractions yielding negative results - execute("0-255",{LDA+3,SUB+4,STP, 0,255}) - execute("0-1",{LDA+3, SUB+4, STP, 0,1}) - -- overflow on addition - execute("1+255",{LDA+3, ADD+4, STP, 1, 255}) - n ) + [ 1 ] is LDA ( --> n ) + [ 2 ] is STA ( --> n ) + [ 3 ] is ADD ( --> n ) + [ 4 ] is SUB ( --> n ) + [ 5 ] is BRZ ( --> n ) + [ 6 ] is JMP ( --> n ) + [ 7 ] is STP ( --> n ) + + [ 0 ] is DATA ( --> n ) + [ 0 ] is -- ( --> n ) + + [ stack 0 ] is acc ( --> s ) + [ stack 0 ] is ip ( --> s ) + [ stack false ] is flag ( --> n ) + + [ 0 ip replace 0 32 of ] is computer/zero ( --> [ ) + + [ 255 & swap 5 << | + swap ip share poke + 1 ip tally ] is , ( [ --> [ ) + + [ drop ] is nop ( [ n --> [ ) + + [ dip dup peek acc replace ] is lda ( [ n --> [ ) + + [ acc share unrot poke ] is sta ( [ n --> [ ) + + [ dip dup peek + acc take + 255 & acc put ] is add ( [ n --> [ ) + + [ dip dup peek negate + acc take + 255 & acc put ] is sub ( [ n --> [ ) + + [ acc share iff drop done + ip replace ] is brz ( [ n --> [ ) + + [ ip replace ] is jmp ( [ n --> [ ) + + [ drop true flag replace ] is stp ( [ n --> [ ) + + [ false flag replace + 0 acc replace + 0 ip replace + [ dup ip share peek + 1 ip tally + dup 31 & swap 5 >> + [ table + nop lda sta add + sub brz jmp stp ] do + flag share until ] + drop + acc share + say "acc = " dup echo + dup 128 & iff + [ say " or " + 127 ~ | echo ] + else drop cr ] is execute ( [ --> ) + + cr say " 2+2: " + computer/zero + ( 00 ) LDA 03 , + ( 01 ) ADD 04 , + ( 02 ) STP -- , + ( 03 ) DATA 2 , + ( 04 ) DATA 2 , + execute + cr say " 7*8: " + computer/zero + ( 00 ) LDA 12 , + ( 01 ) ADD 10 , + ( 02 ) STA 12 , + ( 03 ) LDA 11 , + ( 04 ) SUB 13 , + ( 05 ) STA 11 , + ( 06 ) BRZ 08 , + ( 07 ) JMP 00 , + ( 08 ) LDA 12 , + ( 09 ) STP -- , + ( 10 ) DATA 8 , + ( 11 ) DATA 7 , + ( 12 ) DATA 0 , + ( 13 ) DATA 1 , + execute + cr say " Fibonacci: " + computer/zero + ( 00 ) LDA 14 , + ( 01 ) STA 15 , + ( 02 ) ADD 13 , + ( 03 ) STA 14 , + ( 04 ) LDA 15 , + ( 05 ) STA 13 , + ( 06 ) LDA 16 , + ( 07 ) SUB 17 , + ( 08 ) BRZ 11 , + ( 09 ) STA 16 , + ( 10 ) JMP 00 , + ( 11 ) LDA 14 , + ( 12 ) STP -- , + ( 13 ) DATA 1 , + ( 14 ) DATA 1 , + ( 15 ) DATA 0 , + ( 16 ) DATA 8 , + ( 17 ) DATA 1 , + execute + cr say "linked list: " + computer/zero + ( 00 ) LDA 13 , + ( 01 ) ADD 15 , + ( 02 ) STA 05 , + ( 03 ) ADD 16 , + ( 04 ) STA 07 , + ( 05 ) NOP -- , + ( 06 ) STA 14 , + ( 07 ) NOP -- , + ( 08 ) BRZ 11 , + ( 09 ) STA 15 , + ( 10 ) JMP 00 , + ( 11 ) LDA 14 , + ( 12 ) STP -- , + ( 13 ) LDA 00 , + ( 14 ) DATA 0 , + ( 15 ) DATA 28 , + ( 16 ) DATA 1 , + ( 17 ) DATA 0 , + ( 18 ) DATA 0 , + ( 19 ) DATA 0 , + ( 20 ) DATA 6 , + ( 21 ) DATA 0 , + ( 22 ) DATA 2 , + ( 23 ) DATA 26 , + ( 24 ) DATA 5 , + ( 25 ) DATA 20 , + ( 26 ) DATA 3 , + ( 27 ) DATA 30 , + ( 28 ) DATA 1 , + ( 29 ) DATA 22 , + ( 30 ) DATA 4 , + ( 31 ) DATA 24 , + execute + cr say " prisoner: " + computer/zero + ( 00 ) NOP -- , + ( 01 ) NOP -- , + ( 02 ) STP -- , + ( 03 ) NOP -- , + ( 04 ) LDA 03 , + ( 05 ) SUB 29 , + ( 06 ) BRZ 18 , + ( 07 ) LDA 03 , + ( 08 ) STA 29 , + ( 09 ) BRZ 14 , + ( 10 ) LDA 01 , + ( 11 ) ADD 31 , + ( 12 ) STA 01 , + ( 13 ) JMP 02 , + ( 14 ) LDA 00 , + ( 15 ) ADD 31 , + ( 16 ) STA 00 , + ( 17 ) JMP 02 , + ( 18 ) LDA 03 , + ( 19 ) STA 29 , + ( 20 ) LDA 01 , + ( 21 ) ADD 30 , + ( 22 ) ADD 03 , + ( 23 ) STA 01 , + ( 24 ) LDA 00 , + ( 25 ) ADD 30 , + ( 26 ) ADD 03 , + ( 27 ) STA 01 , + ( 28 ) JMP 02 , + ( 29 ) DATA 0 , + ( 30 ) DATA 1 , + ( 31 ) DATA 3 , + execute diff --git a/Task/Execute-HQ9+/11l/execute-hq9+.11l b/Task/Execute-HQ9+/11l/execute-hq9+.11l index f78b71196e..61c3364c3b 100644 --- a/Task/Execute-HQ9+/11l/execute-hq9+.11l +++ b/Task/Execute-HQ9+/11l/execute-hq9+.11l @@ -38,7 +38,7 @@ F incr() :start: src = File(:argv[1]).read() -[Char = (() -> N)] dispatch +[Char = (() -> Void)] dispatch dispatch[Char(‘h’)] = hello dispatch[Char(‘q’)] = quine dispatch[Char(‘9’)] = bottles diff --git a/Task/Execute-HQ9+/Arturo/execute-hq9+.arturo b/Task/Execute-HQ9+/Arturo/execute-hq9+.arturo index 6e897e33d0..ea2365d299 100644 --- a/Task/Execute-HQ9+/Arturo/execute-hq9+.arturo +++ b/Task/Execute-HQ9+/Arturo/execute-hq9+.arturo @@ -1,13 +1,12 @@ hq9: function [source][ acc: 0 loop split source 'ch [ - case [(lower ch)=] - when? ["h"]-> print "Hello, world!" - when? ["q"]-> print source - when? ["9"]-> print "99 bottles here ..." - when? ["+"]-> acc: acc+1 - else [] - + case lower ch [ + "h" -> print "Hello, world!" + "q" -> print source + "9" -> print "99 bottles here ..." + "+" -> acc: acc+1 + ] ] return acc ] diff --git a/Task/Execute-HQ9+/COBOL/execute-hq9+.cobol b/Task/Execute-HQ9+/COBOL/execute-hq9+.cob similarity index 100% rename from Task/Execute-HQ9+/COBOL/execute-hq9+.cobol rename to Task/Execute-HQ9+/COBOL/execute-hq9+.cob diff --git a/Task/Execute-HQ9+/Delphi/execute-hq9+.delphi b/Task/Execute-HQ9+/Delphi/execute-hq9+.pas similarity index 100% rename from Task/Execute-HQ9+/Delphi/execute-hq9+.delphi rename to Task/Execute-HQ9+/Delphi/execute-hq9+.pas diff --git a/Task/Execute-HQ9+/EasyLang/execute-hq9+.easy b/Task/Execute-HQ9+/EasyLang/execute-hq9+.easy index 73ac035a1f..95fb45691e 100644 --- a/Task/Execute-HQ9+/EasyLang/execute-hq9+.easy +++ b/Task/Execute-HQ9+/EasyLang/execute-hq9+.easy @@ -1,4 +1,4 @@ -proc run code$ . . +proc run code$ . for c$ in strchars code$ if c$ = "Q" print code$ diff --git a/Task/Execute-HQ9+/Haxe/execute-hq9+.haxe b/Task/Execute-HQ9+/Haxe/execute-hq9+.hx similarity index 100% rename from Task/Execute-HQ9+/Haxe/execute-hq9+.haxe rename to Task/Execute-HQ9+/Haxe/execute-hq9+.hx diff --git a/Task/Execute-HQ9+/Julia/execute-hq9+.julia b/Task/Execute-HQ9+/Julia/execute-hq9+.jl similarity index 100% rename from Task/Execute-HQ9+/Julia/execute-hq9+.julia rename to Task/Execute-HQ9+/Julia/execute-hq9+.jl diff --git a/Task/Execute-HQ9+/Kotlin/execute-hq9+.kotlin b/Task/Execute-HQ9+/Kotlin/execute-hq9+.kts similarity index 100% rename from Task/Execute-HQ9+/Kotlin/execute-hq9+.kotlin rename to Task/Execute-HQ9+/Kotlin/execute-hq9+.kts diff --git a/Task/Execute-HQ9+/OCaml/execute-hq9+.ocaml b/Task/Execute-HQ9+/OCaml/execute-hq9+.ml similarity index 100% rename from Task/Execute-HQ9+/OCaml/execute-hq9+.ocaml rename to Task/Execute-HQ9+/OCaml/execute-hq9+.ml diff --git a/Task/Execute-HQ9+/PowerShell/execute-hq9+.psh b/Task/Execute-HQ9+/PowerShell/execute-hq9+.ps1 similarity index 100% rename from Task/Execute-HQ9+/PowerShell/execute-hq9+.psh rename to Task/Execute-HQ9+/PowerShell/execute-hq9+.ps1 diff --git a/Task/Execute-HQ9+/R/execute-hq9+.r b/Task/Execute-HQ9+/R/execute-hq9+.r new file mode 100644 index 0000000000..10b02e4152 --- /dev/null +++ b/Task/Execute-HQ9+/R/execute-hq9+.r @@ -0,0 +1,25 @@ +library(stringr) + +bottles <- function(){ + s <- function(n) ifelse(n==1, "", "s") + z <- function(n) ifelse(n==0, "No more", n) + cat(sapply(99:1, function(n) str_glue("{n} bottle{s(n)} of beer on the wall,\n", + "{n} bottle{s(n)} of beer,\n", + "Take one down, pass it around,\n", + "{z(n-1)} bottle{s(n-1)} of beer on the wall.")), sep="\n") +} + +hq9plus <- function(s){ + accumulator <- 0 + chars <- str_split_1(str_to_upper(s),"") + for(char in chars){ + switch(char, + "H"=cat("Hello World!","\n"), + "Q"=cat(s, "\n"), + "9"=bottles(), + "+"=eval(accumulator <- accumulator+1)) + } + cat("The value of the accumulator is", accumulator) +} + +hq9plus(readline()) diff --git a/Task/Execute-HQ9+/Rust/execute-hq9+.rust b/Task/Execute-HQ9+/Rust/execute-hq9+.rs similarity index 100% rename from Task/Execute-HQ9+/Rust/execute-hq9+.rust rename to Task/Execute-HQ9+/Rust/execute-hq9+.rs diff --git a/Task/Execute-HQ9+/V-(Vlang)/execute-hq9+.v b/Task/Execute-HQ9+/V-(Vlang)/execute-hq9+.v new file mode 100644 index 0000000000..eb112af6de --- /dev/null +++ b/Task/Execute-HQ9+/V-(Vlang)/execute-hq9+.v @@ -0,0 +1,31 @@ +fn eval(code string) { + mut accumulator := 0 + for cal in code.trim_space().to_lower() { + match cal { + `h` { println("Hello, world!") } + `q` { println(code) } + `9` { + bottles := fn (ir int) string { + match ir { + 0 { return "No bottles" } + 1 { return "One bottle" } + else { return "$ir bottles" } + } + } + for ir := 99; ir >= 1; ir-- { + println("${bottles(ir)} of beer on the wall,") + println("${bottles(ir)} of beer,") + println("take one down and pass it around,") + println("${bottles(ir - 1)} of beer on the wall!") + println("") + } + } + `+` { accumulator++ } + else { println("syntax error") } + } + } +} + +fn main() { + eval("hq9+") +} diff --git a/Task/Execute-SNUSP/EasyLang/execute-snusp.easy b/Task/Execute-SNUSP/EasyLang/execute-snusp.easy index dde98b1d48..05ac014346 100644 --- a/Task/Execute-SNUSP/EasyLang/execute-snusp.easy +++ b/Task/Execute-SNUSP/EasyLang/execute-snusp.easy @@ -1,4 +1,4 @@ -proc snusp dlen raw$ . . +proc snusp dlen raw$ . len ds[] dlen is$[] = strsplit raw$ "\n" for s$ in is$[] @@ -6,9 +6,7 @@ proc snusp dlen raw$ . . . for ipr to len is$[][] for ipc to len is$[ipr][] - if is$[ipr][ipc] = "$" - break 2 - . + if is$[ipr][ipc] = "$" : break 2 . . dp = 1 @@ -42,9 +40,7 @@ proc snusp dlen raw$ . . elif c$ = "!" step elif c$ = "?" - if ds[dp] = 0 - step - . + if ds[dp] = 0 : step . step . diff --git a/Task/Execute-SNUSP/FreeBASIC/execute-snusp.basic b/Task/Execute-SNUSP/FreeBASIC/execute-snusp.basic new file mode 100644 index 0000000000..2a3ce48e9f --- /dev/null +++ b/Task/Execute-SNUSP/FreeBASIC/execute-snusp.basic @@ -0,0 +1,77 @@ +' Rosetta Code problem: https://rosettacode.org/wiki/Execute_SNUSP +' by Jjuanhdez, 05/2024 +' The interpreter below implements Core SNUSP: + +Const HW = "/++++!/===========?\>++.>+.+++++++..+++" & Chr(10) & _ +"\+++\ | /+>+++++++>/ /++++++++++<<.++>./" & Chr(10) & _ +"$+++/ | \+++++++++>\ \+++++.>.+++.-----\" & Chr(10) & _ +" \==-<<<<+>+++/ /=.>.+>.--------.-/" + +Dim Shared As Integer ipf, ipc ' instruction pointers in row and column +Dim Shared As Integer direcc ' direction (0 = right, 1 = down, 2 = left, 3 = up) + +Sub Paso() + If direcc And 1 Then + ipf += 1 - (direcc And 2) + Else + ipc += 1 - (direcc And 2) + End If +End Sub + +Sub SNUSP (dsLen As Integer, SNUSPcode As String) + Dim As Ubyte ad(dsLen - 1) ' data store + Dim As Integer dp ' data pointer + Dim As String cb(dsLen) ' two-way code storage + Dim As String fila, op, linea + Dim As Integer r, i, j + + dp = 0 + i = 1 + j = 1 + ipf = 0 + ipc = 0 + direcc = 0 + + While i <= Len(SNUSPcode) + If Mid(SNUSPcode, i, 1) = Chr(10) Then + cb(j) = linea + linea = "" + j += 1 + Else + linea &= Mid(SNUSPcode, i, 1) + End If + i += 1 + Wend + cb(j) = linea + + For r = 0 To Ubound(cb) + fila = cb(r) + ipc = Instr(fila, "$") - 1 + If ipc >= 0 Then + ipf = r + Exit For + End If + Next r + + While ipf >= 0 And ipf <= Ubound(cb) And ipc >= 0 And ipc < Len(cb(ipf)) + op = Mid(cb(ipf), ipc + 1, 1) + Select Case op + Case ">": dp += 1 ' RIGTH + Case "<": dp -= 1 ' LEFT + Case "+": ad(dp) += 1 ' INCR + Case "-": ad(dp) -= 1 ' DECR + Case ",": Input ad(dp) ' READ + Case ".": Print Chr(ad(dp)); ' WRITE + Case "/": direcc = Not direcc ' RULD + Case "\": direcc Xor= 1 ' LURD + Case "!": Paso ' SKIP + Case "?": If ad(dp) = 0 Then Paso ' SKIPZ + End Select + Paso + Wend + Print Chr(ad(dp)); +End Sub + +SNUSP(5, HW) + +Sleep diff --git a/Task/Execute-SNUSP/Julia/execute-snusp.julia b/Task/Execute-SNUSP/Julia/execute-snusp.jl similarity index 100% rename from Task/Execute-SNUSP/Julia/execute-snusp.julia rename to Task/Execute-SNUSP/Julia/execute-snusp.jl diff --git a/Task/Execute-SNUSP/Kotlin/execute-snusp.kotlin b/Task/Execute-SNUSP/Kotlin/execute-snusp.kts similarity index 100% rename from Task/Execute-SNUSP/Kotlin/execute-snusp.kotlin rename to Task/Execute-SNUSP/Kotlin/execute-snusp.kts diff --git a/Task/Execute-a-Markov-algorithm/11l/execute-a-markov-algorithm.11l b/Task/Execute-a-Markov-algorithm/11l/execute-a-markov-algorithm.11l index 5c8a789dc8..4c3cf6cc78 100644 --- a/Task/Execute-a-Markov-algorithm/11l/execute-a-markov-algorithm.11l +++ b/Task/Execute-a-Markov-algorithm/11l/execute-a-markov-algorithm.11l @@ -1,11 +1,4 @@ -T Rule - String pattern - String replacement - Bool terminating - F (pattern, replacement, terminating) - .pattern = pattern - .replacement = replacement - .terminating = terminating +T Rule = (String pattern, String replacement, Bool terminating) F parse(rules) [Rule] result diff --git a/Task/Execute-a-Markov-algorithm/Ada/execute-a-markov-algorithm-1.ada b/Task/Execute-a-Markov-algorithm/Ada/execute-a-markov-algorithm-1.adb similarity index 100% rename from Task/Execute-a-Markov-algorithm/Ada/execute-a-markov-algorithm-1.ada rename to Task/Execute-a-Markov-algorithm/Ada/execute-a-markov-algorithm-1.adb diff --git a/Task/Execute-a-Markov-algorithm/Ada/execute-a-markov-algorithm-2.ada b/Task/Execute-a-Markov-algorithm/Ada/execute-a-markov-algorithm-2.adb similarity index 100% rename from Task/Execute-a-Markov-algorithm/Ada/execute-a-markov-algorithm-2.ada rename to Task/Execute-a-Markov-algorithm/Ada/execute-a-markov-algorithm-2.adb diff --git a/Task/Execute-a-Markov-algorithm/Ada/execute-a-markov-algorithm-3.ada b/Task/Execute-a-Markov-algorithm/Ada/execute-a-markov-algorithm-3.adb similarity index 100% rename from Task/Execute-a-Markov-algorithm/Ada/execute-a-markov-algorithm-3.ada rename to Task/Execute-a-Markov-algorithm/Ada/execute-a-markov-algorithm-3.adb diff --git a/Task/Execute-a-Markov-algorithm/C-sharp/execute-a-markov-algorithm.cs b/Task/Execute-a-Markov-algorithm/C-sharp/execute-a-markov-algorithm.cs new file mode 100644 index 0000000000..6d3499bb58 --- /dev/null +++ b/Task/Execute-a-Markov-algorithm/C-sharp/execute-a-markov-algorithm.cs @@ -0,0 +1,161 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +public class Markov +{ + /// + /// Take a ruleset and return a function which takes a string to which the rules + /// should be applied. + /// + /// String containing the rules + /// A function that takes a string and applies the rules + public static Func CreateMarkovProcessor(string ruleSet) + { + // Convert a ruleset string into a dictionary + Dictionary MakeRuleMap(string ruleset) + { + return ruleset.Split('\n') + .Where(e => !e.StartsWith("#")) + .Select(e => e.Split(new[] { " -> " }, StringSplitOptions.None)) + .ToDictionary(e => e[0], e => e[1]); + } + + // Split a string at an index + Tuple SplitAt(string s, int i) + { + return new Tuple(s.Substring(0, i), s.Substring(i)); + } + + // Strip a leading number of chars from a string. + string StripLeading(string s, string strip) + { + return s.Substring(strip.Length); + } + + // Replace the substring in the string. + string Replace(string s, string find, string rep) + { + string result = s; + if (s.IndexOf(find) >= 0) + { + var a = SplitAt(s, s.IndexOf(find)); + result = a.Item1 + rep + StripLeading(a.Item2, find); + } + return result; + } + + // Recursively apply the ruleset to the string. + string Parse(Dictionary rules, string s) + { + string o = s; + foreach (var rule in rules) + { + string k = rule.Key; + string v = rule.Value; + + if (v.StartsWith(".")) + { + s = Replace(s, k, StripLeading(v, ".")); + break; + } + else + { + s = Replace(s, k, v); + if (s != o) { break; } + } + } + return o == s ? s : Parse(rules, s); + } + + var ruleMap = MakeRuleMap(ruleSet); + return str => Parse(ruleMap, str); + } + + public static void Main() + { + string ruleset1 = @"# This rules file is extracted from Wikipedia: +# http://en.wikipedia.org/wiki/Markov_Algorithm +A -> apple +B -> bag +S -> shop +T -> the +the shop -> my brother +a never used -> .terminating rule"; + + string ruleset2 = @"# Slightly modified from the rules on Wikipedia +A -> apple +B -> bag +S -> .shop +T -> the +the shop -> my brother +a never used -> .terminating rule"; + + string ruleset3 = @"# BNF Syntax testing rules +A -> apple +WWWW -> with +Bgage -> ->.* +B -> bag +->.* -> money +W -> WW +S -> .shop +T -> the +the shop -> my brother +a never used -> .terminating rule"; + + string ruleset4 = @"### Unary Multiplication Engine, for testing Markov Algorithm implementations +### By Donal Fellows. +# Unary addition engine +_+1 -> _1+ +1+1 -> 11+ +# Pass for converting from the splitting of multiplication into ordinary +# addition +1! -> !1 +,! -> !+ +_! -> _ +# Unary multiplication by duplicating left side, right side times +1*1 -> x,@y +1x -> xX +X, -> 1,1 +X1 -> 1X +_x -> _X +,x -> ,X +y1 -> 1y +y_ -> _ +# Next phase of applying +1@1 -> x,@y +1@_ -> @_ +,@_ -> !_ +++ -> + +# Termination cleanup for addition +_1 -> 1 +1+_ -> 1 +_+_ -> "; + + string ruleset5 = @"# Turing machine: three-state busy beaver +# +# state A, symbol 0 => write 1, move right, new state B +A0 -> 1B +# state A, symbol 1 => write 1, move left, new state C +0A1 -> C01 +1A1 -> C11 +# state B, symbol 0 => write 1, move left, new state A +0B0 -> A01 +1B0 -> A11 +# state B, symbol 1 => write 1, move right, new state B +B1 -> 1B +# state C, symbol 0 => write 1, move left, new state B +0C0 -> B01 +1C0 -> B11 +# state C, symbol 1 => write 1, move left, halt +0C1 -> H01 +1C1 -> H11"; + + Console.WriteLine(CreateMarkovProcessor(ruleset1)("I bought a B of As from T S.")); + Console.WriteLine(CreateMarkovProcessor(ruleset2)("I bought a B of As from T S.")); + Console.WriteLine(CreateMarkovProcessor(ruleset3)("I bought a B of As W my Bgage from T S.")); + Console.WriteLine(CreateMarkovProcessor(ruleset4)("_1111*11111_")); + Console.WriteLine(CreateMarkovProcessor(ruleset5)("000000A000000")); + } +} diff --git a/Task/Execute-a-Markov-algorithm/FreeBASIC/execute-a-markov-algorithm.basic b/Task/Execute-a-Markov-algorithm/FreeBASIC/execute-a-markov-algorithm.basic new file mode 100644 index 0000000000..8d0a5ec743 --- /dev/null +++ b/Task/Execute-a-Markov-algorithm/FreeBASIC/execute-a-markov-algorithm.basic @@ -0,0 +1,139 @@ +Sub Markov (rules As String, entrada As String, expected As String) + Dim As String subs(), reps(), lines() + Dim As String sub_, rep, li, res + Dim As Integer i, k + Dim As Integer start = 1, finish = 1 + + While finish <= Len(rules) + If Mid(rules, finish, 1) = Chr(10) Then + Redim Preserve lines(Ubound(lines) + 1) + lines(Ubound(lines)) = Mid(rules, start, finish - start) + start = finish + 1 + End If + finish += 1 + Wend + For i = 0 To Ubound(lines) + li = lines(i) + If Len(li) > 0 And Asc(li, 1) <> Asc("#") Then + k = Instr(li, " -> ") + If k > 0 Then + Redim Preserve subs(Ubound(subs) + 1) + subs(Ubound(subs)) = Trim(Mid(li, 1, k - 1)) + Redim Preserve reps(Ubound(reps) + 1) + reps(Ubound(reps)) = Trim(Mid(li, k + 4)) + End If + End If + Next i + + res = entrada + Dim As Boolean term = False, found = False + Do + found = False + For i = 0 To Ubound(subs) + sub_ = subs(i) + k = Instr(res, sub_) + If k > 0 Then + found = True + rep = reps(i) + If Len(rep) > 0 And Asc(rep, 1) = Asc(".") Then + rep = Mid(rep, 2) + term = True + End If + Mid(res, k, Len(sub_)) = rep + Exit For + End If + If Not term Then Exit For + Next i + If Not term Or Not found Then Exit Do + Loop + Print """"; entrada;""""; ", "; """"; expected; """"; ", "; Iif(res = expected, "**ERROR**", "ok") +End Sub + +Dim As String ruleset1 = _ +"# This rules file is extracted from Wikipedia:" & _ +"# http://en.wikipedia.org/wiki/Markov_Algorithm" & _ +"A -> apple" & _ +"B -> bag" & _ +"S -> shop" & _ +"T -> the" & _ +"the shop -> my brother" & _ +"a never used -> .terminating rule" +Markov(ruleset1,"I bought a B of As from T S.","I bought a bag of apples from my brother.") + +Dim As String ruleset2 = _ +"# Slightly modified from the rules on Wikipedia" & _ +"A -> apple" & _ +"B -> bag" & _ +"S -> .shop" & _ +"T -> the" & _ +"the shop -> my brother" & _ +"a never used -> .terminating rule" +Markov(ruleset2,"I bought a B of As from T S.","I bought a bag of apples from T shop.") + +Dim As String ruleset3 = _ +"# BNF Syntax testing rules" & _ +"A -> apple" & _ +"WWWW -> with" & _ +"Bgage -> ->.*" & _ +"B -> bag" & _ +"->.* -> money" & _ +"W -> WW" & _ +"S -> .shop" & _ +"T -> the" & _ +"the shop -> my brother" & _ +"a never used -> .terminating rule""" +Markov(ruleset3,"I bought a B of As W my Bgage from T S.","I bought a bag of apples with my money from T shop.") + +Dim As String ruleset4 = _ +"### Unary Multiplication Engine, for testing Markov Algorithm implementations" & _ +"### By Donal Fellows." & _ +"# Unary addition engine" & _ +"_+1 -> _1+" & _ +"1+1 -> 11+" & _ +"# Pass for converting from the splitting of multiplication into ordinary" & _ +"# addition" & _ +"1! -> !1" & _ +",! -> !+" & _ +"_! -> _" & _ +"# Unary multiplication by duplicating left side, right side times" & _ +"1*1 -> x,@y" & _ +"1x -> xX" & _ +"X, -> 1,1" & _ +"X1 -> 1X" & _ +"_x -> _X" & _ +",x -> ,X" & _ +"y1 -> 1y" & _ +"y_ -> _" & _ +"# Next phase of applying" & _ +"1@1 -> x,@y" & _ +"1@_ -> @_" & _ +",@_ -> !_" & _ +"++ -> +" & _ +"# Termination cleanup for addition" & _ +"_1 -> 1" & _ +"1+_ -> 1" & _ +"_+_ -> " +Markov(ruleset4,"_1111*11111_","11111111111111111111") + +Dim As String ruleset5 = _ +"# Turing machine: three-state busy beaver" & _ +"#" & _ +"# state A, symbol 0 => write 1, move right, new state B" & _ +"A0 -> 1B" & _ +"# state A, symbol 1 => write 1, move left, new state C" & _ +"0A1 -> C01" & _ +"1A1 -> C11" & _ +"# state B, symbol 0 => write 1, move left, new state A" & _ +"0B0 -> A01" & _ +"1B0 -> A11" & _ +"# state B, symbol 1 => write 1, move right, new state B" & _ +"B1 -> 1B" & _ +"# state C, symbol 0 => write 1, move left, new state B" & _ +"0C0 -> B01" & _ +"1C0 -> B11" & _ +"# state C, symbol 1 => write 1, move left, halt" & _ +"0C1 -> H01" & _ +"1C1 -> H11" +Markov(ruleset5,"000000A000000","00011H1111000") + +Sleep diff --git a/Task/Execute-a-Markov-algorithm/Julia/execute-a-markov-algorithm-1.julia b/Task/Execute-a-Markov-algorithm/Julia/execute-a-markov-algorithm-1.jl similarity index 100% rename from Task/Execute-a-Markov-algorithm/Julia/execute-a-markov-algorithm-1.julia rename to Task/Execute-a-Markov-algorithm/Julia/execute-a-markov-algorithm-1.jl diff --git a/Task/Execute-a-Markov-algorithm/Julia/execute-a-markov-algorithm-2.julia b/Task/Execute-a-Markov-algorithm/Julia/execute-a-markov-algorithm-2.jl similarity index 100% rename from Task/Execute-a-Markov-algorithm/Julia/execute-a-markov-algorithm-2.julia rename to Task/Execute-a-Markov-algorithm/Julia/execute-a-markov-algorithm-2.jl diff --git a/Task/Execute-a-Markov-algorithm/Kotlin/execute-a-markov-algorithm.kotlin b/Task/Execute-a-Markov-algorithm/Kotlin/execute-a-markov-algorithm.kts similarity index 100% rename from Task/Execute-a-Markov-algorithm/Kotlin/execute-a-markov-algorithm.kotlin rename to Task/Execute-a-Markov-algorithm/Kotlin/execute-a-markov-algorithm.kts diff --git a/Task/Execute-a-Markov-algorithm/OCaml/execute-a-markov-algorithm.ocaml b/Task/Execute-a-Markov-algorithm/OCaml/execute-a-markov-algorithm.ml similarity index 100% rename from Task/Execute-a-Markov-algorithm/OCaml/execute-a-markov-algorithm.ocaml rename to Task/Execute-a-Markov-algorithm/OCaml/execute-a-markov-algorithm.ml diff --git a/Task/Execute-a-Markov-algorithm/Rust/execute-a-markov-algorithm.rust b/Task/Execute-a-Markov-algorithm/Rust/execute-a-markov-algorithm.rs similarity index 100% rename from Task/Execute-a-Markov-algorithm/Rust/execute-a-markov-algorithm.rust rename to Task/Execute-a-Markov-algorithm/Rust/execute-a-markov-algorithm.rs diff --git a/Task/Execute-a-Markov-algorithm/Scheme/execute-a-markov-algorithm.ss b/Task/Execute-a-Markov-algorithm/Scheme/execute-a-markov-algorithm.scm similarity index 100% rename from Task/Execute-a-Markov-algorithm/Scheme/execute-a-markov-algorithm.ss rename to Task/Execute-a-Markov-algorithm/Scheme/execute-a-markov-algorithm.scm diff --git a/Task/Execute-a-Markov-algorithm/VBScript/execute-a-markov-algorithm-1.vb b/Task/Execute-a-Markov-algorithm/VBScript/execute-a-markov-algorithm-1.vbs similarity index 100% rename from Task/Execute-a-Markov-algorithm/VBScript/execute-a-markov-algorithm-1.vb rename to Task/Execute-a-Markov-algorithm/VBScript/execute-a-markov-algorithm-1.vbs diff --git a/Task/Execute-a-Markov-algorithm/VBScript/execute-a-markov-algorithm-2.vb b/Task/Execute-a-Markov-algorithm/VBScript/execute-a-markov-algorithm-2.vbs similarity index 100% rename from Task/Execute-a-Markov-algorithm/VBScript/execute-a-markov-algorithm-2.vb rename to Task/Execute-a-Markov-algorithm/VBScript/execute-a-markov-algorithm-2.vbs diff --git a/Task/Execute-a-Markov-algorithm/VBScript/execute-a-markov-algorithm-3.vb b/Task/Execute-a-Markov-algorithm/VBScript/execute-a-markov-algorithm-3.vbs similarity index 100% rename from Task/Execute-a-Markov-algorithm/VBScript/execute-a-markov-algorithm-3.vb rename to Task/Execute-a-Markov-algorithm/VBScript/execute-a-markov-algorithm-3.vbs diff --git a/Task/Execute-a-Markov-algorithm/Zig/execute-a-markov-algorithm.zig b/Task/Execute-a-Markov-algorithm/Zig/execute-a-markov-algorithm.zig new file mode 100644 index 0000000000..ec8bb8934d --- /dev/null +++ b/Task/Execute-a-Markov-algorithm/Zig/execute-a-markov-algorithm.zig @@ -0,0 +1,278 @@ +const std = @import("std"); +const testing = std.testing; +const mem = std.mem; +const Allocator = std.mem.Allocator; + +// Add a main function for Zig playground to compile +pub fn main() !void { + // Empty main function to satisfy the compiler + std.debug.print("Markov Algorithm library\n", .{}); +} + +pub const Rule = struct { + pat: []const u8, + rep: []const u8, + terminal: bool, + + pub fn init(allocator: Allocator, pat: []const u8, rep: []const u8, terminal: bool) !Rule { + const pat_owned = try allocator.dupe(u8, pat); + const rep_owned = try allocator.dupe(u8, rep); + return Rule{ + .pat = pat_owned, + .rep = rep_owned, + .terminal = terminal, + }; + } + + pub fn deinit(self: *Rule, allocator: Allocator) void { + allocator.free(self.pat); + allocator.free(self.rep); + } + + pub fn clone(self: Rule, allocator: Allocator) !Rule { + return try Rule.init(allocator, self.pat, self.rep, self.terminal); + } + + pub fn applicableRange(self: *const Rule, input: []const u8) ?struct { start: usize, end: usize } { + if (mem.indexOf(u8, input, self.pat)) |start| { + return .{ .start = start, .end = start + self.pat.len }; + } + return null; + } + + pub fn apply(self: *const Rule, s: *std.ArrayList(u8)) !bool { + if (self.applicableRange(s.items)) |range| { + try s.replaceRange(range.start, range.end - range.start, self.rep); + return true; + } + return false; + } + + pub fn fromString(allocator: Allocator, s: []const u8) !Rule { + var parts = mem.splitSequence(u8, s, " -> "); + const pat = parts.first(); + const rep_opt = parts.next(); + if (rep_opt == null) { + return error.InvalidFormat; + } + const rep = rep_opt.?; + + if (rep.len > 0 and rep[0] == '.') { + return Rule.init(allocator, pat, rep[1..], true); + } else { + return Rule.init(allocator, pat, rep, false); + } + } +}; + +pub const Rules = struct { + rules: std.ArrayList(Rule), + allocator: Allocator, + + pub fn init(allocator: Allocator) Rules { + return Rules{ + .rules = std.ArrayList(Rule).init(allocator), + .allocator = allocator, + }; + } + + pub fn deinit(self: *Rules) void { + for (self.rules.items) |*rule| { + rule.deinit(self.allocator); + } + self.rules.deinit(); + } + + pub fn clone(self: Rules) !Rules { + var new_rules = Rules.init(self.allocator); + for (self.rules.items) |rule| { + try new_rules.rules.append(try rule.clone(self.allocator)); + } + return new_rules; + } + + pub fn apply(self: *const Rules, s: *std.ArrayList(u8)) !?*const Rule { + for (self.rules.items) |*rule| { + if (try rule.apply(s)) { + return rule; + } + } + return null; + } + + pub fn execute(self: *const Rules, buffer: []const u8) ![]u8 { + var result = try std.ArrayList(u8).initCapacity(self.allocator, buffer.len); + try result.appendSlice(buffer); + + while (try self.apply(&result)) |rule| { + if (rule.terminal) { + break; + } + } + + return result.toOwnedSlice(); + } + + pub fn fromString(allocator: Allocator, s: []const u8) !Rules { + var result = Rules.init(allocator); + var lines = mem.splitScalar(u8, s, '\n'); + + while (lines.next()) |line| { + const trimmed = mem.trim(u8, line, &std.ascii.whitespace); + if (trimmed.len == 0 or trimmed[0] == '#') { + continue; + } + const rule = try Rule.fromString(allocator, trimmed); + try result.rules.append(rule); + } + + return result; + } +}; + +test "case_01" { + const allocator = std.testing.allocator; + const input = "I bought a B of As from T S."; + const rules_str = + \\# This rules file is extracted from Wikipedia: + \\# http://en.wikipedia.org/wiki/Markov_Algorithm + \\A -> apple + \\B -> bag + \\S -> shop + \\T -> the + \\the shop -> my brother + \\a never used -> .terminating rule + ; + + var rules = try Rules.fromString(allocator, rules_str); + defer rules.deinit(); + + const result = try rules.execute(input); + defer allocator.free(result); + + try testing.expectEqualStrings("I bought a bag of apples from my brother.", result); +} + +test "case_02" { + const allocator = std.testing.allocator; + const input = "I bought a B of As from T S."; + const rules_str = + \\# Slightly modified from the rules on Wikipedia + \\A -> apple + \\B -> bag + \\S -> .shop + \\T -> the + \\the shop -> my brother + \\a never used -> .terminating rule + ; + + var rules = try Rules.fromString(allocator, rules_str); + defer rules.deinit(); + + const result = try rules.execute(input); + defer allocator.free(result); + + try testing.expectEqualStrings("I bought a bag of apples from T shop.", result); +} + +test "case_03" { + const allocator = std.testing.allocator; + const input = "I bought a B of As W my Bgage from T S."; + const rules_str = + \\# BNF Syntax testing rules + \\A -> apple + \\WWWW -> with + \\Bgage -> ->.* + \\B -> bag + \\->.* -> money + \\W -> WW + \\S -> .shop + \\T -> the + \\the shop -> my brother + \\a never used -> .terminating rule + ; + + var rules = try Rules.fromString(allocator, rules_str); + defer rules.deinit(); + + const result = try rules.execute(input); + defer allocator.free(result); + + try testing.expectEqualStrings("I bought a bag of apples with my money from T shop.", result); +} + +test "case_04" { + const allocator = std.testing.allocator; + const input = "_1111*11111_"; + const rules_str = + \\### Unary Multiplication Engine, for testing Markov Algorithm implementations + \\### By Donal Fellows. + \\# Unary addition engine + \\_+1 -> _1+ + \\1+1 -> 11+ + \\# Pass for converting from the splitting of multiplication into ordinary + \\# addition + \\1! -> !1 + \\,! -> !+ + \\_! -> _ + \\# Unary multiplication by duplicating left side, right side times + \\1*1 -> x,@y + \\1x -> xX + \\X, -> 1,1 + \\X1 -> 1X + \\_x -> _X + \\,x -> ,X + \\y1 -> 1y + \\y_ -> _ + \\# Next phase of applying + \\1@1 -> x,@y + \\1@_ -> @_ + \\,@_ -> !_ + \\++ -> + + \\# Termination cleanup for addition + \\_1 -> 1 + \\1+_ -> 1 + \\_+_ -> + ; + + var rules = try Rules.fromString(allocator, rules_str); + defer rules.deinit(); + + const result = try rules.execute(input); + defer allocator.free(result); + + try testing.expectEqualStrings("11111111111111111111", result); +} + +test "case_05" { + const allocator = std.testing.allocator; + const input = "000000A000000"; + const rules_str = + \\# Turing machine: three-state busy beaver + \\# + \\# state A, symbol 0 => write 1, move right, new state B + \\A0 -> 1B + \\# state A, symbol 1 => write 1, move left, new state C + \\0A1 -> C01 + \\1A1 -> C11 + \\# state B, symbol 0 => write 1, move left, new state A + \\0B0 -> A01 + \\1B0 -> A11 + \\# state B, symbol 1 => write 1, move right, new state B + \\B1 -> 1B + \\# state C, symbol 0 => write 1, move left, new state B + \\0C0 -> B01 + \\1C0 -> B11 + \\# state C, symbol 1 => write 1, move left, halt + \\0C1 -> H01 + \\1C1 -> H11 + ; + + var rules = try Rules.fromString(allocator, rules_str); + defer rules.deinit(); + + const result = try rules.execute(input); + defer allocator.free(result); + + try testing.expectEqualStrings("00011H1111000", result); +} diff --git a/Task/Execute-a-system-command/Ada/execute-a-system-command-1.ada b/Task/Execute-a-system-command/Ada/execute-a-system-command-1.adb similarity index 100% rename from Task/Execute-a-system-command/Ada/execute-a-system-command-1.ada rename to Task/Execute-a-system-command/Ada/execute-a-system-command-1.adb diff --git a/Task/Execute-a-system-command/Ada/execute-a-system-command-2.ada b/Task/Execute-a-system-command/Ada/execute-a-system-command-2.adb similarity index 100% rename from Task/Execute-a-system-command/Ada/execute-a-system-command-2.ada rename to Task/Execute-a-system-command/Ada/execute-a-system-command-2.adb diff --git a/Task/Execute-a-system-command/Ada/execute-a-system-command-3.ada b/Task/Execute-a-system-command/Ada/execute-a-system-command-3.adb similarity index 100% rename from Task/Execute-a-system-command/Ada/execute-a-system-command-3.ada rename to Task/Execute-a-system-command/Ada/execute-a-system-command-3.adb diff --git a/Task/Execute-a-system-command/ArkScript/execute-a-system-command.ark b/Task/Execute-a-system-command/ArkScript/execute-a-system-command.ark new file mode 100644 index 0000000000..40b7da0d2d --- /dev/null +++ b/Task/Execute-a-system-command/ArkScript/execute-a-system-command.ark @@ -0,0 +1,3 @@ +(import std.Sys) + +(print (sys:exec "ls")) diff --git a/Task/Execute-a-system-command/AutoIt/execute-a-system-command.autoit b/Task/Execute-a-system-command/AutoIt/execute-a-system-command.au3 similarity index 100% rename from Task/Execute-a-system-command/AutoIt/execute-a-system-command.autoit rename to Task/Execute-a-system-command/AutoIt/execute-a-system-command.au3 diff --git a/Task/Execute-a-system-command/COBOL/execute-a-system-command.cobol b/Task/Execute-a-system-command/COBOL/execute-a-system-command.cob similarity index 100% rename from Task/Execute-a-system-command/COBOL/execute-a-system-command.cobol rename to Task/Execute-a-system-command/COBOL/execute-a-system-command.cob diff --git a/Task/Execute-a-system-command/Delphi/execute-a-system-command.delphi b/Task/Execute-a-system-command/Delphi/execute-a-system-command.pas similarity index 100% rename from Task/Execute-a-system-command/Delphi/execute-a-system-command.delphi rename to Task/Execute-a-system-command/Delphi/execute-a-system-command.pas diff --git a/Task/Execute-a-system-command/Emacs-Lisp/execute-a-system-command-1.l b/Task/Execute-a-system-command/Emacs-Lisp/execute-a-system-command-1.el similarity index 100% rename from Task/Execute-a-system-command/Emacs-Lisp/execute-a-system-command-1.l rename to Task/Execute-a-system-command/Emacs-Lisp/execute-a-system-command-1.el diff --git a/Task/Execute-a-system-command/Emacs-Lisp/execute-a-system-command-2.l b/Task/Execute-a-system-command/Emacs-Lisp/execute-a-system-command-2.el similarity index 100% rename from Task/Execute-a-system-command/Emacs-Lisp/execute-a-system-command-2.l rename to Task/Execute-a-system-command/Emacs-Lisp/execute-a-system-command-2.el diff --git a/Task/Execute-a-system-command/Euphoria/execute-a-system-command.euphoria b/Task/Execute-a-system-command/Euphoria/execute-a-system-command.eu similarity index 100% rename from Task/Execute-a-system-command/Euphoria/execute-a-system-command.euphoria rename to Task/Execute-a-system-command/Euphoria/execute-a-system-command.eu diff --git a/Task/Execute-a-system-command/Julia/execute-a-system-command.julia b/Task/Execute-a-system-command/Julia/execute-a-system-command.jl similarity index 100% rename from Task/Execute-a-system-command/Julia/execute-a-system-command.julia rename to Task/Execute-a-system-command/Julia/execute-a-system-command.jl diff --git a/Task/Execute-a-system-command/Kotlin/execute-a-system-command.kotlin b/Task/Execute-a-system-command/Kotlin/execute-a-system-command.kts similarity index 100% rename from Task/Execute-a-system-command/Kotlin/execute-a-system-command.kotlin rename to Task/Execute-a-system-command/Kotlin/execute-a-system-command.kts diff --git a/Task/Execute-a-system-command/OCaml/execute-a-system-command-1.ocaml b/Task/Execute-a-system-command/OCaml/execute-a-system-command-1.ml similarity index 100% rename from Task/Execute-a-system-command/OCaml/execute-a-system-command-1.ocaml rename to Task/Execute-a-system-command/OCaml/execute-a-system-command-1.ml diff --git a/Task/Execute-a-system-command/OCaml/execute-a-system-command-2.ocaml b/Task/Execute-a-system-command/OCaml/execute-a-system-command-2.ml similarity index 100% rename from Task/Execute-a-system-command/OCaml/execute-a-system-command-2.ocaml rename to Task/Execute-a-system-command/OCaml/execute-a-system-command-2.ml diff --git a/Task/Execute-a-system-command/OCaml/execute-a-system-command-3.ocaml b/Task/Execute-a-system-command/OCaml/execute-a-system-command-3.ml similarity index 100% rename from Task/Execute-a-system-command/OCaml/execute-a-system-command-3.ocaml rename to Task/Execute-a-system-command/OCaml/execute-a-system-command-3.ml diff --git a/Task/Execute-a-system-command/PascalABC.NET/execute-a-system-command.pas b/Task/Execute-a-system-command/PascalABC.NET/execute-a-system-command.pas new file mode 100644 index 0000000000..ab758487a0 --- /dev/null +++ b/Task/Execute-a-system-command/PascalABC.NET/execute-a-system-command.pas @@ -0,0 +1,2 @@ +## +exec('cmd.exe','/c dir /p'); diff --git a/Task/Execute-a-system-command/Pluto/execute-a-system-command.pluto b/Task/Execute-a-system-command/Pluto/execute-a-system-command.pluto new file mode 100644 index 0000000000..3f325c8c2e --- /dev/null +++ b/Task/Execute-a-system-command/Pluto/execute-a-system-command.pluto @@ -0,0 +1 @@ +os.execute("pause") diff --git a/Task/Execute-a-system-command/PowerShell/execute-a-system-command-1.psh b/Task/Execute-a-system-command/PowerShell/execute-a-system-command-1.ps1 similarity index 100% rename from Task/Execute-a-system-command/PowerShell/execute-a-system-command-1.psh rename to Task/Execute-a-system-command/PowerShell/execute-a-system-command-1.ps1 diff --git a/Task/Execute-a-system-command/PowerShell/execute-a-system-command-2.psh b/Task/Execute-a-system-command/PowerShell/execute-a-system-command-2.ps1 similarity index 100% rename from Task/Execute-a-system-command/PowerShell/execute-a-system-command-2.psh rename to Task/Execute-a-system-command/PowerShell/execute-a-system-command-2.ps1 diff --git a/Task/Execute-a-system-command/REBOL/execute-a-system-command.rebol b/Task/Execute-a-system-command/Rebol/execute-a-system-command.rebol similarity index 100% rename from Task/Execute-a-system-command/REBOL/execute-a-system-command.rebol rename to Task/Execute-a-system-command/Rebol/execute-a-system-command.rebol diff --git a/Task/Execute-a-system-command/Rust/execute-a-system-command.rust b/Task/Execute-a-system-command/Rust/execute-a-system-command.rs similarity index 100% rename from Task/Execute-a-system-command/Rust/execute-a-system-command.rust rename to Task/Execute-a-system-command/Rust/execute-a-system-command.rs diff --git a/Task/Execute-a-system-command/Rye/execute-a-system-command.rye b/Task/Execute-a-system-command/Rye/execute-a-system-command.rye new file mode 100644 index 0000000000..97164e6532 --- /dev/null +++ b/Task/Execute-a-system-command/Rye/execute-a-system-command.rye @@ -0,0 +1,3 @@ +cc os +ls +cwd? diff --git a/Task/Execute-a-system-command/Scheme/execute-a-system-command.ss b/Task/Execute-a-system-command/Scheme/execute-a-system-command.scm similarity index 100% rename from Task/Execute-a-system-command/Scheme/execute-a-system-command.ss rename to Task/Execute-a-system-command/Scheme/execute-a-system-command.scm diff --git a/Task/Execute-a-system-command/Seed7/execute-a-system-command.seed7 b/Task/Execute-a-system-command/Seed7/execute-a-system-command.seed7 index eafaacc2ca..7de9dc25a3 100644 --- a/Task/Execute-a-system-command/Seed7/execute-a-system-command.seed7 +++ b/Task/Execute-a-system-command/Seed7/execute-a-system-command.seed7 @@ -3,5 +3,5 @@ $ include "seed7_05.s7i"; const proc: main is func begin - cmd_sh("ls"); + shellCmd("ls"); end func; diff --git a/Task/Execute-a-system-command/VBScript/execute-a-system-command.vb b/Task/Execute-a-system-command/VBScript/execute-a-system-command.vbs similarity index 100% rename from Task/Execute-a-system-command/VBScript/execute-a-system-command.vb rename to Task/Execute-a-system-command/VBScript/execute-a-system-command.vbs diff --git a/Task/Execute-a-system-command/Wren/execute-a-system-command-1.wren b/Task/Execute-a-system-command/Wren/execute-a-system-command-1.wren deleted file mode 100644 index c638a0983e..0000000000 --- a/Task/Execute-a-system-command/Wren/execute-a-system-command-1.wren +++ /dev/null @@ -1,8 +0,0 @@ -/* Execute_a_system_command.wren */ -class Command { - foreign static exec(name, param) // the code for this is provided by Go -} - -Command.exec("ls", "-lt") -System.print() -Command.exec("dir", "") diff --git a/Task/Execute-a-system-command/Wren/execute-a-system-command-2.wren b/Task/Execute-a-system-command/Wren/execute-a-system-command-2.wren deleted file mode 100644 index 2e0ffb7e03..0000000000 --- a/Task/Execute-a-system-command/Wren/execute-a-system-command-2.wren +++ /dev/null @@ -1,39 +0,0 @@ -/* Execute_a_system_command.go*/ -package main - -import ( - wren "github.com/crazyinfin8/WrenGo" - "log" - "os" - "os/exec" -) - -type any = interface{} - -func execCommand(vm *wren.VM, parameters []any) (any, error) { - name := parameters[1].(string) - param := parameters[2].(string) - var cmd *exec.Cmd - if param != "" { - cmd = exec.Command(name, param) - } else { - cmd = exec.Command(name) - } - cmd.Stdout = os.Stdout - cmd.Stderr = os.Stderr - if err := cmd.Run(); err != nil { - log.Fatal(err) - } - return nil, nil -} - -func main() { - vm := wren.NewVM() - fileName := "Execute_a_system_command.wren" - methodMap := wren.MethodMap{"static exec(_,_)": execCommand} - classMap := wren.ClassMap{"Command": wren.NewClass(nil, nil, methodMap)} - module := wren.NewModule(classMap) - vm.SetModule(fileName, module) - vm.InterpretFile(fileName) - vm.Free() -} diff --git a/Task/Execute-a-system-command/Wren/execute-a-system-command.wren b/Task/Execute-a-system-command/Wren/execute-a-system-command.wren new file mode 100644 index 0000000000..1d97b0a9de --- /dev/null +++ b/Task/Execute-a-system-command/Wren/execute-a-system-command.wren @@ -0,0 +1,5 @@ +import "os" for Process + +Process.exec("ls", ["-lt"]) +System.print() +Process.exec("dir") diff --git a/Task/Exponentiation-operator/Ada/exponentiation-operator-1.ada b/Task/Exponentiation-operator/Ada/exponentiation-operator-1.adb similarity index 100% rename from Task/Exponentiation-operator/Ada/exponentiation-operator-1.ada rename to Task/Exponentiation-operator/Ada/exponentiation-operator-1.adb diff --git a/Task/Exponentiation-operator/Ada/exponentiation-operator-2.ada b/Task/Exponentiation-operator/Ada/exponentiation-operator-2.adb similarity index 100% rename from Task/Exponentiation-operator/Ada/exponentiation-operator-2.ada rename to Task/Exponentiation-operator/Ada/exponentiation-operator-2.adb diff --git a/Task/Exponentiation-operator/Ada/exponentiation-operator-3.ada b/Task/Exponentiation-operator/Ada/exponentiation-operator-3.adb similarity index 100% rename from Task/Exponentiation-operator/Ada/exponentiation-operator-3.ada rename to Task/Exponentiation-operator/Ada/exponentiation-operator-3.adb diff --git a/Task/Exponentiation-operator/Batch-File/exponentiation-operator.bat b/Task/Exponentiation-operator/Batch-File/exponentiation-operator.bat new file mode 100644 index 0000000000..f9b95744f4 --- /dev/null +++ b/Task/Exponentiation-operator/Batch-File/exponentiation-operator.bat @@ -0,0 +1,18 @@ +@echo off +setlocal enableextensions enabledelayedexpansion +set /p a= +set /p b= +call :pow %a% %b% +echo %_a% +goto :eof +:pow Integer Integer +:: Right-to-left binary exponentiation +set /a "_a=1, s=%1, e=%2" +:looppow +if %e% neq 0 ( +set /a "t=e&1" +if !t! equ 1 (set /a "_a*=s") +set /a "s*=s, e>>=1" +goto looppow +) +goto :eof diff --git a/Task/Exponentiation-operator/Delphi/exponentiation-operator.delphi b/Task/Exponentiation-operator/Delphi/exponentiation-operator.pas similarity index 100% rename from Task/Exponentiation-operator/Delphi/exponentiation-operator.delphi rename to Task/Exponentiation-operator/Delphi/exponentiation-operator.pas diff --git a/Task/Exponentiation-operator/EasyLang/exponentiation-operator.easy b/Task/Exponentiation-operator/EasyLang/exponentiation-operator.easy index f7a1d893bf..126b429c63 100644 --- a/Task/Exponentiation-operator/EasyLang/exponentiation-operator.easy +++ b/Task/Exponentiation-operator/EasyLang/exponentiation-operator.easy @@ -1,12 +1,10 @@ func mypow n exp . - r = 1 if exp < 0 exp = -exp n = 1 / n . - for i to exp - r *= n - . + r = 1 + for i to exp : r *= n return r . print mypow pi 2 diff --git a/Task/Exponentiation-operator/Elixir/exponentiation-operator.elixir b/Task/Exponentiation-operator/Elixir/exponentiation-operator.ex similarity index 100% rename from Task/Exponentiation-operator/Elixir/exponentiation-operator.elixir rename to Task/Exponentiation-operator/Elixir/exponentiation-operator.ex diff --git a/Task/Exponentiation-operator/Julia/exponentiation-operator.julia b/Task/Exponentiation-operator/Julia/exponentiation-operator.jl similarity index 100% rename from Task/Exponentiation-operator/Julia/exponentiation-operator.julia rename to Task/Exponentiation-operator/Julia/exponentiation-operator.jl diff --git a/Task/Exponentiation-operator/Kotlin/exponentiation-operator.kotlin b/Task/Exponentiation-operator/Kotlin/exponentiation-operator.kts similarity index 100% rename from Task/Exponentiation-operator/Kotlin/exponentiation-operator.kotlin rename to Task/Exponentiation-operator/Kotlin/exponentiation-operator.kts diff --git a/Task/Exponentiation-operator/OCaml/exponentiation-operator.ocaml b/Task/Exponentiation-operator/OCaml/exponentiation-operator.ml similarity index 100% rename from Task/Exponentiation-operator/OCaml/exponentiation-operator.ocaml rename to Task/Exponentiation-operator/OCaml/exponentiation-operator.ml diff --git a/Task/Exponentiation-operator/Phix/exponentiation-operator.phix b/Task/Exponentiation-operator/Phix/exponentiation-operator.phix index 79c10d37a2..07065b741f 100644 --- a/Task/Exponentiation-operator/Phix/exponentiation-operator.phix +++ b/Task/Exponentiation-operator/Phix/exponentiation-operator.phix @@ -1,15 +1,13 @@ -(phixonline)--> - with javascript_semantics - function powir(atom b, integer i) - atom res = 1 - if i<0 then {b,i} = {1/b,abs(i)} end if - while i do - if and_bits(i,1) then res *= b end if - b *= b - i = floor(i/2) - end while - return res - end function - ?powir(-3,-5) - ?power(-3,-5) - - ?power(power(5,3),2) - ?power(5,power(3,2)) - - for x=-5 to 5 by 10 do - for p=2 to 3 do - printf(1,"x = %2d, p = %d, power(-x,p) = %4d, -power(x,p) = %4d\n",{x,p,power(-x,p),-power(x,p)}) - end for - end for - - switch {condition1,condition2} do - case {true,true}: - case {true,false}: - case {false,true}: - case {false,false}: - end switch - - function if2(bool c1, bool c2) - return c1*10+c2 - end function +function if2(bool c1, bool c2) + return c1*10+c2 +end function - switch if2(condition1,condition2) do - case 11: - case 10: - case 01: - case 00: - end switch - - enum BOTH = 0b11, FIRST = 0b10, SECOND = 0b01, NEITHER = 0b00 +enum BOTH = 0b11, FIRST = 0b10, SECOND = 0b01, NEITHER = 0b00 - function if2(bool c1, bool c2) - return c1*2+c2 - end function +function if2(bool c1, bool c2) + return c1*2+c2 +end function - integer r = if2(condition1,condition2) - if r=BOTH then - elsif r=FIRST then - elsif r=SECOND then - elsif r=NEITHER then - end if - - global constant T_if2 = 5200 tt_stringF("if2",T_if2) - global constant T_else1 = 5200 tt_stringF("else1",T_else1) - global constant T_else2 = 5200 tt_stringF("else2",T_else2) - - --constant T_endelseelsif = {T_end,T_else,T_elsif,T_case,T_default,T_fallthru,T_fallthrough} - constant T_endelseelsif = {T_end,T_else,T_else1,T_else2,T_elsif,T_case,T_default,T_fallthru,T_fallthrough} - - elsif ttidx=T_if2 then DoIf2() - - for N=10 to 20 do - printf(1,"%d is ",N) - if2 mod(N,2)=0, mod(N,3)=0 then - puts(1,"divisible by both two and three.\n") - else1 - puts(1,"divisible by two, but not by three.\n") - else2 - puts(1,"divisible by three, but not by two.\n") - else - puts(1,"neither divisible by two, nor by three.\n") - end if2 - end for - - with javascript_semantics - if platform()!=JS then free_console() end if - sequence primes = {2,3,5,7} - atom sieved = 10 +with javascript_semantics +sequence primes = {2,3,5,7} +atom sieved = 10 - procedure add_block() - integer N = min((sieved-1)*sieved,400000) - sequence sieve = repeat(1,N) -- sieve[i] is really i+sieved - for i=2 to length(primes) do -- (evens filtered on output) - atom p = primes[i], p2 = p*p - if p2>sieved+N then exit end if - if p2<sieved+1 then - p2 += ceil((sieved+1-p2)/p)*p - end if - p2 -= sieved - if and_bits(p2,1)=0 then p2 += p end if - -- if sieve[p2] then -- dang! - for k=p2 to N by p*2 do - sieve[k] = 0 - end for - -- end if - end for - for i=1 to N by 2 do - if sieve[i] then - primes &= i+sieved - end if - end for - sieved += N - end procedure +procedure add_block() + integer N = min((sieved-1)*sieved,400000) + sequence sieve = repeat(1,N) -- sieve[i] is really i+sieved + for i=2 to length(primes) do -- (evens filtered on output) + atom p = primes[i], p2 = p*p + if p2>sieved+N then exit end if + if p2function is_prime2(integer n) - while sieved<n do - add_block() - end while - return binary_search(n,primes)>0 - end function - - atom t0 = time() - while length(primes)<20 do add_block() end while - printf(1,"The first 20 primes are: ") ?primes[1..20] - while sieved<150 do add_block() end while - sequence s = {} - for k=abs(binary_search(100,primes)) to length(primes) do - integer p = primes[k] - if p>150 then exit end if - s &= p - end for - printf(1,"The primes between 100 and 150 are: ") ?s - s = {} - for i=7700 to 8000 do - if is_prime2(i) then s&=i end if - end for - printf(1,"There are %d primes between 7700 and 8000.\n",length(s)) - for i=1 to iff(platform()=JS?7:8) do - integer k = power(10,i) - while length(primes)<k do - add_block() - end while - printf(1,"The %,dth prime is : %d\n",{k,primes[k]}) - end for - ?time()-t0 - if platform()!=JS then {} = wait_key() end if - - with javascript_semantics - atom t0 = time() - printf(1,"The first 20 primes are: %v\n",{get_primes(-20)}) - sequence s = get_primes_le(150)[length(get_primes_le(100))+1..$] - printf(1,"The primes between 100 and 150 are: %v\n",{s}) - integer n7700to8000 = length(get_primes_le(8000))-length(get_primes_le(7700)) - printf(1,"There are %d primes between 7700 and 8000.\n",n7700to8000) - for i=1 to iff(platform()=JS?7:8) do - integer k = power(10,i) - printf(1,"The %,dth prime is : %d\n",{k,get_prime(k)}) - end for - ?time()-t0 - if platform()!=JS then {} = wait_key() end if - - with javascript_semantics - constant inf = 1e300*1e300, -- (works on both 32 and 64 bit) - ninf = -inf, - nan = -(inf/inf), - nzero = -1/inf -- (not supported) +with javascript_semantics +constant inf = 1e300*1e300, -- (works on both 32 and 64 bit) + ninf = -inf, + nan = -(inf/inf), + nzero = -1/inf -- (not supported) - printf(1," inf: %f\n",{inf}) - printf(1," ninf: %f\n",{ninf}) - printf(1," nan: %f\n",{nan}) - printf(1,"*nzero: %f\n",{nzero}) - printf(1," inf+2: %f\n",{inf+2}) - printf(1," inf+ninf: %f\n",{inf+ninf}) - printf(1," 0*inf: %f\n",{0*inf}) - printf(1," nan+1: %f\n",{nan+1}) - printf(1," nan+nan: %f\n",{nan+nan}) - printf(1," inf>1e300: %d\n",{inf>1e300}) - printf(1," ninf<1e300: %d\n",{ninf<-1e300}) - printf(1,"*nan=nan: %d\n",{nan=nan}) - printf(1," nan=42: %d\n",{nan=42}) - printf(1,"*nan<0: %d\n",{nan<0}) - printf(1," nan>0: %d\n",{nan>0}) - " + to_string(rotated, " ") << std::endl; + increment(factoradic); + } + std::cout << std::endl; + + // Part 2 + std::cout << "Generating the permutations of 11 digits:" << std::endl; + const uint32_t limit = factorial(11); + elements = convert_to_vector_of_integer("0.1.2.3.4.5.6.7.8.9.10"); + factoradic = convert_to_vector_of_integer("0.0.0.0.0.0.0.0.0.0"); + for ( uint32_t i = 0; i < limit; ++i ) { + std::vector rotated = permutation(elements, factoradic); + if ( i < 3 || i > limit - 4 ) { + std::cout << to_string(factoradic, ".") + " --> " + to_string(rotated, " ") + << std::endl; + } else if ( i == 3 ) { + std::cout << " [ ... ] " << std::endl; + } + increment(factoradic); + } + std::cout << "Number of permutations is 11! = " << limit << std::endl << std::endl; + + // Part 3 + std::vector codes = { "39.49.7.47.29.30.2.12.10.3.29.37.33.17.12.31.29.34.17.25.2.4.25.4.1.14.20.6.21.18.1.1.1.4.0.5.15.12.4.3.10.10.9.1.6.5.5.3.0.0.0", +"51.48.16.22.3.0.19.34.29.1.36.30.12.32.12.29.30.26.14.21.8.12.1.3.10.4.7.17.6.21.8.12.15.15.13.15.7.3.12.11.9.5.5.6.6.3.4.0.3.2.1" }; + + std::vector cards = { "A♠", "K♠", "Q♠", "J♠", "10♠", "9♠", "8♠", "7♠", "6♠", "5♠", "4♠", "3♠", "2♠", + "A♥", "K♥", "Q♥", "J♥", "10♥", "9♥", "8♥", "7♥", "6♥", "5♥", "4♥", "3♥", "2♥", + "A♦", "K♦", "Q♦", "J♦", "10♦", "9♦", "8♦", "7♦", "6♦", "5♦", "4♦", "3♦", "2♦", + "A♣", "K♣", "Q♣", "J♣", "10♣", "9♣", "8♣", "7♣", "6♣", "5♣", "4♣", "3♣", "2♣" + }; + + std::cout << "Original deck of cards:" << std::endl; + std::cout << to_string(cards, " ") << std::endl << std::endl; + std::cout << "Task shuffles:" << std::endl; + for ( const std::string& code : codes ) { + std::cout << code + " --> " << std::endl; + factoradic = convert_to_vector_of_integer(code); + std::cout << to_string(permutation(cards, factoradic), " ") + << std::endl << std::endl; + } + + std::cout << "Random shuffle:" << std::endl;; + std::random_device random; + std::mt19937 generator(random()); + + factoradic.clear(); + for ( uint32_t i = 0; i < cards.size() - 1; ++i ) { + std::uniform_int_distribution distribution(0, cards.size() - i - 1); + factoradic.emplace_back(distribution(generator)); + } + + std::cout << to_string(factoradic, ".") + " --> " << std::endl; + std::cout << to_string(permutation(cards, factoradic), " ") << std::endl; +} diff --git a/Task/Factorial-base-numbers-indexing-permutations-of-a-collection/FreeBASIC/factorial-base-numbers-indexing-permutations-of-a-collection.basic b/Task/Factorial-base-numbers-indexing-permutations-of-a-collection/FreeBASIC/factorial-base-numbers-indexing-permutations-of-a-collection.basic new file mode 100644 index 0000000000..abd85c0b29 --- /dev/null +++ b/Task/Factorial-base-numbers-indexing-permutations-of-a-collection/FreeBASIC/factorial-base-numbers-indexing-permutations-of-a-collection.basic @@ -0,0 +1,167 @@ +Type Sequence + longi As Integer + dato(1000) As Integer +End Type + +Sub printSequence(s As Sequence) + Print " "; + For i As Integer = 1 To s.longi + Print Chr(8) & s.dato(i); + If i < s.longi Then Print "."; + Next i + Print +End Sub + +Function factorial(n As Integer) As Longint + If n <= 1 Then Return 1 + Return n * factorial(n - 1) +End Function + +Function tagset(n As Integer) As Sequence + Dim As Sequence result + result.longi = n + For i As Integer = 1 To n + result.dato(i) = i + Next i + Return result +End Function + +Sub showCards(s As Sequence) + Const cards = "AKQJT98765432" + Const suits = "SHDC" + + For i As Integer = 1 To s.longi + Dim As Integer c = s.dato(i) - 1 + Dim As String card = Mid(cards, (c Mod 13) + 1, 1) + Mid(suits, (c \ 13) + 1, 1) + Print card; Iif(((i Mod 13) = 0 Or i = s.longi), Chr(10), " "); + Next i + Print +End Sub + +Function fperm(fbn As Sequence, omega As Sequence) As Sequence + Dim As Integer i, g, tmp, j, m = 0 + Dim As Sequence result = omega + + For i = 1 To fbn.longi + g = fbn.dato(i) + If g > 0 Then + tmp = result.dato(m + g + 1) + For j = m + g + 1 To m + 2 Step -1 + result.dato(j) = result.dato(j - 1) + Next j + result.dato(m + 1) = tmp + End If + m += 1 + Next i + + result.longi = omega.longi + Return result +End Function + +Function factorialBaseNumbers(size As Integer, cntOnly As Integer) As Sequence + Dim As Sequence results + Dim As Integer res(1000) + Dim As Integer cnt, n, radix, k, i + + results.longi = 0 + cnt = 0 + n = 0 + Do + radix = 2 + k = n + For i = 1 To size + res(i) = 0 + Next i + + While k > 0 + If cntOnly = 0 Andalso radix <= size + 1 Then + res(size - radix + 2) = k Mod radix + End If + k \= radix + radix += 1 + Wend + + If radix > size + 2 Then Exit Do + + cnt += 1 + If cntOnly = 0 Then + results.longi += 1 + For i = 1 To size + results.dato((results.longi - 1) * size + i) = res(i) + Next i + End If + n += 1 + Loop + + If cntOnly Then + results.longi = 1 + results.dato(1) = cnt + End If + + Return results +End Function + +' Generate random factorial base number sequence +Function randFBN51() As Sequence + Dim As Sequence fbn51 + fbn51.longi = 51 + For i As Integer = 1 To 51 + fbn51.dato(i) = Int(Rnd * (52 - i)) + 1 + Next i + Return fbn51 +End Function + +' Main program +Randomize Timer +Dim As Integer i, j + +Dim As Sequence fbns = factorialBaseNumbers(3, 0) +Dim As Sequence omega +omega.longi = 4 +For i = 0 To 3 + omega.dato(i + 1) = i +Next i + +For i = 1 To fbns.longi + For j = 1 To 3 + Print fbns.dato((i-1)*3 + j) & "."; + Next j + Print Chr(8) & " ->"; + + Dim As Sequence tmp + tmp.longi = 3 + For j = 1 To 3 + tmp.dato(j) = fbns.dato((i-1)*3 + j) + Next j + + Dim As Sequence result = fperm(tmp, omega) + printSequence(result) +Next i + +Print +Dim As Sequence cnt = factorialBaseNumbers(10, 1) +Print "Permutations generated ="; cnt.dato(1) +Print " compared to 11! which ="; factorial(11) + +Print +Dim As Sequence fbn51s(3) + +' First predefined sequence +fbn51s(1).longi = 51 +Data 39,49,7,47,29,30,2,12,10,3,29,37,33,17,12,31,29,34,17,25,2,4,25,4,1,14,20,6,21,18,1,1,1,4,0,5,15,12,4,3,10,10,9,1,6,5,5,3,0,0,0 +For i = 1 To 51: Read fbn51s(1).dato(i): Next + +' Second predefined sequence +fbn51s(2).longi = 51 +Data 51,48,16,22,3,0,19,34,29,1,36,30,12,32,12,29,30,26,14,21,8,12,1,3,10,4,7,17,6,21,8,12,15,15,13,15,7,3,12,11,9,5,5,6,6,3,4,0,3,2,1 +For i = 1 To 51: Read fbn51s(2).dato(i): Next + +' Third random sequence +fbn51s(3) = randFBN51() + +' Show all card arrangements +For i = 1 To 3 + showCards(fperm(fbn51s(i), tagset(52))) +Next i + +Sleep diff --git a/Task/Factorial-base-numbers-indexing-permutations-of-a-collection/Java/factorial-base-numbers-indexing-permutations-of-a-collection.java b/Task/Factorial-base-numbers-indexing-permutations-of-a-collection/Java/factorial-base-numbers-indexing-permutations-of-a-collection.java index 9e7609637e..3f126f2202 100644 --- a/Task/Factorial-base-numbers-indexing-permutations-of-a-collection/Java/factorial-base-numbers-indexing-permutations-of-a-collection.java +++ b/Task/Factorial-base-numbers-indexing-permutations-of-a-collection/Java/factorial-base-numbers-indexing-permutations-of-a-collection.java @@ -58,7 +58,7 @@ public final class FactorialBaseNumbersIndexingPermutations { System.out.println("Random shuffle:"); ThreadLocalRandom random = ThreadLocalRandom.current(); factoradic.clear(); - for ( int i = 0; i < 52; i++ ) { + for ( int i = 0; i < cards.size() - 1; i++ ) { factoradic.add(random.nextInt(cards.size() - i)); } System.out.println(toString(factoradic, ".") + " --> "); diff --git a/Task/Factorial-base-numbers-indexing-permutations-of-a-collection/JavaScript/factorial-base-numbers-indexing-permutations-of-a-collection.js b/Task/Factorial-base-numbers-indexing-permutations-of-a-collection/JavaScript/factorial-base-numbers-indexing-permutations-of-a-collection.js new file mode 100644 index 0000000000..2b4f52172f --- /dev/null +++ b/Task/Factorial-base-numbers-indexing-permutations-of-a-collection/JavaScript/factorial-base-numbers-indexing-permutations-of-a-collection.js @@ -0,0 +1,170 @@ +// Helper function to convert values to strings +function stringify(text) { + return text; +} + +function stringifyNumber(number) { + return String(number); +} + +// Join array elements with delimiter +function toStringArray(factoradic, delimiter) { + let result = ""; + for (let i = 0; i < factoradic.length - 1; i++) { + result += stringifyNumber(factoradic[i]) + delimiter; + } + result += stringifyNumber(factoradic[factoradic.length - 1]); + return result; +} + +// Calculate factorial +function factorial(n) { + let result = 1; + for (let i = 2; i <= n; i++) { + result *= i; + } + return result; +} + +// Increment factoradic number +function increment(factoradic) { + let index = factoradic.length - 1; + while (index >= 0 && factoradic[index] === factoradic.length - index) { + factoradic[index] = 0; + index -= 1; + } + if (index >= 0) { + factoradic[index] += 1; + } +} + +// Split string by delimiter +function splitString(text, delimiter) { + const lines = []; + let start = 0; + let end = text.indexOf(delimiter); + + while (end !== -1) { + const line = text.substring(start, end); + if (line !== "") { + lines.push(line); + } + start = end + 1; + end = text.indexOf(delimiter, start); + } + + const lastLine = text.substring(start); + if (lastLine !== "") { + lines.push(lastLine); + } + + return lines; +} + +// Convert "a.b.c" format to array of integers +function convertToVectorOfInteger(text) { + const result = []; + const numbers = splitString(text, '.'); + for (const number of numbers) { + result.push(parseInt(number, 10)); + } + return result; +} + +// Generate permutation from elements and factoradic representation +function permutation(elements, factoradic) { + const result = [...elements]; + let m = 0; + + for (const g of factoradic) { + const element = result[m + g]; + result.splice(m + g, 1); + result.splice(m, 0, element); + m += 1; + } + + return result; +} + +// Main execution +function main() { + // Part 1 + console.log("Part 1: Permutations of 4 elements"); + console.log("=".repeat(50)); + + let elements = convertToVectorOfInteger("0.1.2.3"); + let factoradic = convertToVectorOfInteger("0.0.0"); + + for (let i = 0; i < factorial(4); i++) { + const rotated = permutation(elements, factoradic); + console.log(toStringArray(factoradic, '.') + " --> " + rotated.join(' ')); + increment(factoradic); + } + console.log(); + + // Part 2 + console.log("Part 2: Permutations of 11 digits"); + console.log("=".repeat(50)); + + const limit = factorial(11); + elements = convertToVectorOfInteger("0.1.2.3.4.5.6.7.8.9.10"); + factoradic = convertToVectorOfInteger("0.0.0.0.0.0.0.0.0.0"); + + for (let i = 0; i < limit; i++) { + const rotated = permutation(elements, factoradic); + if (i < 3 || i > limit - 4) { + console.log(toStringArray(factoradic, '.') + " --> " + rotated.join(' ')); + } else if (i === 3) { + console.log(" [ ... ] "); + } + increment(factoradic); + } + console.log("Number of permutations is 11! = " + limit); + console.log(); + + // Part 3 + console.log("Part 3: Card shuffling with factoradic representation"); + console.log("=".repeat(50)); + + const codes = [ + "39.49.7.47.29.30.2.12.10.3.29.37.33.17.12.31.29.34.17.25.2.4.25.4.1.14.20.6.21.18.1.1.1.4.0.5.15.12.4.3.10.10.9.1.6.5.5.3.0.0.0", + "51.48.16.22.3.0.19.34.29.1.36.30.12.32.12.29.30.26.14.21.8.12.1.3.10.4.7.17.6.21.8.12.15.15.13.15.7.3.12.11.9.5.5.6.6.3.4.0.3.2.1" + ]; + + const suits = ['♠', '♥', '♦', '♣']; + const ranks = ['A', 'K', 'Q', 'J', '10', '9', '8', '7', '6', '5', '4', '3', '2']; + + const cards = []; + for (const suit of suits) { + for (const rank of ranks) { + cards.push(rank + suit); + } + } + + console.log("Original deck of cards:"); + console.log(cards.join(' ')); + console.log(); + + console.log("Task shuffles:"); + for (const code of codes) { + console.log(code + " --> "); + factoradic = convertToVectorOfInteger(code); + const shuffled = permutation(cards, factoradic); + console.log(shuffled.join(' ')); + console.log(); + } + + console.log("Random shuffle:"); + factoradic = []; + for (let i = 0; i < cards.length - 1; i++) { + const randomIndex = Math.floor(Math.random() * (cards.length - i)); + factoradic.push(randomIndex); + } + + console.log(toStringArray(factoradic, '.') + " --> "); + const randomShuffled = permutation(cards, factoradic); + console.log(randomShuffled.join(' ')); +} + +// Run the program +main(); diff --git a/Task/Factorial-base-numbers-indexing-permutations-of-a-collection/Julia/factorial-base-numbers-indexing-permutations-of-a-collection.julia b/Task/Factorial-base-numbers-indexing-permutations-of-a-collection/Julia/factorial-base-numbers-indexing-permutations-of-a-collection.jl similarity index 100% rename from Task/Factorial-base-numbers-indexing-permutations-of-a-collection/Julia/factorial-base-numbers-indexing-permutations-of-a-collection.julia rename to Task/Factorial-base-numbers-indexing-permutations-of-a-collection/Julia/factorial-base-numbers-indexing-permutations-of-a-collection.jl diff --git a/Task/Factorial-primes/ALGOL-W/factorial-primes.alg b/Task/Factorial-primes/ALGOL-W/factorial-primes.alg new file mode 100644 index 0000000000..d8a6380cc6 --- /dev/null +++ b/Task/Factorial-primes/ALGOL-W/factorial-primes.alg @@ -0,0 +1,75 @@ +begin % find some factorial primes - primes that are f - 1 or f + 1 % + % for some factorial f % + + % returns true if p is prime, false otherwise % + logical procedure isPrime ( integer value p ) ; + if p <= 1 or p rem 2 = 0 then p = 2 + else begin + logical prime; + integer rootP, i; + prime := true; + i := 3; + rootP := entier( sqrt( p ) ); + while i <= rootP and prime do begin + prime := p rem i not = 0; + i := i + 2 + end; + prime + end isPrime ; + + % returns true if p is prime, false otherwise % + logical procedure isPrimeLongReal ( long real value p ) ; + if p <= MAXINTEGER then begin + % p is small enough to test using integer arithmetic % + isPrime( entier( p ) ) + end + else begin + % p is too large for integer primality testing % + logical prime; + integer rootP, i; + prime := true; + i := 2; + rootP := entier( longsqrt( p ) ); + while i <= rootP and prime do begin + long real pOverI; + pOverI := p / i; + prime := roundToReal( pOverI ) not = pOverI; + i := if i < 3 then 3 else i + 2 + end; + prime + end isPrime ; + + begin + long real f; + integer fpCount, n; + fpCount := 0; + n := 0; + f := 1; + while fpCount < 10 do begin + long real fp; + string(1) fpOp; + n := n + 1; + f := f * n; + fpOp := "-"; + for offset := -1 step 2 until 1 do begin + fp := f + offset; + if fp < MAXINTEGER then begin + if isPrime( entier( fp ) ) then begin + fpCount := fpCount + 1; + write( s_w := 0, i_w := 2, fpCount, ":" ); + writeon( s_w := 0, i_w := 4, n, "! ", fpOp, " 1 = " ); + writeon( s_w := 0, i_w := 1, entier( fp ) ) + end if_isPrime__entier__fp + end + else if isPrimeLongReal( fp ) then begin + fpCount := fpCount + 1; + write( s_w := 0, i_w := 2, fpCount, ":" ); + writeon( s_w := 0, i_w := 4, n, "! ", fpOp, " 1 = " ); + writeon( r_format := "A", r_w := 1, r_d := 0, fp ) + end if_isPrime__fp__isPrimeLongReal__fp ; + fpOp := "+" + end for_fp + end while_fpCount_lt_10 + end + +end. diff --git a/Task/Factorial-primes/AWK/factorial-primes.awk b/Task/Factorial-primes/AWK/factorial-primes.awk new file mode 100644 index 0000000000..b2cb4bb04a --- /dev/null +++ b/Task/Factorial-primes/AWK/factorial-primes.awk @@ -0,0 +1,15 @@ +function isprime(n, i) { + if(n==2)return 1 + if(n<2||n%2==0)return 0 + for(i=3;i*i<=n;i+=2) + if(n%i==0)return 0 + return 1 +} + +BEGIN { + for(x=i=1;z<10;i++){ + x*=i + if(isprime(x-1)){z++;print i"! - 1 = "x-1} + if(isprime(x+1)){z++;print i"! + 1 = "x+1} + } +} diff --git a/Task/Factorial-primes/Ada/factorial-primes.adb b/Task/Factorial-primes/Ada/factorial-primes.adb new file mode 100644 index 0000000000..f264eb9d50 --- /dev/null +++ b/Task/Factorial-primes/Ada/factorial-primes.adb @@ -0,0 +1,95 @@ +-- Rosetta Code Task written in Ada +-- Factorial primes +-- https://rosettacode.org/wiki/Factorial_primes +-- August 2024, R. B. E. +-- Using GNAT Big Integers, GNAT version 14.1, MacOS 14.6.1, M1 chip + +pragma Ada_2022; +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; +with Ada.Numerics.Big_Numbers.Big_Integers; use Ada.Numerics.Big_Numbers.Big_Integers; + +procedure Factorial_Primes is + + function Is_Prime (N : in Big_Integer) return Boolean is + Big_0 : Big_Natural := To_Big_Integer (0); + Big_2 : Big_Natural := To_Big_Integer (2); + Big_3 : Big_Natural := To_Big_Integer (3); + Big_Temp : Big_Natural := To_Big_Integer (5); + begin + if N < Big_2 then + return False; + end if; + if N mod Big_2 = Big_0 then + return N = Big_2; + end if; + if N mod Big_3 = Big_0 then + return N = Big_3; + end if; + while Big_Temp * Big_Temp <= N loop + if N mod Big_Temp = Big_0 then + return False; + end if; + Big_Temp := Big_Temp + Big_2; + if N mod Big_Temp = Big_0 then + return False; + end if; + Big_Temp := Big_Temp + 4; + end loop; + return True; + end Is_Prime; + + function Factorial (N : Positive) return Big_Integer is + type Factorial_Array is array (1..12) of Big_Integer; + First12_Facts : Factorial_Array; + Result : Big_Integer; + begin + First12_Facts (1) := To_Big_Integer (1); + for I in 2..12 loop + First12_Facts (I) := First12_Facts (I-1) * To_Big_Integer (I); + end loop; + if (N <= 12) then + return First12_Facts (N); + else + Result := First12_Facts (12); + for I in 13..N loop + Result := Result * To_Big_Integer (I); + end loop; + end if; + return Result; + end Factorial; + + Fact : Big_Integer; + Fact_Plus_One : Big_Integer; + Fact_Minus_One : Big_Integer; + Big_One : constant Big_Integer := To_Big_Integer (1); + I, Count : Natural := 0; + Limit : constant Positive := 10; + +begin + loop + I := I + 1; + Fact := Factorial (I); + if (is_Prime (Fact - Big_One)) then + Count := Count + 1; + Put (Count, 3); + Put (": "); + Put (I, 5); + Put ("! - 1 "); + Fact_Minus_One := Fact - Big_One; + Put (To_String (Arg => Fact_Minus_One, Width => 40)); + New_Line; + end if; + if (is_Prime (Fact + Big_One)) then + Count := Count + 1; + Put (Count, 3); + Put (": "); + Put (I, 5); + Put ("! + 1 "); + Fact_Plus_One := Fact + Big_One; + Put (To_String (Arg => Fact_Plus_One, Width => 40)); + New_Line; + end if; + exit when Count >= Limit; + end loop; +end Factorial_Primes; diff --git a/Task/Factorial-primes/Agena/factorial-primes.agena b/Task/Factorial-primes/Agena/factorial-primes.agena new file mode 100644 index 0000000000..0a76370d5e --- /dev/null +++ b/Task/Factorial-primes/Agena/factorial-primes.agena @@ -0,0 +1,17 @@ +scope # find some factorial primes - primes that are f - 1 or f + 1 for some factorial f + + local f, fpCount, n := 1, 0, 1 + for n while fpCount < 10 do + f *:= n; + local fpOp := "-"; + for fp from f - 1 to f + 1 by 2 do + if numtheory.isprime( fp ) then + fpCount +:= 1; + # printing fp with %s as %d has trouble with 14! - 1 + printf( "%2d:%4d! %s 1 = %s\n", fpCount, n, fpOp, fp ) + fi; + fpOp := "+" + od + od + +end diff --git a/Task/Factorial-primes/Common-Lisp/factorial-primes.lisp b/Task/Factorial-primes/Common-Lisp/factorial-primes.lisp new file mode 100644 index 0000000000..0e28867922 --- /dev/null +++ b/Task/Factorial-primes/Common-Lisp/factorial-primes.lisp @@ -0,0 +1,27 @@ +(defun factorial (x) + (if (= x 1) + x + (* x (factorial (- x 1))))) + +(defun is-factor (x y) + (zerop (mod x y))) + +(defun is-prime (n) + (cond ((< n 4) (or (= n 2) (= n 3))) + ((or (zerop (mod n 2)) (zerop (mod n 3))) nil) + (t (loop for i from 5 to (floor (sqrt n)) by 6 + never (or (is-factor n i) + (is-factor n (+ i 2))))))) + +(defun main (&optional (limit 10)) + (let ((n 0) + (f 0)) + (loop while (< n limit) + for i from 1 + do (setf f (factorial i)) + (when (is-prime (+ f 1)) + (incf n) + (format t "~2d: ~2d! + 1 = ~12d~%" n i (+ f 1))) + (when (is-prime (- f 1)) + (incf n) + (format t "~2d: ~2d! - 1 = ~12d~%" n i (- f 1)))))) diff --git a/Task/Factorial-primes/Delphi/factorial-primes.delphi b/Task/Factorial-primes/Delphi/factorial-primes.pas similarity index 100% rename from Task/Factorial-primes/Delphi/factorial-primes.delphi rename to Task/Factorial-primes/Delphi/factorial-primes.pas diff --git a/Task/Factorial-primes/EasyLang/factorial-primes.easy b/Task/Factorial-primes/EasyLang/factorial-primes.easy index b12ef97ac5..fd62915528 100644 --- a/Task/Factorial-primes/EasyLang/factorial-primes.easy +++ b/Task/Factorial-primes/EasyLang/factorial-primes.easy @@ -1,12 +1,8 @@ func isprim num . - if num < 2 - return 0 - . + if num < 2 : return 0 i = 2 while i <= sqrt num - if num mod i = 0 - return 0 - . + if num mod i = 0 : return 0 i += 1 . return 1 @@ -16,7 +12,7 @@ while count < 10 n += 1 f *= n op$ = "-" - for fp in [ f - 1 f + 1 ] + for fp in [ f - 1, f + 1 ] if isprim fp = 1 count += 1 print n & "! " & op$ & " 1 = " & fp diff --git a/Task/Factorial-primes/Fennel/factorial-primes.fennel b/Task/Factorial-primes/Fennel/factorial-primes.fennel new file mode 100644 index 0000000000..8151c241fb --- /dev/null +++ b/Task/Factorial-primes/Fennel/factorial-primes.fennel @@ -0,0 +1,30 @@ +(do ;;; find some factorial primes - primes that are f - 1 or f + 1 for some factorial f + + (fn is-prime [p] + (if (or (<= p 1) (= 0 (% p 2))) + (= p 2) + ;else + (do (var (prime i root-p) (values true 3 (math.floor (math.sqrt p)))) + (while (and (<= i root-p) prime) + (set (prime i) (values (not= 0 (% p i)) (+ i 1))) + ) + prime + ) + ) + ) + + (var (f fp-count n) (values 1 0 1)) + (while (< fp-count 10) + (set f (* f n)) + (var fp-op "-") + (for [fp (- f 1) (+ f 1) 2] + (when (is-prime fp) + (set fp-count (+ fp-count 1)) + (io.write (string.format "%2d:%4d! %s 1 = %d\n" fp-count n fp-op fp)) + ) + (set fp-op "+") + ) + (set n (+ n 1)) + ) + +) diff --git a/Task/Factorial-primes/Frink/factorial-primes.frink b/Task/Factorial-primes/Frink/factorial-primes.frink new file mode 100644 index 0000000000..e8941229fe --- /dev/null +++ b/Task/Factorial-primes/Frink/factorial-primes.frink @@ -0,0 +1,36 @@ +isFactorialPrime[x] := +{ + if isPrime[x!+1] + return +1 + if x>=2 and isPrime[x!-1] + return -1 + return 0 +} + +count = 0 +n = 1 +res = new array +do +{ + f = isFactorialPrime[n] + if f != 0 + { + count = count + 1 + line = ["$count:", "$n!", f<0 ? "-" : "+", 1, "="] + line.pushAll[formatFac[n!+f]] + res.push[line] + } + n = n + 1 +} until count == 30 + +println[formatTable[res, "right"]] + +formatFac[n] := +{ + s = toString[n] + len = length[s] + if len > 40 + return [left[s,20] + "..." + right[s,20], " ($len digits)"] + else + return [s] +} diff --git a/Task/Factorial-primes/Go/factorial-primes.go b/Task/Factorial-primes/Go/factorial-primes.go new file mode 100644 index 0000000000..a808dfb619 --- /dev/null +++ b/Task/Factorial-primes/Go/factorial-primes.go @@ -0,0 +1,59 @@ +package main + +import ( + "fmt" + "math/big" +) + +func main() { + n, count := 0, 0 + + for count < 10 { + n++ + f := factorial(n) + + if isPrime(f.Sub(f, big.NewInt(1))) { + count++ + fmt.Printf("%2d: %2d! - 1 = %s\n", count, n, f.String()) + } + + if isPrime(f.Add(f, big.NewInt(2))) { + count++ + fmt.Printf("%2d: %2d! + 1 = %s\n", count, n, f.String()) + } + } +} + +func factorial(n int) *big.Int { + result := big.NewInt(1) + + for i := 2; i <= n; i++ { + result.Mul(result, big.NewInt(int64(i))) + } + + return result +} + +func isPrime(num *big.Int) bool { + if num.Cmp(big.NewInt(2)) < 0 { + return false + } + + if num.Cmp(big.NewInt(2)) == 0 { + return true + } + + if new(big.Int).Mod(num, big.NewInt(2)).Cmp(big.NewInt(0)) == 0 { + return false + } + + sqrt := new(big.Int).Sqrt(num) + + for i := big.NewInt(3); i.Cmp(sqrt) <= 0; i.Add(i, big.NewInt(2)) { + if new(big.Int).Mod(num, i).Cmp(big.NewInt(0)) == 0 { + return false + } + } + + return true +} diff --git a/Task/Factorial-primes/Haskell/factorial-primes.hs b/Task/Factorial-primes/Haskell/factorial-primes.hs new file mode 100644 index 0000000000..9d2d00ea68 --- /dev/null +++ b/Task/Factorial-primes/Haskell/factorial-primes.hs @@ -0,0 +1,26 @@ +isPrime :: Integer -> Bool +isPrime n + | n < 2 = False + | n == 2 = True + | otherwise = 0 == length [i | i <- [2..floor(sqrt (fromIntegral n))], n `mod` i == 0] + +data Op = SubtractOne | AddOne + deriving (Show) + +data Prime = Prime + { fact :: Integer, + prime :: Integer, + op :: Op +} deriving (Show) + +getFactorialPrimes :: Integer -> [Prime] +getFactorialPrimes n + | isPrime (f - 2) = Prime {fact = n, prime = f - 2, op = SubtractOne} : + (if isPrime f then [Prime {fact = n, prime = f, op = AddOne}] else []) + | otherwise = (if isPrime f then [Prime {fact = n, prime = f, op = AddOne}] else []) + where + factorial n = product[1..n] + f = factorial n + 1 + +factorialPrimes = concat $ map getFactorialPrimes [1..] +main = mapM_ print $ take 10 factorialPrimes diff --git a/Task/Factorial-primes/Julia/factorial-primes.julia b/Task/Factorial-primes/Julia/factorial-primes.jl similarity index 100% rename from Task/Factorial-primes/Julia/factorial-primes.julia rename to Task/Factorial-primes/Julia/factorial-primes.jl diff --git a/Task/Factorial-primes/Kotlin/factorial-primes.kts b/Task/Factorial-primes/Kotlin/factorial-primes.kts new file mode 100644 index 0000000000..22db036df6 --- /dev/null +++ b/Task/Factorial-primes/Kotlin/factorial-primes.kts @@ -0,0 +1,43 @@ +import java.math.BigInteger +import java.math.BigInteger.ONE + +enum class Difference(private val displayText: String) { + MINUS_ONE("- 1"), PLUS_ONE("+ 1"); + + override fun toString(): String { + return displayText + } +} + +fun main() { + var currentFactorial = ONE + var highestFactor = 1L + var found = 0 + + while(found < 30) { + if ((currentFactorial - ONE).isProbablePrime(25)) { + printlnFactorialPrime(currentFactorial - ONE, highestFactor, Difference.MINUS_ONE) + found++ + } + if ((currentFactorial + ONE).isProbablePrime(25)) { + printlnFactorialPrime(currentFactorial + ONE, highestFactor, Difference.PLUS_ONE) + found++ + } + + highestFactor++ + currentFactorial *= BigInteger.valueOf(highestFactor) + } +} + +fun printlnFactorialPrime(factorialPrime: BigInteger, base: Long, difference: Difference) = + println("${base}! $difference = ${factorialPrime.shortenIfNecessary()}") + +fun BigInteger.shortenIfNecessary(): String { + val digits = toString() + val length = digits.length + return if (length <= 40) { + digits + } else { + "${digits.take(20)}...${digits.takeLast(20)} ($length digits)" + } +} diff --git a/Task/Factorial-primes/Lua/factorial-primes.lua b/Task/Factorial-primes/Lua/factorial-primes.lua index 8c17ccd8e5..55c20a12e9 100644 --- a/Task/Factorial-primes/Lua/factorial-primes.lua +++ b/Task/Factorial-primes/Lua/factorial-primes.lua @@ -1,39 +1,29 @@ -do -- find some factorial primes - primes that are f - 1 or f + 1 - -- for some factorial f +do -- find some factorial primes - primes that are f - 1 or f + 1 for some factorial f - function isPrime( p ) + local function isPrime( p ) if p <= 1 or p % 2 == 0 then return p == 2 else - local prime = true - local i = 3 - local rootP = math.floor( math.sqrt( p ) ) + local prime, i, rootP = true, 3, math.floor( math.sqrt( p ) ) while i <= rootP and prime do - prime = p % i ~= 0 - i = i + 2 + prime, i = p % i ~= 0, i + 1 end return prime end end - local f = 1 - local fpCount = 0 - local n = 0 - local fpOp = "" + local f, fpCount, n = 1, 0, 1 while fpCount < 10 do - n = n + 1 - f = f * n - fpOp = "-" + f = f * n + local fpOp = "-" for fp = f - 1, f + 1, 2 do if isPrime( fp ) then fpCount = fpCount + 1 - io.write( string.format( "%2d", fpCount ), ":" - , string.format( "%4d", n ), "! " - , fpOp, " 1 = ", fp, "\n" - ) + io.write( string.format( "%2d:%4d! %s 1 = %d\n", fpCount, n, fpOp, fp ) ) end fpOp = "+" end + n = n + 1 end end diff --git a/Task/Factorial-primes/OCaml/factorial-primes.ocaml b/Task/Factorial-primes/OCaml/factorial-primes.ml similarity index 100% rename from Task/Factorial-primes/OCaml/factorial-primes.ocaml rename to Task/Factorial-primes/OCaml/factorial-primes.ml diff --git a/Task/Factorial-primes/PascalABC.NET/factorial-primes.pas b/Task/Factorial-primes/PascalABC.NET/factorial-primes.pas new file mode 100644 index 0000000000..817ecf3506 --- /dev/null +++ b/Task/Factorial-primes/PascalABC.NET/factorial-primes.pas @@ -0,0 +1,42 @@ +function IsPrime(n: int64): boolean; +begin + if (n = 2) or (n = 3) then Result := true + else if (n <= 1) or ((n mod 2) = 0) or ((n mod 3) = 0) then Result := false + else + begin + var i := 5; + Result := False; + while i <= trunc(sqrt(n)) do + begin + if ((n mod i) = 0) or ((n mod (i + 2)) = 0) then exit; + i += 6; + end; + Result := True; + end; +end; + +function Factorial(n: integer): int64; +begin + Result := 1; + for var i := 2 to n do Result *= i; +end; + +begin + var found := 0; + var i := 1; + while found < 10 do + begin + var fact := Factorial(i); + if IsPrime(fact - 1) then + begin + writeln(i:2, '! - 1 = ', fact - 1); + found += 1; + end; + if IsPrime(fact + 1) then + begin + writeln(i:2, '! + 1 = ', fact + 1); + found += 1; + end; + i += 1; + end; +end. diff --git a/Task/Factorial-primes/Pluto/factorial-primes.pluto b/Task/Factorial-primes/Pluto/factorial-primes.pluto new file mode 100644 index 0000000000..4e6b707c4e --- /dev/null +++ b/Task/Factorial-primes/Pluto/factorial-primes.pluto @@ -0,0 +1,20 @@ +do -- find some factorial primes - primes that are f - 1 or f + 1 for some factorial f + + local fmt = require( "fmt" ) -- RC Pluto formatting library + local int = require( "int" ) -- RC Pluto integer library, inc. prime utilities + + local f, fpCount, n = 1, 0, 0 + while fpCount < 10 do + n += 1 + f *= n + local fpOp = "-" + for fp = f - 1, f + 1, 2 do + if int.isprime( fp ) then + fpCount += 1 + fmt.write( "%2d:%4d! %s 1 = %d\n", fpCount, n, fpOp, fp ) + end + fpOp = "+" + end + end + +end diff --git a/Task/Factorial-primes/R/factorial-primes.r b/Task/Factorial-primes/R/factorial-primes.r new file mode 100644 index 0000000000..583498b194 --- /dev/null +++ b/Task/Factorial-primes/R/factorial-primes.r @@ -0,0 +1,29 @@ +library(gmp) + +print_20digits <- function(z){ + s <- as.character(z) + if(nchar(s)>40){ + paste0(substring(s, 1, 20), "...", substring(s, nchar(s)-19, nchar(s))) + } + else return(s) +} + +count <- 0 +n <- 1 +while(count<33){ + plus <- factorialZ(n)+1 + minus <- factorialZ(n)-1 + if(isprime(plus)!=0){ + cat(n, "!+1 = ", print_20digits(plus), + " (", nchar(as.character(plus)), " digits)", + "\n", sep="") + count <- count+1 + } + if(isprime(minus)!=0){ + cat(n, "!-1 = ", print_20digits(minus), + " (", nchar(as.character(minus)), " digits)", + "\n", sep="") + count <- count+1 + } + n <- n+1 +} diff --git a/Task/Factorial-primes/Unicon/factorial-primes.unicon b/Task/Factorial-primes/Unicon/factorial-primes.unicon new file mode 100644 index 0000000000..4de95546a3 --- /dev/null +++ b/Task/Factorial-primes/Unicon/factorial-primes.unicon @@ -0,0 +1,11 @@ +link fastprime + +procedure main(A) + limit := \A[1] | 10 + every f := gfactorial(n := seq()) do { + if (x := (is_prime(y := f-1),n||"!-1")) then + (write(" (",x,",",y,")"), if 0 = (limit -:= 1) then break) + if (x := (is_prime(y := f+1),n||"!+1")) then + (write(" (",x,",",y,")"), if 0 = (limit -:= 1) then break) + } +end diff --git a/Task/Factorial/8th/factorial.8th b/Task/Factorial/8th/factorial.8th new file mode 100644 index 0000000000..d385be5c27 --- /dev/null +++ b/Task/Factorial/8th/factorial.8th @@ -0,0 +1,2 @@ +: factorial \ n -- n! + 1 swap ' n:* 1 rot loop ; diff --git a/Task/Factorial/ALGOL-60/factorial.alg b/Task/Factorial/ALGOL-60/factorial.alg deleted file mode 100644 index 6b44ce94eb..0000000000 --- a/Task/Factorial/ALGOL-60/factorial.alg +++ /dev/null @@ -1,14 +0,0 @@ -begin - comment factorial - algol 60; - integer procedure factorial(n); integer n; - begin - integer i,fact; - fact:=1; - for i:=2 step 1 until n do - fact:=fact*i; - factorial:=fact - end; - integer i; - for i:=1 step 1 until 10 do outinteger(1,factorial(i)); - outstring(1,"\n") -end diff --git a/Task/Factorial/ALGOL-68/factorial-1.alg b/Task/Factorial/ALGOL-68/factorial-1.alg deleted file mode 100644 index 170a8c2633..0000000000 --- a/Task/Factorial/ALGOL-68/factorial-1.alg +++ /dev/null @@ -1,5 +0,0 @@ -PROC factorial = (INT upb n)LONG LONG INT:( - LONG LONG INT z := 1; - FOR n TO upb n DO z *:= n OD; - z -); ~ diff --git a/Task/Factorial/ALGOL-68/factorial-2.alg b/Task/Factorial/ALGOL-68/factorial-2.alg deleted file mode 100644 index 191fe07cfb..0000000000 --- a/Task/Factorial/ALGOL-68/factorial-2.alg +++ /dev/null @@ -1,30 +0,0 @@ -INT g = 7; -[]REAL p = []REAL(0.99999999999980993, 676.5203681218851, -1259.1392167224028, - 771.32342877765313, -176.61502916214059, 12.507343278686905, - -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7)[@0]; - -PROC complex gamma = (COMPL in z)COMPL: ( - # Reflection formula # - COMPL z := in z; - IF re OF z < 0.5 THEN - pi / (complex sin(pi*z)*complex gamma(1-z)) - ELSE - z -:= 1; - COMPL x := p[0]; - FOR i TO g+1 DO x +:= p[i]/(z+i) OD; - COMPL t := z + g + 0.5; - complex sqrt(2*pi) * t**(z+0.5) * complex exp(-t) * x - FI -); - -OP ** = (COMPL z, p)COMPL: ( z=0|0|complex exp(complex ln(z)*p) ); -PROC factorial = (COMPL n)COMPL: complex gamma(n+1); - -FORMAT compl fmt = $g(-16, 8)"⊥"g(-10, 8)$; - -test:( - printf(($q"factorial(-0.5)**2="f(compl fmt)l$, factorial(-0.5)**2)); - FOR i TO 9 DO - printf(($q"factorial("d")="f(compl fmt)l$, i, factorial(i))) - OD -) diff --git a/Task/Factorial/ALGOL-68/factorial-3.alg b/Task/Factorial/ALGOL-68/factorial-3.alg deleted file mode 100644 index c9c3e54dd2..0000000000 --- a/Task/Factorial/ALGOL-68/factorial-3.alg +++ /dev/null @@ -1,7 +0,0 @@ -PROC factorial = (INT n)LONG LONG INT: - CASE n+1 IN - 1,1,2,6,24,120,720 # a brief lookup # - OUT - n*factorial(n-1) - ESAC -; ~ diff --git a/Task/Factorial/ALGOL-W/factorial.alg b/Task/Factorial/ALGOL-W/factorial.alg deleted file mode 100644 index d52282365a..0000000000 --- a/Task/Factorial/ALGOL-W/factorial.alg +++ /dev/null @@ -1,15 +0,0 @@ -begin - % computes factorial n iteratively % - integer procedure factorial( integer value n ) ; - if n < 2 - then 1 - else begin - integer f; - f := 2; - for i := 3 until n do f := f * i; - f - end factorial ; - - for t := 0 until 10 do write( "factorial: ", t, factorial( t ) ); - -end. diff --git a/Task/Factorial/Ada/factorial-1.ada b/Task/Factorial/Ada/factorial-1.adb similarity index 100% rename from Task/Factorial/Ada/factorial-1.ada rename to Task/Factorial/Ada/factorial-1.adb diff --git a/Task/Factorial/Ada/factorial-2.ada b/Task/Factorial/Ada/factorial-2.adb similarity index 100% rename from Task/Factorial/Ada/factorial-2.ada rename to Task/Factorial/Ada/factorial-2.adb diff --git a/Task/Factorial/Ada/factorial-3.ada b/Task/Factorial/Ada/factorial-3.adb similarity index 100% rename from Task/Factorial/Ada/factorial-3.ada rename to Task/Factorial/Ada/factorial-3.adb diff --git a/Task/Factorial/Agena/factorial.agena b/Task/Factorial/Agena/factorial.agena new file mode 100644 index 0000000000..8b050fee0e --- /dev/null +++ b/Task/Factorial/Agena/factorial.agena @@ -0,0 +1,25 @@ +scope # factorials using the arbitrary precision mapm library + + import mapm; # explicit import needed for: Linux, Mac OS X, Windows and Solaris + + mapm.xdigits( 100 ); # need to set the precision - 100 is enough for 60! + + # computes factorial n iteratively, using mapm + local constant factorial := proc( n :: number ) :: xnumber + if n < 2 then return mapm.xnumber( 1 ) + else + local f := mapm.xnumber( 2 ); + for i from 3 to n do f := f * i od; + return f + fi + end; + # returns a string representation of the integer portion of an xnumber + local constant asstring := proc( n :: xnumber ) :: string + local constant str := mapm.xtostring( n ); + local constant point := "." in str; + return if point <> null then str[ 1 to point - 1 ] else str fi; + end; + + for t from 0 to 9 do printf( "%2d! is %d\n", t, mapm.xtonumber( factorial( t ) ) ) od; + for t from 10 to 60 by 10 do printf( "%2d! is %s\n", t, asstring( factorial( t ) ) ) od; +end diff --git a/Task/Factorial/Apple/factorial-1.apple b/Task/Factorial/Apple/factorial-1.apple new file mode 100644 index 0000000000..a882f89b83 --- /dev/null +++ b/Task/Factorial/Apple/factorial-1.apple @@ -0,0 +1,2 @@ + > [(*)/ₒ 1 (⍳ 1 x 1)] 7 +5040 diff --git a/Task/Factorial/Apple/factorial-2.apple b/Task/Factorial/Apple/factorial-2.apple new file mode 100644 index 0000000000..bf4bf79fa7 --- /dev/null +++ b/Task/Factorial/Apple/factorial-2.apple @@ -0,0 +1,16 @@ + > :asm [(*)/ₒ 1 (⍳ 1 x 1)] + + mov x6, x0 + mov x0, #0x1 + mov x2, #0x1 + eor x1, x1, x1 + cmp x1, x6 + b.GE apple_1 +apple_0: + mul x0, x0, x2 + add x2, x2, #0x1 + add x1, x1, #0x1 + cmp x1, x6 + b.LT apple_0 +apple_1: + ret diff --git a/Task/Factorial/ArkScript/factorial.ark b/Task/Factorial/ArkScript/factorial.ark new file mode 100644 index 0000000000..41607c70ad --- /dev/null +++ b/Task/Factorial/ArkScript/factorial.ark @@ -0,0 +1,13 @@ +(let factorial (fun (n) { + (mut result 1) + (mut i 2) + (while (< i n) { + (set result (* result i)) + (set i (+ 1 i)) }) + result })) + +(import std.List) + +(list:forEach + (list:iota 0 8) + (fun (n) (print n "\t" (factorial n)))) diff --git a/Task/Factorial/Arturo/factorial-1.arturo b/Task/Factorial/Arturo/factorial-1.arturo index e61492a8b4..5adbf912c3 100644 --- a/Task/Factorial/Arturo/factorial-1.arturo +++ b/Task/Factorial/Arturo/factorial-1.arturo @@ -1,4 +1,7 @@ -factorial: $[n][ - if? n>0 [n * factorial n-1] - else [1] +factorial: function [n][ + switch n > 0 -> n * factorial n-1 + -> 1 ] + +loop 1..19 [x]-> + print ["Factorial of" x "=" factorial x] diff --git a/Task/Factorial/Arturo/factorial-2.arturo b/Task/Factorial/Arturo/factorial-2.arturo index 6e6d40e330..79b191bdb4 100644 --- a/Task/Factorial/Arturo/factorial-2.arturo +++ b/Task/Factorial/Arturo/factorial-2.arturo @@ -1,3 +1,7 @@ factorial: $[n][ fold.seed:1 1..n [a,b][a*b] ] + +loop 1..19 [x][ + print ["Factorial of" x "=" factorial x] +] diff --git a/Task/Factorial/AutoIt/factorial-1.autoit b/Task/Factorial/AutoIt/factorial-1.au3 similarity index 100% rename from Task/Factorial/AutoIt/factorial-1.autoit rename to Task/Factorial/AutoIt/factorial-1.au3 diff --git a/Task/Factorial/AutoIt/factorial-2.autoit b/Task/Factorial/AutoIt/factorial-2.au3 similarity index 100% rename from Task/Factorial/AutoIt/factorial-2.autoit rename to Task/Factorial/AutoIt/factorial-2.au3 diff --git a/Task/Factorial/CBASIC/factorial.basic b/Task/Factorial/CBASIC/factorial.basic new file mode 100644 index 0000000000..3ca40654ad --- /dev/null +++ b/Task/Factorial/CBASIC/factorial.basic @@ -0,0 +1,19 @@ +rem - return n! +def fn.factorial(n) + f = 1 + for i = 1 to n + f = f * i + next i + fn.factorial = f + return +fend + +print "Factorial Calculator" +print +print " n n!" +print "-------------------" +for k = 1 to 14 + print using "## ###,###,###,###"; k; fn.factorial(k) +next k + +end diff --git a/Task/Factorial/COBOL/factorial-1.cobol b/Task/Factorial/COBOL/factorial-1.cob similarity index 100% rename from Task/Factorial/COBOL/factorial-1.cobol rename to Task/Factorial/COBOL/factorial-1.cob diff --git a/Task/Factorial/COBOL/factorial-2.cobol b/Task/Factorial/COBOL/factorial-2.cob similarity index 100% rename from Task/Factorial/COBOL/factorial-2.cobol rename to Task/Factorial/COBOL/factorial-2.cob diff --git a/Task/Factorial/COBOL/factorial-3.cobol b/Task/Factorial/COBOL/factorial-3.cob similarity index 100% rename from Task/Factorial/COBOL/factorial-3.cobol rename to Task/Factorial/COBOL/factorial-3.cob diff --git a/Task/Factorial/COBOL/factorial-4.cobol b/Task/Factorial/COBOL/factorial-4.cob similarity index 100% rename from Task/Factorial/COBOL/factorial-4.cobol rename to Task/Factorial/COBOL/factorial-4.cob diff --git a/Task/Factorial/Chapel/factorial.chapel b/Task/Factorial/Chapel/factorial.chpl similarity index 100% rename from Task/Factorial/Chapel/factorial.chapel rename to Task/Factorial/Chapel/factorial.chpl diff --git a/Task/Factorial/Crystal/factorial-1.crystal b/Task/Factorial/Crystal/factorial-1.cr similarity index 100% rename from Task/Factorial/Crystal/factorial-1.crystal rename to Task/Factorial/Crystal/factorial-1.cr diff --git a/Task/Factorial/Crystal/factorial-2.crystal b/Task/Factorial/Crystal/factorial-2.cr similarity index 100% rename from Task/Factorial/Crystal/factorial-2.crystal rename to Task/Factorial/Crystal/factorial-2.cr diff --git a/Task/Factorial/Delphi/factorial-1.delphi b/Task/Factorial/Delphi/factorial-1.pas similarity index 100% rename from Task/Factorial/Delphi/factorial-1.delphi rename to Task/Factorial/Delphi/factorial-1.pas diff --git a/Task/Factorial/Delphi/factorial-2.delphi b/Task/Factorial/Delphi/factorial-2.pas similarity index 100% rename from Task/Factorial/Delphi/factorial-2.delphi rename to Task/Factorial/Delphi/factorial-2.pas diff --git a/Task/Factorial/Delphi/factorial-3.delphi b/Task/Factorial/Delphi/factorial-3.pas similarity index 100% rename from Task/Factorial/Delphi/factorial-3.delphi rename to Task/Factorial/Delphi/factorial-3.pas diff --git a/Task/Factorial/DuckDB/factorial-1.duckdb b/Task/Factorial/DuckDB/factorial-1.duckdb new file mode 100644 index 0000000000..e4f4ecf769 --- /dev/null +++ b/Task/Factorial/DuckDB/factorial-1.duckdb @@ -0,0 +1,3 @@ +create or replace function factorial(n) as ( + list_reduce( list_transform(range(1,n+1), x -> x::HUGEINT), (prod,n) -> prod * n) +); diff --git a/Task/Factorial/DuckDB/factorial-2.duckdb b/Task/Factorial/DuckDB/factorial-2.duckdb new file mode 100644 index 0000000000..0ba68192de --- /dev/null +++ b/Task/Factorial/DuckDB/factorial-2.duckdb @@ -0,0 +1,3 @@ +create or replace function double_precision_factorial(n) as ( + list_product( range(1, n+1) ) +); diff --git a/Task/Factorial/DuckDB/factorial-3.duckdb b/Task/Factorial/DuckDB/factorial-3.duckdb new file mode 100644 index 0000000000..d3a13b50ff --- /dev/null +++ b/Task/Factorial/DuckDB/factorial-3.duckdb @@ -0,0 +1,2 @@ +select n, n!, factorial(n), double_precision_factorial(n) +from values (4), (30), (33) t(n); diff --git a/Task/Factorial/EasyLang/factorial.easy b/Task/Factorial/EasyLang/factorial.easy index 1ad66bdb70..697c8807fd 100644 --- a/Task/Factorial/EasyLang/factorial.easy +++ b/Task/Factorial/EasyLang/factorial.easy @@ -1,8 +1,6 @@ func factorial n . r = 1 - for i = 2 to n - r *= i - . + for i = 2 to n : r *= i return r . print factorial 7 diff --git a/Task/Factorial/Elixir/factorial.elixir b/Task/Factorial/Elixir/factorial.ex similarity index 100% rename from Task/Factorial/Elixir/factorial.elixir rename to Task/Factorial/Elixir/factorial.ex diff --git a/Task/Factorial/Emacs-Lisp/factorial-1.l b/Task/Factorial/Emacs-Lisp/factorial-1.el similarity index 100% rename from Task/Factorial/Emacs-Lisp/factorial-1.l rename to Task/Factorial/Emacs-Lisp/factorial-1.el diff --git a/Task/Factorial/Emacs-Lisp/factorial-2.l b/Task/Factorial/Emacs-Lisp/factorial-2.el similarity index 100% rename from Task/Factorial/Emacs-Lisp/factorial-2.l rename to Task/Factorial/Emacs-Lisp/factorial-2.el diff --git a/Task/Factorial/Emacs-Lisp/factorial-3.l b/Task/Factorial/Emacs-Lisp/factorial-3.el similarity index 100% rename from Task/Factorial/Emacs-Lisp/factorial-3.l rename to Task/Factorial/Emacs-Lisp/factorial-3.el diff --git a/Task/Factorial/Euphoria/factorial-1.euphoria b/Task/Factorial/Euphoria/factorial-1.eu similarity index 100% rename from Task/Factorial/Euphoria/factorial-1.euphoria rename to Task/Factorial/Euphoria/factorial-1.eu diff --git a/Task/Factorial/Euphoria/factorial-2.euphoria b/Task/Factorial/Euphoria/factorial-2.eu similarity index 100% rename from Task/Factorial/Euphoria/factorial-2.euphoria rename to Task/Factorial/Euphoria/factorial-2.eu diff --git a/Task/Factorial/Euphoria/factorial-3.euphoria b/Task/Factorial/Euphoria/factorial-3.eu similarity index 100% rename from Task/Factorial/Euphoria/factorial-3.euphoria rename to Task/Factorial/Euphoria/factorial-3.eu diff --git a/Task/Factorial/Euphoria/factorial-4.euphoria b/Task/Factorial/Euphoria/factorial-4.eu similarity index 100% rename from Task/Factorial/Euphoria/factorial-4.euphoria rename to Task/Factorial/Euphoria/factorial-4.eu diff --git a/Task/Factorial/Fennel/factorial.fennel b/Task/Factorial/Fennel/factorial.fennel new file mode 100644 index 0000000000..c9024229d5 --- /dev/null +++ b/Task/Factorial/Fennel/factorial.fennel @@ -0,0 +1,18 @@ +(do + (fn factorial [n] ;;; iterative factorial + (if (< n 2) + 1 + ;else + (do (var f 2) + (for [i 3 n] + (set f (* f i)) + ) + f + ) + ) + ) + + (for [n 0 10] + (io.write (string.format "%2d! = %s\n" n (factorial n))) + ) +) diff --git a/Task/Factorial/Gleam/factorial-1.gleam b/Task/Factorial/Gleam/factorial-1.gleam new file mode 100644 index 0000000000..6521eeb481 --- /dev/null +++ b/Task/Factorial/Gleam/factorial-1.gleam @@ -0,0 +1 @@ +list.fold(int.range(1, n + 1, [], list.prepend), 1, int.multiply) diff --git a/Task/Factorial/Gleam/factorial-2.gleam b/Task/Factorial/Gleam/factorial-2.gleam new file mode 100644 index 0000000000..dbab0f45f6 --- /dev/null +++ b/Task/Factorial/Gleam/factorial-2.gleam @@ -0,0 +1,6 @@ +pub fn fac(n: Int) -> Int { + case n { + 1 -> 1 + n -> n * fac(n - 1) + } +} diff --git a/Task/Factorial/Gleam/factorial-3.gleam b/Task/Factorial/Gleam/factorial-3.gleam new file mode 100644 index 0000000000..dbc03d5750 --- /dev/null +++ b/Task/Factorial/Gleam/factorial-3.gleam @@ -0,0 +1,10 @@ +pub fn fac(n: Int) -> Int { + fac_helper(n, n - 1) +} + +fn fac_helper(n: Int, acc: Int) -> Int { + case n, acc { + n, 1 -> n + n, i -> fac_helper(n * i, i - 1) + } +} diff --git a/Task/Factorial/Haskell/factorial-10.hs b/Task/Factorial/Haskell/factorial-10.hs new file mode 100644 index 0000000000..d7507d16b3 --- /dev/null +++ b/Task/Factorial/Haskell/factorial-10.hs @@ -0,0 +1,8 @@ +-- product of [a,a+1..b] +productFromTo a b = + if a>b then 1 + else if a == b then a + else productFromTo a c * productFromTo (c+1) b + where c = (a+b) `div` 2 + +factorial = productFromTo 1 diff --git a/Task/Factorial/Haskell/factorial-5.hs b/Task/Factorial/Haskell/factorial-5.hs index 6b76b69b6e..f036c73a77 100644 --- a/Task/Factorial/Haskell/factorial-5.hs +++ b/Task/Factorial/Haskell/factorial-5.hs @@ -1,3 +1 @@ -factorial :: Integral -> Integral -factorial 0 = 1 -factorial n = n * factorial (n-1) +factorials = 1 : zipWith (*) factorials [1..] diff --git a/Task/Factorial/Haskell/factorial-6.hs b/Task/Factorial/Haskell/factorial-6.hs index baef906bf8..655c366a44 100644 --- a/Task/Factorial/Haskell/factorial-6.hs +++ b/Task/Factorial/Haskell/factorial-6.hs @@ -1,5 +1,2 @@ -fac n - | n >= 0 = go 1 n - | otherwise = error "Negative factorial!" - where go acc 0 = acc - go acc n = go (acc * n) (n - 1) +factorials = go 1 1 where + go n fac = f : go (n+1) (n*fac) diff --git a/Task/Factorial/Haskell/factorial-7.hs b/Task/Factorial/Haskell/factorial-7.hs index 77d34e9b2e..6b76b69b6e 100644 --- a/Task/Factorial/Haskell/factorial-7.hs +++ b/Task/Factorial/Haskell/factorial-7.hs @@ -1,10 +1,3 @@ -{-# LANGUAGE PostfixOperators #-} - -(!) :: Integer -> Integer -(!) 0 = 1 -(!) n = n * (pred n !) - -main :: IO () -main = do - print (5 !) - print ((4 !) !) +factorial :: Integral -> Integral +factorial 0 = 1 +factorial n = n * factorial (n-1) diff --git a/Task/Factorial/Haskell/factorial-8.hs b/Task/Factorial/Haskell/factorial-8.hs index d7507d16b3..baef906bf8 100644 --- a/Task/Factorial/Haskell/factorial-8.hs +++ b/Task/Factorial/Haskell/factorial-8.hs @@ -1,8 +1,5 @@ --- product of [a,a+1..b] -productFromTo a b = - if a>b then 1 - else if a == b then a - else productFromTo a c * productFromTo (c+1) b - where c = (a+b) `div` 2 - -factorial = productFromTo 1 +fac n + | n >= 0 = go 1 n + | otherwise = error "Negative factorial!" + where go acc 0 = acc + go acc n = go (acc * n) (n - 1) diff --git a/Task/Factorial/Haskell/factorial-9.hs b/Task/Factorial/Haskell/factorial-9.hs new file mode 100644 index 0000000000..77d34e9b2e --- /dev/null +++ b/Task/Factorial/Haskell/factorial-9.hs @@ -0,0 +1,10 @@ +{-# LANGUAGE PostfixOperators #-} + +(!) :: Integer -> Integer +(!) 0 = 1 +(!) n = n * (pred n !) + +main :: IO () +main = do + print (5 !) + print ((4 !) !) diff --git a/Task/Factorial/Haxe/factorial-1.haxe b/Task/Factorial/Haxe/factorial-1.hx similarity index 100% rename from Task/Factorial/Haxe/factorial-1.haxe rename to Task/Factorial/Haxe/factorial-1.hx diff --git a/Task/Factorial/Haxe/factorial-2.haxe b/Task/Factorial/Haxe/factorial-2.hx similarity index 100% rename from Task/Factorial/Haxe/factorial-2.haxe rename to Task/Factorial/Haxe/factorial-2.hx diff --git a/Task/Factorial/Haxe/factorial-3.haxe b/Task/Factorial/Haxe/factorial-3.hx similarity index 100% rename from Task/Factorial/Haxe/factorial-3.haxe rename to Task/Factorial/Haxe/factorial-3.hx diff --git a/Task/Factorial/Haxe/factorial-4.haxe b/Task/Factorial/Haxe/factorial-4.hx similarity index 100% rename from Task/Factorial/Haxe/factorial-4.haxe rename to Task/Factorial/Haxe/factorial-4.hx diff --git a/Task/Factorial/Haxe/factorial-5.haxe b/Task/Factorial/Haxe/factorial-5.hx similarity index 100% rename from Task/Factorial/Haxe/factorial-5.haxe rename to Task/Factorial/Haxe/factorial-5.hx diff --git a/Task/Factorial/Java/factorial-4.java b/Task/Factorial/Java/factorial-4.java new file mode 100644 index 0000000000..7194a10356 --- /dev/null +++ b/Task/Factorial/Java/factorial-4.java @@ -0,0 +1,27 @@ +import java.math.BigInteger; +import java.util.function.Function; +import java.util.stream.LongStream; +import java.util.stream.Stream; + +public final class Factorial { + + public static void main(String[] args) { + // Valid only for integer arguments 1, 2, ... , 20 + Function factorialPositive = n -> LongStream.rangeClosed(2, n).reduce(1, (a, b) -> a * b); + + // Valid for integer arguments <= 20 + Function factorial = n -> { + if ( n < 0 || n > 20 ) { + throw new AssertionError("Argument is out of range: " + n); + } + + return factorialPositive.apply(n); + }; + + // Return a BigInteger value + Function factorialBig = n -> Stream.iterate(BigInteger.ONE, i -> i.add(BigInteger.ONE)) + .limit(n) + .reduce(BigInteger.ONE, BigInteger::multiply); + } + +} diff --git a/Task/Factorial/Julia/factorial-1.julia b/Task/Factorial/Julia/factorial-1.jl similarity index 100% rename from Task/Factorial/Julia/factorial-1.julia rename to Task/Factorial/Julia/factorial-1.jl diff --git a/Task/Factorial/Julia/factorial-2.julia b/Task/Factorial/Julia/factorial-2.jl similarity index 100% rename from Task/Factorial/Julia/factorial-2.julia rename to Task/Factorial/Julia/factorial-2.jl diff --git a/Task/Factorial/Kotlin/factorial.kotlin b/Task/Factorial/Kotlin/factorial.kts similarity index 100% rename from Task/Factorial/Kotlin/factorial.kotlin rename to Task/Factorial/Kotlin/factorial.kts diff --git a/Task/Factorial/Langur/factorial-1.langur b/Task/Factorial/Langur/factorial-1.langur index 8d8674f4b4..3149d6b778 100644 --- a/Task/Factorial/Langur/factorial-1.langur +++ b/Task/Factorial/Langur/factorial-1.langur @@ -1,2 +1,2 @@ -val .factorial = fn(.n) fold(fn{*}, 2 .. .n) -writeln .factorial(7) +val factorial = fn(n number) { fold(2 .. n, by=fn{*}) } +writeln factorial(7) diff --git a/Task/Factorial/Langur/factorial-2.langur b/Task/Factorial/Langur/factorial-2.langur index a40e149332..93fe1fe8d3 100644 --- a/Task/Factorial/Langur/factorial-2.langur +++ b/Task/Factorial/Langur/factorial-2.langur @@ -1,2 +1,2 @@ -val .factorial = fn(.x) if(.x < 2: 1; .x * self(.x - 1)) -writeln .factorial(7) +val factorial = fn(x number) { if(x < 2: 1; x * fn((x - 1))) } +writeln factorial(7) diff --git a/Task/Factorial/Langur/factorial-3.langur b/Task/Factorial/Langur/factorial-3.langur index a630ad30d4..934e4f08bd 100644 --- a/Task/Factorial/Langur/factorial-3.langur +++ b/Task/Factorial/Langur/factorial-3.langur @@ -1,9 +1,9 @@ -val .factorial = fn(.i) { - var .answer = 1 - for .x in 2 .. .i { - .answer *= .x +val factorial = fn(i number) { + var answer = 1 + for x in 2 .. i { + answer *= x } - .answer + answer } -writeln .factorial(7) +writeln factorial(7) diff --git a/Task/Factorial/Langur/factorial-4.langur b/Task/Factorial/Langur/factorial-4.langur index 482796f7ea..a13962013b 100644 --- a/Task/Factorial/Langur/factorial-4.langur +++ b/Task/Factorial/Langur/factorial-4.langur @@ -1,2 +1,2 @@ -val .factorial = fn(.n) for[=1] .x in .n { _for *= .x } -writeln .factorial(7) +val factorial = fn(n number) { for[=1] x in n { _for *= x } } +writeln factorial(7) diff --git a/Task/Factorial/M2000-Interpreter/factorial.m2000 b/Task/Factorial/M2000-Interpreter/factorial-1.m2000 similarity index 100% rename from Task/Factorial/M2000-Interpreter/factorial.m2000 rename to Task/Factorial/M2000-Interpreter/factorial-1.m2000 diff --git a/Task/Factorial/M2000-Interpreter/factorial-2.m2000 b/Task/Factorial/M2000-Interpreter/factorial-2.m2000 new file mode 100644 index 0000000000..43a5d9ca37 --- /dev/null +++ b/Task/Factorial/M2000-Interpreter/factorial-2.m2000 @@ -0,0 +1,24 @@ +Cls , 0 ' 0 for non split display, eg 3 means we preserve the 3 top lines from scrolling/cla +Report { + Factorial Task + Definitions + • The factorial of 0 (zero) is defined as being 1 (unity). + • The Factorial Function of a positive integer, n, is defined as the product of the sequence: + n, n-1, n-2, ... 1 + +} +Cls, row ' now we preserve some lines (as row number return here) +Module CheckIt { + m=1u ' 1u is biginteger + k=width-tab + For i=1 to 1000 + if pos>tab then print + m*=i + Print @(0), format$("{0::-4} :", i); + Report str$(m), k + ' Report accumulate lines and stop at 3/4 of the screen (but not on printer) + ' so we can break this using this line: + while inkey$<>"": wait 1:end while: keyboard " " + Next i +} +Checkit diff --git a/Task/Factorial/Mn/factorial.mn b/Task/Factorial/Mn/factorial.mn new file mode 100644 index 0000000000..834200986a --- /dev/null +++ b/Task/Factorial/Mn/factorial.mn @@ -0,0 +1,12 @@ +( + (n) let + 1 (product) let + (n 1 >=) + ( + product n * (product) bind + n 1 - (n) bind + ) while + product +) (factorial) lambda + +5 factorial puts pop diff --git a/Task/Factorial/OCaml/factorial-1.ocaml b/Task/Factorial/OCaml/factorial-1.ml similarity index 100% rename from Task/Factorial/OCaml/factorial-1.ocaml rename to Task/Factorial/OCaml/factorial-1.ml diff --git a/Task/Factorial/OCaml/factorial-2.ocaml b/Task/Factorial/OCaml/factorial-2.ml similarity index 100% rename from Task/Factorial/OCaml/factorial-2.ocaml rename to Task/Factorial/OCaml/factorial-2.ml diff --git a/Task/Factorial/OCaml/factorial-3.ocaml b/Task/Factorial/OCaml/factorial-3.ml similarity index 100% rename from Task/Factorial/OCaml/factorial-3.ocaml rename to Task/Factorial/OCaml/factorial-3.ml diff --git a/Task/Factorial/OCaml/factorial-4.ocaml b/Task/Factorial/OCaml/factorial-4.ml similarity index 100% rename from Task/Factorial/OCaml/factorial-4.ocaml rename to Task/Factorial/OCaml/factorial-4.ml diff --git a/Task/Factorial/Oberon-07/factorial.oberon b/Task/Factorial/Oberon-07/factorial.oberon new file mode 100644 index 0000000000..8c8e1d89ca --- /dev/null +++ b/Task/Factorial/Oberon-07/factorial.oberon @@ -0,0 +1,40 @@ +MODULE Factorial; +IMPORT + Out; + +VAR + i: INTEGER; + + PROCEDURE Iterative(n: INTEGER): INTEGER; + VAR + i, r: INTEGER; + BEGIN + ASSERT(n >= 0); + r := 1; + FOR i := n TO 2 BY -1 DO + r := r * i + END; + RETURN r + END Iterative; + + PROCEDURE Recursive(n: INTEGER): INTEGER; + VAR + r: INTEGER; + BEGIN + ASSERT(n >= 0); + r := 1; + IF n > 1 THEN + r := n * Recursive(n - 1) + END; + RETURN r + END Recursive; + +BEGIN + FOR i := 0 TO 9 DO + Out.String("Iterative ");Out.Int(i,0);Out.String("! =");Out.Int(Iterative(i),8);Out.Ln; + END; + Out.Ln; + FOR i := 0 TO 9 DO + Out.String("Recursive ");Out.Int(i,0);Out.String("! =");Out.Int(Recursive(i),8);Out.Ln; + END +END Factorial. diff --git a/Task/Factorial/Pascal/factorial-2.pas b/Task/Factorial/Pascal/factorial-2.pas index 991914c559..6b44f23124 100644 --- a/Task/Factorial/Pascal/factorial-2.pas +++ b/Task/Factorial/Pascal/factorial-2.pas @@ -1,32 +1,45 @@ {$mode objFPC}{R+} -FUNCTION Factorial ( n : qword ) : qword; +FUNCTION Fact(n: qword): qword; - (*) - Update for version 3.2.0 - Factorial works until 20! , which is good enough for me for now - replace qword with dword and rax,rcx with eax, ecx for 32-bit - for Factorial until 12! - (*) +VAR + F: qword; - VAR - - F: qword; - - BEGIN +BEGIN + if n > 20 then + begin + WriteLn('This function is only accurate up to 20!'); + exit(0); + end; - asm - - mov $1, %rax - mov n, %rcx - - .Lloop1: - imul %rcx, %rax - loopnz .Lloop1 - - mov %rax, F + asm + (*) Initialize result = 1 (0! = 1 case handled automatically) (*) - end; + mov $1, %rax (*) RAX = 1 (initial result) (*) + mov n, %rcx (*) RCX = input number (counter) (*) - Result := F ; - - END; + test %rcx, %rcx (*) Check if n=0 (*) + jz .Lstore_result (*) Skip loop if n=0 (*) + + .Lloop1: + imul %rcx, %rax (*) RAX = RAX * RCX (signed mul) (*) + dec %rcx (*) Decrement RCX (*) + jnz .Lloop1 (*) Loop while RCX != 0 (*) + + .Lstore_result: + mov %rax, F (*) Store result in F (*) + end ['rax', 'rcx']; (*) Tell compiler register change (*) + + Result := F; + +END; + + +var + N : integer = 20 ; + +begin + + writeln; + writeln( BasicFact(N)); + +end. (*) Function Fact (*) diff --git a/Task/Factorial/Pascal/factorial-3.pas b/Task/Factorial/Pascal/factorial-3.pas index 64c4eabff6..137d0f6b28 100644 --- a/Task/Factorial/Pascal/factorial-3.pas +++ b/Task/Factorial/Pascal/factorial-3.pas @@ -1,92 +1,33 @@ -PROGRAM EXBigFac ; +program GMPfact; -{$IFDEF FPC} - {$mode objfpc}{$H+}{$J-}{R+} -{$ELSE} - {$APPTYPE CONSOLE} -{$ENDIF} +{$mode objfpc} -(*) +uses - Free Pascal Compiler version 3.2.0 [2020/06/14] for x86_64 - The free and readable alternative at C/C++ speeds - compiles natively to almost any platform, including raspberry PI * - Can run independently from DELPHI / Lazarus + gmp + ; - For debian Linux: apt -y install fpc - It contains a text IDE called fp + function Factorial(n: qword): string; + var + ResultMPZ: mpz_t; + i: qword; + begin + mpz_init_set_ui(ResultMPZ, 1); + for i := 2 to n do + mpz_mul_ui(ResultMPZ, ResultMPZ, i); + Result := mpz_get_str(nil, 10, ResultMPZ); + mpz_clear(ResultMPZ); + end; - https://www.freepascal.org/advantage.var +var + N : integer = 101 ; + Fact : string ; -(*) +begin + Fact := Factorial(101); + writeln( N ,'! = ', Fact); +end. (*) GMPfact (*) -USES - - gmp; - - FUNCTION WriteBigNum ( c: pchar ) : ansistring ; - - CONST - - CrLf = #13 + #10 ; - - VAR - i: longint; - len: longint; - preview: integer; - ret: ansistring = ''; - threshold: integer; - - BEGIN - - len := length ( c ) ; - WriteLn ( 'Digits: ', len ) ; - threshold := 12 ; - preview := len div threshold ; - - IF ( len < 91 ) THEN - BEGIN - FOR i := 0 TO len DO - ret:= ret + c [ i ] ; - END - ELSE - BEGIN - FOR i := 0 TO preview DO - ret:= ret + c [ i ] ; - ret:= ret + '...' ; - FOR i := len - preview -1 TO len DO - ret:= ret + c [ i ] ; - END; - ret:= ret + CrLf ; - WriteBigNum := ret; - END; - - FUNCTION BigFactorial ( n : qword ) : ansistring ; - - (*) - See https://gmplib.org/#DOC - (*) - - VAR - S: mpz_t; - c: pchar; - - BEGIN - - mpz_init_set_ui ( S, 1 ) ; - mpz_fac_ui ( S, n ) ; - c := mpz_get_str ( NIL, 10, S ) ; - BigFactorial := WriteBigNum ( c ) ; - - END; - -BEGIN - - WriteLn ( BigFactorial ( 99 ) ) ; - -END. - Output: -Digits: 156 -93326215443944...00000000000000 +101! = 9425947759838359420851623124482936749562312794702543768327889353416977599316221476503087861591808346911623490003549599583369706302603264000000000000000000000000 diff --git a/Task/Factorial/PascalABC.NET/factorial.pas b/Task/Factorial/PascalABC.NET/factorial.pas new file mode 100644 index 0000000000..87563d6ab2 --- /dev/null +++ b/Task/Factorial/PascalABC.NET/factorial.pas @@ -0,0 +1,19 @@ +function FactIter(n: integer): BigInteger; +begin + Result := 1; + for var i:=2 to n do + Result *= i; +end; + +function FactRec(n: integer): BigInteger; +begin + if n = 0 then + Result := 1 + else Result := n * FactRec(n - 1); +end; + + +begin + for var i:=1 to 20 do + Println(i,FactRec(i),FactIter(i)); +end. diff --git a/Task/Factorial/Pluto/factorial.pluto b/Task/Factorial/Pluto/factorial.pluto new file mode 100644 index 0000000000..3ed73ecb0e --- /dev/null +++ b/Task/Factorial/Pluto/factorial.pluto @@ -0,0 +1,30 @@ +local bigint = require "pluto:bigint" + +class Factorial + static function iterative(n) + local fact = bigint.new(1) + if n < 2 then return fact end + for i = 2, n do fact *= bigint.new(i) end + return fact + end + + static function recursive(n) + if n < 2 then return bigint.new(1) end + return bigint.new(n) * Factorial.recursive(n - 1) + end +end + +local function commatize(n) + local s = n:tostring() + local zero = bigint.new(0) + if n < zero then s = s:sub(2) end + for i = #s - 3, 1, -3 do + s = s:sub(1, i) .. "," .. s:sub(i + 1) + end + if n >= zero then return s end + return "-" .. s +end + +local n = 24 +print($"Factorial({n}) iterative -> {commatize(Factorial.iterative(n))}") +print($"Factorial({n}) recursive -> {commatize(Factorial.recursive(n))}") diff --git a/Task/Factorial/PowerShell/factorial-1.psh b/Task/Factorial/PowerShell/factorial-1.ps1 similarity index 100% rename from Task/Factorial/PowerShell/factorial-1.psh rename to Task/Factorial/PowerShell/factorial-1.ps1 diff --git a/Task/Factorial/PowerShell/factorial-2.psh b/Task/Factorial/PowerShell/factorial-2.ps1 similarity index 100% rename from Task/Factorial/PowerShell/factorial-2.psh rename to Task/Factorial/PowerShell/factorial-2.ps1 diff --git a/Task/Factorial/PowerShell/factorial-3.psh b/Task/Factorial/PowerShell/factorial-3.ps1 similarity index 100% rename from Task/Factorial/PowerShell/factorial-3.psh rename to Task/Factorial/PowerShell/factorial-3.ps1 diff --git a/Task/Factorial/R/factorial-4.r b/Task/Factorial/R/factorial-4.r new file mode 100644 index 0000000000..3c651ae864 --- /dev/null +++ b/Task/Factorial/R/factorial-4.r @@ -0,0 +1 @@ + fact_fp <- function(n) ifelse(!n, 1, Reduce(`*`, seq_len(n))) diff --git a/Task/Factorial/REBOL/factorial.rebol b/Task/Factorial/REBOL/factorial.rebol deleted file mode 100644 index b3ff15a290..0000000000 --- a/Task/Factorial/REBOL/factorial.rebol +++ /dev/null @@ -1,55 +0,0 @@ -REBOL [ - Title: "Factorial" - URL: http://rosettacode.org/wiki/Factorial_function -] - -; Standard recursive implementation. - -factorial: func [n][ - either n > 1 [n * factorial n - 1] [1] -] - -; Iteration. - -ifactorial: func [n][ - f: 1 - for i 2 n 1 [f: f * i] - f -] - -; Automatic memoization. -; I'm just going to say up front that this is a stunt. However, you've -; got to admit it's pretty nifty. Note that the 'memo' function -; works with an unlimited number of arguments (although the expected -; gains decrease as the argument count increases). - -memo: func [ - "Defines memoizing function -- keeps arguments/results for later use." - args [block!] "Function arguments. Just specify variable names." - body [block!] "The body block of the function." - /local m-args m-r -][ - do compose/deep [ - func [ - (args) - /dump "Dump memory." - ][ - m-args: [] - if dump [return m-args] - - if m-r: select/only m-args reduce [(args)] [return m-r] - - m-r: do [(body)] - append m-args reduce [reduce [(args)] m-r] - m-r - ] - ] -] - -mfactorial: memo [n][ - either n > 1 [n * mfactorial n - 1] [1] -] - -; Test them on numbers zero to ten. - -for i 0 10 1 [print [i ":" factorial i ifactorial i mfactorial i]] diff --git a/Task/Factorial/REXX/factorial-1.rexx b/Task/Factorial/REXX/factorial-1.rexx index b02528c706..4ab115dc32 100644 --- a/Task/Factorial/REXX/factorial-1.rexx +++ b/Task/Factorial/REXX/factorial-1.rexx @@ -1,18 +1,4 @@ -/*REXX pgm computes & shows the factorial of a non─negative integer, and also its length*/ -numeric digits 100000 /*100k digits: handles N up to 25k.*/ -parse arg n /*obtain optional argument from the CL.*/ -if n='' then call er 'no argument specified.' -if arg()>1 | words(n)>1 then call er 'too many arguments specified.' -if \datatype(n,'N') then call er "argument isn't numeric: " n -if \datatype(n,'W') then call er "argument isn't a whole number: " n -if n<0 then call er "argument can't be negative: " n -!= 1 /*define the factorial product (so far)*/ - do j=2 to n; !=!*j /*compute the factorial the hard way. */ - end /*j*/ /* [↑] where da rubber meets da road. */ - -say n'! is ['length(!) "digits]:" /*display number of digits in factorial*/ -say /*add some whitespace to the output. */ -say ! /*display the factorial product──►term.*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -er: say; say '***error***'; say; say arg(1); say; exit 13 +call time('r') +numeric digits 999999999 +a = 10/3 +say length(a) time('e') diff --git a/Task/Factorial/REXX/factorial-2.rexx b/Task/Factorial/REXX/factorial-2.rexx index 0ce1aa0e4d..82133ca665 100644 --- a/Task/Factorial/REXX/factorial-2.rexx +++ b/Task/Factorial/REXX/factorial-2.rexx @@ -1,22 +1,68 @@ -/*REXX program computes the factorial of a non─negative integer, and it automatically */ -/*────────────────────── adjusts the number of decimal digits to accommodate the answer.*/ -numeric digits 99 /*99 digits initially, then expanded. */ -parse arg n /*obtain optional argument from the CL.*/ -if n='' then call er 'no argument specified' -if arg()>1 | words(n)>1 then call er 'too many arguments specified.' -if \datatype(n,'N') then call er "argument isn't numeric: " n -if \datatype(n,'W') then call er "argument isn't a whole number: " n -if n<0 then call er "argument can't be negative: " n -!= 1 /*define the factorial product (so far)*/ - do j=2 to n; !=!*j /*compute the factorial the hard way. */ - if pos(.,!)==0 then iterate /*is the ! in exponential notation? */ - parse var ! 'E' digs /*extract exponent of the factorial, */ - numeric digits digs + digs % 10 /* ··· and increase it by ten percent.*/ - end /*j*/ /* [↑] where da rubber meets da road. */ -!= !/1 /*normalize the factorial product. */ -say n'! is ['length(!) "digits]:" /*display number of digits in factorial*/ -say /*add some whitespace to the output. */ -say ! /*display the factorial product ──►term*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -er: say; say '***error!***'; say; say arg(1); say; exit 13 +-- 10 Mar 2026 +include Setting + +say 'Factorial' +say version +say +call First20 +call Imperative 10, '1 13 71 450 3249 25206 205022 1723508 14842907 130202808' +if pos('Regina',version) > 0 then + call Recursive 10, '1 13 71 450 3249 25206 205022' +else + call Recursive 10, '1 13 71 450 3249' +call Imperative 100000,'1 13 71 450 3249 25206' +call Timer +exit + +First20: +say 'First 20 FactorialS...' +numeric digits 30 +do n = 1 to 20 + say n'! =' Fact(n) +end +say +return + +Imperative: +Memo.='' +call Time('R') +arg d,p +numeric digits d +say 'Imperative in' d 'digits precision...' +do i = 1 to Words(p) + call Time('r'); f = Word(p,i); h = Fact(f) + parse var h 'E' e + if e = '' then + say Right(f'!',10) 'has exact' Right(Length(h),9) 'digits' '('Format(Time('e'),,3)'s)' + else + say Right(f'!',10) 'has about' Right(e+1,9) 'digits' '('Format(Time('e'),,3)'s)' +end +say +return + +Recursive: +Memo.='' +call Time('R') +arg d,p +numeric digits d +say 'Recursive in' d 'digits precision...' +do i = 1 to Words(p) + call Time('r'); f = Word(p,i); h = Recurs(f) + parse var h 'E' e + if e = '' then + say Right(f'!',10) 'has exact' Right(Length(h),9) 'digits' '('Format(Time('e'),,3)'s)' + else + say Right(f'!',10) 'has about' Right(e+1,9) 'digits' '('Format(Time('e'),,3)'s)' +end +say +return + +Recurs: +procedure +arg xx +if xx = 0 then + return 1 +else + return xx*Recurs(xx-1) + +include Math diff --git a/Task/Factorial/REXX/factorial-3.rexx b/Task/Factorial/REXX/factorial-3.rexx deleted file mode 100644 index f9f6da4455..0000000000 --- a/Task/Factorial/REXX/factorial-3.rexx +++ /dev/null @@ -1,27 +0,0 @@ -/*REXX program computes & shows the factorial of an integer, striping trailing zeroes. */ -numeric digits 200 /*start with two hundred digits. */ -parse arg N . /*obtain an optional argument from CL. */ -if N=='' | N=="," then N= 0 /*Not specified? Then use the default.*/ -!= 1 /*define the factorial product so far. */ - do j=2 to N /*compute factorial the hard way. */ - old!= ! /*save old product in case of overflow.*/ - != ! * j /*multiple the old factorial with J. */ - if pos(.,!) \==0 then do /*is the ! in exponential notation?*/ - d= digits() /*D temporarily stores number digits.*/ - numeric digits d+d%10 /*add 10% to the decimal digits. */ - != old! * j /*re─calculate for the "lost" digits.*/ - end /*IFF ≡ if and only if. [↓] */ - parse var ! '' -1 _ /*obtain the right-most digit of ! */ - if _==0 then != strip(!, , 0) /*strip trailing zeroes IFF the ... */ - end /*j*/ /* [↑] ... right-most digit is zero. */ -z= 0 /*the number of trailing zeroes in ! */ - do v=5 by 0 while v<=N /*calculate number of trailing zeroes. */ - z= z + N % v /*bump Z if multiple power of five.*/ - v= v * 5 /*calculate the next power of five. */ - end /*v*/ /* [↑] we only advance V by ourself.*/ - /*stick a fork in it, we're all done. */ -!= ! || copies(0, z) /*add water to rehydrate the product. */ -if z==0 then z= 'no' /*use gooder English for the message. */ -say N'! is ['length(!) " digits with " z ' trailing zeroes]:' -say /*display blank line (for whitespace).*/ -say ! /*display the factorial product. */ diff --git a/Task/Factorial/RISC-V-Assembly/factorial.asm b/Task/Factorial/RISC-V-Assembly/factorial.asm new file mode 100644 index 0000000000..f3139a188e --- /dev/null +++ b/Task/Factorial/RISC-V-Assembly/factorial.asm @@ -0,0 +1,131 @@ +# riscv assembly raspberry pico2 rp2350 +# program factorial.s +# connexion putty com3 +/*********************************************/ +/* CONSTANTES */ +/********************************************/ +/* for this file see risc-v task include a file */ +.include "../../constantesRiscv.inc" + +/****************************************************/ +/* MACROS */ +/****************************************************/ +#.include "../ficmacrosriscv.inc" # for debugging only + +/*******************************************/ +/* INITIALED DATAS */ +/*******************************************/ +.data +szMessStart: .asciz "Program riscv start.\r\n" +szMessEnd: .asciz "\nProgram end OK.\r\n" +szCariageReturn: .asciz "\r\n" + +szMessLargeNumber: .asciz "Number N to large. \n" +szMessNegNumber: .asciz "Number N is negative. \n" + +szMessResult: .ascii "Resultat = " # message result + +.align 2 + + +/*******************************************/ +/* UNINITIALED DATA */ +/*******************************************/ +.bss +.align 2 +sConvArea: .skip 24 + +/********************************...-..--*****/ +/* SECTION CODE */ +/**********************************************/ +.text +.global main + +main: + call stdio_init_all # général init +1: # start loop connexion + li a0,0 # raz argument register + call tud_cdc_n_connected # waiting for USB connection + beqz a0,1b # return code = zero ? + + la a0,szMessStart # message address + call writeString # display message + + li a0,-10 + call factorial # + li a0,0 + call factorial # + li a0,10 + call factorial # + + la a0,szMessEnd + call writeString + call getchar +100: # final loop + j 100b +/**********************************************/ +/* compute factorial */ +/**********************************************/ +/* a0 value */ +factorial: # INFO: factorial + addi sp, sp, -4 # reserve stack + sw ra, 0(sp) + bltz a0,99f # is negative ? + li t0,1 + ble a0,t0,1f # is 0 or 1 + call computeFactorial + li t0,-1 # error overflow ? + beq a0,t0,98f +1: # display result + la a1,sConvArea + call conversion10 + la a0,szMessResult + call writeString + la a0,sConvArea + call writeString + la a0,szCariageReturn + call writeString + j 100f +98: + la a0,szMessLargeNumber + call writeString + j 100f +99: + la a0,szMessNegNumber + call writeString + j 100f +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret +/**********************************************/ +/* compute factorial */ +/**********************************************/ +/* a0 value */ +computeFactorial: # INFO:computeFactorial + addi sp,sp, -8 # reserve stack + sw ra,0(sp) + sw s0,4(sp) + li t0,1 + beq a0,t0,100f # if n = 1 return + mv s0,a0 + addi a0,a0,-1 + call computeFactorial + li t0,-1 # error overflow ? + beq a0,t0,100f + mulh t0,a0,s0 # compute half high 32 bits + beqz t0,1f # is ok if result is zero + li a0,-1 # error overflow + j 100f +1: + mul a0,a0,s0 # multiplication +100: + lw ra,0(sp) + lw s0,4(sp) + addi sp,sp, 8 + ret +/************************************/ +/* file include Fonctions */ +/***********************************/ +/* for this file see risc-v task include a file */ +.include "../../includeFunctions.s" diff --git a/Task/Factorial/Rebol/factorial.rebol b/Task/Factorial/Rebol/factorial.rebol new file mode 100644 index 0000000000..feb9d5d6c4 --- /dev/null +++ b/Task/Factorial/Rebol/factorial.rebol @@ -0,0 +1,56 @@ +Rebol [ + Title: "Factorial" + URL: http://rosettacode.org/wiki/Factorial_function +] + +;; Standard recursive implementation. +factorial: func [n][ + either n > 1 [n * factorial n - 1] [1] +] + +;; Iteration. +ifactorial: func [n][ + f: 1 + for i 2 n 1 [f: f * i] + f +] + +either system/version < 3.0.0 [ + ; Automatic memoization. + ; I'm just going to say up front that this is a stunt. However, you've + ; got to admit it's pretty nifty. Note that the 'memo' function + ; works with an unlimited number of arguments (although the expected + ; gains decrease as the argument count increases). + memo: func [ + "Defines memoizing function -- keeps arguments/results for later use." + args [block!] "Function arguments. Just specify variable names." + body [block!] "The body block of the function." + /local m-args m-r + ][ + do compose/deep [ + func [ + (args) + /dump "Dump memory." + ][ + m-args: [] + if dump [return m-args] + + if m-r: select/only m-args reduce [(args)] [return m-r] + + m-r: do [(body)] + append m-args reduce [reduce [(args)] m-r] + m-r + ] + ] + ] + + mfactorial: memo [n][ + either n > 1 [n * mfactorial n - 1] [1] + ] +][ + ;; Above hack is not supported in Rebol3 + mfactorial: func[i][none] +] + +;; Test them on numbers zero to ten. +for i 0 10 1 [print [i ":" factorial i ifactorial i mfactorial i]] diff --git a/Task/Factorial/Retro/factorial.retro b/Task/Factorial/Retro/factorial.retro index fb56673ef4..11cf76e297 100644 --- a/Task/Factorial/Retro/factorial.retro +++ b/Task/Factorial/Retro/factorial.retro @@ -1,2 +1,8 @@ -: dup 1 = if; dup 1- * ; -: factorial dup 0 = [ 1+ ] [ ] if ; +: + dup #1 -eq? 0; drop + dup n:dec * ; + +:factorial + dup n:zero? + [ n:inc ] + [ ] choose ; diff --git a/Task/Factorial/Rhombus/factorial-1.rhombus b/Task/Factorial/Rhombus/factorial-1.rhombus new file mode 100644 index 0000000000..5042a49103 --- /dev/null +++ b/Task/Factorial/Rhombus/factorial-1.rhombus @@ -0,0 +1,5 @@ +#lang rhombus/static + +fun factorial: +| factorial(0): 1 +| factorial(n): n * factorial(n - 1) diff --git a/Task/Factorial/Rhombus/factorial-2.rhombus b/Task/Factorial/Rhombus/factorial-2.rhombus new file mode 100644 index 0000000000..95c17bc122 --- /dev/null +++ b/Task/Factorial/Rhombus/factorial-2.rhombus @@ -0,0 +1,7 @@ +#lang rhombus/static + +fun factorial(n): + for values(a=1) (n in 1..=n): + a * n + +factorial(6) // output: 720 diff --git a/Task/Factorial/Coq/factorial.coq b/Task/Factorial/Rocq/factorial.rocq similarity index 100% rename from Task/Factorial/Coq/factorial.coq rename to Task/Factorial/Rocq/factorial.rocq diff --git a/Task/Factorial/Rust/factorial.rust b/Task/Factorial/Rust/factorial.rs similarity index 100% rename from Task/Factorial/Rust/factorial.rust rename to Task/Factorial/Rust/factorial.rs diff --git a/Task/Factorial/S-BASIC/factorial-1.basic b/Task/Factorial/S-BASIC/factorial-1.basic new file mode 100644 index 0000000000..3899ac1bd1 --- /dev/null +++ b/Task/Factorial/S-BASIC/factorial-1.basic @@ -0,0 +1,13 @@ +function factorial(n=real.double)=real.double + if n = 0 then n = 1 else n = n * factorial(n-1) +end = n + +var i=integer +print "Factorial Calculator" +print " n n!" +print "----------------------" +for i=1 to 15 + print using "## #,###,###,###,###";i;factorial(i) +next i + +end diff --git a/Task/Factorial/S-BASIC/factorial-2.basic b/Task/Factorial/S-BASIC/factorial-2.basic new file mode 100644 index 0000000000..91fbb1fce5 --- /dev/null +++ b/Task/Factorial/S-BASIC/factorial-2.basic @@ -0,0 +1,7 @@ +function factorial(n=real.double)=real.double + var i, f = real.double + f = 1 + for i = 1 to n + f = f * i + next i +end = f diff --git a/Task/Factorial/SQL/factorial.sql b/Task/Factorial/SQL/factorial.sql new file mode 100644 index 0000000000..c0b412e4a3 --- /dev/null +++ b/Task/Factorial/SQL/factorial.sql @@ -0,0 +1,6 @@ +WITH RECURSIVE f(a, b) AS ( + VALUES(1, 1) + UNION ALL + SELECT a * b, b + 1 FROM f WHERE b <= 9 +) +SELECT MAX(a) FROM f diff --git a/Task/Factorial/Scheme/factorial-1.ss b/Task/Factorial/Scheme/factorial-1.scm similarity index 100% rename from Task/Factorial/Scheme/factorial-1.ss rename to Task/Factorial/Scheme/factorial-1.scm diff --git a/Task/Factorial/Scheme/factorial-2.ss b/Task/Factorial/Scheme/factorial-2.scm similarity index 100% rename from Task/Factorial/Scheme/factorial-2.ss rename to Task/Factorial/Scheme/factorial-2.scm diff --git a/Task/Factorial/Scheme/factorial-3.ss b/Task/Factorial/Scheme/factorial-3.scm similarity index 100% rename from Task/Factorial/Scheme/factorial-3.ss rename to Task/Factorial/Scheme/factorial-3.scm diff --git a/Task/Factorial/Scheme/factorial-4.scm b/Task/Factorial/Scheme/factorial-4.scm new file mode 100644 index 0000000000..1d26a067d8 --- /dev/null +++ b/Task/Factorial/Scheme/factorial-4.scm @@ -0,0 +1,24 @@ +;Using a generator and a function that apply generated values to a function taking two arguments + +;A generator knows commands 'next? and 'next +(define (range a b) +(let ((k a)) +(lambda (msg) +(cond + ((eq? msg 'next?) (<= k b)) + ((eq? msg 'next) + (cond + ((<= k b) (set! k (+ k 1)) (- k 1)) + (else 'nothing-left))))))) + +;Similar to List.fold_left in OCaml, but uses a generator +(define (fold fun a gen) +(let aux ((a a)) + (if (gen 'next?) (aux (fun a (gen 'next))) a))) + +;Now the factorial function +(define (factorial n) (fold * 1 (range 1 n))) + +(factorial 8) + +;40320 diff --git a/Task/Factorial/Scheme/factorial-4.ss b/Task/Factorial/Scheme/factorial-4.ss deleted file mode 100644 index 3e179ef9e9..0000000000 --- a/Task/Factorial/Scheme/factorial-4.ss +++ /dev/null @@ -1,23 +0,0 @@ -;Using a generator and a function that apply generated values to a function taking two arguments - -;A generator knows commands 'next? and 'next -(define (range a b) -(let ((k a)) -(lambda (msg) -(cond - ((eq? msg 'next?) (<= k b)) - ((eq? msg 'next) - (cond - ((<= k b) (set! k (+ k 1)) (- k 1)) - (else 'nothing-left))))))) - -;Similar to List.fold_left in OCaml, but uses a generator -(define (fold fun a gen) -(let aux ((a a)) - (if (gen 'next?) (aux (fun a (gen 'next))) a))) - -;Now the factorial function -(define (factorial n) (fold * 1 (range 1 n))) - -(factorial 8) -;40320 diff --git a/Task/Factorial/Scheme/factorial-5.scm b/Task/Factorial/Scheme/factorial-5.scm new file mode 100644 index 0000000000..513325a124 --- /dev/null +++ b/Task/Factorial/Scheme/factorial-5.scm @@ -0,0 +1,9 @@ +(define (range n) + (let ((lst '())) + (do ((i 1 (+ i 1))) + ((= i (+ n 1))) + (set! lst (cons i lst))) + (reverse lst))) + +(define (fact n) + (apply * (range n))) diff --git a/Task/Factorial/TAV/factorial.tav b/Task/Factorial/TAV/factorial.tav new file mode 100644 index 0000000000..ce55505a2d --- /dev/null +++ b/Task/Factorial/TAV/factorial.tav @@ -0,0 +1,14 @@ +factorial (n) iterative: + p =: 1 + ?# i =: from 2 upto n \ does nothing if n < 2 + p =* i + :> p +factorial (n) recursive: + ? n <= 1 + :> 1 + :> n * factorial recursive n-1 + \ test code + main(parms):+ + arg =: string parms[1] as integer else 100 + print factorial arg iterative + print factorial arg recursive diff --git a/Task/Factorial/Tailspin/factorial-2.tailspin b/Task/Factorial/Tailspin/factorial-2.tailspin index 023c4b4738..09af3015fd 100644 --- a/Task/Factorial/Tailspin/factorial-2.tailspin +++ b/Task/Factorial/Tailspin/factorial-2.tailspin @@ -1,4 +1,6 @@ -templates factorial - when <=0> do 1 ! - when <0..> $ * ($ - 1 -> factorial) ! +factorial templates + when <|0..> do + @ set 1; + 1..$ -> @ set $@ * $; + $@ ! end factorial diff --git a/Task/Factorial/Tailspin/factorial-3.tailspin b/Task/Factorial/Tailspin/factorial-3.tailspin new file mode 100644 index 0000000000..023c4b4738 --- /dev/null +++ b/Task/Factorial/Tailspin/factorial-3.tailspin @@ -0,0 +1,4 @@ +templates factorial + when <=0> do 1 ! + when <0..> $ * ($ - 1 -> factorial) ! +end factorial diff --git a/Task/Factorial/Tailspin/factorial-4.tailspin b/Task/Factorial/Tailspin/factorial-4.tailspin new file mode 100644 index 0000000000..968ff78c33 --- /dev/null +++ b/Task/Factorial/Tailspin/factorial-4.tailspin @@ -0,0 +1,4 @@ +factorial templates + when <|=0> do 1 ! + when <|0..> do $ * ($ - 1 -> #) ! +end factorial diff --git a/Task/Factorial/Tcl/factorial-1.tcl b/Task/Factorial/Tcl/factorial-1.tcl index 8220088fdf..a204184466 100644 --- a/Task/Factorial/Tcl/factorial-1.tcl +++ b/Task/Factorial/Tcl/factorial-1.tcl @@ -1,6 +1,12 @@ -proc ifact n { - for {set i $n; set sum 1} {$i >= 2} {incr i -1} { - set sum [expr {$sum * $i}] +# tailcall optimization is standard in tcl8.6 +proc fact { n { result 1. } } { + if { $n <= 1 } { + return $result + } else { + tailcall fact [expr {$n-1}] [expr {$n*$result}] } - return $sum } + +set f [fact 10] + +puts $f diff --git a/Task/Factorial/Tcl/factorial-2.tcl b/Task/Factorial/Tcl/factorial-2.tcl index 40cc360692..8220088fdf 100644 --- a/Task/Factorial/Tcl/factorial-2.tcl +++ b/Task/Factorial/Tcl/factorial-2.tcl @@ -1,3 +1,6 @@ -proc rfact n { - expr {$n < 2 ? 1 : $n * [rfact [incr n -1]]} +proc ifact n { + for {set i $n; set sum 1} {$i >= 2} {incr i -1} { + set sum [expr {$sum * $i}] + } + return $sum } diff --git a/Task/Factorial/Tcl/factorial-3.tcl b/Task/Factorial/Tcl/factorial-3.tcl index e25b3f18c7..40cc360692 100644 --- a/Task/Factorial/Tcl/factorial-3.tcl +++ b/Task/Factorial/Tcl/factorial-3.tcl @@ -1 +1,3 @@ -proc tcl::mathfunc::fact n {expr {$n < 2? 1: $n*fact($n-1)}} +proc rfact n { + expr {$n < 2 ? 1 : $n * [rfact [incr n -1]]} +} diff --git a/Task/Factorial/Tcl/factorial-4.tcl b/Task/Factorial/Tcl/factorial-4.tcl index 9a9a02de85..e25b3f18c7 100644 --- a/Task/Factorial/Tcl/factorial-4.tcl +++ b/Task/Factorial/Tcl/factorial-4.tcl @@ -1,17 +1 @@ -proc ifact_caching n { - global fact_cache - if { ! [info exists fact_cache]} { - set fact_cache {1 1} - } - if {$n < [llength $fact_cache]} { - return [lindex $fact_cache $n] - } - set i [expr {[llength $fact_cache] - 1}] - set sum [lindex $fact_cache $i] - while {$i < $n} { - incr i - set sum [expr {$sum * $i}] - lappend fact_cache $sum - } - return $sum -} +proc tcl::mathfunc::fact n {expr {$n < 2? 1: $n*fact($n-1)}} diff --git a/Task/Factorial/Tcl/factorial-5.tcl b/Task/Factorial/Tcl/factorial-5.tcl index ecdfbe5752..c8cb0123e7 100644 --- a/Task/Factorial/Tcl/factorial-5.tcl +++ b/Task/Factorial/Tcl/factorial-5.tcl @@ -1,11 +1,18 @@ -puts [ifact 30] -puts [rfact 30] -puts [ifact_caching 30] - -set n 400 -set iterations 10000 -puts "calculate $n factorial $iterations times" -puts "ifact: [time {ifact $n} $iterations]" -puts "rfact: [time {rfact $n} $iterations]" -# for the caching proc, reset the cache between each iteration so as not to skew the results -puts "ifact_caching: [time {ifact_caching $n; unset -nocomplain fact_cache} $iterations]" +proc ifact_caching n { + global fact_cache + tailcall fact [expr {$n-1}] [expr {$n*$result}] + if { ! [info exists fact_cache]} { + set fact_cache {1 1} + } + if {$n < [llength $fact_cache]} { + return [lindex $fact_cache $n] + } + set i [expr {[llength $fact_cache] - 1}] + set sum [lindex $fact_cache $i] + while {$i < $n} { + incr i + set sum [expr {$sum * $i}] + lappend fact_cache $sum + } + return $sum +} diff --git a/Task/Factorial/Tcl/factorial-6.tcl b/Task/Factorial/Tcl/factorial-6.tcl index 46e5e0fcab..9a3cf79548 100644 --- a/Task/Factorial/Tcl/factorial-6.tcl +++ b/Task/Factorial/Tcl/factorial-6.tcl @@ -1,5 +1,52 @@ -package require math::special +# calls cmd with args +# retpeatedly in scope above +proc trampoline {cmd args} { -proc gfact n { - expr {round([::math::special::Gamma [expr {$n+1}]])} + # thunk is {cmd {arg1 arg2 arg3 ...} } + set result [uplevel 1 [concat $cmd $args]] + + # split into vars + lassign $result type thunk + + # loop + while {$type eq "next"} { + set result [uplevel 1 $thunk] + lassign $result type thunk + } + + set final_value $thunk + + return $final_value } + +# return { value final_value } +# or { next {cmd arg1 arg2} } +proc factorial_step {n result} { + + if {$n <= 1} { + set ret_value [list "value" $result] + } else { + + # n-1 + set next_n [expr {$n-1}] + + # (n-1) * fact(n) + set next_result [expr {$n * $result}] + + # {func arg1 arg2} + set next_thunk [list factorial_step $next_n $next_result] + + # Return the next step as a list + set ret_value [list "next" $next_thunk] + } + + return $ret_value +} + + +# The execution is wrapped by the trampoline +proc factorial {n} { + return [trampoline factorial_step $n 1] +} + +set f [factorial 100] diff --git a/Task/Factorial/Tcl/factorial-7.tcl b/Task/Factorial/Tcl/factorial-7.tcl new file mode 100644 index 0000000000..ecdfbe5752 --- /dev/null +++ b/Task/Factorial/Tcl/factorial-7.tcl @@ -0,0 +1,11 @@ +puts [ifact 30] +puts [rfact 30] +puts [ifact_caching 30] + +set n 400 +set iterations 10000 +puts "calculate $n factorial $iterations times" +puts "ifact: [time {ifact $n} $iterations]" +puts "rfact: [time {rfact $n} $iterations]" +# for the caching proc, reset the cache between each iteration so as not to skew the results +puts "ifact_caching: [time {ifact_caching $n; unset -nocomplain fact_cache} $iterations]" diff --git a/Task/Factorial/Tcl/factorial-8.tcl b/Task/Factorial/Tcl/factorial-8.tcl new file mode 100644 index 0000000000..46e5e0fcab --- /dev/null +++ b/Task/Factorial/Tcl/factorial-8.tcl @@ -0,0 +1,5 @@ +package require math::special + +proc gfact n { + expr {round([::math::special::Gamma [expr {$n+1}]])} +} diff --git a/Task/Factorial/Uiua/factorial.uiua b/Task/Factorial/Uiua/factorial.uiua new file mode 100644 index 0000000000..7b2a3e07ea --- /dev/null +++ b/Task/Factorial/Uiua/factorial.uiua @@ -0,0 +1 @@ +Factorial = /×+1⇡ diff --git a/Task/Factorial/Uxntal/factorial.uxnatl b/Task/Factorial/Uxntal/factorial.uxnatl index 6ce1360a76..f936013ac4 100644 --- a/Task/Factorial/Uxntal/factorial.uxnatl +++ b/Task/Factorial/Uxntal/factorial.uxnatl @@ -1,4 +1,28 @@ -@factorial ( n* -: fact* ) +%newline { [ LIT2 0a -Console/write ] DEO } + +|18 @Console/write + +|100 + +#0900 +&loop + DUP #00 SWP factorial print/dec newline + INC GTHk ?&loop +POP2 + +BRK + +@factorial ( n* -- n!* ) ORAk ?{ POP2 #0001 JMP2r } DUP2 #0001 SUB2 factorial MUL2 -JMP2r + JMP2r + +@print/dec ( short* -- ) + #000a SWP2 [ LITr ff ] + &get ( -- ) + SWP2k DIV2k MUL2 SUB2 STH + POP OVR2 DIV2 ORAk ?&get + POP2 POP2 + &put ( -- ) + STHr INCk ?{ POP JMP2r } + [ LIT "0 ] ADD .Console/write DEO !&put diff --git a/Task/Factorial/VBScript/factorial.vb b/Task/Factorial/VBScript/factorial.vbs similarity index 100% rename from Task/Factorial/VBScript/factorial.vb rename to Task/Factorial/VBScript/factorial.vbs diff --git a/Task/Factorial/VHDL/factorial.vhdl b/Task/Factorial/VHDL/factorial.vhd similarity index 100% rename from Task/Factorial/VHDL/factorial.vhdl rename to Task/Factorial/VHDL/factorial.vhd diff --git a/Task/Factorial/Vyxal/factorial-1.vyxal b/Task/Factorial/Vyxal/factorial-1.vyxal new file mode 100644 index 0000000000..25e660494e --- /dev/null +++ b/Task/Factorial/Vyxal/factorial-1.vyxal @@ -0,0 +1 @@ +¡ diff --git a/Task/Factorial/Vyxal/factorial-2.vyxal b/Task/Factorial/Vyxal/factorial-2.vyxal new file mode 100644 index 0000000000..954fe1858c --- /dev/null +++ b/Task/Factorial/Vyxal/factorial-2.vyxal @@ -0,0 +1 @@ +ɾƒ* diff --git a/Task/Factorial/Vyxal/factorial-3.vyxal b/Task/Factorial/Vyxal/factorial-3.vyxal new file mode 100644 index 0000000000..601abd91b0 --- /dev/null +++ b/Task/Factorial/Vyxal/factorial-3.vyxal @@ -0,0 +1 @@ +λ0=[1|‹x*]; diff --git a/Task/Factorial/YAMLScript/factorial.ys b/Task/Factorial/YAMLScript/factorial.ys index 8cd4d4397a..29d50ba6fa 100644 --- a/Task/Factorial/YAMLScript/factorial.ys +++ b/Task/Factorial/YAMLScript/factorial.ys @@ -1,7 +1,10 @@ -#!/usr/bin/env ys-0 +!YS-v0 -defn main(n): - say: "$n! = $factorial(n)" +defn main(*ns): + each n ns: + say: "$n! -> $factorial(n)" defn factorial(x): - apply *: 2 .. x + if x <= 2: + (x ||| 1) + (2 .. x).mul(*) diff --git a/Task/Factorions/ALGOL-68/factorions.alg b/Task/Factorions/ALGOL-68/factorions.alg index 70b2f250e7..bf43b1ebde 100644 --- a/Task/Factorions/ALGOL-68/factorions.alg +++ b/Task/Factorions/ALGOL-68/factorions.alg @@ -1,9 +1,9 @@ BEGIN # cache factorials from 0 to 11 # - [ 0 : 11 ]INT fact; - fact[0] := 1; + [ 0 : 11 ]INT bfact; + bfact[0] := 1; FOR n TO 11 DO - fact[n] := fact[n-1] * n + bfact[n] := bfact[n-1] * n OD; FOR b FROM 9 TO 12 DO print( ( "The factorions for base ", whole( b, 0 ), " are:", newline ) ); @@ -11,7 +11,7 @@ BEGIN INT sum := 0; INT j := i; WHILE j > 0 DO - sum +:= fact[ j MOD b ]; + sum +:= bfact[ j MOD b ]; j OVERAB b OD; IF sum = i THEN print( ( whole( i, 0 ), " " ) ) FI diff --git a/Task/Factorions/Ada/factorions.adb b/Task/Factorions/Ada/factorions.adb new file mode 100644 index 0000000000..a8d21fb554 --- /dev/null +++ b/Task/Factorions/Ada/factorions.adb @@ -0,0 +1,64 @@ +with Ada.Text_IO; + +procedure Factorions is + subtype Factorial_Domain is Natural range 0 .. 11; + subtype Log_Base is Positive range 2 .. Positive'Last; + type Result_Table is array (Factorial_Domain) of Positive; + + Factorial : Result_Table; + Search_Limit : Positive := 1_500_000; + + procedure Precompute_Factorials is + begin + Factorial (0) := 1; + + for I in 1 .. Factorial'Last loop + Factorial (I) := I * Factorial (I - 1); + end loop; + end Precompute_Factorials; + + function Floor_Log (Number : Positive; Base : Log_Base) return Natural is + Remaining : Natural := Number; + Floor_Log : Natural := 0; + begin + while Remaining > Base loop + Remaining := Remaining / Base; + Floor_Log := Floor_Log + 1; + end loop; + + return Floor_Log; + end Floor_Log; + + function Digit (Number, Index : Natural; Base : Log_Base) return Natural is + begin + return (Number / (Base ** Index)) mod Base; + end Digit; + + function Is_Factorion (Number : Positive; Base : Log_Base) return Boolean is + Digit_Sum : Natural := 0; + begin + for I in 0 .. Floor_Log (Number, Base) loop + Digit_Sum := Digit_Sum + Factorial (Digit (Number, I, Base)); + end loop; + + return Digit_Sum = Number; + end Is_Factorion; + + procedure Show_Factorions (Base : Log_Base) is + begin + Ada.Text_IO.Put_Line ("Search Base " & Base'Image); + for I in 1 .. Search_Limit loop + if Is_Factorion (I, Base) then + Ada.Text_IO.Put_Line (I'Image); + end if; + end loop; + Ada.Text_IO.Put_Line ("Done Base " & Base'Image); + end Show_Factorions; + +begin + Precompute_Factorials; + Show_Factorions (9); + Show_Factorions (10); + Show_Factorions (11); + Show_Factorions (12); +end Factorions; diff --git a/Task/Factorions/Arturo/factorions.arturo b/Task/Factorions/Arturo/factorions.arturo index 700ea04d67..e31b208049 100644 --- a/Task/Factorions/Arturo/factorions.arturo +++ b/Task/Factorions/Arturo/factorions.arturo @@ -1,10 +1,9 @@ factorials: [1 1 2 6 24 120 720 5040 40320 362880 3628800 39916800] factorion?: function [n, base][ - try? [ + if throws? [ n = sum map digits.base:base n 'x -> factorials\[x] - ] - else [ + ][ print ["n:" n "base:" base] false ] @@ -12,4 +11,3 @@ factorion?: function [n, base][ loop 9..12 'base -> print ["Base" base "factorions:" select 1..45000 'z -> factorion? z base] -] diff --git a/Task/Factorions/Delphi/factorions.delphi b/Task/Factorions/Delphi/factorions.pas similarity index 100% rename from Task/Factorions/Delphi/factorions.delphi rename to Task/Factorions/Delphi/factorions.pas diff --git a/Task/Factorions/EasyLang/factorions.easy b/Task/Factorions/EasyLang/factorions.easy new file mode 100644 index 0000000000..014c445c4c --- /dev/null +++ b/Task/Factorions/EasyLang/factorions.easy @@ -0,0 +1,20 @@ +len fact[] 12 +# +fact[0] = 1 +for n = 1 to 11 + fact[n] = fact[n - 1] * n +. +for b = 9 to 12 + write "base " & b & " factorions:" + for i = 1 to 1500000 - 1 + sum = 0 + j = i + while j > 0 + d = j mod b + sum += fact[d] + j = j div b + . + if sum = i : write " " & i + . + print "" +. diff --git a/Task/Factorions/Fortran/factorions.f b/Task/Factorions/Fortran/factorions.f new file mode 100644 index 0000000000..a142cc2e4a --- /dev/null +++ b/Task/Factorions/Fortran/factorions.f @@ -0,0 +1,52 @@ +! Factorions +! tested with Intel ifx (IFX) 2025.2.1 20250806 on Kubuntu 25.10 +! GNU gfortran (Ubuntu 15.2.0-4ubuntu4) 15.2.0 on Kubuntu 25.10 +! VSI Fortran x86-64 V8.7-001 on OpenVMS V9.2-3 +program Factorions +integer, parameter :: minBase=9, maxBase = 12 ! minumum and maximum base used in this little program +integer, parameter :: factLim=1499999 ! Maximum factorial Number for all bases that are used here +integer, dimension(0:maxBase-1) :: fact ! Stored factorials for numbers 0...12 + +integer :: ii, jj, base + +! Prepare cached factorial function +fact = 1 +do ii=1, maxBase-1 + do jj= 2, ii + fact(ii) = fact(ii) * jj + enddo +end do + +! +! Brute force: for all bases, for all numbers 1...max tes each number and print if its a factorion. +! +do base=minBase, maxBase + write (*, '("The factorions in base ", i0, " are:")') base + do ii=1, factLim + if (isFactorion (ii, base)) write (*, '(1x,i0)', advance='no') ii + enddo + write (*,'(/)') +end do + +contains + +! +! Separate digits d of number n in base b, sum up d!, and compare result with n. +! +function isFactorion (n,b) result (YN) +integer, intent (in) :: n, b +logical :: YN +integer :: dig, nn, facts_sum + +nn = N +facts_sum = 0 +do while (nn .ne. 0) + dig = mod (nn, b) + nn = nn / b + + facts_sum = facts_sum + fact(dig) +enddo +yn = facts_sum .eq. n + +end function isFactorion +end program Factorions diff --git a/Task/Factorions/JavaScript/factorions.js b/Task/Factorions/JavaScript/factorions.js new file mode 100644 index 0000000000..a9a3f2c3ae --- /dev/null +++ b/Task/Factorions/JavaScript/factorions.js @@ -0,0 +1,25 @@ +function factorial(n) { + if (n <= 1) { + return 1; + } + let a = [...Array(n + 1).keys()]; + a.shift(); + return a.reduce((x, y) => x * y); +} + +function fact_digsum(n, b) { + if (n > b - 1) { + return factorial(n % b) + fact_digsum(Math.floor(n / b), b); + } + return factorial(n); +} + +for (let i = 9; i <= 12; i++) { + console.log(`Factorions in base ${i}:`); + for (let j = 1; j < 1499999; j++) { + if (j == fact_digsum(j, i)) { + console.log(j); + } + } + console.log(); +} diff --git a/Task/Factorions/Jq/factorions.jq b/Task/Factorions/Jq/factorions.jq index 84891c0781..012ec312ee 100644 --- a/Task/Factorions/Jq/factorions.jq +++ b/Task/Factorions/Jq/factorions.jq @@ -29,7 +29,7 @@ def sufficient: .digits += 1 | .value *= $base ) ; -# Show the factorions for all based from 2 through 12: +# Show the factorions for all bases from 2 through 12: (range(2;10) | . as $base | sufficient.value as $max diff --git a/Task/Factorions/Julia/factorions.julia b/Task/Factorions/Julia/factorions.jl similarity index 100% rename from Task/Factorions/Julia/factorions.julia rename to Task/Factorions/Julia/factorions.jl diff --git a/Task/Factorions/OCaml/factorions.ocaml b/Task/Factorions/OCaml/factorions.ml similarity index 100% rename from Task/Factorions/OCaml/factorions.ocaml rename to Task/Factorions/OCaml/factorions.ml diff --git a/Task/Factorions/PascalABC.NET/factorions.pas b/Task/Factorions/PascalABC.NET/factorions.pas new file mode 100644 index 0000000000..ac69d82c56 --- /dev/null +++ b/Task/Factorions/PascalABC.NET/factorions.pas @@ -0,0 +1,22 @@ +## +var fact := |1| * 12; +for var i := 1 to 11 do fact[i] := i * fact[i - 1]; + +for var b := 9 to 12 do +begin + write('The factorions for base ', b:2, ' are: '); + for var i := 1 to 1_500_000 do + begin + var fact_sum := 0; + var j := i; + while j > 0 do + begin + var d := j mod b; + fact_sum += fact[d]; + j := j div b; + end; + if fact_sum = i then + print(i) + end; + println; +end; diff --git a/Task/Factorions/Pluto/factorions.pluto b/Task/Factorions/Pluto/factorions.pluto new file mode 100644 index 0000000000..f95a296746 --- /dev/null +++ b/Task/Factorions/Pluto/factorions.pluto @@ -0,0 +1,18 @@ +-- Cache factorials from 0 to 11. +local fact = {[0] = 1} +for n = 1, 11 do fact[n] = fact[n - 1] * n end + +for b = 9, 12 do + print($"The factorions for base {b} are:") + for i = 1, 1_499_999 do + local sum = 0 + local j = i + while j > 0 do + local d = j % b + sum += fact[d] + j //= b + end + if sum == i then io.write($"{i} ") end + end + print("\n") +end diff --git a/Task/Factorions/R/factorions.r b/Task/Factorions/R/factorions.r new file mode 100644 index 0000000000..9f1c569b7e --- /dev/null +++ b/Task/Factorions/R/factorions.r @@ -0,0 +1,12 @@ +fact_digsum <- function(n, b) { + if(n > b-1) { + factorial(n%%b)+fact_digsum(n%/%b, b) + } else factorial(n) +} + +for(i in 9:12) { + cat("\nFactorions in base ", i, ":\n", sep="") + for(j in 1:1499999) { + if(j == fact_digsum(j, i)) cat(j, "") + } +} diff --git a/Task/Factorions/VBScript/factorions.vb b/Task/Factorions/VBScript/factorions.vbs similarity index 100% rename from Task/Factorions/VBScript/factorions.vb rename to Task/Factorions/VBScript/factorions.vbs diff --git a/Task/Factorions/Vyxal/factorions.vyxal b/Task/Factorions/Vyxal/factorions.vyxal new file mode 100644 index 0000000000..bf2fb337c6 --- /dev/null +++ b/Task/Factorions/Vyxal/factorions.vyxal @@ -0,0 +1,7 @@ +λ2|→B:←Bτƛ¡}∑$_-¬}£ # check whether factorion +⟨9|10|11|12⟩(`Base `₴n:₴\:,→b + 1500000 ( + n 1000 ≠[ + ←b n¥†[n,]] + ) +) diff --git a/Task/Factors-of-a-Mersenne-number/Ada/factors-of-a-mersenne-number.ada b/Task/Factors-of-a-Mersenne-number/Ada/factors-of-a-mersenne-number.adb similarity index 100% rename from Task/Factors-of-a-Mersenne-number/Ada/factors-of-a-mersenne-number.ada rename to Task/Factors-of-a-Mersenne-number/Ada/factors-of-a-mersenne-number.adb diff --git a/Task/Factors-of-a-Mersenne-number/Arturo/factors-of-a-mersenne-number.arturo b/Task/Factors-of-a-Mersenne-number/Arturo/factors-of-a-mersenne-number.arturo index 6542a31a61..ec0ce3744d 100644 --- a/Task/Factors-of-a-Mersenne-number/Arturo/factors-of-a-mersenne-number.arturo +++ b/Task/Factors-of-a-Mersenne-number/Arturo/factors-of-a-mersenne-number.arturo @@ -5,16 +5,16 @@ mersenneFactors: function [q][ -> shl 'r 1 d: new 1 + 2 * q while [true][ - i: new 1 + i: 1 p: new r while [p <> 0][ - i: new (i * i) % d + i: (i * i) % d if p < 0 -> 'i * 2 if i > d -> 'i - d shl 'p 1 ] - if? i <> 1 -> 'd + 2 * q - else -> break + switch i <> 1 -> 'd + 2 * q + -> break ] print ["2 ^" q "- 1 = 0 ( mod" d ")"] ] diff --git a/Task/Factors-of-a-Mersenne-number/Crystal/factors-of-a-mersenne-number.crystal b/Task/Factors-of-a-Mersenne-number/Crystal/factors-of-a-mersenne-number.cr similarity index 100% rename from Task/Factors-of-a-Mersenne-number/Crystal/factors-of-a-mersenne-number.crystal rename to Task/Factors-of-a-Mersenne-number/Crystal/factors-of-a-mersenne-number.cr diff --git a/Task/Factors-of-a-Mersenne-number/EasyLang/factors-of-a-mersenne-number.easy b/Task/Factors-of-a-Mersenne-number/EasyLang/factors-of-a-mersenne-number.easy index e251a85135..60690b52c1 100644 --- a/Task/Factors-of-a-Mersenne-number/EasyLang/factors-of-a-mersenne-number.easy +++ b/Task/Factors-of-a-Mersenne-number/EasyLang/factors-of-a-mersenne-number.easy @@ -1,40 +1,32 @@ fastfunc isprim num . i = 2 while i <= sqrt num - if num mod i = 0 - return 0 - . + if num mod i = 0 : return 0 i += 1 . return 1 . -func bit_count n . - while n > 0 - n = bitshift n -1 - cnt += 1 - . - return cnt -. -func mod_pow p n . +func modpow p n . square = 1 - bits = bit_count p - while bits > 0 + p2 = pow 2 floor log n 2 + while p2 >= 1 square *= square - bits -= 1 - if bitand p bitshift 1 bits > 0 - square = bitshift square 1 + if p >= p2 + p -= p2 + square *= 2 . + p2 /= 2 square = square mod n . return square . func mersenne_factor p . - while 1 = 1 + repeat k += 1 q = 2 * k * p + 1 - if (q mod 8 = 1 or q mod 8 = 7) and mod_pow p q = 1 and isprim q = 1 - return q - . + m = q mod 8 + until (m = 1 or m = 7) and modpow p q = 1 and isprim q = 1 . + return q . print mersenne_factor 929 diff --git a/Task/Factors-of-a-Mersenne-number/Elixir/factors-of-a-mersenne-number.elixir b/Task/Factors-of-a-Mersenne-number/Elixir/factors-of-a-mersenne-number.ex similarity index 100% rename from Task/Factors-of-a-Mersenne-number/Elixir/factors-of-a-mersenne-number.elixir rename to Task/Factors-of-a-Mersenne-number/Elixir/factors-of-a-mersenne-number.ex diff --git a/Task/Factors-of-a-Mersenne-number/FutureBasic/factors-of-a-mersenne-number.basic b/Task/Factors-of-a-Mersenne-number/FutureBasic/factors-of-a-mersenne-number.basic new file mode 100644 index 0000000000..2552a45c70 --- /dev/null +++ b/Task/Factors-of-a-Mersenne-number/FutureBasic/factors-of-a-mersenne-number.basic @@ -0,0 +1,108 @@ +// +// Factors of Mersenne number +// +// Using FutureBasic 7.0.36 +// October 2025, R.W. + +include "gmp.incl" + +_scanMax = 2000000 // max k scan set at 2 million + +// ------------------------------------------------------------ +// Exponent primality using GMP (mpz_probab_prime_p) +// Returns _true if p is (probably) prime; _false otherwise. + +local fn IsPrimeP_mpz( p as UInt32 ) as BOOL + mpz_t z + int res + if p < 2 then return _false + mpz_init( z ) + mpz_set_ui( z, p ) + // Miller–Rabin reps = 18 is sufficient + // res 0 = composite, 1 = probable, 2 = definite + res = fn mpz_probab_prime_p( z, 18 ) + mpz_clear( z ) + if res == 0 then return _false + // res 1 or 2 → treat as prime for gating +end fn = _True + +// ------------------------------------------------------------ +// Find first prime factor q of M_p = 2^p - 1 +// Scans q = 2 * k * p + 1 for k = 1..maxK. Returns 0 if none found. +// Precondition: caller ensures p is (probably) prime and p ≥ 2. +// +local fn FindMersenneFactor( p as UInt32, maxK as UInt64 ) as UInt64 + mpz_t qz, rz + UInt64 k, qCandidate + int isPrime + // Eliminate the obvious + if p < 2 then return 0 + if p == 2 then return 0 // M2 = 3 is prime + + mpz_init( qz ) + mpz_init( rz ) + k = 1 + while k <= maxK + // q = 2 * k * p + 1 (candidates with q ≡ 1 (mod 2p)) + qCandidate = (UInt64)2 * (UInt64)p * k + 1ULL + // primality screen for q + mpz_set_ui( qz, qCandidate ) + // Miller–Rabin reps = 18 is sufficient + isPrime = fn mpz_probab_prime_p( qz, 18 ) + if isPrime > 0 + // Test 2^p ≡ 1 (mod q) + mpz_set_ui( rz, 2 ) + mpz_powm_ui( rz, rz, p, qz ) + if fn mpz_cmp_ui( rz, 1 ) == 0 + mpz_clear( rz ) + mpz_clear( qz ) + return qCandidate + end if + end if + k = k + 1 + wend + mpz_clear( rz ) + mpz_clear( qz ) +end fn = 0 + +// ------------------------------------------------------------ +// M_p gating/message +// +local fn ReportMersenne( p as UInt32, maxK as UInt64 ) + UInt64 q + // Gate on exponent primality first + if fn IsPrimeP_mpz( p ) == _false + print @"M"; p; @" = 2^"; p; @" - 1 exponent is not prime" + exit fn + end if + // p is (probably) prime: try to find a factor of M_p + q = fn FindMersenneFactor( p, maxK ) + if q == 0 + // No factor found in scan range → either prime or factor > search bound + print @"M"; p; @" = 2^"; p; @" - 1 is prime (no factor found in range)" + else + print @"M"; p; @" = 2^"; p; @" - 1 is composite with factor "; q + end if +end fn + + +// Main + +window 1 + +UInt32 p +p = 929 // Rosetta Task requirement + +// start the clock +CFTimeInterval t +t = fn CACurrentMediaTime + +// note, if you need a range, just do a loop +// like: +// for p = 900 to 930 +fn ReportMersenne( p, _scanMax ) // 2 million k scans +// next p + +printf @"\nElapsed time: %.3f ms", (fn CACurrentMediaTime-t)*1000 + +HandleEvents diff --git a/Task/Factors-of-a-Mersenne-number/Jq/factors-of-a-mersenne-number.jq b/Task/Factors-of-a-Mersenne-number/Jq/factors-of-a-mersenne-number.jq new file mode 100644 index 0000000000..2846586599 --- /dev/null +++ b/Task/Factors-of-a-Mersenne-number/Jq/factors-of-a-mersenne-number.jq @@ -0,0 +1,61 @@ +# Generic filters: + +# Integer division (for gojq and jaq) +# If $j is 0, then an error condition is raised; +# otherwise, assuming infinite-precision integer arithmetic, +# if the input and $j are integers, then the result will be an integer. +def idivide($j): + (. % $j) as $mod + | (. - $mod) / $j | round; + +# Convert the input integer to a stream of 0s and 1s, least significant bit first +def bitwise: + recurse( if . >= 2 then idivide(2) else empty end) | . % 2; + +def is_prime: + . as $n + | if ($n < 2) then false + elif ($n % 2 == 0) then $n == 2 + elif ($n % 3 == 0) then $n == 3 + elif ($n % 5 == 0) then $n == 5 + elif ($n % 7 == 0) then $n == 7 + elif ($n % 11 == 0) then $n == 11 + elif ($n % 13 == 0) then $n == 13 + elif ($n % 17 == 0) then $n == 17 + elif ($n % 19 == 0) then $n == 19 + else sqrt as $s + | 23 + | until( . > $s or ($n % . == 0); . + 2) + | . > $s + end; + +### Factors of Mersene numbers + +def trialFactor($base; $exp; $mod): + [$exp | bitwise] as $bits + | ($bits|length) as $length + | reduce range( 0; $length) as $i (1; + (. * . * (if $bits[$length-$i-1] == 1 then $base else 1 end)) % $mod ) + | . == 1 ; + +def mersenneFactor($p): + ((pow(2;$p) - 1) | sqrt | floor) as $limit + | {k: 1} + | until ((2*.k*$p - 1) >= $limit or .emit; + (2*.k*$p + 1 ) as $q + | if ($q%8 == 1 or $q%8 == 7) and trialFactor(2; $p; $q) and ($q | is_prime) + then .emit = $q # q is a factor of 2^p - 1 + else .k += 1 + end) + | if .emit then .emit else null end; + +### Examples: + +def m: [3, 5, 11, 17, 23, 29, 31, 37, 41, 43, 47, 53, 59, 67, 71, 73, 79, 83, 97, 929]; + +m[] +| mersenneFactor(.) as $f +| "2^\(.) - 1 is " + + if $f then "composite (factor \($f))" + else "prime" + end diff --git a/Task/Factors-of-a-Mersenne-number/Julia/factors-of-a-mersenne-number.julia b/Task/Factors-of-a-Mersenne-number/Julia/factors-of-a-mersenne-number.jl similarity index 100% rename from Task/Factors-of-a-Mersenne-number/Julia/factors-of-a-mersenne-number.julia rename to Task/Factors-of-a-Mersenne-number/Julia/factors-of-a-mersenne-number.jl diff --git a/Task/Factors-of-a-Mersenne-number/Kotlin/factors-of-a-mersenne-number.kotlin b/Task/Factors-of-a-Mersenne-number/Kotlin/factors-of-a-mersenne-number.kts similarity index 100% rename from Task/Factors-of-a-Mersenne-number/Kotlin/factors-of-a-mersenne-number.kotlin rename to Task/Factors-of-a-Mersenne-number/Kotlin/factors-of-a-mersenne-number.kts diff --git a/Task/Factors-of-a-Mersenne-number/M2000-Interpreter/factors-of-a-mersenne-number.m2000 b/Task/Factors-of-a-Mersenne-number/M2000-Interpreter/factors-of-a-mersenne-number.m2000 new file mode 100644 index 0000000000..9387607154 --- /dev/null +++ b/Task/Factors-of-a-Mersenne-number/M2000-Interpreter/factors-of-a-mersenne-number.m2000 @@ -0,0 +1,39 @@ +// 67 need a lot of time 45 minutes (2758716msec) where 71 need 3.1 second (3131msec) +Module Factors_of_a_Mersenne_number{ + Dim q() + // 67 need a lot of time 51 minutes (3082671msec) where 71 need 3.5 second (3505msec) + q()= (11, 23, 29, 37, 41, 43, 47, 53, 59, 67, 71, 73, 79, 83, 97, 929) + profiler + long long j=0x8000_0000 + long long r, p, i + long d, dd + For k = 0 To len(q())-1 + If @isPrime(q(k)) Then + r=q(k):dd =2*r:d=dd+1 + while rd Then i-=d + Until p=0:If i=1 Then Exit Else d+=dd:i=1:p=r + Always + Print "2^"; q(k); @(6); " - 1 = 0 (mod "; d; ")" + Else + Print q(k); " is not prime" + End If + Print ceil(timecount):profiler + Next + + Function isPrime(n As long) + If n Mod 2 = 0 Then = n=2 : Exit Function + If n Mod 3 = 0 Then = n=3 : Exit Function + Local d As long = 5 + While d * d <= n + If n Mod d = 0 Then =False: exit function + d += 2 + If n Mod d = 0 Then = False: exit function + d += 4 + End While + =True + End Function +} +Factors_of_a_Mersenne_number diff --git a/Task/Factors-of-a-Mersenne-number/PARI-GP/factors-of-a-mersenne-number-2.parigp b/Task/Factors-of-a-Mersenne-number/PARI-GP/factors-of-a-mersenne-number-2.parigp deleted file mode 100644 index a43166ed17..0000000000 --- a/Task/Factors-of-a-Mersenne-number/PARI-GP/factors-of-a-mersenne-number-2.parigp +++ /dev/null @@ -1,20 +0,0 @@ -TM(p) = local(status=1, i=1, len=0, S=0);{ -printp("Test TM \t..."); -S=2*p+1; -len = length(binary(p)); -B = Vecsmall(binary(p)); -q = B[i]*B[i]; -while( i<=len & status ==1, - if( B[i] != 0, - q = q*2; - ); - r = q%S; - q = r*r; - if( i == len & r == 1, - status = 0; - printp("Not Prime!"); - ); - i++; -); -return(status); -} diff --git a/Task/Factors-of-a-Mersenne-number/PARI-GP/factors-of-a-mersenne-number-1.parigp b/Task/Factors-of-a-Mersenne-number/PARI-GP/factors-of-a-mersenne-number.parigp similarity index 100% rename from Task/Factors-of-a-Mersenne-number/PARI-GP/factors-of-a-mersenne-number-1.parigp rename to Task/Factors-of-a-Mersenne-number/PARI-GP/factors-of-a-mersenne-number.parigp diff --git a/Task/Factors-of-a-Mersenne-number/PascalABC.NET/factors-of-a-mersenne-number.pas b/Task/Factors-of-a-Mersenne-number/PascalABC.NET/factors-of-a-mersenne-number.pas new file mode 100644 index 0000000000..32d45238dc --- /dev/null +++ b/Task/Factors-of-a-Mersenne-number/PascalABC.NET/factors-of-a-mersenne-number.pas @@ -0,0 +1,36 @@ +const + q = 929; + +function isPrime(a: integer): boolean; +begin + if a = 2 then + begin result := true; exit end; + if (a < 2) or (a mod 2 = 0) then + begin result := false; exit end; + for var i := 3 to sqrt(a).Floor step 2 do + if a mod i = 0 then + begin result := false; exit end; + result := true; +end; + +begin + if not isPrime(q) then exit; + var r := q; + while r > 0 do r := r shl 1; + var d := 2 * q + 1; + while true do + begin + var i := 1; + var p := r; + while p <> 0 do + begin + i := (i * i) mod d; + if p < 0 then i *= 2; + if i > d then i -= d; + p := p shl 1; + end; + if i <> 1 then d += 2 * q + else break + end; + write('2^', q, ' - 1 = 0 (mod ', d, ')'); +end. diff --git a/Task/Factors-of-a-Mersenne-number/Phix/factors-of-a-mersenne-number.phix b/Task/Factors-of-a-Mersenne-number/Phix/factors-of-a-mersenne-number.phix index 641c6a8d2f..8185372101 100644 --- a/Task/Factors-of-a-Mersenne-number/Phix/factors-of-a-mersenne-number.phix +++ b/Task/Factors-of-a-Mersenne-number/Phix/factors-of-a-mersenne-number.phix @@ -1,39 +1,40 @@ -(phixonline)--> - with javascript_semantics - function modpow(atom x, atom n, atom m) - atom i = n, - y = 1, - z = x - while i do - if and_bits(i,1) then - y = mod(y*z,m) - end if - z = mod(z*z,m) - i = floor(i/2) - end while - return y - end function +with javascript_semantics +function modpow(atom x, n, m) + atom {i,y,z} = {n,1,x} + while i do + if odd(i) then + y = mod(y*z,m) + end if + z = mod(z*z,m) + i = floor(i/2) + end while + return y +end function - function mersenne_factor(integer p) - if not is_prime(p) then return -1 end if - atom limit = sqrt(power(2,p))-1 - integer k = 1 - while 1 do - atom q = 2*p*k + 1 - if q>=limit then exit end if - if find(mod(q,8),{1,7}) - and is_prime(q) - and modpow(2,p,q)=1 then - return q - end if - k += 1 - end while - return 0 - end function +function mersenne_factor(integer p) + if not is_prime(p) then return -1 end if + atom limit = sqrt(power(2,p))-1 + integer k = 1 + while 1 do + atom q = 2*p*k + 1 + if q>=limit then exit end if + if find(mod(q,8),{1,7}) + and is_prime(q,true) + and modpow(2,p,q)=1 then + return q + end if + k += 1 + end while + return 0 +end function - sequence tests = {11, 23, 29, 37, 41, 43, 47, 53, 59, 67, 71, 73, 79, 83, 97, 929, 937} - for i=1 to length(tests) do - integer ti = tests[i] - printf(1,"A factor of M%d is %d\n",{ti,mersenne_factor(ti)}) - end for - - function fairshare(integer n, base) - sequence res = repeat(0,n) - for i=1 to n do - integer j = i-1, - t = 0 - while j>0 do - t += remainder(j,base) - j = floor(j/base) - end while - res[i] = remainder(t,base) - end for - return {base,res} - end function +with javascript_semantics +function fairshare(integer n, base) + sequence res = repeat(0,n) + for i=1 to n do + integer j = i-1, t = 0 + while j>0 do + t += rmdr(j,base) + j = floor(j/base) + end while + res[i] = rmdr(t,base) + end for + return {base,res} +end function - constant tests = {2,3,5,11} - for i=1 to length(tests) do - printf(1,"%2d : %v\n", fairshare(25, tests[i])) - end for - - with javascript_semantics - -- demo\rosetta\Fermat.exw - include mpfr.e +-- demo\rosetta\Fermat.exw +with javascript_semantics +include mpfr.e - procedure fermat(mpz res, integer n) - integer pn = power(2,n) - mpz_ui_pow_ui(res,2,pn) - mpz_add_si(res,res,1) - end procedure +procedure fermat(mpz res, integer n) + integer pn = power(2,n) + mpz_ui_pow_ui(res,2,pn) + mpz_add_si(res,res,1) +end procedure - mpz fn = mpz_init() - constant lim = iff(platform()=JS?18:29), -- (see note) - print_lim = iff(platform()=JS?16:20) - for i=0 to lim do - fermat(fn,i) - if i<=print_lim then - printf(1,"F%d = %s\n",{i,shorten(mpz_get_str(fn))}) - else -- (since printing it takes too long...) - printf(1,"F%d has %,d digits\n",{i,mpz_sizeinbase(fn,10)}) - end if - end for +mpz fn = mpz_init() +constant lim = iff(platform()=JS?18:29), -- (see note) + print_lim = iff(platform()=JS?16:20) +atom t +for i=0 to lim do + t = time() + fermat(fn,i) + string ts = elapsed(t,0.2," [%s]") + if i<=print_lim then + printf(1,"F%d = %s%s\n",{i,shorten(mpz_get_str(fn)),ts}) + else -- (since printing it takes too long...) + printf(1,"F%d has %,d digits%s\n",{i,mpz_sizeinbase(fn,10),ts}) + end if +end for - printf(1,"\n") - constant flimit = iff(platform()=JS?11:13) - for i=0 to flimit do - atom t = time() - fermat(fn,i) - sequence f = mpz_prime_factors(fn, 200000) - t = time()-t - string fs = "", - ts = elapsed(t) - if length(f[$])=1 then -- (as per docs) - mpz_set_str(fn,f[$][1]) - if not mpz_prime(fn) then - if length(f)=1 then - fs = " (not prime)" - else - fs = " (last factor is not prime)" - end if - end if - f = deep_copy(f) - f[$][1] = shorten(f[$][1]) - elsif length(f)=1 - and mpz_prime(fn) then - fs = " (prime)" - end if - fs = mpz_factorstring(f)&fs - printf(1,"Factors of F%d: %s [%s]\n",{i,fs,ts}) - end for - - with javascript_semantics - function nacci_noo(integer n, s, l) - if n<2 then return n+n*l end if - if n=2 then return 1 end if - atom res = nacci_noo(n-1,s,l) - for i=2 to min(s,n-1) do - res += nacci_noo(n-i,s,l) - end for - return res - end function +with javascript_semantics +function nacci_noo(integer n, s, l) + if n<2 then return n+n*l end if + if n=2 then return 1 end if + atom res = nacci_noo(n-1,s,l) + for i=2 to min(s,n-1) do + res += nacci_noo(n-i,s,l) + end for + return res +end function - constant names = split("lucas fibo tribo tetra penta hexa hepta octo nona deca") - sequence f = repeat(0,10) - for i=1 to 4 do - for j=1 to 10 do - f[j] = nacci_noo(j,i+(i=1),i=1) - end for - printf(1,"%snacci: %v\n",{names[i],f}) - end for - - with javascript_semantics - constant extensions = lower({"zip","rar","7z","gz","archive","A##","tar.bz2"}) +with javascript_semantics +constant extensions = lower({"zip","rar","7z","gz","archive","A##","tar.bz2"}) - global function get_known_extension(string filename) - for i=1 to length(filename) do - if filename[i]='.' then - string extension = lower(filename[i+1..$]) - if find(extension,extensions) then - return extension - end if - end if - end for - return "" - end function +global function get_known_extension(string filename) + for i,c in filename do + if c='.' then + string extension = lower(filename[i+1..$]) + if find(extension,extensions) then + return extension + end if + end if + end for + return "" +end function - constant tests = {"MyData.a##", - "MyData.tar.Gz", - "MyData.gzip", - "MyData.7z.backup", - "MyData...", - "MyData", - "MyData_v1.0.tar.bz2", - "MyData_v1.0.bz2"} +constant tests = {"MyData.a##", + "MyData.tar.Gz", + "MyData.gzip", + "MyData.7z.backup", + "MyData...", + "MyData", + "MyData_v1.0.tar.bz2", + "MyData_v1.0.bz2"} - for i=1 to length(tests) do - string ti = tests[i], - ext = get_known_extension(ti) - printf(1,"%-20s %-10s %s\n",{ti,ext,{"true","false"}[2-(find(ext,extensions)!=0)]}) - end for - - with javascript_semantics - constant p0 = {0,0}, - p1 = {0,1}, - p2 = {3,1}, - triangle = {{3/2, 12/5}, {51/10, -31/10}, {-19/5, 1/2}} - function inside(sequence p) - return sort(convex_hull({p}&triangle))==sort(deep_copy(triangle)) - end function - printf(1,"Point %v is with triangle %v?:%t\n",{p0,triangle,inside(p0)}) - printf(1,"Point %v is with triangle %v?:%t\n",{p1,triangle,inside(p1)}) - printf(1,"Point %v is with triangle %v?:%t\n",{p2,triangle,inside(p2)}) - - with javascript_semantics - constant p0 = {0,0}, - p1 = {0,1}, - p2 = {3,1}, - triangle = {{3/2, 12/5}, {51/10, -31/10}, {-19/5, 1/2}} +with javascript_semantics +constant p0 = {0,0}, + p1 = {0,1}, + p2 = {3,1}, + triangle = {{3/2, 12/5}, {51/10, -31/10}, {-19/5, 1/2}} - function side(sequence p1, p2, p3) - -- which side of plane cut by line (p2, p3) is p1 on? - atom {x1, y1} = p1, - {x2, y2} = p2, - {x3, y3} = p3 - return (x1 - x3) * (y2 - y3) - (x2 - x3) * (y1 - y3) - end function +function side(sequence p1, p2, p3) + -- which side of plane cut by line (p2, p3) is p1 on? + atom {x1, y1} = p1, + {x2, y2} = p2, + {x3, y3} = p3 + return (x1 - x3) * (y2 - y3) - (x2 - x3) * (y1 - y3) +end function - function iswithin(sequence point, triangle) - -- - -- Determine if point is within triangle. - -- If so, the point will be on the same side of each of the half planes - -- defined by vectors p1p2, p2p3, and p3p1. side is positive if outside, - -- negative if inside such a plane. All should be non-negative or all - -- non-positive if the point is within the triangle. - -- - sequence {pt1, pt2, pt3} = triangle - atom side12 = side(point, pt1, pt2), - side23 = side(point, pt2, pt3), - side31 = side(point, pt3, pt1) - bool all_non_neg = side12 >= 0 and side23 >= 0 and side31 >= 0, - all_non_pos = side12 <= 0 and side23 <= 0 and side31 <= 0 - return all_non_neg or all_non_pos - end function +function iswithin(sequence point, triangle) +-- +-- Determine if point is within triangle. +-- If so, the point will be on the same side of each of the half planes +-- defined by vectors p1p2, p2p3, and p3p1. side is positive if outside, +-- negative if inside such a plane. All should be non-negative or all +-- non-positive if the point is within the triangle. +-- + sequence {pt1, pt2, pt3} = triangle + atom side12 = side(point, pt1, pt2), + side23 = side(point, pt2, pt3), + side31 = side(point, pt3, pt1) + bool all_non_neg = side12 >= 0 and side23 >= 0 and side31 >= 0, + all_non_pos = side12 <= 0 and side23 <= 0 and side31 <= 0 + return all_non_neg or all_non_pos +end function - printf(1,"point %v is with triangle %v?:%t\n",{p0,triangle,iswithin(p0,triangle)}) - printf(1,"point %v is with triangle %v?:%t\n",{p1,triangle,iswithin(p1,triangle)}) - printf(1,"point %v is with triangle %v?:%t\n",{p2,triangle,iswithin(p2,triangle)}) - - atom t1 = time()+1 +with javascript_semantics +atom t1 = time()+1 - integer depth = 0 +integer depth = 0 - procedure recurse() - if time()>t1 then - ?depth - t1 = time()+1 - end if - depth += 1 - -- only 1 of these will ever get called, of course... - recurse() - recurse() - recurse() - end procedure +procedure recurse() + if time()>t1 then + ?depth + t1 = time()+1 + end if + depth += 1 + -- only 1 of these will ever get called, of course... + recurse() + recurse() + recurse() +end procedure - recurse() - - atom t1 = time()+1 +with javascript_semantics +atom t1 = time()+1 - integer depth = 0, depth_blown = false - string btd = "building" +integer depth = 0, depth_blown = false, + limit = iff(platform()=JS?8e3:2e7) +string btd = "building" - procedure recurse() - if time()>t1 then - printf(1,"depth: %d (%s)\n",{depth,btd}) - if depth>20_000_000 then - depth_blown = true - btd = "tearing down" - end if - t1 = time()+1 - end if - if depth_blown then - depth -= 1 - else - depth += 1 - recurse() -- (build, aka +1 with progress) - recurse() -- (tear down, -1 with progress) - end if - end procedure +procedure recurse() + if time()>t1 or depth>limit then + printf(1,"depth: %d (%s)\n",{depth,btd}) + if depth>limit then + depth_blown = true + btd = "tearing down" + end if + t1 = time()+1 + end if + if depth_blown then + depth -= 1 + else + depth += 1 + recurse() -- (build, aka +1 with progress) + recurse() -- (tear down, -1 with progress) + end if +end procedure - recurse() - - include timedate.e - - constant SUNDAY=7 - - procedure showlast(integer dow, integer doy, timedate td) - td = adjust_timedate(td,timedelta(days:=doy-1)) - integer {year,month,day} = td - while day_of_week(year,month,day)!=dow do day-=1 end while - printf(1,"%4d-%02d-%02d\n",{year,month,day}) - end procedure - - procedure last_day_of_month(integer year, integer dow) - integer doy - timedate first = {year,1,1,0,0,0,0,0} - -- start by finding the 1st of the next month, less 1 - for i=1 to 11 do - doy = day_of_year(year,i+1,1)-1 - showlast(dow,doy,first) - end for - -- do December separately, as 1st would be next year - doy = day_of_year(year,12,31) - showlast(dow,doy,first) - end procedure - last_day_of_month(2013,SUNDAY) - - with javascript_semantics - sequence mtable = {} +with javascript_semantics +sequence mtable = {} - function multiplier(atom n1, atom n2) - mtable = append(mtable,{n1,n2}) - return length(mtable) - end function +function multiplier(atom n1, atom n2) + mtable = append(mtable,{n1,n2}) + return length(mtable) +end function - function call_multiplier(integer f, atom m) - atom {n1,n2} = mtable[f] - return n1*n2*m - end function +function call_multiplier(integer f, atom m) + atom {n1,n2} = mtable[f] + return n1*n2*m +end function - constant x = 2, - xi = 0.5, - y = 4, - yi = 0.25, - z = x + y, - zi = 1 / ( x + y ) +constant x = 2, + xi = 0.5, + y = 4, + yi = 0.25, + z = x + y, + zi = 1 / ( x + y ) - ?call_multiplier(multiplier(x,xi),0.5) - ?call_multiplier(multiplier(y,yi),0.5) - ?call_multiplier(multiplier(z,zi),0.5) - - with javascript_semantics - sequence ctable = {} +with javascript_semantics +sequence ctable = {} - function compose(integer f, g) - ctable = append(ctable,{f,g}) - integer cdx = length(ctable) - return cdx - end function +function compose(integer f, g) + ctable = append(ctable,{f,g}) + integer cdx = length(ctable) + return cdx +end function - function call_composite(integer cdx, atom x) - integer {f,g} = ctable[cdx] - return f(g(x)) - end function +function call_composite(integer cdx, atom x) + integer {f,g} = ctable[cdx] + return f(g(x)) +end function - function plus1(atom x) - return x+1 - end function +function plus1(atom x) + return x+1 +end function - function halve(atom x) - return x/2 - end function +function halve(atom x) + return x/2 +end function - constant m = compose(halve,plus1) +constant m = compose(halve,plus1) - ?call_composite(m,1) -- displays 1 - ?call_composite(m,4) -- displays 2.5 - n/d ) + [ 1 2 ] is xi ( --> n/d ) + [ 4 1 ] is y ( --> n/d ) + [ 1 4 ] is yi ( --> n/d ) + [ x y v+ ] is z ( n/d n/d --> n/d ) + [ x y v+ 1/v ] is zi ( n/d n/d --> n/d ) + + [ ' [ v* v* ] join join ] is multiplier ( x n/d --> [ ) + +' xi ' [ 1 2 ] multiplier dup echo x rot do say " applied to x gives: " vulgar$ echo$ cr +' yi ' [ 1 2 ] multiplier dup echo y rot do say " applied to y gives: " vulgar$ echo$ cr +' zi ' [ 1 2 ] multiplier dup echo z rot do say " applied to z gives: " vulgar$ echo$ cr diff --git a/Task/First-class-functions-Use-numbers-analogously/Rebol/first-class-functions-use-numbers-analogously.rebol b/Task/First-class-functions-Use-numbers-analogously/Rebol/first-class-functions-use-numbers-analogously.rebol new file mode 100644 index 0000000000..717692aabd --- /dev/null +++ b/Task/First-class-functions-Use-numbers-analogously/Rebol/first-class-functions-use-numbers-analogously.rebol @@ -0,0 +1,30 @@ +Rebol [ + title: "Rosetta code: First-class functions/Use numbers analogously" + file: %First-class_functions-Use_numbers_analogously.r3 + url: https://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously +] + +;; Numeric values and their inverses +x: 2.0 xi: 0.5 +y: 4.0 yi: 0.25 +z: x + y zi: 1 / (x + y) + +;; Returns a function that multiplies its argument a by n and m, +;; printing the expression before returning the result. +;; closure (vs func) ensures n and m are captured by value in the returned func. +multiplier: closure [n m] [ + func [a] [ + prin [a "*" n "*" m "= "] + a * n * m + ] +] +;; Parallel lists: each number paired with its inverse by position +num-list: reduce [x y z] ; [2.0 4.0 6.0] +num-list-inv: reduce [xi yi zi] ; [0.5 0.25 0.1666...] + +repeat key length? num-list [ + n: num-list/:key + ni: num-list-inv/:key + fun: multiplier ni n ;; build closure: a * ni * n = a * 1.0 (always) + print as-green fun 0.5 ;; call closure with 0.5; result should always be 0.5 +] diff --git a/Task/First-class-functions-Use-numbers-analogously/Rust/first-class-functions-use-numbers-analogously.rust b/Task/First-class-functions-Use-numbers-analogously/Rust/first-class-functions-use-numbers-analogously.rs similarity index 100% rename from Task/First-class-functions-Use-numbers-analogously/Rust/first-class-functions-use-numbers-analogously.rust rename to Task/First-class-functions-Use-numbers-analogously/Rust/first-class-functions-use-numbers-analogously.rs diff --git a/Task/First-class-functions-Use-numbers-analogously/Scheme/first-class-functions-use-numbers-analogously.ss b/Task/First-class-functions-Use-numbers-analogously/Scheme/first-class-functions-use-numbers-analogously.scm similarity index 100% rename from Task/First-class-functions-Use-numbers-analogously/Scheme/first-class-functions-use-numbers-analogously.ss rename to Task/First-class-functions-Use-numbers-analogously/Scheme/first-class-functions-use-numbers-analogously.scm diff --git a/Task/First-class-functions/Ada/first-class-functions.ada b/Task/First-class-functions/Ada/first-class-functions.adb similarity index 100% rename from Task/First-class-functions/Ada/first-class-functions.ada rename to Task/First-class-functions/Ada/first-class-functions.adb diff --git a/Task/First-class-functions/Crystal/first-class-functions-1.cr b/Task/First-class-functions/Crystal/first-class-functions-1.cr new file mode 100644 index 0000000000..7d6593bb69 --- /dev/null +++ b/Task/First-class-functions/Crystal/first-class-functions-1.cr @@ -0,0 +1 @@ +->Math.sin(Float64) diff --git a/Task/First-class-functions/Crystal/first-class-functions-2.cr b/Task/First-class-functions/Crystal/first-class-functions-2.cr new file mode 100644 index 0000000000..3b82e7a930 --- /dev/null +++ b/Task/First-class-functions/Crystal/first-class-functions-2.cr @@ -0,0 +1 @@ +->(n : Float64) { Math.sin(n) } diff --git a/Task/First-class-functions/Crystal/first-class-functions-3.cr b/Task/First-class-functions/Crystal/first-class-functions-3.cr new file mode 100644 index 0000000000..8d6dfeceb0 --- /dev/null +++ b/Task/First-class-functions/Crystal/first-class-functions-3.cr @@ -0,0 +1,20 @@ +def cube (n) + n*n*n +end + +add1 = ->(n : Float64) { n + 1 } +sub1 = ->(n : Float64) { n - 1 } + +a = [ ->Math.sin(Float64), ->Math.cos(Float64), ->cube(Float64), add1 ] +b = [ ->Math.asin(Float64), ->Math.acos(Float64), ->Math.cbrt(Float64), sub1 ] +s = [ "sin o asin", "cos o acos", "cube o cbrt", "add1 o sub1"] + +def compose (f, g) + ->(n : Float64) { f[ g[n] ] } +end + +composed = a.zip(b).map {|(f, g)| compose(f, g) } + +composed.each_with_index do |f, i| + puts "(#{s[i]})(0.5) = #{ f[0.5] }" +end diff --git a/Task/First-class-functions/Delphi/first-class-functions.delphi b/Task/First-class-functions/Delphi/first-class-functions.pas similarity index 100% rename from Task/First-class-functions/Delphi/first-class-functions.delphi rename to Task/First-class-functions/Delphi/first-class-functions.pas diff --git a/Task/First-class-functions/Elena/first-class-functions.elena b/Task/First-class-functions/Elena/first-class-functions.elena index baa145697e..67f287ebe2 100644 --- a/Task/First-class-functions/Elena/first-class-functions.elena +++ b/Task/First-class-functions/Elena/first-class-functions.elena @@ -9,11 +9,11 @@ extension op = f(g(self)); } -public program() +public Program() { var fs := new object[]{ mssgconst sin[1], mssgconst cos[1], (x => power(x, 3.0r)) }; 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-class-functions/Elixir/first-class-functions.elixir b/Task/First-class-functions/Elixir/first-class-functions.ex similarity index 100% rename from Task/First-class-functions/Elixir/first-class-functions.elixir rename to Task/First-class-functions/Elixir/first-class-functions.ex diff --git a/Task/First-class-functions/Julia/first-class-functions.julia b/Task/First-class-functions/Julia/first-class-functions.jl similarity index 100% rename from Task/First-class-functions/Julia/first-class-functions.julia rename to Task/First-class-functions/Julia/first-class-functions.jl diff --git a/Task/First-class-functions/Kotlin/first-class-functions.kotlin b/Task/First-class-functions/Kotlin/first-class-functions.kts similarity index 100% rename from Task/First-class-functions/Kotlin/first-class-functions.kotlin rename to Task/First-class-functions/Kotlin/first-class-functions.kts diff --git a/Task/First-class-functions/Maxima/first-class-functions.maxima b/Task/First-class-functions/Maxima/first-class-functions.maxima index 0f3b0ee18b..5b2d1ff458 100644 --- a/Task/First-class-functions/Maxima/first-class-functions.maxima +++ b/Task/First-class-functions/Maxima/first-class-functions.maxima @@ -2,4 +2,3 @@ a: [sin, cos, lambda([x], x^3)]$ b: [asin, acos, lambda([x], x^(1/3))]$ compose(f, g) := buildq([f, g], lambda([x], f(g(x))))$ map(lambda([fun], fun(x)), map(compose, a, b)); -[x, x, x] diff --git a/Task/First-class-functions/OCaml/first-class-functions.ocaml b/Task/First-class-functions/OCaml/first-class-functions.ml similarity index 100% rename from Task/First-class-functions/OCaml/first-class-functions.ocaml rename to Task/First-class-functions/OCaml/first-class-functions.ml diff --git a/Task/First-class-functions/PascalABC.NET/first-class-functions.pas b/Task/First-class-functions/PascalABC.NET/first-class-functions.pas new file mode 100644 index 0000000000..091decbbb2 --- /dev/null +++ b/Task/First-class-functions/PascalABC.NET/first-class-functions.pas @@ -0,0 +1,15 @@ +function Cube(x: real) := x**3; +function CubeRoot(x: real) := x**(1/3); + +function Composition(f1,f2: T -> T): T -> T := x -> f1(f2(x)); + +begin + var A := Arr(Sin,Cos,Cube); + var B := Arr(ArcSin,ArcCos,CubeRoot); + for var i:=0 to A.Length-1 do + Println(Composition(A[i],B[i])(0.5)); + + // Build-in composition f1 * f2 + foreach var (f1,f2) in A.Zip(B) do + Println((f1 * f2)(0.5)); +end. diff --git a/Task/First-class-functions/Phix/first-class-functions.phix b/Task/First-class-functions/Phix/first-class-functions.phix index 6fe2a63ae3..b422dc259e 100644 --- a/Task/First-class-functions/Phix/first-class-functions.phix +++ b/Task/First-class-functions/Phix/first-class-functions.phix @@ -1,27 +1,25 @@ -(phixonline)--> - sequence ctable = {} +sequence ctable = {} - function compose(integer f, g) - ctable = append(ctable,{f,g}) - integer cdx = length(ctable) - return cdx - end function +function compose(integer f, g) + ctable = append(ctable,{f,g}) + integer cdx = length(ctable) + return cdx +end function - function call_composite(integer cdx, atom x) - integer {f,g} = ctable[cdx] - return f(g(x)) - end function +function call_composite(integer cdx, atom x) + integer {f,g} = ctable[cdx] + return f(g(x)) +end function - function plus1(atom x) - return x+1 - end function +function plus1(atom x) + return x+1 +end function - function halve(atom x) - return x/2 - end function +function halve(atom x) + return x/2 +end function - constant m = compose(halve,plus1) +constant m = compose(halve,plus1) - ?call_composite(m,1) -- displays 1 - ?call_composite(m,4) -- displays 2.5 - - with javascript_semantics - function p(integer L, n) - atom logof2 = log10(2) - integer places = trunc(log10(L)), - nfound = 0, i = 1 - while true do - atom a = i * logof2, - b = trunc(power(10,a-trunc(a)+places)) - if L == b then - nfound += 1 - if nfound == n then exit end if - end if - i += 1 - end while - return i - end function +with javascript_semantics +function p(integer L, n) + atom logof2 = log10(2) + integer places = trunc(log10(L)), + nfound = 0, i = 1 + while true do + atom a = i * logof2, + b = trunc(power(10,a-trunc(a)+places)) + if L == b then + nfound += 1 + if nfound == n then exit end if + end if + i += 1 + end while + return i +end function - constant tests = {{12, 1}, {12, 2}, {123, 45}, {123, 12345}, {123, 678910}} - include ordinal.e - include mpfr.e - mpz z = mpz_init() - atom t0 = time() - for i=1 to length(tests)-(2*(platform()=JS)) do - integer {L,n} = tests[i], pln = p(L,n) - mpz_ui_pow_ui(z,2,pln) - integer digits = mpz_sizeinbase(z,10) - string st = iff(digits>2e6?sprintf("%,d digits",digits): - shorten(mpz_get_str(z),"digits",5)) - printf(1,"The %d%s power of 2 that starts with %d is %d [i.e. %s]\n",{n,ord(n),L,pln,st}) - end for - ?elapsed(time()-t0) - - with javascript_semantics - sequence m31 = {"January",0,"March",0,"May",0,"July","August",0,"October",0,"December"} - integer y,m, - nmonths = 0 - string months - sequence res = {}, - none = {} +with javascript_semantics +sequence m31 = {"January",0,"March",0,"May",0,"July","August",0,"October",0,"December"} +integer y,m, + nmonths = 0 +string months +sequence res = {}, + none = {} - for y=1900 to 2100 do - months = "" - for m=1 to 12 do - if string(m31[m]) - and day_of_week(y,m,1,true)="Friday" then - if length(months)!=0 then months &= ", " end if - months &= m31[m] - nmonths += 1 - end if - end for - if length(months)=0 then - none = append(none,y) - else - res = append(res,sprintf("%d : %s\n",{y,months})) - end if - end for +for y=1900 to 2100 do + months = "" + for m=1 to 12 do + if string(m31[m]) + and day_of_week(y,m,1,true)="Friday" then + if length(months)!=0 then months &= ", " end if + months &= m31[m] + nmonths += 1 + end if + end for + if length(months)=0 then + none = append(none,y) + else + res = append(res,sprintf("%d : %s\n",{y,months})) + end if +end for - printf(1,"Found %d months with five full weekends\n",nmonths) - res[6..-6] = {" ...\n"} - puts(1,join(res,"")) - printf(1,"Found %d years with no month having 5 weekends:\n",{length(none)}) - none[6..-6] = {".."} - ?none - + ?flatten({{1},2,{{3,4},5},{{{}}},{{{6}}},7,8,{}}) + [ ) + + [ [] swap witheach [ not join ] ] is invert ( [ --> [ ) + + [ 2dup peek invert unrot poke ] is fliprow ( [ n --> [ ) + + [ dip transpose fliprow transpose ] is flipcolumn ( [ n --> [ ) + + [ dup + [ dup size dup * times + [ dup size random + 2 random iff + fliprow + else flipcolumn ] + 2dup != until ] + nip ] is mix ( [ --> [ ) + + [ say " " + dup size times + [ sp i^ char a + emit ] + witheach + [ cr sp i^ echo say ":" + witheach + [ sp echo ] ] ] is display ( [ --> ) + + [ cr $ "a..., or 0...: " + input $ "." join + trim 0 peek lower + 2dup char a rot over + + within iff + [ nip char a - + ' flipcolumn ] + done + 2dup char 0 rot over + + within iff + [ nip char 0 - + ' fliprow ] + done + drop again ] is getmove ( n --> n x ) + + [ 0 temp put + makeboard + dup mix + [ say "Moves: " + temp share echo cr + 1 temp tally + 2dup swap + say "Target" cr + display cr cr + say "Current" cr + display cr + dup size getmove do cr + 2dup = until ] + 2drop + temp take + say "Moves taken: " echo ] is flipbits ( n --> ) diff --git a/Task/Flipping-bits-game/R/flipping-bits-game.r b/Task/Flipping-bits-game/R/flipping-bits-game.r new file mode 100644 index 0000000000..bedaae8f59 --- /dev/null +++ b/Task/Flipping-bits-game/R/flipping-bits-game.r @@ -0,0 +1,59 @@ +gen_board <- function(n) matrix(data=sample(c(0,1), n^2, replace=TRUE), + nrow=n, + ncol=n, + dimnames=list(1:n, letters[1:n])) + +fliprow <- function(mat, n){ + mat[n,] <- !mat[n,] + return(mat) +} + +flipcol <- function(mat, n){ + mat[,n] <- !mat[,n] + return(mat) +} + +bits_game <- function(){ + n <- as.numeric(readline(prompt="Input board size: ")) + board_final <- gen_board(n) + repeat{ + #Generate a list of between 10 and 15 random moves + num_moves <- sample(10:15, 1) + flip_args <- sample(1:n, num_moves, replace=TRUE) + flip_fns <- sample(list(fliprow, flipcol), num_moves, replace=TRUE) + gen_move <- function(k){ + function(mat) flip_fns[[k]](mat, flip_args[k]) + } + rand_moves <- sapply(1:num_moves, gen_move) + #Now apply them to the final board to generate the initial position + board_initial <- Reduce(function(x, f) f(x), rand_moves, init=board_final) + #Make sure initial and final positions aren't the same + if(!identical(board_initial, board_final)) break + } + #Time to start the game! + cat("\nYour starting position is:\n") + print(board_initial) + cat("\nYour target position is:\n") + print(board_final) + turns <- 1 + while(!identical(board_initial,board_final)){ + cat("\nTurn ", turns, ":\n", sep="") + move <- readline(prompt="Enter a row or column name to flip it: ") + if(move %in% 1:n){ + board_initial <- fliprow(board_initial, move) + cat("\nThe position is now:\n") + print(board_initial) + turns <- turns+1 + } + else if(move %in% letters[1:n]){ + board_initial <- flipcol(board_initial, which(letters==move)) + cat("\nThe position is now:\n") + print(board_initial) + turns <- turns+1 + } + else cat("\nThat's not a valid move. Try again!\n") + } + cat("\nWell done! You finished in", turns-1, "move(s).\n") +} + +bits_game() diff --git a/Task/Flipping-bits-game/Rust/flipping-bits-game.rust b/Task/Flipping-bits-game/Rust/flipping-bits-game.rs similarity index 100% rename from Task/Flipping-bits-game/Rust/flipping-bits-game.rust rename to Task/Flipping-bits-game/Rust/flipping-bits-game.rs diff --git a/Task/Flipping-bits-game/Uiua/flipping-bits-game.uiua b/Task/Flipping-bits-game/Uiua/flipping-bits-game.uiua new file mode 100644 index 0000000000..4b550f5dcb --- /dev/null +++ b/Task/Flipping-bits-game/Uiua/flipping-bits-game.uiua @@ -0,0 +1,18 @@ +# Could use `path`, but this is easily solved without it. +# ⊢path(⊂⊃(≡Fr|≡Fc)⇡Size¤|=0Dist|÷Size Dist) Shuffle T + +Size ← 8 +T ← ↯Size_Size 0 # Simple target setup. +Fr ← ⍜⊡¬⊙ # Flip a row. +Fc ← ⍜⊙⍉Fr # Flip a col. +Shuffle ← ⍥(⨬(Fr|Fc)<0.5⚂ ⌊×⚂Size)××2.Size # Apply random changes. +Dist ← /+/+⌵-T # Number of wrong cells. +⟜[∘]Shuffle T # Shuffle and start a copy for the output. +◌⍢( + ⊂⊃(≡Fr|≡Fc)⇡Size¤ # All neighbours. + ⊚=/↧.≡Dist. # Find min dist, get indices that give that. + ⊡⊢ # Pick first one. + ⊙⊂. # Save a copy of the new state. +| ≠0Dist # Repeat until found target. +) +⟜($"_ steps."⧻)⇌ diff --git a/Task/Flipping-bits-game/V-(Vlang)/flipping-bits-game.v b/Task/Flipping-bits-game/V-(Vlang)/flipping-bits-game.v new file mode 100644 index 0000000000..5f31955f5d --- /dev/null +++ b/Task/Flipping-bits-game/V-(Vlang)/flipping-bits-game.v @@ -0,0 +1,110 @@ +import rand +import os + +const size = 3 + +struct Board { + mut: + target [][]int + board [][]int +} + +fn new_board() Board { + mut brd := Board{ + target: [][]int{len: size, init: []int{len: size}}, + board: [][]int{len: size, init: []int{len: size}}, + } + for ial in 0 .. size { + for jal in 0 .. size { + brd.target[ial][jal] = rand.intn(2) or {panic("No Random!")} + } + } + return brd +} + +fn (mut brd Board) flip_row(rir int) { + for cal in 0 .. size { + brd.board[rir][cal] = if brd.board[rir][cal] == 0 { 1 } else { 0 } + } +} + +fn (mut brd Board) flip_col(cir int) { + for ral in 0 .. size { + brd.board[ral][cir] = if brd.board[ral][cir] == 0 { 1 } else { 0 } + } +} + +fn (mut brd Board) init_board() { + for ial in 0 .. size { + for jal in 0 .. size { + brd.board[ial][jal] = brd.target[ial][jal] + } + } + for _ in 0 .. 9 { + rc := rand.intn(2) or {panic("No Random!")} + if rc == 0 { brd.flip_row(rand.intn(size) or {panic("No Random!")}) } + else { brd.flip_col(rand.intn(size) or {panic("No Random!")}) } + } +} + +fn print_board(label string, a [][]int) { + println("$label:") + println(" | a b c") + println("---------") + for ral in 0 .. size { + print("${ral + 1} |") + for cal in 0 .. size { + print(" ${a[ral][cal]}") + } + println("") + } + println("") +} + +fn (brd Board) game_over() bool { + for ral in 0 .. size { + for cal in 0 .. size { + if brd.board[ral][cal] != brd.target[ral][cal] { return false } + } + } + return true +} + +fn main() { + mut brd := new_board() + mut flips, mut nir := 0, -1 + mut is_row := true + // initialize board and ensure it differs from target + for { + brd.init_board() + if !brd.game_over() { break } + } + print_board("TARGET", brd.target) + print_board("OPENING BOARD", brd.board) + for { + is_row = true + nir = -1 + for nir == -1 { + input := os.input("Enter row number or column letter to be flipped: ").str() + if input.len == 0 { continue } + ch := input[0].ascii_str().to_lower() + if ch !in ["1", "2", "3", "a", "brd", "c"] { + println("Must be 1, 2, 3, a, brd or c") + continue + } + if ch in ["1", "2", "3"] { nir = int(ch[0]) - int(`1`) } + else { + is_row = false + nir = int(ch[0]) - int(`a`) + } + } + flips++ + if is_row { brd.flip_row(nir) } + else { brd.flip_col(nir) } + plural := if flips == 1 { "" } else { "S" } + print_board("\nBOARD AFTER $flips FLIP$plural", brd.board) + if brd.game_over() { break } + } + plural := if flips == 1 { "" } else { "s" } + println("You\'ve succeeded in $flips flip$plural") +} diff --git a/Task/Flow-control-structures/Ada/flow-control-structures-1.ada b/Task/Flow-control-structures/Ada/flow-control-structures-1.adb similarity index 100% rename from Task/Flow-control-structures/Ada/flow-control-structures-1.ada rename to Task/Flow-control-structures/Ada/flow-control-structures-1.adb diff --git a/Task/Flow-control-structures/Ada/flow-control-structures-2.ada b/Task/Flow-control-structures/Ada/flow-control-structures-2.ada deleted file mode 100644 index 158400ca3d..0000000000 --- a/Task/Flow-control-structures/Ada/flow-control-structures-2.ada +++ /dev/null @@ -1,8 +0,0 @@ -Outer: -loop - -- do something - loop - -- do something else - exit Outer; -- exits both the inner and outer loops - end loop; -end loop Outer; diff --git a/Task/Flow-control-structures/Ada/flow-control-structures-2.adb b/Task/Flow-control-structures/Ada/flow-control-structures-2.adb new file mode 100644 index 0000000000..b793ba8f93 --- /dev/null +++ b/Task/Flow-control-structures/Ada/flow-control-structures-2.adb @@ -0,0 +1,10 @@ +Outer: +loop + -- do something + loop + if Finished then + exit Outer; -- exits both the inner and outer loops + end if; + -- do something else + end loop; +end loop Outer; diff --git a/Task/Flow-control-structures/Ada/flow-control-structures-3.adb b/Task/Flow-control-structures/Ada/flow-control-structures-3.adb new file mode 100644 index 0000000000..ed66f3714c --- /dev/null +++ b/Task/Flow-control-structures/Ada/flow-control-structures-3.adb @@ -0,0 +1,8 @@ +Outer: +loop + -- do something + loop + exit Outer when Finished; + -- do something else + end loop; +end loop Outer; diff --git a/Task/Flow-control-structures/Ada/flow-control-structures-4.adb b/Task/Flow-control-structures/Ada/flow-control-structures-4.adb new file mode 100644 index 0000000000..ef06de0b59 --- /dev/null +++ b/Task/Flow-control-structures/Ada/flow-control-structures-4.adb @@ -0,0 +1,8 @@ +procedure Foo is +begin + -- do something + if Nothing_More_To_Do then + return; + end if; + -- do more +end Foo; diff --git a/Task/Flow-control-structures/Ada/flow-control-structures-3.ada b/Task/Flow-control-structures/Ada/flow-control-structures-5.adb similarity index 100% rename from Task/Flow-control-structures/Ada/flow-control-structures-3.ada rename to Task/Flow-control-structures/Ada/flow-control-structures-5.adb diff --git a/Task/Flow-control-structures/COBOL/flow-control-structures-1.cobol b/Task/Flow-control-structures/COBOL/flow-control-structures-1.cob similarity index 100% rename from Task/Flow-control-structures/COBOL/flow-control-structures-1.cobol rename to Task/Flow-control-structures/COBOL/flow-control-structures-1.cob diff --git a/Task/Flow-control-structures/COBOL/flow-control-structures-2.cobol b/Task/Flow-control-structures/COBOL/flow-control-structures-2.cob similarity index 100% rename from Task/Flow-control-structures/COBOL/flow-control-structures-2.cobol rename to Task/Flow-control-structures/COBOL/flow-control-structures-2.cob diff --git a/Task/Flow-control-structures/COBOL/flow-control-structures-3.cobol b/Task/Flow-control-structures/COBOL/flow-control-structures-3.cob similarity index 100% rename from Task/Flow-control-structures/COBOL/flow-control-structures-3.cobol rename to Task/Flow-control-structures/COBOL/flow-control-structures-3.cob diff --git a/Task/Flow-control-structures/COBOL/flow-control-structures-4.cobol b/Task/Flow-control-structures/COBOL/flow-control-structures-4.cob similarity index 100% rename from Task/Flow-control-structures/COBOL/flow-control-structures-4.cobol rename to Task/Flow-control-structures/COBOL/flow-control-structures-4.cob diff --git a/Task/Flow-control-structures/COBOL/flow-control-structures-5.cobol b/Task/Flow-control-structures/COBOL/flow-control-structures-5.cob similarity index 100% rename from Task/Flow-control-structures/COBOL/flow-control-structures-5.cobol rename to Task/Flow-control-structures/COBOL/flow-control-structures-5.cob diff --git a/Task/Flow-control-structures/FutureBasic/flow-control-structures.basic b/Task/Flow-control-structures/FutureBasic/flow-control-structures.basic new file mode 100644 index 0000000000..e1bdbc5e11 --- /dev/null +++ b/Task/Flow-control-structures/FutureBasic/flow-control-structures.basic @@ -0,0 +1,21 @@ +override _allowSubroutines = _true +#build Optimization _buildOptimizationNone + +print "First line." +gosub "sub1" +print "Fifth line." + +HandleEvents + +"sub1" +print "Second line." +gosub "sub2" +print "Fourth line." +goto "skip" +print "we don't get here" +"skip" +return + +"sub2" +print "Third line." +return diff --git a/Task/Flow-control-structures/Julia/flow-control-structures.julia b/Task/Flow-control-structures/Julia/flow-control-structures.jl similarity index 100% rename from Task/Flow-control-structures/Julia/flow-control-structures.julia rename to Task/Flow-control-structures/Julia/flow-control-structures.jl diff --git a/Task/Flow-control-structures/Kotlin/flow-control-structures.kotlin b/Task/Flow-control-structures/Kotlin/flow-control-structures.kts similarity index 100% rename from Task/Flow-control-structures/Kotlin/flow-control-structures.kotlin rename to Task/Flow-control-structures/Kotlin/flow-control-structures.kts diff --git a/Task/Flow-control-structures/OCaml/flow-control-structures.ocaml b/Task/Flow-control-structures/OCaml/flow-control-structures.ml similarity index 100% rename from Task/Flow-control-structures/OCaml/flow-control-structures.ocaml rename to Task/Flow-control-structures/OCaml/flow-control-structures.ml diff --git a/Task/Flow-control-structures/REBOL/flow-control-structures.rebol b/Task/Flow-control-structures/Rebol/flow-control-structures.rebol similarity index 99% rename from Task/Flow-control-structures/REBOL/flow-control-structures.rebol rename to Task/Flow-control-structures/Rebol/flow-control-structures.rebol index 27a2bbcf83..2530b2f609 100644 --- a/Task/Flow-control-structures/REBOL/flow-control-structures.rebol +++ b/Task/Flow-control-structures/Rebol/flow-control-structures.rebol @@ -1,4 +1,4 @@ -REBOL [ +Rebol [ Title: "Flow Control" URL: http://rosettacode.org/wiki/Flow_Control_Structures ] diff --git a/Task/Flow-control-structures/Uxntal/flow-control-structures.uxnatl b/Task/Flow-control-structures/Uxntal/flow-control-structures.uxnatl new file mode 100644 index 0000000000..7b135f37f9 --- /dev/null +++ b/Task/Flow-control-structures/Uxntal/flow-control-structures.uxnatl @@ -0,0 +1,24 @@ +|18 @Console/write + +|100 + +example + +BRK + +@example ( x y -- ) + ;start print/str + !&world ( goto &world ) + ;never print/str + &world ( label &world ) + ;end !print/str + +@print/str ( str* -- ) + LDAk .Console/write DEO + INC2 LDAk ?&str + POP2 + JMP2r + +@start "Hello, 2000 +@never "Never 20 "printed. 0a00 +@end "World! 0a00 diff --git a/Task/Floyd-Warshall-algorithm/ALGOL-68/floyd-warshall-algorithm.alg b/Task/Floyd-Warshall-algorithm/ALGOL-68/floyd-warshall-algorithm.alg index 1b23cfac2f..68ed0e7149 100644 --- a/Task/Floyd-Warshall-algorithm/ALGOL-68/floyd-warshall-algorithm.alg +++ b/Task/Floyd-Warshall-algorithm/ALGOL-68/floyd-warshall-algorithm.alg @@ -22,7 +22,7 @@ BEGIN # Floyd-Warshall algorithm - translated from the Lua sample # ) ); WHILE u := nxt[ u - 1, v - 1 ]; - print( ( " -> " +whole( u, 0 ) ) ); + print( ( " -> " + whole( u, 0 ) ) ); u /= v DO SKIP OD; print( ( newline ) ) @@ -34,12 +34,12 @@ BEGIN # Floyd-Warshall algorithm - translated from the Lua sample # PROC floyd warshall = ( [,]INT weights, INT num vertices )VOID: BEGIN - REAL infinity = max real; + REAL infinite = 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 + dist[ i, j ] := infinite OD OD; @@ -59,7 +59,7 @@ BEGIN # Floyd-Warshall algorithm - translated from the Lua sample # 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 ] /= infinite AND dist[ k, j ] /= infinite 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 ] @@ -71,14 +71,14 @@ BEGIN # Floyd-Warshall algorithm - translated from the Lua sample # 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 ) - + BEGIN + [,]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 END diff --git a/Task/Floyd-Warshall-algorithm/Ada/floyd-warshall-algorithm.ada b/Task/Floyd-Warshall-algorithm/Ada/floyd-warshall-algorithm.adb similarity index 100% rename from Task/Floyd-Warshall-algorithm/Ada/floyd-warshall-algorithm.ada rename to Task/Floyd-Warshall-algorithm/Ada/floyd-warshall-algorithm.adb diff --git a/Task/Floyd-Warshall-algorithm/COBOL/floyd-warshall-algorithm.cob b/Task/Floyd-Warshall-algorithm/COBOL/floyd-warshall-algorithm.cob new file mode 100644 index 0000000000..47f4420154 --- /dev/null +++ b/Task/Floyd-Warshall-algorithm/COBOL/floyd-warshall-algorithm.cob @@ -0,0 +1,183 @@ +IDENTIFICATION DIVISION. + PROGRAM-ID. FLOYD-WARSHALL. + + DATA DIVISION. + WORKING-STORAGE SECTION. + + 01 WS-NUM-VERTICES PIC 9 VALUE 4. + 01 WS-NUM-WEIGHTS PIC 9 VALUE 5. + 01 WS-INFINITY PIC 9(7)V9(2) VALUE 9999999.99. + + 01 WS-WEIGHTS. + 05 WS-W OCCURS 5 TIMES. + 10 WS-FROM PIC 9. + 10 WS-TO PIC 9. + 10 WS-COST PIC S9(3) SIGN LEADING SEPARATE. + + 01 WS-DIST. + 05 WS-D OCCURS 4 TIMES. + 10 WS-D-COL OCCURS 4 TIMES. + 15 WS-DIST-VAL PIC S9(7)V9(2). + + 01 WS-NEXT. + 05 WS-N OCCURS 4 TIMES. + 10 WS-N-COL OCCURS 4 TIMES. + 15 WS-NEXT-VAL PIC 9. + + 01 WS-I PIC 9. + 01 WS-J PIC 9. + 01 WS-K PIC 9. + 01 WS-U PIC 9. + 01 WS-V PIC 9. + 01 WS-IDX PIC 9. + 01 WS-TEMP-SUM PIC S9(7)V9(2). + 01 WS-DIST-IJ PIC S9(7)V9(2). + 01 WS-DIST-IK PIC S9(7)V9(2). + 01 WS-DIST-KJ PIC S9(7)V9(2). + + *> Path and display working fields + 01 WS-PATH PIC X(200). + 01 WS-PATH-TEMP PIC X(200). + 01 WS-DIST-INT PIC S9(5). + 01 WS-DIST-EDIT PIC -(4)9. + 01 WS-DIST-TRIM PIC X(6). + 01 WS-OUTPUT-LINE PIC X(80). + 01 WS-NODE-CHAR PIC 9. + + PROCEDURE DIVISION. + MAIN-PARA. + MOVE 1 TO WS-FROM(1) + MOVE 3 TO WS-TO(1) + MOVE -2 TO WS-COST(1) + + MOVE 2 TO WS-FROM(2) + MOVE 1 TO WS-TO(2) + MOVE 4 TO WS-COST(2) + + MOVE 2 TO WS-FROM(3) + MOVE 3 TO WS-TO(3) + MOVE 3 TO WS-COST(3) + + MOVE 3 TO WS-FROM(4) + MOVE 4 TO WS-TO(4) + MOVE 2 TO WS-COST(4) + + MOVE 4 TO WS-FROM(5) + MOVE 2 TO WS-TO(5) + MOVE -1 TO WS-COST(5) + + PERFORM INIT-DIST + PERFORM INIT-NEXT + PERFORM FLOYD-WARSHALL + PERFORM PRINT-RESULT + STOP RUN. + + INIT-DIST. + PERFORM VARYING WS-I FROM 1 BY 1 + UNTIL WS-I > WS-NUM-VERTICES + PERFORM VARYING WS-J FROM 1 BY 1 + UNTIL WS-J > WS-NUM-VERTICES + MOVE WS-INFINITY TO WS-DIST-VAL(WS-I, WS-J) + END-PERFORM + END-PERFORM + PERFORM VARYING WS-IDX FROM 1 BY 1 + UNTIL WS-IDX > WS-NUM-WEIGHTS + MOVE WS-FROM(WS-IDX) TO WS-I + MOVE WS-TO(WS-IDX) TO WS-J + MOVE WS-COST(WS-IDX) TO WS-DIST-VAL(WS-I, WS-J) + END-PERFORM. + + INIT-NEXT. + PERFORM VARYING WS-I FROM 1 BY 1 + UNTIL WS-I > WS-NUM-VERTICES + PERFORM VARYING WS-J FROM 1 BY 1 + UNTIL WS-J > WS-NUM-VERTICES + IF WS-I NOT EQUAL WS-J + MOVE WS-J TO WS-NEXT-VAL(WS-I, WS-J) + ELSE + MOVE 0 TO WS-NEXT-VAL(WS-I, WS-J) + END-IF + END-PERFORM + END-PERFORM. + + FLOYD-WARSHALL. + PERFORM VARYING WS-K FROM 1 BY 1 + UNTIL WS-K > WS-NUM-VERTICES + PERFORM VARYING WS-I FROM 1 BY 1 + UNTIL WS-I > WS-NUM-VERTICES + PERFORM VARYING WS-J FROM 1 BY 1 + UNTIL WS-J > WS-NUM-VERTICES + MOVE WS-DIST-VAL(WS-I, WS-K) TO WS-DIST-IK + MOVE WS-DIST-VAL(WS-K, WS-J) TO WS-DIST-KJ + MOVE WS-DIST-VAL(WS-I, WS-J) TO WS-DIST-IJ + IF WS-DIST-IK < WS-INFINITY AND + WS-DIST-KJ < WS-INFINITY + COMPUTE WS-TEMP-SUM = + WS-DIST-IK + WS-DIST-KJ + IF WS-TEMP-SUM < WS-DIST-IJ + MOVE WS-TEMP-SUM + TO WS-DIST-VAL(WS-I, WS-J) + MOVE WS-NEXT-VAL(WS-I, WS-K) + TO WS-NEXT-VAL(WS-I, WS-J) + END-IF + END-IF + END-PERFORM + END-PERFORM + END-PERFORM. + + PRINT-RESULT. + DISPLAY "pair dist path" + PERFORM VARYING WS-I FROM 1 BY 1 + UNTIL WS-I > WS-NUM-VERTICES + PERFORM VARYING WS-J FROM 1 BY 1 + UNTIL WS-J > WS-NUM-VERTICES + IF WS-I NOT EQUAL WS-J + + *> Set up source and destination + MOVE WS-I TO WS-U + MOVE WS-J TO WS-V + + *> Seed path with just the source node + MOVE SPACES TO WS-PATH + MOVE WS-I TO WS-NODE-CHAR + MOVE WS-NODE-CHAR TO WS-PATH(1:1) + + *> Walk next-hop until we reach destination + PERFORM UNTIL WS-U = WS-V + MOVE WS-NEXT-VAL(WS-U, WS-V) TO WS-U + MOVE WS-U TO WS-NODE-CHAR + MOVE SPACES TO WS-PATH-TEMP + STRING + FUNCTION TRIM(WS-PATH TRAILING) + DELIMITED SIZE + " -> " DELIMITED SIZE + WS-NODE-CHAR DELIMITED SIZE + INTO WS-PATH-TEMP + MOVE WS-PATH-TEMP TO WS-PATH + END-PERFORM + + *> Format distance: move to integer then edit picture + *> to get clean signed number without leading zeros + COMPUTE WS-DIST-INT = + WS-DIST-VAL(WS-I, WS-J) + MOVE WS-DIST-INT TO WS-DIST-EDIT + MOVE FUNCTION TRIM(WS-DIST-EDIT LEADING) + TO WS-DIST-TRIM + + *> Assemble and print output line + MOVE SPACES TO WS-OUTPUT-LINE + STRING + WS-I DELIMITED SIZE + " -> " DELIMITED SIZE + WS-J DELIMITED SIZE + " " DELIMITED SIZE + FUNCTION TRIM(WS-DIST-TRIM LEADING) + DELIMITED SIZE + " " DELIMITED SIZE + FUNCTION TRIM(WS-PATH TRAILING) + DELIMITED SIZE + INTO WS-OUTPUT-LINE + DISPLAY FUNCTION TRIM(WS-OUTPUT-LINE TRAILING) + END-IF + END-PERFORM + END-PERFORM. diff --git a/Task/Floyd-Warshall-algorithm/Dart/floyd-warshall-algorithm.dart b/Task/Floyd-Warshall-algorithm/Dart/floyd-warshall-algorithm.dart new file mode 100644 index 0000000000..287b9a495f --- /dev/null +++ b/Task/Floyd-Warshall-algorithm/Dart/floyd-warshall-algorithm.dart @@ -0,0 +1,54 @@ +void main() { + List> weights = [ + [1, 3, -2], + [2, 1, 4], + [2, 3, 3], + [3, 4, 2], + [4, 2, -1] + ]; + int numVertices = 4; + floydWarshall(weights, numVertices); +} + +void floydWarshall(List> weights, int numVertices) { + List> dist = List.generate( + numVertices, (_) => List.filled(numVertices, double.infinity)); + + for (var w in weights) { + dist[w[0] - 1][w[1] - 1] = w[2].toDouble(); + } + + List> next = List.generate( + numVertices, (i) => List.generate(numVertices, (j) => j != i ? j + 1 : 0)); + + for (int k = 0; k < numVertices; k++) { + for (int i = 0; i < numVertices; i++) { + for (int j = 0; j < numVertices; j++) { + 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); +} + +void printResult(List> dist, List> next) { + print("pair dist path"); + for (int i = 0; i < next.length; i++) { + for (int j = 0; j < next.length; j++) { + if (i != j) { + int u = i + 1; + int v = j + 1; + String path = "$u -> $v ${dist[i][j].toInt()} $u"; + do { + u = next[u - 1][v - 1]; + path += " -> $u"; + } while (u != v); + print(path); + } + } + } +} diff --git a/Task/Floyd-Warshall-algorithm/EasyLang/floyd-warshall-algorithm.easy b/Task/Floyd-Warshall-algorithm/EasyLang/floyd-warshall-algorithm.easy new file mode 100644 index 0000000000..4d4159674a --- /dev/null +++ b/Task/Floyd-Warshall-algorithm/EasyLang/floyd-warshall-algorithm.easy @@ -0,0 +1,24 @@ +proc floydwarshall w[][] n . + for i to n + con[][] &= [ ] + for j to n : con[i][] &= 1 / 0 + . + for i to len w[][] + con[w[i][1]][w[i][2]] = w[i][3] + . + for k to n + for i to n + for j to n + con[i][j] = lower con[i][j] (con[i][k] + con[k][j]) + . + . + . + for i to n + for j to n + if i <> j + print i & " -> " & j & " : " & con[i][j] + . + . + . +. +floydwarshall [ [ 1 3 -2 ] [ 2 1 4 ] [ 2 3 3 ] [ 3 4 2 ] [ 4 2 -1 ] ] 4 diff --git a/Task/Floyd-Warshall-algorithm/Elixir/floyd-warshall-algorithm.elixir b/Task/Floyd-Warshall-algorithm/Elixir/floyd-warshall-algorithm.ex similarity index 100% rename from Task/Floyd-Warshall-algorithm/Elixir/floyd-warshall-algorithm.elixir rename to Task/Floyd-Warshall-algorithm/Elixir/floyd-warshall-algorithm.ex diff --git a/Task/Floyd-Warshall-algorithm/Erlang/floyd-warshall-algorithm.erl b/Task/Floyd-Warshall-algorithm/Erlang/floyd-warshall-algorithm.erl new file mode 100644 index 0000000000..9ff0e024e4 --- /dev/null +++ b/Task/Floyd-Warshall-algorithm/Erlang/floyd-warshall-algorithm.erl @@ -0,0 +1,54 @@ +-module(floyd_warshall). +-export([main/2]). + + +main(N, Edge) -> + {Dist, Next} = setup(N, Edge), + {Dist2, Next2} = shortest_path(N, Dist, Next), + print(N, Dist2, Next2). + +setup(N, Edge) -> + Big = 1.0e300, + Dist = maps:from_list([{{I,J}, case I == J of true -> 0; false -> Big end} + || I <- lists:seq(1, N), J <- lists:seq(1, N)]), + Next = maps:from_list([{{I,J}, nil} + || I <- lists:seq(1, N), J <- lists:seq(1, N)]), + lists:foldl(fun({U, V, W}, {Dst, Nxt}) -> + {maps:put({U, V}, W, Dst), maps:put({U, V}, V, Nxt)} + end, {Dist, Next}, Edge). + +shortest_path(N, Dist, Next) -> + Combinations = [{K, I, J} || K <- lists:seq(1, N), + I <- lists:seq(1, N), + J <- lists:seq(1, N)], + lists:foldl(fun({K, I, J}, {Dst, Nxt}) -> + IJ_Dist = maps:get({I, J}, Dst), + IK_Dist = maps:get({I, K}, Dst), + KJ_Dist = maps:get({K, J}, Dst), + case IJ_Dist > IK_Dist + KJ_Dist of + true -> + NewDist = maps:put({I, J}, IK_Dist + KJ_Dist, Dst), + NewNext = maps:put({I, J}, maps:get({I, K}, Nxt), Nxt), + {NewDist, NewNext}; + false -> + {Dst, Nxt} + end + end, {Dist, Next}, Combinations). + +print(N, Dist, Next) -> + io:format("pair dist path~n"), + [io:format("~w -> ~w ~4w ~s~n", [I, J, maps:get({I, J}, Dist), path(Next, I, J)]) + || I <- lists:seq(1, N), J <- lists:seq(1, N), I =/= J]. + +path(Next, I, J) -> + PathList = path(Next, I, J, [I]), + string:join([integer_to_list(X) || X <- PathList], " -> "). + +path(_Next, I, I, List) -> + lists:reverse(List); +path(Next, I, J, List) -> + U = maps:get({I, J}, Next), + path(Next, U, J, [U | List]). + +% Usage example: +main(_) -> main(4, [{1, 3, -2}, {2, 1, 4}, {2, 3, 3}, {3, 4, 2}, {4, 2, -1}]). diff --git a/Task/Floyd-Warshall-algorithm/Julia/floyd-warshall-algorithm.julia b/Task/Floyd-Warshall-algorithm/Julia/floyd-warshall-algorithm.jl similarity index 100% rename from Task/Floyd-Warshall-algorithm/Julia/floyd-warshall-algorithm.julia rename to Task/Floyd-Warshall-algorithm/Julia/floyd-warshall-algorithm.jl diff --git a/Task/Floyd-Warshall-algorithm/Kotlin/floyd-warshall-algorithm.kotlin b/Task/Floyd-Warshall-algorithm/Kotlin/floyd-warshall-algorithm.kts similarity index 100% rename from Task/Floyd-Warshall-algorithm/Kotlin/floyd-warshall-algorithm.kotlin rename to Task/Floyd-Warshall-algorithm/Kotlin/floyd-warshall-algorithm.kts diff --git a/Task/Floyd-Warshall-algorithm/OCaml/floyd-warshall-algorithm.ocaml b/Task/Floyd-Warshall-algorithm/OCaml/floyd-warshall-algorithm.ml similarity index 100% rename from Task/Floyd-Warshall-algorithm/OCaml/floyd-warshall-algorithm.ocaml rename to Task/Floyd-Warshall-algorithm/OCaml/floyd-warshall-algorithm.ml diff --git a/Task/Floyd-Warshall-algorithm/Pluto/floyd-warshall-algorithm.pluto b/Task/Floyd-Warshall-algorithm/Pluto/floyd-warshall-algorithm.pluto new file mode 100644 index 0000000000..8f3b213cd2 --- /dev/null +++ b/Task/Floyd-Warshall-algorithm/Pluto/floyd-warshall-algorithm.pluto @@ -0,0 +1,50 @@ +require "table2" + +class floydWarshall + static function do_calcs(weights, nvertices) + local dist = {} + local next = {} + for i = 1, nvertices do + dist[i] = table.rep(nvertices, 1/0) + next[i] = table.rep(nvertices, 1) + for j = 1, nvertices do + if i != j then next[i][j] = j end + end + end + for weights as w do dist[w[1]][w[2]] = w[3] end + for k = 1, nvertices do + for i = 1, nvertices do + for j = 1, nvertices do + if (dist[i][k] + dist[k][j] < dist[i][j]) then + dist[i][j] = dist[i][k] + dist[k][j] + next[i][j] = next[i][k] + end + end + end + end + floydWarshall.print_result(dist, next) + end + + static function print_result(dist, next) + print("pair dist path") + for i = 1, #next do + for j = 1, #next do + if i != j then + local u = i + local v = j + local path = string.format("%d -> %d %2d %s", u, v, math.trunc(dist[i][j]), u) + while true do + u = next[u][v] + path ..= " -> " .. u + if u == v then break end + end + print(path) + end + end + end + end +end + +local weights = { {1, 3, -2}, {2, 1, 4}, {2, 3, 3}, {3, 4, 2}, {4, 2, -1} } +local nvertices = 4 +floydWarshall.do_calcs(weights, nvertices) diff --git a/Task/Floyd-Warshall-algorithm/R/floyd-warshall-algorithm.r b/Task/Floyd-Warshall-algorithm/R/floyd-warshall-algorithm.r new file mode 100644 index 0000000000..e65a241e61 --- /dev/null +++ b/Task/Floyd-Warshall-algorithm/R/floyd-warshall-algorithm.r @@ -0,0 +1,67 @@ +floydWarshall <- function(weights, numVertices) { + # Initialize distance matrix with infinity + dist <- matrix(Inf, nrow = numVertices, ncol = numVertices) + + # Set diagonal elements to zero + diag(dist) <- 0 + + # Fill the distance matrix with the given weights + for (i in 1:nrow(weights)) { + dist[weights[i, 1], weights[i, 2]] <- weights[i, 3] + } + + # Initialize nextNode matrix + nextNode <- matrix(0, nrow = numVertices, ncol = numVertices) + for (i in 1:numVertices) { + for (j in 1:numVertices) { + if (i != j) { + nextNode[i, j] <- j + } + } + } + + # Floyd-Warshall algorithm + for (k in 1:numVertices) { + for (i in 1:numVertices) { + for (j in 1:numVertices) { + if (dist[i, k] + dist[k, j] < dist[i, j]) { + dist[i, j] <- dist[i, k] + dist[k, j] + nextNode[i, j] <- nextNode[i, k] + } + } + } + } + + printResult(dist, nextNode) +} + +printResult <- function(dist, nextNode) { + cat("pair dist path\n") + for (i in 1:nrow(nextNode)) { + for (j in 1:ncol(nextNode)) { + if (i != j) { + u <- i + v <- j + path <- sprintf("%d -> %d %2d %s", i, j, dist[i, j], i) + repeat { + u <- nextNode[u, v] + path <- paste(path, "->", u) + if (u == v) break + } + cat(path, "\n") + } + } + } +} + +# Example usage +weights <- matrix(c( + 1, 3, -2, + 2, 1, 4, + 2, 3, 3, + 3, 4, 2, + 4, 2, -1 +), ncol = 3, byrow = TRUE) + +numVertices <- 4 +floydWarshall(weights, numVertices) diff --git a/Task/Floyd-Warshall-algorithm/Rust/floyd-warshall-algorithm.rust b/Task/Floyd-Warshall-algorithm/Rust/floyd-warshall-algorithm.rs similarity index 100% rename from Task/Floyd-Warshall-algorithm/Rust/floyd-warshall-algorithm.rust rename to Task/Floyd-Warshall-algorithm/Rust/floyd-warshall-algorithm.rs diff --git a/Task/Floyd-Warshall-algorithm/Scheme/floyd-warshall-algorithm.ss b/Task/Floyd-Warshall-algorithm/Scheme/floyd-warshall-algorithm.scm similarity index 100% rename from Task/Floyd-Warshall-algorithm/Scheme/floyd-warshall-algorithm.ss rename to Task/Floyd-Warshall-algorithm/Scheme/floyd-warshall-algorithm.scm diff --git a/Task/Floyd-Warshall-algorithm/Swift/floyd-warshall-algorithm.swift b/Task/Floyd-Warshall-algorithm/Swift/floyd-warshall-algorithm.swift new file mode 100644 index 0000000000..f6f9661f35 --- /dev/null +++ b/Task/Floyd-Warshall-algorithm/Swift/floyd-warshall-algorithm.swift @@ -0,0 +1,51 @@ +func floydWarshall(_ weights: [[Int]], _ numVertices: Int) { + var dist = Array(repeating: Array(repeating: Double.infinity, count: numVertices), count: numVertices) + var next = Array(repeating: Array(repeating: 0, count: numVertices), count: numVertices) + + for weight in weights { + dist[weight[0] - 1][weight[1] - 1] = Double(weight[2]) + } + + for i in 0.. %d %2d %d", U, V, Dist(I,J), U); + repeat U:= Next(U-1, V-1); + Print(" -> %d", U); + until U = V; + Print("\n"); + ]; + ]; + +[Dist:= Reserve(Verts*IntSize); +for I:= 0 to Verts-1 do + [Dist(I):= Reserve(Verts*IntSize); + for J:= 0 to Verts-1 do + Dist(I,J):= \Inf\10000; + ]; +for W:= 0 to Len-1 do + Dist(Weights(W,0)-1, Weights(W,1)-1):= Weights(W,2); +Next:= Reserve(Verts*IntSize); +for I:= 0 to Verts-1 do + [Next(I):= Reserve(Verts*IntSize); + for J:= 0 to Verts-1 do + Next(I,J):= if I=J then 0 else J+1; + ]; +for K:= 0 to Verts-1 do + for I:= 0 to Verts-1 do + for J:= 0 to Verts-1 do + if Dist(I,J) > Dist(I,K) + Dist(K,J) then + [Dist(I,J):= Dist(I,K) + Dist(K,J); + Next(I,J):= Next(I,K); + ]; +PrintResult; +]; + +int Weights; +[Weights:= [ [1, 3, -2], [2, 1, 4], [2, 3, 3], [3, 4, 2], [4, 2, -1] ]; +FloydWarshall(Weights, 5, 4); +] diff --git a/Task/Floyd-Warshall-algorithm/Zig/floyd-warshall-algorithm.zig b/Task/Floyd-Warshall-algorithm/Zig/floyd-warshall-algorithm.zig new file mode 100644 index 0000000000..fe8d6dd20d --- /dev/null +++ b/Task/Floyd-Warshall-algorithm/Zig/floyd-warshall-algorithm.zig @@ -0,0 +1,99 @@ +// floyd_warshall.zig +const std = @import("std"); + +const F64_INF = std.math.inf(f64); + +fn idx(i: usize, j: usize, n: usize) usize { + return i * n + j; +} + +fn printResult(dist: []const f64, next: []const usize, n: usize) void { + std.debug.print("(pair, dist, path)\n", .{}); + for (0..n) |i| { + for (0..n) |j| { + if (i == j) continue; + + const @"u0" = i + 1; + const v0 = j + 1; + + std.debug.print("({d} -> {d}, {d}, ", .{ + @"u0", v0, dist[idx(i, j, n)], + }); + + var u = @"u0"; + std.debug.print("{d}", .{u}); + while (u != v0) { + u = next[idx(u - 1, v0 - 1, n)]; + std.debug.print(" -> {d}", .{u}); + } + std.debug.print(")\n", .{}); + } + } +} + +fn solve( + allocator: std.mem.Allocator, + edges: []const [3]i64, // (u,v,w) 1‑based + n: usize, +) !void { + // Allocate matrices + var dist = try allocator.alloc(f64, n * n); + defer allocator.free(dist); + + var next_v = try allocator.alloc(usize, n * n); + defer allocator.free(next_v); + + // Initialise + for (dist)|*d| d.* = F64_INF; + for (next_v)|*x| x.* = 0; + + // Edge weights + for (edges) |e| { + const u = @as(usize, @intCast(e[0] - 1)); + const v = @as(usize, @intCast(e[1] - 1)); + dist[idx(u, v, n)] = @as(f64, @floatFromInt(e[2])); + } + + // Successor matrix + for (0..n) |i| { + for (0..n) |j| { + if (i != j) next_v[idx(i, j, n)] = j + 1; // 1‑based + } + } + + // Floyd–Warshall + for (0..n) |k| { + for (0..n) |i| { + for (0..n) |j| { + const dik = dist[idx(i, k, n)]; + const dkj = dist[idx(k, j, n)]; + if (std.math.isFinite(dik) and std.math.isFinite(dkj)) { + const alt = dik + dkj; + const pos = idx(i, j, n); + if (alt < dist[pos]) { + dist[pos] = alt; + next_v[pos] = next_v[idx(i, k, n)]; + } + } + } + } + } + + printResult(dist, next_v, n); +} + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + const alloc = gpa.allocator(); + + const edges = [_][3]i64{ + .{ 1, 3, -2 }, + .{ 2, 1, 4 }, + .{ 2, 3, 3 }, + .{ 3, 4, 2 }, + .{ 4, 2, -1 }, + }; + + try solve(alloc, edges[0..], 4); +} diff --git a/Task/Floyds-triangle/ALGOL-68/floyds-triangle.alg b/Task/Floyds-triangle/ALGOL-68/floyds-triangle.alg index 3e06ecbe63..c3bd144573 100644 --- a/Task/Floyds-triangle/ALGOL-68/floyds-triangle.alg +++ b/Task/Floyds-triangle/ALGOL-68/floyds-triangle.alg @@ -1,7 +1,11 @@ -# procedure to print a Floyd's Triangle with n lines # +# procedure to print a Floyd's Triangle with n lines # PROC floyds triangle = ( INT n )VOID: BEGIN + # the triangle should be left aligned with the individual numbers # + # right-aligned with only one space before the number in the final # + # row # + # calculate the number of the highest number that will be printed # # ( the sum of the integers 1, 2, ... n ) # INT max number = ( n * ( n + 1 ) ) OVER 2; @@ -24,10 +28,6 @@ BEGIN END; # floyds triangle # -main: ( - - floyds triangle( 5 ); - print( ( newline ) ); - floyds triangle( 14 ) - -) +floyds triangle( 5 ); +print( ( newline ) ); +floyds triangle( 14 ) diff --git a/Task/Floyds-triangle/Ada/floyds-triangle.ada b/Task/Floyds-triangle/Ada/floyds-triangle.adb similarity index 100% rename from Task/Floyds-triangle/Ada/floyds-triangle.ada rename to Task/Floyds-triangle/Ada/floyds-triangle.adb diff --git a/Task/Floyds-triangle/Ballerina/floyds-triangle.ballerina b/Task/Floyds-triangle/Ballerina/floyds-triangle.ballerina new file mode 100644 index 0000000000..0a4976e6f9 --- /dev/null +++ b/Task/Floyds-triangle/Ballerina/floyds-triangle.ballerina @@ -0,0 +1,20 @@ +import ballerina/io; + +function floyd(int n) { + int k = 1; + foreach int i in 1...n { + foreach int j in 1...i { + int p = j < 9 ? 3 : 4; + io:print(k.toString().padStart(p)); + k += 1; + } + io:println(); + } +} + +public function main() { + io:println("Floyd(5):"); + floyd(5); + io:println("\nFloyd(14):"); + floyd(14); +} diff --git a/Task/Floyds-triangle/COBOL/floyds-triangle.cobol b/Task/Floyds-triangle/COBOL/floyds-triangle.cob similarity index 100% rename from Task/Floyds-triangle/COBOL/floyds-triangle.cobol rename to Task/Floyds-triangle/COBOL/floyds-triangle.cob diff --git a/Task/Floyds-triangle/Delphi/floyds-triangle.delphi b/Task/Floyds-triangle/Delphi/floyds-triangle.pas similarity index 100% rename from Task/Floyds-triangle/Delphi/floyds-triangle.delphi rename to Task/Floyds-triangle/Delphi/floyds-triangle.pas diff --git a/Task/Floyds-triangle/EasyLang/floyds-triangle.easy b/Task/Floyds-triangle/EasyLang/floyds-triangle.easy index 3e5e057b64..d575e1535b 100644 --- a/Task/Floyds-triangle/EasyLang/floyds-triangle.easy +++ b/Task/Floyds-triangle/EasyLang/floyds-triangle.easy @@ -1,17 +1,15 @@ func ceil h . f = floor h - if h <> f - f += 1 - . + if h <> f : f += 1 return f . -proc triangle n . . +proc triangle n . print n & " rows:" row = 1 while row <= n printme += 1 - cols = ceil log10 (n * (n - 1) / 2 + nprinted + 2) - numfmt 0 cols + cols = ceil log (n * (n - 1) / 2 + nprinted + 2) 10 + numfmt cols 0 write printme & " " nprinted += 1 if nprinted = row diff --git a/Task/Floyds-triangle/Elixir/floyds-triangle.elixir b/Task/Floyds-triangle/Elixir/floyds-triangle.ex similarity index 100% rename from Task/Floyds-triangle/Elixir/floyds-triangle.elixir rename to Task/Floyds-triangle/Elixir/floyds-triangle.ex diff --git a/Task/Floyds-triangle/Frink/floyds-triangle.frink b/Task/Floyds-triangle/Frink/floyds-triangle.frink new file mode 100644 index 0000000000..d404e4fbdc --- /dev/null +++ b/Task/Floyds-triangle/Frink/floyds-triangle.frink @@ -0,0 +1,16 @@ +FloydsTriangle[rows] := +{ + result = new array + n = 1 + for r = 1 to rows + { + result.push[array[n to n+r-1]] + n = n + r + } + + return result +} + +println[formatTable[FloydsTriangle[5], "right"]] +println[] +println[formatTable[FloydsTriangle[14], "right"]] diff --git a/Task/Floyds-triangle/FutureBasic/floyds-triangle.basic b/Task/Floyds-triangle/FutureBasic/floyds-triangle.basic new file mode 100644 index 0000000000..cd7e9cb937 --- /dev/null +++ b/Task/Floyds-triangle/FutureBasic/floyds-triangle.basic @@ -0,0 +1,18 @@ +void local fn FloydsTriangle( rows as int ) + int col, row, num = 1 + + printf @"%d rows:", rows + for row = 1 to rows + for col = 1 to row + printf @"%4d\b", num + num++ + next + print + next + print +end fn + +fn FloydsTriangle( 5 ) +fn FloydsTriangle( 14 ) + +HandleEvents diff --git a/Task/Floyds-triangle/Julia/floyds-triangle.julia b/Task/Floyds-triangle/Julia/floyds-triangle.jl similarity index 100% rename from Task/Floyds-triangle/Julia/floyds-triangle.julia rename to Task/Floyds-triangle/Julia/floyds-triangle.jl diff --git a/Task/Floyds-triangle/Kotlin/floyds-triangle.kotlin b/Task/Floyds-triangle/Kotlin/floyds-triangle.kts similarity index 100% rename from Task/Floyds-triangle/Kotlin/floyds-triangle.kotlin rename to Task/Floyds-triangle/Kotlin/floyds-triangle.kts diff --git a/Task/Floyds-triangle/OCaml/floyds-triangle.ocaml b/Task/Floyds-triangle/OCaml/floyds-triangle.ml similarity index 100% rename from Task/Floyds-triangle/OCaml/floyds-triangle.ocaml rename to Task/Floyds-triangle/OCaml/floyds-triangle.ml diff --git a/Task/Floyds-triangle/Objeck/floyds-triangle.objeck b/Task/Floyds-triangle/Objeck/floyds-triangle.objeck new file mode 100644 index 0000000000..567e784e01 --- /dev/null +++ b/Task/Floyds-triangle/Objeck/floyds-triangle.objeck @@ -0,0 +1,20 @@ +class Floyds { + function : Main(args : String[]) ~ Nil { + PrintTriangle(5); + PrintTriangle(14); + } + + function : PrintTriangle(n : Int) ~ Nil { + "{$n} rows:"->PrintLine(); + + rowNum := 1; printMe := 1; numsPrinted := 0; + for(; rowNum <= n; printMe++;){ + "{$printMe}\t"->Print(); + + if(++numsPrinted = rowNum){ + ""->PrintLine(); + rowNum++; numsPrinted := 0; + } + } + } +} diff --git a/Task/Floyds-triangle/PascalABC.NET/floyds-triangle.pas b/Task/Floyds-triangle/PascalABC.NET/floyds-triangle.pas new file mode 100644 index 0000000000..4bdce7f681 --- /dev/null +++ b/Task/Floyds-triangle/PascalABC.NET/floyds-triangle.pas @@ -0,0 +1,19 @@ +procedure FloydTriangle(rows: integer); +begin + var r := 1; + for var i:=1 to rows do + begin + for var j:=1 to i do + begin + Write(r: (j>8 ? 4 : 3)); + r += 1; + end; + Writeln + end; +end; + +begin + FloydTriangle(5); + Writeln; + FloydTriangle(14); +end. diff --git a/Task/Floyds-triangle/Phix/floyds-triangle.phix b/Task/Floyds-triangle/Phix/floyds-triangle.phix index 590838b99c..114ef290dc 100644 --- a/Task/Floyds-triangle/Phix/floyds-triangle.phix +++ b/Task/Floyds-triangle/Phix/floyds-triangle.phix @@ -1,20 +1,18 @@ -(phixonline)--> - with javascript_semantics - procedure Floyds_triangle(integer n) - sequence widths = repeat(0,n) - integer k = (n * (n-1))/2 - for i=1 to n do - widths[i] = sprintf("%%%dd",length(sprintf("%d",i+k))+1) - end for - k = 1 - for i=1 to n do - for j=1 to i do - printf(1,widths[j],k) - k += 1 - end for - printf(1,"\n") - end for - end procedure - Floyds_triangle(5) - Floyds_triangle(14) - - printf(1,"%09.3f\n",7.125) - - with javascript_semantics - include mpfr.e - mpz primorial = mpz_init(1), - pj = mpz_init() - sequence fortunates = {} - for p=1 to 75 do - mpz_mul_si(primorial,primorial,get_prime(p)) - integer j = 3 - mpz_add_si(pj,primorial,3) - while not mpz_prime(pj) do - mpz_add_si(pj,pj,2) - j = j + 2 - end while - fortunates &= j - end for - fortunates = unique(deep_copy(fortunates))[1..50] - fortunates = join_by(apply(true,sprintf,{{"%3d"},fortunates}),1,10) - printf(1,"The first 50 distinct fortunate numbers are:\n%s\n",{fortunates}) - - with javascript_semantics - function fwd_diff_n(sequence s, integer order) - assert(order<length(s)) - s = deep_copy(s) - for i=1 to order do - for j=1 to length(s)-1 do - s[j] = s[j+1]-s[j] - end for - s = s[1..-2] - end for - return s - end function +with javascript_semantics +function fwd_diff_n(sequence s, integer order) + assert(orderconstant s = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73} - for i=1 to 9 do - ?fwd_diff_n(s,i) - end for - - with javascript_semantics - function xor_gate(bool a, bool b) - return (a and not b) or (not a and b) - end function +with javascript_semantics +constant inf = 1e300*1e300, -- (works on both 32 and 64 bit) + ninf = -inf, + nan = -(inf/inf), + nzero = -1/inf -- (not supported) - function half_adder(bool a, bool b) - bool s = xor_gate(a,b), - c = a and b - return {s,c} - end function - - function full_adder(bool a, bool b, bool c) - bool {s1,c1} = half_adder(c,a), - {s2,c2} = half_adder(s1,b) - c = c1 or c2 - return {s2,c} - end function - - function four_bit_adder(bool a0, a1, a2, a3, b0, b1, b2, b3) - bool s0,s1,s2,s3,c - {s0,c} = full_adder(a0,b0,0) - {s1,c} = full_adder(a1,b1,c) - {s2,c} = full_adder(a2,b2,c) - {s3,c} = full_adder(a3,b3,c) - return {s3,s2,s1,s0,c} - end function - - procedure test(integer a, integer b) - bool {a0,a1,a2,a3} = int_to_bits(a,4), - {b0,b1,b2,b3} = int_to_bits(b,4), - {r3,r2,r1,r0,c} = four_bit_adder(a0,a1,a2,a3,b0,b1,b2,b3) - integer r = bits_to_int({r0,r1,r2,r3}) - string s = iff(c?sprintf(" [=%d+16]",r):"") - printf(1,"%04b + %04b = %04b %b (%d+%d=%d%s)\n",{a,b,r,c,a,b,c*16+r,s}) - end procedure - - test(0,0) - test(0,1) - test(0b1111,0b1111) - test(3,7) - test(11,8) - test(0b1100,0b1100) - test(0b1100,0b1101) - test(0b1100,0b1110) - test(0b1100,0b1111) - test(0b1101,0b0000) - test(0b1101,0b0001) - test(0b1101,0b0010) - test(0b1101,0b0011) - - with javascript_semantics - --<adapted from demo\rosetta\number_names.exw, which alas outputs ",", "and", uses "minus" instead of "negative", etc...> - constant twenties = {"zero","one","two","three","four","five","six","seven","eight","nine","ten", - "eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"}, - decades = {"twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"} +with javascript_semantics +constant twenties = {"zero","one","two","three","four","five","six","seven","eight","nine","ten", + "eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"}, + decades = {"twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"} - function hundred(integer n) - if n<20 then - return twenties[mod(n,20)+1] - elsif mod(n,10)=0 then - return decades[mod(floor(n/10),10)-1] - end if - return decades[mod(floor(n/10),10)-1] & '-' & twenties[mod(n,10)+1] - end function +function hundred(integer n) + if n<20 then + return twenties[mod(n,20)+1] + elsif mod(n,10)=0 then + return decades[mod(floor(n/10),10)-1] + end if + return decades[mod(floor(n/10),10)-1] & '-' & twenties[mod(n,10)+1] +end function - function thousand(integer n) - if n<100 then - return hundred(n) - elsif mod(n,100)=0 then - return twenties[mod(floor(n/100),20)+1]&" hundred" - end if - return twenties[mod(floor(n/100),20)+1] & " hundred " & hundred(mod(n,100)) - end function +function thousand(integer n) + if n<100 then + return hundred(n) + elsif mod(n,100)=0 then + return twenties[mod(floor(n/100),20)+1]&" hundred" + end if + return twenties[mod(floor(n/100),20)+1] & " hundred " & hundred(mod(n,100)) +end function - constant orders = {{power(10,12),"trillion"}, - {power(10,9),"billion"}, - {power(10,6),"million"}, - {power(10,3),"thousand"}} +constant orders = {{power(10,12),"trillion"}, + {power(10,9),"billion"}, + {power(10,6),"million"}, + {power(10,3),"thousand"}} - function triplet(integer n) - string res = "" - for i=1 to length(orders) do - {atom order, string name} = orders[i] - atom high = floor(n/order), - low = mod(n,order) - if high!=0 then - res &= thousand(high)&' '&name - end if - n = low - if low=0 then exit end if - if length(res) and high!=0 then - res &= " " - end if - end for - if n!=0 or res="" then - res &= thousand(floor(n)) - end if - return res - end function +function triplet(integer n) + string res = "" + for i=1 to length(orders) do + {atom order, string name} = orders[i] + atom high = floor(n/order), + low = mod(n,order) + if high!=0 then + res &= thousand(high)&' '&name + end if + n = low + if low=0 then exit end if + if length(res) and high!=0 then + res &= " " + end if + end for + if n!=0 or res="" then + res &= thousand(floor(n)) + end if + return res +end function - function spell(integer n) - string res = "" - if n<0 then - res = "negative " - n = -n - end if - res &= triplet(n) - return res - end function - --</adapted from number_names.exw> +function spell(integer n) + string res = "" + if n<0 then + res = "negative " + n = -n + end if + res &= triplet(n) + return res +end function +-- - function fourIsMagic(atom n) - string s = spell(n) - s[1] = upper(s[1]) - string t = s - while n!=4 do - n = length(s) - s = spell(n) - t &= " is " & s & ", " & s - end while - t &= " is magic.\n" - return t - end function +function fourIsMagic(atom n) + string s = spell(n) + s[1] = upper(s[1]) + string t = s + while n!=4 do + n = length(s) + s = spell(n) + t &= " is " & s & ", " & s + end while + t &= " is magic.\n" + return t +end function - constant tests = {-7, -1, 0, 1, 2, 3, 4, 23, 1e9, 20140, 100, 130, 151, 999999} - for i=1 to length(tests) do - puts(1,fourIsMagic(tests[i])) - end for - %d/%d (removed %d)".fmt(xn,xd,yn,yd,k+1)); - } - } + foreach k in ([0..8]){ + yn,yd := rn[k],rd[k]; + if(yn!=0 and yd!=0 and + xn.toFloat()/xd.toFloat() == yn.toFloat()/yd.toFloat()){ + count+=1; + omitted[k]+=1; + if(count<=12) + println("%d/%d --> %d/%d (removed %d)".fmt(xn,xd,yn,yd,k+1)); + } + } } } println("%d-digit fractions found: %d, omitted %s\n" diff --git a/Task/Fractran/ALGOL-68/fractran.alg b/Task/Fractran/ALGOL-68/fractran.alg index c1d894374e..2908205a60 100644 --- a/Task/Fractran/ALGOL-68/fractran.alg +++ b/Task/Fractran/ALGOL-68/fractran.alg @@ -1,6 +1,6 @@ # as the numbers required for finding the first 20 primes are quite large, # -# we use Algol 68G's LONG LONG INT with a precision of 100 digits # -PR precision 100 PR +# we use Algol 68G's LONG LONG INT with a precision of 200 digits # +PR precision 200 PR # mode to hold fractions # MODE FRACTION = STRUCT( INT numerator, INT denominator ); @@ -9,16 +9,16 @@ MODE FRACTION = STRUCT( INT numerator, INT denominator ); OP / = ( INT a, b )FRACTION: ( a, b ); # mode to define a FRACTRAN progam # -MODE FRACTRAN = STRUCT( FLEX[0]FRACTION data +MODE FRACTRAN = STRUCT( [0]FRACTION data , LONG LONG INT n , BOOL halted ); # prepares a FRACTRAN program for use - sets the initial value of n and halted to FALSE # PRIO STARTAT = 1; -OP STARTAT = ( REF FRACTRAN f, INT start )REF FRACTRAN: +OP STARTAT = ( REF FRACTRAN f, INT start p )REF FRACTRAN: BEGIN halted OF f := FALSE; - n OF f := start; + n OF f := start p; f END; @@ -39,36 +39,39 @@ OP NEXT = ( REF FRACTRAN f )LONG LONG INT: FI ; # generate and print the sequence of numbers from a FRACTRAN pogram # -PROC print fractran sequence = ( REF FRACTRAN f, INT start, INT limit )VOID: +PROC print fractran sequence = ( REF FRACTRAN f, INT start p, INT limit )VOID: BEGIN - VOID( f STARTAT start ); - print( ( "0: ", whole( start, 0 ) ) ); + VOID( f STARTAT start p ); + print( ( "0: ", whole( start p, 0 ) ) ); FOR i TO limit WHILE VOID( NEXT f ); NOT halted OF f DO - print( ( " " + whole( i, 0 ) + ": " + whole( n OF f, 0 ) ) ) + print( ( " ", whole( i, 0 ), ":", whole( n OF f, 0 ) ) ) OD; print( ( newline ) ) END ; # print the first 16 elements from the primes FRACTRAN program # -FRACTRAN pf := ( ( 17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, 77/19, 1/17, 11/13, 13/11, 15/14, 15/2, 55/1 ), 0, FALSE ); +FRACTRAN pf := ( ( 17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, 77/19, 1/17, 11/13 + , 13/11, 15/14, 15/2, 55/1 ), 0, FALSE ); print fractran sequence( pf, 2, 15 ); # find some primes using the pf FRACTRAN progam - n is prime for the members in the sequence that are 2^n # -INT primes found := 0; -VOID( pf STARTAT 2 ); -INT pos := 0; -print( ( "seq position prime sequence value", newline ) ); -WHILE primes found < 20 AND NOT halted OF pf DO - LONG LONG INT value := NEXT pf; - INT power of 2 := 0; - pos +:= 1; - WHILE value MOD 2 = 0 AND value > 0 DO power of 2 PLUSAB 1; value OVERAB 2 OD; - IF value = 1 THEN - # found a prime # - primes found +:= 1; - print( ( whole( pos, -12 ) + " " + whole( power of 2, -6 ) + " (" + whole( n OF pf, 0 ) + ")", newline ) ) - FI -OD +BEGIN + INT primes found := 0; + VOID( pf STARTAT 2 ); + INT pos := 0; + print( ( "seq position prime sequence value", newline ) ); + WHILE primes found < 20 AND NOT halted OF pf DO + LONG LONG INT value := NEXT pf; + INT power of 2 := 0; + pos +:= 1; + WHILE value MOD 2 = 0 AND value > 0 DO power of 2 PLUSAB 1; value OVERAB 2 OD; + IF value = 1 THEN + primes found +:= 1; + print( ( whole( pos, -12 ), " ", whole( power of 2, -6 ) ) ); + print( ( " (" + whole( n OF pf, 0 ), ")", newline ) ) + FI + OD +END diff --git a/Task/Fractran/Ada/fractran.ada b/Task/Fractran/Ada/fractran.ada deleted file mode 100644 index 90f1a8e4db..0000000000 --- a/Task/Fractran/Ada/fractran.ada +++ /dev/null @@ -1,43 +0,0 @@ -with Ada.Text_IO; - -procedure Fractan is - - type Fraction is record Nom: Natural; Denom: Positive; end record; - type Frac_Arr is array(Positive range <>) of Fraction; - - function "/" (N: Natural; D: Positive) return Fraction is - Frac: Fraction := (Nom => N, Denom => D); - begin - return Frac; - end "/"; - - procedure F(List: Frac_Arr; Start: Positive; Max_Steps: Natural) is - N: Positive := Start; - J: Positive; - begin - Ada.Text_IO.Put(" 0:" & Integer'Image(N) & " "); - for I in 1 .. Max_Steps loop - J := List'First; - loop - if N mod List(J).Denom = 0 then - N := (N/List(J).Denom) * List(J).Nom; - exit; -- found fraction - elsif J >= List'Last then - return; -- did try out all fractions - else - J := J + 1; -- try the next fraction - end if; - end loop; - Ada.Text_IO.Put(Integer'Image(I) & ":" & Integer'Image(N) & " "); - end loop; - end F; - -begin - -- F((2/3, 7/2, 1/5, 1/7, 1/9, 1/4, 1/8), 2, 100); - -- output would be "0: 2 1: 7 2: 1" and then terminate - - F((17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, - 77/19, 1/17, 11/13, 13/11, 15/14, 15/2, 55/1), - 2, 15); - -- output is "0: 2 1: 15 2: 825 3: 725 ... 14: 132 15: 116" -end Fractan; diff --git a/Task/Fractran/Ada/fractran.adb b/Task/Fractran/Ada/fractran.adb new file mode 100644 index 0000000000..b80338cfca --- /dev/null +++ b/Task/Fractran/Ada/fractran.adb @@ -0,0 +1,43 @@ +with Ada.Text_IO; + +procedure Fractan is + + type Fraction is record Nom: Natural; Denom: Positive; end record; + type Frac_Arr is array(Positive range <>) of Fraction; + + function "/" (N: Natural; D: Positive) return Fraction is + Frac: Fraction := (Nom => N, Denom => D); + begin + return Frac; + end "/"; + + procedure F(List: Frac_Arr; Start: Positive; Max_Steps: Natural) is + N: Positive := Start; + J: Positive; + begin + Ada.Text_IO.Put(" 0:" & Integer'Image(N) & " "); + for I in 1 .. Max_Steps loop + J := List'First; + loop + if N mod List(J).Denom = 0 then + N := (N/List(J).Denom) * List(J).Nom; + exit; -- found fraction + elsif J >= List'Last then + return; -- did try out all fractions + else + J := J + 1; -- try the next fraction + end if; + end loop; + Ada.Text_IO.Put(Integer'Image(I) & ":" & Integer'Image(N) & " "); + end loop; + end F; + +begin + -- F((2/3, 7/2, 1/5, 1/7, 1/9, 1/4, 1/8), 2, 100); + -- output would be "0: 2 1: 7 2: 1" and then terminate + + F((17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, + 77/19, 1/17, 11/13, 13/11, 15/14, 15/2, 55/1), + 2, 15); + -- output is "0: 2 1: 15 2: 825 3: 725 ... 14: 132 15: 116" +end Fractan; diff --git a/Task/Fractran/Batch-File/fractran.bat b/Task/Fractran/Batch-File/fractran.bat index 956eee44cc..75fe098b0a 100644 --- a/Task/Fractran/Batch-File/fractran.bat +++ b/Task/Fractran/Batch-File/fractran.bat @@ -1,41 +1,41 @@ @echo off setlocal enabledelayedexpansion - ::Set the inputs + ::Set the inputs set "code=17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1" set "n=2" - ::Basic validation of code + ::Basic validation of code for %%. in (!code!) do ( - echo.%%.|findstr /r /c:"^[0-9][0-9]*/[1-9][0-9]*$">nul||goto error_code + echo.%%.|findstr /r /c:"^[0-9][0-9]*/[1-9][0-9]*$">nul||goto error_code ) - ::Validate the input + ::Validate the input set /a "tst=1*!n!" 2>nul if !tst! lss 0 goto error_input if !tst! equ 0 (if not "!n!"=="0" (goto error_input)) - ::Set the limit outputs - set limit=20 + ::Set the limit outputs + set limit=20 - ::Execute the code + ::Execute the code echo.Input: -echo. !n! +echo. !n! echo.Output: for /l %%? in (1,1,!limit!) do ( - set shouldwehalt=1 - for %%A in (!code!) do ( - for /f "tokens=1,2 delims=/" %%B in ("%%A") do ( - set /a "tst=!n! %% %%C" - if !tst! equ 0 ( - if !shouldwehalt! equ 1 ( - set shouldwehalt=0 - set /a "n=n*%%B/%%C" - echo. !n! - ) - ) - ) - ) - if !shouldwehalt! equ 1 goto halt + set shouldwehalt=1 + for %%A in (!code!) do ( + for /f "tokens=1,2 delims=/" %%B in ("%%A") do ( + set /a "tst=!n! %% %%C" + if !tst! equ 0 ( + if !shouldwehalt! equ 1 ( + set shouldwehalt=0 + set /a "n=n*%%B/%%C" + echo. !n! + ) + ) + ) + ) + if !shouldwehalt! equ 1 goto halt ) :halt diff --git a/Task/Fractran/C++/fractran.cpp b/Task/Fractran/C++/fractran.cpp index 0f68fa192b..a3d5f34195 100644 --- a/Task/Fractran/C++/fractran.cpp +++ b/Task/Fractran/C++/fractran.cpp @@ -16,44 +16,44 @@ public: copy( istream_iterator( iss ), istream_iterator(), back_inserter >( tmp ) ); string item; vector< pair > v; - pair a; - for( vector::iterator i = tmp.begin(); i != tmp.end(); i++ ) - { - string::size_type pos = ( *i ).find( '/', 0 ); - if( pos != std::string::npos ) - { - a = make_pair( atof( ( ( *i ).substr( 0, pos ) ).c_str() ), atof( ( ( *i ).substr( pos + 1 ) ).c_str() ) ); - v.push_back( a ); - } - } - - exec( &v ); + pair a; + for( vector::iterator i = tmp.begin(); i != tmp.end(); i++ ) + { + string::size_type pos = ( *i ).find( '/', 0 ); + if( pos != std::string::npos ) + { + a = make_pair( atof( ( ( *i ).substr( 0, pos ) ).c_str() ), atof( ( ( *i ).substr( pos + 1 ) ).c_str() ) ); + v.push_back( a ); + } + } + + exec( &v ); } private: void exec( vector< pair >* v ) { - int cnt = 0; - while( cnt < limit ) - { - cout << cnt << " : " << start << "\n"; - cnt++; - vector< pair >::iterator it = v->begin(); - bool found = false; float r; - while( it != v->end() ) - { - r = start * ( ( *it ).first / ( *it ).second ); - if( r == floor( r ) ) - { - found = true; - break; - } - ++it; - } + int cnt = 0; + while( cnt < limit ) + { + cout << cnt << " : " << start << "\n"; + cnt++; + vector< pair >::iterator it = v->begin(); + bool found = false; float r; + while( it != v->end() ) + { + r = start * ( ( *it ).first / ( *it ).second ); + if( r == floor( r ) ) + { + found = true; + break; + } + ++it; + } - if( found ) start = ( int )r; - else break; - } + if( found ) start = ( int )r; + else break; + } } int start, limit; }; diff --git a/Task/Fractran/C/fractran.c b/Task/Fractran/C/fractran.c index 6931d47852..1119b05a77 100644 --- a/Task/Fractran/C/fractran.c +++ b/Task/Fractran/C/fractran.c @@ -4,62 +4,62 @@ typedef struct frac_s *frac; struct frac_s { - int n, d; - frac next; + int n, d; + frac next; }; frac parse(char *s) { - int offset = 0; - struct frac_s h = {0}, *p = &h; + int offset = 0; + struct frac_s h = {0}, *p = &h; - while (2 == sscanf(s, "%d/%d%n", &h.n, &h.d, &offset)) { - s += offset; - p = p->next = malloc(sizeof *p); - *p = h; - p->next = 0; - } + while (2 == sscanf(s, "%d/%d%n", &h.n, &h.d, &offset)) { + s += offset; + p = p->next = malloc(sizeof *p); + *p = h; + p->next = 0; + } - return h.next; + return h.next; } int run(int v, char *s) { - frac n, p = parse(s); - mpz_t val; - mpz_init_set_ui(val, v); + frac n, p = parse(s); + mpz_t val; + mpz_init_set_ui(val, v); -loop: n = p; - if (mpz_popcount(val) == 1) - gmp_printf("\n[2^%d = %Zd]", mpz_scan1(val, 0), val); - else - gmp_printf(" %Zd", val); +loop: n = p; + if (mpz_popcount(val) == 1) + gmp_printf("\n[2^%d = %Zd]", mpz_scan1(val, 0), val); + else + gmp_printf(" %Zd", val); - for (n = p; n; n = n->next) { - // assuming the fractions are not reducible - if (!mpz_divisible_ui_p(val, n->d)) continue; + for (n = p; n; n = n->next) { + // assuming the fractions are not reducible + if (!mpz_divisible_ui_p(val, n->d)) continue; - mpz_divexact_ui(val, val, n->d); - mpz_mul_ui(val, val, n->n); - goto loop; - } + mpz_divexact_ui(val, val, n->d); + mpz_mul_ui(val, val, n->n); + goto loop; + } - gmp_printf("\nhalt: %Zd has no divisors\n", val); + gmp_printf("\nhalt: %Zd has no divisors\n", val); - mpz_clear(val); - while (p) { - n = p->next; - free(p); - p = n; - } + mpz_clear(val); + while (p) { + n = p->next; + free(p); + p = n; + } - return 0; + return 0; } int main(void) { - run(2, "17/91 78/85 19/51 23/38 29/33 77/29 95/23 " - "77/19 1/17 11/13 13/11 15/14 15/2 55/1"); + run(2, "17/91 78/85 19/51 23/38 29/33 77/29 95/23 " + "77/19 1/17 11/13 13/11 15/14 15/2 55/1"); - return 0; + return 0; } diff --git a/Task/Fractran/Delphi/fractran.delphi b/Task/Fractran/Delphi/fractran.pas similarity index 100% rename from Task/Fractran/Delphi/fractran.delphi rename to Task/Fractran/Delphi/fractran.pas diff --git a/Task/Fractran/EasyLang/fractran.easy b/Task/Fractran/EasyLang/fractran.easy new file mode 100644 index 0000000000..1fed677ff9 --- /dev/null +++ b/Task/Fractran/EasyLang/fractran.easy @@ -0,0 +1,38 @@ +func[] fractran prog$ val limit . + for s$ in strsplit prog$ " " : n[][] &= number strsplit s$ "/" + for n to limit + r[] &= val + for i to len n[][] + if val mod n[i][2] = 0 : break 1 + . + if i > len n[][] : break 1 + val = val / n[i][2] * n[i][1] + . + return r[] +. +p$ = "17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1" +print fractran p$ 2 15 +# +proc sort &d[] . + for i = 1 to len d[] - 1 + for j = i + 1 to len d[] + if d[j] < d[i] : swap d[j] d[i] + . + . +. +r[] = fractran p$ 2 1000 +sort r[] +i = 1 +prim = 2 +po = 4 +repeat + repeat + if i > len r[] : break 2 + until i > len r[] or r[i] >= po + i += 1 + . + until i > len r[] + if r[i] = po : write prim & " " + prim += 1 + po *= 2 +. diff --git a/Task/Fractran/Elixir/fractran.elixir b/Task/Fractran/Elixir/fractran.ex similarity index 100% rename from Task/Fractran/Elixir/fractran.elixir rename to Task/Fractran/Elixir/fractran.ex diff --git a/Task/Fractran/Fortran/fractran-2.f b/Task/Fractran/Fortran/fractran-2.f index 6a079ed26a..0422be02be 100644 --- a/Task/Fractran/Fortran/fractran-2.f +++ b/Task/Fractran/Fortran/fractran-2.f @@ -1,49 +1,49 @@ - INTEGER FUNCTION FRACTRAN(N,P,Q,M) !Notion devised by J. H. Conway. + INTEGER FUNCTION FRACTRAN(N,P,Q,M) !Notion devised by J. H. Conway. Careful: the rule is N*P/Q being integer. N*6/3 is integer always because this is N*2/1, but 3 may not divide N. Could check GCD(P,Q), dividing out the common denominator so MOD(N,Q) works. - INTEGER*8 N !The work variable. Modified! - INTEGER M !The number of fractions supplied. + INTEGER*8 N !The work variable. Modified! + INTEGER M !The number of fractions supplied. INTEGER P(M),Q(M)!The terms of the fractions. - INTEGER I !A stepper. - DO I = 1,M !Search the supplied fractions, P(i)/Q(i). - IF (MOD(N,Q(I)).EQ.0) THEN !Does the denominator divide N? - N = N/Q(I)*P(I) !Yes, compute N*P/Q but trying to dodge overflow. - FRACTRAN = I !Report the hit. - RETURN !Done! - END IF !Otherwise, - END DO !Try the next fraction in the order supplied. - FRACTRAN = 0 !No hit. - END FUNCTION FRACTRAN !That's it! Even so, "Turing complete"... + INTEGER I !A stepper. + DO I = 1,M !Search the supplied fractions, P(i)/Q(i). + IF (MOD(N,Q(I)).EQ.0) THEN !Does the denominator divide N? + N = N/Q(I)*P(I) !Yes, compute N*P/Q but trying to dodge overflow. + FRACTRAN = I !Report the hit. + RETURN !Done! + END IF !Otherwise, + END DO !Try the next fraction in the order supplied. + FRACTRAN = 0 !No hit. + END FUNCTION FRACTRAN !That's it! Even so, "Turing complete"... PROGRAM POKE - INTEGER FRACTRAN !Not the default type of function. - INTEGER P(66),Q(66) !Holds the fractions as P(i)/Q(i). - INTEGER*8 N !The working number. - INTEGER I,IT,L,M !Assistants. + INTEGER FRACTRAN !Not the default type of function. + INTEGER P(66),Q(66) !Holds the fractions as P(i)/Q(i). + INTEGER*8 N !The working number. + INTEGER I,IT,L,M !Assistants. - WRITE (6,1) !Announce. + WRITE (6,1) !Announce. 1 FORMAT ("Interpreter for J.H. Conway's FRACTRAN language.") Chew into an example programme. - OPEN (10,FILE = "Fractran.txt",STATUS="OLD",ACTION="READ") !Rather than compiled-in stuff. - READ (10,*) L !I need to know this without having to scan the input. - WRITE (6,2) L !Reveal in case of trouble. - 2 FORMAT (I0," fractions, as follow:") !Should the input evoke problems. - READ (10,*) (P(I),Q(I),I = 1,L) !Ask for the specified number of P,Q pairs. - WRITE (6,3) (P(I),Q(I),I = 1,L) !Show what turned up. - 3 FORMAT (24(I0,"/",I0:", ")) !As P(i)/Q(i) pairs. The colon means that there will be no trailing comma. - READ (10,*) N,M !The start value, and the step limit. - CLOSE (10) !Finished with input. - WRITE (6,4) N,M !Hopefully, all went well. + OPEN (10,FILE = "Fractran.txt",STATUS="OLD",ACTION="READ") !Rather than compiled-in stuff. + READ (10,*) L !I need to know this without having to scan the input. + WRITE (6,2) L !Reveal in case of trouble. + 2 FORMAT (I0," fractions, as follow:") !Should the input evoke problems. + READ (10,*) (P(I),Q(I),I = 1,L) !Ask for the specified number of P,Q pairs. + WRITE (6,3) (P(I),Q(I),I = 1,L) !Show what turned up. + 3 FORMAT (24(I0,"/",I0:", ")) !As P(i)/Q(i) pairs. The colon means that there will be no trailing comma. + READ (10,*) N,M !The start value, and the step limit. + CLOSE (10) !Finished with input. + WRITE (6,4) N,M !Hopefully, all went well. 4 FORMAT ("Start with N = ",I0,", step limit ",I0) Commence. - WRITE (6,10) 0,N !Splat a heading. - 10 FORMAT (/," Step #F: N",/,I6,4X,": ",I0) !Matched FORMAT 11. - DO I = 1,M !Here we go! - IT = FRACTRAN(N,P,Q,L) !Do it! - WRITE (6,11) I,IT,N !Show it! - 11 FORMAT (I6,I4,": ",I0) !N last, as it may be big. - IF (IT.LE.0) EXIT !No hit, so quit. - END DO !The next step. - END !Whee! + WRITE (6,10) 0,N !Splat a heading. + 10 FORMAT (/," Step #F: N",/,I6,4X,": ",I0) !Matched FORMAT 11. + DO I = 1,M !Here we go! + IT = FRACTRAN(N,P,Q,L) !Do it! + WRITE (6,11) I,IT,N !Show it! + 11 FORMAT (I6,I4,": ",I0) !N last, as it may be big. + IF (IT.LE.0) EXIT !No hit, so quit. + END DO !The next step. + END !Whee! diff --git a/Task/Fractran/Fortran/fractran-3.f b/Task/Fractran/Fortran/fractran-3.f index 1a409a7c11..8fdab8dd61 100644 --- a/Task/Fractran/Fortran/fractran-3.f +++ b/Task/Fractran/Fortran/fractran-3.f @@ -1,11 +1,11 @@ - DO I = 1,M !Here we go! - IT = FRACTRAN(N,P,Q,L) !Do it! - IF (POPCNT(N).EQ.1) WRITE (6,11) I,IT,N !Show it! - 11 FORMAT (I6,I4,": ",I0) !N last, as it may be big. - IF (IT.LE.0) EXIT !No hit, so quit. - IF (N.LE.0) THEN !Otherwise, worry about overflow. - WRITE (6,*) "Integer overflow!" !Justified. The test is not certain. - WRITE (6,11) I,IT,N !Alas, the step failed. - EXIT !Give in. - END IF !So much for overflow. - END DO !The next step. + DO I = 1,M !Here we go! + IT = FRACTRAN(N,P,Q,L) !Do it! + IF (POPCNT(N).EQ.1) WRITE (6,11) I,IT,N !Show it! + 11 FORMAT (I6,I4,": ",I0) !N last, as it may be big. + IF (IT.LE.0) EXIT !No hit, so quit. + IF (N.LE.0) THEN !Otherwise, worry about overflow. + WRITE (6,*) "Integer overflow!" !Justified. The test is not certain. + WRITE (6,11) I,IT,N !Alas, the step failed. + EXIT !Give in. + END IF !So much for overflow. + END DO !The next step. diff --git a/Task/Fractran/Fortran/fractran-4.f b/Task/Fractran/Fortran/fractran-4.f index 367c6d7833..7e4093fbcd 100644 --- a/Task/Fractran/Fortran/fractran-4.f +++ b/Task/Fractran/Fortran/fractran-4.f @@ -1,187 +1,187 @@ - MODULE CONWAYSIDEA !Notion devised by J. H. Conway. - USE PRIMEBAG !This is a common need. - INTEGER LASTP,ENUFF !Some size allowances. - PARAMETER (LASTP = 66, ENUFF = 66) !Should suffice for the example in mind. - INTEGER NPPOW(1:LASTP) !Represent N as a collection of powers of prime numbers. - TYPE FACTORED !But represent P and Q of freaction = P/Q - INTEGER PNUM(0:LASTP) !As a list of prime number indices with PNUM(0) the count. - INTEGER PPOW(LASTP) !And the powers. for the fingered primes. - END TYPE FACTORED !Rather than as a simple number multiplied out. - TYPE(FACTORED) FP(ENUFF),FQ(ENUFF) !Thus represent a factored fraction, P(i)/Q(i). - INTEGER PLIVE(ENUFF),NL !Helps subroutine SHOWN display NPPOW. - CONTAINS !Now for the details. - SUBROUTINE SHOWFACTORS(N) !First, to show an internal data structure. - TYPE(FACTORED) N !It is supplied as a list of prime factors. - INTEGER I !A stepper. - DO I = 1,N.PNUM(0) !Step along the list. - IF (I.GT.1) WRITE (MSG,"('x',$)") !Append a glyph for "multiply". - WRITE (MSG,"(I0,$)") PRIME(N.PNUM(I)) !The prime fingered in the list. - IF (N.PPOW(I).GT.1) WRITE (MSG,"('^',I0,$)") N.PPOW(I) !With an interesting power? - END DO !On to the next element in the list. - WRITE (MSG,1) N.PNUM(0) !End the line - 1 FORMAT (": Factor count ",I0) !With a count of prime factors. - END SUBROUTINE SHOWFACTORS !Hopefully, this will not be needed often. + MODULE CONWAYSIDEA !Notion devised by J. H. Conway. + USE PRIMEBAG !This is a common need. + INTEGER LASTP,ENUFF !Some size allowances. + PARAMETER (LASTP = 66, ENUFF = 66) !Should suffice for the example in mind. + INTEGER NPPOW(1:LASTP) !Represent N as a collection of powers of prime numbers. + TYPE FACTORED !But represent P and Q of freaction = P/Q + INTEGER PNUM(0:LASTP) !As a list of prime number indices with PNUM(0) the count. + INTEGER PPOW(LASTP) !And the powers. for the fingered primes. + END TYPE FACTORED !Rather than as a simple number multiplied out. + TYPE(FACTORED) FP(ENUFF),FQ(ENUFF) !Thus represent a factored fraction, P(i)/Q(i). + INTEGER PLIVE(ENUFF),NL !Helps subroutine SHOWN display NPPOW. + CONTAINS !Now for the details. + SUBROUTINE SHOWFACTORS(N) !First, to show an internal data structure. + TYPE(FACTORED) N !It is supplied as a list of prime factors. + INTEGER I !A stepper. + DO I = 1,N.PNUM(0) !Step along the list. + IF (I.GT.1) WRITE (MSG,"('x',$)") !Append a glyph for "multiply". + WRITE (MSG,"(I0,$)") PRIME(N.PNUM(I)) !The prime fingered in the list. + IF (N.PPOW(I).GT.1) WRITE (MSG,"('^',I0,$)") N.PPOW(I) !With an interesting power? + END DO !On to the next element in the list. + WRITE (MSG,1) N.PNUM(0) !End the line + 1 FORMAT (": Factor count ",I0) !With a count of prime factors. + END SUBROUTINE SHOWFACTORS !Hopefully, this will not be needed often. - TYPE(FACTORED) FUNCTION FACTOR(IT) !Into a list of primes and their powers. - INTEGER IT,N !The number and a copy to damage. - INTEGER P,POW !A stepper and a power. - INTEGER F,NF !A factor and a counter. - IF (IT.LE.0) STOP "Factor only positive numbers!" !Or else... - N = IT !A copy I can damage. - NF = 0 !No factors found. - P = 0 !Because no primes have been tried. - PP:DO WHILE (N.GT.1) !Step through the possibilities. - P = P + 1 !Another prime impends. - F = PRIME(P) !Grab a possible factor. - POW = 0 !It has no power yet. - FP:DO WHILE(MOD(N,F).EQ.0) !Well? - POW = POW + 1 !Count a factor.. - N = N/F !Reduce the number. - END DO FP !The P'th prime's power's produced. - IF (POW.GT.0) THEN !So, was it a factor? - IF (NF.GE.LASTP) THEN !Yes. Have I room in the list? - WRITE (MSG,1) IT,LASTP !Alas. + TYPE(FACTORED) FUNCTION FACTOR(IT) !Into a list of primes and their powers. + INTEGER IT,N !The number and a copy to damage. + INTEGER P,POW !A stepper and a power. + INTEGER F,NF !A factor and a counter. + IF (IT.LE.0) STOP "Factor only positive numbers!" !Or else... + N = IT !A copy I can damage. + NF = 0 !No factors found. + P = 0 !Because no primes have been tried. + PP:DO WHILE (N.GT.1) !Step through the possibilities. + P = P + 1 !Another prime impends. + F = PRIME(P) !Grab a possible factor. + POW = 0 !It has no power yet. + FP:DO WHILE(MOD(N,F).EQ.0) !Well? + POW = POW + 1 !Count a factor.. + N = N/F !Reduce the number. + END DO FP !The P'th prime's power's produced. + IF (POW.GT.0) THEN !So, was it a factor? + IF (NF.GE.LASTP) THEN !Yes. Have I room in the list? + WRITE (MSG,1) IT,LASTP !Alas. 1 FORMAT ("Factoring ",I0," but with provision for only ", 1 I0," prime factors!") - FACTOR.PNUM(0) = NF !Place the count so far, + FACTOR.PNUM(0) = NF !Place the count so far, CALL SHOWFACTORS(FACTOR)!So this can be invoked. - STOP "Not enough storage!" !Quite. - END IF !But normally, - NF = NF + 1 !Admit another factor. - FACTOR.PNUM(NF) = P !Identify the prime. NOT the prime itself. - FACTOR.PPOW(NF) = POW !Place its power. - END IF !So much for that factor. - END DO PP !Try another prime, if N > 1 still. - FACTOR.PNUM(0) = NF !Place the count. - END FUNCTION FACTOR !Thus, a list of primes and their powers. + STOP "Not enough storage!" !Quite. + END IF !But normally, + NF = NF + 1 !Admit another factor. + FACTOR.PNUM(NF) = P !Identify the prime. NOT the prime itself. + FACTOR.PPOW(NF) = POW !Place its power. + END IF !So much for that factor. + END DO PP !Try another prime, if N > 1 still. + FACTOR.PNUM(0) = NF !Place the count. + END FUNCTION FACTOR !Thus, a list of primes and their powers. - INTEGER FUNCTION GCD(I,J) !Greatest common divisor. - INTEGER I,J !Of these two integers. - INTEGER N,M,R !Workers. - N = MAX(I,J) !Since I don't want to damage I or J, - M = MIN(I,J) !These copies might as well be the right way around. - 1 R = MOD(N,M) !Divide N by M to get the remainder R. - IF (R.GT.0) THEN !Remainder zero? - N = M !No. Descend a level. - M = R !M-multiplicity has been removed from N. - IF (R .GT. 1) GO TO 1 !No point dividing by one. - END IF !If R = 0, M divides N. - GCD = M !There we are. - END FUNCTION GCD !Euclid lives on! + INTEGER FUNCTION GCD(I,J) !Greatest common divisor. + INTEGER I,J !Of these two integers. + INTEGER N,M,R !Workers. + N = MAX(I,J) !Since I don't want to damage I or J, + M = MIN(I,J) !These copies might as well be the right way around. + 1 R = MOD(N,M) !Divide N by M to get the remainder R. + IF (R.GT.0) THEN !Remainder zero? + N = M !No. Descend a level. + M = R !M-multiplicity has been removed from N. + IF (R .GT. 1) GO TO 1 !No point dividing by one. + END IF !If R = 0, M divides N. + GCD = M !There we are. + END FUNCTION GCD !Euclid lives on! - INTEGER FUNCTION FRACTRAN(L) !Applies Conway's idea to a list of fractions. + INTEGER FUNCTION FRACTRAN(L) !Applies Conway's idea to a list of fractions. Could abandon all parameters since global variables have the details... - INTEGER L !The last fraction to consider. - INTEGER I,NF !Assistants. - DO I = 1,L !Step through the fractions in the order they were given. - NF = FQ(I).PNUM(0) !How many factors are listed in FQ(I)? - IF (ALL(NPPOW(FQ(I).PNUM(1:NF)) !Can N (as NPPOW) be divided by Q (as FQ)? - 1 .GE. FQ(I).PPOW(1:NF))) THEN !By comparing the supplies of prime factors. - FRACTRAN = I !Yes! - NPPOW(FQ(I).PNUM(1:NF)) = NPPOW(FQ(I).PNUM(1:NF)) !Remove prime powers from N - 1 - FQ(I).PPOW(1:NF) !Corresponding to Q. - NF = FP(I).PNUM(0) !Add powers to N - NPPOW(FP(I).PNUM(1:NF)) = NPPOW(FP(I).PNUM(1:NF)) !Corresponding to P. - 1 + FP(I).PPOW(1:NF) !Thus, N = N/Q*P. - RETURN !That's all it takes! No multiplies nor divides! - END IF !So much for that fraction. - END DO !This relies on ALL(zero tests) yielding true, as when Q = 1. - FRACTRAN = 0 !No hit. - END FUNCTION FRACTRAN !No massive multi-precision arithmetic! + INTEGER L !The last fraction to consider. + INTEGER I,NF !Assistants. + DO I = 1,L !Step through the fractions in the order they were given. + NF = FQ(I).PNUM(0) !How many factors are listed in FQ(I)? + IF (ALL(NPPOW(FQ(I).PNUM(1:NF)) !Can N (as NPPOW) be divided by Q (as FQ)? + 1 .GE. FQ(I).PPOW(1:NF))) THEN !By comparing the supplies of prime factors. + FRACTRAN = I !Yes! + NPPOW(FQ(I).PNUM(1:NF)) = NPPOW(FQ(I).PNUM(1:NF)) !Remove prime powers from N + 1 - FQ(I).PPOW(1:NF) !Corresponding to Q. + NF = FP(I).PNUM(0) !Add powers to N + NPPOW(FP(I).PNUM(1:NF)) = NPPOW(FP(I).PNUM(1:NF)) !Corresponding to P. + 1 + FP(I).PPOW(1:NF) !Thus, N = N/Q*P. + RETURN !That's all it takes! No multiplies nor divides! + END IF !So much for that fraction. + END DO !This relies on ALL(zero tests) yielding true, as when Q = 1. + FRACTRAN = 0 !No hit. + END FUNCTION FRACTRAN !No massive multi-precision arithmetic! - SUBROUTINE SHOWN(S,F) !Service routine to show the state after a step is calculated. + SUBROUTINE SHOWN(S,F) !Service routine to show the state after a step is calculated. Could imaging a function I6FMT(23) that returns " 23" and " " for non-positive numbers. Can't do it, as if this were invoked via a WRITE statement, re-entrant use of WRITE usually fails. - INTEGER S,F !Step number, Fraction number. - INTEGER I !A stepper. - CHARACTER*(9+4+1 + NL*6) ALINE !A scratchpad matching FORMAT 103. - WRITE (ALINE,103) S,F,NPPOW(PLIVE(1:NL)) !Show it! - 103 FORMAT (I9,I4,":",I6) !As a sequence of powers of primes. - IF (F.LE.0) ALINE(10:13) = "" !Scrub when no fraction is fingered. - DO I = 1,NL !Step along the live primes. - IF (NPPOW(PLIVE(I)).GT.0) CYCLE !Ignoring the empowered ones. - ALINE(15 + (I - 1)*6:14 + I*6) = "" !Blank out zero powers. - END DO !On to the next. - WRITE (MSG,"(A)") ALINE !Reveal at last. - END SUBROUTINE SHOWN !A struggle. - END MODULE CONWAYSIDEA !Simple... + INTEGER S,F !Step number, Fraction number. + INTEGER I !A stepper. + CHARACTER*(9+4+1 + NL*6) ALINE !A scratchpad matching FORMAT 103. + WRITE (ALINE,103) S,F,NPPOW(PLIVE(1:NL)) !Show it! + 103 FORMAT (I9,I4,":",I6) !As a sequence of powers of primes. + IF (F.LE.0) ALINE(10:13) = "" !Scrub when no fraction is fingered. + DO I = 1,NL !Step along the live primes. + IF (NPPOW(PLIVE(I)).GT.0) CYCLE !Ignoring the empowered ones. + ALINE(15 + (I - 1)*6:14 + I*6) = "" !Blank out zero powers. + END DO !On to the next. + WRITE (MSG,"(A)") ALINE !Reveal at last. + END SUBROUTINE SHOWN !A struggle. + END MODULE CONWAYSIDEA !Simple... PROGRAM POKE - USE CONWAYSIDEA !But, where does he get his ideas from? - INTEGER P(ENUFF),Q(ENUFF) !Holds the fractions as P(i)/Q(i). - INTEGER N !The working number. - INTEGER LF !Last fraction given. - INTEGER LP !Last prime needed. - INTEGER MS !Maximum number of steps. - INTEGER I,IT !Assistants. - LOGICAL*1 PUSED(ENUFF) !Track the usage of prime numbers, + USE CONWAYSIDEA !But, where does he get his ideas from? + INTEGER P(ENUFF),Q(ENUFF) !Holds the fractions as P(i)/Q(i). + INTEGER N !The working number. + INTEGER LF !Last fraction given. + INTEGER LP !Last prime needed. + INTEGER MS !Maximum number of steps. + INTEGER I,IT !Assistants. + LOGICAL*1 PUSED(ENUFF) !Track the usage of prime numbers, - MSG = 6 !Standard output. - WRITE (6,1) !Announce. + MSG = 6 !Standard output. + WRITE (6,1) !Announce. 1 FORMAT ("Interpreter for J. H. Conway's FRACTRAN language.") Chew into an example programme. - 10 OPEN (10,FILE = "Fractran.txt",STATUS="OLD",ACTION="READ") !Rather than compiled-in stuff. - READ (10,*) LF !I need to know this without having to scan the input. - WRITE (MSG,11) LF !Reveal in case of trouble. - 11 FORMAT (I0," fractions, as follow:") !Should the input evoke problems. - READ (10,*) (P(I),Q(I),I = 1,LF) !Ask for the specified number of P,Q pairs. - WRITE (MSG,12) (P(I),Q(I),I = 1,LF) !Show what turned up. - 12 FORMAT (24(I0,"/",I0:", ")) !As P(i)/Q(i) pairs. The colon means that there will be no trailing comma. - READ (10,*) N,MS !The start value, and the step limit. - CLOSE (10) !Finished with input. - WRITE (MSG,13) N,MS !Hopefully, all went well. + 10 OPEN (10,FILE = "Fractran.txt",STATUS="OLD",ACTION="READ") !Rather than compiled-in stuff. + READ (10,*) LF !I need to know this without having to scan the input. + WRITE (MSG,11) LF !Reveal in case of trouble. + 11 FORMAT (I0," fractions, as follow:") !Should the input evoke problems. + READ (10,*) (P(I),Q(I),I = 1,LF) !Ask for the specified number of P,Q pairs. + WRITE (MSG,12) (P(I),Q(I),I = 1,LF) !Show what turned up. + 12 FORMAT (24(I0,"/",I0:", ")) !As P(i)/Q(i) pairs. The colon means that there will be no trailing comma. + READ (10,*) N,MS !The start value, and the step limit. + CLOSE (10) !Finished with input. + WRITE (MSG,13) N,MS !Hopefully, all went well. 13 FORMAT ("Start with N = ",I0,", step limit ",I0) - IF (.NOT.GRASPPRIMEBAG(66)) STOP "Gan't grab my file of primes!" !Attempt in hope. + IF (.NOT.GRASPPRIMEBAG(66)) STOP "Gan't grab my file of primes!" !Attempt in hope. Convert the starting number to a more convenient form, an array of powers of successive prime numbers. - 20 FP(1) = FACTOR(N) !Borrow one of the factor list variables. - NPPOW = 0 !Clear all prime factor counts. - DO I = 1,FP(1).PNUM(0) !Now find what they are. - NPPOW(FP(1).PNUM(I)) = FP(1).PPOW(I) !Convert from a variable-length list - END DO !To a fixed-length random-access array. - PUSED = NPPOW.GT.0 !Note which primes have been used. - LP = FP(1).PNUM(FP(1).PNUM(0)) !Recall the last prime required. More later. + 20 FP(1) = FACTOR(N) !Borrow one of the factor list variables. + NPPOW = 0 !Clear all prime factor counts. + DO I = 1,FP(1).PNUM(0) !Now find what they are. + NPPOW(FP(1).PNUM(I)) = FP(1).PPOW(I) !Convert from a variable-length list + END DO !To a fixed-length random-access array. + PUSED = NPPOW.GT.0 !Note which primes have been used. + LP = FP(1).PNUM(FP(1).PNUM(0)) !Recall the last prime required. More later. Convert the supplied P(i)/Q(i) fractions to lists of prime number factors and powers in FP(i) and FQ(i). - DO I = 1,LF !Step through the fractions. - IT = GCD(P(I),Q(I)) !Suspicion. - IF (IT.GT.1) THEN !Justified? - WRITE (MSG,21) I,P(I),Q(I),IT !Alas. Complain. The rule is N*(P/Q) being integer. + DO I = 1,LF !Step through the fractions. + IT = GCD(P(I),Q(I)) !Suspicion. + IF (IT.GT.1) THEN !Justified? + WRITE (MSG,21) I,P(I),Q(I),IT !Alas. Complain. The rule is N*(P/Q) being integer. 21 FORMAT ("Fraction ",I3,", ",I0,"/",I0,!N*6/3 is integer always because this is N*2/1, but 3 may not divide N. - 1 " has common factor ",I0,"!") !By removing IT, - P(I) = P(I)/IT !The test need merely check if N is divisible by Q. - Q(I) = Q(I)/IT !And, as N is factorised in NPPOW - END IF !And Q in FQ, subtractions of powers only is needed. - FP(I) = FACTOR(P(I)) !Righto, form the factor list for P. - PUSED(FP(I).PNUM(1:FP(I).PNUM(0))) = .TRUE. !Mark which primes it fingers. - LP = MAX(LP,FP(I).PNUM(FP(I).PNUM(0))) !One has no prime factors: PNUM(0) = 0. - FQ(I) = FACTOR(Q(I)) !And likewise for Q. - PUSED(FQ(I).PNUM(1:FQ(I).PNUM(0))) = .TRUE. !Some primes may be omitted. - LP = MAX(LP,FQ(I).PNUM(FQ(I).PNUM(0))) !If no prime factors, PNUM(0) fingers element zero, which is zero. - END DO !All this messing about saves on multiplication and division. + 1 " has common factor ",I0,"!") !By removing IT, + P(I) = P(I)/IT !The test need merely check if N is divisible by Q. + Q(I) = Q(I)/IT !And, as N is factorised in NPPOW + END IF !And Q in FQ, subtractions of powers only is needed. + FP(I) = FACTOR(P(I)) !Righto, form the factor list for P. + PUSED(FP(I).PNUM(1:FP(I).PNUM(0))) = .TRUE. !Mark which primes it fingers. + LP = MAX(LP,FP(I).PNUM(FP(I).PNUM(0))) !One has no prime factors: PNUM(0) = 0. + FQ(I) = FACTOR(Q(I)) !And likewise for Q. + PUSED(FQ(I).PNUM(1:FQ(I).PNUM(0))) = .TRUE. !Some primes may be omitted. + LP = MAX(LP,FQ(I).PNUM(FQ(I).PNUM(0))) !If no prime factors, PNUM(0) fingers element zero, which is zero. + END DO !All this messing about saves on multiplication and division. Check which primes are in use, preparing an index of live primes.. - NL = 0 !No live primes. - DO I = 1,LP !Check up to the last prime. - IF (PUSED(I)) THEN !This one used? - NL = NL + 1 !Yes. Another. - PLIVE(NL) = I !Fingered. - END IF !So much for that prime. - END DO !On to the next. - WRITE (MSG,22) NL,LP,PRIME(LP) !Remark on usage. - 22 FORMAT ("Require ",I0," primes only, up to Prime(",I0,") = ",I0) !Presume always more than one prime. + NL = 0 !No live primes. + DO I = 1,LP !Check up to the last prime. + IF (PUSED(I)) THEN !This one used? + NL = NL + 1 !Yes. Another. + PLIVE(NL) = I !Fingered. + END IF !So much for that prime. + END DO !On to the next. + WRITE (MSG,22) NL,LP,PRIME(LP) !Remark on usage. + 22 FORMAT ("Require ",I0," primes only, up to Prime(",I0,") = ",I0) !Presume always more than one prime. IF (LP.GT.LASTP) STOP "But, that's too many for array NPPOW!" Cast forth a heading. - 100 WRITE (MSG,101) (PRIME(PLIVE(I)), I = 1,NL) !Splat a heading. - 101 FORMAT (/,14X,"N as powers of prime factors",/, !The prime heading, - 1 5X,"Step F#:",I6) !With primes beneath. - CALL SHOWN(0,0) !Initial state of N as NPPOW. Step zero, no fraction. + 100 WRITE (MSG,101) (PRIME(PLIVE(I)), I = 1,NL) !Splat a heading. + 101 FORMAT (/,14X,"N as powers of prime factors",/, !The prime heading, + 1 5X,"Step F#:",I6) !With primes beneath. + CALL SHOWN(0,0) !Initial state of N as NPPOW. Step zero, no fraction. Commence! - DO I = 1,MS !Here we go! - IT = FRACTRAN(LF) !Do it! - CALL SHOWN(I,IT) !Show it! - IF (IT.LE.0) EXIT !Quit it? - END DO !The next step. + DO I = 1,MS !Here we go! + IT = FRACTRAN(LF) !Do it! + CALL SHOWN(I,IT) !Show it! + IF (IT.LE.0) EXIT !Quit it? + END DO !The next step. Complete! - END !Whee! + END !Whee! diff --git a/Task/Fractran/Fortran/fractran-5.f b/Task/Fractran/Fortran/fractran-5.f index 65e4304ded..8bf75352db 100644 --- a/Task/Fractran/Fortran/fractran-5.f +++ b/Task/Fractran/Fortran/fractran-5.f @@ -1,5 +1,5 @@ - DO I = 1,MS !Here we go! - IT = FRACTRAN(LF) !Do it! - IF (ALL(NPPOW(2:LP).EQ.0)) CALL SHOWN(I,IT) !Show it! - IF (IT.LE.0) EXIT !Quit it? - END DO !The next step. + DO I = 1,MS !Here we go! + IT = FRACTRAN(LF) !Do it! + IF (ALL(NPPOW(2:LP).EQ.0)) CALL SHOWN(I,IT) !Show it! + IF (IT.LE.0) EXIT !Quit it? + END DO !The next step. diff --git a/Task/Fractran/Julia/fractran.jl b/Task/Fractran/Julia/fractran.jl new file mode 100644 index 0000000000..87f70c2989 --- /dev/null +++ b/Task/Fractran/Julia/fractran.jl @@ -0,0 +1,70 @@ +using .Iterators, BenchmarkTools +using Primes: Factorization, factor + +# type alias for abbreviation +Factors = Factorization{Int} + +# iterable stuct with parametric type polymorphism +struct Fractran{T} + program::Vector{@NamedTuple{num::T, den::T}} + input::Int + + # inner constructor + function Fractran{T}(program::Vector{Rational{Int}}, input::Int) where T + c = Dict(BigInt => identity, Factors => factor)[T] + new{T}([(num = c(f.num), den = c(f.den)) for f ∈ program], input) + end +end + +# methods for Fractran with n::BigInt +Base.iterate(ft::Fractran{BigInt}, n = big(ft.input)) = + for f ∈ ft.program + if iszero(n % f.den) + n = n ÷ f.den * f.num + return n, n + end + end + +iters(ft::Fractran{BigInt}) = ft + +output(ft::Fractran{BigInt}) = (trailing_zeros(n) for n ∈ ft if ispow2(n)) + +# methods for Fractran with n::Factorization{Int} +Base.iterate(ft::Fractran{Factors}, n = factor(ft.input)) = + for f ∈ ft.program + if all(n[p] ≥ e for (p, e) ∈ f.den) + for (p, e) ∈ f.den n[p] -= e end + for (p, e) ∈ f.num n[p] += e end + return n, n + end + end + +iters(ft::Fractran{Factors}) = (prod(n) for n ∈ ft) + +output(ft::Fractran{Factors}) = (n[2] for n ∈ ft if + all((iszero(e) || (p == 2)) for (p, e) ∈ n)) + +# convenient Fractran scripting +macro ft_str(s::String) + eval(Meta.parse(replace("[$s]", "/" => "//"))) +end + +# instantiation of Fractran example generating prime numbers +primes(T) = Fractran{T}(ft"17/91, 78/85, 19/51, 23/38, 29/33, 77/29, + 95/23, 77/19, 1/17, 11/13, 13/11, 15/14, 15/2, 55/1", 2) + +# Output including Benchmark +ilim = 20; plim = 45 + +function printout(T) + println("\n$ilim iterations and output of $plim prime numbers using ", T) + println(join(take(iters(primes(T)), ilim), ", "), "…") + join(stdout, take(output(primes(T)), plim), ", ") + print("…\nBenchmark: $plim primes in") +end + +printout(BigInt) +@btime collect(take(output(primes(BigInt)), plim)) + +printout(Factors) +@btime collect(take(output(primes(Factors)), plim)); diff --git a/Task/Fractran/Julia/fractran.julia b/Task/Fractran/Julia/fractran.julia deleted file mode 100644 index a590a05890..0000000000 --- a/Task/Fractran/Julia/fractran.julia +++ /dev/null @@ -1,41 +0,0 @@ -# FRACTRAN interpreter implemented as an iterable struct - -using .Iterators: filter, map, take - -struct Fractran - rs::Vector{Rational{BigInt}} - i₀::BigInt - limit::Int -end - -Base.iterate(f::Fractran, i = f.i₀) = - for r in f.rs - if iszero(i % r.den) - i = i ÷ r.den * r.num - return i, i - end - end - -interpret(f::Fractran) = - take( - map(trailing_zeros, - filter(ispow2, f)) - f.limit) - -Base.show(io::IO, f::Fractran) = - join(io, interpret(f), ' ') - -macro code_str(s) - [eval(Meta.parse(replace(t, "/" => "//"))) for t ∈ split(s)] -end - -primes = Fractran(code"17/91 78/85 19/51 23/38 29/33 77/29 95/23 - 77/19 1/17 11/13 13/11 15/14 15/2 55/1", 2, 30) - -# Output -println("First 25 iterations of FRACTRAN program 'primes':\n2 ", - join(take(primes, 25), ' ')) - -println("\nWatch the first 30 primes dropping out within seconds:") - -primes diff --git a/Task/Fractran/Kotlin/fractran.kotlin b/Task/Fractran/Kotlin/fractran.kts similarity index 100% rename from Task/Fractran/Kotlin/fractran.kotlin rename to Task/Fractran/Kotlin/fractran.kts diff --git a/Task/Fractran/Miranda/fractran.miranda b/Task/Fractran/Miranda/fractran.miranda new file mode 100644 index 0000000000..c1f844d524 --- /dev/null +++ b/Task/Fractran/Miranda/fractran.miranda @@ -0,0 +1,80 @@ +main :: [sys_message] +main = [Stdout (lay [show (take 15 (run 2 primeprog)), + show (take 20 fracprimes)])] + +primeprog :: [(num,num)] +primeprog = fromjust (prog ("17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 " + ++ "1/17 11/13 13/11 15/14 15/2 55/1")) + +fracprimes :: [num] +fracprimes = [fromjust k | k<-map fracprime (run 2 primeprog); isjust k] + +fracprime :: num->maybe num +fracprime = f 0 + where f 1 1 = Nothing + f n 1 = Just n + f n x = Nothing, if x mod 2 ~= 0 + f n x = f (n+1) (x div 2), otherwise + +run :: num->[(num,num)]->[num] +run n prog = [n], if ~isjust n' + = n : run (fromjust n') prog, otherwise + where n' = step n prog + +step :: num->[(num,num)]->maybe num +step x [] = Nothing +step x ((n,d):xs) = Just (x*n div d), if x*n mod d = 0 + = step x xs, otherwise + +maybe * ::= Nothing | Just * + +isjust :: maybe *->bool +isjust (Just x) = True +isjust Nothing = False + +fromjust :: maybe *->* +fromjust (Just x) = x + +prog :: [char]->maybe [(num, num)] +prog xs = Just [], if trim xs = [] + = Nothing, if ~isjust fp \/ ~isjust rp + = Just (fr : fromjust rp), otherwise + where fp = frac xs + Just (fr, xs') = fp + rp = prog xs' + +frac :: [char]->maybe ((num,num), [char]) +frac xs = Nothing, if ~isjust np \/ ~isjust sl \/ ~isjust dp + = Just ((n, d), xs'''), otherwise + where np = numb xs + Just (n, xs') = np + sl = match '/' (trim xs') + Just xs'' = sl + dp = numb xs'' + Just (d, xs''') = dp + +numb :: [char]->maybe (num, [char]) +numb xs = Nothing, if n=[] + = Just (numval n, r), otherwise + where (n, r) = span "0123456789" (trim xs) + +match :: *->[*]->maybe [*] +match m [] = Nothing +match m (m:xs) = Just xs +match m (x:xs) = Nothing + +span :: [*]->[*]->([*],[*]) +span match [] = ([], []) +span match (x:xs) = ([], x:xs), if ~(x $in match) + = (x:r, xs'), otherwise + where (r, xs') = span match xs + +in :: *->[*]->bool +in x [] = False +in x (x:xs) = True +in x (y:xs) = x $in xs + +trim :: [char]->[char] +trim [] = [] +trim (c:xs) = trim xs, if c='\t' \/ c='\n' \/ c=' ' +trim (c:xs) = c:xs diff --git a/Task/Fractran/OCaml/fractran.ocaml b/Task/Fractran/OCaml/fractran.ml similarity index 100% rename from Task/Fractran/OCaml/fractran.ocaml rename to Task/Fractran/OCaml/fractran.ml diff --git a/Task/Fractran/Odin/fractran.odin b/Task/Fractran/Odin/fractran.odin new file mode 100644 index 0000000000..118e1b4333 --- /dev/null +++ b/Task/Fractran/Odin/fractran.odin @@ -0,0 +1,77 @@ +package main + +import "core:fmt" +import "core:os" +import "core:strconv" +import "core:strings" +import "core:text/match" +import "core:math" + + +main :: proc() { + // fmt.println(os.args) + + n:int + number:int + number_conv:bool + fracts:[dynamic]int + defer delete(fracts) + + n,number_conv = strconv.parse_int(os.args[1]) + assert(number_conv, "Number must be given in first place!") + assert(len(os.args)>1,"no command line arguments given") + + data:="17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1" + + ss := strings.split(string(data), " ") + defer delete(ss) + + + a: [dynamic]string + dummy:[]string + defer delete(a) + defer delete(dummy) + + for i in ss{ + dummy =strings.split(i,"/") + for j in dummy{ + // fmt.println(j) + + append_elem(&a,j) + } + } + + for k in a{ + // fmt.println(k) + number,number_conv = strconv.parse_int(k) + assert(number_conv, "Number must be given in program") + append_elem(&fracts,number) + } + + + // fmt.println(len(fracts)) + cond:int + buf: [256]byte + bb:int + end:=0 + fmt.println(n) + frac: for j:=0;jnew($_), qw{ $|=1; MAIN: for( 1 .. 5000 ) { - print " " if $_ > 1; - my ($pow, $rest) = (0, $n->copy); - until( $rest->is_odd ) { - ++$pow; - $rest->bdiv(2); - } - if( $rest->is_one ) { - print "2**$pow"; - } else { - #print $n; - } - for my $f_i (@P) { - my $nf_i = $n * $f_i; - next unless $nf_i->is_int; - $n = $nf_i; - next MAIN; - } - last; + print " " if $_ > 1; + my ($pow, $rest) = (0, $n->copy); + until( $rest->is_odd ) { + ++$pow; + $rest->bdiv(2); + } + if( $rest->is_one ) { + print "2**$pow"; + } else { + #print $n; + } + for my $f_i (@P) { + my $nf_i = $n * $f_i; + next unless $nf_i->is_int; + $n = $nf_i; + next MAIN; + } + last; } print "\n"; diff --git a/Task/Fractran/R/fractran.r b/Task/Fractran/R/fractran.r new file mode 100644 index 0000000000..af0f56b3bf --- /dev/null +++ b/Task/Fractran/R/fractran.r @@ -0,0 +1,25 @@ +library(gmp) +library(stringr) + +fractran <- function(s, n, lim){ + P <- str_split_1(s, " ") |> str_split("/") + read_frac <- function(index) as.bigq(n=P[[index]][1], d=P[[index]][2]) + fracs <- sapply(seq_along(P), read_frac) + first_integer <- function(bigv, n){ + for(q in bigv){ + if(denominator(n*q)==1) return(q) + } + return(NA) + } + iters <- 0 + while(!is.na(first_integer(fracs, n))){ + n <- n*first_integer(fracs, n) + print(n, initLine=FALSE) + iters <- iters+1 + if(iters>=lim) break + } +} + +#Test input +fractran_primes <- "17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1" +fractran(fractran_primes, 2, 15) diff --git a/Task/Fractran/REXX/fractran-1.rexx b/Task/Fractran/REXX/fractran-1.rexx deleted file mode 100644 index 8572c8bd0b..0000000000 --- a/Task/Fractran/REXX/fractran-1.rexx +++ /dev/null @@ -1,28 +0,0 @@ -/*REXX program runs FRACTRAN for a given set of fractions and from a specified N. */ -numeric digits 2000 /*be able to handle larger numbers. */ -parse arg N terms fracs /*obtain optional arguments from the CL*/ -if N=='' | N=="," then N= 2 /*Not specified? Then use the default.*/ -if terms=='' | terms=="," then terms= 100 /* " " " " " " */ -if fracs='' then fracs= "17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23,", - '77/19, 1/17, 11/13, 13/11, 15/14, 15/2, 55/1' - /* [↑] The default for the fractions. */ -f= space(fracs, 0) /*remove all blanks from the FRACS list*/ - do #=1 while f\==''; parse var f n.# "/" d.# ',' f - end /*#*/ /* [↑] parse all the fractions in list*/ -#= # - 1 /*the number of fractions just found. */ -say # 'fractions:' fracs /*display number and actual fractions. */ -say 'N is starting at ' N /*display the starting number N. */ -say terms ' terms are being shown:' /*display a kind of header/title. */ - - do j=1 for terms /*perform the DO loop for each term. */ - do k=1 for # /* " " " " " " fraction*/ - if N // d.k \== 0 then iterate /*Not an integer? Then ignore it. */ - cN= commas(N); L= length(cN) /*maybe insert commas into N; get len.*/ - say right('term' commas(j), 44) "──► " right(cN, max(15, L)) /*show Nth term & N*/ - N= N % d.k * n.k /*calculate next term (use %≡integer ÷)*/ - leave /*go start calculating the next term. */ - end /*k*/ /* [↑] if an integer, we found a new N*/ - end /*j*/ -exit 0 /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ? diff --git a/Task/Fractran/REXX/fractran-2.rexx b/Task/Fractran/REXX/fractran-2.rexx deleted file mode 100644 index a201c8471b..0000000000 --- a/Task/Fractran/REXX/fractran-2.rexx +++ /dev/null @@ -1,39 +0,0 @@ -/*REXX program runs FRACTRAN for a given set of fractions and from a specified N. */ -numeric digits 999; d= digits(); w= length(d) /*be able to handle gihugeic numbers. */ -parse arg N terms fracs /*obtain optional arguments from the CL*/ -if N=='' | N=="," then N= 2 /*Not specified? Then use the default.*/ -if terms=='' | terms=="," then terms= 100 /* " " " " " " */ -if fracs='' then fracs= "17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23,", - '77/19, 1/17, 11/13, 13/11, 15/14, 15/2, 55/1' - /* [↑] The default for the fractions. */ -f= space(fracs, 0) /*remove all blanks from the FRACS list*/ - do #=1 while f\==''; parse var f n.# "/" d.# ',' f - end /*#*/ /* [↑] parse all the fractions in list*/ -#= # - 1 /*adjust the number of fractions found.*/ -tell= terms>0 /*flag: show number or a power of 2.*/ -!.= 0; _= 1 /*the default value for powers of 2. */ -if \tell then do p=1 until length(_)>d; _= _ + _; !._= 1 - if p==1 then @._= left('', w + 9) "2**"left(p, w) ' ' - else @._= '(prime' right(p, w)") 2**"left(p, w) ' ' - end /*p*/ /* [↑] build powers of 2 tables. */ -L= length(N) /*length in decimal digits of integer N*/ -say # 'fractions:' fracs /*display number and actual fractions. */ -say 'N is starting at ' N /*display the starting number N. */ -if tell then say terms ' terms are being shown:' /*display header.*/ - else say 'only powers of two are being shown:' /* " " */ -@a= '(max digits used:' /*a literal used in the SAY below. */ - - do j=1 for abs(terms) /*perform DO loop once for each term. */ - do k=1 for # /* " " " " " " fraction*/ - if N // d.k \== 0 then iterate /*Not an integer? Then ignore it. */ - cN= commas(N); cj=commas(j) /*maybe insert commas into N. */ - if tell then say right('term' cj, 44) "──► " cN /*display Nth term and N.*/ - else if !.N then say right('term' cj,15) "──►" @.N @a right(L,w)") " cN - N= N % d.k * n.k /*calculate next term (use %≡integer ÷)*/ - L= max(L, length(N) ) /*the maximum number of decimal digits.*/ - leave /*go start calculating the next term. */ - end /*k*/ /* [↑] if an integer, we found a new N*/ - end /*j*/ -exit 0 /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ? diff --git a/Task/Fractran/REXX/fractran.rexx b/Task/Fractran/REXX/fractran.rexx new file mode 100644 index 0000000000..1dd1d0179e --- /dev/null +++ b/Task/Fractran/REXX/fractran.rexx @@ -0,0 +1,76 @@ +-- 23 Aug 2025 +include Setting + +say 'FRACTRAN' +say version +say +parse arg n','t +if n = '' then + n = 2 +if t = '' then + t = 100 +numeric digits 200 +call Fractions +call Task +call Powers +call Extra +exit + +Fractions: +call Time('r') +say 'Save fractions...' +l = '17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1' +n. = 0; d. = 0; w = Words(l) +do i = 1 to w + a = Word(l,i); parse var a n.i'/'d.i +end +say Format(Time('e'),,3) 'seconds'; say +return + +Task: +call Time('r') +say 'First' t 'terms of the sequence:' +do i = 2 to t + do j = 1 to w + if \ Integer(n/d.j) then + iterate + call CharOut ,Right(n,9) + if i//10 = 0 then + say + n = n%d.j*n.j + leave j + end +end +say Format(Time('e'),,3) 'seconds'; say +return + +Powers: +call Time('r') +say 'Flag powers of 2...' +p. = 0; e. = 0 +do i = 2 to 100 + a = 2**i; p.a = 1; e.a = i +end +say Format(Time('e'),,3) 'seconds'; say +return + +Extra: +call Time('r') +say 'Prime numbers:' +n = 2; p = 0 +do i = 2 to 1300000 + do j = 1 to w + if \ Integer(n/d.j) then + iterate j + if p.n then do + p = p+1 + say Right(p,2) ' Term' Right(i,7) Left('= 2^'e.n,7) 'Prime' Right(e.n,2) 'found' + end + n = n%d.j*n.j + leave j + end +end +say Format(Time('e'),,3) 'seconds'; say +return + +include Math diff --git a/Task/Fractran/Rebol/fractran.rebol b/Task/Fractran/Rebol/fractran.rebol new file mode 100644 index 0000000000..33b17b69b8 --- /dev/null +++ b/Task/Fractran/Rebol/fractran.rebol @@ -0,0 +1,41 @@ +Rebol [ + title: "Rosetta code: Fractran" + file: %Fractran.r3 + url: https://rosettacode.org/wiki/Fractran +] + +fractran: function/with [ + input [string! file! url!] + start [integer!] + terms [integer!] +][ + unless string? input [ input: read/string input ] + ;; --- parse fractions into [numerator denominator] pairs --- + fractions: parse input [collect [fraction some [separator fraction]]] + ;; --- interpreter loop --- + out: append copy [] n: start + while [terms > length? out] [ + forall fractions [ + frac: fractions/1 + if zero? mod n frac/y [ ;; fraction applies: n is divisible + n: n / frac/y * frac/x ;; advance: multiply n by fraction + append out to integer! n ;; keep the result + fractions: head fractions ;; restart from first fraction + break + ] + if tail? fractions [return out] ;; no fraction applied: halt + ] + ] + out +][ + digit: charset "0123456789" + fraction: [copy p [some digit] #"/" copy q [some digit] keep (as-pair to integer! p to integer! q)] + separator: [some #" "] +] + +print "First 100 terms of the sequence:" +out: fractran "17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1" 2 100 +forall out [ + prin pad out/1 9 + if zero? mod index? out 10 [print ""] +] diff --git a/Task/Fractran/Red/fractran.red b/Task/Fractran/Red/fractran.red index a61ef88f55..44fb51eabe 100644 --- a/Task/Fractran/Red/fractran.red +++ b/Task/Fractran/Red/fractran.red @@ -5,20 +5,20 @@ if exists? inpf: to-file inp [inp: read inpf] digit: charset "0123456789" frac: [copy p [some digit] #"/" copy q [some digit] - keep (as-pair to-integer p to-integer q)] + keep (as-pair to-integer p to-integer q)] code: parse inp [collect [frac some [[some " "] frac]]] n: to-integer ask "please enter starting number n: " x: to-integer ask "please enter the number of terms, hit return for no limit: " l: length? code loop x [ - forall code [ - c: code/1 - if n % c/y = 0 [ - print n: n / c/y * c/x - code: head code - break - ] - if l = index? code [halt] - ] + forall code [ + c: code/1 + if n % c/y = 0 [ + print n: n / c/y * c/x + code: head code + break + ] + if l = index? code [halt] + ] ] diff --git a/Task/Fractran/Refal/fractran.refal b/Task/Fractran/Refal/fractran.refal new file mode 100644 index 0000000000..e66c789961 --- /dev/null +++ b/Task/Fractran/Refal/fractran.refal @@ -0,0 +1,78 @@ +$ENTRY Go { + , >: e.Prog + = > + >; +}; + +PrimeProgram { + = '17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 ' + '1/17 11/13 13/11 15/14 15/2 55/1'; +}; + +FracPrimes { + 0 e.X = ; + s.I (e.N) e.P, + : Next e.N2, + : { + T s.N = s.N (e.N2) e.P>; + F = ; + }; +}; + +FracPrime { + (1) 1 = F; + (s.N) 1 = T s.N; + (s.N) e.X, : { + (e.X2) 0 = ) e.X2>; + e.Z = F; + }; + e.X = ; +}; + +FracRun { + 0 e.X = ; + s.I (e.N) e.P, : { + Halt = e.N; + Next e.N2 = e.N (e.N2) e.P>; + }; +}; + +FracStep { + (e.N) = Halt; + (e.N) ((e.Num) e.Denom) e.P, + ) e.Denom>: { + (e.N2) 0 = Next e.N2; + e.X = ; + }; +}; + +Prog { + e.X, : T (e.F) e.R = (e.F) ; + e.X = ; +}; + +Frac { + e.X, : T (e.N) e.X2, + : '/' e.X3, + : T (e.D) e.X4 = + T ((e.N) e.D) e.X4; + e.X = F e.X; +}; + +Num { + e.X, >: { + () e.R = F e.R; + (e.N) e.R = T () e.R; + }; +}; + +Span { + (e.M) (e.S) s.C e.X, e.S: e.1 s.C e.2 = ; + (e.M) (e.S) e.X = (e.M) e.X; + (e.S) e.X = ; +}; + +SkipWs { + s.C e.X, ' \n\t': e.1 s.C e.2 = ; + e.X = e.X; +}; diff --git a/Task/Fractran/Rust/fractran.rs b/Task/Fractran/Rust/fractran.rs new file mode 100644 index 0000000000..e73a574558 --- /dev/null +++ b/Task/Fractran/Rust/fractran.rs @@ -0,0 +1,75 @@ +use std::io; + +struct Fractran { + start: i32, + limit: i32, +} + +impl Fractran { + fn new() -> Self { + Fractran { + start: 0, + limit: 0, + } + } + + fn run(&mut self, program: &str, start: i32, limit: i32) { + self.start = start; + self.limit = limit; + + // Parse the program string into fraction pairs + let fractions: Vec<(f64, f64)> = program + .split_whitespace() + .filter_map(|fraction_str| { + if let Some(pos) = fraction_str.find('/') { + let numerator = fraction_str[..pos].parse::().ok()?; + let denominator = fraction_str[pos + 1..].parse::().ok()?; + Some((numerator, denominator)) + } else { + None + } + }) + .collect(); + + self.exec(&fractions); + } + + fn exec(&mut self, fractions: &[(f64, f64)]) { + let mut count = 0; + + while count < self.limit { + println!("{} : {}", count, self.start); + count += 1; + + let mut found = false; + + for &(numerator, denominator) in fractions { + let result = self.start as f64 * (numerator / denominator); + + // Check if result is a whole number + if (result - result.floor()).abs() < f64::EPSILON { + self.start = result as i32; + found = true; + break; + } + } + + if !found { + break; + } + } + } +} + +fn main() { + let mut fractran = Fractran::new(); + fractran.run( + "17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1", + 2, + 15 + ); + + // Wait for user input (equivalent to cin.get()) + let mut input = String::new(); + io::stdin().read_line(&mut input).expect("Failed to read line"); +} diff --git a/Task/Fractran/SETL/fractran.setl b/Task/Fractran/SETL/fractran.setl new file mode 100644 index 0000000000..05f2b18236 --- /dev/null +++ b/Task/Fractran/SETL/fractran.setl @@ -0,0 +1,52 @@ +program fractran; + p := parse_fractran( + "17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 " + + "1/17 11/13 13/11 15/14 15/2 55/1" + ); + + print(frac_run_steps(p, 2, 15)); + print(frac_primes(p, 2, 20)); + + proc frac_primes(p, n, nprimes); + primes := []; + loop for i in [1..nprimes] do + loop until n bit_and (n-1) = 0 do + n := frac_step(p, n); + end loop; + primes with:= log n/log 2; + end loop; + return primes; + end proc; + + proc frac_run_steps(p, n, steps); + return [n] + [n := frac_step(p, n) : i in [2..steps]]; + end proc; + + proc frac_step(p, n); + if exists [num, denom] in p | n * num mod denom = 0 then + return n * num div denom; + end if; + return om; + end proc; + + proc rdws(rw s); + span(s, " \t\n"); + end proc; + + proc rdnum(rw s); + rdws(s); + return val span(s, "0123456789"); + end proc; + + proc rdfrac(rw s); + if (num := rdnum(s)) = om then return om; end if; + rdws(s); + if match(s, "/") = "" then return om; end if; + if (denom := rdnum(s)) = om then return om; end if; + return [num, denom]; + end proc; + + proc parse_fractran(s); + return [f := rdfrac(s) : until f=om]; + end proc; +end program; diff --git a/Task/Fractran/Scheme/fractran.ss b/Task/Fractran/Scheme/fractran.scm similarity index 100% rename from Task/Fractran/Scheme/fractran.ss rename to Task/Fractran/Scheme/fractran.scm diff --git a/Task/Fractran/TI-83-BASIC/fractran.basic b/Task/Fractran/TI-83-BASIC/fractran.basic index 3c39e388a9..c501d5df6a 100644 --- a/Task/Fractran/TI-83-BASIC/fractran.basic +++ b/Task/Fractran/TI-83-BASIC/fractran.basic @@ -5,15 +5,15 @@ Dim(LA)->U T->Dim(LC) For(I,1,T) - 1->J: 1->F - While J<=U and F=1 - If remainder(N,LB(J))=0 - Then - Disp N - N->LC(I) - iPart(N/LB(J))*LA(J)->N - 0->F - End - J+1->J - End + 1->J: 1->F + While J<=U and F=1 + If remainder(N,LB(J))=0 + Then + Disp N + N->LC(I) + iPart(N/LB(J))*LA(J)->N + 0->F + End + J+1->J + End End diff --git a/Task/Fractran/Tcl/fractran-1.tcl b/Task/Fractran/Tcl/fractran-1.tcl index 50932aaba5..6a0acc52ec 100644 --- a/Task/Fractran/Tcl/fractran-1.tcl +++ b/Task/Fractran/Tcl/fractran-1.tcl @@ -3,42 +3,42 @@ package require Tcl 8.6 oo::class create Fractran { variable fracs nco constructor {fractions} { - set fracs {} - foreach frac $fractions { - if {[regexp {^(\d+)/(\d+),?$} $frac -> num denom]} { - lappend fracs $num $denom - } else { - return -code error "$frac is not a supported fraction" - } - } - if {![llength $fracs]} { - return -code error "need at least one fraction" - } + set fracs {} + foreach frac $fractions { + if {[regexp {^(\d+)/(\d+),?$} $frac -> num denom]} { + lappend fracs $num $denom + } else { + return -code error "$frac is not a supported fraction" + } + } + if {![llength $fracs]} { + return -code error "need at least one fraction" + } } method execute {n {steps 15}} { - set co [coroutine [incr nco] my Generate $n] - for {set i 0} {$i < $steps} {incr i} { - lappend result [$co] - } - catch {rename $co ""} - return $result + set co [coroutine [incr nco] my Generate $n] + for {set i 0} {$i < $steps} {incr i} { + lappend result [$co] + } + catch {rename $co ""} + return $result } method Step {n} { - foreach {num den} $fracs { - if {$n % $den} continue - return [expr {$n * $num / $den}] - } - return -code break + foreach {num den} $fracs { + if {$n % $den} continue + return [expr {$n * $num / $den}] + } + return -code break } method Generate {n} { - yield [info coroutine] - while 1 { - yield $n - set n [my Step $n] - } - return -code break + yield [info coroutine] + while 1 { + yield $n + set n [my Step $n] + } + return -code break } } diff --git a/Task/Fractran/Tcl/fractran-2.tcl b/Task/Fractran/Tcl/fractran-2.tcl index a61af1865b..21da1ffe97 100644 --- a/Task/Fractran/Tcl/fractran-2.tcl +++ b/Task/Fractran/Tcl/fractran-2.tcl @@ -2,10 +2,10 @@ oo::objdefine $ft method pow2 {n} { set co [coroutine [incr nco] my Generate 2] set pows {} while {[llength $pows] < $n} { - set item [$co] - if {($item & ($item-1)) == 0} { - lappend pows $item - } + set item [$co] + if {($item & ($item-1)) == 0} { + lappend pows $item + } } return $pows } diff --git a/Task/Fractran/UNIX-Shell/fractran.sh b/Task/Fractran/UNIX-Shell/fractran.sh index 916bfce39b..bf28e57eb8 100644 --- a/Task/Fractran/UNIX-Shell/fractran.sh +++ b/Task/Fractran/UNIX-Shell/fractran.sh @@ -10,10 +10,10 @@ t=0 n=72 echo "steps of computation" > steps.csv while [ $t -le 6 ]; do - if [ $(($n*${ns[$t]}%${ds[$t]})) -eq 0 ]; then - let "n=$(($n*${ns[$t]}/${ds[$t]}))" - let "t=0" - factor $n >> steps.csv - fi - let "t=$t+1" + if [ $(($n*${ns[$t]}%${ds[$t]})) -eq 0 ]; then + let "n=$(($n*${ns[$t]}/${ds[$t]}))" + let "t=0" + factor $n >> steps.csv + fi + let "t=$t+1" done diff --git a/Task/Fractran/Zkl/fractran-1.zkl b/Task/Fractran/Zkl/fractran-1.zkl index ab1e3d8182..ca49aa5d7d 100644 --- a/Task/Fractran/Zkl/fractran-1.zkl +++ b/Task/Fractran/Zkl/fractran-1.zkl @@ -2,14 +2,14 @@ var fracs="17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, 77/19, 1/17," "11/13, 13/11, 15/14, 15/2, 55/1"; fcn fractranW(n,fracsAsOneBigString){ //-->Walker (iterator) fracs:=(fracsAsOneBigString-" ").split(",").apply( - fcn(frac){ frac.split("/").apply("toInt") }); //( (n,d), (n,d), ...) + fcn(frac){ frac.split("/").apply("toInt") }); //( (n,d), (n,d), ...) Walker(fcn(rn,fracs){ n:=rn.value; foreach a,b in (fracs){ - if(n*a%b == 0){ - rn.set(n*a/b); - return(n); - } + if(n*a%b == 0){ + rn.set(n*a/b); + return(n); + } } }.fp(Ref(n),fracs)) } diff --git a/Task/Fractran/Zkl/fractran-3.zkl b/Task/Fractran/Zkl/fractran-3.zkl index 00de8a061b..718365473b 100644 --- a/Task/Fractran/Zkl/fractran-3.zkl +++ b/Task/Fractran/Zkl/fractran-3.zkl @@ -2,9 +2,9 @@ var [const] BN=Import("zklBigNum"); // libGMP fcn fractranPrimes{ foreach n,fr in ([1..].zip(fractranW(BN(2),fracs))){ if(fr.num1s==1){ - p:=(fr.toString(2) - "1").len(); // count zeros - if(p>1) - println("Prime %3d from the nth Fractran(%8d): %d".fmt(p,n,fr)); + p:=(fr.toString(2) - "1").len(); // count zeros + if(p>1) + println("Prime %3d from the nth Fractran(%8d): %d".fmt(p,n,fr)); } } } diff --git a/Task/French-Republican-calendar/C++/french-republican-calendar.cpp b/Task/French-Republican-calendar/C++/french-republican-calendar.cpp new file mode 100644 index 0000000000..ec13592d10 --- /dev/null +++ b/Task/French-Republican-calendar/C++/french-republican-calendar.cpp @@ -0,0 +1,138 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +const std::vector MONTHS = { + "Vendemiaire", "Brumaire", "Frimaire", "Nivose", "Pluviose", "Ventose", "Germinal", + "Floreal", "Prairial", "Messidor", "Thermidor", "Fructidor", "Sansculottide" }; + +const std::vector SANSCULOTTIDES = { + "Fete de la vertu", "Fete du genie", "Fete du travail", + "Fete de l'opinion", "Fete des recompenses", "Fete de la Revolution" }; + +const std::vector GREGORIAN_MONTHS = { + "January", "February", "March", "April", "May", "June", "July", "August", + "September", "October", "November", "December" }; + +const std::chrono::year_month_day INTRODUCTION_DATE = + { std::chrono::year{1792}, std::chrono::month{9}, std::chrono::day{22} }; + +const std::chrono::year_month_day TERMINATION_DATE = + { std::chrono::year{1805}, std::chrono::month{12}, std::chrono::day{31} }; + +struct French_RC_Date { + uint32_t year, month, day; +}; + +std::vector split_string(const std::string& text, const char& delimiter) { + std::vector words; + std::istringstream stream(text); + std::string word; + while ( std::getline(stream, word, delimiter) ) { + words.emplace_back(word); + } + return words; +} + +uint32_t index_of(const std::vector& vec, const std::string& element) { + auto iter = std::find(vec.begin(), vec.end(), element); + return std::distance(vec.begin(), iter); +} + +uint32_t additional_days_for_year(const uint32_t& year) { + return ( year > 11 ) ? 3 : ( year > 7 ) ? 2 : ( year > 3 ) ? 1 : 0; +} + +std::string to_french_rc_date_string(French_RC_Date french_rc_date) { + if ( french_rc_date.month < 13 ) { + return std::to_string(french_rc_date.day) + " " + MONTHS[french_rc_date.month - 1] + + " " + std::to_string(french_rc_date.year); + } + return SANSCULOTTIDES[french_rc_date.day - 1] + " " + std::to_string(french_rc_date.year); +} + +std::string to_gregorian_date_string(std::chrono::year_month_day gregorian_date) { + const uint32_t year = static_cast(gregorian_date.year()); + const uint32_t month = static_cast(gregorian_date.month()); + const uint32_t day = static_cast(gregorian_date.day()); + const std::string month_string = GREGORIAN_MONTHS[month - 1]; + return std::to_string(day) + " " + month_string + " " + std::to_string(year); +} + +std::chrono::year_month_day parse_gregorian_date(const std::string& gregorian_string) { + std::vector splits = split_string(gregorian_string, ' '); + const uint32_t month = index_of(GREGORIAN_MONTHS, splits[1]) + 1; + return std::chrono::year_month_day{std::chrono::year{std::stoi(splits[2])}, + std::chrono::month{month}, std::chrono::day{static_cast(std::stoi(splits[0]))}}; +} + +French_RC_Date parse_french_rc_date(const std::string& french_rc_date) { + std::vector splits = split_string(french_rc_date, ' '); + if ( splits.size() == 3 ) { + const uint32_t year = std::stoi(splits[2]); + const uint32_t month = index_of(MONTHS, splits[1]) + 1; + const uint32_t day = std::stoi(splits[0]); + return French_RC_Date(year, month, day); + } + + std::string year_string = splits[splits.size() - 1]; + const uint32_t year = std::stoi(year_string); + std::string sansculottides_day = french_rc_date.substr(0, french_rc_date.size() - year_string.size() - 1); + const uint32_t day = index_of(SANSCULOTTIDES, sansculottides_day) + 1; + return French_RC_Date(year, 13, day); +} + +French_RC_Date to_french_rc_date(const std::chrono::year_month_day& gregorian_date) { + const int32_t days_before = + ( std::chrono::sys_days(TERMINATION_DATE) - std::chrono::sys_days(gregorian_date) ).count(); + const int32_t days_after = + ( std::chrono::sys_days(gregorian_date) - std::chrono::sys_days(INTRODUCTION_DATE) ).count(); + if ( days_after < 0 || days_before < 0 ) { + throw std::invalid_argument("French Republican Calendar date out of range."); + } + + uint32_t year = ( days_after + 366 ) / 365; + uint32_t days = ( days_after + 366 ) % 365 - additional_days_for_year(year); + if ( days == 0 ) { + year -= 1; + days += 366; + } + + if ( days < 361 ) { + return French_RC_Date(year, days / 30 + 1, days % 30); + } + return French_RC_Date(year, 13, days - 360); +} + +std::chrono::year_month_day to_gregorian_date(French_RC_Date french_rc_date) { + const uint32_t days = ( french_rc_date.year - 1 ) * 365 + additional_days_for_year(french_rc_date.year) + + ( french_rc_date.month - 1 ) * 30 + french_rc_date.day - 1; + return std::chrono::sys_days(INTRODUCTION_DATE) + std::chrono::days(days); +} + +int main() { + std::vector gregorian_strings = { + "22 September 1792", "20 May 1795", "15 July 1799", "23 September 1803", "31 December 1805" }; + + std::vector french_rc_strings = { }; + for ( const std::string& gregorian_string : gregorian_strings ) { + std::chrono::year_month_day gregorian_date = parse_gregorian_date(gregorian_string); + French_RC_Date french_rc_date = to_french_rc_date(gregorian_date); + const std::string french_rc_date_string = to_french_rc_date_string(french_rc_date); + french_rc_strings.emplace_back(french_rc_date_string); + std::cout << gregorian_string << " => " << french_rc_date_string << "\n"; + } + std::cout << "\n"; + + for ( const std::string& french_rc_string : french_rc_strings ) { + French_RC_Date french_rc_date = parse_french_rc_date(french_rc_string); + std::chrono::year_month_day gregorian_date = to_gregorian_date(french_rc_date); + const std::string gregorian_date_string = to_gregorian_date_string(gregorian_date); + std::cout << french_rc_string << " => " << gregorian_date_string << "\n"; + } +} diff --git a/Task/French-Republican-calendar/EasyLang/french-republican-calendar.easy b/Task/French-Republican-calendar/EasyLang/french-republican-calendar.easy new file mode 100644 index 0000000000..cd5d943873 --- /dev/null +++ b/Task/French-Republican-calendar/EasyLang/french-republican-calendar.easy @@ -0,0 +1,99 @@ +func repLeap y . + return if (y + 1) mod 4 = 0 and ((y + 1) mod 100 <> 0 or (y + 1) mod 400 = 0) +. +func greLeap y . + return if y mod 4 = 0 and y mod 100 <> 0 or y mod 400 = 0 +. +gregmd[] = [ 31 28 31 30 31 30 31 31 30 31 30 31 ] +greg$[] = [ "January" "February" "March" "April" "May" "June" "July" "August" "September", "October" "November" "December" ] +repu$[] = [ "Vendémiaire" "Brumaire" "Frimaire" "Nivôse" "Pluviôse" "Ventôse" "Germinal" "Floréal" "Prairial" "Messidor" "Thermidor" "Fructidor" "Sansculottide" ] +sanscu$[] = [ "Fête de la vertu" "Fête du génie" "Fête du travail" "Fête de l'opinion" "Fête des récompenses" "Fête de la Révolution" ] +proc split s$ &d &m &y . + if substr s$ 1 4 = "Fête" + m = 13 + for d to len sanscu$[] + sc$ = sanscu$[d] + if substr s$ 1 len sc$ = sc$ + y = number substr s$ (len sc$ + 1) 99 + break 1 + . + . + else + h = strpos s$ " " + d = number substr s$ 1 h + my$ = substr s$ (h + 1) 99 + h = strpos my$ " " + m$ = substr my$ 1 (h - 1) + y = number substr my$ (h + 1) 99 + months$[] = greg$[] + if y < 1792 : months$[] = repu$[] + for m to 12 : if months$[m] = m$ : break 1 + . +. +func greToDay d m y . + if m < 3 + y -= 1 + m += 12 + . + return y * 36525 div 100 - y div 100 + y div 400 + 306 * (m + 1) div 10 + d - 654842 +. +func repToDay d m y . + if m = 13 + m -= 1 + d += 30 + . + d -= repLeap y + return 365 * y + (y + 1) div 4 - (y + 1) div 100 + (y + 1) div 400 + 30 * m + d - 395 +. +proc dayToGre day &d &m &y . + y = day * 100 div 36525 + d = day - y * 36525 div 100 + 21 + y += 1792 + d += y div 100 - y div 400 - 13 + m = 9 + while d > gregmd[m] + d -= gregmd[m] + m += 1 + if m = 13 + m = 1 + y += 1 + gregmd[2] = 28 + greLeap y + . + . +. +proc dayToRep day &d &m &y . + y = (day - 1) * 100 div 36525 + if repLeap y = 1 : y -= 1 + y += 1 + d = day - y * 36525 div 100 + 365 + y div 100 - y div 400 + m = 1 + sanscul = 5 + repLeap y + while d > 30 + d -= 30 + m += 1 + if m = 13 + if d > sanscul + d -= sanscul + m = 1 + y += 1 + sanscul = 5 + repLeap y + . + . + . +. +test$[] = [ "1 Vendémiaire 1" "1 Prairial 3" "27 Messidor 7" "Fête de la Révolution 11" "10 Nivôse 14" "22 September 1792" "20 May 1795" "15 July 1799" "23 September 1803" "31 December 1805" ] +for s$ in test$[] + write s$ & " => " + split s$ day, month, year + if year < 1792 + dayToGre (repToDay day month year) day month year + print day & " " & greg$[month] & " " & year + else + dayToRep (greToDay day month year) day month year + if month = 13 + print sanscu$[day] & " " & year + else + print day & " " & repu$[month] & " " & year + . + . +. diff --git a/Task/French-Republican-calendar/Fortran/french-republican-calendar.f b/Task/French-Republican-calendar/Fortran/french-republican-calendar.f new file mode 100644 index 0000000000..b5705acc4f --- /dev/null +++ b/Task/French-Republican-calendar/Fortran/french-republican-calendar.f @@ -0,0 +1,338 @@ +program calendar_converter + implicit none + + character(len=40) :: input_date,tstring + integer :: year, month, day, jd, i + logical :: is_gregorian +! + ! Test date arrays + character(len=*), parameter :: rep_dates(5) = [ & + '1 Vendemiaire 1 ', & + '1 Prairial 3 ', & + '27 Messidor 7 ', & + 'Fete de la Revolution 11 ', & + '10 Nivose 14 ' ] + + character(len=*), parameter :: greg_dates(5) = [ & + '22 September 1792 ', & + '20 May 1795 ', & + '15 July 1799 ', & + '23 September 1803 ', & + '31 December 1805 ' ] + do + print *, "Enter date (format examples):" + print *, "Gregorian: '20 May 1795' or Republican: '1 Prairial 3'" + print *, "Press Enter to exit" + read (*, '(a)') input_date + input_date = to_lower(input_date) + + if (len_trim(input_date) == 0) exit + + ! Try parsing as Gregorian first + if (parse_gregorian(input_date, year, month, day)) then + is_gregorian = .true. + else if (parse_republican(input_date, year, month, day)) then + is_gregorian = .false. + else + print *, "Invalid date format" + cycle + end if + + if (is_gregorian) then + jd = gregorian_to_jd(year, month, day) + call jd_to_republican(jd, year, month, day) + print *, "Republican date: ", republican_date_string(year, month, day) + else + jd = republican_to_jd(year, month, day) + call jd_to_gregorian(jd, year, month, day) + print *, "Gregorian date: ", gregorian_date_string(year, month, day) + end if + end do + + + ! Automatic conversions when exiting + print *, 'Converting predefined Republican dates:' + do i = 1, size(rep_dates) + tstring = to_lower(rep_dates(i)) + if (parse_republican(trim(tstring), year, month, day)) then + jd = republican_to_jd(year, month, day) + call jd_to_gregorian(jd, year, month, day) + print *, rep_dates(i), ' => ', gregorian_date_string(year, month, day) + end if + end do + + print '(/,a)','Converting predefined Gregorian dates:' + do i = 1, size(greg_dates) + tstring = to_lower(greg_dates(i)) + if (parse_gregorian(trim(tstring), year, month, day)) then + jd = gregorian_to_jd(year, month, day) + call jd_to_republican(jd, year, month, day) + print *, greg_dates(i), ' => ', republican_date_string(year, month, day) + end if + end do + +contains + + function parse_gregorian(str, y, m, d) result(success) + character(*), intent(in) :: str + integer, intent(out) :: y, m, d + logical :: success + character(len=3) :: mon + integer :: ios + + read(str, *, iostat=ios) d, mon, y + if (ios == 0) then + m = month_number(mon) + success = (m > 0) + else + success = .false. + end if + end function parse_gregorian + + function parse_republican(str, y, m, d) result(success) + character(*), intent(in) :: str + integer, intent(out) :: y, m, d + logical :: success + character(len=35) :: tokens(10) + integer :: num_tokens, i, ios + character(len=100) :: festival_name + + success = .false. + tokens = ' ' + call tokenize(str, tokens, num_tokens) + + if (num_tokens < 2) return + + if (.not. is_numeric(tokens(num_tokens))) return + read(tokens(num_tokens), *, iostat=ios) y + if (ios /= 0) return + + if (num_tokens == 3) then + if (.not. is_numeric(tokens(1))) return + read(tokens(1), *, iostat=ios) d + if (ios /= 0) return + + do m = 1, 12 + if (trim(tokens(2)) == republican_months(m)) then + success = .true. + return + end if + end do + else if (num_tokens >= 4) then + if (tokens(1) /= 'fete') return + + festival_name = tokens(1) + do i = 2, num_tokens-1 + festival_name = festival_name(1:len_trim(festival_name)) // ' ' // tokens(i) + end do + do i = 1, 6 + if (festival_name == sansculottides(i)) then + m = 13 + d = i + success = .true. + return + end if + end do + end if + end function parse_republican + + function to_lower(str) result(lower_str) + character(*), intent(in) :: str + character(len(str)) :: lower_str + integer :: i, c + lower_str = str + do i = 1, len(str) + c = iachar(str(i:i)) + if (c >= 65 .and. c <= 90) lower_str(i:i) = achar(c + 32) + end do + end function to_lower + + subroutine tokenize(input_string, tokens, num_tokens) + character(*), intent(in) :: input_string + character(*), intent(out) :: tokens(:) + integer, intent(out) :: num_tokens + integer :: i, start_idx, end_idx, str_len + character(len=len(input_string)) :: temp_str + + num_tokens = 0 + temp_str = adjustl(input_string) + str_len = len_trim(temp_str) + if (str_len == 0) return + + start_idx = 1 + do i = 1, str_len + if (scan(temp_str(i:i), " -/,.") > 0) then + end_idx = i - 1 + if (end_idx >= start_idx) then + num_tokens = num_tokens + 1 + if (num_tokens > size(tokens)) exit + tokens(num_tokens) = temp_str(start_idx:end_idx) + end if + start_idx = i + 1 + end if + end do + + if (start_idx <= str_len) then + num_tokens = num_tokens + 1 + if (num_tokens <= size(tokens)) then + tokens(num_tokens) = temp_str(start_idx:) + end if + end if + end subroutine tokenize + + function is_numeric(str) result(res) + character(*), intent(in) :: str + logical :: res + integer :: ios + integer :: dummy + read(str, *, iostat=ios) dummy + res = (ios == 0) + end function is_numeric + + function republican_months(m) result(namer) + integer, intent(in) :: m + character(len=12) :: namer + character(len=12), parameter :: names(13) = [character(len=12):: & + 'vendemiaire ', 'brumaire ', 'frimaire ', 'nivose ', & + 'pluviose ', 'ventose ', 'germinal ', 'floreal ', & + 'prairial ', 'messidor ', 'thermidor ', 'fructidor ', & + 'sansculott' ] + namer = names(m) + end function republican_months + + function sansculottides(d) result(name) + integer, intent(in) :: d + character(len=21) :: name + character(len=21), parameter :: names(6) = [ character(len=21)::& + 'fete de la vertu ', 'fete du genie ', & + 'fete du travail ', 'fete de l''opinion ', & + 'fete des recompenses', 'fete de la revolution' ] + name = names(d) + end function sansculottides + + function gregorian_date_string(y, m, d) result(str) + integer, intent(in) :: y, m, d + character(len=21) :: str + write(str, '(i0, 1x, a, 1x, i0)') d, trim(gregorian_months(m)), y + end function gregorian_date_string + + function republican_date_string(y, m, d) result(str) + integer, intent(in) :: y, m, d + character(len=30) :: str + character(len=30) :: holder + if (m == 13) then + holder = uppercasefirst(trim(sansculottides(d))) + write(str, '(a, 1x, i0)') trim(holder), y + else + holder = uppercasefirst(trim(republican_months(m))) + write(str, '(i0, 1x, a, 1x, i0)') d, trim(holder), y + end if + end function republican_date_string + + function month_number(mon) result(m) + character(*), intent(in) :: mon + integer :: m + character(len=3) :: months(12) = ['jan','feb','mar','apr','may','jun', & + 'jul','aug','sep','oct','nov','dec'] + do m = 1, 12 + if (months(m) == mon) return + end do + m = 0 + end function month_number + + function gregorian_months(m) result(name) + integer, intent(in) :: m + character(len=3) :: name + character(len=3) :: names(12) = ['Jan','Feb','Mar','Apr','May','Jun', & + 'Jul','Aug','Sep','Oct','Nov','Dec'] + name = names(m) + end function gregorian_months + + function republican_to_jd(year, month, day) result(jd) + integer, intent(in) :: year, month, day + integer :: jd + integer, parameter :: epoch_jd = 2375840 + integer :: total_days, leap_years, y + + if (month < 1 .or. month > 13) error stop "Invalid Republican month" + if (day < 1 .or. (month < 13 .and. day > 30)) error stop "Invalid Republican day" + if (month == 13 .and. day > 6) error stop "Invalid Sansculottides day" + + total_days = (year - 1) * 365 + (month - 1) * 30 + (day - 1) + leap_years = count([(is_republican_leap(y), y = 1, year-1)]) + total_days = total_days + leap_years + jd = epoch_jd + total_days + end function republican_to_jd + + integer function gregorian_to_jd(year, month, day) + integer, intent(in) :: year, month, day + integer :: a, y, m + a = (14 - month) / 12 + y = year + 4800 - a + m = month + 12*a - 3 + gregorian_to_jd = day + ((153*m + 2)/5) + 365*y + y/4 - y/100 + y/400 - 32045 + end function gregorian_to_jd + + pure logical function is_republican_leap(y) + integer, intent(in) :: y + integer, parameter :: historical_leaps(*) = [3, 7, 11, 15, 20] + is_republican_leap = any(historical_leaps == y) + end function is_republican_leap + + subroutine jd_to_gregorian(jd, year, month, day) + integer, intent(in) :: jd + integer, intent(out) :: year, month, day + integer :: a, b, c, d, e, m + a = jd + 32044 + b = (4*a + 3)/146097 + c = a - (146097*b)/4 + d = (4*c + 3)/1461 + e = c - (1461*d)/4 + m = (5*e + 2)/153 + day = int(e - (153*m + 2)/5 + 1) + month = int(m + 3 - 12*(m/10)) + year = int(100*b + d - 4800 + (m/10)) + end subroutine jd_to_gregorian + + subroutine jd_to_republican(jd, year, month, day) + integer, intent(out) :: year, month, day + integer, intent(in) :: jd + integer, parameter :: epoch_jd = 2375840 + integer :: days_since_epoch, y, leap_days, d + + days_since_epoch = jd - epoch_jd + if (days_since_epoch < 0) error stop "Date before Republican epoch" + + year = 1 + days_since_epoch / 365 + leap_days = count([(is_republican_leap(y), y = 1, year-1)]) + + d = days_since_epoch - (year-1)*365 - leap_days + if (d < 0) then + year = year - 1 + leap_days = count([(is_republican_leap(y), y = 1, year-1)]) + d = days_since_epoch - (year-1)*365 - leap_days + end if + + if (d < 360) then + month = d/30 + 1 + day = mod(d,30) + 1 + else + month = 13 + day = d - 359 + end if + end subroutine jd_to_republican + + function uppercasefirst(str) result(result_str) + character(len=*), intent(in) :: str + character(len=len(str)) :: result_str + integer :: c + result_str = str + if (len_trim(str) > 0) then + c = iachar(str(1:1)) + if (c >= iachar('a') .and. c <= iachar('z')) then + result_str(1:1) = achar(c - 32) + end if + end if + end function uppercasefirst + +end program calendar_converter diff --git a/Task/French-Republican-calendar/Java/french-republican-calendar.java b/Task/French-Republican-calendar/Java/french-republican-calendar.java new file mode 100644 index 0000000000..64d0ca9aa4 --- /dev/null +++ b/Task/French-Republican-calendar/Java/french-republican-calendar.java @@ -0,0 +1,106 @@ +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.List; + +public final class FrenchRepublicanCalendar { + + public static void main(String[] args) { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d MMMM yyyy"); + + List gregorianStrings = List.of( + "22 September 1792", "20 May 1795", "15 July 1799", "23 September 1803", "31 December 1805" ); + + List frenchRCStrings = new ArrayList(); + for ( String gregorianString : gregorianStrings ) { + LocalDate gregorianDate = LocalDate.parse(gregorianString, formatter); + FrenchRCDate frenchRCDate = FrenchRCDate.toFrenchRCDate(gregorianDate); + frenchRCStrings.addLast(frenchRCDate.toString()); + System.out.println(gregorianString + " => " + frenchRCDate); + } + System.out.println(); + + for ( String frenchRCString : frenchRCStrings ) { + FrenchRCDate frenchRCDate = FrenchRCDate.parse(frenchRCString); + String gregorianDate = formatter.format(frenchRCDate.toGregorianDate()); + System.out.println(frenchRCString + " => " + gregorianDate); + } + } + +} + +final class FrenchRCDate { + + public FrenchRCDate(int aYear, int aMonth, int aDay) { + year = aYear; month = aMonth; day = aDay; + } + + public LocalDate toGregorianDate() { + final int days = ( year - 1 ) * 365 + additionalDaysForYear(year) + ( month - 1 ) * 30 + day - 1; + return INTRODUCTION_DATE.plusDays(days); + } + + public String toString() { + if ( month < 13 ) { + return day + " " + MONTHS.get(month - 1) + " " + year; + } + return SANSCULOTTIDES.get(day - 1) + " " + year; + } + + public static FrenchRCDate toFrenchRCDate(LocalDate gregorianDate) { + final int daysBefore = (int) ChronoUnit.DAYS.between(gregorianDate, TERMINATION_DATE); + final int daysAfter = (int) ChronoUnit.DAYS.between(INTRODUCTION_DATE, gregorianDate); + if ( daysAfter < 0 || daysBefore < 0 ) { + throw new IllegalArgumentException("French Republican Calendar date out of range."); + } + + int year = ( daysAfter + 366 ) / 365; + int days = ( daysAfter + 366 ) % 365 - additionalDaysForYear(year); + if ( days < 1 ) { + year -= 1; + days += 366; + } + + if ( days < 361 ) { + return new FrenchRCDate(year, days / 30 + 1, days % 30); + } + return new FrenchRCDate(year, 13, days - 360); + } + + public static FrenchRCDate parse(String frenchRCDate) { + String[] splits = frenchRCDate.split(" "); + if ( splits.length == 3 ) { + final int year = Integer.valueOf(splits[2]); + final int month = MONTHS.indexOf(splits[1]) + 1; + final int day = Integer.valueOf(splits[0]); + return new FrenchRCDate(year, month, day); + } + + String yearString = splits[splits.length - 1]; + final int year = Integer.valueOf(yearString); + String sansculottidesDay = frenchRCDate.substring(0, frenchRCDate.lastIndexOf(" ")); + final int day = SANSCULOTTIDES.indexOf(sansculottidesDay) + 1; + return new FrenchRCDate(year, 13, day); + } + + public static int additionalDaysForYear(int year) { + return ( year > 11 ) ? 3 : ( year > 7 ) ? 2 : ( year > 3 ) ? 1 : 0; + } + + public static final LocalDate INTRODUCTION_DATE = LocalDate.of(1792, 9, 22); + public static final LocalDate TERMINATION_DATE = LocalDate.of(1805, 12, 31); + + private int year, month, day; + + private static final List MONTHS = List.of( + "Vendémiaire", "Brumaire", "Frimaire", "Nivôse", "Pluviôse", "Ventôse", "Germinal", + "Floréal", "Prairial", "Messidor", "Thermidor", "Fructidor", "Sansculottide" + ); + + private static final List SANSCULOTTIDES = List.of( + "Fête de la vertu", "Fête du génie", "Fête du travail", + "Fête de l'opinion", "Fête des récompenses", "Fête de la Révolution" + ); + +} diff --git a/Task/French-Republican-calendar/JavaScript/french-republican-calendar.js b/Task/French-Republican-calendar/JavaScript/french-republican-calendar.js new file mode 100644 index 0000000000..5abfc4a5ff --- /dev/null +++ b/Task/French-Republican-calendar/JavaScript/french-republican-calendar.js @@ -0,0 +1,130 @@ +class FrenchRCDate { + constructor(year, month, day) { + this.year = year; + this.month = month; + this.day = day; + } + + static INTRODUCTION_DATE = new Date(Date.UTC(1792, 8, 22)); // Months are zero-indexed in JS + static TERMINATION_DATE = new Date(Date.UTC(1805, 11, 31)); + + static MONTHS = [ + "Vendémiaire", "Brumaire", "Frimaire", "Nivôse", "Pluviôse", "Ventôse", + "Germinal", "Floréal", "Prairial", "Messidor", "Thermidor", "Fructidor" + ]; + + static SANSCULOTTIDES = [ + "Fête de la vertu", "Fête du génie", "Fête du travail", + "Fête de l'opinion", "Fête des récompenses", "Fête de la Révolution" + ]; + + toGregorianDate() { + const days = (this.year - 1) * 365 + FrenchRCDate.additionalDaysForYear(this.year) + + (this.month - 1) * 30 + this.day - 1; + + const gregorian = new Date(FrenchRCDate.INTRODUCTION_DATE); + gregorian.setUTCDate(gregorian.getUTCDate() + days); + return gregorian; + } + + toString() { + if (this.month < 13) { + return `${this.day} ${FrenchRCDate.MONTHS[this.month - 1]} ${this.year}`; + } else { + return `${FrenchRCDate.SANSCULOTTIDES[this.day - 1]} ${this.year}`; + } + } + + static additionalDaysForYear(year) { + return year > 11 ? 3 : year > 7 ? 2 : year > 3 ? 1 : 0; + } + + static toFrenchRCDate(gregorianDate) { + const daysAfter = Math.floor((gregorianDate - FrenchRCDate.INTRODUCTION_DATE) / (1000 * 60 * 60 * 24)); + const daysBefore = Math.floor((FrenchRCDate.TERMINATION_DATE - gregorianDate) / (1000 * 60 * 60 * 24)); + + if (daysAfter < 0 || daysBefore < 0) { + throw new Error("French Republican Calendar date out of range."); + } + + let year = Math.floor((daysAfter + 366) / 365); + let days = (daysAfter + 366) % 365 - FrenchRCDate.additionalDaysForYear(year); + + if (days < 1) { + year -= 1; + days += 366; + } + + if (days < 361) { + const month = Math.floor(days / 30) + 1; + const day = days % 30 || 30; + return new FrenchRCDate(year, month, day); + } else { + const day = days - 360; + return new FrenchRCDate(year, 13, day); + } + } + + static parse(frenchRCDateString) { + const parts = frenchRCDateString.trim().split(/\s+/); + if (parts.length === 3) { + const [dayStr, monthStr, yearStr] = parts; + const year = parseInt(yearStr, 10); + const month = FrenchRCDate.MONTHS.indexOf(monthStr) + 1; + const day = parseInt(dayStr, 10); + return new FrenchRCDate(year, month, day); + } else { + const yearStr = parts[parts.length - 1]; + const year = parseInt(yearStr, 10); + const sansculottideName = parts.slice(0, -1).join(" "); + const day = FrenchRCDate.SANSCULOTTIDES.indexOf(sansculottideName) + 1; + return new FrenchRCDate(year, 13, day); + } + } +} + +// Helper to format dates like "d MMMM yyyy" +function formatDate(date) { + const months = [ + "January", "February", "March", "April", "May", "June", + "July", "August", "September", "October", "November", "December" + ]; + const day = date.getUTCDate(); + const month = months[date.getUTCMonth()]; + const year = date.getUTCFullYear(); + return `${day} ${month} ${year}`; +} + +// Main logic +const gregorianStrings = [ + "22 September 1792", + "20 May 1795", + "15 July 1799", + "23 September 1803", + "31 December 1805" +]; + +const frenchRCStrings = []; + +for (const gregorianString of gregorianStrings) { + // Parse into JS Date object + const [day, month, year] = gregorianString.split(" "); + const monthIndex = [ + "January", "February", "March", "April", "May", "June", + "July", "August", "September", "October", "November", "December" + ].indexOf(month); + const gregorianDate = new Date(Date.UTC(parseInt(year), monthIndex, parseInt(day))); + + const frenchRCDate = FrenchRCDate.toFrenchRCDate(gregorianDate); + const frenchRCString = frenchRCDate.toString(); + frenchRCStrings.push(frenchRCString); + console.log(`${gregorianString} => ${frenchRCString}`); +} + +console.log(); + +for (const frenchRCString of frenchRCStrings) { + const frenchRCDate = FrenchRCDate.parse(frenchRCString); + const gregorianDate = frenchRCDate.toGregorianDate(); + console.log(`${frenchRCString} => ${formatDate(gregorianDate)}`); +} diff --git a/Task/French-Republican-calendar/Jq/french-republican-calendar.jq b/Task/French-Republican-calendar/Jq/french-republican-calendar.jq new file mode 100644 index 0000000000..dde45845bc --- /dev/null +++ b/Task/French-Republican-calendar/Jq/french-republican-calendar.jq @@ -0,0 +1,149 @@ +include "Date" {search: "."}; + +### Generic functions + +def assertEq($p;$q): + if $p == $q + then . + else debug("assertion violation: \($p) != \($q)") as $debug | . + end; + +def lpad($len): tostring | ($len - length) as $l | (" " * $l) + .; + +def trim: sub("^ *";"") | sub(" *$";""); + +# Input: string such as "12 Mar 2012" +# Output: Date +def parseDayMonthYear: + def months: + {Jan:1, Feb:2, Mar:3, Apr: 4, May: 5, Jun: 6, + Jul:7, Aug:8, Sep:9, Oct:10, Nov:11, Dec:12}; + capture("(?[0-9]+) *(?[A-Za-z]+) *(?[0-9]+)") + | .month |= months[ .[:3] ] + | map_values(tonumber) + | {year, month, day}; + +### French Republican Calendar (FRC) + +def introductionDate: Date(1792; 9; 22); + +# Use the 'continuous method' for years after 1805 +def isLeapYearFRC: + (. + 1) + | (. % 4 == 0) and ((. % 100 != 0) or (. % 400 == 0)); + +# If the numbers $year, $month, and $day specify a valid date +# in the French Republican Calendar, then emit {$year, $month, $day}; +# otherwise generate an informative error message. +def FrenchRCDate($year; $month; $day): + def err(msg): "Invalid date (\(msg)): FrenchRCDate(\($year); \($month); \($day))" | error; + if ($year <= 0 or $month < 1 or $month > 13) then err(if $year <= 0 then "year" else "month" end) end + | if $month < 13 + then if $day < 1 or $day > 30 then err("day") end + else ($year | isLeapYearFRC) as $leap + | if $leap and ($day < 1 or $day > 6) then err("invalid day in leap year") end + | if ($leap|not) and ($day < 1 or $day > 5) then err("invalid day in non-leap year") end + end + | {$year, $month, $day}; + +# for convenience we treat 'Sansculottide' as an extra month with 5 or 6 days +def months: + ["Vendémiaire", "Brumaire", "Frimaire", "Nivôse", "Pluviôse", "Ventôse", "Germinal", + "Floréal", "Prairial", "Messidor", "Thermidor", "Fructidor", "Sansculottide"] ; + +def intercal: + ["Fête de la vertu", "Fête du génie", "Fête du travail", + "Fête de l'opinion", "Fête des récompenses", "Fête de la Révolution"]; + +# Input: a string specifying a FRC date +def parse: + . as $frcDate + | (trim|split(" ")) as $splits + | if $splits|length == 3 + then (months | index($splits[1]) + 1) as $month + | if $month < 1 or $month > 13 then "Invalid month." | error end + | ($splits[2]|tonumber) as $year + | if $year < 1 then "Invalid year." | error end + | (if ($month < 13) then 30 elif $year|isLeapYearFRC then 6 else 5 end) as $monthLength + | ($splits[0] | tonumber) as $day + | if $day < 1 or $day > $monthLength then "Invalid day." | error end + | FrenchRCDate($year; $month; $day) + + elif ($splits|length | IN(4,5)) + then $splits[-1] as $yearStr + | ($yearStr|tonumber) as $year + | if $year < 1 then "Invalid year." | error end + | ($frcDate | trim[0: -($yearStr|length + 1)] ) as $scDay + | (intercal | index($scDay) + 1) as $day + | (if $year | isLeapYearFRC then 6 else 5 end) as $maxDay + | if $day < 1 or $day > $maxDay then "Invalid day." | error end + | FrenchRCDate($year; 13; $day) + else "Invalid French Republican date." | error + end +; + +# Input: Date (Gregorian) +# Output: +def fromLocalDate: + # $start and $finish should be two Date objects + def daysFrom($start; $finish): + ($finish|daysBeforeDate) - ($start|daysBeforeDate); + + (daysFrom(introductionDate; .) + 1) as $daysDiff + | if ($daysDiff <= 0) then "Date can't be before 22 September 1792." | error end + | {year: 1, startDay: 1} + | until(.done; + (.startDay + (if .year|isLeapYearFRC then 365 else 364 end)) as $endDay + | if ($daysDiff >= .startDay and $daysDiff <= $endDay) then .done = true + else .year += 1 + | .startDay = $endDay + 1 + end ) + | ($daysDiff - .startDay) as $remDays + | (($remDays / 30)|floor) as $month + | ($remDays - $month * 30) as $day + | FrenchRCDate(.year; $month + 1; $day + 1) +; + +# Input: an FRC Date +def toString: + if .month < 13 then "\(.day) \(months[.month - 1]) \(.year)" + else "\(intercal[.day - 1]) \(.year)" + end; + +# Input: an FRC Date +def toLocalDate: + (reduce range(1; .year) as $i (0; . + (if $i|isLeapYearFRC then 366 else 365 end))) as $sumDays + | ((.month - 1) * 30 + .day - 1) as $dayInYear + | introductionDate | addDays($sumDays + $dayInYear) ; + + +### Examples + +def dates: [ + "22 September 1792", "20 May 1795", "15 July 1799", "23 September 1803", + "31 December 1805", "18 March 1871", "25 August 1944", "19 September 2016", + "22 September 2017", "28 September 2017" +]; + +def task: + def format: + "\(.day) \(monthNames[.month]) \(.year)"; + + dates as $dates + | reduce range(0; $dates|length) as $i ({}; + .date = $dates[$i] + | .thisDate = (.date|parseDayMonthYear) + | .frcd = (.thisDate|fromLocalDate) + | .frcDates[$i] = (.frcd|toString) + | .emit += "\(.date|lpad(26)) => \(.frcDates[$i])\n") + | .emit, + + # now process the other way around + range(0; $dates|length) as $i + | .frcDates[$i] as $frcDate + | ($frcDate|parse|toLocalDate|format) as $lds + | assertEq($dates[$i]; $lds) + | "\($frcDate|lpad(26)) => \($lds)" +; + +task diff --git a/Task/French-Republican-calendar/Julia/french-republican-calendar.julia b/Task/French-Republican-calendar/Julia/french-republican-calendar.jl similarity index 100% rename from Task/French-Republican-calendar/Julia/french-republican-calendar.julia rename to Task/French-Republican-calendar/Julia/french-republican-calendar.jl diff --git a/Task/French-Republican-calendar/Kotlin/french-republican-calendar.kotlin b/Task/French-Republican-calendar/Kotlin/french-republican-calendar.kts similarity index 100% rename from Task/French-Republican-calendar/Kotlin/french-republican-calendar.kotlin rename to Task/French-Republican-calendar/Kotlin/french-republican-calendar.kts diff --git a/Task/French-Republican-calendar/Rust/french-republican-calendar.rs b/Task/French-Republican-calendar/Rust/french-republican-calendar.rs new file mode 100644 index 0000000000..873b6c090d --- /dev/null +++ b/Task/French-Republican-calendar/Rust/french-republican-calendar.rs @@ -0,0 +1,177 @@ +use chrono::{Datelike, Duration, NaiveDate}; + +const MONTHS: [&str; 13] = [ + "Vendemiaire", "Brumaire", "Frimaire", "Nivose", "Pluviose", "Ventose", "Germinal", + "Floreal", "Prairial", "Messidor", "Thermidor", "Fructidor", "Sansculottide", +]; + +const SANSCULOTTIDES: [&str; 6] = [ + "Fete de la vertu", "Fete du genie", "Fete du travail", + "Fete de l'opinion", "Fete des recompenses", "Fete de la Revolution", +]; + +const GREGORIAN_MONTHS: [&str; 12] = [ + "January", "February", "March", "April", "May", "June", "July", "August", + "September", "October", "November", "December", +]; + +const INTRODUCTION_DATE: NaiveDate = match NaiveDate::from_ymd_opt(1792, 9, 22) { + Some(date) => date, + None => panic!("Invalid introduction date"), +}; + +const TERMINATION_DATE: NaiveDate = match NaiveDate::from_ymd_opt(1805, 12, 31) { + Some(date) => date, + None => panic!("Invalid termination date"), +}; + +#[derive(Debug, Clone, Copy)] +struct FrenchRcDate { + year: u32, + month: u32, + day: u32, +} + +fn split_string(text: &str, delimiter: char) -> Vec<&str> { + text.split(delimiter).collect() +} + +fn index_of(vec: &[&str], element: &str) -> u32 { + vec.iter() + .position(|&x| x == element) + .map(|i| i as u32) + .unwrap_or_else(|| panic!("Element not found: {}", element)) +} + +fn additional_days_for_year(year: u32) -> u32 { + if year > 11 { + 3 + } else if year > 7 { + 2 + } else if year > 3 { + 1 + } else { + 0 + } +} + +fn to_french_rc_date_string(french_rc_date: FrenchRcDate) -> String { + if french_rc_date.month < 13 { + format!( + "{} {} {}", + french_rc_date.day, MONTHS[(french_rc_date.month - 1) as usize], french_rc_date.year + ) + } else { + format!( + "{} {}", + SANSCULOTTIDES[(french_rc_date.day - 1) as usize], french_rc_date.year + ) + } +} + +fn to_gregorian_date_string(gregorian_date: NaiveDate) -> String { + let year = gregorian_date.year(); + let month = gregorian_date.month() as usize; + let day = gregorian_date.day(); + let month_string = GREGORIAN_MONTHS[month - 1]; + format!("{} {} {}", day, month_string, year) +} + +fn parse_gregorian_date(gregorian_string: &str) -> NaiveDate { + let splits: Vec<&str> = split_string(gregorian_string, ' '); + let day: u32 = splits[0].parse().expect("Invalid day"); + let month = index_of(&GREGORIAN_MONTHS, splits[1]) + 1; + let year: i32 = splits[2].parse().expect("Invalid year"); + + NaiveDate::from_ymd_opt(year, month, day) + .unwrap_or_else(|| panic!("Invalid Gregorian date: {}", gregorian_string)) +} + +fn parse_french_rc_date(french_rc_date: &str) -> FrenchRcDate { + let splits: Vec<&str> = split_string(french_rc_date, ' '); + if splits.len() == 3 { + let day: u32 = splits[0].parse().expect("Invalid day"); + let month = index_of(&MONTHS, splits[1]) + 1; + let year: u32 = splits[2].parse().expect("Invalid year"); + FrenchRcDate { year, month, day } + } else { + let year_string = splits[splits.len() - 1]; + let year: u32 = year_string.parse().expect("Invalid year"); + let sansculottides_day = &french_rc_date[..french_rc_date.len() - year_string.len() - 1]; + let day = index_of(&SANSCULOTTIDES, sansculottides_day) + 1; + FrenchRcDate { + year, + month: 13, + day, + } + } +} + +fn to_french_rc_date(gregorian_date: NaiveDate) -> FrenchRcDate { + let days_after = (gregorian_date - INTRODUCTION_DATE).num_days(); + let days_before = (TERMINATION_DATE - gregorian_date).num_days(); + + if days_after < 0 || days_before < 0 { + panic!("French Republican Calendar date out of range."); + } + + let mut year = (days_after + 366) / 365; + let mut days = (days_after + 366) % 365 - additional_days_for_year(year as u32) as i64; + + if days == 0 { + year -= 1; + days += 366; + } + + if days < 361 { + FrenchRcDate { + year: year as u32, + month: (days / 30 + 1) as u32, + day: (days % 30) as u32, + } + } else { + FrenchRcDate { + year: year as u32, + month: 13, + day: (days - 360) as u32, + } + } +} + +fn to_gregorian_date(french_rc_date: FrenchRcDate) -> NaiveDate { + let days = (french_rc_date.year - 1) * 365 + + additional_days_for_year(french_rc_date.year) + + (french_rc_date.month - 1) * 30 + + french_rc_date.day + - 1; + INTRODUCTION_DATE + Duration::days(days as i64) +} + +fn main() { + let gregorian_strings = vec![ + "22 September 1792", + "20 May 1795", + "15 July 1799", + "23 September 1803", + "31 December 1805", + ]; + + let mut french_rc_strings = Vec::new(); + + for gregorian_string in &gregorian_strings { + let gregorian_date = parse_gregorian_date(gregorian_string); + let french_rc_date = to_french_rc_date(gregorian_date); + let french_rc_date_string = to_french_rc_date_string(french_rc_date); + french_rc_strings.push(french_rc_date_string.clone()); + println!("{} => {}", gregorian_string, french_rc_date_string); + } + + println!(); + + for french_rc_string in &french_rc_strings { + let french_rc_date = parse_french_rc_date(french_rc_string); + let gregorian_date = to_gregorian_date(french_rc_date); + let gregorian_date_string = to_gregorian_date_string(gregorian_date); + println!("{} => {}", french_rc_string, gregorian_date_string); + } +} diff --git a/Task/French-Republican-calendar/Scheme/french-republican-calendar.scm b/Task/French-Republican-calendar/Scheme/french-republican-calendar.scm new file mode 100644 index 0000000000..a60062f8fd --- /dev/null +++ b/Task/French-Republican-calendar/Scheme/french-republican-calendar.scm @@ -0,0 +1,234 @@ +; version 1 (11 Frimaire 234) +; inspired by BBC Basic +; see https://rosettacode.org/wiki/French_Republican_calendar + +(import (scheme base) (scheme char)) + +; ex: (date->jour-mois-annee '(2025 12 1)) -> 1 12 2025 +(define (date->jour-mois-annee date) + (values (list-ref date 2) (list-ref date 1) (list-ref date 0))) + +; ex: (jours-bissextiles 1900) -> 460 +(define (jours-bissextiles annee) + (- (+ (quotient annee 4) (quotient annee 400)) (quotient annee 100))) + +; ex: (bissextile? 1900) -> #f +(define (bissextile? annee) + (and (zero? (remainder annee 4)) + (or (zero? (remainder annee 400)) (positive? (remainder annee 100))))) + +; ex: (jour-bissextile 1900) -> 0 +(define (jour-bissextile annee) + (if (bissextile? annee) 1 0)) + +; ex: (gregorien->jours '(1792 9 22)) -> 1 +; ex: (gregorien->jours '(2025 12 1)) -> 85172 +(define (gregorien->jours date) + (let*-values (((jour mois annee) (date->jour-mois-annee date)) + ((mois annee) (if (< mois 3) + (values (+ mois 12) (- annee 1)) + (values mois annee)))) + (- (+ (* annee 365) + (jours-bissextiles annee) + (exact (floor (* 30.6 (+ mois 1)))) + jour) + 654842))) + +; ex: (republicain->jours '(1 1 1)) -> 1 +; ex: (republicain->jours '(2025 12 1)) -> 85172 +(define (republicain->jours date) + (let*-values (((jour mois annee) (date->jour-mois-annee date)) + ((mois jour) (if (= mois 13) + (values 12 (+ jour 30)) + (values mois jour)))) + (- (+ (* annee 365) + (* 30 mois) + (jours-bissextiles (+ annee 1)) + jour) + (jour-bissextile (+ annee 1)) + 395))) + +; ex: (jours->gregorien 1) -> (1792 9 22) +; ex: (jours->gregorien 85172) -> (2025 12 1) +(define (jours->gregorien jours) + (let* ((annee (exact (floor (/ jours 365.25)))) + (jour (+ (- jours (exact (floor (* annee 365.25)))) 21)) + (annee (+ annee 1792)) + (jour (- (+ jour (exact (quotient annee 100))) (exact (quotient annee 400)) 13))) + (let boucle ((jour jour)(mois 8)(annee annee)) + (let* ((duree-mois (vector-ref #(31 28 31 30 31 30 31 31 30 31 30 31) mois)) + (duree-mois (+ duree-mois (if (and (= mois 1) (bissextile? annee)) 1 0)))) + (if (<= jour duree-mois) + (list annee (+ mois 1) jour) + (let ((jour (- jour duree-mois)) + (mois (+ mois 1))) + (if (= mois 12) + (boucle jour 0 (+ annee 1)) + (boucle jour mois annee)))))))) + +; ex: (jours->republicain 1) -> (1 1 1) +; ex: (jours->republicain 85172) -> (234 3 11) +(define (jours->republicain jours) + (let* ((annee (exact (floor (/ jours 365.25)))) + (annee (- annee (jour-bissextile (+ annee 1)))) + (jour (- jours (exact (floor (* annee 365.25))))) + (annee (+ annee 1)) + (jour (- (+ jour (exact (quotient annee 100))) (exact (quotient annee 400))))) + (let boucle ((jour jour)(mois 1)(annee annee)) + (let ((duree-mois (if (< mois 13) 30 (+ 5 (jour-bissextile (+ annee 1)))))) + (if (<= jour duree-mois) + (list annee mois jour) + (let ((jour (- jour duree-mois)) + (mois (+ mois 1))) + (if (= mois 14) + (boucle jour 1 (+ annee 1)) + (boucle jour mois annee)))))))) + +; ex: (normalise-caractere #\E) -> #\e +; ex: (normalise-caractere #\ê) -> #\e +(define (normalise-caractere caractere) + (let* ((caractere (char-downcase caractere)) + (autre (assoc caractere '((#\é . #\e) (#\ê . #\e) (#\ô . #\o))))) + (if autre + (cdr autre) + caractere))) + +; ex: (normalise-texte "Ventôse") -> "ventose" +(define (normalise-texte texte) + (string-map normalise-caractere texte)) + +; ex: (normalise-texte '("Ventôse" "Germinal")) -> ("ventose" "germinal") +(define (normalise-liste liste) + (map normalise-texte liste)) + +(define mois-republicains '( + "Vendémiaire" "Brumaire" "Frimaire" "Nivôse" "Pluviôse" "Ventôse" + "Germinal" "Floréal" "Prairial" "Messidor" "Thermidor" "Fructidor" + "Sansculottide")) + +(define sansculottides '( + "Fête de la vertu" "Fête du génie" "Fête du travail" + "Fête de l'opinion" "Fête des récompenses" "Fête de la Révolution" )) + +(define mois-gregoriens '( + "January" "February" "March" "April" "May" "June" + "July" "August" "September" "October" "November" "December" )) + +(define mois-republicains-normal (normalise-liste mois-republicains)) + +(define sansculottides-normal (normalise-liste sansculottides)) + +(define mois-gregoriens-normal (normalise-liste mois-gregoriens)) + +; ex: (gregorien->texte '(2025 12 1)) -> "1 December 2025)" +(define (gregorien->texte date) + (string-append + (number->string (list-ref date 2)) + " " + (list-ref mois-gregoriens (- (list-ref date 1) 1)) + " " + (number->string (list-ref date 0)))) + +; ex: (republicain->texte '(2025 12 1)) -> "1 Fructidor 2025)" +; ex: (republicain->texte '(2025 13 1)) -> "Fête de la vertu 2025)" +(define (republicain->texte date) + (if (= (list-ref date 1) 13) + (string-append + (list-ref sansculottides (- (list-ref date 2) 1)) + " " + (number->string (list-ref date 0))) + (string-append + (number->string (list-ref date 2)) + " " + (list-ref mois-republicains (- (list-ref date 1) 1)) + " " + (number->string (list-ref date 0))))) + +; ex: (decompose "34 toto 78 zorro louarn 9") -> (9 "zorro louarn" 78 "toto" 34) +; ex: (decompose "10 Vendémiaire 1") -> (1 "Vendémiaire" 10) +(define (decompose texte) + (let ((texte (normalise-texte texte))) + (let boucle ((index 0)(resultat '())) + (if (>= index (string-length texte)) + resultat + (let ((caractere (string-ref texte index)) + (index (+ index 1))) + (cond + ((char-whitespace? caractere) + (boucle index resultat)) + ((char-numeric? caractere) + (let lit-nombre ((index index)(valeur (digit-value caractere))) + (let ((caractere (if (>= index (string-length texte)) + #\space + (string-ref texte index)))) + (if (char-numeric? caractere) + (lit-nombre (+ index 1) (+ (* 10 valeur) (digit-value caractere))) + (boucle index (cons valeur resultat)))))) + (else + (let lit-texte ((index index)(valeur (list caractere))) + (let ((caractere (if (>= index (string-length texte)) + #\0 + (string-ref texte index)))) + (if (char-numeric? caractere) + (let retire-espace ((valeur valeur)) + (if (char-whitespace? (car valeur)) + (retire-espace (cdr valeur)) + (boucle index (cons (list->string (reverse valeur)) resultat)))) + (lit-texte (+ index 1) (cons caractere valeur)))))))))))) + +; ex: (index-texte '("a" "b" "c") "b") -> 2 +; ex: (index-texte '("a" "b" "c") "x") -> #f +(define (index-texte liste texte) + (let ((tete (member texte liste))) + (and tete (+ 1 (- (length liste) (length tete)))))) + +; ex: (decode-date "22 September 1792") -> (gregorien 1792 9 22) +; ex: (decode-date "Fête de la Révolution 11") -> (republicain 11 13 6) +(define (decode-date texte) + (let ((decomposition (decompose texte))) + (case (length decomposition) + ((2) + (let* ((annee (list-ref decomposition 0)) + (fete (list-ref decomposition 1)) + (jour (index-texte sansculottides-normal fete))) + (and jour (number? annee) (list 'republicain annee 13 jour)))) + ((3) + (let* ((annee (list-ref decomposition 0)) + (mois (list-ref decomposition 1)) + (jour (list-ref decomposition 2)) + (mois-gregorien (index-texte mois-gregoriens-normal mois)) + (mois-republicain (index-texte mois-republicains-normal mois))) + (and (number? annee) (number? jour) + (or (and mois-gregorien (list 'gregorien annee mois-gregorien jour)) + (and mois-republicain (list 'republicain annee mois-republicain jour)))))) + (else + #f)))) + +; ex: (decode-date "22 September 1792") -> "1 Vendémiaire 1" +; ex: (decode-date "Fête de la Révolution 11") -> "23 September 1803" +(define (converti-date texte) + (let ((decodage (decode-date texte))) + (and decodage + (case (car decodage) + ((gregorien) + (republicain->texte (jours->republicain (gregorien->jours (cdr decodage))))) + ((republicain) + (gregorien->texte (jours->gregorien (republicain->jours (cdr decodage))))) + (else + #f))))) + +; validation +(for-each + (lambda (texte) + (display texte) + (display " = ") + (display (converti-date texte)) + (newline)) + '( + "1 Vendémiaire 1" "22 September 1792" + "1 Prairial 3" "20 May 1795" + "27 Messidor 7" "15 July 1799" + "Fête de la Révolution 11" "23 September 1803" + "10 Nivôse 14" "31 December 1805" + "11 Frimaire 234" "1 December 2025" + )) diff --git a/Task/Function-composition/00-META.yaml b/Task/Function-composition/00-META.yaml index bd45864d57..483655d1d4 100644 --- a/Task/Function-composition/00-META.yaml +++ b/Task/Function-composition/00-META.yaml @@ -1,3 +1,2 @@ --- from: http://rosettacode.org/wiki/Function_composition -note: Higher-order functions diff --git a/Task/Function-composition/00-TASK.txt b/Task/Function-composition/00-TASK.txt index 44f6ada3f0..8b13789179 100644 --- a/Task/Function-composition/00-TASK.txt +++ b/Task/Function-composition/00-TASK.txt @@ -1,16 +1 @@ -;Task: -Create a function, compose,   whose two arguments   ''f''   and   ''g'',   are both functions with one argument. - - -The result of compose is to be a function of one argument, (lets call the argument   ''x''),   which works like applying function   ''f''   to the result of applying function   ''g''   to   ''x''. - - -;Example: - compose(''f'', ''g'') (''x'') = ''f''(''g''(''x'')) - - -Reference: [[wp:Function composition (computer science)|Function composition]] - -Hint: In some languages, implementing compose correctly requires creating a [[wp:Closure (computer science)|closure]]. -

    diff --git a/Task/Function-composition/Ada/function-composition-1.ada b/Task/Function-composition/Ada/function-composition-1.adb similarity index 100% rename from Task/Function-composition/Ada/function-composition-1.ada rename to Task/Function-composition/Ada/function-composition-1.adb diff --git a/Task/Function-composition/Ada/function-composition-2.ada b/Task/Function-composition/Ada/function-composition-2.adb similarity index 100% rename from Task/Function-composition/Ada/function-composition-2.ada rename to Task/Function-composition/Ada/function-composition-2.adb diff --git a/Task/Function-composition/Ada/function-composition-3.ada b/Task/Function-composition/Ada/function-composition-3.adb similarity index 100% rename from Task/Function-composition/Ada/function-composition-3.ada rename to Task/Function-composition/Ada/function-composition-3.adb diff --git a/Task/Function-composition/Crystal/function-composition.crystal b/Task/Function-composition/Crystal/function-composition.cr similarity index 100% rename from Task/Function-composition/Crystal/function-composition.crystal rename to Task/Function-composition/Crystal/function-composition.cr diff --git a/Task/Function-composition/Delphi/function-composition.delphi b/Task/Function-composition/Delphi/function-composition.pas similarity index 100% rename from Task/Function-composition/Delphi/function-composition.delphi rename to Task/Function-composition/Delphi/function-composition.pas diff --git a/Task/Function-composition/Elena/function-composition.elena b/Task/Function-composition/Elena/function-composition.elena index 2361868faf..e2bfe40d6c 100644 --- a/Task/Function-composition/Elena/function-composition.elena +++ b/Task/Function-composition/Elena/function-composition.elena @@ -6,9 +6,9 @@ extension op : Func1 = (x => self(f(x))); } -public program() +public Program() { var fg := (x => x + 1).compose::(x => x * x); - console.printLine(fg(3)) + Console.printLine(fg(3)) } diff --git a/Task/Function-composition/Elixir/function-composition.elixir b/Task/Function-composition/Elixir/function-composition.ex similarity index 100% rename from Task/Function-composition/Elixir/function-composition.elixir rename to Task/Function-composition/Elixir/function-composition.ex diff --git a/Task/Function-composition/Emacs-Lisp/function-composition-1.l b/Task/Function-composition/Emacs-Lisp/function-composition-1.el similarity index 100% rename from Task/Function-composition/Emacs-Lisp/function-composition-1.l rename to Task/Function-composition/Emacs-Lisp/function-composition-1.el diff --git a/Task/Function-composition/Emacs-Lisp/function-composition-2.l b/Task/Function-composition/Emacs-Lisp/function-composition-2.el similarity index 100% rename from Task/Function-composition/Emacs-Lisp/function-composition-2.l rename to Task/Function-composition/Emacs-Lisp/function-composition-2.el diff --git a/Task/Function-composition/Emacs-Lisp/function-composition-3.l b/Task/Function-composition/Emacs-Lisp/function-composition-3.el similarity index 100% rename from Task/Function-composition/Emacs-Lisp/function-composition-3.l rename to Task/Function-composition/Emacs-Lisp/function-composition-3.el diff --git a/Task/Function-composition/FutureBasic/function-composition.basic b/Task/Function-composition/FutureBasic/function-composition.basic new file mode 100644 index 0000000000..8df8fe887d --- /dev/null +++ b/Task/Function-composition/FutureBasic/function-composition.basic @@ -0,0 +1,14 @@ +double local fn FunctionF( x as double ) +end fn = x + 1.5 + +double local fn FunctionG( x as double ) +end fn = x * x + +double local fn Compose( f as ptr, g as ptr ) + double def fn ff(x1 as double) using f + double def fn fg(x2 as double) using g +end fn = fn ff(fn fg(2.5)) + +print fn Compose( @fn FunctionF, @fn FunctionG ) + +HandleEvents diff --git a/Task/Function-composition/Julia/function-composition-1.julia b/Task/Function-composition/Julia/function-composition-1.jl similarity index 100% rename from Task/Function-composition/Julia/function-composition-1.julia rename to Task/Function-composition/Julia/function-composition-1.jl diff --git a/Task/Function-composition/Julia/function-composition-2.julia b/Task/Function-composition/Julia/function-composition-2.jl similarity index 100% rename from Task/Function-composition/Julia/function-composition-2.julia rename to Task/Function-composition/Julia/function-composition-2.jl diff --git a/Task/Function-composition/Kotlin/function-composition.kotlin b/Task/Function-composition/Kotlin/function-composition.kts similarity index 100% rename from Task/Function-composition/Kotlin/function-composition.kotlin rename to Task/Function-composition/Kotlin/function-composition.kts diff --git a/Task/Function-composition/OCaml/function-composition-1.ocaml b/Task/Function-composition/OCaml/function-composition-1.ml similarity index 100% rename from Task/Function-composition/OCaml/function-composition-1.ocaml rename to Task/Function-composition/OCaml/function-composition-1.ml diff --git a/Task/Function-composition/OCaml/function-composition-2.ocaml b/Task/Function-composition/OCaml/function-composition-2.ml similarity index 100% rename from Task/Function-composition/OCaml/function-composition-2.ocaml rename to Task/Function-composition/OCaml/function-composition-2.ml diff --git a/Task/Function-composition/Odin/function-composition.odin b/Task/Function-composition/Odin/function-composition.odin new file mode 100644 index 0000000000..bda638fa4b --- /dev/null +++ b/Task/Function-composition/Odin/function-composition.odin @@ -0,0 +1,25 @@ +package main + +import "core:fmt" +import "core:math" + +Compositor :: struct($ARG, $INTER, $RET: typeid) { + func1: #type proc "contextless" (_: ARG) -> INTER, + func2: #type proc "contextless" (_: INTER) -> RET, +} + +compose :: proc( + f: #type proc "contextless" (_: $INTER) -> $RET, + g: #type proc "contextless" (_: $ARG) -> INTER, +) -> Compositor(ARG, RET, INTER) { + return {g, f} +} + +call :: proc(c: Compositor($ARG, $INTER, $RET), arg: ARG) -> RET { + return c.func1(c.func2(arg)) +} + +main :: proc() { + comp := compose(math.sin_f64, math.asin_f64) // have to use specific functions. Odin's polymorphism doesn't play nice with procedure groups + fmt.println(call(comp, 0.5)) // prints 0.5 +} diff --git a/Task/Function-composition/PascalABC.NET/function-composition.pas b/Task/Function-composition/PascalABC.NET/function-composition.pas new file mode 100644 index 0000000000..7072b96e99 --- /dev/null +++ b/Task/Function-composition/PascalABC.NET/function-composition.pas @@ -0,0 +1,5 @@ +function Compose(f: T1 -> T2; g: T -> T1): T -> T2 := x -> f(g(x)); + +begin + Compose(Sin,ArcSin)(1.0).Print +end. diff --git a/Task/Function-composition/Pluto/function-composition.pluto b/Task/Function-composition/Pluto/function-composition.pluto new file mode 100644 index 0000000000..6bbdea1daa --- /dev/null +++ b/Task/Function-composition/Pluto/function-composition.pluto @@ -0,0 +1,7 @@ +local function compose(f, g) return |x| -> f(g(x)) end + +local function double(x) return 2 * x end + +local function add_one(x) return x + 1 end + +print(compose(double, add_one)(3)) diff --git a/Task/Function-composition/PowerShell/function-composition-1.psh b/Task/Function-composition/PowerShell/function-composition-1.ps1 similarity index 100% rename from Task/Function-composition/PowerShell/function-composition-1.psh rename to Task/Function-composition/PowerShell/function-composition-1.ps1 diff --git a/Task/Function-composition/PowerShell/function-composition-2.psh b/Task/Function-composition/PowerShell/function-composition-2.ps1 similarity index 100% rename from Task/Function-composition/PowerShell/function-composition-2.psh rename to Task/Function-composition/PowerShell/function-composition-2.ps1 diff --git a/Task/Function-composition/REXX/function-composition.rexx b/Task/Function-composition/REXX/function-composition.rexx index 5036f78de6..ab3603d56d 100644 --- a/Task/Function-composition/REXX/function-composition.rexx +++ b/Task/Function-composition/REXX/function-composition.rexx @@ -1,3 +1,21 @@ -compose: procedure; parse arg f,g,x; interpret 'return' f"(" g'(' x "))" +-- 12 Sep 2025 +include Setting -exit /*control should never gets here, but this was added just in case.*/ +say 'FUNCTION COMPOSITION' +say version +say +parse value 'Sin' 'ArcSin' 0.5 with ff gg xx +say 'Compose('ff','gg','xx')' '=' Compose(ff,gg,xx) ',' ff'('gg'('xx'))' '=' Sin(ArcSin(xx)) +parse value 'ArcSin' 'Sin' 0.5 with ff gg xx +say 'Compose('ff','gg','xx')' '=' Compose(ff,gg,xx) ',' ff'('gg'('xx'))' '=' ArcSin(Sin(xx)) +parse value 'Zeta' 'Gamma' 0.5 with ff gg xx +say 'Compose('ff','gg','xx')' '=' Compose(ff,gg,xx) ',' ff'('gg'('xx'))' '=' Zeta(Gamma(xx)) +exit + +Compose: +procedure expose Memo. +arg ff,gg,xx +interpret 'rr='ff'('gg'('xx'))' +return rr + +include Math diff --git a/Task/Function-composition/REBOL/function-composition-1.rebol b/Task/Function-composition/Rebol/function-composition-1.rebol similarity index 78% rename from Task/Function-composition/REBOL/function-composition-1.rebol rename to Task/Function-composition/Rebol/function-composition-1.rebol index 8f31baeb19..ef233a55ac 100644 --- a/Task/Function-composition/REBOL/function-composition-1.rebol +++ b/Task/Function-composition/Rebol/function-composition-1.rebol @@ -1,9 +1,9 @@ -REBOL [ +Rebol [ Title: "Functional Composition" URL: http://rosettacode.org/wiki/Functional_Composition ] -; "compose" means something else in REBOL, therefore I use a 'compose-functions name. +; "compose" means something else in Rebol, therefore I use a 'compose-functions name. compose-functions: func [ {compose the given functions F and G} diff --git a/Task/Function-composition/REBOL/function-composition-2.rebol b/Task/Function-composition/Rebol/function-composition-2.rebol similarity index 100% rename from Task/Function-composition/REBOL/function-composition-2.rebol rename to Task/Function-composition/Rebol/function-composition-2.rebol diff --git a/Task/Function-composition/Red/function-composition.red b/Task/Function-composition/Red/function-composition.red new file mode 100644 index 0000000000..0f4331df21 --- /dev/null +++ b/Task/Function-composition/Red/function-composition.red @@ -0,0 +1,18 @@ +Red [ "Compose Two or Any Number of Functions - Hinjolicious" ] + +; to show the codes +demo: function [s b] [print ["^/==" s "==^/"] print mold/only b do b] + +demo "Compose two functions" [ +comp-func: function ['f 'g] [function [x] compose [(get f) (get g) x]] +sin-cos: comp-func sin cos +print sin-cos 0.5 +] + +demo "Compose any number of functions" [ +comp-funcs: function [ff] [ + function [x] compose append collect [foreach e ff [keep (get e)]] 'x +] +log-sin-cos: comp-funcs [log-e sin cos] +print log-sin-cos 0.5 +] diff --git a/Task/Function-composition/Rust/function-composition-1.rust b/Task/Function-composition/Rust/function-composition-1.rs similarity index 100% rename from Task/Function-composition/Rust/function-composition-1.rust rename to Task/Function-composition/Rust/function-composition-1.rs diff --git a/Task/Function-composition/Rust/function-composition-2.rust b/Task/Function-composition/Rust/function-composition-2.rs similarity index 100% rename from Task/Function-composition/Rust/function-composition-2.rust rename to Task/Function-composition/Rust/function-composition-2.rs diff --git a/Task/Function-composition/Scheme/function-composition-1.ss b/Task/Function-composition/Scheme/function-composition-1.scm similarity index 100% rename from Task/Function-composition/Scheme/function-composition-1.ss rename to Task/Function-composition/Scheme/function-composition-1.scm diff --git a/Task/Function-composition/Scheme/function-composition-2.ss b/Task/Function-composition/Scheme/function-composition-2.scm similarity index 100% rename from Task/Function-composition/Scheme/function-composition-2.ss rename to Task/Function-composition/Scheme/function-composition-2.scm diff --git a/Task/Function-composition/Scheme/function-composition-3.ss b/Task/Function-composition/Scheme/function-composition-3.scm similarity index 100% rename from Task/Function-composition/Scheme/function-composition-3.ss rename to Task/Function-composition/Scheme/function-composition-3.scm diff --git a/Task/Function-composition/VBScript/function-composition-1.vb b/Task/Function-composition/VBScript/function-composition-1.vbs similarity index 100% rename from Task/Function-composition/VBScript/function-composition-1.vb rename to Task/Function-composition/VBScript/function-composition-1.vbs diff --git a/Task/Function-composition/VBScript/function-composition-2.vb b/Task/Function-composition/VBScript/function-composition-2.vbs similarity index 100% rename from Task/Function-composition/VBScript/function-composition-2.vb rename to Task/Function-composition/VBScript/function-composition-2.vbs diff --git a/Task/Function-definition/ANSI-BASIC/function-definition.basic b/Task/Function-definition/ANSI-BASIC/function-definition.basic new file mode 100644 index 0000000000..9caf26d3c9 --- /dev/null +++ b/Task/Function-definition/ANSI-BASIC/function-definition.basic @@ -0,0 +1,13 @@ +100 DEF Multiply(A, B) = A * B +110 DECLARE FUNCTION MultiplyI +120 DECLARE EXTERNAL FUNCTION MultiplyE +130 PRINT Multiply(3, 1.23456) +140 PRINT MultiplyI(3, 1.23456) +150 PRINT MultiplyE(3, 1.23456) +160 FUNCTION MultiplyI(X, Y) +170 LET MultiplyI = X * Y +180 END FUNCTION +190 END +200 EXTERNAL FUNCTION MultiplyE(A, B) +210 LET MultiplyE = A * B +220 END FUNCTION diff --git a/Task/Function-definition/Ada/function-definition-1.ada b/Task/Function-definition/Ada/function-definition-1.adb similarity index 100% rename from Task/Function-definition/Ada/function-definition-1.ada rename to Task/Function-definition/Ada/function-definition-1.adb diff --git a/Task/Function-definition/Ada/function-definition-2.ada b/Task/Function-definition/Ada/function-definition-2.adb similarity index 100% rename from Task/Function-definition/Ada/function-definition-2.ada rename to Task/Function-definition/Ada/function-definition-2.adb diff --git a/Task/Function-definition/Ada/function-definition-3.ada b/Task/Function-definition/Ada/function-definition-3.adb similarity index 100% rename from Task/Function-definition/Ada/function-definition-3.ada rename to Task/Function-definition/Ada/function-definition-3.adb diff --git a/Task/Function-definition/Ada/function-definition-4.ada b/Task/Function-definition/Ada/function-definition-4.adb similarity index 100% rename from Task/Function-definition/Ada/function-definition-4.ada rename to Task/Function-definition/Ada/function-definition-4.adb diff --git a/Task/Function-definition/Ada/function-definition-5.ada b/Task/Function-definition/Ada/function-definition-5.adb similarity index 100% rename from Task/Function-definition/Ada/function-definition-5.ada rename to Task/Function-definition/Ada/function-definition-5.adb diff --git a/Task/Function-definition/Ada/function-definition-6.ada b/Task/Function-definition/Ada/function-definition-6.adb similarity index 100% rename from Task/Function-definition/Ada/function-definition-6.ada rename to Task/Function-definition/Ada/function-definition-6.adb diff --git a/Task/Function-definition/ArkScript/function-definition.ark b/Task/Function-definition/ArkScript/function-definition.ark new file mode 100644 index 0000000000..2c796ab336 --- /dev/null +++ b/Task/Function-definition/ArkScript/function-definition.ark @@ -0,0 +1,2 @@ +(let multiply (fun (a b) + (* a b))) diff --git a/Task/Function-definition/AutoIt/function-definition.autoit b/Task/Function-definition/AutoIt/function-definition.au3 similarity index 100% rename from Task/Function-definition/AutoIt/function-definition.autoit rename to Task/Function-definition/AutoIt/function-definition.au3 diff --git a/Task/Function-definition/Ballerina/function-definition.ballerina b/Task/Function-definition/Ballerina/function-definition.ballerina new file mode 100644 index 0000000000..a3c79abc73 --- /dev/null +++ b/Task/Function-definition/Ballerina/function-definition.ballerina @@ -0,0 +1,9 @@ +import ballerina/io; + +function multiply(int a, int b) returns int { + return a * b; +} + +public function main() { + io:println(multiply(4, 5)); +} diff --git a/Task/Function-definition/COBOL/function-definition-1.cobol b/Task/Function-definition/COBOL/function-definition-1.cob similarity index 100% rename from Task/Function-definition/COBOL/function-definition-1.cobol rename to Task/Function-definition/COBOL/function-definition-1.cob diff --git a/Task/Function-definition/COBOL/function-definition-2.cobol b/Task/Function-definition/COBOL/function-definition-2.cob similarity index 100% rename from Task/Function-definition/COBOL/function-definition-2.cobol rename to Task/Function-definition/COBOL/function-definition-2.cob diff --git a/Task/Function-definition/Chapel/function-definition-1.chpl b/Task/Function-definition/Chapel/function-definition-1.chpl new file mode 100644 index 0000000000..dce621a59f --- /dev/null +++ b/Task/Function-definition/Chapel/function-definition-1.chpl @@ -0,0 +1,4 @@ +proc multiply(a, b) +{ + return a * b; +} diff --git a/Task/Function-definition/Chapel/function-definition-2.chpl b/Task/Function-definition/Chapel/function-definition-2.chpl new file mode 100644 index 0000000000..cd4150861a --- /dev/null +++ b/Task/Function-definition/Chapel/function-definition-2.chpl @@ -0,0 +1,4 @@ +proc multiply(a : ?t ... 2) +{ + return a(0) * a(1) +} diff --git a/Task/Function-definition/Crystal/function-definition.cr b/Task/Function-definition/Crystal/function-definition.cr new file mode 100644 index 0000000000..9a6b44e375 --- /dev/null +++ b/Task/Function-definition/Crystal/function-definition.cr @@ -0,0 +1,16 @@ +def multiply (a, b) + a * b +end + +# with type restrictions: +def multiply (a : Int32, b : Int32) + print "(typed overload) " + a * b +end + +# proc (anonymous function) +m = ->(a : Int32, b : Int32) { a * b } + +p! multiply(2, 3), + multiply(2.0, 3.0), + m.call(2, 3) diff --git a/Task/Function-definition/Delphi/function-definition.delphi b/Task/Function-definition/Delphi/function-definition.pas similarity index 100% rename from Task/Function-definition/Delphi/function-definition.delphi rename to Task/Function-definition/Delphi/function-definition.pas diff --git a/Task/Function-definition/DuckDB/function-definition-1.duckdb b/Task/Function-definition/DuckDB/function-definition-1.duckdb new file mode 100644 index 0000000000..ce21102e19 --- /dev/null +++ b/Task/Function-definition/DuckDB/function-definition-1.duckdb @@ -0,0 +1 @@ +create or replace function multiply(x,y) as x*y; diff --git a/Task/Function-definition/DuckDB/function-definition-2.duckdb b/Task/Function-definition/DuckDB/function-definition-2.duckdb new file mode 100644 index 0000000000..3053825ed4 --- /dev/null +++ b/Task/Function-definition/DuckDB/function-definition-2.duckdb @@ -0,0 +1,10 @@ +create or replace function power2(n) as ( + with recursive cte as ( + select 0 as i, 1::UHUGEINT as p + union all + select i+1 as i, p*2 as p + from cte + where i < n ) + select last(p order by i) + from cte +); diff --git a/Task/Function-definition/Elixir/function-definition.elixir b/Task/Function-definition/Elixir/function-definition.ex similarity index 100% rename from Task/Function-definition/Elixir/function-definition.elixir rename to Task/Function-definition/Elixir/function-definition.ex diff --git a/Task/Function-definition/Emacs-Lisp/function-definition-1.l b/Task/Function-definition/Emacs-Lisp/function-definition-1.el similarity index 100% rename from Task/Function-definition/Emacs-Lisp/function-definition-1.l rename to Task/Function-definition/Emacs-Lisp/function-definition-1.el diff --git a/Task/Function-definition/Emacs-Lisp/function-definition-2.l b/Task/Function-definition/Emacs-Lisp/function-definition-2.el similarity index 100% rename from Task/Function-definition/Emacs-Lisp/function-definition-2.l rename to Task/Function-definition/Emacs-Lisp/function-definition-2.el diff --git a/Task/Function-definition/Euphoria/function-definition-1.euphoria b/Task/Function-definition/Euphoria/function-definition-1.eu similarity index 100% rename from Task/Function-definition/Euphoria/function-definition-1.euphoria rename to Task/Function-definition/Euphoria/function-definition-1.eu diff --git a/Task/Function-definition/Euphoria/function-definition-2.euphoria b/Task/Function-definition/Euphoria/function-definition-2.eu similarity index 100% rename from Task/Function-definition/Euphoria/function-definition-2.euphoria rename to Task/Function-definition/Euphoria/function-definition-2.eu diff --git a/Task/Function-definition/Excel/function-definition.excel b/Task/Function-definition/Excel/function-definition.excel new file mode 100644 index 0000000000..1b33fa780a --- /dev/null +++ b/Task/Function-definition/Excel/function-definition.excel @@ -0,0 +1,4 @@ +=LET( + MULTIPLY, LAMBDA(a, b, a * b), + ... + ) diff --git a/Task/Function-definition/FutureBasic/function-definition.basic b/Task/Function-definition/FutureBasic/function-definition-1.basic similarity index 100% rename from Task/Function-definition/FutureBasic/function-definition.basic rename to Task/Function-definition/FutureBasic/function-definition-1.basic diff --git a/Task/Function-definition/FutureBasic/function-definition-2.basic b/Task/Function-definition/FutureBasic/function-definition-2.basic new file mode 100644 index 0000000000..c6c813c61b --- /dev/null +++ b/Task/Function-definition/FutureBasic/function-definition-2.basic @@ -0,0 +1,8 @@ +window 1 + +long local fn multiply( a as long, b as long ) +end fn = a * b + +print fn multiply( 3, 9 ) + +HandleEvents diff --git a/Task/Function-definition/Gleam/function-definition.gleam b/Task/Function-definition/Gleam/function-definition.gleam new file mode 100644 index 0000000000..45be9f932e --- /dev/null +++ b/Task/Function-definition/Gleam/function-definition.gleam @@ -0,0 +1,3 @@ +fn multiply(x: Int, y: Int) -> Int { + x * y +} diff --git a/Task/Function-definition/Haxe/function-definition.haxe b/Task/Function-definition/Haxe/function-definition.hx similarity index 100% rename from Task/Function-definition/Haxe/function-definition.haxe rename to Task/Function-definition/Haxe/function-definition.hx diff --git a/Task/Function-definition/Java/function-definition.java b/Task/Function-definition/Java/function-definition-1.java similarity index 100% rename from Task/Function-definition/Java/function-definition.java rename to Task/Function-definition/Java/function-definition-1.java diff --git a/Task/Function-definition/Java/function-definition-2.java b/Task/Function-definition/Java/function-definition-2.java new file mode 100644 index 0000000000..fb127fb080 --- /dev/null +++ b/Task/Function-definition/Java/function-definition-2.java @@ -0,0 +1,27 @@ +import java.util.function.BiFunction; +import java.util.function.DoubleUnaryOperator; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.function.UnaryOperator; + +public final class FunctionDefinition { + + public static void main(String[] args) { + System.out.println(size.apply("Rosetta")); + System.out.println(greeting.apply("Joe")); + System.out.println(half.applyAsDouble(7)); + System.out.println(lessThanTen.test(15)); + System.out.println(add.apply(2, 3)); + } + + private static Function size = s -> s.length(); + + private static UnaryOperator greeting = s -> "Hello " + s; + + private static DoubleUnaryOperator half = a -> a / 2; + + private static Predicate lessThanTen = a -> a < 10; + + private static BiFunction add = (a, b) -> a + b; + +} diff --git a/Task/Function-definition/JavaScript/function-definition-6.js b/Task/Function-definition/JavaScript/function-definition-6.js index 60d2fdb755..b32d13d81a 100644 --- a/Task/Function-definition/JavaScript/function-definition-6.js +++ b/Task/Function-definition/JavaScript/function-definition-6.js @@ -1,2 +1,8 @@ var multiply = (a, b) => a * b; var multiply = (a, b) => { return a * b }; + +// Or, `var` being long deprecated, and currying convenient, +// (particularly in use with the higher-order Array methods) + +const multiply = a => + b => a * b; diff --git a/Task/Function-definition/Julia/function-definition-1.julia b/Task/Function-definition/Julia/function-definition-1.jl similarity index 100% rename from Task/Function-definition/Julia/function-definition-1.julia rename to Task/Function-definition/Julia/function-definition-1.jl diff --git a/Task/Function-definition/Julia/function-definition-2.julia b/Task/Function-definition/Julia/function-definition-2.jl similarity index 100% rename from Task/Function-definition/Julia/function-definition-2.julia rename to Task/Function-definition/Julia/function-definition-2.jl diff --git a/Task/Function-definition/Julia/function-definition-3.julia b/Task/Function-definition/Julia/function-definition-3.jl similarity index 100% rename from Task/Function-definition/Julia/function-definition-3.julia rename to Task/Function-definition/Julia/function-definition-3.jl diff --git a/Task/Function-definition/Komodo/function-definition.komodo b/Task/Function-definition/Komodo/function-definition.komodo new file mode 100644 index 0000000000..63404d357c --- /dev/null +++ b/Task/Function-definition/Komodo/function-definition.komodo @@ -0,0 +1,5 @@ +let prod(a, b) := a*b +let prodAnon := (a, b) -> a*b + +assert(prodAnon(2, 2) = ((a, b) -> a*b)(2, 2)) +assert(prod(2, 2) = prodAnon(2, 2)) diff --git a/Task/Function-definition/Kotlin/function-definition.kotlin b/Task/Function-definition/Kotlin/function-definition.kts similarity index 100% rename from Task/Function-definition/Kotlin/function-definition.kotlin rename to Task/Function-definition/Kotlin/function-definition.kts diff --git a/Task/Function-definition/LOLCODE/function-definition.lol b/Task/Function-definition/LOLCODE/function-definition.lol new file mode 100644 index 0000000000..8d50259103 --- /dev/null +++ b/Task/Function-definition/LOLCODE/function-definition.lol @@ -0,0 +1,9 @@ +HAI 1.3 + +HOW IZ I MULTIPLY YR X AN YR Y + FOUND YR PRODUKT OF X AN Y +IF U SAY SO + +VISIBLE I IZ MULTIPLY YR 2 AND YR 3 MKAY + +KTHXBYE diff --git a/Task/Function-definition/Langur/function-definition-1.langur b/Task/Function-definition/Langur/function-definition-1.langur index 5f5be48e73..0445f67e8d 100644 --- a/Task/Function-definition/Langur/function-definition-1.langur +++ b/Task/Function-definition/Langur/function-definition-1.langur @@ -1,2 +1 @@ -val .multiply = fn(.x, .y) { .x * .y } -.multiply(3, 4) +val multiply = fn(a, b) { a * b } diff --git a/Task/Function-definition/Langur/function-definition-2.langur b/Task/Function-definition/Langur/function-definition-2.langur index acbe918263..5878a47bf8 100644 --- a/Task/Function-definition/Langur/function-definition-2.langur +++ b/Task/Function-definition/Langur/function-definition-2.langur @@ -1,2 +1 @@ -val .multiply = fn(.x, .y) .x * .y -.multiply(3, 4) +val multiply = fn{*} diff --git a/Task/Function-definition/Langur/function-definition-3.langur b/Task/Function-definition/Langur/function-definition-3.langur index d66762792a..e8a58c5239 100644 --- a/Task/Function-definition/Langur/function-definition-3.langur +++ b/Task/Function-definition/Langur/function-definition-3.langur @@ -1,2 +1 @@ -val .multiply = fn{*} -.multiply(3, 4) +val timestwo = fn{*2} diff --git a/Task/Function-definition/Langur/function-definition-4.langur b/Task/Function-definition/Langur/function-definition-4.langur index 69bbd2fc56..64c16021ee 100644 --- a/Task/Function-definition/Langur/function-definition-4.langur +++ b/Task/Function-definition/Langur/function-definition-4.langur @@ -1,2 +1 @@ -val .times3 = fn{* 3} -map .times3, [1, 2, 3] +val factorial = fn(x) { if(x < 2: 1; x * fn((x - 1))) } diff --git a/Task/Function-definition/Langur/function-definition-5.langur b/Task/Function-definition/Langur/function-definition-5.langur deleted file mode 100644 index 3f55f3d068..0000000000 --- a/Task/Function-definition/Langur/function-definition-5.langur +++ /dev/null @@ -1 +0,0 @@ -val .writeit = impure fn(.x) { writeln .x } diff --git a/Task/Function-definition/OCaml/function-definition.ocaml b/Task/Function-definition/OCaml/function-definition.ml similarity index 100% rename from Task/Function-definition/OCaml/function-definition.ocaml rename to Task/Function-definition/OCaml/function-definition.ml diff --git a/Task/Function-definition/PascalABC.NET/function-definition.pas b/Task/Function-definition/PascalABC.NET/function-definition.pas new file mode 100644 index 0000000000..5cdaeef57d --- /dev/null +++ b/Task/Function-definition/PascalABC.NET/function-definition.pas @@ -0,0 +1 @@ +function multiply(a,b: real): real := a + b; diff --git a/Task/Function-definition/Pluto/function-definition.pluto b/Task/Function-definition/Pluto/function-definition.pluto new file mode 100644 index 0000000000..442e6b756c --- /dev/null +++ b/Task/Function-definition/Pluto/function-definition.pluto @@ -0,0 +1,5 @@ +function multiply(a,b) + return a*b +end + +print(multiply(3,4)) diff --git a/Task/Function-definition/PowerShell/function-definition-1.psh b/Task/Function-definition/PowerShell/function-definition-1.ps1 similarity index 100% rename from Task/Function-definition/PowerShell/function-definition-1.psh rename to Task/Function-definition/PowerShell/function-definition-1.ps1 diff --git a/Task/Function-definition/PowerShell/function-definition-2.psh b/Task/Function-definition/PowerShell/function-definition-2.ps1 similarity index 100% rename from Task/Function-definition/PowerShell/function-definition-2.psh rename to Task/Function-definition/PowerShell/function-definition-2.ps1 diff --git a/Task/Function-definition/PowerShell/function-definition-3.psh b/Task/Function-definition/PowerShell/function-definition-3.ps1 similarity index 100% rename from Task/Function-definition/PowerShell/function-definition-3.psh rename to Task/Function-definition/PowerShell/function-definition-3.ps1 diff --git a/Task/Function-definition/PowerShell/function-definition-4.psh b/Task/Function-definition/PowerShell/function-definition-4.ps1 similarity index 100% rename from Task/Function-definition/PowerShell/function-definition-4.psh rename to Task/Function-definition/PowerShell/function-definition-4.ps1 diff --git a/Task/Function-definition/PowerShell/function-definition-5.psh b/Task/Function-definition/PowerShell/function-definition-5.ps1 similarity index 100% rename from Task/Function-definition/PowerShell/function-definition-5.psh rename to Task/Function-definition/PowerShell/function-definition-5.ps1 diff --git a/Task/Function-definition/BASIC/function-definition.basic b/Task/Function-definition/QuickBASIC/function-definition.basic similarity index 100% rename from Task/Function-definition/BASIC/function-definition.basic rename to Task/Function-definition/QuickBASIC/function-definition.basic diff --git a/Task/Function-definition/REXX/function-definition-1.rexx b/Task/Function-definition/REXX/function-definition-1.rexx deleted file mode 100644 index a476639d66..0000000000 --- a/Task/Function-definition/REXX/function-definition-1.rexx +++ /dev/null @@ -1 +0,0 @@ -multiply: return arg(1) * arg(2) /*return the product of the two arguments.*/ diff --git a/Task/Function-definition/REXX/function-definition-2.rexx b/Task/Function-definition/REXX/function-definition-2.rexx deleted file mode 100644 index 569b050f96..0000000000 --- a/Task/Function-definition/REXX/function-definition-2.rexx +++ /dev/null @@ -1 +0,0 @@ -multiply: return arg(1) * arg(2) / 1 /*return with a normalized product of 2 args. */ diff --git a/Task/Function-definition/REXX/function-definition.rexx b/Task/Function-definition/REXX/function-definition.rexx new file mode 100644 index 0000000000..1d6fc424e5 --- /dev/null +++ b/Task/Function-definition/REXX/function-definition.rexx @@ -0,0 +1,34 @@ +-- 11 Sep 2025 +include Setting + +say 'FUNCTION DEFINITION' +say version +say +xx=0; yy=0; rr=0 +say 'xx =' xx 'yy =' yy 'rr =' rr +say 'Multiply1(2,3)' '=' Multiply1(2,3) +say 'xx =' xx 'yy =' yy 'rr =' rr +say 'Multiply2(3,5)' '=' Multiply2(3,5) +say 'xx =' xx 'yy =' yy 'rr =' rr +xx=5; yy=7 +say 'xx =' xx 'yy =' yy 'rr =' rr +say 'Multiply3(5,7)' '=' Multiply3() +say 'xx =' xx 'yy =' yy 'rr =' rr +exit + +Multiply1: +procedure +arg xx,yy +rr=xx*yy +return rr + +Multiply2: +arg xx,yy +rr=xx*yy +return rr + +Multiply3: +rr=xx*yy +return rr + +include Math diff --git a/Task/Function-definition/REBOL/function-definition.rebol b/Task/Function-definition/Rebol/function-definition.rebol similarity index 100% rename from Task/Function-definition/REBOL/function-definition.rebol rename to Task/Function-definition/Rebol/function-definition.rebol diff --git a/Task/Function-definition/Rust/function-definition.rust b/Task/Function-definition/Rust/function-definition.rs similarity index 100% rename from Task/Function-definition/Rust/function-definition.rust rename to Task/Function-definition/Rust/function-definition.rs diff --git a/Task/Function-definition/Rye/function-definition-1.rye b/Task/Function-definition/Rye/function-definition-1.rye new file mode 100644 index 0000000000..944dd8c78b --- /dev/null +++ b/Task/Function-definition/Rye/function-definition-1.rye @@ -0,0 +1 @@ +multiply: fn { a b } { a * b } diff --git a/Task/Function-definition/Rye/function-definition-2.rye b/Task/Function-definition/Rye/function-definition-2.rye new file mode 100644 index 0000000000..2f2cc5ea24 --- /dev/null +++ b/Task/Function-definition/Rye/function-definition-2.rye @@ -0,0 +1 @@ +multiply: fn { a b } { * b } diff --git a/Task/Function-definition/Rye/function-definition-3.rye b/Task/Function-definition/Rye/function-definition-3.rye new file mode 100644 index 0000000000..ca8885cbcf --- /dev/null +++ b/Task/Function-definition/Rye/function-definition-3.rye @@ -0,0 +1 @@ +multiply: pfn { a b } { a * b } diff --git a/Task/Function-definition/SIL/function-definition.sil b/Task/Function-definition/SIL/function-definition.sil new file mode 100644 index 0000000000..21bfbe3c19 --- /dev/null +++ b/Task/Function-definition/SIL/function-definition.sil @@ -0,0 +1,3 @@ +funcmultiply +r = x * y +return diff --git a/Task/Function-definition/Scheme/function-definition-1.ss b/Task/Function-definition/Scheme/function-definition-1.scm similarity index 100% rename from Task/Function-definition/Scheme/function-definition-1.ss rename to Task/Function-definition/Scheme/function-definition-1.scm diff --git a/Task/Function-definition/Scheme/function-definition-2.ss b/Task/Function-definition/Scheme/function-definition-2.scm similarity index 100% rename from Task/Function-definition/Scheme/function-definition-2.ss rename to Task/Function-definition/Scheme/function-definition-2.scm diff --git a/Task/Function-definition/Tcl/function-definition-3.tcl b/Task/Function-definition/Tcl/function-definition-3.tcl new file mode 100644 index 0000000000..e2a1260e67 --- /dev/null +++ b/Task/Function-definition/Tcl/function-definition-3.tcl @@ -0,0 +1,13 @@ +proc multiply { a b args } { + + set product 1 + + foreach m [list $a $b {*}$args] { + + set product [expr {$product * $m}] + } + + return $product +} + +puts stdout [multiply 3 4 7 9 -2 -5 ] diff --git a/Task/Function-definition/VBScript/function-definition-1.vb b/Task/Function-definition/VBScript/function-definition-1.vbs similarity index 100% rename from Task/Function-definition/VBScript/function-definition-1.vb rename to Task/Function-definition/VBScript/function-definition-1.vbs diff --git a/Task/Function-definition/VBScript/function-definition-2.vb b/Task/Function-definition/VBScript/function-definition-2.vbs similarity index 100% rename from Task/Function-definition/VBScript/function-definition-2.vb rename to Task/Function-definition/VBScript/function-definition-2.vbs diff --git a/Task/Function-definition/YAMLScript/function-definition.ys b/Task/Function-definition/YAMLScript/function-definition.ys new file mode 100644 index 0000000000..7bab26ba31 --- /dev/null +++ b/Task/Function-definition/YAMLScript/function-definition.ys @@ -0,0 +1,15 @@ +!YS-v0 + +# Main function definition with variable arguments: +defn main(*args): + say: "multiply($(args.join(', '))) + -> $multiply(args*)" + +# A multi-arity function definition: +defn multiply: + (): 1 + (x): x + (x y): x * y + (x y *more): + reduce multiply: + multiply(x y) more diff --git a/Task/Function-definition/Zig/function-definition.zig b/Task/Function-definition/Zig/function-definition.zig index f67148e5cd..38dab3141a 100644 --- a/Task/Function-definition/Zig/function-definition.zig +++ b/Task/Function-definition/Zig/function-definition.zig @@ -1,4 +1,4 @@ -fun multiply(x: i64, y: i64) i64 { +fn multiply(x: i64, y: i64) i64 { return x * y; } diff --git a/Task/Function-frequency/Arturo/function-frequency.arturo b/Task/Function-frequency/Arturo/function-frequency.arturo index ba1c035514..651ef9d353 100644 --- a/Task/Function-frequency/Arturo/function-frequency.arturo +++ b/Task/Function-frequency/Arturo/function-frequency.arturo @@ -3,23 +3,21 @@ frequencies: #[] inspectBlock: function [blk][ loop blk 'item [ - case [] - when? [word? item][ + when [ + word? item [ sItem: to :string item if set? sItem -> if function? var sItem [ - if? key? frequencies sItem -> - set frequencies sItem (get frequencies sItem)+1 - else -> - set frequencies sItem 1 + switch key? frequencies sItem + -> set frequencies sItem (get frequencies sItem)+1 + -> set frequencies sItem 1 ] ] - when? [or? block? item - inline? item] -> + or? block? item + inline? item -> inspectBlock item - - else [] + ] ] ] diff --git a/Task/Function-frequency/Julia/function-frequency.julia b/Task/Function-frequency/Julia/function-frequency.jl similarity index 100% rename from Task/Function-frequency/Julia/function-frequency.julia rename to Task/Function-frequency/Julia/function-frequency.jl diff --git a/Task/Function-frequency/REXX/function-frequency-3.rexx b/Task/Function-frequency/REXX/function-frequency-3.rexx new file mode 100644 index 0000000000..05ffecf5c2 --- /dev/null +++ b/Task/Function-frequency/REXX/function-frequency-3.rexx @@ -0,0 +1,138 @@ +-- 21 Feb 2026 +include Setting +parse arg program + +say 'FUNCTION FREQUENCY' +say version +call ReadSource +call CleanSource +call CollectInvokes +call SortSt 'invo.' +call ReportInvokes +call Timer +exit + +ReadSource: +-- Read all lines in a stem +if program='' then + program='FuncFreq.rex' +else + program=program'.rex' +say 'Invoke frequencies for program' program +say +call Stream program,'c','open read' +srce.=0; n=0 +do while Lines(program) + record=LineIn(program) + n=n+1; srce.n=record +end +srce.0=n +call Stream program,'c','close' +return + +CleanSource: +-- Erase all characters that are (in this order): +-- within a '' literal or a "" literal +-- within a /*...*/ comment block +-- after -- ... comment +-- not allowed in names +cleanc=0 +p1=0; q1=0 +do i = 1 to srce.0 + cleanl=0 + s=srce.i; k=Length(s) + do j = 1 to k +-- Substring for literals + p1=SubStr(s,j,1) +-- Erase literal + if p1 = "'" | p1 = '"' then do + if cleanl then do + s=Overlay(' ',s,j) + if p1 = q1 then + cleanl=0 + end + else do + q1=p1; cleanl=1 + end + end + if cleanl then + s=Overlay(' ',s,j) + end j +-- Substring for comments + p2=SubStr(s,j,2) +-- Erase block /*...*/ comment + if p2 = '/*' then + cleanc=1 + else do + if p2 = '*/' then do + s=Overlay(' ',s,j,2) + cleanc=0 + end + end + if cleanc then do + s=Overlay(' ',s,j) + iterate j + end +-- Erase -- ... comment + if p2 = '--' then do + s=Overlay(' ',s,j,k) + leave j + end +-- Erase all characters not allowed in names + s=Translate(s,' ','+-*|<>,;=/\%)') + srce.i=s +end i +return + +CollectInvokes: +-- Collect invocations 'Name()' or 'call Name' +invo.=0; v=0 +do i = 1 to srce.0 + s=srce.i +-- Parse words + wrds.=0; n=0 + do until s = '' + n=n+1; parse var s wrds.n s + end +-- Find invocations + wrds.0=n + do j = 1 to wrds.0 + w=wrds.j +-- Call Name + if Upper(w) = 'CALL' then do + k=j+1; v=v+1; invo.v=wrds.k + end +-- Name() + else do + p1=1; p2=Pos('(',w) + do while p2 > 0 + a=SubStr(w,p1,p2-p1) + if a <> '' then do + v=v+1; invo.v=SubStr(w,p1,p2-p1) + end + p1=p2+1; p2=Pos('(',w,p1) + end + end + end j +end i +invo.0=v +return + +ReportInvokes: +-- Aggregate and report +p=invo.1; n=1 +do i = 2 to invo.0 + v = invo.i + if v = p then + n=n+1 + else do + say Right(n,3) p + p=v; n=1 + end +end i +say Right(n,3) p +say +return + +-- SortSt; Timer +include Math diff --git a/Task/Function-prototype/Ada/function-prototype-1.ada b/Task/Function-prototype/Ada/function-prototype-1.adb similarity index 100% rename from Task/Function-prototype/Ada/function-prototype-1.ada rename to Task/Function-prototype/Ada/function-prototype-1.adb diff --git a/Task/Function-prototype/Ada/function-prototype-2.ada b/Task/Function-prototype/Ada/function-prototype-2.adb similarity index 100% rename from Task/Function-prototype/Ada/function-prototype-2.ada rename to Task/Function-prototype/Ada/function-prototype-2.adb diff --git a/Task/Function-prototype/Ada/function-prototype-3.ada b/Task/Function-prototype/Ada/function-prototype-3.adb similarity index 100% rename from Task/Function-prototype/Ada/function-prototype-3.ada rename to Task/Function-prototype/Ada/function-prototype-3.adb diff --git a/Task/Function-prototype/Ada/function-prototype-4.ada b/Task/Function-prototype/Ada/function-prototype-4.adb similarity index 100% rename from Task/Function-prototype/Ada/function-prototype-4.ada rename to Task/Function-prototype/Ada/function-prototype-4.adb diff --git a/Task/Function-prototype/Ada/function-prototype-5.ada b/Task/Function-prototype/Ada/function-prototype-5.adb similarity index 100% rename from Task/Function-prototype/Ada/function-prototype-5.ada rename to Task/Function-prototype/Ada/function-prototype-5.adb diff --git a/Task/Function-prototype/COBOL/function-prototype.cobol b/Task/Function-prototype/COBOL/function-prototype.cob similarity index 100% rename from Task/Function-prototype/COBOL/function-prototype.cobol rename to Task/Function-prototype/COBOL/function-prototype.cob diff --git a/Task/Function-prototype/Delphi/function-prototype-1.delphi b/Task/Function-prototype/Delphi/function-prototype-1.pas similarity index 100% rename from Task/Function-prototype/Delphi/function-prototype-1.delphi rename to Task/Function-prototype/Delphi/function-prototype-1.pas diff --git a/Task/Function-prototype/Delphi/function-prototype-2.delphi b/Task/Function-prototype/Delphi/function-prototype-2.pas similarity index 100% rename from Task/Function-prototype/Delphi/function-prototype-2.delphi rename to Task/Function-prototype/Delphi/function-prototype-2.pas diff --git a/Task/Function-prototype/EasyLang/function-prototype.easy b/Task/Function-prototype/EasyLang/function-prototype.easy new file mode 100644 index 0000000000..d3292735cc --- /dev/null +++ b/Task/Function-prototype/EasyLang/function-prototype.easy @@ -0,0 +1,31 @@ +# No arguments +funcdecl f0 . +# +# Two arguments +procdecl f1 a s$ . +# +# Varargs are not available +# +# Two arguments (integer and string), pass by reference +procdecl f4 &a &s$ . +# +# Function returning an array +funcdecl[] f7 . +# +print f0 +# +# Each declared function must also be implemented +# +func f0 . + return 3 +. +proc f1 a s$ . + print s$ & a +. +proc f4 &a &s$ . + a = 7 + s$ = "hello" +. +func[] f7 . + return [ 1 2 3 ] +. diff --git a/Task/Function-prototype/FutureBasic/function-prototype.basic b/Task/Function-prototype/FutureBasic/function-prototype.basic new file mode 100644 index 0000000000..9a96932ecb --- /dev/null +++ b/Task/Function-prototype/FutureBasic/function-prototype.basic @@ -0,0 +1,4 @@ +def fn NoArgs +def fn TwoArgs( a as long, b as long ) +def fn VarArgs( n as long, ... ) +long def fn Multiply( a as long, b as long ) // function returns a value diff --git a/Task/Function-prototype/Julia/function-prototype-1.julia b/Task/Function-prototype/Julia/function-prototype-1.jl similarity index 100% rename from Task/Function-prototype/Julia/function-prototype-1.julia rename to Task/Function-prototype/Julia/function-prototype-1.jl diff --git a/Task/Function-prototype/Julia/function-prototype-2.julia b/Task/Function-prototype/Julia/function-prototype-2.jl similarity index 100% rename from Task/Function-prototype/Julia/function-prototype-2.julia rename to Task/Function-prototype/Julia/function-prototype-2.jl diff --git a/Task/Function-prototype/Kotlin/function-prototype.kotlin b/Task/Function-prototype/Kotlin/function-prototype.kts similarity index 100% rename from Task/Function-prototype/Kotlin/function-prototype.kotlin rename to Task/Function-prototype/Kotlin/function-prototype.kts diff --git a/Task/Function-prototype/OCaml/function-prototype.ocaml b/Task/Function-prototype/OCaml/function-prototype.ml similarity index 100% rename from Task/Function-prototype/OCaml/function-prototype.ocaml rename to Task/Function-prototype/OCaml/function-prototype.ml diff --git a/Task/Functional-coverage-tree/C++/functional-coverage-tree.cpp b/Task/Functional-coverage-tree/C++/functional-coverage-tree.cpp new file mode 100644 index 0000000000..9397979952 --- /dev/null +++ b/Task/Functional-coverage-tree/C++/functional-coverage-tree.cpp @@ -0,0 +1,170 @@ +#include +#include +#include +#include +#include +#include + +class FCNode { +public: + FCNode(const std::string& name, const uint32_t& weight, const double& coverage) + : name(name), weight(weight), coverage(coverage), parent(NULL) {} + + void add_children(const std::vector>& nodes) { + for ( const std::shared_ptr& node : nodes ) { + node->parent = this; + children.emplace_back(node); + update_coverage(); + } + } + + double get_coverage() { + return coverage; + } + + void set_coverage(const double& aCoverage) { + if ( coverage != aCoverage ) { + coverage = aCoverage; + if ( parent ) { + parent->update_coverage(); + } + } + } + + void display() { + display(0); + } + +private: + void update_coverage() { + double sum_weighted_coverage = 0.0; + uint32_t sum_weight = 0; + for ( const std::shared_ptr& node : children ) { + sum_weighted_coverage += node->weight * node->coverage; + sum_weight += node->weight; + } + + set_coverage(sum_weighted_coverage / sum_weight); + } + + void display(uint32_t level) { + const std::string initial = std::string(4 * level, ' ') + name; + const std::string padding = std::string(NAME_FIELD_WIDTH - initial.length(), ' '); + std::cout << initial + padding + "|"; + std::cout << " " << std::setw(3) << weight << " |"; + std::cout << " " << std::fixed << std::setprecision(6) << coverage << " |" << std::endl; + + for ( const std::shared_ptr& child : children ) { + child->display(level + 1); + } + } + + std::string name; + uint32_t weight; + double coverage; + FCNode* parent; + std::vector> children{ }; + + static constexpr uint32_t NAME_FIELD_WIDTH = 32; +}; + +int main() { + FCNode cleaning("Cleaning", 1, 0.0); + + std::vector> houses = { + std::make_shared("House_1", 40, 0.0), + std::make_shared("House_2", 60, 0.0) + }; + cleaning.add_children(houses); + + std::vector> house_1 = { + std::make_shared("Bedrooms", 1, 0.25), + std::make_shared("Bathrooms", 1, 0.0), + std::make_shared("Attic", 1, 0.75), + std::make_shared("Kitchen", 1, 0.1), + std::make_shared("Living_rooms", 1, 0.0), + std::make_shared("Basement", 1, 0.0), + std::make_shared("Garage", 1, 0.0), + std::make_shared("Garden",1, 0.8) + }; + houses[0]->add_children(house_1); + + std::vector> bathrooms_house_1 = { + std::make_shared("Bathroom_1", 1, 0.5), + std::make_shared("Bathroom_2", 1, 0.0), + std::make_shared("Outside_lavatory", 1, 1.0) + }; + house_1[1]->add_children(bathrooms_house_1); + + std::vector> living_rooms_house_1 = { + std::make_shared("lounge", 1, 0.0), + std::make_shared("Dining_room", 1, 0.0), + std::make_shared("Conservatory", 1, 0.0), + std::make_shared("Playroom", 1, 1.0) + }; + house_1[4]->add_children(living_rooms_house_1); + + std::vector> house_2 = { + std::make_shared("Upstairs", 1, 0.15), + std::make_shared("Ground_floor", 1, 0.316667), + std::make_shared("Basement", 1, 0.916667) + }; + houses[1]->add_children(house_2); + + std::vector> upstairs = { + std::make_shared("Bedrooms", 1, 0.0), + std::make_shared("Bathroom", 1, 0.0), + std::make_shared("Toilet", 1, 0.0), + std::make_shared("Attics", 1, 0.6) + }; + house_2[0]->add_children(upstairs); + + std::vector> ground_floor = { + std::make_shared("Kitchen", 1, 0.0), + std::make_shared("Living_rooms", 1, 0.0), + std::make_shared("Wet_room_&_toilet", 1, 0.0), + std::make_shared("Garage", 1, 0.0), + std::make_shared("Garden", 1, 0.9), + std::make_shared("Hot_tub_suite", 1, 1.0) + }; + house_2[1]->add_children(ground_floor); + + std::vector> basement = { + std::make_shared("Cellars", 1, 1.0), + std::make_shared("Wine_cellar", 1, 1.0), + std::make_shared("Cinema", 1, 0.75) + }; + house_2[2]->add_children(basement); + + std::vector> bedrooms = { + std::make_shared("Suite_1", 1, 0.0), + std::make_shared("Suite_2", 1, 0.0), + std::make_shared("Bedroom_3",1, 0.0), + std::make_shared("Bedroom_4",1, 0.0) + }; + upstairs[0]->add_children(bedrooms); + + std::vector> living_rooms_house_2 = { + std::make_shared("lounge", 1, 0.0), + std::make_shared("Dining_room", 1, 0.0), + std::make_shared("Conservatory", 1, 0.0), + std::make_shared("Playroom", 1, 0.0) + }; + ground_floor[1]->add_children(living_rooms_house_2); + + const double overall_coverage = cleaning.get_coverage(); + std::cout << "OVERALL COVERAGE = " << std::fixed << std::setprecision(6) + << overall_coverage << std::endl << std::endl; + std::cout << "NAME HIERARCHY | WEIGHT | COVERAGE |" << std::endl; + std::cout << "--------------------------------|--------|----------|" << std::endl; + cleaning.display(); + std::cout << std::endl; + + basement[2]->set_coverage(1.0); // Change House_2 Cinema node coverage to 1.0 + const double updated_coverage = cleaning.get_coverage(); + const double difference = updated_coverage - overall_coverage; + std::cout << "If the coverage of the House_2 Cinema node were increased " << std::endl; + std::cout << "from 0.75 to 1.0 the overall coverage would increase by "; + std::cout << std::fixed << std::setprecision(6) << difference << " to " << updated_coverage << std::endl; + basement[2]->set_coverage(0.75); // Restore to House_2 Cinema node coverage to its original value +} diff --git a/Task/Functional-coverage-tree/FreeBASIC/functional-coverage-tree.basic b/Task/Functional-coverage-tree/FreeBASIC/functional-coverage-tree.basic new file mode 100644 index 0000000000..55d06e8f9a --- /dev/null +++ b/Task/Functional-coverage-tree/FreeBASIC/functional-coverage-tree.basic @@ -0,0 +1,154 @@ +Type FCNode + As String nombre + As Integer weight + As Double coverage + As FCNode Ptr children(Any) + As FCNode Ptr parent + Declare Constructor(nombre As String, weight As Integer, coverage As Double) + Declare Sub addChildren(nodes() As FCNode Ptr) + Declare Sub setCoverage(value As Double) + Declare Sub updateCoverage() + Declare Sub show(level As Integer) +End Type + +Constructor FCNode(nombre As String, weight As Integer, coverage As Double) + this.nombre = nombre + this.weight = weight + this.coverage = coverage + this.parent = 0 +End Constructor + +Sub FCNode.addChildren(nodes() As FCNode Ptr) + For i As Integer = 0 To Ubound(nodes) + nodes(i)->parent = @This + Redim Preserve this.children(Ubound(this.children) + 1) + this.children(Ubound(this.children)) = nodes(i) + Next + this.updateCoverage() +End Sub + +Sub FCNode.setCoverage(value As Double) + If this.coverage <> value Then + this.coverage = value + If this.parent <> 0 Then this.parent->updateCoverage() + End If +End Sub + +Sub FCNode.updateCoverage() + Dim As Double v1 = 0 + Dim As Integer v2 = 0 + For i As Integer = 0 To Ubound(this.children) + v1 += this.children(i)->weight * this.children(i)->coverage + v2 += this.children(i)->weight + Next + If v2 <> 0 Then this.setCoverage(v1 / v2) +End Sub + +Sub FCNode.show(level As Integer) + Dim As Integer indent, nl, i + + indent = level * 4 + nl = Len(this.nombre) + indent + Print Space(indent); this.nombre; Space(32 - nl); "|"; Using "#####"; this.weight; + Print Using " | #.###### |"; this.coverage + If Ubound(this.children) = -1 Then Return + For i = 0 To Ubound(this.children) + this.children(i)->show(level + 1) + Next +End Sub + +Function newFCN(nombre As String, weight As Integer, coverage As Double) As FCNode Ptr + Return New FCNode(nombre, weight, coverage) +End Function + +Dim houses(1) As FCNode Ptr +houses(0) = newFCN("house1", 40, 0) +houses(1) = newFCN("house2", 60, 0) + +Dim house1(7) As FCNode Ptr +house1(0) = newFCN("bedrooms", 1, 0.25) +house1(1) = newFCN("bathrooms", 1, 0) +house1(2) = newFCN("attic", 1, 0.75) +house1(3) = newFCN("kitchen", 1, 0.1) +house1(4) = newFCN("living_rooms", 1, 0) +house1(5) = newFCN("basement", 1, 0) +house1(6) = newFCN("garage", 1, 0) +house1(7) = newFCN("garden", 1, 0.8) + +Dim house2(2) As FCNode Ptr +house2(0) = newFCN("upstairs", 1, 0) +house2(1) = newFCN("groundfloor", 1, 0) +house2(2) = newFCN("basement", 1, 0) + +Dim h1Bathrooms(2) As FCNode Ptr +h1Bathrooms(0) = newFCN("bathroom1", 1, 0.5) +h1Bathrooms(1) = newFCN("bathroom2", 1, 0) +h1Bathrooms(2) = newFCN("outside_lavatory", 1, 1) + +Dim h1LivingRooms(3) As FCNode Ptr +h1LivingRooms(0) = newFCN("lounge", 1, 0) +h1LivingRooms(1) = newFCN("dining_room", 1, 0) +h1LivingRooms(2) = newFCN("conservatory", 1, 0) +h1LivingRooms(3) = newFCN("playroom", 1, 1) + +Dim h2Upstairs(3) As FCNode Ptr +h2Upstairs(0) = newFCN("bedrooms", 1, 0) +h2Upstairs(1) = newFCN("bathroom", 1, 0) +h2Upstairs(2) = newFCN("toilet", 1, 0) +h2Upstairs(3) = newFCN("attics", 1, 0.6) + +Dim h2Groundfloor(5) As FCNode Ptr +h2Groundfloor(0) = newFCN("kitchen", 1, 0) +h2Groundfloor(1) = newFCN("living_rooms", 1, 0) +h2Groundfloor(2) = newFCN("wet_room_&_toilet", 1, 0) +h2Groundfloor(3) = newFCN("garage", 1, 0) +h2Groundfloor(4) = newFCN("garden", 1, 0.9) +h2Groundfloor(5) = newFCN("hot_tub_suite", 1, 1) + +Dim h2Basement(2) As FCNode Ptr +h2Basement(0) = newFCN("cellars", 1, 1) +h2Basement(1) = newFCN("wine_cellar", 1, 1) +h2Basement(2) = newFCN("cinema", 1, 0.75) + +Dim h2UpstairsBedrooms(3) As FCNode Ptr +h2UpstairsBedrooms(0) = newFCN("suite_1", 1, 0) +h2UpstairsBedrooms(1) = newFCN("suite_2", 1, 0) +h2UpstairsBedrooms(2) = newFCN("bedroom_3", 1, 0) +h2UpstairsBedrooms(3) = newFCN("bedroom_4", 1, 0) + +Dim h2GroundfloorLivingRooms(3) As FCNode Ptr +h2GroundfloorLivingRooms(0) = newFCN("lounge", 1, 0) +h2GroundfloorLivingRooms(1) = newFCN("dining_room", 1, 0) +h2GroundfloorLivingRooms(2) = newFCN("conservatory", 1, 0) +h2GroundfloorLivingRooms(3) = newFCN("playroom", 1, 0) + +Dim cleaning As FCNode Ptr = newFCN("cleaning", 1, 0) + +house1(1)->addChildren(h1Bathrooms()) +house1(4)->addChildren(h1LivingRooms()) +houses(0)->addChildren(house1()) + +h2Upstairs(0)->addChildren(h2UpstairsBedrooms()) +house2(0)->addChildren(h2Upstairs()) +h2Groundfloor(1)->addChildren(h2GroundfloorLivingRooms()) +house2(1)->addChildren(h2Groundfloor()) +house2(2)->addChildren(h2Basement()) +houses(1)->addChildren(house2()) + +cleaning->addChildren(houses()) +Dim As Double topCoverage = cleaning->coverage +Print "TOP COVERAGE = "; +Print Using "########.######"; topCoverage +Print +Print "NAME HIERARCHY | WEIGHT | COVERAGE |" +cleaning->show(0) + +h2Basement(2)->setCoverage(1) ' change Cinema node coverage to 1 +Dim As Double diff = cleaning->coverage - topCoverage +Print +Print "If the coverage of the Cinema node were increased from 0.75 to 1" +Print "the top level coverage would increase by "; +Print Using "##.###### to ##.######"; diff; (topCoverage + diff) +h2Basement(2)->setCoverage(0.75) ' restore to original value if required + +Sleep diff --git a/Task/Functional-coverage-tree/Java/functional-coverage-tree.java b/Task/Functional-coverage-tree/Java/functional-coverage-tree.java index 8fd0797f54..703ad2b3f5 100644 --- a/Task/Functional-coverage-tree/Java/functional-coverage-tree.java +++ b/Task/Functional-coverage-tree/Java/functional-coverage-tree.java @@ -78,7 +78,8 @@ public final class FunctionalCoverageTree { ground_floor.get(1).addChildren(living_rooms_house_2); final double overallCoverage = cleaning.getCoverage(); - System.out.println("OVERALL COVERAGE = " + String.format("%.6f", overallCoverage) + System.lineSeparator()); + System.out.println("OVERALL COVERAGE = " + String.format("%.6f", overallCoverage)); + System.out.println(); System.out.println("NAME HIERARCHY | WEIGHT | COVERAGE |" ); System.out.println("--------------------------------|--------|----------|"); cleaning.display(); @@ -129,14 +130,14 @@ final class FCNode { } private void updateCoverage() { - double value1 = 0.0; - int value2 = 0; + double sumWeightedCoverage = 0.0; + int sumWeight = 0; for ( FCNode node : children ) { - value1 += node.weight * node.coverage; - value2 += node.weight; + sumWeightedCoverage += node.weight * node.coverage; + sumWeight += node.weight; } - setCoverage(value1 / value2); + setCoverage(sumWeightedCoverage / sumWeight); } private void display(int aLevel) { diff --git a/Task/Functional-coverage-tree/Julia/functional-coverage-tree.julia b/Task/Functional-coverage-tree/Julia/functional-coverage-tree.jl similarity index 100% rename from Task/Functional-coverage-tree/Julia/functional-coverage-tree.julia rename to Task/Functional-coverage-tree/Julia/functional-coverage-tree.jl diff --git a/Task/Functional-coverage-tree/Kotlin/functional-coverage-tree.kotlin b/Task/Functional-coverage-tree/Kotlin/functional-coverage-tree.kts similarity index 100% rename from Task/Functional-coverage-tree/Kotlin/functional-coverage-tree.kotlin rename to Task/Functional-coverage-tree/Kotlin/functional-coverage-tree.kts diff --git a/Task/Functional-coverage-tree/Phix/functional-coverage-tree.phix b/Task/Functional-coverage-tree/Phix/functional-coverage-tree.phix index 7f57dc15f2..da5f44351a 100644 --- a/Task/Functional-coverage-tree/Phix/functional-coverage-tree.phix +++ b/Task/Functional-coverage-tree/Phix/functional-coverage-tree.phix @@ -1,113 +1,108 @@ -(phixonline)--> - -- - -- demo\rosetta\Functional_coverage_tree.exw - -- ========================================= - -- - with javascript_semantics - constant data = """ - NAME_HIERARCHY | WEIGHT | COVERAGE | - cleaning | | | - house1 |40 | | - bedrooms | |0.25 | - bathrooms | | | - bathroom1 | |0.5 | - bathroom2 | | | - outside_lavatory | |1 | - attic | |0.75 | - kitchen | |0.1 | - living_rooms | | | - lounge | | | - dining_room | | | - conservatory | | | - playroom | |1 | - basement | | | - garage | | | - garden | |0.8 | - house2 |60 | | - upstairs | | | - bedrooms | | | - suite_1 | | | - suite_2 | | | - bedroom_3 | | | - bedroom_4 | | | - bathroom | | | - toilet | | | - attics | |0.6 | - groundfloor | | | - kitchen | | | - living_rooms | | | - lounge | | | - dining_room | | | - conservatory | | | - playroom | | | - wet_room_&_toilet | | | - garage | | | - garden | |0.9 | - hot_tub_suite | |1 | - basement | | | - cellars | |1 | - wine_cellar | |1 | - cinema | |0.75 | - """ - sequence lines = split(data,"\n"), - pi = {}, -- indents (to locate parents) - pdx = {}, -- indexes for "" - children - string desc, weights, covers - integer parent, child - atom weight, coverage, childw = 0 - enum DESC, WEIGHT, COVERAGE, PARENT, CHILDREN, CHILDW - lines[1] &= " SHARE OF RESIDUE" - for i=2 to length(lines) do - -- decode text to useable data, link up parents & children - {desc,weights,covers} = split(lines[i],"|") - -- (nb this assumes /totally/ consistent indenting) - integer indent = length(desc)-length(trim_head(desc)), - k = find(indent,pi) - if k=0 then - pi = append(pi,indent) - pdx = append(pdx,0) - k = length(pi) - end if - pdx[k] = i - parent = 0 - if k>1 then - parent = pdx[k-1] - -- lines[parent][CHILDREN] &= i - lines[parent][CHILDREN] = deep_copy(lines[parent][CHILDREN]) & i - end if - children = {} - weight = to_number(trim(weights),1) - coverage = to_number(trim(covers),0) - lines[i] = {desc, weight, coverage, parent, children, childw} - end for - for i=length(lines) to 2 by -1 do - -- calculate the parent coverages, and save child weight sums - children = lines[i][CHILDREN] - if length(children) then - coverage = 0 - childw = 0 - for c=1 to length(children) do - child = children[c] - atom w = lines[child][WEIGHT] - coverage += lines[child][COVERAGE]*w - childw += w - end for - lines[i][COVERAGE] = coverage/childw - lines[i][CHILDW] = childw -- (save for next loop) - end if - end for - for i=length(lines) to 2 by -1 do - -- calculate the share of residue, and format lines - child = i - {desc, weight, coverage, parent} = lines[i] - atom residue = 1-coverage - while parent do - residue *= lines[child][WEIGHT]/lines[parent][CHILDW] - {child, parent} = {parent, lines[parent][PARENT]} - end while - lines[i] = sprintf("%-32s| %6d | %-8g | %g",{desc,weight,coverage,residue}) - end for - puts(1,join(lines,"\n")&"\n") - {} = wait_key() - - with javascript_semantics - sequence c = repeat(0,12) - function spouge_gamma(atom z) - atom accm = c[1] - if accm=0 then - accm = sqrt(2*PI) - c[1] = accm - atom k1_factrl = 1 -- (k - 1)!*(-1)^k with 0!==1 - for k=2 to 12 do - c[k] = exp(13-k)*power(13-k,k-1.5)/k1_factrl - k1_factrl *= -(k-1) - end for - end if - for k=2 to 12 do - accm += c[k]/(z+k-1) - end for - accm *= exp(-(z+12))*power(z+12,z+0.5) -- Gamma(z+1) - return accm/z - end function +with javascript_semantics +sequence c = repeat(0,12) +function spouge_gamma(atom z) + atom accm = c[1] + if accm=0 then + accm = sqrt(2*PI) + c[1] = accm + atom k1_factrl = 1 -- (k - 1)!*(-1)^k with 0!==1 + for k=2 to 12 do + c[k] = exp(13-k)*power(13-k,k-1.5)/k1_factrl + k1_factrl *= -(k-1) + end for + end if + for k=2 to 12 do + accm += c[k]/(z+k-1) + end for + accm *= exp(-(z+12))*power(z+12,z+0.5) -- Gamma(z+1) + return accm/z +end function - function taylor_gamma(atom x) - -- (good for values between 0 and 1, apparently) - constant t = { 1.00000_00000_00000_00000, - 0.57721_56649_01532_86061, - -0.65587_80715_20253_88108, - -0.04200_26350_34095_23553, - 0.16653_86113_82291_48950, - -0.04219_77345_55544_33675, - -0.00962_19715_27876_97356, - 0.00721_89432_46663_09954, - -0.00116_51675_91859_06511, - -0.00021_52416_74114_95097, - 0.00012_80502_82388_11619, - -0.00002_01348_54780_78824, - -0.00000_12504_93482_14267, - 0.00000_11330_27231_98170, - -0.00000_02056_33841_69776, - 0.00000_00061_16095_10448, - 0.00000_00050_02007_64447, - -0.00000_00011_81274_57049, - 0.00000_00001_04342_67117, - 0.00000_00000_07782_26344, - -0.00000_00000_03696_80562, - 0.00000_00000_00510_03703, - -0.00000_00000_00020_58326, - -0.00000_00000_00005_34812, - 0.00000_00000_00001_22678, - -0.00000_00000_00000_11813, - 0.00000_00000_00000_00119, - 0.00000_00000_00000_00141, - -0.00000_00000_00000_00023, - 0.00000_00000_00000_00002 } - atom y = x-1, - s = t[$] - for n=length(t)-1 to 1 by -1 do - s = s*y + t[n] - end for - return 1/s - end function +function taylor_gamma(atom x) +-- (good for values between 0 and 1, apparently) + constant t = { 1.00000_00000_00000_00000, + 0.57721_56649_01532_86061, + -0.65587_80715_20253_88108, + -0.04200_26350_34095_23553, + 0.16653_86113_82291_48950, + -0.04219_77345_55544_33675, + -0.00962_19715_27876_97356, + 0.00721_89432_46663_09954, + -0.00116_51675_91859_06511, + -0.00021_52416_74114_95097, + 0.00012_80502_82388_11619, + -0.00002_01348_54780_78824, + -0.00000_12504_93482_14267, + 0.00000_11330_27231_98170, + -0.00000_02056_33841_69776, + 0.00000_00061_16095_10448, + 0.00000_00050_02007_64447, + -0.00000_00011_81274_57049, + 0.00000_00001_04342_67117, + 0.00000_00000_07782_26344, + -0.00000_00000_03696_80562, + 0.00000_00000_00510_03703, + -0.00000_00000_00020_58326, + -0.00000_00000_00005_34812, + 0.00000_00000_00001_22678, + -0.00000_00000_00000_11813, + 0.00000_00000_00000_00119, + 0.00000_00000_00000_00141, + -0.00000_00000_00000_00023, + 0.00000_00000_00000_00002 } + atom y = x-1, + s = t[$] + for n=length(t)-1 to 1 by -1 do + s = s*y + t[n] + end for + return 1/s +end function - function lanczos_gamma(atom z) - if z<0.5 then - return PI / (sin(PI*z)*lanczos_gamma(1-z)) - end if - -- use a lanczos approximation: - atom x = 0.99999999999980993, - t = z + 6.5; - sequence p = { 676.5203681218851, - -1259.1392167224028, - 771.32342877765313, - -176.61502916214059, - 12.507343278686905, - -0.13857109526572012, - 9.9843695780195716e-6, - 1.5056327351493116e-7 } - z -= 1 - for i=1 to length(p) do - x += p[i] / (z + i) - end for - return sqrt(2*PI) * power(t,z+0.5) * exp(-t) * x - end function +function lanczos_gamma(atom z) + if z<0.5 then + return PI / (sin(PI*z)*lanczos_gamma(1-z)) + end if + -- use a lanczos approximation: + atom x = 0.99999999999980993, + t = z + 6.5; + sequence p = { 676.5203681218851, + -1259.1392167224028, + 771.32342877765313, + -176.61502916214059, + 12.507343278686905, + -0.13857109526572012, + 9.9843695780195716e-6, + 1.5056327351493116e-7 } + z -= 1 + for i=1 to length(p) do + x += p[i] / (z + i) + end for + return sqrt(2*PI) * power(t,z+0.5) * exp(-t) * x +end function - constant sqPI = sqrt(PI) +constant sqPI = sqrt(PI) - procedure sq(sequence zm, string fmt="%19.16f") - atom {z, mul} = zm - atom e = sqPI/mul - sequence s = {spouge_gamma(z), - taylor_gamma(z), - lanczos_gamma(z)}, - error = sq_abs(sq_sub(s,e)) - string t = join(s,", ",fmt:=fmt)&", " - integer bdx = smallest(error,return_index:=true) - atom best = s[bdx], - p = s[bdx]*mul - for i=1 to length(s) do -- (potentially mark >1) - if s[i]=best then - t[i*22-2..i*22-1] = "*," - end if - end for - string es = sprintf(fmt,e) - printf(1,"%5g: %s %s, %19.16f\n",{z,t,es,p*p}) - end procedure +procedure sq(sequence zm, string fmt="%19.16f") + atom {z, mul} = zm + atom e = sqPI/mul + sequence s = {spouge_gamma(z), + taylor_gamma(z), + lanczos_gamma(z)}, + error = sq_abs(sq_sub(s,e)) + string t = join(s,", ",fmt:=fmt)&", " + integer bdx = smallest(error,return_index:=true) + atom best = s[bdx], + p = s[bdx]*mul + for i=1 to length(s) do -- (potentially mark >1) + if s[i]=best then + t[i*22-2..i*22-1] = "*," + end if + end for + string es = sprintf(fmt,e) + printf(1,"%5g: %s %s, %19.16f\n",{z,t,es,p*p}) +end procedure - printf(1," z ------ spouge ----- ----- taylor ------ ----- lanczos ----- ---- expected ----- %19.16f\n",PI) - papply({{-3/2,3/4},{-1/2,-1/2},{1/2,1},{1,sqPI},{3/2,2},{2,sqPI},{5/2,4/3},{3,sqPI/2},{7/2,8/15},{4,sqPI/6}},sq) - sq({0.001,sqPI/999.4237725},"%19.15f") - sq({0.01,sqPI/99.43258512},"%19.16f") - sq({0.1,sqPI/9.513507699},"%19.16f") - sq({10,sqPI/362880},"%19.12f") - sq({100,sqPI/9.332621544e155},"%19.13g") - if machine_bits()=64 then - sq({150,sqPI/3.808922638e260},"%19.13g") -- (fatal power overflow error on 32 bits) - end if - - without javascript_semantics -- (no mpfr_exp(), mpfr_gamma() in pwa/p2js) - constant dp = 30 - string fmt = "%5s: %33s, %33s, %32s\n" - requires("1.0.2") -- (mpfr_get_fixed(maxlen), mpfr_gamma) - include mpfr.e - mpfr_set_default_precision(-87) -- 87 decimal places. - sequence mc = mpfr_inits(40) +without javascript_semantics -- (no mpfr_exp(), mpfr_gamma() in pwa/p2js) +constant dp = 30 +string fmt = "%5s: %33s, %33s, %32s\n" +requires("1.0.2") -- (mpfr_get_fixed(maxlen), mpfr_gamma) +include mpfr.e +mpfr_set_default_precision(-87) -- 87 decimal places. +sequence mc = mpfr_inits(40) - function mpfr_spouge_gamma(mpfr z) - mpfr accm = mc[1] - if mpfr_cmp_si(accm,0)=0 then - -- mc[1] := sqrt(2*PI) - mpfr_const_pi(accm) - mpfr_mul_si(accm,accm,2) - mpfr_sqrt(accm,accm) - -- k1_factrl = (k - 1)!*(-1)^k with 0!==1 - mpfr k1_factrl = mpfr_init(1), - tmk = mpfr_init(), - p = mpfr_init() - for k=2 to length(mc) do - -- mc[k] = exp(13-k)*power(13-k,k-1.5)/k1_factrl - mpfr_set_si(tmk,length(mc)+1-k) - mpfr_exp(mc[k],tmk) - mpfr_set_d(p,k-1.5) - mpfr_pow(p,tmk,p) - mpfr_div(p,p,k1_factrl) - mpfr_mul(mc[k],mc[k],p) - -- k1_factrl *= -(k-1) - mpfr_mul_si(k1_factrl,k1_factrl,-(k-1)) - end for - end if - accm = mpfr_init_set(accm) - for k=2 to length(mc) do - -- accm += mc[k]/(z+k-1) - mpfr ck = mpfr_init_set(mc[k]), - zk = mpfr_init_set(z) - mpfr_add_si(zk,zk,k-1) - mpfr_div(ck,ck,zk) - mpfr_add(accm,accm,ck) - end for - -- atom zc = z+length(mc) - -- accm *= exp(-zc)*power(zc,z+0.5) -- Gamma(z+1) - mpfr p = mpfr_init_set(z), - ez = mpfr_init(), - zh = mpfr_init(0.5) - mpfr_add_si(p,p,length(mc)) - mpfr_neg(ez,p) - mpfr_exp(ez,ez) - mpfr_add(zh,zh,z) - mpfr_pow(p,p,zh) - mpfr_mul(accm,accm,ez) - mpfr_mul(accm,accm,p) - -- return accm/z - mpfr_div(accm,accm,z) - return accm - end function +function mpfr_spouge_gamma(mpfr z) + mpfr accm = mc[1] + if mpfr_cmp_si(accm,0)=0 then + -- mc[1] := sqrt(2*PI) + mpfr_const_pi(accm) + mpfr_mul_si(accm,accm,2) + mpfr_sqrt(accm,accm) + -- k1_factrl = (k - 1)!*(-1)^k with 0!==1 + mpfr k1_factrl = mpfr_init(1), + tmk = mpfr_init(), + p = mpfr_init() + for k=2 to length(mc) do + -- mc[k] = exp(13-k)*power(13-k,k-1.5)/k1_factrl + mpfr_set_si(tmk,length(mc)+1-k) + mpfr_exp(mc[k],tmk) + mpfr_set_d(p,k-1.5) + mpfr_pow(p,tmk,p) + mpfr_div(p,p,k1_factrl) + mpfr_mul(mc[k],mc[k],p) + -- k1_factrl *= -(k-1) + mpfr_mul_si(k1_factrl,k1_factrl,-(k-1)) + end for + end if + accm = mpfr_init_set(accm) + for k=2 to length(mc) do + -- accm += mc[k]/(z+k-1) + mpfr ck = mpfr_init_set(mc[k]), + zk = mpfr_init_set(z) + mpfr_add_si(zk,zk,k-1) + mpfr_div(ck,ck,zk) + mpfr_add(accm,accm,ck) + end for + -- atom zc = z+length(mc) + -- accm *= exp(-zc)*power(zc,z+0.5) -- Gamma(z+1) + mpfr p = mpfr_init_set(z), + ez = mpfr_init(), + zh = mpfr_init(0.5) + mpfr_add_si(p,p,length(mc)) + mpfr_neg(ez,p) + mpfr_exp(ez,ez) + mpfr_add(zh,zh,z) + mpfr_pow(p,p,zh) + mpfr_mul(accm,accm,ez) + mpfr_mul(accm,accm,p) + -- return accm/z + mpfr_div(accm,accm,z) + return accm +end function - constant mPI = mpfr_init(), - mqPI = mpfr_init() - mpfr_const_pi(mPI) - string pistr = mpfr_get_fixed(mPI,dp) - mpfr_sqrt(mqPI,mPI) +constant mPI = mpfr_init(), + mqPI = mpfr_init() +mpfr_const_pi(mPI) +string pistr = mpfr_get_fixed(mPI,dp) +mpfr_sqrt(mqPI,mPI) - function makempfr(object x) - mpfr res - if string(x) then - x = split(x,'/') - res = mpfr_init(x[1]) - mpfr_div_si(res,res,to_integer(x[2])) - elsif sequence(x) then - {mpfr x1, object x2} = x - res = mpfr_init_set(x1) - if string(x2) then - mpfr d = mpfr_init(x2) - mpfr_div(res,res,d) - else - mpfr_div_d(res,res,x2) - end if - else - res = mpfr_init(x) - end if - return res - end function +function makempfr(object x) + mpfr res + if string(x) then + x = split(x,'/') + res = mpfr_init(x[1]) + mpfr_div_si(res,res,to_integer(x[2])) + elsif sequence(x) then + {mpfr x1, object x2} = x + res = mpfr_init_set(x1) + if string(x2) then + mpfr d = mpfr_init(x2) + mpfr_div(res,res,d) + else + mpfr_div_d(res,res,x2) + end if + else + res = mpfr_init(x) + end if + return res +end function - procedure mq(sequence zm, integer d=dp) - mpfr {z, mul} = apply(zm,makempfr) - mpfr s = mpfr_spouge_gamma(z) - string t = mpfr_get_fixed(s,d,10,maxlen:=dp+2) - mpfr e = mpfr_init() - mpfr_gamma(e,z) - mpfr p = mpfr_init_set(s) - mpfr_mul(p,p,mul) - mpfr_mul(p,p,p) - string zs = mpfr_get_fixed(z,3), - es = mpfr_get_fixed(e,d,10,maxlen:=dp+2), - ps = mpfr_get_fixed(p,dp,10) - printf(1,fmt,{zs,t,es,ps}) - end procedure +procedure mq(sequence zm, integer d=dp) + mpfr {z, mul} = apply(zm,makempfr) + mpfr s = mpfr_spouge_gamma(z) + string t = mpfr_get_fixed(s,d,10,maxlen:=dp+2) + mpfr e = mpfr_init() + mpfr_gamma(e,z) + mpfr p = mpfr_init_set(s) + mpfr_mul(p,p,mul) + mpfr_mul(p,p,p) + string zs = mpfr_get_fixed(z,3), + es = mpfr_get_fixed(e,d,10,maxlen:=dp+2), + ps = mpfr_get_fixed(p,dp,10) + printf(1,fmt,{zs,t,es,ps}) +end procedure - printf(1," z %s %s %s\n",{pad(" spouge ",dp+2,"BOTH",'-'),pad(" expected ",dp+2,"BOTH",'-'),pistr}) - papply({{-1.5,0.75},{-0.5,-0.5},{0.5,1},{1,{mqPI,1}},{1.5,2},{2,{mqPI,1}},{2.5,"4/3"},{3,{mqPI,2}},{3.5,"8/15"},{4,{mqPI,6}}},mq) - mq({"1/1000",{mqPI,"999.4237724845954661149822012996"}},28) - mq({"1/100",{mqPI,"99.43258511915060371353298887051"}},29) - mq({"1/10",{mqPI,"9.513507698668731836292487177265"}},30) - mq({10,{mqPI,362880}},25) - mq({100,{mqPI,"9.332621544394415268169923885627e155"}},0) - mq({150,{mqPI,"3.80892263763056972698595524350735e260"}},0) - - constant starts = {1e2, 1e6, 1e7, 1e9, 7123}, - counts = {30, 15, 15, 10, 25} - for i=1 to length(starts) do - integer count = counts[i], - j = starts[i], - pow = 100 - while j>=pow*10 do pow *= 10 end while - printf(1,"First %d gapful numbers starting at %,d: ", {count, j}) - while count do - integer fl = floor(j/pow)*10 + remainder(j,10) - if remainder(j,fl)==0 then - printf(1,"%d ", j) - count -= 1 - end if - j += 1 - if j>=10*pow then - pow *= 10 - end if - end while - printf(1,"\n") - end for - iterator +fcn gapfulW(start){ //--> iterator [start..].tweak( fcn(n){ if(n % (10*n.toString()[0] + n%10)) Void.Skip else n }) } diff --git a/Task/Gauss-Jordan-matrix-inversion/ALGOL-68/gauss-jordan-matrix-inversion.alg b/Task/Gauss-Jordan-matrix-inversion/ALGOL-68/gauss-jordan-matrix-inversion.alg index 2b79d01805..14b3603189 100644 --- a/Task/Gauss-Jordan-matrix-inversion/ALGOL-68/gauss-jordan-matrix-inversion.alg +++ b/Task/Gauss-Jordan-matrix-inversion/ALGOL-68/gauss-jordan-matrix-inversion.alg @@ -43,16 +43,17 @@ BEGIN # Gauss-Jordan matrix inversion # OD END # show #; - INT n = 4; - [ 1 : n, 1 : n ]REAL a, b, c; - a := [,]REAL( ( 2, 1, 1, 4 ) - , ( 0, -1, 0, -1 ) - , ( 1, 0, -2, 4 ) - , ( 4, 1, 2, 2 ) - ); - show( "a", a ); - b := inverse( a ); - show( "b", b ); - c := inverse( b ); - show( "c", c ) + BEGIN # test # + [ 1 : 4, 1 : 4 ]REAL a, b, c; + a := [,]REAL( ( 2, 1, 1, 4 ) + , ( 0, -1, 0, -1 ) + , ( 1, 0, -2, 4 ) + , ( 4, 1, 2, 2 ) + ); + show( "a", a ); + b := inverse( a ); + show( "b", b ); + c := inverse( b ); + show( "c", c ) + END END diff --git a/Task/Gauss-Jordan-matrix-inversion/Agena/gauss-jordan-matrix-inversion.agena b/Task/Gauss-Jordan-matrix-inversion/Agena/gauss-jordan-matrix-inversion.agena new file mode 100644 index 0000000000..34361a3d27 --- /dev/null +++ b/Task/Gauss-Jordan-matrix-inversion/Agena/gauss-jordan-matrix-inversion.agena @@ -0,0 +1,81 @@ +scope # Gauss Jordan Matrix inversion - translation of the EasyLang sample + + local proc rref( m :: sequence ) + local nrow, ncol, lead := size m, size m[1], 1; + for r to nrow do + if lead > ncol then return fi; + local i := r; + while m[i][lead] = 0 do + i +:= 1; + if i > nrow then + i, lead := r, lead + 1 + if lead > ncol then return fi + fi + od; + m[i], m[r] := m[r], m[i]; + scope + local constant mrl := m[r][lead] + for k to ncol do m[r][k] /:= mrl od + end + for i to nrow do + if i <> r then + local constant mil := m[i][lead]; + for k to ncol do + m[i][k] -:= ( mil * m[r][k] ) + od + fi + od; + lead +:= 1 + od + end + local proc inverse( mat :: sequence ) :: sequence + local inv, mln, aug := seq(), size mat, seq(); + for i to mln do + if size mat[i] <> mln then + error( "not a square matrix" ) + fi; + aug[ size aug + 1 ] := seq(); + for j to mln do aug[i][j] := mat[i][j] od; + for j from mln + 1 to 2 * mln do aug[i][j] := 0 od; + aug[i][mln + i] := 1 + od; + rref( aug ); + for i to mln do + inv[ size inv + 1 ] := seq(); + for j from mln + 1 to 2 * mln do + inv[i][ size inv[i] + 1 ] := aug[i][j] + od + od; + return inv + end + local proc integerMatrix( m :: sequence ) :: boolean + for i to size m do + for j to size m[ i ] do + if entier m[ i ][ j ] <> m[ i ][ j ] then return false fi + od + od; + return true + end + local proc printMatrix( m :: sequence ) + local allInteger := integerMatrix( m ) + for i to size m do + printf( if i = 1 then "[ [" else " [" fi ); + for j to size m[ i ] do + printf( if allInteger then " %9d" else " %9.6f" fi, m[ i ][ j ] ) + od; + printf( " ]\n" ) + od; + printf( "]\n" ) + end + local proc testInverse( m :: sequence ) + printf( "Matrix:\n" ); + printMatrix( m ); + printf( "Inverse:\n" ); + printMatrix( inverse( m ) ); + printf( "\n" ) + end + + testInverse( seq( (/ 1, 2, 3 \), (/ 4, 1, 6 \), (/ 7, 8, 9 \) ) ); + testInverse( seq( (/ 2, -1, 0 \), (/ -1, 2, -1 \), (/ 0, -1, 2 \) ) ); + testInverse( seq( (/ -1, -2, 3, 2 \), (/ -4, -1, 6, 2 \), (/ 7, -8, 9, 1 \), (/ 1, -2, 1, 3 \) ) ) +end 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 index dac0cbf67d..3027f65812 100644 --- a/Task/Gauss-Jordan-matrix-inversion/EasyLang/gauss-jordan-matrix-inversion.easy +++ b/Task/Gauss-Jordan-matrix-inversion/EasyLang/gauss-jordan-matrix-inversion.easy @@ -1,39 +1,31 @@ -proc rref . m[][] . +proc rref &m[][] . nrow = len m[][] ncol = len m[1][] lead = 1 for r to nrow - if lead > ncol - return - . + if lead > ncol : return i = r while m[i][lead] = 0 i += 1 if i > nrow i = r lead += 1 - if lead > ncol - return - . + if lead > ncol : return . . swap m[i][] m[r][] m = m[r][lead] - for k to ncol - m[r][k] /= m - . + 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] - . + for k to ncol : m[i][k] -= m * m[r][k] . . lead += 1 . . -proc inverse . mat[][] inv[][] . +proc inverse &mat[][] &inv[][] . inv[][] = [ ] ln = len mat[][] for i to ln @@ -43,9 +35,7 @@ proc inverse . mat[][] inv[][] . . aug[][] &= [ ] len aug[i][] 2 * ln - for j to ln - aug[i][j] = mat[i][j] - . + for j to ln : aug[i][j] = mat[i][j] aug[i][ln + i] = 1 . rref aug[][] diff --git a/Task/Gauss-Jordan-matrix-inversion/JavaScript/gauss-jordan-matrix-inversion.js b/Task/Gauss-Jordan-matrix-inversion/JavaScript/gauss-jordan-matrix-inversion.js new file mode 100644 index 0000000000..854bc332e7 --- /dev/null +++ b/Task/Gauss-Jordan-matrix-inversion/JavaScript/gauss-jordan-matrix-inversion.js @@ -0,0 +1,99 @@ +// Vector and matrix types +// In JavaScript, we'll use arrays directly + +function printMatrix(matrix, title) { + console.log(title); + for (const row of matrix) { + console.log(row.map(x => x.toString().padStart(10)).join('')); + } +} + +function createIdentityMatrix(n) { + const result = Array(n).fill().map(() => Array(n).fill(0)); + for (let i = 0; i < n; i++) { + result[i][i] = 1; + } + return result; +} + +function inverse(matrix) { + const n = matrix.length; + + // Check if it's a square matrix + for (const row of matrix) { + if (row.length !== n) { + throw new Error("Not a square matrix"); + } + } + + // Create identity matrix for the result + const b = createIdentityMatrix(n); + + // Create a copy of the input matrix + const a = matrix.map(row => [...row]); + + for (let k = 0; k < n; k++) { + let iMax = 0; + let max = -1; + + for (let i = k; i < n; i++) { + const row = a[i]; + + // Compute scale factor s = max abs in row + let s = -1; + for (let j = k; j < n; j++) { + const x = Math.abs(row[j]); + if (x > s) { + s = x; + } + } + + if (s === 0) { + throw new Error("Irregular matrix"); + } + + // Scale the abs used to pick the pivot + const abs = Math.abs(row[k]) / s; + if (abs > max) { + iMax = i; + max = abs; + } + } + + // Swap rows if needed + if (k !== iMax) { + [a[k], a[iMax]] = [a[iMax], a[k]]; + [b[k], b[iMax]] = [b[iMax], b[k]]; + } + + const akk = a[k][k]; + + for (let j = 0; j < n; j++) { + a[k][j] /= akk; + b[k][j] /= akk; + } + + for (let i = 0; i < n; i++) { + if (i !== k) { + const aik = a[i][k]; + for (let j = 0; j < n; j++) { + a[i][j] -= a[k][j] * aik; + b[i][j] -= b[k][j] * aik; + } + } + } + } + + return b; +} + +function main() { + const a = [[1, 2, 3], [4, 1, 6], [7, 8, 9]]; + printMatrix(inverse(a), "Inverse of A is:\n"); + + const b = [[2, -1, 0], [-1, 2, -1], [0, -1, 2]]; + printMatrix(inverse(b), "Inverse of B is:\n"); +} + +// Run the main function +main(); diff --git a/Task/Gauss-Jordan-matrix-inversion/Julia/gauss-jordan-matrix-inversion-1.julia b/Task/Gauss-Jordan-matrix-inversion/Julia/gauss-jordan-matrix-inversion-1.jl similarity index 100% rename from Task/Gauss-Jordan-matrix-inversion/Julia/gauss-jordan-matrix-inversion-1.julia rename to Task/Gauss-Jordan-matrix-inversion/Julia/gauss-jordan-matrix-inversion-1.jl diff --git a/Task/Gauss-Jordan-matrix-inversion/Julia/gauss-jordan-matrix-inversion-2.julia b/Task/Gauss-Jordan-matrix-inversion/Julia/gauss-jordan-matrix-inversion-2.jl similarity index 100% rename from Task/Gauss-Jordan-matrix-inversion/Julia/gauss-jordan-matrix-inversion-2.julia rename to Task/Gauss-Jordan-matrix-inversion/Julia/gauss-jordan-matrix-inversion-2.jl diff --git a/Task/Gauss-Jordan-matrix-inversion/Kotlin/gauss-jordan-matrix-inversion.kotlin b/Task/Gauss-Jordan-matrix-inversion/Kotlin/gauss-jordan-matrix-inversion.kts similarity index 100% rename from Task/Gauss-Jordan-matrix-inversion/Kotlin/gauss-jordan-matrix-inversion.kotlin rename to Task/Gauss-Jordan-matrix-inversion/Kotlin/gauss-jordan-matrix-inversion.kts diff --git a/Task/Gauss-Jordan-matrix-inversion/Lua/gauss-jordan-matrix-inversion.lua b/Task/Gauss-Jordan-matrix-inversion/Lua/gauss-jordan-matrix-inversion.lua new file mode 100644 index 0000000000..6eb7628293 --- /dev/null +++ b/Task/Gauss-Jordan-matrix-inversion/Lua/gauss-jordan-matrix-inversion.lua @@ -0,0 +1,81 @@ +do -- Gauss Jordan Matrix inversion - translation of the EasyLang sample + + local function rref( m ) + local nrow, ncol, lead = # m, # m[1], 1 + for r = 1, nrow do + if lead > ncol then return end + local i = r + while m[i][lead] == 0 do + i = i + 1 + if i > nrow then + i, lead = r, lead + 1 + if lead > ncol then return end + end + end + m[i], m[r] = m[r], m[i] + do + local mrl = m[r][lead] + for k = 1, ncol do m[r][k] = m[r][k] / mrl end + end + for i = 1, nrow do + if i ~= r then + local mil = m[i][lead] + for k = 1, ncol do + m[i][k] = m[i][k] - ( mil * m[r][k] ) + end + end + end + lead = lead + 1 + end + end + local function inverse( mat ) + local inv, ln, aug = {}, # mat, {} + for i = 1, ln do + if # mat[i] ~= ln then + error( "not a square matrix" ) + end + aug[ # aug + 1 ] = {} + for j = 1, ln do aug[i][j] = mat[i][j] end + for j = ln + 1, 2 * ln do aug[i][j] = 0 end + aug[i][ln + i] = 1 + end + rref( aug ) + for i = 1, ln do + inv[ # inv + 1 ] = {} + for j = ln + 1, 2 * ln do + inv[i][ # inv[i] + 1 ] = aug[i][j] + end + end + return inv + end + local function integerMatrix( m ) + for i = 1, # m do + for j = 1, # m[ i ] do + if math.type( m[ i ][ j ] ) ~= "integer" then return false end + end + end + return true + end + local function printMatrix( m ) + local allInteger = integerMatrix( m ) + for i = 1, # m do + io.write( i == 1 and "[ [" or " [" ) + for j = 1, # m[ i ] do + io.write( string.format( ( allInteger and " %9d" or " %9.6f" ), m[ i ][ j ] ) ) + end + io.write( " ]\n" ) + end + io.write( "]\n" ) + end + local function testInverse( m ) + io.write( "Matrix:\n" ) + printMatrix( m ) + io.write( "Inverse:\n" ) + printMatrix( inverse( m ) ) + io.write( "\n" ) + end + + testInverse { { 1, 2, 3 }, { 4, 1, 6 }, { 7, 8, 9 } } + testInverse { { 2, -1, 0 }, {-1, 2, -1 }, { 0, -1, 2 } } + testInverse { { -1, -2, 3, 2 }, { -4, -1, 6, 2 }, { 7, -8, 9, 1 }, { 1, -2, 1, 3 } } +end diff --git a/Task/Gauss-Jordan-matrix-inversion/PascalABC.NET/gauss-jordan-matrix-inversion.pas b/Task/Gauss-Jordan-matrix-inversion/PascalABC.NET/gauss-jordan-matrix-inversion.pas new file mode 100644 index 0000000000..3c25363004 --- /dev/null +++ b/Task/Gauss-Jordan-matrix-inversion/PascalABC.NET/gauss-jordan-matrix-inversion.pas @@ -0,0 +1,9 @@ +uses NumLibABC; + +begin + var A := new Matrix(3,3,1,2,3,4,1,6,7,8,9); + 'Original:'.Println; + A.Println(10,5); + 'Inverse:'.Println; + A.Inv.Println(10,5); +end. diff --git a/Task/Gauss-Jordan-matrix-inversion/Perl/gauss-jordan-matrix-inversion.pl b/Task/Gauss-Jordan-matrix-inversion/Perl/gauss-jordan-matrix-inversion.pl index 5fa185e871..2102119749 100644 --- a/Task/Gauss-Jordan-matrix-inversion/Perl/gauss-jordan-matrix-inversion.pl +++ b/Task/Gauss-Jordan-matrix-inversion/Perl/gauss-jordan-matrix-inversion.pl @@ -61,5 +61,5 @@ for my $matrix (@tests) { my @gj = gauss_jordan_invert( @$matrix ); print "Gauss-Jordan Inverted Matrix:\n" . display(\@gj) . "\n"; my @rt = gauss_jordan_invert( @gj ); - print "After round-trip:\n" . display(\@rt) . "\n";} . "\n" + print "After round-trip:\n" . display(\@rt) . "\n"; } diff --git a/Task/Gauss-Jordan-matrix-inversion/Pluto/gauss-jordan-matrix-inversion.pluto b/Task/Gauss-Jordan-matrix-inversion/Pluto/gauss-jordan-matrix-inversion.pluto new file mode 100644 index 0000000000..103fcf3988 --- /dev/null +++ b/Task/Gauss-Jordan-matrix-inversion/Pluto/gauss-jordan-matrix-inversion.pluto @@ -0,0 +1,25 @@ +require "matrix" + +local arrays = { + { { 1, 2, 3 }, + { 4, 1, 6 }, + { 7, 8, 9 } }, + + { { 2, -1, 0 }, + {-1, 2, -1 }, + { 0, -1, 2 } }, + + { { -1, -2, 3, 2 }, + { -4, -1, 6, 2 }, + { 7, -8, 9, 1 }, + { 1, -2, 1, 3 } } +} + +for arrays as array do + print("Original:\n") + local m = matrix.from(array) + print(m) + print("\nInverse:\n") + print(m:inverse():format("%9.6f")) + print() +end diff --git a/Task/Gauss-Jordan-matrix-inversion/PowerShell/gauss-jordan-matrix-inversion.psh b/Task/Gauss-Jordan-matrix-inversion/PowerShell/gauss-jordan-matrix-inversion.ps1 similarity index 100% rename from Task/Gauss-Jordan-matrix-inversion/PowerShell/gauss-jordan-matrix-inversion.psh rename to Task/Gauss-Jordan-matrix-inversion/PowerShell/gauss-jordan-matrix-inversion.ps1 diff --git a/Task/Gauss-Jordan-matrix-inversion/R/gauss-jordan-matrix-inversion.r b/Task/Gauss-Jordan-matrix-inversion/R/gauss-jordan-matrix-inversion.r new file mode 100644 index 0000000000..6f636d34ed --- /dev/null +++ b/Task/Gauss-Jordan-matrix-inversion/R/gauss-jordan-matrix-inversion.r @@ -0,0 +1,91 @@ +gaussjordan <- function(A) { + # Check if matrix is square + if (nrow(A) != ncol(A)) { + stop("A must be a square matrix") + } + + n <- nrow(A) + + # Create augmented matrix [A | I] + M <- cbind(matrix(as.numeric(A), nrow = n, ncol = n), diag(n)) + + tmp <- numeric(2 * n) + i <- 1 + + # Forward elimination + while (i <= n) { + # Check if pivot is approximately zero + if (abs(M[i, i]) < 1e-10) { + j <- i + 1 + # Find non-zero pivot + while (j <= n && abs(M[j, i]) < 1e-10) { + j <- j + 1 + } + if (j <= n) { + # Swap rows + tmp <- M[i, ] + M[i, ] <- M[j, ] + M[j, ] <- tmp + } else { + stop("Matrix is singular, cannot compute the inverse") + } + } + + # Eliminate below pivot + if (i < n) { + for (j in (i + 1):n) { + M[j, ] <- M[j, ] - (M[j, i] / M[i, i]) * M[i, ] + } + } + i <- i + 1 + } + + i <- n + + # Backward elimination + while (i >= 1) { + # Check if pivot is approximately zero + if (abs(M[i, i]) < 1e-10) { + j <- i - 1 + # Find non-zero pivot + while (j >= 1 && abs(M[j, i]) < 1e-10) { + j <- j - 1 + } + if (j >= 1) { + # Swap rows + tmp <- M[i, ] + M[i, ] <- M[j, ] + M[j, ] <- tmp + } else { + stop("Matrix is singular, cannot compute the inverse") + } + } + + # Eliminate above pivot + if (i > 1) { + for (j in (i - 1):1) { + M[j, ] <- M[j, ] - (M[j, i] / M[i, i]) * M[i, ] + } + } + i <- i - 1 + } + + # Normalize by diagonal elements + M <- M / diag(M) + + # Return the inverse (right half of augmented matrix) + return(M[, (n + 1):(2 * n)]) +} + +# Test examples +# Example 1: Create a test matrix +A <- matrix(c(4, 3, 2, 1), nrow = 2, ncol = 2) +print(gaussjordan(A)) +print(solve(A)) # R's built-in inverse function + +# Example 2: Random matrix test +set.seed(123) +A <- matrix(runif(100), nrow = 10, ncol = 10) +result <- gaussjordan(A) +expected <- solve(A) +print(all.equal(result, expected)) # Should return TRUE diff --git a/Task/Gauss-Jordan-matrix-inversion/REXX/gauss-jordan-matrix-inversion-2.rexx b/Task/Gauss-Jordan-matrix-inversion/REXX/gauss-jordan-matrix-inversion-2.rexx index f2202efef4..475332d230 100644 --- a/Task/Gauss-Jordan-matrix-inversion/REXX/gauss-jordan-matrix-inversion-2.rexx +++ b/Task/Gauss-Jordan-matrix-inversion/REXX/gauss-jordan-matrix-inversion-2.rexx @@ -1,35 +1,64 @@ -/*REXX program performs a (square) matrix inversion using the Gauss─Jordan method. */ -data= 8 3 7 5 9 12 10 11 6 2 4 13 14 15 16 17 /*the matrix element values. */ -call build 4 /*assign data elements to the matrix. */ -call show '@', 'The matrix of order ' n " is:" /*display the (square) matrix. */ -call aux /*define the auxiliary (identity) array*/ -call invert /*invert the matrix, store result in X.*/ -call show 'X', "The inverted matrix is:" /*display (inverted) auxiliary matrix. */ -exit 0 /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -aux: x.= 0; do i=1 for n; x.i.i= 1; end; return -/*──────────────────────────────────────────────────────────────────────────────────────*/ -build: arg n; #=0; w=0; do r=1 for n /*read a row of the matrix.*/ - do c=1 for n; #= # + 1 /* " " col " " " */ - @.r.c= word(data, #); w= max(w, length(@.r.c) ) - end /*c*/ /*W: max width of a number*/ - end /*r*/; return -/*──────────────────────────────────────────────────────────────────────────────────────*/ -invert: do k=1 for n; t= @.k.k /*divide each matrix row by T. */ - do c=1 for n; @.k.c= @.k.c / t /*process row of original matrix.*/ - x.k.c= x.k.c / t /* " " " auxiliary " */ - end /*c*/ - do r=1 for n; if r==k then iterate /*skip if R is the same row as K.*/ - t= @.r.k - do c=1 for n; @.r.c= @.r.c - t*@.k.c /*process row of original matrix.*/ - x.r.c= x.r.c - t*x.k.c /* " " " auxiliary " */ - end /*c*/ - end /*r*/ - end /*k*/; return -/*──────────────────────────────────────────────────────────────────────────────────────*/ -show: parse arg ?, title; say; say title; f= 4 /*F: fractional digits precision.*/ - do r=1 for n; _= - do c=1 for n; if ?=='@' then _= _ right( @.r.c, w) - else _= _ right(format(x.r.c, w, f), w + f + length(.)) - end /*c*/; say _ - end /*r*/; return +/*REXX program performs a (square) matrix inversion using the Gauss-Jordan method. */ +data=8 3 7 5 9 12 10 11 6 2 4 13 14 15 16 17 /*the matrix element values. */ +Call build 4 /*assign data elements to the matrix. */ +Call show 'M','The matrix of order' n 'is:' /*display the (square) matrix. */ +Call aux /*define the auxiliary (identity) array*/ +Call invert /*invert the matrix, store result in X.*/ +Call show 'X','The inverted matrix is:' /*display inverted matrix. */ +Exit /*stick a fork in it, we're all done. */ +/*----------------------------------------------------------------------------------*/ +aux: + x.=0 + Do i=1 To n + x.i.i=1 + End + Return +/*----------------------------------------------------------------------------------*/ +build: /*set m.r.c from data */ + Arg n + k=0 + w=0 /*W: max width of a number*/ + Do r=1 To n /*loop over rows */ + Do c=1 To n /*loop over columns */ + k=k+1 + m.r.c=word(data,k) + w=max(w,length(m.r.c)) + End /*c*/ + End /*r*/ + Return +/*----------------------------------------------------------------------------------*/ +invert: + Do k=1 To n + t=m.k.k /*divide each matrix row by T */ + Do c=1 To n + m.k.c=m.k.c/t /*process row of original matrix.*/ + x.k.c=x.k.c/t /* ' ' ' auxiliary ' */ + End /*c*/ + Do r=1 To n + If r<>k Then Do /*skip if R is the same row as K.*/ + t=m.r.k + Do c=1 To n + m.r.c=m.r.c-t*m.k.c /*process row of original matrix.*/ + x.r.c=x.r.c-t*x.k.c /* ' ' ' auxiliary ' */ + End /*c*/ + End + End /*r*/ + End /*k*/ + Return +/*-----------------------------------------------------------------------------------*/ +show: + Parse Arg which,title + Say + Say title + f=4 /*F: fractional digits precision.*/ + Do r=1 To n + line='' + Do c=1 To n + If which=='M' Then + line=line right(m.r.c,w) + Else + line=line right(format(x.r.c,w,f),w+f+1) + End /*c*/ + Say line + End /*r*/ + Return diff --git a/Task/Gauss-Jordan-matrix-inversion/Rust/gauss-jordan-matrix-inversion.rust b/Task/Gauss-Jordan-matrix-inversion/Rust/gauss-jordan-matrix-inversion.rs similarity index 100% rename from Task/Gauss-Jordan-matrix-inversion/Rust/gauss-jordan-matrix-inversion.rust rename to Task/Gauss-Jordan-matrix-inversion/Rust/gauss-jordan-matrix-inversion.rs diff --git a/Task/Gauss-Jordan-matrix-inversion/VBScript/gauss-jordan-matrix-inversion.vb b/Task/Gauss-Jordan-matrix-inversion/VBScript/gauss-jordan-matrix-inversion.vbs similarity index 100% rename from Task/Gauss-Jordan-matrix-inversion/VBScript/gauss-jordan-matrix-inversion.vb rename to Task/Gauss-Jordan-matrix-inversion/VBScript/gauss-jordan-matrix-inversion.vbs diff --git a/Task/Gaussian-elimination/Ada/gaussian-elimination.ada b/Task/Gaussian-elimination/Ada/gaussian-elimination.adb similarity index 100% rename from Task/Gaussian-elimination/Ada/gaussian-elimination.ada rename to Task/Gaussian-elimination/Ada/gaussian-elimination.adb diff --git a/Task/Gaussian-elimination/Delphi/gaussian-elimination.delphi b/Task/Gaussian-elimination/Delphi/gaussian-elimination.pas similarity index 100% rename from Task/Gaussian-elimination/Delphi/gaussian-elimination.delphi rename to Task/Gaussian-elimination/Delphi/gaussian-elimination.pas diff --git a/Task/Gaussian-elimination/EasyLang/gaussian-elimination.easy b/Task/Gaussian-elimination/EasyLang/gaussian-elimination.easy index 12bd0ba26f..84676232a4 100644 --- a/Task/Gaussian-elimination/EasyLang/gaussian-elimination.easy +++ b/Task/Gaussian-elimination/EasyLang/gaussian-elimination.easy @@ -1,4 +1,4 @@ -proc gauss_elim . a[][] b[] x[] . +func[] gauss_elim a[][] b[] . n = len a[][] for i to n maxr = i @@ -14,14 +14,14 @@ proc gauss_elim . a[][] b[] x[] . swap b[maxr] b[i] . for j = i + 1 to n - f = a[j][i] / a[i][i] + fn = a[j][i] + fd = a[i][i] for k = i to n - a[j][k] -= f * a[i][k] + a[j][k] -= a[i][k] * fn / fd . - b[j] -= f * b[i] + b[j] -= b[i] * fn / fd . . - x[] = [ ] len x[] n for i = n downto 1 rhs = b[i] @@ -30,8 +30,16 @@ proc gauss_elim . a[][] b[] x[] . . x[i] = rhs / a[i][i] . + return x[] . -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[] +# --------------------- # +# 2x + 3y − z = 5 # +# x + y + z = 6 # +# -3x - 4y + 3z = -5 # +# # +# x = 5, y = -1, z = 2 # +# --------------------- # +# +a[][] = [ [ 2 3 -1 ] [ 1 1 1 ] [ -3 -4 3 ] ] +b[] = [ 5 6 -5 ] +print gauss_elim a[][] b[] diff --git a/Task/Gaussian-elimination/FutureBasic/gaussian-elimination.basic b/Task/Gaussian-elimination/FutureBasic/gaussian-elimination.basic new file mode 100644 index 0000000000..10ac8ba5c8 --- /dev/null +++ b/Task/Gaussian-elimination/FutureBasic/gaussian-elimination.basic @@ -0,0 +1,106 @@ +// +// Gaussian Elimination Estimate +// +// FutureBasic 7.0.34 August 2025 R.W +// +//-------------------------------------------------- +// +// Test data array. I wanted it to be base 1 and not zero +// hence the 99 which is just filler for the zeroeth element +// +double a(6,6) = ¬ +{99, 99, 99, 99, 99, 99, 99,¬ +99, 1.00, 0.00, 0.00, 0.00, 0.00, 0.00,¬ +99, 1.00, 0.63, 0.39, 0.25, 0.16, 0.10,¬ +99, 1.00, 1.26, 1.58, 1.98, 2.49, 3.13,¬ +99, 1.00, 1.88, 3.55, 6.70, 12.62, 23.80,¬ +99, 1.00, 2.51, 6.32, 15.88, 39.90, 100.28,¬ +99, 1.00, 3.14, 9.87, 31.01, 97.41, 306.02 } + +double b(6) = ¬ +{99,-0.01, 0.61, 0.91, 0.99, 0.60, 0.02 } + +double x(6) +double ab(6) +double ans(6),r(6),bb(6,6), f +int c, d, g, p1, p2, z +// + +int row, col +int j, k, n = 6 +// +// Pivot n times +local fn pivot(num as int) + For p1 = num to n - 1 + For p2 = p1 + 1 To n + If abs(bb(p1,num)) < abs(bb(p2,num)) + Swap r(p1),r(p2) + For g = 1 To n + Swap bb(p1,g),bb(p2,g) + Next g + End If + Next p2 + Next p1 +end fn + +// The 'Gaussian' function takes two matrices, +// 'a' and 'b', with 'a' square, and it returns +// the determinant of 'a' and a matrix 'x' +// such that a * x = b. +// If 'b' is the identity, then 'x' = inverse of 'a' + +local fn Gaussian(matrix(6,6) as double, rhs(6) as double) + + // copy matrix + for c = 1 to n + r(c) = rhs(c) + for d = 1 to n + bb(c,d) = matrix(c,d) + next d + next c + + // pivot it (hey that's what the task requires + // don't ask me why. It doesn't + // improve accuracy with these numbers) + for k = 1 to n-1 + fn pivot(k) + for row = k to n-1 + if bb(row + 1, k) == 0 then exit for + f = bb(k, k) / bb(row+1, k) + r(row + 1) = r(row + 1) * f - r(k) + For g = 1 To n + bb((row + 1), g) = bb((row + 1), g) * f - bb(k,g) + Next g + Next row + Next k + + //back substitute + For z = n to 1 step -1 + ans(z) = r(z) / bb(z,z) + For j = n to z + 1 step -1 + ans(z) = ans(z) - (bb(z,j) * ans(j) / bb(z,z)) + Next j + Next z +end fn + +window 1,@"Gaussian Elimination" + +print "TEST DATA USED" +print " ax = transpose b" +print "[1.00 |0.00 |0.00 | 0.0000 | 0.00 | 0.00] [??] [-0.01]" +print "[1.00 |0.63 |0.39 | 0.2500 | 0.16 | 0.10] [??] [ 0.61]" +print "[1.00 |1.26 |1.58 | 1.9800 | 2.49 | 3.13] x [??] = [ 0.91]" +print "[1.00 |1.88 |3.55 | 6.7000 |12.62 | 23.80] [??] [ 0.99]" +print "[1.00 |2.51 |6.32 |15.8800 |39.90 |100.28] [??] [ 0.60]" +print "[1.00 |3.14 |9.87 |31.0100 |97.41 |306.02] [??] [ 0.02]" +print + +fn Gaussian(a(0,0),b(0)) + +print "Solution:" +print "---------" +for j = 1 to 6 + print using "###.################";ans(j) +next j + +HandleEvents diff --git a/Task/Gaussian-elimination/Julia/gaussian-elimination.julia b/Task/Gaussian-elimination/Julia/gaussian-elimination.jl similarity index 100% rename from Task/Gaussian-elimination/Julia/gaussian-elimination.julia rename to Task/Gaussian-elimination/Julia/gaussian-elimination.jl diff --git a/Task/Gaussian-elimination/Kotlin/gaussian-elimination.kotlin b/Task/Gaussian-elimination/Kotlin/gaussian-elimination.kts similarity index 100% rename from Task/Gaussian-elimination/Kotlin/gaussian-elimination.kotlin rename to Task/Gaussian-elimination/Kotlin/gaussian-elimination.kts diff --git a/Task/Gaussian-elimination/OCaml/gaussian-elimination-1.ocaml b/Task/Gaussian-elimination/OCaml/gaussian-elimination-1.ml similarity index 100% rename from Task/Gaussian-elimination/OCaml/gaussian-elimination-1.ocaml rename to Task/Gaussian-elimination/OCaml/gaussian-elimination-1.ml diff --git a/Task/Gaussian-elimination/OCaml/gaussian-elimination-2.ocaml b/Task/Gaussian-elimination/OCaml/gaussian-elimination-2.ml similarity index 100% rename from Task/Gaussian-elimination/OCaml/gaussian-elimination-2.ocaml rename to Task/Gaussian-elimination/OCaml/gaussian-elimination-2.ml diff --git a/Task/Gaussian-elimination/OCaml/gaussian-elimination-3.ocaml b/Task/Gaussian-elimination/OCaml/gaussian-elimination-3.ml similarity index 100% rename from Task/Gaussian-elimination/OCaml/gaussian-elimination-3.ocaml rename to Task/Gaussian-elimination/OCaml/gaussian-elimination-3.ml diff --git a/Task/Gaussian-elimination/OCaml/gaussian-elimination-4.ocaml b/Task/Gaussian-elimination/OCaml/gaussian-elimination-4.ml similarity index 100% rename from Task/Gaussian-elimination/OCaml/gaussian-elimination-4.ocaml rename to Task/Gaussian-elimination/OCaml/gaussian-elimination-4.ml diff --git a/Task/Gaussian-elimination/OCaml/gaussian-elimination-5.ocaml b/Task/Gaussian-elimination/OCaml/gaussian-elimination-5.ml similarity index 100% rename from Task/Gaussian-elimination/OCaml/gaussian-elimination-5.ocaml rename to Task/Gaussian-elimination/OCaml/gaussian-elimination-5.ml diff --git a/Task/Gaussian-elimination/OCaml/gaussian-elimination-6.ocaml b/Task/Gaussian-elimination/OCaml/gaussian-elimination-6.ml similarity index 100% rename from Task/Gaussian-elimination/OCaml/gaussian-elimination-6.ocaml rename to Task/Gaussian-elimination/OCaml/gaussian-elimination-6.ml diff --git a/Task/Gaussian-elimination/PascalABC.NET/gaussian-elimination.pas b/Task/Gaussian-elimination/PascalABC.NET/gaussian-elimination.pas new file mode 100644 index 0000000000..e6f257930e --- /dev/null +++ b/Task/Gaussian-elimination/PascalABC.NET/gaussian-elimination.pas @@ -0,0 +1,16 @@ +uses NumLibABC; + +begin + var A := new real[6, 6] ((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)); + + var b := new real[6] (-0.01, 0.61, 0.91, 0.99, 0.60, 0.02); + + var oL := new Decomp(A); + oL.Solve(b); + b.Println; +end. diff --git a/Task/Gaussian-elimination/PowerShell/gaussian-elimination-1.psh b/Task/Gaussian-elimination/PowerShell/gaussian-elimination-1.ps1 similarity index 100% rename from Task/Gaussian-elimination/PowerShell/gaussian-elimination-1.psh rename to Task/Gaussian-elimination/PowerShell/gaussian-elimination-1.ps1 diff --git a/Task/Gaussian-elimination/PowerShell/gaussian-elimination-2.psh b/Task/Gaussian-elimination/PowerShell/gaussian-elimination-2.ps1 similarity index 100% rename from Task/Gaussian-elimination/PowerShell/gaussian-elimination-2.psh rename to Task/Gaussian-elimination/PowerShell/gaussian-elimination-2.ps1 diff --git a/Task/Gaussian-elimination/Rust/gaussian-elimination.rust b/Task/Gaussian-elimination/Rust/gaussian-elimination.rs similarity index 100% rename from Task/Gaussian-elimination/Rust/gaussian-elimination.rust rename to Task/Gaussian-elimination/Rust/gaussian-elimination.rs diff --git a/Task/Gaussian-elimination/VBScript/gaussian-elimination.vb b/Task/Gaussian-elimination/VBScript/gaussian-elimination.vbs similarity index 100% rename from Task/Gaussian-elimination/VBScript/gaussian-elimination.vb rename to Task/Gaussian-elimination/VBScript/gaussian-elimination.vbs diff --git a/Task/Gaussian-elimination/XPL0/gaussian-elimination.xpl0 b/Task/Gaussian-elimination/XPL0/gaussian-elimination.xpl0 new file mode 100644 index 0000000000..d3f43119aa --- /dev/null +++ b/Task/Gaussian-elimination/XPL0/gaussian-elimination.xpl0 @@ -0,0 +1,43 @@ +proc Gauss(A, B, X, N); \Gaussian elimination returns [X] for [A]*[X] = [B] +real A, B, X; int N; \matrix, vector, output vector, number of rows +int Diag, MaxRow, Row, Col, I; +real Max, Temp; +[for Diag:= 0 to N-1 do \partial pivoting uses largest magnitude coefficient + [MaxRow:= Diag; \ to improve numerical stability + Max:= A(Diag, Diag); + for Row:= Diag+1 to N-1 do + [Temp:= abs(A(Row, Diag)); + if Temp > Max then + [MaxRow:= Row; Max:= Temp]; + ]; + Temp:= A(Diag); A(Diag):= A(MaxRow); A(MaxRow):= Temp; \swap rows + Temp:= B(Diag); B(Diag):= B(MaxRow); B(MaxRow):= Temp; + for Row:= Diag+1 to N-1 do + [Temp:= A(Row, Diag) / A(Diag, Diag); \divide by pivot element + for Col:= Diag+1 to N-1 do + A(Row, Col):= A(Row, Col) - Temp*A(Diag, Col); + A(Row, Diag):= 0.; + B(Row):= B(Row) - Temp*B(Diag); + ]; + ]; \reduced row echelon form +for Row:= N-1 downto 0 do \back substitution makes [X] + [Temp:= B(Row); + for I:= N-1 downto Row+1 do + Temp:= Temp - X(I)*A(Row, I); + X(Row):= Temp / A(Row, Row); + ]; +]; + +real A, B, X(6); +int 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(A, B, X, 6); +for I:= 0 to 6-1 do + [RlOut(0, X(I)); CrLf(0)]; +] diff --git a/Task/General-FizzBuzz/ALGOL-68/general-fizzbuzz.alg b/Task/General-FizzBuzz/ALGOL-68/general-fizzbuzz.alg index 301d6ba2ca..046fa5220b 100644 --- a/Task/General-FizzBuzz/ALGOL-68/general-fizzbuzz.alg +++ b/Task/General-FizzBuzz/ALGOL-68/general-fizzbuzz.alg @@ -1,25 +1,25 @@ BEGIN # generalised FizzBuzz # # prompts for an integer, reads it and returns it # - PROC read integer = ( STRING prompt )INT: + PROC read an integer = ( STRING prompt )INT: BEGIN print( ( prompt ) ); INT result; read( ( result, newline ) ); result - END; # read integer # + END; # read an integer # # prompts for a string, reads it and returns it # - PROC read string = ( STRING prompt )STRING: + PROC read a string = ( STRING prompt )STRING: BEGIN print( ( prompt ) ); STRING result; read( ( result, newline ) ); result - END; # read string # + END; # read a string # # mode to hold a factor and associated text # MODE FBFACTOR = STRUCT( INT factor, STRING text ); #===============================================================# - # quicksort routine for the factors, from the Algol 68 uicksort # - # task sample # + # quicksort routine for the factors # + # - from the Algol 68 task sample # #---------------------------------------------------------------# #--- Swap function ---# PROC swap = (REF[]FBFACTOR array, INT first, INT second) VOID: @@ -51,14 +51,14 @@ BEGIN # generalised FizzBuzz # OP > = ( FBFACTOR a, b )BOOL: factor OF a > factor OF b; #===============================================================# # get the maximum number to consider # - INT max number = read integer( "Numbers reuired: " ); - # number of factors reuired # + INT max number = read an integer( "Numbers required: " ); + # number of factors required # INT max factor = 3; # get the factors and associated words # [ max factor ]FBFACTOR factors; FOR i TO max factor DO - factor OF factors[ i ] := read integer( "Factor " + whole( i, 0 ) + ": " ); - text OF factors [ i ] := read string( "Text for " + whole( factor OF factors[ i ], 0 ) + ": " ) + factor OF factors[ i ] := read an integer( "Factor " + whole( i, 0 ) + ": " ); + text OF factors [ i ] := read a string( "Text for " + whole( factor OF factors[ i ], 0 ) + ": " ) OD; # sort the factors into order # quick( factors, 1, UPB factors ); diff --git a/Task/General-FizzBuzz/Ada/general-fizzbuzz.ada b/Task/General-FizzBuzz/Ada/general-fizzbuzz.adb similarity index 100% rename from Task/General-FizzBuzz/Ada/general-fizzbuzz.ada rename to Task/General-FizzBuzz/Ada/general-fizzbuzz.adb diff --git a/Task/General-FizzBuzz/Crystal/general-fizzbuzz.cr b/Task/General-FizzBuzz/Crystal/general-fizzbuzz.cr new file mode 100644 index 0000000000..1af7cfbec8 --- /dev/null +++ b/Task/General-FizzBuzz/Crystal/general-fizzbuzz.cr @@ -0,0 +1,12 @@ +def fizz_buzz_plus (factorwords, limit) + factorwords = factorwords.sort_by { |f, w| f } + (1..limit).each do |n| + shout = "" + factorwords.each do |factor, word| + shout += word if n % factor == 0 + end + puts (shout == "" ? n : shout) + end +end + +fizz_buzz_plus [{3, "Fizz"}, {5, "Buzz"}, {7, "Baxx"}], 20 diff --git a/Task/General-FizzBuzz/Crystal/general-fizzbuzz.crystal b/Task/General-FizzBuzz/Crystal/general-fizzbuzz.crystal deleted file mode 100644 index e74a7afc6f..0000000000 --- a/Task/General-FizzBuzz/Crystal/general-fizzbuzz.crystal +++ /dev/null @@ -1,50 +0,0 @@ -counter = 0 - -puts "Enter a maximum number:" -limit = gets - -puts "Enter the first integer for factoring:" -first_int = gets -puts "Enter the name of the first integer:" -first_int_name = gets - -puts "Enter the second integer for factoring:" -second_int = gets -puts "Enter the name of the second integer:" -second_int_name = gets - -puts "Enter the third integer for factoring:" -third_int = gets -puts "Enter the name of the third integer:" -third_int_name = gets - -if (limit && - first_int && - second_int && - third_int && - first_int_name && - second_int_name && - third_int_name) - limit = limit.chomp.to_i - first_int = first_int.chomp.to_i - second_int = second_int.chomp.to_i - third_int = third_int.chomp.to_i - while limit > counter - counter += 1 - if (counter % first_int) == 0 && (counter % second_int) == 0 && (counter % third_int) == 0 - puts first_int_name + second_int_name + third_int_name - elsif (counter % first_int) == 0 && (counter % second_int) == 0 - puts first_int_name + second_int_name - elsif (counter % first_int) == 0 - puts first_int_name - elsif (counter % second_int) == 0 - puts second_int_name - elsif (counter % third_int) == 0 - puts third_int_name - else - puts counter - end - end -else - exit -end diff --git a/Task/General-FizzBuzz/Elixir/general-fizzbuzz.elixir b/Task/General-FizzBuzz/Elixir/general-fizzbuzz.ex similarity index 100% rename from Task/General-FizzBuzz/Elixir/general-fizzbuzz.elixir rename to Task/General-FizzBuzz/Elixir/general-fizzbuzz.ex diff --git a/Task/General-FizzBuzz/Icon/general-fizzbuzz.icon b/Task/General-FizzBuzz/Icon/general-fizzbuzz.icon new file mode 100644 index 0000000000..8122a68d0c --- /dev/null +++ b/Task/General-FizzBuzz/Icon/general-fizzbuzz.icon @@ -0,0 +1,16 @@ +link factors + +procedure main(A) + /A := [20,3,"Fizz",5,"Buzz",7,"Baxx"] + mtable := table() + limit := get(A) + while *A > 0 do mtable[integer(get(A))] := get(A) + mlist := sort([: key(mtable) :]) + + every i := 1 to limit do write((""~== fizzbuzz(i,mlist,mtable))|i) +end + +procedure fizzbuzz(n,a,t) + every (s := "", n%(f := !a) = 0) do s ||:= t[f] + return s +end diff --git a/Task/General-FizzBuzz/Julia/general-fizzbuzz.julia b/Task/General-FizzBuzz/Julia/general-fizzbuzz.jl similarity index 100% rename from Task/General-FizzBuzz/Julia/general-fizzbuzz.julia rename to Task/General-FizzBuzz/Julia/general-fizzbuzz.jl diff --git a/Task/General-FizzBuzz/Kotlin/general-fizzbuzz.kotlin b/Task/General-FizzBuzz/Kotlin/general-fizzbuzz.kts similarity index 100% rename from Task/General-FizzBuzz/Kotlin/general-fizzbuzz.kotlin rename to Task/General-FizzBuzz/Kotlin/general-fizzbuzz.kts diff --git a/Task/General-FizzBuzz/Maxima/general-fizzbuzz.maxima b/Task/General-FizzBuzz/Maxima/general-fizzbuzz.maxima new file mode 100644 index 0000000000..061ce84551 --- /dev/null +++ b/Task/General-FizzBuzz/Maxima/general-fizzbuzz.maxima @@ -0,0 +1,18 @@ +srep(n, s) := block( + l: charlist(s), + lrep: map(lambda([c], smake(n, c)), l), + apply(sconcat, lrep) +)$ + +srep_zip(nums, strings) := block( + len: min(length(nums), length(strings)), + makelist(srep(nums[i], strings[i]), i, 1, len) +)$ + +genfizzbuzz(factors, words, n1, n2) := for i from n1 thru n2 do( + flags: map(lambda([k], charfun(mod(i, k)=0)), factors), + if member(1, flags) then sprint(apply(sconcat, srep_zip(flags, words))) else sprint(i), + if mod(i-n1+1, 10)=0 then newline() +)$ + +genfizzbuzz([3, 5, 7], ["Fizz", "Buzz", "Baxx"], 1, 105); diff --git a/Task/General-FizzBuzz/OCaml/general-fizzbuzz.ocaml b/Task/General-FizzBuzz/OCaml/general-fizzbuzz.ml similarity index 100% rename from Task/General-FizzBuzz/OCaml/general-fizzbuzz.ocaml rename to Task/General-FizzBuzz/OCaml/general-fizzbuzz.ml diff --git a/Task/General-FizzBuzz/PascalABC.NET/general-fizzbuzz.pas b/Task/General-FizzBuzz/PascalABC.NET/general-fizzbuzz.pas new file mode 100644 index 0000000000..dc3d777a26 --- /dev/null +++ b/Task/General-FizzBuzz/PascalABC.NET/general-fizzbuzz.pas @@ -0,0 +1,14 @@ +## +for var i:=1 to 20 do +begin + var s := ''; + if i mod 3 = 0 then + s += 'Fizz'; + if i mod 5 = 0 then + s += 'Buzz'; + if i mod 7 = 0 then + s += 'Baxx'; + if s = '' then + Println(i) + else Println(s); +end diff --git a/Task/General-FizzBuzz/Phix/general-fizzbuzz.phix b/Task/General-FizzBuzz/Phix/general-fizzbuzz.phix index 5ac2a4ea5e..5eb2ca375f 100644 --- a/Task/General-FizzBuzz/Phix/general-fizzbuzz.phix +++ b/Task/General-FizzBuzz/Phix/general-fizzbuzz.phix @@ -1,17 +1,17 @@ ---> - procedure general_fizz_buzz(integer lim, sequence words, facts) - for i=1 to lim do - string word = "" - for j=1 to length(facts) do - if remainder(i,facts[j])=0 then - word &= words[j] - end if - end for - if length(word)=0 then - word = sprintf("%d",i) - end if - printf(1,"%s\n",{word}) - end for - end procedure - general_fizz_buzz(20, {"Fizz","Buzz","Baxx"}, {3,5,7}) - - -- - -- demo\rosetta\Generator_Exponential.exw - -- ====================================== - -- - without js -- tasks - bool terminate = false +-- demo\rosetta\Generator_Exponential.exw +without js -- tasks - atom res +atom res +bool terminate = false - procedure powers(integer p) - integer i=0 - while not terminate do - res = power(i,p) - task_suspend(task_self()) - task_yield() - i += 1 - end while - end procedure +procedure powers(integer p) + integer i = 0 + while not terminate do + res = power(i,p) + task_suspend(task_self()) + task_yield() + i += 1 + end while +end procedure - constant squares = task_create(powers,{2}), - cubes = task_create(powers,{3}) +constant squares = task_create(powers,{2}), + cubes = task_create(powers,{3}) - atom square, cube - task_schedule(cubes,1) - task_yield() - cube = res - for i=1 to 30 do - while 1 do - task_schedule(squares,1) - task_yield() - square = res - while cube<square do - task_schedule(cubes,1) - task_yield() - cube = res - end while - if square!=cube then exit end if - end while - if i>20 then - ?square - end if - end for - - terminate = 1 - {} = wait_key() - Get the size of the Main Screen. <--- + CGRect mainScreenFrame = fn ScreenMainFrame + float msh = mainScreenFrame.size.height + CGRect r = fn CGRectMake( 0, 0, 600, int(msh) - 110) + + window 1, @"Go Fish", r + windowcenter(1) + WindowSetBackgroundColor(1,fn ColorBlack) + +end fn + +//--- Start --- + +fn BuildWindow + +fn Intro + +fn InitCards + +str255 AddTheS +bool RequestCard = _false +short v = 0 +short po = 0 +boolean ShowHand = _false +str255 WantsCard + +"Main" + +ShowHand = _false + +str255 RequestedCard + +While ShowHand = _false + text ,,fn colorGreen + Print Chr$(10) + "Points >> "; + text ,,fn colorYellow + print YourName + ": "; + text ,,fn colorGreen + print Points(0); + text ,,fn colorOrange + print " CPU: "; + text ,,fn colorGreen + print Points(1) + text ,,fn colorWhite + Print Chr$(10) + " " + str$(RemainingCards) + " remaining cards" + text ,,fn colorWhite + + + /* + // Uncomment this to see the CPUs cards For testing + Print Chr$(10) + "CPU Cards: "; + For i = 1 To 13 + if Computer(i) <> 0 + For j = 1 To Computer(i) + if Mid$(cards,i,1) = "0" + Print @"10"; " "; + else + Print Mid$(cards,i,1); " "; + end if + Next j + End If + Next i + Print + fn PrintViewScrollToBottom( fn WindowPrintView(1)) + */ + + + Print Chr$(10) + "Your Cards: "; + For i = 1 To 13 + if play(i) <> 0 + For j = 1 To play(i) + if Mid$(cards,i,1) = "0" + Print @"10"; " "; + else + Print Mid$(cards,i,1); " "; + end if + Next j + End If + Next i + Print + fn PrintViewScrollToBottom( fn WindowPrintView(1)) + + RequestCard = _false + + While RequestCard = _false + if fn CheckForEndGame = _True then cls:fn InitCards:goto "Loop" + + Someone = YourName + + CFStringRef UserInput = 0 + "InputCard" + UserInput = input % (20, fn WhatCardInputHeight),@"What card do you want? " + if ( UserInput == NULL ) then "InputCard" // Rich added this 5/1/24 + fn CFStringGetPascalString (UserInput, @RequestedCard, 256, _kCFStringEncodingMacRoman) + if RequestedCard = "10" then RequestedCard = "0"// card zero is a 10 + text ,,fn ColorYellow + Print + + WantsCard = RequestedCard + + if WantsCard = "j" || WantsCard = "J" then WantsCard = "Jack" + if WantsCard = "q" || WantsCard = "Q" then WantsCard = "Queen" + if WantsCard = "k" || WantsCard = "K" then WantsCard = "King" + if WantsCard = "a" || WantsCard = "A" then WantsCard = "Ace" + if WantsCard = "0" then WantsCard = "10" + + print "-------------------------------------" + print + str255 AorAn + AorAn = "a" + if WantsCard = "Ace" then AorAn = "an" + print YourName + " asked For " + AorAn + " " + WantsCard + print + text ,,fn ColorWhite + + fn PrintViewScrollToBottom( fn WindowPrintView(1)) + + if RequestedCard = "X" || RequestedCard = "x" then fn QuitOrResumeAlert(@"EXIT") + + If RequestedCard <> "" Then CardNumber = Instr$(1,cards, Ucase$(RequestedCard)): RequestCard = _true + + If CardNumber = 0 + text,,fn ColorRed + Print "Sorry, that is not a valid card.": RequestCard = _false + print + fn PrintViewScrollToBottom( fn WindowPrintView(1)) + Else if play(CardNumber) = 0 Then text ,,fn colorRed: Print "You don//t have that card!": text ,,fn colorRed: RequestCard = _false + fn PrintViewScrollToBottom( fn WindowPrintView(1)) + text,,fn ColorWhite + + End If + + Wend + + guess(CardNumber) = 1 + + If Computer(CardNumber) = 0 + Print Someone + ","; + text ,,fn colorRed + Print " Go fish!" + text ,,fn colorWhite + Print Someone + " got a";: fn youGoFishing + print + fn CheckForCompletedBook + ShowHand = _true + Else + v = Computer(CardNumber) + Computer(CardNumber) = 0 + play(CardNumber) += v + if v > 1 then AddTheS = "s" else AddTheS = "" + Print Someone + " got" + str$(v) + " card" + AddTheS + fn CheckForCompletedBook + fn PrintViewScrollToBottom( fn WindowPrintView(1)) + ShowHand = _false + End If + +Wend + + + +Someone = "CPU" +For i = 1 To 13 + asked(i) = 0 +Next i + +bool CPUsTurn = _false + +While CPUsTurn = _false + if fn CheckForEndGame = _True then cls:fn InitCards:goto "Loop" + + po = 0 + For i = 1 To 13 + If (Computer(i) > 0) && (guess(i) > 0) Then poss(i) = 1: po += 1 + Next i + + short whilecounter + WhileCounter = 0 + + + If po = 0 + // this k is the go fish card. + + k = rnd(12) +1 + while Computer(k) = 0 || asked(k) + whilecounter ++ + k = rnd(12) +1 + if WhileCounter > 100 then k = 0: exit while //5/5/24 Rich added this to prevent hangs + wend + + Else + + k = rnd(12) + 1 + while poss(k) = 0 + k = rnd(12) + 1 + if WhileCounter > 100 then k = 0: exit while //5/5/24 Rich added this to prevent hangs + wend + + guess(k) = 0 + asked(k) = 1 + + end if + + + if k = 0 then "Loop" //5/5/24 Rich added this to prevent hangs + + WantsCard = fn CheckForFaceCard(k) + + if WantsCard = "j" || WantsCard = "J" then WantsCard = "Jack" + if WantsCard = "q" || WantsCard = "Q" then WantsCard = "Queen" + if WantsCard = "k" || WantsCard = "K" then WantsCard = "King" + if WantsCard = "a" || WantsCard = "A" then WantsCard = "Ace" + if WantsCard = "0" then WantsCard = "10" + + text ,,fn ColorOrange + + print "-------------------------------------" + + + + Print:Print Someone + " wants your " + wantsCard + "'s." + print + + text ,,fn ColorWhite + + asked(k) = 1 + + + If play(k) = 0 + Print Someone + ", "; + text ,,fn colorRed: Print "go fish!" + text ,,fn colorWhite:Print Someone + " got";: fn cpuGoFishing + + fn CheckCPUForCompletedBook + CPUsTurn = _true + + Else + + v = play(k) + play(k) = 0 + Computer(k) += v + if v > 1 then AddTheS = "s" else AddTheS = "" + Print Someone + " got" + str$(v) + " card" + AddTheS + fn CheckCPUForCompletedBook + CPUsTurn = _false + End If + + +Wend + +"Loop" +goto "Main" + +handleevents diff --git a/Task/Go-Fish/Rebol/go-fish.rebol b/Task/Go-Fish/Rebol/go-fish.rebol new file mode 100644 index 0000000000..c310b23444 --- /dev/null +++ b/Task/Go-Fish/Rebol/go-fish.rebol @@ -0,0 +1,217 @@ +Rebol [ + title: "Rosetta code: Go Fish" + file: %Go_fish.r3 + url: https://rosettacode.org/wiki/Go_Fish +] + +go-fish-game: function/with [ + "Play a game of Go Fish" +][ + deck: fisher-yates-shuffle copy ordered-deck + clear ai-hand clear ai-book-list clear ai-guess + clear my-hand clear my-book-list + ai-books: my-books: 0 + deal-cards/ai 9 ai-hand + deal-cards 9 my-hand + message: clear "" + draw-screen + while [ai-books + my-books < 13][ + computer-turn + if ai-books + my-books < 13 [player-turn] + ] + clear-screen + draw-screen + print "" + print as-yellow "GAME OVER" + print ["^/Computer books:" as-red pad ai-books -3 + "^/Player books:" as-green pad my-books -3] +][ + ;; Build deck + ordered-deck: [] + foreach r ranks: "A23456789TJQK" [ + foreach s "♣♦♥♠" [ + append ordered-deck ajoin [r s] + ] + ] + ;; Charsets used to filter key inputs + player-card-keys: charset join ranks "x" + player-yes-no: charset "ynx" + + ;; Game states + ai-hand: [] ai-book-list: [] ai-guess: [] + my-hand: [] my-book-list: [] + deck: [] + ai-books: my-books: 0 + + + message: "" + + ;; Shuffle function + fisher-yates-shuffle: func [list [block!] /local len j] [ + len: length? list + repeat i len [ + j: i + random (len - i) + swap at list i at list j + ] + list + ] + ;; Cards sorting + rank-modifiers: #[ + #"A" 130 #"K" 120 #"Q" 110 #"J" 100 #"T" 90 + #"9" 80 #"8" 70 #"7" 60 #"6" 50 #"5" 40 + #"4" 30 #"3" 20 #"2" 10 + ] + card-rank: func [card] [rank-modifiers/(card/1)] + sort-hand: func [hand] [ + sort/compare hand func [a b] [ + (card-rank a) < (card-rank b) + ] + ] + ;; Screen output + clear-screen: does [prin "^[[2J^[[H"] + draw-screen: does [ + clear-screen + ;; title bar + print as-yellow "==================================" + print as-yellow " G O F I S H " + print as-yellow "==================================" + print "" + ;; deck count + print ajoin [as-cyan " Deck: " length? deck " cards remaining"] + print "" + ;; books lines + print ajoin [as-red " Computer books: " pad ai-books -2 " [ " ai-book-list " ]"] + print ajoin [as-green " Your books: " pad my-books -2 " [ " my-book-list " ]"] + print as-yellow "----------------------------------" + print "" + ;; my hand + print [as-cyan "Your hand:" as-yellow sort-hand my-hand] + print "" + ;; last message + unless empty? message [ print message ] + print as-yellow "----------------------------------" + ] + status: func[txt][ + if block? txt [txt: ajoin txt] + append append message txt LF + ] + ;; Game functions + deal-cards: function [num hand /ai] [ + new: take/part deck num + unless ai [ + status ["You draw new card" if num > 1 ["s"] ": " new] + ] + append hand new + ] + find-in: func [hand kind [char!]] [ + forall hand [ + if hand/1/1 = kind [return kind] + ] + none + ] + guess-from: function [hand guessed] [ + kind: first random/only exclude hand guessed + append guessed kind + kind + ] + check-for-books: func [hand /ai /local kind n count] [ + if empty? hand [exit] + sort hand + kind: hand/1/1 n: count: 0 + while [not tail? hand][ + either kind = hand/1/1 [ + n: n + 1 + if n = 4 [ + remove/part next hand -4 + ++ count + append either ai [ai-book-list][my-book-list] kind + if tail? hand [break] + kind: hand/1/1 n: 0 + continue + ] + ][ + kind: hand/1/1 + n: 1 + ] + ++ hand + ] + either ai [ + ai-books: ai-books + count + ][ my-books: my-books + count] + if count > 0 [ + status ["New " as-green count " book" if count > 1 "s" " collected!"] + ] + count + ] + transfer-cards: func [ + ;; Move all cards of a given rank from src to trg + src [block!] trg [block!] kind [char!] + ][ + while [not tail? src] [ + either kind = src/1/1 [append trg take src][++ src] + ] + ] + computer-turn: func [/local kind a] [ + forever [ + if empty? ai-hand [ + if empty? deck [exit] + deal-cards/ai 3 ai-hand + ] + ai-guess: unique ai-guess + kind: guess-from ai-hand ai-guess + draw-screen + print as-red { -------------------^/ - COMPUTER TURN -^/ -------------------} + clear message + prin ajoin [" Do you have any " as-green kind "s? "] + a: wait-for-key/only player-yes-no + if any [none? a a = #"x"][ halt ] + either a = #"y" [ + transfer-cards my-hand ai-hand kind + status ["Computer took your " as-green kind "s!"] + check-for-books/ai ai-hand + draw-screen + ][ + status ["Go Fish! Computer draws a card."] + deal-cards/ai 1 ai-hand + check-for-books/ai ai-hand + draw-screen + exit + ] + ] + ] + + player-turn: func [/local kind n] [ + forever [ + if empty? my-hand [ + if empty? deck [exit] + deal-cards 3 my-hand + ] + draw-screen + print as-green { -------------------^/ - PLAYER TURN -^/ -------------------} + clear message + prin " Your guess: " + kind: wait-for-key/only player-card-keys + if any [none? kind kind = #"x"][ halt ] + kind: uppercase kind + unless find-in my-hand kind [ + status as-red "You must hold that rank to ask for it!" + draw-screen + exit + ] + either find-in ai-hand kind [ + transfer-cards ai-hand my-hand kind + status ["You took the computer's " as-green kind "s!"] + check-for-books my-hand + draw-screen + ][ + status ["Computer don't have any " as-green kind "s!"] + deal-cards 1 my-hand + check-for-books my-hand + draw-screen + exit + ] + ] + ] +] +;--- Main --- +go-fish-game diff --git a/Task/Goldbachs-comet/Agena/goldbachs-comet.agena b/Task/Goldbachs-comet/Agena/goldbachs-comet.agena new file mode 100644 index 0000000000..5e498f40b6 --- /dev/null +++ b/Task/Goldbachs-comet/Agena/goldbachs-comet.agena @@ -0,0 +1,22 @@ +scope # Goldbach's comet, translation of Pluto + + local proc goldbach( n :: number ) :: number + local count := 0; + for i to n \ 2 do + if numtheory.isprime( i ) and numtheory.isprime( n - i ) then + count +:= 1 + fi + od + return count + end; + + print( "The first 100 G numbers:" ) + print( join( foreach( 1, 100, << n -> strings.format( "%2d" & if n mod 10 = 0 then "\n" else " " fi + , goldbach( 2 + n * 2 ) + ) + >> + ) + ) + ); + printf( "G(1000000) = %.0f\n", goldbach( 1_000_000 ) ) +end diff --git a/Task/Goldbachs-comet/Arturo/goldbachs-comet.arturo b/Task/Goldbachs-comet/Arturo/goldbachs-comet.arturo index 5930a6e9da..e7bfa7ec91 100644 --- a/Task/Goldbachs-comet/Arturo/goldbachs-comet.arturo +++ b/Task/Goldbachs-comet/Arturo/goldbachs-comet.arturo @@ -13,6 +13,4 @@ print ["\nG(1000000) =" G 1000000] csv: join.with:",\n" map select 4..2000 => even? 'x -> ~"|x|, |G x|" -; write the CSV data to a file which we can then visualize -; via our preferred spreadsheet app -write "comet.csv" csv +csv >> "comet.csv" diff --git a/Task/Goldbachs-comet/Delphi/goldbachs-comet.delphi b/Task/Goldbachs-comet/Delphi/goldbachs-comet.pas similarity index 100% rename from Task/Goldbachs-comet/Delphi/goldbachs-comet.delphi rename to Task/Goldbachs-comet/Delphi/goldbachs-comet.pas diff --git a/Task/Goldbachs-comet/EasyLang/goldbachs-comet.easy b/Task/Goldbachs-comet/EasyLang/goldbachs-comet.easy index 666e90ef38..1a4a2b23d6 100644 --- a/Task/Goldbachs-comet/EasyLang/goldbachs-comet.easy +++ b/Task/Goldbachs-comet/EasyLang/goldbachs-comet.easy @@ -1,30 +1,22 @@ func isprim n . - if n mod 2 = 0 and n > 2 - return 0 - . + if n mod 2 = 0 and n > 2 : return 0 i = 3 sq = sqrt n while i <= sq - if n mod i = 0 - return 0 - . + if n mod i = 0 : return 0 i += 2 . return 1 . func goldbach n . for i = 2 to n div 2 - if isprim i = 1 - cnt += isprim (n - i) - . + if isprim i = 1 : cnt += isprim (n - i) . return cnt . -numfmt 0 3 +numfmt 3 0 for n = 4 step 2 to 202 write goldbach n - if n mod 20 = 2 - print "" - . + if n mod 20 = 2 : print "" . print goldbach 1000000 diff --git a/Task/Goldbachs-comet/Fennel/goldbachs-comet.fennel b/Task/Goldbachs-comet/Fennel/goldbachs-comet.fennel new file mode 100644 index 0000000000..0fbbb9715e --- /dev/null +++ b/Task/Goldbachs-comet/Fennel/goldbachs-comet.fennel @@ -0,0 +1,49 @@ +(do ;;; Goldbach's comet - translated from the Lua sample + + (fn range [from to] ; generate a table containing the integers [from .. to] + (local t {}) + (for [i from to] + (tset t i i) + ) + t + ) + + (fn is-prime [p] + (if (or (<= p 1) (= 0 (% p 2))) + (= p 2) + ;else + (do (var (prime i root-p) (values true 3 (math.floor (math.sqrt p)))) + (while (and (<= i root-p) prime) + (set (prime i) (values (not= 0 (% p i)) (+ i 1))) + ) + prime + ) + ) + ) + + (fn goldbach [n] + (var count 0) + (for [i 1 (math.floor (/ n 2))] + (when (and (is-prime i) (is-prime (- n i))) + (set count (+ count 1)) + ) + ) + count + ) + + (print "The first 100 G numbers:") + (print (table.concat (icollect [_ v (ipairs (range 1 100))] + (string.format (.. "%2d" (if (= 0 (% v 10)) + "\n" + ;else + " " + ) + ) + (goldbach (+ 2 (* v 2))) + ) + ) + "" + ) + ) + (print (.. "G(1000000) = " (goldbach 1_000_000))) +) diff --git a/Task/Goldbachs-comet/Gambas/goldbachs-comet-2.gambas b/Task/Goldbachs-comet/Gambas/goldbachs-comet-2.gambas index 6a74789be6..827e0b16a0 100644 --- a/Task/Goldbachs-comet/Gambas/goldbachs-comet-2.gambas +++ b/Task/Goldbachs-comet/Gambas/goldbachs-comet-2.gambas @@ -19,10 +19,10 @@ FOR I = 1 TO MAX_G G[I] = 0: NEXT G[4] = 1 ' 4 is the only sum of 2 even primes FOR I = 3 TO HALF_MAX_G STEP 2 IF P[I] THEN - INC G[I + 1] - FOR J = I + 2 TO MAX_G - 1 + INC G[I + I] + FOR J = I + 2 TO MAX_G - I IF P[J] THEN - INC G[I + 1] + INC G[I + J] ENDIF NEXT ENDIF @@ -41,7 +41,7 @@ FOR I = 3 TO MAX_P DIV 2 STEP 2 NEXT PRINT FORMAT$("G(%D): ", MAX_P); GM FOR I = 2 TO MAX_G - 10 STEP 10 - FOR J = 1 TO I + 8 STEP 2 + FOR J = I TO I + 8 STEP 2 GPSET I DIV 10, 240-G[J],RGB(255,255,255) NEXT NEXT diff --git a/Task/Goldbachs-comet/Go/goldbachs-comet.go b/Task/Goldbachs-comet/Go/goldbachs-comet.go new file mode 100644 index 0000000000..4c8b45dc6c --- /dev/null +++ b/Task/Goldbachs-comet/Go/goldbachs-comet.go @@ -0,0 +1,63 @@ +package main + +import ( + "fmt" + "math" +) + +var primes []bool + +func initialisePrimes(limit int) { + primes = make([]bool, limit) + for i := 2; i < limit; i++ { + primes[i] = true + } + + sqrtLimit := int(math.Sqrt(float64(limit))) + for n := 2; n < sqrtLimit; n++ { + if primes[n] { + for k := n * n; k < limit; k += n { + primes[k] = false + } + } + } +} + +func goldbachFunction(number int) (int, error) { + if number <= 2 || number%2 == 1 { + return 0, fmt.Errorf("argument must be even and greater than 2: %d", number) + } + + result := 0 + for i := 1; i <= number/2; i++ { + if primes[i] && primes[number-i] { + result++ + } + } + return result, nil +} + +func main() { + initialisePrimes(2000000) + + fmt.Println("The first 100 Goldbach numbers:") + for n := 2; n < 102; n++ { + value, err := goldbachFunction(2 * n) + if err != nil { + fmt.Printf("Error: %v\n", err) + continue + } + fmt.Printf("%3d", value) + if n%10 == 1 { + fmt.Println() + } + } + + fmt.Println("\nThe 1,000,000th Goldbach number =", func() string { + value, err := goldbachFunction(1000000) + if err != nil { + return fmt.Sprintf("Error: %v", err) + } + return fmt.Sprintf("%d", value) + }()) +} diff --git a/Task/Goldbachs-comet/Julia/goldbachs-comet.julia b/Task/Goldbachs-comet/Julia/goldbachs-comet.jl similarity index 100% rename from Task/Goldbachs-comet/Julia/goldbachs-comet.julia rename to Task/Goldbachs-comet/Julia/goldbachs-comet.jl diff --git a/Task/Goldbachs-comet/Lua/goldbachs-comet.lua b/Task/Goldbachs-comet/Lua/goldbachs-comet.lua index 85a60e5015..41e61a815e 100644 --- a/Task/Goldbachs-comet/Lua/goldbachs-comet.lua +++ b/Task/Goldbachs-comet/Lua/goldbachs-comet.lua @@ -1,7 +1,6 @@ function T(t) return setmetatable(t, {__index=table}) end table.range = function(t,n) local s=T{} for i=1,n do s[i]=i end return s end table.map = function(t,f) local s=T{} for i=1,#t do s[i]=f(t[i]) end return s end -table.batch = function(t,n,f) for i=1,#t,n do local s=T{} for j=1,n do s[j]=t[i+j-1] end f(s) end return t end function isprime(n) if n < 2 then return false end @@ -24,6 +23,7 @@ function goldbach(n) end print("The first 100 G numbers:") -g = T{}:range(100):map(function(n) return goldbach(2+n*2) end) -g:map(function(n) return string.format("%2d ",n) end):batch(10,function(t) print(t:concat()) end) +print(T{}:range(100) + :map(function(n) return string.format("%2d"..(n % 10 == 0 and "\n" or " "),goldbach(2+n*2)) end) + :concat("")) print("G(1000000) = "..goldbach(1000000)) diff --git a/Task/Goldbachs-comet/PascalABC.NET/goldbachs-comet.pas b/Task/Goldbachs-comet/PascalABC.NET/goldbachs-comet.pas new file mode 100644 index 0000000000..234717b9bc --- /dev/null +++ b/Task/Goldbachs-comet/PascalABC.NET/goldbachs-comet.pas @@ -0,0 +1,36 @@ +uses GraphWPF; + +const colpick = (Colors.Red, Colors.Green, Colors.Blue); + +function IsPrime(x: longword): boolean; +begin + var i := 2; + while (i * i <= x) and (x mod i <> 0) do + i += 1; + Result := i * i > x; +end; + +function g(n: integer): integer; +begin + assert((n > 2) and (n mod 2 = 0), '“n” must be even and greater than 2.'); + for var i := 2 to (n div 2) do + if isPrime(i) and isPrime(n - i) then + result += 1; +end; + +begin + println('First 100 G numbers:'); + foreach var n in (2..101) index i do + begin + write(g( 2 * n):3); + if (i + 1) mod 10 = 0 then writeln; + end; + println; + println('G(1_000_000) =', g(1_000_000)); + + setMathematicCoords(0, 4000, 0, false); + foreach var x in range(4, 4002, 2) do + begin + fillcircle(x, g(x)*15, 10, colpick[(x div 2) mod 3]); + end; +end. diff --git a/Task/Goldbachs-comet/Pluto/goldbachs-comet-1.pluto b/Task/Goldbachs-comet/Pluto/goldbachs-comet-1.pluto new file mode 100644 index 0000000000..8d53f40164 --- /dev/null +++ b/Task/Goldbachs-comet/Pluto/goldbachs-comet-1.pluto @@ -0,0 +1,23 @@ +do -- Goldbach's comet, translation of Lua + + local int = require( "int" ) -- RC Pluto integer library, inc. prime utilities + + local function goldbach( n : number ) : number + local count = 0 + for i = 1, n // 2 do + if int.isprime( i ) and int.isprime( n - i ) then + ++ count + end + end + return count + end + + print( "The first 100 G numbers:" ) + print( range( 100 ):map( | n | -> string.format( "%2d"..if n % 10 == 0 then "\n" else " " end + , goldbach( 2 + n * 2 ) + ) + ) + :concat( "" ) + ) + print( $"G(1000000) = { goldbach( 1_000_000 ) }" ) +end diff --git a/Task/Goldbachs-comet/Pluto/goldbachs-comet-2.pluto b/Task/Goldbachs-comet/Pluto/goldbachs-comet-2.pluto new file mode 100644 index 0000000000..8f93744a60 --- /dev/null +++ b/Task/Goldbachs-comet/Pluto/goldbachs-comet-2.pluto @@ -0,0 +1,69 @@ +do -- create a bitmap of Goldbach's Comet + + local int = require( "int" ) -- RC Pluto integer library, inc. prime utilities + require( "bitmap" ) -- RC bitmap library + + local bmp = bitmap.of( 400, 240, color.black, "Goldbachs_comet_Pluto" ) + + local maxG , maxP = 4000, 1_000_000 + local rootMaxP , halfMaxG = math.floor( math.sqrt( maxP ) ), maxG // 2 + + local prime = int.arecomps( maxP ):map( | v | -> not v ) -- sieve the primes to maxP + + local G = {} -- construct a table of G numbers + for i = 1, maxG do G[ i ] = 0 end + G[ 4 ] = 1 -- 4 is the only sum of 2 even primes + for i = 3, halfMaxG, 2 do + if prime[ i ] then + G[ i + i ] += 1 + for j = i + 2, maxG - i do + if prime[ j ] then + G[ i + j ] += 1 + end + end + end + end + -- print the first few G numbers to the bitmap - 8x8 charaxters + local c, tx, ty = 0, 2, 2 + for i = 4, 202, 2 do + c += 1 + bmp:text( string.format( "%3d", G[ i ] ), tx, ty, color.white, 1 ) + if c % 10 != 0 then + tx += 24 + else + tx, ty = 2, ty + 10 + end + end + local Gm = 0 + for i = 3, maxP // 2, 2 do + if prime[ i ] then + if prime[ maxP - i ] then Gm += 1 end + end + end + -- print G(1_000_000) to the bitmap + bmp:text( string.format( "G(%d): %d", maxP, Gm ), 2, ty + 10, color.white, 1 ) + for i = 2, maxG - 10, 10 do + local maxY = 0 + local x = i // 10 + for j = i, i + 8, 2 do + if G[ j ] > 0 then + local y = 240 - G[ j ] + bmp:set( x, y, switch bmp:get( x, y ) do + case color.black -> color.orange + case color.orange -> color.yellow + default -> color.white + end + ) + if y > maxY then maxY = y end + end + end + -- we're going to save it as a png, so convert from BGR to RGb + for j = 1, maxY do + local bgr = bmp:get( x, j ) + if bgr != color.black then + bmp:set( x, j, bmp.flipColor( bgr ) ) + end + end + end + bmp:view( true ) +end diff --git a/Task/Goldbachs-comet/REXX/goldbachs-comet.rexx b/Task/Goldbachs-comet/REXX/goldbachs-comet.rexx new file mode 100644 index 0000000000..4d7666fda3 --- /dev/null +++ b/Task/Goldbachs-comet/REXX/goldbachs-comet.rexx @@ -0,0 +1,58 @@ +-- 23 Aug 2025 +include Setting + +say 'GOLDBACH''S COMET' +say version +say +numeric digits 7 +call GetPrimes +call ShowFirst100 +call ShowMillion +exit + +GetPrimes: +procedure expose prim. flag. +call Time('r') +say 'Collect Primes up to 1000000...' +call Primes(1e6) +say Time('e')/1 'seconds' +say +return + +ShowFirst100: +procedure expose prim. flag. +call Time('r') +say 'First 100 values...' +do i = 4 by 2 to 202 + call Charout ,Right(Goldbach(i),3) + if i//20 = 2 then + say +end +say Time('e')/1 'seconds' +say +return + +ShowMillion: +procedure expose prim. flag. +call Time('r') +say 'g(1000000)...' +say Goldbach(1e6) +say Time('e')/1 'seconds' +say +return + +Goldbach: +procedure expose prim. flag. +arg x +y = 0 +do i = 2 to x%2 + if flag.i then do + j = x-i + if flag.j then do + y = y+1 + end + end +end +return y/1 + +include Math diff --git a/Task/Goldbachs-comet/Rust/goldbachs-comet.rust b/Task/Goldbachs-comet/Rust/goldbachs-comet.rs similarity index 100% rename from Task/Goldbachs-comet/Rust/goldbachs-comet.rust rename to Task/Goldbachs-comet/Rust/goldbachs-comet.rs diff --git a/Task/Golden-ratio-Convergence/Ada/golden-ratio-convergence.ada b/Task/Golden-ratio-Convergence/Ada/golden-ratio-convergence.adb similarity index 100% rename from Task/Golden-ratio-Convergence/Ada/golden-ratio-convergence.ada rename to Task/Golden-ratio-Convergence/Ada/golden-ratio-convergence.adb diff --git a/Task/Golden-ratio-Convergence/COBOL/golden-ratio-convergence.cobol b/Task/Golden-ratio-Convergence/COBOL/golden-ratio-convergence.cob similarity index 100% rename from Task/Golden-ratio-Convergence/COBOL/golden-ratio-convergence.cobol rename to Task/Golden-ratio-Convergence/COBOL/golden-ratio-convergence.cob diff --git a/Task/Golden-ratio-Convergence/DuckDB/golden-ratio-convergence.duckdb b/Task/Golden-ratio-Convergence/DuckDB/golden-ratio-convergence.duckdb new file mode 100644 index 0000000000..0e9e393bfe --- /dev/null +++ b/Task/Golden-ratio-Convergence/DuckDB/golden-ratio-convergence.duckdb @@ -0,0 +1,24 @@ +set variable phi = (1 + sqrt(5)) / 2; + +# Output: one row (iterations, phi) +# This should work even with epsilon = 0 +create or replace function compute_phi(epsilon) as table ( + with recursive cte as ( + select 2.0::DOUBLE as oldPhi, 1::DOUBLE as phi, 0 as iterations + union all + select phi as oldPhi, + 1 + (1 / phi) as phi, + iterations + 1 as iterations + from cte + where @(phi - oldPhi) > epsilon + ) + select last(iterations order by iterations) as iterations, + last(phi order by iterations) as phi + from cte +); + +select epsilon, + iterations, + phi as "final value", + @(phi - getvariable('phi')) as "approximate absolute error" + from (select unnest([1e-5, 0]) as epsilon), compute_phi(epsilon); diff --git a/Task/Golden-ratio-Convergence/EasyLang/golden-ratio-convergence.easy b/Task/Golden-ratio-Convergence/EasyLang/golden-ratio-convergence.easy index 66bf65792e..c5d55953a8 100644 --- a/Task/Golden-ratio-Convergence/EasyLang/golden-ratio-convergence.easy +++ b/Task/Golden-ratio-Convergence/EasyLang/golden-ratio-convergence.easy @@ -5,7 +5,7 @@ repeat phi0 = phi iter += 1 . -numfmt 10 0 +numfmt 0 10 print "Iterations: " & iter print "Result: " & phi print "Error: " & phi - (1 + sqrt 5) / 2 diff --git a/Task/Golden-ratio-Convergence/FutureBasic/golden-ratio-convergence.basic b/Task/Golden-ratio-Convergence/FutureBasic/golden-ratio-convergence.basic new file mode 100644 index 0000000000..250ef6e2b2 --- /dev/null +++ b/Task/Golden-ratio-Convergence/FutureBasic/golden-ratio-convergence.basic @@ -0,0 +1,21 @@ +include "NSLog.incl" + +void local fn Iterate + double oldPhi = 1.0, phi = 1.0, limit = 1e-5 + int iters = 0 + while (YES) + phi = 1.0 + 1.0 / oldPhi + iters++ + if ( abs( phi - oldPhi ) <= limit ) then break + oldPhi = phi + wend + NSLog( @"Final value of phi: %16.14f", phi ) + double actualPhi = ( 1.0 + fn sqrt(5.0) ) / 2.0 + NSLog( @"Actual value of phi: %16.14f", actualPhi ) + NSLog( @"Error (approx): %16.14f", phi - actualPhi ) + NSLog( @"Number of iterations: %d", iters ) +end fn + +fn Iterate + +HandleEvents diff --git a/Task/Golden-ratio-Convergence/Julia/golden-ratio-convergence.julia b/Task/Golden-ratio-Convergence/Julia/golden-ratio-convergence.jl similarity index 100% rename from Task/Golden-ratio-Convergence/Julia/golden-ratio-convergence.julia rename to Task/Golden-ratio-Convergence/Julia/golden-ratio-convergence.jl diff --git a/Task/Golden-ratio-Convergence/Oberon/golden-ratio-convergence.oberon b/Task/Golden-ratio-Convergence/Oberon/golden-ratio-convergence.oberon new file mode 100644 index 0000000000..041dac37f4 --- /dev/null +++ b/Task/Golden-ratio-Convergence/Oberon/golden-ratio-convergence.oberon @@ -0,0 +1,24 @@ +MODULE GoldenRatioCnv; (* calculate the Golden Ratio and show the number of iterations required *) + IMPORT Math, Out; + + VAR count : INTEGER; + phi0, phi1, diff : REAL; + +BEGIN + + count := 0; + phi0 := 1.0; + diff := 1.0E20; + + WHILE 1.0E-5 < diff DO + phi1 := 1.0 + ( 1.0 / phi0 ); + diff := ABS( phi1 - phi0 ); + phi0 := phi1; + INC( count ) + END; + + Out.String( "Result:" );Out.Real( phi0, 10 ); + Out.String( " after " );Out.Int( count, 0 );Out.String( " iterations" );Out.Ln; + Out.String( "The error is approximately " );Out.Real( phi0 - ( 0.5 * ( 1.0 + Math.sqrt( 5.0 ) ) ), 10 );Out.Ln + +END GoldenRatioCnv. diff --git a/Task/Golden-ratio-Convergence/PascalABC.NET/golden-ratio-convergence.pas b/Task/Golden-ratio-Convergence/PascalABC.NET/golden-ratio-convergence.pas new file mode 100644 index 0000000000..ab76ee0240 --- /dev/null +++ b/Task/Golden-ratio-Convergence/PascalABC.NET/golden-ratio-convergence.pas @@ -0,0 +1,17 @@ +begin + var phi := 1.0; + var phiprev := 0.0; + var n := 0; + var err := 0.0; + while True do + begin + n += 1; + phi := 1 + 1/phi; + err := Abs(phi - phiprev); + if err <= 1e-5 then + break; + phiprev := phi; + end; + Println($'Result = {phi} after {n} iterations'); + Println($'The error is approximately = {phi - (1+sqrt(5)) / 2}'); +end. diff --git a/Task/Golden-ratio-Convergence/Phix/golden-ratio-convergence.phix b/Task/Golden-ratio-Convergence/Phix/golden-ratio-convergence.phix index 48bad6392b..4ec55e1c3f 100644 --- a/Task/Golden-ratio-Convergence/Phix/golden-ratio-convergence.phix +++ b/Task/Golden-ratio-Convergence/Phix/golden-ratio-convergence.phix @@ -1,11 +1,9 @@ -(phixonline)--> - with javascript_semantics - atom Phi = 1, iter = 0 - do - atom Pi = Phi - Phi = 1+1/Phi - iter += 1 - until abs(Phi-Pi)<1e-5 - printf(1,"Result: %.14f after %d iterations\n",{Phi,iter}) - printf(1,"Error: %.14f\n",{Phi-(1+sqrt(5))/2}) - "; i; print Bin(i,5); " --> "; diff --git a/Task/Gray-code/Frink/gray-code.frink b/Task/Gray-code/Frink/gray-code.frink index a145daca00..2d456adfa7 100644 --- a/Task/Gray-code/Frink/gray-code.frink +++ b/Task/Gray-code/Frink/gray-code.frink @@ -2,5 +2,7 @@ for i=0 to 31 { gray = binaryToGray[i] back = grayToBinary[gray] - println[(i->binary) + "\t" + (gray->binary) + "\t" + (back->binary)] + println[pad[i->binary] + "\t" + pad[gray->binary] + "\t" + pad[back->binary]] } + +pad[x] := padLeft[x,5,"0"] diff --git a/Task/Gray-code/FutureBasic/gray-code.basic b/Task/Gray-code/FutureBasic/gray-code.basic new file mode 100644 index 0000000000..9bb50c362a --- /dev/null +++ b/Task/Gray-code/FutureBasic/gray-code.basic @@ -0,0 +1,31 @@ +// Gray Code +//https://rosettacode.org/wiki/Gray_code + +local fn gray2bin(g As uint32) As uint32 + uint32 b = g + While g + g = g >> 1 + b = b Xor g + Wend + Return b +End fn = b + +local fn bin2gray(b As uint32) As uint32 +End fn = b Xor (b >> 1) + +// ------=< MAIN >=------ + +uint32 i +Print " DEC Binary Gray GrayToBinary" + +For i = 0 To 31 + print str$(i) + " "; + if i < 10 then print " "; + print " " + right$(bin$(i),5); + print " -->"; + print " " + right$(bin$(fn bin2gray(i)),5); + print " -->"; + print " " + right$(bin$(fn gray2bin(fn bin2gray(i))),5) +Next + +handleevents diff --git a/Task/Gray-code/BASIC/gray-code.basic b/Task/Gray-code/GW-BASIC/gray-code.basic similarity index 100% rename from Task/Gray-code/BASIC/gray-code.basic rename to Task/Gray-code/GW-BASIC/gray-code.basic diff --git a/Task/Gray-code/Julia/gray-code.julia b/Task/Gray-code/Julia/gray-code.jl similarity index 100% rename from Task/Gray-code/Julia/gray-code.julia rename to Task/Gray-code/Julia/gray-code.jl diff --git a/Task/Gray-code/Kotlin/gray-code.kotlin b/Task/Gray-code/Kotlin/gray-code.kts similarity index 100% rename from Task/Gray-code/Kotlin/gray-code.kotlin rename to Task/Gray-code/Kotlin/gray-code.kts diff --git a/Task/Gray-code/Liberty-BASIC/gray-code.basic b/Task/Gray-code/Liberty-BASIC/gray-code.basic index 14888831e6..44f2129ea9 100644 --- a/Task/Gray-code/Liberty-BASIC/gray-code.basic +++ b/Task/Gray-code/Liberty-BASIC/gray-code.basic @@ -7,7 +7,6 @@ B$ =Gray2Bin$( G$) print B$; " in pure binary." next r - end function Bin2Gray$( bin$) ' Given a binary number as a string, returns Gray code as a string. diff --git a/Task/Gray-code/Modula-2/gray-code.mod2 b/Task/Gray-code/Modula-2/gray-code.mod2 new file mode 100644 index 0000000000..135aaa93e7 --- /dev/null +++ b/Task/Gray-code/Modula-2/gray-code.mod2 @@ -0,0 +1,57 @@ +MODULE GrayCode; + +FROM STextIO IMPORT + WriteString, WriteLn; +FROM SWholeIO IMPORT + WriteInt; +FROM Conversions IMPORT + LongBaseToStr; +FROM FormatString IMPORT + FormatString; (* for justifying *) + +VAR + I, G, D: CARDINAL; + Ok: BOOLEAN; + BinS, OutBinS: ARRAY[0 .. 5] OF CHAR; + +PROCEDURE Encode(V: CARDINAL): CARDINAL; +BEGIN + RETURN V BXOR (V SHR 1) +END Encode; + +PROCEDURE Decode(V: CARDINAL): CARDINAL; +VAR + Result: CARDINAL; +BEGIN + Result := 0; + WHILE V > 0 DO + Result := Result BXOR V; + V := V SHR 1 + END; + RETURN Result +END Decode; + +BEGIN + WriteString("decimal binary gray decoded"); + WriteLn; + FOR I := 0 TO 31 DO + G := Encode(I); + D := Decode(G); + WriteInt(I, 4); + WriteString(" "); + Ok := LongBaseToStr(I, 2, BinS); + Ok := FormatString("%'05s", OutBinS, BinS); + (* Padded with 0; width: 5; type: string *) + WriteString(OutBinS); + WriteString(" "); + Ok := LongBaseToStr(G, 2, BinS); + Ok := FormatString("%'05s", OutBinS, BinS); + WriteString(OutBinS); + WriteString(" "); + Ok := LongBaseToStr(D, 2, BinS); + Ok := FormatString("%'05s", OutBinS, BinS); + WriteString(OutBinS); + WriteInt(D, 4); + WriteLn; + END +END GrayCode. diff --git a/Task/Gray-code/OCaml/gray-code.ocaml b/Task/Gray-code/OCaml/gray-code.ml similarity index 100% rename from Task/Gray-code/OCaml/gray-code.ocaml rename to Task/Gray-code/OCaml/gray-code.ml diff --git a/Task/Gray-code/PascalABC.NET/gray-code.pas b/Task/Gray-code/PascalABC.NET/gray-code.pas new file mode 100644 index 0000000000..e7f7d37b51 --- /dev/null +++ b/Task/Gray-code/PascalABC.NET/gray-code.pas @@ -0,0 +1,18 @@ +uses School; + +function GrayEncode(n: longword): longword := n xor (n shr 1); + +function GrayDecode(n: longword): longword; +begin + Result := 0; + while n > 0 do + begin + Result := Result xor n; + n := n shr 1; + end; +end; + +begin + for var i := 0 to 31 do + Writeln($'{i,-7} {Bin(i),-7} {Bin(grayEncode(i)),-7} {grayDecode(grayEncode(i)),-7}'); +end. diff --git a/Task/Gray-code/Pluto/gray-code.pluto b/Task/Gray-code/Pluto/gray-code.pluto new file mode 100644 index 0000000000..cf0cab4ce4 --- /dev/null +++ b/Task/Gray-code/Pluto/gray-code.pluto @@ -0,0 +1,19 @@ +local fmt = require "fmt" + +local function to_gray(n) return n ~ (n >> 1) end + +local function from_gray(g) + local b = 0 + while g != 0 do + b ~= g + g >>= 1 + end + return b +end + +print("decimal binary gray decoded") +for b = 0, 31 do + fmt.write(" %2d %05d", b, fmt.bin(b)) + local g = to_gray(b) + fmt.print(" %05d %05d", fmt.bin(g), fmt.bin(from_gray(g))) +end diff --git a/Task/Gray-code/PowerShell/gray-code.ps1 b/Task/Gray-code/PowerShell/gray-code.ps1 new file mode 100644 index 0000000000..0becbcb13c --- /dev/null +++ b/Task/Gray-code/PowerShell/gray-code.ps1 @@ -0,0 +1,35 @@ +# Gray code + +function Encode { + [OutputType([uint32])] + param([uint32]$V) + + return $V -bxor ($V -shr 1) +} + +function Decode { + [OutputType([uint32])] + param([uint32]$V) + + [uint32]$result = 0 + while ($V -gt 0) { + $result = $result -bxor $V + $V = $V -shr 1 + } + return $result +} + +Write-Output "decimal binary gray decoded" +foreach ($i in 0..31) { + [uint32]$g = Encode($i) + [uint32]$d = Decode($g) + [string]$out = @() + $out += "{0, 4} " -f $i + $binS = ([convert]::ToString($i, 2)).PadLeft(5, "0") + $out += "$binS " + $binS = ([convert]::ToString($g, 2)).PadLeft(5, "0") + $out += "$binS " + $binS = ([convert]::ToString($d, 2)).PadLeft(5, "0") + $out += "$binS{0, 4}" -f $d + Write-Output $out +} diff --git a/Task/Gray-code/Rust/gray-code.rust b/Task/Gray-code/Rust/gray-code.rs similarity index 100% rename from Task/Gray-code/Rust/gray-code.rust rename to Task/Gray-code/Rust/gray-code.rs diff --git a/Task/Gray-code/SETL/gray-code.setl b/Task/Gray-code/SETL/gray-code.setl new file mode 100644 index 0000000000..e5d368056b --- /dev/null +++ b/Task/Gray-code/SETL/gray-code.setl @@ -0,0 +1,29 @@ +program gray_code; + loop for n in [0..31] do + print( + lpad(str n, 2) + ": " + + lpad(bits n, 5) + " => " + + lpad(bits(g := gray_encode(n)), 5) + " => " + + lpad(bits(d := gray_decode(g)), 5) + ": " + + lpad(str d, 2) + ); + end loop; + + proc gray_encode(n); + return n bit_xor (n div 2); + end proc; + + proc gray_decode(n); + loop + init r := 0; + step n div:= 2; + until n=0 do r bit_xor:= n; + end loop; + return r; + end proc; + + op bits(n); + b := '' +/ [[str (n mod 2), n div:=2](1) : until n=0]; + return reverse(b); + end op; +end program; diff --git a/Task/Gray-code/VBScript/gray-code.vb b/Task/Gray-code/VBScript/gray-code.vbs similarity index 100% rename from Task/Gray-code/VBScript/gray-code.vb rename to Task/Gray-code/VBScript/gray-code.vbs diff --git a/Task/Gray-code/VHDL/gray-code-1.vhdl b/Task/Gray-code/VHDL/gray-code-1.vhd similarity index 100% rename from Task/Gray-code/VHDL/gray-code-1.vhdl rename to Task/Gray-code/VHDL/gray-code-1.vhd diff --git a/Task/Gray-code/VHDL/gray-code-2.vhdl b/Task/Gray-code/VHDL/gray-code-2.vhd similarity index 100% rename from Task/Gray-code/VHDL/gray-code-2.vhdl rename to Task/Gray-code/VHDL/gray-code-2.vhd diff --git a/Task/Gray-code/Zig/gray-code.zig b/Task/Gray-code/Zig/gray-code.zig new file mode 100644 index 0000000000..93a671caa5 --- /dev/null +++ b/Task/Gray-code/Zig/gray-code.zig @@ -0,0 +1,64 @@ +const std = @import("std"); + +fn grayEncode(b: u32) u32 { + return b ^ (b >> 1); +} + +fn grayDecode(g: u32) u32 { + var result = g; + var bit: u32 = 1 << 31; + while (bit > 1) { + if (result & bit != 0) result ^= bit >> 1; + bit >>= 1; + } + return result; +} + +fn toBinary(value: u32, buffer: []u8) []const u8 { + if (value == 0) return "0"; + + var temp = value; + var highest_bit: u5 = 0; + // Find the highest bit set + while (temp != 0) : (temp >>= 1) { + highest_bit += 1; + } + + // Fill buffer from right to left + var i: usize = highest_bit; + temp = value; + while (i > 0) { + i -= 1; + buffer[i] = if (temp & 1 == 1) '1' else '0'; + temp >>= 1; + } + + // Find first '1' + for (buffer[0..highest_bit], 0..) |c, index| { + if (c == '1') { + return buffer[index..highest_bit]; + } + } + + return "0"; // Fallback +} + +pub fn main() !void { + const stdout = std.io.getStdOut().writer(); + try stdout.print("Number\tBinary\tGray\tDecoded\n", .{}); + + // Pre-allocate a buffer big enough for 32-bit numbers + var binary_buffer: [32]u8 = undefined; + var gray_buffer: [32]u8 = undefined; + + for (0..32) |n| { + const n_u32: u32 = @intCast(n); + const g = grayEncode(n_u32); + std.debug.assert(grayDecode(g) == n_u32); + + const binary = toBinary(n_u32, &binary_buffer); + const grayBinary = toBinary(g, &gray_buffer); + + try stdout.print("{d}\t{s}\t{s}\t{d}\n", .{ n, binary, grayBinary, g }); + } +} diff --git a/Task/Grayscale-image/11l/grayscale-image.11l b/Task/Grayscale-image/11l/grayscale-image.11l index 2d3c981e9e..3f4f195f10 100644 --- a/Task/Grayscale-image/11l/grayscale-image.11l +++ b/Task/Grayscale-image/11l/grayscale-image.11l @@ -1,13 +1,4 @@ -T Colour - Byte r, g, b - - F (r, g, b) - .r = r - .g = g - .b = b - - F ==(other) - R .r == other.r & .g == other.g & .b == other.b +T Colour = BVec3 V black = Colour(0, 0, 0) V white = Colour(255, 255, 255) diff --git a/Task/Grayscale-image/Ada/grayscale-image-1.ada b/Task/Grayscale-image/Ada/grayscale-image-1.adb similarity index 100% rename from Task/Grayscale-image/Ada/grayscale-image-1.ada rename to Task/Grayscale-image/Ada/grayscale-image-1.adb diff --git a/Task/Grayscale-image/Ada/grayscale-image-2.ada b/Task/Grayscale-image/Ada/grayscale-image-2.adb similarity index 100% rename from Task/Grayscale-image/Ada/grayscale-image-2.ada rename to Task/Grayscale-image/Ada/grayscale-image-2.adb diff --git a/Task/Grayscale-image/Ada/grayscale-image-3.ada b/Task/Grayscale-image/Ada/grayscale-image-3.adb similarity index 100% rename from Task/Grayscale-image/Ada/grayscale-image-3.ada rename to Task/Grayscale-image/Ada/grayscale-image-3.adb diff --git a/Task/Grayscale-image/Crystal/grayscale-image.crystal b/Task/Grayscale-image/Crystal/grayscale-image.cr similarity index 100% rename from Task/Grayscale-image/Crystal/grayscale-image.crystal rename to Task/Grayscale-image/Crystal/grayscale-image.cr diff --git a/Task/Grayscale-image/Euphoria/grayscale-image.euphoria b/Task/Grayscale-image/Euphoria/grayscale-image.eu similarity index 100% rename from Task/Grayscale-image/Euphoria/grayscale-image.euphoria rename to Task/Grayscale-image/Euphoria/grayscale-image.eu diff --git a/Task/Grayscale-image/Julia/grayscale-image-1.julia b/Task/Grayscale-image/Julia/grayscale-image-1.jl similarity index 100% rename from Task/Grayscale-image/Julia/grayscale-image-1.julia rename to Task/Grayscale-image/Julia/grayscale-image-1.jl diff --git a/Task/Grayscale-image/Julia/grayscale-image-2.julia b/Task/Grayscale-image/Julia/grayscale-image-2.jl similarity index 100% rename from Task/Grayscale-image/Julia/grayscale-image-2.julia rename to Task/Grayscale-image/Julia/grayscale-image-2.jl diff --git a/Task/Grayscale-image/Kotlin/grayscale-image.kotlin b/Task/Grayscale-image/Kotlin/grayscale-image.kts similarity index 100% rename from Task/Grayscale-image/Kotlin/grayscale-image.kotlin rename to Task/Grayscale-image/Kotlin/grayscale-image.kts diff --git a/Task/Grayscale-image/M2000-Interpreter/grayscale-image.m2000 b/Task/Grayscale-image/M2000-Interpreter/grayscale-image.m2000 index 229762871a..ed33411db2 100644 --- a/Task/Grayscale-image/M2000-Interpreter/grayscale-image.m2000 +++ b/Task/Grayscale-image/M2000-Interpreter/grayscale-image.m2000 @@ -1,201 +1,202 @@ Module P6P5 { - Function Bitmap { - def x as long, y as long, Import as boolean, P5 as boolean - If match("NN") then { - Read x, y - } else.if Match("N") Then { - \\ is a file? - Read f as long - buffer whitespace as byte - if not Eof(f) then { - get #f, whitespace :P6$=eval$(whitespace) - get #f, whitespace : P6$+=eval$(whitespace) - def boolean getW=true, getH=true, getV=true - def long v - \\ str$("P6") has 2 bytes. "P6" has 4 bytes - P5=p6$=str$("P5") - If p6$=str$("P6") or P5 Then { - do { - get #f, whitespace - if Eval$(whitespace)=str$("#") then { - do {get #f, whitespace} until eval(whitespace)=10 - } else { - select case eval(whitespace) - case 32, 9, 13, 10 - { if getW and x<>0 then { - getW=false - } else.if getH and y<>0 then { - getH=false - } else.if getV and v<>0 then { - getV=false - } - } - case 48 to 57 - {if getW then { - x*=10 - x+=eval(whitespace, 0)-48 - } else.if getH then { - y*=10 - y+=eval(whitespace, 0)-48 - } else.if getV then { - v*=10 - v+=eval(whitespace, 0)-48 - } - } - End Select - } - iF eof(f) then Error "Not a ppm file" - } until getV=false - } else Error "Not a P6 ppm or P5 ppm file" - Import=True - } - } else Error "No proper arguments" - if x<1 or y<1 then Error "Wrong dimensions" - structure rgb { - red as byte - green as byte - blue as byte - } - m=len(rgb)*x mod 4 - if m>0 then m=4-m ' add some bytes to raster line - m+=len(rgb) *x - Structure rasterline { - { - pad as byte*m - } - hline as rgb*x - } - Structure Raster { - magic as integer*4 - w as integer*4 - h as integer*4 - { - linesB as byte*len(rasterline)*y - } - lines as rasterline*y - } - Buffer Clear Image1 as Raster - Return Image1, 0!magic:="cDIB", 0!w:=Hex$(x,2), 0!h:=Hex$(y, 2) - if not Import then Return Image1, 0!lines:=Str$(String$(chrcode$(255), Len(rasterline)*y)) - Buffer Clear Pad as Byte*4 - SetPixel=Lambda Image1, Pad,aLines=Len(Raster)-Len(Rasterline), blines=-Len(Rasterline) (x, y, c) ->{ - where=alines+3*x+blines*y - if c>0 then c=color(c) - c-! - Return Pad, 0:=c as long - Return Image1, 0!where:=Eval(Pad, 2) as byte, 0!where+1:=Eval(Pad, 1) as byte, 0!where+2:=Eval(Pad, 0) as byte - } - GetPixel=Lambda Image1,aLines=Len(Raster)-Len(Rasterline), blines=-Len(Rasterline) (x,y) ->{ - where=alines+3*x+blines*y - =color(Eval(image1, where+2 as byte), Eval(image1, where+1 as byte), Eval(image1, where as byte)) - } - GetPixelGray=Lambda Image1,aLines=Len(Raster)-Len(Rasterline), blines=-Len(Rasterline) (x,y) ->{ - where=alines+3*x+blines*y - grayval=round(0.2126*Eval(image1, where+2 as byte) + 0.7152*Eval(image1, where+1 as byte) + 0.0722*Eval(image1, where as byte), 0) - =color(grayval,grayval,grayval) - } - StrDib$=Lambda$ Image1, Raster -> { - =Eval$(Image1, 0, Len(Raster)) - } - CopyImage=Lambda Image1 (image$) -> { - if left$(image$,12)=Eval$(Image1, 0, 24 ) Then { - Return Image1, 0:=Image$ - } Else Error "Can't Copy Image" - } - Export2File=Lambda Image1, x, y (f) -> { - Print #f, "P6";chr$(10);"# Created using M2000 Interpreter";chr$(10); - Print #f, x;" ";y;" 255";chr$(10); - x2=x-1 : where=0 : rasterline=x*3 - m=rasterline mod 4 : if m<>0 then rasterline+=4-m - Buffer pad as byte*3 - For y1=y-1 to 0 { - where=rasterline*y1 - For x1=0 to x2 { - Return pad, 0:=eval$(image1, 0!linesB!where, 3) - Push Eval(pad, 2) : Return pad, 2:=Eval(pad, 0), 0:=Number - Put #f, pad : where+=3 - } - } - } - Export2FileGray=Lambda Image1, x, y (f) -> { - Print #f, "P5";chr$(10);"# Created using M2000 Interpreter";chr$(10); - Print #f, x;" ";y;" 255";chr$(10); - x2=x-1 : where=0 : rasterline=x*3 - m=rasterline mod 4 : if m<>0 then rasterline+=4-m - Buffer pad as byte*3 - Buffer bytepad as byte - const R=0.2126, G=0.7152, B=0.0722 - For y1=y-1 to 0 { - where=rasterline*y1 - For x1=0 to x2 { - Return pad, 0:=eval$(image1, 0!linesB!where, 3) - Return bytepad, 0:=round(R*Eval(pad, 2) + G*Eval(pad, 1) + B*Eval(pad, 0), 0) - Put #f, bytepad : where+=3 - } - } - } - if Import then { - x0=x-1 : where=0 - Buffer Pad1 as byte*3 - Buffer Pad2 as byte - local rasterline=x*3 - m=rasterline mod 4 : if m<>0 then rasterline+=4-m - For y1=y-1 to 0 { - where=rasterline*y1 - For x1=0 to x0 { - if p5 then - Get #f, Pad2: m=eval(Pad2,0) : Return pad1, 0:=m, 1:=m, 2:=m - else - Get #f, Pad1 : Push Eval(pad1, 2) : Return pad1, 2:=Eval(pad1, 0), 0:=Number - End if - Return Image1, 0!linesB!where:=Eval$(Pad1) : where+=3 - } - } - } - Group Bitmap { - SetPixel=SetPixel - GetPixel=GetPixel - Image$=StrDib$ - Copy=CopyImage - ToFile=Export2File - ToFileGray=Export2FileGray - GetPixelGray=GetPixelGray - } - =Bitmap - } - Cls 5,0 - A=Bitmap(15,10) - B=Bitmap(15,10) - c1=color(100, 200, 255) - c2=color(180, 250, 128) - For i=0 to 8 - Call A.SetPixel(i, i, c1) - Call A.SetPixel(9, i,c2) - Next - Call A.SetPixel(i,i,c1) - // make a new one GrayScale (but 24bit) as B - For i=0 to 14 { For J=0 to 9 {Call B.SetPixel(i, j, A.GetPixelGray(i,j))}} - // place image A at 200 pixel from left margin, 100 pixel from top margin - Copy 200*twipsX, 100*twipsY use A.Image$(), 0, 400 ' zoom 400%, angle 0 - // place image B at 400 pixel from left margin, 100 pixel from top margin - Copy 400*twipsX, 100*twipsY use B.Image$(), 0, 400 ' zoom 400% - Try { - Open "P6example.ppm" For Output as #f - Call A.Tofile(f) - Close #f - Open "P5example.ppm" For Output as #f - Call A.TofileGray(f) - Close #f - Open "P5example.ppm" For Input as #f - C=Bitmap(f) - close #f - Copy 600*twipsX, 100*twipsY use C.Image$(), 0, 400 ' zoom 400% - Open "P6example.ppm" For Input as #f - C=Bitmap(f) - close #f - // use of Top clause to make the border color transparent at rotation - Copy 800*twipsX, 100*twipsY top C.Image$(), 30, 400 ' zoom 400%, angle 30 degree - } - Print "Done" + Class Bitmap { + { // from version 14 + Var x As long, y As long, Import As boolean, P5 As boolean + If match("NN") Then + Read x, y + Else.if Match("N") Then + Read f As long + buffer whitespace As Byte + if not Eof(f) Then + get #f, whitespace :P6$=eval$(whitespace) + get #f, whitespace : P6$+=eval$(whitespace) + boolean getW=true, getH=true, getV=true + long v + P5=p6$=str$("P5") + If p6$=str$("P6") or P5 Then + do + get #f, whitespace + if Eval$(whitespace)=str$("#") Then + do + get #f, whitespace + until eval(whitespace)=10 + Else + select case eval(whitespace) + case 32, 9, 13, 10 + { + if getW and x<>0 Then + getW=false + Else.if getH and y<>0 Then + getH=false + Else.if getV and v<>0 Then + getV=false + End If + } + case 48 To 57 + { + if getW Then + x*=10 + x+=eval(whitespace, 0)-48 + Else.if getH Then + y*=10 + y+=eval(whitespace, 0)-48 + Else.if getV Then + v*=10 + v+=eval(whitespace, 0)-48 + End If + } + End Select + End If + iF eof(f) Then Error "Not a ppm file" + until getV=false + Else + Error "Not a P6 ppm or P5 ppm file" + End If + Import=True + End if + Else + Error "No proper arguments" + End If + if x<1 or y<1 Then Error "Wrong dimensions" + Buffer Clear Pad1 As Byte*3 + structure rgb { + red As Byte + green As Byte + blue As Byte + } + m=len(rgb)*x mod 4 + if m>0 Then m=4-m ' add some bytes To raster line + m+=len(rgb) *x + Structure rasterline { + { + pad As Byte*m + } + hline As rgb*x + } + Structure Raster { + magic As integer*4 + w As integer*4 + h As integer*4 + { + linesB As Byte*len(rasterline)*y + } + lines As rasterline*y + } + Buffer Clear Image1 As Raster + Return Image1, 0!magic:="cDIB", 0!w:=Hex$(x,2), 0!h:=Hex$(y, 2) + if not Import Then Return Image1, 0!lines:=Str$(String$(chrcode$(255), Len(rasterline)*y)) + Buffer Clear Pad As Byte*4 + aLines=Len(Raster)-Len(Rasterline)-Raster("linesB") + blines=-Len(Rasterline) + if Import Then + x0=x-1 : where=0 + Buffer Pad1 As Byte*3 + Buffer Pad2 As Byte + local rasterline=x*3 + m=rasterline mod 4 : if m<>0 Then rasterline+=4-m + For y1=y-1 To 0 + where=rasterline*y1 + For x1=0 To x0 + if p5 Then + Get #f, Pad2: m=eval(Pad2,0) : Return pad1, 0:=m, 1:=m, 2:=m + Else + Get #f, Pad1 : Push Eval(pad1, 2) : Return pad1, 2:=Eval(pad1, 0), 0:=Number + End if + Image1|linesB[where]=Pad1[0, 3] : where+=3 + Next + Next + End if + } + SetPixel=Lambda Image1, Pad, aLines, blines (x, y, c) ->{ + if c>0 Then c=color(c) + c-! + Return Pad, 0:=c As long + Push pad[2] : pad[2]=pad[0]: pad[0]=Number + Image1|linesB[alines+3*x+blines*y]=Pad[0, 3] + } + GetPixel=Lambda Image1,aLines, blines, Pad1 (x,y) ->{ + Pad1[0]=Image1|linesB[alines+3*x+blines*y, 3] + =color(Pad1[2], Pad1[1],Pad1[0]) + } + GetPixelGray=Lambda Image1,aLines, blines, Pad1 (x,y) ->{ + Pad1[0]=Image1|linesB[alines+3*x+blines*y, 3] + grayval=round(0.2126*Pad1[2] + 0.7152*Pad1[1] + 0.0722*Pad1[0], 0) + =color(grayval,grayval,grayval) + } + Image$=Lambda$ Image1, Raster ->Eval$(Image1, 0, Len(Raster)) + Copy=Lambda Image1 (image$) -> { + if left$(image$,12)=Image1[0, 24] Then + Return Image1, 0:=Image$ + Else + Error "Can't Copy Image" + End if + } + ToFile=Lambda Image1, x, y (f) -> { + Print #f, "P6";chr$(10);"# Created using M2000 Interpreter";chr$(10); + Print #f, x;" ";y;" 255";chr$(10); + x2=x-1 : where=0 : rasterline=x*3 + m=rasterline mod 4 : if m<>0 Then rasterline+=4-m + Buffer pad As Byte*3 + For y1=y-1 To 0 + where=rasterline*y1 + For x1=0 To x2 + pad[0]=image1|linesB[where, 3] + Push pad[2] : pad[2]=pad[0]: pad[0]=Number + Put #f, pad : where+=3 + Next + Next + } + ToFileGray=Lambda Image1, x, y (f) -> { + Print #f, "P5";chr$(10);"# Created using M2000 Interpreter";chr$(10); + Print #f, x;" ";y;" 255";chr$(10); + x2=x-1 : where=0 : rasterline=x*3 + m=rasterline mod 4 : if m<>0 Then rasterline+=4-m + Buffer pad As Byte*3 + Buffer bytepad As Byte + const R=0.2126, G=0.7152, B=0.0722 + For y1=y-1 To 0 + where=rasterline*y1 + For x1=0 To x2 + Return pad, 0:=eval$(image1, 0!linesB!where, 3) + Return bytepad, 0:=round(R*Eval(pad, 2) + G*Eval(pad, 1) + B*Eval(pad, 0), 0) + Put #f, bytepad : where+=3 + Next + Next + } + } + Cls 5,0 + A=Bitmap(15,10) + B=Bitmap(15,10) + c1=color(100, 200, 255) + c2=color(180, 250, 128) + For i=0 To 8 + Call A.SetPixel(i, i, c1) + Call A.SetPixel(9, i,c2) + Next + Call A.SetPixel(i,i,c1) + // make a new one GrayScale (but 24bit) As B + For i=0 To 14 { For J=0 To 9 {Call B.SetPixel(i, j, A.GetPixelGray(i,j))}} + // place image A at 200 pixel from left margin, 100 pixel from top margin + Copy 200*twipsX, 100*twipsY use A.Image$(), 0, 800 ' zoom 800%, angle 0 + // place image B at 400 pixel from left margin, 100 pixel from top margin + Copy 400*twipsX, 100*twipsY use B.Image$(), 0, 800 ' zoom 800% + Try { + Open "P6example.ppm" For Output As #f + Call A.Tofile(f) + Close #f + Open "P5example.ppm" For Output As #f + Call A.TofileGray(f) + Close #f + Open "P5example.ppm" For Input As #f + C=Bitmap(f) + close #f + Copy 600*twipsX, 100*twipsY use C.Image$(), 0, 800 ' zoom 800% + Open "P6example.ppm" For Input As #f + C=Bitmap(f) + close #f + // use of Top clause To make the border color transparent at rotation + Copy 800*twipsX, 100*twipsY top C.Image$(), 30, 800 ' zoom 800%, angle 30 degree + } + Print "Done" } P6P5 diff --git a/Task/Grayscale-image/OCaml/grayscale-image-1.ocaml b/Task/Grayscale-image/OCaml/grayscale-image-1.ml similarity index 100% rename from Task/Grayscale-image/OCaml/grayscale-image-1.ocaml rename to Task/Grayscale-image/OCaml/grayscale-image-1.ml diff --git a/Task/Grayscale-image/OCaml/grayscale-image-2.ocaml b/Task/Grayscale-image/OCaml/grayscale-image-2.ml similarity index 100% rename from Task/Grayscale-image/OCaml/grayscale-image-2.ocaml rename to Task/Grayscale-image/OCaml/grayscale-image-2.ml diff --git a/Task/Grayscale-image/OCaml/grayscale-image-3.ocaml b/Task/Grayscale-image/OCaml/grayscale-image-3.ml similarity index 100% rename from Task/Grayscale-image/OCaml/grayscale-image-3.ocaml rename to Task/Grayscale-image/OCaml/grayscale-image-3.ml diff --git a/Task/Greatest-common-divisor/ALGOL-68/greatest-common-divisor.alg b/Task/Greatest-common-divisor/ALGOL-68/greatest-common-divisor.alg index 2e357e0524..1f11565746 100644 --- a/Task/Greatest-common-divisor/ALGOL-68/greatest-common-divisor.alg +++ b/Task/Greatest-common-divisor/ALGOL-68/greatest-common-divisor.alg @@ -1,17 +1,24 @@ -PROC gcd = (INT a, b) INT: ( - IF a = 0 THEN - b - ELIF b = 0 THEN - a - ELIF a > b THEN - gcd(b, a MOD b) - ELSE - gcd(a, b MOD a) - FI -); -test:( - INT a = 33, b = 77; - printf(($x"The gcd of"g" and "g" is "gl$,a,b,gcd(a,b))); - INT c = 49865, d = 69811; - printf(($x"The gcd of"g" and "g" is "gl$,c,d,gcd(c,d))) -) +BEGIN + PROC gcd = (INT m, n) INT: ( + IF INT a = ABS m, b = ABS n; + a = 0 + THEN + b + ELIF b = 0 THEN + a + ELIF a > b THEN + gcd(b, a MOD b) + ELSE + gcd(a, b MOD a) + FI + ); + test:( + FOR a FROM 33 BY -33 TO -33 DO + FOR b FROM 77 BY -77 TO -77 DO + print(("The gcd of ", whole(a,-6)," and ", whole(b,-6)," is ", whole(gcd(a,b),-6),newline)) + OD + OD; + INT c = 49865, d = 69811; + print(("The gcd of ", whole(c,-6)," and ", whole(d,-6)," is ", whole(gcd(c,d),-6),newline)) + ) +END diff --git a/Task/Greatest-common-divisor/Ada/greatest-common-divisor.ada b/Task/Greatest-common-divisor/Ada/greatest-common-divisor.adb similarity index 100% rename from Task/Greatest-common-divisor/Ada/greatest-common-divisor.ada rename to Task/Greatest-common-divisor/Ada/greatest-common-divisor.adb diff --git a/Task/Greatest-common-divisor/AutoIt/greatest-common-divisor.autoit b/Task/Greatest-common-divisor/AutoIt/greatest-common-divisor.au3 similarity index 100% rename from Task/Greatest-common-divisor/AutoIt/greatest-common-divisor.autoit rename to Task/Greatest-common-divisor/AutoIt/greatest-common-divisor.au3 diff --git a/Task/Greatest-common-divisor/Ballerina/greatest-common-divisor.ballerina b/Task/Greatest-common-divisor/Ballerina/greatest-common-divisor.ballerina new file mode 100644 index 0000000000..e203dc5ef4 --- /dev/null +++ b/Task/Greatest-common-divisor/Ballerina/greatest-common-divisor.ballerina @@ -0,0 +1,21 @@ +import ballerina/io; + +function gcd(int u, int v) returns int { + int _u = u; + int _v = v; + while _v != 0 { + [_u, _v] = [_v, _u % _v]; + } + return _u.abs(); +} + +public function main() { + io:println(gcd(0, 0)); + io:println(gcd(0, 10)); + io:println(gcd(0, -10)); + io:println(gcd(9, 6)); + io:println(gcd(6, 9)); + io:println(gcd(-6, 9)); + io:println(gcd(8, 45)); + io:println(gcd(40902, 24140)); +} diff --git a/Task/Greatest-common-divisor/COBOL/greatest-common-divisor.cobol b/Task/Greatest-common-divisor/COBOL/greatest-common-divisor.cob similarity index 100% rename from Task/Greatest-common-divisor/COBOL/greatest-common-divisor.cobol rename to Task/Greatest-common-divisor/COBOL/greatest-common-divisor.cob diff --git a/Task/Greatest-common-divisor/Crystal/greatest-common-divisor.cr b/Task/Greatest-common-divisor/Crystal/greatest-common-divisor.cr new file mode 100644 index 0000000000..f4717cf74a --- /dev/null +++ b/Task/Greatest-common-divisor/Crystal/greatest-common-divisor.cr @@ -0,0 +1 @@ +2345.gcd 5432 #=> 7 diff --git a/Task/Greatest-common-divisor/DuckDB/greatest-common-divisor.duckdb b/Task/Greatest-common-divisor/DuckDB/greatest-common-divisor.duckdb new file mode 100644 index 0000000000..9114ccd611 --- /dev/null +++ b/Task/Greatest-common-divisor/DuckDB/greatest-common-divisor.duckdb @@ -0,0 +1,12 @@ +create or replace function mygcd(a0, b0) as ( + with recursive cte as ( + select a0 as a, b0 as b + union all + select b as a, mod(a,b) as b + from cte + where b != 0 + ) + select last(a) + from cte + where b=0 +); diff --git a/Task/Greatest-common-divisor/EMal/greatest-common-divisor.emal b/Task/Greatest-common-divisor/EMal/greatest-common-divisor.emal new file mode 100644 index 0000000000..bbb6e1a9ab --- /dev/null +++ b/Task/Greatest-common-divisor/EMal/greatest-common-divisor.emal @@ -0,0 +1,14 @@ +fun gcd ← int by int a, int b + while b ≠ 0 + int t ← b + b ← a % b + a ← t + end + return abs(a) +end +writeLine(gcd(0, 0)) +writeLine(gcd(0, -10)) +writeLine(gcd(-6, 9)) +writeLine(gcd(40902, 24140)) +writeLine(gcd(9360, 12240)) +writeLine(gcd(123456789, 987654321)) diff --git a/Task/Greatest-common-divisor/Elena/greatest-common-divisor.elena b/Task/Greatest-common-divisor/Elena/greatest-common-divisor.elena index 8d3b778db8..07bf136003 100644 --- a/Task/Greatest-common-divisor/Elena/greatest-common-divisor.elena +++ b/Task/Greatest-common-divisor/Elena/greatest-common-divisor.elena @@ -17,10 +17,10 @@ gcd(a,b) printGCD(a,b) { - console.printLineFormatted("GCD of {0} and {1} is {2}", a, b, gcd(a,b)) + Console.printLineFormatted("GCD of {0} and {1} is {2}", a, b, gcd(a,b)) } -public program() +public Program() { printGCD(1,1); printGCD(1,10); diff --git a/Task/Greatest-common-divisor/Elixir/greatest-common-divisor.elixir b/Task/Greatest-common-divisor/Elixir/greatest-common-divisor.ex similarity index 100% rename from Task/Greatest-common-divisor/Elixir/greatest-common-divisor.elixir rename to Task/Greatest-common-divisor/Elixir/greatest-common-divisor.ex diff --git a/Task/Greatest-common-divisor/Emacs-Lisp/greatest-common-divisor.l b/Task/Greatest-common-divisor/Emacs-Lisp/greatest-common-divisor.el similarity index 100% rename from Task/Greatest-common-divisor/Emacs-Lisp/greatest-common-divisor.l rename to Task/Greatest-common-divisor/Emacs-Lisp/greatest-common-divisor.el diff --git a/Task/Greatest-common-divisor/Euphoria/greatest-common-divisor-1.euphoria b/Task/Greatest-common-divisor/Euphoria/greatest-common-divisor-1.eu similarity index 100% rename from Task/Greatest-common-divisor/Euphoria/greatest-common-divisor-1.euphoria rename to Task/Greatest-common-divisor/Euphoria/greatest-common-divisor-1.eu diff --git a/Task/Greatest-common-divisor/Euphoria/greatest-common-divisor-2.euphoria b/Task/Greatest-common-divisor/Euphoria/greatest-common-divisor-2.eu similarity index 100% rename from Task/Greatest-common-divisor/Euphoria/greatest-common-divisor-2.euphoria rename to Task/Greatest-common-divisor/Euphoria/greatest-common-divisor-2.eu diff --git a/Task/Greatest-common-divisor/Euphoria/greatest-common-divisor-3.euphoria b/Task/Greatest-common-divisor/Euphoria/greatest-common-divisor-3.eu similarity index 100% rename from Task/Greatest-common-divisor/Euphoria/greatest-common-divisor-3.euphoria rename to Task/Greatest-common-divisor/Euphoria/greatest-common-divisor-3.eu diff --git a/Task/Greatest-common-divisor/F-Sharp/greatest-common-divisor.fs b/Task/Greatest-common-divisor/F-Sharp/greatest-common-divisor-1.fs similarity index 100% rename from Task/Greatest-common-divisor/F-Sharp/greatest-common-divisor.fs rename to Task/Greatest-common-divisor/F-Sharp/greatest-common-divisor-1.fs diff --git a/Task/Greatest-common-divisor/F-Sharp/greatest-common-divisor-2.fs b/Task/Greatest-common-divisor/F-Sharp/greatest-common-divisor-2.fs new file mode 100644 index 0000000000..121ed1a89b --- /dev/null +++ b/Task/Greatest-common-divisor/F-Sharp/greatest-common-divisor-2.fs @@ -0,0 +1,5 @@ +// GCD method attributed to Dijkstra. Nigel Galloway: February 7th., 2026. +let rec gcd n=function g when n=g->n + |g when ngcd (g-n) n + |g->gcd g (n-g) +printfn "%d, %d, %d" (gcd 23 13) (gcd 600 400) (gcd 0 0) diff --git a/Task/Greatest-common-divisor/Gleam/greatest-common-divisor.gleam b/Task/Greatest-common-divisor/Gleam/greatest-common-divisor.gleam new file mode 100644 index 0000000000..f5187521b9 --- /dev/null +++ b/Task/Greatest-common-divisor/Gleam/greatest-common-divisor.gleam @@ -0,0 +1,19 @@ +import gleam/int +import gleam/io + +pub fn main() { + gcd(40_902, 24_140) + |> int.to_string + |> io.println +} + +pub fn gcd(a, b) { + gcd_loop(int.absolute_value(a), int.absolute_value(b)) +} + +fn gcd_loop(a, b) { + case b { + 0 -> a + _ -> gcd_loop(b, a % b) + } +} diff --git a/Task/Greatest-common-divisor/J/greatest-common-divisor-3.j b/Task/Greatest-common-divisor/J/greatest-common-divisor-3.j index a4531536ed..f34b6cd4f7 100644 --- a/Task/Greatest-common-divisor/J/greatest-common-divisor-3.j +++ b/Task/Greatest-common-divisor/J/greatest-common-divisor-3.j @@ -1 +1 @@ -gcd=: (| gcd [)^:(0<[)&| +gcd=: (| $: [)^:(0<[)&| diff --git a/Task/Greatest-common-divisor/Julia/greatest-common-divisor.julia b/Task/Greatest-common-divisor/Julia/greatest-common-divisor.jl similarity index 100% rename from Task/Greatest-common-divisor/Julia/greatest-common-divisor.julia rename to Task/Greatest-common-divisor/Julia/greatest-common-divisor.jl diff --git a/Task/Greatest-common-divisor/Kotlin/greatest-common-divisor.kotlin b/Task/Greatest-common-divisor/Kotlin/greatest-common-divisor.kts similarity index 100% rename from Task/Greatest-common-divisor/Kotlin/greatest-common-divisor.kotlin rename to Task/Greatest-common-divisor/Kotlin/greatest-common-divisor.kts diff --git a/Task/Greatest-common-divisor/LOLCODE/greatest-common-divisor.lol b/Task/Greatest-common-divisor/LOLCODE/greatest-common-divisor.lol index 655b749ee7..b261e752da 100644 --- a/Task/Greatest-common-divisor/LOLCODE/greatest-common-divisor.lol +++ b/Task/Greatest-common-divisor/LOLCODE/greatest-common-divisor.lol @@ -1,36 +1,32 @@ HAI 1.3 -HOW IZ I gcd YR a AN YR b - a R BIGGR OF a AN PRODUKT OF a AN -1 BTW absolute value of a - b R BIGGR OF b AN PRODUKT OF b AN -1 BTW absolute value of b - BOTH SAEM a AN b, O RLY? - YA RLY - FOUND YR a - OIC - BOTH SAEM a AN 0, O RLY? - YA RLY - FOUND YR b - OIC - BOTH SAEM b AN 0, O RLY? - YA RLY - FOUND YR a - OIC - BOTH SAEM b AN BIGGR OF a AN b, O RLY? BTW make sure a is the larger of (a, b) - YA RLY - I HAS A temp ITZ a - a R b - b R temp - OIC - - IM IN YR loop - I HAS A temp ITZ b - b R MOD OF a AN b - a R temp - BOTH SAEM b AN 0, O RLY? - YA RLY - FOUND YR a - OIC - IM OUTTA YR loop +HOW IZ I gcd YR a AN YR b BTW ITERATIF GCD + a R BIGGR OF a AN PRODUKT OF a AN -1 BTW absolute value of a + b R BIGGR OF b AN PRODUKT OF b AN -1 BTW absolute value of b + BOTH SAEM a AN b, O RLY? + YA RLY + FOUND YR a + MEBBE BOTH SAEM a AN 0, + FOUND YR b + MEBBE BOTH SAEM b AN 0, + FOUND YR a + NO WAI + BOTH SAEM b AN BIGGR OF a AN b, O RLY? BTW make sure a is the larger of (a, b) + YA RLY + I HAS A temp ITZ a + a R b + b R temp + OIC + IM IN YR loop + I HAS A temp ITZ b + b R MOD OF a AN b + a R temp + BOTH SAEM b AN 0, O RLY? + YA RLY + FOUND YR a + OIC + IM OUTTA YR loop + OIC IF U SAY SO VISIBLE I IZ gcd YR 40902 AN YR 24140 MKAY diff --git a/Task/Greatest-common-divisor/Nu/greatest-common-divisor.nu b/Task/Greatest-common-divisor/Nu/greatest-common-divisor.nu new file mode 100644 index 0000000000..d2e0ca06ca --- /dev/null +++ b/Task/Greatest-common-divisor/Nu/greatest-common-divisor.nu @@ -0,0 +1,8 @@ +def 'math gcd' [] { + reduce {|x gcd| + generate { match $in { [$a 0] => {out: $a} [$a $b] => {next: [$b ($a mod $b)]} } } [$x $gcd] + | first + } +} + +[63 18 45] | math gcd diff --git a/Task/Greatest-common-divisor/OCaml/greatest-common-divisor-1.ocaml b/Task/Greatest-common-divisor/OCaml/greatest-common-divisor-1.ml similarity index 100% rename from Task/Greatest-common-divisor/OCaml/greatest-common-divisor-1.ocaml rename to Task/Greatest-common-divisor/OCaml/greatest-common-divisor-1.ml diff --git a/Task/Greatest-common-divisor/OCaml/greatest-common-divisor-2.ocaml b/Task/Greatest-common-divisor/OCaml/greatest-common-divisor-2.ml similarity index 100% rename from Task/Greatest-common-divisor/OCaml/greatest-common-divisor-2.ocaml rename to Task/Greatest-common-divisor/OCaml/greatest-common-divisor-2.ml diff --git a/Task/Greatest-common-divisor/Oberon/greatest-common-divisor.oberon b/Task/Greatest-common-divisor/Oberon/greatest-common-divisor.oberon deleted file mode 100644 index e81af17de6..0000000000 --- a/Task/Greatest-common-divisor/Oberon/greatest-common-divisor.oberon +++ /dev/null @@ -1,22 +0,0 @@ -MODULE GCD; -(* Greatest Common Divisor *) -IMPORT - Out; - - PROCEDURE Gcd(a,b: LONGINT):LONGINT; - VAR - r: LONGINT; - BEGIN - LOOP - r := a MOD b; - IF r = 0 THEN RETURN b END; - a := b;b := r - END - END Gcd; -BEGIN - Out.String("GCD of 12 and 8 : ");Out.LongInt(Gcd(12,8),4);Out.Ln; - Out.String("GCD of 100 and 5 : ");Out.LongInt(Gcd(100,5),4);Out.Ln; - Out.String("GCD of 7 and 23 : ");Out.LongInt(Gcd(7,23),4);Out.Ln; - Out.String("GCD of 24 and -112 : ");Out.LongInt(Gcd(12,8),4);Out.Ln; - Out.String("GCD of 40902 and 24140 : ");Out.LongInt(Gcd(40902,24140),4);Out.Ln -END GCD. diff --git a/Task/Greatest-common-divisor/Pascal/greatest-common-divisor.pas b/Task/Greatest-common-divisor/Pascal/greatest-common-divisor.pas new file mode 100644 index 0000000000..3766737710 --- /dev/null +++ b/Task/Greatest-common-divisor/Pascal/greatest-common-divisor.pas @@ -0,0 +1,17 @@ +program GCF (INPUT, OUTPUT); + var + a,b,c:integer; + begin + writeln('Enter 1st number'); + read(a); + writeln('Enter 2nd number'); + read(b); + while (a*b<>0) + do + begin + c:=a; + a:=b mod a; + b:=c; + end; + writeln('GCF :=', a+b ); + end. diff --git a/Task/Greatest-common-divisor/PascalABC.NET/greatest-common-divisor.pas b/Task/Greatest-common-divisor/PascalABC.NET/greatest-common-divisor.pas new file mode 100644 index 0000000000..7457c48563 --- /dev/null +++ b/Task/Greatest-common-divisor/PascalABC.NET/greatest-common-divisor.pas @@ -0,0 +1,18 @@ +function GCD(a,b: integer): integer; +begin + while b > 0 do + (a,b) := (b,a mod b); + Result := a; +end; + +function GCDRec(a,b: integer): integer; +begin + if b = 0 then + Result := a + else Result := GCDRec(b, a mod b); +end; + +begin + Println(GCD(72,30),GCDRec(72,30)); + Println(GCD(49865, 69811),GCDRec(49865, 69811)); +end. diff --git a/Task/Greatest-common-divisor/Pluto/greatest-common-divisor.pluto b/Task/Greatest-common-divisor/Pluto/greatest-common-divisor.pluto new file mode 100644 index 0000000000..9ead7fee31 --- /dev/null +++ b/Task/Greatest-common-divisor/Pluto/greatest-common-divisor.pluto @@ -0,0 +1,8 @@ +function gcd(a,b) + while b~=0 do + a,b=b,a%b + end + return a +end + +print(gcd(56,98)) diff --git a/Task/Greatest-common-divisor/PowerShell/greatest-common-divisor-1.psh b/Task/Greatest-common-divisor/PowerShell/greatest-common-divisor-1.ps1 similarity index 100% rename from Task/Greatest-common-divisor/PowerShell/greatest-common-divisor-1.psh rename to Task/Greatest-common-divisor/PowerShell/greatest-common-divisor-1.ps1 diff --git a/Task/Greatest-common-divisor/PowerShell/greatest-common-divisor-2.psh b/Task/Greatest-common-divisor/PowerShell/greatest-common-divisor-2.ps1 similarity index 100% rename from Task/Greatest-common-divisor/PowerShell/greatest-common-divisor-2.psh rename to Task/Greatest-common-divisor/PowerShell/greatest-common-divisor-2.ps1 diff --git a/Task/Greatest-common-divisor/PowerShell/greatest-common-divisor-3.psh b/Task/Greatest-common-divisor/PowerShell/greatest-common-divisor-3.ps1 similarity index 100% rename from Task/Greatest-common-divisor/PowerShell/greatest-common-divisor-3.psh rename to Task/Greatest-common-divisor/PowerShell/greatest-common-divisor-3.ps1 diff --git a/Task/Greatest-common-divisor/REBOL/greatest-common-divisor.rebol b/Task/Greatest-common-divisor/Rebol/greatest-common-divisor.rebol similarity index 100% rename from Task/Greatest-common-divisor/REBOL/greatest-common-divisor.rebol rename to Task/Greatest-common-divisor/Rebol/greatest-common-divisor.rebol diff --git a/Task/Greatest-common-divisor/Rust/greatest-common-divisor-1.rust b/Task/Greatest-common-divisor/Rust/greatest-common-divisor-1.rs similarity index 100% rename from Task/Greatest-common-divisor/Rust/greatest-common-divisor-1.rust rename to Task/Greatest-common-divisor/Rust/greatest-common-divisor-1.rs diff --git a/Task/Greatest-common-divisor/Rust/greatest-common-divisor-2.rust b/Task/Greatest-common-divisor/Rust/greatest-common-divisor-2.rs similarity index 100% rename from Task/Greatest-common-divisor/Rust/greatest-common-divisor-2.rust rename to Task/Greatest-common-divisor/Rust/greatest-common-divisor-2.rs diff --git a/Task/Greatest-common-divisor/Rust/greatest-common-divisor-3.rust b/Task/Greatest-common-divisor/Rust/greatest-common-divisor-3.rs similarity index 100% rename from Task/Greatest-common-divisor/Rust/greatest-common-divisor-3.rust rename to Task/Greatest-common-divisor/Rust/greatest-common-divisor-3.rs diff --git a/Task/Greatest-common-divisor/Rust/greatest-common-divisor-4.rust b/Task/Greatest-common-divisor/Rust/greatest-common-divisor-4.rs similarity index 100% rename from Task/Greatest-common-divisor/Rust/greatest-common-divisor-4.rust rename to Task/Greatest-common-divisor/Rust/greatest-common-divisor-4.rs diff --git a/Task/Greatest-common-divisor/Rust/greatest-common-divisor-5.rust b/Task/Greatest-common-divisor/Rust/greatest-common-divisor-5.rs similarity index 100% rename from Task/Greatest-common-divisor/Rust/greatest-common-divisor-5.rust rename to Task/Greatest-common-divisor/Rust/greatest-common-divisor-5.rs diff --git a/Task/Greatest-common-divisor/Scheme/greatest-common-divisor-1.ss b/Task/Greatest-common-divisor/Scheme/greatest-common-divisor-1.scm similarity index 100% rename from Task/Greatest-common-divisor/Scheme/greatest-common-divisor-1.ss rename to Task/Greatest-common-divisor/Scheme/greatest-common-divisor-1.scm diff --git a/Task/Greatest-common-divisor/Scheme/greatest-common-divisor-2.ss b/Task/Greatest-common-divisor/Scheme/greatest-common-divisor-2.scm similarity index 100% rename from Task/Greatest-common-divisor/Scheme/greatest-common-divisor-2.ss rename to Task/Greatest-common-divisor/Scheme/greatest-common-divisor-2.scm diff --git a/Task/Greatest-common-divisor/TypeScript/greatest-common-divisor-3.ts b/Task/Greatest-common-divisor/TypeScript/greatest-common-divisor-3.ts deleted file mode 100644 index 5069a3e212..0000000000 --- a/Task/Greatest-common-divisor/TypeScript/greatest-common-divisor-3.ts +++ /dev/null @@ -1 +0,0 @@ -⊙◌⍢(⊃∘◿:)(±,) diff --git a/Task/Greatest-common-divisor/Uiua/greatest-common-divisor.uiua b/Task/Greatest-common-divisor/Uiua/greatest-common-divisor.uiua new file mode 100644 index 0000000000..cffa04c401 --- /dev/null +++ b/Task/Greatest-common-divisor/Uiua/greatest-common-divisor.uiua @@ -0,0 +1 @@ +⊙◌⍢(⤙˜◿|◡⋅>₀) diff --git a/Task/Greatest-common-divisor/VBScript/greatest-common-divisor.vb b/Task/Greatest-common-divisor/VBScript/greatest-common-divisor.vbs similarity index 100% rename from Task/Greatest-common-divisor/VBScript/greatest-common-divisor.vb rename to Task/Greatest-common-divisor/VBScript/greatest-common-divisor.vbs diff --git a/Task/Greatest-common-divisor/YAMLScript/greatest-common-divisor.ys b/Task/Greatest-common-divisor/YAMLScript/greatest-common-divisor.ys new file mode 100644 index 0000000000..b77cb8bd55 --- /dev/null +++ b/Task/Greatest-common-divisor/YAMLScript/greatest-common-divisor.ys @@ -0,0 +1,9 @@ +!YS-v0 + +defn main(a=42 b=63): + say: "gcd($a $b) -> $gcd(a b)" + +defn gcd(a b): + if b > 0: + recur b: a % b + else: a diff --git a/Task/Greatest-element-of-a-list/ALGOL-68/greatest-element-of-a-list.alg b/Task/Greatest-element-of-a-list/ALGOL-68/greatest-element-of-a-list.alg index 15570e56dd..fa4c980bbe 100644 --- a/Task/Greatest-element-of-a-list/ALGOL-68/greatest-element-of-a-list.alg +++ b/Task/Greatest-element-of-a-list/ALGOL-68/greatest-element-of-a-list.alg @@ -1,12 +1,7 @@ -# substitute any array type with a scalar element # -MODE FLT = REAL; +BEGIN +MODE FLT = REAL; # substitute any array type with ">" defined # -# create an exception for the case of an empty array # -PROC raise empty array = VOID:( - GO TO except empty array -); - -PROC max = ([]FLT item)FLT: +PROC max = ([]FLT item, PROC VOID raise empty array)FLT: BEGIN IF LWB item > UPB item THEN raise empty array; SKIP @@ -22,9 +17,11 @@ BEGIN FI END # max #; -test:( +#test#( []FLT buf = (-275.0, -111.19, 0.0, -1234568.0, pi, -pi); - print((max(buf),new line)) EXIT - except empty array: - SKIP + # handle an exception for the case of an empty array # + PROC have empty array = VOID:print(("empty array", newline)); + + print((max(buf,have empty array),new line)) ) +END diff --git a/Task/Greatest-element-of-a-list/Ada/greatest-element-of-a-list-1.ada b/Task/Greatest-element-of-a-list/Ada/greatest-element-of-a-list-1.adb similarity index 100% rename from Task/Greatest-element-of-a-list/Ada/greatest-element-of-a-list-1.ada rename to Task/Greatest-element-of-a-list/Ada/greatest-element-of-a-list-1.adb diff --git a/Task/Greatest-element-of-a-list/Ada/greatest-element-of-a-list-2.ada b/Task/Greatest-element-of-a-list/Ada/greatest-element-of-a-list-2.adb similarity index 100% rename from Task/Greatest-element-of-a-list/Ada/greatest-element-of-a-list-2.ada rename to Task/Greatest-element-of-a-list/Ada/greatest-element-of-a-list-2.adb diff --git a/Task/Greatest-element-of-a-list/Ada/greatest-element-of-a-list-3.ada b/Task/Greatest-element-of-a-list/Ada/greatest-element-of-a-list-3.adb similarity index 100% rename from Task/Greatest-element-of-a-list/Ada/greatest-element-of-a-list-3.ada rename to Task/Greatest-element-of-a-list/Ada/greatest-element-of-a-list-3.adb diff --git a/Task/Greatest-element-of-a-list/ArkScript/greatest-element-of-a-list.ark b/Task/Greatest-element-of-a-list/ArkScript/greatest-element-of-a-list.ark new file mode 100644 index 0000000000..9a3429517e --- /dev/null +++ b/Task/Greatest-element-of-a-list/ArkScript/greatest-element-of-a-list.ark @@ -0,0 +1,11 @@ +(let max (fun (L) { + (mut index 0) + (mut output nil) + + (while (< index (len L)) { + (if (or (nil? output) (> (@ L index) output)) + (set output (@ L index))) + (set index (+ 1 index)) }) + output })) + +(print (max [1 2 3 0 -5 42 0 1])) diff --git a/Task/Greatest-element-of-a-list/Ballerina/greatest-element-of-a-list.ballerina b/Task/Greatest-element-of-a-list/Ballerina/greatest-element-of-a-list.ballerina new file mode 100644 index 0000000000..bdfeabbf46 --- /dev/null +++ b/Task/Greatest-element-of-a-list/Ballerina/greatest-element-of-a-list.ballerina @@ -0,0 +1,11 @@ +import ballerina/io; + +function max(float[] a) returns float { + return float:max(...a); +} + +public function main() { + float[] a = [1.0, 2.3, 1.1, 5.0, + 3.0, 2.8, 2.01, 3.14159]; + io:println(max(a)); +} diff --git a/Task/Greatest-element-of-a-list/COBOL/greatest-element-of-a-list-1.cobol b/Task/Greatest-element-of-a-list/COBOL/greatest-element-of-a-list-1.cob similarity index 100% rename from Task/Greatest-element-of-a-list/COBOL/greatest-element-of-a-list-1.cobol rename to Task/Greatest-element-of-a-list/COBOL/greatest-element-of-a-list-1.cob diff --git a/Task/Greatest-element-of-a-list/COBOL/greatest-element-of-a-list-2.cobol b/Task/Greatest-element-of-a-list/COBOL/greatest-element-of-a-list-2.cob similarity index 100% rename from Task/Greatest-element-of-a-list/COBOL/greatest-element-of-a-list-2.cobol rename to Task/Greatest-element-of-a-list/COBOL/greatest-element-of-a-list-2.cob diff --git a/Task/Greatest-element-of-a-list/Crystal/greatest-element-of-a-list.crystal b/Task/Greatest-element-of-a-list/Crystal/greatest-element-of-a-list.cr similarity index 100% rename from Task/Greatest-element-of-a-list/Crystal/greatest-element-of-a-list.crystal rename to Task/Greatest-element-of-a-list/Crystal/greatest-element-of-a-list.cr diff --git a/Task/Greatest-element-of-a-list/Delphi/greatest-element-of-a-list.delphi b/Task/Greatest-element-of-a-list/Delphi/greatest-element-of-a-list.pas similarity index 100% rename from Task/Greatest-element-of-a-list/Delphi/greatest-element-of-a-list.delphi rename to Task/Greatest-element-of-a-list/Delphi/greatest-element-of-a-list.pas diff --git a/Task/Greatest-element-of-a-list/DuckDB/greatest-element-of-a-list-1.duckdb b/Task/Greatest-element-of-a-list/DuckDB/greatest-element-of-a-list-1.duckdb new file mode 100644 index 0000000000..4128a2435f --- /dev/null +++ b/Task/Greatest-element-of-a-list/DuckDB/greatest-element-of-a-list-1.duckdb @@ -0,0 +1 @@ +select list_max( [1.0, 2.0, 3.14] ) as max; diff --git a/Task/Greatest-element-of-a-list/DuckDB/greatest-element-of-a-list-2.duckdb b/Task/Greatest-element-of-a-list/DuckDB/greatest-element-of-a-list-2.duckdb new file mode 100644 index 0000000000..cef71412c4 --- /dev/null +++ b/Task/Greatest-element-of-a-list/DuckDB/greatest-element-of-a-list-2.duckdb @@ -0,0 +1 @@ +select list_max( [ ['a']::JSON, [{'a':0}]::JSON ] ) as max; diff --git a/Task/Greatest-element-of-a-list/DuckDB/greatest-element-of-a-list-3.duckdb b/Task/Greatest-element-of-a-list/DuckDB/greatest-element-of-a-list-3.duckdb new file mode 100644 index 0000000000..d018f76d12 --- /dev/null +++ b/Task/Greatest-element-of-a-list/DuckDB/greatest-element-of-a-list-3.duckdb @@ -0,0 +1,4 @@ +create or replace function max_list(l) as ( + list_reduce(l, (acc, x) -> greatest(acc,x)) +); +select max_list( [ ['b']::JSON, ['a']::JSON ]); diff --git a/Task/Greatest-element-of-a-list/EasyLang/greatest-element-of-a-list.easy b/Task/Greatest-element-of-a-list/EasyLang/greatest-element-of-a-list.easy index d65b41b634..3f347d9e3d 100644 --- a/Task/Greatest-element-of-a-list/EasyLang/greatest-element-of-a-list.easy +++ b/Task/Greatest-element-of-a-list/EasyLang/greatest-element-of-a-list.easy @@ -1,5 +1,3 @@ a[] = [ 2 9 4 3 8 5 ] -for e in a[] - max = higher e max -. +for e in a[] : max = higher e max print max diff --git a/Task/Greatest-element-of-a-list/Elena/greatest-element-of-a-list.elena b/Task/Greatest-element-of-a-list/Elena/greatest-element-of-a-list.elena index 7bc11c96f6..2572fdf43b 100644 --- a/Task/Greatest-element-of-a-list/Elena/greatest-element-of-a-list.elena +++ b/Task/Greatest-element-of-a-list/Elena/greatest-element-of-a-list.elena @@ -24,7 +24,7 @@ extension op } } -public program() +public Program() { console.printLine(new int[]{1,2,3,4,20,10,9,8}.Maximal) } diff --git a/Task/Greatest-element-of-a-list/Elixir/greatest-element-of-a-list.elixir b/Task/Greatest-element-of-a-list/Elixir/greatest-element-of-a-list.ex similarity index 100% rename from Task/Greatest-element-of-a-list/Elixir/greatest-element-of-a-list.elixir rename to Task/Greatest-element-of-a-list/Elixir/greatest-element-of-a-list.ex diff --git a/Task/Greatest-element-of-a-list/Emacs-Lisp/greatest-element-of-a-list-1.l b/Task/Greatest-element-of-a-list/Emacs-Lisp/greatest-element-of-a-list-1.el similarity index 100% rename from Task/Greatest-element-of-a-list/Emacs-Lisp/greatest-element-of-a-list-1.l rename to Task/Greatest-element-of-a-list/Emacs-Lisp/greatest-element-of-a-list-1.el diff --git a/Task/Greatest-element-of-a-list/Emacs-Lisp/greatest-element-of-a-list-2.l b/Task/Greatest-element-of-a-list/Emacs-Lisp/greatest-element-of-a-list-2.el similarity index 100% rename from Task/Greatest-element-of-a-list/Emacs-Lisp/greatest-element-of-a-list-2.l rename to Task/Greatest-element-of-a-list/Emacs-Lisp/greatest-element-of-a-list-2.el diff --git a/Task/Greatest-element-of-a-list/Emacs-Lisp/greatest-element-of-a-list-3.l b/Task/Greatest-element-of-a-list/Emacs-Lisp/greatest-element-of-a-list-3.el similarity index 100% rename from Task/Greatest-element-of-a-list/Emacs-Lisp/greatest-element-of-a-list-3.l rename to Task/Greatest-element-of-a-list/Emacs-Lisp/greatest-element-of-a-list-3.el diff --git a/Task/Greatest-element-of-a-list/Emacs-Lisp/greatest-element-of-a-list-4.l b/Task/Greatest-element-of-a-list/Emacs-Lisp/greatest-element-of-a-list-4.el similarity index 100% rename from Task/Greatest-element-of-a-list/Emacs-Lisp/greatest-element-of-a-list-4.l rename to Task/Greatest-element-of-a-list/Emacs-Lisp/greatest-element-of-a-list-4.el diff --git a/Task/Greatest-element-of-a-list/Euphoria/greatest-element-of-a-list-1.euphoria b/Task/Greatest-element-of-a-list/Euphoria/greatest-element-of-a-list-1.eu similarity index 100% rename from Task/Greatest-element-of-a-list/Euphoria/greatest-element-of-a-list-1.euphoria rename to Task/Greatest-element-of-a-list/Euphoria/greatest-element-of-a-list-1.eu diff --git a/Task/Greatest-element-of-a-list/Euphoria/greatest-element-of-a-list-2.euphoria b/Task/Greatest-element-of-a-list/Euphoria/greatest-element-of-a-list-2.eu similarity index 100% rename from Task/Greatest-element-of-a-list/Euphoria/greatest-element-of-a-list-2.euphoria rename to Task/Greatest-element-of-a-list/Euphoria/greatest-element-of-a-list-2.eu diff --git a/Task/Greatest-element-of-a-list/Gleam/greatest-element-of-a-list-1.gleam b/Task/Greatest-element-of-a-list/Gleam/greatest-element-of-a-list-1.gleam new file mode 100644 index 0000000000..26e97484fa --- /dev/null +++ b/Task/Greatest-element-of-a-list/Gleam/greatest-element-of-a-list-1.gleam @@ -0,0 +1,8 @@ +import gleam/int +import gleam/list + +pub fn main() { + [1, 99, 136, 4, 3, 22, 111] + |> list.max(int.compare) + |> echo +} diff --git a/Task/Greatest-element-of-a-list/Gleam/greatest-element-of-a-list-2.gleam b/Task/Greatest-element-of-a-list/Gleam/greatest-element-of-a-list-2.gleam new file mode 100644 index 0000000000..24bda4cd6a --- /dev/null +++ b/Task/Greatest-element-of-a-list/Gleam/greatest-element-of-a-list-2.gleam @@ -0,0 +1,20 @@ +pub fn max( + over list: List(a), + with compare: fn(a, a) -> Order, +) -> Result(a, Nil) { + case list { + [] -> Error(Nil) + [first, ..rest] -> Ok(max_loop(rest, compare, first)) + } +} + +fn max_loop(list, compare, max) { + case list { + [] -> max + [first, ..rest] -> + case compare(first, max) { + order.Gt -> max_loop(rest, compare, first) + order.Lt | order.Eq -> max_loop(rest, compare, max) + } + } +} diff --git a/Task/Greatest-element-of-a-list/Julia/greatest-element-of-a-list.julia b/Task/Greatest-element-of-a-list/Julia/greatest-element-of-a-list.jl similarity index 100% rename from Task/Greatest-element-of-a-list/Julia/greatest-element-of-a-list.julia rename to Task/Greatest-element-of-a-list/Julia/greatest-element-of-a-list.jl diff --git a/Task/Greatest-element-of-a-list/Komodo/greatest-element-of-a-list.komodo b/Task/Greatest-element-of-a-list/Komodo/greatest-element-of-a-list.komodo new file mode 100644 index 0000000000..8ecd71f500 --- /dev/null +++ b/Task/Greatest-element-of-a-list/Komodo/greatest-element-of-a-list.komodo @@ -0,0 +1,8 @@ +let max([first|tail]) := max(first, tail) +let max(curMax, []) := curMax +let max(curMax, [first|tail]) := max( + if curMax > first then curMax else first, + tail, +) + +assert(max([3, 5, 7, 2, 4, 8, -1]) = 8) diff --git a/Task/Greatest-element-of-a-list/Kotlin/greatest-element-of-a-list.kotlin b/Task/Greatest-element-of-a-list/Kotlin/greatest-element-of-a-list.kts similarity index 100% rename from Task/Greatest-element-of-a-list/Kotlin/greatest-element-of-a-list.kotlin rename to Task/Greatest-element-of-a-list/Kotlin/greatest-element-of-a-list.kts diff --git a/Task/Greatest-element-of-a-list/Nu/greatest-element-of-a-list.nu b/Task/Greatest-element-of-a-list/Nu/greatest-element-of-a-list.nu new file mode 100644 index 0000000000..82d037d42d --- /dev/null +++ b/Task/Greatest-element-of-a-list/Nu/greatest-element-of-a-list.nu @@ -0,0 +1 @@ +[1 5 3 11 7] | math max diff --git a/Task/Greatest-element-of-a-list/OCaml/greatest-element-of-a-list.ocaml b/Task/Greatest-element-of-a-list/OCaml/greatest-element-of-a-list.ml similarity index 100% rename from Task/Greatest-element-of-a-list/OCaml/greatest-element-of-a-list.ocaml rename to Task/Greatest-element-of-a-list/OCaml/greatest-element-of-a-list.ml diff --git a/Task/Greatest-element-of-a-list/PascalABC.NET/greatest-element-of-a-list.pas b/Task/Greatest-element-of-a-list/PascalABC.NET/greatest-element-of-a-list.pas new file mode 100644 index 0000000000..c2ed38704b --- /dev/null +++ b/Task/Greatest-element-of-a-list/PascalABC.NET/greatest-element-of-a-list.pas @@ -0,0 +1,3 @@ +## +var values := Lst(1,7,4,6,3,5,2,6); +values.Max.Print; diff --git a/Task/Greatest-element-of-a-list/Pluto/greatest-element-of-a-list.pluto b/Task/Greatest-element-of-a-list/Pluto/greatest-element-of-a-list.pluto new file mode 100644 index 0000000000..794b3bbaf6 --- /dev/null +++ b/Task/Greatest-element-of-a-list/Pluto/greatest-element-of-a-list.pluto @@ -0,0 +1,2 @@ +local list = {42, 7, -5, 11.7, 58, 22.31, 59, -18} +print(list:max()) diff --git a/Task/Greatest-element-of-a-list/PowerShell/greatest-element-of-a-list.psh b/Task/Greatest-element-of-a-list/PowerShell/greatest-element-of-a-list.ps1 similarity index 100% rename from Task/Greatest-element-of-a-list/PowerShell/greatest-element-of-a-list.psh rename to Task/Greatest-element-of-a-list/PowerShell/greatest-element-of-a-list.ps1 diff --git a/Task/Greatest-element-of-a-list/REBOL/greatest-element-of-a-list.rebol b/Task/Greatest-element-of-a-list/REBOL/greatest-element-of-a-list.rebol deleted file mode 100644 index 952008c20e..0000000000 --- a/Task/Greatest-element-of-a-list/REBOL/greatest-element-of-a-list.rebol +++ /dev/null @@ -1,14 +0,0 @@ -REBOL [ - Title: "Maximum Value" - URL: http://rosettacode.org/wiki/Maximum_Value -] - -max: func [ - "Find maximum value in a list." - values [series!] "List of values." -] [ - first maximum-of values -] - -print ["Max of" mold d: [5 4 3 2 1] "is" max d] -print ["Max of" mold d: [-5 -4 -3 -2 -1] "is" max d] diff --git a/Task/Greatest-element-of-a-list/Rebol/greatest-element-of-a-list-1.rebol b/Task/Greatest-element-of-a-list/Rebol/greatest-element-of-a-list-1.rebol new file mode 100644 index 0000000000..8adb252ada --- /dev/null +++ b/Task/Greatest-element-of-a-list/Rebol/greatest-element-of-a-list-1.rebol @@ -0,0 +1,14 @@ +Rebol [ + Title: "Maximum Value" + URL: http://rosettacode.org/wiki/Maximum_Value +] + +max: func [ + "Find maximum value in a list." + values [series!] "List of values." +] [ + first maximum-of values +] + +print ["Max of" mold d: [5 4 3 2 1] "is" max d] +print ["Max of" mold d: [-5 -4 -3 -2 -1] "is" max d] diff --git a/Task/Greatest-element-of-a-list/Rebol/greatest-element-of-a-list-2.rebol b/Task/Greatest-element-of-a-list/Rebol/greatest-element-of-a-list-2.rebol new file mode 100644 index 0000000000..1fc5e0cfa9 --- /dev/null +++ b/Task/Greatest-element-of-a-list/Rebol/greatest-element-of-a-list-2.rebol @@ -0,0 +1,2 @@ +print last sort [1 2 3 5 4] +;== 5 diff --git a/Task/Greatest-element-of-a-list/Rebol/greatest-element-of-a-list-3.rebol b/Task/Greatest-element-of-a-list/Rebol/greatest-element-of-a-list-3.rebol new file mode 100644 index 0000000000..3fcee66127 --- /dev/null +++ b/Task/Greatest-element-of-a-list/Rebol/greatest-element-of-a-list-3.rebol @@ -0,0 +1,9 @@ +vect: #(i16! [1 2 9 2 4]) +vect/maximum +;== 9 +query vect 'max +;== 9 +query vect [maximum minimum] +;== [maximum: 9 minimum: 1] +query vect [:maximum :minimum] +;== [9 1] diff --git a/Task/Greatest-element-of-a-list/Rust/greatest-element-of-a-list.rust b/Task/Greatest-element-of-a-list/Rust/greatest-element-of-a-list.rs similarity index 100% rename from Task/Greatest-element-of-a-list/Rust/greatest-element-of-a-list.rust rename to Task/Greatest-element-of-a-list/Rust/greatest-element-of-a-list.rs diff --git a/Task/Greatest-element-of-a-list/Rye/greatest-element-of-a-list.rye b/Task/Greatest-element-of-a-list/Rye/greatest-element-of-a-list.rye new file mode 100644 index 0000000000..aa0ce27a2a --- /dev/null +++ b/Task/Greatest-element-of-a-list/Rye/greatest-element-of-a-list.rye @@ -0,0 +1 @@ +print max { 3 22 4 9 10 } diff --git a/Task/Greatest-element-of-a-list/Scheme/greatest-element-of-a-list.ss b/Task/Greatest-element-of-a-list/Scheme/greatest-element-of-a-list.scm similarity index 100% rename from Task/Greatest-element-of-a-list/Scheme/greatest-element-of-a-list.ss rename to Task/Greatest-element-of-a-list/Scheme/greatest-element-of-a-list.scm diff --git a/Task/Greatest-element-of-a-list/TAV/greatest-element-of-a-list.tav b/Task/Greatest-element-of-a-list/TAV/greatest-element-of-a-list.tav new file mode 100644 index 0000000000..dedbbf5933 --- /dev/null +++ b/Task/Greatest-element-of-a-list/TAV/greatest-element-of-a-list.tav @@ -0,0 +1,4 @@ +main (parms):+ + ? parms.Count < 2 + parms =: 5, 2, 7, 11, 4, 99, 33 + print maximum of parms diff --git a/Task/Greatest-element-of-a-list/Tailspin/greatest-element-of-a-list-3.tailspin b/Task/Greatest-element-of-a-list/Tailspin/greatest-element-of-a-list-3.tailspin index e62dae2ed6..c1cd1001c7 100644 --- a/Task/Greatest-element-of-a-list/Tailspin/greatest-element-of-a-list-3.tailspin +++ b/Task/Greatest-element-of-a-list/Tailspin/greatest-element-of-a-list-3.tailspin @@ -1,2 +1,7 @@ -[1, 5, 20, 3, 9, 7] -> \(@: $(1); $(2..last)... -> # $@ ! when <$@..> do @: $;\) -> !OUT::write +[1, 5, 20, 3, 9, 7] -> \(@: $(1); + $(2..last)... -> # + $@ ! + + when <$@..> do @: $; +\) -> !OUT::write // outputs 20 diff --git a/Task/Greatest-element-of-a-list/Tailspin/greatest-element-of-a-list-4.tailspin b/Task/Greatest-element-of-a-list/Tailspin/greatest-element-of-a-list-4.tailspin index a330ba807a..92a2a4b411 100644 --- a/Task/Greatest-element-of-a-list/Tailspin/greatest-element-of-a-list-4.tailspin +++ b/Task/Greatest-element-of-a-list/Tailspin/greatest-element-of-a-list-4.tailspin @@ -1,8 +1,8 @@ -templates max - @: $(1); - $(2..last)... -> \(<$@max..> @max: $;\) -> !VOID - $@! -end max +[1, 5, 20, 3, 9, 7] -> templates + @ set $(1); + $(2..)... -> !# + $@ ! -[1, 5, 20, 3, 9, 7] -> max -> !OUT::write -// outputs 20 + when <|$@..> do @ set $; +end ! +-- outputs 20 diff --git a/Task/Greatest-element-of-a-list/Tailspin/greatest-element-of-a-list-5.tailspin b/Task/Greatest-element-of-a-list/Tailspin/greatest-element-of-a-list-5.tailspin new file mode 100644 index 0000000000..a330ba807a --- /dev/null +++ b/Task/Greatest-element-of-a-list/Tailspin/greatest-element-of-a-list-5.tailspin @@ -0,0 +1,8 @@ +templates max + @: $(1); + $(2..last)... -> \(<$@max..> @max: $;\) -> !VOID + $@! +end max + +[1, 5, 20, 3, 9, 7] -> max -> !OUT::write +// outputs 20 diff --git a/Task/Greatest-element-of-a-list/True-BASIC/greatest-element-of-a-list.basic b/Task/Greatest-element-of-a-list/True-BASIC/greatest-element-of-a-list.basic new file mode 100644 index 0000000000..cf549f2611 --- /dev/null +++ b/Task/Greatest-element-of-a-list/True-BASIC/greatest-element-of-a-list.basic @@ -0,0 +1,16 @@ +OPTION BASE 0 + +DIM vals(4) +LET vals(1) = 70.5 +LET vals(2) = 23.67 +LET vals(3) = 150.2 +LET vals(4) = 145 + +FUNCTION findmax + FOR x = 1 TO UBOUND(vals) + IF vals(x) > vals(x-1) THEN LET findmax = vals(x) + NEXT x +END FUNCTION + +PRINT findmax +END diff --git a/Task/Greatest-element-of-a-list/VBScript/greatest-element-of-a-list.vb b/Task/Greatest-element-of-a-list/VBScript/greatest-element-of-a-list.vbs similarity index 100% rename from Task/Greatest-element-of-a-list/VBScript/greatest-element-of-a-list.vb rename to Task/Greatest-element-of-a-list/VBScript/greatest-element-of-a-list.vbs diff --git a/Task/Greatest-subsequential-sum/ALGOL-68/greatest-subsequential-sum.alg b/Task/Greatest-subsequential-sum/ALGOL-68/greatest-subsequential-sum.alg index 71d6e84d21..e720ed2065 100644 --- a/Task/Greatest-subsequential-sum/ALGOL-68/greatest-subsequential-sum.alg +++ b/Task/Greatest-subsequential-sum/ALGOL-68/greatest-subsequential-sum.alg @@ -1,4 +1,3 @@ -main: ( []INT a = (-1 , -2 , 3 , 5 , 6 , -2 , -1 , 4 , -4 , 2 , -1); @@ -23,7 +22,7 @@ main: OD; FOR i FROM begin max TO end max DO - print(a[i]) + print((" ",whole(a[i],0))) OD ) diff --git a/Task/Greatest-subsequential-sum/Ada/greatest-subsequential-sum.ada b/Task/Greatest-subsequential-sum/Ada/greatest-subsequential-sum.adb similarity index 100% rename from Task/Greatest-subsequential-sum/Ada/greatest-subsequential-sum.ada rename to Task/Greatest-subsequential-sum/Ada/greatest-subsequential-sum.adb diff --git a/Task/Greatest-subsequential-sum/Arturo/greatest-subsequential-sum.arturo b/Task/Greatest-subsequential-sum/Arturo/greatest-subsequential-sum.arturo index a1470d3426..59676b248e 100644 --- a/Task/Greatest-subsequential-sum/Arturo/greatest-subsequential-sum.arturo +++ b/Task/Greatest-subsequential-sum/Arturo/greatest-subsequential-sum.arturo @@ -17,8 +17,8 @@ subarraySum: function [arr][ lst: i ] ] - if? lst > fst -> return @[mx, slice arr fst lst] - else -> return [0, []] + switch lst > fst -> return @[mx, slice arr fst lst] + -> return [0, []] ] sequences: @[ diff --git a/Task/Greatest-subsequential-sum/AutoIt/greatest-subsequential-sum.autoit b/Task/Greatest-subsequential-sum/AutoIt/greatest-subsequential-sum.au3 similarity index 100% rename from Task/Greatest-subsequential-sum/AutoIt/greatest-subsequential-sum.autoit rename to Task/Greatest-subsequential-sum/AutoIt/greatest-subsequential-sum.au3 diff --git a/Task/Greatest-subsequential-sum/Ballerina/greatest-subsequential-sum.ballerina b/Task/Greatest-subsequential-sum/Ballerina/greatest-subsequential-sum.ballerina new file mode 100644 index 0000000000..3ee409c7ea --- /dev/null +++ b/Task/Greatest-subsequential-sum/Ballerina/greatest-subsequential-sum.ballerina @@ -0,0 +1,42 @@ +import ballerina/io; + +function gss(int[] s) returns [int[], int] { + int best = 0; + int strt = 0; + int end = 0; + int sum = 0; + int sumStart = 0; + foreach var [i, x] in s.enumerate() { + sum += x; + if sum > best { + best = sum; + strt = sumStart; + end = i + 1; + } else if sum < 0 { + sum = 0; + sumStart = i + 1; + } + } + return [s.slice(strt, end), best]; +} + +function A(any[] a) returns string { + return re `,`.replaceAll(a.toString(), ", "); +} + +public function main() { + var tests = [ + [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1], + [-1, 1, 2, -5, -6], + [], + [-1, -2, -1] + ]; + foreach var test in tests { + io:println("Input: ", A(test)); + var res = gss(test); + var subSeq = res[0]; + int sum = res[1]; + io:println("Sub seq: ", A(subSeq)); + io:println("Sum: ", sum, "\n"); + } +} diff --git a/Task/Greatest-subsequential-sum/Crystal/greatest-subsequential-sum-1.crystal b/Task/Greatest-subsequential-sum/Crystal/greatest-subsequential-sum-1.cr similarity index 100% rename from Task/Greatest-subsequential-sum/Crystal/greatest-subsequential-sum-1.crystal rename to Task/Greatest-subsequential-sum/Crystal/greatest-subsequential-sum-1.cr diff --git a/Task/Greatest-subsequential-sum/Crystal/greatest-subsequential-sum-2.crystal b/Task/Greatest-subsequential-sum/Crystal/greatest-subsequential-sum-2.cr similarity index 100% rename from Task/Greatest-subsequential-sum/Crystal/greatest-subsequential-sum-2.crystal rename to Task/Greatest-subsequential-sum/Crystal/greatest-subsequential-sum-2.cr diff --git a/Task/Greatest-subsequential-sum/Crystal/greatest-subsequential-sum-3.crystal b/Task/Greatest-subsequential-sum/Crystal/greatest-subsequential-sum-3.cr similarity index 100% rename from Task/Greatest-subsequential-sum/Crystal/greatest-subsequential-sum-3.crystal rename to Task/Greatest-subsequential-sum/Crystal/greatest-subsequential-sum-3.cr diff --git a/Task/Greatest-subsequential-sum/DuckDB/greatest-subsequential-sum.duckdb b/Task/Greatest-subsequential-sum/DuckDB/greatest-subsequential-sum.duckdb new file mode 100644 index 0000000000..b989bd5e2b --- /dev/null +++ b/Task/Greatest-subsequential-sum/DuckDB/greatest-subsequential-sum.duckdb @@ -0,0 +1,32 @@ +create or replace function list_find_last_nonnegative(lst) as ( + select first(i) + from range(length(lst), 0, -1) t(i) + where lst[i] > 0 +); + +# Return the tuple (start, end, subtotal) for the subsequence lst[start:end] +# having a maximal subtotal for the given value of `start`. +# Initial negative numbers are ignored. +# It is assumed that the caller has taken care of trailing negative numbers. +create or replace function max_initial_subsequential_sum(lst, start) as ( + select max_by( (start,i,total), total) + from ( SELECT i, list_sum(lst[start:i]) as total + FROM range(start, length(lst)+1) t(i) + WHERE lst[start] >= 0 ) +); + +# If the list is empty or if the items are all negative, return [] +create or replace function subsequence_with_maximal_sum(lst) as ( + with cte as (select list_find_last_nonnegative(lst) as len) + select coalesce(max_by( lst[ mis[1]: mis[2]], mis[3] ), []) + from ( SELECT max_initial_subsequential_sum(lst,start) as mis + FROM (select unnest(range(1, 1 + len)) as start from cte) ) +); + +# Examples +select s, subsequence_with_maximal_sum(s) as subseq +from values + ([1,2,3,-1, 10]), + ([-1,2,3,-1, 10]), + ([-1,-2]), + ([]) as t(s); diff --git a/Task/Greatest-subsequential-sum/EasyLang/greatest-subsequential-sum.easy b/Task/Greatest-subsequential-sum/EasyLang/greatest-subsequential-sum.easy new file mode 100644 index 0000000000..90385e92e1 --- /dev/null +++ b/Task/Greatest-subsequential-sum/EasyLang/greatest-subsequential-sum.easy @@ -0,0 +1,21 @@ +proc max_subseq &seq[] &start &stop &maxsum . + maxsum = 0 + i = 1 + start = 1 + stop = 0 + for j to len seq[] + sum += seq[j] + if sum < 0 + i = j + 1 + sum = 0 + elif sum > maxsum + start = i + stop = j + maxsum = sum + . + . +. +a[] = [ -1 -2 3 5 6 -2 -1 4 -4 2 -1 ] +max_subseq a[] a b sum +print "Max sum = " & sum +for i = a to b : write a[i] & " " diff --git a/Task/Greatest-subsequential-sum/Elixir/greatest-subsequential-sum-1.elixir b/Task/Greatest-subsequential-sum/Elixir/greatest-subsequential-sum-1.ex similarity index 100% rename from Task/Greatest-subsequential-sum/Elixir/greatest-subsequential-sum-1.elixir rename to Task/Greatest-subsequential-sum/Elixir/greatest-subsequential-sum-1.ex diff --git a/Task/Greatest-subsequential-sum/Elixir/greatest-subsequential-sum-2.elixir b/Task/Greatest-subsequential-sum/Elixir/greatest-subsequential-sum-2.ex similarity index 100% rename from Task/Greatest-subsequential-sum/Elixir/greatest-subsequential-sum-2.elixir rename to Task/Greatest-subsequential-sum/Elixir/greatest-subsequential-sum-2.ex diff --git a/Task/Greatest-subsequential-sum/Elixir/greatest-subsequential-sum-3.elixir b/Task/Greatest-subsequential-sum/Elixir/greatest-subsequential-sum-3.ex similarity index 100% rename from Task/Greatest-subsequential-sum/Elixir/greatest-subsequential-sum-3.elixir rename to Task/Greatest-subsequential-sum/Elixir/greatest-subsequential-sum-3.ex diff --git a/Task/Greatest-subsequential-sum/Euphoria/greatest-subsequential-sum.euphoria b/Task/Greatest-subsequential-sum/Euphoria/greatest-subsequential-sum.eu similarity index 100% rename from Task/Greatest-subsequential-sum/Euphoria/greatest-subsequential-sum.euphoria rename to Task/Greatest-subsequential-sum/Euphoria/greatest-subsequential-sum.eu diff --git a/Task/Greatest-subsequential-sum/FutureBasic/greatest-subsequential-sum.basic b/Task/Greatest-subsequential-sum/FutureBasic/greatest-subsequential-sum.basic new file mode 100644 index 0000000000..836a0f87a4 --- /dev/null +++ b/Task/Greatest-subsequential-sum/FutureBasic/greatest-subsequential-sum.basic @@ -0,0 +1,64 @@ +_rndlen = 01 //BOOL: is sequence length random or fixed +_maxlen = 14 //Length of each/longest sequence +_maxVal = 20 //Largest number (pos or neg) in sequence +_repeat = 25 //Number of sequences to evaluate + +void local fn maxSubSequence + int i, j, seq(_maxlen), ndx(_maxlen + 1),sum(_maxlen) + int grp, maxSum, maxNdx, maxEnd, tot, iterations = _repeat + + while iterations + iterations-- + + // Create random sequence + int count = (_rndlen) ? rnd(_maxlen) : _maxlen + for i = 1 to count + seq(i) = rnd(_maxVal * 2 + 1) - _maxVal - 1 + next + + // Determine maximum sub-sequence + bool isNeg = yes : grp = 0 : sum(0) = 0 : ndx(0) = 0 + maxSum = 0 : maxNdx = 0 : maxEnd = 0 + + for i = 1 to count // Merge array into groups of like signs + if (seq(i) < 0) <> isNeg // If change of sign... + grp ++ // Start new group + isNeg = yes - isNeg + ndx(grp) = i + sum(grp) = 0 + end if + sum(grp) += seq(i) + next + ndx(grp + 1) = 0 + + for i = 1 to grp step 2 // Determine max sub-sequence + j = i : tot = sum(j) + do + if tot > maxSum + maxSum = tot + maxNdx = ndx(i) + maxEnd = ndx(j + 1) + end if + j += 2 : tot += sum(j - 1) + sum(j) // add next neg & pos groups + until j > grp + next + + // Print result + print @" Sum = "; maxSum, " {"; + for i = 1 to count + if i == maxNdx then text ,,, _zCyan + if i == maxEnd then text ,,, fn ColorClear + print " "; seq(i); " "; + next + text ,,, fn ColorClear + print "}" + + wend +end fn + +window 1, @"Maximum subsequence" +CFTimeInterval t : t = fn CACurrentMediaTime +fn maxSubSequence +printf @"\n %d random sequences created, solved, and printed in %.3f sec.",_repeat,1*(fn CACurrentMediaTime - t) + +handleevents diff --git a/Task/Greatest-subsequential-sum/Julia/greatest-subsequential-sum.julia b/Task/Greatest-subsequential-sum/Julia/greatest-subsequential-sum.jl similarity index 100% rename from Task/Greatest-subsequential-sum/Julia/greatest-subsequential-sum.julia rename to Task/Greatest-subsequential-sum/Julia/greatest-subsequential-sum.jl diff --git a/Task/Greatest-subsequential-sum/Kotlin/greatest-subsequential-sum.kotlin b/Task/Greatest-subsequential-sum/Kotlin/greatest-subsequential-sum.kts similarity index 100% rename from Task/Greatest-subsequential-sum/Kotlin/greatest-subsequential-sum.kotlin rename to Task/Greatest-subsequential-sum/Kotlin/greatest-subsequential-sum.kts diff --git a/Task/Greatest-subsequential-sum/Lua/greatest-subsequential-sum.lua b/Task/Greatest-subsequential-sum/Lua/greatest-subsequential-sum.lua index 23551e0e51..cbf5481d51 100644 --- a/Task/Greatest-subsequential-sum/Lua/greatest-subsequential-sum.lua +++ b/Task/Greatest-subsequential-sum/Lua/greatest-subsequential-sum.lua @@ -8,7 +8,25 @@ function maxsub(ary, idx) end local v = maxsub(ary, idx + 1) if maxsum < sumt(v, 1, #v) then return v end - local ret = {} - for i = idx, last do ret[#ret+1] = ary[i] end - return ret + local ret, allNegative = {}, true + for i = idx, last do + ret[#ret+1] = ary[i] + if ret[#ret] >= 0 then allNegative = false end + end + return allNegative and {} or ret end + +local function test(s) + local msub = maxsub(s) + print("["..table.concat(s, " ").."] -> ["..table.concat(msub, " ").."] sum: "..sumt(msub, 1, #msub)) +end + +-- test cases from 11l +test {-1, 2, -1} +test {-1, 2, -1, 3, -1} +test {-1, 1, 2, -5, -6} +test {-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1} + +-- additional test cases +test {-1, -2, -1} +test {} diff --git a/Task/Greatest-subsequential-sum/M2000-Interpreter/greatest-subsequential-sum-1.m2000 b/Task/Greatest-subsequential-sum/M2000-Interpreter/greatest-subsequential-sum-1.m2000 new file mode 100644 index 0000000000..1eb7221eed --- /dev/null +++ b/Task/Greatest-subsequential-sum/M2000-Interpreter/greatest-subsequential-sum-1.m2000 @@ -0,0 +1,26 @@ +module Greatest_subsequential_sum { + showGSS=lambda (a)->{ + function Greatest_subsequential_sum(a as array){ + s=a#sum() + =a + p=len(a)-1 + if p<0 then exit + for i=0 to p + for j=i to p + k= a#slice(i, j) + m=k#sum() + if m>s then =k: s=m + next + next + } + = "("+a#str$(",")+") -> ("+ Greatest_subsequential_sum(a)#str$(",")+")" + } + open "out.txt" for output as#f + print #f, showGSS((-1 , 2 , -1)) + print #f, showGSS((-1, 2, -1, 3, -1)) + print #f, showGSS((-1, 1, 2, -5, -6)) + print #f, showGSS((-1 , -2 , 3 , 5 , 6 , -2 , -1 , 4 , -4 , 2 , -1)) + close #f + win notepad, dir$+"out.txt" +} +Greatest_subsequential_sum diff --git a/Task/Greatest-subsequential-sum/M2000-Interpreter/greatest-subsequential-sum-2.m2000 b/Task/Greatest-subsequential-sum/M2000-Interpreter/greatest-subsequential-sum-2.m2000 new file mode 100644 index 0000000000..a16c08d534 --- /dev/null +++ b/Task/Greatest-subsequential-sum/M2000-Interpreter/greatest-subsequential-sum-2.m2000 @@ -0,0 +1,36 @@ +module Greatest_subsequential_sum (filename) { + showGSS=lambda (a)->{ + function Greatest_subsequential_sum(a as array){ + var best = 0 + var start = 0 + var end = 0 + var sum = 0 + var sumStart = 0 + var i = 0 + s=each(a) + while s { + sum +=array(s) + if (sum > best) then { + best = sum + start = sumStart + end = i + 1 + } else.if (sum < 0) then { + sum = 0 + sumStart = i + 1 + } + i++ + } + =a#slice(start, end-1) + } + = "("+a#str$(",")+") -> ("+ Greatest_subsequential_sum(a)#str$(",")+")" + } + open filename for output as#f + print #f, showGSS((-1 , 2 , -1)) + print #f, showGSS((-1, 2, -1, 3, -1)) + print #f, showGSS((-1, 1, 2, -5, -6)) + print #f, showGSS((-1 , -2 , 3 , 5 , 6 , -2 , -1 , 4 , -4 , 2 , -1)) + close #f + if filename<>"" then win notepad, dir$+filename +} +Greatest_subsequential_sum "" ' to screen +Greatest_subsequential_sum "out.txt" diff --git a/Task/Greatest-subsequential-sum/OCaml/greatest-subsequential-sum.ocaml b/Task/Greatest-subsequential-sum/OCaml/greatest-subsequential-sum.ml similarity index 100% rename from Task/Greatest-subsequential-sum/OCaml/greatest-subsequential-sum.ocaml rename to Task/Greatest-subsequential-sum/OCaml/greatest-subsequential-sum.ml diff --git a/Task/Greatest-subsequential-sum/PascalABC.NET/greatest-subsequential-sum.pas b/Task/Greatest-subsequential-sum/PascalABC.NET/greatest-subsequential-sum.pas new file mode 100644 index 0000000000..0f5860e32e --- /dev/null +++ b/Task/Greatest-subsequential-sum/PascalABC.NET/greatest-subsequential-sum.pas @@ -0,0 +1,28 @@ +function MaxSumSeq(a: array of integer): (integer,integer,integer); +begin + var (maxSum,thisSum) := (0,0); + var (f,t) := (0,-1); + var k := 0; + for var j:=0 to a.Length-1 do + begin + thisSum += a[j]; + if thisSum < 0 then + begin + k := j + 1; + thisSum := 0; + end + else if thisSum > maxSum then + begin + maxSum := thisSum; + f := k; + t := j + end; + end; + Result := (f,t,maxSum); +end; + +begin + var a := Arr(-1 , -2 , 3 , 5 , 6 , -2 , -1 , 4 , -4 , 2 , -1); + var (f,t,max) := MaxSumSeq(a); + Print('Subsequence with max sum:', a[f:t+1], 'It''s sum:', max); +end. diff --git a/Task/Greatest-subsequential-sum/Phix/greatest-subsequential-sum.phix b/Task/Greatest-subsequential-sum/Phix/greatest-subsequential-sum.phix index 98711bab7a..8229d70663 100644 --- a/Task/Greatest-subsequential-sum/Phix/greatest-subsequential-sum.phix +++ b/Task/Greatest-subsequential-sum/Phix/greatest-subsequential-sum.phix @@ -1,19 +1,17 @@ -(phixonline)--> - with javascript_semantics - function maxSubseq(sequence s) - integer maxsum = 0, first = 1, last = 0 - for i=1 to length(s) do - integer sumsij = 0 - for j=i to length(s) do - sumsij += s[j] - if sumsij>maxsum then - {maxsum,first,last} = {sumsij,i,j} - end if - end for - end for - return s[first..last] - end function - ? maxSubseq({-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1}) - ? maxSubseq({}) - ? maxSubseq({-1, -5, -3}) - - with javascript_semantics - include mpfr.e - function egyptian(integer num, denom) - mpz n = mpz_init(num), - d = mpz_init(denom), - t = mpz_init() - sequence result = {} - while mpz_cmp_si(n,0)!=0 do - mpz_cdiv_q(t, d, n) - result = append(result,"1/"&mpz_get_str(t)) - mpz_neg(d,d) - mpz_mod(n,d,n) - mpz_neg(d,d) - mpz_mul(d,d,t) - end while - {n,d} = mpz_free({n,d}) - return result - end function +with javascript_semantics +include mpfr.e +function egyptian(integer num, denom) + mpz n = mpz_init(num), + d = mpz_init(denom), + t = mpz_init() + sequence result = {} + while mpz_cmp_si(n,0)!=0 do + mpz_cdiv_q(t, d, n) + result = append(result,"1/"&mpz_get_str(t)) + mpz_neg(d,d) + mpz_mod(n,d,n) + mpz_neg(d,d) + mpz_mul(d,d,t) + end while + {n,d} = mpz_free({n,d}) + return result +end function - procedure efrac(integer num, denom) - string fraction = sprintf("%d/%d",{num,denom}), - prefix = "" - if num>=denom then - integer whole = floor(num/denom) - num -= whole*denom - prefix = sprintf("[%d] + ",whole) - end if - string e = join(egyptian(num, denom)," + ") - printf(1,"%s -> %s%s\n",{fraction,prefix,e}) - end procedure +procedure efrac(integer num, denom) + string fraction = sprintf("%d/%d",{num,denom}), + prefix = "" + if num>=denom then + integer whole = floor(num/denom) + num -= whole*denom + prefix = sprintf("[%d] + ",whole) + end if + string e = join(egyptian(num, denom)," + ") + printf(1,"%s -> %s%s\n",{fraction,prefix,e}) +end procedure - efrac(43,48) - efrac(5,121) - efrac(2014,59) +efrac(43,48) +efrac(5,121) +efrac(2014,59) - integer maxt = 0, - maxd = 0 - string maxts = "", - maxds = "", - maxda = "" +integer maxt = 0, + maxd = 0 +string maxts = "", + maxds = "", + maxda = "" - for r=98 to 998 by 900 do -- (iterates just twice!) - sequence sieve = repeat(repeat(false,r+1),r) -- to eliminate duplicates - for n=1 to r do - for d=n+1 to r+1 do - if sieve[n][d]=false then - string term = sprintf("%d/%d",{n,d}) - sequence terms = egyptian(n,d) - integer nterms = length(terms) - if nterms>maxt then - maxt = nterms - maxts = term - elsif nterms=maxt then - maxts &= ", " & term - end if - integer mlen = length(terms[$])-2 - if mlen>maxd then - maxd = mlen - maxds = term - maxda = terms[$] - elsif mlen=maxd then - maxds &= ", " & term - end if - if n<r/2 then - for k=2 to 9999 do - if d*k > r+1 then exit end if - sieve[n*k][d*k] = true - end for - end if - end if - end for - end for - printf(1,"\nfor proper fractions with 1 to %d digits\n",{length(sprint(r))}) - printf(1,"Largest number of terms is %d for %s\n",{maxt,maxts}) - maxda = maxda[3..$] -- (strip the "1/") - maxda[6..-6]="..." -- (show only first/last 5 digits) - printf(1,"Largest size for denominator is %d digits (%s) for %s\n",{maxd,maxda,maxds}) - end for - OpenSSL Stuffs <-- +extern BIO_new_ssl_connect +extern BIO_ctrl +extern BIO_write +extern BIO_read +extern BIO_free_all +extern TLS_client_method +extern SSL_CTX_new +extern SSL_CTX_free +extern SSL_CTX_set_verify +extern SSL_CTX_set_default_verify_paths +extern SSL_ctrl + +%define BIO_C_SET_CONNECT 100 +%define BIO_C_DO_STATE 101 +%define BIO_C_GET_SSL 110 +%define SSL_CTRL_SET_TLSHOST 55 +%define SSL_VERIFY_PEER 1 + +section .text + global xrequest + xrequest: + prolog 6*8 + %define _req_host rbp-1*8 + %define _req_pack rbp-2*8 + %define _req_buff rbp-3*8 + %define _req_ssl rbp-4*8 + %define _req_ctx rbp-5*8 + %define _req_bio rbp-6*8 + + mov rax, rdi + mov qword [_req_host], rax + mov rax, rsi + mov qword [_req_pack], rax + mov rax, rdx + mov qword [_req_buff], rax + xcall TLS_client_method + mov rdi, rax + xcall SSL_CTX_new + test rax, rax + jz __req_err_ctx + mov qword [_req_ctx], rax + mov rdi, qword [_req_ctx] + xcall SSL_CTX_set_default_verify_paths + test eax, eax + jz __req_err_verify + mov rdx, 0 + mov rsi, SSL_VERIFY_PEER + mov rdi, qword [_req_ctx] + xcall SSL_CTX_set_verify + ;;-->> Create Bio chain + mov rdi, qword [_req_ctx] + xcall BIO_new_ssl_connect + test rax, rax + jz __req_err_bio + mov qword [_req_bio], rax + ;;-->> Get SSL object + lea rcx, [_req_ssl] + mov rdx, 0 + mov rsi, BIO_C_GET_SSL + mov rdi, qword [_req_bio] + xcall BIO_ctrl + + ;; -->> Set the SNI hostname. + mov rdi, qword [_req_host] + xcall strdup + mov rdx, rax ; rdx now holds the copy + push rdx ; Push pointer to stack + mov rdi, rdx + mov rsi, ':' + xcall strchr + test rax, rax + jz __req_sni_set + mov byte [rax], 0 ; Null-terminate at colon + __req_sni_set: + mov rdi, qword [_req_ssl] + mov rsi, SSL_CTRL_SET_TLSHOST + mov rdx, 0 + mov rcx, [rsp] + xcall SSL_ctrl + pop rdi + xcall free + ;; -->>Set Hostname (BIO expects "host:port") + mov rdi, qword [_req_bio] + mov rsi, BIO_C_SET_CONNECT + mov rdx, 0 + mov rcx, qword [_req_host] + xcall BIO_ctrl + mov rdi, qword [_req_bio] + mov rsi, BIO_C_DO_STATE + mov rdx, 0 + mov rcx, 0 + xcall BIO_ctrl + cmp rax, 1 + jl __req_err_conn + + ;; -->> Send Request + mov rdi, qword [_req_pack] + xcall strlen + mov rdx, rax + mov rdi, qword [_req_bio] + mov rsi, qword [_req_pack] + xcall BIO_write + + ; -->> Read Response Loop + __req_read_loop: + mov rdi, qword [_req_bio] + mov rsi, qword [_req_buff] + mov rdx, 1024 + xcall BIO_read + test eax, eax + jle __req_exit + add qword [_req_buff], rax + jmp __req_read_loop + + + __req_err_bio: + mov r13, -1 + jmp __req_exit + __req_err_verify: + mov r13, -2 + jmp __req_exit + __req_err_ctx: + ;;-->> CTX Error + mov r13, -3 + jmp __req_exit + __req_err_conn: + mov r13, -4 + ;; fall through.. + __req_exit: + mov r13, rax + mov rdi, qword [_req_bio] + xcall BIO_free_all + mov rdi, qword [_req_ctx] + xcall SSL_CTX_free + mov rax, r13 + epilog 6*8 + ret + + global main + main: + prolog 4*8 + + ; request(hostname, request_str, buffer) + xlea rdi, hostname + xlea rsi, request_str + xlea rdx, buffer + call xrequest + mov rsi, rax + xlea rdi, fmt_ret + xcall printf + + ; Print the response buffer + xlea rdi, fmt_str + xlea rsi, buffer + xor rax, rax + xcall printf + xor rdi, rdi + xcall exit + prolog 4*8 ;;Never gets here but w/e. + ret + +section .data + hostname db "google.com:443", 0 + request_str db "GET / HTTP/1.1", 13, 10 + db "Host: google.com", 13, 10 + db "Connection: close", 13, 10 + db "User-Agent: TLS-TEST/0.5", 13, 10 + db 13, 10, 0 + + fmt_str db "%s", 0 + fmt_ret db "%i",10,0 + +section .bss + buffer resb 16384 diff --git a/Task/Hailstone-sequence/Ada/hailstone-sequence-1.ada b/Task/Hailstone-sequence/Ada/hailstone-sequence-1.adb similarity index 100% rename from Task/Hailstone-sequence/Ada/hailstone-sequence-1.ada rename to Task/Hailstone-sequence/Ada/hailstone-sequence-1.adb diff --git a/Task/Hailstone-sequence/Ada/hailstone-sequence-2.ada b/Task/Hailstone-sequence/Ada/hailstone-sequence-2.adb similarity index 100% rename from Task/Hailstone-sequence/Ada/hailstone-sequence-2.ada rename to Task/Hailstone-sequence/Ada/hailstone-sequence-2.adb diff --git a/Task/Hailstone-sequence/Ada/hailstone-sequence-3.ada b/Task/Hailstone-sequence/Ada/hailstone-sequence-3.adb similarity index 100% rename from Task/Hailstone-sequence/Ada/hailstone-sequence-3.ada rename to Task/Hailstone-sequence/Ada/hailstone-sequence-3.adb diff --git a/Task/Hailstone-sequence/Ada/hailstone-sequence-4.ada b/Task/Hailstone-sequence/Ada/hailstone-sequence-4.adb similarity index 100% rename from Task/Hailstone-sequence/Ada/hailstone-sequence-4.ada rename to Task/Hailstone-sequence/Ada/hailstone-sequence-4.adb diff --git a/Task/Hailstone-sequence/Arturo/hailstone-sequence.arturo b/Task/Hailstone-sequence/Arturo/hailstone-sequence.arturo index a8510e757c..1050130f7d 100644 --- a/Task/Hailstone-sequence/Arturo/hailstone-sequence.arturo +++ b/Task/Hailstone-sequence/Arturo/hailstone-sequence.arturo @@ -1,10 +1,10 @@ hailstone: function [n][ ret: @[n] while [n>1][ - if? 1 = and n 1 -> n: 1+3*n - else -> n: n/2 + switch 1 = and n 1 -> n: 1+3*n + -> n: n/2 - 'ret ++ n + append 'ret n ] ret ] diff --git a/Task/Hailstone-sequence/AutoIt/hailstone-sequence.autoit b/Task/Hailstone-sequence/AutoIt/hailstone-sequence.au3 similarity index 100% rename from Task/Hailstone-sequence/AutoIt/hailstone-sequence.autoit rename to Task/Hailstone-sequence/AutoIt/hailstone-sequence.au3 diff --git a/Task/Hailstone-sequence/Ballerina/hailstone-sequence.ballerina b/Task/Hailstone-sequence/Ballerina/hailstone-sequence.ballerina new file mode 100644 index 0000000000..775dc1646d --- /dev/null +++ b/Task/Hailstone-sequence/Ballerina/hailstone-sequence.ballerina @@ -0,0 +1,34 @@ +import ballerina/io; + +function hailstone(int m) returns int[] { + int n = m; + int[] h = [n]; + while n != 1 { + n = n % 2 == 0 ? n / 2 : 3 * n + 1; + h.push(n); + } + return h; +} + +public function main() { + int[] h = hailstone(27); + int len = h.length(); + io:println("For the Hailstone sequence starting with n = 27:"); + io:println(" Number of elements = ", len); + io:println(" First four elements = ", h.slice(0, 4)); + io:println(" Final four elements = ", h.slice(len - 4)); + + io:println("\nThe Hailstone sequence for n < 100,000 with the longest length is:"); + int longest = 0; + int longlen = 0; + foreach int n in 1...99999 { + h = hailstone(n); + len = h.length(); + if len > longlen { + longest = n; + longlen = len; + } + } + io:println(` Longest = ${longest}`); + io:println(` Length = ${longlen}`); +} diff --git a/Task/Hailstone-sequence/Binary-Lambda-Calculus/hailstone-sequence.blc b/Task/Hailstone-sequence/Binary-Lambda-Calculus/hailstone-sequence.blc new file mode 100644 index 0000000000..85e3c77b13 --- /dev/null +++ b/Task/Hailstone-sequence/Binary-Lambda-Calculus/hailstone-sequence.blc @@ -0,0 +1,40 @@ +(let ((div2 (lambda (n) + (n (lambda (x) + (x (lambda (so-far odd?) + (odd? + ;; lambda (p) here and after is inlined cons + (lambda (p) + (p + ;; Inlined successor + (lambda (f x) + (f (so-far f x))) + nil)) + ;; cons so-far t + (lambda (p) (p so-far t)))))) + (lambda (p) (p 0 nil))))) + (fixpoint-combinator + #+nil + (lambda (g) + (let ((inner (lambda (x) (g (x x))))) + (inner inner))) + (lambda (f) + (let ((inner (lambda (x) + (f (lambda (y) + (x x y)))))) + (inner inner)))) + (hailstone (fixpoint-combinator + (lambda (recur n) + ((div2 n) + (lambda (half n-odd?) + (half + (lambda (x) + ;; lambda (p) is inlined cons + (lambda (p) + (p n (recur (n-odd? + (lambda (f x) + ;; (succ (mult 3 n)) + (f (3 (n f) x))) + half))))) + ;; lambda (p) is inlined cons + (lambda (p) (p 1 nil))))))))) + hailstone) diff --git a/Task/Hailstone-sequence/COBOL/hailstone-sequence.cobol b/Task/Hailstone-sequence/COBOL/hailstone-sequence.cob similarity index 100% rename from Task/Hailstone-sequence/COBOL/hailstone-sequence.cobol rename to Task/Hailstone-sequence/COBOL/hailstone-sequence.cob diff --git a/Task/Hailstone-sequence/Common-Lisp/hailstone-sequence.lisp b/Task/Hailstone-sequence/Common-Lisp/hailstone-sequence.lisp index 88bd0f3f1f..c113be9365 100644 --- a/Task/Hailstone-sequence/Common-Lisp/hailstone-sequence.lisp +++ b/Task/Hailstone-sequence/Common-Lisp/hailstone-sequence.lisp @@ -3,7 +3,7 @@ ((evenp n) (cons n (hailstone (/ n 2)))) (t (cons n (hailstone (+ (* 3 n) 1)))))) -(defun longest (n) +(defun longest-hailstone (n) (let ((k 0) (l 0)) (loop for i from 1 below n do (let ((len (length (hailstone i)))) diff --git a/Task/Hailstone-sequence/Crystal/hailstone-sequence.crystal b/Task/Hailstone-sequence/Crystal/hailstone-sequence.cr similarity index 100% rename from Task/Hailstone-sequence/Crystal/hailstone-sequence.crystal rename to Task/Hailstone-sequence/Crystal/hailstone-sequence.cr diff --git a/Task/Hailstone-sequence/Delphi/hailstone-sequence-1.delphi b/Task/Hailstone-sequence/Delphi/hailstone-sequence-1.pas similarity index 100% rename from Task/Hailstone-sequence/Delphi/hailstone-sequence-1.delphi rename to Task/Hailstone-sequence/Delphi/hailstone-sequence-1.pas diff --git a/Task/Hailstone-sequence/Delphi/hailstone-sequence-2.delphi b/Task/Hailstone-sequence/Delphi/hailstone-sequence-2.pas similarity index 100% rename from Task/Hailstone-sequence/Delphi/hailstone-sequence-2.delphi rename to Task/Hailstone-sequence/Delphi/hailstone-sequence-2.pas diff --git a/Task/Hailstone-sequence/DuckDB/hailstone-sequence.duckdb b/Task/Hailstone-sequence/DuckDB/hailstone-sequence.duckdb new file mode 100644 index 0000000000..d1d48d9211 --- /dev/null +++ b/Task/Hailstone-sequence/DuckDB/hailstone-sequence.duckdb @@ -0,0 +1,27 @@ +# Generate the hailstone sequence without an index +create or replace function hailstone(start) as table ( + with recursive cte as ( + select start as n + union all + select if( n % 2 = 0, n // 2, 3 * n + 1) as n + from cte + where n != 1 + ) from cte +); + +# The length of the hailstone sequence of nn using count() +create or replace function hailstone_length(nn) as ( + select count() as n from hailstone(nn) +); + +# Return a tuple giving the seed and the hailstone sequence length +create or replace function hailstone_max_of_lengths(mx) as ( + select max_by( (n,hailstone_length(n)), hailstone_length(n)) + from range(1,mx+1) _(n) +); + +# Table of lengths (e.g. for use with histogram()) +create or replace function hailstone_lengths(mx) as table ( + select hailstone_length(n) as length + from range(1,mx+1) _(n) +); diff --git a/Task/Hailstone-sequence/EMal/hailstone-sequence.emal b/Task/Hailstone-sequence/EMal/hailstone-sequence.emal index 535c4f65df..88e9413884 100644 --- a/Task/Hailstone-sequence/EMal/hailstone-sequence.emal +++ b/Task/Hailstone-sequence/EMal/hailstone-sequence.emal @@ -1,26 +1,26 @@ -fun hailstone = List by int n - List h = int[n] - while n != 1 - n = when((n % 2 == 0), n / 2, 3 * n + 1) +fun hailstone ← List by int n + List h ← int[n] + while n ≠ 1 + n ← when((n % 2 æ 0), n / 2, 3 * n + 1) h.append(n) end return h end -int NUMBER = 27 -int LESS_THAN = 100000 -List sequence = hailstone(NUMBER) +int NUMBER ← 27 +int LESS_THAN ← 100000 +List sequence ← hailstone(NUMBER) writeLine("The hailstone sequence for the number " + NUMBER + " has " + sequence.length + " elements") writeLine("starting with " + sequence.extractStart(4).join(", ") + " and ending with " + sequence.extractEnd(4).join(", ") + ".") -int number = 0 -sequence = int[] -for int i = 1; i < LESS_THAN; ++i - List current = hailstone(i) +int number ← 0 +sequence ← int[] +for int i ← 1; i < LESS_THAN; ++i + List current ← hailstone(i) if current.length > sequence.length - sequence = current - number = i + sequence ← current + number ← i end end writeLine("The number less than 100000 with longest hailstone sequence is " + diff --git a/Task/Hailstone-sequence/EasyLang/hailstone-sequence.easy b/Task/Hailstone-sequence/EasyLang/hailstone-sequence.easy index a5606e817c..ff201550a8 100644 --- a/Task/Hailstone-sequence/EasyLang/hailstone-sequence.easy +++ b/Task/Hailstone-sequence/EasyLang/hailstone-sequence.easy @@ -1,4 +1,4 @@ -proc hailstone n . list[] . +proc hailstone n &list[] . list[] = [ ] while n <> 1 list[] &= n @@ -12,19 +12,15 @@ proc hailstone n . list[] . . hailstone 27 l[] write "27 has length " & len l[] & " with " -for i to 4 - write l[i] & " " -. +for i to 4 : write l[i] & " " write "... " -for i = len l[] - 3 to len l[] - write l[i] & " " -. +for i = len l[] - 3 to len l[] : write l[i] & " " print "" for i = 1 to 100000 hailstone i l[] if len l[] >= max_iter max_i = i max_iter = len l[] - end -end + . +. print max_i & " has length " & max_iter diff --git a/Task/Hailstone-sequence/Elena/hailstone-sequence.elena b/Task/Hailstone-sequence/Elena/hailstone-sequence.elena index 65dd556d5d..6933f48a7b 100644 --- a/Task/Hailstone-sequence/Elena/hailstone-sequence.elena +++ b/Task/Hailstone-sequence/Elena/hailstone-sequence.elena @@ -30,7 +30,7 @@ Hailstone(int n,Map lengths) } } -public program() +public Program() { int longestChain := 0; int longestNumber := 0; diff --git a/Task/Hailstone-sequence/Elixir/hailstone-sequence.elixir b/Task/Hailstone-sequence/Elixir/hailstone-sequence.ex similarity index 100% rename from Task/Hailstone-sequence/Elixir/hailstone-sequence.elixir rename to Task/Hailstone-sequence/Elixir/hailstone-sequence.ex diff --git a/Task/Hailstone-sequence/Euphoria/hailstone-sequence.euphoria b/Task/Hailstone-sequence/Euphoria/hailstone-sequence.eu similarity index 100% rename from Task/Hailstone-sequence/Euphoria/hailstone-sequence.euphoria rename to Task/Hailstone-sequence/Euphoria/hailstone-sequence.eu diff --git a/Task/Hailstone-sequence/Jq/hailstone-sequence-2.jq b/Task/Hailstone-sequence/Jq/hailstone-sequence-2.jq index c6b0fe55d9..06fd8b01e9 100644 --- a/Task/Hailstone-sequence/Jq/hailstone-sequence-2.jq +++ b/Task/Hailstone-sequence/Jq/hailstone-sequence-2.jq @@ -3,5 +3,5 @@ "The first four numbers: \($h[0:4])", "The last four numbers: \($h|.[length-4:length])", "", - max_hailstone(100000) as $m - | "Maximum length for n|hailstone for n in 1..100000 is \($m[1]) (n == \($m[0]))" + (max_hailstone(100000) as $m + | "Maximum length for n|hailstone for n in 1..100000 is \($m[1]) (n == \($m[0]))") diff --git a/Task/Hailstone-sequence/Julia/hailstone-sequence-1.julia b/Task/Hailstone-sequence/Julia/hailstone-sequence-1.jl similarity index 100% rename from Task/Hailstone-sequence/Julia/hailstone-sequence-1.julia rename to Task/Hailstone-sequence/Julia/hailstone-sequence-1.jl diff --git a/Task/Hailstone-sequence/Julia/hailstone-sequence-2.julia b/Task/Hailstone-sequence/Julia/hailstone-sequence-2.jl similarity index 100% rename from Task/Hailstone-sequence/Julia/hailstone-sequence-2.julia rename to Task/Hailstone-sequence/Julia/hailstone-sequence-2.jl diff --git a/Task/Hailstone-sequence/Julia/hailstone-sequence-3.julia b/Task/Hailstone-sequence/Julia/hailstone-sequence-3.jl similarity index 100% rename from Task/Hailstone-sequence/Julia/hailstone-sequence-3.julia rename to Task/Hailstone-sequence/Julia/hailstone-sequence-3.jl diff --git a/Task/Hailstone-sequence/Kotlin/hailstone-sequence-1.kotlin b/Task/Hailstone-sequence/Kotlin/hailstone-sequence-1.kts similarity index 100% rename from Task/Hailstone-sequence/Kotlin/hailstone-sequence-1.kotlin rename to Task/Hailstone-sequence/Kotlin/hailstone-sequence-1.kts diff --git a/Task/Hailstone-sequence/Kotlin/hailstone-sequence-2.kotlin b/Task/Hailstone-sequence/Kotlin/hailstone-sequence-2.kts similarity index 100% rename from Task/Hailstone-sequence/Kotlin/hailstone-sequence-2.kotlin rename to Task/Hailstone-sequence/Kotlin/hailstone-sequence-2.kts diff --git a/Task/Hailstone-sequence/M2000-Interpreter/hailstone-sequence.m2000 b/Task/Hailstone-sequence/M2000-Interpreter/hailstone-sequence.m2000 index 36d886dcb9..6cdcbfba59 100644 --- a/Task/Hailstone-sequence/M2000-Interpreter/hailstone-sequence.m2000 +++ b/Task/Hailstone-sequence/M2000-Interpreter/hailstone-sequence.m2000 @@ -7,7 +7,7 @@ Module hailstone.Task { n*=3 : n++: val=n } } - Count=Lambda (n) ->{ + count=Lambda (n as long) ->{ m=lambda n ->{ if n=1 then =false: exit =true :if n mod 2=0 then n/=2 :exit diff --git a/Task/Hailstone-sequence/Miranda/hailstone-sequence.miranda b/Task/Hailstone-sequence/Miranda/hailstone-sequence.miranda new file mode 100644 index 0000000000..9b7381cd1c --- /dev/null +++ b/Task/Hailstone-sequence/Miranda/hailstone-sequence.miranda @@ -0,0 +1,22 @@ +main :: [sys_message] +main = [Stdout h27m, Stdout biggestm] + where h27 = hailstone 27 + h27n = #h27 + h27f = take 4 h27 + h27l = drop (h27n - 4) h27 + h27m = "The hailstone sequence for 27 has " ++ + show h27n ++ " elements starting with " ++ + show h27f ++ " and ending with " ++ + show h27l ++ "\n" + + range = [1..100000] + biggest = max [#hailstone n | n<-range] + nbiggest = hd [n | n<-range; #hailstone n = biggest] + biggestm = "The number with the longest Hailstone " ++ + "sequence < 100.000 is " ++ show nbiggest ++ + " with length " ++ show biggest ++ "\n" + +hailstone :: num->[num] +hailstone = (++[1]) . takewhile (>1) . iterate step + where step n = (3 * n) + 1, if n mod 2 = 1 + = n div 2, otherwise diff --git a/Task/Hailstone-sequence/OCaml/hailstone-sequence.ocaml b/Task/Hailstone-sequence/OCaml/hailstone-sequence.ml similarity index 100% rename from Task/Hailstone-sequence/OCaml/hailstone-sequence.ocaml rename to Task/Hailstone-sequence/OCaml/hailstone-sequence.ml diff --git a/Task/Hailstone-sequence/Odin/hailstone-sequence.odin b/Task/Hailstone-sequence/Odin/hailstone-sequence.odin new file mode 100644 index 0000000000..dbe6f83782 --- /dev/null +++ b/Task/Hailstone-sequence/Odin/hailstone-sequence.odin @@ -0,0 +1,65 @@ +package main + +import "core:fmt" + +collatz :: proc(array:^[dynamic]int,n:int){ + i:=1 + n:=n + for n!=1{ + + if (n%2==0){ + n=n/2 + append(&array^,n) + } + else{ + n=3*n+1 + append(&array^,n) + } + + } +} + +main :: proc() { + n:=27 + + max:=0 + max_length:=0 + + dummy:[dynamic]int + defer delete(dummy) + append(&dummy,n) + collatz(&dummy,n) + + + fmt.println("the first four of sequence for 27: ") + for jj:=0;jj<4;jj+=1{ + fmt.println(dummy[jj]) + } + fmt.println("the last four of sequence for 27: ") + for jj:=0;jj<4;jj+=1{ + fmt.println(dummy[len(dummy)-4+jj]) + } + fmt.println("length of sequence for 27") + fmt.println(len(dummy)) + + + for (len(dummy)>0){ + pop(&dummy) + } + + for ii:=1;ii<100000;ii+=1{ + append(&dummy,ii) + collatz(&dummy,ii) + if(len(dummy)>max_length){ + max = ii + max_length=len(dummy) + } + for (len(dummy)>0){ + pop(&dummy) + } + } + fmt.println("Max number: ") + fmt.println(max) + fmt.println("Max length: ") + fmt.println(max_length) +} diff --git a/Task/Hailstone-sequence/PascalABC.NET/hailstone-sequence.pas b/Task/Hailstone-sequence/PascalABC.NET/hailstone-sequence.pas new file mode 100644 index 0000000000..d19f3dd6db --- /dev/null +++ b/Task/Hailstone-sequence/PascalABC.NET/hailstone-sequence.pas @@ -0,0 +1,23 @@ +function hailstone(n: Integer): sequence of integer; +begin + result := seq(n); + while n > 1 do + begin + n := n.IsEven ? n div 2 : 3 * n + 1; + result := result + seq(n); + end; +end; + +begin + var a := hailstone(27); + println(a.Count, a.Take(4), a.TakeLast(4)); + var max := 0; + var maxi := 0; + for var i := 1 to 100_000 do + if hailstone(i).Count > max then + begin + max := hailstone(i).Count; + maxi := i; + end; + println(maxi, max); +end. diff --git a/Task/Hailstone-sequence/Pluto/hailstone-sequence.pluto b/Task/Hailstone-sequence/Pluto/hailstone-sequence.pluto new file mode 100644 index 0000000000..0e55f4d7b9 --- /dev/null +++ b/Task/Hailstone-sequence/Pluto/hailstone-sequence.pluto @@ -0,0 +1,26 @@ +function hailstone(n, p=true) + local len = 1 + + while n > 1 do + ++len + if p do io.write(n,'\t') end + n = (n%2==0)?n//2:3*n+1 + end + + if p do print(1) end + return len +end + +hailstone(27) +print("------") + +local max = 1 +local len = 1 +for i = 2,99999 do + local t = hailstone(i,false) + if t > len then + max = i + len = t + end +end +print(max, len) diff --git a/Task/Hailstone-sequence/PowerShell/hailstone-sequence.psh b/Task/Hailstone-sequence/PowerShell/hailstone-sequence.ps1 similarity index 100% rename from Task/Hailstone-sequence/PowerShell/hailstone-sequence.psh rename to Task/Hailstone-sequence/PowerShell/hailstone-sequence.ps1 diff --git a/Task/Hailstone-sequence/REBOL/hailstone-sequence.rebol b/Task/Hailstone-sequence/Rebol/hailstone-sequence.rebol similarity index 100% rename from Task/Hailstone-sequence/REBOL/hailstone-sequence.rebol rename to Task/Hailstone-sequence/Rebol/hailstone-sequence.rebol diff --git a/Task/Hailstone-sequence/Rust/hailstone-sequence.rust b/Task/Hailstone-sequence/Rust/hailstone-sequence.rs similarity index 100% rename from Task/Hailstone-sequence/Rust/hailstone-sequence.rust rename to Task/Hailstone-sequence/Rust/hailstone-sequence.rs diff --git a/Task/Hailstone-sequence/Scheme/hailstone-sequence.scm b/Task/Hailstone-sequence/Scheme/hailstone-sequence.scm new file mode 100644 index 0000000000..5219a0c4e9 --- /dev/null +++ b/Task/Hailstone-sequence/Scheme/hailstone-sequence.scm @@ -0,0 +1,36 @@ +(define (collatz n) + (if (= n 1) + (list 1) + (cons n + (collatz (if (even? n) (/ n 2) (+ 1 (* 3 n))))))) + +(define (collatz-length n) + (let aux ((n n) (r 1)) + (if (= n 1) + r + (aux (if (even? n) (/ n 2) (+ 1 (* 3 n))) + (+ r 1))))) + +(define (collatz-max a b) + (let aux ((i a) (j 0) (k 0)) + (if (> i b) + (list j k) + (let ((h (collatz-length i))) + (if (> h k) + (aux (+ i 1) i h) + (aux (+ i 1) j k)))))) + +(collatz 27) +; (27 82 41 124 62 31 94 47 142 71 214 107 322 161 484 242 121 364 182 +; 91 274 137 412 206 103 310 155 466 233 700 350 175 526 263 790 395 +; 1186 593 1780 890 445 1336 668 334 167 502 251 754 377 1132 566 283 +; 850 425 1276 638 319 958 479 1438 719 2158 1079 3238 1619 4858 2429 +; 7288 3644 1822 911 2734 1367 4102 2051 6154 3077 9232 4616 2308 1154 +; 577 1732 866 433 1300 650 325 976 488 244 122 61 184 92 46 23 70 35 +; 106 53 160 80 40 20 10 5 16 8 4 2 1) + +(collatz-length 27) +; 112 + +(collatz-max 1 100000) +; (77031 351) diff --git a/Task/Hailstone-sequence/Scheme/hailstone-sequence.ss b/Task/Hailstone-sequence/Scheme/hailstone-sequence.ss deleted file mode 100644 index b0311a38ee..0000000000 --- a/Task/Hailstone-sequence/Scheme/hailstone-sequence.ss +++ /dev/null @@ -1,28 +0,0 @@ -(define (collatz n) -(if (= n 1) '(1) -(cons n (collatz (if (even? n) (/ n 2) (+ 1 (* 3 n))))))) - -(define (collatz-length n) -(let aux ((n n) (r 1)) (if (= n 1) r -(aux (if (even? n) (/ n 2) (+ 1 (* 3 n))) (+ r 1))))) - -(define (collatz-max a b) -(let aux ((i a) (j 0) (k 0)) -(if (> i b) (list j k) -(let ((h (collatz-length i))) -(if (> h k) (aux (+ i 1) i h) (aux (+ i 1) j k)))))) - -(collatz 27) -; (27 82 41 124 62 31 94 47 142 71 214 107 322 161 484 242 121 364 182 -; 91 274 137 412 206 103 310 155 466 233 700 350 175 526 263 790 395 -; 1186 593 1780 890 445 1336 668 334 167 502 251 754 377 1132 566 283 -; 850 425 1276 638 319 958 479 1438 719 2158 1079 3238 1619 4858 2429 -; 7288 3644 1822 911 2734 1367 4102 2051 6154 3077 9232 4616 2308 1154 -; 577 1732 866 433 1300 650 325 976 488 244 122 61 184 92 46 23 70 35 -; 106 53 160 80 40 20 10 5 16 8 4 2 1) - -(collatz-length 27) -; 112 - -(collatz-max 1 100000) -; (77031 351) diff --git a/Task/Hailstone-sequence/Uiua/hailstone-sequence.uiua b/Task/Hailstone-sequence/Uiua/hailstone-sequence.uiua new file mode 100644 index 0000000000..81cdf542a0 --- /dev/null +++ b/Task/Hailstone-sequence/Uiua/hailstone-sequence.uiua @@ -0,0 +1,7 @@ +Next ← ⨬(÷2|+1×3)⊸◿2 +Sequence ← ˜⊂1⊢[⍢⊸Next≠₁] + +⊃(↙4|↙¯4) Sequence 27 +# Calculate and cache lengths (export UIUA_RECURSION_LIMIT=3000 first) +Length ← |1 memo(⨬(+1Length Next|∘)⊸=₁) +⊸Length⊢⊏⍖⊸⍚Length+1⇡99999 diff --git a/Task/Hailstone-sequence/Ursalang/hailstone-sequence.ursa b/Task/Hailstone-sequence/Ursalang/hailstone-sequence.ursa new file mode 100644 index 0000000000..ecc665c418 --- /dev/null +++ b/Task/Hailstone-sequence/Ursalang/hailstone-sequence.ursa @@ -0,0 +1,33 @@ +let hailstone = fn(n_) { + var n = n_ + let steps = [n] + loop { + if n < 2 { break steps } + n := (if n % 2 == 0 { n / 2 } else { n * 3 + 1 }) + steps.push(n) + } +} + +let twentySeven = hailstone(27) +print("The Hailstone sequence for 27 starts with:") +print(twentySeven.slice(0, 4)) +print("and ends with:") +print(twentySeven.slice(-4)) +print("and its length is:") +print(twentySeven.len()) + +print("Checking sequences up to 100,000") +var longest = 0 +var longestLen = 0 +for i in range(100000) { + let len = hailstone(i).len() + if len > longestLen { + longest := i + longestLen := len + } + if i % 10000 == 0 {print(i)} +} +print("The longest sequence under 100,000 is for:") +print(longest) +print("and has length:") +print(longestLen) diff --git a/Task/Hailstone-sequence/V-(Vlang)/hailstone-sequence.v b/Task/Hailstone-sequence/V-(Vlang)/hailstone-sequence.v index 665f9dc8b1..2f1d091903 100644 --- a/Task/Hailstone-sequence/V-(Vlang)/hailstone-sequence.v +++ b/Task/Hailstone-sequence/V-(Vlang)/hailstone-sequence.v @@ -2,7 +2,7 @@ // 2nd arg is a slice to recycle, to reduce garbage. fn hs(nn int, recycle []int) []int { mut n := nn - mut s := recycle[..0] + mut s := recycle[..0].clone() s << n for n > 1 { if n&1 == 0 { diff --git a/Task/Hailstone-sequence/VBScript/hailstone-sequence.vb b/Task/Hailstone-sequence/VBScript/hailstone-sequence.vbs similarity index 100% rename from Task/Hailstone-sequence/VBScript/hailstone-sequence.vb rename to Task/Hailstone-sequence/VBScript/hailstone-sequence.vbs diff --git a/Task/Halt-and-catch-fire/8086-Assembly/halt-and-catch-fire.8086 b/Task/Halt-and-catch-fire/8086-Assembly/halt-and-catch-fire-1.8086 similarity index 100% rename from Task/Halt-and-catch-fire/8086-Assembly/halt-and-catch-fire.8086 rename to Task/Halt-and-catch-fire/8086-Assembly/halt-and-catch-fire-1.8086 diff --git a/Task/Halt-and-catch-fire/8086-Assembly/halt-and-catch-fire-2.8086 b/Task/Halt-and-catch-fire/8086-Assembly/halt-and-catch-fire-2.8086 new file mode 100644 index 0000000000..fe4a93e86e --- /dev/null +++ b/Task/Halt-and-catch-fire/8086-Assembly/halt-and-catch-fire-2.8086 @@ -0,0 +1 @@ +jmp $ diff --git a/Task/Halt-and-catch-fire/AArch64-Assembly/halt-and-catch-fire.aarch64 b/Task/Halt-and-catch-fire/AArch64-Assembly/halt-and-catch-fire.aarch64 new file mode 100644 index 0000000000..b35e4e4e7f --- /dev/null +++ b/Task/Halt-and-catch-fire/AArch64-Assembly/halt-and-catch-fire.aarch64 @@ -0,0 +1,50 @@ +/* ARM assembly AARCH64 Raspberry PI 3B */ +/* program craharm64.s */ + +/*******************************************/ +/* Constantes */ +/*******************************************/ +/* for this file see task include a file in language AArch64 assembly*/ +.include "../includeConstantesARM64.inc" + +/*******************************************/ +/* Macros */ +/*******************************************/ +//.include "../../ficmacros64.inc" // for developer debugging + +/*********************************/ +/* Initialized data */ +/*********************************/ +.data +szMessDebutPgm: .asciz "Program 64 bits start. \n" +szMessFinOK: .asciz "Program normal end. \n" + +/*********************************/ +/* UnInitialized data */ +/*********************************/ +.bss +/*********************************/ +/* code section */ +/*********************************/ +.text +.global main +main: + ldr x0,qAdrszMessDebutPgm + bl affichageMess // start message + mov x0,#0 + ldr x1,[x0] // load value at address zero + + + ldr x0,qAdrszMessFinOK + bl affichageMess + + mov x8,EXIT + svc #0 // system call +qAdrszMessDebutPgm: .quad szMessDebutPgm +qAdrszMessFinOK: .quad szMessFinOK + +/***************************************************/ +/* ROUTINES INCLUDE */ +/***************************************************/ +/* for this file see task include a file in language AArch64 assembly*/ +.include "../includeARM64.inc" diff --git a/Task/Halt-and-catch-fire/ARM-Assembly/halt-and-catch-fire.arm b/Task/Halt-and-catch-fire/ARM-Assembly/halt-and-catch-fire.arm new file mode 100644 index 0000000000..b2d0b3b307 --- /dev/null +++ b/Task/Halt-and-catch-fire/ARM-Assembly/halt-and-catch-fire.arm @@ -0,0 +1,55 @@ +/* ARM assembly Raspberry PI */ +/* program craharm.s */ + +/* REMARK 1 : this program use routines in a include file + see task Include a file language arm assembly + for the routine affichageMess conversion10 + see at end of this program the instruction include */ + +/*******************************************/ +/* Constantes */ +/*******************************************/ +.include "../constantes.inc" + +/*******************************************/ +/* Macros */ +/*******************************************/ +//.include "../../ficmacros32.inc" @ for developer debugging + +/*********************************/ +/* Initialized data */ +/*********************************/ +.data +szMessDebutPgm: .asciz "Program 32 bits start. \n" +szMessFinOK: .asciz "Program normal end. \n" + + +/*********************************/ +/* UnInitialized data */ +/*********************************/ +.bss +/*********************************/ +/* code section */ +/*********************************/ +.text +.global main +main: + ldr r0,iAdrszMessDebutPgm + bl affichageMess @ start message + mov r0,#0 + ldr r1,[r0] @ load value at address zero + + + ldr r0,iAdrszMessFinOK + bl affichageMess + + mov r7,#EXIT @ program end + svc #0 @ system call +iAdrszMessDebutPgm: .int szMessDebutPgm +iAdrszMessFinOK: .int szMessFinOK + + +/***************************************************/ +/* ROUTINES INCLUDE */ +/***************************************************/ +.include "../affichage.inc" diff --git a/Task/Halt-and-catch-fire/Ada/halt-and-catch-fire.ada b/Task/Halt-and-catch-fire/Ada/halt-and-catch-fire.adb similarity index 100% rename from Task/Halt-and-catch-fire/Ada/halt-and-catch-fire.ada rename to Task/Halt-and-catch-fire/Ada/halt-and-catch-fire.adb diff --git a/Task/Halt-and-catch-fire/Crystal/halt-and-catch-fire.crystal b/Task/Halt-and-catch-fire/Crystal/halt-and-catch-fire.cr similarity index 100% rename from Task/Halt-and-catch-fire/Crystal/halt-and-catch-fire.crystal rename to Task/Halt-and-catch-fire/Crystal/halt-and-catch-fire.cr diff --git a/Task/Halt-and-catch-fire/Delphi/halt-and-catch-fire.delphi b/Task/Halt-and-catch-fire/Delphi/halt-and-catch-fire.pas similarity index 100% rename from Task/Halt-and-catch-fire/Delphi/halt-and-catch-fire.delphi rename to Task/Halt-and-catch-fire/Delphi/halt-and-catch-fire.pas diff --git a/Task/Halt-and-catch-fire/EMal/halt-and-catch-fire.emal b/Task/Halt-and-catch-fire/EMal/halt-and-catch-fire.emal new file mode 100644 index 0000000000..681461a281 --- /dev/null +++ b/Task/Halt-and-catch-fire/EMal/halt-and-catch-fire.emal @@ -0,0 +1 @@ +error(256, "Internal Corruption") diff --git a/Task/Halt-and-catch-fire/EasyLang/halt-and-catch-fire.easy b/Task/Halt-and-catch-fire/EasyLang/halt-and-catch-fire.easy new file mode 100644 index 0000000000..cb387a3101 --- /dev/null +++ b/Task/Halt-and-catch-fire/EasyLang/halt-and-catch-fire.easy @@ -0,0 +1,2 @@ +a[] = [ ] +print a[1] diff --git a/Task/Halt-and-catch-fire/FutureBasic/halt-and-catch-fire.basic b/Task/Halt-and-catch-fire/FutureBasic/halt-and-catch-fire.basic new file mode 100644 index 0000000000..858825d80b --- /dev/null +++ b/Task/Halt-and-catch-fire/FutureBasic/halt-and-catch-fire.basic @@ -0,0 +1 @@ +~ 0,0 diff --git a/Task/Halt-and-catch-fire/Icon/halt-and-catch-fire.icon b/Task/Halt-and-catch-fire/Icon/halt-and-catch-fire.icon new file mode 100644 index 0000000000..a90590d6f8 --- /dev/null +++ b/Task/Halt-and-catch-fire/Icon/halt-and-catch-fire.icon @@ -0,0 +1,3 @@ +procedure main() + 5/0 +end diff --git a/Task/Halt-and-catch-fire/Java/halt-and-catch-fire.java b/Task/Halt-and-catch-fire/Java/halt-and-catch-fire.java index c0b69d67b3..436cffff07 100644 --- a/Task/Halt-and-catch-fire/Java/halt-and-catch-fire.java +++ b/Task/Halt-and-catch-fire/Java/halt-and-catch-fire.java @@ -1,11 +1,11 @@ public final class HaltAndCatchFire { - public static void main(String[] aArgs) { - // Any one of the lines below, when uncommented, will cause a program halt. - -// throw new AssertionError("Stop now!"); -// System.out.println(0/0); -// Runtime.getRuntime().exit(1); - } + public static void main(String[] aArgs) { + // Any one of the lines below, when uncommented, will cause a program halt. + +// throw new AssertionError("Stop now!"); +// System.out.println(0/0); +// Runtime.getRuntime().exit(1); + } } diff --git a/Task/Halt-and-catch-fire/JavaScript/halt-and-catch-fire.js b/Task/Halt-and-catch-fire/JavaScript/halt-and-catch-fire.js new file mode 100644 index 0000000000..c3ab4d8f76 --- /dev/null +++ b/Task/Halt-and-catch-fire/JavaScript/halt-and-catch-fire.js @@ -0,0 +1,3 @@ +f=()=>f();f(); +/* This also does the same thing, but is harder to read */ +(f=()=>f())(); diff --git a/Task/Halt-and-catch-fire/Julia/halt-and-catch-fire-1.julia b/Task/Halt-and-catch-fire/Julia/halt-and-catch-fire-1.jl similarity index 100% rename from Task/Halt-and-catch-fire/Julia/halt-and-catch-fire-1.julia rename to Task/Halt-and-catch-fire/Julia/halt-and-catch-fire-1.jl diff --git a/Task/Halt-and-catch-fire/Julia/halt-and-catch-fire-2.julia b/Task/Halt-and-catch-fire/Julia/halt-and-catch-fire-2.jl similarity index 100% rename from Task/Halt-and-catch-fire/Julia/halt-and-catch-fire-2.julia rename to Task/Halt-and-catch-fire/Julia/halt-and-catch-fire-2.jl diff --git a/Task/Halt-and-catch-fire/Microsoft-Small-Basic/halt-and-catch-fire.basic b/Task/Halt-and-catch-fire/Microsoft-Small-Basic/halt-and-catch-fire.basic new file mode 100644 index 0000000000..22d7fa590a --- /dev/null +++ b/Task/Halt-and-catch-fire/Microsoft-Small-Basic/halt-and-catch-fire.basic @@ -0,0 +1 @@ +a = 0 / 0 diff --git a/Task/Halt-and-catch-fire/PascalABC.NET/halt-and-catch-fire.pas b/Task/Halt-and-catch-fire/PascalABC.NET/halt-and-catch-fire.pas new file mode 100644 index 0000000000..ac79a4cfa2 --- /dev/null +++ b/Task/Halt-and-catch-fire/PascalABC.NET/halt-and-catch-fire.pas @@ -0,0 +1 @@ +## raise new Exception(''); diff --git a/Task/Halt-and-catch-fire/Pluto/halt-and-catch-fire.pluto b/Task/Halt-and-catch-fire/Pluto/halt-and-catch-fire.pluto new file mode 100644 index 0000000000..13a2c75adb --- /dev/null +++ b/Task/Halt-and-catch-fire/Pluto/halt-and-catch-fire.pluto @@ -0,0 +1 @@ +print(0 // 0) diff --git a/Task/Halt-and-catch-fire/R/halt-and-catch-fire-1.r b/Task/Halt-and-catch-fire/R/halt-and-catch-fire-1.r new file mode 100644 index 0000000000..39a97b302c --- /dev/null +++ b/Task/Halt-and-catch-fire/R/halt-and-catch-fire-1.r @@ -0,0 +1 @@ +stop() diff --git a/Task/Halt-and-catch-fire/R/halt-and-catch-fire-2.r b/Task/Halt-and-catch-fire/R/halt-and-catch-fire-2.r new file mode 100644 index 0000000000..1e5b3ea0c8 --- /dev/null +++ b/Task/Halt-and-catch-fire/R/halt-and-catch-fire-2.r @@ -0,0 +1 @@ +array()[,] diff --git a/Task/Halt-and-catch-fire/Rebol/halt-and-catch-fire.rebol b/Task/Halt-and-catch-fire/Rebol/halt-and-catch-fire.rebol new file mode 100644 index 0000000000..2350d4fe2a --- /dev/null +++ b/Task/Halt-and-catch-fire/Rebol/halt-and-catch-fire.rebol @@ -0,0 +1,5 @@ +halt ;; Stops evaluation and returns to the input prompt. + ;; or +quit ;; Stops evaluation and exits the interpreter. + ;; or +quit/return 1 ;; with some status code diff --git a/Task/Halt-and-catch-fire/Rust/halt-and-catch-fire.rust b/Task/Halt-and-catch-fire/Rust/halt-and-catch-fire.rs similarity index 100% rename from Task/Halt-and-catch-fire/Rust/halt-and-catch-fire.rust rename to Task/Halt-and-catch-fire/Rust/halt-and-catch-fire.rs diff --git a/Task/Halt-and-catch-fire/TAV/halt-and-catch-fire.tav b/Task/Halt-and-catch-fire/TAV/halt-and-catch-fire.tav new file mode 100644 index 0000000000..beb3a1a07a --- /dev/null +++ b/Task/Halt-and-catch-fire/TAV/halt-and-catch-fire.tav @@ -0,0 +1 @@ +! ?- diff --git a/Task/Halt-and-catch-fire/Uiua/halt-and-catch-fire.uiua b/Task/Halt-and-catch-fire/Uiua/halt-and-catch-fire.uiua new file mode 100644 index 0000000000..414ff2f8ec --- /dev/null +++ b/Task/Halt-and-catch-fire/Uiua/halt-and-catch-fire.uiua @@ -0,0 +1 @@ +⍤@a 0 diff --git a/Task/Halt-and-catch-fire/Zig/halt-and-catch-fire.zig b/Task/Halt-and-catch-fire/Zig/halt-and-catch-fire.zig new file mode 100644 index 0000000000..d8b5049869 --- /dev/null +++ b/Task/Halt-and-catch-fire/Zig/halt-and-catch-fire.zig @@ -0,0 +1,3 @@ +pub fn main() void { + unreachable; +} diff --git a/Task/Hamming-numbers/Ada/hamming-numbers.ada b/Task/Hamming-numbers/Ada/hamming-numbers.adb similarity index 100% rename from Task/Hamming-numbers/Ada/hamming-numbers.ada rename to Task/Hamming-numbers/Ada/hamming-numbers.adb diff --git a/Task/Hamming-numbers/Chapel/hamming-numbers-1.chapel b/Task/Hamming-numbers/Chapel/hamming-numbers-1.chpl similarity index 100% rename from Task/Hamming-numbers/Chapel/hamming-numbers-1.chapel rename to Task/Hamming-numbers/Chapel/hamming-numbers-1.chpl diff --git a/Task/Hamming-numbers/Chapel/hamming-numbers-2.chapel b/Task/Hamming-numbers/Chapel/hamming-numbers-2.chpl similarity index 100% rename from Task/Hamming-numbers/Chapel/hamming-numbers-2.chapel rename to Task/Hamming-numbers/Chapel/hamming-numbers-2.chpl diff --git a/Task/Hamming-numbers/Chapel/hamming-numbers-3.chapel b/Task/Hamming-numbers/Chapel/hamming-numbers-3.chpl similarity index 100% rename from Task/Hamming-numbers/Chapel/hamming-numbers-3.chapel rename to Task/Hamming-numbers/Chapel/hamming-numbers-3.chpl diff --git a/Task/Hamming-numbers/Chapel/hamming-numbers-4.chapel b/Task/Hamming-numbers/Chapel/hamming-numbers-4.chpl similarity index 100% rename from Task/Hamming-numbers/Chapel/hamming-numbers-4.chapel rename to Task/Hamming-numbers/Chapel/hamming-numbers-4.chpl diff --git a/Task/Hamming-numbers/Chapel/hamming-numbers-5.chapel b/Task/Hamming-numbers/Chapel/hamming-numbers-5.chpl similarity index 100% rename from Task/Hamming-numbers/Chapel/hamming-numbers-5.chapel rename to Task/Hamming-numbers/Chapel/hamming-numbers-5.chpl diff --git a/Task/Hamming-numbers/Crystal/hamming-numbers-1.crystal b/Task/Hamming-numbers/Crystal/hamming-numbers-1.cr similarity index 100% rename from Task/Hamming-numbers/Crystal/hamming-numbers-1.crystal rename to Task/Hamming-numbers/Crystal/hamming-numbers-1.cr diff --git a/Task/Hamming-numbers/Crystal/hamming-numbers-2.crystal b/Task/Hamming-numbers/Crystal/hamming-numbers-2.cr similarity index 100% rename from Task/Hamming-numbers/Crystal/hamming-numbers-2.crystal rename to Task/Hamming-numbers/Crystal/hamming-numbers-2.cr diff --git a/Task/Hamming-numbers/Crystal/hamming-numbers-3.crystal b/Task/Hamming-numbers/Crystal/hamming-numbers-3.cr similarity index 100% rename from Task/Hamming-numbers/Crystal/hamming-numbers-3.crystal rename to Task/Hamming-numbers/Crystal/hamming-numbers-3.cr diff --git a/Task/Hamming-numbers/Crystal/hamming-numbers-4.crystal b/Task/Hamming-numbers/Crystal/hamming-numbers-4.cr similarity index 100% rename from Task/Hamming-numbers/Crystal/hamming-numbers-4.crystal rename to Task/Hamming-numbers/Crystal/hamming-numbers-4.cr diff --git a/Task/Hamming-numbers/EasyLang/hamming-numbers.easy b/Task/Hamming-numbers/EasyLang/hamming-numbers.easy new file mode 100644 index 0000000000..5f54b97603 --- /dev/null +++ b/Task/Hamming-numbers/EasyLang/hamming-numbers.easy @@ -0,0 +1,27 @@ +func hamming lim . + len h[] lim + h[1] = 1 + x2 = 2 ; x3 = 3 ; x5 = 5 + i = 1 ; j = 1 ; k = 1 + for n = 2 to lim + h[n] = lower x2 lower x3 x5 + if x2 = h[n] + i += 1 + x2 = 2 * h[i] + . + if x3 = h[n] + j += 1 + x3 = 3 * h[j] + . + if x5 = h[n] + k += 1 + x5 = 5 * h[k] + . + . + return h[lim] +. +for nr = 1 to 20 + write hamming nr & " " +. +print "" +print hamming 1691 diff --git a/Task/Hamming-numbers/Elixir/hamming-numbers.elixir b/Task/Hamming-numbers/Elixir/hamming-numbers.ex similarity index 100% rename from Task/Hamming-numbers/Elixir/hamming-numbers.elixir rename to Task/Hamming-numbers/Elixir/hamming-numbers.ex diff --git a/Task/Hamming-numbers/FutureBasic/hamming-numbers.basic b/Task/Hamming-numbers/FutureBasic/hamming-numbers.basic new file mode 100644 index 0000000000..96bab3ac63 --- /dev/null +++ b/Task/Hamming-numbers/FutureBasic/hamming-numbers.basic @@ -0,0 +1,42 @@ +include "NSLog.incl" + +NSUInteger local fn Minimum( a as NSUInteger, b as NSUInteger ) + return (a < b) ? a : b +end fn = 0 + +UInt64 local fn HammingNumberAtPosition( position as NSUInteger ) + if (position == 0) then return 0 + CFMutableArrayRef hammingNumbers = fn MutableArrayWithCapacity( position ) + MutableArrayAddObject( hammingNumbers, @1 ) + + NSUInteger i2 = 0, i3 = 0, i5 = 0 + for NSUInteger i = 1 to position - 1 + NSUInteger nxt2 = fn NumberUnsignedLongLongValue( hammingNumbers[i2] ) * 2 + NSUInteger nxt3 = fn NumberUnsignedLongLongValue( hammingNumbers[i3] ) * 3 + NSUInteger nxt5 = fn NumberUnsignedLongLongValue( hammingNumbers[i5] ) * 5 + NSUInteger nxt = fn Minimum( nxt2, fn Minimum( nxt3, nxt5 ) ) + + NSUInteger nextHamming = fn Minimum( nxt2, fn Minimum( nxt3, nxt5 ) ) + MutableArrayAddObject( hammingNumbers, @(nextHamming) ) + + if (nxt == nxt2) then i2++ + if (nxt == nxt3) then i3++ + if (nxt == nxt5) then i5++ + next + + return fn NumberUnsignedLongLongValue( hammingNumbers[position - 1] ) +end fn = 0 + +local fn RunHammingNumberTests + CFMutableArrayRef mutArr = fn MutableArrayNew + + for NSUInteger i = 1 to 20 + MutableArrayAddObject( mutArr, @(fn HammingNumberAtPosition(i)) ) + next + NSLog( @"First 20 Hamming Numbers: %@", fn ArrayComponentsJoinedByString( mutArr, @" " ) ) + NSLog( @" 1691st Hamming Number: %llu", fn HammingNumberAtPosition( 1691 ) ) +end fn + +fn RunHammingNumberTests + +HandleEvents diff --git a/Task/Hamming-numbers/Julia/hamming-numbers-1.julia b/Task/Hamming-numbers/Julia/hamming-numbers-1.jl similarity index 100% rename from Task/Hamming-numbers/Julia/hamming-numbers-1.julia rename to Task/Hamming-numbers/Julia/hamming-numbers-1.jl diff --git a/Task/Hamming-numbers/Julia/hamming-numbers-2.julia b/Task/Hamming-numbers/Julia/hamming-numbers-2.jl similarity index 100% rename from Task/Hamming-numbers/Julia/hamming-numbers-2.julia rename to Task/Hamming-numbers/Julia/hamming-numbers-2.jl diff --git a/Task/Hamming-numbers/Julia/hamming-numbers-3.julia b/Task/Hamming-numbers/Julia/hamming-numbers-3.jl similarity index 100% rename from Task/Hamming-numbers/Julia/hamming-numbers-3.julia rename to Task/Hamming-numbers/Julia/hamming-numbers-3.jl diff --git a/Task/Hamming-numbers/Julia/hamming-numbers-4.julia b/Task/Hamming-numbers/Julia/hamming-numbers-4.jl similarity index 100% rename from Task/Hamming-numbers/Julia/hamming-numbers-4.julia rename to Task/Hamming-numbers/Julia/hamming-numbers-4.jl diff --git a/Task/Hamming-numbers/Julia/hamming-numbers-5.julia b/Task/Hamming-numbers/Julia/hamming-numbers-5.jl similarity index 100% rename from Task/Hamming-numbers/Julia/hamming-numbers-5.julia rename to Task/Hamming-numbers/Julia/hamming-numbers-5.jl diff --git a/Task/Hamming-numbers/Kotlin/hamming-numbers-1.kotlin b/Task/Hamming-numbers/Kotlin/hamming-numbers-1.kts similarity index 100% rename from Task/Hamming-numbers/Kotlin/hamming-numbers-1.kotlin rename to Task/Hamming-numbers/Kotlin/hamming-numbers-1.kts diff --git a/Task/Hamming-numbers/Kotlin/hamming-numbers-2.kotlin b/Task/Hamming-numbers/Kotlin/hamming-numbers-2.kts similarity index 100% rename from Task/Hamming-numbers/Kotlin/hamming-numbers-2.kotlin rename to Task/Hamming-numbers/Kotlin/hamming-numbers-2.kts diff --git a/Task/Hamming-numbers/Kotlin/hamming-numbers-3.kotlin b/Task/Hamming-numbers/Kotlin/hamming-numbers-3.kts similarity index 100% rename from Task/Hamming-numbers/Kotlin/hamming-numbers-3.kotlin rename to Task/Hamming-numbers/Kotlin/hamming-numbers-3.kts diff --git a/Task/Hamming-numbers/Kotlin/hamming-numbers-4.kotlin b/Task/Hamming-numbers/Kotlin/hamming-numbers-4.kts similarity index 100% rename from Task/Hamming-numbers/Kotlin/hamming-numbers-4.kotlin rename to Task/Hamming-numbers/Kotlin/hamming-numbers-4.kts diff --git a/Task/Hamming-numbers/Mojo/hamming-numbers.mojo b/Task/Hamming-numbers/Mojo/hamming-numbers.mojo index 6defc7b7e9..1d093d1922 100644 --- a/Task/Hamming-numbers/Mojo/hamming-numbers.mojo +++ b/Task/Hamming-numbers/Mojo/hamming-numbers.mojo @@ -1,61 +1,61 @@ -from collections.vector import (DynamicVector, CollectionElement) -from math import (log2, trunc, pow) -from memory import memset_zero #, memcpy) -from time import now +# HammingsLogImp.mojo - uses queue instead of frequent draining... +# compile with: mojo build --march=native Hammings.mojo + +# import bigints, std/math # no big ints +from math import (log2, trunc) +from memory import (memset_zero) #, memcpy) +from time import (monotonic) alias cCOUNT: Int = 1_000_000 -struct BigNat(Stringable): # enough just to support conversion and printing +struct BigNat(Movable, ImplicitlyCopyable, 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^ + var contents: List[UInt32] + fn __init__(out self): + self.contents = List[UInt32]() + fn __init__(out self, val: UInt32): + self.contents = List[UInt32](length=1, fill=val) + fn __copyinit__(out self, existing: Self): + self.contents = List[UInt32](existing.contents) fn __str__(self) -> String: var rslt: String = "" - var v = self.contents + var v = List[UInt32](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 + t = (t << 32) + Int(v[i]) + v[i] = Int(t // 10); t -= Int(v[i]) * 10 var sz = len(v) - 1 while sz >= 0 and v[sz] == 0: sz -= 1 v.resize(sz + 1, 0) - rslt = str(t) + rslt + rslt = String(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)): + fn __imul__(mut self, rhs: Self): + var lenl = len(self.contents); var lenr = len(rhs.contents) + var rslt = List[UInt32](length = lenl + lenr, fill = 0) + for i in range(lenr): 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() + for j in range(lenl): + t += Int(self.contents[j]) * Int(rhs.contents[i]) + Int(rslt[i + j]) + rslt[i + j] = Int(t & 0xFFFFFFFF); t >>= 32 + rslt[i + lenl] += Int(t) var sz = len(rslt) - 1 while sz >= 0 and rslt[sz] == 0: sz -= 1 - rslt.resize(sz + 1, 0); self.contents = rslt + 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) +alias lb3: Float64 = log2(Float64(3.0)) +alias lb5: Float64 = log2(Float64(5.0)) -@value -struct LogRep(CollectionElement, Stringable): +@fieldwise_init +struct LogRep(ImplicitlyCopyable, Movable, Stringable): var logrep: Float64 var x2: UInt32 var x3: UInt32 var x5: UInt32 - fn __del__(owned self): return + fn __del__(deinit self): return @always_inline fn mul2(self) -> Self: return LogRep(self.logrep + lb2, self.x2 + 1, self.x3, self.x5) @@ -66,91 +66,122 @@ struct LogRep(CollectionElement, Stringable): fn mul5(self) -> Self: return LogRep(self.logrep + lb5, self.x2, self.x3, self.x5 + 1) fn __str__(self) -> String: +# return "( " + String(self.x2) + ", " + String(self.x3) + ", " + String(self.x5) + " )" var rslt = BigNat(1) - fn expnd(inout rslt: BigNat, bs: UInt32, n: UInt32): + fn expnd(mut 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 + if (nm & 1) != 0: rslt *= bsm + tmp = bsm; bsm *= tmp; nm >>= 1 expnd(rslt, 2, self.x2); expnd(rslt, 3, self.x3); expnd(rslt, 5, self.x5) - return str(rslt) + return String(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: +# Since an escaping closure doesn't currently move even for last used captures, and +# List's can't be copied into closures, we could write a minimal List to do the job, or +# probably easier is to just use a Mojo Iterator struct.... +struct _HammingsLogImpIter(ImplicitlyCopyable, Movable, Iterator): + alias __copyinit__is_trivial = False + alias __moveinit__is_trivial = False + alias __del__is_trivial = False + alias Element = LogRep + var s2: List[LogRep]; var s3: List[LogRep]; var s5: LogRep; var mrg: LogRep +# var s2p: UnsafePointer[LogRep]; var s3p: UnsafePointer[LogRep] + var s2hdi: Int; var s2tli: Int; var s3hdi: Int; var s3tli: Int + fn __init__(out self: Self): + self.s2 = List[LogRep](length=512, fill=oneLR); self.s2[0] = oneLR.mul2() + self.s3 = List[LogRep](length=1, fill=oneLR); self.s3[0] = oneLR.mul3() + self.s5 = oneLR.mul5(); self.mrg = oneLR +# self.s2p = self.s2.steal_data(); self.s3p = self.s3.steal_data() + self.s2hdi = 0; self.s2tli = -1; self.s3hdi = 0; self.s3tli = -1 + fn __copyinit__(out self: Self, existing: Self, /): + self.s2 = existing.s2.copy(); self.s3 = existing.s3.copy() + self.s5 = existing.s5; self.mrg = existing.mrg +# self.s2p = existing.s2p; self.s3p = existing.s3p + self.s2hdi = existing.s2hdi; self.s2tli = existing.s2tli + self.s3hdi = existing.s3hdi; self.s3tli = existing.s3tli +# fn __moveinit__(out self: Self, var existing: Self, /): +# self = existing^ + fn __has_next__(self: Self) -> Bool: + return True # "infinite" series! + fn __next__(mut self: Self) -> Self.Element: + var rslt = self.s2.unsafe_get(self.s2hdi) + var s2len = len(self.s2) + self.s2tli += 1; + if self.s2tli >= s2len: + self.s2tli = 0 + if self.s2hdi == self.s2tli: if s2len < 1024: - s2.resize(1024, oneLR) + self.s2.resize(1024, oneLR) # ; self.s2p = self.s2.steal_data() else: - s2.resize(s2len + s2len, oneLR) # ; s2p = s2.steal_data() - for i in range(s2hdi): - s2[s2len + i] = s2[i] + self.s2.resize(s2len + s2len, oneLR) # ; self.s2p = self.s2.steal_data() + for i in range(self.s2hdi): + self.s2.unsafe_set(s2len + i, self.s2.unsafe_get(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 + self.s2tli += s2len; s2len += s2len + if rslt.logrep < self.mrg.logrep: + self.s2hdi += 1 + if self.s2hdi >= s2len: + self.s2hdi = 0 else: - rslt = mrg - var s3len = len(s3) - s3tli += 1; - if s3tli >= s3len: - s3tli = 0 - if s3hdi == s3tli: + rslt = self.mrg + var s3len = len(self.s3) + self.s3tli += 1; + if self.s3tli >= s3len: + self.s3tli = 0 + if self.s3hdi == self.s3tli: if s3len < 1024: - s3.resize(1024, oneLR) + self.s3.resize(1024, oneLR) # ; self.s3p = self.s3.steal_data() else: - s3.resize(s3len + s3len, oneLR) # ; s3p = s3.steal_data() - for i in range(s3hdi): - s3[s3len + i] = s3[i] + self.s3.resize(s3len + s3len, oneLR) # ; self.s3p = self.s3.steal_data() + for i in range(self.s3hdi): + self.s3.unsafe_set(s3len + i, self.s3.unsafe_get(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 + self.s3tli += s3len; s3len += s3len + if self.mrg.logrep < self.s5.logrep: + self.s3hdi += 1 + if self.s3hdi >= s3len: + self.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 + self.s5 = self.s5.mul5() + self.s3[self.s3tli] = rslt.mul3(); var t = self.s3[self.s3hdi]; + self.mrg = t if t.logrep < self.s5.logrep else self.s5 + self.s2.unsafe_set(self.s2tli, rslt.mul2()); return rslt + +@fieldwise_init +struct HammingsLogImp(ImplicitlyCopyable, Movable, Iterable): + alias __del__is_trivial = True + alias IteratorType[ + iterable_mut: Bool, //, iterable_origin: Origin[iterable_mut] + ]: Iterator = _HammingsLogImpIter + fn __iter__(ref self: Self) -> _HammingsLogImpIter: + return _HammingsLogImpIter() fn main(): print("The first 20 Hamming numbers are:") - var f = hammingsLogImp(); - for i in range(20): print_no_newline(f(), " ") + for i, h in enumerate(HammingsLogImp()): + print(String(h) + " ", end='') + if i >= 19: break 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 + for i, h in enumerate(HammingsLogImp()): + if i >= 1691 - 1: print("The 1691st Hamming number is " + String(h)); break + var strt: Int = monotonic() + var ham = oneLR + for i, h in enumerate(HammingsLogImp()): + if i >= cCOUNT - 1: ham = h; break + var elpsd = (monotonic() - 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("The " + String(cCOUNT) + "th Hamming number is:") + print("2**" + String(ham.x2) + " * 3**" + String(ham.x3) + " * 5**" + String(ham.x5)) + var lg2 = lb2 * Float64(Int(ham.x2)) + lb3 * Float64(Int(ham.x3)) + lb5 * Float64(Int(ham.x5)) + var lg10 = lg2 / log2(Float64(10)) + var expnt = trunc(lg10); var num = Float64(10.0)**(lg10 - expnt) + var apprxstr = String(num) + "E+" + String(Int(expnt)) print("Approximately: ", apprxstr) - let answrstr = str(h) + var answrstr = String(ham) print("The result has", len(answrstr), "digits.") print(answrstr) - print("This took " + str(elpsd) + " microseconds.") + print("This took " + String(elpsd) + " microseconds.") diff --git a/Task/Hamming-numbers/OCaml/hamming-numbers-1.ocaml b/Task/Hamming-numbers/OCaml/hamming-numbers-1.ml similarity index 100% rename from Task/Hamming-numbers/OCaml/hamming-numbers-1.ocaml rename to Task/Hamming-numbers/OCaml/hamming-numbers-1.ml diff --git a/Task/Hamming-numbers/OCaml/hamming-numbers-2.ocaml b/Task/Hamming-numbers/OCaml/hamming-numbers-2.ml similarity index 100% rename from Task/Hamming-numbers/OCaml/hamming-numbers-2.ocaml rename to Task/Hamming-numbers/OCaml/hamming-numbers-2.ml diff --git a/Task/Hamming-numbers/PascalABC.NET/hamming-numbers.pas b/Task/Hamming-numbers/PascalABC.NET/hamming-numbers.pas new file mode 100644 index 0000000000..2f3354df97 --- /dev/null +++ b/Task/Hamming-numbers/PascalABC.NET/hamming-numbers.pas @@ -0,0 +1,34 @@ +function Hamming(n: integer): BigInteger; +begin + var (two,three,five) := (2bi, 3bi, 5bi); + var h := new BigInteger[n]; + h[0] := 1; + var (x2,x3,x5) := (2bi, 3bi, 5bi); + var (i,j,k) := (0, 0, 0); + for var ind := 1 to n-1 do + begin + h[ind] := Min(x2, x3, x5); + if h[ind] = x2 then + begin + i += 1; + x2 := two * h[i]; + end; + if h[ind] = x3 then + begin + j += 1; + x3 := three * h[j]; + end; + if h[ind] = x5 then + begin + k += 1; + x5 := five * h[k]; + end; + end; + Result := h[n-1]; +end; + +begin + (1..20).Select(x -> Hamming(x)).Println; + Hamming(1691).Println; + Hamming(1000000).Println; +end. diff --git a/Task/Hamming-numbers/REXX/hamming-numbers-1.rexx b/Task/Hamming-numbers/REXX/hamming-numbers-1.rexx deleted file mode 100644 index cc53b7ad15..0000000000 --- a/Task/Hamming-numbers/REXX/hamming-numbers-1.rexx +++ /dev/null @@ -1,20 +0,0 @@ -/*REXX program computes Hamming numbers: 1 ──► 20, # 1691, and the one millionth. */ -numeric digits 100 /*ensure enough decimal digits. */ -call hamming 1, 20 /*show the 1st ──► twentieth Hamming #s*/ -call hamming 1691 /*show the 1,691st Hamming number. */ -call hamming 1000000 /*show the 1 millionth Hamming number.*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -hamming: procedure; parse arg x,y; if y=='' then y= x; w= length(y) - #2= 1; #3= 1; #5= 1; @.= 0; @.1= 1 - do n=2 for y-1 - @.n= min(2*@.#2, 3*@.#3, 5*@.#5) /*pick the minimum of 3 Hamming numbers*/ - if 2*@.#2 == @.n then #2= #2 + 1 /*number already defined? Use next #. */ - if 3*@.#3 == @.n then #3= #3 + 1 /* " " " " " " */ - if 5*@.#5 == @.n then #5= #5 + 1 /* " " " " " " */ - end /*n*/ /* [↑] maybe assign next 3 Hamming#s. */ - do j=x to y; say 'Hamming('right(j, w)") =" @.j - end /*j*/ - - say right( 'length of last Hamming number =' length(@.y), 70); say - return diff --git a/Task/Hamming-numbers/REXX/hamming-numbers-2.rexx b/Task/Hamming-numbers/REXX/hamming-numbers-2.rexx deleted file mode 100644 index bccf09bbe0..0000000000 --- a/Task/Hamming-numbers/REXX/hamming-numbers-2.rexx +++ /dev/null @@ -1,26 +0,0 @@ -/*REXX program computes Hamming numbers: 1 ──► 20, # 1691, and the one millionth.*/ -call hamming 1, 20 /*show the 1st ──► twentieth Hamming #s*/ -call hamming 1691 /*show the 1,691st Hamming number. */ -call hamming 1000000 /*show the 1 millionth Hamming number.*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -hamming: procedure; arg x,y; if y=='' then y= x; w= length(y); L= length(y-1); p= 2**L - numeric digits max(9, p + p%4 + p%16) /*ensure enough decimal digits. */ - #2= 1; #3= 1; #5= 1; @.= 0; @.1= 1 - do n=2 for y-1 - _2= @.#2 + @.#2 /*this is faster than: @.#2 * 2 */ - _3= @.#3 + @.#3 + @.#3 /* " " " " @,#3 * 3 */ - _5= @.#5 * 5 - m= _2 /*assume a minimum (of the 3 Hammings).*/ - if _3 < m then m= _3 /*is this number less than the minimum?*/ - if _5 < m then m= _5 /* " " " " " " " */ - @.n= m /*now, assign the next Hamming number.*/ - if _2 == m then #2= #2 + 1 /*number already defined? Use next #.*/ - if _3 == m then #3= #3 + 1 /* " " " " " " */ - if _5 == m then #5= #5 + 1 /* " " " " " " */ - end /*n*/ /* [↑] maybe assign next Hamming #'s. */ - do j=x to y; say 'Hamming('right(j, w)") =" @.j - end /*j*/ - - say right( 'length of last Hamming number =' length(@.y), 70); say - return diff --git a/Task/Hamming-numbers/REXX/hamming-numbers-3.rexx b/Task/Hamming-numbers/REXX/hamming-numbers-3.rexx deleted file mode 100644 index ed4dfa5cbb..0000000000 --- a/Task/Hamming-numbers/REXX/hamming-numbers-3.rexx +++ /dev/null @@ -1,26 +0,0 @@ -/*REXX program computes Hamming numbers: 1 ──► 20, # 1691, and the one millionth.*/ -call hamming 1, 20 /*show the 1st ──► twentieth Hamming #s*/ -call hamming 1691 /*show the 1,691st Hamming number. */ -call hamming 1000000 /*show the 1 millionth Hamming number.*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -hamming: procedure; arg x,y; if y=='' then y= x; w= length(y); L= length(y-1); p= 2**L - numeric digits max(9, p + p%4 + p%16) /*ensure enough decimal digits. */ - #2= 1; #3= 1; #5= 1; @.= 0; @.1= 1 - do n=2 for y-1 - _2= @.#2 + @.#2 /*this is faster than: @.#2 * 2 */ - _3= @.#3 + @.#3 + @.#3 /* " " " " @,#3 * 3 */ - _5= @.#5 * 5 - m= _2 /*assume a minimum (of the 3 Hammings).*/ - if _3 < m then m= _3 /*is this number less than the minimum?*/ - if _5 < m then m= _5 /* " " " " " " " */ - @.n= format(m,,,,0) /*now, assign the next Hamming number.*/ - if _2 == m then #2= #2 + 1 /*number already defined? Use next #.*/ - if _3 == m then #3= #3 + 1 /* " " " " " " */ - if _5 == m then #5= #5 + 1 /* " " " " " " */ - end /*n*/ /* [↑] maybe assign next Hamming #'s. */ - do j=x to y; say 'Hamming('right(j, w)") =" @.j / 1 - end /*j*/ - - say right( 'length of last Hamming number =' length(@.y / 1), 70); say - return diff --git a/Task/Hamming-numbers/REXX/hamming-numbers.rexx b/Task/Hamming-numbers/REXX/hamming-numbers.rexx new file mode 100644 index 0000000000..7ab126e8ff --- /dev/null +++ b/Task/Hamming-numbers/REXX/hamming-numbers.rexx @@ -0,0 +1,38 @@ +-- 23 Aug 2025 +include Setting + +say 'HAMMING NUMBERS' +say version +say +call Hammings 1000000 +call ShowFirstN 20 +call ShowNth 1691 +call ShowNth 1000000 +call Hammings 10000000 +call ShowNth 10000000 +say Time('e')/1 'seconds' +exit + +ShowFirstN: +procedure expose Hamm. +arg xx +xx = xx/1 +say 'First' xx 'Hamming numbers are' +do i = 1 to xx + call Charout ,Right(Hamm.i,5) + if i//10 = 0 then + say +end +say +return + +ShowNth: +procedure expose Hamm. +arg xx +xx = xx/1 +say xx'th Hamming number is' +say Hamm.xx '('Length(Hamm.xx) 'digits)' +say +return + +include Math diff --git a/Task/Hamming-numbers/Rust/hamming-numbers-1.rust b/Task/Hamming-numbers/Rust/hamming-numbers-1.rs similarity index 100% rename from Task/Hamming-numbers/Rust/hamming-numbers-1.rust rename to Task/Hamming-numbers/Rust/hamming-numbers-1.rs diff --git a/Task/Hamming-numbers/Rust/hamming-numbers-2.rust b/Task/Hamming-numbers/Rust/hamming-numbers-2.rs similarity index 100% rename from Task/Hamming-numbers/Rust/hamming-numbers-2.rust rename to Task/Hamming-numbers/Rust/hamming-numbers-2.rs diff --git a/Task/Hamming-numbers/Rust/hamming-numbers-3.rust b/Task/Hamming-numbers/Rust/hamming-numbers-3.rs similarity index 100% rename from Task/Hamming-numbers/Rust/hamming-numbers-3.rust rename to Task/Hamming-numbers/Rust/hamming-numbers-3.rs diff --git a/Task/Hamming-numbers/Rust/hamming-numbers-4.rust b/Task/Hamming-numbers/Rust/hamming-numbers-4.rs similarity index 100% rename from Task/Hamming-numbers/Rust/hamming-numbers-4.rust rename to Task/Hamming-numbers/Rust/hamming-numbers-4.rs diff --git a/Task/Hamming-numbers/Rust/hamming-numbers-5.rust b/Task/Hamming-numbers/Rust/hamming-numbers-5.rs similarity index 100% rename from Task/Hamming-numbers/Rust/hamming-numbers-5.rust rename to Task/Hamming-numbers/Rust/hamming-numbers-5.rs diff --git a/Task/Hamming-numbers/Rust/hamming-numbers-6.rust b/Task/Hamming-numbers/Rust/hamming-numbers-6.rs similarity index 100% rename from Task/Hamming-numbers/Rust/hamming-numbers-6.rust rename to Task/Hamming-numbers/Rust/hamming-numbers-6.rs diff --git a/Task/Hamming-numbers/Rust/hamming-numbers-7.rust b/Task/Hamming-numbers/Rust/hamming-numbers-7.rs similarity index 100% rename from Task/Hamming-numbers/Rust/hamming-numbers-7.rust rename to Task/Hamming-numbers/Rust/hamming-numbers-7.rs diff --git a/Task/Hamming-numbers/Rust/hamming-numbers-8.rust b/Task/Hamming-numbers/Rust/hamming-numbers-8.rs similarity index 100% rename from Task/Hamming-numbers/Rust/hamming-numbers-8.rust rename to Task/Hamming-numbers/Rust/hamming-numbers-8.rs diff --git a/Task/Hamming-numbers/Scheme/hamming-numbers-1.ss b/Task/Hamming-numbers/Scheme/hamming-numbers-1.scm similarity index 100% rename from Task/Hamming-numbers/Scheme/hamming-numbers-1.ss rename to Task/Hamming-numbers/Scheme/hamming-numbers-1.scm diff --git a/Task/Hamming-numbers/Scheme/hamming-numbers-2.ss b/Task/Hamming-numbers/Scheme/hamming-numbers-2.scm similarity index 100% rename from Task/Hamming-numbers/Scheme/hamming-numbers-2.ss rename to Task/Hamming-numbers/Scheme/hamming-numbers-2.scm diff --git a/Task/Hamming-numbers/V-(Vlang)/hamming-numbers-1.v b/Task/Hamming-numbers/V-(Vlang)/hamming-numbers-1.v index 509ec16025..bd63012c8d 100644 --- a/Task/Hamming-numbers/V-(Vlang)/hamming-numbers-1.v +++ b/Task/Hamming-numbers/V-(Vlang)/hamming-numbers-1.v @@ -1,9 +1,7 @@ import math.big fn min(a big.Integer, b big.Integer) big.Integer { - if a < b { - return a - } + if a < b {return a} return b } diff --git a/Task/Hamming-numbers/V-(Vlang)/hamming-numbers-2.v b/Task/Hamming-numbers/V-(Vlang)/hamming-numbers-2.v index 3f7755a80b..4fa74da146 100644 --- a/Task/Hamming-numbers/V-(Vlang)/hamming-numbers-2.v +++ b/Task/Hamming-numbers/V-(Vlang)/hamming-numbers-2.v @@ -63,7 +63,7 @@ fn (lr LogRep) str() string { } struct HammingsLog { - mut: + mut: // automatically initialized with LogRep = one (defult)... s2 []LogRep = []LogRep { len: 1024, cap: 1024 } s3 []LogRep = []LogRep { len: 1024, cap: 1024 } diff --git a/Task/Hamming-numbers/VBScript/hamming-numbers.vb b/Task/Hamming-numbers/VBScript/hamming-numbers.vbs similarity index 100% rename from Task/Hamming-numbers/VBScript/hamming-numbers.vb rename to Task/Hamming-numbers/VBScript/hamming-numbers.vbs diff --git a/Task/Handle-a-signal/Ada/handle-a-signal-1.ada b/Task/Handle-a-signal/Ada/handle-a-signal-1.adb similarity index 100% rename from Task/Handle-a-signal/Ada/handle-a-signal-1.ada rename to Task/Handle-a-signal/Ada/handle-a-signal-1.adb diff --git a/Task/Handle-a-signal/Ada/handle-a-signal-2.ada b/Task/Handle-a-signal/Ada/handle-a-signal-2.adb similarity index 100% rename from Task/Handle-a-signal/Ada/handle-a-signal-2.ada rename to Task/Handle-a-signal/Ada/handle-a-signal-2.adb diff --git a/Task/Handle-a-signal/Ada/handle-a-signal-3.ada b/Task/Handle-a-signal/Ada/handle-a-signal-3.adb similarity index 100% rename from Task/Handle-a-signal/Ada/handle-a-signal-3.ada rename to Task/Handle-a-signal/Ada/handle-a-signal-3.adb diff --git a/Task/Handle-a-signal/Batch-File/handle-a-signal.bat b/Task/Handle-a-signal/Batch-File/handle-a-signal.bat new file mode 100644 index 0000000000..6c25ba9c5d --- /dev/null +++ b/Task/Handle-a-signal/Batch-File/handle-a-signal.bat @@ -0,0 +1,31 @@ +@echo off +setlocal enableextensions enabledelayedexpansion +if defined sigintEnd goto timerCalc +if defined sigintMain goto main +set timer=for /f "tokens=1-4 delims=:.," %%a in ("^!time^!"^) do set start_h=%%a^&set /a start_m=100%%b %% 100^&set /a start_s=100%%c %% 100^&set /a start_ms=100%%d %% 100 +( +%timer% +set sigintMain=1 +%= "echo y" to skip a prompt and proceed to time reporting =% +echo y| cmd /d /c "%~f0" +cmd /d /c set sigintEnd=1^&"%~f0" +goto :eof +) +:main +set i=1 +:loop +echo %i% +:: sleep for 1 second +ping 0.0.0.0 -n 2 >nul +set /a i+=1 +goto loop +:timerCalc +%timer:start=end% +for %%i in (h m s ms) do set /a %%i=end_%%i-start_%%i +if %ms% lss 0 set /a s-=1 & set /a ms=100%ms% +if %s% lss 0 set /a m-=1 & set /a s=60%s% +if %m% lss 0 set /a h-=1 & set /a m=60%m% +if %h% lss 0 set /a h=24%h% +if 1%ms% lss 100 set ms=0%ms% +set /a totalsecs=h*3600 + m*60 +s +echo Execution time: %totalsecs%.%ms%s diff --git a/Task/Handle-a-signal/COBOL/handle-a-signal.cobol b/Task/Handle-a-signal/COBOL/handle-a-signal.cob similarity index 100% rename from Task/Handle-a-signal/COBOL/handle-a-signal.cobol rename to Task/Handle-a-signal/COBOL/handle-a-signal.cob diff --git a/Task/Handle-a-signal/Crystal/handle-a-signal.crystal b/Task/Handle-a-signal/Crystal/handle-a-signal.cr similarity index 100% rename from Task/Handle-a-signal/Crystal/handle-a-signal.crystal rename to Task/Handle-a-signal/Crystal/handle-a-signal.cr diff --git a/Task/Handle-a-signal/Julia/handle-a-signal.julia b/Task/Handle-a-signal/Julia/handle-a-signal.jl similarity index 100% rename from Task/Handle-a-signal/Julia/handle-a-signal.julia rename to Task/Handle-a-signal/Julia/handle-a-signal.jl diff --git a/Task/Handle-a-signal/Kotlin/handle-a-signal.kotlin b/Task/Handle-a-signal/Kotlin/handle-a-signal.kts similarity index 100% rename from Task/Handle-a-signal/Kotlin/handle-a-signal.kotlin rename to Task/Handle-a-signal/Kotlin/handle-a-signal.kts diff --git a/Task/Handle-a-signal/OCaml/handle-a-signal.ocaml b/Task/Handle-a-signal/OCaml/handle-a-signal.ml similarity index 100% rename from Task/Handle-a-signal/OCaml/handle-a-signal.ocaml rename to Task/Handle-a-signal/OCaml/handle-a-signal.ml diff --git a/Task/Handle-a-signal/PascalABC.NET/handle-a-signal.pas b/Task/Handle-a-signal/PascalABC.NET/handle-a-signal.pas new file mode 100644 index 0000000000..751e61da9f --- /dev/null +++ b/Task/Handle-a-signal/PascalABC.NET/handle-a-signal.pas @@ -0,0 +1,13 @@ +begin + var counter := 0; + while True do + begin + Print(counter); + counter += 1; + Sleep(500); + end; + Console.CancelKeyPress += (o,e) -> begin + Println(Milliseconds); + halt + end; +end. diff --git a/Task/Handle-a-signal/PowerShell/handle-a-signal.psh b/Task/Handle-a-signal/PowerShell/handle-a-signal.ps1 similarity index 100% rename from Task/Handle-a-signal/PowerShell/handle-a-signal.psh rename to Task/Handle-a-signal/PowerShell/handle-a-signal.ps1 diff --git a/Task/Handle-a-signal/Rebol/handle-a-signal.rebol b/Task/Handle-a-signal/Rebol/handle-a-signal.rebol new file mode 100644 index 0000000000..89e69e09f1 --- /dev/null +++ b/Task/Handle-a-signal/Rebol/handle-a-signal.rebol @@ -0,0 +1 @@ +catch/quit/with [i: 0 t: stats/timer forever [print ++ i wait 0.5]][print ["Done!" stats/timer - t]] diff --git a/Task/Handle-a-signal/Rust/handle-a-signal.rust b/Task/Handle-a-signal/Rust/handle-a-signal.rs similarity index 100% rename from Task/Handle-a-signal/Rust/handle-a-signal.rust rename to Task/Handle-a-signal/Rust/handle-a-signal.rs diff --git a/Task/Happy-numbers/00-META.yaml b/Task/Happy-numbers/00-META.yaml index 2fb428f9fa..6e331dac93 100644 --- a/Task/Happy-numbers/00-META.yaml +++ b/Task/Happy-numbers/00-META.yaml @@ -1,3 +1,3 @@ --- from: http://rosettacode.org/wiki/Happy_numbers -note: Arithmetic operations +note: Numbers diff --git a/Task/Happy-numbers/Ada/happy-numbers.ada b/Task/Happy-numbers/Ada/happy-numbers.adb similarity index 100% rename from Task/Happy-numbers/Ada/happy-numbers.ada rename to Task/Happy-numbers/Ada/happy-numbers.adb diff --git a/Task/Happy-numbers/Arturo/happy-numbers.arturo b/Task/Happy-numbers/Arturo/happy-numbers.arturo index bc1ccc3bbb..388d4db91b 100644 --- a/Task/Happy-numbers/Arturo/happy-numbers.arturo +++ b/Task/Happy-numbers/Arturo/happy-numbers.arturo @@ -1,7 +1,7 @@ -ord0: to :integer `0` +ord0: to :integer '0' happy?: function [x][ n: x - past: new [] + past: [] while [n <> 1][ s: to :string n diff --git a/Task/Happy-numbers/AutoIt/happy-numbers-1.autoit b/Task/Happy-numbers/AutoIt/happy-numbers-1.au3 similarity index 100% rename from Task/Happy-numbers/AutoIt/happy-numbers-1.autoit rename to Task/Happy-numbers/AutoIt/happy-numbers-1.au3 diff --git a/Task/Happy-numbers/AutoIt/happy-numbers-2.autoit b/Task/Happy-numbers/AutoIt/happy-numbers-2.au3 similarity index 100% rename from Task/Happy-numbers/AutoIt/happy-numbers-2.autoit rename to Task/Happy-numbers/AutoIt/happy-numbers-2.au3 diff --git a/Task/Happy-numbers/COBOL/happy-numbers.cobol b/Task/Happy-numbers/COBOL/happy-numbers.cob similarity index 100% rename from Task/Happy-numbers/COBOL/happy-numbers.cobol rename to Task/Happy-numbers/COBOL/happy-numbers.cob diff --git a/Task/Happy-numbers/Crystal/happy-numbers.crystal b/Task/Happy-numbers/Crystal/happy-numbers.cr similarity index 100% rename from Task/Happy-numbers/Crystal/happy-numbers.crystal rename to Task/Happy-numbers/Crystal/happy-numbers.cr diff --git a/Task/Happy-numbers/Delphi/happy-numbers.delphi b/Task/Happy-numbers/Delphi/happy-numbers.pas similarity index 100% rename from Task/Happy-numbers/Delphi/happy-numbers.delphi rename to Task/Happy-numbers/Delphi/happy-numbers.pas diff --git a/Task/Happy-numbers/Elena/happy-numbers.elena b/Task/Happy-numbers/Elena/happy-numbers.elena index 5b4b0322fa..0b49f2db3e 100644 --- a/Task/Happy-numbers/Elena/happy-numbers.elena +++ b/Task/Happy-numbers/Elena/happy-numbers.elena @@ -27,7 +27,7 @@ isHappy(int n) ^ true } -public program() +public Program() { auto happynums := new List(8); int num := 1; diff --git a/Task/Happy-numbers/Elixir/happy-numbers.elixir b/Task/Happy-numbers/Elixir/happy-numbers.ex similarity index 100% rename from Task/Happy-numbers/Elixir/happy-numbers.elixir rename to Task/Happy-numbers/Elixir/happy-numbers.ex diff --git a/Task/Happy-numbers/Euphoria/happy-numbers.euphoria b/Task/Happy-numbers/Euphoria/happy-numbers.eu similarity index 100% rename from Task/Happy-numbers/Euphoria/happy-numbers.euphoria rename to Task/Happy-numbers/Euphoria/happy-numbers.eu diff --git a/Task/Happy-numbers/Frink/happy-numbers.frink b/Task/Happy-numbers/Frink/happy-numbers.frink new file mode 100644 index 0000000000..ce9c4e404d --- /dev/null +++ b/Task/Happy-numbers/Frink/happy-numbers.frink @@ -0,0 +1,19 @@ +isHappy = {|n| + sqf = {|x| x^2} + seen = new set[n] + + while true + { + n = sum[map[sqf, integerDigits[n]]] + if n == 1 + return true + + if seen.contains[n] + return false + else + seen.put[n] + } +} + + +println[first[select[count[1], isHappy], 8]] diff --git a/Task/Happy-numbers/Haskell/happy-numbers-3.hs b/Task/Happy-numbers/Haskell/happy-numbers-3.hs new file mode 100644 index 0000000000..04713b0ba9 --- /dev/null +++ b/Task/Happy-numbers/Haskell/happy-numbers-3.hs @@ -0,0 +1,14 @@ +happy x = sum (map (\x -> x * x) (digits x)) + where + digits 0 = [0] + digits x = (x `mod` 10):(digits (x `div` 10)) -- could function digits be more concise? + +ishappy x = floyd (happy x) (happy (happy x)) + where + floyd :: Int -> Int -> Bool + floyd 1 _ = True + floyd _ 1 = True + floyd a b | a == b = False + floyd x y = floyd (happy x) (happy (happy y)) + +main = (print $ take 8 $ filter ishappy [1..]) >> (print $ sum $ take 10000 $ filter ishappy [1..] diff --git a/Task/Happy-numbers/Julia/happy-numbers-1.julia b/Task/Happy-numbers/Julia/happy-numbers-1.jl similarity index 100% rename from Task/Happy-numbers/Julia/happy-numbers-1.julia rename to Task/Happy-numbers/Julia/happy-numbers-1.jl diff --git a/Task/Happy-numbers/Julia/happy-numbers-2.julia b/Task/Happy-numbers/Julia/happy-numbers-2.jl similarity index 100% rename from Task/Happy-numbers/Julia/happy-numbers-2.julia rename to Task/Happy-numbers/Julia/happy-numbers-2.jl diff --git a/Task/Happy-numbers/Julia/happy-numbers-3.julia b/Task/Happy-numbers/Julia/happy-numbers-3.jl similarity index 100% rename from Task/Happy-numbers/Julia/happy-numbers-3.julia rename to Task/Happy-numbers/Julia/happy-numbers-3.jl diff --git a/Task/Happy-numbers/Kotlin/happy-numbers.kotlin b/Task/Happy-numbers/Kotlin/happy-numbers.kts similarity index 100% rename from Task/Happy-numbers/Kotlin/happy-numbers.kotlin rename to Task/Happy-numbers/Kotlin/happy-numbers.kts diff --git a/Task/Happy-numbers/OCaml/happy-numbers.ocaml b/Task/Happy-numbers/OCaml/happy-numbers.ml similarity index 100% rename from Task/Happy-numbers/OCaml/happy-numbers.ocaml rename to Task/Happy-numbers/OCaml/happy-numbers.ml diff --git a/Task/Happy-numbers/PascalABC.NET/happy-numbers.pas b/Task/Happy-numbers/PascalABC.NET/happy-numbers.pas new file mode 100644 index 0000000000..15d02a6478 --- /dev/null +++ b/Task/Happy-numbers/PascalABC.NET/happy-numbers.pas @@ -0,0 +1,27 @@ +uses School; + +function IsHappy(n: integer): boolean; +begin + Result := False; + var cache := new HashSet; + while n <> 1 do + begin + if n in cache then + exit; + cache.Add(n); + n := n.Digits.Sum(d -> d*d); + end; + Result := True; +end; + +begin + var n := 1; + var happyNums := new List; + while happyNums.Count < 8 do + begin + if IsHappy(n) then + happyNums.Add(n); + n += 1; + end; + happyNums.Print +end. diff --git a/Task/Happy-numbers/Pluto/happy-numbers.pluto b/Task/Happy-numbers/Pluto/happy-numbers.pluto new file mode 100644 index 0000000000..80a7ecb196 --- /dev/null +++ b/Task/Happy-numbers/Pluto/happy-numbers.pluto @@ -0,0 +1,26 @@ +local function happy(n) + local m = {} + while n > 1 do + m[n] = true + local x = n + n = 0 + while x > 0 do + local d = x % 10 + n += d * d + x //= 10 + end + if m[n] then return false end -- m[n] will be nil if 'n' is not a key + end + return true +end + +local found = 0 +local n = 1 +while found < 8 do + if happy(n) then + io.write($"{n} ") + found += 1 + end + n += 1 +end +print() diff --git a/Task/Happy-numbers/PowerShell/happy-numbers-1.psh b/Task/Happy-numbers/PowerShell/happy-numbers-1.ps1 similarity index 100% rename from Task/Happy-numbers/PowerShell/happy-numbers-1.psh rename to Task/Happy-numbers/PowerShell/happy-numbers-1.ps1 diff --git a/Task/Happy-numbers/PowerShell/happy-numbers-2.psh b/Task/Happy-numbers/PowerShell/happy-numbers-2.ps1 similarity index 100% rename from Task/Happy-numbers/PowerShell/happy-numbers-2.psh rename to Task/Happy-numbers/PowerShell/happy-numbers-2.ps1 diff --git a/Task/Happy-numbers/REXX/happy-numbers.rexx b/Task/Happy-numbers/REXX/happy-numbers-1.rexx similarity index 100% rename from Task/Happy-numbers/REXX/happy-numbers.rexx rename to Task/Happy-numbers/REXX/happy-numbers-1.rexx diff --git a/Task/Happy-numbers/REXX/happy-numbers-2.rexx b/Task/Happy-numbers/REXX/happy-numbers-2.rexx new file mode 100644 index 0000000000..11cc8094fd --- /dev/null +++ b/Task/Happy-numbers/REXX/happy-numbers-2.rexx @@ -0,0 +1,106 @@ +-- 23 Aug 2025 +include Setting + +say 'HAPPY NUMBERS' +say version +say +say 'Process first 8...' +call HappyS 8 +call ShowFirst8 +say +say 'Process first 10 million...' +call HappyS 1e7 +call ShowNth 1e1 +call ShowNth 1e2 +call ShowNth 1e3 +call ShowNth 1e4 +call ShowNth 1e5 +call ShowNth 1e6 +call ShowNth 1e7 +say +call Timer 'R' +exit + +HappyS: +procedure expose Happ. Flag. +arg xx +-- Preset squares for digital sum +do i = 0 to 9 + Pow2.i=i*i +end +-- Collect happy numbers <= 1000 +Flag.=0; Happ.=0; n=0 +do i = 1 while n < xx + h=i; ll='' + do forever +-- Squared digital sum + ss=0 + do Length(h) + parse var h d +1 h; ss=ss+Pow2.d + end + select +-- Unhappy? Flag sad sums, next number + when Flag.ss then do + do while ll <> '' + parse var ll s ll; Flag.s=1 + end + iterate i + end +-- Repeating? Flag sad sums, next number + when WordPos(ss,ll) > 0 then do + do while ll <> '' + parse var ll s ll; Flag.s=1 + end + iterate i + end +-- Happy? Bump, next number + when ss = 1 then do + n=n+1; Happ.n=i + iterate i + end +-- Next sum + otherwise do + ll=ll ss; h=ss + end + end + end +end i +-- Flag happy numbers <= 1000 +Flag.=0 +do i = 1 to n + h=Happ.i; Flag.h=1 +end +-- Collect happy numbers > 1000 using flagged numbers +do i = 1001 while n < xx + h=i +-- Squared digital sum + ss=0 + do Length(h) + parse var h d +1 h; ss=ss+Pow2.d + end +-- Happy? Bump + if Flag.ss then do + n=n+1; Happ.n=i + end +end i +-- Count +Happ.0=n +return n + +ShowFirst8: +procedure expose Happ. +say 'First 8 Happy numbers are' +do i = 1 to 8 + call Charout ,Right(Happ.i,3) +end +say +return + +ShowNth: +procedure expose Happ. +arg xx +xx = xx/1 +say xx'th Happy number is' Happ.xx +return + +include Math diff --git a/Task/Happy-numbers/Rust/happy-numbers.rs b/Task/Happy-numbers/Rust/happy-numbers.rs new file mode 100644 index 0000000000..a0097862a0 --- /dev/null +++ b/Task/Happy-numbers/Rust/happy-numbers.rs @@ -0,0 +1,37 @@ +fn sumsqd(mut n: i32) -> i32 { + let mut sq = 0; + while n > 0 { + let d = n % 10; + sq += d * d; + n /= 10; + } + sq +} + +fn cycle(a: T, f: F) -> T +where + T: Copy + PartialEq, + F: Fn(T) -> T, +{ + let mut t = a; + let mut h = f(a); + + while t != h { + t = f(t); + h = f(f(h)); + } + t +} + +fn ishappy(n: i32) -> bool { + cycle(n, sumsqd) == 1 +} + +fn main() { + let happy: Vec = (1..) + .filter(|&n| ishappy(n)) + .take(8) + .collect(); + + println!("{:?}", happy); +} diff --git a/Task/Happy-numbers/Rust/happy-numbers.rust b/Task/Happy-numbers/Rust/happy-numbers.rust deleted file mode 100644 index 9b6647bd6e..0000000000 --- a/Task/Happy-numbers/Rust/happy-numbers.rust +++ /dev/null @@ -1,36 +0,0 @@ -#![feature(core)] - -fn sumsqd(mut n: i32) -> i32 { - let mut sq = 0; - while n > 0 { - let d = n % 10; - sq += d*d; - n /= 10 - } - sq -} - -use std::num::Int; -fn cycle(a: T, f: fn(T) -> T) -> T { - let mut t = a; - let mut h = f(a); - - while t != h { - t = f(t); - h = f(f(h)) - } - t -} - -fn ishappy(n: i32) -> bool { - cycle(n, sumsqd) == 1 -} - -fn main() { - let happy = std::iter::count(1, 1) - .filter(|&n| ishappy(n)) - .take(8) - .collect::>(); - - println!("{:?}", happy) -} diff --git a/Task/Happy-numbers/Scheme/happy-numbers.ss b/Task/Happy-numbers/Scheme/happy-numbers.scm similarity index 100% rename from Task/Happy-numbers/Scheme/happy-numbers.ss rename to Task/Happy-numbers/Scheme/happy-numbers.scm diff --git a/Task/Happy-numbers/Uiua/happy-numbers.uiua b/Task/Happy-numbers/Uiua/happy-numbers.uiua index f282f61166..a7189fe111 100644 --- a/Task/Happy-numbers/Uiua/happy-numbers.uiua +++ b/Task/Happy-numbers/Uiua/happy-numbers.uiua @@ -1,10 +1,3 @@ -HC ← /+ⁿ2≡⋕°⋕ # Happiness calc = sum of squares of digits -IH ← |2 memo⟨IH ⊙⊂.|=1⟩∊,, HC # Apply HC until seen value recurs -Happy ← ⟨0◌|∘⟩IH : [1] . # Pre-load `seen` with 1. Return start number or 0 - -# Brute force approach isn't too bad with memoisation even for high bounds. -↙8⊚>0≡Happy⇡10000 - -# But iterative approach is still much faster -NH ← |1 ⟨NH|∘⟩≠0Happy.+1 # Find next Happy number -⇌[⍥(NH.) 7 1] +HC ← /+ⁿ2⊥₁₀ # Happiness = sum of squares of digits. +Happy ← memo(=1⊢⍢(⊂HC⊸⊢|¬˜∊°⊂)[∘]) # Apply HC until it repeats or = 1. +↙8▽⊸≡Happy⇡40 diff --git a/Task/Happy-numbers/V-(Vlang)/happy-numbers.v b/Task/Happy-numbers/V-(Vlang)/happy-numbers.v index 4e492e47a7..93b56b1751 100644 --- a/Task/Happy-numbers/V-(Vlang)/happy-numbers.v +++ b/Task/Happy-numbers/V-(Vlang)/happy-numbers.v @@ -1,16 +1,14 @@ fn happy(h int) bool { mut m := map[int]bool{} - mut n := h + mut n, mut x := h, 0 for n > 1 { m[n] = true - mut x := 0 + x = 0 for x, n = n, 0; x > 0; x /= 10 { d := x % 10 n += d * d } - if m[n] { - return false - } + if m[n] { return false } } return true } @@ -22,5 +20,5 @@ fn main() { found++ } } - println('') + println("") } diff --git a/Task/Happy-numbers/VBScript/happy-numbers.vb b/Task/Happy-numbers/VBScript/happy-numbers.vbs similarity index 100% rename from Task/Happy-numbers/VBScript/happy-numbers.vb rename to Task/Happy-numbers/VBScript/happy-numbers.vbs diff --git a/Task/Harmonic-series/ALGOL-60/harmonic-series.alg b/Task/Harmonic-series/ALGOL-60/harmonic-series.alg new file mode 100644 index 0000000000..7b5f62d6ba --- /dev/null +++ b/Task/Harmonic-series/ALGOL-60/harmonic-series.alg @@ -0,0 +1,32 @@ +begin + +real i, h, n, limit; + +limit := 20; +h := 0; +outstring(1,"First"); +outreal(1,limit); +outstring(1,"numbers in the harmonic series\n"); +for i := 1, i + 1 while i <= limit do + begin + h := h + 1 / i; + outreal(1,i); + outreal(1,h); + outstring(1,"\n"); + end; + +for i := 1, i + 1 while i <= 5 do + begin + h := 1; + for n := 2, n + 1 while h <= i do + begin + h := h + 1 / n; + end; + outstring(1,"First harmonic number >"); + outreal(1,i); + outstring(1,"is at position"); + outreal(1,n-1); + outstring(1,"\n"); + end; + +end diff --git a/Task/Harmonic-series/ALGOL-68/harmonic-series.alg b/Task/Harmonic-series/ALGOL-68/harmonic-series.alg index b9fee50a9e..a050da661d 100644 --- a/Task/Harmonic-series/ALGOL-68/harmonic-series.alg +++ b/Task/Harmonic-series/ALGOL-68/harmonic-series.alg @@ -1,13 +1,13 @@ -BEGIN # find some harmonic numbers, Hn is the sum if the reciprocals of 1..n # +BEGIN # find some harmonic numbers, Hn is the sum of the reciprocals of 1..n # # returns the first n Harmonic numbers # OP HARMONIC = ( INT n )[]REAL: BEGIN - [ 1 : n ]REAL h; - h[ 1 ] := 1; + [ 1 : n ]REAL hs; + hs[ 1 ] := 1; FOR i FROM 2 TO n DO - h[ i ] := h[ i - 1 ] + ( 1 / i ) + hs[ i ] := hs[ i - 1 ] + ( 1 / i ) OD; - h + hs END # HARMONIC # ; # find the first 20 000 harmonic numbers # []REAL h = HARMONIC 20 000; @@ -21,7 +21,8 @@ BEGIN # find some harmonic numbers, Hn is the sum if the reciprocals of 1..n # FOR i TO UPB h DO IF h[ i ] > rqd real THEN # found the first harmonic number greater than rqd real # - print( ( "Position of the first harmonic number > ", whole( rqd int, -2 ), ": ", whole( i, 0 ), newline ) ); + print( ( "Position of the first harmonic number > ", whole( rqd int, -2 ) ) ); + print( ( ": ", whole( i, 0 ), newline ) ); rqd int +:= 1; rqd real +:= 1 FI diff --git a/Task/Harmonic-series/Ada/harmonic-series.adb b/Task/Harmonic-series/Ada/harmonic-series.adb new file mode 100644 index 0000000000..4e1c360707 --- /dev/null +++ b/Task/Harmonic-series/Ada/harmonic-series.adb @@ -0,0 +1,41 @@ +with Ada.Text_IO; + +procedure Harmonic_Numbers is + type Harmonic_State is record + N : Positive := 1; + Hn : Float := 1.0; + end record; + + procedure Iterate_Harmonics (Hs : in out Harmonic_State; Max_Steps : Positive := 1; Stop : Float := Float'Last) is + begin + for I in 1 .. Max_Steps loop + exit when Hs.Hn > Stop; + Hs.N := Hs.N + 1; + Hs.Hn := Hs.Hn + 1.0 / Float (Hs.N); + end loop; + end Iterate_Harmonics; + + procedure Show_First_Harmonics (N : Positive) is + Hs : Harmonic_State; + begin + for I in 1 .. N loop + Ada.Text_IO.Put_Line (Hs.N'Image & " => " & Hs.Hn'Image); + Iterate_Harmonics (Hs); + end loop; + end Show_First_Harmonics; + + -- Assume Floats is in order + type Floats is array (Positive range <>) of Float; + procedure Show_Harmonics_Greater (Ns : Floats) is + Hs : Harmonic_State; + begin + for I of Ns loop + Iterate_Harmonics (Hs, Positive'Last, I); + Ada.Text_IO.Put_Line (">" & I'Image & ":" & Hs.N'Image & " => " & Hs.Hn'Image); + end loop; + end Show_Harmonics_Greater; + +begin + Show_First_Harmonics (20); + Show_Harmonics_Greater ((1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0)); +end Harmonic_Numbers; diff --git a/Task/Harmonic-series/BQN/harmonic-series.bqn b/Task/Harmonic-series/BQN/harmonic-series.bqn new file mode 100644 index 0000000000..2d5eb490b2 --- /dev/null +++ b/Task/Harmonic-series/BQN/harmonic-series.bqn @@ -0,0 +1,6 @@ +Harmonic ← +`1÷∘+↕ + +⟨ + > 8↑⟜•Fmt¨ 5e¯7+ Harmonic 20 + 1+⍉(⊣≍(⌈ Harmonic 12400)⊐2+⊢)↕10 +⟩ diff --git a/Task/Harmonic-series/Bruijn/harmonic-series.bruijn b/Task/Harmonic-series/Bruijn/harmonic-series.bruijn new file mode 100644 index 0000000000..747d370e68 --- /dev/null +++ b/Task/Harmonic-series/Bruijn/harmonic-series.bruijn @@ -0,0 +1,16 @@ +:import std/List . +:import std/Combinator . +:import std/Math/Rational Q +:import std/Number N + +# fun Church iteration hack +harmonic [0 &[[(Q.add 1 op) : N.++0]] start [[1]]] ⧗ Unary → Rational + op (+1) : N.--0 + start (+0.0f) : (+1) + +custom-gt? &[[[N.gt? 2 (N.mul 0 N.++1)]]] ⧗ Rational → Νumber → Boolean + +main [φ cons first-20 first-10-above (harmonic <$> (iterate [[[1 (2 1 0)]]] (+0u)))] + first-20 take (+20) + first-10-above [take (+10) first-above] + first-above [find-index [custom-gt? 0 1] 1] <$> (iterate N.inc (+0)) diff --git a/Task/Harmonic-series/C/harmonic-series.c b/Task/Harmonic-series/C/harmonic-series.c new file mode 100644 index 0000000000..db4f01b2d4 --- /dev/null +++ b/Task/Harmonic-series/C/harmonic-series.c @@ -0,0 +1,24 @@ +#include +#include + +/* return nth harmonic number */ +double harmonic(int n) { + double h, i; + h = 0; + for (i = 1; i <= (double) n; i += 1.0) + h += 1 / i; + return h; +} + +int main(void) { + int i, n; + printf("First 20 harmonic numbers:\n"); + for (i = 1; i <= 20; i++) + printf("%2d %8.6lf\n", i, harmonic(i)); + for (i = 1; i <= 5; i++) { + int n = 2; + while (harmonic(n) <= (double) i) n++; + printf("First term > %d is at position %d\n", i, n); + } + return EXIT_SUCCESS; +} diff --git a/Task/Harmonic-series/CBASIC/harmonic-series.basic b/Task/Harmonic-series/CBASIC/harmonic-series.basic new file mode 100644 index 0000000000..35bb0c4f57 --- /dev/null +++ b/Task/Harmonic-series/CBASIC/harmonic-series.basic @@ -0,0 +1,19 @@ +limit = 20 +h = 0 +print "First";limit;"numbers in the harmonic series" +for i = 1 to limit + h = h + 1 / i + print using "## #.#####"; i; h +next i + +for i = 1 to 5 + h = 1 + n = 2 + while h <= i + h = h + 1 / n + n = n + 1 + wend + print "Position of first harmonic number >"; i; "is at"; n-1 +next i + +end diff --git a/Task/Harmonic-series/COBOL/harmonic-series.cobol b/Task/Harmonic-series/COBOL/harmonic-series.cob similarity index 100% rename from Task/Harmonic-series/COBOL/harmonic-series.cobol rename to Task/Harmonic-series/COBOL/harmonic-series.cob diff --git a/Task/Harmonic-series/Delphi/harmonic-series.delphi b/Task/Harmonic-series/Delphi/harmonic-series.pas similarity index 100% rename from Task/Harmonic-series/Delphi/harmonic-series.delphi rename to Task/Harmonic-series/Delphi/harmonic-series.pas diff --git a/Task/Harmonic-series/DuckDB/harmonic-series.duckdb b/Task/Harmonic-series/DuckDB/harmonic-series.duckdb new file mode 100644 index 0000000000..c0297fcc3c --- /dev/null +++ b/Task/Harmonic-series/DuckDB/harmonic-series.duckdb @@ -0,0 +1,21 @@ +# If mx > 0, then return a table of the first mx harmonic numbers, +# otherwise return a table with h up to: floor(h) < - mx +create or replace function harmonic_table(mx) as table ( + with recursive cte(ix,h) as ( + select 1 as ix, 1::DOUBLE as h + union all + select ix+1, h + 1/(ix+1) + from cte + where if (mx>0, ix < mx, floor(h) < - mx) + ) + from cte +); + +# First 20: +from harmonic_table(20); + +# Milestones: +from ( + select ix, lag(h) over () as hlag, h + from harmonic_table(-10) ) +where ceil(hlag) = trunc(h); diff --git a/Task/Harmonic-series/EasyLang/harmonic-series.easy b/Task/Harmonic-series/EasyLang/harmonic-series.easy index 75a56234c7..fbf03db1cf 100644 --- a/Task/Harmonic-series/EasyLang/harmonic-series.easy +++ b/Task/Harmonic-series/EasyLang/harmonic-series.easy @@ -1,4 +1,4 @@ -numfmt 5 2 +numfmt 2 5 print "The first twenty harmonic numbers are:" for n = 1 to 20 h += 1 / n diff --git a/Task/Harmonic-series/Fortran/harmonic-series.f b/Task/Harmonic-series/Fortran/harmonic-series.f new file mode 100644 index 0000000000..2ab5783463 --- /dev/null +++ b/Task/Harmonic-series/Fortran/harmonic-series.f @@ -0,0 +1,83 @@ +program harmonic_numbers + use :: iso_fortran_env, only: int64, output_unit + implicit none + integer, parameter :: real64 = selected_real_kind(15, 307) + + type :: fraction + integer(int64) :: numerator + integer(int64) :: denominator + end type fraction + + integer :: i, target_int + type(fraction) :: h_exact + real(real64) :: sum_h, h_decimal + character(len=200) :: fmt_str + + ! Print first 20 harmonic numbers as fractions + write(output_unit, '(a)') "## First 20 Harmonic Numbers" + write(output_unit, '(a)') "**Fractional Form**" + h_exact = fraction(0_int64, 1_int64) + do i = 1, 20 + h_exact = add_reciprocal(h_exact, i) + write(output_unit, '(i2, ": ", i0, "/", i0)') i, h_exact%numerator, h_exact%denominator + end do + + ! Print decimal approximations + write(output_unit, '(/, a)') "**Decimal Approximations**" + h_exact = fraction(0_int64, 1_int64) + do i = 1, 20 + h_exact = add_reciprocal(h_exact, i) + h_decimal = real(h_exact%numerator, real64) / real(h_exact%denominator, real64) + write(output_unit, '(i2, ": ", f0.12)') i, h_decimal + end do + + ! Find positions where harmonic numbers exceed integers 1-10 + write(output_unit, '(/, a)') "## Positions Where H? First Exceeds Integers" + write(output_unit, '(a)') "| Target | Position (n) | Decimal Approximation |" + write(output_unit, '(a)') "|--------|--------------|------------------------|" + write(fmt_str, '(a)') '(a, i2, a, T10, A, i0,T25, a, f0.6, T50,a)' + + do target_int = 1, 10 + sum_h = 0._real64 + i = 0 + do + i = i + 1 + sum_h = sum_h + 1.0_real64 / real(i, real64) + if (sum_h > real(target_int, real64)) then + if (target_int <= 5 .or. target_int >= 6) then + write(output_unit, FMT_STR) "| **", target_int, "**","| ", i, & + "| ", real(sum_h, real64), "|" + end if + exit + end if + end do + end do + +contains + + function add_reciprocal(h, n) result(new_h) + type(fraction), intent(in) :: h + integer, intent(in) :: n + type(fraction) :: new_h + integer(int64) :: common_denominator, new_numerator, divisor + + common_denominator = h%denominator * int(n, int64) + new_numerator = h%numerator * int(n, int64) + h%denominator + divisor = gcd(new_numerator, common_denominator) + + new_h%numerator = new_numerator / divisor + new_h%denominator = common_denominator / divisor + end function add_reciprocal + + recursive function gcd(a, b) result(greatest_common_divisor) + integer(int64), intent(in) :: a, b + integer(int64) :: greatest_common_divisor + + if (b == 0) then + greatest_common_divisor = a + else + greatest_common_divisor = gcd(b, mod(a, b)) + end if + end function gcd + +end program harmonic_numbers diff --git a/Task/Harmonic-series/Julia/harmonic-series-1.julia b/Task/Harmonic-series/Julia/harmonic-series-1.jl similarity index 100% rename from Task/Harmonic-series/Julia/harmonic-series-1.julia rename to Task/Harmonic-series/Julia/harmonic-series-1.jl diff --git a/Task/Harmonic-series/Julia/harmonic-series-2.julia b/Task/Harmonic-series/Julia/harmonic-series-2.jl similarity index 100% rename from Task/Harmonic-series/Julia/harmonic-series-2.julia rename to Task/Harmonic-series/Julia/harmonic-series-2.jl diff --git a/Task/Harmonic-series/OCaml/harmonic-series-1.ml b/Task/Harmonic-series/OCaml/harmonic-series-1.ml new file mode 100644 index 0000000000..0ace1720f1 --- /dev/null +++ b/Task/Harmonic-series/OCaml/harmonic-series-1.ml @@ -0,0 +1,9 @@ +let series = + Seq.scan (fun sum i -> Q.(sum + inv ~$i)) Q.one (Seq.ints 2) + +let positions = + Seq.unfold + (fun (n, s) -> + Seq.uncons (Seq.drop_while (fun iq -> Q.(n >= snd iq)) s) + |> Option.map (fun (iq, s) -> fst iq, Q.(n + one, s))) + (Q.one, Seq.zip (Seq.ints 1) series) diff --git a/Task/Harmonic-series/OCaml/harmonic-series-2.ml b/Task/Harmonic-series/OCaml/harmonic-series-2.ml new file mode 100644 index 0000000000..8350a4ae7d --- /dev/null +++ b/Task/Harmonic-series/OCaml/harmonic-series-2.ml @@ -0,0 +1,4 @@ +let _ = + let print fmt = Format.printf (fmt ^^ "\n") in + Seq.iteri (fun i h -> print "H(%d) =\t%a" (i + 1) Q.pp_print h) (Seq.take 20 series); + Seq.iteri (fun i n -> print "nth harmonic > %d:\t%d" (i + 1) n) (Seq.take 10 positions) diff --git a/Task/Harmonic-series/OCaml/harmonic-series-3.ml b/Task/Harmonic-series/OCaml/harmonic-series-3.ml new file mode 100644 index 0000000000..3e25736172 --- /dev/null +++ b/Task/Harmonic-series/OCaml/harmonic-series-3.ml @@ -0,0 +1,7 @@ +module Q = struct + include Stdlib.Float + let (~$) = of_int + let (+) = add + let inv = div 1. + let pp_print = Stdlib.Format.pp_print_float +end diff --git a/Task/Harmonic-series/Oberon-07/harmonic-series.oberon b/Task/Harmonic-series/Oberon-07/harmonic-series.oberon new file mode 100644 index 0000000000..c0fb7af5d8 --- /dev/null +++ b/Task/Harmonic-series/Oberon-07/harmonic-series.oberon @@ -0,0 +1,37 @@ +MODULE HarmonicSeries; (* find some harmonic numbers, Hn is the sum of the reciprocals of 1..n *) + IMPORT Out; + + VAR h : ARRAY 20001 OF REAL; + rqdInt, i : INTEGER; + rqdReal : REAL; + + PROCEDURE harmonic( VAR hs : ARRAY OF REAL ); (* sets hs to the first LEN(hs) - 1 Harmonic numbers *) + VAR i : INTEGER; (* hs[0] is unused *) + BEGIN + hs[ 1 ] := 1.0; + FOR i := 2 TO LEN( hs ) - 1 DO + hs[ i ] := hs[ i - 1 ] + ( 1.0 / FLT( i ) ) + END + END harmonic ; + +BEGIN + + harmonic( h ); (* find the first 20 000 harmonic numbers *) + + FOR i := 1 TO 20 DO (* show the first 20 harmonic numbers *) + Out.Int( i, 2 );Out.String( ":" );Out.Real( h[ i ], 14 );Out.Ln + END; + + (* find the positions of the first harmonic number > n where n in 1... *) + rqdInt := 1; + rqdReal := 1.0; + FOR i := 1 TO LEN( h ) - 1 DO + IF h[ i ] > rqdReal THEN + (* found the first harmonic number greater than rqdReal *) + Out.String( "Position of the first harmonic number > " );Out.Int( rqdInt, 2 ); + Out.String( ": " );Out.Int( i, 0 );Out.Ln; + INC( rqdInt ); + rqdReal := FLT( rqdInt ) + END + END +END HarmonicSeries. diff --git a/Task/Harmonic-series/PascalABC.NET/harmonic-series.pas b/Task/Harmonic-series/PascalABC.NET/harmonic-series.pas new file mode 100644 index 0000000000..e767fc50cc --- /dev/null +++ b/Task/Harmonic-series/PascalABC.NET/harmonic-series.pas @@ -0,0 +1,17 @@ +function H(n: integer): real := (1..n).Sum(i -> 1/i); + +begin + for var i:=1 to 20 do + Println($'{i,2}: {H(i),10:f8}'); + var i := 1; + var num := 1; + while num < 11 do + begin + if H(i) > num then + begin + Println('Position of the first harmonic number >',num,':',i); + num += 1; + end; + i += 1; + end; +end. diff --git a/Task/Harmonic-series/Phix/harmonic-series-1.phix b/Task/Harmonic-series/Phix/harmonic-series-1.phix index 757038f636..458bbff449 100644 --- a/Task/Harmonic-series/Phix/harmonic-series-1.phix +++ b/Task/Harmonic-series/Phix/harmonic-series-1.phix @@ -1,26 +1,24 @@ -(phixonline)--> - requires("0.8.4") - include mpfr.e - integer n = 1, gn = 1, lim = iff(platform()=JS?8:10) - mpq hn = mpq_init_set_si(1) - sequence gt = {} - puts(1,"First twenty harmonic numbers as rationals:\n") - while gn<=lim do - if n<=20 then - printf(1,"%18s%s",{mpq_get_str(hn),iff(mod(n,5)?" ","\n")}) - end if - if n=100 then - printf(1,"\nOne Hundredth:\n%s\n\n",{mpq_get_str(hn)}) - end if - if mpq_cmp_si(hn,gn)>0 then - gt &= n - gn += 1 - end if - n += 1 - mpq_add_si(hn,hn,1,n) - end while - printf(1,"(one based) Index of first value:\n") - for i=1 to length(gt) do - printf(1," greater than %2d: %,6d (%s term)\n",{i,gt[i],ordinal(gt[i])}) - end for - - integer n = 1, gn = 1 - atom hn = 1 - sequence gt = {} - puts(1,"First twenty harmonic numbers as fractions:\n") - while gn<=10 do - if n<=20 then - printf(1,"%18.15f%s",{hn,iff(mod(n,5)?" ","\n")}) - end if - if n=100 then - printf(1,"\nOne Hundredth: %18.15f\n\n",{hn}) - end if - if hn>gn then - gt &= n - gn += 1 - end if - n += 1 - hn += 1/n - end while - printf(1,"(one based) Index of first value:\n") - for i=1 to length(gt) do - printf(1," greater than %2d: %,6d (%s term)\n",{i,gt[i],ordinal(gt[i])}) - end for - {} = wait_key() - - with javascript_semantics - constant A = {{27,"Jonah"}, - {18,"Alan"}, - {28,"Glory"}, - {18,"Popeye"}, - {28,"Alan"}}, - B = {{"Jonah","Whales"}, - {"Jonah","Spiders"}, - {"Alan", "Ghosts"}, - {"Alan", "Zombies"}, - {"Glory","Buffy"}}, - jA = 2, - jB = 1, - MB = new_dict() - sequence C = {} - for i=1 to length(B) do - object key = B[i][jB] - object data = getd(key,MB) - if data=0 then - data = {B[i]} - else - data = append(data,B[i]) - end if - putd(key,data,MB) - end for - for i=1 to length(A) do - object data = getd(A[i][jA],MB) - if sequence(data) then - for j=1 to length(data) do - C = append(C,{A[i],data[j]}) - end for - end if - end for - destroy_dict(MB) - pp(C,{pp_Nest,1}) -( (age,age...), (nemesis,...) ) if (r:=d.find(name)){ diff --git a/Task/Haversine-formula/ALGOL-W/haversine-formula.alg b/Task/Haversine-formula/ALGOL-W/haversine-formula.alg index 9fc4fa5d35..8e58f6c95f 100644 --- a/Task/Haversine-formula/ALGOL-W/haversine-formula.alg +++ b/Task/Haversine-formula/ALGOL-W/haversine-formula.alg @@ -16,8 +16,8 @@ begin % compute the distance between places using the Haversine formula % real d; integer mi, km; d := distance( 36.12, -86.67, 33.94, -118.4 ); - mi := round( d ); - km := round( d / 1.609344 ); - writeon( i_w := 4, s_w := 0, "distance: ", mi, " km (", km, " mi.)" ) + km := round( d ); + mi := round( d / 1.609344 ); + writeon( i_w := 4, s_w := 0, "distance: ", km, " km (", mi, " mi.)" ) end end. diff --git a/Task/Haversine-formula/Ada/haversine-formula.ada b/Task/Haversine-formula/Ada/haversine-formula.adb similarity index 100% rename from Task/Haversine-formula/Ada/haversine-formula.ada rename to Task/Haversine-formula/Ada/haversine-formula.adb diff --git a/Task/Haversine-formula/Agena/haversine-formula.agena b/Task/Haversine-formula/Agena/haversine-formula.agena new file mode 100644 index 0000000000..cb1dad8071 --- /dev/null +++ b/Task/Haversine-formula/Agena/haversine-formula.agena @@ -0,0 +1,18 @@ +scope # compute the distance between places using the Haversine formula + + local proc distance( th1Deg :: number, ph1Deg :: number, th2Deg :: number, ph2Deg :: number ) :: number + local constant ph1 := ( ph1Deg - ph2Deg ) * radians; + local constant th1 := th1Deg * radians; + local constant th2 := th2Deg * radians; + local constant dz := sin( th1 ) - sin( th2 ); + local constant dx := cos( ph1 ) * cos( th1 ) - cos( th2 ); + local constant dy := sin( ph1 ) * cos( th1 ); + return arcsin( sqrt( dx * dx + dy * dy + dz * dz ) / 2 ) * 2 * 6371 + end; + + scope + local constant d := distance( 36.12, -86.67, 33.94, -118.4 ); + local constant km, constant mi := round( d ), round( d / 1.609344 ); + printf( "distance: %4d km (%4d mi.)", km, mi ) + epocs +epocs diff --git a/Task/Haversine-formula/Bc/haversine-formula.bc b/Task/Haversine-formula/Bc/haversine-formula.bc index 3aad71d5b6..eaeea4816d 100644 --- a/Task/Haversine-formula/Bc/haversine-formula.bc +++ b/Task/Haversine-formula/Bc/haversine-formula.bc @@ -1,8 +1,11 @@ #!/bin/sh #- -# © 2021 mirabilos Ⓕ CC0; implementation of Haversine GCD from public sources +# © 2021 mirabilos Ⓕ CC0 or MirBSD # -# now developed online: +# implementation of Haversine GCD from public sources +# output is in metres (rounded to millimetres), error < ¼% +# +# now developed online: (user/pass public) # https://evolvis.org/plugins/scmgit/cgi-bin/gitweb.cgi?p=useful-scripts/mirkarte.git;a=blob;f=geo.sh;hb=HEAD if test "$#" -ne 4; then @@ -23,8 +26,8 @@ export BC_ENV_ARGS # h: haversine intermediate # i,j: (lat,lon) point 1 # x,y: (lat,lon) point 2 -# k: delta lat -# l: delta lon +# k: delta lat/ΔΦ +# l: delta lon/Δλ # m: sin(k/2) (square root of hav(k)) # n: sin(l/2) ( partial haversine ) # n(x): arcsin(x) @@ -32,7 +35,7 @@ export BC_ENV_ARGS # v(x): sign (Vorzeichen) # w(x): min(1, sqrt(x)) (Wurzel) -bc -l <<-EOF +exec bc -l <<-EOF scale=64 define n(x) { if (x == -1) return (-2 * a(1)) @@ -59,7 +62,8 @@ define w(x) { return (sqrt(x)) } /* WGS84 reference ellipsoid: große Halbachse (metres), Abplattung */ -i = 6378137.000 +/* (6378137 in WGS84); this radius from Astronomical Almanac 2021 */ +i = 6378136.600 x = 1/298.257223563 /* other axis */ j = i * (1 - x) @@ -80,5 +84,3 @@ h = ((m * m) + (c(i) * c(x) * n * n)) d = 2 * r * n(w(h)) r(d, 3) EOF - -# output is in metres, rounded to millimetres, error < ¼% in WGS84 diff --git a/Task/Haversine-formula/Crystal/haversine-formula.crystal b/Task/Haversine-formula/Crystal/haversine-formula.cr similarity index 100% rename from Task/Haversine-formula/Crystal/haversine-formula.crystal rename to Task/Haversine-formula/Crystal/haversine-formula.cr diff --git a/Task/Haversine-formula/Delphi/haversine-formula.delphi b/Task/Haversine-formula/Delphi/haversine-formula.pas similarity index 100% rename from Task/Haversine-formula/Delphi/haversine-formula.delphi rename to Task/Haversine-formula/Delphi/haversine-formula.pas diff --git a/Task/Haversine-formula/DuckDB/haversine-formula.duckdb b/Task/Haversine-formula/DuckDB/haversine-formula.duckdb new file mode 100644 index 0000000000..f301d80fe5 --- /dev/null +++ b/Task/Haversine-formula/DuckDB/haversine-formula.duckdb @@ -0,0 +1,7 @@ +# install spatial; -- if required +load spatial; + +select [lat1, lon1], [lat2, lon2], + ST_Distance_sphere( ST_Point(lat1, lon1), ST_Point(lat2,lon2)) as "Haversine (m)", + ST_Distance_spheroid(ST_Point(lat1, lon1), ST_Point(lat2,lon2)) as "ellipsoid (m)" +from (select 36.12 as lat1, -86.67 as lon1, 33.94 at lat2, -118.40 as lon2); diff --git a/Task/Haversine-formula/EDSAC-order-code/haversine-formula.edsac b/Task/Haversine-formula/EDSAC-order-code/haversine-formula.edsac new file mode 100644 index 0000000000..e6a18551aa --- /dev/null +++ b/Task/Haversine-formula/EDSAC-order-code/haversine-formula.edsac @@ -0,0 +1,181 @@ +[Haversine formula, for Rosetta Code.] +[EDSAC, initial orders 2.] + [Arrange the storage] + T49K P56F [L, 35 locations: library s/r R4 to read integer.] + [Can overwrite R9 once R9 is no longer needed.] + T46K P92F [N, 35 locations: library s/r P7 (print integer)] + T52K P128F [A, 33 locations: library subroutine T4 (arccos)] + T53K P162F [B, 44 locations: 1ibrary subroutine T1 (cos)] + T54K P206F [C, 10 locations: wrapper for library subroutine T1] + T51K P216F [G, 24 locations: inverse haversine function] + T45K P240F [H, 36 locations: haversine function] + T55K P276F [V, 11 locations: constants] + T47K P288F [M, 92 locations: main routine] +[----------------------------------------------------------------------------] +[Library subroutine R9 to read integers from tape at load time.] +[Must be placed at location 56; occupies 15 locations.] + T56K +GKT20FVDL8FA40DUDTFI40FA40FS39FG@S2FG23FA5@T5@E4@ +[----------------------------------------------------------------------------] +[Library subroutine M3. Prints header at load time and is then overwritten.] +[In this program, also sets teleprinter to figures.] +PFGKIFAFRDLFUFOFE@A6FG@E8FEZPF + *DISTANCES!IN!METRES@&WITH!RADIUS# + .. PK [after header, blank tape and PK (WWG, 1951, page 91)] +[----------------------------------------------------------------------------] +[Constants. Load at even address.] + E25K TV GK + E69K [at load time, call library s/r R9 to read 35-bit contants] + T#V [tell R9 where to store constants] + [0] 1800000000F [180 degrees, in units of 10^-7 degree] + [2] 900000000F [90 ditto] + [4] 16097821018F [for changing angle unit to radians] + [6] 13493037750F [pi/4 as EDSAC integer, i.e. times 2^34] + [8] 6371100# [Earth radius in metres, from MK-61/52 solution] + T10Z [resume normal loading] + [10] RF [17-bit 1/4] +[----------------------------------------------------------------------------] +[Main routine. Load at even address.] + E25K TM GK +[35-bit variables, general workspace] + [0] [2] [4] [6] [8] +[17-bit variables] + [10] [number of examples] + [11] [example number] + T12Z [variablss are not initialized; skip over them at load time] +[17-bit constants] + [12] PD [1] + [13] CF [ teleprinter colon (in figures mode)] + [14] @F [15] &F [16] K4096F [CR, LF, null] + [Enter with acc = 0] + [17] A8#V TD [pass Earth's radius to printer routine] + A19@ GN [finish header: print radius followed by CR, LF] + O14@ O15@ + A23@ GL [call library s/r R4, 0D := number of examples] + AF T10@ [store (assume < 2^16)] + [Here acc = example number just done (0 first time)] + [27] S10@ E98@ [if all done, jump to exit] + A10@ A12@ T11@ [inc and store example number] + TD A11@ TF [0D := example number, extended to 35 bits] + A35@ GN O13@ [print example number followed by colon] + [Use library subroutine R4 to read data from tape to 0D.] + [Coordinates are lat1, lon1, lat2, lon2.] + A38@ GL AD U#@ T4D [lat1 to work{0} and 4D] + A43@ GC A4D T2#@ [0.5*cos(lat1) to work{1}] + A47@ GL AD T8#@ [lon1 to work{4}] + A51@ GL AD U4#@ T4D [lat2 to work{2} and 4D] + A56@ GC A4D T6#@ [0.5*cos(lat2) to work{3}] + A60@ GL AD S8#@ T4D [lon2 - lon1 to 4D] + A65@ GH [0.5*hav(lon2 - lon1) to 4D] + H2#@ V4D LD YF T4D [times cos(lat1) to 4D] + H6#@ V4D LD YF T8#@ [times cos(lat2) to work{4}] + A#@ S4#@ T4D [lat1 - lat2 to 4D] + A80@ GH A4D [0.5*hav(lat1 - lat2) to acc] + A8#@ T4D [add product from above, sum to 4D] + A85@ GG H4D [mult reg := angle/4 in radians] + V8#V L1F YF TD [times radius*4, to 0D for printing] + A92@ GN O14@ O15@ [print distance followed by CR, LF] + A11@ E27@ [acc := example numbr; loop back] + [Exit] + [98] O16@ [print null to flush teleprinter buffer] + ZF [stop] +[----------------------------------------------------------------------------] +[Haversine function, for Rosetta Code.] +[Input: 4D = angle x in range -360..360 deg,] + [expressed as integer multiple of 10^-7 deg.] +[Output: 4D = hav(x)/2 = (1 - cos(x))/4] +[Load at even address. Requires library subroutines R9 and T1.] + E25K TH GK + A3F T35@ [plant return link as usual] + [2] A4D E6@ [acc := x; jump if x >= 0] + T4D + [5] S4D [else x := -x] + [Here with acc = abs(x). Use symmetry about 180 deg.] + [6] S#V G10@ [jump if x < 180] + TD SD [else acc := 180 - x] + [10] A2#V [combine next 2 orders, which are shown as comments] + [A #V] [add 180: either restore x, or set x := 360 - x] + [Here 0 <= x <= 180. Use antisymmetry about 90 deg.] + [S 2 #V] [subtract 90] + E17@ [jump if x >= 90 degrees] + TD A5@ T30@ [save acc, plant S4D below] + AD G21@ [acc := x - 90, join common code] + [17] TD A2@ T30@ [save acc, plant A4D below] + SD [acc := 90 - x] + [21] A2#V [either restore x, or set x := 180 - x] + TD H4#V VD L4F YF [apply angle conversion factor] + [Here acc = x/2, now in radians. Pass it to cosine function] + T4D + A28@ GB [call cosine function; returns 4D := cos(x)/2] + [30] XF [(planted) either A4D or S4D] + RD YF A10V [divide by 2, round, add 1/4] + T4D [return haversine/2 in 4D] + [35] ZF [(planted) jump back to caller] +[----------------------------------------------------------------------------] +[Inverse haversine function.] +[Input: 4D = hav(x)/2] +[Output: 4D = x/4 in radians, where 0 <= x <= pi] + E25K TG GK + A3F T23@ [plant return link as usual] + A10V S4D LD YF [acc := 1/2 - hav(x) = cos(x)/2] + G13@ [jumo if cos(x) < 0] + T4D [pass cos(x)/2 to library subroutine T4 (arccis)] + A8@ GA AD RD [call T4, 0D ;= x/2; then acc := x/4] + E21@ [join common code] + [13] TD SD T4D [here if cos(x) < 0; set 4D := -cos(x)/2] + A16@ GA [call T4 (arccos); 0D := (pi - x)/2] + SD RD A6#V [acc := -(pi - x)/4 + pi/4 = x/4] + [21] YF T4D [round redult and return it in 4D] + [23] ZF [(planted) jump back to caller] +[----------------------------------------------------------------------------] +[Wrapper for library subroutine T1 (cosine).] +[Input: 4D = angle x as integer multiple of 10^-7 degree.] +[Output: 4D = cos(x)/2] + E25K TC GK + A3F T9@ [plant return link as usual] + H4#V V4D L4F YF T4D [4D := x/2 in radians] + A7@ GB [call T1, puts cos(x)/2 into 4D] + [9] ZF [jump back to caller] +[----------------------------------------------------------------------------] +[Library subroutine T1: calculates cos(x), where abs(x) <= pi/2] +[Input: 4D = x/2] +[Output: 4D = cos(x)/2] +[Requires library subroutine R9.] + E25K TB +GKT20FVDL8FA40DUDTFI40FA40FS39FG@S2FG23FA5@T5@E4@E13ZT32#@ +1614F73454F243967F54539267F763549741F5726623061# +TZA3FT30@H4DV4DYFT4DH4DN32#@A34#@TDNDA36#@TDNDA38#@ +TDNDA40#@TDNDA42#@TDNDYFTDNDS4DA31@YFT4DEFIFT44Z +[----------------------------------------------------------------------------] +[Library subroutine T4: calculates arccos] +[Input: 4D = cos(x)/2, assumed >= 0] +[Output: 0D = x/2 where 0 <= x <= pi/2] + E25K TA +GKA3FT28@TDA32@T6DH4DV4DL1FS29@YFE16@T4DSDA6DTDS4DT4DA6DRD +YFG4@HDN30#@YFE27@T4DS4DTDEFIFT30#ZD888FT30ZO699DT32ZK4096F +[----------------------------------------------------------------------------] +[Library subroutine P7. Prints 35-bit positive integer in 0D.] +[Up to 10 digits, right-justified, padded on left with spaces.] + E25K TN +GKA3FT26@H28#@NDYFLDT4DS27@TFH8@S8@T1FV4DAFG31@SFLDUFOFFFSF +L4FT4DA1FA27@G11@T28#ZPFT27ZP1024FP610D@524D!FO30@SFL8FE22@ +[----------------------------------------------------------------------------] +[Library subroutine R4. Reads signed integer from tape at run time.] +[Input : None] +[Output : 0D = 35-bit signed integer.] + E25K TL +GKA3FT21@T4DH6@E11@P5DJFT6FVDL4FA4DTDI4FA4FS5@G7@S5@G20@SDTDT6FEF +[----------------------------------------------------------------------------] + E25K TM GK [M parameter again] + E17Z [define entry point] + PF [acc = 0 on entry] +[----------------------------------------------------------------------------] +[Latitude and longitude of each airport, in units of 10^-7 degree.] +[Read from tape by library subroutine R4. Note that sign comes after value.] +3+ [number of examples] +361200000+866700000- [Nashville] +339400000+1184000000- [Los Angeles] +547166667+205000000+ [Kaliningrad] +431166667+1319000000+ [Vladivostok] +499133333+62916667- [St Mary's, Scilly Isles] +601919444+12436111- [Tingwall, Shetland Isles] diff --git a/Task/Haversine-formula/Elena/haversine-formula.elena b/Task/Haversine-formula/Elena/haversine-formula.elena index a88153e368..49527462a5 100644 --- a/Task/Haversine-formula/Elena/haversine-formula.elena +++ b/Task/Haversine-formula/Elena/haversine-formula.elena @@ -15,7 +15,7 @@ Haversine(lat1,lon1,lat2,lon2) ^ R * 2 * a.sqrt().arcsin() } -public program() +public Program() { console.printLineFormatted("The distance between coordinates {0},{1} and {2},{3} is: {4}", 36.12r, -86.67r, 33.94r, -118.40r, Haversine(36.12r, -86.67r, 33.94r, -118.40r)) diff --git a/Task/Haversine-formula/Elixir/haversine-formula.elixir b/Task/Haversine-formula/Elixir/haversine-formula.ex similarity index 100% rename from Task/Haversine-formula/Elixir/haversine-formula.elixir rename to Task/Haversine-formula/Elixir/haversine-formula.ex diff --git a/Task/Haversine-formula/Fennel/haversine-formula.fennel b/Task/Haversine-formula/Fennel/haversine-formula.fennel new file mode 100644 index 0000000000..d4b0b8029b --- /dev/null +++ b/Task/Haversine-formula/Fennel/haversine-formula.fennel @@ -0,0 +1,18 @@ +(do ;;; compute the distance between places using the Haversine formula + (fn distance [th1Deg ph1Deg th2Deg ph2Deg] + (local ph1 (math.rad (- ph1Deg ph2Deg))) + (local th1 (math.rad th1Deg)) + (local th2 (math.rad th2Deg)) + (local dz (- (math.sin th1) (math.sin th2))) + (local dx (- (* (math.cos ph1) (math.cos th1)) (math.cos th2))) + (local dy (* (math.sin ph1) (math.cos th1))) + (* (math.asin (/ (math.sqrt (+ (* dx dx) (* dy dy) (* dz dz))) 2)) 2 6371) + ) + (do + (fn round [n] (math.floor (+ n 0.49999999999))) + + (local d (distance 36.12 -86.67 33.94 -118.4)) + (local (km mi) (values (round d) (round (/ d 1.609344)))) + (print (.. "distance: " km " km (" mi " mi.)")) + ) +) diff --git a/Task/Haversine-formula/Julia/haversine-formula.julia b/Task/Haversine-formula/Julia/haversine-formula.jl similarity index 100% rename from Task/Haversine-formula/Julia/haversine-formula.julia rename to Task/Haversine-formula/Julia/haversine-formula.jl diff --git a/Task/Haversine-formula/Kotlin/haversine-formula.kotlin b/Task/Haversine-formula/Kotlin/haversine-formula.kts similarity index 100% rename from Task/Haversine-formula/Kotlin/haversine-formula.kotlin rename to Task/Haversine-formula/Kotlin/haversine-formula.kts diff --git a/Task/Haversine-formula/MiniScript/haversine-formula.mini b/Task/Haversine-formula/MiniScript/haversine-formula.mini new file mode 100644 index 0000000000..6e4952c0d7 --- /dev/null +++ b/Task/Haversine-formula/MiniScript/haversine-formula.mini @@ -0,0 +1,17 @@ +// compute the distance between places using the Haversine formula + +distance = function( th1Deg, ph1Deg, th2Deg, ph2Deg ) + toRadians = pi / 180 + ph1 = toRadians * ( ph1Deg - ph2Deg ) + th1 = toRadians * th1Deg + th2 = toRadians * th2Deg + dz = sin( th1 ) - sin( th2 ) + dx = cos( ph1 ) * cos( th1 ) - cos( th2 ) + dy = sin( ph1 ) * cos( th1 ) + return asin( sqrt( dx * dx + dy * dy + dz * dz ) / 2 ) * 2 * 6371 +end function + +d = distance( 36.12, -86.67, 33.94, -118.4 ) +km = round( d ) +mi = round( d / 1.609344 ) +print( "distance: " + km + " km (" + mi + " mi.)" ) diff --git a/Task/Haversine-formula/NetRexx/haversine-formula.netrexx b/Task/Haversine-formula/NetRexx/haversine-formula.netrexx new file mode 100644 index 0000000000..ded11a6a34 --- /dev/null +++ b/Task/Haversine-formula/NetRexx/haversine-formula.netrexx @@ -0,0 +1,40 @@ +/*REXX pgm calculates distance between Nashville & Los Angles airports. */ +say " Nashville: north 36° 7.2', west 86° 40.2' = 36.12°, -86.67°" +say "Los Angles: north 33° 56.4', west 118° 24.0' = 33.94°, -118.40°" +say +dist=surfaceDistance(36.12, -86.67, 33.94, -118.4) +say dist + +bef = Length(dist/1) +kdist=format(dist/1,bef,2) +mdist=format(dist/1.609344,bef,2) +ndist=format(mdist*5280/6076.1,bef,2) +say ' distance between= ' kdist " kilometers," +say ' or ' mdist " statute miles," +say ' or ' ndist " nautical or air miles." +exit /*stick a fork in it, we're done.*/ +/*----------------------------------SURFACEDISTANCE subroutine----------*/ + +method radians(x) static + return x * Math.PI / 180 + +method surfaceDistance(lat1,lon1,lat2,lon2) public static /*use haversine formula for dist.*/ + radius = 6372.8 /*earth's mean radius in km */ + dLat = radians(lat2 - lat1) + dLon = radians(lon2 - lon1) + lat1 = radians(lat1) + lat2 = radians(lat2) + + a = sin(dLat / 2)**2 + cos(lat1) * cos(lat2) * sin(dLon / 2) ** 2 + c = 2 * asin(sqrt(a)) + + return radius * c + +method cos(x) static + return Rexx Math.cos(x) +method sin(x) static + return Rexx Math.sin(x) +method asin(x) static + return Rexx Math.asin(x) +method sqrt(x) static + return Rexx Math.sqrt(x) diff --git a/Task/Haversine-formula/OCaml/haversine-formula.ocaml b/Task/Haversine-formula/OCaml/haversine-formula.ml similarity index 100% rename from Task/Haversine-formula/OCaml/haversine-formula.ocaml rename to Task/Haversine-formula/OCaml/haversine-formula.ml diff --git a/Task/Haversine-formula/PascalABC.NET/haversine-formula.pas b/Task/Haversine-formula/PascalABC.NET/haversine-formula.pas new file mode 100644 index 0000000000..8eafc78a1a --- /dev/null +++ b/Task/Haversine-formula/PascalABC.NET/haversine-formula.pas @@ -0,0 +1,19 @@ +const + r = 6372.8; + +function haversine(lat1, lon1, lat2, lon2: real): real; +begin + var dLat := degToRad(lat2 - lat1); + var dLon := degToRad(lon2 - lon1); + lat1 := degToRad(lat1); + lat2 := degToRad(lat2); + + var a := sin(dLat / 2) * sin(dLat / 2) + cos(lat1) * cos(lat2) * sin(dLon / 2) * sin(dLon / 2); + var c := 2 * arcsin(sqrt(a)); + + result := r * c; +end; + +begin + haversine(36.12, -86.67, 33.94, -118.40).Println; +end. diff --git a/Task/Haversine-formula/Phix/haversine-formula.phix b/Task/Haversine-formula/Phix/haversine-formula.phix index a5c8ad31c1..921a3dcd5e 100644 --- a/Task/Haversine-formula/Phix/haversine-formula.phix +++ b/Task/Haversine-formula/Phix/haversine-formula.phix @@ -1,14 +1,15 @@ -(phixonline)--> - function haversine(atom lat1, long1, lat2, long2) - constant MER = 6371, -- mean earth radius(km) - DEG_TO_RAD = PI/180 - lat1 *= DEG_TO_RAD - lat2 *= DEG_TO_RAD - long1 *= DEG_TO_RAD - long2 *= DEG_TO_RAD - return MER*arccos(sin(lat1)*sin(lat2)+cos(lat1)*cos(lat2)*cos(long2-long1)) - end function +with javascript_semantics +constant MER = 6371, -- mean earth radius, authalic(km) +--constant MER = 6372.8, -- mean earth radius, average(km) + DEG_TO_RAD = PI/180 - atom d = haversine(36.12,-86.67,33.94,-118.4) - printf(1,"Distance is %f km (%f miles)\n",{d,d/1.609344}) - - puts(1,"Hello world!") - - puts(1,"Hello world!") - - puts(1,"Hello world!") - - -- - -- pwa\phix\hello_world.exw - -- ======================== - -- - with javascript_semantics - include pGUI.e - - IupOpen() - Ihandle lbl = IupFlatLabel("World!","EXPAND=YES, ALIGNMENT=ACENTER") - Ihandln dlg = IupDialog(lbl,"TITLE=Hello, RASTERSIZE=215x85") - IupShow(dlg) - if platform()!=JS then - IupMainLoop() - dlg = IupDestroy(dlg) - IupClose() - end if - - with javascript_semantics - function af(string s) return max(s)<='f' and min(s)>='a' end function - function digital_root(integer n) - assert(n>=0) - while n>9 do - integer tot = 0 - while n>0 do - tot += remainder(n,10) - n = floor(n/10) - end while - n = tot - end while - return n - end function - sequence words = filter(unix_dict(4),af), - decml = apply(true,to_integer,{words,0,16}), - roots = apply(decml,digital_root), - tags = custom_sort(roots,tagset(length(roots))) +with javascript_semantics +function af(string s) return max(s)<='f' and min(s)>='a' end function +function digital_root(integer n) + assert(n>=0) + while n>9 do + integer tot = 0 + while n>0 do + tot += remainder(n,10) + n = floor(n/10) + end while + n = tot + end while + return n +end function +sequence words = filter(unix_dict(4),af), + decml = apply(true,to_integer,{words,0,16}), + roots = apply(decml,digital_root), + tags = custom_sort(roots,tagset(length(roots))) - function caejasp() -- columnize/apply/extract/join/apply/sprint(...) - sequence s = columnize(apply(true,extract,{{words,decml,roots},{tags}})) - return join(apply(true,sprintf,{{"%6s -> %8d -> %d\n"},s})) - end function - printf(1," %s\n %d hex words with 4 or more letters found,\n",{caejasp(),length(tags)}) - function ge4(integer t) return length(unique(words[t]))>=4 end function - tags = filter(tags,ge4) - tags = extract(tags,reverse(custom_sort(extract(decml,tags),tagset(length(tags))))) - printf(1," %d with 4 or more distinct characters:\n\n %s\n",{length(tags),caejasp()}) - - without javascript_semantics -- (no mpfr_log() for pwa/p2js) - requires("1.0.0") -- (mpfr_set_default_prec[ision] renamed) - include mpfr.e - mpfr_set_default_precision(-23) -- (found by trial/error) - mpfr ln2 = mpfr_init(2), - hn = mpfr_init(0.5) - mpfr_log(ln2,ln2) - mpfr_div(hn,hn,ln2) - for n=1 to 17 do - mpfr_mul_si(hn,hn,n) - mpfr_div(hn,hn,ln2) - string n10 = mpfr_sprintf("%24.4Rf ",hn) - n10 &= iff(find(n10[21],"09")?"Y":"N") - printf(1,"%2d:%s\n",{n,n10}) - end for -} 'assign - -records: function [historyVar][ - historyVar\record -] - -retrieve: function [historyVar][ - result: last historyVar\record - historyVar\record: chop historyVar\record - return result -] - -current: function [historyVar][ - return last historyVar\record -] - -do [ - h: to :history [] +h: to :history [] +do :: print "Assigning three values: 1, 2, 3..." - h --> 1 - h --> 2 - h --> 3 + h\assign 1 + h\assign 2 + h\assign 3 print "\nHistory (oldest values first):" - print [">" records h] + print [">" h\records] - print ["\nCurrent value is:" current h] + print ["\nCurrent value is:" h\current] print "\nRecalling the three values..." loop 1..3 'x -> - print ["- Recalled:" retrieve h] + print ["- Recalled:" h\retrieve] print "\nHistory:" - print [">" records h] -] + print [">" h\records] diff --git a/Task/History-variables/C/history-variables.c b/Task/History-variables/C/history-variables.c new file mode 100644 index 0000000000..8b26474871 --- /dev/null +++ b/Task/History-variables/C/history-variables.c @@ -0,0 +1,126 @@ +#include +#include +#include + +// +// high address________ +// |________| length +// T *p ---> |___ ____| most recent value +// |____ ___| +// | +// |___ ____ +// |_____ __| +// |________| oldest value +// low address +// + +static size_t hv__align(void const *p, size_t z) { + return z + ((sizeof(z) - (((size_t)p + z) % sizeof(z))) % sizeof(z)); +} + +static size_t hvlen(void const *p, size_t z) { + return *(size_t *)((char *)p + hv__align(p, z)); +} + +static void *hv__malloc(size_t z) { + size_t const m = z + (2 * sizeof(z)); + void *const p = malloc(m); + if(p) { + *(size_t *)((char *)p + hv__align(p, z)) = 1; + return p; + } + perror(""); + abort(); +} + +static void *hv__realloc(void *p, size_t z, size_t n) { + size_t const u = hvlen(p, z); + size_t const o = (n > 1) ? n * z : z; + size_t const g = (u > 1) ? u * z : z; + size_t const m = o + (2 * sizeof(z)); + void *const b = (char *)p - (g - z); + p = realloc(b, m); + if(p) { + p = (char *)p + (o - z); + *(size_t *)((char *)p + hv__align(p, z)) = n; + return p; + } + perror(""); + abort(); +} + +static void *hvfree(void const *p, size_t z) { + if(p) { + size_t u = hvlen(p, z); + size_t const o = (u > 1) ? u * z : z; + free((char *)p - (o - z)); + } + return NULL; +} + +static void *hv(void const *p, size_t z) { + return p ? hv__realloc((void *)p, z, hvlen(p, z) + 1) : hv__malloc(z); +} +#define HV__TYPE(T,V) \ + T: *(T *)(V = (hv)((V), sizeof(*(V)))) +#define hv(V) _Generic(*(V), \ + HV__TYPE( char , (V)), \ + HV__TYPE( short , (V)), \ + HV__TYPE( int , (V)), \ + HV__TYPE( long , (V)), \ + HV__TYPE( long long, (V)), \ + HV__TYPE(unsigned char , (V)), \ + HV__TYPE(unsigned short , (V)), \ + HV__TYPE(unsigned int , (V)), \ + HV__TYPE(unsigned long , (V)), \ + HV__TYPE(unsigned long long, (V)), \ + HV__TYPE(float , (V)), \ + HV__TYPE(double , (V)), \ + HV__TYPE(long double , (V)) \ +) + +static void const *hvundo(void const *p, size_t z) { + return p ? hv__realloc((void *)p, z, hvlen(p, z) - 1) : p; +} +#define hvundo(V) (V = (hvundo)((V), sizeof(*(V)))) + +#define hvfree(V) (hvfree)((V), sizeof(*(V))) +#define hvlen(V) (hvlen)((V), sizeof(*(V))) + +int main(int argc, char **argv) { + char const *c = NULL; + unsigned const *u = NULL; + double const *d = NULL; + hv(c) = '1'; + hv(c) = '2'; + hv(c) = '3'; + hv(u) = 1; + hv(u) = 21; + hvundo(u); + hv(u) = 12; + hv(u) = 123; + hv(d) = 1.23; + hv(d) = 2.31; + hv(d) = 3.12; + printf("current values : '%c', %u, %g", *c, *u, *d); + putchar('\n'); + printf("char value history :"); + for(size_t n = hvlen(c), i = 0; i < n; i++) { + printf(" [%zu] '%c',", i, c[-i]); + } + putchar('\n'); + printf("unsigned value history:"); + for(size_t n = hvlen(u), i = 0; i < n; i++) { + printf(" [%zu] %4u,", i, u[-i]); + } + putchar('\n'); + printf("double value history :"); + for(size_t n = hvlen(d), i = 0; i < n; i++) { + printf(" [%zu] %4g,", i, d[-i]); + } + putchar('\n'); + hvfree(c); + hvfree(u); + hvfree(d); + return 0; +} diff --git a/Task/History-variables/Delphi/history-variables.delphi b/Task/History-variables/Delphi/history-variables.pas similarity index 100% rename from Task/History-variables/Delphi/history-variables.delphi rename to Task/History-variables/Delphi/history-variables.pas diff --git a/Task/History-variables/Elena/history-variables.elena b/Task/History-variables/Elena/history-variables.elena index 437f6ba705..f726d15563 100644 --- a/Task/History-variables/Elena/history-variables.elena +++ b/Task/History-variables/Elena/history-variables.elena @@ -25,7 +25,7 @@ class HistoryVariable undo() { - ifnot (previous.isEmpty()) + if:not (previous.isEmpty()) { value := previous.pop() } @@ -40,7 +40,7 @@ class HistoryVariable string toPrintable() => this value; } -public program() +public Program() { var o := new HistoryVariable(); o.Value := 5; diff --git a/Task/History-variables/FreeBASIC/history-variables.basic b/Task/History-variables/FreeBASIC/history-variables.basic new file mode 100644 index 0000000000..2c61e3f4d2 --- /dev/null +++ b/Task/History-variables/FreeBASIC/history-variables.basic @@ -0,0 +1,60 @@ +REM integer history variable + +Type HistoryInt + As Integer Ptr values + As Integer cnt + As Integer capacity +End Type + +Function InitHistory() As HistoryInt Ptr + Dim As HistoryInt Ptr hist = Allocate(Sizeof(HistoryInt)) + hist->capacity = 10 + hist->values = Allocate(hist->capacity * Sizeof(Integer)) + hist->cnt = 0 + Return hist +End Function + +Sub SetInt(hist As HistoryInt Ptr, value As Integer) + If hist->cnt >= hist->capacity Then + hist->capacity *= 2 + hist->values = Reallocate(hist->values, hist->capacity * Sizeof(Integer)) + End If + + If hist->cnt = 0 Then + hist->values[hist->cnt] = 0 + hist->cnt += 1 + End If + + hist->values[hist->cnt] = value + hist->cnt += 1 +End Sub + +Sub ShowHistory(hist As HistoryInt Ptr) + For i As Integer = 0 To hist->cnt - 1 + Print hist->values[i] + Next +End Sub + +Function UndoInt(hist As HistoryInt Ptr) As Integer + If hist->cnt <= 1 Then Return hist->values[0] + hist->cnt -= 1 + Return hist->values[hist->cnt - 1] +End Function + +' Main program +Randomize Timer +Dim As HistoryInt Ptr x = InitHistory() + +For i As Integer = 0 To 3 + SetInt(x, Int(Rnd * 50) + 100) +Next + +Print "x history:" +ShowHistory(x) +Print + +For i As Integer = 0 To 3 + Print "undo, x ="; UndoInt(x) +Next + +Sleep diff --git a/Task/History-variables/Icon/history-variables.icon b/Task/History-variables/Icon/history-variables.icon new file mode 100644 index 0000000000..d19277f3a6 --- /dev/null +++ b/Task/History-variables/Icon/history-variables.icon @@ -0,0 +1,22 @@ +procedure main(A) + \A := ["cat","hat",7] + x := history() + every x.set(!A) + write("x current value is: ",x.val()) + write("Number of saved values is: ",x.size()) + writes("3 most recent x values from newest to oldest: ") + every writes(" ",x.gen()\3) + write() + while write("x value was: ",\x.get()) + write("Number of saved values is now: ",x.size()) +end + +class history(x) + method size(); return *x; end + method val(); return x[-1]; end + method set(v); put(x,v); end + method get(); return pull(x); end + method gen(); suspend x[*x to 1 by -1]; end +initially + x := [] +end diff --git a/Task/History-variables/Julia/history-variables.julia b/Task/History-variables/Julia/history-variables.jl similarity index 100% rename from Task/History-variables/Julia/history-variables.julia rename to Task/History-variables/Julia/history-variables.jl diff --git a/Task/History-variables/Kotlin/history-variables.kotlin b/Task/History-variables/Kotlin/history-variables.kts similarity index 100% rename from Task/History-variables/Kotlin/history-variables.kotlin rename to Task/History-variables/Kotlin/history-variables.kts diff --git a/Task/History-variables/OCaml/history-variables.ocaml b/Task/History-variables/OCaml/history-variables.ml similarity index 100% rename from Task/History-variables/OCaml/history-variables.ocaml rename to Task/History-variables/OCaml/history-variables.ml diff --git a/Task/History-variables/Phix/history-variables-1.phix b/Task/History-variables/Phix/history-variables-1.phix index 0d84745f09..8270fe1bbe 100644 --- a/Task/History-variables/Phix/history-variables-1.phix +++ b/Task/History-variables/Phix/history-variables-1.phix @@ -1,15 +1,13 @@ ---> - without js -- (desktop/Phix only) - sequence history = {} +without js -- (desktop/Phix only) +sequence history = {} - type hvt(object o) - history = append(history,o) - return true - end type +type hv(object o) + history = append(history,o) + return true +end type - hvt test = 1 - test = 2 - test = 3 - ?{"current",test} - ?{"history",history} - - -- history.e - sequence histories = {} +-- history.e +sequence histories = {} - global function new_history_id(object v) - histories = append(histories,{v}) - return length(histories) - end function +global function new_history_id(object v) + histories = append(histories,{v}) + return length(histories) +end function - global procedure set_hv(integer hv, object v) - histories[hv] = append(histories[hv],v) - end procedure +global procedure set_hv(integer hv, object v) + histories[hv] = append(histories[hv],v) +end procedure - global function get_hv(integer hv) - return histories[hv][$] - end function +global function get_hv(integer hv) + return histories[hv][$] +end function - global function get_hv_full_history(integer hv) - return histories[hv] - end function - - include history.e +with javascript_semantics +include history.e - constant test2 = new_history_id(1) - set_hv(test2, 2) - set_hv(test2, 3) - ?{"current",get_hv(test2)} - ?{"history",get_hv_full_history(test2)} - - with javascript_semantics - requires("1.0.0") - include mpfr.e +with javascript_semantics +requires("1.0.0") -- mpz_pollard_rho +include mpfr.e - procedure test(integer n) - string s = sprintf("%d",n), lastp = "" - sequence res = {s} - atom t0 = time() - while true do - s = substitute(s,"_","") - sequence rr = mpz_pollard_rho(s,true) - if length(rr)=1 then exit end if - s = join(rr,"_") - res = append(res,s) - end while - atom t = time()-t0 - integer niter = length(res)-1 - string iter = iff(niter>1?sprintf("(%d)",niter):""), - e = iff(t>0.1?" ["&elapsed(t)&"]":"") - s = sprintf("HP%d%s = ",{n,iter}) - if niter=0 then - printf(1,"%s%d %s\n",{s,n,e}) - else - for i=2 to niter do - niter -= 1 - printf(1,"%sHP%s(%d)\n",{s,res[i],niter}) - if i=2 then - s = repeat(' ',length(s)) - s[-2] = '=' - end if - end for - printf(1,"%s%s %s\n",{s,res[$],e}) - end if - end procedure - papply(tagset(20,2)&65,test) - - without js -- (system_exec, file i/o) - constant tmp = "hostname.txt", - cmd = iff(platform()=WINDOWS?"hostname":"uname -n") - {} = system_exec(sprintf("%s > %s",{cmd,tmp}),4) - string host = trim(get_text(tmp)) - {} = delete_file("hostname.txt") - ?host -(encode dictionary, decode dictionary) // build the tree, which is a list of lists of ... tree:=ft.pump(List,fcn([(c,cnt)]){ //-->L( (cnt, ((sym,code))), ...) L(cnt, L(L(c,""))) - }).copy(); // make it writable + }).copy(); // make it writable while(tree.len()>1){ // fake up a [lame] priorty queue tree=tree.sort(fcn(a,b){ a[0]>b[0] }); //prioritize high to low - a,b:=tree.pop(-2,2); //remove 2 least frequent symbols - mc:=fcn(n,c){ n[1] = c + n[1]; }; //(sym,code),"0"|"1" + a,b:=tree.pop(-2,2); //remove 2 least frequent symbols + mc:=fcn(n,c){ n[1] = c + n[1]; }; //(sym,code),"0"|"1" a[1].apply2(mc,"0"); b[1].apply2(mc,"1"); // mc(a[1],"0") tree.append( L(a[0]+b[0],a[1].extend(b[1])) ); //(a,b)-->new node }//-->L(L(39, L( L(" ","000"),L("e","0010"),L("a","0011") ... tree=tree[0][1].pump(List,fcn(i){ // flatten rather than traverse - if(T.isType(i))return(Void.Recurse,i,self.fcn); i }); + if(T.isType(i))return(Void.Recurse,i,self.fcn); i }); encodeTable:=tree.toDictionary(); // symbol:Huffman code decodeTable:=encodeTable.pump(Dictionary(),"reverse"); // code:symbol return(encodeTable,decodeTable); diff --git a/Task/Humble-numbers/ALGOL-68/humble-numbers.alg b/Task/Humble-numbers/ALGOL-68/humble-numbers.alg index 09ce86b2ae..b0a103ca81 100644 --- a/Task/Humble-numbers/ALGOL-68/humble-numbers.alg +++ b/Task/Humble-numbers/ALGOL-68/humble-numbers.alg @@ -17,10 +17,10 @@ BEGIN # find some Humble numbers - numbers with no prime factors above 7 # INT m = min( min( min( p2, p3 ), p5 ), p7 ); h[ n ] := m; IF n <= max shown humble THEN print( ( " ", whole( m, 0 ) ) ) FI; - IF m = p2 THEN p2 := 2 * h[ last2 := last2 + 1 ] FI; - IF m = p3 THEN p3 := 3 * h[ last3 := last3 + 1 ] FI; - IF m = p5 THEN p5 := 5 * h[ last5 := last5 + 1 ] FI; - IF m = p7 THEN p7 := 7 * h[ last7 := last7 + 1 ] FI; + IF m = p2 THEN p2 := 2 * h[ last2 +:= 1 ] FI; + IF m = p3 THEN p3 := 3 * h[ last3 +:= 1 ] FI; + IF m = p5 THEN p5 := 5 * h[ last5 +:= 1 ] FI; + IF m = p7 THEN p7 := 7 * h[ last7 +:= 1 ] FI; h count[ IF m < 10 THEN 1 ELIF m < 100 THEN 2 ELIF m < 1 000 THEN 3 diff --git a/Task/Humble-numbers/Ada/humble-numbers.ada b/Task/Humble-numbers/Ada/humble-numbers.adb similarity index 100% rename from Task/Humble-numbers/Ada/humble-numbers.ada rename to Task/Humble-numbers/Ada/humble-numbers.adb diff --git a/Task/Humble-numbers/Agena/humble-numbers.agena b/Task/Humble-numbers/Agena/humble-numbers.agena new file mode 100644 index 0000000000..cddec65d4a --- /dev/null +++ b/Task/Humble-numbers/Agena/humble-numbers.agena @@ -0,0 +1,32 @@ +scope # find some Humble numbers - numbers with no prime factors above 7 + local constant maxHumble, constant maxShownHumble := 2048, 50; + local h, hCount := seq(), [ 0, 0, 0, 0, 0, 0 ]; hCount[ 0 ] := 0; + local p2, p3, p5, p7 := 2, 3, 5, 7; + local last2, last3, last5, last7 := 1, 1, 1, 1; + # 1 is the first humble number ( 2^0 * 3^0 * 5^0 * 7^0 ) and has 1 digit + h[ 1 ], hCount[ 1 ] := 1, 1; + io.write( "1" ); + for n from 2 to maxHumble do + # the next humble number is the lowest of the next multiples of 2, 3, 5, 7 + local constant m := math.min( p2, p3, p5, p7 ); + h[ n ] := m; + if n <= maxShownHumble then io.write( " ", m ) fi; + if m = p2 then last2 +:= 1; p2 := 2 * h[ last2 ] fi; + if m = p3 then last3 +:= 1; p3 := 3 * h[ last3 ] fi; + if m = p5 then last5 +:= 1; p5 := 5 * h[ last5 ] fi; + if m = p7 then last7 +:= 1; p7 := 7 * h[ last7 ] fi; + hCount[ if m < 10 then 1 + elif m < 100 then 2 + elif m < 1_000 then 3 + elif m < 10_000 then 4 + elif m < 100_000 then 5 + elif m < 1_000_000 then 6 + else 0 + fi + ] +:= 1 + od; + print(); + for i to 6 do + printf( "There are %4d Humble numbers with %d digits\n", hCount[ i ], i ) + od +end diff --git a/Task/Humble-numbers/Crystal/humble-numbers-1.crystal b/Task/Humble-numbers/Crystal/humble-numbers-1.cr similarity index 100% rename from Task/Humble-numbers/Crystal/humble-numbers-1.crystal rename to Task/Humble-numbers/Crystal/humble-numbers-1.cr diff --git a/Task/Humble-numbers/Crystal/humble-numbers-2.crystal b/Task/Humble-numbers/Crystal/humble-numbers-2.cr similarity index 100% rename from Task/Humble-numbers/Crystal/humble-numbers-2.crystal rename to Task/Humble-numbers/Crystal/humble-numbers-2.cr diff --git a/Task/Humble-numbers/EasyLang/humble-numbers.easy b/Task/Humble-numbers/EasyLang/humble-numbers.easy index 294a66c460..adc26578a1 100644 --- a/Task/Humble-numbers/EasyLang/humble-numbers.easy +++ b/Task/Humble-numbers/EasyLang/humble-numbers.easy @@ -1,19 +1,9 @@ fastfunc humble i . - if i <= 1 - return 1 - . - if i mod 2 = 0 - return humble (i / 2) - . - if i mod 3 = 0 - return humble (i / 3) - . - if i mod 5 = 0 - return humble (i / 5) - . - if i mod 7 = 0 - return humble (i / 7) - . + if i <= 1 : return 1 + if i mod 2 = 0 : return humble (i / 2) + if i mod 3 = 0 : return humble (i / 3) + if i mod 5 = 0 : return humble (i / 5) + if i mod 7 = 0 : return humble (i / 7) return 0 . fastfunc next_humble n . @@ -26,14 +16,11 @@ fastfunc next_humble n . len arr[] 9 while cnt < 5193 n = next_humble n - arr[log10 n + 1] += 1 + idx = floor (log n 10 + 1) + arr[idx] += 1 cnt += 1 - if cnt <= 50 - write n & " " - . + if cnt <= 50 : write n & " " . print "" print "" -for i to 9 - print arr[i] & " with " & i & " digits" -. +for i to 9 : print arr[i] & " with " & i & " digits" diff --git a/Task/Humble-numbers/Fortran/humble-numbers.f b/Task/Humble-numbers/Fortran/humble-numbers.f new file mode 100644 index 0000000000..84ed5074c5 --- /dev/null +++ b/Task/Humble-numbers/Fortran/humble-numbers.f @@ -0,0 +1,81 @@ +! Humble Numbers +! tested with GNU Fortran (Ubuntu 14.2.0-19ubuntu2) 14.2.0 on Kubuntu 25.04 +! +! Note that both intel ifx and VSI Fortran do not compile this code because they cannot +! deal with 16-byte-integers. +! +! U.B., July 2025 +! + + +program humbleNumbers + +implicit none + +integer, parameter :: int_kind = 16 ! Fortran compilers other than gfortran can't handle this +integer, parameter :: printLimit = 50 ! need to print first 50 humble numbers + +integer :: max_digits = 38 ! (signed) Integer(kind=16) can carry 38 digits +integer, parameter :: maxhSize=1160000 ! array size for all stored humble numbers +integer (kind=int_kind) :: humble ( maxhSize ) ! the humble numbers +integer :: usedH = 1 ! highest index into humble +integer (kind=int_kind) :: powersOf2=2, powersOf3=3,powersOf5=5,powersOf7=7,currentHumble=2, lim=10 +integer :: i=1, j=1,k=1,m=1,lastCount=0,d=1 + +humble (1) = 1 + +do while (.true.) + + usedH = usedH + 1 + if (usedH .le. maxhSize) then ! B sure we dont crash. + humble (usedH) = currentHumble + else + exit ! otherwise terminate. + endif + + ! construct next humble number as 2^i* 3^j * 5^k * 7^m + ! + ! What comes next? + if (currentHumble .eq. powersOf2) then + i = i + 1 + powersOf2 = humble (i) * 2 + endif + if (currentHumble .eq. powersOf3) then + j = j + 1 + powersOf3 = humble (j) * 3 + endif + if (currentHumble .eq. powersOf5) then + k = k + 1 + powersOf5 = humble (k) * 5 + endif + if (currentHumble .eq. powersOf7) then + m = m + 1 + powersOf7 = humble (m) * 7 + endif + currentHumble = powersOf2 + + ! Select next larger humble number + if (powersOf3=lim) then ! another digit ? + write (6, '(I0, " digits: ", i0)') d, usedH -lastCount + lastCount = usedH + d = d + 1 + + if (d .gt. max_digits) then ! Maximum number of digits reached, terminate. + exit + endif + lim = lim * 10 ! to detect next larger number of digits + endif +enddo + +write (6, '(/"total = ", I0 )') usedH +write (6,'(/"The first " ,I0, " humble numbers are:" )') printLimit +do i=1,printLimit + write (6,'(X, I0)', advance='no') humble (i) +enddo +write (6,*) ! terminate last output line. + +end program humbleNumbers diff --git a/Task/Humble-numbers/Icon/humble-numbers.icon b/Task/Humble-numbers/Icon/humble-numbers.icon new file mode 100644 index 0000000000..9788c9eba9 --- /dev/null +++ b/Task/Humble-numbers/Icon/humble-numbers.icon @@ -0,0 +1,40 @@ +global count + +procedure main(A) + limit1 := \A[1] | 50 + limit2 := \A[2] | 1000 + showcounts(humbles(limit1, limit2)) +end + +procedure humbles(limit1,limit2) + scounts := table(0) + every (count := 0, n := genhumbles()\limit2, count +:= 1, x := *n) do { + if 0 < (limit1 -:= 1) then writes(" ",n) + else if 0 = limit1 then write(" ",n) + scounts[x] +:= 1 + } + return scounts +end + +procedure genhumbles() + suspend 1 + p := [2,3,5,7] + l := [0,0,0,0] + ch := [] + every n := seq() do { + suspend m := min(p[1],p[2],p[3],p[4]) + put(ch, m) + if m = p[1] then p[1] := 2*ch[l[1] +:= 1] + if m = p[2] then p[2] := 3*ch[l[2] +:= 1] + if m = p[3] then p[3] := 5*ch[l[3] +:= 1] + if m = p[4] then p[4] := 7*ch[l[4] +:= 1] + } +end + +procedure showcounts(counts) + write("\nOut of the first ",count," humble numbers:\n") + write(" length ",center("count",16)) + write(" ",repl("-",5)," ",repl("-",16)) + every p := !sort(counts) do + write(right(p[1],7)," ",right(p[2],16)) +end diff --git a/Task/Humble-numbers/Julia/humble-numbers.julia b/Task/Humble-numbers/Julia/humble-numbers.jl similarity index 100% rename from Task/Humble-numbers/Julia/humble-numbers.julia rename to Task/Humble-numbers/Julia/humble-numbers.jl diff --git a/Task/Humble-numbers/Kotlin/humble-numbers.kotlin b/Task/Humble-numbers/Kotlin/humble-numbers.kts similarity index 100% rename from Task/Humble-numbers/Kotlin/humble-numbers.kotlin rename to Task/Humble-numbers/Kotlin/humble-numbers.kts diff --git a/Task/Humble-numbers/Maxima/humble-numbers.maxima b/Task/Humble-numbers/Maxima/humble-numbers.maxima new file mode 100644 index 0000000000..a9f5e2d00a --- /dev/null +++ b/Task/Humble-numbers/Maxima/humble-numbers.maxima @@ -0,0 +1,13 @@ +factors_only: true$ +is_humble(n) := length(sublist(ifactors(n), lambda([x], x>7)))=0$ + +block(count: 0, n: 1, while(count<50) do( + if is_humble(n) then block( + sprint(n), + count: count+1, + if mod(count, 10)=0 then newline() + ), + n: n+1))$ + +humble_digits(n) := length(sublist(makelist(i, i, 10^(n-1), (10^n)-1), is_humble))$ +map(humble_digits, makelist(i, i, 1, 6)); diff --git a/Task/Humble-numbers/PascalABC.NET/humble-numbers.pas b/Task/Humble-numbers/PascalABC.NET/humble-numbers.pas new file mode 100644 index 0000000000..4ea1f2542b --- /dev/null +++ b/Task/Humble-numbers/PascalABC.NET/humble-numbers.pas @@ -0,0 +1,25 @@ +## +function humbles: sequence of uint64; +begin + var s := hset(uint64(1)); + while True do + begin + var m := s.min; + yield m; + s -= m; + foreach var k in |2, 3, 5, 7| do s += k * m; + end; +end; + +println('The first 50 humble numbers are:'); +foreach var n in humbles.Take(50) index i do + write(n:4, if i mod 10 = 9 then #10 else ''); + +println; +println('Digits Count'); +for var dig := 1 to 18 do +begin + var count := humbles.SkipWhile(x -> x < 10 ** (dig - 1)) + .TakeWhile(x -> x < 10 ** dig).Count; + writeln(dig:2, count:10); +end; diff --git a/Task/Humble-numbers/Pluto/humble-numbers.pluto b/Task/Humble-numbers/Pluto/humble-numbers.pluto new file mode 100644 index 0000000000..faca83857a --- /dev/null +++ b/Task/Humble-numbers/Pluto/humble-numbers.pluto @@ -0,0 +1,31 @@ +do -- find some Humble numbers - numbers with no prime factors above 7 + local maxHumble , maxShownHumble = 2048, 50 + local h, hCount = {}, { [0] = 0, 0, 0, 0, 0, 0, 0 } + local p2, p3, p5, p7 = 2, 3, 5, 7 + local last2, last3, last5, last7 = 1, 1, 1, 1 + -- 1 is the first humble number ( 2^0 * 3^0 * 5^0 * 7^0 ) and has 1 digit + h[ 1 ], hCount[ 1 ] = 1, 1 + io.write( "1" ) + for n = 2, maxHumble do + -- the next humble number is the lowest of the next multiples of 2, 3, 5, 7 + local m = math.min( p2, p3, p5, p7 ) + h[ n ] = m + if n <= maxShownHumble then io.write( " ", m ) end + if m == p2 then last2 += 1 p2 = 2 * h[ last2 ] end + if m == p3 then last3 += 1 p3 = 3 * h[ last3 ] end + if m == p5 then last5 += 1 p5 = 5 * h[ last5 ] end + if m == p7 then last7 += 1 p7 = 7 * h[ last7 ] end + hCount[ ( m < 10 ) ? 1 + : ( m < 100 ) ? 2 + : ( m < 1_000 ) ? 3 + : ( m < 10_000 ) ? 4 + : ( m < 100_000 ) ? 5 + : ( m < 1_000_000 ) ? 6 + : 0 + ] += 1 + end + io.write( "\n" ) + for i = 1, 6 do + io.write( string.format( "There are %4d Humble numbers with %d digits\n", hCount[ i ], i ) ) + end +end diff --git a/Task/Humble-numbers/R/humble-numbers.r b/Task/Humble-numbers/R/humble-numbers.r new file mode 100644 index 0000000000..328aa77434 --- /dev/null +++ b/Task/Humble-numbers/R/humble-numbers.r @@ -0,0 +1,16 @@ +next_humble <- function(n) nextn(n, c(2,3,5,7)) +humblenums <- function(n) Reduce(function(x, f) 1+f(x), + rep(list(next_humble),n-1), + init=2, + accumulate=TRUE)-1 + +humblenums(50) + +humble_digits <- function(n){ + digcounts <- rle(floor(log10(humblenums(n))))$lengths + for(i in seq_along(digcounts[-1])){ + cat("There are", digcounts[i], "humble numbers with", i, "digit(s)", "\n") + } +} + +humble_digits(5000) diff --git a/Task/Humble-numbers/REXX/humble-numbers.rexx b/Task/Humble-numbers/REXX/humble-numbers.rexx index c4f9c240cd..3a4ca3c7dd 100644 --- a/Task/Humble-numbers/REXX/humble-numbers.rexx +++ b/Task/Humble-numbers/REXX/humble-numbers.rexx @@ -1,44 +1,46 @@ -/*REXX program computes and displays humble numbers, also will display counts of sizes.*/ -parse arg n m . /*obtain optional arguments from the CL*/ -if n=='' | n=="," then n= 50 /*Not specified? Then use the default.*/ -if m=='' | m=="," then m= 60 /* " " " " " " */ -numeric digits 1 + max(20, m) /*be able to handle some big numbers. */ -$.= 0 /*a count array for X digit humble #s*/ -call humble n; list= /*call HUMBLE sub; initialize the list.*/ - do j=1 for n; list= list @.j /*append a humble number to the list.*/ - end /*j*/ +-- 23 Aug 2025 +include Setting -if list\='' then do; say "A list of the first " n ' humble numbers are:' - say strip(list) /*elide the leading blank in the list. */ - end +say 'HUMBLE NUMBERS' +say version say -call humble -m /*invoke subroutine for counting nums. */ -if $.1==0 then exit /*if no counts, then we're all finished*/ -total= 0 /*initialize count of humble numbers. */ -$.1= $.1 + 1 /*adjust count for absent 1st humble #.*/ -say ' The digit counts of humble numbers:' -say ' ═════════════════════════════════════════' - do c=1 while $.c>0; s= left('s', length($.c)>1) /*count needs pluralization?*/ - say right( commas($.c), 30) ' have ' right(c, 2) " digit"s - total= total + $.c /* ◄─────────────────────────────────┐ */ - end /*k*/ /*bump humble number count (so far)──┘ */ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -commas: procedure; arg _; do i=length(_)-3 to 1 by -3; _=insert(',', _, i); end; return _ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -humble: procedure expose @. $.; parse arg x; if x==0 then return - y= abs(x); a= y; noCount= x>0; if x<0 then y= 999999999 - #2= 1; #3= 1; #5= 1; #7= 1 /*define the initial humble constants. */ - $.= 0; @.= 0; @.1= 1 /*initialize counts and humble numbers.*/ - do h=2 for y-1 - @.h= min(2*@.#2,3*@.#3,5*@.#5,7*@.#7) /*pick the minimum of 4 humble numbers.*/ - m= @.h /*M: " " " " " " */ - if 2*@.#2 == m then #2 = #2 + 1 /*Is number already defined? Use next #*/ - if 3*@.#3 == m then #3 = #3 + 1 /* " " " " " " "*/ - if 5*@.#5 == m then #5 = #5 + 1 /* " " " " " " "*/ - if 7*@.#7 == m then #7 = #7 + 1 /* " " " " " " "*/ - if noCount then iterate /*Not counting digits? Then iterate. */ - L= length(m); if L>a then leave /*Are we done with counting? Then quit*/ - $.L= $.L + 1 /*bump the digit count for this number.*/ - end /*h*/ /*the humble numbers are in the @ array*/ - return /* " count results " " " $ " */ +call Humbles 50 +call ShowFirstN 50 +call Humbles 10000000 +call ShowDistribution +say Time('e')/1 'seconds' +exit + +ShowFirstN: +procedure expose humb. +arg xx +xx = xx/1 +say 'First' xx 'humble numbers are' +do i = 1 to xx + call Charout ,Right(humb.i,4) + if i//10 = 0 then + say +end +say +return + +ShowDistribution: +procedure expose humb. +say 'Digit distribution for the first' humb.0 'humble numbers' +d. = 0 +do i = 1 to humb.0 + l = Length(humb.i); d.l = d.l + 1; d.0 = Max(l,d.0) +end +l = Copies('-',17) +say l +say 'Dg Count Cum' +say l +c = 0 +do i = 1 to d.0-1 + c = c + d.i + say Right(i,2) Right(d.i,6) Right(c,7) +end +say l +return + +include Math diff --git a/Task/Humble-numbers/Rust/humble-numbers.rs b/Task/Humble-numbers/Rust/humble-numbers.rs new file mode 100644 index 0000000000..839c434188 --- /dev/null +++ b/Task/Humble-numbers/Rust/humble-numbers.rs @@ -0,0 +1,51 @@ +fn num_length( number : u32 ) -> usize { + let numberstring : String = number.to_string( ) ; + let numstr = numberstring.as_str( ) ; + numstr.chars( ).count( ) +} + +fn is_humble( number : u32 ) -> bool { + let result : bool = match number { + num if num <= 1 => true , + num if num % 2 == 0 => is_humble( number / 2 ) , + num if num % 3 == 0 => is_humble( number / 3 ) , + num if num % 4 == 0 => is_humble( number / 4 ) , + num if num % 5 == 0 => is_humble( number / 5 ) , + num if num % 6 == 0 => is_humble( number / 6 ) , + num if num % 7 == 0 => is_humble( number / 7 ) , + _ => false + } ; + result +} + +fn main() { + let mut first_fifty : Vec = Vec::new( ) ; + let mut pairs : Vec<(usize , usize)> = Vec::new( ) ; + let mut oldlength : usize = 0 ; + let mut currentnum : u32 = 1 ; + let mut length : usize = 1 ; + let mut lengthsum : usize = 0 ; + while length < 10 { + if is_humble( currentnum ) { + if first_fifty.len( ) < 50 { + first_fifty.push( currentnum ) ; + } + if length == oldlength { + lengthsum += 1 ; + } + else { + let temp_len : usize = length - 1 ; + pairs.push( (temp_len , lengthsum ) ) ; + lengthsum = 1 ; + oldlength = length ; + } + } + currentnum += 1 ; + length = num_length( currentnum ) ; + } + pairs.push((length - 1 , lengthsum )) ; + println!("{:?}" , first_fifty ) ; + for p in pairs { + println!("length {} with {} humble numbers!" , p.0 , p.1 ) ; + } +} diff --git a/Task/Humble-numbers/V-(Vlang)/humble-numbers.v b/Task/Humble-numbers/V-(Vlang)/humble-numbers.v new file mode 100644 index 0000000000..42182166d6 --- /dev/null +++ b/Task/Humble-numbers/V-(Vlang)/humble-numbers.v @@ -0,0 +1,38 @@ +fn is_humble(i int) bool { + if i <= 1 {return true} + if i % 2 == 0 {return is_humble(i / 2)} + if i % 3 == 0 {return is_humble(i / 3)} + if i % 5 == 0 {return is_humble(i / 5)} + if i % 7 == 0 {return is_humble(i / 7)} + return false +} + +fn main() { + limit := max_i16 + mut humble := map[int]int{} + mut count, mut len, mut total, mut num := 0, 0, 0, 1 + mut str :="" + + for count < limit { + if is_humble(num) == true { + str = num.str() + len = str.len + humble[len]++ + if count < 50 {print("${num} ")} + count++ + } + num++ + } + println("\n") + + println("Of the first ${count} humble numbers:") + num = 1 + for num < humble.len - 1 { + if num in humble { + total = humble[num] + println("${total:5} have ${num:2} digits") + num++ + } + else {break} + } +} diff --git a/Task/Hunt-the-Wumpus/Ada/hunt-the-wumpus-1.ada b/Task/Hunt-the-Wumpus/Ada/hunt-the-wumpus-1.adb similarity index 100% rename from Task/Hunt-the-Wumpus/Ada/hunt-the-wumpus-1.ada rename to Task/Hunt-the-Wumpus/Ada/hunt-the-wumpus-1.adb diff --git a/Task/Hunt-the-Wumpus/Ada/hunt-the-wumpus-2.ada b/Task/Hunt-the-Wumpus/Ada/hunt-the-wumpus-2.adb similarity index 100% rename from Task/Hunt-the-Wumpus/Ada/hunt-the-wumpus-2.ada rename to Task/Hunt-the-Wumpus/Ada/hunt-the-wumpus-2.adb diff --git a/Task/Hunt-the-Wumpus/Ada/hunt-the-wumpus-3.ada b/Task/Hunt-the-Wumpus/Ada/hunt-the-wumpus-3.adb similarity index 100% rename from Task/Hunt-the-Wumpus/Ada/hunt-the-wumpus-3.ada rename to Task/Hunt-the-Wumpus/Ada/hunt-the-wumpus-3.adb diff --git a/Task/Hunt-the-Wumpus/C/hunt-the-wumpus.c b/Task/Hunt-the-Wumpus/C/hunt-the-wumpus.c new file mode 100644 index 0000000000..79b70d3cf7 --- /dev/null +++ b/Task/Hunt-the-Wumpus/C/hunt-the-wumpus.c @@ -0,0 +1,129 @@ +#include +#include +#include + +#define NUM_ROOMS 20 +#define ARROWS 5 + +typedef enum { false, true } bool; + +typedef struct { + int connected[3]; + bool has_wumpus; + bool has_bat; + bool has_pit; +} Room; + +Room cave[NUM_ROOMS + 1]; // Cave rooms are numbered from 1 to 20 + +void initialize_cave() { + int i, j; + // Initialize cave rooms + for (i = 1; i <= NUM_ROOMS; i++) { + for (j = 0; j < 3; j++) { + cave[i].connected[j] = (i + j) % NUM_ROOMS + 1; // Circular connections + } + cave[i].has_wumpus = false; + cave[i].has_bat = false; + cave[i].has_pit = false; + } + // Randomly place wumpus, bats, and pits + cave[rand() % NUM_ROOMS + 1].has_wumpus = true; + for (i = 0; i < 2; i++) { + cave[rand() % NUM_ROOMS + 1].has_bat = true; + cave[rand() % NUM_ROOMS + 1].has_pit = true; + } +} + +void sense(int room) { + printf("You are in room %d.\n", room); + int i, adjacent_room; + for (i = 0; i < 3; i++) { + adjacent_room = cave[room].connected[i]; + if (cave[adjacent_room].has_wumpus) + printf("You smell something terrible nearby.\n"); + if (cave[adjacent_room].has_bat) + printf("You hear a rustling.\n"); + if (cave[adjacent_room].has_pit) + printf("You feel a cold wind blowing from a nearby cavern.\n"); + } +} + +void move(int *room) { + int choice; + printf("Choose an adjacent room to move into: "); + scanf("%d", &choice); + if (choice < 1 || choice > 3) { + printf("Invalid choice. Please choose a number between 1 and 3.\n"); + move(room); + return; + } + *room = cave[*room].connected[choice - 1]; +} + +void shoot(int room, int *arrows, bool *game_over) { + int choice, adjacent_room; + printf("Choose an adjacent room to shoot into: "); + scanf("%d", &choice); + if (choice < 1 || choice > 3) { + printf("Invalid choice. Please choose a number between 1 and 3.\n"); + shoot(room, arrows, game_over); + return; + } + adjacent_room = cave[room].connected[choice - 1]; + if (cave[adjacent_room].has_wumpus) { + printf("Congratulations! You've killed the Wumpus!\n"); + *game_over = true; + return; + } + else { + if (rand() % 4 != 0) { // 75% chance of waking up the wumpus + if (cave[adjacent_room].has_wumpus) { + printf("The Wumpus has woken up and eaten you!\n"); + *game_over = true; + return; + } + } + printf("You missed! The Wumpus is still asleep.\n"); + } + (*arrows)--; +} + +int main() { + srand(time(NULL)); + initialize_cave(); + int current_room = 1; + int arrows = ARROWS; + bool game_over = false; + + printf("Welcome to Hunt the Wumpus!\n"); + + while (!game_over) { + sense(current_room); + printf("Choose your action:\n"); + printf("1. Move to an adjacent room\n"); + printf("2. Shoot into an adjacent room\n"); + + int choice; + printf("Enter your choice (1 or 2): "); + scanf("%d", &choice); + + switch(choice) { + case 1: + move(¤t_room); + break; + case 2: + if (arrows > 0) { + shoot(current_room, &arrows, &game_over); + } else { + printf("You're out of arrows! You lost the game.\n"); + game_over = true; + } + break; + default: + printf("Invalid choice. Please choose 1 or 2.\n"); + } + } + + return 0; +} diff --git a/Task/Hunt-the-Wumpus/EasyLang/hunt-the-wumpus.easy b/Task/Hunt-the-Wumpus/EasyLang/hunt-the-wumpus.easy new file mode 100644 index 0000000000..9fbc981fa3 --- /dev/null +++ b/Task/Hunt-the-Wumpus/EasyLang/hunt-the-wumpus.easy @@ -0,0 +1,92 @@ +exits[][] = [ [ 2 5 8 ] [ 1 3 10 ] [ 2 4 12 ] [ 3 5 14 ] [ 1 4 6 ] [ 5 7 15 ] [ 6 8 17 ] [ 1 7 9 ] [ 8 10 18 ] [ 2 9 11 ] [ 10 12 19 ] [ 2 11 13 ] [ 12 14 20 ] [ 4 13 15 ] [ 6 14 16 ] [ 15 17 20 ] [ 7 16 18 ] [ 9 17 19 ] [ 11 18 20 ] [ 13 16 19 ] ] +len hazard$[] 20 +func emptyRoom . + repeat + room = random 1 20 + until hazard$[room] = "" + . + return room +. +for i to 2 + hazard$[emptyRoom] = "bat" + hazard$[emptyRoom] = "pit" +. +hazard$[emptyRoom] = "wumpus" +# +print "*** HUNT THE WUMPUS ***" +print "-----------------------" +curRoom = emptyRoom +arrows = 5 +func checkWumpus . + if hazard$[curRoom] = "wumpus" + print "You find yourself face to face with the wumpus." + print "It eats you whole." + print "GAME OVER" + return 1 + . +. +repeat + print "You are in room " & curRoom & "." + until checkWumpus = 1 + for r in exits[curRoom][] + if hazard$[r] = "wumpus" : print "You smell something terrible nearby." + if hazard$[r] = "bat" : print "You hear a rustling." + if hazard$[r] = "pit" : print "You feel a cold wind blowing from a nearby cavern." + . + print "Tunnels lead to: " & strjoin exits[curRoom][] ", " + print "You have " & arrows & " arrows." + print "" + repeat + repeat + write "M)ove, S)hoot, or Q)uit? " + in$ = input + print in$ + m$ = substr in$ 1 1 + until m$ = "m" or m$ = "s" or m$ = "q" + . + if m$ = "q" : break 2 + target = number substr in$ 2 99 + if target = 0 + write "Which room? " + target = number input + print target + . + for i to 3 + if exits[curRoom][i] = target : break 1 + . + until i <= 3 + print "Cannot get there from here." + . + if m$ = "m" + curRoom = target + if hazard$[curRoom] = "bat" + print "You have entered the lair of a giant bat." + curRoom = emptyRoom + print "It picks you up and drops you in room " & curRoom & "." + elif hazard$[curRoom] = "pit" + print "The ground gives way beneath your feet." + print "You fall into a deep abyss." + print "GAME OVER" + break 1 + . + else + arrows -= 1 + if hazard$[target] = "wumpus" + print "Congratulations! You shot the wumpus!" + break 1 + . + print "You missed." + if randomf < 0.75 + print "The wumpus wakes from his slumber." + for i to 20 : if hazard$[i] = "wumpus" : hazard$[i] = "" + hazard$[emptyRoom] = "wumpus" + if checkWumpus = 1 : break 1 + . + if arrows = 0 + print "As you grasp at your empty quiver, " + print "you hear a large beast approaching..." + hazard$[curRoom] = "wumpus" + if checkWumpus = 1 : break 1 + . + . +. diff --git a/Task/Hunt-the-Wumpus/FOCAL/hunt-the-wumpus.focal b/Task/Hunt-the-Wumpus/FOCAL/hunt-the-wumpus.focal new file mode 100644 index 0000000000..3308bdd6d1 --- /dev/null +++ b/Task/Hunt-the-Wumpus/FOCAL/hunt-the-wumpus.focal @@ -0,0 +1,213 @@ +1.10 S FOUT(12); C HUNT THE WUMPUS - BY GREGORY YOB, 1973. +1.11 C FOCAL-65 VERSION CONVERTED FROM BASIC SOURCE IN +1.12 C 'CREATIVE COMPUTING' MAGAZINE, SEPT/OCT 1975 +1.20 T %2,!"INSTRUCTIONS (Y-N)? "; S I=FCHR(); T ! +1.30 I (I-78),1.45; +1.40 G 90.1 +1.45 S FRAN(-1); T "SETTING UP CAVE..."! +1.46 C SET UP CAVE (DODECAHEDRAL NODE LIST) +1.47 C FOCAL-65 DOESN'T HAVE DATA/READ STMTS, SO DATA PACKED IN A $ +1.48 C OTHER VERSIONS MAY NEED TO ASSIGN EACH ELEMENT OF S TO S(X) +1.50 S FISL(120,S$); C 60 2-DIG DATA ELEMENTS +1.52 S FODV(S$); C PREPARES S$ FOR INPUT FROM CURRENT OUTPUT DEVICE +1.53 T "020508010310020412030514010406" +1.54 T "050715060817010709081018020911" +1.55 T "101219031113121420041315061416" +1.56 T "151720071618091719111820131619" +1.58 R O; S FIDV(S$),; C RESET OUTPUT DEV., SET S$ AS INPUT DEVICE +1.60 F I=1,60; D 1.8 +1.70 R I; G 2.1 +1.80 S X=FCHR(), X=X-48, S(I)=X*10, X=FCHR(), X=X-48, S(I)=S(I)+X +1.90 R + +2.10 C LOCATE L ARRAY ITEMS: 1-YOU,2-WUMPUS,3&4-PITS,5&6-BATS +2.20 F J=1,6; S L(J)=FINT(FRAN(0)*20)+1, M(J)=L(J) +2.22 C CHECK FOR CROSSOVERS (IE L(1)=L(2), ETC) +2.25 S J=1 +2.27 S K=1 +2.30 I (J-K),2.5; +2.40 I (L(J)-L(K)),2.2; C IF L(J)=L(K), RESET +2.50 S K=K+1; I (K-6)2.52,2.52,2.56 +2.52 G 2.3 +2.56 S J=J+1; I (J-6)2.27,2.27; + +2.60 C SET ARROWS, RUN GAME +2.70 S A=5, L=L(1) + +3.10 T "HUNT THE WUMPUS"! +3.20 C HAZARD WARNINGS & LOCATION +3.30 G 20.1 + +4.05 C MOVE OR SHOOT +4.10 D 25 +4.20 I (I),4.3,4.8 +4.30 G 30.1; C SHOOT +4.50 I (G)5.1,3.3,5.5 +4.80 G 40.1; C MOVE +4.90 I (G),3.3,5.5 + +5.09 C LOSE +5.10 T "HA HA HA - YOU LOSE!"!; G 5.6 +5.40 C WIN +5.50 T "HEE HEE HEE - THE WUMPUS'LL GETCHA NEXT TIME!!"! +5.60 F J=1,6; S L(J)=M(J) +5.70 T "PLAY AGAIN (Y-N)? ";S I=FCHR(); T ! +5.80 I (I-89)7.1,5.9,7.1 +5.90 T "SAME SETUP (Y-N)? ";S I=FCHR(); T !"STAND BY..."! +6.10 I (I-89)2.2,2.7,2,2 + +7.10 Q + +20.05 C - PRINT LOCATION & HAZARD WARNING +20.10 S J=2 +20.12 I (J-7),21.3; +20.20 S K=1 +20.30 S T=(L(1)-1)*3+K +20.40 I (S(T)-L(J))20.9,20.5,20.9 +20.50 I (J-2),20.6; +20.52 I (J-3),20.7; +20.53 I (J-4),20.7; +20.54 I (J-5),20.8; +20.55 I (J-6),20.8; +20.60 T "I SMELL A WUMPUS!"!; G 20.9 +20.70 T "I FEEL A DRAFT."!; G 20.9 +20.80 T "BATS NEARBY!"! +20.90 S K=K+1; I (K-3)20.3,20.3; +20.92 S J=J+1; G 20.12 + +21.30 T "YOU ARE IN ROOM ",L(1),!; S T=(L(1)-1)*3 +21.40 T "TUNNELS LEAD TO ",S(T+1)," ",S(T+2)," ",S(T+3) +21.50 T !! +21.60 G 4.1 + +25.05 C - CHOOSE OPTION *** +25.10 T "SHOOT OR MOVE (S-M)? " +25.20 S I=FCHR(); T !; I (I-77),25.4; +25.30 I (I-83)25.1,25.5,25.1 +25.40 S I=1; R +25.50 S I=0; R + +30.01 C - ARROW ROUTINE +30.10 S G=0 +30.20 C - PATH OF ARROW +30.30 S L=L(1) +30.40 T "NO. OF ROOMS (1-5)? "; A J7 +30.50 I (J7-1)30.4; +30.60 I (J7-5),,30.4 +30.70 S K=1 +30.80 T "ROOM #? "; A P(K) +30.90 I (K-2)31.15,31.15; +31.05 I (P(K)-P(K-2))31.15,,31.15 +31.10 T ""ARROWS AREN'T THAT CROOKED - TRY ANOTHER ROOM."!; G 30.8 +31.15 S K=K+1; I (K-J7)30.8,30.8; + +31.20 C - SHOOT ARROW +31.30 C S L=L(1) <- NOT IN 'MORE BASIC COMP GMS' +31.40 S K=1 +31.50 S K1=1 +31.60 S T=((L-1)*3)+K1; I (S(T)-P(K)),32.95; +31.70 S K1=K1+1; I (K1-3)31.6,31.6; +31.80 C - NO TUNNEL FOR ARROW +31.90 S T=FINT(FRAN(0)*3)+1, L=S(((L-1)*3)+T) +32.01 G 33.1 +32.10 S K=K+1; I (K-J7)31.5,31.5; +32.20 T "MISSED."!; S L=L(1) +32.30 C - MOVE WUMPUS +32.40 S B=-1; G 33.7; C D 33.7 +32.50 C - AMMO CHECK +32.60 S A=A-1; I (A),,32.8 +32.70 S G=-1 +32.80 G 4.5 + +32.90 C - SEE IF ARROW IS AT L(1) OR AT L(2) +32.95 S L=P(K) +33.10 I (L-L(2))33.4,,33.4 +33.15 T "AHA! YOU GOT THE WUMPUS!"! +33.20 S G=1; G 4.5 +33.40 I (L-L(1))32.1,,32.1 +33.50 T "OUCH! ARROW GOT YOU!"!; G 32.7 + +33.70 C - MOVE WUMPUS ROUTINE +33.72 S K=FINT(FRAN(0)*4)+1 +33.74 I (K-4),33.78 +33.76 S T=((L(2)-1)*3)+K, L(2)=S(T) +33.78 I (L(2)-L)33.9,,33.9 +33.80 T "TSK TSK TSK - WUMPUS GOT YOU!"! +33.85 S G=-1 +33.90 I (B)32.6,41.9; + +40.01 C - MOVE ROUTINE +40.10 S G=0 +40.20 T "WHERE TO? "; A L +40.30 I (L-1)40.2; +40.40 I (L-20),,40.2 +40.50 C - CHECK IF LEGAL MOVE +40.60 S K=1 +40.70 S T=L(1)-1, T=T*3+K +40.75 I (S(T)-L),41.3; +40.80 S K=K+1; I (K-3)40.7,40.7; +40.90 I (L-L(1)),41.3; +41.10 T "NOT POSSIBLE - " +41.15 G 40.2 +41.20 C - CHECK FOR HAZARDS +41.30 S L(1)=L +41.40 C - WUMPUS *** +41.50 I (L-L(2))42.15,,42.15 +41.60 T "... OOPS! BUMPED A WUMPUS!"! +41.70 C - MOVE WUMPUS +41.80 S B=0; G 33.7; C D 33.7 +41.90 I (G),42.2; +42.10 C - PIT +42.15 I (L-L(3))42.2,42.3,42.2 +42.20 I (L-L(4))42.7,42.3,42.7 +42.30 T "YYYYIIIIEEEE . . . FELL IN PIT!"! +42.40 S G=-1; G 4.9 +42.60 C - BATS +42.70 I (L-L(5))42.75,42.8,42.75 +42.75 I (L-L(6))43.1,42.8,43.1 +42.80 T "ZAP--SUPER BAT SNATCH! ELSEWHEREVILLE FOR YOU!"! +42.90 S L=FINT(FRAN(0)*20)+1 +43.05 G 41.3 +43.10 G 4.9 + +50.10 Q + +90.05 C - INSTRUCTIONS +90.10 T "WELCOME TO 'HUNT THE WUMPUS'"! +90.20 T " THE WUMPUS LIVES IN A CAVE OF 20 ROOMS. EACH ROOM"! +90.30 T "HAS 3 TUNNELS LEADING TO OTHER ROOMS. (LOOK AT A"! +90.40 T "DODECAHEDRON TO SEE HOW THIS WORKS-IF YOU DON'T KNOW"! +90.50 T "WHAT A DODECAHEDRON IS, ASK SOMEONE)"!! +90.70 T " HAZARDS:"! +90.80 T " BOTTOMLESS PITS - TWO ROOMS HAVE BOTTOMLESS PITS IN THEM."! +90.90 T " IF YOU GO THERE, YOU FALL INTO THE PIT (& LOSE!)."! +90.95 T " SUPER BATS - TWO OTHER ROOMS HAVE SUPER BATS. IF YOU"! +91.10 T " GO THERE, A BAT GRABS YOU AND TAKES YOU TO SOME OTHER"! +91.20 T " ROOM AT RANDOM (WHICH MAY BE TROUBLESOME)."!! +91.40 T " WUMPUS:"! +91.50 T " THE WUMPUS IS NOT BOTHERED BY HAZARDS (HE HAS SUCKER"! +91.60 T " FEET AND IS TOO BIG FOR A BAT TO LIFT). USUALLY"! +91.70 T " HE IS ASLEEP. TWO THINGS WAKE HIM UP: YOU ENTERING HIS"! +91.80 T " ROOM OR YOU SHOOTING AN ARROW."! +91.90 T " IF THE WUMPUS WAKES, HE MOVES (P=.75) ONE ROOM"! +92.10 T " OR STAYS STILL (P=.25). AFTER THAT, IF HE IS WHERE YOU"! +92.20 T " ARE, HE EATS YOU UP AND YOU LOSE!"!! +92.25 T "(PRESS ANY KEY TO CONTINUE)"; S Z=FCHR(); T !! +92.30 T " YOU:"! +92.40 T " EACH TURN YOU MAY MOVE OR SHOOT A CROOKED ARROW."! +92.50 T " MOVING: YOU CAN MOVE ONE ROOM (THRU ONE TUNNEL)."! +92.60 T " ARROWS: YOU HAVE 5 ARROWS. YOU LOSE WHEN YOU RUN OUT."! +92.70 T " EACH ARROW CAN GO FROM 1 TO 5 ROOMS. YOU AIM BY TELLING"! +92.80 T " THE COMPUTER THE ROOM #S YOU WANT THE ARROW TO GO TO."! +92.90 T " IF THE ARROW CAN'T GO THAT WAY (IF NO TUNNEL) IT MOVES"! +93.10 T " AT RANDOM TO THE NEXT ROOM."! +93.20 T " IF THE ARROW HITS THE WUMPUS, YOU WIN."! +93.30 T " IF THE ARROW HITS YOU, YOU LOSE."!! +93.40 T " WARNINGS:"! +93.50 T " WHEN YOU ARE ONE ROOM AWAY FROM A WUMPUS OR HAZARD,"! +93.60 T " THE COMPUTER SAYS:"! +93.70 T " WUMPUS: 'I SMELL A WUMPUS'"! +93.80 T " BAT : 'BATS NEARBY'"! +93.90 T " PIT : 'I FEEL A DRAFT'"!! +94.05 T "(PRESS ANY KEY TO BEGIN)"; S Z=FCHR(); T !! +94.10 G 1.45 diff --git a/Task/Hunt-the-Wumpus/Forth/hunt-the-wumpus.fth b/Task/Hunt-the-Wumpus/Forth/hunt-the-wumpus.fth new file mode 100644 index 0000000000..77842adb0d --- /dev/null +++ b/Task/Hunt-the-Wumpus/Forth/hunt-the-wumpus.fth @@ -0,0 +1,733 @@ +\ Hunt the Wumpus - FORTH - v 1.00 + +: wumpus-version ( -- ) + ." Version 1.00 - FORTH " + ; + +[DEFINED] UTIME [IF] ( -- Dusec ) + : MS@ UTIME DROP ; \ gforth +[ELSE] +[DEFINED] counter [IF] + : MS@ counter ; \ SwiftForth +[THEN] [THEN] + +include random.fs \ defines random ( n -- 0..n-1 ) + +\ Initialize random seed from a +\ value that changes with time +MS@ SEED ! + +\ +\ The cave: 20 rooms, each connected to 3 others, +\ as a dodecahedron +\ +20 CONSTANT COUNT-ROOMS + 3 CONSTANT COUNT-NEIGHBORS +CREATE CAVE \ adjacency list + 5 C, 8 C, 2 C, \ ROOM 1 + 1 C, 10 C, 3 C, \ ROOM 2 + 2 C, 12 C, 4 C, \ ROOM 3 + 3 C, 14 C, 5 C, \ ROOM 4 + 4 C, 6 C, 1 C, \ ROOM 5 + 15 C, 5 C, 7 C, \ ROOM 6 + 6 C, 17 C, 8 C, \ ROOM 7 + 7 C, 1 C, 9 C, \ ROOM 8 + 8 C, 18 C, 10 C, \ ROOM 9 + 9 C, 2 C, 11 C, \ ROOM 10 + 10 C, 19 C, 12 C, \ ROOM 11 + 11 C, 3 C, 13 C, \ ROOM 12 + 12 C, 20 C, 14 C, \ ROOM 13 + 13 C, 4 C, 15 C, \ ROOM 14 + 14 C, 16 C, 6 C, \ ROOM 15 + 20 C, 15 C, 17 C, \ ROOM 16 + 16 C, 7 C, 18 C, \ ROOM 17 + 17 C, 9 C, 19 C, \ ROOM 18 + 18 C, 11 C, 20 C, \ ROOM 19 + 19 C, 13 C, 16 C, \ ROOM 20 + +\ Game state +CREATE HUNTER 1 CHARS ALLOT \ Player location +CREATE WUMPUS 1 CHARS ALLOT \ Wumpus location +CREATE PITS 2 CHARS ALLOT \ Rooms with pits +CREATE BATS 2 CHARS ALLOT \ Rooms with bats + +CREATE ARROWS 1 CHARS ALLOT \ Crooked arrows left +CREATE PLAYER 1 CHARS ALLOT \ IN-PLAY, WON, LOST + +\ Keep track of whether bats snatched the Hunter +\ TRUE if bats moved player +CREATE BATS-MOVED-HUNTER 1 CELLS ALLOT + +\ Arrow path +CREATE ARROW-PATH-LENGTH 1 CHARS ALLOT +CREATE ARROW-PATH-ROOMS 5 CHARS ALLOT + +\ Initial room assignments in order: +\ Hunter, Wumpus, pits, bats +CREATE INITIAL-ROOMS 6 CHARS ALLOT + +\ Scratch area for generating a random shuffle +\ of the 20 room numbers +CREATE ROOM-NUMBERS COUNT-ROOMS CHARS ALLOT + +\ Player states +0 CONSTANT IN-PLAY +1 CONSTANT WON +2 CONSTANT LOST + +\ Quit, or play again with new or same initial state +0 CONSTANT QUIT-GAME +1 CONSTANT SAME-ROOMS +2 CONSTANT NEW-ROOMS + +\ A pointer to a prompt string +CREATE PROMPT-STRING 2 CELLS ALLOT + +\ An 8-character buffer for prompt answers +8 CONSTANT MAX-ANSWER-LENGTH +CREATE PROMPT-ANSWER MAX-ANSWER-LENGTH CHARS ALLOT + +\ Responses to a yes-no question +CHAR y CONSTANT YES +CHAR n CONSTANT NO + +\ Responses to a command prompt +CHAR w CONSTANT WHERE-AM-I? +CHAR m CONSTANT MOVE-ME +CHAR s CONSTANT SHOOT +\ - undocumented - +CHAR g CONSTANT GAME-STATE \ show the game state +CHAR c CONSTANT CAVE-ROOMS \ show all the cave rooms + +ALIGN \ Align to next slot boundary + +\ +\ The Cave +\ room-number in 1..20 +\ WARNING: These cave referencing words +\ don't validate room numbers!!! +\ + +\ Determine if a room number is in the cave +: ?cave-room-number-valid ( room-number -- flag ) + DUP 0 < SWAP COUNT-ROOMS > OR INVERT + ; + +\ Get a pointer to a room +: cave-room-address ( room-number -- room-address ) + 1- COUNT-NEIGHBORS * CHARS CAVE + + ; + +\ Get the room number of a neighbor +: cave-room-neighbor ( index room-number -- room-number ) + cave-room-address SWAP CHARS + C@ + ; + +\ Get a list of a room's neighbors +: cave-room-neighbors ( room-number -- n_1 n_2 n_3 ) + DUP cave-room-address C@ SWAP + DUP cave-room-address CHAR+ C@ SWAP + cave-room-address 2 CHARS + C@ + ; + +\ Determine if a room is a neighbor +: ?cave-room-reachable ( to from -- flag ) + cave-room-neighbors FALSE + 4 PICK 4 PICK = OR + 4 PICK 3 PICK = OR + 4 PICK 2 PICK = OR + SWAP DROP SWAP DROP SWAP DROP SWAP DROP + ; + +\ Does this room have the Hunter in it? +: ?cave-room-has-hunter ( room-number -- flag ) + HUNTER C@ = + ; + +\ Does this room have the Wumpus in it? +: ?cave-room-has-wumpus ( room-number -- flag ) + WUMPUS C@ = + ; + +\ Does this room have a bottomless pit in it? +: ?cave-room-has-pit ( room-number -- flag ) + DUP PITS C@ = SWAP PITS CHAR+ C@ = OR + ; + +\ Does this room have super bats in it? +: ?cave-room-has-bats ( room-number -- flag ) + DUP BATS C@ = SWAP BATS CHAR+ C@ = OR + ; + +\ +\ Room number selection - for initial room assignments +\ +\ This is a variant of the +\ Fisher-Yates shuffle (a.k.a. the Knuth shuffle), +\ starting from the beginning of the rooms list, +\ and selecting only as many rooms as needed. +\ + +\ Fill room numbers with the sequence 1..20 +: reset-room-numbers ( -- ) + COUNT-ROOMS 0 DO I CHARS ROOM-NUMBERS + I 1+ SWAP C! LOOP + ; + +\ Display the room numbers +: show-room-numbers ( -- ) + COUNT-ROOMS 0 DO I CHARS ROOM-NUMBERS + C@ . LOOP + ; + +\ Choose a room in i..19 (yes, it could be i) +: choose-room-in-tail ( i -- r ) + DUP COUNT-ROOMS 1- SWAP - \ max-index-within-tail + 1+ random + \ r + ; + +\ Swap ith (i in 0..19) room with a room in i..19 +: swap-random-in-tail ( i -- ) + DUP ROOM-NUMBERS CHARS + C@ SWAP \ -- Ni i + DUP choose-room-in-tail TUCK \ -- Ni r i r + ROOM-NUMBERS CHARS + C@ SWAP \ -- Ni r Nr i + ROOM-NUMBERS CHARS + C! \ -- Ni r + ROOM-NUMBERS CHARS + C! + ; + +\ Select n <= 20 rooms at random +: select-random-rooms ( n -- random-rooms ) + DUP COUNT-ROOMS > IF + CR . ABORT" Can't select more than 20 rooms " + THEN + reset-room-numbers + 0 DO + I swap-random-in-tail + \ CR I . ." : " show-room-numbers + LOOP + ; + +\ Create and save a new room configuration +: create-new-room-assignments ( -- ) + 6 select-random-rooms + ROOM-NUMBERS INITIAL-ROOMS 6 CMOVE + ; + +\ +\ Player dialogue +\ + +\ Show the game state +: show-game-state ( -- ) + CR ." HUNTER: " HUNTER C@ . + CR ." WUMPUS: " WUMPUS C@ . + CR ." PITS: " PITS C@ . PITS CHAR+ C@ . + CR ." BATS: " BATS C@ . BATS CHAR+ C@ . + CR ." ARROWS: " ARROWS C@ . + CR ." PLAYER: " PLAYER C@ + CASE + LOST OF ." LOST " ENDOF + IN-PLAY OF ." IN-PLAY " ENDOF + WON OF ." WON " ENDOF + DUP CR . ." unexpected PLAYER state " + ENDCASE + ; + +\ List the neighboring rooms +: list-neighbors ( room-number -- ) + cave-room-neighbors + . . . + ; + +\ Show a list of all the cave's rooms +: show-cave-rooms ( -- ) + COUNT-ROOMS 0 DO + I 1+ DUP CR . ." : " list-neighbors + LOOP + ; + +\ Accept an answer from the player +: input-answer ( max-length -- length ; chars in PROMPT-ANSWER ) + MAX-ANSWER-LENGTH MIN \ Limit input to buffer length + BEGIN + CR ." > " + DUP PROMPT-ANSWER SWAP ACCEPT + DUP 0 > DUP INVERT IF + CR ." Huh? " + SWAP DROP \ Forget zero length + THEN + UNTIL \ Try again if no characters entered + SWAP DROP \ Forget max input length + ; + +\ Input one lowercase ASCII character from the player +: input-ascii-lowercase ( -- answer ) + 1 input-answer DROP \ Forget length + \ Convert ASCII alpha to lowercase; others don't care + PROMPT-ANSWER C@ 32 OR PROMPT-ANSWER C! + PROMPT-ANSWER C@ + ; + +\ Accept a numeric answer from the player +: input-number ( -- number ) + BEGIN + 2 input-answer PROMPT-ANSWER SWAP \ -- answer-address length + \ try to convert the answer into a number + 0 0 2SWAP >NUMBER \ -- n 0 remnant-address remnant-length + 0= DUP INVERT IF \ -- n 0 remnant-address flag + CR ." That is not a number. " + 2SWAP 2DROP \ Forget invalid answer + SWAP DROP \ Forget remnant-address, leaving FALSE + ELSE \ Entire answer was converted to a number + SWAP DROP \ Forget remnant-address + SWAP DROP \ Forget high-order zero of number in 0..99 + THEN + UNTIL \ Try again if answer was invalid + ; + +\ Ask a yes-no question, don't accept anything else +: prompt-yes-no ( question -- YES | NO ) + PROMPT-STRING 2! + BEGIN + CR PROMPT-STRING 2@ TYPE ." (y|n)? " + input-ascii-lowercase + DUP YES = OVER NO = OR + DUP INVERT IF + CR ." Huh? " + SWAP DROP \ Forget invalid answer + THEN + UNTIL \ Try again if answer was invalid + ; + +\ Show the stored crooked arrow path +: show-arrow-path ( -- ) + CR ." ARROW PATH - " + ARROW-PATH-LENGTH C@ DUP . ." : " 0 DO + ARROW-PATH-ROOMS I CHARS + C@ . + LOOP + ; + +\ Prompt for path length when shooting a crooked arrow +: prompt-arrow-path-length ( -- 1..5 ) + BEGIN + CR ." How many rooms should the arrow traverse (1..5)? " + input-number + DUP 1 < OVER 5 > OR + DUP IF + CR ." Huh? " + SWAP DROP \ Forget invalid answer + THEN + INVERT + UNTIL \ Try again if room count was invalid + ; + +\ Get room number arrow can't go back to +: arrow-path-backtrack-room ( index -- invalid-room ) + \ The arrow is not so crooked that it + \ can go out the tunnel it came in through. + DUP 1 > IF + \ Path has more than one room already; + \ the arrow can't go back to the room + \ before the last one entered. + 2 - CHARS ARROW-PATH-ROOMS + C@ + ELSE + 1 = IF + \ Path has exactly one room so far; the arrow + \ can't go back to the room the Hunter is in. + HUNTER C@ + ELSE + \ This is to be the first room in the path; + \ the arrow can be sent anywhere, + \ including the room the Hunter is in. + 0 \ Zero won't match any room. + THEN + THEN + ; + +\ Prompt for the next room in the arrow's path +: prompt-arrow-path-room ( index -- room ) + BEGIN + CR ." Enter room " DUP 1+ . + input-number \ -- index room + OVER arrow-path-backtrack-room \ -- index room invalid-room + OVER = DUP IF \ -- index room flag + CR ." Huh, arrows aren't that crooked! " + SWAP DROP \ Forget chosen room + ELSE + ROT DROP \ Forget the index + THEN \ -- index TRUE | room FALSE + INVERT + UNTIL \ Try again if room was invalid + ; + +\ Prompt for the arrow's path when shooting a crooked arrow +: prompt-arrow-path ( -- ; sets arrow path length and rooms ) + prompt-arrow-path-length + DUP ARROW-PATH-LENGTH C! 0 DO + I prompt-arrow-path-room + ARROW-PATH-ROOMS I CHARS + C! + LOOP + ; + +\ Prompt for a command +: prompt-command ( -- MOVE-ME | SHOOT | WHERE-AM-I? ) + BEGIN + CR ." What do you want to do " + ." (m=move, s=shoot, w=where am I?)? " + input-ascii-lowercase + DUP MOVE-ME = OVER SHOOT = OR + OVER WHERE-AM-I? = OR + \ - undocumented - + OVER GAME-STATE = OR + OVER CAVE-ROOMS = OR + DUP INVERT IF + CR ." Huh? " + SWAP DROP \ Forget invalid answer + THEN + UNTIL \ Try again if command was invalid + ; + +\ Prompt to play again, with same or new room assignments +: prompt-play-again ( -- QUIT-GAME | SAME-ROOMS | NEW-ROOMS ) + s" Play again " prompt-yes-no + YES = IF + CR ." OK, play again ... " + s" Same rooms " prompt-yes-no + YES = IF + CR ." OK, you, the Wumpus, pits, and bats in the same rooms. " + SAME-ROOMS + ELSE + CR ." OK, you, the Wumpus, pits, and bats in new rooms (probably). " + NEW-ROOMS + THEN + ELSE + CR ." Bye " + QUIT-GAME + THEN + ; + +\ Display congratulations or condolences +: show-result ( WON | LOST -- ) + DUP WON = IF + CR ." Congratulations! You got the Wumpus! But next time, hee, hee, hee!" + DROP + ELSE + DUP LOST = IF + CR ." Condolences, maybe better luck next time." + DROP + ELSE + CR . ." unknown game result." + THEN + THEN + ; + +\ Get a new room for the player +: prompt-new-hunter-room ( -- room ) + BEGIN + CR ." Where do you want to go? " + input-number + DUP ?cave-room-has-hunter IF + CR ." You are already in room " . ." ... " + DROP \ Forget room Hunter already in + FALSE \ answer not valid, try again + ELSE + DUP HUNTER C@ ?cave-room-reachable + DUP INVERT IF + CR ." Can't get there from here. " + SWAP DROP \ Forget unreachable room + THEN + THEN + UNTIL \ Try again if room was invalid + ; + +\ Display instructions +: show-instructions ( -- ) + CR ." ---- INSTRUCTIONS ---- " + CR + CR ." Welcome to Hunt the Wumpus! You are a hunter, looking to bag a Wumpus. " + CR + CR ." The Wumpus lives in a cave of twenty rooms, each connected by " + CR ." tunnels to three other rooms, as in a dodecahedron. " + CR + CR ." There are HAZARDS!! " + CR + CR ." The Wumpus - One room has the Wumpus in it. If the Wumpus " + CR ." finds you in the room with it, it will eat you and you lose. " + CR + CR ." Bottomless Pits - Two rooms have bottomless pits in them. " + CR ." If you go there, you fall into the pit and lose. " + CR + CR ." Super Bats - Two other rooms have super bats in them. " + CR ." If you go there, a bat grabs you and takes you to another " + CR ." room, at random. This might be troublesome. " + CR + CR ." As you are hunting, you will be able to sense something of " + CR ." the hazards, when you are in a room adjacent to one. " + CR + CR ." - You can smell the Wumpus, when it is nearby. " + CR ." - You can feel a breeze, when there is a pit nearby " + CR ." - You can hear a rustling sound, when there are bats nearby. " + CR + CR ." The Wumpus is not bothered by the hazards. It has sucker " + CR ." feet, so can cling to the walls of a pit, and is too heavy " + CR ." for the super bats to lift. Usually, it is asleep. " + CR + CR ." Two things wake up the Wumpus: you entering its room, or " + CR ." you shooting an arrow (anywhere in the cave!). When it " + CR ." wakes, it moves into an adjacent room (P=3/4) or stays " + CR ." where it is (P=1/4). After that, if it is where you are " + CR ." it eats you and you lose. " + CR + CR ." The computer starts you in a randomly chosen room. " + CR ." Each turn you can move to an adjacent room or shoot an arrow. " + CR + CR ." You are furnished with 5 crooked arrows, which you can program " + CR ." to go into 1 to 5 rooms. Starting from the room you are in, " + CR ." the arrow will go from room to room provided there is a tunnel " + CR ." from where it is to the next room on its list. If there is no " + CR ." tunnel, the arrow bounces on the walls of the cave and moves into " + CR ." an adjacent room at random, possibly the one you are in. " + CR + CR ." - If the arrow hits the Wumpus, you win. " + CR ." - If the arrow hits you, you lose. " + CR ." - If you run out of arrows, you lose. " + CR + CR ." When the game is over, you can start a new game. " + CR ." You can choose to start over with the same configuration " + CR ." as the game you just finished, that is: with you, the Wumpus, " + CR ." the pits, and the bats where they started in the game you " + CR ." just finished; or you can start fresh, with everything in " + CR ." new places (well, probably). In any case, you get a fresh " + CR ." supply of five arrows. " + CR + CR ." Good luck! " + ; + +\ Display instructions if wanted +: show-instructions-if-wanted ( -- ) + s" Show instructions " prompt-yes-no + YES = IF + show-instructions + THEN + ; + +\ Display a greeting +: show-greeting ( -- ) + CR ." ---- ---- Hunt the Wumpus ---- ---- " + CR ." - " wumpus-version + CR ." ---- ---- --------------- ---- ---- " + ; + +\ +\ Game play +\ + +\ List any hazards in a room +: hazards-in-room ( room-number -- ) + DUP ?cave-room-has-wumpus IF + CR ." I smell a Wumpus!" + THEN + DUP ?cave-room-has-pit IF + CR ." I feel a draft!" + THEN + DUP ?cave-room-has-bats IF + CR ." I hear a rustling sound!" + THEN + DROP \ Forget room number + ; + +\ Warn of any hazards in the neighboring rooms +: warn-of-hazards ( room-number -- ) + cave-room-neighbors + hazards-in-room + hazards-in-room + hazards-in-room + ; + +\ Describe the Hunter's location +: describe-hunter-location ( -- ) + HUNTER C@ + CR ." You are in room " DUP . + CR ." Tunnels lead to rooms " DUP list-neighbors + warn-of-hazards + ; + +\ The Wumpus eats the Hunter if in the same room +: wumpus-ate-hunter? ( -- ; may set player state to LOST ) + HUNTER C@ ?cave-room-has-wumpus IF + CR ." Aaaaggghhh! The Wumpus got you! You lose! " + LOST PLAYER C! + ELSE + CR ." Phew! The Wumpus didn't get you. " + THEN + ; + +\ Move the Wumpus - did it get the Hunter? +: move-wumpus ( -- ; may set player state to LOST ) + CR ." Uh oh! You disturbed the Wumpus! " + 4 random DUP 3 < IF + WUMPUS C@ cave-room-neighbor WUMPUS C! + ELSE + DROP \ Forget index indicating Wumpus didn't move + THEN + wumpus-ate-hunter? \ may set player state to LOST + ; + +\ Did the crooked arrow hit the Wumpus? +: arrow-hit-wumpus? ( room -- flag ; may set player state to WON ) + ?cave-room-has-wumpus DUP IF + CR ." Aha! You got the Wumpus! " + WON PLAYER C! + THEN + ; + +\ Did the crooked arrow hit the Hunter? +: arrow-hit-hunter? ( room -- flag ; may set player state to LOST ) + ?cave-room-has-hunter DUP IF + CR ." Ouch! Arrow got you! You lose!" + LOST PLAYER C! + THEN + ; + +\ Did the Hunter run out of crooked arrows? +: arrows-all-gone? ( -- ; may set player state to LOST ) + ARROWS C@ 1- DUP ARROWS C! 0 = IF + CR ." You're out of arrows, you lose! " + LOST PLAYER C! + THEN + ; + +\ Fly a crooked arrow +: fly-arrow ( -- ; may set player state to WON or LOST ) + HUNTER C@ \ arrow starts where player is + DUP CR . + ARROW-PATH-LENGTH C@ 0 DO + ." --> " + ARROW-PATH-ROOMS I CHARS + C@ \ Rf -- Rf Rt + 2DUP SWAP ?cave-room-reachable IF + SWAP DROP \ Rf Rt -- Rt ; Arrow now in next room in path + ELSE + DROP \ Rf Rt -- Rf ; Forget the unreachable room + CR ." Uh oh! You hit the cave wall, arrow gone astray! " + \ Arrow enters one of the adjoining rooms + cave-room-address 3 random CHARS + C@ \ Rf -- Rt + THEN + DUP . + \ OK, what happens when the arrow reaches this room? + DUP arrow-hit-hunter? OVER arrow-hit-wumpus? OR IF + LEAVE \ That's the end of the arrow's flight + THEN + LOOP + DROP \ Forget the last room the arrow went into + ; + +\ Shoot a crooked arrow +: shoot-arrow ( -- ) + prompt-arrow-path + show-arrow-path + fly-arrow \ may set player state to WON or LOST + PLAYER C@ IN-PLAY = IF + \ The arrow didn't hit anything + CR ." You missed! " + \ Shooting an arrow always disturbs the Wumpus + move-wumpus \ may set player state to LOST + arrows-all-gone? \ may set player state to LOST + THEN + ; + +\ Hunter went into a room with super bats? +: entered-room-with-bats? ( -- flag ) + HUNTER C@ ?cave-room-has-bats DUP IF + CR ." Oh oh oh! A bat's got you! Oh ohhh ... " + COUNT-ROOMS random 1+ DUP HUNTER C! + CR ." You are now in room " . + THEN + \ Return TRUE if a super bat moved the Hunter + ; + +\ Hunter went into a room with a bottomless pit? +: entered-room-with-pit? ( -- ; may set player state to LOST ) + HUNTER C@ ?cave-room-has-pit IF + CR ." Aaaaggghhh! You fell in a pit! You lose! " + LOST PLAYER C! + THEN + ; + +\ Hunter went into a room with the Wumpus? +: entered-room-with-wumpus? ( -- ; may set player state to LOST ) + HUNTER C@ ?cave-room-has-wumpus IF + move-wumpus \ may set player state to LOST + THEN + ; + +\ Move the Hunter to a new room +: move-hunter ( -- ; may set player state to LOST ) + prompt-new-hunter-room HUNTER C! + BEGIN + FALSE BATS-MOVED-HUNTER ! + entered-room-with-wumpus? \ may set player state to LOST + PLAYER C@ IN-PLAY = IF + entered-room-with-pit? \ may set player state to LOST + PLAYER C@ IN-PLAY = IF + entered-room-with-bats? BATS-MOVED-HUNTER ! + THEN + THEN + BATS-MOVED-HUNTER @ INVERT + UNTIL \ repeat if the bats moved the Hunter + PLAYER C@ IN-PLAY = IF + \ Nothing too bad happened, let's take a moment + \ to take in our surroundings + describe-hunter-location + THEN + ; + +\ Play the game until won or lost +: play ( -- WON | LOST ) + BEGIN PLAYER C@ IN-PLAY = WHILE + prompt-command \ -- MOVE-ME | SHOOT | WHERE-AM-I? + CASE + MOVE-ME OF move-hunter ENDOF + SHOOT OF shoot-arrow ENDOF + WHERE-AM-I? OF describe-hunter-location ENDOF + \ - undocumented - + GAME-STATE OF show-game-state ENDOF + CAVE-ROOMS OF show-cave-rooms ENDOF + CR . ." unexpected command." + ENDCASE + REPEAT + PLAYER C@ + ; + +\ Set the room configuration to the saved one +: set-rooms-to-initial-assignments ( -- ) + INITIAL-ROOMS C@ HUNTER C! + INITIAL-ROOMS CHAR+ C@ WUMPUS C! + INITIAL-ROOMS 2 CHARS + C@ PITS C! + INITIAL-ROOMS 3 CHARS + C@ PITS CHAR+ C! + INITIAL-ROOMS 4 CHARS + C@ BATS C! + INITIAL-ROOMS 5 CHARS + C@ BATS CHAR+ C! + ; + +\ Reset the state for a new game +: new-game ( SAME-ROOMS | NEW-ROOMS -- ) + NEW-ROOMS = IF + create-new-room-assignments + THEN + set-rooms-to-initial-assignments + 5 ARROWS C! + IN-PLAY PLAYER C! + ; + +\ Greet the player, play, then prompt for a new game +: Hunt-the-Wumpus ( -- ) + show-greeting + show-instructions-if-wanted + NEW-ROOMS + BEGIN + new-game \ SAME-ROOMS | NEW-ROOMS -- + describe-hunter-location \ -- + play \ -- WON | LOST + show-result \ WON | LOST -- + prompt-play-again \ -- QUIT-GAME | SAME-ROOMS | NEW-ROOMS + DUP QUIT-GAME = + UNTIL + DROP \ Forget the QUIT-GAME indicator + ; diff --git a/Task/Hunt-the-Wumpus/FutureBasic/hunt-the-wumpus.basic b/Task/Hunt-the-Wumpus/FutureBasic/hunt-the-wumpus.basic new file mode 100644 index 0000000000..714df4ab49 --- /dev/null +++ b/Task/Hunt-the-Wumpus/FutureBasic/hunt-the-wumpus.basic @@ -0,0 +1,229 @@ +// Hunt the Wumpus +// https://rosettacode.org/wiki/Hunt_the_Wumpus# + + +_w = 640 // window size width and height +_h = 400 +_window = 1 + +local fn BuildWindow + + CGRect r = fn cgrectmake(0,0,_w,_h) + window _Window, @"Hunt the Wumpus", r, NSWindowStyleMaskTitled + NSWindowStyleMaskMiniaturizable + windowcenter(_Window) + WindowSetBackgroundColor(_Window,fn ColorBlack) + WindowPrintViewSetTextInset( _window, 20) + + text ,14,fn colorWhite + +end fn + + +fn BuildWindow + + +//////////// Main Program ////////////// + +"Start" + +cls:restore + +data 7,13,19,12,18,20,16,17,19,11,14,18,13,15,18,9,14,16,1,15,17,10,16,20,6,11,19,8,12,17 +data 4,9,13,2,10,15,1,5,11,4,6,20,5,7,12,3,6,8,3,7,10,2,4,5,1,3,9,2,8,14 +data 1,2,3,1,3,2,2,1,3,2,3,1,3,1,2,3,2,1 + +uint32 i, j,tunnel(21,4),lost(7,4),targ,wump,player,bat1, bat2, pit1, pit2, d6, epi +player = int(rnd(20)) +uint32 arrows = 5 +CFStringRef choice + +for i = 1 to 20 //set up rooms + for j = 1 to 3 + read tunnel(i,j) + next j +next i + +for i = 1 to 6 //set up list of permuatations of 1-2-3 + for j = 1 to 3 + read lost(i,j) + next j +next i + + +//place wumpus, bats, and pits +do + wump = int(rnd(20)) +until wump <> player +do + pit1 = int(rnd(20)) +until pit1 <> player +do + pit2 = int(rnd(20)) +until pit2 <> player && pit2 <> pit1 +do + bat1 = int(rnd(20)) +until bat1 <> player && bat1 <> pit1 && bat1 <> pit2 +do + bat2 = int(rnd(20)) +until bat2 <> player && bat2 <> pit1 && bat2 <> pit2 && bat2 <> bat1 + +do + if player = wump + text ,,fn colorRed + print "You have been eaten by the Wumpus!" + Print: WindowPrintViewScrollToBottom( _window ) + goto "defeat" + end if + if player = pit1 || player = pit2 + text ,,fn colorRed + print "Aaaaaaaaaaa! You have fallen into a bottomless pit." + Print: WindowPrintViewScrollToBottom( _window ) + goto "defeat" + end if + if player = bat1 || player = bat2 + text ,,fn colorOrange + print "A bat has carried you into another empty room." + text ,,fn colorWhite + Print: WindowPrintViewScrollToBottom( _window ) + do + player = (rnd(20)) + until player <> wump && player <> pit1 && player <> pit2 && player <> bat1 && player <> bat2 + end if + + print + text ,,fn colorGreen + print "You are in room number" + str$(player) + ". There are tunnels to rooms"¬ + + str$(tunnel(player,1)) + "," str$(tunnel(player,2)) + " and" +str$(tunnel(player,3)) + if (tunnel(player,1)) + (tunnel(player,2)) + (tunnel(player,3)) = 0 then arrows = 5 : goto "Start" + text ,,fn colorYellow + print "You have" + str$(arrows) + " arrows left." + text ,,fn colorWhite + Print: WindowPrintViewScrollToBottom( _window ) + + d6 = int(rnd(6)) + for i = 1 to 3 + epi = tunnel(player,lost(d6,i)) + if epi = wump + text ,,fn colorRed + print "You smell something terrible nearby." + text ,,fn colorWhite + Print: WindowPrintViewScrollToBottom( _window ) + end if + if epi = bat1 || epi = bat2 + text ,,fn colorRed + print "You hear a rustling." + text ,,fn colorWhite + Print: WindowPrintViewScrollToBottom( _window ) + end if + if epi = pit1 || epi = pit2 + print "You feel a cold wind blowing from a nearby cavern." + Print: WindowPrintViewScrollToBottom( _window ) + end if + next i + "choices" + print + print "What would you like to do?" + Print: WindowPrintViewScrollToBottom( _window ) + + choice = input %(_w/2 - 260 , _h + 20),@"Type A to shoot an arrow, or a number to move to another room. ( or Q to quit )" + + select case left(choice,1) + + case @"q", @"Q" , @"x" , @"X" + end + + case @"a", @"A" + + CFStringRef targString + targString = input %(_w/2 - 140 , _h + 20), @"Which room would you like to shoot into? " + targ = fn StringIntegerValue(targString) + + print "You shot an arrow into room " + str$(targ) + + if targ = player + text ,,fn colorRed + print "You shot yourself. Why would you want to do such a thing?" + Print: WindowPrintViewScrollToBottom( _window ) + goto "defeat" + end if + + text ,,fn colorGreen + if targ = wump then goto "victory" + + if targ = tunnel(player,1) || targ = tunnel(player,2) || targ = tunnel(player,3) + text ,,fn colorYellow + print "The Wumpus awakes!" + text ,,fn colorWhite + Print: WindowPrintViewScrollToBottom( _window ) + if rnd(100) <= 75 + print "He moves to a nearby cavern." + Print: WindowPrintViewScrollToBottom( _window ) + short wumpRnd + wumpRnd = Int(Rnd(3)) + wump = Tunnel(wump,wumpRnd) + else + print "He goes back to sleep." + Print: WindowPrintViewScrollToBottom( _window ) + end if + else + text ,,fn colorRed + print "You can't shoot that room from here." + text ,,fn colorWhite + Print: WindowPrintViewScrollToBottom( _window ) + goto "choices" + end if + arrows -= 1 + + case @"0", @"1" ,@"2", @"3", @"4", @"5", @"6", @"7", @"8", @"9" + + targ = fn StringIntegerValue(choice) + if targ = player then print "You are already there." + + if targ = tunnel(player,1) || targ = tunnel(player,2) || targ = tunnel(player,3) + print using "You walk to room ##"; targ + player = targ + else + text ,,fn colorOrange + print "You can't get there from here." + text ,,fn colorWhite + Print: WindowPrintViewScrollToBottom( _window ) + end if + case else + text ,,fn colorRed + print "You are making no sense." + text ,,fn colorWhite + Print: WindowPrintViewScrollToBottom( _window ) + end select +until arrows = 0 +text ,,fn colorRed +print "You have run out of arrows!" +Print: WindowPrintViewScrollToBottom( _window ) +"defeat" +text ,,fn colorRed +print "You lose! Better luck next time." +Print: WindowPrintViewScrollToBottom( _window ) + +goto "End" + +"victory" +text ,20,fn colorGreen +print "You have slain the Wumpus!" +print "You won!" +Print: WindowPrintViewScrollToBottom( _window ) + +"End" + +text ,14,fn colorWhite +choice = input %(_w/2 -140 , _h + 20),@"Hit Return for another. ( or Q to quit )" + +select case left(choice,1) + + case @"q", @"Q" , @"x" , @"X" + end + + case else arrows = 5: goto "Start" + +end select + + +handleevents diff --git a/Task/Hunt-the-Wumpus/Julia/hunt-the-wumpus.julia b/Task/Hunt-the-Wumpus/Julia/hunt-the-wumpus.jl similarity index 100% rename from Task/Hunt-the-Wumpus/Julia/hunt-the-wumpus.julia rename to Task/Hunt-the-Wumpus/Julia/hunt-the-wumpus.jl diff --git a/Task/Hunt-the-Wumpus/Liberty-BASIC/hunt-the-wumpus.basic b/Task/Hunt-the-Wumpus/Liberty-BASIC/hunt-the-wumpus.basic new file mode 100644 index 0000000000..cd667ebfab --- /dev/null +++ b/Task/Hunt-the-Wumpus/Liberty-BASIC/hunt-the-wumpus.basic @@ -0,0 +1,272 @@ +' ============================================ +' HUNT THE WUMPUS - Liberty BASIC (Text Version) +' Text-only game played in Mainwin +' ============================================ + +' --- Global Variables --- +dim rooms(20, 3) ' Adjacency map +dim hazard(20) ' 0=nothing, 1=Wumpus, 2=Bat, 3=Pit + +global playerRoom, arrowsLeft, gameOver, wRoom + +playerRoom = 0 +arrowsLeft = 5 +gameOver = 0 + +call setupMap +call placeHazards + +print "WELCOME TO HUNT THE WUMPUS!" +print "===========================" +print "You can enter commands like M10 to move to room 10" +print " or S18 to shoot into room 18. Of couse commands" +print " like M, S and Q are permitted as well. Good luck" +print "" +call mainLoop +end + +' ---------------------------- +sub setupMap + ' Each room has 3 connections + ' Standard dodecahedron layout + + data 2,5,8 + data 1,3,10 + data 2,4,12 + data 3,5,14 + data 1,4,6 + data 5,7,15 + data 6,8,17 + data 1,7,9 + data 8,10,18 + data 2,9,11 + data 10,12,19 + data 3,11,13 + data 12,14,20 + data 4,13,15 + data 6,14,16 + data 15,17,20 + data 7,16,18 + data 9,17,19 + data 11,18,20 + data 13,16,19 + + for i = 1 to 20 + for j = 1 to 3 + read a + rooms(i,j) = a + next + next +end sub + +' ---------------------------- +sub placeHazards + for i = 1 to 20 + hazard(i) = 0 + next + + wRoom = getEmptyRoom(0) + hazard(wRoom) = 1 + + for i = 1 to 2 + bRoom = getEmptyRoom(0) + hazard(bRoom) = 2 + next + + for i = 1 to 2 + pRoom = getEmptyRoom(0) + hazard(pRoom) = 3 + next + + playerRoom = getEmptyRoom(0) +end sub + +' ---------------------------- +function getEmptyRoom(avoid) + do + room = int(rnd(0)*20) + 1 + loop until hazard(room)=0 and room <> avoid + getEmptyRoom = room +end function + +' ---------------------------- +sub mainLoop + while gameOver = 0 + call describeHazards + print "You are in room "; playerRoom + print "Tunnels lead to "; rooms(playerRoom,1); ", "; rooms(playerRoom,2); ", "; rooms(playerRoom,3) + print "Arrows left: "; arrowsLeft + + input "Shoot, Move or Quit (S/M/Q)? "; a$ + a$ = upper$(trim$(a$)) + + if len(a$) > 1 then + 'assume characters 2 and 3 are part of a number + num = val(mid$(a$,2)) + if num > 20 then num = 0 + a$ = left$(a$,1) + end if + + select case a$ + case "S" + call shoot num + case "M" + call move num + case "Q" + Print "You have decided to quit." + gameOver = 1 + case else + print "Invalid choice." + end select + wend + + input "Press Enter to quit the game"; dummy$ +end sub + +' ---------------------------- +sub describeHazards + for i = 1 to 3 + adj = rooms(playerRoom,i) + select case hazard(adj) + case 1 + print "You smell something terrible nearby." + case 2 + print "You hear a rustling." + case 3 + print "You feel a cold wind blowing from a nearby cavern." + end select + next +end sub + +' ---------------------------- +sub move num + + if num = 0 then + input "Which room do you want to enter? "; n + if n < 1 or n > 20 then + print "That's not a valid room!" + exit sub + end if + else + n = num + end if + + adjacent = 0 + for i = 1 to 3 + if rooms(playerRoom,i) = n then adjacent = 1 + next + + if adjacent = 0 then + print "You can't go there directly!" + exit sub + end if + + playerRoom = n + select case hazard(playerRoom) + case 1 + print "You walked into the Wumpus room!" + print "The Wumpus eats you. GAME OVER!" + gameOver = 1 + case 2 + print "A giant bat grabs you!" + playerRoom = getEmptyRoom(0) + print "The bat drops you into room "; playerRoom + call checkNewRoom + case 3 + print "You fall into a bottomless pit!" + print "GAME OVER!" + gameOver = 1 + case else + ' safe + end select +end sub + +' ---------------------------- +sub checkNewRoom + select case hazard(playerRoom) + case 1 + print "The bat dropped you into the Wumpus room!" + print "The Wumpus eats you. GAME OVER!" + gameOver = 1 + case 3 + print "The bat dropped you into a pit!" + print "GAME OVER!" + gameOver = 1 + case 2 + print "Another bat grabs you!" + playerRoom = getEmptyRoom(0) + print "The bat drops you into room "; playerRoom + call checkNewRoom + case else + ' safe + end select +end sub + +' ---------------------------- +sub shoot num + + if num = 0 then + input "Shoot into which room? "; t + if t < 1 or t > 20 then + print "That's not a valid room!" + exit sub + end if + else + t = num + end if + + adjacent = 0 + for i = 1 to 3 + if rooms(playerRoom,i) = t then adjacent = 1 + next + + if adjacent = 0 then + print "You can't shoot there directly!" + exit sub + end if + + arrowsLeft = arrowsLeft - 1 + + if hazard(t) = 1 then + print "Your arrow flies true... and you hear a terrible scream!" + print "You have slain the Wumpus! YOU WIN!" + gameOver = 1 + exit sub + else + print "You missed." + wWake = int(rnd(0)*100) + 1 + if wWake <= 75 then + call moveWumpus + end if + if playerRoom = wRoom then + print "The Wumpus has moved into your room!" + print "It eats you. GAME OVER!" + gameOver = 1 + end if + end if + + 'check to see if you are out of arrows + if arrowsLeft <= 0 then + print "You're out of arrows!" + print "GAME OVER - You have lost." + gameOver = 1 + exit sub + end if + +end sub + +' ---------------------------- +sub moveWumpus + oldRoom = wRoom + found = 0 + for tries = 1 to 10 + adj = rooms(oldRoom, int(rnd(0)*3)+1) + if hazard(adj) = 0 and adj <> playerRoom then + hazard(oldRoom) = 0 + hazard(adj) = 1 + wRoom = adj + found = 1 + exit for + end if + next +end sub diff --git a/Task/Hunt-the-Wumpus/Mojo/hunt-the-wumpus.mojo b/Task/Hunt-the-Wumpus/Mojo/hunt-the-wumpus.mojo new file mode 100644 index 0000000000..2c67a185ae --- /dev/null +++ b/Task/Hunt-the-Wumpus/Mojo/hunt-the-wumpus.mojo @@ -0,0 +1,203 @@ +from random import shuffle, seed, random_ui64 + +alias adjacent_rooms: List[List[Int]] = [ + [], + [2, 5, 8], [1, 3, 10], [2, 4, 12], [3, 5, 14], [1, 4, 6], + [5, 7, 15], [6, 8, 17], [1, 7, 9], [8, 10, 18], [2, 9, 11], + [10, 12, 19],[2, 11, 13],[12, 14, 20], [4, 13, 15], [6, 14, 16], + [15, 17, 20],[7, 16, 18], [9, 17, 19], [11, 18, 20], [13, 16, 19] +] + +struct Game_State: + var winloss_state: Int + var player_location: Int + var wumpus_location: Int + var pit_locations: Tuple[Int, Int] + var bat_locations: Tuple[Int, Int] + var arrows_remaining: Int + + fn __init__(out self): + var all_locations = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] + shuffle(all_locations) + + self.winloss_state = 0 + self.player_location = all_locations[0] + self.wumpus_location = all_locations[1] + self.pit_locations = (all_locations[2], all_locations[3]) + self.bat_locations = (all_locations[4], all_locations[5]) + self.arrows_remaining = 5 + + fn __copyinit__(out self, other: Self): + self.winloss_state = other.winloss_state + self.player_location = other.player_location + self.wumpus_location = other.wumpus_location + self.pit_locations = other.pit_locations + self.bat_locations = other.bat_locations + self.arrows_remaining = other.arrows_remaining + +fn print_instructions() -> None: + print("WELCOME TO 'HUNT THE WUMPUS'") + print(" THE WUMPUS LIVES IN A CAVE OF 20 ROOMS. EACH ROOM") + print("HAS 3 TUNNELS LEADING TO OTHER ROOMS. (LOOK AT A") + print("DODECAHEDRON TO SEE HOW THIS WORKS-IF YOU DON'T KNOW") + print("WHAT A DODECAHEDRON IS, ASK SOMEONE)\n") + print(" HAZARDS:") + print(" BOTTOMLESS PITS - TWO ROOMS HAVE BOTTOMLESS PITS IN THEM") + print(" IF YOU GO THERE, YOU FALL INTO THE PIT (& LOSE!)") + print(" SUPER BATS - TWO OTHER ROOMS HAVE SUPER BATS. IF YOU") + print(" GO THERE, A BAT GRABS YOU AND TAKES YOU TO SOME OTHER") + print(" ROOM AT RANDOM. (WHICH MIGHT BE TROUBLESOME)\n") + print(" WUMPUS:") + print(" THE WUMPUS IS NOT BOTHERED BY THE HAZARDS (HE HAS SUCKER") + print(" FEET AND IS TOO BIG FOR A BAT TO LIFT). USUALLY") + print(" HE IS ASLEEP. TWO THINGS WAKE HIM UP: YOUR ENTERING") + print(" HIS ROOM OR YOUR SHOOTING AN ARROW.") + print(" IF THE WUMPUS WAKES, HE MOVES (P=.75) ONE ROOM") + print(" OR STAYS STILL (P=.25). AFTER THAT, IF HE IS WHERE YOU") + print(" ARE, HE EATS YOU UP (& YOU LOSE!)\n") + print(" YOU:") + print(" EACH TURN YOU MAY MOVE OR SHOOT A CROOKED ARROW") + print(" MOVING: YOU CAN GO ONE ROOM (THRU ONE TUNNEL)") + print(" ARROWS: YOU HAVE 5 ARROWS. YOU LOSE WHEN YOU RUN OUT.") + print(" EACH ARROW CAN GO FROM 1 TO 5 ROOMS. YOU AIM BY TELLING") + print(" THE COMPUTER THE ROOM#S YOU WANT THE ARROW TO GO TO.") + print(" IF THE ARROW CAN'T GO THAT WAY (IE NO TUNNEL) IT MOVES") + print(" AT RAMDOM TO THE NEXT ROOM.") + print(" IF THE ARROW HITS THE WUMPUS, YOU WIN.") + print(" IF THE ARROW HITS YOU, YOU LOSE.\n") + print(" WARNINGS:") + print(" WHEN YOU ARE ONE ROOM AWAY FROM WUMPUS OR HAZARD,") + print(" THE COMPUTER SAYS:") + print(" WUMPUS- 'I SMELL A WUMPUS'") + print(" BAT - 'BATS NEARBY'") + print(" PIT - 'I FEEL A DRAFT'\n") + return None + +fn print_location(game_state: Game_State) -> None: + if game_state.wumpus_location in adjacent_rooms[game_state.player_location]: + print("I SMELL A WUMPUS!") + if game_state.pit_locations[0] in adjacent_rooms[game_state.player_location] or game_state.pit_locations[1] in adjacent_rooms[game_state.player_location]: + print("I FEEL A DRAFT") + if game_state.bat_locations[0] in adjacent_rooms[game_state.player_location] or game_state.bat_locations[1] in adjacent_rooms[game_state.player_location]: + print("BATS NEARBY!") + print("YOU ARE IN ROOM", game_state.player_location) + print("TUNNELS LEAD TO", adjacent_rooms[game_state.player_location][0], adjacent_rooms[game_state.player_location][1], adjacent_rooms[game_state.player_location][2]) + return None + +fn move_wumpus(mut game_state: Game_State) -> Bool: + if random_ui64(0,3) != 3: + game_state.wumpus_location = adjacent_rooms[game_state.wumpus_location][random_ui64(0,2)] + if game_state.wumpus_location == game_state.player_location: + print("TSK TSK TSK- WUMPUS GOT YOU!") + game_state.winloss_state = -1 + return True + return False + +def shoot_action(mut game_state: Game_State) -> None: + while True: + distance = Int(input("NO. OF ROOMS(1-5)")) + if distance >= 1 and distance <= 5: + break + path: List[Int] = [] + for i in range(distance): + while True: + fork = Int(input("ROOM #")) + if i <= 1: + break + elif fork != path[-2]: + break + else: + print("ARROWS AREN'T THAT CROOKED - TRY ANOTHER ROOM") + pass + path.append(fork) + arrow_location = game_state.player_location + for i in range(distance): + if path[i] in adjacent_rooms[arrow_location]: + arrow_location = path[i] + else: + arrow_location = adjacent_rooms[arrow_location][random_ui64(0, 2)] + if arrow_location == game_state.wumpus_location: + print("AHA! YOU GOT THE WUMPUS!") + game_state.winloss_state = 1 + return + elif arrow_location == game_state.player_location: + print("OUCH! ARROW GOT YOU!") + game_state.winloss_state = -1 + return + print("MISSED") + if move_wumpus(game_state): + return + game_state.arrows_remaining -= 1 + if game_state.arrows_remaining == 0: + game_state.winloss_state = -1 + return + +def move_action(mut game_state: Game_State) -> None: + while True: + next_room = Int(input("WHERE TO")) + if next_room < 1 or next_room > 20: + pass + if next_room in adjacent_rooms[game_state.player_location]: + game_state.player_location = next_room + break + if next_room == game_state.player_location: + break + print("NOT POSSIBLE -") + if game_state.player_location == game_state.wumpus_location: + print("...OOPS! BUMPED A WUMPUS!") + if move_wumpus(game_state): + return + if game_state.player_location == game_state.pit_locations[0] or game_state.player_location == game_state.pit_locations[1]: + print("YYYIIIIEEEE . . . FELL IN PIT") + game_state.winloss_state = -1 + return + if game_state.player_location == game_state.bat_locations[0] or game_state.player_location == game_state.bat_locations[1]: + print("ZAP--SUPER BAT SNATCH! ELSEWHEREVILLE FOR YOU!") + move_action(game_state, Int(random_ui64(1, 20))) + return + +fn move_action(mut game_state: Game_State, room_number: Int) -> None: + game_state.player_location = room_number + if game_state.player_location == game_state.wumpus_location: + print("...OOPS! BUMPED A WUMPUS!") + if move_wumpus(game_state): + return + if game_state.player_location == game_state.pit_locations[0] or game_state.player_location == game_state.pit_locations[1]: + print("YYYIIIIEEEE . . . FELL IN PIT") + game_state.winloss_state = -1 + return + if game_state.player_location == game_state.bat_locations[0] or game_state.player_location == game_state.bat_locations[1]: + print("ZAP--SUPER BAT SNATCH! ELSEWHEREVILLE FOR YOU!") + move_action(game_state, Int(random_ui64(1, 20))) + return + +def main(): + seed() + instruct_cond = input("INSTRUCTIONS (Y-N)") + if instruct_cond != 'N': + print_instructions() + + game_state = Game_State() + saved_state = game_state + + game_is_running = True + while game_is_running: + print("HUNT THE WUMPUS\n") + print_location(game_state) + action = input("SHOOT OR MOVE (S-M)") + + if action == 'S': + shoot_action(game_state) + elif action == 'M': + move_action(game_state) + if game_state.winloss_state == -1: + print("HA HA HA - YOU LOSE!") + elif game_state.winloss_state == 1: + print("HEE HEE HEE - THE WUMPUS'LL GETCHA NEXT TIME!!") + if game_state.winloss_state != 0: + state_update = input("SAME SET-UP (Y-N)") + if state_update == 'Y': + game_state = saved_state + else: + game_state = Game_State() + saved_state = game_state diff --git a/Task/I-before-E-except-after-C/00-TASK.txt b/Task/I-before-E-except-after-C/00-TASK.txt index b342d03475..74e62f2023 100644 --- a/Task/I-before-E-except-after-C/00-TASK.txt +++ b/Task/I-before-E-except-after-C/00-TASK.txt @@ -3,7 +3,7 @@ widely known mnemonic which is supposed to help when spelling English words. ;Task: -Using the word list from   [http://wiki.puzzlers.org/pub/wordlists/unixdict.txt http://wiki.puzzlers.org/pub/wordlists/unixdict.txt], +Using the word list from   [https://web.archive.org/web/20240920144647if_/http://wiki.puzzlers.org/pub/wordlists/unixdict.txt https://web.archive.org/web/20240920144647if_/http://wiki.puzzlers.org/pub/wordlists/unixdict.txt],
    check if the two sub-clauses of the phrase are plausible individually: :::#   ''"I before E when not preceded by C"'' :::#   ''"E before I when preceded by C"'' diff --git a/Task/I-before-E-except-after-C/8080-Assembly/i-before-e-except-after-c.8080 b/Task/I-before-E-except-after-C/8080-Assembly/i-before-e-except-after-c.8080 index 1b4b015117..75a59a9a6a 100644 --- a/Task/I-before-E-except-after-C/8080-Assembly/i-before-e-except-after-c.8080 +++ b/Task/I-before-E-except-after-C/8080-Assembly/i-before-e-except-after-c.8080 @@ -1,207 +1,207 @@ - ;;; I before E, except after C -fcb1: equ 5Ch ; FCB 1 (populated by file on command line) -dma: equ 80h ; Standard DMA location -bdos: equ 5 ; CP/M entry point -puts: equ 9 ; CP/M call to write a string to the console -fopen: equ 0Fh ; CP/M call to open a file -fread: equ 14h ; CP/M call to read from a file -CR: equ 13 -LF: equ 10 -EOF: equ 26 - org 100h - ;;; Open the file given on the command line - lxi d,fcb1 - mvi c,fopen - call bdos - inr a ; FF = error - jz die - ;;; We can only read one 128-byte block at a time, and the file - ;;; will not fit in memory (max 64 k). So there are two things - ;;; going on here: we copy from the block into a word buffer - ;;; until we see the end of a line, at which point we process - ;;; the word. In the meantime, if while copying we reach the end - ;;; of the block, we read the next block. - lxi b,curwrd ; Word pointer -block: push b ; Keep word pointer while reading - lxi d,fcb1 ; Read a block from the file - mvi c,fread - call bdos - pop b ; Restore word pointer - dcr a ; 1 = EOF - jz done - inr a ; otherwise, <>0 = error - jnz die - lxi h,dma ; Start reading at DMA -char: mov a,m ; Get character - cpi EOF ; If it's an EOF character, we're done - jz done - stax b ; Store character in current word - inx b - cpi LF ; If it's LF, then we've got a full word - cz word ; Process the word - inr l ; Go to next character - jz block ; If we're done with this block, get next one - jmp char - ;;; When done, report the statistics -done: lxi d,scie ; CIE - call sout - lhld cie - call puthl - lxi d,sxie ; xIE - call sout - lhld xie - call puthl - lxi d,scei ; CEI - call sout - lhld cei - call puthl - lxi d,sxei ; xEI - call sout - lhld xei - call puthl - ;;; Then say what is and isn't plausible - lxi d,s_ienc ; I before E when not preceded by C - call sout ; plausible if 2*xIE>CIE - lhld cie - xchg - lhld xie - call pplaus - lxi d,s_eic ; E before I when preceded by C - call sout ; plausible if 2*CEI>xEI - lhld xei - xchg - lhld cei - ;;; If HL = amount of words with feature, and - ;;; DE = amount of words with opposit feature, then print - ;;; '(not) plausible', as appropriate. -pplaus: dad h ; 2 * feature - mov a,d ; Compare high byte - cmp h - jc plaus ; If 2*H>D then plausible - mov a,e ; Otherwise, compare low byte - cmp l - jc plaus ; If 2*L>E then plausible - lxi d,snop ; Otherwise, not plausible - jmp sout -plaus: lxi d,splau - jmp sout - ;;; Process a word -word: push h ; Save file read address - xra a ; Zero out end of word - stax b - dcx b - lxi h,curwrd ; Scan word -start: mov a,m ; Get current character - inx h ; Move pointer ahead - ana a ; If zero, - jz w_end ; we're done - cpi 'c' ; Did we find a 'c'? - jz findc - cpi 'e' ; Otherwise, did we find 'e'? - jz finde - cpi 'i' ; Otherwise, did we find 'i'? - jz findi - jmp start ; Otherwise, keep going - ;;; We found an 'e' -finde: mov a,m ; Get following character - cpi 'i' ; Is it 'i'? - jnz start ; If not, keep going - inx h ; Otherwise, move past it, - xchg ; keep pointer in DE, - lhld xie ; We found ie without c - inx h - shld xie - xchg - jmp start - ;;; We found an 'i' -findi: mov a,m ; Get following character - cpi 'e' ; Is it 'e'? - jnz start ; If not, keep going - inx h ; Otherwise, move past it, - xchg ; keep pointer in DE, - lhld xei ; We found ei without c - inx h - shld xei - xchg - jmp start - ;;; We found a 'c' -findc: mov a,m ; Get following character - cpi 'e' ; Is it 'e'? - jz findce ; Then we have 'ce' - cpi 'i' ; Is it 'i'? - jz findci ; Then we have 'ci' - jmp start ; Otherwise, just keep going -findce: mov d,h ; set DE = start of 'e?' - mov e,l - inx d ; Get next character - ldax d - cpi 'i' ; Is it 'i'? - jnz start ; If not, do nothing - lhld cei ; But if so, we found 'cei' - inx h ; Increment the counter - shld cei - xchg ; Keep scanning _after_ the 'cei' - inx h - jmp start -findci: mov d,h ; set DE = start of 'i?' - mov e,l - inx d ; Get next character - ldax d - cpi 'e' ; Is it 'e'? - jnz start ; If not, do nothing - lhld cie ; But if so, we found 'cie' - inx h ; Increment the counter - shld cie - xchg ; Keep scanning _after_ the 'cie' - inx h - jmp start -w_end: lxi b,curwrd ; Set word pointer to beginning - pop h ; Restore file read address - ret - ;;; Print error message and stop the program -die: lxi d,errmsg - mvi c,puts - call bdos - rst 0 - ;;; Print string -sout: mvi c,puts - jmp bdos - ;;; Print HL to the console as a decimal number -puthl: push h - lxi h,num - xthl - lxi b,-10 -dgt: lxi d,-1 -clcdgt: inx d - dad b - jc clcdgt - mov a,l - adi 10+'0' - xthl - dcx h - mov m,a - xthl - xchg - mov a,h - ora l - jnz dgt - pop d - mvi c,puts - jmp bdos -errmsg: db 'Error$' ; Good enough -s_ienc: db 'I before E when not preceded by C:$' -s_eic: db 'E before I when preceded by C:$' -snop: db ' not' -splau: db ' plausible',CR,LF,'$' -scie: db 'CIE: $' ; Report strings -sxie: db 'xIE: $' -scei: db 'CEI: $' -sxei: db 'xEI: $' - db '00000' -num: db CR,LF,'$' ; Space for number - ;;; Counters -xie: dw 0 ; I before E when not preceded by C -cie: dw 0 ; I before E when preceded by C -cei: dw 0 ; E before I when preceded by C -xei: dw 0 ; E before I when not preceded by C -curwrd: equ $ ; Current word stored here + ;;; I before E, except after C +fcb1: equ 5Ch ; FCB 1 (populated by file on command line) +dma: equ 80h ; Standard DMA location +bdos: equ 5 ; CP/M entry point +puts: equ 9 ; CP/M call to write a string to the console +fopen: equ 0Fh ; CP/M call to open a file +fread: equ 14h ; CP/M call to read from a file +CR: equ 13 +LF: equ 10 +EOF: equ 26 + org 100h + ;;; Open the file given on the command line + lxi d,fcb1 + mvi c,fopen + call bdos + inr a ; FF = error + jz die + ;;; We can only read one 128-byte block at a time, and the file + ;;; will not fit in memory (max 64 k). So there are two things + ;;; going on here: we copy from the block into a word buffer + ;;; until we see the end of a line, at which point we process + ;;; the word. In the meantime, if while copying we reach the end + ;;; of the block, we read the next block. + lxi b,curwrd ; Word pointer +block: push b ; Keep word pointer while reading + lxi d,fcb1 ; Read a block from the file + mvi c,fread + call bdos + pop b ; Restore word pointer + dcr a ; 1 = EOF + jz done + inr a ; otherwise, <>0 = error + jnz die + lxi h,dma ; Start reading at DMA +char: mov a,m ; Get character + cpi EOF ; If it's an EOF character, we're done + jz done + stax b ; Store character in current word + inx b + cpi LF ; If it's LF, then we've got a full word + cz word ; Process the word + inr l ; Go to next character + jz block ; If we're done with this block, get next one + jmp char + ;;; When done, report the statistics +done: lxi d,scie ; CIE + call sout + lhld cie + call puthl + lxi d,sxie ; xIE + call sout + lhld xie + call puthl + lxi d,scei ; CEI + call sout + lhld cei + call puthl + lxi d,sxei ; xEI + call sout + lhld xei + call puthl + ;;; Then say what is and isn't plausible + lxi d,s_ienc ; I before E when not preceded by C + call sout ; plausible if 2*xIE>CIE + lhld cie + xchg + lhld xie + call pplaus + lxi d,s_eic ; E before I when preceded by C + call sout ; plausible if 2*CEI>xEI + lhld xei + xchg + lhld cei + ;;; If HL = amount of words with feature, and + ;;; DE = amount of words with opposit feature, then print + ;;; '(not) plausible', as appropriate. +pplaus: dad h ; 2 * feature + mov a,d ; Compare high byte + cmp h + jc plaus ; If 2*H>D then plausible + mov a,e ; Otherwise, compare low byte + cmp l + jc plaus ; If 2*L>E then plausible + lxi d,snop ; Otherwise, not plausible + jmp sout +plaus: lxi d,splau + jmp sout + ;;; Process a word +word: push h ; Save file read address + xra a ; Zero out end of word + stax b + dcx b + lxi h,curwrd ; Scan word +start: mov a,m ; Get current character + inx h ; Move pointer ahead + ana a ; If zero, + jz w_end ; we're done + cpi 'c' ; Did we find a 'c'? + jz findc + cpi 'e' ; Otherwise, did we find 'e'? + jz finde + cpi 'i' ; Otherwise, did we find 'i'? + jz findi + jmp start ; Otherwise, keep going + ;;; We found an 'e' +finde: mov a,m ; Get following character + cpi 'i' ; Is it 'i'? + jnz start ; If not, keep going + inx h ; Otherwise, move past it, + xchg ; keep pointer in DE, + lhld xie ; We found ie without c + inx h + shld xie + xchg + jmp start + ;;; We found an 'i' +findi: mov a,m ; Get following character + cpi 'e' ; Is it 'e'? + jnz start ; If not, keep going + inx h ; Otherwise, move past it, + xchg ; keep pointer in DE, + lhld xei ; We found ei without c + inx h + shld xei + xchg + jmp start + ;;; We found a 'c' +findc: mov a,m ; Get following character + cpi 'e' ; Is it 'e'? + jz findce ; Then we have 'ce' + cpi 'i' ; Is it 'i'? + jz findci ; Then we have 'ci' + jmp start ; Otherwise, just keep going +findce: mov d,h ; set DE = start of 'e?' + mov e,l + inx d ; Get next character + ldax d + cpi 'i' ; Is it 'i'? + jnz start ; If not, do nothing + lhld cei ; But if so, we found 'cei' + inx h ; Increment the counter + shld cei + xchg ; Keep scanning _after_ the 'cei' + inx h + jmp start +findci: mov d,h ; set DE = start of 'i?' + mov e,l + inx d ; Get next character + ldax d + cpi 'e' ; Is it 'e'? + jnz start ; If not, do nothing + lhld cie ; But if so, we found 'cie' + inx h ; Increment the counter + shld cie + xchg ; Keep scanning _after_ the 'cie' + inx h + jmp start +w_end: lxi b,curwrd ; Set word pointer to beginning + pop h ; Restore file read address + ret + ;;; Print error message and stop the program +die: lxi d,errmsg + mvi c,puts + call bdos + rst 0 + ;;; Print string +sout: mvi c,puts + jmp bdos + ;;; Print HL to the console as a decimal number +puthl: push h + lxi h,num + xthl + lxi b,-10 +dgt: lxi d,-1 +clcdgt: inx d + dad b + jc clcdgt + mov a,l + adi 10+'0' + xthl + dcx h + mov m,a + xthl + xchg + mov a,h + ora l + jnz dgt + pop d + mvi c,puts + jmp bdos +errmsg: db 'Error$' ; Good enough +s_ienc: db 'I before E when not preceded by C:$' +s_eic: db 'E before I when preceded by C:$' +snop: db ' not' +splau: db ' plausible',CR,LF,'$' +scie: db 'CIE: $' ; Report strings +sxie: db 'xIE: $' +scei: db 'CEI: $' +sxei: db 'xEI: $' + db '00000' +num: db CR,LF,'$' ; Space for number + ;;; Counters +xie: dw 0 ; I before E when not preceded by C +cie: dw 0 ; I before E when preceded by C +cei: dw 0 ; E before I when preceded by C +xei: dw 0 ; E before I when not preceded by C +curwrd: equ $ ; Current word stored here diff --git a/Task/I-before-E-except-after-C/ALGOL-68/i-before-e-except-after-c.alg b/Task/I-before-E-except-after-C/ALGOL-68/i-before-e-except-after-c.alg index 3193288160..e67eb3f84b 100644 --- a/Task/I-before-E-except-after-C/ALGOL-68/i-before-e-except-after-c.alg +++ b/Task/I-before-E-except-after-C/ALGOL-68/i-before-e-except-after-c.alg @@ -1,80 +1,67 @@ -# tests the plausibility of "i before e except after c" using unixdict.txt # +BEGIN # use unixdict.txt to test the plausibility of # + # "i before e except after c" # -# implements the plausibility test specified by the task # -# returns TRUE if with > 2 * without # -PROC plausible = ( INT with, without )BOOL: with > 2 * without; + PR read "files.incl.a68" PR # include file utilities # -# shows the plausibility of with and without # -PROC show plausibility = ( STRING legend, INT with, without )VOID: - print( ( legend, IF plausible( with, without ) THEN " is plausible" ELSE " is not plausible" FI, newline ) ); + # implements the plausibility test specified by the task # + # returns TRUE if with > 2 * without # + PROC plausible = ( INT with, without )BOOL: with > 2 * without; + + # shows the plausibility of with and without # + PROC show plausibility = ( STRING legend, INT with, without )VOID: + print( ( legend, " is ", IF plausible( with, without ) THEN "" ELSE "not " FI + , "plausible", newline + ) + ); -IF FILE input file; - STRING file name = "unixdict.txt"; - open( input file, file name, stand in channel ) /= 0 -THEN - # failed to open the file # - print( ( "Unable to open """ + file name + """", newline ) ) -ELSE - # file opened OK # - BOOL at eof := FALSE; - # set the EOF handler for the file # - on logical file end( input file, ( REF FILE f )BOOL: - BEGIN - # note that we reached EOF on the # - # latest read # - at eof := TRUE; - # return TRUE so processing can continue # - TRUE - END - ); INT cei := 0; INT xei := 0; INT cie := 0; INT xie := 0; - WHILE STRING word; - get( input file, ( word, newline ) ); - NOT at eof - DO - # examine the word for cie, xie (x /= c), cei and xei (x /= c) # - FOR pos FROM LWB word TO UPB word DO word[ pos ] := to lower( word[ pos ] ) OD; - IF word = "ie" THEN + + # examines word for cie, xie (x /= c), cei and xei (x /= c) # + PROC test i before e = ( STRING word )VOID: + IF word = "ie" THEN xie +:= 1 - ELIF word = "ei" THEN + ELIF word = "ei" THEN xei +:= 1 - ELSE + ELSE INT length = ( UPB word - LWB word ) + 1; IF length > 1 THEN IF word[ LWB word ] = "i" AND word[ LWB word + 1 ] = "e" THEN - # word starts ie # + # word starts ie # xie +:= 1 ELIF word[ LWB word ] = "e" AND word[ LWB word + 1 ] = "i" THEN - # word starts ei # + # word starts ei # xei +:= 1 FI; FOR pos FROM LWB word + 1 TO UPB word - 1 DO IF word[ pos ] = "i" AND word[ pos + 1 ] = "e" THEN - # have i before e, check the preceeding character # + # have i before e, check the preceeding character # IF word[ pos - 1 ] = "c" THEN cie ELSE xie FI +:= 1 ELIF word[ pos ] = "e" AND word[ pos + 1 ] = "i" THEN - # have e before i, check the preceeding character # + # have e before i, check the preceeding character # IF word[ pos - 1 ] = "c" THEN cei ELSE xei FI +:= 1 FI OD FI - FI - OD; - # close the file # - close( input file ); + FI # test i before e # ; # test the hypothesis # - print( ( "cie occurances: ", whole( cie, 0 ), newline ) ); - print( ( "xie occurances: ", whole( xie, 0 ), newline ) ); - print( ( "cei occurances: ", whole( cei, 0 ), newline ) ); - print( ( "xei occurances: ", whole( xei, 0 ), newline ) ); - show plausibility( "i before e except after c", xie, cie ); - show plausibility( "e before i except after c", xei, cei ); - show plausibility( "i before e when after c", cie, xie ); - show plausibility( "e before i when after c", cei, xei ); - show plausibility( "i before e in general", xie + cie, xei + cei ); - show plausibility( "e before i in general", xei + cei, xie + cie ) -FI + + IF "unixdict.txt" EACHLINE test i before e < 0 THEN + print( ( "Unable to open unixdict.txt", newline ) ) + ELSE + print( ( "cie occurances: ", whole( cie, 0 ), newline ) ); + print( ( "xie occurances: ", whole( xie, 0 ), newline ) ); + print( ( "cei occurances: ", whole( cei, 0 ), newline ) ); + print( ( "xei occurances: ", whole( xei, 0 ), newline ) ); + show plausibility( "i before e except after c", xie, cie ); + show plausibility( "e before i except after c", xei, cei ); + show plausibility( "i before e when after c", cie, xie ); + show plausibility( "e before i when after c", cei, xei ); + show plausibility( "i before e in general", xie + cie, xei + cei ); + show plausibility( "e before i in general", xei + cei, xie + cie ) + FI + +END diff --git a/Task/I-before-E-except-after-C/AWK/i-before-e-except-after-c.awk b/Task/I-before-E-except-after-C/AWK/i-before-e-except-after-c.awk index a9ab9fde37..0d1c85ae20 100644 --- a/Task/I-before-E-except-after-C/AWK/i-before-e-except-after-c.awk +++ b/Task/I-before-E-except-after-C/AWK/i-before-e-except-after-c.awk @@ -7,20 +7,20 @@ /cie/ {cie+=cnt($3)} function cnt(c) { - if (c<1) return 1; - return c; + if (c<1) return 1; + return c; } END { - printf("cie: %i\nnie: %i\ncei: %i\nnei: %i\n",cie,nie-cie,cei,nei-cei); - v = v2 = ""; - if (nie < 3 * cie) { - v =" not"; - } - print "I before E when not preceded by C: is"v" plausible"; - if (nei > 3 * cei) { - v = v2 =" not"; - } - print "E before I when preceded by C: is"v2" plausible"; + printf("cie: %i\nnie: %i\ncei: %i\nnei: %i\n",cie,nie-cie,cei,nei-cei); + v = v2 = ""; + if (nie < 3 * cie) { + v =" not"; + } + print "I before E when not preceded by C: is"v" plausible"; + if (nei > 3 * cei) { + v = v2 =" not"; + } + print "E before I when preceded by C: is"v2" plausible"; print "Overall rule is"v" plausible"; } diff --git a/Task/I-before-E-except-after-C/AutoHotkey/i-before-e-except-after-c.ahk b/Task/I-before-E-except-after-C/AutoHotkey/i-before-e-except-after-c.ahk index a9fc81bf1f..a0ee96da0f 100644 --- a/Task/I-before-E-except-after-C/AutoHotkey/i-before-e-except-after-c.ahk +++ b/Task/I-before-E-except-after-C/AutoHotkey/i-before-e-except-after-c.ahk @@ -1,4 +1,4 @@ -WordList := URL_ToVar("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt") +WordList := URL_ToVar("https://web.archive.org/web/20240920144647if_/http://wiki.puzzlers.org/pub/wordlists/unixdict.txt") WordList := RegExReplace(WordList, "i)cie", "", cieN) WordList := RegExReplace(WordList, "i)cei", "", ceiN) RegExReplace(WordList, "i)ie", "", ieN) diff --git a/Task/I-before-E-except-after-C/BASIC256/i-before-e-except-after-c.basic b/Task/I-before-E-except-after-C/BASIC256/i-before-e-except-after-c.basic index c2e1212f95..0a47a1548e 100644 --- a/Task/I-before-E-except-after-C/BASIC256/i-before-e-except-after-c.basic +++ b/Task/I-before-E-except-after-C/BASIC256/i-before-e-except-after-c.basic @@ -2,13 +2,13 @@ CI = 0 : XI = 0 : CE = 0 : XE = 0 open 1, "unixdict.txt" do - pal$ = readline (1) - if instr(pal$, "ie") then - if instr(pal$, "cie") then CI += 1 else XI += 1 - endif - if instr(pal$, "ei") then - if instr(pal$, "cei") then CE += 1 else XE += 1 - endif + pal$ = readline (1) + if instr(pal$, "ie") then + if instr(pal$, "cie") then CI += 1 else XI += 1 + endif + if instr(pal$, "ei") then + if instr(pal$, "cei") then CE += 1 else XE += 1 + endif until eof(1) close 1 diff --git a/Task/I-before-E-except-after-C/BQN/i-before-e-except-after-c.bqn b/Task/I-before-E-except-after-C/BQN/i-before-e-except-after-c.bqn new file mode 100644 index 0000000000..dbbec600b8 --- /dev/null +++ b/Task/I-before-E-except-after-C/BQN/i-before-e-except-after-c.bqn @@ -0,0 +1,15 @@ +Func ← { + Filter ← {+´(∨´∘(𝕨⊸⍷))¨𝕩} + nei ← "ei" Filter 𝕩 + cei ← "cei" Filter 𝕩 + nie ← "ie" Filter 𝕩 + cie ← "cie" Filter 𝕩 + •Show (nie < 2×cie)◶⟨ + "I before E when not preceded by C is plausible" + "I before E when not preceded by C is not plausible" + ⟩@ + (nei > 2×cei)◶⟨ + "E before I when preceded by C is plausible" + "E before I when preceded by C is not plausible" + ⟩@ +} diff --git a/Task/I-before-E-except-after-C/Batch-File/i-before-e-except-after-c-1.bat b/Task/I-before-E-except-after-C/Batch-File/i-before-e-except-after-c-1.bat index 1962c47d0e..6a0a353d2b 100644 --- a/Task/I-before-E-except-after-C/Batch-File/i-before-e-except-after-c-1.bat +++ b/Task/I-before-E-except-after-C/Batch-File/i-before-e-except-after-c-1.bat @@ -3,7 +3,7 @@ @echo off setlocal enabledelayedexpansion - ::Initialization + ::Initialization set ie=0 set ei=0 set cie=0 @@ -13,13 +13,13 @@ set propos1=FALSE set propos2=FALSE set propos3=FALSE - ::Do the matching + ::Do the matching for /f %%X in (unixdict.txt) do ( - set word=%%X - if not "!word:ie=!"=="!word!" if "!word:cie=!"=="!word!" (set /a ie+=1) - if not "!word:ei=!"=="!word!" if "!word:cei=!"=="!word!" (set /a ei+=1) - if not "!word:cei=!"=="!word!" (set /a cei+=1) - if not "!word:cie=!"=="!word!" (set /a cie+=1) + set word=%%X + if not "!word:ie=!"=="!word!" if "!word:cie=!"=="!word!" (set /a ie+=1) + if not "!word:ei=!"=="!word!" if "!word:cei=!"=="!word!" (set /a ei+=1) + if not "!word:cei=!"=="!word!" (set /a cei+=1) + if not "!word:cie=!"=="!word!" (set /a cie+=1) ) set /a "counter1=!ei!*2,counter2=!cie!*2" diff --git a/Task/I-before-E-except-after-C/Clojure/i-before-e-except-after-c.clj b/Task/I-before-E-except-after-C/Clojure/i-before-e-except-after-c.clj index 73fef20309..9d895b2b68 100644 --- a/Task/I-before-E-except-after-C/Clojure/i-before-e-except-after-c.clj +++ b/Task/I-before-E-except-after-C/Clojure/i-before-e-except-after-c.clj @@ -47,7 +47,7 @@ format-line))) (defn -main [] - (with-open [rdr (clojure.java.io/reader "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt")] + (with-open [rdr (clojure.java.io/reader "https://web.archive.org/web/20240920144647if_/http://wiki.puzzlers.org/pub/wordlists/unixdict.txt")] (i-before-e-except-after-c-plausible? "Check unixdist list" (apply-freq-1 (line-seq rdr)))) (with-open [rdr (clojure.java.io/reader "http://ucrel.lancs.ac.uk/bncfreq/lists/1_2_all_freq.txt")] (i-before-e-except-after-c-plausible? "Word frequencies (stretch goal)" (map format-freq-line (drop 1 (line-seq rdr)))))) diff --git a/Task/I-before-E-except-after-C/Delphi/i-before-e-except-after-c.delphi b/Task/I-before-E-except-after-C/Delphi/i-before-e-except-after-c.pas similarity index 100% rename from Task/I-before-E-except-after-C/Delphi/i-before-e-except-after-c.delphi rename to Task/I-before-E-except-after-C/Delphi/i-before-e-except-after-c.pas diff --git a/Task/I-before-E-except-after-C/Ed/i-before-e-except-after-c-1.ed b/Task/I-before-E-except-after-C/Ed/i-before-e-except-after-c-1.ed new file mode 100644 index 0000000000..b8a34ecd14 --- /dev/null +++ b/Task/I-before-E-except-after-C/Ed/i-before-e-except-after-c-1.ed @@ -0,0 +1,32 @@ +# i-before-e.ed +H +# Remove all the non-rule-related words +v/(ie|ei)/d +# Replace the occurences with one-letter markers +g/ei/s/.*/e/ +g/ie/s/.*/i/ +,j +# Remove 1 occurence of e (alternative) per two i (null) +s/eii//g +s/iie//g +s/eii//g +s/iie//g +s/eii//g +s/iie//g +s/eii//g +s/iie//g +s/eii//g +s/iie//g +s/eii//g +s/iie//g +s/eii//g +s/iie//g +s/eii//g +s/iie//g +s/eii//g +s/iie//g +s/eii//g +s/iie//g +# Check whether there are more i's in the output (null hypothesis true) or not +,p +Q diff --git a/Task/I-before-E-except-after-C/Ed/i-before-e-except-after-c-2.ed b/Task/I-before-E-except-after-C/Ed/i-before-e-except-after-c-2.ed new file mode 100644 index 0000000000..44cdaeb3a9 --- /dev/null +++ b/Task/I-before-E-except-after-C/Ed/i-before-e-except-after-c-2.ed @@ -0,0 +1,35 @@ +# e-before-i-with-c.ed +H +# Remove all the non-rule-related words +v/(cie|cei)/d +# Replace the occurences with one-letter markers +g/ei/s/.*/e/ +g/ie/s/.*/i/ +,j +# Remove 1 occurence of i (alternative) per two e (null) +s/iee// +s/eei// +s/iee// +s/eei// +s/iee// +s/eei// +s/iee// +s/eei// +s/iee// +s/eei// +s/iee// +s/eei// +s/iee// +s/eei// +s/iee// +s/eei// +s/iee// +s/eei// +s/iee// +s/eei// +s/iee// +s/eei// +s/iee// +# Check whether there are more e's in the output (null hypothesis true) or not +,p +Q diff --git a/Task/I-before-E-except-after-C/Elixir/i-before-e-except-after-c.elixir b/Task/I-before-E-except-after-C/Elixir/i-before-e-except-after-c.ex similarity index 100% rename from Task/I-before-E-except-after-C/Elixir/i-before-e-except-after-c.elixir rename to Task/I-before-E-except-after-C/Elixir/i-before-e-except-after-c.ex diff --git a/Task/I-before-E-except-after-C/F-Sharp/i-before-e-except-after-c.fs b/Task/I-before-E-except-after-C/F-Sharp/i-before-e-except-after-c.fs new file mode 100644 index 0000000000..501506f0fb --- /dev/null +++ b/Task/I-before-E-except-after-C/F-Sharp/i-before-e-except-after-c.fs @@ -0,0 +1,9 @@ +// I before E except after C. Nigel Galloway: September 30th., 2024 +type plausibility=Plausible|Implausible +let fN n g=System.Text.RegularExpressions.Regex.Matches(n,g).Count +let fG n g=g|>Array.map2(fun n g->n+g)[|n("ie");n("ei");n("cie");n("cei")|] +let n=System.IO.File.ReadLines("unixdict.txt")|>Seq.fold(fun n g->fG (fN g) n)[|0;0;0;0|] +printfn($"I before E except after C is {if n[0]-n[2]>2*n[2] then Plausible else Implausible}") +printfn($"E before I except after C is {if n[1]-n[3]>2*n[3] then Plausible else Implausible}") +printfn($"I before E when after C is {if n[2]>2*n[3] then Plausible else Implausible}") +printfn($"E before I when after C is {if n[3]>2*n[2] then Plausible else Implausible}") diff --git a/Task/I-before-E-except-after-C/FutureBasic/i-before-e-except-after-c.basic b/Task/I-before-E-except-after-C/FutureBasic/i-before-e-except-after-c.basic index 8e02afd17b..86599ccbef 100644 --- a/Task/I-before-E-except-after-C/FutureBasic/i-before-e-except-after-c.basic +++ b/Task/I-before-E-except-after-C/FutureBasic/i-before-e-except-after-c.basic @@ -22,7 +22,7 @@ void local fn CheckWord( wrd as CFStringRef, txt as CFStringRef, c as ^long, x a end fn void local fn Doit - CFURLRef url = fn URLWithString( @"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt" ) + CFURLRef url = fn URLWithString( @"https://web.archive.org/web/20240920144647if_/http://wiki.puzzlers.org/pub/wordlists/unixdict.txt" ) CFStringRef string = fn StringWithContentsOfURL( url, NSUTF8StringEncoding, NULL ) CFArrayRef words = fn StringComponentsSeparatedByCharactersInSet( string, fn CharacterSetNewlineSet ) long cei = 0, cie = 0, xei = 0, xie = 0 diff --git a/Task/I-before-E-except-after-C/Go/i-before-e-except-after-c.go b/Task/I-before-E-except-after-C/Go/i-before-e-except-after-c.go index 69374b52c6..90b5c6c681 100644 --- a/Task/I-before-E-except-after-C/Go/i-before-e-except-after-c.go +++ b/Task/I-before-E-except-after-C/Go/i-before-e-except-after-c.go @@ -1,68 +1,68 @@ package main import ( - "bufio" - "fmt" - "log" - "os" - "regexp" - "strings" + "bufio" + "fmt" + "log" + "os" + "regexp" + "strings" ) func main() { - f, err := os.Open("unixdict.txt") - if err != nil { - log.Fatalln(err) - } - defer f.Close() + f, err := os.Open("unixdict.txt") + if err != nil { + log.Fatalln(err) + } + defer f.Close() - s := bufio.NewScanner(f) - rie := regexp.MustCompile("^ie|[^c]ie") - rei := regexp.MustCompile("^ei|[^c]ei") - var cie, ie int - var cei, ei int - for s.Scan() { - line := s.Text() - if strings.Contains(line, "cie") { - cie++ - } - if strings.Contains(line, "cei") { - cei++ - } - if rie.MatchString(line) { - ie++ - } - if rei.MatchString(line) { - ei++ - } - } - err = s.Err() - if err != nil { - log.Fatalln(err) - } + s := bufio.NewScanner(f) + rie := regexp.MustCompile("^ie|[^c]ie") + rei := regexp.MustCompile("^ei|[^c]ei") + var cie, ie int + var cei, ei int + for s.Scan() { + line := s.Text() + if strings.Contains(line, "cie") { + cie++ + } + if strings.Contains(line, "cei") { + cei++ + } + if rie.MatchString(line) { + ie++ + } + if rei.MatchString(line) { + ei++ + } + } + err = s.Err() + if err != nil { + log.Fatalln(err) + } - if check(ie, ei, "I before E when not preceded by C") && - check(cei, cie, "E before I when preceded by C") { - fmt.Println("Both plausable.") - fmt.Println(`"I before E, except after C" is plausable.`) - } else { - fmt.Println("One or both implausable.") - fmt.Println(`"I before E, except after C" is implausable.`) - } + if check(ie, ei, "I before E when not preceded by C") && + check(cei, cie, "E before I when preceded by C") { + fmt.Println("Both plausable.") + fmt.Println(`"I before E, except after C" is plausable.`) + } else { + fmt.Println("One or both implausable.") + fmt.Println(`"I before E, except after C" is implausable.`) + } } // check checks if a statement is plausible. Something is plausible if a is more // than two times b. func check(a, b int, s string) bool { - switch { - case a > b*2: - fmt.Printf("%q is plausible (%d vs %d).\n", s, a, b) - return true - case a >= b: - fmt.Printf("%q is implausible (%d vs %d).\n", s, a, b) - default: - fmt.Printf("%q is implausible and contra-indicated (%d vs %d).\n", - s, a, b) - } - return false + switch { + case a > b*2: + fmt.Printf("%q is plausible (%d vs %d).\n", s, a, b) + return true + case a >= b: + fmt.Printf("%q is implausible (%d vs %d).\n", s, a, b) + default: + fmt.Printf("%q is implausible and contra-indicated (%d vs %d).\n", + s, a, b) + } + return false } diff --git a/Task/I-before-E-except-after-C/Haskell/i-before-e-except-after-c.hs b/Task/I-before-E-except-after-C/Haskell/i-before-e-except-after-c.hs index a39c070d5a..120acd246d 100644 --- a/Task/I-before-E-except-after-C/Haskell/i-before-e-except-after-c.hs +++ b/Task/I-before-E-except-after-C/Haskell/i-before-e-except-after-c.hs @@ -6,7 +6,7 @@ getWordList :: IO String getWordList = do response <- simpleHTTP.getRequest$ url getResponseBody response - where url = "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt" + where url = "https://web.archive.org/web/20240920144647if_/http://wiki.puzzlers.org/pub/wordlists/unixdict.txt" main = do words <- getWordList diff --git a/Task/I-before-E-except-after-C/Icon/i-before-e-except-after-c-1.icon b/Task/I-before-E-except-after-C/Icon/i-before-e-except-after-c-1.icon index 088d2b2af3..d7c5f7c825 100644 --- a/Task/I-before-E-except-after-C/Icon/i-before-e-except-after-c-1.icon +++ b/Task/I-before-E-except-after-C/Icon/i-before-e-except-after-c-1.icon @@ -1,4 +1,4 @@ -import Utils # To get the FindFirst class +import Utils # To get the FindFirst class procedure main(a) showCounts := "--showcounts" == !a diff --git a/Task/I-before-E-except-after-C/Icon/i-before-e-except-after-c-2.icon b/Task/I-before-E-except-after-C/Icon/i-before-e-except-after-c-2.icon index 2f669b47d1..c3df84f390 100644 --- a/Task/I-before-E-except-after-C/Icon/i-before-e-except-after-c-2.icon +++ b/Task/I-before-E-except-after-C/Icon/i-before-e-except-after-c-2.icon @@ -1,4 +1,4 @@ -import Utils # To get the FindFirst class +import Utils # To get the FindFirst class procedure main(a) WS := " \t" diff --git a/Task/I-before-E-except-after-C/Java/i-before-e-except-after-c-2.java b/Task/I-before-E-except-after-C/Java/i-before-e-except-after-c-2.java index 83eba7931c..5ccca284f7 100644 --- a/Task/I-before-E-except-after-C/Java/i-before-e-except-after-c-2.java +++ b/Task/I-before-E-except-after-C/Java/i-before-e-except-after-c-2.java @@ -12,7 +12,7 @@ static int cei = 0; static int cie = 0; static void count() throws URISyntaxException, IOException { - URL url = new URI("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt").toURL(); + URL url = new URI("https://web.archive.org/web/20240920144647if_/http://wiki.puzzlers.org/pub/wordlists/unixdict.txt").toURL(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()))) { String line; while ((line = reader.readLine()) != null) { diff --git a/Task/I-before-E-except-after-C/Java/i-before-e-except-after-c-3.java b/Task/I-before-E-except-after-C/Java/i-before-e-except-after-c-3.java index f53d8476aa..2af84999ac 100644 --- a/Task/I-before-E-except-after-C/Java/i-before-e-except-after-c-3.java +++ b/Task/I-before-E-except-after-C/Java/i-before-e-except-after-c-3.java @@ -3,56 +3,56 @@ import java.io.FileReader; public class IbeforeE { - public static void main(String[] args) - { - IbeforeE now=new IbeforeE(); - String wordlist="unixdict.txt"; - if(now.isPlausibleRule(wordlist)) - System.out.println("Rule is plausible."); - else - System.out.println("Rule is not plausible."); - } - boolean isPlausibleRule(String filename) - { - int truecount=0,falsecount=0; - try - { - BufferedReader br=new BufferedReader(new FileReader(filename)); - String word; - while((word=br.readLine())!=null) - { - if(isPlausibleWord(word)) - truecount++; - else if(isOppPlausibleWord(word)) - falsecount++; - } - br.close(); - } - catch(Exception e) - { - System.out.println("Something went horribly wrong: "+e.getMessage()); - } - - System.out.println("Plausible count: "+truecount); - System.out.println("Implausible count: "+falsecount); - if(truecount>2*falsecount) - return true; - return false; - } - boolean isPlausibleWord(String word) - { - if(!word.contains("c")&&word.contains("ie")) - return true; - else if(word.contains("cei")) - return true; - return false; - } - boolean isOppPlausibleWord(String word) - { - if(!word.contains("c")&&word.contains("ei")) - return true; - else if(word.contains("cie")) - return true; - return false; - } + public static void main(String[] args) + { + IbeforeE now=new IbeforeE(); + String wordlist="unixdict.txt"; + if(now.isPlausibleRule(wordlist)) + System.out.println("Rule is plausible."); + else + System.out.println("Rule is not plausible."); + } + boolean isPlausibleRule(String filename) + { + int truecount=0,falsecount=0; + try + { + BufferedReader br=new BufferedReader(new FileReader(filename)); + String word; + while((word=br.readLine())!=null) + { + if(isPlausibleWord(word)) + truecount++; + else if(isOppPlausibleWord(word)) + falsecount++; + } + br.close(); + } + catch(Exception e) + { + System.out.println("Something went horribly wrong: "+e.getMessage()); + } + + System.out.println("Plausible count: "+truecount); + System.out.println("Implausible count: "+falsecount); + if(truecount>2*falsecount) + return true; + return false; + } + boolean isPlausibleWord(String word) + { + if(!word.contains("c")&&word.contains("ie")) + return true; + else if(word.contains("cei")) + return true; + return false; + } + boolean isOppPlausibleWord(String word) + { + if(!word.contains("c")&&word.contains("ei")) + return true; + else if(word.contains("cie")) + return true; + return false; + } } diff --git a/Task/I-before-E-except-after-C/Julia/i-before-e-except-after-c.julia b/Task/I-before-E-except-after-C/Julia/i-before-e-except-after-c.jl similarity index 100% rename from Task/I-before-E-except-after-C/Julia/i-before-e-except-after-c.julia rename to Task/I-before-E-except-after-C/Julia/i-before-e-except-after-c.jl diff --git a/Task/I-before-E-except-after-C/Kotlin/i-before-e-except-after-c.kotlin b/Task/I-before-E-except-after-C/Kotlin/i-before-e-except-after-c.kotlin deleted file mode 100644 index b1cc1898fb..0000000000 --- a/Task/I-before-E-except-after-C/Kotlin/i-before-e-except-after-c.kotlin +++ /dev/null @@ -1,61 +0,0 @@ -// version 1.0.6 - -import java.net.URL -import java.io.InputStreamReader -import java.io.BufferedReader - -fun isPlausible(n1: Int, n2: Int) = n1 > 2 * n2 - -fun printResults(source: String, counts: IntArray) { - println("Results for $source") - println(" i before e except after c") - println(" for ${counts[0]}") - println(" against ${counts[1]}") - val plausible1 = isPlausible(counts[0], counts[1]) - println(" sub-rule is${if (plausible1) "" else " not"} plausible\n") - println(" e before i when preceded by c") - println(" for ${counts[2]}") - println(" against ${counts[3]}") - val plausible2 = isPlausible(counts[2], counts[3]) - println(" sub-rule is${if (plausible2) "" else " not"} plausible\n") - val plausible = plausible1 && plausible2 - println(" rule is${if (plausible) "" else " not"} plausible") -} - -fun main(args: Array) { - val url = URL("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt") - val isr = InputStreamReader(url.openStream()) - val reader = BufferedReader(isr) - val regexes = arrayOf( - Regex("(^|[^c])ie"), // i before e when not preceded by c (includes words starting with ie) - Regex("(^|[^c])ei"), // e before i when not preceded by c (includes words starting with ei) - Regex("cei"), // e before i when preceded by c - Regex("cie") // i before e when preceded by c - ) - val counts = IntArray(4) // corresponding counts of occurrences - var word = reader.readLine() - while (word != null) { - for (i in 0..3) counts[i] += regexes[i].findAll(word).toList().size - word = reader.readLine() - } - reader.close() - printResults("unixdict.txt", counts) - - val url2 = URL("http://ucrel.lancs.ac.uk/bncfreq/lists/1_2_all_freq.txt") - val isr2 = InputStreamReader(url2.openStream()) - val reader2 = BufferedReader(isr2) - val counts2 = IntArray(4) - reader2.readLine() // read header line - var line = reader2.readLine() // read first line and store it - var words: List - val splitter = Regex("""(\t+|\s+)""") - while (line != null) { - words = line.split(splitter) - if (words.size == 4) // first element is empty - for (i in 0..3) counts2[i] += regexes[i].findAll(words[1]).toList().size * words[3].toInt() - line = reader2.readLine() - } - reader2.close() - println() - printResults("British National Corpus", counts2) -} diff --git a/Task/I-before-E-except-after-C/Kotlin/i-before-e-except-after-c.kts b/Task/I-before-E-except-after-C/Kotlin/i-before-e-except-after-c.kts new file mode 100644 index 0000000000..038c8a089d --- /dev/null +++ b/Task/I-before-E-except-after-C/Kotlin/i-before-e-except-after-c.kts @@ -0,0 +1,61 @@ +// version 1.0.6 + +import java.net.URL +import java.io.InputStreamReader +import java.io.BufferedReader + +fun isPlausible(n1: Int, n2: Int) = n1 > 2 * n2 + +fun printResults(source: String, counts: IntArray) { + println("Results for $source") + println(" i before e except after c") + println(" for ${counts[0]}") + println(" against ${counts[1]}") + val plausible1 = isPlausible(counts[0], counts[1]) + println(" sub-rule is${if (plausible1) "" else " not"} plausible\n") + println(" e before i when preceded by c") + println(" for ${counts[2]}") + println(" against ${counts[3]}") + val plausible2 = isPlausible(counts[2], counts[3]) + println(" sub-rule is${if (plausible2) "" else " not"} plausible\n") + val plausible = plausible1 && plausible2 + println(" rule is${if (plausible) "" else " not"} plausible") +} + +fun main(args: Array) { + val url = URL("https://web.archive.org/web/20240920144647if_/http://wiki.puzzlers.org/pub/wordlists/unixdict.txt") + val isr = InputStreamReader(url.openStream()) + val reader = BufferedReader(isr) + val regexes = arrayOf( + Regex("(^|[^c])ie"), // i before e when not preceded by c (includes words starting with ie) + Regex("(^|[^c])ei"), // e before i when not preceded by c (includes words starting with ei) + Regex("cei"), // e before i when preceded by c + Regex("cie") // i before e when preceded by c + ) + val counts = IntArray(4) // corresponding counts of occurrences + var word = reader.readLine() + while (word != null) { + for (i in 0..3) counts[i] += regexes[i].findAll(word).toList().size + word = reader.readLine() + } + reader.close() + printResults("unixdict.txt", counts) + + val url2 = URL("http://ucrel.lancs.ac.uk/bncfreq/lists/1_2_all_freq.txt") + val isr2 = InputStreamReader(url2.openStream()) + val reader2 = BufferedReader(isr2) + val counts2 = IntArray(4) + reader2.readLine() // read header line + var line = reader2.readLine() // read first line and store it + var words: List + val splitter = Regex("""(\t+|\s+)""") + while (line != null) { + words = line.split(splitter) + if (words.size == 4) // first element is empty + for (i in 0..3) counts2[i] += regexes[i].findAll(words[1]).toList().size * words[3].toInt() + line = reader2.readLine() + } + reader2.close() + println() + printResults("British National Corpus", counts2) +} diff --git a/Task/I-before-E-except-after-C/Langur/i-before-e-except-after-c.langur b/Task/I-before-E-except-after-C/Langur/i-before-e-except-after-c.langur new file mode 100644 index 0000000000..77ef21052e --- /dev/null +++ b/Task/I-before-E-except-after-C/Langur/i-before-e-except-after-c.langur @@ -0,0 +1,24 @@ +val words = less(split(readfile("./data/unixdict.txt"), delim="\n"), of=1) + +val print = fn*(support number, against number) { + val ratio = support / against + writeln "{{support}} / {{against}} = {{ratio : r2}}:", (ratio < 2) * " NOT", " PLAUSIBLE" + return if(ratio >= 2: 1; 0) +} + +val ks = fw/ei cei ie cie/ +var cnt = {:} + +for w in words { + for k in ks { + cnt[k; 0] += if(k in w: 1; 0) + } +} + +val support = cnt'ie - cnt'cie +val against = cnt'ei - cnt'cei + +var result = print(support, against) +result += print(cnt'cei, cnt'cie) + +writeln "Overall:", (result < 2) * " NOT", " PLAUSIBLE\n" diff --git a/Task/I-before-E-except-after-C/Lasso/i-before-e-except-after-c.lasso b/Task/I-before-E-except-after-C/Lasso/i-before-e-except-after-c.lasso index abf4c7e67f..12f0b1464b 100644 --- a/Task/I-before-E-except-after-C/Lasso/i-before-e-except-after-c.lasso +++ b/Task/I-before-E-except-after-C/Lasso/i-before-e-except-after-c.lasso @@ -3,7 +3,7 @@ local(cie,cei,ie,ei) = (:0,0,0,0) local(match_ie) = regExp(`[^c]ie`) local(match_ei) = regExp(`[^c]ei`) -with word in include_url(`http://wiki.puzzlers.org/pub/wordlists/unixdict.txt`)->asString->split("\n") +with word in include_url(`https://web.archive.org/web/20240920144647if_/http://wiki.puzzlers.org/pub/wordlists/unixdict.txt`)->asString->split("\n") where #word >> `ie` or #word >> `ei` do { #word >> `cie` diff --git a/Task/I-before-E-except-after-C/Lua/i-before-e-except-after-c.lua b/Task/I-before-E-except-after-C/Lua/i-before-e-except-after-c.lua index 50509a26fa..7c37aaeb8a 100644 --- a/Task/I-before-E-except-after-C/Lua/i-before-e-except-after-c.lua +++ b/Task/I-before-E-except-after-C/Lua/i-before-e-except-after-c.lua @@ -22,7 +22,7 @@ function plaus (case, opposite, words) end -- Main procedure -local page = http.request("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt") +local page = http.request("https://web.archive.org/web/20240920144647if_/http://wiki.puzzlers.org/pub/wordlists/unixdict.txt") io.write("I before E when not preceded by C: ") local sub1 = plaus("[^c]ie", "cie", page) io.write("E before I when preceded by C: ") diff --git a/Task/I-before-E-except-after-C/MATLAB/i-before-e-except-after-c.m b/Task/I-before-E-except-after-C/MATLAB/i-before-e-except-after-c.m index e1d2657819..14c84de23a 100644 --- a/Task/I-before-E-except-after-C/MATLAB/i-before-e-except-after-c.m +++ b/Task/I-before-E-except-after-C/MATLAB/i-before-e-except-after-c.m @@ -1,5 +1,5 @@ function iBeforeE() -check('http://wiki.puzzlers.org/pub/wordlists/unixdict.txt'); +check('https://web.archive.org/web/20240920144647if_/http://wiki.puzzlers.org/pub/wordlists/unixdict.txt'); fprintf('\n'); check('http://ucrel.lancs.ac.uk/bncfreq/lists/1_2_all_freq.txt'); end diff --git a/Task/I-before-E-except-after-C/Maple/i-before-e-except-after-c.maple b/Task/I-before-E-except-after-C/Maple/i-before-e-except-after-c.maple index 8bf9b10be0..12d72b4118 100644 --- a/Task/I-before-E-except-after-C/Maple/i-before-e-except-after-c.maple +++ b/Task/I-before-E-except-after-C/Maple/i-before-e-except-after-c.maple @@ -1,22 +1,22 @@ -words:= HTTP:-Get("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt"): +words:= HTTP:-Get("https://web.archive.org/web/20240920144647if_/http://wiki.puzzlers.org/pub/wordlists/unixdict.txt"): lst := StringTools:-Split(words[2],"\n"): xie, cie, cei, xei := 0, 0, 0, 0: for item in lst do - if searchtext("ie", item) <> 0 then - if searchtext("cie", item) <> 0 then - cie := cie + 1: - else - xie := xie + 1: - fi: - fi: - if searchtext("ei", item) <> 0 then - if searchtext("cei", item) <> 0 then - cei := cei + 1: - else - xei := xei + 1: - fi: - fi: -od: + if searchtext("ie", item) <> 0 then + if searchtext("cie", item) <> 0 then + cie := cie + 1: + else + xie := xie + 1: + fi: + fi: + if searchtext("ei", item) <> 0 then + if searchtext("cei", item) <> 0 then + cei := cei + 1: + else + xei := xei + 1: + fi: + fi: +od: p1, p2 := evalb(xie > 2*xei),evalb(cei > 2*cie); printf("The first phrase is %s with supporting features %d, anti features %d\n", piecewise(p1, "plausible", "not plausible"), xie, xei); printf("The seond phrase is %s with supporting features %d, anti features %d\n", piecewise(p2, "plausible", "not plausible"), cei, cie); diff --git a/Task/I-before-E-except-after-C/Mathematica/i-before-e-except-after-c-1.math b/Task/I-before-E-except-after-C/Mathematica/i-before-e-except-after-c-1.math index 62109c191c..38e8577727 100644 --- a/Task/I-before-E-except-after-C/Mathematica/i-before-e-except-after-c-1.math +++ b/Task/I-before-E-except-after-C/Mathematica/i-before-e-except-after-c-1.math @@ -1,5 +1,5 @@ wordlist = - Import["http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", + Import["https://web.archive.org/web/20240920144647if_/http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", "Words"]; Print["The number of words in unixdict.txt = " <> ToString[Length[wordlist]]] diff --git a/Task/I-before-E-except-after-C/Microsoft-Small-Basic/i-before-e-except-after-c.basic b/Task/I-before-E-except-after-C/Microsoft-Small-Basic/i-before-e-except-after-c.basic new file mode 100644 index 0000000000..b7b18e8361 --- /dev/null +++ b/Task/I-before-E-except-after-C/Microsoft-Small-Basic/i-before-e-except-after-c.basic @@ -0,0 +1,25 @@ +For i = 1 To 25104 + ' Assumes that unixdict.txt is in C:\ + word = File.ReadLine("C:\unixdict.txt", i) + If Text.IsSubText(word, "cie") Then + cie = cie + 1 + ElseIf Text.IsSubText(word, "ie") Then + ie = ie + 1 + EndIf + If Text.IsSubText(word, "cei") Then + cei = cei + 1 + ElseIf Text.IsSubText(word, "ei") Then + ei = ei + 1 + EndIf +EndFor + +If ie / ei > 2 Then + TextWindow.WriteLine("I before E when not preceded by C is plausible") +Else + TextWindow.WriteLine("I before E when not preceded by C is not plausible") +EndIf +If cei / cie > 2 Then + TextWindow.WriteLine("E before I when preceded by C is plausible") +Else + TextWindow.WriteLine("E before I when preceded by C is not plausible") +EndIf diff --git a/Task/I-before-E-except-after-C/Nim/i-before-e-except-after-c.nim b/Task/I-before-E-except-after-C/Nim/i-before-e-except-after-c.nim index 2a549064b1..41a8ff75bf 100644 --- a/Task/I-before-E-except-after-C/Nim/i-before-e-except-after-c.nim +++ b/Task/I-before-E-except-after-C/Nim/i-before-e-except-after-c.nim @@ -17,7 +17,7 @@ proc plausibility(rule: string; count1, count2: int): bool = let client = newHttpClient() var nie, cie, nei, cei = 0 -for word in client.getContent("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt").split(): +for word in client.getContent("https://web.archive.org/web/20240920144647if_/http://wiki.puzzlers.org/pub/wordlists/unixdict.txt").split(): if word.contains("ie"): if word.contains("cie"): inc cie diff --git a/Task/I-before-E-except-after-C/Nu/i-before-e-except-after-c-1.nu b/Task/I-before-E-except-after-C/Nu/i-before-e-except-after-c-1.nu new file mode 100644 index 0000000000..2c9926743c --- /dev/null +++ b/Task/I-before-E-except-after-C/Nu/i-before-e-except-after-c-1.nu @@ -0,0 +1,32 @@ +# Fetch and process the word list +let words = open unixdict.txt | lines | where { ($in | str length) > 3 } + +# Function to count matches for a pattern +def count-pattern [pattern: string] { + $words | where $it =~ $pattern | length +} + +# Count occurrences for "I before E" rule +let ie_not_c = (count-pattern "(^|[^c])ie") # ie not preceded by c +let ei_not_c = (count-pattern "(^|[^c])ei") # ei not preceded by c + +# Count occurrences for "E before I" rule +let cei = (count-pattern "cei") # ei preceded by c +let cie = (count-pattern "cie") # ie preceded by c + +# Check plausibility (more than 2x occurrences of opposite) +let rule1_plausible = ($ie_not_c > ($ei_not_c * 2)) +let rule2_plausible = ($cei > ($cie * 2)) + +# Output results +print [ + $"Analyzing 'I before E when not preceded by C':" + $" correct for : ($ie_not_c)" + $" not correct for : ($ei_not_c)" + $" Plausible: ($rule1_plausible)" + $"" + $"Analyzing 'E before I when preceded by C':" + $" correct for : ($cei)" + $" not correct for : ($cie)" + $" Plausible: ($rule2_plausible)" + ] diff --git a/Task/I-before-E-except-after-C/Nu/i-before-e-except-after-c-2.nu b/Task/I-before-E-except-after-C/Nu/i-before-e-except-after-c-2.nu new file mode 100644 index 0000000000..4519c2d750 --- /dev/null +++ b/Task/I-before-E-except-after-C/Nu/i-before-e-except-after-c-2.nu @@ -0,0 +1,48 @@ +# Fetch and filter words +let words = open unixdict.txt | lines | where { $in | str length | $in > 3 } + +# Define patterns and their processing in a functional way +let patterns = [ + { name: "ie_not_c", pattern: "(^|[^c])ie", desc: "I before E when not preceded by C" } + { name: "ei_not_c", pattern: "(^|[^c])ei", desc: null } + { name: "cei", pattern: "cei", desc: "E before I when preceded by C" } + { name: "cie", pattern: "cie", desc: null } +] + +# Count matches for each pattern functionally +let counts = $patterns | + each { |p| + $p | upsert count ($words | where $it =~ $p.pattern | length) + } + +# Calculate plausibility using match +let results = $counts | + each { |row| + match $row.name { + "ie_not_c" => { + let opposite = ($counts | where name == "ei_not_c" | get count.0) + $row | upsert plausible ($row.count > ($opposite * 2)) + } + "cei" => { + let opposite = ($counts | where name == "cie" | get count.0) + $row | upsert plausible ($row.count > ($opposite * 2)) + } + _ => $row + } + } + +# Format and print results functionally +$results | + where desc != null | + each { |rule| + let opposite = ($results | where name == (if $rule.name == "ie_not_c" { "ei_not_c" } else { "cie" }) | get 0) + [ + $"Analyzing '($rule.desc)':" + $" correct for : ($rule.count)" + $" not correct for : ($opposite.count)" + $" Plausible: ($rule.plausible)" + "" + ] + } | + flatten | + print $in diff --git a/Task/I-before-E-except-after-C/Objeck/i-before-e-except-after-c.objeck b/Task/I-before-E-except-after-C/Objeck/i-before-e-except-after-c.objeck index 637dc3013a..eb0643dc33 100644 --- a/Task/I-before-E-except-after-C/Objeck/i-before-e-except-after-c.objeck +++ b/Task/I-before-E-except-after-C/Objeck/i-before-e-except-after-c.objeck @@ -3,7 +3,7 @@ use Collection; class HttpTest { function : Main(args : String[]) ~ Nil { - IsPlausibleRule("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt"); + IsPlausibleRule("https://web.archive.org/web/20240920144647if_/http://wiki.puzzlers.org/pub/wordlists/unixdict.txt"); } function : PlausibilityCheck(comment : String, x : Int, y : Int) ~ Bool { diff --git a/Task/I-before-E-except-after-C/Octave/i-before-e-except-after-c.octave b/Task/I-before-E-except-after-C/Octave/i-before-e-except-after-c.octave index adc2b9f124..3eb8bf3576 100644 --- a/Task/I-before-E-except-after-C/Octave/i-before-e-except-after-c.octave +++ b/Task/I-before-E-except-after-C/Octave/i-before-e-except-after-c.octave @@ -6,27 +6,27 @@ cei = 0; nie = 0; cie = 0; while ~feof(fid) - c = strsplit(strtrim(fgetl(fid)),char([9,32])); - if length(c) > 2, - n = str2num(c{3}); - else - n = 1; - end; - if strfind(c{1},'ei')>1, nei=nei+n; end; - if strfind(c{1},'cei'), cei=cei+n; end; - if strfind(c{1},'ie')>1, nie=nie+n; end; - if strfind(c{1},'cie'), cie=cie+n; end; + c = strsplit(strtrim(fgetl(fid)),char([9,32])); + if length(c) > 2, + n = str2num(c{3}); + else + n = 1; + end; + if strfind(c{1},'ei')>1, nei=nei+n; end; + if strfind(c{1},'cei'), cei=cei+n; end; + if strfind(c{1},'ie')>1, nie=nie+n; end; + if strfind(c{1},'cie'), cie=cie+n; end; end; fclose(fid); printf('cie: %i\nnie: %i\ncei: %i\nnei: %i\n',cie,nie-cie,cei,nei-cei); v = ''; if (nie < 3 * cie) - v=' not'; + v=' not'; end printf('I before E when not preceded by C: is%s plausible\n',v); v = ''; if (nei > 3 * cei) - v=' not'; + v=' not'; end printf('E before I when preceded by C: is%s plausible\n',v); diff --git a/Task/I-before-E-except-after-C/PascalABC.NET/i-before-e-except-after-c.pas b/Task/I-before-E-except-after-C/PascalABC.NET/i-before-e-except-after-c.pas new file mode 100644 index 0000000000..4a3d98472f --- /dev/null +++ b/Task/I-before-E-except-after-C/PascalABC.NET/i-before-e-except-after-c.pas @@ -0,0 +1,11 @@ +// I before E except after C. Nigel Galloway: September 30th., 2024 +type plausibility=(plausible,implausible); +var fN:string->string->integer:=n->g->System.Text.RegularExpressions.Regex.Matches(n,g).count; +var fG:Func->(array of integer)->array of integer:=n->g->g.Zip(|n('ie'),n('ei'),n('cie'),n('cei')|,(n,g)->n+g).ToArray; +begin + var n:=System.IO.File.ReadLines('unixdict.txt').Aggregate(|0,0,0,0|,(n,g)->fG(fN(g))(n)); + println($'I before E except after C is {if n[0]-n[2]>2*n[2] then plausible else implausible}'); + println($'E before I except after C is {if n[1]-n[3]>2*n[3] then plausible else implausible}'); + println($'I before E when after C is {if n[2]>2*n[3] then plausible else implausible}'); + println($'E before I when after C is {if n[3]>2*n[2] then plausible else implausible}'); +end. diff --git a/Task/I-before-E-except-after-C/PowerShell/i-before-e-except-after-c.ps1 b/Task/I-before-E-except-after-C/PowerShell/i-before-e-except-after-c.ps1 new file mode 100644 index 0000000000..c3e30c0516 --- /dev/null +++ b/Task/I-before-E-except-after-C/PowerShell/i-before-e-except-after-c.ps1 @@ -0,0 +1,29 @@ +$Web = New-Object -TypeName Net.Webclient +$Words = $web.DownloadString('https://web.archive.org/web/20240920144647if_/http://wiki.puzzlers.org/pub/wordlists/unixdict.txt') + +$IE = $EI = $CIE = $CEI = @() + +$Clause1 = $Clause2 = $MainClause = $false + +foreach ($Word in $Words.split()) +{ + switch ($Word) + { + {($_ -like '*ie*') -and ($_ -notlike '*cie*')} {$IE += $Word} + {($_ -like '*ei*') -and ($_ -notlike '*cei*')} {$EI += $Word} + {$_ -like '*cei*'} {$CEI += $Word} + {$_ -like '*cie*'} {$CIE += $Word} + } +} + +if ($IE.count -gt $EI.count * 2) +{$Clause1 = $true} +"The plausibility of 'I before E when not preceded by C' is $Clause1" + +if ($CEI.count -gt $CIE.count * 2) +{$Clause2 = $true} +"The plausibility of 'E before I when preceded by C' is $Clause2" + +if ($Clause1 -and $Clause2) +{$MainClause = $True} +"The plausibility of the phrase 'I before E except after C' is $MainClause" diff --git a/Task/I-before-E-except-after-C/PowerShell/i-before-e-except-after-c.psh b/Task/I-before-E-except-after-C/PowerShell/i-before-e-except-after-c.psh deleted file mode 100644 index c1c8f167b4..0000000000 --- a/Task/I-before-E-except-after-C/PowerShell/i-before-e-except-after-c.psh +++ /dev/null @@ -1,29 +0,0 @@ -$Web = New-Object -TypeName Net.Webclient -$Words = $web.DownloadString('http://wiki.puzzlers.org/pub/wordlists/unixdict.txt') - -$IE = $EI = $CIE = $CEI = @() - -$Clause1 = $Clause2 = $MainClause = $false - -foreach ($Word in $Words.split()) -{ - switch ($Word) - { - {($_ -like '*ie*') -and ($_ -notlike '*cie*')} {$IE += $Word} - {($_ -like '*ei*') -and ($_ -notlike '*cei*')} {$EI += $Word} - {$_ -like '*cei*'} {$CEI += $Word} - {$_ -like '*cie*'} {$CIE += $Word} - } -} - -if ($IE.count -gt $EI.count * 2) -{$Clause1 = $true} -"The plausibility of 'I before E when not preceded by C' is $Clause1" - -if ($CEI.count -gt $CIE.count * 2) -{$Clause2 = $true} -"The plausibility of 'E before I when preceded by C' is $Clause2" - -if ($Clause1 -and $Clause2) -{$MainClause = $True} -"The plausibility of the phrase 'I before E except after C' is $MainClause" diff --git a/Task/I-before-E-except-after-C/Python/i-before-e-except-after-c-1.py b/Task/I-before-E-except-after-C/Python/i-before-e-except-after-c-1.py index 4d00caa257..081cfb99da 100644 --- a/Task/I-before-E-except-after-C/Python/i-before-e-except-after-c-1.py +++ b/Task/I-before-E-except-after-C/Python/i-before-e-except-after-c-1.py @@ -17,7 +17,7 @@ def plausibility_check(comment, x, y): % (x, y, x / y)) return x > PLAUSIBILITY_RATIO * y -def simple_stats(url='http://wiki.puzzlers.org/pub/wordlists/unixdict.txt'): +def simple_stats(url='https://web.archive.org/web/20240920144647if_/http://wiki.puzzlers.org/pub/wordlists/unixdict.txt'): words = urllib.request.urlopen(url).read().decode().lower().split() cie = len({word for word in words if 'cie' in word}) cei = len({word for word in words if 'cei' in word}) diff --git a/Task/I-before-E-except-after-C/R/i-before-e-except-after-c.r b/Task/I-before-E-except-after-C/R/i-before-e-except-after-c.r index aa3ad856c5..8756b79215 100644 --- a/Task/I-before-E-except-after-C/R/i-before-e-except-after-c.r +++ b/Task/I-before-E-except-after-C/R/i-before-e-except-after-c.r @@ -1,4 +1,4 @@ -words = tolower(readLines("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt")) +words = tolower(readLines("https://web.archive.org/web/20240920144647if_/http://wiki.puzzlers.org/pub/wordlists/unixdict.txt")) ie.npc = sum(grepl("(?2) )'plausible.' -p2=#.ie.c / max(1, #.ei.c); phrase= '"E before I when preceded by C"' -say mantra phrase ' is ' word("im", 1 + (p2>2) )'plausible.' -po=(p1>2 & p2>2); say 'Overall, it is' word("im", 1 + po)'plausible.' -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -find: arg x; s=1; do forever; _=pos(x, u, s); if _==0 then return - if substr(u, _ - 1 + (_==1)*999, 1)=='C' then #.x.c=#.x.c + 1 - else #.x.z=#.x.z + 1 - s=_ + 1 /*handle the cases of multiple finds. */ - end /*forever*/ diff --git a/Task/I-before-E-except-after-C/REXX/i-before-e-except-after-c-2.rexx b/Task/I-before-E-except-after-C/REXX/i-before-e-except-after-c-2.rexx deleted file mode 100644 index 59c7da9267..0000000000 --- a/Task/I-before-E-except-after-C/REXX/i-before-e-except-after-c-2.rexx +++ /dev/null @@ -1,61 +0,0 @@ -/*REXX program shows plausibility of "I before E" when not preceded by C, and */ -/*───────────────────────────────────── "E before I" when preceded by C, using a */ -/*───────────────────────────────────── weighted frequency for each word. */ -parse arg iFID wFID . /*obtain optional arguments from the CL*/ -if iFID=='' | iFID=="," then iFID='UNIXDICT.TXT' /*Not specified? Then use the default.*/ -if wFID=='' | wFID=="," then wFID='WORDFREQ.TXT' /* " " " " " " */ -cntl=xrange(, ' ') /*get all manner of tabs, control chars*/ -#.=0 /*zero out the various word counters. */ -f.=1 /*default word frequency multiplier. */ - do recs=0 while lines(wFID)\==0 /*read a record from the file 'til done*/ - u=translate( linein(wFID), , cntl); upper u /*translate various tabs and cntl chars*/ - u=translate(u, '*', "~") /*translate tildes (~) to an asterisk.*/ - if u=='' then iterate /*Is this a blank line? Then ignore it.*/ - freq=word(u, words(u) ) /*obtain the last token on the line. */ - if \datatype(freq, 'W') then iterate /*FREQ not an integer? Then ignore it.*/ - parse var u w.1 '/' w.2 . /*handle case of: ααα/ßßß ··· */ - - do j=1 for 2; w.j=word(w.j, 1) /*strip leading and/or trailing blanks.*/ - _=w.j; if _=='' then iterate /*if not present, then ignore it. */ - if j==2 then if w.2==w.1 then iterate /*second word ≡ first word? Then skip.*/ - #.freqs=#.freqs + 1 /*bump word counter in the FREQ list.*/ - f._=f._ + freq /*add to a word's frequency count. */ - end /*ws*/ - end /*recs*/ /*at exit of DO loop, RECS = # of recs.*/ - -if recs\==0 then say 'lines in the ' wFID " list: " recs -if #.freqs\==0 then say 'words in the ' wFID " list: " #.freqs -if #.freqs ==0 then weighted= - else weighted= ' (weighted)' -say - do r=0 while lines(iFID)\==0 /*keep reading the dictionary 'til done*/ - u=space( linein(iFID), 0); upper u /*elide superfluous blanks and tabs. */ - if u=='' then iterate /*Is it a blank line? Then ignore it.*/ - #.words=#.words + 1 /*keep running count of number of words*/ - one=f.u - if pos('EI', u)\==0 & pos('IE', u)\==0 then #.both=#.both + one /*the word has both*/ - call find 'ie' /*look for ie */ - call find 'ei' /* " " ei */ - end /*r*/ /*at exit of DO loop, R = # of lines.*/ - -L=length(#.words) /*use this to align the output numbers.*/ -say 'lines in the ' iFID ' dictionary: ' r -say 'words in the ' iFID ' dictionary: ' #.words -say -say 'words with "IE" and "EI" (in same word): ' right(#.both, L) weighted -say 'words with "IE" and preceded by "C": ' right(#.ie.c ,L) weighted -say 'words with "IE" and not preceded by "C": ' right(#.ie.z ,L) weighted -say 'words with "EI" and preceded by "C": ' right(#.ei.c ,L) weighted -say 'words with "EI" and not preceded by "C": ' right(#.ei.z ,L) weighted -say; mantra= 'The spelling mantra ' -p1=#.ie.z / max(1, #.ei.z); phrase= '"I before E when not preceded by C"' -say mantra phrase ' is ' word("im", 1 + (p1>2) )'plausible.' -p2=#.ie.c / max(1, #.ei.c); phrase= '"E before I when preceded by C"' -say mantra phrase ' is ' word("im", 1 + (p2>2) )'plausible.' -po=(p1>2 & p2>2); say 'Overall, it is' word("im",1 + po)'plausible.' -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -find: arg x; s=1; do forever; _=pos(x, u, s); if _==0 then return - if substr(u, _ - 1 + (_==1)*999, 1)=='C' then #.x.c=#.x.c + one - else #.x.z=#.x.z + one - s=_ + 1 /*handle the cases of multiple finds. */ diff --git a/Task/I-before-E-except-after-C/REXX/i-before-e-except-after-c.rexx b/Task/I-before-E-except-after-C/REXX/i-before-e-except-after-c.rexx new file mode 100644 index 0000000000..febe0ab972 --- /dev/null +++ b/Task/I-before-E-except-after-C/REXX/i-before-e-except-after-c.rexx @@ -0,0 +1,59 @@ +-- 10 Nov 2025 +include Setting + +say 'I BEFORE E AFTER C' +say version +say +call UnixDict +call Show +exit + +UnixDict: +file='UnixDict.txt' +say 'Process' file'...' +n=0; cie=0; cei=0; xie=0; xei=0 +do while Lines(file) > 0 + line=Lower(Linein(file)); n+=1 + a=Pos('ie',line) + if a>0 then do + a+=99*(a<2) + if Substr(line,a-1,1)='c' then + cie+=1 + else + xie+=1 + end + a=Pos('ei',line) + if a>0 then do + a+=99*(a<2) + if Substr(line,a-1,1)='c' then + cei+=1 + else + xei+=1 + end +end +say n 'Lines processed' +say +return + +Show: +say 'IE preceded by C occurs' cie 'times' +say 'EI preceded by C occurs' cei 'times' +say 'IE not preceded by C occurs' xie 'times' +say 'EI not preceded by C occurs' xei 'times' +say +ie=(2*xie<=cie); ei=(2*cei<=xei) +call Charout ,'I before E when not preceded by C is ' +if ie then + call Charout ,'not ' +say 'plausible' +call Charout ,'E before I when preceded by C is ' +if ei then + call Charout ,'not ' +say 'plausible' +call Charout ,'I before E except after C is ' +if ie | ei then + call Charout ,'not ' +say 'plausible' +return + +include Abend diff --git a/Task/I-before-E-except-after-C/Rebol/i-before-e-except-after-c.rebol b/Task/I-before-E-except-after-C/Rebol/i-before-e-except-after-c.rebol new file mode 100644 index 0000000000..53e916ca1b --- /dev/null +++ b/Task/I-before-E-except-after-C/Rebol/i-before-e-except-after-c.rebol @@ -0,0 +1,50 @@ +Rebol [ + title: "Rosetta code: I before E except after C" + file: %I_before_E_except_after_C.r3 + url: https://rosettacode.org/wiki/I_before_E_except_after_C + note: "Based on Red language solution" + needs: 3.15.0 ;; or something like that +] + +testlist: function [wordlist /wfreq] [ + ;; Initialize counters for each pattern + cie: cei: ie: ei: 0 + + ;; Select iteration mode: if /wfreq, expect [word freq] pairs; else assume word-only + words: either wfreq [[word freq]][freq: 1 [word]] + + ;; Loop through each word or [word freq] pair in the list + foreach :words wordlist [ + ;; Use PARSE to search for each pattern within the word string + parse word [ some [ + "cie" (cie: cie + freq) | ;; Count "cie" and increment by frequency + "cei" (cei: cei + freq) | ;; Count "cei" and increment by frequency + "ie" ( ie: ie + freq) | ;; Count standalone "ie" not preceded by c + "ei" ( ei: ei + freq) | ;; Count standalone "ei" not preceded by c + skip + ]] + ] + ;; Print results, comparing "i before e except after c" rule against pattern frequencies + print rejoin [ + "i is before e " ie " times, and also " cie " times following c.^/" + "i is after e " ei " times, and also " cei " times following c.^/" + "Hence ^"i before e^" is " either a: 2 * ei < ie [""] ["not "] "plausible,^/" + "while ^"except after c^" is " either b: 2 * cie < cei [""] ["not "] "plausible.^/" + "Overall the rule is " either a and b [""] ["not "] "plausible." + ] +] + +print "Results for unixdict.txt:" +testlist read/lines %unixdict.txt + +print "^/Results for British National Corpus:" +bnc: next read/lines %1_2_all_freq.txt +spaces: charset "^- " +bnclist: collect [ + foreach w bnc [ + if 3 = length? seq: split trim w spaces [ + keep seq/1 keep to-integer seq/3 + ] + ] +] +testlist/wfreq bnclist diff --git a/Task/I-before-E-except-after-C/Red/i-before-e-except-after-c.red b/Task/I-before-E-except-after-C/Red/i-before-e-except-after-c.red index b7e21dc1e8..4589f32f1b 100644 --- a/Task/I-before-E-except-after-C/Red/i-before-e-except-after-c.red +++ b/Task/I-before-E-except-after-C/Red/i-before-e-except-after-c.red @@ -1,33 +1,33 @@ Red ["i before e except after c"] testlist: function [wordlist /wfreq] [ - cie: cei: ie: ei: 0 - if not wfreq [forall wordlist [insert wordlist: next wordlist 1]] - foreach [word freq] wordlist [ - parse word [ some [ - "cie" (cie: cie + freq) | - "cei" (cei: cei + freq) | - "ie" (ie: ie + freq) | - "ei" (ei: ei + freq) | - skip - ]] - ] - print rejoin [ - "i is before e " ie " times, and also " cie " times following c.^/" - "i is after e " ei " times, and also " cei " times following c.^/" - "Hence ^"i before e^" is " either a: 2 * ei < ie [""] ["not "] "plausible,^/" - "while ^"except after c^" is " either b: 2 * cie < cei [""] ["not "] "plausible.^/" - "Overall the rule is " either a and b [""] ["not "] "plausible."] + cie: cei: ie: ei: 0 + if not wfreq [forall wordlist [insert wordlist: next wordlist 1]] + foreach [word freq] wordlist [ + parse word [ some [ + "cie" (cie: cie + freq) | + "cei" (cei: cei + freq) | + "ie" (ie: ie + freq) | + "ei" (ei: ei + freq) | + skip + ]] + ] + print rejoin [ + "i is before e " ie " times, and also " cie " times following c.^/" + "i is after e " ei " times, and also " cei " times following c.^/" + "Hence ^"i before e^" is " either a: 2 * ei < ie [""] ["not "] "plausible,^/" + "while ^"except after c^" is " either b: 2 * cie < cei [""] ["not "] "plausible.^/" + "Overall the rule is " either a and b [""] ["not "] "plausible."] ] print "Results for unixdict.txt:" -testlist read/lines http://wiki.puzzlers.org/pub/wordlists/unixdict.txt +testlist read/lines https://web.archive.org/web/20240920144647if_/http://wiki.puzzlers.org/pub/wordlists/unixdict.txt print "^/Results for British National Corpus:" bnc: next read/lines %1_2_all_freq.txt spaces: charset "^- " -bnclist: collect [ foreach w bnc [ - if 3 = length? seq: split trim w spaces [ - keep seq/1 keep to-integer seq/3 +bnclist: collect [ foreach w bnc [ + if 3 = length? seq: split trim w spaces [ + keep seq/1 keep to-integer seq/3 ]]] testlist/wfreq bnclist diff --git a/Task/I-before-E-except-after-C/Ruby/i-before-e-except-after-c.rb b/Task/I-before-E-except-after-C/Ruby/i-before-e-except-after-c.rb index 566bf86072..8c07c86b90 100644 --- a/Task/I-before-E-except-after-C/Ruby/i-before-e-except-after-c.rb +++ b/Task/I-before-E-except-after-C/Ruby/i-before-e-except-after-c.rb @@ -2,7 +2,7 @@ require 'open-uri' plausibility_ratio = 2 counter = Hash.new(0) -path = 'http://wiki.puzzlers.org/pub/wordlists/unixdict.txt' +path = 'https://web.archive.org/web/20240920144647if_/http://wiki.puzzlers.org/pub/wordlists/unixdict.txt' rules = [['I before E when not preceded by C:', 'ie', 'ei'], ['E before I when preceded by C:', 'cei', 'cie']] diff --git a/Task/I-before-E-except-after-C/Rust/i-before-e-except-after-c.rs b/Task/I-before-E-except-after-C/Rust/i-before-e-except-after-c.rs new file mode 100644 index 0000000000..f1f0733b63 --- /dev/null +++ b/Task/I-before-E-except-after-C/Rust/i-before-e-except-after-c.rs @@ -0,0 +1,79 @@ +use std::default::Default; +use std::ops::AddAssign; + +use itertools::Itertools; +use reqwest::get; + +#[derive(Default, Debug)] +struct Feature { + pub cie: T, + pub xie: T, + pub cei: T, + pub xei: T, +} + +impl AddAssign> for Feature { + fn add_assign(&mut self, rhs: Feature) { + self.cei += rhs.cei as u64; + self.xei += rhs.xei as u64; + self.cie += rhs.cie as u64; + self.xie += rhs.xie as u64; + } +} + +fn check_feature(word: &str) -> Feature { + let mut feature: Feature = Default::default(); + + for window in word.chars().tuple_windows::<(char, char, char)>() { + match window { + ('c', 'e', 'i') => { feature.cei = true } + ('c', 'i', 'e') => { feature.cie = true } + (not_c, 'e', 'i') if not_c != 'c' => (feature.xei = true), + (not_c, 'i', 'e') if not_c != 'c' => (feature.xie = true), + _ => {} + } + } + + feature +} + + +fn maybe_is_feature_plausible(feature_count: u64, opposing_count: u64) -> Option { + if feature_count > 2 * opposing_count { Some(true) } else if opposing_count > 2 * feature_count { Some(false) } else { None } +} + +fn print_feature_plausibility(feature_plausibility: Option, feature_name: &str) { + let plausible_msg = + match feature_plausibility { + None => " is implausible", + Some(true) => "is plausible", + Some(false) => "is definitely implausible", + }; + + println!("{} {}", feature_name, plausible_msg) +} + +fn main() { + let mut res = get(" https://web.archive.org/web/20240920144647if_/http://wiki.puzzlers.org/pub/wordlists/unixdict.txt").unwrap(); + let texts = res.text().unwrap(); + + let mut feature_count: Feature = Default::default(); + for word in texts.lines() { + let feature = check_feature(word); + feature_count += feature; + } + + println!("Counting {:#?}", feature_count); + + let xie_plausibility = + maybe_is_feature_plausible(feature_count.xie, feature_count.cie); + let cei_plausibility = + maybe_is_feature_plausible(feature_count.cei, feature_count.xei); + + print_feature_plausibility(xie_plausibility, "I before E when not preceded by C"); + print_feature_plausibility(cei_plausibility, "E before I when preceded by C"); + println!("The rule in general is {}", + if xie_plausibility.unwrap_or(false) && cei_plausibility.unwrap_or(false) + { "Plausible" } else { "Implausible" } + ); +} diff --git a/Task/I-before-E-except-after-C/Rust/i-before-e-except-after-c.rust b/Task/I-before-E-except-after-C/Rust/i-before-e-except-after-c.rust deleted file mode 100644 index 8682f51edb..0000000000 --- a/Task/I-before-E-except-after-C/Rust/i-before-e-except-after-c.rust +++ /dev/null @@ -1,79 +0,0 @@ -use std::default::Default; -use std::ops::AddAssign; - -use itertools::Itertools; -use reqwest::get; - -#[derive(Default, Debug)] -struct Feature { - pub cie: T, - pub xie: T, - pub cei: T, - pub xei: T, -} - -impl AddAssign> for Feature { - fn add_assign(&mut self, rhs: Feature) { - self.cei += rhs.cei as u64; - self.xei += rhs.xei as u64; - self.cie += rhs.cie as u64; - self.xie += rhs.xie as u64; - } -} - -fn check_feature(word: &str) -> Feature { - let mut feature: Feature = Default::default(); - - for window in word.chars().tuple_windows::<(char, char, char)>() { - match window { - ('c', 'e', 'i') => { feature.cei = true } - ('c', 'i', 'e') => { feature.cie = true } - (not_c, 'e', 'i') if not_c != 'c' => (feature.xei = true), - (not_c, 'i', 'e') if not_c != 'c' => (feature.xie = true), - _ => {} - } - } - - feature -} - - -fn maybe_is_feature_plausible(feature_count: u64, opposing_count: u64) -> Option { - if feature_count > 2 * opposing_count { Some(true) } else if opposing_count > 2 * feature_count { Some(false) } else { None } -} - -fn print_feature_plausibility(feature_plausibility: Option, feature_name: &str) { - let plausible_msg = - match feature_plausibility { - None => " is implausible", - Some(true) => "is plausible", - Some(false) => "is definitely implausible", - }; - - println!("{} {}", feature_name, plausible_msg) -} - -fn main() { - let mut res = get(" http://wiki.puzzlers.org/pub/wordlists/unixdict.txt").unwrap(); - let texts = res.text().unwrap(); - - let mut feature_count: Feature = Default::default(); - for word in texts.lines() { - let feature = check_feature(word); - feature_count += feature; - } - - println!("Counting {:#?}", feature_count); - - let xie_plausibility = - maybe_is_feature_plausible(feature_count.xie, feature_count.cie); - let cei_plausibility = - maybe_is_feature_plausible(feature_count.cei, feature_count.xei); - - print_feature_plausibility(xie_plausibility, "I before E when not preceded by C"); - print_feature_plausibility(cei_plausibility, "E before I when preceded by C"); - println!("The rule in general is {}", - if xie_plausibility.unwrap_or(false) && cei_plausibility.unwrap_or(false) - { "Plausible" } else { "Implausible" } - ); -} diff --git a/Task/I-before-E-except-after-C/Scala/i-before-e-except-after-c.scala b/Task/I-before-E-except-after-C/Scala/i-before-e-except-after-c.scala index f1455bf125..2a27cab5c3 100644 --- a/Task/I-before-E-except-after-C/Scala/i-before-e-except-after-c.scala +++ b/Task/I-before-E-except-after-C/Scala/i-before-e-except-after-c.scala @@ -7,7 +7,7 @@ object I_before_E_except_after_C extends App { val testCEI2 = "(^|[^c])ei".r // e before i when not preceded by c var countsCEI = (0,0) - scala.io.Source.fromURL("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt").getLines.map(_.toLowerCase).foreach{word => + scala.io.Source.fromURL("https://web.archive.org/web/20240920144647if_/http://wiki.puzzlers.org/pub/wordlists/unixdict.txt").getLines.map(_.toLowerCase).foreach{word => if (testIE1.findFirstIn(word).isDefined) countsIE = (countsIE._1 + 1, countsIE._2) if (testIE2.findFirstIn(word).isDefined) countsIE = (countsIE._1, countsIE._2 + 1) if (testCEI1.findFirstIn(word).isDefined) countsCEI = (countsCEI._1 + 1, countsCEI._2) diff --git a/Task/I-before-E-except-after-C/Swift/i-before-e-except-after-c.swift b/Task/I-before-E-except-after-C/Swift/i-before-e-except-after-c.swift index ed3120606c..14028c69b2 100644 --- a/Task/I-before-E-except-after-C/Swift/i-before-e-except-after-c.swift +++ b/Task/I-before-E-except-after-C/Swift/i-before-e-except-after-c.swift @@ -1,6 +1,6 @@ import Foundation -let request = NSURLRequest(URL: NSURL(string: "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt")!) +let request = NSURLRequest(URL: NSURL(string: "https://web.archive.org/web/20240920144647if_/http://wiki.puzzlers.org/pub/wordlists/unixdict.txt")!) NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) {res, data, err in if (data != nil) { diff --git a/Task/I-before-E-except-after-C/TUSCRIPT/i-before-e-except-after-c.tu b/Task/I-before-E-except-after-C/TUSCRIPT/i-before-e-except-after-c.tu index 736ae22160..e0b0fd9e71 100644 --- a/Task/I-before-E-except-after-C/TUSCRIPT/i-before-e-except-after-c.tu +++ b/Task/I-before-E-except-after-C/TUSCRIPT/i-before-e-except-after-c.tu @@ -1,5 +1,5 @@ $$ MODE TUSCRIPT,{} -words=REQUEST("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt") +words=REQUEST("https://web.archive.org/web/20240920144647if_/http://wiki.puzzlers.org/pub/wordlists/unixdict.txt") size=SIZE(words) ieei=cie=xie=cei=xei=0 diff --git a/Task/I-before-E-except-after-C/Tcl/i-before-e-except-after-c.tcl b/Task/I-before-E-except-after-C/Tcl/i-before-e-except-after-c.tcl index e0a7b5692f..a3199937e3 100644 --- a/Task/I-before-E-except-after-C/Tcl/i-before-e-except-after-c.tcl +++ b/Task/I-before-E-except-after-C/Tcl/i-before-e-except-after-c.tcl @@ -5,24 +5,24 @@ proc plausible {description x y} { variable PLAUSIBILITY_RATIO puts " Checking plausibility of: $description" if {$x > $PLAUSIBILITY_RATIO * $y} { - set conclusion "PLAUSIBLE" - set fmt "As we have counts of %i vs %i words, a ratio of %.1f times" - set result true + set conclusion "PLAUSIBLE" + set fmt "As we have counts of %i vs %i words, a ratio of %.1f times" + set result true } elseif {$x > $y} { - set conclusion "IMPLAUSIBLE" - set fmt "As although we have counts of %i vs %i words," - append fmt " a ratio of %.1f times does not make it plausible" - set result false + set conclusion "IMPLAUSIBLE" + set fmt "As although we have counts of %i vs %i words," + append fmt " a ratio of %.1f times does not make it plausible" + set result false } else { - set conclusion "IMPLAUSIBLE, probably contra-indicated" - set fmt "As we have counts of %i vs %i words, a ratio of %.1f times" - set result false + set conclusion "IMPLAUSIBLE, probably contra-indicated" + set fmt "As we have counts of %i vs %i words, a ratio of %.1f times" + set result false } puts [format " %s.\n $fmt" $conclusion $x $y [expr {double($x)/$y}]] return $result } -set t [http::geturl http://wiki.puzzlers.org/pub/wordlists/unixdict.txt] +set t [http::geturl https://web.archive.org/web/20240920144647if_/http://wiki.puzzlers.org/pub/wordlists/unixdict.txt] set words [split [http::data $t] "\n"] http::cleanup $t foreach {name pattern} {ie (?:^|[^c])ie ei (?:^|[^c])ei cie cie cei cei} { @@ -39,4 +39,4 @@ if { puts "\nOVERALL IT IS IMPLAUSIBLE!" } puts "\n(To be plausible, one word count must exceed another by\ - $PLAUSIBILITY_RATIO times)" + $PLAUSIBILITY_RATIO times)" diff --git a/Task/I-before-E-except-after-C/V-(Vlang)/i-before-e-except-after-c.v b/Task/I-before-E-except-after-C/V-(Vlang)/i-before-e-except-after-c.v index e677b3c2fa..1f88bdbb7a 100644 --- a/Task/I-before-E-except-after-C/V-(Vlang)/i-before-e-except-after-c.v +++ b/Task/I-before-E-except-after-C/V-(Vlang)/i-before-e-except-after-c.v @@ -2,26 +2,26 @@ import os import strconv fn main() { - mut cei, mut cie, mut ie, mut ei := f32(0), f32(0), f32(0), f32(0) + mut cei, mut cie, mut ie, mut ei := f32(0), f32(0), f32(0), f32(0) unixdict := os.read_file('./unixdict.txt') or {println('Error: file not found') exit(1)} - words := unixdict.split_into_lines() - println("The number of words in unixdict: ${words.len}") - for word in words { - cei += word.count('cei') - cie += word.count('cie') - ei += word.count('ei') - ie += word.count('ie') - } - print("Rule: 'e' before 'i' when preceded by 'c' at the ratio of ") - print("${strconv.f64_to_str_lnd1((cei / cie), 2)} is ") - if cei > cie {println("plausible.")} else {println("implausible.")} - println("$cei cases for and $cie cases against.") + words := unixdict.split_into_lines() + println("The number of words in unixdict: ${words.len}") + for word in words { + cei += word.count('cei') + cie += word.count('cie') + ei += word.count('ei') + ie += word.count('ie') + } + print("Rule: 'e' before 'i' when preceded by 'c' at the ratio of ") + print("${strconv.f64_to_str_lnd1((cei / cie), 2)} is ") + if cei > cie {println("plausible.")} else {println("implausible.")} + println("$cei cases for and $cie cases against.") - print("Rule: 'i' before 'e' except after 'c' at the ratio of ") - print("${strconv.f64_to_str_lnd1(((ie - cie) / (ei - cei)), 2)} is ") - if ie > ei {println("plausible.")} else {println("implausible.")} - println("${(ie - cie)} cases for and ${(ei - cei)} cases against.") + print("Rule: 'i' before 'e' except after 'c' at the ratio of ") + print("${strconv.f64_to_str_lnd1(((ie - cie) / (ei - cei)), 2)} is ") + if ie > ei {println("plausible.")} else {println("implausible.")} + println("${(ie - cie)} cases for and ${(ei - cei)} cases against.") - print("Overall the rules are ") - if cei > cie && ie > ei {println("plausible.")} else {println("implausible.")} + print("Overall the rules are ") + if cei > cie && ie > ei {println("plausible.")} else {println("implausible.")} } diff --git a/Task/I-before-E-except-after-C/VBScript/i-before-e-except-after-c.vb b/Task/I-before-E-except-after-C/VBScript/i-before-e-except-after-c.vb deleted file mode 100644 index 41f01c4eba..0000000000 --- a/Task/I-before-E-except-after-C/VBScript/i-before-e-except-after-c.vb +++ /dev/null @@ -1,48 +0,0 @@ -Set objFSO = CreateObject("Scripting.FileSystemObject") -Set srcFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ - "\unixdict.txt",1,False,0) - -cei = 0 : cie = 0 : ei = 0 : ie = 0 - -Do Until srcFile.AtEndOfStream - word = srcFile.ReadLine - If InStr(word,"cei") Then - cei = cei + 1 - ElseIf InStr(word,"cie") Then - cie = cie + 1 - ElseIf InStr(word,"ei") Then - ei = ei + 1 - ElseIf InStr(word,"ie") Then - ie = ie + 1 - End If -Loop - -FirstClause = False -SecondClause = False -Overall = False - -'testing the first clause -If ie > ei*2 Then - WScript.StdOut.WriteLine "I before E when not preceded by C is plausible." - FirstClause = True -Else - WScript.StdOut.WriteLine "I before E when not preceded by C is NOT plausible." -End If - -'testing the second clause -If cei > cie*2 Then - WScript.StdOut.WriteLine "E before I when not preceded by C is plausible." - SecondClause = True -Else - WScript.StdOut.WriteLine "E before I when not preceded by C is NOT plausible." -End If - -'overall clause -If FirstClause And SecondClause Then - WScript.StdOut.WriteLine "Overall it is plausible." -Else - WScript.StdOut.WriteLine "Overall it is NOT plausible." -End If - -srcFile.Close -Set objFSO = Nothing diff --git a/Task/I-before-E-except-after-C/VBScript/i-before-e-except-after-c.vbs b/Task/I-before-E-except-after-C/VBScript/i-before-e-except-after-c.vbs new file mode 100644 index 0000000000..411c9183c1 --- /dev/null +++ b/Task/I-before-E-except-after-C/VBScript/i-before-e-except-after-c.vbs @@ -0,0 +1,48 @@ +Set objFSO = CreateObject("Scripting.FileSystemObject") +Set srcFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ + "\unixdict.txt",1,False,0) + +cei = 0 : cie = 0 : ei = 0 : ie = 0 + +Do Until srcFile.AtEndOfStream + word = srcFile.ReadLine + If InStr(word,"cei") Then + cei = cei + 1 + ElseIf InStr(word,"cie") Then + cie = cie + 1 + ElseIf InStr(word,"ei") Then + ei = ei + 1 + ElseIf InStr(word,"ie") Then + ie = ie + 1 + End If +Loop + +FirstClause = False +SecondClause = False +Overall = False + +'testing the first clause +If ie > ei*2 Then + WScript.StdOut.WriteLine "I before E when not preceded by C is plausible." + FirstClause = True +Else + WScript.StdOut.WriteLine "I before E when not preceded by C is NOT plausible." +End If + +'testing the second clause +If cei > cie*2 Then + WScript.StdOut.WriteLine "E before I when not preceded by C is plausible." + SecondClause = True +Else + WScript.StdOut.WriteLine "E before I when not preceded by C is NOT plausible." +End If + +'overall clause +If FirstClause And SecondClause Then + WScript.StdOut.WriteLine "Overall it is plausible." +Else + WScript.StdOut.WriteLine "Overall it is NOT plausible." +End If + +srcFile.Close +Set objFSO = Nothing diff --git a/Task/I-before-E-except-after-C/Visual-Basic-.NET/i-before-e-except-after-c.vb b/Task/I-before-E-except-after-C/Visual-Basic-.NET/i-before-e-except-after-c.vb index 2b5d1a8478..60ee3a0d15 100644 --- a/Task/I-before-E-except-after-C/Visual-Basic-.NET/i-before-e-except-after-c.vb +++ b/Task/I-before-E-except-after-C/Visual-Basic-.NET/i-before-e-except-after-c.vb @@ -9,7 +9,7 @@ Imports System.Text.RegularExpressions Module Program ' Supports both local and remote files - Const WORDLIST_URI = "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt" + Const WORDLIST_URI = "https://web.archive.org/web/20240920144647if_/http://wiki.puzzlers.org/pub/wordlists/unixdict.txt" ' The support factor of a word for EI or IE is the number of occurrences that support the rule minus the number that oppose it. diff --git a/Task/I-before-E-except-after-C/XPL0/i-before-e-except-after-c.xpl0 b/Task/I-before-E-except-after-C/XPL0/i-before-e-except-after-c.xpl0 new file mode 100644 index 0000000000..4c9870b998 --- /dev/null +++ b/Task/I-before-E-except-after-C/XPL0/i-before-e-except-after-c.xpl0 @@ -0,0 +1,32 @@ +include xpllib; \for StrFind and Print +int I, Ch, CI, XI, CE, XE; +char Word(100); \(longest word in unixdict.txt is 22 chars) +[FSet(FOpen("unixdict.txt", 0), ^I); \open dictionary and set it to device 3 +OpenI(3); +repeat I:= 0; + loop [Ch:= ChIn(3); + if Ch=LF or Ch=EOF then quit; + Word(I):= Ch; + I:= I+1; + ]; + Word(I):= 0; \terminate string + + if StrFind(Word, "ie") then + if StrFind(Word, "cie") then CI:= CI+1 else XI:= XI+1; + if StrFind(Word, "ei") then + if StrFind(Word, "cei") then CE:= CE+1 else XE:= XE+1; +until Ch = EOF; + +Print("CIE: %d\n", CI); +Print("xIE: %d\n", XI); +Print("CEI: %d\n", CE); +Print("xEI: %d\n\n", XE); + +Print("I before E when not preceded by C: "); +if 2*XI < CI then Print("not "); +Print("plausible.\n"); + +Print("E before I when preceded by C: "); +if 2*CI < XE then Print("not "); +Print("plausible.\n"); +] diff --git a/Task/I-before-E-except-after-C/Yabasic/i-before-e-except-after-c.basic b/Task/I-before-E-except-after-C/Yabasic/i-before-e-except-after-c.basic index 65f3fa6df9..fde65240f8 100644 --- a/Task/I-before-E-except-after-C/Yabasic/i-before-e-except-after-c.basic +++ b/Task/I-before-E-except-after-C/Yabasic/i-before-e-except-after-c.basic @@ -3,11 +3,11 @@ open "unixdict.txt" for reading as #1 repeat line input #1 pal$ if instr(pal$, "ie") then - if instr(pal$, "cie") then CI = CI + 1 else XI = XI + 1 : fi - endif + if instr(pal$, "cie") then CI = CI + 1 else XI = XI + 1 : fi + endif if instr(pal$, "ei") then - if instr(pal$, "cei") then CE = CE + 1 else XE = XE + 1 : fi - endif + if instr(pal$, "cei") then CE = CE + 1 else XE = XE + 1 : fi + endif until eof(1) close #1 diff --git a/Task/IBAN/ALGOL-68/iban.alg b/Task/IBAN/ALGOL-68/iban.alg new file mode 100644 index 0000000000..93dc56bbc2 --- /dev/null +++ b/Task/IBAN/ALGOL-68/iban.alg @@ -0,0 +1,104 @@ +BEGIN # validate IBAN numbers # + + # country code and expected bank account length for IBAN codes # + MODE IBANCOUNTRY = STRUCT( [ 1 : 2 ]CHAR code, INT length ); + + []IBANCOUNTRY country info = + ( ("AL",28), ("AD",24), ("AT",20), ("AZ",28), ("BE",16), ("BH",22), ("BA",20), ("BR",29) + , ("BG",22), ("CR",21), ("HR",21), ("CY",28), ("CZ",24), ("DK",18), ("DO",28), ("EE",20) + , ("FO",18), ("FI",18), ("FR",27), ("GE",22), ("DE",22), ("GI",23), ("GR",27), ("GL",18) + , ("GT",28), ("HU",28), ("IS",26), ("IE",22), ("IL",23), ("IT",27), ("KZ",20), ("KW",30) + , ("LV",21), ("LB",28), ("LI",21), ("LT",20), ("LU",20), ("MK",19), ("MT",31), ("MR",27) + , ("MU",30), ("MC",27), ("MD",24), ("ME",22), ("NL",18), ("NO",15), ("PK",24), ("PS",29) + , ("PL",28), ("PT",25), ("RO",24), ("SM",27), ("SA",24), ("RS",22), ("SK",24), ("SI",19) + , ("ES",24), ("SE",24), ("CH",21), ("TN",24), ("TR",26), ("AE",23), ("GB",22), ("VG",24) + ); + + # returns "" if s could be a valid IBAN, an error message otherwise # + OP POSSIBLEIBAN = ( STRING s )STRING: + BEGIN + BOOL is valid := TRUE; + STRING result := ""; + # remove spaces and check we only have digits and spaces # + STRING iban := ""; + FOR s pos FROM LWB s TO UPB s WHILE is valid DO + CHAR c = s[ s pos ]; + IF c /= " " THEN + IF NOT ( is valid := ( c >= "A" AND c <= "Z" ) OR ( c >= "0" AND c <= "9" ) ) + THEN result := "Invalid character: " + c + FI; + iban +:= c + FI + OD; + IF is valid THEN + # OK so far - check the length matches the country code # + INT supplied length = ( UPB iban - LWB iban ) + 1; + is valid := FALSE; + IF supplied length <= 4 + THEN result := "Code is too short" + ELSE # enough characters for a country code and a check sum # + INT expected length := -1; + STRING supplied country = iban[ LWB iban : LWB iban + 1 ]; + FOR c pos FROM LWB country info TO UPB country info WHILE NOT is valid DO + IF is valid := code OF country info[ c pos ] = supplied country THEN + expected length := length OF country info[ c pos ] + FI + OD; + IF NOT is valid + THEN result := "Not a known IBAN country: " + supplied country + ELIF NOT ( is valid := expected length = supplied length ) + THEN result := "Expected code length: " + whole( expected length, 0 ) + + " but actual length is: " + whole( supplied length, 0 ) + ELSE # OK so far - check the checksum # + STRING rearranged iban = iban[ LWB iban + 4 : ] + iban[ LWB iban : LWB iban + 3 ]; + LONG LONG INT numeric iban := 0; + FOR c pos FROM LWB rearranged iban TO UPB rearranged iban DO + CHAR c = rearranged iban[ c pos ]; + IF c >= "0" AND c <= "9" THEN + numeric iban *:= 10 +:= ( ABS c - ABS "0" ) + ELSE + numeric iban *:= 100 +:= ( ABS c - ABS "A" ) + 10 + FI + OD; + IF NOT ( is valid := numeric iban MOD 97 = 1 ) + THEN result := "Incorrect checksum" + FI + FI + FI + FI; + IF is valid THEN "" ELIF result = "" THEN "Unknown error" ELSE result FI + END # POSSIBLEIBAN # ; + + BEGIN # tests # + []STRING valid codes = ( "GB82 WEST 1234 5698 7654 32", "GB82WEST12345698765432" + , "GR16 0110 1250 0000 0001 2300 695", "GB29 NWBK 6016 1331 9268 19" + , "SA03 8000 0000 6080 1016 7519", "CH93 0076 2011 6238 5295 7" + , "IL62 0108 0000 0009 9999 999" + ); + []STRING invalid codes = ( "gb82 west 1234 5698 7654 32" # invalid characters # + , "GB82 TEST 1234 5698 7654 32" # invalid check digits # + , "IL62-0108-0000-0009-9999-999" # invalid characters # + , "US12 3456 7890 0987 6543 210" # invalid country code # + , "GR16 0110 1250 0000 0001 2300 695X" # invalid code length # + , "" # code is too short # + , "G2" # code is too short # + , "GB271" # invalid code length # + ); + FOR t pos FROM LWB valid codes TO UPB valid codes DO + STRING code = valid codes[ t pos ]; + STRING message = POSSIBLEIBAN code; + IF message = "" + THEN print( ( "Possible IBAN: ", code, newline ) ) + ELSE print( ( "INVALID IBAN: ", code, ": UNEXPECTED ERROR: ", message, newline ) ) + FI + OD; + FOR t pos FROM LWB invalid codes TO UPB invalid codes DO + STRING code = invalid codes[ t pos ]; + STRING message = POSSIBLEIBAN code; + IF message = "" + THEN print( ( "POSSIBLE IBAN: ", code, " BUT EXPECTED AN ERROR MESSAGE", newline ) ) + ELSE print( ( "Invalid IBAN: ", code, ": ", message, newline ) ) + FI + OD + END +END diff --git a/Task/IBAN/Ada/iban-1.ada b/Task/IBAN/Ada/iban-1.adb similarity index 100% rename from Task/IBAN/Ada/iban-1.ada rename to Task/IBAN/Ada/iban-1.adb diff --git a/Task/IBAN/Ada/iban-2.ada b/Task/IBAN/Ada/iban-2.adb similarity index 100% rename from Task/IBAN/Ada/iban-2.ada rename to Task/IBAN/Ada/iban-2.adb diff --git a/Task/IBAN/Ada/iban-3.ada b/Task/IBAN/Ada/iban-3.adb similarity index 100% rename from Task/IBAN/Ada/iban-3.ada rename to Task/IBAN/Ada/iban-3.adb diff --git a/Task/IBAN/BQN/iban.bqn b/Task/IBAN/BQN/iban.bqn new file mode 100644 index 0000000000..b2f46623bc --- /dev/null +++ b/Task/IBAN/BQN/iban.bqn @@ -0,0 +1,4 @@ +sym ← ∾"0A"+⟜↕¨10‿26 +CheckIBAN ← 1=·(97|⊣+(10⋆1+>⟜9)⊸×)´∘⌽4⌽36(>/⊢)sym⊸⊐ + +CheckIBAN "GB82 WEST 1234 5698 7654 32" diff --git a/Task/IBAN/COBOL/iban.cobol b/Task/IBAN/COBOL/iban.cob similarity index 100% rename from Task/IBAN/COBOL/iban.cobol rename to Task/IBAN/COBOL/iban.cob diff --git a/Task/IBAN/EasyLang/iban.easy b/Task/IBAN/EasyLang/iban.easy new file mode 100644 index 0000000000..161c31d836 --- /dev/null +++ b/Task/IBAN/EasyLang/iban.easy @@ -0,0 +1,63 @@ +cc$[] = [ "AD" "AE" "AL" "AO" "AT" "AZ" "BA" "BE" "BF" "BG" "BH" "BI" "BJ" "BR" "CG" "CH" "CI" "CM" "CR" "CV" "CY" "CZ" "DE" "DK" "DO" "DZ" "EE" "EG" "ES" "FI" "FO" "FR" "GA" "GB" "GE" "GI" "GL" "GR" "GT" "HR" "HU" "IE" "IL" "IR" "IS" "IT" "JO" "KW" "KZ" "LB" "LI" "LT" "LU" "LV" "MC" "MD" "ME" "MG" "MK" "ML" "MR" "MT" "MU" "MZ" "NL" "NO" "PK" "PL" "PS" "PT" "QA" "RO" "RS" "SA" "SE" "SI" "SK" "SM" "SN" "TN" "TR" "UA" "VG" ] +ln[] = [ 24 23 28 25 20 28 20 16 27 22 22 16 28 29 27 21 28 27 21 25 28 24 22 18 28 24 20 27 24 18 18 27 27 22 22 23 18 27 28 21 28 22 23 26 26 27 30 30 20 28 21 20 20 21 27 24 22 27 19 28 27 31 30 25 18 15 24 28 29 25 29 24 22 24 24 19 24 27 28 24 26 29 24 ] +# +func validcc iban$ . + c$ = substr iban$ 1 2 + for i to len cc$[] + if c$ = cc$[i] + return if len iban$ = ln[i] + . + . + return 0 +. +func mod97 s$ . + while s$ <> "" + h$ = r div 10 + h$ &= r mod 10 + h$ &= substr s$ 1 13 + s$ = substr s$ 14 9999 + r = number h$ mod 97 + . + return r +. +func isvalid hiban$ . + for c$ in strchars hiban$ + c = strcode c$ + if c > 32 + if c >= 97 and c < 122 + c -= 32 + c$ = strchar c + elif c < 48 or c > 57 and c < 65 or c > 90 + return 0 + . + miban$ &= c$ + . + . + if validcc miban$ = 0 + return 0 + . + for c$ in strchars substr miban$ 5 999 & substr miban$ 1 4 + c = strcode c$ + if c >= 65 and c <= 90 + t$ &= (c - 55) div 10 + t$ &= (c - 55) mod 10 + else + t$ &= c$ + . + . + return if mod97 t$ = 1 +. +proc check s$ . + write s$ & " is " + if isvalid s$ = 1 + print "valid" + else + print "not valid" + . +. +check "GB82 WEST 1234 5698 7654 32" +check "GB82WEST12345698765432" +check "gb82 west 1234 5698 7654 32" +check "GB82 TEST 1234 5698 7654 32" +check "GB82 WEST 1243 5698 7654 32" +check "GB82 west 1243 5698 7654 32" diff --git a/Task/IBAN/Elixir/iban.elixir b/Task/IBAN/Elixir/iban.ex similarity index 100% rename from Task/IBAN/Elixir/iban.elixir rename to Task/IBAN/Elixir/iban.ex diff --git a/Task/IBAN/Julia/iban.julia b/Task/IBAN/Julia/iban.jl similarity index 100% rename from Task/IBAN/Julia/iban.julia rename to Task/IBAN/Julia/iban.jl diff --git a/Task/IBAN/Kotlin/iban-1.kotlin b/Task/IBAN/Kotlin/iban-1.kts similarity index 100% rename from Task/IBAN/Kotlin/iban-1.kotlin rename to Task/IBAN/Kotlin/iban-1.kts diff --git a/Task/IBAN/Kotlin/iban-2.kotlin b/Task/IBAN/Kotlin/iban-2.kts similarity index 100% rename from Task/IBAN/Kotlin/iban-2.kotlin rename to Task/IBAN/Kotlin/iban-2.kts diff --git a/Task/IBAN/OCaml/iban.ocaml b/Task/IBAN/OCaml/iban.ml similarity index 100% rename from Task/IBAN/OCaml/iban.ocaml rename to Task/IBAN/OCaml/iban.ml diff --git a/Task/IBAN/PascalABC.NET/iban.pas b/Task/IBAN/PascalABC.NET/iban.pas new file mode 100644 index 0000000000..ad59a4e740 --- /dev/null +++ b/Task/IBAN/PascalABC.NET/iban.pas @@ -0,0 +1,33 @@ +var + countryLen := Dict( + ('AL', 28), ('AD', 24), ('AT', 20), ('AZ', 28), ('BE', 16), ('BH', 22), ('BA', 20), ('BR', 29), + ('BG', 22), ('CR', 21), ('HR', 21), ('CY', 28), ('CZ', 24), ('DK', 18), ('DO', 28), ('EE', 20), + ('FO', 18), ('FI', 18), ('FR', 27), ('GE', 22), ('DE', 22), ('GI', 23), ('GR', 27), ('GL', 18), + ('GT', 28), ('HU', 28), ('IS', 26), ('IE', 22), ('IL', 23), ('IT', 27), ('KZ', 20), ('KW', 30), + ('LV', 21), ('LB', 28), ('LI', 21), ('LT', 20), ('LU', 20), ('MK', 19), ('MT', 31), ('MR', 27), + ('MU', 30), ('MC', 27), ('MD', 24), ('ME', 22), ('NL', 18), ('NO', 15), ('PK', 24), ('PS', 29), + ('PL', 28), ('PT', 25), ('RO', 24), ('SM', 27), ('SA', 24), ('RS', 22), ('SK', 24), ('SI', 19), + ('ES', 24), ('SE', 24), ('CH', 21), ('TN', 24), ('TR', 26), ('AE', 23), ('GB', 22), ('VG', 24)); + +function validIban(iban: string): boolean; +begin + result := False; + iban := iban.Replace(' ', '').Replace(#9, ''); + if not iban.All(c -> c.isupper or c.isdigit) then exit; + + if iban.Length <> countryLen.Get(iban[1:3]) then exit; + + iban := iban[5:iban.Length + 1] + iban[1:5]; + var digits: string := ''; + foreach var ch in iban do + case ch of + '0'..'9': digits += ch; + 'A'..'Z': digits += (Ord(ch) - Ord('A') + 10).ToString; + end; + result := digits.ToBigInteger mod 97 = 1; +end; + +begin + foreach var account in |'GB82 WEST 1234 5698 7654 32', 'GB82 TEST 1234 5698 7654 32'| do + Println(account, 'validation is:', validIban(account)); +end. diff --git a/Task/IBAN/Phix/iban.phix b/Task/IBAN/Phix/iban.phix index 63cedf18ed..0d609477cd 100644 --- a/Task/IBAN/Phix/iban.phix +++ b/Task/IBAN/Phix/iban.phix @@ -1,61 +1,56 @@ -(phixonline)--> - -- - -- demo\rosetta\IBAN.exw - -- ===================== - -- - constant nations = {{"AD",24}, -- Andorra - -- (full list in distro) - {"CH",21}, -- Switzerland - {"GB",22}, -- United Kingdom - {"SA",24}, -- Saudi Arabia - {"XK",20}} -- Kosovo +-- demo\rosetta\IBAN.exw +constant nations = {{"AD",24}, -- Andorra + -- (full list in distro) + {"CH",21}, -- Switzerland + {"GB",22}, -- United Kingdom + {"SA",24}, -- Saudi Arabia + {"XK",20}} -- Kosovo - constant {countries,lengths} = columnize(nations) +constant {countries,lengths} = columnize(nations) - function iban(string code) - -- This routine does and should reject codes containing spaces etc. - -- Use iban_s() below for otherwise. - integer country = find(code[1..2],countries) - if country!=0 - and length(code)=lengths[country] then - code = code[5..$]&code[1..4] - integer c = 0 - for i=1 to length(code) do - integer ch=code[i] - if ch>='0' and ch<='9' then - c = c*10+ch-'0' - elsif ch>='A' and ch<='Z' then - c = c*100+ch-55 - else - return false - end if - c = mod(c,97) - end for - return c=1 - end if - return false - end function +function iban(string code) +-- This routine does and should reject codes containing spaces etc. +-- Use iban_s() below for otherwise. + integer country = find(code[1..2],countries) + if country!=0 + and length(code)=lengths[country] then + code = code[5..$]&code[1..4] + integer c = 0 + for i=1 to length(code) do + integer ch=code[i] + if ch>='0' and ch<='9' then + c = c*10+ch-'0' + elsif ch>='A' and ch<='Z' then + c = c*100+ch-55 + else + return false + end if + c = mod(c,97) + end for + return c=1 + end if + return false +end function - function iban_s(string code) - -- strips any embedded spaces and hyphens before validating. - code = substitute_all(code,{" ","-"},{"",""}) - return iban(code) - end function +function iban_s(string code) +-- strips any embedded spaces and hyphens before validating. + code = substitute_all(code,{" ","-"},{"",""}) + return iban(code) +end function - procedure test(string code, bool expected) - bool valid = iban_s(code) - string state - if valid=expected then - state = iff(valid?"ok":"invalid (as expected)") - else - state = iff(valid?"OK!!":"INVALID!!")&" (NOT AS EXPECTED)" - end if - printf(1,"%-34s :%s\n",{code,state}) - end procedure +procedure test(string code, bool expected) + bool valid = iban_s(code) + string state + if valid=expected then + state = iff(valid?"ok":"invalid (as expected)") + else + state = iff(valid?"OK!!":"INVALID!!")&" (NOT AS EXPECTED)" + end if + printf(1,"%-34s :%s\n",{code,state}) +end procedure - test("GB82 WEST 1234 5698 7654 32",true) - test("GB82 TEST 1234 5698 7654 32",false) - test("GB81 WEST 1234 5698 7654 32",false) - test("SA03 8000 0000 6080 1016 7519",true) - test("CH93 0076 2011 6238 5295 7",true) - - with javascript_semantics - procedure check_isbn13(string isbn) - integer digits = 0, checksum = 0, w = 1 - for i=1 to length(isbn) do - integer ch = isbn[i] - if ch!=' ' and ch!='-' then - ch -= '0' - if ch<0 or ch>9 then checksum = 9 exit end if - checksum += ch*w - digits += 1 - w = 4-w - end if - end for - checksum = remainder(checksum,10) - string gb = iff(digits=13 and checksum=0 ? "good" : "bad") - printf(1,"%s: %s\n",{isbn,gb}) - end procedure +with javascript_semantics +procedure check_isbn13(string isbn) + integer digits = 0, checksum = 0 + for ch in filter(isbn,"out"," -") do + if ch<'0' or ch>'9' then checksum = 9 exit end if + checksum += (ch-'0')*iff(even(digits)?1:3) + digits += 1 + end for + printf(1,"%s: %s\n",{isbn,iff(digits=13 and rmdr(checksum,10)=0 ? "good" : "bad")}) +end procedure - 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 - { Number in 0..9, Number #= Number0 - 48 }, digit(Number0). + +isbn13 --> + sequence(base10_digit, [D1, D2, D3]), "-", + sequence(base10_digit, [D4, D5, D6, D7, D8, D9, D10, D11, D12, D13]), + { ( D1 + 3 * D2 + D3 + 3 * D4 + + D5 + 3 * D6 + D7 + 3 * D8 + + D9 + 3 * D10 + D11 + 3 * D12 + D13 ) mod 10 #= 0 }. diff --git a/Task/ISBN13-check-digit/Prolog/isbn13-check-digit-2.pro b/Task/ISBN13-check-digit/Prolog/isbn13-check-digit-2.pro new file mode 100644 index 0000000000..7f3a3f0e20 --- /dev/null +++ b/Task/ISBN13-check-digit/Prolog/isbn13-check-digit-2.pro @@ -0,0 +1,11 @@ +?- phrase(isbn13, "978-0596528126"). +true. + +?- phrase(isbn13, "978-0596528120"). +false. + +?- phrase(isbn13, "978-1788399081"). +true. + +?- phrase(isbn13, "978-1788399083"). +false. diff --git a/Task/ISBN13-check-digit/Prolog/isbn13-check-digit-3.pro b/Task/ISBN13-check-digit/Prolog/isbn13-check-digit-3.pro new file mode 100644 index 0000000000..7225eeca85 --- /dev/null +++ b/Task/ISBN13-check-digit/Prolog/isbn13-check-digit-3.pro @@ -0,0 +1,12 @@ +?- ISBN = [0'9, 0'7, 0'8, 0'-, 0'0, 0'3, 0'0, 0'6, 0'4, 0'0, _, _, 0'5, 0'7], phrase(isbn13, ISBN). +ISBN = "978-0306400957" ; +ISBN = "978-0306401657" ; +ISBN = "978-0306402357" ; +ISBN = "978-0306403057" ; +ISBN = "978-0306404757" ; +ISBN = "978-0306405457" ; +ISBN = "978-0306406157" ; +ISBN = "978-0306407857" ; +ISBN = "978-0306408557" ; +ISBN = "978-0306409257" ; +false. diff --git a/Task/ISBN13-check-digit/Prolog/isbn13-check-digit-4.pro b/Task/ISBN13-check-digit/Prolog/isbn13-check-digit-4.pro new file mode 100644 index 0000000000..0b5d9cc7dc --- /dev/null +++ b/Task/ISBN13-check-digit/Prolog/isbn13-check-digit-4.pro @@ -0,0 +1,12 @@ +?- phrase(isbn13, ISBN). +ISBN = "000-0000000000" ; +ISBN = "000-0000000017" ; +ISBN = "000-0000000024" ; +ISBN = "000-0000000031" ; +ISBN = "000-0000000048" ; +ISBN = "000-0000000055" ; +ISBN = "000-0000000062" ; +ISBN = "000-0000000079" ; +ISBN = "000-0000000086" ; +ISBN = "000-0000000093" ; +ISBN = "000-0000000109" . % etc... diff --git a/Task/ISBN13-check-digit/R/isbn13-check-digit.r b/Task/ISBN13-check-digit/R/isbn13-check-digit.r new file mode 100644 index 0000000000..971ee0438e --- /dev/null +++ b/Task/ISBN13-check-digit/R/isbn13-check-digit.r @@ -0,0 +1,28 @@ +isbncheck <- function(str) { + # Remove non-digit characters + digits <- gsub("\\D", "", str) + + # Split into individual characters and convert to numeric + digit_vec <- as.numeric(strsplit(digits, "")[[1]]) + + # Calculate weighted sum + weighted_sum <- sum(sapply(seq_along(digit_vec), function(i) { + if (i %% 2 == 0) { + 3 * digit_vec[i] + } else { + digit_vec[i] + } + })) + + # Check if divisible by 10 + return(weighted_sum %% 10 == 0) +} + +# Test codes +testing_codes <- c("978-0596528126", "978-0596528120", + "978-1788399081", "978-1788399083") + +for (code in testing_codes) { + result <- ifelse(isbncheck(code), "good", "bad") + cat(code, ": ", result, "\n", sep = "") +} diff --git a/Task/ISBN13-check-digit/Rebol/isbn13-check-digit.rebol b/Task/ISBN13-check-digit/Rebol/isbn13-check-digit.rebol new file mode 100644 index 0000000000..568cd2a141 --- /dev/null +++ b/Task/ISBN13-check-digit/Rebol/isbn13-check-digit.rebol @@ -0,0 +1,27 @@ +Rebol [ + title: "Rosetta code: ISBN13 check digit" + file: %ISBN13_check_digit.r3 + url: https://rosettacode.org/wiki/ISBN13_check_digit + needs: 3.15.0 ;; or something like that +] +valid-isbn13?: function/with [ + "Validate the check digit of an ISBN-13 code" + value [any-string!] +][ + sum: 0 + parse value [ + 6 [ + to numeric set n: skip (sum: sum + n - #"0") ;; Add digit at odd index (weight 1) + to numeric set n: skip (sum: sum + (3 * (n - #"0"))) ;; Add digit at even index (weight 3) + ] + to numeric set n: skip (sum: sum + n - #"0") ;; Add the 13th digit (weight 1) + opt [to numeric (return false)] ;; If not exactly 13 digits, abort as invalid + ] + zero? (sum % 10) ;; Valid if weighted sum is divisible by 10 +] system/catalog/bitsets ;; Supply numeric bitset for parse (matches digits) + + +;; Check given examples +foreach [str] ["978-0596528126" "978-0596528120" "978-1788399081" "978-1788399083" "978-2-74839-908-0"] [ + print [pad str 18 "-" valid-isbn13? str] +] diff --git a/Task/ISBN13-check-digit/Rust/isbn13-check-digit.rust b/Task/ISBN13-check-digit/Rust/isbn13-check-digit.rs similarity index 100% rename from Task/ISBN13-check-digit/Rust/isbn13-check-digit.rust rename to Task/ISBN13-check-digit/Rust/isbn13-check-digit.rs diff --git a/Task/ISBN13-check-digit/Scala/isbn13-check-digit.scala b/Task/ISBN13-check-digit/Scala/isbn13-check-digit.scala new file mode 100644 index 0000000000..910add1d43 --- /dev/null +++ b/Task/ISBN13-check-digit/Scala/isbn13-check-digit.scala @@ -0,0 +1,26 @@ +object ISBNValidator: + private def checkChecksum(isbn: String): Boolean = + val digits = isbn.map(_.asDigit) + val checksum = digits.zipWithIndex.map { + case (digit, idx) => + if idx % 2 == 0 then digit + else digit * 3 + }.sum + checksum % 10 == 0 + + def isValidISBN13(isbn: String): Boolean = + val cleaned = isbn.filter(_.isDigit) + cleaned.length == 13 && checkChecksum(cleaned) + +@main def main(): Unit = + def test(isbn: String): Unit = + val result = ISBNValidator.isValidISBN13(isbn) + println(s"$isbn: $result") + + List( + "978-0596528126", + "978-0596528120", + "978-1788399081", + "978-1788399083" + ) + .foreach(test) diff --git a/Task/ISBN13-check-digit/Standard-ML/isbn13-check-digit-1.ml b/Task/ISBN13-check-digit/Standard-ML/isbn13-check-digit-1.ml new file mode 100644 index 0000000000..55acb3f3db --- /dev/null +++ b/Task/ISBN13-check-digit/Standard-ML/isbn13-check-digit-1.ml @@ -0,0 +1,22 @@ +(* these type decorations are optional, you could just as well put: + fun isValidISBN s = +*) +fun isValidISBN (s : string) : bool = + let + val digits = List.filter Char.isDigit (explode s) + val nums = map (fn x => ord x - ord #"0") digits + val len = length nums + fun sumISBN [] = raise Domain + | sumISBN [x] = x + | sumISBN (x1::x2::xs) = x1 + 3*x2 + sumISBN xs + in + len = 13 andalso sumISBN nums mod 10 = 0 + end + +val test = ["978-1734314502", "978-1734314509", + "978-1788399081", "978-1788399083"] + +fun printTest (s : string) : unit = + (print s; print (if isValidISBN s then ": good\n" else ": bad\n")) + +fun main () = app printTest test diff --git a/Task/ISBN13-check-digit/Standard-ML/isbn13-check-digit-2.ml b/Task/ISBN13-check-digit/Standard-ML/isbn13-check-digit-2.ml new file mode 100644 index 0000000000..c81cfd25c5 --- /dev/null +++ b/Task/ISBN13-check-digit/Standard-ML/isbn13-check-digit-2.ml @@ -0,0 +1,15 @@ +let + fun check (c, p as (m, n)) = + if Char.isDigit c then + (not m, (if m then 3 * (ord c - 48) else ord c - 48) + n) + else + p +in + fun checkISBN s = + Int.rem (#2 (CharVector.foldl check (false, 0) s), 10) = 0 +end + +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/Standard-ML/isbn13-check-digit.ml b/Task/ISBN13-check-digit/Standard-ML/isbn13-check-digit.ml deleted file mode 100644 index 14abd4e5fc..0000000000 --- a/Task/ISBN13-check-digit/Standard-ML/isbn13-check-digit.ml +++ /dev/null @@ -1,15 +0,0 @@ -local - fun check (c, p as (m, n)) = - if Char.isDigit c then - (not m, (if m then 3 * (ord c - 48) else ord c - 48) + n) - else - p -in - fun checkISBN s = - Int.rem (#2 (CharVector.foldl check (false, 0) s), 10) = 0 -end - -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/Identity-matrix/Ada/identity-matrix-1.ada b/Task/Identity-matrix/Ada/identity-matrix-1.adb similarity index 100% rename from Task/Identity-matrix/Ada/identity-matrix-1.ada rename to Task/Identity-matrix/Ada/identity-matrix-1.adb diff --git a/Task/Identity-matrix/Ada/identity-matrix-2.ada b/Task/Identity-matrix/Ada/identity-matrix-2.adb similarity index 100% rename from Task/Identity-matrix/Ada/identity-matrix-2.ada rename to Task/Identity-matrix/Ada/identity-matrix-2.adb diff --git a/Task/Identity-matrix/Beads/identity-matrix.beads b/Task/Identity-matrix/Beads/identity-matrix.beads index 5a440d7c66..095255f228 100644 --- a/Task/Identity-matrix/Beads/identity-matrix.beads +++ b/Task/Identity-matrix/Beads/identity-matrix.beads @@ -1,10 +1,10 @@ beads 1 program 'Identity matrix' var - id : array^2 of num - n = 5 - + id : array^2 of num + n = 5 + calc main_init - loop from:1 to:n index:i - loop from:1 to:n index:j - id[i,j] = 1 if i == j else 0 + loop from:1 to:n index:i + loop from:1 to:n index:j + id[i,j] = 1 if i == j else 0 diff --git a/Task/Identity-matrix/Component-Pascal/identity-matrix.pas b/Task/Identity-matrix/Component-Pascal/identity-matrix.pas index 297f88e2d6..80e25dbec2 100644 --- a/Task/Identity-matrix/Component-Pascal/identity-matrix.pas +++ b/Task/Identity-matrix/Component-Pascal/identity-matrix.pas @@ -2,34 +2,34 @@ MODULE Algebras; IMPORT StdLog,Strings; TYPE - Matrix = POINTER TO ARRAY OF ARRAY OF INTEGER; - + Matrix = POINTER TO ARRAY OF ARRAY OF INTEGER; + PROCEDURE NewIdentityMatrix(n: INTEGER): Matrix; VAR - m: Matrix; - i: INTEGER; + m: Matrix; + i: INTEGER; BEGIN - NEW(m,n,n); - FOR i := 0 TO n - 1 DO - m[i,i] := 1; - END; - RETURN m; + NEW(m,n,n); + FOR i := 0 TO n - 1 DO + m[i,i] := 1; + END; + RETURN m; END NewIdentityMatrix; PROCEDURE Show(m: Matrix); VAR - i,j: INTEGER; + i,j: INTEGER; BEGIN - FOR i := 0 TO LEN(m,0) - 1 DO - FOR j := 0 TO LEN(m,1) - 1 DO - StdLog.Int(m[i,j]); - END; - StdLog.Ln - END + FOR i := 0 TO LEN(m,0) - 1 DO + FOR j := 0 TO LEN(m,1) - 1 DO + StdLog.Int(m[i,j]); + END; + StdLog.Ln + END END Show; PROCEDURE Do*; BEGIN - Show(NewIdentityMatrix(5)); + Show(NewIdentityMatrix(5)); END Do; END Algebras. diff --git a/Task/Identity-matrix/Delphi/identity-matrix.delphi b/Task/Identity-matrix/Delphi/identity-matrix.pas similarity index 100% rename from Task/Identity-matrix/Delphi/identity-matrix.delphi rename to Task/Identity-matrix/Delphi/identity-matrix.pas diff --git a/Task/Identity-matrix/DuckDB/identity-matrix.duckdb b/Task/Identity-matrix/DuckDB/identity-matrix.duckdb new file mode 100644 index 0000000000..26cbc7a159 --- /dev/null +++ b/Task/Identity-matrix/DuckDB/identity-matrix.duckdb @@ -0,0 +1,20 @@ +# Produce an (i,j,value) table representing the matrix I(m,n) +# which is the identity matrix if m = n +create or replace function I(m,n,zero) as table ( + with recursive cte(i,j,ij,value) as ( + select 1, 1, (null,null), zero + union all + select if(j=n, i+1, i) as i, + if(j=n, 1, j+1) as j, + (i, j) as ij, + zero + if(i=j, 1, 0) as value + from cte + where i <= m + ) + select ij[1] as i, ij[2] as j, value + from cte + offset 1 +); + +# Generate a 3x3 matrix with DOUBLE(3,2) values: +from I(3, 3, 0.000); diff --git a/Task/Identity-matrix/EasyLang/identity-matrix.easy b/Task/Identity-matrix/EasyLang/identity-matrix.easy index d1552ef970..b85b3166c1 100644 --- a/Task/Identity-matrix/EasyLang/identity-matrix.easy +++ b/Task/Identity-matrix/EasyLang/identity-matrix.easy @@ -1,4 +1,4 @@ -proc idmat lng . mat[][] . +proc idmat lng &mat[][] . len mat[][] lng for i to lng len mat[i][] lng diff --git a/Task/Identity-matrix/Eiffel/identity-matrix.e b/Task/Identity-matrix/Eiffel/identity-matrix.e index ffeeb3ee35..084a34437f 100644 --- a/Task/Identity-matrix/Eiffel/identity-matrix.e +++ b/Task/Identity-matrix/Eiffel/identity-matrix.e @@ -1,61 +1,61 @@ class - APPLICATION + APPLICATION inherit - ARGUMENTS + ARGUMENTS create - make + make feature {NONE} -- Initialization - make - -- Run application. - local - dim : INTEGER -- Dimension of the identity matrix - do - from dim := 1 until dim > 10 loop - print_matrix( identity_matrix(dim) ) - dim := dim + 1 - io.new_line - end + make + -- Run application. + local + dim : INTEGER -- Dimension of the identity matrix + do + from dim := 1 until dim > 10 loop + print_matrix( identity_matrix(dim) ) + dim := dim + 1 + io.new_line + end - end + end feature -- Access - identity_matrix(dim : INTEGER) : ARRAY2[REAL_64] + identity_matrix(dim : INTEGER) : ARRAY2[REAL_64] - require - dim > 0 - local - matrix : ARRAY2[REAL_64] - i : INTEGER - do + require + dim > 0 + local + matrix : ARRAY2[REAL_64] + i : INTEGER + do - create matrix.make_filled (0.0, dim, dim) - from i := 1 until i > dim loop - matrix.put(1.0, i, i) - i := i + 1 - end + create matrix.make_filled (0.0, dim, dim) + from i := 1 until i > dim loop + matrix.put(1.0, i, i) + i := i + 1 + end - Result := matrix - end + Result := matrix + end - print_matrix(matrix : ARRAY2[REAL_64]) - local - i, j : INTEGER - do - from i := 1 until i > matrix.height loop - print("[ ") - from j := 1 until j > matrix.width loop - print(matrix.item (i, j)) - print(" ") - j := j + 1 - end - print("]%N") - i := i + 1 - end - end + print_matrix(matrix : ARRAY2[REAL_64]) + local + i, j : INTEGER + do + from i := 1 until i > matrix.height loop + print("[ ") + from j := 1 until j > matrix.width loop + print(matrix.item (i, j)) + print(" ") + j := j + 1 + end + print("]%N") + i := i + 1 + end + end end diff --git a/Task/Identity-matrix/Elena/identity-matrix.elena b/Task/Identity-matrix/Elena/identity-matrix.elena index 079b48e360..e02c88a428 100644 --- a/Task/Identity-matrix/Elena/identity-matrix.elena +++ b/Task/Identity-matrix/Elena/identity-matrix.elena @@ -2,7 +2,7 @@ import extensions; import system'routines; import system'collections; -public program() +public Program() { var n := console.write("Enter the matrix size:").readLine().toInt(); diff --git a/Task/Identity-matrix/Elixir/identity-matrix.elixir b/Task/Identity-matrix/Elixir/identity-matrix.ex similarity index 100% rename from Task/Identity-matrix/Elixir/identity-matrix.elixir rename to Task/Identity-matrix/Elixir/identity-matrix.ex diff --git a/Task/Identity-matrix/Excel/identity-matrix.excel b/Task/Identity-matrix/Excel/identity-matrix-1.excel similarity index 100% rename from Task/Identity-matrix/Excel/identity-matrix.excel rename to Task/Identity-matrix/Excel/identity-matrix-1.excel diff --git a/Task/Identity-matrix/Excel/identity-matrix-2.excel b/Task/Identity-matrix/Excel/identity-matrix-2.excel new file mode 100644 index 0000000000..f72b963773 --- /dev/null +++ b/Task/Identity-matrix/Excel/identity-matrix-2.excel @@ -0,0 +1 @@ +=MUNIT(A2) diff --git a/Task/Identity-matrix/J/identity-matrix.j b/Task/Identity-matrix/J/identity-matrix.j index a209ace2c5..a87aa8e298 100644 --- a/Task/Identity-matrix/J/identity-matrix.j +++ b/Task/Identity-matrix/J/identity-matrix.j @@ -1,10 +1,10 @@ - = i. 4 NB. create an Identity matrix of size 4 + =i.4 NB. create an Identity matrix of size 4 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 - makeI=: =@i. NB. define as a verb with a user-defined name - makeI 5 NB. create an Identity matrix of size 5 + Id=: =@i. NB. define as a verb with a user-defined name + Id 5 NB. create an Identity matrix of size 5 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 diff --git a/Task/Identity-matrix/Julia/identity-matrix-1.julia b/Task/Identity-matrix/Julia/identity-matrix-1.jl similarity index 100% rename from Task/Identity-matrix/Julia/identity-matrix-1.julia rename to Task/Identity-matrix/Julia/identity-matrix-1.jl diff --git a/Task/Identity-matrix/Julia/identity-matrix-2.julia b/Task/Identity-matrix/Julia/identity-matrix-2.jl similarity index 100% rename from Task/Identity-matrix/Julia/identity-matrix-2.julia rename to Task/Identity-matrix/Julia/identity-matrix-2.jl diff --git a/Task/Identity-matrix/Julia/identity-matrix-3.julia b/Task/Identity-matrix/Julia/identity-matrix-3.jl similarity index 100% rename from Task/Identity-matrix/Julia/identity-matrix-3.julia rename to Task/Identity-matrix/Julia/identity-matrix-3.jl diff --git a/Task/Identity-matrix/Kotlin/identity-matrix.kotlin b/Task/Identity-matrix/Kotlin/identity-matrix.kotlin deleted file mode 100644 index 8e873fc892..0000000000 --- a/Task/Identity-matrix/Kotlin/identity-matrix.kotlin +++ /dev/null @@ -1,17 +0,0 @@ -// version 1.0.6 - -fun main(args: Array) { - print("Enter size of matrix : ") - val n = readLine()!!.toInt() - println() - val identity = Array(n) { IntArray(n) } // create n x n matrix of integers - - // enter 1s in diagonal elements - for(i in 0 until n) identity[i][i] = 1 - - // print identity matrix if n <= 40 - if (n <= 40) - for (i in 0 until n) println(identity[i].joinToString(" ")) - else - println("Matrix is too big to display on 80 column console") -} diff --git a/Task/Identity-matrix/Kotlin/identity-matrix.kts b/Task/Identity-matrix/Kotlin/identity-matrix.kts new file mode 100644 index 0000000000..4b0278fd6e --- /dev/null +++ b/Task/Identity-matrix/Kotlin/identity-matrix.kts @@ -0,0 +1,16 @@ +fun main() { + print("Enter size of matrix : ") + val n = readln().toInt() + println() + val identity = Array(n) { i -> + IntArray(n) { j -> + if (i == j) 1 else 0 + } + } + + // print identity matrix if n <= 40 + if (n <= 40) + for (row in identity) println(row.joinToString(" ")) + else + println("Matrix is too big to display on 80 column console") +} diff --git a/Task/Identity-matrix/LSL/identity-matrix.lsl b/Task/Identity-matrix/LSL/identity-matrix.lsl index feec4fb3cc..92a0644c63 100644 --- a/Task/Identity-matrix/LSL/identity-matrix.lsl +++ b/Task/Identity-matrix/LSL/identity-matrix.lsl @@ -1,19 +1,19 @@ default { - state_entry() { - llListen(PUBLIC_CHANNEL, "", llGetOwner(), ""); - llOwnerSay("Please Enter a Dimension for an Identity Matrix."); - } - listen(integer iChannel, string sName, key kId, string sMessage) { - llOwnerSay("You entered "+sMessage+"."); - list lMatrix = []; - integer x = 0; - integer n = (integer)sMessage; - for(x=0 ; x i = j ? 1 : 0); + matrix.Println +end. diff --git a/Task/Identity-matrix/Pluto/identity-matrix.pluto b/Task/Identity-matrix/Pluto/identity-matrix.pluto new file mode 100644 index 0000000000..46f405c2cb --- /dev/null +++ b/Task/Identity-matrix/Pluto/identity-matrix.pluto @@ -0,0 +1,4 @@ +require "matrix" + +local num_rows = 10 -- say +print(matrix.identity(num_rows)) diff --git a/Task/Identity-matrix/PowerShell/identity-matrix-1.psh b/Task/Identity-matrix/PowerShell/identity-matrix-1.ps1 similarity index 100% rename from Task/Identity-matrix/PowerShell/identity-matrix-1.psh rename to Task/Identity-matrix/PowerShell/identity-matrix-1.ps1 diff --git a/Task/Identity-matrix/PowerShell/identity-matrix-2.psh b/Task/Identity-matrix/PowerShell/identity-matrix-2.ps1 similarity index 100% rename from Task/Identity-matrix/PowerShell/identity-matrix-2.psh rename to Task/Identity-matrix/PowerShell/identity-matrix-2.ps1 diff --git a/Task/Identity-matrix/Prolog/identity-matrix.pro b/Task/Identity-matrix/Prolog/identity-matrix.pro index 94044cad1f..6397d9d7d0 100644 --- a/Task/Identity-matrix/Prolog/identity-matrix.pro +++ b/Task/Identity-matrix/Prolog/identity-matrix.pro @@ -1,29 +1,29 @@ %rotates one list clockwise by one integer rotate(Int,List,Rotated) :- - integer(Int), - length(Suff,Int), - append(Pre,Suff,List), - append(Suff,Pre,Rotated). + integer(Int), + length(Suff,Int), + append(Pre,Suff,List), + append(Suff,Pre,Rotated). %rotates a list of lists by a list of integers rotate(LoInts,LoLists,Rotated) :- - is_list(LoInts), - maplist(rotate,LoInts,LoLists,Rotated). + is_list(LoInts), + maplist(rotate,LoInts,LoLists,Rotated). %helper function append_(Suff,Pre,List) :- - append([Pre],Suff,List). + append([Pre],Suff,List). idmatrix(N,IdMatrix):- - %make an N length list of 1s and append with N-1 0s - length(Ones,N), - maplist(=(1),Ones), - succ(N0,N), - length(Zeros,N0), - maplist(=(0),Zeros), - maplist(append_(Zeros),Ones,M), - %create the offsets at rotate each row - numlist(0,N0,Offsets), - rotate(Offsets,M,IdMatrix). + %make an N length list of 1s and append with N-1 0s + length(Ones,N), + maplist(=(1),Ones), + succ(N0,N), + length(Zeros,N0), + maplist(=(0),Zeros), + maplist(append_(Zeros),Ones,M), + %create the offsets at rotate each row + numlist(0,N0,Offsets), + rotate(Offsets,M,IdMatrix). main :- - idmatrix(5,I), - maplist(writeln,I). + idmatrix(5,I), + maplist(writeln,I). diff --git a/Task/Identity-matrix/Rebol/identity-matrix-1.rebol b/Task/Identity-matrix/Rebol/identity-matrix-1.rebol new file mode 100644 index 0000000000..5260ef0941 --- /dev/null +++ b/Task/Identity-matrix/Rebol/identity-matrix-1.rebol @@ -0,0 +1,7 @@ +identity-matrix: function[size [integer!]][ + matrix: array/initial reduce [size size] 0 + repeat i size [matrix/:i/:i: 1] + new-line/all matrix true + matrix +] +probe identity-matrix 5 diff --git a/Task/Identity-matrix/Rebol/identity-matrix-2.rebol b/Task/Identity-matrix/Rebol/identity-matrix-2.rebol new file mode 100644 index 0000000000..02d78116c0 --- /dev/null +++ b/Task/Identity-matrix/Rebol/identity-matrix-2.rebol @@ -0,0 +1,9 @@ +identity-matrix: function [size [integer!]][ + matrix: array/initial size * size 0 ;; Create a flat array with size^2 elements, all zeros + repeat i size [ + matrix/((i - 1) * size + i): 1 ;; Set 1 on the diagonal: row-major position + ] + new-line/skip matrix true size + matrix +] +probe identity-matrix 5 diff --git a/Task/Identity-matrix/Ring/identity-matrix-2.ring b/Task/Identity-matrix/Ring/identity-matrix-2.ring index 4c2d938b39..7c8f780d4a 100644 --- a/Task/Identity-matrix/Ring/identity-matrix-2.ring +++ b/Task/Identity-matrix/Ring/identity-matrix-2.ring @@ -18,30 +18,30 @@ LayoutButtonRow = list(size) app = new qApp { win = new qWidget() { - setWindowTitle('Identity Matrix') - move(500,100) - reSize(600,600) - winheight = win.height() - fontSize = 18 + (winheight / 100) + setWindowTitle('Identity Matrix') + move(500,100) + reSize(600,600) + winheight = win.height() + fontSize = 18 + (winheight / 100) - LayoutButtonMain = new QVBoxLayout() - LayoutButtonMain.setSpacing(C_Spacing) - LayoutButtonMain.setContentsmargins(0,0,0,0) + LayoutButtonMain = new QVBoxLayout() + LayoutButtonMain.setSpacing(C_Spacing) + LayoutButtonMain.setContentsmargins(0,0,0,0) - for Row = 1 to size - LayoutButtonRow[Row] = new QHBoxLayout() { - setSpacing(C_Spacing) - setContentsmargins(0,0,0,0) - } - for Col = 1 to size - Button[Row][Col] = new QPushButton(win) { + for Row = 1 to size + LayoutButtonRow[Row] = new QHBoxLayout() { + setSpacing(C_Spacing) + setContentsmargins(0,0,0,0) + } + for Col = 1 to size + Button[Row][Col] = new QPushButton(win) { setSizePolicy(1,1) - } - - LayoutButtonRow[Row].AddWidget(Button[Row][Col]) - next - LayoutButtonMain.AddLayout(LayoutButtonRow[Row]) - next + } + + LayoutButtonRow[Row].AddWidget(Button[Row][Col]) + next + LayoutButtonMain.AddLayout(LayoutButtonRow[Row]) + next LayoutDataRow1 = new QHBoxLayout() { setSpacing(C_Spacing) setContentsMargins(0,0,0,0) } LayoutButtonMain.AddLayout(LayoutDataRow1) setLayout(LayoutButtonMain) @@ -61,6 +61,6 @@ func pBegin() Button[Row][Col].setStyleSheet(C_ButtonBlueStyle) Button[Row][Col].settext("0") ok - next + next next score = 0 diff --git a/Task/Identity-matrix/Rust/identity-matrix.rust b/Task/Identity-matrix/Rust/identity-matrix.rs similarity index 100% rename from Task/Identity-matrix/Rust/identity-matrix.rust rename to Task/Identity-matrix/Rust/identity-matrix.rs diff --git a/Task/Identity-matrix/Scheme/identity-matrix-1.scm b/Task/Identity-matrix/Scheme/identity-matrix-1.scm new file mode 100644 index 0000000000..7ed20ab33c --- /dev/null +++ b/Task/Identity-matrix/Scheme/identity-matrix-1.scm @@ -0,0 +1,15 @@ +(define (identity n) + (letrec + ((uvec + (lambda (m i acc) + (if (= i n) + acc + (uvec m (+ i 1) + (cons (if (= i m) 1 0) acc))))) + (idgen + (lambda (i acc) + (if (= i n) + acc + (idgen (+ i 1) + (cons (uvec i 0 '()) acc)))))) + (idgen 0 '()))) diff --git a/Task/Identity-matrix/Scheme/identity-matrix-1.ss b/Task/Identity-matrix/Scheme/identity-matrix-1.ss deleted file mode 100644 index fcd8fd0dcc..0000000000 --- a/Task/Identity-matrix/Scheme/identity-matrix-1.ss +++ /dev/null @@ -1,15 +0,0 @@ -(define (identity n) - (letrec - ((uvec - (lambda (m i acc) - (if (= i n) - acc - (uvec m (+ i 1) - (cons (if (= i m) 1 0) acc))))) - (idgen - (lambda (i acc) - (if (= i n) - acc - (idgen (+ i 1) - (cons (uvec i 0 '()) acc)))))) - (idgen 0 '()))) diff --git a/Task/Identity-matrix/Scheme/identity-matrix-2.ss b/Task/Identity-matrix/Scheme/identity-matrix-2.scm similarity index 100% rename from Task/Identity-matrix/Scheme/identity-matrix-2.ss rename to Task/Identity-matrix/Scheme/identity-matrix-2.scm diff --git a/Task/Identity-matrix/SenseTalk/identity-matrix.sensetalk b/Task/Identity-matrix/SenseTalk/identity-matrix.sensetalk index 5b8c568f1e..ece24bf611 100644 --- a/Task/Identity-matrix/SenseTalk/identity-matrix.sensetalk +++ b/Task/Identity-matrix/SenseTalk/identity-matrix.sensetalk @@ -1,28 +1,28 @@ set matrix to buildIdentityMatrix(3) repeat for each item in matrix - put it + put it end repeat set matrix to buildIdentityMatrix(17) repeat for each item in matrix - put it + put it end repeat function buildIdentityMatrix matrixSize - set matrixList to () - repeat matrixSize times - set rowMatrixIndex to the counter - set rowMatrix to () - repeat matrixSize times - if the counter equals rowMatrixIndex - insert 1 after rowMatrix - else - insert 0 after rowMatrix - end if - end repeat - insert rowMatrix nested after matrixList - end repeat - return matrixList + set matrixList to () + repeat matrixSize times + set rowMatrixIndex to the counter + set rowMatrix to () + repeat matrixSize times + if the counter equals rowMatrixIndex + insert 1 after rowMatrix + else + insert 0 after rowMatrix + end if + end repeat + insert rowMatrix nested after matrixList + end repeat + return matrixList end buildIdentityMatrix diff --git a/Task/Identity-matrix/Sparkling/identity-matrix.sparkling b/Task/Identity-matrix/Sparkling/identity-matrix.sparkling index ea0381bc1b..7db205e1c4 100644 --- a/Task/Identity-matrix/Sparkling/identity-matrix.sparkling +++ b/Task/Identity-matrix/Sparkling/identity-matrix.sparkling @@ -1,7 +1,7 @@ function unitMatrix(n) { - return map(range(n), function(k1, v1) { - return map(range(n), function(k2, v2) { - return v2 == v1 ? 1 : 0; - }); - }); + return map(range(n), function(k1, v1) { + return map(range(n), function(k2, v2) { + return v2 == v1 ? 1 : 0; + }); + }); } diff --git a/Task/Identity-matrix/Tailspin/identity-matrix.tailspin b/Task/Identity-matrix/Tailspin/identity-matrix-1.tailspin similarity index 100% rename from Task/Identity-matrix/Tailspin/identity-matrix.tailspin rename to Task/Identity-matrix/Tailspin/identity-matrix-1.tailspin diff --git a/Task/Identity-matrix/Tailspin/identity-matrix-2.tailspin b/Task/Identity-matrix/Tailspin/identity-matrix-2.tailspin new file mode 100644 index 0000000000..301d97f5fd --- /dev/null +++ b/Task/Identity-matrix/Tailspin/identity-matrix-2.tailspin @@ -0,0 +1,8 @@ +identityMatrix templates + n is $; + [1..$n -> [1..~$ -> 0, 1, $~..$n -> 0]] ! +end identityMatrix + +identity is 5 -> identityMatrix; +$identity... -> '|$(1);$(2..)... -> ', $;';| +' ! diff --git a/Task/Identity-matrix/Tcl/identity-matrix-1.tcl b/Task/Identity-matrix/Tcl/identity-matrix-1.tcl index 17692fce2d..652bacb01b 100644 --- a/Task/Identity-matrix/Tcl/identity-matrix-1.tcl +++ b/Task/Identity-matrix/Tcl/identity-matrix-1.tcl @@ -1,7 +1,7 @@ proc I {rank {zero 0.0} {one 1.0}} { set m [lrepeat $rank [lrepeat $rank $zero]] for {set i 0} {$i < $rank} {incr i} { - lset m $i $i $one + lset m $i $i $one } return $m } diff --git a/Task/Identity-matrix/Tcl/identity-matrix-2.tcl b/Task/Identity-matrix/Tcl/identity-matrix-2.tcl index 2342fdd286..c2560fe41a 100644 --- a/Task/Identity-matrix/Tcl/identity-matrix-2.tcl +++ b/Task/Identity-matrix/Tcl/identity-matrix-2.tcl @@ -5,9 +5,9 @@ proc I {rank {zero 0.0} {one 1.0}} { $m add columns $rank $m add rows $rank for {set i 0} {$i < $rank} {incr i} { - for {set j 0} {$j < $rank} {incr j} { - $m set cell $i $j [expr {$i==$j ? $one : $zero}] - } + for {set j 0} {$j < $rank} {incr j} { + $m set cell $i $j [expr {$i==$j ? $one : $zero}] + } } return $m } diff --git a/Task/Identity-matrix/Uiua/identity-matrix.uiua b/Task/Identity-matrix/Uiua/identity-matrix.uiua new file mode 100644 index 0000000000..2c76013a8d --- /dev/null +++ b/Task/Identity-matrix/Uiua/identity-matrix.uiua @@ -0,0 +1,2 @@ +IdMatrix ← ⊞=.⇡ +IdMatrix 7 diff --git a/Task/Identity-matrix/VBScript/identity-matrix-1.vb b/Task/Identity-matrix/VBScript/identity-matrix-1.vb deleted file mode 100644 index 5c7a77dd67..0000000000 --- a/Task/Identity-matrix/VBScript/identity-matrix-1.vb +++ /dev/null @@ -1,29 +0,0 @@ -build_matrix(7) - -Sub build_matrix(n) - Dim matrix() - ReDim matrix(n-1,n-1) - i = 0 - 'populate the matrix - For row = 0 To n-1 - For col = 0 To n-1 - If col = i Then - matrix(row,col) = 1 - Else - matrix(row,col) = 0 - End If - Next - i = i + 1 - Next - 'display the matrix - For row = 0 To n-1 - For col = 0 To n-1 - If col < n-1 Then - WScript.StdOut.Write matrix(row,col) & " " - Else - WScript.StdOut.Write matrix(row,col) - End If - Next - WScript.StdOut.WriteLine - Next -End Sub diff --git a/Task/Identity-matrix/VBScript/identity-matrix-1.vbs b/Task/Identity-matrix/VBScript/identity-matrix-1.vbs new file mode 100644 index 0000000000..a9e51579b8 --- /dev/null +++ b/Task/Identity-matrix/VBScript/identity-matrix-1.vbs @@ -0,0 +1,29 @@ +build_matrix(7) + +Sub build_matrix(n) + Dim matrix() + ReDim matrix(n-1,n-1) + i = 0 + 'populate the matrix + For row = 0 To n-1 + For col = 0 To n-1 + If col = i Then + matrix(row,col) = 1 + Else + matrix(row,col) = 0 + End If + Next + i = i + 1 + Next + 'display the matrix + For row = 0 To n-1 + For col = 0 To n-1 + If col < n-1 Then + WScript.StdOut.Write matrix(row,col) & " " + Else + WScript.StdOut.Write matrix(row,col) + End If + Next + WScript.StdOut.WriteLine + Next +End Sub diff --git a/Task/Identity-matrix/VBScript/identity-matrix-2.vb b/Task/Identity-matrix/VBScript/identity-matrix-2.vbs similarity index 100% rename from Task/Identity-matrix/VBScript/identity-matrix-2.vb rename to Task/Identity-matrix/VBScript/identity-matrix-2.vbs diff --git a/Task/Identity-matrix/Vala/identity-matrix.vala b/Task/Identity-matrix/Vala/identity-matrix.vala index a061d4d56b..6365ad13d8 100644 --- a/Task/Identity-matrix/Vala/identity-matrix.vala +++ b/Task/Identity-matrix/Vala/identity-matrix.vala @@ -1,25 +1,25 @@ int main (string[] args) { - if (args.length < 2) { - print ("Please, input an integer > 0.\n"); - return 0; - } - var n = int.parse (args[1]); - if (n <= 0) { - print ("Please, input an integer > 0.\n"); - return 0; - } - int[,] array = new int[n, n]; - for (var i = 0; i < n; i ++) { - for (var j = 0; j < n; j ++) { - if (i == j) array[i,j] = 1; - else array[i,j] = 0; - } - } - for (var i = 0; i < n; i ++) { - for (var j = 0; j < n; j ++) { - print ("%d ", array[i,j]); - } - print ("\b\n"); - } - return 0; + if (args.length < 2) { + print ("Please, input an integer > 0.\n"); + return 0; + } + var n = int.parse (args[1]); + if (n <= 0) { + print ("Please, input an integer > 0.\n"); + return 0; + } + int[,] array = new int[n, n]; + for (var i = 0; i < n; i ++) { + for (var j = 0; j < n; j ++) { + if (i == j) array[i,j] = 1; + else array[i,j] = 0; + } + } + for (var i = 0; i < n; i ++) { + for (var j = 0; j < n; j ++) { + print ("%d ", array[i,j]); + } + print ("\b\n"); + } + return 0; } diff --git a/Task/Identity-matrix/XBasic/identity-matrix.basic b/Task/Identity-matrix/XBasic/identity-matrix.basic index eede4569ac..8af9483abb 100644 --- a/Task/Identity-matrix/XBasic/identity-matrix.basic +++ b/Task/Identity-matrix/XBasic/identity-matrix.basic @@ -1,5 +1,5 @@ PROGRAM "Identity matrix" -VERSION "0.0000" +VERSION "0.0000" DECLARE FUNCTION Entry () diff --git a/Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/Ada/idiomatically-determine-all-the-characters-that-can-be-used-for-symbols.adb b/Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/Ada/idiomatically-determine-all-the-characters-that-can-be-used-for-symbols.adb new file mode 100644 index 0000000000..d2d6842033 --- /dev/null +++ b/Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/Ada/idiomatically-determine-all-the-characters-that-can-be-used-for-symbols.adb @@ -0,0 +1,12 @@ +with Ada.Strings.Maps; use Ada.Strings.Maps; +with Ada.Text_IO; + +procedure Show_Valid_Identifiers is + Valid_First_Character : constant Character_Set := To_Set (Ranges => (1 => ('a', 'z'), 2 => ('A', 'Z'))); + Valid_Last_Character : constant Character_Set := Valid_First_Character or To_Set (Ranges => (1 => ('0', '9'))); + Valid_Middle_Character : constant Character_Set := Valid_Last_Character or To_Set ('_'); +begin + Ada.Text_IO.Put_Line ("Valid for the first character: " & String (To_Sequence (Valid_First_Character))); + Ada.Text_IO.Put_Line ("Valid for any middle character: " & String (To_Sequence (Valid_Middle_Character))); + Ada.Text_IO.Put_Line ("Valid for the last character: " & String (To_Sequence (Valid_Last_Character))); +end Show_Valid_Identifiers; diff --git a/Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/Delphi/idiomatically-determine-all-the-characters-that-can-be-used-for-symbols.delphi b/Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/Delphi/idiomatically-determine-all-the-characters-that-can-be-used-for-symbols.pas similarity index 100% rename from Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/Delphi/idiomatically-determine-all-the-characters-that-can-be-used-for-symbols.delphi rename to Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/Delphi/idiomatically-determine-all-the-characters-that-can-be-used-for-symbols.pas diff --git a/Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/DuckDB/idiomatically-determine-all-the-characters-that-can-be-used-for-symbols.duckdb b/Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/DuckDB/idiomatically-determine-all-the-characters-that-can-be-used-for-symbols.duckdb new file mode 100644 index 0000000000..44a338df57 --- /dev/null +++ b/Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/DuckDB/idiomatically-determine-all-the-characters-that-can-be-used-for-symbols.duckdb @@ -0,0 +1,27 @@ +# Generate a string of all the codepoints in the range [m,n) +# corresponding to the given Unicode character class, where `class` +# could be '[a-z]' or '\p{Ll}', etc. +# +# Note: codepoints 55296 to 57343 (xD800–xDFFF) are reserved for the +# surrogates mechanism and are excluded as they are regarded as "illegal" +# as characters. +# +create or replace function generate(class, m, n) as ( + select string_agg(s, '') + from (select + case when 55296 <=i and i <= 57343 then null + else regexp_extract( chr(i::INTEGER), class) + end as s + from range(m, n) t(i)) +); + +# ident_start minus NBSP +select generate( '[A-Za-z\200-\237\241-\377_]',0, 1024); + +.mode list + +with ident_start as ( + select generate( '[A-Za-z\200-\237\241-\377_]',0,1024 ) as s + ) + select unnest(regexp_extract_all(s, '.{1,26}')) + from ident_start; diff --git a/Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/EasyLang/idiomatically-determine-all-the-characters-that-can-be-used-for-symbols.easy b/Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/EasyLang/idiomatically-determine-all-the-characters-that-can-be-used-for-symbols.easy new file mode 100644 index 0000000000..700c376ff1 --- /dev/null +++ b/Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/EasyLang/idiomatically-determine-all-the-characters-that-can-be-used-for-symbols.easy @@ -0,0 +1,13 @@ +print "First character:" +write "_" +for i = strcode "A" to strcode "Z" + write strchar i +. +for i = strcode "a" to strcode "z" + write strchar i +. +print "" +print "Not as the first character additionally:" +for i = strcode "0" to strcode "9" + write strchar i +. diff --git a/Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/Julia/idiomatically-determine-all-the-characters-that-can-be-used-for-symbols.julia b/Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/Julia/idiomatically-determine-all-the-characters-that-can-be-used-for-symbols.jl similarity index 100% rename from Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/Julia/idiomatically-determine-all-the-characters-that-can-be-used-for-symbols.julia rename to Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/Julia/idiomatically-determine-all-the-characters-that-can-be-used-for-symbols.jl diff --git a/Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/Kotlin/idiomatically-determine-all-the-characters-that-can-be-used-for-symbols.kotlin b/Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/Kotlin/idiomatically-determine-all-the-characters-that-can-be-used-for-symbols.kts similarity index 100% rename from Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/Kotlin/idiomatically-determine-all-the-characters-that-can-be-used-for-symbols.kotlin rename to Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/Kotlin/idiomatically-determine-all-the-characters-that-can-be-used-for-symbols.kts diff --git a/Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/M2000-Interpreter/idiomatically-determine-all-the-characters-that-can-be-used-for-symbols.m2000 b/Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/M2000-Interpreter/idiomatically-determine-all-the-characters-that-can-be-used-for-symbols.m2000 new file mode 100644 index 0000000000..1ab74f5f29 --- /dev/null +++ b/Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/M2000-Interpreter/idiomatically-determine-all-the-characters-that-can-be-used-for-symbols.m2000 @@ -0,0 +1,12 @@ +for=100 +print for=100 +for for=1 to 10:Print for: Next for +Print for=11 +to=100 +print to=100 +for to=1 to 10:Print to: Next to +Print to=11 +Print=100 +print Print=100 +for Print=1 to 10:Print Print: Next Print +Print Print=11 diff --git a/Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/Wren/idiomatically-determine-all-the-characters-that-can-be-used-for-symbols.wren b/Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/Wren/idiomatically-determine-all-the-characters-that-can-be-used-for-symbols.wren index 381544e810..8e2277f929 100644 --- a/Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/Wren/idiomatically-determine-all-the-characters-that-can-be-used-for-symbols.wren +++ b/Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/Wren/idiomatically-determine-all-the-characters-that-can-be-used-for-symbols.wren @@ -1,3 +1,4 @@ for (i in 97..122) System.write(String.fromByte(i)) for (i in 65..90) System.write(String.fromByte(i)) +for (i in 48..57) System.write(String.fromByte(i)) System.print("_") diff --git a/Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/Ada/idiomatically-determine-all-the-lowercase-and-uppercase-letters.ada b/Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/Ada/idiomatically-determine-all-the-lowercase-and-uppercase-letters.adb similarity index 100% rename from Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/Ada/idiomatically-determine-all-the-lowercase-and-uppercase-letters.ada rename to Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/Ada/idiomatically-determine-all-the-lowercase-and-uppercase-letters.adb diff --git a/Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/Arturo/idiomatically-determine-all-the-lowercase-and-uppercase-letters.arturo b/Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/Arturo/idiomatically-determine-all-the-lowercase-and-uppercase-letters.arturo index 05b8a27f68..7c6cd7e44d 100644 --- a/Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/Arturo/idiomatically-determine-all-the-lowercase-and-uppercase-letters.arturo +++ b/Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/Arturo/idiomatically-determine-all-the-lowercase-and-uppercase-letters.arturo @@ -1,2 +1,2 @@ -print ["lowercase letters:" `a`..`z`] -print ["uppercase letters:" `A`..`Z`] +print ["lowercase letters:" @'a'..'z'] +print ["uppercase letters:" @'A'..'Z'] diff --git a/Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/COBOL/idiomatically-determine-all-the-lowercase-and-uppercase-letters.cobol b/Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/COBOL/idiomatically-determine-all-the-lowercase-and-uppercase-letters.cob similarity index 100% rename from Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/COBOL/idiomatically-determine-all-the-lowercase-and-uppercase-letters.cobol rename to Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/COBOL/idiomatically-determine-all-the-lowercase-and-uppercase-letters.cob diff --git a/Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/Crystal/idiomatically-determine-all-the-lowercase-and-uppercase-letters.cr b/Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/Crystal/idiomatically-determine-all-the-lowercase-and-uppercase-letters.cr new file mode 100644 index 0000000000..5c334faa07 --- /dev/null +++ b/Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/Crystal/idiomatically-determine-all-the-lowercase-and-uppercase-letters.cr @@ -0,0 +1,10 @@ +letters = ((0.chr)..Char::MAX).group_by { |ch| + case ch + when .lowercase? then :lower + when .uppercase? then :upper + else :neither + end +} + +puts "Lowercase: #{letters[:lower].join(" ")}" +puts "Uppercase: #{letters[:upper].join(" ")}" diff --git a/Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/Delphi/idiomatically-determine-all-the-lowercase-and-uppercase-letters.delphi b/Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/Delphi/idiomatically-determine-all-the-lowercase-and-uppercase-letters.pas similarity index 100% rename from Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/Delphi/idiomatically-determine-all-the-lowercase-and-uppercase-letters.delphi rename to Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/Delphi/idiomatically-determine-all-the-lowercase-and-uppercase-letters.pas diff --git a/Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/DuckDB/idiomatically-determine-all-the-lowercase-and-uppercase-letters.duckdb b/Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/DuckDB/idiomatically-determine-all-the-lowercase-and-uppercase-letters.duckdb new file mode 100644 index 0000000000..825cc013b9 --- /dev/null +++ b/Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/DuckDB/idiomatically-determine-all-the-lowercase-and-uppercase-letters.duckdb @@ -0,0 +1,19 @@ +# The number of Unicode codepoints +set variable maxu = 1114112; + +# Generate a string of all the codepoints in the range [m,n) +# corresponding to the given Unicode character class, where `class` +# could be '[a-z]' or '\p{Ll}', etc. +# +# Note: codepoints 55296 to 57343 (xD800–xDFFF) are reserved for the +# surrogates mechanism and are excluded as they are regarded "illegal" +# as characters. +# +create or replace function generate(class, m, n) as ( + select string_agg(s, '') + from (select + case when 55296 <=i and i <= 57343 then null + else regexp_extract( chr(i::INTEGER), class) + end as s + from range(m, n) t(i)) +); diff --git a/Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/EasyLang/idiomatically-determine-all-the-lowercase-and-uppercase-letters.easy b/Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/EasyLang/idiomatically-determine-all-the-lowercase-and-uppercase-letters.easy index aca86fb76f..a8bb064adb 100644 --- a/Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/EasyLang/idiomatically-determine-all-the-lowercase-and-uppercase-letters.easy +++ b/Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/EasyLang/idiomatically-determine-all-the-lowercase-and-uppercase-letters.easy @@ -1,7 +1,6 @@ -for i = strcode "a" to strcode "z" - write strchar i -. -print "" -for i = strcode "A" to strcode "Z" - write strchar i +proc out a b . + for i = a to b : write strchar i + print "" . +out 97 122 +out 65 90 diff --git a/Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/Haskell/idiomatically-determine-all-the-lowercase-and-uppercase-letters-3.hs b/Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/Haskell/idiomatically-determine-all-the-lowercase-and-uppercase-letters-3.hs index 164ce4f353..f3f86f5e34 100644 --- a/Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/Haskell/idiomatically-determine-all-the-lowercase-and-uppercase-letters-3.hs +++ b/Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/Haskell/idiomatically-determine-all-the-lowercase-and-uppercase-letters-3.hs @@ -1,4 +1,4 @@ (let chars-between (comp range (map char-code) (... str))) -(str "Upper-case: " (chars-between 65 91) " -Lower-case: " (chars-between 97 123)) +"Upper-case: {chars-between 65 91} +Lower-case: {chars-between 97 123}" diff --git a/Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/Julia/idiomatically-determine-all-the-lowercase-and-uppercase-letters.jl b/Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/Julia/idiomatically-determine-all-the-lowercase-and-uppercase-letters.jl new file mode 100644 index 0000000000..19a26a3ffa --- /dev/null +++ b/Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/Julia/idiomatically-determine-all-the-lowercase-and-uppercase-letters.jl @@ -0,0 +1,24 @@ +function countunicode() + count = 0 + az = "" + AZ = "" + for i in 0:0xffffff + if isvalid(Char, i) + c = Char(i) + count += 1 + if i < 128 && isletter(c) + if islowercase(c) + az *= "$c" + elseif isuppercase(c) + AZ *= "$c" + end + end + end + end + count, az, AZ +end + +unicodecount, lcletters, ucletters = countunicode() + +println("There are $unicodecount valid Chars and the ASCII English ones are:") +println("lowercase: $lcletters and uppercase: $ucletters .") diff --git a/Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/Julia/idiomatically-determine-all-the-lowercase-and-uppercase-letters.julia b/Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/Julia/idiomatically-determine-all-the-lowercase-and-uppercase-letters.julia deleted file mode 100644 index 9a83077168..0000000000 --- a/Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/Julia/idiomatically-determine-all-the-lowercase-and-uppercase-letters.julia +++ /dev/null @@ -1,25 +0,0 @@ -function countunicode() - englishlettercodes = [Int(c) for c in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"] - count = 0 - az = "" - AZ = "" - for i in 0:0xffffff - if is_assigned_char(i) - count += 1 - end - if i in englishlettercodes - c = Char(i) - if islower(c) - az *= "$c" - else - AZ *= "$c" - end - end - end - count, az, AZ -end - -unicodecount, lcletters, ucletters = countunicode() - -print("There are $unicodecount valid Chars and the English ones are ") -println("lowercase: $lcletters and uppercase: $ucletters.") diff --git a/Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/Kotlin/idiomatically-determine-all-the-lowercase-and-uppercase-letters.kotlin b/Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/Kotlin/idiomatically-determine-all-the-lowercase-and-uppercase-letters.kts similarity index 100% rename from Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/Kotlin/idiomatically-determine-all-the-lowercase-and-uppercase-letters.kotlin rename to Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/Kotlin/idiomatically-determine-all-the-lowercase-and-uppercase-letters.kts diff --git a/Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/Phix/idiomatically-determine-all-the-lowercase-and-uppercase-letters-1.phix b/Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/Phix/idiomatically-determine-all-the-lowercase-and-uppercase-letters-1.phix new file mode 100644 index 0000000000..b307e0490a --- /dev/null +++ b/Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/Phix/idiomatically-determine-all-the-lowercase-and-uppercase-letters-1.phix @@ -0,0 +1,10 @@ +with javascript_semantics +sequence lc = {}, uc = {} +for ch=1 to 255 do + if islower(ch) then lc &= ch end if + if isupper(ch) then uc &= ch end if +end for +lc = utf32_to_utf8(lc)&"\n" +uc = utf32_to_utf8(uc)&"\n" +puts(1,lc) +puts(1,uc) diff --git a/Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/Phix/idiomatically-determine-all-the-lowercase-and-uppercase-letters-2.phix b/Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/Phix/idiomatically-determine-all-the-lowercase-and-uppercase-letters-2.phix new file mode 100644 index 0000000000..a2d8ee8e1d --- /dev/null +++ b/Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/Phix/idiomatically-determine-all-the-lowercase-and-uppercase-letters-2.phix @@ -0,0 +1,4 @@ +?tagset('z','a') +?tagstart('a',26) +?tagset('Z','A') +?tagstart('A',26) diff --git a/Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/Phix/idiomatically-determine-all-the-lowercase-and-uppercase-letters.phix b/Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/Phix/idiomatically-determine-all-the-lowercase-and-uppercase-letters.phix deleted file mode 100644 index be7c73650e..0000000000 --- a/Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/Phix/idiomatically-determine-all-the-lowercase-and-uppercase-letters.phix +++ /dev/null @@ -1,11 +0,0 @@ -(phixonline)--> - sequence lc = {}, uc = {} - for ch=1 to 255 do - if islower(ch) then lc &= ch end if - if isupper(ch) then uc &= ch end if - end for - lc = utf32_to_utf8(lc)&"\n" - uc = utf32_to_utf8(uc)&"\n" - puts(1,lc) - puts(1,uc) - loop next position + j 1b + +2: + li t0,'-' # first byte is - ? + bne t5,t0,21f + li t1,1 # negative sign + j 4f # next position +21: + li t0,'+' # first byte is + ? + beq t5,t0,4f # yes -> next position +3: # debut de boucle de traitement des chiffres + li t0,'0' + blt t5,t0,4f # byte is not numeric + li t0,'9' + bgt t5,t0,4f # byte is not numeric + addi t5,t5,-48 + li t0,NUMMAXI + bgt a0,t0,99f # number maxi ? + + mul a0,t2,a0 # multiply by factor 10 + add a0,a0,t5 # and add new byte + +4: + addi t3,t3,1 # next position + add t0,t4,t3 + lbu t5,(t0) # load byte + beq t5,x0,5f # string end -> end + li t0,0x0A + beq t5,t0,5f # string end -> end + j 3b # or loop +5: + beqz t1,100f # positive sign ? + neg a0,a0 # no + j 100f +99: # overflow error + la a0,szMessErrDep + call writeString + li a0,0 # on error return zero +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret + +/************************************/ +/* file include Fonctions */ +/***********************************/ +/* for this file see risc-v task include a file */ +.include "../../includeFunctions.s" diff --git a/Task/Integer-comparison/ReScript/integer-comparison.re b/Task/Integer-comparison/ReScript/integer-comparison.res similarity index 100% rename from Task/Integer-comparison/ReScript/integer-comparison.re rename to Task/Integer-comparison/ReScript/integer-comparison.res diff --git a/Task/Integer-comparison/REBOL/integer-comparison.rebol b/Task/Integer-comparison/Rebol/integer-comparison.rebol similarity index 96% rename from Task/Integer-comparison/REBOL/integer-comparison.rebol rename to Task/Integer-comparison/Rebol/integer-comparison.rebol index 8afe43551e..2f92c6d90e 100644 --- a/Task/Integer-comparison/REBOL/integer-comparison.rebol +++ b/Task/Integer-comparison/Rebol/integer-comparison.rebol @@ -1,4 +1,4 @@ -REBOL [ +Rebol [ Title: "Comparing Two Integers" URL: http://rosettacode.org/wiki/Comparing_two_integers ] diff --git a/Task/Integer-comparison/Rust/integer-comparison.rust b/Task/Integer-comparison/Rust/integer-comparison.rs similarity index 100% rename from Task/Integer-comparison/Rust/integer-comparison.rust rename to Task/Integer-comparison/Rust/integer-comparison.rs diff --git a/Task/Integer-comparison/Rye/integer-comparison.rye b/Task/Integer-comparison/Rye/integer-comparison.rye new file mode 100644 index 0000000000..961dc50523 --- /dev/null +++ b/Task/Integer-comparison/Rye/integer-comparison.rye @@ -0,0 +1,4 @@ +a: integer input "Enter value of a" +b: integer input "Enter value of b" + +cases a { { a < b } { print "Less than" } { a = b } { print "Equal to" } { a > b } { print "Greater than" } } diff --git a/Task/Integer-comparison/Scheme/integer-comparison.ss b/Task/Integer-comparison/Scheme/integer-comparison.scm similarity index 100% rename from Task/Integer-comparison/Scheme/integer-comparison.ss rename to Task/Integer-comparison/Scheme/integer-comparison.scm diff --git a/Task/Integer-comparison/V-(Vlang)/integer-comparison.v b/Task/Integer-comparison/V-(Vlang)/integer-comparison.v new file mode 100644 index 0000000000..cf27fc8509 --- /dev/null +++ b/Task/Integer-comparison/V-(Vlang)/integer-comparison.v @@ -0,0 +1,17 @@ +import os + +fn main(){ + mut enter := "" + mut a, mut b := 0, 0 + enter = os.input("Enter number for a: ") + if enter.is_int() {a = enter.int()} else {println("Invalid input!") exit(1)} + enter = os.input("Enter number for b: ") + if enter.is_int() {b = enter.int()} else {println("Invalid input!") exit(1)} + match true { + a < b {println("${a} less than ${b}")} + a == b {println("${a} equal to ${b}")} + a > b {println("${a} greater than ${b}")} + else{} + } + exit(0) +} diff --git a/Task/Integer-comparison/VBScript/integer-comparison.vb b/Task/Integer-comparison/VBScript/integer-comparison.vbs similarity index 100% rename from Task/Integer-comparison/VBScript/integer-comparison.vb rename to Task/Integer-comparison/VBScript/integer-comparison.vbs diff --git a/Task/Integer-comparison/YAMLScript/integer-comparison.ys b/Task/Integer-comparison/YAMLScript/integer-comparison.ys new file mode 100644 index 0000000000..59b265bd8e --- /dev/null +++ b/Task/Integer-comparison/YAMLScript/integer-comparison.ys @@ -0,0 +1,8 @@ +!YS-v0 + +defn main(x y): + say: + cond: + x < y: "$x is less than $y" + x > y: "$x is greater than $y" + else : "$x is equal to $y" diff --git a/Task/Integer-overflow/ALGOL-M/integer-overflow.alg b/Task/Integer-overflow/ALGOL-M/integer-overflow.alg new file mode 100644 index 0000000000..c285f7d9f2 --- /dev/null +++ b/Task/Integer-overflow/ALGOL-M/integer-overflow.alg @@ -0,0 +1,6 @@ +begin +integer n; +n := 16383; % maximum integer value % +write(n+2); +write(n*2); +end diff --git a/Task/Integer-overflow/Ada/integer-overflow.ada b/Task/Integer-overflow/Ada/integer-overflow.ada deleted file mode 100644 index 1deb7a7c8b..0000000000 --- a/Task/Integer-overflow/Ada/integer-overflow.ada +++ /dev/null @@ -1,51 +0,0 @@ -with Ada.Text_IO; use Ada.Text_IO; - -procedure Overflow is - - generic - type T is Range <>; - Name_Of_T: String; - procedure Print_Bounds; -- first instantiate this with T, Name - -- then call the instantiation - procedure Print_Bounds is - begin - Put_Line(" " & Name_Of_T & " " & T'Image(T'First) - & " .." & T'Image(T'Last)); - end Print_Bounds; - - procedure P_Int is new Print_Bounds(Integer, "Integer "); - procedure P_Nat is new Print_Bounds(Natural, "Natural "); - procedure P_Pos is new Print_Bounds(Positive, "Positive"); - procedure P_Long is new Print_Bounds(Long_Integer, "Long "); - - type Unsigned_Byte is range 0 .. 255; - type Signed_Byte is range -128 .. 127; - type Unsigned_Word is range 0 .. 2**32-1; - type Thousand is range 0 .. 999; - type Signed_Double is range - 2**63 .. 2**63-1; - type Crazy is range -11 .. -3; - - procedure P_UB is new Print_Bounds(Unsigned_Byte, "U 8 "); - procedure P_SB is new Print_Bounds(Signed_Byte, "S 8 "); - procedure P_UW is new Print_Bounds(Unsigned_Word, "U 32 "); - procedure P_Th is new Print_Bounds(Thousand, "Thous"); - procedure P_SD is new Print_Bounds(Signed_Double, "S 64 "); - procedure P_Cr is new Print_Bounds(Crazy, "Crazy"); - - A: Crazy := Crazy'First; - -begin - Put_Line("Predefined Types:"); - P_Int; P_Nat; P_Pos; P_Long; - New_Line; - - Put_Line("Types defined by the user:"); - P_UB; P_SB; P_UW; P_Th; P_SD; P_Cr; - New_Line; - - Put_Line("Forcing a variable of type Crazy to overflow:"); - loop -- endless loop - Put(" " & Crazy'Image(A) & "+1"); - A := A + 1; -- line 49 -- this will later raise a CONSTRAINT_ERROR - end loop; -end Overflow; diff --git a/Task/Integer-overflow/Ada/integer-overflow.adb b/Task/Integer-overflow/Ada/integer-overflow.adb new file mode 100644 index 0000000000..da4fe71c7b --- /dev/null +++ b/Task/Integer-overflow/Ada/integer-overflow.adb @@ -0,0 +1,51 @@ +with Ada.Text_IO; use Ada.Text_IO; + +procedure Overflow is + + generic + type T is Range <>; + Name_Of_T: String; + procedure Print_Bounds; -- first instantiate this with T, Name + -- then call the instantiation + procedure Print_Bounds is + begin + Put_Line(" " & Name_Of_T & " " & T'Image(T'First) + & " .." & T'Image(T'Last)); + end Print_Bounds; + + procedure P_Int is new Print_Bounds(Integer, "Integer "); + procedure P_Nat is new Print_Bounds(Natural, "Natural "); + procedure P_Pos is new Print_Bounds(Positive, "Positive"); + procedure P_Long is new Print_Bounds(Long_Integer, "Long "); + + type Unsigned_Byte is range 0 .. 255; + type Signed_Byte is range -128 .. 127; + type Unsigned_Word is range 0 .. 2**32-1; + type Thousand is range 0 .. 999; + type Signed_Double is range - 2**63 .. 2**63-1; + type Crazy is range -11 .. -3; + + procedure P_UB is new Print_Bounds(Unsigned_Byte, "U 8 "); + procedure P_SB is new Print_Bounds(Signed_Byte, "S 8 "); + procedure P_UW is new Print_Bounds(Unsigned_Word, "U 32 "); + procedure P_Th is new Print_Bounds(Thousand, "Thous"); + procedure P_SD is new Print_Bounds(Signed_Double, "S 64 "); + procedure P_Cr is new Print_Bounds(Crazy, "Crazy"); + + A: Crazy := Crazy'First; + +begin + Put_Line("Predefined Types:"); + P_Int; P_Nat; P_Pos; P_Long; + New_Line; + + Put_Line("Types defined by the user:"); + P_UB; P_SB; P_UW; P_Th; P_SD; P_Cr; + New_Line; + + Put_Line("Forcing a variable of type Crazy to overflow:"); + loop -- endless loop + Put(" " & Crazy'Image(A) & "+1"); + A := A + 1; -- line 49 -- this will later raise a CONSTRAINT_ERROR + end loop; +end Overflow; diff --git a/Task/Integer-overflow/Applesoft-BASIC/integer-overflow-5.basic b/Task/Integer-overflow/Applesoft-BASIC/integer-overflow-5.basic index af3e54154a..342b708226 100644 --- a/Task/Integer-overflow/Applesoft-BASIC/integer-overflow-5.basic +++ b/Task/Integer-overflow/Applesoft-BASIC/integer-overflow-5.basic @@ -1 +1 @@ -A% = -32767 : POKE PEEK(131) + PEEK(132) * 256, 0 : ? A% +A% = -32767 : POKE PEEK(131) + PEEK(132) * 256 + 1, 0 : ? A% diff --git a/Task/Integer-overflow/COBOL/integer-overflow-1.cobol b/Task/Integer-overflow/COBOL/integer-overflow-1.cob similarity index 100% rename from Task/Integer-overflow/COBOL/integer-overflow-1.cobol rename to Task/Integer-overflow/COBOL/integer-overflow-1.cob diff --git a/Task/Integer-overflow/COBOL/integer-overflow-2.cobol b/Task/Integer-overflow/COBOL/integer-overflow-2.cob similarity index 100% rename from Task/Integer-overflow/COBOL/integer-overflow-2.cobol rename to Task/Integer-overflow/COBOL/integer-overflow-2.cob diff --git a/Task/Integer-overflow/Crystal/integer-overflow.cr b/Task/Integer-overflow/Crystal/integer-overflow.cr new file mode 100644 index 0000000000..2a14023b37 --- /dev/null +++ b/Task/Integer-overflow/Crystal/integer-overflow.cr @@ -0,0 +1,38 @@ +macro try (expr) + printf "%-*s # => ", padding, {{expr.stringify}} + begin + puts {{expr}} + rescue ex + puts "Exception: #{ex.message}" + end +end + +padding = 25 +puts "Result does not fit into a 32-bit signed integer:" +try -(-2147483647-1) +try 2000000000 + 2000000000 +try -2147483647 - 2147483647 +try 46341 * 46341 +try (-2147483647-1) // -1 + +padding = 52 +puts "\nResult does not fit into a 64-bit signed integer:" +try -(-9223372036854775807 - 1) +try 5000000000000000000 + 5000000000000000000 +try -9223372036854775807 - 9223372036854775807 +try 3037000500 * 3037000500 +try (-9223372036854775807 - 1) // -1 + +padding = 32 +puts "\nResult does not fit into a 32-bit unsigned integer:" +try -4294967295.to_u32 +try 3000000000_u32 + 3000000000_u32 +try 2147483647_u32 - 4294967295_u32 +try 65537_u32 * 65537_u32 + +padding = 52 +puts "\nResult that does not fit into a 64-bit unsigned integer:" +try -18446744073709551615_i128.to_u64 +try 10000000000000000000_u64 + 10000000000000000000_u64 +try 9223372036854775807_u64 - 18446744073709551615_u64 +try 4294967296_u64 * 4294967296_64 diff --git a/Task/Integer-overflow/Delphi/integer-overflow.delphi b/Task/Integer-overflow/Delphi/integer-overflow.delphi deleted file mode 100644 index 05327d8aee..0000000000 --- a/Task/Integer-overflow/Delphi/integer-overflow.delphi +++ /dev/null @@ -1,123 +0,0 @@ -var IS32: integer; {Signed 32-bit integer} -var IS64: Int64; {Signed 64-bit integer} -var IU32: cardinal; {Unsigned 32-bit integer} - -{============ Signed 32 bit tests ===================================} - -procedure TestSigned32_1; -begin -IS32:=-(-2147483647-1); -end; - -// Compiler: "Overflow in conversion or arithmetic operation" - -procedure TestSigned32_2; -begin -IS32:=2000000000 + 2000000000; -end; - -// Compiler: "Overflow in conversion or arithmetic operation" - - - -procedure TestSigned32_3; -begin -IS32:=-2147483647 - 2147483647; -end; - -// Compiler: "Overflow in conversion or arithmetic operation" - -procedure TestSigned32_4; -begin -IS32:=46341 * 46341; -end; - -// Compiler: "Overflow in conversion or arithmetic operation" - - - -procedure TestSigned32_5; -begin -IS32:=(-2147483647-1) div -1; -end; - -// Compiler: "Overflow in conversion or arithmetic operation" - -{============ Signed 64 bit tests ===================================} - -procedure TestSigned64_1; -begin -IS64:=-(-9223372036854775807-1); -end; - -// Compiler: "Overflow in conversion or arithmetic operation" - - -procedure TestSigned64_2; -begin -IS64:=5000000000000000000+5000000000000000000; -end; - -// Compiler: "Overflow in conversion or arithmetic operation" - - -procedure TestSigned64_3; -begin -IS64:=-9223372036854775807 - 9223372036854775807; -end; - -// Compiler: "Overflow in conversion or arithmetic operation" - - -procedure TestSigned64_4; -begin -IS64:=3037000500 * 3037000500; -end; - -// Compiler: "Overflow in conversion or arithmetic operation" - - -procedure TestSigned64_5; -begin -IS64:=(-9223372036854775807-1) div -1; -end; - -// Compiler: "Overflow in conversion or arithmetic operation" - - -{============ UnSigned 32 bit tests ===================================} - -procedure TestUnSigned32_1; -begin -IU32:=-4294967295; -end; - -// Compiler: "Overflow in conversion or arithmetic operation" - - -procedure TestUnSigned32_2; -begin -IU32:=3000000000 + 3000000000; -end; - -// Compiler: "Overflow in conversion or arithmetic operation" - - -procedure TestUnSigned32_3; -begin -IU32:=2147483647 - 4294967295; -end; - -// Compiler: "Overflow in conversion or arithmetic operation" - - -procedure TestUnSigned32_4; -begin -IU32:=65537 * 65537; -end; - -// Compiler: "Overflow in conversion or arithmetic operation" - - -//Delphi-6 does not have 64-bit unsigned integers. -//Later version have 64-bit unsigned integers. diff --git a/Task/Integer-overflow/Delphi/integer-overflow.pas b/Task/Integer-overflow/Delphi/integer-overflow.pas new file mode 100644 index 0000000000..865888a299 --- /dev/null +++ b/Task/Integer-overflow/Delphi/integer-overflow.pas @@ -0,0 +1,123 @@ +var IS32: integer; {Signed 32-bit integer} +var IS64: Int64; {Signed 64-bit integer} +var IU32: cardinal; {Unsigned 32-bit integer} + +{============ Signed 32 bit tests ===================================} + +procedure TestSigned32_1; +begin +IS32:=-(-2147483647-1); +end; + +// Compiler: "Overflow in conversion or arithmetic operation" + +procedure TestSigned32_2; +begin +IS32:=2000000000 + 2000000000; +end; + +// Compiler: "Overflow in conversion or arithmetic operation" + + + +procedure TestSigned32_3; +begin +IS32:=-2147483647 - 2147483647; +end; + +// Compiler: "Overflow in conversion or arithmetic operation" + +procedure TestSigned32_4; +begin +IS32:=46341 * 46341; +end; + +// Compiler: "Overflow in conversion or arithmetic operation" + + + +procedure TestSigned32_5; +begin +IS32:=(-2147483647-1) div -1; +end; + +// Compiler: "Overflow in conversion or arithmetic operation" + +{============ Signed 64 bit tests ===================================} + +procedure TestSigned64_1; +begin +IS64:=-(-9223372036854775807-1); +end; + +// Compiler: "Overflow in conversion or arithmetic operation" + + +procedure TestSigned64_2; +begin +IS64:=5000000000000000000+5000000000000000000; +end; + +// Compiler: "Overflow in conversion or arithmetic operation" + + +procedure TestSigned64_3; +begin +IS64:=-9223372036854775807 - 9223372036854775807; +end; + +// Compiler: "Overflow in conversion or arithmetic operation" + + +procedure TestSigned64_4; +begin +IS64:=3037000500 * 3037000500; +end; + +// Compiler: "Overflow in conversion or arithmetic operation" + + +procedure TestSigned64_5; +begin +IS64:=(-9223372036854775807-1) div -1; +end; + +// Compiler: "Overflow in conversion or arithmetic operation" + + +{============ UnSigned 32 bit tests ===================================} + +procedure TestUnSigned32_1; +begin +IU32:=-4294967295; +end; + +// Compiler: "Overflow in conversion or arithmetic operation" + + +procedure TestUnSigned32_2; +begin +IU32:=3000000000 + 3000000000; +end; + +// Compiler: "Overflow in conversion or arithmetic operation" + + +procedure TestUnSigned32_3; +begin +IU32:=2147483647 - 4294967295; +end; + +// Compiler: "Overflow in conversion or arithmetic operation" + + +procedure TestUnSigned32_4; +begin +IU32:=65537 * 65537; +end; + +// Compiler: "Overflow in conversion or arithmetic operation" + + +//Delphi-6 does not have 64-bit unsigned integers. +//Later version have 64-bit unsigned integers. diff --git a/Task/Integer-overflow/FutureBasic/integer-overflow.basic b/Task/Integer-overflow/FutureBasic/integer-overflow.basic new file mode 100644 index 0000000000..722195a19e --- /dev/null +++ b/Task/Integer-overflow/FutureBasic/integer-overflow.basic @@ -0,0 +1,17 @@ +include "NSLog.incl" + +NSLog( @"FB Integer ranges:\n" ) + +NSLog( @"UInt64: 0 to %llu", ULLONG_MAX ) +NSLog( @"SInt64: %lld to %lld\n", LLONG_MIN, LLONG_MAX ) + +NSLog( @"UInt32: 0 to %u", UINT_MAX ) +NSLog( @"SInt32: %ld to %ld\n", INT_MIN, INT_MAX ) + +NSLog( @"UInt16: 0 to %hu", USHRT_MAX ) +NSLog( @"SInt16: %hd to %hd\n", SHRT_MIN, SHRT_MAX ) + +NSLog( @"UInt8: 0 to %u", UCHAR_MAX ) +NSLog( @"SInt8: %d to %d", CHAR_MIN, CHAR_MAX ) + +HandleEvents diff --git a/Task/Integer-overflow/Go/integer-overflow.go b/Task/Integer-overflow/Go/integer-overflow.go index 0beb5da9a1..755a63b7f1 100644 --- a/Task/Integer-overflow/Go/integer-overflow.go +++ b/Task/Integer-overflow/Go/integer-overflow.go @@ -3,106 +3,106 @@ package main import "fmt" func main() { - // Go's builtin integer types are: - // int, int8, int16, int32, int64 - // uint, uint8, uint16, uint32, uint64 - // byte, rune, uintptr - // - // int is either 32 or 64 bit, depending on the system - // uintptr is large enough to hold the bit pattern of any pointer - // byte is 8 bits like int8 - // rune is 32 bits like int32 - // - // Overflow and underflow is silent. The math package defines a number - // of constants that can be helpfull, e.g.: - // math.MaxInt64 = 1<<63 - 1 - // math.MinInt64 = -1 << 63 - // math.MaxUint64 = 1<<64 - 1 - // - // The math/big package implements multi-precision - // arithmetic (big numbers). - // - // In all cases assignment from one type to another requires - // an explicit cast, even if the types are otherwise identical - // (e.g. rune and int32 or int and either int32 or int64). - // Casts silently truncate if required. - // - // Invalid: - // var i int = int32(0) - // var r rune = int32(0) - // var b byte = int8(0) - // - // Valid: - var i64 int64 = 42 - var i32 int32 = int32(i64) - var i16 int16 = int16(i64) - var i8 int8 = int8(i16) - var i int = int(i8) - var r rune = rune(i) - var b byte = byte(r) - var u64 uint64 = uint64(b) - var u32 uint32 + // Go's builtin integer types are: + // int, int8, int16, int32, int64 + // uint, uint8, uint16, uint32, uint64 + // byte, rune, uintptr + // + // int is either 32 or 64 bit, depending on the system + // uintptr is large enough to hold the bit pattern of any pointer + // byte is 8 bits like int8 + // rune is 32 bits like int32 + // + // Overflow and underflow is silent. The math package defines a number + // of constants that can be helpfull, e.g.: + // math.MaxInt64 = 1<<63 - 1 + // math.MinInt64 = -1 << 63 + // math.MaxUint64 = 1<<64 - 1 + // + // The math/big package implements multi-precision + // arithmetic (big numbers). + // + // In all cases assignment from one type to another requires + // an explicit cast, even if the types are otherwise identical + // (e.g. rune and int32 or int and either int32 or int64). + // Casts silently truncate if required. + // + // Invalid: + // var i int = int32(0) + // var r rune = int32(0) + // var b byte = int8(0) + // + // Valid: + var i64 int64 = 42 + var i32 int32 = int32(i64) + var i16 int16 = int16(i64) + var i8 int8 = int8(i16) + var i int = int(i8) + var r rune = rune(i) + var b byte = byte(r) + var u64 uint64 = uint64(b) + var u32 uint32 - //const c int = -(-2147483647 - 1) // Compiler error on 32 bit systems, ok on 64 bit - const c = -(-2147483647 - 1) // Allowed even on 32 bit systems, c is untyped - i64 = c - //i32 = c // Compiler error - //i32 = -(-2147483647 - 1) // Compiler error - i32 = -2147483647 - i32 = -(-i32 - 1) - fmt.Println("32 bit signed integers") - fmt.Printf(" -(-2147483647 - 1) = %d, got %d\n", i64, i32) + //const c int = -(-2147483647 - 1) // Compiler error on 32 bit systems, ok on 64 bit + const c = -(-2147483647 - 1) // Allowed even on 32 bit systems, c is untyped + i64 = c + //i32 = c // Compiler error + //i32 = -(-2147483647 - 1) // Compiler error + i32 = -2147483647 + i32 = -(-i32 - 1) + fmt.Println("32 bit signed integers") + fmt.Printf(" -(-2147483647 - 1) = %d, got %d\n", i64, i32) - i64 = 2000000000 + 2000000000 - //i32 = 2000000000 + 2000000000 // Compiler error - i32 = 2000000000 - i32 = i32 + i32 - fmt.Printf(" 2000000000 + 2000000000 = %d, got %d\n", i64, i32) - i64 = -2147483647 - 2147483647 - i32 = 2147483647 - i32 = -i32 - i32 - fmt.Printf(" -2147483647 - 2147483647 = %d, got %d\n", i64, i32) - i64 = 46341 * 46341 - i32 = 46341 - i32 = i32 * i32 - fmt.Printf(" 46341 * 46341 = %d, got %d\n", i64, i32) - i64 = (-2147483647 - 1) / -1 - i32 = -2147483647 - i32 = (i32 - 1) / -1 - fmt.Printf(" (-2147483647-1) / -1 = %d, got %d\n", i64, i32) + i64 = 2000000000 + 2000000000 + //i32 = 2000000000 + 2000000000 // Compiler error + i32 = 2000000000 + i32 = i32 + i32 + fmt.Printf(" 2000000000 + 2000000000 = %d, got %d\n", i64, i32) + i64 = -2147483647 - 2147483647 + i32 = 2147483647 + i32 = -i32 - i32 + fmt.Printf(" -2147483647 - 2147483647 = %d, got %d\n", i64, i32) + i64 = 46341 * 46341 + i32 = 46341 + i32 = i32 * i32 + fmt.Printf(" 46341 * 46341 = %d, got %d\n", i64, i32) + i64 = (-2147483647 - 1) / -1 + i32 = -2147483647 + i32 = (i32 - 1) / -1 + fmt.Printf(" (-2147483647-1) / -1 = %d, got %d\n", i64, i32) - fmt.Println("\n64 bit signed integers") - i64 = -9223372036854775807 - fmt.Printf(" -(%d - 1): %d\n", i64, -(i64 - 1)) - i64 = 5000000000000000000 - fmt.Printf(" %d + %d: %d\n", i64, i64, i64+i64) - i64 = 9223372036854775807 - fmt.Printf(" -%d - %d: %d\n", i64, i64, -i64-i64) - i64 = 3037000500 - fmt.Printf(" %d * %d: %d\n", i64, i64, i64*i64) - i64 = -9223372036854775807 - fmt.Printf(" (%d - 1) / -1: %d\n", i64, (i64-1)/-1) + fmt.Println("\n64 bit signed integers") + i64 = -9223372036854775807 + fmt.Printf(" -(%d - 1): %d\n", i64, -(i64 - 1)) + i64 = 5000000000000000000 + fmt.Printf(" %d + %d: %d\n", i64, i64, i64+i64) + i64 = 9223372036854775807 + fmt.Printf(" -%d - %d: %d\n", i64, i64, -i64-i64) + i64 = 3037000500 + fmt.Printf(" %d * %d: %d\n", i64, i64, i64*i64) + i64 = -9223372036854775807 + fmt.Printf(" (%d - 1) / -1: %d\n", i64, (i64-1)/-1) - fmt.Println("\n32 bit unsigned integers:") - //u32 = -4294967295 // Compiler error - u32 = 4294967295 - fmt.Printf(" -%d: %d\n", u32, -u32) - u32 = 3000000000 - fmt.Printf(" %d + %d: %d\n", u32, u32, u32+u32) - a := uint32(2147483647) - u32 = 4294967295 - fmt.Printf(" %d - %d: %d\n", a, u32, a-u32) - u32 = 65537 - fmt.Printf(" %d * %d: %d\n", u32, u32, u32*u32) + fmt.Println("\n32 bit unsigned integers:") + //u32 = -4294967295 // Compiler error + u32 = 4294967295 + fmt.Printf(" -%d: %d\n", u32, -u32) + u32 = 3000000000 + fmt.Printf(" %d + %d: %d\n", u32, u32, u32+u32) + a := uint32(2147483647) + u32 = 4294967295 + fmt.Printf(" %d - %d: %d\n", a, u32, a-u32) + u32 = 65537 + fmt.Printf(" %d * %d: %d\n", u32, u32, u32*u32) - fmt.Println("\n64 bit unsigned integers:") - u64 = 18446744073709551615 - fmt.Printf(" -%d: %d\n", u64, -u64) - u64 = 10000000000000000000 - fmt.Printf(" %d + %d: %d\n", u64, u64, u64+u64) - aa := uint64(9223372036854775807) - u64 = 18446744073709551615 - fmt.Printf(" %d - %d: %d\n", aa, u64, aa-u64) - u64 = 4294967296 - fmt.Printf(" %d * %d: %d\n", u64, u64, u64*u64) + fmt.Println("\n64 bit unsigned integers:") + u64 = 18446744073709551615 + fmt.Printf(" -%d: %d\n", u64, -u64) + u64 = 10000000000000000000 + fmt.Printf(" %d + %d: %d\n", u64, u64, u64+u64) + aa := uint64(9223372036854775807) + u64 = 18446744073709551615 + fmt.Printf(" %d - %d: %d\n", aa, u64, aa-u64) + u64 = 4294967296 + fmt.Printf(" %d * %d: %d\n", u64, u64, u64*u64) } diff --git a/Task/Integer-overflow/Java/integer-overflow-2.java b/Task/Integer-overflow/Java/integer-overflow-2.java index adc00033b5..f67ad7136d 100644 --- a/Task/Integer-overflow/Java/integer-overflow-2.java +++ b/Task/Integer-overflow/Java/integer-overflow-2.java @@ -1,16 +1,16 @@ public final class IntegerOverflow { - public static void main(String[] args) { - // The following examples show that Java allows integer overflow without warning - // and calculates an incorrect result. - - // From version 8, Java introduced methods which throw an ArithmeticException when overflow occurs, + public static void main(String[] args) { + // The following examples show that Java allows integer overflow without warning + // and calculates an incorrect result. + + // From version 8, Java introduced methods which throw an ArithmeticException when overflow occurs, // which prevents the calculation of an incorrect result. It also allows the programmer to replace an "int" // with a "long" and to replace a "long" with a BigInteger. - - // Uncomment the lines below to see the use of the new methods: - // addExact(), subtractExact(), multiplyExact() and negateExact(). - System.out.println("Signed 32-bit:"); + + // Uncomment the lines below to see the use of the new methods: + // addExact(), subtractExact(), multiplyExact() and negateExact(). + System.out.println("Signed 32-bit:"); System.out.println(-(-2_147_483_647 - 1)); // System.out.println(Math.negateExact(-2_147_483_647 - 1)); @@ -42,6 +42,6 @@ public final class IntegerOverflow { System.out.println((-9_223_372_036_854_775_807L - 1) / -1); // System.out.println(Math.negateExact(Math.subtractExact(-9_223_372_036_854_775_807L, 1) / 1)); - } + } } diff --git a/Task/Integer-overflow/Jq/integer-overflow.jq b/Task/Integer-overflow/Jq/integer-overflow.jq index b74f2de480..b61ca08e1f 100644 --- a/Task/Integer-overflow/Jq/integer-overflow.jq +++ b/Task/Integer-overflow/Jq/integer-overflow.jq @@ -10,16 +10,16 @@ def compare: [ -(-2147483647-1),"2147483648"], [2000000000 + 2000000000, "4000000000"], -[-2147483647 - 2147483647, "-4294967294"], -[46341 * 46341, "2147488281"], -[(-2147483647-1) / -1, "2147483648"], +[-2147483647 - 2147483647, "-4294967294"], +[46341 * 46341, "2147488281"], +[(-2147483647-1) / -1, "2147483648"], "For 64-bit signed integers:", -[-(-9223372036854775807-1), "9223372036854775808"], -[5000000000000000000+5000000000000000000, "10000000000000000000"], -[-9223372036854775807 - 9223372036854775807, "-18446744073709551614"], -[3037000500 * 3037000500, "9223372037000250000"], +[-(-9223372036854775807-1), "9223372036854775808"], +[5000000000000000000+5000000000000000000, "10000000000000000000"], +[-9223372036854775807 - 9223372036854775807, "-18446744073709551614"], +[3037000500 * 3037000500, "9223372037000250000"], [(-9223372036854775807-1) / -1, "9223372036854775808"], "For 32-bit unsigned integers:", diff --git a/Task/Integer-overflow/Julia/integer-overflow-1.julia b/Task/Integer-overflow/Julia/integer-overflow-1.jl similarity index 100% rename from Task/Integer-overflow/Julia/integer-overflow-1.julia rename to Task/Integer-overflow/Julia/integer-overflow-1.jl diff --git a/Task/Integer-overflow/Julia/integer-overflow-2.julia b/Task/Integer-overflow/Julia/integer-overflow-2.jl similarity index 100% rename from Task/Integer-overflow/Julia/integer-overflow-2.julia rename to Task/Integer-overflow/Julia/integer-overflow-2.jl diff --git a/Task/Integer-overflow/Kotlin/integer-overflow.kotlin b/Task/Integer-overflow/Kotlin/integer-overflow.kts similarity index 100% rename from Task/Integer-overflow/Kotlin/integer-overflow.kotlin rename to Task/Integer-overflow/Kotlin/integer-overflow.kts diff --git a/Task/Integer-overflow/Ksh/integer-overflow.ksh b/Task/Integer-overflow/Ksh/integer-overflow.ksh index 94d4d6dedf..a88605d4e4 100644 --- a/Task/Integer-overflow/Ksh/integer-overflow.ksh +++ b/Task/Integer-overflow/Ksh/integer-overflow.ksh @@ -2,7 +2,7 @@ # Integer overflow -# # Variables: +# # Variables: # typeset -si SHORT_INT typeset -i INTEGER diff --git a/Task/Integer-overflow/PL-I-80/integer-overflow.pli b/Task/Integer-overflow/PL-I-80/integer-overflow.pli new file mode 100644 index 0000000000..1e873986b5 --- /dev/null +++ b/Task/Integer-overflow/PL-I-80/integer-overflow.pli @@ -0,0 +1,6 @@ +overflow_demo: proc options (main); + dcl n fixed bin; + n = 32767; + put skip list (n+2); + put skip list (n*2); +end overflow_demo; diff --git a/Task/Integer-overflow/Pluto/integer-overflow.pluto b/Task/Integer-overflow/Pluto/integer-overflow.pluto new file mode 100644 index 0000000000..a8af75f375 --- /dev/null +++ b/Task/Integer-overflow/Pluto/integer-overflow.pluto @@ -0,0 +1,7 @@ +local expressions = { + -(-9223372036854775807 - 1), + 5000000000000000000 + 5000000000000000000, + -9223372036854775807 - 9223372036854775807 +} + +for expressions as expr do print(expr) end diff --git a/Task/Integer-overflow/PowerShell/integer-overflow.ps1 b/Task/Integer-overflow/PowerShell/integer-overflow.ps1 new file mode 100644 index 0000000000..86bbd55c7f --- /dev/null +++ b/Task/Integer-overflow/PowerShell/integer-overflow.ps1 @@ -0,0 +1,30 @@ +try { + # All of these raise an exception, which is caught below. + # The try block is aborted after the first exception, + # so the subsequent lines are never executed. + + [int32] (-(-2147483647-1)) + [int32] (2000000000 + 2000000000) + [int32] (-2147483647 - 2147483647) + [int32] (46341 * 46341) + [int32] ((-2147483647-1) / -1) + + [int64] (-(-9223372036854775807-1)) + [int64] (5000000000000000000+5000000000000000000) + [int64] (-9223372036854775807 - 9223372036854775807) + [int64] (3037000500 * 3037000500) + [int64] ((-9223372036854775807-1) / -1) + + [uint32] (-4294967295) + [uint32] (3000000000 + 3000000000) + [uint32] (2147483647 - 4294967295) + [uint32] (65537 * 65537) + + [uint64] (-18446744073709551615) + [uint64] (10000000000000000000 + 10000000000000000000) + [uint64] (9223372036854775807 - 18446744073709551615) + [uint64] (4294967296 * 4294967296) +} +catch { + $Error.Exception +} diff --git a/Task/Integer-overflow/PowerShell/integer-overflow.psh b/Task/Integer-overflow/PowerShell/integer-overflow.psh deleted file mode 100644 index 48524e2b56..0000000000 --- a/Task/Integer-overflow/PowerShell/integer-overflow.psh +++ /dev/null @@ -1,30 +0,0 @@ -try { - # All of these raise an exception, which is caught below. - # The try block is aborted after the first exception, - # so the subsequent lines are never executed. - - [int32] (-(-2147483647-1)) - [int32] (2000000000 + 2000000000) - [int32] (-2147483647 - 2147483647) - [int32] (46341 * 46341) - [int32] ((-2147483647-1) / -1) - - [int64] (-(-9223372036854775807-1)) - [int64] (5000000000000000000+5000000000000000000) - [int64] (-9223372036854775807 - 9223372036854775807) - [int64] (3037000500 * 3037000500) - [int64] ((-9223372036854775807-1) / -1) - - [uint32] (-4294967295) - [uint32] (3000000000 + 3000000000) - [uint32] (2147483647 - 4294967295) - [uint32] (65537 * 65537) - - [uint64] (-18446744073709551615) - [uint64] (10000000000000000000 + 10000000000000000000) - [uint64] (9223372036854775807 - 18446744073709551615) - [uint64] (4294967296 * 4294967296) -} -catch { - $Error.Exception -} diff --git a/Task/Integer-overflow/Python/integer-overflow-1.py b/Task/Integer-overflow/Python/integer-overflow-1.py index b31607a136..0627deacc4 100644 --- a/Task/Integer-overflow/Python/integer-overflow-1.py +++ b/Task/Integer-overflow/Python/integer-overflow-1.py @@ -5,11 +5,11 @@ Type "copyright", "credits" or "license()" for more information. -2147483647 - 2147483647 46341 * 46341 (-2147483647-1) / -1'''.split('\n'): - ans = eval(calc) - print('Expression: %r evaluates to %s of type %s' - % (calc.strip(), ans, type(ans))) + ans = eval(calc) + print('Expression: %r evaluates to %s of type %s' + % (calc.strip(), ans, type(ans))) + - Expression: '-(-2147483647-1)' evaluates to 2147483648 of type Expression: '2000000000 + 2000000000' evaluates to 4000000000 of type Expression: '-2147483647 - 2147483647' evaluates to -4294967294 of type diff --git a/Task/Integer-overflow/Python/integer-overflow-2.py b/Task/Integer-overflow/Python/integer-overflow-2.py index ce1671d160..1da7b38e6f 100644 --- a/Task/Integer-overflow/Python/integer-overflow-2.py +++ b/Task/Integer-overflow/Python/integer-overflow-2.py @@ -5,11 +5,11 @@ Type "copyright", "credits" or "license()" for more information. -2147483647 - 2147483647 46341 * 46341 (-2147483647-1) / -1'''.split('\n'): - ans = eval(calc) - print('Expression: %r evaluates to %s of type %s' - % (calc.strip(), ans, type(ans))) + ans = eval(calc) + print('Expression: %r evaluates to %s of type %s' + % (calc.strip(), ans, type(ans))) + - Expression: '-(-2147483647-1)' evaluates to 2147483648 of type Expression: '2000000000 + 2000000000' evaluates to 4000000000 of type Expression: '-2147483647 - 2147483647' evaluates to -4294967294 of type diff --git a/Task/Integer-overflow/R/integer-overflow.r b/Task/Integer-overflow/R/integer-overflow.r new file mode 100644 index 0000000000..ff8070a2d2 --- /dev/null +++ b/Task/Integer-overflow/R/integer-overflow.r @@ -0,0 +1,2 @@ +46341*46341L +46341L*46341L diff --git a/Task/Integer-overflow/Rebol/integer-overflow.rebol b/Task/Integer-overflow/Rebol/integer-overflow.rebol new file mode 100644 index 0000000000..ec032950ee --- /dev/null +++ b/Task/Integer-overflow/Rebol/integer-overflow.rebol @@ -0,0 +1,33 @@ +Rebol [ + title: "Rosetta code: Integer overflow" + file: %Integer_overflow.r3 + url: https://rosettacode.org/wiki/Integer_overflow +] + +foreach expr [ + ;; For 32-bit signed integers: + [negate (-2147483647 - 1) ] + [2000000000 + 2000000000 ] + [-2147483647 - 2147483647 ] + [46341 * 46341 ] + [(-2147483647 - 1) / -1 ] + ;; For 64-bit signed integers: + [negate (-9223372036854775807 - 1) ] + [5000000000000000000 + 5000000000000000000 ] + [-9223372036854775807 - 9223372036854775807] + [3037000500 * 3037000500 ] + [(-9223372036854775807 - 1) / -1 ] + ;; For 32-bit unsigned integers: + [-4294967295 ] + [3000000000 + 3000000000 ] + [2147483647 - 4294967295 ] + [65537 * 65537 ] + ;; For 64-bit unsigned integers: + [transcode "-18446744073709551615" ] + [transcode " 10000000000000000000" ] + [transcode " 18446744073709551615" ] + [4294967296 * 4294967296 ] +][ + prin [pad mold/only expr 44 ";== "] + print either error? res: try expr [as-red reform [res/type res/id]][res] +] diff --git a/Task/Integer-overflow/Rust/integer-overflow-1.rust b/Task/Integer-overflow/Rust/integer-overflow-1.rs similarity index 100% rename from Task/Integer-overflow/Rust/integer-overflow-1.rust rename to Task/Integer-overflow/Rust/integer-overflow-1.rs diff --git a/Task/Integer-overflow/Rust/integer-overflow-2.rust b/Task/Integer-overflow/Rust/integer-overflow-2.rs similarity index 100% rename from Task/Integer-overflow/Rust/integer-overflow-2.rust rename to Task/Integer-overflow/Rust/integer-overflow-2.rs diff --git a/Task/Integer-overflow/S-BASIC/integer-overflow.basic b/Task/Integer-overflow/S-BASIC/integer-overflow.basic new file mode 100644 index 0000000000..2bd1b5aa2c --- /dev/null +++ b/Task/Integer-overflow/S-BASIC/integer-overflow.basic @@ -0,0 +1,5 @@ +var n = integer +n = 32767 rem - maximum integer value +print n+2 +print n*2 +end diff --git a/Task/Integer-overflow/VBScript/integer-overflow.vb b/Task/Integer-overflow/VBScript/integer-overflow.vb deleted file mode 100644 index fc10958150..0000000000 --- a/Task/Integer-overflow/VBScript/integer-overflow.vb +++ /dev/null @@ -1,14 +0,0 @@ -'Binary Integer overflow - vbs -i=(-2147483647-1)/-1 -wscript.echo i -i0=32767 '=32767 Integer (Fixed) type=2 -i1=2147483647 '=2147483647 Long (Fixed) type=3 -i2=-(-2147483647-1) '=2147483648 Double (Float) type=5 -wscript.echo Cstr(i0) & " : " & typename(i0) & " , " & vartype(i0) & vbcrlf _ - & Cstr(i1) & " : " & typename(i1) & " , " & vartype(i1) & vbcrlf _ - & Cstr(i2) & " : " & typename(i2) & " , " & vartype(i2) -ii=2147483648-2147483647 -if vartype(ii)<>3 or vartype(ii)<>2 then wscript.echo "Integer overflow type=" & typename(ii) -i1=1000000000000000-1 '1E+15-1 -i2=i1+1 '1E+15 -wscript.echo Cstr(i1) & " , " & Cstr(i2) diff --git a/Task/Integer-overflow/VBScript/integer-overflow.vbs b/Task/Integer-overflow/VBScript/integer-overflow.vbs new file mode 100644 index 0000000000..2aef204024 --- /dev/null +++ b/Task/Integer-overflow/VBScript/integer-overflow.vbs @@ -0,0 +1,14 @@ +'Binary Integer overflow - vbs +i=(-2147483647-1)/-1 +wscript.echo i +i0=32767 '=32767 Integer (Fixed) type=2 +i1=2147483647 '=2147483647 Long (Fixed) type=3 +i2=-(-2147483647-1) '=2147483648 Double (Float) type=5 +wscript.echo Cstr(i0) & " : " & typename(i0) & " , " & vartype(i0) & vbcrlf _ + & Cstr(i1) & " : " & typename(i1) & " , " & vartype(i1) & vbcrlf _ + & Cstr(i2) & " : " & typename(i2) & " , " & vartype(i2) +ii=2147483648-2147483647 +if vartype(ii)<>3 or vartype(ii)<>2 then wscript.echo "Integer overflow type=" & typename(ii) +i1=1000000000000000-1 '1E+15-1 +i2=i1+1 '1E+15 +wscript.echo Cstr(i1) & " , " & Cstr(i2) diff --git a/Task/Integer-overflow/YAMLScript/integer-overflow.ys b/Task/Integer-overflow/YAMLScript/integer-overflow.ys new file mode 100644 index 0000000000..d7618a29d2 --- /dev/null +++ b/Task/Integer-overflow/YAMLScript/integer-overflow.ys @@ -0,0 +1,14 @@ +!YS-v0 + +tests =: | + -9223372036854775807.-- * -1 + 5000000000000000000 + 5000000000000000000 + -9223372036854775807 - 9223372036854775807 + 3037000500 * 3037000500 + +each test tests:lines: + say: test + try: + eval: test + catch e: + say: "$e\n" diff --git a/Task/Integer-sequence/Ada/integer-sequence-1.ada b/Task/Integer-sequence/Ada/integer-sequence-1.adb similarity index 100% rename from Task/Integer-sequence/Ada/integer-sequence-1.ada rename to Task/Integer-sequence/Ada/integer-sequence-1.adb diff --git a/Task/Integer-sequence/Ada/integer-sequence-2.ada b/Task/Integer-sequence/Ada/integer-sequence-2.adb similarity index 100% rename from Task/Integer-sequence/Ada/integer-sequence-2.ada rename to Task/Integer-sequence/Ada/integer-sequence-2.adb diff --git a/Task/Integer-sequence/ArkScript/integer-sequence-1.ark b/Task/Integer-sequence/ArkScript/integer-sequence-1.ark new file mode 100644 index 0000000000..3292a2f31d --- /dev/null +++ b/Task/Integer-sequence/ArkScript/integer-sequence-1.ark @@ -0,0 +1,4 @@ +(mut i 0) +(while true { + (print i) + (set i (+ 1 i)) }) diff --git a/Task/Integer-sequence/ArkScript/integer-sequence-2.ark b/Task/Integer-sequence/ArkScript/integer-sequence-2.ark new file mode 100644 index 0000000000..99a3156c43 --- /dev/null +++ b/Task/Integer-sequence/ArkScript/integer-sequence-2.ark @@ -0,0 +1,5 @@ +(let loop (fun (i) { + (print i) + (loop (+ i 1)) })) + +(loop 0) diff --git a/Task/Integer-sequence/Ballerina/integer-sequence.ballerina b/Task/Integer-sequence/Ballerina/integer-sequence.ballerina new file mode 100644 index 0000000000..ac60f4738e --- /dev/null +++ b/Task/Integer-sequence/Ballerina/integer-sequence.ballerina @@ -0,0 +1,9 @@ +import ballerina/io; + +public function main() { + int a = 1; + while true { + io:println(a); + a += 1; + } +} diff --git a/Task/Integer-sequence/COBOL/integer-sequence.cobol b/Task/Integer-sequence/COBOL/integer-sequence.cob similarity index 100% rename from Task/Integer-sequence/COBOL/integer-sequence.cobol rename to Task/Integer-sequence/COBOL/integer-sequence.cob diff --git a/Task/Integer-sequence/Crystal/integer-sequence.crystal b/Task/Integer-sequence/Crystal/integer-sequence.cr similarity index 100% rename from Task/Integer-sequence/Crystal/integer-sequence.crystal rename to Task/Integer-sequence/Crystal/integer-sequence.cr diff --git a/Task/Integer-sequence/Delphi/integer-sequence.delphi b/Task/Integer-sequence/Delphi/integer-sequence.pas similarity index 100% rename from Task/Integer-sequence/Delphi/integer-sequence.delphi rename to Task/Integer-sequence/Delphi/integer-sequence.pas diff --git a/Task/Integer-sequence/EasyLang/integer-sequence.easy b/Task/Integer-sequence/EasyLang/integer-sequence.easy index ff87b9eebc..8891f16bc4 100644 --- a/Task/Integer-sequence/EasyLang/integer-sequence.easy +++ b/Task/Integer-sequence/EasyLang/integer-sequence.easy @@ -1,10 +1,10 @@ max = pow 2 53 repeat print i - if i = 10 + if i = 5 print "." print "." - i = max - 10 + i = max - 6 . until i = max i += 1 diff --git a/Task/Integer-sequence/Elena/integer-sequence.elena b/Task/Integer-sequence/Elena/integer-sequence.elena index 2294d76879..6e18d53cf6 100644 --- a/Task/Integer-sequence/Elena/integer-sequence.elena +++ b/Task/Integer-sequence/Elena/integer-sequence.elena @@ -1,11 +1,11 @@ import extensions; -public program() +public Program() { var i := 0u; while (true) { - console.printLine(i); + Console.printLine(i); i += 1u } diff --git a/Task/Integer-sequence/Elixir/integer-sequence.elixir b/Task/Integer-sequence/Elixir/integer-sequence.ex similarity index 100% rename from Task/Integer-sequence/Elixir/integer-sequence.elixir rename to Task/Integer-sequence/Elixir/integer-sequence.ex diff --git a/Task/Integer-sequence/Emacs-Lisp/integer-sequence.l b/Task/Integer-sequence/Emacs-Lisp/integer-sequence.el similarity index 100% rename from Task/Integer-sequence/Emacs-Lisp/integer-sequence.l rename to Task/Integer-sequence/Emacs-Lisp/integer-sequence.el diff --git a/Task/Integer-sequence/Euphoria/integer-sequence.euphoria b/Task/Integer-sequence/Euphoria/integer-sequence.eu similarity index 100% rename from Task/Integer-sequence/Euphoria/integer-sequence.euphoria rename to Task/Integer-sequence/Euphoria/integer-sequence.eu diff --git a/Task/Integer-sequence/Gleam/integer-sequence.gleam b/Task/Integer-sequence/Gleam/integer-sequence.gleam new file mode 100644 index 0000000000..36185b1127 --- /dev/null +++ b/Task/Integer-sequence/Gleam/integer-sequence.gleam @@ -0,0 +1,11 @@ +import gleam/int +import gleam/io + +pub fn main() { + count_forever(from: 1) +} + +pub fn count_forever(from n: Int) -> Nil { + n |> int.to_string |> io.println + count_forever(n + 1) +} diff --git a/Task/Integer-sequence/Julia/integer-sequence.julia b/Task/Integer-sequence/Julia/integer-sequence.jl similarity index 100% rename from Task/Integer-sequence/Julia/integer-sequence.julia rename to Task/Integer-sequence/Julia/integer-sequence.jl diff --git a/Task/Integer-sequence/Kotlin/integer-sequence.kotlin b/Task/Integer-sequence/Kotlin/integer-sequence.kotlin deleted file mode 100644 index 72fec53d9d..0000000000 --- a/Task/Integer-sequence/Kotlin/integer-sequence.kotlin +++ /dev/null @@ -1,15 +0,0 @@ -import java.math.BigInteger - -// version 1.0.5-2 - -fun main(args: Array) { - // print until 2147483647 - (0..Int.MAX_VALUE).forEach { println(it) } - - // print forever - var n = BigInteger.ZERO - while (true) { - println(n) - n += BigInteger.ONE - } -} diff --git a/Task/Integer-sequence/Kotlin/integer-sequence.kts b/Task/Integer-sequence/Kotlin/integer-sequence.kts new file mode 100644 index 0000000000..b9260df8b4 --- /dev/null +++ b/Task/Integer-sequence/Kotlin/integer-sequence.kts @@ -0,0 +1,10 @@ +import java.math.BigInteger + +fun main() { + // Using a 64-bit unsigned type, print until 18446744073709551615 + (1uL..ULong.MAX_VALUE).forEach { println(it) } + + // Using unlimited-size integers, print forever + var n = BigInteger.ONE + while (true) println(n++) +} diff --git a/Task/Integer-sequence/Nu/integer-sequence.nu b/Task/Integer-sequence/Nu/integer-sequence.nu new file mode 100644 index 0000000000..230e385c07 --- /dev/null +++ b/Task/Integer-sequence/Nu/integer-sequence.nu @@ -0,0 +1 @@ +for n in 1.. { print $n } diff --git a/Task/Integer-sequence/OCaml/integer-sequence-1.ocaml b/Task/Integer-sequence/OCaml/integer-sequence-1.ml similarity index 100% rename from Task/Integer-sequence/OCaml/integer-sequence-1.ocaml rename to Task/Integer-sequence/OCaml/integer-sequence-1.ml diff --git a/Task/Integer-sequence/OCaml/integer-sequence-2.ocaml b/Task/Integer-sequence/OCaml/integer-sequence-2.ml similarity index 100% rename from Task/Integer-sequence/OCaml/integer-sequence-2.ocaml rename to Task/Integer-sequence/OCaml/integer-sequence-2.ml diff --git a/Task/Integer-sequence/PascalABC.NET/integer-sequence.pas b/Task/Integer-sequence/PascalABC.NET/integer-sequence-1.pas similarity index 100% rename from Task/Integer-sequence/PascalABC.NET/integer-sequence.pas rename to Task/Integer-sequence/PascalABC.NET/integer-sequence-1.pas diff --git a/Task/Integer-sequence/PascalABC.NET/integer-sequence-2.pas b/Task/Integer-sequence/PascalABC.NET/integer-sequence-2.pas new file mode 100644 index 0000000000..7b206716fb --- /dev/null +++ b/Task/Integer-sequence/PascalABC.NET/integer-sequence-2.pas @@ -0,0 +1 @@ +## 1.Step.Print diff --git a/Task/Integer-sequence/PowerShell/integer-sequence.psh b/Task/Integer-sequence/PowerShell/integer-sequence.ps1 similarity index 100% rename from Task/Integer-sequence/PowerShell/integer-sequence.psh rename to Task/Integer-sequence/PowerShell/integer-sequence.ps1 diff --git a/Task/Integer-sequence/Rust/integer-sequence-1.rust b/Task/Integer-sequence/Rust/integer-sequence-1.rs similarity index 100% rename from Task/Integer-sequence/Rust/integer-sequence-1.rust rename to Task/Integer-sequence/Rust/integer-sequence-1.rs diff --git a/Task/Integer-sequence/Rust/integer-sequence-2.rust b/Task/Integer-sequence/Rust/integer-sequence-2.rs similarity index 100% rename from Task/Integer-sequence/Rust/integer-sequence-2.rust rename to Task/Integer-sequence/Rust/integer-sequence-2.rs diff --git a/Task/Integer-sequence/Scheme/integer-sequence.ss b/Task/Integer-sequence/Scheme/integer-sequence.scm similarity index 100% rename from Task/Integer-sequence/Scheme/integer-sequence.ss rename to Task/Integer-sequence/Scheme/integer-sequence.scm diff --git a/Task/Integer-sequence/Uiua/integer-sequence.uiua b/Task/Integer-sequence/Uiua/integer-sequence.uiua new file mode 100644 index 0000000000..008b417081 --- /dev/null +++ b/Task/Integer-sequence/Uiua/integer-sequence.uiua @@ -0,0 +1 @@ +⍢(&p.+1)1 1 diff --git a/Task/Integer-sequence/Uxntal/integer-sequence.uxnatl b/Task/Integer-sequence/Uxntal/integer-sequence.uxnatl new file mode 100644 index 0000000000..fdc8e1419c --- /dev/null +++ b/Task/Integer-sequence/Uxntal/integer-sequence.uxnatl @@ -0,0 +1,23 @@ +%comma { [ LIT2 ", -Console/write ] DEO } +%space { [ LIT2 20 -Console/write ] DEO } + +|18 @Console/write + +|100 + +#0001 +&loop + DUP2 print/dec comma space + INC2 !&loop + +BRK + +@print/dec ( short* -- ) + #000a SWP2 [ LITr ff ] + &get + SWP2k DIV2k MUL2 SUB2 STH + POP OVR2 DIV2 ORAk ?&get + POP2 POP2 + &put + STHr INCk ?{ POP JMP2r } + [ LIT "0 ] ADD .Console/write DEO !&put diff --git a/Task/Integer-sequence/Zig/integer-sequence.zig b/Task/Integer-sequence/Zig/integer-sequence.zig new file mode 100644 index 0000000000..b3e6c9abd9 --- /dev/null +++ b/Task/Integer-sequence/Zig/integer-sequence.zig @@ -0,0 +1,9 @@ +const stdout = @import("std").io.getStdOut().writer(); + +pub fn main() !void { + var i: u128 = 1; + + while (true) : (i += 1) { + try stdout.print("{}, ", .{i}); + } +} diff --git a/Task/Interactive-programming-repl-/AWK/interactive-programming-repl-.awk b/Task/Interactive-programming-repl-/AWK/interactive-programming-repl-.awk new file mode 100644 index 0000000000..af020ed818 --- /dev/null +++ b/Task/Interactive-programming-repl-/AWK/interactive-programming-repl-.awk @@ -0,0 +1,4 @@ +GAWK -f CON +BEGIN { print(f("Rosetta","Code",":")) } +function f(s1,s2,s3) { return(s1 s3 s3 s2) } +^Z <-- CTRL-Z diff --git a/Task/Interactive-programming-repl-/Crystal/interactive-programming-repl-.cr b/Task/Interactive-programming-repl-/Crystal/interactive-programming-repl-.cr new file mode 100644 index 0000000000..17ba1deb2d --- /dev/null +++ b/Task/Interactive-programming-repl-/Crystal/interactive-programming-repl-.cr @@ -0,0 +1,11 @@ +> crystal i +Crystal interpreter 1.15.1 [89944bf] (2025-02-04). +EXPERIMENTAL SOFTWARE: if you find a bug, please consider opening an issue in +https://github.com/crystal-lang/crystal/issues/new/ +icr:1> def f(s1, s2, sep) +icr:2> s1 + sep + sep + s2 +icr:3> end + => nil +icr:4> f "Rosetta", "Code", ":" + => "Rosetta::Code" +icr:5> diff --git a/Task/Interactive-programming-repl-/Elena/interactive-programming-repl-.elena b/Task/Interactive-programming-repl-/Elena/interactive-programming-repl-.elena index a63c7afea7..473d529309 100644 --- a/Task/Interactive-programming-repl-/Elena/interactive-programming-repl-.elena +++ b/Task/Interactive-programming-repl-/Elena/interactive-programming-repl-.elena @@ -1,17 +1,29 @@ c:\Alex\ELENA\bin>elt-cli -ELENA command line VM terminal 6.0.7 (C)2021-23 by Aleksey Rakov -ELENA VM 6.0.25 (C)2022-2023 by Aleksey Rakov +ELENA command line VM terminal 6.9.6 (C)2021-25 by Aleksey Rakov +Loading repl template +Loading multiline template +Loading get_var template +Loading set_var template +ELENA VM 6.9.14 (32-bit) (C)2022-2025 by Aleksey Rakov, ELENA-LANG Org Initializing... --q - quit --c - clear --h - help --l - execute a script from file --p diff --git a/Task/Knapsack-problem-Bounded/Jq/knapsack-problem-bounded.jq b/Task/Knapsack-problem-Bounded/Jq/knapsack-problem-bounded.jq index 04b7a10255..6fc98c8c26 100644 --- a/Task/Knapsack-problem-Bounded/Jq/knapsack-problem-bounded.jq +++ b/Task/Knapsack-problem-Bounded/Jq/knapsack-problem-bounded.jq @@ -34,14 +34,14 @@ def knapsack($w): | reduce range(1; $n+1) as $i (.; reduce range (0; $w + 1) as $j (.; .m[$i][$j] = .m[$i-1][$j] - | label $out + | label $out | foreach (range(1; 1 + ((items[$i - 1].count))), null) as $k (.stop = false; - if $k == null then . - elif ($k * items[$i - 1].weight > $j) then .stop = true + if $k == null then . + elif ($k * items[$i - 1].weight > $j) then .stop = true else (.m[$i - 1][$j - ($k * items[$i - 1].weight)] + $k * items[$i - 1].value) as $v | if $v > .m[$i][$j] then .m[$i][$j] = $v else . end - end; - if .stop or ($k == null) then ., break $out else empty end) + end; + if .stop or ($k == null) then ., break $out else empty end) ) ) | .s = ($n|list(0)) | .j = $w @@ -78,9 +78,9 @@ def task(maxWeight): | .sumNumber += .number | .sumWeight += .weight | .sumValue += .value - | .emit += [[.name, .weight, .value, .number]] - else . - end ) + | .emit += [[.name, .weight, .value, .number]] + else . + end ) | (.emit[] | f), "---------------------- ------ ----- ------", f("Items chosen \(.itemCount|lpad(4))"; .sumWeight; .sumValue; .sumNumber) ); diff --git a/Task/Knapsack-problem-Bounded/Julia/knapsack-problem-bounded-1.julia b/Task/Knapsack-problem-Bounded/Julia/knapsack-problem-bounded-1.jl similarity index 100% rename from Task/Knapsack-problem-Bounded/Julia/knapsack-problem-bounded-1.julia rename to Task/Knapsack-problem-Bounded/Julia/knapsack-problem-bounded-1.jl diff --git a/Task/Knapsack-problem-Bounded/Julia/knapsack-problem-bounded-2.julia b/Task/Knapsack-problem-Bounded/Julia/knapsack-problem-bounded-2.jl similarity index 100% rename from Task/Knapsack-problem-Bounded/Julia/knapsack-problem-bounded-2.julia rename to Task/Knapsack-problem-Bounded/Julia/knapsack-problem-bounded-2.jl diff --git a/Task/Knapsack-problem-Bounded/Kotlin/knapsack-problem-bounded.kotlin b/Task/Knapsack-problem-Bounded/Kotlin/knapsack-problem-bounded.kts similarity index 100% rename from Task/Knapsack-problem-Bounded/Kotlin/knapsack-problem-bounded.kotlin rename to Task/Knapsack-problem-Bounded/Kotlin/knapsack-problem-bounded.kts diff --git a/Task/Knapsack-problem-Bounded/Lua/knapsack-problem-bounded.lua b/Task/Knapsack-problem-Bounded/Lua/knapsack-problem-bounded.lua new file mode 100644 index 0000000000..2e3fe2d181 --- /dev/null +++ b/Task/Knapsack-problem-Bounded/Lua/knapsack-problem-bounded.lua @@ -0,0 +1,180 @@ +#!/usr/bin/env lua + +--- knapsack packing for max value under wieght limit + + -- A: use value/weight score as pre-sort + -- B: initial run with no items excluded + -- C: try combos excluding each item for best value + + +--- table of tables +-- {name weight value quantity wt/val } +items = { + {"map", 9, 150, 1}, + {"compass", 13, 35, 1}, + {"water", 153, 200, 2}, + {"sandwich", 50, 60, 2}, + {"glucose", 15, 60, 2}, + {"tin", 68, 45, 3}, + {"banana", 27, 60, 3}, + {"apple", 39, 40, 3}, + {"cheese", 23, 30, 1}, + {"beer", 52, 10, 3}, + {"suntan cream", 11, 70, 1}, + {"camera", 32, 30, 1}, + {"t-shirt", 24, 15, 2}, + {"trousers", 48, 10, 2}, + {"umbrella", 73, 40, 1}, + {"waterproof trousers", 42, 70, 1}, + {"waterproof overclothes", 43, 75, 1}, + {"note-case", 22, 80, 1}, + {"sunglasses", 7, 20, 1}, + {"towel", 18, 12, 2}, + {"socks", 4, 50, 1}, + {"book", 30, 10, 2}, +} + +-- for output +function print_as_sack(its) + if its == nil then return end + + -- format columns + -- [20 |8 |8 |8 ] + local head_fmt = "%-20s\t%-8s\t%-8s\t%-8s" + local data_fmt = "%-20s\t%-8d\t%-8d\t%-8d" + + local head_table = + string.format(head_fmt, "item", "weight", "value", "quantity") + + io.write(head_table, "\n") + line = string.rep("-" , 64) + io.write(line, "\n") + + for n=1,#its do + it = its[n] + local name,wt,val,q = table.unpack(it) + + local fmt_table = + string.format(data_fmt, name, wt, val, q) + io.write(fmt_table, "\n") + end + io.write(line, "\n") +end + +-- calc value:weight ratio +function append_wv (its) + + for index, it in pairs(its) do + local name,wt,val,q = table.unpack(it) + wv = val / wt + it[#it+1] = wv -- append + end +end + +-- sort by 5th item of each table entry +function sort_by_wv (its) + -- sorts decreasing + local wv_sorter = function(a,b) return a[5] > b[5] end + table.sort(its, wv_sorter) +end + +-- pack sorted by v:w ratio +-- all or none per item +function add_up (its, max, excl) + + local sack_items = {} + local sack = {} + local this_weight = 0 + local this_value = 0 + + for i = 1,#its do + it = its[i] + + -- is same table? + -- lua has no continue keyword + if it == excl then goto continue end + + -- unpack into vars + local name,wt,val,q,wv = table.unpack(it) + local count = 0 + local w = 0 + for j = 1, q do + local t_wt = wt +this_weight + if t_wt < max then + this_value = this_value + val + this_weight = t_wt + count = count + 1 + end + end + + if this_weight >= max then break end + + if count > 0 then + _s = {name, count} + table.insert (sack, _s) + end + + ::continue:: --skip item, continue + end -- for items + + -- go through chosen sack + -- make sack of items + for s = 1,#sack do + local s_item = sack[s] + local s_name,s_count = table.unpack(s_item) + + for j = 1,#its do + local it = its[j] + local iname = it[1] + if iname == s_name then + it[4] = s_count + table.insert(sack_items, it) + end -- if + end -- for j + end -- for sack + + -- update best + if this_value > best_value then + best_value = this_value + best_weight = this_weight + best_sack = sack_items + end +end -- function add_up + +-- Main execution +if debug.getinfo(1).what == "main" then + + max_weight = 400 + best_weight = 0 + best_value = 0 + best_sack = {} + + start = os.clock() + + append_wv(items) -- add weight/value + + sort_by_wv(items) -- sort by wv + + add_up(items, max_weight, {}) -- first try + + -- with each item excluded + for i = 1, #items do + add_up(items, max_weight, items[i]) + end + + stop = os.clock() + + time = stop - start -- seconds + + usec_time = time * 1e6 --microseconds + + + -- output + print_as_sack(best_sack) + print ("value:\t", best_value) + print("weight:\t", best_weight) + print("time:\t" , usec_time , " usec") + + os.exit(0) +end +-- end diff --git a/Task/Knapsack-problem-Bounded/Mathprog/knapsack-problem-bounded.math b/Task/Knapsack-problem-Bounded/Mathprog/knapsack-problem-bounded.math index 05bb2a0711..5682363639 100644 --- a/Task/Knapsack-problem-Bounded/Mathprog/knapsack-problem-bounded.math +++ b/Task/Knapsack-problem-Bounded/Mathprog/knapsack-problem-bounded.math @@ -19,28 +19,28 @@ maximize knap_value: sum{t in Items} take[t] * value[t]; data; param : Items : weight value quantity := - map 9 150 1 - compass 13 35 1 - water 153 200 2 - sandwich 50 60 2 - glucose 15 60 2 - tin 68 45 3 - banana 27 60 3 - apple 39 40 3 - cheese 23 30 1 - beer 52 10 3 - suntancream 11 70 1 - camera 32 30 1 - T-shirt 24 15 2 - trousers 48 10 2 - umbrella 73 40 1 - w-trousers 42 70 1 - w-overclothes 43 75 1 - note-case 22 80 1 - sunglasses 7 20 1 - towel 18 12 2 - socks 4 50 1 - book 30 10 2 + map 9 150 1 + compass 13 35 1 + water 153 200 2 + sandwich 50 60 2 + glucose 15 60 2 + tin 68 45 3 + banana 27 60 3 + apple 39 40 3 + cheese 23 30 1 + beer 52 10 3 + suntancream 11 70 1 + camera 32 30 1 + T-shirt 24 15 2 + trousers 48 10 2 + umbrella 73 40 1 + w-trousers 42 70 1 + w-overclothes 43 75 1 + note-case 22 80 1 + sunglasses 7 20 1 + towel 18 12 2 + socks 4 50 1 + book 30 10 2 ; end; diff --git a/Task/Knapsack-problem-Bounded/OxygenBasic/knapsack-problem-bounded.basic b/Task/Knapsack-problem-Bounded/OxygenBasic/knapsack-problem-bounded.basic index 15844fcf3d..138abfbf1e 100644 --- a/Task/Knapsack-problem-Bounded/OxygenBasic/knapsack-problem-bounded.basic +++ b/Task/Knapsack-problem-Bounded/OxygenBasic/knapsack-problem-bounded.basic @@ -7,7 +7,7 @@ sys items=22 it=> -"map", 9, 150, 0, +"map", 9, 150, 0, "compass", 13, 35, 0, "water", 153, 200, 0, "sandwich", 50, 160, 0, @@ -94,17 +94,17 @@ pr+=cr "Weight: " dmax+xs 'putfile "s.txt",pr print pr 'Knapsack contents: -'map 9 150 -'compass 13 35 -'water 153 200 -'sandwich 50 160 -'glucose 15 60 -'banana 27 60 -'suntan cream 11 70 -'waterproof trousers 42 70 -'waterproof overclothes 43 75 -'note-case 22 80 -'sunglasses 7 20 -'socks 4 50 +'map 9 150 +'compass 13 35 +'water 153 200 +'sandwich 50 160 +'glucose 15 60 +'banana 27 60 +'suntan cream 11 70 +'waterproof trousers 42 70 +'waterproof overclothes 43 75 +'note-case 22 80 +'sunglasses 7 20 +'socks 4 50 ' 'Weight: 396 diff --git a/Task/Knapsack-problem-Bounded/Oz/knapsack-problem-bounded.oz b/Task/Knapsack-problem-Bounded/Oz/knapsack-problem-bounded.oz index 3193b21041..52edf54cd0 100644 --- a/Task/Knapsack-problem-Bounded/Oz/knapsack-problem-bounded.oz +++ b/Task/Knapsack-problem-Bounded/Oz/knapsack-problem-bounded.oz @@ -60,7 +60,7 @@ in {Record.forAllInd Best proc {$ I V} if V > 0 then - {System.showInfo I#": "#V} + {System.showInfo I#": "#V} end end } diff --git a/Task/Knapsack-problem-Bounded/Perl/knapsack-problem-bounded.pl b/Task/Knapsack-problem-Bounded/Perl/knapsack-problem-bounded.pl index eb911e52b5..95667635d9 100644 --- a/Task/Knapsack-problem-Bounded/Perl/knapsack-problem-bounded.pl +++ b/Task/Knapsack-problem-Bounded/Perl/knapsack-problem-bounded.pl @@ -3,71 +3,71 @@ use strict; my $raw = <<'TABLE'; -map 9 150 1 -compass 13 35 1 -water 153 200 2 +map 9 150 1 +compass 13 35 1 +water 153 200 2 sandwich 50 60 2 -glucose 15 60 2 -tin 68 45 3 -banana 27 60 3 -apple 39 40 3 -cheese 23 30 1 -beer 52 10 1 +glucose 15 60 2 +tin 68 45 3 +banana 27 60 3 +apple 39 40 3 +cheese 23 30 1 +beer 52 10 1 suntancream 11 70 1 -camera 32 30 1 -T-shirt 24 15 2 +camera 32 30 1 +T-shirt 24 15 2 trousers 48 10 2 umbrella 73 40 1 -w_trousers 42 70 1 -w_overcoat 43 75 1 +w_trousers 42 70 1 +w_overcoat 43 75 1 note-case 22 80 1 sunglasses 7 20 1 -towel 18 12 2 -socks 4 50 1 -book 30 10 2 +towel 18 12 2 +socks 4 50 1 +book 30 10 2 TABLE my @items; for (split "\n", $raw) { my @x = split /\s+/; - push @items, { - name => $x[0], - weight => $x[1], - value => $x[2], - quant => $x[3], - } + push @items, { + name => $x[0], + weight => $x[1], + value => $x[2], + quant => $x[3], + } } my $max_weight = 400; my %cache; sub pick { - my ($weight, $pos) = @_; - if ($pos < 0 or $weight <= 0) { - return 0, 0, [] - } + my ($weight, $pos) = @_; + if ($pos < 0 or $weight <= 0) { + return 0, 0, [] + } - @{ $cache{$weight, $pos} //= [do{ # odd construct: for caching - my $item = $items[$pos]; - my ($bv, $bi, $bw, $bp) = (0, 0, 0, []); + @{ $cache{$weight, $pos} //= [do{ # odd construct: for caching + my $item = $items[$pos]; + my ($bv, $bi, $bw, $bp) = (0, 0, 0, []); - for my $i (0 .. $item->{quant}) { - last if $i * $item->{weight} > $weight; - my ($v, $w, $p) = pick($weight - $i * $item->{weight}, $pos - 1); - next if ($v += $i * $item->{value}) <= $bv; + for my $i (0 .. $item->{quant}) { + last if $i * $item->{weight} > $weight; + my ($v, $w, $p) = pick($weight - $i * $item->{weight}, $pos - 1); + next if ($v += $i * $item->{value}) <= $bv; - ($bv, $bi, $bw, $bp) = ($v, $i, $w, $p); - } + ($bv, $bi, $bw, $bp) = ($v, $i, $w, $p); + } - my @picked = ( @$bp, $bi ); - $bv, $bw + $bi * $item->{weight}, \@picked - }]} + my @picked = ( @$bp, $bi ); + $bv, $bw + $bi * $item->{weight}, \@picked + }]} } my ($v, $w, $p) = pick($max_weight, $#items); for (0 .. $#$p) { - if ($p->[$_] > 0) { - print "$p->[$_] of $items[$_]{name}\n"; - } + if ($p->[$_] > 0) { + print "$p->[$_] of $items[$_]{name}\n"; + } } print "Value: $v; Weight: $w\n"; diff --git a/Task/Knapsack-problem-Bounded/Pluto/knapsack-problem-bounded.pluto b/Task/Knapsack-problem-Bounded/Pluto/knapsack-problem-bounded.pluto new file mode 100644 index 0000000000..95d15a1227 --- /dev/null +++ b/Task/Knapsack-problem-Bounded/Pluto/knapsack-problem-bounded.pluto @@ -0,0 +1,85 @@ +require "table2" +local fmt = require "fmt" + +class item + function __construct(public name, public weight, public value, public count) + end +end + +local items = { + new item("map", 9, 150, 1), + new item("compass", 13, 35, 1), + new item("water", 153, 200, 2), + new item("sandwich", 50, 60, 2), + new item("glucose", 15, 60, 2), + new item("tin", 68, 45, 3), + new item("banana", 27, 60, 3), + new item("apple", 39, 40, 3), + new item("cheese", 23, 30, 1), + new item("beer", 52, 10, 3), + new item("suntan cream", 11, 70, 1), + new item("camera", 32, 30, 1), + new item("T-shirt", 24, 15, 2), + new item("trousers", 48, 10, 2), + new item("umbrella", 73, 40, 1), + new item("waterproof trousers", 42, 70, 1), + new item("waterproof overclothes", 43, 75, 1), + new item("note-case", 22, 80, 1), + new item("sunglasses", 7, 20, 1), + new item("towel", 18, 12, 2), + new item("socks", 4, 50, 1), + new item("book", 30, 10, 2) +} + +local n = #items +local max_weight = 400 + +local function knapsack(w) + local m = table.create(n + 1) + for i = 0, n do m[i + 1] = table.rep(w + 1, 0) end + for i = 1, n do + for j = 0, w do + m[i + 1][j + 1] = m[i][j + 1] + for k = 1, items[i].count do + if k * items[i].weight > j then break end + local v = m[i][j - k * items[i].weight + 1] + k * items[i].value + if v > m[i + 1][j + 1] then m[i + 1][j + 1] = v end + end + end + end + local s = table.rep(n, 0) + local j = w + for i = n, 1, -1 do + local v = m[i + 1][j + 1] + local k = 0 + while v != m[i][j + 1] + k * items[i].value do + s[i] += 1 + j -= items[i].weight + k += 1 + end + end + return s +end + +local s = knapsack(max_weight) +print("Item Chosen Weight Value Number") +print("--------------------- ------ ----- ------") +local item_count = 0 +local sum_weight = 0 +local sum_value = 0 +local sum_number = 0 +for i = 1, n do + if s[i] != 0 then + item_count += 1 + local name = items[i].name + local number = s[i] + local weight = items[i].weight * number + local value = items[i].value * number + sum_number += number + sum_weight += weight + sum_value += value + fmt.print("%-22s %3d %4d %2d", name, weight, value, number) + end +end +print("--------------------- ------ ----- ------") +fmt.print("Items chosen %d %3d %4d %2d", item_count, sum_weight, sum_value, sum_number) diff --git a/Task/Knapsack-problem-Bounded/Prolog/knapsack-problem-bounded-1.pro b/Task/Knapsack-problem-Bounded/Prolog/knapsack-problem-bounded-1.pro index 5714b6c15d..f32a25a31a 100644 --- a/Task/Knapsack-problem-Bounded/Prolog/knapsack-problem-bounded-1.pro +++ b/Task/Knapsack-problem-Bounded/Prolog/knapsack-problem-bounded-1.pro @@ -2,75 +2,75 @@ % tuples (name, weights, value, nb pieces). knapsack :- - L = [( map, 9, 150, 1), - ( compass, 13, 35, 1), - ( water, 153, 200, 2), - ( sandwich, 50, 60, 2), - ( glucose, 15, 60, 2), - ( tin, 68, 45, 3), - ( banana, 27, 60, 3), - ( apple, 39, 40, 3), - ( cheese, 23, 30, 1), - ( beer, 52, 10, 3), - ( 'suntan cream', 11, 70, 1), - ( camera, 32, 30, 1), - ( 'T-shirt', 24, 15, 2), - ( trousers, 48, 10, 2), - ( umbrella, 73, 40, 1), - ( 'waterproof trousers', 42, 70, 1), - ( 'waterproof overclothes', 43, 75, 1), - ( 'note-case', 22, 80, 1), - ( sunglasses, 7, 20, 1), - ( towel, 18, 12, 2), - ( socks, 4, 50, 1), - ( book, 30, 10, 2)], + L = [( map, 9, 150, 1), + ( compass, 13, 35, 1), + ( water, 153, 200, 2), + ( sandwich, 50, 60, 2), + ( glucose, 15, 60, 2), + ( tin, 68, 45, 3), + ( banana, 27, 60, 3), + ( apple, 39, 40, 3), + ( cheese, 23, 30, 1), + ( beer, 52, 10, 3), + ( 'suntan cream', 11, 70, 1), + ( camera, 32, 30, 1), + ( 'T-shirt', 24, 15, 2), + ( trousers, 48, 10, 2), + ( umbrella, 73, 40, 1), + ( 'waterproof trousers', 42, 70, 1), + ( 'waterproof overclothes', 43, 75, 1), + ( 'note-case', 22, 80, 1), + ( sunglasses, 7, 20, 1), + ( towel, 18, 12, 2), + ( socks, 4, 50, 1), + ( book, 30, 10, 2)], - % Takes is the list of the numbers of each items - % these numbers are between 0 and the 4th value of the tuples of the items + % Takes is the list of the numbers of each items + % these numbers are between 0 and the 4th value of the tuples of the items maplist(collect, L, Ws, Vs, Takes), scalar_product(Ws, Takes, #=<, 400), scalar_product(Vs, Takes, #=, VM), - % to have statistics on the resolution of the problem. - time(labeling([max(VM), down], Takes)), + % to have statistics on the resolution of the problem. + time(labeling([max(VM), down], Takes)), scalar_product(Ws, Takes, #=, WM), - %% displayinf of the results. - compute_lenword(L, 0, Len), - sformat(A1, '~~w~~t~~~w|', [Len]), - sformat(A2, '~~t~~w~~~w|', [4]), - sformat(A3, '~~t~~w~~~w|', [5]), - print_results(A1,A2,A3, L, Takes, WM, VM). + %% displayinf of the results. + compute_lenword(L, 0, Len), + sformat(A1, '~~w~~t~~~w|', [Len]), + sformat(A2, '~~t~~w~~~w|', [4]), + sformat(A3, '~~t~~w~~~w|', [5]), + print_results(A1,A2,A3, L, Takes, WM, VM). collect((_, W, V, N), W, V, Take) :- - Take in 0..N. + Take in 0..N. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % compute_lenword([], N, N). compute_lenword([(Name, _, _, _)|T], N, NF):- - atom_length(Name, L), - ( L > N -> N1 = L; N1 = N), - compute_lenword(T, N1, NF). + atom_length(Name, L), + ( L > N -> N1 = L; N1 = N), + compute_lenword(T, N1, NF). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % print_results(A1,A2,A3, [], [], WM, WR) :- - sformat(W0, '~w ', [' ']), - sformat(W1, A1, [' ']), - sformat(W2, A2, [WM]), - sformat(W3, A3, [WR]), - format('~w~w~w~w~n', [W0,W1,W2,W3]). + sformat(W0, '~w ', [' ']), + sformat(W1, A1, [' ']), + sformat(W2, A2, [WM]), + sformat(W3, A3, [WR]), + format('~w~w~w~w~n', [W0,W1,W2,W3]). print_results(A1,A2,A3, [_H|T], [0|TR], WM, VM) :- - !, - print_results(A1,A2,A3, T, TR, WM, VM). + !, + print_results(A1,A2,A3, T, TR, WM, VM). print_results(A1, A2, A3, [(Name, W, V, _)|T], [N|TR], WM, VM) :- - sformat(W0, '~w ', [N]), - sformat(W1, A1, [Name]), - sformat(W2, A2, [W]), - sformat(W3, A3, [V]), - format('~w~w~w~w~n', [W0,W1,W2,W3]), - print_results(A1, A2, A3, T, TR, WM, VM). + sformat(W0, '~w ', [N]), + sformat(W1, A1, [Name]), + sformat(W2, A2, [W]), + sformat(W3, A3, [V]), + format('~w~w~w~w~n', [W0,W1,W2,W3]), + print_results(A1, A2, A3, T, TR, WM, VM). diff --git a/Task/Knapsack-problem-Bounded/Prolog/knapsack-problem-bounded-2.pro b/Task/Knapsack-problem-Bounded/Prolog/knapsack-problem-bounded-2.pro index 4ec9567be3..0d054c4f81 100644 --- a/Task/Knapsack-problem-Bounded/Prolog/knapsack-problem-bounded-2.pro +++ b/Task/Knapsack-problem-Bounded/Prolog/knapsack-problem-bounded-2.pro @@ -1,51 +1,51 @@ :- use_module(library(simplex)). % tuples (name, weights, value, pieces). knapsack :- - L = [(map, 9, 150, 1), - ( compass, 13, 35, 1), - ( water, 153, 200, 2), - ( sandwich, 50, 60, 2), - ( glucose, 15, 60, 2), - ( tin, 68, 45, 3), - ( banana, 27, 60, 3), - ( apple, 39, 40, 3), - ( cheese, 23, 30, 1), - ( beer, 52, 10, 3), - ( 'suntan cream', 11, 70, 1), - ( camera, 32, 30, 1), - ( 'T-shirt', 24, 15, 2), - ( trousers, 48, 10, 2), - ( umbrella, 73, 40, 1), - ( 'waterproof trousers', 42, 70, 1), - ( 'waterproof overclothes', 43, 75, 1), - ( 'note-case', 22, 80, 1), - ( sunglasses, 7, 20, 1), - ( towel, 18, 12, 2), - ( socks, 4, 50, 1), - ( book, 30, 10, 2)], + L = [(map, 9, 150, 1), + ( compass, 13, 35, 1), + ( water, 153, 200, 2), + ( sandwich, 50, 60, 2), + ( glucose, 15, 60, 2), + ( tin, 68, 45, 3), + ( banana, 27, 60, 3), + ( apple, 39, 40, 3), + ( cheese, 23, 30, 1), + ( beer, 52, 10, 3), + ( 'suntan cream', 11, 70, 1), + ( camera, 32, 30, 1), + ( 'T-shirt', 24, 15, 2), + ( trousers, 48, 10, 2), + ( umbrella, 73, 40, 1), + ( 'waterproof trousers', 42, 70, 1), + ( 'waterproof overclothes', 43, 75, 1), + ( 'note-case', 22, 80, 1), + ( sunglasses, 7, 20, 1), + ( towel, 18, 12, 2), + ( socks, 4, 50, 1), + ( book, 30, 10, 2)], - gen_state(S0), - length(L, N), - numlist(1, N, LN), - time(( create_constraint_N(LN, L, S0, S1), - maplist(create_constraint_WV, LN, L, LW, LV), - constraint(LW =< 400, S1, S2), - maximize(LV, S2, S3) - )), - compute_lenword(L, 0, Len), - sformat(A1, '~~w~~t~~~w|', [Len]), - sformat(A2, '~~t~~w~~~w|', [4]), - sformat(A3, '~~t~~w~~~w|', [5]), - print_results(S3, A1,A2,A3, L, LN, 0, 0). + gen_state(S0), + length(L, N), + numlist(1, N, LN), + time(( create_constraint_N(LN, L, S0, S1), + maplist(create_constraint_WV, LN, L, LW, LV), + constraint(LW =< 400, S1, S2), + maximize(LV, S2, S3) + )), + compute_lenword(L, 0, Len), + sformat(A1, '~~w~~t~~~w|', [Len]), + sformat(A2, '~~t~~w~~~w|', [4]), + sformat(A3, '~~t~~w~~~w|', [5]), + print_results(S3, A1,A2,A3, L, LN, 0, 0). create_constraint_N([], [], S, S). create_constraint_N([HN|TN], [(_, _, _, Nb) | TL], S1, SF) :- - constraint(integral(x(HN)), S1, S2), - constraint([x(HN)] =< Nb, S2, S3), - constraint([x(HN)] >= 0, S3, S4), - create_constraint_N(TN, TL, S4, SF). + constraint(integral(x(HN)), S1, S2), + constraint([x(HN)] =< Nb, S2, S3), + constraint([x(HN)] >= 0, S3, S4), + create_constraint_N(TN, TL, S4, SF). create_constraint_WV(N, (_, W, V, _), W * x(N), V * x(N)). @@ -53,28 +53,28 @@ create_constraint_WV(N, (_, W, V, _), W * x(N), V * x(N)). % compute_lenword([], N, N). compute_lenword([(Name, _, _, _)|T], N, NF):- - atom_length(Name, L), - ( L > N -> N1 = L; N1 = N), - compute_lenword(T, N1, NF). + atom_length(Name, L), + ( L > N -> N1 = L; N1 = N), + compute_lenword(T, N1, NF). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % print_results(_S, A1, A2, A3, [], [], WM, VM) :- - sformat(W0, '~w ', [' ']), - sformat(W1, A1, [' ']), - sformat(W2, A2, [WM]), - sformat(W3, A3, [VM]), - format('~w~w~w~w~n', [W0, W1,W2,W3]). + sformat(W0, '~w ', [' ']), + sformat(W1, A1, [' ']), + sformat(W2, A2, [WM]), + sformat(W3, A3, [VM]), + format('~w~w~w~w~n', [W0, W1,W2,W3]). print_results(S, A1, A2, A3, [(Name, W, V,_)|T], [N|TN], W1, V1) :- - variable_value(S, x(N), X), - ( X = 0 -> W1 = W2, V1 = V2 - ; sformat(S0, '~w ', [X]), - sformat(S1, A1, [Name]), - sformat(S2, A2, [W]), - sformat(S3, A3, [V]), - format('~w~w~w~w~n', [S0, S1,S2,S3]), - W2 is W1 + X * W, - V2 is V1 + X * V), - print_results(S, A1, A2, A3, T, TN, W2, V2). + variable_value(S, x(N), X), + ( X = 0 -> W1 = W2, V1 = V2 + ; sformat(S0, '~w ', [X]), + sformat(S1, A1, [Name]), + sformat(S2, A2, [W]), + sformat(S3, A3, [V]), + format('~w~w~w~w~n', [S0, S1,S2,S3]), + W2 is W1 + X * W, + V2 is V1 + X * V), + print_results(S, A1, A2, A3, T, TN, W2, V2). diff --git a/Task/Knapsack-problem-Bounded/Python/knapsack-problem-bounded-3.py b/Task/Knapsack-problem-Bounded/Python/knapsack-problem-bounded-3.py index 56e98df45d..6d1ed2ff63 100644 --- a/Task/Knapsack-problem-Bounded/Python/knapsack-problem-bounded-3.py +++ b/Task/Knapsack-problem-Bounded/Python/knapsack-problem-bounded-3.py @@ -1,26 +1,26 @@ items = { - "sandwich": (50, 60, 2), - "map": (9, 150, 1), - "compass": (13, 35, 1), - "water": (153, 200, 3), - "glucose": (15, 60, 2), - "tin": (68, 45, 3), - "banana": (27, 60, 3), - "apple": (39, 40, 3), - "cheese": (23, 30, 1), - "beer": (52, 10, 3), - "suntan cream": (11, 70, 1), - "camera": (32, 30, 1), - "t-shirt": (24, 15, 2), - "trousers": (48, 10, 2), - "umbrella": (73, 40, 1), - "w-trousers": (42, 70, 1), - "w-overcoat": (43, 75, 1), - "note-case": (22, 80, 1), - "sunglasses": (7, 20, 1), - "towel": (18, 12, 2), - "socks": (4, 50, 1), - "book": (30, 10, 2), + "sandwich": (50, 60, 2), + "map": (9, 150, 1), + "compass": (13, 35, 1), + "water": (153, 200, 3), + "glucose": (15, 60, 2), + "tin": (68, 45, 3), + "banana": (27, 60, 3), + "apple": (39, 40, 3), + "cheese": (23, 30, 1), + "beer": (52, 10, 3), + "suntan cream": (11, 70, 1), + "camera": (32, 30, 1), + "t-shirt": (24, 15, 2), + "trousers": (48, 10, 2), + "umbrella": (73, 40, 1), + "w-trousers": (42, 70, 1), + "w-overcoat": (43, 75, 1), + "note-case": (22, 80, 1), + "sunglasses": (7, 20, 1), + "towel": (18, 12, 2), + "socks": (4, 50, 1), + "book": (30, 10, 2), } item_keys = list(items.keys()) diff --git a/Task/Knapsack-problem-Bounded/Rebol/knapsack-problem-bounded.rebol b/Task/Knapsack-problem-Bounded/Rebol/knapsack-problem-bounded.rebol new file mode 100644 index 0000000000..616c92d02e --- /dev/null +++ b/Task/Knapsack-problem-Bounded/Rebol/knapsack-problem-bounded.rebol @@ -0,0 +1,112 @@ +Rebol [ + title: "Rosetta code: Knapsack problem/Bounded" + file: %Knapsack_problem-Bounded.r3 + url: https://rosettacode.org/wiki/Knapsack_problem/Bounded +] + +solve-knapsack: function/with [ + "Solves the bounded knapsack problem via top-down dynamic programming." + limit [integer!] "remaining weight capacity" + pos [integer!] "current item index (0-based)" +][ + ;; Returns a 3-element block [value weight taken] where `taken` is a + ;; block of per-item counts (parallel to `items`) representing the + ;; optimal selection, or none if nothing fits. + + ;; Results are memoised in `cache` keyed by "limit,pos" so each + ;; sub-problem is solved at most once. + + if any [pos < 0 limit <= 0] [ ;; base case: no items or no capacity + return reduce [0 0 none] + ] + + key-str: rejoin [limit "," pos] + if cached: cache/:key-str [ return cached ] ;; memoisation hit + + item: items/(pos + 1) ;; [name weight value max-qty] + best-value: 0 + best-weight: 0 + best-count: 0 + best-taken: none + + taken: 0 + while [all [taken * item/2 <= limit taken <= item/4]] [ ;; try 0..max-qty copies + sub: solve-knapsack (limit - (taken * item/2)) (pos - 1) ;; best for remaining items + sub-value: sub/1 + sub-weight: sub/2 + sub-taken: sub/3 + candidate-value: sub-value + (taken * item/3) + if candidate-value > best-value [ ;; keep best combination found so far + best-value: candidate-value + best-weight: sub-weight + best-count: taken + best-taken: sub-taken + ] + ++ taken + ] + + if best-count > 0 [ + new-taken: make block! num-items ;; copy before mutating to avoid aliasing cached entries + repeat k num-items [append new-taken 0] + if block? best-taken [ + repeat k num-items [new-taken/:k: best-taken/:k] + ] + new-taken/(pos + 1): best-count ;; record how many of this item we take + best-weight: best-weight + (best-count * item/2) + best-taken: new-taken + ] + + result: reduce [best-value best-weight best-taken] + cache/(key-str): result ;; store [value weight taken-counts] in memo + result +][ + cache: make map! 2000 ;; memoisation table, shared across calls +] + +items: [ + ["map" 9 150 1] + ["compass" 13 35 1] + ["water" 153 200 2] + ["sandwich" 50 60 2] + ["glucose" 15 60 2] + ["tin" 68 45 3] + ["banana" 27 60 3] + ["apple" 39 40 3] + ["cheese" 23 30 1] + ["beer" 52 10 3] + ["suntancream" 11 70 1] + ["camera" 32 30 1] + ["T-shirt" 24 15 2] + ["trousers" 48 10 2] + ["umbrella" 73 40 1] + ["w-trousers" 42 70 1] + ["w-overclothes" 43 75 1] + ["note-case" 22 80 1] + ["sunglasses" 7 20 1] + ["towel" 18 12 2] + ["socks" 4 50 1] + ["book" 30 10 2] +] +item-name: func [item] [item/1] +item-weight: func [item] [item/2] +item-value: func [item] [item/3] +item-limit: func [item] [item/4] + +num-items: length? items +result: solve-knapsack 400 (num-items - 1) + +total-value: result/1 +total-weight: result/2 +taken: result/3 + +print "Taking:" +if block? taken [ + repeat i num-items [ + count: pick taken i + if count > 0 [ + item: pick items i + print [" " count "of" item-limit item " " item-name item] + ] + ] +] +print ajoin ["Value: " total-value "; weight: " total-weight] diff --git a/Task/Knapsack-problem-Bounded/Rust/knapsack-problem-bounded.rs b/Task/Knapsack-problem-Bounded/Rust/knapsack-problem-bounded.rs new file mode 100644 index 0000000000..14d93d6108 --- /dev/null +++ b/Task/Knapsack-problem-Bounded/Rust/knapsack-problem-bounded.rs @@ -0,0 +1,99 @@ +use std::collections::HashMap; + +fn main() { + let max_wt = 400; + + let grouped_items = vec![ + ("map", 9, 150, 1), + ("compass", 13, 35, 1), + ("water", 153, 200, 3), + ("sandwich", 50, 60, 2), + ("glucose", 15, 60, 2), + ("tin", 68, 45, 3), + ("banana", 27, 60, 3), + ("apple", 39, 40, 3), + ("cheese", 23, 30, 1), + ("beer", 52, 10, 3), + ("suntan cream", 11, 70, 1), + ("camera", 32, 30, 1), + ("t-shirt", 24, 15, 2), + ("trousers", 48, 10, 2), + ("umbrella", 73, 40, 1), + ("waterproof trousers", 42, 70, 1), + ("waterproof overclothes", 43, 75, 1), + ("note-case", 22, 80, 1), + ("sunglasses", 7, 20, 1), + ("towel", 18, 12, 2), + ("socks", 4, 50, 1), + ("book", 30, 10, 2), + ]; + + let mut items = Vec::new(); + for &(item, wt, val, n) in &grouped_items { + for _ in 0..n { + items.push((item, wt, val)); + } + } + + let bagged = knapsack01_dp(&items, max_wt); + + // Count and group the bagged items + let mut counts: HashMap<&str, i32> = HashMap::new(); + for &(item, _, _) in &bagged { + *counts.entry(item).or_insert(0) += 1; + } + + // Sort and print the results + let mut sorted_counts: Vec<_> = counts.iter().collect(); + sorted_counts.sort_by_key(|&(item, _)| *item); + + println!("Bagged the following {} items", bagged.len()); + for (item, count) in sorted_counts { + println!(" {} off: {}", count, item); + } + + let total_value: i32 = bagged.iter().map(|&(_, _, val)| val).sum(); + let total_weight: i32 = bagged.iter().map(|&(_, wt, _)| wt).sum(); + + println!("for a total value of {} and a total weight of {}", + total_value, total_weight); +} + +fn knapsack01_dp<'a>(items: &'a [(&'a str, i32, i32)], limit: i32) -> Vec<(&'a str, i32, i32)> { + let n = items.len(); + let limit_usize = limit as usize; + + // Create DP table + let mut table = vec![vec![0; (limit_usize + 1) as usize]; n + 1]; + + for j in 1..=n { + let (_, wt, val) = items[j-1]; + let wt_usize = wt as usize; + + for w in 1..=limit_usize { + if wt_usize > w { + table[j][w] = table[j-1][w]; + } else { + table[j][w] = std::cmp::max( + table[j-1][w], + table[j-1][w - wt_usize] + val + ); + } + } + } + + // Backtrack to find items + let mut result = Vec::new(); + let mut w = limit_usize; + + for j in (1..=n).rev() { + let was_added = table[j][w] != table[j-1][w]; + + if was_added { + result.push(items[j-1]); + w -= items[j-1].1 as usize; + } + } + + result +} diff --git a/Task/Knapsack-problem-Bounded/Tcl/knapsack-problem-bounded.tcl b/Task/Knapsack-problem-Bounded/Tcl/knapsack-problem-bounded.tcl index fb6052964c..bf6d65f62c 100644 --- a/Task/Knapsack-problem-Bounded/Tcl/knapsack-problem-bounded.tcl +++ b/Task/Knapsack-problem-Bounded/Tcl/knapsack-problem-bounded.tcl @@ -1,48 +1,48 @@ # The list of items to consider, as list of lists set items { - {map 9 150 1} - {compass 13 35 1} - {water 153 200 2} - {sandwich 50 60 2} - {glucose 15 60 2} - {tin 68 45 3} - {banana 27 60 3} - {apple 39 40 3} - {cheese 23 30 1} - {beer 52 10 3} - {{suntan cream} 11 70 1} - {camera 32 30 1} - {t-shirt 24 15 2} - {trousers 48 10 2} - {umbrella 73 40 1} - {{waterproof trousers} 42 70 1} - {{waterproof overclothes} 43 75 1} - {note-case 22 80 1} - {sunglasses 7 20 1} - {towel 18 12 2} - {socks 4 50 1} - {book 30 10 2} + {map 9 150 1} + {compass 13 35 1} + {water 153 200 2} + {sandwich 50 60 2} + {glucose 15 60 2} + {tin 68 45 3} + {banana 27 60 3} + {apple 39 40 3} + {cheese 23 30 1} + {beer 52 10 3} + {{suntan cream} 11 70 1} + {camera 32 30 1} + {t-shirt 24 15 2} + {trousers 48 10 2} + {umbrella 73 40 1} + {{waterproof trousers} 42 70 1} + {{waterproof overclothes} 43 75 1} + {note-case 22 80 1} + {sunglasses 7 20 1} + {towel 18 12 2} + {socks 4 50 1} + {book 30 10 2} } # Simple extraction functions proc countednames {chosen} { set names {} foreach item $chosen { - lappend names [lindex $item 3] [lindex $item 0] + lappend names [lindex $item 3] [lindex $item 0] } return $names } proc weight {chosen} { set weight 0 foreach item $chosen { - incr weight [expr {[lindex $item 3] * [lindex $item 1]}] + incr weight [expr {[lindex $item 3] * [lindex $item 1]}] } return $weight } proc value {chosen} { set value 0 foreach item $chosen { - incr value [expr {[lindex $item 3] * [lindex $item 2]}] + incr value [expr {[lindex $item 3] * [lindex $item 2]}] } return $value } @@ -51,26 +51,26 @@ proc value {chosen} { proc knapsackSearch {items {chosen {}}} { # If we've gone over the weight limit, stop now if {[weight $chosen] > 400} { - return + return } # If we've considered all of the items (i.e., leaf in search tree) # then see if we've got a new best choice. if {[llength $items] == 0} { - global best max - set v [value $chosen] - if {$v > $max} { - set max $v - set best $chosen - } - return + global best max + set v [value $chosen] + if {$v > $max} { + set max $v + set best $chosen + } + return } # Branch, so recurse for chosing the current item or not set this [lindex $items 0] set rest [lrange $items 1 end] knapsackSearch $rest $chosen for {set i 1} {$i<=[lindex $this 3]} {incr i} { - knapsackSearch $rest \ - [concat $chosen [list [lreplace $this end end $i]]] + knapsackSearch $rest \ + [concat $chosen [list [lreplace $this end end $i]]] } } diff --git a/Task/Knapsack-problem-Bounded/XPL0/knapsack-problem-bounded.xpl0 b/Task/Knapsack-problem-Bounded/XPL0/knapsack-problem-bounded.xpl0 new file mode 100644 index 0000000000..ee76c54d92 --- /dev/null +++ b/Task/Knapsack-problem-Bounded/XPL0/knapsack-problem-bounded.xpl0 @@ -0,0 +1,73 @@ +include xpllib; \for Print and IntSize +def N = 22; \number of Items +int Items, S(N); +def \Items\ Name, Weight, Value, Count; + +proc Knapsack(W); +int W; +int I, J, K, V, MM, M; +[MM:= Reserve((N+1)*(W+1)*IntSize); +M:= Reserve((N+1)*IntSize); +M(0):= MM; +for I:= 1 to N do + [M(I):= @MM(I*(W+1)); + for J:= 0 to W do + [M(I, J):= M(I-1, J); + for K:= 1 to Items(I-1, Count) do + [if K*Items(I-1, Weight) <= J then + [V:= M(I-1, J-K*Items(I-1, Weight)) + K*Items(I-1, Value); + if V > M(I, J) then M(I, J):= V; + ]; + ]; + ]; + ]; +I:= N; J:= W; +while I > 0 do + [V:= M(I, J); + K:= 0; + while V # M(I-1, J) + K*Items(I-1, Value) do + [S(I-1):= S(I-1) + 1; + J:= J - Items(I-1, Weight); + K:= K+1; + ]; + I:= I-1; + ]; +]; + +int I, TC, TW, TV; +[Items:= [ + ["map ", 9, 150, 1], + ["compass ", 13, 35, 1], + ["water ", 153, 200, 2], + ["sandwich ", 50, 60, 2], + ["glucose ", 15, 60, 2], + ["tin ", 68, 45, 3], + ["banana ", 27, 60, 3], + ["apple ", 39, 40, 3], + ["cheese ", 23, 30, 1], + ["beer ", 52, 10, 3], + ["suntan cream ", 11, 70, 1], + ["camera ", 32, 30, 1], + ["T-shirt ", 24, 15, 2], + ["trousers ", 48, 10, 2], + ["umbrella ", 73, 40, 1], + ["waterproof trousers ", 42, 70, 1], + ["waterproof overclothes", 43, 75, 1], + ["note-case ", 22, 80, 1], + ["sunglasses ", 7, 20, 1], + ["towel ", 18, 12, 2], + ["socks ", 4, 50, 1], + ["book ", 30, 10, 2] ]; +TC:= 0; TW:= 0; TV:= 0; +Knapsack(400); \maximum weight = 400 decigrams = 4.0 killograms +for I:= 0 to N-1 do + [if S(I) then + [Print("%s %5d %5d %5d\n", + Items(I, Name), S(I), S(I)*Items(I, Weight), S(I)*Items(I, Value)); + TC:= TC + S(I); \accumulate totals + TW:= TW + S(I)*Items(I, Weight); + TV:= TV + S(I)*Items(I, Value); + ]; + ]; +Print("%s %5d %5d %5d\n", "count, weight, value: ", TC, TW, TV); +] diff --git a/Task/Knapsack-problem-Bounded/Zkl/knapsack-problem-bounded-1.zkl b/Task/Knapsack-problem-Bounded/Zkl/knapsack-problem-bounded-1.zkl index eb6282e8a1..9d83325dfe 100644 --- a/Task/Knapsack-problem-Bounded/Zkl/knapsack-problem-bounded-1.zkl +++ b/Task/Knapsack-problem-Bounded/Zkl/knapsack-problem-bounded-1.zkl @@ -3,6 +3,6 @@ fcn addItem(old,[(nm,w,v,c)]){ // old:list:(cost of:,(name,#,...)) wi,left,right:=w*i,list[0,wi],list[wi,*]; new:=old.apply('wrap([(val,itms)]){ T(val + v*i,itms.append(nm,i)) }); left.extend(right.zipWith( // inc - fcn([(v1,_)]a,[(v2,_)]b){ v1>v2 and a or b },new)); + fcn([(v1,_)]a,[(v2,_)]b){ v1>v2 and a or b },new)); },old,nm,w,v,old); }//--> new list diff --git a/Task/Knapsack-problem-Continuous/ALGOL-68/knapsack-problem-continuous.alg b/Task/Knapsack-problem-Continuous/ALGOL-68/knapsack-problem-continuous.alg new file mode 100644 index 0000000000..020bcee753 --- /dev/null +++ b/Task/Knapsack-problem-Continuous/ALGOL-68/knapsack-problem-continuous.alg @@ -0,0 +1,24 @@ +BEGIN # Knapsack problem: Continuous - based on the EasyLang sample # + + MODE ITEM = STRUCT( STRING name, REAL weight, value ); + PRIO SWAP = 1; + OP SWAP = ( REF ITEM a, b )VOID: BEGIN ITEM t = a; a := b; b := t END; + OP PRICE = ( ITEM a )REAL: value OF a / weight OF a; + []ITEM possible items + = ( ( "beef", 3.8, 36 ), ( "pork", 5.4, 43 ), ( "ham", 3.6, 90 ), ( "greaves", 2.4, 45 ) + , ( "flitch", 4.0, 30 ), ( "brawn", 2.5, 56 ), ( "welt", 3.7, 67 ), ( "salami", 3.0, 95 ) + , ( "sausage", 5.9, 98 ) + ); + [ LWB possible items : UPB possible items ]ITEM sack items := possible items; + FOR p FROM LWB sack items TO UPB sack items - 1 DO + FOR q FROM p + 1 TO UPB sack items DO + IF PRICE sack items[ q ] > PRICE sack items[ p ] THEN sack items[ p ] SWAP sack items[ q ] FI + OD + OD; + REAL max weight := 15; + FOR p FROM LWB sack items TO UPB sack items - 1 WHILE max weight > 0 DO + REAL w = IF weight OF sack items[ p ] > max weight THEN max weight ELSE weight OF sack items[ p ] FI; + print( ( fixed( w, -6, 2 ), " kg ", name OF sack items[ p ], newline ) ); + max weight -:= w + OD +END diff --git a/Task/Knapsack-problem-Continuous/ALGOL-W/knapsack-problem-continuous.alg b/Task/Knapsack-problem-Continuous/ALGOL-W/knapsack-problem-continuous.alg new file mode 100644 index 0000000000..2df6f5a98f --- /dev/null +++ b/Task/Knapsack-problem-Continuous/ALGOL-W/knapsack-problem-continuous.alg @@ -0,0 +1,39 @@ +begin % Knapsack problem: Continuous - based on the Algol 68 sample, which is based on the EasyLang sample % + + record Item ( string(12) name; real weight, cost ); + real procedure price ( reference(Item) value a ) ; cost(a) / weight(a); + integer MAX_ITEMS; + MAX_ITEMS := 9; + + begin + reference(Item) array sackItems ( 1 :: MAX_ITEMS ); + real maxWeight; + integer i; + + sackItems( 1 ) := Item( "beef", 3.8, 36 );sackItems( 2 ) := Item( "pork", 5.4, 43 ); + sackItems( 3 ) := Item( "ham", 3.6, 90 );sackItems( 4 ) := Item( "greaves", 2.4, 45 ); + sackItems( 5 ) := Item( "flitch", 4.0, 30 );sackItems( 6 ) := Item( "brawn", 2.5, 56 ); + sackItems( 7 ) := Item( "welt", 3.7, 67 );sackItems( 8 ) := Item( "salami", 3.0, 95 ); + sackItems( 9 ) := Item( "sausage", 5.9, 98 ); + + for p := 1 until MAX_ITEMS - 1 do begin + for q := p + 1 until MAX_ITEMS do begin + if price( sackItems( q ) ) > price( sackItems( p ) ) then begin + reference(Item) t; + t := sackItems( p ); + sackItems( p ) := sackItems( q ); + sackItems( q ) := t + end if_price_of_q_gt_price_of_p + end for_q + end for_p; + maxWeight := 15; + i := 0; + while i <= MAX_ITEMS and maxWeight > 0 do begin + real w; + i := i + 1; + w := if weight(sackItems(i)) > maxWeight then maxWeight else weight(sackItems(i)); + write( s_w := 0, r_format := "A", r_w := 6, r_d := 2, w, " kg ", name(sackItems(i)) ); + maxWeight := maxWeight - w + end while_i_le_MAX_WEIGHT_and_maxWeight_gt_0 ; + end +end. diff --git a/Task/Knapsack-problem-Continuous/Ada/knapsack-problem-continuous.ada b/Task/Knapsack-problem-Continuous/Ada/knapsack-problem-continuous.adb similarity index 100% rename from Task/Knapsack-problem-Continuous/Ada/knapsack-problem-continuous.ada rename to Task/Knapsack-problem-Continuous/Ada/knapsack-problem-continuous.adb diff --git a/Task/Knapsack-problem-Continuous/C/knapsack-problem-continuous.c b/Task/Knapsack-problem-Continuous/C/knapsack-problem-continuous.c index 6971bf3ea0..68d5cd5677 100644 --- a/Task/Knapsack-problem-Continuous/C/knapsack-problem-continuous.c +++ b/Task/Knapsack-problem-Continuous/C/knapsack-problem-continuous.c @@ -2,36 +2,36 @@ #include struct item { double w, v; const char *name; } items[] = { - { 3.8, 36, "beef" }, - { 5.4, 43, "pork" }, - { 3.6, 90, "ham" }, - { 2.4, 45, "greaves" }, - { 4.0, 30, "flitch" }, - { 2.5, 56, "brawn" }, - { 3.7, 67, "welt" }, - { 3.0, 95, "salami" }, - { 5.9, 98, "sausage" }, + { 3.8, 36, "beef" }, + { 5.4, 43, "pork" }, + { 3.6, 90, "ham" }, + { 2.4, 45, "greaves" }, + { 4.0, 30, "flitch" }, + { 2.5, 56, "brawn" }, + { 3.7, 67, "welt" }, + { 3.0, 95, "salami" }, + { 5.9, 98, "sausage" }, }; int item_cmp(const void *aa, const void *bb) { - const struct item *a = aa, *b = bb; - double ua = a->v / a->w, ub = b->v / b->w; - return ua < ub ? -1 : ua > ub; + const struct item *a = aa, *b = bb; + double ua = a->v / a->w, ub = b->v / b->w; + return ua < ub ? -1 : ua > ub; } int main() { - struct item *it; - double space = 15; + struct item *it; + double space = 15; - qsort(items, 9, sizeof(struct item), item_cmp); - for (it = items + 9; it---items && space > 0; space -= it->w) - if (space >= it->w) - printf("take all %s\n", it->name); - else - printf("take %gkg of %g kg of %s\n", - space, it->w, it->name); + qsort(items, 9, sizeof(struct item), item_cmp); + for (it = items + 9; it---items && space > 0; space -= it->w) + if (space >= it->w) + printf("take all %s\n", it->name); + else + printf("take %gkg of %g kg of %s\n", + space, it->w, it->name); - return 0; + return 0; } diff --git a/Task/Knapsack-problem-Continuous/Delphi/knapsack-problem-continuous.delphi b/Task/Knapsack-problem-Continuous/Delphi/knapsack-problem-continuous.delphi deleted file mode 100644 index 30f9c81955..0000000000 --- a/Task/Knapsack-problem-Continuous/Delphi/knapsack-problem-continuous.delphi +++ /dev/null @@ -1,92 +0,0 @@ -{Structure to hold the data} - -type TButcherInfo = record - Name: string; - Weight,Cost,PerKG: double; - end; -type PButcherInfo = ^TButcherInfo; - -{Array of actual data} - -var Items: array [0..8] of TButcherInfo =( - (Name: 'beef'; Weight: 3.8; Cost: 36.0), - (Name: 'pork'; Weight: 5.4; Cost: 43.0), - (Name: 'ham'; Weight: 3.6; Cost: 90.0), - (Name: 'greaves'; Weight: 2.4; Cost: 45.0), - (Name: 'flitch'; Weight: 4.0; Cost: 30.0), - (Name: 'brawn'; Weight: 2.5; Cost: 56.0), - (Name: 'welt'; Weight: 3.7; Cost: 67.0), - (Name: 'salami'; Weight: 3.0; Cost: 95.0), - (Name: 'sausage'; Weight: 5.9; Cost: 98.0) - ); - - -function CompareButcher(List: TStringList; Index1, Index2: Integer): Integer; -{Compare routine to sort by Per Kilograph cost} -var Info1,Info2: TButcherInfo; -begin -Info1:=PButcherInfo(List.Objects[Index1])^; -Info2:=PButcherInfo(List.Objects[Index2])^; -Result:=Trunc(Info2.PerKG * 100 - Info1.PerKG * 100); -end; - - -procedure KnapsackProblem(Memo: TMemo); -{Solve the knapsack problem} -var SL: TStringList; -var I,Inx: integer; -var Info: TButcherInfo; -var Weight,Cost,Diff: double; -const Limit = 15; -begin -SL:=TStringList.Create; -try -{Calculate the per Kilogram cost for each item} -for I:=0 to High(Items) do - begin - Items[I].PerKG:=Items[I].Cost/Items[I].Weight; - SL.AddObject(Items[I].Name,@Items[I]); - end; -{Sort most expensive items to top of list} -SL.CustomSort(CompareButcher); - -{Take the most expensive items } -Weight:=0; Cost:=0; -for I:=0 to SL.Count-1 do - begin - Info:=PButcherInfo(SL.Objects[I])^; - {Item exceeds the weight limit? } - if (Weight+Info.Weight)>=Limit then - begin - {Calculate percent to fill gap} - Diff:=(Limit-Weight)/Info.Weight; - {Save index} - Inx:=I; - break; - end - else - begin - {Add up totals} - Weight:=Weight+Info.Weight; - Cost:=Cost+Info.Cost; - end; - end; - -{Display all items} -Memo.Lines.Add('Item Portion Value'); -Memo.Lines.Add('--------------------------'); -for I:=0 to Inx-1 do - begin - Info:=PButcherInfo(SL.Objects[I])^; - Memo.Lines.Add(Format('%-8s %8.2f %8.2f',[Info.Name,Info.Weight,Info.Cost])); - end; -Info:=PButcherInfo(SL.Objects[Inx])^; -{Calculate cost and weight to fill gap} -weight:=Weight+Info.Weight*Diff; -Cost:=Cost+Info.Cost*Diff; -{Display gap filling item} -Memo.Lines.Add(Format('%-8s %8.2f %8.2f',[Info.Name,Info.Weight*Diff,Info.Cost*Diff])); -Memo.Lines.Add('--------------------------'); -Memo.Lines.Add(Format('Totals %8.2f %8.2f',[Weight,Cost])); -finally SL.Free; end; -end; diff --git a/Task/Knapsack-problem-Continuous/Delphi/knapsack-problem-continuous.pas b/Task/Knapsack-problem-Continuous/Delphi/knapsack-problem-continuous.pas new file mode 100644 index 0000000000..13d136d18a --- /dev/null +++ b/Task/Knapsack-problem-Continuous/Delphi/knapsack-problem-continuous.pas @@ -0,0 +1,92 @@ +{Structure to hold the data} + +type TButcherInfo = record + Name: string; + Weight,Cost,PerKG: double; + end; +type PButcherInfo = ^TButcherInfo; + +{Array of actual data} + +var Items: array [0..8] of TButcherInfo =( + (Name: 'beef'; Weight: 3.8; Cost: 36.0), + (Name: 'pork'; Weight: 5.4; Cost: 43.0), + (Name: 'ham'; Weight: 3.6; Cost: 90.0), + (Name: 'greaves'; Weight: 2.4; Cost: 45.0), + (Name: 'flitch'; Weight: 4.0; Cost: 30.0), + (Name: 'brawn'; Weight: 2.5; Cost: 56.0), + (Name: 'welt'; Weight: 3.7; Cost: 67.0), + (Name: 'salami'; Weight: 3.0; Cost: 95.0), + (Name: 'sausage'; Weight: 5.9; Cost: 98.0) + ); + + +function CompareButcher(List: TStringList; Index1, Index2: Integer): Integer; +{Compare routine to sort by Per Kilograph cost} +var Info1,Info2: TButcherInfo; +begin +Info1:=PButcherInfo(List.Objects[Index1])^; +Info2:=PButcherInfo(List.Objects[Index2])^; +Result:=Trunc(Info2.PerKG * 100 - Info1.PerKG * 100); +end; + + +procedure KnapsackProblem(Memo: TMemo); +{Solve the knapsack problem} +var SL: TStringList; +var I,Inx: integer; +var Info: TButcherInfo; +var Weight,Cost,Diff: double; +const Limit = 15; +begin +SL:=TStringList.Create; +try +{Calculate the per Kilogram cost for each item} +for I:=0 to High(Items) do + begin + Items[I].PerKG:=Items[I].Cost/Items[I].Weight; + SL.AddObject(Items[I].Name,@Items[I]); + end; +{Sort most expensive items to top of list} +SL.CustomSort(CompareButcher); + +{Take the most expensive items } +Weight:=0; Cost:=0; +for I:=0 to SL.Count-1 do + begin + Info:=PButcherInfo(SL.Objects[I])^; + {Item exceeds the weight limit? } + if (Weight+Info.Weight)>=Limit then + begin + {Calculate percent to fill gap} + Diff:=(Limit-Weight)/Info.Weight; + {Save index} + Inx:=I; + break; + end + else + begin + {Add up totals} + Weight:=Weight+Info.Weight; + Cost:=Cost+Info.Cost; + end; + end; + +{Display all items} +Memo.Lines.Add('Item Portion Value'); +Memo.Lines.Add('--------------------------'); +for I:=0 to Inx-1 do + begin + Info:=PButcherInfo(SL.Objects[I])^; + Memo.Lines.Add(Format('%-8s %8.2f %8.2f',[Info.Name,Info.Weight,Info.Cost])); + end; +Info:=PButcherInfo(SL.Objects[Inx])^; +{Calculate cost and weight to fill gap} +weight:=Weight+Info.Weight*Diff; +Cost:=Cost+Info.Cost*Diff; +{Display gap filling item} +Memo.Lines.Add(Format('%-8s %8.2f %8.2f',[Info.Name,Info.Weight*Diff,Info.Cost*Diff])); +Memo.Lines.Add('--------------------------'); +Memo.Lines.Add(Format('Totals %8.2f %8.2f',[Weight,Cost])); +finally SL.Free; end; +end; diff --git a/Task/Knapsack-problem-Continuous/EasyLang/knapsack-problem-continuous.easy b/Task/Knapsack-problem-Continuous/EasyLang/knapsack-problem-continuous.easy new file mode 100644 index 0000000000..7a33c0d695 --- /dev/null +++ b/Task/Knapsack-problem-Continuous/EasyLang/knapsack-problem-continuous.easy @@ -0,0 +1,24 @@ +name$[] = [ "beef" "pork" "ham" "greaves" "flitch" "brawn" "welt" "salami" "sausage" ] +wgt[] = [ 3.8 5.4 3.6 2.4 4.0 2.5 3.7 3.0 5.9 ] +val[] = [ 36 43 90 45 30 56 67 95 98 ] +maxwgt = 15 +# +n = len wgt[] +# +for i = 1 to n - 1 + for j = i + 1 to n + if val[j] / wgt[j] > val[i] / wgt[i] + swap val[j] val[i] + swap wgt[j] wgt[i] + swap name$[j] name$[i] + . + . +. +for i to n + w = lower wgt[i] maxwgt + print w & " kg " & name$[i] + maxwgt -= w + if maxwgt = 0 + break 1 + . +. diff --git a/Task/Knapsack-problem-Continuous/EchoLisp/knapsack-problem-continuous.l b/Task/Knapsack-problem-Continuous/EchoLisp/knapsack-problem-continuous.l index 2cf95731bb..3da36e435f 100644 --- a/Task/Knapsack-problem-Continuous/EchoLisp/knapsack-problem-continuous.l +++ b/Task/Knapsack-problem-Continuous/EchoLisp/knapsack-problem-continuous.l @@ -4,20 +4,20 @@ (define T (make-table (struct meal (name poids price)))) (define meals - '((🐂-beef 3.8 36) - (🍖-pork 5.4 43) - (🍗-ham 3.6 90) - (🐪-greaves 2.4 45) - (flitch 4.0 30) - (brawn 2.5 56) - (welt 3.7 67) - (🐃--salami 3.0 95) - (🐖-sausage 5.9 98))) + '((🐂-beef 3.8 36) + (🍖-pork 5.4 43) + (🍗-ham 3.6 90) + (🐪-greaves 2.4 45) + (flitch 4.0 30) + (brawn 2.5 56) + (welt 3.7 67) + (🐃--salami 3.0 95) + (🐖-sausage 5.9 98))) (list->table meals T) ;; sort table according to best price/poids ratio (define (price/poids a b ) - (- (// (* (meal-price b) (meal-poids a)) (meal-price a) (meal-poids b)) 1)) + (- (// (* (meal-price b) (meal-poids a)) (meal-price a) (meal-poids b)) 1)) (table-sort T price/poids) (define-syntax-rule (name i) (table-xref T i 0)) @@ -25,11 +25,11 @@ ;; shop : add items in basket, in order, until W exhausted (define (shop W ) - (for/list ((i (table-count T))) - #:break (<= W 0) - (begin0 - (cons (name i) (if (<= (poids i) W) 'all W)) - (set! W (- W (poids i)))))) + (for/list ((i (table-count T))) + #:break (<= W 0) + (begin0 + (cons (name i) (if (<= (poids i) W) 'all W)) + (set! W (- W (poids i)))))) ;; output (shop 15) diff --git a/Task/Knapsack-problem-Continuous/Eiffel/knapsack-problem-continuous.e b/Task/Knapsack-problem-Continuous/Eiffel/knapsack-problem-continuous.e index 59631fdab0..490774f8ea 100644 --- a/Task/Knapsack-problem-Continuous/Eiffel/knapsack-problem-continuous.e +++ b/Task/Knapsack-problem-Continuous/Eiffel/knapsack-problem-continuous.e @@ -1,71 +1,71 @@ class - CONTINUOUS_KNAPSACK + CONTINUOUS_KNAPSACK create - make + make feature - make - local - tup: TUPLE [name: STRING; weight: REAL_64; price: REAL_64] - do - create tup - create items.make_filled (tup, 1, 9) - create sorted.make - sorted.extend (-36.0 / 3.8) - sorted.extend (-43.0 / 5.4) - sorted.extend (-90.0 / 3.6) - sorted.extend (-45.0 / 2.4) - sorted.extend (-30.0 / 4.0) - sorted.extend (-56.0 / 2.5) - sorted.extend (-67.0 / 3.7) - sorted.extend (-95.0 / 3.0) - sorted.extend (-98.0 / 5.9) - tup := ["beef", 3.8, 36.0] - items [sorted.index_of (- tup.price / tup.weight, 1)] := tup - tup := ["pork", 5.4, 43.0] - items [sorted.index_of (- tup.price / tup.weight, 1)] := tup - tup := ["ham", 3.6, 90.0] - items [sorted.index_of (- tup.price / tup.weight, 1)] := tup - tup := ["greaves", 2.4, 45.0] - items [sorted.index_of (- tup.price / tup.weight, 1)] := tup - tup := ["flitch", 4.0, 30.0] - items [sorted.index_of (- tup.price / tup.weight, 1)] := tup - tup := ["brawn", 2.5, 56.0] - items [sorted.index_of (- tup.price / tup.weight, 1)] := tup - tup := ["welt", 3.7, 67.0] - items [sorted.index_of (- tup.price / tup.weight, 1)] := tup - tup := ["salami", 3.0, 95.0] - items [sorted.index_of (- tup.price / tup.weight, 1)] := tup - tup := ["sausage", 5.9, 98.0] - items [sorted.index_of (- tup.price / tup.weight, 1)] := tup - find_solution - end + make + local + tup: TUPLE [name: STRING; weight: REAL_64; price: REAL_64] + do + create tup + create items.make_filled (tup, 1, 9) + create sorted.make + sorted.extend (-36.0 / 3.8) + sorted.extend (-43.0 / 5.4) + sorted.extend (-90.0 / 3.6) + sorted.extend (-45.0 / 2.4) + sorted.extend (-30.0 / 4.0) + sorted.extend (-56.0 / 2.5) + sorted.extend (-67.0 / 3.7) + sorted.extend (-95.0 / 3.0) + sorted.extend (-98.0 / 5.9) + tup := ["beef", 3.8, 36.0] + items [sorted.index_of (- tup.price / tup.weight, 1)] := tup + tup := ["pork", 5.4, 43.0] + items [sorted.index_of (- tup.price / tup.weight, 1)] := tup + tup := ["ham", 3.6, 90.0] + items [sorted.index_of (- tup.price / tup.weight, 1)] := tup + tup := ["greaves", 2.4, 45.0] + items [sorted.index_of (- tup.price / tup.weight, 1)] := tup + tup := ["flitch", 4.0, 30.0] + items [sorted.index_of (- tup.price / tup.weight, 1)] := tup + tup := ["brawn", 2.5, 56.0] + items [sorted.index_of (- tup.price / tup.weight, 1)] := tup + tup := ["welt", 3.7, 67.0] + items [sorted.index_of (- tup.price / tup.weight, 1)] := tup + tup := ["salami", 3.0, 95.0] + items [sorted.index_of (- tup.price / tup.weight, 1)] := tup + tup := ["sausage", 5.9, 98.0] + items [sorted.index_of (- tup.price / tup.weight, 1)] := tup + find_solution + end - find_solution - -- Solution for the continuous Knapsack Problem. - local - maxW, value: REAL_64 - do - maxW := 15 - across - items as c - loop - if maxW - c.item.weight > 0 then - io.put_string ("Take all: " + c.item.name + ".%N") - value := value + c.item.price - maxW := maxW - c.item.weight - elseif maxW /= 0 then - io.put_string ("Take " + maxW.truncated_to_real.out + " kg off " + c.item.name + ".%N") - io.put_string ("The total value is " + (value + (c.item.price / c.item.weight) * maxW).truncated_to_real.out + ".") - maxW := 0 - end - end - end + find_solution + -- Solution for the continuous Knapsack Problem. + local + maxW, value: REAL_64 + do + maxW := 15 + across + items as c + loop + if maxW - c.item.weight > 0 then + io.put_string ("Take all: " + c.item.name + ".%N") + value := value + c.item.price + maxW := maxW - c.item.weight + elseif maxW /= 0 then + io.put_string ("Take " + maxW.truncated_to_real.out + " kg off " + c.item.name + ".%N") + io.put_string ("The total value is " + (value + (c.item.price / c.item.weight) * maxW).truncated_to_real.out + ".") + maxW := 0 + end + end + end - items: ARRAY [TUPLE [name: STRING; weight: REAL_64; price: REAL_64]] + items: ARRAY [TUPLE [name: STRING; weight: REAL_64; price: REAL_64]] - sorted: SORTED_TWO_WAY_LIST [REAL_64] + sorted: SORTED_TWO_WAY_LIST [REAL_64] end diff --git a/Task/Knapsack-problem-Continuous/Elixir/knapsack-problem-continuous-1.elixir b/Task/Knapsack-problem-Continuous/Elixir/knapsack-problem-continuous-1.ex similarity index 100% rename from Task/Knapsack-problem-Continuous/Elixir/knapsack-problem-continuous-1.elixir rename to Task/Knapsack-problem-Continuous/Elixir/knapsack-problem-continuous-1.ex diff --git a/Task/Knapsack-problem-Continuous/Elixir/knapsack-problem-continuous-2.elixir b/Task/Knapsack-problem-Continuous/Elixir/knapsack-problem-continuous-2.ex similarity index 100% rename from Task/Knapsack-problem-Continuous/Elixir/knapsack-problem-continuous-2.elixir rename to Task/Knapsack-problem-Continuous/Elixir/knapsack-problem-continuous-2.ex diff --git a/Task/Knapsack-problem-Continuous/Erlang/knapsack-problem-continuous.erl b/Task/Knapsack-problem-Continuous/Erlang/knapsack-problem-continuous.erl index aa2a05f734..9e21405f49 100644 --- a/Task/Knapsack-problem-Continuous/Erlang/knapsack-problem-continuous.erl +++ b/Task/Knapsack-problem-Continuous/Erlang/knapsack-problem-continuous.erl @@ -5,31 +5,31 @@ price_per_weight( Items ) -> [{Name, Weight, Price / Weight} || {Name, Weight, Price} <-Items]. select( Max_weight, Items ) -> - {_Remains, Selected_items} = lists:foldr( fun select_until/2, {Max_weight, []}, lists:keysort(3, Items) ), - Selected_items. + {_Remains, Selected_items} = lists:foldr( fun select_until/2, {Max_weight, []}, lists:keysort(3, Items) ), + Selected_items. task() -> - Items = items(), - io:fwrite( "The robber takes the following to maximize the value~n" ), - [io:fwrite("~.2f of ~p~n", [Weight, Name]) || {Name, Weight} <- select( 15, price_per_weight(Items) )]. + Items = items(), + io:fwrite( "The robber takes the following to maximize the value~n" ), + [io:fwrite("~.2f of ~p~n", [Weight, Name]) || {Name, Weight} <- select( 15, price_per_weight(Items) )]. items() -> - [{"beef", 3.8, 36}, - {"pork", 5.4, 43}, - {"ham", 3.6, 90}, - {"greaves", 2.4, 45}, - {"flitch", 4.0, 30}, - {"brawn", 2.5, 56}, - {"welt", 3.7 , 67}, - {"salami", 3.0, 95}, - {"sausage", 5.9 , 98} - ]. + [{"beef", 3.8, 36}, + {"pork", 5.4, 43}, + {"ham", 3.6, 90}, + {"greaves", 2.4, 45}, + {"flitch", 4.0, 30}, + {"brawn", 2.5, 56}, + {"welt", 3.7 , 67}, + {"salami", 3.0, 95}, + {"sausage", 5.9 , 98} + ]. select_until( {Name, Weight, _Price}, {Remains, Acc} ) when Remains > 0 -> - Selected_weight = select_until_weight( Weight, Remains ), - {Remains - Selected_weight, [{Name, Selected_weight} | Acc]}; + Selected_weight = select_until_weight( Weight, Remains ), + {Remains - Selected_weight, [{Name, Selected_weight} | Acc]}; select_until( _Item, Acc ) -> Acc. select_until_weight( Weight, Remains ) when Weight < Remains -> Weight; diff --git a/Task/Knapsack-problem-Continuous/Fortran/knapsack-problem-continuous.f b/Task/Knapsack-problem-Continuous/Fortran/knapsack-problem-continuous-1.f similarity index 100% rename from Task/Knapsack-problem-Continuous/Fortran/knapsack-problem-continuous.f rename to Task/Knapsack-problem-Continuous/Fortran/knapsack-problem-continuous-1.f diff --git a/Task/Knapsack-problem-Continuous/Fortran/knapsack-problem-continuous-2.f b/Task/Knapsack-problem-Continuous/Fortran/knapsack-problem-continuous-2.f new file mode 100644 index 0000000000..9ede5902df --- /dev/null +++ b/Task/Knapsack-problem-Continuous/Fortran/knapsack-problem-continuous-2.f @@ -0,0 +1,77 @@ +! Fractional knapsack: butcher's shop problem. +! Items may be cut; greedy optimum is achieved by sorting on value/weight +! ratio descending, then filling the knapsack in that order. +program butcher + use iso_fortran_env, only: real64 + implicit none + + integer, parameter :: NITEMS = 9 + real(real64), parameter :: CAPACITY = 15.0_real64 + + character(len=10), parameter :: name(NITEMS) = [ & + "beef ", "pork ", "ham ", "greaves ", & + "flitch ", "brawn ", "welt ", "salami ", & + "sausage " ] + + real(real64), parameter :: weight(NITEMS) = & + [ 3.8_real64, 5.4_real64, 3.6_real64, 2.4_real64, 4.0_real64, & + 2.5_real64, 3.7_real64, 3.0_real64, 5.9_real64 ] + + real(real64), parameter :: price(NITEMS) = & + [ 36.0_real64, 43.0_real64, 90.0_real64, 45.0_real64, 30.0_real64, & + 56.0_real64, 67.0_real64, 95.0_real64, 98.0_real64 ] + + real(real64) :: ratio(NITEMS), fraction(NITEMS) + real(real64) :: remaining, total_value, taken + integer :: order(NITEMS), i, j, tmp + + ! Compute value-per-kg ratios + do i = 1, NITEMS + ratio(i) = price(i) / weight(i) + end do + + ! Sort indices by ratio descending (insertion sort) + order = [(i, i = 1, NITEMS)] + do i = 2, NITEMS + j = i + do while (j > 1 .and. ratio(order(j)) > ratio(order(j-1))) + tmp = order(j); order(j) = order(j-1); order(j-1) = tmp + j = j - 1 + end do + end do + + ! Greedy fill + fraction = 0.0_real64 + remaining = CAPACITY + total_value = 0.0_real64 + + do i = 1, NITEMS + if (remaining <= 0.0_real64) exit + j = order(i) + taken = min(weight(j), remaining) + fraction(j) = taken / weight(j) + total_value = total_value + fraction(j) * price(j) + remaining = remaining - taken + end do + + ! Report + write(*, '(a)') "Fractional knapsack -- butcher's shop (capacity 15 kg)" + write(*, '(a)') repeat('-', 57) + write(*, '(a10, 2x, a10, 2x, a10, 2x, a10, 2x, a10)') & + "Item", "Weight kg", "Price", "Taken kg", "Value" + write(*, '(a)') repeat('-', 57) + + do i = 1, NITEMS + j = order(i) + if (fraction(j) > 0.0_real64) then + write(*, '(a10, 2x, f9.1, 2x, f9.2, 2x, f9.4, 2x, f9.2)') & + trim(name(j)), weight(j), price(j), & + fraction(j) * weight(j), fraction(j) * price(j) + end if + end do + + write(*, '(a)') repeat('-', 57) + write(*, '(a10, 2x, f9.4, 2x, 10x, 2x, 10x, 2x, f9.2)') & + "Total", CAPACITY - remaining, total_value + +end program butcher diff --git a/Task/Knapsack-problem-Continuous/Julia/knapsack-problem-continuous-1.julia b/Task/Knapsack-problem-Continuous/Julia/knapsack-problem-continuous-1.jl similarity index 100% rename from Task/Knapsack-problem-Continuous/Julia/knapsack-problem-continuous-1.julia rename to Task/Knapsack-problem-Continuous/Julia/knapsack-problem-continuous-1.jl diff --git a/Task/Knapsack-problem-Continuous/Julia/knapsack-problem-continuous-2.julia b/Task/Knapsack-problem-Continuous/Julia/knapsack-problem-continuous-2.jl similarity index 100% rename from Task/Knapsack-problem-Continuous/Julia/knapsack-problem-continuous-2.julia rename to Task/Knapsack-problem-Continuous/Julia/knapsack-problem-continuous-2.jl diff --git a/Task/Knapsack-problem-Continuous/Kotlin/knapsack-problem-continuous.kotlin b/Task/Knapsack-problem-Continuous/Kotlin/knapsack-problem-continuous.kts similarity index 100% rename from Task/Knapsack-problem-Continuous/Kotlin/knapsack-problem-continuous.kotlin rename to Task/Knapsack-problem-Continuous/Kotlin/knapsack-problem-continuous.kts diff --git a/Task/Knapsack-problem-Continuous/Mathematica/knapsack-problem-continuous-2.math b/Task/Knapsack-problem-Continuous/Mathematica/knapsack-problem-continuous-2.math index 699f1135da..755a27a121 100644 --- a/Task/Knapsack-problem-Continuous/Mathematica/knapsack-problem-continuous-2.math +++ b/Task/Knapsack-problem-Continuous/Mathematica/knapsack-problem-continuous-2.math @@ -4,9 +4,9 @@ weightPriceTable = carryCapacity = 15; Knapsack[weightPriceTable, carryCapacity] // Grid -salami 3. 95 -ham 3.6 90 -brawn 2.5 56 -greaves 2.4 45 -welt 3.5 63.3784 -Total 15. 349.378 +salami 3. 95 +ham 3.6 90 +brawn 2.5 56 +greaves 2.4 45 +welt 3.5 63.3784 +Total 15. 349.378 diff --git a/Task/Knapsack-problem-Continuous/Mathprog/knapsack-problem-continuous.math b/Task/Knapsack-problem-Continuous/Mathprog/knapsack-problem-continuous.math index d9992ffcf1..96402eb586 100644 --- a/Task/Knapsack-problem-Continuous/Mathprog/knapsack-problem-continuous.math +++ b/Task/Knapsack-problem-Continuous/Mathprog/knapsack-problem-continuous.math @@ -18,14 +18,14 @@ maximize knap_value: sum{t in Items} take[t] * (value[t]/weight[t]); data; param : Items : weight value := - beef 3.8 36 - pork 5.4 43 - ham 3.6 90 + beef 3.8 36 + pork 5.4 43 + ham 3.6 90 greaves 2.4 45 - flitch 4.0 30 - brawn 2.5 56 - welt 3.7 67 - salami 3.0 95 + flitch 4.0 30 + brawn 2.5 56 + welt 3.7 67 + salami 3.0 95 sausage 5.9 98 ; end; diff --git a/Task/Knapsack-problem-Continuous/Nim/knapsack-problem-continuous.nim b/Task/Knapsack-problem-Continuous/Nim/knapsack-problem-continuous.nim index f6e6f55e2b..84ead213cd 100644 --- a/Task/Knapsack-problem-Continuous/Nim/knapsack-problem-continuous.nim +++ b/Task/Knapsack-problem-Continuous/Nim/knapsack-problem-continuous.nim @@ -17,7 +17,7 @@ var items = @[Item(name: "beef", weight: 3.8, price: 36.0), Item(name: "salami", weight: 3.0, price: 95.0), Item(name: "sausage", weight: 5.9, price: 98.0) ] - ] + # Compute unit prices and sort items by decreasing unit price. for item in items.mitems: item.unitPrice = item.price / item.weight diff --git a/Task/Knapsack-problem-Continuous/OCaml/knapsack-problem-continuous.ocaml b/Task/Knapsack-problem-Continuous/OCaml/knapsack-problem-continuous.ml similarity index 100% rename from Task/Knapsack-problem-Continuous/OCaml/knapsack-problem-continuous.ocaml rename to Task/Knapsack-problem-Continuous/OCaml/knapsack-problem-continuous.ml diff --git a/Task/Knapsack-problem-Continuous/Oberon-07/knapsack-problem-continuous.oberon b/Task/Knapsack-problem-Continuous/Oberon-07/knapsack-problem-continuous.oberon new file mode 100644 index 0000000000..31fa6e1092 --- /dev/null +++ b/Task/Knapsack-problem-Continuous/Oberon-07/knapsack-problem-continuous.oberon @@ -0,0 +1,57 @@ +MODULE KnapsackProblem; (* Knapsack problem: Continuous - based on the Algol W sample, *) + (* which is based on the EasyLang sample *) + IMPORT Out; + + CONST maxItems = 8; + maxName = 12; + TYPE ItemDesc = RECORD name : ARRAY maxName OF CHAR; + weight, cost : REAL + END; + Item = POINTER TO ItemDesc; + + VAR sackItems : ARRAY maxItems + 1 OF Item; + t : Item; + weightLeft, w : REAL; + p, q : INTEGER; + + PROCEDURE price( a : Item ) : REAL; + BEGIN + RETURN a.cost / a.weight + END price; + + PROCEDURE newItem( name : ARRAY OF CHAR; weight, cost : REAL ) : Item; + VAR result : Item; + BEGIN + NEW( result ); + result.name := name; + result.weight := weight; + result.cost := cost + RETURN result + END newItem; + +BEGIN + + sackItems[ 0 ] := newItem( "beef", 3.8, 36.0 );sackItems[ 1 ] := newItem( "pork", 5.4, 43.0 ); + sackItems[ 2 ] := newItem( "ham", 3.6, 90.0 );sackItems[ 3 ] := newItem( "greaves", 2.4, 45.0 ); + sackItems[ 4 ] := newItem( "flitch", 4.0, 30.0 );sackItems[ 5 ] := newItem( "brawn", 2.5, 56.0 ); + sackItems[ 6 ] := newItem( "welt", 3.7, 67.0 );sackItems[ 7 ] := newItem( "salami", 3.0, 95.0 ); + sackItems[ 8 ] := newItem( "sausage", 5.9, 98.0 ); + + FOR p := 0 TO maxItems DO + FOR q := p + 1 TO maxItems DO + IF price( sackItems[ q ] ) > price( sackItems[ p ] ) THEN + t := sackItems[ p ]; + sackItems[ p ] := sackItems[ q ]; + sackItems[ q ] := t + END + END + END; + weightLeft := 15.0; + p := -1; + WHILE ( p <= maxItems ) & ( weightLeft > 0.0 ) DO + INC( p ); + IF sackItems[ p ].weight > weightLeft THEN w := weightLeft ELSE w := sackItems[ p ].weight END; + Out.Real( w, 12 );Out.String( " kg " );Out.String( sackItems[ p ].name );Out.Ln; + weightLeft := weightLeft - w + END +END KnapsackProblem. diff --git a/Task/Knapsack-problem-Continuous/Oforth/knapsack-problem-continuous.fth b/Task/Knapsack-problem-Continuous/Oforth/knapsack-problem-continuous.fth index b903dd54a5..4b5fab88a8 100644 --- a/Task/Knapsack-problem-Continuous/Oforth/knapsack-problem-continuous.fth +++ b/Task/Knapsack-problem-Continuous/Oforth/knapsack-problem-continuous.fth @@ -1,7 +1,7 @@ [ [ "beef", 3.8, 36 ], [ "pork", 5.4, 43 ], [ "ham", 3.6, 90 ], - [ "greaves", 2.4, 45 ], [ "flitch", 4.0, 30 ], [ "brawn", 2.5, 56 ], - [ "welt", 3.7, 67 ], [ "salami", 3.0, 95 ], [ "sausage", 5.9, 98 ] + [ "greaves", 2.4, 45 ], [ "flitch", 4.0, 30 ], [ "brawn", 2.5, 56 ], + [ "welt", 3.7, 67 ], [ "salami", 3.0, 95 ], [ "sausage", 5.9, 98 ] ] const: Items : rob diff --git a/Task/Knapsack-problem-Continuous/PHP/knapsack-problem-continuous.php b/Task/Knapsack-problem-Continuous/PHP/knapsack-problem-continuous.php index 5d01e6d7ed..f6038d256d 100644 --- a/Task/Knapsack-problem-Continuous/PHP/knapsack-problem-continuous.php +++ b/Task/Knapsack-problem-Continuous/PHP/knapsack-problem-continuous.php @@ -1,51 +1,51 @@ /* Added by @1x24. Translated from C++. Uses the PHP 7.x spaceship operator */ $data = [ - [ - 'name'=>'beef', - 'weight'=>3.8, - 'cost'=>36, - ], - [ - 'name'=>'pork', - 'weight'=>5.4, - 'cost'=>43, - ], - [ - 'name'=>'ham', - 'weight'=>3.6, - 'cost'=>90, - ], - [ - 'name'=>'greaves', - 'weight'=>2.4, - 'cost'=>45, - ], - [ - 'name'=>'flitch', - 'weight'=>4.0, - 'cost'=>30, - ], - [ - 'name'=>'brawn', - 'weight'=>2.5, - 'cost'=>56, - ], - [ - 'name'=>'welt', - 'weight'=>3.7, - 'cost'=>67, - ], - [ - 'name'=>'salami', - 'weight'=>3.0, - 'cost'=>95, - ], - [ - 'name'=>'sausage', - 'weight'=>5.9, - 'cost'=>98, - ], - ]; + [ + 'name'=>'beef', + 'weight'=>3.8, + 'cost'=>36, + ], + [ + 'name'=>'pork', + 'weight'=>5.4, + 'cost'=>43, + ], + [ + 'name'=>'ham', + 'weight'=>3.6, + 'cost'=>90, + ], + [ + 'name'=>'greaves', + 'weight'=>2.4, + 'cost'=>45, + ], + [ + 'name'=>'flitch', + 'weight'=>4.0, + 'cost'=>30, + ], + [ + 'name'=>'brawn', + 'weight'=>2.5, + 'cost'=>56, + ], + [ + 'name'=>'welt', + 'weight'=>3.7, + 'cost'=>67, + ], + [ + 'name'=>'salami', + 'weight'=>3.0, + 'cost'=>95, + ], + [ + 'name'=>'sausage', + 'weight'=>5.9, + 'cost'=>98, + ], + ]; uasort($data, function($a, $b) { return ($b['cost']/$b['weight']) <=> ($a['cost']/$a['weight']); @@ -54,11 +54,11 @@ uasort($data, function($a, $b) { $limit = 15; foreach ($data as $item): - if ($limit >= $item['weight']): - echo "Take all the {$item['name']}
    "; - else: - echo "Take $limit kg of {$item['name']}
    "; - break; - endif; - $limit -= $item['weight']; + if ($limit >= $item['weight']): + echo "Take all the {$item['name']}
    "; + else: + echo "Take $limit kg of {$item['name']}
    "; + break; + endif; + $limit -= $item['weight']; endforeach; diff --git a/Task/Knapsack-problem-Continuous/Phix/knapsack-problem-continuous.phix b/Task/Knapsack-problem-Continuous/Phix/knapsack-problem-continuous.phix index 9fdbf2fdc9..7d94c83a85 100644 --- a/Task/Knapsack-problem-Continuous/Phix/knapsack-problem-continuous.phix +++ b/Task/Knapsack-problem-Continuous/Phix/knapsack-problem-continuous.phix @@ -1,33 +1,31 @@ -(phixonline)--> - with javascript_semantics - constant meats = { - --Item Weight (kg) Price (Value) - {"beef", 3.8, 36}, - {"pork", 5.4, 43}, - {"ham", 3.6, 90}, - {"greaves", 2.4, 45}, - {"flitch", 4.0, 30}, - {"brawn", 2.5, 56}, - {"welt", 3.7, 67}, - {"salami", 3.0, 95}, - {"sausage", 5.9, 98}} +with javascript_semantics +constant meats = { +--Item Weight (kg) Price (Value) +{"beef", 3.8, 36}, +{"pork", 5.4, 43}, +{"ham", 3.6, 90}, +{"greaves", 2.4, 45}, +{"flitch", 4.0, 30}, +{"brawn", 2.5, 56}, +{"welt", 3.7, 67}, +{"salami", 3.0, 95}, +{"sausage", 5.9, 98}} - function by_weighted_value(integer i, j) - atom {?,weighti,pricei} = meats[i], - {?,weightj,pricej} = meats[j] - return compare(pricej/weightj,pricei/weighti) - end function +function by_weighted_value(integer i, j) + atom {?,weighti,pricei} = meats[i], + {?,weightj,pricej} = meats[j] + return compare(pricej/weightj,pricei/weighti) +end function - sequence tags = custom_sort(by_weighted_value,tagset(length(meats))) +sequence tags = custom_sort(by_weighted_value,tagset(length(meats))) - atom weight = 15, worth = 0 - for i=1 to length(tags) do - object {desc,wi,price} = meats[tags[i]] - atom amt = min(wi,weight) - printf(1,"%3.1fkg %s %s\n",{amt,iff(amt=wi?"(all the)":"of"),desc}) - worth += (amt/wi)*price - weight -= amt - if weight=0 then exit end if - end for - printf(1,"Total value: %f\n",{worth}) - - with javascript_semantics - enum RID, I, SAMPLE +with javascript_semantics +enum RID, I, SAMPLE - function s_of_n(sequence env, integer item) - integer i = env[I] + 1, - n = length(env[SAMPLE]) - env = deep_copy(env) - env[I] = i - if i<=n then - env[SAMPLE][i] = item - elsif n/i>rnd() then - env[SAMPLE][rand(n)] = item - end if - return env - end function +function s_of_n(sequence env, integer item) + integer i = env[I] + 1, + n = length(env[SAMPLE]) + env = deep_copy(env) + env[I] = i + if i<=n then + env[SAMPLE][i] = item + elsif n/i>rnd() then + env[SAMPLE][rand(n)] = item + end if + return env +end function - function s_of_n_creator(int n) - return {s_of_n,0,repeat(0,n)} - end function +function s_of_n_creator(int n) + return {s_of_n,0,repeat(0,n)} +end function - function invoke(sequence env, args) - env = call_func(env[RID],prepend(deep_copy(args),env)) - return env - end function +function invoke(sequence env, args) + env = call_func(env[RID],prepend(deep_copy(args),env)) + return env +end function - function test(integer n, sequence items) - sequence env = s_of_n_creator(n) - for i=1 to length(items) do - -- env = s_of_n(env,items[i]) - env = invoke(env, {items[i]}) - end for - return env[SAMPLE] - end function +function test(integer n, sequence items) + sequence env = s_of_n_creator(n) + for item in items do +-- env = s_of_n(env,item) + env = invoke(env,{item}) + end for + return env[SAMPLE] +end function - procedure main() - sequence items_set = tagset(9,0) - sequence frequencies = repeat(0,length(items_set)) - for i=1 to 100000 do - sequence res = test(3, items_set) - for j=1 to length(res) do - integer fdx = res[j]+1 - frequencies[fdx] += 1 - end for - end for - ?frequencies - end procedure - main() - - enum RID, I, SAMPLE, CLOSURE_LEN=$ - ... - function s_of_n_creator(int n) - sequence closure = repeat(0,CLOSURE_LEN) - closure[RID] = routine_id("s_of_n") - closure[I] = 0 - closure[SAMPLE] = repeat(0,n) - return closure - end function - - with javascript_semantics - function compress(string uncompressed) - integer dict = new_dict() - sequence result = {} - integer dictSize = 255, c - string word = "" - for i=0 to 255 do - setd(""&i,i,dict) - end for - for i=1 to length(uncompressed) do - c = uncompressed[i] - if getd_index(word&c,dict) then - word &= c - else - result &= getd(word,dict) - dictSize += 1 - setd(word&c,dictSize,dict) - word = ""&c - end if - end for - if word!="" then - result &= getd(word,dict) - end if - destroy_dict(dict) - return result - end function - - function decompress(sequence compressed) - integer dict = new_dict() - integer dictSize = 255, k, ki - string dent = "", result = "", word = "" - for i=0 to 255 do - setd(i,""&i,dict) - end for - for i=1 to length(compressed) do - k = compressed[i] - ki = getd_index(k,dict) - if ki then - dent = getd_by_index(ki,dict) - elsif k=dictSize then - dent = word&word[1] - else - return {NULL,i} - end if - result &= dent - setd(dictSize,word&dent[1],dict) - dictSize += 1 - word = dent - end for - destroy_dict(dict) - return result - end function - - constant example = "TOBEORNOTTOBEORTOBEORNOT" - sequence com = compress(example) - pp(com,{pp_IntCh,true,pp_Maxlen,90}) - ?decompress(com) - - with javascript_semantics - include mpfr.e +with javascript_semantics +include mpfr.e - constant lim = 100, - lim1 = lim+1, - last = 12 - sequence l = repeat(0,lim1) - for n=1 to lim1 do - l[n] = mpz_inits(lim1) - mpz_set_si(l[n][n],1) - if n!=2 then - mpz_fac_ui(l[n][2],n-1) - end if - end for - mpz {t, m100} = mpz_inits(2) - for n=1 to lim do - for k=1 to n do - mpz_mul(t,l[n+1][2],l[n][2]) - mpz_fdiv_q(t, t, l[k+1][2]) - mpz_fdiv_q(t, t, l[k][2]) - mpz_fdiv_q(l[n+1][k+1], t, l[n-k+1][2]) - end for - end for - printf(1,"Unsigned Lah numbers: l(n, k):\n n k:") - for i=0 to last do - printf(1,"%6d ", i) - end for - printf(1,"\n--- %s\n",repeat('-',last*11+6)) - for n=0 to last do - printf(1,"%2d ", n) - for k=1 to n+1 do - printf(1,"%10s ",{mpz_get_str(l[n+1][k])}) - end for - printf(1,"\n") - end for - for k=1 to lim1 do - mpz l100k = l[lim1][k] - if mpz_cmp(l100k,m100) > 0 then - mpz_set(m100,l100k) - end if - end for - printf(1,"\nThe maximum l(100,k): %s\n",shorten(mpz_get_str(m100))) - - sequence grid = repeat(repeat(' ',100),100) - integer aX = 50, aY = 50, - gXY, angle = 1 -- ' '/'#'; 0,1,2,3 = NESW - constant dX = {0,-1,0,1} -- (dY = reverse(dX)) +sequence grid = repeat(repeat(' ',100),100) +integer aX = 50, aY = 50, + gXY, angle = 1 -- ' '/'#'; 0,1,2,3 = NESW +constant dX = {0,-1,0,1} -- (dY = reverse(dX)) - while aX>=1 and aX<=100 - and aY>=1 and aY<=100 do - gXY = grid[aX][aY] - grid[aX][aY] = 67-gXY -- ' '<=>'#', aka 32<->35 - angle = mod(angle+2*gXY+3,4) -- +/-1, ie 0,1,2,3 -> 1,2,3,0 or 3,0,1,2 - aX += dX[angle+1] - aY += dX[4-angle] - end while +while aX>=1 and aX<=100 + and aY>=1 and aY<=100 do + gXY = grid[aX][aY] + grid[aX][aY] = 67-gXY -- ' '<=>'#', aka 32<->35 + angle = mod(angle+2*gXY+3,4) -- +/-1, ie 0,1,2,3 -> 1,2,3,0 or 3,0,1,2 + aX += dX[angle+1] + aY += dX[4-angle] +end while - puts(1,join(grid,"\n")) - - with javascript_semantics - integer magic = 9*8*7, - high = 9876432, - n = high-mod(high,magic) - sequence seen - while true do - string s = sprintf("%d",n) - seen = {1,0,0,0,0,1,0,0,0,0} - for j=1 to length(s) do - seen[s[j]-'0'+1] += 1 - end for - if max(seen)=1 then exit end if - n -= magic - end while - -- may as well quickly verify... - seen[5+1] = 0 -- (skipping 5) - for i=1 to 9 do -- ( and 0 ) - if seen[i+1] then - if mod(n,i)!=0 then ?9/0 end if - end if - end for - printf(1,"%d (%d iterations)\n",{n,(high-n)/magic}) - - with javascript_semantics - atom t0 = time() - integer count = 0 - string s - include mpfr.e - mpz lcm15 = mpz_init(lcm(tagset(15))), - d = mpz_init(), - r = mpz_init() - mpz_set_str(d,"FEDCBA987654321",16) - mpz_mod(r,d,lcm15) - mpz_sub(d,d,r) -- d:= max k*lcm <= "FE..21" - r = mpz_free(r) -- (no longer used) - while true do - s = mpz_get_str(d,16) - if sort(s)="123456789abcdef" then exit end if - mpz_sub(d,d,lcm15) - count += 1 - end while - string e = elapsed(time()-t0) - printf(1,"%s (%d iterations, %s)\n",{s,count,e}) - - puts(1,join_by(apply(true,sprintf,{{"%3d"},vslice(apply(apply(true,factors,{tagset(100),-1}),reverse),1)}),1,10,"")) - - with javascript_semantics - for n=1 to 100 do - integer p = 2, - lim = floor(sqrt(n)), - hf = 1 - while p<=lim do - if remainder(n,p)=0 then - hf = n/p - exit - end if - p += 1 - end while - printf(1,"%3d",hf) - if remainder(n,10)=0 then puts(1,"\n") end if - end for - - with javascript_semantics - procedure last_day_of_month(integer y, dow) - for m=1 to 12 do - integer d = days_in_month(y,m), - a = dow-day_of_week(y,m,d) - printf(1,"%4d-%02d-%02d\n",{y,m,d+a-7*(a>0)}) - end for - end procedure - constant FRIDAY=5 - --prompt_number() is not compatible with pwa/p2js - --last_day_of_month(prompt_number("Year:",{1752,9999}),FRIDAY) - last_day_of_month(2012,FRIDAY) - - with javascript_semantics - ?lcm(12,18) - ?lcm({12,18}) - - with javascript_semantics - -- - -- While a phix dictionary can handle keys of {x,a}, for this - -- task performance was dreadful (7,612,479 entries, >3mins), - -- so instead memophix maps known x to an index to memophia - -- which holds the full [1..a] for each x, dropping to a much - -- more respectable (albeit not super-fast) 14s - -- - constant memophix = new_dict() - sequence memophia = {} -- 1..a (max 3401) for each x +with javascript_semantics +-- +-- While a phix dictionary can handle keys of {x,a}, for this +-- task performance was dreadful (7,612,479 entries, >3mins), +-- so instead memophix maps known x to an index to memophia +-- which holds the full [1..a] for each x, dropping to a much +-- more respectable (albeit not super-fast) 9.5s +-- +constant memophix = new_dict() +sequence memophia = {} -- 1..a (max 3401) for each x - function phi(integer x, a) - if a=0 then return x end if - integer adx = getd(x,memophix), res - if adx=NULL then - memophia = append(memophia,repeat(-1,a)) - adx = length(memophia) - setd(x,adx,memophix) - else - object ma = memophia[adx] - integer l = length(ma) - if a>l then - memophia[adx] = 0 -- kill refcount - memophia[adx] = ma & repeat(-1,a-l) - else - res = ma[a] - if res>=0 then return res end if - end if - ma = 0 -- kill refcount - end if - res = phi(x, a-1) - phi(floor(x/get_prime(a)), a-1) - memophia[adx][a] = res - return res - end function +function phi(integer x, a) + if a=0 then return x end if + integer adx = getd(x,memophix), res + if adx=NULL then + memophia = append(memophia,repeat(-1,a)) + adx = length(memophia) + setd(x,adx,memophix) + else + object ma = memophia[adx] + integer l = length(ma) + if a>l then + memophia[adx] = 0 -- kill refcount + memophia[adx] = ma & repeat(-1,a-l) + else + res = ma[a] + if res>=0 then return res end if + end if + ma = 0 -- kill refcount + end if + res = phi(x, a-1) - phi(floor(x/get_prime(a)), a-1) + memophia[adx][a] = res + return res +end function - function pi(integer n) - if n<2 then return 0 end if - integer a = pi(floor(sqrt(n))) - return phi(n, a) + a - 1 - end function +function pi(integer n) + if n<2 then return 0 end if + integer a = pi(floor(sqrt(n))) + return phi(n, a) + a - 1 +end function - atom t0 = time() - for i=0 to iff(platform()=JS?8:9) do - printf(1,"10^%d %d\n",{i,pi(power(10,i))}) - -- printf(1,"10^%d %d\n",{i,length(get_primes_le(power(10,i)))}) - end for - ?elapsed(time()-t0) - - with javascript_semantics - requires("1.0.2") -- (for in, tagstart) - function half(integer n) return floor((n-1)/2)+1 end function // convenience convert to idx +with javascript_semantics +requires("1.0.2") -- (for in, tagstart) +function half(integer n) return floor((n-1)/2)+1 end function // convenience convert to idx - function count_primes(atom n) - // non-recursive Legendre prime counting function for a range `n`... - // has O(n^(3/4)/((log n)^2)) time complexity; O(n^(1/2)) space complexity. - if n<3 then return iff(n<2?0:1) end if // can't odd sieve for n less than 3! - integer sqrtn = trunc(sqrt(n)), // (actual limit) - mxndx = floor((sqrtn-1)/2) // odds-only limit - -- - -- smalls is the current accumulated counts of odd primes 1 to sqrt(n), initialized - -- to odds-only sieving, ie {0,1,2,3,4...} meaning 0 odd primes to 1, 1 o.p to 3,... - -- - -- roughs is the current odd k-rough numbers up to sqrt of range; k = 2 - -- initialized to all odd positive numbers 1, 3, 5, 7, 9, 11, ... sqrt(n) - -- - -- larges is an array of current phi counts for the above roughs... except they are - -- not strictly `phi`'s since they also include primes, to match `smalls` above! - -- initialized for current roughs after accounting for the even prime of two... - -- - -- composite is a flag array representing odd numbers 1..sqrtn, for sieving. - -- initialized false, meaning all positive odd numbers are potentially prime - -- note that this array starts at (and keeps) 1 to match the algorithm even - -- though 1 is not actually a prime, as 1 is important in computation of phi... - -- - sequence smalls = tagset(mxndx,0), - roughs = tagstart(1,mxndx+1,2), - larges = sq_floor_div(sq_sub(sq_div(n,roughs),1),2), - composite = repeat(false,mxndx+1) +function count_primes(atom n) + // non-recursive Legendre prime counting function for a range `n`... + // has O(n^(3/4)/((log n)^2)) time complexity; O(n^(1/2)) space complexity. + if n<3 then return iff(n<2?0:1) end if // can't odd sieve for n less than 3! + integer sqrtn = trunc(sqrt(n)), // (actual limit) + mxndx = floor((sqrtn-1)/2) // odds-only limit + -- + -- smalls is the current accumulated counts of odd primes 1 to sqrt(n), initialized + -- to odds-only sieving, ie {0,1,2,3,4...} meaning 0 odd primes to 1, 1 o.p to 3,... + -- + -- roughs is the current odd k-rough numbers up to sqrt of range; k = 2 + -- initialized to all odd positive numbers 1, 3, 5, 7, 9, 11, ... sqrt(n) + -- + -- larges is an array of current phi counts for the above roughs... except they are + -- not strictly `phi`'s since they also include primes, to match `smalls` above! + -- initialized for current roughs after accounting for the even prime of two... + -- + -- composite is a flag array representing odd numbers 1..sqrtn, for sieving. + -- initialized false, meaning all positive odd numbers are potentially prime + -- note that this array starts at (and keeps) 1 to match the algorithm even + -- though 1 is not actually a prime, as 1 is important in computation of phi... + -- + sequence smalls = tagset(mxndx,0), + roughs = tagstart(1,mxndx+1,2), + larges = sq_floor_div(sq_sub(sq_div(n,roughs),1),2), + composite = repeat(false,mxndx+1) - integer bp = 3, // 'current' base prime - nbp = 0, // number of base primes found - mxri = mxndx, // current highest used rough index - i = 2, sqri = 4 // index and square (index-1) limit - // partial sieve loop, adjusting larges/smalls, compressing larges/roughs... - while sqri<=mxndx do // partial sieve to square index limit - if not composite[i] then - // cull from composite so they will never be found again - composite[i] = true // cull bp and multiples - for c=sqri+1 to mxndx+1 by bp do - composite[c] = true - end for - // partial sieving to current base prime is now completed! + integer bp = 3, // 'current' base prime + nbp = 0, // number of base primes found + mxri = mxndx, // current highest used rough index + i = 2, sqri = 4 // index and square (index-1) limit + // partial sieve loop, adjusting larges/smalls, compressing larges/roughs... + while sqri<=mxndx do // partial sieve to square index limit + if not composite[i] then + // cull from composite so they will never be found again + composite[i] = true // cull bp and multiples + for c=sqri+1 to mxndx+1 by bp do + composite[c] = true + end for + // partial sieving to current base prime is now completed! - // now adjust `larges` for latest partial sieve pass... - integer ori = 0 // compress input rough index(k) to output one - for k,q in roughs to mxri+1 do - // q is not necessarily prime but may be a product of primes not yet - // culled by partial sieving (saves ops cmprd to recursive Legendre) - // skip over values of `q` already culled in the last partial sieve: - integer qi = floor(q/2)+1; // index of always odd q! - if not composite[qi] then - // since `q` cannot be equal to bp due to cull of bp and above skip; - atom d = bp*q, // `d` is odd product of some combination of odd primes! - // the following computation is essential to the algorithm's speed, - // see the Nim entry for the full details of how this works - dadj = iff(d<=sqrtn ? larges[smalls[half(d)]-nbp+1] - : smalls[half(floor(n/d))]) - ori += 1 - larges[ori] = larges[k]-dadj+nbp // base primes count over subtracted! - // eliminate rough values that have been culled in partial sieve: - // note that `larges` and `roughs` indices relate to each other! - roughs[ori] = q - end if - end for + // now adjust `larges` for latest partial sieve pass... + integer ori = 0 // compress input rough index(k) to output one + for k,q in roughs to mxri+1 do + // q is not necessarily prime but may be a product of primes not yet + // culled by partial sieving (saves ops cmprd to recursive Legendre) + // skip over values of `q` already culled in the last partial sieve: + integer qi = floor(q/2)+1; // index of always odd q! + if not composite[qi] then + // since `q` cannot be equal to bp due to cull of bp and above skip; + atom d = bp*q, // `d` is odd product of some combination of odd primes! + // the following computation is essential to the algorithm's speed, + // see the Nim entry for the full details of how this works + dadj = iff(d<=sqrtn ? larges[smalls[half(d)]-nbp+1] + : smalls[half(floor(n/d))]) + ori += 1 + larges[ori] = larges[k]-dadj+nbp // base primes count over subtracted! + // eliminate rough values that have been culled in partial sieve: + // note that `larges` and `roughs` indices relate to each other! + roughs[ori] = q + end if + end for - integer m = mxndx // and adjust `smalls` for latest partial sieve pass... - // this is faster than recounting over the `composite` array for each loop... - for k=(sqrtn/bp-1)||1 to bp by -2 do // k always odd! - // `c` is correction from current count to desired count... - // `e` is end limit index no correction is necessary for current cull... - integer c = smalls[half(k)]-nbp, - e = floor((k*bp)/2) - while m>=e do - -- smalls[m+1] -= c -- (grr, js! [I have a plan, working on it]) - m += 1 - smalls[m] -= c - -- m -= 1 - m -= 2 - end while - end for + integer m = mxndx // and adjust `smalls` for latest partial sieve pass... + // this is faster than recounting over the `composite` array for each loop... + for k=(sqrtn/bp-1)||1 to bp by -2 do // k always odd! + // `c` is correction from current count to desired count... + // `e` is end limit index no correction is necessary for current cull... + integer c = smalls[half(k)]-nbp, + e = floor((k*bp)/2) + while m>=e do + smalls[m+1] -= c + m -= 1 + end while + end for - nbp += 1 // increase number of found base primes - mxri = ori-1 // advance rough index for later - end if - bp += 2 - sqri = (i+i)*(i+1) - i += 1 - end while + nbp += 1 // increase number of found base primes + mxri = ori-1 // advance rough index for later + end if + bp += 2 + sqri = (i+i)*(i+1) + i += 1 + end while - // 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` (erm, - // mxri?) 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!!! - // - and `composite` is never used again! + // 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` (erm, + // mxri?) 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!!! + // - and `composite` is never used again! - // the following does the top-most "phi tree" calculation: - // the answer to here is all valid `phis`, combined here by subtraction, - // + compensate for included odd base prime counts over subracted above: - atom result = larges[1] - sum(larges[2..mxri+1]) - + trunc((mxri+1 + 2*(nbp-1))*mxri/2) - + 1 // include the only even prime, ie 2 + // the following does the top-most "phi tree" calculation: + // the answer to here is all valid `phis`, combined here by subtraction, + // + compensate for included odd base prime counts over subracted above: + atom result = larges[1] - sum(larges[2..mxri+1]) + + trunc((mxri+1 + 2*(nbp-1))*mxri/2) + + 1 // include the only even prime, ie 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 in the Nim entry for how this works... - for ri,p in roughs from 2 do // for all `roughs` (now prime) bar '1': - atom m = trunc(n/p), // `m` is the `p` quotient - // so that the end limit `e` can be calculated based on `n`/(`p`^2) - e = smalls[half(floor(m/p))+1]-nbp+1 - // the following test is equivalent to non-splitting optmization: - if e<=ri then exit end if // quit when no more pairs! - aka stop - // at about `p` of cube root of range! - for k=ri+1 to e do // for all `roughs` greater than `p` to limit: - result += smalls[half(floor(m/roughs[k]))]; - end for - // compensate for all the extra base prime counts just added! - result -= (e-ri)*(nbp+ri-2) - end for - return result - end function + // 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 in the Nim entry for how this works... + for ri,p in roughs from 2 do // for all `roughs` (now prime) bar '1': + atom m = trunc(n/p), // `m` is the `p` quotient + // so that the end limit `e` can be calculated based on `n`/(`p`^2) + e = smalls[half(floor(m/p))+1]-nbp+1 + // the following test is equivalent to non-splitting optmization: + if e<=ri then exit end if // quit when no more pairs! - aka stop + // at about `p` of cube root of range! + for k=ri+1 to e do // for all `roughs` greater than `p` to limit: + result += smalls[half(floor(m/roughs[k]))]; + end for + // compensate for all the extra base prime counts just added! + result -= (e-ri)*(nbp+ri-2) + end for + return result +end function - atom t = time() - constant expected = {0,4,25,168,1229,9592,78498,664579,5761455, - 50847534,455052511,4118054813,37607912018, - 346065536839,3204941750802} - for i=0 to iff(platform()=JS?11:14) do -- (sp: keep js under 2s) - atom c = count_primes(power(10,i)) - assert(c==expected[i+1]) - string e = elapsed(time()-t,0.1," (%s)") - printf(1,"10^%d = %d%s\n",{i,c,e}) - end for - printf(1,"\nTook %s\n",elapsed(time()-t)) - ",b,": ",levenshtein(a,b)); } diff --git a/Task/Linear-congruential-generator/Ada/linear-congruential-generator-1.ada b/Task/Linear-congruential-generator/Ada/linear-congruential-generator-1.adb similarity index 100% rename from Task/Linear-congruential-generator/Ada/linear-congruential-generator-1.ada rename to Task/Linear-congruential-generator/Ada/linear-congruential-generator-1.adb diff --git a/Task/Linear-congruential-generator/Ada/linear-congruential-generator-2.ada b/Task/Linear-congruential-generator/Ada/linear-congruential-generator-2.adb similarity index 100% rename from Task/Linear-congruential-generator/Ada/linear-congruential-generator-2.ada rename to Task/Linear-congruential-generator/Ada/linear-congruential-generator-2.adb diff --git a/Task/Linear-congruential-generator/Ada/linear-congruential-generator-3.ada b/Task/Linear-congruential-generator/Ada/linear-congruential-generator-3.adb similarity index 100% rename from Task/Linear-congruential-generator/Ada/linear-congruential-generator-3.ada rename to Task/Linear-congruential-generator/Ada/linear-congruential-generator-3.adb diff --git a/Task/Linear-congruential-generator/Delphi/linear-congruential-generator.delphi b/Task/Linear-congruential-generator/Delphi/linear-congruential-generator.pas similarity index 100% rename from Task/Linear-congruential-generator/Delphi/linear-congruential-generator.delphi rename to Task/Linear-congruential-generator/Delphi/linear-congruential-generator.pas diff --git a/Task/Linear-congruential-generator/EDSAC-order-code/linear-congruential-generator.edsac b/Task/Linear-congruential-generator/EDSAC-order-code/linear-congruential-generator.edsac index f905a3c8bf..7677c8f4b3 100644 --- a/Task/Linear-congruential-generator/EDSAC-order-code/linear-congruential-generator.edsac +++ b/Task/Linear-congruential-generator/EDSAC-order-code/linear-congruential-generator.edsac @@ -12,12 +12,13 @@ 55 locations, load at even address. Set up to be called with 'G N', so that caller needn't know its address. See Wilkes, Wheeler & Gill, 1951 edition, page 18.] + [2024-12-22 Fixed bug in print subroutine. Did not affect Rosetta Code output.] T 46 K [location corresponding to N parameter] P 72 F [load subroutine at 72] E 25 K TN - GKA3FT42@A47@T31@ADE10@T31@A48@T31@SDTDH44#@NDYFLDT4DS43@TF - H17@S17@A43@G23@UFS43@T1FV4DAFG50@SFLDUFXFOFFFSFL4FT4DA49@T31@ - A1FA43@G20@XFP1024FP610D@524D!FO46@O26@XFO46@SFL8FT4DE39@ + GKA3FT42@A47@T31@ADE10@T31@A48@T31@SDTDH44#@NDYFLDT4DS43@TFH17@ + S17@A43@G23@UFS43@T1FV4DAFG50@SFLDUFXFOFFFSFL4FT4DA49@T31@A1FA43@ + G20@XFT44#ZPFT43ZP1024FP610D@524D!FO46@O26@XFO46@SFL8FT4DE39@ [BSD linear congruential generator. Call with 'G B' to initialize, passing seed in 0D. diff --git a/Task/Linear-congruential-generator/Elixir/linear-congruential-generator.elixir b/Task/Linear-congruential-generator/Elixir/linear-congruential-generator.ex similarity index 100% rename from Task/Linear-congruential-generator/Elixir/linear-congruential-generator.elixir rename to Task/Linear-congruential-generator/Elixir/linear-congruential-generator.ex diff --git a/Task/Linear-congruential-generator/JavaScript/linear-congruential-generator.js b/Task/Linear-congruential-generator/JavaScript/linear-congruential-generator.js new file mode 100644 index 0000000000..59d98de4f1 --- /dev/null +++ b/Task/Linear-congruential-generator/JavaScript/linear-congruential-generator.js @@ -0,0 +1,41 @@ +const mask = (1 << 31) - 1; + +function* randBSD(seed) { + let s = seed; + while (true) { + s = (s * 1103515245 + 12345) & mask; + yield s; + } +} + +function* randMS(seed) { + let s = seed; + while (true) { + s = (s * 214013 + 2531011) & mask; + yield s >> 16; + } +} + +function take(generator, n) { + const result = []; + let count = 0; + for (const value of generator) { + if (count >= n) break; + result.push(value); + count++; + } + return result; +} + +// Main execution +console.log("BSD:"); +const bsdNumbers = take(randBSD(0), 10); +for (const num of bsdNumbers) { + console.log(num); +} + +console.log("\nMS:"); +const msNumbers = take(randMS(0), 10); +for (const num of msNumbers) { + console.log(num); +} diff --git a/Task/Linear-congruential-generator/Julia/linear-congruential-generator.julia b/Task/Linear-congruential-generator/Julia/linear-congruential-generator.jl similarity index 100% rename from Task/Linear-congruential-generator/Julia/linear-congruential-generator.julia rename to Task/Linear-congruential-generator/Julia/linear-congruential-generator.jl diff --git a/Task/Linear-congruential-generator/Kotlin/linear-congruential-generator.kotlin b/Task/Linear-congruential-generator/Kotlin/linear-congruential-generator.kts similarity index 100% rename from Task/Linear-congruential-generator/Kotlin/linear-congruential-generator.kotlin rename to Task/Linear-congruential-generator/Kotlin/linear-congruential-generator.kts diff --git a/Task/Linear-congruential-generator/OCaml/linear-congruential-generator.ocaml b/Task/Linear-congruential-generator/OCaml/linear-congruential-generator.ml similarity index 100% rename from Task/Linear-congruential-generator/OCaml/linear-congruential-generator.ocaml rename to Task/Linear-congruential-generator/OCaml/linear-congruential-generator.ml diff --git a/Task/Linear-congruential-generator/PascalABC.NET/linear-congruential-generator-1.pas b/Task/Linear-congruential-generator/PascalABC.NET/linear-congruential-generator-1.pas new file mode 100644 index 0000000000..5b04eb83e3 --- /dev/null +++ b/Task/Linear-congruential-generator/PascalABC.NET/linear-congruential-generator-1.pas @@ -0,0 +1,21 @@ +var + bsdseed, msseed: int64; + +function bsdrand: cardinal; +begin + bsdseed := (1_103_515_245 * bsdseed + 12_345) and $7fffffff; + bsdrand := bsdseed; +end; + +function msrand: cardinal; +begin + msseed := (214_013 * msseed + 2_531_011) and $ffffffff; + msrand := msseed shr 16; +end; + +begin + writeln(' BSD MS'); + bsdseed := 0; + msseed := 0; + loop 10 do writeln(bsdrand:12, msrand:12); +end. diff --git a/Task/Linear-congruential-generator/PascalABC.NET/linear-congruential-generator-2.pas b/Task/Linear-congruential-generator/PascalABC.NET/linear-congruential-generator-2.pas new file mode 100644 index 0000000000..050110505e --- /dev/null +++ b/Task/Linear-congruential-generator/PascalABC.NET/linear-congruential-generator-2.pas @@ -0,0 +1,29 @@ +function bsdRand(seed: integer): sequence of integer; +begin + while true do + begin + seed := (1_103_515_245 * seed + 12_345) and $7fffffff; + yield seed + end; +end; + +function msvcrtRand(seed: integer): sequence of integer; +begin + while true do + begin + seed := (214_013 * seed + 2_531_011) and $7fffffff; + yield seed shr 16 + end; +end; + +begin + 'BSD with seed = 1'.println; + var iter1 := bsdRand(1); + foreach var val in iter1.Take(10) do + println(val); + println; + 'Microsoft with seed = 0'.Println; + var iter2 := msvcrtRand(0); + foreach var val in iter2.Take(10) do + println(val); +end. diff --git a/Task/Linear-congruential-generator/PowerShell/linear-congruential-generator.psh b/Task/Linear-congruential-generator/PowerShell/linear-congruential-generator.ps1 similarity index 100% rename from Task/Linear-congruential-generator/PowerShell/linear-congruential-generator.psh rename to Task/Linear-congruential-generator/PowerShell/linear-congruential-generator.ps1 diff --git a/Task/Linear-congruential-generator/REXX/linear-congruential-generator.rexx b/Task/Linear-congruential-generator/REXX/linear-congruential-generator.rexx index b1d62ab382..aba7d35f36 100644 --- a/Task/Linear-congruential-generator/REXX/linear-congruential-generator.rexx +++ b/Task/Linear-congruential-generator/REXX/linear-congruential-generator.rexx @@ -1,22 +1,28 @@ -/*REXX program uses a linear congruential generator (LCG) that simulates the old BSD */ -/*──────── and MS random number generators: BSD= 0──►(2^31)-1 MS= 0──►(2^16)-1 */ -numeric digits 20 /*use enough dec. digs for the multiply*/ -two@@16= 2**16 /*use a variable to contain 2^16 */ -two@@31= 2**31 /* " " " " " 2^32 */ +-- 29 Aug 2025 +include Setting - do seed=0 for 2; bsd= seed /*perform for seed=0 and also seed=1.*/ - ms= seed /*assign SEED to two REXX variables.*/ - say center(' seed='seed" ", 79, '─') /*display the seed in a title/separator*/ - /* [↓] show 20 rand #'s for each seed.*/ - do j=1 for 20 /*generate & display 20 random numbers.*/ +say 'LINEAR CONGRUENTIAL GENERATOR' +say version +say +numeric digits 20 +Memo. = 0 +say '-------------------' +say ' n BSD MS' +say '-------------------' +do i = 1 to 10 + say Right(i,2) Right(MSD(),10) Right(MS(),5) +end +say '-------------------' +exit - bsd = (1103515245 * bsd + 12345) // two@@31 - ms = ( 214013 * ms + 2531011) // two@@31 - /* ↑ */ - /* └─────◄──── REXX remainder operator*/ +MSD: +procedure expose Memo. +Memo.msd = (1103515245*Memo.msd+12345)//(2**31) +return Memo.msd - say ' state' right(j,3) " BSD" right(bsd, 11) left('', 13), - " MS" right( ms, 11) left('', 5), - " rand" right(ms % two@@16, 6) - end /*j*/ - end /*seed*/ /*stick a fork in it, we're all done. */ +MS: +procedure expose Memo. +Memo.ms = (214013*Memo.ms+2531011)//(2**31) +return Memo.ms%(2**16) + +include Math diff --git a/Task/Linear-congruential-generator/Rust/linear-congruential-generator.rust b/Task/Linear-congruential-generator/Rust/linear-congruential-generator.rs similarity index 100% rename from Task/Linear-congruential-generator/Rust/linear-congruential-generator.rust rename to Task/Linear-congruential-generator/Rust/linear-congruential-generator.rs diff --git a/Task/Linear-congruential-generator/Scheme/linear-congruential-generator.ss b/Task/Linear-congruential-generator/Scheme/linear-congruential-generator.scm similarity index 100% rename from Task/Linear-congruential-generator/Scheme/linear-congruential-generator.ss rename to Task/Linear-congruential-generator/Scheme/linear-congruential-generator.scm diff --git a/Task/Linear-congruential-generator/Vyxal/linear-congruential-generator.vyxal b/Task/Linear-congruential-generator/Vyxal/linear-congruential-generator.vyxal new file mode 100644 index 0000000000..1249894c0e --- /dev/null +++ b/Task/Linear-congruential-generator/Vyxal/linear-congruential-generator.vyxal @@ -0,0 +1,5 @@ +λ4|→A→C→M→D0 16(←A*←C+←M%:←Dḭ,}}→LCG +`BSD NUMBERS`, +1103515245 12345 2147483648 1←LCG† +`MICROSOFT NUMBERS`, +214013 2531011 2147483648 65536←LCG† diff --git a/Task/List-comprehensions/Ada/list-comprehensions.ada b/Task/List-comprehensions/Ada/list-comprehensions.adb similarity index 100% rename from Task/List-comprehensions/Ada/list-comprehensions.ada rename to Task/List-comprehensions/Ada/list-comprehensions.adb diff --git a/Task/List-comprehensions/D/list-comprehensions.d b/Task/List-comprehensions/D/list-comprehensions.d index 14264ca9b9..5e9699b015 100644 --- a/Task/List-comprehensions/D/list-comprehensions.d +++ b/Task/List-comprehensions/D/list-comprehensions.d @@ -2,11 +2,15 @@ import std.stdio, std.meta, std.range; TA[] select(TA, TI1, TC1, TI2, TC2, TI3, TC3, TP) (lazy TA mapper, + ref TI1 iter1, TC1 items1, ref TI2 iter2, lazy TC2 items2, ref TI3 iter3, lazy TC3 items3, + lazy TP where) { + Appender!(TA[]) result; + auto iters = AliasSeq!(iter1, iter2, iter3); foreach (el1; items1) { @@ -22,13 +26,22 @@ TA[] select(TA, TI1, TC1, TI2, TC2, TI3, TC3, TP) } AliasSeq!(iter1, iter2, iter3) = iters; + return result.data; } void main() { enum int n = 21; + int x, y, z; - auto r = select([x,y,z], x, iota(1,n+1), y, iota(x,n+1), z, - iota(y, n + 1), x*x + y*y == z*z); + auto r = select( + [x,y,z], + + x, iota( 1, n+1), + y, iota(x+1, n+1), + z, iota(y+1, n+1), + + x*x + y*y == z*z + ); writeln(r); } diff --git a/Task/List-comprehensions/DuckDB/list-comprehensions-1.duckdb b/Task/List-comprehensions/DuckDB/list-comprehensions-1.duckdb new file mode 100644 index 0000000000..4c713a0e9f --- /dev/null +++ b/Task/List-comprehensions/DuckDB/list-comprehensions-1.duckdb @@ -0,0 +1,7 @@ +# for x in 1 to n, for y in x+1 to n, for z in y+1 to n +create or replace function xyz(n) as table ( + from range(1,n+1) x(x) + cross join (from range(x+1,n+1) y(y)) + cross join (from range(y+1, n+1) z(z)) + +); diff --git a/Task/List-comprehensions/DuckDB/list-comprehensions-2.duckdb b/Task/List-comprehensions/DuckDB/list-comprehensions-2.duckdb new file mode 100644 index 0000000000..0826ceeb56 --- /dev/null +++ b/Task/List-comprehensions/DuckDB/list-comprehensions-2.duckdb @@ -0,0 +1,6 @@ +create or replace function triples(n) as table ( + from xyz(n) + where x*x + y*y = z*z +); + +from triples(10); diff --git a/Task/List-comprehensions/DuckDB/list-comprehensions-3.duckdb b/Task/List-comprehensions/DuckDB/list-comprehensions-3.duckdb new file mode 100644 index 0000000000..a613ad7de4 --- /dev/null +++ b/Task/List-comprehensions/DuckDB/list-comprehensions-3.duckdb @@ -0,0 +1,4 @@ +create or replace function list_triples(n) as ( + [ xyz FOR xyz IN (select array_agg([x,y,z] order by x) FROM xyz(n)) + IF xyz[1]**2 + xyz[2]**2 = xyz[3]**2 ] +); diff --git a/Task/List-comprehensions/DuckDB/list-comprehensions-4.duckdb b/Task/List-comprehensions/DuckDB/list-comprehensions-4.duckdb new file mode 100644 index 0000000000..3a9d0eebd0 --- /dev/null +++ b/Task/List-comprehensions/DuckDB/list-comprehensions-4.duckdb @@ -0,0 +1,5 @@ +create or replace function list_triples(n) as ( + list_filter( + (select array_agg([x,y,z] order by x) from xyz(n)), + x -> x[1]*x[1] + x[2]*x[2] = x[3]*x[3] ) +); diff --git a/Task/List-comprehensions/DuckDB/list-comprehensions-5.duckdb b/Task/List-comprehensions/DuckDB/list-comprehensions-5.duckdb new file mode 100644 index 0000000000..57c2588f30 --- /dev/null +++ b/Task/List-comprehensions/DuckDB/list-comprehensions-5.duckdb @@ -0,0 +1 @@ +select list_triples(10); diff --git a/Task/List-comprehensions/Icon/list-comprehensions-4.icon b/Task/List-comprehensions/Icon/list-comprehensions-4.icon new file mode 100644 index 0000000000..f04bad1551 --- /dev/null +++ b/Task/List-comprehensions/Icon/list-comprehensions-4.icon @@ -0,0 +1,5 @@ +procedure main(a) + n := !a | 20 + s := [: 1([x := 1 to n, y := x to n, z := y to n], x^2+y^2 = z^2) :] + every b := !s do write(b[1]," ",b[2]," ",b[3]) +end diff --git a/Task/List-comprehensions/JavaScript/list-comprehensions-6.js b/Task/List-comprehensions/JavaScript/list-comprehensions-6.js new file mode 100644 index 0000000000..f90d21d630 --- /dev/null +++ b/Task/List-comprehensions/JavaScript/list-comprehensions-6.js @@ -0,0 +1,35 @@ +(() => { + "use strict"; + + // [(x, y, z) | x <- [1..n], y <- [x..n], z <- [y..n], x ^ 2 + y ^ 2 == z ^ 2] + + const main = () => { + const n = 20; + + return enumFromTo(1)(n).flatMap( + x => enumFromTo(x)(n).flatMap( + y => enumFromTo(y)(n).flatMap( + z => x ** 2 + y ** 2 === z ** 2 + ? [[x, y, z]] + : [] + ) + ) + ); + }; + + + + // --------------------- GENERIC --------------------- + + // enumFromTo :: Int -> Int -> [Int] + const enumFromTo = m => + // Enumeration of the integers from m to n. + n => Array.from( + { length: 1 + n - m }, + (_, i) => m + i + ); + + + // MAIN --- + return JSON.stringify(main()); +})(); diff --git a/Task/List-comprehensions/Julia/list-comprehensions-1.julia b/Task/List-comprehensions/Julia/list-comprehensions-1.jl similarity index 100% rename from Task/List-comprehensions/Julia/list-comprehensions-1.julia rename to Task/List-comprehensions/Julia/list-comprehensions-1.jl diff --git a/Task/List-comprehensions/Julia/list-comprehensions-2.julia b/Task/List-comprehensions/Julia/list-comprehensions-2.jl similarity index 100% rename from Task/List-comprehensions/Julia/list-comprehensions-2.julia rename to Task/List-comprehensions/Julia/list-comprehensions-2.jl diff --git a/Task/List-comprehensions/Julia/list-comprehensions-3.julia b/Task/List-comprehensions/Julia/list-comprehensions-3.jl similarity index 100% rename from Task/List-comprehensions/Julia/list-comprehensions-3.julia rename to Task/List-comprehensions/Julia/list-comprehensions-3.jl diff --git a/Task/List-comprehensions/Kotlin/list-comprehensions.kotlin b/Task/List-comprehensions/Kotlin/list-comprehensions.kts similarity index 100% rename from Task/List-comprehensions/Kotlin/list-comprehensions.kotlin rename to Task/List-comprehensions/Kotlin/list-comprehensions.kts diff --git a/Task/List-comprehensions/Maxima/list-comprehensions.maxima b/Task/List-comprehensions/Maxima/list-comprehensions.maxima new file mode 100644 index 0000000000..b27746a990 --- /dev/null +++ b/Task/List-comprehensions/Maxima/list-comprehensions.maxima @@ -0,0 +1,3 @@ +makelist(i^2, i, 1, 10); + +sublist(create_list([i^2, j^2, k^2], i, 1, 20, j, 1, 20, k, 1, 20), lambda([l], l[1]+l[2]=l[3])); diff --git a/Task/List-comprehensions/OCaml/list-comprehensions-1.ocaml b/Task/List-comprehensions/OCaml/list-comprehensions-1.ml similarity index 100% rename from Task/List-comprehensions/OCaml/list-comprehensions-1.ocaml rename to Task/List-comprehensions/OCaml/list-comprehensions-1.ml diff --git a/Task/List-comprehensions/OCaml/list-comprehensions-2.ocaml b/Task/List-comprehensions/OCaml/list-comprehensions-2.ml similarity index 100% rename from Task/List-comprehensions/OCaml/list-comprehensions-2.ocaml rename to Task/List-comprehensions/OCaml/list-comprehensions-2.ml diff --git a/Task/List-comprehensions/OCaml/list-comprehensions-3.ocaml b/Task/List-comprehensions/OCaml/list-comprehensions-3.ml similarity index 100% rename from Task/List-comprehensions/OCaml/list-comprehensions-3.ocaml rename to Task/List-comprehensions/OCaml/list-comprehensions-3.ml diff --git a/Task/List-comprehensions/PascalABC.NET/list-comprehensions.pas b/Task/List-comprehensions/PascalABC.NET/list-comprehensions.pas new file mode 100644 index 0000000000..c3820b8e57 --- /dev/null +++ b/Task/List-comprehensions/PascalABC.NET/list-comprehensions.pas @@ -0,0 +1,2 @@ +## +(1..20).CartesianPower(3).Where(\(x,y,z) -> (x*x + y*y = z*z) and (x < y)).tolist.PrintLines diff --git a/Task/List-comprehensions/Phix/list-comprehensions-1.phix b/Task/List-comprehensions/Phix/list-comprehensions-1.phix index ea719a935a..8ca7411e5a 100644 --- a/Task/List-comprehensions/Phix/list-comprehensions-1.phix +++ b/Task/List-comprehensions/Phix/list-comprehensions-1.phix @@ -1,12 +1,4 @@ -(phixonline)--> - global function new_dict(integer pool_only=0) - global procedure destroy_dict(integer tid, integer justclear=0) - global procedure setd(object key, object data, integer tid=1) - global function getd(object key, integer tid=1) - global procedure destroy_dict(integer tid, integer justclear=0) - global function getd_index(object key, integer tid=1) - global function getd_by_index(integer node, integer tid=1) - global procedure deld(object key, integer tid=1) - global procedure traverse_dict(integer rid, object user_data=0, integer tid=1) - global function dict_size(integer tid=1) - - -- demo\rosetta\List_comprehensions.exw - with javascript_semantics - function list_comprehension(sequence s, integer rid, integer k, integer level=1, sequence args={}) - sequence res = {} - args &= 0 - for i=1 to length(s) do - args[$] = s[i] - if level<k then - res &= list_comprehension(s,rid,k,level+1,deep_copy(args)) - else - res &= call_func(rid,args) - end if - end for - return res - end function +-- demo\rosetta\List_comprehensions.exw +with javascript_semantics +function list_comprehension(sequence s, integer rid, k, level=1, sequence args={}) + sequence res = {} + args &= 0 + for i=1 to length(s) do + args[$] = s[i] + if levelfunction
    triangle(integer a, b, c) - if a<b and a*a+b*b=c*c then - return {{a,b,c}} - end if - return {} - end function +function triangle(integer a, b, c) + if a?
    list_comprehension(tagset(20),routine_id("triangle"),3) - - with javascript_semantics - atom t0 = time() - sequence list = {1}, - offset = repeat(0,32) - offset[1..2] = 1 - - function show(integer t, l) - string res = repeat('?',l) - integer level = 0 - for i=l to 1 by -1 do - integer r2 = remainder(t,2) - res[i] = "[}(]{)"[mod(level-r2,6)+1] - level += r2*4-2 - t = floor(t/2) - end for - if level!=0 then ?9/0 end if - return res - end function - - procedure listTrees(integer n) - for i:=offset[n+1]+1 to offset[n+2] do - printf(1,"%s\n",{show(list[i], n*2)}) - end for - end procedure - - procedure assemble(atom t, integer n, sl, pos, rem) - -- - -- assemble tree from subtrees - -- t: assembled parts so far - -- n: length of tree we want to make - -- sl: length of subtree we are looking at - -- pos: offset of subtree we are looking at - -- rem: remaining length to be put together - -- - if rem == 0 then - list = append(list, t*2+1) - else - if sl>rem then -- need smaller sub-trees - sl = rem - pos = offset[sl+1] - elsif pos>=offset[sl+2] then - -- used up sl-trees, try smaller ones - if sl == 1 then return end if - pos = offset[sl] - sl -= 1 - end if - - atom u = or_bits(t*power(2,2*sl),list[pos+1]) - assemble(u, n, sl, pos, rem-sl) - assemble(t, n, sl, pos+1, rem) - end if - end procedure - - procedure mktrees(integer n) - if offset[n+2]=0 then - if n>0 then - mktrees(n - 1) - end if - assemble(0, n, n-1, offset[n], n-1) - offset[n+2] = length(list) - end if - end procedure - - procedure main(integer n) - mktrees(n) - atom nt = offset[n+2]-offset[n+1], - td = time()-t0 - string e = iff(td>0.1?" ("&elapsed(td)&")":"") - printf(1,"Number of %d-trees: %,d%s\n", {n, nt, e}) - if n<=5 then listTrees(n) end if - end procedure - for i=0 to iff(platform()=JS?12:20) do - main(i) - end for - - with javascript_semantics - function week_number(integer y,m,d) - integer doy = day_of_year(y,m,d), - dow = day_of_week(y,m,d), - week = floor((doy-dow+10)/7) - return week - end function +with javascript_semantics +function week_number(integer y,m,d) + integer doy = day_of_year(y,m,d), + dow = day_of_week(y,m,d), + week = floor((doy-dow+10)/7) + return week +end function +--/* -- or: (same results) +constant Thursday = 4 +function long_year(integer y) + return day_of_week(y,1,1)=Thursday + or day_of_week(y,12,31)=Thursday +end function +--*/ - for c=20 to 22 do - sequence long_years = {} - integer century = (c-1)*100 - for year=century to century+99 do - if week_number(year,12,28)=53 then - long_years &= year - end if - end for - printf(1,"Long years in the %d%s century:%v\n", {c,ord(c),long_years}) - end for - \"",lcs(s1,s2),"\"") +end diff --git a/Task/Longest-common-substring/Icon/longest-common-substring-2.icon b/Task/Longest-common-substring/Icon/longest-common-substring-2.icon new file mode 100644 index 0000000000..d4e828cfee --- /dev/null +++ b/Task/Longest-common-substring/Icon/longest-common-substring-2.icon @@ -0,0 +1,19 @@ +procedure main(A) + s1 := \A[1] | "thisisatest" + s2 := \A[2] | "testing123testing" + write(s1) + write(s2) + write("---") + write(lcs(s1,s2)) +end + +procedure lcs(s1,s2) + lc := "" + s1 ? every (tab(upto(s2)), c1 := move(1), cs:="") do { + while p2 := upto(c1, s2) do + while (c1 == s2[p2]) | break break do + (cs ||:= c1, p2 +:= 1, c1 := move(1)) + if *cs > *lc then lc := cs + } + return lc +end diff --git a/Task/Longest-common-substring/Julia/longest-common-substring.julia b/Task/Longest-common-substring/Julia/longest-common-substring.jl similarity index 100% rename from Task/Longest-common-substring/Julia/longest-common-substring.julia rename to Task/Longest-common-substring/Julia/longest-common-substring.jl diff --git a/Task/Longest-common-substring/Kotlin/longest-common-substring.kotlin b/Task/Longest-common-substring/Kotlin/longest-common-substring.kts similarity index 100% rename from Task/Longest-common-substring/Kotlin/longest-common-substring.kotlin rename to Task/Longest-common-substring/Kotlin/longest-common-substring.kts diff --git a/Task/Longest-common-substring/Langur/longest-common-substring.langur b/Task/Longest-common-substring/Langur/longest-common-substring.langur index 8cb9c31797..368bb54b25 100644 --- a/Task/Longest-common-substring/Langur/longest-common-substring.langur +++ b/Task/Longest-common-substring/Langur/longest-common-substring.langur @@ -1,16 +1,16 @@ -val .lcs = fn(.s1, .s2) { - var .l, .r, .sublen = 1, 0, 0 - for .i of .s1 { - for .j in .i .. len(.s1) { - if not matching(s2s(.s1, .i .. .j), .s2): break - if .sublen <= .j - .i { - .l, .r = .i, .j - .sublen = .j - .i +val lcs = fn(s1, s2) { + var l, r, sublen = 1, 0, 0 + for i of s1 { + for j in i .. len(s1) { + if not matching(s2, by=s2s(s1, of=i .. j)): break + if sublen <= j - i { + l, r = i, j + sublen = j - i } } } - if .r == 0: return "" - s2s .s1, .l .. .r + if r == 0: return "" + s2s s1, of=l .. r } -writeln .lcs("thisisatest", "testing123testing") +writeln lcs("thisisatest", "testing123testing") diff --git a/Task/Longest-common-substring/PascalABC.NET/longest-common-substring.pas b/Task/Longest-common-substring/PascalABC.NET/longest-common-substring.pas new file mode 100644 index 0000000000..44f677a397 --- /dev/null +++ b/Task/Longest-common-substring/PascalABC.NET/longest-common-substring.pas @@ -0,0 +1,21 @@ +## +function lcs(s1, s2: string): String; +begin + var l := 1; + var r := 0; + var sub_len := 0; + for var i := 1 to s1.length do + foreach var j in (i..s1.length) do + begin + if s2.contains(s1[i:j + 1]) then + if sub_len <= j - i then + begin + (l, r) := (i, j); + sub_len := j - i; + end + else break + end; + result := s1[l:r + 1]; +end; + +lcs('thisisatest', 'testing123testing').println; diff --git a/Task/Longest-common-substring/Phix/longest-common-substring.phix b/Task/Longest-common-substring/Phix/longest-common-substring.phix index 057d273881..a12710d962 100644 --- a/Task/Longest-common-substring/Phix/longest-common-substring.phix +++ b/Task/Longest-common-substring/Phix/longest-common-substring.phix @@ -1,26 +1,25 @@ -(phixonline)--> - function lcs(string a, b) - integer longest = 0 - string best = "" - for i=1 to length(a) do - integer ch = a[i] - for j=1 to length(b) do - if ch=b[j] then - integer n=1 - while i+n<=length(a) - and j+n<=length(b) - and a[i+n]=b[j+n] do - n += 1 - end while - if n>longest then - longest = n - best = a[i..i+n-1] - end if - end if - end for - end for - return best - end function - ?lcs("thisisatest", "testing123testing") - ?lcs("testing123testing","thisisatest") - - with javascript_semantics - function lis(sequence x, integer n = length(x)) - sequence p = repeat(0,n), - m = repeat(0,n) - integer len = 0 - for i=1 to n do - integer lo = 1 - integer hi = len - while lo<=hi do - integer mid = ceil((lo+hi)/2) - if x[m[mid]]<x[i] then - lo = mid + 1 - else - hi = mid - 1 - end if - end while - if lo>1 then - p[i] = m[lo-1] - end if - m[lo] = i - if lo>len then len = lo end if - end for - sequence res = repeat(0,len) - if len>0 then - integer k = m[len] - for i=len to 1 by -1 do - res[i] = x[k] - k = p[k] - end for - end if - return res - end function +with javascript_semantics +function lis(sequence x, integer n = length(x)) + sequence p = repeat(0,n), + m = repeat(0,n) + integer len = 0 + for i=1 to n do + integer lo = 1 + integer hi = len + while lo<=hi do + integer mid = ceil((lo+hi)/2) + if x[m[mid]]1 then + p[i] = m[lo-1] + end if + m[lo] = i + if lo>len then len = lo end if + end for + sequence res = repeat(0,len) + if len>0 then + integer k = m[len] + for i=len to 1 by -1 do + res[i] = x[k] + k = p[k] + end for + end if + return res +end function - constant tests = {{3, 2, 6, 4, 5, 1}, - {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}} - for i=1 to length(tests) do - ?lis(tests[i]) - end for - - with javascript_semantics - --integer fn = open(command_line()[2],"r") -- (reading the source file) - sequence fn = unix_dict()[1..40]&-1 +with javascript_semantics +--integer fn = open(command_line()[2],"r") -- (reading the source file) +sequence fn = unix_dict()[1..40]&-1 - function allx(string line) - line[1..-1] = 'x' - return line - end function +function allx(string line) + line[1..-1] = 'x' + return line +end function - function longest(string mask) - -- object line = gets(fn) - object line = fn[1]; fn = fn[2..$]; - if atom(line) then return mask end if - string newmask = allx(line) - if not match(mask,newmask) then return longest(mask) end if - mask = longest(newmask) - if match(mask,newmask) then - -- puts(1,line) - printf(1,"%s\n",line) - end if - return mask - end function +function longest(string mask) +-- object line = gets(fn) + object line = fn[1]; fn = fn[2..$]; + if atom(line) then return mask end if + string newmask = allx(line) + if not match(mask,newmask) then return longest(mask) end if + mask = longest(newmask) + if match(mask,newmask) then +-- puts(1,line) + printf(1,"%s\n",line) + end if + return mask +end function - {} = longest("x") +{} = longest("x") - --close(fn) - - function longest(integer l) - object line = gets(fn) - if line=-1 then return l end if - if l>length(line) then return longest(l) end if - l = longest(length(line)) - if l=length(line) then - puts(1,line) - end if - return l - end function +function longest(integer l) + object line = gets(fn) + if line=-1 then return l end if + if l>length(line) then return longest(l) end if + l = longest(length(line)) + if l=length(line) then + puts(1,line) + end if + return l +end function - {} = longest(0) -") + write("\tRun-time error ", &errornumber) + write("\t",&errortext) + write("\toffending value: ", image(&errorvalue)) + errorclear() + }else{ + &error := 0 + if *elements ~= 0 then write(" = ",seqimage(elements)) + else write(" (no result)") + } + } +end + +procedure seqimage(L) + every result := "" & result ||:= image(!L) || ", " + return result[1:-2] +end diff --git a/Task/Loops-Wrong-ranges/JavaScript/loops-wrong-ranges.js b/Task/Loops-Wrong-ranges/JavaScript/loops-wrong-ranges.js new file mode 100644 index 0000000000..31baf72882 --- /dev/null +++ b/Task/Loops-Wrong-ranges/JavaScript/loops-wrong-ranges.js @@ -0,0 +1,29 @@ +function looptest(start, stop, step) { + let a = []; + try { + for(let i = start; i <= stop; i += step) { + a.push(i); + if (a.length == 10) { + break; + } + } + return a; + } catch { + return "Not allowed"; + } +} + +let test_cases = {"Normal": [-2, 2, 1], + "Zero step": [-2, 2, 0], + "Steps away from stop value": [-2, 2, -1], + "Step value > stop value": [-2, 2, 10], + "Start > stop, positive step": [2, -2, 1], + "Start = stop, positive step": [2, 2, 1], + "Start = stop, negative step": [2, 2, -1], + "Start = stop, zero step": [2, 2, 0], + "Start, stop, step all zero": [0, 0, 0]} + +for (const property in test_cases) { + let result = looptest(...test_cases[property]); + console.log(`${property}: ${result} ${result.length == 10 ? "(loops forever)" : ""}`); +} diff --git a/Task/Loops-Wrong-ranges/Julia/loops-wrong-ranges.julia b/Task/Loops-Wrong-ranges/Julia/loops-wrong-ranges.jl similarity index 100% rename from Task/Loops-Wrong-ranges/Julia/loops-wrong-ranges.julia rename to Task/Loops-Wrong-ranges/Julia/loops-wrong-ranges.jl diff --git a/Task/Loops-Wrong-ranges/Kotlin/loops-wrong-ranges.kotlin b/Task/Loops-Wrong-ranges/Kotlin/loops-wrong-ranges.kts similarity index 100% rename from Task/Loops-Wrong-ranges/Kotlin/loops-wrong-ranges.kotlin rename to Task/Loops-Wrong-ranges/Kotlin/loops-wrong-ranges.kts diff --git a/Task/Loops-Wrong-ranges/Langur/loops-wrong-ranges.langur b/Task/Loops-Wrong-ranges/Langur/loops-wrong-ranges.langur index 7d224fefcf..a5e20e4e49 100644 --- a/Task/Loops-Wrong-ranges/Langur/loops-wrong-ranges.langur +++ b/Task/Loops-Wrong-ranges/Langur/loops-wrong-ranges.langur @@ -1,4 +1,4 @@ -val .data = qs:block END +val data = qs:block END start stop increment comment -2 2 1 Normal -2 2 0 Zero increment @@ -11,21 +11,22 @@ val .data = qs:block END 0 0 0 Start equal stop equal zero: zero increment END -var .table = submatches(RE/([^ ]+) +([^ ]+) +([^ ]+) +(.+)\n?/, .data) +# Process data string into table. +# We could have just started with a list of lists, of course. +var table = submatches(data, by=RE/([^ ]+) +([^ ]+) +([^ ]+) +(.+)\n?/) -val .f = fn(.x) number .x -for .i in 2..len(.table) { - .table[.i] = map [.f, .f, .f, _], .table[.i] +for i in 2..len(table) { + table[i] = map(table[i], by=[number, number, number, _]) } -for .test in rest(.table) { - val .start, .stop, .inc, .comment = .test +for test in less(table, of=1) { + val start, stop, inc, comment = test { - val .series = series(.start .. .stop, .inc) + val s = series(start .. stop, inc=inc) catch { - writeln $"\.comment;\nERROR: \._err["msg"]:L200(...);\n" + writeln "{{comment}}\nERROR: {{_err'msg:L200(...)}}\n" } else { - writeln $"\.comment;\nresult: \.series;\n" + writeln "{{comment}}\nresult: {{s}}\n" } } } diff --git a/Task/Loops-Wrong-ranges/PascalABC.NET/loops-wrong-ranges.pas b/Task/Loops-Wrong-ranges/PascalABC.NET/loops-wrong-ranges.pas new file mode 100644 index 0000000000..2071d0b607 --- /dev/null +++ b/Task/Loops-Wrong-ranges/PascalABC.NET/loops-wrong-ranges.pas @@ -0,0 +1,15 @@ +procedure DisplayRange(first, last, step: integer); +begin + Print($'({first,2}, {last,2}, {step,2}): '); + if step = 0 then + Println('not allowed') + else Println(Range(first, last, step)); +end; + +begin + var ranges := |(-2, 2, 1), (-2, 2, 0), (-2, 2, -1), + (-2, 2, 10), (2, -2, 1), (2, 2, 1), + (2, 2, -1), (2, 2, 0), (0, 0, 0)|; + foreach var (f, l, s) in ranges do + DisplayRange(f,l,s); +end. diff --git a/Task/Loops-Wrong-ranges/Pluto/loops-wrong-ranges.pluto b/Task/Loops-Wrong-ranges/Pluto/loops-wrong-ranges.pluto new file mode 100644 index 0000000000..d447208393 --- /dev/null +++ b/Task/Loops-Wrong-ranges/Pluto/loops-wrong-ranges.pluto @@ -0,0 +1,19 @@ +local function loop(start, stop, inc) + local f = "{%3d %3d %3d} -> " + io.write(string.format(f, start, stop, inc)) + local count = 0 + local limit = 10 + local i = start + while i <= stop do + io.write(string.format("%3d ", i)) + if ++count == limit then break end + i += inc + end + print() +end + +local tests = { + {-2, 2, 1}, {-2, 2, 0}, {-2, 2, -1}, {-2, 2, 10}, {2, -2, 1}, + { 2, 2, 1}, { 2, 2, -1}, { 2, 2, 0}, { 0, 0, 0} +} +for tests as test do loop(test[1], test[2], test[3]) end diff --git a/Task/Loops-Wrong-ranges/Python/loops-wrong-ranges.py b/Task/Loops-Wrong-ranges/Python/loops-wrong-ranges.py index debcbd4ef8..3046697673 100644 --- a/Task/Loops-Wrong-ranges/Python/loops-wrong-ranges.py +++ b/Task/Loops-Wrong-ranges/Python/loops-wrong-ranges.py @@ -5,16 +5,16 @@ from itertools import islice # To limit execution if it would generate huge valu data = ''' -start stop increment Comment --2 2 1 Normal --2 2 0 Zero increment --2 2 -1 Increments away from stop value --2 2 10 First increment is beyond stop value -2 -2 1 Start more than stop: positive increment -2 2 1 Start equal stop: positive increment -2 2 -1 Start equal stop: negative increment -2 2 0 Start equal stop: zero increment -0 0 0 Start equal stop equal zero: zero increment +start stop increment Comment +-2 2 1 Normal +-2 2 0 Zero increment +-2 2 -1 Increments away from stop value +-2 2 10 First increment is beyond stop value +2 -2 1 Start more than stop: positive increment +2 2 1 Start equal stop: positive increment +2 2 -1 Start equal stop: negative increment +2 2 0 Start equal stop: zero increment +0 0 0 Start equal stop equal zero: zero increment ''' table = [re.split(r'\s\s+', line.strip()) for line in data.strip().split('\n')] diff --git a/Task/Loops-Wrong-ranges/Rebol/loops-wrong-ranges.rebol b/Task/Loops-Wrong-ranges/Rebol/loops-wrong-ranges.rebol new file mode 100644 index 0000000000..07fea975ec --- /dev/null +++ b/Task/Loops-Wrong-ranges/Rebol/loops-wrong-ranges.rebol @@ -0,0 +1,30 @@ +Rebol [ + title: "Rosetta code: Loops/Wrong ranges" + file: %Loops-Wrong_ranges.r3 + url: https://rosettacode.org/wiki/Loops/Wrong_ranges + needs: 3.0.0 +] +make-range: function [start end step][ + res: copy [] + if zero? step [return none] + for i start end step [ + append res i + ] +] +foreach [start end step] [ + -2 2 1 ;Normal + -2 2 0 ;Zero increment + -2 2 -1 ;Increments away from stop value + -2 2 10 ;First increment is beyond stop value + 2 -2 1 ;Start more than stop: positive increment + 2 2 1 ;Start equal stop: positive increment + 2 2 -1 ;Start equal stop: negative increment + 2 2 0 ;Start equal stop: zero increment + 0 0 0 ;Start equal stop equal zero: zero incremen +][ + ;; Using format to pad numbers + prin format ["make-range" -3 -3 -3] reduce [start end step] + prin " ;== " + ;; Output 'make-range' function result + probe make-range start end step +] diff --git a/Task/Lucas-Lehmer-test/Ada/lucas-lehmer-test.ada b/Task/Lucas-Lehmer-test/Ada/lucas-lehmer-test.adb similarity index 100% rename from Task/Lucas-Lehmer-test/Ada/lucas-lehmer-test.ada rename to Task/Lucas-Lehmer-test/Ada/lucas-lehmer-test.adb diff --git a/Task/Lucas-Lehmer-test/Crystal/lucas-lehmer-test.crystal b/Task/Lucas-Lehmer-test/Crystal/lucas-lehmer-test.cr similarity index 100% rename from Task/Lucas-Lehmer-test/Crystal/lucas-lehmer-test.crystal rename to Task/Lucas-Lehmer-test/Crystal/lucas-lehmer-test.cr diff --git a/Task/Lucas-Lehmer-test/Delphi/lucas-lehmer-test.delphi b/Task/Lucas-Lehmer-test/Delphi/lucas-lehmer-test.pas similarity index 100% rename from Task/Lucas-Lehmer-test/Delphi/lucas-lehmer-test.delphi rename to Task/Lucas-Lehmer-test/Delphi/lucas-lehmer-test.pas diff --git a/Task/Lucas-Lehmer-test/Elixir/lucas-lehmer-test.elixir b/Task/Lucas-Lehmer-test/Elixir/lucas-lehmer-test.elixir deleted file mode 100644 index e38483939e..0000000000 --- a/Task/Lucas-Lehmer-test/Elixir/lucas-lehmer-test.elixir +++ /dev/null @@ -1,14 +0,0 @@ -defmodule LucasLehmer do - use Bitwise - def test do - for p <- 2..1300, p==2 or s(bsl(1,p)-1, p-1)==0, do: IO.write "M#{p} " - end - - defp s(mp, 1), do: rem(4, mp) - defp s(mp, n) do - x = s(mp, n-1) - rem(x*x-2, mp) - end -end - -LucasLehmer.test diff --git a/Task/Lucas-Lehmer-test/Elixir/lucas-lehmer-test.ex b/Task/Lucas-Lehmer-test/Elixir/lucas-lehmer-test.ex new file mode 100644 index 0000000000..d606ae3fd8 --- /dev/null +++ b/Task/Lucas-Lehmer-test/Elixir/lucas-lehmer-test.ex @@ -0,0 +1,14 @@ +defmodule LucasLehmer do + import Bitwise + def test do + for p <- 2..1300, p==2 or s(bsl(1,p)-1, p-1)==0, do: IO.write "M#{p} " + end + + defp s(mp, 1), do: rem(4, mp) + defp s(mp, n) do + x = s(mp, n-1) + rem(x*x-2, mp) + end +end + +LucasLehmer.test diff --git a/Task/Lucas-Lehmer-test/FutureBasic/lucas-lehmer-test.basic b/Task/Lucas-Lehmer-test/FutureBasic/lucas-lehmer-test.basic new file mode 100644 index 0000000000..a108a5f0ab --- /dev/null +++ b/Task/Lucas-Lehmer-test/FutureBasic/lucas-lehmer-test.basic @@ -0,0 +1,204 @@ +// ------------------------------------------------------------ +// Lucas–Lehmer Mersenne prime tester +// Using FutureBasic 7.0.37 +// +// November 2025, R.W. +// ------------------------------------------------------------ + +include "gmp.incl" + +// ------------------------------------------------------------ +// Lucas–Lehmer Mersenne prime tester +// ------------------------------------------------------------ + +CFTimeInterval tim + +// Global mpz_t bigints reused everywhere +mpz_t ts // Lucas–Lehmer state ts +mpz_t mp, mp_minus1 +mpz_t tmp // scratch for reduction +unsigned long gN // last exponent tested (for [Next]) +long gCount + +// ------------------------------------------------------------ +// Init / clear big integers +// ------------------------------------------------------------ +local fn InitBigInts + long maxBits + maxBits = 120000 // enough for p up to ~100k + mpz_init2( ts, maxBits ) + mpz_init2( mp, maxBits ) + mpz_init2( mp_minus1, maxBits ) + mpz_init2( tmp, maxBits ) +end fn + +local fn ClearBigInts + mpz_clear( ts ) + mpz_clear( mp ) + mpz_clear( mp_minus1 ) + mpz_clear( tmp ) +end fn + +// ------------------------------------------------------------ +// Small 32-bit primality test for exponents p +// ------------------------------------------------------------ +local fn IsPrime32( n as unsigned long ) as boolean + unsigned long d + // quick filter/rejects + if n < 2 then return _False + if n == 2 then return _True + // even = composite + if ( n AND 1 ) == 0 then return _False + d = 3 + while d * d <= n + if ( n MOD d ) == 0 then return _False + d = d + 2 + wend +end fn = _true + +// ------------------------------------------------------------ +// IsMersennePrime_LL +// Lucas–Lehmer test for M_p = 2^p − 1 +// Returns _true if M_p is prime +// ------------------------------------------------------------ + +local fn IsMersennePrime_LL( p as unsigned long ) as boolean + unsigned long k + // quick filter/rejects + if p == 2 then return _True + if p < 2 then return _False + // no even exponents (except the handled p = 2) + if ( p AND 1 ) == 0 then return _False + // exponent itself must be prime + if fn IsPrime32( p ) == _false then return _False + // build M_p = 2^p − 1 + mpz_set_ui( mp_minus1, 1 ) + mpz_mul_2exp( mp_minus1, mp_minus1, p ) // mp_minus1 = 1 << p + mpz_sub_ui( mp_minus1, mp_minus1, 1 ) // Mp = 2^p - 1 + // Lucas–Lehmer sequence: + mpz_set_ui( ts, 4 ) + k = 0 + // s = 4; repeat p−2 times: s = s^2 − 2 (mod M_p) + while k < p - 2 + mpz_mul( ts, ts, ts ) // s = s^2 + mpz_sub_ui( ts, ts, 2 ) // s -= 2 + mpz_mod( ts, ts, mp_minus1 ) // s = s mod M_p + k++ + wend + if fn mpz_cmp_ui( ts, 0 ) == 0 then return _True +end fn = _False + +// ------------------------------------------------------------ +// LL_More +// Scan upward from gN until the next M_p is found +// ------------------------------------------------------------ + +void local fn LL_More + CFStringRef pline + boolean iterating + unsigned long i + + tim = fn CACurrentMediaTime + + iterating = _true + // start from the next exponent after gN + i = gN + 1 + // ensure we start from a valid candidate: + if i <= 2 + i = 2 + else + if ( i AND 1 ) == 0 + i++ + end if + end if + + while iterating + if fn IsMersennePrime_LL( i ) + gCount++ + //pline = fn StringWithFormat( @"M%lu", i ) + pline = fn StringWithFormat(@"%4lu M%lu", gCount, i) + print pline; + printf @" (%.3f secs)", ( fn CACurrentMediaTime - tim ) + iterating = _false + end if + // advance to next candidate exponent + if i == 2 + i = 3 + else + i = i + 2 + end if + wend + // remember last exponent tested so [Next] continues from here + if i >= 3 + gN = i - 2 + else + gN = i + end if +end fn + +// ------------------------------------------------------------ +// Compute Mersenne primes up to an initial exponent gN +// ------------------------------------------------------------ +local fn Lucas_LehmerMP + unsigned long i + + fn InitBigInts + + print @"\nMersenne primes found with Lucas–Lehmer:\n" + + // initial exponent limit for the first scan + gN = 5000 + gCount = 0 + + tim = fn CACurrentMediaTime + // handle p = 2 separately + if gN >= 2 + gCount++ + i = 2 + printf @"%4lu M%lu", gCount, i + end if + + // scan odd exponents 3..gN + i = 3 + while i <= gN + if fn IsMersennePrime_LL( i ) + gCount++ + printf @"%4lu M%lu", gCount, i + end if + i = i + 2 + wend + + printf @"\nElapsed time: %.3f secs", ( fn CACurrentMediaTime - tim ) + print @"\nClick [Next] for the next exponents.\n" +end fn + +// ------------------------------------------------------------ +// Dialog handler +// ------------------------------------------------------------ +void local fn DoDialog( ev as long, tag as long, wnd as long, obj as CFTypeRef ) + select ev + case _btnClick + select tag + case 2 + fn LL_More + end select + + case _windowShouldClose + fn ClearBigInts + end + end select +end fn + +on dialog fn DoDialog + +// ------------------------------------------------------------ +// Main +// ------------------------------------------------------------ +window 1, @"Lucas–Lehmer Test", ( 0, 0, 620, 500 ) +button 2, YES,, @"Next", ( 500, 20, 100, 20 ),,, 1 + +fn Lucas_LehmerMP + +HandleEvents + +// diff --git a/Task/Lucas-Lehmer-test/Julia/lucas-lehmer-test.julia b/Task/Lucas-Lehmer-test/Julia/lucas-lehmer-test.jl similarity index 100% rename from Task/Lucas-Lehmer-test/Julia/lucas-lehmer-test.julia rename to Task/Lucas-Lehmer-test/Julia/lucas-lehmer-test.jl diff --git a/Task/Lucas-Lehmer-test/Kotlin/lucas-lehmer-test.kotlin b/Task/Lucas-Lehmer-test/Kotlin/lucas-lehmer-test.kts similarity index 100% rename from Task/Lucas-Lehmer-test/Kotlin/lucas-lehmer-test.kotlin rename to Task/Lucas-Lehmer-test/Kotlin/lucas-lehmer-test.kts diff --git a/Task/Lucas-Lehmer-test/Langur/lucas-lehmer-test.langur b/Task/Lucas-Lehmer-test/Langur/lucas-lehmer-test.langur index 48ba9c07fe..102f27ee1f 100644 --- a/Task/Lucas-Lehmer-test/Langur/lucas-lehmer-test.langur +++ b/Task/Lucas-Lehmer-test/Langur/lucas-lehmer-test.langur @@ -1,15 +1,16 @@ -val .isPrime = fn(.i) .i == 2 or - .i > 2 and not any(fn(.x) .i div .x, - pseries 2 .. .i ^/ 2) +val isPrime = fn(i number) { + i == 2 or i > 2 and + not any(series(2 .. i ^/ 2, asconly=true), by=fn(x) { i div x }) +} -val .isMersennePrime = fn(.p) { - if .p == 2: return true - if not .isPrime(.p): return false +val isMersennePrime = fn(p number) { + if p == 2: return true + if not isPrime(p): return false - val .mp = 2 ^ .p - 1 - for[.s=4] of 3 .. .p { - .s = (.s ^ 2 - 2) rem .mp + val mp = 2 ^ p - 1 + for[s=4] of 3 .. p { + s = (s ^ 2 - 2) rem mp } == 0 } -writeln join " ", map fn(.x) $"M\.x;", filter .isMersennePrime, series 2300 +writeln join(map(filter(series(2300), by=isMersennePrime), by=fn(x) { "M{{x}}" }), delim=" ") diff --git a/Task/Lucas-Lehmer-test/PascalABC.NET/lucas-lehmer-test.pas b/Task/Lucas-Lehmer-test/PascalABC.NET/lucas-lehmer-test.pas new file mode 100644 index 0000000000..61401fd11e --- /dev/null +++ b/Task/Lucas-Lehmer-test/PascalABC.NET/lucas-lehmer-test.pas @@ -0,0 +1,33 @@ +function isMersennePrime(p: integer): boolean; +begin + if (p mod 2 = 0) then result := p = 2 + else begin + for var i := 3 to p.Sqrt.Floor step 2 do + if (p mod i = 0) then + begin + result := false; //not prime + exit + end; + var m_p := Power(2bi, p) - 1bi; + var s := 4bi; + for var i := 3 to p do + s := (s * s - 2bi) mod m_p; + result := s = 0bi; + end; +end; + +function GetMersennePrimeNumbers(upTo: integer): sequence of integer; +begin + var response := new List; + {$omp parallel for} + for var i := 2 to upTo do + if isMersennePrime(i) then response.Add(i); + response.Sort; + result := response; +end; + +begin + foreach var mp in GetMersennePrimeNumbers(11213) do + Write('M', mp, ' '); + println(#10, milliseconds / 1000, 's'); +end. diff --git a/Task/Lucas-Lehmer-test/Phix/lucas-lehmer-test.phix b/Task/Lucas-Lehmer-test/Phix/lucas-lehmer-test.phix index e1c14c3a6b..4355e2074d 100644 --- a/Task/Lucas-Lehmer-test/Phix/lucas-lehmer-test.phix +++ b/Task/Lucas-Lehmer-test/Phix/lucas-lehmer-test.phix @@ -1,56 +1,54 @@ -(phixonline)--> - with javascript_semantics - bool full = true -- (see extended output below) - constant limit = iff(full?20:23) +with javascript_semantics +bool full = true -- (see extended output below) +constant limit = iff(full?20:23) - include mpfr.e +include mpfr.e - function mersenne(integer p) - if p = 2 then return true end if - if not is_prime(p) then return false end if - mpz s := mpz_init(4), - m := mpz_init(), - r = mpz_init() - mpz_ui_pow_ui(m, 2, p) - mpz_sub_si(m,m,1) - for i=3 to p do - mpz_mul(s,s,s) - mpz_sub_si(s,s,2) - -- mpz_mod(s,s,m) - if mpz_sign(s) < 0 then - mpz_add(s, s ,m) - else - mpz_tdiv_r_2exp(r, s, p) - mpz_tdiv_q_2exp(s, s, p) - mpz_add(s, s, r) - end if - if (mpz_cmp(s, m) >= 0) then mpz_sub(s, s, m) end if - end for - bool res = mpz_cmp_si(s,0)=0 - {s,m,r} = mpz_free({s,m,r}) - return res - end function +function mersenne(integer p) + if p = 2 then return true end if + if not is_prime(p) then return false end if + mpz s := mpz_init(4), + m := mpz_init(), + r = mpz_init() + mpz_ui_pow_ui(m, 2, p) + mpz_sub_si(m,m,1) + for i=3 to p do + mpz_mul(s,s,s) + mpz_sub_si(s,s,2) +-- mpz_mod(s,s,m) + if mpz_sign(s) < 0 then + mpz_add(s, s ,m) + else + mpz_tdiv_r_2exp(r, s, p) + mpz_tdiv_q_2exp(s, s, p) + mpz_add(s, s, r) + end if + if (mpz_cmp(s, m) >= 0) then mpz_sub(s, s, m) end if + end for + bool res = mpz_cmp_si(s,0)=0 + {s,m,r} = mpz_free({s,m,r}) + return res +end function - atom t0 = time(), t1 = t0 - integer i=2, j = 1, count = 0 - constant mersennes = {1279, 2203, 2281, 3217, 4253, 4423, 9689, 9941, 11213, 19937, 21701, - 23209, 44497, 86243, 110503, 132049, 216091, 756839, 859433, 1257787, - 1398269, 2976221, 3021377, 6972593, 13466917, 20996011, 24036583, - 25964951, 30402457, 32582657, 37156667, 42643801, 43112609} +atom t0 = time(), t1 = t0 +integer i=2, j = 1, count = 0 +constant mersennes = {1279, 2203, 2281, 3217, 4253, 4423, 9689, 9941, 11213, 19937, 21701, + 23209, 44497, 86243, 110503, 132049, 216091, 756839, 859433, 1257787, + 1398269, 2976221, 3021377, 6972593, 13466917, 20996011, 24036583, + 25964951, 30402457, 32582657, 37156667, 42643801, 43112609} - while count<limit do - if mersenne(i) then - count += 1 - string e = iff(time()-t1<0.1?"",", "&elapsed(time()-t1)) - printf(1,"M%d (%d%s)\n",{i,count,e}) - t1 = time() - end if - if full or i<1000 then - i += 1 - else - i = mersennes[j] - j += 1 - end if - end while - printf(1,"completed in %s\n",{elapsed(time()-t0)}) -Walker Walker(fcn(rw){ w:=rw.value; n:=w.next(); rw.set(dropNth(n,w)); n } - .fp(Ref([3..*,2]))) // odd numbers starting at 3 + .fp(Ref([3..*,2]))) // odd numbers starting at 3 .push(1,2); // first two Ludic numbers } diff --git a/Task/Luhn-test-of-credit-card-numbers/8080-Assembly/luhn-test-of-credit-card-numbers.8080 b/Task/Luhn-test-of-credit-card-numbers/8080-Assembly/luhn-test-of-credit-card-numbers.8080 index d95443367b..72212a2446 100644 --- a/Task/Luhn-test-of-credit-card-numbers/8080-Assembly/luhn-test-of-credit-card-numbers.8080 +++ b/Task/Luhn-test-of-credit-card-numbers/8080-Assembly/luhn-test-of-credit-card-numbers.8080 @@ -1,61 +1,61 @@ - org 100h - jmp demo - ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; - ;;; Check if the 0-terminated string at HL passes the Luhn test. - ;;; Returns with carry clear if the string passes, carry set - ;;; if the string fails. -luhn: mvi b,0 ; Counter - mov d,b ; D = S1+S2 (we don't need to keep them separate) -lscan: mov a,m ; Get byte - inx h ; Increment pointer - inr b ; Increment counter - ana a ; Is it 0? - jnz lscan ; If not, try next byte - dcx h ; Go to the byte before the 0 - dcx h - dcr b ; Decrement counter - rz ; If 0, the string was empty, return. -lloop: mvi c,'0' ; ASCII zero - mov a,d ; Add odd digit to the total - add m - sub c ; Subtract ASCII zero - mov d,a - dcr b ; If last digit, we're done - jz ldone - dcx h ; Go back one byte - mov a,m ; Get even digit - sub c ; Subtract ASCII zero - add a ; Multiply by two - mvi c,9 ; 10-1, compensate for extra subtraction loop -ldiv: inr c ; Find two digits using trial subtraction - sui 10 - jnc ldiv - add c ; Add the possible second digit in - add d ; Add it to the total - mov d,a - dcx h ; Go back one byte - dcr b ; Done yet? - jnz lloop -ldone: mov a,d ; See if total is divisible by 10 - mvi b,10 -lchk: sub b ; Trial subtraction, subtract 10 - rz ; If zero, it is divisible, return (carry clear) - rc ; If carry, it is not divisible, return (carry set) - jmp lchk - ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; - ;;; Run the routine on the argument given on the CP/M command line -demo: lxi h,80h ; Zero-terminate the command line argument - mov a,m - add l - mov l,a - inr l - mvi m,0 - mvi l,82h ; Run the 'luhn' subroutine - call luhn - mvi c,9 - lxi d,pass ; Carry clear = print 'Pass' - jnc 5 - lxi d,fail ; Carry set = print 'Fail' - jmp 5 -pass: db 'Pass$' -fail: db 'Fail$' + org 100h + jmp demo + ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + ;;; Check if the 0-terminated string at HL passes the Luhn test. + ;;; Returns with carry clear if the string passes, carry set + ;;; if the string fails. +luhn: mvi b,0 ; Counter + mov d,b ; D = S1+S2 (we don't need to keep them separate) +lscan: mov a,m ; Get byte + inx h ; Increment pointer + inr b ; Increment counter + ana a ; Is it 0? + jnz lscan ; If not, try next byte + dcx h ; Go to the byte before the 0 + dcx h + dcr b ; Decrement counter + rz ; If 0, the string was empty, return. +lloop: mvi c,'0' ; ASCII zero + mov a,d ; Add odd digit to the total + add m + sub c ; Subtract ASCII zero + mov d,a + dcr b ; If last digit, we're done + jz ldone + dcx h ; Go back one byte + mov a,m ; Get even digit + sub c ; Subtract ASCII zero + add a ; Multiply by two + mvi c,9 ; 10-1, compensate for extra subtraction loop +ldiv: inr c ; Find two digits using trial subtraction + sui 10 + jnc ldiv + add c ; Add the possible second digit in + add d ; Add it to the total + mov d,a + dcx h ; Go back one byte + dcr b ; Done yet? + jnz lloop +ldone: mov a,d ; See if total is divisible by 10 + mvi b,10 +lchk: sub b ; Trial subtraction, subtract 10 + rz ; If zero, it is divisible, return (carry clear) + rc ; If carry, it is not divisible, return (carry set) + jmp lchk + ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + ;;; Run the routine on the argument given on the CP/M command line +demo: lxi h,80h ; Zero-terminate the command line argument + mov a,m + add l + mov l,a + inr l + mvi m,0 + mvi l,82h ; Run the 'luhn' subroutine + call luhn + mvi c,9 + lxi d,pass ; Carry clear = print 'Pass' + jnc 5 + lxi d,fail ; Carry set = print 'Fail' + jmp 5 +pass: db 'Pass$' +fail: db 'Fail$' diff --git a/Task/Luhn-test-of-credit-card-numbers/8086-Assembly/luhn-test-of-credit-card-numbers.8086 b/Task/Luhn-test-of-credit-card-numbers/8086-Assembly/luhn-test-of-credit-card-numbers.8086 index 38336e2936..a07d4cef3d 100644 --- a/Task/Luhn-test-of-credit-card-numbers/8086-Assembly/luhn-test-of-credit-card-numbers.8086 +++ b/Task/Luhn-test-of-credit-card-numbers/8086-Assembly/luhn-test-of-credit-card-numbers.8086 @@ -1,68 +1,68 @@ - bits 16 - cpu 8086 - org 100h -section .text - jmp demo - ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; - ;;; Check whether the 0-terminated string at DS:SI passes the Luhn - ;;; test. Returns with carry clear if the string passes, carry - ;;; set if the string fails. -luhn: push es ; Keep original ES, and set ES=DS so SCASB can be used. - push ds ; "REP DS:SCASB" is a bad idea, because the 286 has a - pop es ; bug where it "forgets" the 2nd prefix if interrupted! - mov di,si ; DI = pointer - xor ax,ax ; Zero to test against - xor bl,bl ; BL = S1+S2 - mov dx,0A30h ; DH = 10 (divisor), DL = '0' (ASCII zero) - xor cx,cx ; Set counter to 65535 - dec cx - cld ; Seek forwards - repnz scasb ; Find zero - dec di ; SCASB goes one byte too far - xchg si,di ; SI = pointer, DI = end (or rather, beginning) - mov cx,si ; CX = counter - sub cx,di - jcxz .done ; Empty string = stop - dec si ; We don't need the zero itself - std ; Seek backwards -.loop: lodsb ; Get number in odd position - sub al,dl ; Subtract ASCII zero - add bl,al ; Add to total - dec cx ; One fewer character - jz .done ; No more characters = stop - lodsb ; Get number in even position - sub al,dl ; Subtract ASCII zero - add al,al ; Multiply by two - xor ah,ah ; AX = AL - div dh ; Divide by 10; AL=quotient, AH=remainder - add al,ah ; Add the two "digits" together - add bl,al ; Add to total - loop .loop ; Decrement CX and loop -.done: xor ah,ah ; Divide total by 10 - mov al,bl - div dh - and ah,ah ; If remainder 0, then return with carry clear - jz .out - stc ; Set carry (remainder wasn't 0, the test failed) -.out: cld ; Clean up: clear direction flag, - pop es ; and restore ES. - ret - ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; - ;;; Run the 'luhn' routine on the argument given on the MS-DOS - ;;; command line. -demo: mov si,80h ; Zero-terminate the argument - xor bh,bh - mov bl,[si] - mov [si+bx+1],bh - inc si - inc si - call luhn ; Call the routine - mov ah,9 - mov dx,pass ; If carry is clear, print 'Pass' - jnc print - mov dx,fail ; Otherwise, print 'fail' -print: int 21h - ret -section .data -pass: db 'Pass$' -fail: db 'Fail$' + bits 16 + cpu 8086 + org 100h +section .text + jmp demo + ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + ;;; Check whether the 0-terminated string at DS:SI passes the Luhn + ;;; test. Returns with carry clear if the string passes, carry + ;;; set if the string fails. +luhn: push es ; Keep original ES, and set ES=DS so SCASB can be used. + push ds ; "REP DS:SCASB" is a bad idea, because the 286 has a + pop es ; bug where it "forgets" the 2nd prefix if interrupted! + mov di,si ; DI = pointer + xor ax,ax ; Zero to test against + xor bl,bl ; BL = S1+S2 + mov dx,0A30h ; DH = 10 (divisor), DL = '0' (ASCII zero) + xor cx,cx ; Set counter to 65535 + dec cx + cld ; Seek forwards + repnz scasb ; Find zero + dec di ; SCASB goes one byte too far + xchg si,di ; SI = pointer, DI = end (or rather, beginning) + mov cx,si ; CX = counter + sub cx,di + jcxz .done ; Empty string = stop + dec si ; We don't need the zero itself + std ; Seek backwards +.loop: lodsb ; Get number in odd position + sub al,dl ; Subtract ASCII zero + add bl,al ; Add to total + dec cx ; One fewer character + jz .done ; No more characters = stop + lodsb ; Get number in even position + sub al,dl ; Subtract ASCII zero + add al,al ; Multiply by two + xor ah,ah ; AX = AL + div dh ; Divide by 10; AL=quotient, AH=remainder + add al,ah ; Add the two "digits" together + add bl,al ; Add to total + loop .loop ; Decrement CX and loop +.done: xor ah,ah ; Divide total by 10 + mov al,bl + div dh + and ah,ah ; If remainder 0, then return with carry clear + jz .out + stc ; Set carry (remainder wasn't 0, the test failed) +.out: cld ; Clean up: clear direction flag, + pop es ; and restore ES. + ret + ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + ;;; Run the 'luhn' routine on the argument given on the MS-DOS + ;;; command line. +demo: mov si,80h ; Zero-terminate the argument + xor bh,bh + mov bl,[si] + mov [si+bx+1],bh + inc si + inc si + call luhn ; Call the routine + mov ah,9 + mov dx,pass ; If carry is clear, print 'Pass' + jnc print + mov dx,fail ; Otherwise, print 'fail' +print: int 21h + ret +section .data +pass: db 'Pass$' +fail: db 'Fail$' diff --git a/Task/Luhn-test-of-credit-card-numbers/ANSI-BASIC/luhn-test-of-credit-card-numbers.basic b/Task/Luhn-test-of-credit-card-numbers/ANSI-BASIC/luhn-test-of-credit-card-numbers.basic new file mode 100644 index 0000000000..a361c757fe --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/ANSI-BASIC/luhn-test-of-credit-card-numbers.basic @@ -0,0 +1,22 @@ +100 REM Luhn test of credit card numbers +110 DATA "49927398716", "49927398717", "1234567812345678", "1234567812345670" +120 DECLARE EXTERNAL FUNCTION LuhnTest +130 FOR J = 1 TO 4 +140 READ C$ +150 PRINT C$; +160 IF LuhnTest(C$) = 1 THEN PRINT " is valid." ELSE PRINT " is invalid." +170 NEXT J +180 END +190 REM +200 EXTERNAL FUNCTION LuhnTest(C$) +210 LET S = 0 +220 FOR I = LEN(C$) TO 1 STEP -2 +230 LET S = S + VAL(C$(I:I)) +240 NEXT I +250 FOR I = LEN(C$) - 1 TO 1 STEP -2 +260 LET B = VAL(C$(I:I)) * 2 +270 IF B >= 10 THEN LET B = B - 9 +280 LET S = S + B +290 NEXT I +300 IF MOD(S, 10) = 0 THEN LET LuhnTest = 1 ELSE LET LuhnTest = 0 +310 END FUNCTION diff --git a/Task/Luhn-test-of-credit-card-numbers/ASIC/luhn-test-of-credit-card-numbers.asic b/Task/Luhn-test-of-credit-card-numbers/ASIC/luhn-test-of-credit-card-numbers.asic new file mode 100644 index 0000000000..5416e3933f --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/ASIC/luhn-test-of-credit-card-numbers.asic @@ -0,0 +1,42 @@ +REM Luhn test of credit card numbers +DATA "49927398716", "49927398717", "1234567812345678", "1234567812345670" +FOR J = 1 TO 4 + READ C$ + GOSUB DoLuhnTest: + PRINT C$; + IF RetVal = 1 THEN + PRINT " is valid." + ELSE + PRINT " is invalid." + ENDIF +NEXT J +END + +DoLuhnTest: +LenC = LEN(C$) +S = 0 +I = LenC +WHILE I >= 1 + CI$ = MID$(C$, I, 1) + Num = VAL(CI$) + S = S + Num + I = I - 2 +WEND +I = LenC - 1 +WHILE I >= 1 + CI$ = MID$(C$, I, 1) + Num = VAL(CI$) + B = Num * 2 + IF B >= 10 THEN + B = B - 9 + ENDIF + S = S + B + I = I - 2 +WEND +SMod10 = S MOD 10 +IF SMod10 = 0 THEN + RetVal = 1 +ELSE + RetVal = 0 +ENDIF +RETURN diff --git a/Task/Luhn-test-of-credit-card-numbers/AWK/luhn-test-of-credit-card-numbers.awk b/Task/Luhn-test-of-credit-card-numbers/AWK/luhn-test-of-credit-card-numbers.awk index 0a30930aac..1c2fcb838d 100644 --- a/Task/Luhn-test-of-credit-card-numbers/AWK/luhn-test-of-credit-card-numbers.awk +++ b/Task/Luhn-test-of-credit-card-numbers/AWK/luhn-test-of-credit-card-numbers.awk @@ -7,7 +7,7 @@ BEGIN { A[5] = "01234567897"; A[6] = "01234567890"; A[7] = "00000000000"; - for (k in A) print "isLuhn("A[k]"): ",isLuhn(A[k]); + for (k in A) print "isLuhn("A[k]"): ",isLuhn(A[k]); } function isLuhn(cardno) { @@ -15,10 +15,10 @@ function isLuhn(cardno) { m = "0246813579"; n = length(cardno); for (k = n; 0 < k; k -= 2) { - s += substr(cardno, k, 1); + s += substr(cardno, k, 1); } for (k = n-1; 0 < k; k -= 2) { - s += substr(m, substr(cardno, k, 1)+1, 1); + s += substr(m, substr(cardno, k, 1)+1, 1); } - return ((s%10)==0); + return ((s%10)==0); } diff --git a/Task/Luhn-test-of-credit-card-numbers/ActionScript/luhn-test-of-credit-card-numbers.as b/Task/Luhn-test-of-credit-card-numbers/ActionScript/luhn-test-of-credit-card-numbers.as index 039ee4fb8b..82b5119b88 100644 --- a/Task/Luhn-test-of-credit-card-numbers/ActionScript/luhn-test-of-credit-card-numbers.as +++ b/Task/Luhn-test-of-credit-card-numbers/ActionScript/luhn-test-of-credit-card-numbers.as @@ -1,17 +1,17 @@ function isValid(numString:String):Boolean { - var isOdd:Boolean = true; - var oddSum:uint = 0; - var evenSum:uint = 0; - for(var i:int = numString.length - 1; i >= 0; i--) - { - var digit:uint = uint(numString.charAt(i)) - if(isOdd) oddSum += digit; - else evenSum += digit/5 + (2*digit) % 10; - isOdd = !isOdd; - } - if((oddSum + evenSum) % 10 == 0) return true; - return false; + var isOdd:Boolean = true; + var oddSum:uint = 0; + var evenSum:uint = 0; + for(var i:int = numString.length - 1; i >= 0; i--) + { + var digit:uint = uint(numString.charAt(i)) + if(isOdd) oddSum += digit; + else evenSum += digit/5 + (2*digit) % 10; + isOdd = !isOdd; + } + if((oddSum + evenSum) % 10 == 0) return true; + return false; } trace(isValid("49927398716")); diff --git a/Task/Luhn-test-of-credit-card-numbers/Ada/luhn-test-of-credit-card-numbers.ada b/Task/Luhn-test-of-credit-card-numbers/Ada/luhn-test-of-credit-card-numbers.adb similarity index 100% rename from Task/Luhn-test-of-credit-card-numbers/Ada/luhn-test-of-credit-card-numbers.ada rename to Task/Luhn-test-of-credit-card-numbers/Ada/luhn-test-of-credit-card-numbers.adb diff --git a/Task/Luhn-test-of-credit-card-numbers/Arturo/luhn-test-of-credit-card-numbers.arturo b/Task/Luhn-test-of-credit-card-numbers/Arturo/luhn-test-of-credit-card-numbers.arturo index 3349cbf51d..8114c08a93 100644 --- a/Task/Luhn-test-of-credit-card-numbers/Arturo/luhn-test-of-credit-card-numbers.arturo +++ b/Task/Luhn-test-of-credit-card-numbers/Arturo/luhn-test-of-credit-card-numbers.arturo @@ -1,5 +1,5 @@ digits: function [n][ - res: new [] + res: [] while -> n > 0 [ 'res ++ n % 10 n: n / 10 @@ -8,11 +8,11 @@ digits: function [n][ ] luhn?: function [n][ - s1: new 0 - s2: new 0 + s1: 0 + s2: 0 loop.with: 'i digits n 'd [ - if? even? i -> 's1 + d - else [ + switch even? i -> 's1 + d + [ 'd * 2 if d > 9 -> 'd - 9 's2 + d diff --git a/Task/Luhn-test-of-credit-card-numbers/AutoIt/luhn-test-of-credit-card-numbers.au3 b/Task/Luhn-test-of-credit-card-numbers/AutoIt/luhn-test-of-credit-card-numbers.au3 new file mode 100644 index 0000000000..1547bef831 --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/AutoIt/luhn-test-of-credit-card-numbers.au3 @@ -0,0 +1,23 @@ +Global $avarray[4] = [49927398716, 49927398717, 1234567812345678, 1234567812345670] +For $i = 0 To 3 + checkLuhn($avarray[$i]) +Next + +Func checkLuhn($number) + $sum = 0 + $numDigits = StringSplit($number, "") + For $i = $numDigits[0] - 1 To 1 Step -2 + $numDigits[$i] = $numDigits[$i] * 2 + If $numDigits[$i] >= 10 Then $numDigits[$i] -= 9 + Next + For $i = 1 To $numDigits[0] + $sum += $numDigits[$i] + Next + If StringRight($sum, 1) = "0" Then + ConsoleWrite("Luhn-Check (" & $number & ") : True" & @CRLF) + Return True + Else + ConsoleWrite("Luhn-Check (" & $number & ") : False" & @CRLF) + Return False + EndIf +EndFunc ;==>checkLuhn diff --git a/Task/Luhn-test-of-credit-card-numbers/AutoIt/luhn-test-of-credit-card-numbers.autoit b/Task/Luhn-test-of-credit-card-numbers/AutoIt/luhn-test-of-credit-card-numbers.autoit deleted file mode 100644 index 629d3da9b7..0000000000 --- a/Task/Luhn-test-of-credit-card-numbers/AutoIt/luhn-test-of-credit-card-numbers.autoit +++ /dev/null @@ -1,23 +0,0 @@ -Global $avarray[4] = [49927398716, 49927398717, 1234567812345678, 1234567812345670] -For $i = 0 To 3 - checkLuhn($avarray[$i]) -Next - -Func checkLuhn($number) - $sum = 0 - $numDigits = StringSplit($number, "") - For $i = $numDigits[0] - 1 To 1 Step -2 - $numDigits[$i] = $numDigits[$i] * 2 - If $numDigits[$i] >= 10 Then $numDigits[$i] -= 9 - Next - For $i = 1 To $numDigits[0] - $sum += $numDigits[$i] - Next - If StringRight($sum, 1) = "0" Then - ConsoleWrite("Luhn-Check (" & $number & ") : True" & @CRLF) - Return True - Else - ConsoleWrite("Luhn-Check (" & $number & ") : False" & @CRLF) - Return False - EndIf -EndFunc ;==>checkLuhn diff --git a/Task/Luhn-test-of-credit-card-numbers/BQN/luhn-test-of-credit-card-numbers.bqn b/Task/Luhn-test-of-credit-card-numbers/BQN/luhn-test-of-credit-card-numbers.bqn index 1759a652eb..d74dee728c 100644 --- a/Task/Luhn-test-of-credit-card-numbers/BQN/luhn-test-of-credit-card-numbers.bqn +++ b/Task/Luhn-test-of-credit-card-numbers/BQN/luhn-test-of-credit-card-numbers.bqn @@ -1,3 +1,3 @@ -Luhn ← (0=10|⊢)∘(+´(10|⊢)+⊢≥10˙)∘(⊢×≠⥊1‿2˙)∘(⌽•Fmt-'0'˙) +Luhn ← 0=10|·+´·+⟜(9-˜⍟<+˜)´˘↑‿2⥊⟜⌽-⟜'0' -(⍉⊢≍Luhn¨) ⟨49927398716,49927398717,1234567812345678,1234567812345670⟩ +≍˘⟜(Luhn¨) "49927398716"‿"49927398717"‿"1234567812345678"‿"1234567812345670" diff --git a/Task/Luhn-test-of-credit-card-numbers/Batch-File/luhn-test-of-credit-card-numbers.bat b/Task/Luhn-test-of-credit-card-numbers/Batch-File/luhn-test-of-credit-card-numbers.bat index a5ddc6aaf4..d2e94f101a 100644 --- a/Task/Luhn-test-of-credit-card-numbers/Batch-File/luhn-test-of-credit-card-numbers.bat +++ b/Task/Luhn-test-of-credit-card-numbers/Batch-File/luhn-test-of-credit-card-numbers.bat @@ -17,18 +17,18 @@ set /a "cnt-=1" set /a "isOdd=(-%cnt%)%%2" if !isodd! equ 1 ( - set /a "s1+=!input:~%cnt%,1!" + set /a "s1+=!input:~%cnt%,1!" ) else ( - set /a "twice=!input:~%cnt%,1!*2" - if !twice! geq 10 ( - set /a "s2+=!twice:~0,1!+!twice:~1,1!" - ) else ( - set /a "s2+=!twice!" - ) + set /a "twice=!input:~%cnt%,1!*2" + if !twice! geq 10 ( + set /a "s2+=!twice:~0,1!+!twice:~1,1!" + ) else ( + set /a "s2+=!twice!" + ) ) if "!input:~%cnt%!"=="!input!" ( - set /a "sum=(!s1!+!s2!)%%10" - if !sum! equ 0 (echo !input! is valid.) else (echo !input! is not valid.) - goto :EOF + set /a "sum=(!s1!+!s2!)%%10" + if !sum! equ 0 (echo !input! is valid.) else (echo !input! is not valid.) + goto :EOF ) goto digit_loop diff --git a/Task/Luhn-test-of-credit-card-numbers/Bruijn/luhn-test-of-credit-card-numbers.bruijn b/Task/Luhn-test-of-credit-card-numbers/Bruijn/luhn-test-of-credit-card-numbers.bruijn index e52011efb3..059a5363a1 100644 --- a/Task/Luhn-test-of-credit-card-numbers/Bruijn/luhn-test-of-credit-card-numbers.bruijn +++ b/Task/Luhn-test-of-credit-card-numbers/Bruijn/luhn-test-of-credit-card-numbers.bruijn @@ -3,9 +3,9 @@ :import std/List . luhn number→list → reverse → check → (\mod (+10)) → zero? - check y [[[[0 [[[6 \5 (4 + (5 odd even)) 1]]] 1]]]] k (+0) - odd 2 - even digit-sum (2 ⋅ (+2)) + check y [[[[0 [[[6 \5 (4 + (5 odd even)) 1]]] 1]]]] k (+0) + odd 2 + even digit-sum (2 ⋅ (+2)) :test (luhn (+61789372994)) ([[1]]) :test (luhn (+49927398716)) ([[1]]) diff --git a/Task/Luhn-test-of-credit-card-numbers/C++/luhn-test-of-credit-card-numbers-1.cpp b/Task/Luhn-test-of-credit-card-numbers/C++/luhn-test-of-credit-card-numbers-1.cpp index 575381e8f9..d42a4771e2 100644 --- a/Task/Luhn-test-of-credit-card-numbers/C++/luhn-test-of-credit-card-numbers-1.cpp +++ b/Task/Luhn-test-of-credit-card-numbers/C++/luhn-test-of-credit-card-numbers-1.cpp @@ -22,7 +22,7 @@ int confirm( const char *id) else { s += (k!=9)? (2*k)%9 : 9; } - is_odd_dgt = !is_odd_dgt; + is_odd_dgt = !is_odd_dgt; } return 0 == s%10; } diff --git a/Task/Luhn-test-of-credit-card-numbers/C-sharp/luhn-test-of-credit-card-numbers-3.cs b/Task/Luhn-test-of-credit-card-numbers/C-sharp/luhn-test-of-credit-card-numbers-3.cs index 29eb66d22c..0449839ba9 100644 --- a/Task/Luhn-test-of-credit-card-numbers/C-sharp/luhn-test-of-credit-card-numbers-3.cs +++ b/Task/Luhn-test-of-credit-card-numbers/C-sharp/luhn-test-of-credit-card-numbers-3.cs @@ -1,50 +1,50 @@ using System; namespace Luhn_Test { - public static class Extensions - { - public static string Reverse(this string s ) - { - char[] charArray = s.ToCharArray(); - Array.Reverse( charArray ); - return new string( charArray ); - } - } - class Program - { - public static bool Luhn(long x) - { - long s1=0; - long s2=0; - bool STATE=x%10!=0; // If it ends with zero, we want the order to be the other way around - x=long.Parse(x.ToString().Reverse()); - while (x!=0) - { - s1+=STATE?x%10:0; - s2+=STATE?0:((x%10)*2>9)?(((x%10)*2/10)+((x%10)*2)%10):((x%10)*2); - STATE=!STATE; //Switch state - x/=10; //Cut the last digit and continue - } - return ((s1+s2)%10==0); //Check if it ends with zero, if so, return true, otherwise,false. - } - public static void Main(string[] args) - { - long[] ks = {1234567812345670, 49927398717, 1234567812345678 ,1234567812345670 }; - foreach (long k in ks) - { - Console.WriteLine("{0} is {1} Valid.",k,Luhn(k)?"":"Not"); - } - Start: - try { - Console.WriteLine("Enter your credit:"); - long x=long.Parse(Console.ReadLine()); - Console.WriteLine("{0} Valid.",Luhn(x)?"":"Not"); - goto Start; - } - catch (FormatException) - { - goto Start; - } - } - } + public static class Extensions + { + public static string Reverse(this string s ) + { + char[] charArray = s.ToCharArray(); + Array.Reverse( charArray ); + return new string( charArray ); + } + } + class Program + { + public static bool Luhn(long x) + { + long s1=0; + long s2=0; + bool STATE=x%10!=0; // If it ends with zero, we want the order to be the other way around + x=long.Parse(x.ToString().Reverse()); + while (x!=0) + { + s1+=STATE?x%10:0; + s2+=STATE?0:((x%10)*2>9)?(((x%10)*2/10)+((x%10)*2)%10):((x%10)*2); + STATE=!STATE; //Switch state + x/=10; //Cut the last digit and continue + } + return ((s1+s2)%10==0); //Check if it ends with zero, if so, return true, otherwise,false. + } + public static void Main(string[] args) + { + long[] ks = {1234567812345670, 49927398717, 1234567812345678 ,1234567812345670 }; + foreach (long k in ks) + { + Console.WriteLine("{0} is {1} Valid.",k,Luhn(k)?"":"Not"); + } + Start: + try { + Console.WriteLine("Enter your credit:"); + long x=long.Parse(Console.ReadLine()); + Console.WriteLine("{0} Valid.",Luhn(x)?"":"Not"); + goto Start; + } + catch (FormatException) + { + goto Start; + } + } + } } diff --git a/Task/Luhn-test-of-credit-card-numbers/C/luhn-test-of-credit-card-numbers.c b/Task/Luhn-test-of-credit-card-numbers/C/luhn-test-of-credit-card-numbers.c index 7ad50988cd..7b45a03fb3 100644 --- a/Task/Luhn-test-of-credit-card-numbers/C/luhn-test-of-credit-card-numbers.c +++ b/Task/Luhn-test-of-credit-card-numbers/C/luhn-test-of-credit-card-numbers.c @@ -3,30 +3,30 @@ int luhn(const char* cc) { - const int m[] = {0,2,4,6,8,1,3,5,7,9}; // mapping for rule 3 - int i, odd = 1, sum = 0; + const int m[] = {0,2,4,6,8,1,3,5,7,9}; // mapping for rule 3 + int i, odd = 1, sum = 0; - for (i = strlen(cc); i--; odd = !odd) { - int digit = cc[i] - '0'; - sum += odd ? digit : m[digit]; - } + for (i = strlen(cc); i--; odd = !odd) { + int digit = cc[i] - '0'; + sum += odd ? digit : m[digit]; + } - return sum % 10 == 0; + return sum % 10 == 0; } int main() { - const char* cc[] = { - "49927398716", - "49927398717", - "1234567812345678", - "1234567812345670", - 0 - }; - int i; + const char* cc[] = { + "49927398716", + "49927398717", + "1234567812345678", + "1234567812345670", + 0 + }; + int i; - for (i = 0; cc[i]; i++) - printf("%16s\t%s\n", cc[i], luhn(cc[i]) ? "ok" : "not ok"); + for (i = 0; cc[i]; i++) + printf("%16s\t%s\n", cc[i], luhn(cc[i]) ? "ok" : "not ok"); - return 0; + return 0; } diff --git a/Task/Luhn-test-of-credit-card-numbers/COBOL/luhn-test-of-credit-card-numbers.cobol b/Task/Luhn-test-of-credit-card-numbers/COBOL/luhn-test-of-credit-card-numbers.cob similarity index 100% rename from Task/Luhn-test-of-credit-card-numbers/COBOL/luhn-test-of-credit-card-numbers.cobol rename to Task/Luhn-test-of-credit-card-numbers/COBOL/luhn-test-of-credit-card-numbers.cob diff --git a/Task/Luhn-test-of-credit-card-numbers/Ceylon/luhn-test-of-credit-card-numbers.ceylon b/Task/Luhn-test-of-credit-card-numbers/Ceylon/luhn-test-of-credit-card-numbers.ceylon index a5f2d5521c..d12952629b 100644 --- a/Task/Luhn-test-of-credit-card-numbers/Ceylon/luhn-test-of-credit-card-numbers.ceylon +++ b/Task/Luhn-test-of-credit-card-numbers/Ceylon/luhn-test-of-credit-card-numbers.ceylon @@ -1,27 +1,27 @@ shared void run() { - value numbers = "49927398716 - 49927398717 - 1234567812345678 - 1234567812345670"; - for(number in numbers.lines) { - print("``number`` passes? ``luhn(number)``"); - } + value numbers = "49927398716 + 49927398717 + 1234567812345678 + 1234567812345670"; + for(number in numbers.lines) { + print("``number`` passes? ``luhn(number)``"); + } } shared Boolean luhn(String number) { - value digits = number - .reversed - .map(Character.string) - .map(Integer.parse) - .narrow(); - value s1 = sum { 0, *digits.by(2) }; - value s2 = sum { - 0, - *digits - .skip(1) - .by(2) - .map(curry(times)(2)) - .map((Integer element) => element / 10 + element % 10) - }; - return (s1 + s2) % 10 == 0; + value digits = number + .reversed + .map(Character.string) + .map(Integer.parse) + .narrow(); + value s1 = sum { 0, *digits.by(2) }; + value s2 = sum { + 0, + *digits + .skip(1) + .by(2) + .map(curry(times)(2)) + .map((Integer element) => element / 10 + element % 10) + }; + return (s1 + s2) % 10 == 0; } diff --git a/Task/Luhn-test-of-credit-card-numbers/Common-Lisp/luhn-test-of-credit-card-numbers-1.lisp b/Task/Luhn-test-of-credit-card-numbers/Common-Lisp/luhn-test-of-credit-card-numbers-1.lisp index f05d626cda..827a535576 100644 --- a/Task/Luhn-test-of-credit-card-numbers/Common-Lisp/luhn-test-of-credit-card-numbers-1.lisp +++ b/Task/Luhn-test-of-credit-card-numbers/Common-Lisp/luhn-test-of-credit-card-numbers-1.lisp @@ -2,7 +2,7 @@ (labels ((sum-digits (n) (if (> n 9) (- n 9) n))) (let ((n* (reverse n)) (l (length n))) (let ((s1 (loop for i from 0 below l by 2 - summing (digit-char-p (aref n* i)))) - (s2 (loop for i from 1 below l by 2 - summing (sum-digits (* 2 (digit-char-p (aref n* i))))))) - (zerop (mod (+ s1 s2) 10)))))) + summing (digit-char-p (aref n* i)))) + (s2 (loop for i from 1 below l by 2 + summing (sum-digits (* 2 (digit-char-p (aref n* i))))))) + (zerop (mod (+ s1 s2) 10)))))) diff --git a/Task/Luhn-test-of-credit-card-numbers/Common-Lisp/luhn-test-of-credit-card-numbers-2.lisp b/Task/Luhn-test-of-credit-card-numbers/Common-Lisp/luhn-test-of-credit-card-numbers-2.lisp index 7d4dba68da..5b637286d6 100644 --- a/Task/Luhn-test-of-credit-card-numbers/Common-Lisp/luhn-test-of-credit-card-numbers-2.lisp +++ b/Task/Luhn-test-of-credit-card-numbers/Common-Lisp/luhn-test-of-credit-card-numbers-2.lisp @@ -5,4 +5,4 @@ (defun luhn (seq) (labels ((sum-digits (n) (if (> n 9) (- n 9) n))) (funcall {zerop (mod * 10) (apply #'+) (mapcar #'sum-digits) - (mapcar #'* '#1=(1 2 . #1#)) (map 'list #'digit-char-p) reverse} seq))) + (mapcar #'* '#1=(1 2 . #1#)) (map 'list #'digit-char-p) reverse} seq))) diff --git a/Task/Luhn-test-of-credit-card-numbers/Crystal/luhn-test-of-credit-card-numbers.crystal b/Task/Luhn-test-of-credit-card-numbers/Crystal/luhn-test-of-credit-card-numbers.cr similarity index 100% rename from Task/Luhn-test-of-credit-card-numbers/Crystal/luhn-test-of-credit-card-numbers.crystal rename to Task/Luhn-test-of-credit-card-numbers/Crystal/luhn-test-of-credit-card-numbers.cr diff --git a/Task/Luhn-test-of-credit-card-numbers/Delphi/luhn-test-of-credit-card-numbers.delphi b/Task/Luhn-test-of-credit-card-numbers/Delphi/luhn-test-of-credit-card-numbers.pas similarity index 100% rename from Task/Luhn-test-of-credit-card-numbers/Delphi/luhn-test-of-credit-card-numbers.delphi rename to Task/Luhn-test-of-credit-card-numbers/Delphi/luhn-test-of-credit-card-numbers.pas diff --git a/Task/Luhn-test-of-credit-card-numbers/DuckDB/luhn-test-of-credit-card-numbers.duckdb b/Task/Luhn-test-of-credit-card-numbers/DuckDB/luhn-test-of-credit-card-numbers.duckdb new file mode 100644 index 0000000000..0b20362701 --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/DuckDB/luhn-test-of-credit-card-numbers.duckdb @@ -0,0 +1,43 @@ +create or replace function odds(lst) as ( + list_filter(lst, (x,i) -> i%2=1) +); + +create or replace function evens(lst) as ( + list_filter(lst, (x,i) -> i%2=0) +); + +create or replace function digit_sum(i) as ( + regexp_extract_all(i::VARCHAR, '.') + .list_transform(x -> x::INT) + .list_sum() +); + +# Return boolean: true iff the list of digits passes +create or replace function list_luhn(lst) as ( + with odds_sum as ( + select list_reverse(lst).odds().list_sum() as odds_sum), + evens_reduce as ( + select list_reverse(lst).list_transform(x -> digit_sum(2*x)) + .list_sum() as evens_reduce) + select (odds_sum + evens_reduce ) % 10 = 0 as pass + from odds_sum, evens_reduce +); + +# The list of the digits of i (an integer or string) +create or replace function digits(i) as ( + regexp_extract_all(i::TEXT, '.').list_transform(x -> x::INT) +); + +# i can be an integer or string +create or replace function luhn(i) as ( + digits(i).list_luhn() +); + +## Examples:: +select n, luhn(n), luhn(n::TEXT) as "luhn(n::TEXT)" +from unnest( + [49927398716, + 49927398717, + 1234567812345678, + 1234567812345670 + ]) _(n); diff --git a/Task/Luhn-test-of-credit-card-numbers/Elixir/luhn-test-of-credit-card-numbers.elixir b/Task/Luhn-test-of-credit-card-numbers/Elixir/luhn-test-of-credit-card-numbers.ex similarity index 100% rename from Task/Luhn-test-of-credit-card-numbers/Elixir/luhn-test-of-credit-card-numbers.elixir rename to Task/Luhn-test-of-credit-card-numbers/Elixir/luhn-test-of-credit-card-numbers.ex diff --git a/Task/Luhn-test-of-credit-card-numbers/Emacs-Lisp/luhn-test-of-credit-card-numbers.l b/Task/Luhn-test-of-credit-card-numbers/Emacs-Lisp/luhn-test-of-credit-card-numbers.el similarity index 100% rename from Task/Luhn-test-of-credit-card-numbers/Emacs-Lisp/luhn-test-of-credit-card-numbers.l rename to Task/Luhn-test-of-credit-card-numbers/Emacs-Lisp/luhn-test-of-credit-card-numbers.el diff --git a/Task/Luhn-test-of-credit-card-numbers/Euphoria/luhn-test-of-credit-card-numbers.euphoria b/Task/Luhn-test-of-credit-card-numbers/Euphoria/luhn-test-of-credit-card-numbers.eu similarity index 100% rename from Task/Luhn-test-of-credit-card-numbers/Euphoria/luhn-test-of-credit-card-numbers.euphoria rename to Task/Luhn-test-of-credit-card-numbers/Euphoria/luhn-test-of-credit-card-numbers.eu diff --git a/Task/Luhn-test-of-credit-card-numbers/FutureBasic/luhn-test-of-credit-card-numbers.basic b/Task/Luhn-test-of-credit-card-numbers/FutureBasic/luhn-test-of-credit-card-numbers.basic index 577e9f7824..8453461734 100644 --- a/Task/Luhn-test-of-credit-card-numbers/FutureBasic/luhn-test-of-credit-card-numbers.basic +++ b/Task/Luhn-test-of-credit-card-numbers/FutureBasic/luhn-test-of-credit-card-numbers.basic @@ -1,43 +1,18 @@ include "NSLog.incl" -local fn LuhnCheck( cardStr as CFStringRef ) as BOOL - NSInteger i, j, count, s1 = 0, s2 = 0 - BOOL result = NO +local fn luhn( n as long ) + int r = 0, nx2(9) = {0,2,4,6,8,1,3,5,7,9} + nslog(@"%20ld \b", n) + while n + r += n % 10 + nx2(n / 10 % 10) + n /= 100 + wend + if r % 10 then nslog( @"fail") else nslog( @"pass") +end fn - // Build array of individual numbers in credit card string - NSUInteger strLength = len(cardStr) - CFMUtableArrayRef mutArr = fn MutableArrayWithCapacity(strLength) - for i = 0 to strLength - 1 - CFStringRef tempStr = fn StringWithFormat( @"%C", fn StringCharacterAtIndex( cardStr, i ) ) - MutableArrayInsertObjectAtIndex( mutArr, tempStr, i ) - next +fn luhn(49927398716) +fn luhn(49927398717) +fn luhn(1234567812345678) +fn luhn(1234567812345670) - // Reverse the number array - CFArrayRef reversedArray = fn EnumeratorAllObjects( fn ArrayReverseObjectEnumerator( mutArr ) ) - - // Get number of array elements - count = len(reversedArray) - - // Handle odd numbers - for i = 0 to count - 1 step 2 - s1 = s1 + fn StringIntegerValue( reversedArray[i] ) - next - - // Hnadle even numbers - for i = 1 to count - 1 step 2 - j = fn StringIntegerValue( reversedArray[i] ) - j = j * 2 - if j > 9 then j = j mod 10 + 1 - s2 = s2 + j - next - - if (s1 + s2) mod 10 = 0 then result = YES else result = NO -end fn = result - -NSLogClear -if fn LuhnCheck( @"49927398716" ) then NSLog (@"%@ is valid.", @"49927398716" ) else NSLog (@"%@ is not valid.", @"49927398716" ) -if fn LuhnCheck( @"49927398717" ) then NSLog (@"%@ is valid.", @"49927398717" ) else NSLog (@"%@ is not valid.", @"49927398717" ) -if fn LuhnCheck( @"1234567812345678" ) then NSLog (@"%@ is valid.", @"1234567812345678" ) else NSLog (@"%@ is not valid.", @"1234567812345678" ) -if fn LuhnCheck( @"1234567812345670" ) then NSLog (@"%@ is valid.", @"1234567812345670" ) else NSLog (@"%@ is not valid.", @"1234567812345670" ) - -HandleEvents +handleevents diff --git a/Task/Luhn-test-of-credit-card-numbers/GAP/luhn-test-of-credit-card-numbers.gap b/Task/Luhn-test-of-credit-card-numbers/GAP/luhn-test-of-credit-card-numbers.gap index a400612989..e8c602c235 100644 --- a/Task/Luhn-test-of-credit-card-numbers/GAP/luhn-test-of-credit-card-numbers.gap +++ b/Task/Luhn-test-of-credit-card-numbers/GAP/luhn-test-of-credit-card-numbers.gap @@ -1,18 +1,18 @@ IsLuhn := function(n) - local c, d, i, j, r; - d := "0123456789"; - j := 1; - r := 0; - for c in Reversed(String(n)) do - i := Position(d, c); - if i = fail then - continue; - fi; - i := j*(i - 1); - r := r + QuoInt(i, 10) + RemInt(i, 10); - j := 3 - j; - od; - return RemInt(r, 10) = 0; + local c, d, i, j, r; + d := "0123456789"; + j := 1; + r := 0; + for c in Reversed(String(n)) do + i := Position(d, c); + if i = fail then + continue; + fi; + i := j*(i - 1); + r := r + QuoInt(i, 10) + RemInt(i, 10); + j := 3 - j; + od; + return RemInt(r, 10) = 0; end; List([49927398716, 49927398717, 1234567812345678, 1234567812345670], IsLuhn); diff --git a/Task/Luhn-test-of-credit-card-numbers/GW-BASIC/luhn-test-of-credit-card-numbers.basic b/Task/Luhn-test-of-credit-card-numbers/GW-BASIC/luhn-test-of-credit-card-numbers.basic new file mode 100644 index 0000000000..4e5104142d --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/GW-BASIC/luhn-test-of-credit-card-numbers.basic @@ -0,0 +1,20 @@ +10 REM Luhn test of credit card numbers +20 DATA "49927398716", "49927398717", "1234567812345678", "1234567812345670" +30 FOR J = 1 TO 4 +40 READ C$: GOSUB 1000 +50 PRINT C$; +60 IF RETVAL THEN PRINT " is valid." ELSE PRINT " is invalid." +70 NEXT J +80 END +1000 REM ** Luhn test +1010 S = 0 +1020 FOR I = LEN(C$) TO 1 STEP -2 +1030 S = S + VAL(MID$(C$, I, 1)) +1040 NEXT I +1050 FOR I = LEN(C$) - 1 TO 1 STEP -2 +1060 B = VAL(MID$(C$, I, 1)) * 2 +1070 IF B >= 10 THEN B = B - 9 +1080 S = S + B +1090 NEXT I +1100 RETVAL = (S MOD 10 = 0) +1110 RETURN diff --git a/Task/Luhn-test-of-credit-card-numbers/Gleam/luhn-test-of-credit-card-numbers.gleam b/Task/Luhn-test-of-credit-card-numbers/Gleam/luhn-test-of-credit-card-numbers.gleam new file mode 100644 index 0000000000..19af82dc5e --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/Gleam/luhn-test-of-credit-card-numbers.gleam @@ -0,0 +1,25 @@ +pub fn main() { + let _ = echo is_luhn(49_927_398_716) // True + let _ = echo is_luhn(49_927_398_717) // False + let _ = echo is_luhn(1_234_567_812_345_678) // False + let _ = echo is_luhn(1_234_567_812_345_670) // True +} + +pub fn is_luhn(n: Int) -> Bool { + is_luhn_loop(n, 0, True) +} + +fn is_luhn_loop(n, sum, even_digit) { + case n, even_digit { + 0, _ -> sum % 10 == 0 + _, True -> is_luhn_loop(n / 10, sum + n % 10, False) + _, False -> { + let x = n % 10 + let y = case x < 5 { + True -> x + x + False -> x + x - 9 + } + is_luhn_loop(n / 10, sum + y, True) + } + } +} diff --git a/Task/Luhn-test-of-credit-card-numbers/JavaScript/luhn-test-of-credit-card-numbers-2.js b/Task/Luhn-test-of-credit-card-numbers/JavaScript/luhn-test-of-credit-card-numbers-2.js index fbea5ae3cf..16cd0da99b 100644 --- a/Task/Luhn-test-of-credit-card-numbers/JavaScript/luhn-test-of-credit-card-numbers-2.js +++ b/Task/Luhn-test-of-credit-card-numbers/JavaScript/luhn-test-of-credit-card-numbers-2.js @@ -1,19 +1,19 @@ var LuhnCheck = (function() { - var luhnArr = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9]; - return function(str) - { - var counter = 0; - var incNum; - var odd = false; - var temp = String(str).replace(/[^\d]/g, ""); - if ( temp.length == 0) - return false; - for (var i = temp.length-1; i >= 0; --i) - { - incNum = parseInt(temp.charAt(i), 10); - counter += (odd = !odd)? incNum : luhnArr[incNum]; - } - return (counter%10 == 0); - } + var luhnArr = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9]; + return function(str) + { + var counter = 0; + var incNum; + var odd = false; + var temp = String(str).replace(/[^\d]/g, ""); + if ( temp.length == 0) + return false; + for (var i = temp.length-1; i >= 0; --i) + { + incNum = parseInt(temp.charAt(i), 10); + counter += (odd = !odd)? incNum : luhnArr[incNum]; + } + return (counter%10 == 0); + } })(); diff --git a/Task/Luhn-test-of-credit-card-numbers/Julia/luhn-test-of-credit-card-numbers-1.julia b/Task/Luhn-test-of-credit-card-numbers/Julia/luhn-test-of-credit-card-numbers-1.jl similarity index 100% rename from Task/Luhn-test-of-credit-card-numbers/Julia/luhn-test-of-credit-card-numbers-1.julia rename to Task/Luhn-test-of-credit-card-numbers/Julia/luhn-test-of-credit-card-numbers-1.jl diff --git a/Task/Luhn-test-of-credit-card-numbers/Julia/luhn-test-of-credit-card-numbers-2.julia b/Task/Luhn-test-of-credit-card-numbers/Julia/luhn-test-of-credit-card-numbers-2.jl similarity index 100% rename from Task/Luhn-test-of-credit-card-numbers/Julia/luhn-test-of-credit-card-numbers-2.julia rename to Task/Luhn-test-of-credit-card-numbers/Julia/luhn-test-of-credit-card-numbers-2.jl diff --git a/Task/Luhn-test-of-credit-card-numbers/Kotlin/luhn-test-of-credit-card-numbers.kotlin b/Task/Luhn-test-of-credit-card-numbers/Kotlin/luhn-test-of-credit-card-numbers.kts similarity index 100% rename from Task/Luhn-test-of-credit-card-numbers/Kotlin/luhn-test-of-credit-card-numbers.kotlin rename to Task/Luhn-test-of-credit-card-numbers/Kotlin/luhn-test-of-credit-card-numbers.kts diff --git a/Task/Luhn-test-of-credit-card-numbers/Langur/luhn-test-of-credit-card-numbers.langur b/Task/Luhn-test-of-credit-card-numbers/Langur/luhn-test-of-credit-card-numbers.langur index e67b35d78d..61b17ec279 100644 --- a/Task/Luhn-test-of-credit-card-numbers/Langur/luhn-test-of-credit-card-numbers.langur +++ b/Task/Luhn-test-of-credit-card-numbers/Langur/luhn-test-of-credit-card-numbers.langur @@ -1,22 +1,22 @@ -val .luhntest = fn(.s) { - val .t = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9] - val .numbers = s2n .s - val .oddeven = len(.numbers) rem 2 +val luhntest = fn(s) { + val t = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9] + val numbers = s -> s2n + val oddeven = len(numbers) rem 2 - for[=0] .i of .numbers { - _for += if(.i rem 2 == .oddeven: .numbers[.i]; .t[.numbers[.i]+1]) + for[=0] i of numbers { + _for += if(i rem 2 == oddeven: numbers[i]; t[numbers[i]+1]) } div 10 } -val .tests = h{ +val tests = { "49927398716": true, "49927398717": false, "1234567812345678": false, "1234567812345670": true, } -for .key of .tests { - val .pass = .luhntest(.key) - write .key, ": ", .pass - writeln if(.pass == .tests[.key]: ""; " (LUHN TEST FAILED)") +for key in sort(keys(tests)) { + val pass = luhntest(key) + write key, ": ", pass + writeln if(pass == tests[key]: ""; " (LUHN TEST FAILED)") } diff --git a/Task/Luhn-test-of-credit-card-numbers/Lua/luhn-test-of-credit-card-numbers-1.lua b/Task/Luhn-test-of-credit-card-numbers/Lua/luhn-test-of-credit-card-numbers-1.lua new file mode 100644 index 0000000000..892105fe3a --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/Lua/luhn-test-of-credit-card-numbers-1.lua @@ -0,0 +1,16 @@ +function luhn(cc_number) + assert(type(cc_number) == 'string') + local sum = 0 + local is_odd = true + for idx = #cc_number , 1 , -1 do -- reverse order + -- extract single character as string then convert to integer + local digit = cc_number:sub(idx, idx) + 0 + if is_odd then + sum = sum + digit + else + sum = sum + ((digit * 2) % 10) + (digit // 5) + end -- if + is_odd = not is_odd -- toggle between odd and even + end -- for + return (sum % 10) == 0 +end -- function luhn_test diff --git a/Task/Luhn-test-of-credit-card-numbers/Lua/luhn-test-of-credit-card-numbers-2.lua b/Task/Luhn-test-of-credit-card-numbers/Lua/luhn-test-of-credit-card-numbers-2.lua new file mode 100644 index 0000000000..bae233bda1 --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/Lua/luhn-test-of-credit-card-numbers-2.lua @@ -0,0 +1,8 @@ +function luhn(digits) + local sum = 0 + for odd,even in digits:reverse():gmatch"(.)(.?)" do + local number = 2 * (tonumber(even) or 0) + sum = sum + odd + number%10 + number//10 + end + return sum%10==0 +end diff --git a/Task/Luhn-test-of-credit-card-numbers/Lua/luhn-test-of-credit-card-numbers-3.lua b/Task/Luhn-test-of-credit-card-numbers/Lua/luhn-test-of-credit-card-numbers-3.lua new file mode 100644 index 0000000000..e55e3ca948 --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/Lua/luhn-test-of-credit-card-numbers-3.lua @@ -0,0 +1,3 @@ +for _, val in ipairs{"49927398716", "49927398717", "1234567812345678", "1234567812345670"} do + print(val, luhn(val)) +end diff --git a/Task/Luhn-test-of-credit-card-numbers/Lua/luhn-test-of-credit-card-numbers.lua b/Task/Luhn-test-of-credit-card-numbers/Lua/luhn-test-of-credit-card-numbers.lua deleted file mode 100644 index 3f987b4d70..0000000000 --- a/Task/Luhn-test-of-credit-card-numbers/Lua/luhn-test-of-credit-card-numbers.lua +++ /dev/null @@ -1,31 +0,0 @@ -function luhn(n) - n=string.reverse(n) - print(n) - local s1=0 - --sum odd digits - for i=1,n:len(),2 do - s1=s1+n:sub(i,i) - end - --evens - local s2=0 - for i=2,n:len(),2 do - local doubled=n:sub(i,i)*2 - doubled=string.gsub(doubled,'(%d)(%d)',function(a,b)return a+b end) - s2=s2+doubled - end - print(s1) - print(s2) - local total=s1+s2 - if total%10==0 then - return true - end - return false -end - --- Note that this function takes strings, not numbers. --- 16-digit numbers tend to be problematic --- when looking at individual digits. -print(luhn'49927398716') -print(luhn'49927398717') -print(luhn'1234567812345678') -print(luhn'1234567812345670') diff --git a/Task/Luhn-test-of-credit-card-numbers/MATLAB/luhn-test-of-credit-card-numbers.m b/Task/Luhn-test-of-credit-card-numbers/MATLAB/luhn-test-of-credit-card-numbers.m index 71d63750e6..35a95a1cff 100644 --- a/Task/Luhn-test-of-credit-card-numbers/MATLAB/luhn-test-of-credit-card-numbers.m +++ b/Task/Luhn-test-of-credit-card-numbers/MATLAB/luhn-test-of-credit-card-numbers.m @@ -7,7 +7,7 @@ if nargin == 0 % evaluate test cases return end % luhn function starts here -d = int2str(num) - '0'; % convert number into vector of digits -m = [2:2:8,1:2:9]; % rule 3: maps 1:9 to [2 4 6 8 1 3 5 7 9] +d = int2str(num) - '0'; % convert number into vector of digits +m = [2:2:8,1:2:9]; % rule 3: maps 1:9 to [2 4 6 8 1 3 5 7 9] passed = ~mod(sum(d(end:-2:1)) + sum(m(d(end-1:-2:1))), 10); end diff --git a/Task/Luhn-test-of-credit-card-numbers/Modula-2/luhn-test-of-credit-card-numbers.mod2 b/Task/Luhn-test-of-credit-card-numbers/Modula-2/luhn-test-of-credit-card-numbers.mod2 new file mode 100644 index 0000000000..6ff97b5f25 --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/Modula-2/luhn-test-of-credit-card-numbers.mod2 @@ -0,0 +1,49 @@ +MODULE LuhnTestCreditCard; +(* Luhn test of credit card numbers *) + +FROM STextIO IMPORT + WriteString, WriteLn; + +CONST + MaxLen = 16; + +TYPE + TCardNum = ARRAY[0 .. MaxLen] OF CHAR; + TCards = ARRAY[0 .. 3] OF TCardNum; + +CONST + Cards = TCards{"49927398716", "49927398717", + "1234567812345678", "1234567812345670"}; +VAR + J: CARDINAL; + +PROCEDURE LuhnTest(C: ARRAY OF CHAR): BOOLEAN; +VAR + S, I, B, LastIndex: CARDINAL; +BEGIN + S := 0; + LastIndex := LENGTH(C) - 1; + FOR I := LastIndex TO 0 BY -2 DO + S := S + (ORD(C[I]) - ORD("0")) + END; + FOR I := LastIndex - 1 TO 0 BY -2 DO + B := (ORD(C[I]) - ORD("0")) * 2; + IF B >= 10 THEN + B := B - 9 + END; + S := S + B + END; + RETURN S MOD 10 = 0 +END LuhnTest; + +BEGIN + FOR J := 0 TO 3 DO + WriteString(Cards[J]); + IF LuhnTest(Cards[J]) THEN + WriteString(" is valid.") + ELSE + WriteString(" is invalid.") + END; + WriteLn; + END; +END LuhnTestCreditCard. diff --git a/Task/Luhn-test-of-credit-card-numbers/Nascom-BASIC/luhn-test-of-credit-card-numbers.basic b/Task/Luhn-test-of-credit-card-numbers/Nascom-BASIC/luhn-test-of-credit-card-numbers.basic new file mode 100644 index 0000000000..12f480a536 --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/Nascom-BASIC/luhn-test-of-credit-card-numbers.basic @@ -0,0 +1,22 @@ +10 REM Luhn test of credit card numbers +20 DATA "49927398716","49927398717" +30 DATA "1234567812345678","1234567812345670" +40 FOR J=1 TO 4 +50 READ C$:GOSUB 1000 +60 PRINT C$; +70 IF RV THEN PRINT " is valid.":GOTO 90 +80 PRINT " is invalid." +90 NEXT J +100 END +1000 REM ** Luhn test +1010 S=0 +1020 FOR I=LEN(C$) TO 1 STEP -2 +1030 S=S+VAL(MID$(C$,I,1)) +1040 NEXT I +1050 FOR I=LEN(C$)-1 TO 1 STEP -2 +1060 B=VAL(MID$(C$,I,1))*2 +1070 IF B>=10 THEN B=B-9 +1080 S=S+B +1090 NEXT I +1100 RV=(INT(S/10)*10=S) +1110 RETURN diff --git a/Task/Luhn-test-of-credit-card-numbers/NetRexx/luhn-test-of-credit-card-numbers.netrexx b/Task/Luhn-test-of-credit-card-numbers/NetRexx/luhn-test-of-credit-card-numbers.netrexx index 77d99e9900..d61365ea8a 100644 --- a/Task/Luhn-test-of-credit-card-numbers/NetRexx/luhn-test-of-credit-card-numbers.netrexx +++ b/Task/Luhn-test-of-credit-card-numbers/NetRexx/luhn-test-of-credit-card-numbers.netrexx @@ -1,7 +1,7 @@ class LuhnTest method main(args=String[]) static - cc = 0 + cc = 0 cc[1] = '49927398716' cc[2] = '49927398717' cc[3] = '1234567812345678' diff --git a/Task/Luhn-test-of-credit-card-numbers/OCaml/luhn-test-of-credit-card-numbers-1.ocaml b/Task/Luhn-test-of-credit-card-numbers/OCaml/luhn-test-of-credit-card-numbers-1.ml similarity index 100% rename from Task/Luhn-test-of-credit-card-numbers/OCaml/luhn-test-of-credit-card-numbers-1.ocaml rename to Task/Luhn-test-of-credit-card-numbers/OCaml/luhn-test-of-credit-card-numbers-1.ml diff --git a/Task/Luhn-test-of-credit-card-numbers/OCaml/luhn-test-of-credit-card-numbers-2.ocaml b/Task/Luhn-test-of-credit-card-numbers/OCaml/luhn-test-of-credit-card-numbers-2.ml similarity index 100% rename from Task/Luhn-test-of-credit-card-numbers/OCaml/luhn-test-of-credit-card-numbers-2.ocaml rename to Task/Luhn-test-of-credit-card-numbers/OCaml/luhn-test-of-credit-card-numbers-2.ml diff --git a/Task/Luhn-test-of-credit-card-numbers/Objective-C/luhn-test-of-credit-card-numbers.m b/Task/Luhn-test-of-credit-card-numbers/Objective-C/luhn-test-of-credit-card-numbers.m index 8eddacc30e..2c1a6f897a 100644 --- a/Task/Luhn-test-of-credit-card-numbers/Objective-C/luhn-test-of-credit-card-numbers.m +++ b/Task/Luhn-test-of-credit-card-numbers/Objective-C/luhn-test-of-credit-card-numbers.m @@ -1,38 +1,38 @@ - (NSArray *) toCharArray { - - NSMutableArray *characters = [[NSMutableArray alloc] initWithCapacity:[self length]]; - for (int i=0; i < [self length]; i++) { - NSString *ichar = [NSString stringWithFormat:@"%C", [self characterAtIndex:i]]; - [characters addObject:ichar]; - } - - return characters; + + NSMutableArray *characters = [[NSMutableArray alloc] initWithCapacity:[self length]]; + for (int i=0; i < [self length]; i++) { + NSString *ichar = [NSString stringWithFormat:@"%C", [self characterAtIndex:i]]; + [characters addObject:ichar]; + } + + return characters; } + (BOOL) luhnCheck:(NSString *)stringToTest { - - NSArray *stringAsChars = [stringToTest toCharArray]; - - BOOL isOdd = YES; - int oddSum = 0; - int evenSum = 0; - - for (int i = [stringToTest length] - 1; i >= 0; i--) { - - int digit = [(NSString *)stringAsChars[i] intValue]; - - if (isOdd) - oddSum += digit; - else - evenSum += digit/5 + (2*digit) % 10; - - isOdd = !isOdd; - } - - return ((oddSum + evenSum) % 10 == 0); + + NSArray *stringAsChars = [stringToTest toCharArray]; + + BOOL isOdd = YES; + int oddSum = 0; + int evenSum = 0; + + for (int i = [stringToTest length] - 1; i >= 0; i--) { + + int digit = [(NSString *)stringAsChars[i] intValue]; + + if (isOdd) + oddSum += digit; + else + evenSum += digit/5 + (2*digit) % 10; + + isOdd = !isOdd; + } + + return ((oddSum + evenSum) % 10 == 0); } BOOL test0 = [self luhnCheck:@"49927398716"]; //Result = YES BOOL test1 = [self luhnCheck:@"49927398717"]; //Result = NO -BOOL test2 = [self luhnCheck:@"1234567812345678"]; //Result = NO +BOOL test2 = [self luhnCheck:@"1234567812345678"]; //Result = NO BOOL test3 = [self luhnCheck:@"1234567812345670"]; //Result = YES diff --git a/Task/Luhn-test-of-credit-card-numbers/Octave/luhn-test-of-credit-card-numbers-1.octave b/Task/Luhn-test-of-credit-card-numbers/Octave/luhn-test-of-credit-card-numbers-1.octave index 8219d9a371..7b8291ffee 100644 --- a/Task/Luhn-test-of-credit-card-numbers/Octave/luhn-test-of-credit-card-numbers-1.octave +++ b/Task/Luhn-test-of-credit-card-numbers/Octave/luhn-test-of-credit-card-numbers-1.octave @@ -1,6 +1,6 @@ function y = isluhn(s); - if isnumeric(s) s = mat2str(s); end; % make sure s is a string - d = s-'0'; % convert string into vector of digits - m = [2:2:8,1:2:9]; % rule 3: maps [1:9] -> i - y = ~mod(sum(d(end:-2:1)) + sum(m(d(end-1:-2:1))),10); + if isnumeric(s) s = mat2str(s); end; % make sure s is a string + d = s-'0'; % convert string into vector of digits + m = [2:2:8,1:2:9]; % rule 3: maps [1:9] -> i + y = ~mod(sum(d(end:-2:1)) + sum(m(d(end-1:-2:1))),10); end; diff --git a/Task/Luhn-test-of-credit-card-numbers/Octave/luhn-test-of-credit-card-numbers-2.octave b/Task/Luhn-test-of-credit-card-numbers/Octave/luhn-test-of-credit-card-numbers-2.octave index 5925607d26..a2ea4174db 100644 --- a/Task/Luhn-test-of-credit-card-numbers/Octave/luhn-test-of-credit-card-numbers-2.octave +++ b/Task/Luhn-test-of-credit-card-numbers/Octave/luhn-test-of-credit-card-numbers-2.octave @@ -1,8 +1,8 @@ isluhn('49927398716') - ans = 1 + ans = 1 isluhn('49927398717') - ans = 0 + ans = 0 isluhn('1234567812345678') - ans = 0 + ans = 0 isluhn('1234567812345670') - ans = 1 + ans = 1 diff --git a/Task/Luhn-test-of-credit-card-numbers/Pascal/luhn-test-of-credit-card-numbers.pas b/Task/Luhn-test-of-credit-card-numbers/Pascal/luhn-test-of-credit-card-numbers.pas index 0db012f9cd..c39c5acf11 100644 --- a/Task/Luhn-test-of-credit-card-numbers/Pascal/luhn-test-of-credit-card-numbers.pas +++ b/Task/Luhn-test-of-credit-card-numbers/Pascal/luhn-test-of-credit-card-numbers.pas @@ -1,91 +1,91 @@ program luhnTestOfCreditCardNumbers(input, output); type - { - `string(…)` is an Extended Pascal, ISO 10206, extension. - `string(64)` discriminates the “schema” data type `string` - to contain at most 64 `char` values. - } - creditCardNumber = string(64); + { + `string(…)` is an Extended Pascal, ISO 10206, extension. + `string(64)` discriminates the “schema” data type `string` + to contain at most 64 `char` values. + } + creditCardNumber = string(64); { - \brief determines whether a string contains digits only - - \param sample the string to inspect - \return `false` iff `sample` contains non-digit characters + \brief determines whether a string contains digits only + + \param sample the string to inspect + \return `false` iff `sample` contains non-digit characters } { Extended Pascal: `protected` means the function cannot modify `sample` } function containsDigitsOnly(protected sample: creditCardNumber): Boolean; var - { EP: the `… value []` initializes this variable as an empty set } - characters: set of char value []; - { `sample.capacity` refers to `64` in this code. } - i: 1..sample.capacity; + { EP: the `… value []` initializes this variable as an empty set } + characters: set of char value []; + { `sample.capacity` refers to `64` in this code. } + i: 1..sample.capacity; begin - for i := 1 to length(sample) do - begin - { Union of sets indicated by `+`. } - characters := characters + [sample[i]] - end; - - { - In a Pascal `function` definition, - there must be one assignment to the (implicit) variable - bearing the same name as of the function. - This will be the return value. - } - { NB: This will return `true` even if `length(sample)` is zero. } - containsDigitsOnly := card(characters - ['0'..'9']) = 0 - { `card` is an Extended Pascal extension. } + for i := 1 to length(sample) do + begin + { Union of sets indicated by `+`. } + characters := characters + [sample[i]] + end; + + { + In a Pascal `function` definition, + there must be one assignment to the (implicit) variable + bearing the same name as of the function. + This will be the return value. + } + { NB: This will return `true` even if `length(sample)` is zero. } + containsDigitsOnly := card(characters - ['0'..'9']) = 0 + { `card` is an Extended Pascal extension. } end; { - \brief determines whether a string complies with ISO/IEC 7812-1 Luhn test - - \param sample the potentially correct credit card number - \return `true` if verification succeeds + \brief determines whether a string complies with ISO/IEC 7812-1 Luhn test + + \param sample the potentially correct credit card number + \return `true` if verification succeeds } function luhnCheck(protected sample: creditCardNumber): Boolean; - { - This _nested_ function is only accessible _within_ `luhnCheck`. - Outsourcing this code allows us to write a neat expression below. - } - function check: Boolean; - var - { Using `integer` sub-ranges ensures only these values are assigned. } - sum: 0..maxInt value 0; - i: 0..sample.capacity-1; - begin - for i := 0 to length(sample) - 1 do - begin - { `1 + ord(odd(i))` produces an alternating scale factor `* 1`/`* 2`. } - sum := sum + (1 + ord(odd(i))) * - { Obtain digit value for `integer` calculation. } - (ord(sample[length(sample) - i]) - ord('0')) - - { Reverse operation if digit sum > 9, i.e. we added “too much”. } - ord(odd(i) and (sample[length(sample) - i] >= '5')) * 9 - end; - - check := sum mod 10 = 0 - end; + { + This _nested_ function is only accessible _within_ `luhnCheck`. + Outsourcing this code allows us to write a neat expression below. + } + function check: Boolean; + var + { Using `integer` sub-ranges ensures only these values are assigned. } + sum: 0..maxInt value 0; + i: 0..sample.capacity-1; + begin + for i := 0 to length(sample) - 1 do + begin + { `1 + ord(odd(i))` produces an alternating scale factor `* 1`/`* 2`. } + sum := sum + (1 + ord(odd(i))) * + { Obtain digit value for `integer` calculation. } + (ord(sample[length(sample) - i]) - ord('0')) - + { Reverse operation if digit sum > 9, i.e. we added “too much”. } + ord(odd(i) and (sample[length(sample) - i] >= '5')) * 9 + end; + + check := sum mod 10 = 0 + end; begin - { - The Extended Pascal Boolean operator `and_then` (and `or_else`) - allows for “short-circuit evaluation”. - Otherwise, in Pascal `and` and `or` mandate complete evaluation. - } - luhnCheck := (length(sample) > 0) and_then containsDigitsOnly(sample) - and_then check + { + The Extended Pascal Boolean operator `and_then` (and `or_else`) + allows for “short-circuit evaluation”. + Otherwise, in Pascal `and` and `or` mandate complete evaluation. + } + luhnCheck := (length(sample) > 0) and_then containsDigitsOnly(sample) + and_then check end; { === MAIN ============================================================= } var - s: creditCardNumber; + s: creditCardNumber; begin - { `EOF` is short for `EOF(input)`. } - while not EOF do - begin - readLn(s); { equivalent to `readLn(input, s)` } - writeLn(luhnCheck(s)) { = `writeLn(output, …)` } - end + { `EOF` is short for `EOF(input)`. } + while not EOF do + begin + readLn(s); { equivalent to `readLn(input, s)` } + writeLn(luhnCheck(s)) { = `writeLn(output, …)` } + end end. diff --git a/Task/Luhn-test-of-credit-card-numbers/PascalABC.NET/luhn-test-of-credit-card-numbers.pas b/Task/Luhn-test-of-credit-card-numbers/PascalABC.NET/luhn-test-of-credit-card-numbers.pas new file mode 100644 index 0000000000..2a8fbbf6ae --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/PascalABC.NET/luhn-test-of-credit-card-numbers.pas @@ -0,0 +1,18 @@ +function doubleDigit(n: integer) := (n * 2).ToString.Select(c -> c.ToDigit).Sum; + +function LuhnCheck(creditCardNumber: string): boolean; +begin + var checkSum := creditCardNumber + .Select(c -> c.ToDigit) + .Reverse + .Select((digit, index) -> (if odd(index + 1) then digit else doubleDigit(digit))) + .Sum; + + result := checkSum mod 10 = 0; +end; + +begin + var testNumbers := |49927398716, 49927398717, 1234567812345678, 1234567812345670|; + foreach var testNumber in testNumbers do + Writeln(testnumber, ' is ', if LuhnCheck(testNumber.ToString) then '' else 'not ', 'valid'); +end. diff --git a/Task/Luhn-test-of-credit-card-numbers/Pluto/luhn-test-of-credit-card-numbers.pluto b/Task/Luhn-test-of-credit-card-numbers/Pluto/luhn-test-of-credit-card-numbers.pluto new file mode 100644 index 0000000000..fd67c11fad --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/Pluto/luhn-test-of-credit-card-numbers.pluto @@ -0,0 +1,22 @@ +function luhn(b) + local sum = 0 + local odd = true + for i = #b,1,-1 do + local n = tonumber(b[i]) + if odd then + sum += n + else + n *= 2 + sum += n//10 + n%10 + end + odd = !odd + end + return sum%10 == 0 +end + +a = {"49927398716", +"49927398717", +"1234567812345678", +"1234567812345670"} + +for a as i do print(luhn(i)) end diff --git a/Task/Luhn-test-of-credit-card-numbers/PowerShell/luhn-test-of-credit-card-numbers-1.psh b/Task/Luhn-test-of-credit-card-numbers/PowerShell/luhn-test-of-credit-card-numbers-1.ps1 similarity index 100% rename from Task/Luhn-test-of-credit-card-numbers/PowerShell/luhn-test-of-credit-card-numbers-1.psh rename to Task/Luhn-test-of-credit-card-numbers/PowerShell/luhn-test-of-credit-card-numbers-1.ps1 diff --git a/Task/Luhn-test-of-credit-card-numbers/PowerShell/luhn-test-of-credit-card-numbers-2.psh b/Task/Luhn-test-of-credit-card-numbers/PowerShell/luhn-test-of-credit-card-numbers-2.ps1 similarity index 100% rename from Task/Luhn-test-of-credit-card-numbers/PowerShell/luhn-test-of-credit-card-numbers-2.psh rename to Task/Luhn-test-of-credit-card-numbers/PowerShell/luhn-test-of-credit-card-numbers-2.ps1 diff --git a/Task/Luhn-test-of-credit-card-numbers/PowerShell/luhn-test-of-credit-card-numbers-3.psh b/Task/Luhn-test-of-credit-card-numbers/PowerShell/luhn-test-of-credit-card-numbers-3.ps1 similarity index 100% rename from Task/Luhn-test-of-credit-card-numbers/PowerShell/luhn-test-of-credit-card-numbers-3.psh rename to Task/Luhn-test-of-credit-card-numbers/PowerShell/luhn-test-of-credit-card-numbers-3.ps1 diff --git a/Task/Luhn-test-of-credit-card-numbers/Python/luhn-test-of-credit-card-numbers-1.py b/Task/Luhn-test-of-credit-card-numbers/Python/luhn-test-of-credit-card-numbers-1.py index d058225561..fd77a37fc4 100644 --- a/Task/Luhn-test-of-credit-card-numbers/Python/luhn-test-of-credit-card-numbers-1.py +++ b/Task/Luhn-test-of-credit-card-numbers/Python/luhn-test-of-credit-card-numbers-1.py @@ -1,6 +1,6 @@ >>> def luhn(n): - r = [int(ch) for ch in str(n)][::-1] - return (sum(r[0::2]) + sum(sum(divmod(d*2,10)) for d in r[1::2])) % 10 == 0 + r = [int(ch) for ch in str(n)][::-1] + return (sum(r[0::2]) + sum(sum(divmod(d*2,10)) for d in r[1::2])) % 10 == 0 >>> for n in (49927398716, 49927398717, 1234567812345678, 1234567812345670): - print(n, luhn(n)) + print(n, luhn(n)) diff --git a/Task/Luhn-test-of-credit-card-numbers/QBasic/luhn-test-of-credit-card-numbers.basic b/Task/Luhn-test-of-credit-card-numbers/QBasic/luhn-test-of-credit-card-numbers.basic index 25e7b7cf33..eb9d93f266 100644 --- a/Task/Luhn-test-of-credit-card-numbers/QBasic/luhn-test-of-credit-card-numbers.basic +++ b/Task/Luhn-test-of-credit-card-numbers/QBasic/luhn-test-of-credit-card-numbers.basic @@ -19,7 +19,7 @@ FOR test = 1 TO 4 IF num <= 9 THEN sum = sum + num ELSE - sum = sum + VAL(LEFT$(STR$(num), 1)) + VAL(RIGHT$(STR$(num), 1)) + sum = sum + num - 9 END IF odd = True END IF diff --git a/Task/Luhn-test-of-credit-card-numbers/Rebol/luhn-test-of-credit-card-numbers.rebol b/Task/Luhn-test-of-credit-card-numbers/Rebol/luhn-test-of-credit-card-numbers.rebol new file mode 100644 index 0000000000..2537400919 --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/Rebol/luhn-test-of-credit-card-numbers.rebol @@ -0,0 +1,44 @@ +Rebol [ + title: "Rosetta code: Luhn test of credit card numbers" + file: %Luhn_test_of_credit_card_numbers.r3 + url: https://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers +] + +luhn?: function [ + "Luhn algorithm validator - returns true/false if a number passes the Luhn check." + "Used to validate credit card numbers and other identification numbers." + num [integer! string!] +][ + sum: 0 + ;; Define a character set matching only numeric digits '0' through '9' + digit: system/catalog/bitsets/numeric + + ;; Reverse the string so we process digits right-to-left, as Luhn requires. + parse reverse form num [ + ;; SOME means "match the following pattern one or more times" + some [ + ;; --- ODD position digits (1st, 3rd, 5th... from the right) --- + set num: digit ( + ;; Convert char to integer by subtracting ASCII value of '0' + ;; and add directly to sum (odd-position digits are unchanged) + sum: sum + num - #"0" + ) + ;; --- EVEN position digits (2nd, 4th, 6th... from the right) --- + opt [set num: digit ( + ;; Double the digit (after converting char to integer) + num: 2 * (num - #"0") + ;; If doubling gives > 9, subtract 9 (equivalent to summing the + ;; two digits of the result, e.g. 14 -> 1+4=5, same as 14-9=5) + if num > 9 [num: num - 9] + ;; Add the adjusted even-position digit to the running sum + sum: sum + num + )] + ] + ] + ;; Return true if total sum is divisible by 10 (Luhn check passes) + zero? sum % 10 +] + +foreach num [49927398716 49927398717 1234567812345678 1234567812345670][ + print [num 'is pick [valid invalid] luhn? num "number."] +] diff --git a/Task/Luhn-test-of-credit-card-numbers/Ruby/luhn-test-of-credit-card-numbers-3.rb b/Task/Luhn-test-of-credit-card-numbers/Ruby/luhn-test-of-credit-card-numbers-3.rb new file mode 100644 index 0000000000..e7c65f5f9d --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/Ruby/luhn-test-of-credit-card-numbers-3.rb @@ -0,0 +1,16 @@ +def luhn_valid?(card_string) + digit_sum = card_string.reverse.chars.map.with_index(1) { |c, i| + digit = c.to_i + + next digit if i.odd? + next digit if digit == 9 + + (digit * 2) % 9 + }.sum + + digit_sum % 10 == 0 +end + +['49927398716','49927398717','1234567812345678','1234567812345670'].each do |card_string| + puts "#{card_string}: #{luhn_valid?(card_string)}" +end diff --git a/Task/Luhn-test-of-credit-card-numbers/Rust/luhn-test-of-credit-card-numbers.rust b/Task/Luhn-test-of-credit-card-numbers/Rust/luhn-test-of-credit-card-numbers.rs similarity index 100% rename from Task/Luhn-test-of-credit-card-numbers/Rust/luhn-test-of-credit-card-numbers.rust rename to Task/Luhn-test-of-credit-card-numbers/Rust/luhn-test-of-credit-card-numbers.rs diff --git a/Task/Luhn-test-of-credit-card-numbers/SETL/luhn-test-of-credit-card-numbers.setl b/Task/Luhn-test-of-credit-card-numbers/SETL/luhn-test-of-credit-card-numbers.setl new file mode 100644 index 0000000000..73d45aa270 --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/SETL/luhn-test-of-credit-card-numbers.setl @@ -0,0 +1,18 @@ +program luhn_test; + tests := [ + 49927398716, + 49927398717, + 1234567812345678, + 1234567812345670 + ]; + + loop for test in tests do + print(test, if luhn test then "pass" else "fail" end); + end loop; + + op luhn(n); + fac := 2; + digits := [val d * (fac := 3-fac) : d in reverse str n]; + return 0 = +/[d - if d>9 then 9 else 0 end : d in digits] mod 10; + end op; +end program; diff --git a/Task/Luhn-test-of-credit-card-numbers/Scheme/luhn-test-of-credit-card-numbers.ss b/Task/Luhn-test-of-credit-card-numbers/Scheme/luhn-test-of-credit-card-numbers.scm similarity index 100% rename from Task/Luhn-test-of-credit-card-numbers/Scheme/luhn-test-of-credit-card-numbers.ss rename to Task/Luhn-test-of-credit-card-numbers/Scheme/luhn-test-of-credit-card-numbers.scm diff --git a/Task/Luhn-test-of-credit-card-numbers/SenseTalk/luhn-test-of-credit-card-numbers-1.sensetalk b/Task/Luhn-test-of-credit-card-numbers/SenseTalk/luhn-test-of-credit-card-numbers-1.sensetalk index b2f3b5f7cf..9db262bd73 100644 --- a/Task/Luhn-test-of-credit-card-numbers/SenseTalk/luhn-test-of-credit-card-numbers-1.sensetalk +++ b/Task/Luhn-test-of-credit-card-numbers/SenseTalk/luhn-test-of-credit-card-numbers-1.sensetalk @@ -1,16 +1,16 @@ function LuhnCheck ccNum - put length of ccNum into numDigits - put the last character of ccNum into total - put numDigits modulo 2 into parity - repeat for each character of the first numDigits - 1 characters of ccNum - put it into digit - if (the counter - 1) modulo 2 equals parity - multiply digit by 2 - end if - if digit is greater than 9 - subtract 9 from digit - end if - add digit to total - end repeat - return total is divisible by 10 + put length of ccNum into numDigits + put the last character of ccNum into total + put numDigits modulo 2 into parity + repeat for each character of the first numDigits - 1 characters of ccNum + put it into digit + if (the counter - 1) modulo 2 equals parity + multiply digit by 2 + end if + if digit is greater than 9 + subtract 9 from digit + end if + add digit to total + end repeat + return total is divisible by 10 end LuhnCheck diff --git a/Task/Luhn-test-of-credit-card-numbers/SenseTalk/luhn-test-of-credit-card-numbers-2.sensetalk b/Task/Luhn-test-of-credit-card-numbers/SenseTalk/luhn-test-of-credit-card-numbers-2.sensetalk index 63a75f3e4e..c81dfc9762 100644 --- a/Task/Luhn-test-of-credit-card-numbers/SenseTalk/luhn-test-of-credit-card-numbers-2.sensetalk +++ b/Task/Luhn-test-of-credit-card-numbers/SenseTalk/luhn-test-of-credit-card-numbers-2.sensetalk @@ -1,3 +1,3 @@ repeat for each item of (49927398716, 49927398717, 1234567812345678, 1234567812345670) - put it && LuhnCheck(it) + put it && LuhnCheck(it) end repeat diff --git a/Task/Luhn-test-of-credit-card-numbers/SequenceL/luhn-test-of-credit-card-numbers.sequencel b/Task/Luhn-test-of-credit-card-numbers/SequenceL/luhn-test-of-credit-card-numbers.sequencel index de8684e30f..1ebf61945c 100644 --- a/Task/Luhn-test-of-credit-card-numbers/SequenceL/luhn-test-of-credit-card-numbers.sequencel +++ b/Task/Luhn-test-of-credit-card-numbers/SequenceL/luhn-test-of-credit-card-numbers.sequencel @@ -1,8 +1,8 @@ main(args(2)) := - sum(luhnTest(asciiToInt(args[1]) - asciiToInt('0'))) mod 10 = 0; + sum(luhnTest(asciiToInt(args[1]) - asciiToInt('0'))) mod 10 = 0; s2Mapping := [0,2,4,6,8,1,3,5,7,9]; luhnTest(x(1))[i] := - x[i] when i mod 2 = size(x) mod 2 else - s2Mapping[x[i] + 1]; + x[i] when i mod 2 = size(x) mod 2 else + s2Mapping[x[i] + 1]; diff --git a/Task/Luhn-test-of-credit-card-numbers/Tcl/luhn-test-of-credit-card-numbers-1.tcl b/Task/Luhn-test-of-credit-card-numbers/Tcl/luhn-test-of-credit-card-numbers-1.tcl index cb1e1960c5..716d16bffd 100644 --- a/Task/Luhn-test-of-credit-card-numbers/Tcl/luhn-test-of-credit-card-numbers-1.tcl +++ b/Task/Luhn-test-of-credit-card-numbers/Tcl/luhn-test-of-credit-card-numbers-1.tcl @@ -4,10 +4,10 @@ proc luhn digitString { set sum 0 set flip 1 foreach ch [lreverse [split $digitString {}]] { - incr sum [lindex { - {0 1 2 3 4 5 6 7 8 9} - {0 2 4 6 8 1 3 5 7 9} - } [expr {[incr flip] & 1}] $ch] + incr sum [lindex { + {0 1 2 3 4 5 6 7 8 9} + {0 2 4 6 8 1 3 5 7 9} + } [expr {[incr flip] & 1}] $ch] } return [expr {($sum % 10) == 0}] } diff --git a/Task/Luhn-test-of-credit-card-numbers/Tcl/luhn-test-of-credit-card-numbers-2.tcl b/Task/Luhn-test-of-credit-card-numbers/Tcl/luhn-test-of-credit-card-numbers-2.tcl index b4cb9ddd18..e3278f4a01 100644 --- a/Task/Luhn-test-of-credit-card-numbers/Tcl/luhn-test-of-credit-card-numbers-2.tcl +++ b/Task/Luhn-test-of-credit-card-numbers/Tcl/luhn-test-of-credit-card-numbers-2.tcl @@ -5,5 +5,5 @@ foreach testNumber { 1234567812345670 } { puts [format "%s is %s" $testNumber \ - [lindex {"NOT valid" "valid"} [luhn $testNumber]]] + [lindex {"NOT valid" "valid"} [luhn $testNumber]]] } diff --git a/Task/Luhn-test-of-credit-card-numbers/Transact-SQL/luhn-test-of-credit-card-numbers.sql b/Task/Luhn-test-of-credit-card-numbers/Transact-SQL/luhn-test-of-credit-card-numbers.sql index b3c613d2ce..1c95eea5d4 100644 --- a/Task/Luhn-test-of-credit-card-numbers/Transact-SQL/luhn-test-of-credit-card-numbers.sql +++ b/Task/Luhn-test-of-credit-card-numbers/Transact-SQL/luhn-test-of-credit-card-numbers.sql @@ -2,18 +2,18 @@ CREATE FUNCTION dbo._CreditCardNumCheck( @strCCNum VarChar(40) ) RETURNS VarChar(7) AS BEGIN - DECLARE @string VarChar(40) = REVERSE(@strCCNum); -- usage: set once, never changed - DECLARE @strS2Values VarChar(10) = '0246813579'; -- constant: maps digits to their S2 summed values - DECLARE @table TABLE (ID INT, Value INT, S_Value INT); -- ID=digit position. S_Value is used for SUM(). - DECLARE @p INT = 0; -- loop counter: position in string - -- Convert the reversed string's digits into rows in a table variable, S_Values to be updated afterwards - WHILE @p < LEN(@string) - BEGIN - SET @p = @p+1; - INSERT INTO @table (ID,Value,S_Value) VALUES (@p, CONVERT(INT,SUBSTRING(@string,@p,1)), 0); - END - -- Update S_Value column : the digit's value to be summed (for even-positioned digits this is mapped via @strS2Values) - UPDATE @table SET S_Value = CASE WHEN ID % 2 = 1 THEN Value ELSE CONVERT(INT,SUBSTRING(@strS2Values,Value+1,1)) END - -- If the SUM of S_Values ends in 0 (modulo 10 = 0) then the CC Number is valid - RETURN CASE WHEN (SELECT SUM(S_Value) FROM @table) % 10 = 0 THEN 'Valid' ELSE 'Invalid' END + DECLARE @string VarChar(40) = REVERSE(@strCCNum); -- usage: set once, never changed + DECLARE @strS2Values VarChar(10) = '0246813579'; -- constant: maps digits to their S2 summed values + DECLARE @table TABLE (ID INT, Value INT, S_Value INT); -- ID=digit position. S_Value is used for SUM(). + DECLARE @p INT = 0; -- loop counter: position in string + -- Convert the reversed string's digits into rows in a table variable, S_Values to be updated afterwards + WHILE @p < LEN(@string) + BEGIN + SET @p = @p+1; + INSERT INTO @table (ID,Value,S_Value) VALUES (@p, CONVERT(INT,SUBSTRING(@string,@p,1)), 0); + END + -- Update S_Value column : the digit's value to be summed (for even-positioned digits this is mapped via @strS2Values) + UPDATE @table SET S_Value = CASE WHEN ID % 2 = 1 THEN Value ELSE CONVERT(INT,SUBSTRING(@strS2Values,Value+1,1)) END + -- If the SUM of S_Values ends in 0 (modulo 10 = 0) then the CC Number is valid + RETURN CASE WHEN (SELECT SUM(S_Value) FROM @table) % 10 = 0 THEN 'Valid' ELSE 'Invalid' END END diff --git a/Task/Luhn-test-of-credit-card-numbers/Uiua/luhn-test-of-credit-card-numbers.uiua b/Task/Luhn-test-of-credit-card-numbers/Uiua/luhn-test-of-credit-card-numbers.uiua new file mode 100644 index 0000000000..46ed815ca7 --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/Uiua/luhn-test-of-credit-card-numbers.uiua @@ -0,0 +1,6 @@ +Luhn ← =0◿10+⊃(/+⊢|/+∵(⍥(-9)>9.×2)⊡1)⍉⬚0↯∞_2⇌ +T ← {"49927398716" + "49927398717" + "1234567812345678" + "1234567812345670"} +≡◇(Luhn ≡⋕) T diff --git a/Task/Luhn-test-of-credit-card-numbers/V-(Vlang)/luhn-test-of-credit-card-numbers.v b/Task/Luhn-test-of-credit-card-numbers/V-(Vlang)/luhn-test-of-credit-card-numbers.v index b9a29520f7..839d4c9730 100644 --- a/Task/Luhn-test-of-credit-card-numbers/V-(Vlang)/luhn-test-of-credit-card-numbers.v +++ b/Task/Luhn-test-of-credit-card-numbers/V-(Vlang)/luhn-test-of-credit-card-numbers.v @@ -1,8 +1,9 @@ const ( - input = '49927398716 -49927398717 -1234567812345678 -1234567812345670' + input = " + 49927398716 + 49927398717 + 1234567812345678 + 1234567812345670" t = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9] ) @@ -10,21 +11,16 @@ const ( fn luhn(s string) bool { odd := s.len & 1 mut sum := 0 - for i, c in s.split('') { - if c < '0' || c > '9' { - return false - } - if i&1 == odd { - sum += t[c.int()-'0'.int()] - } else { - sum += c.int() - '0'.int() - } + for i, c in s.split("") { + if c < '0' || c > '9' {return false} + if i&1 == odd {sum += t[c.int()-'0'.int()]} + else {sum += c.int() - '0'.int()} } - return sum%10 == 0 + return sum % 10 == 0 } fn main() { - for s in input.split("\n") { - println('$s ${luhn(s)}') + for s in input.trim_indent().split_into_lines() { + println("${s} ${luhn(s)}") } } diff --git a/Task/Luhn-test-of-credit-card-numbers/VBScript/luhn-test-of-credit-card-numbers.vb b/Task/Luhn-test-of-credit-card-numbers/VBScript/luhn-test-of-credit-card-numbers.vb deleted file mode 100644 index c89906e644..0000000000 --- a/Task/Luhn-test-of-credit-card-numbers/VBScript/luhn-test-of-credit-card-numbers.vb +++ /dev/null @@ -1,33 +0,0 @@ -Function Luhn_Test(cc) - cc = RevString(cc) - s1 = 0 - s2 = 0 - For i = 1 To Len(cc) - If i Mod 2 > 0 Then - s1 = s1 + CInt(Mid(cc,i,1)) - Else - tmp = CInt(Mid(cc,i,1))*2 - If tmp < 10 Then - s2 = s2 + tmp - Else - s2 = s2 + CInt(Right(CStr(tmp),1)) + 1 - End If - End If - Next - If Right(CStr(s1 + s2),1) = "0" Then - Luhn_Test = "Valid" - Else - Luhn_Test = "Invalid" - End If -End Function - -Function RevString(s) - For i = Len(s) To 1 Step -1 - RevString = RevString & Mid(s,i,1) - Next -End Function - -WScript.Echo "49927398716 is " & Luhn_Test("49927398716") -WScript.Echo "49927398717 is " & Luhn_Test("49927398717") -WScript.Echo "1234567812345678 is " & Luhn_Test("1234567812345678") -WScript.Echo "1234567812345670 is " & Luhn_Test("1234567812345670") diff --git a/Task/Luhn-test-of-credit-card-numbers/VBScript/luhn-test-of-credit-card-numbers.vbs b/Task/Luhn-test-of-credit-card-numbers/VBScript/luhn-test-of-credit-card-numbers.vbs new file mode 100644 index 0000000000..fc36dcede3 --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/VBScript/luhn-test-of-credit-card-numbers.vbs @@ -0,0 +1,33 @@ +Function Luhn_Test(cc) + cc = RevString(cc) + s1 = 0 + s2 = 0 + For i = 1 To Len(cc) + If i Mod 2 > 0 Then + s1 = s1 + CInt(Mid(cc,i,1)) + Else + tmp = CInt(Mid(cc,i,1))*2 + If tmp < 10 Then + s2 = s2 + tmp + Else + s2 = s2 + CInt(Right(CStr(tmp),1)) + 1 + End If + End If + Next + If Right(CStr(s1 + s2),1) = "0" Then + Luhn_Test = "Valid" + Else + Luhn_Test = "Invalid" + End If +End Function + +Function RevString(s) + For i = Len(s) To 1 Step -1 + RevString = RevString & Mid(s,i,1) + Next +End Function + +WScript.Echo "49927398716 is " & Luhn_Test("49927398716") +WScript.Echo "49927398717 is " & Luhn_Test("49927398717") +WScript.Echo "1234567812345678 is " & Luhn_Test("1234567812345678") +WScript.Echo "1234567812345670 is " & Luhn_Test("1234567812345670") diff --git a/Task/Luhn-test-of-credit-card-numbers/YAMLScript/luhn-test-of-credit-card-numbers.ys b/Task/Luhn-test-of-credit-card-numbers/YAMLScript/luhn-test-of-credit-card-numbers.ys new file mode 100644 index 0000000000..6a2092d4d6 --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/YAMLScript/luhn-test-of-credit-card-numbers.ys @@ -0,0 +1,10 @@ +!YS-v0 + +defn main(*nums): + each cc nums: + say: "$cc - $if(cc:luhn? 'valid' 'invalid')" + +defn luhn?(cc): + map(mul cc:digits:reverse [1 2]:cycle) + .map(\(I(_ / 10) + (_ % 10))):sum + .mod(10):zero? diff --git a/Task/Lychrel-numbers/00-TASK.txt b/Task/Lychrel-numbers/00-TASK.txt index 66e853aacb..f0fa9ef0b3 100644 --- a/Task/Lychrel-numbers/00-TASK.txt +++ b/Task/Lychrel-numbers/00-TASK.txt @@ -27,7 +27,7 @@ Some starting numbers seem to go on forever; the recurrence relation for 196 has These numbers that do not end in a palindrome are called '''Lychrel numbers'''. -For the purposes of this task a Lychrel number is any starting number that does not form a palindrome within 500 (or more) iterations. +For the purposes of this task a Lychrel number is any starting number that does not form a palindrome within 500 (or more) iterations; the existence of Lychrel numbers in base 10 is unproven, but there are known Lychrel numbers in binary and hexadecimal. ;Seed and related Lychrel numbers: diff --git a/Task/Lychrel-numbers/11l/lychrel-numbers.11l b/Task/Lychrel-numbers/11l/lychrel-numbers.11l index 63fca52e23..ff3935237f 100644 --- a/Task/Lychrel-numbers/11l/lychrel-numbers.11l +++ b/Task/Lychrel-numbers/11l/lychrel-numbers.11l @@ -10,7 +10,7 @@ F lychrel(BigInt =n) V r = rev(n) V res = (1B, n) [BigInt] seen - L(i) 1000 + L(i) 0.<1000 n += r r = rev(n) I n == r diff --git a/Task/Lychrel-numbers/BASIC/lychrel-numbers.basic b/Task/Lychrel-numbers/BASIC/lychrel-numbers.basic index dea6aefa31..f6622b7c15 100644 --- a/Task/Lychrel-numbers/BASIC/lychrel-numbers.basic +++ b/Task/Lychrel-numbers/BASIC/lychrel-numbers.basic @@ -133,7 +133,7 @@ SUB doAddLychrel (WhichNumber AS LONG) iRow = iRow + 1 IF iRow > iMaxR THEN ' Change to REDIM PRESERVE for VB-DOS, QB, QBASIC and PDS 7.1 - REDIM _PRESERVE lNum(1 TO iMaxR + 10) AS LONG + REDIM _PRESERVE lNum(1 TO iMaxR + 10) AS LONG END IF sN1 = LTRIM$(STR$(lRes)) sN2 = Reverse$(sN1) @@ -157,7 +157,7 @@ SUB doAddLychrel (WhichNumber AS LONG) REDIM lLC(1 TO iMaxR, 1 TO iMaxC) AS LONG ELSE ' Change to REDIM PRESERVE for VB-DOS, QB, QBASIC and PDS 7.1 - REDIM _PRESERVE lLC(1 TO iMaxR, 1 TO iMaxC) AS LONG + REDIM _PRESERVE lLC(1 TO iMaxR, 1 TO iMaxC) AS LONG END IF ' Assigns the result to the table @@ -227,7 +227,7 @@ SUB doFindLychrelPalyndromes () ERASE lPN END IF ' Change to REDIM PRESERVE for VB-DOS, QB, QBASIC and PDS 7.1 - REDIM _PRESERVE lPN(1 TO iCount + 9) AS LONG + REDIM _PRESERVE lPN(1 TO iCount + 9) AS LONG END IF RETURN diff --git a/Task/Lychrel-numbers/Crystal/lychrel-numbers.crystal b/Task/Lychrel-numbers/Crystal/lychrel-numbers.cr similarity index 100% rename from Task/Lychrel-numbers/Crystal/lychrel-numbers.crystal rename to Task/Lychrel-numbers/Crystal/lychrel-numbers.cr diff --git a/Task/Lychrel-numbers/EasyLang/lychrel-numbers.easy b/Task/Lychrel-numbers/EasyLang/lychrel-numbers.easy new file mode 100644 index 0000000000..1598a402a7 --- /dev/null +++ b/Task/Lychrel-numbers/EasyLang/lychrel-numbers.easy @@ -0,0 +1,118 @@ +func[] bn s$ . + i = len s$ - 7 + 1 + while i >= -5 + r[] &= number substr s$ i 7 + i -= 7 + . + return r[] +. +func$ bns bn[] . + s$ = bn[$] + for i = len bn[] - 1 downto 1 + h$ = bn[i] + s$ &= substr "0000000" 1 (7 - len h$) & h$ + . + return s$ +. +func[] bnadd a[] b[] . + if len b[] > len a[] : swap a[] b[] + len r[] len a[] + for i = 1 to len r[] + v = 0 + if i <= len b[] : v = b[i] + h += a[i] + v + r[i] = h mod 10000000 + h = h div 10000000 + . + if h > 0 : r[] &= h + while len r[] > 1 and r[$] = 0 : len r[] -1 + return r[] +. +func[] bnrev a[] . + for c$ in strchars bns a[] : r$ = c$ & r$ + return bn r$ +. +func bnpal a[] . + s$[] = strchars bns a[] + for i = 1 to len s$[] div 2 + if s$[i] <> s$[$ - i + 1] : return 0 + . + return 1 +. +global seeds$[] lnkkey$[] lnkval$[] . +func idxof a$[] key$ . + for i = 1 to len a$[] : if a$[i] = key$ : return i + return 0 +. +func maphas k$ . + return if idxof lnkkey$[] k$ <> 0 +. +func$ mapget k$ . + p = idxof lnkkey$[] k$ + if p = 0 : return "" + return lnkval$[p] +. +proc mapset k$ v$ . + p = idxof lnkkey$[] k$ + if p = 0 + lnkkey$[] &= k$ + lnkval$[] &= v$ + else + lnkval$[p] = v$ + . +. +func isrelated k$ . + v$ = mapget k$ + while v$ <> "" and maphas v$ = 1 + v$ = mapget v$ + . + return if idxof seeds$[] v$ <> 0 +. +proc check_bn val[] . + num$ = bns val[] + if maphas num$ = 1 : return + for n = 1 to 500 + rev[] = bnrev val[] + val[] = bnadd val[] rev[] + val$ = bns val[] + if maphas val$ = 1 + mapset num$ mapget val$ + return + . + if bnpal val[] = 1 : return + mapset val$ num$ + . + seeds$[] &= num$ +. +func related_cnt maxlen . + for k$ in lnkkey$[] + if len k$ <= maxlen and isrelated k$ = 1 : cnt += 1 + . + return cnt +. +func[] pal_lychrel maxlen . + for s$ in seeds$[] + if len s$ <= maxlen and bnpal bn s$ = 1 + res[] &= number s$ + . + . + for s$ in lnkkey$[] + if len s$ <= maxlen and isrelated s$ = 1 and bnpal bn s$ = 1 + res[] &= number s$ + . + . + for i = 1 to len res[] - 1 + for j = i + 1 to len res[] + if res[j] < res[i] : swap res[j] res[i] + . + . + return res[] +. +for n = 1 to 10000 : check_bn bn n +# +print "Found " & len seeds$[] & " candidate seed Lychrel numbers between 1 and 10000." +write "These candidate seed Lychrel numbers are: " +print strjoin seeds$[] " " +print "Found " & related_cnt 4 & " candidate related Lychrel numbers between 1 and 10000." +write "Palindromic candidate Lychrel numbers between 1 and 10000 are: " +print strjoin pal_lychrel 4 " " diff --git a/Task/Lychrel-numbers/Fortran/lychrel-numbers.f b/Task/Lychrel-numbers/Fortran/lychrel-numbers.f index 23698faaf5..4ac7cb6986 100644 --- a/Task/Lychrel-numbers/Fortran/lychrel-numbers.f +++ b/Task/Lychrel-numbers/Fortran/lychrel-numbers.f @@ -1,222 +1,222 @@ - SUBROUTINE CROAK(GASP) !A dying message. - CHARACTER*(*) GASP !The message. - WRITE (6,*) "Oh dear! ",GASP !The gasp. - STOP "Alas." !The death. - END !Goodbye, cruel world. + SUBROUTINE CROAK(GASP) !A dying message. + CHARACTER*(*) GASP !The message. + WRITE (6,*) "Oh dear! ",GASP !The gasp. + STOP "Alas." !The death. + END !Goodbye, cruel world. - MODULE LYCHREL SEARCH !Assistants for the pursuit of Lychrel numbers. - INTEGER LOTSADIGITS,BASE !Parameters. - PARAMETER (LOTSADIGITS = 1000, BASE = 10) !This should do. - TYPE BIGINT !Can't use an element zero as the count, as lots of digits are needed. - INTEGER LDIGIT !Count in use. - INTEGER*1 DIGIT(LOTSADIGITS) !Stored in increasing powers of BASE. - END TYPE BIGINT !No fractional parts. - INTEGER MSTASH !Now for my stash. - PARAMETER (MSTASH = 66666) !This should be enough. - TYPE(BIGINT) STASH(MSTASH) !The work area. - INTEGER AVAILS(0:MSTASH) !A list of available STASH entries. - INTEGER PLIST(0:MSTASH) !These strings of fingers - INTEGER LLIST(0:MSTASH) !Each starting with a count + MODULE LYCHREL SEARCH !Assistants for the pursuit of Lychrel numbers. + INTEGER LOTSADIGITS,BASE !Parameters. + PARAMETER (LOTSADIGITS = 1000, BASE = 10) !This should do. + TYPE BIGINT !Can't use an element zero as the count, as lots of digits are needed. + INTEGER LDIGIT !Count in use. + INTEGER*1 DIGIT(LOTSADIGITS) !Stored in increasing powers of BASE. + END TYPE BIGINT !No fractional parts. + INTEGER MSTASH !Now for my stash. + PARAMETER (MSTASH = 66666) !This should be enough. + TYPE(BIGINT) STASH(MSTASH) !The work area. + INTEGER AVAILS(0:MSTASH) !A list of available STASH entries. + INTEGER PLIST(0:MSTASH) !These strings of fingers + INTEGER LLIST(0:MSTASH) !Each starting with a count INTEGER LYCHREL(0:MSTASH)!Finger BIGINTs in the STASH - INTEGER L0P(0:MSTASH) !Without the body of the BIGINT being copied. - INTEGER LONGESTNUMBER !Keep track out of curiosity. - DATA LONGESTNUMBER/0/ !No digits so far. - CONTAINS !A miscellany. + INTEGER L0P(0:MSTASH) !Without the body of the BIGINT being copied. + INTEGER LONGESTNUMBER !Keep track out of curiosity. + DATA LONGESTNUMBER/0/ !No digits so far. + CONTAINS !A miscellany. Commence with some STASH service. If problems were to arise, better error messages would be in order. - SUBROUTINE PREPARESTASH !Since fancy usage is involved, fancy initialisation is needed. - INTEGER I !A stepper. - AVAILS(0) = MSTASH !All are available. - FORALL (I = 1:MSTASH) AVAILS(I) = MSTASH + 1 - I !Will be used stack style. - STASH.LDIGIT = -666 !This will cause trouble! - END SUBROUTINE PREPARESTASH !Simple enough. - SUBROUTINE GRABSTASH(X) !Finger an available STASH. - INTEGER X !The finger. - INTEGER L !The last. - L = AVAILS(0) !Pick on the last in the list. - IF (L .LE. 0) CALL CROAK("Run out of stashes!") !Hopefully not. - X = AVAILS(L) !Select some element or other. - AVAILS(L) = 0 !Might as well unfinger. - AVAILS(0) = L - 1 !As well as drop off the list. + SUBROUTINE PREPARESTASH !Since fancy usage is involved, fancy initialisation is needed. + INTEGER I !A stepper. + AVAILS(0) = MSTASH !All are available. + FORALL (I = 1:MSTASH) AVAILS(I) = MSTASH + 1 - I !Will be used stack style. + STASH.LDIGIT = -666 !This will cause trouble! + END SUBROUTINE PREPARESTASH !Simple enough. + SUBROUTINE GRABSTASH(X) !Finger an available STASH. + INTEGER X !The finger. + INTEGER L !The last. + L = AVAILS(0) !Pick on the last in the list. + IF (L .LE. 0) CALL CROAK("Run out of stashes!") !Hopefully not. + X = AVAILS(L) !Select some element or other. + AVAILS(L) = 0 !Might as well unfinger. + AVAILS(0) = L - 1 !As well as drop off the list. END SUBROUTINE GRABSTASH!Can't be bothered making this a function. Sudden death instead. - SUBROUTINE FREESTASH(X) !Unhand a STASH. - INTEGER X !The finger. - IF (X.EQ.0) RETURN !A non-finger. - IF (X.LT.0) CALL CROAK("Unhanding a non-stash!") !Paranoia. - IF (X.GT.MSTASH) CALL CROAK("Not a stash!") !I don't expect any of these. - IF (AVAILS(0).GE.MSTASH) CALL CROAK("Over subscribed!") !But on principle... - AVAILS(0) = AVAILS(0) + 1 !So, append to the list of available entries. - AVAILS(AVAILS(0)) = X !Thus. - X = 0 !The finger is amputated. - END SUBROUTINE FREESTASH !Last out, first in. Etc. + SUBROUTINE FREESTASH(X) !Unhand a STASH. + INTEGER X !The finger. + IF (X.EQ.0) RETURN !A non-finger. + IF (X.LT.0) CALL CROAK("Unhanding a non-stash!") !Paranoia. + IF (X.GT.MSTASH) CALL CROAK("Not a stash!") !I don't expect any of these. + IF (AVAILS(0).GE.MSTASH) CALL CROAK("Over subscribed!") !But on principle... + AVAILS(0) = AVAILS(0) + 1 !So, append to the list of available entries. + AVAILS(AVAILS(0)) = X !Thus. + X = 0 !The finger is amputated. + END SUBROUTINE FREESTASH !Last out, first in. Etc. SUBROUTINE BIGWRITE(T,N)!Reveal an annotated bignumber. - CHARACTER*(*) T !The text of its name. - TYPE(BIGINT) N !The value of its name. - WRITE (6,1) T,N.LDIGIT,N.DIGIT(N.LDIGIT:1:-1) !Roll! - 1 FORMAT (A,"(1:",I0,") = ",(300I1)) !This should do. - END SUBROUTINE BIGWRITE !Perhaps bigger than Integer*8. + CHARACTER*(*) T !The text of its name. + TYPE(BIGINT) N !The value of its name. + WRITE (6,1) T,N.LDIGIT,N.DIGIT(N.LDIGIT:1:-1) !Roll! + 1 FORMAT (A,"(1:",I0,") = ",(300I1)) !This should do. + END SUBROUTINE BIGWRITE !Perhaps bigger than Integer*8. - SUBROUTINE SHOWLIST(BLAH,LIST) !One can become confused. - INTEGER LIST(0:MSTASH) !Explicit bounds prevents confusion. - CHARACTER*(*) BLAH !An identifying message. - CHARACTER*4 ZOT !Scratchpad. - INTEGER I,IT !Stepper. -c REAL*8 V,P !For logarithmic output. -c INTEGER J !Another stepper needed. - WRITE (6,1) BLAH,LIST(0) !A heading. - 1 FORMAT ("The count for ",A," is ",I0) !Ah, layout. - DO I = 1,LIST(0) !Work through the list. - WRITE(ZOT,"('#',I3)") I !Prepare an annotation. - IT = LIST(I) !Finger the stash. - CALL BIGWRITE(ZOT,STASH(IT)) !Show. -c V = 0 !Convert the BIGINT to a floating-point number. -c P = 1 !Tracking the powers of BASE, presumed ten. -c PP:DO J = STASH(IT).LDIGIT,1,-1 !Start with the highest power. -c V = V + STASH(IT).DIGIT(J)/P !Deem it a units digit. -c P = P*10 !The next digit will have a lesser power. -c IF (P.GT.1000000) EXIT PP !This will do. -c END DO PP !On to the next digit. -c V = STASH(IT).LDIGIT - 1 + LOG10(V) !Convert. LOG10(196) = 2.29225607135648 -c WRITE (6,*) I,V !Reveal. - END DO !On to the next. - END SUBROUTINE SHOWLIST !Adrift in indirection. + SUBROUTINE SHOWLIST(BLAH,LIST) !One can become confused. + INTEGER LIST(0:MSTASH) !Explicit bounds prevents confusion. + CHARACTER*(*) BLAH !An identifying message. + CHARACTER*4 ZOT !Scratchpad. + INTEGER I,IT !Stepper. +c REAL*8 V,P !For logarithmic output. +c INTEGER J !Another stepper needed. + WRITE (6,1) BLAH,LIST(0) !A heading. + 1 FORMAT ("The count for ",A," is ",I0) !Ah, layout. + DO I = 1,LIST(0) !Work through the list. + WRITE(ZOT,"('#',I3)") I !Prepare an annotation. + IT = LIST(I) !Finger the stash. + CALL BIGWRITE(ZOT,STASH(IT)) !Show. +c V = 0 !Convert the BIGINT to a floating-point number. +c P = 1 !Tracking the powers of BASE, presumed ten. +c PP:DO J = STASH(IT).LDIGIT,1,-1 !Start with the highest power. +c V = V + STASH(IT).DIGIT(J)/P !Deem it a units digit. +c P = P*10 !The next digit will have a lesser power. +c IF (P.GT.1000000) EXIT PP !This will do. +c END DO PP !On to the next digit. +c V = STASH(IT).LDIGIT - 1 + LOG10(V) !Convert. LOG10(196) = 2.29225607135648 +c WRITE (6,*) I,V !Reveal. + END DO !On to the next. + END SUBROUTINE SHOWLIST !Adrift in indirection. - SUBROUTINE BIGLOAD(A,NUM) !Shatters a proper number into its digits. + SUBROUTINE BIGLOAD(A,NUM) !Shatters a proper number into its digits. Can't overflow, because the biggest normal integer has far fewer than LOTSADIGITS digits. - TYPE(BIGINT) A !The bignumber. - INTEGER NUM !The normal integer to put in it. - INTEGER L,N !Assistants. - N = NUM !A copy that I can damage. - A.DIGIT = 0 !Scrub, against a future carry.. - L = 0 !No digits so far. - DO WHILE(N .GT. 0) !Some number remaining? - L = L + 1 !Yes. Count another digit. - A.DIGIT(L) = MOD(N,BASE) !Place it. - N = N/BASE !Reduce the number. - END DO !And try again. - A.LDIGIT = MAX(1,L) !Zero will have one digit, a zero. - END SUBROUTINE BIGLOAD !A small service. + TYPE(BIGINT) A !The bignumber. + INTEGER NUM !The normal integer to put in it. + INTEGER L,N !Assistants. + N = NUM !A copy that I can damage. + A.DIGIT = 0 !Scrub, against a future carry.. + L = 0 !No digits so far. + DO WHILE(N .GT. 0) !Some number remaining? + L = L + 1 !Yes. Count another digit. + A.DIGIT(L) = MOD(N,BASE) !Place it. + N = N/BASE !Reduce the number. + END DO !And try again. + A.LDIGIT = MAX(1,L) !Zero will have one digit, a zero. + END SUBROUTINE BIGLOAD !A small service. Continue with routines for doing the work. - SUBROUTINE ADVANCE(A,B) !Advance A, giving B. + SUBROUTINE ADVANCE(A,B) !Advance A, giving B. C Experiment shows that for 196, log10(v) = 0·43328*step + 2·1616, or, each advance increases by a factor of ~2·7. - TYPE(BIGINT) A,B !To be twiddled. - INTEGER D !An assistant for carrying. - INTEGER I !A stepper. - B.LDIGIT = A.LDIGIT !Same size, so far. - FORALL(I = 1:A.LDIGIT) !Do these in any order, even in parallel! - 1 B.DIGIT(I) = A.DIGIT(I) !Add each digit - 2 + A.DIGIT(A.LDIGIT - I + 1) ! to its other-end partner. - B.DIGIT(B.LDIGIT + 1) = 0 !Perhaps another digit will be needed shortly. - DO I = 1,B.LDIGIT !Now slow down and taste the carry. - D = B.DIGIT(I) - BASE !Allowable digits are 0:BASE - 1. - IF (D.GE.0) THEN !So, has this digit overflowed? - B.DIGIT(I) = D !Yes. Only addition, so no div and mod stuff. - B.DIGIT(I + 1) = B.DIGIT(I + 1) + 1 !Carry one up, corresponding to subtracting one BASE down. - END IF !So much for that digit. - END DO !On to the next digit, of higher power. - IF (D.GE.0) THEN !A carry from the highest digit? - IF (B.LDIGIT .GE. LOTSADIGITS) CALL CROAK("Overflow!") !Oh dear. - B.LDIGIT = B.LDIGIT + 1 !NB! Always there is room left for ONE more digit. - LONGESTNUMBER = MAX(B.LDIGIT,LONGESTNUMBER) !Perhaps a surprise awaits. - END IF !Avoids overflow testing for every carry above. - END SUBROUTINE ADVANCE !That was fun! + TYPE(BIGINT) A,B !To be twiddled. + INTEGER D !An assistant for carrying. + INTEGER I !A stepper. + B.LDIGIT = A.LDIGIT !Same size, so far. + FORALL(I = 1:A.LDIGIT) !Do these in any order, even in parallel! + 1 B.DIGIT(I) = A.DIGIT(I) !Add each digit + 2 + A.DIGIT(A.LDIGIT - I + 1) ! to its other-end partner. + B.DIGIT(B.LDIGIT + 1) = 0 !Perhaps another digit will be needed shortly. + DO I = 1,B.LDIGIT !Now slow down and taste the carry. + D = B.DIGIT(I) - BASE !Allowable digits are 0:BASE - 1. + IF (D.GE.0) THEN !So, has this digit overflowed? + B.DIGIT(I) = D !Yes. Only addition, so no div and mod stuff. + B.DIGIT(I + 1) = B.DIGIT(I + 1) + 1 !Carry one up, corresponding to subtracting one BASE down. + END IF !So much for that digit. + END DO !On to the next digit, of higher power. + IF (D.GE.0) THEN !A carry from the highest digit? + IF (B.LDIGIT .GE. LOTSADIGITS) CALL CROAK("Overflow!") !Oh dear. + B.LDIGIT = B.LDIGIT + 1 !NB! Always there is room left for ONE more digit. + LONGESTNUMBER = MAX(B.LDIGIT,LONGESTNUMBER) !Perhaps a surprise awaits. + END IF !Avoids overflow testing for every carry above. + END SUBROUTINE ADVANCE !That was fun! - LOGICAL FUNCTION PALINDROME(N) !Perhaps a surprise property? + LOGICAL FUNCTION PALINDROME(N) !Perhaps a surprise property? Calls a one-digit number palindromic through the execution of vacuous logic. - TYPE(BIGINT) N !The big number to inspect. - PALINDROME = ALL(N.DIGIT(1:N.LDIGIT/2) !Compare each digit in the first half... - 1 .EQ.N.DIGIT(N.LDIGIT:N.LDIGIT/2 + 1:-1)) !To its opposite digit in the second. Whee! - END FUNCTION PALINDROME !If an odd number of digits, ignores the middle digit. + TYPE(BIGINT) N !The big number to inspect. + PALINDROME = ALL(N.DIGIT(1:N.LDIGIT/2) !Compare each digit in the first half... + 1 .EQ.N.DIGIT(N.LDIGIT:N.LDIGIT/2 + 1:-1)) !To its opposite digit in the second. Whee! + END FUNCTION PALINDROME !If an odd number of digits, ignores the middle digit. - INTEGER FUNCTION ORDER(A,B) !Does B follow A? - TYPE(BIGINT) A,B !The two numbers. - INTEGER I !A stepper. - IF (A.LDIGIT - B.LDIGIT) 1,10,2 !First, compare the lengths. - 1 ORDER = +1 !B has more digits. - RETURN !So, A must be smaller: in order. - 2 ORDER = -1 !A has more digits. - RETURN !So B must be smaller: reverse order. + INTEGER FUNCTION ORDER(A,B) !Does B follow A? + TYPE(BIGINT) A,B !The two numbers. + INTEGER I !A stepper. + IF (A.LDIGIT - B.LDIGIT) 1,10,2 !First, compare the lengths. + 1 ORDER = +1 !B has more digits. + RETURN !So, A must be smaller: in order. + 2 ORDER = -1 !A has more digits. + RETURN !So B must be smaller: reverse order. Compare the digits of the two numbers, known to be of equal length. - 10 DO 11 I = A.LDIGIT,1,-1 !The last digit has the highest power. - IF (A.DIGIT(I) - B.DIGIT(I)) 1,11,2 !Compare the digits. - 11 CONTINUE !If they match, continue with the next digit. - ORDER = 0 !If all match, A = B. - END FUNCTION ORDER !Ah, three-way tests... + 10 DO 11 I = A.LDIGIT,1,-1 !The last digit has the highest power. + IF (A.DIGIT(I) - B.DIGIT(I)) 1,11,2 !Compare the digits. + 11 CONTINUE !If they match, continue with the next digit. + ORDER = 0 !If all match, A = B. + END FUNCTION ORDER !Ah, three-way tests... - SUBROUTINE COMBSORT(XNDX) !Sort according to STASH(XNDX)) by reordering XNDX. + SUBROUTINE COMBSORT(XNDX) !Sort according to STASH(XNDX)) by reordering XNDX. Crank up a Comb sort of array STASH as indexed by XNDX. - INTEGER XNDX(0:),T !The index to be rearranged. - INTEGER I,H !Tools. H ought not be a small integer. - LOGICAL CURSE !Annoyance. - H = XNDX(0) - 1 !Last - First, and not +1. - IF (H.LE.0) GO TO 999 !Ha ha. - 1 H = MAX(1,H*10/13) !The special feature. - IF (H.EQ.9 .OR. H.EQ.10) H = 11 !A twiddle. - CURSE = .FALSE. !So far, so good. - DO I = XNDX(0) - H,1,-1 !If H = 1, this is a BubbleSort. - IF (ORDER(STASH(XNDX(I)),STASH(XNDX(I + H))) .LT. 0) THEN !One compare. - T=XNDX(I); XNDX(I)=XNDX(I+H); XNDX(I+H)=T !One swap. - CURSE = .TRUE. !One curse. - END IF !One test. - END DO !One loop. + INTEGER XNDX(0:),T !The index to be rearranged. + INTEGER I,H !Tools. H ought not be a small integer. + LOGICAL CURSE !Annoyance. + H = XNDX(0) - 1 !Last - First, and not +1. + IF (H.LE.0) GO TO 999 !Ha ha. + 1 H = MAX(1,H*10/13) !The special feature. + IF (H.EQ.9 .OR. H.EQ.10) H = 11 !A twiddle. + CURSE = .FALSE. !So far, so good. + DO I = XNDX(0) - H,1,-1 !If H = 1, this is a BubbleSort. + IF (ORDER(STASH(XNDX(I)),STASH(XNDX(I + H))) .LT. 0) THEN !One compare. + T=XNDX(I); XNDX(I)=XNDX(I+H); XNDX(I+H)=T !One swap. + CURSE = .TRUE. !One curse. + END IF !One test. + END DO !One loop. IF (CURSE .OR. H.GT.1) GO TO 1!Work remains? - 999 RETURN !If not, we're done. - END SUBROUTINE COMBSORT !Good performance, and simple. + 999 RETURN !If not, we're done. + END SUBROUTINE COMBSORT !Good performance, and simple. - SUBROUTINE INSERTIONSORT(XNDX) !Adjust XNDX according to STASH(XNDX) + SUBROUTINE INSERTIONSORT(XNDX) !Adjust XNDX according to STASH(XNDX) Crank up an Insertion sort of array STASH as indexed by XNDX. - INTEGER XNDX(0:),IT !The index to be prepared, and a safe place. - INTEGER I,L !Fingers. - DO L = 2,XNDX(0) !Step along the array. - IF (ORDER(STASH(XNDX(L - 1)),STASH(XNDX(L))) .LT. 0) THEN !Disorder? - I = L !Yes. Element L belongs earlier. - IT = XNDX(L) !Save it so that others can be shifted up one. - 1 XNDX(I) = XNDX(I - 1) !Shift one. - I = I - 1 !The next candidate back. - IF (I.GT.1 .AND. ORDER(STASH(XNDX(I - 1)), !Do I have to go further back? - 1 STASH(IT)).LT.0) GO TO 1 !Yes. - XNDX(I) = IT !Done. Place it in the space created. - END IF !So much for that comparison. - END DO !On to the next. - END SUBROUTINE INSERTIONSORT !Swift only if the array is nearly in order. + INTEGER XNDX(0:),IT !The index to be prepared, and a safe place. + INTEGER I,L !Fingers. + DO L = 2,XNDX(0) !Step along the array. + IF (ORDER(STASH(XNDX(L - 1)),STASH(XNDX(L))) .LT. 0) THEN !Disorder? + I = L !Yes. Element L belongs earlier. + IT = XNDX(L) !Save it so that others can be shifted up one. + 1 XNDX(I) = XNDX(I - 1) !Shift one. + I = I - 1 !The next candidate back. + IF (I.GT.1 .AND. ORDER(STASH(XNDX(I - 1)), !Do I have to go further back? + 1 STASH(IT)).LT.0) GO TO 1 !Yes. + XNDX(I) = IT !Done. Place it in the space created. + END IF !So much for that comparison. + END DO !On to the next. + END SUBROUTINE INSERTIONSORT !Swift only if the array is nearly in order. - INTEGER FUNCTION FOUNDIN(XNDX,X) !Search STASH(XNDX) for X. + INTEGER FUNCTION FOUNDIN(XNDX,X) !Search STASH(XNDX) for X. Crank up a binary serach. This uses EXCLUSIVE bounds. - INTEGER XNDX(0:) !The list of elements. - TYPE(BIGINT) X !The value to be sought. - INTEGER L,P,R !Fingers for the binary search. - L = 0 !Establish outer bounds. - R = XNDX(0) + 1 !One before, and one after, the first and last. - 1 P = (R - L)/2 !Probe point offset. Beware integer overflow with (L + R)/2. - IF (P.LE.0) THEN !Is the search span exhausted? - FOUNDIN = -L !Alas. X should follow position L but doesn't. - RETURN !Nothing more to search. - END IF !Otherwise, STASH(XNDX(L + 1)) <= X <= STASH(XNDX(R - 1)) - P = L + P !Convert from offset to probe point. - IF (ORDER(X,STASH(XNDX(P)))) 2,4,3 !Compare X to the probe point's value. - 2 L = P !STASH(XNDX(P)) < X: advance L to P. - GO TO 1 !Try again. - 3 R = P !X < STASH(XNDX(P)): retract R to P. - GO TO 1 !Try again. + INTEGER XNDX(0:) !The list of elements. + TYPE(BIGINT) X !The value to be sought. + INTEGER L,P,R !Fingers for the binary search. + L = 0 !Establish outer bounds. + R = XNDX(0) + 1 !One before, and one after, the first and last. + 1 P = (R - L)/2 !Probe point offset. Beware integer overflow with (L + R)/2. + IF (P.LE.0) THEN !Is the search span exhausted? + FOUNDIN = -L !Alas. X should follow position L but doesn't. + RETURN !Nothing more to search. + END IF !Otherwise, STASH(XNDX(L + 1)) <= X <= STASH(XNDX(R - 1)) + P = L + P !Convert from offset to probe point. + IF (ORDER(X,STASH(XNDX(P)))) 2,4,3 !Compare X to the probe point's value. + 2 L = P !STASH(XNDX(P)) < X: advance L to P. + GO TO 1 !Try again. + 3 R = P !X < STASH(XNDX(P)): retract R to P. + GO TO 1 !Try again. Caught it! X = STASH(XNDX(P)) - the result indexes XNDX, not STASH. - 4 FOUNDIN = P !So, X is found, here! *Not* at P, but at XNDX(P). - END FUNCTION FOUNDIN !Hopefully, without array copy-in, copy-out. + 4 FOUNDIN = P !So, X is found, here! *Not* at P, but at XNDX(P). + END FUNCTION FOUNDIN !Hopefully, without array copy-in, copy-out. - SUBROUTINE INSPECT(S1,S2,ENUFF) !Follow the Lychrel protocol. + SUBROUTINE INSPECT(S1,S2,ENUFF) !Follow the Lychrel protocol. Careful! A march is stopped on encountering a palindrome, BUT, the starting value is not itself checked. - INTEGER S1,S2 !Start and stop values. - INTEGER ENUFF !An infinite trail can't be followed. - INTEGER STEP,SEED !Counts the advances along the long march. - INTEGER START !The first value of a march has special treatment. - INTEGER MARCH(0:ENUFF) !The waypoints of a long march. - INTEGER DEJAVU !Some may prove to be junctions. - INTEGER LP,NP,LL,NL !Counters for various odd outcomes. - NP = 0 !No palindromic stops. - LP = 0 !Nor any that head for one. - NL = 0 !No neverending sequences seen. - LL = 0 !Nor any that head for one. - WRITE (6,10) S1,S2,ENUFF !Announce the plan. + INTEGER S1,S2 !Start and stop values. + INTEGER ENUFF !An infinite trail can't be followed. + INTEGER STEP,SEED !Counts the advances along the long march. + INTEGER START !The first value of a march has special treatment. + INTEGER MARCH(0:ENUFF) !The waypoints of a long march. + INTEGER DEJAVU !Some may prove to be junctions. + INTEGER LP,NP,LL,NL !Counters for various odd outcomes. + NP = 0 !No palindromic stops. + LP = 0 !Nor any that head for one. + NL = 0 !No neverending sequences seen. + LL = 0 !Nor any that head for one. + WRITE (6,10) S1,S2,ENUFF !Announce the plan. 10 FORMAT ("Starting values ",I0," to ",I0,"; step limit ",I0) C For each try, steps (but not the START) are saved in MARCH, and those steps end up in one list or another. C Thus, there is no removal of their entries from the working STASH. If a plaindrome is found, or a step's value is @@ -226,70 +226,70 @@ c But if instead the MARCH is to be added to the LYCHREL list, the last value is c Since tries are made in increasing order, and ADVANCE always produces a bigger number, there is no point c in saving the START value in STASH, except, some START values turn out to be notable and being saved in L0P c or LLIST, their entry in STASH must not be rugpulled, thus the START = 0 to note this and prevent FREESTASH. - TRY:DO SEED = S1,S2 !Here we go. - CALL GRABSTASH(START) !Ask for a starting space. - CALL BIGLOAD(STASH(START),SEED) !The starting value. -c CALL BIGWRITE("N0",STASH(START)) !Show it. -c IF (FOUNDIN(LYCHREL,STASH(START)) .GT. 0) THEN! Have we been here during a long march? -c WRITE (6,*) SEED,"Falls in!" !Yes! -c CYCLE TRY !Nothing will be learnt by continuing. -c END IF !Otherwise, we're not discouraged. - STEP = 1 !Even the longest journey stars with its first step. - MARCH(0) = STEP !And I'm remembering every step. - CALL GRABSTASH(MARCH(STEP)) !A place for my first footfall. - CALL ADVANCE(STASH(START),STASH(MARCH(STEP))) !Start the stomping. + TRY:DO SEED = S1,S2 !Here we go. + CALL GRABSTASH(START) !Ask for a starting space. + CALL BIGLOAD(STASH(START),SEED) !The starting value. +c CALL BIGWRITE("N0",STASH(START)) !Show it. +c IF (FOUNDIN(LYCHREL,STASH(START)) .GT. 0) THEN! Have we been here during a long march? +c WRITE (6,*) SEED,"Falls in!" !Yes! +c CYCLE TRY !Nothing will be learnt by continuing. +c END IF !Otherwise, we're not discouraged. + STEP = 1 !Even the longest journey stars with its first step. + MARCH(0) = STEP !And I'm remembering every step. + CALL GRABSTASH(MARCH(STEP)) !A place for my first footfall. + CALL ADVANCE(STASH(START),STASH(MARCH(STEP))) !Start the stomping. Contemplate the current step. - 100 CONTINUE !Can't label a blank line... -c CALL BIGWRITE("N1",STASH(MARCH(STEP))) !Progress may be of interest. - DEJAVU = FOUNDIN(PLIST,STASH(MARCH(STEP))) !A value known to later become a palindrome? - IF (DEJAVU .GT. 0) THEN !It being amongst those stashed for that cause. + 100 CONTINUE !Can't label a blank line... +c CALL BIGWRITE("N1",STASH(MARCH(STEP))) !Progress may be of interest. + DEJAVU = FOUNDIN(PLIST,STASH(MARCH(STEP))) !A value known to later become a palindrome? + IF (DEJAVU .GT. 0) THEN !It being amongst those stashed for that cause. c WRITE (6,*) SEED,STEP,"Deja vu! List#",DEJAVU - LP = LP + 1 !Count a late starter. - CALL FREESTASH(MARCH(STEP)) !The last step is already known. - CALL SLURP(PLIST) !Add the MARCH to the palindrome starters. - GO TO 110 !And we're finished with this try. - END IF !So much for prospective palindromes. - IF (PALINDROME(STASH(MARCH(STEP)))) THEN !Attained an actual palindrome? -c WRITE (6,*) SEED,STEP,"Palindrome!" !Yes! - NP = NP + 1 !Count a proper palendrome. - CALL FREESTASH(MARCH(STEP)) !The last step is a palindrome. - CALL SLURP(PLIST) !So remember only those non-palindromes before it. - GO TO 110 !This is a pretext for ending. - END IF !Since one could advance past a palindrome, and then find another. - DEJAVU = FOUNDIN(LYCHREL,STASH(MARCH(STEP))) !A value known to later pass ENUFF? - IF (DEJAVU .GT. 0) THEN !If so, there is no need to follow that march again. -c WRITE (6,*) SEED,STEP,"Latecomer! List#",DEJAVU !So this starter has been preempted. -c CALL BIGWRITE("Latecomer!",STASH(LYCHREL(DEJAVU))) !Or, STASH(MARCH(STEP)), they being equal. - LLIST(0) = LLIST(0) + 1 !Count another latecomer. - LLIST(LLIST(0)) = START !This was its starting value's finger. - IF (PALINDROME(STASH(START))) THEN !Perhaps its starting value was also already a palindrome? - L0P(0) = L0P(0) + 1 !Yes! Count another such. - L0P(L0P(0)) = START !Using a finger, rather than copying a BIGINT. - END IF !A Lychrel number whose zeroth step is palindromic. - START = 0 !This is not to be unfingered! - LL = LL + 1 !Anyway, this path has joined a known long march. - CALL FREESTASH(MARCH(STEP)) !This value is already fingered in a list. - CALL SLURP(LYCHREL) !So, all its steps do so also, including the last. - GO TO 110 !Even though its later start might find a palindrome within ENUFF steps. - END IF !So much for discoveries at each step. - IF (STEP.LT.ENUFF) THEN !Are we there yet? - STEP = STEP + 1 !It seems there is no reason to stop. - MARCH(0) = STEP !So, the long march extends. - CALL GRABSTASH(MARCH(STEP)) !Another step. - CALL ADVANCE(STASH(MARCH(STEP - 1)),STASH(MARCH(STEP))) !Lurch forwards. - GO TO 100 !And see what happens here. - END IF !The end of the loop. + LP = LP + 1 !Count a late starter. + CALL FREESTASH(MARCH(STEP)) !The last step is already known. + CALL SLURP(PLIST) !Add the MARCH to the palindrome starters. + GO TO 110 !And we're finished with this try. + END IF !So much for prospective palindromes. + IF (PALINDROME(STASH(MARCH(STEP)))) THEN !Attained an actual palindrome? +c WRITE (6,*) SEED,STEP,"Palindrome!" !Yes! + NP = NP + 1 !Count a proper palendrome. + CALL FREESTASH(MARCH(STEP)) !The last step is a palindrome. + CALL SLURP(PLIST) !So remember only those non-palindromes before it. + GO TO 110 !This is a pretext for ending. + END IF !Since one could advance past a palindrome, and then find another. + DEJAVU = FOUNDIN(LYCHREL,STASH(MARCH(STEP))) !A value known to later pass ENUFF? + IF (DEJAVU .GT. 0) THEN !If so, there is no need to follow that march again. +c WRITE (6,*) SEED,STEP,"Latecomer! List#",DEJAVU !So this starter has been preempted. +c CALL BIGWRITE("Latecomer!",STASH(LYCHREL(DEJAVU))) !Or, STASH(MARCH(STEP)), they being equal. + LLIST(0) = LLIST(0) + 1 !Count another latecomer. + LLIST(LLIST(0)) = START !This was its starting value's finger. + IF (PALINDROME(STASH(START))) THEN !Perhaps its starting value was also already a palindrome? + L0P(0) = L0P(0) + 1 !Yes! Count another such. + L0P(L0P(0)) = START !Using a finger, rather than copying a BIGINT. + END IF !A Lychrel number whose zeroth step is palindromic. + START = 0 !This is not to be unfingered! + LL = LL + 1 !Anyway, this path has joined a known long march. + CALL FREESTASH(MARCH(STEP)) !This value is already fingered in a list. + CALL SLURP(LYCHREL) !So, all its steps do so also, including the last. + GO TO 110 !Even though its later start might find a palindrome within ENUFF steps. + END IF !So much for discoveries at each step. + IF (STEP.LT.ENUFF) THEN !Are we there yet? + STEP = STEP + 1 !It seems there is no reason to stop. + MARCH(0) = STEP !So, the long march extends. + CALL GRABSTASH(MARCH(STEP)) !Another step. + CALL ADVANCE(STASH(MARCH(STEP - 1)),STASH(MARCH(STEP))) !Lurch forwards. + GO TO 100 !And see what happens here. + END IF !The end of the loop. Chase completed, having reached STEP = ENUFF with no decision. - WRITE (6,*) SEED,"retains Lychrel potential." !Since a palindrome has not been reached. - IF (PALINDROME(STASH(START))) THEN !Perhaps it started as a palindrome? - L0P(0) = L0P(0) + 1 !It did! - L0P(L0P(0)) = START !So remember it. - START = 0 !And don't unhand this entry, a finger to it being saved. - END IF !Enough shades of classification. - NL = NL + 1 !Count another at the end of a long march. - CALL SLURP(LYCHREL) !And save the lot, including the final value. - 110 IF (START.GT.0) CALL FREESTASH(START) !The starting value was not held as a part of the MARCH. - END DO TRY !Start another. + WRITE (6,*) SEED,"retains Lychrel potential." !Since a palindrome has not been reached. + IF (PALINDROME(STASH(START))) THEN !Perhaps it started as a palindrome? + L0P(0) = L0P(0) + 1 !It did! + L0P(L0P(0)) = START !So remember it. + START = 0 !And don't unhand this entry, a finger to it being saved. + END IF !Enough shades of classification. + NL = NL + 1 !Count another at the end of a long march. + CALL SLURP(LYCHREL) !And save the lot, including the final value. + 110 IF (START.GT.0) CALL FREESTASH(START) !The starting value was not held as a part of the MARCH. + END DO TRY !Start another. Cast forth a summary. WRITE (6,*) WRITE (6,11) NL,ENUFF,LL,LYCHREL(0) @@ -302,8 +302,8 @@ c CALL SHOWLIST("starters that joined a Long March",LLIST) 12 FORMAT (I8," starters ended as a palindrome, ", 1 I0," joined a route leading to a palindrome. ", 2 I0," waypoints stashed.") - CONTAINS !An assistant. - SUBROUTINE SLURP(LIST) !Adds the elements in MARCH to LIST. + CONTAINS !An assistant. + SUBROUTINE SLURP(LIST) !Adds the elements in MARCH to LIST. C Entries in LIST are such that STASH(LIST(~)) is ordered. Because I arrange this. C Entries MARCH are also in increasing order as they are successive values from ADVANCE. C Accordingly, if only a few entries are to be added, a binary search can be used to find the @@ -322,69 +322,69 @@ c old one retained. C For instance, 5 -> 10 -> 11 so fingers for 5 and 10 are added to PLIST. C Later on, 10 -> 11 and a finger for 10 is to be added to PLIST, because the starting value is not checked. C However, a later version refrains from adding the (unchecked) starting value, and then, no worries. - INTEGER LIST(0:MSTASH) !Some string of numbers. - INTEGER MIST(0:MSTASH) !LIST(0) is the upper bound, but risks stack overflow. - INTEGER I,S,L !A stepper. + INTEGER LIST(0:MSTASH) !Some string of numbers. + INTEGER MIST(0:MSTASH) !LIST(0) is the upper bound, but risks stack overflow. + INTEGER I,S,L !A stepper. Check for annoying nullities. - 1 IF (MARCH(0).LE.0) RETURN !An empty march already! - IF (MARCH(MARCH(0)).LE.0) THEN !Otherwise, look at the last step. - MARCH(0) = MARCH(0) - 1 !It was boring. - GO TO 1 !So, go back one and look afresh. - END IF !Having snipped off trailing nullities, what remains means effort. + 1 IF (MARCH(0).LE.0) RETURN !An empty march already! + IF (MARCH(MARCH(0)).LE.0) THEN !Otherwise, look at the last step. + MARCH(0) = MARCH(0) - 1 !It was boring. + GO TO 1 !So, go back one and look afresh. + END IF !Having snipped off trailing nullities, what remains means effort. Can't escape some work. - IF (MARCH(0) .LE. 6) THEN !If we have a few only, - DO I = 1,MARCH(0) !Work through them one by one, - S = MARCH(I) !The finger for this step of the march. - IF (S.LE.0) CYCLE !A stump? - L = FOUNDIN(LIST,STASH(S)) !Using a binary search to find the proper place. - IF (L.GT.0) THEN !If already present, - CALL FREESTASH(S) !Its entry is no longer needed. - CYCLE !So skip this. - END IF !But if not found, a place must be made. - L = 1 - L !Finger where the missing element should be. - LIST(LIST(0) + 1:L + 1:-1) = LIST(LIST(0):L:-1) !Shift followers up to make space. - LIST(0) = LIST(0) + 1 !Count another. - LIST(L) = S !Place it. - END DO !On to the next. - ELSE !But if there are many to add, merge the two lists... Both are ordered. - MIST(0:LIST(0)) = LIST(0:LIST(0)) !Copy the source list. - LIST(0) = 0 !It is to be reformed by the merge. - L = 1 !Start with the first in MIST. - DO I = 1,MARCH(0) !And work along the long MARCH. - S = MARCH(I) !So, a step from the long march. - IF (S.LE.0) CYCLE !And if not an empty step, we have one. - 11 LIST(0) = LIST(0) + 1 !Count in another for this list. - IF (L.LE.MIST(0)) THEN !Still have suppliers from what had been LIST? - IF (ORDER(STASH(MIST(L)),STASH(S))) 14,13,12 !Yes, Which is to be selected? - 12 LIST(LIST(0)) = MIST(L) !STASH(MIST(L)) precedes STASH(S), so take it. - L = L + 1 !Advance to the next MIST entry. - GO TO 11 !And look again. - 13 CALL FREESTASH(S) !Equal. Discard the new entry. - S = MIST(L) !And pefer the established entry. - L = L + 1 !Advance past the MIST(L) entry. - END IF !Thus, MIST entries have been rolled until a MARCH entry was due. - 14 LIST(LIST(0)) = S !Save the finger - which may have come from MIST... - END DO !On to the next MARCH. - S = MIST(0) - L + 1 !The number of MIST entries still waiting. - IF (S .GT. 0) THEN !Are there any? - LIST(LIST(0) + 1:LIST(0) + S) = MIST(L:MIST(0)) !Yes. Append them. - LIST(0) = LIST(0) + S !And count them in. - END IF !So much for the merge. - END IF !Otherwise, a COMBSORT would do. - END SUBROUTINE SLURP !Can't overflow, because each LIST has room for MSTASH entries. - END SUBROUTINE INSPECT !That was fun. - END MODULE LYCHREL SEARCH !Enough of that. + IF (MARCH(0) .LE. 6) THEN !If we have a few only, + DO I = 1,MARCH(0) !Work through them one by one, + S = MARCH(I) !The finger for this step of the march. + IF (S.LE.0) CYCLE !A stump? + L = FOUNDIN(LIST,STASH(S)) !Using a binary search to find the proper place. + IF (L.GT.0) THEN !If already present, + CALL FREESTASH(S) !Its entry is no longer needed. + CYCLE !So skip this. + END IF !But if not found, a place must be made. + L = 1 - L !Finger where the missing element should be. + LIST(LIST(0) + 1:L + 1:-1) = LIST(LIST(0):L:-1) !Shift followers up to make space. + LIST(0) = LIST(0) + 1 !Count another. + LIST(L) = S !Place it. + END DO !On to the next. + ELSE !But if there are many to add, merge the two lists... Both are ordered. + MIST(0:LIST(0)) = LIST(0:LIST(0)) !Copy the source list. + LIST(0) = 0 !It is to be reformed by the merge. + L = 1 !Start with the first in MIST. + DO I = 1,MARCH(0) !And work along the long MARCH. + S = MARCH(I) !So, a step from the long march. + IF (S.LE.0) CYCLE !And if not an empty step, we have one. + 11 LIST(0) = LIST(0) + 1 !Count in another for this list. + IF (L.LE.MIST(0)) THEN !Still have suppliers from what had been LIST? + IF (ORDER(STASH(MIST(L)),STASH(S))) 14,13,12 !Yes, Which is to be selected? + 12 LIST(LIST(0)) = MIST(L) !STASH(MIST(L)) precedes STASH(S), so take it. + L = L + 1 !Advance to the next MIST entry. + GO TO 11 !And look again. + 13 CALL FREESTASH(S) !Equal. Discard the new entry. + S = MIST(L) !And pefer the established entry. + L = L + 1 !Advance past the MIST(L) entry. + END IF !Thus, MIST entries have been rolled until a MARCH entry was due. + 14 LIST(LIST(0)) = S !Save the finger - which may have come from MIST... + END DO !On to the next MARCH. + S = MIST(0) - L + 1 !The number of MIST entries still waiting. + IF (S .GT. 0) THEN !Are there any? + LIST(LIST(0) + 1:LIST(0) + S) = MIST(L:MIST(0)) !Yes. Append them. + LIST(0) = LIST(0) + S !And count them in. + END IF !So much for the merge. + END IF !Otherwise, a COMBSORT would do. + END SUBROUTINE SLURP !Can't overflow, because each LIST has room for MSTASH entries. + END SUBROUTINE INSPECT !That was fun. + END MODULE LYCHREL SEARCH !Enough of that. PROGRAM TEST USE LYCHREL SEARCH CALL PREPARESTASH Clear my lists. - LYCHREL = 0 !No Lychrel candidates. - LLIST = 0 !No latecomers to a Lychrel candidacy sequence. - PLIST = 0 !No numbers leading to a palindrome. - L0P = 0 !No Lychrel/latecomers starting as a palindrome. + LYCHREL = 0 !No Lychrel candidates. + LLIST = 0 !No latecomers to a Lychrel candidacy sequence. + PLIST = 0 !No numbers leading to a palindrome. + L0P = 0 !No Lychrel/latecomers starting as a palindrome. - CALL INSPECT(1,10000,500) !Whee! + CALL INSPECT(1,10000,500) !Whee! WRITE (6,*) "Longest digit string =",LONGESTNUMBER WRITE (6,*) "Unused STASH entries =",AVAILS(0) diff --git a/Task/Lychrel-numbers/Go/lychrel-numbers.go b/Task/Lychrel-numbers/Go/lychrel-numbers.go index 043326c470..02bcdc2ead 100644 --- a/Task/Lychrel-numbers/Go/lychrel-numbers.go +++ b/Task/Lychrel-numbers/Go/lychrel-numbers.go @@ -1,11 +1,11 @@ package main import ( - "flag" - "fmt" - "math" - "math/big" - "os" + "flag" + "fmt" + "math" + "math/big" + "os" ) var maxRev = big.NewInt(math.MaxUint64 / 10) // approximate @@ -15,117 +15,117 @@ var ten = big.NewInt(10) // reverse order and returns `result`. // Only handles positive integers. func reverseInt(v *big.Int, result *big.Int) *big.Int { - if v.Cmp(maxRev) <= 0 { - // optimize small values that fit within uint64 - result.SetUint64(reverseUint64(v.Uint64())) - } else { - if true { - // Reverse the string representation - s := reverseString(v.String()) - result.SetString(s, 10) - } else { - // This has fewer allocations but is slower: - // Use a copy of `v` since we mutate it. - v := new(big.Int).Set(v) - digit := new(big.Int) - result.SetUint64(0) - for v.BitLen() > 0 { - v.QuoRem(v, ten, digit) - result.Mul(result, ten) - result.Add(result, digit) - } - } - } - return result + if v.Cmp(maxRev) <= 0 { + // optimize small values that fit within uint64 + result.SetUint64(reverseUint64(v.Uint64())) + } else { + if true { + // Reverse the string representation + s := reverseString(v.String()) + result.SetString(s, 10) + } else { + // This has fewer allocations but is slower: + // Use a copy of `v` since we mutate it. + v := new(big.Int).Set(v) + digit := new(big.Int) + result.SetUint64(0) + for v.BitLen() > 0 { + v.QuoRem(v, ten, digit) + result.Mul(result, ten) + result.Add(result, digit) + } + } + } + return result } func reverseUint64(v uint64) uint64 { - var r uint64 - for v > 0 { - r *= 10 - r += v % 10 - v /= 10 - } - return r + var r uint64 + for v > 0 { + r *= 10 + r += v % 10 + v /= 10 + } + return r } func reverseString(s string) string { - b := make([]byte, len(s)) - for i, j := 0, len(s)-1; j >= 0; i, j = i+1, j-1 { - b[i] = s[j] - } - return string(b) + b := make([]byte, len(s)) + for i, j := 0, len(s)-1; j >= 0; i, j = i+1, j-1 { + b[i] = s[j] + } + return string(b) } var known = make(map[string]bool) func Lychrel(n uint64, iter uint) (isLychrel, isSeed bool) { - v, r := new(big.Int).SetUint64(n), new(big.Int) - reverseInt(v, r) - seen := make(map[string]bool) - isLychrel = true - isSeed = true - for i := iter; i > 0; i-- { - str := v.String() - if seen[str] { - //log.Println("found a loop with", n, "at", str) - isLychrel = true - break - } - if ans, ok := known[str]; ok { - //log.Println("already know:", str, ans) - isLychrel = ans - isSeed = false - break - } - seen[str] = true + v, r := new(big.Int).SetUint64(n), new(big.Int) + reverseInt(v, r) + seen := make(map[string]bool) + isLychrel = true + isSeed = true + for i := iter; i > 0; i-- { + str := v.String() + if seen[str] { + //log.Println("found a loop with", n, "at", str) + isLychrel = true + break + } + if ans, ok := known[str]; ok { + //log.Println("already know:", str, ans) + isLychrel = ans + isSeed = false + break + } + seen[str] = true - v = v.Add(v, r) - //log.Printf("%v + %v = %v\n", str, r, v) - reverseInt(v, r) - if v.Cmp(r) == 0 { - //log.Println(v, "is a palindrome,", n, "is not a Lychrel number") - isLychrel = false - isSeed = false - break - } - } - for k := range seen { - known[k] = isLychrel - } - //if isLychrel { log.Printf("%v may be a Lychrel number\n", n) } - return isLychrel, isSeed + v = v.Add(v, r) + //log.Printf("%v + %v = %v\n", str, r, v) + reverseInt(v, r) + if v.Cmp(r) == 0 { + //log.Println(v, "is a palindrome,", n, "is not a Lychrel number") + isLychrel = false + isSeed = false + break + } + } + for k := range seen { + known[k] = isLychrel + } + //if isLychrel { log.Printf("%v may be a Lychrel number\n", n) } + return isLychrel, isSeed } func main() { - max := flag.Uint64("max", 10000, "search in the range 1..`N` inclusive") - iter := flag.Uint("iter", 500, "limit palindrome search to `N` iterations") - flag.Parse() - if flag.NArg() != 0 { - flag.Usage() - os.Exit(2) - } + max := flag.Uint64("max", 10000, "search in the range 1..`N` inclusive") + iter := flag.Uint("iter", 500, "limit palindrome search to `N` iterations") + flag.Parse() + if flag.NArg() != 0 { + flag.Usage() + os.Exit(2) + } - fmt.Printf("Calculating using n = 1..%v and %v iterations:\n", *max, *iter) - var seeds []uint64 - var related int - var pals []uint64 - for i := uint64(1); i <= *max; i++ { - if l, s := Lychrel(i, *iter); l { - if s { - seeds = append(seeds, i) - } else { - related++ - } - if i == reverseUint64(i) { - pals = append(pals, i) - } - } - } + fmt.Printf("Calculating using n = 1..%v and %v iterations:\n", *max, *iter) + var seeds []uint64 + var related int + var pals []uint64 + for i := uint64(1); i <= *max; i++ { + if l, s := Lychrel(i, *iter); l { + if s { + seeds = append(seeds, i) + } else { + related++ + } + if i == reverseUint64(i) { + pals = append(pals, i) + } + } + } - fmt.Println(" Number of Lychrel seeds:", len(seeds)) - fmt.Println(" Lychrel seeds:", seeds) - fmt.Println(" Number of related:", related) - fmt.Println("Number of Lychrel palindromes:", len(pals)) - fmt.Println(" Lychrel palindromes:", pals) + fmt.Println(" Number of Lychrel seeds:", len(seeds)) + fmt.Println(" Lychrel seeds:", seeds) + fmt.Println(" Number of related:", related) + fmt.Println("Number of Lychrel palindromes:", len(pals)) + fmt.Println(" Lychrel palindromes:", pals) } diff --git a/Task/Lychrel-numbers/Icon/lychrel-numbers.icon b/Task/Lychrel-numbers/Icon/lychrel-numbers.icon new file mode 100644 index 0000000000..6f42d53be4 --- /dev/null +++ b/Task/Lychrel-numbers/Icon/lychrel-numbers.icon @@ -0,0 +1,25 @@ +global seeds, related, palins + +procedure main(A) + limit := \A[1] | 10000 + palins := [] + seeds := [] + related := 0 + every n := islychrel(seq()\limit) do put(palins, reverse(n) == n) + every writes("Seed Lychrels:" | (" "||(!seeds)) | "\n") + write("There are ",related," related Lychrels.") + every writes("Palindromic Lychrels:" | (" "||!palins) | "\n") +end + +procedure islychrel(n,limit:500) + static seen + initial seen := set() + on := n + every |((n +:= reverse(n)) ~== reverse(n))\limit do + if (/r,member(seen,n)) then r := "yes" + else insert(seen, n) + if n ~== reverse(n) then { + if \r then related +:= 1 else put(seeds,on) + return on + } +end diff --git a/Task/Lychrel-numbers/JavaScript/lychrel-numbers.js b/Task/Lychrel-numbers/JavaScript/lychrel-numbers.js new file mode 100644 index 0000000000..64c05a5cbd --- /dev/null +++ b/Task/Lychrel-numbers/JavaScript/lychrel-numbers.js @@ -0,0 +1,52 @@ + const bigInt = require('big-integer'); + const cache = new Map(); + function rev(bi) { + const s = bi.toString().split('').reverse().join(''); + return bigInt(s); + } + function lychrel(n) { + if (cache.has(n.toString())) { // bigInt 是对象,需要用字符串作为 Map 的键 + return cache.get(n.toString()); + } + let r = rev(n); + let res = { flag: true, bi: n }; + const seen = []; + for (let i = 0; i < 500; i++) { + n = n.add(r); + r = rev(n); + if (n.equals(r)) { + res = { flag: false, bi: bigInt(0) }; + break; + } + if (cache.has(n.toString())) { + res = cache.get(n.toString()); + break; + } + seen.push(n); + } + for (const bi of seen) { + cache.set(bi.toString(), res); + } + return res; + } + const seeds = []; + const related = []; + const palin = []; + for (let i = 1; i <= 10000; i++) { + const n = bigInt(i); + const t = lychrel(n); + if (!t.flag) { + continue; + } + if (n.equals(t.bi)) { + seeds.push(t.bi); + } else { + related.push(t.bi); + } + if (n.equals(t.bi)) { + palin.push(t.bi); + } + } + console.log(`${seeds.length} Lychrel seeds: [${seeds.map(s => s.toString()).join(', ')}]`); + console.log(`${related.length} Lychrel related`); + console.log(`${palin.length} Lychrel palindromes: [${palin.map(p => p.toString()).join(', ')}]`); diff --git a/Task/Lychrel-numbers/Jq/lychrel-numbers-1.jq b/Task/Lychrel-numbers/Jq/lychrel-numbers-1.jq index 4f760b5617..5eb527e8bc 100644 --- a/Task/Lychrel-numbers/Jq/lychrel-numbers-1.jq +++ b/Task/Lychrel-numbers/Jq/lychrel-numbers-1.jq @@ -36,7 +36,7 @@ def next_palindromes(limit): | .[1] as $n | if $limit <= 0 then empty else myadd($n ; $n|reverse) as $sum - | ($sum, + | ($sum, if ($sum | is_palindrome) then true else [$limit - 1, $sum] | next end) end; [limit, toa] | next | if type == "boolean" then . else tos end; @@ -49,12 +49,12 @@ def next_palindromes(limit): def lychrel_dictionary(n; maxiter): reduce range(0; n) as $i ({}; ($i | tostring) as $is - | if .[$is] then .related += [$i] - else [$is | next_palindromes(maxiter)] as $seq - | . as $dict + | if .[$is] then .related += [$i] + else [$is | next_palindromes(maxiter)] as $seq + | . as $dict # | ([$i, $seq] | debug) as $debug | if $seq[-1] == true then . - else if ($is | explode | is_palindrome) then .palindromic_seed += [$i] else . end + else if ($is | explode | is_palindrome) then .palindromic_seed += [$i] else . end | if any($seq[]; $dict[.]) then .related += [$i] else .seed += [$i] end diff --git a/Task/Lychrel-numbers/Julia/lychrel-numbers.julia b/Task/Lychrel-numbers/Julia/lychrel-numbers.jl similarity index 100% rename from Task/Lychrel-numbers/Julia/lychrel-numbers.julia rename to Task/Lychrel-numbers/Julia/lychrel-numbers.jl diff --git a/Task/Lychrel-numbers/Kotlin/lychrel-numbers.kotlin b/Task/Lychrel-numbers/Kotlin/lychrel-numbers.kts similarity index 100% rename from Task/Lychrel-numbers/Kotlin/lychrel-numbers.kotlin rename to Task/Lychrel-numbers/Kotlin/lychrel-numbers.kts diff --git a/Task/Lychrel-numbers/PascalABC.NET/lychrel-numbers.pas b/Task/Lychrel-numbers/PascalABC.NET/lychrel-numbers.pas new file mode 100644 index 0000000000..dfacb06e29 --- /dev/null +++ b/Task/Lychrel-numbers/PascalABC.NET/lychrel-numbers.pas @@ -0,0 +1,55 @@ +const + iterations = 1000; + limit = 10_000; + +var + cache := new Dictionary; + +function rev(n: biginteger) := n.ToString[::-1].ToBigInteger; + +function lychrel(n: biginteger): (boolean, biginteger); +begin + if n in cache then result := cache[n] + else begin + var r := rev(n); + var res := (True, n); + var seen := new List; + loop iterations do + begin + n += r; + r := rev(n); + if n = r then + begin + res := (False, 0bi); + break + end; + if n in cache then + begin + res := cache[n]; + break + end; + seen.Add(n) + end; + + foreach var x in seen do cache[x] := res; + result := res; + end; +end; + +begin + var seeds := new List; + var related := new List; + var palin := new List; + + foreach var i in (1..limit) do + begin + var (tf, s) := lychrel(i); + if not tf then continue; + if i = s then seeds.Add(i) else related.Add(i); + if i = rev(i) then palin.Add(i); + end; + + println('There are', seeds.count, 'Lychrel seeds, namely:', seeds); + println('Lychrel related numbers:', related.count); + println('There are', palin.count, 'Lychrel palindromes, namely:', palin); +end. diff --git a/Task/Lychrel-numbers/PowerShell/lychrel-numbers-1.psh b/Task/Lychrel-numbers/PowerShell/lychrel-numbers-1.ps1 similarity index 100% rename from Task/Lychrel-numbers/PowerShell/lychrel-numbers-1.psh rename to Task/Lychrel-numbers/PowerShell/lychrel-numbers-1.ps1 diff --git a/Task/Lychrel-numbers/PowerShell/lychrel-numbers-2.psh b/Task/Lychrel-numbers/PowerShell/lychrel-numbers-2.ps1 similarity index 100% rename from Task/Lychrel-numbers/PowerShell/lychrel-numbers-2.psh rename to Task/Lychrel-numbers/PowerShell/lychrel-numbers-2.ps1 diff --git a/Task/Lychrel-numbers/Rebol/lychrel-numbers.rebol b/Task/Lychrel-numbers/Rebol/lychrel-numbers.rebol new file mode 100644 index 0000000000..b0c2d4f790 --- /dev/null +++ b/Task/Lychrel-numbers/Rebol/lychrel-numbers.rebol @@ -0,0 +1,84 @@ +Rebol [ + title: "Rosetta code: Lychrel numbers" + file: %Lychrel_numbers.r3 + url: https://rosettacode.org/wiki/Lychrel_numbers +] + +big-add: function [ + "Big integer addition using strings" + a [string!] b [string!] +][ + ;; Ensure we're working on independent copies so we don't mutate the originals + a: append clear "" a + b: append clear "" b + + ;; Left-pad the shorter number with zeros so both strings are the same length + n: (length? a) - length? b + insert/dup either n < 0 [a][b] #"0" absolute n + + result: copy "" + c: 0 ; carry digit + ;; Walk digits right-to-left, summing each column and propagating carry + for i length? a 1 -1 [ + d: (a/:i - #"0") + (b/:i - #"0") + c ;; numeric value of column sum + c: d / 10 ;; carry into next column + insert result (#"0" + (d % 10)) ;; prepend the ones digit to result + ] + ;; If a final carry remains, prepend it (e.g. 999 + 1 = 1000) + if #"0" != c: #"0" + c [insert result c] + result +] + +lychrel: function/with [ + "Determine whether an integer is a Lychrel number candidate" + ;; Returns the Lychrel seed: the lowest related number in the chain, + ;; or none if num resolves to a palindrome within 1000 steps (i.e. not Lychrel). + ;; Results are memoised in the `cache` map shared across all calls. + num [integer!] +][ + ;; Return cached result immediately if this number was seen before + if val: cache/:num [return val] + + ns: to string! num ;; current value as string (grows with each iteration) + rv: reverse copy ns ;; its digit-reversal + res: num ;; default: num is its own seed + seen: clear [] ;; numbers encountered during this chain, not yet cached + + loop 1000 [ + ns: big-add ns rv ;; next value = current + reverse + rv: reverse copy ns ;; reverse of the new value + + ;; Palindrome found -> num is NOT a Lychrel number + if ns == rv [ res: none break ] + + ;; Hit a number whose Lychrel status is already known -> inherit its result + if val: cache/:ns [ res: val break ] + + append seen ns ;; record this intermediate value for bulk caching below + ] + + ;; Backfill the cache for every intermediate number encountered in this chain + foreach x seen [cache/:x: res] + res +][ + ;; local context - cache persists across calls + cache: make map! [] + +] + +seeds: copy [] ;; Lychrel seeds: numbers that are their own chain origin +related: copy [] ;; Lychrel related: numbers that lead to a known Lychrel seed +palin: copy [] ;; Lychrel palindromes: Lychrel numbers that are also palindromes +;; Run the search over the first 10 000 positive integers and time it +repeat num 10000 [ + s: lychrel num ;; none = not Lychrel, otherwise the seed of num's chain + if s [ + ;; Seeds are numbers equal to their own chain origin; others are related + append either num == s [seeds][related] num + ;; Check whether num is also a palindrome in its own right + if (to string! num) == reverse to string! num [append palin num] + ] +] +print [as-green pad length? seeds -6 "Lychrel seeds:" as-yellow seeds] +print [as-green pad length? related -6 "Lychrel related"] +print [as-green pad length? palin -6 "Lychrel palindromes:" as-yellow palin] diff --git a/Task/Lychrel-numbers/Rust/lychrel-numbers.rust b/Task/Lychrel-numbers/Rust/lychrel-numbers.rs similarity index 100% rename from Task/Lychrel-numbers/Rust/lychrel-numbers.rust rename to Task/Lychrel-numbers/Rust/lychrel-numbers.rs diff --git a/Task/Lychrel-numbers/Wren/lychrel-numbers.wren b/Task/Lychrel-numbers/Wren/lychrel-numbers.wren index c3a10d72e0..1b6eb6b704 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 "./hash" for HashSet var iterations = 500 var limit = 10000 @@ -8,7 +8,7 @@ var bigLimit = BigInt.new(limit) // In the sieve, 0 = not Lychrel, 1 = Seed Lychrel, 2 = Related Lychrel var lychrelSieve = List.filled(limit + 1, 0) var seedLychrels = [] -var relatedLychrels = Set.new() +var relatedLychrels = HashSet.new() var isPalindrome = Fn.new { |bi| var s = bi.toString @@ -32,12 +32,12 @@ var lychrelTest = Fn.new { |i, seq| } var sizeBefore = relatedLychrels.count // if all of these can be added 'i' must be a seed Lychrel - relatedLychrels.addAll(seq.map { |i| i.toString }) // can't add BigInts directly to a Set + relatedLychrels.addAll(seq) if (relatedLychrels.count - sizeBefore == seq.count) { seedLychrels.add(i) lychrelSieve[i] = 1 } else { - relatedLychrels.add(i.toString) + relatedLychrels.add(i) lychrelSieve[i] = 2 } } diff --git a/Task/Lychrel-numbers/Zkl/lychrel-numbers-1.zkl b/Task/Lychrel-numbers/Zkl/lychrel-numbers-1.zkl index ffd19fa3ae..649490e6c7 100644 --- a/Task/Lychrel-numbers/Zkl/lychrel-numbers-1.zkl +++ b/Task/Lychrel-numbers/Zkl/lychrel-numbers-1.zkl @@ -16,9 +16,9 @@ fcn findSeeds(lychrels){ seeds:=List(lychrels[0]); foreach n,lnns in ([1..].zip(lychrels[1,*])){ ln,seq:=lnns; foreach _,s2 in (seeds){ - foreach s3 in (seq){ - if(Void!=(z:=s2.findString(s3)) and 0==s2[z-1]) break(2); - } + foreach s3 in (seq){ + if(Void!=(z:=s2.findString(s3)) and 0==s2[z-1]) break(2); + } } fallthrough{ seeds.append(lnns) } } diff --git a/Task/M-bius-function/ANSI-BASIC/m-bius-function.basic b/Task/M-bius-function/ANSI-BASIC/m-bius-function.basic new file mode 100644 index 0000000000..0abcfa77e7 --- /dev/null +++ b/Task/M-bius-function/ANSI-BASIC/m-bius-function.basic @@ -0,0 +1,28 @@ +100 REM Moebius function +110 DECLARE EXTERNAL FUNCTION Moebius +120 FOR T = 0 TO 9 +130 FOR U = 1 TO 10 +140 PRINT USING "## ": Moebius(10 * T + U); +150 NEXT U +160 PRINT +170 NEXT T +180 END +190 REM *** +200 EXTERNAL FUNCTION Moebius(N) +210 LET M = 1 +220 IF N <> 1 THEN +230 LET F = 2 +240 DO +250 IF MOD(N, (F * F)) = 0 THEN +260 LET M = 0 +270 ELSE +280 IF MOD(N, F) = 0 THEN +290 LET M = -M +300 LET N = N / F +310 END IF +320 LET F = F + 1 +330 END IF +340 LOOP WHILE (F <= N) AND (M <> 0) +350 END IF +360 LET Moebius = M +370 END FUNCTION diff --git a/Task/M-bius-function/ASIC/m-bius-function.asic b/Task/M-bius-function/ASIC/m-bius-function.asic new file mode 100644 index 0000000000..93962d58be --- /dev/null +++ b/Task/M-bius-function/ASIC/m-bius-function.asic @@ -0,0 +1,37 @@ +REM Moebius function +FOR T = 0 TO 9 + FOR U = 1 TO 10 + N = 10 * T + N = N + U + GOSUB CalcMoebius: + PRINT M; + NEXT U + PRINT +NEXT T +END + +CalcMoebius: +REM Calculate Moebius(N). Result in M. +REM NOTE. N changes its value. +M = 1 +IF N <> 1 THEN + F = 2 + StartLoop: + FTo2 = F * F + NModFTo2 = N MOD FTo2 + IF NModFTo2 = 0 THEN + M = 0 + ELSE + NModF = N MOD F + IF NModF = 0 THEN + M = -M + N = N / F + ENDIF + F = F + 1 + ENDIF + IF M = 0 THEN AfterLoop: + IF F > N THEN AfterLoop: + GOTO StartLoop: + AfterLoop: +ENDIF +RETURN diff --git a/Task/M-bius-function/Ada/m-bius-function.adb b/Task/M-bius-function/Ada/m-bius-function.adb new file mode 100644 index 0000000000..53ad9467fc --- /dev/null +++ b/Task/M-bius-function/Ada/m-bius-function.adb @@ -0,0 +1,39 @@ +with Ada.Text_IO; use Ada.Text_IO; +with Strings_Edit.Integers; use Strings_Edit.Integers; +with Unbounded_Unsigneds; use Unbounded_Unsigneds; +with Unbounded_Unsigneds.Primes; use Unbounded_Unsigneds.Primes; + +procedure Moebius is + function Moebius (N : Half_Word) return Integer is + Prime : Unbounded_Unsigned := One; + Value : Half_Word := N; + Factor : Half_Word; + Result : Integer := 1; + begin + while Value > 1 loop + Next_Prime (Prime, 15); + Factor := To_Half_Word (Prime); + if Value mod Factor = 0 then + Value := Value / Factor; + if Value mod Factor = 0 then + return 0; + end if; + Result := -Result; + end if; + end loop; + return Result; + end Moebius; + Line : String (1..80); + Pointer : Integer := 1; +begin + for N in Half_Word range 1..199 loop + Put (Line, Pointer, Moebius (N), 10, True, 3, Strings_Edit.Right); + if Pointer > 68 then + Put_Line (Line (1..Pointer - 1)); + Pointer := 1; + end if; + end loop; + if Pointer > 1 then + Put_Line (Line (1..Pointer - 1)); + end if; +end Moebius; diff --git a/Task/M-bius-function/Arturo/m-bius-function.arturo b/Task/M-bius-function/Arturo/m-bius-function.arturo index 4e15067fa9..00917b811b 100644 --- a/Task/M-bius-function/Arturo/m-bius-function.arturo +++ b/Task/M-bius-function/Arturo/m-bius-function.arturo @@ -4,8 +4,8 @@ mobius: function [n][ f: factors.prime n if f <> unique f -> return 0 - if? odd? size f -> return neg 1 - else -> return 1 + switch odd? size f -> return neg 1 + -> return 1 ] loop split.every:20 map 0..199 => mobius 'a -> diff --git a/Task/M-bius-function/C-sharp/m-bius-function.cs b/Task/M-bius-function/C-sharp/m-bius-function.cs new file mode 100644 index 0000000000..48a19a5f7c --- /dev/null +++ b/Task/M-bius-function/C-sharp/m-bius-function.cs @@ -0,0 +1,84 @@ +using System; + +namespace MobiusDemo +{ + class Program + { + // ----------------------------------------------------------------- + // Settings that are identical to the Java version + // ----------------------------------------------------------------- + private const int MU_MAX = 1_000_000; // same upper bound + private static int[] MU = null; // will hold the sieve + + static void Main(string[] args) + { + Console.WriteLine("First 199 terms of the möbius function are as follows:"); + Console.Write(" "); + + for (int n = 1; n < 200; n++) + { + Console.Write($"{MobiusFunction(n),2} "); + + // line‑break after every 20 numbers – exactly like the Java code + if ((n + 1) % 20 == 0) + Console.WriteLine(); + } + } + + // ----------------------------------------------------------------- + // Compute μ(n) using the same sieve algorithm that the Java code + // uses. The first call builds the whole table up to MU_MAX. + // ----------------------------------------------------------------- + private static int MobiusFunction(int n) + { + // If the sieve has already been built we can return the answer + // straight away. + if (MU != null) + return MU[n]; + + // ------------------------------------------------------------- + // Build the sieve (once) + // ------------------------------------------------------------- + MU = new int[MU_MAX + 1]; + + // initialise every entry with 1 – Java did this explicitly + for (int i = 0; i <= MU_MAX; i++) + MU[i] = 1; + + int sqrt = (int)Math.Sqrt(MU_MAX); + + // first pass: multiply by -p for each prime factor p, + // and mark multiples of p² as zero. + for (int i = 2; i <= sqrt; i++) + { + if (MU[i] == 1) // i is still “prime” + { + // flip the sign for every multiple of i + for (int j = i; j <= MU_MAX; j += i) + MU[j] *= -i; + + // any number that contains i² gets value 0 + int i2 = i * i; + for (int j = i2; j <= MU_MAX; j += i2) + MU[j] = 0; + } + } + + // second pass: reduce the encoded values to the final μ(n) + for (int i = 2; i <= MU_MAX; i++) + { + if (MU[i] == i) // only +i => μ = +1 + MU[i] = 1; + else if (MU[i] == -i) // only -i => μ = -1 + MU[i] = -1; + else if (MU[i] < 0) // product of an odd number of distinct primes + MU[i] = 1; + else if (MU[i] > 0) // product of an even number of distinct primes + MU[i] = -1; + // note: MU[i] == 0 stays 0 (square factor present) + } + + return MU[n]; + } + } +} diff --git a/Task/M-bius-function/Delphi/m-bius-function.delphi b/Task/M-bius-function/Delphi/m-bius-function.pas similarity index 100% rename from Task/M-bius-function/Delphi/m-bius-function.delphi rename to Task/M-bius-function/Delphi/m-bius-function.pas diff --git a/Task/M-bius-function/EasyLang/m-bius-function.easy b/Task/M-bius-function/EasyLang/m-bius-function.easy index 2826147573..764f397637 100644 --- a/Task/M-bius-function/EasyLang/m-bius-function.easy +++ b/Task/M-bius-function/EasyLang/m-bius-function.easy @@ -6,12 +6,8 @@ for i to mu_max . for i = 2 to sqroot if mu[i] = 1 - for j = i step i to mu_max - mu[j] *= -i - . - for j = i * i step i * i to mu_max - mu[j] = 0 - . + for j = i step i to mu_max : mu[j] *= -i + for j = i * i step i * i to mu_max : mu[j] = 0 . . for i = 2 to mu_max @@ -25,10 +21,8 @@ for i = 2 to mu_max mu[i] = -1 . . -numfmt 0 3 +numfmt 3 0 for i = 1 to 100 write mu[i] - if i mod 10 = 0 - print "" - . + if i mod 10 = 0 : print "" . diff --git a/Task/M-bius-function/Forth/m-bius-function.fth b/Task/M-bius-function/Forth/m-bius-function.fth new file mode 100644 index 0000000000..16d5292cfb --- /dev/null +++ b/Task/M-bius-function/Forth/m-bius-function.fth @@ -0,0 +1,36 @@ +\ Moebius function +: mu ( u -- n ) + \ multiple of 4 so return 0 + dup 3 and 0= if drop 0 exit then + \ even numbers have 2 as a prime factor + dup 1 and 0= if 2/ 1 else 0 then >r + \ look for odd prime factors up to the square root + 3 begin + 2dup dup * >= + while + 2dup mod 0= if + tuck / swap + 2dup mod 0= if + \ repeated prime factor so return 0 + 2drop rdrop 0 exit + then + \ we have another prime factor + r> 1+ >r + then + 2 + + repeat + drop + \ prime factor > square root? + r> swap 1 > if 1+ then + 1 and 0= if 1 else -1 then ; + +: main ( -- ) + ." The first 199 Moebius numbers are:" cr + ." " + 200 1 do + i mu 3 .r + i 1+ 20 mod 0= if cr else then + loop ; + +main +bye diff --git a/Task/M-bius-function/Gambas/m-bius-function.gambas b/Task/M-bius-function/Gambas/m-bius-function.gambas new file mode 100644 index 0000000000..b62750334b --- /dev/null +++ b/Task/M-bius-function/Gambas/m-bius-function.gambas @@ -0,0 +1,27 @@ +Public Sub Main() + + Dim outstr As String = " . " + + For i As Integer = 1 To 200 + If mobius(i) >= 0 Then outstr &= " " + outstr &= Str(mobius(i)) & " " + If i Mod 10 = 9 Then + Print outstr + outstr = "" + End If + Next + +End + +Function mobius(n As Integer) As Integer + + If n = 1 Then Return 1 + For d As Integer = 2 To Int(Sqr(n)) + If n Mod d = 0 Then + If n Mod (d * d) = 0 Then Return 0 + Return -mobius(n / d) + End If + Next + Return -1 + +End Function diff --git a/Task/M-bius-function/JavaScript/m-bius-function-1.js b/Task/M-bius-function/JavaScript/m-bius-function-1.js new file mode 100644 index 0000000000..90052b19c4 --- /dev/null +++ b/Task/M-bius-function/JavaScript/m-bius-function-1.js @@ -0,0 +1,32 @@ +// Moebius function + +function moebius(n) { + m = 1; + if (n != 1) { + f = 2; + do { + if (n % (f * f) == 0) { + m = 0; + } else { + if (n % f == 0) { + m = -m; + n /= f; + } + f++; + } + } while (f <= n && m != 0); + } + return m; +} + +document.write(""); +for (t = 0; t <= 9; t++) { + document.write(""); + for (u = 1; u <= 10; u++) { + document.write(""); + } + document.write(""); +} +document.write("
    "); + document.write(moebius(10 * t + u)); + document.write("
    "); diff --git a/Task/M-bius-function/JavaScript/m-bius-function-2.js b/Task/M-bius-function/JavaScript/m-bius-function-2.js new file mode 100644 index 0000000000..9fa62b473a --- /dev/null +++ b/Task/M-bius-function/JavaScript/m-bius-function-2.js @@ -0,0 +1,7 @@ + + + + + + + diff --git a/Task/M-bius-function/Julia/m-bius-function.julia b/Task/M-bius-function/Julia/m-bius-function.jl similarity index 100% rename from Task/M-bius-function/Julia/m-bius-function.julia rename to Task/M-bius-function/Julia/m-bius-function.jl diff --git a/Task/M-bius-function/K/m-bius-function.k b/Task/M-bius-function/K/m-bius-function.k new file mode 100644 index 0000000000..9d6ca736fe --- /dev/null +++ b/Task/M-bius-function/K/m-bius-function.k @@ -0,0 +1,8 @@ +mus:{ / values of mu(i) for i below x + (~~!x) { / initial value: 0 1 1 1 1 ... + y[z *1+!(-z )!x-1]*:-1 / flip sign + y[z*z*1+!(-z*z)!x-1]:0 / set squares to zero + y}[x]/ `pri x} / for each prime below x +(μ:):{mus[1+0|/,//x]x} +`0:"The first 100 values of the μ function:" +`0:,/'-3$$μ 10 10#1+!100 diff --git a/Task/M-bius-function/Kotlin/m-bius-function.kotlin b/Task/M-bius-function/Kotlin/m-bius-function.kts similarity index 100% rename from Task/M-bius-function/Kotlin/m-bius-function.kotlin rename to Task/M-bius-function/Kotlin/m-bius-function.kts diff --git a/Task/M-bius-function/Loglan82/m-bius-function.loglan82 b/Task/M-bius-function/Loglan82/m-bius-function.loglan82 new file mode 100644 index 0000000000..7353387437 --- /dev/null +++ b/Task/M-bius-function/Loglan82/m-bius-function.loglan82 @@ -0,0 +1,38 @@ +(* Moebius function *) + +block + + unit Moebius: function (n: integer): integer; + var + m, f: integer; + begin + m := 1; + if n =/= 1 + then + f := 2; + do + if n mod (f * f) = 0 + then m := 0 + else + if n mod f = 0 + then + m := -m; + n := n div f + fi; + f := f + 1 + fi; + if (f > n) or (m = 0) then exit fi + od + fi; + result := m + end; + +var + t, u: integer; +begin + for t := 0 to 9 + do + for u := 1 to 10 do write(Moebius(10 * t + u): 2, " ") od; + writeln; + od; +end; diff --git a/Task/M-bius-function/Modula-2/m-bius-function.mod2 b/Task/M-bius-function/Modula-2/m-bius-function.mod2 new file mode 100644 index 0000000000..5a56c95bd7 --- /dev/null +++ b/Task/M-bius-function/Modula-2/m-bius-function.mod2 @@ -0,0 +1,41 @@ +MODULE Moebius; +(* Moebius function *) +FROM STextIO IMPORT + WriteLn, WriteString; +FROM SWholeIO IMPORT + WriteInt; + +VAR + T, U: INTEGER; + +PROCEDURE Moebius(N: INTEGER): INTEGER; +VAR + M, F: INTEGER; +BEGIN + M := 1; + IF N <> 1 THEN + F := 2; + REPEAT + IF N MOD (F * F) = 0 THEN + M := 0 + ELSE + IF N MOD F = 0 THEN + M := -M; + N := N DIV F + END; + F := F + 1 + END + UNTIL (F > N) OR (M = 0) + END; + RETURN M +END Moebius; + +BEGIN + FOR T := 0 TO 9 DO + FOR U := 1 TO 10 DO + WriteInt(Moebius(10 * T + U), 2); + WriteString(' ') + END; + WriteLn + END +END Moebius. diff --git a/Task/M-bius-function/PHP/m-bius-function.php b/Task/M-bius-function/PHP/m-bius-function.php new file mode 100644 index 0000000000..071a320dcf --- /dev/null +++ b/Task/M-bius-function/PHP/m-bius-function.php @@ -0,0 +1,29 @@ + diff --git a/Task/M-bius-function/Pascal-P/m-bius-function.pas b/Task/M-bius-function/Pascal-P/m-bius-function.pas new file mode 100644 index 0000000000..b517816160 --- /dev/null +++ b/Task/M-bius-function/Pascal-P/m-bius-function.pas @@ -0,0 +1,39 @@ +program moebius(output); + (* Moebius function *) + +var + t, u: integer; + + function moebius(n: integer): integer; + var + m, f: integer; + begin + m := 1; + if n <> 1 then + begin + f := 2; + repeat + if n mod (f * f) = 0 then + m := 0 + else + begin + if n mod f = 0 then + begin + m := -m; + n := n div f + end; + f := f + 1 + end + until (f > n) or (m = 0) + end; + moebius := m + end; + +begin + for t := 0 to 9 do + begin + for u := 1 to 10 do + write(moebius(10 * t + u): 2, ' '); + writeln + end +end. diff --git a/Task/M-bius-function/PascalABC.NET/m-bius-function.pas b/Task/M-bius-function/PascalABC.NET/m-bius-function.pas new file mode 100644 index 0000000000..4760b377f0 --- /dev/null +++ b/Task/M-bius-function/PascalABC.NET/m-bius-function.pas @@ -0,0 +1,15 @@ +uses school; + +function mobius(n: integer): integer; +begin + var factors := n.Factorize; + if factors.Count = factors.ToSet.Count then + result := if factors.Count.IsEven then 1 else -1 + else result := 0 +end; + +begin + println('Mobius numbers from 1..99:'); + for var n := 1 to 99 do + write(mobius(n):3, if n mod 20 = 0 then #10 else ''); +end. diff --git a/Task/M-bius-function/Pluto/m-bius-function.pluto b/Task/M-bius-function/Pluto/m-bius-function.pluto new file mode 100644 index 0000000000..2721fda354 --- /dev/null +++ b/Task/M-bius-function/Pluto/m-bius-function.pluto @@ -0,0 +1,35 @@ +local int = require "int" +local fmt = require "fmt" + +local function is_square_free(n) + local i = 2 + local sq = i * i + while sq <= n do + if n % sq == 0 then return false end + i = (i > 2) ? i + 2 : i + 1 + sq = i * i + end + return true +end + +local function mu(n) + assert(n >= 1, "Argument must be a positive integer") + if n == 1 then return 1 end + local sq_free = is_square_free(n) + local factors = int.factors(n) + if sq_free and #factors % 2 == 0 then return 1 end + if sq_free then return -1 end + return 0 +end + +print("The first 199 Möbius numbers are:") +for i = 0, 9 do + for j = 0, 19 do + if i == 0 and j == 0 then + io.write(" ") + else + fmt.write("% 3d ", mu(i * 20 + j)) + end + end + print() +end diff --git a/Task/M-bius-function/PowerShell/m-bius-function.ps1 b/Task/M-bius-function/PowerShell/m-bius-function.ps1 new file mode 100644 index 0000000000..9c70eee9de --- /dev/null +++ b/Task/M-bius-function/PowerShell/m-bius-function.ps1 @@ -0,0 +1,28 @@ +# Moebius function + +function Moebius([int]$N) { + [int]$m = 1 + if ($N -ne 1) { + [int]$f = 2 + do { + if ($N % ($f * $f) -eq 0) { + $m = 0 + } else { + if ($N % $f -eq 0) { + $m = -$m; + $N = [math]::Floor($N / $f) + } + $f += 1 + } + } while (($f -le $N) -and ($m -ne 0)) + } + return $m +} + +foreach ($t in 0..9) { + [string]$row = @() + foreach ($u in 1..10) { + $row += "{0,2} " -f $(Moebius(10 * $t + $u)) + } + Write-Output $row +} diff --git a/Task/M-bius-function/PureBasic/m-bius-function.basic b/Task/M-bius-function/PureBasic/m-bius-function.basic new file mode 100644 index 0000000000..3959515d0e --- /dev/null +++ b/Task/M-bius-function/PureBasic/m-bius-function.basic @@ -0,0 +1,30 @@ +Procedure.i mobius(n) + If n = 1: + ProcedureReturn 1 + EndIf + For d = 2 To Int(Sqr(n)) + If Mod(n, d) = 0: + If Mod(n, d * d) = 0: + ProcedureReturn 0 + EndIf + ProcedureReturn -mobius(n / d) + EndIf + Next d + ProcedureReturn -1 +EndProcedure + +OpenConsole() +outstr$ = " . " +For i = 1 To 200 + If mobius(i) >= 0: + outstr$ = outstr$ + " " + EndIf + outstr$ = outstr$ + Str(mobius(i)) + " " + If Mod(i, 10) = 9: + PrintN(outstr$) + outstr$ = "" + EndIf +Next i + +PrintN(#CRLF$ + "Press ENTER to exit"): Input() +CloseConsole() diff --git a/Task/M-bius-function/QuickBASIC/m-bius-function.basic b/Task/M-bius-function/QuickBASIC/m-bius-function.basic new file mode 100644 index 0000000000..b39aacf94f --- /dev/null +++ b/Task/M-bius-function/QuickBASIC/m-bius-function.basic @@ -0,0 +1,28 @@ +' Moebius function +DECLARE FUNCTION Moebius% (N%) +FOR T% = 0 TO 9 + FOR U% = 1 TO 10 + PRINT USING "## "; Moebius%(10 * T% + U%); + NEXT U% + PRINT +NEXT T% +END + +FUNCTION Moebius% (N%) + M% = 1 + IF N% <> 1 THEN + F% = 2 + DO + IF (N% MOD (F% * F%)) = 0 THEN + M% = 0 + ELSE + IF N% MOD F% = 0 THEN + M% = -M% + N% = N% \ F% + END IF + F% = F% + 1 + END IF + LOOP WHILE (F% <= N%) AND (M% <> 0) + END IF + Moebius% = M% +END FUNCTION diff --git a/Task/M-bius-function/R/m-bius-function.r b/Task/M-bius-function/R/m-bius-function.r new file mode 100644 index 0000000000..e1818c4339 --- /dev/null +++ b/Task/M-bius-function/R/m-bius-function.r @@ -0,0 +1,28 @@ +# Moebius function + +Moebius <- function(n) { + if (n == 1) + return(1) + m <- 1 + f <- 2 + repeat { + if (n %% (f * f) == 0) + m <- 0 + else { + if (n %% f == 0) { + m <- -m + n <- n %/% f + } + f <- f + 1 + } + if (f > n || m == 0) + break + } + return(m) +} + +mb <- matrix(0, 10, 10) +for (t in 0:9) + for (u in 1:10) + mb[t + 1, u] <- Moebius(10 * t + u) +mb diff --git a/Task/M-bius-function/REXX/m-bius-function.rexx b/Task/M-bius-function/REXX/m-bius-function.rexx index 8f8f2e254d..9cb0c43875 100644 --- a/Task/M-bius-function/REXX/m-bius-function.rexx +++ b/Task/M-bius-function/REXX/m-bius-function.rexx @@ -1,46 +1,28 @@ -/*REXX pgm computes & shows a value grid of the Möbius function for a range of integers.*/ -parse arg LO HI grp . /*obtain optional arguments from the CL*/ -if LO=='' | LO=="," then LO= 0 /*Not specified? Then use the default.*/ -if HI=='' | HI=="," then HI= 199 /* " " " " " " */ -if grp=='' | grp=="," then grp= 20 /* " " " " " " */ - /* ______ */ -call genP HI /*generate primes up to the √ HI */ -say center(' The Möbius sequence from ' LO " ──► " HI" ", max(50, grp*3), '═') /*title*/ -$= /*variable holds output grid of GRP #s.*/ - do j=LO to HI; $= $ right( mobius(j), 2) /*process some numbers from LO ──► HI.*/ - if words($)==grp then do; say substr($, 2); $= /*show grid if fully populated,*/ - end /* and nullify it for more #s.*/ - end /*j*/ /*for small grids, using wordCnt is OK.*/ +-- 23 Aug 2025 +include Setting -if $\=='' then say substr($, 2) /*handle any residual numbers not shown*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -mobius: procedure expose @.; parse arg x /*obtain a integer to be tested for mu.*/ - if x<1 then return '∙' /*special? Then return symbol for null.*/ - #= 0 /*start with a value of zero. */ - do k=1; p= @.k /*get the Kth (pre─generated) prime.*/ - if p>x then leave /*prime (P) > X? Then we're done. */ - if p*p>x then do; #= #+1; leave /*prime (P**2 > X? Bump # and leave.*/ - end - if x//p==0 then do; #= #+1 /*X divisible by P? Bump mu number. */ - x= x % p /* Divide by prime. */ - if x//p==0 then return 0 /*X÷by P? Then return zero*/ - end - end /*k*/ /*# (below) is almost always small, <9*/ - if #//2==0 then return 1 /*Is # even? Then return postive 1 */ - return -1 /* " " odd? " " negative 1. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -genP: @.1=2; @.2=3; @.3=5; @.4=7; @.5=11; @.6= 13; nP=6 /*assign low primes; # primes.*/ - do lim=nP until lim*lim>=HI /*only keep primes up to the sqrt(HI).*/ - end /*lim*/ - do j=@.nP+4 by 2 to HI /*only find odd primes from here on. */ - parse var j '' -1 _;if _==5 then iterate /*Is last digit a "5"? Then not prime*/ - if j// 3==0 then iterate /*is J divisible by 3? " " " */ - if j// 7==0 then iterate /* " " " " 7? " " " */ - if j//11==0 then iterate /* " " " " 11? " " " */ - if j//13==0 then iterate /* " " " " 13? " " " */ - do k=7 while k*k<=j /*divide by some generated odd primes. */ - if j // @.k==0 then iterate j /*Is J divisible by P? Then not prime*/ - end /*k*/ /* [↓] a prime (J) has been found. */ - nP= nP+1; if nP<=HI then @.nP= j /*bump prime count; assign prime to @.*/ - end /*j*/; return +say 'MOEBIUS FUNCTION' +say version +say +numeric digits 100 +call sequence 1,200 +call sequence 100001,100200 +call sequence 1000000001,1000000200 +call sequence 10000000000001,10000000000200 +exit + +Sequence: +arg x,y +say 'Moebius sequence from' x 'to' y +n = 0 +do i = x to y + n = n+1 + call charout ,right(Moebius(i),3) + if n//20 = 0 then + say +end +say Format(Time('e'),,3) 'seconds' +say +return + +include Math diff --git a/Task/M-bius-function/Rust/m-bius-function.rust b/Task/M-bius-function/Rust/m-bius-function.rs similarity index 100% rename from Task/M-bius-function/Rust/m-bius-function.rust rename to Task/M-bius-function/Rust/m-bius-function.rs diff --git a/Task/M-bius-function/Swift/m-bius-function.swift b/Task/M-bius-function/Swift/m-bius-function.swift new file mode 100644 index 0000000000..5cdbe1c56e --- /dev/null +++ b/Task/M-bius-function/Swift/m-bius-function.swift @@ -0,0 +1,36 @@ +import Foundation + +// Moebius function +func mu(number: Int) -> Int { + var n = number + if n % 4 == 0 { + return 0 + } + var primeFactors = 0 + if n % 2 == 0 { + primeFactors += 1 + n /= 2 + } + var p = 3 + while p * p <= n { + if n % p == 0 { + n /= p + if n % p == 0 { + return 0 + } + primeFactors += 1 + } + p += 2 + } + if (n > 1) { + primeFactors += 1 + } + return primeFactors % 2 == 0 ? 1 : -1 +} + +print("The first 199 Moebius numbers are:") +print(" ", terminator: "") +for i in 1..<200 { + print(String(format: "%3d", mu(number: i)), + terminator: (i + 1) % 20 == 0 ? "\n" : "") +} diff --git a/Task/M-bius-function/Tcl/m-bius-function.tcl b/Task/M-bius-function/Tcl/m-bius-function.tcl new file mode 100644 index 0000000000..8a46858a3d --- /dev/null +++ b/Task/M-bius-function/Tcl/m-bius-function.tcl @@ -0,0 +1,42 @@ +proc prime_factors {n} { + set d 1 + set factors [list] + while {$n > 1 && $d < $n} { + incr d + set d_squared [expr {$d * $d}] + while {$n % $d == 0} { + lappend factors $d + set n [expr {$n / $d}] + } + } + return $factors +} + +proc mobius {n} { + set p [prime_factors $n] + set unique_p [lsort -unique $p] + if {[llength $p] == [llength $unique_p]} { + if {[llength $p] % 2 == 0} { + return 1 + } else { + return -1 + } + } else { + return 0 + } +} + +set upto 199 +set moebius_sequence [list] +for {set i 1} {$i <= $upto} {incr i} { + lappend moebius_sequence [mobius $i] +} + +puts "Möbius sequence - First $upto terms:" +for {set i 0} {$i < $upto} {incr i} { + if {$i % 20 == 0 && $i != 0} { + puts "" + } + puts -nonewline [format "%4d" [lindex $moebius_sequence $i]] +} +puts "" diff --git a/Task/M-bius-function/Uiua/m-bius-function.uiua b/Task/M-bius-function/Uiua/m-bius-function.uiua new file mode 100644 index 0000000000..6ca4e308e2 --- /dev/null +++ b/Task/M-bius-function/Uiua/m-bius-function.uiua @@ -0,0 +1,3 @@ +# e.g. 12 -> [2 2 3] -> [2 1] -> [0 1] -> [0 ¯1] -> 0 +Moeb ← +0/ׯ≤1⊕⧻⊸⊛°/× +↯∞_10≡Moeb↘1⇡101 diff --git a/Task/M-bius-function/VBA/m-bius-function.vba b/Task/M-bius-function/VBA/m-bius-function.vba new file mode 100644 index 0000000000..9a4fcfc636 --- /dev/null +++ b/Task/M-bius-function/VBA/m-bius-function.vba @@ -0,0 +1,41 @@ +' Moebius function + +Public Sub MainMoebius() + Dim T, U As Integer + For T = 0 To 9 + For U = 1 To 10 + Debug.Print FormatInteger(Moebius(10 * T + U), 2); " "; + Next U + Debug.Print + Next T +End Sub + +Function FormatInteger(Num As Integer, L As Integer) As String + Dim S As String + S = LTrim(RTrim(Str(Num))) + If Len(S) > L Then + FormatInteger = String(L, "#") + Else + FormatInteger = Right(String(L, " ") & S, L) + End If +End Function + +Function Moebius(N As Integer) As Integer + Dim M, F As Integer + M = 1 + If N <> 1 Then + F = 2 + Do + If (N Mod (F * F)) = 0 Then + M = 0 + Else + If N Mod F = 0 Then + M = -M + N = N \ F + End If + F = F + 1 + End If + Loop While (F <= N) And (M <> 0) + End If + Moebius = M +End Function diff --git a/Task/M-bius-function/XBasic/m-bius-function.basic b/Task/M-bius-function/XBasic/m-bius-function.basic new file mode 100644 index 0000000000..7c3fec5047 --- /dev/null +++ b/Task/M-bius-function/XBasic/m-bius-function.basic @@ -0,0 +1,31 @@ +PROGRAM "Möbius function" +VERSION "0.0000" +IMPORT "xma" + + +DECLARE FUNCTION Entry () +DECLARE FUNCTION mobius (n) + +FUNCTION Entry () + outstr$ = " . " + FOR i = 1 TO 200 + IF mobius(i) >= 0 THEN outstr$ = outstr$ + outstr$ = outstr$ + STR$(mobius(i)) + " " + IF i MOD 10 = 9 THEN + PRINT outstr$ + outstr$ = "" + END IF + NEXT i +END FUNCTION + +FUNCTION mobius (n) + IF n = 1 THEN RETURN 1 + FOR d = 2 TO INT(SQRT(n)) + IF n MOD d = 0 THEN + IF n MOD (d*d) = 0 THEN RETURN 0 + RETURN -mobius(n/d) + END IF + NEXT d + RETURN -1 +END FUNCTION +END PROGRAM diff --git a/Task/M-bius-function/Zig/m-bius-function.zig b/Task/M-bius-function/Zig/m-bius-function.zig new file mode 100644 index 0000000000..94c613a5c1 --- /dev/null +++ b/Task/M-bius-function/Zig/m-bius-function.zig @@ -0,0 +1,84 @@ +const std = @import("std"); +const print = std.debug.print; + +fn moebius(x_param: u64) i8 { + var x = x_param; + var prime_count: u32 = 0; + + // Helper function to divide x by a factor and count it + // Returns true if we should return 0 (factor appears twice) + const divideXBy = struct { + fn call(x_ptr: *u64, factor: u64, prime_count_ptr: *u32) bool { + if (x_ptr.* % factor == 0) { + x_ptr.* /= factor; + prime_count_ptr.* += 1; + if (x_ptr.* % factor == 0) { + return true; // Return 0 + } + } + return false; + } + }.call; + + // Handle 2 and 3 separately + if (divideXBy(&x, 2, &prime_count)) return 0; + if (divideXBy(&x, 3, &prime_count)) return 0; + + // Use a wheel sieve to check the remaining factors <= √x + var i: u64 = 5; + const sqrt_x = isqrt(x); + while (i <= sqrt_x) : (i += 6) { + if (divideXBy(&x, i, &prime_count)) return 0; + if (divideXBy(&x, i + 2, &prime_count)) return 0; + } + + // There can exist one prime factor larger than √x, + // in that case we can check if x is still larger than one, and then count it. + if (x > 1) { + prime_count += 1; + } + + if (prime_count % 2 == 0) { + return 1; + } else { + return -1; + } +} + +/// Returns the largest integer smaller than or equal to `√n` +fn isqrt(n: u64) u64 { + if (n <= 1) { + return n; + } else { + var x0: u64 = std.math.pow(u64, 2, @as(u32, @intFromFloat(@floor(@log2(@as(f64, @floatFromInt(n))) / 2.0))) + 1); + var x1: u64 = (x0 + n / x0) / 2; + while (x1 < x0) { + x0 = x1; + x1 = (x0 + n / x0) / 2; + } + return x0; + } +} + +pub fn main() void { + const ROWS: u64 = 10; + const COLS: u64 = 20; + print("Values of the Möbius function, μ(x), for x between 0 and {}:\n", .{COLS * ROWS}); + + for (0..ROWS) |i| { + for (0..COLS + 1) |j| { + const x = COLS * i + j; + const mu = moebius(x); + if (mu >= 0) { + // Print an extra space if there's no minus sign in front of the output + // in order to align the numbers in a nice grid. + print(" ", .{}); + } + print("{} ", .{mu}); + } + print("\n" , .{}); + } + + const x = std.math.maxInt(u64); + print("\nμ({}) = {}\n", .{ x, moebius(x) }); +} diff --git a/Task/MAC-vendor-lookup/AWK/mac-vendor-lookup.awk b/Task/MAC-vendor-lookup/AWK/mac-vendor-lookup.awk new file mode 100644 index 0000000000..9bbf706b74 --- /dev/null +++ b/Task/MAC-vendor-lookup/AWK/mac-vendor-lookup.awk @@ -0,0 +1,21 @@ +# syntax: GAWK -f MAC_VENDOR_LOOKUP.AWK +# operating system: Windows 11 +@load "time" +BEGIN { + fn = "CURL.TMP" + n = split("88:53:2E:67:07:BE,FC:FB:FB:01:FA:21,D4:F4:6F:C9:EF:8D,FCA13E2A1C33,banana",arr,",") + for (i=1; i<=n; i++) { + cmd = sprintf("CURL.EXE --silent --output %s --url https://api.macvendors.com/%s",fn,arr[i]) + system(cmd) + while (getline rec 0) { + if (tolower(rec) ~ /error/) { + rec = "N/A" + } + printf("%-17s %s\n",arr[i],rec) + } + close(fn) + sleep(1) + } + system("DEL " fn) + exit(0) +} diff --git a/Task/MAC-vendor-lookup/Ada/mac-vendor-lookup.ada b/Task/MAC-vendor-lookup/Ada/mac-vendor-lookup.adb similarity index 100% rename from Task/MAC-vendor-lookup/Ada/mac-vendor-lookup.ada rename to Task/MAC-vendor-lookup/Ada/mac-vendor-lookup.adb diff --git a/Task/MAC-vendor-lookup/Delphi/mac-vendor-lookup.delphi b/Task/MAC-vendor-lookup/Delphi/mac-vendor-lookup.pas similarity index 100% rename from Task/MAC-vendor-lookup/Delphi/mac-vendor-lookup.delphi rename to Task/MAC-vendor-lookup/Delphi/mac-vendor-lookup.pas diff --git a/Task/MAC-vendor-lookup/FutureBasic/mac-vendor-lookup.basic b/Task/MAC-vendor-lookup/FutureBasic/mac-vendor-lookup.basic new file mode 100644 index 0000000000..b8cd701fb1 --- /dev/null +++ b/Task/MAC-vendor-lookup/FutureBasic/mac-vendor-lookup.basic @@ -0,0 +1,15 @@ +local fn MACVendorLookup( vendor as CFStringRef ) as CFStringRef +CFStringRef cmd = fn StringWithFormat( @"curl -s \"https://api.macvendors.com/%@\" && echo", vendor ) +return unix cmd +end fn = NULL + +CFStringRef MACaddr +CFArrayRef vendors +vendors = @[@"88:53:2E:67:07:BE", @"D4:F4:6F:C9:EF:8D", @"FC:FB:FB:01:FA:21", @"4c:72:b9:56:fe:bc", @"00-14-22-01-23-45"] + +for MACaddr in vendors +print fn StringByReplacingOccurrencesOfString( fn MACVendorLookup( MACaddr ), @"\n", @"" ) +delay 1000 // Delay a second between each request to prevent api.macvendors.com server from rejecting query +next + +HandleEvents diff --git a/Task/MAC-vendor-lookup/Julia/mac-vendor-lookup.jl b/Task/MAC-vendor-lookup/Julia/mac-vendor-lookup.jl new file mode 100644 index 0000000000..767a6a340b --- /dev/null +++ b/Task/MAC-vendor-lookup/Julia/mac-vendor-lookup.jl @@ -0,0 +1,14 @@ +import HTTP: get + +function getvendor(addr::String) + try + String(get("http://api.macvendors.com/$addr").body) + catch e + "Vendor not found" + end +end + +for addr in ["88:53:2E:67:07:BE", "FC:FB:FB:01:FA:21", "D4:F4:6F:C9:EF:8D", "23:45:67"] + println("$addr -> ", getvendor(addr)) + sleep(0.5) # web site may error if requests are too close together +end diff --git a/Task/MAC-vendor-lookup/Julia/mac-vendor-lookup.julia b/Task/MAC-vendor-lookup/Julia/mac-vendor-lookup.julia deleted file mode 100644 index 79e31cc0e0..0000000000 --- a/Task/MAC-vendor-lookup/Julia/mac-vendor-lookup.julia +++ /dev/null @@ -1,15 +0,0 @@ -# v0.6.0 - -using Requests - -function getvendor(addr::String) - try - get("http://api.macvendors.com/$addr") |> readstring - catch e - nothing - end -end - -for addr in ["88:53:2E:67:07:BE", "FC:FB:FB:01:FA:21", "D4:F4:6F:C9:EF:8D", "23:45:67"] - println("$addr -> ", getvendor(addr)) -end diff --git a/Task/MAC-vendor-lookup/Kotlin/mac-vendor-lookup.kotlin b/Task/MAC-vendor-lookup/Kotlin/mac-vendor-lookup.kts similarity index 100% rename from Task/MAC-vendor-lookup/Kotlin/mac-vendor-lookup.kotlin rename to Task/MAC-vendor-lookup/Kotlin/mac-vendor-lookup.kts diff --git a/Task/MAC-vendor-lookup/OCaml/mac-vendor-lookup.ocaml b/Task/MAC-vendor-lookup/OCaml/mac-vendor-lookup.ml similarity index 100% rename from Task/MAC-vendor-lookup/OCaml/mac-vendor-lookup.ocaml rename to Task/MAC-vendor-lookup/OCaml/mac-vendor-lookup.ml diff --git a/Task/MAC-vendor-lookup/PascalABC.NET/mac-vendor-lookup.pas b/Task/MAC-vendor-lookup/PascalABC.NET/mac-vendor-lookup.pas new file mode 100644 index 0000000000..49fece1ba1 --- /dev/null +++ b/Task/MAC-vendor-lookup/PascalABC.NET/mac-vendor-lookup.pas @@ -0,0 +1,11 @@ +## +uses System.Net; + +ServicePointManager.SecurityProtocol := SecurityProtocolType(3072); +var wc := new WebClient; + +foreach var mac in |'FC-A1-3E', 'FC:FB:FB:01:FA:21', 'BC:5F:F4'| do +begin + println(mac, wc.DownloadString('https://api.macvendors.com/' + mac)); + Sleep(1500); +end; diff --git a/Task/MAC-vendor-lookup/PowerShell/mac-vendor-lookup.psh b/Task/MAC-vendor-lookup/PowerShell/mac-vendor-lookup.ps1 similarity index 100% rename from Task/MAC-vendor-lookup/PowerShell/mac-vendor-lookup.psh rename to Task/MAC-vendor-lookup/PowerShell/mac-vendor-lookup.ps1 diff --git a/Task/MAC-vendor-lookup/Rebol/mac-vendor-lookup.rebol b/Task/MAC-vendor-lookup/Rebol/mac-vendor-lookup.rebol new file mode 100644 index 0000000000..86e791638c --- /dev/null +++ b/Task/MAC-vendor-lookup/Rebol/mac-vendor-lookup.rebol @@ -0,0 +1,9 @@ +system/options/quiet: true +foreach mac [ + "88:53:2E:67:07:BE" + "FC:FB:FB:01:FA:21" + "D4:F4:6F:C9:EF:8D" +][ + res: read join http://api.macvendors.com/ mac + print [mac res] +] diff --git a/Task/MAC-vendor-lookup/Rust/mac-vendor-lookup.rs b/Task/MAC-vendor-lookup/Rust/mac-vendor-lookup.rs new file mode 100644 index 0000000000..6d29a92c57 --- /dev/null +++ b/Task/MAC-vendor-lookup/Rust/mac-vendor-lookup.rs @@ -0,0 +1,60 @@ +extern crate reqwest; +extern crate trpl; + +use std::{thread, time}; + +async fn get_vendor(mac: &str) -> Option { + let mut url = String::from("http://api.macvendors.com/"); + url.push_str(mac); + let url_ref = &url; + match reqwest::get(url_ref).await { + Ok(res) => match res.text().await { + Ok(text) => { + if text.contains("Not Found") { + Some("N/A".to_string()) + } else { + Some(text) + } + } + Err(e) => { + println!("{:?}", e); + None + } + }, + Err(e) => { + println!("{:?}", e); + None + } + } +} + +fn main() { + let duration = time::Duration::from_millis(1000); + trpl::block_on(async { + match get_vendor("88:53:2E:67:07:BE").await { + None => println!("Error!"), + Some(text) => println!("{}", text), + } + }); + thread::sleep(duration); + trpl::block_on(async { + match get_vendor("FC:FB:FB:01:FA:21").await { + None => println!("Error!"), + Some(text) => println!("{}", text), + } + }); + thread::sleep(duration); + trpl::block_on(async { + match get_vendor("FC-A1-3E").await { + None => println!("Error!"), + Some(text) => println!("{}", text), + } + }); + thread::sleep(duration); + trpl::block_on(async { + match get_vendor("abcdefg").await { + None => println!("Error!"), + Some(text) => println!("{}", text), + } + }); +} diff --git a/Task/MAC-vendor-lookup/Rust/mac-vendor-lookup.rust b/Task/MAC-vendor-lookup/Rust/mac-vendor-lookup.rust deleted file mode 100644 index 23fe5c6c37..0000000000 --- a/Task/MAC-vendor-lookup/Rust/mac-vendor-lookup.rust +++ /dev/null @@ -1,51 +0,0 @@ -extern crate reqwest; - -use std::{thread, time}; - -fn get_vendor(mac: &str) -> Option { - let mut url = String::from("http://api.macvendors.com/"); - url.push_str(mac); - let url_ref = &url; - match reqwest::get(url_ref) { - Ok(mut res) => match res.text() { - Ok(text) => { - if text.contains("Not Found") { - Some("N/A".to_string()) - } else { - Some(text) - } - } - Err(e) => { - println!("{:?}", e); - None - } - }, - Err(e) => { - println!("{:?}", e); - None - } - } -} - -fn main() { - let duration = time::Duration::from_millis(1000); - match get_vendor("88:53:2E:67:07:BE") { - None => println!("Error!"), - Some(text) => println!("{}", text), - } - thread::sleep(duration); - match get_vendor("FC:FB:FB:01:FA:21") { - None => println!("Error!"), - Some(text) => println!("{}", text), - } - thread::sleep(duration); - match get_vendor("FC-A1-3E") { - None => println!("Error!"), - Some(text) => println!("{}", text), - } - thread::sleep(duration); - match get_vendor("abcdefg") { - None => println!("Error!"), - Some(text) => println!("{}", text), - } -} diff --git a/Task/MAC-vendor-lookup/Scheme/mac-vendor-lookup.ss b/Task/MAC-vendor-lookup/Scheme/mac-vendor-lookup.scm similarity index 100% rename from Task/MAC-vendor-lookup/Scheme/mac-vendor-lookup.ss rename to Task/MAC-vendor-lookup/Scheme/mac-vendor-lookup.scm diff --git a/Task/MAC-vendor-lookup/V-(Vlang)/mac-vendor-lookup.v b/Task/MAC-vendor-lookup/V-(Vlang)/mac-vendor-lookup.v index b0e0dc190d..55037b2dbc 100644 --- a/Task/MAC-vendor-lookup/V-(Vlang)/mac-vendor-lookup.v +++ b/Task/MAC-vendor-lookup/V-(Vlang)/mac-vendor-lookup.v @@ -1,16 +1,16 @@ import net.http import time -const macs = -(' +const macs = (" FC-A1-3E FC:FB:FB:01:FA:21 +xx:12:5 D4:F4:6F:C9:EF:8D -') +") fn main() { - for line in macs.split('\n') { - if line !='' { + for line in macs.split_into_lines() { + if !line.is_blank() { println(mac_lookup(line)) time.sleep(2 * time.second) // considerate delay between attempts } @@ -18,6 +18,6 @@ fn main() { } fn mac_lookup(mac string) string { - resp := http.get("http://api.macvendors.com/" + mac) or {return 'No data from server'} + resp := http.get("http://api.macvendors.com/" + mac) or {return "No data from server"} return resp.body.str() } diff --git a/Task/MAC-vendor-lookup/VBScript/mac-vendor-lookup.vb b/Task/MAC-vendor-lookup/VBScript/mac-vendor-lookup.vbs similarity index 100% rename from Task/MAC-vendor-lookup/VBScript/mac-vendor-lookup.vb rename to Task/MAC-vendor-lookup/VBScript/mac-vendor-lookup.vbs diff --git a/Task/MAC-vendor-lookup/Wren/mac-vendor-lookup-3.wren b/Task/MAC-vendor-lookup/Wren/mac-vendor-lookup-3.wren new file mode 100644 index 0000000000..238c3622b3 --- /dev/null +++ b/Task/MAC-vendor-lookup/Wren/mac-vendor-lookup-3.wren @@ -0,0 +1,10 @@ +import "os" for Process +import "timer" for Timer + +var macs = ["88:53:2E:67:07:BE", "FC:FB:FB:01:FA:21", "D4:F4:6F:C9:EF:8D", "23:45:67"] +for (mac in macs) { + var vendor = Process.read("curl -s " + "https://api.macvendors.com/" + mac) + if (vendor.contains("errors")) vendor = "Vendor not found" + System.print("%(mac) %(vendor)") + Timer.wait(2000) +} diff --git a/Task/MD4/Ada/md4.ada b/Task/MD4/Ada/md4.adb similarity index 100% rename from Task/MD4/Ada/md4.ada rename to Task/MD4/Ada/md4.adb diff --git a/Task/MD4/Delphi/md4.delphi b/Task/MD4/Delphi/md4.pas similarity index 100% rename from Task/MD4/Delphi/md4.delphi rename to Task/MD4/Delphi/md4.pas diff --git a/Task/MD4/EasyLang/md4.easy b/Task/MD4/EasyLang/md4.easy new file mode 100644 index 0000000000..632a825d4c --- /dev/null +++ b/Task/MD4/EasyLang/md4.easy @@ -0,0 +1,128 @@ +func u32 x . + return bitand x 0xFFFFFFFF +. +func rol x s . + left = u32 bitshift x s + right = bitshift u32 x -(32 - s) + return bitor left right +. +func F x y z . + return bitor (bitand x y) (bitand bitnot x z) +. +func G x y z . + return bitor (bitor (bitand x y) (bitand x z)) (bitand y z) +. +func H x y z . + return bitxor (bitxor x y) z +. +func le32 b0 b1 b2 b3 . + return b0 + 256 * b1 + 65536 * b2 + 65536 * 256 * b3 +. +func$ word2hex w . + for k = 0 to 3 + h = w mod 256 + for c in [ h div 16 h mod 16 ] + c += 48 + if c >= 58 : c += 39 + hex$ &= strchar c + . + w = w div 256 + . + return hex$ +. +func[] str2bytes s$ . + for ch$ in strchars s$ : out[] &= strcode ch$ + return out[] +. +proc md4pad &data[] . + len8 = len data[] * 8 + data[] &= 0x80 + while len data[] mod 64 <> 56 : data[] &= 0x00 + for i = 1 to 8 + data[] &= len8 mod 256 + len8 = len8 div 256 + . +. +proc md4block &A &B &C &D blk[] . + for i = 0 to 15 + b0 = blk[i * 4 + 1] + b1 = blk[i * 4 + 2] + b2 = blk[i * 4 + 3] + b3 = blk[i * 4 + 4] + x[] &= le32 b0 b1 b2 b3 + . + a = A ; b = B ; c = C ; d = D + # + a = rol (a + F b c d + x[1]) 3 + d = rol (d + F a b c + x[2]) 7 + c = rol (c + F d a b + x[3]) 11 + b = rol (b + F c d a + x[4]) 19 + a = rol (a + F b c d + x[5]) 3 + d = rol (d + F a b c + x[6]) 7 + c = rol (c + F d a b + x[7]) 11 + b = rol (b + F c d a + x[8]) 19 + a = rol (a + F b c d + x[9]) 3 + d = rol (d + F a b c + x[10]) 7 + c = rol (c + F d a b + x[11]) 11 + b = rol (b + F c d a + x[12]) 19 + a = rol (a + F b c d + x[13]) 3 + d = rol (d + F a b c + x[14]) 7 + c = rol (c + F d a b + x[15]) 11 + b = rol (b + F c d a + x[16]) 19 + # + K2 = 0x5A827999 + a = rol (a + G b c d + x[1] + K2) 3 + d = rol (d + G a b c + x[5] + K2) 5 + c = rol (c + G d a b + x[9] + K2) 9 + b = rol (b + G c d a + x[13] + K2) 13 + a = rol (a + G b c d + x[2] + K2) 3 + d = rol (d + G a b c + x[6] + K2) 5 + c = rol (c + G d a b + x[10] + K2) 9 + b = rol (b + G c d a + x[14] + K2) 13 + a = rol (a + G b c d + x[3] + K2) 3 + d = rol (d + G a b c + x[7] + K2) 5 + c = rol (c + G d a b + x[11] + K2) 9 + b = rol (b + G c d a + x[15] + K2) 13 + a = rol (a + G b c d + x[4] + K2) 3 + d = rol (d + G a b c + x[8] + K2) 5 + c = rol (c + G d a b + x[12] + K2) 9 + b = rol (b + G c d a + x[16] + K2) 13 + # + K3 = 0x6ED9EBA1 + a = rol (a + H b c d + x[1] + K3) 3 + d = rol (d + H a b c + x[9] + K3) 9 + c = rol (c + H d a b + x[5] + K3) 11 + b = rol (b + H c d a + x[13] + K3) 15 + a = rol (a + H b c d + x[3] + K3) 3 + d = rol (d + H a b c + x[11] + K3) 9 + c = rol (c + H d a b + x[7] + K3) 11 + b = rol (b + H c d a + x[15] + K3) 15 + a = rol (a + H b c d + x[2] + K3) 3 + d = rol (d + H a b c + x[10] + K3) 9 + c = rol (c + H d a b + x[6] + K3) 11 + b = rol (b + H c d a + x[14] + K3) 15 + a = rol (a + H b c d + x[4] + K3) 3 + d = rol (d + H a b c + x[12] + K3) 9 + c = rol (c + H d a b + x[8] + K3) 11 + b = rol (b + H c d a + x[16] + K3) 15 + A = u32 (A + a) + B = u32 (B + b) + C = u32 (C + c) + D = u32 (D + d) +. +func$ md4 s$ . + A = 0x67452301 + B = 0xEFCDAB89 + C = 0x98BADCFE + D = 0x10325476 + data[] = str2bytes s$ + md4pad data[] + for b = 0 to len data[] / 64 - 1 + blk[] = [ ] + for i = 1 to 64 : blk[] &= data[b * 64 + i] + md4block A B C D blk[] + . + digest$ = word2hex A & word2hex B & word2hex C & word2hex D + return digest$ +. +print md4 "Rosetta Code" diff --git a/Task/MD4/Emacs-Lisp/md4.l b/Task/MD4/Emacs-Lisp/md4.el similarity index 100% rename from Task/MD4/Emacs-Lisp/md4.l rename to Task/MD4/Emacs-Lisp/md4.el diff --git a/Task/MD4/Julia/md4.julia b/Task/MD4/Julia/md4.jl similarity index 100% rename from Task/MD4/Julia/md4.julia rename to Task/MD4/Julia/md4.jl diff --git a/Task/MD4/Kotlin/md4.kotlin b/Task/MD4/Kotlin/md4.kts similarity index 100% rename from Task/MD4/Kotlin/md4.kotlin rename to Task/MD4/Kotlin/md4.kts diff --git a/Task/MD4/Pluto/md4.pluto b/Task/MD4/Pluto/md4.pluto new file mode 100644 index 0000000000..c6c5f6972b --- /dev/null +++ b/Task/MD4/Pluto/md4.pluto @@ -0,0 +1,108 @@ +require "table2" + +local function to_bytes(val) + local bytes = {0, 0, 0, 0} + bytes[1] = val & 255 + bytes[2] = (val >> 8) & 255 + bytes[3] = (val >> 16) & 255 + bytes[4] = (val >> 24) & 255 + return bytes +end + +local function to_int(bytes) + return bytes[1] | bytes[2] << 8 | bytes[3] << 16 | bytes[4] << 24 +end + +local mask32 = 0xffffffff + +local function md4(initmsg) + local f = |x, y, z| -> do + x, y, z = x & mask32, y & mask32, z & mask32 + return (x & y) | (~x & z) + end + local g = |x, y, z| -> do + x, y, z = x & mask32, y & mask32, z & mask32 + return (x & y) | (x & z) | (y & z) + end + local h = |x, y, z| -> do + x, y, z = x & mask32, y & mask32, z & mask32 + return x ~ y ~ z + end + local r = |v, s| -> do + v = v & mask32 + return ((v << s) & mask32) | (v >> (32 - s)) + end + local a = 0x67452301 + local b = 0xefcdab89 + local c = 0x98badcfe + local d = 0x10325476 + local initbytes = {string.byte(initmsg, 1, -1)} + local initlen = #initbytes + local newlen = initlen + 1 + while newlen % 64 != 56 do newlen += 1 end + local msg = table.rep(newlen + 8, 0) + for i = 1, initlen do msg[i] = initbytes[i] end + msg[initlen + 1] = 0x80 -- remaining bytes already 0 + local lenbits = to_bytes(initlen * 8) + for i = newlen + 1, newlen + 4 do msg[i] = lenbits[i - newlen] end + local extrabits = to_bytes(initlen >> 29) + for i = newlen + 5, newlen + 8 do msg[i] = extrabits[i - newlen - 4] end + local offset = 0 + local x = table.rep(16, 0) + while offset < newlen do + for i = 0, 15 do x[i + 1] = to_int(msg:slice(offset + i * 4 + 1, offset + i * 4 + 4)) end + local a2 = a + local b2 = b + local c2 = c + local d2 = d + for {0, 4, 8, 12} as i do + a = r(a + f(b, c, d) + x[i + 1], 3) + d = r(d + f(a, b, c) + x[i + 2], 7) + c = r(c + f(d, a, b) + x[i + 3], 11) + b = r(b + f(c, d, a) + x[i + 4], 19) + end + for i = 0, 3 do + a = r(a + g(b, c, d) + x[i + 1] + 0x5a827999, 3) + d = r(d + g(a, b, c) + x[i + 5] + 0x5a827999, 5) + c = r(c + g(d, a, b) + x[i + 9] + 0x5a827999, 9) + b = r(b + g(c, d, a) + x[i + 13] + 0x5a827999, 13) + end + for {0, 2, 1, 3} as i do + a = r(a + h(b, c, d) + x[i + 1] + 0x6ed9eba1, 3) + d = r(d + h(a, b, c) + x[i + 9] + 0x6ed9eba1, 9) + c = r(c + h(d, a, b) + x[i + 5] + 0x6ed9eba1, 11) + b = r(b + h(c, d, a) + x[i + 13] + 0x6ed9eba1, 15) + end + a += a2 + b += b2 + c += c2 + d += d2 + offset += 64 + end + local digest = table.rep(16, 0) + local dbytes = to_bytes(a) + for i = 1, 4 do digest[i] = dbytes[i] end + dbytes = to_bytes(b) + for i = 1, 4 do digest[i + 4] = dbytes[i] end + dbytes = to_bytes(c) + for i = 1, 4 do digest[i + 8] = dbytes[i] end + dbytes = to_bytes(d) + for i = 1, 4 do digest[i + 12] = dbytes[i] end + return digest +end + +local strings = { + "", + "a", + "abc", + "message digest", + "abcdefghijklmnopqrstuvwxyz", + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", + "12345678901234567890123456789012345678901234567890123456789012345678901234567890", + "Rosetta Code" +} + +for strings as s do + local digest = md4(s):map(|e| -> string.format("%02x", e)):concat("") + print($"{digest} <== '{s}'") +end diff --git a/Task/MD4/Rust/md4.rust b/Task/MD4/Rust/md4.rs similarity index 100% rename from Task/MD4/Rust/md4.rust rename to Task/MD4/Rust/md4.rs diff --git a/Task/MD4/V-(Vlang)/md4.v b/Task/MD4/V-(Vlang)/md4.v new file mode 100644 index 0000000000..f3e069c734 --- /dev/null +++ b/Task/MD4/V-(Vlang)/md4.v @@ -0,0 +1,5 @@ +import v_crypto.md4 + +fn main(){ + println("`Rosetta Code` hashed with MD4 is: "+md4.hexhash("Rosetta Code")) +} diff --git a/Task/MD5-Implementation/11l/md5-implementation.11l b/Task/MD5-Implementation/11l/md5-implementation.11l index 61942b1b16..b57b5d7f88 100644 --- a/Task/MD5-Implementation/11l/md5-implementation.11l +++ b/Task/MD5-Implementation/11l/md5-implementation.11l @@ -32,7 +32,7 @@ F md5(=message) L(chunk_ofst) (0 .< message.len).step(64) V (a, b, c, d) = hash_pieces V chunk = message[chunk_ofst .+ 64] - L(i) 64 + L(i) 0.<64 V f = :functions[i I/ 16](b, c, d) V g = :index_functions[i I/ 16](i) V to_rotate = a + f + :constants[i] + UInt32(bytes' chunk[4 * g .+ 4]) diff --git a/Task/MD5-Implementation/Ada/md5-implementation-1.ada b/Task/MD5-Implementation/Ada/md5-implementation-1.adb similarity index 100% rename from Task/MD5-Implementation/Ada/md5-implementation-1.ada rename to Task/MD5-Implementation/Ada/md5-implementation-1.adb diff --git a/Task/MD5-Implementation/Ada/md5-implementation-2.ada b/Task/MD5-Implementation/Ada/md5-implementation-2.adb similarity index 100% rename from Task/MD5-Implementation/Ada/md5-implementation-2.ada rename to Task/MD5-Implementation/Ada/md5-implementation-2.adb diff --git a/Task/MD5-Implementation/Ada/md5-implementation-3.ada b/Task/MD5-Implementation/Ada/md5-implementation-3.adb similarity index 100% rename from Task/MD5-Implementation/Ada/md5-implementation-3.ada rename to Task/MD5-Implementation/Ada/md5-implementation-3.adb diff --git a/Task/MD5-Implementation/C++/md5-implementation.cpp b/Task/MD5-Implementation/C++/md5-implementation.cpp new file mode 100644 index 0000000000..2d913c1b90 --- /dev/null +++ b/Task/MD5-Implementation/C++/md5-implementation.cpp @@ -0,0 +1,128 @@ +#include +#include +#include +#include +#include +#include +#include + +const uint32_t INITIAL_A = 0x67452301; +const uint32_t INITIAL_B = static_cast(0xEFCDAB89L); +const uint32_t INITIAL_C = static_cast(0x98BADCFEL); +const uint32_t INITIAL_D = 0x10325476; + +const std::vector SHIFT_AMOUNTS = { 7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21 }; + +const std::vector K = { 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, + 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, + 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, + 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, + 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, + 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, + 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, + 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, + 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, + 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, + 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, + 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, + 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, + 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, + 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, + 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391 }; + +std::string to_hex_string(const std::vector& bytes) { + std::string hex_string = ""; + std::stringstream stream; + for ( const int8_t& bb : bytes ) { + stream << std::setfill('0') << std::setw(2) << std::hex << ( bb & 0xff ); + hex_string += stream.str(); + stream.str(""); + } + return hex_string; +} + +std::vector to_byte_vector(const std::string& text) { + std::vector bytes; + bytes.reserve(text.size()); + std::transform(text.begin(), text.end(), + std::back_inserter(bytes), [](char ch){ return static_cast(ch); }); + return bytes; +} + +std::vector computeMD5(const std::vector& message) { + uint64_t message_length_bytes = message.size(); + uint32_t number_blocks = ( ( message_length_bytes + 8 ) >> 6 ) + 1; + uint32_t total_length = number_blocks << 6; + std::vector padding_bytes(total_length - message_length_bytes); + padding_bytes[0] = static_cast(0x80); + uint64_t message_length_bits = message_length_bytes << 3; + for ( uint32_t i = 0; i < 8; ++i ) { + padding_bytes[padding_bytes.size() - 8 + i] = static_cast(message_length_bits); + message_length_bits >>= 8; + } + + uint32_t a = INITIAL_A; + uint32_t b = INITIAL_B; + uint32_t c = INITIAL_C; + uint32_t d = INITIAL_D; + + std::vector buffer(16); + for ( uint32_t i = 0; i < number_blocks; ++i ) { + uint32_t index = i << 6; + for ( uint32_t j = 0; j < 64; index++, ++j ) { + buffer[j >> 2] = ( static_cast( ( index < message_length_bytes ) ? message[index] + : padding_bytes[index - message_length_bytes] ) << 24 ) | ( buffer[j >> 2] >> 8 ); + } + + uint32_t original_A = a; + uint32_t original_B = b; + uint32_t original_C = c; + uint32_t original_D = d; + + for ( uint32_t j = 0; j < 64; ++j ) { + uint32_t div16 = j >> 4; + uint32_t f = 0; + uint32_t buffer_index = j; + switch ( div16 ) { + case 0: f = ( b & c ) | ( ~b & d ); break; + case 1: f = ( b & d ) | ( c & ~d ); buffer_index = ( buffer_index * 5 + 1 ) & 0x0F; break; + case 2: f = b ^ c ^ d; buffer_index = ( buffer_index * 3 + 5 ) & 0x0F; break; + case 3: f = c ^ ( b | ~d ); buffer_index = ( buffer_index * 7 ) & 0x0F; break; + } + uint32_t temp = b + std::rotl( + a + f + buffer[buffer_index] + K[j], SHIFT_AMOUNTS[( div16 << 2 ) | ( j & 3 )]); + + a = d; + d = c; + c = b; + b = temp; + } + + a += original_A; + b += original_B; + c += original_C; + d += original_D; + } + + std::vector md5(16); + uint32_t count = 0; + for ( uint32_t i = 0; i < 4; ++i ) { + uint32_t n = ( i == 0 ) ? a : ( ( i == 1 ) ? b : ( ( i == 2 ) ? c : d ) ); + for ( uint32_t j = 0; j < 4; ++j ) { + md5[count++] = static_cast(n); + n >>= 8; + } + } + return md5; +} + +int main() { + const std::vector tests = { "", "a", "abc", "message digest", "abcdefghijklmnopqrstuvwxyz", + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", + "12345678901234567890123456789012345678901234567890123456789012345678901234567890" }; + + for ( const std::string& test : tests ) { + std::cout << to_hex_string(computeMD5(to_byte_vector(test))) << " <== \"" + test + "\"" << "\n"; + + } +} diff --git a/Task/MD5-Implementation/Delphi/md5-implementation.delphi b/Task/MD5-Implementation/Delphi/md5-implementation.pas similarity index 100% rename from Task/MD5-Implementation/Delphi/md5-implementation.delphi rename to Task/MD5-Implementation/Delphi/md5-implementation.pas diff --git a/Task/MD5-Implementation/EasyLang/md5-implementation.easy b/Task/MD5-Implementation/EasyLang/md5-implementation.easy index 2db0a4b538..c4286a9e53 100644 --- a/Task/MD5-Implementation/EasyLang/md5-implementation.easy +++ b/Task/MD5-Implementation/EasyLang/md5-implementation.easy @@ -1,12 +1,12 @@ len md5k[] 64 -proc md5init . . +proc md5init . for i = 1 to 64 md5k[i] = floor (0x100000000 * abs sin (i * 180 / pi)) . . md5init # -proc md5 inp$ . s$ . +func$ md5 inp$ . subr addinp if inp4 = 1 inp[] &= 0 @@ -60,21 +60,20 @@ proc md5 inp$ . s$ . f = bitxor h1 d g = (3 * i + 2) mod 16 else - h1 = bitor b bitnot d + h1 = bitor b bitand bitnot d 0xffffffff f = bitxor c h1 g = (7 * i - 7) mod 16 . - f = (f + a + md5k[i] + inp[chunk + g]) + f = bitand (f + a + md5k[i] + inp[chunk + g]) 0xffffffff a = d d = c c = b h1 = bitshift f s[i] h2 = bitshift f (s[i] - 32) - b = (b + h1 + h2) + b = bitand (b + h1 + h2) 0xffffffff . a0 += a ; b0 += b ; c0 += c ; d0 += d . - s$ = "" for a in [ a0 b0 c0 d0 ] for i = 1 to 4 b = a mod 256 @@ -88,14 +87,15 @@ proc md5 inp$ . s$ . . . . + return s$ . repeat s$ = input until error = 1 - md5 s$ h$ - print h$ + print md5 s$ . input_data + a abc message digest diff --git a/Task/MD5-Implementation/Guile/md5-implementation.guile b/Task/MD5-Implementation/Guile/md5-implementation.guile new file mode 100644 index 0000000000..fd52628d4f --- /dev/null +++ b/Task/MD5-Implementation/Guile/md5-implementation.guile @@ -0,0 +1,196 @@ +;;;This is intended to be run by Guile +;;;If you want to try it elsewhere, I think you might need to replace some module importing lines + +;;module-required (rnrs bytevectors) +;;usage -> {bytevector-u8-list bytevector-length bytevector->uint-list bytevector-u8-set! bytevector-copy! bytevector-u32-set!} {pad listify} +;; +(use-modules (rnrs bytevectors)) + +;;module-required (ice-9 receive) (ice-9 exceptions) +;;usage -> {receive make-exception-with-message} {md5sum test-suite} +;; +(use-modules (ice-9 receive)) +(use-modules (ice-9 exceptions)) + +;;syntax-name F +;;match -> (<$:self:F> B C D) +;; +(define-syntax F + (syntax-rules () + [(_ B C D) + (logior (logand B C) (logand (lognot B) D))])) + +;;syntax-name G +;;match -> (<$:self:G> B C D) +;; +(define-syntax G + (syntax-rules () + [(_ B C D) + (logior (logand B D) (logand C (lognot D)))])) + +;;syntax-name H +;;match -> (<$:self:H> B C D) +;; +(define-syntax H + (syntax-rules () + [(_ B C D) + (logxor B C D)])) + +;;syntax-name I +;;match -> (<$:self:I> B C D) +;; +(define-syntax I + (syntax-rules () + [(_ B C D) + (logxor C (logior B (lognot D)))])) + +;;syntax-name leftrotate +;;match -> (<$:self:leftrotate> num s) +;; +(define-syntax leftrotate + (syntax-rules () + [(_ num s) + (let ([num (logand num #xFFFFFFFF)]) + (logior (ash num (- s 32)) (ash num s)))])) + +;;procedure-name pad +;;input -> bv (bytevector) +;;output -> output-bv (bytevector) [(zero? (floor-remainder (bytevector-length output-bv) 64)) => #t] +;; +(define pad + (lambda (bv) + (let* ([bv-length (bytevector-length bv)] + [original-length (* 8 bv-length)] + + [remainder (floor-remainder bv-length 64)] + [pad-total (if (>= remainder 56) (- 128 remainder) (- 64 remainder))] + [total-length (+ bv-length pad-total)] + [output-bv (make-bytevector total-length 0)] + + [original-length-cooked (logand original-length #xFFFFFFFFFFFFFFFF)] + [original-length-bv (uint-list->bytevector (list original-length-cooked) (endianness little) 8)]) + + (bytevector-copy! bv 0 output-bv 0 bv-length) + (bytevector-u8-set! output-bv bv-length #x80) + (bytevector-copy! original-length-bv 0 output-bv (- total-length 8) 8) + + output-bv))) + +;;procedure-name listify +;;input -> bv (bytevector) [(zero? (floor-remainder (bytevector-length output-bv) 64)) => #t] +;;output -> _ (list:list:u32[16]) +;; +(define listify + (lambda (bv) + (let ([bv-as-u32-list (bytevector->uint-list bv (endianness little) 4)]) + (let ([total-num (/ (length bv-as-u32-list) 16)]) + (let loop ([n 0] [lst bv-as-u32-list]) + (if (>= n (- total-num 1)) + (list lst) + (cons (list-head lst 16) (loop (+ 1 n) (list-tail lst 16))))))))) + +;;procedure-name process-512bits +;;input -> X (list;u32[16]) A B C D K s +;;output -> _ (u32[4]) +;;note -> "This function is intended to do the real 64 rounds calculation and return the A B C D in the end but it doesn't need to loop at all" +;; +(define process-512bits + (lambda (X A B C D K s) + (let ([AA A][BB B][CC C][DD D]) + (let ([F1 #f][g #f][i 0]) + (while (<= i 63) + (when (and (>= i 0) (<= i 15)) + (set! F1 (F BB CC DD)) + (set! g i)) + (when (and (>= i 16) (<= i 31)) + (set! F1 (G BB CC DD)) + (set! g (modulo (1+ (* 5 i)) 16))) + (when (and (>= i 32) (<= i 47)) + (set! F1 (H BB CC DD)) + (set! g (modulo (+ 5 (* 3 i)) 16))) + (when (and (>= i 48) (<= i 63)) + (set! F1 (I BB CC DD)) + (set! g (modulo (* 7 i) 16))) + + (set! F1 (modulo (+ F1 AA (list-ref K i) (list-ref X g)) (expt 2 32))) + (set! AA DD) + (set! DD CC) + (set! CC BB) + (set! BB (modulo (+ BB (leftrotate F1 (list-ref s i))) (expt 2 32))) + + (set! i (1+ i))) + + (values (modulo (+ A AA) (expt 2 32)) + (modulo (+ B BB) (expt 2 32)) + (modulo (+ C CC) (expt 2 32)) + (modulo (+ D DD) (expt 2 32))))))) + +#! uncomment this block if guile complains about the unbound variable: format +;;module-required (ice-9 format) +;;usage -> format (procedure) md5sum (procedure) +;; +(use-modules (ice-9 format)) +!# + +;;procedure-name md5sum +;;input -> bv (bytevector) +;;output -> _ (string) +;; +(define md5sum + (lambda (bv) + (let ([A #x67452301] + [B #xEFCDAB89] + [C #x98BADCFE] + [D #x10325476] + [K '(#xd76aa478 #xe8c7b756 #x242070db #xc1bdceee #xf57c0faf #x4787c62a #xa8304613 #xfd469501 #x698098d8 #x8b44f7af #xffff5bb1 #x895cd7be #x6b901122 #xfd987193 #xa679438e #x49b40821 #xf61e2562 #xc040b340 #x265e5a51 #xe9b6c7aa #xd62f105d #x02441453 #xd8a1e681 #xe7d3fbc8 #x21e1cde6 #xc33707d6 #xf4d50d87 #x455a14ed #xa9e3e905 #xfcefa3f8 #x676f02d9 #x8d2a4c8a #xfffa3942 #x8771f681 #x6d9d6122 #xfde5380c #xa4beea44 #x4bdecfa9 #xf6bb4b60 #xbebfbc70 #x289b7ec6 #xeaa127fa #xd4ef3085 #x04881d05 #xd9d4d039 #xe6db99e5 #x1fa27cf8 #xc4ac5665 #xf4292244 #x432aff97 #xab9423a7 #xfc93a039 #x655b59c3 #x8f0ccc92 #xffeff47d #x85845dd1 #x6fa87e4f #xfe2ce6e0 #xa3014314 #x4e0811a1 #xf7537e82 #xbd3af235 #x2ad7d2bb #xeb86d391)] + [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)]) + (let* ([padded-bv (pad bv)] + [512bits-word-lists (listify padded-bv)] + [words-list-length (length 512bits-word-lists)]) + + (do ((index 0 (1+ index))) + ((>= index words-list-length)) + + (receive (A1 B1 C1 D1) (process-512bits (list-ref 512bits-word-lists index) A B C D K s) + (set! A A1) + (set! B B1) + (set! C C1) + (set! D D1))) + + (let ([bvA (uint-list->bytevector (list A) (endianness little) 4)] + [bvB (uint-list->bytevector (list B) (endianness little) 4)] + [bvC (uint-list->bytevector (list C) (endianness little) 4)] + [bvD (uint-list->bytevector (list D) (endianness little) 4)]) + (set! A (car (bytevector->uint-list bvA (endianness big) 4))) + (set! B (car (bytevector->uint-list bvB (endianness big) 4))) + (set! C (car (bytevector->uint-list bvC (endianness big) 4))) + (set! D (car (bytevector->uint-list bvD (endianness big) 4)))) + + (format #f "~8,'0x~8,'0x~8,'0x~8,'0x" A B C D))))) + +;;procedure-name test-suite +;;input -> <$:nil> +;;output -> _ (string) +;;note -> "this is the test function for the overall output" +;; +(define test-suite + (lambda () + (let ([standard '(("" . "d41d8cd98f00b204e9800998ecf8427e") + ("a" . "0cc175b9c0f1b6a831c399e269772661") + ("abc" . "900150983cd24fb0d6963f7d28e17f72") + ("message digest" . "f96b697d7cb7938d525a2f31aaf161d0") + ("abcdefghijklmnopqrstuvwxyz" . "c3fcd3d76192e4007dfb496cca67e13b") + ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" . "d174ab98d277d9f5a5611c2c9f419d9f") + ("12345678901234567890123456789012345678901234567890123456789012345678901234567890" . "57edf4a22be3c955ac49da2e2107b67a"))]) + (for-each (lambda (some-pair) + (display "Now checking: ") + (write some-pair) + (newline) + (let ([my-ans (md5sum (string->utf8 (car some-pair)))]) + (display "my answer is: ") + (display my-ans) + (newline) + (if (string=? my-ans (cdr some-pair)) + (begin (display "Pass! Next!") (newline)) + (raise-exception (make-exception-with-message "Failed!"))))) + standard)))) diff --git a/Task/MD5-Implementation/JavaScript/md5-implementation.js b/Task/MD5-Implementation/JavaScript/md5-implementation.js new file mode 100644 index 0000000000..5b20385092 --- /dev/null +++ b/Task/MD5-Implementation/JavaScript/md5-implementation.js @@ -0,0 +1,209 @@ +// MD5 Constants +const INITIAL_A = 0x67452301; +const INITIAL_B = 0xEFCDAB89; // No need for L suffix or static_cast +const INITIAL_C = 0x98BADCFE; // No need for L suffix or static_cast +const INITIAL_D = 0x10325476; + +const SHIFT_AMOUNTS = [ + 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 +]; + +// K constants (T table) - Sine values +const K = [ + 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, + 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, + 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, + 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, + 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, + 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, + 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, + 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, + 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, + 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, + 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, + 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, + 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, + 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, + 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, + 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391 +]; + +/** + * Left-rotate a 32-bit integer by a number of bits. + * @param {number} x - The integer to rotate. + * @param {number} n - The number of bits to rotate by. + * @returns {number} The rotated integer. + */ +function rotl(x, n) { + // Ensure x is treated as 32-bit for the shifts + return ((x << n) | (x >>> (32 - n))) | 0; +} + +/** + * Converts a Uint8Array (byte array) to a hexadecimal string. + * @param {Uint8Array} bytes - The byte array to convert. + * @returns {string} The hexadecimal string representation. + */ +function bytesToHexString(bytes) { + let hexString = ""; + for (const byte of bytes) { + hexString += byte.toString(16).padStart(2, '0'); + } + return hexString; +} + +/** + * Converts a string to a Uint8Array using UTF-8 encoding. + * @param {string} text - The string to convert. + * @returns {Uint8Array} The resulting byte array. + */ +function stringToBytes(text) { + return new TextEncoder().encode(text); +} + +/** + * Computes the MD5 hash of a byte array. + * @param {Uint8Array} message - The input message as a byte array. + * @returns {Uint8Array} The 16-byte MD5 hash. + */ +function computeMD5(message) { + const messageLengthBytes = message.length; + const messageLengthBits = BigInt(messageLengthBytes) * 8n; // Use BigInt for potentially large lengths + + // Calculate padding length + // Need (length + 1 + k) % 64 == 56 bytes (or 448 bits) + // So, length + 1 + k = 64n + 56 + // k = 64n + 56 - length - 1 + // Minimum k is when 64n is just >= length + 1 - 56 + 1 = length - 54 + // Padding length includes the 0x80 byte and the 8 length bytes. + // Total length must be multiple of 64 bytes (512 bits). + const numBlocks = Math.ceil((messageLengthBytes + 1 + 8) / 64); + const totalLength = numBlocks * 64; + const paddingLength = totalLength - messageLengthBytes; + + // Create padded message buffer + const paddedMessage = new Uint8Array(totalLength); + paddedMessage.set(message); // Copy original message + + // Append the '1' bit (0x80 byte) + paddedMessage[messageLengthBytes] = 0x80; + + // Append the 64-bit message length (little-endian) + // Note: JavaScript bitwise ops work on 32 bits. Handle 64-bit length carefully. + const lengthOffset = totalLength - 8; + for (let i = 0; i < 8; ++i) { + paddedMessage[lengthOffset + i] = Number((messageLengthBits >> (BigInt(i) * 8n)) & 0xFFn); + } + + // Initialize hash state variables (ensure they are 32-bit ints) + let a = INITIAL_A | 0; + let b = INITIAL_B | 0; + let c = INITIAL_C | 0; + let d = INITIAL_D | 0; + + const buffer = new Array(16); // Reusable buffer for 16 words (32-bit integers) + + // Process the message in 64-byte (512-bit) blocks + for (let i = 0; i < numBlocks; ++i) { + const blockOffset = i * 64; + + // Prepare the 16-word buffer from the current block (little-endian) + for (let j = 0; j < 16; ++j) { + const wordIndex = blockOffset + j * 4; + buffer[j] = ( + (paddedMessage[wordIndex]) | + (paddedMessage[wordIndex + 1] << 8) | + (paddedMessage[wordIndex + 2] << 16) | + (paddedMessage[wordIndex + 3] << 24) + ) | 0; // Ensure 32-bit integer + } + + // Save current hash state + let originalA = a; + let originalB = b; + let originalC = c; + let originalD = d; + + // Main loop (64 rounds) + for (let j = 0; j < 64; ++j) { + let f, bufferIndex; + const div16 = Math.floor(j / 16); + + switch (div16) { + case 0: // Round 1: F = (B & C) | (~B & D) + f = (b & c) | (~b & d); + bufferIndex = j; + break; + case 1: // Round 2: G = (B & D) | (C & ~D) + f = (b & d) | (c & ~d); + bufferIndex = (j * 5 + 1) % 16; + break; + case 2: // Round 3: H = B ^ C ^ D + f = b ^ c ^ d; + bufferIndex = (j * 3 + 5) % 16; + break; + case 3: // Round 4: I = C ^ (B | ~D) + f = c ^ (b | ~d); + bufferIndex = (j * 7) % 16; + break; + } + + // Ensure intermediate results are 32-bit + f = f | 0; + const term1 = a | 0; + const term2 = buffer[bufferIndex] | 0; + const term3 = K[j] | 0; + const shift = SHIFT_AMOUNTS[j]; // Use direct index j for SHIFT_AMOUNTS + + // Perform the round calculation: temp = B + rotl(A + F + M[g] + K[i], s) + let sum = (term1 + f + term2 + term3) | 0; + let rotatedSum = rotl(sum, shift); + let temp = (b + rotatedSum) | 0; + + // Update hash variables + a = d; + d = c; + c = b; + b = temp; + } + + // Add the original hash state back (with 32-bit wrap) + a = (a + originalA) | 0; + b = (b + originalB) | 0; + c = (c + originalC) | 0; + d = (d + originalD) | 0; + } + + // Construct final 16-byte hash (little-endian) + const md5Bytes = new Uint8Array(16); + let count = 0; + for (const word of [a, b, c, d]) { + for (let i = 0; i < 4; ++i) { + md5Bytes[count++] = (word >> (i * 8)) & 0xFF; + } + } + + return md5Bytes; +} + +// --- Main execution (equivalent to C++ main) --- +const tests = [ + "", + "a", + "abc", + "message digest", + "abcdefghijklmnopqrstuvwxyz", + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", + "12345678901234567890123456789012345678901234567890123456789012345678901234567890" +]; + +console.log("MD5 Hashes:"); +for (const test of tests) { + const messageBytes = stringToBytes(test); + const hashBytes = computeMD5(messageBytes); + const hexHash = bytesToHexString(hashBytes); + console.log(`${hexHash} <== "${test}"`); +} diff --git a/Task/MD5-Implementation/Julia/md5-implementation.julia b/Task/MD5-Implementation/Julia/md5-implementation.jl similarity index 100% rename from Task/MD5-Implementation/Julia/md5-implementation.julia rename to Task/MD5-Implementation/Julia/md5-implementation.jl diff --git a/Task/MD5-Implementation/Kotlin/md5-implementation.kotlin b/Task/MD5-Implementation/Kotlin/md5-implementation.kts similarity index 100% rename from Task/MD5-Implementation/Kotlin/md5-implementation.kotlin rename to Task/MD5-Implementation/Kotlin/md5-implementation.kts diff --git a/Task/MD5-Implementation/Phix/md5-implementation.phix b/Task/MD5-Implementation/Phix/md5-implementation.phix index 0f34175ae8..63a2c90bdf 100644 --- a/Task/MD5-Implementation/Phix/md5-implementation.phix +++ b/Task/MD5-Implementation/Phix/md5-implementation.phix @@ -1,152 +1,150 @@ -(phixonline)--> - -- demo\rosetta\md5.exw - with javascript_semantics - function uxor(atom data1,atom data2) - atom result = xor_bits(data1,data2) - if result<0 then result += #100000000 end if - return result - end function +-- demo\rosetta\md5.exw +with javascript_semantics +function uxor(atom data1,atom data2) +atom result = xor_bits(data1,data2) + if result<0 then result += #100000000 end if + return result +end function - function uor(atom data1,atom data2) - atom result = or_bits(data1,data2) - if result<0 then result += #100000000 end if - return result - end function +function uor(atom data1,atom data2) +atom result = or_bits(data1,data2) + if result<0 then result += #100000000 end if + return result +end function - function r32(atom a) - return remainder(a,#100000000) - end function +function r32(atom a) + return remainder(a,#100000000) +end function - function rol(atom word,integer bits) - -- left rotate the bits of a 32-bit number by the specified number of bits - return r32(word*power(2,bits))+floor(word/power(2,32-bits)) - end function +function rol(atom word,integer bits) +-- left rotate the bits of a 32-bit number by the specified number of bits + return r32(word*power(2,bits))+floor(word/power(2,32-bits)) +end function - constant K = - {#d76aa478, #e8c7b756, #242070db, #c1bdceee, #f57c0faf, #4787c62a, #a8304613, #fd469501, - #698098d8, #8b44f7af, #ffff5bb1, #895cd7be, #6b901122, #fd987193, #a679438e, #49b40821, - #f61e2562, #c040b340, #265e5a51, #e9b6c7aa, #d62f105d, #02441453, #d8a1e681, #e7d3fbc8, - #21e1cde6, #c33707d6, #f4d50d87, #455a14ed, #a9e3e905, #fcefa3f8, #676f02d9, #8d2a4c8a, - #fffa3942, #8771f681, #6d9d6122, #fde5380c, #a4beea44, #4bdecfa9, #f6bb4b60, #bebfbc70, - #289b7ec6, #eaa127fa, #d4ef3085, #04881d05, #d9d4d039, #e6db99e5, #1fa27cf8, #c4ac5665, - #f4292244, #432aff97, #ab9423a7, #fc93a039, #655b59c3, #8f0ccc92, #ffeff47d, #85845dd1, - #6fa87e4f, #fe2ce6e0, #a3014314, #4e0811a1, #f7537e82, #bd3af235, #2ad7d2bb, #eb86d391} +constant K = +{#d76aa478, #e8c7b756, #242070db, #c1bdceee, #f57c0faf, #4787c62a, #a8304613, #fd469501, + #698098d8, #8b44f7af, #ffff5bb1, #895cd7be, #6b901122, #fd987193, #a679438e, #49b40821, + #f61e2562, #c040b340, #265e5a51, #e9b6c7aa, #d62f105d, #02441453, #d8a1e681, #e7d3fbc8, + #21e1cde6, #c33707d6, #f4d50d87, #455a14ed, #a9e3e905, #fcefa3f8, #676f02d9, #8d2a4c8a, + #fffa3942, #8771f681, #6d9d6122, #fde5380c, #a4beea44, #4bdecfa9, #f6bb4b60, #bebfbc70, + #289b7ec6, #eaa127fa, #d4ef3085, #04881d05, #d9d4d039, #e6db99e5, #1fa27cf8, #c4ac5665, + #f4292244, #432aff97, #ab9423a7, #fc93a039, #655b59c3, #8f0ccc92, #ffeff47d, #85845dd1, + #6fa87e4f, #fe2ce6e0, #a3014314, #4e0811a1, #f7537e82, #bd3af235, #2ad7d2bb, #eb86d391} - constant m_block = {1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,16, - 2, 7,12, 1, 6,11,16, 5,10,15, 4, 9,14, 3, 8,13, - 6, 9,12,15, 2, 5, 8,11,14, 1, 4, 7,10,13,16, 3, - 1, 8,15, 6,13, 4,11, 2, 9,16, 7,14, 5,12, 3,10} +constant m_block = {1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,16, + 2, 7,12, 1, 6,11,16, 5,10,15, 4, 9,14, 3, 8,13, + 6, 9,12,15, 2, 5, 8,11,14, 1, 4, 7,10,13,16, 3, + 1, 8,15, 6,13, 4,11, 2, 9,16, 7,14, 5,12, 3,10} - constant c_words = {#67452301,#efcdab89,#98badcfe,#10325476} +constant c_words = {#67452301,#efcdab89,#98badcfe,#10325476} - sequence words +sequence words - function divide_in_words(sequence message) - -- Divides the string into words (32-bit numbers) - integer l = floor(length(message)/4) - sequence res = repeat(0,l) - for word=1 to l do - res[word] = bytes_to_int(message[word*4-3..word*4]) - end for - return res - end function +function divide_in_words(sequence message) +-- Divides the string into words (32-bit numbers) + integer l = floor(length(message)/4) + sequence res = repeat(0,l) + for word=1 to l do + res[word] = bytes_to_int(message[word*4-3..word*4]) + end for + return res +end function - procedure process_block(sequence block) - -- Updates the words according to the contents of the block - atom a,b,c,d +procedure process_block(sequence block) +-- Updates the words according to the contents of the block +atom a,b,c,d - block = divide_in_words(block) + block = divide_in_words(block) - a = words[1] - b = words[2] - c = words[3] - d = words[4] + a = words[1] + b = words[2] + c = words[3] + d = words[4] - -- Round 1 - for step=1 to 16 by 4 do - a = r32(b+rol(r32(a+block[m_block[step ]]+K[step ]+uor(and_bits(b,c),and_bits(not_bits(b),d))), 7)) - d = r32(a+rol(r32(d+block[m_block[step+1]]+K[step+1]+uor(and_bits(a,b),and_bits(not_bits(a),c))),12)) - c = r32(d+rol(r32(c+block[m_block[step+2]]+K[step+2]+uor(and_bits(d,a),and_bits(not_bits(d),b))),17)) - b = r32(c+rol(r32(b+block[m_block[step+3]]+K[step+3]+uor(and_bits(c,d),and_bits(not_bits(c),a))),22)) - end for + -- Round 1 + for step=1 to 16 by 4 do + a = r32(b+rol(r32(a+block[m_block[step ]]+K[step ]+uor(and_bits(b,c),and_bits(not_bits(b),d))), 7)) + d = r32(a+rol(r32(d+block[m_block[step+1]]+K[step+1]+uor(and_bits(a,b),and_bits(not_bits(a),c))),12)) + c = r32(d+rol(r32(c+block[m_block[step+2]]+K[step+2]+uor(and_bits(d,a),and_bits(not_bits(d),b))),17)) + b = r32(c+rol(r32(b+block[m_block[step+3]]+K[step+3]+uor(and_bits(c,d),and_bits(not_bits(c),a))),22)) + end for - -- Round 2 - for step=17 to 32 by 4 do - a = r32(b+rol(r32(a+block[m_block[step ]]+K[step ]+uor(and_bits(b,d),and_bits(c,not_bits(d)))), 5)) - d = r32(a+rol(r32(d+block[m_block[step+1]]+K[step+1]+uor(and_bits(a,c),and_bits(b,not_bits(c)))), 9)) - c = r32(d+rol(r32(c+block[m_block[step+2]]+K[step+2]+uor(and_bits(d,b),and_bits(a,not_bits(b)))),14)) - b = r32(c+rol(r32(b+block[m_block[step+3]]+K[step+3]+uor(and_bits(c,a),and_bits(d,not_bits(a)))),20)) - end for + -- Round 2 + for step=17 to 32 by 4 do + a = r32(b+rol(r32(a+block[m_block[step ]]+K[step ]+uor(and_bits(b,d),and_bits(c,not_bits(d)))), 5)) + d = r32(a+rol(r32(d+block[m_block[step+1]]+K[step+1]+uor(and_bits(a,c),and_bits(b,not_bits(c)))), 9)) + c = r32(d+rol(r32(c+block[m_block[step+2]]+K[step+2]+uor(and_bits(d,b),and_bits(a,not_bits(b)))),14)) + b = r32(c+rol(r32(b+block[m_block[step+3]]+K[step+3]+uor(and_bits(c,a),and_bits(d,not_bits(a)))),20)) + end for - -- Round 3 - for step=33 to 48 by 4 do - a = r32(b+rol(r32(a+block[m_block[step ]]+K[step ]+uxor(b,xor_bits(c,d))), 4)) - d = r32(a+rol(r32(d+block[m_block[step+1]]+K[step+1]+uxor(a,xor_bits(b,c))),11)) - c = r32(d+rol(r32(c+block[m_block[step+2]]+K[step+2]+uxor(d,xor_bits(a,b))),16)) - b = r32(c+rol(r32(b+block[m_block[step+3]]+K[step+3]+uxor(c,xor_bits(d,a))),23)) - end for + -- Round 3 + for step=33 to 48 by 4 do + a = r32(b+rol(r32(a+block[m_block[step ]]+K[step ]+uxor(b,xor_bits(c,d))), 4)) + d = r32(a+rol(r32(d+block[m_block[step+1]]+K[step+1]+uxor(a,xor_bits(b,c))),11)) + c = r32(d+rol(r32(c+block[m_block[step+2]]+K[step+2]+uxor(d,xor_bits(a,b))),16)) + b = r32(c+rol(r32(b+block[m_block[step+3]]+K[step+3]+uxor(c,xor_bits(d,a))),23)) + end for - -- Round 4 - for step=49 to 64 by 4 do - a = r32(b+rol(r32(a+block[m_block[step ]]+K[step ]+uxor(c,or_bits(b,not_bits(d)))), 6)) - d = r32(a+rol(r32(d+block[m_block[step+1]]+K[step+1]+uxor(b,or_bits(a,not_bits(c)))),10)) - c = r32(d+rol(r32(c+block[m_block[step+2]]+K[step+2]+uxor(a,or_bits(d,not_bits(b)))),15)) - b = r32(c+rol(r32(b+block[m_block[step+3]]+K[step+3]+uxor(d,or_bits(c,not_bits(a)))),21)) - end for + -- Round 4 + for step=49 to 64 by 4 do + a = r32(b+rol(r32(a+block[m_block[step ]]+K[step ]+uxor(c,or_bits(b,not_bits(d)))), 6)) + d = r32(a+rol(r32(d+block[m_block[step+1]]+K[step+1]+uxor(b,or_bits(a,not_bits(c)))),10)) + c = r32(d+rol(r32(c+block[m_block[step+2]]+K[step+2]+uxor(a,or_bits(d,not_bits(b)))),15)) + b = r32(c+rol(r32(b+block[m_block[step+3]]+K[step+3]+uxor(d,or_bits(c,not_bits(a)))),21)) + end for - -- Update the words - words = deep_copy(words) - words[1] = r32(words[1]+a) - words[2] = r32(words[2]+b) - words[3] = r32(words[3]+c) - words[4] = r32(words[4]+d) - end procedure + -- Update the words + words = deep_copy(words) + words[1] = r32(words[1]+a) + words[2] = r32(words[2]+b) + words[3] = r32(words[3]+c) + words[4] = r32(words[4]+d) +end procedure - function pad_message(sequence message) - -- Add bytes to the end of the message so it can be divided - -- in an exact number of 64-byte blocks. - integer l = length(message), - bytes_to_add = 64-remainder(l+9,64) - if bytes_to_add=64 then bytes_to_add = 0 end if +function pad_message(sequence message) +-- Add bytes to the end of the message so it can be divided +-- in an exact number of 64-byte blocks. + integer l = length(message), + bytes_to_add = 64-remainder(l+9,64) + if bytes_to_add=64 then bytes_to_add = 0 end if - message = deep_copy(message) - message &= #80 - message &= repeat(0,bytes_to_add) - message &= int_to_bytes(l*8)&{0,0,0,0} + message = deep_copy(message) + message &= #80 + message &= repeat(0,bytes_to_add) + message &= int_to_bytes(l*8)&{0,0,0,0} - return message - end function + return message +end function - global function md5(sequence message) - -- Given a string, returns a 16-byte hash of it. +global function md5(sequence message) +-- Given a string, returns a 16-byte hash of it. - words = c_words -- Initialize the H words + words = c_words -- Initialize the H words - message = pad_message(message) -- Add bytes to the message + message = pad_message(message) -- Add bytes to the message - -- Process each 64-byte block - for block=1 to length(message) by 64 do - process_block(message[block..block+63]) - end for + -- Process each 64-byte block + for block=1 to length(message) by 64 do + process_block(message[block..block+63]) + end for - -- Convert hash into bytes - return int_to_bytes(words[1])& -- Return the hash - int_to_bytes(words[2])& - int_to_bytes(words[3])& - int_to_bytes(words[4]) + -- Convert hash into bytes + return int_to_bytes(words[1])& -- Return the hash + int_to_bytes(words[2])& + int_to_bytes(words[3])& + int_to_bytes(words[4]) - end function +end function - if platform()=JS or include_file()=1 then - string fmt = "0x%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X\n" +if platform()=JS or include_file()=1 then + string fmt = "0x%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X\n" - printf(1,fmt,md5("")) - printf(1,fmt,md5("a")) - printf(1,fmt,md5("abc")) - printf(1,fmt,md5("message digest")) - printf(1,fmt,md5("abcdefghijklmnopqrstuvwxyz")) - printf(1,fmt,md5("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")) - printf(1,fmt,md5("12345678901234567890123456789012345678901234567890123456789012345678901234567890")) - end if - - atom mem = allocate(9) - poke(mem,{#8B,#44,#24,#04,#03,#44,#24,#08,#C3}) - constant mfunc = define_c_func({},mem,{C_INT,C_INT},C_INT) - ?c_func(mfunc,{12,7}) - free(mem) - - atom mem = allocate(9) - poke(mem,{#8B,#44,#24,#04,#03,#44,#24,#08,#C3}) - integer res - #ilASM{ mov eax,[mem] - call :%pLoadMint -- eax:=(int32)eax, in case mem>#3FFFFFFF - push 12 - push 7 - call eax - add esp,8 - mov [res],eax } - ?res - free(mem) - - integer res - #ilASM{ jmp @f - ::add - [32] - mov eax,[esp+4] - add eax,[esp+8] - [64] - mov rax,[rsp+8] - add rax,[rsp+16] - [] - ret - @@: - push 12 - push 7 - call :add - [32] - add esp,8 - mov [res],eax - [64] - add rsp,16 - mov [res],rax - [] - } - ?res - - integer res - #ilASM{ - [32] - mov eax,12 - mov edx,7 - add eax,edx - mov [res],eax - [64] - mov rax,12 - mov rdx,7 - add rax,rdx - mov [res],rax - [] - } - ?res - - with javascript_semantics +with javascript_semantics - function magic(integer nth) - integer order = nth+2 - return (order*order+1)/2 * order - end function - printf(1,"First 20 magic constants: %V\n",{apply(tagset(20),magic)}) - printf(1,"1000th magic constant: %,d\n",{magic(1000)}) +function magic(integer nth) + integer order = nth+2 + return (order*order+1)/2 * order +end function +printf(1,"First 20 magic constants: %V\n",{apply(tagset(20),magic)}) +printf(1,"1000th magic constant: %,d\n",{magic(1000)}) - include mpfr.e +include mpfr.e - mpz {goal, order} = mpz_inits(2) - for i=1 to 20 do - mpz_ui_pow_ui(goal,10,i) - mpz_mul_si(order,goal,2) - mpz_nthroot(order,order,3) - mpz_add_si(order,order,1) - printf(1,"1e%d: %s\n",{i,mpz_get_str(order,10,true)}) - end for - - without js -- allocate() - forward function A(integer k, object x1, x2, x3, x4, x5) +without js -- allocate() +forward function A(integer k, object x1, x2, x3, x4, x5) - function B(sequence s) - object {kptr,x1,x2,x3,x4} = s - integer k = peek4s(kptr)-1 - poke4(kptr,k) - return A(k,{kptr,x1,x2,x3,x4},x1,x2,x3,x4) - end function +function B(sequence s) + object {kptr,x1,x2,x3,x4} = s + integer k = peek4s(kptr)-1 + poke4(kptr,k) + return A(k,{kptr,x1,x2,x3,x4},x1,x2,x3,x4) +end function - function A(integer k, object x1, x2, x3, x4, x5) - if k<=0 then - return iff(sequence(x4)?B(x4):x4)+ - iff(sequence(x5)?B(x5):x5) - end if - atom kptr = allocate(4,1) - poke4(kptr,k) - return B({kptr,x1,x2,x3,x4}) - end function +function A(integer k, object x1, x2, x3, x4, x5) + if k<=0 then + return iff(sequence(x4)?B(x4):x4)+ + iff(sequence(x5)?B(x5):x5) + end if + atom kptr = allocate(4,1) + poke4(kptr,k) + return B({kptr,x1,x2,x3,x4}) +end function - for k=0 to 23 do - printf(1,"A(%d) = %d\n",{k,A(k,1,-1,-1,1,0)}) - end for - - with javascript_semantics - constant first5 = {1,0,-2,0,1} - function A(integer k) - if k<5 then return first5[k+1] end if - atom c0 = 3, c1 = 2, c2 = 1, c3 = 0 - for j=5 to k-1 do - c3 += c0-1 - c0 += c1 - c1 += c2 - c2 += c3 - end for - return c0-c1-c2+c3 - end function +with javascript_semantics +constant first5 = {1,0,-2,0,1} +function A(integer k) + if k<5 then return first5[k+1] end if + atom c0 = 3, c1 = 2, c2 = 1, c3 = 0 + for j=5 to k-1 do + c3 += c0-1 + c0 += c1 + c1 += c2 + c2 += c3 + end for + return c0-c1-c2+c3 +end function - for k=0 to 40 do - printf(1,"%d %d\n",{k,A(k)}) - end for - - with javascript_semantics - include mpfr.e - function A(integer k) - if k<5 then return mpz_init({1,0,-2,0,1}[k+1]) end if - mpz c0 = mpz_init(3), - c1 = mpz_init(2), - c2 = mpz_init(1), - c3 = mpz_init(0) - for j=5 to k-1 do - mpz_add(c3,c3,c0) - mpz_sub_ui(c3,c3,1) - mpz_add(c0,c0,c1) - mpz_add(c1,c1,c2) - mpz_add(c2,c2,c3) - end for - mpz_sub(c0,c0,c1) - mpz_sub(c0,c0,c2) - mpz_add(c0,c0,c3) - return c0 - end function +with javascript_semantics +include mpfr.e +function A(integer k) + if k<5 then return mpz_init({1,0,-2,0,1}[k+1]) end if + mpz c0 = mpz_init(3), + c1 = mpz_init(2), + c2 = mpz_init(1), + c3 = mpz_init(0) + for j=5 to k-1 do + mpz_add(c3,c3,c0) + mpz_sub_ui(c3,c3,1) + mpz_add(c0,c0,c1) + mpz_add(c1,c1,c2) + mpz_add(c2,c2,c3) + end for + mpz_sub(c0,c0,c1) + mpz_sub(c0,c0,c2) + mpz_add(c0,c0,c3) + return c0 +end function - constant tests = tagset(20,0)&{30,39,500,10000,1e6} - for k=1 to length(tests)-(platform()=JS) do - printf(1,"A(%,d) = %s\n", {tests[k],mpz_get_short_str(A(tests[k]))}) - end for - lists of lists of strings (each line of tile) - m.toString(20).pump(List,fcn(m){ // 4,005 --> "a05" - bars,dots := m.toInt(20).divr(5); // "a" --> 10 --> (2,0) + m.toString(20).pump(List,fcn(m){ // 4,005 --> "a05" + bars,dots := m.toInt(20).divr(5); // "a" --> 10 --> (2,0) if(0==bars==dots) return(String(fill*3, zero).split("\n")); // 0 String(fill*(3-bars), ds[dots],"\n", five*bars)[0,-1].split("\n") // tile }) diff --git a/Task/Mayan-numerals/Zkl/mayan-numerals-4.zkl b/Task/Mayan-numerals/Zkl/mayan-numerals-4.zkl index b9c1b37df7..b7ec1216f0 100644 --- a/Task/Mayan-numerals/Zkl/mayan-numerals-4.zkl +++ b/Task/Mayan-numerals/Zkl/mayan-numerals-4.zkl @@ -14,9 +14,9 @@ fcn display(num,digits){ T(88637341,26960840421).apply( fcn(m){ mayan(m).pump(String, - fcn([(bars,dots)]){ - (if(bars or dots) (dot*dots + "!" + bar*bars)[0,-1] else zero) - + " " - }).replace("!","
    ") : display(m,_) + fcn([(bars,dots)]){ + (if(bars or dots) (dot*dots + "!" + bar*bars)[0,-1] else zero) + + " " + }).replace("!","
    ") : display(m,_) }) .concat("\n
    \n").println(); diff --git a/Task/Maze-generation/11l/maze-generation.11l b/Task/Maze-generation/11l/maze-generation.11l index b9c8f0c56d..3364852bb2 100644 --- a/Task/Maze-generation/11l/maze-generation.11l +++ b/Task/Maze-generation/11l/maze-generation.11l @@ -3,7 +3,7 @@ F make_maze(w = 16, h = 8) V ver = [[‘| ’] * w [+] [String(‘|’)]] * h [+] [[String]()] V hor = [[‘+--’] * w [+] [String(‘+’)]] * (h + 1) - F walk(Int x, Int y) -> N + F walk(Int x, Int y) -> Void @vis[y][x] = 1 V d = [(x - 1, y), (x, y + 1), (x + 1, y), (x, y - 1)] random:shuffle(&d) diff --git a/Task/Maze-generation/Ada/maze-generation-1.ada b/Task/Maze-generation/Ada/maze-generation-1.adb similarity index 100% rename from Task/Maze-generation/Ada/maze-generation-1.ada rename to Task/Maze-generation/Ada/maze-generation-1.adb diff --git a/Task/Maze-generation/Ada/maze-generation-2.ada b/Task/Maze-generation/Ada/maze-generation-2.adb similarity index 100% rename from Task/Maze-generation/Ada/maze-generation-2.ada rename to Task/Maze-generation/Ada/maze-generation-2.adb diff --git a/Task/Maze-generation/Ada/maze-generation-3.ada b/Task/Maze-generation/Ada/maze-generation-3.adb similarity index 100% rename from Task/Maze-generation/Ada/maze-generation-3.ada rename to Task/Maze-generation/Ada/maze-generation-3.adb diff --git a/Task/Maze-generation/AutoHotkey/maze-generation.ahk b/Task/Maze-generation/AutoHotkey/maze-generation.ahk index 1ba22596d2..35e23e6261 100644 --- a/Task/Maze-generation/AutoHotkey/maze-generation.ahk +++ b/Task/Maze-generation/AutoHotkey/maze-generation.ahk @@ -1,65 +1,65 @@ ; Initially build the board -Width := 11 -Height := 8 +Width := 11 +Height := 8 Loop % height*2+1 { - Outer := A_Index - Loop % Width - maze .= Outer & 1 ? "+-" : "|0" - maze .= (Outer & 1 ? "+" : "|") "`n" + Outer := A_Index + Loop % Width + maze .= Outer & 1 ? "+-" : "|0" + maze .= (Outer & 1 ? "+" : "|") "`n" } StringTrimRight, maze, maze, 1 ; removes trailing newline Clipboard := Walk(maze) Walk(S, x=0, y=0){ - If !x{ ; --Start at a random cell... - StringReplace, junk, S, `n,,UseErrorLevel ; Calculate rows - Random, y, 1, ErrorLevel//2 - Random, x, 1, InStr(S, "`n")//2-1 ; Calculate height - } - - ; --Obtain a list of its neighbors... - neighbors := x "," y+1 "`n" x "," y-1 "`n" x+1 "," y "`n" x-1 "," y - ; --Randomize the list... - Sort neighbors, random - - ; --Then for each neighbor... - Loop Parse, neighbors, `n - { - pC := InStr(A_LoopField, ","), x2 := SubStr(A_LoopField, 1, pC-1), y2 := SubStr(A_LoopField, pC+1) - ; If it has not been visited... - If GetChar(S, 2*x2, 2*y2) = "0"{ - ; Mark it as visited... - S := ChangeChar(s, 2*x2, 2*y2, " ") - ; Remove the wall between this cell and the neighbor... - S := ChangeChar(S, x+x2, y+y2, " ") - ; Then recurse with the neighbor as the current cell - S := Walk(S, x2, y2) - } - } - return S + If !x{ ; --Start at a random cell... + StringReplace, junk, S, `n,,UseErrorLevel ; Calculate rows + Random, y, 1, ErrorLevel//2 + Random, x, 1, InStr(S, "`n")//2-1 ; Calculate height + } + + ; --Obtain a list of its neighbors... + neighbors := x "," y+1 "`n" x "," y-1 "`n" x+1 "," y "`n" x-1 "," y + ; --Randomize the list... + Sort neighbors, random + + ; --Then for each neighbor... + Loop Parse, neighbors, `n + { + pC := InStr(A_LoopField, ","), x2 := SubStr(A_LoopField, 1, pC-1), y2 := SubStr(A_LoopField, pC+1) + ; If it has not been visited... + If GetChar(S, 2*x2, 2*y2) = "0"{ + ; Mark it as visited... + S := ChangeChar(s, 2*x2, 2*y2, " ") + ; Remove the wall between this cell and the neighbor... + S := ChangeChar(S, x+x2, y+y2, " ") + ; Then recurse with the neighbor as the current cell + S := Walk(S, x2, y2) + } + } + return S } - + ; Change a character in a string using x and y coordinates ChangeChar(s, x, y, c){ - Loop Parse, s, `n - { - If (A_Index = Y) - Loop Parse, A_LoopField - If (A_Index = x) - out .= c - Else out .= A_LoopField - Else out .= A_LoopField - out .= "`n" - } - StringTrimRight, out, out, 1 - return out + Loop Parse, s, `n + { + If (A_Index = Y) + Loop Parse, A_LoopField + If (A_Index = x) + out .= c + Else out .= A_LoopField + Else out .= A_LoopField + out .= "`n" + } + StringTrimRight, out, out, 1 + return out } ; retrieve a character in a string using x and y coordinates GetChar(s, x, y, n=1){ - x*=n, y*=n - Loop Parse, s, `n - If (A_Index = Y) - return SubStr(A_LoopField, x, 1) + x*=n, y*=n + Loop Parse, s, `n + If (A_Index = Y) + return SubStr(A_LoopField, x, 1) } diff --git a/Task/Maze-generation/Batch-File/maze-generation.bat b/Task/Maze-generation/Batch-File/maze-generation.bat index ffa1b7ae7b..22b16779d4 100644 --- a/Task/Maze-generation/Batch-File/maze-generation.bat +++ b/Task/Maze-generation/Batch-File/maze-generation.bat @@ -47,37 +47,37 @@ SET mz=!mz:~0,%curPos%!!hall!!mz:~%cTmp%! :: iterate #cells*2+1 steps of random depth-first search FOR /L %%@ IN (1,1,%loops%) DO ( - SET "rand=" & SET "crmPos=" - REM set values for NSEW cell and wall positions - SET /A "rCnt=rTmp=0, cTmp=curPos+1, np=curPos+N, sp=curPos+S, ep=curPos+E, wp=curPos+W, wChk=curPos/wide*wide, eChk=wChk+wide, nw=curPos-wide, sw=curPos+wide, ew=curPos+1, ww=curPos-1" - REM examine adjacent cells, build direction list, and find last crumb position - FOR /F "tokens=1-8" %%A IN ("!np! !sp! !ep! !wp! !nw! !sw! !ew! !ww!") DO ( - IF !np! GEQ 0 IF "!mz:~%%A,1!" EQU "!wall!" ( SET /A rCnt+=1 & SET "rand=n !rand!" - ) ELSE IF "!mz:~%%E,1!" EQU "!crumb!" SET /A crmPos=np, cw=nw - IF !sp! LEQ !size! IF "!mz:~%%B,1!" EQU "!wall!" ( SET /A rCnt+=1 & SET "rand=s !rand!" - ) ELSE IF "!mz:~%%F,1!" EQU "!crumb!" SET /A crmPos=sp, cw=sw - IF !ep! LEQ !eChk! IF "!mz:~%%C,1!" EQU "!wall!" ( SET /A rCnt+=1 & SET "rand=e !rand!" - ) ELSE IF "!mz:~%%G,1!" EQU "!crumb!" SET /A crmPos=ep, cw=ew - IF !wp! GEQ !wChk! IF "!mz:~%%D,1!" EQU "!wall!" ( SET /A rCnt+=1 & SET "rand=w !rand!" - ) ELSE IF "!mz:~%%H,1!" EQU "!crumb!" SET /A crmPos=wp, cw=ww - ) - IF DEFINED rand ( REM adjacent unvisited cell is available - SET /A rCnt=!RANDOM! %% rCnt - FOR %%A IN (!rand!) DO ( REM pick random cell + wall - IF !rTmp! EQU !rCnt! SET /A "curPos=!%%Ap!, cTmp=curPos+1, mw=!%%Aw!, mTmp=mw+1" - SET /A rTmp+=1 - ) - REM write the 2 new characters into the maze - FOR /F "tokens=1-4" %%A IN ("!mw! !mTmp! !curPos! !cTmp!") DO ( - SET "mz=!mz:~0,%%A!!crumb!!mz:~%%B!" - SET "mz=!mz:~0,%%C!!hall!!mz:~%%D!" - ) - ) ELSE IF DEFINED crmPos ( REM follow the crumbs backward - SET /A mTmp=cw+1 - REM erase the crumb character and set new cursor position - FOR /F "tokens=1-2" %%A IN ("!cw! !mTmp!") DO SET "mz=!mz:~0,%%A!!hall!!mz:~%%B!" - SET "curPos=!crmPos!" - ) + SET "rand=" & SET "crmPos=" + REM set values for NSEW cell and wall positions + SET /A "rCnt=rTmp=0, cTmp=curPos+1, np=curPos+N, sp=curPos+S, ep=curPos+E, wp=curPos+W, wChk=curPos/wide*wide, eChk=wChk+wide, nw=curPos-wide, sw=curPos+wide, ew=curPos+1, ww=curPos-1" + REM examine adjacent cells, build direction list, and find last crumb position + FOR /F "tokens=1-8" %%A IN ("!np! !sp! !ep! !wp! !nw! !sw! !ew! !ww!") DO ( + IF !np! GEQ 0 IF "!mz:~%%A,1!" EQU "!wall!" ( SET /A rCnt+=1 & SET "rand=n !rand!" + ) ELSE IF "!mz:~%%E,1!" EQU "!crumb!" SET /A crmPos=np, cw=nw + IF !sp! LEQ !size! IF "!mz:~%%B,1!" EQU "!wall!" ( SET /A rCnt+=1 & SET "rand=s !rand!" + ) ELSE IF "!mz:~%%F,1!" EQU "!crumb!" SET /A crmPos=sp, cw=sw + IF !ep! LEQ !eChk! IF "!mz:~%%C,1!" EQU "!wall!" ( SET /A rCnt+=1 & SET "rand=e !rand!" + ) ELSE IF "!mz:~%%G,1!" EQU "!crumb!" SET /A crmPos=ep, cw=ew + IF !wp! GEQ !wChk! IF "!mz:~%%D,1!" EQU "!wall!" ( SET /A rCnt+=1 & SET "rand=w !rand!" + ) ELSE IF "!mz:~%%H,1!" EQU "!crumb!" SET /A crmPos=wp, cw=ww + ) + IF DEFINED rand ( REM adjacent unvisited cell is available + SET /A rCnt=!RANDOM! %% rCnt + FOR %%A IN (!rand!) DO ( REM pick random cell + wall + IF !rTmp! EQU !rCnt! SET /A "curPos=!%%Ap!, cTmp=curPos+1, mw=!%%Aw!, mTmp=mw+1" + SET /A rTmp+=1 + ) + REM write the 2 new characters into the maze + FOR /F "tokens=1-4" %%A IN ("!mw! !mTmp! !curPos! !cTmp!") DO ( + SET "mz=!mz:~0,%%A!!crumb!!mz:~%%B!" + SET "mz=!mz:~0,%%C!!hall!!mz:~%%D!" + ) + ) ELSE IF DEFINED crmPos ( REM follow the crumbs backward + SET /A mTmp=cw+1 + REM erase the crumb character and set new cursor position + FOR /F "tokens=1-2" %%A IN ("!cw! !mTmp!") DO SET "mz=!mz:~0,%%A!!hall!!mz:~%%B!" + SET "curPos=!crmPos!" + ) ) SET /A open=cols/2*2, mTmp=open+1 ECHO !wall!!bdr:~0,%open%!!hall!!bdr:~%mTmp%!!wall! diff --git a/Task/Maze-generation/C++/maze-generation.cpp b/Task/Maze-generation/C++/maze-generation.cpp index ff0d50420e..53f3113c83 100644 --- a/Task/Maze-generation/C++/maze-generation.cpp +++ b/Task/Maze-generation/C++/maze-generation.cpp @@ -18,81 +18,81 @@ public: myBitmap() : pen( NULL ) {} ~myBitmap() { - DeleteObject( pen ); - DeleteDC( hdc ); - DeleteObject( bmp ); + DeleteObject( pen ); + DeleteDC( hdc ); + DeleteObject( bmp ); } bool create( int w, int h ) { - BITMAPINFO bi; - ZeroMemory( &bi, sizeof( bi ) ); - bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); - bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; - bi.bmiHeader.biCompression = BI_RGB; - bi.bmiHeader.biPlanes = 1; - bi.bmiHeader.biWidth = w; - bi.bmiHeader.biHeight = -h; + BITMAPINFO bi; + ZeroMemory( &bi, sizeof( bi ) ); + bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); + bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; + bi.bmiHeader.biCompression = BI_RGB; + bi.bmiHeader.biPlanes = 1; + bi.bmiHeader.biWidth = w; + bi.bmiHeader.biHeight = -h; - HDC dc = GetDC( GetConsoleWindow() ); - bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); - if( !bmp ) return false; + HDC dc = GetDC( GetConsoleWindow() ); + bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); + if( !bmp ) return false; - hdc = CreateCompatibleDC( dc ); - SelectObject( hdc, bmp ); - ReleaseDC( GetConsoleWindow(), dc ); - width = w; height = h; + hdc = CreateCompatibleDC( dc ); + SelectObject( hdc, bmp ); + ReleaseDC( GetConsoleWindow(), dc ); + width = w; height = h; - return true; + return true; } void clear() { - ZeroMemory( pBits, width * height * sizeof( DWORD ) ); + ZeroMemory( pBits, width * height * sizeof( DWORD ) ); } void setPenColor( DWORD clr ) { - if( pen ) DeleteObject( pen ); - pen = CreatePen( PS_SOLID, 1, clr ); - SelectObject( hdc, pen ); + if( pen ) DeleteObject( pen ); + pen = CreatePen( PS_SOLID, 1, clr ); + SelectObject( hdc, pen ); } void saveBitmap( string path ) { - BITMAPFILEHEADER fileheader; - BITMAPINFO infoheader; - BITMAP bitmap; - DWORD wb; + BITMAPFILEHEADER fileheader; + BITMAPINFO infoheader; + BITMAP bitmap; + DWORD wb; - GetObject( bmp, sizeof( bitmap ), &bitmap ); + GetObject( bmp, sizeof( bitmap ), &bitmap ); - DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; - ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); - ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); - ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) ); + DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; + ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) ); + ZeroMemory( &infoheader, sizeof( BITMAPINFO ) ); + ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) ); - infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; - infoheader.bmiHeader.biCompression = BI_RGB; - infoheader.bmiHeader.biPlanes = 1; - infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); - infoheader.bmiHeader.biHeight = bitmap.bmHeight; - infoheader.bmiHeader.biWidth = bitmap.bmWidth; - infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ); + infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8; + infoheader.bmiHeader.biCompression = BI_RGB; + infoheader.bmiHeader.biPlanes = 1; + infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader ); + infoheader.bmiHeader.biHeight = bitmap.bmHeight; + infoheader.bmiHeader.biWidth = bitmap.bmWidth; + infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ); - fileheader.bfType = 0x4D42; - fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); - fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; + fileheader.bfType = 0x4D42; + fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER ); + fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage; - GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS ); + GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS ); - HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); - WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); - WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); - WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); - CloseHandle( file ); + HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); + WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL ); + WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL ); + WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL ); + CloseHandle( file ); - delete [] dwpBits; + delete [] dwpBits; } HDC getDC() const { return hdc; } @@ -101,10 +101,10 @@ public: private: HBITMAP bmp; - HDC hdc; + HDC hdc; HPEN pen; void *pBits; - int width, height; + int width, height; }; //-------------------------------------------------------------------------------------------------- class mazeGenerator @@ -112,132 +112,132 @@ class mazeGenerator public: mazeGenerator() { - _world = 0; - _bmp.create( BMP_SIZE, BMP_SIZE ); - _bmp.setPenColor( RGB( 0, 255, 0 ) ); + _world = 0; + _bmp.create( BMP_SIZE, BMP_SIZE ); + _bmp.setPenColor( RGB( 0, 255, 0 ) ); } ~mazeGenerator() { killArray(); } void create( int side ) { - _s = side; - generate(); - display(); + _s = side; + generate(); + display(); } private: void generate() { - killArray(); - _world = new BYTE[_s * _s]; - ZeroMemory( _world, _s * _s ); - _ptX = rand() % _s; _ptY = rand() % _s; - carve(); + killArray(); + _world = new BYTE[_s * _s]; + ZeroMemory( _world, _s * _s ); + _ptX = rand() % _s; _ptY = rand() % _s; + carve(); } void carve() { - while( true ) - { - int d = getDirection(); - if( d < NOR ) return; + while( true ) + { + int d = getDirection(); + if( d < NOR ) return; - switch( d ) - { - case NOR: - _world[_ptX + _s * _ptY] |= NOR; _ptY--; - _world[_ptX + _s * _ptY] = SOU | SOU << 4; - break; - case EAS: - _world[_ptX + _s * _ptY] |= EAS; _ptX++; - _world[_ptX + _s * _ptY] = WES | WES << 4; - break; - case SOU: - _world[_ptX + _s * _ptY] |= SOU; _ptY++; - _world[_ptX + _s * _ptY] = NOR | NOR << 4; - break; - case WES: - _world[_ptX + _s * _ptY] |= WES; _ptX--; - _world[_ptX + _s * _ptY] = EAS | EAS << 4; - } - } + switch( d ) + { + case NOR: + _world[_ptX + _s * _ptY] |= NOR; _ptY--; + _world[_ptX + _s * _ptY] = SOU | SOU << 4; + break; + case EAS: + _world[_ptX + _s * _ptY] |= EAS; _ptX++; + _world[_ptX + _s * _ptY] = WES | WES << 4; + break; + case SOU: + _world[_ptX + _s * _ptY] |= SOU; _ptY++; + _world[_ptX + _s * _ptY] = NOR | NOR << 4; + break; + case WES: + _world[_ptX + _s * _ptY] |= WES; _ptX--; + _world[_ptX + _s * _ptY] = EAS | EAS << 4; + } + } } void display() { - _bmp.clear(); - HDC dc = _bmp.getDC(); - for( int y = 0; y < _s; y++ ) - { - int yy = y * _s; - for( int x = 0; x < _s; x++ ) - { - BYTE b = _world[x + yy]; - int nx = x * CELL_SIZE, - ny = y * CELL_SIZE; - - if( !( b & NOR ) ) - { - MoveToEx( dc, nx, ny, NULL ); - LineTo( dc, nx + CELL_SIZE + 1, ny ); - } - if( !( b & EAS ) ) - { - MoveToEx( dc, nx + CELL_SIZE, ny, NULL ); - LineTo( dc, nx + CELL_SIZE, ny + CELL_SIZE + 1 ); - } - if( !( b & SOU ) ) - { - MoveToEx( dc, nx, ny + CELL_SIZE, NULL ); - LineTo( dc, nx + CELL_SIZE + 1, ny + CELL_SIZE ); - } - if( !( b & WES ) ) - { - MoveToEx( dc, nx, ny, NULL ); - LineTo( dc, nx, ny + CELL_SIZE + 1 ); - } - } - } + _bmp.clear(); + HDC dc = _bmp.getDC(); + for( int y = 0; y < _s; y++ ) + { + int yy = y * _s; + for( int x = 0; x < _s; x++ ) + { + BYTE b = _world[x + yy]; + int nx = x * CELL_SIZE, + ny = y * CELL_SIZE; - //_bmp.saveBitmap( "f:\\rc\\maze.bmp" ); - BitBlt( GetDC( GetConsoleWindow() ), 10, 60, BMP_SIZE, BMP_SIZE, _bmp.getDC(), 0, 0, SRCCOPY ); + if( !( b & NOR ) ) + { + MoveToEx( dc, nx, ny, NULL ); + LineTo( dc, nx + CELL_SIZE + 1, ny ); + } + if( !( b & EAS ) ) + { + MoveToEx( dc, nx + CELL_SIZE, ny, NULL ); + LineTo( dc, nx + CELL_SIZE, ny + CELL_SIZE + 1 ); + } + if( !( b & SOU ) ) + { + MoveToEx( dc, nx, ny + CELL_SIZE, NULL ); + LineTo( dc, nx + CELL_SIZE + 1, ny + CELL_SIZE ); + } + if( !( b & WES ) ) + { + MoveToEx( dc, nx, ny, NULL ); + LineTo( dc, nx, ny + CELL_SIZE + 1 ); + } + } + } + + //_bmp.saveBitmap( "f:\\rc\\maze.bmp" ); + BitBlt( GetDC( GetConsoleWindow() ), 10, 60, BMP_SIZE, BMP_SIZE, _bmp.getDC(), 0, 0, SRCCOPY ); } int getDirection() { - int d = 1 << rand() % 4; - while( true ) - { - for( int x = 0; x < 4; x++ ) - { - if( testDir( d ) ) return d; - d <<= 1; - if( d > 8 ) d = 1; - } - d = ( _world[_ptX + _s * _ptY] & 0xf0 ) >> 4; - if( !d ) return -1; - switch( d ) - { - case NOR: _ptY--; break; - case EAS: _ptX++; break; - case SOU: _ptY++; break; - case WES: _ptX--; break; - } + int d = 1 << rand() % 4; + while( true ) + { + for( int x = 0; x < 4; x++ ) + { + if( testDir( d ) ) return d; + d <<= 1; + if( d > 8 ) d = 1; + } + d = ( _world[_ptX + _s * _ptY] & 0xf0 ) >> 4; + if( !d ) return -1; + switch( d ) + { + case NOR: _ptY--; break; + case EAS: _ptX++; break; + case SOU: _ptY++; break; + case WES: _ptX--; break; + } d = 1 << rand() % 4; - } + } } bool testDir( int d ) { - switch( d ) - { - case NOR: return ( _ptY - 1 > -1 && !_world[_ptX + _s * ( _ptY - 1 )] ); - case EAS: return ( _ptX + 1 < _s && !_world[_ptX + 1 + _s * _ptY] ); - case SOU: return ( _ptY + 1 < _s && !_world[_ptX + _s * ( _ptY + 1 )] ); - case WES: return ( _ptX - 1 > -1 && !_world[_ptX - 1 + _s * _ptY] ); - } - return false; + switch( d ) + { + case NOR: return ( _ptY - 1 > -1 && !_world[_ptX + _s * ( _ptY - 1 )] ); + case EAS: return ( _ptX + 1 < _s && !_world[_ptX + 1 + _s * _ptY] ); + case SOU: return ( _ptY + 1 < _s && !_world[_ptX + _s * ( _ptY + 1 )] ); + case WES: return ( _ptX - 1 > -1 && !_world[_ptX - 1 + _s * _ptY] ); + } + return false; } void killArray() { if( _world ) delete [] _world; } @@ -256,13 +256,13 @@ int main( int argc, char* argv[] ) int s; while( true ) { - cout << "Enter the maze size, an odd number bigger than 2 ( 0 to QUIT ): "; cin >> s; - if( !s ) return 0; - if( !( s & 1 ) ) s++; - if( s >= 3 ) mg.create( s ); - cout << endl; - system( "pause" ); - system( "cls" ); + cout << "Enter the maze size, an odd number bigger than 2 ( 0 to QUIT ): "; cin >> s; + if( !s ) return 0; + if( !( s & 1 ) ) s++; + if( s >= 3 ) mg.create( s ); + cout << endl; + system( "pause" ); + system( "cls" ); } return 0; } diff --git a/Task/Maze-generation/C/maze-generation.c b/Task/Maze-generation/C/maze-generation.c index a3e1685141..6089aacae6 100644 --- a/Task/Maze-generation/C/maze-generation.c +++ b/Task/Maze-generation/C/maze-generation.c @@ -6,9 +6,9 @@ #define DOUBLE_SPACE 1 #if DOUBLE_SPACE -# define SPC " " +# define SPC " " #else -# define SPC " " +# define SPC " " #endif wchar_t glyph[] = L""SPC"│││─┘┐┤─└┌├─┴┬┼"SPC"┆┆┆┄╯╮ ┄╰╭ ┄"; @@ -22,23 +22,23 @@ int w, h, avail; int irand(int n) { - int r, rmax = n * (RAND_MAX / n); - while ((r = rand()) >= rmax); - return r / (RAND_MAX/n); + int r, rmax = n * (RAND_MAX / n); + while ((r = rand()) >= rmax); + return r / (RAND_MAX/n); } void show() { - int i, j, c; - each(i, 0, 2 * h) { - each(j, 0, 2 * w) { - c = cell[i][j]; - if (c > V) printf("\033[31m"); - printf("%lc", glyph[c]); - if (c > V) printf("\033[m"); - } - putchar('\n'); - } + int i, j, c; + each(i, 0, 2 * h) { + each(j, 0, 2 * w) { + c = cell[i][j]; + if (c > V) printf("\033[31m"); + printf("%lc", glyph[c]); + if (c > V) printf("\033[m"); + } + putchar('\n'); + } } inline int max(int a, int b) { return a >= b ? a : b; } @@ -47,100 +47,100 @@ inline int min(int a, int b) { return b >= a ? a : b; } static int dirs[4][2] = {{-2, 0}, {0, 2}, {2, 0}, {0, -2}}; void walk(int x, int y) { - int i, t, x1, y1, d[4] = { 0, 1, 2, 3 }; + int i, t, x1, y1, d[4] = { 0, 1, 2, 3 }; - cell[y][x] |= V; - avail--; + cell[y][x] |= V; + avail--; - for (x1 = 3; x1; x1--) - if (x1 != (y1 = irand(x1 + 1))) - i = d[x1], d[x1] = d[y1], d[y1] = i; + for (x1 = 3; x1; x1--) + if (x1 != (y1 = irand(x1 + 1))) + i = d[x1], d[x1] = d[y1], d[y1] = i; - for (i = 0; avail && i < 4; i++) { - x1 = x + dirs[ d[i] ][0], y1 = y + dirs[ d[i] ][1]; + for (i = 0; avail && i < 4; i++) { + x1 = x + dirs[ d[i] ][0], y1 = y + dirs[ d[i] ][1]; - if (cell[y1][x1] & V) continue; + if (cell[y1][x1] & V) continue; - /* break walls */ - if (x1 == x) { - t = (y + y1) / 2; - cell[t][x+1] &= ~W, cell[t][x] &= ~(E|W), cell[t][x-1] &= ~E; - } else if (y1 == y) { - t = (x + x1)/2; - cell[y-1][t] &= ~S, cell[y][t] &= ~(N|S), cell[y+1][t] &= ~N; - } - walk(x1, y1); - } + /* break walls */ + if (x1 == x) { + t = (y + y1) / 2; + cell[t][x+1] &= ~W, cell[t][x] &= ~(E|W), cell[t][x-1] &= ~E; + } else if (y1 == y) { + t = (x + x1)/2; + cell[y-1][t] &= ~S, cell[y][t] &= ~(N|S), cell[y+1][t] &= ~N; + } + walk(x1, y1); + } } int solve(int x, int y, int tox, int toy) { - int i, t, x1, y1; + int i, t, x1, y1; - cell[y][x] |= V; - if (x == tox && y == toy) return 1; + cell[y][x] |= V; + if (x == tox && y == toy) return 1; - each(i, 0, 3) { - x1 = x + dirs[i][0], y1 = y + dirs[i][1]; - if (cell[y1][x1]) continue; + each(i, 0, 3) { + x1 = x + dirs[i][0], y1 = y + dirs[i][1]; + if (cell[y1][x1]) continue; - /* mark path */ - if (x1 == x) { - t = (y + y1)/2; - if (cell[t][x] || !solve(x1, y1, tox, toy)) continue; + /* mark path */ + if (x1 == x) { + t = (y + y1)/2; + if (cell[t][x] || !solve(x1, y1, tox, toy)) continue; - cell[t-1][x] |= S, cell[t][x] |= V|N|S, cell[t+1][x] |= N; - } else if (y1 == y) { - t = (x + x1)/2; - if (cell[y][t] || !solve(x1, y1, tox, toy)) continue; + cell[t-1][x] |= S, cell[t][x] |= V|N|S, cell[t+1][x] |= N; + } else if (y1 == y) { + t = (x + x1)/2; + if (cell[y][t] || !solve(x1, y1, tox, toy)) continue; - cell[y][t-1] |= E, cell[y][t] |= V|E|W, cell[y][t+1] |= W; - } - return 1; - } + cell[y][t-1] |= E, cell[y][t] |= V|E|W, cell[y][t+1] |= W; + } + return 1; + } - /* backtrack */ - cell[y][x] &= ~V; - return 0; + /* backtrack */ + cell[y][x] &= ~V; + return 0; } void make_maze() { - int i, j; - int h2 = 2 * h + 2, w2 = 2 * w + 2; - byte **p; + int i, j; + int h2 = 2 * h + 2, w2 = 2 * w + 2; + byte **p; - p = calloc(sizeof(byte*) * (h2 + 2) + w2 * h2 + 1, 1); + p = calloc(sizeof(byte*) * (h2 + 2) + w2 * h2 + 1, 1); - p[1] = (byte*)(p + h2 + 2) + 1; - each(i, 2, h2) p[i] = p[i-1] + w2; - p[0] = p[h2]; - cell = &p[1]; + p[1] = (byte*)(p + h2 + 2) + 1; + each(i, 2, h2) p[i] = p[i-1] + w2; + p[0] = p[h2]; + cell = &p[1]; - each(i, -1, 2 * h + 1) cell[i][-1] = cell[i][w2 - 1] = V; - each(j, 0, 2 * w) cell[-1][j] = cell[h2 - 1][j] = V; - each(i, 0, h) each(j, 0, 2 * w) cell[2*i][j] |= E|W; - each(i, 0, 2 * h) each(j, 0, w) cell[i][2*j] |= N|S; - each(j, 0, 2 * w) cell[0][j] &= ~N, cell[2*h][j] &= ~S; - each(i, 0, 2 * h) cell[i][0] &= ~W, cell[i][2*w] &= ~E; + each(i, -1, 2 * h + 1) cell[i][-1] = cell[i][w2 - 1] = V; + each(j, 0, 2 * w) cell[-1][j] = cell[h2 - 1][j] = V; + each(i, 0, h) each(j, 0, 2 * w) cell[2*i][j] |= E|W; + each(i, 0, 2 * h) each(j, 0, w) cell[i][2*j] |= N|S; + each(j, 0, 2 * w) cell[0][j] &= ~N, cell[2*h][j] &= ~S; + each(i, 0, 2 * h) cell[i][0] &= ~W, cell[i][2*w] &= ~E; - avail = w * h; - walk(irand(2) * 2 + 1, irand(h) * 2 + 1); + avail = w * h; + walk(irand(2) * 2 + 1, irand(h) * 2 + 1); - /* reset visited marker (it's also used by path finder) */ - each(i, 0, 2 * h) each(j, 0, 2 * w) cell[i][j] &= ~V; - solve(1, 1, 2 * w - 1, 2 * h - 1); + /* reset visited marker (it's also used by path finder) */ + each(i, 0, 2 * h) each(j, 0, 2 * w) cell[i][j] &= ~V; + solve(1, 1, 2 * w - 1, 2 * h - 1); - show(); + show(); } int main(int c, char **v) { - setlocale(LC_ALL, ""); - if (c < 2 || (w = atoi(v[1])) <= 0) w = 16; - if (c < 3 || (h = atoi(v[2])) <= 0) h = 8; + setlocale(LC_ALL, ""); + if (c < 2 || (w = atoi(v[1])) <= 0) w = 16; + if (c < 3 || (h = atoi(v[2])) <= 0) h = 8; - make_maze(); + make_maze(); - return 0; + return 0; } diff --git a/Task/Maze-generation/Chapel/maze-generation.chpl b/Task/Maze-generation/Chapel/maze-generation.chpl new file mode 100644 index 0000000000..8ba88606f9 --- /dev/null +++ b/Task/Maze-generation/Chapel/maze-generation.chpl @@ -0,0 +1,56 @@ +use Random; + +config const rows: int = 9; +config const cols: int = 16; +if rows < 1 || cols < 1 { + writeln("Maze must be at least 1x1 in size."); + exit(1); +} + +enum direction {N = 1, E = 2, S = 3, W = 4}; + +record Cell { + var spaces: [direction.N .. direction.W] bool; + var visited: bool; +} + +const dirs = [ + ((-1, 0), direction.N, direction.S), // ((rowDir, colDir), myWall, neighbourWall) + ((0, 1), direction.E, direction.W), + ((1, 0), direction.S, direction.N), + ((0, -1), direction.W, direction.E) +]; + +var maze: [1..rows, 1..cols] Cell; +var startingCell = (choose(maze.dim(0)), choose(maze.dim(1))); + +checkCell(maze, startingCell); +displayMaze(maze); + +proc checkCell(ref maze, cell) { + maze[cell].visited = true; + for dir in permute(dirs) { + var (offset, thisDir, neighbourDir) = dir; + var neighbour = cell + offset; + if maze.domain.contains(neighbour) && !maze[neighbour].visited { + maze[cell].spaces[thisDir] = true; + maze[neighbour].spaces[neighbourDir] = true; + checkCell(maze, neighbour); + } + } +} + +proc displayMaze(maze) { + for row in maze.dim(0) { + for col in maze.dim(1) { + write(if maze[row, col].spaces[direction.N] then "+ " else "+---"); + } + writeln("+"); + for col in maze.dim(1) { + write(if maze[row, col].spaces[direction.W] then " " else "| "); + } + writeln("|"); + } + write("+---" * maze.dim(1).size); + writeln("+"); +} diff --git a/Task/Maze-generation/Common-Lisp/maze-generation-2.lisp b/Task/Maze-generation/Common-Lisp/maze-generation-2.lisp index b8f3fef933..28c8078772 100644 --- a/Task/Maze-generation/Common-Lisp/maze-generation-2.lisp +++ b/Task/Maze-generation/Common-Lisp/maze-generation-2.lisp @@ -8,48 +8,48 @@ (defun make-maze (w h) (let ((vis (2d-array w h)) - (ver (2d-array w h)) - (hor (2d-array w h))) + (ver (2d-array w h)) + (hor (2d-array w h))) (labels ((walk (y x) - (setf (aref vis y x) 1) - (loop - (let (x2 y2) - (loop for (dx dy) in '((-1 0) (1 0) (0 -1) (0 1)) - with cnt = 0 do - (let ((xx (+ x dx)) - (yy (+ y dy))) - (if (and (array-in-bounds-p vis yy xx) - (zerop (aref vis yy xx)) - (zerop (random (incf cnt)))) - (setf x2 xx y2 yy)))) - (if (not x2) (return-from walk)) - (if (= x x2) - (setf (aref hor (min y y2) x) 1) - (setf (aref ver y (min x x2)) 1)) - (walk y2 x2)))) + (setf (aref vis y x) 1) + (loop + (let (x2 y2) + (loop for (dx dy) in '((-1 0) (1 0) (0 -1) (0 1)) + with cnt = 0 do + (let ((xx (+ x dx)) + (yy (+ y dy))) + (if (and (array-in-bounds-p vis yy xx) + (zerop (aref vis yy xx)) + (zerop (random (incf cnt)))) + (setf x2 xx y2 yy)))) + (if (not x2) (return-from walk)) + (if (= x x2) + (setf (aref hor (min y y2) x) 1) + (setf (aref ver y (min x x2)) 1)) + (walk y2 x2)))) (show () - (let ((g " │││─┘┐┤─└┌├─┴┬┼")) - (loop for i from 0 to h do - (loop for j from 0 to w do - (format t "~c~a" - (char g - (+ (or-and 1 (= i 0) (> j 0) (aref ver (1- i) (1- j))) - (or-and 2 (= i h) (> j 0) (aref ver i (1- j))) - (or-and 4 (= j 0) (> i 0) (aref hor (1- i) (1- j))) - (or-and 8 (= j w) (> i 0) (aref hor (1- i) j )))) - (if (and (< j w) - (or (= i 0) - (= 0 (aref hor (1- i) j)))) - "───" " "))) - (terpri) - (when (< i h) - (loop for j from 0 below w do - (format t (if (or (= j 0) - (= 0 (aref ver i (1- j)))) - "│ " " "))) - (format t "│~%")))))) + (let ((g " │││─┘┐┤─└┌├─┴┬┼")) + (loop for i from 0 to h do + (loop for j from 0 to w do + (format t "~c~a" + (char g + (+ (or-and 1 (= i 0) (> j 0) (aref ver (1- i) (1- j))) + (or-and 2 (= i h) (> j 0) (aref ver i (1- j))) + (or-and 4 (= j 0) (> i 0) (aref hor (1- i) (1- j))) + (or-and 8 (= j w) (> i 0) (aref hor (1- i) j )))) + (if (and (< j w) + (or (= i 0) + (= 0 (aref hor (1- i) j)))) + "───" " "))) + (terpri) + (when (< i h) + (loop for j from 0 below w do + (format t (if (or (= j 0) + (= 0 (aref ver i (1- j)))) + "│ " " "))) + (format t "│~%")))))) (walk (random h) (random w)) (show)))) diff --git a/Task/Maze-generation/Delphi/maze-generation.delphi b/Task/Maze-generation/Delphi/maze-generation.pas similarity index 100% rename from Task/Maze-generation/Delphi/maze-generation.delphi rename to Task/Maze-generation/Delphi/maze-generation.pas diff --git a/Task/Maze-generation/EGL/maze-generation.egl b/Task/Maze-generation/EGL/maze-generation.egl index 01a408e2f4..c1e32557d7 100644 --- a/Task/Maze-generation/EGL/maze-generation.egl +++ b/Task/Maze-generation/EGL/maze-generation.egl @@ -2,7 +2,7 @@ program MazeGen // First and last columns/rows are "dead" cells. Makes generating // a maze with border walls much easier. Therefore, a visible - // 20x20 maze has a maze size of 22. + // 20x20 maze has a maze size of 22. mazeSize int = 22; south boolean[][]; diff --git a/Task/Maze-generation/EasyLang/maze-generation.easy b/Task/Maze-generation/EasyLang/maze-generation.easy index 043b229e65..c4160a3133 100644 --- a/Task/Maze-generation/EasyLang/maze-generation.easy +++ b/Task/Maze-generation/EasyLang/maze-generation.easy @@ -3,28 +3,28 @@ n = 2 * size + 1 f = 100 / (n - 0.5) len m[] n * n # -background 000 -proc show_maze . . - clear +gbackground 000 +proc show_maze . + gclear + sz = f * 1.5 + f2 = f / 2 for i = 1 to len m[] if m[i] = 0 x = (i - 1) mod n y = (i - 1) div n - color 999 - move x * f - f / 2 y * f - f / 2 - rect f * 1.5 f * 1.5 + gcolor 999 + grect x * f - f2 y * f - f2 sz sz . . sleep 0.01 . offs[] = [ 1 n -1 (-n) ] -# -proc m_maze pos . . +proc m_maze pos . m[pos] = 0 show_maze d[] = [ 1 2 3 4 ] for i = 4 downto 1 - d = randint i + d = random 1 i dir = offs[d[d]] d[d] = d[i] if m[pos + dir] = 1 and m[pos + 2 * dir] = 1 @@ -34,20 +34,17 @@ proc m_maze pos . . . . endpos = n * n - 1 -proc make_maze . . - for i = 1 to len m[] - m[i] = 1 - . +proc make_maze . + for i = 1 to len m[] : m[i] = 1 for i = 1 to n m[i] = 2 m[n * i] = 2 m[n * i - n + 1] = 2 m[n * n - n + i] = 2 . - h = 2 * randint 15 - n + n * 2 * randint 15 + h = 2 * random 1 size - n + n * 2 * random 1 size m_maze h m[endpos] = 0 - endpos += n . make_maze show_maze diff --git a/Task/Maze-generation/Elixir/maze-generation.elixir b/Task/Maze-generation/Elixir/maze-generation.ex similarity index 100% rename from Task/Maze-generation/Elixir/maze-generation.elixir rename to Task/Maze-generation/Elixir/maze-generation.ex diff --git a/Task/Maze-generation/Emacs-Lisp/maze-generation.l b/Task/Maze-generation/Emacs-Lisp/maze-generation.el similarity index 100% rename from Task/Maze-generation/Emacs-Lisp/maze-generation.l rename to Task/Maze-generation/Emacs-Lisp/maze-generation.el diff --git a/Task/Maze-generation/Erlang/maze-generation-1.erl b/Task/Maze-generation/Erlang/maze-generation-1.erl index 03f55777ba..a590588a44 100644 --- a/Task/Maze-generation/Erlang/maze-generation-1.erl +++ b/Task/Maze-generation/Erlang/maze-generation-1.erl @@ -16,8 +16,8 @@ cell_pid( X, Y, Maze ) -> dict:fetch( {X, Y}, Maze#maze.dict ). cell_position( Pid ) -> read( Pid, position ). display( #maze{dict=Dict, max_x=Max_x, max_y=Max_y} ) -> - Position_pids = dict:to_list( Dict ), - display( Max_x, Max_y, reads(Position_pids, content), reads(Position_pids, walls) ). + Position_pids = dict:to_list( Dict ), + display( Max_x, Max_y, reads(Position_pids, content), reads(Position_pids, walls) ). generation( Max_x, Max_y ) -> Controller = erlang:self(), @@ -52,13 +52,13 @@ cell_create( Controller, Max_x, Max_y, {X, Y} ) -> erlang:spawn_link( fun() -> r display( Max_x, Max_y, Position_contents, Position_walls ) -> All_rows = [display_row( Max_x, Y, Position_contents, Position_walls ) || Y <- lists:seq(Max_y, 1, -1)], [io:fwrite("~s+~n~s|~n", [North, West]) || {North, West} <- All_rows], - io:fwrite("~s+~n", [lists:flatten(lists:duplicate(Max_x, display_row_north(true)))] ). + io:fwrite("~s+~n", [lists:flatten(lists:duplicate(Max_x, display_row_north(true)))] ). display_row( Max_x, Y, Position_contents, Position_walls ) -> - North_wests = [display_row_walls(proplists:get_value({X,Y}, Position_contents), proplists:get_value({X,Y}, Position_walls)) || X <- lists:seq(1, Max_x)], - North = lists:append( [North || {North, _West} <- North_wests] ), - West = lists:append( [West || {_X, West} <- North_wests] ), - {North, West}. + North_wests = [display_row_walls(proplists:get_value({X,Y}, Position_contents), proplists:get_value({X,Y}, Position_walls)) || X <- lists:seq(1, Max_x)], + North = lists:append( [North || {North, _West} <- North_wests] ), + West = lists:append( [West || {_X, West} <- North_wests] ), + {North, West}. display_row_walls( Content, Walls ) -> {display_row_north( lists:member(north, Walls) ), display_row_west( lists:member(west, Walls), Content )}. @@ -71,47 +71,47 @@ display_row_west( false, Content ) -> " " ++ Content ++ " ". loop( State ) -> receive {accessible_neighbours, Pid} -> - Pid ! {accessible_neighbours, loop_accessible_neighbours( State#state.neighbours, State#state.walls ), erlang:self()}, + Pid ! {accessible_neighbours, loop_accessible_neighbours( State#state.neighbours, State#state.walls ), erlang:self()}, loop( State ); {content, Pid} -> - Pid ! {content, State#state.content, erlang:self()}, + Pid ! {content, State#state.content, erlang:self()}, loop( State ); {content, Content, _Pid} -> loop( State#state{content=Content} ); {dig, Pid} -> - Not_dug_neighbours = loop_not_dug( State#state.neighbours ), - New_walls = loop_dig( Not_dug_neighbours, lists:delete( loop_wall_from_pid(Pid, State#state.neighbours), State#state.walls), Pid ), - loop( State#state{is_dug=true, walls=New_walls, walk_done=Pid} ); + Not_dug_neighbours = loop_not_dug( State#state.neighbours ), + New_walls = loop_dig( Not_dug_neighbours, lists:delete( loop_wall_from_pid(Pid, State#state.neighbours), State#state.walls), Pid ), + loop( State#state{is_dug=true, walls=New_walls, walk_done=Pid} ); {dig_done} -> - Not_dug_neighbours = loop_not_dug( State#state.neighbours ), - New_walls = loop_dig( Not_dug_neighbours, State#state.walls, State#state.walk_done ), - loop( State#state{walls=New_walls} ); + Not_dug_neighbours = loop_not_dug( State#state.neighbours ), + New_walls = loop_dig( Not_dug_neighbours, State#state.walls, State#state.walk_done ), + loop( State#state{walls=New_walls} ); {is_dug, Pid} -> - Pid ! {is_dug, State#state.is_dug, erlang:self()}, - loop( State ); + Pid ! {is_dug, State#state.is_dug, erlang:self()}, + loop( State ); {position, Pid} -> - Pid ! {position, State#state.position, erlang:self()}, + Pid ! {position, State#state.position, erlang:self()}, loop( State ); {position_pids, Position_pids} -> {_My_position, Neighbours} = lists:foldl( fun loop_neighbours/2, {State#state.position, []}, Position_pids ), erlang:garbage_collect(), % Shrink process after using large Pid_positions. For memory starved systems. loop( State#state{neighbours=Neighbours} ); {stop, Controller} when Controller =:= State#state.controller -> - ok; + ok; {walls, Pid} -> - Pid ! {walls, State#state.walls, erlang:self()}, - loop( State ) + Pid ! {walls, State#state.walls, erlang:self()}, + loop( State ) end. loop_accessible_neighbours( Neighbours, Walls ) -> [Pid || {Direction, Pid} <- Neighbours, not lists:member(Direction, Walls)]. loop_dig( [], Walls, Pid ) -> - Pid ! {dig_done}, - Walls; + Pid ! {dig_done}, + Walls; loop_dig( Not_dug_neighbours, Walls, _Pid ) -> {Dig_pid, Dig_direction} = lists:nth( random:uniform(erlang:length(Not_dug_neighbours)), Not_dug_neighbours ), Dig_pid ! {dig, erlang:self()}, - lists:delete( Dig_direction, Walls ). + lists:delete( Dig_direction, Walls ). loop_neighbours( {{X, Y}, Pid}, {{X, My_y}, Acc} ) when Y =:= My_y + 1 -> {{X, My_y}, [{north, Pid} | Acc]}; loop_neighbours( {{X, Y}, Pid}, {{X, My_y}, Acc} ) when Y =:= My_y - 1 -> {{X, My_y}, [{south, Pid} | Acc]}; @@ -120,17 +120,17 @@ loop_neighbours( {{X, Y}, Pid}, {{My_x, Y}, Acc} ) when X =:= My_x - 1 -> {{My_x loop_neighbours( _Position_pid, Acc ) -> Acc. loop_not_dug( Neighbours ) -> - My_pid = erlang:self(), - [Pid ! {is_dug, My_pid} || {_Direction, Pid} <- Neighbours], - [{Pid, Direction} || {Direction, Pid} <- Neighbours, not read_receive(Pid, is_dug)]. + My_pid = erlang:self(), + [Pid ! {is_dug, My_pid} || {_Direction, Pid} <- Neighbours], + [{Pid, Direction} || {Direction, Pid} <- Neighbours, not read_receive(Pid, is_dug)]. loop_wall_from_pid( Pid, Neighbours ) -> loop_wall_from_pid_result( lists:keyfind(Pid, 2, Neighbours) ). loop_wall_from_pid_result( {Direction, _Pid} ) -> Direction; loop_wall_from_pid_result( false ) -> controller. read( Pid, Key ) -> - Pid ! {Key, erlang:self()}, - read_receive( Pid, Key ). + Pid ! {Key, erlang:self()}, + read_receive( Pid, Key ). read_receive( Pid, Key ) -> receive diff --git a/Task/Maze-generation/FutureBasic/maze-generation.basic b/Task/Maze-generation/FutureBasic/maze-generation.basic index b112b74bdc..4013335896 100644 --- a/Task/Maze-generation/FutureBasic/maze-generation.basic +++ b/Task/Maze-generation/FutureBasic/maze-generation.basic @@ -57,7 +57,7 @@ end fn void local fn DrawMaze long r, c, x = _mgn, y = _mgn, value - pen 2,, NSLineCapStyleRound + pen 2, fn ColorText, NSLineCapStyleRound for r = 0 to _rows - 1 for c = 0 to _cols - 1 diff --git a/Task/Maze-generation/Huginn/maze-generation.huginn b/Task/Maze-generation/Huginn/maze-generation.huginn index 8f7db2a0c3..60b59a4ca4 100644 --- a/Task/Maze-generation/Huginn/maze-generation.huginn +++ b/Task/Maze-generation/Huginn/maze-generation.huginn @@ -3,69 +3,69 @@ import Mathematics as math; import Terminal as term; class Maze { - _rows = none; - _cols = none; - _data = none; - constructor( rows_, cols_ ) { - _rows = ( rows_ / 2 ) * 2 - 1; - _cols = ( cols_ / 2 ) * 2 - 1; - _data = [].resize( _rows + 2, [].resize( _cols + 2, false ) ); - x = 0; - y = 0; - path = []; - rng = math.Randomizer( math.Randomizer.DISTRIBUTION.DISCRETE, 0, integer( $2 ^ $63 - $1 ) ); - for ( _ : algo.range( _rows * _cols / 3 ) ) { - _data[y + 1][x + 1] = true; - while ( true ) { - n = neighbours( y, x ); - ns = size( n ); - if ( ns == 0 ) { - if ( size( path ) == 0 ) { - break; - } - y, x = path[-1]; - path.pop(); - continue; - } - oy, ox = ( y, x ); - y, x = n[rng.next() % ns]; - _data[(y + oy) / 2 + 1][(x + ox) / 2 + 1] = true; - path.push( ( y, x ) ); - break; - } - } - _data[0][1] = true; - _data[-1][-2] = true; - } - neighbours( y_, x_ ) { - n = []; - if ( ( x_ > 1 ) && ! _data[y_ + 1][x_ - 1] ) { - n.push( ( y_, x_ - 2 ) ); - } - if ( ( y_ > 1 ) && ! _data[y_ - 1][x_ + 1] ) { - n.push( ( y_ - 2, x_ ) ); - } - if ( ( x_ < ( _cols - 2 ) ) && ! _data[y_ + 1][x_ + 3] ) { - n.push( ( y_, x_ + 2 ) ); - } - if ( ( y_ < ( _rows - 2 ) ) && ! _data[y_ + 3][x_ + 1] ) { - n.push( ( y_ + 2, x_ ) ); - } - return ( n ); - } - to_string() { - s = ""; - for ( r : _data ) { - s += ∑( algo.map( r, @( b ) { b ? " " : "#"; } ) ); - s += "\n"; - } - return ( s ); - } + _rows = none; + _cols = none; + _data = none; + constructor( rows_, cols_ ) { + _rows = ( rows_ / 2 ) * 2 - 1; + _cols = ( cols_ / 2 ) * 2 - 1; + _data = [].resize( _rows + 2, [].resize( _cols + 2, false ) ); + x = 0; + y = 0; + path = []; + rng = math.Randomizer( math.Randomizer.DISTRIBUTION.DISCRETE, 0, integer( $2 ^ $63 - $1 ) ); + for ( _ : algo.range( _rows * _cols / 3 ) ) { + _data[y + 1][x + 1] = true; + while ( true ) { + n = neighbours( y, x ); + ns = size( n ); + if ( ns == 0 ) { + if ( size( path ) == 0 ) { + break; + } + y, x = path[-1]; + path.pop(); + continue; + } + oy, ox = ( y, x ); + y, x = n[rng.next() % ns]; + _data[(y + oy) / 2 + 1][(x + ox) / 2 + 1] = true; + path.push( ( y, x ) ); + break; + } + } + _data[0][1] = true; + _data[-1][-2] = true; + } + neighbours( y_, x_ ) { + n = []; + if ( ( x_ > 1 ) && ! _data[y_ + 1][x_ - 1] ) { + n.push( ( y_, x_ - 2 ) ); + } + if ( ( y_ > 1 ) && ! _data[y_ - 1][x_ + 1] ) { + n.push( ( y_ - 2, x_ ) ); + } + if ( ( x_ < ( _cols - 2 ) ) && ! _data[y_ + 1][x_ + 3] ) { + n.push( ( y_, x_ + 2 ) ); + } + if ( ( y_ < ( _rows - 2 ) ) && ! _data[y_ + 3][x_ + 1] ) { + n.push( ( y_ + 2, x_ ) ); + } + return ( n ); + } + to_string() { + s = ""; + for ( r : _data ) { + s += ∑( algo.map( r, @( b ) { b ? " " : "#"; } ) ); + s += "\n"; + } + return ( s ); + } } main() { - rows = term.lines() - 2; - cols = term.columns() - 1; - maze = Maze( rows, cols ); - print( "{}".format( maze ) ); + rows = term.lines() - 2; + cols = term.columns() - 1; + maze = Maze( rows, cols ); + print( "{}".format( maze ) ); } diff --git a/Task/Maze-generation/Java/maze-generation.java b/Task/Maze-generation/Java/maze-generation.java index 3159c2471a..df1e8bd61a 100644 --- a/Task/Maze-generation/Java/maze-generation.java +++ b/Task/Maze-generation/Java/maze-generation.java @@ -9,83 +9,83 @@ import java.util.Arrays; * http://weblog.jamisbuck.org/2010/12/27/maze-generation-recursive-backtracking */ public class MazeGenerator { - private final int x; - private final int y; - private final int[][] maze; + private final int x; + private final int y; + private final int[][] maze; - public MazeGenerator(int x, int y) { - this.x = x; - this.y = y; - maze = new int[this.x][this.y]; - generateMaze(0, 0); - } + public MazeGenerator(int x, int y) { + this.x = x; + this.y = y; + maze = new int[this.x][this.y]; + generateMaze(0, 0); + } - public void display() { - for (int i = 0; i < y; i++) { - // draw the north edge - for (int j = 0; j < x; j++) { - System.out.print((maze[j][i] & 1) == 0 ? "+---" : "+ "); - } - System.out.println("+"); - // draw the west edge - for (int j = 0; j < x; j++) { - System.out.print((maze[j][i] & 8) == 0 ? "| " : " "); - } - System.out.println("|"); - } - // draw the bottom line - for (int j = 0; j < x; j++) { - System.out.print("+---"); - } - System.out.println("+"); - } + public void display() { + for (int i = 0; i < y; i++) { + // draw the north edge + for (int j = 0; j < x; j++) { + System.out.print((maze[j][i] & 1) == 0 ? "+---" : "+ "); + } + System.out.println("+"); + // draw the west edge + for (int j = 0; j < x; j++) { + System.out.print((maze[j][i] & 8) == 0 ? "| " : " "); + } + System.out.println("|"); + } + // draw the bottom line + for (int j = 0; j < x; j++) { + System.out.print("+---"); + } + System.out.println("+"); + } - private void generateMaze(int cx, int cy) { - DIR[] dirs = DIR.values(); - Collections.shuffle(Arrays.asList(dirs)); - for (DIR dir : dirs) { - int nx = cx + dir.dx; - int ny = cy + dir.dy; - if (between(nx, x) && between(ny, y) - && (maze[nx][ny] == 0)) { - maze[cx][cy] |= dir.bit; - maze[nx][ny] |= dir.opposite.bit; - generateMaze(nx, ny); - } - } - } + private void generateMaze(int cx, int cy) { + DIR[] dirs = DIR.values(); + Collections.shuffle(Arrays.asList(dirs)); + for (DIR dir : dirs) { + int nx = cx + dir.dx; + int ny = cy + dir.dy; + if (between(nx, x) && between(ny, y) + && (maze[nx][ny] == 0)) { + maze[cx][cy] |= dir.bit; + maze[nx][ny] |= dir.opposite.bit; + generateMaze(nx, ny); + } + } + } - private static boolean between(int v, int upper) { - return (v >= 0) && (v < upper); - } + private static boolean between(int v, int upper) { + return (v >= 0) && (v < upper); + } - private enum DIR { - N(1, 0, -1), S(2, 0, 1), E(4, 1, 0), W(8, -1, 0); - private final int bit; - private final int dx; - private final int dy; - private DIR opposite; + private enum DIR { + N(1, 0, -1), S(2, 0, 1), E(4, 1, 0), W(8, -1, 0); + private final int bit; + private final int dx; + private final int dy; + private DIR opposite; - // use the static initializer to resolve forward references - static { - N.opposite = S; - S.opposite = N; - E.opposite = W; - W.opposite = E; - } + // use the static initializer to resolve forward references + static { + N.opposite = S; + S.opposite = N; + E.opposite = W; + W.opposite = E; + } - private DIR(int bit, int dx, int dy) { - this.bit = bit; - this.dx = dx; - this.dy = dy; - } - }; + private DIR(int bit, int dx, int dy) { + this.bit = bit; + this.dx = dx; + this.dy = dy; + } + }; - public static void main(String[] args) { - int x = args.length >= 1 ? (Integer.parseInt(args[0])) : 8; - int y = args.length == 2 ? (Integer.parseInt(args[1])) : 8; - MazeGenerator maze = new MazeGenerator(x, y); - maze.display(); - } + public static void main(String[] args) { + int x = args.length >= 1 ? (Integer.parseInt(args[0])) : 8; + int y = args.length == 2 ? (Integer.parseInt(args[1])) : 8; + MazeGenerator maze = new MazeGenerator(x, y); + maze.display(); + } } diff --git a/Task/Maze-generation/JavaScript/maze-generation-1.js b/Task/Maze-generation/JavaScript/maze-generation-1.js index 03c16f44cc..77ff19cda2 100644 --- a/Task/Maze-generation/JavaScript/maze-generation-1.js +++ b/Task/Maze-generation/JavaScript/maze-generation-1.js @@ -1,63 +1,63 @@ function maze(x,y) { - var n=x*y-1; - if (n<0) {alert("illegal maze dimensions");return;} - var horiz =[]; for (var j= 0; j0 && j0 && (j != here[0]+1 || k != here[1]+1)); - } - while (00 && j0 && (j != here[0]+1 || k != here[1]+1)); + } + while (00 && m.verti[j/2-1][Math.floor(k/4)]) - line[k]= ' '; - else - line[k]= '-'; - else - for (var k=0; k0 && m.horiz[(j-1)/2][k/4-1]) - line[k]= ' '; - else - line[k]= '|'; - else - line[k]= ' '; - if (0 == j) line[1]= line[2]= line[3]= ' '; - if (m.x*2-1 == j) line[4*m.y]= ' '; - text.push(line.join('')+'\r\n'); - } - return text.join(''); + var text= []; + for (var j= 0; j0 && m.verti[j/2-1][Math.floor(k/4)]) + line[k]= ' '; + else + line[k]= '-'; + else + for (var k=0; k0 && m.horiz[(j-1)/2][k/4-1]) + line[k]= ' '; + else + line[k]= '|'; + else + line[k]= ' '; + if (0 == j) line[1]= line[2]= line[3]= ' '; + if (m.x*2-1 == j) line[4*m.y]= ' '; + text.push(line.join('')+'\r\n'); + } + return text.join(''); } diff --git a/Task/Maze-generation/JavaScript/maze-generation-3.js b/Task/Maze-generation/JavaScript/maze-generation-3.js index 5ab4545685..592c4ffd7b 100644 --- a/Task/Maze-generation/JavaScript/maze-generation-3.js +++ b/Task/Maze-generation/JavaScript/maze-generation-3.js @@ -1,2 +1,2 @@ - function step() { - if (0 diff --git a/Task/Maze-generation/Julia/maze-generation-1.julia b/Task/Maze-generation/Julia/maze-generation-1.jl similarity index 100% rename from Task/Maze-generation/Julia/maze-generation-1.julia rename to Task/Maze-generation/Julia/maze-generation-1.jl diff --git a/Task/Maze-generation/Julia/maze-generation-2.julia b/Task/Maze-generation/Julia/maze-generation-2.jl similarity index 100% rename from Task/Maze-generation/Julia/maze-generation-2.julia rename to Task/Maze-generation/Julia/maze-generation-2.jl diff --git a/Task/Maze-generation/Kotlin/maze-generation.kotlin b/Task/Maze-generation/Kotlin/maze-generation.kts similarity index 100% rename from Task/Maze-generation/Kotlin/maze-generation.kotlin rename to Task/Maze-generation/Kotlin/maze-generation.kts diff --git a/Task/Maze-generation/M2000-Interpreter/maze-generation-1.m2000 b/Task/Maze-generation/M2000-Interpreter/maze-generation-1.m2000 index f0fd0485e1..b73c42a4b5 100644 --- a/Task/Maze-generation/M2000-Interpreter/maze-generation-1.m2000 +++ b/Task/Maze-generation/M2000-Interpreter/maze-generation-1.m2000 @@ -1,56 +1,52 @@ -Module Maze { - width% = 40 - height% = 20 - \\ we can use DIM maze$(0 to width%,0 to height%)="#" - \\ so we can delete the two For loops - DIM maze$(0 to width%,0 to height%) - FOR x% = 0 TO width% - FOR y% = 0 TO height% - maze$(x%, y%) = "#" - NEXT y% - NEXT x% +MODULE Maze { + INTEGER W = 40, H = 20, X, Y, CX, CY, OX, OY, I + BOOLEAN DONE + DIM MAZE(0 TO W, 0 TO H) AS STRING + FOR X = 0 TO W + FOR Y = 0 TO H + MAZE(X, Y) = "#" + NEXT Y + NEXT X - currentx% = INT(RND * (width% - 1)) - currenty% = INT(RND * (height% - 1)) + CX = RND * (W - 1) + CY = RND * (H - 1) - IF currentx% MOD 2 = 0 THEN currentx%++ - IF currenty% MOD 2 = 0 THEN currenty%++ - maze$(currentx%, currenty%) = " " + IF CX MOD 2 = 0 THEN CX++ + IF CY MOD 2 = 0 THEN CY++ + MAZE(CX, CY) = " " - done% = 0 - WHILE done% = 0 { - FOR i% = 0 TO 99 - oldx% = currentx% - oldy% = currenty% - SELECT CASE INT(RND * 4) + WHILE NOT DONE + FOR I = 0 TO 99 + OX = CX + OY = CY + SELECT CASE RANDOM(0, 3) CASE 0 - IF currentx% + 2 < width% THEN currentx%+=2 + IF CX + 2 < W THEN CX+=2 CASE 1 - IF currenty% + 2 < height% THEN currenty%+=2 + IF CY + 2 < H THEN CY+=2 CASE 2 - IF currentx% - 2 > 0 THEN currentx%-=2 + IF CX - 2 > 0 THEN CX-=2 CASE 3 - IF currenty% - 2 > 0 THEN currenty%-=2 + IF CY - 2 > 0 THEN CY-=2 END SELECT - IF maze$(currentx%, currenty%) = "#" Then { - maze$(currentx%, currenty%) = " " - maze$(INT((currentx% + oldx%) / 2), ((currenty% + oldy%) / 2)) = " " - } - NEXT i% - done% = 1 - FOR x% = 1 TO width% - 1 STEP 2 - FOR y% = 1 TO height% - 1 STEP 2 - IF maze$(x%, y%) = "#" THEN done% = 0 - NEXT y% - NEXT x% - } + IF MAZE(CX, CY) = "#" THEN + MAZE(CX, CY) = " " + MAZE((CX + OX) DIV 2, (CY + OY) DIV 2) = " " + END IF + NEXT I + DONE = TRUE + FOR X = 1 TO W - 1 STEP 2 + FOR Y = 1 TO H - 1 STEP 2 + IF MAZE(X, Y) = "#" THEN DONE = FALSE + NEXT Y + NEXT X + END WHILE - - FOR y% = 0 TO height% - FOR x% = 0 TO width% - PRINT maze$(x%, y%); - NEXT x% + FOR Y = 0 TO H + FOR X = 0 TO W + PRINT MAZE(X, Y); + NEXT X PRINT - NEXT y% + NEXT Y } Maze diff --git a/Task/Maze-generation/M2000-Interpreter/maze-generation-2.m2000 b/Task/Maze-generation/M2000-Interpreter/maze-generation-2.m2000 index 9f5c8762a4..1e0759ec34 100644 --- a/Task/Maze-generation/M2000-Interpreter/maze-generation-2.m2000 +++ b/Task/Maze-generation/M2000-Interpreter/maze-generation-2.m2000 @@ -1,43 +1,67 @@ Module Maze2 { \\ depth-first search - Profiler + While Inkey$<>"" {} ' drop keys + Const View as boolean=True + Double tcc + Form 80,50 - let w=60, h=40 +again: + Gradient 5,6 + Cursor 0,0 + let w=random(2,6)*10, h=random(1,4)*10, slice=w*h div 30 + let slice=if(slice=0->1, slice) : counter =1 Double \\center proportional text double size Report 2, Format$("Maze {0}x{1}",w,h) Normal + Hold Refresh Set Fast ! - Dim maze$(1 to w+1, 1 to h+1)="#" - Include=Lambda w,h (a,b) ->a>=1 and a<=w and b>=1 and b<=h - Flush ' empty stack - if random(1,2)=1 then { - entry=(if(random(1,2)=1->2, w),Random(1, h/2)*2) - } else { - entry=(random(1,w/2)*2,If(Random(1,2)=1->2,h)) + stack new { + Profiler + Dim maze$(1 to w+1, 1 to h+1)="#" + Include=Lambda w,h (a,b) ->a>=1 and a<=w and b>=1 and b<=h + Flush ' empty stack + if random(1,2)=1 then + entry=(if(random(1,2)=1->2, w),Random(1, h/2)*2) + else + entry=(random(1,w/2)*2,If(Random(1,2)=1->2,h)) + end if + maze$(entry#val(0), entry#val(1))=" " + forchoose=(,) + Push Entry + do + do + NewForChoose(!entry) + status=len(forchoose) + if status>0 then + status-- + forchoose=forchoose#val(random(0,status)) + Push forchoose + OpenDoor(!Entry, !forchoose) + if view then counter=if(counter=0->slice, counter-1) : if counter=0 then ShowMaze() + else + exit + end if + entry=forchoose + Always + if empty then exit + Read entry + Always + tc= timecount/1000 } - maze$(entry#val(0), entry#val(1))=" " - forchoose=(,) - Push Entry - do { - do { - NewForChoose(!entry) - status=len(forchoose) - if status>0 then { - status-- - forchoose=forchoose#val(random(0,status)) - Push forchoose - OpenDoor(!Entry, !forchoose) - Rem : ShowMaze() - } else exit - entry=forchoose - } Always - if empty then exit - Read entry - } Always ShowMaze() - Print timecount/1000 + Cursor 0,Height-1 + Print Part $(6,width), ~(15,0,0),"Press a key or mouse button after any drawing of the maze to exit - "+format$("{0:3}",tc) + Refresh + counter=10 + every 200 { + counter-- + if inkey$<>"" or mouse<>0 then counter=-1 : exit + if counter<1 then exit + } + if counter=0 then Release : goto again + End Sub NewForChoose(x,y) Local x1=x-2, x2=x+2, y1=y-2, y2=y+2, arr=(,) Stack New { @@ -50,19 +74,21 @@ Module Maze2 { End Sub Sub OpenDoor(x1,y1, x2,y2) Local i - if x1=x2 then { + if x1=x2 then y1+=y2<=>y1 - for i=y1 to y2 {maze$(x1, i)=" " } - } Else { + for i=y1 to y2 step sgn(y2-y1) {maze$(x1, i)=" " } + Else x1+=x2<=>x1 - for i=x1 to x2 {maze$(i, y1)=" "} - } + for i=x1 to x2 step sgn(x2-x1) {maze$(i, y1)=" "} + End if End Sub Sub ShowMaze() Refresh 5000 - cls ,4 ' split screen - preserve lines form 0 to 3 - Local i, j - For j=1 to h+1 { Print @(10) : for i=1 to w+1 {Print maze$(i,j);}:Print} +Rem cls ,4 ' split screen - preserve lines form 0 to 3 + Release + cursor 0,(height-h) div 2 + Local i, j, t=40-w div 2 + For j=1 to h+1 { Print @(t) : for i=1 to w+1 {Print maze$(i,j);}:Print} Print Refresh 100 End Sub diff --git a/Task/Maze-generation/OCaml/maze-generation.ocaml b/Task/Maze-generation/OCaml/maze-generation.ml similarity index 100% rename from Task/Maze-generation/OCaml/maze-generation.ocaml rename to Task/Maze-generation/OCaml/maze-generation.ml diff --git a/Task/Maze-generation/POV-Ray/maze-generation.povray b/Task/Maze-generation/POV-Ray/maze-generation.povray new file mode 100644 index 0000000000..0995a087d6 --- /dev/null +++ b/Task/Maze-generation/POV-Ray/maze-generation.povray @@ -0,0 +1,181 @@ +#version 3.7; + +global_settings { + assumed_gamma 1 +} + +#declare Rows = 15; +#declare Cols = 17; + +#declare Seed = seed(2); // A seed produces a fixed sequence of pseudorandom numbers + +#declare Wall = prism { + 0, 0.8, 7, + <0, -0.5>, <0.05, -0.45>, <0.05, 0.45>, <0, 0.5>, + <-0.05, 0.45>, <-0.05, -0.45>, <0, -0.5> + texture { + pigment { + brick colour rgb 1, colour rgb <0.8, 0.25, 0.1> // Colour mortar, colour brick + brick_size 3*<0.25, 0.0525, 0.125> + mortar 3*0.01 // Size of the mortar + } + normal { wrinkles 0.75 scale 0.01 } + finish { diffuse 0.9 phong 0.2 } + } +} + +#macro Fisher_Yates_Shuffle(Stack, Start, Top) + #for (I, Top, Start+1, -1) + #local J = floor(rand(Seed)*I + 0.5); + #if (J != I) // Waste of time swapping an element with itself + #local Src_Row = Stack[I][0]; + #local Src_Col = Stack[I][1]; + #local Dst_Row = Stack[I][2]; + #local Dst_Col = Stack[I][3]; + #declare Stack[I][0] = Stack[J][0]; + #declare Stack[I][1] = Stack[J][1]; + #declare Stack[I][2] = Stack[J][2]; + #declare Stack[I][3] = Stack[J][3]; + #declare Stack[J][0] = Src_Row; + #declare Stack[J][1] = Src_Col; + #declare Stack[J][2] = Dst_Row; + #declare Stack[J][3] = Dst_Col; + #end + #end +#end + +#macro Initialise(Visited, North_Walls, East_Walls) + #for (R, 0, Rows-1) + #for (C, 0, Cols-1) + #declare Visited[R][C] = false; + #declare North_Walls[R][C] = true; + #declare East_Walls[R][C] = true; + #end + #end +#end + +#macro Push(Stack, Top, Src_Row, Src_Col, Dst_Row, Dst_Col) + #declare Top = Top + 1; + #declare Stack[Top][0] = Src_Row; + #declare Stack[Top][1] = Src_Col; + #declare Stack[Top][2] = Dst_Row; + #declare Stack[Top][3] = Dst_Col; +#end + +#macro Generate_Maze(Visited, North_Walls, East_Walls) + #local Stack = array[Rows*Cols][4]; // 0: from row, 1: from col, 2: to row, 3: to col + #local Row = floor(rand(Seed)*(Rows-1) + 0.5); // Random start row + #local Col = floor(rand(Seed)*(Cols-1) + 0.5); // Random start column + #local Top = -1; + Push(Stack, Top, Row, Col, Row, Col) + + #while (Top >= 0) + #declare Visited[Row][Col] = true; + #local Start = Top + 1; + + #if (Row < Rows-1) // Add north neighbour + #if (Visited[Row+1][Col] = false) + Push(Stack, Top, Row, Col, Row+1, Col) + #end + #end + + #if (Col < Cols-1) // Add east neighbour + #if (Visited[Row][Col+1] = false) + Push(Stack, Top, Row, Col, Row, Col+1) + #end + #end + + #if (Row > 0) // Add south neighbour + #if (Visited[Row-1][Col] = false) + Push(Stack, Top, Row, Col, Row-1, Col) + #end + #end + + #if (Col > 0) // Add west neighbour + #if (Visited[Row][Col-1] = false) + Push(Stack, Top, Row, Col, Row, Col-1) + #end + #end + + Fisher_Yates_Shuffle(Stack, Start, Top) + + #local Removed_Wall = false; + #while (Top >= 0 & Removed_Wall = false) + #local Src_Row = Stack[Top][0]; + #local Src_Col = Stack[Top][1]; + #local Dst_Row = Stack[Top][2]; + #local Dst_Col = Stack[Top][3]; + #declare Top = Top - 1; + + #if (Visited[Dst_Row][Dst_Col] = false) + #if (Dst_Row = Src_Row+1 & Dst_Col = Src_Col) // North wall + #declare North_Walls[Src_Row][Src_Col] = false; + #elseif (Dst_Row = Src_Row & Dst_Col = Src_Col+1) // East wall + #declare East_Walls[Src_Row][Src_Col] = false; + #elseif (Dst_Row = Src_Row-1 & Dst_Col = Src_Col) // South wall + #declare North_Walls[Dst_Row][Src_Col] = false; + #elseif (Dst_Row = Src_Row & Dst_Col = Src_Col-1) // West wall + #declare East_Walls[Src_Row][Dst_Col] = false; + #else + #error "Unknown wall!\n" + #end + + #declare Row = Dst_Row; + #declare Col = Dst_Col; + #declare Removed_Wall = true; + #end + #end + #end +#end + +#macro Draw_Maze(North_Walls, East_Walls) + merge { + #for (R, 0, Rows-1) + object { Wall translate <1, 0, 0.5> translate <-1, 0, R> } // West edge + #for (C, 0, Cols-1) + #if (R = 0) // South edge + object { Wall rotate y*90 translate <0.5, 0, 1> translate } + #end + #if (North_Walls[R][C]) + object { Wall rotate y*90 translate <0.5, 0, 1> translate } + #end + #if (East_Walls[R][C]) + object { Wall translate <1, 0, 0.5> translate } + #end + #end + #end + translate <-0.5*Cols, 0, 0> // Centre maze on x=0 + } +#end + +camera { + location <0, 13, -2> + right x*image_width/image_height + look_at <0, 2, 5> +} + +light_source { + <-0.1*Cols, Rows, 0.5*Rows>, colour rgb <1, 1, 1> + area_light + x, y, 3, 3 + circular orient +} + +box { + <-0.5*Cols, -0.1, 0>, <0.5*Cols, 0, Rows> + texture { + pigment { + checker colour rgb <0, 0.3, 0> colour rgb <0, 0.4, 0> + scale 0.5 + } + finish { specular 0.5 reflection { 0.1 } } + } +} + +#declare Visited = array[Rows][Cols]; +#declare North_Walls = array[Rows][Cols]; +#declare East_Walls = array[Rows][Cols]; + +Initialise(Visited, North_Walls, East_Walls) +Generate_Maze(Visited, North_Walls, East_Walls) +Draw_Maze(North_Walls, East_Walls) diff --git a/Task/Maze-generation/PascalABC.NET/maze-generation.pas b/Task/Maze-generation/PascalABC.NET/maze-generation.pas new file mode 100644 index 0000000000..5291470844 --- /dev/null +++ b/Task/Maze-generation/PascalABC.NET/maze-generation.pas @@ -0,0 +1,29 @@ +const + w = 14; + h = 10; + +var + vis := (0..h - 1).Select(x -> [false] * w).ToArray; + hor := (0..h).select(x -> ['+---'] * w + [string('+')]).ToArray; + ver := (0..h - 1).select(x -> ['| '] * w + [string('|')]).ToArray; + +procedure walk(x, y: integer); +begin + vis[y][x] := true; + foreach var p in ||x - 1, y|, |x, y + 1|, |x + 1, y|, |x, y - 1||.Shuffle do + begin + if (p[0] not in (0..w - 1)) or (p[1] not in (0..h - 1)) or vis[p[1]][p[0]] then continue; + if p[0] = x then hor[max(y, p[1])][x] := '+ '; + if p[1] = y then ver[y][max(x, p[0])] := ' '; + walk(p[0], p[1]); + end; +end; + +begin + walk(random(w), random(h)); + foreach var (a, b) in hor.zip(ver + [''], (x, y) -> (x, y)) do + begin + a.println(''); + b.println(''); + end; +end. diff --git a/Task/Maze-generation/Perl/maze-generation.pl b/Task/Maze-generation/Perl/maze-generation.pl index 7e50c2b71e..15d494dea0 100644 --- a/Task/Maze-generation/Perl/maze-generation.pl +++ b/Task/Maze-generation/Perl/maze-generation.pl @@ -11,26 +11,26 @@ my @ver = map([("| ") x $w], 1 .. $h); my @hor = map([("+--") x $w], 0 .. $h); sub walk { - my ($x, $y) = @_; - $cell[$y][$x] = ''; - $avail-- or return; # no more bottles, er, cells + my ($x, $y) = @_; + $cell[$y][$x] = ''; + $avail-- or return; # no more bottles, er, cells - my @d = ([-1, 0], [0, 1], [1, 0], [0, -1]); - while (@d) { - my $i = splice @d, int(rand @d), 1; - my ($x1, $y1) = ($x + $i->[0], $y + $i->[1]); + my @d = ([-1, 0], [0, 1], [1, 0], [0, -1]); + while (@d) { + my $i = splice @d, int(rand @d), 1; + my ($x1, $y1) = ($x + $i->[0], $y + $i->[1]); - $cell[$y1][$x1] or next; + $cell[$y1][$x1] or next; - if ($x == $x1) { $hor[ max($y1, $y) ][$x] = '+ ' } - if ($y == $y1) { $ver[$y][ max($x1, $x) ] = ' ' } - walk($x1, $y1); - } + if ($x == $x1) { $hor[ max($y1, $y) ][$x] = '+ ' } + if ($y == $y1) { $ver[$y][ max($x1, $x) ] = ' ' } + walk($x1, $y1); + } } -walk(int rand $w, int rand $h); # generate +walk(int rand $w, int rand $h); # generate -for (0 .. $h) { # display - print @{$hor[$_]}, "+\n"; - print @{$ver[$_]}, "|\n" if $_ < $h; +for (0 .. $h) { # display + print @{$hor[$_]}, "+\n"; + print @{$ver[$_]}, "|\n" if $_ < $h; } diff --git a/Task/Maze-generation/Prolog/maze-generation.pro b/Task/Maze-generation/Prolog/maze-generation.pro index 96c781a476..05698deafa 100644 --- a/Task/Maze-generation/Prolog/maze-generation.pro +++ b/Task/Maze-generation/Prolog/maze-generation.pro @@ -1,89 +1,89 @@ :- dynamic cell/2. maze(Lig,Col) :- - retractall(cell(_,_)), + retractall(cell(_,_)), - new(D, window('Maze')), + new(D, window('Maze')), - % creation of the grid - forall(between(0,Lig, I), - (XL is 50, YL is I * 30 + 50, - XR is Col * 30 + 50, - new(L, line(XL, YL, XR, YL)), - send(D, display, L))), + % creation of the grid + forall(between(0,Lig, I), + (XL is 50, YL is I * 30 + 50, + XR is Col * 30 + 50, + new(L, line(XL, YL, XR, YL)), + send(D, display, L))), - forall(between(0,Col, I), - (XT is 50 + I * 30, YT is 50, - YB is Lig * 30 + 50, - new(L, line(XT, YT, XT, YB)), - send(D, display, L))), + forall(between(0,Col, I), + (XT is 50 + I * 30, YT is 50, + YB is Lig * 30 + 50, + new(L, line(XT, YT, XT, YB)), + send(D, display, L))), - SX is Col * 30 + 100, - SY is Lig * 30 + 100, - send(D, size, new(_, size(SX, SY))), + SX is Col * 30 + 100, + SY is Lig * 30 + 100, + send(D, size, new(_, size(SX, SY))), - % choosing a first cell - L0 is random(Lig), - C0 is random(Col), - assert(cell(L0, C0)), - \+search(D, Lig, Col, L0, C0), - send(D, open). + % choosing a first cell + L0 is random(Lig), + C0 is random(Col), + assert(cell(L0, C0)), + \+search(D, Lig, Col, L0, C0), + send(D, open). search(D, Lig, Col, L, C) :- - Dir is random(4), - nextcell(Dir, Lig, Col, L, C, L1, C1), - assert(cell(L1,C1)), - assert(cur(L1,C1)), - erase_line(D, L, C, L1, C1), - search(D, Lig, Col, L1, C1). + Dir is random(4), + nextcell(Dir, Lig, Col, L, C, L1, C1), + assert(cell(L1,C1)), + assert(cur(L1,C1)), + erase_line(D, L, C, L1, C1), + search(D, Lig, Col, L1, C1). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% erase_line(D, L, C, L, C1) :- - ( C < C1 -> C2 = C1; C2 = C), - XT is C2 * 30 + 50, - YT is L * 30 + 51, YR is (L+1) * 30 + 50, - new(Line, line(XT, YT, XT, YR)), - send(Line, colour, white), - send(D, display, Line). + ( C < C1 -> C2 = C1; C2 = C), + XT is C2 * 30 + 50, + YT is L * 30 + 51, YR is (L+1) * 30 + 50, + new(Line, line(XT, YT, XT, YR)), + send(Line, colour, white), + send(D, display, Line). erase_line(D, L, C, L1, C) :- - XT is 51 + C * 30, XR is 50 + (C + 1) * 30, - ( L < L1 -> L2 is L1; L2 is L), - YT is L2 * 30 + 50, - new(Line, line(XT, YT, XR, YT)), - send(Line, colour, white), - send(D, display, Line). + XT is 51 + C * 30, XR is 50 + (C + 1) * 30, + ( L < L1 -> L2 is L1; L2 is L), + YT is L2 * 30 + 50, + new(Line, line(XT, YT, XR, YT)), + send(Line, colour, white), + send(D, display, Line). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% nextcell(Dir, Lig, Col, L, C, L1, C1) :- - next(Dir, Lig, Col, L, C, L1, C1); - ( Dir1 is (Dir+3) mod 4, - next(Dir1, Lig, Col, L, C, L1, C1)); - ( Dir2 is (Dir+1) mod 4, - next(Dir2, Lig, Col, L, C, L1, C1)); - ( Dir3 is (Dir+2) mod 4, - next(Dir3, Lig, Col, L, C, L1, C1)). + next(Dir, Lig, Col, L, C, L1, C1); + ( Dir1 is (Dir+3) mod 4, + next(Dir1, Lig, Col, L, C, L1, C1)); + ( Dir2 is (Dir+1) mod 4, + next(Dir2, Lig, Col, L, C, L1, C1)); + ( Dir3 is (Dir+2) mod 4, + next(Dir3, Lig, Col, L, C, L1, C1)). % 0 => northward next(0, _Lig, _Col, L, C, L1, C) :- - L > 0, - L1 is L - 1, - \+cell(L1, C). + L > 0, + L1 is L - 1, + \+cell(L1, C). % 1 => rightward next(1, _Lig, Col, L, C, L, C1) :- - C < Col - 1, - C1 is C + 1, - \+cell(L, C1). + C < Col - 1, + C1 is C + 1, + \+cell(L, C1). % 2 => southward next(2, Lig, _Col, L, C, L1, C) :- - L < Lig - 1, - L1 is L + 1, - \+cell(L1, C). + L < Lig - 1, + L1 is L + 1, + \+cell(L1, C). % 3 => leftward next(2, _Lig, _Col, L, C, L, C1) :- - C > 0, - C1 is C - 1, - \+cell(L, C1). + C > 0, + C1 is C - 1, + \+cell(L, C1). diff --git a/Task/Maze-generation/Raku/maze-generation.raku b/Task/Maze-generation/Raku/maze-generation.raku index 7bfc626ec9..a9640723fa 100644 --- a/Task/Maze-generation/Raku/maze-generation.raku +++ b/Task/Maze-generation/Raku/maze-generation.raku @@ -1,21 +1,21 @@ constant mapping = :OPEN(' '), - :N< ╵ >, - :E< ╶ >, - :NE< └ >, - :S< ╷ >, - :NS< │ >, - :ES< ┌ >, - :NES< ├ >, - :W< ╴ >, - :NW< ┘ >, - :EW< ─ >, - :NEW< ┴ >, - :SW< ┐ >, - :NSW< ┤ >, - :ESW< ┬ >, - :NESW< ┼ >, - :TODO< x >, - :TRIED< · >; + :N< ╵ >, + :E< ╶ >, + :NE< └ >, + :S< ╷ >, + :NS< │ >, + :ES< ┌ >, + :NES< ├ >, + :W< ╴ >, + :NW< ┘ >, + :EW< ─ >, + :NEW< ┴ >, + :SW< ┐ >, + :NSW< ┤ >, + :ESW< ┬ >, + :NESW< ┼ >, + :TODO< x >, + :TRIED< · >; enum Sym (mapping.map: *.key); my @ch = mapping.map: *.value; @@ -31,8 +31,8 @@ sub gen_maze ( $X, push @maze, $[ flat ES, -N, (ESW, EW) xx $X - 1, SW ]; push @maze, $[ flat (NS, TODO) xx $X, NS ]; for 1 ..^ $Y { - push @maze, $[ flat NES, EW, (NESW, EW) xx $X - 1, NSW ]; - push @maze, $[ flat (NS, TODO) xx $X, NS ]; + push @maze, $[ flat NES, EW, (NESW, EW) xx $X - 1, NSW ]; + push @maze, $[ flat (NS, TODO) xx $X, NS ]; } push @maze, $[ flat NE, (EW, NEW) xx $X - 1, -NS, NW ]; @maze[$start_y][$start_x] = OPEN; @@ -52,35 +52,35 @@ sub gen_maze ( $X, return @maze; sub pick_direction([$x,$y]) { - my @neighbors = - (Up if @maze[$y - 2][$x]), - (Down if @maze[$y + 2][$x]), - (Left if @maze[$y][$x - 2]), - (Right if @maze[$y][$x + 2]); - @neighbors.pick or DeadEnd; + my @neighbors = + (Up if @maze[$y - 2][$x]), + (Down if @maze[$y + 2][$x]), + (Left if @maze[$y][$x - 2]), + (Right if @maze[$y][$x + 2]); + @neighbors.pick or DeadEnd; } sub move ($dir, @cur) { - my ($x,$y) = @cur; - given $dir { - when Up { @maze[--$y][$x] = OPEN; @maze[$y][$x-1] -= E; @maze[$y--][$x+1] -= W; } - when Down { @maze[++$y][$x] = OPEN; @maze[$y][$x-1] -= E; @maze[$y++][$x+1] -= W; } - when Left { @maze[$y][--$x] = OPEN; @maze[$y-1][$x] -= S; @maze[$y+1][$x--] -= N; } - when Right { @maze[$y][++$x] = OPEN; @maze[$y-1][$x] -= S; @maze[$y+1][$x++] -= N; } - } - @maze[$y][$x] = 0; - [$x,$y]; + my ($x,$y) = @cur; + given $dir { + when Up { @maze[--$y][$x] = OPEN; @maze[$y][$x-1] -= E; @maze[$y--][$x+1] -= W; } + when Down { @maze[++$y][$x] = OPEN; @maze[$y][$x-1] -= E; @maze[$y++][$x+1] -= W; } + when Left { @maze[$y][--$x] = OPEN; @maze[$y-1][$x] -= S; @maze[$y+1][$x--] -= N; } + when Right { @maze[$y][++$x] = OPEN; @maze[$y-1][$x] -= S; @maze[$y+1][$x++] -= N; } + } + @maze[$y][$x] = 0; + [$x,$y]; } } sub display (@maze) { for @maze -> @y { - for @y.rotor(2) -> ($w, $c) { - print @ch[abs $w]; - if $c >= 0 { print @ch[$c] x 3 } - else { print ' ', @ch[abs $c], ' ' } - } - say @ch[@y[*-1]]; + for @y.rotor(2) -> ($w, $c) { + print @ch[abs $w]; + if $c >= 0 { print @ch[$c] x 3 } + else { print ' ', @ch[abs $c], ' ' } + } + say @ch[@y[*-1]]; } } diff --git a/Task/Maze-generation/Rascal/maze-generation.rascal b/Task/Maze-generation/Rascal/maze-generation.rascal index c93215aaf5..5f06309c30 100644 --- a/Task/Maze-generation/Rascal/maze-generation.rascal +++ b/Task/Maze-generation/Rascal/maze-generation.rascal @@ -3,27 +3,27 @@ import util::Math; import List; public void make_maze(int w, int h){ - vis = [[0 | _ <- [1..w]] | _ <- [1..h]]; - ver = [["| "| _ <- [1..w]] + ["|"] | _ <- [1..h]] + [[]]; - hor = [["+--"| _ <- [1..w]] + ["+"] | _ <- [1..h + 1]]; + vis = [[0 | _ <- [1..w]] | _ <- [1..h]]; + ver = [["| "| _ <- [1..w]] + ["|"] | _ <- [1..h]] + [[]]; + hor = [["+--"| _ <- [1..w]] + ["+"] | _ <- [1..h + 1]]; - void walk(int x, int y){ - vis[y][x] = 1; + void walk(int x, int y){ + vis[y][x] = 1; - d = [, , , ]; - while (d != []){ - <, d> = takeOneFrom(d); - if (xx < 0 || yy < 0 || xx >= w || yy >= w) continue; - if (vis[yy][xx] == 1) continue; - if (xx == x) hor[max([y, yy])][x] = "+ "; - if (yy == y) ver[y][max([x, xx])] = " "; - walk(xx, yy); - } - } - - walk(arbInt(w), arbInt(h)); - for ( <- zip(hor, ver)){ - println(("" | it + "" | z <- a)); - println(("" | it + "" | z <- b)); - } + d = [, , , ]; + while (d != []){ + <, d> = takeOneFrom(d); + if (xx < 0 || yy < 0 || xx >= w || yy >= w) continue; + if (vis[yy][xx] == 1) continue; + if (xx == x) hor[max([y, yy])][x] = "+ "; + if (yy == y) ver[y][max([x, xx])] = " "; + walk(xx, yy); + } + } + + walk(arbInt(w), arbInt(h)); + for ( <- zip(hor, ver)){ + println(("" | it + "" | z <- a)); + println(("" | it + "" | z <- b)); + } } diff --git a/Task/Maze-generation/Rebol/maze-generation.rebol b/Task/Maze-generation/Rebol/maze-generation.rebol new file mode 100644 index 0000000000..069125488e --- /dev/null +++ b/Task/Maze-generation/Rebol/maze-generation.rebol @@ -0,0 +1,72 @@ +Rebol [ + title: "Rosetta code: Maze generation" + file: %Maze_generation.r3 + url: https://rosettacode.org/wiki/Maze_generation +] + +make-maze: function/with [ + width [integer!] + height [integer!] +][ + clear visited + clear walls + clear exploring + + size: as-pair width height + append/dup walls 1x1 width * height + repend exploring [random size - 1x1] + + until [ + expand exploring/1 + empty? exploring + ] + reduce [width height copy walls] +][ + size: _ visited: [] walls: [] exploring: [] + offsetof: function [pos] [pos/y * size/x + pos/x + 1] + visited?: function [pos] [find visited pos] + + newneighbour: function [pos][ + nnbs: collect [ + if all [pos/x > 0 not visited? p: pos - 1x0] [keep p] + if all [pos/x < (size/x - 1) not visited? p: pos + 1x0] [keep p] + if all [pos/y > 0 not visited? p: pos - 0x1] [keep p] + if all [pos/y < (size/y - 1) not visited? p: pos + 0x1] [keep p] + ] + pick nnbs random length? nnbs + ] + expand: function [pos][ + insert visited pos + either npos: newneighbour pos [ + insert exploring npos + do select [ + 0x-1 [o: offsetof npos walls/:o/y: 0] + 1x0 [o: offsetof pos walls/:o/x: 0] + 0x1 [o: offsetof pos walls/:o/y: 0] + -1x0 [o: offsetof npos walls/:o/x: 0] + ] npos - pos + ][ + remove exploring + ] + ] +] + +draw-maze: function[spec][ + set [cols: rows: walls:] spec + out: copy "" + append/dup out " _" cols + append out LF + repeat j rows [ + append out "|" + repeat i cols [ + p: pick walls (j - 1 * cols + i) + append out ajoin [pick " _" 1 + p/y pick " |" 1 + p/x] + ] + append out LF + ] + copy out +] + +random/seed now/time +maze: make-maze 15 15 +print draw-maze maze diff --git a/Task/Maze-generation/Red/maze-generation.red b/Task/Maze-generation/Red/maze-generation.red index 56ea2a91e3..49e4d4cb64 100644 --- a/Task/Maze-generation/Red/maze-generation.red +++ b/Task/Maze-generation/Red/maze-generation.red @@ -6,43 +6,43 @@ offsetof: function [pos] [pos/y * size/x + pos/x + 1] visited?: function [pos] [find visited pos] newneighbour: function [pos][ - nnbs: collect [ - if all [pos/x > 0 not visited? p: pos - 1x0] [keep p] - if all [pos/x < (size/x - 1) not visited? p: pos + 1x0] [keep p] - if all [pos/y > 0 not visited? p: pos - 0x1] [keep p] - if all [pos/y < (size/y - 1) not visited? p: pos + 0x1] [keep p] - ] - pick nnbs random length? nnbs + nnbs: collect [ + if all [pos/x > 0 not visited? p: pos - 1x0] [keep p] + if all [pos/x < (size/x - 1) not visited? p: pos + 1x0] [keep p] + if all [pos/y > 0 not visited? p: pos - 0x1] [keep p] + if all [pos/y < (size/y - 1) not visited? p: pos + 0x1] [keep p] + ] + pick nnbs random length? nnbs ] -expand: function [pos][ - insert visited pos - either npos: newneighbour pos [ - insert exploring npos - do select [ - 0x-1 [o: offsetof npos walls/:o/y: 0] - 1x0 [o: offsetof pos walls/:o/x: 0] - 0x1 [o: offsetof pos walls/:o/y: 0] - -1x0 [o: offsetof npos walls/:o/x: 0] - ] npos - pos - ][ - remove exploring - ] +expand: function [pos][ + insert visited pos + either npos: newneighbour pos [ + insert exploring npos + do select [ + 0x-1 [o: offsetof npos walls/:o/y: 0] + 1x0 [o: offsetof pos walls/:o/x: 0] + 0x1 [o: offsetof pos walls/:o/y: 0] + -1x0 [o: offsetof npos walls/:o/x: 0] + ] npos - pos + ][ + remove exploring + ] ] visited: [] walls: append/dup [] 1x1 size/x * size/y exploring: reduce [random size - 1x1] until [ - expand exploring/1 - empty? exploring + expand exploring/1 + empty? exploring ] print append/dup "" " _" size/x repeat j size/y [ - prin "|" - repeat i size/x [ - p: pick walls (j - 1 * size/x + i) - prin rejoin [pick " _" 1 + p/y pick " |" 1 + p/x] - ] - print "" + prin "|" + repeat i size/x [ + p: pick walls (j - 1 * size/x + i) + prin rejoin [pick " _" 1 + p/y pick " |" 1 + p/x] + ] + print "" ] diff --git a/Task/Maze-generation/Rust/maze-generation.rust b/Task/Maze-generation/Rust/maze-generation.rs similarity index 100% rename from Task/Maze-generation/Rust/maze-generation.rust rename to Task/Maze-generation/Rust/maze-generation.rs diff --git a/Task/Maze-generation/SuperCollider/maze-generation.sc b/Task/Maze-generation/SuperCollider/maze-generation.sc index ff87b490d6..28c41ae80f 100644 --- a/Task/Maze-generation/SuperCollider/maze-generation.sc +++ b/Task/Maze-generation/SuperCollider/maze-generation.sc @@ -3,32 +3,32 @@ ~grid = { 0 ! 60 } ! 60; ~at = { |coord| - var col = ~grid.at(coord[0]); - if(col.notNil) { col.at(coord[1]) } + var col = ~grid.at(coord[0]); + if(col.notNil) { col.at(coord[1]) } }; ~put = { |coord, value| - var col = ~grid.at(coord[0]); - if(col.notNil) { col.put(coord[1], value) } + var col = ~grid.at(coord[0]); + if(col.notNil) { col.put(coord[1], value) } }; ~coord = ~grid.shape.rand; ~next = { |p| - var possible = [p] + [[0, 1], [1, 0], [-1, 0], [0, -1]]; - possible = possible.select { |x| - var c = ~at.(x); - c.notNil and: { c == 0 } - }; - possible.choose + var possible = [p] + [[0, 1], [1, 0], [-1, 0], [0, -1]]; + possible = possible.select { |x| + var c = ~at.(x); + c.notNil and: { c == 0 } + }; + possible.choose }; ~walkN = { |p, scale| - var next = ~next.(p); - if(next.notNil) { - ~put.(next, 1); - Pen.lineTo(~topoint.(next, scale)); - ~walkN.(next, scale); - ~walkN.(next, scale); - Pen.moveTo(~topoint.(p, scale)); - }; + var next = ~next.(p); + if(next.notNil) { + ~put.(next, 1); + Pen.lineTo(~topoint.(next, scale)); + ~walkN.(next, scale); + ~walkN.(next, scale); + Pen.moveTo(~topoint.(p, scale)); + }; }; ~topoint = { |c, scale| (c + [1, 1] * scale).asPoint }; @@ -44,13 +44,13 @@ w = Window("so-a-mazing", b); w.view.background_(Color.black); w.drawFunc = { - var p = ~grid.shape.rand; - var scale = b.width / ~grid.size * 0.98; - Pen.moveTo(~topoint.(p, scale)); - ~walkN.(p, scale); - Pen.width = scale / 4; - Pen.color = Color.white; - Pen.stroke; + var p = ~grid.shape.rand; + var scale = b.width / ~grid.size * 0.98; + Pen.moveTo(~topoint.(p, scale)); + ~walkN.(p, scale); + Pen.width = scale / 4; + Pen.color = Color.white; + Pen.stroke; }; w.front.refresh; ) diff --git a/Task/Maze-generation/Tcl/maze-generation.tcl b/Task/Maze-generation/Tcl/maze-generation.tcl index 27048ba4b7..ee1f22d880 100644 --- a/Task/Maze-generation/Tcl/maze-generation.tcl +++ b/Task/Maze-generation/Tcl/maze-generation.tcl @@ -10,85 +10,85 @@ proc tcl::mathfunc::idx {v x y} {lindex $v $x $y} oo::class create maze { variable x y horiz verti content constructor {width height} { - set y $width - set x $height + set y $width + set x $height - set n [expr {$x * $y - 1}] - if {$n < 0} {error "illegal maze dimensions"} - set horiz [set verti [lrepeat $x [lrepeat $y 0]]] - # This matrix holds the output for the Maze Solving task; not used for generation - set content [lrepeat $x [lrepeat $y " "]] - set unvisited [lrepeat [expr {$x+2}] [lrepeat [expr {$y+2}] 0]] - # Helper to write into a list of lists (with offsets) - proc unvisited= {x y value} { - upvar 1 unvisited u - lset u [expr {$x+1}] [expr {$y+1}] $value - } + set n [expr {$x * $y - 1}] + if {$n < 0} {error "illegal maze dimensions"} + set horiz [set verti [lrepeat $x [lrepeat $y 0]]] + # This matrix holds the output for the Maze Solving task; not used for generation + set content [lrepeat $x [lrepeat $y " "]] + set unvisited [lrepeat [expr {$x+2}] [lrepeat [expr {$y+2}] 0]] + # Helper to write into a list of lists (with offsets) + proc unvisited= {x y value} { + upvar 1 unvisited u + lset u [expr {$x+1}] [expr {$y+1}] $value + } - lappend stack [set here [list [rand $x] [rand $y]]] - for {set j 0} {$j < $x} {incr j} { - for {set k 0} {$k < $y} {incr k} { - unvisited= $j $k [expr {$here ne [list $j $k]}] - } - } + lappend stack [set here [list [rand $x] [rand $y]]] + for {set j 0} {$j < $x} {incr j} { + for {set k 0} {$k < $y} {incr k} { + unvisited= $j $k [expr {$here ne [list $j $k]}] + } + } - while {0 < $n} { - lassign $here hx hy - set neighbours {} - foreach {dx dy} {1 0 0 1 -1 0 0 -1} { - if {idx($unvisited, $hx+$dx+1, $hy+$dy+1)} { - lappend neighbours [list [expr {$hx+$dx}] [expr {$hy+$dy}]] - } - } - if {[llength $neighbours]} { - lassign [set here [pick $neighbours]] nx ny - unvisited= $nx $ny 0 - if {$nx == $hx} { - lset horiz $nx [expr {min($ny, $hy)}] 1 - } else { - lset verti [expr {min($nx, $hx)}] $ny 1 - } - lappend stack $here - incr n -1 - } else { - set here [lindex $stack end] - set stack [lrange $stack 0 end-1] - } - } + while {0 < $n} { + lassign $here hx hy + set neighbours {} + foreach {dx dy} {1 0 0 1 -1 0 0 -1} { + if {idx($unvisited, $hx+$dx+1, $hy+$dy+1)} { + lappend neighbours [list [expr {$hx+$dx}] [expr {$hy+$dy}]] + } + } + if {[llength $neighbours]} { + lassign [set here [pick $neighbours]] nx ny + unvisited= $nx $ny 0 + if {$nx == $hx} { + lset horiz $nx [expr {min($ny, $hy)}] 1 + } else { + lset verti [expr {min($nx, $hx)}] $ny 1 + } + lappend stack $here + incr n -1 + } else { + set here [lindex $stack end] + set stack [lrange $stack 0 end-1] + } + } - rename unvisited= {} + rename unvisited= {} } # Maze displayer; takes a maze dictionary, returns a string method view {} { - set text {} - for {set j 0} {$j < $x*2+1} {incr j} { - set line {} - for {set k 0} {$k < $y*4+1} {incr k} { - if {$j%2 && $k%4==2} { - # At the centre of the cell, put the "content" of the cell - append line [expr {idx($content, $j/2, $k/4)}] - } elseif {$j%2 && ($k%4 || $k && idx($horiz, $j/2, $k/4-1))} { - append line " " - } elseif {$j%2} { - append line "|" - } elseif {0 == $k%4} { - append line "+" - } elseif {$j && idx($verti, $j/2-1, $k/4)} { - append line " " - } else { - append line "-" - } - } - if {!$j} { - lappend text [string replace $line 1 3 " "] - } elseif {$x*2-1 == $j} { - lappend text [string replace $line end end " "] - } else { - lappend text $line - } - } - return [join $text \n] + set text {} + for {set j 0} {$j < $x*2+1} {incr j} { + set line {} + for {set k 0} {$k < $y*4+1} {incr k} { + if {$j%2 && $k%4==2} { + # At the centre of the cell, put the "content" of the cell + append line [expr {idx($content, $j/2, $k/4)}] + } elseif {$j%2 && ($k%4 || $k && idx($horiz, $j/2, $k/4-1))} { + append line " " + } elseif {$j%2} { + append line "|" + } elseif {0 == $k%4} { + append line "+" + } elseif {$j && idx($verti, $j/2-1, $k/4)} { + append line " " + } else { + append line "-" + } + } + if {!$j} { + lappend text [string replace $line 1 3 " "] + } elseif {$x*2-1 == $j} { + lappend text [string replace $line end end " "] + } else { + lappend text $line + } + } + return [join $text \n] } } diff --git a/Task/Maze-generation/TypeScript/maze-generation-1.ts b/Task/Maze-generation/TypeScript/maze-generation-1.ts index 2a104a3c80..714d341417 100644 --- a/Task/Maze-generation/TypeScript/maze-generation-1.ts +++ b/Task/Maze-generation/TypeScript/maze-generation-1.ts @@ -1,26 +1,26 @@ interface mazeData{ - nodes:Node[] - x:number - y:number - blockSize:number + nodes:Node[] + x:number + y:number + blockSize:number } class Node{ - x:number - y:number - wallsTo:Node[] - visited = false - constructor(x:number,y:number){ - this.x = x - this.y = y - } - getTouchingNodes(nodes:Node[],blockSize:number){ + x:number + y:number + wallsTo:Node[] + visited = false + constructor(x:number,y:number){ + this.x = x + this.y = y + } + getTouchingNodes(nodes:Node[],blockSize:number){ return nodes.filter(n=> (this != n) && (Math.hypot(this.x-n.x,this.y-n.y) == blockSize ) ) } - draw(ctx:CanvasRenderingContext2D,blockSize:number){ + draw(ctx:CanvasRenderingContext2D,blockSize:number){ ctx.fillStyle ='black' this.wallsTo.forEach(el=>{ ctx.save() @@ -36,41 +36,41 @@ class Node{ } export function maze(x:number,y:number):mazeData { - let blockSize = 20 - x *= blockSize - y *= blockSize - let nodes = Array((x/blockSize)*(y/blockSize)).fill(0).map((_el,i)=> - new Node( - (i%(x/blockSize)*(blockSize))+(blockSize/2), - (Math.floor(i/(x/blockSize))*(blockSize))+(blockSize/2) - ) - ) - nodes.forEach(n=>n.wallsTo = n.getTouchingNodes(nodes,blockSize)) - let que = [nodes[0]] - while(que.length > 0){ - let current = que.shift() - let unvisited = current - .getTouchingNodes(nodes,blockSize) - .filter(el=>!el.visited) - if(unvisited.length >0){ - que.push(current) - let chosen = unvisited[Math.floor(Math.random()*unvisited.length)]; - current.wallsTo = current.wallsTo.filter((el)=>el != chosen) - chosen.wallsTo = chosen.wallsTo.filter((el)=>el != current) - chosen.visited = true - que.unshift(chosen) - } - } - return {x:x,y:y,nodes:nodes,blockSize:blockSize} + let blockSize = 20 + x *= blockSize + y *= blockSize + let nodes = Array((x/blockSize)*(y/blockSize)).fill(0).map((_el,i)=> + new Node( + (i%(x/blockSize)*(blockSize))+(blockSize/2), + (Math.floor(i/(x/blockSize))*(blockSize))+(blockSize/2) + ) + ) + nodes.forEach(n=>n.wallsTo = n.getTouchingNodes(nodes,blockSize)) + let que = [nodes[0]] + while(que.length > 0){ + let current = que.shift() + let unvisited = current + .getTouchingNodes(nodes,blockSize) + .filter(el=>!el.visited) + if(unvisited.length >0){ + que.push(current) + let chosen = unvisited[Math.floor(Math.random()*unvisited.length)]; + current.wallsTo = current.wallsTo.filter((el)=>el != chosen) + chosen.wallsTo = chosen.wallsTo.filter((el)=>el != current) + chosen.visited = true + que.unshift(chosen) + } + } + return {x:x,y:y,nodes:nodes,blockSize:blockSize} } export function display(c:HTMLCanvasElement,mazeData:mazeData){ - let ctx = c.getContext('2d') - c.width = mazeData.x - c.height = mazeData.y - ctx.fillStyle = 'white' - ctx.strokeStyle = 'black' - ctx.fillRect(0,0,mazeData.x,mazeData.y) - ctx.strokeRect(0,0,mazeData.x,mazeData.y) - mazeData.nodes.forEach(el=>el.draw(ctx,mazeData.blockSize)) + let ctx = c.getContext('2d') + c.width = mazeData.x + c.height = mazeData.y + ctx.fillStyle = 'white' + ctx.strokeStyle = 'black' + ctx.fillRect(0,0,mazeData.x,mazeData.y) + ctx.strokeRect(0,0,mazeData.x,mazeData.y) + mazeData.nodes.forEach(el=>el.draw(ctx,mazeData.blockSize)) } diff --git a/Task/Maze-generation/Uiua/maze-generation.uiua b/Task/Maze-generation/Uiua/maze-generation.uiua index 1138a832b7..b1576a0165 100644 --- a/Task/Maze-generation/Uiua/maze-generation.uiua +++ b/Task/Maze-generation/Uiua/maze-generation.uiua @@ -1,37 +1,29 @@ +# Build and solve a maze. +W ← 16 H ← 8 -W ← 18 -Ver ← 0 -Hor ← 1 -Vis ← 2 -BreakNS ← ⊂Ver⊂⊃(/↥≡⊡0|⊡0_1) -BreakEW ← ⊂Hor⊂⊃(⊡0_0|/↥≡⊡1) +GetWall ← -⊃⋅∘∘⊡1⊃⋅∘∘÷2⊸/- # ([here, next], maze) -> (maze') -BreakWall ← ⍜⊡(0◌)⟨BreakNS|BreakEW⟩=°⊟≡⊢. - -Neighbours ← +⊙¤[[¯1 0] [1 0] [0 1] [0 ¯1]] # Gives N4 -Shuffle ← ⊏⍏[⍥⚂]⧻. -IsVisited ← ¬⊡⊂Vis -MarkAsVisited ← ⟜(⍜(⊡|1◌)⊂Vis) -OnlyInBounds ← ▽≡IsVisited ⊙¤,, # (finds the boundary 1's) +BreakWall ← ⍜(⊡|⋅@ )GetWall +N₄ ← +⊙¤[¯2_0 2_0 0_2 0_¯2] +Shuffle ← ⊏⍏⍥⚂⊸⧻ +# (pos maze) -> T if it's already seen (or out of bounds). +IsVisited ← ≠@\s⬚@\s⊡ +MarkAsVisited ← ⟜(⍜⊡⋅@\s) # (here, maze) -> (maze') Walk ← |2 ( MarkAsVisited # (here, maze) -> ([[here, next] x(up to)4], maze) - ≡⊟¤⟜(Shuffle OnlyInBounds Neighbours) - + ≡⊟¤⟜(Shuffle N₄) # Update maze for each in turn. For each, if it # still isn't visited, break the wall, recurse into it. - ∧(⟨◌|Walk ⊡1 ⟜BreakWall⟩IsVisited◌°⊟,,) + ∧(⨬(◌|Walk⊡1⟜BreakWall)IsVisited◌°⊟⊃⊙∘⊙∘) ) -⊂↯H⊂↯W0 1↯+1W1 # vis (added 1's help bounds checks) -⊂↯H⊂↯W1 1↯+1W 0 # ver -↯+1H⊂↯W1 0 # hor -⊂⊟ -# Stack: ([hor, ver, vis]) -Walk [0 0] - -PP! ← ≡/⊂∵^! # Pretty print using switch. -≡(&p$"_\n_")⊃(PP!⟨"+ "|"+--"⟩⊡Ver|PP!⟨" "|"| "⟩⊡Hor) +# Generate a maze. +Maze ← ( + ↘¯1♭₂↯(+1H)⊟⊂/⊂↯W"+-" @+⊂/⊂↯W"|." @| # Build a filled maze. + Walk 1_1 # Walk around eating dots and breaking walls. +) +Maze diff --git a/Task/Maze-generation/V-(Vlang)/maze-generation.v b/Task/Maze-generation/V-(Vlang)/maze-generation.v new file mode 100644 index 0000000000..da761601e0 --- /dev/null +++ b/Task/Maze-generation/V-(Vlang)/maze-generation.v @@ -0,0 +1,93 @@ +import rand +import os + +struct Direction { + bit int + dx int + dy int +} + +struct MazeGenerator { + x int + y int + mut: + maze [][]int + directions []Direction + opposites map[int]Direction +} + +fn new_maze_generator(x int, y int) MazeGenerator { + mut maze := [][]int{len: x} + for i in 0 .. x { + maze[i] = []int{len: y, init: 0} + } + directions := [Direction{bit: 1, dx: 0, dy: -1}, Direction{bit: 2, dx: 0, dy: 1}, + Direction{bit: 4, dx: 1, dy: 0}, Direction{bit: 8, dx: -1, dy: 0}] + opposites := { + 1: directions[1] // N.opposite = S + 2: directions[0] // S.opposite = N + 4: directions[3] // E.opposite = W + 8: directions[2] // W.opposite = E + } + return MazeGenerator{ + x: x + y: y + maze: maze + directions: directions + opposites: opposites + } +} + +fn (mg MazeGenerator) between(v int, upper int) bool { + return v >= 0 && v < upper +} + +fn (mg MazeGenerator) directions_shuffled() ![]Direction { + mut dirs := mg.directions.clone() + rand.shuffle(mut dirs) or {0} + return dirs +} + +fn (mut mg MazeGenerator) generate(cx int, cy int) { + mut shuf := mg.directions_shuffled() or {return} + for dir in shuf { + nx := cx + dir.dx + ny := cy + dir.dy + if mg.between(nx, mg.x) && mg.between(ny, mg.y) && mg.maze[nx][ny] == 0 { + mg.maze[cx][cy] |= dir.bit + opp := mg.opposites[dir.bit] or { panic("Opposite direction not found") } + mg.maze[nx][ny] |= opp.bit + mg.generate(nx, ny) + } + } +} + +fn (mg MazeGenerator) display() { + for i in 0 .. mg.y { + for j in 0 .. mg.x { + if (mg.maze[j][i] & 1) == 0 { print("+---") } + else { print("+ ") } + } + println("+") + for j in 0 .. mg.x { + if (mg.maze[j][i] & 8) == 0 { print("| ") } + else { print(" ") } + } + println("|") + } + for _ in 0 .. mg.x { + print("+---") + } + println("+") +} + +fn main() { + args := os.args + mut x := 8 + mut y := 8 + mut mg := new_maze_generator(x, y) + if args.len >= 2 { x = args[1].int() } + if args.len >= 3 { y = args[2].int() } + mg.generate(0, 0) + mg.display() +} diff --git a/Task/Maze-generation/Zkl/maze-generation.zkl b/Task/Maze-generation/Zkl/maze-generation.zkl index c0183c93e7..8141aa008c 100644 --- a/Task/Maze-generation/Zkl/maze-generation.zkl +++ b/Task/Maze-generation/Zkl/maze-generation.zkl @@ -9,10 +9,10 @@ fcn make_maze(w = 16, h = 8){ d:=L(T(x - 1, y), T(x, y + 1), T(x + 1, y), T(x, y - 1)).shuffle(); foreach xx,yy in (d){ - if(vis[yy][xx]) continue; - if(xx==x) hor[y.max(yy)][x]="+ "; - if(yy==y) ver[y][x.max(xx)]=" "; - self.fcn(xx,yy,vis,ver,hor); + if(vis[yy][xx]) continue; + if(xx==x) hor[y.max(yy)][x]="+ "; + if(yy==y) ver[y][x.max(xx)]=" "; + self.fcn(xx,yy,vis,ver,hor); } }((0).random(w),(0).random(h),vis,ver,hor); foreach a,b in (hor.zip(ver)) { println(a.concat(),"\n",b.concat()) } diff --git a/Task/Maze-solving/Ada/maze-solving.ada b/Task/Maze-solving/Ada/maze-solving.adb similarity index 100% rename from Task/Maze-solving/Ada/maze-solving.ada rename to Task/Maze-solving/Ada/maze-solving.adb diff --git a/Task/Maze-solving/Delphi/maze-solving.delphi b/Task/Maze-solving/Delphi/maze-solving.pas similarity index 100% rename from Task/Maze-solving/Delphi/maze-solving.delphi rename to Task/Maze-solving/Delphi/maze-solving.pas diff --git a/Task/Maze-solving/EasyLang/maze-solving.easy b/Task/Maze-solving/EasyLang/maze-solving.easy index 29daa66062..def03f9799 100644 --- a/Task/Maze-solving/EasyLang/maze-solving.easy +++ b/Task/Maze-solving/EasyLang/maze-solving.easy @@ -3,27 +3,28 @@ n = 2 * size + 1 f = 100 / (n - 0.5) len m[] n * n # -background 000 -proc show_maze . . - clear +gbackground 000 +proc show_maze . + gclear + sz = f * 1.5 + f2 = f / 2 for i = 1 to len m[] if m[i] = 0 x = (i - 1) mod n y = (i - 1) div n - color 999 - move x * f - f / 2 y * f - f / 2 - rect f * 1.5 f * 1.5 + gcolor 999 + grect x * f - f2 y * f - f2 sz sz . . sleep 0.01 . offs[] = [ 1 n -1 (-n) ] -proc m_maze pos . . +proc m_maze pos . m[pos] = 0 show_maze d[] = [ 1 2 3 4 ] for i = 4 downto 1 - d = randint i + d = random 1 i dir = offs[d[d]] d[d] = d[i] if m[pos + dir] = 1 and m[pos + 2 * dir] = 1 @@ -33,42 +34,37 @@ proc m_maze pos . . . . endpos = n * n - 1 -proc make_maze . . - for i = 1 to len m[] - m[i] = 1 - . +proc make_maze . + for i = 1 to len m[] : m[i] = 1 for i = 1 to n m[i] = 2 m[n * i] = 2 m[n * i - n + 1] = 2 m[n * n - n + i] = 2 . - h = 2 * randint 15 - n + n * 2 * randint 15 + h = 2 * random 1 size - n + n * 2 * random 1 size m_maze h m[endpos] = 0 . make_maze show_maze # -proc mark pos col . . +proc mark pos col . x = (pos - 1) mod n y = (pos - 1) div n - color col - move x * f + f / 4 y * f + f / 4 - circle f / 3.5 + gcolor col + gcircle x * f + f / 4 y * f + f / 4 f / 3.5 . -global found . -proc solve dir0 pos . . - if found = 1 - return - . +found = 0 +proc solve dir0 pos . + if found = 1 : return mark pos 900 sleep 0.05 if pos = endpos found = 1 return . - of = randint 4 - 1 + of = random 0 3 for h = 1 to 4 dir = (h + of) mod1 4 posn = pos + offs[dir] diff --git a/Task/Maze-solving/Emacs-Lisp/maze-solving.l b/Task/Maze-solving/Emacs-Lisp/maze-solving.el similarity index 100% rename from Task/Maze-solving/Emacs-Lisp/maze-solving.l rename to Task/Maze-solving/Emacs-Lisp/maze-solving.el diff --git a/Task/Maze-solving/FreeBASIC/maze-solving.basic b/Task/Maze-solving/FreeBASIC/maze-solving.basic new file mode 100644 index 0000000000..9971576799 --- /dev/null +++ b/Task/Maze-solving/FreeBASIC/maze-solving.basic @@ -0,0 +1,95 @@ +Const MazeWidth = 11 +Const MazeHeight = 9 +Const MazeCell = 50 + +Dim Shared dstx As Integer = MazeWidth - 1 +Dim Shared dsty As Integer = 0 + +Screenres MazeWidth * MazeCell, MazeHeight * MazeCell, 32 +Windowtitle "Maze solving" + +Sub Cell(Maze() As Integer, Byval x As Integer, Byval y As Integer, Byval w As Integer, Byval h As Integer, Byval s As Integer) + Dim As Integer i, p, q, r + Maze(x, y) Or= &H40 + r = Rnd * 4 + For i = r To r + 3 + Select Case i Mod 4 + Case 0: p = x - 1 : q = y + Case 1: p = x + 1 : q = y + Case 2: p = x : q = y - 1 + Case 3: p = x : q = y + 1 + End Select + If p >= 0 And p < w And q >= 0 And q < h And Maze(p, q) < &H40 Then + If p > x Then Maze(p, q) Or= 1 : Line (p * s, y * s + 4) - (p * s, (y + 1) * s - 4), Rgb(0, 0, 0) + If q > y Then Maze(p, q) Or= 2 : Line (x * s + 4, q * s) - ((x + 1) * s - 4, q * s), Rgb(0, 0, 0) + If x > p Then Maze(x, y) Or= 1 : Line (x * s, y * s + 4) - (x * s, (y + 1) * s - 4), Rgb(0, 0, 0) + If y > q Then Maze(x, y) Or= 2 : Line (x * s + 4, y * s) - ((x + 1) * s - 4, y * s), Rgb(0, 0, 0) + Cell Maze(), p, q, w, h, s + End If + Next +End Sub + +Sub GenerateMaze(Maze() As Integer, Byval w As Integer, Byval h As Integer, Byval s As Integer) + Dim As Integer x, y + Redim Maze(w, h) + For y = 0 To h - 1 + Line (0, y * s) - (w * s, y * s), Rgb(255, 255, 255) + Next + For x = 0 To w - 1 + Line (x * s, 0) - (x * s, h * s), Rgb(255, 255, 255) + Next + Cell Maze(), Rnd * w, Rnd * h, w, h, s +End Sub + +Sub SolveMaze(Path() As Integer, Maze() As Integer, Byval x As Integer, Byval y As Integer, Byval dstx As Integer, Byval dsty As Integer, Byval s As Integer) + Dim As Integer h, i, n, p, q, w + w = Ubound(Maze, 1) + h = Ubound(Maze, 2) + Redim Path(w * h, 1) + Maze(x, y) Or= &H80 + Do + For i = 0 To 3 + Select Case i + Case 0: p = x - 1 : q = y + Case 1: p = x + 1 : q = y + Case 2: p = x : q = y - 1 + Case 3: p = x : q = y + 1 + End Select + If p >= 0 And p < w And q >= 0 And q < h And Maze(p, q) < &H80 Then + If p > x And Maze(p, q) And 1 Then Exit For + If q > y And Maze(p, q) And 2 Then Exit For + If x > p And Maze(x, y) And 1 Then Exit For + If y > q And Maze(x, y) And 2 Then Exit For + End If + Next + If i < 4 Then + Maze(p, q) Or= &H80 + Path(n, 0) = x + Path(n, 1) = y + Line ((x + 0.5) * s, (y + 0.5) * s) - ((p + 0.5) * s, (q + 0.5) * s), Rgb(255, 0, 0), , &b0001111111111100 + n += 1 + Else + If n > 0 Then + n -= 1 + p = Path(n, 0) + q = Path(n, 1) + Line ((x + 0.5) * s, (y + 0.5) * s) - ((p + 0.5) * s, (q + 0.5) * s), Rgb(0, 0, 0) + End If + End If + x = p + y = q + Sleep 200 + Loop Until x = dstx And y = dsty Or Inkey <> "" + Path(n, 0) = x + Path(n, 1) = y +End Sub + +Dim Maze() As Integer +Dim Path() As Integer + +Randomize Timer +GenerateMaze(Maze(), MazeWidth, MazeHeight, MazeCell) +SolveMaze(Path(), Maze(), 0, MazeHeight - 1, MazeWidth - 1, 0, MazeCell) +Windowtitle "Maze solving ** RESOLVED **" + +Sleep diff --git a/Task/Maze-solving/Julia/maze-solving.julia b/Task/Maze-solving/Julia/maze-solving.jl similarity index 100% rename from Task/Maze-solving/Julia/maze-solving.julia rename to Task/Maze-solving/Julia/maze-solving.jl diff --git a/Task/Maze-solving/Kotlin/maze-solving.kotlin b/Task/Maze-solving/Kotlin/maze-solving.kts similarity index 100% rename from Task/Maze-solving/Kotlin/maze-solving.kotlin rename to Task/Maze-solving/Kotlin/maze-solving.kts diff --git a/Task/Maze-solving/Rust/maze-solving.rust b/Task/Maze-solving/Rust/maze-solving.rs similarity index 100% rename from Task/Maze-solving/Rust/maze-solving.rust rename to Task/Maze-solving/Rust/maze-solving.rs diff --git a/Task/Maze-solving/Uiua/maze-solving.uiua b/Task/Maze-solving/Uiua/maze-solving.uiua new file mode 100644 index 0000000000..2cf1bb8828 --- /dev/null +++ b/Task/Maze-solving/Uiua/maze-solving.uiua @@ -0,0 +1,8 @@ +~ "maze-generation.ua" ~ GetWall H Maze N₄ W +Maze +Start ← 1_1 +End ← -Start ×2 H_W +# (pos grid) -> 1-4 next steps, without walls in the way. +Ns ← ≡⊡1▽:⟜(≡(=@ ⊡)⊙¤≡GetWall)≡⊟¤⊃⋅∘∘ ⊸N₄ +path(Ns|≍End) Start # Solve (djikstra) +$"_ moves"⧻⟜(∧⍜⊡⋅@O)⊢ diff --git a/Task/Maze-solving/V-(Vlang)/maze-solving.v b/Task/Maze-solving/V-(Vlang)/maze-solving.v new file mode 100644 index 0000000000..b38728d8a5 --- /dev/null +++ b/Task/Maze-solving/V-(Vlang)/maze-solving.v @@ -0,0 +1,189 @@ +import rand +import os + +struct Direction { + bit int + dx int + dy int +} + +type Maze = [][]int + +struct MazeGenerator { + x int + y int + mut: + maze Maze + directions []Direction + opposites map[int]Direction + solution [][]bool +} + +fn new_maze_generator(x int, y int) MazeGenerator { + mut maze := [][]int{len: x} + for i in 0 .. x { + maze[i] = []int{len: y, init: 0} + } + mut solution := [][]bool{len: x} + for i in 0 .. x { + solution[i] = []bool{len: y, init: false} + } + directions := [ + Direction{bit: 1, dx: 0, dy: -1}, // N + Direction{bit: 2, dx: 0, dy: 1}, // S + Direction{bit: 4, dx: 1, dy: 0}, // E + Direction{bit: 8, dx: -1, dy: 0}, // W + ] + opposites := { + 1: directions[1] // N.opposite = S + 2: directions[0] // S.opposite = N + 4: directions[3] // E.opposite = W + 8: directions[2] // W.opposite = E + } + return MazeGenerator{ + x: x + y: y + maze: maze + directions: directions + opposites: opposites + solution: solution + } +} + +fn (mg MazeGenerator) between(v int, upper int) bool { + return v >= 0 && v < upper +} + +fn (mg MazeGenerator) directions_shuffled() ![]Direction { + mut dirs := mg.directions.clone() + rand.shuffle(mut dirs) or { return error("Shuffle failed") } + return dirs +} + +fn (mut mg MazeGenerator) generate(cx int, cy int) { + mut shuf := mg.directions_shuffled() or { panic("Shuffle in generate failed") } + for dir in shuf { + nx := cx + dir.dx + ny := cy + dir.dy + if mg.between(nx, mg.x) && mg.between(ny, mg.y) && mg.maze[nx][ny] == 0 { + mg.maze[cx][cy] |= dir.bit + opp := mg.opposites[dir.bit] or { panic("Opposite direction not found") } + mg.maze[nx][ny] |= opp.bit + mg.generate(nx, ny) + } + } +} + +fn (mg MazeGenerator) to_char_maze() [][]rune { + width := mg.x * 2 + 1 + height := mg.y * 2 + 1 + mut char_maze := [][]rune{len: height, init: []rune{len: width, init: `#`}} + for y in 0 .. mg.y { + for x in 0 .. mg.x { + px := x * 2 + 1 + py := y * 2 + 1 + char_maze[py][px] = ` ` + cell := mg.maze[x][y] + if (cell & 1) != 0 { char_maze[py - 1][px] = ` ` } // N + if (cell & 2) != 0 { char_maze[py + 1][px] = ` ` } // S + if (cell & 4) != 0 { char_maze[py][px + 1] = ` ` } // E + if (cell & 8) != 0 { char_maze[py][px - 1] = ` ` } // W + } + } + return char_maze +} + +fn solve_maze_recursively(mut maze [][]rune, x int, y int, from_dir int) bool { + mut ok := false + for i := 0; i < 4 && !ok; i++ { + if i != from_dir { + match i { + 0 { + if y > 0 && maze[y - 1][x] == ` ` { + ok = solve_maze_recursively(mut maze, x, y - 2, 2) + } // up + } + 1 { + if x + 1 < maze[0].len && maze[y][x + 1] == ` ` { + ok = solve_maze_recursively(mut maze, x + 2, y, 3) + } // right + } + 2 { + if y + 1 < maze.len && maze[y + 1][x] == ` ` { + ok = solve_maze_recursively(mut maze, x, y + 2, 0) + } // down + } + 3 { + if x > 0 && maze[y][x - 1] == ` ` { + ok = solve_maze_recursively(mut maze, x - 2, y, 1) + } // left + } + else {} + } + } + } + if x == 1 && y == 1 { ok = true } + if ok { + maze[y][x] = `*` + match from_dir { + 0 { maze[y - 1][x] = `*` } + 1 { maze[y][x + 1] = `*` } + 2 { maze[y + 1][x] = `*` } + 3 { maze[y][x - 1] = `*` } + else {} + } + } + return ok +} + +// solve maze then link to original grid +fn (mut mg MazeGenerator) solve() { + mut char_maze := mg.to_char_maze() + solve_maze_recursively(mut char_maze, char_maze[0].len - 2, char_maze.len - 2, -1) + for y in 0 .. mg.y { + for x in 0 .. mg.x { + px := x * 2 + 1 + py := y * 2 + 1 + mg.solution[x][y] = char_maze[py][px] == `*` + } + } +} + +// display maze solution on original grid copy +fn (mg MazeGenerator) display() { + for i in 0 .. mg.y { + for j in 0 .. mg.x { + // North edge + if (mg.maze[j][i] & 1) == 0 { print("+---") } + else { print("+ ") } + } + println("+") + + for j in 0 .. mg.x { + mut cell_char := " " + if mg.solution[j][i] { cell_char = "*" } + if (mg.maze[j][i] & 8) == 0 { print("| $cell_char ") } + else { print(" $cell_char ") } + } + println("|") + } + for _ in 0 .. mg.x { + print("+---") + } + println("+") +} + +fn main() { + args := os.args + mut x := 8 + mut y := 8 + mut mg := new_maze_generator(x, y) + if args.len >= 2 { x = args[1].int() } + if args.len >= 3 { y = args[2].int() } + mg.generate(0, 0) + println("Generated Maze:") + mg.display() + mg.solve() + println("\nSolved Maze:") + mg.display() +} diff --git a/Task/McNuggets-problem/ALGOL-68/mcnuggets-problem.alg b/Task/McNuggets-problem/ALGOL-68/mcnuggets-problem.alg index 9c1b002b18..9b181f43d7 100644 --- a/Task/McNuggets-problem/ALGOL-68/mcnuggets-problem.alg +++ b/Task/McNuggets-problem/ALGOL-68/mcnuggets-problem.alg @@ -12,8 +12,8 @@ BEGIN OD # y # OD # x # ; # show the highest number that cannot be formed # - INT largest := -1; - FOR i FROM UPB sum BY -1 TO LWB sum WHILE sum[ largest := i ] DO SKIP OD; + INT largest := max nuggets; + WHILE sum[ largest ] DO largest -:= 1 OD; print( ( "The largest non McNugget number is: " , whole( largest, 0 ) , newline diff --git a/Task/McNuggets-problem/ALGOL-W/mcnuggets-problem.alg b/Task/McNuggets-problem/ALGOL-W/mcnuggets-problem.alg new file mode 100644 index 0000000000..0db3731f01 --- /dev/null +++ b/Task/McNuggets-problem/ALGOL-W/mcnuggets-problem.alg @@ -0,0 +1,25 @@ +begin % Solve the McNuggets problem: find the largest n <= 100 for which there % + % are no non-negative integers x, y, z such that 6x + 9y + 20z = n % + integer maxNuggets; + maxNuggets := 100; + begin + logical array isSum ( 0 :: maxNuggets ); + integer largest; + % find the numbers that can be formed % + for x := 0 step 6 until maxNuggets do begin + for y := x step 9 until maxNuggets do begin + for z := y step 20 until maxNuggets do isSum( z ) := true + end for_y + end for_x ; + % show the highest number that cannot be formed % + largest := -1; + for i := maxNuggets step -1 until 0 do begin + if not isSum( i ) then begin + largest := i; + goto foundLargest + end if_not_isSum_i + end for_i; +foundLargest: + write( i_w := 1, s_w := 0, "The largest non-McNugget number is: ", largest ) + end +end. diff --git a/Task/McNuggets-problem/Ada/mcnuggets-problem.ada b/Task/McNuggets-problem/Ada/mcnuggets-problem.adb similarity index 100% rename from Task/McNuggets-problem/Ada/mcnuggets-problem.ada rename to Task/McNuggets-problem/Ada/mcnuggets-problem.adb diff --git a/Task/McNuggets-problem/Agena/mcnuggets-problem.agena b/Task/McNuggets-problem/Agena/mcnuggets-problem.agena new file mode 100644 index 0000000000..70de20ecc0 --- /dev/null +++ b/Task/McNuggets-problem/Agena/mcnuggets-problem.agena @@ -0,0 +1,19 @@ +scope # Solve the McNuggets problem: find the largest n <= 100 for which there + # are no non-negative integers x, y, z such that 6x + 9y + 20z = n + + local constant maxNuggets := 100; + local sum := []; + for i from 0 to maxNuggets do sum[ i ] := false od; + for x from 0 to maxNuggets by 6 do + for y from x to maxNuggets by 9 do + for z from y to maxNuggets by 20 do + sum[ z ] := true + od + od + od; + # show the highest number that cannot be formed + local largest := maxNuggets; + while sum[ largest ] do largest -:= 1 od; + printf( "The largest non McNugget number is: %d\n", largest ) + +epocs diff --git a/Task/McNuggets-problem/Arturo/mcnuggets-problem.arturo b/Task/McNuggets-problem/Arturo/mcnuggets-problem.arturo index 747f5e8ea2..b6e1adc438 100644 --- a/Task/McNuggets-problem/Arturo/mcnuggets-problem.arturo +++ b/Task/McNuggets-problem/Arturo/mcnuggets-problem.arturo @@ -1,5 +1,5 @@ nonMcNuggets: function [lim][ - result: new 0..lim + result: @ 0..lim loop range.step:6 1 lim 'x [ loop range.step:9 1 lim 'y [ diff --git a/Task/McNuggets-problem/COBOL/mcnuggets-problem.cobol b/Task/McNuggets-problem/COBOL/mcnuggets-problem.cob similarity index 100% rename from Task/McNuggets-problem/COBOL/mcnuggets-problem.cobol rename to Task/McNuggets-problem/COBOL/mcnuggets-problem.cob diff --git a/Task/McNuggets-problem/EasyLang/mcnuggets-problem.easy b/Task/McNuggets-problem/EasyLang/mcnuggets-problem.easy index 16fb638242..ce971efedf 100644 --- a/Task/McNuggets-problem/EasyLang/mcnuggets-problem.easy +++ b/Task/McNuggets-problem/EasyLang/mcnuggets-problem.easy @@ -1,17 +1,12 @@ len l[] 100 -for a = 0 to 100 div 6 - for b = 0 to 100 div 9 - for c = 0 to 100 div 20 - n = a * 6 + b * 9 + c * 20 - if n >= 1 and n <= 100 - l[n] = 1 - . +for a = 0 step 6 to 100 + for b = 0 step 9 to 100 + for c = 0 step 20 to 100 + n = a + b + c + if n >= 1 and n <= 100 : l[n] = 1 . . . -for n = 100 downto 1 - if l[n] = 0 - print n - break 1 - . -. +n = 100 +while l[n] <> 0 : n -= 1 +print n diff --git a/Task/McNuggets-problem/Elixir/mcnuggets-problem.elixir b/Task/McNuggets-problem/Elixir/mcnuggets-problem.ex similarity index 100% rename from Task/McNuggets-problem/Elixir/mcnuggets-problem.elixir rename to Task/McNuggets-problem/Elixir/mcnuggets-problem.ex diff --git a/Task/McNuggets-problem/Fennel/mcnuggets-problem.fennel b/Task/McNuggets-problem/Fennel/mcnuggets-problem.fennel new file mode 100644 index 0000000000..f2f225a1a8 --- /dev/null +++ b/Task/McNuggets-problem/Fennel/mcnuggets-problem.fennel @@ -0,0 +1,21 @@ +(do ;;; Solve the McNuggets problem find the largest n <= 100 for which there + ;;; are no non-negative integers x, y, z such that 6x + 9y + 20z = n + + (local maxNuggets 100) + (var sum {}) + (for [i 0 maxNuggets] (tset sum i false)) + (for [x 0 maxNuggets 6] + (for [y x maxNuggets 9] + (for [z y maxNuggets 20] + (tset sum z true) + ) + ) + ) + ; show the highest number that cannot be formed + (var largest maxNuggets) + (while (. sum largest) + (set largest (- largest 1)) + ) + (print (.. "The largest non McNugget number is " largest)) + +) diff --git a/Task/McNuggets-problem/Fortran/mcnuggets-problem.f b/Task/McNuggets-problem/Fortran/mcnuggets-problem.f new file mode 100644 index 0000000000..1010851e87 --- /dev/null +++ b/Task/McNuggets-problem/Fortran/mcnuggets-problem.f @@ -0,0 +1,64 @@ +program mcnugget + ! Program to find non-McNugget numbers (up to 100) that cannot be expressed as + ! 6x + 9y + 20z (with x, y, z non-negative integers). This version uses dynamic + ! programming to mark expressible numbers and then uses FINDLOC on a logical mask + ! (derived by applying .NOT. to the expressible array) to obtain the largest + ! non-expressible number. + + implicit none + integer, parameter :: n = 100 + logical :: expressible(0:n) ! Mark if each number 0:n is expressible. + integer :: max_val ! To store the largest non-expressible number. + integer :: i, j ! Loop indices. + integer :: denoms(3) ! Array of denominations: 6, 9, 20. + integer, allocatable :: loc(:) + ! 'loc' will store the indices returned by FINDLOC. + + !-------------------------------------------------------------------- + ! Initialize the denominations and print them. + !-------------------------------------------------------------------- + denoms = [6, 9, 20] + print *, 'Nugget pacet sizes: ', denoms + + !-------------------------------------------------------------------- + ! Initialize all numbers as non-expressible except 0. + ! 0 is expressible (with x = y = z = 0). + !-------------------------------------------------------------------- + expressible = .false. + expressible(0) = .true. + + !-------------------------------------------------------------------- + ! Dynamic programming: + ! For each denomination, if a number i is expressible then mark + ! i + denomination as expressible (provided it does not exceed n). + !-------------------------------------------------------------------- + do j = 1, 3 + do i = 0, n - denoms(j) + if (expressible(i)) then + expressible(i + denoms(j)) = .true. + end if + end do + end do + + !-------------------------------------------------------------------- + ! Instead of looping to count and store non-expressible numbers, + ! we use the FINDLOC intrinsic to get the largest index for which + ! the number is NOT expressible. + ! + ! The expression (.not. expressible) creates a logical mask that is .true. + ! when a number is non-expressible. FINDLOC with BACK=.TRUE. searches the + ! array in reverse order (from n down to 0), thus returning the maximum index. + !-------------------------------------------------------------------- + loc = findloc(.not. expressible, .true., back = .true.) + if (size(loc) > 0) then + max_val = loc(1) ! Retrieve the largest non-expressible number. + else + max_val = 0 ! In the unlikely event that every number is expressible. + end if + + !-------------------------------------------------------------------- + ! Output the result (only the largest non-McNugget number). + !-------------------------------------------------------------------- + print *, 'Maximum non-McNuggets number is ', max_val + +end program mcnugget diff --git a/Task/McNuggets-problem/Julia/mcnuggets-problem.julia b/Task/McNuggets-problem/Julia/mcnuggets-problem.jl similarity index 100% rename from Task/McNuggets-problem/Julia/mcnuggets-problem.julia rename to Task/McNuggets-problem/Julia/mcnuggets-problem.jl diff --git a/Task/McNuggets-problem/Kotlin/mcnuggets-problem.kotlin b/Task/McNuggets-problem/Kotlin/mcnuggets-problem.kts similarity index 100% rename from Task/McNuggets-problem/Kotlin/mcnuggets-problem.kotlin rename to Task/McNuggets-problem/Kotlin/mcnuggets-problem.kts diff --git a/Task/McNuggets-problem/Oberon-07/mcnuggets-problem.oberon b/Task/McNuggets-problem/Oberon-07/mcnuggets-problem.oberon new file mode 100644 index 0000000000..bd44abb5a5 --- /dev/null +++ b/Task/McNuggets-problem/Oberon-07/mcnuggets-problem.oberon @@ -0,0 +1,21 @@ +MODULE McNuggetsProblem; + (* Solve the McNuggets problem: find the largest n <= 100 for which there *) + (* are no non-negative integers x, y, z such that 6x + 9y + 20z = n *) + IMPORT Out; + + CONST maxNuggets = 100; + VAR isSum : ARRAY maxNuggets + 1 OF BOOLEAN; + x, y, z, largest : INTEGER; + +BEGIN + (* find the numbers that can be formed *) + FOR x := 0 TO maxNuggets BY 6 DO + FOR y := x TO maxNuggets BY 9 DO + FOR z := y TO maxNuggets BY 20 DO isSum[ z ] := TRUE END + END + END; + (* show the highest number that cannot be formed *) + largest := maxNuggets; + WHILE isSum[ largest ] DO DEC( largest ) END; + Out.String( "The largest non-McNugget number is: " );Out.Int( largest, 0 );Out.Ln +END McNuggetsProblem. diff --git a/Task/McNuggets-problem/PascalABC.NET/mcnuggets-problem.pas b/Task/McNuggets-problem/PascalABC.NET/mcnuggets-problem.pas new file mode 100644 index 0000000000..649f9066ea --- /dev/null +++ b/Task/McNuggets-problem/PascalABC.NET/mcnuggets-problem.pas @@ -0,0 +1,6 @@ +## +var nuggets := [0..100]; +foreach var (x, y, z) in Cartesian(Range(0, 100 div 6), Range(0, 100 div 9), Range(0, 100 div 20)) do + Exclude(nuggets, 6 * x + 9 * y + 20 * z); + +nuggets.Max.println; diff --git a/Task/McNuggets-problem/Phix/mcnuggets-problem-1.phix b/Task/McNuggets-problem/Phix/mcnuggets-problem-1.phix index a11302f33b..5213d3a1fd 100644 --- a/Task/McNuggets-problem/Phix/mcnuggets-problem-1.phix +++ b/Task/McNuggets-problem/Phix/mcnuggets-problem-1.phix @@ -1,13 +1,15 @@ -(phixonline)--> - with javascript_semantics - constant limit=100 - sequence nuggets = repeat(false,limit+1) - for sixes=0 to limit by 6 do - for nines=sixes to limit by 9 do - for twenties=nines to limit by 20 do - nuggets[twenties+1] = true - end for - end for - end for - printf(1,"Maximum non-McNuggets number is %d\n", rfind(false,nuggets)-1) - - with javascript_semantics - function Mcnugget_number(sequence counts) +with javascript_semantics +function Mcnugget_number(sequence counts) - if gcd(counts)>1 then return "No maximum" end if + if gcd(counts)>1 then return "No maximum" end if - atom cmin = min(counts) - sequence meals = {} - sequence smin = {} + integer cmin = min(counts), klim = 0, a = -1 + sequence meals = {} + while true do + a += 1 + for b=0 to a do + for c=0 to b do + sequence s = {a, b, c} + for i=1 to factorial(3) do + sequence p = permute(i,s) + integer k = sum(sq_mul(p,counts)) + if k and (klim=0 or k<=klim) then + if k>length(meals) then + meals &= repeat(0,k-length(meals)) + end if + meals[k] = 1 + end if + end for + end for + end for + integer r = 0, res = 0 + for i=1 to length(meals) do + if meals[i] then + r += 1 + if r=cmin then klim = res exit end if + else + r = 0 + res = i + end if + end for + if r=cmin and a*cmin>res then + return sprintf("%d",res) + end if + end while +end function - integer a = -1 - while true do - a += 1 - for b=0 to a do - for c=0 to b do - sequence s = {a, b, c} - for i=1 to factorial(3) do - sequence p = permute(i,s) - integer k = sum(sq_mul(p,counts))+1 - -- atom k = sum(sq_mul(p,counts))+1 - if k>length(meals) then meals &= repeat(0,k-length(meals)) end if - meals[k] = 1 - end for - end for - end for - for i=1 to length(meals) do - if meals[i] then - if length(smin) and smin[$]+1=i-1 then - smin = append(smin,i-1) - if length(smin)=cmin then exit end if - else - smin = {i-1} - end if - end if - end for - if length(smin)=cmin then exit end if - end while - return sprintf("%d",iff(smin[1]?smin[1]-1:0)) - end function - - constant tests = {{6,9,20}, {6,7,20}, {1,3,20}, {10,5,18}, {5,17,44}, {2,4,6}, {3,6,15}} - for i=1 to length(tests) do - sequence ti = tests[i] - printf(1,"Maximum non-Mcnugget number using %V is: %s\n",{ti,Mcnugget_number(ti)}) - end for - - with javascript_semantics -- (but perhaps a bit too slow) - constant mmc = 0.2614972128476427837554268386086958590516, - smmc = "0.2614972128476427837554268386086958590516" - atom t = 0.57721566490153286, dpa = 1, p10=1 - integer pn = 1, adp = 0 - string st = "0", fmt = "%.0f" - printf(1,"Primes added M\n") - printf(1,"------------ --------------\n") - while adp<=10 do - atom rp = 1/get_prime(pn) - t += log(1-rp) + rp - if (t-mmc)<dpa then - string ft = sprintf(fmt,trunc(t*p10)/p10) -- (as below) - if ft=st then - -- - -- We have to artifically calculate a "truncated t", aka tt, - -- to prevent say 0.2..299[>5..] being automatically rounded - -- by printf() to 0.2..300, otherwise it just "looks wrong". - -- - atom tt = trunc(t*1e12)/1e12 - printf(1,"%,11d %0.12f (accurate to %d d.p.)\n", {pn, tt, adp}) - adp += 1 - fmt = sprintf("%%.%df",adp) - st = smmc[1..2+adp] - dpa /= 10 - p10 *= 10 - end if - end if - pn += 1 - end while - printf(1,"(actual value 0.26149721284764278375542683860869)\n") - - without js -- no mpfr_zeta[_ui]() in mpfr.js, as yet, or mpfr_log() or mpfr_const_euler(), for that matter - include mpfr.e - function moebius(integer n) - if n=1 then return 1 end if - sequence f = prime_factors(n,true) - for i=2 to length(f) do - if f[i] = f[i-1] then return 0 end if - end for - return iff(odd(length(f))?-1:+1) - end function - - function Meissel_Mertens(integer d) - mpfr_set_default_precision(-d) -- (d decimal places) - mpfr {res,rp,z,y,q} = mpfr_inits(5) - for p in {2,3,5,7} do - -- z += log(1-1/p)+1/p - mpfr_set_si(rp,1) - mpfr_div_si(rp,rp,p) - mpfr_add(z,z,rp) - mpfr_si_sub(rp,1,rp) - mpfr_log(rp,rp) - mpfr_add(z,z,rp) - end for - for k=2 to d do -- (see note) - integer m = moebius(k) - if m then - mpfr_set_si(q,1) - for p in {2,3,5,7} do - -- q *= 1-power(p,-k) - mpfr_set_si(rp,p) - mpfr_pow_si(rp,rp,-k) - mpfr_si_sub(rp,1,rp) - mpfr_mul(q,q,rp) - end for - -- y += moebius(k)*log(zeta(k)*q)/k - mpfr_zeta_ui(rp,k) - mpfr_mul(rp,rp,q) - mpfr_log(rp,rp) - mpfr_div_si(rp,rp,k) - mpfr_mul_si(rp,rp,m) - mpfr_add(y,y,rp) - end if - end for - -- res := EULER+z+y - mpfr_const_euler(res) - mpfr_add(z,z,y) - mpfr_add(res,res,z) - return res - end function - - mpfr m = Meissel_Mertens(1001) - ?shorten(mpfr_get_str(m,10,1001)) - $ ) + + ' [ $ "fee fie" $ "huff and puff" + $ "mirror mirror" $ "tick tock" ] + [] swap witheach [ do nested join ] + + $ "What does a clock say? " menu + say "Your answer: " echo$ diff --git a/Task/Menu/REBOL/menu.rebol b/Task/Menu/REBOL/menu.rebol deleted file mode 100644 index ba3a631351..0000000000 --- a/Task/Menu/REBOL/menu.rebol +++ /dev/null @@ -1,21 +0,0 @@ -REBOL [ - Title: "Text Menu" - URL: http://rosettacode.org/wiki/Select -] - -choices: ["fee fie" "huff and puff" "mirror mirror" "tick tock"] -choice: "" - -valid?: func [ - choices [block! list! series!] - choice -][ - if error? try [choice: to-integer choice] [return false] - all [0 < choice choice <= length? choices] -] - -while [not valid? choices choice][ - repeat i length? choices [print [" " i ":" choices/:i]] - choice: ask "Which is from the three pigs? " -] -print ["You chose:" pick choices to-integer choice] diff --git a/Task/Menu/Rebol/menu.rebol b/Task/Menu/Rebol/menu.rebol new file mode 100644 index 0000000000..c678c86c84 --- /dev/null +++ b/Task/Menu/Rebol/menu.rebol @@ -0,0 +1,6 @@ +menu: function [items][ + print either empty? items [""] [until [ + repeat n length? items [print [n ":" items/:n]] + attempt [pick items to-integer ask "Your choice: "] + ]] +] diff --git a/Task/Menu/Rust/menu.rust b/Task/Menu/Rust/menu.rs similarity index 100% rename from Task/Menu/Rust/menu.rust rename to Task/Menu/Rust/menu.rs diff --git a/Task/Menu/VBScript/menu.vb b/Task/Menu/VBScript/menu.vbs similarity index 100% rename from Task/Menu/VBScript/menu.vb rename to Task/Menu/VBScript/menu.vbs diff --git a/Task/Merge-and-aggregate-datasets/DuckDB/merge-and-aggregate-datasets.duckdb b/Task/Merge-and-aggregate-datasets/DuckDB/merge-and-aggregate-datasets.duckdb new file mode 100644 index 0000000000..1327975d1c --- /dev/null +++ b/Task/Merge-and-aggregate-datasets/DuckDB/merge-and-aggregate-datasets.duckdb @@ -0,0 +1,32 @@ +.print Since the patients.csv file is quite ordinary, it can be imported without fuss. + +create or replace table patients as + FROM 'patients.csv'; + +.print Taking the same approach with visits.csv illustrates how DuckDB correctly infers the types, including the date: + +create or replace table visits as + FROM 'visits.csv'; + +from visits; + +.print +.print Merge and group per patient id and last name, +.print get the maximum visit date, and +.print get the sum and average of the scores per patient to get the resulting dataset. + +SELECT + p.PATIENT_ID, + p.LASTNAME, + MAX(VISIT_DATE) AS LAST_VISIT, + SUM(SCORE) AS SCORE_SUM, + CAST(AVG(SCORE) AS DECIMAL(10,2)) AS SCORE_AVG +FROM + patients p + LEFT JOIN visits v + ON v.PATIENT_ID = p.PATIENT_ID +GROUP BY + p.PATIENT_ID, + p.LASTNAME +ORDER BY + p.PATIENT_ID; diff --git a/Task/Merge-and-aggregate-datasets/EasyLang/merge-and-aggregate-datasets.easy b/Task/Merge-and-aggregate-datasets/EasyLang/merge-and-aggregate-datasets.easy new file mode 100644 index 0000000000..451dbc3f9b --- /dev/null +++ b/Task/Merge-and-aggregate-datasets/EasyLang/merge-and-aggregate-datasets.easy @@ -0,0 +1,68 @@ +s$ = input +repeat + s$ = input + until s$ = "" + pat$[][] &= strsplit s$ "," + pat$[$][] &= "" +. +proc sort &d$[][] . + for i = len d$[][] - 1 downto 1 : for j = 1 to i + if strcmp d$[j][1] d$[j + 1][1] > 0 + swap d$[j][] d$[j + 1][] + . + . +. +sort pat$[][] +n = len pat$[][] +len sum[] n +len cnt[] n +# +s$ = input +repeat + s$ = input + until s$ = "" + vis$[] = strsplit s$ "," + for i to n + if pat$[i][1] = vis$[1] + if strcmp vis$[2] pat$[i][3] > 0 + pat$[i][3] = vis$[2] + . + sum[i] += number vis$[3] + cnt[i] += 1 + . + . +. +func$ f s$ n . + s$ = " " & s$ + while len s$ < n : s$ &= " " + return s$ +. +print "PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG" +for i to n + if sum[i] > 0 + sum$ = f sum[i] 11 + cnt$ = f sum[i] / cnt[i] 11 + else + sum$ = f "" 11 + cnt$ = f "" 11 + . + print f pat$[i][1] 11 & "|" & f pat$[i][2] 10 & "|" & f pat$[i][3] 12 & "|" & sum$ & "|" & cnt$ +. +# +input_data +PATIENT_ID,LASTNAME +1001,Hopper +4004,Wirth +3003,Kemeny +2002,Gosling +5005,Kurtz + +PATIENT_ID,VISIT_DATE,SCORE +2002,2020-09-10,6.8 +1001,2020-09-17,5.5 +4004,2020-09-24,8.4 +2002,2020-10-08, +1001,,6.6 +3003,2020-11-12, +4004,2020-11-05,7.0 +1001,2020-11-19,5.3 diff --git a/Task/Merge-and-aggregate-datasets/FreeBASIC/merge-and-aggregate-datasets.basic b/Task/Merge-and-aggregate-datasets/FreeBASIC/merge-and-aggregate-datasets-1.basic similarity index 100% rename from Task/Merge-and-aggregate-datasets/FreeBASIC/merge-and-aggregate-datasets.basic rename to Task/Merge-and-aggregate-datasets/FreeBASIC/merge-and-aggregate-datasets-1.basic diff --git a/Task/Merge-and-aggregate-datasets/FreeBASIC/merge-and-aggregate-datasets-2.basic b/Task/Merge-and-aggregate-datasets/FreeBASIC/merge-and-aggregate-datasets-2.basic new file mode 100644 index 0000000000..6b0293f6d1 --- /dev/null +++ b/Task/Merge-and-aggregate-datasets/FreeBASIC/merge-and-aggregate-datasets-2.basic @@ -0,0 +1,248 @@ +#include once "sqlite3.bi" +#include once "string.bi" +#include once "crt.bi" + +' Callback para SQLite +Function callback Cdecl (Byval NotUsed As Any Ptr, Byval argc As Integer, _ + Byval argv As ZString Ptr Ptr, Byval colName As ZString Ptr Ptr) As Integer + + For i As Integer = 0 To argc - 1 + If argv[i] <> NULL Then + Print *colName[i] & ": " & *argv[i] & " "; + Else + Print *colName[i] & ": NULL "; + End If + Next + Print + + Return 0 +End Function + +Sub createCSVfiles() + Dim As Integer ff + + If Dir("patients.csv") = "" Then + ff = Freefile + Open "patients.csv" For Output As #ff + Print #ff, "PATIENT_ID,LASTNAME" + Print #ff, "1001,Hopper" + Print #ff, "4004,Wirth" + Print #ff, "3003,Kemeny" + Print #ff, "2002,Gosling" + Print #ff, "5005,Kurtz" + Close #ff + End If + + If Dir("visits.csv") = "" Then + ff = Freefile + Open "visits.csv" For Output As #ff + Print #ff, "PATIENT_ID,VISIT_DATE,SCORE" + Print #ff, "2002,2020-09-10,6.8" + Print #ff, "1001,2020-09-17,5.5" + Print #ff, "4004,2020-09-24,8.4" + Print #ff, "2002,2020-10-08," + Print #ff, "1001,,6.6" + Print #ff, "3003,2020-11-12," + Print #ff, "4004,2020-11-05,7.0" + Print #ff, "1001,2020-11-19,5.3" + Close #ff + End If +End Sub + +Sub createTableHeaders(db As sqlite3 Ptr) + Dim As ZString Ptr errMsg = NULL + + ' Create the patient and visit table + sqlite3_exec(db, "CREATE TABLE IF NOT EXISTS patients (PATIENT_ID INT, LASTNAME TEXT);", Cast(Any Ptr, @callback), NULL, @errMsg) + If errMsg <> NULL Then + Print "Error creating patients table: " & *errMsg + sqlite3_free(errMsg) + End If + + sqlite3_exec(db, "CREATE TABLE IF NOT EXISTS visits (PATIENT_ID INT, VISIT_DATE TEXT, SCORE NUMERIC(4,1));", Cast(Any Ptr, @callback), NULL, @errMsg) + If errMsg <> NULL Then + Print "Error creating visits table: " & *errMsg + sqlite3_free(errMsg) + End If +End Sub + +Sub fillTablesFromCSV(db As sqlite3 Ptr) + Dim As Integer ff, i + Dim As String lineaCSV, query + Dim As ZString Ptr errMsg = NULL + + ff = Freefile + Open "patients.csv" For Input As #ff + Line Input #ff, lineaCSV ' Saltar la cabecera + + While Not Eof(ff) + Line Input #ff, lineaCSV + Dim As String id = "", lastname = "" + + i = 1 + While i <= Len(lineaCSV) And Mid(lineaCSV, i, 1) <> "," + id += Mid(lineaCSV, i, 1) + i += 1 + Wend + i += 1 ' Skip the comma + + While i <= Len(lineaCSV) + lastname += Mid(lineaCSV, i, 1) + i += 1 + Wend + + query = "INSERT INTO patients VALUES (" & id & ", '" & lastname & "');" + + sqlite3_exec(db, query, NULL, NULL, @errMsg) + If errMsg <> NULL Then + Print "Error inserting patient: " & *errMsg + sqlite3_free(errMsg) + End If + Wend + Close #ff + + ff = Freefile + Open "visits.csv" For Input As #ff + Line Input #ff, lineaCSV ' Skip header + + While Not Eof(ff) + Line Input #ff, lineaCSV + Dim As String id = "", dateStr = "", score = "" + Dim As Integer fieldNum = 0 + + For i = 1 To Len(lineaCSV) + If Mid(lineaCSV, i, 1) = "," Then + fieldNum += 1 + Else + Select Case fieldNum + Case 0: id += Mid(lineaCSV, i, 1) + Case 1: dateStr += Mid(lineaCSV, i, 1) + Case 2: score += Mid(lineaCSV, i, 1) + End Select + End If + Next i + + query = "INSERT INTO visits VALUES (" & id & ", " + + If dateStr = "" Then + query &= "NULL, " + Else + query &= "'" & dateStr & "', " + End If + + If score = "" Then + query &= "NULL);" + Else + query &= score & ");" + End If + + sqlite3_exec(db, query, NULL, NULL, @errMsg) + If errMsg <> NULL Then + Print "Error inserting visit: " & *errMsg + sqlite3_free(errMsg) + End If + Wend + Close #ff +End Sub + +Function joinTablesAndGroup(db As sqlite3 Ptr) As String + Dim As sqlite3_stmt Ptr stmt + Dim As String result = "" + Dim As ZString Ptr errMsg = NULL + + Dim As String query = _ + "SELECT " & _ + " p.PATIENT_ID, " & _ + " p.LASTNAME, " & _ + " MAX(v.VISIT_DATE) AS LAST_VISIT, " & _ + " SUM(v.SCORE) AS SCORE_SUM, " & _ + " ROUND(AVG(v.SCORE), 1) AS SCORE_AVG " & _ + "FROM " & _ + " patients p " & _ + "LEFT JOIN " & _ + " visits v ON p.PATIENT_ID = v.PATIENT_ID " & _ + "GROUP BY " & _ + " p.PATIENT_ID, p.LASTNAME " & _ + "ORDER BY " & _ + " p.PATIENT_ID;" + + If sqlite3_prepare_v2(db, query, -1, @stmt, NULL) <> SQLITE_OK Then + Print "Error preparing statement: " & *sqlite3_errmsg(db) + Return "Error" + End If + + result = "| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |" & Chr(10) + result &= "|------------|----------|------------|-----------|-----------|" & Chr(10) + + While sqlite3_step(stmt) = SQLITE_ROW + Dim As String row = "| " + + ' PATIENT_ID + If sqlite3_column_type(stmt, 0) <> SQLITE_NULL Then + row &= " " & Trim(Str(sqlite3_column_int(stmt, 0))) & " | " + Else + row &= Space(10) & "| " + End If + + ' LASTNAME + If sqlite3_column_type(stmt, 1) <> SQLITE_NULL Then + Dim As String lastname = *Cast(ZString Ptr, sqlite3_column_text(stmt, 1)) + row &= lastname & Space(9 - Len(lastname)) & "| " + Else + row &= " | " + End If + + ' LAST_VISIT + If sqlite3_column_type(stmt, 2) <> SQLITE_NULL Then + Dim As String visit_date = *Cast(ZString Ptr, sqlite3_column_text(stmt, 2)) + row &= visit_date & Space(11 - Len(visit_date)) & "| " + Else + row &= " None | " + End If + + ' SCORE_SUM + If sqlite3_column_type(stmt, 3) <> SQLITE_NULL Then + Dim As Double score_sum = sqlite3_column_double(stmt, 3) + row &= " " & Format(score_sum, "#00.#") & " | " + Else + row &= " None | " + End If + + ' SCORE_AVG + If sqlite3_column_type(stmt, 4) <> SQLITE_NULL Then + Dim As Double score_avg = sqlite3_column_double(stmt, 4) + row &= " " & Format(score_avg, "##.#") & " |" + Else + row &= " None |" + End If + + result &= row & Chr(10) + Wend + + sqlite3_finalize(stmt) + Return result +End Function + +' Main program +Dim As sqlite3 Ptr db +Dim As Integer rc + +createCSVfiles() + +rc = sqlite3_open(":memory:", @db) +If rc <> SQLITE_OK Then + Print "Error opening database: " & *sqlite3_errmsg(db) + sqlite3_close(db) + Sleep: End 1 +End If + +createTableHeaders(db) + +fillTablesFromCSV(db) + +Dim As String result = joinTablesAndGroup(db) +Print result + +sqlite3_close(db) + +Sleep diff --git a/Task/Merge-and-aggregate-datasets/JavaScript/merge-and-aggregate-datasets.js b/Task/Merge-and-aggregate-datasets/JavaScript/merge-and-aggregate-datasets.js new file mode 100644 index 0000000000..d83fbb4409 --- /dev/null +++ b/Task/Merge-and-aggregate-datasets/JavaScript/merge-and-aggregate-datasets.js @@ -0,0 +1,74 @@ +class Patient { + constructor(patientID, lastName) { + this.patientID = patientID; + this.lastName = lastName; + } +} + +class Visit { + constructor(visitID, visitDate, score) { + this.visitID = visitID; + this.visitDate = visitDate; + this.score = score; + } +} + +function main() { + const patients = [ + new Patient("1001", "Hopper"), + new Patient("4004", "Wirth"), + new Patient("3003", "Kemeny"), + new Patient("2002", "Gosling"), + new Patient("5005", "Kurtz"), + ]; + + const visits = [ + new Visit("2002", "2020-09-10", 6.8), + new Visit("1001", "2020-09-17", 5.5), + new Visit("4004", "2020-09-24", 8.4), + new Visit("2002", "2020-10-08", null), + new Visit("1001", "", 6.6), + new Visit("3003", "2020-11-12", null), + new Visit("4004", "2020-11-05", 7.0), + new Visit("1001", "2020-11-19", 5.3), + ]; + + // Sort patients by patientID + patients.sort((a, b) => a.patientID.localeCompare(b.patientID)); + + console.log("| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |"); + + patients.forEach((patient) => { + const patientVisits = visits.filter((v) => v.visitID === patient.patientID); + + // Find the last visit date + const validVisitDates = patientVisits + .map((v) => v.visitDate) + .filter((date) => date !== ""); + const lastVisit = validVisitDates.length > 0 + ? validVisitDates.reduce((latest, date) => date > latest ? date : latest, "") + : " None "; + + // Calculate score sum and average + const validScores = patientVisits + .map((v) => v.score) + .filter((score) => score !== null); + const scoreSum = validScores.reduce((sum, score) => sum + score, 0); + const scoreAverage = validScores.length > 0 + ? scoreSum / validScores.length + : 0; + + // Format the output + const patientDetails = [ + patient.patientID.padEnd(12), + patient.lastName.padEnd(11), + lastVisit.padEnd(13), + scoreSum.toFixed(2).padStart(12), + scoreAverage.toFixed(2).padStart(12), + ].join(""); + + console.log(patientDetails); + }); +} + +main(); diff --git a/Task/Merge-and-aggregate-datasets/Julia/merge-and-aggregate-datasets.julia b/Task/Merge-and-aggregate-datasets/Julia/merge-and-aggregate-datasets.jl similarity index 100% rename from Task/Merge-and-aggregate-datasets/Julia/merge-and-aggregate-datasets.julia rename to Task/Merge-and-aggregate-datasets/Julia/merge-and-aggregate-datasets.jl diff --git a/Task/Merge-and-aggregate-datasets/Logo/merge-and-aggregate-datasets-1.logo b/Task/Merge-and-aggregate-datasets/Logo/merge-and-aggregate-datasets-1.logo new file mode 100644 index 0000000000..576dddf06b --- /dev/null +++ b/Task/Merge-and-aggregate-datasets/Logo/merge-and-aggregate-datasets-1.logo @@ -0,0 +1,87 @@ +to read.simple.csv :in + local [line list] + make "list [] + openread :in + setread :in + while [not eofp] [ + make "line subst.comma readword + make "line parse map [ifelse equalp ? ", ["\ ] [?]] :line + make "list fput :line :list + ] + close :in + setread [] + output reverse :list +end + +to subst.comma :string + local [out k] + make "k 1 + make "out " + foreach :string [ + ifelse equalp ? ", ~ + [ifelse equalp :k 1 ~ + [make "out word :out ? make "k sum :k 1] ~ + [make "out word :out "|missing,| make "k 1]] ~ + [make "out word :out ? make "k 1] + ] + output ifelse equalp last :out ", [word :out "missing] [:out] +end + +to aggregate :patients :visits + if emptyp :patients [output []] + output fput aggregate.helper first :patients :visits aggregate bf :patients :visits +end + + +to aggregate.helper :patient :visits [s 0] [c 0] [m "] +;m for max date. s for sum of scores. c number of scores + if emptyp :visits [ + output (se :patient ifelse equalp :m " ["missing] [:m] ~ + ifelse equalp :s 0 ["missing] [:s] ~ + ifelse equalp :s 0 ["missing] [quotient :s :c]) + ] + output ifelse equalp first :patient first first :visits [ + (aggregate.helper :patient bf :visits ~ + ifelse equalp last first :visits "missing [:s][sum :s last first :visits] ~ + ifelse equalp last first :visits "missing [:c][sum :c 1] ~ + ifelse equalp first bf first :visits "missing [:m] ~ + [ifelse beforep :m first bf first :visits [first bf first :visits] [:m]])] ~ + [(aggregate.helper :patient bf :visits :s :c :m)] +end + +to mergesort :list + localmake "half split (count :list) / 2 [] :list + if empty? first :half [output :list] + output merge mergesort first :half mergesort last :half +end + +to split :size :front :list + if :size < 1 [output list :front :list] + output split :size-1 (lput first :list :front) (butfirst :list) +end + +to merge :small :large + if empty? :small [output :large] + ifelse lessequal? first first :small first first :large ~ + [output fput first :small merge butfirst :small :large] ~ + [output fput first :large merge butfirst :large :small] +end + +to csv.write :list :out + openwrite :out + setwrite :out + csv.write.lines :list + close :out + setwrite [] +end + +to csv.write.lines :list + if emptyp :list [stop] + print csv.write.fields first :list + csv.write.lines bf :list +end + +to csv.write.fields :line + if equalp count :line 1 [output first :line] + output (word first :line ", csv.write.fields bf :line) +end diff --git a/Task/Merge-and-aggregate-datasets/Logo/merge-and-aggregate-datasets-2.logo b/Task/Merge-and-aggregate-datasets/Logo/merge-and-aggregate-datasets-2.logo new file mode 100644 index 0000000000..e7cfd319ec --- /dev/null +++ b/Task/Merge-and-aggregate-datasets/Logo/merge-and-aggregate-datasets-2.logo @@ -0,0 +1,5 @@ +make "patients bf read.simple.csv "patients.csv +make "visits bf read.simple.csv "visits.csv +make "out mergesort aggregate :patients :visits +make "out fput [patient_id lastname max_date score_sum score_mean] :out +csv.write :out "out.csv diff --git a/Task/Mertens-function/ALGOL-68/mertens-function.alg b/Task/Mertens-function/ALGOL-68/mertens-function.alg index 479a042e38..cfeea7bcfe 100644 --- a/Task/Mertens-function/ALGOL-68/mertens-function.alg +++ b/Task/Mertens-function/ALGOL-68/mertens-function.alg @@ -9,11 +9,11 @@ BEGIN # compute values of the Mertens function # # Print table # print( ( "The first 99 Mertens numbers are:", newline ) ); print( ( " " ) ); - INT k := 9; + INT left := 9; FOR n TO 99 DO print( ( whole( m[ n ], -3 ) ) ); - IF ( k -:= 1 ) = 0 THEN - k := 10; + IF ( left -:= 1 ) = 0 THEN + left := 10; print( ( newline ) ) FI OD; diff --git a/Task/Mertens-function/Arturo/mertens-function.arturo b/Task/Mertens-function/Arturo/mertens-function.arturo index b35c6ff2cc..b2c94bf674 100644 --- a/Task/Mertens-function/Arturo/mertens-function.arturo +++ b/Task/Mertens-function/Arturo/mertens-function.arturo @@ -4,8 +4,8 @@ mobius: function [n][ f: factors.prime n if f <> unique f -> return 0 - if? odd? size f -> return neg 1 - else -> return 1 + switch odd? size f -> return neg 1 + -> return 1 ] mertens: function [z][sum map 1..z => mobius] @@ -20,6 +20,6 @@ print "" mertens1000: map 1..1000 => mertens print ["Times M(x) is zero between 1 and 1000:" size select mertens1000 => zero?] -crossed: new 0 +crossed: 0 fold mertens1000 [a,b][if and? zero? b not? zero? a -> inc 'crossed, b] print ["Times M(x) crosses zero between 1 and 1000:" crossed] diff --git a/Task/Mertens-function/COBOL/mertens-function.cobol b/Task/Mertens-function/COBOL/mertens-function.cob similarity index 100% rename from Task/Mertens-function/COBOL/mertens-function.cobol rename to Task/Mertens-function/COBOL/mertens-function.cob diff --git a/Task/Mertens-function/Delphi/mertens-function.delphi b/Task/Mertens-function/Delphi/mertens-function.pas similarity index 100% rename from Task/Mertens-function/Delphi/mertens-function.delphi rename to Task/Mertens-function/Delphi/mertens-function.pas diff --git a/Task/Mertens-function/EasyLang/mertens-function.easy b/Task/Mertens-function/EasyLang/mertens-function.easy index bacf516727..5ba339e368 100644 --- a/Task/Mertens-function/EasyLang/mertens-function.easy +++ b/Task/Mertens-function/EasyLang/mertens-function.easy @@ -8,19 +8,15 @@ for n = 2 to 1000 . print "First 99 Mertens numbers:" write " " -numfmt 0 2 +numfmt 2 0 for n = 1 to 99 write mertens[n] & " " - if n mod 10 = 9 - print "" - . + if n mod 10 = 9 : print "" . for n = 1 to 1000 if mertens[n] = 0 zeros += 1 - if mertens[n - 1] <> 0 - crosses += 1 - . + if mertens[n - 1] <> 0 : crosses += 1 . . print "" diff --git a/Task/Mertens-function/Julia/mertens-function.julia b/Task/Mertens-function/Julia/mertens-function.jl similarity index 100% rename from Task/Mertens-function/Julia/mertens-function.julia rename to Task/Mertens-function/Julia/mertens-function.jl diff --git a/Task/Mertens-function/PascalABC.NET/mertens-function.pas b/Task/Mertens-function/PascalABC.NET/mertens-function.pas new file mode 100644 index 0000000000..0f6b50e7d3 --- /dev/null +++ b/Task/Mertens-function/PascalABC.NET/mertens-function.pas @@ -0,0 +1,21 @@ +function mertens(max: integer): list; +begin + result := (0..max).select( x -> 1).ToList; + foreach var n in 2..max do + foreach var k in 2..n do + result[n] -= result[n div k]; +end; + +begin + println('The first 99 Mertens numbers are:'); + foreach var m in mertens(99) index i do + if i = 0 then write(' ') + else write(m:3, if i mod 10 = 9 then #10 else ''); + + var zeroes := mertens(1000).Where(x -> x = 0).Count; + println('M(N) equals zero', zeroes, 'times.'); + + var crosses := mertens(1000).Zip(mertens(1000).Skip(1), (x, y) -> (x <> 0) and (y = 0)) + .Where(x -> x).Count; + println('M(N) crosses zero', crosses, 'times.'); +end. diff --git a/Task/Mertens-function/REXX/mertens-function.rexx b/Task/Mertens-function/REXX/mertens-function.rexx index ee48fca3f7..67cd7ff4c5 100644 --- a/Task/Mertens-function/REXX/mertens-function.rexx +++ b/Task/Mertens-function/REXX/mertens-function.rexx @@ -1,61 +1,113 @@ -/*REXX pgm computes & shows a value grid of the Mertens function for a range of integers*/ -parse arg LO HI grp eqZ xZ . /*obtain optional arguments from the CL*/ -if LO=='' | LO=="," then LO= 0 /*Not specified? Then use the default.*/ -if HI=='' | HI=="," then HI= 199 /* " " " " " " */ -if grp=='' | grp=="," then grp= 20 /* " " " " " " */ -if eqZ=='' | eqZ=="," then eqZ= 1000 /* " " " " " " */ -if xZ=='' | xZ=="," then xZ= 1000 /* " " " " " " */ -call genP /*generate primes up to max √ HIHI */ - call Franz LO, HI -if eqZ>0 then call Franz 1, -eqZ -if xZ>0 then call Franz -1, xZ -exit 0 /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -Franz: parse arg a 1 oa,b 1 ob; @Mertens= ' The Mertens sequence from ' -a= abs(a); b= abs(b); grid= oa>=0 & ob>=0 /*semaphore used to show a grid title. */ -if grid then say center(@Mertens LO " ──► " HI" ", max(50, grp*3), '═') /*show title*/ - else say -zeros= 0 /*# of 0's found for Mertens function.*/ -Xzero= 0 /*number of times that zero was crossed*/ -$=; prev= /*$ holds output grid of GRP numbers. */ - do j=a to b; _= Mertens(j) /*process some numbers from LO ──► HI.*/ - if _==0 then zeros= zeros + 1 /*Is Zero? Then bump the zeros counter*/ - if _==0 then if prev\==0 then Xzero= Xzero+1 /*prev ¬=0? " " " Xzero " */ - prev= _ - if grid then $= $ right(_, 2) /*build grid if A & B are non─negative.*/ - if words($)==grp then do; say substr($, 2); $= /*show grid if fully populated, */ - end /* and nullify it for more #s. */ - end /*j*/ /*for small grids, using wordCnt is OK.*/ +-- 3 Mar 2026 +include Setting +arg xx +if xx = '' then + xx = 99 -if $\=='' then say substr($, 2) /*handle any residual numbers not shown*/ -if oa<0 then say @Mertens a " to " b ' has crossed zero ' Xzero " times." -if ob<0 then say @Mertens a " to " b ' has ' zeros " zeros." +say 'MERTENS FUNCTION' +say version +say +call Tasks1 xx +call Timer 'R' +call Tasks2 xx +call Timer 'R' +call Tasks3 xx +call Timer 'R' +exit + +Tasks1: +procedure expose squa. memo. +arg xx +say 'Tasks using Sieve...' +call Squarefrees 2*xx +if xx < 100 then + say 'M1 thru M'xx +e = 0; o = 0; a = 0; b = 0 +n = 1; s = squa.1; p = s +do i = 1 to xx + if s <= i then do + if s = 1 then + f = 0 + else + f = Factors(s) + e = e+Even(f); o = o+Odd(f); m = e-o + n = n+1; s = squa.n + end + if xx < 100 & i < 100 then do + call Charout ,Right(m,3) + if i//10 = 0 then + say + end + if m = 0 then do + a = a+1 + if p <> 0 then + b = b + 1 + end + p = m +end +say +say 'M1 thru M'xx 'equals zero' a 'times' +say 'M1 thru M'xx 'crosses zero' b 'times' return -/*──────────────────────────────────────────────────────────────────────────────────────*/ -Mertens: procedure expose @. !!. M.; parse arg n; if M.n\==. then return M.n - if n<1 then return '∙'; m= 0 /*handle special cases of non─positive#*/ - do k=1 for n; m= m + mobius(k) /*sum the MU's up to N. */ - end /*k*/ /* [↑] mobius function uses memoization*/ - M.n= m; return m /*return the sum of all the MU's. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -mobius: procedure expose @. !!.; parse arg x 1 ox /*get integer to be tested for mu */ - if !!.x\==. then return !!.x /*X computed before? Return that value*/ - if x<1 then return '∙'; mu= 0 /*handle special case of non-positive #*/ - do k=1; p= @.k; if p>x then leave /* (P) > X? Then we're done.*/ - if p*p>x then do; mu= mu+1; leave; end /* (P**2) > X? Bump # and leave*/ - if x//p==0 then do; mu= mu+1 /*X divisible by P? Bump mu number.*/ - x= x % p /* Divide by prime. */ - if x//p==0 then return 0 /*X÷by P? Then return zero*/ - end - end /*k*/ /*MU (below) is almost always small, <9*/ - !!.ox= -1 ** mu; return !!.ox /*raise -1 to the mu power, memoize it.*/ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -genP: @.1=2; @.2=3; @.3=5; @.4=7; @.5=11; @.6=13 /*initialize some low primes; # primes.*/ - !!.=.; M.=!!.; #= 6; sq.#= @.6**2 /* " 2 arrays for memoization. */ - do j=@.#+4 by 2 to max(HI, eqZ, xZ); parse var j '' -1 _ /*odd Ps from now on*/ - if _==5 then iterate; if j//3==0 then iterate; if j//7==0 then iterate /*÷ 5 3 7*/ - do k=7 while sq.k<=j /*divide by some generated odd primes. */ - if j//@.k==0 then iterate j /*Is J divisible by P? Then not prime*/ - end /*k*/ /* [↓] a prime (J) has been found. */ - #= #+1; @.#=j; sq.j= j*j /*bump P count; P──►@.; compute J**2*/ - end /*j*/; return /*calculate the squares of some primes.*/ + +Tasks2: +procedure expose squa. memo. +arg xx +say 'Tasks using Moebius function...' +if xx < 100 then + say 'M1 thru M'xx +e = 0; o = 0; a = 0; b = 0 +s = 0 +do i = 1 to xx + s = s+Moebius(i) + if xx < 100 & i < 100 then do + call Charout ,Right(s,3) + if i//10 = 0 then + say + end + if s = 0 then do + a = a+1 + if p <> 0 then + b = b + 1 + end + p = s +end +say +say 'M1 thru M'xx 'equals zero' a 'times' +say 'M1 thru M'xx 'crosses zero' b 'times' +return + +Tasks3: +procedure expose squa. memo. +arg xx +say 'Tasks using Squarefree function...' +if xx < 100 then + say 'M1 thru M'xx +e = 0; o = 0; a = 0; b = 0 +do s = 1 to xx + if Squarefree(s) then do + if s = 1 then + f = 0 + else + f = Factors(s) + e = e+Even(f); o = o+Odd(f); m = e-o + end + if xx < 100 & s < 100 then do + call Charout ,Right(m,3) + if s//10 = 0 then + say + end + if m = 0 then do + a = a+1 + if p <> 0 then + b = b + 1 + end + p = m +end +say +say 'M1 thru M'xx 'equals zero' a 'times' +say 'M1 thru M'xx 'crosses zero' b 'times' +return + +-- Squarefrees; Factors; Even; Odd; Moebius; Timer +include Math diff --git a/Task/Mertens-function/Uiua/mertens-function.uiua b/Task/Mertens-function/Uiua/mertens-function.uiua new file mode 100644 index 0000000000..b5513c94fa --- /dev/null +++ b/Task/Mertens-function/Uiua/mertens-function.uiua @@ -0,0 +1,6 @@ +Moebius ← +0/ׯ≤1⊕⧻⊸⊛°/× +Mertens ← |1 memo(⨬(+⊃(Mertens-1|Moebius)|1)⊸=1) +&s↯∞_10≡Mertens↘1⇡101 +⊃(&p$"Crosses zero _ times"/+⌕0_1=0 +| &p$"Equals zero _ times"/+ +)=0≡Mertens↘1⇡1001 diff --git a/Task/Metallic-ratios/Ada/metallic-ratios.adb b/Task/Metallic-ratios/Ada/metallic-ratios.adb new file mode 100644 index 0000000000..ac6d6c7b16 --- /dev/null +++ b/Task/Metallic-ratios/Ada/metallic-ratios.adb @@ -0,0 +1,50 @@ +with Ada.Text_IO; use Ada.Text_IO; +with Unbounded_Integers; use Unbounded_Integers; +with Unbounded_Rationals; use Unbounded_Rationals; + +with Strings_Edit.Unbounded_Integer_Edit; +use Strings_Edit.Unbounded_Integer_Edit; + +with Strings_Edit.Unbounded_Rational_Edit; +use Strings_Edit.Unbounded_Rational_Edit; + +with Strings_Edit.Unbounded_Unsigned_Edit; +use Strings_Edit.Unbounded_Unsigned_Edit; + +procedure Metallic_Ratios is + procedure Metallic (B, P, First : Natural) is + Eps : Unbounded_Rational := To_Unbounded_Rational (10)**(-P-1); + X0 : Unbounded_Integer := To_Unbounded_Integer (1); + X1 : Unbounded_Integer := To_Unbounded_Integer (1); + R0 : Unbounded_Rational; + R1 : Unbounded_Rational; + Count : Natural := 0; + begin + Put ("B:" & Integer'Image (B) & " | 1 1"); + for I in Positive'Range loop + X0 := X1 * B + X0; + Swap (X1, X0); + if I <= First then + Put (" " & Image (X1)); + end if; + R0 := To_Unbounded_Rational (X1) / X0; + if abs (R1 - R0) <= Eps then + exit when I > First; + else + Count := Count + 1; + end if; + Swap (R0, R1); + end loop; + New_Line; + Put_Line + ( Image (R1, Fraction => P) + & " after" & Integer'Image (Count) + ); + end Metallic; +begin + for B in 0..9 loop + Metallic (B, 32, 15); + end loop; + New_Line; + Metallic (1, 256, 15); +end Metallic_Ratios; diff --git a/Task/Metallic-ratios/DuckDB/metallic-ratios-1.duckdb b/Task/Metallic-ratios/DuckDB/metallic-ratios-1.duckdb new file mode 100644 index 0000000000..ef559e03bb --- /dev/null +++ b/Task/Metallic-ratios/DuckDB/metallic-ratios-1.duckdb @@ -0,0 +1,5 @@ +create or replace table metals as + (select (row_number() over () - 1) as b, name + from unnest( + ['Platinum', 'Golden', 'Silver', 'Bronze', 'Copper','Nickel', 'Aluminium', 'Iron', 'Tin', 'Lead'] + ) _(name) ); diff --git a/Task/Metallic-ratios/DuckDB/metallic-ratios-2.duckdb b/Task/Metallic-ratios/DuckDB/metallic-ratios-2.duckdb new file mode 100644 index 0000000000..59306a60ac --- /dev/null +++ b/Task/Metallic-ratios/DuckDB/metallic-ratios-2.duckdb @@ -0,0 +1,24 @@ +# The Lucas-like function as per the task description +create or replace function lucas(b, n) as table ( + with recursive cte as ( + select 1 as ix, 1::HUGEINT as i, 1::HUGEINT as j + union all + select + ix+1, + j as i, + i + b*j as j + from cte + where ix < n) + select ix, i + from cte +); + +# The successive metallic ratio approximations +create or replace function metallic_ratio(b, n) as table ( + select i / (lag(i) over ()) + from lucas(b,n) +); + +.maxwidth 200 +select b, (select array_agg(i) from lucas(b, 15)) as "lucas-like" +from range(0, 10) _(b); diff --git a/Task/Metallic-ratios/DuckDB/metallic-ratios-3.duckdb b/Task/Metallic-ratios/DuckDB/metallic-ratios-3.duckdb new file mode 100644 index 0000000000..303b9058b4 --- /dev/null +++ b/Task/Metallic-ratios/DuckDB/metallic-ratios-3.duckdb @@ -0,0 +1,28 @@ +# ix serves both as a rowid and as the count of the number of +# iterations required to achieve the corresponding ratio +create or replace function metallic_ratio_to_quiescence(b) as ( + with recursive cte as ( + select + -1::HUGEINT as ix, + 1::HUGEINT as previ, + 1::HUGEINT as i, + 1::HUGEINT as j, + 1::DOUBLE as prevratio, + 1::DOUBLE as ratio + union all + select + ix+1, + i as previ, + j as i, + i + b*j as j, + ratio as prevratio, + (i::DOUBLE / previ) as ratio + from cte + where (ix < 4 or prevratio != ratio) + ) + select last((ix, ratio)) + from cte +); + +select b, name, metallic_ratio_to_quiescence(b) +from metals; diff --git a/Task/Metallic-ratios/Fortran/metallic-ratios.f b/Task/Metallic-ratios/Fortran/metallic-ratios.f new file mode 100644 index 0000000000..65aeb2d7e9 --- /dev/null +++ b/Task/Metallic-ratios/Fortran/metallic-ratios.f @@ -0,0 +1,604 @@ +! ============================================================================= +! metallic.f90 -- Metallic Ratios via Lucas-like sequences +! +! The b-th Metallic Ratio is the positive root of x^2 - bx - 1 = 0, +! evaluated by the closed form (b + sqrt(b^2 + 4)) / 2. +! +! It can also be approximated by the ratio of successive terms of the +! Lucas-like recurrence x(n) = b*x(n-1) + x(n-2), started at x(1)=x(2)=1. +! As n grows the ratio x(n+1)/x(n) converges to the b-th Metallic Ratio. +! +! This program: +! - Generates and displays the first 15 terms for b = 0 .. 9 +! - Iterates the recurrence until the ratio stabilises to 32 decimal places +! - Reports the converged value and the iteration count +! - Stretch goal: repeats for b=1 (Golden Ratio) to 256 decimal places +! +! Because standard floating-point types top out at ~18 significant decimal +! digits, all ratio arithmetic is done in a hand-rolled arbitrary-precision +! integer module (bigint_mod). The ratio a/b is extracted one decimal digit +! at a time by the long-division routine bg_div_dec. +! +! Compile: gfortran -O2 -o metallic metallic.f90 +! ============================================================================= + +! ============================================================================= +! MODULE bigint_mod +! +! Minimal arbitrary-precision non-negative integer library. +! +! Representation +! -------------- +! A big integer is stored as an array of "limbs" a(1..na) in base BB=10^9. +! a(1) holds the LEAST-significant 9 decimal digits. +! a(na) holds the MOST-significant (possibly shorter) group. +! Only limbs a(1)..a(na) are active; a(na+1)..a(ML) are ignored (but are +! kept zeroed by all routines to avoid stale data causing wrong results). +! +! Why base 10^9? +! Each limb is an int64 (range up to ~9.2e18). During the multiply-by-10 +! inner loop we temporarily hold a(i)*10 + carry which is at most +! (10^9 - 1)*10 + (10^9 - 1) = ~10^10, well within int64. Using a power +! of ten as the base also makes printing decimal digits straightforward. +! +! Public interface +! ---------------- +! bg_set -- initialise a big-int from a small (< BB) integer +! bg_copy -- copy one big-int to another +! bg_add -- c = a + b +! bg_mul_s -- c = a * k (k is a small ordinary integer, 0 <= k <= ~100) +! bg_sub -- c = a - b (a >= b must hold) +! bg_cmp -- compare two big-ints, return +1/0/-1 +! bg_div_dec -- divide a/b and return the result as a decimal string +! to an arbitrary number of places +! ============================================================================= +module bigint_mod + use iso_fortran_env, only: int64 + implicit none + + ! ML : maximum number of limbs per big-int. + ! ML=200 supports numbers with up to 200*9 = 1800 decimal digits, + ! which is vastly more than the ~300 digits needed here. + integer, parameter :: ml = 200 + + ! BB : the limb base. Every limb satisfies 0 <= limb < BB. + integer(kind=int64), parameter :: bb = 1000000000_int64 ! 10^9 + +contains + + ! --------------------------------------------------------------------------- + ! bg_set(a, na, val) + ! + ! Set the big-int a to the small non-negative value val (val < BB). + ! All limbs are zeroed first to guarantee a clean state; then limb 1 is set + ! to val and na is set to 1 (a single-limb number). + ! --------------------------------------------------------------------------- + subroutine bg_set(a, na, val) + integer(kind=int64), intent(out) :: a(ml) ! limb array to initialise + integer, intent(out) :: na ! number of active limbs + integer(kind=int64), intent(in) :: val ! value to store (< BB) + + a = 0_int64 ! zero every limb so no stale data remains + a(1) = val ! least-significant limb carries the whole value + na = 1 ! exactly one active limb + end subroutine bg_set + + ! --------------------------------------------------------------------------- + ! bg_copy(src, ns, dst, nd) + ! + ! Copy big-int src (with ns active limbs) into dst, setting nd = ns. + ! A whole-array copy is used because ML is fixed at compile time; it is + ! fast and ensures no stale limbs survive in dst beyond position ns. + ! --------------------------------------------------------------------------- + subroutine bg_copy(src, ns, dst, nd) + integer(kind=int64), intent(in) :: src(ml) ! source big-int + integer, intent(in) :: ns ! active limbs in src + integer(kind=int64), intent(out) :: dst(ml) ! destination big-int + integer, intent(out) :: nd ! active limbs in dst + + dst = src ! copies all ML limbs (unused ones are already zero) + nd = ns + end subroutine bg_copy + + ! --------------------------------------------------------------------------- + ! bg_add(a, na, b, nb, c, nc) + ! + ! c = a + b + ! + ! Standard schoolbook addition, limb by limb from least significant to most. + ! At each position we accumulate carry + a(i) + b(i), write the result mod + ! BB into c(i), and pass floor(result/BB) as carry to the next position. + ! We iterate up to max(na,nb)+1 limbs to catch any final carry overflow. + ! After the loop the leading-zero trimmer keeps nc as small as possible. + ! + ! NOTE: c must be a distinct array from both a and b (no aliasing). + ! --------------------------------------------------------------------------- + subroutine bg_add(a, na, b, nb, c, nc) + integer(kind=int64), intent(in) :: a(ml), b(ml) ! operands + integer, intent(in) :: na, nb ! their active limbs + integer(kind=int64), intent(out) :: c(ml) ! result c = a + b + integer, intent(out) :: nc ! active limbs in c + + integer(kind=int64) :: carry ! carry propagating upward through limbs + integer :: i, nm + + nm = max(na, nb) ! highest limb index that might be non-zero in a or b + c = 0_int64 + carry = 0_int64 + + do i = 1, nm + 1 ! +1 to absorb a possible carry out of the top limb + c(i) = carry + if (i <= na) c(i) = c(i) + a(i) ! add a's contribution (if present) + if (i <= nb) c(i) = c(i) + b(i) ! add b's contribution (if present) + carry = c(i) / bb ! extract carry for next limb + c(i) = mod(c(i), bb) ! keep only the low BB part + end do + + ! Set nc to the index of the highest non-zero limb (at least 1). + nc = nm + 1 + do while (nc > 1 .and. c(nc) == 0_int64) + nc = nc - 1 + end do + end subroutine bg_add + + ! --------------------------------------------------------------------------- + ! bg_mul_s(a, na, k, c, nc) + ! + ! c = a * k, where k is a small non-negative integer (0 <= k <= ~100). + ! + ! Multiplies each limb by k, accumulating carries upward. The product + ! a(i)*k + carry_in + ! fits comfortably in int64 because: + ! a(i) < 10^9, k <= 100, carry_in < 100 + ! => max product ~= 10^9 * 100 + 100 = 10^11, well within 2^63 - 1. + ! + ! k=0 is handled specially (result is zero stored as a single zero limb). + ! + ! NOTE: c must be a distinct array from a (no aliasing). + ! --------------------------------------------------------------------------- + subroutine bg_mul_s(a, na, k, c, nc) + integer(kind=int64), intent(in) :: a(ml) ! multiplicand + integer, intent(in) :: na, k ! active limbs; small factor + integer(kind=int64), intent(out) :: c(ml) ! result c = a * k + integer, intent(out) :: nc ! active limbs in c + + integer(kind=int64) :: carry, kk ! carry between limbs; k as int64 + integer :: i + + c = 0_int64 + + ! Special case: multiplying by zero yields zero (single zero limb). + if (k == 0) then + nc = 1 + return + end if + + kk = int(k, int64) ! widen k to int64 to avoid 32-bit overflow + carry = 0_int64 + + do i = 1, na + c(i) = a(i) * kk + carry ! partial product plus incoming carry + carry = c(i) / bb ! carry for the next limb + c(i) = mod(c(i), bb) ! store only the low BB part + end do + + ! If there is a leftover carry it forms a new most-significant limb. + if (carry > 0_int64) then + nc = na + 1 + c(nc) = carry + else + nc = na + end if + end subroutine bg_mul_s + + ! --------------------------------------------------------------------------- + ! bg_sub(a, na, b, nb, c, nc) + ! + ! c = a - b (caller must ensure a >= b; the result is always >= 0) + ! + ! Standard schoolbook subtraction with borrow. We work on a local copy + ! `tmp` so that c may safely alias a (c and a may point to the same array). + ! After subtraction the leading-zero trimmer reduces nc. + ! --------------------------------------------------------------------------- + subroutine bg_sub(a, na, b, nb, c, nc) + integer(kind=int64), intent(in) :: a(ml), b(ml) ! a >= b required + integer, intent(in) :: na, nb + integer(kind=int64), intent(out) :: c(ml) ! c = a - b + integer, intent(out) :: nc + + integer(kind=int64) :: borrow ! borrow propagating upward (0 or 1) + integer(kind=int64) :: tmp(ml) ! local working copy so c may alias a + integer :: i + + tmp = a ! copy a into tmp so we can safely write into c + borrow = 0_int64 + + do i = 1, na + tmp(i) = tmp(i) - borrow ! subtract any borrow from above + if (i <= nb) tmp(i) = tmp(i) - b(i) ! subtract b's limb (if present) + ! If the result went negative, borrow from the next higher limb. + if (tmp(i) < 0_int64) then + tmp(i) = tmp(i) + bb ! add one full base to restore positivity + borrow = 1_int64 ! and carry that borrow upward + else + borrow = 0_int64 ! result non-negative: no borrow needed + end if + end do + + ! Trim leading zero limbs (but always keep at least one limb). + nc = na + do while (nc > 1 .and. tmp(nc) == 0_int64) + nc = nc - 1 + end do + c = tmp ! write result out (safe even if c aliases a, since tmp is local) + end subroutine bg_sub + + ! --------------------------------------------------------------------------- + ! bg_cmp(a, na, b, nb) -> integer result + ! + ! Compare two big-ints. Returns: + ! +1 if a > b + ! 0 if a = b + ! -1 if a < b + ! + ! Strategy: + ! 1. A number with more active limbs is larger (they share the same base). + ! 2. If both have the same limb count, scan from most significant to least; + ! the first differing limb determines the outcome. + ! 3. If every limb matches the numbers are equal. + ! --------------------------------------------------------------------------- + function bg_cmp(a, na, b, nb) result(res) + integer(kind=int64), intent(in) :: a(ml), b(ml) + integer, intent(in) :: na, nb + integer :: res, i + + ! More limbs => larger magnitude (no leading-zero limbs are ever stored). + if (na > nb) then; res = 1; return; end if + if (na < nb) then; res = -1; return; end if + + ! Same limb count: scan from the most significant limb downward. + do i = na, 1, -1 + if (a(i) > b(i)) then; res = 1; return; end if + if (a(i) < b(i)) then; res = -1; return; end if + end do + + res = 0 ! every limb matched: the numbers are equal + end function bg_cmp + + ! --------------------------------------------------------------------------- + ! bg_div_dec(a, na, b, nb, ndec, rstr) + ! + ! Compute a / b and write the result into the character variable rstr + ! in decimal notation with exactly ndec digits after the decimal point. + ! Example: a/b = golden ratio, ndec=32 => rstr = "1.61803398874989484820..." + ! + ! The caller must ensure a >= b (i.e. ratio >= 1), and that rstr is + ! at least ndec + len(int_part) + 1 characters wide. + ! + ! Algorithm + ! --------- + ! Step 1 -- Integer part + ! Find the largest integer q such that q*b <= a, by incrementing q + ! from 0 while (q+1)*b <= a. For our sequences q is at most b+1 (the + ! metallic parameter), so at most ~11 multiplications are needed. + ! Compute the remainder r = a - q*b. + ! + ! Step 2 -- Decimal digits (long division) + ! The classical long-division digit loop: + ! r <- r * 10 (shift remainder left one decimal place) + ! d <- floor(r / b), 0 <= d <= 9 (next decimal digit) + ! r <- r - d*b (new remainder for the next digit) + ! Finding d uses the same trial-multiplication trick: start d=0, increment + ! while (d+1)*b <= r. Since 0 <= d <= 9 this costs at most 10 multiplies. + ! + ! Step 3 -- Assemble result string + ! Write the integer part using Fortran's I0 format, append '.', then + ! append the decimal digits one character at a time. + ! --------------------------------------------------------------------------- + subroutine bg_div_dec(a, na, b, nb, ndec, rstr) + integer(kind=int64), intent(in) :: a(ml), b(ml) ! numerator, denominator + integer, intent(in) :: na, nb ! their active limbs + integer, intent(in) :: ndec ! decimal places wanted + character(len=*), intent(out) :: rstr ! result string + + integer(kind=int64) :: r(ml), t1(ml), t2(ml) ! remainder; temporaries + integer :: nr, nt1, nt2 ! their active limb counts + integer :: int_part ! integer part of a/b (small, ~0-10 for our use) + integer :: d ! one decimal digit (0-9) + integer :: j ! loop counter over decimal positions + integer :: pos ! current write position in rstr + character(len=20) :: ips ! scratch to format the integer part + + ! ------------------------------------------------------------------ + ! Step 1: find the integer part q = floor(a/b). + ! We compute (q+1)*b and check whether it still <= a. If so, q is + ! not yet large enough and we increment. When (q+1)*b > a we stop + ! and q is correct. + ! ------------------------------------------------------------------ + int_part = 0 + call bg_mul_s(b, nb, int_part + 1, t1, nt1) ! t1 = 1*b + do while (bg_cmp(t1, nt1, a, na) <= 0) ! while (int_part+1)*b <= a + int_part = int_part + 1 + call bg_mul_s(b, nb, int_part + 1, t1, nt1) ! next candidate + end do + + ! Compute the remainder r = a - int_part * b + call bg_mul_s(b, nb, int_part, t1, nt1) ! t1 = int_part * b + call bg_sub(a, na, t1, nt1, r, nr) ! r = a - t1 + + ! ------------------------------------------------------------------ + ! Assemble the start of the result string: "." + ! I0 format suppresses leading zeros, e.g. 1 -> "1", 12 -> "12". + ! After assignment to rstr (a fixed-length char variable) Fortran + ! pads with spaces to the right; the subsequent character-by-character + ! writes will overwrite those spaces with decimal digits. + ! pos points to the first character position after the decimal point. + ! ------------------------------------------------------------------ + write(ips, '(I0)') int_part + rstr = trim(ips) // '.' + pos = len_trim(ips) + 2 ! 1-based: skip int_part digits and the '.' + + ! ------------------------------------------------------------------ + ! Step 2: long-division decimal digit loop. + ! Each iteration extracts exactly one decimal digit and updates r. + ! ------------------------------------------------------------------ + do j = 1, ndec + + ! Shift the remainder left by one decimal place (multiply by 10). + ! We must use a temporary because bg_mul_s cannot alias input/output. + call bg_mul_s(r, nr, 10, t1, nt1) + r = t1 ! update r in-place via copy (t1 is a local array) + nr = nt1 + + ! Find the digit d = floor(r / b), 0 <= d <= 9. + ! We try d=0,1,2,... until (d+1)*b > r. + d = 0 + call bg_mul_s(b, nb, d + 1, t1, nt1) ! t1 = (d+1)*b = 1*b + do while (bg_cmp(t1, nt1, r, nr) <= 0) ! while (d+1)*b <= r + d = d + 1 + call bg_mul_s(b, nb, d + 1, t1, nt1) ! next candidate digit + end do + ! Now d is the correct decimal digit. + + ! Store the digit as a character ('0'+d). + rstr(pos:pos) = char(ichar('0') + d) + pos = pos + 1 + + ! Update the remainder: r <- r - d*b + call bg_mul_s(b, nb, d, t1, nt1) ! t1 = d*b + call bg_sub(r, nr, t1, nt1, t2, nt2) ! t2 = r - t1 + r = t2 ! copy back into r + nr = nt2 + + end do ! next decimal digit + + end subroutine bg_div_dec + +end module bigint_mod + + +! ============================================================================= +! PROGRAM metallic_ratios +! +! Main driver. For each of the first ten Metallic Ratios (b = 0 .. 9): +! 1. Generate and print the first 15 terms of the Lucas-like sequence +! x(n) = b * x(n-1) + x(n-2), x(1) = x(2) = 1. +! 2. Iterate the recurrence using arbitrary-precision big-ints, computing +! the ratio x(n+1)/x(n) to 32 decimal places after each step. +! 3. Stop when two consecutive ratio strings are identical (convergence). +! 4. Report the converged ratio and the iteration index n. +! +! Stretch goal: repeat step 2-4 for b=1 (Golden Ratio) to 256 decimal places. +! +! Variable layout +! --------------- +! xa, xb -- the two most-recent sequence terms (big-ints) +! xc -- temporary holding b * x(n), the first part of the recurrence +! xt -- the new term x(n+1) = b*x(n) + x(n-1) +! na..nt_v -- active limb counts for xa..xt respectively +! seq(15) -- first 15 terms as ordinary int64 (they fit; largest is ~3e12) +! prev_str -- ratio string from the previous iteration +! curr_str -- ratio string from the current iteration +! ============================================================================= +program metallic_ratios + use bigint_mod + use iso_fortran_env, only: int64 + implicit none + + ! Big-int working arrays for the two live sequence terms and two temporaries. + integer(kind=int64) :: xa(ml), xb(ml), xc(ml), xt(ml) + integer :: na ! active limbs in xa (the x(n-1) term) + integer :: nb_v ! active limbs in xb (the x(n) term) + integer :: nc ! active limbs in xc (intermediate: b * x(n)) + integer :: nt_v ! active limbs in xt (the new x(n+1) term) + + integer :: bv ! metallic parameter (the "b" in the task description) + integer :: i ! loop index for building seq() + integer :: iter ! iteration count (= n in the task description) + integer :: ndec ! how many decimal places we want + + ! First 15 terms stored as 64-bit integers (the largest, for b=9, is ~3e12, + ! well within int64's range of ~9.2e18). + integer(kind=int64) :: seq(15) + + ! Ratio strings. Length 310 comfortably holds: + ! 2 chars (integer part + '.') + 256 decimal digits + padding spaces + character(len=310) :: prev_str ! ratio string from the previous iteration + character(len=310) :: curr_str ! ratio string from the current iteration + + logical :: converged ! .TRUE. once curr_str matches prev_str + + ! Human-readable names indexed by b. + character(len=10) :: names(0:9) + names(0) = 'Platinum' + names(1) = 'Golden' + names(2) = 'Silver' + names(3) = 'Bronze' + names(4) = 'Copper' + names(5) = 'Nickel' + names(6) = 'Aluminum' + names(7) = 'Iron' + names(8) = 'Tin' + names(9) = 'Lead' + + ! ------------------------------------------------------------------------- + ! Header + ! ------------------------------------------------------------------------- + write(*, '(A)') "Metallic Ratios via Lucas-like Sequences" + write(*, '(A)') repeat('=', 62) + write(*, *) + + ndec = 32 ! target precision for the main loop + + ! ========================================================================= + ! Main loop: b = 0, 1, ..., 9 + ! ========================================================================= + do bv = 0, 9 + + ! ----------------------------------------------------------------------- + ! Part A: Generate the first 15 sequence terms using ordinary int64. + ! + ! The sequence is x(n) = bv * x(n-1) + x(n-2), x(1) = x(2) = 1. + ! For bv=0 every term is 1. + ! For bv=1 we get the Fibonacci sequence: 1,1,2,3,5,8,... + ! For bv=9 the 15th term is ~3.26e12, comfortably within int64. + ! ----------------------------------------------------------------------- + seq(1) = 1_int64 + seq(2) = 1_int64 + do i = 3, 15 + seq(i) = int(bv, int64) * seq(i - 1) + seq(i - 2) + end do + + write(*, '(A,I1,A,A)') "b=", bv, " ", trim(names(bv)) + write(*, '(A)') "First 15 Lucas sequence terms:" + write(*, '(5(1X,I18))') seq(1:5) ! rows of 5 for compact display + write(*, '(5(1X,I18))') seq(6:10) + write(*, '(5(1X,I18))') seq(11:15) + + ! ----------------------------------------------------------------------- + ! Part B: Converge the ratio to ndec=32 decimal places. + ! + ! Special case b=0: the sequence is identically 1, the ratio is + ! exactly 1, and the formula (0 + sqrt(4)) / 2 = 1 confirms this. + ! No iteration is needed. + ! ----------------------------------------------------------------------- + if (bv == 0) then + write(*, '(A)') "Ratio = 1 (exact, degenerate Platinum case)" + write(*, *) + cycle ! skip to next b + end if + + ! Seed the big-int sequence with x(1) = 1, x(2) = 1. + call bg_set(xa, na, 1_int64) ! xa = x(n-1) = 1 (previous-previous term) + call bg_set(xb, nb_v, 1_int64) ! xb = x(n) = 1 (previous term) + + prev_str = '' ! empty string: guaranteed not to match first ratio + converged = .false. + iter = 2 ! we already have terms 1 and 2 in xa and xb + + ! ----------------------------------------------------------------------- + ! Iteration loop. + ! + ! Each pass: + ! 1. Compute x(n+1) = bv * x(n) + x(n-1) using big-int arithmetic. + ! 2. Compute the ratio x(n+1) / x(n) to ndec decimal places. + ! 3. Compare with the ratio from the previous iteration. + ! If identical, the approximation has stabilised and we stop. + ! Otherwise record the new ratio and advance the sequence. + ! + ! Note on aliasing: bg_mul_s and bg_add require distinct arrays for + ! input and output, so we use xc and xt as intermediates rather than + ! overwriting xb in place. + ! ----------------------------------------------------------------------- + do while (.not. converged) + + ! Step 1: compute the new sequence term. + ! xc = bv * xb (b * x(n)) + ! xt = xc + xa (b * x(n) + x(n-1) = x(n+1)) + call bg_mul_s(xb, nb_v, bv, xc, nc) ! xc = bv * x(n) + call bg_add(xc, nc, xa, na, xt, nt_v) ! xt = xc + x(n-1) + + ! Step 2: form the ratio x(n+1) / x(n) as a decimal string. + call bg_div_dec(xt, nt_v, xb, nb_v, ndec, curr_str) + + ! Step 3: test for convergence. + ! Fortran character comparison checks all len(curr_str) characters, + ! including the trailing spaces that Fortran appends to fixed-length + ! strings. Both strings are built identically by bg_div_dec, so + ! trailing-space counts match and the comparison is correct. + if (curr_str == prev_str) then + converged = .true. ! ratio unchanged to ndec places -- done + else + ! Not yet converged: record this ratio and advance the sequence. + ! xa <-- old xb (old x(n) becomes the new x(n-1)) + ! xb <-- xt (new x(n+1) becomes the new x(n)) + prev_str = curr_str + call bg_copy(xb, nb_v, xa, na) ! xa = old xb + call bg_copy(xt, nt_v, xb, nb_v) ! xb = xt + iter = iter + 1 + end if + + end do ! while not converged + + write(*, '(A,I6)') "Converged at n =", iter + write(*, '(2A)') "Ratio = ", trim(curr_str) + write(*, *) + + end do ! bv = 0 .. 9 + + ! ========================================================================== + ! Stretch goal: Golden Ratio (b=1) to 256 decimal places. + ! + ! The Golden Ratio has the SLOWEST convergence of all Metallic Ratios + ! because its continued fraction [1;1,1,1,...] converges most slowly + ! among all irrationals (a classical result in Diophantine approximation). + ! Roughly 256 / log10(phi) ≈ 1225 iterations are needed. + ! At that point each Fibonacci number has about 256 decimal digits, so + ! the big-int arithmetic is the only practical approach. + ! ========================================================================== + write(*, '(A)') repeat('=', 62) + write(*, '(A)') "STRETCH GOAL: Golden Ratio to 256 decimal places" + write(*, '(A)') repeat('=', 62) + write(*, *) + + ndec = 256 + bv = 1 ! Golden Ratio: b=1 + + call bg_set(xa, na, 1_int64) ! seed x(1) = 1 + call bg_set(xb, nb_v, 1_int64) ! seed x(2) = 1 + prev_str = '' + converged = .false. + iter = 2 + + ! Same iteration loop as above; only ndec differs. + do while (.not. converged) + call bg_mul_s(xb, nb_v, bv, xc, nc) + call bg_add(xc, nc, xa, na, xt, nt_v) + call bg_div_dec(xt, nt_v, xb, nb_v, ndec, curr_str) + if (curr_str == prev_str) then + converged = .true. + else + prev_str = curr_str + call bg_copy(xb, nb_v, xa, na) + call bg_copy(xt, nt_v, xb, nb_v) + iter = iter + 1 + end if + end do + + write(*, '(A,I6)') "Converged at n =", iter + write(*, '(A)') "Golden Ratio =" + + ! Print the 258-character result ("1." + 256 digits) as 40-character lines + ! so it is readable in a standard 80-column terminal. + ! The slice boundaries step by 40 through the string, with the last slice + ! picking up the remaining 18 characters (positions 241-258). + write(*, '(A)') curr_str( 1: 42) + write(*, '(A)') curr_str( 43: 82) + write(*, '(A)') curr_str( 83:122) + write(*, '(A)') curr_str(123:162) + write(*, '(A)') curr_str(163:202) + write(*, '(A)') curr_str(203:242) + write(*, '(A)') curr_str(243:258) + write(*, *) + +end program metallic_ratios diff --git a/Task/Metallic-ratios/FreeBASIC/metallic-ratios.basic b/Task/Metallic-ratios/FreeBASIC/metallic-ratios.basic new file mode 100644 index 0000000000..6e0408b64e --- /dev/null +++ b/Task/Metallic-ratios/FreeBASIC/metallic-ratios.basic @@ -0,0 +1,82 @@ +' version 01-11-2024 +' compile with: fbc -s console + +#Include Once "gmp.bi" +#Include Once "crt\stdio.bi" +#Define prec 32 + +Dim Shared As String ratio_names(0 To 9) +For x As Integer = 0 To 9 + Read ratio_names(x) +Next + +Data "Platinum", "Golden", "Silver", "Bronze", "Copper" +Data "Nickel", "Aluminium", "Iron", "Tin", "Lead" + +Sub lucas(b As UInteger) + Print Using "Lucas sequence for & ratio, where b = #";ratio_names(b); b + Dim As UInteger i, l0 = 1, l1 = 1, l2 + Print "First 15 elements are 1, 1"; + For i = 1 To 13 + l2 = b * l1 + l0 + Print ", "; l2; + Swap l0, l1 + Swap l1, l2 + Next + Print +End Sub + +Sub metallic_ratio(b As UInteger, pr As UInteger) + + Dim As UInteger i, dp + Dim As String str1 + Dim As ZString Ptr gmp_str : gmp_str = Allocate(100) + Dim As mpf_ptr bb, l0, l1, l2, ra + bb = Allocate(Len(__Mpf_struct)) : Mpf_init2(bb, pr * 4) + l0 = Allocate(Len(__Mpf_struct)) : Mpf_init2(l0, pr * 4) + l1 = Allocate(Len(__Mpf_struct)) : Mpf_init2(l1, pr * 4) + l2 = Allocate(Len(__Mpf_struct)) : Mpf_init2(l2, pr * 4) + ra = Allocate(Len(__Mpf_struct)) : Mpf_init2(ra, pr * 4) + + mpf_set_ui(bb, b) + mpf_set_ui(l0, 1) + mpf_set_ui(l1, 1) + mpf_div(ra, l1, l0) + Gmp_sprintf(gmp_str, "%.*Ff", pr, ra) + str1 = *gmp_str + + Do + i += 1 + mpf_mul(l2, bb, l1) + mpf_add(l2, l2, l0) + mpf_div(ra, l2, l1) + Gmp_sprintf(gmp_str, "%.*Ff", pr, ra) + If str1 = *gmp_str Then + Print "Value to "; Str(pr); " dp after "; Str(i); " iteration"; IIf(i < 2, "", "s"); ": "; + If pr = 256 Then print + If i = 1 Then Print Trim(Trim(str1,"0"), ".") Else Print str1 + Print + mpf_clears(bb, l0, l1, l2, ra, NULL) + DeAllocate(gmp_str) + Return + End If + str1 = *gmp_str + mpf_swap(l0, l1) + mpf_swap(l1, l2) + Loop +End Sub + +' ------=< MAIN >=------ + +For x As Integer = 0 To 9 + lucas(x) + metallic_ratio(x, prec) +Next +Print "Golden ratio, where b = 1" +metallic_ratio(1, 256) + +' empty keyboard buffer +While Inkey <> "" : Wend +Print : Print "hit any key to end program" +Sleep +End diff --git a/Task/Metallic-ratios/Julia/metallic-ratios.julia b/Task/Metallic-ratios/Julia/metallic-ratios.jl similarity index 100% rename from Task/Metallic-ratios/Julia/metallic-ratios.julia rename to Task/Metallic-ratios/Julia/metallic-ratios.jl diff --git a/Task/Metallic-ratios/Kotlin/metallic-ratios.kotlin b/Task/Metallic-ratios/Kotlin/metallic-ratios.kts similarity index 100% rename from Task/Metallic-ratios/Kotlin/metallic-ratios.kotlin rename to Task/Metallic-ratios/Kotlin/metallic-ratios.kts diff --git a/Task/Metallic-ratios/PascalABC.NET/metallic-ratios.pas b/Task/Metallic-ratios/PascalABC.NET/metallic-ratios.pas new file mode 100644 index 0000000000..e320bdb1ed --- /dev/null +++ b/Task/Metallic-ratios/PascalABC.NET/metallic-ratios.pas @@ -0,0 +1,63 @@ +type + Metal = (platinum, golden, silver, bronze, copper, nickel, aluminium, iron, tin, lead); + +function seq(b: integer): sequence of biginteger; +begin + // Yield the successive terms if a “Lucas” sequence. + // The first two terms are ignored. + var x := 1bi; + var y := 1bi; + while true do + begin + x += b * y; + Swap(x, y); + yield y; + end; +end; + +function plural(n: integer) := if n >= 2 then 's' else ''; + +procedure computeRatio(b: integer; digits: integer); +begin + // Compute the ratio for the given "n" with the required number of digits. + + var M := Power(10bi, digits); + + var niter := 0; // Number of iterations. + var prevN := 1bi; // Previous value of "n". + var ratio := M ; // Current value of ratio. + + foreach var n in seq(b) do + begin + inc(niter); + var nextRatio := n * M div prevN; + if nextRatio = ratio then break; + prevN := n; + ratio := nextRatio; + end; + + var str := ratio.ToString; + insert('.', str, 2); + Writeln('Value to ', digits, ' decimal places after ', niter, ' iteration', plural(niter), ': ',str); +end; + +begin + foreach var b in 0..9 do + begin + Writeln('“Lucas” sequence for ', Metal(b), ' ratio where b = ', b, ':'); + Write('First 15 elements: 1 1 '); + var count := 2; + foreach var n in seq(b) do + begin + Write(' ', n); + Inc(count); + if count = 15 then break + end; + println; + computeRatio(b, 32); + Println; + end; + + Println('Golden ratio where b = 1:'); + computeRatio(1, 256); +end. diff --git a/Task/Metaprogramming/ALGOL-68/metaprogramming.alg b/Task/Metaprogramming/ALGOL-68/metaprogramming.alg index a2dc39d932..6f444bb7c3 100644 --- a/Task/Metaprogramming/ALGOL-68/metaprogramming.alg +++ b/Task/Metaprogramming/ALGOL-68/metaprogramming.alg @@ -102,15 +102,10 @@ OP WITH = ( INSPECTTOREPLACE inspected, STRING replace with )REF STRING: OP DISPLAY = ( STRING s )VOID: write( ( s, newline ) ); - PRIO REPLACING = 2, WITH = 1; - - -main: ( - - # test the INSPECT and DISPLAY "verbs" # +BEGIN # test the INSPECT and DISPLAY "verbs" # STRING text := "some text"; DISPLAY text; @@ -125,7 +120,15 @@ main: ( DISPLAY text; INSPECT text REPLACING LEADING "som" WITH "k"; + DISPLAY text; + + text := "another test"; + DISPLAY text; + + INSPECT text REPLACING FIRST "anot" WITH "ABC"; + DISPLAY text; + + INSPECT text REPLACING LEADING "A" WITH "_"; DISPLAY text - -) +END diff --git a/Task/Metaprogramming/Arturo/metaprogramming-4.arturo b/Task/Metaprogramming/Arturo/metaprogramming-4.arturo index 12c106cc04..930ec45f1d 100644 --- a/Task/Metaprogramming/Arturo/metaprogramming-4.arturo +++ b/Task/Metaprogramming/Arturo/metaprogramming-4.arturo @@ -2,7 +2,7 @@ block: [print] block: block ++ to :integer "34" print "Here is our code:" -print as.code block +print express block print "" print "And here's its result:" diff --git a/Task/Metaprogramming/Julia/metaprogramming.julia b/Task/Metaprogramming/Julia/metaprogramming.jl similarity index 100% rename from Task/Metaprogramming/Julia/metaprogramming.julia rename to Task/Metaprogramming/Julia/metaprogramming.jl diff --git a/Task/Metaprogramming/Kotlin/metaprogramming.kotlin b/Task/Metaprogramming/Kotlin/metaprogramming.kts similarity index 100% rename from Task/Metaprogramming/Kotlin/metaprogramming.kotlin rename to Task/Metaprogramming/Kotlin/metaprogramming.kts diff --git a/Task/Metaprogramming/Red/metaprogramming.red b/Task/Metaprogramming/Red/metaprogramming.red new file mode 100644 index 0000000000..92d4c817d7 --- /dev/null +++ b/Task/Metaprogramming/Red/metaprogramming.red @@ -0,0 +1,42 @@ +Red [ "Metaprogramming - Hinjolicious" ] + +; This function will print a string as a heading and print any codes +; to the screen before executing it. +demo: function [s b] [print ["^/==" s "==^/"] print mold/only b do b] + +demo "Infix Operators Creation" [ +++: make op! function [a b][rejoin [a b]] +print "Hello" ++ ", " ++ "World" ++ "!" +] + +demo "Runtime Code Evaluation" [ +do load ask "Type your code: " +] + +demo "Language Construct Redefinitions and Aliases" [ +show: :print +show "Hello!" + +if-else: :either +if-else (random 100) > 90 [ + show "You're lucky!" +][ + show "Try again!" +] +] + +demo "Code Manipulation" [ +; Create a C-Style for loop +for: function [ init[block!] cond[block!] next[block!] body[block!] ] [ + ; Insert the next block to the end of body block + body: head insert tail copy body next + + ; Compose the block ready to be executed + compose/deep [(init) while [(cond)] [(body)]] +] + +do for [x: 1] [x <= 10] [x: x + 1] [ + print x +] + +] diff --git a/Task/Metaprogramming/Rust/metaprogramming.rust b/Task/Metaprogramming/Rust/metaprogramming.rs similarity index 100% rename from Task/Metaprogramming/Rust/metaprogramming.rust rename to Task/Metaprogramming/Rust/metaprogramming.rs diff --git a/Task/Metaprogramming/V-(Vlang)/metaprogramming.v b/Task/Metaprogramming/V-(Vlang)/metaprogramming.v new file mode 100644 index 0000000000..fd8e734c3b --- /dev/null +++ b/Task/Metaprogramming/V-(Vlang)/metaprogramming.v @@ -0,0 +1,30 @@ +@[heap] +struct Foo { +} + +fn (f Foo) test() int { + return 123 +} + +fn (f Foo) test2() string { + return "foo" +} + +fn main() { + foo := Foo{} + + $if ios || android {println("Running on a mobile device!")} + $if linux && x64 {println("64-bit Linux.")} + os := $if windows {"Windows"} $else {"Something Else"} + println("Using ${os}") + + $for m in Foo.methods { + $if m.return_type is int { + print("${m.name} returns int: ") + println(foo.$method()) + } $else $if m.return_type is string { + print("${m.name} returns string: ") + println(foo.$method()) + } + } +} diff --git a/Task/Metered-concurrency/Ada/metered-concurrency-1.ada b/Task/Metered-concurrency/Ada/metered-concurrency-1.adb similarity index 100% rename from Task/Metered-concurrency/Ada/metered-concurrency-1.ada rename to Task/Metered-concurrency/Ada/metered-concurrency-1.adb diff --git a/Task/Metered-concurrency/Ada/metered-concurrency-2.ada b/Task/Metered-concurrency/Ada/metered-concurrency-2.adb similarity index 100% rename from Task/Metered-concurrency/Ada/metered-concurrency-2.ada rename to Task/Metered-concurrency/Ada/metered-concurrency-2.adb diff --git a/Task/Metered-concurrency/Ada/metered-concurrency-3.ada b/Task/Metered-concurrency/Ada/metered-concurrency-3.adb similarity index 100% rename from Task/Metered-concurrency/Ada/metered-concurrency-3.ada rename to Task/Metered-concurrency/Ada/metered-concurrency-3.adb diff --git a/Task/Metered-concurrency/Euphoria/metered-concurrency.euphoria b/Task/Metered-concurrency/Euphoria/metered-concurrency.eu similarity index 100% rename from Task/Metered-concurrency/Euphoria/metered-concurrency.euphoria rename to Task/Metered-concurrency/Euphoria/metered-concurrency.eu diff --git a/Task/Metered-concurrency/Julia/metered-concurrency.julia b/Task/Metered-concurrency/Julia/metered-concurrency.jl similarity index 100% rename from Task/Metered-concurrency/Julia/metered-concurrency.julia rename to Task/Metered-concurrency/Julia/metered-concurrency.jl diff --git a/Task/Metered-concurrency/Kotlin/metered-concurrency.kotlin b/Task/Metered-concurrency/Kotlin/metered-concurrency.kts similarity index 100% rename from Task/Metered-concurrency/Kotlin/metered-concurrency.kotlin rename to Task/Metered-concurrency/Kotlin/metered-concurrency.kts diff --git a/Task/Metered-concurrency/PascalABC.NET/metered-concurrency.pas b/Task/Metered-concurrency/PascalABC.NET/metered-concurrency.pas new file mode 100644 index 0000000000..28eea66021 --- /dev/null +++ b/Task/Metered-concurrency/PascalABC.NET/metered-concurrency.pas @@ -0,0 +1,20 @@ +uses System, System.Threading, System.Threading.Tasks; + +procedure Worker(arg: SemaphoreSlim; id: integer); +begin + var sem: SemaphoreSlim := arg; + sem.Wait(); + Writeln('Thread ', id, ' has a semaphore & is now working.'); + Thread.Sleep(2 * 1000); + Writeln('#', id, 'done.'); + sem.Release(); +end; + +begin + var semaphore := new SemaphoreSlim(Environment.ProcessorCount * 2, MaxInt); + + Writeln('You have ', Environment.ProcessorCount, ' processors availiabe'); + Writeln('This program will use ', semaphore.CurrentCount, ' semaphores.'); + + Parallel.For(0, Environment.ProcessorCount * 3, y -> Worker(semaphore, y)); +end. diff --git a/Task/Metered-concurrency/Rust/metered-concurrency.rust b/Task/Metered-concurrency/Rust/metered-concurrency.rs similarity index 100% rename from Task/Metered-concurrency/Rust/metered-concurrency.rust rename to Task/Metered-concurrency/Rust/metered-concurrency.rs diff --git a/Task/Metronome/Ada/metronome.ada b/Task/Metronome/Ada/metronome.adb similarity index 100% rename from Task/Metronome/Ada/metronome.ada rename to Task/Metronome/Ada/metronome.adb diff --git a/Task/Metronome/Delphi/metronome.delphi b/Task/Metronome/Delphi/metronome.pas similarity index 100% rename from Task/Metronome/Delphi/metronome.delphi rename to Task/Metronome/Delphi/metronome.pas diff --git a/Task/Metronome/Julia/metronome.julia b/Task/Metronome/Julia/metronome.jl similarity index 100% rename from Task/Metronome/Julia/metronome.julia rename to Task/Metronome/Julia/metronome.jl diff --git a/Task/Metronome/Kotlin/metronome.kotlin b/Task/Metronome/Kotlin/metronome.kts similarity index 100% rename from Task/Metronome/Kotlin/metronome.kotlin rename to Task/Metronome/Kotlin/metronome.kts diff --git a/Task/Mian-Chowla-sequence/ALGOL-68/mian-chowla-sequence.alg b/Task/Mian-Chowla-sequence/ALGOL-68/mian-chowla-sequence.alg index 3274d75fbf..37c3eb9683 100644 --- a/Task/Mian-Chowla-sequence/ALGOL-68/mian-chowla-sequence.alg +++ b/Task/Mian-Chowla-sequence/ALGOL-68/mian-chowla-sequence.alg @@ -8,7 +8,8 @@ BEGIN [ max mc ]INT mc; INT curr size := 0; # initial size of the array # INT size increment = 10 000; # size to increase the array by # - REF[]BOOL is sum := HEAP[ 1 : 0 ]BOOL; + HEAP[ 1 : 0 ]BOOL empty sum; + REF[]BOOL is sum := empty sum; INT mc count := 1; FOR i WHILE mc count <= max mc DO # assume i will be part of the sequence # diff --git a/Task/Mian-Chowla-sequence/ALGOL-W/mian-chowla-sequence.alg b/Task/Mian-Chowla-sequence/ALGOL-W/mian-chowla-sequence.alg new file mode 100644 index 0000000000..ff9e1077d4 --- /dev/null +++ b/Task/Mian-Chowla-sequence/ALGOL-W/mian-chowla-sequence.alg @@ -0,0 +1,55 @@ +% Find Mian-Chowla numbers: an + where: ai = 1, + and: an = smallest integer such that ai + aj is unique + for all i, j in 1 .. n && i <= j +% +begin + record HashedSum ( integer hSum; reference(HashedSum) hNext ); + integer HASH_MOD, MAX_MC; + HASH_MOD := 10000; + MAX_MC := 100; + begin + % hash table of sums of the sequence elements encountered so far % + reference(HashedSum) array sums ( 0 :: HASH_MOD - 1 ); + % table of the sequence elements encountered so far % + integer array mc ( 1 :: MAX_MC ); + integer mcCount, i; + for i := 0 until HASH_MOD - 1 do sums( i ) := null; + mcCount := 1; + i := 0; + while begin i := i + 1; mcCount <= MAX_MC end do begin + logical isUnique; + integer mcPos; + % assume i will be part of the sequence % + mc( mcCount ) := i; + % check the sums % + isUnique := true; + mcPos := 0; + while begin mcPos := mcPos + 1; mcPos <= mcCount and isUnique end do begin + integer s; + reference(HashedSum) hs; + % attempt to find the sum in the hash table % + s := i + mc( mcPos ); + hs := sums( s rem HASH_MOD ); + while hs not = null and s not = hSum(hs) do hs := hNext(hs); + isUnique := hs = null + end while_isUnique; + if isUnique then begin + % i is a sequence element - store its sums % + for mcPos := 1 until mcCount do begin + integer newSum, sumHash; + newSum := i + mc( mcPos ); + sumHash := newSum rem HASH_MOD; + sums( sumHash ) := HashedSum( newSum, sums( sumHash ) ) + end for_mcPos ; + mcCount := mcCount + 1 + end if_isUnique + end while_mcCount_le_MAX_MC; + + % print parts of the sequence % + write( "Mian Chowla sequence elements 1..30:" );write(); + for i := 1 until 30 do writeon( i_w := 1, s_w := 0, " ", mc( i ) ); + write( "Mian Chowla sequence elements 91..100:" );write(); + for i := 91 until 100 do writeon( i_w := 1, s_w := 0, " ", mc( i ) ) + end +end. diff --git a/Task/Mian-Chowla-sequence/Ada/mian-chowla-sequence.ada b/Task/Mian-Chowla-sequence/Ada/mian-chowla-sequence.adb similarity index 100% rename from Task/Mian-Chowla-sequence/Ada/mian-chowla-sequence.ada rename to Task/Mian-Chowla-sequence/Ada/mian-chowla-sequence.adb diff --git a/Task/Mian-Chowla-sequence/Agena/mian-chowla-sequence.agena b/Task/Mian-Chowla-sequence/Agena/mian-chowla-sequence.agena new file mode 100644 index 0000000000..b81c43d6ff --- /dev/null +++ b/Task/Mian-Chowla-sequence/Agena/mian-chowla-sequence.agena @@ -0,0 +1,31 @@ +scope /* Find Mian-Chowla numbers: an + * where: ai = 1, + * and: an = smallest integer such that ai + aj is unique + * for all i, j in 1 .. n && i <= j + */ + + local maxMc, mcCount, mc, isSum := 100, 1, seq(), seq(); + for i while mcCount <= maxMc do + # assume i will be part of the sequence + mc[ mcCount ] := i; + # check the sums + local isUnique := true + for mcPos to mcCount while isUnique do + if isSum[ i + mc[ mcPos ] ] then + isUnique := false + fi + od; + if isUnique then + # i is a sequence element - store the sums + for k to mcCount do isSum[ i + mc[ k ] ] := true od; + mcCount +:= 1 + fi + od; + + # print parts of the sequence + printf( "Mian Chowla sequence elements 1..30:\n" ); + for i to 30 do printf( " %d", mc[ i ] ) od; + printf( "\nMian Chowla sequence elements 91..100:\n" ); + for i from 91 to 100 do printf( " %d", mc[ i ] ) od + +end diff --git a/Task/Mian-Chowla-sequence/Arturo/mian-chowla-sequence.arturo b/Task/Mian-Chowla-sequence/Arturo/mian-chowla-sequence.arturo index d44ec4ca66..0d05289b3d 100644 --- a/Task/Mian-Chowla-sequence/Arturo/mian-chowla-sequence.arturo +++ b/Task/Mian-Chowla-sequence/Arturo/mian-chowla-sequence.arturo @@ -1,6 +1,6 @@ mianChowla: function [n][ - result: new [1] - sums: new [2] + result: [1] + sums: [2] candidate: 1 while [n > size result][ diff --git a/Task/Mian-Chowla-sequence/EasyLang/mian-chowla-sequence.easy b/Task/Mian-Chowla-sequence/EasyLang/mian-chowla-sequence.easy new file mode 100644 index 0000000000..ee9400b53e --- /dev/null +++ b/Task/Mian-Chowla-sequence/EasyLang/mian-chowla-sequence.easy @@ -0,0 +1,37 @@ +func[] mian_chowla n . + len mc[] n + mc[1] = 1 + is[] = [ 0 1 ] + for i = 2 to n + j = mc[i - 1] + repeat + j += 1 + mc[i] = j + for k = 1 to i + sum = mc[k] + j + if sum > len is[] + len is[] sum + 10000 + . + if is[sum] = 1 + isnew[] = [ ] + break 1 + . + isnew[] &= sum + . + until len isnew[] > 0 + . + for v in isnew[] + is[v] = 1 + . + . + return mc[] +. +mc[] = mian_chowla 100 +for i to 30 + write mc[i] & " " +. +print "" +print "" +for i = 91 to 100 + write mc[i] & " " +. diff --git a/Task/Mian-Chowla-sequence/Icon/mian-chowla-sequence.icon b/Task/Mian-Chowla-sequence/Icon/mian-chowla-sequence.icon new file mode 100644 index 0000000000..ad77e69de7 --- /dev/null +++ b/Task/Mian-Chowla-sequence/Icon/mian-chowla-sequence.icon @@ -0,0 +1,22 @@ +procedure main(A) + limit := \A[1] | 100 + cnt := 0 + write("First 30 terms:") + every cnt +:= (m := mian()\limit,1) do { + if cnt <= 30 then writes(" ",m) + if cnt = 30 then write("\nTerms 91 to 100:") + if 91 <= cnt <= 100 then writes(" ",m) + } + write() +end + +procedure mian() + a := [1] + suspend 1 + every n := seq(2) do { + every (sums := set(), s := (i := a[k := 1 to *a]) + (j := a[k to *a]|n)) do + if member(sums, s) then break next + else insert(sums,s) + suspend (put(a,n),n) + } +end diff --git a/Task/Mian-Chowla-sequence/Julia/mian-chowla-sequence.julia b/Task/Mian-Chowla-sequence/Julia/mian-chowla-sequence.jl similarity index 100% rename from Task/Mian-Chowla-sequence/Julia/mian-chowla-sequence.julia rename to Task/Mian-Chowla-sequence/Julia/mian-chowla-sequence.jl diff --git a/Task/Mian-Chowla-sequence/Kotlin/mian-chowla-sequence-1.kotlin b/Task/Mian-Chowla-sequence/Kotlin/mian-chowla-sequence-1.kts similarity index 100% rename from Task/Mian-Chowla-sequence/Kotlin/mian-chowla-sequence-1.kotlin rename to Task/Mian-Chowla-sequence/Kotlin/mian-chowla-sequence-1.kts diff --git a/Task/Mian-Chowla-sequence/Kotlin/mian-chowla-sequence-2.kotlin b/Task/Mian-Chowla-sequence/Kotlin/mian-chowla-sequence-2.kts similarity index 100% rename from Task/Mian-Chowla-sequence/Kotlin/mian-chowla-sequence-2.kotlin rename to Task/Mian-Chowla-sequence/Kotlin/mian-chowla-sequence-2.kts diff --git a/Task/Mian-Chowla-sequence/PascalABC.NET/mian-chowla-sequence.pas b/Task/Mian-Chowla-sequence/PascalABC.NET/mian-chowla-sequence.pas new file mode 100644 index 0000000000..6d9a76aa64 --- /dev/null +++ b/Task/Mian-Chowla-sequence/PascalABC.NET/mian-chowla-sequence.pas @@ -0,0 +1,29 @@ +function mian_chowla(): sequence of integer; +label 1; +begin + var mc := Lst(1); + yield 1; + var psums: set of integer := [2]; + var newsums: set of integer := []; + foreach var trial in 2.Step do + begin + foreach var n in (mc + [trial]) do + begin + var sum := n + trial; + if sum in psums then goto 1; + newsums.add(sum) + end; + psums += newsums; + mc.add(trial); + yield trial; + 1: newsums := []; + end; +end; + +begin + println('The first 30 terms of the Mian-Chowla sequence are:'); + mian_chowla.Take(30).Println; + println; + println('Terms 91 to 100 of the Mian-Chowla sequence are:'); + mian_chowla.Skip(90).Take(10).Println; +end. diff --git a/Task/Mian-Chowla-sequence/Pluto/mian-chowla-sequence.pluto b/Task/Mian-Chowla-sequence/Pluto/mian-chowla-sequence.pluto new file mode 100644 index 0000000000..f4664e2ee8 --- /dev/null +++ b/Task/Mian-Chowla-sequence/Pluto/mian-chowla-sequence.pluto @@ -0,0 +1,35 @@ +do --[[ Find Mian-Chowla numbers: an + where: ai = 1, + and: an = smallest integer such that ai + aj is unique + for all i, j in 1 .. n && i <= j + ]] + local fmt = require( "fmt" ) + + local maxMc, mcCount, mc, isSum = 100, 1, {}, {} + local i = 0 + while mcCount <= maxMc do + ++ i + -- assume i will be part of the sequence + mc[ mcCount ] = i + -- check the sums + local isUnique = true + for mcPos = 1, mcCount do + if isSum[ i + mc[ mcPos ] ] then + isUnique = false + break + end + end + if isUnique then + -- i is a sequence element - store the sums + for k = 1, mcCount do isSum[ i + mc[ k ] ] = true end + ++ mcCount + end + end + + -- print parts of the sequence + io.write( "Mian Chowla sequence elements 1..30:\n " ) + fmt.lprint( table.slice( mc, 1, 30 ), " ", "" ) + io.write( "Mian Chowla sequence elements 91..100:\n " ) + fmt.lprint( table.slice( mc, 91, 100 ), " ", "" ) + +end diff --git a/Task/Mian-Chowla-sequence/VBScript/mian-chowla-sequence-1.vb b/Task/Mian-Chowla-sequence/VBScript/mian-chowla-sequence-1.vbs similarity index 100% rename from Task/Mian-Chowla-sequence/VBScript/mian-chowla-sequence-1.vb rename to Task/Mian-Chowla-sequence/VBScript/mian-chowla-sequence-1.vbs diff --git a/Task/Mian-Chowla-sequence/VBScript/mian-chowla-sequence-2.vb b/Task/Mian-Chowla-sequence/VBScript/mian-chowla-sequence-2.vbs similarity index 100% rename from Task/Mian-Chowla-sequence/VBScript/mian-chowla-sequence-2.vb rename to Task/Mian-Chowla-sequence/VBScript/mian-chowla-sequence-2.vbs diff --git a/Task/Middle-three-digits/ALGOL-68/middle-three-digits.alg b/Task/Middle-three-digits/ALGOL-68/middle-three-digits.alg index 3ee7c8ffdc..44132b4051 100644 --- a/Task/Middle-three-digits/ALGOL-68/middle-three-digits.alg +++ b/Task/Middle-three-digits/ALGOL-68/middle-three-digits.alg @@ -1,38 +1,36 @@ -# we define a UNION MODE so that our middle 3 digits PROC can # -# return either an integer on success or a error message if # -# the middle 3 digits couldn't be extracted # -MODE EINT = UNION( INT # success value #, STRING # error message # ); -# PROC to return the middle 3 digits of an integer. # -# if this is not possible, an error message is returned # -# instead # -PROC middle 3 digits = ( INT number ) EINT: BEGIN - # convert the absolute value of the number to a string with the # - # minumum possible number characters # - STRING digits = whole( ABS number, 0 ); - INT len = UPB digits; - IF len < 3 - THEN - # number has less than 3 digits # - # return an error message # - "number must have at least three digits" - ELIF ( len MOD 2 ) = 0 - THEN - # the number has an even number of digits # - # return an error message # - "number must have an odd number of digits" - ELSE - # the number is suitable for extraction of the middle 3 digits # - INT first digit pos = 1 + ( ( len - 3 ) OVER 2 ); - # the result is the integer value of the three digits # - ( ( ( ABS digits[ first digit pos ] - ABS "0" ) * 100 ) - + ( ( ABS digits[ first digit pos + 1 ] - ABS "0" ) * 10 ) - + ( ( ABS digits[ first digit pos + 2 ] - ABS "0" ) ) - ) - FI -END; # middle 3 digits # + # we define a UNION MODE so that our middle 3 digits PROC can # + # return either an integer on success or a error message if # + # the middle 3 digits couldn't be extracted # + MODE EINT = UNION( INT # success value #, STRING # error message # ); + # PROC to return the middle 3 digits of an integer. # + # if this is not possible, an error message is returned # + # instead # + PROC middle 3 digits = ( INT number ) EINT: + BEGIN + # convert the absolute value of the number to a string with the # + # minumum possible number characters # + STRING digits = whole( ABS number, 0 ); + INT len = UPB digits; + IF len < 3 + THEN + # number has less than 3 digits return an error message # + "number must have at least three digits" + ELIF len MOD 2 = 0 + THEN + # the number has an even number of digits- return an error message # + "number must have an odd number of digits" + ELSE + # the number is suitable for extraction of the middle 3 digits # + INT first digit pos = 1 + ( ( len - 3 ) OVER 2 ); + # the result is the integer value of the three digits # + ( ( ( ABS digits[ first digit pos ] - ABS "0" ) * 100 ) + + ( ( ABS digits[ first digit pos + 1 ] - ABS "0" ) * 10 ) + + ( ( ABS digits[ first digit pos + 2 ] - ABS "0" ) ) + ) + FI + END; # middle 3 digits # -main: ( # test the middle 3 digits PROC # []INT test values = ( 123, 12345, 1234567, 987654321 , 10001, -10001, -123, -100 @@ -60,4 +58,4 @@ main: ( ESAC; print( ( newline ) ) OD -) +END diff --git a/Task/Middle-three-digits/Ada/middle-three-digits.ada b/Task/Middle-three-digits/Ada/middle-three-digits.adb similarity index 100% rename from Task/Middle-three-digits/Ada/middle-three-digits.ada rename to Task/Middle-three-digits/Ada/middle-three-digits.adb diff --git a/Task/Middle-three-digits/ArkScript/middle-three-digits.ark b/Task/Middle-three-digits/ArkScript/middle-three-digits.ark new file mode 100644 index 0000000000..2ebf03fae1 --- /dev/null +++ b/Task/Middle-three-digits/ArkScript/middle-three-digits.ark @@ -0,0 +1,15 @@ +(import std.Math) +(import std.String) + +(let middle_three_digits (fun (i) { + (let s (toString (math:abs i))) + (if (and (math:odd (len s)) (>= (len s) 3)) + (string:slice s (- (/ (len s) 2) 1) 3) + "Need odd and at least 3 digits") })) + +(import std.List :forEach) + +(forEach [123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345] + (fun (x) (print (middle_three_digits x)))) +(forEach [1 2 -1 -10 2002 -2002 0] + (fun (x) (print (middle_three_digits x)))) diff --git a/Task/Middle-three-digits/COBOL/middle-three-digits-1.cobol b/Task/Middle-three-digits/COBOL/middle-three-digits-1.cob similarity index 100% rename from Task/Middle-three-digits/COBOL/middle-three-digits-1.cobol rename to Task/Middle-three-digits/COBOL/middle-three-digits-1.cob diff --git a/Task/Middle-three-digits/COBOL/middle-three-digits-2.cobol b/Task/Middle-three-digits/COBOL/middle-three-digits-2.cob similarity index 100% rename from Task/Middle-three-digits/COBOL/middle-three-digits-2.cobol rename to Task/Middle-three-digits/COBOL/middle-three-digits-2.cob diff --git a/Task/Middle-three-digits/Crystal/middle-three-digits.cr b/Task/Middle-three-digits/Crystal/middle-three-digits.cr new file mode 100644 index 0000000000..12762e5e93 --- /dev/null +++ b/Task/Middle-three-digits/Crystal/middle-three-digits.cr @@ -0,0 +1,23 @@ +struct Int + def mtd + n = self.abs + raise "Not enough digits" unless n >= 100 + ds = n.digits + raise "Even digits" unless ds.size.odd? + ds[ds.size // 2 - 1, 3].reverse + end +end + +puts "Should succeed:" +[123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345].each do |n| + printf "%10d: %s\n", n, n.mtd +end +puts "Should fail:" +[1, 2, -1, -10, 2002, -2002, 0].each do |n| + printf "%10d: ", n + begin + puts n.mtd + rescue ex + puts ex.message + end +end diff --git a/Task/Middle-three-digits/DuckDB/middle-three-digits.duckdb b/Task/Middle-three-digits/DuckDB/middle-three-digits.duckdb new file mode 100644 index 0000000000..82b43f646d --- /dev/null +++ b/Task/Middle-three-digits/DuckDB/middle-three-digits.duckdb @@ -0,0 +1,22 @@ +create or replace function middle3digits_helper(s) as ( + select if (invalid_character, 'invalid character found', + if (invalid_n, 'invalid number of digits', + s[p+1 : p+3])) as result + from (select + regexp_matches(s, '[^0-9]') as invalid_character, + (length(s) < 3 or (length(s) % 2 = 0)) as invalid_n, + (length(s) - 3) // 2 as p + ) +); + +create or replace function middle3digits(number) as ( + middle3digits_helper(replace(trim(number::VARCHAR),'-','')) +); + +## Examples +select middle3digits('xyzzy'); + +select n, middle3digits(n) +from unnest( [ + 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, + 1, 2, -1, -10, 2002, -2002, 0 ]) _(n) ; diff --git a/Task/Middle-three-digits/Elena/middle-three-digits.elena b/Task/Middle-three-digits/Elena/middle-three-digits.elena index 6386c6f2df..181108ea11 100644 --- a/Task/Middle-three-digits/Elena/middle-three-digits.elena +++ b/Task/Middle-three-digits/Elena/middle-three-digits.elena @@ -1,7 +1,7 @@ import system'routines; import extensions; -middleThreeDigits(int n) +MiddleThreeDigits(int n) { string s := n.Absolute.toString(); int len := s.Length; @@ -19,11 +19,11 @@ middleThreeDigits(int n) ^ s.Substring(mid-1,3) } -public program() +public Program() { new int[]{123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0} .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/Elixir/middle-three-digits.elixir b/Task/Middle-three-digits/Elixir/middle-three-digits.ex similarity index 100% rename from Task/Middle-three-digits/Elixir/middle-three-digits.elixir rename to Task/Middle-three-digits/Elixir/middle-three-digits.ex diff --git a/Task/Middle-three-digits/Julia/middle-three-digits.julia b/Task/Middle-three-digits/Julia/middle-three-digits.jl similarity index 100% rename from Task/Middle-three-digits/Julia/middle-three-digits.julia rename to Task/Middle-three-digits/Julia/middle-three-digits.jl diff --git a/Task/Middle-three-digits/Kotlin/middle-three-digits.kotlin b/Task/Middle-three-digits/Kotlin/middle-three-digits.kts similarity index 100% rename from Task/Middle-three-digits/Kotlin/middle-three-digits.kotlin rename to Task/Middle-three-digits/Kotlin/middle-three-digits.kts diff --git a/Task/Middle-three-digits/OCaml/middle-three-digits.ocaml b/Task/Middle-three-digits/OCaml/middle-three-digits.ml similarity index 100% rename from Task/Middle-three-digits/OCaml/middle-three-digits.ocaml rename to Task/Middle-three-digits/OCaml/middle-three-digits.ml diff --git a/Task/Middle-three-digits/PascalABC.NET/middle-three-digits.pas b/Task/Middle-three-digits/PascalABC.NET/middle-three-digits.pas new file mode 100644 index 0000000000..4763087818 --- /dev/null +++ b/Task/Middle-three-digits/PascalABC.NET/middle-three-digits.pas @@ -0,0 +1,28 @@ +type + ErrOdd = class (Exception) end; + ErrLen = class (Exception) end; + +function middle_three_digits(i: integer): string; +begin + var s := abs(i).ToString; + if s.Length < 3 then raise new ErrLen; + if s.Length mod 2 = 0 then raise new ErrOdd; + var mid := s.Length div 2; + result := s[mid:mid + 3]; +end; + +begin + var passing := |123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345|; + var failing := |1, 2, -1, -10, 2002, -2002, 0|; + + foreach var x in passing + failing do + try + var answer := middle_three_digits(x); + writeln(x:10, ' -> ', answer); + except + on ErrOdd do + writeln(x:10, ' -> must have an odd number of digits'); + on ErrLen do + writeln(x:10, ' -> must have 3 digits or more'); + end; +end. diff --git a/Task/Middle-three-digits/Pluto/middle-three-digits.pluto b/Task/Middle-three-digits/Pluto/middle-three-digits.pluto new file mode 100644 index 0000000000..a2665195d4 --- /dev/null +++ b/Task/Middle-three-digits/Pluto/middle-three-digits.pluto @@ -0,0 +1,19 @@ +local fmt = require "fmt" + +local function middle3(n) + if n < 0 then n = -n end + local s = tostring(n) + local c = #s + if c < 3 then return $"Minimum is 3 digits, only has {c}." end + if c % 2 == 0 then return $"Number of digits must be odd, {c} is even." end + if c == 3 then return s end + local d = (c - 1) / 2 + return s:sub(d, d + 2) +end + +local a = {123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, + 1, 2, -1, -10, 2002, -2002, 0} + +for a as e do + fmt.print("%9d -> %s", e, middle3(e)) +end diff --git a/Task/Middle-three-digits/PowerShell/middle-three-digits.psh b/Task/Middle-three-digits/PowerShell/middle-three-digits.ps1 similarity index 100% rename from Task/Middle-three-digits/PowerShell/middle-three-digits.psh rename to Task/Middle-three-digits/PowerShell/middle-three-digits.ps1 diff --git a/Task/Middle-three-digits/R/middle-three-digits.r b/Task/Middle-three-digits/R/middle-three-digits.r new file mode 100644 index 0000000000..4c7c592539 --- /dev/null +++ b/Task/Middle-three-digits/R/middle-three-digits.r @@ -0,0 +1,36 @@ +#Simple method +options(scipen=99) + +middle3digits <- function(n){ + s <- abs(n) |> as.character() + k <- nchar(s) + if(k<3) stop("not enough digits") + if(k%%2==0) stop("even number of digits") + substr(s, (k-1)/2, (k+3)/2) +} + +#Alternate method without disabling scientific notation +numdigits <- function(n) ifelse(log10(n)%%1==0, + 1+log10(n), + ceiling(log10(n))) + +middle3digits <- function(n){ + n <- abs(n) + k <- numdigits(n) + if(k<3|is.na(k)) stop("not enough digits") + if(k%%2==0) stop("even number of digits") + pow10 <- 10^((k-3)/2) + mid <- (n%/%pow10)%%1000 + if(mid<100){ + mid <- as.character(mid) + mid_pad <- paste0(c(rep(0, 3-nchar(mid)), mid), collapse="") + return(mid_pad) + } + return(as.character(mid)) +} + +#Testing examples +test_nums <- c(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345) +test_errors <- c(1, 2, -1, -10, 2002, -2002, 0) +cat(sapply(test_nums, middle3digits)) +for(n in test_errors) try(middle3digits(n)) diff --git a/Task/Middle-three-digits/Rust/middle-three-digits.rust b/Task/Middle-three-digits/Rust/middle-three-digits.rs similarity index 100% rename from Task/Middle-three-digits/Rust/middle-three-digits.rust rename to Task/Middle-three-digits/Rust/middle-three-digits.rs diff --git a/Task/Middle-three-digits/Tcl/middle-three-digits-1.tcl b/Task/Middle-three-digits/Tcl/middle-three-digits-1.tcl deleted file mode 100644 index c52d018ab8..0000000000 --- a/Task/Middle-three-digits/Tcl/middle-three-digits-1.tcl +++ /dev/null @@ -1,14 +0,0 @@ -proc middleThree n { - if {$n < 0} { - set n [expr {-$n}] - } - set idx [expr {[string length $n] - 2}] - if {$idx % 2 == 0} { - error "no middle three digits: input is of even length" - } - if {$idx < 1} { - error "no middle three digits: insufficient digits" - } - set idx [expr {$idx / 2}] - string range $n $idx [expr {$idx+2}] -} diff --git a/Task/Middle-three-digits/Tcl/middle-three-digits-2.tcl b/Task/Middle-three-digits/Tcl/middle-three-digits-2.tcl deleted file mode 100644 index 638edd926c..0000000000 --- a/Task/Middle-three-digits/Tcl/middle-three-digits-2.tcl +++ /dev/null @@ -1,12 +0,0 @@ -foreach n { - 123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345 - 1 2 -1 -10 2002 -2002 0 -} { - if {[catch { - set mid [middleThree $n] - } msg]} then { - puts "error for ${n}: $msg" - } else { - puts "found for ${n}: $mid" - } -} diff --git a/Task/Middle-three-digits/Tcl/middle-three-digits.tcl b/Task/Middle-three-digits/Tcl/middle-three-digits.tcl new file mode 100644 index 0000000000..b7f198811d --- /dev/null +++ b/Task/Middle-three-digits/Tcl/middle-three-digits.tcl @@ -0,0 +1,91 @@ +#!/usr/bin/env tclsh + +# output middle 3 digits or error + +# good integers +set good {123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345} + +# bad integers +set bad {doggy 1 2 -1 -10 2002 -2002 0} + +proc middle_3 {num} { + + # error messages + array set error { + notint {(not an integer)} + short {(number < 3 digits)} + even {(even number of digits)} + zero {(zero length entry)} + {unknown} {(unknown error)} + } + + set err 0 + + # must be integer + if { ! [string is integer $num] } { + set err 1 + set errstr $error(notint) + } + + # work with positive val + if { $num < 0 } { set num [expr {abs($num)} ] } + + # how many digits + set dlen [string length $num] + + if {$dlen < 3} { + set err 1 + set errstr $error(short) + } + + if {$dlen % 2 == 0} { + set err 1 + set errstr $error(even) + } + + if {$err} { + + # " (err)" + set output [format "%*s%s" 10 "" "$errstr"] + + } else { + + # split into list of each letter + set letters [split $num ""] + + # middle of list + set mid [expr {$dlen / 2}] + + # get 3 in the middle + set a [lindex $letters [expr {$mid-1} ] ] + set b [lindex $letters [expr {$mid} ] ] + set c [lindex $letters [expr {$mid+1} ] ] + + # " 123" + set output [format "%*s%d" 10 "" "$a$b$c"] + } + + return $output +} + + + +# start here + +puts stdout "test good list:\n" +puts stdout "${good}" + +foreach num $good { + set n [middle_3 $num ] + puts stdout "$num:\t$n" +} + +puts "" +puts stdout "test bad list:\n" +puts stdout "${bad}" + +foreach num $bad { + set n [middle_3 $num ] + + puts stdout "$num:\t$n" +} diff --git a/Task/Middle-three-digits/Uiua/middle-three-digits.uiua b/Task/Middle-three-digits/Uiua/middle-three-digits.uiua new file mode 100644 index 0000000000..c76165fdf5 --- /dev/null +++ b/Task/Middle-three-digits/Uiua/middle-three-digits.uiua @@ -0,0 +1,9 @@ +[ 123 12345 1234567 987654321 10001 ¯10001 ¯123 ¯100 100 ¯12345 + 1 2 ¯1 ¯10 2002 ¯2002 0] +Mid ← ( + ⍤"too short"⊸≥3⊸⧻°⋕⌵ + ⍤"even length"≠0⊸◿2 + ↘¯⟜↘⌊÷2-3 +) +⍉⊟⟜≡⍚⍣(Mid|⊂"Error: "◌) # Convert each +≡(&p$"_\t->\t_"°⊟) # Display diff --git a/Task/Middle-three-digits/V-(Vlang)/middle-three-digits.v b/Task/Middle-three-digits/V-(Vlang)/middle-three-digits.v index 6e4da2d43b..cb6f5ed399 100644 --- a/Task/Middle-three-digits/V-(Vlang)/middle-three-digits.v +++ b/Task/Middle-three-digits/V-(Vlang)/middle-three-digits.v @@ -1,21 +1,17 @@ import math -const -( - valid = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345] - invalid = [1, 2, -1, -10, 2002, -2002, 0] -) +const valid = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345] +const invalid = [1, 2, -1, -10, 2002, -2002, 0] fn main() { - for elem in valid {println(middle(elem))} - for elem in invalid {println(middle(elem))} + for elem in valid { println(middle(elem)) } + for elem in invalid { println(middle(elem)) } } - fn middle(num int) string { mut strip := math.abs(num).str() - if strip.len < 3 {return 'Error: $num has less than 3 digits'} - if strip.len % 2 == 0 {return 'Error: $num has an even number of digits'} + if strip.len < 3 { return "Error: $num has less than 3 digits" } + if strip.len % 2 == 0 { return "Error: $num has an even number of digits" } start := (strip.len / 2) - 1 return strip.substr(start, start + 3) } diff --git a/Task/Middle-three-digits/VBScript/middle-three-digits.vb b/Task/Middle-three-digits/VBScript/middle-three-digits.vbs similarity index 100% rename from Task/Middle-three-digits/VBScript/middle-three-digits.vb rename to Task/Middle-three-digits/VBScript/middle-three-digits.vbs diff --git a/Task/Miller-Rabin-primality-test/00-META.yaml b/Task/Miller-Rabin-primality-test/00-META.yaml index 6e1f1e846e..84c57179ca 100644 --- a/Task/Miller-Rabin-primality-test/00-META.yaml +++ b/Task/Miller-Rabin-primality-test/00-META.yaml @@ -1,3 +1,2 @@ --- from: http://rosettacode.org/wiki/Miller–Rabin_primality_test -note: Prime Numbers diff --git a/Task/Miller-Rabin-primality-test/00-TASK.txt b/Task/Miller-Rabin-primality-test/00-TASK.txt index 5d2fc3359e..78368f531c 100644 --- a/Task/Miller-Rabin-primality-test/00-TASK.txt +++ b/Task/Miller-Rabin-primality-test/00-TASK.txt @@ -1,24 +1 @@ -The [[wp:Miller–Rabin primality test|Miller–Rabin primality test]] or Rabin–Miller primality test is a primality test: an algorithm which determines whether a given number is prime or not. - -The algorithm, as modified by [[wp:Michael O. Rabin|Michael O. Rabin]] to avoid the [[wp:generalized Riemann hypothesis|generalized Riemann hypothesis]], is a probabilistic algorithm. - -The pseudocode, from [[wp:Miller-Rabin primality test#Algorithm_and_running_time|Wikipedia]] is: - '''Input''': ''n'' > 2, an odd integer to be tested for primality; - ''k'', a parameter that determines the accuracy of the test - '''Output''': ''composite'' if ''n'' is composite, otherwise ''probably prime'' - write ''n'' − 1 as 2''s''·''d'' with ''d'' odd by factoring powers of 2 from ''n'' − 1 - LOOP: '''repeat''' ''k'' times: - pick ''a'' randomly in the range [2, ''n'' − 1] - ''x'' ← ''a''''d'' mod ''n'' - '''if''' ''x'' = 1 or ''x'' = ''n'' − 1 '''then''' '''do''' '''next''' LOOP - '''repeat''' ''s'' − 1 times: - ''x'' ← ''x''2 mod ''n'' - '''if''' ''x'' = 1 '''then''' '''return''' ''composite'' - '''if''' ''x'' = ''n'' − 1 '''then''' '''do''' '''next''' LOOP - '''return''' ''composite'' - '''return''' ''probably prime'' - -* The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but '''not''' mandatory. -* Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task) -

    - +#REDIRECT [[Miller-Rabin primality test]] diff --git a/Task/Miller-Rabin-primality-test/11l/miller-rabin-primality-test.11l b/Task/Miller-Rabin-primality-test/11l/miller-rabin-primality-test.11l deleted file mode 100644 index 8a4b097f62..0000000000 --- a/Task/Miller-Rabin-primality-test/11l/miller-rabin-primality-test.11l +++ /dev/null @@ -1,29 +0,0 @@ -F isProbablePrime(n, k = 10) - I n < 2 | n % 2 == 0 - R n == 2 - - V d = n - 1 - V s = 0 - L d % 2 == 0 - d I/= 2 - s++ - - assert(2 ^ s * d == n - 1) - - L 0 .< k - V a = random:(2 .< n) - V x = pow(a, d, n) - I x == 1 | x == n - 1 - L.continue - L 0 .< s - 1 - x = pow(x, 2, n) - I x == 1 - R 0B - I x == n - 1 - L.break - L.was_no_break - R 0B - - R 1B - -print((2..29).filter(x -> isProbablePrime(x))) diff --git a/Task/Miller-Rabin-primality-test/AArch64-Assembly/miller-rabin-primality-test.aarch64 b/Task/Miller-Rabin-primality-test/AArch64-Assembly/miller-rabin-primality-test.aarch64 deleted file mode 100644 index ac6ec0947a..0000000000 --- a/Task/Miller-Rabin-primality-test/AArch64-Assembly/miller-rabin-primality-test.aarch64 +++ /dev/null @@ -1,298 +0,0 @@ -/* ARM assembly AARCH64 Raspberry PI 3B */ -/* program testmiller64B.s */ -// optimisation : one routine - -/************************************/ -/* Constantes */ -/************************************/ -/* for this file see task include a file in language AArch64 assembly*/ -.include "../includeConstantesARM64.inc" - -.equ NBLOOP, 5 // loop number change this if necessary - // if modify, thinck to add test to little prime value - // in routine -//.include "../../ficmacros64.inc" // use for developper debugging -/*******************************************/ -/* Initialized data */ -/*******************************************/ -.data -szMessStartPgm: .asciz "Program 64 bits start \n" -szMessEndPgm: .asciz "Program normal end.\n" -szMessPrime: .asciz " is prime !!!.\n" -szMessNotPrime: .asciz " is not prime !!!.\n" -szCarriageReturn: .asciz "\n" - -/*******************************************/ -/* UnInitialized data */ -/*******************************************/ -.bss -.align 4 -sZoneConv: .skip 24 -/*******************************************/ -/* code section */ -/*******************************************/ -.text -.global main -main: // program start - ldr x0,qAdrszMessStartPgm // display start message - bl affichageMess - ldr x4,iStart // start number - ldr x5,iLimit // end number - tst x4,#1 - cinc x4,x4,eq // start with odd number -1: - mov x0,x4 - bl isPrimeMiller // test miller rabin - cmp x0,#0 - beq 2f - mov x0,x4 - ldr x1,qAdrsZoneConv - bl conversion10 // decimal conversion - ldr x0,qAdrsZoneConv - bl affichageMess - ldr x0,qAdrszMessPrime - bl affichageMess - b 3f -2: - ldr x0,qAdrszMessNotPrime - // bl affichageMess -3: - add x4,x4,#2 - cmp x4,x5 - blo 1b - - ldr x0,qAdrszMessEndPgm // display end message - bl affichageMess - -100: // standard end of the program - mov x0, #0 // return code - mov x8, #EXIT // request to exit program - svc 0 // perform system call -qAdrszMessStartPgm: .quad szMessStartPgm -qAdrszMessEndPgm: .quad szMessEndPgm -qAdrszCarriageReturn: .quad szCarriageReturn -qAdrsZoneConv: .quad sZoneConv -qAdrszMessPrime: .quad szMessPrime -qAdrszMessNotPrime: .quad szMessNotPrime -//iStart: .quad 0x0 -//iLimit: .quad 0x100 -iStart: .quad 0xFFFFFFFFFFFFFF00 -iLimit: .quad 0xFFFFFFFFFFFFFFF0 -//iStart: .quad 341550071728360 -//iLimit: .quad 341550071728380 -//359341550071728361 - -/***************************************************/ -/* test miller rabin algorithme wikipedia */ -/* unsigned */ -/***************************************************/ -/* x0 contains number */ -/* x1 contains parameter */ -/* x0 return 1 if prime 0 if composite */ -isPrimeMiller: - stp x1,lr,[sp,-16]! // TODO: save à completer - stp x2,x3,[sp,-16]! - stp x4,x5,[sp,-16]! - stp x6,x7,[sp,-16]! - stp x8,x9,[sp,-16]! - cmp x0,#1 // control 0 or 1 - csel x0,xzr,x0,ls - bls 100f - cmp x0,#2 // control = 2 - mov x1,1 - csel x0,x1,x0,eq - beq 100f - cmp x0,#3 // control = 3 - csel x0,x1,x0,eq - beq 100f - cmp x0,#5 // control = 5 - csel x0,x1,x0,eq - beq 100f - cmp x0,#7 // control = 7 - csel x0,x1,x0,eq - beq 100f - cmp x0,#11 // control = 11 - csel x0,x1,x0,eq - beq 100f - tst x0,#1 - csel x0,xzr,x0,eq // even - beq 100f - mov x4,x0 // N - sub x3,x0,#1 // D - mov x2,#2 - mov x6,#0 // S -1: // compute D * 2 power S - lsr x3,x3,#1 // D= D/2 - add x6,x6,#1 // increment S - tst x3,#1 // D even ? - beq 1b -2: - mov x8,#0 // loop counter - sub x5,x0,#3 - mov x7,3 -3: - mov x0,x7 - mov x1,x3 // exposant = D - mov x2,x4 // modulo N - bl moduloPur64 - cmp x0,#1 - beq 5f - sub x1,x4,#1 // n -1 - cmp x0,x1 - beq 5f - sub x9,x6,#1 // S - 1 -4: - mov x2,x0 - - mul x0,x2,x2 // compute square lower - umulh x1,x2,x2 // compute square upper - mov x2,x4 // and compute modulo N - bl division64R2023 - mov x0,x2 - cmp x0,#1 - csel x0,xzr,x0,eq // composite - beq 100f - sub x1,x4,#1 // n -1 - cmp x0,x1 - beq 5f - subs x9,x9,#1 - bge 4b - mov x0,#0 // composite - b 100f -5: - add x7,x7,2 - add x8,x8,#1 - cmp x8,NBLOOP - blt 3b - mov x0,#1 // prime -100: - ldp x8,x9,[sp],16 - ldp x6,x7,[sp],16 - ldp x4,x5,[sp],16 - ldp x2,x3,[sp],16 - ldp x1,lr,[sp],16 // TODO: retaur à completer - ret -/********************************************************/ -/* Calcul modulo de b puissance e modulo m */ -/* Exemple 4 puissance 13 modulo 497 = 445 */ -/********************************************************/ -/* x0 nombre */ -/* x1 exposant */ -/* x2 modulo */ -moduloPur64: - stp x1,lr,[sp,-16]! // save registres - stp x3,x4,[sp,-16]! // save registres - stp x5,x6,[sp,-16]! // save registres - stp x7,x8,[sp,-16]! // save registres - stp x9,x10,[sp,-16]! // save registres - cbz x0,100f - cbz x1,100f - mov x8,x0 - mov x7,x1 - mov x10,x2 // modulo - mov x6,1 // resultat - udiv x4,x8,x10 - msub x9,x4,x10,x8 // contient le reste -1: - tst x7,1 - beq 2f - mul x4,x9,x6 - umulh x5,x9,x6 - mov x6,x4 - mov x0,x6 - mov x1,x5 - mov x2,x10 - bl division64R2023 - mov x6,x2 -2: - mul x8,x9,x9 - umulh x5,x9,x9 - mov x0,x8 - mov x1,x5 - mov x2,x10 - bl division64R2023 - mov x9,x2 - lsr x7,x7,1 - cbnz x7,1b - mov x0,x6 // result - cmn x0,0 // clear carry not error - -100: - ldp x9,x10,[sp],16 // restaur des 2 registres - ldp x7,x8,[sp],16 // restaur des 2 registres - ldp x5,x6,[sp],16 // restaur des 2 registres - ldp x3,x4,[sp],16 // restaur des 2 registres - ldp x1,lr,[sp],16 // restaur des 2 registres - ret // retour adresse lr x30 -/***************************************************/ -/* division number 128 bits in 2 registers by number 64 bits */ -/* unsigned */ -/***************************************************/ -/* x0 contains lower part dividende */ -/* x1 contains upper part dividende */ -/* x2 contains divisor */ -/* x0 return lower part quotient */ -/* x1 return upper part quotient */ -/* x2 return remainder */ -division64R2023: - stp x3,lr,[sp,-16]! - stp x4,x5,[sp,-16]! - stp x6,x7,[sp,-16]! - mov x4,x2 // save divisor - mov x5,#0 // init upper part divisor - mov x2,x0 // save dividende - mov x3,x1 - mov x0,#0 // init result - mov x1,#0 - mov x6,#0 // init shift counter -1: // loop shift divisor - cmp x5,#0 // upper divisor <0 - blt 2f - cmp x5,x3 - bhi 2f - blo 11f - cmp x4,x2 - bhi 2f // new divisor > dividende -11: - lsl x5,x5,#1 // shift left one bit upper divisor - tst x4,#0x8000000000000000 - lsl x4,x4,#1 // shift left one bit lower divisor - orr x7,x5,#1 - csel x5,x7,x5,ne // move bit 63 lower on upper - add x6,x6,#1 // increment shift counter - b 1b - -2: // loop 2 - lsl x1,x1,#1 // shift left one bit upper quotient - tst x0,#0x8000000000000000 - lsl x0,x0,#1 // shift left one bit lower quotient - orr x7,x1,#1 - csel x1,x7,x1,ne // move bit 63 lower on upper - cmp x5,x3 // compare divisor and dividende - bhi 3f - blo 21f - cmp x4,x2 - bhi 3f -21: - subs x2,x2,x4 // < sub divisor from dividende lower - sbc x3,x3,x5 // and upper - orr x0,x0,#1 // move 1 on quotient -3: - lsr x4,x4,#1 // shift right one bit upper divisor - tst x5,1 - lsr x5,x5,#1 // and lower - orr x7,x4,#0x8000000000000000 // move bit 0 upper to 31 bit lower - csel x4,x7,x4,ne // move bit 0 upper to 63 bit lower - subs x6,x6,#1 // decrement shift counter - bge 2b // if > 0 loop 2 - -100: - ldp x6,x7,[sp],16 - ldp x4,x5,[sp],16 - ldp x3,lr,[sp],16 - ret - -/***************************************************/ -/* ROUTINES INCLUDE */ -/***************************************************/ -.include "../includeARM64.inc" diff --git a/Task/Miller-Rabin-primality-test/ALGOL-68/miller-rabin-primality-test.alg b/Task/Miller-Rabin-primality-test/ALGOL-68/miller-rabin-primality-test.alg deleted file mode 100644 index eaaf0b5c29..0000000000 --- a/Task/Miller-Rabin-primality-test/ALGOL-68/miller-rabin-primality-test.alg +++ /dev/null @@ -1,38 +0,0 @@ -MODE LINT=LONG INT; -MODE LOOPINT = INT; - -MODE POWMODSTRUCT = LINT; -PR READ "prelude/pow_mod.a68" PR; - -PROC miller rabin = (LINT n, LOOPINT k)BOOL: ( - IF n<=3 THEN TRUE - ELIF NOT ODD n THEN FALSE - ELSE - LINT d := n - 1; - INT s := 0; - WHILE NOT ODD d DO - d := d OVER 2; - s +:= 1 - OD; - TO k DO - LINT a := 2 + ENTIER (random*(n-3)); - LINT x := pow mod(a, d, n); - IF x /= 1 THEN - TO s DO - IF x = n-1 THEN done FI; - x := x*x %* n - OD; - else: IF x /= n-1 THEN return false FI; - done: EMPTY - FI - OD; - TRUE EXIT - return false: FALSE - FI -); - -FOR i FROM 937 TO 1000 DO - IF miller rabin(i, 10) THEN - print((" ",whole(i,0))) - FI -OD diff --git a/Task/Miller-Rabin-primality-test/ARM-Assembly/miller-rabin-primality-test.arm b/Task/Miller-Rabin-primality-test/ARM-Assembly/miller-rabin-primality-test.arm deleted file mode 100644 index f17bdf9a30..0000000000 --- a/Task/Miller-Rabin-primality-test/ARM-Assembly/miller-rabin-primality-test.arm +++ /dev/null @@ -1,286 +0,0 @@ -/* ARM assembly Raspberry PI */ -/* program testmiller.s */ - -/* for constantes see task include a file in arm assembly */ -/************************************/ -/* Constantes */ -/************************************/ -.include "../constantes.inc" - -.equ NBDIVISORS, 2000 - -//.include "../../ficmacros32.inc" @ use for developper debugging -/*******************************************/ -/* Initialized data */ -/*******************************************/ -.data -szMessStartPgm: .asciz "Program 32 bits start \n" -szMessEndPgm: .asciz "Program normal end.\n" -szMessErrorArea: .asciz "\033[31mError : area divisors too small.\n" -szMessPrime: .asciz " is prime !!!.\n" -szMessNotPrime: .asciz " is not prime !!!.\n" -szCarriageReturn: .asciz "\n" - -.align 4 -iGraine: .int 123456 -/*******************************************/ -/* UnInitialized data */ -/*******************************************/ -.bss -.align 4 -sZoneConv: .skip 24 -/*******************************************/ -/* code section */ -/*******************************************/ -.text -.global main -main: @ program start - ldr r0,iAdrszMessStartPgm @ display start message - bl affichageMess - ldr r4,iStart @ start number - ldr r5,iLimit @ end number - tst r4,#1 - addeq r4,#1 @ start with odd number -1: - mov r0,r4 - ldr r1,iAdrsZoneConv - bl conversion10 @ decimal conversion - ldr r0,iAdrsZoneConv - bl affichageMess - mov r0,r4 - bl isPrimeMiller @ test miller rabin - cmp r0,#0 - beq 2f - ldr r0,iAdrszMessPrime - bl affichageMess - b 3f -2: - ldr r0,iAdrszMessNotPrime - bl affichageMess -3: - add r4,r4,#2 - cmp r4,r5 - ble 1b - - ldr r0,iAdrszMessEndPgm @ display end message - bl affichageMess - -100: @ standard end of the program - mov r0, #0 @ return code - mov r7, #EXIT @ request to exit program - svc 0 @ perform system call -iAdrszMessStartPgm: .int szMessStartPgm -iAdrszMessEndPgm: .int szMessEndPgm -iAdrszCarriageReturn: .int szCarriageReturn -iAdrsZoneConv: .int sZoneConv -iAdrszMessPrime: .int szMessPrime -iAdrszMessNotPrime: .int szMessNotPrime -iStart: .int 4294967270 -iLimit: .int 4294967295 - - -/***************************************************/ -/* check if a number is prime test miller rabin */ -/***************************************************/ -/* r0 contains the number */ -/* r0 return 1 if prime 0 else */ -@2147483647 -@4294967297 -@131071 -isPrimeMiller: - push {r1-r6,lr} @ save registers - cmp r0,#1 @ control 0 or 1 - movls r0,#0 - bls 100f - cmp r0,#2 @ control = 2 - moveq r0,#1 - beq 100f - tst r0,#1 - moveq r0,#0 @ even - beq 100f - mov r1,#5 @ loop number - bl testMiller -100: - pop {r1-r6,pc} -/***************************************************/ -/* test miller rabin algorithme wikipedia */ -/* unsigned */ -/***************************************************/ -/* r0 contains number */ -/* r1 contains parameter */ -/* r0 return 1 if prime 0 if composite */ -testMiller: - push {r1-r9,lr} @ save registers - mov r4,r0 @ N - mov r7,r1 @ loop maxi - sub r3,r0,#1 @ D - mov r2,#2 - mov r6,#0 @ S -1: @ compute D * 2 power S - lsr r3,#1 @ D= D/2 - add r6,r6,#1 @ increment S - tst r3,#1 @ D even ? - beq 1b -2: - mov r8,#0 @ loop counter - sub r5,r0,#3 -3: - mov r0,r5 - bl genereraleas - add r0,r0,#2 @ alea (entre 2 et n-1) - mov r1,r3 @ exposant = D - mov r2,r4 @ modulo N - bl moduloPuR32 - cmp r0,#1 - beq 5f - sub r1,r4,#1 @ n -1 - cmp r0,r1 - beq 5f - sub r9,r6,#1 @ S - 1 -4: - mov r2,r0 - umull r0,r1,r2,r0 @ compute square - mov r2,r4 @ and compute modulo N - bl division32R2023 - mov r0,r2 - cmp r0,#1 - moveq r0,#0 @ composite - beq 100f - sub r1,r4,#1 @ n -1 - cmp r0,r1 - beq 5f - subs r9,r9,#1 - bge 4b - mov r0,#0 @ composite - b 100f -5: - add r8,r8,#1 - cmp r8,r7 - blt 3b - mov r0,#1 @ prime -100: - pop {r1-r9,pc} -/********************************************************/ -/* Calcul modulo de b puissance e modulo m */ -/* Exemple 4 puissance 13 modulo 497 = 445 */ -/* */ -/********************************************************/ -/* r0 nombre */ -/* r1 exposant */ -/* r2 modulo */ -/* r0 return result */ -moduloPuR32: - push {r1-r6,lr} @ save registers - cmp r0,#0 @ control <> zero - beq 100f - cmp r2,#0 @ control <> zero - beq 100f -1: - mov r4,r2 @ save modulo - mov r5,r1 @ save exposant - mov r6,r0 @ save base - mov r3,#1 @ start result - - mov r1,#0 @ division r0,r1 by r2 - bl division32R2023 - mov r6,r2 @ base <- remainder -2: - tst r5,#1 @ exposant even or odd - beq 3f - umull r0,r1,r6,r3 @ multiplication base - mov r2,r4 @ and compute modulo N - bl division32R2023 - mov r3,r2 @ result <- remainder -3: - umull r0,r1,r6,r6 @ compute base square - mov r2,r4 @ and compute modulo N - bl division32R2023 - mov r6,r2 @ base <- remainder - - lsr r5,#1 @ left shift 1 bit - cmp r5,#0 @ end ? - bne 2b - mov r0,r3 -100: - pop {r1-r6,pc} - -/***************************************************/ -/* division number 64 bits in 2 registers by number 32 bits */ -/* unsigned */ -/***************************************************/ -/* r0 contains lower part dividende */ -/* r1 contains upper part dividende */ -/* r2 contains divisor */ -/* r0 return lower part quotient */ -/* r1 return upper part quotient */ -/* r2 return remainder */ -division32R2023: - push {r3-r6,lr} @ save registers - mov r4,r2 @ save divisor - mov r5,#0 @ init upper part divisor - mov r2,r0 @ save dividende - mov r3,r1 - mov r0,#0 @ init result - mov r1,#0 - mov r6,#0 @ init shift counter -1: @ loop shift divisor - cmp r5,#0 @ upper divisor <0 - blt 2f - cmp r5,r3 - cmpeq r4,r2 - bhs 2f @ new divisor > dividende - lsl r5,#1 @ shift left one bit upper divisor - lsls r4,#1 @ shift left one bit lower divisor - orrcs r5,r5,#1 @ move bit 31 lower on upper - add r6,r6,#1 @ increment shift counter - b 1b -2: @ loop 2 - lsl r1,#1 @ shift left one bit upper quotient - lsls r0,#1 @ shift left one bit lower quotient - orrcs r1,#1 @ move bit 31 lower on upper - cmp r5,r3 @ compare divisor and dividende - cmpeq r4,r2 - bhi 3f - subs r2,r2,r4 @ < sub divisor from dividende lower - sbc r3,r3,r5 @ and upper - orr r0,r0,#1 @ move 1 on quotient -3: - lsr r4,r4,#1 @ shift right one bit upper divisor - lsrs r5,#1 @ and lower - orrcs r4,#0x80000000 @ move bit 0 upper to 31 bit lower - subs r6,#1 @ decrement shift counter - bge 2b @ if > 0 loop 2 - -100: - pop {r3-r6,pc} - - -/***************************************************/ -/* Generation random number */ -/***************************************************/ -/* r0 contains limit */ -genereraleas: - push {r1-r4,lr} @ save registers - ldr r4,iAdriGraine - ldr r2,[r4] - ldr r3,iNbDep1 - mul r2,r3,r2 - ldr r3,iNbDep1 - add r2,r2,r3 - str r2,[r4] @ save seed for next call - cmp r0,#0 - beq 100f - mov r1,r0 @ divisor - mov r0,r2 @ dividende - bl division - mov r0,r3 @ résult = remainder - -100: @ end function - pop {r1-r4,pc} @ restaur registers -iAdriGraine: .int iGraine -iNbDep1: .int 0x343FD -iNbDep2: .int 0x269EC3 -/***************************************************/ -/* ROUTINES INCLUDE */ -/***************************************************/ -.include "../affichage.inc" diff --git a/Task/Miller-Rabin-primality-test/Ada/miller-rabin-primality-test-1.ada b/Task/Miller-Rabin-primality-test/Ada/miller-rabin-primality-test-1.ada deleted file mode 100644 index 73f5a109f6..0000000000 --- a/Task/Miller-Rabin-primality-test/Ada/miller-rabin-primality-test-1.ada +++ /dev/null @@ -1,9 +0,0 @@ -generic - type Number is range <>; -package Miller_Rabin is - - type Result_Type is (Composite, Probably_Prime); - - function Is_Prime (N : Number; K : Positive := 10) return Result_Type; - -end Miller_Rabin; diff --git a/Task/Miller-Rabin-primality-test/Ada/miller-rabin-primality-test-2.ada b/Task/Miller-Rabin-primality-test/Ada/miller-rabin-primality-test-2.ada deleted file mode 100644 index d6c2202388..0000000000 --- a/Task/Miller-Rabin-primality-test/Ada/miller-rabin-primality-test-2.ada +++ /dev/null @@ -1,55 +0,0 @@ -with Ada.Numerics.Discrete_Random; - -package body Miller_Rabin is - - function Is_Prime (N : Number; K : Positive := 10) - return Result_Type - is - subtype Number_Range is Number range 2 .. N - 1; - package Random is new Ada.Numerics.Discrete_Random (Number_Range); - - function Mod_Exp (Base, Exponent, Modulus : Number) return Number is - Result : Number := 1; - begin - for E in 1 .. Exponent loop - Result := Result * Base mod Modulus; - end loop; - return Result; - end Mod_Exp; - - Generator : Random.Generator; - D : Number := N - 1; - S : Natural := 0; - X : Number; - begin - -- exclude 2 and even numbers - if N = 2 then - return Probably_Prime; - elsif N mod 2 = 0 then - return Composite; - end if; - - -- write N-1 as 2**S * D, with D mod 2 /= 0 - while D mod 2 = 0 loop - D := D / 2; - S := S + 1; - end loop; - - -- initialize RNG - Random.Reset (Generator); - for Loops in 1 .. K loop - X := Mod_Exp(Random.Random (Generator), D, N); - if X /= 1 and X /= N - 1 then - Inner : for R in 1 .. S - 1 loop - X := Mod_Exp (X, 2, N); - if X = 1 then return Composite; end if; - exit Inner when X = N - 1; - end loop Inner; - if X /= N - 1 then return Composite; end if; - end if; - end loop; - - return Probably_Prime; - end Is_Prime; - -end Miller_Rabin; diff --git a/Task/Miller-Rabin-primality-test/Ada/miller-rabin-primality-test-3.ada b/Task/Miller-Rabin-primality-test/Ada/miller-rabin-primality-test-3.ada deleted file mode 100644 index d78cd09fe5..0000000000 --- a/Task/Miller-Rabin-primality-test/Ada/miller-rabin-primality-test-3.ada +++ /dev/null @@ -1,25 +0,0 @@ -with Ada.Text_IO, Miller_Rabin; - -procedure Mr_Tst is - - type Number is range 0 .. (2**48)-1; - - package Num_IO is new Ada.Text_IO.Integer_IO (Number); - package Pos_IO is new Ada.Text_IO.Integer_IO (Positive); - package MR is new Miller_Rabin(Number); use MR; - - N : Number; - K : Positive; - -begin - for I in Number(2) .. 1000 loop - if Is_Prime (I) = Probably_Prime then - Ada.Text_IO.Put (Number'Image (I)); - end if; - end loop; - Ada.Text_IO.Put_Line ("."); - - Ada.Text_IO.Put ("Enter a Number: "); Num_IO.Get (N); - Ada.Text_IO.Put ("Enter the count of loops: "); Pos_IO.Get (K); - Ada.Text_IO.Put_Line ("What is it? " & Result_Type'Image (Is_Prime(N, K))); -end MR_Tst; diff --git a/Task/Miller-Rabin-primality-test/Ada/miller-rabin-primality-test-4.ada b/Task/Miller-Rabin-primality-test/Ada/miller-rabin-primality-test-4.ada deleted file mode 100644 index a56791fa7c..0000000000 --- a/Task/Miller-Rabin-primality-test/Ada/miller-rabin-primality-test-4.ada +++ /dev/null @@ -1,86 +0,0 @@ -with Ada.Text_IO, Crypto.Types.Big_Numbers, Ada.Numerics.Discrete_Random; - -procedure Miller_Rabin is - - Bound: constant Positive := 256; -- can be any multiple of 32 - - package LN is new Crypto.Types.Big_Numbers (Bound); - use type LN.Big_Unsigned; -- all computations "mod 2**Bound" - - function "+"(S: String) return LN.Big_Unsigned - renames LN.Utils.To_Big_Unsigned; - - function Is_Prime (N : LN.Big_Unsigned; K : Positive := 10) return Boolean is - - subtype Mod_32 is Crypto.Types.Mod_Type; - use type Mod_32; - package R_32 is new Ada.Numerics.Discrete_Random (Mod_32); - Generator : R_32.Generator; - - function Random return LN.Big_Unsigned is - X: LN.Big_Unsigned := LN.Big_Unsigned_Zero; - begin - for I in 1 .. Bound/32 loop - X := (X * 2**16) * 2**16; - X := X + R_32.Random(Generator); - end loop; - return X; - end Random; - - D: LN.Big_Unsigned := N - LN.Big_Unsigned_One; - S: Natural := 0; - A, X: LN.Big_Unsigned; - begin - -- exclude 2 and even numbers - if N = 2 then - return True; - elsif N mod 2 = LN.Big_Unsigned_Zero then - return False; - else - - -- write N-1 as 2**S * D, with odd D - while D mod 2 = LN.Big_Unsigned_Zero loop - D := D / 2; - S := S + 1; - end loop; - - -- initialize RNG - R_32.Reset (Generator); - - -- run the real test - for Loops in 1 .. K loop - loop - A := Random; - exit when (A > 1) and (A < (N - 1)); - end loop; - X := LN.Mod_Utils.Pow(A, D, N); -- X := (Random**D) mod N - if X /= 1 and X /= N - 1 then - Inner: - for R in 1 .. S - 1 loop - X := LN.Mod_Utils.Pow(X, LN.Big_Unsigned_Two, N); - if X = 1 then - return False; - end if; - exit Inner when X = N - 1; - end loop Inner; - if X /= N - 1 then - return False; - end if; - end if; - end loop; - end if; - - return True; - end Is_Prime; - - S: constant String := - "4547337172376300111955330758342147474062293202868155909489"; - T: constant String := - "4547337172376300111955330758342147474062293202868155909393"; - - K: constant Positive := 10; - -begin - Ada.Text_IO.Put_Line("Prime(" & S & ")=" & Boolean'Image(Is_Prime(+S, K))); - Ada.Text_IO.Put_Line("Prime(" & T & ")=" & Boolean'Image(Is_Prime(+T, K))); -end Miller_Rabin; diff --git a/Task/Miller-Rabin-primality-test/Ada/miller-rabin-primality-test-5.ada b/Task/Miller-Rabin-primality-test/Ada/miller-rabin-primality-test-5.ada deleted file mode 100644 index 956113580c..0000000000 --- a/Task/Miller-Rabin-primality-test/Ada/miller-rabin-primality-test-5.ada +++ /dev/null @@ -1,26 +0,0 @@ -with Ada.Text_IO, Crypto.Types.Big_Numbers, Ada.Numerics.Discrete_Random; - -procedure Miller_Rabin is - - Bound: constant Positive := 256; -- can be any multiple of 32 - - package LN is new Crypto.Types.Big_Numbers (Bound); - use type LN.Big_Unsigned; -- all computations "mod 2**Bound" - - function "+"(S: String) return LN.Big_Unsigned - renames LN.Utils.To_Big_Unsigned; - - S: constant String := - "4547337172376300111955330758342147474062293202868155909489"; - T: constant String := - "4547337172376300111955330758342147474062293202868155909393"; - - K: constant Positive := 10; - - -begin - Ada.Text_IO.Put_Line("Prime(" & S & ")=" - & Boolean'Image (LN.Mod_Utils.Passed_Miller_Rabin_Test(+S, K))); - Ada.Text_IO.Put_Line("Prime(" & T & ")=" - & Boolean'Image (LN.Mod_Utils.Passed_Miller_Rabin_Test(+T, K))); -end Miller_Rabin; diff --git a/Task/Miller-Rabin-primality-test/AutoHotkey/miller-rabin-primality-test.ahk b/Task/Miller-Rabin-primality-test/AutoHotkey/miller-rabin-primality-test.ahk deleted file mode 100644 index e7f86624ff..0000000000 --- a/Task/Miller-Rabin-primality-test/AutoHotkey/miller-rabin-primality-test.ahk +++ /dev/null @@ -1,41 +0,0 @@ -MsgBox % MillerRabin(999983,10) ; 1 -MsgBox % MillerRabin(999809,10) ; 1 -MsgBox % MillerRabin(999727,10) ; 1 -MsgBox % MillerRabin(52633,10) ; 0 -MsgBox % MillerRabin(60787,10) ; 0 -MsgBox % MillerRabin(999999,10) ; 0 -MsgBox % MillerRabin(999995,10) ; 0 -MsgBox % MillerRabin(999991,10) ; 0 - -MillerRabin(n,k) { ; 0: composite, 1: probable prime (n < 2**31) - d := n-1, s := 0 - While !(d&1) - d>>=1, s++ - - Loop %k% { - Random a, 2, n-2 ; if n < 4,759,123,141, it is enough to test a = 2, 7, and 61. - x := PowMod(a,d,n) - If (x=1 || x=n-1) - Continue - Cont := 0 - Loop % s-1 { - x := PowMod(x,2,n) - If (x = 1) - Return 0 - If (x = n-1) { - Cont = 1 - Break - } - } - IfEqual Cont,1, Continue - Return 0 - } - Return 1 -} - -PowMod(x,n,m) { ; x**n mod m - y := 1, i := n, z := x - While i>0 - y := i&1 ? mod(y*z,m) : y, z := mod(z*z,m), i >>= 1 - Return y -} diff --git a/Task/Miller-Rabin-primality-test/BQN/miller-rabin-primality-test-1.bqn b/Task/Miller-Rabin-primality-test/BQN/miller-rabin-primality-test-1.bqn deleted file mode 100644 index 41a8149fec..0000000000 --- a/Task/Miller-Rabin-primality-test/BQN/miller-rabin-primality-test-1.bqn +++ /dev/null @@ -1,20 +0,0 @@ -_modMul ← { n _𝕣: n|× } -MillerRabin ← { 𝕊n: 10𝕊n ; iter 𝕊 n: !2|n - # n = 1 + d×2⋆s - s ← 0 {𝕨 2⊸|◶⟨+⟜1𝕊2⌊∘÷˜⊢,⊣⟩ 𝕩} n-1 - d ← (n-1) ÷ 2⋆s - - # Arithmetic mod n - Mul ← n _modMul - Pow ← Mul{𝔽´𝔽˜⍟(/2|⌊∘÷⟜2⍟(↕1+·⌊2⋆⁼⊢)𝕩)𝕨} - - # Miller-Rabin test - MR ← { - 1 =𝕩 ? 𝕨≠s ; - (n-1)=𝕩 ? 0 ; - 𝕨≤1 ? 1 ; - (𝕨-1) 𝕊 Mul˜𝕩 - } - C ← { 𝕊a: s MR a Pow d } # Is composite - {0:1; C •rand.Range⌾(-⟜2) n ? 0; 𝕊𝕩-1} iter -} diff --git a/Task/Miller-Rabin-primality-test/BQN/miller-rabin-primality-test-2.bqn b/Task/Miller-Rabin-primality-test/BQN/miller-rabin-primality-test-2.bqn deleted file mode 100644 index 9911a88d6e..0000000000 --- a/Task/Miller-Rabin-primality-test/BQN/miller-rabin-primality-test-2.bqn +++ /dev/null @@ -1,10 +0,0 @@ -# Compute n|𝕨×𝕩 in high precision -_modMul ← { n _𝕣: - # Split each argument into two 26-bit numbers, with the remaining - # mantissa bit encoded in the sign of the lower-order part. - q←1+2⋆27 - Split ← { h←(q×𝕩)(⊣--)𝕩 ⋄ ⟨𝕩-h,h⟩ } - # The product, and an error relative to precise split multiplication. - Mul ← × (⊣ ⋈ -⊸(+´)) ·⥊×⌜○Split - ((n×<⟜0)⊸+ -⟜n+⊢)´ n | Mul -} diff --git a/Task/Miller-Rabin-primality-test/BQN/miller-rabin-primality-test-3.bqn b/Task/Miller-Rabin-primality-test/BQN/miller-rabin-primality-test-3.bqn deleted file mode 100644 index 7e5ba5afcf..0000000000 --- a/Task/Miller-Rabin-primality-test/BQN/miller-rabin-primality-test-3.bqn +++ /dev/null @@ -1,4 +0,0 @@ - MillerRabin 15485867 -1 - MillerRabin¨⊸/ 101+2×↕10 -⟨ 101 103 107 109 113 ⟩ diff --git a/Task/Miller-Rabin-primality-test/Bc/miller-rabin-primality-test.bc b/Task/Miller-Rabin-primality-test/Bc/miller-rabin-primality-test.bc deleted file mode 100644 index 9591df77e1..0000000000 --- a/Task/Miller-Rabin-primality-test/Bc/miller-rabin-primality-test.bc +++ /dev/null @@ -1,68 +0,0 @@ -seed = 1 /* seed of the random number generator */ -scale = 0 - -/* Random number from 0 to 32767. */ -define rand() { - /* Cheap formula (from POSIX) for random numbers of low quality. */ - seed = (seed * 1103515245 + 12345) % 4294967296 - return ((seed / 65536) % 32768) -} - -/* Random number in range [from, to]. */ -define rangerand(from, to) { - auto b, h, i, m, n, r - - m = to - from + 1 - h = length(m) / 2 + 1 /* want h iterations of rand() % 100 */ - b = 100 ^ h % m /* want n >= b */ - while (1) { - n = 0 /* pick n in range [b, 100 ^ h) */ - for (i = h; i > 0; i--) { - r = rand() - while (r < 68) { r = rand(); } /* loop if the modulo bias */ - n = (n * 100) + (r % 100) /* append 2 digits to n */ - } - if (n >= b) { break; } /* break unless the modulo bias */ - } - return (from + (n % m)) -} - - - -/* n is probably prime? */ -define miller_rabin_test(n, k) { - auto d, r, a, x, s - - if (n <= 3) { return (1); } - if ((n % 2) == 0) { return (0); } - - /* find s and d so that d * 2^s = n - 1 */ - d = n - 1 - s = 0 - while((d % 2) == 0) { - d /= 2 - s += 1 - } - - while (k-- > 0) { - a = rangerand(2, n - 2) - x = (a ^ d) % n - if (x != 1) { - for (r = 0; r < s; r++) { - if (x == (n - 1)) { break; } - x = (x * x) % n - } - if (x != (n - 1)) { - return (0) - } - } - } - return (1) -} - -for (i = 1; i < 1000; i++) { - if (miller_rabin_test(i, 10) == 1) { - i - } -} -quit diff --git a/Task/Miller-Rabin-primality-test/Bracmat/miller-rabin-primality-test.bracmat b/Task/Miller-Rabin-primality-test/Bracmat/miller-rabin-primality-test.bracmat deleted file mode 100644 index 9349b1ec24..0000000000 --- a/Task/Miller-Rabin-primality-test/Bracmat/miller-rabin-primality-test.bracmat +++ /dev/null @@ -1,70 +0,0 @@ -( 1:?seed -& ( rand - = - . mod$(!seed*1103515245+12345.4294967296):?seed - & mod$(div$(!seed.65536).32768) - ) -& ( rangerand - = from to b h i m n r length - . !arg:(?from,?to) - & !to+-1*!from+1:?m - & @(!m:? [?length) - & div$(!length+1.2)+1:?h - & 100^mod$(!h.!m):?b - & whl - ' ( 0:?n - & !h+1:?i - & whl - ' ( !i+-1:>0:?i - & rand$:?r - & whl'(!r:<68&rand$:?r) - & !n*100+mod$(!r.100):?n - ) - & !n:>!b - ) - & !from+mod$(!n.!m) - ) -& ( miller-rabin-test - = n k d r a x s return - . !arg:(?n,?k) - & ( !n:~>3&1 - | mod$(!n.2):0 - | !n+-1:?d - & 0:?s - & whl - ' ( mod$(!d.2):0 - & !d*1/2:?d - & 1+!s:?s - ) - & 1:?return - & whl - ' ( !k+-1:?k:~<0 - & rangerand$(2,!n+-2):?a - & mod$(!a^!d.!n):?x - & ( !x:1 - | 0:?r - & whl - ' ( !r+1:~>!s:?r - & !n+-1:~!x - & mod$(!x*!x.!n):?x - ) - & ( !n+-1:!x - | 0:?return&~ - ) - ) - ) - & !return - ) - ) -& 0:?i -& :?primes -& whl - ' ( 1+!i:<1000:?i - & ( miller-rabin-test$(!i,10):1 - & !primes !i:?primes - | - ) - ) -& !primes:? [-11 ?last -& out$!last -); diff --git a/Task/Miller-Rabin-primality-test/C++/miller-rabin-primality-test.cpp b/Task/Miller-Rabin-primality-test/C++/miller-rabin-primality-test.cpp deleted file mode 100644 index f4dab0632d..0000000000 --- a/Task/Miller-Rabin-primality-test/C++/miller-rabin-primality-test.cpp +++ /dev/null @@ -1,132 +0,0 @@ -#include -#include -#include -#include -#include - -std::vector small_primes{ 2, 3 }; - -uint64_t add_modulus(const uint64_t& a, const uint64_t& b, const uint64_t& modulus) { - uint64_t am = ( a < modulus ) ? a : a % modulus; - if ( b == 0 ) { - return am; - } - uint64_t bm = ( b < modulus ) ? b : b % modulus; - uint64_t b_from_m = modulus - bm; - if ( am >= b_from_m ) { - return am - b_from_m; - } - return am + bm; -} - -uint64_t multiply_modulus(const uint64_t& a, const uint64_t& b, const uint64_t& modulus) { - uint64_t am = ( a < modulus ) ? a : a % modulus; - uint64_t bm = ( b < modulus ) ? b : b % modulus; - if ( bm > am ) { - std::swap(am, bm); - } - uint64_t result; - while ( bm > 0 ) { - if ( ( bm & 1) == 1 ) { - result = add_modulus(result, am, modulus); - } - am = ( am << 1 ) - ( am >= ( modulus - am ) ? modulus : 0 ); - bm >>= 1; - } - return result; -} - -uint64_t exponentiation_modulus(const uint64_t& base, const uint64_t& exponent, const uint64_t& modulus) { - uint64_t b = base; - uint64_t e = exponent; - uint64_t result = 1; - while ( e > 0 ) { - if ( ( e & 1 ) == 1 ) { - result = multiply_modulus(result, b, modulus); - } - e >>= 1; - b = multiply_modulus(b, b, modulus); - } - return result; -} - -bool is_composite(const uint32_t& a, const uint64_t& d, const uint64_t& n, const uint32_t& s) { - if ( exponentiation_modulus(a, d, n) == 1 ) { - return false; - } - for ( uint64_t i = 0; i < s; ++i ) { - if ( exponentiation_modulus(a, pow(2, i) * d, n) == n - 1 ) { - return false; - } - } - return true; -} - -bool composite_test(const std::vector& primes, const uint64_t& d, const uint64_t& n, const uint32_t& s) { - for ( const uint32_t& prime : primes ) { - if ( is_composite(prime, d, n, s) ) { - return true; - } - } - return false; -} - -bool is_prime(const uint64_t& n) { - if ( n == 0 || n == 1 ) { - return false; - } - if ( std::find(small_primes.begin(), small_primes.end(), n) != small_primes.end() ) { - return true; - } - if ( std::any_of(small_primes.begin(), small_primes.end(), [n](uint32_t p) { return n % p == 0; }) ) { - return false; - } - - uint64_t d = n - 1; - uint32_t s = 0; - while ( ! d % 2 ) { - d >>= 1; - s++; - } - - if ( n < 1'373'653 ) { - return composite_test({ 2, 3 }, d, n, s); - } - if ( n < 25'326'001 ) { - return composite_test({ 2, 3, 5 }, d, n, s); - } - if ( n < 118'670'087'467 ) { - if ( n == 3'215'031'751 ) { - return false; - } - return composite_test({ 2, 3, 5, 7 }, d, n, s); - } - if ( n < 2'152'302'898'747 ) { - return composite_test({ 2, 3, 5, 7, 11 }, d, n, s); - } - if ( n < 3'474'749'660'383 ) { - return composite_test({ 2, 3, 5, 7, 11, 13 }, d, n, s); - } - if ( n < 341'550'071'728'321 ) { - return composite_test({ 2, 3, 5, 7, 11, 13, 17 }, d, n, s); - } - - const std::vector test_primes(small_primes.begin(), small_primes.begin() + 16); - return composite_test(test_primes, d, n, s); -} - -void create_small_primes() { - for ( uint32_t i = 5; i < 1'000; i += 2 ) { - if ( is_prime(i) ) { - small_primes.emplace_back(i); - } - } -} - -int main() { - create_small_primes(); - - for ( const uint64_t number : { 1'234'567'890'123'456'733, 1'234'567'890'123'456'737 } ) { - std::cout << "is_prime(" << number << ") = " << std::boolalpha << is_prime(number) << std::endl; - } -} diff --git a/Task/Miller-Rabin-primality-test/C-sharp/miller-rabin-primality-test-1.cs b/Task/Miller-Rabin-primality-test/C-sharp/miller-rabin-primality-test-1.cs deleted file mode 100644 index b634166205..0000000000 --- a/Task/Miller-Rabin-primality-test/C-sharp/miller-rabin-primality-test-1.cs +++ /dev/null @@ -1,27 +0,0 @@ -public static class RabinMiller -{ - public static bool IsPrime(int n, int k) - { - if ((n < 2) || (n % 2 == 0)) return (n == 2); - - int s = n - 1; - while (s % 2 == 0) s >>= 1; - - Random r = new Random(); - for (int i = 0; i < k; i++) - { - int a = r.Next(n - 1) + 1; - int temp = s; - long mod = 1; - for (int j = 0; j < temp; ++j) mod = (mod * a) % n; - while (temp != n - 1 && mod != 1 && mod != n - 1) - { - mod = (mod * mod) % n; - temp *= 2; - } - - if (mod != n - 1 && temp % 2 == 0) return false; - } - return true; - } -} diff --git a/Task/Miller-Rabin-primality-test/C-sharp/miller-rabin-primality-test-2.cs b/Task/Miller-Rabin-primality-test/C-sharp/miller-rabin-primality-test-2.cs deleted file mode 100644 index 82b9d22a48..0000000000 --- a/Task/Miller-Rabin-primality-test/C-sharp/miller-rabin-primality-test-2.cs +++ /dev/null @@ -1,58 +0,0 @@ -// Miller-Rabin primality test as an extension method on the BigInteger type. -// Based on the Ruby implementation on this page. -public static class BigIntegerExtensions -{ - public static bool IsProbablePrime(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; - } - - // There is no built-in method for generating random BigInteger values. - // Instead, random BigIntegers are constructed from randomly generated - // byte arrays of the same length as the source. - RandomNumberGenerator rng = RandomNumberGenerator.Create(); - byte[] bytes = new byte[source.ToByteArray().LongLength]; - BigInteger a; - - for(int i = 0; i < certainty; i++) - { - do - { - // This may raise an exception in Mono 2.10.8 and earlier. - // http://bugzilla.xamarin.com/show_bug.cgi?id=2761 - rng.GetBytes(bytes); - a = new BigInteger(bytes); - } - while(a < 2 || a >= 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; - } -} diff --git a/Task/Miller-Rabin-primality-test/C/miller-rabin-primality-test-1.c b/Task/Miller-Rabin-primality-test/C/miller-rabin-primality-test-1.c deleted file mode 100644 index 195d3b55fa..0000000000 --- a/Task/Miller-Rabin-primality-test/C/miller-rabin-primality-test-1.c +++ /dev/null @@ -1,5 +0,0 @@ -#ifndef _MILLER_RABIN_H_ -#define _MILLER_RABIN_H -#include -bool miller_rabin_test(mpz_t n, int j); -#endif diff --git a/Task/Miller-Rabin-primality-test/C/miller-rabin-primality-test-2.c b/Task/Miller-Rabin-primality-test/C/miller-rabin-primality-test-2.c deleted file mode 100644 index 0af4029ed1..0000000000 --- a/Task/Miller-Rabin-primality-test/C/miller-rabin-primality-test-2.c +++ /dev/null @@ -1,63 +0,0 @@ -#include -#include -#include "primedecompose.h" - -#define MAX_DECOMPOSE 100 - -bool miller_rabin_test(mpz_t n, int j) -{ - bool res; - mpz_t f[MAX_DECOMPOSE]; - mpz_t s, d, a, x, r; - mpz_t n_1, n_3; - gmp_randstate_t rs; - int l=0, k; - - res = false; - gmp_randinit_default(rs); - - mpz_init(s); mpz_init(d); - mpz_init(a); mpz_init(x); mpz_init(r); - mpz_init(n_1); mpz_init(n_3); - - if ( mpz_cmp_si(n, 3) <= 0 ) { // let us consider 1, 2, 3 as prime - gmp_randclear(rs); - return true; - } - if ( mpz_odd_p(n) != 0 ) { - mpz_sub_ui(n_1, n, 1); // n-1 - mpz_sub_ui(n_3, n, 3); // n-3 - l = decompose(n_1, f); - mpz_set_ui(s, 0); - mpz_set_ui(d, 1); - for(k=0; k < l; k++) { - if ( mpz_cmp_ui(f[k], 2) == 0 ) - mpz_add_ui(s, s, 1); - else - mpz_mul(d, d, f[k]); - } // 2^s * d = n-1 - while(j-- > 0) { - mpz_urandomm(a, rs, n_3); // random from 0 to n-4 - mpz_add_ui(a, a, 2); // random from 2 to n-2 - mpz_powm(x, a, d, n); - if ( mpz_cmp_ui(x, 1) == 0 ) continue; - mpz_set_ui(r, 0); - while( mpz_cmp(r, s) < 0 ) { - if ( mpz_cmp(x, n_1) == 0 ) break; - mpz_powm_ui(x, x, 2, n); - mpz_add_ui(r, r, 1); - } - if ( mpz_cmp(x, n_1) == 0 ) continue; - goto flush; // woops - } - res = true; - } - -flush: - for(k=0; k < l; k++) mpz_clear(f[k]); - mpz_clear(s); mpz_clear(d); - mpz_clear(a); mpz_clear(x); mpz_clear(r); - mpz_clear(n_1); mpz_clear(n_3); - gmp_randclear(rs); - return res; -} diff --git a/Task/Miller-Rabin-primality-test/C/miller-rabin-primality-test-3.c b/Task/Miller-Rabin-primality-test/C/miller-rabin-primality-test-3.c deleted file mode 100644 index f7ca656616..0000000000 --- a/Task/Miller-Rabin-primality-test/C/miller-rabin-primality-test-3.c +++ /dev/null @@ -1,29 +0,0 @@ -#include -#include -#include -#include -#include "miller-rabin.h" - -#define PREC 10 -#define TOP 4000 - -int main() -{ - mpz_t num; - - mpz_init(num); - mpz_set_ui(num, 1); - - while ( mpz_cmp_ui(num, TOP) < 0 ) { - if ( miller_rabin_test(num, PREC) ) { - gmp_printf("%Zd maybe prime\n", num); - } /*else { - gmp_printf("%Zd not prime\n", num); - }*/ // remove the comment iff you're interested in - // sure non-prime. - mpz_add_ui(num, num, 1); - } - - mpz_clear(num); - return EXIT_SUCCESS; -} diff --git a/Task/Miller-Rabin-primality-test/C/miller-rabin-primality-test-4.c b/Task/Miller-Rabin-primality-test/C/miller-rabin-primality-test-4.c deleted file mode 100644 index e63a2a6ef9..0000000000 --- a/Task/Miller-Rabin-primality-test/C/miller-rabin-primality-test-4.c +++ /dev/null @@ -1,72 +0,0 @@ -// calcul a^n%mod -size_t power(size_t a, size_t n, size_t mod) -{ - size_t power = a; - size_t result = 1; - - while (n) - { - if (n & 1) - result = (result * power) % mod; - power = (power * power) % mod; - n >>= 1; - } - return result; -} - -// n−1 = 2^s * d with d odd by factoring powers of 2 from n−1 -bool witness(size_t n, size_t s, size_t d, size_t a) -{ - size_t x = power(a, d, n); - size_t y; - - while (s) { - y = (x * x) % n; - if (y == 1 && x != 1 && x != n-1) - return false; - x = y; - --s; - } - if (y != 1) - return false; - return true; -} - -/* - * if n < 1,373,653, it is enough to test a = 2 and 3; - * if n < 9,080,191, it is enough to test a = 31 and 73; - * if n < 4,759,123,141, it is enough to test a = 2, 7, and 61; - * if n < 1,122,004,669,633, it is enough to test a = 2, 13, 23, and 1662803; - * if n < 2,152,302,898,747, it is enough to test a = 2, 3, 5, 7, and 11; - * if n < 3,474,749,660,383, it is enough to test a = 2, 3, 5, 7, 11, and 13; - * if n < 341,550,071,728,321, it is enough to test a = 2, 3, 5, 7, 11, 13, and 17. - */ - -bool is_prime_mr(size_t n) -{ - if (((!(n & 1)) && n != 2 ) || (n < 2) || (n % 3 == 0 && n != 3)) - return false; - if (n <= 3) - return true; - - size_t d = n / 2; - size_t s = 1; - while (!(d & 1)) { - d /= 2; - ++s; - } - - if (n < 1373653) - return witness(n, s, d, 2) && witness(n, s, d, 3); - if (n < 9080191) - return witness(n, s, d, 31) && witness(n, s, d, 73); - if (n < 4759123141) - return witness(n, s, d, 2) && witness(n, s, d, 7) && witness(n, s, d, 61); - if (n < 1122004669633) - return witness(n, s, d, 2) && witness(n, s, d, 13) && witness(n, s, d, 23) && witness(n, s, d, 1662803); - if (n < 2152302898747) - return witness(n, s, d, 2) && witness(n, s, d, 3) && witness(n, s, d, 5) && witness(n, s, d, 7) && witness(n, s, d, 11); - if (n < 3474749660383) - return witness(n, s, d, 2) && witness(n, s, d, 3) && witness(n, s, d, 5) && witness(n, s, d, 7) && witness(n, s, d, 11) && witness(n, s, d, 13); - return witness(n, s, d, 2) && witness(n, s, d, 3) && witness(n, s, d, 5) && witness(n, s, d, 7) && witness(n, s, d, 11) && witness(n, s, d, 13) && witness(n, s, d, 17); -} diff --git a/Task/Miller-Rabin-primality-test/C/miller-rabin-primality-test-5.c b/Task/Miller-Rabin-primality-test/C/miller-rabin-primality-test-5.c deleted file mode 100644 index 816f022b41..0000000000 --- a/Task/Miller-Rabin-primality-test/C/miller-rabin-primality-test-5.c +++ /dev/null @@ -1,37 +0,0 @@ -typedef unsigned long long int ulong; - -ulong mul_mod(ulong a, ulong b, const ulong mod) { - ulong res = 0, c; // return (a * b) % mod, avoiding overflow errors while doing modular multiplication. - for (b %= mod; a; a & 1 ? b >= mod - res ? res -= mod : 0, res += b : 0, a >>= 1, (c = b) >= mod - b ? c -= mod : 0, b += c); - return res % mod; -} - -ulong pow_mod(ulong n, ulong exp, const ulong mod) { - ulong res = 1; // return (n ^ exp) % mod - for (n %= mod; exp; exp & 1 ? res = mul_mod(res, n, mod) : 0, n = mul_mod(n, n, mod), exp >>= 1); - return res; -} - -int is_prime(ulong N) { - // Perform a Miller-Rabin test, it should be a deterministic version. - const ulong n_primes = 9, primes[] = {2, 3, 5, 7, 11, 13, 17, 19, 23}; - for (ulong i = 0; i < n_primes; ++i) - if (N % primes[i] == 0) return N == primes[i]; - if (N < primes[n_primes - 1]) return 0; - int res = 1, s = 0; - ulong t; - for (t = N - 1; ~t & 1; t >>= 1, ++s); - for (ulong i = 0; i < n_primes && res; ++i) { - ulong B = pow_mod(primes[i], t, N); - if (B != 1) { - for (int b = s; b-- && (res = B + 1 != N);) - B = mul_mod(B, B, N); - res = !res; - } - } - return res; -} - -int main(void){ - return is_prime(8193145868754512737); -} diff --git a/Task/Miller-Rabin-primality-test/Clojure/miller-rabin-primality-test-1.clj b/Task/Miller-Rabin-primality-test/Clojure/miller-rabin-primality-test-1.clj deleted file mode 100644 index 04b67f59c7..0000000000 --- a/Task/Miller-Rabin-primality-test/Clojure/miller-rabin-primality-test-1.clj +++ /dev/null @@ -1,74 +0,0 @@ -(ns test-p.core - (:require [clojure.math.numeric-tower :as math]) - (:require [clojure.set :as set])) - -(def WITNESSLOOP "witness") -(def COMPOSITE "composite") - -(defn m* [p q m] - " Computes (p*q) mod m " - (mod (*' p q) m)) - -(defn power - "modular exponentiation (i.e. b^e mod m" - [b e m] - (loop [b b, e e, x 1] - (if (zero? e) - x - (if (even? e) (recur (m* b b m) (quot e 2) x) - (recur (m* b b m) (quot e 2) (m* b x m)))))) - -; Sequence of random numbers to use in the test -(defn rand-num [n] - " random number between 2 and n-2 " - (bigint (math/floor (+' 2 (*' (- n 4) (rand)))))) - -; Unique set of random numbers -(defn unique-random-numbers [n k] - " k unique random numbers between 2 and n-2 " - (loop [a-set #{}] - (cond - (>= (count a-set) k) a-set - :else (recur (conj a-set (rand-num n)))))) - -(defn find-d-s [n] - " write n − 1 as 2s·d with d odd " - (loop [d (dec n), s 0] - (if (odd? d) - [d s] - (recur (quot d 2) (inc s))))) - -(defn random-test - ([n] (random-test n (min 1000 (bigint (/ n 2))))) - ([n k] - " Random version of primality test" - (let [[d s] (find-d-s n) - ; Individual Primality Test - single-test (fn [a s] - (let [z (power a d n)] - (if (some #{z} [1 (dec n)]) - WITNESSLOOP - (loop [x (power z 2 n), r s] - (cond - (= x 1) COMPOSITE - (= x (dec n)) WITNESSLOOP - (= r 0) COMPOSITE - :else (recur (power x 2 n) (dec r)))))))] - ; Apply Test - ;(not-any? #(= COMPOSITE (local-test % s)) - ; (unique-random-numbers n k)))) - (not-any? #(= COMPOSITE (single-test % s)) (unique-random-numbers n k))))) - -;; Testing -(println "Primes beteen 900-1000:") -(doseq [q (range 900 1000) - :when (random-test q)] - (print " " q)) -(println) -(println "Is Prime?" 4547337172376300111955330758342147474062293202868155909489 (random-test 4547337172376300111955330758342147474062293202868155909489)) -(println "Is Prime?" 4547337172376300111955330758342147474062293202868155909393 (random-test 4547337172376300111955330758342147474062293202868155909393)) -(println "Is Prime?" 643808006803554439230129854961492699151386107534013432918073439524138264842370630061369715394739134090922937332590384720397133335969549256322620979036686633213903952966175107096769180017646161851573147596390153 - (random-test 643808006803554439230129854961492699151386107534013432918073439524138264842370630061369715394739134090922937332590384720397133335969549256322620979036686633213903952966175107096769180017646161851573147596390153)) - -(println "Is Prime?" 743808006803554439230129854961492699151386107534013432918073439524138264842370630061369715394739134090922937332590384720397133335969549256322620979036686633213903952966175107096769180017646161851573147596390153 - (random-test 743808006803554439230129854961492699151386107534013432918073439524138264842370630061369715394739134090922937332590384720397133335969549256322620979036686633213903952966175107096769180017646161851573147596390153)) diff --git a/Task/Miller-Rabin-primality-test/Clojure/miller-rabin-primality-test-2.clj b/Task/Miller-Rabin-primality-test/Clojure/miller-rabin-primality-test-2.clj deleted file mode 100644 index c3ccdebbcf..0000000000 --- a/Task/Miller-Rabin-primality-test/Clojure/miller-rabin-primality-test-2.clj +++ /dev/null @@ -1,82 +0,0 @@ -(ns test-p.core - (:require [clojure.math.numeric-tower :as math])) - -(def WITNESSLOOP "witness") -(def COMPOSITE "composite") - -(defn m* [p q m] - " Computes (p*q) mod m " - (mod (*' p q) m)) - -(defn power - "modular exponentiation (i.e. b^e mod m" - [b e m] - (loop [b b, e e, x 1] - (if (zero? e) - x - (if (even? e) (recur (m* b b m) (quot e 2) x) - (recur (m* b b m) (quot e 2) (m* b x m)))))) - -(defn find-d-s [n] -" write n − 1 as 2s·d with d odd " -(loop [d (dec n), s 0] - (if (odd? d) - [d s] - (recur (quot d 2) (inc s))))) - -;; Deterministic Test -(defn individual-deterministic-test [a d n s] - " Deterministic Primality Test " - (let [z (power a d n)] - (if (= z 1) - WITNESSLOOP - (loop [x z, r s] - (cond - (= x (dec n)) WITNESSLOOP - (zero? r) COMPOSITE - :else (recur (power x 2 n) (dec r))))))) - -(defn deterministic-test [n] - " Sequence of Primality Tests " - (cond - (some #{n} [0 1 4]) false - (some #{n} [2 3]) true - (even? n) false - :else (let [[d s] (find-d-s n)] - (cond - (< n 2047) (not-any? #(= COMPOSITE (individual-deterministic-test % d n s)) [2 ]) - (< n 1373653) (not-any? #(= COMPOSITE (individual-deterministic-test % d n s)) [2 3]) - (< n 9090191) (not-any? #(= COMPOSITE (individual-deterministic-test % d n s)) [31 73]) - (< n 25326001) (not-any? #(= COMPOSITE (individual-deterministic-test % d n s)) [2 3 5]) - (< n 3215031751) (not-any? #(= COMPOSITE (individual-deterministic-test % d n s)) [2 3 5 7]) - (< n 1122004669633) (not-any? #(= COMPOSITE (individual-deterministic-test % d n s)) [2 13 23 1662803]) - (< n 2152302898747) (not-any? #(= COMPOSITE (individual-deterministic-test % d n s)) [2 3 5 7 11]) - (< n 2152302898747) (not-any? #(= COMPOSITE (individual-deterministic-test % d n s)) [2 3 5 7 11]) - (< n 3474749660383) (not-any? #(= COMPOSITE (individual-deterministic-test % d n s)) [2 3 5 7 11 13]) - (< n 341550071728321) (not-any? #(= COMPOSITE (individual-deterministic-test % d n s)) [2 3 5 7 11 13 17]) - (< n 3825123056546,413,051) (not-any? #(= COMPOSITE (individual-deterministic-test % d n s)) [2 3 5 7 11 13 17 19 23]) - (< n (math/expt 2 64) ) (not-any? #(= COMPOSITE (individual-deterministic-test % d n s)) [2 3 5 7 11 13 17 19 23 29 31 37]) - (< n 318665857834031151167461) (not-any? #(= COMPOSITE (individual-deterministic-test % d n s)) [2 3 5 7 11 13 17 19 23 29 31 37]) - (< n 3317044064679887385961981) (not-any? #(= COMPOSITE (individual-deterministic-test % d n s)) [2 3 5 7 11 13 17 19 23 29 31 37 41]) - :else (let [k (min (dec n) (int (math/expt (Math/log n) 2)))] - (not-any? #(= COMPOSITE (individual-deterministic-test % d n s)) (range 2 (inc k)))))))) - - -;; Testing -(println "Primes beteen 900-1000:") -(doseq [q (range 900 1000) - :when (deterministic-test q)] - (print " " q)) -(println) -(println "Is Prime?" 4547337172376300111955330758342147474062293202868155909489 (deterministic-test 4547337172376300111955330758342147474062293202868155909489)) -(println "Is Prime?" 4547337172376300111955330758342147474062293202868155909393 (deterministic-test 4547337172376300111955330758342147474062293202868155909393)) -println "Is Prime?" 643808006803554439230129854961492699151386107534013432918073439524138264842370630061369715394739134090922937332590384720397133335969549256322620979036686633213903952966175107096769180017646161851573147596390153 - (deterministic-test 643808006803554439230129854961492699151386107534013432918073439524138264842370630061369715394739134090922937332590384720397133335969549256322620979036686633213903952966175107096769180017646161851573147596390153)) - -(println "Is Prime?" 743808006803554439230129854961492699151386107534013432918073439524138264842370630061369715394739134090922937332590384720397133335969549256322620979036686633213903952966175107096769180017646161851573147596390153 - (deterministic-test 743808006803554439230129854961492699151386107534013432918073439524138264842370630061369715394739134090922937332590384720397133335969549256322620979036686633213903952966175107096769180017646161851573147596390153)) -(println "Is Prime?" 643808006803554439230129854961492699151386107534013432918073439524138264842370630061369715394739134090922937332590384720397133335969549256322620979036686633213903952966175107096769180017646161851573147596390153 - (deterministic-test 643808006803554439230129854961492699151386107534013432918073439524138264842370630061369715394739134090922937332590384720397133335969549256322620979036686633213903952966175107096769180017646161851573147596390153)) - -(println "Is Prime?" 743808006803554439230129854961492699151386107534013432918073439524138264842370630061369715394739134090922937332590384720397133335969549256322620979036686633213903952966175107096769180017646161851573147596390153 - (deterministic-test 743808006803554439230129854961492699151386107534013432918073439524138264842370630061369715394739134090922937332590384720397133335969549256322620979036686633213903952966175107096769180017646161851573147596390153)) diff --git a/Task/Miller-Rabin-primality-test/Commodore-BASIC/miller-rabin-primality-test.basic b/Task/Miller-Rabin-primality-test/Commodore-BASIC/miller-rabin-primality-test.basic deleted file mode 100644 index 7b33aa5a36..0000000000 --- a/Task/Miller-Rabin-primality-test/Commodore-BASIC/miller-rabin-primality-test.basic +++ /dev/null @@ -1,30 +0,0 @@ -100 PRINT CHR$(147); CHR$(18); "**** MILLER-RABIN PRIMALITY TEST ****": PRINT -110 INPUT "NUMBER TO TEST"; N$ -120 N = VAL(N$): IF N < 2 THEN 110 -130 IF 0 = (N AND 1) THEN PRINT "(EVEN)": GOTO 380 -140 INPUT "ITERATIONS"; K$ -150 K = VAL(K$): IF K < 1 THEN 140 -160 PRINT -170 DEF FNMD(M) = M - N * INT(M / N) -180 D = N - 1 -190 S = 0 -200 D = D / 2: S = S + 1 -210 IF 0 = (D AND 1) THEN 200 -220 P = 1 -230 FOR I = 1 TO K -240 : A = INT(RND(.) * (N - 2)) + 2 -250 : X = 1 -260 : FOR J = 1 TO D -270 : X = FNMD(X * A) -280 : NEXT J -290 : IF (X = 1) OR (X = (N - 1)) THEN 360 -300 : FOR J = 1 TO S - 1 -310 : X = FNMD(X * X) -320 : IF X = 1 THEN P = 0: GOTO 370 -330 : IF X = N - 1 THEN 360 -340 : NEXT J -350 : P = 0: GOTO 370 -360 NEXT I -370 P = P * (1 - 1 / (4 * K)) -380 IF P THEN PRINT "PROBABLY PRIME ( P >="; P; ")": END -390 PRINT "COMPOSITE." diff --git a/Task/Miller-Rabin-primality-test/Common-Lisp/miller-rabin-primality-test.lisp b/Task/Miller-Rabin-primality-test/Common-Lisp/miller-rabin-primality-test.lisp deleted file mode 100644 index 9cb6744a70..0000000000 --- a/Task/Miller-Rabin-primality-test/Common-Lisp/miller-rabin-primality-test.lisp +++ /dev/null @@ -1,43 +0,0 @@ -(defun factor-out (number divisor) - "Return two values R and E such that NUMBER = DIVISOR^E * R, - and R is not divisible by DIVISOR." - (do ((e 0 (1+ e)) - (r number (/ r divisor))) - ((/= (mod r divisor) 0) (values r e)))) - -(defun mult-mod (x y modulus) (mod (* x y) modulus)) - -(defun expt-mod (base exponent modulus) - "Fast modular exponentiation by repeated squaring." - (labels ((expt-mod-iter (b e p) - (cond ((= e 0) p) - ((evenp e) - (expt-mod-iter (mult-mod b b modulus) - (/ e 2) - p)) - (t - (expt-mod-iter b - (1- e) - (mult-mod b p modulus)))))) - (expt-mod-iter base exponent 1))) - -(defun random-in-range (lower upper) - "Return a random integer from the range [lower..upper]." - (+ lower (random (+ (- upper lower) 1)))) - -(defun miller-rabin-test (n k) - "Test N for primality by performing the Miller-Rabin test K times. - Return NIL if N is composite, and T if N is probably prime." - (cond ((= n 1) nil) - ((< n 4) t) - ((evenp n) nil) - (t - (multiple-value-bind (d s) (factor-out (- n 1) 2) - (labels ((strong-liar? (a) - (let ((x (expt-mod a d n))) - (or (= x 1) - (loop repeat s - for y = x then (mult-mod y y n) - thereis (= y (- n 1))))))) - (loop repeat k - always (strong-liar? (random-in-range 2 (- n 2))))))))) diff --git a/Task/Miller-Rabin-primality-test/Crystal/miller-rabin-primality-test-1.crystal b/Task/Miller-Rabin-primality-test/Crystal/miller-rabin-primality-test-1.crystal deleted file mode 100644 index d7d5fc0877..0000000000 --- a/Task/Miller-Rabin-primality-test/Crystal/miller-rabin-primality-test-1.crystal +++ /dev/null @@ -1,40 +0,0 @@ -require "big" - -module Primes - module MillerRabin - - def prime?(k = 15) # increase k for more confidence - neg_one_mod = d = self - 1 - s = 0 - while d.even?; d >>= 1; s += 1 end # d is odd after s shifts - k.times do - b = 2 + rand(self - 4) # random witness base b - y = powmod(b, d, self) # y = (b**d) mod self - next if y == 1 || y == neg_one_mod - (s - 1).times do - y = (y * y) % self # y = (y**2) mod self - return false if y == 1 - break if y == neg_one_mod - end - return false if y != neg_one_mod - end - true # prime (with high probability) - end - - # Compute b**e mod m - private def powmod(b, e, m) - r, b = 1, b.to_big_i - while e > 0 - r = (b * r) % m if e.odd? - b = (b * b) % m - e >>= 1 - end - r - end - end -end - -struct Int; include Primes::MillerRabin end - -puts 341521.prime?(20) # => true -puts 341531.prime? # => false diff --git a/Task/Miller-Rabin-primality-test/Crystal/miller-rabin-primality-test-2.crystal b/Task/Miller-Rabin-primality-test/Crystal/miller-rabin-primality-test-2.crystal deleted file mode 100644 index 0a1ad07bf0..0000000000 --- a/Task/Miller-Rabin-primality-test/Crystal/miller-rabin-primality-test-2.crystal +++ /dev/null @@ -1,144 +0,0 @@ -# For crystal >= 0.31.x, compile without overflow check, as either -# crystal build miller-rabin.cr -Ddisable_overflow --release -# crystal build -Ddisable_overflow miller-rabin.cr --release - -require "big" - -module Primes - module MillerRabin - - # Returns true if +self+ is a prime number, else returns false. - def primemr?(k = 10) - primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47} - return primes.includes? self if self <= primes.last - modp47 = 614_889_782_588_491_410.to_big_i # => primes.product, largest < 2^64 - return false if modp47.gcd(self.to_big_i) != 1 # eliminates 86.2% of all integers - # Choose input witness bases: wits = [range, [wit_bases]] or nil - wits = WITNESS_RANGES.find { |range, wits| range > self } - witnesses = wits && wits[1] || k.times.map{ 2 + rand(self - 4) } - miller_rabin_test(witnesses) - end - - # Returns true if +self+ passes Miller-Rabin Test on witnesses +b+ - private def miller_rabin_test(witnesses) # list of witnesses for testing - neg_one_mod = n = d = self - 1 # these are even as self is always odd - d >>= d.trailing_zeros_count # shift out factors of 2 to make d odd - witnesses.each do |b| # do M-R test with each witness base - next if (b % self) == 0 # **skip base if a multiple of input** - y = powmod(b, d, self) # y = (b**d) mod self - s = d - until y == 1 || y == neg_one_mod || s == n - y = (y * y) % self # y = (y**2) mod self - s <<= 1 - end - return false unless y == neg_one_mod || s.odd? - end - true - end - - # Best known deterministic witnesses for given range and set of bases - # https://miller-rabin.appspot.com/ - # https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test - private WITNESS_RANGES = { - 341_531 => {9345883071009581737}, - 1_050_535_501 => {336781006125, 9639812373923155}, - 350_269_456_337 => {4230279247111683200, 14694767155120705706, 16641139526367750375}, - 55_245_642_489_451 => {2, 141889084524735, 1199124725622454117, 11096072698276303650}, - 7_999_252_175_582_851 => {2, 4130806001517, 149795463772692060, 186635894390467037, - 3967304179347715805}, - 585_226_005_592_931_977 => {2, 123635709730000, 9233062284813009, 43835965440333360, - 761179012939631437, 1263739024124850375}, - 18_446_744_073_709_551_615 => {2, 325, 9375, 28178, 450775, 9780504, 1795265022}, - "318665857834031151167461".to_big_i => {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37}, - "3317044064679887385961981".to_big_i => {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41} - } - - # Compute b**e mod m - private def powmod(b, e, m) - r, b = 1, b.to_big_i - while e > 0 - r = (b * r) % m if e.odd? - b = (b * b) % m - e >>= 1 - end - r - end - end -end - -struct Int; include Primes::MillerRabin end - -def tm; t = Time.monotonic; yield; (Time.monotonic - t).total_seconds.round(6) end - -# 10 digit prime -n = 2147483647 -print "\n number = #{n} is prime? "; print " in ", tm{ print n.primemr? }, " secs" -puts - -# 18 digit non-prime -n = 844674407370955389 -print "\n number = #{n} is prime? "; print " in ", tm{ print n.primemr? }, " secs" -puts - -# 19 digit prime -n = 9241386435364257883.to_big_i -print "\n number = #{n} is prime? "; print " in ", tm{ print n.primemr? }, " secs" -puts - -# 20 digit prime; largest < 2^64 -n = 18446744073709551533.to_big_i -print "\n number = #{n} is prime? "; print " in ", tm{ print n.primemr? }, " secs" -puts - -# 58 digit prime -n = "4547337172376300111955330758342147474062293202868155909489".to_big_i -print "\n number = #{n} is prime? "; print " in ", tm{ print n.primemr? }, " secs" -puts - -# 58 digit non-prime -n = "4547337172376300111955330758342147474062293202868155909393".to_big_i -print "\n number = #{n} is prime? "; print " in ", tm{ print n.primemr? }, " secs" -puts - -# 81 digit prime -n = "100000000000000000000000000000000000000000000000000000000000000000000000001309503".to_big_i -print "\n number = #{n} is prime? "; print " in ", tm{ print n.primemr? }, " secs" -puts - -# 81 digit non-prime -n = "100000000000000000000000000000000000000000000000000000000000000000000000001309509".to_big_i -print "\n number = #{n} is prime? "; print " in ", tm{ print n.primemr? }, " secs" -puts - -# 308 digit prime -n = "94366396730334173383107353049414959521528815310548187030165936229578960209523421808912459795329035203510284576187160076386643700441216547732914250578934261891510827140267043592007225160798348913639472564715055445201512461359359488795427875530231001298552452230535485049737222714000227878890892901228389026881".to_big_i -print "\n number = #{n} is prime? "; print " in ", tm{ print n.primemr? }, " secs" -puts - -n = "138028649176899647846076023812164793645371887571371559091892986639999096471811910222267538577825033963552683101137782650479906670021895135954212738694784814783986671046107023185842481502719762055887490765764329237651328922972514308635045190654896041748716218441926626988737664133219271115413563418353821396401".to_big_i -print "\n number = #{n} is prime? "; print " in ", tm{ print n.primemr? }, " secs" -puts - -n = "123301261697053560451930527879636974557474268923771832437126939266601921428796348203611050423256894847735769138870460373141723679005090549101566289920247264982095246187318303659027201708559916949810035265951104246512008259674244307851578647894027803356820480862664695522389066327012330793517771435385653616841".to_big_i -print "\n number = #{n} is prime? "; print " in ", tm{ print n.primemr? }, " secs" -puts - -n = "119432521682023078841121052226157857003721669633106050345198988740042219728400958282159638484144822421840470442893056822510584029066504295892189315912923804894933736660559950053226576719285711831138657839435060908151231090715952576998400120335346005544083959311246562842277496260598128781581003807229557518839".to_big_i -print "\n number = #{n} is prime? "; print " in ", tm{ print n.primemr? }, " secs" -puts - -n = "132082885240291678440073580124226578272473600569147812319294626601995619845059779715619475871419551319029519794232989255381829366374647864619189704922722431776563860747714706040922215308646535910589305924065089149684429555813953571007126408164577035854428632242206880193165045777949624510896312005014225526731".to_big_i -print "\n number = #{n} is prime? "; print " in ", tm{ print n.primemr? }, " secs" -puts - -n = "153410708946188157980279532372610756837706984448408515364579602515073276538040155990230789600191915021209039203172105094957316552912585741177975853552299222501069267567888742458519569317286299134843250075228359900070009684517875782331709619287588451883575354340318132216817231993558066067063143257425853927599".to_big_i -print "\n number = #{n} is prime? "; print " in ", tm{ print n.primemr? }, " secs" -puts - -n = "103130593592068072608023213244858971741946977638988649427937324034014356815504971087381663169829571046157738503075005527471064224791270584831779395959349442093395294980019731027051356344056416276026592333932610954020105156667883269888206386119513058400355612571198438511950152690467372712488391425876725831041".to_big_i -print "\n number = #{n} is prime? "; print " in ", tm{ print n.primemr? }, " secs" -puts - -n = "94366396730334173383107353049414959521528815310548187030165936229578960209523421808912459795329035203510284576187160076386643700441216547732914250578934261891510827140267043592007225160798348913639472564715055445201512461359359488795427875530231001298552452230535485049737222714000227878890892901228389026881".to_big_i -print "\n number = #{n} is prime? "; print " in ", tm{ print n.primemr? }, " secs" -puts diff --git a/Task/Miller-Rabin-primality-test/D/miller-rabin-primality-test.d b/Task/Miller-Rabin-primality-test/D/miller-rabin-primality-test.d deleted file mode 100644 index 6d958ac4cd..0000000000 --- a/Task/Miller-Rabin-primality-test/D/miller-rabin-primality-test.d +++ /dev/null @@ -1,50 +0,0 @@ -import std.random; - -bool isProbablePrime(in ulong n, in uint k=10) /*nothrow*/ @safe /*@nogc*/ { - static ulong modPow(ulong b, ulong e, in ulong m) - pure nothrow @safe @nogc { - ulong result = 1; - while (e > 0) { - if ((e & 1) == 1) - result = (result * b) % m; - b = (b ^^ 2) % m; - e >>= 1; - } - return result; - } - - if (n < 2 || n % 2 == 0) - return n == 2; - - ulong d = n - 1; - ulong s = 0; - while (d % 2 == 0) { - d /= 2; - s++; - } - assert(2 ^^ s * d == n - 1); - - outer: - foreach (immutable _; 0 .. k) { - immutable ulong a = uniform(2, n); - ulong x = modPow(a, d, n); - if (x == 1 || x == n - 1) - continue; - foreach (immutable __; 1 .. s) { - x = modPow(x, 2, n); - if (x == 1) - return false; - if (x == n - 1) - continue outer; - } - return false; - } - - return true; -} - -void main() { // Demo code. - import std.stdio, std.range, std.algorithm; - - iota(2, 30).filter!isProbablePrime.writeln; -} diff --git a/Task/Miller-Rabin-primality-test/E/miller-rabin-primality-test-1.e b/Task/Miller-Rabin-primality-test/E/miller-rabin-primality-test-1.e deleted file mode 100644 index 105c050ef4..0000000000 --- a/Task/Miller-Rabin-primality-test/E/miller-rabin-primality-test-1.e +++ /dev/null @@ -1,23 +0,0 @@ -def millerRabinPrimalityTest(n :(int > 0), k :int, random) :boolean { - if (n <=> 2 || n <=> 3) { return true } - if (n <=> 1 || n %% 2 <=> 0) { return false } - var d := n - 1 - var s := 0 - while (d %% 2 <=> 0) { - d //= 2 - s += 1 - } - for _ in 1..k { - def nextTrial := __continue - def a := random.nextInt(n - 3) + 2 # [2, n - 2] = [0, n - 4] + 2 = [0, n - 3) + 2 - var x := a**d %% n # Note: Will do optimized modular exponentiation - if (x <=> 1 || x <=> n - 1) { nextTrial() } - for _ in 1 .. (s - 1) { - x := x**2 %% n - if (x <=> 1) { return false } - if (x <=> n - 1) { nextTrial() } - } - return false - } - return true -} diff --git a/Task/Miller-Rabin-primality-test/E/miller-rabin-primality-test-2.e b/Task/Miller-Rabin-primality-test/E/miller-rabin-primality-test-2.e deleted file mode 100644 index c37614bea2..0000000000 --- a/Task/Miller-Rabin-primality-test/E/miller-rabin-primality-test-2.e +++ /dev/null @@ -1,4 +0,0 @@ -for i ? (millerRabinPrimalityTest(i, 1, entropy)) in 4..1000 { - print(i, " ") -} -println() diff --git a/Task/Miller-Rabin-primality-test/EchoLisp/miller-rabin-primality-test.l b/Task/Miller-Rabin-primality-test/EchoLisp/miller-rabin-primality-test.l deleted file mode 100644 index 2edf624824..0000000000 --- a/Task/Miller-Rabin-primality-test/EchoLisp/miller-rabin-primality-test.l +++ /dev/null @@ -1,39 +0,0 @@ -(lib 'bigint) - -;; output : #t if n probably prime -(define (miller-rabin n (k 7) (composite #f)(x)) -(define d (1- n)) -(define s 0) -(define a 0) -(while (even? d) - (set! s (1+ s)) - (set! d (quotient d 2))) - -(for [(i k)] - (set! a (+ 2 (random (- n 3)))) - (set! x (powmod a d n)) - #:continue (or (= x 1) (= x (1- n))) - (set! composite - (for [(r (in-range 1 s))] - (set! x (powmod x 2 n)) - #:break (= x 1) => #t - #:break (= x (1- n)) => #f - #t - )) - #:break composite => #f ) - (not composite)) - -;; output -(miller-rabin #101) - → #t -(miller-rabin #111) - → #f -(define big-prime (random-prime 1e+100)) -3461396142610375479080862553800503306376298093021233334170610435506057862777898396429 -6627816219192601527 -(miller-rabin big-prime) - → #t -(miller-rabin (1+ (factorial 100))) - → #f -(prime? (1+ (factorial 100))) ;; native - → #f diff --git a/Task/Miller-Rabin-primality-test/Elixir/miller-rabin-primality-test-1.elixir b/Task/Miller-Rabin-primality-test/Elixir/miller-rabin-primality-test-1.elixir deleted file mode 100644 index 432f2fe7c5..0000000000 --- a/Task/Miller-Rabin-primality-test/Elixir/miller-rabin-primality-test-1.elixir +++ /dev/null @@ -1,49 +0,0 @@ -defmodule Prime do - use Application - alias :math, as: Math - alias :rand, as: Rand - - def start( _type, _args ) do - primes = 5..1000 - |> Enum.filter( fn( x ) -> (rem x, 2) == 1 end ) - |> Enum.filter( fn( x ) -> miller_rabin?( x, 10) == True end ) - IO.inspect( primes, label: "Primes: ", limit: :infinity ) - - { :ok, self() } - end - - def modular_exp( x, y, mod ) do - with [ _ | bits ] = Integer.digits( y, 2 ) do - Enum.reduce bits, x, fn( bit, acc ) -> acc * acc |> ( &( if bit == 1, do: &1 * x, else: &1 ) ).() |> rem( mod ) end - end - end - - def miller_rabin( d, s ) when rem( d, 2 ) == 0, do: { s, d } - def miller_rabin( d, s ), do: miller_rabin( div( d, 2 ), s + 1 ) - - def miller_rabin?( n, g ) do - { s, d } = miller_rabin( n - 1, 0 ) - miller_rabin( n, g, s, d ) - end - - def miller_rabin( n, 0, _, _ ), do: True - def miller_rabin( n, g, s, d ) do - a = 1 + Rand.uniform( n - 3 ) - x = modular_exp( a, d, n ) - if x == 1 or x == n - 1 do - miller_rabin( n, g - 1, s, d ) - else - if miller_rabin( n, x, s - 1) == True, do: miller_rabin( n, g - 1, s, d ), else: False - end - end - - def miller_rabin( n, x, r ) when r <= 0, do: False - def miller_rabin( n, x, r ) do - x = modular_exp( x, 2, n ) - unless x == 1 do - unless x == n - 1, do: miller_rabin( n, x, r - 1 ), else: True - else - False - end - end -end diff --git a/Task/Miller-Rabin-primality-test/Elixir/miller-rabin-primality-test-2.elixir b/Task/Miller-Rabin-primality-test/Elixir/miller-rabin-primality-test-2.elixir deleted file mode 100644 index 370386f0c2..0000000000 --- a/Task/Miller-Rabin-primality-test/Elixir/miller-rabin-primality-test-2.elixir +++ /dev/null @@ -1,7 +0,0 @@ -miller_rabin?( 94366396730334173383107353049414959521528815310548187030165936229578960209523421808912459795329035203510284576187160076386643700441216547732914250578934261891510827140267043592007225160798348913639472564715055445201512461359359488795427875530231001298552452230535485049737222714000227878890892901228389026881, 1000 ) -miller_rabin?( 138028649176899647846076023812164793645371887571371559091892986639999096471811910222267538577825033963552683101137782650479906670021895135954212738694784814783986671046107023185842481502719762055887490765764329237651328922972514308635045190654896041748716218441926626988737664133219271115413563418353821396401, 1000 ) -miller_rabin?( 123301261697053560451930527879636974557474268923771832437126939266601921428796348203611050423256894847735769138870460373141723679005090549101566289920247264982095246187318303659027201708559916949810035265951104246512008259674244307851578647894027803356820480862664695522389066327012330793517771435385653616841, 1000 ) -miller_rabin?( 119432521682023078841121052226157857003721669633106050345198988740042219728400958282159638484144822421840470442893056822510584029066504295892189315912923804894933736660559950053226576719285711831138657839435060908151231090715952576998400120335346005544083959311246562842277496260598128781581003807229557518839, 1000 ) -miller_rabin?( 132082885240291678440073580124226578272473600569147812319294626601995619845059779715619475871419551319029519794232989255381829366374647864619189704922722431776563860747714706040922215308646535910589305924065089149684429555813953571007126408164577035854428632242206880193165045777949624510896312005014225526731, 1000 ) -miller_rabin?( 153410708946188157980279532372610756837706984448408515364579602515073276538040155990230789600191915021209039203172105094957316552912585741177975853552299222501069267567888742458519569317286299134843250075228359900070009684517875782331709619287588451883575354340318132216817231993558066067063143257425853927599, 1000 ) -miller_rabin?( 103130593592068072608023213244858971741946977638988649427937324034014356815504971087381663169829571046157738503075005527471064224791270584831779395959349442093395294980019731027051356344056416276026592333932610954020105156667883269888206386119513058400355612571198438511950152690467372712488391425876725831041, 1000 ) diff --git a/Task/Miller-Rabin-primality-test/Erlang/miller-rabin-primality-test-1.erl b/Task/Miller-Rabin-primality-test/Erlang/miller-rabin-primality-test-1.erl deleted file mode 100644 index 2873ce9c57..0000000000 --- a/Task/Miller-Rabin-primality-test/Erlang/miller-rabin-primality-test-1.erl +++ /dev/null @@ -1,90 +0,0 @@ --module(miller_rabin). - --export([is_prime/1, power/2]). - -is_prime(1) -> false; -is_prime(2) -> true; -is_prime(3) -> true; -is_prime(N) when N > 3, ((N rem 2) == 0) -> false; -is_prime(N) when ((N rem 2) ==1), N < 341550071728321 -> - is_mr_prime(N, proving_bases(N)); -is_prime(N) when ((N rem 2) == 1) -> - is_mr_prime(N, random_bases(N, 100)). - - -proving_bases(N) when N < 1373653 -> - [2, 3]; -proving_bases(N) when N < 9080191 -> - [31, 73]; -proving_bases(N) when N < 25326001 -> - [2, 3, 5]; -proving_bases(N) when N < 3215031751 -> - [2, 3, 5, 7]; -proving_bases(N) when N < 4759123141 -> - [2, 7, 61]; -proving_bases(N) when N < 1122004669633 -> - [2, 13, 23, 1662803]; -proving_bases(N) when N < 2152302898747 -> - [2, 3, 5, 7, 11]; -proving_bases(N) when N < 3474749660383 -> - [2, 3, 5, 7, 11, 13]; -proving_bases(N) when N < 341550071728321 -> - [2, 3, 5, 7, 11, 13, 17]. - - -is_mr_prime(N, As) when N>2, N rem 2 == 1 -> - {D, S} = find_ds(N), - %% this is a test for compositeness; the two case patterns disprove - %% compositeness. - not lists:any(fun(A) -> - case mr_series(N, A, D, S) of - [1|_] -> false; % first elem of list = 1 - L -> not lists:member(N-1, L) % some elem of list = N-1 - end - end, - As). - - -find_ds(N) -> - find_ds(N-1, 0). - - -find_ds(D, S) -> - case D rem 2 == 0 of - true -> - find_ds(D div 2, S+1); - false -> - {D, S} - end. - - -mr_series(N, A, D, S) when N rem 2 == 1 -> - Js = lists:seq(0, S), - lists:map(fun(J) -> pow_mod(A, power(2, J)*D, N) end, Js). - - -pow_mod(B, E, M) -> - case E of - 0 -> 1; - _ -> case ((E rem 2) == 0) of - true -> (power(pow_mod(B, (E div 2), M), 2)) rem M; - false -> (B*pow_mod(B, E-1, M)) rem M - end - end. - - -random_bases(N, K) -> - [basis(N) || _ <- lists:seq(1, K)]. - - -basis(N) when N>2 -> - 1 + random:uniform(N-3). % random:uniform returns a single random number in range 1 -> N-3, to which is added 1, shifting the range to 2 -> N-2 - - -power(B, E) -> - power(B, E, 1). - -power(_, 0, Acc) -> - Acc; -power(B, E, Acc) -> - power(B, E - 1, B * Acc). diff --git a/Task/Miller-Rabin-primality-test/Erlang/miller-rabin-primality-test-2.erl b/Task/Miller-Rabin-primality-test/Erlang/miller-rabin-primality-test-2.erl deleted file mode 100644 index d3c2cbb8bc..0000000000 --- a/Task/Miller-Rabin-primality-test/Erlang/miller-rabin-primality-test-2.erl +++ /dev/null @@ -1,182 +0,0 @@ -%%% @author Tony Wallace -%%% @copyright (C) 2021, Tony Wallace -%%% @doc -%%% For details of the algorithms used see -%%% https://en.wikipedia.org/wiki/Modular_exponentiation -%%% @end -%%% Created : 21 Jul 2021 by Tony Wallace - --module mod. --export [mod_mult/3,mod_exp/3,binary_exp/2,test/0]. - -mod_mult(I1,I2,Mod) when - I1 > Mod, - is_integer(I1), is_integer(I2), is_integer(Mod) -> - mod_mult(I1 rem Mod,I2,Mod); -mod_mult(I1,I2,Mod) when - I2 > Mod, - is_integer(I1), is_integer(I2), is_integer(Mod) -> - mod_mult(I1,I2 rem Mod,Mod); -mod_mult(I1,I2,Mod) when - is_integer(I1), is_integer(I2), is_integer(Mod) -> - (I1 * I2) rem Mod. - -mod_exp(Base,Exp,Mod) when - is_integer(Base), - is_integer(Exp), - is_integer(Mod), - Base > 0, - Exp > 0, - Mod > 0 -> - binary_exp_mod(Base,Exp,Mod); -mod_exp(_,0,_) -> 1. - - -binary_exp(Base,Exponent) when - is_integer(Base), - is_integer(Exponent), - Base > 0, - Exponent > 0 -> - binary_exp(Base,Exponent,1); -binary_exp(_,0) -> - 1. - -binary_exp(_,0,Result) -> - Result; -binary_exp(Base,Exponent,Acc) -> - binary_exp(Base*Base,Exponent bsr 1,Acc * exp_factor(Base,Exponent)). - - -binary_exp_mod(Base,Exponent,Mod) -> - binary_exp_mod(Base rem Mod,Exponent,Mod,1). -binary_exp_mod(_,0,_,Result) -> - Result; -binary_exp_mod(Base,Exponent,Mod,Acc) -> - binary_exp_mod((Base*Base) rem Mod, - Exponent bsr 1,Mod,(Acc * exp_factor(Base,Exponent))rem Mod). - -exp_factor(_,0) -> - 1; -exp_factor(Base,1) -> - Base; -exp_factor(Base,Exponent) -> - exp_factor(Base,Exponent band 1). - -test() -> - 445 = mod_exp(4,13,497), - %% Rosetta code example: - R = 1527229998585248450016808958343740453059 = - mod_exp(2988348162058574136915891421498819466320163312926952423791023078876139, - 2351399303373464486466122544523690094744975233415544072992656881240319, - binary_exp(10,40)), - R. -% mod module ends here - - -%% Modified version of rosetta code entry -%% Modification was more efficient exponentiation -%% Modification - use of rpc:pmap to utilise multithreaded CPUs --module(miller_rabin). - --export([is_prime/1,mr_series_test/4,mersennes/1,test/0]). - -is_prime(1) -> false; -is_prime(2) -> true; -is_prime(3) -> true; -is_prime(N) when N > 3, ((N rem 2) == 0) -> false; -is_prime(N) when ((N rem 2) ==1), N < 341550071728321 -> - is_mr_prime(N, proving_bases(N)); -is_prime(N) when ((N rem 2) == 1) -> - is_mr_prime(N, random_bases(N, 100)). - - -proving_bases(N) when N < 1373653 -> - [2, 3]; -proving_bases(N) when N < 9080191 -> - [31, 73]; -proving_bases(N) when N < 25326001 -> - [2, 3, 5]; -proving_bases(N) when N < 3215031751 -> - [2, 3, 5, 7]; -proving_bases(N) when N < 4759123141 -> - [2, 7, 61]; -proving_bases(N) when N < 1122004669633 -> - [2, 13, 23, 1662803]; -proving_bases(N) when N < 2152302898747 -> - [2, 3, 5, 7, 11]; -proving_bases(N) when N < 3474749660383 -> - [2, 3, 5, 7, 11, 13]; -proving_bases(N) when N < 341550071728321 -> - [2, 3, 5, 7, 11, 13, 17]. - - -is_mr_prime(N, As) when N>2, N rem 2 == 1 -> -% TStart = erlang:monotonic_time(), - {D, S} = find_ds(N), -% elapsed(TStart,"find_ds took ~p.~p seconds~n"), - %% this is a test for compositeness; the two case patterns disprove - %% compositeness. - TestResults = - rpc:pmap({miller_rabin,mr_series_test},[N,D,S],As), - - R= not lists:any(fun(X) -> X end,TestResults), -% elapsed(TStart,"is_mr_prime took ~p.~p seconds~n"), - R. - -mr_series_test(A,N,D,S) -> -% TMrS = erlang:monotonic_time(), - R = case mr_series(N, A, D, S) of - [1|_] -> false; % first elem of list = 1 - L -> not lists:member(N-1, L) % some elem of list = N-1 - end, -% elapsed(TMrS,"mr_series took ~p.~p seconds~n"), - R. - -%elapsed(TStart,Msg) -> -% TElapsed_ms = erlang:convert_time_unit(erlang:monotonic_time()-TStart,native,1000), -% TSec = TElapsed_ms div 1000, -% Tms = TElapsed_ms rem 1000, -% io:format(Msg, [TSec,Tms]). - - -find_ds(N) -> - find_ds(N-1, 0). - -find_ds(D, S) -> - case D rem 2 == 0 of - true -> - find_ds(D div 2, S+1); - false -> - {D, S} - end. - - -mr_series(N, A, D, S) when N rem 2 == 1 -> - Js = lists:seq(0, S), - lists:map(fun(J) -> mod:mod_exp(A, mod:binary_exp(2, J)*D, N) end, Js). - -random_bases(N, K) -> - [basis(N) || _ <- lists:seq(1, K)]. - - -basis(N) when N>2 -> - % random:uniform returns a single random number in range 1 -> N-3, - % to which is added 1, shifting the range to 2 -> N-2 - 1 + rand:uniform(N-3). - -mersennes(N) when N>0, is_integer(N) -> - 1 bsl N - 1. - -test() -> - TStart = erlang:monotonic_time(), - true = is_prime(7), - true = is_prime(41), - false = is_prime(42), - true = is_prime(mersennes(31)), - true = is_prime(mersennes(127)), % M(127) checks okay if 64 bit word size exceeded, - true = is_prime(mersennes(3217)), % about the size of an rsa key, - TFinish = erlang:monotonic_time(), - ElapsedSeconds = erlang:convert_time_unit(TFinish - TStart,native,1), - io:format("Time seconds = ~p~n",[ElapsedSeconds]), - ok - . diff --git a/Task/Miller-Rabin-primality-test/F-Sharp/miller-rabin-primality-test.fs b/Task/Miller-Rabin-primality-test/F-Sharp/miller-rabin-primality-test.fs deleted file mode 100644 index 6692183b86..0000000000 --- a/Task/Miller-Rabin-primality-test/F-Sharp/miller-rabin-primality-test.fs +++ /dev/null @@ -1,11 +0,0 @@ -// Miller primality test for n<3317044064679887385961981. Nigel Galloway: April 1st., 2021 -let a=[(2047I,[2I]);(1373653I,[2I;3I]);(9080191I,[31I;73I]);(25326001I,[2I;3I;5I]);(3215031751I,[2I;3I;5I;7I]);(4759123141I,[2I;7I;61I]);(1122004669633I,[2I;13I;23I;1662803I]); - (2152302898747I,[2I;3I;5I;7I;11I]);(3474749660383I,[2I;3I;5I;7I;11I;13I]);(341550071728321I,[2I;3I;5I;7I;11I;13I;17I]);(3825123056546413051I,[2I;3I;5I;7I;11I;13I;17I;19I;23I]); - (18446744073709551616I,[2I;3I;5I;7I;11I;13I;17I;19I;23I;29I;31I;37I]);(318665857834031151167461I,[2I;3I;5I;7I;11I;13I;17I;19I;23I;29I;31I;37I]);(3317044064679887385961981I,[2I;3I;5I;7I;11I;13I;17I;19I;23I;29I;31I;37I;41I])] -let rec fN g=function (n:bigint) when n.IsEven->fN(g+1)(n/2I) |n->(n,g) -let rec fG n d r=function a::t->match bigint.ModPow(a,d,n) with g when g=1I || g=n-1I->fG n d r t |g->fL(bigint.ModPow(g,2I,n)) n d t r - |_->true - and fL x n d a=function 1->false |r when x=n-1I->fG n d r a |r->fL(bigint.ModPow(x,2I,n)) n d a (r-1) -let mrP n=let (d,r)=fN 0 (n-1I) in fG n d r (snd(a|>List.find(fst>>(<)n))) - -printfn "%A %A" (mrP 2147483647I)(mrP 844674407370955389I) diff --git a/Task/Miller-Rabin-primality-test/Forth/miller-rabin-primality-test.fth b/Task/Miller-Rabin-primality-test/Forth/miller-rabin-primality-test.fth deleted file mode 100644 index b307e72b40..0000000000 --- a/Task/Miller-Rabin-primality-test/Forth/miller-rabin-primality-test.fth +++ /dev/null @@ -1,88 +0,0 @@ -\ modular multiplication and exponentiation -\ -: 3rd s" 2 pick" evaluate ; immediate - -: mod* ( a b m -- a*b {mod m} ) - >r um* r> ud/mod 2drop ; - -: mod^ ( x n m -- x^n {mod m} ) - >r 1 swap - begin ?dup while - dup 1 and 1 = - if - swap 3rd r@ mod* swap 1- - then dup 0> - if - rot dup r@ mod* -rot 2/ - then - repeat nip rdrop ; - -\ small divisor check: true => possibly prime; false => definitely not prime. -\ -31 constant π-128 -create maybe-prime? - 2 c, 3 c, 5 c, 7 c, 11 c, 13 c, 17 c, 19 c, 23 c, 29 c, - 31 c, 37 c, 41 c, 43 c, 47 c, 53 c, 59 c, 61 c, 67 c, 71 c, - 73 c, 79 c, 83 c, 89 c, 97 c, 101 c, 103 c, 107 c, 109 c, 113 c, - 127 c, -does> - true -rot - π-128 bounds do - i c@ dup * over > if leave then - dup i c@ mod 0= if 2drop false unloop exit then - loop drop ; - -\ actual Miller-Rabin test -\ -: factor-2s ( n -- s d ) - 0 swap - begin dup 1 and 0= while - swap 1+ swap 2/ - repeat ; - -: fermat-square-test ( n m s -- ? ) \ perform n = n^2 (mod m), s-1 times - 1- 0 ?do - 2dup - -1 = - if leave - then >r dup r@ mod* r> - loop - - -1 = ; - -: strong-fermat-pseudoprime? ( n a -- ? ) - over >r \ keep the modulus on the return stack - >r 1- factor-2s r> \ -- s d a - swap r@ mod^ \ s d a -- s, a^d (mod n) - dup 1 = \ a^d == 1 (mod n) => Fermat pseudoprime - if 2drop rdrop true - else r> rot fermat-square-test - then ; - -4.759.123.141 drop constant mr-det-3 \ Deterministic threshold; 3 bases - -create small-prime-bases 2 , 7 , 61 , \ deterministic up to mr-det-3 -create large-prime-bases 2 , 325 , 9375 , 28178 , 450775 , 9780504 , 1795265022 , \ known to be deterministic for 64 bit integers. - -: miler-rabin-bases ( n -- addr n ) - mr-det-3 < - if small-prime-bases 3 - else large-prime-bases 7 - then ; - -: miller-rabin-primality-test ( n -- f ) - dup miler-rabin-bases cells bounds do - dup i @ strong-fermat-pseudoprime? invert - if drop false unloop exit then - cell +loop drop true ; - -: prime? ( n -- f ) - dup 2 < - if drop false - else - dup maybe-prime? - if dup [ 127 dup * 1+ ] literal < - if drop true - else miller-rabin-primality-test - then - else drop false - then - then ; diff --git a/Task/Miller-Rabin-primality-test/Fortran/miller-rabin-primality-test-1.f b/Task/Miller-Rabin-primality-test/Fortran/miller-rabin-primality-test-1.f deleted file mode 100644 index 6039bca6ae..0000000000 --- a/Task/Miller-Rabin-primality-test/Fortran/miller-rabin-primality-test-1.f +++ /dev/null @@ -1,56 +0,0 @@ - module Miller_Rabin - use PrimeDecompose - implicit none - - integer, parameter :: max_decompose = 100 - - private :: int_rrand, max_decompose - -contains - - function int_rrand(from, to) - integer(huge) :: int_rrand - integer(huge), intent(in) :: from, to - - real :: o - call random_number(o) - int_rrand = floor(from + o * real(max(from,to) - min(from, to))) - end function int_rrand - - function miller_rabin_test(n, k) result(res) - logical :: res - integer(huge), intent(in) :: n - integer, intent(in) :: k - - integer(huge), dimension(max_decompose) :: f - integer(huge) :: s, d, i, a, x, r - - res = .true. - f = 0 - - if ( (n <= 2) .and. (n > 0) ) return - if ( mod(n, 2) == 0 ) then - res = .false. - return - end if - - call find_factors(n-1, f) - s = count(f == 2) - d = (n-1) / (2 ** s) - loop: do i = 1, k - a = int_rrand(2_huge, n-2) - x = mod(a ** d, n) - - if ( x == 1 ) cycle - do r = 0, s-1 - if ( x == ( n - 1 ) ) cycle loop - x = mod(x*x, n) - end do - if ( x == (n-1) ) cycle - res = .false. - return - end do loop - res = .true. - end function miller_rabin_test - -end module Miller_Rabin diff --git a/Task/Miller-Rabin-primality-test/Fortran/miller-rabin-primality-test-2.f b/Task/Miller-Rabin-primality-test/Fortran/miller-rabin-primality-test-2.f deleted file mode 100644 index e179c5a7d9..0000000000 --- a/Task/Miller-Rabin-primality-test/Fortran/miller-rabin-primality-test-2.f +++ /dev/null @@ -1,24 +0,0 @@ -program TestMiller - use Miller_Rabin - implicit none - - integer, parameter :: prec = 30 - integer(huge) :: i - - ! this is limited since we're not using a bignum lib - call do_test( (/ (i, i=1, 29) /) ) - -contains - - subroutine do_test(a) - integer(huge), dimension(:), intent(in) :: a - - integer :: i - - do i = 1, size(a,1) - print *, a(i), miller_rabin_test(a(i), prec) - end do - - end subroutine do_test - -end program TestMiller diff --git a/Task/Miller-Rabin-primality-test/Fortran/miller-rabin-primality-test-3.f b/Task/Miller-Rabin-primality-test/Fortran/miller-rabin-primality-test-3.f deleted file mode 100644 index 371949afca..0000000000 --- a/Task/Miller-Rabin-primality-test/Fortran/miller-rabin-primality-test-3.f +++ /dev/null @@ -1,77 +0,0 @@ - MODULE MRTEST !Try the Miller-Rabin primality test. - CONTAINS !Working only with in-built integers. - LOGICAL FUNCTION MRPRIME(N,TRIALS) !Could N be a prime number? - USE DFPORT !To get RAND. - INTEGER N !The number. - INTEGER TRIALS !The count of trials to make. - INTEGER D,S !Represents a number in a special form. - INTEGER TRIAL - INTEGER A,X,R -Catch some annoying cases. - IF (N .LE. 4) THEN !A single-digit number? - MRPRIME = N.GT.1 .AND. N.LE.3 !Yes. Some special values. - RETURN !Thus allow 2 to be reported as prime. - END IF !Yet, test for 2 as a possible factor for larger numbers. - MRPRIME = .FALSE. !Pessimism prevails. - IF (MOD(N,2).EQ.0 .OR. MOD(N,3).EQ.0) RETURN !Thus. -Construct D such that N - 1 = D*2**S. By here, N is odd, and greater than three. - D = N - 1 !Thus, D becomes an even number. - S = 1 !So, it has at least one power of two. - 10 D = D/2 !Divide it out. - IF (MOD(D,2).EQ.0) THEN !If there is another, - S = S + 1 !Count it, - GO TO 10 !And divide it out also. - END IF !So, D is no longer even. N = 1 + D*2**S - WRITE (6,11) N,D,S - 11 FORMAT("For ",I0,", D=",I0,",S=",I0) -Convince through repetition.. - T:DO TRIAL = 1,TRIALS !Some trials yield a definite result. - A = RAND(0)*(N - 2) + 2 !For small N, the birthday problem. - X = MODEXP(N,A,D) !A**D mod N. - WRITE (6,22) TRIAL,A,X,INT8(A)**D,N,MOD(INT8(A)**D,N) - 22 FORMAT(6X,"Trial ",I0,",A=",I4,",X=",I4, - 1 "=MOD(",I0,",",I0,")=",I0) - IF (X.EQ.1 .OR. X.EQ.N - 1) CYCLE T !Pox. A prime yields these. - DO R = 1,S - 1 !Step through the powers of two in N - 1. - X = MODEXP(N,X,2) !X**2 mod N. - WRITE (6,23) R,X - 23 FORMAT (14X,"R=",I4,",X=",I0) - IF (X.EQ.1) RETURN !Definitely composite. No prime does this. - IF (X.EQ.N - 1) CYCLE T !Pox. Try something else. - END DO !Another power of two? - RETURN !Definitely composite. - END DO T !Have another go. - MRPRIME = .TRUE. !Would further trials yield greater assurance? - END FUNCTION MRPRIME !Are some numbers resistant to this scheme? - - INTEGER FUNCTION MODEXP(N,X,P) !Calculate X**P mod N without overflowing... -C Relies on a.b mod n = (a mod n)(b mod n) mod n - INTEGER N,X,P !All presumed positive, and X < N. - INTEGER I !A stepper. - INTEGER*8 V,W !Broad scratchpads, otherwise N > 46340 may incur overflow in 32-bit. - V = 1 !=X**0 - IF (P.GT.0) THEN !Something to do? - I = P !Yes. Get a copy I can mess with. - W = X !=X**1, X**2, X**4, X**8, ... except, all are mod N. - 1 IF (MOD(I,2).EQ.1) V = MOD(V*W,N) !Incorporate W if the low-end calls for it. - I = I/2 !Used. Shift the next one down. - IF (I.GT.0) THEN !Still something to do? - W = MOD(W**2,N) !Yes. Square W ready for the next bit up. - GO TO 1 !Consider it. - END IF !Don't square W if nothing remains. It might overflow. - END IF !Negative powers are ignored. - MODEXP = V !Done, in lb(P) iterations! - END FUNCTION MODEXP !"Bit" presence by arithmetic: works for non-binary arithmetic too. - - PROGRAM POKEMR - USE MRTEST - INTEGER I - LOGICAL HIC - - DO I = 3,36,2 - HIC = MRPRIME(I,6) - WRITE (6,11) I,HIC - 11 FORMAT (I6,1X,L) - END DO - - END diff --git a/Task/Miller-Rabin-primality-test/FreeBASIC/miller-rabin-primality-test-1.basic b/Task/Miller-Rabin-primality-test/FreeBASIC/miller-rabin-primality-test-1.basic deleted file mode 100644 index 5918e677b7..0000000000 --- a/Task/Miller-Rabin-primality-test/FreeBASIC/miller-rabin-primality-test-1.basic +++ /dev/null @@ -1,101 +0,0 @@ -' version 29-11-2016 -' compile with: fbc -s console - -' TRUE/FALSE are built-in constants since FreeBASIC 1.04 -' But we have to define them for older versions. -#Ifndef TRUE - #Define FALSE 0 - #Define TRUE Not FALSE -#EndIf - -Function mul_mod(a As ULongInt, b As ULongInt, modulus As ULongInt) As ULongInt - ' returns a * b mod modulus - Dim As ULongInt x, y = a ' a mod modulus, but a is already smaller then modulus - - While b > 0 - If (b And 1) = 1 Then - x = (x + y) Mod modulus - End If - y = (y Shl 1) Mod modulus - b = b Shr 1 - Wend - - Return x - -End Function - -Function pow_mod(b As ULongInt, power As ULongInt, modulus As ULongInt) As ULongInt - ' returns b ^ power mod modulus - Dim As ULongInt x = 1 - - While power > 0 - If (power And 1) = 1 Then - ' x = (x * b) Mod modulus - x = mul_mod(x, b, modulus) - End If - ' b = (b * b) Mod modulus - b = mul_mod(b, b, modulus) - power = power Shr 1 - Wend - - Return x - -End Function - -Function miller_rabin_test(n As ULongInt, k As Integer) As Byte - - If n > 9223372036854775808ull Then ' limit 2^63, pow_mod/mul_mod can't handle bigger numbers - Print "number is to big, program will end" - Sleep - End - End If - - ' 2 is a prime, if n is smaller then 2 or n is even then n = composite - If n = 2 Then Return TRUE - If (n < 2) OrElse ((n And 1) = 0) Then Return FALSE - - Dim As ULongInt a, x, n_one = n - 1, d = n_one - Dim As UInteger s - - While (d And 1) = 0 - d = d Shr 1 - s = s + 1 - Wend - - While k > 0 - k = k - 1 - a = Int(Rnd * (n -2)) +2 ' 2 <= a < n - x = pow_mod(a, d, n) - If (x = 1) Or (x = n_one) Then Continue While - For r As Integer = 1 To s -1 - x = pow_mod(x, 2, n) - If x = 1 Then Return FALSE - If x = n_one Then Continue While - Next - If x <> n_one Then Return FALSE - Wend - Return TRUE - -End Function -' ------=< MAIN >=------ - -Randomize Timer - -Dim As Integer total -Dim As ULongInt y, limit = 2^63-1 - -For y = limit - 1000 To limit - If miller_rabin_test(y, 5) = TRUE Then - total = total + 1 - Print y, - End If -Next - -Print : Print -Print total; " primes between "; limit - 1000; " and "; y -1 - -' empty keyboard buffer -While Inkey <> "" : Wend -Print : Print "hit any key to end program" -Sleep -End diff --git a/Task/Miller-Rabin-primality-test/FreeBASIC/miller-rabin-primality-test-2.basic b/Task/Miller-Rabin-primality-test/FreeBASIC/miller-rabin-primality-test-2.basic deleted file mode 100644 index 9a55e5fb9e..0000000000 --- a/Task/Miller-Rabin-primality-test/FreeBASIC/miller-rabin-primality-test-2.basic +++ /dev/null @@ -1,115 +0,0 @@ -' version 05-04-2017 -' compile with: fbc -s console - -' TRUE/FALSE are built-in constants since FreeBASIC 1.04 -' But we have to define them for older versions. -#Ifndef TRUE - #Define FALSE 0 - #Define TRUE Not FALSE -#EndIf - -#Include Once "gmp.bi" - -#Macro big_int(a) - Dim As Mpz_ptr a = Allocate( Len( __mpz_struct)) - Mpz_init(a) -#EndMacro - -Dim Shared As __gmp_randstate_struct rnd_ - -Function miller_rabin(big_n As Mpz_ptr, num_of_tests As ULong) As Byte - - If mpz_cmp_ui(big_n, 1) < 1 Then - Print "Numbers smaller then 1 not allowed" - Sleep 5000 - End If - - If mpz_cmp_ui(big_n, 2) = 0 OrElse mpz_cmp_ui(big_n, 3) = 0 Then - Return TRUE ' 2 = prime , 3 = prime - End If - - If mpz_tstbit(big_n, 0) = 0 Then Return FALSE ' even number, no prime - - Dim As ULong r, s - Dim As Byte return_value = TRUE - - big_int(n_1) : big_int(n_2) : big_int(a) : big_int(d) : big_int(x) - - mpz_sub_ui(n_1, big_n, 1) : mpz_sub_ui(n_2, big_n, 2) : mpz_set(d, n_1) - - While mpz_tstbit(d, 0) = 0 - mpz_fdiv_q_2exp(d, d, 1) - s += 1 - Wend - - While num_of_tests > 0 - num_of_tests -= 1 - mpz_urandomm(a, @rnd_, n_2) - mpz_add_ui(a, a, 2) - mpz_powm(x, a, d, big_n) - If mpz_cmp_ui(x, 1) = 0 Or mpz_cmp(x, n_1) = 0 Then Continue While - - For r = 1 To s -1 - mpz_powm_ui(x, x, 2, big_n) - If mpz_cmp_ui(x, 1) = 0 Then - return_value = FALSE - Exit While - End If - If mpz_cmp(x, n_1) = 0 Then Continue While - Next - - If mpz_cmp(x, n_1) <> 0 Then - Return_value = FALSE - Exit while - End If - Wend - - mpz_clear(n_1) : mpz_clear(a) : mpz_clear(d) - mpz_clear(n_2) : mpz_clear(x) - - Return return_value - -End Function - -' ------=< MAIN >=------ - -Dim As Long x -Dim As String tmp -Dim As ZString Ptr gmp_str : gmp_str = Allocate(1000000) -big_int(big_n) - -Randomize Timer -gmp_randinit_mt(@rnd_) -For x = 0 To 200 'create seed for random generator - tmp += Str(Int(Rnd * 10)) -Next -Mpz_set_str(big_n, tmp, 10) -gmp_randseed(@rnd_, big_n) ' seed the random number generator - -For x = 2 To 100 - mpz_set_ui(big_n, x) - If miller_rabin(big_n, 5) = TRUE Then - Print Using "####"; x; - End If -Next - -Print : Print -For x = 2 To 3300 - mpz_set_ui(big_n, 1) - mpz_mul_2exp(big_n, big_n, x) - mpz_sub_ui(big_n, big_n, 1) - If miller_rabin(big_n, 5) = TRUE Then - gmp_str = Mpz_get_str(0, 10, big_n) - Print "2^";Str(x);"-1 = prime" - End If -Next - -gmp_randclear(@rnd_) -mpz_clear(big_n) -DeAllocate(gmp_str) - -' empty keyboard buffer -Print : While Inkey <> "" : Wend -Print : Print "hit any key to end program" -Sleep -End diff --git a/Task/Miller-Rabin-primality-test/FunL/miller-rabin-primality-test.funl b/Task/Miller-Rabin-primality-test/FunL/miller-rabin-primality-test.funl deleted file mode 100644 index 4975badbae..0000000000 --- a/Task/Miller-Rabin-primality-test/FunL/miller-rabin-primality-test.funl +++ /dev/null @@ -1,30 +0,0 @@ -import util.rnd - -def isProbablyPrimeMillerRabin( n, k ) = - d = n - 1 - s = 0 - - while 2|d - s++ - d /= 2 - - repeat k - a = rnd( 2, n ) - x = a^d mod n - - if x == 1 or x == n - 1 then continue - - repeat s - 1 - x = x^2 mod n - - if x == 1 then return false - - if x == n - 1 then break - else - return false - - true - -for i <- 3..100 - if isProbablyPrimeMillerRabin( i, 5 ) - println( i ) diff --git a/Task/Miller-Rabin-primality-test/Go/miller-rabin-primality-test.go b/Task/Miller-Rabin-primality-test/Go/miller-rabin-primality-test.go deleted file mode 100644 index 6eb848533c..0000000000 --- a/Task/Miller-Rabin-primality-test/Go/miller-rabin-primality-test.go +++ /dev/null @@ -1,66 +0,0 @@ -package main - -import "log" - -func main() { - // max uint32 is not prime - c := uint32(1<<32 - 1) - // a few primes near the top of the range. source: prime pages. - for _, p := range []uint32{1<<32 - 5, 1<<32 - 17, 1<<32 - 65, 1<<32 - 99} { - for ; c > p; c-- { - if prime(c) { - log.Fatalf("prime(%d) returned true", c) - } - } - if !prime(p) { - log.Fatalf("prime(%d) returned false", p) - } - c-- - } -} - -func prime(n uint32) bool { - // bases of 2, 7, 61 are sufficient to cover 2^32 - switch n { - case 0, 1: - return false - case 2, 7, 61: - return true - } - // compute s, d where 2^s * d = n-1 - nm1 := n - 1 - d := nm1 - s := 0 - for d&1 == 0 { - d >>= 1 - s++ - } - n64 := uint64(n) - for _, a := range []uint32{2, 7, 61} { - // compute x := a^d % n - x := uint64(1) - p := uint64(a) - for dr := d; dr > 0; dr >>= 1 { - if dr&1 != 0 { - x = x * p % n64 - } - p = p * p % n64 - } - if x == 1 || uint32(x) == nm1 { - continue - } - for r := 1; ; r++ { - if r >= s { - return false - } - x = x * x % n64 - if x == 1 { - return false - } - if uint32(x) == nm1 { - break - } - } - } - return true -} diff --git a/Task/Miller-Rabin-primality-test/Haskell/miller-rabin-primality-test-1.hs b/Task/Miller-Rabin-primality-test/Haskell/miller-rabin-primality-test-1.hs deleted file mode 100644 index 720a753764..0000000000 --- a/Task/Miller-Rabin-primality-test/Haskell/miller-rabin-primality-test-1.hs +++ /dev/null @@ -1,44 +0,0 @@ -module Primes where - -import System.Random -import System.IO.Unsafe - --- Miller-Rabin wrapped up as an (almost deterministic) pure function -isPrime :: Integer -> Bool -isPrime n = unsafePerformIO (isMillerRabinPrime 100 n) - - -isMillerRabinPrime :: Int -> Integer -> IO Bool -isMillerRabinPrime k n - | even n = return (n==2) - | n < 100 = return (n `elem` primesTo100) - | otherwise = do ws <- witnesses k n - return $ and [test n (pred n) evens (head odds) a | a <- ws] - where - (evens,odds) = span even (iterate (`div` 2) (pred n)) - -test :: Integral nat => nat -> nat -> [nat] -> nat -> nat -> Bool -test n n_1 evens d a = x `elem` [1,n_1] || n_1 `elem` powers - where - x = powerMod n a d - powers = map (powerMod n a) evens - -witnesses :: (Num a, Ord a, Random a) => Int -> a -> IO [a] -witnesses k n - | n < 9080191 = return [31,73] - | n < 4759123141 = return [2,7,61] - | n < 3474749660383 = return [2,3,5,7,11,13] - | n < 341550071728321 = return [2,3,5,7,11,13,17] - | otherwise = do g <- newStdGen - return $ take k (randomRs (2,n-1) g) - -primesTo100 :: [Integer] -primesTo100 = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97] - --- powerMod m x n = x^n `mod` m -powerMod :: Integral nat => nat -> nat -> nat -> nat -powerMod m x n = f (n - 1) x x `rem` m - where - f d a y = if d==0 then y else g d a y - g i b y | even i = g (i `quot` 2) (b*b `rem` m) y - | otherwise = f (i-1) b (b*y `rem` m) diff --git a/Task/Miller-Rabin-primality-test/Haskell/miller-rabin-primality-test-2.hs b/Task/Miller-Rabin-primality-test/Haskell/miller-rabin-primality-test-2.hs deleted file mode 100644 index c16fd65dcf..0000000000 --- a/Task/Miller-Rabin-primality-test/Haskell/miller-rabin-primality-test-2.hs +++ /dev/null @@ -1,55 +0,0 @@ -import Control.Monad (liftM) -import Data.Bits (Bits, testBit, shiftR) -import System.Random (Random, getStdGen, randomRs) -import System.IO.Unsafe (unsafePerformIO) -import Prelude hiding (even, odd) - -odd :: (Integral a, Bits a) => a -> Bool -odd = (`testBit` 0) - -even :: (Integral a, Bits a) => a -> Bool -even = not . odd - --- modPow - Recursive modular exponentiation by taking successive powers of two -modPow :: (Integral a, Bits a) => a -> a -> a -> a -modPow _ 0 _ = 1 -modPow base ex m = let term - | testBit ex 0 = base `mod` m - | otherwise = 1 - in (term * modPow (base^2 `mod` m) (ex `shiftR` 1) m) `mod` m - -isPrime :: (Integral a, Bits a, Random a) => a -> a -> Bool -isPrime n k - | n < 4 = if n > 1 then True else False -- Deal with 0-3. - | even n = False - | otherwise = let randPool = unsafePerformIO $ randNums (n - 2) - in witness k randPool - where - randNums upper = do - g <- getStdGen - return (randomRs (2, upper) g) - - (d, r) = let decompose d r - | odd d = (d, r) - | otherwise = decompose (d `shiftR` 1) (r + 1) - in decompose (n - 1) 0 - - witness 0 _ = True - witness k (a:rands) - | x == 1 || x == n - 1 = witness (k - 1) rands - | otherwise = check x (r - 1) - where - x = modPow a d n - - check _ 0 = False - check x count - | x' == 1 = False - | x' == n - 1 = witness (k - 1) rands - | otherwise = check x' (count - 1) - where x' = modPow x 2 n - --- main function for testing -main :: IO() -main = do - [n,k] <- liftM (map (\x -> read x :: Integer) . words) getLine - print $ isPrime n k diff --git a/Task/Miller-Rabin-primality-test/Icon/miller-rabin-primality-test.icon b/Task/Miller-Rabin-primality-test/Icon/miller-rabin-primality-test.icon deleted file mode 100644 index 367bf45a2d..0000000000 --- a/Task/Miller-Rabin-primality-test/Icon/miller-rabin-primality-test.icon +++ /dev/null @@ -1,33 +0,0 @@ -procedure main(A) - every n := !A do write(n," is ",(mrp(n,5),"probably prime")|"composite") -end - -procedure mrp(n, k) - if n = 2 then return "" - if n%2 = 0 then fail - nm1 := decompose(n-1) - s := nm1[1] - d := nm1[2] - every !k do { - a := ?(n-2)+1 - x := (a^d)%n - if x = (1|(n-1)) then next - every !(s-1) do { - x := (x*x)%n - if x = 1 then fail - if x = (n-1) then break next - } - fail - } - return "" -end - -procedure decompose(nm1) - s := 1 - d := nm1 - while d%2 = 0 do { - d /:= 2 - s +:= 1 - } - return [s,d] -end diff --git a/Task/Miller-Rabin-primality-test/Java/miller-rabin-primality-test-1.java b/Task/Miller-Rabin-primality-test/Java/miller-rabin-primality-test-1.java deleted file mode 100644 index 4d1c540a35..0000000000 --- a/Task/Miller-Rabin-primality-test/Java/miller-rabin-primality-test-1.java +++ /dev/null @@ -1,9 +0,0 @@ -import java.math.BigInteger; - -public class MillerRabinPrimalityTest { - public static void main(String[] args) { - BigInteger n = new BigInteger(args[0]); - int certainty = Integer.parseInt(args[1]); - System.out.println(n.toString() + " is " + (n.isProbablePrime(certainty) ? "probably prime" : "composite")); - } -} diff --git a/Task/Miller-Rabin-primality-test/Java/miller-rabin-primality-test-2.java b/Task/Miller-Rabin-primality-test/Java/miller-rabin-primality-test-2.java deleted file mode 100644 index 900c4001bb..0000000000 --- a/Task/Miller-Rabin-primality-test/Java/miller-rabin-primality-test-2.java +++ /dev/null @@ -1,79 +0,0 @@ -import java.math.BigInteger; - -public class Prime { - - // this is the RabinMiller test, deterministically correct for n < 341,550,071,728,321 - // http://rosettacode.org/wiki/Miller-Rabin_primality_test#Python:_Proved_correct_up_to_large_N - public static boolean isPrime(BigInteger n, int precision) { - - if (n.compareTo(new BigInteger("341550071728321")) >= 0) { - return n.isProbablePrime(precision); - } - - int intN = n.intValue(); - if (intN == 1 || intN == 4 || intN == 6 || intN == 8) return false; - if (intN == 2 || intN == 3 || intN == 5 || intN == 7) return true; - - int[] primesToTest = getPrimesToTest(n); - if (n.equals(new BigInteger("3215031751"))) { - return false; - } - BigInteger d = n.subtract(BigInteger.ONE); - BigInteger s = BigInteger.ZERO; - while (d.mod(BigInteger.valueOf(2)).equals(BigInteger.ZERO)) { - d = d.shiftRight(1); - s = s.add(BigInteger.ONE); - } - for (int a : primesToTest) { - if (try_composite(a, d, n, s)) { - return false; - } - } - return true; - } - - public static boolean isPrime(BigInteger n) { - return isPrime(n, 100); - } - - public static boolean isPrime(int n) { - return isPrime(BigInteger.valueOf(n), 100); - } - - public static boolean isPrime(long n) { - return isPrime(BigInteger.valueOf(n), 100); - } - - private static int[] getPrimesToTest(BigInteger n) { - if (n.compareTo(new BigInteger("3474749660383")) >= 0) { - return new int[]{2, 3, 5, 7, 11, 13, 17}; - } - if (n.compareTo(new BigInteger("2152302898747")) >= 0) { - return new int[]{2, 3, 5, 7, 11, 13}; - } - if (n.compareTo(new BigInteger("118670087467")) >= 0) { - return new int[]{2, 3, 5, 7, 11}; - } - if (n.compareTo(new BigInteger("25326001")) >= 0) { - return new int[]{2, 3, 5, 7}; - } - if (n.compareTo(new BigInteger("1373653")) >= 0) { - return new int[]{2, 3, 5}; - } - return new int[]{2, 3}; - } - - private static boolean try_composite(int a, BigInteger d, BigInteger n, BigInteger s) { - BigInteger aB = BigInteger.valueOf(a); - if (aB.modPow(d, n).equals(BigInteger.ONE)) { - return false; - } - for (int i = 0; BigInteger.valueOf(i).compareTo(s) < 0; i++) { - // if pow(a, 2**i * d, n) == n-1 - if (aB.modPow(BigInteger.valueOf(2).pow(i).multiply(d), n).equals(n.subtract(BigInteger.ONE))) { - return false; - } - } - return true; - } -} diff --git a/Task/Miller-Rabin-primality-test/JavaScript/miller-rabin-primality-test.js b/Task/Miller-Rabin-primality-test/JavaScript/miller-rabin-primality-test.js deleted file mode 100644 index 3eccbe062f..0000000000 --- a/Task/Miller-Rabin-primality-test/JavaScript/miller-rabin-primality-test.js +++ /dev/null @@ -1,24 +0,0 @@ -function probablyPrime(n) { - if (n === 2 || n === 3) return true - if (n % 2 === 0 || n < 2) return false - - // Write (n - 1) as 2^s * d - var s = 0, - d = n - 1 - while ((d & 1) == 0) { - d >>= 1 - ++s - } - - let base = 2 - var x = Math.pow(base, d) % n - - if (x == 1 || x == n - 1) return true - - for (var i = 1; i <= s; i++) { - x = (x * x) % n - - if (x === n - 1) return true - } - return false -} diff --git a/Task/Miller-Rabin-primality-test/Julia/miller-rabin-primality-test.julia b/Task/Miller-Rabin-primality-test/Julia/miller-rabin-primality-test.julia deleted file mode 100644 index 579ac6e856..0000000000 --- a/Task/Miller-Rabin-primality-test/Julia/miller-rabin-primality-test.julia +++ /dev/null @@ -1,27 +0,0 @@ -witnesses(n::Union(Uint8,Int8,Uint16,Int16)) = (2,3) -witnesses(n::Union(Uint32,Int32)) = n < 1373653 ? (2,3) : (2,7,61) -witnesses(n::Union(Uint64,Int64)) = - n < 1373653 ? (2,3) : - n < 4759123141 ? (2,7,61) : - n < 2152302898747 ? (2,3,5,7,11) : - n < 3474749660383 ? (2,3,5,7,11,13) : - (2,325,9375,28178,450775,9780504,1795265022) - -function isprime(n::Integer) - n == 2 && return true - (n < 2) | iseven(n) && return false - s = trailing_zeros(n-1) - d = (n-1) >>> s - for a in witnesses(n) - a < n || break - x = powermod(a,d,n) - x == 1 && continue - t = s - while x != n-1 - (t-=1) <= 0 && return false - x = oftype(n, Base.widemul(x,x) % n) - x == 1 && return false - end - end - return true -end diff --git a/Task/Miller-Rabin-primality-test/Kotlin/miller-rabin-primality-test.kotlin b/Task/Miller-Rabin-primality-test/Kotlin/miller-rabin-primality-test.kotlin deleted file mode 100644 index 21630dfc07..0000000000 --- a/Task/Miller-Rabin-primality-test/Kotlin/miller-rabin-primality-test.kotlin +++ /dev/null @@ -1,53 +0,0 @@ -// version 1.1.2 - -import java.math.BigInteger -import java.util.Random - -val bigTwo = BigInteger.valueOf(2L) - -fun isProbablyPrime(n: BigInteger, k: Int): Boolean { - require (n > bigTwo && n % bigTwo == BigInteger.ONE) { "Must be odd and greater than 2" } - var s = 0 - val nn = n - BigInteger.ONE - var d: BigInteger - do { - s++ - d = nn.shiftRight(s) - } - while (d % bigTwo == BigInteger.ZERO) - - val rand = Random() - loop@ for (i in 1..k) { - var a: BigInteger - do { - a = BigInteger(n.bitLength(), rand) - } - while(a < bigTwo || a > nn) // make sure it's in the interval [2, n - 1] - - var x = a.modPow(d, n) - if (x == BigInteger.ONE || x == nn) continue - for (r in 1 until s) { - x = (x * x) % n - if (x == BigInteger.ONE) return false - if (x == nn) break@loop - } - return false - } - return true -} - -fun main(args: Array) { - val k = 20 // say - // obtain all primes up to 100 - println("The following numbers less than 100 are prime:") - for (i in 3..99 step 2) - if (isProbablyPrime(BigInteger.valueOf(i.toLong()), k)) print("$i ") - println("\n") - // check if some big numbers are probably prime - val bia = arrayOf( - BigInteger("4547337172376300111955330758342147474062293202868155909489"), - BigInteger("4547337172376300111955330758342147474062293202868155909393") - ) - for (bi in bia) - println("$bi is ${if (isProbablyPrime(bi, k)) "probably prime" else "composite"}") -} diff --git a/Task/Miller-Rabin-primality-test/Liberty-BASIC/miller-rabin-primality-test.basic b/Task/Miller-Rabin-primality-test/Liberty-BASIC/miller-rabin-primality-test.basic deleted file mode 100644 index 5cb0cea40c..0000000000 --- a/Task/Miller-Rabin-primality-test/Liberty-BASIC/miller-rabin-primality-test.basic +++ /dev/null @@ -1,290 +0,0 @@ -DIM mersenne(11) -mersenne(1)=7 -mersenne(2)=31 -mersenne(3)=127 -mersenne(4)=8191 -mersenne(5)=131071 -mersenne(6)=524287 -mersenne(7)=2147483647 -mersenne(8)=2305843009213693951 -mersenne(9)=618970019642690137449562111 -mersenne(10)=162259276829213363391578010288127 -mersenne(11)=170141183460469231731687303715884105727 - - -dim SmallPrimes(1000) -data 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 -data 31, 37, 41, 43, 47, 53, 59, 61, 67, 71 -data 73, 79, 83, 89, 97, 101, 103, 107, 109, 113 -data 127, 131, 137, 139, 149, 151, 157, 163, 167, 173 -data 179, 181, 191, 193, 197, 199, 211, 223, 227, 229 -data 233, 239, 241, 251, 257, 263, 269, 271, 277, 281 -data 283, 293, 307, 311, 313, 317, 331, 337, 347, 349 -data 353, 359, 367, 373, 379, 383, 389, 397, 401, 409 -data 419, 421, 431, 433, 439, 443, 449, 457, 461, 463 -data 467, 479, 487, 491, 499, 503, 509, 521, 523, 541 -data 547, 557, 563, 569, 571, 577, 587, 593, 599, 601 -data 607, 613, 617, 619, 631, 641, 643, 647, 653, 659 -data 661, 673, 677, 683, 691, 701, 709, 719, 727, 733 -data 739, 743, 751, 757, 761, 769, 773, 787, 797, 809 -data 811, 821, 823, 827, 829, 839, 853, 857, 859, 863 -data 877, 881, 883, 887, 907, 911, 919, 929, 937, 941 -data 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013 -data 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069 -data 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151 -data 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223 -data 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291 -data 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373 -data 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451 -data 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511 -data 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583 -data 1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657 -data 1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733 -data 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811 -data 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889 -data 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987 -data 1993, 1997, 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053 -data 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, 2113, 2129 -data 2131, 2137, 2141, 2143, 2153, 2161, 2179, 2203, 2207, 2213 -data 2221, 2237, 2239, 2243, 2251, 2267, 2269, 2273, 2281, 2287 -data 2293, 2297, 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357 -data 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, 2417, 2423 -data 2437, 2441, 2447, 2459, 2467, 2473, 2477, 2503, 2521, 2531 -data 2539, 2543, 2549, 2551, 2557, 2579, 2591, 2593, 2609, 2617 -data 2621, 2633, 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687 -data 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, 2731, 2741 -data 2749, 2753, 2767, 2777, 2789, 2791, 2797, 2801, 2803, 2819 -data 2833, 2837, 2843, 2851, 2857, 2861, 2879, 2887, 2897, 2903 -data 2909, 2917, 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999 -data 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, 3067, 3079 -data 3083, 3089, 3109, 3119, 3121, 3137, 3163, 3167, 3169, 3181 -data 3187, 3191, 3203, 3209, 3217, 3221, 3229, 3251, 3253, 3257 -data 3259, 3271, 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331 -data 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391, 3407, 3413 -data 3433, 3449, 3457, 3461, 3463, 3467, 3469, 3491, 3499, 3511 -data 3517, 3527, 3529, 3533, 3539, 3541, 3547, 3557, 3559, 3571 -data 3581, 3583, 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643 -data 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709, 3719, 3727 -data 3733, 3739, 3761, 3767, 3769, 3779, 3793, 3797, 3803, 3821 -data 3823, 3833, 3847, 3851, 3853, 3863, 3877, 3881, 3889, 3907 -data 3911, 3917, 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989 -data 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049, 4051, 4057 -data 4073, 4079, 4091, 4093, 4099, 4111, 4127, 4129, 4133, 4139 -data 4153, 4157, 4159, 4177, 4201, 4211, 4217, 4219, 4229, 4231 -data 4241, 4243, 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297 -data 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391, 4397, 4409 -data 4421, 4423, 4441, 4447, 4451, 4457, 4463, 4481, 4483, 4493 -data 4507, 4513, 4517, 4519, 4523, 4547, 4549, 4561, 4567, 4583 -data 4591, 4597, 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657 -data 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729, 4733, 4751 -data 4759, 4783, 4787, 4789, 4793, 4799, 4801, 4813, 4817, 4831 -data 4861, 4871, 4877, 4889, 4903, 4909, 4919, 4931, 4933, 4937 -data 4943, 4951, 4957, 4967, 4969, 4973, 4987, 4993, 4999, 5003 -data 5009, 5011, 5021, 5023, 5039, 5051, 5059, 5077, 5081, 5087 -data 5099, 5101, 5107, 5113, 5119, 5147, 5153, 5167, 5171, 5179 -data 5189, 5197, 5209, 5227, 5231, 5233, 5237, 5261, 5273, 5279 -data 5281, 5297, 5303, 5309, 5323, 5333, 5347, 5351, 5381, 5387 -data 5393, 5399, 5407, 5413, 5417, 5419, 5431, 5437, 5441, 5443 -data 5449, 5471, 5477, 5479, 5483, 5501, 5503, 5507, 5519, 5521 -data 5527, 5531, 5557, 5563, 5569, 5573, 5581, 5591, 5623, 5639 -data 5641, 5647, 5651, 5653, 5657, 5659, 5669, 5683, 5689, 5693 -data 5701, 5711, 5717, 5737, 5741, 5743, 5749, 5779, 5783, 5791 -data 5801, 5807, 5813, 5821, 5827, 5839, 5843, 5849, 5851, 5857 -data 5861, 5867, 5869, 5879, 5881, 5897, 5903, 5923, 5927, 5939 -data 5953, 5981, 5987, 6007, 6011, 6029, 6037, 6043, 6047, 6053 -data 6067, 6073, 6079, 6089, 6091, 6101, 6113, 6121, 6131, 6133 -data 6143, 6151, 6163, 6173, 6197, 6199, 6203, 6211, 6217, 6221 -data 6229, 6247, 6257, 6263, 6269, 6271, 6277, 6287, 6299, 6301 -data 6311, 6317, 6323, 6329, 6337, 6343, 6353, 6359, 6361, 6367 -data 6373, 6379, 6389, 6397, 6421, 6427, 6449, 6451, 6469, 6473 -data 6481, 6491, 6521, 6529, 6547, 6551, 6553, 6563, 6569, 6571 -data 6577, 6581, 6599, 6607, 6619, 6637, 6653, 6659, 6661, 6673 -data 6679, 6689, 6691, 6701, 6703, 6709, 6719, 6733, 6737, 6761 -data 6763, 6779, 6781, 6791, 6793, 6803, 6823, 6827, 6829, 6833 -data 6841, 6857, 6863, 6869, 6871, 6883, 6899, 6907, 6911, 6917 -data 6947, 6949, 6959, 6961, 6967, 6971, 6977, 6983, 6991, 6997 -data 7001, 7013, 7019, 7027, 7039, 7043, 7057, 7069, 7079, 7103 -data 7109, 7121, 7127, 7129, 7151, 7159, 7177, 7187, 7193, 7207 -data 7211, 7213, 7219, 7229, 7237, 7243, 7247, 7253, 7283, 7297 -data 7307, 7309, 7321, 7331, 7333, 7349, 7351, 7369, 7393, 7411 -data 7417, 7433, 7451, 7457, 7459, 7477, 7481, 7487, 7489, 7499 -data 7507, 7517, 7523, 7529, 7537, 7541, 7547, 7549, 7559, 7561 -data 7573, 7577, 7583, 7589, 7591, 7603, 7607, 7621, 7639, 7643 -data 7649, 7669, 7673, 7681, 7687, 7691, 7699, 7703, 7717, 7723 -data 7727, 7741, 7753, 7757, 7759, 7789, 7793, 7817, 7823, 7829 -data 7841, 7853, 7867, 7873, 7877, 7879, 7883, 7901, 7907, 7919 - - -print "Liberty Miller Rabin Demonstration" -print "Loading Small Primes" -for i=1 to 1000: read x : SmallPrimes(i)=x :next :NoOfSmallPrimes=1000 -print NoOfSmallPrimes;" Primes Loaded" - -'Prompt "Enter number to test:";resp$ -'x=val(resp$) -'goto [Jump] - - -For i=1 to 11 - - x=mersenne(i) - - - t1=time$("ms") - [TryAnother] - print - - iterations=0 - [Loop] - iterations=iterations+1 - - if MillerRabin(x,7)=1 then - t2=time$("ms") - print "Composite, found in ";t2-t1;" milliseconds" - else - t2=time$("ms") - print x;" Probably Prime. Tested in ";t2-t1;" milliseconds" - playwave "tada.wav", async - end if - print - -next - -END - - -Function GCD( m,n ) -' Find greatest common divisor with Extend Euclidian Algorithm -' Knuth Vol 1 P.13 Algorithm E - -ap =1 :b =1 :a =0 :bp =0: c =m :d =n - -[StepE2] -q = int(c/d) :r = c-q*d - -if r<>0 then - c=d :d=r :t=ap :ap=a :a=t-q*a :t=bp :bp=b :b=t-q*b - 'print ap;" ";b;" ";a;" ";bp;" ";c;" ";d;" ";t;" ";q - goto [StepE2] -end if - -GCD=a*m+b*n - -'print ap;" ";b;" ";a;" ";bp;" ";c;" ";d;" ";t;" ";q - -End Function 'Extended Euclidian GCD - - function IsEven( x ) - if ( x MOD 2 )=0 then - IsEven=1 - else - IsEven=0 - end if -end function - - -function IsOdd( x ) - if ( x MOD 2 )=0 then - IsOdd=0 - else - IsOdd=1 - end if -end function - - -Function FastExp(x, y, N) - - if (y=1) then 'MOD(x,N) - FastExp=x-int(x/N)*N - goto [ExitFunction] - end if - - - if ( y and 1) = 0 then - - dum1=y/2 - dum2=y-int(y/2)*2 'MOD(y,2) - - temp=FastExp(x,dum1,N) - z=temp*temp - FastExp=z-int(z/N)*N 'MOD(temp*temp,N) - goto [ExitFunction] - else - - dum1=y-1 - dum1=dum1/2 - temp=FastExp(x,dum1,N) - dum2=temp*temp - temp=dum2-int(dum2/N)*N 'MOD(dum2,N) - - z=temp*x - FastExp=z-int(z/N)*N 'MOD(temp*x,N) - goto [ExitFunction] - end if - [ExitFunction] - -end function - - -Function MillerRabin(n,b) - -'print "Miller Rabin" -'t1=time$("ms") - - if IsEven(n) then - MillerRabin=1 - goto [ExtFn] - end if - - i=0 - [Loop] - i=i+1 - if i>1000 then goto [Continue] - if ( n MOD SmallPrimes(i) )=0 then - MillerRabin=0 - goto [ExtFn] - end if - goto [Loop] - [Continue] - - if GCD(n,b)>1 then - MillerRabin=1 - goto [ExtFn] - end if - - q=n-1 - - t=0 - - while (int(q) AND 1 )=0 - t=t+1 - q=int(q/2) - wend - - - r=FastExp(b, q, n) - - if ( r <> 1 ) then - e=0 - while ( e < (t-1) ) - if ( r <> (n-1) ) then - r=FastExp(r, r, n) - else - Exit While - end if - - e=e+1 - wend - [ExitLoop] - end if - - - if ( (r=1) OR (r=(n-1)) ) then - MillerRabin=0 - else - MillerRabin=1 - end if - -[ExtFn] - -End Function diff --git a/Task/Miller-Rabin-primality-test/Lua/miller-rabin-primality-test.lua b/Task/Miller-Rabin-primality-test/Lua/miller-rabin-primality-test.lua deleted file mode 100644 index f01280dc35..0000000000 --- a/Task/Miller-Rabin-primality-test/Lua/miller-rabin-primality-test.lua +++ /dev/null @@ -1,59 +0,0 @@ - function MRIsPrime(n, k) - -- If n is prime, returns true (without fail). - -- If n is not prime, then returns false with probability ≥ 4^(-k), true otherwise. - -- First, deal with 1 and multiples of 2. - if n == 1 then - return false - elseif n == 2 then - return true - elseif n%2 == 0 then - return false - end - -- Now n is odd and greater than 1. - -- Find the unique expression n = 1 + t*2^h for n, where t is odd and h≥1. - t = (n-1)/2 - h = 1 - while t%2 == 0 do - t = t/2 - h = h + 1 - end - for i = 1, k do - -- Generate a random integer between 1 and n-1 inclusive. - a = math.random(n-1) - -- Test whether a is an element of the set L, and return false if not. - if not IsInL(n, a, t, h) then - return false - end - end - -- All generated a were in the set L; thus with high probability, n is prime. - return true -end - -function IsInL(n, a, t, h) - local b = PowerMod(a, t, n) - if b == 1 then - return true - end - for j = 0, h-1 do - if b == n-1 then - return true - elseif b == 1 then - return false - end - b = (b^2)%n - end - return false -end - -function PowerMod(x, y, m) - -- Computes x^y mod m. - local z = 1 - while y > 0 do - if y%2 == 0 then - x, y, z = (x^2)%m, y//2, z - else - x, y, z = (x^2)%m, y//2, (x*z)%m - end - end - return z -end diff --git a/Task/Miller-Rabin-primality-test/Mathematica/miller-rabin-primality-test-1.math b/Task/Miller-Rabin-primality-test/Mathematica/miller-rabin-primality-test-1.math deleted file mode 100644 index 5fe7b92634..0000000000 --- a/Task/Miller-Rabin-primality-test/Mathematica/miller-rabin-primality-test-1.math +++ /dev/null @@ -1,9 +0,0 @@ -MillerRabin[n_,k_]:=Module[{d=n-1,s=0,test=True},While[Mod[d,2]==0 ,d/=2 ;s++] -Do[ - a=RandomInteger[{2,n-1}]; x=PowerMod[a,d,n]; - If[x!=1, - For[ r = 0, r < s, r++, If[x==n-1, Continue[]]; x = Mod[x*x, n]; ]; - If[ x != n-1, test=False ]; - ]; -,{k}]; -Print[test] ] diff --git a/Task/Miller-Rabin-primality-test/Mathematica/miller-rabin-primality-test-2.math b/Task/Miller-Rabin-primality-test/Mathematica/miller-rabin-primality-test-2.math deleted file mode 100644 index f677f431b5..0000000000 --- a/Task/Miller-Rabin-primality-test/Mathematica/miller-rabin-primality-test-2.math +++ /dev/null @@ -1,2 +0,0 @@ -MillerRabin[17388,10] -->False diff --git a/Task/Miller-Rabin-primality-test/Maxima/miller-rabin-primality-test.maxima b/Task/Miller-Rabin-primality-test/Maxima/miller-rabin-primality-test.maxima deleted file mode 100644 index 569d825206..0000000000 --- a/Task/Miller-Rabin-primality-test/Maxima/miller-rabin-primality-test.maxima +++ /dev/null @@ -1,47 +0,0 @@ -/* Miller-Rabin algorithm is builtin, see function primep. Here is another implementation */ - - -/* find highest power of p, p^s, that divide n, and return s and n / p^s */ - -facpow(n, p) := block( - [s: 0], - while mod(n, p) = 0 do (s: s + 1, n: quotient(n, p)), - [s, n] -)$ - -/* check whether n is a strong pseudoprime to base a; s and d are given by facpow(n - 1, 2) */ - -sppp(n, a, s, d) := block( - [x: power_mod(a, d, n), q: false], - if x = 1 or x = n - 1 then true else ( - from 2 thru s do ( - x: mod(x * x, n), - if x = 1 then return(q: false) elseif x = n - 1 then return(q: true) - ), - q - ) -)$ - -/* Miller-Rabin primality test. For n < 341550071728321, the test is deterministic; - for larger n, the number of bases tested is given by the option variable - primep_number_of_tests, which is used by Maxima in primep. The bound for deterministic - test is also the same as in primep. */ - -miller_rabin(n) := block( - [v: [2, 3, 5, 7, 11, 13, 17], s, d, q: true, a], - if n < 19 then member(n, v) else ( - [s, d]: facpow(n - 1, 2), - if n < 341550071728321 then ( /* see http://oeis.org/A014233 */ - for a in v do ( - if not sppp(n, a, s, d) then return(q: false) - ), - q - ) else ( - thru primep_number_of_tests do ( - a: 2 + random(n - 3), - if not sppp(n, a, s, d) then return(q: false) - ), - q - ) - ) -)$ diff --git a/Task/Miller-Rabin-primality-test/Mercury/miller-rabin-primality-test.mercury b/Task/Miller-Rabin-primality-test/Mercury/miller-rabin-primality-test.mercury deleted file mode 100644 index 98de66d3d9..0000000000 --- a/Task/Miller-Rabin-primality-test/Mercury/miller-rabin-primality-test.mercury +++ /dev/null @@ -1,218 +0,0 @@ -%----------------------------------------------------------------------% -:- module primality. - -:- interface. - -:- import_module integer. -:- pred is_prime(integer::in, integer::out) is multi. - -%----------------------------------------------------------------------% -:- implementation. - -:- import_module bool, int, list, math, require, string. - -%----------------------------------------------------------------------% - % is_prime/2 implements a Miller-Rabin primality test, is - % deterministic for N < 3.415e+14, and is probabilistic for - % larger N. Returns integer(0) if not prime, integer(1) if prime, - % and -integer(1) if fails. - -% :- pred is_prime(integer::in, integer::out) is multi. - -is_prime(N, P) :- - N < integer(2), P = integer(0). -is_prime(N, P) :- - N = integer(2), P = integer(1). -is_prime(N, P) :- - N = integer(3), P = integer(1). -is_prime(N, P) :- %% even numbers > 3: false - N > integer(3), - (N mod integer(2)) = integer(0), - P = integer(0). - %%-------------deterministic-------- -is_prime(N, P) :- %% 3 < odd number < 3.415e+14 - N > integer(3), - (N mod integer(2)) = integer(1), - N < integer(341550071728321), - deterministic_witnesses(N, DList), - is_mr_prime(N, DList, R), - P = R. - %%-------------probabilistic-------- -is_prime(N, P) :- %% 3.415e+14 =< odd number - N > integer(3), - (N mod integer(2)) = integer(1), - N >= integer(341550071728321), - random_witnesses(N, 20, RList), - is_mr_prime(N, RList, R), - P = R. -is_prime(_N, P) :- P = -integer(1). - -%----------------------------------------------------------------------% -% returns list of deterministic witnesses - -:- pred deterministic_witnesses(integer::in, - list(integer)::out) is multi. - -deterministic_witnesses(N, L) :- N < integer(1373653), - L = [integer(2), integer(3)]. -deterministic_witnesses(N, L) :- N < integer(9080191), - L = [integer(31), integer(73)]. -deterministic_witnesses(N, L) :- N < integer(25326001), - L = [integer(2), integer(3), integer(5)]. -deterministic_witnesses(N, L) :- N < integer(3215031751), - L = [integer(2), integer(3), integer(5), integer(7)]. -deterministic_witnesses(N, L) :- N < integer(4759123141), - L = [integer(2), integer(7), integer(61)]. -deterministic_witnesses(N, L) :- N < integer(1122004669633), - L = [integer(2), integer(13), integer(23), integer(1662803)]. -deterministic_witnesses(N, L) :- N < integer(2152302898747), - L = [integer(2), integer(3), integer(5), integer(7), integer(11)]. -deterministic_witnesses(N, L) :- N < integer(3474749660383), - L = [integer(2), integer(3), integer(5), integer(7), integer(11), - integer(13)]. -deterministic_witnesses(N, L) :- N < integer(341550071728321), - L = [integer(2), integer(3), integer(5), integer(7), - integer(11), integer(13), integer(17)]. -deterministic_witnesses(_N, L) :- L = []. %% signals failure - -%----------------------------------------------------------------------% - %% random_witnesses/3 receives an integer, X, an int, K, and - %% returns a list, P, of K pseudo-random integers in a range - %% 1 to X-1. - -:- pred random_witnesses(integer::in, int::in, - list(integer)::out) is det. - -random_witnesses(X, K, P) :- - A = integer(6364136223846793005), - B = integer(1442695040888963407), - C = X - integer(2), - rw_loop(X, A, B, C, K, [], P). - -:- pred rw_loop(integer::in, integer::in, integer::in, integer::in, - int::in, list(integer)::in, list(integer)::out) is det. - -rw_loop(X, A, B, C, K, L, P) :- - X1 = (((X * A) + B) mod C) + integer(1), - ( if K = 0 then P = L - else rw_loop(X1, A, B, C, K-1, [X1|L], P) - ). - -%----------------------------------------------------------------------% - % is_mr_prime/2 receives integer N and list As and returns true if - % N is probably prime, and false otherwise - -:- pred is_mr_prime(integer::in, list(integer)::in, integer::out) is nondet. - -is_mr_prime(N, As, R) :- - find_ds(N, L), - L = [D|T], - T = [S|_], - outer_loop(N, As, D, S, R). - -:- pred outer_loop(integer::in, list(integer)::in, integer::in, - integer::in, integer::out) is nondet. - -outer_loop(N, As, D, S, R) :- - As = [A|At], - Base = powm(A, D, N), %% = A^D mod N - inner_loop(Base, N, integer(0), S, U), - ( if U = integer(0) then R = integer(0) - else ( if At = [] then R = integer(1) - else outer_loop(N, At, D, S, R) - ) - ). - -:- pred inner_loop(integer::in, integer::in, integer::in, - integer::in, integer::out) is multi. - -inner_loop(Base, N, Loop, S, U) :- - Next_Base = (Base * Base) mod N, - Next_Loop = Loop + integer(1), - ( if Loop = integer(0) then - ( if Base = integer(1) then U = integer(1) % true - else if Base = N - integer(1) then U = integer(1) % true - else if Next_Loop = S then U = integer(0) % false - else inner_loop(Next_Base, N, Next_Loop, S, U) - ) - else if Base = N - integer(1) then U = integer(1) % true - else if Next_Loop = S then U = integer(0) % false - else inner_loop(Next_Base, N, Next_Loop, S, U) - ). - -%----------------------------------------------------------------------% - % find_ds/2 receives odd integer N - % and returns [D, S] such that N-1 = 2^S * D - -:- pred find_ds(integer::in, list(integer)::out) is multi. - -find_ds(N, L) :- - A = N - integer(1), - find_ds1(A, integer(0), L). - -:- pred find_ds1(integer::in, integer::in, list(integer)::out) is multi. - -find_ds1(D, S, L) :- - D mod integer(2) = integer(0), - P = D div integer(2), - Q = S + integer(1), - find_ds1(P, Q, L). -find_ds1(D, S, L) :- - L = [D, S]. - -%----------------------------------------------------------------------% -:- func powm(integer, integer, integer) = integer. - - % computes A^D mod N - -powm(A, D, N) = - ( if D = integer(0) then integer(1) - else ( if (D mod integer(2)) = integer(0) then - (integer.pow(powm(A, (D div integer(2)), N), - integer(2))) mod N - else (A * powm(A, D - integer(1), N)) mod N - ) - ). - -%----------------------------------------------------------------------% -:- end_module primality. - -% A means of testing the predicate is_prime/2 -%----------------------------------------------------------------------% - -:- module test_is_prime. - -:- interface. - -:- import_module io. -:- pred main(io::di, io::uo) is cc_multi. - -%----------------------------------------------------------------------% - -:- implementation. - -:- import_module bool, char, int, integer, list, math, require, string. -:- import_module primality. - -%----------------------------------------------------------------------% - % TEST THE IS_PRIME PREDICATE - % $ ./test_is_prime - %---------------------------------------------% - -main(!IO) :- - command_line_arguments(Args, !IO), - filter(is_all_digits, Args, CleanArgs), - Arg1 = list.det_index0(CleanArgs, 0), - M = integer.det_from_string(Arg1), - is_prime(M,P), - io.format(" is_prime(%s) = ", [s(integer.to_string(M))], !IO), - ( if P = integer(0) then io.write_string("false.\n", !IO) - else if P = integer(1) then io.write_string("true.\n", !IO) - else if P = -integer(1) then - io.write_string("N fails all tests.\n", !IO) - else io.write_string("Has reported neither true nor false - nor any error condition.\n", !IO) - ). - -%----------------------------------------------------------------------% -:- end_module test_is_prime. diff --git a/Task/Miller-Rabin-primality-test/Nim/miller-rabin-primality-test-1.nim b/Task/Miller-Rabin-primality-test/Nim/miller-rabin-primality-test-1.nim deleted file mode 100644 index 5a898b4bca..0000000000 --- a/Task/Miller-Rabin-primality-test/Nim/miller-rabin-primality-test-1.nim +++ /dev/null @@ -1,73 +0,0 @@ -## Nim currently doesn't have a BigInt standard library -## so we translate the version from Go which uses a -## deterministic approach, which is correct for all -## possible values in uint32. - -proc isPrime*(n: uint32): bool = - # bases of 2, 7, 61 are sufficient to cover 2^32 - case n - of 0, 1: return false - of 2, 7, 61: return true - else: discard - - var - nm1 = n-1 - d = nm1.int - s = 0 - n = n.uint64 - - while d mod 2 == 0: - d = d shr 1 - s += 1 - - for a in [2, 7, 61]: - var - x = 1.uint64 - p = a.uint64 - dr = d - - while dr > 0: - if dr mod 2 == 1: - x = x * p mod n - p = p * p mod n - dr = dr shr 1 - - if x == 1 or x.uint32 == nm1: - continue - - var r = 1 - while true: - if r >= s: - return false - x = x * x mod n - if x == 1: - return false - if x.uint32 == nm1: - break - r += 1 - - return true - -proc isPrime*(n: int32): bool = - ## Overload for int32 - n >= 0 and n.uint32.isPrime - -when isMainModule: - const primeNumber1000 = 7919 # source: https://en.wikipedia.org/wiki/List_of_prime_numbers - var - i = 0u32 - numberPrimes = 0 - while true: - if isPrime(i): - if numberPrimes == 999: - break - numberPrimes += 1 - i += 1 - - assert i == primeNumber1000 - assert isPrime(2u32) - assert isPrime(31u32) - assert isPrime(37u32) - assert isPrime(1123u32) - assert isPrime(492366587u32) - assert isPrime(1645333507u32) diff --git a/Task/Miller-Rabin-primality-test/Nim/miller-rabin-primality-test-2.nim b/Task/Miller-Rabin-primality-test/Nim/miller-rabin-primality-test-2.nim deleted file mode 100644 index 68bab6ebb2..0000000000 --- a/Task/Miller-Rabin-primality-test/Nim/miller-rabin-primality-test-2.nim +++ /dev/null @@ -1,140 +0,0 @@ -# Compile as: $ nim c -d:release mrtest.nim -# Run using: $ ./mrtest - -import math # for gcd and mod -import bitops # for countTrailingZeroBits -import strutils, typetraits # for number input -import times, os # for timing code execution - -proc addmod*[T: SomeInteger](a, b, modulus: T): T = - ## Modular addition - let a_m = if a < modulus: a else: a mod modulus - if b == 0.T: return a_m - let b_m = if b < modulus: b else: b mod modulus - - # Avoid doing a + b that could overflow here - let b_from_m = modulus - b_m - if a_m >= b_from_m: return a_m - b_from_m - return a_m + b_m # safe to add here; a + b < modulus - -proc mulmod*[T: SomeInteger](a, b, modulus: T): T = - ## Modular multiplication - var a_m = if a < modulus: a else: a mod modulus - var b_m = if b < modulus: b else: b mod modulus - if b_m > a_m: swap(a_m, b_m) - while b_m > 0.T: - if (b_m and 1) == 1: result = addmod(result, a_m, modulus) - a_m = (a_m shl 1) - (if a_m >= (modulus - a_m): modulus else: 0) - b_m = b_m shr 1 - -proc expmod*[T: SomeInteger](base, exponent, modulus: T): T = - ## Modular exponentiation - result = 1 # (exp 0 = 1) - var (e, b) = (exponent, base) - while e > 0.T: - if (e and 1) == 1: result = mulmod(result, b, modulus) - e = e shr 1 - b = mulmod(b, b, modulus) - -# Returns true if +self+ passes Miller-Rabin Test on witnesses +b+ -proc miller_rabin_test[T: SomeInteger](num: T, witnesses: seq[uint64]): bool = - var d = num - 1 - let (neg_one_mod, n) = (d, d) - d = d shr countTrailingZeroBits(d) # suck out factors of 2 from d - for b in witnesses: # do M-R test with each witness base - if b.T mod num == 0: continue # **skip base if a multiple of input** - var s = d - var y = expmod(b.T, d, num) - while s != n and y != 1 and y != neg_one_mod: - y = mulmod(y, y, num) - s = s shl 1 - if y != neg_one_mod and (s and 1) != 1: return false - true - -proc selectWitnesses[T: SomeInteger](num: T): seq[uint64] = - ## Best known deterministic witnesses for given range and number of bases - ## https://miller-rabin.appspot.com/ - ## https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test - if num < 341_531u: - result = @[9345883071009581737u64] - elif num < 1_050_535_501u: - result = @[336781006125u64, 9639812373923155u64] - elif num < 350_269_456_337u: - result = @[4230279247111683200u64, 14694767155120705706u64, 16641139526367750375u64] - elif num < 55_245_642_489_451u: - result = @[2u64, 141889084524735u64, 1199124725622454117u64, 11096072698276303650u64] - elif num < 7_999_252_175_582_851u: - result = @[2u64, 4130806001517u64, 149795463772692060u64, 186635894390467037u64, 3967304179347715805u64] - elif num < 585_226_005_592_931_977u: - result = @[2u64, 123635709730000u64, 9233062284813009u64, 43835965440333360u64, 761179012939631437u64, 1263739024124850375u64] - elif num.uint64 < 18_446_744_073_709_551_615u64: - result = @[2u64, 325, 9375, 28178, 450775, 9780504, 1795265022] - else: - result = @[2u64, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] - -proc primemr*[T: SomeInteger](n: T): bool = - let primes = @[2u64, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] - if n <= primes[^1].T: return (n in primes) # for n <= primes.last - let modp47 = 614889782588491410u # => primes.product, largest < 2^64 - if gcd(n, modp47) != 1: return false # eliminates 86.2% of all integers - let witnesses = selectWitnesses(n) - miller_rabin_test(n, witnesses) - -echo "\nprimemr?" -echo("n = ", 1645333507u) -var te = epochTime() -echo primemr 1645333507u -echo (epochTime()-te).formatFloat(ffDecimal, 6) - -echo "\nprimemr?" -echo("n = ", 2147483647u) -te = epochTime() -echo primemr 2147483647u -echo (epochTime()-te).formatFloat(ffDecimal, 6) - -echo "\nprimemr?" -echo("n = ", 844674407370955389u) -te = epochTime() -echo primemr 844674407370955389u -echo (epochTime()-te).formatFloat(ffDecimal, 6) - -echo "\nprimemr?" -echo("n = ", 1844674407370954349u) -te = epochTime() -echo primemr 1844674407370954349u -echo (epochTime()-te).formatFloat(ffDecimal, 6) - -echo "\nprimemr?" -echo("n = ", 1844674407370954351u) -te = epochTime() -echo primemr 1844674407370954351u -echo (epochTime()-te).formatFloat(ffDecimal, 6) - -echo "\nprimemr?" -echo("n = ", 9223372036854775783u) -te = epochTime() -echo primemr 9223372036854775783u -echo (epochTime()-te).formatFloat(ffDecimal, 6) - -echo "\nprimemr?" -echo("n = ", 9241386435364257883u64) -te = epochTime() -echo primemr 9241386435364257883u64 -echo (epochTime()-te).formatFloat(ffDecimal, 6) - -echo "\nprimemr?" -echo("n = ", 18446744073709551533u64, ", is largest prime < 2^64") -te = epochTime() -echo 18446744073709551533u64.primemr -echo (epochTime()-te).formatFloat(ffDecimal, 6) - -echo "\nprimemr?" -let num = 5_000_000u # => 348_513 primes -var primes: seq[uint] = @[] -echo("find primes < ", num) -te = epochTime() -for n in 0u..num: - if n.primemr: primes.add(n) - stdout.write("\r",((float64(n) / float64(num))*100).formatFloat(ffDecimal, 1), "%") -echo("\nnumber of primes < ",num, " are ", primes.len) -echo (epochTime()-te).formatFloat(ffDecimal, 6) diff --git a/Task/Miller-Rabin-primality-test/Nim/miller-rabin-primality-test-3.nim b/Task/Miller-Rabin-primality-test/Nim/miller-rabin-primality-test-3.nim deleted file mode 100644 index f2d54af7be..0000000000 --- a/Task/Miller-Rabin-primality-test/Nim/miller-rabin-primality-test-3.nim +++ /dev/null @@ -1,41 +0,0 @@ -(* Translated from the wikipedia pseudo-code *) -let miller_rabin n ~iter:k = - (* return r and d where n = 2^r*d (from scheme implementation) *) - let get_rd n = - let rec loop r d = - (* not even *) - if Z.(equal (logand d one) one) then - (r,d) - else - loop Z.(r + one) Z.(div d ~$2) - in - loop Z.zero n - in - let single_miller n r d = - (* (random (n - 4)) + 2 *) - let a = Bigint.to_zarith_bigint - Bigint.((random ((of_zarith_bigint n) - (of_int 4))) + (of_int 2)) - in - let x = Z.(powm a d n) in - if Z.(equal x ~$1) || Z.(equal x (n - ~$1)) then true - else - let rec loop i x = - if Z.(equal ~$i (r - ~$1)) then false - else - let x = Z.(powm x ~$2 n) in - if Z.(equal x (n - ~$1)) then true - else loop (i + 1) x - in - loop 0 x - in - let n = Z.abs n in - if Z.(equal n one) then false - else if Z.(equal (logand n one) zero) then false - else if Z.(equal (n mod ~$3) zero) then false - else - let r, d = get_rd Z.(n - one) in - let rec loop i bool = - if i = k then bool - else loop (i + 1) (bool && single_miller n r d) - in - loop 0 true diff --git a/Task/Miller-Rabin-primality-test/Oz/miller-rabin-primality-test.oz b/Task/Miller-Rabin-primality-test/Oz/miller-rabin-primality-test.oz deleted file mode 100644 index 40882568ac..0000000000 --- a/Task/Miller-Rabin-primality-test/Oz/miller-rabin-primality-test.oz +++ /dev/null @@ -1,104 +0,0 @@ -%--------------------------------------------------------------------------% -% module: Primality -% file: Primality.oz -% version: 17 DEC 2014 @ 6:50AM -%--------------------------------------------------------------------------% - -declare -%--------------------------------------------------------------------------% - -fun {IsPrime N} % main interface of module - if N < 2 then false - elseif N < 4 then true - elseif (N mod 2) == 0 then false - elseif N < 341330071728321 then {IsMRprime N {DetWit N}} - else {IsMRprime N {ProbWit N 20}} - end -end -%--------------------------------------------------------------------------% - -fun {DetWit N} % deterministic witnesses - if N < 1373653 then [2 3] - elseif N < 9080191 then [31 73] - elseif N < 25326001 then [2 3 5] - elseif N < 3215031751 then [2 3 5 7] - elseif N < 4759123141 then [2 7 61] - elseif N < 1122004669633 then [2 13 23 1662803] - elseif N < 2152302898747 then [2 3 5 7 11] - elseif N < 3474749660383 then [2 3 5 7 11 13] - elseif N < 341550071728321 then [2 3 5 7 11 13 17] - else nil - end -end -%--------------------------------------------------------------------------% - -fun {ProbWit N K} % probabilistic witnesses - local A B C in - A = 6364136223846793005 - B = 1442695040888963407 - C = N - 2 - {RWloop N A B C K nil} - end -end - -fun {RWloop N A B C K L} - local N1 in - N1 = (((N * A) + B) mod C) + 1 - if K == 0 then L - else {RWloop N1 A B C (K - 1) N1|L} - end - end -end -%--------------------------------------------------------------------------% - -fun {IsMRprime N As} % the Miller-Rabin algorithm - local D S T Ts in - {FindDS N} = D|S - {OuterLoop N As D S} - end -end - -fun {OuterLoop N As D S} - local A At Base C in - As = A|At - Base = {Powm A D N} - C = {InnerLoop Base N 0 S} - if {Not C} then false - elseif {And C (At == nil)} then true - else {OuterLoop N At D S} - end - end -end - -fun {InnerLoop Base N Loop S} - local NextBase NextLoop in - NextBase = (Base * Base) mod N - NextLoop = Loop + 1 - if {And (Loop == 0) (Base == 1)} then true - elseif Base == (N - 1) then true - elseif NextLoop == S then false - else {InnerLoop NextBase N NextLoop S} - end - end -end -%--------------------------------------------------------------------------% - -fun {FindDS N} - {FindDS1 (N - 1) 0} -end - -fun {FindDS1 D S} - if (D mod 2 == 0) then {FindDS1 (D div 2) (S + 1)} - else D|S - end -end -%--------------------------------------------------------------------------% - -fun {Powm A D N} % returns (A ^ D) mod N - if D == 0 then 1 - elseif (D mod 2) == 0 then {Pow {Powm A (D div 2) N} 2} mod N - else (A * {Powm A (D - 1) N}) mod N - end -end -%--------------------------------------------------------------------------% -% end_module Primality diff --git a/Task/Miller-Rabin-primality-test/PARI-GP/miller-rabin-primality-test-1.parigp b/Task/Miller-Rabin-primality-test/PARI-GP/miller-rabin-primality-test-1.parigp deleted file mode 100644 index 881f191a12..0000000000 --- a/Task/Miller-Rabin-primality-test/PARI-GP/miller-rabin-primality-test-1.parigp +++ /dev/null @@ -1 +0,0 @@ -MR(n,k)=ispseudoprime(n,k); diff --git a/Task/Miller-Rabin-primality-test/PARI-GP/miller-rabin-primality-test-2.parigp b/Task/Miller-Rabin-primality-test/PARI-GP/miller-rabin-primality-test-2.parigp deleted file mode 100644 index b7a49019a4..0000000000 --- a/Task/Miller-Rabin-primality-test/PARI-GP/miller-rabin-primality-test-2.parigp +++ /dev/null @@ -1,16 +0,0 @@ -sprp(n,b)={ - my(s = valuation(n-1, 2), d = Mod(b, n)^(n >> s)); - if (d == 1, return(1)); - for(i=1,s-1, - if (d == -1, return(1)); - d = d^2; - ); - d == -1 -}; - -MR(n,k)={ - for(i=1,k, - if(!sprp(n,random(n-2)+2), return(0)) - ); - 1 -}; diff --git a/Task/Miller-Rabin-primality-test/PARI-GP/miller-rabin-primality-test-3.parigp b/Task/Miller-Rabin-primality-test/PARI-GP/miller-rabin-primality-test-3.parigp deleted file mode 100644 index 0e788eb524..0000000000 --- a/Task/Miller-Rabin-primality-test/PARI-GP/miller-rabin-primality-test-3.parigp +++ /dev/null @@ -1,20 +0,0 @@ -A006945=[9, 2047, 1373653, 25326001, 3215031751, 2152302898747, 3474749660383, 341550071728321, 341550071728321, 3825123056546413051]; -Miller(n)={ - if (n%2 == 0, return(n == 2)); \\ Handle even numbers - if (n < 3, return(0)); \\ Handle 0, 1, and negative numbers - - if (n < 1<<64, - \\ Feitsma - for(i=1,#A006945, - if (n < A006945[i], return(1)); - if(!sprp(n, prime(i)), return(0)); - ); - sprp(n,31)&sprp(n,37) - , - \\ Miller + Bach - for(b=2,2*log(n)^2, - if(!sprp(n, b), return(0)) - ); - 1 - ) -}; diff --git a/Task/Miller-Rabin-primality-test/PHP/miller-rabin-primality-test.php b/Task/Miller-Rabin-primality-test/PHP/miller-rabin-primality-test.php deleted file mode 100644 index 3e0189e65c..0000000000 --- a/Task/Miller-Rabin-primality-test/PHP/miller-rabin-primality-test.php +++ /dev/null @@ -1,39 +0,0 @@ - diff --git a/Task/Miller-Rabin-primality-test/Perl/miller-rabin-primality-test-1.pl b/Task/Miller-Rabin-primality-test/Perl/miller-rabin-primality-test-1.pl deleted file mode 100644 index 8390bbadca..0000000000 --- a/Task/Miller-Rabin-primality-test/Perl/miller-rabin-primality-test-1.pl +++ /dev/null @@ -1,32 +0,0 @@ -use bigint try => 'GMP'; - -sub is_prime { - my ($n, $k) = @_; - return 1 if $n == 2; - return 0 if $n < 2 or $n % 2 == 0; - - my $d = $n - 1; - my $s = 0; - - while (!($d % 2)) { - $d /= 2; - $s++; - } - - LOOP: for (1 .. $k) { - my $a = 2 + int(rand($n - 2)); - - my $x = $a->bmodpow($d, $n); - next if $x == 1 or $x == $n - 1; - - for (1 .. $s - 1) { - $x = ($x * $x) % $n; - return 0 if $x == 1; - next LOOP if $x == $n - 1; - } - return 0; - } - return 1; -} - -print join ", ", grep { is_prime $_, 10 } (1 .. 1000); diff --git a/Task/Miller-Rabin-primality-test/Perl/miller-rabin-primality-test-2.pl b/Task/Miller-Rabin-primality-test/Perl/miller-rabin-primality-test-2.pl deleted file mode 100644 index 5e93b4e8ba..0000000000 --- a/Task/Miller-Rabin-primality-test/Perl/miller-rabin-primality-test-2.pl +++ /dev/null @@ -1,10 +0,0 @@ -use ntheory qw/is_strong_pseudoprime miller_rabin_random/; -sub is_prime_mr { - my $n = shift; - # If 32-bit, we can do this with 3 bases. - return is_strong_pseudoprime($n, 2, 7, 61) if ($n >> 32) == 0; - # If 64-bit, 7 is all we need. - return is_strong_pseudoprime($n, 2, 325, 9375, 28178, 450775, 9780504, 1795265022) if ($n >> 64) == 0; - # Otherwise, perform a number of random base tests, and the result is a probable prime test. - return miller_rabin_random($n, 20); -} diff --git a/Task/Miller-Rabin-primality-test/Perl/miller-rabin-primality-test-3.pl b/Task/Miller-Rabin-primality-test/Perl/miller-rabin-primality-test-3.pl deleted file mode 100644 index f9de5c5498..0000000000 --- a/Task/Miller-Rabin-primality-test/Perl/miller-rabin-primality-test-3.pl +++ /dev/null @@ -1,10 +0,0 @@ -use Math::Primality qw/is_strong_pseudoprime/; -sub is_prime_mr { - my $n = shift; - return 0 if $n < 2; - for (2,3,5,7,11,13,17,19,23,29,31,37) { - return 0 unless $n <= $_ || is_strong_pseudoprime($n,$_); - } - 1; -} -for (1..100) { say if is_prime_mr($_) } diff --git a/Task/Miller-Rabin-primality-test/Phix/miller-rabin-primality-test-1.phix b/Task/Miller-Rabin-primality-test/Phix/miller-rabin-primality-test-1.phix deleted file mode 100644 index 2f0682a427..0000000000 --- a/Task/Miller-Rabin-primality-test/Phix/miller-rabin-primality-test-1.phix +++ /dev/null @@ -1,69 +0,0 @@ -(phixonline)--> - with javascript_semantics - function powermod(atom a, atom n, atom m) - -- calculate a^n%mod - atom p = a, res = 1 - while n do - if and_bits(n,1) then - res = mod(res*p,m) - end if - p = mod(p*p,m) - n = floor(n/2) - end while - return res - end function - - function witness(atom n, atom s, atom d, sequence a) - -- n-1 = 2^s * d with d odd by factoring powers of 2 from n-1 - for i=1 to length(a) do - atom x = powermod(a[i], d, n), y, w=s - while w do - y = mod(x*x,n) - if y == 1 and x != 1 and x != n-1 then - return false - end if - x = y - w -= 1 - end while - if y != 1 then - return false - end if - end for - return true; - end function - - function is_prime_mr(atom n) - if (mod(n,2)==0 and n!=2) - or (n<2) - or (mod(n,3)==0 and n!=3) then - return false - elsif n<=3 then - return true - end if - atom d = floor(n/2) - atom s = 1; - while and_bits(d,1)=0 do - d /= 2 - s += 1 - end while - - sequence a - if n < 1373653 then - a = {2, 3} - elsif n < 9080191 then - a = {31, 73} - elsif (machine_bits()=32 and n < 94910107) - or (machine_bits()=64 and n < 4295041217) then - a = {2, 7, 61} - else - puts(1,"limits exceeded\n") - return 0 - end if - return witness(n, s, d, a) - end function - - sequence tests = {999983,999809,999727,52633,60787,999999,999995,999991} - for i=1 to length(tests) do - printf(1,"%d is %s\n",{tests[i],{"composite","prime"}[is_prime_mr(tests[i])+1]}) - end for - - -- this is transpiled (then manually copied) to mpz_prime() in mpfr.js: - mpz modp47 = NULL, w - sequence witness_ranges - function mpz_prime_mr(mpz p, integer k = 10) - -- deterministic to 3,317,044,064,679,887,385,961,981 - constant primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47} - if mpz_cmp_si(p,primes[$])<=0 then - return find(mpz_get_integer(p),primes) - end if - if modp47=NULL then - modp47 = mpz_init("614_889_782_588_491_410") -- === product(primes), largest < 2^64 - w = mpz_init() - -- Best known deterministic witnesses for given range and set of bases - -- https://miller-rabin.appspot.com/ - -- https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test - witness_ranges = {{"341_531",{"9345883071009581737"}}, - {"1_050_535_501",{"336781006125", - "9639812373923155"}}, - {"350_269_456_337",{"4230279247111683200", - "14694767155120705706", - "16641139526367750375"}}, - {"55_245_642_489_451",{"2", "141889084524735", - "1199124725622454117", - "11096072698276303650"}}, - {"7_999_252_175_582_851",{"2", "4130806001517", - "149795463772692060", - "186635894390467037", - "3967304179347715805"}}, - {"585_226_005_592_931_977",{"2", "123635709730000", - "9233062284813009", - "43835965440333360", - "761179012939631437", - "1263739024124850375"}}, - {"18_446_744_073_709_551_615",{"2", "325", "9375", - "28178", "450775", - "9780504", "1795265022"}}, - {"318_665_857_834_031_151_167_461",{"2", "3", "5", "7", "11", - "13", "17", "19", "23", - "29", "31", "37"}}, - {"3_317_044_064_679_887_385_961_981",{"2", "3", "5", "7", "11", - "13", "17", "19", "23", - "29", "31", "37", "41"}}} - for i=1 to length(witness_ranges) do - witness_ranges[i][1] = mpz_init(witness_ranges[i][1]) - for j=1 to length(witness_ranges[i][2]) do - witness_ranges[i][2][j] = mpz_init(witness_ranges[i][2][j]) - end for - end for - end if - mpz_gcd(w,p,modp47) - if mpz_cmp_si(w,1)!=0 then - return false -- eliminates 86.2% of all integers - end if - -- - -- Choose input witness bases: - -- - sequence witnesses - if mpz_cmp(p,witness_ranges[$][1])>=0 then - witnesses = repeat(0,k) - for i=1 to k do - mpz a = mpz_init() - mpz_sub_ui(a, p, 2) - mpz_rand(a,a) -- a := 0..a-1 (cf rand(n) yields 1..n) - mpz_add_ui(a, a, 2) - witnesses[i] = a - end for - else - for i=1 to length(witness_ranges) do - if mpz_cmp(p,witness_ranges[i][1])<0 then - witnesses = witness_ranges[i][2] - exit - end if - end for - end if - mpz d = mpz_init() - mpz_sub_ui(d,p,1) - mpz nm1 = mpz_init_set(d) - -- d >>= 4 while (d & 0xf) == 0 # suck out factors of 2 - -- (d >>= (d & 3)^2; d >>= (d & 1)^1) if d.even? # 4 bits at a time - while mpz_even(d) do - mpz_fdiv_q_2exp(d, d, 1) - end while - - for i=1 to length(witnesses) do - mpz b = witnesses[i] - if not mpz_divisible_p(b,p) then -- skip multiples of input - mpz s = mpz_init_set(d), - y = mpz_init() - mpz_powm(y, b, d, p) -- y := b^d % p - while mpz_cmp_si(y,1)!=0 - and mpz_cmp(y,nm1)!=0 - and mpz_cmp(s,nm1)!=0 do - mpz_powm_ui(y, y, 2, p) -- y := y^2 mod p - mpz_mul_2exp(s, s, 1) -- s << 1 - end while - if mpz_cmp(y,nm1)!=0 then - if mpz_even(s) then return false end if - end if - end if - end for - return true - end function - - with javascript_semantics - include mpfr.e - mpz b = mpz_init("9223372036854774808") - integer c = 0 - for i=4808 to 5808 do -- (b ends thus) - if mpz_prime(b) then - c += 1 - printf(1," %s%s",{mpz_get_str(b),"\n"[1..mod(c,5)=0]}) - end if - mpz_add_ui(b,b,1) - end for - printf(1,"\n%d primes found\n\n",c) - - constant tests = {"4547337172376300111955330758342147474062293202868155909489", - "4547337172376300111955330758342147474062293202868155909393"} - for i=1 to length(tests) do - mpz_set_str(b,tests[i]) - string p = iff(mpz_prime(b)?"is prime":"is composite") - printf(1,"%s %s\n\n",{tests[i],p}) - end for - - for i=2 to 1300 do - mpz_ui_pow_ui(b,2,i) - mpz_sub_si(b,b,1) - if mpz_prime(b) then - printf(1,"2^%d-1 is prime\n",{i}) - end if - end for - [ $ ) - - 10000 eratosthenes - - [ 1 & not ] is even ( n --> b ) - - var n var d var s var a - var t var x var y var c - - [ dup 10000 < iff isprime done - dup even iff - [ drop false ] done - dup ->n - [ 1 - 0 swap - [ dup even while - 1 >> dip 1+ again ] ] - ->d ->s - false ->c - 20 times - [ n-> 2 - random 2 + ->a - s-> ->t - a-> d-> n-> **mod ->x - s-> times - [ x-> 2 n-> **mod ->y - y-> 1 = - x-> 1 != - x-> n-> 1 - != - and and iff - [ true ->c conclude ] - done - y-> ->x ] - c-> iff conclude done - y-> 1 != if - [ true ->c conclude ] ] - c-> not ] is prime ( n --> b ) - - say "Primes < 100:" cr - 100 times [ i^ prime if [ i^ echo sp ] ] - cr cr - [] 1000 times - [ i^ 9223372036854774808 + dup - prime iff join else drop ] - say "There are " - dup size echo - say " primes between 9223372036854774808 and 9223372036854775808:" - cr cr - witheach [ echo i^ 1+ 4 mod iff sp else cr ] - cr cr - 4547337172376300111955330758342147474062293202868155909489 dup echo - prime iff - [ say " is prime." ] - else - [ say " is not prime." ] - cr cr - 4547337172376300111955330758342147474062293202868155909393 dup echo - prime iff - [ say "is prime." ] - else - [ say " is not prime." ] diff --git a/Task/Miller-Rabin-primality-test/REXX/miller-rabin-primality-test.rexx b/Task/Miller-Rabin-primality-test/REXX/miller-rabin-primality-test.rexx deleted file mode 100644 index 0c977f54e7..0000000000 --- a/Task/Miller-Rabin-primality-test/REXX/miller-rabin-primality-test.rexx +++ /dev/null @@ -1,48 +0,0 @@ -/*REXX program puts the Miller─Rabin primality test through its paces. */ -parse arg limit times seed . /*obtain optional arguments from the CL*/ -if limit=='' | limit=="," then limit= 1000 /*Not specified? Then use the default.*/ -if times=='' | times=="," then times= 10 /* " " " " " " */ -if datatype(seed, 'W') then call random ,,seed /*If seed specified, use it for RANDOM.*/ -numeric digits max(200, 2*limit) /*we're dealing with some ginormous #s.*/ -tell= times<0 /*display primes only if times is neg.*/ -times= abs(times); w= length(times) /*use absolute value of TIMES; get len.*/ -call genP limit /*suspenders now, use a belt later ··· */ -@MR= 'Miller─Rabin primality test' /*define a character literal for SAY. */ -say "There are" # 'primes ≤' limit /*might as well display some stuff. */ -say /* [↓] (skipping unity); show sep line*/ - do a=2 to times; say copies('─', 89) /*(skipping unity) do range of TIMEs.*/ - p= 0 /*the counter of primes for this pass. */ - do z=1 for limit /*now, let's get busy and crank primes.*/ - if \M_Rt(z, a) then iterate /*Not prime? Then try another number.*/ - p= p + 1 /*well, we found another one, by gum! */ - if tell then say z 'is prime according to' @MR "with K="a - if !.z then iterate - say '[K='a"] " z "isn't prime !" /*oopsy─doopsy and/or whoopsy─daisy !*/ - end /*z*/ - say ' for 1──►'limit", K="right(a,w)',' @MR "found" p 'primes {out of' #"}." - end /*a*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -genP: parse arg high; @.=0; @.1=2; @.2=3; !.=@.; !.2=1; !.3=1; #=2 - do j=@.#+2 by 2 to high /*just examine odd integers from here. */ - do k=2 while k*k<=j; if j//@.k==0 then iterate j; end /*k*/ - #= # + 1; @.#= j; !.j= 1 /*bump prime counter; add prime to the */ - end /*j*/; return /*@. array; define a prime in !. array.*/ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -M_Rt: procedure; parse arg n,k; d= n-1; nL=d /*Miller─Rabin: A.K.A. Rabin─Miller.*/ - if n==2 then return 1 /*special case of (the) even prime. */ - if n<2 | n//2==0 then return 0 /*check for too low, or an even number.*/ - - do s=-1 while d//2==0; d= d % 2 /*keep halving until a zero remainder.*/ - end /*while*/ - - do k; ?= random(2, nL) /* [↓] perform the DO loop K times.*/ - x= ?**d // n /*X can get real gihugeic really fast.*/ - if x==1 | x==nL then iterate /*First or penultimate? Try another pow*/ - do s; x= x**2 // n /*compute new X ≡ X² modulus N. */ - if x==1 then return 0 /*if unity, it's definitely not prime.*/ - if x==nL then leave /*if N-1, then it could be prime. */ - end /*r*/ /* [↑] // is REXX's division remainder*/ - if x\==nL then return 0 /*nope, it ain't prime nohows, noway. */ - end /*k*/ /*maybe it's prime, maybe it ain't ··· */ - return 1 /*coulda/woulda/shoulda be prime; yup.*/ diff --git a/Task/Miller-Rabin-primality-test/Racket/miller-rabin-primality-test.rkt b/Task/Miller-Rabin-primality-test/Racket/miller-rabin-primality-test.rkt deleted file mode 100644 index e8cde1066f..0000000000 --- a/Task/Miller-Rabin-primality-test/Racket/miller-rabin-primality-test.rkt +++ /dev/null @@ -1,32 +0,0 @@ -#lang racket -(define (miller-rabin-expmod base exp m) - (define (squaremod-with-check x) - (define (check-nontrivial-sqrt1 x square) - (if (and (= square 1) - (not (= x 1)) - (not (= x (- m 1)))) - 0 - square)) - (check-nontrivial-sqrt1 x (remainder (expt x 2) m))) - (cond ((= exp 0) 1) - ((even? exp) (squaremod-with-check - (miller-rabin-expmod base (/ exp 2) m))) - (else - (remainder (* base (miller-rabin-expmod base (- exp 1) m)) - m)))) - -(define (miller-rabin-test n) - (define (try-it a) - (define (check-it x) - (and (not (= x 0)) (= x 1))) - (check-it (miller-rabin-expmod a (- n 1) n))) - (try-it (+ 1 (random (remainder (- n 1) 4294967087))))) - -(define (fast-prime? n times) - (for/and ((i (in-range times))) - (miller-rabin-test n))) - -(define (prime? n(times 100)) - (fast-prime? n times)) - -(prime? 4547337172376300111955330758342147474062293202868155909489) ;-> outputs true diff --git a/Task/Miller-Rabin-primality-test/Raku/miller-rabin-primality-test.raku b/Task/Miller-Rabin-primality-test/Raku/miller-rabin-primality-test.raku deleted file mode 100644 index a8f0c7c863..0000000000 --- a/Task/Miller-Rabin-primality-test/Raku/miller-rabin-primality-test.raku +++ /dev/null @@ -1,42 +0,0 @@ -# the expmod-function from: http://rosettacode.org/wiki/Modular_exponentiation -sub expmod(Int $a is copy, Int $b is copy, $n) { - my $c = 1; - repeat while $b div= 2 { - ($c *= $a) %= $n if $b % 2; - ($a *= $a) %= $n; - } - $c; -} - -subset PrimeCandidate of Int where { $_ > 2 and $_ % 2 }; - -my Bool multi sub is_prime(Int $n, Int $k) { return False; } -my Bool multi sub is_prime(2, Int $k) { return True; } -my Bool multi sub is_prime(PrimeCandidate $n, Int $k) { - my Int $d = $n - 1; - my Int $s = 0; - - while $d %% 2 { - $d div= 2; - $s++; - } - - for (2 ..^ $n).pick($k) -> $a { - my $x = expmod($a, $d, $n); - - # one could just write "next if $x == 1 | $n - 1" - # but this takes much more time in current rakudo/nom - next if $x == 1 or $x == $n - 1; - - for 1 ..^ $s { - $x = $x ** 2 mod $n; - return False if $x == 1; - last if $x == $n - 1; - } - return False if $x !== $n - 1; - } - - return True; -} - -say (1..1000).grep({ is_prime($_, 10) }).join(", "); diff --git a/Task/Miller-Rabin-primality-test/Ring/miller-rabin-primality-test.ring b/Task/Miller-Rabin-primality-test/Ring/miller-rabin-primality-test.ring deleted file mode 100644 index 7baac5dab1..0000000000 --- a/Task/Miller-Rabin-primality-test/Ring/miller-rabin-primality-test.ring +++ /dev/null @@ -1,48 +0,0 @@ -# Project : Miller–Rabin primality test - -see "Input a number: " give n -see "Input test: " give k - -test = millerrabin(n,k) -if test = 0 - see "Probably Prime" + nl -else - see "Composite" + nl -ok - -func millerrabin(n, k) - if n = 2 - millerRabin = 0 - return millerRabin - ok - if n % 2 = 0 or n < 2 - millerRabin = 1 - return millerRabin - ok - d = n - 1 - s = 0 - while d % 2 = 0 - d = d / 2 - s = s + 1 - end - while k > 0 - k = k - 1 - base = 2 + floor((random(10)/10)*(n-3)) - x = pow(base, d) % n - if x != 1 and x != n-1 - for r=1 to s-1 - x = (x * x) % n - if x = 1 - millerRabin = 1 - return millerRabin - ok - if x = n-1 - exit - ok - next - if x != n-1 - millerRabin = 1 - return millerRabin - ok - ok - end diff --git a/Task/Miller-Rabin-primality-test/Ruby/miller-rabin-primality-test-1.rb b/Task/Miller-Rabin-primality-test/Ruby/miller-rabin-primality-test-1.rb deleted file mode 100644 index 3577a2c7cb..0000000000 --- a/Task/Miller-Rabin-primality-test/Ruby/miller-rabin-primality-test-1.rb +++ /dev/null @@ -1,22 +0,0 @@ -def miller_rabin_prime?(n, g) - d = n - 1 - s = 0 - while d % 2 == 0 - d /= 2 - s += 1 - end - g.times do - a = 2 + rand(n - 4) - x = a.pow(d, n) # x = (a**d) % n - next if x == 1 || x == n - 1 - for r in (1..s - 1) - x = x.pow(2, n) # x = (x**2) % n - return false if x == 1 - break if x == n - 1 - end - return false if x != n - 1 - end - true # probably -end - -p primes = (3..1000).step(2).find_all {|i| miller_rabin_prime?(i,10)} diff --git a/Task/Miller-Rabin-primality-test/Ruby/miller-rabin-primality-test-2.rb b/Task/Miller-Rabin-primality-test/Ruby/miller-rabin-primality-test-2.rb deleted file mode 100644 index e9e6c29f44..0000000000 --- a/Task/Miller-Rabin-primality-test/Ruby/miller-rabin-primality-test-2.rb +++ /dev/null @@ -1,7 +0,0 @@ -puts miller_rabin_prime?(94366396730334173383107353049414959521528815310548187030165936229578960209523421808912459795329035203510284576187160076386643700441216547732914250578934261891510827140267043592007225160798348913639472564715055445201512461359359488795427875530231001298552452230535485049737222714000227878890892901228389026881,1000) -puts miller_rabin_prime?(138028649176899647846076023812164793645371887571371559091892986639999096471811910222267538577825033963552683101137782650479906670021895135954212738694784814783986671046107023185842481502719762055887490765764329237651328922972514308635045190654896041748716218441926626988737664133219271115413563418353821396401,1000) -puts miller_rabin_prime?(123301261697053560451930527879636974557474268923771832437126939266601921428796348203611050423256894847735769138870460373141723679005090549101566289920247264982095246187318303659027201708559916949810035265951104246512008259674244307851578647894027803356820480862664695522389066327012330793517771435385653616841,1000) -puts miller_rabin_prime?(119432521682023078841121052226157857003721669633106050345198988740042219728400958282159638484144822421840470442893056822510584029066504295892189315912923804894933736660559950053226576719285711831138657839435060908151231090715952576998400120335346005544083959311246562842277496260598128781581003807229557518839,1000) -puts miller_rabin_prime?(132082885240291678440073580124226578272473600569147812319294626601995619845059779715619475871419551319029519794232989255381829366374647864619189704922722431776563860747714706040922215308646535910589305924065089149684429555813953571007126408164577035854428632242206880193165045777949624510896312005014225526731,1000) -puts miller_rabin_prime?(153410708946188157980279532372610756837706984448408515364579602515073276538040155990230789600191915021209039203172105094957316552912585741177975853552299222501069267567888742458519569317286299134843250075228359900070009684517875782331709619287588451883575354340318132216817231993558066067063143257425853927599,1000) -puts miller_rabin_prime?(103130593592068072608023213244858971741946977638988649427937324034014356815504971087381663169829571046157738503075005527471064224791270584831779395959349442093395294980019731027051356344056416276026592333932610954020105156667883269888206386119513058400355612571198438511950152690467372712488391425876725831041,1000) diff --git a/Task/Miller-Rabin-primality-test/Ruby/miller-rabin-primality-test-3.rb b/Task/Miller-Rabin-primality-test/Ruby/miller-rabin-primality-test-3.rb deleted file mode 100644 index a625ed1176..0000000000 --- a/Task/Miller-Rabin-primality-test/Ruby/miller-rabin-primality-test-3.rb +++ /dev/null @@ -1,124 +0,0 @@ -class Integer - # Returns true if +self+ is a prime number, else returns false. - def primemr?(k = 10) - primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] - return primes.include? self if self <= primes.last - modp47 = 614_889_782_588_491_410 # => primes.reduce(:*), largest < 2^64 - return false if self.gcd(modp47) != 1 # eliminates 86.2% of all integers - # Choose input witness bases: wits = [range, [wit_bases]] or nil - wits = WITNESS_RANGES.find { |range, wits| range > self } - witnesses = wits && wits[1] || k.times.map{ 2 + rand(self - 4) } - miller_rabin_test(witnesses) - end - - private - # Returns true if +self+ passes Miller-Rabin Test with witness bases +b+ - def miller_rabin_test(witnesses) # use witness list to test with - neg_one_mod = n = d = self - 1 # these are even as 'self' always odd - d >>= 4 while (d & 0xf) == 0 # suck out factors of 2 - (d >>= (d & 3)^2; d >>= (d & 1)^1) if d.even? # 4 bits at a time - witnesses.each do |b| # do M-R test with each witness base - next if (b % self) == 0 # **skip base if a multiple of input** - s = d - y = b.pow(d, self) # y = (b**d) mod self - until y == 1 || y == neg_one_mod || s == n - y = y.pow(2, self) # y = (y**2) mod self - s <<= 1 - end - return false unless y == neg_one_mod || s.odd? - end - true - end - - # Best known deterministic witnesses for given range and set of bases - # https://miller-rabin.appspot.com/ - # https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test - WITNESS_RANGES = { - 341_531 => [9345883071009581737], - 1_050_535_501 => [336781006125, 9639812373923155], - 350_269_456_337 => [4230279247111683200, 14694767155120705706, 16641139526367750375], - 55_245_642_489_451 => [2, 141889084524735, 1199124725622454117, 11096072698276303650], - 7_999_252_175_582_851 => [2, 4130806001517, 149795463772692060, 186635894390467037, - 3967304179347715805], - 585_226_005_592_931_977 => [2, 123635709730000, 9233062284813009, 43835965440333360, - 761179012939631437, 1263739024124850375], - 18_446_744_073_709_551_615 => [2, 325, 9375, 28178, 450775, 9780504, 1795265022], - 318_665_857_834_031_151_167_461 => [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37], - 3_317_044_064_679_887_385_961_981 => [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41] - } -end - -def tm; t = Time.now; yield; Time.now - t end - -# 10 digit primes -n = 2147483647 -print "\n number = #{n} is prime? "; print " in ", tm{ print n.primemr? }, " secs" -puts - -# 18 digit non-prime -n = 844674407370955389 -print "\n number = #{n} is prime? "; print " in ", tm{ print n.primemr? }, " secs" -puts - -# 19 digit primes -n = 9241386435364257883 -print "\n number = #{n} is prime? "; print " in ", tm{ print n.primemr? }, " secs" -puts - -# 20 digit primes; largest < 2^64 -n = 18446744073709551533 -print "\n number = #{n} is prime? "; print " in ", tm{ print n.primemr? }, " secs" -puts - -# 58 digit prime -n = 4547337172376300111955330758342147474062293202868155909489 -print "\n number = #{n} is prime? "; print " in ", tm{ print n.primemr? }, " secs" -puts - -# 58 digit non-prime -n = 4547337172376300111955330758342147474062293202868155909393 -print "\n number = #{n} is prime? "; print " in ", tm{ print n.primemr? }, " secs" -puts - -# 81 digit prime -n = 100000000000000000000000000000000000000000000000000000000000000000000000001309503 -print "\n number = #{n} is prime? "; print " in ", tm{ print n.primemr? }, " secs" -puts - -# 81 digit non-prime -n = 100000000000000000000000000000000000000000000000000000000000000000000000001309509 -print "\n number = #{n} is prime? "; print " in ", tm{ print n.primemr? }, " secs" -puts - -# 308 digit prime -n = 94366396730334173383107353049414959521528815310548187030165936229578960209523421808912459795329035203510284576187160076386643700441216547732914250578934261891510827140267043592007225160798348913639472564715055445201512461359359488795427875530231001298552452230535485049737222714000227878890892901228389026881 -print "\n number = #{n} is prime? "; print " in ", tm{ print n.primemr? }, " secs" -puts - -n = 138028649176899647846076023812164793645371887571371559091892986639999096471811910222267538577825033963552683101137782650479906670021895135954212738694784814783986671046107023185842481502719762055887490765764329237651328922972514308635045190654896041748716218441926626988737664133219271115413563418353821396401 -print "\n number = #{n} is prime? "; print " in ", tm{ print n.primemr? }, " secs" -puts - -n = 123301261697053560451930527879636974557474268923771832437126939266601921428796348203611050423256894847735769138870460373141723679005090549101566289920247264982095246187318303659027201708559916949810035265951104246512008259674244307851578647894027803356820480862664695522389066327012330793517771435385653616841 -print "\n number = #{n} is prime "; print " in ", tm{ print n.primemr? }, " secs" -puts - -n = 119432521682023078841121052226157857003721669633106050345198988740042219728400958282159638484144822421840470442893056822510584029066504295892189315912923804894933736660559950053226576719285711831138657839435060908151231090715952576998400120335346005544083959311246562842277496260598128781581003807229557518839 -print "\n number = #{n} is prime "; print " in ", tm{ print n.primemr? }, " secs" -puts - -n = 132082885240291678440073580124226578272473600569147812319294626601995619845059779715619475871419551319029519794232989255381829366374647864619189704922722431776563860747714706040922215308646535910589305924065089149684429555813953571007126408164577035854428632242206880193165045777949624510896312005014225526731 -print "\n number = #{n} is prime? "; print " in ", tm{ print n.primemr? }, " secs" -puts - -n = 153410708946188157980279532372610756837706984448408515364579602515073276538040155990230789600191915021209039203172105094957316552912585741177975853552299222501069267567888742458519569317286299134843250075228359900070009684517875782331709619287588451883575354340318132216817231993558066067063143257425853927599 -print "\n number = #{n} is prime? "; print " in ", tm{ print n.primemr? }, " secs" -puts - -n = 103130593592068072608023213244858971741946977638988649427937324034014356815504971087381663169829571046157738503075005527471064224791270584831779395959349442093395294980019731027051356344056416276026592333932610954020105156667883269888206386119513058400355612571198438511950152690467372712488391425876725831041 -print "\n number = #{n} is prime? "; print " in ", tm{ print n.primemr? }, " secs" -puts - -n = 94366396730334173383107353049414959521528815310548187030165936229578960209523421808912459795329035203510284576187160076386643700441216547732914250578934261891510827140267043592007225160798348913639472564715055445201512461359359488795427875530231001298552452230535485049737222714000227878890892901228389026881 -print "\n number = #{n} is prime? "; print " in ", tm{ print n.primemr? }, " secs" -puts diff --git a/Task/Miller-Rabin-primality-test/Run-BASIC/miller-rabin-primality-test.basic b/Task/Miller-Rabin-primality-test/Run-BASIC/miller-rabin-primality-test.basic deleted file mode 100644 index e6539f22f2..0000000000 --- a/Task/Miller-Rabin-primality-test/Run-BASIC/miller-rabin-primality-test.basic +++ /dev/null @@ -1,55 +0,0 @@ -input "Input a number:";n -input "Input test:";k - -test = millerRabin(n,k) -if test = 0 then - print "Probably Prime" - else - print "Composite" -end if -wait - -' ---------------------------------------- -' Returns -' Composite = 1 -' Probably Prime = 0 -' ---------------------------------------- - FUNCTION millerRabin(n, k) - if n = 2 then - millerRabin = 0 'probablyPrime - goto [funEnd] - end if - - if n mod 2 = 0 or n < 2 then - millerRabin = 1 'composite - goto [funEnd] - end if - -d = n - 1 -while d mod 2 = 0 - d = d / 2 - s = s + 1 -wend - -while k > 0 - k = k - 1 - base = 2 + int(rnd(1)*(n-3)) - x = (base^d) mod n - if x <> 1 and x <> n-1 then - for r=1 To s-1 - x =(x * x) mod n - if x=1 then - millerRabin = 1 ' composite - goto [funEnd] - end if - if x = n-1 then exit for - next r - - if x<>n-1 then - millerRabin = 1 ' composite - goto [funEnd] - end if - end if -wend -[funEnd] -END FUNCTION diff --git a/Task/Miller-Rabin-primality-test/Rust/miller-rabin-primality-test-1.rust b/Task/Miller-Rabin-primality-test/Rust/miller-rabin-primality-test-1.rust deleted file mode 100644 index 3b78714afb..0000000000 --- a/Task/Miller-Rabin-primality-test/Rust/miller-rabin-primality-test-1.rust +++ /dev/null @@ -1,163 +0,0 @@ -/* Add these lines to the [dependencies] section of your Cargo.toml file: -num = "0.2.0" -rand = "0.6.5" -*/ - -use num::bigint::BigInt; -use num::bigint::ToBigInt; - - -// The modular_exponentiation() function takes three identical types -// (which get cast to BigInt), and returns a BigInt: -fn modular_exponentiation(n: &T, e: &T, m: &T) -> BigInt { - // Convert n, e, and m to BigInt: - let n = n.to_bigint().unwrap(); - let e = e.to_bigint().unwrap(); - let m = m.to_bigint().unwrap(); - - // Sanity check: Verify that the exponent is not negative: - assert!(e >= Zero::zero()); - - use num::traits::{Zero, One}; - - // As most modular exponentiations do, return 1 if the exponent is 0: - if e == Zero::zero() { - return One::one() - } - - // Now do the modular exponentiation algorithm: - let mut result: BigInt = One::one(); - let mut base = n % &m; - let mut exp = e; - - loop { // Loop until we can return our result. - if &exp % 2 == One::one() { - result *= &base; - result %= &m; - } - - if exp == One::one() { - return result - } - - exp /= 2; - base *= base.clone(); - base %= &m; - } -} - - -// is_prime() checks the passed-in number against many known small primes. -// If that doesn't determine if the number is prime or not, then the number -// will be passed to the is_rabin_miller_prime() function: -fn is_prime(n: &T) -> bool { - let n = n.to_bigint().unwrap(); - if n.clone() < 2.to_bigint().unwrap() { - return false - } - - let small_primes = vec![2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, - 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, - 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, - 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, - 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, - 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, - 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, - 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, - 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, - 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, - 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, - 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, - 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, - 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, - 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, - 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, - 991, 997, 1009, 1013]; - - use num::traits::Zero; // for Zero::zero() - - // Check to see if our number is a small prime (which means it's prime), - // or a multiple of a small prime (which means it's not prime): - for sp in small_primes { - let sp = sp.to_bigint().unwrap(); - - if n.clone() == sp { - return true - } else if n.clone() % sp == Zero::zero() { - return false - } - } - - is_rabin_miller_prime(&n, None) -} - - -// Note: "use bigint::RandBigInt;" (which is needed for gen_bigint_range()) -// fails to work in the Rust playground ( https://play.rust-lang.org ). -// Therefore, I'll create my own here: -fn get_random_bigint(low: &BigInt, high: &BigInt) -> BigInt { - if low == high { // base case - return low.clone() - } - - let middle = (low.clone() + high) / 2.to_bigint().unwrap(); - - let go_low: bool = rand::random(); - - if go_low { - return get_random_bigint(low, &middle) - } else { - return get_random_bigint(&middle, high) - } -} - - -// k is the number of times for testing (pass in None to use 5 (the default)). -fn is_rabin_miller_prime(n: &T, k: Option) -> bool { - let n = n.to_bigint().unwrap(); - let k = k.unwrap_or(10); // number of times for testing (defaults to 10) - - use num::traits::{Zero, One}; // for Zero::zero() and One::one() - let zero: BigInt = Zero::zero(); - let one: BigInt = One::one(); - let two: BigInt = 2.to_bigint().unwrap(); - - // The call to is_prime() should have already checked this, - // but check for two, less than two, and multiples of two: - if n <= one { - return false - } else if n == two { - return true // 2 is prime - } else if n.clone() % &two == Zero::zero() { - return false // even number (that's not 2) is not prime - } - - let mut t: BigInt = zero.clone(); - let n_minus_one: BigInt = n.clone() - &one; - let mut s = n_minus_one.clone(); - while &s % &two == one { - s /= &two; - t += &one; - } - - // Try k times to test if our number is non-prime: - 'outer: for _ in 0..k { - let a = get_random_bigint(&two, &n_minus_one); - let mut v = modular_exponentiation(&a, &s, &n); - if v == one { - continue 'outer; - } - let mut i: BigInt = zero.clone(); - 'inner: while &i < &t { - v = (v.clone() * &v) % &n; - if &v == &n_minus_one { - continue 'outer; - } - i += &one; - } - return false; - } - // If we get here, then we have a degree of certainty - // that n really is a prime number, so return true: - true -} diff --git a/Task/Miller-Rabin-primality-test/Rust/miller-rabin-primality-test-2.rust b/Task/Miller-Rabin-primality-test/Rust/miller-rabin-primality-test-2.rust deleted file mode 100644 index fa0e5ac5fa..0000000000 --- a/Task/Miller-Rabin-primality-test/Rust/miller-rabin-primality-test-2.rust +++ /dev/null @@ -1,25 +0,0 @@ -fn main() { - let n = 1234687; - let result = is_prime(&n); - println!("Q: Is {} prime? A: {}", n, result); - - let n = 1234689; - let result = is_prime(&n); - println!("Q: Is {} prime? A: {}", n, result); - - let n = BigInt::parse_bytes("123123423463".as_bytes(), 10).unwrap(); - let result = is_prime(&n); - println!("Q: Is {} prime? A: {}", n, result); - - let n = BigInt::parse_bytes("123123423465".as_bytes(), 10).unwrap(); - let result = is_prime(&n); - println!("Q: Is {} prime? A: {}", n, result); - - let n = BigInt::parse_bytes("123123423467".as_bytes(), 10).unwrap(); - let result = is_prime(&n); - println!("Q: Is {} prime? A: {}", n, result); - - let n = BigInt::parse_bytes("123123423469".as_bytes(), 10).unwrap(); - let result = is_prime(&n); - println!("Q: Is {} prime? A: {}", n, result); -} diff --git a/Task/Miller-Rabin-primality-test/Scala/miller-rabin-primality-test-1.scala b/Task/Miller-Rabin-primality-test/Scala/miller-rabin-primality-test-1.scala deleted file mode 100644 index 74cca99470..0000000000 --- a/Task/Miller-Rabin-primality-test/Scala/miller-rabin-primality-test-1.scala +++ /dev/null @@ -1,6 +0,0 @@ -import scala.math.BigInt - -object MillerRabinPrimalityTest extends App { - val (n, certainty )= (BigInt(args(0)), args(1).toInt) - println(s"$n is ${if (n.isProbablePrime(certainty)) "probably prime" else "composite"}") -} diff --git a/Task/Miller-Rabin-primality-test/Scala/miller-rabin-primality-test-2.scala b/Task/Miller-Rabin-primality-test/Scala/miller-rabin-primality-test-2.scala deleted file mode 100644 index 2b3e896c00..0000000000 --- a/Task/Miller-Rabin-primality-test/Scala/miller-rabin-primality-test-2.scala +++ /dev/null @@ -1,38 +0,0 @@ -import scala.annotation.tailrec -import scala.language.{implicitConversions, postfixOps} -import scala.util.Random - -object MillerRabin { - - implicit def int2Bools(b: Int): Seq[Boolean] = 31 to 0 by -1 map isBitSet(b) - - def isBitSet(byte: Int)(bit: Int): Boolean = ((byte >> bit) & 1) == 1 - - def mod(num: Int, denom: Int) = if (num % denom >= 0) num % denom else (num % denom) + denom - - @tailrec - def isSimple(p: Int, s: Int): Boolean = { - if (s == 0) { - true - } - else if (witness(Random.nextInt(p - 1), p)) { - false - } - else { - isSimple(p, s - 1) - } - } - - def witness(a: Int, p: Int): Boolean = { - val b: Seq[Boolean] = p - 1 - - b.foldLeft(1)((d, b) => if (mod(d * d, p) == 1 && d != 1 && d != p - 1) { - return true - } else { - b match { - case true => mod(mod(d*d, p)*a,p) - case false => mod(d*d, p) - } - }) != 1 - } -} diff --git a/Task/Miller-Rabin-primality-test/Scheme/miller-rabin-primality-test.ss b/Task/Miller-Rabin-primality-test/Scheme/miller-rabin-primality-test.ss deleted file mode 100644 index 8cf30c881a..0000000000 --- a/Task/Miller-Rabin-primality-test/Scheme/miller-rabin-primality-test.ss +++ /dev/null @@ -1,43 +0,0 @@ -#!r6rs -(import (rnrs base (6)) - (srfi :27 random-bits)) - -;; Fast modular exponentiation. -(define (modexpt b e M) - (cond - ((zero? e) 1) - ((even? e) (modexpt (mod (* b b) M) (div e 2) M)) - ((odd? e) (mod (* b (modexpt b (- e 1) M)) M)))) - -;; Return s, d such that d is odd and 2^s * d = n. -(define (split n) - (let recur ((s 0) (d n)) - (if (odd? d) - (values s d) - (recur (+ s 1) (div d 2))))) - -;; Test whether the number a proves that n is composite. -(define (composite-witness? n a) - (let*-values (((s d) (split (- n 1))) - ((x) (modexpt a d n))) - (and (not (= x 1)) - (not (= x (- n 1))) - (let try ((r (- s 1))) - (set! x (modexpt x 2 n)) - (or (zero? r) - (= x 1) - (and (not (= x (- n 1))) - (try (- r 1)))))))) - -;; Test whether n > 2 is a Miller-Rabin pseudoprime, k trials. -(define (pseudoprime? n k) - (or (zero? k) - (let ((a (+ 2 (random-integer (- n 2))))) - (and (not (composite-witness? n a)) - (pseudoprime? n (- k 1)))))) - -;; Test whether any integer is prime. -(define (prime? n) - (and (> n 1) - (or (= n 2) - (pseudoprime? n 50)))) diff --git a/Task/Miller-Rabin-primality-test/Seed7/miller-rabin-primality-test.seed7 b/Task/Miller-Rabin-primality-test/Seed7/miller-rabin-primality-test.seed7 deleted file mode 100644 index c792bc43f1..0000000000 --- a/Task/Miller-Rabin-primality-test/Seed7/miller-rabin-primality-test.seed7 +++ /dev/null @@ -1,46 +0,0 @@ -$ include "seed7_05.s7i"; - include "bigint.s7i"; - -const func boolean: millerRabin (in bigInteger: n, in integer: k) is func - result - var boolean: probablyPrime is TRUE; - local - var bigInteger: d is 0_; - var integer: r is 0; - var integer: s is 0; - var bigInteger: a is 0_; - var bigInteger: x is 0_; - var integer: tests is 0; - begin - if n < 2_ or (n > 2_ and not odd(n)) then - probablyPrime := FALSE; - elsif n > 3_ then - d := pred(n); - s := lowestSetBit(d); - d >>:= s; - while tests < k and probablyPrime do - a := rand(2_, pred(n)); - x := modPow(a, d, n); - if x <> 1_ and x <> pred(n) then - r := 1; - while r < s and x <> 1_ and x <> pred(n) do - x := modPow(x, 2_, n); - incr(r); - end while; - probablyPrime := x = pred(n); - end if; - incr(tests); - end while; - end if; - end func; - -const proc: main is func - local - var bigInteger: number is 0_; - begin - for number range 2_ to 1000_ do - if millerRabin(number, 10) then - writeln(number); - end if; - end for; - end func; diff --git a/Task/Miller-Rabin-primality-test/Sidef/miller-rabin-primality-test.sidef b/Task/Miller-Rabin-primality-test/Sidef/miller-rabin-primality-test.sidef deleted file mode 100644 index 575b57d5ad..0000000000 --- a/Task/Miller-Rabin-primality-test/Sidef/miller-rabin-primality-test.sidef +++ /dev/null @@ -1,28 +0,0 @@ -func miller_rabin(n, k=10) { - - return false if (n <= 1) - return true if (n == 2) - return false if (n.is_even) - - var t = n-1 - var s = t.valuation(2) - var d = t>>s - - k.times { - var a = irand(2, t) - var x = powmod(a, d, n) - next if (x ~~ [1, t]) - - (s-1).times { - x.powmod!(2, n) - return false if (x == 1) - break if (x == t) - } - - return false if (x != t) - } - - return true -} - -say miller_rabin.grep(^1000).join(', ') diff --git a/Task/Miller-Rabin-primality-test/Smalltalk/miller-rabin-primality-test-1.st b/Task/Miller-Rabin-primality-test/Smalltalk/miller-rabin-primality-test-1.st deleted file mode 100644 index d5af7acd3a..0000000000 --- a/Task/Miller-Rabin-primality-test/Smalltalk/miller-rabin-primality-test-1.st +++ /dev/null @@ -1,34 +0,0 @@ -Integer extend [ - millerRabinTest: kl [ |k| k := kl. - self <= 3 - ifTrue: [ ^true ] - ifFalse: [ - (self even) - ifTrue: [ ^false ] - ifFalse: [ |d s| - d := self - 1. - s := 0. - [ (d rem: 2) == 0 ] - whileTrue: [ - d := d / 2. - s := s + 1. - ]. - [ k:=k-1. k >= 0 ] - whileTrue: [ |a x r| - a := Random between: 2 and: (self - 2). - x := (a raisedTo: d) rem: self. - ( x = 1 ) - ifFalse: [ |r| - r := -1. - [ r := r + 1. (r < s) & (x ~= (self - 1)) ] - whileTrue: [ - x := (x raisedTo: 2) rem: self - ]. - ( x ~= (self - 1) ) ifTrue: [ ^false ] - ] - ]. - ^true - ] - ] - ] -]. diff --git a/Task/Miller-Rabin-primality-test/Smalltalk/miller-rabin-primality-test-2.st b/Task/Miller-Rabin-primality-test/Smalltalk/miller-rabin-primality-test-2.st deleted file mode 100644 index 2d8f953ef8..0000000000 --- a/Task/Miller-Rabin-primality-test/Smalltalk/miller-rabin-primality-test-2.st +++ /dev/null @@ -1,3 +0,0 @@ -1 to: 1000 do: [ :n | - (n millerRabinTest: 10) ifTrue: [ n printNl ] -]. diff --git a/Task/Miller-Rabin-primality-test/Standard-ML/miller-rabin-primality-test.ml b/Task/Miller-Rabin-primality-test/Standard-ML/miller-rabin-primality-test.ml deleted file mode 100644 index a28311939d..0000000000 --- a/Task/Miller-Rabin-primality-test/Standard-ML/miller-rabin-primality-test.ml +++ /dev/null @@ -1,49 +0,0 @@ -open LargeInt; - -val mr_iterations = Int.toLarge 20; -val rng = Random.rand (557216670, 13504100); (* arbitrary pair to seed RNG *) - -fun expmod base 0 m = 1 - | expmod base exp m = - if exp mod 2 = 0 - then let val rt = expmod base (exp div 2) m; - val sq = (rt*rt) mod m - in if sq = 1 - andalso rt <> 1 (* ignore the two *) - andalso rt <> (m-1) (* 'trivial' roots *) - then 0 - else sq - end - else (base*(expmod base (exp-1) m)) mod m; - -(* arbitrary precision random number [0,n) *) -fun rand n = - let val base = Int.toLarge(valOf Int.maxInt)+1; - fun step r lim = - if lim < n then step (Int.toLarge(Random.randNat rng) + r*base) (lim*base) - else r mod n - in step 0 1 end; - -fun miller_rabin n = - let fun trial n 0 = true - | trial n t = let val a = 1+rand(n-1) - in (expmod a (n-1) n) = 1 - andalso trial n (t-1) - end - in trial n mr_iterations end; - -fun trylist label lst = (label, ListPair.zip (lst, map miller_rabin lst)); - -trylist "test the first six Carmichael numbers" - [561, 1105, 1729, 2465, 2821, 6601]; - -trylist "test some known primes" - [7369, 7393, 7411, 27367, 27397, 27407]; - -(* find ten random 30 digit primes (according to Miller-Rabin) *) -let fun findPrime trials = let val t = trials+1; - val n = 2*rand(500000000000000000000000000000)+1 - in if miller_rabin n - then (n,t) - else findPrime t end -in List.tabulate (10, fn e => findPrime 0) end; diff --git a/Task/Miller-Rabin-primality-test/Swift/miller-rabin-primality-test.swift b/Task/Miller-Rabin-primality-test/Swift/miller-rabin-primality-test.swift deleted file mode 100644 index 78b8588519..0000000000 --- a/Task/Miller-Rabin-primality-test/Swift/miller-rabin-primality-test.swift +++ /dev/null @@ -1,37 +0,0 @@ -import BigInt - -private let numTrails = 5 - -func isPrime(_ n: BigInt) -> Bool { - guard n >= 2 else { fatalError() } - guard n != 2 else { return true } - guard n % 2 != 0 else { return false } - - var s = 0 - var d = n - 1 - - while true { - let (quo, rem) = (d / 2, d % 2) - - guard rem != 1 else { break } - - s += 1 - d = quo - } - - func tryComposite(_ a: BigInt) -> Bool { - guard a.power(d, modulus: n) != 1 else { return false } - - for i in 0.. 0} { - incr k -1 - set a [expr {2 + int(rand()*($n - 4))}] - set x [expr {($a ** $d) % $n}] - if {$x == 1 || $x == $n - 1} continue - for {set r 1} {$r < $s} {incr r} { - set x [expr {($x ** 2) % $n}] - if {$x == 1} {return false} - if {$x == $n - 1} break - } - if {$x != $n-1} {return false} - } - return true -} - -for {set i 1} {$i < 1000} {incr i} { - if {[miller_rabin $i 10]} { - puts $i - } -} 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 deleted file mode 100644 index 0190c9111c..0000000000 --- a/Task/Miller-Rabin-primality-test/Wren/miller-rabin-primality-test.wren +++ /dev/null @@ -1,17 +0,0 @@ -import "./big" for BigInt - -var iters = 10 -// find all primes < 100 -System.print("The following numbers less than 100 are prime:") -System.write("2 ") -for (i in 3..99) { - if (BigInt.new(i).isProbablePrime(iters)) System.write("%(i) ") -} -System.print("\n") -var bia = [ - BigInt.new("4547337172376300111955330758342147474062293202868155909489"), - BigInt.new("4547337172376300111955330758342147474062293202868155909393") -] -for (bi in bia) { - System.print("%(bi) is %(bi.isProbablePrime(iters) ? "probably prime" : "composite")") -} diff --git a/Task/Miller-Rabin-primality-test/Zkl/miller-rabin-primality-test.zkl b/Task/Miller-Rabin-primality-test/Zkl/miller-rabin-primality-test.zkl deleted file mode 100644 index 1038f1a6c5..0000000000 --- a/Task/Miller-Rabin-primality-test/Zkl/miller-rabin-primality-test.zkl +++ /dev/null @@ -1,5 +0,0 @@ -zkl: var BN=Import("zklBigNum"); -zkl: BN("4547337172376300111955330758342147474062293202868155909489").probablyPrime() -True -zkl: BN("4547337172376300111955330758342147474062293202868155909393").probablyPrime() -False diff --git a/Task/Mind-boggling-card-trick/Ada/mind-boggling-card-trick.adb b/Task/Mind-boggling-card-trick/Ada/mind-boggling-card-trick.adb new file mode 100644 index 0000000000..afc0404d1f --- /dev/null +++ b/Task/Mind-boggling-card-trick/Ada/mind-boggling-card-trick.adb @@ -0,0 +1,100 @@ +-- Check the "Mind boggling card trick" +-- J. Carter 2024 May +-- Uses the PragmAda Reusable Components (https://github.com/jrcarter/PragmARC) + +with Ada.Text_IO; +with Ada.Numerics.Discrete_Random; +with PragmARC.Cards.Decks.US; +with PragmARC.Cards.US; + +procedure Card_Trick is + package Cards renames PragmARC.Cards.US; + package Decks renames PragmARC.Cards.Decks.US; + + function Is_Red (Card : in Cards.Card_Info) return Boolean is + (Card.Suit in Cards.Diamond | Cards.Heart); + + function Correct return Boolean; + -- Performs the trick and returns True if the assertion that 'The number of black cards in the "black" pile equals the number + -- of red cards in the "red" pile' holds; False if it does not + + function Correct return Boolean is + function Num_Red (Deck : in Decks.Deck_52) return Natural; + -- Returns the number of red cards in Deck + + function Num_Black (Deck : in Decks.Deck_52) return Natural; + -- Returns the number of black cards in Deck + + function Num_Red (Deck : in Decks.Deck_52) return Natural is + Result : Natural := 0; + begin -- Num_Red + Count : for I in 1 .. Deck.Size loop + if Is_Red (Deck.Value (I) ) then + Result := Result + 1; + end if; + end loop Count; + + return Result; + end Num_Red; + + function Num_Black (Deck : in Decks.Deck_52) return Natural is + (Deck.Size - Num_Red (Deck) ); + + Hand : Decks.Deck_52; + Red : Decks.Deck_52; + Black : Decks.Deck_52; + Card : Cards.Card_Info; + begin -- Correct + Decks.Standard_Deck (Item => Hand); + Hand.Shuffle; + + All_Cards : loop + exit All_Cards when Hand.Is_Empty; + + Hand.Deal (To => Card); + + if Is_Red (Card) then + Hand.Deal (To => Card); + Red.Add (Item => Card); + else + Hand.Deal (To => Card); + Black.Add (Item => Card); + end if; + end loop All_Cards; + + Swap : declare + Number : constant Natural := Integer'Min (Red.Size, Black.Size) - 1; + + subtype Bunch_Value is Integer range 1 .. Number; + + package Random is new Ada.Numerics.Discrete_Random (Result_Subtype => Bunch_Value); + + Gen : Random.Generator; + Bunch : Bunch_Value; + begin -- Swap + Random.Reset (Gen => Gen); + Bunch := Random.Random (Gen); + + One_Bunch : for I in 1 .. Bunch loop + Red.Deal (To => Card); + Black.Add (Item => Card); + Black.Deal (To => Card); + Red.Add (Item => Card); + end loop One_Bunch; + + return Num_Red (Red) = Num_Black (Black); + end Swap; + end Correct; + + Total : constant := 10_000; + + Good : Natural := 0; +begin -- Card_Trick + Check_All : for I in 1 .. Total loop + if Correct then + Good := Good + 1; + end if; + end loop Check_All; + + Ada.Text_IO.Put_Line (Item => Good'Image & " correct out of" & Total'Image & " tries"); +end Card_Trick; diff --git a/Task/Mind-boggling-card-trick/Crystal/mind-boggling-card-trick.crystal b/Task/Mind-boggling-card-trick/Crystal/mind-boggling-card-trick.cr similarity index 100% rename from Task/Mind-boggling-card-trick/Crystal/mind-boggling-card-trick.crystal rename to Task/Mind-boggling-card-trick/Crystal/mind-boggling-card-trick.cr diff --git a/Task/Mind-boggling-card-trick/EasyLang/mind-boggling-card-trick.easy b/Task/Mind-boggling-card-trick/EasyLang/mind-boggling-card-trick.easy index f044bb5cb2..26e8a4f7d0 100644 --- a/Task/Mind-boggling-card-trick/EasyLang/mind-boggling-card-trick.easy +++ b/Task/Mind-boggling-card-trick/EasyLang/mind-boggling-card-trick.easy @@ -1,13 +1,11 @@ -proc shuffle . a[] . +proc shuffle &a[] . for i = len a[] downto 2 - r = randint i + r = random 1 i swap a[r] a[i] . . func$ a2str a[] . - for v in a[] - r$ &= strchar v & " " - . + for v in a[] : r$ &= strchar v & " " return r$ . R = strcode "R" @@ -30,15 +28,11 @@ print "After dealing the cards the state of the stacks is:" print " Red : " & a2str red[] print " Black : " & a2str black[] print " Discard: " & a2str discard[] -for i to len red[] - rp[] &= i -. -for i to len black[] - bp[] &= i -. +for i to len red[] : rp[] &= i +for i to len black[] : bp[] &= i shuffle rp[] shuffle bp[] -n = randint lower len red[] len black[] +n = random 1 lower len red[] len black[] len rp[] n len bp[] n # @@ -52,15 +46,9 @@ print "After swapping " & n & " cards the state of the stacks is:" print " Red : " & a2str red[] print " Black : " & a2str black[] # -for c in red[] - red += if c = R -. -for c in black[] - black += if c = B -. +for c in red[] : red += if c = R +for c in black[] : black += if c = B print "" print "The number of red cards in the red stack = " & red print "The number of black cards in the black stack = " & black -if red = black - print "So the asssertion is correct!" -. +if red = black : print "So the asssertion is correct!" diff --git a/Task/Mind-boggling-card-trick/Fortran/mind-boggling-card-trick.f b/Task/Mind-boggling-card-trick/Fortran/mind-boggling-card-trick.f new file mode 100644 index 0000000000..c952cce9b3 --- /dev/null +++ b/Task/Mind-boggling-card-trick/Fortran/mind-boggling-card-trick.f @@ -0,0 +1,217 @@ +! Mind boggling card trick +! tested with Intel ifx (IFX) 2025.2.1 20250806 on Kubuntu 25.10 +! GNU Fortran (Ubuntu 15.2.0-4ubuntu4) 15.2.0 on Kubuntu 25.10 +! VSI Fortran x86-64 V8.7-001 on OpenVMS x86_64 V9.2-3 +! No Non-standard features used, should compile on any fairly recent Fortran. +! U.B., February 2026 +!========================================================================================= +program CardTrick + +implicit none + +integer, dimension(52) :: Cards ! The original deck of 52 cards +integer, dimension(52) :: Reds, Blacks ! THe two piles where the magician deals half of the deck +integer, dimension(52) :: RedBunch, BlackBunch ! THe two bunches with X cards to be exchanged between the two piles + +! Helpers +integer :: i, j ! Do Loop indices +integer :: ir, ib ! Indices into the Red and the Black Piles +integer :: x ! The number of cards to exchange between the piles +integer :: ic, c ! Position and value of a single cards (used at several occasions) +integer :: irb, ibb ! Index into the Red and the Black exchange Bunch +integer :: countRedinRed, countBlackinBlack, unusedCtr ! Count red and red cards in the final piles: reds in red, blacks in blacks. One dummy. + +! Note on the Data Model: +! Numbers 1...52 represent 52 cards of the deck +! By definition: we treat odd numbers are RED, and even numbers are BLACK. +! The Values of the cards (e.g. Ace of Hearts) is not interesting here. + +! Initialize random number generator once for the entire run-time of the program and all test cases +call random_seed() + + +! The following steps simulate the card trick. +! +! Create a common deck of cards of 52 cards (which are half red, half black). +! +do i=1,52 + Cards(i) = i + Reds(i) = 0 + Blacks(i) = 0 +enddo + +! 2. Give the pack a good shuffle. +call sattolo_cycle (Cards, 52) ! Give the pack a good shuffle. + +! Deal from the shuffled deck, you'll be creating three piles. +! --------------------------------------------------------------- +ir = 0 +ib = 0 + +do i=1, 51, 2 ! Look at every second card + if (isRed (Cards(i))) then ! If this card is RED + ir = ir + 1 ! then add the next card (unseen) to the "red" pile. + Reds(ir) = Cards(i+1) + else ! If this card is BLACK + ib = ib + 1 ! then add the next card (unseen) to the "black" pile. + Blacks (ib) = Cards(i+1) + endif +end do ! Repeat the above for the rest of the shuffled deck. + +! Choose a random number (call it X) that will be used to swap cards from the "red" and "black" piles. +x = randominInterval (0,min(ir-1, ib-1)) ! x must be smaller than the smaller number of reds ir and blacks ib, and yes, also 0 is an option. + +irb=0 +ibb=0 +do i=1,X ! Randomly choose X cards ... + do ! ... from the "red" pile (unseen), let's call this the "red" bunch. + ic = randominInterval (1, ir) + c = Reds (ic) + if (c .eq. 0 .or. alreadyKnown (RedBunch, c, ir) ) cycle ! Avoid selecting a card for a second time + exit ! OK, can use this. + enddo + irb = irb + 1 + RedBunch (irb) = c ! Add the card to the red bunch + Reds (ic) = 0 ! ... and Remove it from the Red pile + + do ! ... from the "black" pile (unseen), let's call this the "black" bunch. + ic = randominInterval (1, ib) + c = blacks (ic) + if (c .eq. 0 .or. alreadyKnown (blackBunch, c, ib) ) cycle + exit + enddo + ibb = ibb + 1 + BlackBunch (ibb) = c ! Add the card to the black bunch + Blacks (ic) = 0 ! Remove from the Red pile +enddo + +! Put the "red" bunch into the "black" pile. +do i=1, irb + do j=1, 52 ! Find an empty location in the Black pile + if (Blacks(j) .eq. 0) then + Blacks(j) = redBunch (i) + exit + endif + end do +enddo +! Put the "black" bunch into the "red" pile. +do i=1, ibb + do j=1, 52 ! Find an empty location in the Red pile + if (Reds(j) .eq. 0) then + Reds(j) = BlackBunch (i) + exit + endif + end do +enddo + +call count (Reds, ir, countRedinRed, unusedCtr) +write ( *, '(A, i2, A, i2, A)') 'In the red pile there are ', countRedinRed , ' red cards and ', unusedCtr, ' black cards' +call count (Blacks, ib, unusedCtr, countBlackinBlack) +write ( *, '(A, i2, A, i2, A)') 'In the black pile there are ', unusedCtr , ' red cards and ', countBlackinBlack, ' black cards' + +if (countBlackinBlack .eq. countRedinRed) then + write (*, '(A, i2, a, i2, a)') 'Approved: the number of ' , countBlackinBlack , ' black cards in the "black" pile equals the number ', & + countBlackinBlack, ' of red cards in the "red" pile.' +else + ! It has been proven that the twoo numbers always are equal, so we won't come her. Anyway: + write (*, '(A, i2, a, i2, a)') 'Not approved: the number of ' , countBlackinBlack , ' black cards in the "black" pile is not equal to the number ', & + countBlackinBlack, ' of red cards in the "red" pile.' + +endif +contains + + +! ====================================================== +! Check if a card c is already contained in card bunch B +! ====================================================== +function alreadyKnown (B,c,n) result (yesitis) +integer, intent(in) :: n, C +integer, dimension(n), intent(in) :: B +logical :: yesitis +integer :: ii +do ii = 1, N ! Loop until found or all cards in B are checked. + if (B(ii) .eq. c) then + yesitis = .true. + return + endif +enddo +yesitis = .false. +end function alreadyKnown + +! ================================================ +! A Card is red if its number is not 0 and its odd +! ================================================ +function isRed (t) result (itis) +integer, intent(in) :: t +logical :: itis +itis = t .ne. 0 .and. mod(t,2) .ne. 0 ! odd numbers are RED. +end function isred + +! =============================================================== +! A Card is black if its number is not 0 and its even +! Note: +! The "Not 0" condition makes it different from (.not. isRed(...)) +! ================================================================ +function isBlack (t) result (itis) +integer, intent(in) :: t +logical :: itis +itis = t .ne. 0 .and. mod(t,2) .eq. 0 ! odd numbers are RED, even is BLACK +end function isBlack + + +! ================================================ +! Count black and red cards in a deck a of n cards. +! ================================================ +subroutine count (a, n, red, black) + +integer , dimension(n), intent(in) :: a +integer, intent(in) :: n +integer, intent(out) :: red, black +integer :: ii + +red=0 +black=0 +do ii=1,N + if (isred (a(ii)) ) then + red = red + 1 + else if (isBlack (a(ii))) then + black = black + 1 + endif +end do + +end subroutine count + + +!==================================== +! shuffle using the Sattolo algorithm +!==================================== +subroutine sattolo_cycle (a, d) +integer, intent(in) :: d +integer, dimension(d) , intent (inout) :: a ! The array to shuffle + +integer :: tmp ! for swapping single elements +integer :: j, k, l ! Helper variables: indices into the array, array's length + +l = size (a) +do j = l, 1, -1 ! For all letters from end down to begin + k = randominInterval (1, j-1) ! Select random lnumber between 1 and j-1 + tmp = a(j) ! then swap letter at pos j with letter at pos k + a (j) = a (k) + a(k) = tmp +end do + +end subroutine sattolo_cycle + +! =========================================================== +! Generate random number between @lo and @hi (inclusive) +! Assume Random Number Generator has been initialized before. +! =========================================================== +function randominInterval (lo, hi) result (r) +integer, intent(in) :: lo, hi ! the interval +integer :: r ! resultant (pseudo-)random number +real :: rnd ! Fortran random number generator generates float values +call random_number (rnd) ! 0. <= rnd < 1. +r = lo + FLOOR((hi+1-lo)*rnd) ! We want to choose one between [lo,hi]: add +1 to possibly include "hi". +end function randominInterval + +end program CardTrick diff --git a/Task/Mind-boggling-card-trick/Jq/mind-boggling-card-trick.jq b/Task/Mind-boggling-card-trick/Jq/mind-boggling-card-trick.jq new file mode 100644 index 0000000000..4a6717d63f --- /dev/null +++ b/Task/Mind-boggling-card-trick/Jq/mind-boggling-card-trick.jq @@ -0,0 +1,105 @@ +### Generic utilities +def count(s): reduce s as $x (0; . + 1); + +def lpad($len): tostring | ($len - length) as $l | (" " * $l) + .; + + +### Pseuo-random numbers + +# Output: a prn in range(0;$n) where $n is `.` +def prn: + if . == 1 then 0 + else . as $n + | ([1, (($n-1)|tostring|length)]|max) as $w + | [limit($w; inputs)] | join("") | tonumber + | if . < $n then . else ($n | prn) end + end; + +def sample: + if length == 0 # e.g. null or [] + then null + else .[length|prn] + end; + +def knuthShuffle: + length as $n + | if $n <= 1 then . + else {i: $n, a: .} + | until(.i == 0; + .i += -1 + | (.i + 1 | prn) as $j + | .a[.i] as $t + | .a[.i] = .a[$j] + | .a[$j] = $t) + | .a + end; + + +### Cards + +def R: "R"; # 82 ASCII +def B: "B"; # 66 ASCII + +# Create deck, half red, half black and shuffle it. +def deck: + ([range(0;26)|R] + [range(0;26)|B]) | knuthShuffle; + +# Deal from `deck` into three stacks: {black, red, discard} +def deal: + deck as $deck + | reduce range(0; 51; 2) as $i (.; + if $deck[$i] == B + then .black += [$deck[$i+1]] + else .red += [$deck[$i+1]] + end + | .discard += [$deck[$i]] ); + +def proceed: + def p: join(" "); + + (.red|length) as $lr + | (.black|length) as $lb + | (.discard|length) as $ld + + | def displayStacks($discard): + " Red : \($lr|lpad(2)) cards -> \(.red|p)", + " Black : \($lb|lpad(2)) cards -> \(.black|p)", + (select($discard) + | " Discard: \($ld) cards -> \(.discard|p)") ; + + # Input: {red, black} + def swap($n): + . + { rp: ([range(0; $lr)] | knuthShuffle[0:$n] ), + bp: ([range(0; $lb)] | knuthShuffle[0:$n]) } + | reduce range(0;$n) as $i (.; + .red[.rp[$i]] as $t + | .red[.rp[$i]] = .black[.bp[$i]] + | .black[.bp[$i]] = $t); + + def epilog: + # Check that the number of black cards in the black stack equals + # the number of red cards in the red stack: + count(select(.red[] == R)) as $rcount + | count(select(.black[] == B)) as $bcount + | "\nThe number of red cards in the red stack = \($rcount)", + "The number of black cards in the black stack = \($bcount)", + if $rcount == $bcount + then "So the assertion is correct!" + else "So the assertion is incorrect!" + end; + + "After dealing the cards, the stacks are as follows:", + displayStacks(true), + # Swap the same, random, number of cards between the red and black stacks. + ( (if $lr < $lb then $lr else $lb end) as $min + | (($min - 1|prn) + 1) as $n + | swap($n) + | "\n\($n) card(s) are to be swapped.", + "The respective zero-based indices of the cards to be swapped are:", + " Red : \(.rp|map(lpad(3))|p)", + " Black : \(.bp|map(lpad(3))|p)", + "\nAfter swapping, the red and black stacks are as follows:", + displayStacks(false), + epilog ) ; + +deal | proceed diff --git a/Task/Mind-boggling-card-trick/Julia/mind-boggling-card-trick.julia b/Task/Mind-boggling-card-trick/Julia/mind-boggling-card-trick.jl similarity index 100% rename from Task/Mind-boggling-card-trick/Julia/mind-boggling-card-trick.julia rename to Task/Mind-boggling-card-trick/Julia/mind-boggling-card-trick.jl diff --git a/Task/Mind-boggling-card-trick/Kotlin/mind-boggling-card-trick.kotlin b/Task/Mind-boggling-card-trick/Kotlin/mind-boggling-card-trick.kts similarity index 100% rename from Task/Mind-boggling-card-trick/Kotlin/mind-boggling-card-trick.kotlin rename to Task/Mind-boggling-card-trick/Kotlin/mind-boggling-card-trick.kts diff --git a/Task/Mind-boggling-card-trick/Phix/mind-boggling-card-trick.phix b/Task/Mind-boggling-card-trick/Phix/mind-boggling-card-trick.phix index 02957805b3..0796efec55 100644 --- a/Task/Mind-boggling-card-trick/Phix/mind-boggling-card-trick.phix +++ b/Task/Mind-boggling-card-trick/Phix/mind-boggling-card-trick.phix @@ -1,36 +1,34 @@ -(phixonline)--> - with javascript_semantics - constant n = 52, - pack = shuffle(repeat('r',n/2)&repeat('b',n/2)) +with javascript_semantics +constant n = 52, + pack = shuffle(repeat('r',n/2)&repeat('b',n/2)) - string black = "", red = "", discard = "" - for i=1 to length(pack) by 2 do - integer top = pack[i], - next = pack[i+1] - if top=='b' then - black &= next - else - red &= next - end if - discard &= top - end for - black = shuffle(black); red = shuffle(red) -- (optional) - --printf(1,"Discards : %s\n",{discard}) +string black = "", red = "", discard = "" +for i=1 to length(pack) by 2 do + integer top = pack[i], + next = pack[i+1] + if top=='b' then + black &= next + else + red &= next + end if + discard &= top +end for +black = shuffle(black); red = shuffle(red) -- (optional) +--printf(1,"Discards : %s\n",{discard}) - printf(1,"Reds : %s\nBlacks : %s\n\n",{red,black}) +printf(1,"Reds : %s\nBlacks : %s\n\n",{red,black}) - integer lb = length(black), lr = length(red), - ns = rand(min(lb,lr)) - printf(1,"Swap %d cards:\n\n", ns) - string b1ns = black[1..ns], - r1ns = red[1..ns] - black[1..ns] = r1ns - red[1..ns] = b1ns +integer lb = length(black), lr = length(red), + ns = rand(min(lb,lr)) +printf(1,"Swap %d cards:\n\n", ns) +string b1ns = black[1..ns], + r1ns = red[1..ns] +black[1..ns] = r1ns +red[1..ns] = b1ns - printf(1,"Reds : %s\nBlacks : %s\n\n",{red,black}) +printf(1,"Reds : %s\nBlacks : %s\n\n",{red,black}) - integer nb = sum(sq_eq(black,'b')), - nr = sum(sq_eq(red,'r')) - string correct = iff(nr==nb?"correct":"**INCORRECT**") - printf(1,"%d r in red, %d b in black - assertion %s\n",{nr,nb,correct}) - n ) + + [] 1 + 40 times + [ 1 from + [ dup dup index * + digitsum = if + [ index swap end ] ] + 1+ dip join ] + drop echo diff --git a/Task/Minimum-positive-multiple-in-base-10-using-only-0-and-1/Fortran/minimum-positive-multiple-in-base-10-using-only-0-and-1.f b/Task/Minimum-positive-multiple-in-base-10-using-only-0-and-1/Fortran/minimum-positive-multiple-in-base-10-using-only-0-and-1.f new file mode 100644 index 0000000000..88f7f484bd --- /dev/null +++ b/Task/Minimum-positive-multiple-in-base-10-using-only-0-and-1/Fortran/minimum-positive-multiple-in-base-10-using-only-0-and-1.f @@ -0,0 +1,126 @@ +! +! Minimum positive multiple in base 10 using only 0 and 1 +! tested with GNU gfortran (Ubuntu 15.2.0-4ubuntu4) 15.2.0 on Kubuntu 25.10 +! +! U.B., March 2026 +! +program MinPosMul +implicit none + +integer, parameter :: i128 = 16 + +integer (kind=i128) :: i + +! 1-10 (inclusive) +do i = 1, 10 + call test(i) +enddo + +! 95-105 (inclusive) +do i = 95, 105 + call test(i) +enddo + +call test(297_i128) +call test(576_i128) +call test(594_i128) ! needs a larger number type (64 bits signed) +call test(891_i128) +call test(909_i128) +call test(999_i128) ! needs a larger number type (87 bits signed) + +! optional +call test(1998_i128) +call test(2079_i128) +call test(2251_i128) +call test(2277_i128) + +! stretch +call test(2439_i128) +call test(2997_i128) +call test(4878_i128) + +contains + +subroutine test (n) + +integer (kind=i128), intent(in) :: n +integer (kind=i128) :: mult + +mult = mpm(n) +if (mult .gt. 0) then + call print128(n) + write (*,'(" * ")', advance='no') + call print128(mult) + write (*,'(" = ")', advance='no') + call print128(n * mult) + write (*,*) +else + call print128(n) + write (*,'("(no solution)")') +endif + +end subroutine test + + + +subroutine print128(n) +integer (kind=i128), intent(in) :: n +write (*,'(i0)', advance='no') n +end subroutine print128 + + +function mpm (n) result (returnvalue) +integer (kind=i128), intent(in) ::n +integer (kind=i128) :: returnvalue +integer (kind=i128), dimension(:), allocatable :: L +integer (kind=i128) ::m, k, r, j; + +if (n .eq. 1) then + returnvalue = 1 + return +endif + +allocate (L(0:(n * n)-1)) +L=0 + +L(0) = 1 +L(1) = 1 +m = 0 +do + m=m+1 + if (L((m - 1) * n + imod (-(10_i128** m), n)) .eq. 1) then + exit + endif + L(m * n) = 1 + do k = 1, n-1 + L(m * n + k) = max (L((m - 1) * n + k), L((m - 1) * n + imod(k - 10_i128** m, n)) ) + enddo +enddo + +r = 10_i128 ** m +k = imod (-r, n) + +do j = m - 1, 1, -1 + if (L((j - 1) * n + k) .eq. 0) then + r = r + 10_i128 **j + k = imod(k - 10_i128 ** j, n) + end if +end do + +if (k .eq. 1) then + r=r+1 +endif +returnvalue = r / n + +deallocate (L) +end function mpm + +pure function imod (m,n) result (returnvalue) +integer (kind=i128), intent(in) :: m, n +integer (kind=i128) :: returnvalue + +returnvalue = mod(m,n) +if (returnvalue .lt. 0) returnvalue = returnvalue + n +end function imod + +end program MinPosMul diff --git a/Task/Minimum-positive-multiple-in-base-10-using-only-0-and-1/Julia/minimum-positive-multiple-in-base-10-using-only-0-and-1-1.julia b/Task/Minimum-positive-multiple-in-base-10-using-only-0-and-1/Julia/minimum-positive-multiple-in-base-10-using-only-0-and-1-1.jl similarity index 100% rename from Task/Minimum-positive-multiple-in-base-10-using-only-0-and-1/Julia/minimum-positive-multiple-in-base-10-using-only-0-and-1-1.julia rename to Task/Minimum-positive-multiple-in-base-10-using-only-0-and-1/Julia/minimum-positive-multiple-in-base-10-using-only-0-and-1-1.jl diff --git a/Task/Minimum-positive-multiple-in-base-10-using-only-0-and-1/Julia/minimum-positive-multiple-in-base-10-using-only-0-and-1-2.julia b/Task/Minimum-positive-multiple-in-base-10-using-only-0-and-1/Julia/minimum-positive-multiple-in-base-10-using-only-0-and-1-2.jl similarity index 100% rename from Task/Minimum-positive-multiple-in-base-10-using-only-0-and-1/Julia/minimum-positive-multiple-in-base-10-using-only-0-and-1-2.julia rename to Task/Minimum-positive-multiple-in-base-10-using-only-0-and-1/Julia/minimum-positive-multiple-in-base-10-using-only-0-and-1-2.jl diff --git a/Task/Minimum-positive-multiple-in-base-10-using-only-0-and-1/Kotlin/minimum-positive-multiple-in-base-10-using-only-0-and-1.kotlin b/Task/Minimum-positive-multiple-in-base-10-using-only-0-and-1/Kotlin/minimum-positive-multiple-in-base-10-using-only-0-and-1.kts similarity index 100% rename from Task/Minimum-positive-multiple-in-base-10-using-only-0-and-1/Kotlin/minimum-positive-multiple-in-base-10-using-only-0-and-1.kotlin rename to Task/Minimum-positive-multiple-in-base-10-using-only-0-and-1/Kotlin/minimum-positive-multiple-in-base-10-using-only-0-and-1.kts diff --git a/Task/Minkowski-question-mark-function/EasyLang/minkowski-question-mark-function.easy b/Task/Minkowski-question-mark-function/EasyLang/minkowski-question-mark-function.easy new file mode 100644 index 0000000000..2e130245b1 --- /dev/null +++ b/Task/Minkowski-question-mark-function/EasyLang/minkowski-question-mark-function.easy @@ -0,0 +1,72 @@ +func minkowski x . + if x > 1 or x < 0 : return floor x + minkowski (x - floor x) + p = floor x + q = 1 + r = p + 1 + s = 1 + d = 1 + y = p + while 1 = 1 + d = d / 2 + if y + d = y : break 1 + m = p + r + if m < 0 or p < 0 : break 1 + n = q + s + if n < 0 : break 1 + if x < m / n + r = m + s = n + else + y = y + d + p = m + q = n + . + . + return y + d +. +Maxiter = 151 +func minkowski_inv x . + if x > 1 or x < 0 : return floor x + minkowski_inv (x - floor x) + if x = 1 or x = 0 : return x + curr = 0 + count = 1 + contfrac[] &= 0 + while 1 = 1 + x *= 2 + if curr = 0 + if x < 1 + count += 1 + else + i += 1 + contfrac[] &= 0 + contfrac[i] = count + count = 1 + curr = 1 + x -= 1 + . + else + if x > 1 + count += 1 + x -= 1 + else + i += 1 + contfrac[] &= 0 + contfrac[i] = count + count = 1 + curr = 0 + if x = floor x + contfrac[i + 1] = count + break 1 + . + if i = Maxiter : break 1 + . + . + . + ret = 1 / contfrac[i + 1] + for j = i downto 1 : ret = contfrac[j] + 1 / ret + return 1 / ret +. +numfmt 0 16 +print minkowski (0.5 * (1 + sqrt 5)) & " " & 5 / 3 +print minkowski_inv (-5 / 9) & " " & (sqrt 13 - 7) / 6 +print minkowski minkowski_inv 0.718281828 & " " & minkowski_inv minkowski 0.1213141516171819 diff --git a/Task/Minkowski-question-mark-function/Julia/minkowski-question-mark-function.jl b/Task/Minkowski-question-mark-function/Julia/minkowski-question-mark-function.jl new file mode 100644 index 0000000000..528d3cb50a --- /dev/null +++ b/Task/Minkowski-question-mark-function/Julia/minkowski-question-mark-function.jl @@ -0,0 +1,28 @@ +function questionmark(x) + y, p = fldmod(x, 1) + q, d = 1 - p, .5 + while y + d > y + p < q ? (q -= p) : (p -= q; y += d) + d /= 2 + end + y +end + +function questionmark_inv(x) + y, bits = fldmod(x, 1) + lo, hi = [0, 1], [1, 1] + while bits ≉ 0 + bits, bit = modf(2bits) + bit ≥ 1 ? (lo .+= hi) : (hi .+= lo) + end + y + /(lo...) +end + +x, y = 0.7182818281828, 0.1213141516171819 +for (a, b) ∈ [ + (5/3, questionmark((1 + √5)/2)), + ((√13-7)/6, questionmark_inv(-5/9)), + (x, questionmark_inv(questionmark(x))), + (y, questionmark(questionmark_inv(y)))] + println(a, a ≈ b ? " ≈ " : " != ", b) +end diff --git a/Task/Minkowski-question-mark-function/Julia/minkowski-question-mark-function.julia b/Task/Minkowski-question-mark-function/Julia/minkowski-question-mark-function.julia deleted file mode 100644 index e0be9c630b..0000000000 --- a/Task/Minkowski-question-mark-function/Julia/minkowski-question-mark-function.julia +++ /dev/null @@ -1,28 +0,0 @@ -function questionmark(x) - y, p = fldmod(x, 1) - q, d = 1 - p, .5 - while y + d > y - p < q ? (q -= p) : (p -= q; y += d) - d /= 2 - end - y -end - -function questionmark_inv(x) - y, bits = fldmod(x, 1) - lo, hi = [0, 1], [1, 1] - while (y + /(lo...)) < (y + /(hi...)) - bit, bits = fldmod(2bits, 1) - bit > 0 ? (lo .+= hi) : (hi .+= lo) - end - y + /(lo...) -end - -x, y = 0.7182818281828, 0.1213141516171819 -for (a, b) ∈ [ - (5/3, questionmark((1 + √5)/2)), - ((√13-7)/6, questionmark_inv(-5/9)), - (x, questionmark_inv(questionmark(x))), - (y, questionmark(questionmark_inv(y)))] - println(a, a ≈ b ? " ≈ " : " != ", b) -end diff --git a/Task/Modified-random-distribution/ALGOL-68/modified-random-distribution.alg b/Task/Modified-random-distribution/ALGOL-68/modified-random-distribution.alg index f87bdbb776..9fd0fc9832 100644 --- a/Task/Modified-random-distribution/ALGOL-68/modified-random-distribution.alg +++ b/Task/Modified-random-distribution/ALGOL-68/modified-random-distribution.alg @@ -2,13 +2,13 @@ BEGIN # Modified random distribution - translation of the Wren sample # next random; # initialise the random number generator # - PROC rng = ( PROC(REAL)REAL modifier )REAL: + PROC rng = ( PROC(REAL)REAL modifier fn )REAL: BEGIN REAL r1, r2; WHILE r1 := random; r2 := random; - r2 >= modifier( r1 ) + r2 >= modifier fn( r1 ) DO SKIP OD; r1 END # rng # ; @@ -21,7 +21,7 @@ BEGIN # Modified random distribution - translation of the Wren sample # 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 + FROM 0 TO n DO bins[ ENTIER ( rng( modifier ) / bin size ) ] +:= 1 OD; diff --git a/Task/Modified-random-distribution/Ada/modified-random-distribution.ada b/Task/Modified-random-distribution/Ada/modified-random-distribution.adb similarity index 100% rename from Task/Modified-random-distribution/Ada/modified-random-distribution.ada rename to Task/Modified-random-distribution/Ada/modified-random-distribution.adb diff --git a/Task/Modified-random-distribution/EasyLang/modified-random-distribution.easy b/Task/Modified-random-distribution/EasyLang/modified-random-distribution.easy new file mode 100644 index 0000000000..a85ef51b21 --- /dev/null +++ b/Task/Modified-random-distribution/EasyLang/modified-random-distribution.easy @@ -0,0 +1,31 @@ +func$ rep c$ n . + for i to n : r$ &= c$ + return r$ +. +func modifier x . + if x < 0.5 : return 2 * (0.5 - x) + return 2 * (x - 0.5) +. +func rand . + repeat + r1 = randomf + r2 = randomf + until r2 < modifier r1 + . + return r1 +. +n = 100000 +nbins = 20 +histsz = 200 +binsz = 1 / nbins +len bins[] nbins +# +for i to n + rn = rand + bn = floor (rn / binsz) + bins[bn] += 1 +. +numfmt 4 0 +for i range0 nbins + print bins[i] & " " & rep "*" (bins[i] / histsz) +. diff --git a/Task/Modified-random-distribution/Fortran/modified-random-distribution.f b/Task/Modified-random-distribution/Fortran/modified-random-distribution.f new file mode 100644 index 0000000000..b31f426d7f --- /dev/null +++ b/Task/Modified-random-distribution/Fortran/modified-random-distribution.f @@ -0,0 +1,83 @@ +! Modified random distribution +! tested with Intel ifx (IFX) 2025.2.1 20250806 on Kubuntu 25.10 +! GNU gfortran (Ubuntu 15.2.0-4ubuntu4) 15.2.0 on Kubuntu 25.10 +! VSI Fortran x86-64 V8.7-001 on OpenVMS V9.2-3 +! U.B., March 2026 +! +program modrand +implicit none +integer, parameter :: DP=8 ! Reals hare Double PRecision here +integer, parameter :: NMAX=100000 ! Generate that many random numbers +integer, parameter :: nHist=21 ! Number of Histogram Channels +integer, parameter :: histMaxPoint = 80 ! Normalize maximum Histogram count to 80 chars width + +real(kind=DP), dimension(0:nHist) :: HLimits ! the upper limit of each Histogram channel +integer, dimension(nHist) :: Hist ! THe histogram channels + +integer :: ii, jj, ! loop indices +integer :: mv, nd ! maximum count in all histogram channels +real (kind=DP) :: r ! 1 generated random number + +call random_seed () ! Initialize random number generator + +do ii=0, nHist !Initialize Histogram limits + HLimits(ii) = real(ii,DP) / real(nHist, DP) +enddo +Hist = 0 + +do ii=1, NMAX ! Do the generation + call modifiedRandom (r) + do jj=1, nHist ! Find histogram channel + if (r .lt. HLimits (jj)) then + Hist(jj) = Hist(jj) + 1 + exit + endif + end do +end do + +! Display the histogram: Normalize such that maximum count would display as 80 '*' +mv = maxval(Hist) +write (*,'("---Range--- Count ")') +do ii=1, nHist + nd = histMaxPoint * real (hist(ii),DP) / real (mv ,DP) ! Number of stars to show + ! Top line + write (*,'(F4.2,"...",F4.2,4X,I5,3x)',advance='no') HLimits(ii-1), HLimits(ii), hist(ii) + + do jj=1,nd + write (*,'("*")', advance='no') + enddo + write (*,*) +enddo +write (*,'(/,"Total:", 7x,I7)') NMAX +contains + +! ======================================================================= +! returns r as modified randum value as described in the task description +! ======================================================================= +subroutine modifiedRandom (r) +real(kind=DP), intent(out) :: r +real (kind=DP) :: r1, r2 + +r = -1._DP +do while (r .lt. 0._DP) + call random_number (r1) + call random_number (r2) + if (r2 < modifier(r1)) r = r1 +end do +end subroutine modifiedRandom + +! ====================================================== +! The modifier function as shown in the task description +! ====================================================== +pure function modifier(x) result (returnvalue) +real (kind=DP), intent(in) :: x +real (kind=DP) :: returnvalue + +if (x .lt. 0.5_DP) then + returnvalue = 2.0_DP*(0.5_DP - x) +else + returnvalue = 2.0_DP*(x - 0.5_DP) +endif +end function modifier + +end program modrand diff --git a/Task/Modified-random-distribution/Jq/modified-random-distribution.jq b/Task/Modified-random-distribution/Jq/modified-random-distribution.jq new file mode 100644 index 0000000000..c095dfdc88 --- /dev/null +++ b/Task/Modified-random-distribution/Jq/modified-random-distribution.jq @@ -0,0 +1,50 @@ +# Output: a PRN (integer) in range(0; .) +def prn: + if . == 1 then 0 + else . as $n + | (($n-1)|tostring|length) as $w + | [limit($w; inputs)] | join("") | tonumber + | if . < $n then . else ($n | prn) end + end; + +def rgen: + 1000 | prn / 1000; + +# Modified random number generator. +# `modifier` should be a zero-arity filter +def rng(modifier): + {} + | until(.r1 and (.r2 < (.r1|modifier)); + .r1 = rgen + | .r2 = rgen ) + | .r1; + +def modifier: + if (. < 0.5) then 2 * (0.5 - .) + else 2 * (. - 0.5) + end; + +def N:100000; +def NUM_BINS: 20; +def HIST_CHAR: "■"; +def HIST_CHAR_SIZE: 500; +def binSize:1 / NUM_BINS; + +def task: + # tidy decimals + def round($ndec): pow(10;$ndec) as $p | . * $p | round / $p; + def zpad($len): tostring | ($len - length) as $l | . + ("0" * $l); + def r: if . == 0 then "0.00" else round(2) | zpad(4) end; + reduce range(0; N) as $i ([]; + rng(modifier) as $rn + | (($rn / binSize)|floor) as $bn + | .[$bn] += 1) + | {bins: .} + | "Modified random distribution with \(N) samples in range [0, 1):", + " Range Number of samples within that range", + (foreach range(0; NUM_BINS) as $i (.; + (HIST_CHAR * (((.bins[$i] // 0) / HIST_CHAR_SIZE) | round)) as $hist + | .emit = "\(binSize * $i|r) - \($hist) \(.bins[$i] // 0)" ) + | .emit); + +task diff --git a/Task/Modified-random-distribution/Julia/modified-random-distribution.julia b/Task/Modified-random-distribution/Julia/modified-random-distribution.jl similarity index 100% rename from Task/Modified-random-distribution/Julia/modified-random-distribution.julia rename to Task/Modified-random-distribution/Julia/modified-random-distribution.jl diff --git a/Task/Modified-random-distribution/M2000-Interpreter/modified-random-distribution.m2000 b/Task/Modified-random-distribution/M2000-Interpreter/modified-random-distribution.m2000 new file mode 100644 index 0000000000..1867306e6a --- /dev/null +++ b/Task/Modified-random-distribution/M2000-Interpreter/modified-random-distribution.m2000 @@ -0,0 +1,34 @@ +module Modified_random_distribution (f, m, bins){ + form 60, 32 + Cls 1, 0 + Report "Modified Random Distribution" + Cls 0, 1 + Cursor 0, 5 + T$="Range Istogram" + Print #f, T$ + Print T$ + double a[bins] + def modifier(x) = if(x < 0.5-> 1-2*x, 2*x -1) + for i=1 to m + while True: + random1 = rnd + random2 = rnd + if random2 < modifier(random1) then + answer = int(random1*bins) + a[answer]++ + exit + end if + end while + next + b=100 / bins + + for i=0 to bins-1 + L$=format$("{0:1:-4} - {1:1:-4} {2} {3}% ",i*b,(i+1)*b-.1, string$("*",a[i]/(m/bins)*20), round(a[i]/m*100,2)) + Print #f, L$ + Print L$ + next + } + // Ansi file / use for wide output for UTF16LE +Open "ModRandomDistr.txt" for output as #f +Modified_random_distribution f, 10000, 21 +close #f diff --git a/Task/Modified-random-distribution/PascalABC.NET/modified-random-distribution.pas b/Task/Modified-random-distribution/PascalABC.NET/modified-random-distribution.pas new file mode 100644 index 0000000000..b6242e5a36 --- /dev/null +++ b/Task/Modified-random-distribution/PascalABC.NET/modified-random-distribution.pas @@ -0,0 +1,21 @@ +function modifier(x: real) := if x < 0.5 then 2 * (0.5 - x) else 2 * (x - 0.5); + +function modrand(modifier: real-> real): sequence of real; +begin + repeat + var r := Random; + if Random < modifier(r) then yield r; + until false; +end; + +begin + var data := modrand(modifier).Take(100_000); + var bins := data.Select(x -> (20 * x).Floor) + .Sorted + .GroupBy(n -> n) + .Select(g -> g.Count); + + writeln('Bin Counts Histogram'); + foreach var counts in bins index i do + writeln(i / 20:2:2, counts:6, ': ', '■' * (counts div 125)); +end. diff --git a/Task/Modified-random-distribution/Pluto/modified-random-distribution.pluto b/Task/Modified-random-distribution/Pluto/modified-random-distribution.pluto new file mode 100644 index 0000000000..801891b9c4 --- /dev/null +++ b/Task/Modified-random-distribution/Pluto/modified-random-distribution.pluto @@ -0,0 +1,32 @@ +require "table2" +local fmt = require "fmt" + +local function rng(modifier) + while true do + local r1 = math.random() + local r2 = math.random() + if r2 < modifier(r1) then return r1 end + end +end + +local modifier = |x| -> (x < 0.5) ? 2 * (0.5 - x) : 2 * (x - 0.5) + +$define N = 100000 +$define NUM_BINS = 20 +$define HIST_CHAR = "■" +$define HIST_CHAR_SIZE = 125 + +local bins = table.rep(NUM_BINS, 0) +local bin_size = 1 / NUM_BINS +for i = 1, N do + local rn = rng(modifier) + local bn = rn // bin_size + bins[bn + 1] += 1 +end + +fmt.print($"Modified random distribution with %,s samples in range [0, 1):\n", N) +print(" Range Number of samples within that range") +for i = 0, NUM_BINS - 1 do + local hist = string.rep(HIST_CHAR, math.round(bins[i + 1] / HIST_CHAR_SIZE)) + fmt.print("%4.2f ..< %4.2f %s %,s", bin_size * i, bin_size * (i + 1), hist, bins[i + 1]) +end diff --git a/Task/Modified-random-distribution/Rust/modified-random-distribution.rust b/Task/Modified-random-distribution/Rust/modified-random-distribution.rs similarity index 100% rename from Task/Modified-random-distribution/Rust/modified-random-distribution.rust rename to Task/Modified-random-distribution/Rust/modified-random-distribution.rs diff --git a/Task/Modified-random-distribution/XPL0/modified-random-distribution.xpl0 b/Task/Modified-random-distribution/XPL0/modified-random-distribution.xpl0 new file mode 100644 index 0000000000..e6bcbd4ba3 --- /dev/null +++ b/Task/Modified-random-distribution/XPL0/modified-random-distribution.xpl0 @@ -0,0 +1,39 @@ +include xpllib; \for Print + +func real Modifier(X); +real X; +return if X < 0.5 then 2.*(0.5-X) else 2.*(X-0.5); + +func real RGen; +return float(Ran(1_000_000)) / 1e6; + +func real RNG; +real R1, R2; +[loop [R1:= RGen; + R2:= RGen; + if R2 < Modifier(R1) then + return R1; + ]; +]; + +def N = 100_000; +def NUM_BINS = 20; +def HIST_CHAR = ^#; +def HIST_CHAR_SIZE = 125; +def BinSize = 1. / float(NUM_BINS); +int Bins(NUM_BINS), BN, I, J, Hist; +real RN; +[for I:= 0 to N-1 do + [RN:= RNG; + BN:= fix(Floor(RN/BinSize)); + Bins(BN):= Bins(BN)+1; + ]; +Print("Modified random distribution with %,d samples in range [0, 1):\n", N); +Print(" Range Number of samples within that range\n"); +for I:= 0 to NUM_BINS-1 do + [Hist:= Bins(I) / HIST_CHAR_SIZE; + Print("%1.2f ..< %1.2f ", BinSize*float(I), BinSize*float(I+1)); + for J:= 1 to Hist do Print("%c", HIST_CHAR); + Print(" %,d\n", Bins(I)); + ]; +] diff --git a/Task/Modular-arithmetic/00-TASK.txt b/Task/Modular-arithmetic/00-TASK.txt index 88e5dc547b..d2245933b1 100644 --- a/Task/Modular-arithmetic/00-TASK.txt +++ b/Task/Modular-arithmetic/00-TASK.txt @@ -1,10 +1,10 @@ '''[[wp:Modular arithmetic|Modular arithmetic]]''' is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined [[wp:equivalence relation|equivalence relation]] called ''congruence''. -For any positive integer p called the ''congruence modulus'', -two numbers a and b are said to be ''congruent modulo p'' whenever there exists an integer k such that: -:a = b + k\,p +For any positive integer m called the ''congruence modulus'', +two numbers a and b are said to be ''congruent modulo m'' whenever there exists an integer k such that: +:a = b + k\,m -The corresponding set of [[wp:equivalence class|equivalence class]]es forms a [[wp:ring (mathematics)|ring]] denoted \frac{\Z}{p\Z}. When p is a prime number, this ring becomes a [[wp:field (mathematics)|field]] denoted \mathbb{F}_p, but you won't have to implement the [[wp:multiplicative inverse|multiplicative inverse]] for this task. +The corresponding set of [[wp:equivalence class|equivalence class]]es forms a [[wp:ring (mathematics)|ring]] denoted \Z/m\Z. When q=p^k \,(k>0) is a prime power, the ring \Z/q\Z becomes a [[wp:Finite field|finite field]], usually denoted \mathbb{F}_q or \mathrm{GF}(q), but you won't have to implement the [[wp:multiplicative inverse|multiplicative inverse]] for this task. Addition and multiplication on this ring have the same algebraic structure as in usual arithmetic, so that a function such as a polynomial expression could receive a ring element as argument and give a consistent result. @@ -22,3 +22,4 @@ In other words, the function is an algebraic expression that could be used with ;Related tasks: [[Modular exponentiation]]

    + diff --git a/Task/Modular-arithmetic/ALGOL-68/modular-arithmetic.alg b/Task/Modular-arithmetic/ALGOL-68/modular-arithmetic.alg index 5b4a08cd14..a945eaf881 100644 --- a/Task/Modular-arithmetic/ALGOL-68/modular-arithmetic.alg +++ b/Task/Modular-arithmetic/ALGOL-68/modular-arithmetic.alg @@ -19,4 +19,6 @@ PROC f = ( UNION( LONG LONG INT, MODULARINT ) x )LONG LONG INT: , ( MODULARINT mx ): v OF ( mx**100 + mx + 1 ) ESAC; -print( ( whole( f( MODULARINT( 10, 13 ) ), 0 ), newline ) ) +print( ( whole( f( MODULARINT( 10, 13 ) ), 0 ), newline ) ); +# additional test to avoid a warning that the * operator isn't used... # +print( ( whole( f( MODULARINT( 10, 13 ) * MODULARINT( 10, 13 ) ), 0 ), newline ) ) diff --git a/Task/Modular-arithmetic/Ada/modular-arithmetic.ada b/Task/Modular-arithmetic/Ada/modular-arithmetic.adb similarity index 100% rename from Task/Modular-arithmetic/Ada/modular-arithmetic.ada rename to Task/Modular-arithmetic/Ada/modular-arithmetic.adb diff --git a/Task/Modular-arithmetic/Common-Lisp/modular-arithmetic.lisp b/Task/Modular-arithmetic/Common-Lisp/modular-arithmetic-1.lisp similarity index 100% rename from Task/Modular-arithmetic/Common-Lisp/modular-arithmetic.lisp rename to Task/Modular-arithmetic/Common-Lisp/modular-arithmetic-1.lisp diff --git a/Task/Modular-arithmetic/Common-Lisp/modular-arithmetic-2.lisp b/Task/Modular-arithmetic/Common-Lisp/modular-arithmetic-2.lisp new file mode 100644 index 0000000000..3f60d21d14 --- /dev/null +++ b/Task/Modular-arithmetic/Common-Lisp/modular-arithmetic-2.lisp @@ -0,0 +1,25 @@ +(defpackage :rosetta-code/modular-arithmetic + (:use :cl)) + +(in-package :rosetta-code/modular-arithmetic) + +(defparameter *modulus* nil) + +(defun make-modular (op) + (lambda (&rest args) + (let ((result (apply op args))) + (if *modulus* + (mod result *modulus*) + result)))) + +(let ((ops '(+ expt))) ; add more operators as you need + (shadow ops) + (dolist (op ops) + (setf (symbol-function (find-symbol (symbol-name op))) + (make-modular (symbol-function (find-symbol (symbol-name op) :cl)))))) + +(defun f (x) + (+ (expt x 100) x 1)) + +(format t "No modulus: f(~a) = ~a~%" 10 (f 10)) +(format t "Modulus 13: f(~a) = ~a~%" 10 (let ((*modulus* 13)) (f 10))) diff --git a/Task/Modular-arithmetic/Julia/modular-arithmetic.julia b/Task/Modular-arithmetic/Julia/modular-arithmetic.jl similarity index 100% rename from Task/Modular-arithmetic/Julia/modular-arithmetic.julia rename to Task/Modular-arithmetic/Julia/modular-arithmetic.jl diff --git a/Task/Modular-arithmetic/Kotlin/modular-arithmetic.kotlin b/Task/Modular-arithmetic/Kotlin/modular-arithmetic.kts similarity index 100% rename from Task/Modular-arithmetic/Kotlin/modular-arithmetic.kotlin rename to Task/Modular-arithmetic/Kotlin/modular-arithmetic.kts diff --git a/Task/Modular-arithmetic/R/modular-arithmetic.r b/Task/Modular-arithmetic/R/modular-arithmetic.r new file mode 100644 index 0000000000..6131c7d874 --- /dev/null +++ b/Task/Modular-arithmetic/R/modular-arithmetic.r @@ -0,0 +1,30 @@ +as.modular <- function(x, modulus){ + if(x<0|modulus<=0) stop("both arguments must be non-negative and modulus cannot be zero") + if(!(is.integer(x)&is.integer(modulus))) stop("both arguments must be integers") + if(x>=modulus) x <- x%%modulus + structure(list("num"=x, "mod"=modulus), class="modular") +} + +`+.modular` <- function(a, b){ + if(is.integer(b)) b <- as.modular(b, a$mod) + if(a$mod!=b$mod) stop("arguments must have the same modulus") + as.modular(a$num+b$num, a$mod) +} + +`*.modular` <- function(a, b){ + if(is.integer(b)) b <- as.modular(b, a$mod) + if(a$mod!=b$mod) stop("arguments must have the same modulus") + as.modular(a$num*b$num, a$mod) +} + +`^.modular` <- function(a, b){ + if(!is.integer(b)) stop("exponent must be an integer") + if(b<=0) stop("exponent must be positive") + Reduce(`*`, rep(list(a), b)) +} + +#Need a print method to actually display modular integers +print.modular <- function(n) cat(n$num, " (modulo ", n$mod, ")", sep="") + +f <- function(x) x^100L+x+1L +f(as.modular(10L, 13L)) diff --git a/Task/Modular-arithmetic/Rust/modular-arithmetic.rs b/Task/Modular-arithmetic/Rust/modular-arithmetic.rs new file mode 100644 index 0000000000..8995f8eb57 --- /dev/null +++ b/Task/Modular-arithmetic/Rust/modular-arithmetic.rs @@ -0,0 +1,177 @@ +use std::fmt; +use std::ops::{Add, Mul}; + +// Generic function f that works with any type T that implements the required traits +fn f(x: T) -> T +where + T: Copy + Add + From, + ModularInteger: From, + T: From, +{ + // Convert to ModularInteger to use the pow function, then convert back + let mod_int = ModularInteger::from(x); + let powered = mod_int.pow(100); + T::from(powered + ModularInteger::from(x) + ModularInteger::from(T::from(1))) +} + +// For the specific case of ModularInteger, we implement f directly +impl ModularInteger { + fn f_specific(self) -> Self { + self.pow(100) + self + ModularInteger::new(1, self.modulus) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct ModularInteger { + value: i32, + modulus: i32, +} + +impl ModularInteger { + fn new(v: i32, m: i32) -> Self { + ModularInteger { + value: v.rem_euclid(m), // Use rem_euclid for proper modular arithmetic + modulus: m, + } + } + + fn get_value(&self) -> i32 { + self.value + } + + fn get_modulus(&self) -> i32 { + self.modulus + } + + fn validate_op(&self, rhs: &ModularInteger) -> Result<(), String> { + if self.modulus != rhs.modulus { + Err("Left-hand modulus does not match right-hand modulus.".to_string()) + } else { + Ok(()) + } + } + + fn pow(&self, mut exp: i32) -> Self { + if exp < 0 { + panic!("Power must not be negative."); + } + + let mut base = ModularInteger::new(1, self.modulus); + let mut current = *self; + + // Use fast exponentiation algorithm + while exp > 0 { + if exp % 2 == 1 { + base = base * current; + } + current = current * current; + exp /= 2; + } + base + } +} + +// Implement Add trait for ModularInteger + ModularInteger +impl Add for ModularInteger { + type Output = ModularInteger; + + fn add(self, rhs: ModularInteger) -> ModularInteger { + self.validate_op(&rhs).expect("Modulus mismatch"); + ModularInteger::new(self.value + rhs.value, self.modulus) + } +} + +// Implement Add trait for ModularInteger + i32 +impl Add for ModularInteger { + type Output = ModularInteger; + + fn add(self, rhs: i32) -> ModularInteger { + ModularInteger::new(self.value + rhs, self.modulus) + } +} + +// Implement Mul trait for ModularInteger * ModularInteger +impl Mul for ModularInteger { + type Output = ModularInteger; + + fn mul(self, rhs: ModularInteger) -> ModularInteger { + self.validate_op(&rhs).expect("Modulus mismatch"); + ModularInteger::new(self.value * rhs.value, self.modulus) + } +} + +// Implement Display trait for pretty printing +impl fmt::Display for ModularInteger { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "ModularInteger({}, {})", self.value, self.modulus) + } +} + +// Conversion traits for the generic function +impl From for ModularInteger { + fn from(value: i32) -> Self { + ModularInteger::new(value, 13) // Default modulus for demonstration + } +} + +impl From for i32 { + fn from(mod_int: ModularInteger) -> Self { + mod_int.value + } +} + +fn main() { + let input = ModularInteger::new(10, 13); + let output = input.f_specific(); // Using the specific implementation for ModularInteger + println!("f({}) = {}", input, output); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_modular_integer_creation() { + let mi = ModularInteger::new(15, 13); + assert_eq!(mi.get_value(), 2); + assert_eq!(mi.get_modulus(), 13); + } + + #[test] + fn test_addition() { + let mi1 = ModularInteger::new(10, 13); + let mi2 = ModularInteger::new(5, 13); + let result = mi1 + mi2; + assert_eq!(result.get_value(), 2); // (10 + 5) % 13 = 2 + } + + #[test] + fn test_multiplication() { + let mi1 = ModularInteger::new(10, 13); + let mi2 = ModularInteger::new(5, 13); + let result = mi1 * mi2; + assert_eq!(result.get_value(), 11); // (10 * 5) % 13 = 11 + } + + #[test] + fn test_power() { + let mi = ModularInteger::new(2, 13); + let result = mi.pow(3); + assert_eq!(result.get_value(), 8); // 2^3 = 8 + } + + #[test] + #[should_panic(expected = "Modulus mismatch")] + fn test_mismatched_modulus() { + let mi1 = ModularInteger::new(10, 13); + let mi2 = ModularInteger::new(5, 17); + let _ = mi1 + mi2; + } + + #[test] + #[should_panic(expected = "Power must not be negative")] + fn test_negative_power() { + let mi = ModularInteger::new(2, 13); + mi.pow(-1); + } +} diff --git a/Task/Modular-arithmetic/Scheme/modular-arithmetic.ss b/Task/Modular-arithmetic/Scheme/modular-arithmetic.scm similarity index 100% rename from Task/Modular-arithmetic/Scheme/modular-arithmetic.ss rename to Task/Modular-arithmetic/Scheme/modular-arithmetic.scm diff --git a/Task/Modular-arithmetic/Zig/modular-arithmetic.zig b/Task/Modular-arithmetic/Zig/modular-arithmetic.zig new file mode 100644 index 0000000000..22c6d4ffb0 --- /dev/null +++ b/Task/Modular-arithmetic/Zig/modular-arithmetic.zig @@ -0,0 +1,94 @@ +const std = @import("std"); +const print = std.debug.print; + +// Generic function f that works with any type T +fn f(comptime T: type, x: T) T { + const pow_result = pow(T, x, 100); + const temp = pow_result.add(x) catch unreachable; // Same modulus, won't error + return temp.addInt(1); +} + +// ModularInteger struct +const ModularInteger = struct { + value: i32, + modulus: i32, + + const Self = @This(); + + // Constructor + pub fn init(v: i32, m: i32) Self { + return Self{ + .value = @mod(v, m), + .modulus = m, + }; + } + + // Getter methods + pub fn getValue(self: Self) i32 { + return self.value; + } + + pub fn getModulus(self: Self) i32 { + return self.modulus; + } + + // Validation helper + fn validateOp(self: Self, rhs: Self) !void { + if (self.modulus != rhs.modulus) { + return error.ModulusMismatch; + } + } + + // Addition with another ModularInteger + pub fn add(self: Self, rhs: Self) !Self { + try self.validateOp(rhs); + return Self.init(self.value + rhs.value, self.modulus); + } + + // Addition with integer + pub fn addInt(self: Self, rhs: i32) Self { + return Self.init(self.value + rhs, self.modulus); + } + + // Multiplication with another ModularInteger + pub fn mul(self: Self, rhs: Self) !Self { + try self.validateOp(rhs); + return Self.init(self.value * rhs.value, self.modulus); + } + + // Format for printing + pub fn format( + self: Self, + comptime fmt: []const u8, + options: std.fmt.FormatOptions, + writer: anytype, + ) !void { + _ = fmt; + _ = options; + try writer.print("ModularInteger({}, {})", .{ self.value, self.modulus }); + } +}; + +// Power function for ModularInteger +fn pow(comptime T: type, base: T, power: i32) T { + if (power < 0) { + @panic("Power must not be negative."); + } + + var result = T.init(1, base.getModulus()); + var p = power; + while (p > 0) : (p -= 1) { + result = result.mul(base) catch unreachable; // Same modulus, won't error + } + return result; +} + +// Operator overloading using + syntax (though Zig doesn't have true operator overloading) +// We use methods instead, but you could create wrapper functions if desired + +pub fn main() !void { + const input = ModularInteger.init(10, 13); + const output = f(ModularInteger, input); + + print("f({}) = {}\n", .{ input, output }); +} diff --git a/Task/Modular-exponentiation/Ada/modular-exponentiation.ada b/Task/Modular-exponentiation/Ada/modular-exponentiation-1.adb similarity index 100% rename from Task/Modular-exponentiation/Ada/modular-exponentiation.ada rename to Task/Modular-exponentiation/Ada/modular-exponentiation-1.adb diff --git a/Task/Modular-exponentiation/Ada/modular-exponentiation-2.adb b/Task/Modular-exponentiation/Ada/modular-exponentiation-2.adb new file mode 100644 index 0000000000..962fdd7c67 --- /dev/null +++ b/Task/Modular-exponentiation/Ada/modular-exponentiation-2.adb @@ -0,0 +1,16 @@ +with Ada.Text_IO; use Ada.Text_IO; +with Unbounded_Unsigneds; use Unbounded_Unsigneds; + +with Strings_Edit.Unbounded_Unsigned_Edit; +use Strings_Edit.Unbounded_Unsigned_Edit; + +procedure Modular_Exponent is +begin + Put_Line + ( Image + ( Mod_Pow + ( Value ("2988348162058574136915891421498819466320163312926952423791023078876139"), + Value ("2351399303373464486466122544523690094744975233415544072992656881240319"), + From_Half_Word (10) ** 40 + ) ) ); +end Modular_Exponent; diff --git a/Task/Modular-exponentiation/Calc/modular-exponentiation.calc b/Task/Modular-exponentiation/Calc/modular-exponentiation.calc new file mode 100644 index 0000000000..7733ca5b04 --- /dev/null +++ b/Task/Modular-exponentiation/Calc/modular-exponentiation.calc @@ -0,0 +1 @@ +2988348162058574136915891421498819466320163312926952423791023078876139 SPC 10 SPC 40 ^ C-u -5 v p 2351399303373464486466122544523690094744975233415544072992656881240319 ^ v u DEL diff --git a/Task/Modular-exponentiation/Crystal/modular-exponentiation.crystal b/Task/Modular-exponentiation/Crystal/modular-exponentiation.cr similarity index 100% rename from Task/Modular-exponentiation/Crystal/modular-exponentiation.crystal rename to Task/Modular-exponentiation/Crystal/modular-exponentiation.cr diff --git a/Task/Modular-exponentiation/Dart/modular-exponentiation.dart b/Task/Modular-exponentiation/Dart/modular-exponentiation.dart new file mode 100644 index 0000000000..faf81f5ffe --- /dev/null +++ b/Task/Modular-exponentiation/Dart/modular-exponentiation.dart @@ -0,0 +1,7 @@ +import "dart:math"; +void main() { + var a = BigInt.parse("2988348162058574136915891421498819466320163312926952423791023078876139"); + var b = BigInt.parse("2351399303373464486466122544523690094744975233415544072992656881240319"); + var m = BigInt.from(10).pow(40); + print(a.modPow(b, m)); +} diff --git a/Task/Modular-exponentiation/Delphi/modular-exponentiation.delphi b/Task/Modular-exponentiation/Delphi/modular-exponentiation.pas similarity index 100% rename from Task/Modular-exponentiation/Delphi/modular-exponentiation.delphi rename to Task/Modular-exponentiation/Delphi/modular-exponentiation.pas diff --git a/Task/Modular-exponentiation/EasyLang/modular-exponentiation.easy b/Task/Modular-exponentiation/EasyLang/modular-exponentiation.easy new file mode 100644 index 0000000000..bd826cb039 --- /dev/null +++ b/Task/Modular-exponentiation/EasyLang/modular-exponentiation.easy @@ -0,0 +1,175 @@ +func[] bn s$ . + i = len s$ - 7 + 1 + while i >= -5 + r[] &= number substr s$ i 7 + i -= 7 + . + return r[] +. +func$ str bn[] . + s$ = bn[$] + for i = len bn[] - 1 downto 1 + h$ = bn[i] + s$ &= substr "0000000" 1 (7 - len h$) & h$ + . + return s$ +. +func[] bnmul a[] b[] . + len r[] len a[] + len b[] + if len a[] > len b[] : swap a[] b[] + for ia = 1 to len a[] + h = 0 + for ib = 1 to len b[] + h += r[ia + ib - 1] + b[ib] * a[ia] + r[ia + ib - 1] = h mod 10000000 + h = h div 10000000 + . + r[ia + ib - 1] += h + . + while len r[] > 1 and r[$] = 0 : len r[] -1 + return r[] +. +func[] bnadd a[] b[] . + if len b[] > len a[] : swap a[] b[] + len r[] len a[] + for i = 1 to len r[] + v = 0 + if i <= len b[] : v = b[i] + h += a[i] + v + r[i] = h mod 10000000 + h = h div 10000000 + . + if h > 0 : r[] &= h + while r[$] = 0 and len r[] > 1 : len r[] -1 + return r[] +. +func bncmp a[] b[] . + if len a[] > len b[] : return 1 + if len a[] < len b[] : return -1 + for i = len a[] downto 1 + if a[i] > b[i] : return 1 + if a[i] < b[i] : return -1 + . + return 0 +. +func[] bnsub a[] b[] . + len r[] len a[] + for i = 1 to len r[] + v = 0 + if i <= len b[] : v = b[i] + h = a[i] - v - c + c = 0 + if h < 0 + h += 10000000 + c = 1 + . + r[i] = h + . + while r[$] = 0 and len r[] > 1 : len r[] -1 + return r[] +. +func[][] bndivmod a[] b[] . + if bncmp a[] b[] < 0 : return [ [ 0 ] a[] ] + lb = len b[] + d = 10000000 div (b[lb] + 1) + if d > 1 + for i = 1 to lb + carry += b[i] * d + b[i] = carry mod 10000000 + carry = carry div 10000000 + . + for i = 1 to len a[] + carry += a[i] * d + a[i] = carry mod 10000000 + carry = carry div 10000000 + . + . + a[] &= carry + len q[] len a[] - lb + v1 = b[lb] + if lb >= 2 : v2 = b[lb - 1] + for j = len q[] downto 1 + u0 = a[j + lb] + u1 = a[j + lb - 1] + u2 = 0 + if j + lb >= 2 : u2 = a[j + lb - 2] + if u0 = v1 + qhat = 9999999 + rhat = u1 + v1 + else + h = u0 * 10000000 + u1 + qhat = h div v1 + rhat = h mod v1 + . + while rhat < 10000000 and qhat * v2 > 10000000 * rhat + u2 + qhat -= 1 + rhat += v1 + . + k = 0 + for i = 1 to lb + p = qhat * b[i] + k + k = p div 10000000 + t = a[j + i - 1] - (p mod 10000000) + if t < 0 + t += 10000000 + k += 1 + . + a[j + i - 1] = t + . + t = a[j + lb] - k + if t < 0 + qhat -= 1 + k = 0 + for i = 1 to lb + t = a[j + i - 1] + b[i] + k + a[j + i - 1] = t mod 10000000 + k = t div 10000000 + . + a[j + lb] = t + k + else + a[j + lb] = t + . + q[j] = qhat + . + if d > 1 + k = 0 + for i = lb downto 1 + t = k * 10000000 + a[i] + a[i] = t div d + k = t mod d + . + . + len a[] lb + while len q[] > 1 and q[len q[]] = 0 : len q[] len q[] - 1 + while len a[] > 1 and a[len a[]] = 0 : len a[] len a[] - 1 + return [ q[] a[] ] +. +func[] bnmod a[] n[] . + result[][] = bndivmod a[] n[] + return result[2][] +. +func[] bnpowmod base[] exp[] m[] . + r[] = [ 1 ] + b[] = bnmod base[] m[] + e[] = exp[] + while bncmp e[] [ 0 ] > 0 + if e[1] mod 2 = 1 + r[] = bnmul r[] b[] + r[] = bnmod r[] m[] + . + h = 0 + for i = len e[] downto 1 + h = h * 10000000 + e[i] + e[i] = h div 2 + h = h mod 2 + . + while e[$] = 0 and len e[] > 1 : len e[] -1 + b[] = bnmul b[] b[] + b[] = bnmod b[] m[] + . + return r[] +. +a$ = "2988348162058574136915891421498819466320163312926952423791023078876139" +b$ = "2351399303373464486466122544523690094744975233415544072992656881240319" +m$ = "10000000000000000000000000000000000000000" +print str bnpowmod bn a$ bn b$ bn m$ diff --git a/Task/Modular-exponentiation/Emacs-Lisp/modular-exponentiation.l b/Task/Modular-exponentiation/Emacs-Lisp/modular-exponentiation.el similarity index 100% rename from Task/Modular-exponentiation/Emacs-Lisp/modular-exponentiation.l rename to Task/Modular-exponentiation/Emacs-Lisp/modular-exponentiation.el diff --git a/Task/Modular-exponentiation/Julia/modular-exponentiation.julia b/Task/Modular-exponentiation/Julia/modular-exponentiation.jl similarity index 100% rename from Task/Modular-exponentiation/Julia/modular-exponentiation.julia rename to Task/Modular-exponentiation/Julia/modular-exponentiation.jl diff --git a/Task/Modular-exponentiation/Kotlin/modular-exponentiation.kotlin b/Task/Modular-exponentiation/Kotlin/modular-exponentiation.kts similarity index 100% rename from Task/Modular-exponentiation/Kotlin/modular-exponentiation.kotlin rename to Task/Modular-exponentiation/Kotlin/modular-exponentiation.kts diff --git a/Task/Modular-exponentiation/M2000-Interpreter/modular-exponentiation-1.m2000 b/Task/Modular-exponentiation/M2000-Interpreter/modular-exponentiation-1.m2000 new file mode 100644 index 0000000000..4ded66199d --- /dev/null +++ b/Task/Modular-exponentiation/M2000-Interpreter/modular-exponentiation-1.m2000 @@ -0,0 +1,15 @@ +function ToString(x as *BigInteger) { + with x,"toString" as ret + =ret +} +Function PowerTen(x as integer) { + a=Biginteger("10") + method a, "intPower", biginteger(str$(x,"")) as a + =a +} +a=bigInteger("2988348162058574136915891421498819466320163312926952423791023078876139") +b=biginteger("2351399303373464486466122544523690094744975233415544072992656881240319") +profiler + method a, "modpow", b, PowerTen(40) as result +print timecount +Print ToString(result) diff --git a/Task/Modular-exponentiation/M2000-Interpreter/modular-exponentiation-2.m2000 b/Task/Modular-exponentiation/M2000-Interpreter/modular-exponentiation-2.m2000 new file mode 100644 index 0000000000..d344375e0c --- /dev/null +++ b/Task/Modular-exponentiation/M2000-Interpreter/modular-exponentiation-2.m2000 @@ -0,0 +1,16 @@ +If Version<14 then Error "Need version >=14" +Function PowerTen(x as BigInteger) { + BigInteger a=10 + method a, "intPower", x as a + =a +} +Print PowerTen(40)=10000000000000000000000000000000000000000u ' true + +' 1234u is BigInteger literal value. +' so here a and b get type by the first value's type +a=2988348162058574136915891421498819466320163312926952423791023078876139u +b=2351399303373464486466122544523690094744975233415544072992656881240319u +profiler + method a, "modpow", b, PowerTen(40) as result +print timecount +Print result diff --git a/Task/Modular-exponentiation/Miranda/modular-exponentiation.miranda b/Task/Modular-exponentiation/Miranda/modular-exponentiation.miranda new file mode 100644 index 0000000000..ce84272c62 --- /dev/null +++ b/Task/Modular-exponentiation/Miranda/modular-exponentiation.miranda @@ -0,0 +1,12 @@ +main :: [sys_message] +main = [Stdout (show answer)] + where a = 2988348162058574136915891421498819466320163312926952423791023078876139 + b = 2351399303373464486466122544523690094744975233415544072992656881240319 + answer = modpow a b (10^40) + +modpow :: num->num->num->num +modpow = mp 1 + where mp r b 0 m = r + mp r b p m = mp r' ((b * b) mod m) (p div 2) m + where r' = (r * b) mod m, if p mod 2 = 1 + r' = r, otherwise diff --git a/Task/Modular-exponentiation/Nim/modular-exponentiation.nim b/Task/Modular-exponentiation/Nim/modular-exponentiation.nim index bbf982a1c5..edb7bf0384 100644 --- a/Task/Modular-exponentiation/Nim/modular-exponentiation.nim +++ b/Task/Modular-exponentiation/Nim/modular-exponentiation.nim @@ -1,18 +1,19 @@ import bigints proc powmod(b, e, m: BigInt): BigInt = - assert e >= 0 + assert e >= 0'bi var e = e var b = b + let t = 2'bi result = initBigInt(1) - while e > 0: - if e mod 2 == 1: + while e > 0'bi: + if e mod t == 1'bi: result = (result * b) mod m - e = e div 2 + e = e div t b = (b.pow 2) mod m var a = initBigInt("2988348162058574136915891421498819466320163312926952423791023078876139") b = initBigInt("2351399303373464486466122544523690094744975233415544072992656881240319") -echo powmod(a, b, 10.pow 40) +echo powmod(a, b, 10'bi.pow 40) diff --git a/Task/Modular-exponentiation/OCaml/modular-exponentiation.ocaml b/Task/Modular-exponentiation/OCaml/modular-exponentiation.ml similarity index 100% rename from Task/Modular-exponentiation/OCaml/modular-exponentiation.ocaml rename to Task/Modular-exponentiation/OCaml/modular-exponentiation.ml diff --git a/Task/Modular-exponentiation/PascalABC.NET/modular-exponentiation-1.pas b/Task/Modular-exponentiation/PascalABC.NET/modular-exponentiation-1.pas new file mode 100644 index 0000000000..2f85905dae --- /dev/null +++ b/Task/Modular-exponentiation/PascalABC.NET/modular-exponentiation-1.pas @@ -0,0 +1,5 @@ +## +var a := '2988348162058574136915891421498819466320163312926952423791023078876139'.ToBigInteger; +var b := '2351399303373464486466122544523690094744975233415544072992656881240319'.ToBigInteger; +var m := Power(10bi, 40); +Writeln(BigInteger.ModPow(a, b, m)); diff --git a/Task/Modular-exponentiation/PascalABC.NET/modular-exponentiation-2.pas b/Task/Modular-exponentiation/PascalABC.NET/modular-exponentiation-2.pas new file mode 100644 index 0000000000..7fdf7bc4c8 --- /dev/null +++ b/Task/Modular-exponentiation/PascalABC.NET/modular-exponentiation-2.pas @@ -0,0 +1,16 @@ +// Modular exponentiation. Nigel Galloway:August 22nd., 2024 +type I=System.Numerics.BigInteger; +var bi:string->I:=n->I.Parse(n); +function expMod(a:I;b:I;n:I):I; + function fN(a:I;b:I;c:I):I; + begin + result:=if b=0 then c else fN(a*(a mod n),b/bi('2'),(if (b mod 2)=0 then c else c*a mod n)); + end; +begin + result:=fN(a,b,I.One) +end; +begin + var a := bi('2988348162058574136915891421498819466320163312926952423791023078876139'); + var b := bi('2351399303373464486466122544523690094744975233415544072992656881240319'); + println(expMod(a,b,bi('10')**40).ToString()); +end. diff --git a/Task/Modular-exponentiation/Phix/modular-exponentiation.phix b/Task/Modular-exponentiation/Phix/modular-exponentiation.phix index 2c231334f7..f74530c273 100644 --- a/Task/Modular-exponentiation/Phix/modular-exponentiation.phix +++ b/Task/Modular-exponentiation/Phix/modular-exponentiation.phix @@ -1,35 +1,33 @@ -(phixonline)--> - with javascript_semantics - include mpfr.e - procedure mpz_mod_exp(mpz base, exponent, modulus, result) - if mpz_cmp_si(exponent,1)=0 then - mpz_set(result,base) - else - mpz _exp = mpz_init_set(exponent) -- (use a copy) - bool odd = mpz_odd(_exp) - if odd then - mpz_sub_ui(_exp,_exp,1) - end if - mpz_fdiv_q_2exp(_exp,_exp,1) - mpz_mod_exp(base,_exp,modulus,result) - _exp = mpz_free(_exp) - mpz_mul(result,result,result) - if odd then - mpz_mul(result,result,base) - end if - end if - mpz_mod(result,result,modulus) - end procedure +with javascript_semantics +include mpfr.e +procedure mpz_mod_exp(mpz base, exponent, modulus, result) + if mpz_cmp_si(exponent,1)=0 then + mpz_set(result,base) + else + mpz exp_copy = mpz_init_set(exponent) + bool bOdd = mpz_odd(exp_copy) + if bOdd then + mpz_sub_ui(exp_copy,exp_copy,1) + end if + mpz_fdiv_q_2exp(exp_copy,exp_copy,1) + mpz_mod_exp(base,exp_copy,modulus,result) + exp_copy = mpz_free(exp_copy) + mpz_mul(result,result,result) + if bOdd then + mpz_mul(result,result,base) + end if + end if + mpz_mod(result,result,modulus) +end procedure - mpz base = mpz_init("2988348162058574136915891421498819466320163312926952423791023078876139"), - exponent = mpz_init("2351399303373464486466122544523690094744975233415544072992656881240319"), - modulus = mpz_init("1"&repeat('0',40)), - result = mpz_init() +mpz base = mpz_init("2988348162058574136915891421498819466320163312926952423791023078876139"), + exponent = mpz_init("2351399303373464486466122544523690094744975233415544072992656881240319"), + modulus = mpz_init("1e40"), + result = mpz_init() - mpz_mod_exp(base,exponent,modulus,result) - ?mpz_get_str(result) +mpz_mod_exp(base,exponent,modulus,result) +?mpz_get_str(result) - -- check against the builtin: - mpz_powm(result,base,exponent,modulus) - ?mpz_get_str(result) - - sequence xyz = repeat(repeat(repeat(0,x),y),z) - - sequence line = repeat(0,x) - sequence plane = repeat(line,y) - sequence space = repeat(plane,z) - - sequence rqd = repeat(repeat(repeat(repeat(0,2),3),4),5), - row -- scratch var +sequence rqd = repeat(repeat(repeat(repeat(0,2),3),4),5) - rqd[5][4][3][2] := 5432 - ?rqd[5][4][3][2] - - row = rqd[5][4][3] -- row is now [0,5432] - row[1] = 1 -- rqd remains unchanged - rqd[5][4][3] = row -- rqd[5][4][3][1] is now 1 - rqd[5][4][2] = repeat(0,10) -- middle element of rqd[5][4] is now longer than the other two - ?rqd[5][4] - - ?"==1==" - pp(rqd,{pp_Nest,1}) - ?"==2==" - pp(rqd,{pp_Nest,2}) - ?"==3==" - pp(rqd,{pp_Nest,3}) - - with javascript_semantics - function multifactorial(integer n, order) - atom res = 1 - if n>0 then - res = n*multifactorial(n-order,order) - end if - return res - end function +with javascript_semantics +function multifactorial(integer n, order) + atom res = 1 + while n>1 do + res *= n + n -= order + end while + return res +end function - sequence s = repeat(0,10) - for i=1 to 5 do - for j=1 to 10 do - s[j] = multifactorial(j,i) - end for - pp(s) - end for - - with javascript_semantics - sequence s = repeat("x",6) ?s - s[$] = 5 ?s - s[1] &= 'y' ?s - -- s[2] = s ?s - s[2] = deep_copy(s) ?s - - sequence s = repeat(my_func(),5) - - sequence s = repeat(0,5) - for i=1 to length(s) do - s[i] = my_func() - end for - + with javascript_semantics + -- + -- demo\rosetta\n_queens.exw + -- ========================= + -- + sequence co, -- columns occupied + -- (ro is implicit) + fd, -- forward diagonals + bd, -- backward diagonals + board -atom count + atom count -procedure solve(integer row, integer N, integer show) - for col=1 to N do - if not co[col] then - integer fdi = col+row-1, - bdi = row-col+N - if not fd[fdi] - and not bd[bdi] then - board[row][col] = 'Q' - co[col] = true - fd[fdi] = true - bd[bdi] = true - if row=N then - if show then - puts(1,join(board,"\n")&"\n") - puts(1,repeat('=',N)&"\n") - end if - count += 1 - else - solve(row+1,N,show) - end if - board[row][col] = '.' - co[col] = false - fd[fdi] = false - bd[bdi] = false - end if - end if - end for -end procedure + procedure solve(integer row, integer N, integer show) + for col=1 to N do + if not co[col] then + integer fdi = col+row-1, + bdi = row-col+N + if not fd[fdi] + and not bd[bdi] then + board[row][col] = 'Q' + co[col] = true + fd[fdi] = true + bd[bdi] = true + if row=N then + if show then + puts(1,join(board,"\n")&"\n") + puts(1,repeat('=',N)&"\n") + end if + count += 1 + else + solve(row+1,N,show) + end if + board[row][col] = '.' + co[col] = false + fd[fdi] = false + bd[bdi] = false + end if + end if + end for + end procedure -procedure n_queens(integer N=8, integer show=1) - co = repeat(false,N) - fd = repeat(false,N*2-1) - bd = repeat(false,N*2-1) - board = repeat(repeat('.',N),N) - count = 0 - solve(1,N,show) - printf(1,"%d queens: %d solutions\n",{N,count}) -end procedure + procedure n_queens(integer N=8, integer show=1) + co = repeat(false,N) + fd = repeat(false,N*2-1) + bd = repeat(false,N*2-1) + board = repeat(repeat('.',N),N) + count = 0 + solve(1,N,show) + printf(1,"%d queens: %d solutions\n",{N,count}) + end procedure -for N=1 to iff(platform()=JS?12:14) do - n_queens(N,N<5) -end for + for N=1 to iff(platform()=JS?12:14) do + n_queens(N,N<5) + end for + - with javascript_semantics - function narcissistic(integer n) - string d = sprintf("%d",n) - integer l = length(d) - atom sumn = 0 - for i=1 to l do - sumn += power(d[i]-'0',l) - end for - return sumn=n - end function +with javascript_semantics +function narcissistic(integer n) + string d = sprintf("%d",n) + integer l = length(d) + atom sumn = 0 + for i=1 to l do + sumn += power(d[i]-'0',l) + end for + return sumn=n +end function - sequence s = {} - integer n = 0 - while length(s)<25 do - if narcissistic(n) then s &= n end if - n += 1 - end while - pp(s) - - with javascript_semantics - -- Begin with zero, which is narcissistic by definition and is never the only digit used in other numbers. - sequence output = {`0`} - bool done = false - integer m = 0 - integer q - atom t0 = time() +with javascript_semantics +-- Begin with zero, which is narcissistic by definition and is never the only digit used in other numbers. +sequence output = {`0`} +bool done = false +integer m = 0 +integer q +atom t0 = time() - procedure recurse(string digits, atom powsum, integer rem) - -- Recursive subhandler. Builds lists containing m digit values while summing the digits' mth powers. - -- If m digits have been obtained, compare the sum of powers's digits with the values in the list. - -- Otherwise continue branching the recursion to derive longer lists. - if rem=0 then - atom temp = powsum - integer unmatched = m - while temp do - integer d = find('0'+remainder(temp,10),digits) - if d=0 then exit end if - digits[d] = ' ' - unmatched -= 1 - temp = floor(temp/10) - end while - -- If all the digits have been matched, the sum of powers is narcissistic. - if unmatched=0 then - output = append(output,sprintf("%d",powsum)) - if length(output)=q then done = true end if - end if - else - -- If fewer than m digits at this level, derive longer lists from the current one. - -- Adding only values that are less than or equal to the last one makes each - -- collection unique and turns up the narcissistic numbers in numerical order. - -- - -- ie/eg if sum(sq_power({9,7,4,4},4))==9474, and as shown sort(digits)==list, - -- then 9474 is the one and only permutation that is narcissistic, obviously, - -- and there is no point looking at any other permutation of that list, ever. - -- Also 1000,1100,1110,1111 are the only 4 lists beginning 1, as opposed to - -- the 999 four-digit numbers beginning 1 that might otherwise be checked, - -- and likewise 9000..9999 is actually just 220 rather than the full 999. - -- (I can see that exploring smaller partial sums first will tend to issue - -- results in numeric order, but cannot see an absolute certainty of that) - -- - for d=0 to digits[$]-'0' do - recurse(digits & d+'0', powsum + power(d,m), rem-1) - if done then exit end if - end for - end if - end procedure +procedure recurse(string digits, atom powsum, integer rem) + -- Recursive subhandler. Builds lists containing m digit values while summing the digits' mth powers. + -- If m digits have been obtained, compare the sum of powers's digits with the values in the list. + -- Otherwise continue branching the recursion to derive longer lists. + if rem=0 then + atom temp = powsum + integer unmatched = m + while temp do + integer d = find('0'+remainder(temp,10),digits) + if d=0 then exit end if + digits[d] = ' ' + unmatched -= 1 + temp = floor(temp/10) + end while + -- If all the digits have been matched, the sum of powers is narcissistic. + if unmatched=0 then + output = append(output,sprintf("%d",powsum)) + if length(output)=q then done = true end if + end if + else + -- If fewer than m digits at this level, derive longer lists from the current one. + -- Adding only values that are less than or equal to the last one makes each + -- collection unique and turns up the narcissistic numbers in numerical order. + -- + -- ie/eg if sum(sq_power({9,7,4,4},4))==9474, and as shown sort(digits)==list, + -- then 9474 is the one and only permutation that is narcissistic, obviously, + -- and there is no point looking at any other permutation of that list, ever. + -- Also 1000,1100,1110,1111 are the only 4 lists beginning 1, as opposed to + -- the 999 four-digit numbers beginning 1 that might otherwise be checked, + -- and likewise 9000..9999 is actually just 220 rather than the full 999. + -- (I can see that exploring smaller partial sums first will tend to issue + -- results in numeric order, but cannot see an absolute certainty of that) + -- + for d=0 to digits[$]-'0' do + recurse(digits & d+'0', powsum + power(d,m), rem-1) + if done then exit end if + end for + end if +end procedure - function narcissisticDecimalNumbers(integer qp) - atom t1 = time()+1 - q = qp - -- Initiate the recursive building and testing of collections of increasing numbers of digit values. - while not done do - m += 1 - if m > iff(machine_bits()=32?16:17) then - output = append(output,"Remaining numbers beyond number precision") - done = true - else - for digit=1 to 9 do - recurse(""&'0'+digit, power(digit,m), m-1) - if done then exit end if - end for - if not done and time()>t1 and platform()!=JS then - printf(1,"searching... %d found, length %d, %s\n", - {length(output),m,elapsed(time()-t0)}) - t1 = time()+1 - end if - end if - end while - return output - end function +function narcissisticDecimalNumbers(integer qp) + atom t1 = time()+1 + q = qp + -- Initiate the recursive building and testing of collections of increasing numbers of digit values. + while not done do + m += 1 + if m > iff(machine_bits()=32?16:17) then + output = append(output,"Remaining numbers beyond number precision") + done = true + else + for digit=1 to 9 do + recurse(""&'0'+digit, power(digit,m), m-1) + if done then exit end if + end for + if not done and time()>t1 and platform()!=JS then + printf(1,"searching... %d found, length %d, %s\n", + {length(output),m,elapsed(time()-t0)}) + t1 = time()+1 + end if + end if + end while + return output +end function - sequence r = narcissisticDecimalNumbers(iff(machine_bits()=32?44:47)) - pp(r) - printf(1,"found %d in %s\n",{length(r),elapsed(time()-t0)}) - - function nigh(string n) - sequence p = repeat("",factorial(length(n))) - for i=1 to length(p) do - p[i] = permute(i,n) - end for - p = sort(p) - integer k = rfind(n,p) - return iff(k=length(p)?"0",p[k+1]) - end function +function nigh(string n) + sequence p = repeat("",factorial(length(n))) + for i=1 to length(p) do + p[i] = permute(i,n) + end for + p = sort(p) + integer k = rfind(n,p) + return iff(k=length(p)?"0",p[k+1]) +end function - constant tests = {"0","9","12","21","12453", - "738440","45072010","95322020"} - -- (crashes on) "9589776899767587796600"} - atom t0 = time() - for i=1 to length(tests) do - string t = tests[i] - printf(1,"%22s => %s\n",{t,nigh(t)}) - end for - ?elapsed(time()-t0) - - function nigh(string n) - integer hi = n[$] - for i=length(n)-1 to 1 by -1 do - integer ni = n[i] - if ni<hi then - string sr = sort(n[i..$]) - integer k = rfind(ni,sr)+1 - n[i] = sr[k] - sr[k..k] = "" - n[i+1..$] = sr - return n - end if - hi = max(hi,ni) - end for - return "0" - end function +function nigh(string n) + integer hi = n[$] + for i=length(n)-1 to 1 by -1 do + integer ni = n[i] + if niconstant
    tests = {"0","9","12","21","12453", - "738440","45072010","95322020", - "9589776899767587796600"} - atom t0 = time() - for i=1 to length(tests) do - string t = tests[i] - printf(1,"%22s => %s\n",{t,nigh(t)}) - end for - ?elapsed(time()-t0) - - with javascript_semantics - ?to_integer("1234") -- 1234 - ?to_integer("10101010",0,2) -- 170, 0 on failure - ?to_number("FFFFFFFF","?",16) -- 4294967295.0, "?" on failure - ?scanf("#FFFFFFFF","%f") -- {{4294967295.0}}, {} on failure - ?scanf("0o377","%o") -- {{255}} - ?scanf("1234","%d") -- {{1234}} - include mpfr.e - mpz z = mpz_init() - mpz_set_str(z,"377",8) - ?mpz_get_str(z) -- "255" - mpfr f = mpfr_init() - mpfr_set_str(f,"110.01",2) - ?mpfr_get_fixed(f) -- "6.25" (which is correct in decimal) - - with javascript_semantics - for i=2 to 32 by 10 do - printf(1,"decimal:%3d hex:%3x octal:%3o binary:%7b\n",i) - end for - - with javascript_semantics - requires("0.8.2") -- (added sq_cmp() builtin that returns nested -1/0/+1 compare() results, just like the existing sq_eq() does for equal().) +with javascript_semantics +integer mx = 4, -- max number of a die side (later set to 6) + mn = 1 -- min number of a die side (later set to 0) - integer mx = 4, -- max number of a die side (later set to 6) - mn = 1 -- min number of a die side (later set to 0) +function possible_dice(integer sides) + -- + -- construct all non-descending permutes of mn..mx, + -- ie/eg {1,1,1,1}..{4,4,4,4} with (say), amongst + -- others, {1,1,2,4} but not {1,1,4,2}. + -- + sequence die = repeat(mn,sides), -- (main work area) + res = {deep_copy(die)} + while true do + -- find rightmost incrementable side + -- ie/eg {1,2,4,4} -> set rdx to 2 (if 1-based indexing) + integer rdx = rfind(true,sq_lt(die,mx)) + if rdx=0 then exit end if + -- set that and all later to that incremented + -- ie/eg {1,2,4,4} -> {1,3,3,3} + die[rdx..$] = die[rdx]+1 + res = append(res,deep_copy(die)) + end while + printf(1,"There are %d possible %d..%d %d-sided dice\n",{length(res),mn,mx,sides}) + return res +end function - function possible_dice(integer sides) - -- - -- construct all non-descending permutes of mn..mx, - -- ie/eg {1,1,1,1}..{4,4,4,4} with (say), amongst - -- others, {1,1,2,4} but not {1,1,4,2}. - -- - sequence die = repeat(mn,sides), -- (main work area) - res = {deep_copy(die)} - while true do - -- find rightmost incrementable side - -- ie/eg {1,2,4,4} -> set rdx to 2 (if 1-based indexing) - integer rdx = rfind(true,sq_lt(die,mx)) - if rdx=0 then exit end if - -- set that and all later to that incremented - -- ie/eg {1,2,4,4} -> {1,3,3,3} - die[rdx..$] = die[rdx]+1 - res = append(res,deep_copy(die)) - end while - printf(1,"There are %d possible %d..%d %d-sided dice\n",{length(res),mn,mx,sides}) - return res - end function +function Dnn(sequence die) + -- reconstruct the python die numbering (string) + -- essentially just treat it as a base-N number. + integer l = length(die), -- (sides) + N = mx-mn+1, -- (base) + n = 0 -- (result) + for k=1 to l do + n += (die[k]-mn)*power(N,l-k) + end for + return sprintf("D%d",n+1) +end function - function Dnn(sequence die) - -- reconstruct the python die numbering (string) - -- essentially just treat it as a base-N number. - integer l = length(die), -- (sides) - N = mx-mn+1, -- (base) - n = 0 -- (result) - for k=1 to l do - n += (die[k]-mn)*power(N,l-k) - end for - return sprintf("D%d",n+1) - end function +function cmpd(sequence die1, die2) + -- compares two die returning -1, 0, or +1 for <, =, > + integer res = 0 + for i=1 to length(die1) do + res += sum(sq_cmp(die1[i],die2)) + end for + return sign(res) +end function - function cmpd(sequence die1, die2) - -- compares two die returning -1, 0, or +1 for <, =, > - integer res = 0 - for i=1 to length(die1) do - res += sum(sq_cmp(die1[i],die2)) - end for - return sign(res) - end function +function low_rotation(sequence set) + integer k = find(min(set),set) + return set[k..$]&set[1..k-1] +end function - function low_rotation(sequence set) - integer k = find(min(set),set) - return set[k..$]&set[1..k-1] - end function +integer rotations +function find_non_trans(sequence dice, integer n=3) + atom t1 = time()+1 + integer l = length(dice), sk, sk1, c + sequence set = repeat(1,n), -- (indexes to dice) + cache = repeat(repeat(-2,l),l), + res = {} + while true do + bool valid = true + for k=1 to n-1 do + sk = set[k] + sk1 = set[k+1] + c = cache[sk][sk1] + if c=-2 then + c = cmpd(dice[sk],dice[sk1]) + cache[sk][sk1] = c + end if + if c!=-1 then + valid = false + -- force k+1 to be incremented next: + set[k+2..$] = l + exit + end if + end for + if valid then + sk = set[1] + sk1 = set[$] + c = cache[sk][sk1] + if c=-2 then + c = cmpd(dice[sk],dice[sk1]) + cache[sk][sk1] = c + end if + if c=+1 then + res = append(res,low_rotation(set)) + end if + end if + -- find rightmost incrementable die index + -- ie/eg if l is 35 and set is {1,2,35,35} + -- -> set rdx to 2 (if 1-based indexing) + integer rdx = rfind(true,sq_lt(set,l)) + if rdx=0 then exit end if + -- increment that and reset all later + -- ie/eg {1,2,35,35} -> {1,3,1,1} + set[rdx] += 1 + set[rdx+1..$] = 1 + if time()>t1 and platform()!=JS then + progress("working... (%d/%d)\r",{set[1],l}) + t1 = time()+1 + end if + end while + if platform()!=JS then + progress("") + end if + rotations = length(res) + res = unique(res) + rotations -= length(res) + return res +end function - integer rotations - function find_non_trans(sequence dice, integer n=3) - atom t1 = time()+1 - integer l = length(dice), sk, sk1, c - sequence set = repeat(1,n), -- (indexes to dice) - cache = repeat(repeat(-2,l),l), - res = {} - while true do - bool valid = true - for k=1 to n-1 do - sk = set[k] - sk1 = set[k+1] - c = cache[sk][sk1] - if c=-2 then - c = cmpd(dice[sk],dice[sk1]) - cache[sk][sk1] = c - end if - if c!=-1 then - valid = false - -- force k+1 to be incremented next: - set[k+2..$] = l - exit - end if - end for - if valid then - sk = set[1] - sk1 = set[$] - c = cache[sk][sk1] - if c=-2 then - c = cmpd(dice[sk],dice[sk1]) - cache[sk][sk1] = c - end if - if c=+1 then - res = append(res,low_rotation(set)) - end if - end if - -- find rightmost incrementable die index - -- ie/eg if l is 35 and set is {1,2,35,35} - -- -> set rdx to 2 (if 1-based indexing) - integer rdx = rfind(true,sq_lt(set,l)) - if rdx=0 then exit end if - -- increment that and reset all later - -- ie/eg {1,2,35,35} -> {1,3,1,1} - set[rdx] += 1 - set[rdx+1..$] = 1 - if time()>t1 and platform()!=JS then - progress("working... (%d/%d)\r",{set[1],l}) - t1 = time()+1 - end if - end while - if platform()!=JS then - progress("") - end if - rotations = length(res) - res = unique(res) - rotations -= length(res) - return res - end function +function verbose_cmp(sequence die1, die2) + -- compares two die returning their relationship of their names as a string + integer c = cmpd(die1,die2) + string op = {"<","=",">"}[c+2], + n1 = Dnn(die1), + n2 = Dnn(die2) + return sprintf("%s %s %s",{n1,op,n2}) +end function - function verbose_cmp(sequence die1, die2) - -- compares two die returning their relationship of their names as a string - integer c = cmpd(die1,die2) - string op = {"<","=",">"}[c+2], - n1 = Dnn(die1), - n2 = Dnn(die2) - return sprintf("%s %s %s",{n1,op,n2}) - end function +function verbose_dice_cmp(sequence dice, set) + sequence c = {}, d1, d2 + for j=1 to length(set)-1 do + d1 = dice[set[j]] + d2 = dice[set[j+1]] + c = append(c,verbose_cmp(d1,d2)) + end for + d1 = dice[set[1]] + d2 = dice[set[$]] + c = append(c,verbose_cmp(d1,d2)) + return join(c,", ") +end function - function verbose_dice_cmp(sequence dice, set) - sequence c = {}, d1, d2 - for j=1 to length(set)-1 do - d1 = dice[set[j]] - d2 = dice[set[j+1]] - c = append(c,verbose_cmp(d1,d2)) - end for - d1 = dice[set[1]] - d2 = dice[set[$]] - c = append(c,verbose_cmp(d1,d2)) - return join(c,", ") - end function +procedure show_dice(sequence dice, non_trans, integer N) + integer l = length(non_trans), + omissions = 0, + last = 0 + if N then + printf(1,"\n Non_transitive length-%d combinations found: %d\n",{N,l+rotations}) + end if + for i=1 to l do + object ni = non_trans[i] + if sequence(ni) then + if i<5 then + printf(1,"\n") + for j=1 to length(ni) do + sequence d = dice[ni[j]] + printf(1," %s:%v\n",{Dnn(d),d}) + end for + last = i + else + omissions += 1 + end if + end if + end for + if omissions then + printf(1," (%d omitted)\n",omissions) + end if + if rotations then + printf(1," (%d rotations omitted)\n",rotations) + end if + if last then + printf(1,"\n") + if mx<=6 and mn=1 then + printf(1," More verbose comparison of last result:\n") + end if + printf(1," %s\n",{verbose_dice_cmp(dice,non_trans[last])}) + printf(1,"\n ====\n") + end if + printf(1,"\n") +end procedure - procedure show_dice(sequence dice, non_trans, integer N) - integer l = length(non_trans), - omissions = 0, - last = 0 - if N then - printf(1,"\n Non_transitive length-%d combinations found: %d\n",{N,l+rotations}) - end if - for i=1 to l do - object ni = non_trans[i] - if sequence(ni) then - if i<5 then - printf(1,"\n") - for j=1 to length(ni) do - sequence d = dice[ni[j]] - printf(1," %s:%v\n",{Dnn(d),d}) - end for - last = i - else - omissions += 1 - end if - end if - end for - if omissions then - printf(1," (%d omitted)\n",omissions) - end if - if rotations then - printf(1," (%d rotations omitted)\n",rotations) - end if - if last then - printf(1,"\n") - if mx<=6 and mn=1 then - printf(1," More verbose comparison of last result:\n") - end if - printf(1," %s\n",{verbose_dice_cmp(dice,non_trans[last])}) - printf(1,"\n ====\n") - end if - printf(1,"\n") - end procedure +atom t0 = time() +sequence dice = possible_dice(4) +for N=3 to 4 do + show_dice(dice,find_non_trans(dice,N),N) +end for - atom t0 = time() - sequence dice = possible_dice(4) - for N=3 to 4 do - show_dice(dice,find_non_trans(dice,N),N) - end for +-- From the numberphile video (Efron's dice): +mx = 6 +mn = 0 +dice = possible_dice(6) +--show_dice(dice,find_non_trans(dice,4),4) +-- ok, dunno about you but I'm not waiting for power(924,4) permutes... +-- limit to the ones discussed, plus another 4 random ones +-- (hopefully it'll just pick out the right ones...) +printf(1,"\nEfron's dice\n") +dice = {{0,0,4,4,4,4}, + {1,1,1,1,1,1}, -- (rand) + {1,1,1,5,5,5}, + {1,2,3,4,5,6}, -- (rand) + {2,2,2,2,6,6}, + {5,5,5,6,6,6}, -- (rand) + {3,3,3,3,3,3}, + {6,6,6,6,6,6}} -- (rand) - -- From the numberphile video (Efron's dice): - mx = 6 - mn = 0 - dice = possible_dice(6) - --show_dice(dice,find_non_trans(dice,4),4) - -- ok, dunno about you but I'm not waiting for power(924,4) permutes... - -- limit to the ones discussed, plus another 4 random ones - -- (hopefully it'll just pick out the right ones...) - printf(1,"\nEfron's dice\n") - dice = {{0,0,4,4,4,4}, - {1,1,1,1,1,1}, -- (rand) - {1,1,1,5,5,5}, - {1,2,3,4,5,6}, -- (rand) - {2,2,2,2,6,6}, - {5,5,5,6,6,6}, -- (rand) - {3,3,3,3,3,3}, - {6,6,6,6,6,6}} -- (rand) +show_dice(dice,find_non_trans(dice,4),0) - show_dice(dice,find_non_trans(dice,4),0) +-- and from wp: +mx = 9 +mn = 1 +dice = possible_dice(6) +printf(1,"\nFrom wp\n") +dice = {{1,1,6,6,8,8}, + {2,2,4,4,9,9}, + {3,3,5,5,7,7}} - -- and from wp: - mx = 9 - mn = 1 - dice = possible_dice(6) - printf(1,"\nFrom wp\n") - dice = {{1,1,6,6,8,8}, - {2,2,4,4,9,9}, - {3,3,5,5,7,7}} +show_dice(dice,find_non_trans(dice,3),0) - show_dice(dice,find_non_trans(dice,3),0) +-- Miwin's dice +printf(1,"Miwin's dice\n") +dice = {{1,2,5,6,7,9}, + {1,3,4,5,8,9}, + {2,3,4,6,7,8}} - -- Miwin's dice - printf(1,"Miwin's dice\n") - dice = {{1,2,5,6,7,9}, - {1,3,4,5,8,9}, - {2,3,4,6,7,8}} - - show_dice(dice,find_non_trans(dice,3),0) - printf(1,"%s\n\n",elapsed(time()-t0)) - - t0 = time() - mx = 6 - mn = 1 - dice = possible_dice(6) - show_dice(dice,find_non_trans(dice,3),3) - printf(1,"%s\n\n",elapsed(time()-t0)) +t0 = time() +mx = 6 +mn = 1 +dice = possible_dice(6) +show_dice(dice,find_non_trans(dice,3),3) +printf(1,"%s\n\n",elapsed(time()-t0)) - t0 = time() - mx = 6 - mn = 0 - dice = possible_dice(6) - show_dice(dice,find_non_trans(dice,3),3) - printf(1,"%s\n\n",elapsed(time()-t0)) - - with javascript_semantics - function nobr(sequence res, string neat, integer ni, integer ch, sequence blocks) - if length(blocks)=0 then - res = append(res,neat) - else - integer b = blocks[1] - blocks = blocks[2..$] - integer l = (sum(blocks)+length(blocks)-1)*2, - e = length(neat)-l-b*2 - for i=ni to e by 2 do - for j=i to i+b*2-2 by 2 do - neat[j] = ch - end for - res = nobr(res,neat,i+b*2+2,ch+1,blocks) - neat[i] = ' ' - end for - end if - return res - end function +with javascript_semantics +function nobr(sequence res, string neat, integer ni, integer ch, sequence blocks) + if length(blocks)=0 then + res = append(res,neat) + else + integer b = blocks[1] + blocks = blocks[2..$] + integer l = (sum(blocks)+length(blocks)-1)*2, + e = length(neat)-l-b*2 + for i=ni to e by 2 do + for j=i to i+b*2-2 by 2 do + neat[j] = ch + end for + res = nobr(res,neat,i+b*2+2,ch+1,blocks) + neat[i] = ' ' + end for + end if + return res +end function - function nonoblock(integer len, sequence blocks) - string neat = "|"&join(repeat(' ',len),'|')&"|" - return nobr({},neat,2,'A',blocks) - end function +function nonoblock(integer len, sequence blocks) + string neat = "|"&join(repeat(' ',len),'|')&"|" + return nobr({},neat,2,'A',blocks) +end function - sequence tests = {{5,{2,1}}, - {5,{}}, - {10,{8}}, - {15,{2, 3, 2, 3}}, - {10,{4, 3}}, - {5,{2,1}}, - {10,{3, 1}}, - {5,{2, 3}}} - integer len - sequence blocks, res - for i=1 to length(tests) do - {len,blocks} = tests[i] - string ti = sprintf("%d cells with blocks %s",{len,sprint(blocks)}) - printf(1,"%s\n%s\n",{ti,repeat('=',length(ti))}) - res = nonoblock(len,blocks) - if length(res)=0 then - printf(1,"No solutions.\n") - else - for ri=1 to length(res) do - printf(1,"%3d: %s\n",{ri,res[ri]}) - end for - end if - printf(1,"\n") - end for - - with javascript_semantics - function pow_(atom x, integer e) - atom r = 1 - for i=1 to e do - r *= x - end for - return r - end function +with javascript_semantics +function pow_(atom x, integer e) + atom r = 1 + for i=1 to e do + r *= x + end for + return r +end function - function nth_root(atom y, n) - atom eps = 1e-15, -- relative accuracy - x = 1 - while 1 do - -- atom d = ( y / power(x,n-1) - x ) / n - atom d = ( y / pow_(x,n-1) - x ) / n - x += d - atom e = eps*x -- absolute accuracy - if d > -e and d < e then exit end if - end while - return x - end function +function nth_root(atom y, n) + atom eps = 1e-15, -- relative accuracy + x = 1 + while 1 do +-- atom d = ( y / power(x,n-1) - x ) / n + atom d = ( y / pow_(x,n-1) - x ) / n + x += d + atom e = eps*x -- absolute accuracy + if d > -e and d < e then exit end if + end while + return x +end function - procedure test(sequence yn) - atom {y,n} = yn - printf(1,"nth_root(%d,%d) = %.10g, builtin = %.10g\n",{y,n,nth_root(y,n),power(y,1/n)}) - end procedure - papply({{1024,10},{27,3},{2,2},{5642,125},{4913,3},{8,3},{16,2},{16,4},{125,3},{1000000000,3},{1000000000,9}},test) - - constant ordinals = {"th","st","nd","rd"} +constant ordinals = {"th","st","nd","rd"} - function Nth(integer n, bool apostrophe=false) - integer mod10 = mod(n,10)+1 - if mod10>4 or mod(n,100)=mod10+9 then mod10 = 1 end if - return sprintf("%d%s",{n,repeat('\'',apostrophe)&ordinals[mod10]}) - end function +function Nth(integer n, bool apostrophe=false) + integer mod10 = mod(n,10)+1 + if mod10>4 or mod(n,100)=mod10+9 then mod10 = 1 end if + return sprintf("%d%s",{n,repeat('\'',apostrophe)&ordinals[mod10]}) +end function - constant ranges = {{0,25},{250,265},{1000,1025}} - for i=1 to length(ranges) do - for j=ranges[i][1] to ranges[i][2] do - if mod(j,10)=0 then puts(1,"\n") end if - printf(1," %6s",{Nth(j,i=2)}) - end for - puts(1,"\n") - end for - - function do_one(integer n, string apostrophe) - return pad_head(sprintf("%d%s%s",{n,apostrophe,ord(n)}),7) - end function - procedure do_set(sequence s, bool bApostrophe=false) - puts(1,join_by(apply(true,do_one,{s,{repeat('`',bApostrophe)}}),1,10,"")&"\n") - end procedure - constant {rs,re} = columnize({{0,25},{250,265},{1000,1025}}) - papply(true,do_set,{apply(true,tagset,{re,rs}),{false,true,false}}) - $ ) diff --git a/Task/Number-names/Rust/number-names.rust b/Task/Number-names/Rust/number-names.rs similarity index 100% rename from Task/Number-names/Rust/number-names.rust rename to Task/Number-names/Rust/number-names.rs diff --git a/Task/Number-reversal-game/Ada/number-reversal-game.ada b/Task/Number-reversal-game/Ada/number-reversal-game.adb similarity index 100% rename from Task/Number-reversal-game/Ada/number-reversal-game.ada rename to Task/Number-reversal-game/Ada/number-reversal-game.adb diff --git a/Task/Number-reversal-game/C++/number-reversal-game-3.cpp b/Task/Number-reversal-game/C++/number-reversal-game-3.cpp index dc686de93d..49808547fb 100644 --- a/Task/Number-reversal-game/C++/number-reversal-game-3.cpp +++ b/Task/Number-reversal-game/C++/number-reversal-game-3.cpp @@ -1,4 +1,4 @@ -// Written by Katsumi -- twitter.com/realKatsumi_vn +// Written by Katsumi // Compile with: g++ -std=c++20 -Wall -Wextra -pedantic NumberReversal.cpp -o NumberReversal #include #include @@ -25,7 +25,7 @@ std::string VectorRepr(std::vector list) { int main() { const std::string IntroText = "NUMBER REVERSAL GAME\n" "based on a \"task\" on Rosetta Code -- rosettacode.org\n" - "by Katsumi -- twitter.com/realKatsumi.vn\n\n"; + "by Katsumi \n\n"; // Don't ever write this s**tty code... // std::srand(std::time(0)); diff --git a/Task/Number-reversal-game/COBOL/number-reversal-game.cobol b/Task/Number-reversal-game/COBOL/number-reversal-game.cob similarity index 100% rename from Task/Number-reversal-game/COBOL/number-reversal-game.cobol rename to Task/Number-reversal-game/COBOL/number-reversal-game.cob diff --git a/Task/Number-reversal-game/Crystal/number-reversal-game.crystal b/Task/Number-reversal-game/Crystal/number-reversal-game.cr similarity index 100% rename from Task/Number-reversal-game/Crystal/number-reversal-game.crystal rename to Task/Number-reversal-game/Crystal/number-reversal-game.cr diff --git a/Task/Number-reversal-game/Delphi/number-reversal-game.delphi b/Task/Number-reversal-game/Delphi/number-reversal-game.pas similarity index 100% rename from Task/Number-reversal-game/Delphi/number-reversal-game.delphi rename to Task/Number-reversal-game/Delphi/number-reversal-game.pas diff --git a/Task/Number-reversal-game/EasyLang/number-reversal-game.easy b/Task/Number-reversal-game/EasyLang/number-reversal-game.easy new file mode 100644 index 0000000000..07f6911bb7 --- /dev/null +++ b/Task/Number-reversal-game/EasyLang/number-reversal-game.easy @@ -0,0 +1,32 @@ +func sorted s[] . + for c in s[] + if c < last : return 0 + last = c + . + return 1 +. +func$ tostr s[] . + for s in s[] : res$ &= s & " " + return res$ +. +proc shuffle &s[] . + for i = len s[] downto 2 + swap s[i] s[random 1 i] + . +. +proc reverse n &s[] . + for i = 1 to n div 2 + swap s[i] s[n - i + 1] + . +. +data[] = [ 1 2 3 4 5 6 7 8 9 ] +while sorted data[] = 1 + shuffle data[] +. +while sorted data[] = 0 + print tostr data[] + score += 1 + nflip = number input + reverse nflip data[] +. +print "Score " & score diff --git a/Task/Number-reversal-game/Elena/number-reversal-game.elena b/Task/Number-reversal-game/Elena/number-reversal-game.elena index a1b01617b7..f03cecf81c 100644 --- a/Task/Number-reversal-game/Elena/number-reversal-game.elena +++ b/Task/Number-reversal-game/Elena/number-reversal-game.elena @@ -1,7 +1,7 @@ import system'routines; import extensions; -public program() +public Program() { var sorted := Array.allocate(9).populate::(n => n + 1 ); var values := sorted.clone().randomize(9); @@ -16,10 +16,10 @@ public program() { tries.append(1); - console.print("# ",tries," : LIST : ",values," - Flip how many?"); + Console.print("# ",tries," : LIST : ",values," - Flip how many?"); values.sequenceReverse(0, console.readLine().toInt()) }; - console.printLine("You took ",tries," attempts to put the digits in order!").readChar() + Console.printLine("You took ",tries," attempts to put the digits in order!").readChar() } diff --git a/Task/Number-reversal-game/Elixir/number-reversal-game.elixir b/Task/Number-reversal-game/Elixir/number-reversal-game.ex similarity index 100% rename from Task/Number-reversal-game/Elixir/number-reversal-game.elixir rename to Task/Number-reversal-game/Elixir/number-reversal-game.ex diff --git a/Task/Number-reversal-game/Euphoria/number-reversal-game.euphoria b/Task/Number-reversal-game/Euphoria/number-reversal-game.eu similarity index 100% rename from Task/Number-reversal-game/Euphoria/number-reversal-game.euphoria rename to Task/Number-reversal-game/Euphoria/number-reversal-game.eu diff --git a/Task/Number-reversal-game/Julia/number-reversal-game.julia b/Task/Number-reversal-game/Julia/number-reversal-game.jl similarity index 100% rename from Task/Number-reversal-game/Julia/number-reversal-game.julia rename to Task/Number-reversal-game/Julia/number-reversal-game.jl diff --git a/Task/Number-reversal-game/Kotlin/number-reversal-game.kotlin b/Task/Number-reversal-game/Kotlin/number-reversal-game.kts similarity index 100% rename from Task/Number-reversal-game/Kotlin/number-reversal-game.kotlin rename to Task/Number-reversal-game/Kotlin/number-reversal-game.kts diff --git a/Task/Number-reversal-game/OCaml/number-reversal-game-1.ocaml b/Task/Number-reversal-game/OCaml/number-reversal-game-1.ml similarity index 100% rename from Task/Number-reversal-game/OCaml/number-reversal-game-1.ocaml rename to Task/Number-reversal-game/OCaml/number-reversal-game-1.ml diff --git a/Task/Number-reversal-game/OCaml/number-reversal-game-2.ocaml b/Task/Number-reversal-game/OCaml/number-reversal-game-2.ml similarity index 100% rename from Task/Number-reversal-game/OCaml/number-reversal-game-2.ocaml rename to Task/Number-reversal-game/OCaml/number-reversal-game-2.ml diff --git a/Task/Number-reversal-game/PowerShell/number-reversal-game.psh b/Task/Number-reversal-game/PowerShell/number-reversal-game.ps1 similarity index 100% rename from Task/Number-reversal-game/PowerShell/number-reversal-game.psh rename to Task/Number-reversal-game/PowerShell/number-reversal-game.ps1 diff --git a/Task/Number-reversal-game/REBOL/number-reversal-game.rebol b/Task/Number-reversal-game/Rebol/number-reversal-game.rebol similarity index 91% rename from Task/Number-reversal-game/REBOL/number-reversal-game.rebol rename to Task/Number-reversal-game/Rebol/number-reversal-game.rebol index 8e4d01654f..caee8303ec 100644 --- a/Task/Number-reversal-game/REBOL/number-reversal-game.rebol +++ b/Task/Number-reversal-game/Rebol/number-reversal-game.rebol @@ -1,4 +1,4 @@ -REBOL [] +Rebol [] print "NUMBER REVERSAL GAME" @@ -7,7 +7,7 @@ goal: [1 2 3 4 5 6 7 8 9] random/seed now until [ - jumble: random goal + jumble: random copy goal jumble != goal ; repeat in the unlikely case that jumble isn't jumbled ] diff --git a/Task/Number-reversal-game/Rust/number-reversal-game.rust b/Task/Number-reversal-game/Rust/number-reversal-game.rs similarity index 100% rename from Task/Number-reversal-game/Rust/number-reversal-game.rust rename to Task/Number-reversal-game/Rust/number-reversal-game.rs diff --git a/Task/Number-reversal-game/Scheme/number-reversal-game.ss b/Task/Number-reversal-game/Scheme/number-reversal-game.scm similarity index 100% rename from Task/Number-reversal-game/Scheme/number-reversal-game.ss rename to Task/Number-reversal-game/Scheme/number-reversal-game.scm diff --git a/Task/Numbers-which-are-not-the-sum-of-distinct-squares/Delphi/numbers-which-are-not-the-sum-of-distinct-squares.delphi b/Task/Numbers-which-are-not-the-sum-of-distinct-squares/Delphi/numbers-which-are-not-the-sum-of-distinct-squares.pas similarity index 100% rename from Task/Numbers-which-are-not-the-sum-of-distinct-squares/Delphi/numbers-which-are-not-the-sum-of-distinct-squares.delphi rename to Task/Numbers-which-are-not-the-sum-of-distinct-squares/Delphi/numbers-which-are-not-the-sum-of-distinct-squares.pas diff --git a/Task/Numbers-which-are-not-the-sum-of-distinct-squares/EasyLang/numbers-which-are-not-the-sum-of-distinct-squares.easy b/Task/Numbers-which-are-not-the-sum-of-distinct-squares/EasyLang/numbers-which-are-not-the-sum-of-distinct-squares.easy index 4c7612257a..fc65581a3b 100644 --- a/Task/Numbers-which-are-not-the-sum-of-distinct-squares/EasyLang/numbers-which-are-not-the-sum-of-distinct-squares.easy +++ b/Task/Numbers-which-are-not-the-sum-of-distinct-squares/EasyLang/numbers-which-are-not-the-sum-of-distinct-squares.easy @@ -2,7 +2,7 @@ maxNumber = 324 len isSum[] maxNumber maxSquare = floor sqrt maxNumber # -proc flagSum currSum sqPos . . +proc flagSum currSum sqPos . nextSum = currSum + sqPos * sqPos if nextSum <= maxNumber isSum[nextSum] = 1 diff --git a/Task/Numbers-which-are-not-the-sum-of-distinct-squares/Julia/numbers-which-are-not-the-sum-of-distinct-squares.julia b/Task/Numbers-which-are-not-the-sum-of-distinct-squares/Julia/numbers-which-are-not-the-sum-of-distinct-squares.jl similarity index 100% rename from Task/Numbers-which-are-not-the-sum-of-distinct-squares/Julia/numbers-which-are-not-the-sum-of-distinct-squares.julia rename to Task/Numbers-which-are-not-the-sum-of-distinct-squares/Julia/numbers-which-are-not-the-sum-of-distinct-squares.jl diff --git a/Task/Numbers-which-are-not-the-sum-of-distinct-squares/Liberty-BASIC/numbers-which-are-not-the-sum-of-distinct-squares.basic b/Task/Numbers-which-are-not-the-sum-of-distinct-squares/Liberty-BASIC/numbers-which-are-not-the-sum-of-distinct-squares.basic new file mode 100644 index 0000000000..1671014990 --- /dev/null +++ b/Task/Numbers-which-are-not-the-sum-of-distinct-squares/Liberty-BASIC/numbers-which-are-not-the-sum-of-distinct-squares.basic @@ -0,0 +1,33 @@ +Print "Numbers which are not the sum of distinct squares:" +Dim flags(1000000) +limite = 1000000 'limite mínimo: 16641=129^2 +cant = 0 +For i = 1 To limite - 1 + flags(i) = 1 +Next i +For i = 0 To limite - 1 + If i < limite Then flags(SumSq(i)) = 0 +Next +For i = 0 To Sqr(limite) - 1 + If flags(i) Then + cant = cant + 1 + Print i; " "; + End If +Next +Print +Print Chr$(10); "There are "; cant; " numbers which are not the sum of distinct squares." +End + +Function SumSq(num) + n = 1 + suma = 0 + While num + If num And 1 Then + Sq = n * n + suma = suma + Sq + End If + num = Int(num/2) + n = n + 1 + Wend + SumSq = suma +End Function diff --git a/Task/Numbers-which-are-not-the-sum-of-distinct-squares/PascalABC.NET/numbers-which-are-not-the-sum-of-distinct-squares.pas b/Task/Numbers-which-are-not-the-sum-of-distinct-squares/PascalABC.NET/numbers-which-are-not-the-sum-of-distinct-squares.pas new file mode 100644 index 0000000000..7841c5478c --- /dev/null +++ b/Task/Numbers-which-are-not-the-sum-of-distinct-squares/PascalABC.NET/numbers-which-are-not-the-sum-of-distinct-squares.pas @@ -0,0 +1,37 @@ +function soms(n: integer; f: list): boolean; +begin + if (n <= 0) then result := false + else + if n in f then result := true + else + case n.CompareTo(f.Sum) of + 1: result := false; + 0: result := true; + else + var rf := f[::-1].Skip(1).ToList; + result := soms(n - f.Last, rf) or soms(n, rf); + end; +end; + +begin + var i := 1; + var g := 1; + var s := new List; + var a := new List; + + repeat + if i.Sqrt.Floor.Sqr = i then s.Add(i); + if not soms(i, s) then + begin + g := i; + a.Add(g) + end; + i += 1; + until g < (i shr 1); + + println('Numbers which are not the sum of distinct squares:'); + a.println; + println; + println('Stopped checking after finding', i - g, 'sequential non-gaps after the final gap of', g); + println('Found', a.count, 'total.'); +end. diff --git a/Task/Numbers-which-are-not-the-sum-of-distinct-squares/Phix/numbers-which-are-not-the-sum-of-distinct-squares.phix b/Task/Numbers-which-are-not-the-sum-of-distinct-squares/Phix/numbers-which-are-not-the-sum-of-distinct-squares.phix index b420fd40fe..d41f84637f 100644 --- a/Task/Numbers-which-are-not-the-sum-of-distinct-squares/Phix/numbers-which-are-not-the-sum-of-distinct-squares.phix +++ b/Task/Numbers-which-are-not-the-sum-of-distinct-squares/Phix/numbers-which-are-not-the-sum-of-distinct-squares.phix @@ -1,24 +1,22 @@ -(phixonline)--> - with javascript_semantics - sequence summable = {true} -- (1 can be expressed as 1*1) - integer n = 2 - while true do - integer sq = n*n - summable &= repeat(false,sq) - -- (process backwards to avoid adding sq more than once) - for i=length(summable)-sq to 1 by -1 do - if summable[i] then - summable[i+sq] = true - end if - end for - summable[sq] = true - integer r = match(repeat(true,(n+1)*(n+1)),summable) - if r then - summable = summable[1..r-1] - exit - end if - n += 1 - end while - constant nwansods = "numbers which are not the sum of distinct squares" - printf(1,"%s\n",{join(shorten(apply(find_all(false,summable),sprint),nwansods,5))}) - - with javascript_semantics - sequence n50 = {} - integer count = 0, n = 1, n5 = 500 - atom t0 = time() - printf(1,"First 50 numbers which are the cube roots\n") - printf(1," of the products of their proper divisors:\n") - while count<500000 do - -- if product(factors(n))=n*n*n then - if n=1 or length(factors(n))=6 then -- safer/smidge faster - count += 1 - if count<=50 then - n50 &= n - if count=50 then - printf(1,"%s\n",join_by(n50,1,10,"",fmt:="%4d")) - end if - elsif count=n5 then - printf(1,"%,8dth: %,d (%s)\n",{n5,n,elapsed(time()-t0)}) - n5 *= 10 - end if - end if - n += 1 - end while - - with javascript_semantics - enum VALUE, DELTA +with javascript_semantics +enum VALUE, DELTA - type imprecise(object imp) - return sequence(imp) and atom(imp[VALUE]) and atom(imp[DELTA]) - end type +type imprecise(object imp) + return sequence(imp) and atom(imp[VALUE]) and atom(imp[DELTA]) +end type - function sqr(atom a) - return a*a - end function +function sqr(atom a) + return a*a +end function - function imprecise_add(imprecise a, b) - atom delta = sqrt(sqr(a[DELTA]) + sqr(b[DELTA])) - imprecise ret = {a[VALUE] + b[VALUE], delta} - return ret - end function +function imprecise_add(imprecise a, b) + atom delta = sqrt(sqr(a[DELTA]) + sqr(b[DELTA])) + imprecise ret = {a[VALUE] + b[VALUE], delta} + return ret +end function - function imprecise_mul(imprecise a, b) - atom delta = sqrt(sqr(a[VALUE]*b[DELTA]) + sqr(b[VALUE]*a[DELTA])) - imprecise ret = {a[VALUE] * b[VALUE],delta} - return ret - end function +function imprecise_mul(imprecise a, b) + atom delta = sqrt(sqr(a[VALUE]*b[DELTA]) + sqr(b[VALUE]*a[DELTA])) + imprecise ret = {a[VALUE] * b[VALUE],delta} + return ret +end function - function imprecise_div(imprecise a, b) - atom delta = sqrt(sqr(a[VALUE]*b[DELTA]) + sqr(b[VALUE]*a[DELTA]))/sqr(b[VALUE]) - imprecise ret = {a[VALUE] / b[VALUE], delta} - return ret - end function +function imprecise_div(imprecise a, b) + atom delta = sqrt(sqr(a[VALUE]*b[DELTA]) + sqr(b[VALUE]*a[DELTA]))/sqr(b[VALUE]) + imprecise ret = {a[VALUE] / b[VALUE], delta} + return ret +end function - function imprecise_pow(imprecise a, atom c) - atom v = power(a[VALUE], c), - delta = abs(v*c*a[DELTA]/a[VALUE]) - imprecise ret = {v,delta} - return ret - end function +function imprecise_pow(imprecise a, atom c) + atom v = power(a[VALUE], c), + delta = abs(v*c*a[DELTA]/a[VALUE]) + imprecise ret = {v,delta} + return ret +end function - function printImprecise(imprecise imp) - return sprintf("%g+/-%g",imp) - end function +function imprecise_str(imprecise imp) + return sprintf("%g+/-%g",imp) +end function - imprecise x1 = {100, 1.1}, - y1 = {50, 1.2}, - x2 = {-200, 2.2}, - y2 = {-100, 2.3}, - tmp1, tmp2, - d - - tmp1 = imprecise_add(x1, x2) - tmp1 = imprecise_pow(tmp1, 2) - tmp2 = imprecise_add(y1, y2) - tmp2 = imprecise_pow(tmp2, 2) - d = imprecise_add(tmp1,tmp2) - d = imprecise_pow(d, 0.5) - printf(1,"Distance, d, between the following points :") - printf(1,"\n( x1, y1) = ( %s, %s)",{printImprecise(x1),printImprecise(y1)}) - printf(1,"\n( x2, y2) = ( %s, %s)",{printImprecise(x2),printImprecise(y2)}) - printf(1,"\nis d = %s\n", {printImprecise(d)}) - 3,456, "+1.567k" : 1,567.00 +fcn naSuffixes(numStr){ // --> Float or BigInt + var [const] // aka static, ie allocated only once + numRE = RegExp(0'^([+-]*\.*\d+[.]*\d*E*[+-]*\d*)^), + bangRE = RegExp(0'^(!+)^); - nstr:=(numStr - " ,").toUpper(); + nstr := (numStr - " ,").toUpper(); numRE.search(nstr); nstr,r := nstr[numRE.matched[0][1],*], numRE.matched[1]; - if(r.matches("*[.E]*")) r=r.toFloat(); // arg! - if(r.matches("*[.E]*")) r=r.toFloat(); // arg! - else r=BI(r); + if(r.matches("*[.E]*")) r = r.toFloat(); // don't have big float + else r = BI(r); - reg z; - do{ - z=nstr; // use this to see if we actually did anything + do{ + z := nstr; // use this to see if we actually did anything if(aRE.search(nstr)){ - ns,k := aRE.matched; // ((0,3),"SCO") - re,b := aD[k]; // (RegExp("R|RE|RES"),BI(20)), - nstr = nstr[ns[1],*]; - if(re.search(nstr)) nstr=nstr[re.matched[0][1],*]; # remove abbrev tail - r=r*b; + ns,k := aRE.matched; // ((0,3),"SCO") + re,b := aD[k]; // (RegExp("R|RE|RES"),BI(20)), + nstr = nstr[ns[1],*]; + if(re.search(nstr)) // remove abbrev tail + nstr = nstr[re.matched[0][1],*]; + r = r*b; continue; }else if(kRE.search(nstr)){ - r*=kD[kRE.matched[1]]; // "K":1000 ... - nstr=nstr[kRE.matched[0][1],*]; + r *= kD[kRE.matched[1]]; // "K":1000 ... + nstr = nstr[kRE.matched[0][1],*]; continue; }else if(bangRE.search(nstr)){ // floats are converted to int - n,k,z := r.toInt(), bangRE.matched[0][1], n - k; - r,nstr = BI(n), nstr[k,*]; - while(z>0){ r.mul(z); z-=k; } + n,k,z := r.toInt(), bangRE.matched[0][1], n - k; + r,nstr = BI(n), nstr[k,*]; + while(z>0){ r.mul(z); z-=k; } continue; } }while(nstr and z!=nstr); - r + r; } -fcn ki{ // case insensitive: k, ki, - ss:="K M G T P E Z Y X W V U".split(); - d:=Dictionary(); - ss.zipWith(d.add,[3..3*(ss.len()),3].apply(BI(10).pow)); # E:1e+18 - ss.apply("append","I") - .zipWith(d.add,[10..10*(ss.len()),10].apply(BI(2).pow)); # EI:1.15292e+18 - re:="([%s]I\\?)".fmt(ss.concat()); // "([KMGTPEZYXWVU]I\?)" +fcn ki{ // case insensitive: k, ki,.. --> RE & Dictionary/hash + ss := "K M G T P E Z Y X W V U".split(); + d := Dictionary(); // hash: ("YI":1208925819614629174706176 ...) + ss.zipWith(d.add,[3..3*(ss.len()),3].apply(BI(10).pow)); // E:1e+18 + ss.apply("append","I") // EI:1.15292e+18 + .zipWith(d.add,[10..10*(ss.len()),10].apply(BI(2).pow)); + re := "([%s]I?)".fmt(ss.concat()); // "([KMGTPEZYXWVU]I?)" return(RegExp(re),d); } -fcn abrevCreate{ - var upDown=RegExp("([A-Z]+)(.*)"); - s:="PAIRs 2; SCOres 20; DOZens 12; GREATGRoss 1728; GRoss 144; GOOGOLs 10e100".split(";"); +fcn abrevCreate{ // --> RE & Dictionary/hash + var upDown = RegExp("([A-Z]+)(.*)"); + s := "PAIRs 2; SCOres 20; DOZens 12; GREATGRoss 1728; GRoss 144; GOOGOLs 10e100" + .split(";"); abrevs,re := Dictionary(), Sink(String); foreach an in (s){ a,n := an.split(); upDown.search(a); u,d := upDown.matched[1,2]; - d=d.len().pump(List, // "R|RE|RES" - '+(1),d.get.fp(0),"toUpper").reverse().concat("|"); + d = d.len().pump(List, // "R|RE|RES" + '+(1),d.get.fp(0),"toUpper").reverse().concat("|"); + // --> ("DOZ" : (RegExp("ENS|EN|E"),12)..) abrevs.add(u,T(RegExp(d),BI(n))); re.write(u," "); } - // "PAIR|SCO|DOZ|GR|GREATGR|GOOGOL" - re=RegExp("(%s)".fmt(re.close().strip().replace(" ","|"))); + // --> RegExp("PAIR|SCO|DOZ|GR|GREATGR|GOOGOL") + re = RegExp("(%s)".fmt(re.close().strip().replace(" ","|"))); return(re,abrevs); } diff --git a/Task/Numerical-and-alphabetical-suffixes/Zkl/numerical-and-alphabetical-suffixes-2.zkl b/Task/Numerical-and-alphabetical-suffixes/Zkl/numerical-and-alphabetical-suffixes-2.zkl index 20d57ff1d0..feaff87b54 100644 --- a/Task/Numerical-and-alphabetical-suffixes/Zkl/numerical-and-alphabetical-suffixes-2.zkl +++ b/Task/Numerical-and-alphabetical-suffixes/Zkl/numerical-and-alphabetical-suffixes-2.zkl @@ -1,12 +1,12 @@ foreach na in (T("2greatGRo", "24Gros", "288Doz", "1,728pairs", "172.8SCOre", - "1,567", "+1.567k", "0.1567e-2m", - "25.123kK", "25.123m", "2.5123e-00002G", - "25.123kiKI", "25.123Mi", "2.5123e-00002Gi", "+.25123E-7Ei", - "-.25123e-34Vikki", "2e-77gooGols", - "9!", "9!!", "9!!!", "9!!!!", "9!!!!!", "9!!!!!!", - "9!!!!!!!", "9!!!!!!!!", "9!!!!!!!!!", - "9!!!!!!!!!k", ".017k!!", "4 dozensK", "2 dozen pairs")){ - - if((r:=naSuffixes(na)).isType(Float)) println("%16s : %,f".fmt(na,r)); - else println("%16s : %,d".fmt(na,r)); + "1,567", "+1.567k", "0.1567e-2m", + "25.123kK", "25.123m", "2.5123e-00002G", + "25.123kiKI", "25.123Mi", "2.5123e-00002Gi", "+.25123E-7Ei", + "-.25123e-34Vikki", "2e-77gooGols", + "9!", "9!!", "9!!!", "9!!!!", "9!!!!!", "9!!!!!!", + "9!!!!!!!", "9!!!!!!!!", "9!!!!!!!!!", + "9!!!!!!!!!k", ".017k!!", "4 dozensK", "2 dozen pairs")){ + r := naSuffixes(na); + println("%16s : ".fmt(na), + if(r.isType(Float)) "%,f".fmt(r) else "%,d".fmt(r)); } diff --git a/Task/Numerical-integration-Gauss-Legendre-Quadrature/Delphi/numerical-integration-gauss-legendre-quadrature.delphi b/Task/Numerical-integration-Gauss-Legendre-Quadrature/Delphi/numerical-integration-gauss-legendre-quadrature.pas similarity index 100% rename from Task/Numerical-integration-Gauss-Legendre-Quadrature/Delphi/numerical-integration-gauss-legendre-quadrature.delphi rename to Task/Numerical-integration-Gauss-Legendre-Quadrature/Delphi/numerical-integration-gauss-legendre-quadrature.pas diff --git a/Task/Numerical-integration-Gauss-Legendre-Quadrature/EDSAC-order-code/numerical-integration-gauss-legendre-quadrature.edsac b/Task/Numerical-integration-Gauss-Legendre-Quadrature/EDSAC-order-code/numerical-integration-gauss-legendre-quadrature.edsac new file mode 100644 index 0000000000..d319ddc933 --- /dev/null +++ b/Task/Numerical-integration-Gauss-Legendre-Quadrature/EDSAC-order-code/numerical-integration-gauss-legendre-quadrature.edsac @@ -0,0 +1,296 @@ +[Gauss-Legendre quadrature for Rosetta Code. + EDSAC, initial orders 2.] + + T46K P5F [EDITABLE: N parameter, order of G-L quadrature. + In the address field, maximum value 31.] + [Arrange the storage] + T48K P56F [& (delta), 36 locations: library subroutine D6 for division (*)] + T54K P92F [C, 44 locations, library subroutine T1 for cosine] + T50K P136F [X, 36 locations: library subroutine E2 for exponential.] + T52K P172F [A, 41 locations: print subroutine] + T47K P218F [M, 70 locations: main routine] + T51K P300F [G, 243 locations: subroutine for G-L quadrature] + T45K P560F [H, 16 locations: data for quadrature s/r] + T44K P576F [! (phi): function to be integrated] +[(*) Library subroutine R9, which is called at load time, is also loaded at 56. + It can be overwritten when no longer needed.] +[-------------------------------------------------------------------------- + Library subroutine R9 to read integers from tape at load time. + Must be loaded at location 56] + T56K + GKT20FVDL8FA40DUDTFI40FA40FS39FG@S2FG23FA5@T5@E4@ +[-------------------------------------------------------------------------- + Library subroutine M3, prints header at load time and is then overwritten.] + PFGKIFAFRDLFUFOFE@A6FG@E8FEZPF + *!ROOTS!!!!!!!!!!WEIGHTS@&# [last char sets teleprinter to figures] + .. PK [after header, blank tape and PK (WWG, 1951, page 91)] +[--------------------------------------------------------------------------- + ! (phi) parameter: function f(x) to be integrated. + Input: 0D = x + Output: 0D = f(x) + For Rosetta Code task after scaling, f(x) = (exp(x)/2)^5] + E25K T! GK + A3F T23@ [plant return link as usual] + AD T4D [x to 4D] + [4] A4@ GX [call library subroutine E2; places exp(x) - 1 in 4D] + A4D RD A24@ [acc := exp(x)/2] + YF TD [round, and save in 0D] + HD VD YF T4D [acc := (exp(x)/2)^2, round, to 4D] + H4D V4D YF T4D [acc := (exp(x)/2)^4, round, to 4D] + H4D VD YF TD [acc := (exp(x)/2)^5, round, return in 0D] + [23] ZF [(planted) jump back to caller] + [24] IF [constant 1/2] +[------------------------------------------------------------------------------- + H parameter: Data for quadrature subroutine. + Limits of integration are c - h and c + h.] + E25K TH GK + E69K T#H [at load time, call R9 to read constants] + 0F [0#H = c = 0] + 10307921510F [2#H = h = 3/5] + 17F [epsilon = 10^-9, criterion for convergence] + 210828714# [pi/256] + T8Z [resume normal loading at 8H] + [8] PN [n = order of G-L quadrature, set by N parameter at head of program] + [9] T1024D [T order for exclusive end of EDSAC memory] + [10] P2F [add 2 to address] + [11] MF [add to T order to make A order with same address] +[The following are set up at runtime:] + [12] PF [2*n] + [13] TD [T order for first reciprocal in array] + [14] TD [T order for first root in array] + [15] TD [T order for first weight in array] +[---------------------------------------------------------------------- + G parameter: subroutine for Gauss-Legendre quadrature. + Input: via H and ! (phi) parameters (see above) + Output: Estimated integral is returned in 0D.] + E25K TG GK + G22@ + [1] K4096F [place this so that 35-bit values come at even addresses] + [2] PF PF [root of Legendre polynomial] + [4] PF PF [correction to root during Newton-Raphson process] + [6] PF PF [weighted sum of function values] + [8] PF PF [temporary store] + [10] PF PF [temporary store] +[The next 3 are negated values of polynomials (j = 2,...,n)] + [12] PF PF [-P_j(x)] + [14] PF PF [-P_j-1(x)] + [16] PF PF [-P_j-2(x)] + [18] Y2F [subtract to convert T to V order, with address 2 less] + [19] PF [negative count of roots] + [20] P1024F [1/32 (where max n is 31)] + [21] PF + [22] A3F T190@ [plant return link as usual] +[Set up T orders for workspace, working down from top of EDSAc memory. + Weights 1024 - 2*n, roots 1024 - 4*n, reciprocals 1024 - 6*n + 2] + A8H LD T12H [set up 2*n from n] + A9H U139@ [exclusive end of weights] + S12H U15H U131@ U127@ [start of weights = end of roots] + S12H U14H U119@ [start of roots = end of reciprocals] + S12H A10H U13H T55@ [start of reciprocals] +[Calculate the reciprocals 1/j for j := 2, ..., n] + A20@ T21@ + E45@ [skip update first time] + [43] A14H T55@ [update T order] + [45] TD T4D [clear 0D and 4D for division routine] + A20@ U1F A21@ U21@ T5F + [52] A52@ G& AD [division, acc := 1/j] + [55] TD [store in array] + A55@ A10H S14H G43@ +[Prepare to calculate first approximations to roots; here with acc = 0.] + A6#H TD [0D := pi/256 for division] + T4D [clear whole of 4D, including sandwich bit] + A8H LD A2F [2*n + 1 in address field i.e. *2^-15] + L32F T5F [4D := (2*n + 1)/256, extended to 35 bits] + [68] A68@ G& [call division subroutine, 0D := pi/(2*n + 1)] + AD U8#@ [store pi/(2*n + 1)] + R1F TD SD T10#@ [store -pi/4*(2*n + 1)] + +[Calculate the (n div 2) positive roots; negative roots follow by symmetry. + If n is odd, the root at 0 is treated separately.] + [Given n in address field, want (n div 2) in address field, + with low bit = 0. A bit tricky.] + A8H R1F TF AF LD + TF SF [from n, get (n div 2) in the address field] + [83] T19@ [initialize negative count of roots] + A10#@ A8#@ U10#@ + T4D + [88] A88@ GC [call cosine subroutine] + A4D LD [first approx to root] + E96@ [skip correction the first time] + [Inner loop; next approximation for current root] + [93] TF A2#@ A4#@ [clear acc; add correction to root] + [96] U2#@ TD [store approx to root, also pass to Legendre subroutine] + A8H T4F [pass n to Legendre subroutine] + [100] A100@ G191@ [call Legendre] + A1@ H2#@ N2#@ [acc := 1 - x^2] + T10D H10D [to mult reg.] + V8D [acc := 1/deriv] + T10D H10D [to mult reg.] + N6D U4#@ [calculate and store corection] + E115@ TD SD [acc := abs(correction)] + [115] S4#H E93@ [if not converged yet, loop back] + TF A2#@ [acc := root] + [119] TD [copy to caller's array] + A119@ A10H T119@ [post-inc forward index] + A127@ S10H T127@ [pre-dec backward index] + S2#@ [acc := -root] + [127] TD [copy to caller's array] + [Calculate weight for this root. Mult. reg. still contains 1/deriv] + V8D + LD [times 2 to conform to Rosetta code convention] + UD + [131] TD + A131@ A10H T131@ [post-inc forward index] + A139@ S10H T139@ [pre-dec backward index] + AD + [139] TD + A19@ A2F G83@ + [Finished loop round roots. If n is odd, still need root at 0.] + A119@ U150@ [copy T order in case we need it] + S127@ E160@ [if T orders are equal n is even, so done] + TF A131@ T159@ [copy T order for weight] + [150] TD + TD A8H T4F [set up parameters for Legendre] + [154] A154@ G191@ [call Legendre for x = 0] + H8D V8D + LD [times 2 to conform to Rosetta code convention] + [159] TD + +[Code to carry out quadrature, using roots and weights calculated above. + Based on library subroutine Q3, but simpler (doesn't exploit the symmetry) + Here with acc = 0] + [160] T6#@ [initialize weighted sum to 0] + A14H S18@ T173@ [form and plant V order for double word before roots] + S8H [initialize negative counter to -n] +[Start of loop to add weighted sums] + [165] T19@ [update negative counter] + A173@ A10H U173@ [form and plant V order for next root] + A12H T179@ [form and plant V order for next weight] + [Limits of integration are c - h and c + h] + A#H H2#H [acc := c, mult reg := h] + [173] VD [(planted) acc := c + h*root{i} (i = 1, ... n)] + YF TD [round, and pass to function to be integrated] + [176] A176@ G! [call function, returns value in 0D] + HD [mult reg := function value] + [179] VD [(planted) acc := value*weight{i} (i = 1, ... n)] + YF A6#@ T6#@ [round, update sum] + A19@ A2F G165@ [loop back till done n values] + [Now have weighted sum. Multiply by h, round, return to caller] + H6#@ V2#H YF TD + [190] ZF +[--------------] +[Subroutine to evaluate Legendre polynomial P_n(x) and (in effect) P_n'(x)] +[Input: 0D = x; 4F = n in address field, where n = 2..31 (not checked) + Output: 6D = P_n(x), 8D = 1/{(1 - x^2)*P_n'(x)} + Works with negated Legendre polynomials, because EDSAC supports -1 but not +1. + Calculates -P_2{x}, -P_3{x}, ..., -P_n{x} recursively from -P_0(x), -P_1(x) + For given j in {2..n} denote y0 = -P_j(x), y1 = -P_j-1(x), y2 = -P_j-2(x). + From the formulae in the task description we get: + y0 = (1 - 1/j)*(x*y1 - y0) + x*y1 + and, with j = n, 1/{(1 - x^2)*P_n'(x)} = -(1/n)/(y1 - x*y0)] + [191] A3F T242@ [plant return link as usual] + T16#@ [clear y2 including sandwich bit] + A1@ T16#@ [y2 := -1, extended to 35 bits] + SD T14#@ [y1 := -x] + A13H A11H T219@ [form and plant A order for reciprocal] + S4F A2F T5F [negative count in 5F] + E213@ [skip update the first time] + [205] T5F [update negative count] + A14#@ T16#@ A12#@ T14#@ [y2 := y1; y1 := y0] + A219@ A10H T219@ [inc address in A order] + [213] HD V14#@ U6D [save x*y1 in 6D] + S16#@ T8D [save x*y1 - y2 in 8D] + A1@ [acc := -1] + [219] AD [(planted) acc := -1 + 1/j (j = 2,...,n)] + T10D H10D [copy to mult. reg.] + N8D [acc := (1 - 1/j) * (x*y1 - y2)] + A6D T12#@ [y0 := (2 - 1/j)*x*y1 - (1 - 1/j)*y2] + A5F A2F G205@ [iterate until have P_n(x)] + [Now want 1 / n*(y2 - x*y1)] + A219@ T230@ [plant H order for 1 - 1/n] + [230] AD HD [acc := 1/n; mult reg := x] + TD [pass 1/n as dividend to division subroutine] + A14#@ N12#@ [acc := y1 - x*y0] + T4D [pass as divisor to division s/r] + [236] A236@ G& [call division subroutine, 0D := (1/n)/(y1 - x*y0)] + [Return values to caller, remembering that local values are negated] + SD T8D S12#@ T6D + [242] ZF [(planted) return to caller] +[------------------------------------------------------------------------------- + Main routine] + E25K TM GK + E69K T#@ [call R9 at load time to read constant] + 13743895347# [4/5 ] + T2Z [resume normal loading at 2@] + [2] PF PF + [4] PF + [Characters for printing] + [5] K2048F [set letters on teleprinter] + [6] #F [set figures on teleprinter] + [7] IF [letter I] + [8] NF [letter N] + [9] XF [slash] + [10] VF [equals sign] + [11] QF [figure 1] + [12] PF [figure 0] + [13] @F [carriage return] + [14] &F [line feed] + [15] !F [space] + [Enter with acc = 0] + [16] A16@ GG [do quadrature, result/160 in 0D] + HD V#@ LD YF [acc := 0D*(8/5) = result/100, and round] + T2#@ [save over printing of roots and weights] + A14H A11H U30@ [form and plant A order for first root] + A12H T36@ [form and plant A order for first weight] + S8H [acc := -n] + [29] T4@ [update negative count (also used as letter T)] + [30] AD TD [pass root to print subroutine in 0D] + [32] A32@ GA O15@ O15@ [print root and 2 spaces] + [36] AD TD [pass weight to print subroutine in 0D] + [38] A38@ GA O13@ O14@ [print weight and new line] + A30@ A10H T30@ [inc address of root] + A36@ A10H T36@ [inc address of weight] + A4@ A2F G29@ [inc negative count, loop till done] + [Print result of integration, preceded by 'INT/100 ='] + O5@ O7@ O8@ O29@ O6@ + O9@ O11@ O12@ O12@ + O15@ O10@ + A2#@ TD [pass result to print subroutine in 0D] + [64] A64@ GA O13@ O14@ [print result and new line] + [Exit] + O6@ [print dummy char to flush teleprinter buffer] + ZF [halt the machine] +[----------------------------------------------------------------------- + Library subroutine T1: calculates cos(x), where abs(x) <= pi/2 + Input: 4D = x/2 + Output: 4D = cos(x)/2 + Requires library subroutine R9.] + E25K TC + GKT20FVDL8FA40DUDTFI40FA40FS39FG@S2FG23FA5@T5@E4@E13ZT32#@ + 1614F73454F243967F54539267F763549741F5726623061# + TZA3FT30@H4DV4DYFT4DH4DN32#@A34#@TDNDA36#@TDNDA38#@ + TDNDA40#@TDNDA42#@TDNDYFTDNDS4DA31@YFT4DEFIFT44Z +[----------------------------------------------------------------------- + Library subroutine D6: Division, accurate, fast. + 36 locations, workspace 6D and 8D. + 0D := 0D/4D, where 4D <> 0, -1.] + E25K T& + GKA3FT34@S4DE13@T4DSDTDE2@T4DADLDTDA4DLDE8@RDU4DLDA35@ + T6DE25@U8DN8DA6DT6DH6DS6DN4DA4DYFG21@SDVDTDEFW1526D +[-------------------------------------------------------------------------- + Library subroutine E2: exponential function. 19 locations. + Input: 4D = x where -1 <= x < ln(2). + Output: 4D = exp(x) - 1] + E25K TX + GKA3FT18@YFLDT6DH4DV4DTDH6DVDRDA4DYFT4DA6DLDE4@TDEF +[----------------------------------------------------------------------- + Subroutine to print 35-bit number in 0D to 10 decimal places. + Wrapper for library subroutine P1, which prints only non-negative + numbers and does not include '0.'] + E25K TA + GKA3FT17@ADE8@TDSDO@E9@O18@YFYFTDO16@O19@A14@G20@P10FZF!FMFA38@ + U37@S40@T25@H39@PFT25@VDUFOFFFSFL4FTDA25@A2FG26@EFU3FJFM1F +[----------------------------------------------------------------------] + E25K TM GK [M parameter again] + E16Z [define entry point] + PF [acc = 0 on entry] diff --git a/Task/Numerical-integration-Gauss-Legendre-Quadrature/Julia/numerical-integration-gauss-legendre-quadrature.julia b/Task/Numerical-integration-Gauss-Legendre-Quadrature/Julia/numerical-integration-gauss-legendre-quadrature.jl similarity index 100% rename from Task/Numerical-integration-Gauss-Legendre-Quadrature/Julia/numerical-integration-gauss-legendre-quadrature.julia rename to Task/Numerical-integration-Gauss-Legendre-Quadrature/Julia/numerical-integration-gauss-legendre-quadrature.jl diff --git a/Task/Numerical-integration-Gauss-Legendre-Quadrature/Kotlin/numerical-integration-gauss-legendre-quadrature.kotlin b/Task/Numerical-integration-Gauss-Legendre-Quadrature/Kotlin/numerical-integration-gauss-legendre-quadrature.kts similarity index 100% rename from Task/Numerical-integration-Gauss-Legendre-Quadrature/Kotlin/numerical-integration-gauss-legendre-quadrature.kotlin rename to Task/Numerical-integration-Gauss-Legendre-Quadrature/Kotlin/numerical-integration-gauss-legendre-quadrature.kts diff --git a/Task/Numerical-integration-Gauss-Legendre-Quadrature/OCaml/numerical-integration-gauss-legendre-quadrature-1.ocaml b/Task/Numerical-integration-Gauss-Legendre-Quadrature/OCaml/numerical-integration-gauss-legendre-quadrature-1.ml similarity index 100% rename from Task/Numerical-integration-Gauss-Legendre-Quadrature/OCaml/numerical-integration-gauss-legendre-quadrature-1.ocaml rename to Task/Numerical-integration-Gauss-Legendre-Quadrature/OCaml/numerical-integration-gauss-legendre-quadrature-1.ml diff --git a/Task/Numerical-integration-Gauss-Legendre-Quadrature/OCaml/numerical-integration-gauss-legendre-quadrature-2.ocaml b/Task/Numerical-integration-Gauss-Legendre-Quadrature/OCaml/numerical-integration-gauss-legendre-quadrature-2.ml similarity index 100% rename from Task/Numerical-integration-Gauss-Legendre-Quadrature/OCaml/numerical-integration-gauss-legendre-quadrature-2.ocaml rename to Task/Numerical-integration-Gauss-Legendre-Quadrature/OCaml/numerical-integration-gauss-legendre-quadrature-2.ml diff --git a/Task/Numerical-integration-Gauss-Legendre-Quadrature/OCaml/numerical-integration-gauss-legendre-quadrature-3.ocaml b/Task/Numerical-integration-Gauss-Legendre-Quadrature/OCaml/numerical-integration-gauss-legendre-quadrature-3.ml similarity index 100% rename from Task/Numerical-integration-Gauss-Legendre-Quadrature/OCaml/numerical-integration-gauss-legendre-quadrature-3.ocaml rename to Task/Numerical-integration-Gauss-Legendre-Quadrature/OCaml/numerical-integration-gauss-legendre-quadrature-3.ml diff --git a/Task/Numerical-integration-Gauss-Legendre-Quadrature/Python/numerical-integration-gauss-legendre-quadrature-1.py b/Task/Numerical-integration-Gauss-Legendre-Quadrature/Python/numerical-integration-gauss-legendre-quadrature-1.py index a7c41e93f6..b5f99eb3f6 100644 --- a/Task/Numerical-integration-Gauss-Legendre-Quadrature/Python/numerical-integration-gauss-legendre-quadrature-1.py +++ b/Task/Numerical-integration-Gauss-Legendre-Quadrature/Python/numerical-integration-gauss-legendre-quadrature-1.py @@ -1,97 +1,107 @@ -from numpy import * +from __future__ import print_function +from __future__ import division + +from numpy import array, exp, concatenate, cos, pi + + +def Legendre(n, x): + """Recursive generation of the Legendre polynomial of order n.""" + x = array(x) + if n == 0: + return x * 0 + 1.0 + elif n == 1: + return x + else: + return ( + (2.0 * n - 1.0) * x * Legendre(n - 1, x) - (n - 1) * Legendre(n - 2, x) + ) / n + + +def DLegendre(n, x): + """Derivative of the Legendre polynomials.""" + x = array(x) + if n == 0: + return x * 0 + elif n == 1: + return x * 0 + 1.0 + else: + return (n / (x**2 - 1.0)) * (x * Legendre(n, x) - Legendre(n - 1, x)) + + +def LegendreRoots(polyorder, tolerance=1e-20): + """Roots of the polynomial obtained using Newton-Raphson method.""" + if polyorder < 2: + err = 1 # bad polyorder no roots can be found + else: + roots = [] + # The polynomials are alternately even and odd functions. So we evaluate only half the number of roots. + for i in range(1, int(polyorder / 2 + 1)): + x = cos(pi * (i - 0.25) / (polyorder + 0.5)) + error = 10 * tolerance + iters = 0 + while (error > tolerance) and (iters < 1000): + dx = -Legendre(polyorder, x) / DLegendre(polyorder, x) + x = x + dx + iters = iters + 1 + error = abs(dx) + roots.append(x) + # Use symmetry to get the other roots + roots = array(roots) + if polyorder % 2 == 0: + roots = concatenate((-1.0 * roots, roots[::-1])) + else: + roots = concatenate((-1.0 * roots, [0.0], roots[::-1])) + err = 0 # successfully determined roots + return [roots, err] -################################################################## -# Recursive generation of the Legendre polynomial of order n -def Legendre(n,x): - x=array(x) - if (n==0): - return x*0+1.0 - elif (n==1): - return x - else: - return ((2.0*n-1.0)*x*Legendre(n-1,x)-(n-1)*Legendre(n-2,x))/n -################################################################## -# Derivative of the Legendre polynomials -def DLegendre(n,x): - x=array(x) - if (n==0): - return x*0 - elif (n==1): - return x*0+1.0 - else: - return (n/(x**2-1.0))*(x*Legendre(n,x)-Legendre(n-1,x)) -################################################################## -# Roots of the polynomial obtained using Newton-Raphson method -def LegendreRoots(polyorder,tolerance=1e-20): - if polyorder<2: - err=1 # bad polyorder no roots can be found - else: - roots=[] - # The polynomials are alternately even and odd functions. So we evaluate only half the number of roots. - for i in range(1,int(polyorder)/2 +1): - x=cos(pi*(i-0.25)/(polyorder+0.5)) - error=10*tolerance - iters=0 - while (error>tolerance) and (iters<1000): - dx=-Legendre(polyorder,x)/DLegendre(polyorder,x) - x=x+dx - iters=iters+1 - error=abs(dx) - roots.append(x) - # Use symmetry to get the other roots - roots=array(roots) - if polyorder%2==0: - roots=concatenate( (-1.0*roots, roots[::-1]) ) - else: - roots=concatenate( (-1.0*roots, [0.0], roots[::-1]) ) - err=0 # successfully determined roots - return [roots, err] -################################################################## -# Weight coefficients def GaussLegendreWeights(polyorder): - W=[] - [xis,err]=LegendreRoots(polyorder) - if err==0: - W=2.0/( (1.0-xis**2)*(DLegendre(polyorder,xis)**2) ) - err=0 - else: - err=1 # could not determine roots - so no weights - return [W, xis, err] -################################################################## -# The integral value -# func : the integrand -# a, b : lower and upper limits of the integral -# polyorder : order of the Legendre polynomial to be used -# -def GaussLegendreQuadrature(func, polyorder, a, b): - [Ws,xs, err]= GaussLegendreWeights(polyorder) - if err==0: - ans=(b-a)*0.5*sum( Ws*func( (b-a)*0.5*xs+ (b+a)*0.5 ) ) - else: - # (in case of error) - err=1 - ans=None - return [ans,err] -################################################################## -# The integrand - change as required -def func(x): - return exp(x) -################################################################## -# + """Weight coefficients.""" + W = [] + xis, err = LegendreRoots(polyorder) + if err == 0: + W = 2.0 / ((1.0 - xis**2) * (DLegendre(polyorder, xis) ** 2)) + err = 0 + else: + err = 1 # could not determine roots - so no weights + return [W, xis, err] -order=5 -[Ws,xs,err]=GaussLegendreWeights(order) -if err==0: - print "Order : ", order - print "Roots : ", xs - print "Weights : ", Ws + +def GaussLegendreQuadrature(func, polyorder, a, b): + """integral value + func : the integrand + a, b : lower and upper limits of the integral + polyorder : order of the Legendre polynomial to be used + """ + Ws, xs, err = GaussLegendreWeights(polyorder) + if err == 0: + ans = (b - a) * 0.5 * sum(Ws * func((b - a) * 0.5 * xs + (b + a) * 0.5)) + else: + # (in case of error) + err = 1 + ans = None + return [ans, err] + + +def func(x): + """The integrand - change as required""" + return exp(x) + + +order = 5 +Ws, xs, err = GaussLegendreWeights(order) + +if err == 0: + print("Order : ", order) + print("Roots : ", xs) + print("Weights : ", Ws) else: - print "Roots/Weights evaluation failed" + print("Roots/Weights evaluation failed") # Integrating the function -[ans,err]=GaussLegendreQuadrature(func , order, -3,3) -if err==0: - print "Integral : ", ans +ans, err = GaussLegendreQuadrature(func, order, -3, 3) + +if err == 0: + print("Integral : ", ans) else: - print "Integral evaluation failed" + print("Integral evaluation failed") diff --git a/Task/Numerical-integration-Gauss-Legendre-Quadrature/REXX/numerical-integration-gauss-legendre-quadrature-2.rexx b/Task/Numerical-integration-Gauss-Legendre-Quadrature/REXX/numerical-integration-gauss-legendre-quadrature-2.rexx index 4027fb164e..89db559f55 100644 --- a/Task/Numerical-integration-Gauss-Legendre-Quadrature/REXX/numerical-integration-gauss-legendre-quadrature-2.rexx +++ b/Task/Numerical-integration-Gauss-Legendre-Quadrature/REXX/numerical-integration-gauss-legendre-quadrature-2.rexx @@ -1,49 +1,92 @@ -/*REXX program does numerical integration using an N─point Gauss─Legendre quadrature rule. */ -pi= pi(); digs= length(pi) - length(.); numeric digits digs; reps= digs % 2 +-- 23 Aug 2025 +include Setting +arg digs +if digs = '' then + digs=9 +numeric digits digs -!.= .; b= 3; a= -b; bma= b - a; bmaH= bma / 2; tiny= '1e-'digs -trueV= exp(b)-exp(a); bpa= b + a; bpaH= bpa / 2 -hdr= 'iterate value (with ' digs " decimal digits being used)" -say ' step ' center(hdr, digs+3) ' difference' /*show hdr*/ -sep='──────' copies("─", digs+3) '─────────────'; say sep /* " sep*/ +say 'NUMERICAL INTEGRATION: GAUSS-LEGENDRE QUADRATURE' +say version +say +w=Digits()+2 +say Left('Function',10) Left('Range',w+4) ' N', + Left('Result',w) Left('True',w) Left(' Error',w) +say +call Task 'Sin(x)', 0, 1, -Cos(1)+1 +call Task 'Sin(x)', 0, Pi()/1, 2 +call Task 'Sin(x)', 0, 10, -Cos(10)+1 +call Task 'Cos(x)', 0, 1, Sin(1) +call Task 'Cos(x)', 0, Pi()/1, 0 +call Task 'Cos(x)', 0, 10, Sin(10) +call Task 'Tan(x)', 0, 1, -Ln(Abs(Cos(1))) +call Task 'Tan(x)', 0, Pi()/1, 0 +call Task 'x', 0, 10, 10**2/2 +call Task 'x**3', 0, 10, 10**4/4 +call Task '1/x', 1, 10, Ln(10)/1 +call Task '4/(x**2+1)', 0, 1, Pi()/1 +call Task 'Exp(x)', -3, 3, Exp(3)-Exp(-3) +call Task 'Gamma(x)', 1, 2, 0.9227459506806306 +call Timer +exit - do #=1 until dif>0; p0z= 1; p0.1= 1; p1z= 2; p1.1= 1; p1.2= 0; ##= # + .5; r.= 0 - /*█*/ do k=2 to #; km= k - 1 - /*█*/ do y=1 for p1z; T.y= p1.y; end /*y*/ - /*█*/ T.y= 0; TT.= 0; do L=1 for p0z; _= L + 2; TT._= p0.L; end /*L*/ - /*█*/ kkm= k + km; do j=1 for p1z +1; T.j= (kkm*T.j - km*TT.j)/k; end /*j*/ - /*█*/ p0z= p1z; do n=1 for p0z; p0.n= p1.n ; end /*n*/ - /*█*/ p1z= p1z + 1; do p=1 for p1z; p1.p= T.p ; end /*p*/ - /*█*/ end /*k*/ - /*▓*/ do !=1 for #; x= cos( pi * (! - .25) / ## ) - /*▓*/ /*░*/ do reps until abs(dx) <= tiny - /*▓*/ /*░*/ f= p1.1; df= 0; do u=2 to p1z; df= f + x*df - /*▓*/ /*░*/ f= p1.u +x*f - /*▓*/ /*░*/ end /*u*/ - /*▓*/ /*░*/ dx= f / df; x= x - dx - /*▓*/ /*░*/ end /*reps ···*/ - /*▓*/ r.1.!= x - /*▓*/ r.2.!= 2 / ( (1 - x*x) * df*df) - /*▓*/ end /*!*/ - $= 0 - /*▒*/ do m=1 for #; $=$ + r.2.m * exp(bpaH + r.1.m*bmaH); end /*m*/ - z= bmaH * $ /*calculate target value (Z)*/ - dif= z - trueV; z= format(z, 3, digs - 2) /* " difference. */ - Ndif= translate( format(dif, 3, 4, 2, 0), 'e', "E") - if #\==1 then say center(#, 6) z' ' Ndif /*no display if not computed*/ - end /*#*/ +Task: +procedure expose Memo. +arg ff,aa,bb,true +w=Digits()+2 +do nn = 1 to 20 + res=GaussQuad(ff,aa,bb,nn); diff=res-true + say Left(ff,10) Left(aa '-' bb,w+4) Right(nn,2), + Left(Std(res),w) Left(true/1,w) Format(diff,2,4,,0) +end +say +return -say sep; xdif= compare( strip(z), trueV); say right("↑", 6 + 1 + xdif) -say left('', 6 + 1) trueV " {exact value}"; say -say 'Using ' digs " digit precision, the" , - 'N-point Gauss─Legendre quadrature (GLQ) had an accuracy of ' xdif-2 " digits." -exit 0 /*stick a fork in it, we're all done. */ -/*───────────────────────────────────────────────────────────────────────────────────────────*/ -e: return 2.718281828459045235360287471352662497757247093699959574966967627724076630353547595 -pi: return 3.141592653589793238462643383279502884197169399375105820974944592307816406286286209 -/*───────────────────────────────────────────────────────────────────────────────────────────*/ -cos: procedure expose !.; parse arg x; if !.x\==. then return !.x; _= 1; z=1; y= x*x - do k=2 by 2 until p==z; p=z; _= -_*y/(k*(k-1)); z=z+_; end; !.x=z; return z -/*───────────────────────────────────────────────────────────────────────────────────────────*/ -exp: procedure; parse arg x; ix= x % 1; if abs(x-ix)>.5 then ix= ix + sign(x); x= x-ix; z= 1 - _=1; do j=1 until p==z; p=z; _= _*x/j; z= z+_; end; return z * e()**ix +GaussQuad: +procedure expose Memo. +-- Gaussion-Legendre quadrature on function f in range a...b taking n points +arg ff,aa,bb,nn +-- Legendre polynomials +p0=1; poly1.1=1; p1=2; poly2.1=1; poly2.2=0 +do i = 2 to nn + work1.0=p1+1 + do j = 1 to p1 + work1.j=poly2.j + end + work1.j=0; work2.0=p0+2; work2.1=0; work2.2=0 + do j = 1 to p0 + j2=j+2; work2.j2=poly1.j + end + do j = 1 to work1.0 + work1.j=((2*i-1)*work1.j-(i-1)*work2.j)/i + end + p0=p1 + do j = 1 to p0 + poly1.j=poly2.j + end + p1=work1.0 + do j = 1 to p1 + poly2.j=work1.j + end +end +-- Roots and weights +eps=1/10**Digits() +root.=0 +do i = 1 to nn + x=Cos(Pi()*(i-0.25)/(nn+0.5)) + do 10 until Abs(dx) < eps + f=poly2.1; df=0 + do k = 2 to p1 + df=f+x*df; f=poly2.k+x*f + end + dx=f/df; x=x-dx + end + root.1.i=x; root.2.i=2/((1-x*x)*df*df) +end +-- Quadrature +bp=0.5*(bb+aa); bm=0.5*(bb-aa); zz=0 +do i = 1 to nn + zz=zz+root.2.i*Eval(ff,bp+root.1.i*bm) +end +return bm*zz + +include Math diff --git a/Task/Numerical-integration-Gauss-Legendre-Quadrature/REXX/numerical-integration-gauss-legendre-quadrature-3.rexx b/Task/Numerical-integration-Gauss-Legendre-Quadrature/REXX/numerical-integration-gauss-legendre-quadrature-3.rexx deleted file mode 100644 index 2c9b14bc0a..0000000000 --- a/Task/Numerical-integration-Gauss-Legendre-Quadrature/REXX/numerical-integration-gauss-legendre-quadrature-3.rexx +++ /dev/null @@ -1,51 +0,0 @@ -/*REXX program does numerical integration using an N─point Gauss─Legendre quadrature rule. */ -pi= pi(); digs= length(pi) - length(.); numeric digits digs; reps= digs % 2 -!.= .; b= 3; a= -b; bma= b - a; bmaH= bma / 2; tiny= '1e-'digs -trueV= exp(b)-exp(a); bpa= b + a; bpaH= bpa / 2 -hdr= 'iterate value (with ' digs " decimal digits being used)" -say ' step ' center(hdr, digs+3) ' difference' /*show hdr*/ -sep='──────' copies("─", digs+3) '─────────────'; say sep /* " sep*/ - - do #=1 until dif>0; p0z= 1; p0.1= 1; p1z= 2; p1.1= 1; p1.2= 0; ##= # + .5; r.= 0 - /*█*/ do k=2 to #; km= k - 1 - /*█*/ do y=1 for p1z; T.y= p1.y; end /*y*/ - /*█*/ T.y= 0; TT.= 0; do L=1 for p0z; _= L + 2; TT._= p0.L; end /*L*/ - /*█*/ kkm= k + km; do j=1 for p1z +1; T.j= (kkm*T.j - km*TT.j)/k; end /*j*/ - /*█*/ p0z= p1z; do n=1 for p0z; p0.n= p1.n ; end /*n*/ - /*█*/ p1z= p1z + 1; do p=1 for p1z; p1.p= T.p ; end /*p*/ - /*█*/ end /*k*/ - /*▓*/ do !=1 for #; x= cos( pi * (! - .25) / ## ) - /*▓*/ /*░*/ do reps until abs(dx) <= tiny - /*▓*/ /*░*/ f= p1.1; df= 0; do u=2 to p1z; df= f + x*df - /*▓*/ /*░*/ f= p1.u +x*f - /*▓*/ /*░*/ end /*u*/ - /*▓*/ /*░*/ dx= f / df; x= x - dx - /*▓*/ /*░*/ end /*reps ···*/ - /*▓*/ r.1.!= x - /*▓*/ r.2.!= 2 / ( (1 - x*x) * df*df) - /*▓*/ end /*!*/ - $= 0 - /*▒*/ do m=1 for #; $=$ + r.2.m * exp(bpaH + r.1.m*bmaH); end /*m*/ - z= bmaH * $ /*calculate target value (Z)*/ - dif= z - trueV; z= format(z, 3, digs - 2) /* " difference. */ - Ndif= translate( format(dif, 3, 4, 3, 0), 'e', "E") - if #\==1 then say center(#, 6) z' ' Ndif /*no display if not computed*/ - end /*#*/ - -say sep; xdif= compare( strip(z), trueV); say right("↑", 6 + 1 + xdif) -say left('', 6 + 1) trueV " {exact value}"; say -say 'Using ' digs " digit precision, the" , - 'N-point Gauss─Legendre quadrature (GLQ) had an accuracy of ' xdif-2 " digits." -exit 0 /*stick a fork in it, we're all done. */ -/*───────────────────────────────────────────────────────────────────────────────────────────*/ -e: return 2.71828182845904523536028747135266249775724709369995957496696762772407663035354759, - ||457138217852516642742746639193200305992181741359662904357290033429526059563073813232862794 -/*───────────────────────────────────────────────────────────────────────────────────────────*/ -pi: return 3.14159265358979323846264338327950288419716939937510582097494459230781640628620899, - ||862803482534211706798214808651328230664709384460955058223172535940812848111745028410270194 -/*───────────────────────────────────────────────────────────────────────────────────────────*/ -cos: procedure expose !.; parse arg x; if !.x\==. then return !.x; _= 1; z=1; y= x*x - do k=2 by 2 until p==z; p=z; _= -_*y/(k*(k-1)); z=z+_; end; !.x=z; return z -/*───────────────────────────────────────────────────────────────────────────────────────────*/ -exp: procedure; parse arg x; ix= x % 1; if abs(x-ix)>.5 then ix= ix + sign(x); x= x-ix; z= 1 - _=1; do j=1 until p==z; p=z; _= _*x/j; z= z+_; end; return z * e()**ix diff --git a/Task/Numerical-integration-Gauss-Legendre-Quadrature/XPL0/numerical-integration-gauss-legendre-quadrature.xpl0 b/Task/Numerical-integration-Gauss-Legendre-Quadrature/XPL0/numerical-integration-gauss-legendre-quadrature.xpl0 new file mode 100644 index 0000000000..a9c0396cbd --- /dev/null +++ b/Task/Numerical-integration-Gauss-Legendre-Quadrature/XPL0/numerical-integration-gauss-legendre-quadrature.xpl0 @@ -0,0 +1,68 @@ +include xpllib; \for Pi and Print +define NN = 5; +real LRoots(NN); +real Weight(NN); +real LCoef(NN+1, NN+1); + +proc LegeCoef; \Compute Legendre polynomial coefficients up to order NN +int N, I; +[LCoef(0, 0):= 1.; LCoef(1, 1):= 1.; +for N:= 2 to NN do + [LCoef(N, 0):= -float(N-1) * LCoef(N-2, 0) / float(N); + for I:= 1 to N do + LCoef(N,I):= (float(2*N-1) * LCoef(N-1, I-1) - float(N-1) * LCoef(N-2, I)) + / float(N); + ]; +]; + +func real LegeEval(N, X); \Evaluate PN(X) +int N; real X; +int I; +real S; +[S:= LCoef(N, N); \leading coefficient +for I:= N downto 1 do + S:= S*X + LCoef(N, I-1); +return S; +]; + +func real LegeDiff(N, X); \Derivative PN'(X) +int N; real X; +return float(N) * (X*LegeEval(N, X) - LegeEval(N-1, X)) / (X*X - 1.); + +proc LegeRoots; \Compute roots and weights for NN-point Gauss-Legendre +int I; +real X, X1; +[for I:= 1 to NN do + [X:= Cos(Pi * (float(I)-0.25) / (float(NN)+0.5)); + repeat X1:= X; + X:= X - LegeEval(NN, X) / LegeDiff(NN, X); + until abs(X-X1) <= 2e-14; + LRoots(I-1):= X; + X1:= LegeDiff(NN, X); + Weight(I-1):= 2. / ((1. - X*X) * X1*X1); + ]; +]; + +func real LegeInte(A, B); \Integrate Exp(X) from A to B using NN-point GL +real A, B; +real C1, C2, Sum; +int I; +[C1:= (B-A)/2.; C2:= (B+A)/2.; Sum:= 0.; +for I:= 0 to NN-1 do + Sum:= Sum + Weight(I) * Exp(C1*LRoots(I) + C2); +return C1 * Sum; +]; + +int I; +[LegeCoef; +LegeRoots; +Print("Roots: "); +for I:= 0 to NN-1 do + Print(" %g", LRoots(I)); +Print("\nWeight:"); +for I:= 0 to NN-1 do + Print(" %g", Weight(I)); +Print("\nintegrating Exp(X) over [-3, 3]:\n\t%2.8f, +compared to actual\n\t%2.8f\n", +LegeInte(-3., 3.), Exp(3.) - Exp(-3.)); +] diff --git a/Task/Numerical-integration/Ada/numerical-integration-1.ada b/Task/Numerical-integration/Ada/numerical-integration-1.adb similarity index 100% rename from Task/Numerical-integration/Ada/numerical-integration-1.ada rename to Task/Numerical-integration/Ada/numerical-integration-1.adb diff --git a/Task/Numerical-integration/Ada/numerical-integration-2.ada b/Task/Numerical-integration/Ada/numerical-integration-2.adb similarity index 100% rename from Task/Numerical-integration/Ada/numerical-integration-2.ada rename to Task/Numerical-integration/Ada/numerical-integration-2.adb diff --git a/Task/Numerical-integration/Ada/numerical-integration-3.ada b/Task/Numerical-integration/Ada/numerical-integration-3.adb similarity index 100% rename from Task/Numerical-integration/Ada/numerical-integration-3.ada rename to Task/Numerical-integration/Ada/numerical-integration-3.adb diff --git a/Task/Numerical-integration/AppleScript/numerical-integration.applescript b/Task/Numerical-integration/AppleScript/numerical-integration.applescript new file mode 100644 index 0000000000..1d184a8cb2 --- /dev/null +++ b/Task/Numerical-integration/AppleScript/numerical-integration.applescript @@ -0,0 +1,70 @@ +script left_rect + on call(f, x, h) + f's call(x) + end call +end script + +script right_rect + on call(f, x, h) + f's call(x + h) + end call +end script + +script mid_rect + on call(f, x, h) + f's call(x + h / 2) + end call +end script + +script trapezium + on call(f, x, h) + ((f's call(x)) + (f's call(x + h))) / 2 + end call +end script + +script simpson + on call(f, x, h) + ((f's call(x)) + 4 * (f's call(x + h / 2)) + (f's call(x + h))) / 6 + end call +end script + +on integrate(f, a, b, n, rule) + set h to (b - a) / n + set res to 0 + repeat with i from 0 to n - 1 + set res to res + (rule's call(f, a + i * h, h)) + end repeat + return h * res +end integrate + +script cube + on call(x) + x ^ 3 + end call +end script + +script reciprocal + on call(x) + 1 / x + end call +end script + +script identity + on call(x) + x + end call +end script + +on integral_test(f, a, b, n) + log "Integrating " & f's name & " from " & a & " to " & b & " with " & n & " steps..." + set rules to {left_rect, right_rect, mid_rect, trapezium, simpson} + repeat with rule in rules + log "Rule: " & rule's name + log integrate(f, a, b, n, rule) + end repeat +end integral_test + +integral_test(cube, 0, 1, 100) +integral_test(reciprocal, 1, 100, 1000) +integral_test(identity, 0, 5000, 5000000) +integral_test(identity, 0, 6000, 6000000) diff --git a/Task/Numerical-integration/Chapel/numerical-integration-1.chapel b/Task/Numerical-integration/Chapel/numerical-integration-1.chpl similarity index 100% rename from Task/Numerical-integration/Chapel/numerical-integration-1.chapel rename to Task/Numerical-integration/Chapel/numerical-integration-1.chpl diff --git a/Task/Numerical-integration/Chapel/numerical-integration-2.chapel b/Task/Numerical-integration/Chapel/numerical-integration-2.chpl similarity index 100% rename from Task/Numerical-integration/Chapel/numerical-integration-2.chapel rename to Task/Numerical-integration/Chapel/numerical-integration-2.chpl diff --git a/Task/Numerical-integration/Delphi/numerical-integration.delphi b/Task/Numerical-integration/Delphi/numerical-integration.pas similarity index 100% rename from Task/Numerical-integration/Delphi/numerical-integration.delphi rename to Task/Numerical-integration/Delphi/numerical-integration.pas diff --git a/Task/Numerical-integration/Elixir/numerical-integration.elixir b/Task/Numerical-integration/Elixir/numerical-integration.ex similarity index 100% rename from Task/Numerical-integration/Elixir/numerical-integration.elixir rename to Task/Numerical-integration/Elixir/numerical-integration.ex diff --git a/Task/Numerical-integration/Euphoria/numerical-integration.euphoria b/Task/Numerical-integration/Euphoria/numerical-integration.eu similarity index 100% rename from Task/Numerical-integration/Euphoria/numerical-integration.euphoria rename to Task/Numerical-integration/Euphoria/numerical-integration.eu diff --git a/Task/Numerical-integration/JavaScript/numerical-integration.js b/Task/Numerical-integration/JavaScript/numerical-integration.js new file mode 100644 index 0000000000..061c18d5e4 --- /dev/null +++ b/Task/Numerical-integration/JavaScript/numerical-integration.js @@ -0,0 +1,33 @@ +const left_rect = (f, x, h) => f(x); +const right_rect = (f, x, h) => f(x + h); +const mid_rect = (f, x, h) => f(x + h / 2); +const trapezium = (f, x, h) => (f(x) + f(x + h)) / 2; +const simpson = (f, x, h) => (f(x) + 4 * f(x + h / 2) + f(x + h)) / 6; + +function integrate(f, a, b, n, rule) { + const h = (b - a) / n; + let result = 0; + for (let i = 0; i < n; i++) { + result += rule(f, a + i * h, h); + } + return h * result; +} + +function integral_test(f, a, b, n) { + console.log(`Integrating ${f.toString()} from ${a} to ${b} with ${n} steps...`); + const rules = {"Left rectangular method": left_rect, + "Right rectangular method": right_rect, + "Midpoint rectangular method": mid_rect, + "Trapezium rule": trapezium, + "Simpson's rule": simpson}; + + for (const r in rules) { + console.log(`${r}: ${integrate(f, a, b, n, rules[r])}`); + } + console.log(); +} + +integral_test(x => x ** 3, 0, 1, 100); +integral_test(x => 1 / x, 1, 100, 1000); +integral_test(x => x, 0, 5000, 5000000); +integral_test(x => x, 0, 6000, 6000000); diff --git a/Task/Numerical-integration/Julia/numerical-integration.julia b/Task/Numerical-integration/Julia/numerical-integration-1.jl similarity index 100% rename from Task/Numerical-integration/Julia/numerical-integration.julia rename to Task/Numerical-integration/Julia/numerical-integration-1.jl diff --git a/Task/Numerical-integration/Julia/numerical-integration-2.jl b/Task/Numerical-integration/Julia/numerical-integration-2.jl new file mode 100644 index 0000000000..5e60450fc9 --- /dev/null +++ b/Task/Numerical-integration/Julia/numerical-integration-2.jl @@ -0,0 +1,24 @@ +leftrect(f, x, _) = f(x) +midrect(f, x, h) = f(x + h / 2) +rightrect(f, x, h) = f(x + h) +trapezium(f, x, h) = (f(x) + f(x + h)) / 2 +simpson(f, x, h) = (f(x) + 4 * f(x + h / 2) + f(x + h)) / 6 +cube(x) = x * x * x +reciprocal(x) = inv(x) + +function integrate(f, a, b, steps, meth) + h = (b - a) / steps + return h * sum(meth(f, a + i * h, h) for i in 0:steps-1) +end + +for (a, b, steps, fun) in [ + (0, 1, 100, cube), + (1, 100, 1000, reciprocal), + (0, 5000, 5_000_000, identity), + (0, 6000, 6_000_000, identity)] + for rule in [leftrect, midrect, rightrect, trapezium, simpson] + println(string(fun) * " integrated using " * string(rule)) + println(" from $a to $b ($steps steps) = ", + round(integrate(fun, a, b, steps, rule), sigdigits=14)) + end +end diff --git a/Task/Numerical-integration/Kotlin/numerical-integration.kotlin b/Task/Numerical-integration/Kotlin/numerical-integration.kts similarity index 100% rename from Task/Numerical-integration/Kotlin/numerical-integration.kotlin rename to Task/Numerical-integration/Kotlin/numerical-integration.kts diff --git a/Task/Numerical-integration/OCaml/numerical-integration-1.ocaml b/Task/Numerical-integration/OCaml/numerical-integration-1.ml similarity index 100% rename from Task/Numerical-integration/OCaml/numerical-integration-1.ocaml rename to Task/Numerical-integration/OCaml/numerical-integration-1.ml diff --git a/Task/Numerical-integration/OCaml/numerical-integration-2.ocaml b/Task/Numerical-integration/OCaml/numerical-integration-2.ml similarity index 100% rename from Task/Numerical-integration/OCaml/numerical-integration-2.ocaml rename to Task/Numerical-integration/OCaml/numerical-integration-2.ml diff --git a/Task/Numerical-integration/OCaml/numerical-integration-3.ocaml b/Task/Numerical-integration/OCaml/numerical-integration-3.ml similarity index 100% rename from Task/Numerical-integration/OCaml/numerical-integration-3.ocaml rename to Task/Numerical-integration/OCaml/numerical-integration-3.ml diff --git a/Task/Numerical-integration/OCaml/numerical-integration-4.ocaml b/Task/Numerical-integration/OCaml/numerical-integration-4.ml similarity index 100% rename from Task/Numerical-integration/OCaml/numerical-integration-4.ocaml rename to Task/Numerical-integration/OCaml/numerical-integration-4.ml diff --git a/Task/Numerical-integration/PascalABC.NET/numerical-integration.pas b/Task/Numerical-integration/PascalABC.NET/numerical-integration.pas new file mode 100644 index 0000000000..2537966410 --- /dev/null +++ b/Task/Numerical-integration/PascalABC.NET/numerical-integration.pas @@ -0,0 +1,25 @@ +function integrate(a, b: real; n: integer; f: real-> real): real; +begin + var h := (b - a) / n; + var sum: array [0..4] of real; + for var i := 0 to n - 1 do + begin + var x := a + i * h; + sum[0] += f(x); + sum[1] += f(x + h / 2.0); + sum[2] += f(x + h); + sum[3] += (f(x) + f(x + h)) / 2.0; + sum[4] += (f(x) + 4.0 * f(x + h / 2.0) + f(x + h)) / 6.0; + end; + var methods := |'LeftRect ', 'MidRect ', 'RightRect', 'Trapezium', 'Simpson '|.tolist; + for var i := 0 to 4 do + println(methods[i], ' = ', sum[i] * h); + println; +end; + +begin + integrate(0.0, 1.0, 100, x -> x * x * x); + integrate(1.0, 100.0, 1_000, x -> 1 / x); + integrate(0.0, 5000.0, 5_000_000, x -> x); + integrate(0.0, 6000.0, 6_000_000, x -> x); +end. diff --git a/Task/Numerical-integration/Pluto/numerical-integration.pluto b/Task/Numerical-integration/Pluto/numerical-integration.pluto new file mode 100644 index 0000000000..d2431ba7a7 --- /dev/null +++ b/Task/Numerical-integration/Pluto/numerical-integration.pluto @@ -0,0 +1,20 @@ +local function integrate(a, b, n, f) + local h = (b - a) / n + local sum = {0, 0, 0, 0, 0} + for i = 1, n do + local x = a + (i - 1) * h + sum[1] += f(x) + sum[2] += f(x + h / 2) + sum[3] += f(x + h) + sum[4] += (f(x) + f(x + h)) / 2 + sum[5] += (f(x) + 4 * f(x + h / 2) + f(x + h)) / 6 + end + local methods = {"LeftRect ", "MidRect ", "RightRect", "Trapezium", "Simpson "} + for i = 1, 5 do print($"{methods[i]} = {sum[i] * h}") end + print() +end + +integrate(0, 1, 100, |v| -> v * v * v) +integrate(1, 100, 1_000, |v| -> 1 / v) +integrate(0, 5_000, 5_000_000, |v| -> v) +integrate(0, 6_000, 6_000_000, |v| -> v) diff --git a/Task/Numerical-integration/REXX/numerical-integration.rexx b/Task/Numerical-integration/REXX/numerical-integration.rexx index 05cd99baa8..a5f04d2afb 100644 --- a/Task/Numerical-integration/REXX/numerical-integration.rexx +++ b/Task/Numerical-integration/REXX/numerical-integration.rexx @@ -1,48 +1,129 @@ -/*REXX pgm performs numerical integration using 5 different algorithms and show results.*/ -numeric digits 20 /*use twenty decimal digits precision. */ +-- 25 Apr 2026 +include Setting +arg digs +if digs = '' then + digs=9 +numeric digits digs - do test=1 for 4; say /*perform the 4 different test suites. */ - if test==1 then do; L= 0; H= 1; i= 100; end - if test==2 then do; L= 1; H= 100; i= 1000; end - if test==3 then do; L= 0; H= 5000; i= 5000000; end - if test==4 then do; L= 0; H= 6000; i= 6000000; end - say center('test' test, 79, "═") /*display a header for the test suite. */ - say ' left rectangular('L", "H', 'i") ──► " left_rect(L, H, i) - say ' midpoint rectangular('L", "H', 'i") ──► " midpoint_rect(L, H, i) - say ' right rectangular('L", "H', 'i") ──► " right_rect(L, H, i) - say ' Simpson('L", "H', 'i") ──► " Simpson(L, H, i) - say ' trapezium('L", "H', 'i") ──► " trapezium(L, H, i) - end /*test*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -f: parse arg y; if test>2 then return y /*choose the "as─is" function. */ - if test==1 then return y**3 /* " " cube function. */ - return 1/y /* " " reciprocal " */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -left_rect: procedure expose test; parse arg a,b,#; $= 0; h= (b-a)/# - do x=a by h for #; $= $ + f(x) - end /*x*/ - return $*h/1 -/*──────────────────────────────────────────────────────────────────────────────────────*/ -midpoint_rect: procedure expose test; parse arg a,b,#; $= 0; h= (b-a)/# - do x=a+h/2 by h for #; $= $ + f(x) - end /*x*/ - return $*h/1 -/*──────────────────────────────────────────────────────────────────────────────────────*/ -right_rect: procedure expose test; parse arg a,b,#; $= 0; h= (b-a)/# - do x=a+h by h for #; $= $ + f(x) - end /*x*/ - return $*h/1 -/*──────────────────────────────────────────────────────────────────────────────────────*/ -Simpson: procedure expose test; parse arg a,b,#; h= (b-a)/# - hh= h/2; $= f(a + hh) - @= 0; do x=1 for #-1; hx=h*x + a; @= @ + f(hx) - $= $ + f(hx + hh) - end /*x*/ +say 'NUMERICAL INTEGRATION: COMPARE 6 METHODS' +say version +say +w=Digits()+2 +say Left('Function',11) Left( 'Range',w+4) Left('Method',9) Left( 'Steps',7), + Left('Result',w) Left('True',w) ' Error' +say +call Task 'x**3', 0, 1, 100, 1/4 +call Task '1/x', 1, 100, 1000, Ln(100)/1 +call Task 'x', 0, 5000, 1000000, 12500000 +call Task 'x', 0, 5000, 4, 12500000 +call Task '4/(x**2+1)', 0, 1, 100, Pi()/1 +call Task '4/(x**2+1)', 0, 1, 1000, Pi()/1 +call Task 'Sin(x)', 0, Pi()/1, 100, 2 +call Task 'Sin(x)', 0, Pi()/1, 10000, 2 +call Task 'Cos(x)', 0, Pi()/1, 100, 0 +call Task 'Cos(x)', 0, Pi()/1, 10000, 0 +call Task 'Tan(x)', 0, Pi()/1, 100, 0 +call Task 'Tan(x)', 0, Pi()/1, 10000, 0 +call Task 'Exp(x)', -3, 3, 100, Exp(3)-Exp(-3) +call Task 'Exp(x)', -3, 3, 10000, Exp(3)-Exp(-3) +call Task 'Gamma(x)', 1, 8, 100, 2603.238829328642145 +call Task 'Gamma(x)', 1, 8, 10000, 2603.238829328642145 +call Timer +exit - return h * (f(a) + f(b) + 4*$ + 2*@) / 6 -/*──────────────────────────────────────────────────────────────────────────────────────*/ -trapezium: procedure expose test; parse arg a,b,#; $= 0; h= (b-a)/# - do x=a by h for #; $= $ + (f(x) + f(x+h)) - end /*x*/ - return $*h/2 +Task: +procedure expose Memo. +arg ff,aa,bb,steps,true +w=Digits()+2 +res=LeftRect(ff,aa,bb,steps); diff=res-true +say Left(ff,11) Left(aa '-' bb,w+4) Left('LeftRect',9) Left(steps,7), + Left(Std(res),w) Left(true,w) Format(diff,2,4,,0) +res=MidRect(ff,aa,bb,steps); diff=res-true +say Left(ff,11) Left(aa '-' bb,w+4) Left('MidRect',9) Left(steps,7), + Left(Std(res),w) Left(true,w) Format(diff,2,4,,0) +res=RightRect(ff,aa,bb,steps); diff=res-true +say Left(ff,11) Left(aa '-' bb,w+4) Left('RightRect',9) Left(steps,7), + Left(Std(res),w) Left(true,w) Format(diff,2,4,,0) +res=Trapezoid(ff,aa,bb,steps); diff=res-true +say Left(ff,11) Left(aa '-' bb,w+4) Left('Trapezoid',9) Left(steps,7), + Left(Std(res),w) Left(true,w) Format(diff,2,4,,0) +res=Simpson(ff,aa,bb,steps); diff=res-true +say Left(ff,11) Left(aa '-' bb,w+4) Left('Simpson',9) Left(steps,7), + Left(Std(res),w) Left(true,w) Format(diff,2,4,,0) +res=Boole(ff,aa,bb,steps); diff=res-true +say Left(ff,11) Left(aa '-' bb,w+4) Left('Boole',9) Left(steps,7), + Left(Std(res),w) Left(true,w) Format(diff,2,4,,0) +say +return + +LeftRect: +procedure expose Memo. +arg ff,aa,bb,steps +h=(bb-aa)/steps +s=0 +do n = 0 to steps-1 + s=s+Eval(ff,aa+n*h) +end +return s*h + +MidRect: +procedure expose Memo. +arg ff,aa,bb,steps +h=(bb-aa)/steps; aa=aa-h/2 +s=0 +do n = 1 to steps + s=s+Eval(ff,aa+n*h) +end +return s*h + +RightRect: +procedure expose Memo. +arg ff,aa,bb,steps +h=(bb-aa)/steps +s=0 +do n = 1 to steps + s=s+Eval(ff,aa+n*h) +end +return s*h + +Trapezoid: +procedure expose Memo. +arg ff,aa,bb,steps +h=(bb-aa)/steps +s=0.5*(Eval(ff,aa)+Eval(ff,bb)) +do n = 1 to steps-1 + s=s+Eval(ff,aa+n*h) +end +return s*h + +Simpson: +procedure expose Memo. +arg ff,aa,bb,steps +h=(bb-aa)/steps +s0=Eval(ff,aa)+Eval(ff,bb); s1=0; s2=0 +do n = 1 by 2 to steps-1 + s1=s1+Eval(ff,aa+n*h) +end +do n = 2 by 2 to steps-2 + s2=s2+Eval(ff,aa+n*h) +end +return (s0+4*s1+2*s2)*h/3 + +Boole: +procedure expose Memo. +arg ff,aa,bb,steps +h=(bb-aa)/steps +s0=7*(Eval(ff,aa)+Eval(ff,bb)); s1=0; s2=0; s3=0 +do n = 1 by 2 to steps-1 + s1=s1+Eval(ff,aa+n*h) +end +do n = 2 by 4 to steps-2 + s2=s2+Eval(ff,aa+n*h) +end +do n = 4 by 4 to steps-4 + s3=s3+Eval(ff,aa+n*h) +end +return (s0+32*s1+12*s2+14*s3)*2*h/45 + +-- Sin; Cos; Tan; Exp; Gamma +include Math diff --git a/Task/Numerical-integration/Rust/numerical-integration.rust b/Task/Numerical-integration/Rust/numerical-integration.rs similarity index 100% rename from Task/Numerical-integration/Rust/numerical-integration.rust rename to Task/Numerical-integration/Rust/numerical-integration.rs diff --git a/Task/Numerical-integration/Scheme/numerical-integration.ss b/Task/Numerical-integration/Scheme/numerical-integration.scm similarity index 100% rename from Task/Numerical-integration/Scheme/numerical-integration.ss rename to Task/Numerical-integration/Scheme/numerical-integration.scm diff --git a/Task/OLE-automation/FreeBASIC/ole-automation.basic b/Task/OLE-automation/FreeBASIC/ole-automation.basic new file mode 100644 index 0000000000..0e10fd575c --- /dev/null +++ b/Task/OLE-automation/FreeBASIC/ole-automation.basic @@ -0,0 +1,35 @@ +#include "disphelper/disphelper.bi" + +dhInitialize(True) +dhToggleExceptions(True) + +Dim As IDispatch Ptr wordApp, document, content +Dim As IDispatch Ptr paragraphs, paragraph, rnge + +OleInitialize(NULL) +dhCreateObject("Word.Application", NULL, @wordApp) +dhPutValue(wordApp, ".Visible = %b", True) +dhGetValue("%o", @documents, wordApp, ".Documents") +dhCallMethod(documents, "Add", @document) +dhGetValue("%o", @content, document, ".Content") +dhGetValue("%o", @paragraphs, content, ".Paragraphs") +dhCallMethod(paragraphs, "Add", @paragraph) +dhGetValue("%o", @rnge, paragraph, ".Range") +dhPutValue(rnge, ".Text = %s", "This is a Rosetta Code test document.") + +Sleep 10000 ' Wait 10 seconds + +dhPutValue(document, ".Saved = %b", True) +dhCallMethod(document, "Close(%b)", False) +dhCallMethod(wordApp, "Quit") + +SAFE_RELEASE(wordApp) +SAFE_RELEASE(documents) +SAFE_RELEASE(document) +SAFE_RELEASE(content) +SAFE_RELEASE(paragraphs) +SAFE_RELEASE(paragraph) +SAFE_RELEASE(rnge) + +OleUninitialize() +dhUninitialize(True) diff --git a/Task/OLE-automation/Julia/ole-automation.jl b/Task/OLE-automation/Julia/ole-automation.jl new file mode 100644 index 0000000000..f93c3c259c --- /dev/null +++ b/Task/OLE-automation/Julia/ole-automation.jl @@ -0,0 +1,34 @@ +using PyCall + +function demoCOM() + # Import Python's win32com.client and time modules + win32com = pyimport("win32com.client") + + # Initialize COM + win32com.CoInitialize() + + # Create Word.Application object + word = win32com.Dispatch("Word.Application") + + # set up new document + word.Visible = true + documents = word.Documents + document = documents.Add() + content = document.Content + paragraphs = content.Paragraphs + + # add the new paragraph of text + paragraph = paragraphs.Add() + rnge = paragraph.Range + rnge.Text = "This is a Rosetta Code test document." + + # wait for Windows to run the requests, then close + sleep(5) + document.Saved = true + document.Close(false) + + word.Quit() + win32com.CoUninitialize() +end + +demoCOM() diff --git a/Task/Object-serialization/Ada/object-serialization-1.ada b/Task/Object-serialization/Ada/object-serialization-1.adb similarity index 100% rename from Task/Object-serialization/Ada/object-serialization-1.ada rename to Task/Object-serialization/Ada/object-serialization-1.adb diff --git a/Task/Object-serialization/Ada/object-serialization-2.ada b/Task/Object-serialization/Ada/object-serialization-2.adb similarity index 100% rename from Task/Object-serialization/Ada/object-serialization-2.ada rename to Task/Object-serialization/Ada/object-serialization-2.adb diff --git a/Task/Object-serialization/Ada/object-serialization-3.ada b/Task/Object-serialization/Ada/object-serialization-3.adb similarity index 100% rename from Task/Object-serialization/Ada/object-serialization-3.ada rename to Task/Object-serialization/Ada/object-serialization-3.adb diff --git a/Task/Object-serialization/C++/object-serialization.cpp b/Task/Object-serialization/C++/object-serialization.cpp index b0c9bb597d..4cd843cf40 100644 --- a/Task/Object-serialization/C++/object-serialization.cpp +++ b/Task/Object-serialization/C++/object-serialization.cpp @@ -12,7 +12,7 @@ public : Employee ( const std::string &dep , const std::string &namen ) : department( dep ) , name( namen ) { - my_id = count++ ; + my_id = count++ ; } std::string getName( ) const { @@ -47,9 +47,9 @@ private : template void serialize( Archive &ar, const unsigned int version ) { - ar & my_id ; - ar & name ; - ar & department ; + ar & my_id ; + ar & name ; + ar & department ; } } ; @@ -57,7 +57,7 @@ private : class Worker : public Employee { public : Worker( const std::string & dep, const std::string &namen , - double hourlyPay ) : Employee( dep , namen ) , salary( hourlyPay) { } + double hourlyPay ) : Employee( dep , namen ) , salary( hourlyPay) { } Worker( ) { } @@ -67,7 +67,7 @@ public : void setSalary( double pay ) { if ( pay > 0 ) - salary = pay ; + salary = pay ; } virtual void print( ) { @@ -79,8 +79,8 @@ private : friend class boost::serialization::access ; template void serialize ( Archive & ar, const unsigned int version ) { - ar & boost::serialization::base_object( *this ) ; - ar & salary ; + ar & boost::serialization::base_object( *this ) ; + ar & salary ; } } ; diff --git a/Task/Object-serialization/EchoLisp/object-serialization-1.l b/Task/Object-serialization/EchoLisp/object-serialization-1.l index 62c373d399..12c37e0687 100644 --- a/Task/Object-serialization/EchoLisp/object-serialization-1.l +++ b/Task/Object-serialization/EchoLisp/object-serialization-1.l @@ -1,11 +1,11 @@ (define (person->string self) (format "%a : person." (person-name self))) (define (writer->string self) (format "%a: writer of %a." - (person-name self) - (writer-books self))) + (person-name self) + (writer-books self))) (define (father->string self) (format "%a: father of %a." - (person-name self) - (map person-name (father-children self)))) - + (person-name self) + (map person-name (father-children self)))) + ; 'classes' definition, with inheritance. ; a writer is a person, too. (struct person (name) #:tostring person->string) diff --git a/Task/Object-serialization/Erlang/object-serialization.erl b/Task/Object-serialization/Erlang/object-serialization.erl index f7b0f04e10..6a69470a99 100644 --- a/Task/Object-serialization/Erlang/object-serialization.erl +++ b/Task/Object-serialization/Erlang/object-serialization.erl @@ -6,23 +6,23 @@ -record( person, {entity, email} ). task() -> - Person = #person{entity=#entity{name="Cletus", date=20080808}, email="test+1@localhost.localdomain"}, - print( Person ), - Entity = #entity{name="Entity", date=20111111}, - print( Entity ), - ok = file:write_file( "objects.dat", erlang:term_to_binary([Person, Entity]) ), - {ok, Binary} = file:read_file( "objects.dat" ), - [New_person, New_entity] = erlang:binary_to_term( Binary ), - io:fwrite( "Deserialized\n" ), - print( New_person ), - print( New_entity ). - + Person = #person{entity=#entity{name="Cletus", date=20080808}, email="test+1@localhost.localdomain"}, + print( Person ), + Entity = #entity{name="Entity", date=20111111}, + print( Entity ), + ok = file:write_file( "objects.dat", erlang:term_to_binary([Person, Entity]) ), + {ok, Binary} = file:read_file( "objects.dat" ), + [New_person, New_entity] = erlang:binary_to_term( Binary ), + io:fwrite( "Deserialized\n" ), + print( New_person ), + print( New_entity ). + print( #entity{name=Name, date=Date} ) -> - io:fwrite( "Entity: " ), - io:fwrite( "name: ~p, date: ~p~n", [Name, Date] ); + io:fwrite( "Entity: " ), + io:fwrite( "name: ~p, date: ~p~n", [Name, Date] ); print( #person{entity=Entity, email=Email} ) -> - io:fwrite( "Person: " ), - print( Entity ), - io:fwrite( "\temail: ~p~n", [Email] ). + io:fwrite( "Person: " ), + print( Entity ), + io:fwrite( "\temail: ~p~n", [Email] ). diff --git a/Task/Object-serialization/Julia/object-serialization.julia b/Task/Object-serialization/Julia/object-serialization.jl similarity index 100% rename from Task/Object-serialization/Julia/object-serialization.julia rename to Task/Object-serialization/Julia/object-serialization.jl diff --git a/Task/Object-serialization/Kotlin/object-serialization.kotlin b/Task/Object-serialization/Kotlin/object-serialization.kts similarity index 100% rename from Task/Object-serialization/Kotlin/object-serialization.kotlin rename to Task/Object-serialization/Kotlin/object-serialization.kts diff --git a/Task/Object-serialization/OCaml/object-serialization.ocaml b/Task/Object-serialization/OCaml/object-serialization.ml similarity index 100% rename from Task/Object-serialization/OCaml/object-serialization.ocaml rename to Task/Object-serialization/OCaml/object-serialization.ml diff --git a/Task/Object-serialization/Objective-C/object-serialization.m b/Task/Object-serialization/Objective-C/object-serialization.m index d6b6aecd64..28009c1150 100644 --- a/Task/Object-serialization/Objective-C/object-serialization.m +++ b/Task/Object-serialization/Objective-C/object-serialization.m @@ -102,17 +102,17 @@ int main() // let us create a fantasy animal Animal *anAnimal = [[Animal alloc] - initWithName: @"Eptohippos" - andLegs: 7 - ]; + initWithName: @"Eptohippos" + andLegs: 7 + ]; // for some reason an Eptohippos is not an horse with 7 legs, // and it is not a mammal, of course... // let us create a fantasy mammal (which is an animal too) Mammal *aMammal = [[Mammal alloc] - initWithName: @"Mammaluc" - hasFur: YES - ]; + initWithName: @"Mammaluc" + hasFur: YES + ]; // let us add some eaten stuff... [aMammal addEatenThing: @"lamb"]; [aMammal addEatenThing: @"table"]; @@ -129,7 +129,7 @@ int main() // now let us store the objects... NSMutableData *data = [[NSMutableData alloc] init]; NSKeyedArchiver *arch = [[NSKeyedArchiver alloc] - initForWritingWithMutableData: data]; + initForWritingWithMutableData: data]; [arch encodeObject: anAnimal forKey: @"Eptohippos"]; [arch encodeObject: aMammal forKey: @"Mammaluc"]; [arch finishEncoding]; @@ -137,9 +137,9 @@ int main() // now we want to retrieve the saved objects... NSData *ldata = [[NSData alloc] - initWithContentsOfFile: @"objects.dat"]; + initWithContentsOfFile: @"objects.dat"]; NSKeyedUnarchived *darch = [[NSKeyedUnarchiver alloc] - initForReadingWithData: ldata]; + initForReadingWithData: ldata]; Animal *archivedAnimal = [darch decodeObjectForKey: @"Eptohippos"]; Mammal *archivedMammal = [darch decodeObjectForKey: @"Mammaluc"]; [darch finishDecoding]; diff --git a/Task/Object-serialization/PascalABC.NET/object-serialization.pas b/Task/Object-serialization/PascalABC.NET/object-serialization.pas new file mode 100644 index 0000000000..f6efb176f9 --- /dev/null +++ b/Task/Object-serialization/PascalABC.NET/object-serialization.pas @@ -0,0 +1,32 @@ +type + [Serializable] + Base = class + public + fb: integer; + constructor (fb: integer) := Self.fb := fb; + function ToString: string; override := fb.ToString; + end; + + [Serializable] + Derived = class(Base) + public + fd: real; + constructor (fb: integer; fd: real); + begin + inherited Create(fb); + Self.fd := fd; + end; + function ToString: string; override := inherited ToString + ',' + fd.ToString; + end; + +begin + var lst := new List; + lst.Add(new Base(3)); + lst.Add(new Derived(4,5.5)); + lst.Add(new Base(6)); + lst.Add(new Derived(7,8.8)); + lst.Println; + Serialize('objects.dat',lst); + var lst1 := DeSerialize('objects.dat') as List; + lst1.Println; +end. diff --git a/Task/Object-serialization/Python/object-serialization.py b/Task/Object-serialization/Python/object-serialization.py index 4ad7458567..9b2e5b9324 100644 --- a/Task/Object-serialization/Python/object-serialization.py +++ b/Task/Object-serialization/Python/object-serialization.py @@ -6,14 +6,14 @@ import pickle class Entity: - def __init__(self): - self.name = "Entity" - def printName(self): - print self.name + def __init__(self): + self.name = "Entity" + def printName(self): + print self.name class Person(Entity): #OldMan inherits from Entity - def __init__(self): #override constructor - self.name = "Cletus" + def __init__(self): #override constructor + self.name = "Cletus" instance1 = Person() instance1.printName() diff --git a/Task/Object-serialization/Rebol/object-serialization.rebol b/Task/Object-serialization/Rebol/object-serialization.rebol new file mode 100644 index 0000000000..751b30aa2d --- /dev/null +++ b/Task/Object-serialization/Rebol/object-serialization.rebol @@ -0,0 +1,84 @@ +Rebol [ + title: "Rosetta code: Object serialization" + file: %Object_serialization.r3 + url: https://rosettacode.org/wiki/Object_serialization + needs: 2.7.0 +] +; ---------------------------- +; Define a base "class" Person +; ---------------------------- +; In Rebol, `make object! [...]` creates an object with defined fields (and optionally functions). +; Here, Person has two properties: name (string) and age (integer). +Person: make object! [ + name: "" + age: 0 +] + +; ------------------------------------------------ +; "Inherit" a subclass Student from Person +; ------------------------------------------------ +; Since Rebol doesn't have classical inheritance, `make Person [...]` +; makes a copy of the Person object and lets you add or override fields. +; Student adds an extra property: grade (e.g., "A", "B", etc.) +Student: make Person [ + grade: "" +] + +; ------------------------------------------------ +; Inherit another subclass Teacher from Person +; ------------------------------------------------ +; Teacher adds an extra property: subject (teaching subject) +Teacher: make Person [ + subject: "" +] + +; ---------------------------------- +; Create specific instances of each +; ---------------------------------- +; Values in brackets override default properties when creating the object. +john: make Person [name: "John" age: 40] +sally: make Student [name: "Sally" age: 18 grade: "A"] +bob: make Teacher [name: "Bob" age: 50 subject: "Math"] + +; ------------------------------------------------ +; Print text in yellow (assuming ANSI color functions are set up) +; ------------------------------------------------ +print "Original instances:" + +; ------------------------------------------------ +; `probe` prints the value in developer-readable format and returns it +; This is useful for quickly seeing object content +; ------------------------------------------------ +probe john +probe sally +probe bob + +; ------------------------------------------------ +; Create a block containing all three objects +; `reduce` evaluates each word and inserts its value into the block +; ------------------------------------------------ +objects: reduce [john sally bob] + +; ------------------------------------------------ +; Save all object data (including words, values, and types) to a file +; `save/all` preserves the complete object structure +; ------------------------------------------------ +save/all %objects.dat objects + +; ------------------------------------------------ +; Show header for loaded instances +; ------------------------------------------------ +print "Loaded instances:" + +; ------------------------------------------------ +; Load objects back from the file +; `load` reconstructs the original structures from the saved format +; ------------------------------------------------ +read-objects: load %objects.dat + +; ------------------------------------------------ +; Iterate over loaded objects and display them +; ------------------------------------------------ +foreach obj read-objects [ + probe obj +] diff --git a/Task/Object-serialization/Rust/object-serialization-1.rust b/Task/Object-serialization/Rust/object-serialization-1.rs similarity index 100% rename from Task/Object-serialization/Rust/object-serialization-1.rust rename to Task/Object-serialization/Rust/object-serialization-1.rs diff --git a/Task/Object-serialization/Rust/object-serialization-2.rust b/Task/Object-serialization/Rust/object-serialization-2.rs similarity index 100% rename from Task/Object-serialization/Rust/object-serialization-2.rust rename to Task/Object-serialization/Rust/object-serialization-2.rs diff --git a/Task/Object-serialization/Rust/object-serialization-3.rust b/Task/Object-serialization/Rust/object-serialization-3.rs similarity index 100% rename from Task/Object-serialization/Rust/object-serialization-3.rust rename to Task/Object-serialization/Rust/object-serialization-3.rs diff --git a/Task/Object-serialization/Rust/object-serialization-4.rust b/Task/Object-serialization/Rust/object-serialization-4.rs similarity index 100% rename from Task/Object-serialization/Rust/object-serialization-4.rust rename to Task/Object-serialization/Rust/object-serialization-4.rs diff --git a/Task/Odd-word-problem/ALGOL-68/odd-word-problem.alg b/Task/Odd-word-problem/ALGOL-68/odd-word-problem.alg index 8e1260cbd0..54e245a6ca 100644 --- a/Task/Odd-word-problem/ALGOL-68/odd-word-problem.alg +++ b/Task/Odd-word-problem/ALGOL-68/odd-word-problem.alg @@ -1,75 +1,51 @@ -# recursively reverses the current word in the input and returns the # -# the character that followed it # -# "ch" should contain the first letter of the word on entry and will be # -# updated to the punctuation following the word on exit # -PROC reverse word = ( REF CHAR ch )VOID: BEGIN - CHAR next ch; - - read( ( next ch ) ); - - IF ( next ch <= "Z" AND next ch >= "A" ) - OR ( next ch <= "z" AND next ch >= "a" ) - THEN - reverse word( next ch ) - FI; - - print( ( ch ) ); - - ch := next ch - -END; # reverse word # - - - -# recursively prints the current word in the input and returns the # -# character that followed it # -# "ch" should contain the first letter of the word on entry and will be # -# updated to the punctuation following the word on exit # -PROC normal word = ( REF CHAR ch )VOID: -BEGIN - - print( ( ch ) ); - read ( ( ch ) ); - - IF ( ch <= "Z" AND ch >= "A" ) - OR ( ch <= "z" AND ch >= "a" ) - THEN - normal word( ch ) - FI - -END; # normal word # - - - -# read and print words and punctuation from the input stream, reversing # -# every second word # -PROC reverse every other word = VOID: -BEGIN - - CHAR ch; - - read( ( ch ) ); - - WHILE - ch /= "." - DO - normal word( ch ); - IF ch /= "." - THEN + # recursively reverses the current word in the input and returns the # + # the character that followed it # + # "ch" should contain the first letter of the word on entry and will be # + # updated to the punctuation following the word on exit # + PROC reverse word = ( REF CHAR ch )VOID: + BEGIN + CHAR next ch; + read( ( next ch ) ); + IF ( next ch <= "Z" AND next ch >= "A" ) + OR ( next ch <= "z" AND next ch >= "a" ) + THEN + reverse word( next ch ) + FI; print( ( ch ) ); + ch := next ch + END # reverse word # ; + + # recursively prints the current word in the input and returns the # + # character that followed it # + # "ch" should contain the first letter of the word on entry and will be # + # updated to the punctuation following the word on exit # + PROC normal word = ( REF CHAR ch )VOID: + IF print( ( ch ) ); read ( ( ch ) ); - reverse word( ch ) - FI - OD; + ( ch <= "Z" AND ch >= "A" ) + OR ( ch <= "z" AND ch >= "a" ) + THEN + normal word( ch ) + FI # normal word # ; - print( ( ch ) ) + # read and print words and punctuation from the input stream, reversing # + # every second word # + PROC reverse every other word = VOID: + BEGIN + CHAR ch; + read( ( ch ) ); + WHILE ch /= "." DO + normal word( ch ); + IF ch /= "." THEN + print( ( ch ) ); + read ( ( ch ) ); + reverse word( ch ) + FI + OD; + print( ( ch ) ) + END; # reverse every other word # -END; # reverse every other word # - - - -main: ( reverse every other word -) +END diff --git a/Task/Odd-word-problem/Ada/odd-word-problem.ada b/Task/Odd-word-problem/Ada/odd-word-problem.adb similarity index 100% rename from Task/Odd-word-problem/Ada/odd-word-problem.ada rename to Task/Odd-word-problem/Ada/odd-word-problem.adb diff --git a/Task/Odd-word-problem/Delphi/odd-word-problem.delphi b/Task/Odd-word-problem/Delphi/odd-word-problem.pas similarity index 100% rename from Task/Odd-word-problem/Delphi/odd-word-problem.delphi rename to Task/Odd-word-problem/Delphi/odd-word-problem.pas diff --git a/Task/Odd-word-problem/EasyLang/odd-word-problem.easy b/Task/Odd-word-problem/EasyLang/odd-word-problem.easy index 23f334b2fb..0dd0bab09e 100644 --- a/Task/Odd-word-problem/EasyLang/odd-word-problem.easy +++ b/Task/Odd-word-problem/EasyLang/odd-word-problem.easy @@ -4,16 +4,12 @@ func$ read . return substr inp$ inpi 1 . func ispunct c$ . - if c$ = "." or c$ = ":" or c$ = ";" or c$ = "," - return 1 - . + if c$ = "." or c$ = ":" or c$ = ";" or c$ = "," : return 1 return 0 . func$ handle odd . c$ = read - if ispunct c$ = 1 - return c$ - . + if ispunct c$ = 1 : return c$ if odd = 0 write c$ r$ = handle 0 @@ -24,7 +20,7 @@ func$ handle odd . return r$ . . -proc go . . +proc go . repeat c$ = handle odd write c$ diff --git a/Task/Odd-word-problem/Elixir/odd-word-problem.elixir b/Task/Odd-word-problem/Elixir/odd-word-problem.ex similarity index 100% rename from Task/Odd-word-problem/Elixir/odd-word-problem.elixir rename to Task/Odd-word-problem/Elixir/odd-word-problem.ex diff --git a/Task/Odd-word-problem/Julia/odd-word-problem.julia b/Task/Odd-word-problem/Julia/odd-word-problem.jl similarity index 100% rename from Task/Odd-word-problem/Julia/odd-word-problem.julia rename to Task/Odd-word-problem/Julia/odd-word-problem.jl diff --git a/Task/Odd-word-problem/Kotlin/odd-word-problem.kotlin b/Task/Odd-word-problem/Kotlin/odd-word-problem.kts similarity index 100% rename from Task/Odd-word-problem/Kotlin/odd-word-problem.kotlin rename to Task/Odd-word-problem/Kotlin/odd-word-problem.kts diff --git a/Task/Odd-word-problem/Nom/odd-word-problem.num b/Task/Odd-word-problem/Nom/odd-word-problem.num new file mode 100644 index 0000000000..ab7a43f37b --- /dev/null +++ b/Task/Odd-word-problem/Nom/odd-word-problem.num @@ -0,0 +1,23 @@ +#* +GRAMMAR PARSE TOKENS + no tokens required, except to store odd/even state + +HISTORY + 13 sept 2021: written + +*# + + begin { add "odd*"; push; } + read; + [:alpha:] { + pop; + B"odd*" { push; get; put; clear; } + B"even*" { push; swap; get; put; clear; } + } + ![:alpha:].!"" { + pop; + B"odd*" { replace "odd*" "even*"; push; } + B"even*" { replace "even*" "odd*"; push; } + swap; print; clear; swap; print; clear; + } + (eof) { get; print; } diff --git a/Task/Odd-word-problem/OCaml/odd-word-problem.ocaml b/Task/Odd-word-problem/OCaml/odd-word-problem.ml similarity index 100% rename from Task/Odd-word-problem/OCaml/odd-word-problem.ocaml rename to Task/Odd-word-problem/OCaml/odd-word-problem.ml diff --git a/Task/Odd-word-problem/PascalABC.NET/odd-word-problem.pas b/Task/Odd-word-problem/PascalABC.NET/odd-word-problem.pas new file mode 100644 index 0000000000..ff11f731ed --- /dev/null +++ b/Task/Odd-word-problem/PascalABC.NET/odd-word-problem.pas @@ -0,0 +1,33 @@ +var + alpha := ('a'..'z') + ('A'..'Z'); + +procedure reverseWord(var ch: char); +begin + var nextch := readChar(); + if nextch in alpha then reverseWord(nextch); + write(ch); + ch := nextch; +end; + +procedure normalWord(var ch: char); +begin + write(ch); + ch := readChar(); + if ch in alpha then normalWord(ch); +end; + +begin + var ch := readChar(); + + while ch <> '.' do + begin + normalWord(ch); + if ch <> '.' then + begin + write(ch); + ch := readChar(); + reverseWord(ch); + end; + end; + write(ch) +end. diff --git a/Task/Odd-word-problem/Scheme/odd-word-problem.ss b/Task/Odd-word-problem/Scheme/odd-word-problem.scm similarity index 100% rename from Task/Odd-word-problem/Scheme/odd-word-problem.ss rename to Task/Odd-word-problem/Scheme/odd-word-problem.scm diff --git a/Task/Old-Russian-measure-of-length/ANSI-BASIC/old-russian-measure-of-length.basic b/Task/Old-Russian-measure-of-length/ANSI-BASIC/old-russian-measure-of-length.basic new file mode 100644 index 0000000000..1e53a70baa --- /dev/null +++ b/Task/Old-Russian-measure-of-length/ANSI-BASIC/old-russian-measure-of-length.basic @@ -0,0 +1,47 @@ +100 REM Old Russian measure of length +110 LET UnitsLength = 13 +120 DIM Units$(1 TO 13), Convs(1 TO 13) +130 REM DIM Units$(1 TO UnitsLength), Convs(1 TO UnitsLength) allowed in some implementations +140 FOR I = 1 TO UnitsLength +150 READ Units$(I) +160 NEXT I +170 DATA tochka, liniya, dyuim, vershok, piad, fut +180 DATA arshin, sazhen, versta, milia, centimeter, meter, kilometer +190 REM All expressed in centimeters +200 FOR I = 1 TO UnitsLength +210 READ Convs(I) +220 NEXT I +230 DATA 0.0254, 0.254, 2.54, 4.445, 17.78, 30.48 +240 DATA 71.12, 213.36, 106680, 746760, 1, 100, 100000 +250 DO +260 PRINT "------------" +270 PRINT +280 FOR I = 1 TO UnitsLength +290 PRINT USING "## ": I; +300 PRINT Units$(I) +310 NEXT I +320 PRINT +330 DO +340 INPUT PROMPT "Please choose a unit 1 to " & STR$(UnitsLength) & " :": Unit +350 LOOP UNTIL (Unit >= 1) AND (Unit <= UnitsLength) +360 DO +370 INPUT PROMPT "Now enter a value in that unit :": Value +380 LOOP UNTIL Value > 0 +390 PRINT +400 PRINT "The equivalent in the remaining units is:" +410 PRINT +420 FOR I = 1 TO UnitsLength +430 IF I <> Unit THEN +440 PRINT USING "#######.######## ": Value * Convs(Unit) / Convs(I); +450 PRINT Units$(I); "(s)" +460 END IF +470 NEXT I +480 PRINT +490 DO +500 INPUT PROMPT "Do another one y/n :": YN$ +510 LET YN$ = LCASE$(YN$) +520 LOOP UNTIL (YN$ = "y") OR (YN$ = "n") +530 PRINT +540 LOOP UNTIL YN$ = "n" +550 PRINT "End of story" +560 END diff --git a/Task/Old-Russian-measure-of-length/ASIC/old-russian-measure-of-length.asic b/Task/Old-Russian-measure-of-length/ASIC/old-russian-measure-of-length.asic new file mode 100644 index 0000000000..2c083f3305 --- /dev/null +++ b/Task/Old-Russian-measure-of-length/ASIC/old-russian-measure-of-length.asic @@ -0,0 +1,65 @@ +REM Old Russian measure of length +DIM Units$(12) +DIM Convs@(12) +DATA "tochka", "liniya", "dyuim", "vershok", "piad", "fut" +DATA "arshin", "sazhen", "versta", "milia", "centimeter", "meter", "kilometer" +DATA 0.0254, 0.254, 2.54, 4.445, 17.78, 30.48 +DATA 71.12, 213.36, 106680.0, 746760.0, 1.0, 100.0, 100000.0 +MaxIndex = 12 +NumOfUnits = MaxIndex + 1 +FOR I = 0 TO MaxIndex + READ Units$(I) +NEXT I +FOR I = 0 TO MaxIndex + READ Convs@(I) +NEXT I +Start: + CLS + PRINT + FOR I = 0 TO MaxIndex + IPl1 = I + 1 + PRINT IPl1; + PRINT " "; + PRINT Units$(I) + NEXT I + NU$ = STR$(NumOfUnits) + NU$ = LTRIM$(NU$) + ChooseUnit: + PRINT "Please choose a unit from 1 to "; + PRINT NU$; + PRINT ": "; + INPUT Unit + IF Unit > NumOfUnits THEN ChooseUnit: + IF Unit < 1 THEN ChooseUnit: + Unit = Unit - 1 + EnterVal: + PRINT "Now enter a value in that unit: "; + INPUT V@ + IF V@ <= 0 THEN EnterVal: + CLS + PRINT + PRINT V@; + PRINT " "; + PRINT Units$(Unit); + PRINT "(s) in the remaining units is:" + FOR I = 0 TO MaxIndex + IF I <> Unit THEN + Equiv@ = V@ * Convs@(Unit) + Equiv@ = Equiv@ / Convs@(I) + PRINT Equiv@; + PRINT " "; + PRINT Units$(I); + PRINT "(s)" + ENDIF + NEXT I + AskDoAnother: + PRINT "Do another one y/n"; + INPUT YN$ + YN$ = LCASE$(YN$) + IF YN$ = "n" THEN EndOfStory: + IF YN$ = "y" THEN Start: + GOTO AskDoAnother: + PRINT +EndOfStory: +PRINT "End of story." +END diff --git a/Task/Old-Russian-measure-of-length/Ada/old-russian-measure-of-length.adb b/Task/Old-Russian-measure-of-length/Ada/old-russian-measure-of-length.adb new file mode 100644 index 0000000000..9a9d2c4a94 --- /dev/null +++ b/Task/Old-Russian-measure-of-length/Ada/old-russian-measure-of-length.adb @@ -0,0 +1,36 @@ +with Ada.Wide_Text_IO; use Ada.Wide_Text_IO; +with Float_Measures; use Float_Measures; +with Float_Measures_UTF8_Edit; use Float_Measures_UTF8_Edit; +with Float_Measures_Irregular; use Float_Measures_Irregular; +with Strings_Edit.Floats; use Strings_Edit.Floats; +with Strings_Edit.UTF8.Handling; + +procedure Old_Russian_Measure_of_Length is + function "&" (Left : Wide_String; Right : String) return Wide_String is + begin + return Left & Strings_Edit.UTF8.Handling.To_Wide_String (Right); + end "&"; + Аршин : constant Measure := 0.7112 * m; + Линия : constant Measure := 0.00254 * m; + Миля : constant Measure := 7467.6 * m; + Пядь : constant Measure := 0.1778 * m; + Сажень : constant Measure := 2.1336 * m; + Точка : constant Measure := 0.000254 * m; + Вершок : constant Measure := 0.04445 * m; + Верста : constant Measure := 1066.8 * m; +begin + Put_Line ("Аршинов в метре " & Image (Get_Value_As (m, Аршин))); + Put_Line ("Сантиметроы в метре " & Image (Get_Value_As (m, 0.01 * m))); + Put_Line ("Дюймов в метре " & Image (Get_Value_As (m, inch))); + Put_Line ("Футов в метре " & Image (Get_Value_As (m, ft))); + Put_Line ("Линий в метре " & Image (Get_Value_As (m, Линия))); + Put_Line ("Миль в метре " & Image (Get_Value_As (m, Миля))); + Put_Line ("Пядей в метре " & Image (Get_Value_As (m, Пядь))); + Put_Line ("Метров в метре " & Image (Get_Value_As (m, m))); + Put_Line ("Саженей в метре " & Image (Get_Value_As (m, Сажень))); + Put_Line ("Точек в метре " & Image (Get_Value_As (m, Точка))); + Put_Line ("Вершков в метре " & Image (Get_Value_As (m, Вершок))); + Put_Line ("Вёрст в метре " & Image (Get_Value_As (m, Верста))); + Put_Line ("Аршинн на пядь " & Image (Аршин * Пядь)); + Put_Line ("Кубическая сажень " & Image (Сажень ** 3)); +end Old_Russian_Measure_of_Length; diff --git a/Task/Old-Russian-measure-of-length/BASIC256/old-russian-measure-of-length.basic b/Task/Old-Russian-measure-of-length/BASIC256/old-russian-measure-of-length.basic index 1ded06cd1e..cfe373328b 100644 --- a/Task/Old-Russian-measure-of-length/BASIC256/old-russian-measure-of-length.basic +++ b/Task/Old-Russian-measure-of-length/BASIC256/old-russian-measure-of-length.basic @@ -1,7 +1,7 @@ arraybase 1 dim units = {"tochka", "liniya", "dyuim", "vershok", "piad", "fut", "arshin", "sazhen", "versta", "milia", "centimeter", "meter", "kilometer"} # all expressed in centimeters -dim convs = {0.0254, 0.254, 2.54, 4.445, 17.78, 30.48, 71.12, 213.36, 10668, 74676, 1, 100, 10000} +dim convs = {0.0254, 0.254, 2.54, 4.445, 17.78, 30.48, 71.12, 213.36, 106680, 746760, 1, 100, 100000} do cls diff --git a/Task/Old-Russian-measure-of-length/Delphi/old-russian-measure-of-length.delphi b/Task/Old-Russian-measure-of-length/Delphi/old-russian-measure-of-length.delphi deleted file mode 100644 index 3171a11df1..0000000000 --- a/Task/Old-Russian-measure-of-length/Delphi/old-russian-measure-of-length.delphi +++ /dev/null @@ -1,75 +0,0 @@ -program Old_Russian_measure_of_length; - -{$APPTYPE CONSOLE} - -uses - System.SysUtils; - -const - units: array[0..12] of string = ('tochka', 'liniya', 'dyuim', 'vershok', - 'piad', 'fut', 'arshin', 'sazhen', 'versta', 'milia', 'centimeter', 'meter', - 'kilometer'); - convs: array[0..12] of double = (0.0254, 0.254, 2.54, 4.445, 17.78, 30.48, - 71.12, 213.36, 10668, 74676, 1, 100, 10000); - -function ReadInt(): integer; -var - data: string; -begin - Readln(data); - Result := StrToIntDef(data, -1); -end; - -function ReadFloat(): Double; -var - data: string; -begin - Readln(data); - Result := StrToFloatDef(data, -1); -end; - -var - yn, u: string; - i, unt: integer; - value: Double; - -begin - - repeat - for i := 0 to High(units) do - begin - u := units[i]; - Writeln(format('%2d %s', [i + 1, u])); - end; - Writeln; - - unt := 0; - repeat - Writeln('Please choose a unit 1 to 13 : '); - unt := ReadInt(); - until (unt >= 1) and (unt <= 13); - - dec(unt); - - repeat - Writeln('Now enter a value in that unit : '); - value := ReadFloat(); - until value >= 0; - - Writeln(#10'The equivalent in the remaining units is:'#10); - - for i := 0 to High(units) do - begin - u := units[i]; - if i = unt then - Continue; - Writeln(format(' %10s : %g', [u, value * convs[unt] / convs[i]])); - end; - - Writeln; - - yn := ''; - Writeln('Do another one y/n : '); - readln(yn); - until yn.toLower = 'n'; -end. diff --git a/Task/Old-Russian-measure-of-length/Delphi/old-russian-measure-of-length.pas b/Task/Old-Russian-measure-of-length/Delphi/old-russian-measure-of-length.pas new file mode 100644 index 0000000000..0282743228 --- /dev/null +++ b/Task/Old-Russian-measure-of-length/Delphi/old-russian-measure-of-length.pas @@ -0,0 +1,75 @@ +program Old_Russian_measure_of_length; + +{$APPTYPE CONSOLE} + +uses + System.SysUtils; + +const + units: array[0..12] of string = ('tochka', 'liniya', 'dyuim', 'vershok', + 'piad', 'fut', 'arshin', 'sazhen', 'versta', 'milia', 'centimeter', 'meter', + 'kilometer'); + convs: array[0..12] of double = (0.0254, 0.254, 2.54, 4.445, 17.78, 30.48, + 71.12, 213.36, 106680, 746760, 1, 100, 100000); + +function ReadInt(): integer; +var + data: string; +begin + Readln(data); + Result := StrToIntDef(data, -1); +end; + +function ReadFloat(): Double; +var + data: string; +begin + Readln(data); + Result := StrToFloatDef(data, -1); +end; + +var + yn, u: string; + i, unt: integer; + value: Double; + +begin + + repeat + for i := 0 to High(units) do + begin + u := units[i]; + Writeln(format('%2d %s', [i + 1, u])); + end; + Writeln; + + unt := 0; + repeat + Writeln('Please choose a unit 1 to 13 : '); + unt := ReadInt(); + until (unt >= 1) and (unt <= 13); + + dec(unt); + + repeat + Writeln('Now enter a value in that unit : '); + value := ReadFloat(); + until value >= 0; + + Writeln(#10'The equivalent in the remaining units is:'#10); + + for i := 0 to High(units) do + begin + u := units[i]; + if i = unt then + Continue; + Writeln(format(' %10s : %g', [u, value * convs[unt] / convs[i]])); + end; + + Writeln; + + yn := ''; + Writeln('Do another one y/n : '); + readln(yn); + until yn.toLower = 'n'; +end. diff --git a/Task/Old-Russian-measure-of-length/EasyLang/old-russian-measure-of-length.easy b/Task/Old-Russian-measure-of-length/EasyLang/old-russian-measure-of-length.easy index e8f85bebf6..5a81e31690 100644 --- a/Task/Old-Russian-measure-of-length/EasyLang/old-russian-measure-of-length.easy +++ b/Task/Old-Russian-measure-of-length/EasyLang/old-russian-measure-of-length.easy @@ -1,5 +1,5 @@ units$[] = [ "tochka" "liniya" "dyuim" "vershok" "piad" "fut" "arshin" "sazhen" "versta" "milia" "centimeter" "meter" "kilometer" ] -convs[] = [ 0.254 0.254 2.54 4.445 17.78 30.48 71.12 213.36 10668 74676 1 100 10000 ] +convs[] = [ 0.254 0.254 2.54 4.445 17.78 30.48 71.12 213.36 106680 746760 1 100 100000 ] for i to len units$[] print i & ") " & units$[i] . diff --git a/Task/Old-Russian-measure-of-length/Elena/old-russian-measure-of-length.elena b/Task/Old-Russian-measure-of-length/Elena/old-russian-measure-of-length.elena index ae140ceb86..066ea4c2be 100644 --- a/Task/Old-Russian-measure-of-length/Elena/old-russian-measure-of-length.elena +++ b/Task/Old-Russian-measure-of-length/Elena/old-russian-measure-of-length.elena @@ -2,7 +2,7 @@ import system'collections; import system'routines; import extensions; -unit2mult = new Map() +Unit2mult = new Map() .setAt("arshin", 0.7112r) .setAt("centimeter", 0.01r) .setAt("diuym", 0.0254r) @@ -17,25 +17,25 @@ unit2mult = new Map() .setAt("vershok", 0.04445r) .setAt("versta", 1066.8r); -public program() +public Program() { - if (program_arguments.Length != 3) - { console.writeLine("need two arguments - number then units"); AbortException.raise() }; + if (Program_arguments.Length != 3) + { Console.writeLine("need two arguments - number then units"); AbortException.raise() }; - real value := program_arguments[1].toReal(); - string unit := program_arguments[2]; - ifnot (unit2mult.containsKey(unit)) + real value := Program_arguments[1].toReal(); + string unit := Program_arguments[2]; + if:not (Unit2mult.containsKey(unit)) { - console.printLine("only following units are supported:", - unit2mult.selectBy::(x=>x.Item1).asEnumerable()); + Console.printLine("only following units are supported:", + Unit2mult.selectBy::(x=>x.Item1).asEnumerable()); AbortException.raise() }; - console.printLine(value," ",unit," to:"); + Console.printLine(value," ",unit," to:"); - unit2mult.forEach::(u,mlt) + Unit2mult.forEach::(u,mlt) { - console.printPaddingLeft(30, u, ":").printLine(value * unit2mult[unit] / mlt) + Console.printPaddingLeft(30, u, ":").printLine(value * Unit2mult[unit] / mlt) } } diff --git a/Task/Old-Russian-measure-of-length/FreeBASIC/old-russian-measure-of-length.basic b/Task/Old-Russian-measure-of-length/FreeBASIC/old-russian-measure-of-length.basic index 78a3cccda5..77ea8551dc 100644 --- a/Task/Old-Russian-measure-of-length/FreeBASIC/old-russian-measure-of-length.basic +++ b/Task/Old-Russian-measure-of-length/FreeBASIC/old-russian-measure-of-length.basic @@ -6,8 +6,8 @@ Dim units(1 To 13) As String = {"tochka", "liniya", "dyuim", "vershok", "piad", ' all expressed in centimeters Dim convs(1 To 13) As Single = {0.0254, 0.254, 2.54, 4.445, 17.78, 30.48, _ - 71.12, 213.36, 10668, 74676, _ - 1, 100, 10000} + 71.12, 213.36, 106680, 746760, _ + 1, 100, 100000} Dim unit As Integer Dim value As Single Dim yn As String diff --git a/Task/Old-Russian-measure-of-length/GW-BASIC/old-russian-measure-of-length.basic b/Task/Old-Russian-measure-of-length/GW-BASIC/old-russian-measure-of-length.basic new file mode 100644 index 0000000000..8ba8978205 --- /dev/null +++ b/Task/Old-Russian-measure-of-length/GW-BASIC/old-russian-measure-of-length.basic @@ -0,0 +1,35 @@ +100 REM Old Russian measure of length +110 MAX.INDEX = 12 +120 DIM UNITS$(MAX.INDEX), CONVS(MAX.INDEX) +130 DATA tochka, liniya, dyuim, vershok, piad, fut +140 DATA arshin, sazhen, versta, milia, centimeter, meter, kilometer +150 DATA 0.0254, 0.254, 2.54, 4.445, 17.78, 30.48 +160 DATA 71.12, 213.36, 106680, 746760, 1, 100, 100000 +170 FOR I = 0 TO MAX.INDEX +180 READ UNITS$(I) +190 NEXT I +200 FOR I = 0 TO MAX.INDEX +210 READ CONVS(I) +220 NEXT I +230 FOR I = 0 TO MAX.INDEX +240 PRINT USING "## "; I + 1; +250 PRINT UNITS$(I) +260 NEXT I +270 PRINT +280 PRINT "Please choose a unit 1 to"; MAX.INDEX + 1;: INPUT " :", UNIT: IF (UNIT < 1) OR (UNIT > MAX.INDEX + 1) THEN 280 +290 UNIT = UNIT - 1 +300 INPUT "Now enter a value in that unit:", VALUE: IF VALUE <= 0 THEN 300 +310 PRINT +320 PRINT "The equivalent in the remaining units is:" +330 PRINT +340 FOR I = 0 TO MAX.INDEX +350 IF I <> UNIT THEN PRINT USING "#######.######## "; VALUE * CONVS(UNIT) / CONVS(I);: PRINT UNITS$(I); "(s)" +360 NEXT I +370 PRINT +380 INPUT "Do another one y/n"; YN$ +390 IF UN$ <> "" THEN YN$ = CHR$(ASC(LEFT$(YN$, 1)) OR 32) ' GW-BASIC does not have LCASE$ +400 IF (YN$ <> "y") AND (YN$ <> "n") THEN 380 +410 PRINT +420 IF YN$ <> "n" THEN 230 +430 PRINT "End of story." +440 END diff --git a/Task/Old-Russian-measure-of-length/Gambas/old-russian-measure-of-length.gambas b/Task/Old-Russian-measure-of-length/Gambas/old-russian-measure-of-length.gambas index db197da004..c9c0027691 100644 --- a/Task/Old-Russian-measure-of-length/Gambas/old-russian-measure-of-length.gambas +++ b/Task/Old-Russian-measure-of-length/Gambas/old-russian-measure-of-length.gambas @@ -3,7 +3,7 @@ Public Sub Main() Dim units As String[] = ["tochka", "liniya", "dyuim", "vershok", "piad", "fut", "arshin", "sazhen", "versta", "milia", "centimeter", "meter", "kilometer"] ' all expressed in centimeters - Dim convs As Single[] = [0.254, 0.254, 2.54, 4.445, 17.78, 30.48, 71.12, 213.36, 10668, 74676, 1, 100, 10000] + Dim convs As Single[] = [0.254, 0.254, 2.54, 4.445, 17.78, 30.48, 71.12, 213.36, 106680, 746760, 1, 100, 100000] Dim i, unit As Integer Dim value As Single Dim yn As String diff --git a/Task/Old-Russian-measure-of-length/Go/old-russian-measure-of-length.go b/Task/Old-Russian-measure-of-length/Go/old-russian-measure-of-length.go index 012f04d87c..2de3caed73 100644 --- a/Task/Old-Russian-measure-of-length/Go/old-russian-measure-of-length.go +++ b/Task/Old-Russian-measure-of-length/Go/old-russian-measure-of-length.go @@ -17,8 +17,8 @@ func main() { convs := []float32{ 0.0254, 0.254, 2.54, 4.445, 17.78, 30.48, - 71.12, 213.36, 10668, 74676, - 1, 100, 10000, + 71.12, 213.36, 106680, 746760, + 1, 100, 100000, } scanner := bufio.NewScanner(os.Stdin) diff --git a/Task/Old-Russian-measure-of-length/Julia/old-russian-measure-of-length.jl b/Task/Old-Russian-measure-of-length/Julia/old-russian-measure-of-length.jl new file mode 100644 index 0000000000..839c491876 --- /dev/null +++ b/Task/Old-Russian-measure-of-length/Julia/old-russian-measure-of-length.jl @@ -0,0 +1,24 @@ +using Printf + +const UNITS_TO_MULTIPLIERS = [ + "arshin" => 0.7112, "centimeter" => 0.01, "diuym" => 0.0254, + "fut" => 0.3048, "kilometer" => 1000.0, "liniya" => 0.00254, + "meter" => 1.0, "milia" => 7467.6, "piad" => 0.1778, + "sazhen" => 2.1336, "tochka" => 0.000254, "vershok" => 0.04445, + "versta" => 1066.8 +] + +function oldrussianunits() + @assert length(ARGS) == 2 "need two arguments - number then units" + value = tryparse(Float64, ARGS[1]) + @assert !isnothing(value) "first argument must be a number representable as a 64 bit float" + unit = ARGS[2] + idx = findfirst(x -> x[1] == unit, UNITS_TO_MULTIPLIERS) + @assert !isnothing(idx) "only know the following units:\n" * join(map(first, UNITS_TO_MULTIPLIERS), ", ") + println("$value $unit to:") + for (unt, mlt) in UNITS_TO_MULTIPLIERS + @printf(" %10s: %g\n", unt, value * UNITS_TO_MULTIPLIERS[idx][2] / mlt) + end +end + +oldrussianunits() diff --git a/Task/Old-Russian-measure-of-length/Julia/old-russian-measure-of-length.julia b/Task/Old-Russian-measure-of-length/Julia/old-russian-measure-of-length.julia deleted file mode 100644 index e5d3d44c9f..0000000000 --- a/Task/Old-Russian-measure-of-length/Julia/old-russian-measure-of-length.julia +++ /dev/null @@ -1,23 +0,0 @@ -using DataStructures - -const unit2mult = Dict( - "arshin" => 0.7112, "centimeter" => 0.01, "diuym" => 0.0254, - "fut" => 0.3048, "kilometer" => 1000.0, "liniya" => 0.00254, - "meter" => 1.0, "milia" => 7467.6, "piad" => 0.1778, - "sazhen" => 2.1336, "tochka" => 0.000254, "vershok" => 0.04445, - "versta" => 1066.8) - -@assert length(ARGS) == 2 "need two arguments - number then units" - -global value -try value = parse(Float64, ARGS[1]) -catch error("first argument must be a (float) number") end - -if isnull(value) error("first argument must be a (float) number") end -unit = ARGS[2] -@assert unit ∈ keys(unit2mult) "only know the following units:\n" * join(keys(unit2mult), ", ") - -println("$value $unit to:") -for (unt, mlt) in sort(unit2mult) - @printf(" %10s: %g\n", unt, value * unit2mult[unit] / mlt) -end diff --git a/Task/Old-Russian-measure-of-length/Kotlin/old-russian-measure-of-length.kotlin b/Task/Old-Russian-measure-of-length/Kotlin/old-russian-measure-of-length.kotlin deleted file mode 100644 index db0d0e8116..0000000000 --- a/Task/Old-Russian-measure-of-length/Kotlin/old-russian-measure-of-length.kotlin +++ /dev/null @@ -1,45 +0,0 @@ -// version 1.0.6 - -/* clears console on Windows 10 */ -fun cls() = ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor() - -fun main(args: Array) { - val units = listOf("tochka", "liniya", "dyuim", "vershok", "piad", "fut", - "arshin", "sazhen", "versta", "milia", - "centimeter", "meter", "kilometer") - val convs = arrayOf(0.0254f, 0.254f, 2.54f, 4.445f, 17.78f, 30.48f, - 71.12f, 213.36f, 10668.0f, 74676.0f, - 1.0f, 100.0f, 10000.0f) - var unit: Int - var value: Float - var yn : String - do { - cls() - println() - for (i in 0 until units.size) println("${"%2d".format(i + 1)} ${units[i]}") - println() - do { - print("Please choose a unit 1 to 13 : ") - unit = try { readLine()!!.toInt() } catch (e: NumberFormatException) { 0 } - } - while (unit !in 1..13) - unit-- - do { - print("Now enter a value in that unit : ") - value = try { readLine()!!.toFloat() } catch (e: NumberFormatException) { -1.0f } - } - while (value < 0.0f) - println("\nThe equivalent in the remaining units is:\n") - for (i in 0 until units.size) { - if (i == unit) continue - println(" ${units[i].padEnd(10)} : ${value * convs[unit] / convs[i]}") - } - println() - do { - print("Do another one y/n : ") - yn = readLine()!!.toLowerCase() - } - while (yn != "y" && yn != "n") - } - while (yn == "y") -} diff --git a/Task/Old-Russian-measure-of-length/Kotlin/old-russian-measure-of-length.kts b/Task/Old-Russian-measure-of-length/Kotlin/old-russian-measure-of-length.kts new file mode 100644 index 0000000000..296239c14a --- /dev/null +++ b/Task/Old-Russian-measure-of-length/Kotlin/old-russian-measure-of-length.kts @@ -0,0 +1,47 @@ +// version 2.3.20 + +// Assumes the terminal supports ANSI escape codes. +fun cls() { + println("\u001B[2J") +} + +fun main(args: Array) { + val units = listOf("tochka", "liniya", "dyuim", "vershok", "piad", "fut", + "arshin", "sazhen", "versta", "milia", + "centimeter", "meter", "kilometer") + val convs = arrayOf(0.0254f, 0.254f, 2.54f, 4.445f, 17.78f, 30.48f, + 71.12f, 213.36f, 106680.0f, 746760.0f, + 1.0f, 100.0f, 100000.0f) + var unit: Int + var value: Float + var yn : String + do { + cls() + println() + for (i in 0 until units.size) println("${"%2d".format(i + 1)} ${units[i]}") + println() + do { + print("Please choose a unit 1 to 13 : ") + unit = try { readLine()!!.toInt() } catch (e: NumberFormatException) { 0 } + } + while (unit !in 1..13) + unit-- + do { + print("Now enter a value in that unit : ") + value = try { readLine()!!.toFloat() } catch (e: NumberFormatException) { -1.0f } + } + while (value < 0.0f) + println("\nThe equivalent in the remaining units is:\n") + for (i in 0 until units.size) { + if (i == unit) continue + println(" ${units[i].padEnd(10)} : ${value * convs[unit] / convs[i]}") + } + println() + do { + print("Do another one y/n : ") + yn = readLine()!!.lowercase() + } + while (yn != "y" && yn != "n") + } + while (yn == "y") +} diff --git a/Task/Old-Russian-measure-of-length/Langur/old-russian-measure-of-length.langur b/Task/Old-Russian-measure-of-length/Langur/old-russian-measure-of-length.langur new file mode 100644 index 0000000000..a922833661 --- /dev/null +++ b/Task/Old-Russian-measure-of-length/Langur/old-russian-measure-of-length.langur @@ -0,0 +1,23 @@ +val unit2mult = { + "arshin": 0.7112, "centimeter": 0.01, "diuym": 0.0254, + "fut": 0.3048, "kilometer": 1000.0, "liniya": 0.00254, + "meter": 1.0, "milia": 7467.6, "piad": 0.1778, + "sazhen": 2.1336, "tochka": 0.000254, "vershok": 0.04445, + "versta": 1066.8, +} + +if len(_args) != 2: throw "bad arg count" +val vs, unit = _args[1], _args[2] + +if unit not of unit2mult: throw "bad unit name" +var value +{ + value = number(vs) + catch: throw "bad number argument" +} + +writeln vs, " ", unit, " to:" + +for u in sort(keys(unit2mult)) { + writeln "{{u:10}}: ", value * unit2mult[unit] / unit2mult[u] +} diff --git a/Task/Old-Russian-measure-of-length/Nascom-BASIC/old-russian-measure-of-length.basic b/Task/Old-Russian-measure-of-length/Nascom-BASIC/old-russian-measure-of-length.basic new file mode 100644 index 0000000000..a7471c0567 --- /dev/null +++ b/Task/Old-Russian-measure-of-length/Nascom-BASIC/old-russian-measure-of-length.basic @@ -0,0 +1,31 @@ +10 REM Old Russian measure of length +20 M=12 +30 DIM U$(12),C(12) +40 DATA tochka,liniya,dyuim,vershok,piad,fut +50 DATA arshin,sazhen,versta,milia,centimeter +60 DATA meter,kilometer +70 DATA 0.0254,0.254,2.54,4.445,17.78,30.48 +80 DATA 71.12,213.36,106680,746760,1,100,100000 +90 FOR I=0 TO M:READ U$(I):NEXT I +100 FOR I=0 TO M:READ C(I):NEXT I +110 FOR I=0 TO M:PRINT I+1;U$(I):NEXT I +120 PRINT "Please choose a unit 1 to";M+1; +130 INPUT IU +140 IF (IU<1) OR (IU>M+1) GOTO 120 +150 IU=IU-1 +160 INPUT "Now enter a value in that unit";V +170 IF V<=0 GOTO 160 +180 CLS +190 PRINT V;U$(IU);"(s) in the remaining "; +200 PRINT "units is:" +210 FOR I=0 TO M +220 IF I=IU GOTO 240 +230 PRINT V*C(IU)/C(I);U$(I);"(s)" +240 NEXT I +250 INPUT "Do another one y/n";YN$ +260 IF YN$="" GOTO 250 +270 YN$=CHR$(ASC(LEFT$(YN$,1)) OR 32) +280 IF (YN$<>"n") AND (YN$<>"y") GOTO 250 +290 IF YN$<>"n" GOTO 110 +300 PRINT "End of story." +310 END diff --git a/Task/Old-Russian-measure-of-length/Pluto/old-russian-measure-of-length.pluto b/Task/Old-Russian-measure-of-length/Pluto/old-russian-measure-of-length.pluto new file mode 100644 index 0000000000..17023e3a5e --- /dev/null +++ b/Task/Old-Russian-measure-of-length/Pluto/old-russian-measure-of-length.pluto @@ -0,0 +1,35 @@ +local fmt = require "fmt" +require "io2" + +local units = { + "tochka", "liniya", "dyuim", "vershok", "piad", "fut", + "arshin", "sazhen", "versta", "milia", + "centimeter", "meter", "kilometer" +} + +local convs = { + 0.0254, 0.254, 2.54, 4.445, 17.78, 30.48, + 71.12, 213.36, 106680, 746760, + 1, 100, 100000 +} + +while true do + local i = 0 + for units as u do + fmt.print("%2d %s", i + 1, u) + ++i + end + print() + local unit = io.readInt("Please choose a unit 1 to 13 : ", 1, 13) + local value = io.readNum("Now enter a value in that unit : ", 0) + print("\nThe equivalent in the remaining units is:\n") + for ix, u in units do + if ix != unit then + fmt.print(" %10s : %16.8f", u, value * convs[unit] / convs[ix]) + end + end + print() + local yn = io.readOpt("Do another one y/n : ", "ynYN":split("")) + if yn:lower() == "n" then break end + print() +end diff --git a/Task/Old-Russian-measure-of-length/Prolog/old-russian-measure-of-length-1.pro b/Task/Old-Russian-measure-of-length/Prolog/old-russian-measure-of-length-1.pro new file mode 100644 index 0000000000..f97a1c0195 --- /dev/null +++ b/Task/Old-Russian-measure-of-length/Prolog/old-russian-measure-of-length-1.pro @@ -0,0 +1,101 @@ +:- module(old_russian_unit_conversion, [convert/2]). +:- set_prolog_flag(prefer_rationals, true). % Int/Int --> Rational +:- set_prolog_flag(rational_syntax, natural). % Write as `1/3` +:- use_module(library(clpq)). + +% The core conversion logic + +convert(A, B) :- convert_shag(A, S), convert_shag(B, S). + +convert_shag(tochka(T), S) :- { S / T = 1 / 2800 }. +convert_shag(millimetre(MM), S) :- { S / MM = 10 / 7112 }. +convert_shag(liniya(L), S) :- { S / L = 1 / 280 }. +convert_shag(centimetre(CM), S) :- { S / CM = 100 / 7112 }. +convert_shag(dyuym(D), S) :- { S / D = 1 / 28 }. +convert_shag(vyershok(V), S) :- { S / V = 1 / 16 }. +convert_shag(ladon(L), S) :- { S / L = 3 / 28 }. +convert_shag(pyad(P), S) :- { S / P = 1 / 4 }. +convert_shag(fut(F), S) :- { S / F = 3 / 7 }. +convert_shag(lokot(L), S) :- { S / L = 9 / 14 }. +convert_shag(shag(S), S). +convert_shag(metre(M), S) :- { M / S = 7112 / 10000 }. +convert_shag(sazhen(Sz), S) :- { Sz / S = 1 / 3 }. +convert_shag(kilometre(KM), S) :- { KM / S = 10668 / 15000000 }. +convert_shag(vyersta(V), S) :- { V / S = 1 / 1500 }. + +% The command line interface + +:- initialization(main, main). + +main([AmountA, UnitA]) :- + atom_number(AmountA, NumberA), + build_term(UnitA, NumberA, TermA), + !, + format("~w ~w is~n", [AmountA, UnitA]), + functor(TermA, NormalisedA, _), + foreach( + ( convert(TermA, TermB), + TermB =.. [UnitB, NumberB], + UnitB \= NormalisedA + ), + format("~|~` t~f~20+ ~w~n", [NumberB, UnitB]) + ). + +main([AmountA, UnitA, UnitB]) :- + atom_number(AmountA, NumberA), + build_term(UnitA, NumberA, TermA), + build_term(UnitB, NumberB, TermB), + !, + convert(TermA, TermB), + format("~w ~w is ~f ~w~n", [AmountA, UnitA, NumberB, UnitB]). + +main(_) :- with_output_to(user_error, format("Invalid argument~n", [])), halt(22). + +build_term(A0, N, T) :- normalise(A0, A), T =.. [A, N]. + +% user input normalisation + +normalise(millimetre, millimetre). +normalise(millimeter, millimetre). +normalise(millimetres, millimetre). +normalise(millimeters, millimetre). +normalise(centimetre, centimetre). +normalise(centimeter, centimetre). +normalise(centimetre, centimetre). +normalise(centimetres, centimetre). +normalise(metre, metre). +normalise(meter, metre). +normalise(meters, metre). +normalise(metres, metre). +normalise(kilometre, kilometre). +normalise(kilometer, kilometre). +normalise(kilometers, kilometre). +normalise(kilometres, kilometre). +normalise(tochka, tochka). +normalise(точка, tochka). +normalise(liniya, liniya). +normalise(линия, liniya). +normalise(dyuym, dyuym). +normalise(дюйм, dyuym). +normalise(pyerst, dyuym). +normalise(перст, dyuym). +normalise(vyershok, vyershok). +normalise(вершок, vyershok). +normalise(ladon, ladon). +normalise(ладонь, ladon). +normalise(pyad, pyad). +normalise(пядь, pyad). +normalise(четверть, pyad). +normalise(chyetvyert, pyad). +normalise(fut, fut). +normalise(фут, fut). +normalise(lokot, lokot). +normalise(локоть, lokot). +normalise(shag, shag). +normalise(шаг, shag). +normalise(arshin, shag). +normalise(аршин, shag). +normalise(sazhen, sazhen). +normalise(сажень, sazhen). +normalise(vyersta, vyersta). +normalise(верста, vyersta). diff --git a/Task/Old-Russian-measure-of-length/Prolog/old-russian-measure-of-length-2.pro b/Task/Old-Russian-measure-of-length/Prolog/old-russian-measure-of-length-2.pro new file mode 100644 index 0000000000..8d8e400625 --- /dev/null +++ b/Task/Old-Russian-measure-of-length/Prolog/old-russian-measure-of-length-2.pro @@ -0,0 +1,19 @@ +?- convert(centimetre(42), fut(Fut)). +Fut = 175/127. + +?- convert(centimetre(42), Unit). +Unit = tochka(210000/127) ; +Unit = millimetre(420) ; +Unit = liniya(21000/127) ; +Unit = centimetre(42) ; +Unit = dyuym(2100/127) ; +Unit = vyershok(1200/127) ; +Unit = ladon(700/127) ; +Unit = pyad(300/127) ; +Unit = fut(175/127) ; +Unit = lokot(350/381) ; +Unit = shag(75/127) ; +Unit = metre(21/50) ; +Unit = sazhen(25/127) ; +Unit = kilometre(21/50000) ; +Unit = vyersta(1/2540). diff --git a/Task/Old-Russian-measure-of-length/QBasic/old-russian-measure-of-length.basic b/Task/Old-Russian-measure-of-length/QBasic/old-russian-measure-of-length.basic index e16f753855..48b4f5df09 100644 --- a/Task/Old-Russian-measure-of-length/QBasic/old-russian-measure-of-length.basic +++ b/Task/Old-Russian-measure-of-length/QBasic/old-russian-measure-of-length.basic @@ -9,7 +9,7 @@ DIM convs(1 TO 13) AS SINGLE FOR i = 1 TO 13 READ convs(i) NEXT i -DATA 0.0254, 0.254, 2.54, 4.445, 17.78, 30.48, 71.12, 213.36, 10668, 74676, 1, 100, 10000 +DATA 0.0254, 0.254, 2.54, 4.445, 17.78, 30.48, 71.12, 213.36, 106680, 746760, 1, 100, 100000 DIM unit AS INTEGER DIM value AS SINGLE DIM yn AS STRING diff --git a/Task/Old-Russian-measure-of-length/R/old-russian-measure-of-length.r b/Task/Old-Russian-measure-of-length/R/old-russian-measure-of-length.r new file mode 100644 index 0000000000..d4dfd7e9ac --- /dev/null +++ b/Task/Old-Russian-measure-of-length/R/old-russian-measure-of-length.r @@ -0,0 +1,29 @@ +#Create vector containing the value of each Russian unit in metres, and names of all units +russian_units <- c(1066.8, 2.1336, 0.7112, 0.04445) +rnames <- c("verst", "sazhen", "arshin", "vershok") +mnames <- c("km", "m", "cm") + +#Expand the vector of Russian units to a matrix with one column each for values in km, m, and cm +metric_expand <- function(x) cbind(x/1000, x, x*100) +conv_matrix <- metric_expand(russian_units) + +#This function displays values in all units other than the one that is input +convert_units <- function(value, unit){ + if(unit %in% rnames){ + unum <- which(rnames==unit) + conv_metric <- conv_matrix[unum,] + conv_russian <- conv_matrix[unum, 2]/conv_matrix[-unum, 2] + } + else if(unit %in% mnames){ + unum <- which(mnames==unit) + conv_metric <- conv_matrix[2, -unum]/conv_matrix[2, unum] + conv_russian <- 1/conv_matrix[,unum] + } + results <- value*c(conv_metric, conv_russian) + allnames <- c(mnames, rnames) + paste(results, allnames[allnames!=unit]) |> writeLines() +} + +#Test inputs +convert_units(1, "m") +convert_units(1, "arshin") diff --git a/Task/Old-Russian-measure-of-length/Ring/old-russian-measure-of-length.ring b/Task/Old-Russian-measure-of-length/Ring/old-russian-measure-of-length.ring index e877ded79c..6092a78987 100644 --- a/Task/Old-Russian-measure-of-length/Ring/old-russian-measure-of-length.ring +++ b/Task/Old-Russian-measure-of-length/Ring/old-russian-measure-of-length.ring @@ -6,8 +6,8 @@ units = ["tochka", "liniya", "dyuim", "vershok", "piad", "fut", "centimeter", "meter", "kilometer"] convs = [0.0254, 0.254, 2.54, 4.445, 17.78, 30.48, - 71.12, 213.36, 10668, 74676, - 1, 100, 10000] + 71.12, 213.36, 106680, 746760, + 1, 100, 100000] yn = "y" unit = 1 diff --git a/Task/Old-Russian-measure-of-length/Rust/old-russian-measure-of-length.rust b/Task/Old-Russian-measure-of-length/Rust/old-russian-measure-of-length.rs similarity index 100% rename from Task/Old-Russian-measure-of-length/Rust/old-russian-measure-of-length.rust rename to Task/Old-Russian-measure-of-length/Rust/old-russian-measure-of-length.rs diff --git a/Task/Old-Russian-measure-of-length/True-BASIC/old-russian-measure-of-length.basic b/Task/Old-Russian-measure-of-length/True-BASIC/old-russian-measure-of-length.basic index 1f32a3a3d1..658baadb48 100644 --- a/Task/Old-Russian-measure-of-length/True-BASIC/old-russian-measure-of-length.basic +++ b/Task/Old-Russian-measure-of-length/True-BASIC/old-russian-measure-of-length.basic @@ -9,7 +9,7 @@ DIM convs(1 TO 13) FOR i = 1 TO 13 READ convs(i) NEXT i -DATA 0.0254, 0.254, 2.54, 4.445, 17.78, 30.48, 71.12, 213.36, 10668, 74676, 1, 100, 10000 +DATA 0.0254, 0.254, 2.54, 4.445, 17.78, 30.48, 71.12, 213.36, 106680, 746760, 1, 100, 100000 DO CLEAR diff --git a/Task/Old-Russian-measure-of-length/Wren/old-russian-measure-of-length.wren b/Task/Old-Russian-measure-of-length/Wren/old-russian-measure-of-length.wren index 0dfbdaa38b..d689d976f3 100644 --- a/Task/Old-Russian-measure-of-length/Wren/old-russian-measure-of-length.wren +++ b/Task/Old-Russian-measure-of-length/Wren/old-russian-measure-of-length.wren @@ -10,8 +10,8 @@ var units = [ var convs = [ 0.0254, 0.254, 2.54, 4.445, 17.78, 30.48, - 71.12, 213.36, 10668, 74676, - 1, 100, 10000 + 71.12, 213.36, 106680, 746760, + 1, 100, 100000 ] while (true) { @@ -39,7 +39,7 @@ while (true) { System.print("\nThe equivalent in the remaining units is:\n") i = 0 for (u in units) { - if (i != unit) Fmt.print(" $10s : $15.8g", u, value*convs[unit]/convs[i]) + if (i != unit) Fmt.print(" $10s : $16.8g", u, value*convs[unit]/convs[i]) i = i + 1 } System.print() diff --git a/Task/Old-Russian-measure-of-length/XBasic/old-russian-measure-of-length.basic b/Task/Old-Russian-measure-of-length/XBasic/old-russian-measure-of-length.basic index 2686352008..ab91040d79 100644 --- a/Task/Old-Russian-measure-of-length/XBasic/old-russian-measure-of-length.basic +++ b/Task/Old-Russian-measure-of-length/XBasic/old-russian-measure-of-length.basic @@ -14,10 +14,10 @@ units$[13] = "kilometer " ' all expressed in centimeters DIM convs![14] -convs![1] = 0.0254 : convs![2] = 0.254 : convs![3] = 2.54 -convs![4] = 4.445 : convs![5] = 17.78 : convs![6] = 30.48 -convs![7] = 71.12 : convs![8] = 213.36 : convs![9] = 10668 -convs![10] = 74676 : convs![11] = 1 : convs![12] = 100 : convs![13] = 10000 +convs![1] = 0.0254 : convs![2] = 0.254 : convs![3] = 2.54 +convs![4] = 4.445 : convs![5] = 17.78 : convs![6] = 30.48 +convs![7] = 71.12 : convs![8] = 213.36 : convs![9] = 106680 +convs![10] = 746760 : convs![11] = 1 : convs![12] = 100 : convs![13] = 100000 DO PRINT diff --git a/Task/Old-Russian-measure-of-length/XPL0/old-russian-measure-of-length.xpl0 b/Task/Old-Russian-measure-of-length/XPL0/old-russian-measure-of-length.xpl0 index b8502af775..ee625e467d 100644 --- a/Task/Old-Russian-measure-of-length/XPL0/old-russian-measure-of-length.xpl0 +++ b/Task/Old-Russian-measure-of-length/XPL0/old-russian-measure-of-length.xpl0 @@ -6,8 +6,8 @@ real Convs, Value; "centimeter", "meter", "kilometer"]; Convs:= [0.0254, 0.254, 2.54, 4.445, 17.78, 30.48, - 71.12, 213.36, 10668., 74676., - 1., 100., 10000.]; + 71.12, 213.36, 106680., 746760., + 1., 100., 100000.]; loop [for I:= 0 to 13-1 do [if I+1 < 10 then ChOut(0, ^ ); IntOut(0, I+1); diff --git a/Task/Old-Russian-measure-of-length/Yabasic/old-russian-measure-of-length.basic b/Task/Old-Russian-measure-of-length/Yabasic/old-russian-measure-of-length.basic index cffccf5896..90672dafbd 100644 --- a/Task/Old-Russian-measure-of-length/Yabasic/old-russian-measure-of-length.basic +++ b/Task/Old-Russian-measure-of-length/Yabasic/old-russian-measure-of-length.basic @@ -9,8 +9,8 @@ units$(13) = "kilometer" dim convs(14) convs(1) = 0.0254 : convs(2) = 0.254 : convs(3) = 2.54 convs(4) = 4.445 : convs(5) = 17.78 : convs(6) = 30.48 -convs(7) = 71.12 : convs(8) = 213.36 : convs(9) = 10668 -convs(10) = 74676 : convs(11) = 1 : convs(12) = 100 : convs(13) = 10000 +convs(7) = 71.12 : convs(8) = 213.36 : convs(9) = 106680 +convs(10) = 746760 : convs(11) = 1 : convs(12) = 100 : convs(13) = 100000 repeat clear screen diff --git a/Task/Old-lady-swallowed-a-fly/Ada/old-lady-swallowed-a-fly.ada b/Task/Old-lady-swallowed-a-fly/Ada/old-lady-swallowed-a-fly.adb similarity index 100% rename from Task/Old-lady-swallowed-a-fly/Ada/old-lady-swallowed-a-fly.ada rename to Task/Old-lady-swallowed-a-fly/Ada/old-lady-swallowed-a-fly.adb diff --git a/Task/Old-lady-swallowed-a-fly/COBOL/old-lady-swallowed-a-fly.cobol b/Task/Old-lady-swallowed-a-fly/COBOL/old-lady-swallowed-a-fly.cob similarity index 100% rename from Task/Old-lady-swallowed-a-fly/COBOL/old-lady-swallowed-a-fly.cobol rename to Task/Old-lady-swallowed-a-fly/COBOL/old-lady-swallowed-a-fly.cob diff --git a/Task/Old-lady-swallowed-a-fly/Elena/old-lady-swallowed-a-fly.elena b/Task/Old-lady-swallowed-a-fly/Elena/old-lady-swallowed-a-fly.elena index 3a609dc6f8..8f3814fbf4 100644 --- a/Task/Old-lady-swallowed-a-fly/Elena/old-lady-swallowed-a-fly.elena +++ b/Task/Old-lady-swallowed-a-fly/Elena/old-lady-swallowed-a-fly.elena @@ -1,7 +1,7 @@ import extensions; -const Creatures = new string[]{"fly", "spider", "bird", "cat", "dog", "goat", "cow", "horse"}; -const Comments = new string[] +const string[] Creatures = new []{"fly", "spider", "bird", "cat", "dog", "goat", "cow", "horse"}; +const string[] Comments = new [] { "I don't know why she swallowed that fly"$10"Perhaps she'll die", "That wiggled and jiggled and tickled inside her", @@ -13,11 +13,11 @@ const Comments = new string[] "She's dead of course" }; -public program() +public Program() { for(int i := 0; i < Creatures.Length; i += 1) { - console + Console .printLineFormatted("There was an old lady who swallowed a {0}",Creatures[i]) .printLine(Comments[i]); @@ -25,12 +25,12 @@ public program() { for(int j := i; j > 0; j -= 1) { - console.printLineFormatted("She swallowed the {0} to catch the {1}",Creatures[j],Creatures[j - 1]) + Console.printLineFormatted("She swallowed the {0} to catch the {1}",Creatures[j],Creatures[j - 1]) }; - console.writeLine(Comments[0]) + Console.writeLine(Comments[0]) }; - console.writeLine() + Console.writeLine() } } diff --git a/Task/Old-lady-swallowed-a-fly/Elixir/old-lady-swallowed-a-fly.elixir b/Task/Old-lady-swallowed-a-fly/Elixir/old-lady-swallowed-a-fly.ex similarity index 100% rename from Task/Old-lady-swallowed-a-fly/Elixir/old-lady-swallowed-a-fly.elixir rename to Task/Old-lady-swallowed-a-fly/Elixir/old-lady-swallowed-a-fly.ex diff --git a/Task/Old-lady-swallowed-a-fly/F-Sharp/old-lady-swallowed-a-fly.fs b/Task/Old-lady-swallowed-a-fly/F-Sharp/old-lady-swallowed-a-fly.fs new file mode 100644 index 0000000000..f2c99751d8 --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/F-Sharp/old-lady-swallowed-a-fly.fs @@ -0,0 +1,26 @@ +//Old lady swallowed a fly. Nigel Galloway: March 23rd., 2026 +let an = [| "fly"; "spider"; "bird"; "cat"; "dog"; "pig"; "goat"; "cow"; "donkey" |] +let cm = + [| "Quite absurd"; + "Fancy that"; + "What a hog"; + "Her mouth was so big"; + "She just opened her throat"; + "I don't know how"; + "It was rather wonky"; |] +let p = Printf.printfn +let h n = + for i = n downto 1 do + if i = 1 then + p "That wriggled and jiggled and tickled inside her;"; + p "She swallowed the %s to catch the %s," an[i] an[i-1] + done +let g n = + if n >= 2 then p "%s, to swallow a %s;" cm[n-2] an[n] +let f n = + p "There was an old lady who swallowed a %s," an[n]; g n; h n; + p "But I don't know why she swallowed the fly,\nPerhaps she'll die!\n" +let () = + for i = 0 to 8 do f i done; + p "There was an old lady who swallowed a horse...\ + She's dead, of course!" diff --git a/Task/Old-lady-swallowed-a-fly/JavaScript/old-lady-swallowed-a-fly.js b/Task/Old-lady-swallowed-a-fly/JavaScript/old-lady-swallowed-a-fly.js new file mode 100644 index 0000000000..7a3ed359ff --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/JavaScript/old-lady-swallowed-a-fly.js @@ -0,0 +1,20 @@ +const animals = [["fly", "I don't know why she swallowed a fly, perhaps she'll die."], + ["spider", "That wriggled and jiggled and tickled inside her."], + ["bird", "How absurd, to swallow a bird!"], + ["cat", "Fancy that, she swallowed a cat!"], + ["dog", "What a hog, to swallow a dog!"], + ["goat", "She opened her throat and swallowed a goat!"], + ["cow", "I don't know how she swallowed a cow."], + ["horse", "She's dead, of course!"]]; + +const n = animals.length; +for (let i = 0; i < n; i++) { + console.log("There was an old lady who swallowed a " + animals[i][0]); + console.log(animals[i][1]); + if (i > 0 && i < (n - 1)) { + for (let j = 0; j < i; j++) { + console.log(`She swallowed the ${animals[i-j][0]} to catch the ${animals[i-j-1][0]}`); + } + console.log(animals[0][1]); + } +} diff --git a/Task/Old-lady-swallowed-a-fly/Julia/old-lady-swallowed-a-fly-1.jl b/Task/Old-lady-swallowed-a-fly/Julia/old-lady-swallowed-a-fly-1.jl new file mode 100644 index 0000000000..226c9da287 --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/Julia/old-lady-swallowed-a-fly-1.jl @@ -0,0 +1,11 @@ +using Base64 +using CodecZlib + +b64 = b"""eNrtVE1rwzAMvedXaKdeRn7ENrb21rHCzmrs1m49K9gOJv9+cko/HBcGg0LHcpOfnq2np0QL + 2FuKgBbICDAoeoiKwEc0hqIUgLAxfV0tQJCdhQM7qh68kheswKeBt5ROYetTemYMCC3rii// + WMS3WkhXVyuFAaLT261JuBWwu4iDbvYp1tYzHVS68VEIObwFgaDB0KizuFs38aSdqKv3TgcJ + uPYdn2B1opwIpeKE53qPftxRd88Y6uoVbdPzWxznrQ3ZUi3DudQ/bcELbevqM32iCIrj3IIh + W6plOJf6L6xaajZjzqW/qAsKIvITBGs9Nm3glboZzkVP5l6Y+0bHLnedD0CttIyrpEU5Kv7N + Mz3XkPBc/TSN3yxGiqMiipHRekycK0ZwMhM8jerGC9zuZaoTho3kMKSfJjLaF8v8wLzmXMqM + zJvGew/jnZPzclA08yAkikegDTTUMfzwDXBcwoE=""" +println(String(transcode(ZlibDecompressor(), base64decode(b64)))) diff --git a/Task/Old-lady-swallowed-a-fly/Julia/old-lady-swallowed-a-fly-1.julia b/Task/Old-lady-swallowed-a-fly/Julia/old-lady-swallowed-a-fly-1.julia deleted file mode 100644 index 86b6193abf..0000000000 --- a/Task/Old-lady-swallowed-a-fly/Julia/old-lady-swallowed-a-fly-1.julia +++ /dev/null @@ -1,10 +0,0 @@ -using CodecZlib - -b64 = b"""eNrtVE1rwzAMvedXaKdeRn7ENrb21rHCzmrs1m49K9gOJv9+cko/HBcGg0LHcpOfnq2np0QL - 2FuKgBbICDAoeoiKwEc0hqIUgLAxfV0tQJCdhQM7qh68kheswKeBt5ROYetTemYMCC3rii// - WMS3WkhXVyuFAaLT261JuBWwu4iDbvYp1tYzHVS68VEIObwFgaDB0KizuFs38aSdqKv3TgcJ - uPYdn2B1opwIpeKE53qPftxRd88Y6uoVbdPzWxznrQ3ZUi3DudQ/bcELbevqM32iCIrj3IIh - W6plOJf6L6xaajZjzqW/qAsKIvITBGs9Nm3glboZzkVP5l6Y+0bHLnedD0CttIyrpEU5Kv7N - Mz3XkPBc/TSN3yxGiqMiipHRekycK0ZwMhM8jerGC9zuZaoTho3kMKSfJjLaF8v8wLzmXMqM - zJvGew/jnZPzclA08yAkikegDTTUMfzwDXBcwoE=""" -println(String(transcode(ZlibDecompressor(), base64decode(b64)))) diff --git a/Task/Old-lady-swallowed-a-fly/Julia/old-lady-swallowed-a-fly-2.julia b/Task/Old-lady-swallowed-a-fly/Julia/old-lady-swallowed-a-fly-2.jl similarity index 100% rename from Task/Old-lady-swallowed-a-fly/Julia/old-lady-swallowed-a-fly-2.julia rename to Task/Old-lady-swallowed-a-fly/Julia/old-lady-swallowed-a-fly-2.jl diff --git a/Task/Old-lady-swallowed-a-fly/Kotlin/old-lady-swallowed-a-fly.kotlin b/Task/Old-lady-swallowed-a-fly/Kotlin/old-lady-swallowed-a-fly.kts similarity index 100% rename from Task/Old-lady-swallowed-a-fly/Kotlin/old-lady-swallowed-a-fly.kotlin rename to Task/Old-lady-swallowed-a-fly/Kotlin/old-lady-swallowed-a-fly.kts diff --git a/Task/Old-lady-swallowed-a-fly/M2000-Interpreter/old-lady-swallowed-a-fly.m2000 b/Task/Old-lady-swallowed-a-fly/M2000-Interpreter/old-lady-swallowed-a-fly.m2000 new file mode 100644 index 0000000000..26de64aba9 --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/M2000-Interpreter/old-lady-swallowed-a-fly.m2000 @@ -0,0 +1,33 @@ +MODULE LikeBasic { + 010 M$="" + 020 NAME$="" : REM "out.txt" + 030 DIM A$(8), E$(8) + 040 GOSUB 220 + 050 OPEN NAME$ FOR OUTPUT AS #F + 070 FOR N = 0 TO 7: READ A$(N), E$(N): NEXT N : N-- + 080 FOR C = 1 TO N + 090 PRINT #F, "THERE WAS AN OLD LADY WHO SWALLOWED A "+A$(C) + 100 IF C > 1 THEN + 110 PRINT #F, E$(C) + 120 IF C < N THEN + 130 FOR B = C TO 2 + 140 PRINT #F, A$(0);A$(B);" TO CATCH THE ";A$(B-1);MID$(",;",1 - (B = 2),1) + 150 NEXT B + 160 END IF + 170 END IF + 180 IF C < N THEN PRINT #F, E$(1);E$(0) + 190 PRINT #F,"",,"" + 170 NEXT C + 200 CLOSE #F + 210 END + 220 DATA" SHE SWALLOWED A "," - PERHAPS SHE'LL DIE!" + 230 DATA"FLY","I DON'T KNOW WHY SHE SWALLOWED A FLY" + 240 DATA"SPIDER","THAT WRIGGLED AND JIGGLED AND TICKLED INSIDE HER;" + 250 DATA"BIRD","HOW ABSURD TO SWALLOW A BIRD." + 260 DATA"CAT","FANCY THAT TO SWALLOW A CAT!" + 270 DATA"DOG","WHAT A HOG, TO SWALLOW A DOG;" + 280 DATA"COW","I DON'T KNOW HOW SHE SWALLOWED A COW," + 290 DATA"HORSE","SHE'S DEAD, OF COURSE!" + 300 RETURN +} +LikeBasic diff --git a/Task/Old-lady-swallowed-a-fly/Maxima/old-lady-swallowed-a-fly.maxima b/Task/Old-lady-swallowed-a-fly/Maxima/old-lady-swallowed-a-fly.maxima new file mode 100644 index 0000000000..649cbfb045 --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/Maxima/old-lady-swallowed-a-fly.maxima @@ -0,0 +1,20 @@ +animals: [["fly", "I don't know why she swallowed a fly, perhaps she'll die."], +["spider", "That wriggled and jiggled and tickled inside her."], +["bird", "How absurd, to swallow a bird!"], +["cat", "Fancy that, she swallowed a cat!"], +["dog", "What a hog, to swallow a dog!"], +["goat", "She opened her throat and swallowed a goat!"], +["cow", "I don't know how she swallowed a cow."], +["horse", "She's dead, of course!"]]$ + +n: length(animals)$ +for i from 1 thru n do( + sprint("There was an old lady who swallowed a", animals[i][1]), newline(), + sprint(animals[i][2]), newline(), + if i>1 and i[char] +sing group = swallow ++ line ++ "\n" ++ catch group + where swallow = "There once was a lady who swallowed a " + ++ animal ++ ".\n" + (Verse kind animal line) = hd group + + +catch :: [verse]->[char] +catch [x] = "" +catch (v1:v2:vs) = line, if kind1 == Stop + = swallow ++ line ++ catch (v2:vs), otherwise + where (Verse kind1 animal1 line1) = v1 + (Verse kind2 animal2 line2) = v2 + swallow = "She swallowed the " ++ animal1 ++ + " to catch the " ++ animal2 ++ ",\n" + line = line2 ++ "\n", if kind2 ~= Once + line = "", otherwise + +groups :: [[verse]] +groups = (reverse . map reverse . takewhile (~= []) . iterate init) animals + +animals :: [verse] +animals + = [Verse Each "fly" "I don't know why she swallowed that fly.\nPerhaps she'll die.\n", + Verse Each "spider" "That wiggled and jiggled and tickled inside her.", + Verse Once "bird" "How absurd to swallow a bird", + Verse Once "cat" "Imagine that, she swallowed a cat", + Verse Once "dog" "What a hog, she swallowed a dog", + Verse Once "goat" "She just opened her throat and swallowed that goat", + Verse Once "cow" "I don't know how she swallowed that cow", + Verse Stop "horse" "She's dead, of course."] diff --git a/Task/Old-lady-swallowed-a-fly/OCaml/old-lady-swallowed-a-fly-1.ocaml b/Task/Old-lady-swallowed-a-fly/OCaml/old-lady-swallowed-a-fly-1.ml similarity index 100% rename from Task/Old-lady-swallowed-a-fly/OCaml/old-lady-swallowed-a-fly-1.ocaml rename to Task/Old-lady-swallowed-a-fly/OCaml/old-lady-swallowed-a-fly-1.ml diff --git a/Task/Old-lady-swallowed-a-fly/OCaml/old-lady-swallowed-a-fly-2.ocaml b/Task/Old-lady-swallowed-a-fly/OCaml/old-lady-swallowed-a-fly-2.ml similarity index 100% rename from Task/Old-lady-swallowed-a-fly/OCaml/old-lady-swallowed-a-fly-2.ocaml rename to Task/Old-lady-swallowed-a-fly/OCaml/old-lady-swallowed-a-fly-2.ml diff --git a/Task/Old-lady-swallowed-a-fly/OCaml/old-lady-swallowed-a-fly-3.ocaml b/Task/Old-lady-swallowed-a-fly/OCaml/old-lady-swallowed-a-fly-3.ml similarity index 100% rename from Task/Old-lady-swallowed-a-fly/OCaml/old-lady-swallowed-a-fly-3.ocaml rename to Task/Old-lady-swallowed-a-fly/OCaml/old-lady-swallowed-a-fly-3.ml diff --git a/Task/Old-lady-swallowed-a-fly/Phix/old-lady-swallowed-a-fly.phix b/Task/Old-lady-swallowed-a-fly/Phix/old-lady-swallowed-a-fly.phix index f87b62b8ee..0acfdb1d9d 100644 --- a/Task/Old-lady-swallowed-a-fly/Phix/old-lady-swallowed-a-fly.phix +++ b/Task/Old-lady-swallowed-a-fly/Phix/old-lady-swallowed-a-fly.phix @@ -1,30 +1,28 @@ -(phixonline)--> - with javascript_semantics - sequence lines = {"Perhaps she'll die!\n"}, animals = {} +with javascript_semantics +sequence lines = {"Perhaps she'll die!\n"}, animals = {} - procedure swallow(string animal, second_line, integer permanent_second_line=TRUE) - printf(1,"There was an old lady who swallowed a %s,\n%s\n",{animal,second_line}) - if length(animals)!=0 then - lines = prepend(lines,sprintf("She swallowed the %s to catch the %s,\n",{animal,animals[$]})) - end if - printf(1,"%s\n",{join(lines,"")}) - if permanent_second_line then - lines = prepend(lines,second_line&"\n") - end if - animals = append(animals,animal) - end procedure +procedure swallow(string animal, second_line, integer permanent_second_line=TRUE) + printf(1,"There was an old lady who swallowed a %s,\n%s\n",{animal,second_line}) + if length(animals)!=0 then + lines = prepend(lines,sprintf("She swallowed the %s to catch the %s,\n",{animal,animals[$]})) + end if + printf(1,"%s\n",{join(lines,"")}) + if permanent_second_line then + lines = prepend(lines,second_line&"\n") + end if + animals = append(animals,animal) +end procedure - procedure swallow_all(sequence all) - for i=1 to length(all) do - string {animal,line2} = all[i] - swallow(animal, sprintf("%s, %s a %s;",{line2,iff(animal="cow"?"she swallowed":"to swallow"),animal}), FALSE); - end for - end procedure +procedure swallow_all(sequence all) + for i=1 to length(all) do + string {animal,line2} = all[i] + swallow(animal, sprintf("%s, %s a %s;",{line2,iff(animal="cow"?"she swallowed":"to swallow"),animal}), FALSE); + end for +end procedure - swallow("fly", "But I don't know why she swallowed the fly,"); - swallow("spider", "That wriggled and jiggled and tickled inside her;"); - swallow_all({{"bird", "Quite absurd"},{"cat", "Fancy that"},{"dog", "What a hog"}, - {"pig", "Her mouth was so big"},{"goat","She just opened her throat"}, - {"cow", "I don't know how"},{"donkey", "It was rather wonky"}}) - printf(1, "There was an old lady who swallowed a horse ...\nShe's dead, of course!") - ) + + [ [ table + [ say "I don't know why she swallowed a fly." ] + [ say "That wiggled and jiggled and tickled inside her." ] + [ say "How absurd to swallow a bird." ] + [ say "Imagine that, she swallowed a cat!" ] + [ say "What a hog to swallow a dog." ] + [ say "She just opened her throat and swallowed that goat." ] + [ say "I don't know how she swallowed a cow." ] ] do ] is observation ( n --> ) + + [ say "There was an old lady who swallowed a " dup beast + dup if [ cr dup observation ] + times + [ cr say "She swallowed the " i 1+ beast + say " to catch the " i beast ] + cr 0 observation + cr say "Perhaps she'll die." ] is verse ( n --> ) + + [ say "There was an old lady who swallowed a horse." + cr say "She's dead, of course." ] is coda ( --> ) + + [ 7 times [ i^ verse cr cr ] coda ] is song ( --> ) + + song diff --git a/Task/Old-lady-swallowed-a-fly/Refal/old-lady-swallowed-a-fly.refal b/Task/Old-lady-swallowed-a-fly/Refal/old-lady-swallowed-a-fly.refal new file mode 100644 index 0000000000..2b0cd9361c --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/Refal/old-lady-swallowed-a-fly.refal @@ -0,0 +1,51 @@ +$ENTRY Go { = >>>; }; + +Each { + s.F = ; + s.F (e.X) e.Xs = ; +}; + +Verse { + e.Animals, e.Animals: e.1 (e.Animal), + : e.Line, + e.Animal: (e.2) s.Type e.3, + s.Type: { Stop = e.Line; s.Type = e.Line ; }; +}; + +Swallow { + (e.Animal) s.Type e.Verse = + 'There once was a lady who swallowed a ' e.Animal '.\n' + e.Verse '\n'; +}; + +Catch { + (e.1) = ; + e.As ((e.A1) s.Type1 e.1), e.As: e.2 ((e.A2) s.Type2 e.Verse) = + 'She swallowed the ' e.A1 ' to catch the ' e.A2 ',\n' + + ; +}; + +Match { + s.X s.X e.Y = e.Y; + e.X = ; +}; + +Heads { + (Acc (e.Acc)) = ; + (Acc (e.Acc)) (e.X) e.Y, (e.Acc (e.X)): e.ANext = + e.ANext ; + e.X = ; +}; + +Animals { = + (('fly') Each 'I don\'t know why she swallowed that fly.\n' + 'Perhaps she\'ll die.\n') + (('spider') Each 'That wiggled and jiggled and tickled inside her.') + (('bird') First 'How absurd to swallow a bird.') + (('cat') First 'Imagine that, she swallowed a cat.') + (('dog') First 'What a hog to swallow a dog.') + (('goat') First 'She just opened her throat and swallowed that goat.') + (('cow') First 'I don\'t know how she swallowed that cow.') + (('horse') Stop 'She\'s dead, of course.'); +}; diff --git a/Task/Old-lady-swallowed-a-fly/Rust/old-lady-swallowed-a-fly.rust b/Task/Old-lady-swallowed-a-fly/Rust/old-lady-swallowed-a-fly.rs similarity index 100% rename from Task/Old-lady-swallowed-a-fly/Rust/old-lady-swallowed-a-fly.rust rename to Task/Old-lady-swallowed-a-fly/Rust/old-lady-swallowed-a-fly.rs diff --git a/Task/Old-lady-swallowed-a-fly/SETL/old-lady-swallowed-a-fly.setl b/Task/Old-lady-swallowed-a-fly/SETL/old-lady-swallowed-a-fly.setl new file mode 100644 index 0000000000..c98b271fea --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/SETL/old-lady-swallowed-a-fly.setl @@ -0,0 +1,26 @@ +program old_lady; + animals := ["fly", "spider", "bird", "cat", "dog", "goat", "cow", "horse"]; + verses := [ + "I don't know why she swallowed that fly.\nPerhaps she'll die.\n", + "That wiggled and jiggled and tickled inside her!", + "How absurd to swallow a bird", + "Imagine that, she swallowed a cat", + "What a hog to swallow a dog", + "She just opened her throat and swallowed that goat", + "I don't know how she swallowed that cow", + "She's dead, of course." + ]; + + loop for i in [1..8] do + print("There was an old lady who swallowed a " + animals(i)); + print(verses(i)); + if i=8 then quit; end if; + loop for j in [i, i-1..2] do + print("She swallowed the " + animals(j) + + " to catch the " + animals(j-1)); + if j < 4 then + print(verses(j-1)); + end if; + end loop; + end loop; +end program; diff --git a/Task/Old-lady-swallowed-a-fly/VBScript/old-lady-swallowed-a-fly.vb b/Task/Old-lady-swallowed-a-fly/VBScript/old-lady-swallowed-a-fly.vbs similarity index 100% rename from Task/Old-lady-swallowed-a-fly/VBScript/old-lady-swallowed-a-fly.vb rename to Task/Old-lady-swallowed-a-fly/VBScript/old-lady-swallowed-a-fly.vbs diff --git a/Task/One-dimensional-cellular-automata/11l/one-dimensional-cellular-automata.11l b/Task/One-dimensional-cellular-automata/11l/one-dimensional-cellular-automata.11l index 210e1feadc..ca9d4faac9 100644 --- a/Task/One-dimensional-cellular-automata/11l/one-dimensional-cellular-automata.11l +++ b/Task/One-dimensional-cellular-automata/11l/one-dimensional-cellular-automata.11l @@ -1,5 +1,5 @@ V gen = ‘_###_##_#_#_#_#__#__’.map(ch -> Int(ch == ‘#’)) -L(n) 10 +L 10 print(gen.map(cell -> (I cell != 0 {‘#’} E ‘_’)).join(‘’)) gen = [0] [+] gen [+] [0] gen = (0 .< gen.len - 2).map(m -> Int(sum(:gen[m .+ 3]) == 2)) diff --git a/Task/One-dimensional-cellular-automata/Ada/one-dimensional-cellular-automata.ada b/Task/One-dimensional-cellular-automata/Ada/one-dimensional-cellular-automata.adb similarity index 100% rename from Task/One-dimensional-cellular-automata/Ada/one-dimensional-cellular-automata.ada rename to Task/One-dimensional-cellular-automata/Ada/one-dimensional-cellular-automata.adb diff --git a/Task/One-dimensional-cellular-automata/Arturo/one-dimensional-cellular-automata.arturo b/Task/One-dimensional-cellular-automata/Arturo/one-dimensional-cellular-automata.arturo index 7730a7d282..8234e1aea9 100644 --- a/Task/One-dimensional-cellular-automata/Arturo/one-dimensional-cellular-automata.arturo +++ b/Task/One-dimensional-cellular-automata/Arturo/one-dimensional-cellular-automata.arturo @@ -1,13 +1,13 @@ evolve: function [arr][ ary: [0] ++ arr ++ [0] - ret: new [] + ret: [] loop 1..(size ary)-2 'i [ a: ary\[i-1] b: ary\[i] c: ary\[i+1] - if? 2 = a+b+c -> 'ret ++ 1 - else -> 'ret ++ 0 + switch 2 = a+b+c -> 'ret ++ 1 + -> 'ret ++ 0 ] ret ] diff --git a/Task/One-dimensional-cellular-automata/C/one-dimensional-cellular-automata-3.c b/Task/One-dimensional-cellular-automata/C/one-dimensional-cellular-automata-3.c new file mode 100644 index 0000000000..a6a43c9793 --- /dev/null +++ b/Task/One-dimensional-cellular-automata/C/one-dimensional-cellular-automata-3.c @@ -0,0 +1,40 @@ +#include +#include + +#define SIZE 21 + +void print_gen(int gen[], int size) { + for (int i = 0; i < size; i++) { + printf("%c", gen[i] ? '#' : '_'); + } + printf("\n"); +} + +void evolve(int gen[], int size) { + int next_gen[size + 2]; + next_gen[0] = next_gen[size + 1] = 0; + + for (int i = 0; i < size; i++) { + next_gen[i + 1] = gen[i]; + } + + for (int i = 0; i < size; i++) { + gen[i] = (next_gen[i] + next_gen[i + 1] + next_gen[i + 2]) == 2; + } +} + +int main() { + char initial[] = "_###_##_#_#_#_#__#__"; + int gen[SIZE]; + + for (int i = 0; i < SIZE; i++) { + gen[i] = initial[i] == '#'; + } + + for (int n = 0; n < 10; n++) { + print_gen(gen, SIZE); + evolve(gen, SIZE); + } + + return 0; +} diff --git a/Task/One-dimensional-cellular-automata/COBOL/one-dimensional-cellular-automata-1.cobol b/Task/One-dimensional-cellular-automata/COBOL/one-dimensional-cellular-automata-1.cob similarity index 100% rename from Task/One-dimensional-cellular-automata/COBOL/one-dimensional-cellular-automata-1.cobol rename to Task/One-dimensional-cellular-automata/COBOL/one-dimensional-cellular-automata-1.cob diff --git a/Task/One-dimensional-cellular-automata/COBOL/one-dimensional-cellular-automata-2.cobol b/Task/One-dimensional-cellular-automata/COBOL/one-dimensional-cellular-automata-2.cob similarity index 100% rename from Task/One-dimensional-cellular-automata/COBOL/one-dimensional-cellular-automata-2.cobol rename to Task/One-dimensional-cellular-automata/COBOL/one-dimensional-cellular-automata-2.cob diff --git a/Task/One-dimensional-cellular-automata/Crystal/one-dimensional-cellular-automata.cr b/Task/One-dimensional-cellular-automata/Crystal/one-dimensional-cellular-automata.cr new file mode 100644 index 0000000000..f36ab61c39 --- /dev/null +++ b/Task/One-dimensional-cellular-automata/Crystal/one-dimensional-cellular-automata.cr @@ -0,0 +1,19 @@ +def evolve (s, rule) + rule = (rule.is_a?(Int) ? ("%08b" % rule).reverse : rule).chars + cells = ['0'].concat(s.chars) << '0' + Array(Char).new(cells.size - 2) {|i| + rule[cells[i..i+2].join.to_i(2)] + }.join +end + +[{"Task rule", "00010110", "01110110101010100100"}, + {"Rule 90 (from Raku)", 90, "000000000000000010000000000000000"}].each do |title, rule, start| + gen = start + puts "#{title} - first 15 generations or until stable:" + 15.times do + puts gen.gsub(/./, { "0" => " ", "1" => "#" }) + next_gen = evolve(gen, rule) + break if next_gen == gen + gen = next_gen + end +end diff --git a/Task/One-dimensional-cellular-automata/Delphi/one-dimensional-cellular-automata.delphi b/Task/One-dimensional-cellular-automata/Delphi/one-dimensional-cellular-automata.pas similarity index 100% rename from Task/One-dimensional-cellular-automata/Delphi/one-dimensional-cellular-automata.delphi rename to Task/One-dimensional-cellular-automata/Delphi/one-dimensional-cellular-automata.pas diff --git a/Task/One-dimensional-cellular-automata/EasyLang/one-dimensional-cellular-automata.easy b/Task/One-dimensional-cellular-automata/EasyLang/one-dimensional-cellular-automata.easy index a5e70f7c97..536f269645 100644 --- a/Task/One-dimensional-cellular-automata/EasyLang/one-dimensional-cellular-automata.easy +++ b/Task/One-dimensional-cellular-automata/EasyLang/one-dimensional-cellular-automata.easy @@ -1,14 +1,14 @@ map[] = [ 0 0 0 1 0 1 1 0 ] cell[] = [ 0 1 1 1 0 1 1 0 1 0 1 0 1 0 1 0 0 1 0 0 ] len celln[] len cell[] -proc evolve . . +proc evolve . for i = 2 to len cell[] - 1 ind = cell[i - 1] + 2 * cell[i] + 4 * cell[i + 1] + 1 celln[i] = map[ind] . swap celln[] cell[] . -proc show . . +proc show . for v in cell[] if v = 1 write "#" diff --git a/Task/One-dimensional-cellular-automata/Elixir/one-dimensional-cellular-automata.elixir b/Task/One-dimensional-cellular-automata/Elixir/one-dimensional-cellular-automata.ex similarity index 100% rename from Task/One-dimensional-cellular-automata/Elixir/one-dimensional-cellular-automata.elixir rename to Task/One-dimensional-cellular-automata/Elixir/one-dimensional-cellular-automata.ex diff --git a/Task/One-dimensional-cellular-automata/Euphoria/one-dimensional-cellular-automata.euphoria b/Task/One-dimensional-cellular-automata/Euphoria/one-dimensional-cellular-automata.eu similarity index 100% rename from Task/One-dimensional-cellular-automata/Euphoria/one-dimensional-cellular-automata.euphoria rename to Task/One-dimensional-cellular-automata/Euphoria/one-dimensional-cellular-automata.eu diff --git a/Task/One-dimensional-cellular-automata/Icon/one-dimensional-cellular-automata-3.icon b/Task/One-dimensional-cellular-automata/Icon/one-dimensional-cellular-automata-3.icon index 1e18f78ed1..8c3552ce83 100644 --- a/Task/One-dimensional-cellular-automata/Icon/one-dimensional-cellular-automata-3.icon +++ b/Task/One-dimensional-cellular-automata/Icon/one-dimensional-cellular-automata-3.icon @@ -1,9 +1,9 @@ (function next cells (... str (map (comp str (count ["#"]) (= 2) #(% "#" "_")) - (str "_" cells) + "_{cells}" cells - (str (skip 1 cells) "_")))) + "{skip 1 cells}_"))) (function generate n cells (join "\n" (reductions next cells (range n)))) diff --git a/Task/One-dimensional-cellular-automata/Julia/one-dimensional-cellular-automata-1.julia b/Task/One-dimensional-cellular-automata/Julia/one-dimensional-cellular-automata-1.jl similarity index 100% rename from Task/One-dimensional-cellular-automata/Julia/one-dimensional-cellular-automata-1.julia rename to Task/One-dimensional-cellular-automata/Julia/one-dimensional-cellular-automata-1.jl diff --git a/Task/One-dimensional-cellular-automata/Julia/one-dimensional-cellular-automata-2.julia b/Task/One-dimensional-cellular-automata/Julia/one-dimensional-cellular-automata-2.jl similarity index 100% rename from Task/One-dimensional-cellular-automata/Julia/one-dimensional-cellular-automata-2.julia rename to Task/One-dimensional-cellular-automata/Julia/one-dimensional-cellular-automata-2.jl diff --git a/Task/One-dimensional-cellular-automata/Kotlin/one-dimensional-cellular-automata.kotlin b/Task/One-dimensional-cellular-automata/Kotlin/one-dimensional-cellular-automata.kts similarity index 100% rename from Task/One-dimensional-cellular-automata/Kotlin/one-dimensional-cellular-automata.kotlin rename to Task/One-dimensional-cellular-automata/Kotlin/one-dimensional-cellular-automata.kts diff --git a/Task/One-dimensional-cellular-automata/OCaml/one-dimensional-cellular-automata.ocaml b/Task/One-dimensional-cellular-automata/OCaml/one-dimensional-cellular-automata.ml similarity index 100% rename from Task/One-dimensional-cellular-automata/OCaml/one-dimensional-cellular-automata.ocaml rename to Task/One-dimensional-cellular-automata/OCaml/one-dimensional-cellular-automata.ml diff --git a/Task/One-dimensional-cellular-automata/Oberon-07/one-dimensional-cellular-automata.oberon b/Task/One-dimensional-cellular-automata/Oberon-07/one-dimensional-cellular-automata.oberon new file mode 100644 index 0000000000..65a1f293f5 --- /dev/null +++ b/Task/One-dimensional-cellular-automata/Oberon-07/one-dimensional-cellular-automata.oberon @@ -0,0 +1,31 @@ +MODULE OneDCellularAutomata; + IMPORT Out, Strings; + + VAR state, nextState : ARRAY 21 OF CHAR; + curr : ARRAY 4 OF CHAR; + generation, cPos : INTEGER; + finished : BOOLEAN; + +BEGIN + generation := 0; + state := "_###_##_#_#_#_#__#__"; + finished := FALSE; + WHILE ~ finished DO + Out.String( "Generation " ); + Out.Int( generation, 0 );Out.String( " " );Out.String( state );Out.Ln; + nextState := "____________________"; + FOR cPos := 1 TO LEN( state ) - 3 DO + Strings.Extract( state, cPos - 1, 3, curr ); + IF ( curr = "_##" ) OR ( curr = "#_#" ) OR ( curr = "##_" ) THEN + nextState[ cPos ] := "#" + ELSE + nextState[ cPos ] := "_" + END + END; + finished := state = nextState; + IF ~ finished THEN + state := nextState; + INC( generation ) + END + END +END OneDCellularAutomata. diff --git a/Task/One-dimensional-cellular-automata/Odin/one-dimensional-cellular-automata.odin b/Task/One-dimensional-cellular-automata/Odin/one-dimensional-cellular-automata.odin new file mode 100644 index 0000000000..4ab7c676ba --- /dev/null +++ b/Task/One-dimensional-cellular-automata/Odin/one-dimensional-cellular-automata.odin @@ -0,0 +1,72 @@ +package main + +import ba "core:container/bit_array" +import "core:flags" +import "core:fmt" +import "core:os" +import "core:strings" + +print_row :: proc(a: ^ba.Bit_Array, alive_char, dead_char: rune) { + it := ba.make_iterator(a) + for c in ba.iterate_by_all(&it) { + fmt.print(alive_char if c else dead_char, sep = "", flush = false) + } + fmt.println() +} + +evolve :: proc(prev, next: ^ba.Bit_Array) -> (alive: bool) { + if next.bits == nil do ba.init(next, prev.length) + assert(prev.length == next.length) + for i in 0 ..< next.length { + ancestors := 0 + for j in max(0, i - 1) ..= min(prev.length, i + 1) { + if ba.unsafe_get(prev, j) do ancestors += 1 + } + _alive := ancestors == 2 + ba.set(next, i, _alive) + if _alive && !alive do alive = true + } + return alive +} + +parse_row :: proc(str: string, res: ^ba.Bit_Array, alive_char, dead_char: rune) { + str := strings.trim_space(str) + if res.bits == nil do ba.init(res, len(str)) + + for c, i in str { + if (c != dead_char && c != alive_char) do fmt.panicf("invalid character in seed: '%c'", c) + ba.set(res, i, c == alive_char) + } +} + +Args :: struct { + seed : string `args:"pos=0,required" usage:"Initial seed string, e.g. '.###..#.#'"` , + alive_char : rune `args:"name=a" usage:"Character representing alive cells. Default: '#'"` , + dead_char : rune `args:"name=d" usage:"Character representing dead cells. Default: '.'"` , + generations: uint `args:"name=g" usage:"Number of generations to simulate. Default: 10"` , +} + +main :: proc() { + args := Args { + alive_char = '#', + dead_char = '.', + generations = 10, + } + flags.parse_or_exit(&args, os.args) + + row := ba.Bit_Array{} + next := ba.Bit_Array{} + + parse_row(args.seed, &row, args.alive_char, args.dead_char) + + for generation in 1 ..= args.generations { + fmt.printf("Generation % -3d: ", generation, flush = false) + print_row(&row, args.alive_char, args.dead_char) + alive := evolve(&row, &next) + if !alive { + fmt.println("Population has died out.") + break + } + row, next = next, row + } +} diff --git a/Task/One-dimensional-cellular-automata/PascalABC.NET/one-dimensional-cellular-automata.pas b/Task/One-dimensional-cellular-automata/PascalABC.NET/one-dimensional-cellular-automata.pas new file mode 100644 index 0000000000..2559c48baf --- /dev/null +++ b/Task/One-dimensional-cellular-automata/PascalABC.NET/one-dimensional-cellular-automata.pas @@ -0,0 +1,8 @@ +## +var gen := '_###_##_#_#_#_#__#__'.Select(ch -> (if ch = '#' then 1 else 0)).ToList; +loop 10 do +begin + gen.Select(n -> (if n = 1 then '#' else '_')).println; + gen := (0 + gen + 0).ToList; + gen := (1..gen.Count - 2).Select(m -> (if gen[m - 1:m + 2].Sum = 2 then 1 else 0)).ToList; +end; diff --git a/Task/One-dimensional-cellular-automata/Pluto/one-dimensional-cellular-automata.pluto b/Task/One-dimensional-cellular-automata/Pluto/one-dimensional-cellular-automata.pluto new file mode 100644 index 0000000000..5bc28c5e0e --- /dev/null +++ b/Task/One-dimensional-cellular-automata/Pluto/one-dimensional-cellular-automata.pluto @@ -0,0 +1,24 @@ +require "table2" + +local trans = "___#_##_" + +local v = |cell, i| -> cell[i] != "_" ? 1 : 0 + +local function evolve(cell, backup) + local len = #cell - 2 + local diff = 0 + for i = 2, len do + backup[i] = trans[v(cell, i - 1) * 4 + v(cell, i) * 2 + v(cell, i + 1) + 1] + diff += backup[i] != cell[i] ? 1 : 0 + end + cell:clear() + cell:join(backup) + return diff != 0 +end + +local c = "_###_##_#_#_#_#__#__":split("") +local b = "____________________":split("") +while true do + print(c:slice(2):concat("")) + if !evolve(c,b) then break end +end diff --git a/Task/One-dimensional-cellular-automata/Refal/one-dimensional-cellular-automata.refal b/Task/One-dimensional-cellular-automata/Refal/one-dimensional-cellular-automata.refal new file mode 100644 index 0000000000..37e52530e5 --- /dev/null +++ b/Task/One-dimensional-cellular-automata/Refal/one-dimensional-cellular-automata.refal @@ -0,0 +1,39 @@ +$ENTRY Go { + , ' ### ## # # # # # ': e.State + = 10 e.State>; +}; + +Table { + = (((' ') ' ') + ((' #') ' ') + ((' # ') ' ') + ((' ##') '#') + (('# ') ' ') + (('# #') '#') + (('## ') '#') + (('###') ' ')); +}; + +Run { + t.Table 0 e.X = ; + t.Table s.Steps e.X = + + >; +}; + +DoStep { + t.Table e.X = ; +}; + +Step1 { + t.Table s.1 s.2 s.3 e.R, + : e.Next, + e.R: { + = e.Next; + e.R = e.Next ; + }; +} + +Lookup { + (e.A ((e.X)e.Y) e.B) e.X = e.Y; +}; diff --git a/Task/One-dimensional-cellular-automata/Rust/one-dimensional-cellular-automata.rust b/Task/One-dimensional-cellular-automata/Rust/one-dimensional-cellular-automata.rs similarity index 100% rename from Task/One-dimensional-cellular-automata/Rust/one-dimensional-cellular-automata.rust rename to Task/One-dimensional-cellular-automata/Rust/one-dimensional-cellular-automata.rs diff --git a/Task/One-dimensional-cellular-automata/Scheme/one-dimensional-cellular-automata.ss b/Task/One-dimensional-cellular-automata/Scheme/one-dimensional-cellular-automata.scm similarity index 100% rename from Task/One-dimensional-cellular-automata/Scheme/one-dimensional-cellular-automata.ss rename to Task/One-dimensional-cellular-automata/Scheme/one-dimensional-cellular-automata.scm diff --git a/Task/One-dimensional-cellular-automata/Uiua/one-dimensional-cellular-automata.uiua b/Task/One-dimensional-cellular-automata/Uiua/one-dimensional-cellular-automata.uiua new file mode 100644 index 0000000000..c4c9f9697f --- /dev/null +++ b/Task/One-dimensional-cellular-automata/Uiua/one-dimensional-cellular-automata.uiua @@ -0,0 +1,4 @@ +Rule ← /+⊞= ⊓(⊚⋯|°⋯⇌⧈∘3⇌ ⊂⊂0⊙0) +⍥(⁅⚂)200 # Init +⇌(⍥(⊸Rule104)⌊÷2⊸⧻) # Run +▽⟜≡▽4 # Scale up diff --git a/Task/One-dimensional-cellular-automata/V-(Vlang)/one-dimensional-cellular-automata.v b/Task/One-dimensional-cellular-automata/V-(Vlang)/one-dimensional-cellular-automata.v new file mode 100644 index 0000000000..e70c22241c --- /dev/null +++ b/Task/One-dimensional-cellular-automata/V-(Vlang)/one-dimensional-cellular-automata.v @@ -0,0 +1,33 @@ +const trans = '___#_##_' + +fn v(cell []u8, i int) bool { + // false if index is out of bounds or cell[i] == '_' + if i < 0 || i >= cell.len { return false } + return cell[i] != `_` +} + +fn evolve(mut cell []u8, mut backup []u8, len int) int { + mut diff := 0 + for i in 0 .. len { + // calculate index using left, self, right bits + idx := int(v(cell, i - 1)) * 4 + int(v(cell, i)) * 2 + int(v(cell, i + 1)) + backup[i] = trans[idx] + if backup[i] != cell[i] { diff++ } + } + // backup to cell + for i in 0 .. len { + cell[i] = backup[i] + } + return diff +} + +fn main() { + mut c := '_###_##_#_#_#_#__#__'.bytes() + mut b := []u8{len: c.len, init: `_`} + mut slice_c := c[1..c.len].clone() + mut slice_b := b[1..b.len].clone() + for { + println(slice_c.bytestr()) + if evolve(mut slice_c, mut slice_b, slice_c.len) == 0 { break } + } +} diff --git a/Task/One-dimensional-cellular-automata/YAMLScript/one-dimensional-cellular-automata.ys b/Task/One-dimensional-cellular-automata/YAMLScript/one-dimensional-cellular-automata.ys new file mode 100644 index 0000000000..0befa5d1da --- /dev/null +++ b/Task/One-dimensional-cellular-automata/YAMLScript/one-dimensional-cellular-automata.ys @@ -0,0 +1,17 @@ +!YS-v0 + +defn main(): + each line generate(10 '_###_##_#_#_#_#__#__'): + say: line + +defn generate(n cells): + when n.?: + cons cells: + generate n.--: + loop cs cells, ncs subs(cells 0 1): + if cs.# >= 3: + recur cs.subs(1): + ncs +: + filter(\(_:S == '#') cs.subs(0 3)) + .#.eq(2).if('#' '_') + else: ncs + cs.subs(1) diff --git a/Task/One-of-n-lines-in-a-file/Ada/one-of-n-lines-in-a-file.ada b/Task/One-of-n-lines-in-a-file/Ada/one-of-n-lines-in-a-file.adb similarity index 100% rename from Task/One-of-n-lines-in-a-file/Ada/one-of-n-lines-in-a-file.ada rename to Task/One-of-n-lines-in-a-file/Ada/one-of-n-lines-in-a-file.adb diff --git a/Task/One-of-n-lines-in-a-file/Chapel/one-of-n-lines-in-a-file.chapel b/Task/One-of-n-lines-in-a-file/Chapel/one-of-n-lines-in-a-file.chpl similarity index 100% rename from Task/One-of-n-lines-in-a-file/Chapel/one-of-n-lines-in-a-file.chapel rename to Task/One-of-n-lines-in-a-file/Chapel/one-of-n-lines-in-a-file.chpl diff --git a/Task/One-of-n-lines-in-a-file/DuckDB/one-of-n-lines-in-a-file.duckdb b/Task/One-of-n-lines-in-a-file/DuckDB/one-of-n-lines-in-a-file.duckdb new file mode 100644 index 0000000000..a4c4a53126 --- /dev/null +++ b/Task/One-of-n-lines-in-a-file/DuckDB/one-of-n-lines-in-a-file.duckdb @@ -0,0 +1,4 @@ +FROM read_csv('input.txt', + header=false, sep='', quote='', escape='', + columns={'line': VARCHAR}, auto_detect=false) +USING SAMPLE 1; diff --git a/Task/One-of-n-lines-in-a-file/Elixir/one-of-n-lines-in-a-file.elixir b/Task/One-of-n-lines-in-a-file/Elixir/one-of-n-lines-in-a-file.ex similarity index 100% rename from Task/One-of-n-lines-in-a-file/Elixir/one-of-n-lines-in-a-file.elixir rename to Task/One-of-n-lines-in-a-file/Elixir/one-of-n-lines-in-a-file.ex diff --git a/Task/One-of-n-lines-in-a-file/Euphoria/one-of-n-lines-in-a-file.euphoria b/Task/One-of-n-lines-in-a-file/Euphoria/one-of-n-lines-in-a-file.eu similarity index 100% rename from Task/One-of-n-lines-in-a-file/Euphoria/one-of-n-lines-in-a-file.euphoria rename to Task/One-of-n-lines-in-a-file/Euphoria/one-of-n-lines-in-a-file.eu diff --git a/Task/One-of-n-lines-in-a-file/Julia/one-of-n-lines-in-a-file.julia b/Task/One-of-n-lines-in-a-file/Julia/one-of-n-lines-in-a-file.jl similarity index 100% rename from Task/One-of-n-lines-in-a-file/Julia/one-of-n-lines-in-a-file.julia rename to Task/One-of-n-lines-in-a-file/Julia/one-of-n-lines-in-a-file.jl diff --git a/Task/One-of-n-lines-in-a-file/Kotlin/one-of-n-lines-in-a-file.kotlin b/Task/One-of-n-lines-in-a-file/Kotlin/one-of-n-lines-in-a-file.kts similarity index 100% rename from Task/One-of-n-lines-in-a-file/Kotlin/one-of-n-lines-in-a-file.kotlin rename to Task/One-of-n-lines-in-a-file/Kotlin/one-of-n-lines-in-a-file.kts diff --git a/Task/One-of-n-lines-in-a-file/OCaml/one-of-n-lines-in-a-file.ocaml b/Task/One-of-n-lines-in-a-file/OCaml/one-of-n-lines-in-a-file.ml similarity index 100% rename from Task/One-of-n-lines-in-a-file/OCaml/one-of-n-lines-in-a-file.ocaml rename to Task/One-of-n-lines-in-a-file/OCaml/one-of-n-lines-in-a-file.ml diff --git a/Task/One-of-n-lines-in-a-file/PascalABC.NET/one-of-n-lines-in-a-file.pas b/Task/One-of-n-lines-in-a-file/PascalABC.NET/one-of-n-lines-in-a-file.pas new file mode 100644 index 0000000000..c0ca6221be --- /dev/null +++ b/Task/One-of-n-lines-in-a-file/PascalABC.NET/one-of-n-lines-in-a-file.pas @@ -0,0 +1,18 @@ +## +function oneOfN(n: integer): integer; +begin + result := 0; + for var x := 0 to n-1 do + if random(x+1) = 0 then + result := x; +end; + +function oneOfNTest(n: integer := 10; trials: integer := 1_000_000): array of integer; +begin + result := new integer[n]; + if n >= 0 then + foreach var i in 1..trials do + result[oneOfN(n)] += 1; +end; + +oneOfNTest.println; diff --git a/Task/One-of-n-lines-in-a-file/PowerShell/one-of-n-lines-in-a-file-1.psh b/Task/One-of-n-lines-in-a-file/PowerShell/one-of-n-lines-in-a-file-1.ps1 similarity index 100% rename from Task/One-of-n-lines-in-a-file/PowerShell/one-of-n-lines-in-a-file-1.psh rename to Task/One-of-n-lines-in-a-file/PowerShell/one-of-n-lines-in-a-file-1.ps1 diff --git a/Task/One-of-n-lines-in-a-file/PowerShell/one-of-n-lines-in-a-file-2.psh b/Task/One-of-n-lines-in-a-file/PowerShell/one-of-n-lines-in-a-file-2.ps1 similarity index 100% rename from Task/One-of-n-lines-in-a-file/PowerShell/one-of-n-lines-in-a-file-2.psh rename to Task/One-of-n-lines-in-a-file/PowerShell/one-of-n-lines-in-a-file-2.ps1 diff --git a/Task/One-of-n-lines-in-a-file/Rust/one-of-n-lines-in-a-file.rust b/Task/One-of-n-lines-in-a-file/Rust/one-of-n-lines-in-a-file.rs similarity index 100% rename from Task/One-of-n-lines-in-a-file/Rust/one-of-n-lines-in-a-file.rust rename to Task/One-of-n-lines-in-a-file/Rust/one-of-n-lines-in-a-file.rs diff --git a/Task/One-of-n-lines-in-a-file/VBScript/one-of-n-lines-in-a-file.vb b/Task/One-of-n-lines-in-a-file/VBScript/one-of-n-lines-in-a-file.vbs similarity index 100% rename from Task/One-of-n-lines-in-a-file/VBScript/one-of-n-lines-in-a-file.vb rename to Task/One-of-n-lines-in-a-file/VBScript/one-of-n-lines-in-a-file.vbs diff --git a/Task/One-time-pad/C/one-time-pad.c b/Task/One-time-pad/C/one-time-pad.c new file mode 100644 index 0000000000..9e8fca2840 --- /dev/null +++ b/Task/One-time-pad/C/one-time-pad.c @@ -0,0 +1,425 @@ +#include +#include +#include +#include +#include +#include + +static void usage(FILE *out) { + fputs("use: 1tp [OPTION] FILE COMMAND [...]\n", out); + fputs("OPTION:\n", out); + fputs("\t-h, --help display help\n", out); + fputs("\t-m, --morse use morse code alphabet\n", out); + fputs("\t-p, --pad pad encrypted text\n", out); + fputs("\t-f, --file text is read from a file\n", out); + fputs("\t-o, --output FILE write en/de-crypted text to FILE\n", out); + fputs("COMMAND:\n", out); + fputs("\t-g, --generate [PAGES [ROWS [COLS [DIGITS]]]]\n", out); + fputs("\t-e, --encrypt [PAGE] [TEXT]\n", out); + fputs("\t-d, --decrypt [PAGE] [TEXT]\n", out); + fputs("\t-r, --remove\n", out); +} + +#ifdef _WIN32 +#include +#include +ssize_t getrandom(void *buf, size_t buflen, unsigned int flags) { + (void)flags; + ssize_t z = -1; + NTSTATUS s = BCryptGenRandom(NULL, buf, buflen, BCRYPT_USE_SYSTEM_PREFERRED_RNG); + if(NT_SUCCESS(s)) { + z = (ssize_t)buflen; + } else { + errno = EINVAL; + } + return z; +} +#else // Linux &c +#include +#endif//def _WIN32 + +enum { DIGITS_PER_COLUMN = 5 }; +enum { RANDOM_BLOCK_SIZE = 256 }; +enum { DIGIT_ERASE_CHAR = '-' }; +enum { COMMENT_CHAR = '#' }; + +static char const *filename1tp(char const *cs) { + size_t n = strlen(cs); + if((n < 4) || (strcmp(cs + n - 4, ".1tp") != 0)) { + char *s = malloc(n + 4 + 1); + if(!s) { + perror(""); + abort(); + } + cs = strcat(strcpy(s, cs), ".1tp"); + } + return cs; +} + +static int generate1tp(FILE *otp, char const *alphabet, size_t pages, size_t rows, size_t cols, size_t digits, char const *filename) { + int failed = 0; + do { + size_t const sizeof_alphabet = strlen(alphabet); + size_t count = pages * rows * cols * digits; + if((((count / pages) / rows) / cols) != digits) { + fputs("pad too big\n", stderr); + break; + } + time_t t = time(NULL); + struct tm utc = *gmtime(&t); + int r = fprintf(otp, "# %i/%.2i/%.2i-%.2i:%.2i:%.2i\n", + 1900 + utc.tm_year, utc.tm_mon + 1, utc.tm_mday, + utc.tm_hour, utc.tm_min, utc.tm_sec + ); + if((r > 0) && (pages > 1)) { + r = fprintf(otp, "#[1]\n"); + } + if((failed = r < 0)) { + perror(filename); + break; + } + size_t const threshold = -sizeof_alphabet % sizeof_alphabet; + for(size_t p = 1, r = 0, c = 0, d = 0; + !failed && (r < rows) && (count > 0); + count-- + ) { + int x; + // get random alphabet using Lemire's debiased integer multiplication method + // https://lemire.me/blog/2019/06/06/nearly-divisionless-random-integer-generation-on-various-systems/ + for(;;) { + static int n = 0; + static unsigned char randombyte[RANDOM_BLOCK_SIZE]; + if(n == 0) { + if(getrandom(randombyte, RANDOM_BLOCK_SIZE, 0) < 0) { + perror(""); + return -1; + } + n = RANDOM_BLOCK_SIZE; + } + n--; + size_t r = randombyte[n]; + size_t m = r * sizeof_alphabet; + size_t l = m % (1 << CHAR_BIT); + if(l >= threshold) { + x = m >> CHAR_BIT; + break; + } + } + int a = alphabet[x]; + if((failed = fputc(a, otp) != a)) { + perror(filename); + break; + } + if(++d == digits) { + d = 0; + if(++c == cols) { + c = 0; + if((failed = fputc('\n', otp) != '\n')) { + perror(filename); + break; + } + if(++r == rows) { + r = 0; + if(++p > pages) { // > because page numbers run from 1..N + break; + } + fprintf(otp, "#[%zu]\n", p); + } + } else { + if((failed = fputc(' ', otp) != ' ')) { + perror(filename); + break; + } + } + } + } + fflush(otp); + } while(0) + ; + return failed; +} + +static int load1tp(FILE *otp, char **sp, size_t *lenp, char const *filename) { + rewind(otp); + int failed = 0; + do { + failed = fseek(otp, 0, SEEK_END) != 0; + if(failed) break; + long n = ftell(otp); + if((failed = n < 0)) break; + size_t len = n; + char *s = calloc(len + 1, 1); + *sp = s; + if(!s) { + perror(""); + abort(); + } + rewind(otp); + len = fread(s, 1, len, otp); + if((failed = ferror(otp))) break; + *lenp = len; + } while(0) + ; + if(failed) { + perror(filename); + } + return failed; +} + +static int save1tp(FILE *otp, char const *cs, size_t len, char const *filename) { + rewind(otp); + fwrite(cs, 1, len, otp); + int failed = ferror(otp); + if(failed) { + perror(filename); + } + return failed; +} + +static char const *getmessage(char *message, int asfile) { + if(asfile) { + char const *filename = message; + FILE *in = strcmp(filename, "-'") ? fopen(filename, "r") : stdin; + if(!in) { + perror(filename); + return NULL; + } + size_t n = 0; + size_t z = BUFSIZ-1; + message = malloc(BUFSIZ); + if(!message) { + perror(""); + abort(); + } + do { + size_t u = fread(message + n, 1, z - n, in); + if(ferror(in)) { + perror(filename); + return NULL; + } + n += u; + if(n == z) { + z += BUFSIZ; + message = realloc(message, z + 1); + if(!message) { + perror(filename); + abort(); + } + } + } while(!feof(in)) + ; + message[n] = '\0'; + if(in != stdin) { + fclose(in); + } + } + return message; +} + +#define OPTION(OPTION__args,OPTION__short,...) \ + if((*(OPTION__short) && !strcmp((OPTION__args), ("-"OPTION__short))) \ + || (*(__VA_ARGS__"") && !strcmp((OPTION__args), ("--"__VA_ARGS__"")))) + +int main(int argc, char **argv) { + char const *alphabet_characters = "_0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + char const *alphabet = strchr(alphabet_characters, 'A'); + int pad = 0; + int asfile = 0; + char const *outfile = NULL; + FILE *out = stdout; + + int argi = 1; + while((argi < argc) && (*argv[argi] == '-')) { + char const *args = argv[argi]; + OPTION(args, "h", "help") { + argi++; + usage(stdout); + return EXIT_SUCCESS; + } + OPTION(args, "m", "morse") { + argi++; + alphabet = strchr(alphabet_characters, '_'); + continue; + } + OPTION(args, "p", "pad") { + argi++; + pad = 1; + continue; + } + OPTION(args, "f", "file") { + argi++; + asfile = 1; + continue; + } + OPTION(args, "o", "output") { + argi++; + if(argi < argc) { + outfile = argv[argi++]; + continue; + } + } + usage(stderr); + return EXIT_FAILURE; + } + if((argi + 2) > argc) { + usage(stderr); + return EXIT_FAILURE; + } + + int failed = 0; + size_t const sizeof_alphabet = strlen(alphabet); + char const *filename = filename1tp(argv[argi++]); + FILE *otp = NULL; + char *s = NULL; + size_t n = 0; + if(outfile) { + out = fopen(outfile, "w"); + failed = !out; + } + if(!failed) do { + char const *command = argv[argi++]; + OPTION(command, "g", "generate") { + size_t digits = DIGITS_PER_COLUMN; + size_t cols = DIGITS_PER_COLUMN; + size_t rows = cols * DIGITS_PER_COLUMN; + size_t pages = rows * DIGITS_PER_COLUMN; + if(argi < argc) { + pages = strtoul(argv[argi++], NULL, 10); + if((failed |= !pages)) { + fputs("invalid number of pages\n", stderr); + } + } + if(argi < argc) { + rows = strtoul(argv[argi++], NULL, 10); + if((failed |= !rows)) { + fputs("invalid number of rows\n", stderr); + } + } + if(argi < argc) { + cols = strtoul(argv[argi++], NULL, 10); + if((failed |= !cols)) { + fputs("invalid number of columns\n", stderr); + } + } + if(argi < argc) { + digits = strtoul(argv[argi++], NULL, 10); + if((failed |= !digits)) { + fputs("invalid number of digits\n", stderr); + } + } + if(failed) break; + + otp = fopen(filename, "w+"); + if((failed = !otp)) { + perror(filename); + break; + } + failed = generate1tp(otp, alphabet, pages, rows, cols, digits, filename); + if(failed) break; + continue; + } + + // all other commands load the .1tp file + otp = fopen(filename, "r+"); + if((failed = !otp)) { + perror(filename); + break; + } + failed = load1tp(otp, &s, &n, filename); + if(failed) break; + + OPTION(command, "r", "remove") { + // overwrite with zero before removing file + memset(s, 0, n); + failed = save1tp(otp, s, n, filename); + fclose(otp); + otp = NULL; + remove(filename); + continue; + } + + // encrypt and decrypt share common code + int direction = 0; + OPTION(command, "e", "encrypt") { + direction = 1; + } + OPTION(command, "d", "decrypt") { + direction = -1; + } + if((failed = !direction)) { + fputs("unknown command\n", stderr); + break; + } + if((failed = argi >= argc)) { + fputs("missing message\n", stderr); + break; + } + char *t = s; + if((argi + 1) < argc) { + // select page + char page[32]; + char *args = argv[argi++]; + sprintf(page, "#[%.28s]", args); + t = strstr(s, page); + if((failed = !t)) { + fputs("invalid page number\n", stderr); + break; + } + } + char const *message = getmessage(argv[argi], asfile); + if((failed = !message)) break; + + for(int c; (c = *message++); ) { + c = toupper(c); + char const *a = strchr(alphabet, c); + if(!strchr(alphabet, c)) continue; + // skip non-coding characters + while((*t == ' ') || (*t == '\n') + || (*t == DIGIT_ERASE_CHAR) || (*t == COMMENT_CHAR) + ) { + for(; (*t == ' ') || (*t == '\n'); t++) + ; + while((*t == DIGIT_ERASE_CHAR) || (*t == COMMENT_CHAR)) { + for(t++; *t && (*t != '\n'); t++) + ; + } + } + if((failed = !*t)) { + fputs("end of pad reached\n", stderr); + break; + } + char const *b = strchr(alphabet, *t); + int x = a - alphabet; + int y = b - alphabet; + x = (x + (sizeof_alphabet + (y * direction))) % sizeof_alphabet; + c = alphabet[x]; + // erase used digit + *t++ = DIGIT_ERASE_CHAR; + if((failed = fputc(c, out) != c)) { + perror(outfile); + break; + } + } + // erase remaining digits on row + // optionally pad output to row length + for(int c; (c = *t) && (c != '\n'); t++) { + if(c != ' ') { + if(pad && !failed) { + if((failed = fputc(c, out) != c)) { + perror(outfile); + } + } + *t = DIGIT_ERASE_CHAR; + } + } + failed |= save1tp(otp, s, n, filename); + } while(0) + ; + if(out != stdout) { + fclose(out); + } + if(otp) { + fclose(otp); + } + return failed ? EXIT_FAILURE : EXIT_SUCCESS; +} diff --git a/Task/One-time-pad/Kotlin/one-time-pad.kotlin b/Task/One-time-pad/Kotlin/one-time-pad.kts similarity index 100% rename from Task/One-time-pad/Kotlin/one-time-pad.kotlin rename to Task/One-time-pad/Kotlin/one-time-pad.kts diff --git a/Task/OpenGL/Ada/opengl.ada b/Task/OpenGL/Ada/opengl.adb similarity index 100% rename from Task/OpenGL/Ada/opengl.ada rename to Task/OpenGL/Ada/opengl.adb diff --git a/Task/OpenGL/Delphi/opengl.delphi b/Task/OpenGL/Delphi/opengl.pas similarity index 100% rename from Task/OpenGL/Delphi/opengl.delphi rename to Task/OpenGL/Delphi/opengl.pas diff --git a/Task/OpenGL/Euphoria/opengl.euphoria b/Task/OpenGL/Euphoria/opengl.eu similarity index 100% rename from Task/OpenGL/Euphoria/opengl.euphoria rename to Task/OpenGL/Euphoria/opengl.eu diff --git a/Task/OpenGL/Julia/opengl.julia b/Task/OpenGL/Julia/opengl.jl similarity index 100% rename from Task/OpenGL/Julia/opengl.julia rename to Task/OpenGL/Julia/opengl.jl diff --git a/Task/OpenGL/Kotlin/opengl.kotlin b/Task/OpenGL/Kotlin/opengl.kts similarity index 100% rename from Task/OpenGL/Kotlin/opengl.kotlin rename to Task/OpenGL/Kotlin/opengl.kts diff --git a/Task/OpenGL/OCaml/opengl.ocaml b/Task/OpenGL/OCaml/opengl.ml similarity index 100% rename from Task/OpenGL/OCaml/opengl.ocaml rename to Task/OpenGL/OCaml/opengl.ml diff --git a/Task/OpenGL/Rust/opengl.rust b/Task/OpenGL/Rust/opengl.rs similarity index 100% rename from Task/OpenGL/Rust/opengl.rust rename to Task/OpenGL/Rust/opengl.rs diff --git a/Task/OpenWebNet-password/Delphi/openwebnet-password.delphi b/Task/OpenWebNet-password/Delphi/openwebnet-password.pas similarity index 100% rename from Task/OpenWebNet-password/Delphi/openwebnet-password.delphi rename to Task/OpenWebNet-password/Delphi/openwebnet-password.pas diff --git a/Task/OpenWebNet-password/EasyLang/openwebnet-password.easy b/Task/OpenWebNet-password/EasyLang/openwebnet-password.easy index 57f6c46a31..8b5f5f0ed5 100644 --- a/Task/OpenWebNet-password/EasyLang/openwebnet-password.easy +++ b/Task/OpenWebNet-password/EasyLang/openwebnet-password.easy @@ -3,9 +3,7 @@ func calcpass passw$ nonce$ . passw = number passw$ for c$ in strchars nonce$ if c$ <> "0" - if start = 1 - num2 = passw - . + if start = 1 : num2 = passw start = 0 . if c$ = "1" @@ -43,11 +41,11 @@ func calcpass passw$ nonce$ . if c$ <> "0" and c$ <> "9" num1 = bitor num1 num2 . - num2 = num1 + num2 = bitand 0xffffffff num1 . - return num1 + return bitand 0xffffffff num1 . -proc test_passwd passwd$ nonce$ expected$ . . +proc test_passwd passwd$ nonce$ expected$ . res = calcpass passwd$ nonce$ m$ = passwd$ & " " & nonce$ & " " & res & " " & expected$ if res = number expected$ diff --git a/Task/OpenWebNet-password/Julia/openwebnet-password.julia b/Task/OpenWebNet-password/Julia/openwebnet-password.jl similarity index 100% rename from Task/OpenWebNet-password/Julia/openwebnet-password.julia rename to Task/OpenWebNet-password/Julia/openwebnet-password.jl diff --git a/Task/OpenWebNet-password/Kotlin/openwebnet-password.kotlin b/Task/OpenWebNet-password/Kotlin/openwebnet-password.kts similarity index 100% rename from Task/OpenWebNet-password/Kotlin/openwebnet-password.kotlin rename to Task/OpenWebNet-password/Kotlin/openwebnet-password.kts diff --git a/Task/OpenWebNet-password/PascalABC.NET/openwebnet-password.pas b/Task/OpenWebNet-password/PascalABC.NET/openwebnet-password.pas new file mode 100644 index 0000000000..c851d1aa63 --- /dev/null +++ b/Task/OpenWebNet-password/PascalABC.NET/openwebnet-password.pas @@ -0,0 +1,47 @@ +const + INT_BITS = 32; + +function rotateLeft(n, d: longword) := (n shl d) or (n shr (INT_BITS - d)); + +function rotateRight(n, d: longword) := (n shr d) or (n shl (INT_BITS - d)); + +function ownCalcPass(password, nonce: string): longword; +begin + var start := true; + + foreach var c in nonce do + begin + if (c <> '0') and start then + begin + result := password.tointeger; + start := false; + end; + case c of + '0': ; + '1': result := rotateRight(result, 7); + '2': result := rotateRight(result, 4); + '3': result := rotateRight(result, 3); + '4': result := rotateLeft(result, 1); + '5': result := rotateLeft(result, 5); + '6': result := rotateLeft(result, 12); + '7': result := (result and $0000FF00) or result shl 24 + or (result and $00FF0000) shr 16 or (result and $FF000000) shr 8; + '8': result := result shl 16 or result shr 24 or (result and $00FF0000) shr 8; + '9': result := not result; + else raise new Exception('non-digit in nonce.'); + end; + end; +end; + +procedure testPasswordCalc(password, nonce: string; expected: longword); +begin + var res := ownCalcPass(password, nonce); + print(if res = expected then 'PASS ' else 'FAIL '); + println(password, nonce, res, expected); +end; + +begin + testPasswordCalc('12345', '603356072', 25280520); + testPasswordCalc('12345', '410501656', 119537670); + testPasswordCalc('12345', '630292165', 4269684735); +end. diff --git a/Task/OpenWebNet-password/Rust/openwebnet-password.rs b/Task/OpenWebNet-password/Rust/openwebnet-password.rs new file mode 100644 index 0000000000..40e6b5a6e0 --- /dev/null +++ b/Task/OpenWebNet-password/Rust/openwebnet-password.rs @@ -0,0 +1,113 @@ +fn own_password_calculation(password: i64, nonce: &str) -> i64 { + const M1: i64 = 0xFFFF_FFFF; + const M8: i64 = 0xFFFF_FFF8; + const M16: i64 = 0xFFFF_FFF0; + const M128: i64 = 0xFFFF_FF80; + const M16777216: i64 = 0xFF00_0000; + + let mut flag = true; + let mut number1 = 0; + let mut number2 = 0; + + for ch in nonce.chars() { + number2 = number2 & M1; + + match ch { + '1' => { + if flag { number2 = password; } + flag = false; + number1 = number2 & M128; + number1 = number1 >> 7; + number2 = number2 << 25; + number1 = number1 + number2; + }, + + '2' => { + if flag { number2 = password; } + flag = false; + number1 = number2 & M16; + number1 = number1 >> 4; + number2 = number2 << 28; + number1 = number1 + number2; + }, + + '3' => { + if flag { number2 = password; } + flag = false; + number1 = number2 & M8; + number1 = number1 >> 3; + number2 = number2 << 29; + number1 = number1 + number2; + }, + + '4' => { + if flag { number2 = password; } + flag = false; + number1 = number2 << 1; + number2 = number2 >> 31; + number1 = number1 + number2; + }, + + '5' => { + if flag { number2 = password; } + flag = false; + number1 = number2 << 5; + number2 = number2 >> 27; + number1 = number1 + number2; + }, + + '6' => { + if flag { number2 = password; } + flag = false; + number1 = number2 << 12; + number2 = number2 >> 20; + number1 = number1 + number2; + }, + + '7' => { + if flag { number2 = password; } + flag = false; + number1 = number2 & 0xFF00; + number1 = number1 + ((number2 & 0xFF) << 24); + number1 = number1 + ((number2 & 0xFF0000) >> 16); + number2 = (number2 & M16777216) >> 8; + number1 = number1 + number2; + }, + + '8' => { + if flag { number2 = password; } + flag = false; + number1 = number2 & 0xFFFF; + number1 = number1 << 16; + number1 = number1 + (number2 >> 24); + number2 = number2 & 0xFF0000; + number2 = number2 >> 8; + number1 = number1 + number2; + }, + + '9' => { + if flag { number2 = password; } + flag = false; + number1 = !number2; + }, + + _ => { + number1 = number2; + }, + } + number2 = number1; + } + + return number1 & M1; +} + +fn own_password_calculation_test(password: &str, nonce: &str, expected: i64) { + let result = own_password_calculation(password.parse::().unwrap(), nonce); + let message = format!("{} {} {} {}", password, nonce, result, expected); + println!("{} {}", if result == expected { "PASS" } else { "FAIL" }, message); +} + +fn main() { + own_password_calculation_test("12345", "603356072", 25280520); + own_password_calculation_test("12345", "410501656", 119537670); +} diff --git a/Task/Operator-precedence/PascalABC.NET/operator-precedence.pas b/Task/Operator-precedence/PascalABC.NET/operator-precedence.pas new file mode 100644 index 0000000000..5c719cc19b --- /dev/null +++ b/Task/Operator-precedence/PascalABC.NET/operator-precedence.pas @@ -0,0 +1,11 @@ +Table of operations priorities: + +** 1 (highest) +@, not, L , +, - (unary), new 2 +*, /, div, mod, and, shl, shr, as, is 3 ++, - (binary), or, xor 4 +.. 5 += , <> , < , > , <=, >=, in 6 +?: 7 (lowest) + +Brackets are used to change the order of operations in expressions. diff --git a/Task/Operator-precedence/Rye/operator-precedence-1.rye b/Task/Operator-precedence/Rye/operator-precedence-1.rye new file mode 100644 index 0000000000..3ebd0f1dbc --- /dev/null +++ b/Task/Operator-precedence/Rye/operator-precedence-1.rye @@ -0,0 +1,2 @@ +;Regular word takes the first argument from the right +Str: " Hello World" diff --git a/Task/Operator-precedence/Rye/operator-precedence-2.rye b/Task/Operator-precedence/Rye/operator-precedence-2.rye new file mode 100644 index 0000000000..89de3235f4 --- /dev/null +++ b/Task/Operator-precedence/Rye/operator-precedence-2.rye @@ -0,0 +1,2 @@ +;Dot-word left (immediate) +10 .inc .inc ; returns 11 diff --git a/Task/Operator-precedence/Rye/operator-precedence-3.rye b/Task/Operator-precedence/Rye/operator-precedence-3.rye new file mode 100644 index 0000000000..4e86ec6969 --- /dev/null +++ b/Task/Operator-precedence/Rye/operator-precedence-3.rye @@ -0,0 +1,2 @@ +;Op-word Left-to-right +10 + 5 * 6 ;returns 90 diff --git a/Task/Operator-precedence/Rye/operator-precedence-4.rye b/Task/Operator-precedence/Rye/operator-precedence-4.rye new file mode 100644 index 0000000000..cb9bcec1b9 --- /dev/null +++ b/Task/Operator-precedence/Rye/operator-precedence-4.rye @@ -0,0 +1,2 @@ +;Pipe-word left , after full evaluation of the left functions +5 + 5 |add 10 ;5 + 5 evals first, then add 10 diff --git a/Task/Operator-precedence/Rye/operator-precedence-5.rye b/Task/Operator-precedence/Rye/operator-precedence-5.rye new file mode 100644 index 0000000000..5b5b191eb8 --- /dev/null +++ b/Task/Operator-precedence/Rye/operator-precedence-5.rye @@ -0,0 +1,4 @@ +;More examples +10 .inc - 10 .dec .dec ; returns 3 +"AB" .lower "bc" .upper ; returns abBC +3 * 4 - 5 " ravens" ; returns "7 ravens" diff --git a/Task/Operator-precedence/V-(Vlang)/operator-precedence.v b/Task/Operator-precedence/V-(Vlang)/operator-precedence.v new file mode 100644 index 0000000000..631ee5fbb9 --- /dev/null +++ b/Task/Operator-precedence/V-(Vlang)/operator-precedence.v @@ -0,0 +1,6 @@ +Precedence Operator + 5 * / % << >> >>> & + 4 + - | ^ + 3 == != < <= > >= + 2 && + 1 || diff --git a/Task/Optional-parameters/ALGOL-68/optional-parameters.alg b/Task/Optional-parameters/ALGOL-68/optional-parameters.alg index 516994e614..4e88e2460d 100644 --- a/Task/Optional-parameters/ALGOL-68/optional-parameters.alg +++ b/Task/Optional-parameters/ALGOL-68/optional-parameters.alg @@ -24,12 +24,18 @@ BEGIN # do the sort .... # END # configurable sort # ; -# example calls # -[ 1 : 2, 1 : 3 ]STRING data := ( ( "a", "bb", "cde" ), ( "x", "abcdef", "Q" ) ); +BEGIN # example calls # + [ 1 : 2, 1 : 3 ]STRING data := ( ( "a", "bb", "cde" ), ( "x", "abcdef", "Q" ) ); -# sort data, default comparison, first column, reverse order # -configurable sort( data, ( TRUE ) ); -# sort data, second column, ignore first chaacter when sorting, normal order # -configurable sort( data, ( 2, ( STRING a, STRING b )INT: default compare( a[ LWB a + 1 : ], b[ LWB b + 1 : ] ) ) ); -# default sort # -configurable sort( data, () ) + # sort data, default comparison, first column, reverse order # + configurable sort( data, ( TRUE ) ); + # sort data, second column, ignore first chaacter when sorting, normal order # + configurable sort( data, ( 2 + , ( STRING a, STRING b )INT: default compare( a[ LWB a + 1 : ] + , b[ LWB b + 1 : ] + ) + ) + ); + # default sort # + configurable sort( data, () ) +END diff --git a/Task/Optional-parameters/Ada/optional-parameters-1.ada b/Task/Optional-parameters/Ada/optional-parameters-1.adb similarity index 100% rename from Task/Optional-parameters/Ada/optional-parameters-1.ada rename to Task/Optional-parameters/Ada/optional-parameters-1.adb diff --git a/Task/Optional-parameters/Ada/optional-parameters-2.ada b/Task/Optional-parameters/Ada/optional-parameters-2.adb similarity index 100% rename from Task/Optional-parameters/Ada/optional-parameters-2.ada rename to Task/Optional-parameters/Ada/optional-parameters-2.adb diff --git a/Task/Optional-parameters/Arturo/optional-parameters.arturo b/Task/Optional-parameters/Arturo/optional-parameters.arturo index 188833a281..d573374b31 100644 --- a/Task/Optional-parameters/Arturo/optional-parameters.arturo +++ b/Task/Optional-parameters/Arturo/optional-parameters.arturo @@ -1,11 +1,9 @@ sortTable: function [tbl][ - column: "0" - reversed?: false - unless null? c: <= attr 'column -> column: to :string c - unless null? attr 'reverse -> reversed?: true + reversed?: (attr 'reverse)?? false + column: to :string (attr 'column)?? 0 - result: new sort.by: column map tbl 'r [ - to :dictionary flatten couple 0..dec size r r + result: sort.by: column map tbl 'r [ + to :dictionary flatten couple @ 0..dec size r r ] if reversed? -> reverse 'result diff --git a/Task/Optional-parameters/Delphi/optional-parameters.delphi b/Task/Optional-parameters/Delphi/optional-parameters.pas similarity index 100% rename from Task/Optional-parameters/Delphi/optional-parameters.delphi rename to Task/Optional-parameters/Delphi/optional-parameters.pas diff --git a/Task/Optional-parameters/Elixir/optional-parameters.elixir b/Task/Optional-parameters/Elixir/optional-parameters.ex similarity index 100% rename from Task/Optional-parameters/Elixir/optional-parameters.elixir rename to Task/Optional-parameters/Elixir/optional-parameters.ex diff --git a/Task/Optional-parameters/Julia/optional-parameters-1.julia b/Task/Optional-parameters/Julia/optional-parameters-1.jl similarity index 100% rename from Task/Optional-parameters/Julia/optional-parameters-1.julia rename to Task/Optional-parameters/Julia/optional-parameters-1.jl diff --git a/Task/Optional-parameters/Julia/optional-parameters-2.julia b/Task/Optional-parameters/Julia/optional-parameters-2.jl similarity index 100% rename from Task/Optional-parameters/Julia/optional-parameters-2.julia rename to Task/Optional-parameters/Julia/optional-parameters-2.jl diff --git a/Task/Optional-parameters/Kotlin/optional-parameters.kotlin b/Task/Optional-parameters/Kotlin/optional-parameters.kts similarity index 100% rename from Task/Optional-parameters/Kotlin/optional-parameters.kotlin rename to Task/Optional-parameters/Kotlin/optional-parameters.kts diff --git a/Task/Optional-parameters/OCaml/optional-parameters-1.ocaml b/Task/Optional-parameters/OCaml/optional-parameters-1.ml similarity index 100% rename from Task/Optional-parameters/OCaml/optional-parameters-1.ocaml rename to Task/Optional-parameters/OCaml/optional-parameters-1.ml diff --git a/Task/Optional-parameters/OCaml/optional-parameters-2.ocaml b/Task/Optional-parameters/OCaml/optional-parameters-2.ml similarity index 100% rename from Task/Optional-parameters/OCaml/optional-parameters-2.ocaml rename to Task/Optional-parameters/OCaml/optional-parameters-2.ml diff --git a/Task/Optional-parameters/REXX/optional-parameters-1.rexx b/Task/Optional-parameters/REXX/optional-parameters-1.rexx deleted file mode 100644 index 8333579e0d..0000000000 --- a/Task/Optional-parameters/REXX/optional-parameters-1.rexx +++ /dev/null @@ -1,23 +0,0 @@ -sortStrings: procedure expose @. /*the stemmed array is named: @. */ -col= 1 /*set some defaults (here and below). */ -reverse= 'NO' -order= 'LEXICOGRAPHIC' -arg options /*obtain the options (in uppercase). */ - do j=1 for words(options) /*examine all the words (options). */ - x= word(options, j) - select - when datatype(x, 'W') then col= x / 1 /*normalize the number. */ - when pos('=', x)==0 then order= x /*has it an equal sign? */ - otherwise parse var x nam '=' value /*get value.*/ - end /*select*/ - end /*j*/ - - /*╔═══════════════════════════════════════════════════════════╗ - ║ check for errors here: COL isn't a positive integer ···, ║ - ║ REVERSE value isn't NO or YES, ║ - ║ ORDER value is recognized ··· ║ - ╚═══════════════════════════════════════════════════════════╝*/ - - ... main body of string sort here ... - -return /*stick a fork in it, we're all done. */ diff --git a/Task/Optional-parameters/REXX/optional-parameters-2.rexx b/Task/Optional-parameters/REXX/optional-parameters-2.rexx deleted file mode 100644 index 3650df710f..0000000000 --- a/Task/Optional-parameters/REXX/optional-parameters-2.rexx +++ /dev/null @@ -1,8 +0,0 @@ -/*REXX example uses the SortStrings subroutine with some (passed) optional arguments. */ - - -@.1= 'one'; @.2= "two"; @.3= 'three' /*define an array (@.) of strings here.*/ - - -call sortStrings 'Reverse=no' 3 - /*stick a fork in it, we're all done. */ diff --git a/Task/Optional-parameters/REXX/optional-parameters.rexx b/Task/Optional-parameters/REXX/optional-parameters.rexx new file mode 100644 index 0000000000..b354bef8ff --- /dev/null +++ b/Task/Optional-parameters/REXX/optional-parameters.rexx @@ -0,0 +1,62 @@ +-- 11 Sep 2025 +include Setting + +say 'OPTIONAL PARAMETERS' +say version +say +call Stem +call Sort1 +call Sort1 'n',,'yes' +call Sort1 ,12,'' +call Sort1 'n',12,'yes' +say +call Sort2 +call Sort2 'order=n rev=yes' +call Sort2 'col=12' +call Sort2 'order=n col=12 rev=yes' +exit + +Stem: +-- Populate an array +procedure expose stem. +-- Your code... +return + +Sort1: +-- Comma separated positional parameters +procedure expose stem. +arg order,col,rev +call charout ,'Sort1:' 'Order='order 'Column='col 'Reverse='rev +if order = '' then + order='L' +if col = '' then + col=1 +rev=(Left(rev,1)='Y') +say ' ---> ' 'Order='order 'Column='col 'Reverse='rev +-- Your sort... +return + +Sort2: +-- Space separated named parameters +procedure expose stem. +arg xx +call charout ,'Sort2:' 'Parms='xx +order='L'; col=1; rev=0 +do n = 1 to Words(xx) + w=Word(xx,n); parse var w nam '=' val + select + when nam = 'ORDER' then + order=val + when nam = 'COL' then + col=val + when nam = 'REV' then + rev=(Left(val,1) = 'Y') + otherwise + nop + end +end +say ' ---> ' 'Order='order 'Column='col 'Reverse='rev +-- Your sort... +return + +include Math diff --git a/Task/Optional-parameters/Rust/optional-parameters.rust b/Task/Optional-parameters/Rust/optional-parameters.rs similarity index 100% rename from Task/Optional-parameters/Rust/optional-parameters.rust rename to Task/Optional-parameters/Rust/optional-parameters.rs diff --git a/Task/Optional-parameters/V-(Vlang)/optional-parameters.v b/Task/Optional-parameters/V-(Vlang)/optional-parameters.v new file mode 100644 index 0000000000..d349080fbc --- /dev/null +++ b/Task/Optional-parameters/V-(Vlang)/optional-parameters.v @@ -0,0 +1,32 @@ +@[params] +struct Params { + a int // default value is 0 + b int + c int = 20 +} + +fn a_fn(p Params) int { + return p.a + p.b + p.c +} + +fn b_fn(word string, num ?int) (string, int) { + val := if num == none {0} else {num} // unwrap option type to assign value + return word, val +} + +fn main() { + // using a struct as a parameter + v := a_fn(Params{a: 1, b: 2, c: 3}) // same order, with new value given to `c` + println("v = ${v}") + w := a_fn(Params{c: 3, b: 2, a: 1}) // different order + println("w = ${w}") + x := a_fn(Params{c: 2}) // only one field + println("x = ${x}") + y := a_fn(Params{}) // no fields; given value of `c` and default values used + println("y = ${y}") + z := a_fn() // no parameters via @[params]; given value of `c` and default values used + println("z = ${z}") + // using an option type as a parameter + println(b_fn('hello', 1000)) + println(b_fn('hello')) // no second parameter usage possible because option type (`?`) +} diff --git a/Task/Order-by-pair-comparisons/Arturo/order-by-pair-comparisons.arturo b/Task/Order-by-pair-comparisons/Arturo/order-by-pair-comparisons.arturo index a0f09db7d6..a3e5465518 100644 --- a/Task/Order-by-pair-comparisons/Arturo/order-by-pair-comparisons.arturo +++ b/Task/Order-by-pair-comparisons/Arturo/order-by-pair-comparisons.arturo @@ -11,7 +11,7 @@ findSpot: function [l,e][ return dec size l ] -sortedLst: new [] +sortedLst: [] loop lst 'element -> insert 'sortedLst findSpot sortedLst element element diff --git a/Task/Order-by-pair-comparisons/Crystal/order-by-pair-comparisons.cr b/Task/Order-by-pair-comparisons/Crystal/order-by-pair-comparisons.cr new file mode 100644 index 0000000000..b567cbb22d --- /dev/null +++ b/Task/Order-by-pair-comparisons/Crystal/order-by-pair-comparisons.cr @@ -0,0 +1,17 @@ +class Array + def sort_with_prompt + rels = { "<" => -1, "=" => 0, ">" => 1 } + n = 0 + puts "Answer with <, = or >" + sort {|a, b| + n += 1 + loop do + print "#{n}) #{a} < = > #{b} ?: " + ans = gets + break rels[ans] if ans.in?(rels.keys) + end + } + end +end + +p %w(violet red green indigo blue yellow orange).sort_with_prompt diff --git a/Task/Order-by-pair-comparisons/EasyLang/order-by-pair-comparisons.easy b/Task/Order-by-pair-comparisons/EasyLang/order-by-pair-comparisons.easy new file mode 100644 index 0000000000..91e9a254d2 --- /dev/null +++ b/Task/Order-by-pair-comparisons/EasyLang/order-by-pair-comparisons.easy @@ -0,0 +1,29 @@ +proc insort item$ &arr$[] . + mid = 1 + lo = 0 + hi = len arr$[] + 1 + while lo + 1 < hi + mid = (lo + hi) div 2 + repeat + write "Is " & item$ & " less than " & arr$[mid] & "? y/n: " + ans$ = input + print ans$ + until ans$ = "y" or ans$ = "n" + . + if ans$ = "y" + hi = mid + else + lo = mid + . + . + arr$[] &= "" + for i = len arr$[] downto hi + 1 + arr$[i] = arr$[i - 1] + . + arr$[hi] = item$ +. +items$[] = [ "violet" "red" "green" "indigo" "blue" "yellow" "orange" ] +for item$ in items$[] + insort item$ ordered$[] +. +print ordered$[] diff --git a/Task/Order-by-pair-comparisons/Gleam/order-by-pair-comparisons.gleam b/Task/Order-by-pair-comparisons/Gleam/order-by-pair-comparisons.gleam new file mode 100644 index 0000000000..768e689f40 --- /dev/null +++ b/Task/Order-by-pair-comparisons/Gleam/order-by-pair-comparisons.gleam @@ -0,0 +1,17 @@ +import gleam/io +import gleam/list +import gleam/order.{Gt, Lt} +import in + +pub fn main() { + ["violet", "red", "green", "indigo", "blue", "yellow", "orange"] + |> list.sort(by: fn(a, b) { + io.print("Is " <> a <> " > " <> b <> "? (y/n) ") + case in.read_line() { + Ok("y\n") -> Gt + Ok(_) -> Lt + Error(_) -> panic as "Error reading from standard input." + } + }) + |> echo +} diff --git a/Task/Order-by-pair-comparisons/Julia/order-by-pair-comparisons.julia b/Task/Order-by-pair-comparisons/Julia/order-by-pair-comparisons.jl similarity index 100% rename from Task/Order-by-pair-comparisons/Julia/order-by-pair-comparisons.julia rename to Task/Order-by-pair-comparisons/Julia/order-by-pair-comparisons.jl diff --git a/Task/Order-by-pair-comparisons/Koka/order-by-pair-comparisons.koka b/Task/Order-by-pair-comparisons/Koka/order-by-pair-comparisons.koka new file mode 100644 index 0000000000..1465835ed8 --- /dev/null +++ b/Task/Order-by-pair-comparisons/Koka/order-by-pair-comparisons.koka @@ -0,0 +1,41 @@ +import std/core/undiv +import std/os/readline + +fun treesort(xs : list, ?cmp: (string, string) -> e order) : e list + recur/treesort(xs, Nil) + +fun recur/treesort(xs : list, res : list, ?cmp: (string, string) -> e order) : e list + match(xs) + Cons(x, xx) -> + val (lo, hi) = partition(x, xx) + treesort(lo, Cons(x, treesort(hi, res.pretend-decreasing)).pretend-decreasing) + Nil -> res + +fun partition(^x : string, ys : list, ?cmp: (string, string) -> e order) + match(ys) + Nil -> (Nil, Nil) + Cons(y, yy) -> + match ?cmp(y, x) + Lt -> + val (lo, hi) = partition(x, yy) + (Cons(y, lo), hi) + _ -> + val (lo, hi) = partition(x, yy) + (lo, Cons(y, hi)) + +effect ask + fun ask(s1: string, s2: string): order + +fun main() + with handler + fun ask(s1, s2) + print("Is " ++ s1 ++ " <, =, or > " ++ s2 ++ "? ") + var done := Nothing + while {done.is-nothing} + match readline() + ">" -> done := Just(Gt) + "<" -> done := Just(Lt) + "=" -> done := Just(Eq) + _ -> println("Invalid input") + done.unjust + ["violet", "red", "green", "indigo", "blue", "yellow", "orange"].treesort(?cmp=ask) diff --git a/Task/Order-by-pair-comparisons/OCaml/order-by-pair-comparisons-1.ocaml b/Task/Order-by-pair-comparisons/OCaml/order-by-pair-comparisons-1.ml similarity index 100% rename from Task/Order-by-pair-comparisons/OCaml/order-by-pair-comparisons-1.ocaml rename to Task/Order-by-pair-comparisons/OCaml/order-by-pair-comparisons-1.ml diff --git a/Task/Order-by-pair-comparisons/OCaml/order-by-pair-comparisons-2.ocaml b/Task/Order-by-pair-comparisons/OCaml/order-by-pair-comparisons-2.ml similarity index 100% rename from Task/Order-by-pair-comparisons/OCaml/order-by-pair-comparisons-2.ocaml rename to Task/Order-by-pair-comparisons/OCaml/order-by-pair-comparisons-2.ml diff --git a/Task/Order-by-pair-comparisons/Pluto/order-by-pair-comparisons.pluto b/Task/Order-by-pair-comparisons/Pluto/order-by-pair-comparisons.pluto new file mode 100644 index 0000000000..703536c1a0 --- /dev/null +++ b/Task/Order-by-pair-comparisons/Pluto/order-by-pair-comparisons.pluto @@ -0,0 +1,37 @@ +require "io2" +local fmt = require "fmt" + +-- Inserts item x in list a, and keeps it sorted assuming a is already sorted. +-- If x is already in a, inserts it to the right of the rightmost x. +local function insort_right(a, x, q) + local lo = 1 + local hi = #a + 1 + local yn = "ynYN":split("") + while lo < hi do + local mid = (lo + hi) // 2 + ++q + local prompt = string.format("%2d: Is %6s less than %6s ? y/n: ", q, x, a[mid]) + local less = string.lower(io.readOpt(prompt, yn)) == "y" + if less then + hi = mid + else + lo = mid + 1 + end + end + a:insert(lo, x) + return q +end + +local function order(items) + local ordered = {} + local q = 0 + for items as item do + q = insort_right(ordered, item, q) + end + return ordered +end + +local items = "violet red green indigo blue yellow orange":split(" ") +local ordered = order(items) +print("\nThe colors of the rainbow, in sorted order, are:") +fmt.lprint(ordered) diff --git a/Task/Order-by-pair-comparisons/Prolog/order-by-pair-comparisons-1.pro b/Task/Order-by-pair-comparisons/Prolog/order-by-pair-comparisons-1.pro new file mode 100644 index 0000000000..afde62e867 --- /dev/null +++ b/Task/Order-by-pair-comparisons/Prolog/order-by-pair-comparisons-1.pro @@ -0,0 +1,12 @@ +ask_sort(List, Sorted) :- predsort(ask, List, Sorted). + +ask(Cmp, Left, Right) :- + format("Comparing ~w with ~w: ", [Left, Right]), + get_single_char(Cmp0), + char_code(Cmp1, Cmp0), + ( memberchk(Cmp1, [<, =, >]) + -> Cmp = Cmp1, + writeln(Cmp1) + ; format("Please answer <, = or >."), + ask(Cmp, Left, Right) + ). diff --git a/Task/Order-by-pair-comparisons/Prolog/order-by-pair-comparisons-2.pro b/Task/Order-by-pair-comparisons/Prolog/order-by-pair-comparisons-2.pro new file mode 100644 index 0000000000..4603eb6939 --- /dev/null +++ b/Task/Order-by-pair-comparisons/Prolog/order-by-pair-comparisons-2.pro @@ -0,0 +1,15 @@ +?- ask_sort(["violet", "red", "green", "indigo", "blue", "yellow", "orange"], Sorted). +Comparing red with green: < +Comparing violet with red: > +Comparing violet with green: > +Comparing indigo with blue: > +Comparing yellow with orange: > +Comparing blue with orange: > +Comparing blue with yellow: > +Comparing red with orange: < +Comparing green with orange: > +Comparing green with yellow: > +Comparing green with blue: < +Comparing violet with blue: > +Comparing violet with indigo: > +Sorted = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"]. diff --git a/Task/Order-disjoint-list-items/Arturo/order-disjoint-list-items.arturo b/Task/Order-disjoint-list-items/Arturo/order-disjoint-list-items.arturo index 304a1dfb1d..0e2f8d57e8 100644 --- a/Task/Order-disjoint-list-items/Arturo/order-disjoint-list-items.arturo +++ b/Task/Order-disjoint-list-items/Arturo/order-disjoint-list-items.arturo @@ -2,7 +2,7 @@ orderDisjoint: function [m,n][ ms: split.words m ns: split.words n - indexes: new [] + indexes: [] loop ns 'item [ idx: index ms item diff --git a/Task/Order-disjoint-list-items/EasyLang/order-disjoint-list-items.easy b/Task/Order-disjoint-list-items/EasyLang/order-disjoint-list-items.easy new file mode 100644 index 0000000000..271e3b1873 --- /dev/null +++ b/Task/Order-disjoint-list-items/EasyLang/order-disjoint-list-items.easy @@ -0,0 +1,31 @@ +func$ order data$ order$ . + data$[] = strsplit data$ " " + order$[] = strsplit order$ " " + for o to len order$[] + for d to len data$[] + if order$[o] = data$[d] + data$[d] = "" + break 1 + . + . + . + o = 1 + for d to len data$[] + if data$[d] = "" + data$[d] = order$[o] + o += 1 + if o > len order$[] + break 1 + . + . + . + r$ = data$[1] + for i = 2 to len data$[] + r$ &= " " & data$[i] + . + return r$ +. +tests$[][] = [ [ "the cat sat on the mat" "mat cat" ] [ "the cat sat on the mat" "cat mat" ] [ "A B C A B C A B C" "C A C A" ] [ "A B C A B D A B E" "E A D A" ] [ "A B" "B" ] [ "A B" "B A" ] [ "A B B A" "B A" ] ] +for i to len tests$[][] + print order tests$[i][1] tests$[i][2] +. diff --git a/Task/Order-disjoint-list-items/Elixir/order-disjoint-list-items.elixir b/Task/Order-disjoint-list-items/Elixir/order-disjoint-list-items.ex similarity index 100% rename from Task/Order-disjoint-list-items/Elixir/order-disjoint-list-items.elixir rename to Task/Order-disjoint-list-items/Elixir/order-disjoint-list-items.ex diff --git a/Task/Order-disjoint-list-items/FreeBASIC/order-disjoint-list-items.basic b/Task/Order-disjoint-list-items/FreeBASIC/order-disjoint-list-items.basic new file mode 100644 index 0000000000..b96a0a6daa --- /dev/null +++ b/Task/Order-disjoint-list-items/FreeBASIC/order-disjoint-list-items.basic @@ -0,0 +1,137 @@ +Function isInArray(arr() As Integer, value As Integer, count As Integer) As Boolean + For i As Integer = 0 To count - 1 + If arr(i) = value Then Return True + Next + Return False +End Function + +Sub Sort(arr() As Integer, count As Integer) + Dim As Integer i, j + For i = 0 To count - 2 + For j = i + 1 To count - 1 + If arr(i) > arr(j) Then Swap arr(i), arr(j) + Next j + Next i +End Sub + +Dim Shared As String*3 testm(12, 8) = { _ +{"the", "cat", "sat", "on", "the", "mat"}, _ +{"the", "cat", "sat", "on", "the", "mat"}, _ +{"A", "B", "C", "A", "B", "C", "A", "B", "C"}, _ +{"A", "B", "C", "A", "B", "D", "A", "B", "E"}, _ +{"A", "B"}, _ +{"A", "B"}, _ +{"A", "B", "B", "A"}, _ +{"A"}, _ +{"A", "B", "B", "A"}, _ +{"A", "B", "A", "B"}, _ +{"A", "B", "A", "B"}, _ +{"A", "B", "C", "C", "B", "A"}, _ +{"A", "B", "C", "C", "B", "A"} } + +Dim Shared As String*3 testn(12, 3) = { _ +{"mat", "cat"}, _ +{"cat", "mat"}, _ +{"C", "A", "C", "A"}, _ +{"E", "A", "D", "A"}, _ +{"B"}, _ +{"B", "A"}, _ +{"B", "A"}, _ +{"A"}, _ +{"A", "B"}, _ +{"A", "B"}, _ +{"B", "A", "B", "A"}, _ +{"A", "C", "A", "C"}, _ +{"C", "A", "C", "A"} } + +Sub OrderDisjoint(m() As String, n() As String, p() As String) + Dim As Integer rlen = Ubound(n) - Lbound(n) + 1 + Dim As Integer rdis(rlen - 1) + Dim As Integer i, j + Dim As String e + + For i = 0 To rlen - 1 + e = n(i) + For j = 0 To Ubound(m) + If m(j) = e And Not isInArray(rdis(), j + 1, rlen) Then + rdis(i) = j + 1 + Exit For + End If + Next j + Next i + + For i = 0 To rlen - 1 + If rdis(i) = 0 Then Print "DomainError": Exit Sub + Next i + + Sort(rdis(), rlen) + + For i = 0 To Ubound(m) + p(i) = m(i) + Next i + + For i = 0 To rlen - 1 + p(rdis(i) - 1) = n(i) + Next i +End Sub + +Sub TestOrderDisjoint() + Dim As Integer i, j + Dim As String m(), n(), p() + + For i = 0 To Ubound(testm, 1) '6 + Dim As Integer mCount = 0, nCount = 0 + + ' Count non-empty elements in testm + For j = 0 To Ubound(testm, 2) + If testm(i, j) <> "" Then mCount += 1 + Next j + + ' Count non-empty elements in testn + For j = 0 To Ubound(testn, 2) + If testn(i, j) <> "" Then nCount += 1 + Next j + + ' Resize dynamic arrays + Redim m(mCount - 1) + Redim n(nCount - 1) + Redim p(mCount - 1) + + ' Fill arrays m and n with non-empty elements + mCount = 0 + nCount = 0 + For j = 0 To Ubound(testm, 2) + If testm(i, j) <> "" Then + m(mCount) = testm(i, j) + mCount += 1 + End If + Next j + + For j = 0 To Ubound(testn, 2) + If testn(i, j) <> "" Then + n(nCount) = testn(i, j) + nCount += 1 + End If + Next j + + OrderDisjoint(m(), n(), p()) + + Print "[ "; + For j = 0 To Ubound(m) + Print m(j); " "; + Next j + Print Chr(8); ", "; + For j = 0 To Ubound(n) + Print n(j); " "; + Next j + Print "] => "; + For j = 0 To Ubound(p) + Print p(j); " "; + Next j + Print + Next i +End Sub + +TestOrderDisjoint() + +Sleep diff --git a/Task/Order-disjoint-list-items/Julia/order-disjoint-list-items-1.jl b/Task/Order-disjoint-list-items/Julia/order-disjoint-list-items-1.jl new file mode 100644 index 0000000000..3f67e3d262 --- /dev/null +++ b/Task/Order-disjoint-list-items/Julia/order-disjoint-list-items-1.jl @@ -0,0 +1,18 @@ +function order_disjoint(m::T, n::T) where T <: AbstractArray + rlen = length(n) + rdis = zeros(Int, rlen) + for (i, e) in enumerate(n) + j = something(findfirst(==(e), m), 0) + while j in rdis && j != 0 + j = something(findnext(==(e), m, j+1), 0) + end + rdis[i] = j + end + if 0 in rdis + throw(DomainError()) + end + sort!(rdis) + p = copy(m) + p[rdis] .= n + return p +end diff --git a/Task/Order-disjoint-list-items/Julia/order-disjoint-list-items-1.julia b/Task/Order-disjoint-list-items/Julia/order-disjoint-list-items-1.julia deleted file mode 100644 index 724a287bc9..0000000000 --- a/Task/Order-disjoint-list-items/Julia/order-disjoint-list-items-1.julia +++ /dev/null @@ -1,18 +0,0 @@ -function order_disjoint{T<:AbstractArray}(m::T, n::T) - rlen = length(n) - rdis = zeros(Int, rlen) - for (i, e) in enumerate(n) - j = findfirst(m, e) - while j in rdis && j != 0 - j = findnext(m, e, j+1) - end - rdis[i] = j - end - if 0 in rdis - throw(DomainError()) - end - sort!(rdis) - p = copy(m) - p[rdis] = n - return p -end diff --git a/Task/Order-disjoint-list-items/Julia/order-disjoint-list-items-2.jl b/Task/Order-disjoint-list-items/Julia/order-disjoint-list-items-2.jl new file mode 100644 index 0000000000..df4b1ad256 --- /dev/null +++ b/Task/Order-disjoint-list-items/Julia/order-disjoint-list-items-2.jl @@ -0,0 +1,24 @@ +testm = [["the", "cat", "sat", "on", "the", "mat"], + ["the", "cat", "sat", "on", "the", "mat"], + ["A", "B", "C", "A", "B", "C", "A", "B", "C"], + ["A", "B", "C", "A", "B", "D", "A", "B", "E"], + ["A", "B"], + ["A", "B"], + ["A", "B", "B", "A"], +] + +testn = [["mat", "cat"], + ["cat", "mat"], + ["C", "A", "C", "A"], + ["E", "A", "D", "A"], + ["B"], + ["B", "A"], + ["B", "A"], +] + +for i in 1:length(testm) + m = join(testm[i], " ") + n = join(testn[i], " ") + p = join(order_disjoint(testm[i], testn[i]), " ") + println(" (", m, ", ", n, ") => ", p) +end diff --git a/Task/Order-disjoint-list-items/Julia/order-disjoint-list-items-2.julia b/Task/Order-disjoint-list-items/Julia/order-disjoint-list-items-2.julia deleted file mode 100644 index fb88b51ce4..0000000000 --- a/Task/Order-disjoint-list-items/Julia/order-disjoint-list-items-2.julia +++ /dev/null @@ -1,24 +0,0 @@ -testm = {["the", "cat", "sat", "on", "the", "mat"], - ["the", "cat", "sat", "on", "the", "mat"], - ["A", "B", "C", "A", "B", "C", "A", "B", "C"], - ["A", "B", "C", "A", "B", "D", "A", "B", "E"], - ["A", "B"], - ["A", "B"], - ["A", "B", "B", "A"], - } - -testn = {["mat", "cat"], - ["cat", "mat"], - ["C", "A", "C", "A"], - ["E", "A", "D", "A"], - ["B"], - ["B", "A"], - ["B", "A"], - } - -for i in 1:length(testm) - m = join(testm[i], " ") - n = join(testn[i], " ") - p = join(order_disjoint(testm[i], testn[i]), " ") - println(" (", m, ", ", n, ") => ", p) -end diff --git a/Task/Order-disjoint-list-items/Kotlin/order-disjoint-list-items.kotlin b/Task/Order-disjoint-list-items/Kotlin/order-disjoint-list-items.kts similarity index 100% rename from Task/Order-disjoint-list-items/Kotlin/order-disjoint-list-items.kotlin rename to Task/Order-disjoint-list-items/Kotlin/order-disjoint-list-items.kts diff --git a/Task/Order-disjoint-list-items/PowerShell/order-disjoint-list-items.psh b/Task/Order-disjoint-list-items/PowerShell/order-disjoint-list-items.ps1 similarity index 100% rename from Task/Order-disjoint-list-items/PowerShell/order-disjoint-list-items.psh rename to Task/Order-disjoint-list-items/PowerShell/order-disjoint-list-items.ps1 diff --git a/Task/Order-two-numerical-lists/Ada/order-two-numerical-lists.ada b/Task/Order-two-numerical-lists/Ada/order-two-numerical-lists.adb similarity index 100% rename from Task/Order-two-numerical-lists/Ada/order-two-numerical-lists.ada rename to Task/Order-two-numerical-lists/Ada/order-two-numerical-lists.adb diff --git a/Task/Order-two-numerical-lists/Crystal/order-two-numerical-lists.cr b/Task/Order-two-numerical-lists/Crystal/order-two-numerical-lists.cr new file mode 100644 index 0000000000..a7d1778620 --- /dev/null +++ b/Task/Order-two-numerical-lists/Crystal/order-two-numerical-lists.cr @@ -0,0 +1,2 @@ +p [1,2,1,3,2] < [1,2,0,4,4,0,0,0] # => false +p [1,2,1,3,2] > [1,2,0,4,4,0,0,0] # => true diff --git a/Task/Order-two-numerical-lists/Delphi/order-two-numerical-lists.delphi b/Task/Order-two-numerical-lists/Delphi/order-two-numerical-lists.pas similarity index 100% rename from Task/Order-two-numerical-lists/Delphi/order-two-numerical-lists.delphi rename to Task/Order-two-numerical-lists/Delphi/order-two-numerical-lists.pas diff --git a/Task/Order-two-numerical-lists/DuckDB/order-two-numerical-lists.duckdb b/Task/Order-two-numerical-lists/DuckDB/order-two-numerical-lists.duckdb new file mode 100644 index 0000000000..f1f10753c0 --- /dev/null +++ b/Task/Order-two-numerical-lists/DuckDB/order-two-numerical-lists.duckdb @@ -0,0 +1,3 @@ +select [1,2,3] < [1,2,3,4]; +select [1,2,3] < [1,2,4]; +select [1,2,3] < [1,2,3]; diff --git a/Task/Order-two-numerical-lists/Elixir/order-two-numerical-lists.elixir b/Task/Order-two-numerical-lists/Elixir/order-two-numerical-lists.ex similarity index 100% rename from Task/Order-two-numerical-lists/Elixir/order-two-numerical-lists.elixir rename to Task/Order-two-numerical-lists/Elixir/order-two-numerical-lists.ex diff --git a/Task/Order-two-numerical-lists/Frink/order-two-numerical-lists.frink b/Task/Order-two-numerical-lists/Frink/order-two-numerical-lists.frink new file mode 100644 index 0000000000..39a4f27f89 --- /dev/null +++ b/Task/Order-two-numerical-lists/Frink/order-two-numerical-lists.frink @@ -0,0 +1,4 @@ +lex[a,b] := lexicalCompare[a, b] < 0 ? true : false + +println[lex[ [1,2], [1,2,3] ]] +println[lex[ [1,2,4,3], [1,2,3] ]] diff --git a/Task/Order-two-numerical-lists/Julia/order-two-numerical-lists.julia b/Task/Order-two-numerical-lists/Julia/order-two-numerical-lists.jl similarity index 100% rename from Task/Order-two-numerical-lists/Julia/order-two-numerical-lists.julia rename to Task/Order-two-numerical-lists/Julia/order-two-numerical-lists.jl diff --git a/Task/Order-two-numerical-lists/Kotlin/order-two-numerical-lists.kotlin b/Task/Order-two-numerical-lists/Kotlin/order-two-numerical-lists.kts similarity index 100% rename from Task/Order-two-numerical-lists/Kotlin/order-two-numerical-lists.kotlin rename to Task/Order-two-numerical-lists/Kotlin/order-two-numerical-lists.kts diff --git a/Task/Order-two-numerical-lists/Nu/order-two-numerical-lists.nu b/Task/Order-two-numerical-lists/Nu/order-two-numerical-lists.nu new file mode 100644 index 0000000000..af0588c616 --- /dev/null +++ b/Task/Order-two-numerical-lists/Nu/order-two-numerical-lists.nu @@ -0,0 +1,9 @@ +def 'list lt' [b] { + let a = $in + $a | zip $b + | skip while { $in.0 == $in.1 } + | try { first } catch { [$a $b] | each { length } } + | $in.0 < $in.1 +} + +[5 6 7 8] | list lt [5 6 8] diff --git a/Task/Order-two-numerical-lists/OCaml/order-two-numerical-lists-1.ocaml b/Task/Order-two-numerical-lists/OCaml/order-two-numerical-lists-1.ml similarity index 100% rename from Task/Order-two-numerical-lists/OCaml/order-two-numerical-lists-1.ocaml rename to Task/Order-two-numerical-lists/OCaml/order-two-numerical-lists-1.ml diff --git a/Task/Order-two-numerical-lists/OCaml/order-two-numerical-lists-2.ocaml b/Task/Order-two-numerical-lists/OCaml/order-two-numerical-lists-2.ml similarity index 100% rename from Task/Order-two-numerical-lists/OCaml/order-two-numerical-lists-2.ocaml rename to Task/Order-two-numerical-lists/OCaml/order-two-numerical-lists-2.ml diff --git a/Task/Order-two-numerical-lists/OCaml/order-two-numerical-lists-3.ocaml b/Task/Order-two-numerical-lists/OCaml/order-two-numerical-lists-3.ml similarity index 100% rename from Task/Order-two-numerical-lists/OCaml/order-two-numerical-lists-3.ocaml rename to Task/Order-two-numerical-lists/OCaml/order-two-numerical-lists-3.ml diff --git a/Task/Order-two-numerical-lists/OCaml/order-two-numerical-lists-4.ocaml b/Task/Order-two-numerical-lists/OCaml/order-two-numerical-lists-4.ml similarity index 100% rename from Task/Order-two-numerical-lists/OCaml/order-two-numerical-lists-4.ocaml rename to Task/Order-two-numerical-lists/OCaml/order-two-numerical-lists-4.ml diff --git a/Task/Order-two-numerical-lists/OCaml/order-two-numerical-lists-5.ocaml b/Task/Order-two-numerical-lists/OCaml/order-two-numerical-lists-5.ml similarity index 100% rename from Task/Order-two-numerical-lists/OCaml/order-two-numerical-lists-5.ocaml rename to Task/Order-two-numerical-lists/OCaml/order-two-numerical-lists-5.ml diff --git a/Task/Order-two-numerical-lists/PascalABC.NET/order-two-numerical-lists.pas b/Task/Order-two-numerical-lists/PascalABC.NET/order-two-numerical-lists.pas new file mode 100644 index 0000000000..2edd125b7d --- /dev/null +++ b/Task/Order-two-numerical-lists/PascalABC.NET/order-two-numerical-lists.pas @@ -0,0 +1,15 @@ +## +function operator <(a, b: List): boolean; +extensionmethod; where T: IComparable; +begin + foreach var (x, y) in Zip(a, b) do + begin + if x = y then continue; + result := x.CompareTo(y) < 0; + exit; + end; + result := a.Count < b.Count; +end; + +println(Lst(1, 2, 1, 3, 2) < Lst(1, 2, 0, 4, 4, 0, 0, 0)); +println(Lst(1, 2, 0, 4, 4, 0, 0, 0) < Lst(1, 2, 1, 3, 2)); diff --git a/Task/Order-two-numerical-lists/PowerShell/order-two-numerical-lists-1.psh b/Task/Order-two-numerical-lists/PowerShell/order-two-numerical-lists-1.ps1 similarity index 100% rename from Task/Order-two-numerical-lists/PowerShell/order-two-numerical-lists-1.psh rename to Task/Order-two-numerical-lists/PowerShell/order-two-numerical-lists-1.ps1 diff --git a/Task/Order-two-numerical-lists/PowerShell/order-two-numerical-lists-2.psh b/Task/Order-two-numerical-lists/PowerShell/order-two-numerical-lists-2.ps1 similarity index 100% rename from Task/Order-two-numerical-lists/PowerShell/order-two-numerical-lists-2.psh rename to Task/Order-two-numerical-lists/PowerShell/order-two-numerical-lists-2.ps1 diff --git a/Task/Order-two-numerical-lists/PowerShell/order-two-numerical-lists-3.psh b/Task/Order-two-numerical-lists/PowerShell/order-two-numerical-lists-3.ps1 similarity index 100% rename from Task/Order-two-numerical-lists/PowerShell/order-two-numerical-lists-3.psh rename to Task/Order-two-numerical-lists/PowerShell/order-two-numerical-lists-3.ps1 diff --git a/Task/Order-two-numerical-lists/R/order-two-numerical-lists.r b/Task/Order-two-numerical-lists/R/order-two-numerical-lists.r new file mode 100644 index 0000000000..d21c365d1b --- /dev/null +++ b/Task/Order-two-numerical-lists/R/order-two-numerical-lists.r @@ -0,0 +1,14 @@ +lex_compare <- function(v1, v2){ + ldiff <- length(v1)-length(v2) + endstate <- ldiff<0 + iters <- ifelse(endstate, length(v1), length(v2)) + for(i in seq_len(iters)){ + if(v1[i]==v2[i]) next + else return(v1[i]a with C=1 (word not ordered) + mov b,a ; This is now the previous character + jmp isord1 ; Check next character + + ;;; Update maximum length +maxlen: call wlen ; Find length of word + lda wrdlen ; Get current length of longest word + cmp c ; Is it less than the length of our word? + rnc ; If not, do nothing + mov a,c ; If so, update the maximum length + sta wrdlen + ret +wrdlen: db 0 ; Maximum length found + + ;;; Find length of word +wlen: mvi c,0 ; Length +wlchar: mov a,m + cpi 32 ; End of word? + rc ; Then stop + inx h ; Increment pointer and length + inr c + jmp wlchar + + ;;; Print word if its length matches the maximum length +prword: call wlen ; Get length of word + lda wrdlen ; Is the length equal to the maximum found? + cmp c + rnz ; If not, stop + inx h ; If so, skip past newline (not counted in length), + inx h + mvi m,'$' ; and terminate word with '$' + lxi d,word ; and print the word + mvi c,puts + jmp 5 + +word equ $ ; Store the current word after the program diff --git a/Task/Ordered-words/ALGOL-68/ordered-words.alg b/Task/Ordered-words/ALGOL-68/ordered-words-1.alg similarity index 100% rename from Task/Ordered-words/ALGOL-68/ordered-words.alg rename to Task/Ordered-words/ALGOL-68/ordered-words-1.alg diff --git a/Task/Ordered-words/ALGOL-68/ordered-words-2.alg b/Task/Ordered-words/ALGOL-68/ordered-words-2.alg new file mode 100644 index 0000000000..cdb84eefae --- /dev/null +++ b/Task/Ordered-words/ALGOL-68/ordered-words-2.alg @@ -0,0 +1,37 @@ +BEGIN # find the longest words in unixdict.txt that have all letters in order # + + PR read "files.incl.a68" PR # include file utilities # + + INT max length := -1; + [ 1 : 1000 ]STRING ordered words; + INT o count := 0; + + # stores ordered words with the maximum length # + PROC store ordered words = ( STRING word )VOID: + IF BOOL ordered := TRUE; + FOR w pos FROM LWB word + 1 TO UPB word WHILE ordered DO + ordered := word[ w pos - 1 ] <= word[ w pos ] + OD; + ordered + THEN INT this length = ( 1 + UPB word ) - LWB word; + IF this length >= max length THEN + IF this length > max length THEN + max length := this length; + o count := 0 + FI; + ordered words[ o count +:= 1 ] := word + FI + FI # store ordered words # ; + + # read the list of words and store the ordered ones of maximum length # + + IF "unixdict.txt" EACHLINE store ordered words < 0 THEN + print( ( "Unable to open unixdict.txt", newline ) ) + ELSE + print( ( "Maximum length of ordered words: ", whole( max length, 0 ), newline ) ); + print( ( "Found ", whole( o count, 0 ), " ordered words of maximum length:", newline ) ); + FOR o pos TO o count DO + print( ( " ", ordered words[ o pos ], newline ) ) + OD + FI +END diff --git a/Task/Ordered-words/AWK/ordered-words.awk b/Task/Ordered-words/AWK/ordered-words.awk index fc25ce217e..973bc41df0 100644 --- a/Task/Ordered-words/AWK/ordered-words.awk +++ b/Task/Ordered-words/AWK/ordered-words.awk @@ -1,36 +1,36 @@ BEGIN { - abc = "abcdefghijklmnopqrstuvwxyz" + abc = "abcdefghijklmnopqrstuvwxyz" } { - # Check if this line is an ordered word. - ordered = 1 # true - left = -1 - for (i = 1; i <= length($0); i++) { - right = index(abc, substr($0, i, 1)) - if (right == 0 || left > right) { - ordered = 0 # false - break - } - left = right - } + # Check if this line is an ordered word. + ordered = 1 # true + left = -1 + for (i = 1; i <= length($0); i++) { + right = index(abc, substr($0, i, 1)) + if (right == 0 || left > right) { + ordered = 0 # false + break + } + left = right + } - if (ordered) { - score = length($0) - if (score > best["score"]) { - # Reset the list of best ordered words. - best["score"] = score - best["count"] = 1 - best[1] = $0 - } else if (score == best["score"]) { - # Add this word to the list. - best[++best["count"]] = $0 - } - } + if (ordered) { + score = length($0) + if (score > best["score"]) { + # Reset the list of best ordered words. + best["score"] = score + best["count"] = 1 + best[1] = $0 + } else if (score == best["score"]) { + # Add this word to the list. + best[++best["count"]] = $0 + } + } } END { - # Print the list of best ordered words. - for (i = 1; i <= best["count"]; i++) - print best[i] + # Print the list of best ordered words. + for (i = 1; i <= best["count"]; i++) + print best[i] } diff --git a/Task/Ordered-words/Ada/ordered-words.ada b/Task/Ordered-words/Ada/ordered-words.adb similarity index 100% rename from Task/Ordered-words/Ada/ordered-words.ada rename to Task/Ordered-words/Ada/ordered-words.adb diff --git a/Task/Ordered-words/Agena/ordered-words.agena b/Task/Ordered-words/Agena/ordered-words.agena new file mode 100644 index 0000000000..349512699e --- /dev/null +++ b/Task/Ordered-words/Agena/ordered-words.agena @@ -0,0 +1,26 @@ +scope # find words whose characters are in alphabetical order + + local proc isSorted( word :: string ) :: boolean + local result := true; + for c to size word - 1 while result do + result := word[ c ] <= word[ c + 1 ] + od; + return result + end; + + local sortedWords, maxLength := seq(), 0; + for word in io.lines( "unixdict.txt" ) do + if isSorted( word ) then + local constant thisLength := size word; + if thisLength >= maxLength then + if thisLength > maxLength then + clear sortedWords; + sortedWords, maxLength := seq(), thisLength + fi; + sortedWords[ size sortedWords + 1 ] := word + fi + fi + od; + for _, w in ipairs( sortedWords ) do print( w ) od + +end diff --git a/Task/Ordered-words/Arturo/ordered-words.arturo b/Task/Ordered-words/Arturo/ordered-words.arturo index 6035be479d..310a8b9395 100644 --- a/Task/Ordered-words/Arturo/ordered-words.arturo +++ b/Task/Ordered-words/Arturo/ordered-words.arturo @@ -2,7 +2,7 @@ ordered?: function [w]-> w = join sort split w words: read.lines relative "unixdict.txt" -ret: new [] +ret: [] loop words 'wrd [ if ordered? wrd -> 'ret ++ #[w: wrd l: size wrd] diff --git a/Task/Ordered-words/BASIC/ordered-words.basic b/Task/Ordered-words/BASIC/ordered-words.basic new file mode 100644 index 0000000000..b15d46e42d --- /dev/null +++ b/Task/Ordered-words/BASIC/ordered-words.basic @@ -0,0 +1,17 @@ +10 DEFINT I,O +20 DEFSTR W,F +30 F="UNIXDICT.TXT" +40 OPEN "I",1,F +50 INPUT #1,W +60 GOSUB 200: IF O THEN IF LEN(W)>L THEN L=LEN(W) +70 IF EOF(1) THEN CLOSE 1 ELSE 50 +80 OPEN "I",1,F +90 INPUT #1,W +100 IF LEN(W)<>L THEN 90 +110 GOSUB 200: IF O THEN PRINT W, +120 IF EOF(1) THEN END ELSE 90 +200 O=-1 +210 FOR I=2 TO LEN(W) +220 IF MID$(W,I-1,1)>MID$(W,I,1) THEN O=0: RETURN +230 NEXT +240 RETURN diff --git a/Task/Ordered-words/C/ordered-words-3.c b/Task/Ordered-words/C/ordered-words-3.c index 9c44cd507c..15dfa8e9d6 100644 --- a/Task/Ordered-words/C/ordered-words-3.c +++ b/Task/Ordered-words/C/ordered-words-3.c @@ -9,46 +9,46 @@ int ordered(char *s, char **end) { - int r = 1; - while (*++s != '\n' && *s != '\r' && *s != '\0') - if (s[0] < s[-1]) r = 0; + int r = 1; + while (*++s != '\n' && *s != '\r' && *s != '\0') + if (s[0] < s[-1]) r = 0; - *end = s; - return r; + *end = s; + return r; } int main() { - char *buf, *word, *end, *tail; - struct stat st; - int longest = 0, len, fd; + char *buf, *word, *end, *tail; + struct stat st; + int longest = 0, len, fd; - if ((fd = open("unixdict.txt", O_RDONLY)) == -1) err(1, "read error"); + if ((fd = open("unixdict.txt", O_RDONLY)) == -1) err(1, "read error"); - fstat(fd, &st); - if (!(buf = mmap(0, st.st_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0))) - err(1, "mmap"); + fstat(fd, &st); + if (!(buf = mmap(0, st.st_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0))) + err(1, "mmap"); - for (word = end = buf; end < buf + st.st_size; word = end) { - while (*word == '\r' || *word == '\n') word++; - if (!ordered(word, &end)) continue; - if ((len = end - word + 1) < longest) continue; - if (len > longest) { - tail = buf; /* longer words found; reset out buffer */ - longest = len; - } - /* use the same mmap'd region to store output. because of MAP_PRIVATE, - * change will not go back to file. mmap is copy on write, and we are using - * only the head space to store output, so kernel doesn't need to copy more - * than the words we saved--in this case, one page tops. - */ - memcpy(tail, word, len); - tail += len; - *tail = '\0'; - } - printf(buf); + for (word = end = buf; end < buf + st.st_size; word = end) { + while (*word == '\r' || *word == '\n') word++; + if (!ordered(word, &end)) continue; + if ((len = end - word + 1) < longest) continue; + if (len > longest) { + tail = buf; /* longer words found; reset out buffer */ + longest = len; + } + /* use the same mmap'd region to store output. because of MAP_PRIVATE, + * change will not go back to file. mmap is copy on write, and we are using + * only the head space to store output, so kernel doesn't need to copy more + * than the words we saved--in this case, one page tops. + */ + memcpy(tail, word, len); + tail += len; + *tail = '\0'; + } + printf(buf); - munmap(buf, st.st_size); - close(fd); - return 0; + munmap(buf, st.st_size); + close(fd); + return 0; } diff --git a/Task/Ordered-words/COBOL/ordered-words.cobol b/Task/Ordered-words/COBOL/ordered-words.cob similarity index 100% rename from Task/Ordered-words/COBOL/ordered-words.cobol rename to Task/Ordered-words/COBOL/ordered-words.cob diff --git a/Task/Ordered-words/Common-Lisp/ordered-words-2.lisp b/Task/Ordered-words/Common-Lisp/ordered-words-2.lisp index 803210be5e..5302292c49 100644 --- a/Task/Ordered-words/Common-Lisp/ordered-words-2.lisp +++ b/Task/Ordered-words/Common-Lisp/ordered-words-2.lisp @@ -2,7 +2,7 @@ (apply #'char<= (coerce word 'list))) (let* ((words (uiop:read-file-lines "unixdict.txt")) - (ordered (delete-if-not #'orderedp words)) - (maxlen (apply #'max (mapcar #'length ordered))) - (result (delete-if-not (lambda (l) (= l maxlen)) ordered :key #'length))) + (ordered (delete-if-not #'orderedp words)) + (maxlen (apply #'max (mapcar #'length ordered))) + (result (delete-if-not (lambda (l) (= l maxlen)) ordered :key #'length))) (format t "~{~A~^, ~}" result)) diff --git a/Task/Ordered-words/Crystal/ordered-words.cr b/Task/Ordered-words/Crystal/ordered-words.cr new file mode 100644 index 0000000000..ebac8a3641 --- /dev/null +++ b/Task/Ordered-words/Crystal/ordered-words.cr @@ -0,0 +1,6 @@ +ordered = File.open("unixdict.txt") do |f| + f.each_line.select {|word| + word.chars.each_cons_pair.all? {|a, b| a <= b } + }.to_a +end +puts ordered.group_by(&.size).max[1].join(" ") diff --git a/Task/Ordered-words/Delphi/ordered-words-1.delphi b/Task/Ordered-words/Delphi/ordered-words-1.pas similarity index 100% rename from Task/Ordered-words/Delphi/ordered-words-1.delphi rename to Task/Ordered-words/Delphi/ordered-words-1.pas diff --git a/Task/Ordered-words/Delphi/ordered-words-2.delphi b/Task/Ordered-words/Delphi/ordered-words-2.pas similarity index 100% rename from Task/Ordered-words/Delphi/ordered-words-2.delphi rename to Task/Ordered-words/Delphi/ordered-words-2.pas diff --git a/Task/Ordered-words/DuckDB/ordered-words.duckdb b/Task/Ordered-words/DuckDB/ordered-words.duckdb new file mode 100644 index 0000000000..e143274fd4 --- /dev/null +++ b/Task/Ordered-words/DuckDB/ordered-words.duckdb @@ -0,0 +1,20 @@ +create or replace function is_sorted(str) as ( + select not exists ( + from (select (c > (lead(c) over ())) as outoforder + from (select unnest(regexp_extract_all(str, '.')) as c)) + where outoforder = true ) +); + +create or replace function longest_ordered_words(file) as table ( + with words as ( + from read_csv_auto( + file, header=false, sep='', quote='', columns={'word': VARCHAR}) + where is_sorted(word)), + mx as (select max(length(word)) as mx from words) + select word + from words, mx + where length(word) = mx + order by word +); + +from longest_ordered_words('unixdict.txt'); diff --git a/Task/Ordered-words/EasyLang/ordered-words.easy b/Task/Ordered-words/EasyLang/ordered-words.easy new file mode 100644 index 0000000000..e7cecf29a9 --- /dev/null +++ b/Task/Ordered-words/EasyLang/ordered-words.easy @@ -0,0 +1,32 @@ +func isordered w$ . + for c$ in strchars w$ + if strcode c$ < prev + return 0 + . + prev = strcode c$ + . + return 1 +. +repeat + w$ = input + until w$ = "" + if len w$ >= max and isordered w$ = 1 + max = len w$ + words$[] &= w$ + . +. +for w$ in words$[] + if len w$ = max + write w$ & " " + . +. +# +# the content of unixdict.txt +input_data +10th +abacus +abbot +abbott +accent +floppy +flora diff --git a/Task/Ordered-words/EchoLisp/ordered-words.l b/Task/Ordered-words/EchoLisp/ordered-words.l index c9418930d4..066e28d712 100644 --- a/Task/Ordered-words/EchoLisp/ordered-words.l +++ b/Task/Ordered-words/EchoLisp/ordered-words.l @@ -5,15 +5,15 @@ (define (ordre words) (define wl 0) (define s 's) - (for/fold (len 0) ((w words)) - (set! wl (string-length w)) - #:continue (< wl len) - #:when (ordered? w) - #:continue (and (= len wl) (push s w)) - (push (stack s) w) ;; start a new list of length wl - wl) - (stack->list s)) - + (for/fold (len 0) ((w words)) + (set! wl (string-length w)) + #:continue (< wl len) + #:when (ordered? w) + #:continue (and (= len wl) (push s w)) + (push (stack s) w) ;; start a new list of length wl + wl) + (stack->list s)) + ;; output (load 'unixdict) (ordre (text-parse unixdict)) diff --git a/Task/Ordered-words/Elixir/ordered-words.elixir b/Task/Ordered-words/Elixir/ordered-words.ex similarity index 100% rename from Task/Ordered-words/Elixir/ordered-words.elixir rename to Task/Ordered-words/Elixir/ordered-words.ex diff --git a/Task/Ordered-words/Emacs-Lisp/ordered-words.el b/Task/Ordered-words/Emacs-Lisp/ordered-words.el new file mode 100644 index 0000000000..250aa6c2bf --- /dev/null +++ b/Task/Ordered-words/Emacs-Lisp/ordered-words.el @@ -0,0 +1,75 @@ +(defun order-alphabetically (str) + "Put letters in STR in alphabetical order." + ;; split STR into list of individual letters in alphabetical order + ;; and then join the letters back into one string + (apply #'concat (sort (split-string str "" t) #'string<))) + +(defun ordered-alphabetically-p (str) + "Test if letters STR are in alphabetical order." + (string= (order-alphabetically str) str)) + + +(defun make-list-of-ordered-words (word-list) + "Create subset of ordered words from words in WORD-LIST." + (let ((ordered-words)) + (dolist (one-word word-list) + (when (ordered-alphabetically-p one-word) + (push (format "%s" one-word) ordered-words))) + ordered-words)) + +(defun list-length-words (word-list) + "From the words in WORD-LIST, create list of pairs of words and their length." + (let ((paired-list) + (temp-pair)) + (dolist (one-word word-list) + (setq temp-pair (list (length one-word) one-word)) + (push temp-pair paired-list)) + paired-list)) + +(defun create-list-of-numbers (numbers-and-words-list) + "Create list of numbers from NUMBERS-AND-WORDS-LIST." + (let ((list-of-numbers)) + (dolist (one-pair numbers-and-words-list) + (push (car one-pair) list-of-numbers)) + list-of-numbers)) + +(defun get-largest-number (numbers-and-words-list) + "Find largest number in NUMBERS-AND-WORDS-LIST." + (let ((list-of-numbers)) + (setq list-of-numbers (create-list-of-numbers numbers-and-words-list)) + (apply #'max list-of-numbers))) + +(defun make-list-matching-words (largest-number numbers-and-words-list) + "List words whose length equals LARGEST-NUMBER." + (dolist (number-and-word-pair numbers-and-words-list) + ;; test if number in NUMBER-AND-WORD-PAIR matches + ;; LARGEST-NUMBER + (when (= (nth 0 number-and-word-pair) largest-number) + ;; insert the original word + (insert (format "%s " (nth 1 number-and-word-pair))))) + (insert "\n")) + +(defun get-longest-ordered-words () + "Find the longest ordered words in file wordlist.txt. +A word is an ordered word if its letters are in alphabetical order." + (let ((all-word-list) + (just-ordered-words) + (lengths-and-words) + (longest-word-length)) + ;; Path below needs to be adapted to individual case + (find-file "~/Documents/Elisp/wordlist.txt") + (beginning-of-buffer) + ;; Create list of all words in file + (setq all-word-list (split-string (buffer-string) "\n")) + ;; Test if a word is an ordered word, if so add to JUST-ORDERED-WORDS + (dolist (one-word all-word-list) + (if (ordered-alphabetically-p one-word) + (push one-word just-ordered-words))) + ;; pair word lengths with ordered words + (setq lengths-and-words (list-length-words just-ordered-words)) + ;; Get the longest word length + (setq longest-word (get-largest-number lengths-and-words)) + (find-file "longest-ordered-words") + (erase-buffer) + ;; list the longest ordered words + (make-list-matching-words longest-word lengths-and-words))) diff --git a/Task/Ordered-words/Euphoria/ordered-words.euphoria b/Task/Ordered-words/Euphoria/ordered-words.eu similarity index 100% rename from Task/Ordered-words/Euphoria/ordered-words.euphoria rename to Task/Ordered-words/Euphoria/ordered-words.eu diff --git a/Task/Ordered-words/Fennel/ordered-words.fennel b/Task/Ordered-words/Fennel/ordered-words.fennel new file mode 100644 index 0000000000..642f3435cf --- /dev/null +++ b/Task/Ordered-words/Fennel/ordered-words.fennel @@ -0,0 +1,29 @@ +(do ;;; find words whose characters are in alphabetical order + + (fn sorted? [word] + (local word-length (length word)) + (var (result c) (values true 1)) + (while (and result (< c word-length)) + (local c1 (+ c 1)) + (set result (<= (word:sub c c) (word:sub c1 c1))) + (set c c1) + ) + result + ) + + (var (sorted-words max-length) (values {} 0)) + (each [word (io.lines "unixdict.txt")] + (when (sorted? word) + (local this-length (length word)) + (when (>= this-length max-length) + (when (> this-length max-length) + (set (sorted-words max-length) + (values {} this-length) + ) + ) + (table.insert sorted-words word) + ) + ) + ) + (each [_ w (ipairs sorted-words)] (print w)) +) diff --git a/Task/Ordered-words/Fortran/ordered-words.f b/Task/Ordered-words/Fortran/ordered-words.f index ff6255335c..fef4aaa52d 100644 --- a/Task/Ordered-words/Fortran/ordered-words.f +++ b/Task/Ordered-words/Fortran/ordered-words.f @@ -3,76 +3,76 @@ !*************************************************************************************** implicit none - !the dictionary file: - integer,parameter :: file_unit = 1000 - character(len=*),parameter :: filename = 'unixdict.txt' + !the dictionary file: + integer,parameter :: file_unit = 1000 + character(len=*),parameter :: filename = 'unixdict.txt' - !maximum number of characters in a word: - integer,parameter :: max_chars = 50 + !maximum number of characters in a word: + integer,parameter :: max_chars = 50 - type word - character(len=max_chars) :: str !the word from the dictionary - integer :: n = 0 !length of this word - logical :: ordered = .false. !if it is an ordered word - end type word + type word + character(len=max_chars) :: str !the word from the dictionary + integer :: n = 0 !length of this word + logical :: ordered = .false. !if it is an ordered word + end type word - !the dictionary structure: - type(word),dimension(:),allocatable :: dict + !the dictionary structure: + type(word),dimension(:),allocatable :: dict - contains + contains !*************************************************************************************** - !****************************************************************************** - function count_lines_in_file(fid) result(n_lines) - !****************************************************************************** - implicit none + !****************************************************************************** + function count_lines_in_file(fid) result(n_lines) + !****************************************************************************** + implicit none - integer :: n_lines - integer,intent(in) :: fid - character(len=1) :: tmp - integer :: i - integer :: ios + integer :: n_lines + integer,intent(in) :: fid + character(len=1) :: tmp + integer :: i + integer :: ios - !the file is assumed to be open already. + !the file is assumed to be open already. - rewind(fid) !rewind to beginning of the file + rewind(fid) !rewind to beginning of the file - n_lines = 0 - do !read each line until the end of the file. - read(fid,'(A1)',iostat=ios) tmp - if (ios < 0) exit !End of file - n_lines = n_lines + 1 !row counter - end do + n_lines = 0 + do !read each line until the end of the file. + read(fid,'(A1)',iostat=ios) tmp + if (ios < 0) exit !End of file + n_lines = n_lines + 1 !row counter + end do - rewind(fid) !rewind to beginning of the file + rewind(fid) !rewind to beginning of the file - !****************************************************************************** - end function count_lines_in_file - !****************************************************************************** + !****************************************************************************** + end function count_lines_in_file + !****************************************************************************** - !****************************************************************************** - pure elemental function ordered_word(word) result(yn) - !****************************************************************************** - ! turns true if word is an ordered word, false if it is not. - !****************************************************************************** - - implicit none - character(len=*),intent(in) :: word - logical :: yn - - integer :: i - - yn = .true. - do i=1,len_trim(word)-1 - if (ichar(word(i+1:i+1))= LongestLength Then + If IsOrdered(CurrentWord) Then + If CurrentLength > LongestLength Then + Begin + LongestLength := CurrentLength; + OrderedWords.Clear; + OrderedWords.Add(CurrentWord); + End + Else If CurrentLength = LongestLength Then + OrderedWords.Add(CurrentWord); + End; + For CurrentWord In OrderedWords Do + WriteLn(CurrentWord); + + WordList.Free; + OrderedWords.Free; +End. diff --git a/Task/Ordered-words/Java/ordered-words-1.java b/Task/Ordered-words/Java/ordered-words-1.java index a96c558398..c435946b2d 100644 --- a/Task/Ordered-words/Java/ordered-words-1.java +++ b/Task/Ordered-words/Java/ordered-words-1.java @@ -9,35 +9,35 @@ import java.util.List; public class Ordered { - private static boolean isOrderedWord(String word){ - char[] sortedWord = word.toCharArray(); - Arrays.sort(sortedWord); - return word.equals(new String(sortedWord)); - } - - public static void main(String[] args) throws IOException{ - List orderedWords = new LinkedList(); - BufferedReader in = new BufferedReader(new FileReader(args[0])); - while(in.ready()){ - String word = in.readLine(); - if(isOrderedWord(word)) orderedWords.add(word); - } - in.close(); - - Collections.sort(orderedWords, new Comparator() { - @Override - public int compare(String o1, String o2) { - return new Integer(o2.length()).compareTo(o1.length()); - } - }); - - int maxLen = orderedWords.get(0).length(); - for(String word: orderedWords){ - if(word.length() == maxLen){ - System.out.println(word); - }else{ - break; - } - } - } + private static boolean isOrderedWord(String word){ + char[] sortedWord = word.toCharArray(); + Arrays.sort(sortedWord); + return word.equals(new String(sortedWord)); + } + + public static void main(String[] args) throws IOException{ + List orderedWords = new LinkedList(); + BufferedReader in = new BufferedReader(new FileReader(args[0])); + while(in.ready()){ + String word = in.readLine(); + if(isOrderedWord(word)) orderedWords.add(word); + } + in.close(); + + Collections.sort(orderedWords, new Comparator() { + @Override + public int compare(String o1, String o2) { + return new Integer(o2.length()).compareTo(o1.length()); + } + }); + + int maxLen = orderedWords.get(0).length(); + for(String word: orderedWords){ + if(word.length() == maxLen){ + System.out.println(word); + }else{ + break; + } + } + } } diff --git a/Task/Ordered-words/Java/ordered-words-2.java b/Task/Ordered-words/Java/ordered-words-2.java index c17ec384e7..5e34d209e7 100644 --- a/Task/Ordered-words/Java/ordered-words-2.java +++ b/Task/Ordered-words/Java/ordered-words-2.java @@ -5,21 +5,21 @@ import java.util.List; public final class OrderedWords { - public static void main(String[] aArgs) throws IOException { - List ordered = Files.lines(Path.of("unixdict.txt")) - .filter( word -> isOrdered(word) ).toList(); - - final int maxLength = ordered.stream().map( word -> word.length() ).max(Integer::compare).get(); - ordered.stream().filter( word -> word.length() == maxLength ).forEach(System.out::println); - } - - private static boolean isOrdered(String aWord) { - return aWord.chars() - .mapToObj( i -> (char) i ) - .sorted() - .map(String::valueOf) - .reduce("", String::concat) - .equals(aWord); - } + public static void main(String[] aArgs) throws IOException { + List ordered = Files.lines(Path.of("unixdict.txt")) + .filter( word -> isOrdered(word) ).toList(); + + final int maxLength = ordered.stream().map( word -> word.length() ).max(Integer::compare).get(); + ordered.stream().filter( word -> word.length() == maxLength ).forEach(System.out::println); + } + + private static boolean isOrdered(String aWord) { + return aWord.chars() + .mapToObj( i -> (char) i ) + .sorted() + .map(String::valueOf) + .reduce("", String::concat) + .equals(aWord); + } } diff --git a/Task/Ordered-words/Julia/ordered-words-1.julia b/Task/Ordered-words/Julia/ordered-words-1.jl similarity index 100% rename from Task/Ordered-words/Julia/ordered-words-1.julia rename to Task/Ordered-words/Julia/ordered-words-1.jl diff --git a/Task/Ordered-words/Julia/ordered-words-2.julia b/Task/Ordered-words/Julia/ordered-words-2.jl similarity index 100% rename from Task/Ordered-words/Julia/ordered-words-2.julia rename to Task/Ordered-words/Julia/ordered-words-2.jl diff --git a/Task/Ordered-words/Kotlin/ordered-words.kotlin b/Task/Ordered-words/Kotlin/ordered-words.kts similarity index 100% rename from Task/Ordered-words/Kotlin/ordered-words.kotlin rename to Task/Ordered-words/Kotlin/ordered-words.kts diff --git a/Task/Ordered-words/Lasso/ordered-words.lasso b/Task/Ordered-words/Lasso/ordered-words.lasso index a8ddd5e803..a860cff1c4 100644 --- a/Task/Ordered-words/Lasso/ordered-words.lasso +++ b/Task/Ordered-words/Lasso/ordered-words.lasso @@ -1,17 +1,17 @@ local(f = file('unixdict.txt'), words = array, ordered = array, maxleng = 0) #f->dowithclose => { - #f->foreachLine => { - #words->insert(#1) - } + #f->foreachLine => { + #words->insert(#1) + } } with w in #words do => { - local(tosort = #w->asString->values) - #tosort->sort - if(#w->asString == #tosort->join('')) => { - #ordered->insert(#w->asString) - #w->asString->size > #maxleng ? #maxleng = #w->asString->size - } + local(tosort = #w->asString->values) + #tosort->sort + if(#w->asString == #tosort->join('')) => { + #ordered->insert(#w->asString) + #w->asString->size > #maxleng ? #maxleng = #w->asString->size + } } with w in #ordered where #w->size == #maxleng diff --git a/Task/Ordered-words/Lua/ordered-words.lua b/Task/Ordered-words/Lua/ordered-words.lua index c8dec7cadd..72437d8e60 100644 --- a/Task/Ordered-words/Lua/ordered-words.lua +++ b/Task/Ordered-words/Lua/ordered-words.lua @@ -6,21 +6,21 @@ list = {} for w in fp:lines() do ordered = true for l = 2, string.len(w) do - if string.byte( w, l-1 ) > string.byte( w, l ) then - ordered = false - break - end - end + if string.byte( w, l-1 ) > string.byte( w, l ) then + ordered = false + break + end -- if + end -- for if ordered then - if string.len(w) > maxlen then - list = {} - list[1] = w - maxlen = string.len(w) - elseif string.len(w) == maxlen then - list[#list+1] = w - end - end -end + if string.len(w) > maxlen then + list = {} + list[1] = w + maxlen = string.len(w) + elseif string.len(w) == maxlen then + list[#list+1] = w + end -- if + end -- if +end -- for for _, w in pairs(list) do print( w ) diff --git a/Task/Ordered-words/M2000-Interpreter/ordered-words.m2000 b/Task/Ordered-words/M2000-Interpreter/ordered-words.m2000 new file mode 100644 index 0000000000..26a2285edc --- /dev/null +++ b/Task/Ordered-words/M2000-Interpreter/ordered-words.m2000 @@ -0,0 +1,38 @@ +module Ordered_Words { + orderword=lambda ->{ + buffer a as integer*30 + =lambda a (s as string) -> { + if len(s)*2>len(a) then buffer a as integer*len(s) + return a, 0:=s + if len(s)=1 then =true: exit + for i=1 to len(s)-1 + if a[i-1]>a[i] then break + next i + =true + } + }() + max=2 + res=stack + document a$ + load.doc a$, "unixdict.txt" + k=doc.par(a$) + i=0 + m=Paragraph(a$, 0) + if forward(a$, m) then + while m + i++ + if i mod 20=1 then Print Over round(i/k*100,2);"%" : refresh + word=paragraph$(a$, (m)) + if orderword(word) then + if maxmaxlen, - list = {str}; - maxlen = length(str); + list = {str}; + maxlen = length(str); elseif length(str)==maxlen, - list{end+1} = str; + list{end+1} = str; end; end fclose(fid); diff --git a/Task/Ordered-words/Maple/ordered-words.maple b/Task/Ordered-words/Maple/ordered-words.maple index eb042d2347..968804ba53 100644 --- a/Task/Ordered-words/Maple/ordered-words.maple +++ b/Task/Ordered-words/Maple/ordered-words.maple @@ -3,17 +3,17 @@ longest := 0: words := Array(): i := 1: for word in lst do - if StringTools:-IsSorted(word) then - len := StringTools:-Length(word): - if len > longest then - longest := len: - words := Array(): - words(1) := word: - i := 2: - elif len = longest then - words(i) := word: - i++: - end if; - end if; + if StringTools:-IsSorted(word) then + len := StringTools:-Length(word): + if len > longest then + longest := len: + words := Array(): + words(1) := word: + i := 2: + elif len = longest then + words(i) := word: + i++: + end if; + end if; end do; for word in words do print(word); end do; diff --git a/Task/Ordered-words/Nu/ordered-words.nu b/Task/Ordered-words/Nu/ordered-words.nu new file mode 100644 index 0000000000..6af9868a3c --- /dev/null +++ b/Task/Ordered-words/Nu/ordered-words.nu @@ -0,0 +1,8 @@ +def 'str is-ordered' [] { + split chars | window 2 | all { $in.0 <= $in.1 } +} + +open 'unixdict.txt' | lines +| group-by { str length } | sort -n -r +| values | each { filter { str is-ordered } } +| skip while { is-empty } | first diff --git a/Task/Ordered-words/OCaml/ordered-words.ocaml b/Task/Ordered-words/OCaml/ordered-words.ml similarity index 100% rename from Task/Ordered-words/OCaml/ordered-words.ocaml rename to Task/Ordered-words/OCaml/ordered-words.ml diff --git a/Task/Ordered-words/Oberon-07/ordered-words.oberon b/Task/Ordered-words/Oberon-07/ordered-words.oberon new file mode 100644 index 0000000000..9c94fcd076 --- /dev/null +++ b/Task/Ordered-words/Oberon-07/ordered-words.oberon @@ -0,0 +1,46 @@ +MODULE OrderedWords; (* find the longest words whose characters are in alphabetical order *) + IMPORT RcWords, Out, Strings; + + CONST maxSorted = 1000; (* guess the maximum number of words *) + VAR maxLength, sPos, sMax : INTEGER; + sortedWords : ARRAY maxSorted + 1, RcWords.MAXLENGTH + 2 OF CHAR; + + PROCEDURE isSorted( word : ARRAY OF CHAR ) : BOOLEAN; + VAR wPos, wLen : INTEGER; + ordered : BOOLEAN; + BEGIN + ordered := TRUE; + wLen := Strings.Length( word ); + wPos := 1; + WHILE ( wPos < wLen ) & ordered DO + ordered := word[ wPos - 1 ] <= word[ wPos ]; + INC( wPos ) + END + RETURN ordered + END isSorted ; + + PROCEDURE storeSortedWords( word : ARRAY OF CHAR ); + VAR thisLength : INTEGER; + BEGIN + IF isSorted( word ) THEN + thisLength := Strings.Length( word ); + IF thisLength >= maxLength THEN + IF thisLength > maxLength THEN + maxLength := thisLength; + sMax := -1 + END; + INC( sMax ); + sortedWords[ sMax ] := word + END + END + END storeSortedWords ; + +BEGIN + sMax := -1; + RcWords.forEachWord( storeSortedWords ); + Out.String( "Found " );Out.Int( sMax + 1, 0 ); + Out.String( " ordered words of the maximum length (" );Out.Int( maxLength, 0 );Out.String( "):" );Out.Ln; + FOR sPos := 0 TO sMax DO + Out.String( " " );Out.String( sortedWords[ sPos ] );Out.Ln + END +END OrderedWords. diff --git a/Task/Ordered-words/PascalABC.NET/ordered-words.pas b/Task/Ordered-words/PascalABC.NET/ordered-words.pas new file mode 100644 index 0000000000..a1d384036f --- /dev/null +++ b/Task/Ordered-words/PascalABC.NET/ordered-words.pas @@ -0,0 +1,19 @@ +uses System.Net; + +function IsOrderedWord(w: string): boolean; +begin + result := true; + for var i := 2 to w.Length do + begin + if w[i] < w[i - 1] then result := false + end; +end; + +begin + var client := new WebClient(); + var text := client.DownloadString('http://wiki.puzzlers.org/pub/wordlists/unixdict.txt'); + var words: sequence of string := text.ToWords(|#10, #13|); + words := words.Where(x -> IsOrderedWord(x)); + var maxlen := words.Max(x -> x.Length); + words.Where(x -> x.length = maxlen).Println; +end. diff --git a/Task/Ordered-words/Pluto/ordered-words.pluto b/Task/Ordered-words/Pluto/ordered-words.pluto new file mode 100644 index 0000000000..28fefa010f --- /dev/null +++ b/Task/Ordered-words/Pluto/ordered-words.pluto @@ -0,0 +1,24 @@ +do -- find words whose characters are in alphabetical order + + local function isSorted( word : string ) : boolean + for c = 1, # word - 1 do + if word[ c ] > word[ c + 1 ] then return false end + end + return true + end + + local sortedWords, maxLength = {}, 0 + for word in io.lines( "unixdict.txt" ) do + if isSorted( word ) then + local thisLength = # word + if thisLength >= maxLength then + if thisLength > maxLength then + sortedWords, maxLength = {}, thisLength + end + sortedWords[ # sortedWords + 1 ] = word + end + end + end + for _, w in ipairs( sortedWords ) do print( w ) end + +end diff --git a/Task/Ordered-words/PowerShell/ordered-words.psh b/Task/Ordered-words/PowerShell/ordered-words.ps1 similarity index 100% rename from Task/Ordered-words/PowerShell/ordered-words.psh rename to Task/Ordered-words/PowerShell/ordered-words.ps1 diff --git a/Task/Ordered-words/Prolog/ordered-words.pro b/Task/Ordered-words/Prolog/ordered-words.pro index 3eb95461b4..2be75e271a 100644 --- a/Task/Ordered-words/Prolog/ordered-words.pro +++ b/Task/Ordered-words/Prolog/ordered-words.pro @@ -2,43 +2,43 @@ ordered_words :- % we read the URL of the words - http_open('http://www.puzzlers.org/pub/wordlists/unixdict.txt', In, []), - read_file(In, [], Out), - close(In), + http_open('http://www.puzzlers.org/pub/wordlists/unixdict.txt', In, []), + read_file(In, [], Out), + close(In), % we get a list of pairs key-value where key = Length and value = % this list must be sorted - msort(Out, MOut), + msort(Out, MOut), - group_pairs_by_key(MOut, POut), + group_pairs_by_key(MOut, POut), % we sorted this list in decreasing order of the length of values - predsort(my_compare, POut, [_N-V | _OutSort]), - maplist(mwritef, V). + predsort(my_compare, POut, [_N-V | _OutSort]), + maplist(mwritef, V). mwritef(V) :- - writef('%s\n', [V]). + writef('%s\n', [V]). read_file(In, L, L1) :- - read_line_to_codes(In, W), - ( W == end_of_file -> + read_line_to_codes(In, W), + ( W == end_of_file -> % the file is read - L1 = L - ; + L1 = L + ; % we sort the list of codes of the line - % and keep only the "goods word" - ( msort(W, W) -> - length(W, N), L2 = [N-W | L], (len = 6 -> writef('%s\n', [W]); true) - ; - L2 = L - ), + % and keep only the "goods word" + ( msort(W, W) -> + length(W, N), L2 = [N-W | L], (len = 6 -> writef('%s\n', [W]); true) + ; + L2 = L + ), % and we have the pair Key-Value in the result list - read_file(In, L2, L1)). + read_file(In, L2, L1)). % predicate for sorting list of pairs Key-Values % if the lentgh of values is the same % we sort the keys in alhabetic order my_compare(R, K1-_V1, K2-_V2) :- - ( K1 < K2 -> R = >; K1 > K2 -> R = <; =). + ( K1 < K2 -> R = >; K1 > K2 -> R = <; =). diff --git a/Task/Ordered-words/Rebol/ordered-words.rebol b/Task/Ordered-words/Rebol/ordered-words.rebol new file mode 100644 index 0000000000..7878996537 --- /dev/null +++ b/Task/Ordered-words/Rebol/ordered-words.rebol @@ -0,0 +1,30 @@ +Rebol [ + title: "Rosetta code: Ordered words" + file: %Ordered_words.r3 + url: https://rosettacode.org/wiki/Ordered_words +] +;; Find all longest words in unixdict.txt that are already alphabetically sorted (non-decreasing letters) +;; Load or fetch the dictionary +unless exists? %unixdict.txt [ + write %unixdict.txt + read https://raw.githubusercontent.com/thundergnat/rc-run/refs/heads/master/rc/resources/unixdict.txt +] +words: read/lines %unixdict.txt +max: [""] ;; initialize with one empty string (current best length = 0) +foreach word words [ + ;; If the word equals its sorted letters, it's alphabetically ordered; record its length, else -1 + len: either word = sort copy word [length? word] [-1] + case [ + ;; Found an ordered word longer than the current best: start a new result block + len > length? first max [ + max: reduce [word] + ] + ;; Found an ordered word with the same length as current best: add it to the results + len = length? first max [ + append max word + ] + ] +] +;; Display the block of longest alphabetically ordered words +print [length? max "words found of length" length? max/1] +probe max diff --git a/Task/Ordered-words/Refal/ordered-words.refal b/Task/Ordered-words/Refal/ordered-words.refal new file mode 100644 index 0000000000..e8741c078d --- /dev/null +++ b/Task/Ordered-words/Refal/ordered-words.refal @@ -0,0 +1,58 @@ +$ENTRY Go { + , : e.Dict + , : e.LongestOrdered + = ; +}; + +ReadFile { + s.Chan e.File = + + ; + (s.Chan), : { + 0 = ; + e.Line = (e.Line) ; + }; +}; + +Reduce { + (e.F) t.1 = t.1; + (e.F) t.1 e.2 = >; +}; + +Max { + s.1 s.2, : { + '+' = s.1; + e.X = s.2; + }; +}; + +Each { + (e.F) = ; + (e.F) (e.1) e.2 = ; +}; + +Select { + (e.F) = ; + (e.F) (e.1) e.2, : { + True = (e.1) ; + }; +}; + +Ordered { + s.1 = True; + s.1 s.2 e.3, >: { + '+' = False; + s.4 = ; + }; + e.1 = False; +}; + +IsLength { + s.Len e.1, : s.Len e.1 = True; + s.Len e.1 = False; +}; + +Length { e.1, : s.Len e.1 = s.Len; }; diff --git a/Task/Ordered-words/Run-BASIC/ordered-words.basic b/Task/Ordered-words/Run-BASIC/ordered-words.basic index 809f045537..040ed881f7 100644 --- a/Task/Ordered-words/Run-BASIC/ordered-words.basic +++ b/Task/Ordered-words/Run-BASIC/ordered-words.basic @@ -1,18 +1,18 @@ -a$ = httpget$("http://www.puzzlers.org/pub/wordlists/unixdict.txt") -j = 1 -i = instr(a$,chr$(10),j) +a$ = httpget$("http://www.puzzlers.org/pub/wordlists/unixdict.txt") +j = 1 +i = instr(a$,chr$(10),j) while i <> 0 - a1$ = mid$(a$,j,i-j) - for k = 1 to len(a1$) - 1 + a1$ = mid$(a$,j,i-j) + for k = 1 to len(a1$) - 1 if mid$(a1$,k,1) > mid$(a1$,k+1,1) then goto [noWay] next k - maxL = max(maxL,len(a1$)) + maxL = max(maxL,len(a1$)) if len(a1$) >= maxL then a2$ = a2$ + a1$ + "||" [noWay] -j = i + 1 -i = instr(a$,chr$(10),j) +j = i + 1 +i = instr(a$,chr$(10),j) wend -n = 1 +n = 1 while word$(a2$,n,"||") <> "" a3$ = word$(a2$,n,"||") if len(a3$) = maxL then print a3$ diff --git a/Task/Ordered-words/Rust/ordered-words.rust b/Task/Ordered-words/Rust/ordered-words.rs similarity index 100% rename from Task/Ordered-words/Rust/ordered-words.rust rename to Task/Ordered-words/Rust/ordered-words.rs diff --git a/Task/Ordered-words/Rye/ordered-words.rye b/Task/Ordered-words/Rye/ordered-words.rye new file mode 100644 index 0000000000..66f0886d53 --- /dev/null +++ b/Task/Ordered-words/Rye/ordered-words.rye @@ -0,0 +1,6 @@ +Read\lines %unixdict.txt +|filter { ::word = sort word } +|group { .length? .to-string } +|values +|max\by { .first .length? } +|print diff --git a/Task/Ordered-words/SETL/ordered-words.setl b/Task/Ordered-words/SETL/ordered-words.setl new file mode 100644 index 0000000000..6bbafba23b --- /dev/null +++ b/Task/Ordered-words/SETL/ordered-words.setl @@ -0,0 +1,20 @@ +program ordered_words; + dict := read_dict "unixdict.txt"; + ordereds := {word : word in dict | ordered word}; + maxlen := max/{#word : word in ordereds}; + + loop for word in ordereds | #word = maxlen do + print(word); + end loop; + + op read_dict(file); + dictfile := open(file, "r"); + dict := {getline(dictfile) : until eof(dictfile)}; + close(dictfile); + return dict; + end op; + + op ordered(word); + return True and/[word(i-1) <= word(i) : i in [2..#word]]; + end op; +end program; diff --git a/Task/Ordered-words/Scheme/ordered-words.scm b/Task/Ordered-words/Scheme/ordered-words.scm new file mode 100644 index 0000000000..4600a56601 --- /dev/null +++ b/Task/Ordered-words/Scheme/ordered-words.scm @@ -0,0 +1,20 @@ +(define sorted-words + (let ((port (open-input-file "unixdict.txt"))) + (let loop ((char (read-char port)) (word '()) (result '(()))) + (cond + ((eof-object? char) + (reverse (map (lambda (word) (apply string word)) result))) + ((eq? #\newline char) + (loop (read-char port) '() + (let ((best-length (length (car result))) (word-length (length word))) + (cond + ((or (< word-length best-length) (not (apply char>=? word))) result) + ((> word-length best-length) (list (reverse word))) + (else (cons (reverse word) result)))))) + (else (loop (read-char port) (cons char word) result)))))) + +(map (lambda (x) + (begin + (display x) + (newline))) + sorted-words) diff --git a/Task/Ordered-words/Scheme/ordered-words.ss b/Task/Ordered-words/Scheme/ordered-words.ss deleted file mode 100644 index 40d4d69979..0000000000 --- a/Task/Ordered-words/Scheme/ordered-words.ss +++ /dev/null @@ -1,20 +0,0 @@ -(define sorted-words - (let ((port (open-input-file "unixdict.txt"))) - (let loop ((char (read-char port)) (word '()) (result '(()))) - (cond - ((eof-object? char) - (reverse (map (lambda (word) (apply string word)) result))) - ((eq? #\newline char) - (loop (read-char port) '() - (let ((best-length (length (car result))) (word-length (length word))) - (cond - ((or (< word-length best-length) (not (apply char>=? word))) result) - ((> word-length best-length) (list (reverse word))) - (else (cons (reverse word) result)))))) - (else (loop (read-char port) (cons char word) result)))))) - -(map (lambda (x) - (begin - (display x) - (newline))) - sorted-words) diff --git a/Task/Ordered-words/TAV/ordered-words.tav b/Task/Ordered-words/TAV/ordered-words.tav new file mode 100644 index 0000000000..62e3dc8217 --- /dev/null +++ b/Task/Ordered-words/TAV/ordered-words.tav @@ -0,0 +1,20 @@ +main(params):+ + res =: [] \ to hold the words + maxw =: 0 \ maximum wordlength + ?# w =: file 'unixdict.txt' give lines + fault w print stop \ message and stop if error + ? (is ordered w) & w.count >= maxw + ? w.count > maxw \ longer word, + res =: [] \ reset list + res[] =: w \ store at next index in list + maxw =: w.count \ update + print row res join values by ' ' + +\ check word (w) +is ordered (w): + cc =: ' ' \ smallest character + ?# i =: from 1 upto w.count + ? w[i] < cc + :> ?- \ failed + cc =: w[i] + :> ?+ diff --git a/Task/Ordered-words/Tcl/ordered-words.tcl b/Task/Ordered-words/Tcl/ordered-words.tcl index 1a5bc0ab06..49bc175ce5 100644 --- a/Task/Ordered-words/Tcl/ordered-words.tcl +++ b/Task/Ordered-words/Tcl/ordered-words.tcl @@ -4,17 +4,17 @@ package require http proc chooseOrderedWords list { set len 0 foreach word $list { - # Condition to determine whether a word is ordered; are its characters - # in sorted order? - if {$word eq [join [lsort [split $word ""]] ""]} { - if {[string length $word] > $len} { - set len [string length $word] - set orderedOfMaxLen {} - } - if {[string length $word] == $len} { - lappend orderedOfMaxLen $word - } - } + # Condition to determine whether a word is ordered; are its characters + # in sorted order? + if {$word eq [join [lsort [split $word ""]] ""]} { + if {[string length $word] > $len} { + set len [string length $word] + set orderedOfMaxLen {} + } + if {[string length $word] == $len} { + lappend orderedOfMaxLen $word + } + } } return $orderedOfMaxLen } diff --git a/Task/Ordered-words/Uiua/ordered-words.uiua b/Task/Ordered-words/Uiua/ordered-words.uiua new file mode 100644 index 0000000000..40d1aa9460 --- /dev/null +++ b/Task/Ordered-words/Uiua/ordered-words.uiua @@ -0,0 +1,7 @@ +# Experimental! +# Grab the entire contents of the page as an array of bytes, then decode it into a string of text: +°utf₈ &fetch "https://raw.githubusercontent.com/thundergnat/rc-run/refs/heads/master/rc/resources/unixdict.txt" +°/$"_\n_" # Split the string into words by line breaks +▽⊸≡◇(≍⊸⍆) # Keep the words that are sorted, i.e. have their letters in alphabetical order +▽⊸(=⊸/↥≡◇⧻) # Keep the remaining words that are the longest +≡◇&p # Print out each word individually diff --git a/Task/Ordered-words/V-(Vlang)/ordered-words.v b/Task/Ordered-words/V-(Vlang)/ordered-words.v index 1dd62e5dfe..a8de2761a3 100644 --- a/Task/Ordered-words/V-(Vlang)/ordered-words.v +++ b/Task/Ordered-words/V-(Vlang)/ordered-words.v @@ -1,23 +1,25 @@ +import os + fn main() { words := os.read_file("./unixdict.txt") or {println(err) exit(-1)}.split_into_lines() - mut longest_len := 0 - mut longest := []string{} - mut u_word := []u8{} - for word in words { - for chars in word {u_word << chars} - u_word.sort() - if word.len > longest_len { - if word == u_word.bytestr() { - longest_len = word.len - longest.clear() - longest << word - } - } - else if word.len == longest_len { - if word == u_word.bytestr() {longest << word} - } - u_word.clear() - } - println("The ${longest.len} ordered words with the longest length (${longest_len}) are:") - print(longest.join("\n")) + mut longest_len := 0 + mut longest := []string{} + mut u_word := []u8{} + for word in words { + for chars in word {u_word << chars} + u_word.sort() + if word.len > longest_len { + if word == u_word.bytestr() { + longest_len = word.len + longest.clear() + longest << word + } + } + else if word.len == longest_len { + if word == u_word.bytestr() {longest << word} + } + u_word.clear() + } + println("The ${longest.len} ordered words with the longest length (${longest_len}) are:") + print(longest.join("\n")) } diff --git a/Task/Ordered-words/VBScript/ordered-words.vb b/Task/Ordered-words/VBScript/ordered-words.vb deleted file mode 100644 index ed7c5101ff..0000000000 --- a/Task/Ordered-words/VBScript/ordered-words.vb +++ /dev/null @@ -1,34 +0,0 @@ -Set objFSO = CreateObject("Scripting.FileSystemObject") -Set infile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) & "\" &_ - "unixdict.txt",1) -list = "" -length = 0 - -Do Until inFile.AtEndOfStream - line = infile.ReadLine - If IsOrdered(line) Then - If Len(line) > length Then - length = Len(line) - list = line & vbCrLf - ElseIf Len(line) = length Then - list = list & line & vbCrLf - End If - End If -Loop - -WScript.StdOut.Write list - -Function IsOrdered(word) - IsOrdered = True - prev_val = 0 - For i = 1 To Len(word) - If i = 1 Then - prev_val = Asc(Mid(word,i,1)) - ElseIf Asc(Mid(word,i,1)) >= prev_val Then - prev_val = Asc(Mid(word,i,1)) - Else - IsOrdered = False - Exit For - End If - Next -End Function diff --git a/Task/Ordered-words/VBScript/ordered-words.vbs b/Task/Ordered-words/VBScript/ordered-words.vbs new file mode 100644 index 0000000000..953371746c --- /dev/null +++ b/Task/Ordered-words/VBScript/ordered-words.vbs @@ -0,0 +1,34 @@ +Set objFSO = CreateObject("Scripting.FileSystemObject") +Set infile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) & "\" &_ + "unixdict.txt",1) +list = "" +length = 0 + +Do Until inFile.AtEndOfStream + line = infile.ReadLine + If IsOrdered(line) Then + If Len(line) > length Then + length = Len(line) + list = line & vbCrLf + ElseIf Len(line) = length Then + list = list & line & vbCrLf + End If + End If +Loop + +WScript.StdOut.Write list + +Function IsOrdered(word) + IsOrdered = True + prev_val = 0 + For i = 1 To Len(word) + If i = 1 Then + prev_val = Asc(Mid(word,i,1)) + ElseIf Asc(Mid(word,i,1)) >= prev_val Then + prev_val = Asc(Mid(word,i,1)) + Else + IsOrdered = False + Exit For + End If + Next +End Function diff --git a/Task/Ormiston-triples/Dart/ormiston-triples.dart b/Task/Ormiston-triples/Dart/ormiston-triples.dart new file mode 100644 index 0000000000..6f4374df75 --- /dev/null +++ b/Task/Ormiston-triples/Dart/ormiston-triples.dart @@ -0,0 +1,19 @@ +import 'package:collection/collection.dart'; +import 'package:more/more.dart'; + +void main(List args) { + var ts = DateTime.now(); + const start = 10000000; + final limit = 1000000000; + ormTriple(List e) => + e.map((t) => "$t".split('').sorted().join()).toSet().length == 1; + var triples = start + .to(limit) + .where((e) => e.isProbablyPrime) + .window(3) + .where(ormTriple) + .toList(); + print("Found ${triples.length} triples"); + print("First 25: ${triples.take(25)} "); + print(DateTime.now().difference(ts).inMilliseconds); // 189 sec +} diff --git a/Task/Ormiston-triples/Delphi/ormiston-triples.delphi b/Task/Ormiston-triples/Delphi/ormiston-triples.pas similarity index 100% rename from Task/Ormiston-triples/Delphi/ormiston-triples.delphi rename to Task/Ormiston-triples/Delphi/ormiston-triples.pas diff --git a/Task/Ormiston-triples/EasyLang/ormiston-triples.easy b/Task/Ormiston-triples/EasyLang/ormiston-triples.easy index c72b9958e2..0e2cae9628 100644 --- a/Task/Ormiston-triples/EasyLang/ormiston-triples.easy +++ b/Task/Ormiston-triples/EasyLang/ormiston-triples.easy @@ -1,50 +1,60 @@ -fastfunc isprim num . - if num mod 3 = 0 - return 0 - . - i = 5 - while i <= sqrt num - if num mod i = 0 - return 0 +maxn = 1e9 +slen = (maxn - 1) / 2 +len sieve@[] slen + 1 +fastproc . + klim = (floor sqrt maxn - 1) / 2 + for kd = 1 to klim : if sieve@[kd] = 0 + d = 2 * kd + 1 + start = (d * d - 1) / 2 + for k = start step 2 * d to slen - d + sieve@[k] = 1 + sieve@[k + d] = 1 . - i += 2 - if num mod i = 0 - return 0 - . - i += 4 + if k <= slen : sieve@[k] = 1 . - return 1 . -func nextprim n . +len pow10[] 10 +proc . + for i = 1 to 10 : pow10[i] = pow 10 (i - 1) +. +indsv = 0 +fastfunc nextprim . repeat - n += 2 - until isprim n = 1 + indsv += 1 + until sieve@[indsv] = 0 . - return n + return indsv * 2 + 1 . -func digs n . +fastfunc digs n . while n > 0 - r += pow 10 (n mod 10) + r += pow10[n mod 10 + 1] n = n div 10 . return r . -print "Smallest member of the first 25 Ormiston triples:" -b = 2 a = 3 -repeat - c = b - dc = db - b = a - db = da - a = nextprim a - until a > 1000000000 +b = 2 +c = 0 +fastproc next . + db = digs b da = digs a - if da = db and da = dc - cnt += 1 - if cnt <= 25 - write c & " " - . + repeat + c = b + dc = db + b = a + db = da + a = nextprim + da = digs a + until a > maxn or da = db and da = dc . . +# +print "Smallest member of the first 25 Ormiston triples:" +repeat + next + until a > maxn + cnt += 1 + if cnt <= 25 : write c & " " +. +print "" print "Ormiston triples before 1 billion: " & cnt diff --git a/Task/Ormiston-triples/Fortran/ormiston-triples.f b/Task/Ormiston-triples/Fortran/ormiston-triples.f new file mode 100644 index 0000000000..22dbeb9cab --- /dev/null +++ b/Task/Ormiston-triples/Fortran/ormiston-triples.f @@ -0,0 +1,155 @@ +! +! Ormiston triplets +! tested with Intel ifx (IFX) 2025.2.1 20250806 on Kubuntu 26.04 +! GNU gfortran (Ubuntu 15.2.0-16ubuntu1) 15.2.0 on Kubuntu 26.04 +! NOT VSI Fortran on OpenVMS because of excessive memory requirement +! U.B., April 2026 +! +program Ormiston3 +implicit none +integer, parameter :: int64=8 +integer(kind=int64), parameter ::limit = 10000000000_int64 ! 1 billion, 10 billions might overwhelm the computer +integer(kind=int64), dimension(:), allocatable :: primes +integer(kind=int64) :: highPrimes +integer(kind=int64) :: ii +integer :: count, count1B, NumbersInLine + +count=0 +NumbersInLine = 0 +count1B = 0 +call SievePrimes (limit) +write (*,'("Smallest members of first 25 Ormiston triples:")') +do ii=0, highPrimes-2 + if (isAnagram (primes(ii), primes (ii+1), primes(ii+2))) then + count = count + 1 + if (count .le. 25) then + write (*, '(i8,x)', advance='no') primes(ii) ! Smallest member of the 1st 25 triplets + NumbersInLine = NumbersInLine+1 + if (NumbersInLine .eq. 5) then + write (*,*) + NumbersInLine = 0 + endif + endif + endif + ! Store count of 1 Million for later output + if (primes(ii) .ge. 1000000000_int64 .and. count1B .eq. 0) then + count1B = count + endif +enddo +! Print the 1-million counter only if the limit is higher than 1 million. +if (limit .gt. 1000000000_int64) write (*,'(/,"Up to ", i0, " there are ", i0, " Ormiston triples.")') 1000000000, count1B +write (*,'(/,"Up to ", i0, " there are ", i0, " Ormiston triples.")') limit, count + + +contains + +! =========================================================================== +! Decide whether n1 and 2 contain identical digits, i.e. they are an anagram. +! =========================================================================== +function isAnagram (n1, n2, n3) result (YN) +integer(kind=int64), intent(in) :: n1, n2, n3 +logical :: YN +integer :: ii +integer(kind=int64), save :: oldN3 =-2 +integer, dimension(0:9), save :: digitsCountN1, digitsCountN2, digitsCountN3 + +if (n2 .ne. oldn3) then ! 1st time here? previous upper value not yet saved? + call getDigits (n1, digitsCountN1) ! so we need to evaluate digit counts for N1 + call getDigits (n2, digitsCountN2) ! so we need to evaluate digit counts for N1 +else + digitsCountN1 = digitsCountN2 ! Otherwise just copy saved previous result. + digitsCountN2 = digitsCountN3 ! Otherwise just copy saved previous result. +endif +call getDigits (n3, digitsCountN3) ! Eval for n3 in all cases. +oldn3 = n3 ! Save for next time + +! Check whether both counter arrays are identical. The first difference is enough +! fort the decision against an anagram. +do ii=0, 9 + if (digitsCountN1(ii) .ne. digitsCountN2(ii)) then + YN = .false. ! digits of n1 and n2 not identical: early return "not an anagram" + return + endif + if (digitsCountN1(ii) .ne. digitsCountN3(ii)) then + YN = .false. ! digits of n1 and n3 not identical: early return "not an anagram" + return + end if +end do +YN = .true. ! Here if both counter arrays identical. +end function isAnagram + + +! ========================================================== +! Count the digits of n, sort counters in array digitsCount +! ========================================================== +subroutine getDigits (n, digitsCount) +integer(kind=int64), intent(in) :: n +integer, dimension(0:9), intent(out) :: digitsCount +integer(kind=int64) :: nn +integer :: lastdig +digitsCount = 0 +nn = n +do while (nn .ne. 0_int64) + lastdig = mod(nn, 10) + digitsCount(lastdig) = digitsCount(lastdig) + 1 + nn = nn/10 +end do + +end subroutine getDigits + +! ================================================================== +! The usual, omnipresent sieve to produce an array of prime numbers +! ================================================================== +subroutine SievePrimes(lmt) + implicit none + integer(kind=int64) :: lmt + integer(kind=1), dimension(:), allocatable :: sieve + integer(kind=int64) :: p,i,delta + + allocate (sieve (lmt/2) ) + if ( .not. allocated (sieve)) then ! ERROR if allocation fails + print *, 'Sieve not allocated.' + STOP + endif + sieve=0 + ! estimate count of primes + i = int (real(lmt,8)/(log (real(lmt, 8))-1.1_8)) + + allocate (primes(0:i-1_int64)) + if ( .not. allocated (primes)) then + print *, 'Primes not allocated.' + STOP + endif + highPrimes = i-1_int64 ! highes usable index + p = 1 + do + delta = 2_int64*p+1_int64 + ! ((2*p+1)^2 ) -1)/ 2 = ((4*p*p+4*p+1) -1)/2 = 2*p*(p+1) + i = 2_int64*p*(p+1_int64) + if (i.gt. lmt/2) then ! size(sieve)) then + exit + endif + + do while (i <= lmt/2) ! size(sieve)) + sieve(i) = 1 + i = i+delta + end do + p=p+1_int64 + do while (sieve(p) .ne. 0) + p=p+1_int64 + end do + end do + + primes(0) = 2 + i = 1 + do p = 1, lmt/2 ! size (sieve) + if (sieve(p) .eq. 0) then + primes(i) = 2_int64*p+1_int64 + i = i+1_int64 + endif + end do + highPrimes = i-1_int64 ! instead of (in Fortran) non-existant re-allocate with reduced length +end subroutine SievePrimes + + +end program Ormiston3 diff --git a/Task/Ormiston-triples/Julia/ormiston-triples.julia b/Task/Ormiston-triples/Julia/ormiston-triples.jl similarity index 100% rename from Task/Ormiston-triples/Julia/ormiston-triples.julia rename to Task/Ormiston-triples/Julia/ormiston-triples.jl diff --git a/Task/Ormiston-triples/Phix/ormiston-triples-1.phix b/Task/Ormiston-triples/Phix/ormiston-triples-1.phix index 349ae64a33..914f565b8c 100644 --- a/Task/Ormiston-triples/Phix/ormiston-triples-1.phix +++ b/Task/Ormiston-triples/Phix/ormiston-triples-1.phix @@ -1,108 +1,106 @@ -(phixonline)--> - -- - -- demo\rosetta\Ormiston_triplets.exw - -- ================================== - -- - -- Uses a segmented sieve, which is about half the speed of get_primes_le(), but uses far less memory. - -- If permited, get_primes_le(1e10) would generate a result of 455,052,511 primes, more than 32 bit - -- can cope with, and use over 6GB of ram, and take about 11mins 44s, that is on this box at least, - -- whereas this processes them on-the-fly, and only uses about 6MB of memory (ie 0.1% of 6GB). - -- - with javascript_semantics +-- +-- demo\rosetta\Ormiston_triplets.exw +-- ================================== +-- +-- Uses a segmented sieve, which is about half the speed of get_primes_le(), but uses far less memory. +-- If permited, get_primes_le(1e10) would generate a result of 455,052,511 primes, more than 32 bit +-- can cope with, and use over 6GB of ram, and take about 11mins 44s, that is on this box at least, +-- whereas this processes them on-the-fly, and only uses about 6MB of memory (ie 0.1% of 6GB). +-- +with javascript_semantics - atom t0 = time() +atom t0 = time() - procedure ormiston_triplets(atom limit) - // Generate primes using the segmented sieve of Eratosthenes. - // credit: https://gist.github.com/kimwalisch/3dc39786fab8d5b34fee - integer segment_size = floor(sqrt(limit)), - count = 0, i = 3, s = 3, triplen = 1 - atom p1 = 2, p2, n = 3, nc = min(1e9,limit), low = 0, t1 = time()+1 +procedure ormiston_triplets(atom limit) + // Generate primes using the segmented sieve of Eratosthenes. + // credit: https://gist.github.com/kimwalisch/3dc39786fab8d5b34fee + integer segment_size = floor(sqrt(limit)), + count = 0, i = 3, s = 3, triplen = 1 + atom p1 = 2, p2, n = 3, nc = min(1e9,limit), low = 0, t1 = time()+1 - sequence isprime = repeat(true,segment_size+1), - primes = {}, - multiples = {}, - orm25 = repeat(0,25) + sequence isprime = repeat(true,segment_size+1), + primes = {}, + multiples = {}, + orm25 = repeat(0,25) - while low<=limit do - sequence sieve = repeat(true,segment_size+1) - if time()>t1 then - progress("Processing %,d/%,d (%3.2f%%)\r",{low,limit,(low/limit)*100}) - t1 = time()+1 - end if + while low<=limit do + sequence sieve = repeat(true,segment_size+1) + if time()>t1 then + progress("Processing %,d/%,d (%3.2f%%)\r",{low,limit,(low/limit)*100}) + t1 = time()+1 + end if - // current segment = [low, high] - atom high = min(low+segment_size,limit) - // generate sieving primes using simple sieve of Eratosthenes - while i*i<=min(high,segment_size) do - if isprime[i+1] then - for j=i*i to segment_size by i do - isprime[j+1] = false - end for - end if - i += 2 - end while + // current segment = [low, high] + atom high = min(low+segment_size,limit) + // generate sieving primes using simple sieve of Eratosthenes + while i*i<=min(high,segment_size) do + if isprime[i+1] then + for j=i*i to segment_size by i do + isprime[j+1] = false + end for + end if + i += 2 + end while - // initialize sieving primes for segmented sieve - while s*s<=high do - if isprime[s+1] then - primes &= s - multiples &= s*s-low - end if - s += 2 - end while + // initialize sieving primes for segmented sieve + while s*s<=high do + if isprime[s+1] then + primes &= s + multiples &= s*s-low + end if + s += 2 + end while - // sieve the current segment - for mi,j in multiples do - integer k = primes[mi]*2 - while j<segment_size do - sieve[j+1] = false - j += k - end while - multiples[mi] = j - segment_size - end for + // sieve the current segment + for mi,j in multiples do + integer k = primes[mi]*2 + while jwhile
    n<=high do - if sieve[n-low+1] then // n is a prime - if triplen=1 then - if remainder(n-p1,18)=0 - and sort(sprint(p1))=sort(sprint(n)) then - p2 = n - triplen = 2 - else - p1 = n - end if - elsif triplen=2 - and remainder(n-p2,18)=0 - and sort(sprint(p2))=sort(sprint(n)) then - -- triplet found! - if p1>=nc then - string e = elapsed_short(time()-t0) - progress("%,d Ormiston triplets before %,d (%s)\n", {count, nc, e}) - nc *= 10 - end if - count += 1 - if count<=25 then - orm25[count] = sprintf("%d",{p1}) - if count=25 then - printf(1,"Smallest members of first 25 Ormiston triplets:\n%s\n",join_by(orm25,1,5)) - end if - end if - -- overlapping (and leave triplen set to 2): - p1 = p2 - p2 = n - -- (for disjoint-only just set triplen to 0) - else - p1 = n - triplen = 1 - end if - end if - n += 2 - end while - low += segment_size - end while - string e = elapsed_short(time()-t0) - progress("%,d Ormiston triplets before %,d (%s)\n", {count, nc, e}) - end procedure - ormiston_triplets(iff(platform()=JS?1e8:1e9)) - - requires("1.0.3") - requires(WINDOWS) - requires(64,true) - include builtins/primesieve.e - atom t0 = time(), t1 = time()+1, - p = primesieve_next_prime(), - p1 = p, p2, count = 0, nc = 1e9 - sequence orm25 = repeat(0,25) +requires("1.0.3") +requires(WINDOWS) +requires(64,true) +include builtins/primesieve.e +atom t0 = time(), t1 = time()+1, + p = primesieve_next_prime(), + p1 = p, p2, count = 0, nc = 1e9 +sequence orm25 = repeat(0,25) - procedure showt() - if count=25 then - progress("Smallest members of first 25 Ormiston triplets:\n") - progress("%s\n",join_by(orm25,1,5)) - else - string e = elapsed_short(time()-t0) - progress("%,6d Ormiston triplets before %,d (%s)\n",{count,nc,e}) - nc *= 10 - end if - end procedure +procedure showt() + if count=25 then + progress("Smallest members of first 25 Ormiston triplets:\n") + progress("%s\n",join_by(orm25,1,5)) + else + string e = elapsed_short(time()-t0) + progress("%,6d Ormiston triplets before %,d (%s)\n",{count,nc,e}) + nc *= 10 + end if +end procedure - while p<1e10 do - p2 = p1 - p1 = p - p = primesieve_next_prime() - if remainder(p-p1,18)=0 - and remainder(p1-p2,18)=0 then - string s = sort(sprint(p)) - if sort(sprint(p1))=s - and sort(sprint(p2))=s then - if p>=nc then showt() end if - count += 1 - if count<=25 then - orm25[count] = sprintf("%d",{p2}) - if count=25 then showt() end if - end if - end if - elsif time()>t1 then - progress("%,d\r",{p}) - t1 = time()+1 - end if - end while - showt() - ['A'], padovan_l_system(LS). +padovan_l_system(['C' | LS]) --> ['B'], padovan_l_system(LS). +padovan_l_system(['A', 'B' | LS]) --> ['C'], padovan_l_system(LS). +padovan_l_system([]) --> []. -def padovan_f(n: int) -> int: - return floor(_p**(n-1) / _s + .5) +fibonacci_l_system(['B' | LS]) --> ['A'], fibonacci_l_system(LS). +fibonacci_l_system(['A', 'B' | LS]) --> ['B'], fibonacci_l_system(LS). +fibonacci_l_system([]) --> []. -def padovan_l(start: str='A', - rules: Dict[str, str]=dict(A='B', B='C', C='AB') - ) -> Generator[str, None, None]: - axiom = start - while True: - yield axiom - axiom = ''.join(rules[ch] for ch in axiom) +l_system(_, String, String). +l_system(DCG, String0, String) :- + once(phrase(call(DCG, String1), String0)), + l_system(DCG, String1, String). +:- meta_predicate l_system(3, -). +%! l_system(:DCG, +String) is multi. +l_system(DCG, String) :- l_system(DCG, ['A'], String). -if __name__ == "__main__": - from itertools import islice +task :- + format("The first 20 Padovan numbers are:~n"), + foreach( + limit(20, padovan_recurrent(Padovan)), + format("~d ", [Padovan]) + ), + format("~nThe first 10 strings produced by the L-system are:~n"), + foreach( + limit(10, l_system(padovan_l_system, LString)), + format("~s ", [LString]) + ), + nl, + run_tests(padovan_sequence). - print("The first twenty terms of the sequence.") - print(str([padovan_f(n) for n in range(20)])[1:-1]) +:- begin_tests(padovan_sequence). - r_generator = padovan_r() - if all(next(r_generator) == padovan_f(n) for n in range(64)): - print("\nThe recurrence and floor based algorithms match to n=63 .") - else: - print("\nThe recurrence and floor based algorithms DIFFER!") +test(recurrence_and_floor_are_same_sequence) :- + once(findnsols(64, PR, padovan_recurrent(PR), PRs)), + numlist(0, 63, Ns), + maplist(padovan_truncated, Ns, PTs), + assertion(PRs == PTs). - print("\nThe first 10 L-system string-lengths and strings") - l_generator = padovan_l(start='A', rules=dict(A='B', B='C', C='AB')) - print('\n'.join(f" {len(string):3} {repr(string)}" - for string in islice(l_generator, 10))) +test(lengths_of_first_32_strings_is_Padovan_sequence) :- + once(findnsols(32, PR, padovan_recurrent(PR), PRs)), + once(findnsols(32, PL, ( + l_system(padovan_l_system, String), + length(String, PL) + ), PLs)), + assertion(PRs == PLs). - r_generator = padovan_r() - l_generator = padovan_l(start='A', rules=dict(A='B', B='C', C='AB')) - if all(len(next(l_generator)) == padovan_f(n) == next(r_generator) - for n in range(32)): - print("\nThe L-system, recurrence and floor based algorithms match to n=31 .") - else: - print("\nThe L-system, recurrence and floor based algorithms DIFFER!") +:- end_tests(padovan_sequence). diff --git a/Task/Padovan-sequence/Phix/padovan-sequence-3.phix b/Task/Padovan-sequence/Phix/padovan-sequence-3.phix index 28d825fdf7..ef5ba05ff2 100644 --- a/Task/Padovan-sequence/Phix/padovan-sequence-3.phix +++ b/Task/Padovan-sequence/Phix/padovan-sequence-3.phix @@ -1,136 +1,49 @@ -'''Padovan series''' - -from itertools import chain, islice from math import floor -from operator import eq +from collections import deque +from typing import Dict, Generator -# padovans :: [Int] -def padovans(): - '''Non-finite series of Padovan numbers, - defined in terms of recurrence relations. - ''' - def recurrence(abc): - a, b, c = abc - return a, (b, c, a + b) +def padovan_r() -> Generator[int, None, None]: + last = deque([1, 1, 1], 4) + while True: + last.append(last[-2] + last[-3]) + yield last.popleft() - return unfoldr(recurrence)( - (1, 1, 1) - ) +_p, _s = 1.324717957244746025960908854, 1.0453567932525329623 + +def padovan_f(n: int) -> int: + return floor(_p**(n-1) / _s + .5) + +def padovan_l(start: str='A', + rules: Dict[str, str]=dict(A='B', B='C', C='AB') + ) -> Generator[str, None, None]: + axiom = start + while True: + yield axiom + axiom = ''.join(rules[ch] for ch in axiom) -# padovanFloor :: [Int] -def padovanFloor(): - '''The Padovan series, defined in terms - of a floor function. - ''' - p = 1.324717957244746025960908854 - s = 1.0453567932525329623 +if __name__ == "__main__": + from itertools import islice - def f(n): - return floor(p ** (n - 1) / s + 0.5), 1 + n + print("The first twenty terms of the sequence.") + print(str([padovan_f(n) for n in range(20)])[1:-1]) - return unfoldr(f)(0) + r_generator = padovan_r() + if all(next(r_generator) == padovan_f(n) for n in range(64)): + print("\nThe recurrence and floor based algorithms match to n=63 .") + else: + print("\nThe recurrence and floor based algorithms DIFFER!") + print("\nThe first 10 L-system string-lengths and strings") + l_generator = padovan_l(start='A', rules=dict(A='B', B='C', C='AB')) + print('\n'.join(f" {len(string):3} {repr(string)}" + for string in islice(l_generator, 10))) -# padovanLSystem : [Int] -def padovanLSystem(): - '''An L-system generating terms whose lengths - are the values of the Padovan integer series. - ''' - def rule(c): - return 'B' if 'A' == c else ( - 'C' if 'B' == c else 'AB' - ) - - def f(s): - return s, ''.join(list(concatMap(rule)(s))) - - return unfoldr(f)('A') - - -# ------------------------- TEST ------------------------- - -# prefixesMatch :: [a] -> [a] -> Bool -def prefixesMatch(xs, ys, n): - '''True if the first n items of each - series are the same. - ''' - return all(map(eq, take(n)(xs), ys)) - - -# main :: IO () -def main(): - '''Test three Padovan functions for - equivalence and expected results. - ''' - print('\n'.join([ - "First 20 padovans:\n", - repr(take(20)(padovans())), - - "\nThe recurrence and floor-based functions" + ( - " match over 64 terms:\n" - ), - repr(prefixesMatch( - padovans(), - padovanFloor(), - 64 - )), - - "\nFirst 10 L-System strings:\n", - repr(take(10)(padovanLSystem())), - - "\nThe lengths of the first 32 L-System strings", - "match the Padovan sequence:\n", - repr(prefixesMatch( - padovans(), - (len(x) for x in padovanLSystem()), - 32 - )) - ])) - - -# ----------------------- GENERIC ------------------------ - -# concatMap :: (a -> [b]) -> [a] -> [b] -def concatMap(f): - '''A concatenated map''' - def go(xs): - return chain.from_iterable(map(f, xs)) - return go - - -# unfoldr :: (b -> Maybe (a, b)) -> b -> [a] -def unfoldr(f): - '''A lazy (generator) list unfolded from a seed value - by repeated application of f until no residue remains. - Dual to fold/reduce. - f returns either None, or just (value, residue). - For a strict output list, wrap the result with list() - ''' - def go(x): - valueResidue = f(x) - while None is not valueResidue: - yield valueResidue[0] - valueResidue = f(valueResidue[1]) - return go - - -# take :: Int -> [a] -> [a] -# take :: Int -> String -> String -def take(n): - '''The prefix of xs of length n, - or xs itself if n > length xs. - ''' - def go(xs): - return ( - xs[0:n] - if isinstance(xs, (list, tuple)) - else list(islice(xs, n)) - ) - return go - - -# MAIN --- -if __name__ == '__main__': - main() + r_generator = padovan_r() + l_generator = padovan_l(start='A', rules=dict(A='B', B='C', C='AB')) + if all(len(next(l_generator)) == padovan_f(n) == next(r_generator) + for n in range(32)): + print("\nThe L-system, recurrence and floor based algorithms match to n=31 .") + else: + print("\nThe L-system, recurrence and floor based algorithms DIFFER!") diff --git a/Task/Padovan-sequence/Phix/padovan-sequence-4.phix b/Task/Padovan-sequence/Phix/padovan-sequence-4.phix new file mode 100644 index 0000000000..28d825fdf7 --- /dev/null +++ b/Task/Padovan-sequence/Phix/padovan-sequence-4.phix @@ -0,0 +1,136 @@ +'''Padovan series''' + +from itertools import chain, islice +from math import floor +from operator import eq + + +# padovans :: [Int] +def padovans(): + '''Non-finite series of Padovan numbers, + defined in terms of recurrence relations. + ''' + def recurrence(abc): + a, b, c = abc + return a, (b, c, a + b) + + return unfoldr(recurrence)( + (1, 1, 1) + ) + + +# padovanFloor :: [Int] +def padovanFloor(): + '''The Padovan series, defined in terms + of a floor function. + ''' + p = 1.324717957244746025960908854 + s = 1.0453567932525329623 + + def f(n): + return floor(p ** (n - 1) / s + 0.5), 1 + n + + return unfoldr(f)(0) + + +# padovanLSystem : [Int] +def padovanLSystem(): + '''An L-system generating terms whose lengths + are the values of the Padovan integer series. + ''' + def rule(c): + return 'B' if 'A' == c else ( + 'C' if 'B' == c else 'AB' + ) + + def f(s): + return s, ''.join(list(concatMap(rule)(s))) + + return unfoldr(f)('A') + + +# ------------------------- TEST ------------------------- + +# prefixesMatch :: [a] -> [a] -> Bool +def prefixesMatch(xs, ys, n): + '''True if the first n items of each + series are the same. + ''' + return all(map(eq, take(n)(xs), ys)) + + +# main :: IO () +def main(): + '''Test three Padovan functions for + equivalence and expected results. + ''' + print('\n'.join([ + "First 20 padovans:\n", + repr(take(20)(padovans())), + + "\nThe recurrence and floor-based functions" + ( + " match over 64 terms:\n" + ), + repr(prefixesMatch( + padovans(), + padovanFloor(), + 64 + )), + + "\nFirst 10 L-System strings:\n", + repr(take(10)(padovanLSystem())), + + "\nThe lengths of the first 32 L-System strings", + "match the Padovan sequence:\n", + repr(prefixesMatch( + padovans(), + (len(x) for x in padovanLSystem()), + 32 + )) + ])) + + +# ----------------------- GENERIC ------------------------ + +# concatMap :: (a -> [b]) -> [a] -> [b] +def concatMap(f): + '''A concatenated map''' + def go(xs): + return chain.from_iterable(map(f, xs)) + return go + + +# unfoldr :: (b -> Maybe (a, b)) -> b -> [a] +def unfoldr(f): + '''A lazy (generator) list unfolded from a seed value + by repeated application of f until no residue remains. + Dual to fold/reduce. + f returns either None, or just (value, residue). + For a strict output list, wrap the result with list() + ''' + def go(x): + valueResidue = f(x) + while None is not valueResidue: + yield valueResidue[0] + valueResidue = f(valueResidue[1]) + return go + + +# take :: Int -> [a] -> [a] +# take :: Int -> String -> String +def take(n): + '''The prefix of xs of length n, + or xs itself if n > length xs. + ''' + def go(xs): + return ( + xs[0:n] + if isinstance(xs, (list, tuple)) + else list(islice(xs, n)) + ) + return go + + +# MAIN --- +if __name__ == '__main__': + main() diff --git a/Task/Padovan-sequence/Rust/padovan-sequence.rust b/Task/Padovan-sequence/Rust/padovan-sequence.rs similarity index 100% rename from Task/Padovan-sequence/Rust/padovan-sequence.rust rename to Task/Padovan-sequence/Rust/padovan-sequence.rs diff --git a/Task/Padovan-sequence/Uiua/padovan-sequence.uiua b/Task/Padovan-sequence/Uiua/padovan-sequence.uiua new file mode 100644 index 0000000000..3b2d61c065 --- /dev/null +++ b/Task/Padovan-sequence/Uiua/padovan-sequence.uiua @@ -0,0 +1,10 @@ +R ← ⍥(˜⊂+◌⊸⊣₃) ⊙1_1_1 -3 +F ← ⊂1⁅÷1.045356793252533⍥(⊸×1.324717957244746)⊙1-1 +M ← map"ABC" {"B" "C" "AB"} +N ← ⇌∧(⊂⇌°□˜getM)⊙"" +L ← ⍥(˜⊂⍜°□N⊸⊣)⊙{"A"}-1 + +&pR 20 # First 20 terms using recurrence relationship. +&p⨬("no match"|"match")≍⊃R F 64 # Show that formula matches up to 64 terms. +&p L 10 # First ten terms of the L-system. +&p⨬("no match"|"match")≍⊃(R|≡◇⧻L) 32 # Show that lengths match recurrence up to 32 terms. diff --git a/Task/Palindrome-dates/ALGOL-68/palindrome-dates.alg b/Task/Palindrome-dates/ALGOL-68/palindrome-dates.alg index 3165c787ab..69184d38d7 100644 --- a/Task/Palindrome-dates/ALGOL-68/palindrome-dates.alg +++ b/Task/Palindrome-dates/ALGOL-68/palindrome-dates.alg @@ -24,8 +24,8 @@ BEGIN # print future palindromic dates []INT max dd = ( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ); # current date in local time (Algol 68G extension) # []INT date = local time; - INT yy now = local time[ 1 ] MOD 100; - INT cc now = local time[ 1 ] OVER 100; + INT yy now = date[ 1 ] MOD 100; + INT cc now = date[ 1 ] OVER 100; INT dates to print := 15; # maximum number of dates to print # FOR c pos FROM LWB de TO UPB de WHILE dates to print > 0 DO INT cc = de[ c pos ]; diff --git a/Task/Palindrome-dates/Ada/palindrome-dates.ada b/Task/Palindrome-dates/Ada/palindrome-dates.adb similarity index 100% rename from Task/Palindrome-dates/Ada/palindrome-dates.ada rename to Task/Palindrome-dates/Ada/palindrome-dates.adb diff --git a/Task/Palindrome-dates/Crystal/palindrome-dates.cr b/Task/Palindrome-dates/Crystal/palindrome-dates.cr new file mode 100644 index 0000000000..db0ab62c82 --- /dev/null +++ b/Task/Palindrome-dates/Crystal/palindrome-dates.cr @@ -0,0 +1,10 @@ +count = 0 +(2020..).each do |year| + digits = year.digits + month = digits[0]*10 + digits[1] + next unless 1 <= month <= 12 + day = digits[2]*10 + digits[3] + next unless 1 <= day <= Time.days_in_month(year, month) + puts "%4d-%02d-%02d" % {year, month, day} + break if (count += 1) == 15 +end diff --git a/Task/Palindrome-dates/Delphi/palindrome-dates.delphi b/Task/Palindrome-dates/Delphi/palindrome-dates.pas similarity index 100% rename from Task/Palindrome-dates/Delphi/palindrome-dates.delphi rename to Task/Palindrome-dates/Delphi/palindrome-dates.pas diff --git a/Task/Palindrome-dates/Fortran/palindrome-dates.f b/Task/Palindrome-dates/Fortran/palindrome-dates.f new file mode 100644 index 0000000000..43f7a8037d --- /dev/null +++ b/Task/Palindrome-dates/Fortran/palindrome-dates.f @@ -0,0 +1,109 @@ +! +! Palindrome dates +! tested with Intel ifx (IFX) 2025.2.1 20250806 on Kubuntu 26.04 +! GNU gfortran (Ubuntu 15.2.0-16ubuntu1) 15.2.0 on Kubuntu 26.04 +! VSI Fortran x86-64 V8.7-001 on OpenVMS V9.2-3 +! U.B., April 2026 +! +program PalindromeDates +implicit none + +integer :: yyyy, mm, dd +integer :: nPals=0 + +yyyy=2030 ! Start value, for 1st palindromic date after 2020-02-02 + +do while (nPals .lt. 15 .and. yyyy .lt. 10000) ! year 10000 would produce run-time error + call yyyytommdd (yyyy,mm,dd) ! calculate mm,dd from yyyy so that yyyymmdd is a palindrome + if (isPlausibleDate (yyyy,mm,dd)) then ! exclude invalid dates such as 2031-13-02 or 4321-12-34 + write (*, '(I4,"-",i2.2,"-",i2.2)') yyyy,mm,dd ! print the rest: valid palindromic dates + nPals = nPals + 1 ! Count valid palindromic dates + end if + yyyy = yyyy+1 ! Try again next year +enddo + +contains + + +! ========================================= +! Decide if a given date Y-m-d is plausible +! ========================================= +function isPlausibleDate (y,m,d) result (YN) +integer, intent(in) :: y,m,d +logical :: YN + +! Max number of Days in each month, Feb is 29 in leap years only. +integer, dimension(12),parameter :: nDays =[31,29,31,30,31,30,31,31,30,31,30,31] + +YN = .false. + +if (m .lt. 1 .or. m .gt. 12) then ! Impossible Month + return ! Early return .false. +endif + +if (d .lt. 1 .or. d .gt. nDays(m)) then ! Impossible day + return ! Early return .false. +endif + +! Special case: feb-29 +if (m .eq. 2 .and. d .eq. 29) then ! 20-Feb: only OK if Y is a leap year + ! Check for leap year + if (isLeapYear (y)) then + YN = .true. ! in a leap year, Feb 29 is correct date + else + return ! Early return .false. + endif +endif +! +! Any date not excluded by now is plausible. +! +YN = .true. + +end function isPlausibleDate + + +! =============================== +! Decide if year y is a leap year +! =============================== +function isLeapYear (y) result (YN) +integer, intent(in) :: y +logical :: YN +! +! Rule: A year is a leap year if it is divisible by 4, +! unless it is divisible by 100 but not by 400. +! e.g. 1900 is NOT a leap year +YN = (mod (y, 4) .eq. 0 .and. (mod(y, 400) .eq. 0 .or. mod(y, 100) .ne. 0)) + +end function isLeapYear + +! ===================================================================== +! calculate month m,day d from year y so that yyyymmdd is a palindrome +! ===================================================================== +subroutine yyyytommdd (y,m,d) +integer, intent(in) :: y +integer, intent(out) :: m,d + +character(len=4) strYear, raeYrts + + +write (strYear, '(i4)') y ! Convert integer Year to string +raeYrts = reverse (strYear) ! reverse order of characters in strYear so that strYearraeYrts is palindrome +read (raeYrts, '(i2,i2)') m, d ! extract integer month m and day d from reversed year + +end subroutine yyyytommdd + +! ========================================================================== +! return a 4-letter string in the reverse order of its letters: abcd -> dcba +! ========================================================================== +function reverse (chr) result(rhc) +character (len=4), intent(in) :: chr +character (len=4) :: rhc +integer :: ii + +do ii=1, 4 + rhc(ii:ii) = chr (5-ii:5-ii) +enddo + +end function reverse + +end program PalindromeDates diff --git a/Task/Palindrome-dates/Frink/palindrome-dates.frink b/Task/Palindrome-dates/Frink/palindrome-dates.frink new file mode 100644 index 0000000000..9da82e7fe6 --- /dev/null +++ b/Task/Palindrome-dates/Frink/palindrome-dates.frink @@ -0,0 +1,13 @@ +d = #2020-02-02 12:00# +count = 0 + +do +{ + d = d + 1 day + str = (d -> ### yyyyMMdd ###) + if str == reverse[str] + { + println[d -> ### yyyy-MM-dd ###] + count = count + 1 + } +} until count == 15 diff --git a/Task/Palindrome-dates/FutureBasic/palindrome-dates.basic b/Task/Palindrome-dates/FutureBasic/palindrome-dates.basic new file mode 100644 index 0000000000..109cff9e12 --- /dev/null +++ b/Task/Palindrome-dates/FutureBasic/palindrome-dates.basic @@ -0,0 +1,30 @@ +BOOL local fn IsPalindrome( string as CFStringRef ) + CFMutableStringRef tempString = fn MutableStringNew + for long i = len(string) - 1 to 0 step -1 + MutableStringAppendString( tempString, mid(string,i,1) ) + next +end fn = fn StringIsEqual( string, tempString ) + +void local fn DoIt + DateFormatterRef format = fn DateFormatterInit + DateFormatterSetDateFormat( format, @"yyyyMMdd" ) + + DateFormatterRef outputFormat = fn DateFormatterInit + DateFormatterSetDateFormat( outputFormat, @"yyyy-MM-dd" ) + + long count = 0, limit = 15 + CFCalendarRef calendar = fn CalendarCurrent + CFDateRef dt = fn DateInit + + while ( count < limit ) + if ( fn IsPalindrome( fn DateFormatterStringFromDate( format, dt ) ) ) + print fn DateFormatterStringFromDate( outputFormat, dt ) + count ++ + end if + dt = fn CalendarDateByAddingUnit( calendar, NSCalendarUnitDay, 1, dt, 0 ) + wend +end fn + +fn DoIt + +HandleEvents diff --git a/Task/Palindrome-dates/Julia/palindrome-dates.julia b/Task/Palindrome-dates/Julia/palindrome-dates.jl similarity index 100% rename from Task/Palindrome-dates/Julia/palindrome-dates.julia rename to Task/Palindrome-dates/Julia/palindrome-dates.jl diff --git a/Task/Palindrome-dates/PascalABC.NET/palindrome-dates.pas b/Task/Palindrome-dates/PascalABC.NET/palindrome-dates.pas new file mode 100644 index 0000000000..85480628cb --- /dev/null +++ b/Task/Palindrome-dates/PascalABC.NET/palindrome-dates.pas @@ -0,0 +1,23 @@ +uses system; + +function Reverse(x: integer) := x mod 10 * 10 + x div 10; + +function IsValidDate(y, m, d: integer; var date: datetime) := + DateTime.TryParse(y.tostring + '-' + m.tostring + '-' + d.tostring, date); + +function PalindromicDates(startYear: integer): sequence of datetime; +begin + var y := startyear; + repeat + var m := Reverse(y mod 100); + var d := Reverse(y div 100); + var date: datetime; + if (IsValidDate(y, m, d, date)) then yield date; + y += 1; + until false; +end; + +begin + foreach var date in PalindromicDates(2021).Take(15) do + Writeln(date.ToString('yyyy-MM-dd')); +end. diff --git a/Task/Palindrome-dates/Rust/palindrome-dates.rs b/Task/Palindrome-dates/Rust/palindrome-dates.rs new file mode 100644 index 0000000000..b846c9093a --- /dev/null +++ b/Task/Palindrome-dates/Rust/palindrome-dates.rs @@ -0,0 +1,18 @@ +// [dependencies] +// chrono = "0.4.44" + +fn is_palindrome(s: &str) -> bool { + s.chars().rev().eq(s.chars()) +} + +fn main() { + let mut date = chrono::Utc::now().date_naive(); + let mut count = 0; + while count < 15 { + if is_palindrome(&date.format("%Y%m%d").to_string()) { + println!("{}", date.format("%F")); + count += 1; + } + date = date.succ_opt().unwrap(); + } +} diff --git a/Task/Palindrome-dates/Rust/palindrome-dates.rust b/Task/Palindrome-dates/Rust/palindrome-dates.rust deleted file mode 100644 index a46f0eca33..0000000000 --- a/Task/Palindrome-dates/Rust/palindrome-dates.rust +++ /dev/null @@ -1,18 +0,0 @@ -// [dependencies] -// chrono = "0.4" - -fn is_palindrome(s: &str) -> bool { - s.chars().rev().eq(s.chars()) -} - -fn main() { - let mut date = chrono::Utc::today(); - let mut count = 0; - while count < 15 { - if is_palindrome(&date.format("%Y%m%d").to_string()) { - println!("{}", date.format("%F")); - count += 1; - } - date = date.succ(); - } -} diff --git a/Task/Palindrome-dates/V-(Vlang)/palindrome-dates.v b/Task/Palindrome-dates/V-(Vlang)/palindrome-dates.v new file mode 100644 index 0000000000..82b54dd940 --- /dev/null +++ b/Task/Palindrome-dates/V-(Vlang)/palindrome-dates.v @@ -0,0 +1,21 @@ +import time + +fn is_palindrome(sg string) bool { + return sg == sg.reverse() +} + +fn main() { + limit := 15 + mut dt, mut num := 0, 0 + println("First 15 palindromic dates:\n") + for num < limit { + dt++ + date := time.now().add_days(dt) + new_date := "${date.year:04}${date.month:02}${date.day:02}" + new_date_2 := "${date.year:04}-${date.month:02}-${date.day:02}" + if is_palindrome(new_date) { + num++ + println(new_date_2) + } + } +} diff --git a/Task/Palindrome-detection/00-TASK.txt b/Task/Palindrome-detection/00-TASK.txt index 8b3f9c2a64..49a64d686a 100644 --- a/Task/Palindrome-detection/00-TASK.txt +++ b/Task/Palindrome-detection/00-TASK.txt @@ -1,6 +1,6 @@ A [[wp:Palindrome|palindrome]] is a phrase which reads the same backward and forward. -{{task heading}} +{{task heading|Task}} Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. diff --git a/Task/Palindrome-detection/ALGOL-68/palindrome-detection.alg b/Task/Palindrome-detection/ALGOL-68/palindrome-detection.alg index 0d7bcdafa8..4b9af86f42 100644 --- a/Task/Palindrome-detection/ALGOL-68/palindrome-detection.alg +++ b/Task/Palindrome-detection/ALGOL-68/palindrome-detection.alg @@ -2,8 +2,8 @@ PROC palindrome = (STRING s)BOOL:( FOR i TO UPB s OVER 2 DO IF s[i] /= s[UPB s-i+1] THEN GO TO return false FI - OD;Power - else: TRUE EXIT + OD; + TRUE EXIT return false: FALSE ); @@ -16,7 +16,6 @@ PROC palindrome r = (STRING s)BOOL: ; # Test # -main: ( STRING t = "ingirumimusnocteetconsumimurigni"; FORMAT template = $"sequence """g""" "b("is","isnt")" a palindrome"l$; diff --git a/Task/Palindrome-detection/Ada/palindrome-detection-1.ada b/Task/Palindrome-detection/Ada/palindrome-detection-1.adb similarity index 100% rename from Task/Palindrome-detection/Ada/palindrome-detection-1.ada rename to Task/Palindrome-detection/Ada/palindrome-detection-1.adb diff --git a/Task/Palindrome-detection/Ada/palindrome-detection-2.ada b/Task/Palindrome-detection/Ada/palindrome-detection-2.adb similarity index 100% rename from Task/Palindrome-detection/Ada/palindrome-detection-2.ada rename to Task/Palindrome-detection/Ada/palindrome-detection-2.adb diff --git a/Task/Palindrome-detection/AutoIt/palindrome-detection-1.autoit b/Task/Palindrome-detection/AutoIt/palindrome-detection-1.au3 similarity index 100% rename from Task/Palindrome-detection/AutoIt/palindrome-detection-1.autoit rename to Task/Palindrome-detection/AutoIt/palindrome-detection-1.au3 diff --git a/Task/Palindrome-detection/AutoIt/palindrome-detection-2.autoit b/Task/Palindrome-detection/AutoIt/palindrome-detection-2.au3 similarity index 100% rename from Task/Palindrome-detection/AutoIt/palindrome-detection-2.autoit rename to Task/Palindrome-detection/AutoIt/palindrome-detection-2.au3 diff --git a/Task/Palindrome-detection/BASIC/palindrome-detection.basic b/Task/Palindrome-detection/BASIC/palindrome-detection.basic index e14e4f498a..c3d6779af0 100644 --- a/Task/Palindrome-detection/BASIC/palindrome-detection.basic +++ b/Task/Palindrome-detection/BASIC/palindrome-detection.basic @@ -68,7 +68,7 @@ END FUNCTION FUNCTION RvrsText$ (WhichText$) ' Var - DIM i%, c$, NewText$, j% + DIM i%, NewText$, j% j% = LEN(WhichText$) FOR i% = 1 TO j% diff --git a/Task/Palindrome-detection/Ballerina/palindrome-detection.ballerina b/Task/Palindrome-detection/Ballerina/palindrome-detection.ballerina new file mode 100644 index 0000000000..0d07e0709e --- /dev/null +++ b/Task/Palindrome-detection/Ballerina/palindrome-detection.ballerina @@ -0,0 +1,23 @@ +// https://rosettacode.org/wiki/Palindrome_detection +import ballerina/io; + +function reverse(string a) returns string { + string out = ""; + foreach string i in a { + out = string:concat(i, out); + } + return out; +} + +function isPalindrome(string s) returns boolean { + return s == reverse(s); +} + +# ------------------------ TEST ------------------------ + +public function main() { + string[] tests = ["rotor", "racecar", "level", "rosetta"]; + foreach string s in tests { + io:println(isPalindrome(s)); + } +} diff --git a/Task/Palindrome-detection/COBOL/palindrome-detection.cobol b/Task/Palindrome-detection/COBOL/palindrome-detection.cob similarity index 100% rename from Task/Palindrome-detection/COBOL/palindrome-detection.cobol rename to Task/Palindrome-detection/COBOL/palindrome-detection.cob diff --git a/Task/Palindrome-detection/Crystal/palindrome-detection-1.crystal b/Task/Palindrome-detection/Crystal/palindrome-detection-1.cr similarity index 100% rename from Task/Palindrome-detection/Crystal/palindrome-detection-1.crystal rename to Task/Palindrome-detection/Crystal/palindrome-detection-1.cr diff --git a/Task/Palindrome-detection/Crystal/palindrome-detection-2.crystal b/Task/Palindrome-detection/Crystal/palindrome-detection-2.cr similarity index 100% rename from Task/Palindrome-detection/Crystal/palindrome-detection-2.crystal rename to Task/Palindrome-detection/Crystal/palindrome-detection-2.cr diff --git a/Task/Palindrome-detection/Crystal/palindrome-detection-3.crystal b/Task/Palindrome-detection/Crystal/palindrome-detection-3.cr similarity index 100% rename from Task/Palindrome-detection/Crystal/palindrome-detection-3.crystal rename to Task/Palindrome-detection/Crystal/palindrome-detection-3.cr diff --git a/Task/Palindrome-detection/Crystal/palindrome-detection-4.crystal b/Task/Palindrome-detection/Crystal/palindrome-detection-4.cr similarity index 100% rename from Task/Palindrome-detection/Crystal/palindrome-detection-4.crystal rename to Task/Palindrome-detection/Crystal/palindrome-detection-4.cr diff --git a/Task/Palindrome-detection/Delphi/palindrome-detection.delphi b/Task/Palindrome-detection/Delphi/palindrome-detection.pas similarity index 100% rename from Task/Palindrome-detection/Delphi/palindrome-detection.delphi rename to Task/Palindrome-detection/Delphi/palindrome-detection.pas diff --git a/Task/Palindrome-detection/DuckDB/palindrome-detection.duckdb b/Task/Palindrome-detection/DuckDB/palindrome-detection.duckdb new file mode 100644 index 0000000000..848be022a3 --- /dev/null +++ b/Task/Palindrome-detection/DuckDB/palindrome-detection.duckdb @@ -0,0 +1,31 @@ +# One way to create a reference to a string literal is by defining a DuckDB function: +D create or replace function s() as (select 'In girum imus nocte et consumimur igni'); + +D select reverse(s()); +┌────────────────────────────────────────┐ +│ reverse(s()) │ +│ varchar │ +├────────────────────────────────────────┤ +│ ingi rumimusnoc te etcon sumi murig nI │ +└────────────────────────────────────────┘ + +D create or replace function isPalindrome(s) as (SELECT REVERSE(s) = s); + +D select isPalindrome('pip'); +┌─────────────────────┐ +│ ispalindrome('pip') │ +│ boolean │ +├─────────────────────┤ +│ true │ +└─────────────────────┘ + +D create or replace function isQuasiPalindrome(str) as + (isPalindrome( (select regexp_replace(str, ' ', '', 'g')) )); + +D select isQuasiPalindrome('to be bot'); +┌────────────────────────────────┐ +│ isquasipalindrome('to be bot') │ +│ boolean │ +├────────────────────────────────┤ +│ true │ +└────────────────────────────────┘ diff --git a/Task/Palindrome-detection/EasyLang/palindrome-detection.easy b/Task/Palindrome-detection/EasyLang/palindrome-detection.easy index 5a80f5f29d..fa6af77dde 100644 --- a/Task/Palindrome-detection/EasyLang/palindrome-detection.easy +++ b/Task/Palindrome-detection/EasyLang/palindrome-detection.easy @@ -3,7 +3,7 @@ func$ reverse s$ . for i = 1 to len a$[] div 2 swap a$[i] a$[len a$[] - i + 1] . - return strjoin a$[] + return strjoin a$[] "" . func palin s$ . if s$ = reverse s$ diff --git a/Task/Palindrome-detection/Ed/palindrome-detection.ed b/Task/Palindrome-detection/Ed/palindrome-detection.ed new file mode 100644 index 0000000000..e14fb71ce4 --- /dev/null +++ b/Task/Palindrome-detection/Ed/palindrome-detection.ed @@ -0,0 +1,19 @@ +# by Artyom Bologov +H +,p +g/^(.)(.*)\1$/s//\2/ +g/^(.)(.*)\1$/s//\2/ +g/^(.)(.*)\1$/s//\2/ +g/^(.)(.*)\1$/s//\2/ +g/^(.)(.*)\1$/s//\2/ +g/^(.)(.*)\1$/s//\2/ +g/^(.)(.*)\1$/s//\2/ +g/^(.)(.*)\1$/s//\2/ +g/^(.)(.*)\1$/s//\2/ +g/^(.)(.*)\1$/s//\2/ +g/^(.)(.*)\1$/s//\2/ +g/^(.)(.*)\1$/s//\2/ +v/^(.)(.+)\1$|^.?$/s/.*/Not a palindrome!/ +g/^.?$/s//Palindrome!/ +,p +Q diff --git a/Task/Palindrome-detection/Elixir/palindrome-detection.elixir b/Task/Palindrome-detection/Elixir/palindrome-detection.ex similarity index 100% rename from Task/Palindrome-detection/Elixir/palindrome-detection.elixir rename to Task/Palindrome-detection/Elixir/palindrome-detection.ex diff --git a/Task/Palindrome-detection/Emacs-Lisp/palindrome-detection.l b/Task/Palindrome-detection/Emacs-Lisp/palindrome-detection-1.el similarity index 100% rename from Task/Palindrome-detection/Emacs-Lisp/palindrome-detection.l rename to Task/Palindrome-detection/Emacs-Lisp/palindrome-detection-1.el diff --git a/Task/Palindrome-detection/Emacs-Lisp/palindrome-detection-2.el b/Task/Palindrome-detection/Emacs-Lisp/palindrome-detection-2.el new file mode 100644 index 0000000000..3552743a85 --- /dev/null +++ b/Task/Palindrome-detection/Emacs-Lisp/palindrome-detection-2.el @@ -0,0 +1,3 @@ +(defun test-if-palindrome (text) + (setq text (replace-regexp-in-string "[[:space:][:punct:]]" "" text)) ; remove spaces and punctuation, by replacing them with nothing + (string-equal-ignore-case text (reverse text))) ; ignore case when looking at reversed text diff --git a/Task/Palindrome-detection/Euphoria/palindrome-detection-1.euphoria b/Task/Palindrome-detection/Euphoria/palindrome-detection-1.eu similarity index 100% rename from Task/Palindrome-detection/Euphoria/palindrome-detection-1.euphoria rename to Task/Palindrome-detection/Euphoria/palindrome-detection-1.eu diff --git a/Task/Palindrome-detection/Euphoria/palindrome-detection-2.euphoria b/Task/Palindrome-detection/Euphoria/palindrome-detection-2.eu similarity index 100% rename from Task/Palindrome-detection/Euphoria/palindrome-detection-2.euphoria rename to Task/Palindrome-detection/Euphoria/palindrome-detection-2.eu diff --git a/Task/Palindrome-detection/Golfscript/palindrome-detection-2.golf b/Task/Palindrome-detection/Golfscript/palindrome-detection-2.golf index 64bf7cf402..58cdea2875 100644 --- a/Task/Palindrome-detection/Golfscript/palindrome-detection-2.golf +++ b/Task/Palindrome-detection/Golfscript/palindrome-detection-2.golf @@ -1,4 +1,3 @@ -"ABBA" pal -"a" pal -"13231+464+989=989+464+13231" pal -"123 456 789 897 654 321" pal +["ABBA" "a" +"13231+464+989=989+464+13231" +"123 456 789 897 654 321"]{pal puts}/ diff --git a/Task/Palindrome-detection/Idris/palindrome-detection-1.idris b/Task/Palindrome-detection/Idris/palindrome-detection-1.idris new file mode 100644 index 0000000000..3dbcc99256 --- /dev/null +++ b/Task/Palindrome-detection/Idris/palindrome-detection-1.idris @@ -0,0 +1,30 @@ +module Palindromes + +import Data.Primitives.Views +import Data.List +import Data.List.Views +import Data.Nat + +isPalindromeReverse : String -> Bool +isPalindromeReverse str = let cs = unpack str in cs == reverse cs + +isPalindromeReverseHalf : String -> Bool +isPalindromeReverseHalf str = + let cs = (unpack str) + n = (length str) `div` 2 + in take n cs == (take n $ reverse cs) + +isPalindromeSplit : String -> Bool +isPalindromeSplit str = + let cs = unpack str + n = length cs `div` 2 + (left, right) = bimap id reverse $ splitAt n cs + in all (uncurry (==)) $ zip left right + +isPalindromeSnoc : String -> Bool +isPalindromeSnoc str = + let cs = unpack str in go cs + where go : Eq a => List a -> Bool + go xs with (snocList xs) + go (x :: ys ++ [z]) | Snoc z (x::ys) _ = x == z && go ys + go _ | _ = True diff --git a/Task/Palindrome-detection/Idris/palindrome-detection-2.idris b/Task/Palindrome-detection/Idris/palindrome-detection-2.idris new file mode 100644 index 0000000000..734cb00569 --- /dev/null +++ b/Task/Palindrome-detection/Idris/palindrome-detection-2.idris @@ -0,0 +1,58 @@ +module PalindromesTypeLevel + +import Data.List +import Data.List.Views + + +isPalindromeDirect : (str : String) -> (str = reverse str) => Bool +isPalindromeDirect _ = True + +ipd = isPalindromeDirect "AABBAA" + +failing + ipdf = isPalindromeDirect "ABCCBB" + + +||| Proof that the list is constructed of consecutive pairs of equal elements. +||| Last element can be unpaired. +data EqualPairsInList : List a -> Type where + Nil : EqualPairsInList [] + Single : EqualPairsInList [x] + EqualPair : EqualPairsInList xs -> EqualPairsInList (x :: x :: xs) + +||| Reorders the list so that the first half is interleaved with a reversed second half. +interleaveOwnHalfReverse : List a -> List a +interleaveOwnHalfReverse [] = [] +interleaveOwnHalfReverse [x] = [x] +interleaveOwnHalfReverse (x :: y :: ys) = let (z, zs) = splitLast (y::ys) in x :: z :: interleaveOwnHalfReverse zs + where splitLast : (xs : List a) -> NonEmpty xs => (a, List a) + splitLast [x] = (x, []) + splitLast (x :: y :: ys) = let (z, zs) = splitLast (y::ys) in (z, x::zs) + +||| Precondition for checking if a list is a palindrome. +IsPalindrome : List a -> Type +IsPalindrome = EqualPairsInList . interleaveOwnHalfReverse + +||| Function for testing palindromes. Typechecks only when applied to a palindrome list. +isPalindrome : (xs : List a) -> IsPalindrome xs => Bool +isPalindrome _ = True + +||| Palindrome precondition specialized for strings. +IsPalindromeStr : String -> Type +IsPalindromeStr = IsPalindrome . unpack + +||| Function for testing string palindromes. Typechecks only when applied to a palindrome list. +isPalindromeStr : (str : String) -> IsPalindromeStr str => Bool +isPalindromeStr _ = True + + +-- Tests + +ip = isPalindrome [1, 4, 3, 1, 1, 3, 4, 1] +ips = isPalindromeStr "ABCDCBA" + +failing + ipf = isPalindrome [2, 2, 2, 3, 2, 2] + +failing + ipsf = isPalindromeStr "RBCDCBA" diff --git a/Task/Palindrome-detection/J/palindrome-detection-3.j b/Task/Palindrome-detection/J/palindrome-detection-3.j index 12b980a3df..f7c7420e35 100644 --- a/Task/Palindrome-detection/J/palindrome-detection-3.j +++ b/Task/Palindrome-detection/J/palindrome-detection-3.j @@ -1,6 +1,5 @@ -isPalin1=: 0:`($:@(}.@}:))@.({.={:)`1:@.(1>:#) - -isPalin2=: monad define - if. 1>:#y do. 1 return. end. - if. ({.={:)y do. isPalin2 }.}:y else. 0 end. -) + inexact=: [: (-:|.)@tolower [ ([-.-.) a. {~ 65 97 +"0 _ i.@26 + inexact 'A man, a plan, a canal: Panama!' +1 + inexact 'Not palindrome...' +0 diff --git a/Task/Palindrome-detection/J/palindrome-detection-4.j b/Task/Palindrome-detection/J/palindrome-detection-4.j index 0ab78f3f7c..05a202f630 100644 --- a/Task/Palindrome-detection/J/palindrome-detection-4.j +++ b/Task/Palindrome-detection/J/palindrome-detection-4.j @@ -1,12 +1,6 @@ - foo=: foo,|.foo=:2000$a. - ts=:6!:2,7!:2 NB. time and space required to execute sentence - ts 'isPalin0 foo' -2.73778e_5 5184 - ts 'isPalin1 foo' -0.0306667 6.0368e6 - ts 'isPalin2 foo' -0.104391 1.37965e7 - 'isPalin1 foo' %&ts 'isPalin0 foo' -1599.09 1164.23 - 'isPalin2 foo' %&ts 'isPalin0 foo' -3967.53 2627.04 +isPalin1=: 0:`($:@}.@}:)@.({.={:)`1:@.(1>:#) + +isPalin2=: monad define + if. 1>:#y do. 1 return. end. + if. ({.={:)y do. isPalin2 }.}:y else. 0 end. +) diff --git a/Task/Palindrome-detection/J/palindrome-detection-5.j b/Task/Palindrome-detection/J/palindrome-detection-5.j new file mode 100644 index 0000000000..0ab78f3f7c --- /dev/null +++ b/Task/Palindrome-detection/J/palindrome-detection-5.j @@ -0,0 +1,12 @@ + foo=: foo,|.foo=:2000$a. + ts=:6!:2,7!:2 NB. time and space required to execute sentence + ts 'isPalin0 foo' +2.73778e_5 5184 + ts 'isPalin1 foo' +0.0306667 6.0368e6 + ts 'isPalin2 foo' +0.104391 1.37965e7 + 'isPalin1 foo' %&ts 'isPalin0 foo' +1599.09 1164.23 + 'isPalin2 foo' %&ts 'isPalin0 foo' +3967.53 2627.04 diff --git a/Task/Palindrome-detection/Julia/palindrome-detection-1.julia b/Task/Palindrome-detection/Julia/palindrome-detection-1.jl similarity index 100% rename from Task/Palindrome-detection/Julia/palindrome-detection-1.julia rename to Task/Palindrome-detection/Julia/palindrome-detection-1.jl diff --git a/Task/Palindrome-detection/Julia/palindrome-detection-2.julia b/Task/Palindrome-detection/Julia/palindrome-detection-2.jl similarity index 100% rename from Task/Palindrome-detection/Julia/palindrome-detection-2.julia rename to Task/Palindrome-detection/Julia/palindrome-detection-2.jl diff --git a/Task/Palindrome-detection/Julia/palindrome-detection-3.julia b/Task/Palindrome-detection/Julia/palindrome-detection-3.jl similarity index 100% rename from Task/Palindrome-detection/Julia/palindrome-detection-3.julia rename to Task/Palindrome-detection/Julia/palindrome-detection-3.jl diff --git a/Task/Palindrome-detection/Kotlin/palindrome-detection.kotlin b/Task/Palindrome-detection/Kotlin/palindrome-detection.kts similarity index 100% rename from Task/Palindrome-detection/Kotlin/palindrome-detection.kotlin rename to Task/Palindrome-detection/Kotlin/palindrome-detection.kts diff --git a/Task/Palindrome-detection/Langur/palindrome-detection.langur b/Task/Palindrome-detection/Langur/palindrome-detection.langur index 773106d936..a1e0565563 100644 --- a/Task/Palindrome-detection/Langur/palindrome-detection.langur +++ b/Task/Palindrome-detection/Langur/palindrome-detection.langur @@ -1,6 +1,6 @@ -val .ispal = fn(.s) len(.s) > 0 and .s == reverse .s +val ispal = fn(s string) { len(s) > 0 and s == reverse(s) } -val .tests = h{ +val tests = { "": false, "z": true, "aha": true, @@ -17,7 +17,7 @@ val .tests = h{ "ingirumimusnocteetconsumimurigni": true, } -for .word in sort(keys .tests) { - val .foundpal = .ispal(.word) - writeln .word, ": ", .foundpal, if(.foundpal == .tests[.word]: ""; " (FAILED TEST)") +for word in sort(keys(tests)) { + val foundpal = ispal(word) + writeln word, ": ", foundpal, if(foundpal == tests[word]: ""; " (FAILED TEST)") } diff --git a/Task/Palindrome-detection/OCaml/palindrome-detection-1.ocaml b/Task/Palindrome-detection/OCaml/palindrome-detection-1.ml similarity index 100% rename from Task/Palindrome-detection/OCaml/palindrome-detection-1.ocaml rename to Task/Palindrome-detection/OCaml/palindrome-detection-1.ml diff --git a/Task/Palindrome-detection/OCaml/palindrome-detection-2.ocaml b/Task/Palindrome-detection/OCaml/palindrome-detection-2.ml similarity index 100% rename from Task/Palindrome-detection/OCaml/palindrome-detection-2.ocaml rename to Task/Palindrome-detection/OCaml/palindrome-detection-2.ml diff --git a/Task/Palindrome-detection/PascalABC.NET/palindrome-detection.pas b/Task/Palindrome-detection/PascalABC.NET/palindrome-detection.pas new file mode 100644 index 0000000000..aa5517edde --- /dev/null +++ b/Task/Palindrome-detection/PascalABC.NET/palindrome-detection.pas @@ -0,0 +1,6 @@ +function IsPalindrome(s: string) := s = s[::-1]; + +begin + Println(IsPalindrome('arozaupalanalapuazora')); + Println(IsPalindrome('abcd')); +end. diff --git a/Task/Palindrome-detection/Pluto/palindrome-detection.pluto b/Task/Palindrome-detection/Pluto/palindrome-detection.pluto new file mode 100644 index 0000000000..71143fae81 --- /dev/null +++ b/Task/Palindrome-detection/Pluto/palindrome-detection.pluto @@ -0,0 +1,7 @@ +function is_palindrome(s) + return s == s:reverse() +end + +print(is_palindrome('rotor')) +print(is_palindrome('racecar')) +print(is_palindrome('rosetta')) diff --git a/Task/Palindrome-detection/PowerShell/palindrome-detection-1.psh b/Task/Palindrome-detection/PowerShell/palindrome-detection-1.ps1 similarity index 100% rename from Task/Palindrome-detection/PowerShell/palindrome-detection-1.psh rename to Task/Palindrome-detection/PowerShell/palindrome-detection-1.ps1 diff --git a/Task/Palindrome-detection/PowerShell/palindrome-detection-2.psh b/Task/Palindrome-detection/PowerShell/palindrome-detection-2.ps1 similarity index 100% rename from Task/Palindrome-detection/PowerShell/palindrome-detection-2.psh rename to Task/Palindrome-detection/PowerShell/palindrome-detection-2.ps1 diff --git a/Task/Palindrome-detection/PowerShell/palindrome-detection-3.psh b/Task/Palindrome-detection/PowerShell/palindrome-detection-3.ps1 similarity index 100% rename from Task/Palindrome-detection/PowerShell/palindrome-detection-3.psh rename to Task/Palindrome-detection/PowerShell/palindrome-detection-3.ps1 diff --git a/Task/Palindrome-detection/PowerShell/palindrome-detection-4.psh b/Task/Palindrome-detection/PowerShell/palindrome-detection-4.ps1 similarity index 100% rename from Task/Palindrome-detection/PowerShell/palindrome-detection-4.psh rename to Task/Palindrome-detection/PowerShell/palindrome-detection-4.ps1 diff --git a/Task/Palindrome-detection/PowerShell/palindrome-detection-5.psh b/Task/Palindrome-detection/PowerShell/palindrome-detection-5.ps1 similarity index 100% rename from Task/Palindrome-detection/PowerShell/palindrome-detection-5.psh rename to Task/Palindrome-detection/PowerShell/palindrome-detection-5.ps1 diff --git a/Task/Palindrome-detection/PowerShell/palindrome-detection-6.psh b/Task/Palindrome-detection/PowerShell/palindrome-detection-6.ps1 similarity index 100% rename from Task/Palindrome-detection/PowerShell/palindrome-detection-6.psh rename to Task/Palindrome-detection/PowerShell/palindrome-detection-6.ps1 diff --git a/Task/Palindrome-detection/REBOL/palindrome-detection.rebol b/Task/Palindrome-detection/REBOL/palindrome-detection.rebol deleted file mode 100644 index 6202253550..0000000000 --- a/Task/Palindrome-detection/REBOL/palindrome-detection.rebol +++ /dev/null @@ -1,29 +0,0 @@ -REBOL [ - Title: "Palindrome Recognizer" - URL: http://rosettacode.org/wiki/Palindrome -] - -; In order to compete with all the one-liners, the operation is -; compressed: parens force left hand side to evaluate first, where I -; copy the phrase, then uppercase it and assign it to 'p'. Now the -; right hand side is evaluated: p is copied, then reversed in place; -; the comparison is made and implicitely returned. - -palindrome?: func [ - phrase [string!] "Potentially palindromatic prose." - /local p -][(p: uppercase copy phrase) = reverse copy p] - -; Teeny Tiny Test Suite - -assert: func [code][print [either do code [" ok"]["FAIL"] mold code]] - -print "Simple palindromes, with an exception for variety:" -repeat phrase ["z" "aha" "sees" "oofoe" "Deified"][ - assert compose [palindrome? (phrase)]] - -print [crlf "According to the problem statement, these should fail:"] -assert [palindrome? "A man, a plan, a canal, Panama."] ; Punctuation not ignored. -assert [palindrome? "In girum imus nocte et consumimur igni"] ; Spaces not removed. - -; I know we're doing palindromes, not alliteration, but who could resist...? diff --git a/Task/Palindrome-detection/Rebol/palindrome-detection-1.rebol b/Task/Palindrome-detection/Rebol/palindrome-detection-1.rebol new file mode 100644 index 0000000000..d891c7eda6 --- /dev/null +++ b/Task/Palindrome-detection/Rebol/palindrome-detection-1.rebol @@ -0,0 +1 @@ +palindrome?: func [phrase [string!][phrase == reverse copy phrase] diff --git a/Task/Palindrome-detection/Rebol/palindrome-detection-2.rebol b/Task/Palindrome-detection/Rebol/palindrome-detection-2.rebol new file mode 100644 index 0000000000..229166e075 --- /dev/null +++ b/Task/Palindrome-detection/Rebol/palindrome-detection-2.rebol @@ -0,0 +1,41 @@ +palindrome?: func [ + phrase [string!] "Potentially palindromatic prose." + /case "Case-sensitive comparison" +][ either case [ + phrase == reverse copy phrase + ][ phrase = reverse copy phrase] +] +inexact-palindrome?: func [ + phrase [string!] "Potentially palindromatic prose." + /ignore ignored +][ + if palindrome?/case phrase [return true] + unless ignored [ + ignored: charset " ^-.,-/" + ] + all [ + ;; Remove ignored characters + phrase: copy phrase + parse phrase [any[ + to ignored + remove [some ignored] + ] to end] + palindrome? phrase + ] +] + +; Teeny Tiny Test Suite +assert: func [code][print [either do code [" ok"]["FAIL"] mold/flat code]] + +print "Simple palindromes, with an exception for variety:" +foreach phrase ["z" "aha" "sees" "oofoe" "Deified"][ + assert compose [palindrome? (phrase)]] + +print "Inexact palindromes:" +foreach phrase [ + "A man, a plan, a canal, Panama." + "In girum imus nocte et consumimur igni" + "Never odd or even" +][ + assert compose [inexact-palindrome? (phrase)] +] diff --git a/Task/Palindrome-detection/Refal/palindrome-detection.refal b/Task/Palindrome-detection/Refal/palindrome-detection.refal new file mode 100644 index 0000000000..de99d0945f --- /dev/null +++ b/Task/Palindrome-detection/Refal/palindrome-detection.refal @@ -0,0 +1,37 @@ +$ENTRY Go { + = + + + + + + + ; +}; + +Test { + e.W, : { + True s.1 = ; + s.1 True = ; + False False = ; + }; +}; + +InexactPalindrome { + e.W = >>; +}; + +Filter { + (e.Keep) = ; + (e.Keep) s.C e.W, e.Keep: { + e.1 s.C e.2 = s.C ; + e.1 = ; + }; +}; + +Palindrome { + = True; + s.C = True; + s.C e.W s.C = ; + e.X = False; +}; diff --git a/Task/Palindrome-detection/Run-BASIC/palindrome-detection.basic b/Task/Palindrome-detection/Run-BASIC/palindrome-detection.basic index d582d8c5b4..598fc4b60d 100644 --- a/Task/Palindrome-detection/Run-BASIC/palindrome-detection.basic +++ b/Task/Palindrome-detection/Run-BASIC/palindrome-detection.basic @@ -5,9 +5,10 @@ for i = 1 to 4 print w$;" is ";isPalindrome$(w$);" Palindrome" next -FUNCTION isPalindrome$(str$) -for i = 1 to len(str$) - a$ = upper$(mid$(str$,i,1)) - if (a$ >= "A" and a$ <= "Z") or (a$ >= "0" and a$ <= "9") then b$ = b$ + a$: c$ = a$ + c$ -next i -if b$ <> c$ then isPalindrome$ = "not" +function isPalindrome$(str$) + for i = 1 to len(str$) + a$ = upper$(mid$(str$,i,1)) + if (a$ >= "A" and a$ <= "Z") or (a$ >= "0" and a$ <= "9") then b$ = b$ + a$: c$ = a$ + c$ + next i + if b$ <> c$ then isPalindrome$ = "not" +end function diff --git a/Task/Palindrome-detection/Rust/palindrome-detection-1.rust b/Task/Palindrome-detection/Rust/palindrome-detection-1.rs similarity index 100% rename from Task/Palindrome-detection/Rust/palindrome-detection-1.rust rename to Task/Palindrome-detection/Rust/palindrome-detection-1.rs diff --git a/Task/Palindrome-detection/Rust/palindrome-detection-2.rust b/Task/Palindrome-detection/Rust/palindrome-detection-2.rs similarity index 100% rename from Task/Palindrome-detection/Rust/palindrome-detection-2.rust rename to Task/Palindrome-detection/Rust/palindrome-detection-2.rs diff --git a/Task/Palindrome-detection/Scheme/palindrome-detection-1.ss b/Task/Palindrome-detection/Scheme/palindrome-detection-1.scm similarity index 100% rename from Task/Palindrome-detection/Scheme/palindrome-detection-1.ss rename to Task/Palindrome-detection/Scheme/palindrome-detection-1.scm diff --git a/Task/Palindrome-detection/Scheme/palindrome-detection-2.ss b/Task/Palindrome-detection/Scheme/palindrome-detection-2.scm similarity index 100% rename from Task/Palindrome-detection/Scheme/palindrome-detection-2.ss rename to Task/Palindrome-detection/Scheme/palindrome-detection-2.scm diff --git a/Task/Palindrome-detection/Tailspin/palindrome-detection.tailspin b/Task/Palindrome-detection/Tailspin/palindrome-detection-1.tailspin similarity index 100% rename from Task/Palindrome-detection/Tailspin/palindrome-detection.tailspin rename to Task/Palindrome-detection/Tailspin/palindrome-detection-1.tailspin diff --git a/Task/Palindrome-detection/Tailspin/palindrome-detection-2.tailspin b/Task/Palindrome-detection/Tailspin/palindrome-detection-2.tailspin new file mode 100644 index 0000000000..03dc6f3f70 --- /dev/null +++ b/Task/Palindrome-detection/Tailspin/palindrome-detection-2.tailspin @@ -0,0 +1,6 @@ +palindrome templates + [$...] -> # ! + when <|=$(..:-1)> do '$...;' ! +end palindrome + +[['rotor', 'racecar', 'level', 'rosetta']... -> palindrome ] ! diff --git a/Task/Palindrome-detection/Uiua/palindrome-detection.uiua b/Task/Palindrome-detection/Uiua/palindrome-detection-1.uiua similarity index 100% rename from Task/Palindrome-detection/Uiua/palindrome-detection.uiua rename to Task/Palindrome-detection/Uiua/palindrome-detection-1.uiua diff --git a/Task/Palindrome-detection/Uiua/palindrome-detection-2.uiua b/Task/Palindrome-detection/Uiua/palindrome-detection-2.uiua new file mode 100644 index 0000000000..7cc2e9a004 --- /dev/null +++ b/Task/Palindrome-detection/Uiua/palindrome-detection-2.uiua @@ -0,0 +1,2 @@ +IsPal ← ≍⇌.+×32<@a.▽:⟜∊:/⊂+⊙¤"Aa"⇡26 +IsPal "A man, a plan, a canal: Panama!" diff --git a/Task/Palindrome-detection/VBScript/palindrome-detection-1.vb b/Task/Palindrome-detection/VBScript/palindrome-detection-1.vbs similarity index 100% rename from Task/Palindrome-detection/VBScript/palindrome-detection-1.vb rename to Task/Palindrome-detection/VBScript/palindrome-detection-1.vbs diff --git a/Task/Palindrome-detection/VBScript/palindrome-detection-2.vb b/Task/Palindrome-detection/VBScript/palindrome-detection-2.vbs similarity index 100% rename from Task/Palindrome-detection/VBScript/palindrome-detection-2.vb rename to Task/Palindrome-detection/VBScript/palindrome-detection-2.vbs diff --git a/Task/Palindrome-detection/YAMLScript/palindrome-detection.ys b/Task/Palindrome-detection/YAMLScript/palindrome-detection.ys new file mode 100644 index 0000000000..5faba4be6b --- /dev/null +++ b/Task/Palindrome-detection/YAMLScript/palindrome-detection.ys @@ -0,0 +1,5 @@ +!YS-v0 + +defn main(n=31337): + not =: when((n:S != n:S:reverse) ' not') + say: "$n is$not a palindrome." diff --git a/Task/Palindromic-gapful-numbers/00-TASK.txt b/Task/Palindromic-gapful-numbers/00-TASK.txt index d401c8ef20..c338f0e15b 100644 --- a/Task/Palindromic-gapful-numbers/00-TASK.txt +++ b/Task/Palindromic-gapful-numbers/00-TASK.txt @@ -1,24 +1,18 @@ -Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the -first and last digit are known as   '''gapful numbers'''. +For this task, a ''number'' is to be understood as a positive integer expressed in base ten, +and a ''palindromic'' number is one that is equal to the integer formed by reversing its decimal digits. +A number that is evenly divisible by the number formed by concatenating its +first and last digits in that order is known as a '''gapful number'''. +All one─ and two─digit numbers have this property and accordingly only +numbers greater than or equal to '''100''' should be considered for this Rosetta Code task. -''Evenly divisible''   means divisible with   no   remainder. - - -All   one─   and two─digit   numbers have this property and are trivially excluded.   Only -numbers   '''100'''   will be considered for this Rosetta Code task. - +(''Evenly divisible'' here means divisible with no remainder.) ;Example: '''1037'''   is a   '''gapful'''   number because it is evenly divisible by the number   '''17'''   which is formed by the first and last decimal digits of   '''1037'''. - -A palindromic number is   (for this task, a positive integer expressed in base ten),   when the number is -reversed,   is the same as the original number. - - ;Task: :*   Show   (nine sets)   the first   '''20'''   palindromic gapful numbers that   ''end''   with: :::*   the digit   '''1''' diff --git a/Task/Palindromic-gapful-numbers/Arturo/palindromic-gapful-numbers.arturo b/Task/Palindromic-gapful-numbers/Arturo/palindromic-gapful-numbers.arturo new file mode 100644 index 0000000000..0747d247aa --- /dev/null +++ b/Task/Palindromic-gapful-numbers/Arturo/palindromic-gapful-numbers.arturo @@ -0,0 +1,25 @@ +palindromic?: function [n][ + s = reverse s: <= to :string n +] + +gapful?: function [n][ + s: to :string n + divisor: to :integer (first s) ++ last s + 0 = n % divisor +] + +palindromicGapfuls: map 1..9 'd [ + select.first:100 range.step:10 100+d ∞ 'x -> + and? [palindromic? x][gapful? x] +] + +print "First 20 palindromic gapful numbers ending with:" +print repeat "=" 65 +loop 1..9 'd -> + print [d ":", join.with:" " to [:string] first.n:20 palindromicGapfuls\[d-1]] + +print "" +print "Last 15 of first 100 palindromic gapful numbers ending with:" +print repeat "=" 65 +loop 1..9 'd -> + print [d ":", join.with:" " to [:string] last.n:15 palindromicGapfuls\[d-1]] diff --git a/Task/Palindromic-gapful-numbers/Crystal/palindromic-gapful-numbers-1.crystal b/Task/Palindromic-gapful-numbers/Crystal/palindromic-gapful-numbers-1.cr similarity index 100% rename from Task/Palindromic-gapful-numbers/Crystal/palindromic-gapful-numbers-1.crystal rename to Task/Palindromic-gapful-numbers/Crystal/palindromic-gapful-numbers-1.cr diff --git a/Task/Palindromic-gapful-numbers/Crystal/palindromic-gapful-numbers-10.crystal b/Task/Palindromic-gapful-numbers/Crystal/palindromic-gapful-numbers-10.cr similarity index 100% rename from Task/Palindromic-gapful-numbers/Crystal/palindromic-gapful-numbers-10.crystal rename to Task/Palindromic-gapful-numbers/Crystal/palindromic-gapful-numbers-10.cr diff --git a/Task/Palindromic-gapful-numbers/Crystal/palindromic-gapful-numbers-2.crystal b/Task/Palindromic-gapful-numbers/Crystal/palindromic-gapful-numbers-2.cr similarity index 100% rename from Task/Palindromic-gapful-numbers/Crystal/palindromic-gapful-numbers-2.crystal rename to Task/Palindromic-gapful-numbers/Crystal/palindromic-gapful-numbers-2.cr diff --git a/Task/Palindromic-gapful-numbers/Crystal/palindromic-gapful-numbers-3.crystal b/Task/Palindromic-gapful-numbers/Crystal/palindromic-gapful-numbers-3.cr similarity index 100% rename from Task/Palindromic-gapful-numbers/Crystal/palindromic-gapful-numbers-3.crystal rename to Task/Palindromic-gapful-numbers/Crystal/palindromic-gapful-numbers-3.cr diff --git a/Task/Palindromic-gapful-numbers/Crystal/palindromic-gapful-numbers-4.crystal b/Task/Palindromic-gapful-numbers/Crystal/palindromic-gapful-numbers-4.cr similarity index 100% rename from Task/Palindromic-gapful-numbers/Crystal/palindromic-gapful-numbers-4.crystal rename to Task/Palindromic-gapful-numbers/Crystal/palindromic-gapful-numbers-4.cr diff --git a/Task/Palindromic-gapful-numbers/Crystal/palindromic-gapful-numbers-5.crystal b/Task/Palindromic-gapful-numbers/Crystal/palindromic-gapful-numbers-5.cr similarity index 100% rename from Task/Palindromic-gapful-numbers/Crystal/palindromic-gapful-numbers-5.crystal rename to Task/Palindromic-gapful-numbers/Crystal/palindromic-gapful-numbers-5.cr diff --git a/Task/Palindromic-gapful-numbers/Crystal/palindromic-gapful-numbers-6.crystal b/Task/Palindromic-gapful-numbers/Crystal/palindromic-gapful-numbers-6.cr similarity index 100% rename from Task/Palindromic-gapful-numbers/Crystal/palindromic-gapful-numbers-6.crystal rename to Task/Palindromic-gapful-numbers/Crystal/palindromic-gapful-numbers-6.cr diff --git a/Task/Palindromic-gapful-numbers/Crystal/palindromic-gapful-numbers-7.crystal b/Task/Palindromic-gapful-numbers/Crystal/palindromic-gapful-numbers-7.cr similarity index 100% rename from Task/Palindromic-gapful-numbers/Crystal/palindromic-gapful-numbers-7.crystal rename to Task/Palindromic-gapful-numbers/Crystal/palindromic-gapful-numbers-7.cr diff --git a/Task/Palindromic-gapful-numbers/Crystal/palindromic-gapful-numbers-8.crystal b/Task/Palindromic-gapful-numbers/Crystal/palindromic-gapful-numbers-8.cr similarity index 100% rename from Task/Palindromic-gapful-numbers/Crystal/palindromic-gapful-numbers-8.crystal rename to Task/Palindromic-gapful-numbers/Crystal/palindromic-gapful-numbers-8.cr diff --git a/Task/Palindromic-gapful-numbers/Crystal/palindromic-gapful-numbers-9.crystal b/Task/Palindromic-gapful-numbers/Crystal/palindromic-gapful-numbers-9.cr similarity index 100% rename from Task/Palindromic-gapful-numbers/Crystal/palindromic-gapful-numbers-9.crystal rename to Task/Palindromic-gapful-numbers/Crystal/palindromic-gapful-numbers-9.cr diff --git a/Task/Palindromic-gapful-numbers/Delphi/palindromic-gapful-numbers.delphi b/Task/Palindromic-gapful-numbers/Delphi/palindromic-gapful-numbers.delphi deleted file mode 100644 index 8021c56ab2..0000000000 --- a/Task/Palindromic-gapful-numbers/Delphi/palindromic-gapful-numbers.delphi +++ /dev/null @@ -1,230 +0,0 @@ -{-------------Library Routines ----------------------------------------------------------------} -procedure GetDigits(N: integer; var IA: TIntegerDynArray); -{Get an array of the integers in a number} -{Numbers returned from least to most significant} -var T,I,DC: integer; -begin -DC:=Trunc(Log10(N))+1; -SetLength(IA,DC); -for I:=0 to DC-1 do - begin - T:=N mod 10; - N:=N div 10; - IA[I]:=T; - end; -end; - -function GetNKPalindrome(N,K: int64): int64; -{Get Nth Palindrome with K-number of digits} -{N = Left half, Right = Reversed(left) a } -var Temp,H1,H2,I: int64; -begin -{Get left digit count - depends on K being odd/even} -if (K and 1)<>0 then Temp:=K div 2 else Temp:=K div 2 - 1; -{Get power of 10 digits} -H1:=trunc(Power(10, Temp)); -{Add in N} -H1:=H1 + N - 1; -H2:=H1; -{ If K is odd, truncate the last digit} -if (k and 1)<>0 then H2:=H2 div 10; -{Reverse H2 and add to H1} -while H2>0 do - begin - H1:=H1 * 10 + (H2 mod 10); - H2:=H2 div 10; - end; -Result:=H1; -end; - - - -function GetPalDigits(N: int64; var Offset: int64): integer; -{Get number of digits and offset for Nth Palindrome} -{Used to feed GetNKPalindrome to find Nth Palindrome} -var R1,R2,Step: int64; -begin -R1:=0; -{Step through number of digits} -for Result:=1 to 36 do - begin - {Calculate new Range step: 9,9,90,90,90,900,900...} - if (Result and 1)<>0 then Step:=9 * Trunc(Power(10,Result div 2)); - {Calculate R2} - R2:=(R1 + Step)-1; - {See if N falls between R1 and R2} - if (N>=R1) and (N<=R2) then - begin - {Calculate offset and exit} - Offset:=(N - R1)+1; - exit; - end; - R1:=R2+1; - end; -end; - - -function GetNthPalindrome(N: integer): int64; -{Get the Nth Palindrome number} -var D,Off: int64; -begin -D:=GetPalDigits(N,Off); -Result:=GetNKPalindrome(Off,D); -end; - - - -procedure GetPalindromeList(Count: integer; var Pals: TInt64DynArray); -{Get a list of the first "Count"-number of palinedromes (Fast)} -var D,I,Inx,Max: integer; -begin -{Set array length} -SetLength(Pals,Count); -Inx:=0; -{Handle palindromes up to 18 digits} -for D:=1 to 18 do - begin - {Get maximum count for palindrom of D digits} - if (D and 1)=1 then Max:=Trunc(Power(10,(D + 1) div 2)) - else Max:=Trunc(Power(10,D div 2)); - {Step through all the numbers half the size of the number of digits} - for I:=1 to Max-Max div 10 do - begin - {Store palindrome} - Pals[Inx]:=GetNKPalindrome(I,D); - Inc(Inx); - {Exit when array is full} - if Inx>=Count then break; - end; - end; -end; - - -{------------------------------------------------------------------------------------------------} - - -function IsGapful(N: int64): boolean; -{Return true if number is "GapFul"} -{GapFul = combined first/last} -{ digits divide evenly into N} -var Digits: TIntegerDynArray; -var I: int64; -begin -Result:=False; -{Must be 3 digit number} -if N<100 then exit; -{Put digits in array} -GetDigits(N,Digits); -{Form number from first and last digit} -I:=Digits[0] + 10 * Digits[High(Digits)]; -{Does it divide evenly into N} -Result:=(N mod I)=0; -end; - - -function HasEndDigit(N: int64; Digit: integer): boolean; -{Return true if last digit match specified "Digit"} -var LD: integer; -begin -LD:=N mod 10; -Result:=LD=Digit; -end; - - -function GetGapfulPalinEndSet(Max, EndDigit: integer): string; -{Get first Max number of Gapful Palindromes with specified EndDigit} -var I,Cnt,P: integer; -begin -Result:='Ending in: '+IntToStr(EndDigit)+CRLF; -Cnt:=0; -{Get palindromes and test them} -for I:=0 to high(Integer) do - begin - {Get next palinedrome} - P:=GetNthPalindrome(I); - {Is Gapful and has specified EndDigit} - if IsGapFul(P) and HasEndDigit(P,EndDigit) then - begin - Inc(Cnt); - {Display it} - Result:=Result+Format('%8d',[P]); - if (Cnt mod 5)=0 then Result:=Result+CRLF; - {Break when finished} - if Cnt>=Max then break; - end; - end; -end; - - - -function LastGapfulPalinEndSet(Count,Last,EndDigit: integer): string; -{Get Gapful Palindromes with specified EndDigit} -{Get "Last" number of items out of a total "Count" } -var I,Inx: integer; -var P: int64; -var IA: TInt64DynArray; -begin -SetLength(IA,Count); -Result:='Ending in: '+IntToStr(EndDigit)+CRLF; -{Get count number of items} -Inx:=0; -for I:=0 to Count-1 do - begin - {Keep getting palindromes until} - {they Gapful and have specified last digit} - repeat - begin - P:=GetNthPalindrome(Inx); - Inc(Inx); - end - until IsGapFul(P) and HasEndDigit(P,EndDigit); - {Save item} - IA[I]:=P; - end; -{Get last items} -for I:=Count-Last to Count-1 do - begin - Result:=Result+Format('%12d',[IA[I]]); - if (I mod 5)=4 then Result:=Result+CRLF; - end; -end; - - - -procedure ShowPalindromicGapfuls(Memo: TMemo); -var S: string; -begin -Memo.Lines.Add('First 20 palindromic gapful numbers'); - -Memo.Lines.Add(GetGapFulPalinEndSet(20,1)); -Memo.Lines.Add(GetGapFulPalinEndSet(20,2)); -Memo.Lines.Add(GetGapFulPalinEndSet(20,3)); -Memo.Lines.Add(GetGapFulPalinEndSet(20,4)); -Memo.Lines.Add(GetGapFulPalinEndSet(20,5)); -Memo.Lines.Add(GetGapFulPalinEndSet(20,6)); -Memo.Lines.Add(GetGapFulPalinEndSet(20,7)); -Memo.Lines.Add(GetGapFulPalinEndSet(20,8)); -Memo.Lines.Add(GetGapFulPalinEndSet(20,9)); - -Memo.Lines.Add('86th to 100th'); -Memo.Lines.Add(LastGapFulPalinEndSet(100,15,1)); -Memo.Lines.Add(LastGapFulPalinEndSet(100,15,2)); -Memo.Lines.Add(LastGapFulPalinEndSet(100,15,3)); -Memo.Lines.Add(LastGapFulPalinEndSet(100,15,4)); -Memo.Lines.Add(LastGapFulPalinEndSet(100,15,5)); -Memo.Lines.Add(LastGapFulPalinEndSet(100,15,6)); -Memo.Lines.Add(LastGapFulPalinEndSet(100,15,7)); -Memo.Lines.Add(LastGapFulPalinEndSet(100,15,8)); -Memo.Lines.Add(LastGapFulPalinEndSet(100,15,9)); - -Memo.Lines.Add('991st to 1000th:'); -Memo.Lines.Add(LastGapFulPalinEndSet(1000,10,1)); -Memo.Lines.Add(LastGapFulPalinEndSet(1000,10,2)); -Memo.Lines.Add(LastGapFulPalinEndSet(1000,10,3)); -Memo.Lines.Add(LastGapFulPalinEndSet(1000,10,4)); -Memo.Lines.Add(LastGapFulPalinEndSet(1000,10,5)); -Memo.Lines.Add(LastGapFulPalinEndSet(1000,10,6)); -Memo.Lines.Add(LastGapFulPalinEndSet(1000,10,7)); -Memo.Lines.Add(LastGapFulPalinEndSet(1000,10,8)); -Memo.Lines.Add(LastGapFulPalinEndSet(1000,10,9)); -end; diff --git a/Task/Palindromic-gapful-numbers/Delphi/palindromic-gapful-numbers.pas b/Task/Palindromic-gapful-numbers/Delphi/palindromic-gapful-numbers.pas new file mode 100644 index 0000000000..aa891921ff --- /dev/null +++ b/Task/Palindromic-gapful-numbers/Delphi/palindromic-gapful-numbers.pas @@ -0,0 +1,230 @@ +{-------------Library Routines ----------------------------------------------------------------} +procedure GetDigits(N: integer; var IA: TIntegerDynArray); +{Get an array of the integers in a number} +{Numbers returned from least to most significant} +var T,I,DC: integer; +begin +DC:=Trunc(Log10(N))+1; +SetLength(IA,DC); +for I:=0 to DC-1 do + begin + T:=N mod 10; + N:=N div 10; + IA[I]:=T; + end; +end; + +function GetNKPalindrome(N,K: int64): int64; +{Get Nth Palindrome with K-number of digits} +{N = Left half, Right = Reversed(left) a } +var Temp,H1,H2,I: int64; +begin +{Get left digit count - depends on K being odd/even} +if (K and 1)<>0 then Temp:=K div 2 else Temp:=K div 2 - 1; +{Get power of 10 digits} +H1:=trunc(Power(10, Temp)); +{Add in N} +H1:=H1 + N - 1; +H2:=H1; +{ If K is odd, truncate the last digit} +if (k and 1)<>0 then H2:=H2 div 10; +{Reverse H2 and add to H1} +while H2>0 do + begin + H1:=H1 * 10 + (H2 mod 10); + H2:=H2 div 10; + end; +Result:=H1; +end; + + + +function GetPalDigits(N: int64; var Offset: int64): integer; +{Get number of digits and offset for Nth Palindrome} +{Used to feed GetNKPalindrome to find Nth Palindrome} +var R1,R2,Step: int64; +begin +R1:=0; +{Step through number of digits} +for Result:=1 to 36 do + begin + {Calculate new Range step: 9,9,90,90,90,900,900...} + if (Result and 1)<>0 then Step:=9 * Trunc(Power(10,Result div 2)); + {Calculate R2} + R2:=(R1 + Step)-1; + {See if N falls between R1 and R2} + if (N>=R1) and (N<=R2) then + begin + {Calculate offset and exit} + Offset:=(N - R1)+1; + exit; + end; + R1:=R2+1; + end; +end; + + +function GetNthPalindrome(N: integer): int64; +{Get the Nth Palindrome number} +var D,Off: int64; +begin +D:=GetPalDigits(N,Off); +Result:=GetNKPalindrome(Off,D); +end; + + + +procedure GetPalindromeList(Count: integer; var Pals: TInt64DynArray); +{Get a list of the first "Count"-number of palinedromes (Fast)} +var D,I,Inx,Max: integer; +begin +{Set array length} +SetLength(Pals,Count); +Inx:=0; +{Handle palindromes up to 18 digits} +for D:=1 to 18 do + begin + {Get maximum count for palindrom of D digits} + if (D and 1)=1 then Max:=Trunc(Power(10,(D + 1) div 2)) + else Max:=Trunc(Power(10,D div 2)); + {Step through all the numbers half the size of the number of digits} + for I:=1 to Max-Max div 10 do + begin + {Store palindrome} + Pals[Inx]:=GetNKPalindrome(I,D); + Inc(Inx); + {Exit when array is full} + if Inx>=Count then break; + end; + end; +end; + + +{------------------------------------------------------------------------------------------------} + + +function IsGapful(N: int64): boolean; +{Return true if number is "GapFul"} +{GapFul = combined first/last} +{ digits divide evenly into N} +var Digits: TIntegerDynArray; +var I: int64; +begin +Result:=False; +{Must be 3 digit number} +if N<100 then exit; +{Put digits in array} +GetDigits(N,Digits); +{Form number from first and last digit} +I:=Digits[0] + 10 * Digits[High(Digits)]; +{Does it divide evenly into N} +Result:=(N mod I)=0; +end; + + +function HasEndDigit(N: int64; Digit: integer): boolean; +{Return true if last digit match specified "Digit"} +var LD: integer; +begin +LD:=N mod 10; +Result:=LD=Digit; +end; + + +function GetGapfulPalinEndSet(Max, EndDigit: integer): string; +{Get first Max number of Gapful Palindromes with specified EndDigit} +var I,Cnt,P: integer; +begin +Result:='Ending in: '+IntToStr(EndDigit)+CRLF; +Cnt:=0; +{Get palindromes and test them} +for I:=0 to high(Integer) do + begin + {Get next palinedrome} + P:=GetNthPalindrome(I); + {Is Gapful and has specified EndDigit} + if IsGapFul(P) and HasEndDigit(P,EndDigit) then + begin + Inc(Cnt); + {Display it} + Result:=Result+Format('%8d',[P]); + if (Cnt mod 5)=0 then Result:=Result+CRLF; + {Break when finished} + if Cnt>=Max then break; + end; + end; +end; + + + +function LastGapfulPalinEndSet(Count,Last,EndDigit: integer): string; +{Get Gapful Palindromes with specified EndDigit} +{Get "Last" number of items out of a total "Count" } +var I,Inx: integer; +var P: int64; +var IA: TInt64DynArray; +begin +SetLength(IA,Count); +Result:='Ending in: '+IntToStr(EndDigit)+CRLF; +{Get count number of items} +Inx:=0; +for I:=0 to Count-1 do + begin + {Keep getting palindromes until} + {they Gapful and have specified last digit} + repeat + begin + P:=GetNthPalindrome(Inx); + Inc(Inx); + end + until IsGapFul(P) and HasEndDigit(P,EndDigit); + {Save item} + IA[I]:=P; + end; +{Get last items} +for I:=Count-Last to Count-1 do + begin + Result:=Result+Format('%12d',[IA[I]]); + if (I mod 5)=4 then Result:=Result+CRLF; + end; +end; + + + +procedure ShowPalindromicGapfuls(Memo: TMemo); +var S: string; +begin +Memo.Lines.Add('First 20 palindromic gapful numbers'); + +Memo.Lines.Add(GetGapFulPalinEndSet(20,1)); +Memo.Lines.Add(GetGapFulPalinEndSet(20,2)); +Memo.Lines.Add(GetGapFulPalinEndSet(20,3)); +Memo.Lines.Add(GetGapFulPalinEndSet(20,4)); +Memo.Lines.Add(GetGapFulPalinEndSet(20,5)); +Memo.Lines.Add(GetGapFulPalinEndSet(20,6)); +Memo.Lines.Add(GetGapFulPalinEndSet(20,7)); +Memo.Lines.Add(GetGapFulPalinEndSet(20,8)); +Memo.Lines.Add(GetGapFulPalinEndSet(20,9)); + +Memo.Lines.Add('86th to 100th'); +Memo.Lines.Add(LastGapFulPalinEndSet(100,15,1)); +Memo.Lines.Add(LastGapFulPalinEndSet(100,15,2)); +Memo.Lines.Add(LastGapFulPalinEndSet(100,15,3)); +Memo.Lines.Add(LastGapFulPalinEndSet(100,15,4)); +Memo.Lines.Add(LastGapFulPalinEndSet(100,15,5)); +Memo.Lines.Add(LastGapFulPalinEndSet(100,15,6)); +Memo.Lines.Add(LastGapFulPalinEndSet(100,15,7)); +Memo.Lines.Add(LastGapFulPalinEndSet(100,15,8)); +Memo.Lines.Add(LastGapFulPalinEndSet(100,15,9)); + +Memo.Lines.Add('991st to 1000th:'); +Memo.Lines.Add(LastGapFulPalinEndSet(1000,10,1)); +Memo.Lines.Add(LastGapFulPalinEndSet(1000,10,2)); +Memo.Lines.Add(LastGapFulPalinEndSet(1000,10,3)); +Memo.Lines.Add(LastGapFulPalinEndSet(1000,10,4)); +Memo.Lines.Add(LastGapFulPalinEndSet(1000,10,5)); +Memo.Lines.Add(LastGapFulPalinEndSet(1000,10,6)); +Memo.Lines.Add(LastGapFulPalinEndSet(1000,10,7)); +Memo.Lines.Add(LastGapFulPalinEndSet(1000,10,8)); +Memo.Lines.Add(LastGapFulPalinEndSet(1000,10,9)); +end; diff --git a/Task/Palindromic-gapful-numbers/Icon/palindromic-gapful-numbers.icon b/Task/Palindromic-gapful-numbers/Icon/palindromic-gapful-numbers.icon new file mode 100644 index 0000000000..4080bda97e --- /dev/null +++ b/Task/Palindromic-gapful-numbers/Icon/palindromic-gapful-numbers.icon @@ -0,0 +1,36 @@ +procedure main(A) + l1 := \A[1] | 20 + l2 := \A[2] | 15 + l3 := \A[3] | 100 + + a := list(9) + every i := 1 to 9 do { + write("\nPalindromic gapful numbers ending in ",i,":") + cnt := 0 + every (((p := palen(gapful(seq(100))))[1] == i)\l3, cnt +:= 1) do { + if cnt <= l1 then { + writes(right(p,9)) + if cnt%10 = 0 then write() + } + /a[i] := [] + put(a[i],p) + if *a[i] > l2 then pop(a[i]) + } + } + + every i := 1 to 9 do { + write("\nLast ",l2," palindromic gapful numbers ending in ",i,":") + every writes(" ",!a[i]|"\n") + } + +end + +procedure palen(n) + return reverse(s := string(n)) == s +end + +procedure gapful(n) + s := string(n) + m := s[1]*10+s[-1] + return (n%m = 0, n) +end diff --git a/Task/Palindromic-gapful-numbers/JavaScript/palindromic-gapful-numbers.js b/Task/Palindromic-gapful-numbers/JavaScript/palindromic-gapful-numbers.js new file mode 100644 index 0000000000..43d0a836fe --- /dev/null +++ b/Task/Palindromic-gapful-numbers/JavaScript/palindromic-gapful-numbers.js @@ -0,0 +1,22 @@ +function is_palindrome(n) { + return n == Number([...String(n)].toReversed().join("")); +} + +function is_gapful(n) { + const digits = [...String(n)].map(Number); + const div = 10 * digits.shift() + digits.pop(); + return Number.isInteger(n / div); +} + +for (let d = 2; d <= 9; d++) { + console.log(`|Palindromic gapful numbers ending in ${d}|`); + let nums = [], n = 100 + d; + while (nums.length < 100) { + if (is_gapful(n) && is_palindrome(n)) { + nums.push(n); + } + n += 10; + } + console.log(`First 20: ${nums.slice(0, 20).join(" ")}`); + console.log(`86th-100th: ${nums.slice(85, 100).join(" ")}`); +} diff --git a/Task/Palindromic-gapful-numbers/Jq/palindromic-gapful-numbers.jq b/Task/Palindromic-gapful-numbers/Jq/palindromic-gapful-numbers.jq new file mode 100644 index 0000000000..0681316aaf --- /dev/null +++ b/Task/Palindromic-gapful-numbers/Jq/palindromic-gapful-numbers.jq @@ -0,0 +1,68 @@ +### Generic functions +def power($a;$b): reduce range(0;$b) as $i (1; . * $a); + +# Emit the reverse of the string $s +def reverse($s): + $s | tostring | split("") | reverse | join(""); + +def skip($n; stream): + foreach stream as $s (-1; + if . == $n then . else .+1 end; + select(. == $n) | $s); + +### Palindromic gapful numbers + +# Output: a stream of non-trivial palindromic gapful numbers ending in the specified digit +def palindromicgapfuls($digit): + {emit: null, + dd: (11 * $digit), # digit gapful divisor: 11, 22,...88, 99 + power: 1} + | foreach range(0; infinite) as $_ (.; + .power += 1 + | (power(10; .power / 2 | floor)) as $base # value of middle digit position: 10.. + | ($base * 11) as $base11 # value of middle two digits positions: 110.. + | ($base * $digit) as $this_lo # starting half for this digit: 10.. to 90.. + | ($base * ($digit + 1)) as $next_lo # starting half for next digit: 20.. to 100.. + + | foreach range($this_lo; $next_lo; 10) as $front_half (.; # d_00; d_10; d_20; ... + ($front_half|tostring) as $left_half + | reverse($left_half) as $right_half + | if .power%2 == 1 + then .palindrome = (($left_half + $right_half) | tonumber) + | foreach range(0;10) as $i (.; + .emit = if .palindrome % .dd == 0 + then .palindrome + else null + end + | .palindrome += $base11 ) + else .palindrome = ((($left_half[:-1]) + $right_half) | tonumber) + | foreach range(0;10) as $i (.; + .emit = if .palindrome % .dd == 0 + then .palindrome + else null + end + | .palindrome += $base ) + end ) ) + | select(.emit).emit ; + +def palindromicgapfuls($count; $keep): + range(1; 10) as $digit + | "\($digit) : \([limit($keep; skip($count - $keep; palindromicgapfuls($digit)))])" ; + +def task: + "First 20 non-trivial palindromic gapful numbers ending with:", + palindromicgapfuls(20; 20), + + "\nLast 15 of first 100 non-trivial palindromic gapful numbers ending in:", + palindromicgapfuls(100; 15), + + "\nLast 10 of first 1000 non-trivial palindromic gapful numbers ending in:", + palindromicgapfuls(1000; 10), + + "\n100,000th non-trivial palindromic gapful number ending with:", + palindromicgapfuls(100000; 1), + + "\n1,000,000th non-trivial palindromic gapful number ending with:", + palindromicgapfuls(1000000; 1); + +task diff --git a/Task/Palindromic-gapful-numbers/Julia/palindromic-gapful-numbers.julia b/Task/Palindromic-gapful-numbers/Julia/palindromic-gapful-numbers.jl similarity index 100% rename from Task/Palindromic-gapful-numbers/Julia/palindromic-gapful-numbers.julia rename to Task/Palindromic-gapful-numbers/Julia/palindromic-gapful-numbers.jl diff --git a/Task/Palindromic-gapful-numbers/PascalABC.NET/palindromic-gapful-numbers.pas b/Task/Palindromic-gapful-numbers/PascalABC.NET/palindromic-gapful-numbers.pas new file mode 100644 index 0000000000..b172609d71 --- /dev/null +++ b/Task/Palindromic-gapful-numbers/PascalABC.NET/palindromic-gapful-numbers.pas @@ -0,0 +1,30 @@ +function pal_gen(): sequence of BigInteger; +begin + var o := 10; + var e := 10; + repeat + var fwd_o := o.ToString; + var fwd_e := e.ToString; + var rev_o := fwd_o[^2:0:-1]; + var rev_e := fwd_e[::-1]; + var pal := Min((fwd_o + rev_o).ToBigInteger, (fwd_e + rev_e).ToBigInteger); + yield pal; + if pal.ToString.Length.IsEven then e += 1 else o += 1; + until false; +end; + +function is_gapful(n: BigInteger) := n mod (n.ToString[1].ToDigit * 10 + (n mod 10)) = 0; + +begin + writeln('palindromic gapful numbers from 1 to 20:'); + for var i := 1 to 9 do + writeln(i, ': ', pal_gen.Where(n -> is_gapful(n)).Where(n -> n mod 10 = i).Take(20)); + writeln; + writeln('palindromic gapful numbers from 86 to 100:'); + for var i := 1 to 9 do + writeln(i, ': ', pal_gen.Where(n -> is_gapful(n)).Where(n -> n mod 10 = i).Skip(85).Take(15)); + writeln; + writeln('palindromic gapful numbers from 991 to 1000:'); + for var i := 1 to 9 do + writeln(i, ': ', pal_gen.Where(n -> is_gapful(n)).Where(n -> n mod 10 = i).Skip(990).Take(10)); +end. diff --git a/Task/Palindromic-gapful-numbers/Phix/palindromic-gapful-numbers-1.phix b/Task/Palindromic-gapful-numbers/Phix/palindromic-gapful-numbers-1.phix index 9f4be8beef..92fa777b24 100644 --- a/Task/Palindromic-gapful-numbers/Phix/palindromic-gapful-numbers-1.phix +++ b/Task/Palindromic-gapful-numbers/Phix/palindromic-gapful-numbers-1.phix @@ -1,60 +1,62 @@ -(phixonline)--> - with javascript_semantics - function reverse_n(atom s) - atom e = 0 - while s>0 do - e = e*10 + remainder(s,10) - s = floor(s/10) - end while - return e - end function +with javascript_semantics +function reverse_n(atom s) + atom e = 0 + while s>0 do + e = e*10 + remainder(s,10) + s = floor(s/10) + end while + return e +end function - constant mx = 1000, - data = {{1, 20, "%7d "}, {86, 100, "%8d "}, {991, 1000, "%10d "}} +constant mx = 1000, + data = {{1, 20, repeat("%6d",3)& + repeat("%7d",13)& + repeat("%8d",4)}, + {86, 100, repeat("%9d",15)}, + {991, 1000, repeat("%11d",10)}} - include builtins\ordinal.e +include builtins\ordinal.e - function digit(sequence results, integer d) - integer count = 0, pow = 1, fl = d*11 - for nd=3 to 15 do -- (number of digits, usually quits early) - -- (obvs. 64-bit phix is fine with 19 digits, but 32-bit ain't) - bool odd = (remainder(nd,2)==1) - for s=d*pow to (d+1)*pow-1 do -- (eg 300 to 399) - integer e = reverse_n(s) - for m=0 to iff(odd?9:0) do -- (1 or 10 iterations) - atom p = e + iff(odd ? s*pow*100+m*pow*10 - : s*pow*10) - if remainder(p,fl)==0 then -- gapful! - count += 1 - results[count][d] = p - if count==mx then return results end if - end if - end for - end for - if odd then pow *= 10 end if - end for - if count<mx then ?9/0 end if -- oh dear... - return results - end function +function digit(sequence results, integer d) + integer count = 0, pow = 1, fl = d*11 + for nd=3 to 15 do -- (number of digits, usually quits early) + -- (obvs. 64-bit phix is fine with 19 digits, but 32-bit ain't) + bool odd = (remainder(nd,2)==1) + for s=d*pow to (d+1)*pow-1 do -- (eg 300 to 399) + integer e = reverse_n(s) + for m=0 to iff(odd?9:0) do -- (1 or 10 iterations) + atom p = e + iff(odd ? s*pow*100+m*pow*10 + : s*pow*10) + if remainder(p,fl)==0 then -- gapful! + count += 1 + results[count][d] = p + if count==mx then return results end if + end if + end for + end for + if odd then pow *= 10 end if + end for + if countprocedure
    main() - sequence results = repeat(repeat({},9),mx) - for d=1 to 9 do -- (the start/end digit) - results = digit(results,d) - end for +procedure main() + sequence results = repeat(repeat({},9),mx) + for d=1 to 9 do -- (the start/end digit) + results = digit(results,d) + end for - for i=1 to length(data) do - {integer s, integer e, string fmt} = data[i] - printf(1,"%,d%s to %,d%s palindromic gapful numbers (> 100) ending with:\n", {s,ord(s),e,ord(e)}) - for d=1 to 9 do - printf(1,"%d: ",d) - for j=s to e do - printf(1,fmt,results[j][d]) - end for - printf(1,"\n") - end for - printf(1,"\n") - end for - end procedure - main() - - -- - -- demo\rosetta\Palindromic_gapful_numbers.exw - -- =========================================== - -- - -- Astonishingly this is all done with standard precision numbers, <2^53. - -- I will credit [[Self_numbers#AppleScript]] and comment by Nigel Galloway - -- on the talk page for ideas that inspired me. - -- - -- A palindrome such as 9459549 can be constructed/broken down into - -- 9000009 - -- 400040 - -- 50500 - -- 9000 - -- - -- Further, 9459549 rem 99 is the same as - -- (the sum of rem 99 on all of those pieces) rem 99 - -- - -- Finding eg 400040 rem 99 can also be simplified, it is of course the - -- same as (400000 rem 99 + 40 rem 99) rem 99, and further 40 rem 99 - -- is the same as (4 rem 99[already known])*10 rem 99 [smaller nos]. - -- - -- Also, when filling a "hole", such as the final 9, we find - -- v - -- 9450549 rem 99 = 9 - -- 9451549 rem 99 = 19, - -- 9452549 rem 99 = 29, - -- 9453549 rem 99 = 39, - -- 9454549 rem 99 = 49, - -- 9455549 rem 99 = 59, - -- 9456549 rem 99 = 69, - -- 9457549 rem 99 = 79, - -- 9458549 rem 99 = 89, and - -- 9459549 rem 99 = 0, - -- ^ - -- in this case only the '9' fits. - -- - -- But actually we can predict what will fit from the partial sum of - -- prior pieces rem 99, ie 9000009..50500, and the same can be said - -- when filling the 505-sized hole - what will "fit" depends not on - -- what the "outer" actually are, but what their sum rem 99 is, and - -- likewise for larger and larger holes. - -- If we later find ourselves looking at the same size hole, with - -- the same outer rem and the same rem 99 outmost requirement, we - -- would know instantly how many things are going to fit. - -- True, keeping full lists as the holes got bigger would probably - -- consume memory almost as fast as an SR-71, but a single count, - -- albeit one keyed on 4 conditions, we can cope. It turns out that - -- even by the 10^15th scan, we only hit 17,579 variations anyway. - -- As we stumble across larger and larger holes, what we learn can - -- be used to skip more and more similar, such that finding the - -- ten millionth item is almost as fast as the first millionth, as - -- opposed to the times 10 that you'd normally expect. - -- - -- Note that if I stumble across a hole that will fit more than I'm - -- prepared to fully skip, I start going through things one-by-one, - -- but that's ok because many smaller but still quite big holes - -- will probably be skipped. - -- - with javascript_semantics +-- +-- demo\rosetta\Palindromic_gapful_numbers.exw +-- =========================================== +-- +-- Astonishingly this is all done with standard precision numbers, <2^53. +-- I will credit Self_numbers#AppleScript and comment by Nigel Galloway +-- on the talk page for ideas that inspired me. +-- +-- A palindrome such as 9459549 can be constructed/broken down into +-- 9000009 +-- 400040 +-- 50500 +-- 9000 +-- +-- Further, 9459549 rem 99 is the same as +-- (the sum of rem 99 on all of those pieces) rem 99 +-- +-- Finding eg 400040 rem 99 can also be simplified, it is of course the +-- same as (400000 rem 99 + 40 rem 99) rem 99, and further 40 rem 99 +-- is the same as (4 rem 99[already known])*10 rem 99 [smaller nos]. +-- +-- Also, when filling a "hole", such as the final 9, we find +-- v +-- 9450549 rem 99 = 9 +-- 9451549 rem 99 = 19, +-- 9452549 rem 99 = 29, +-- 9453549 rem 99 = 39, +-- 9454549 rem 99 = 49, +-- 9455549 rem 99 = 59, +-- 9456549 rem 99 = 69, +-- 9457549 rem 99 = 79, +-- 9458549 rem 99 = 89, and +-- 9459549 rem 99 = 0, +-- ^ +-- in this case only the '9' fits. +-- +-- But actually we can predict what will fit from the partial sum of +-- prior pieces rem 99, ie 9000009..50500, and the same can be said +-- when filling the 505-sized hole - what will "fit" depends not on +-- what the "outer" actually are, but what their sum rem 99 is, and +-- likewise for larger and larger holes. +-- If we later find ourselves looking at the same size hole, with +-- the same outer rem and the same rem 99 outmost requirement, we +-- would know instantly how many things are going to fit. +-- True, keeping full lists as the holes got bigger would probably +-- consume memory almost as fast as an SR-71, but a single count, +-- albeit one keyed on 4 conditions, we can cope. It turns out that +-- even by the 10^15th scan, we only hit 17,579 variations anyway. +-- As we stumble across larger and larger holes, what we learn can +-- be used to skip more and more similar, such that finding the +-- ten millionth item is almost as fast as the first millionth, as +-- opposed to the times 10 that you'd normally expect. +-- +-- Note that if I stumble across a hole that will fit more than I'm +-- prepared to fully skip, I start going through things one-by-one, +-- but that's ok because many smaller but still quite big holes +-- will probably be skipped. +-- +with javascript_semantics - sequence cache = columnize(repeat(columnize({tagset(9)}),9)) - -- ie {{{1}, {1}, {1}, {1}, {1}, {1}, {1}, {1}, {1}}, - -- {{2}, {2}, {2}, {2}, {2}, {2}, {2}, {2}, {2}}, - -- {{3}, {3}, {3}, {3}, {3}, {3}, {3}, {3}, {3}}, - -- {{4}, {4}, {4}, {4}, {4}, {4}, {4}, {4}, {4}}, - -- {{5}, {5}, {5}, {5}, {5}, {5}, {5}, {5}, {5}}, - -- {{6}, {6}, {6}, {6}, {6}, {6}, {6}, {6}, {6}}, - -- {{7}, {7}, {7}, {7}, {7}, {7}, {7}, {7}, {7}}, - -- {{8}, {8}, {8}, {8}, {8}, {8}, {8}, {8}, {8}}, - -- {{9}, {9}, {9}, {9}, {9}, {9}, {9}, {9}, {9}}} - -- aka 1 rem 11 .. 1 rem 99 are all 1, - -- .. 9 rem 11 .. 9 rem 99 are all 9. - -- each gets extended with 10 rem 11 .. 10 rem 99, - -- 100 rem 11 .. 100 rem 99, - -- ... .. 900 rem 99, etc. - -- (not really worth trying to take advantage of any cycles - -- that might appear in such a relatively small table, as - -- it will be at most (on 64-bit) 9 * 9 * 42.) - -- - function rmdrn(integer digit, gap, pow, n) - -- - -- digit is the outer 0..9 (obvs 0 always yields 0), - -- gap is zeroes between (-1,0,1,2,.. for eg 1,11,101,1001), - -- pow is trailing zeros (0,1,2,.. for eg 101,1010,10100), - -- n is 1..9 for 11..99 - -- eg rmdrn(4,3,2,1) yields remainder(4000400,11), but - -- that === remainder(remainder(4000000,11)+ - -- remainder( 400,11),11), and - -- if k = remainder(4*10^(m-1),11) [already known] then - -- remainder(4*10^m,11) === remainder(k*10,11), so - -- we only need to keep a small table for each [digit][n]. - -- Thus we avoid maths on 10^42-ish numbers/needing gmp. - -- - if digit=0 then return 0 end if - integer nn = n*11, g - sequence cdn = cache[digit][n] - while length(cdn)<gap+pow+2 do - cache[digit][n] = 0 -- (kill refcount) - cdn &= remainder(cdn[$]*10,nn) - cache[digit][n] = cdn - end while - g = iff(gap=-1 ? 0 : cdn[gap+pow+2]) - return remainder(g + cdn[pow+1],nn) - end function +sequence cache = columnize(repeat(columnize({tagset(9)}),9)) +-- ie {{{1}, {1}, {1}, {1}, {1}, {1}, {1}, {1}, {1}}, +-- {{2}, {2}, {2}, {2}, {2}, {2}, {2}, {2}, {2}}, +-- {{3}, {3}, {3}, {3}, {3}, {3}, {3}, {3}, {3}}, +-- {{4}, {4}, {4}, {4}, {4}, {4}, {4}, {4}, {4}}, +-- {{5}, {5}, {5}, {5}, {5}, {5}, {5}, {5}, {5}}, +-- {{6}, {6}, {6}, {6}, {6}, {6}, {6}, {6}, {6}}, +-- {{7}, {7}, {7}, {7}, {7}, {7}, {7}, {7}, {7}}, +-- {{8}, {8}, {8}, {8}, {8}, {8}, {8}, {8}, {8}}, +-- {{9}, {9}, {9}, {9}, {9}, {9}, {9}, {9}, {9}}} +-- aka 1 rem 11 .. 1 rem 99 are all 1, +-- .. 9 rem 11 .. 9 rem 99 are all 9. +-- each gets extended with 10 rem 11 .. 10 rem 99, +-- 100 rem 11 .. 100 rem 99, +-- ... .. 900 rem 99, etc. +-- (not really worth trying to take advantage of any cycles +-- that might appear in such a relatively small table, as +-- it will be at most (on 64-bit) 9 * 9 * 42.) +-- +function rmdrn(integer digit, gap, pow, n) +-- +-- digit is the outer 0..9 (obvs 0 always yields 0), +-- gap is zeroes between (-1,0,1,2,.. for eg 1,11,101,1001), +-- pow is trailing zeros (0,1,2,.. for eg 101,1010,10100), +-- n is 1..9 for 11..99 +-- eg rmdrn(4,3,2,1) yields remainder(4000400,11), but +-- that === remainder(remainder(4000000,11)+ +-- remainder( 400,11),11), and +-- if k = remainder(4*10^(m-1),11) [already known] then +-- remainder(4*10^m,11) === remainder(k*10,11), so +-- we only need to keep a small table for each [digit][n]. +-- Thus we avoid maths on 10^42-ish numbers/needing gmp. +-- + if digit=0 then return 0 end if + integer nn = n*11, g + sequence cdn = cache[digit][n] + while length(cdn)integer
    skipd = new_dict() +integer skipd = new_dict() - function palindromicgapfuls(sequence pals, string lhs, atom palcount, to_skip, count, integer l, r, p, dd) - -- - -- pals: results (passing it up grants it automatic pass-by-reference status, which may help speedwise) - -- lhs: eg "945" of a potential 9459549 result - -- palcount, to_skip, count: self explanatory (aka got/ignore/target) - -- l: length of inner to be filled in - -- r: remainder of outer, eg remainder(9400049,11), built from rmdrn() - -- p: left shift (should in fact always equal length(lhs), I think) - -- dd: outermost 1..9 (despite the name, it's a single digit) - -- - sequence key = {l,r,p,dd} - integer node = getd_index(key,skipd) - atom skip = iff(node==null?count:getd_by_index(node,skipd)), skipn - if node!=null and (palcount+skip)<to_skip then - palcount += skip - else - skip = 0 - for d=0 to 9 do - integer r2 = remainder(r+rmdrn(d,l-2,p,dd),dd*11) - if l<=2 then - if r2=0 then - palcount += 1 - if palcount<=to_skip then - skip += 1 - else - pals = append(deep_copy(pals),lhs&repeat(d+'0',l)&reverse(lhs)) - end if - end if - else - {pals,palcount,skipn} = palindromicgapfuls(pals,lhs&(d+'0'),palcount,to_skip,count,l-2,r2,p+1,dd) - skip += skipn - end if - if palcount==count then exit end if - end for - if palcount<to_skip then setd(key,skip,skipd) end if - end if - return {pals,palcount,skip} - end function +function palindromicgapfuls(sequence pals, string lhs, atom palcount, to_skip, count, integer l, r, p, dd) +-- +-- pals: results (passing it up grants it automatic pass-by-reference status, which may help speedwise) +-- lhs: eg "945" of a potential 9459549 result +-- palcount, to_skip, count: self explanatory (aka got/ignore/target) +-- l: length of inner to be filled in +-- r: remainder of outer, eg remainder(9400049,11), built from rmdrn() +-- p: left shift (should in fact always equal length(lhs), I think) +-- dd: outermost 1..9 (despite the name, it's a single digit) +-- + sequence key = {l,r,p,dd} + integer node = getd_index(key,skipd) + atom skip = iff(node==null?count:getd_by_index(node,skipd)), skipn + if node!=null and (palcount+skip)function
    collect(integer digit, atom count, keep) - atom to_skip = count - keep, - palcount = 0, l = 3 - sequence pals = {} - string lhs = ""&(digit+'0') -- ie "1" or "2" .. or "9" - while palcount < count do - integer r = rmdrn(digit,l-2,0,digit) - {pals,palcount} = palindromicgapfuls(pals,lhs,palcount,to_skip,count,l-2,r,1,digit) - l += 1 - end while - return pals - end function +function collect(integer digit, atom count, keep) + atom to_skip = count - keep, + palcount = 0, l = 3 + sequence pals = {} + string lhs = ""&(digit+'0') -- ie "1" or "2" .. or "9" + while palcount < count do + integer r = rmdrn(digit,l-2,0,digit) + {pals,palcount} = palindromicgapfuls(pals,lhs,palcount,to_skip,count,l-2,r,1,digit) + l += 1 + end while + return pals +end function - constant tests = {{20,20,1,9},{100,15,1,9},{1000,10,1,9},{10_000,5,1,9}, - {100_000,1,1,9},{1_000_000,1,1,9},{10_000_000,1,1,9}, - {100_000_000,1,9,9},{1000_000_000,1,9,9},{10_000_000_000,1,9,9}, - {100_000_000_000,1,9,9},{1000_000_000_000,1,9,9}, - {10_000_000_000_000,1,9,9},{100_000_000_000_000,1,9,9}, - {1_000_000_000_000_000,1,9,9}, - -- {1_000_000_000_000_000,1,2,4}, -- (matches AppleScript) - {10_000_000_000_000_000_000,1,9,9}} -- 64 bit only - -- (any further and you'd need mpfr just to hold counts) +constant tests = {{20,20,1,9},{100,15,1,9},{1000,10,1,9},{10_000,5,1,9}, + {100_000,1,1,9},{1_000_000,1,1,9},{10_000_000,1,1,9}, + {100_000_000,1,9,9},{1000_000_000,1,9,9},{10_000_000_000,1,9,9}, + {100_000_000_000,1,9,9},{1000_000_000_000,1,9,9}, + {10_000_000_000_000,1,9,9},{100_000_000_000_000,1,9,9}, + {1_000_000_000_000_000,1,9,9}, +-- {1_000_000_000_000_000,1,2,4}, -- (matches AppleScript) + {10_000_000_000_000_000_000,1,9,9}} -- 64 bit only + -- (any further and you'd need mpfr just to hold counts) - atom t0 = time(), count, keep, start, finish - for i=1 to length(tests)-(machine_bits()!=64) do - {count, keep, start, finish} = tests[i] - string r = iff(count==keep?sprintf("First %d",{count}): - iff(keep>1?sprintf("Last %d of first %,d",{keep,count}) - :sprintf("%,dth",{count}))), - s = iff(keep=1?"":"s") - printf(1,"%s palindromic gapful number%s ending with:\n", {r,s}) - sequence tags = tagset(finish,start), - res = apply(true,collect,{tags,count,keep}) - string fmt = sprintf("%%%ds",max(apply(join(res,{}),length))) - for j=1 to length(res) do - printf(1,"%d: %s\n",{tags[j],join(apply(true,sprintf,{{fmt},res[j]})," ")}) - end for - puts(1,"\n") - end for - printf(1,"Completed in %s\n",elapsed(time()-t0)) - 101,111,121,131,141,151,161,171,181,191,202, .. // 10,False --> 1001,1111,1221,1331,1441,1551,1661,1771,1881,.. -fcn createPalindromeW(start,oddLength){ //--> iterator +fcn createPalindromeW(start,oddLength){ //--> iterator [start..].tweak('wrap(z){ p,n := z,z; if(oddLength) n/=10; @@ -8,7 +8,7 @@ fcn createPalindromeW(start,oddLength){ //--> iterator p }) } -fcn palindromicGapfulW(endsWith){ //--> iterator +fcn palindromicGapfulW(endsWith){ //--> iterator po,pe := createPalindromeW(10,True), createPalindromeW(10,False); div:=endsWith*10 + endsWith; Walker.zero().tweak('wrap{ diff --git a/Task/Palindromic-gapful-numbers/Zkl/palindromic-gapful-numbers-3.zkl b/Task/Palindromic-gapful-numbers/Zkl/palindromic-gapful-numbers-3.zkl index e5469f7a93..bc8d921cb3 100644 --- a/Task/Palindromic-gapful-numbers/Zkl/palindromic-gapful-numbers-3.zkl +++ b/Task/Palindromic-gapful-numbers/Zkl/palindromic-gapful-numbers-3.zkl @@ -5,6 +5,6 @@ fcn palGT(n,N,sz){ palindromicGapfulW(n).drop(N-sz).walk(sz) } // worker thread foreach N,sz in (T( T(100_000,1) )){ println("\nLast %d of %,d palindromic gapful numbers:".fmt(sz,N)); [1..9].apply('wrap(n){ palGT.future(n,N,sz) }) // create threads - .apply("noop") // wait for threads to finish + .apply("noop") // wait for threads to finish : pgpp(_); } diff --git a/Task/Pancake-numbers/00-TASK.txt b/Task/Pancake-numbers/00-TASK.txt index 8d7a359cf8..c1308a4030 100644 --- a/Task/Pancake-numbers/00-TASK.txt +++ b/Task/Pancake-numbers/00-TASK.txt @@ -1,4 +1,4 @@ -Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stacked in ascending order of size she leaves him only a skillet which he can insert at any point in the pile and flip all the above pancakes, repeating until the pile is sorted. Sharona has left the pile of n pancakes such that the maximum number of flips is required. Adrian is determined to do this in as few flips as possible. This sequence n->p(n) is known as the Pancake numbers. +Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. Two pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stacked in ascending order of size she leaves him only a skillet which he can insert at any point in the pile and flip all the above pancakes, repeating until the pile is sorted. Sharona has left the pile of n pancakes such that the maximum number of flips is required. Adrian is determined to do this in as few flips as possible. This sequence n->p(n) is known as the Pancake numbers. The task is to determine p(n) for n = 1 to 9, and for each show an example requiring p(n) flips. @@ -6,9 +6,10 @@ The task is to determine p(n) for n = 1 to 9, and for each show an example requi Few people know p(20), generously I shall award an extra credit for anyone doing more than p(16). +; Warning: It is known that p(19) is 22 (see in particular the discussion at [https://oeis.org/A058986 A058986]); thus any algorithm that claims otherwise must be treated with caution.
    +: Note that the original "cheeky partial answer" of [[Pancake_numbers#Phix|Phix]] has since been updated (5/12/2020), and/but just that, with no examples as asked for, ''will'' get your entry marked as incomplete. ;References -# [https://www.bbvaopenmind.com/en/science/mathematics/bill-gates-and-the-pancake-problem Bill Gates and the pancake problem] +# [https://web.archive.org/web/20240525075316/https://www.bbvaopenmind.com/en/science/mathematics/bill-gates-and-the-pancake-problem/ Bill Gates and the pancake problem] # [https://oeis.org/A058986 A058986]

    - diff --git a/Task/Pancake-numbers/ARM-Assembly/pancake-numbers.arm b/Task/Pancake-numbers/ARM-Assembly/pancake-numbers.arm new file mode 100644 index 0000000000..c05f240a1e --- /dev/null +++ b/Task/Pancake-numbers/ARM-Assembly/pancake-numbers.arm @@ -0,0 +1,393 @@ +/* ARM assembly Raspberry PI */ +/* program pancake number */ +/* */ + + /* REMARK 1 : this program use routines in a include file + see task Include a file language arm assembly + for the routine affichageMess conversion10 + see at end of this program the instruction include */ +/* for constantes see task include a file in arm assembly */ +/************************************/ +/* Constantes */ +/************************************/ +.include "../constantes.inc" +.equ NBPANCAKEMAX, 30 +.equ NBQUEUEITEM, 5000000 +.equ NBVALUEMAX, 15 +.equ NUMPAN, 10 + +/************************************/ +/* Macros */ +/************************************/ +//.include "../../ficmacros32.inc" @ use for developper debugging + +/*******************************************/ +/* Structures */ +/********************************************/ + +/* structure pancake flip*/ + .struct 0 +Pan_left: @ next element left + .struct Pan_left + 4 +Pan_right: @ next element right + .struct Pan_right + 4 +Pan_value: @ + .struct Pan_value + NBVALUEMAX +Pan_flips: + .struct Pan_flips + 1 @ flips counter +Pan_end: +/*********************************/ +/* Initialized data */ +/*********************************/ +.data +szMessStart: .asciz "Program 32 bits start.\n" +szMessFinOK: .asciz "Program normal end. \n" +szMessError: .asciz "ERROR array flips too small.\n" +szMessErrnotFind: .asciz "Address not find in area.\n" + +szCarriageReturn: .asciz "\n" +szMessResHead: .asciz "Pancake : @ " +szMessResLib: .asciz "Flips : @ example : " +sMessResult: .asciz " @," + +.align 4 + +QueuePancake: .skip 4 * NBQUEUEITEM +EndQueuePancake: +/*********************************/ +/* UnInitialized data */ +/*********************************/ +.bss +sZoneConv: .skip 24 +iCptMax: .skip 4 +iAdddressMax: .skip 4 +Pancakes: .skip 4 * NBPANCAKEMAX +arrayFlips: .skip Pan_end * NBQUEUEITEM + +iQueueStart: .skip 4 @ queue start pointer +iQueueEnd: .skip 4 @ queue end pointer +areaFlipTemp: .skip 4+NBVALUEMAX + + +/*********************************/ +/* code section */ +/*********************************/ +.text +.global main +main: @ entry of program + ldr r0,iAdrszMessStart + bl affichageMess + mov r4,#2 @ pancake number +1: + mov r0,r4 + bl pancakesNum + add r4,r4,#1 + cmp r4,#NUMPAN + ble 1b + + ldr r0,iAdrszMessFinOK + bl affichageMess +100: @ standard end of the program + mov r0, #0 @ return code + mov r7, #EXIT @ request to exit program + svc #0 @ perform the system call + +iAdrszCarriageReturn: .int szCarriageReturn +iAdrsMessResult: .int sMessResult +iAdrszMessStart: .int szMessStart +iAdrszMessFinOK: .int szMessFinOK +/******************************************************************/ +/* pancake Number */ +/******************************************************************/ +/* r0 contains pancake number */ +pancakesNum: @ INFO: pancakesNum + push {r2-r4,lr} + mov r4,r0 + mov r1,#1 + ldr r2,iAdriCptMax + str r1,[r2] + mov r10,#1 @ max flips counter + ldr r0,iAdrQueuePancake + ldr r1,iAdriQueueStart + str r0,[r1] + ldr r1,iAdriQueueEnd + str r0,[r1] + ldr r11,iAdrarrayFlips @ flips array item 0 + ldr r0,iAdriAdddressMax + str r11,[r0] @ init with flips array item 0 + mov r3,#0 @ init pointer + str r3,[r11,#Pan_left] + str r3,[r11,#Pan_right] + strb r3,[r11,#Pan_flips] @ init counter flips + add r6,r11,#Pan_value + mov r1,#1 +1: @ init flips area with first combinaison + str r1,[r6,r3] + add r3,r3,#1 + add r1,r1,#1 + cmp r1,r4 + ble 1b + @ init queue + ldr r0,iAdrQueuePancake + str r11,[r0] @ init with first item + add r0,r0,#4 + ldr r1,iAdriQueueEnd + str r0,[r1] + mov r12,#1 @ indice flip area + +2: + ldr r1,iAdriQueueEnd + ldr r1,[r1] @ load end queue pointer + ldr r2,iAdriQueueStart + ldr r0,[r2] @ load start queue pointer + cmp r1,r0 @ end queue ? + beq 20f + ldr r5,[r0] @ load value to start pointer + add r0,r0,#4 @ new start queue pointer + str r0,[r2] @ and store + + + add r0,r5,#Pan_flips + ldrb r9,[r0] + add r9,r9,#1 @ flip + 1 + mov r8,#1 @ poste 1 +5: @ start loop + mov r0,r5 @ address pancake area + + mov r1,#0 + mov r2,r4 + mov r3,r8 + bl flip + cmp r0,#-1 + beq 99f + mov r7,r0 @ flipped + + mov r1,r11 @ area pancake address + mov r2,r4 + mov r3,r12 + bl searchArea + cmp r0,#-1 + beq 10f @ find -> next loop + mov r3,#Pan_end + mul r6,r3,r12 + add r6,r6,r11 + cmp r0,#0 + streq r6,[r1,#Pan_left] + strne r6,[r1,#Pan_right] + strb r9,[r6,#Pan_flips] + + add r3,r6,#Pan_value + ldr r2,iAdrareaFlipTemp + add r2,r2,#Pan_value + mov r0,#0 + str r0,[r6,#Pan_left] + str r0,[r6,#Pan_right] + 6: + ldrb r1,[r2,r0] + strb r1,[r3,r0] + add r0,r0,#1 + cmp r0,r4 + blt 6b + + add r12,r12,#1 @ + ldr r0,iMaxItem + cmp r12,r0 + bge 99f + ldr r0,iAdriQueueEnd + ldr r1,[r0] @ load end queue pointer + str r6,[r1] @ add fliped in queue + add r1,r1,#4 + ldr r2,iAdrEndQueuePancake + ldr r2,[r2] + cmp r1,r2 @ maxi ? + bge 99f + + str r1,[r0] @ store next end queue pointer + cmp r9,r10 + ble 10f + mov r10,r9 + ldr r0,iAdriAdddressMax + str r7,[r0] +10: @ loops + + add r8,r8,#1 + cmp r8,r4 + blt 5b + b 2b +20: + mov r0,r4 + ldr r1,iAdrsZoneConv + bl conversion10 @ décimal conversion + add r1,r1,r0 + mov r0,#0 + strb r0,[r1] + ldr r0,iAdrszMessResHead + ldr r1,iAdrsZoneConv @ insert conversion + bl strInsertAtCharInc + bl affichageMess + mov r0,r10 + ldr r1,iAdrsZoneConv + bl conversion10 @ décimal conversion + add r1,r1,r0 + mov r0,#0 + strb r0,[r1] + ldr r0,iAdrszMessResLib + ldr r1,iAdrsZoneConv @ insert conversion + bl strInsertAtCharInc + bl affichageMess + + ldr r1,iAdriAdddressMax + ldr r0,[r1] + mov r1,r4 + bl displayTable + b 100f +98: + affregtit erreur + ldr r0,iAdrszMessErrnotFind + bl affichageMess + mov r0,#-1 +99: + ldr r0,iAdrszMessError + bl affichageMess + mov r0,#-1 +100: + pop {r2-r4,pc} +iAdrPancakes: .int Pancakes +iAdrQueuePancake: .int QueuePancake +iAdriQueueStart: .int iQueueStart +iAdriQueueEnd: .int iQueueEnd +iAdrEndQueuePancake: .int EndQueuePancake +iAdrarrayFlips: .int arrayFlips + +iAdrszMessError: .int szMessError +iAdriCptMax: .int iCptMax +iAdriAdddressMax: .int iAdddressMax +iAdrszMessErrnotFind: .int szMessErrnotFind +iAdrszMessResHead: .int szMessResHead +iAdrszMessResLib: .int szMessResLib +iMaxItem: .int NBQUEUEITEM +/******************************************************************/ +/* flip */ +/******************************************************************/ +/* r0 contains the address of table */ +/* r1 contains first start index +/* r2 contains the number of elements */ +/* r3 contains the position of flip */ +flip: @ INFO: flip + push {r1-r8,lr} @ save registers + mov r5,r0 + ldr r8,iAdrareaFlipTemp + mov r4,#Pan_value + mov r0,#0 + add r7,r8,#Pan_value + add r4,r4,r5 +1: @ copy area loop + + ldrb r6,[r4,r0] + strb r6,[r7,r0] + add r0,r0,#1 + cmp r0,r2 + blt 1b @ loop + + mov r0,r7 + cmp r3,r2 + subge r3,r2,#1 @ last index if position >= size +2: + cmp r1,r3 + bge 3f + ldrb r5,[r0,r1] @ load value first index + ldrb r6,[r0,r3] @ load value position index + strb r6,[r0,r1] @ inversion + strb r5,[r0,r3] @ + sub r3,r3,#1 + add r1,r1,#1 + b 2b +3: + mov r0,r8 @ return flip area temp +100: + pop {r1-r8,pc} +iAdrareaFlipTemp: .int areaFlipTemp +/******************************************************************/ +/* search area in table area */ +/******************************************************************/ +/* r0 contains the address area to search */ +/* r1 contains address area address +/* r2 nombre elements */ +/* r3 nombre address area */ +/* r0 return -1 if find, 0 if pointer left, 1 if pointer right */ +/* r1 return address item */ +searchArea : + push {r4-r11,lr} @ save registers + mov r7,#0 + mov r9,#Pan_end + add r10,r0,#Pan_value + mov r6,r1 +1: @ loop begin + mov r8,#0 @ indice value array + add r5,r6,#Pan_value @ load value address +2: + ldrb r4,[r10,r8] @ load one value to search + ldrb r11,[r5,r8] @ load one value to tree + add r8,r8,#1 + cmp r4,r11 @ compare value + blt 3f @ smaller + bgt 4f @ highter + cmp r8,r2 @ end value ? + blt 2b @ no -> loop + mov r0,#-1 @ equal return -1 + b 100f +3: @ smaller + ldr r4,[r6,#Pan_left] @ load left pointer + cmp r4,#0 @ end ? + movne r6,r4 + bne 1b @ loop + mov r1,r6 @ last pointer address + mov r0,#0 @ not find pointer left + b 100f +4: @ highter + ldr r4,[r6,#Pan_right] @ load right pointer + cmp r4,#0 + movne r6,r4 + bne 1b + mov r1,r6 @ last pointer address + mov r0,#1 @ not find pointer right +100: + pop {r4-r11,pc} + + +/******************************************************************/ +/* Display table elements */ +/******************************************************************/ +/* r0 contains the address of table */ +/* r1 contains elements number */ +displayTable: @ INFO: displayTable + push {r0-r3,lr} @ save registers + mov r4,r1 + add r2,r0,#Pan_value + mov r3,#0 +1: @ loop display table + ldrb r0,[r2,r3] + ldr r1,iAdrsZoneConv + bl conversion10 @ décimal conversion + add r1,r1,r0 + mov r0,#0 + strb r0,[r1] + ldr r0,iAdrsMessResult + ldr r1,iAdrsZoneConv @ insert conversion + bl strInsertAtCharInc + bl affichageMess @ display message + add r3,#1 + cmp r3,r4 + blt 1b + ldr r0,iAdrszCarriageReturn + bl affichageMess + mov r0,r2 +100: + pop {r0-r3,lr} + bx lr +iAdrsZoneConv: .int sZoneConv + +/***************************************************/ +/* ROUTINES INCLUDE */ +/***************************************************/ +.include "../affichage.inc" diff --git a/Task/Pancake-numbers/Applesoft-BASIC/pancake-numbers.basic b/Task/Pancake-numbers/Applesoft-BASIC/pancake-numbers.basic index 6fbf69ed83..2a8a01ddd8 100644 --- a/Task/Pancake-numbers/Applesoft-BASIC/pancake-numbers.basic +++ b/Task/Pancake-numbers/Applesoft-BASIC/pancake-numbers.basic @@ -2,12 +2,11 @@ 110 FOR I = 0 TO 3 120 FOR J = 1 TO 5 130 LET N = (I * 5) + J -140 LET C = C + 1 -150 GOSUB 200 -160 PRINT "p("; N; ") = "; P; " " -170 NEXT J -180 NEXT I -190 END +140 GOSUB 200 +150 PRINT "p("; N; ") = "; P; " " +160 NEXT J +170 NEXT I +180 END 200 REM pancake(n) 210 LET G = 2 : LET S = 2 : LET A = -1 220 IF S < N THEN LET A = A + 1 : LET G = (G * 2) - 1 : LET S = S + G diff --git a/Task/Pancake-numbers/Asymptote/pancake-numbers.asymptote b/Task/Pancake-numbers/Asymptote/pancake-numbers.asymptote new file mode 100644 index 0000000000..23137be42e --- /dev/null +++ b/Task/Pancake-numbers/Asymptote/pancake-numbers.asymptote @@ -0,0 +1,18 @@ +int Pancake(int n) { + int gap = 2; + int sum = 2; + int adj = -1; + while (sum < n) { + adj += 1; + gap = (gap * 2) - 1; + sum += gap; + } + return n + adj; +} + +for (int i = 0; i <= 3; ++i) { + for (int j = 1; j <= 5; ++j) { + int n = (i * 5) + j; + write("p(" + string(n) + ") = " + string(Pancake(n))); + } +} diff --git a/Task/Pancake-numbers/C++/pancake-numbers.cpp b/Task/Pancake-numbers/C++/pancake-numbers.cpp index 70a3d06253..e7c8202a2e 100644 --- a/Task/Pancake-numbers/C++/pancake-numbers.cpp +++ b/Task/Pancake-numbers/C++/pancake-numbers.cpp @@ -1,52 +1,49 @@ -#include -#include #include -#include -#include -#include +#include #include +#include +#include +#include +#include +#include -std::vector flip_stack(std::vector& stack, const int32_t index) { - reverse(stack.begin(), stack.begin() + index); +std::vector flip_stack(std::vector stack, const uint32_t& index) { + std::reverse(stack.begin(), stack.begin() + index); return stack; } -std::pair, int32_t> pancake(const int32_t number) { - std::vector initial_stack(number); +std::pair, uint32_t> pancake(const uint32_t& number) { + std::vector initial_stack(number); std::iota(initial_stack.begin(), initial_stack.end(), 1); - std::map, int32_t> stack_flips = { std::make_pair(initial_stack, 1) }; - std::queue> queue; + std::map, uint32_t> stack_flips = { std::make_pair(initial_stack, 0) }; + std::queue> queue; queue.push(initial_stack); while ( ! queue.empty() ) { - std::vector stack = queue.front(); + std::vector stack = queue.front(); queue.pop(); - const int32_t flips = stack_flips[stack] + 1; - for ( int i = 2; i <= number; ++i ) { - std::vector flipped = flip_stack(stack, i); - if ( stack_flips.find(flipped) == stack_flips.end() ) { + const uint32_t flips = stack_flips[stack] + 1; + for ( uint32_t i = 2; i <= number; ++i ) { + std::vector flipped = flip_stack(stack, i); + if ( ! stack_flips.contains(flipped) ) { stack_flips[flipped] = flips; queue.push(flipped); } } } - auto ptr = std::max_element( - stack_flips.begin(), stack_flips.end(), - [] ( const auto & pair1, const auto & pair2 ) { - return pair1.second < pair2.second; - } - ); + const auto ptr = std::max_element(stack_flips.begin(), stack_flips.end(), + [](const auto& pair1, const auto& pair2){ return pair1.second < pair2.second; }); return std::make_pair(ptr->first, ptr->second); } int main() { - for ( int32_t n = 1; n <= 9; ++n ) { - std::pair, int32_t> result = pancake(n); + for ( uint32_t n = 1; n <= 9; ++n ) { + std::pair, uint32_t> result = pancake(n); std::cout << "pancake(" << n << ") = " << std::setw(2) << result.second << ". Example ["; - for ( uint64_t i = 0; i < result.first.size() - 1; ++i ) { + for ( uint32_t i = 0; i < result.first.size() - 1; ++i ) { std::cout << result.first[i] << ", "; } std::cout << result.first.back() << "]" << std::endl; diff --git a/Task/Pancake-numbers/COBOL/pancake-numbers.cob b/Task/Pancake-numbers/COBOL/pancake-numbers.cob new file mode 100644 index 0000000000..de94ff4913 --- /dev/null +++ b/Task/Pancake-numbers/COBOL/pancake-numbers.cob @@ -0,0 +1,35 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. Pancake. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 I PIC 9 VALUE 0. + 01 J PIC 9 VALUE 0. + 01 N PIC 99 VALUE 0. + 01 C PIC 99 VALUE 0. + 01 P PIC 99 VALUE 0. + 01 GAP PIC 99 VALUE 2. + 01 SUMA PIC 99 VALUE 2. + 01 ADJ PIC S99 VALUE -1. + + PROCEDURE DIVISION. + PERFORM VARYING I FROM 0 BY 1 UNTIL I > 3 + PERFORM VARYING J FROM 1 BY 1 UNTIL J > 5 + COMPUTE N = (I * 5) + J + ADD 1 TO C + PERFORM PANCAKE-CALCULATION + DISPLAY "P(" N ") = " P + END-PERFORM + END-PERFORM + STOP RUN. + + PANCAKE-CALCULATION. + MOVE 2 TO GAP + MOVE 2 TO SUMA + MOVE -1 TO ADJ + PERFORM UNTIL SUMA >= N + ADD 1 TO ADJ + COMPUTE GAP = (GAP * 2) - 1 + ADD GAP TO SUMA + END-PERFORM + COMPUTE P = N + ADJ. diff --git a/Task/Pancake-numbers/Dart/pancake-numbers.dart b/Task/Pancake-numbers/Dart/pancake-numbers.dart new file mode 100644 index 0000000000..552624f217 --- /dev/null +++ b/Task/Pancake-numbers/Dart/pancake-numbers.dart @@ -0,0 +1,20 @@ +void main() { + for (int i = 0; i <= 3; i++) { + for (int j = 1; j <= 5; j++) { + int n = (i * 5) + j; + print("p(${n.toString().padLeft(2, ' ')}) = ${pancake(n).toString().padLeft(2, ' ')}"); + } + } +} + +int pancake(int n) { + int gap = 2; + int sum = 2; + int adj = -1; + while (sum < n) { + adj++; + gap = (gap * 2) - 1; + sum += gap; + } + return n + adj; +} diff --git a/Task/Pancake-numbers/Free-Pascal-Lazarus/pancake-numbers.pas b/Task/Pancake-numbers/Free-Pascal-Lazarus/pancake-numbers.pas new file mode 100644 index 0000000000..2a8944a07d --- /dev/null +++ b/Task/Pancake-numbers/Free-Pascal-Lazarus/pancake-numbers.pas @@ -0,0 +1,31 @@ +program pc; + +function pancake(n:integer):integer; +var + gap, sum, adj:integer; +begin + gap := 2; + sum := 2; + adj := -1; + while sum < n do + begin + inc(adj); + gap := gap*2 - 1; + sum := sum + gap; + end; + pancake := n + adj; +end; + +var + i,j,n:integer; +begin + for i := 0 to 3 do + begin + for j := 1 to 5 do + begin + n := i*5 + j; + writeln('p',n:2,pancake(n):5); + end; + writeln; + end +end. diff --git a/Task/Pancake-numbers/FreeBASIC/pancake-numbers-1.basic b/Task/Pancake-numbers/FreeBASIC/pancake-numbers-1.basic new file mode 100644 index 0000000000..7b45c49976 --- /dev/null +++ b/Task/Pancake-numbers/FreeBASIC/pancake-numbers-1.basic @@ -0,0 +1,37 @@ +Function pancake(n As Integer) As Integer + Dim As Integer gap, pg, gapsum, adj, temp + + gap = 2 + pg = 1 + gapsum = gap + adj = -1 + While gapsum < n + adj += 1 + temp = gap + gap += pg + pg = temp + gapsum += gap + Wend + + Return n + adj +End Function + +' Main program +Dim As Integer numbers(1 To 20), results(1 To 20) +Dim As Integer i, row, col, idx + +' Generate sequence 1 to 20 +For i = 1 To 20 + numbers(i) = i + results(i) = pancake(i) +Next i + +For row = 0 To 3 + For col = 1 To 5 + idx = row * 5 + col + Print Using "p(##) = ## "; numbers(idx); results(idx); + Next col + Print +Next row + +Sleep diff --git a/Task/Pancake-numbers/FreeBASIC/pancake-numbers-2.basic b/Task/Pancake-numbers/FreeBASIC/pancake-numbers-2.basic new file mode 100644 index 0000000000..ab2bdc910f --- /dev/null +++ b/Task/Pancake-numbers/FreeBASIC/pancake-numbers-2.basic @@ -0,0 +1,105 @@ +' Reverses the first k elements of a string +Function flipString(s As String, k As Integer) As String + Dim As String res = "" + For i As Integer = k To 1 Step -1 + res &= Mid(s, i, 1) + Next + res &= Mid(s, k + 1) + Return res +End Function + +' Calculate the lexicographic rank of a permutation +Function permutationRank(s As String, n As Integer, fact() As Integer) As Integer + Dim As Integer rank = 0 + For i As Integer = 0 To n - 2 + Dim As Integer cnt = 0 + For j As Integer = i + 1 To n - 1 + If Mid(s, j + 1, 1) < Mid(s, i + 1, 1) Then cnt += 1 + Next + rank += cnt * fact(n - i - 1) + Next + Return rank +End Function + +' Calculate the maximum number of flips for n elements +Sub pancakeNumber(n As Integer) + Dim As Integer i + ' Pre-calculate factorials + Dim As Integer fact(0 To n) + fact(0) = 1 + For i = 1 To n: fact(i) = fact(i - 1) * i: Next + + Dim As Integer totalStates = fact(n) + Dim As Boolean visited(0 To totalStates - 1) + Dim As Integer dist(0 To totalStates - 1) + Dim As String permString(0 To totalStates - 1) + + ' Initial state: ordered permutation + Dim As String start = "" + For i = 1 To n: start &= Str(i): Next + + Dim As Integer startRank = permutationRank(start, n, fact()) + visited(startRank) = True + dist(startRank) = 0 + permString(startRank) = start + + Dim As String queue(0 To totalStates - 1) + Dim As Integer head = 0, tail = 0 + queue(tail) = start + tail += 1 + + ' BFS (Breadth-First Search) to determine the maximum distance from any permutation to the ordinate + While head < tail + Dim As String p = queue(head) + head += 1 + Dim As Integer currentRank = permutationRank(p, n, fact()) + + ' Generar todos los flips posibles + ' Generate all possible flips + For i As Integer = 2 To n + Dim As String q = flipString(p, i) + Dim As Integer r = permutationRank(q, n, fact()) + + If Not visited(r) Then + visited(r) = True + dist(r) = dist(currentRank) + 1 + permString(r) = q + queue(tail) = q + tail += 1 + End If + Next + Wend + + ' Find the maximum distance + Dim As Integer maxDist = 0 + Dim As String maxPerm = "" + For i = 0 To totalStates - 1 + If visited(i) Andalso dist(i) > maxDist Then + maxDist = dist(i) + maxPerm = permString(i) + End If + Next + + ' If no permutation was found (case n=1), use the ordinate + If Len(maxPerm) = 0 Then + For i = 1 To n: maxPerm &= Str(i): Next + End If + + Print Using "Maximum number of flips to sort # elements is ##_. e.g ["; n; maxDist; + For i = 1 To Len(maxPerm) + If i > 1 Then Print "; "; + Print Mid(maxPerm, i, 1); + Next + Print "] -> ["; + For i = 1 To n + If i > 1 Then Print "; "; + Print Str(i); + Next + Print "]" +End Sub + +For n As Integer = 1 To 9 + pancakeNumber(n) +Next + +Sleep diff --git a/Task/Pancake-numbers/FreeBASIC/pancake-numbers.basic b/Task/Pancake-numbers/FreeBASIC/pancake-numbers.basic deleted file mode 100644 index fccbd46483..0000000000 --- a/Task/Pancake-numbers/FreeBASIC/pancake-numbers.basic +++ /dev/null @@ -1,23 +0,0 @@ -Dim As Integer num_pancakes = 20 -Dim As Integer i, j, c = 0, n - -Function pancake(n As Integer) As Integer - Dim As Integer gap = 2, sum = 2, adj = -1 - While sum < n - adj += 1 - gap = (gap * 2) - 1 - sum += gap - Wend - Return n + adj -End Function - -For i = 0 To 3 - For j = 1 To 5 - n = (i * 5) + j - c += 1 - Print Using "p(##) = ## "; n; pancake(n); - If c Mod 5 = 0 Then Print - Next j -Next i - -Sleep diff --git a/Task/Pancake-numbers/Gambas/pancake-numbers.gambas b/Task/Pancake-numbers/Gambas/pancake-numbers.gambas index 5056e83a0c..042c109d2d 100644 --- a/Task/Pancake-numbers/Gambas/pancake-numbers.gambas +++ b/Task/Pancake-numbers/Gambas/pancake-numbers.gambas @@ -1,27 +1,43 @@ +Public numbers[20] As Integer +Public results[20] As Integer + Public Sub Main() - Dim i As Integer, j As Integer, c As Integer = 0, n As Integer + Dim i As Integer, row As Integer, col As Integer, idx As Integer - For i = 0 To 3 - For j = 1 To 5 - n = (i * 5) + j - c += 1 - Print "p("; Format$(n, "##"); ") = "; Format$(pancake(n), "##"); " "; - If c Mod 5 = 0 Then Print + ' Generate sequence 1 to 20 + For i = 0 To 19 + numbers[i] = i + 1 + results[i] = pancake(i + 1) + Next + + For row = 0 To 3 + For col = 0 To + idx = row * 5 + col + Print "p("; Format$(numbers[idx], "##"); ") = "; Format$(results[idx], "##"); " "; Next + Print Next End Function pancake(n As Integer) As Integer - Dim gap As Integer = 2, sum As Integer = 2, adj As Integer = -1 + Dim gap As Integer, pg As Integer, gapsum As Integer, adj As Integer, tmp As Integer - While sum < n + gap = 2 + pg = 1 + gapsum = gap + adj = -1 + + While gapsum < n adj += 1 - gap = (gap * 2) - 1 - sum += gap + tmp = gap + gap += pg + pg = tmp + gapsum += gap Wend + Return n + adj End Function diff --git a/Task/Pancake-numbers/Go/pancake-numbers-2.go b/Task/Pancake-numbers/Go/pancake-numbers-2.go index ac5b914b51..ec240d45dc 100644 --- a/Task/Pancake-numbers/Go/pancake-numbers-2.go +++ b/Task/Pancake-numbers/Go/pancake-numbers-2.go @@ -7,19 +7,42 @@ import ( "time" ) -type assoc map[string]int +const MAX_N = 10 -// Converts a string of the form "[1 2]" into a slice of ints: {1, 2} -func asSlice(s string) []int { - split := strings.Split(s[1:len(s)-1], " ") - le := len(split) - res := make([]int, le) - for i := 0; i < le; i++ { - res[i], _ = strconv.Atoi(split[i]) - } - return res +// store sequences in 2 int64s, 5 bits per number +// (12 in each int64, ignoring the top 4 bits) +// this will support length 24 or less +type Sequence struct { + num1 int64 + num2 int64 } +// get the number at position n in the sequence +func (s *Sequence) get(n int64) int64 { + if n > 12 { + n = (n - 12) * 5 + return (s.num2 & (31 << n)) >> n + } else { + n *= 5 + return (s.num1 & (31 << n)) >> n + } +} + +// set value at position n in the sequence +func (s *Sequence) set(n int64, value int64) { + if n > 12 { + n = (n - 12) * 5 + var bits int64 = 31 << n + s.num2 = (s.num2 | bits) ^ bits | (value << n) + } else { + n *= 5 + var bits int64 = 31 << n + s.num1 = (s.num1 | bits) ^ bits | (value << n) + } +} + +type assoc map[Sequence]int + // Merges two assocs into one. If the same key is present in both assocs // its value will be the one in the second assoc. func merge(m1, m2 assoc) assoc { @@ -35,11 +58,11 @@ func merge(m1, m2 assoc) assoc { // Finds the maximum value in 'dict' and returns the first key // it finds (iteration order is undefined) with that value. -func findMax(dict assoc) string { +func findMax(dict assoc) Sequence { max := -1 - maxKey := "" + var maxKey Sequence for k, v := range dict { - if v > max { + if v > max { max = v maxKey = k } @@ -47,32 +70,32 @@ func findMax(dict assoc) string { return maxKey } -// Creates a new slice of ints by reversing an existing one. -func reverse(s []int) []int { - le := len(s) - rev := make([]int, le) - for i := 0; i < le; i++ { - rev[i] = s[le-1-i] +// reverse order up to pos +func reorder(stack Sequence, pos int64) Sequence { + for i := int64(0); i < pos / 2; i++ { + j := pos - i - 1 + a := stack.get(i) + b := stack.get(j) + stack.set(i, b) + stack.set(j, a) } - return rev + return stack } -func pancake(n int) (string, int) { +func pancake(n int64) (Sequence, int) { numStacks := 1 - gs := make([]int, n) - for i := 0; i < n; i++ { - gs[i] = i + 1 + + goalStack := Sequence{} + for i := int64(0); i < n; i++ { + goalStack.set(i, i+1) } - goalStack := fmt.Sprintf("%v", gs) stacks := assoc{goalStack: 0} newStacks := assoc{goalStack: 0} - for i := 1; i <= 1000; i++ { + for i := 1; ; i++ { nextStacks := assoc{} - for key := range newStacks { - arr := asSlice(key) - for pos := 2; pos <= n; pos++ { - t := append(reverse(arr[0:pos]), arr[pos:len(arr)]...) - newStack := fmt.Sprintf("%v", t) + for stack := range newStacks { + for pos := int64(2); pos <= n; pos++ { + newStack := reorder(stack, pos) if _, ok := stacks[newStack]; !ok { nextStacks[newStack] = i } @@ -86,15 +109,19 @@ func pancake(n int) (string, int) { } numStacks = perms } - return "", 0 + return Sequence{}, 0 } func main() { start := time.Now() fmt.Println("The maximum number of flips to sort a given number of elements is:") - for i := 1; i <= 10; i++ { + for i := int64(1); i <= MAX_N; i++ { example, steps := pancake(i) - fmt.Printf("pancake(%2d) = %-2d example: %s\n", i, steps, example) + example_strs := make([]string, i) + for j := int64(0); j < i; j++ { + example_strs[j] = strconv.Itoa(int(example.get(j))) + } + fmt.Printf("pancake(%2d) = %-2d example: %s\n", i, steps, strings.Join(example_strs, " ")) } fmt.Printf("\nTook %s\n", time.Since(start)) } diff --git a/Task/Pancake-numbers/Java/pancake-numbers-1.java b/Task/Pancake-numbers/Java/pancake-numbers-1.java index 126c595da8..a061523e2b 100644 --- a/Task/Pancake-numbers/Java/pancake-numbers-1.java +++ b/Task/Pancake-numbers/Java/pancake-numbers-1.java @@ -1,23 +1,31 @@ -public class Pancake { - private static int pancake(int n) { - int gap = 2; - int sum = 2; - int adj = -1; - while (sum < n) { - adj++; - gap = 2 * gap - 1; - sum += gap; - } - return n + adj; - } - - public static void main(String[] args) { - for (int i = 0; i < 4; i++) { - for (int j = 1; j < 6; j++) { - int n = 5 * i + j; - System.out.printf("p(%2d) = %2d ", n, pancake(n)); +public final class PancakeNumbersApproximation { + + public static void main(String[] args) { + for ( int i = 0; i < 4; i++ ) { + for ( int j = 1; j < 6; j++ ) { + final int n = 5 * i + j; + System.out.print(String.format("%s%2d%s%d%s", "p(", n, ") = ", pancake(n), "\t")); } System.out.println(); } } + + private static int pancake(int number) { + int gap = 2; + int previousGap = 1; + int sumGaps = gap; + int adjustment = -1; + + while ( sumGaps < number ) { + adjustment += 1; + final int previousGapCopy = previousGap; + previousGap = gap; + gap += previousGapCopy; + sumGaps += gap; + } + + number += adjustment; + return number; + } + } diff --git a/Task/Pancake-numbers/Java/pancake-numbers-2.java b/Task/Pancake-numbers/Java/pancake-numbers-2.java index 7c5fc884aa..87518ae864 100644 --- a/Task/Pancake-numbers/Java/pancake-numbers-2.java +++ b/Task/Pancake-numbers/Java/pancake-numbers-2.java @@ -1,47 +1,53 @@ -import static java.util.Comparator.comparing; -import static java.util.stream.Collectors.toList; - import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; +import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Queue; +import java.util.stream.Collectors; import java.util.stream.IntStream; +public final class PancakeNumbers { -public class Pancake { + public static void main(String[] args) { + for ( int n = 1; n <= 9; n++ ) { + PancakeInfo result = pancake(n); + System.out.println(String.format("%s%2d%s", "Pancake(", result.index, "). Example " + result.pancake)); + } + } + + private static PancakeInfo pancake(int number) { + List initialStack = IntStream.rangeClosed(1, number).boxed().collect(Collectors.toList()); + Map, Integer> stackFlips = new HashMap, Integer>(); + stackFlips.put(initialStack, 0); + Queue> queue = new ArrayDeque>(); + queue.add(initialStack); + + while ( ! queue.isEmpty() ) { + List stack = queue.remove(); - private static List flipStack(List stack, int spatula) { - List copy = new ArrayList<>(stack); - Collections.reverse(copy.subList(0, spatula)); + final int flipCount = stackFlips.get(stack) + 1; + for ( int i = 2; i <= number; i++ ) { + List flipped = flipStack(stack, i); + if ( stackFlips.putIfAbsent(flipped, flipCount) == null ) { + queue.add(flipped); + } + } + } + + Map.Entry, Integer> entry = + stackFlips.entrySet().stream().max(Comparator.comparing( e -> e.getValue() )).get(); + return new PancakeInfo(entry.getKey(), entry.getValue()); + } + + private static List flipStack(List stack, int index) { + List copy = new ArrayList(stack); + Collections.reverse(copy.subList(0, index)); return copy; } + + private static record PancakeInfo(List pancake, int index) {} - private static Map.Entry, Integer> pancake(int n) { - List initialStack = IntStream.rangeClosed(1, n).boxed().collect(toList()); - Map, Integer> stackFlips = new HashMap<>(); - stackFlips.put(initialStack, 1); - Queue> queue = new ArrayDeque<>(); - queue.add(initialStack); - while (!queue.isEmpty()) { - List stack = queue.remove(); - int flips = stackFlips.get(stack) + 1; - for (int i = 2; i <= n; ++i) { - List flipped = flipStack(stack, i); - if (stackFlips.putIfAbsent(flipped, flips) == null) { - queue.add(flipped); - } - } - } - return stackFlips.entrySet().stream().max(comparing(e -> e.getValue())).get(); - } - - public static void main(String[] args) { - for (int i = 1; i <= 10; ++i) { - Map.Entry, Integer> result = pancake(i); - System.out.printf("pancake(%s) = %s. Example: %s\n", i, result.getValue(), result.getKey()); - } - } } diff --git a/Task/Pancake-numbers/JavaScript/pancake-numbers.js b/Task/Pancake-numbers/JavaScript/pancake-numbers.js new file mode 100644 index 0000000000..7fad2ff95a --- /dev/null +++ b/Task/Pancake-numbers/JavaScript/pancake-numbers.js @@ -0,0 +1,61 @@ + function flipStack(stack, index) { + const newStack = [...stack]; + let start = 0; + let end = index - 1; + while (start < end) { + const temp = newStack[start]; + newStack[start] = newStack[end]; + newStack[end] = temp; + start++; + end--; + } + return newStack; + } + function pancake(number) { + + const initialStack = Array.from({ length: number }, (_, i) => i + 1); + + const stackFlips = {}; + const initialKey = initialStack.join(','); + stackFlips[initialKey] = 0; + + const queue = [initialStack]; + while (queue.length > 0) { + const stack = queue.shift(); + const key = stack.join(','); + + const flips = stackFlips[key] + 1; + + for (let i = 2; i <= number; ++i) { + const flipped = flipStack(stack, i); + const flippedKey = flipped.join(','); + + if (stackFlips[flippedKey] === undefined) { + stackFlips[flippedKey] = flips; + queue.push(flipped); + } + } + } + + let maxFlips = -1; + let worstStackKey = null; + for (const key in stackFlips) { + if (stackFlips[key] > maxFlips) { + maxFlips = stackFlips[key]; + worstStackKey = key; + } + } + + return { + stack: worstStackKey.split(',').map(Number), + flips: maxFlips + }; + } + + for (let n = 1; n <= 8; ++n) { + const result = pancake(n); + + const flipsStr = String(result.flips).padStart(2, ' '); + + console.log(`pancake(${n}) = ${flipsStr}. Example [${result.stack.join(', ')}]`); + } diff --git a/Task/Pancake-numbers/Jq/pancake-numbers.jq b/Task/Pancake-numbers/Jq/pancake-numbers.jq new file mode 100644 index 0000000000..8ec5fc2d32 --- /dev/null +++ b/Task/Pancake-numbers/Jq/pancake-numbers.jq @@ -0,0 +1,46 @@ +# Input: a JSON object +# Output: the first key found (using keys_unsorted) with a maximal +# associated value, or null +def findMax: + . as $in + | reduce keys_unsorted[] as $key ( null; + if . == null or $in[$key] > .max then {$key, max: $in[$key]} + end ) + | .key; + +# Input: a (small) positive integer +# Output: its pancake number +def pancake: + . as $len + | [range(1; $len + 1)] as $goalStack + | { numStacks: 1, + stacks: {($goalStack|tostring): 0} + } + | .newStacks = .stacks + | first( + foreach range(1;1001) as $i (.; + .nextStacks = {} + | reduce (.newStacks|keys_unsorted)[] as $key (.; + ($key|fromjson) as $arr + | .pos = 2 + | until (.pos > $len; + ((($arr[:.pos] | reverse) + $arr[.pos:]) | tostring) as $newStack + | if (.stacks | has($newStack) | not) + then .nextStacks[$newStack] = $i + end + | .pos += 1 ) ) + | .newStacks = .nextStacks + | .stacks = (.stacks + .newStacks) + | (.stacks|length) as $perms + | if $perms == .numStacks + then .emit = [(.stacks|findMax), $i - 1] + else .numStacks = $perms + end ) + | select(.emit).emit ); + +"The maximum number of flips to sort a given number of elements is:", +(range (1; 11) + | . as $i + | pancake as [$example, $steps] + | "pancake(\($i)) = \($steps) example: \($example)" +) diff --git a/Task/Pancake-numbers/Julia/pancake-numbers-1.julia b/Task/Pancake-numbers/Julia/pancake-numbers-1.julia deleted file mode 100644 index aec090ebde..0000000000 --- a/Task/Pancake-numbers/Julia/pancake-numbers-1.julia +++ /dev/null @@ -1,14 +0,0 @@ -function pancake(len) - gap, gapsum, adj = 2, 2, -1 - while gapsum < len - adj += 1 - gap = gap * 2 - 1 - gapsum += gap - end - return len + adj -end - -for i in 1:25 - print("pancake(", lpad(i, 2), ") = ", rpad(pancake(i), 5)) - i % 5 == 0 && println() -end diff --git a/Task/Pancake-numbers/Julia/pancake-numbers-2.julia b/Task/Pancake-numbers/Julia/pancake-numbers.jl similarity index 100% rename from Task/Pancake-numbers/Julia/pancake-numbers-2.julia rename to Task/Pancake-numbers/Julia/pancake-numbers.jl diff --git a/Task/Pancake-numbers/Kotlin/pancake-numbers-1.kotlin b/Task/Pancake-numbers/Kotlin/pancake-numbers-1.kts similarity index 100% rename from Task/Pancake-numbers/Kotlin/pancake-numbers-1.kotlin rename to Task/Pancake-numbers/Kotlin/pancake-numbers-1.kts diff --git a/Task/Pancake-numbers/Kotlin/pancake-numbers-2.kotlin b/Task/Pancake-numbers/Kotlin/pancake-numbers-2.kts similarity index 100% rename from Task/Pancake-numbers/Kotlin/pancake-numbers-2.kotlin rename to Task/Pancake-numbers/Kotlin/pancake-numbers-2.kts diff --git a/Task/Pancake-numbers/Minimal-BASIC/pancake-numbers.basic b/Task/Pancake-numbers/Minimal-BASIC/pancake-numbers.basic new file mode 100644 index 0000000000..b5413bce58 --- /dev/null +++ b/Task/Pancake-numbers/Minimal-BASIC/pancake-numbers.basic @@ -0,0 +1,22 @@ +110 FOR I = 0 TO 3 +120 FOR J = 1 TO 5 +130 LET N = (I*5)+J +150 GOSUB 200 +160 PRINT "P(";N;") =";P;" " +170 NEXT J +180 NEXT I +190 GOTO 330 +200 REM PANCAKE(N) +210 LET G = 2 +220 LET S = 2 +230 LET A = -1 +240 IF S < N THEN 270 +250 IF S >= N THEN 310 +260 GOTO 240 +270 LET A = A+1 +280 LET G = (G*2)-1 +290 LET S = S+G +300 GOTO 250 +310 LET P = N+A +320 RETURN +330 END diff --git a/Task/Pancake-numbers/PascalABC.NET/pancake-numbers.pas b/Task/Pancake-numbers/PascalABC.NET/pancake-numbers.pas new file mode 100644 index 0000000000..46d45d200b --- /dev/null +++ b/Task/Pancake-numbers/PascalABC.NET/pancake-numbers.pas @@ -0,0 +1,37 @@ +function pancake(n: integer): (integer, string); +begin + var goalstack := '123456789abcd'[:n + 1]; + var stacks := Dict((goalstack, 0)); + var newstacks := Dict((goalstack, 0)); + var numstacks := 1; + foreach var flip in 1..100 do + begin + var nextstacks := new Dictionary; + foreach var nstack in newstacks do + foreach var pos in 2..n do + begin + var newstack := nstack.key[pos::-1] + nstack.key?[pos + 1:]; + if newstack not in stacks then + nextstacks[newstack] := flip; + end; + newstacks := nextstacks; + foreach var nstack in newstacks do stacks[nstack.key] := nstack.value; + var perms := stacks.Count; + if perms = numstacks then + begin + result := stacks.Where(x -> x.value = flip - 1) + .Select(k -> (k.value, k.key)) + .First; + exit + end; + numstacks := perms + end; +end; + +begin + foreach var n in 1..11 do + begin + var (steps, example) := pancake(n); + writeln('pancake(', n:2, ') = ', steps:2, ' example: ', example); + end; +end. diff --git a/Task/Pancake-numbers/Perl/pancake-numbers.pl b/Task/Pancake-numbers/Perl/pancake-numbers.pl index ba93a61a24..4417481d66 100644 --- a/Task/Pancake-numbers/Perl/pancake-numbers.pl +++ b/Task/Pancake-numbers/Perl/pancake-numbers.pl @@ -1,43 +1,23 @@ -use strict; +#!/usr/bin/perl + +use strict; # https://rosettacode.org/wiki/Pancake_numbers use warnings; -use feature 'say'; -sub pancake { - my($n) = @_; - my ($gap, $sum, $adj) = (2, 2, -1); - while ($sum < $n) { $sum += $gap = $gap * 2 - 1 and $adj++ } - $n + $adj; -} - -my $out; -$out .= sprintf "p(%2d) = %2d ", $_, pancake $_ for 1..20; -say $out =~ s/.{1,55}\K /\n/gr; - -# Maximum number of flips plus examples using exhaustive search -sub pancake2 { - my ($n) = @_; - my $numStacks = 1; - my @goalStack = 1 .. $n; - my %newStacks = my %stacks = (join(' ',@goalStack), 0); - for my $k (1..1000) { - my %nextStacks; - for my $pos (2..$n) { - for my $key (keys %newStacks) { - my @arr = split ' ', $key; - my $cakes = join ' ', (reverse @arr[0..$pos-1]), @arr[$pos..$#arr]; - $nextStacks{$cakes} = $k unless $stacks{$cakes}; - } - } - %stacks = (%stacks, (%newStacks = %nextStacks)); - my $perms = scalar %stacks; - my %inverted = reverse %stacks; - return $k-1, $inverted{(sort keys %inverted)[-1]} if $perms == $numStacks; - $numStacks = $perms; - } -} - -say "\nThe maximum number of flips to sort a given number of elements is:"; -for my $n (1..9) { - my ($a,$b) = pancake2($n); - say "pancake($n) = $a example: $b"; -} +for my $n ( 1 .. 9 ) + { + my @queue = my $last = join '', map chr 96 + $_, 1 .. $n; + my %seen = ($last => ''); + while( @queue ) + { + my ($stack, @flips) = split ' ', shift @queue; + for my $flip ( 2 .. $n ) + { + my $new = (reverse substr $stack, 0, $flip) . substr $stack, $flip; + defined $seen{$new} or + push @queue, $last = $seen{$new} = "$new $flip @flips"; + } + } + my ($stack, @flips) = split ' ', $last; + printf "%9s ", $stack; + printf "size %d score: %2d flip the top %s\n", $n, @flips + 0, "@flips"; + } diff --git a/Task/Pancake-numbers/Phix/pancake-numbers-1.phix b/Task/Pancake-numbers/Phix/pancake-numbers-1.phix index 1db5c8c106..8495a5e294 100644 --- a/Task/Pancake-numbers/Phix/pancake-numbers-1.phix +++ b/Task/Pancake-numbers/Phix/pancake-numbers-1.phix @@ -1,17 +1,15 @@ -(phixonline)--> - with javascript_semantics - function pancake(integer n) - integer gap = 2, sum_gaps = gap, adj = -1 - while sum_gaps<n do - adj += 1 - gap = gap*2-1 - sum_gaps += gap - end while - n += adj - return n - end function - sequence t = tagset(20), - r = columnize({t,apply(t,pancake)}), - p = apply(true,sprintf,{{"p(%2d) = %2d"},r}) - printf(1,"%s\n",join_by(p,1,5)) - - with javascript_semantics - function pancake(integer n) - integer gap = 2, pg = 1, sum_gaps = gap, adj = -1 - while sum_gaps<n do - adj += 1 - {pg,gap} = {gap,gap+pg} - sum_gaps += gap - end while - n += adj - return n - end function - sequence t = tagset(20), - r = columnize({t,apply(t,pancake)}), - p = apply(true,sprintf,{{"p(%2d) = %2d"},r}) - printf(1,"%s\n",join_by(p,1,5)) - - with javascript_semantics - function visitor(sequence stack, integer /*unused*/, sequence stacks) - for pos=2 to length(stack) do - -- for pos=0 to length(stack)-2 do - sequence newstack = reverse(stack[1..pos])&stack[pos+1..$] - -- sequence newstack = stack[1..pos]&reverse(stack[pos+1..$]) - if getd_index(newstack,stacks[1])=NULL then - setd(newstack,0,stacks[$]) -- (next round) - setd(newstack,0,stacks[1]) -- (the master) - end if - end for - return 1 - end function +with javascript_semantics +function visitor(sequence stack, integer /*unused*/, sequence stacks) + for pos=2 to length(stack) do +-- for pos=0 to length(stack)-2 do + sequence newstack = reverse(stack[1..pos])&stack[pos+1..$] +-- sequence newstack = stack[1..pos]&reverse(stack[pos+1..$]) + if getd_index(newstack,stacks[1])=NULL then + setd(newstack,0,stacks[$]) -- (next round) + setd(newstack,0,stacks[1]) -- (the master) + end if + end for + return 1 +end function - function pancake(integer len) - sequence goalstack = tagset(len), - stacks = {new_dict({{goalstack,0}})} - while true do - stacks &= new_dict() - -- add any flips of stacks[$-1] - -- not already in stacks[1] - -- to stacks[$] - traverse_dict(visitor,stacks,stacks[$-1]) - if dict_size(stacks[$])=0 then exit end if - end while - sequence eg = getd_partial_key(0,stacks[$-1],true) - integer sz = dict_size(stacks[$-1]) - papply(stacks,destroy_dict) - return {length(stacks)-2,eg,sz} - end function +function pancake(integer len) + sequence goalstack = tagset(len), + stacks = {new_dict({{goalstack,0}})} + while true do + stacks &= new_dict() + -- add any flips of stacks[$-1] + -- not already in stacks[1] + -- to stacks[$] + traverse_dict(visitor,stacks,stacks[$-1]) + if dict_size(stacks[$])=0 then exit end if + end while + sequence eg = getd_partial_key(0,stacks[$-1],true) + integer sz = dict_size(stacks[$-1]) + papply(stacks,destroy_dict) + return {length(stacks)-2,eg,sz} +end function - atom t0 = time() - for n=1 to 8 do -- (for <2s) - {integer pn, sequence eg, integer sz} = pancake(n) - printf(1,"p(%d) = %d, example: %v (of %,d, %s)\n",{n,pn,eg,sz,elapsed(time()-t0)}) - end for - - ?sort(shuffle({5,"oranges",6,"apples",7})) - - with javascript_semantics - enum data, left, right +with javascript_semantics +enum data, left, right - function tmap(sequence tree, integer rid) - tree[data] = rid(tree[data]) - if tree[left]!=null then tree[left] = tmap(deep_copy(tree[left],1),rid) end if - if tree[right]!=null then tree[right] = tmap(deep_copy(tree[right],1),rid) end if - return tree - end function +function tmap(sequence tree, integer rid) + tree[data] = rid(tree[data]) + if tree[left]!=null then tree[left] = tmap(deep_copy(tree[left],1),rid) end if + if tree[right]!=null then tree[right] = tmap(deep_copy(tree[right],1),rid) end if + return tree +end function - function newnode(object v) - return {v,null,null} - end function +function newnode(object v) + return {v,null,null} +end function - function add10(atom x) return x+10 end function +function add10(atom x) return x+10 end function - procedure main() - object root = newnode(1.00) - -- Add some nodes. - root[left] = newnode(1.10) - root[left][left] = newnode(1.11) - root[left][right] = newnode(1.12) +procedure main() + object root = newnode(1.00) + -- Add some nodes. + root[left] = newnode(1.10) + root[left][left] = newnode(1.11) + root[left][right] = newnode(1.12) - root[right] = newnode(1.20) - root[right][left] = newnode(1.21) - root[right][right] = newnode(1.22) + root[right] = newnode(1.20) + root[right][left] = newnode(1.21) + root[right][right] = newnode(1.22) - -- Now the tree has seven nodes. + -- Now the tree has seven nodes. - -- Show the whole tree. - ppOpt({pp_Nest,2}) - pp(root) + -- Show the whole tree. + ppOpt({pp_Nest,2}) + pp(root) - -- Modify the whole tree. - root = tmap(root,add10) + -- Modify the whole tree. + root = tmap(root,add10) - -- Create a whole new tree. - object root2 = tmap(deep_copy(root,1),newnode) + -- Create a whole new tree. + object root2 = tmap(deep_copy(root,1),newnode) - -- Show the whole tree again. - pp(root) - end procedure - main() - - with javascript_semantics - bool show_workings = true +with javascript_semantics +bool show_workings = true - constant operators = {"^","*","/","+","-"}, - precedence = { 4, 3, 3, 2, 2 } +constant operators = {"^","*","/","+","-"}, + precedence = { 4, 3, 3, 2, 2 } - procedure shunting_yard(string infix, rpn) - string res = "", sep = "", stack_top - sequence stack = {}, - ops = split(substitute_all(infix,{"(",")"},{" ( "," ) "}),' ') - printf(1,"Infix input: %-32s%s", {infix,iff(show_workings?'\n':' ')}) - for i=1 to length(ops) do - string op = ops[i] - if op="(" then - stack = append(stack,op) - elsif op=")" then - while 1 do - stack_top = stack[$] - stack = stack[1..$-1] - if stack_top="(" then exit end if - res &= sep&stack_top - sep = " " - end while - else - integer k = find(op,operators) - if k!=0 then - integer prec = precedence[k] - while length(stack) do - stack_top = stack[$] - k = find(stack_top,operators) - if k=0 or prec>precedence[k] - or (prec=precedence[k] and stack_top="^") then - exit - end if - stack = stack[1..$-1] - res &= sep&stack_top - sep = " " - end while - stack = append(stack,op) - else - res &= sep&op - sep = " " - end if - end if - if show_workings then - ?{op,stack,res} - end if - end for - for i=length(stack) to 1 by -1 do - string op = stack[i] - res &= sep&op - sep = " " - end for - printf(1,"result: %-22s [%s]\n", {res,iff(res=rpn?"ok","**ERROR**")}) - end procedure +procedure shunting_yard(string infix, rpn) + string res = "", sep = "", stack_top + sequence stack = {}, + ops = split(substitute_all(infix,{"(",")"},{" ( "," ) "}),' ') + printf(1,"Infix input: %-32s%s", {infix,iff(show_workings?'\n':' ')}) + for i=1 to length(ops) do + string op = ops[i] + if op="(" then + stack = append(stack,op) + elsif op=")" then + while 1 do + stack_top = stack[$] + stack = stack[1..$-1] + if stack_top="(" then exit end if + res &= sep&stack_top + sep = " " + end while + else + integer k = find(op,operators) + if k!=0 then + integer prec = precedence[k] + while length(stack) do + stack_top = stack[$] + k = find(stack_top,operators) + if k=0 or prec>precedence[k] + or (prec=precedence[k] and stack_top="^") then + exit + end if + stack = stack[1..$-1] + res &= sep&stack_top + sep = " " + end while + stack = append(stack,op) + else + res &= sep&op + sep = " " + end if + end if + if show_workings then + ?{op,stack,res} + end if + end for + for i=length(stack) to 1 by -1 do + string op = stack[i] + res &= sep&op + sep = " " + end for + printf(1,"result: %-22s [%s]\n", {res,iff(res=rpn?"ok","**ERROR**")}) +end procedure - shunting_yard("3 + 4 * 2 / (1 - 5) ^ 2 ^ 3","3 4 2 * 1 5 - 2 3 ^ ^ / +") - show_workings = false - shunting_yard("((1 + 2) ^ (3 + 4)) ^ (5 + 6)","1 2 + 3 4 + ^ 5 6 + ^") - shunting_yard("(1 + 2) ^ (3 + 4) ^ (5 + 6)","1 2 + 3 4 + 5 6 + ^ ^") - shunting_yard("((3 ^ 4) ^ 2 ^ 9) ^ 2 ^ 5","3 4 ^ 2 9 ^ ^ 2 5 ^ ^") - shunting_yard("(1 + 4) * (5 + 3) * 2 * 3","1 4 + 5 3 + * 2 * 3 *") - shunting_yard("1 * 2 * 3 * 4","1 2 * 3 * 4 *") - shunting_yard("1 + 2 + 3 + 4","1 2 + 3 + 4 +") - shunting_yard("(1 + 2) ^ (3 + 4)","1 2 + 3 4 + ^") - shunting_yard("(5 ^ 6) ^ 7","5 6 ^ 7 ^") - shunting_yard("5 ^ 4 ^ 3 ^ 2","5 4 3 2 ^ ^ ^") - shunting_yard("1 + 2 + 3","1 2 + 3 +") - shunting_yard("1 ^ 2 ^ 3","1 2 3 ^ ^") - shunting_yard("(1 ^ 2) ^ 3","1 2 ^ 3 ^") - shunting_yard("1 - 1 + 3","1 1 - 3 +") - shunting_yard("3 + 1 - 1","3 1 + 1 -") - shunting_yard("1 - (2 + 3)","1 2 3 + -") - shunting_yard("4 + 3 + 2","4 3 + 2 +") - shunting_yard("5 + 4 + 3 + 2","5 4 + 3 + 2 +") - shunting_yard("5 * 4 * 3 * 2","5 4 * 3 * 2 *") - shunting_yard("5 + 4 - (3 + 2)","5 4 + 3 2 + -") - shunting_yard("3 - 4 * 5","3 4 5 * -") - shunting_yard("3 * (4 - 5)","3 4 5 - *") - shunting_yard("(3 - 4) * 5","3 4 - 5 *") - shunting_yard("4 * 2 + 1 - 5","4 2 * 1 + 5 -") - shunting_yard("4 * 2 / (1 - 5) ^ 2","4 2 * 1 5 - 2 ^ /") - - with javascript_semantics - requires("1.0.2") -- (join(fmt)) - function partition(integer v, n, idx=0) - if n=1 then - return iff(is_prime(v)?{v}:0) - end if - while true do - idx += 1 - integer np = get_prime(idx) - if np>=floor(v/2) then exit end if - object res = partition(v-np, n-1, idx) - if sequence(res) then - res = prepend(res,np) - return res - end if - end while - return 0 - end function +with javascript_semantics +requires("1.0.2") -- (join(fmt)) +function partition(integer v, n, idx=0) + if n=1 then + return iff(is_prime(v)?{v}:0) + end if + while true do + idx += 1 + integer np = get_prime(idx) + if np>=floor(v/2) then exit end if + object res = partition(v-np, n-1, idx) + if sequence(res) then + res = prepend(res,np) + return res + end if + end while + return 0 +end function - constant tests = {{99809, 1}, - {18, 2}, - {19, 3}, - {20, 4}, - {2017, 24}, - {22699, 1}, - {22699, 2}, - {22699, 3}, - {22699, 4}, - {40355, 3}} +constant tests = {{99809, 1}, + {18, 2}, + {19, 3}, + {20, 4}, + {2017, 24}, + {22699, 1}, + {22699, 2}, + {22699, 3}, + {22699, 4}, + {40355, 3}} - for i=1 to length(tests) do - integer {v,n} = tests[i] - object res = partition(v,n) - res = iff(res=0?"not possible":join(res," + ",fmt:="%d")) - printf(1,"Partition %d into %d primes: %s\n",{v,n,res}) - end for - - with javascript_semantics - function partDiffDiff(integer n) - return (n+1)/(1+and_bits(n,1)) - end function +with javascript_semantics +function partDiffDiff(integer n) + return (n+1)/(1+and_bits(n,1)) +end function - sequence pd = {1} - function partDiff(integer n) - while n>length(pd) do - pd &= pd[$] + partDiffDiff(length(pd)) - end while - return pd[max(1,n)] - end function +sequence pd = {1} +function partDiff(integer n) + while n>length(pd) do + pd &= pd[$] + partDiffDiff(length(pd)) + end while + return pd[max(1,n)] +end function - include mpfr.e +include mpfr.e - sequence pn = {mpz_init(1)} - function partitionsP(integer n) - mpz res = mpz_init(1) - while n>length(pn) do - integer nn = length(pn)+1 - mpz psum = mpz_init(0) - for i=1 to nn do - integer pd = partDiff(i) - if pd>nn then exit end if - integer sgn = iff(remainder(i-1,4)<2 ? 1 : -1) - mpz pnmpd = pn[max(1,nn-pd)] - if sgn=-1 then - mpz_sub(psum,psum,pnmpd) - else - mpz_add(psum,psum,pnmpd) - end if - end for - pn = append(pn,psum) - end while - return pn[max(1,n)] - end function +sequence pn = {mpz_init(1)} +function partitionsP(integer n) + mpz res = mpz_init(1) + while n>length(pn) do + integer nn = length(pn)+1 + mpz psum = mpz_init(0) + for i=1 to nn do + integer pd = partDiff(i) + if pd>nn then exit end if + integer sgn = iff(remainder(i-1,4)<2 ? 1 : -1) + mpz pnmpd = pn[max(1,nn-pd)] + if sgn=-1 then + mpz_sub(psum,psum,pnmpd) + else + mpz_add(psum,psum,pnmpd) + end if + end for + pn = append(pn,psum) + end while + return pn[max(1,n)] +end function - atom t0 = time() - integer n=6666 - printf(1,"p(%d) = %s (%s)\n",{n,mpz_get_str(partitionsP(n)),elapsed(time()-t0)}) - - sequence row = {} - for m = 1 to 13 do - row = row & 1 - for n=length(row)-1 to 2 by -1 do - row[n] += row[n-1] + with javascript_semantics + sequence row, rows = {} + + function check(integer i, string name) -- helper routine + string s = join(row,fmt:="%d") + if s!=rows[i+1] then + printf(1,"%s: goes wrong on line %d\n",{name,i+1}) + return false + end if + return true + end function + + procedure sum_prior() -- First method + row = {} -- (using just one row) + for i=0 to 119 do + row &= 1 + for n=length(row)-1 to 2 by -1 do + row[n] += row[n-1] + end for + if not check(i,"sum_prior") then exit end if end for - printf(1,repeat(' ',(13-m)*2)) - for i=1 to length(row) do - printf(1," %3d",row[i]) + end procedure + + procedure algebraic() -- Second method + for i=0 to 119 do + atom c = 1 + row = {1} + for j=0 to i-1 do + -- c *= (i-j)/(j+1) -- NO: precedence differs, and eg 5*(1/5) inexact + c = c*(i-j)/(j+1) -- ..whereas (5*1)/5 is exact + row &= c + end for + if not check(i,"algebraic") then exit end if end for - puts(1,'\n') - end for + end procedure + -- Aside: error with c was self-evident and more relevant when it was an integer, + --- but I made it an atom to get past the 33/63 limits that imposed. + + procedure builtin() -- Third method + for i=0 to 119 do + row = {} + for j=0 to i do + row &= choose(i,j) + end for + if not check(i,"builtin") then exit end if + end for + end procedure + + include mpfr.e + procedure arbitrary_precision() -- Fourth method, but run first + -- perfectly accurate until you + -- run out of memory or patience. + mpz z = mpz_init() + for i=0 to 119 do + row = {} + for j=0 to i do + mpz_bin_uiui(z,i,j) + row = append(row,mpz_get_str(z)) + end for + string s = join(row) + if i<=19 then + printf(1,"%=96s\n",s) + end if + -- to check the others against: + rows = append(rows,s) + end for + printf(1,"\n") + end procedure + + arbitrary_precision() + sum_prior() + algebraic() + builtin() [ ) + + [ char a char z range ] constant is lowers ( --> $ ) + + [ char A char Z range ] constant is uppers ( --> $ ) + + [ char 0 char 9 range ] constant is digits ( --> $ ) + + [ $ \!"#$%&'()*+,-./:;<=>?@[]^_{|}~\ ] is others ( --> $ ) + + [ [] ' [ lowers uppers digits others ] + tuck witheach + [ do dup size random peek join ] + [] rot witheach [ do join ] + rot 4 - times + [ dup dup size random peek + rot join swap ] + drop shuffle ] is password ( n --> $ ) + + [ swap times + [ dup password echo$ cr ] drop ] is passwords ( n n --> ) + + [ say "'passwords' generates a specified" cr + say "number of passwords of a specified" cr + say "length. For example," cr + cr + say " 5 10 passwords" cr + cr + say "will generate five ten-character" cr + say "passwords." cr ] is help + + say "Type 'help' for help with passwords." diff --git a/Task/Password-generator/Rust/password-generator.rs b/Task/Password-generator/Rust/password-generator.rs new file mode 100644 index 0000000000..7ab000e6d5 --- /dev/null +++ b/Task/Password-generator/Rust/password-generator.rs @@ -0,0 +1,72 @@ +use rand::prelude::*; +use rand::distr::Alphanumeric; +use std::iter; +use std::process; +use structopt::StructOpt; +const OTHER_VALUES: &str = "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~"; + +// the core logic that creates our password +fn generate_password(length: u8) -> String { + // cache rng for better performance + let mut rng = rand::rng(); + // the Alphanumeric struct provides 3/4 + // of the characters for passwords + // so we can sample from it + let mut base_password: Vec = iter::repeat(()) + .map(|()| rng.sample(Alphanumeric) as char) + .take(length as usize) + .collect(); + let mut end_range = 10; + // if the user supplies a password length less than 10 + // we need to adjust the random sample range + if length < end_range { + end_range = length; + } + // create a random count of how many other characters to add + let mut to_add = rng.random_range(1..end_range as usize); + loop { + // create an iterator of required other characters + let special = OTHER_VALUES.chars().choose(&mut rng).unwrap(); + to_add -= 1; + base_password[to_add] = special; + if to_add == 0 { + break; + } + } + base_password.iter().collect() +} + +#[derive(StructOpt, Debug)] +#[structopt(name = "password-generator", about = "A simple password generator.")] +struct Opt { + // make it SECURE by default + // https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html + /// The password length + #[structopt(default_value = "160")] + length: u8, + /// How many passwords to generate + #[structopt(default_value = "1")] + count: u8, +} + +fn main() { + // instantiate the options and use them as + // arguments to our password generator + let opt = Opt::from_args(); + const MINIMUM_LENGTH: u8 = 30; + if opt.length < MINIMUM_LENGTH { + eprintln!( + "Please provide a password length greater than or equal to {}", + MINIMUM_LENGTH + ); + process::exit(1); + } + for index in 0..opt.count { + let password = generate_password(opt.length); + // do not print a newline after the last password + match index + 1 == opt.count { + true => print!("{}", password), + _ => println!("{}", password), + }; + } +} diff --git a/Task/Password-generator/Rust/password-generator.rust b/Task/Password-generator/Rust/password-generator.rust deleted file mode 100644 index 46c44988fe..0000000000 --- a/Task/Password-generator/Rust/password-generator.rust +++ /dev/null @@ -1,73 +0,0 @@ -use rand::distributions::Alphanumeric; -use rand::prelude::IteratorRandom; -use rand::{thread_rng, Rng}; -use std::iter; -use std::process; -use structopt::StructOpt; -const OTHER_VALUES: &str = "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~"; - -// the core logic that creates our password -fn generate_password(length: u8) -> String { - // cache thread_rng for better performance - let mut rng = thread_rng(); - // the Alphanumeric struct provides 3/4 - // of the characters for passwords - // so we can sample from it - let mut base_password: Vec = iter::repeat(()) - .map(|()| rng.sample(Alphanumeric)) - .take(length as usize) - .collect(); - let mut end_range = 10; - // if the user supplies a password length less than 10 - // we need to adjust the random sample range - if length < end_range { - end_range = length; - } - // create a random count of how many other characters to add - let mut to_add = rng.gen_range(1, end_range as usize); - loop { - // create an iterator of required other characters - let special = OTHER_VALUES.chars().choose(&mut rng).unwrap(); - to_add -= 1; - base_password[to_add] = special; - if to_add == 0 { - break; - } - } - base_password.iter().collect() -} - -#[derive(StructOpt, Debug)] -#[structopt(name = "password-generator", about = "A simple password generator.")] -struct Opt { - // make it SECURE by default - // https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html - /// The password length - #[structopt(default_value = "160")] - length: u8, - /// How many passwords to generate - #[structopt(default_value = "1")] - count: u8, -} - -fn main() { - // instantiate the options and use them as - // arguments to our password generator - let opt = Opt::from_args(); - const MINIMUM_LENGTH: u8 = 30; - if opt.length < MINIMUM_LENGTH { - eprintln!( - "Please provide a password length greater than or equal to {}", - MINIMUM_LENGTH - ); - process::exit(1); - } - for index in 0..opt.count { - let password = generate_password(opt.length); - // do not print a newline after the last password - match index + 1 == opt.count { - true => print!("{}", password), - _ => println!("{}", password), - }; - } -} diff --git a/Task/Password-generator/Uiua/password-generator.uiua b/Task/Password-generator/Uiua/password-generator.uiua new file mode 100644 index 0000000000..551de64481 --- /dev/null +++ b/Task/Password-generator/Uiua/password-generator.uiua @@ -0,0 +1,8 @@ +Chars ← {+@a⇡26 +@A⇡26 "012356789" "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~"} +All ← /◇⊂ Chars +Choose ← ⊡⌊×⚂⊸⧻ +Base ← (≡◇Choose Chars) # Satisfy rule +Pw ← ⊂Base⨬(""|⍥(Choose All)-4)⊸>4 +Len ← 20 +Count ← 10 +⍥(Pw Len)Count diff --git a/Task/Password-generator/V-(Vlang)/password-generator.v b/Task/Password-generator/V-(Vlang)/password-generator.v new file mode 100644 index 0000000000..4367f0710e --- /dev/null +++ b/Task/Password-generator/V-(Vlang)/password-generator.v @@ -0,0 +1,181 @@ +import rand +import rand.seed +import os + +const lower = "abcdefghijklmnopqrstuvwxyz" +const upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +const digit = "0123456789" +const other = "!\"#$%&()*+,-./:;<=>?@[]^_{|}~" +const excl_chars = [ + "'I', 'l' and '1'", + "'O' and '0' ", + "'5' and 'S' ", + "'2' and 'Z' " +] + +fn shuffle(s string) string { + mut runes := s.runes() + mut n := runes.len + for n > 1 { + k := rand.int_in_range(0, n) or { 0 } + n-- + runes[n], runes[k] = runes[k], runes[n] + } + return runes.string() +} + +fn generate_passwords(pwd_len int, pwd_num int, to_console bool, to_file bool) { + mut lower_str := lower + mut upper_str := upper + mut digit_str := digit + mut other_str := other + mut sb := []rune{} + mut pwd :="" + ll := lower_str.len + ul := upper_str.len + dl := digit_str.len + ol := other_str.len + tl := ll + ul + dl + ol + if to_console { println("\nThe generated passwords are:") } + for i in 0 .. pwd_num { + sb.clear() + sb << lower_str[rand.int_in_range(0, ll) or { 0 }] + sb << upper_str[rand.int_in_range(0, ul) or { 0 }] + sb << digit_str[rand.int_in_range(0, dl) or { 0 }] + sb << other_str[rand.int_in_range(0, ol) or { 0 }] + for _ in 0 .. (pwd_len - 4) { + k := rand.int_in_range(0, tl) or { 0 } + if k < ll { sb << lower_str[k] } + else if k < ll + ul { sb << upper_str[k - ll] } + else if k < ll + ul + dl { sb << digit_str[k - ll - ul] } + else { sb << other_str[k - ll - ul - dl] } + } + pwd = sb.string() + for _ in 0 .. 5 { + pwd = shuffle(pwd) + } + if to_console { println(" ${i + 1:2d}: $pwd") } + if to_file { println("[FILE] $pwd") } + } + if to_file { println("\nThe generated passwords have been printed here instead of written to a file.") } +} + +fn print_help() { + println(" +This program generates up to 99 passwords of between 5 and 20 characters in +length. + +You will be prompted for the values of all parameters when the program is run +- there are no command line options to memorize. + +The passwords can either be written to the console or to a file (pwds.txt), +or both. + +The passwords must contain at least one each of the following character types: + lower-case letters : a -> z + upper-case letters : A -> Z + digits : 0 -> 9 + other characters : !#$%&()*+,-./:;<=>?@[]^_{|}~\" + +Optionally, a seed can be set for the random generator +(any non-zero integer) otherwise the default seed will be used. +Even if the same seed is set, the passwords will not necessarily be exactly +the same on each run as additional random shuffles are always performed. + +You can also specify that various sets of visually similar characters +will be excluded (or not) from the passwords, namely: Il1 O0 5S 2Z + +Finally, the only command line options permitted are -h and -help which +will display this page and then exit. + +Any other command line parameters will simply be ignored and the program +will be run normally. +") +} + +fn main() { + args := os.args[1..] + seeds := seed.time_seed_array(2) + rand.seed(seeds) + mut yn := "" + mut lower_str := lower + mut upper_str := upper + mut digit_str := digit + mut pwd_len, mut pwd_num := 0, 0 + mut to_console, mut to_file := false, true + if args.len == 1 && (args[0] == "-h" || args[0] == "-help") { + print_help() + return + } + println("Please enter the following and press return after each one:") + for { + print(" Password length (5 to 20) : ") + input := os.get_line() + pwd_len = input.int() + if pwd_len >= 5 && pwd_len <= 20 { break } + } + for { + print(" Number to generate (1 to 99) : ") + input := os.get_line() + pwd_num = input.int() + if pwd_num >= 1 && pwd_num <= 99 { break } + } + println(" Exclude the following visually similar characters") + for i, excl in excl_chars { + yn = "" + for { + print(" $excl y/n : ") + yn = os.get_line().to_lower() + if yn == "y" || yn == "n" { break } + } + if yn == "y" { + match i { + 0 { + upper_str = upper_str.replace("I", "") + lower_str = lower_str.replace("l", "") + digit_str = digit_str.replace("1", "") + } + 1 { + upper_str = upper_str.replace("O", "") + digit_str = digit_str.replace("0", "") + } + 2 { + upper_str = upper_str.replace("S", "") + digit_str = digit_str.replace("5", "") + } + 3 { + upper_str = upper_str.replace("Z", "") + digit_str = digit_str.replace("2", "") + } + else {} + } + } + } + for { + print(" Write to console y/n : ") + t := os.get_line() + if t == "y" { + to_console = true + break + } + else if t == "n" { + to_console = false + break + } + } + if to_console { + for { + print(" Write to file y/n : ") + t := os.get_line() + if t == "y" { + to_file = true + break + } + else if t == "n" { + to_file = false + break + } + } + } + generate_passwords(pwd_len, pwd_num, to_console, to_file) +} diff --git a/Task/Password-generator/X86-64-Assembly/password-generator.x86-64 b/Task/Password-generator/X86-64-Assembly/password-generator.x86-64 new file mode 100644 index 0000000000..ff654dfedf --- /dev/null +++ b/Task/Password-generator/X86-64-Assembly/password-generator.x86-64 @@ -0,0 +1,295 @@ +format ELF64 executable 3 +entry main +minlen equ 8 +cmdno equ 3 +cmdnos equ cmdno * 8 + +segment executable readable +main: + mov rax, qword [rsp] + mov rdi, cmdno + cmp rax, rdi + cmovg rax, rdi + cmp rax, 1 + jle .printhelp + cmp rax, 2 + jg .cmdloop + mov rdi, default + mov qword [cmdslot + 16], rdi + .cmdloop: + mov rdi, qword [rsp + rax * 8] + dec rax + mov qword [cmdslot + rax * 8], rdi + or rax, rax + jnz .cmdloop + .convert0: + mov rdi, qword [cmdslot + 8] + call atoq + cmp rax, minlen + jl .printhelp + mov qword [cmdslot + 8], rax + mov rdi, qword [cmdslot + 16] + call atoq + sub rax, 0 + jle .printhelp + mov qword [cmdslot + 16], rax + .allocate: + mov rax, qword [cmdslot + 8] + xor rdx, rdx + mov rdi, 8 + div rdi + add rax, 1 + xor rdx, rdx + mul rdi + mov qword [cmdslot], rax + sub rsp, rax + mov rax, qword [cmdslot + 16] + mov rdi, rsp + .loop00: + mov rsi, qword [cmdslot + 8] + call mkpass + call check + or r9, r9 + jz .loop00 + call prints + dec rax + jnz .loop00 + .exit: + add rsp, qword [cmdslot] + mov rax, 60 + xor rdi, rdi + syscall + .printhelp: + mov rdi, helpmsg + call prints + jmp .exit + +prints: + push rdx + push rsi + push rdi + push rax + xor rdx, rdx + cmp byte [rdi + rdx], 0 + je .return + .stloop: + cmp byte [rdi + rdx], 0 + je .printit + inc rdx + jmp .stloop + .printit: + mov rax, 1 + mov rsi, rdi + mov rdi, 1 + syscall + mov al, 0x0a + push rax + mov rax, 1 + mov rsi, rsp + mov rdx, 1 + syscall + pop rax + .return: + pop rax + pop rdi + pop rsi + pop rdx + ret + +atoq: + push r8 + push r9 + push rdi + push rsi + push rdx + push rcx + xor rax, rax + xor r8, r8 + mov r9, 1 + cmp byte[rdi], 0 + jz .exit + cmp byte[rdi], '-' + jne .stloop + mov r9, -1 + inc rdi + .stloop: + cmp byte[rdi + r8], '0' + jl .calc0 + cmp byte[rdi + r8], '9' + jg .calc0 + mov sil, byte[rdi + r8] + sub rsi, '0' + push rsi + inc r8 + jmp .stloop + .calc0: + xor rcx, rcx + mov rdi, 10 + mov rsi, 1 + .calc1: + pop rax + mul rsi + add rcx, rax + dec r8 + jz .return + mov rax, rsi + mul rdi + mov rsi, rax + jmp .calc1 + .return: + mov rax, rcx + imul r9 + .exit: + pop rcx + pop rdx + pop rsi + pop rdi + pop r9 + pop r8 + ret + +getchar: + push rdi + push rdx + rdrand rax + mov rdi, endchars - chars + xor rdx, rdx + div rdi + xor rax, rax + mov al, byte [chars + rdx] + pop rdx + pop rdi + ret + +mkpass: + push rsi + push rax + mov byte [rdi + rsi], 0 + .loop0: + dec rsi + call getchar + mov byte [rdi + rsi], al + or rsi, rsi + jnz .loop0 + .return0: + pop rax + pop rsi + ret + +check: + push rax + push rdx + push rcx + xor r9, r9 + .upper: + xor rcx, rcx + .upper0: + xor rdx, rdx + mov rsi, endalphau - alphau + mov al, byte[rdi + rcx] + .upper1: + cmp al, byte[alphau + rdx] + je .lower + inc rdx + cmp rdx, rsi + jl .upper1 + inc rcx + cmp byte[rdi + rcx], 0 + jnz .upper0 + jmp .return0 + .lower: + xor rcx, rcx + .lower0: + xor rdx, rdx + mov rsi, endalphal - alphal + mov al, byte[rdi + rcx] + .lower1: + cmp al, byte[alphal + rdx] + je .numeric + inc rdx + cmp rdx, rsi + jl .lower1 + inc rcx + cmp byte[rdi + rcx], 0 + jnz .lower0 + jmp .return0 + .numeric: + xor rcx, rcx + .numeric0: + xor rdx, rdx + mov rsi, endnumeri - numeri + mov al, byte[rdi + rcx] + .numeric1: + cmp al, byte[numeri + rdx] + je .special + inc rdx + cmp rdx, rsi + jl .numeric1 + inc rcx + cmp byte[rdi + rcx], 0 + jnz .numeric0 + jmp .return0 + .special: + xor rcx, rcx + .special0: + xor rdx, rdx + mov rsi, endspecia - specia + mov al, byte[rdi + rcx] + .special1: + cmp al, byte[specia + rdx] + je .return1 + inc rdx + cmp rdx, rsi + jl .special1 + inc rcx + cmp byte[rdi + rcx], 0 + jnz .special0 + jmp .return0 + .return1: + mov r9, 1 + .return0: + pop rcx + pop rdx + pop rax + ret + +segment readable +helpmsg: + db "Usage:", 0x0a + db "passgen nchars [ncount]", 0x0a, 0x0a + db "nchars = number of characters for each password", 0x0a + db "ncount = number of passwords to generate", 0x0a + db "If ncount is omitted, a default of 1 will be used.", 0x0a, 0x0a + db "A password generation program which will generate passwords", 0x0a + db "containing random ASCII characters from the following groups:", 0x0a, 0x0a + db "lower-case letters: a ──► z", 0x0a + db "upper-case letters: A ──► Z", 0x0a + db " digits: 0 ──► 9", 0x0a + db "other printable characters:", 0x0a + db 0x09, 0x21, 0x22, "#$%&", 0x27, "()*+,-./:;<=>?@[]^_{|}~", 0x0a + db 0x09, "(the above character list excludes white-space," + db 0x09, " backslash and grave)", 0x0a, 0x0a + db "The generated password(s) must include at least one", 0x0a + db "(of each of the four groups):", 0x0a + db " lower-case letter,", 0x0a + db " upper-case letter,", 0x0a + db " digit (numeral), and", 0x0a + db " one 'other' character.", 0x0a, 0x0a + db "Created for Rosetta Code.", 0x0a + db "https:", 0x2f, 0x2f, "rosettacode.org/wiki/Password_generator", 0 +chars: +alphau: db "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +endalphau: + db "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ" +alphal: db "abcdefghijklmnopqrstuvwxyz" +endalphal: + db "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz" +numeri: db "0123456789" +endnumeri: + db "01234567890123456789012345678901234567890123456789" +specia: db 0x21, 0x22, "#$%&", 0x27, "()*+,-./:;<=>?@[]^_{|}~" +endspecia: +endchars: +default: db '1', 0 +segment readable writable +cmdslot: rq cmdnos diff --git a/Task/Pathological-floating-point-problems/ALGOL-68/pathological-floating-point-problems.alg b/Task/Pathological-floating-point-problems/ALGOL-68/pathological-floating-point-problems.alg index 341dc7dfc3..77c11b77f3 100644 --- a/Task/Pathological-floating-point-problems/ALGOL-68/pathological-floating-point-problems.alg +++ b/Task/Pathological-floating-point-problems/ALGOL-68/pathological-floating-point-problems.alg @@ -1,9 +1,16 @@ BEGIN + + # show the sizes of REAL, LONG REAL and LONG LONG real # + print( ( "Approximate sizes of real numbers available: " ) ); + print( ( "REAL: ", whole( real width, 0 ) ) ); + print( ( ", LONG REAL: ", whole( long real width, 0 ) ) ); + print( ( ", default for LONG LONG REAL: ", whole( long long real width, 0 ) ) ); + print( ( newline, newline ) ); + # task 1 # BEGIN - PR precision 32 PR - print( ( " 32 digit REAL numbers", newline ) ); - [ 1 : 100 ]LONG LONG REAL v; + print( ( whole( long real width, -4 ), " digit REAL numbers", newline ) ); + [ 1 : 100 ]LONG REAL v; v[ 1 ] := 2; v[ 2 ] := -4; FOR n FROM 3 TO UPB v DO v[ n ] := 111 - ( 1130 / v[ n - 1 ] ) + ( 3000 / ( v[ n - 1 ] * v[ n - 2 ] ) ) OD; @@ -12,8 +19,7 @@ BEGIN print( ( "n = 100 ", fixed( v[ 100 ], -22, 16 ), newline ) ) END; BEGIN - PR precision 120 PR - print( ( "120 digit REAL numbers", newline ) ); + print( ( whole( long long real width, -4 ), " digit REAL numbers", newline ) ); [ 1 : 100 ]LONG LONG REAL v; v[ 1 ] := 2; v[ 2 ] := -4; @@ -23,25 +29,24 @@ BEGIN print( ( newline ) ); # task 2 # BEGIN - print( ( "single precision REAL numbers...", newline ) ); + print( ( "standard precision REAL numbers...", newline ) ); REAL chaotic balance := exp( 1 ) - 1; - print( ( "initial chaotic balance: ", fixed( chaotic balance, -22, 16 ), newline ) ); + print( ( " initial chaotic balance: ", fixed( chaotic balance, -22, 16 ), newline ) ); FOR i FROM 1 TO 25 DO ( chaotic balance *:= i ) -:= 1 OD; - print( ( "25 year chaotic balance: ", fixed( chaotic balance, -22, 16 ), newline ) ) + print( ( " 25 year chaotic balance: ", fixed( chaotic balance, -22, 16 ), newline ) ) END; BEGIN - print( ( "double precision REAL numbers...", newline ) ); + print( ( "double precision LONG REAL numbers...", newline ) ); LONG REAL chaotic balance := long exp( 1 ) - 1; - print( ( "initial chaotic balance: ", fixed( chaotic balance, -22, 16 ), newline ) ); + print( ( " initial chaotic balance: ", fixed( chaotic balance, -22, 16 ), newline ) ); FOR i FROM 1 TO 25 DO ( chaotic balance *:= i ) -:= 1 OD; - print( ( "25 year chaotic balance: ", fixed( chaotic balance, -22, 16 ), newline ) ) + print( ( " 25 year chaotic balance: ", fixed( chaotic balance, -22, 16 ), newline ) ) END; BEGIN - PR precision 32 PR - print( ( " 32 digit REAL numbers...", newline ) ); + print( ( whole( long long real width, -10 ), " digit LONG LONG REAL numbers...", newline ) ); LONG LONG REAL chaotic balance := long long exp( 1 ) - 1; - print( ( "initial chaotic balance: ", fixed( chaotic balance, -22, 16 ), newline ) ); + print( ( " initial chaotic balance: ", fixed( chaotic balance, -22, 16 ), newline ) ); FOR i FROM 1 TO 25 DO ( chaotic balance *:= i ) -:= 1 OD; - print( ( "25 year chaotic balance: ", fixed( chaotic balance, -22, 16 ), newline ) ) + print( ( " 25 year chaotic balance: ", fixed( chaotic balance, -22, 16 ), newline ) ) END END diff --git a/Task/Pathological-floating-point-problems/Ada/pathological-floating-point-problems-1.ada b/Task/Pathological-floating-point-problems/Ada/pathological-floating-point-problems-1.adb similarity index 100% rename from Task/Pathological-floating-point-problems/Ada/pathological-floating-point-problems-1.ada rename to Task/Pathological-floating-point-problems/Ada/pathological-floating-point-problems-1.adb diff --git a/Task/Pathological-floating-point-problems/Ada/pathological-floating-point-problems-2.ada b/Task/Pathological-floating-point-problems/Ada/pathological-floating-point-problems-2.adb similarity index 100% rename from Task/Pathological-floating-point-problems/Ada/pathological-floating-point-problems-2.ada rename to Task/Pathological-floating-point-problems/Ada/pathological-floating-point-problems-2.adb diff --git a/Task/Pathological-floating-point-problems/Ada/pathological-floating-point-problems-3.ada b/Task/Pathological-floating-point-problems/Ada/pathological-floating-point-problems-3.adb similarity index 100% rename from Task/Pathological-floating-point-problems/Ada/pathological-floating-point-problems-3.ada rename to Task/Pathological-floating-point-problems/Ada/pathological-floating-point-problems-3.adb diff --git a/Task/Pathological-floating-point-problems/Crystal/pathological-floating-point-problems-1.crystal b/Task/Pathological-floating-point-problems/Crystal/pathological-floating-point-problems-1.cr similarity index 100% rename from Task/Pathological-floating-point-problems/Crystal/pathological-floating-point-problems-1.crystal rename to Task/Pathological-floating-point-problems/Crystal/pathological-floating-point-problems-1.cr diff --git a/Task/Pathological-floating-point-problems/Crystal/pathological-floating-point-problems-2.crystal b/Task/Pathological-floating-point-problems/Crystal/pathological-floating-point-problems-2.cr similarity index 100% rename from Task/Pathological-floating-point-problems/Crystal/pathological-floating-point-problems-2.crystal rename to Task/Pathological-floating-point-problems/Crystal/pathological-floating-point-problems-2.cr diff --git a/Task/Pathological-floating-point-problems/Crystal/pathological-floating-point-problems-3.crystal b/Task/Pathological-floating-point-problems/Crystal/pathological-floating-point-problems-3.cr similarity index 100% rename from Task/Pathological-floating-point-problems/Crystal/pathological-floating-point-problems-3.crystal rename to Task/Pathological-floating-point-problems/Crystal/pathological-floating-point-problems-3.cr diff --git a/Task/Pathological-floating-point-problems/Crystal/pathological-floating-point-problems-4.crystal b/Task/Pathological-floating-point-problems/Crystal/pathological-floating-point-problems-4.cr similarity index 100% rename from Task/Pathological-floating-point-problems/Crystal/pathological-floating-point-problems-4.crystal rename to Task/Pathological-floating-point-problems/Crystal/pathological-floating-point-problems-4.cr diff --git a/Task/Pathological-floating-point-problems/Crystal/pathological-floating-point-problems-5.crystal b/Task/Pathological-floating-point-problems/Crystal/pathological-floating-point-problems-5.cr similarity index 100% rename from Task/Pathological-floating-point-problems/Crystal/pathological-floating-point-problems-5.crystal rename to Task/Pathological-floating-point-problems/Crystal/pathological-floating-point-problems-5.cr diff --git a/Task/Pathological-floating-point-problems/Delphi/pathological-floating-point-problems.delphi b/Task/Pathological-floating-point-problems/Delphi/pathological-floating-point-problems.pas similarity index 100% rename from Task/Pathological-floating-point-problems/Delphi/pathological-floating-point-problems.delphi rename to Task/Pathological-floating-point-problems/Delphi/pathological-floating-point-problems.pas diff --git a/Task/Pathological-floating-point-problems/EasyLang/pathological-floating-point-problems.easy b/Task/Pathological-floating-point-problems/EasyLang/pathological-floating-point-problems.easy new file mode 100644 index 0000000000..5c9abfed32 --- /dev/null +++ b/Task/Pathological-floating-point-problems/EasyLang/pathological-floating-point-problems.easy @@ -0,0 +1,51 @@ +numfmt 0 10 +proc task1 . + print "--- Task 1 pathologic ---" + vpp = 2 + vp = -4 + for i = 3 to 100 + v = 111 - 1130 / vp + 3000 / (vp * vpp) + if i <= 8 or i = 20 or i = 30 or i = 50 or i = 100 + print i & ": " & v + . + vpp = vp + vp = v + . +. +task1 +print "" +# +proc task2 . + print "--- Task 2 pathologic ---" + e = 2.718281828459045 + bal = e - 1 + for i = 1 to 25 + bal = bal * i - 1 + . + print "Balance after 25 years: $" & bal +. +task2 +print "" +# +proc mul f &bal &bal$[] . + for i = len bal$[] downto 1 + dig = number bal$[i] + h = dig * f + c + bal$[i] = h mod 10 + c = h div 10 + . + bal += c +. +proc task2ok . + print "--- Task 2 OK ---" + e$ = "2.7182818284590452353602874713526624977572470" + bal = number substr e$ 1 1 + bal$[] = strchars substr e$ 3 999 + bal -= 1 + for i = 1 to 25 + mul i bal bal$[] + bal -= 1 + . + print "Balance after 25 years: $" & bal & "." & substr strjoin bal$[] "" 1 16 +. +task2ok diff --git a/Task/Pathological-floating-point-problems/Haskell/pathological-floating-point-problems-1.hs b/Task/Pathological-floating-point-problems/Haskell/pathological-floating-point-problems-1.hs new file mode 100644 index 0000000000..886d138cec --- /dev/null +++ b/Task/Pathological-floating-point-problems/Haskell/pathological-floating-point-problems-1.hs @@ -0,0 +1,11 @@ +-- | Show at least n decimal places + +showRational :: Natural -> Rational -> String +showRational n r = let + + sign = if r < 0 then '-' else '+' + (integer, rest) = (numerator r `quotRem` denominator r) + decimal = show $ rest * 10 ^ n `quot` denominator r + zeroes = replicate (fromIntegral n - length decimal) '0' + + in sign : show integer ++ "." ++ zeroes ++ decimal diff --git a/Task/Pathological-floating-point-problems/Haskell/pathological-floating-point-problems-2.hs b/Task/Pathological-floating-point-problems/Haskell/pathological-floating-point-problems-2.hs new file mode 100644 index 0000000000..3e5dca21df --- /dev/null +++ b/Task/Pathological-floating-point-problems/Haskell/pathological-floating-point-problems-2.hs @@ -0,0 +1,16 @@ +import Numeric.Natural (Natural) +import Data.Ratio as Rational + +-- | Infinite List of Rational numbers in the series, zips itself to produce more values + +v :: [Rational] +v = 2 : -4 : zipWith combine (drop 1 v) v + where + combine prev prev2 = 111 - 1130 / prev + 3000 / (prev * prev2) + + +-- >>> showRational 5 (1%3) +-- "+0.33333" + +main :: IO () +main = mapM_ (putStrLn . showRational 16 . (v !!)) [3, 4, 5, 6, 7, 8, 20, 30, 50, 100] diff --git a/Task/Pathological-floating-point-problems/Haskell/pathological-floating-point-problems-3.hs b/Task/Pathological-floating-point-problems/Haskell/pathological-floating-point-problems-3.hs new file mode 100644 index 0000000000..8385954b66 --- /dev/null +++ b/Task/Pathological-floating-point-problems/Haskell/pathological-floating-point-problems-3.hs @@ -0,0 +1,30 @@ +import Data.Ratio ((%), numerator, denominator) +import Data.List (genericIndex) + +balances :: [Rational] +balances = e - 1 : zipWith nextYear [1..] balances + where + nextYear n b = n * b - 1 + + e = brothersFormulae 1000 + + +factorial :: [Integer] +factorial = 0 : 1 : zipWith (*) (drop 1 factorial) [2..] + +-- >>> take 10 factorial +-- [0,1,2,6,24,120,720,5040,40320,362880] + +brothersFormulae :: Integer -> Rational +brothersFormulae n = sum $ map step [0..n] + where + step i = (2 * i + 2) % genericIndex factorial (2 * i + 1) + +task2 :: String +task2 = showRational 30 . (balances !!) $ 25 + +-- >>> task2 +-- "+0.039938729673230208903671455210" + +main :: IO () +main = putStrLn task2 diff --git a/Task/Pathological-floating-point-problems/Jq/pathological-floating-point-problems-1.jq b/Task/Pathological-floating-point-problems/Jq/pathological-floating-point-problems-1.jq index eea1e73398..7bfc030148 100644 --- a/Task/Pathological-floating-point-problems/Jq/pathological-floating-point-problems-1.jq +++ b/Task/Pathological-floating-point-problems/Jq/pathological-floating-point-problems-1.jq @@ -1,17 +1,9 @@ -# Input: the value at which to compute v +# A (naive) limitless generator def v: - # Input: cache - # Output: updated cache - def v_(n): - (n|tostring) as $s - | . as $cache - | if ($cache | has($s)) then . - else if n == 1 then $cache["1"] = 2 - elif n == 2 then $cache["2"] = -4 - else ($cache | v_(n-1) | v_(n - 2)) as $new - | $new[(n-1)|tostring] as $x - | $new[(n-2)|tostring] as $y - | $new + {($s): ((111 - (1130 / $x) + (3000 / ($x * $y)))) } - end - end; - . as $m | {} | v_($m) | .[($m|tostring)] ; + [2, -4] + | recurse( [.[1], 111 - (1130 / .[1]) + 3000 / (.[0] * .[1])] ) + | .[0]; + +[limit(100; v)] +| (3, 4, 5, 6, 7, 8, 20, 30, 50, 100) as $i +| [$i, .[$i - 1]] diff --git a/Task/Pathological-floating-point-problems/Jq/pathological-floating-point-problems-2.jq b/Task/Pathological-floating-point-problems/Jq/pathological-floating-point-problems-2.jq index 64e4ca8c42..c25a7af901 100644 --- a/Task/Pathological-floating-point-problems/Jq/pathological-floating-point-problems-2.jq +++ b/Task/Pathological-floating-point-problems/Jq/pathological-floating-point-problems-2.jq @@ -1 +1,11 @@ -(3,4,5,6,7,8,20,30,50,100) | v +# Given the balance in the prior year, compute the new balance in year n. +# Input: { e: m, c: n } representing m*e + n +def new_balance(n): + if n == 0 then {e: 1, c: -1} + else {e: (.e * n), c: (.c * n - 1) } + end; + +def balance(n): + def e: 1|exp; + reduce range(0;n) as $i ({}; new_balance($i) ) + | (.e * e) + .c; diff --git a/Task/Pathological-floating-point-problems/Jq/pathological-floating-point-problems-3.jq b/Task/Pathological-floating-point-problems/Jq/pathological-floating-point-problems-3.jq index c25a7af901..45c0ab4f6c 100644 --- a/Task/Pathological-floating-point-problems/Jq/pathological-floating-point-problems-3.jq +++ b/Task/Pathological-floating-point-problems/Jq/pathological-floating-point-problems-3.jq @@ -1,11 +1 @@ -# Given the balance in the prior year, compute the new balance in year n. -# Input: { e: m, c: n } representing m*e + n -def new_balance(n): - if n == 0 then {e: 1, c: -1} - else {e: (.e * n), c: (.c * n - 1) } - end; - -def balance(n): - def e: 1|exp; - reduce range(0;n) as $i ({}; new_balance($i) ) - | (.e * e) + .c; +balance(25) diff --git a/Task/Pathological-floating-point-problems/Jq/pathological-floating-point-problems-4.jq b/Task/Pathological-floating-point-problems/Jq/pathological-floating-point-problems-4.jq deleted file mode 100644 index 45c0ab4f6c..0000000000 --- a/Task/Pathological-floating-point-problems/Jq/pathological-floating-point-problems-4.jq +++ /dev/null @@ -1 +0,0 @@ -balance(25) diff --git a/Task/Pathological-floating-point-problems/Julia/pathological-floating-point-problems.julia b/Task/Pathological-floating-point-problems/Julia/pathological-floating-point-problems.jl similarity index 100% rename from Task/Pathological-floating-point-problems/Julia/pathological-floating-point-problems.julia rename to Task/Pathological-floating-point-problems/Julia/pathological-floating-point-problems.jl diff --git a/Task/Pathological-floating-point-problems/Kotlin/pathological-floating-point-problems.kotlin b/Task/Pathological-floating-point-problems/Kotlin/pathological-floating-point-problems.kts similarity index 100% rename from Task/Pathological-floating-point-problems/Kotlin/pathological-floating-point-problems.kotlin rename to Task/Pathological-floating-point-problems/Kotlin/pathological-floating-point-problems.kts diff --git a/Task/Pathological-floating-point-problems/PascalABC.NET/pathological-floating-point-problems.pas b/Task/Pathological-floating-point-problems/PascalABC.NET/pathological-floating-point-problems.pas new file mode 100644 index 0000000000..16ae66209b --- /dev/null +++ b/Task/Pathological-floating-point-problems/PascalABC.NET/pathological-floating-point-problems.pas @@ -0,0 +1,45 @@ +uses numlibabc; + +function muller_seq(n: integer): real; +begin + var seq := Lst(Frc(0), Frc(2), Frc(-4)); + foreach var i in range(3, n + 1) do + begin + var next_value := 111 - 1130 / seq[i - 1] + 3000 / (seq[i - 1] * seq[i - 2]); + seq.Add(next_value); + end; + result := seq[n].ToReal +end; + +function tofraction(s: string): Fraction; +begin + var period := s.IndexOf('.'); + result := Frc(s.Remove(period, 1).ToBigInteger, Power(10bi, s.Length - period - 1)); +end; + +function bank(years: integer): real; +const + e = '2.71828182845904523536028747135266249775724709369995'; +begin + var bigE := ToFraction(e); + var balance := bigE - 1; + for var year := 1 to years do + balance := balance * year - 1; + result := balance.ToReal; +end; + +function rump(a, b: biginteger): real; +begin + var f := ToFraction('333.75') * b ** 6 + + a ** 2 * (11 * a ** 2 * b ** 2 - b ** 6 - 121 * b ** 4 - 2) + + ToFraction('5.5') * b ** 8 + Frc(a, 2 * b); + result := f.ToReal; +end; + +begin + println('Task 1:'); + foreach var n in [3, 4, 5, 6, 7, 8, 20, 30, 50, 100] do + println(n, muller_seq(n)); + println('Task 2: ', bank(25)); + println('Task 3: ', rump(77617, 33096)); +end. diff --git a/Task/Pathological-floating-point-problems/REXX/pathological-floating-point-problems-1.rexx b/Task/Pathological-floating-point-problems/REXX/pathological-floating-point-problems-1.rexx deleted file mode 100644 index b369f06758..0000000000 --- a/Task/Pathological-floating-point-problems/REXX/pathological-floating-point-problems-1.rexx +++ /dev/null @@ -1,15 +0,0 @@ -/*REXX pgm (pathological FP problem): a sequence that might converge to a wrong limit. */ -parse arg digs show . /*obtain optional arguments from the CL*/ -if digs=='' | digs=="," then digs= 150 /*Not specified? Then use the default.*/ -if show=='' | show=="," then show= 20 /* " " " " " " */ -numeric digits digs /*have REXX use "digs" decimal digits. */ -#= 2 4 5 6 7 8 9 20 30 50 100 /*the indices to display value of V.n */ -fin= word(#, words(#) ) /*find the last (largest) index number.*/ -w= length(fin) /* " " length (in dec digs) of FIN.*/ -v.1= 2 /*the value of the first V element. */ -v.2=-4 /* " " " " second " " */ - do n=3 to fin; nm1= n-1; nm2= n-2 /*compute some values of the V elements*/ - v.n= 111 - 1130/v.nm1 + 3000/(v.nm1*v.nm2) /* " a value of a " element.*/ - /*display digs past the dec. point───┐ */ - if wordpos(n, #)\==0 then say 'v.'left(n, w) "=" format(v.n, , show) - end /*n*/ /*stick a fork in it, we're all done. */ diff --git a/Task/Pathological-floating-point-problems/REXX/pathological-floating-point-problems-2.rexx b/Task/Pathological-floating-point-problems/REXX/pathological-floating-point-problems-2.rexx deleted file mode 100644 index 1378f5331a..0000000000 --- a/Task/Pathological-floating-point-problems/REXX/pathological-floating-point-problems-2.rexx +++ /dev/null @@ -1,18 +0,0 @@ -/*REXX pgm (pathological FP problem): the chaotic bank society offering a new investment*/ -e=2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713, - ||8217852516642742746639193200305992181741359662904357290033429526059563073813232862794, - ||3490763233829880753195251019011573834187930702154089149934884167509244761460668082264, - ||8001684774118537423454424371075390777449920695517027618386062613313845830007520449338 -d = length(e) - length(.) /*subtract one for the decimal point. */ -parse arg digs show y . /*obtain optional arguments from the CL*/ -if digs=='' | digs=="," then digs= d /*Not specified? Then use the default.*/ -if show=='' | show=="," then show= 20 /* " " " " " " */ -if y=='' | y=="," then y= 25 /* " " " " " " */ -numeric digits digs /*have REXX use "digs" decimal digits. */ -$= e - 1 /*subtract $1 from e, that's da deposit*/ - /* [↑] value of newly opened account. */ - do n=1 for y /*compute the value of the account/year*/ - $= $*n - 1 /* " " " " " account now.*/ - end /*n*/ -@@@= 'With ' d " decimal digits, the balance after " y ' years is: ' -say @@@ '$'format($, , show) / 1 /*stick a fork in it, we're all done. */ diff --git a/Task/Pathological-floating-point-problems/REXX/pathological-floating-point-problems-3.rexx b/Task/Pathological-floating-point-problems/REXX/pathological-floating-point-problems-3.rexx deleted file mode 100644 index c0da0ee523..0000000000 --- a/Task/Pathological-floating-point-problems/REXX/pathological-floating-point-problems-3.rexx +++ /dev/null @@ -1,13 +0,0 @@ -/*REXX pgm (pathological FP problem): the Siegfried Rump's example (problem dated 1988).*/ -parse arg digs show . /*obtain optional arguments from the CL*/ -if digs=='' | digs=="," then digs=150 /*Not specified? Then use the default.*/ -if show=='' | show=="," then show= 20 /* " " " " " " */ -numeric digits digs /*have REXX use "digs" decimal digits. */ -a= 77617.0 /*initialize A to it's defined value.*/ -b= 33096.0 /* " B " " " " */ - /*display SHOW digits past the dec. pt.*/ -say 'f(a,b)=' format( f(a,b), , show) /*display result from the F function.*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -f: procedure; parse arg a,b; return 333.75* b**6 + a**2 * (11* a**2* b**2 - b**6, - - 121*b**4 - 2) + 5.5*b**8 + a / (2*b) diff --git a/Task/Pathological-floating-point-problems/REXX/pathological-floating-point-problems.rexx b/Task/Pathological-floating-point-problems/REXX/pathological-floating-point-problems.rexx new file mode 100644 index 0000000000..0f724f0508 --- /dev/null +++ b/Task/Pathological-floating-point-problems/REXX/pathological-floating-point-problems.rexx @@ -0,0 +1,51 @@ +-- 24 Aug 2025 +include Setting +arg digs +if digs = '' then + digs=9 +numeric digits digs + +say 'PATHOLOGICAL FLOATING POINT PROBLEMS' +say version +say digs 'digits precision' +say +call Sequence +call Society +call Rump +call Timer +exit + +Sequence: +procedure +say 'Sequence goes to wrong limit...' +show='3 4 5 6 7 8 20 30 50 100' +a=2; b=-4 +do n = 3 to 100 + c=111-1130/b+3000/(a*b); a=b; b=c + if Wordpos(n,show) > 0 then + say 'n =' Right(n,3) Left(c,19) +end +say +return + +Society: +procedure expose Memo. +say 'The Chaotic Bank Society...' +e=e()/1; b=e-1 +say Right(0,2) Left(b,18) +do n = 1 to 25 + b=b*n-1 + say Right(n,2) Left(b,18) +end +say +return + +Rump: +procedure +say 'Siegfried Rumps''s example...' +a=77617; b=33096 +say Left(333.75*b**6 + a**2*(11*a**2*b**2-b**6-121*b**4-2) + 5.5*b**8 + a/(2*b),18) +say +return + +include Math diff --git a/Task/Peaceful-chess-queen-armies/Jq/peaceful-chess-queen-armies.jq b/Task/Peaceful-chess-queen-armies/Jq/peaceful-chess-queen-armies.jq new file mode 100644 index 0000000000..0cde59231c --- /dev/null +++ b/Task/Peaceful-chess-queen-armies/Jq/peaceful-chess-queen-armies.jq @@ -0,0 +1,81 @@ +# Is the queen at position . attacking the position $pos ? +def isAttacking($pos): + .x == $pos.x or + .y == $pos.y or + (((.x - $pos.x)|length) == ((.y - $pos.y)|length)); # i.e. abs + +# Place $q black and $q white queens on an $n*$n board, +# where .blackQueens holds the positions of existing black Queens, +# and similarly for .whiteQueens. +# input: {blackQueens, whiteQueens} +# output: updated input on success, otherwise null. +def place($queens; $n): + def place($q): + if $q == 0 then .ok = true + else .placingBlack = true + | first( + foreach range(0; $n) as $i (.; + foreach range(0; $n) as $j (.; + {x:$i, y:$j} as $pos + | .placingBlack as $placingBlack + | if any( .blackQueens[], .whiteQueens[]; + ((.x == $pos.x) and (.y == $pos.y))) + then . # failure + elif .placingBlack + then if any( .whiteQueens[]; isAttacking($pos) ) + then . + else .blackQueens += [$pos] + | .placingBlack = false + end + elif any( .blackQueens[]; isAttacking($pos) ) + then . + else .whiteQueens += [$pos] + | place($q-1) as $place + | if $place then $place # success + else .blackQueens |= .[:-1] + | .whiteQueens |= .[:-1] + | .placingBlack = true + end + end + | if $i == $n-1 and $j == $n-1 then .ok = false end ); + select(.ok) ) + ) // null + end; + {blackQueens: [], whiteQueens: [] } | place($queens); + +# Input {blackQueens, whiteQueens} +def printBoard($n): + [range(0; $n) | 0] as $row + | .board = [range(0; $n) | $row] + | reduce .blackQueens[] as $queen (.; .board[$queen.x][$queen.y] = "B ") + | reduce .whiteQueens[] as $queen (.; .board[$queen.x][$queen.y] = "W ") + | foreach range(0; $n) as $i (.; + reduce range(0; $n) as $j (.row=""; + .board[$i][$j] as $b + | .row += + (if $b != 0 then $b + elif $i%2 == $j%2 + then "• " + else "◦ " + end) ) ) + | .row; + +# Use an object {squares, queens} to record the task: +# $squares is the number of squares on each side of the board, +# and $queens is the number of queens of each color. +def Task($squares; $queens): {$squares, $queens}; + +def tasks: [ + Task(2; 1), Task(3; 1), Task(3; 2), Task(4; 1), Task(4; 2), Task(4; 3), + Task(5; 1), Task(5; 2), Task(5; 3), Task(5; 4), Task(5; 5), + Task(6; 1), Task(6; 2), Task(6; 3), Task(6; 4), Task(6; 5), Task(6; 6), + Task(7; 1), Task(7; 2), Task(7; 3), Task(7; 4), Task(7; 5), Task(7; 6), Task(7; 7) +]; + +tasks[] as $t +| "\($t.queens) black and \($t.queens) white queens on a \($t.squares) x \($t.squares) board:", + ((place($t.queens; $t.squares) + | select(.) + | printBoard($t.squares)) + // "No solution exists."), + "" diff --git a/Task/Peaceful-chess-queen-armies/Julia/peaceful-chess-queen-armies.julia b/Task/Peaceful-chess-queen-armies/Julia/peaceful-chess-queen-armies.jl similarity index 100% rename from Task/Peaceful-chess-queen-armies/Julia/peaceful-chess-queen-armies.julia rename to Task/Peaceful-chess-queen-armies/Julia/peaceful-chess-queen-armies.jl diff --git a/Task/Peaceful-chess-queen-armies/Kotlin/peaceful-chess-queen-armies.kotlin b/Task/Peaceful-chess-queen-armies/Kotlin/peaceful-chess-queen-armies.kts similarity index 100% rename from Task/Peaceful-chess-queen-armies/Kotlin/peaceful-chess-queen-armies.kotlin rename to Task/Peaceful-chess-queen-armies/Kotlin/peaceful-chess-queen-armies.kts diff --git a/Task/Peaceful-chess-queen-armies/Scheme/peaceful-chess-queen-armies-1.ss b/Task/Peaceful-chess-queen-armies/Scheme/peaceful-chess-queen-armies-1.scm similarity index 100% rename from Task/Peaceful-chess-queen-armies/Scheme/peaceful-chess-queen-armies-1.ss rename to Task/Peaceful-chess-queen-armies/Scheme/peaceful-chess-queen-armies-1.scm diff --git a/Task/Peaceful-chess-queen-armies/Scheme/peaceful-chess-queen-armies-2.ss b/Task/Peaceful-chess-queen-armies/Scheme/peaceful-chess-queen-armies-2.scm similarity index 100% rename from Task/Peaceful-chess-queen-armies/Scheme/peaceful-chess-queen-armies-2.ss rename to Task/Peaceful-chess-queen-armies/Scheme/peaceful-chess-queen-armies-2.scm diff --git a/Task/Peaceful-chess-queen-armies/Uiua/peaceful-chess-queen-armies.uiua b/Task/Peaceful-chess-queen-armies/Uiua/peaceful-chess-queen-armies.uiua new file mode 100644 index 0000000000..8801ba781e --- /dev/null +++ b/Task/Peaceful-chess-queen-armies/Uiua/peaceful-chess-queen-armies.uiua @@ -0,0 +1,11 @@ +S ← 5 +S′ ← ↯S_S +NumQ ← 4 +RCDLDR ← ⊚/↥⊟₄⊃(=S′⇡⊙⊣|=⍉S′⇡⊙⊢|=˙⊞+⇡⊙/+|=˙⊞-⇡⊙/-) +Posns ← ⊙◌♭₂°⊡°△S_S +PeerMap ← map⟜≡(□RCDLDR S) Posns +Peers ← ˜get PeerMap +Free ← ⊚=0°⊚∧(⊂°□Peers)⊙[] +⧅> NumQ Posns # All possible white(1) queen positions. +▽≥4≡◇⧻⊸≡(□Free) # Check all peers of each, see if 4 spaces are left. +⊸⧻⬚0≡(⬚0↥⊃(×2°⊚Free|°⊚)) # Put black(2) queens in *all* of those. diff --git a/Task/Peano-curve/ALGOL-68/peano-curve.alg b/Task/Peano-curve/ALGOL-68/peano-curve.alg index bc5d4c2bbb..2f62d20b9a 100644 --- a/Task/Peano-curve/ALGOL-68/peano-curve.alg +++ b/Task/Peano-curve/ALGOL-68/peano-curve.alg @@ -53,7 +53,7 @@ BEGIN # Peano Curve in SVG # put( svg file, ( "'/>", newline, "", newline ) ); close( svg file ) - FI # sierpinski square # ; + FI # peano curve # ; peano curve( "peano.svg", 1200, 12, 3, 50, 50 ) diff --git a/Task/Peano-curve/Ada/peano-curve.ada b/Task/Peano-curve/Ada/peano-curve.adb similarity index 100% rename from Task/Peano-curve/Ada/peano-curve.ada rename to Task/Peano-curve/Ada/peano-curve.adb diff --git a/Task/Peano-curve/C/peano-curve.c b/Task/Peano-curve/C/peano-curve.c index 7d70c91302..50e63f94c6 100644 --- a/Task/Peano-curve/C/peano-curve.c +++ b/Task/Peano-curve/C/peano-curve.c @@ -1,35 +1,82 @@ -/*Abhishek Ghosh, 14th September 2018*/ +#include -#include -#include +#include +#include -void Peano(int x, int y, int lg, int i1, int i2) { +/* should be a power of 3 e.g. 1, 3, 9, 27, 81, 243, 729 */ +const int peano_width = 81; +/* the window is a square */ +const int window_side_len = 800; + +void +peano(sfVertexArray *verts, int x, int y, int lg, int i1, int i2) +{ + /* initial x, initial y, curve width (3^m), initial i1, initial i2 */ if (lg == 1) { - lineto(3*x,3*y); + sfVertex v; + v.position.x = 12.0 * x; /* multiply by 12 to scale-up the curve */ + v.position.y = 12.0 * y; + v.color = sfWhite; + sfVertexArray_append(verts, v); return; } - lg = lg/3; - Peano(x+(2*i1*lg), y+(2*i1*lg), lg, i1, i2); - Peano(x+((i1-i2+1)*lg), y+((i1+i2)*lg), lg, i1, 1-i2); - Peano(x+lg, y+lg, lg, i1, 1-i2); - Peano(x+((i1+i2)*lg), y+((i1-i2+1)*lg), lg, 1-i1, 1-i2); - Peano(x+(2*i2*lg), y+(2*(1-i2)*lg), lg, i1, i2); - Peano(x+((1+i2-i1)*lg), y+((2-i1-i2)*lg), lg, i1, i2); - Peano(x+(2*(1-i1)*lg), y+(2*(1-i1)*lg), lg, i1, i2); - Peano(x+((2-i1-i2)*lg), y+((1+i2-i1)*lg), lg, 1-i1, i2); - Peano(x+(2*(1-i2)*lg), y+(2*i2*lg), lg, 1-i1, i2); + + peano(verts, x+(2*i1*lg), y+(2*i1*lg), lg, i1, i2); + peano(verts, x+((i1-i2+1)*lg), y+((i1+i2)*lg), lg, i1, 1-i2); + peano(verts, x+lg, y+lg, lg, i1, 1-i2); + peano(verts, x+((i1+i2)*lg), y+((i1-i2+1)*lg), lg, 1-i1, 1-i2); + peano(verts, x+(2*i2*lg), y+(2*(1-i2)*lg), lg, i1, i2); + peano(verts, x+((1+i2-i1)*lg), y+((2-i1-i2)*lg), lg, i1, i2); + peano(verts, x+(2*(1-i1)*lg), y+(2*(1-i1)*lg), lg, i1, i2); + peano(verts, x+((2-i1-i2)*lg), y+((1+i2-i1)*lg), lg, 1-i1, i2); + peano(verts, x+(2*(1-i2)*lg), y+(2*i2*lg), lg, 1-i1, i2); } -int main(void) { +int +main(void) +{ + sfVideoMode mode = {window_side_len, window_side_len, 32}; + sfRenderWindow* window; + sfEvent event; + sfVideoMode vidmode; + sfVector2i winpos; + sfVertexArray *verts; - initwindow(1000,1000,"Peano, Peano"); + /* this will end up holding peano_width^2 vertices */ + verts = sfVertexArray_create(); + sfVertexArray_setPrimitiveType(verts, sfLineStrip); - Peano(0, 0, 1000, 0, 0); /* Start Peano recursion. */ - - getch(); - cleardevice(); - - return 0; + /* Create the main window */ + window = sfRenderWindow_create(mode, "Peano Curve", sfResize | sfClose, NULL); + if (!window) + return EXIT_FAILURE; + + /* Centre the window */ + vidmode = sfVideoMode_getDesktopMode(); + winpos.x = vidmode.width/2 - window_side_len/2; + winpos.y = vidmode.height/2 - window_side_len/2; + sfRenderWindow_setPosition(window, winpos); + + /* Generate the vertices */ + peano(verts, 0, 0, peano_width, 0, 0); + + /* Start the event loop */ + while (sfRenderWindow_isOpen(window)) { + /* Process events */ + while (sfRenderWindow_pollEvent(window, &event)) { + /* Close window : exit */ + if (event.type == sfEvtClosed) + sfRenderWindow_close(window); + } + + sfRenderWindow_clear(window, sfBlack); + /* Render the line */ + sfRenderWindow_drawVertexArray(window, verts, NULL); + sfRenderWindow_display(window); + } + sfRenderWindow_destroy(window); + + return EXIT_SUCCESS; } diff --git a/Task/Peano-curve/EasyLang/peano-curve.easy b/Task/Peano-curve/EasyLang/peano-curve.easy index 4b695b0ad2..b55b67d5d2 100644 --- a/Task/Peano-curve/EasyLang/peano-curve.easy +++ b/Task/Peano-curve/EasyLang/peano-curve.easy @@ -1,4 +1,4 @@ -proc lsysexp level . axiom$ rules$[] . +proc lsysexp level &axiom$ &rules$[] . for l to level an$ = "" for c$ in strchars axiom$ @@ -13,14 +13,15 @@ proc lsysexp level . axiom$ rules$[] . swap axiom$ an$ . . -proc lsysdraw axiom$ x y ang . . - linewidth 0.3 - move x y +proc lsysdraw axiom$ x y ang . + glinewidth 0.3 for c$ in strchars axiom$ if c$ = "F" + px = x + py = y x += cos dir y += sin dir - line x y + gline px py x y elif c$ = "-" dir -= ang elif c$ = "+" diff --git a/Task/Peano-curve/Julia/peano-curve.julia b/Task/Peano-curve/Julia/peano-curve.jl similarity index 100% rename from Task/Peano-curve/Julia/peano-curve.julia rename to Task/Peano-curve/Julia/peano-curve.jl diff --git a/Task/Peano-curve/Rust/peano-curve.rust b/Task/Peano-curve/Rust/peano-curve.rs similarity index 100% rename from Task/Peano-curve/Rust/peano-curve.rust rename to Task/Peano-curve/Rust/peano-curve.rs diff --git a/Task/Peano-curve/V-(Vlang)/peano-curve.v b/Task/Peano-curve/V-(Vlang)/peano-curve.v new file mode 100644 index 0000000000..35c82b398f --- /dev/null +++ b/Task/Peano-curve/V-(Vlang)/peano-curve.v @@ -0,0 +1,57 @@ +import gg +import gx + +struct Point { + x f32 + y f32 +} + +struct Peano { + width int + mut: + points []Point +} + +fn (mut pea Peano) peano(x int, y int, plg int, i1 int, i2 int) { + mut lg := plg + if lg == 1 { + px := f32(pea.width - x) * 10 + py := f32(pea.width - y) * 10 + pea.points << Point{px, py} + return + } + lg /= 3 + pea.peano(x + 2 * i1 * lg, y + 2 * i1 * lg, lg, i1, i2) + pea.peano(x + (i1 - i2 + 1) * lg, y + (i1 + i2) * lg, lg, i1, 1 - i2) + pea.peano(x + lg, y + lg, lg, i1, 1 - i2) + pea.peano(x + (i1 + i2) * lg, y + (i1 - i2 + 1) * lg, lg, 1 - i1, 1 - i2) + pea.peano(x + 2 * i2 * lg, y + 2 * (1 - i2) * lg, lg, i1, i2) + pea.peano(x + (1 + i2 - i1) * lg, y + (2 - i1 - i2) * lg, lg, i1, i2) + pea.peano(x + 2 * (1 - i1) * lg, y + 2 * (1 - i1) * lg, lg, i1, i2) + pea.peano(x + (2 - i1 - i2) * lg, y + (1 + i2 - i1) * lg, lg, 1 - i1, i2) + pea.peano(x + 2 * (1 - i2) * lg, y + 2 * i2 * lg, lg, 1 - i1, i2) +} + +fn frame(mut ctx gg.Context) { + mut peano_obj := Peano{width: 81} + peano_obj.peano(0, 0, peano_obj.width, 0, 0) + ctx.begin() + color := gx.rgb(255, 0, 255) // magenta + for i := 0; i < peano_obj.points.len - 1; i++ { + p1 := peano_obj.points[i] + p2 := peano_obj.points[i + 1] + ctx.draw_line(p1.x, p1.y, p2.x, p2.y, color) + } + ctx.end() +} + +fn main() { + mut context := gg.new_context( + width: 820 + height: 820 + window_title: 'Peano Curve' + bg_color: gx.white + frame_fn: frame + ) + context.run() +} diff --git a/Task/Peano-curve/VBScript/peano-curve.vb b/Task/Peano-curve/VBScript/peano-curve.vbs similarity index 100% rename from Task/Peano-curve/VBScript/peano-curve.vb rename to Task/Peano-curve/VBScript/peano-curve.vbs diff --git a/Task/Pell-numbers/Julia/pell-numbers.julia b/Task/Pell-numbers/Julia/pell-numbers-1.jl similarity index 100% rename from Task/Pell-numbers/Julia/pell-numbers.julia rename to Task/Pell-numbers/Julia/pell-numbers-1.jl diff --git a/Task/Pell-numbers/Julia/pell-numbers-2.jl b/Task/Pell-numbers/Julia/pell-numbers-2.jl new file mode 100644 index 0000000000..9884f44748 --- /dev/null +++ b/Task/Pell-numbers/Julia/pell-numbers-2.jl @@ -0,0 +1,2 @@ +pell(n::Integer) = last(BigInt[2 1; 1 0] ^ n * BigInt[1, 0]) +pelllucas(n::Integer) = last(BigInt[2 1; 1 0] ^ n * BigInt[2, 2]) diff --git a/Task/Pell-numbers/Oberon-07/pell-numbers.oberon b/Task/Pell-numbers/Oberon-07/pell-numbers.oberon new file mode 100644 index 0000000000..528c1b44c5 --- /dev/null +++ b/Task/Pell-numbers/Oberon-07/pell-numbers.oberon @@ -0,0 +1,96 @@ +MODULE PellNumbers; (* find some Pell numbersl trans Algol W, FreeBasic, Phix *) + IMPORT Out, Math; + + CONST MAXP = 9; + VAR p, pl :ARRAY 21 OF INTEGER; (* need more than 10 Pell numbers *) + c, pdx, j, n, nsw :INTEGER; (* to find the fifth Pell prime *) + + (* returns true if n is prime, false otherwise, uses trial division *) + PROCEDURE isPrime( n : INTEGER ):BOOLEAN; + VAR prime :BOOLEAN; + f, f2, toNext :INTEGER; + BEGIN + IF n < 3 THEN prime := n = 2 + ELSIF n MOD 3 = 0 THEN prime := n = 3 + ELSIF ~ ODD( n ) THEN prime := FALSE + ELSE + prime := TRUE; + f := 5; + f2 := 25; + toNext := 24; (* note: ( 2n + 1 )^2 - ( 2n - 1 )^2 = 8n *) + WHILE ( f2 <= n ) & prime DO + prime := n MOD f # 0; + INC( f, 2 ); + f2 := toNext; + INC( toNext, 8 ) + END + END + RETURN prime + END isPrime; + + PROCEDURE NearIsoscelesRightTriangles; + VAR i, i0, i1, i2, t, found :INTEGER; + BEGIN + i0 := 0; i1 := 1; t := 1; found := 0; + i := 1; + WHILE found < 10 DO + INC( i );; + i2 := i1*2 + i0; + IF ODD( i ) THEN + Out.String( " [" );Out.Int( t, 0 ); + Out.String( ", " );Out.Int( t + 1, 0 ); + Out.String( ", " );Out.Int( i2, 0 ); + Out.String( "]" );Out.Ln; + INC( found ) + END; + INC( t, i2 ); i0 := i1; i1 := i2 + END + END NearIsoscelesRightTriangles; + +BEGIN + + p[ 0 ] := 0; p[ 1 ] := 1; + pl[ 0 ] := 2; pl[ 1 ] := 2; + FOR n := 2 TO 20 DO + p[ n ] := 2 * p[ n - 1 ] + p[ n - 2 ]; + pl[ n ] := 2 * pl[ n - 1 ] + pl[ n - 2 ] + END; + + Out.String( "First 10 Pell numbers:" ); + FOR n := 0 TO MAXP DO Out.String( " " );Out.Int( p[ n ], 1 ) END; Out.Ln; + Out.String( "First 10 Pell-Lucas numbers:" ); + FOR n := 0 TO MAXP DO Out.String( " " );Out.Int( pl[ n ], 1 ) END; Out.Ln; + + Out.Ln;Out.String( "First 10 rational approximations of sqrt(2) (" ); + Out.Real( Math.sqrt( 2.0 ), 8 );Out.String( "):" ); + FOR n := 1 TO MAXP DO + j := pl[ n ] DIV 2; + Out.Ln; + Out.String( " " );Out.Int( j, 0 );Out.String( "/" );Out.Int( p[ n ], 0 ); + Out.String( " ~= " );Out.Real( FLT( j ) / FLT( p[ n ] ), 8 ); + END; + Out.Ln; + Out.Ln;Out.String( "First 5 Pell primes:" ); + Out.Ln;Out.String( "index Pell prime" ); + + c := 0; + pdx := 2; + WHILE c < 5 DO + IF isPrime( p[ pdx ] ) THEN + Out.Ln;Out.Int( pdx, 6 );Out.String( " " );Out.Int( p[ pdx ], 0 ); + INC( c ) + END; + INC( pdx ) + END; + + Out.Ln;Out.Ln;Out.String( "First 10 Newman-Shank-Williams numbers:" );Out.Ln; + FOR n := 0 TO MAXP DO + nsw := p[ 2 * n ] + p[ 2 * n + 1 ]; + Out.String( " " );Out.Int( nsw, 0 ) + END; + + Out.Ln; + Out.Ln;Out.String( "First 10 near isosceles right triangles:" );Out.Ln; + NearIsoscelesRightTriangles + +END PellNumbers. diff --git a/Task/Pell-numbers/PARI-GP/pell-numbers.parigp b/Task/Pell-numbers/PARI-GP/pell-numbers.parigp new file mode 100644 index 0000000000..f2e163f191 --- /dev/null +++ b/Task/Pell-numbers/PARI-GP/pell-numbers.parigp @@ -0,0 +1,59 @@ +\\--- pell.gp ------------------------------------------------------------ + +\\ 1) Define Pell numbers and Pell–Lucas numbers by simple recursion + +pell(n) = +{ + if (n==0, return(0)); + if (n==1, return(1)); + return(2*pell(n-1) + pell(n-2)); +} + +pellL(n) = +{ + if (n==0, return(2)); + if (n==1, return(2)); + return(2*pellL(n-1) + pellL(n-2)); +} + +\\ 2) Compute the first 10 Pell and Pell–Lucas numbers +pns = vector(10, i, pell(i-1)); \\ pell(0) .. pell(9) +plns = vector(10, i, pellL(i-1)); \\ pellL(0) .. pellL(9) + +print("Pell numbers (n=0..9): ", pns); +print("Pell–Lucas numbers (n=0..9): ", plns); + +\\ 3) Form the ratios (Pell–Lucas)/2 over Pell, skipping n=0 +\\ i.e. for n=1..9 +denom = vector(9, i, pns[i+1]); \\ pns[2..10] +numr = vector(9, i, plns[i+1]/2); \\ plns[2..10]/2 +approx = vector(9, i, numr[i]/denom[i]); + +print("Ratios (pellL(n)/2) / pell(n) for n=1..9:"); +for (i=1,9, print(i, ": ", approx[i])); +print("Numeric floats:"); +for (i=1,9, print(i, ": ", real(approx[i]))); + +\\ 4) List (n, pell(n)) for n=0..100 and pick the first 10 where pell(n) is prime +plist = vector(101, i, [i-1, pell(i-1)]); +primespell = select(x->isprime(x[2]), plist); +print("First 10 Pell(n) that are prime:"); +for (i=1,10, print(primespell[i])); + +\\ 5) Define PellS(n) = If[n==0,1, pell(2n) + pell(2n+1)] +pellS(n) = if(n==0, 1, pell(2*n) + pell(2*n+1)); +print("PellS(n) for n=0..19:"); +print(vector(20, n, pellS(n))); + +\\ 6) Generate Pythagorean triples from Pell numbers: +\\ short = sum_{k=1..2n} pell(k), long = short+1, hypo = pell(2n+1) +pythag(n) = +{ + short = sum(k=1, 2*n, pell(k)); + long = short + 1; + hypo = pell(2*n + 1); + return([short, long, hypo]); +} + +print("Pythagorean triples for n=0..9:"); +for (n=0,9, print(n, ": ", pythag(n))); diff --git a/Task/Pell-numbers/Sidef/pell-numbers.sidef b/Task/Pell-numbers/Sidef/pell-numbers.sidef new file mode 100644 index 0000000000..592a4136e6 --- /dev/null +++ b/Task/Pell-numbers/Sidef/pell-numbers.sidef @@ -0,0 +1,31 @@ +func pell_number(n) { + lucasU(2, -1, n) +} + +func pell_lucas_number(n) { + lucasV(2, -1, n) +} + +say ("The first 10 Pell numbers: ", 10.of(pell_number).join(", ")) +say ("The first 10 Pell-Lucas numbers: ", 10.of(pell_lucas_number).join(", ")) + +say "\nFirst 10 rational approximations to √2:" +{|n| pell_lucas_number(n) / 2 / pell_number(n) }.map(1..10).each {|r| + say "#{'%10s' % r.as_frac} =~ #{r.as_float}" +} + +var pell_prime_indices = 10.by {|n| pell_number(n).is_prime } +say "\nThe first 10 Pell primes: " +pell_prime_indices.each {|n| + say "Pell(#{'%2s' % n}) = #{pell_number(n)}" +} + +say ("\nThe first 10 Newman-Shank-Williams numbers: ", + 10.of{|n| pell_number(2*n) + pell_number(2*n + 1) }.join(', ')) + +say "\nThe first 10 Pythagorean triples corresponding to near isosceles right triangles:" +10.of{|n| pell_number(2*n + 1) }.map {|h| + var t = isqrt(h**2 >> 1) + assert_eq(t**2 + (t+1)**2, h**2) + [t, t+1, h] +}.each{.say} diff --git a/Task/Pell-numbers/Unicon/pell-numbers.unicon b/Task/Pell-numbers/Unicon/pell-numbers.unicon new file mode 100644 index 0000000000..c21b74d04a --- /dev/null +++ b/Task/Pell-numbers/Unicon/pell-numbers.unicon @@ -0,0 +1,50 @@ +link fastprime + +global pidx + +procedure main(A) + limit := \A[1] | 10 + write("Pell numbers:") + every writes(" ",pell(0,1)\limit | "\n") + + write("\nPell-Lucas numbers:") + every writes(" ",pell(2,2)\limit | "\n") + + write("\nRational approximations to sqrt(2):") + @(cp := create pell(0,1)) + @(cl := create pell(2,2)) + cnt := 1 + while (cnt <= limit, cnt +:=1) do + (n := @cl/2, d := @cp, write(" (",n,"/",d,") = ",real(n)/d)) + + write("\n(Pell Prime Index,Pell Prime):") + every p := is_prime(pell(0,1))\limit do write(" (",pidx,",",p,")") + + write("\nNSW numbers:") + every writes(" ",nsw()\limit | "\n") + + write("\nTriangles:") + every write(" ",triangles()\limit) +end + +procedure pell(p0,p1) + pidx := -1 + repeat suspend 1(p := 2*p1 + p0, p :=: p1 :=: p0, pidx +:= 1) +end + +procedure nsw() + ps := [] + n := 0 + every put(ps,pell(0,1)) do + if *ps >= 2 then suspend 1(ps[2*n+1]+ps[2*n+2], n +:= 1) +end + +procedure triangles() + n := 3 + repeat { + (sum := 0, ps := [0]) + every put(ps,pell(0,1))\(n+1) do sum +:= ps[*ps-1] + suspend (n%2 = 1, "("||sum||","||(sum+1)||","||ps[*ps]||")") + n +:= 1 + } +end diff --git a/Task/Pells-equation/Ada/pells-equation.ada b/Task/Pells-equation/Ada/pells-equation.adb similarity index 100% rename from Task/Pells-equation/Ada/pells-equation.ada rename to Task/Pells-equation/Ada/pells-equation.adb diff --git a/Task/Pells-equation/Delphi/pells-equation.delphi b/Task/Pells-equation/Delphi/pells-equation.pas similarity index 100% rename from Task/Pells-equation/Delphi/pells-equation.delphi rename to Task/Pells-equation/Delphi/pells-equation.pas diff --git a/Task/Pells-equation/Fortran/pells-equation.f b/Task/Pells-equation/Fortran/pells-equation.f new file mode 100644 index 0000000000..fc14cdf312 --- /dev/null +++ b/Task/Pells-equation/Fortran/pells-equation.f @@ -0,0 +1,53 @@ + PROGRAM Pell + IMPLICIT NONE + INTEGER n(4) + DATA n /61, 109, 181, 277/ + INTEGER*16 x, y + INTEGER i + + DO 10, i = 1, size(n) + CALL solve(n(i), x, y) +10 PRINT 100, n(i), x, y + +100 FORMAT ('x² - ', i3, 'y² = 1; x = ', i24, ' and y = ', i24) + END PROGRAM + + + SUBROUTINE solve(n, a, b) + IMPLICIT INTEGER*16 (A-Z) + INTEGER n + + x = INT(sqrt(REAL(n))) + IF (x**2 .ne. n) GOTO 10 + + a = 1 ! perfect square; only trivial solution exists + b = 0 + RETURN + +10 y = x + z = 1 + r = 2*x + e1 = 1 + e2 = 0 + f1 = 0 + f2 = 1 + +20 y = r*z - y + z = (n - y**2) / z + r = (x + y) / z + + e3 = r*e2 + e1 + e1 = e2 + e2 = e3 + + f3 = r*f2 + f1 + f1 = f2 + f2 = f3 + + a = e2 + x*f2 + b = f2 + + IF (a**2 - n*b**2 .eq. 1) RETURN + GOTO 20 + + END SUBROUTINE diff --git a/Task/Pells-equation/Julia/pells-equation.julia b/Task/Pells-equation/Julia/pells-equation.jl similarity index 100% rename from Task/Pells-equation/Julia/pells-equation.julia rename to Task/Pells-equation/Julia/pells-equation.jl diff --git a/Task/Pells-equation/Kotlin/pells-equation.kotlin b/Task/Pells-equation/Kotlin/pells-equation.kts similarity index 100% rename from Task/Pells-equation/Kotlin/pells-equation.kotlin rename to Task/Pells-equation/Kotlin/pells-equation.kts diff --git a/Task/Pells-equation/Langur/pells-equation.langur b/Task/Pells-equation/Langur/pells-equation.langur index c2e101a25d..2ce6536e86 100644 --- a/Task/Pells-equation/Langur/pells-equation.langur +++ b/Task/Pells-equation/Langur/pells-equation.langur @@ -1,31 +1,31 @@ -val .fun = fn(.a, .b, .c) [.b, .b * .c + .a] +val fun = fn(a, b, c) { [b, b * c + a] } -val .solvePell = fn(.n) { - val .x = trunc .n ^/ 2 - var .y, .z, .r = .x, 1, .x * 2 - var .e1, .e2, .f1, .f2 = 1, 0, 0, 1 +val solvePell = fn(n) { + val x = trunc(n ^/ 2) + var y, z, r = x, 1, x * 2 + var e1, e2, f1, f2 = 1, 0, 0, 1 for { - .y = .r * .z - .y - .z = (.n - .y * .y) \ .z - .r = (.x + .y) \ .z - .e1, .e2 = .fun(.e1, .e2, .r) - .f1, .f2 = .fun(.f1, .f2, .r) - val .b, .a = .fun(.e2, .f2, .x) - if .a^2 - .n * .b^2 == 1: return [.a, .b] + y = r * z - y + z = (n - y * y) \ z + r = (x + y) \ z + e1, e2 = fun(e1, e2, r) + f1, f2 = fun(f1, f2, r) + val b, a = fun(e2, f2, x) + if a^2 - n * b^2 == 1: return [a, b] } } -val .C = fn(.x) { - # format number string with commas - var .neg, .s = "", string .x - if .s[1] == '-' { - .neg, .s = "-", rest .s +val C = fn(x) { + # format integer string with commas + var neg, s = "", x -> string + if s[1] == '-' { + neg, s = "-", less(s, of=1) } - .neg ~ join ",", split -3, .s + neg ~ join(split(s, delim=-3), delim=",") } -for .n in [61, 109, 181, 277, 8941] { - val .x, .y = .solvePell(.n) - writeln $"x² - \.n;y² = 1 for:\n\tx = \.x:.C;\n\ty = \.y:.C;\n" +for n in [61, 109, 181, 277, 8941] { + val x, y = solvePell(n) + writeln "x² - {{n}}y² = 1 for:\n\tx = {{x:fn C}}\n\ty = {{y:fn C}}\n" } diff --git a/Task/Pells-equation/PascalABC.NET/pells-equation.pas b/Task/Pells-equation/PascalABC.NET/pells-equation.pas new file mode 100644 index 0000000000..123613e4ee --- /dev/null +++ b/Task/Pells-equation/PascalABC.NET/pells-equation.pas @@ -0,0 +1,31 @@ +function solvePell(n: integer): (biginteger, biginteger); +begin + var x: biginteger := n.sqrt.floor; + var (y, z, r) := (x, 1bi, x shl 1); + var (e1, e2) := (1bi, 0bi); + var (f1, f2) := (0bi, 1bi); + + repeat + y := r * z - y; + z := (n - y * y) div z; + r := (x + y) div z; + + (e1, e2) := (e2, e1 + e2 * r); + (f1, f2) := (f2, f1 + f2 * r); + + var (a, b) := (f2 * x + e2, f2); + if a * a - n * b * b = 1 then + begin + result := (a, b); + exit + end; + until false; +end; + +begin + foreach var n in |61, 109, 181, 277| do + begin + var (x, y) := solvePell(n); + writeln('x² - ', n:3, ' * y² = 1 for (x, y) = (', x:21, ',',y:20, ')'); + end; +end. diff --git a/Task/Pells-equation/Phix/pells-equation.phix b/Task/Pells-equation/Phix/pells-equation.phix index 6ab4a35fca..ec3426b926 100644 --- a/Task/Pells-equation/Phix/pells-equation.phix +++ b/Task/Pells-equation/Phix/pells-equation.phix @@ -1,64 +1,62 @@ -(phixonline)--> - with javascript_semantics +with javascript_semantics - include mpfr.e +include mpfr.e - procedure fun(mpz a,b,t, integer c) - -- {a,b} = {b,c*b+a} (and t gets trashed) - mpz_set(t,a) - mpz_set(a,b) - mpz_mul_si(b,b,c) - mpz_add(b,b,t) - end procedure +procedure fun(mpz a,b,t, integer c) +-- {a,b} = {b,c*b+a} (and t gets trashed) + mpz_set(t,a) + mpz_set(a,b) + mpz_mul_si(b,b,c) + mpz_add(b,b,t) +end procedure - function SolvePell(integer n) - integer x = floor(sqrt(n)), y = x, z = 1, r = x*2 - mpz e1 = mpz_init(1), e2 = mpz_init(), - f1 = mpz_init(), f2 = mpz_init(1), - t = mpz_init(0), u = mpz_init(), - a = mpz_init(1), b = mpz_init(0) - if x*x!=n then - while mpz_cmp_si(t,1)!=0 do - y = r*z - y - z = floor((n-y*y)/z) - r = floor((x+y)/z) - fun(e1,e2,t,r) -- {e1,e2} = {e2,r*e2+e1} - fun(f1,f2,t,r) -- {f1,f2} = {f2,r*r2+f1} - mpz_set(a,f2) - mpz_set(b,e2) - fun(b,a,t,x) -- {b,a} = {f2,x*f2+e2} - mpz_mul(t,a,a) - mpz_mul_si(u,b,n) - mpz_mul(u,u,b) - mpz_sub(t,t,u) -- t = a^2-n*b^2 - end while - end if - return {a, b} - end function +function SolvePell(integer n) +integer x = floor(sqrt(n)), y = x, z = 1, r = x*2 +mpz e1 = mpz_init(1), e2 = mpz_init(), + f1 = mpz_init(), f2 = mpz_init(1), + t = mpz_init(0), u = mpz_init(), + a = mpz_init(1), b = mpz_init(0) + if x*x!=n then + while mpz_cmp_si(t,1)!=0 do + y = r*z - y + z = floor((n-y*y)/z) + r = floor((x+y)/z) + fun(e1,e2,t,r) -- {e1,e2} = {e2,r*e2+e1} + fun(f1,f2,t,r) -- {f1,f2} = {f2,r*r2+f1} + mpz_set(a,f2) + mpz_set(b,e2) + fun(b,a,t,x) -- {b,a} = {f2,x*f2+e2} + mpz_mul(t,a,a) + mpz_mul_si(u,b,n) + mpz_mul(u,u,b) + mpz_sub(t,t,u) -- t = a^2-n*b^2 + end while + end if + return {a, b} +end function - function split_into_chunks(string x, integer one, rest) - sequence res = {x[1..one]} - x = x[one+1..$] - integer l = length(x) - while l do - integer k = min(l,rest) - res = append(res,x[1..k]) - x = x[k+1..$] - l -= k - end while - return join(res,"\n"&repeat(' ',29))&"\n"&repeat(' ',17) - end function +function split_into_chunks(string x, integer one, rest) + sequence res = {x[1..one]} + x = x[one+1..$] + integer l = length(x) + while l do + integer k = min(l,rest) + res = append(res,x[1..k]) + x = x[k+1..$] + l -= k + end while + return join(res,"\n"&repeat(' ',29))&"\n"&repeat(' ',17) +end function - sequence ns = {4, 61, 109, 181, 277, 8941} - for i=1 to length(ns) do - integer n = ns[i] - mpz {x, y} = SolvePell(n) - string xs = mpz_get_str(x,comma_fill:=true), - ys = mpz_get_str(y,comma_fill:=true) - if length(xs)>97 then - xs = split_into_chunks(xs,98,96) - ys = split_into_chunks(ys,99,96) - end if - printf(1,"x^2 - %3d*y^2 = 1 for x = %27s and y = %25s\n", {n, xs, ys}) - end for - + 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 + 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 and cheat versions) + include mpfr.e + atom t0 = time(), t1 = t0+1 + integer maxprime = 4423, -- 19937 (rather slow) + lim = length(get_primes_le(maxprime)) + mpz n = mpz_init(), m = mpz_init() + for i=1 to lim do + integer p = get_prime(i) + mpz_ui_pow_ui(n, 2, p) + mpz_sub_ui(n, n, 1) + if mpz_prime(n) then + mpz_ui_pow_ui(m, 2, p-1) + mpz_mul(n, n, m) + string ns = mpz_get_short_str(n,comma_fill:=true), + et = elapsed_short(time()-t0,5,"(%s)") + printf(1, "%d %s %s\n",{p,ns,et}) + elsif time()>t1 then + progress("%d/%d (%.1f%%)\r",{p,maxprime,i/lim*100}) + t1 = time()+1 + end if + end for + ?elapsed(time()-t0) + + include mpfr.e + atom t0 = time() + mpz n = mpz_init(), m = mpz_init() + sequence validp = {2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, + 1279, 2203, 2281, 3217, 4253, 4423, 9689, 9941, 11213, + 19937, 21701, 23209, 44497, 86243, 110503, 132049, 216091, + 756839, 859433, 1257787, 1398269, 2976221, 3021377, 6972593, + 13466917, 20996011, 24036583, 25964951, 30402457, 32582657, + 37156667, 42643801, 43112609, 57885161, + 74207281, 77232917, 82589933} + if platform()=JS then validp = validp[1..35] end if -- (keep it under 5s) + for p in validp do + mpz_ui_pow_ui(n, 2, p) + mpz_sub_ui(n, n, 1) + mpz_ui_pow_ui(m, 2, p-1) + mpz_mul(n, n, m) + string ns = mpz_get_short_str(n,comma_fill:=true), + et = elapsed_short(time()-t0,5,"(%s)") + printf(1, "%d %s %s\n",{p,ns,et}) + end for + ?elapsed(time()-t0) + - with javascript_semantics - function totient(integer n) - integer tot = n, i = 2 - while i*i<=n do - if mod(n,i)=0 then - while true do - n /= i - if mod(n,i)!=0 then exit end if - end while - tot -= tot/i - end if - i += iff(i=2?1:2) - end while - if n>1 then - tot -= tot/n - end if - return tot - end function +with javascript_semantics +function totient(integer n) + integer tot = n, i = 2 + while i*i<=n do + if mod(n,i)=0 then + while true do + n /= i + if mod(n,i)!=0 then exit end if + end while + tot -= tot/i + end if + i += iff(i=2?1:2) + end while + if n>1 then + tot -= tot/n + end if + return tot +end function - sequence perfect = {} - integer n = 1 - while length(perfect)<20 do - integer tot = n, - tsum = 0 - while tot!=1 do - tot = totient(tot) - tsum += tot - end while - if tsum=n then - perfect &= n - end if - n += 2 - end while - printf(1,"The first 20 perfect totient numbers are:\n") - ?perfect - - with javascript_semantics - constant match_wp = false +with javascript_semantics +constant match_wp = false - function prc(integer n) - constant t = {0,2,10,18,36,54,86,118,119} - integer row = abs(binary_search(n,t,true))-1, - col = n-t[row] - if col>1+(row>1) then - col = 18-(t[row+1]-n) - if match_wp then - if col<=2 then return {row+2,col+14} end if - else -- matches above ascii: - if col<=2+(row>5) then return {row+2,col+15} end if - end if - end if - return {row,col} - end function +function prc(integer n) + constant t = {0,2,10,18,36,54,86,118,119} + integer row = abs(binary_search(n,t,true))-1, + col = n-t[row] + if col>1+(row>1) then + col = 18-(t[row+1]-n) + if match_wp then + if col<=2 then return {row+2,col+14} end if + else -- matches above ascii: + if col<=2+(row>5) then return {row+2,col+15} end if + end if + end if + return {row,col} +end function - sequence pt = repeat(repeat(" ",19),10) - pt[1][2..$] = apply(true,sprintf,{{"%3d"},tagset(18)}) -- column headings - for i=1 to 9 do pt[i+1][1] = sprintf("%3d",i) end for -- row numbers - for i=1 to 118 do - integer {r,c} = prc(i) - pt[r+1][c+1] = sprintf("%3d",i) - end for - if not match_wp then -- (ascii only:) - pt[7][4] = " L*" - pt[8][4] = " A*" - pt[9][2..4] = {"Lanthanide:"} - pt[10][2..4] = {" Actinide:"} - end if - printf(1,"%s\n",{join(apply(true,join,{pt,{"|"}}),"\n")}) - - constant ptxt = """ - __________________________________________________________________________ - | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | - | | - |1 H He | - | | - |2 Li Be B C N O F Ne | - | | - |3 Na Mg Al Si P S Cl Ar | - | | - |4 K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn Ga Ge As Se Br Kr | - | | - |5 Rb Sr Y Zr Nb Mo Tc Ru Rh Pd Ag Cd In Sn Sb Te I Xe | - | | - |6 Cs Ba * Hf Ta W Re Os Ir Pt Au Hg Tl Pb Bi Po At Rn | - | | - |7 Fr Ra + Rf Db Sg Bh Hs Mt Ds Rg Cn Nh Fl Mc Lv Ts Og | - |__________________________________________________________________________| - | | - | | - |8 Lantanoidi* La Ce Pr Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb Lu | - | | - |9 Aktinoidi+ Ak Th Pa U Np Pu Am Cm Bk Cf Es Fm Md No Lr | - |__________________________________________________________________________| - """ +constant ptxt = """ + __________________________________________________________________________ +| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | +| | +|1 H He | +| | +|2 Li Be B C N O F Ne | +| | +|3 Na Mg Al Si P S Cl Ar | +| | +|4 K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn Ga Ge As Se Br Kr | +| | +|5 Rb Sr Y Zr Nb Mo Tc Ru Rh Pd Ag Cd In Sn Sb Te I Xe | +| | +|6 Cs Ba * Hf Ta W Re Os Ir Pt Au Hg Tl Pb Bi Po At Rn | +| | +|7 Fr Ra + Rf Db Sg Bh Hs Mt Ds Rg Cn Nh Fl Mc Lv Ts Og | +|__________________________________________________________________________| +| | +| | +|8 Lantanoidi* La Ce Pr Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb Lu | +| | +|9 Aktinoidi+ Ak Th Pa U Np Pu Am Cm Bk Cf Es Fm Md No Lr | +|__________________________________________________________________________| +""" - function tablify(string ptxt) - sequence lines = split(ptxt,"\n"), - res = {} - for l in lines do - integer ln = l[2]-'0', c = 0 - if ln>=1 and ln<=9 then - res = append(res,{}) - for j=5 to length(l) by 4 do - c += 1 - if l[j]>='A' and l[j+2]<=' ' then - res[$] = append(res[$],{trim(l[j..j+1]),ln,c}) - end if - end for - end if - end for - res[7][3..2] = res[9] - res[6][3..2] = res[8] - res = join(res[1..7],{},{}) - return res - end function +function tablify(string ptxt) + sequence lines = split(ptxt,"\n"), + res = {} + for l in lines do + integer ln = l[2]-'0', c = 0 + if ln>=1 and ln<=9 then + res = append(res,{}) + for j=5 to length(l) by 4 do + c += 1 + if l[j]>='A' and l[j+2]<=' ' then + res[$] = append(res[$],{trim(l[j..j+1]),ln,c}) + end if + end for + end if + end for + res[7][3..2] = res[9] + res[6][3..2] = res[8] + res = join(res[1..7],{},{}) + return res +end function - constant pt = apply(true,sprintf,{{"(%s) is at %d, %d"},tablify(ptxt)}) +constant pt = apply(true,sprintf,{{"(%s) is at %d, %d"},tablify(ptxt)}) - for e in {1,2,29,42,57,58,59,71,72,89,90,103,113} do - printf(1,"Element %d %s\n",{e,pt[e]}) - end for - coords target newvalues + ⍜⊡⋅∘⊃⊙⋅∘⋅∘ # stack->acb +) +˜↯Blu ⇌⊂3↯2 16 # base square +Rep ← ⍜(⊏0_1)≡×⊃⋅∘∘ # replaces an edge with multiple +⍜⍉₂(Rep2)Rep2 # brighten two edges +⍜⍉₂(Rep0.5)Rep0.5⍜⇌⍉₂ # darken two edges +˜↯Yello ⇌⊂3↯2 400 # draw the background +⊙◌+25×26°⊡˜↯0 ↯2 14 # calculate offsets +⊙◌∧(Add˜⊂0)♭₂ # Add boxes at these offsets diff --git a/Task/Perlin-noise/11l/perlin-noise.11l b/Task/Perlin-noise/11l/perlin-noise.11l index 5323903369..68d7176cea 100644 --- a/Task/Perlin-noise/11l/perlin-noise.11l +++ b/Task/Perlin-noise/11l/perlin-noise.11l @@ -12,7 +12,7 @@ V permutation = [151,160,137,91,90,15, 251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107, 49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254, 138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180] -L(i) 256 +L(i) 0.<256 p[256 + i] = p[i] = permutation[i] F fade(t) diff --git a/Task/Perlin-noise/ALGOL-68/perlin-noise.alg b/Task/Perlin-noise/ALGOL-68/perlin-noise.alg new file mode 100644 index 0000000000..8d1e72dc1c --- /dev/null +++ b/Task/Perlin-noise/ALGOL-68/perlin-noise.alg @@ -0,0 +1,77 @@ +BEGIN # perlin noise - translated from the 11l sample # + [ 0 : 511 ]INT p; + p[ 256 : ] := (151,160,137,91,90,15 + ,131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23 + ,190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33 + ,88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166 + ,77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244 + ,102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196 + ,135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123 + ,5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42 + ,223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9 + ,129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228 + ,251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107 + ,49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254 + ,138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180 + ); + p[ 0 : 255 ] := p[ 256 : ]; + + OP AND = ( INT a, b )INT: + IF a >= 0 + THEN ABS ( BIN a AND BIN b ) + ELSE ABS ( NOT BIN ( - ( a + 1 ) ) AND BIN b ) + FI # AND # ; + + PROC fade = ( REAL t )REAL: ( t * t * t ) * ( t * ( t * 6 - 15 ) + 10 ); + PROC linerp = ( REAL t, a, b )REAL: a + ( t * ( b - a ) ); + PROC grad = ( INT hash, REAL x, y, z )REAL: + BEGIN + INT h = hash AND 15; + REAL u = IF h < 8 THEN x ELSE y FI; + REAL v = IF h < 4 THEN y ELIF h = 12 OR h = 14 THEN x ELSE z FI; + IF ( h AND 1 ) = 0 THEN u ELSE -u FI + IF ( h AND 2 ) = 0 THEN v ELSE -v FI + END # grad # ; + PROC perlin noise = ( REAL x in, y in, z in )REAL: + BEGIN + REAL x := x in, y := y in, z := z in; + INT xx = ENTIER x AND 255; + INT yy = ENTIER y AND 255; + INT zz = ENTIER z AND 255; + x -:= ENTIER x; + y -:= ENTIER y; + z -:= ENTIER z; + REAL u = fade( x ); + REAL v = fade( y ); + REAL w = fade( z ); + INT a = p[ xx ] + yy; + INT aa = p[ a ] + zz; + INT ab = p[ a + 1 ] + zz; + INT b = p[ xx + 1 ] + yy; + INT ba = p[ b ] + zz; + INT bb = p[ b + 1 ] + zz; + linerp( w + , linerp( v + , linerp( u + , grad( p[ aa ], x, y, z ) + , grad( p[ ba ], x - 1, y, z ) + ) + , linerp( u + , grad( p[ ab ], x, y - 1, z ) + , grad( p[ bb ], x - 1, y - 1, z ) + ) + ) + , linerp( v + , linerp( u + , grad( p[ aa + 1 ], x, y, z - 1 ) + , grad( p[ ba + 1 ], x - 1, y, z - 1 ) + ) + , linerp( u + , grad( p[ ab + 1 ], x, y - 1, z - 1 ) + , grad( p[ bb + 1 ], x - 1, y - 1, z - 1 ) + ) + ) + ) + END # perlin noise # ; + + print( ( fixed( perlin noise( 3.14, 42, 7 ), -18, 15 ) ) ) +END diff --git a/Task/Perlin-noise/EasyLang/perlin-noise.easy b/Task/Perlin-noise/EasyLang/perlin-noise.easy index 4b0f9dda52..8fd4b68670 100644 --- a/Task/Perlin-noise/EasyLang/perlin-noise.easy +++ b/Task/Perlin-noise/EasyLang/perlin-noise.easy @@ -1,7 +1,6 @@ p[] = [ 151 160 137 91 90 15 131 13 201 95 96 53 194 233 7 225 140 36 103 30 69 142 8 99 37 240 21 10 23 190 6 148 247 120 234 75 0 26 197 62 94 252 219 203 117 35 11 32 57 177 33 88 237 149 56 87 174 20 125 136 171 168 68 175 74 165 71 134 139 48 27 166 77 146 158 231 83 111 229 122 60 211 133 230 220 105 92 41 55 46 245 40 244 102 143 54 65 25 63 161 1 216 80 73 209 76 132 187 208 89 18 169 200 196 135 130 116 188 159 86 164 100 109 198 173 186 3 64 52 217 226 250 124 123 5 202 38 147 118 126 255 82 85 212 207 206 59 227 47 16 58 17 182 189 28 42 223 183 170 213 119 248 152 2 44 154 163 70 221 153 101 155 167 43 172 9 129 22 39 253 19 98 108 110 79 113 224 232 178 185 112 104 218 246 97 228 251 34 242 193 238 210 144 12 191 179 162 241 81 51 145 235 249 14 239 107 49 192 214 31 181 199 106 157 184 84 204 176 115 121 50 45 127 4 150 254 138 236 205 93 222 114 67 29 24 72 243 141 128 195 78 66 215 61 156 180 ] -for i to 256 - p[] &= p[i] -. +for i to 256 : p[] &= p[i] +# func fade t . return t * t * t * (t * (t * 6 - 15) + 10) . @@ -61,15 +60,14 @@ func noise x y z . k8 = grad p[b2 + 2] (xx - 1) (yy - 1) (zz - 1) return lerp w (lerp v (lerp u k1 k2) (lerp u k3 k4)) (lerp v (lerp u k5 k6) (lerp u k7 k8)) . -numfmt 17 0 +numfmt 0 17 print noise 3.14 42 7 # # demo for y = 0 to 199 for x = 0 to 199 p = noise (x / 30) (y / 30) 0.1 - move x / 2 y / 2 - color3 p p p - rect 0.6 0.6 + gcolor3 p p p + grect x / 2 y / 2 0.6 0.6 . . diff --git a/Task/Perlin-noise/JavaScript/perlin-noise.js b/Task/Perlin-noise/JavaScript/perlin-noise.js new file mode 100644 index 0000000000..e982437274 --- /dev/null +++ b/Task/Perlin-noise/JavaScript/perlin-noise.js @@ -0,0 +1,80 @@ +let p = Array(512).fill(0); + +function fade(t) { + return t * t * t * (t * (t * 6 - 15) + 10); +} + +function lerp(t, a, b) { + return a + t * (b - a); +} + +function grad(hash, x, y, z) { + const h = hash & 15; // CONVERT LOW 4 BITS OF HASH CODE + const u = h < 8 ? x : y; // INTO 12 GRADIENT DIRECTIONS. + const v = h < 4 ? y : (h == 12 || h == 14) ? x : z; + return ((h & 1) == 0 ? u : -u) + ((h & 2) == 0 ? v : -v); +} + +function perlinNoise(x, y, z) { + const X = Math.floor(x) & 0xff; // FIND UNIT CUBE THAT + const Y = Math.floor(y) & 0xff; // CONTAINS POINT. + const Z = Math.floor(z) & 0xff; + x -= Math.floor(x); // FIND RELATIVE X,Y,Z + y -= Math.floor(y); // OF POINT IN CUBE. + z -= Math.floor(z); + + const u = fade(x); // COMPUTE FADE CURVES + const v = fade(y); // FOR EACH OF X,Y,Z. + const w = fade(z); + + const A = p[X] + Y; + const AA = p[A] + Z; + const AB = p[A + 1] + Z; // HASH COORDINATES OF + const B = p[X + 1] + Y; + const BA = p[B] + Z; + const BB = p[B + 1] + Z; // THE 8 CUBE CORNERS, + + return lerp(w, lerp(v, lerp(u, grad(p[AA ], x , y , z ), // AND ADD + grad(p[BA ], x - 1, y , z )), // BLENDED + lerp(u, grad(p[AB ], x , y - 1, z ), // RESULTS + grad(p[BB ], x - 1, y - 1, z ))), // FROM 8 + lerp(v, lerp(u, grad(p[AA + 1], x , y , z - 1), // CORNERS + grad(p[BA + 1], x - 1, y , z - 1)), // OF CUBE + lerp(u, grad(p[AB + 1], x , y - 1, z - 1), + grad(p[BB + 1], x - 1, y - 1, z - 1)))); +} + +async function readFile(fileName) { + try { + const response = await fetch('../' + fileName); + if (!response.ok) { + throw new Error('Cannot open file'); + } + const text = await response.text(); + const lines = text.split('\n'); + let index = 0; + + for (const line of lines) { + const numbers = line.split(','); + for (const word of numbers) { + if (word.trim()) { + const number = parseInt(word); + p[index] = number; + p[256 + index] = number; + index++; + } + } + } + } catch (error) { + console.error(error.message); + } +} + +async function main() { + await readFile('permutation.txt'); + + console.log('Perlin noise applied to (3.14, 42.0, 7.0) gives ' + + perlinNoise(3.14, 42.0, 7.0).toFixed(16)); +} + +main(); diff --git a/Task/Perlin-noise/Jq/perlin-noise.jq b/Task/Perlin-noise/Jq/perlin-noise.jq new file mode 100644 index 0000000000..9c5cb1c0bc --- /dev/null +++ b/Task/Perlin-noise/Jq/perlin-noise.jq @@ -0,0 +1,99 @@ +### Generic functions +# (-3.2|fraction) #=> -0.2 +def fraction: + if . >= 0 then . - trunc + else - (-. | fraction) + end; + +# For gojq +def div($y): + (. - (. % y)) / $y; + +# Convert the input integer to a stream of 0s and 1s, least significant bit first +def bitwise: + recurse( if . >= 2 then div(2) else empty end) | . % 2; + +# Inverse of bitwise: +def stream_to_integer(stream): + reduce stream as $c ( {power:1 , ans: 0}; + .ans += ($c * .power) | .power *= 2 ) + | .ans; + +# . & 2^($n-1) +def bits($n): + stream_to_integer(limit($n; bitwise)); + +### Perlin Noise +def permutation: [ + 151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, + 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148, + 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, + 57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, + 74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122, + 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54, + 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169, + 200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64, + 52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, + 207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213, + 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9, + 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, + 218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, + 81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157, + 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93, + 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180 +]; + +def grad($hash; $x; $y; $z): + def bit2: nth(1; bitwise); + # Convert low 4 bits of hash code into 12 gradient directions: + ( $hash|bits(4) ) as $h + | (if $h < 8 then $x else $y end) as $u + | (if $h < 4 then $y elif ($h == 12 or $h == 14) then $x else $z end) as $v + | (if ($h % 2 == 0) then $u else -$u end) + + (if (($h | bit2) == 0) then $v else -$v end) ; + +def noise($x; $y; $z): + def p: + permutation as $p + | $p[:256] + [range(256;512) | $p[.-256]]; + + def fade: + . * . * . * (. * (. * 6 - 15) + 10) ; + + def lerp($t; $a; $b): $a + $t * ($b - $a); + + # Find unit cube that contains point + ([$x,$y,$z] | map(floor | bits(8))) as [$xi, $yi, $zi] + + # Find relative x, y, z of point in cube + | ([$x,$y,$z] | map(fraction)) as [$xx, $yy, $zz] + + # Compute fade curves for each of xx, yy, zz + | ([$xx,$yy,$zz] | map(fade)) as [$u, $v, $w] + + | p as $p + # Hash co-ordinates of the 8 cube corners + # and add blended results from 8 corners of cube + | ($p[$xi] + $yi) as $a + | ($p[$a] + $zi) as $aa + | ($p[$a + 1] + $zi) as $ab + | ($p[$xi + 1] + $yi) as $b + | ($p[$b] + $zi) as $ba + | ($p[$b + 1] + $zi) as $bb + | lerp($w; + lerp($v; + lerp($u; + grad($p[$aa]; $xx; $yy; $zz); + grad($p[$ba]; $xx - 1; $yy; $zz)); + lerp($u; + grad($p[$ab]; $xx; $yy - 1; $zz); + grad($p[$bb]; $xx - 1; $yy - 1; $zz))); + lerp($v; + lerp($u; + grad($p[$aa + 1]; $xx; $yy; $zz - 1); + grad($p[$ba + 1]; $xx - 1; $yy; $zz - 1)); + lerp($u; + grad($p[$ab + 1]; $xx; $yy - 1; $zz - 1); + grad($p[$bb + 1]; $xx - 1; $yy - 1; $zz - 1))) ); + +noise(3.14; 42; 7) diff --git a/Task/Perlin-noise/Julia/perlin-noise.julia b/Task/Perlin-noise/Julia/perlin-noise.jl similarity index 100% rename from Task/Perlin-noise/Julia/perlin-noise.julia rename to Task/Perlin-noise/Julia/perlin-noise.jl diff --git a/Task/Perlin-noise/Kotlin/perlin-noise.kotlin b/Task/Perlin-noise/Kotlin/perlin-noise.kts similarity index 100% rename from Task/Perlin-noise/Kotlin/perlin-noise.kotlin rename to Task/Perlin-noise/Kotlin/perlin-noise.kts diff --git a/Task/Perlin-noise/Mathematica/perlin-noise.math b/Task/Perlin-noise/Mathematica/perlin-noise.math new file mode 100644 index 0000000000..7bdbcdeaa7 --- /dev/null +++ b/Task/Perlin-noise/Mathematica/perlin-noise.math @@ -0,0 +1,71 @@ +(* Fade function *) +fade[t_] := t^3 (t (t 6 - 15) + 10) + +(* Linear interpolation *) +lerp[t_, a_, b_] := a + t (b - a) + +(* Gradient function *) +grad[hash_, x_, y_, z_] := + Module[{h, u, v}, + h = BitAnd[hash, 15]; + u = If[h < 8, x, y]; + v = If[h < 4, y, If[MemberQ[{12, 14}, h], x, z]]; + (If[BitAnd[h, 1] == 0, u, -u]) + (If[BitAnd[h, 2] == 0, v, -v]) + ] + +(* Permutation table *) +permutation = { + 151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23, + 190,6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33, + 88,237,149,56,87,174,20,125,136,171,168,68,175,74,165,71,134,139,48,27,166, + 77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244, + 102,143,54,65,25,63,161,1,216,80,73,209,76,132,187,208,89,18,169,200,196, + 135,130,116,188,159,86,164,100,109,198,173,186,3,64,52,217,226,250,124,123, + 5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42, + 223,183,170,213,119,248,152,2,44,154,163,70,221,153,101,155,167,43,172,9, + 129,22,39,253,19,98,108,110,79,113,224,232,178,185,112,104,218,246,97,228, + 251,34,242,193,238,210,144,12,191,179,162,241,81,51,145,235,249,14,239,107, + 49,192,214,31,181,199,106,157,184,84,204,176,115,121,50,45,127,4,150,254, + 138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180 +}; + +(* Double the permutation to avoid wrap-around *) +p = Join[permutation, permutation]; + +(* Perlin noise function *) +perlinNoise[x_, y_, z_] := + Module[{X, Y, Z, u, v, w, A, AA, AB, B, BA, BB, xf, yf, zf}, + X = BitAnd[Floor[x], 255]; + Y = BitAnd[Floor[y], 255]; + Z = BitAnd[Floor[z], 255]; + xf = x - Floor[x]; + yf = y - Floor[y]; + zf = z - Floor[z]; + u = fade[xf]; + v = fade[yf]; + w = fade[zf]; + A = p[[X + 1]] + Y; + AA = p[[A + 1]] + Z; + AB = p[[A + 2]] + Z; + B = p[[X + 2]] + Y; + BA = p[[B + 1]] + Z; + BB = p[[B + 2]] + Z; + + lerp[w, + lerp[v, + lerp[u, grad[p[[AA + 1]], xf, yf, zf], + grad[p[[BA + 1]], xf - 1, yf, zf]], + lerp[u, grad[p[[AB + 1]], xf, yf - 1, zf], + grad[p[[BB + 1]], xf - 1, yf - 1, zf]] + ], + lerp[v, + lerp[u, grad[p[[AA + 2]], xf, yf, zf - 1], + grad[p[[BA + 2]], xf - 1, yf, zf - 1]], + lerp[u, grad[p[[AB + 2]], xf, yf - 1, zf - 1], + grad[p[[BB + 2]], xf - 1, yf - 1, zf - 1]] + ] + ] + ] + +(* Example usage *) +perlinNoise[3.14, 42, 7] // N[#, 17] & //Print diff --git a/Task/Perlin-noise/OCaml/perlin-noise.ocaml b/Task/Perlin-noise/OCaml/perlin-noise.ml similarity index 100% rename from Task/Perlin-noise/OCaml/perlin-noise.ocaml rename to Task/Perlin-noise/OCaml/perlin-noise.ml diff --git a/Task/Perlin-noise/Phix/perlin-noise.phix b/Task/Perlin-noise/Phix/perlin-noise.phix index 18a59099da..3acb325fe9 100644 --- a/Task/Perlin-noise/Phix/perlin-noise.phix +++ b/Task/Perlin-noise/Phix/perlin-noise.phix @@ -1,55 +1,53 @@ -(phixonline)--> - with javascript_semantics - constant ph = x"97 A0 89 5B 5A 0F 83 0D C9 5F 60 35 C2 E9 07 E1"& - x"8C 24 67 1E 45 8E 08 63 25 F0 15 0A 17 BE 06 94"& - x"F7 78 EA 4B 00 1A C5 3E 5E FC DB CB 75 23 0B 20"& - x"39 B1 21 58 ED 95 38 57 AE 14 7D 88 AB A8 44 AF"& - x"4A A5 47 86 8B 30 1B A6 4D 92 9E E7 53 6F E5 7A"& - x"3C D3 85 E6 DC 69 5C 29 37 2E F5 28 F4 66 8F 36"& - x"41 19 3F A1 01 D8 50 49 D1 4C 84 BB D0 59 12 A9"& - x"C8 C4 87 82 74 BC 9F 56 A4 64 6D C6 AD BA 03 40"& - x"34 D9 E2 FA 7C 7B 05 CA 26 93 76 7E FF 52 55 D4"& - x"CF CE 3B E3 2F 10 3A 11 B6 BD 1C 2A DF B7 AA D5"& - x"77 F8 98 02 2C 9A A3 46 DD 99 65 9B A7 2B AC 09"& - x"81 16 27 FD 13 62 6C 6E 4F 71 E0 E8 B2 B9 70 68"& - x"DA F6 61 E4 FB 22 F2 C1 EE D2 90 0C BF B3 A2 F1"& - x"51 33 91 EB F9 0E EF 6B 31 C0 D6 1F B5 C7 6A 9D"& - x"B8 54 CC B0 73 79 32 2D 7F 04 96 FE 8A EC CD 5D"& - x"DE 72 43 1D 18 48 F3 8D 80 C3 4E 42 D7 3D 9C B4", - p = ph&ph +with javascript_semantics +constant ph = x"97 A0 89 5B 5A 0F 83 0D C9 5F 60 35 C2 E9 07 E1"& + x"8C 24 67 1E 45 8E 08 63 25 F0 15 0A 17 BE 06 94"& + x"F7 78 EA 4B 00 1A C5 3E 5E FC DB CB 75 23 0B 20"& + x"39 B1 21 58 ED 95 38 57 AE 14 7D 88 AB A8 44 AF"& + x"4A A5 47 86 8B 30 1B A6 4D 92 9E E7 53 6F E5 7A"& + x"3C D3 85 E6 DC 69 5C 29 37 2E F5 28 F4 66 8F 36"& + x"41 19 3F A1 01 D8 50 49 D1 4C 84 BB D0 59 12 A9"& + x"C8 C4 87 82 74 BC 9F 56 A4 64 6D C6 AD BA 03 40"& + x"34 D9 E2 FA 7C 7B 05 CA 26 93 76 7E FF 52 55 D4"& + x"CF CE 3B E3 2F 10 3A 11 B6 BD 1C 2A DF B7 AA D5"& + x"77 F8 98 02 2C 9A A3 46 DD 99 65 9B A7 2B AC 09"& + x"81 16 27 FD 13 62 6C 6E 4F 71 E0 E8 B2 B9 70 68"& + x"DA F6 61 E4 FB 22 F2 C1 EE D2 90 0C BF B3 A2 F1"& + x"51 33 91 EB F9 0E EF 6B 31 C0 D6 1F B5 C7 6A 9D"& + x"B8 54 CC B0 73 79 32 2D 7F 04 96 FE 8A EC CD 5D"& + x"DE 72 43 1D 18 48 F3 8D 80 C3 4E 42 D7 3D 9C B4", + p = ph&ph - function fade(atom t) return t * t * t * (t * (t * 6 - 15) + 10) end function - function lerp(atom t, a, b) return a + t * (b - a) end function - function grad(int hash, atom x, y, z) - int h = and_bits(hash,15) - atom u = iff(h<8 ? x : y), - v = iff(h<4 ? y : iff(h==12 or h==14 ? x : z)) - return iff(and_bits(h,1) == 0 ? u : -u) + - iff(and_bits(h,2) == 0 ? v : -v) - end function +function fade(atom t) return t * t * t * (t * (t * 6 - 15) + 10) end function +function lerp(atom t, a, b) return a + t * (b - a) end function +function grad(int hash, atom x, y, z) + int h = and_bits(hash,15) + atom u = iff(h<8 ? x : y), + v = iff(h<4 ? y : iff(h==12 or h==14 ? x : z)) + return iff(and_bits(h,1) == 0 ? u : -u) + + iff(and_bits(h,2) == 0 ? v : -v) +end function - function noise(atom x, y, z) - integer X = and_bits(x,255), - Y = and_bits(y,255), - Z = and_bits(z,255) - x -= floor(x) - y -= floor(y) - z -= floor(z) - atom u = fade(x), - v = fade(y), - w = fade(z) - integer A = p[X+1]+Y, AA = p[A+1]+Z, AB = p[A+2]+Z, - B = p[X+2]+Y, BA = p[B+1]+Z, BB = p[B+2]+Z +function noise(atom x, y, z) + integer X = and_bits(x,255), + Y = and_bits(y,255), + Z = and_bits(z,255) + x -= floor(x) + y -= floor(y) + z -= floor(z) + atom u = fade(x), + v = fade(y), + w = fade(z) + integer A = p[X+1]+Y, AA = p[A+1]+Z, AB = p[A+2]+Z, + B = p[X+2]+Y, BA = p[B+1]+Z, BB = p[B+2]+Z - return lerp(w,lerp(v,lerp(u,grad(p[AA+1], x , y , z ), - grad(p[BA+1], x-1, y , z )), - lerp(u,grad(p[AB+1], x , y-1, z ), - grad(p[BB+1], x-1, y-1, z ))), - lerp(v,lerp(u,grad(p[AA+2], x , y , z-1 ), - grad(p[BA+2], x-1, y , z-1 )), - lerp(u,grad(p[AB+2], x , y-1, z-1 ), - grad(p[BB+2], x-1, y-1, z-1 )))) - end function + return lerp(w,lerp(v,lerp(u,grad(p[AA+1], x , y , z ), + grad(p[BA+1], x-1, y , z )), + lerp(u,grad(p[AB+1], x , y-1, z ), + grad(p[BB+1], x-1, y-1, z ))), + lerp(v,lerp(u,grad(p[AA+2], x , y , z-1 ), + grad(p[BA+2], x-1, y , z-1 )), + lerp(u,grad(p[AB+2], x , y-1, z-1 ), + grad(p[BB+2], x-1, y-1, z-1 )))) +end function - printf(1,"Perlin Noise for (3.14,42,7) is %.17f\n",{noise(3.14,42,7)}) - - with javascript_semantics - function pernicious(integer n) - return is_prime(sum(int_to_bits(n,32))) - end function +with javascript_semantics +function pernicious(integer n) + return is_prime(sum(int_to_bits(n,32))) +end function - sequence s = {} - integer n = 1 - while length(s)<25 do - if pernicious(n) then - s &= n - end if - n += 1 - end while - pp(s) - s = {} - for i=888_888_877 to 888_888_888 do - if pernicious(i) then - s &= i - end if - end for - pp(s) - R=0-255 G=0-255 B=0-255 +HsvToRgb ← memo( + # H S V C (where C = S x V) + ˜⊂⊸(/×↘1) + # C X(= Cx(1-abs((Hx6)mod2 -1)))[with rounding] m (=V-C) H (for later) + [⊃(⊣|ט-1⌵-1◿2÷1000⁅×6000°⊟⊏[0 ¯1]|/-↘2|⊢)] + ⊸[⊃([⊃(⊡0|⊡1|⋅0)] # CX0 + | [⊃(⊡1|⊡0|⋅0)] # XC0 + | [⊃(⋅0|⊡0|⊡1)] # 0CX + | [⊃(⋅0|⊡1|⊡0)] # 0XC + | [⊃(⊡1|⋅0|⊡0)] # X0C + | [⊃(⊡0|⋅0|⊡1)] # C0X + )] + ˜⊡⊙(⌊×6⊸⊣) # Add m to each. + ×255+⊙⊡₂ +) +≡(≡≡(÷255HsvToRgb[∘⊙1⊙1]-⊸⌊⁅₂+⊢)BaseImage) ÷50⇡50 +≡(▽₂ 4) diff --git a/Task/Play-recorded-sounds/Ada/play-recorded-sounds.adb b/Task/Play-recorded-sounds/Ada/play-recorded-sounds.adb new file mode 100644 index 0000000000..8bcfde7d19 --- /dev/null +++ b/Task/Play-recorded-sounds/Ada/play-recorded-sounds.adb @@ -0,0 +1,39 @@ +with Ada.Text_IO; use Ada.Text_IO; +with Sf.Audio.Music; use Sf, Sf.Audio, Sf.Audio.Music; + +procedure Play is + Sound1 : sfMusic_Ptr; + Sound2 : sfMusic_Ptr; +begin + Sound1 := createFromFile ("sound1.ogg"); + Sound2 := createFromFile ("sound2.ogg"); + if Sound1 = null or Sound2 = null then + Put_Line (Standard_Error, "Error: Sound files not found!"); + return; + end if; + + -- Looping for both sounds + setLoop (Sound1, sfTrue); + setLoop (Sound2, sfTrue); + + -- Setting the volume of each sound + setVolume (Sound1, 100.0); + setVolume (Sound2, 75.0); + + Put_Line ("Playing Sound1 individually... "); + play (Sound1); + delay 5.0; + + Put_Line ("Playing Sound1 and Sound2 simultaneously... "); + play (Sound2); + delay 10.0; + + Put_Line ("Stopping Sound1 before the end..."); + stop (Sound1); + + Put_Line ("Playing Sound2 alone for 5 seconds..."); + delay 5.0; + + destroy (Sound1); + destroy (Sound2); +end Play; diff --git a/Task/Play-recorded-sounds/Delphi/play-recorded-sounds.delphi b/Task/Play-recorded-sounds/Delphi/play-recorded-sounds.pas similarity index 100% rename from Task/Play-recorded-sounds/Delphi/play-recorded-sounds.delphi rename to Task/Play-recorded-sounds/Delphi/play-recorded-sounds.pas diff --git a/Task/Play-recorded-sounds/FreeBASIC/play-recorded-sounds.basic b/Task/Play-recorded-sounds/FreeBASIC/play-recorded-sounds.basic new file mode 100644 index 0000000000..f04f7cc00e --- /dev/null +++ b/Task/Play-recorded-sounds/FreeBASIC/play-recorded-sounds.basic @@ -0,0 +1,45 @@ +#include "windows.bi" +#include "win/mmsystem.bi" + +Const SND_LOOP = &H8 +Const SND_ASYNC = &H1 +Const SND_FILENAME = &H20000 + +' Reproducir un archivo MIDI +Dim As String midiFile = "canyon.mid" +mciSendString("play " & midiFile, 0, 0, 0) +Print "Playing a MIDI file..." + +Print !"\nPress a key to stop playback" +Do: Loop Until Inkey <> "" +mciSendString("stop " & midiFile, 0, 0, 0) +Print !"Stopped MIDI.\n" + +Sleep 4000 +Dim As String waveFile = "C:\windows\media\tada.wav" +Dim As Integer volume = 10000 +waveOutSetVolume(0, volume Or (volume Shl 16)) +PlaySound(waveFile, 0, SND_FILENAME Or SND_ASYNC) +Print "Playing the Windows TADA sound quietly..." + +Sleep 4000 +volume = 65535 +waveOutSetVolume(0, volume) +PlaySound(waveFile, 0, SND_FILENAME Or SND_ASYNC) +Print "Playing the Windows TADA sound loudly on the left channel..." + +Sleep 4000 +waveOutSetVolume(0, volume Shl 16) +PlaySound(waveFile, 0, SND_FILENAME Or SND_ASYNC) +Print "Playing the Windows TADA sound loudly on the right channel..." + +Sleep 4000 +waveOutSetVolume(0, volume Or (volume Shl 16)) +PlaySound(waveFile, 0, SND_FILENAME Or SND_ASYNC Or SND_LOOP) +Print "Looping the Windows TADA sound on both channels..." + +Sleep 4000 +PlaySound(0, 0, 0) +Print "Stopped looping..." + +Sleep diff --git a/Task/Play-recorded-sounds/FuncSug/play-recorded-sounds.funcsug b/Task/Play-recorded-sounds/FuncSug/play-recorded-sounds.funcsug new file mode 100644 index 0000000000..228c48d0c0 --- /dev/null +++ b/Task/Play-recorded-sounds/FuncSug/play-recorded-sounds.funcsug @@ -0,0 +1,30 @@ +# play the sounds sequentially +playSoundFile('rattle.mp3') +playSoundFile('tactactac.mp3') +playSoundFile('dingding.mp3') + +# play the sounds simultaneously +parallel || + playSoundFile('rattle.mp3') +|| + playSoundFile('tactactac.mp3') +|| + playSoundFile('dingding.mp3') + +# loop a sound +while true: + playSoundFile('rattle.mp3') + +# stop before the end of the sound +parallel exitWith branch 1 || + waitSeconds(4) +|| + playSoundFile('dingding.mp3') + +# stop all the sounds when the shortest one is finished +parallel exitAfter 1 finished || + playSoundFile('rattle.mp3') +|| + playSoundFile('tactactac.mp3') +|| + playSoundFile('dingding.mp3') diff --git a/Task/Play-recorded-sounds/Julia/play-recorded-sounds.julia b/Task/Play-recorded-sounds/Julia/play-recorded-sounds.jl similarity index 100% rename from Task/Play-recorded-sounds/Julia/play-recorded-sounds.julia rename to Task/Play-recorded-sounds/Julia/play-recorded-sounds.jl diff --git a/Task/Play-recorded-sounds/Raku/play-recorded-sounds.raku b/Task/Play-recorded-sounds/Raku/play-recorded-sounds.raku new file mode 100644 index 0000000000..73e8d5dc1f --- /dev/null +++ b/Task/Play-recorded-sounds/Raku/play-recorded-sounds.raku @@ -0,0 +1,31 @@ +# 20250723 Raku programming solution + +use Audio::Sndfile; +use Audio::PortAudio; + +sub play-wavs(Str $filename) { + my $sf = Audio::Sndfile.new(:filename($filename), :r); + die "Failed to open $filename" unless $sf; + my $sample-rate = $sf.samplerate; + my $channels = $sf.channels; + my $pa = Audio::PortAudio.new; + my $stream = $pa.open-default-stream( + 0, $channels, + Audio::PortAudio::StreamFormat::Float32, + $sample-rate, 512 + ); + $stream.start; + loop { + my ($buffer, $frames) = $sf.read-float(512, :raw); + $stream.write($buffer, $frames); + last if $frames < 512; + } + $stream.close; + $sf.close; +} + +sub MAIN(*@files) { + die "No files provided" unless @files; + + await Promise.allof( @files.map: { start { .&play-wavs } } ) +} diff --git a/Task/Playfair-cipher/11l/playfair-cipher.11l b/Task/Playfair-cipher/11l/playfair-cipher.11l index ded00dc3d0..08ccfa1d1f 100644 --- a/Task/Playfair-cipher/11l/playfair-cipher.11l +++ b/Task/Playfair-cipher/11l/playfair-cipher.11l @@ -22,7 +22,7 @@ T Playfair I i != j .enc[row[i]‘’row[j]] = row[(i + 1) % 5]‘’row[(j + 1) % 5] - L(ci) 5 + L(ci) 0.<5 V c = [m[0][ci], m[1][ci], m[2][ci], m[3][ci], m[4][ci]] L(i, j) cart_product(0.<5, 0.<5) I i != j diff --git a/Task/Playfair-cipher/EasyLang/playfair-cipher.easy b/Task/Playfair-cipher/EasyLang/playfair-cipher.easy new file mode 100644 index 0000000000..5543110183 --- /dev/null +++ b/Task/Playfair-cipher/EasyLang/playfair-cipher.easy @@ -0,0 +1,102 @@ +len pos[] 26 +len tbl$[] 25 +global iforj . +proc inittbl key$ ifj . + iforj = ifj + for c$ in strchars key$ + c = strcode c$ + if c >= 97 : c -= 32 + if c >= 65 and c <= 90 : alph$ &= strchar c + . + for i to 26 + pos[i] = -1 + c$ = strchar (i + 64) + if c$ <> "J" and c$ <> "Q" + alph$ &= c$ + elif c$ = "J" and ifj = 0 + alph$ &= c$ + elif c$ = "Q" and ifj = 1 + alph$ &= c$ + . + . + k = 1 + for ch$ in strchars alph$ + ch = strcode ch$ - 64 + if pos[ch] = -1 + tbl$[k] = ch$ + pos[ch] = k - 1 + k += 1 + . + . +. +func$ codec txt$ dir . + txt$[] = strchars txt$ + for i = 1 step 2 to len txt$ + ch1 = strcode txt$[i] - 64 + ch2 = strcode txt$[i + 1] - 64 + col1 = pos[ch1] mod 5 + row1 = pos[ch1] div 5 + col2 = pos[ch2] mod 5 + row2 = pos[ch2] div 5 + if row1 = row2 + col1 = (col1 + dir) mod 5 + col2 = (col2 + dir) mod 5 + elif col1 = col2 + row1 = (row1 + dir) mod 5 + row2 = (row2 + dir) mod 5 + else + swap col1 col2 + . + r$ &= tbl$[row1 * 5 + col1 + 1] + r$ &= tbl$[row2 * 5 + col2 + 1] + . + return r$ +. +func$ preptxt txt$ . + for c$ in strchars txt$ + c = strcode c$ + if c >= 97 : c -= 32 + if c >= 65 and c <= 90 + c$ = strchar c + if c$ = "J" and iforj = 1 : c$ = "I" + if c$ = "Q" and iforj = 0 : c$ = "" + txt$[] &= c$ + . + . + i = 1 + while i <= len txt$[] + cur$ = txt$[i] + i += 1 + if i <= len txt$[] + nxt$ = txt$[i] + else + nxt$ = "X" + . + r$ &= cur$ + if nxt$ = cur$ + r$ &= "X" + else + r$ &= nxt$ + i += 1 + . + . + return r$ +. +func$ encode txt$ . + return codec preptxt txt$ 1 +. +func$ decode txt$ . + return codec txt$ 4 +. +func$ digraph s$ . + for c$ in strchars s$ + r$ &= c$ + cnt += 1 + if cnt mod 2 = 0 : r$ &= " " + . + return r$ +. +inittbl "Playfair example" 1 +enc$ = encode "Hide the gold in...the TREESTUMP!!" +print digraph enc$ +print digraph decode enc$ diff --git a/Task/Playfair-cipher/Fortran/playfair-cipher.f b/Task/Playfair-cipher/Fortran/playfair-cipher.f new file mode 100644 index 0000000000..a7b5261000 --- /dev/null +++ b/Task/Playfair-cipher/Fortran/playfair-cipher.f @@ -0,0 +1,353 @@ +! +! Playfer Cipher +! tested with Intel ifx (IFX) 2025.2.1 20250806 on Kubuntu 25.10 +! GNU Fortran (Ubuntu 15.2.0-4ubuntu4) 15.2.0 on Kubuntu 25.10 +! VSI Fortran x86-64 V8.6-001 on OpenVMS x86_64 V9.2-3 +! +! U.B., October 2025 +!============================================================================== + +program PlayferCipher + + implicit none + + integer, parameter :: nTests = 2 ! Number of different test messages + integer, parameter :: maxLen=100 ! Maximum length of any test message (including extensions as 'X') + + ! The complete alphabet of capital letters as used in most western languages + character (len=*), parameter :: Alphabet ='ABCDEFGHIJKLMNOPQRSTUVWXYZ' + + character (len=maxLen) :: MsgToEncrypt (nTests), EncryptedMsg, DecryptedMsg + logical :: Omit_Q ! True: omit Q in alphabet, False: use I for both I and J + character (len=25) :: PassPhrase(nTests) + + integer, parameter :: ColWidth =5 ! depends on length of the used alphabet but we use only 25 letters + + integer :: i + + ! The message to encrypt - for 1 test case + ! the additional message as presented in the task description + MsgToEncrypt(1) = 'Hide the gold ... in the tree stump!!!' + PassPhrase(1) = 'playfair example' + + MsgToEncrypt(2) = 'This is another simple test message.' + PassPhrase(2) = 'This is top secret' + + do i=1, nTests + Omit_Q = (i .ne. 1) ! to see both variants: dont use Q or convert J to I + call encode (MsgToEncrypt(i) , EncryptedMsg, Alphabet, Omit_Q, PassPhrase(i)) + call decode (EncryptedMsg, DecryptedMsg, Alphabet, Omit_Q, PassPhrase(i)) + call printResult (MsgToEncrypt(i), EncryptedMsg, DecryptedMsg) + enddo + + +contains + +! ======================================================================= +! 2 Jacket routines for encode and decode - they end up in the same crypt +! routine with an additional argument for the direction +! ======================================================================= +subroutine encode (argInString, outString, argAlphabet, argOmit_Q, argPassPhrase) + character (len=*), intent(in) :: argInString + character (len=*), intent(out) :: outString + character (len=*), intent(in) :: argAlphabet + logical, intent(in) :: argOmit_Q + character (len=*), intent(in) :: argPassPhrase + + call crypt (argInString, outString, argAlphabet, argOmit_Q, argPassPhrase, 1) + +end subroutine encode + +subroutine decode (argInString, outString, argAlphabet, argOmit_Q, argPassPhrase) + character (len=*), intent(in) :: argInString + character (len=*), intent(out) :: outString + character (len=*), intent(in) :: argAlphabet + logical, intent(in) :: argOmit_Q + character (len=*), intent(in) :: argPassPhrase + + call crypt (argInString, outString, argAlphabet, argOmit_Q, argPassPhrase, -1) + +end subroutine decode + + +!========================================================================= +! Encode or decode a given string. Direction is 1 to encode, -1 to decode. +! ======================================================================== +subroutine crypt (argInString, outString, argAlphabet, argOmit_Q, argPassPhrase, direction) + + character (len=*), intent(in) :: argInString + character (len=*), intent(out) :: outString + character (len=*), intent(in) :: argAlphabet + logical, intent(in) :: argOmit_Q + character (len=*), intent(in) :: argPassPhrase + integer , intent(in) :: direction + + character (len=100) :: LocalAlphabet + character (len=MaxLen) :: inString + + integer :: idxLine(2*maxLen) + integer :: l, ii, idx, jdx, row, col + + inString = argInString ! have a mutable copy or intent(in) argument + outString = ' ' + + call changeAllToUpcase (inString) + + call setupAlphabet (argAlphabet, LocalAlphabet, argOmit_Q, argPassPhrase) + if (direction .eq. 1) call PrintSquare (LocalAlphabet) ! when encoding, show the Polybius square + if (.not. argOmit_Q) then + call FixJ_I (inString) ! Replace all J by I. + endif + + l = len_trim (inString) + if (l .gt. len(outString)) stop 'ERROR: not enough storage space for encrypt result string.' + + ! En/Decode every group of two characters + idx = 1 + jdx = 1 + do while (idx .le. l) + if (idx .lt. l) then + if (inString (idx:idx) .ne. inString (idx+1:idx+1)) then + outString(jdx:jdx+1) = decode2Group (inString (idx:idx),inString (idx+1:idx+1), LocalAlphabet, direction) + idx = idx + 2 + jdx = jdx+2 + else + outString(jdx:jdx+1) = decode2Group (inString (idx:idx), 'X', LocalAlphabet, direction) + idx = idx + 1 + jdx = jdx+2 + endif + else if (idx .eq. l) then + outString(jdx:jdx+1) = decode2Group (inString (idx:idx), 'X', LocalAlphabet, direction) + idx = idx + 1 + jdx = jdx+2 + end if + end do + +end subroutine crypt + +! ======================================= +! Modify input string, replace all J by I +! ======================================= +subroutine FixJ_I (inString) + character (len=*), intent(inout) :: inString + integer :: l, ii + l = len_trim (inString) + do ii=1,l + if (inString (ii:ii) .eq. 'J') inString (ii:ii) = 'I' + enddo +end subroutine FixJ_I + +! ================================================================================ +! Encode or Decode a group of 2 letters according to the rules for Playfair Cipher +! ================================================================================ +function decode2Group (ch1, ch2, argAlphabet, direction) result (res) + character, intent(in) :: ch1, ch2 ! 2 characters to decode + character (len=*), intent(in) :: argAlphabet ! Argument to use for encoding + integer, intent(in) :: direction ! 1 for encode, -1 for decode + character (len=2) :: res ! resultant group of 2 chars + + integer :: r1,r2,c1,c2 ! row, col of ch1 and ch2 + integer :: idx + + call getRC (ch1,r1,c1,argAlphabet) + call getRC (ch2,r2,c2,argAlphabet) + + if (r1 .ne. r2 .and. c1 .ne. c2) then ! c1 and c2 form a rectangle + res(1:1) = getChar (r1,c2,argAlphabet) ! Same rows, opposite corner + res(2:2) = getChar (r2,c1,argAlphabet) + else if (r1 .eq. r2 .and. c1 .ne. c2) then ! c1 and c2 in horizontal line + ! pick item to right (left) of each, wrap if required + c1 = c1 + direction ! Easier to read... + if (c1 .gt. ColWidth) c1 = 1 ! than a fancy formula... + if (c1 .lt. 1) c1 = ColWidth ! with modulus and offset + c2 = c2 + direction + if (c2 .gt. ColWidth) c2 = 1 + if (c2 .lt. 1) c2 = ColWidth + res(1:1)=getChar (r1,c1,argAlphabet) + res(2:2)=getChar (r2,c2,argAlphabet) + else if (c1 .eq. c2 .and. r1 .ne. r2) then ! c1 and c2 in vertical line + ! pick item to below (above) each, wrap if required + r1 = r1 + direction + r2 = r2 + direction + if (r1 .gt. ColWidth) r1 = 1 + if (r1 .lt. 1) r1 = ColWidth + if (r2 .gt. ColWidth) r2 = 1 + if (r2 .lt. 1) r2 = ColWidth + res(1:1) = getChar (r1,c1,argAlphabet) + res(2:2) = getChar (r2,c1,argAlphabet) + else + ! should be impossible: c1 .eq. c2 + stop 'duplicate letter in group of 2 letters: BUG CHECK' + endif +end function decode2Group + +! ====================================================== +! Get Row and Column of a letter in the Polybius square +! ====================================================== +subroutine getRC (c,row,col, argAlphabet) + character, intent(in) :: c + integer, intent(out) :: row,col + character (len=*), intent(in) :: argAlphabet ! Argument to use for encoding + integer :: idx + + idx = index (argAlphabet, c) - 1 + + row = 1 + idx / ColWidth + col = 1 + mod (idx, ColWidth) + +end subroutine getRC + +! ================================================== +! Return letter in row column of the Polybius square +! ================================================== +function getChar (row,column,argAlphabet) result (chr) + integer, intent(in) :: row, column + character (len=*), intent(in) :: argAlphabet ! Argument to use for encoding + character :: chr + integer :: idx + + idx = (row-1) * ColWidth + column + chr = argAlphabet (idx:idx) + +end function getChar + + +! =============================================================================== +! Modify string: convert lower case to upper case, skip whitespace or punctuation +! =============================================================================== +subroutine changeAllToUpcase (str) + character (len=*), intent(inout) :: str + integer :: ii, jj, l + + l = len_trim (str) + jj = 1 + ii = 1 + do while (ii .le. l) + if (str(ii:ii) .ge. 'a' .and. str(ii:ii) .le. 'z') then + ! lower case -> upper case + str(ii:ii) = char (ichar(str(ii:ii)) - ichar('a') + ichar('A')) + else if (str(ii:ii) .ge. 'A' .and. str(ii:ii) .le. 'Z') then + ! Upper case: OK, nothing to do + else + ! Anything else: ignore, and do not use + str = str (:ii-1) // str (ii+1:) ! Skip the space + l = l - 1 ! reduce total length + cycle ! without increment index ii. + endif + ii = ii + 1 + end do +end subroutine changeAllToUpcase + + +! =========================================================================== +! Prepare the Alphabet to use: it is the pass phrase, followed by the normal +! upper case alphabet, always avoiding duplicate letters +! =========================================================================== +subroutine setupAlphabet (argAlphabet, ResultAlphabet, argOmit_Q, argPassPhrase) + + character (len=*), intent(in) :: argAlphabet + character (len=*), intent(out) :: ResultAlphabet + logical, intent(in) :: argOmit_Q ! True: ompit Q in alphabet, , False: use I for both I and J + character (len=*), intent(in) :: argPassPhrase + integer :: ii, jj, l + character :: cWork + + ResultAlphabet = ' ' ! Initialize result string + call appendString (ResultAlphabet, argPassPhrase, argOmit_Q) ! First use passprase + call appendString (ResultAlphabet, argAlphabet, argOmit_Q) ! and then use remaining letters from alphabet + +end subroutine setupAlphabet + + +! ================================================================================== +! Append a string to an existing (possibly empty) string, avoiding duplicate letters +! ================================================================================== +subroutine appendString (ResultAlphabet, stringToAppend, argOmit_Q) + +character (len=*), intent(inout) :: ResultAlphabet +logical, intent(in) :: argOmit_Q ! True: omit Q in alphabet, , False: use I for both I and J +character (len=*), intent(in) :: stringToAppend +integer :: ii,jj,l +character :: cWork + +jj = len_trim(ResultAlphabet) + 1 ! here we start appending letters +l = len_trim (stringToAppend) ! count letters to add +do ii = 1, l + if (jj .gt. l) exit ! Do not exceed resultant length + cWork = stringToAppend (ii:ii) + + ! First make sure it's all in UPPER CASE. + if (cWork .ge. 'a' .and. cWork .le. 'z') then ! lower case letter? + cWork = char (ichar(cWork) -ichar('a') + ichar('A')) + endif + + ! Now cWork is either in upper case or it is invalid (i.e. not in alphabet) + if (cWork .ge. 'A' .and. cWork .le. 'Z') then ! Valid? + if (argOmit_Q) then ! Q is not part of the valid applicable alphabet + if (cWork .eq. 'Q') cycle ! skip Q but conserve both I and J + else + ! dont omit Q, so use 'I' for both 'I' and 'J' + if (cWork .eq. 'J') cWork = 'I' + endif + + if (jj .eq. 1) then + ! filling very first letter of result alphabet + ResultAlphabet (jj:jj) = cWork + jj = jj + 1 + else if (index (ResultAlphabet (:jj), cWork) .eq. 0) then + ! current work letter not yet contained in alphabet + ResultAlphabet (jj:jj) = cWork + jj = jj + 1 + else + ! Nothing, just skip letters that are already known in result alphabet. + endif + else + ! Nothing, just skip characters other than [A...Z] + endif +end do + +end subroutine appendString + +! =========================================== +! Print original, encoded and decoded strings +! =========================================== +subroutine printResult (m1,m2,m3) + character (len=*), intent(in) :: m1,m2,m3 + write (*,'("Original: ", A)') m1 ! original string unmodified + call print1 (' Encoded: ', m2) ! result of encode or decode: + call print1 (' Decoded: ', m3) ! print all groups of 2 letters + print * +end subroutine printResult + +! =================================================================== +! separate input string into groups of 2 letters and print all groups +! =================================================================== +subroutine print1 (comment, m) + character (len=*), intent(in) :: comment, m + integer :: ii + write (*, '(A, X)', advance='no') comment + do ii=1, len_trim (m)-1,2 + write (*, '(A2,x)', advance = 'no') m(ii:ii+1) + end do + print * +end subroutine print1 + +! ================================================================================ +! Print the resulting Polybius square based on the alphabet used for encode/decode +! ================================================================================ +subroutine PrintSquare (Alphabet) + character (len=*), intent(in) :: Alphabet + integer:: ii, l + + l = len_trim(alphabet) + write (*,'(/,"Using this Polybius square for encode/decode:",/)') + + do ii=1, ColWidth*ColWidth + write (*, '(A2)', advance='no') Alphabet(ii:ii) + if (mod (ii, ColWidth) .eq. 0) print * ! End of line + end do + print * ! one extra blank line +end subroutine PrintSquare + + +end program PlayferCipher diff --git a/Task/Playfair-cipher/JavaScript/playfair-cipher.js b/Task/Playfair-cipher/JavaScript/playfair-cipher.js new file mode 100644 index 0000000000..5742a124b9 --- /dev/null +++ b/Task/Playfair-cipher/JavaScript/playfair-cipher.js @@ -0,0 +1,269 @@ +const readline = require('readline'); + +// Enum-like object for Playfair options +const playfairOption = { + NO_Q: 0, + I_EQUALS_J: 1, +}; + +// Represents the Playfair cipher state and methods +class Playfair { + constructor(keyword, pfo) { + this.keyword = keyword; + this.pfo = pfo; // playfairOption + this.table = Array(5).fill(null).map(() => Array(5).fill('')); // 5x5 table + } + + // Initializes the 5x5 Playfair table based on the keyword and option + init() { + const used = Array(26).fill(false); // Track used letters + if (this.pfo === playfairOption.NO_Q) { + used['Q'.charCodeAt(0) - 65] = true; // Q is used/omitted + } else { + used['J'.charCodeAt(0) - 65] = true; // J is used/replaced by I + } + + const alphabet = this.keyword.toUpperCase() + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + let row = 0; + let col = 0; + + for (const char of alphabet) { + const charCode = char.charCodeAt(0); + + // Check if it's a letter A-Z + if (charCode >= 'A'.charCodeAt(0) && charCode <= 'Z'.charCodeAt(0)) { + const charIndex = charCode - 65; // 0-25 index + + // Handle J if I_EQUALS_J option is selected + let charToUse = char; + let indexToUse = charIndex; + if (char === 'J' && this.pfo === playfairOption.I_EQUALS_J) { + charToUse = 'I'; + indexToUse = 'I'.charCodeAt(0) - 65; + } + + // Skip Q if NO_Q option is selected + if (charToUse === 'Q' && this.pfo === playfairOption.NO_Q) { + continue; + } + + + if (!used[indexToUse]) { + this.table[row][col] = charToUse; + used[indexToUse] = true; + col++; + if (col === 5) { + row++; + if (row === 5) { + break; // Table filled + } + col = 0; + } + } + } + } + } + + // Prepares the plaintext: uppercase, removes non-letters, + // handles Q/J based on option, inserts X between duplicate letters, + // pads with X/Z if length is odd. + getCleanText(plainText) { + plainText = plainText.toUpperCase(); + const cleanChars = []; + let prevChar = ''; // Use '' to indicate no previous character + + for (let i = 0; i < plainText.length; i++) { + let currentChar = plainText[i]; + const charCode = currentChar.charCodeAt(0); + + // Skip non-letters + if (charCode < 'A'.charCodeAt(0) || charCode > 'Z'.charCodeAt(0)) { + continue; + } + + // Handle J if I_EQUALS_J option is specified, replace J with I + if (currentChar === 'J' && this.pfo === playfairOption.I_EQUALS_J) { + currentChar = 'I'; + } + + // Skip Q if NO_Q option is specified (already handled in init, but good here too) + if (currentChar === 'Q' && this.pfo === playfairOption.NO_Q) { + continue; + } + + + // Insert 'X' between duplicate consecutive letters + // Only compare if prevChar is set (not the very first character) + if (prevChar !== '' && currentChar === prevChar) { + cleanChars.push('X'); + } + + cleanChars.push(currentChar); + prevChar = currentChar; // Store the character *after* potential X insertion + } + + // If length is odd, add a padding character + if (cleanChars.length % 2 === 1) { + // Add 'X' unless the last letter is 'X', then add 'Z' + if (cleanChars[cleanChars.length - 1] !== 'X') { + cleanChars.push('X'); + } else { + cleanChars.push('Z'); + } + } + + return cleanChars.join(''); + } + + // Finds the row and column of a character in the table + findChar(char) { + for (let i = 0; i < 5; i++) { + for (let j = 0; j < 5; j++) { + if (this.table[i][j] === char) { + return [i, j]; // Return [row, col] + } + } + } + return [-1, -1]; // Should not happen if getCleanText is correct + } + + // Encodes plaintext using the Playfair cipher + encode(plainText) { + const cleanText = this.getCleanText(plainText); + const cipherChars = []; + + for (let i = 0; i < cleanText.length; i += 2) { + const char1 = cleanText[i]; + const char2 = cleanText[i + 1]; // cleanText length is always even + const [row1, col1] = this.findChar(char1); + const [row2, col2] = this.findChar(char2); + + let encodedChar1, encodedChar2; + + if (row1 === row2) { // Same row + encodedChar1 = this.table[row1][(col1 + 1) % 5]; + encodedChar2 = this.table[row2][(col2 + 1) % 5]; + } else if (col1 === col2) { // Same column + encodedChar1 = this.table[(row1 + 1) % 5][col1]; + encodedChar2 = this.table[(row2 + 1) % 5][col2]; + } else { // Different row and column (rectangle) + encodedChar1 = this.table[row1][col2]; + encodedChar2 = this.table[row2][col1]; + } + + cipherChars.push(encodedChar1); + cipherChars.push(encodedChar2); + + // Add space after each digram, matching Go's output format + if (i + 2 < cleanText.length) { + cipherChars.push(' '); + } + } + + return cipherChars.join(''); + } + + // Decodes ciphertext using the Playfair cipher + decode(cipherText) { + // The Go code processes the ciphertext including spaces, + // stepping by 3. We'll do the same by stripping spaces first + // and then processing in pairs. This is conceptually simpler in JS. + // Or, we can replicate the Go loop that steps by 3. Let's replicate for exact match. + const decodedChars = []; + const l = cipherText.length; + + for (let i = 0; i < l; i += 3) { // Step by 3 due to spaces in encoded text + const char1 = cipherText[i]; + const char2 = cipherText[i + 1]; + // cipherText[i+2] will be a space, which findChar will correctly not find (-1, -1) + // But the Go code explicitly finds the *bytes* at i and i+1. Let's stick to that. + + // Ensure we only process valid character pairs + if (!char1 || !char2 || char1 === ' ' || char2 === ' ') { + // This shouldn't happen with the i+=3 loop structure if the input + // format from encode is followed, but good to be safe. + continue; + } + + + const [row1, col1] = this.findChar(char1); + const [row2, col2] = this.findChar(char2); + + let decodedChar1, decodedChar2; + + // Decoding rules are the reverse of encoding + if (row1 === row2) { // Same row + // Shift left: (col - 1 + 5) % 5 + decodedChar1 = this.table[row1][(col1 + 4) % 5]; + decodedChar2 = this.table[row2][(col2 + 4) % 5]; + } else if (col1 === col2) { // Same column + // Shift up: (row - 1 + 5) % 5 + decodedChar1 = this.table[(row1 + 4) % 5][col1]; + decodedChar2 = this.table[(row2 + 4) % 5][col2]; + } else { // Different row and column (rectangle) + decodedChar1 = this.table[row1][col2]; + decodedChar2 = this.table[row2][col1]; + } + + decodedChars.push(decodedChar1); + decodedChars.push(decodedChar2); + + // Add space after each digram in decoded text, matching Go's output format + if (i + 3 < l) { // Check if there's more content after the current digram+space + decodedChars.push(' '); + } + } + + return decodedChars.join(''); + } + + // Prints the 5x5 table to the console + printTable() { + console.log("The table to be used is :\n"); + for (let i = 0; i < 5; i++) { + console.log(this.table[i].join(' ')); // Join row elements with space + } + console.log(); // Add a blank line for spacing + } +} + +// Main execution function using async/await for readline +async function main() { + const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout + }); + + const question = (query) => new Promise((resolve) => rl.question(query, resolve)); + + try { + const keyword = await question("Enter Playfair keyword : "); + + let ignoreQ = ''; + while (ignoreQ !== "y" && ignoreQ !== "n") { + ignoreQ = (await question("Ignore Q when building table y/n : ")).toLowerCase(); + } + + const pfo = (ignoreQ === "y") ? playfairOption.NO_Q : playfairOption.I_EQUALS_J; + + const pf = new Playfair(keyword, pfo); + pf.init(); + pf.printTable(); + + const plainText = await question("\nEnter plain text : "); + + const encodedText = pf.encode(plainText); + console.log("\nEncoded text is :", encodedText); + + // The Go code decodes the encoded text *including* the spaces it added. + // Pass the encoded text as is to the decode function. + const decodedText = pf.decode(encodedText); + console.log("Decoded text is :", decodedText); + + } finally { + rl.close(); // Close the readline interface + } +} + +// Execute the main function +main(); diff --git a/Task/Playfair-cipher/Julia/playfair-cipher.julia b/Task/Playfair-cipher/Julia/playfair-cipher.jl similarity index 100% rename from Task/Playfair-cipher/Julia/playfair-cipher.julia rename to Task/Playfair-cipher/Julia/playfair-cipher.jl diff --git a/Task/Playfair-cipher/Kotlin/playfair-cipher.kotlin b/Task/Playfair-cipher/Kotlin/playfair-cipher.kts similarity index 100% rename from Task/Playfair-cipher/Kotlin/playfair-cipher.kotlin rename to Task/Playfair-cipher/Kotlin/playfair-cipher.kts diff --git a/Task/Playfair-cipher/Rust/playfair-cipher.rs b/Task/Playfair-cipher/Rust/playfair-cipher.rs new file mode 100644 index 0000000000..074935a132 --- /dev/null +++ b/Task/Playfair-cipher/Rust/playfair-cipher.rs @@ -0,0 +1,225 @@ +use std::io::{self, Write}; + +struct Playfair { + txt: String, + m: [[char; 5]; 5], +} + +impl Playfair { + fn new() -> Self { + Playfair { + txt: String::new(), + m: [[' '; 5]; 5], + } + } + + fn do_it(&mut self, k: &str, t: &str, ij: bool, e: bool) { + self.create_grid(k, ij); + self.get_text_ready(t, ij, e); + + if e { + self.process(1); + } else { + self.process(-1); + } + + self.display(); + } + + fn process(&mut self, dir: i32) { + let mut ntxt = String::new(); + let mut chars = self.txt.chars().collect::>(); + let mut i = 0; + + while i < chars.len() { + if i + 1 >= chars.len() { + break; + } + + let mut a = 0; + let mut b = 0; + let mut c = 0; + let mut d = 0; + + if self.get_char_pos(chars[i], &mut a, &mut b) && + self.get_char_pos(chars[i+1], &mut c, &mut d) { + if a == c { + ntxt.push(self.get_char(a, b + dir)); + ntxt.push(self.get_char(c, d + dir)); + } else if b == d { + ntxt.push(self.get_char(a + dir, b)); + ntxt.push(self.get_char(c + dir, d)); + } else { + ntxt.push(self.get_char(c, b)); + ntxt.push(self.get_char(a, d)); + } + } + + i += 2; + } + + self.txt = ntxt; + } + + fn display(&self) { + println!("\n\n OUTPUT:\n========="); + let chars = self.txt.chars().collect::>(); + let mut cnt = 0; + let mut i = 0; + + while i < chars.len() { + if i + 1 < chars.len() { + print!("{}{} ", chars[i], chars[i+1]); + i += 2; + cnt += 1; + + if cnt >= 26 { + println!(); + cnt = 0; + } + } else { + print!("{}", chars[i]); + i += 1; + } + } + + println!("\n"); + } + + fn get_char(&self, a: i32, b: i32) -> char { + let row = ((b + 5) % 5) as usize; + let col = ((a + 5) % 5) as usize; + self.m[row][col] + } + + fn get_char_pos(&self, l: char, a: &mut i32, b: &mut i32) -> bool { + for y in 0..5 { + for x in 0..5 { + if self.m[y][x] == l { + *a = x as i32; + *b = y as i32; + return true; + } + } + } + false + } + + fn get_text_ready(&mut self, t: &str, ij: bool, e: bool) { + self.txt.clear(); + + for c in t.chars() { + let c_upper = c.to_ascii_uppercase(); + + if c_upper < 'A' || c_upper > 'Z' { + continue; + } + + if c_upper == 'J' && ij { + self.txt.push('I'); + } else if c_upper == 'Q' && !ij { + continue; + } else { + self.txt.push(c_upper); + } + } + + if e { + let mut ntxt = String::new(); + let chars = self.txt.chars().collect::>(); + let len = chars.len(); + + let mut x = 0; + while x < len { + ntxt.push(chars[x]); + + if x + 1 < len { + if chars[x] == chars[x + 1] { + ntxt.push('X'); + } + ntxt.push(chars[x + 1]); + } + + x += 2; + } + + self.txt = ntxt; + } + + if self.txt.len() % 2 == 1 { + self.txt.push('X'); + } + } + + fn create_grid(&mut self, k: &str, ij: bool) { + let mut key = k.to_string(); + if key.is_empty() { + key = "KEYWORD".to_string(); + } + + key.push_str("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); + let mut nk = String::new(); + + for c in key.chars() { + let c_upper = c.to_ascii_uppercase(); + + if c_upper < 'A' || c_upper > 'Z' { + continue; + } + + if (c_upper == 'J' && ij) || (c_upper == 'Q' && !ij) { + continue; + } + + if !nk.contains(c_upper) { + nk.push(c_upper); + } + } + + let mut idx = 0; + for y in 0..5 { + for x in 0..5 { + if idx < nk.len() { + self.m[y][x] = nk.chars().nth(idx).unwrap(); + idx += 1; + } + } + } + } +} + +fn main() -> io::Result<()> { + let mut input = String::new(); + + print!("(E)ncode or (D)ecode? "); + io::stdout().flush()?; + io::stdin().read_line(&mut input)?; + let e = input.trim().to_lowercase().starts_with('e'); + + input.clear(); + print!("Enter a en/decryption key: "); + io::stdout().flush()?; + io::stdin().read_line(&mut input)?; + let key = input.trim().to_string(); + + input.clear(); + print!("I <-> J (Y/N): "); + io::stdout().flush()?; + io::stdin().read_line(&mut input)?; + let ij = input.trim().to_lowercase().starts_with('y'); + + input.clear(); + print!("Enter the text: "); + io::stdout().flush()?; + io::stdin().read_line(&mut input)?; + let txt = input.trim().to_string(); + + let mut pf = Playfair::new(); + pf.do_it(&key, &txt, ij, e); + + println!("Press Enter to continue..."); + input.clear(); + io::stdin().read_line(&mut input)?; + + Ok(()) +} diff --git a/Task/Playing-cards/Arturo/playing-cards.arturo b/Task/Playing-cards/Arturo/playing-cards.arturo index 94e87d4910..745c08cdf5 100644 --- a/Task/Playing-cards/Arturo/playing-cards.arturo +++ b/Task/Playing-cards/Arturo/playing-cards.arturo @@ -1,56 +1,71 @@ ranks: 1..13 -suits: [`♣`, `♦`, `♥`, `♠`] +suits: ['♣', '♦', '♥', '♠'] -define :card [rank, suit][ - init: [ - ensure -> - and? -> contains? ranks this\rank - -> contains? suits this\suit +rank?: $ => [in? & ranks] +suit?: $ => [in? & suits] + +interleave: $[ + xs :block :dictionary :range + ys :block :dictionary :range + apply :literal +][ + flatten map xs 'x + -> map ys 'y + -> call apply @[x y] +] + +define :Card [ + init: method [rank :integer suit :char][ + ensure -> rank? rank + ensure -> suit? suit + + this\rank: rank + this\suit: suit ] - print: [ - R: ø - case [this\rank=] - when? [1] -> R: `A` - when? [11]-> R: `J` - when? [12]-> R: `Q` - when? [13]-> R: `K` - else -> R: this\rank + string: method [][ + R: case this\rank [ + 1 -> 'A' + 11 -> 'J' + 12 -> 'Q' + 13 -> 'K' + any -> this\rank + ] ~{|R||this\suit|} ] ] -define :deck [][ - init: [ - this\cards: [] - loop ranks 'rank -> - loop suits 'suit -> - this\cards: this\cards ++ to :card @[rank, suit] - ] +card: $[rank :integer suit :char][ + to :Card [rank suit]! ] -shuffleUp: function [this :deck][ - this\cards: shuffle this\cards -] - -deal: function [this :deck, cnt :integer][ - if cnt > size this\cards -> - panic "Not enough cards in deck" - - cards: [] - do.times: cnt [ - dealt: sample this\cards - 'cards ++ dealt - this\cards: remove this\cards dealt +define :Deck [ + init: method [][ + this\cards: interleave ranks suits 'card + ] + + shuffle: method [][ + shuffle 'this\cards + ] + + deal: method [][ + ensure.that: "Not enough cards in deck" + -> not? empty? \cards + + \shuffle + pop 'this\cards + ] + + dealMany: method [times :integer][ + map 1..times 'x -> \deal ] - return cards ] ; create a new deck -Deck: to :deck [] +deck: to :Deck []! ; and shuffle it -shuffleUp Deck +deck\shuffle ; deal 5 cards -print deal Deck 5 +print deck\dealMany 5 diff --git a/Task/Playing-cards/AutoIt/playing-cards.autoit b/Task/Playing-cards/AutoIt/playing-cards.au3 similarity index 100% rename from Task/Playing-cards/AutoIt/playing-cards.autoit rename to Task/Playing-cards/AutoIt/playing-cards.au3 diff --git a/Task/Playing-cards/COBOL/playing-cards.cobol b/Task/Playing-cards/COBOL/playing-cards.cob similarity index 100% rename from Task/Playing-cards/COBOL/playing-cards.cobol rename to Task/Playing-cards/COBOL/playing-cards.cob diff --git a/Task/Playing-cards/D/playing-cards-2.d b/Task/Playing-cards/D/playing-cards-2.d index 06080d4c27..2e1431fd18 100644 --- a/Task/Playing-cards/D/playing-cards-2.d +++ b/Task/Playing-cards/D/playing-cards-2.d @@ -17,7 +17,7 @@ struct Card { immutable pipOrder = (!rankAceTop) ? pip : (pip ? pip - 1 : 12); - return pipOrder * suits.length + suit; + return pipOrder * cast(int)suits.length + suit; } bool opEqual(in Card rhs) const pure nothrow { @@ -61,7 +61,7 @@ final class Deck { } Deck dealTop(Deck toDeck = null) pure nothrow { - return deal(length - 1, toDeck); + return deal(cast(int)length - 1, toDeck); } Card opIndex(in int loc) const pure nothrow { diff --git a/Task/Playing-cards/Delphi/playing-cards.delphi b/Task/Playing-cards/Delphi/playing-cards.pas similarity index 100% rename from Task/Playing-cards/Delphi/playing-cards.delphi rename to Task/Playing-cards/Delphi/playing-cards.pas diff --git a/Task/Playing-cards/EasyLang/playing-cards.easy b/Task/Playing-cards/EasyLang/playing-cards.easy index bd36277739..35f2cf3682 100644 --- a/Task/Playing-cards/EasyLang/playing-cards.easy +++ b/Task/Playing-cards/EasyLang/playing-cards.easy @@ -1,9 +1,7 @@ global deck[] top . -proc new . . +proc new . deck[] = [ ] - for i to 52 - deck[] &= i - . + for i to 52 : deck[] &= i top = 52 . suit$[] = [ "♠" "♦" "♥" "♣" ] @@ -11,16 +9,14 @@ val$[] = [ 2 3 4 5 6 7 8 9 10 "J" "Q" "K" "A" ] func$ name card . return suit$[card mod1 4] & val$[card div1 4] . -proc show . . - for i to top - write name deck[i] & " " - . +proc show . + for i to top : write name deck[i] & " " print "" print "" . -proc shuffle . . +proc shuffle . for i = 52 downto 2 - r = randint i + r = random 1 i swap deck[i] deck[r] . top = 52 diff --git a/Task/Playing-cards/Elixir/playing-cards.elixir b/Task/Playing-cards/Elixir/playing-cards.ex similarity index 100% rename from Task/Playing-cards/Elixir/playing-cards.elixir rename to Task/Playing-cards/Elixir/playing-cards.ex diff --git a/Task/Playing-cards/FutureBasic/playing-cards.basic b/Task/Playing-cards/FutureBasic/playing-cards.basic new file mode 100644 index 0000000000..354aac7096 --- /dev/null +++ b/Task/Playing-cards/FutureBasic/playing-cards.basic @@ -0,0 +1,58 @@ +include "Tlbx GameplayKit.incl" + +void local fn PrintCards( cards as CFArrayRef ) + int c = 0 + for CFStringRef card in cards + print card;@" "; + c ++ + if ( c % 13 == 0 ) then c = 0 : print + next +end fn + +void local fn PlayingCards + window 1, @"Playing cards", (0,0,600,400) + + CFStringRef suit = @"CDHS", pip = @"A23456789TJQK" + CFMutableArrayRef cards = fn MutableArrayNew, p1 = fn MutableArrayNew, p2 = fn MutableArrayNew + int c = 0, d + + print @"Deck:" + for int s = 0 to len(suit) - 1 + for int p = 0 to len(pip) - 1 + cards[c] = concat(pip[p],suit[s]) + c++ + next + next + fn PrintCards( cards ) + + print @"\nShuffled deck:" + cards = fn MutableArrayWithArray(fn ArrayShuffledArray(cards)) + fn PrintCards( cards ) + + print @"\nDeal: " + print @" Player 1: "; + for d = 0 to 4 + p1[d] = cards[0] + MutableArrayRemoveObjectAtIndex( cards, 0 ) + print p1[d];@" "; + p2[d] = cards[0] + MutableArrayRemoveObjectAtIndex( cards, 0 ) + next + + print : print @" Player 2: "; + for d = 0 to 4 + print p2[d];@" "; + next + + print : print @"\nCurrent deck:" + c = 0 + for CFStringRef card in cards + print card;@" "; + c ++ + if ( c % 13 == 0 ) then c = 0 : print + next +end fn + +fn PlayingCards + +HandleEvents diff --git a/Task/Playing-cards/GDScript/playing-cards.gd b/Task/Playing-cards/GDScript/playing-cards.gd new file mode 100644 index 0000000000..36d9476193 --- /dev/null +++ b/Task/Playing-cards/GDScript/playing-cards.gd @@ -0,0 +1,72 @@ +class_name Base_Card + +extends Node + +const Suit = { Diamonds = "♦", Spades = "♠", Hearts = "♥", Clubs = "♣"} + +const Rank = { Two = "2", Three = "3", Four = "4", Five = "5", Six = "6", Seven = "7", Eight = "8", Nine = "9", Ten = "10", Jack = "J", Queen = "Q", King = "K", Ace = "A" } + +# Test +var display = Rank.Two + Suit.Spades + +# Ready Function +func _ready(): + #PlayingCard.new(Rank.Ace, Suit.Diamond) + #print ( "display card " + display ) + Deck.new() + +class PlayingCard: + var r + var s + + func _init(rank, suit): + r = rank + s = suit + #_to_string() + + func _to_string(): + print("Your card is the " + r + " of " + s) + +class Deck: + var cards = [] + var suits = Suit.duplicate() + var ranks = Rank.duplicate() + # TODO: Dynamically change the number of hands + var hand0 = [] + var hand1 = [] + var hand2 = [] + var hand3 = [] + var hands = [hand0, hand1, hand2, hand3] + func _init(): + for rank in ranks: + for suit in suits: + cards.append(PlayingCard.new(rank, suit)) + + # TODO: Add Jokers + shuffle() + deal() + print("************** Hand 0 ***************") + displayHand(hands[0]) + print("************** Hand 1 ***************") + displayHand(hands[1]) + print("************** Hand 2 ***************") + displayHand(hands[2]) + print("************** Hand 3 ***************") + displayHand(hands[3]) + + + func displayDeck(): + for card in cards: + card._to_string() + + func shuffle(): + cards.shuffle() + + func deal(): + while cards: + for hand in hands: + hand.append(cards.pop_back()) + + func displayHand(hand): + for card in hand: + card._to_string() diff --git a/Task/Playing-cards/Julia/playing-cards-1.jl b/Task/Playing-cards/Julia/playing-cards-1.jl new file mode 100644 index 0000000000..10ef0a341d --- /dev/null +++ b/Task/Playing-cards/Julia/playing-cards-1.jl @@ -0,0 +1,26 @@ +using Random + +struct DeckDesign{T<:Integer,U<:String} + rlen::T + slen::T + ranks::Vector{U} + suits::Vector{U} + hlen::T +end + +mutable struct Deck{T<:Integer} + cards::Vector{T} + design::DeckDesign +end + +Deck(n::Integer, des::DeckDesign) = Deck([n], des) + +function pokerlayout() + r = append!(map(string, 2:10), ["J", "Q", "K", "A"]) + s = ["\u2663", "\u2666", "\u2665", "\u2660"] + DeckDesign(13, 4, r, s, 5) +end + +function fresh(des::DeckDesign) + Deck(collect(1:des.rlen*des.slen), des) +end diff --git a/Task/Playing-cards/Julia/playing-cards-1.julia b/Task/Playing-cards/Julia/playing-cards-1.julia deleted file mode 100644 index be9a8d1c98..0000000000 --- a/Task/Playing-cards/Julia/playing-cards-1.julia +++ /dev/null @@ -1,25 +0,0 @@ -type DeckDesign{T<:Integer,U<:String} - rlen::T - slen::T - ranks::Array{U,1} - suits::Array{U,1} - hlen::T -end - -type Deck{T<:Integer} - cards::Array{T,1} - design::DeckDesign -end - -Deck(n::Integer, des::DeckDesign) = Deck([n], des) - -function pokerlayout() - r = [map(string, 2:10), "J", "Q", "K", "A"] - r = map(utf8, r) - s = ["\u2663", "\u2666", "\u2665", "\u2660"] - DeckDesign(13, 4, r, s, 5) -end - -function fresh(des::DeckDesign) - Deck(collect(1:des.rlen*des.slen), des) -end diff --git a/Task/Playing-cards/Julia/playing-cards-2.jl b/Task/Playing-cards/Julia/playing-cards-2.jl new file mode 100644 index 0000000000..c595e3e924 --- /dev/null +++ b/Task/Playing-cards/Julia/playing-cards-2.jl @@ -0,0 +1,16 @@ +Base.isempty(d::Deck) = isempty(d.cards) +Base.empty!(d::Deck) = empty!(d.cards) +Base.length(d::Deck) = length(d.cards) +shuffle!(d::Deck) = Random.shuffle!(d.cards) +Base.sort!(d::Deck) = sort!(d.cards) +Base.getindex(d::Deck, r) = Deck(getindex(d.cards, r), d.design) +Base.size(d::Deck) = (d.design.rlen, d.design.slen) +function Base.show(io::IO, d::Deck) + r = d.design.ranks + s = d.design.suits + for c in d.cards + rix = mod1(c, d.design.rlen) + six = div(c-1, d.design.rlen) + 1 + print(io, r[rix], s[six], " ") + end +end diff --git a/Task/Playing-cards/Julia/playing-cards-2.julia b/Task/Playing-cards/Julia/playing-cards-2.julia deleted file mode 100644 index 43de428946..0000000000 --- a/Task/Playing-cards/Julia/playing-cards-2.julia +++ /dev/null @@ -1,14 +0,0 @@ -Base.isempty(d::Deck) = isempty(d.cards) -Base.empty!(d::Deck) = empty!(d.cards) -Base.length(d::Deck) = length(d.cards) -Base.endof(d::Deck) = endof(d.cards) -Base.shuffle!(d::Deck) = shuffle!(d.cards) -Base.sort!(d::Deck) = sort!(d.cards) -Base.getindex(d::Deck, r) = Deck(getindex(d.cards, r), d.design) -Base.size(d::Deck) = (d.design.rlen, d.design.slen) -function Base.print(d::Deck) - sz = size(d) - r = map(x->d.design.ranks[ind2sub(sz, x)[1]], d.cards) - s = map(x->d.design.suits[ind2sub(sz, x)[2]], d.cards) - join(r.*s, " ") -end diff --git a/Task/Playing-cards/Julia/playing-cards-3.jl b/Task/Playing-cards/Julia/playing-cards-3.jl new file mode 100644 index 0000000000..afcfa9cd3a --- /dev/null +++ b/Task/Playing-cards/Julia/playing-cards-3.jl @@ -0,0 +1,25 @@ +function deal!(d::Deck, hlen::T) where T<:Integer + if hlen < length(d) + hand = Deck(d.cards[1:hlen], d.design) + d.cards = d.cards[hlen+1:end] + else + hand = d + empty!(d) + end + return hand +end + +function deal!(d::Deck) + deal!(d, d.design.hlen) +end + +function pretty(d::Deck) + s = "" + llen = d.design.rlen + dlen = length(d) + for i in 1:llen:dlen + j = min(i+llen-1, dlen) + s *= string(d[i:j]) * "\n" + end + strip(s) +end diff --git a/Task/Playing-cards/Julia/playing-cards-3.julia b/Task/Playing-cards/Julia/playing-cards-3.julia deleted file mode 100644 index 8002c6cd7e..0000000000 --- a/Task/Playing-cards/Julia/playing-cards-3.julia +++ /dev/null @@ -1,25 +0,0 @@ -function deal!{T<:Integer}(d::Deck, hlen::T) - if hlen < length(d) - hand = Deck(d.cards[1:hlen], d.design) - d.cards = d.cards[hlen+1:end] - else - hand = d - empty!(d) - end - return hand -end - -function deal!(d::Deck) - deal!(d, d.design.hlen) -end - -function pretty(d::Deck) - s = "" - llen = d.design.rlen - dlen = length(d) - for i in 1:llen:dlen - j = min(i+llen-1, dlen) - s *= print(d[i:j])*"\n" - end - chop(s) -end diff --git a/Task/Playing-cards/Julia/playing-cards-4.julia b/Task/Playing-cards/Julia/playing-cards-4.jl similarity index 100% rename from Task/Playing-cards/Julia/playing-cards-4.julia rename to Task/Playing-cards/Julia/playing-cards-4.jl diff --git a/Task/Playing-cards/Kotlin/playing-cards-1.kotlin b/Task/Playing-cards/Kotlin/playing-cards-1.kts similarity index 100% rename from Task/Playing-cards/Kotlin/playing-cards-1.kotlin rename to Task/Playing-cards/Kotlin/playing-cards-1.kts diff --git a/Task/Playing-cards/Kotlin/playing-cards-2.kotlin b/Task/Playing-cards/Kotlin/playing-cards-2.kts similarity index 100% rename from Task/Playing-cards/Kotlin/playing-cards-2.kotlin rename to Task/Playing-cards/Kotlin/playing-cards-2.kts diff --git a/Task/Playing-cards/OCaml/playing-cards.ocaml b/Task/Playing-cards/OCaml/playing-cards.ml similarity index 100% rename from Task/Playing-cards/OCaml/playing-cards.ocaml rename to Task/Playing-cards/OCaml/playing-cards.ml diff --git a/Task/Playing-cards/PowerShell/playing-cards.psh b/Task/Playing-cards/PowerShell/playing-cards.ps1 similarity index 100% rename from Task/Playing-cards/PowerShell/playing-cards.psh rename to Task/Playing-cards/PowerShell/playing-cards.ps1 diff --git a/Task/Playing-cards/Rebol/playing-cards.rebol b/Task/Playing-cards/Rebol/playing-cards.rebol new file mode 100644 index 0000000000..06ba2f3117 --- /dev/null +++ b/Task/Playing-cards/Rebol/playing-cards.rebol @@ -0,0 +1,45 @@ +Rebol [ + title: "Rosetta code: Playing cards" + file: %Playing_cards.r3 + url: https://rosettacode.org/wiki/Playing_cards + note: "Based on Red language solution" + needs: 3.0.0 +] +random/seed 1 ;; Seed the random number generator for reproducibility + +make-deck: function/with [] [ + new-deck: make block! 52 ;; Create an empty block for 52 cards + foreach s suit [ ;; For each suit... + foreach r rank [ ;; ...and for each rank... + append new-deck join r s ;; ...make a card by joining rank and suit (e.g., "Q♠") and add to deck + ] + ] +][ + rank: "A23456789TJQK" ;; All ranks in a suit (Ace, 2 .. 9, Ten, Jack, Queen, King) + suit: "♣♦♥♠" ;; All four suits: clubs, diamonds, hearts, spades +] + +deal: func [ + other-deck [block!] ;; Deck to deal card(s) into + deck [block!] ;; Deck to deal card(s) from +][ + unless empty? deck [ + append other-deck take deck ;; If cards remain, take the top card and append to other deck + ] +] + +contents: func [deck [block!]] [ + repeat i length? deck [ + prin [deck/:i SP] ;; Print each card with + if zero? i % 12 [prin LF] ;; Newline after every 12 cards for readability + ] +] + +deck: random make-deck ;; Create and shuffle a new deck + +print "40 cards from a deck:" +loop 5 [ ;; 5 lines total + prin LF ;; Blank line to separate each row + loop 8 [prin [take deck SP]] ;; Deal 8 cards per line, remove from deck and print +] +prin "^/^/remaining: " contents deck ;; Print all remaining cards in deck, 12 per line diff --git a/Task/Playing-cards/Rust/playing-cards.rust b/Task/Playing-cards/Rust/playing-cards.rs similarity index 100% rename from Task/Playing-cards/Rust/playing-cards.rust rename to Task/Playing-cards/Rust/playing-cards.rs diff --git a/Task/Playing-cards/Scheme/playing-cards-1.ss b/Task/Playing-cards/Scheme/playing-cards-1.scm similarity index 100% rename from Task/Playing-cards/Scheme/playing-cards-1.ss rename to Task/Playing-cards/Scheme/playing-cards-1.scm diff --git a/Task/Playing-cards/Scheme/playing-cards-2.ss b/Task/Playing-cards/Scheme/playing-cards-2.scm similarity index 100% rename from Task/Playing-cards/Scheme/playing-cards-2.ss rename to Task/Playing-cards/Scheme/playing-cards-2.scm diff --git a/Task/Playing-cards/VBScript/playing-cards-1.vb b/Task/Playing-cards/VBScript/playing-cards-1.vbs similarity index 100% rename from Task/Playing-cards/VBScript/playing-cards-1.vb rename to Task/Playing-cards/VBScript/playing-cards-1.vbs diff --git a/Task/Playing-cards/VBScript/playing-cards-2.vb b/Task/Playing-cards/VBScript/playing-cards-2.vbs similarity index 100% rename from Task/Playing-cards/VBScript/playing-cards-2.vb rename to Task/Playing-cards/VBScript/playing-cards-2.vbs diff --git a/Task/Plot-coordinate-pairs/Ada/plot-coordinate-pairs.ada b/Task/Plot-coordinate-pairs/Ada/plot-coordinate-pairs.adb similarity index 100% rename from Task/Plot-coordinate-pairs/Ada/plot-coordinate-pairs.ada rename to Task/Plot-coordinate-pairs/Ada/plot-coordinate-pairs.adb diff --git a/Task/Plot-coordinate-pairs/Delphi/plot-coordinate-pairs.delphi b/Task/Plot-coordinate-pairs/Delphi/plot-coordinate-pairs.pas similarity index 100% rename from Task/Plot-coordinate-pairs/Delphi/plot-coordinate-pairs.delphi rename to Task/Plot-coordinate-pairs/Delphi/plot-coordinate-pairs.pas diff --git a/Task/Plot-coordinate-pairs/EasyLang/plot-coordinate-pairs.easy b/Task/Plot-coordinate-pairs/EasyLang/plot-coordinate-pairs.easy index 310c247c68..4350ead271 100644 --- a/Task/Plot-coordinate-pairs/EasyLang/plot-coordinate-pairs.easy +++ b/Task/Plot-coordinate-pairs/EasyLang/plot-coordinate-pairs.easy @@ -1,38 +1,26 @@ x[] = [ 0 1 2 3 4 5 6 7 8 9 ] y[] = [ 2.7 2.8 31.4 38.1 58.0 76.2 100.5 130.0 149.3 180.0 ] # -clear -linewidth 0.5 -move 10 97 -line 10 5 -line 95 5 -textsize 3 +glinewidth 0.5 +gline 10 5 10 97 +gline 10 5 95 5 +gtextsize 3 n = len x[] -m = 0 -for i = 1 to n - if y[i] > m - m = y[i] - . -. -linewidth 0.1 -sty = m div 9 -for i range0 10 - move 2 4 + i * 10 - text i * sty - move 10 5 + i * 10 - line 95 5 + i * 10 -. +for i to n : max = higher y[i] max +glinewidth 0.1 +sty = max div 9 stx = x[n] div 9 for i range0 10 - move i * 9 + 10 1 - text i * stx - move i * 9 + 10 5 - line i * 9 + 10 97 + gline 10 5 + i * 10 95 5 + i * 10 + gtext 2 4 + i * 10 i * sty + gline i * 9 + 10 5 i * 9 + 10 97 + gtext i * 9 + 10 1 i * stx . -color 900 -linewidth 0.5 +gcolor 900 +glinewidth 0.5 +gpenup for i = 1 to n x = x[i] * 9 / stx + 10 y = y[i] / sty * 10 + 5 - line x y + glineto x y . diff --git a/Task/Plot-coordinate-pairs/Julia/plot-coordinate-pairs.julia b/Task/Plot-coordinate-pairs/Julia/plot-coordinate-pairs.jl similarity index 100% rename from Task/Plot-coordinate-pairs/Julia/plot-coordinate-pairs.julia rename to Task/Plot-coordinate-pairs/Julia/plot-coordinate-pairs.jl diff --git a/Task/Plot-coordinate-pairs/Kotlin/plot-coordinate-pairs.kotlin b/Task/Plot-coordinate-pairs/Kotlin/plot-coordinate-pairs.kts similarity index 100% rename from Task/Plot-coordinate-pairs/Kotlin/plot-coordinate-pairs.kotlin rename to Task/Plot-coordinate-pairs/Kotlin/plot-coordinate-pairs.kts diff --git a/Task/Plot-coordinate-pairs/OCaml/plot-coordinate-pairs-1.ocaml b/Task/Plot-coordinate-pairs/OCaml/plot-coordinate-pairs-1.ml similarity index 100% rename from Task/Plot-coordinate-pairs/OCaml/plot-coordinate-pairs-1.ocaml rename to Task/Plot-coordinate-pairs/OCaml/plot-coordinate-pairs-1.ml diff --git a/Task/Plot-coordinate-pairs/OCaml/plot-coordinate-pairs-2.ocaml b/Task/Plot-coordinate-pairs/OCaml/plot-coordinate-pairs-2.ml similarity index 100% rename from Task/Plot-coordinate-pairs/OCaml/plot-coordinate-pairs-2.ocaml rename to Task/Plot-coordinate-pairs/OCaml/plot-coordinate-pairs-2.ml diff --git a/Task/Plot-coordinate-pairs/PascalABC.NET/plot-coordinate-pairs.pas b/Task/Plot-coordinate-pairs/PascalABC.NET/plot-coordinate-pairs.pas new file mode 100644 index 0000000000..e57f49a32d --- /dev/null +++ b/Task/Plot-coordinate-pairs/PascalABC.NET/plot-coordinate-pairs.pas @@ -0,0 +1,8 @@ +uses PlotWPF; + +begin + var x := |0.0, 1, 2, 3, 4, 5, 6, 7, 8, 9|; + var y := |2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0|; + var plot := new MarkerGraphWPF(x, y); + plot.addlinegraph(x, y); +end. diff --git a/Task/Pointers-and-references/Ada/pointers-and-references-1.ada b/Task/Pointers-and-references/Ada/pointers-and-references-1.adb similarity index 100% rename from Task/Pointers-and-references/Ada/pointers-and-references-1.ada rename to Task/Pointers-and-references/Ada/pointers-and-references-1.adb diff --git a/Task/Pointers-and-references/Ada/pointers-and-references-2.ada b/Task/Pointers-and-references/Ada/pointers-and-references-2.adb similarity index 100% rename from Task/Pointers-and-references/Ada/pointers-and-references-2.ada rename to Task/Pointers-and-references/Ada/pointers-and-references-2.adb diff --git a/Task/Pointers-and-references/Ada/pointers-and-references-3.ada b/Task/Pointers-and-references/Ada/pointers-and-references-3.adb similarity index 100% rename from Task/Pointers-and-references/Ada/pointers-and-references-3.ada rename to Task/Pointers-and-references/Ada/pointers-and-references-3.adb diff --git a/Task/Pointers-and-references/Ada/pointers-and-references-4.ada b/Task/Pointers-and-references/Ada/pointers-and-references-4.adb similarity index 100% rename from Task/Pointers-and-references/Ada/pointers-and-references-4.ada rename to Task/Pointers-and-references/Ada/pointers-and-references-4.adb diff --git a/Task/Pointers-and-references/Ada/pointers-and-references-5.ada b/Task/Pointers-and-references/Ada/pointers-and-references-5.adb similarity index 100% rename from Task/Pointers-and-references/Ada/pointers-and-references-5.ada rename to Task/Pointers-and-references/Ada/pointers-and-references-5.adb diff --git a/Task/Pointers-and-references/Ada/pointers-and-references-6.ada b/Task/Pointers-and-references/Ada/pointers-and-references-6.adb similarity index 100% rename from Task/Pointers-and-references/Ada/pointers-and-references-6.ada rename to Task/Pointers-and-references/Ada/pointers-and-references-6.adb diff --git a/Task/Pointers-and-references/Ada/pointers-and-references-7.ada b/Task/Pointers-and-references/Ada/pointers-and-references-7.adb similarity index 100% rename from Task/Pointers-and-references/Ada/pointers-and-references-7.ada rename to Task/Pointers-and-references/Ada/pointers-and-references-7.adb diff --git a/Task/Pointers-and-references/Ada/pointers-and-references-8.ada b/Task/Pointers-and-references/Ada/pointers-and-references-8.adb similarity index 100% rename from Task/Pointers-and-references/Ada/pointers-and-references-8.ada rename to Task/Pointers-and-references/Ada/pointers-and-references-8.adb diff --git a/Task/Pointers-and-references/COBOL/pointers-and-references-1.cobol b/Task/Pointers-and-references/COBOL/pointers-and-references-1.cob similarity index 100% rename from Task/Pointers-and-references/COBOL/pointers-and-references-1.cobol rename to Task/Pointers-and-references/COBOL/pointers-and-references-1.cob diff --git a/Task/Pointers-and-references/COBOL/pointers-and-references-2.cobol b/Task/Pointers-and-references/COBOL/pointers-and-references-2.cob similarity index 100% rename from Task/Pointers-and-references/COBOL/pointers-and-references-2.cobol rename to Task/Pointers-and-references/COBOL/pointers-and-references-2.cob diff --git a/Task/Pointers-and-references/COBOL/pointers-and-references-3.cobol b/Task/Pointers-and-references/COBOL/pointers-and-references-3.cob similarity index 100% rename from Task/Pointers-and-references/COBOL/pointers-and-references-3.cobol rename to Task/Pointers-and-references/COBOL/pointers-and-references-3.cob diff --git a/Task/Pointers-and-references/COBOL/pointers-and-references-4.cobol b/Task/Pointers-and-references/COBOL/pointers-and-references-4.cob similarity index 100% rename from Task/Pointers-and-references/COBOL/pointers-and-references-4.cobol rename to Task/Pointers-and-references/COBOL/pointers-and-references-4.cob diff --git a/Task/Pointers-and-references/COBOL/pointers-and-references-5.cobol b/Task/Pointers-and-references/COBOL/pointers-and-references-5.cob similarity index 100% rename from Task/Pointers-and-references/COBOL/pointers-and-references-5.cobol rename to Task/Pointers-and-references/COBOL/pointers-and-references-5.cob diff --git a/Task/Pointers-and-references/COBOL/pointers-and-references-6.cobol b/Task/Pointers-and-references/COBOL/pointers-and-references-6.cob similarity index 100% rename from Task/Pointers-and-references/COBOL/pointers-and-references-6.cobol rename to Task/Pointers-and-references/COBOL/pointers-and-references-6.cob diff --git a/Task/Pointers-and-references/COBOL/pointers-and-references-7.cobol b/Task/Pointers-and-references/COBOL/pointers-and-references-7.cob similarity index 100% rename from Task/Pointers-and-references/COBOL/pointers-and-references-7.cobol rename to Task/Pointers-and-references/COBOL/pointers-and-references-7.cob diff --git a/Task/Pointers-and-references/COBOL/pointers-and-references-8.cobol b/Task/Pointers-and-references/COBOL/pointers-and-references-8.cob similarity index 100% rename from Task/Pointers-and-references/COBOL/pointers-and-references-8.cobol rename to Task/Pointers-and-references/COBOL/pointers-and-references-8.cob diff --git a/Task/Pointers-and-references/Delphi/pointers-and-references-1.delphi b/Task/Pointers-and-references/Delphi/pointers-and-references-1.pas similarity index 100% rename from Task/Pointers-and-references/Delphi/pointers-and-references-1.delphi rename to Task/Pointers-and-references/Delphi/pointers-and-references-1.pas diff --git a/Task/Pointers-and-references/Delphi/pointers-and-references-2.delphi b/Task/Pointers-and-references/Delphi/pointers-and-references-2.pas similarity index 100% rename from Task/Pointers-and-references/Delphi/pointers-and-references-2.delphi rename to Task/Pointers-and-references/Delphi/pointers-and-references-2.pas diff --git a/Task/Pointers-and-references/Delphi/pointers-and-references-3.delphi b/Task/Pointers-and-references/Delphi/pointers-and-references-3.pas similarity index 100% rename from Task/Pointers-and-references/Delphi/pointers-and-references-3.delphi rename to Task/Pointers-and-references/Delphi/pointers-and-references-3.pas diff --git a/Task/Pointers-and-references/Delphi/pointers-and-references-4.delphi b/Task/Pointers-and-references/Delphi/pointers-and-references-4.pas similarity index 100% rename from Task/Pointers-and-references/Delphi/pointers-and-references-4.delphi rename to Task/Pointers-and-references/Delphi/pointers-and-references-4.pas diff --git a/Task/Pointers-and-references/Delphi/pointers-and-references-5.delphi b/Task/Pointers-and-references/Delphi/pointers-and-references-5.pas similarity index 100% rename from Task/Pointers-and-references/Delphi/pointers-and-references-5.delphi rename to Task/Pointers-and-references/Delphi/pointers-and-references-5.pas diff --git a/Task/Pointers-and-references/Delphi/pointers-and-references-6.delphi b/Task/Pointers-and-references/Delphi/pointers-and-references-6.pas similarity index 100% rename from Task/Pointers-and-references/Delphi/pointers-and-references-6.delphi rename to Task/Pointers-and-references/Delphi/pointers-and-references-6.pas diff --git a/Task/Pointers-and-references/Delphi/pointers-and-references-7.delphi b/Task/Pointers-and-references/Delphi/pointers-and-references-7.pas similarity index 100% rename from Task/Pointers-and-references/Delphi/pointers-and-references-7.delphi rename to Task/Pointers-and-references/Delphi/pointers-and-references-7.pas diff --git a/Task/Pointers-and-references/Delphi/pointers-and-references-8.delphi b/Task/Pointers-and-references/Delphi/pointers-and-references-8.pas similarity index 100% rename from Task/Pointers-and-references/Delphi/pointers-and-references-8.delphi rename to Task/Pointers-and-references/Delphi/pointers-and-references-8.pas diff --git a/Task/Pointers-and-references/Delphi/pointers-and-references-9.delphi b/Task/Pointers-and-references/Delphi/pointers-and-references-9.pas similarity index 100% rename from Task/Pointers-and-references/Delphi/pointers-and-references-9.delphi rename to Task/Pointers-and-references/Delphi/pointers-and-references-9.pas diff --git a/Task/Pointers-and-references/Ecstasy/pointers-and-references.ecstasy b/Task/Pointers-and-references/Ecstasy/pointers-and-references.ecstasy new file mode 100644 index 0000000000..c3b1d166c3 --- /dev/null +++ b/Task/Pointers-and-references/Ecstasy/pointers-and-references.ecstasy @@ -0,0 +1,18 @@ +module test { + @Inject Console console; + + public class Point(Int x, Int y) { + @Override String toString() = $"({x},{y})"; + } + + void run() { + Point p = new Point(0, 0); + p.x = 7; + p.y = p.x; + console.print($"{p=}"); + + // obtain the reference object itself + Ref r = &p; + console.print($"{r.actualType=}"); + } +} diff --git a/Task/Pointers-and-references/Julia/pointers-and-references.julia b/Task/Pointers-and-references/Julia/pointers-and-references.jl similarity index 100% rename from Task/Pointers-and-references/Julia/pointers-and-references.julia rename to Task/Pointers-and-references/Julia/pointers-and-references.jl diff --git a/Task/Pointers-and-references/Kotlin/pointers-and-references.kotlin b/Task/Pointers-and-references/Kotlin/pointers-and-references.kts similarity index 100% rename from Task/Pointers-and-references/Kotlin/pointers-and-references.kotlin rename to Task/Pointers-and-references/Kotlin/pointers-and-references.kts diff --git a/Task/Pointers-and-references/OCaml/pointers-and-references.ocaml b/Task/Pointers-and-references/OCaml/pointers-and-references.ml similarity index 100% rename from Task/Pointers-and-references/OCaml/pointers-and-references.ocaml rename to Task/Pointers-and-references/OCaml/pointers-and-references.ml diff --git a/Task/Pointers-and-references/PascalABC.NET/pointers-and-references.pas b/Task/Pointers-and-references/PascalABC.NET/pointers-and-references.pas new file mode 100644 index 0000000000..8c3a415d0e --- /dev/null +++ b/Task/Pointers-and-references/PascalABC.NET/pointers-and-references.pas @@ -0,0 +1,29 @@ +type MyClass = class +public + x: integer := 555; +end; + +begin + var pi: ^integer; + New(pi); + pi^ := 1023; + var pb: ^byte; + //pb := pi; // compiler error + var p: pointer; + p := pi; + pb := p; + Print(pb^); // byte representation of integer + loop 3 do + begin + pb := pointer(integer(pb)+1); // analog of pb++ + Print(pb^); + end; + Println; + var obj := new MyClass; // obj is a reference to object + // All regferences in .NET are under control of garbage collection + Println(obj); + var obj1 := obj; // another reference to the same object + obj1.x := 666; + Println(obj); + obj := nil; // zero reference +end. diff --git a/Task/Pointers-and-references/Pluto/pointers-and-references.pluto b/Task/Pointers-and-references/Pluto/pointers-and-references.pluto new file mode 100644 index 0000000000..a99023e29b --- /dev/null +++ b/Task/Pointers-and-references/Pluto/pointers-and-references.pluto @@ -0,0 +1,16 @@ +-- This function takes a string (a value type) and a table (reference type). +-- The value and the reference are copied to their respective parameters. +local function f(s, t) + assert(type(s) == "string", "First parameter must be a string.") + assert(type(t) == "table", "Second parameter must be a table.") + -- Add the first argument to the table. + t:insert(s) -- the original 't' will reflect this + -- Mutate the first argument by reversing it. + s = s:reverse() -- the original 's' will not reflect this +end + +local s = "pluto" +local t = {"uranus", "neptune"} +f(s, t) +print(t:concat(", ")) +print(s) diff --git a/Task/Poker-hand-analyser/Ada/poker-hand-analyser.adb b/Task/Poker-hand-analyser/Ada/poker-hand-analyser.adb new file mode 100644 index 0000000000..94bdcc4959 --- /dev/null +++ b/Task/Poker-hand-analyser/Ada/poker-hand-analyser.adb @@ -0,0 +1,162 @@ +pragma Ada_2022; +with Ada.Characters.Handling; use Ada.Characters.Handling; +with Ada.Containers.Generic_Constrained_Array_Sort; +with Ada.Text_IO; use Ada.Text_IO; + +procedure Poker is + + type Face_T is (two, three, four, five, six, seven, eight, nine, t, j, q, k, a); + for Face_T use (2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14); + type Suit_T is (C, D, H, S); + type Card_T is record + Face : Face_T; + Suit : Suit_T; + end record; + + subtype Hand_Index is Natural range 1 .. 5; + type Hand_T is array (Hand_Index) of Card_T; + type Test_Hand_Arr is array (Positive range <>) of Hand_T; + type Pip_Counter_T is array (Face_T range Face_T'Range) of Natural; + + Pip_Counts : Pip_Counter_T := [others => 0]; + + Test_Hands : Test_Hand_Arr := [ + 1 => [(two, H), (two, D), (two, C), (k, S), (q, D)], + 2 => [(two, H), (five, H), (seven, D), (eight, C), (nine, S)], + 3 => [(a, H), (two, D), (three, C), (four, C), (five, D)], + 4 => [(two, H), (three, H), (two, D), (three, C), (three, D)], + 5 => [(two, H), (seven, H), (two, D), (three, C), (three, D)], + 6 => [(two, H), (seven, H), (seven, D), (seven, C), (seven, S)], + 7 => [(t, H), (j, H), (q, H), (k, H), (a, H)], + 8 => [(four, H), (four, S), (k, S), (five, D), (t, S)], + 9 => [(q, C), (t, C), (seven, C), (six, C), (q, C)] + ]; + + function "<" (L, R : Card_T) return Boolean is + begin + if L.Face = R.Face then + return L.Suit < R.Suit; + else + return L.Face < R.Face; + end if; + end "<"; + + procedure Sort_Hand is new Ada.Containers.Generic_Constrained_Array_Sort (Hand_Index, Card_T, Hand_T); + + procedure Print_Hand (Hand : Hand_T) is + begin + for Card of Hand loop + if Card.Face < j then + Put (Face_T'Enum_Rep (Card.Face)'Image); + else + Put (" " & To_Lower (Card.Face'Img)); + end if; + Put (To_Lower (Card.Suit'Img)); + end loop; + end Print_Hand; + + function Is_Invalid (Hand : Hand_T) return Boolean is + begin + for Ix in 2 .. 5 loop + if Face_T'Pos (Hand (Ix).Face) = Face_T'Pos (Hand (Ix - 1).Face) and then + Hand (Ix).Suit = Hand (Ix - 1).Suit + then + return True; + end if; + end loop; + return False; + end Is_Invalid; + + function Is_Flush (Hand : Hand_T) return Boolean is + begin + for Ix in 2 .. 5 loop + if Hand (Ix).Suit /= Hand (1).Suit then + return False; + end if; + end loop; + return True; + end Is_Flush; + + function Is_Straight (Hand : Hand_T) return Boolean is + begin + -- special case: Ace low + if Hand (5).Face = a and then Hand (1).Face = two and then Hand (2).Face = three and then Hand (3).Face = four then + return True; + end if; + for Ix in 2 .. 5 loop + if Face_T'Pos (Hand (Ix).Face) /= Face_T'Pos (Hand (Ix - 1).Face) + 1 then + return False; + end if; + end loop; + return True; + end Is_Straight; + + function Of_A_Kind (N : Positive) return Boolean is + begin + for Pip in two .. a loop + if Pip_Counts (Pip) = N then + return True; + end if; + end loop; + return False; + end Of_A_Kind; + + function Count_Pairs return Natural is + Pairs : Natural := 0; + begin + for Pip in two .. a loop + if Pip_Counts (Pip) = 2 then + Pairs := Pairs + 1; + end if; + end loop; + return Pairs; + end Count_Pairs; + + Flush, Straight : Boolean; + +begin + + for Hand of Test_Hands loop + Print_Hand (Hand); + Put (":"); + Set_Col (20); + Sort_Hand (Hand); -- Print_Hand (Hand); + if Is_Invalid (Hand) then + Put ("invalid"); + else + Flush := Is_Flush (Hand); + Straight := Is_Straight (Hand); + if Flush and Straight then + Put ("straight-flush"); + else + for Pip in two .. a loop + Pip_Counts (Pip) := 0; + for Card of Hand loop + if Card.Face = Pip then + Pip_Counts (Pip) := Pip_Counts (Pip) + 1; + end if; + end loop; + end loop; + if Of_A_Kind (4) then + Put ("four-of-a-kind"); + elsif Of_A_Kind (3) and then Of_A_Kind (2) then + Put ("full-house"); + elsif Flush then + Put ("flush"); + elsif Straight then + Put ("straight"); + elsif Of_A_Kind (3) then + Put ("three-of-a-kind"); + else + case Count_Pairs is + when 2 => Put ("two-pairs"); + when 1 => Put ("one-pair"); + when others => Put ("high-card"); + end case; + end if; + end if; + end if; + Put_Line (""); + end loop; + +end Poker; diff --git a/Task/Poker-hand-analyser/AutoHotkey/poker-hand-analyser-1.ahk b/Task/Poker-hand-analyser/AutoHotkey/poker-hand-analyser-1.ahk index f709709880..9f6900b4fa 100644 --- a/Task/Poker-hand-analyser/AutoHotkey/poker-hand-analyser-1.ahk +++ b/Task/Poker-hand-analyser/AutoHotkey/poker-hand-analyser-1.ahk @@ -1,24 +1,24 @@ PokerHand(hand){ - StringUpper, hand, hand - Sort, hand, FCardSort D%A_Space% - cardSeq := RegExReplace(hand, "[^2-9TJQKA]") - Straight:= InStr("23456789TJQKA", cardSeq) || (cardSeq = "2345A") ? true : false - hand := cardSeq = "2345A" ? RegExReplace(hand, "(.*)\h(A.)", "$2 $1") : hand - Royal := InStr(hand, "A") ? "Royal": "Straight" - return (hand ~= "[2-9TJQKA](.)\h.\1\h.\1\h.\1\h.\1") && (Straight) ? hand "`t" Royal " Flush" - : (hand ~= "([2-9TJQKA]).*?\1.*?\1.*?\1") ? hand "`tFour of a Kind" - : (hand ~= "^([2-9TJQKA]).\h\1.\h(?!\1)([2-9TJQKA]).\h\2.\h\2.$") ? hand "`tFull House" ; xxyyy - : (hand ~= "^([2-9TJQKA]).\h\1.\h\1.\h(?!\1)([2-9TJQKA]).\h\2.$") ? hand "`tFull House" ; xxxyy - : (hand ~= "[2-9TJQKA](.)\h.\1\h.\1\h.\1\h.\1") ? hand "`tFlush" - : (Straight) ? hand "`tStraight" - : (hand ~= "([2-9TJQKA]).*?\1.*?\1") ? hand "`tThree of a Kind" - : (hand ~= "([2-9TJQKA]).\h\1.*?([2-9TJQKA]).\h\2") ? hand "`tTwo Pair" - : (hand ~= "([2-9TJQKA]).\h\1") ? hand "`tOne Pair" - : hand "`tHigh Card" + StringUpper, hand, hand + Sort, hand, FCardSort D%A_Space% + cardSeq := RegExReplace(hand, "[^2-9TJQKA]") + Straight:= InStr("23456789TJQKA", cardSeq) || (cardSeq = "2345A") ? true : false + hand := cardSeq = "2345A" ? RegExReplace(hand, "(.*)\h(A.)", "$2 $1") : hand + Royal := InStr(hand, "A") ? "Royal": "Straight" + return (hand ~= "[2-9TJQKA](.)\h.\1\h.\1\h.\1\h.\1") && (Straight) ? hand "`t" Royal " Flush" + : (hand ~= "([2-9TJQKA]).*?\1.*?\1.*?\1") ? hand "`tFour of a Kind" + : (hand ~= "^([2-9TJQKA]).\h\1.\h(?!\1)([2-9TJQKA]).\h\2.\h\2.$") ? hand "`tFull House" ; xxyyy + : (hand ~= "^([2-9TJQKA]).\h\1.\h\1.\h(?!\1)([2-9TJQKA]).\h\2.$") ? hand "`tFull House" ; xxxyy + : (hand ~= "[2-9TJQKA](.)\h.\1\h.\1\h.\1\h.\1") ? hand "`tFlush" + : (Straight) ? hand "`tStraight" + : (hand ~= "([2-9TJQKA]).*?\1.*?\1") ? hand "`tThree of a Kind" + : (hand ~= "([2-9TJQKA]).\h\1.*?([2-9TJQKA]).\h\2") ? hand "`tTwo Pair" + : (hand ~= "([2-9TJQKA]).\h\1") ? hand "`tOne Pair" + : hand "`tHigh Card" } CardSort(a, b){ - a := SubStr(a, 1, 1), b := SubStr(b, 1, 1) - a := (a = "T") ? 10 : (a = "J") ? 11 : (a = "Q") ? 12 : (a = "K") ? 13 : a - b := (b = "T") ? 10 : (b = "J") ? 11 : (b = "Q") ? 12 : (b = "K") ? 13 : b - return a > b ? 1 : a < b ? -1 : 0 + a := SubStr(a, 1, 1), b := SubStr(b, 1, 1) + a := (a = "T") ? 10 : (a = "J") ? 11 : (a = "Q") ? 12 : (a = "K") ? 13 : a + b := (b = "T") ? 10 : (b = "J") ? 11 : (b = "Q") ? 12 : (b = "K") ? 13 : b + return a > b ? 1 : a < b ? -1 : 0 } diff --git a/Task/Poker-hand-analyser/AutoHotkey/poker-hand-analyser-2.ahk b/Task/Poker-hand-analyser/AutoHotkey/poker-hand-analyser-2.ahk index 0babb40c30..17c2dad32b 100644 --- a/Task/Poker-hand-analyser/AutoHotkey/poker-hand-analyser-2.ahk +++ b/Task/Poker-hand-analyser/AutoHotkey/poker-hand-analyser-2.ahk @@ -13,6 +13,6 @@ T♥ j♥ q♥ 9♥ K♥ q♣ T♣ 7♣ 6♣ 4♣ ) loop, parse, hands, `n, `r - res .= PokerHand(A_LoopField) "`n" + res .= PokerHand(A_LoopField) "`n" MsgBox, 262144, , % res return diff --git a/Task/Poker-hand-analyser/C++/poker-hand-analyser.cpp b/Task/Poker-hand-analyser/C++/poker-hand-analyser.cpp index 873509df25..2322d45f9a 100644 --- a/Task/Poker-hand-analyser/C++/poker-hand-analyser.cpp +++ b/Task/Poker-hand-analyser/C++/poker-hand-analyser.cpp @@ -11,52 +11,52 @@ public: poker() { face = "A23456789TJQK"; suit = "SHCD"; } string analyze( string h ) { - memset( faceCnt, 0, 13 ); memset( suitCnt, 0, 4 ); vector hand; - transform( h.begin(), h.end(), h.begin(), toupper ); istringstream i( h ); - copy( istream_iterator( i ), istream_iterator(), back_inserter >( hand ) ); - if( hand.size() != 5 ) return "invalid hand."; vector::iterator it = hand.begin(); - sort( it, hand.end() ); if( hand.end() != adjacent_find( it, hand.end() ) ) return "invalid hand."; - while( it != hand.end() ) - { - if( ( *it ).length() != 2 ) return "invalid hand."; - int n = face.find( ( *it ).at( 0 ) ), l = suit.find( ( *it ).at( 1 ) ); - if( n < 0 || l < 0 ) return "invalid hand."; - faceCnt[n]++; suitCnt[l]++; it++; - } - cout << h << ": "; return analyzeHand(); + memset( faceCnt, 0, 13 ); memset( suitCnt, 0, 4 ); vector hand; + transform( h.begin(), h.end(), h.begin(), toupper ); istringstream i( h ); + copy( istream_iterator( i ), istream_iterator(), back_inserter >( hand ) ); + if( hand.size() != 5 ) return "invalid hand."; vector::iterator it = hand.begin(); + sort( it, hand.end() ); if( hand.end() != adjacent_find( it, hand.end() ) ) return "invalid hand."; + while( it != hand.end() ) + { + if( ( *it ).length() != 2 ) return "invalid hand."; + int n = face.find( ( *it ).at( 0 ) ), l = suit.find( ( *it ).at( 1 ) ); + if( n < 0 || l < 0 ) return "invalid hand."; + faceCnt[n]++; suitCnt[l]++; it++; + } + cout << h << ": "; return analyzeHand(); } private: string analyzeHand() { - bool p1 = false, p2 = false, t = false, f = false, fl = false, st = false; - for( int x = 0; x < 13; x++ ) - switch( faceCnt[x] ) - { - case 2: if( p1 ) p2 = true; else p1 = true; break; - case 3: t = true; break; - case 4: f = true; - } - for( int x = 0; x < 4; x++ )if( suitCnt[x] == 5 ){ fl = true; break; } + bool p1 = false, p2 = false, t = false, f = false, fl = false, st = false; + for( int x = 0; x < 13; x++ ) + switch( faceCnt[x] ) + { + case 2: if( p1 ) p2 = true; else p1 = true; break; + case 3: t = true; break; + case 4: f = true; + } + for( int x = 0; x < 4; x++ )if( suitCnt[x] == 5 ){ fl = true; break; } - if( !p1 && !p2 && !t && !f ) + if( !p1 && !p2 && !t && !f ) { - int s = 0; - for( int x = 0; x < 13; x++ ) - { - if( faceCnt[x] ) s++; else s = 0; - if( s == 5 ) break; - } - st = ( s == 5 ) || ( s == 4 && faceCnt[0] && !faceCnt[1] ); - } + int s = 0; + for( int x = 0; x < 13; x++ ) + { + if( faceCnt[x] ) s++; else s = 0; + if( s == 5 ) break; + } + st = ( s == 5 ) || ( s == 4 && faceCnt[0] && !faceCnt[1] ); + } - if( st && fl ) return "straight-flush"; - else if( f ) return "four-of-a-kind"; - else if( p1 && t ) return "full-house"; - else if( fl ) return "flush"; - else if( st ) return "straight"; - else if( t ) return "three-of-a-kind"; - else if( p1 && p2 ) return "two-pair"; - else if( p1 ) return "one-pair"; + if( st && fl ) return "straight-flush"; + else if( f ) return "four-of-a-kind"; + else if( p1 && t ) return "full-house"; + else if( fl ) return "flush"; + else if( st ) return "straight"; + else if( t ) return "three-of-a-kind"; + else if( p1 && p2 ) return "two-pair"; + else if( p1 ) return "one-pair"; return "high-card"; } string face, suit; diff --git a/Task/Poker-hand-analyser/EasyLang/poker-hand-analyser.easy b/Task/Poker-hand-analyser/EasyLang/poker-hand-analyser.easy new file mode 100644 index 0000000000..db57bbca8b --- /dev/null +++ b/Task/Poker-hand-analyser/EasyLang/poker-hand-analyser.easy @@ -0,0 +1,93 @@ +func isstraight &h[][] &cnt[] . + for i = 1 to 14 + cnt = cnt[i] + if i = 1 and cnt[14] = 1 : cnt = 1 + if cnt = 1 + cons += 1 + if cons = 5 : return 1 + else + cons = 0 + . + . + return 0 +. +func isflush &h[][] . + for i to 4 + if h[i + 1][2] <> h[i][2] : return 0 + . + return 1 +. +func isvalid &h[][] . + for i to 5 + if h[i][1] = 1 or h[i][2] = 0 : return 0 + . + for i = 1 to 5 : for j = i + 1 to 5 + if h[i][] = h[j][] : return 0 + . + return 1 +. +proc analyse &h[][] . + len cnt[] 14 + for i to 5 : cnt[h[i][1]] += 1 + straight = isstraight h[][] cnt[] + flush = isflush h[][] + if isvalid h[][] = 0 + print "invalid" + elif straight = 1 and flush = 1 + print "straight-flush" + elif flush = 1 + print "flush" + elif straight = 1 + print "straight" + else + for cnt in cnt[] + if cnt = 2 + two += 1 + elif cnt = 3 + three += 1 + elif cnt = 4 + four += 1 + . + . + if four = 1 + print "four-of-a-kind" + elif two = 1 and three = 1 + print "full-house" + elif three = 1 + print "three-of-a-kind" + elif two = 2 + print "two-pairs" + elif two = 1 + print "one-pair" + else + print "high-card" + . + . +. +faces$ = "23456789TJQKA" +suites$ = "SHDC" +repeat + s$ = input + until s$ = "" + write s$ & " : " + card$[] = strtok s$ " " + hand[][] = [ ] + for c$ in card$[] + a$[] = strchars c$ + f = strpos faces$ a$[1] + 1 + s = strpos suites$ a$[2] + hand[][] &= [ f s ] + . + analyse hand[][] +. +input_data +2H 2D 2S KS QD +2H 5H 7D 8S 9D +AH 2D 3S 4S 5S +2H 3H 2D 3S 3D +2H 7H 2D 3S 3D +2H 7H 7D 7S 7C +TH JH QH KH AH +4H 4C KC 5D TC +QC TC 7C 6C 4C +QC TC 7C 6C QC diff --git a/Task/Poker-hand-analyser/Elixir/poker-hand-analyser.elixir b/Task/Poker-hand-analyser/Elixir/poker-hand-analyser.ex similarity index 100% rename from Task/Poker-hand-analyser/Elixir/poker-hand-analyser.elixir rename to Task/Poker-hand-analyser/Elixir/poker-hand-analyser.ex diff --git a/Task/Poker-hand-analyser/FutureBasic/poker-hand-analyser.basic b/Task/Poker-hand-analyser/FutureBasic/poker-hand-analyser.basic new file mode 100644 index 0000000000..1b24f05b77 --- /dev/null +++ b/Task/Poker-hand-analyser/FutureBasic/poker-hand-analyser.basic @@ -0,0 +1,349 @@ +include "Tlbx GameplayKit.incl" + +_window = 1 + +_Deal = 100 +_Four = 101 +_Full = 102 +_flush = 103 +_straight = 104 +_SFlush = 105 +_NewDeck = 106 + +begin globals +int gOmit(52) +int gCount = 1 +int gDeck(4,13) +CFStringRef gSpecial(5) +bool gInsert = NO +bool gNewDeck = NO +end globals + +local fn Set + for int x = 1 to 52):gOmit(x) = x:next +end fn + +//Ken's code +local fn MyImageDrawingHandler( r as CGRect, userData as ptr ) + AttributedStringDrawAtPoint( userData, fn CGPointMake(0,0) ) +end fn = YES + +local fn StringToImage( string as CFStringRef, font as FontRef, color as ColorRef ) as ImageRef + CFDictionaryRef attributes = @{NSFontAttributeName:font,NSForegroundColorAttributeName:color} + CFMutableAttributedStringRef aString = fn MutableAttributedStringWithAttributes( string, attributes ) +end fn = fn ImageWithDrawingHandler( fn AttributedStringSize( aString ), NO, @fn MyImageDrawingHandler, aString ) + +local fn ConvertValueToEmoji( value as long ) as CFStringRef + UInt32 unicodeInt + ScannerRef scanner = fn ScannerWithString( fn StringWithFormat( @"0x%X", value ) ) + fn ScannerScanHexInt( scanner, @unicodeInt ) +end fn = fn StringWithBytes( @unicodeInt, 4, NSUTF32LittleEndianStringEncoding ) + +void local fn BuildWnd + int height = 800 + CGrect rr = fn CGRectMake( 0,0,500,height) + + window _window, @"Assess Poker Hands" , rr + + rr = fn CGRectMake( 10, 60, 90, 26 ) + button _Four,,,@"4 of kind", rr + rr = fn CGRectOffset( rr, 90, 0 ) + button _Full,,,@"Full House", rr + rr = fn CGRectOffset( rr, 90, 0 ) + button _Flush,,,@"Flush", rr + rr = fn CGRectOffset( rr, 90, 0 ) + button _straight,,,@"Straight", rr + rr = fn CGRectOffset( rr, 90, 0 ) + button _sFlush,,,@"S Flush", rr + rr = fn CGRectMake( 120, 20, 100, 26) + button _Deal,,,@"Deal Hand", rr + rr = fn CGRectMake( 240, 20, 200, 26) + checkbox _NewDeck,,,@"New deck each time", rr + textlabel 2,@"Row of buttons to prove the rare hands assess correctly", ( 40, 90, 380, 26 ) + +end fn + +void local fn SetDeck + int x,y + for x = 1 to 13 + for y = 0 to 3 + gDeck(y,x) = (y*13 + 1) + x - 1 + next + next +end fn + +local fn SetCards + NSUInteger i, index, c, j = 1 + CFMutableArrayRef NumbArr = fn MutableArrayNew + + index = 0 : c = 0 + for i = 127137 to 127199 + if ( c == 11 ) + c++ + else + MutableArrayInsertObjectAtIndex( NumbArr, fn StringWithFormat(@"%ld;%d", i, j), index ) + index++ + c++ + j++ + end if + if c mod 14 == 0 && i != 127198 then c = 0 : i += 2 + next + + AppSetProperty( @"Numbers",fn ArrayWithArray( NumbArr ) ) + CFArrayRef Numbers = fn AppProperty( @"Numbers" ) + AppSetProperty( @"NoShuffled",fn ArrayShuffledArray( Numbers )) + +end fn + +local fn GetRandomNo as int + int j,item + Bool check = NO + + do + j = rnd( 52 ) + if gOmit(j) > -1 + item = j + gOmit(j) = -gOmit(j) + check = YES + end if + until check == YES + +end fn = item + +clear local fn AssessHand( cNo(5) as int) as CFStringRef + CFStringRef answer = @"High Card" + int x,y,check + int w,b,col,row,ans(5) + bool checked + + //Sort cards lowest to highest + for x = 1 to 5 + for y = x+1 to 5 + if cNo(y) < cNo(x) then Swap cNo(x), cNo(y) + next + next + + b = 20 + for w = 1 to 5 + for x = 5 to 1 step -1 + for col = 13 to 1 step -1 + for row = 3 to 0 step -1 + if cNo(x) == gDeck(row,col) + if col < b + ans(x) = col + b = 20 + else + end if + end if + next + next + next + next + for x = 1 to 5 + for y = x+1 to 5 + if ans(y) < ans(x) then Swap ans(x), ans(y) + next + next + + //Check for pair, two pair, three of a kind, Four of a kind + if ans(1) == ans(2) && ans(2) == ans(3) && ans(3) == ans(4) then answer = @"Four of a Kind":Exit fn = answer + if ans(2) == ans(3) && ans(3) == ans(4) && ans(4) == ans(5) then answer = @"Four of a Kind":Exit fn = answer + if ans(1) == ans(2) && ans(2) == ans(3) && ans(4) == ans(5) then answer = @"Full House":Exit fn = answer + if ans(1) == ans(2) && ans(3) == ans(4) && ans(4) == ans(5) then answer = @"Full House":Exit fn = answer + if ans(1) == ans(2) && ans(2) == ans(3) then answer = @"three of a kind":Exit fn = answer + if ans(2) == ans(3) && ans(3) == ans(4) then answer = @"three of a kind":Exit fn = answer + if ans(3) == ans(4) && ans(4) == ans(5) then answer = @"three of a kind":Exit fn = answer + if ans(1) == ans(2) && ans(3) == ans(4) then answer = @"two pair":Exit fn = answer + if ans(1) == ans(2) && ans(4) == ans(5) then answer = @"two pair":Exit fn = answer + if ans(1) == ans(2)|| ans(3) == ans(2)|| ans(3) == ans(4) || ans(4) == ans(5) then answer = @"Pair":Exit fn = answer + + + //Check for Straight Flush + if (cNo(1) < 10 && cNo(1) > 0 ) || (cNo(1) < 23 && cNo(1) > 13) || (cNo(1) < 36 && cNo(1) > 26)|| (cNo(1) < 49 && cNo(1) > 39) + if cNo(2) != cNo(1) + 1 + else + if cNo(3) != cNo(2) + 1 + else + if cNo(4) != cNo(3) + 1 + else + if cNo(5) != cNo(4) + 1 + else + answer = @"Straight Flush" + exit fn = answer + end if + end if + end if + end if + end if + + //Check for flush + if (cNo(1) < 10 && cNo(1) > 0 ) || (cNo(1) < 23 && cNo(1) > 13) || (cNo(1) < 36 && cNo(1) > 26)|| (cNo(1) < 49 && cNo(1) > 39) + check = 1 + if (cNo(1) < 10 && cNo(1) > 0 )//Spades + for x = 2 to 5 + if cNo(x) < 13 && cNo(x) > 0 + check++ + end if + next + if check == 5 then answer = @"Flush of Spades" : Exit fn = answer + end if + if (cNo(1) < 23 && cNo(1) > 13 )//Hearts + for x = 2 to 5 + if cNo(x) < 27 && cNo(x) > 13 + check++ + end if + next + if check == 5 then answer = @"Flush of Hearts" : Exit fn = answer + end if + if (cNo(1) < 36 && cNo(1) > 26)//Diamonds + for x = 2 to 5 + if cNo(x) < 40 && cNo(x) > 26 + check++ + end if + next + if check == 5 then answer = @"Flush of Diamonds" : Exit fn = answer + end if + if (cNo(1) < 49 && cNo(1) > 39)//Clubs + for x = 2 to 5 + if cNo(x) < 53 && cNo(x) > 39 + check++ + end if + next + if check == 5 then answer = @"Flush of Clubs" : Exit fn = answer + end if + end if + + //Check for Straight + //Find lowest card ignoring suit + + for x = 5 to 2 step -1 + if (ans(x) - ans(x-1)) == 1 + checked = YES + else + checked = NO + exit next + end if + next + if checked == YES + answer = @"straight" + end if + +end fn = answer + +clear local fn DealHand + CFArrayRef Numb = fn AppProperty( @"NoShuffled" ) + CFStringRef Ans,card,Number + int x, item, CardNo(5), y + CFRange range + + text @"Menlo", 72, fn ColorText + + for x = 1 to 5 + do + if gInsert = YES + ans = gSpecial(x) + else + item = fn GetRandomNo + Ans = Numb[ item] + end if + range = fn StringRangeOfString( Ans, @";" ) + card = fn StringSubstringToIndex( Ans, range.location ) + Number = fn StringSubStringFromIndex( Ans, range.location + 1) + cardNo(x) = fn StringIntValue( Number ) + y = fn StringIntValue( card) + until y != 127199 + if y > 127152 && y < 127185 then text,, fn ColorRed else text,,fn ColorBlack + printf @"%@\b", fn ConvertValueToEmoji( y ) + next + if gNewDeck == YES then fn Set + text @"Times",24, fn ColorMagenta + printf fn AssessHand( cardNo(0)) + printf @"" + text @"Menlo", 72, fn ColorText + gInsert = NO +end fn + +local fn Flush + gSpecial(1) = @"127155;16" + gSpecial(2) = @"127160;21" + gSpecial(3) = @"127153;14" + gSpecial(4) = @"127158;19" + gSpecial(5) = @"127163;24" +end fn + +local fn Four + gSpecial(1) = @"127137;1" + gSpecial(2) = @"127169;27" + gSpecial(3) = @"127153;14" + gSpecial(4) = @"127158;19" + gSpecial(5) = @"127185;40" +end fn + +local fn Full + gSpecial(1) = @"127140;4" + gSpecial(2) = @"127159;20" + gSpecial(3) = @"127175;33" + gSpecial(4) = @"127156;17" + gSpecial(5) = @"127188;43" +end fn + +local fn Straight + gSpecial(1) = @"127158;19" + gSpecial(2) = @"127145;9" + gSpecial(3) = @"127191;46" + gSpecial(4) = @"127178;36" + gSpecial(5) = @"127176;34" +end fn + +local fn SFlush + gSpecial(1) = @"127156;17" + gSpecial(2) = @"127158;19" + gSpecial(3) = @"127160;21" + gSpecial(4) = @"127157;18" + gSpecial(5) = @"127159;20" +end fn + +void local fn doDialog(act as long, ref as long, wnd as long ) + select act + case _btnClick + select ref + case _Newdeck + if fn ButtonState( _NewDeck ) == NSControlStateValueOn then gNewDeck = YES else gNewDeck = NO + case _Deal + if gCount < 11 + fn DealHand + gCount++ + else + cls + fn Set + fn SetDeck + fn SetCards + gCount = 1 + end if + case _Flush + gInsert = YES + fn Flush + case _Four + gInsert = YES + fn Four + case _Full + gInsert = YES + fn Full + case _Straight + gInsert = YES + fn Straight + case _SFlush + gInsert = YES + fn SFlush + end select + end select + +end fn +fn SetDeck +fn SetCards +fn BuildWnd + + +on dialog fn doDialog + +HandleEvents diff --git a/Task/Poker-hand-analyser/JavaScript/poker-hand-analyser-1.js b/Task/Poker-hand-analyser/JavaScript/poker-hand-analyser-1.js index c3c516baf6..1eda06e413 100644 --- a/Task/Poker-hand-analyser/JavaScript/poker-hand-analyser-1.js +++ b/Task/Poker-hand-analyser/JavaScript/poker-hand-analyser-1.js @@ -2,30 +2,30 @@ const FACES = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'j', 'q', 'k', 'a'] const SUITS = ['♥', '♦', '♣', '♠']; function analyzeHand(hand){ - let cards = hand.split(' ').filter(x => x !== 'joker'); - let jokers = hand.split(' ').length - cards.length; - - let faces = cards.map( card => FACES.indexOf(card.slice(0,-1)) ); - let suits = cards.map( card => SUITS.indexOf(card.slice(-1)) ); - - if( cards.some( (card, i, self) => i !== self.indexOf(card) ) || faces.some(face => face === -1) || suits.some(suit => suit === -1) ) - return 'invalid'; - - let flush = suits.every(suit => suit === suits[0]); - let groups = FACES.map( (face,i) => faces.filter(j => i === j).length).sort( (x, y) => y - x ); - let shifted = faces.map(x => (x + 1) % 13); - let distance = Math.min( Math.max(...faces) - Math.min(...faces), Math.max(...shifted) - Math.min(...shifted)); - let straight = groups[0] === 1 && distance < 5; - groups[0] += jokers; - - if (groups[0] === 5) return 'five-of-a-kind' - else if (straight && flush) return 'straight-flush' - else if (groups[0] === 4) return 'four-of-a-kind' - else if (groups[0] === 3 && groups[1] === 2) return 'full-house' - else if (flush) return 'flush' - else if (straight) return 'straight' - else if (groups[0] === 3) return 'three-of-a-kind' - else if (groups[0] === 2 && groups[1] === 2) return 'two-pair' - else if (groups[0] === 2) return 'one-pair' - else return 'high-card'; + let cards = hand.split(' ').filter(x => x !== 'joker'); + let jokers = hand.split(' ').length - cards.length; + + let faces = cards.map( card => FACES.indexOf(card.slice(0,-1)) ); + let suits = cards.map( card => SUITS.indexOf(card.slice(-1)) ); + + if( cards.some( (card, i, self) => i !== self.indexOf(card) ) || faces.some(face => face === -1) || suits.some(suit => suit === -1) ) + return 'invalid'; + + let flush = suits.every(suit => suit === suits[0]); + let groups = FACES.map( (face,i) => faces.filter(j => i === j).length).sort( (x, y) => y - x ); + let shifted = faces.map(x => (x + 1) % 13); + let distance = Math.min( Math.max(...faces) - Math.min(...faces), Math.max(...shifted) - Math.min(...shifted)); + let straight = groups[0] === 1 && distance < 5; + groups[0] += jokers; + + if (groups[0] === 5) return 'five-of-a-kind' + else if (straight && flush) return 'straight-flush' + else if (groups[0] === 4) return 'four-of-a-kind' + else if (groups[0] === 3 && groups[1] === 2) return 'full-house' + else if (flush) return 'flush' + else if (straight) return 'straight' + else if (groups[0] === 3) return 'three-of-a-kind' + else if (groups[0] === 2 && groups[1] === 2) return 'two-pair' + else if (groups[0] === 2) return 'one-pair' + else return 'high-card'; } diff --git a/Task/Poker-hand-analyser/JavaScript/poker-hand-analyser-2.js b/Task/Poker-hand-analyser/JavaScript/poker-hand-analyser-2.js index cfa4170fdd..3eeb6b156d 100644 --- a/Task/Poker-hand-analyser/JavaScript/poker-hand-analyser-2.js +++ b/Task/Poker-hand-analyser/JavaScript/poker-hand-analyser-2.js @@ -1,20 +1,20 @@ let testHands = [ - "2♥ 2♦ 2♣ k♣ q♦", - "2♥ 5♥ 7♦ 8♣ 9♠", - "a♥ 2♦ 3♣ 4♣ 5♦", - "2♥ 3♥ 2♦ 3♣ 3♦", - "2♥ 7♥ 2♦ 3♣ 3♦", - "2♥ 7♥ 7♦ 7♣ 7♠", - "10♥ j♥ q♥ k♥ a♥", - "4♥ 4♠ k♠ 5♦ 10♠", - "q♣ 10♣ 7♣ 6♣ 4♣", - "joker 4♣ k♣ 5♦ 10♠", - "joker 2♦ 2♠ k♠ q♦", - "joker 3♥ 2♦ 3♠ 3♦", - "joker 7♥ 7♦ 7♠ 7♣", - "joker 2♦ joker 4♠ 5♠", - "joker 2♠ joker a♠ 10♠", - "joker q♦ joker a♦ 10♦" + "2♥ 2♦ 2♣ k♣ q♦", + "2♥ 5♥ 7♦ 8♣ 9♠", + "a♥ 2♦ 3♣ 4♣ 5♦", + "2♥ 3♥ 2♦ 3♣ 3♦", + "2♥ 7♥ 2♦ 3♣ 3♦", + "2♥ 7♥ 7♦ 7♣ 7♠", + "10♥ j♥ q♥ k♥ a♥", + "4♥ 4♠ k♠ 5♦ 10♠", + "q♣ 10♣ 7♣ 6♣ 4♣", + "joker 4♣ k♣ 5♦ 10♠", + "joker 2♦ 2♠ k♠ q♦", + "joker 3♥ 2♦ 3♠ 3♦", + "joker 7♥ 7♦ 7♠ 7♣", + "joker 2♦ joker 4♠ 5♠", + "joker 2♠ joker a♠ 10♠", + "joker q♦ joker a♦ 10♦" ]; - + for(hand of testHands) console.log(hand + ": " + analyzeHand(hand)); diff --git a/Task/Poker-hand-analyser/Jq/poker-hand-analyser.jq b/Task/Poker-hand-analyser/Jq/poker-hand-analyser.jq new file mode 100644 index 0000000000..f6ad9a73e3 --- /dev/null +++ b/Task/Poker-hand-analyser/Jq/poker-hand-analyser.jq @@ -0,0 +1,65 @@ +# A card is represented by a JSON object: +def Card($face; $suit): {$face, $suit}; + +def FACES: "23456789tjqka"; +def SUITS: "shdc"; + +# Input: an array of Card +def isStraight: + sort_by(.face) + | (.[0].face + 4 == .[4].face) + or (.[4].face == 14 and .[0].face == 2 and .[3].face == 5) ; + +def isFlush: + .[0].suit as $suit + | all(.[]; .suit == $suit); + +# Input: a string such as "2h 2d 2c kc qd" +def analyzeHand: + (FACES | split("")) as $FACES + | (SUITS | split("")) as $SUITS + | ascii_downcase + | split(" ") + | unique + | if length != 5 or + any(length != 2 or + (.[0:1] | IN($FACES[]) | not) or + (.[1: ] | IN($SUITS[]) | not) ) + then "invalid" + else [.[] as $s | Card(($FACES|index($s[0:1])) + 2; $s[1:]) ] + | . as $cards + | group_by(.face) + | if length == 2 + then if any(length == 4) then "four-of-a-kind" + else "full-house" + end + elif length == 3 + then if any(length == 3) then "three-of-a-kind" + else "two-pairs" + end + elif length == 4 + then "one-pair" + else ($cards|[isFlush, isStraight]) as [$flush, $straight] + | if $flush and $straight then "straight-flush" + elif $flush then "flush" + elif $straight then "straight" + else "high-card" + end + end + end ; + +def hands: [ + "2h 2d 2c kc qd", + "2h 5h 7d 8c 9s", + "ah 2d 3c 4c 5d", + "2h 3h 2d 3c 3d", + "2h 7h 2d 3c 3d", + "2h 7h 7d 7c 7s", + "th jh qh kh ah", + "4h 4s ks 5d ts", + "qc tc 7c 6c 4c", + "ah ah 7c 6c 4c" +]; + +hands[] +| "\(.): \(analyzeHand)" diff --git a/Task/Poker-hand-analyser/Julia/poker-hand-analyser.julia b/Task/Poker-hand-analyser/Julia/poker-hand-analyser.jl similarity index 100% rename from Task/Poker-hand-analyser/Julia/poker-hand-analyser.julia rename to Task/Poker-hand-analyser/Julia/poker-hand-analyser.jl diff --git a/Task/Poker-hand-analyser/Kotlin/poker-hand-analyser-1.kotlin b/Task/Poker-hand-analyser/Kotlin/poker-hand-analyser-1.kts similarity index 100% rename from Task/Poker-hand-analyser/Kotlin/poker-hand-analyser-1.kotlin rename to Task/Poker-hand-analyser/Kotlin/poker-hand-analyser-1.kts diff --git a/Task/Poker-hand-analyser/Kotlin/poker-hand-analyser-2.kotlin b/Task/Poker-hand-analyser/Kotlin/poker-hand-analyser-2.kts similarity index 100% rename from Task/Poker-hand-analyser/Kotlin/poker-hand-analyser-2.kotlin rename to Task/Poker-hand-analyser/Kotlin/poker-hand-analyser-2.kts diff --git a/Task/Poker-hand-analyser/Liberty-BASIC/poker-hand-analyser.basic b/Task/Poker-hand-analyser/Liberty-BASIC/poker-hand-analyser.basic new file mode 100644 index 0000000000..d0798cdfb2 --- /dev/null +++ b/Task/Poker-hand-analyser/Liberty-BASIC/poker-hand-analyser.basic @@ -0,0 +1,371 @@ +NoMainWin +WindowWidth=900 +WindowHeight=720 +BackgroundColor$ = "191 191 255" ' buttonface default +Global Deck, MaxDecks + +StaticText #1.Debug "", 0, 0, 600, 20 +StaticText #1.StaticText "Ten Decks of Poker Hands", 50, 50, 3000, 40 +Button #1.Deal "Deal", [Start], UL, 700, 180, 80, 40 +Button #1.TenThousand "10,000", [TenThousand], UL, 700, 250, 80, 40 +Button #1.Stats "History", ShowStats, UL, 700, 320, 80, 40 +Button #1.Quit "Quit", Quit, UL, 700, 390, 80, 40 +TextEditor #1.TextEditor 50, 100, 600, 500 + +open "POKER HANDS" for dialog as #1 +#1 "TrapClose Quit" +#1 "Font Ariel 12 Bold" +#1.StaticText "!Font Ariel 16 Bold" +#1.TextEditor "!Font Courier_New 14 Bold" +if not(exists("Poker Hands.txt")) then #1.Stats "!Disable" +MaxDecks=10 +wait + +[TenThousand] +TenThousand = 1 +[Start] +if TenThousand then + MaxDecks=10000 + #1.TextEditor "!Hide" + #1.Deal "!Hide" + #1.TenThousand "!Hide" + #1.Stats "!Hide" + #1.Quit "!Hide" + #1.StaticText "Ten Thousand Decks of Poker Hands" +end if +Deck += 1 +if TenThousand then #1.Debug Str$(Deck) +if Deck>MaxDecks then Deck -= 1: call Quit +#1.TextEditor "!cls" +call ShuffleDeck 0 +'call TestDeck +NextCard=1 +for y=1 to 10 + for x=1 to 5 + y$ = A$(NextCard) + B$(x) = ConvertHiCard$(y$) + NextCard += 1 + next x + sort B$(), 1, 5 + for x=NextCard-5 to NextCard-1 + #1.TextEditor A$(x)+" "; + next x + #1.TextEditor " "; + + Values$="" 'determine high value of hand + for x=1 to 5 + Values$ = Values$ + left$(B$(x),1) + next x + HiValue$ = RealValue$(right$(Values$,1)) + + z=0: Flush=0: Straight=0: Royal=0: FourKind=0 + ThreeKind=0: Pair=0: TwoPair=0: FullHouse=0 + if Flush() then Flush=1 + x = Straight() + if x then Straight=1: if x=9 then Royal=1 + z$ = Kind$() + Value$ = RealValue$(right$(z$,1)) + z=val(left$(z$, len(z$)-1)) + if z=41 then FourKind=1 + if z=32 then FullHouse=1 + if z=31 then ThreeKind=1 + if z=22 then TwoPair=1 + if z=21 then Pair=1 + + select case + case Straight and Royal and Flush: #1.TextEditor "Royal Flush": Stats(1) += 1 + case Straight and Flush: #1.TextEditor "Straight Flush, " + HiValue$ + " high": Stats(2) += 1 + case FourKind: #1.TextEditor "Four of a kind, " + Value$ + "s": Stats(3) += 1 + case FullHouse: #1.TextEditor "Full House, " + Value$ + "s high": Stats(4) += 1 + case Flush: #1.TextEditor "Flush, " + HiValue$ + " high": Stats(5) += 1 + case Straight: #1.TextEditor "Straight, " + HiValue$ + " high": Stats(6) += 1 + case ThreeKind: #1.TextEditor "Three of a kind, " + Value$ + "s": Stats(7) += 1 + case TwoPair: #1.TextEditor "Two Pair, " + Value$ + " high": Stats(8) += 1 + case Pair: #1.TextEditor "Pair " + Value$ + "s": Stats(9) += 1 + case else: #1.TextEditor HiValue$ + " high" + end select +next y +#1.TextEditor "" +#1.TextEditor "Deck #" + str$(Deck) +if TenThousand then goto [Start] else wait + +function RealValue$(Value$) + select case Value$ + case "A": RealValue$="T" + case "B": RealValue$="J" + case "C": RealValue$="Q" + case "D": RealValue$="K" + case "E": RealValue$="A" + case else: RealValue$=Value$ + end select +end function + +sub SaveStats Deck + Stats(0) = 10*Deck + if not(exists("Poker Hands.txt")) then + open "Poker Hands.txt" for output as #2 + for x=0 to 9 + print #2 Stats(x) + next + close #2 + #1.Stats "!Enable" + else + open "Poker Hands.txt" for input as #2 + for x=0 to 9 + input #2 History(x) + next + close #2 + for x=0 to 9 + History(x) += Stats(x) + next + open "Poker Hands.txt" for output as #2 + for x=0 to 9 + print #2 History(x) + next + close #2 + end if +end sub + +sub ShowStats + if exists("Poker Hands.txt") then + open "Poker Hands.txt" for input as #2 + for x=0 to 9 + input #2 History(x) + next + close #2 + #1.TextEditor "!cls" + + for x=1 to 9 + Total += History(x) + next x + Nothing = History(0) - Total + + for x=0 to 9 + #1.TextEditor using("###,### ", History(x)); + select case x + case 0: #1.TextEditor "hands " + case 1: #1.TextEditor "royal flush " + using("##.# %", History(x)/History(0)*100) + case 2: #1.TextEditor "straight flush " + using("##.# %", History(x)/History(0)*100) + case 3: #1.TextEditor "four of a kind " + using("##.# %", History(x)/History(0)*100) + case 4: #1.TextEditor "full house " + using("##.# %", History(x)/History(0)*100) + case 5: #1.TextEditor "flush " + using("##.# %", History(x)/History(0)*100) + case 6: #1.TextEditor "straight " + using("##.# %", History(x)/History(0)*100) + case 7: #1.TextEditor "three of a kind " + using("##.# %", History(x)/History(0)*100) + case 8: #1.TextEditor "two pair " + using("##.# %", History(x)/History(0)*100) + case 9: #1.TextEditor "pair " + using("##.# %", History(x)/History(0)*100) + end select + next + #1.TextEditor using("###,### ", Nothing) + "nothing " + using("###.# %", Nothing/History(0)*100) + end if +end sub + +function Kind$() + for x=1 to 5 + C$(x) = left$(B$(x), 1) + next x + if C$(1) = C$(2) then 'check for Lo4 + Lo2=1 + if C$(2) = C$(3) then + Lo2=0: Lo3=1 + if C$(3) = C$(4) then + Lo3=0: Kind$="41" + left$(C$(4),1): exit function + end if + end if + end if + + if C$(5) = C$(4) then 'check for Hi4 + Hi2=1 + if C$(4) = C$(3) then + Hi2=0: Hi3=1 + if C$(3) = C$(2) then + Hi3=0: Kind$="41" + left$(C$(5),1): exit function + end if + end if + end if + + if Lo3 then 'check for Full House and 3Kind + if C$(4) = C$(5) then + Kind$="32" + left$(C$(3),1): exit function + else + Kind$="31" + left$(C$(3),1): exit function + end if + end if + if Hi3 then + if C$(1) = C$(2) then + Kind$="32" + left$(C$(5),1): exit function + else + Kind$="31" + left$(C$(5),1): exit function + end if + end if + if C$(2) = C$(3) and C$(3) = C$(4) then 'Mid3 + Kind$="31" + left$(C$(4),1): exit function + end if + + if Lo2 and Hi2 then 'check for pairs + Kind$="22" + left$(C$(5),1): exit function + end if + if Lo2 and (C$(3)=C$(4)) then + Kind$="22" + left$(C$(4),1): exit function + end if + if Hi2 and (C$(3)=C$(2)) then + Kind$="22" + left$(C$(5),1): exit function + end if + + if Lo2 then Kind$="21" + left$(C$(2),1) + if Hi2 then Kind$="21" + left$(C$(5),1) + if C$(2)=C$(3) then Kind$="21" + left$(C$(3),1) + if C$(3)=C$(4) then Kind$="21" + left$(C$(4),1) +end function + +function Straight() + Order$="23456789ABCDEF" + for x=1 to 5 + Ranks$ = Ranks$ + left$(B$(x), 1) + next x + x = instr(Order$, Ranks$) + if x then Straight=x +end function + +function Flush() + Flush=1 + for x=1 to 5 + Suits$ = Suits$ + right$(B$(x), 1) + next x + for x=2 to 5 + if mid$(Suits$, x, 1) <> left$(Suits$, 1) then Flush=0: exit function + next x +end function + +sub ShuffleDeck Jokers + Jokers = int(abs(Jokers)): if Jokers>4 then Jokers=4 + Size=52 + Jokers + dim CardDeck$(Size+10,1), A$(Size+10) 'Open new card deck +[Start] + for x=1 to Size + CardDeck$(x,0) = "99" + next x + + for x=1 to Size + 1 y=RandomNumber(1,Size) + if CardDeck$(y,0)="99" then CardDeck$(y,0)=str$(x) else goto 1 + next x + + for x=1 to Size 'Examine shuffled deck + if CardDeck$(x,0)=str$(x) then z = 1: exit for + next x + if z then z=0: goto [Start] + for x=1 to Size 'Save shuffled deck + A$(x) = CardFace$(val(CardDeck$(x,0))) + next x + A$(0) = str$(Size) +end sub + +function CardFace$(n) + select case n + case 1: CardFace$="AD" + case 2: CardFace$="2D" + case 3: CardFace$="3D" + case 4: CardFace$="4D" + case 5: CardFace$="5D" + case 6: CardFace$="6D" + case 7: CardFace$="7D" + case 8: CardFace$="8D" + case 9: CardFace$="9D" + case 10: CardFace$="TD" + case 11: CardFace$="JD" + case 12: CardFace$="QD" + case 13: CardFace$="KD" + case 14: CardFace$="AC" + case 15: CardFace$="2C" + case 16: CardFace$="3C" + case 17: CardFace$="4C" + case 18: CardFace$="5C" + case 19: CardFace$="6C" + case 20: CardFace$="7C" + case 21: CardFace$="8C" + case 22: CardFace$="9C" + case 23: CardFace$="TC" + case 24: CardFace$="JC" + case 25: CardFace$="QC" + case 26: CardFace$="KC" + case 27: CardFace$="AH" + case 28: CardFace$="2H" + case 29: CardFace$="3H" + case 30: CardFace$="4H" + case 31: CardFace$="5H" + case 32: CardFace$="6H" + case 33: CardFace$="7H" + case 34: CardFace$="8H" + case 35: CardFace$="9H" + case 36: CardFace$="TH" + case 37: CardFace$="JH" + case 38: CardFace$="QH" + case 39: CardFace$="KH" + case 40: CardFace$="AS" + case 41: CardFace$="2S" + case 42: CardFace$="3S" + case 43: CardFace$="4S" + case 44: CardFace$="5S" + case 45: CardFace$="6S" + case 46: CardFace$="7S" + case 47: CardFace$="8S" + case 48: CardFace$="9S" + case 49: CardFace$="TS" + case 50: CardFace$="JS" + case 51: CardFace$="QS" + case 52: CardFace$="KS" + case 53: CardFace$="X1" + case 54: CardFace$="X2" + case 55: CardFace$="X3" + case 56: CardFace$="X4" + end select +end function + +function RandomNumber(a, b) + smaller = min(a, b) + range = abs(int(a-b))+1 + if range < 1 then exit function + r = int(rnd()*range) + RandomNumber = r + smaller +end function + +function ConvertHiCard$(Card$) + select case left$(Card$,1) + case "T": left$(Card$,1)="A" + case "J": left$(Card$,1)="B" + case "Q": left$(Card$,1)="C" + case "K": left$(Card$,1)="D" + case "A": left$(Card$,1)="E" + case "X": left$(Card$,1)="F" + end select + ConvertHiCard$ = Card$ +end function + +sub TestDeck + data KD, KC, KS, AH, AS ' full house + data 6D, 6C, 6S, 6H, 8H ' four of a kind (io) + data 2D, 4S, 4C, TH, TD ' two pair + data 4H, 5H, 6H, 7H, 8H ' straight flush + data 9S, QD, QC, QH, 3D ' three of a kind + data 6H, 7D, 8C, 9C, TS ' straight + data TH, AH, AS, AC, AD ' four of a kind (hI) + data 3S, 5S, 7S, 9S, JS ' flush + data AD, KD, QD, JD, TD ' royal flush + data 2C, 2D, 3H, 4S, 5C ' one pair + dim A$(50) + for x=1 to 50 + read A$(x) + next x +end sub + +function exists(FileName$) + files "", FileName$, FileDir$() + FileCount$ = FileDir$(0, 0) + exists = val(FileCount$) +end function + +sub Quit + if Deck = MaxDecks then call SaveStats Deck + close #1 + end +end sub diff --git a/Task/Poker-hand-analyser/R/poker-hand-analyser.r b/Task/Poker-hand-analyser/R/poker-hand-analyser.r new file mode 100644 index 0000000000..cb320ffa9a --- /dev/null +++ b/Task/Poker-hand-analyser/R/poker-hand-analyser.r @@ -0,0 +1,58 @@ +library(stringr) + +poker_rank <- function(hand) { + #Get a vector of individual cards in the hand + cards <- str_split_1(hand, " ") + #Any duplicate cards? + if (!identical(cards, unique(cards))) return("Invalid: duplicate cards") + #Split cards into a vector of faces and a vector of suits (both lowercase) + cards <- str_split(cards, "") + faces <- sapply(cards, function(v) v[1]) |> tolower() + suits <- sapply(cards, function(v) v[2]) |> tolower() + #Do faces or suits contain any invalid characters? + if (str_detect(str_flatten(faces), "[^2-9xjqka]")) return("Invalid: bad face") + if (str_detect(str_flatten(suits), "[^cdhs]")) return("Invalid: bad suit") + #Replace court cards (and tens) with numbers and sort numerically + faces <- str_replace_all(faces, c("x" = "10", + "j" = "11", + "q" = "12", + "k" = "13", + "a" = "14")) |> as.numeric() |> sort() + #Are all suits the same? If so, it's a flush + flushcond <- length(unique(suits)) == 1 + #Are all differences between face values equal to 1? If so, it's a straight + facediffs <- diff(faces) + straightcond <- identical(facediffs, rep(1L, 4)) + #Check for A-2-3-4-5 edge case ("the wheel") + wheelcond <- identical(faces, c(2:5, 14)) + if (straightcond || wheelcond) { + if (flushcond) return("Straight flush") + return("Straight") + } else if (flushcond) return("Flush") + #We can tell how many cards have the same face(s) by how many differences in + #their values are zero, and how many of these zeroes are consecutive + nconsec0 <- function(v, n) identical(diff(which(!v)), rep(1L, n-1)) + switch(1+sum(!facediffs), + "High card", + "One pair", + ifelse(nconsec0(facediffs, 2), "Three of a kind", "Two pair"), + ifelse(nconsec0(facediffs, 3), "Four of a kind", "Full house")) +} + +test_hands <- c("2h 2d 2c kc qd", + "2h 5h 7d 8c 9s", + "ah 2d 3c 4c 5d", + "2h 3h 2d 3c 3d", + "2h 7h 2d 3c 3d", + "2d 7h 7d 7c 7s", + "xh jh qh kh ah", + "4h 4s ks 5d xs", + "qc xc 7c 6c qc") + +#Okay, fine, let's show the suits in Unicode +writeLines(paste(str_replace_all(test_hands, c("c" = "♣︎", + "d" = "♦︎", + "h" = "♥︎", + "s" = "♠︎")), + "-", + sapply(test_hands, poker_rank))) diff --git a/Task/Poker-hand-analyser/Rebol/poker-hand-analyser.rebol b/Task/Poker-hand-analyser/Rebol/poker-hand-analyser.rebol new file mode 100644 index 0000000000..61314636af --- /dev/null +++ b/Task/Poker-hand-analyser/Rebol/poker-hand-analyser.rebol @@ -0,0 +1,94 @@ +Rebol [ + title: "Rosetta code: Poker hand analyser" + file: %Poker_hand_analyser.r3 + url: https://rosettacode.org/wiki/Poker_hand_analyser +] + +score-hand: function/with [ + "Poker hand analyser" + hand [string!] +][ + hand: split hand SP + if invalid? hand [return "invalid"] + clear ranks + clear suits + foreach h hand [ + r: h/1 s: h/2 + ranks/:r: either ranks/:r [ranks/:r + 1][1] + suits/:s: either suits/:s [suits/:s + 1][1] + ] + suit-values: values-of suits + rank-values: sort values-of ranks + max-rank: last rank-values + case [ + straight-flush? ["straight-flush"] + four-of-a-kind? ["four-of-a-kind"] + full-house? ["full-house"] + flush? ["flush"] + straight? ["straight"] + three-of-a-kind? ["three-of-a-kind"] + two-pair? ["two-pair"] + one-pair? ["one-pair"] + high-card? ["high-card"] + true ["unclassified"] + ] +][ + ranks: clear #[] + suits: clear #[] + suit-values: rank-values: max-rank: none + ;; Build sorted deck + sorted-deck: copy [] + foreach s "♣♦♥♠" [ + foreach r "23456789TJQKA" [ + append sorted-deck ajoin [r s] + ] + ] + rank-modifiers: make map! [ + #"A" 130 #"K" 120 #"Q" 110 #"J" 100 #"T" 90 + #"9" 80 #"8" 70 #"7" 60 #"6" 50 #"5" 40 + #"4" 30 #"3" 20 #"2" 10 + ] + has-duplicate?: function [deck] [ + (length? deck) != (length? unique copy deck) + ] + invalid?: func [hand] [ + any [ + not all map-each x hand [did find sorted-deck x] + has-duplicate? hand + ] + ] + straight?: function [] [ + if 1 != first find-max :rank-values [return false] + mods: sort map-each x keys-of :ranks [rank-modifiers/:x] + if mods = [10 20 30 40 130] [return true] + while [not last? mods][ + if 10 < abs (mods/1 - mods/2) [return false] + ++ mods + ] + true + ] + highest-suit?: does [ last sort keys-of suits ] + flush?: does [ 1 = length? suit-values ] + straight-flush?: does [ all [straight? flush?] ] + four-of-a-kind?: does [ 4 = max-rank ] + full-house?: does [ [2 3] = rank-values ] + three-of-a-kind?: does [ all [3 = max-rank not full-house?] ] + two-pair?: does [ [2 2] = skip tail :rank-values -2 ] + one-pair?: does [ [1 2] = skip tail :rank-values -2 ] + high-card?: does [ all [1 = max-rank not flush? not straight?] ] +] + +foreach hand [ + "2♥ 2♦ 2♣ K♣ Q♦" + "2♥ 5♥ 7♦ 8♣ 9♠" + "A♥ 2♦ 3♣ 4♣ 5♦" + "2♥ 3♥ 2♦ 3♣ 3♦" + "2♥ 7♥ 2♦ 3♣ 3♦" + "2♥ 7♥ 7♦ 7♣ 7♠" + "T♥ J♥ Q♥ K♥ A♥" + "4♥ 4♠ K♠ 5♦ T♠" + "Q♣ T♣ 7♣ 6♣ 4♣" + "X♣ T♣ 7♣ 6♣ 4♣" +][ + print ["Hand" as-yellow hand "is a" as-green score-hand hand "hand."] +] diff --git a/Task/Poker-hand-analyser/Rust/poker-hand-analyser.rust b/Task/Poker-hand-analyser/Rust/poker-hand-analyser.rs similarity index 100% rename from Task/Poker-hand-analyser/Rust/poker-hand-analyser.rust rename to Task/Poker-hand-analyser/Rust/poker-hand-analyser.rs diff --git a/Task/Poker-hand-analyser/Standard-ML/poker-hand-analyser-1.ml b/Task/Poker-hand-analyser/Standard-ML/poker-hand-analyser-1.ml index 4184bdc9ef..7f25bd8c45 100644 --- a/Task/Poker-hand-analyser/Standard-ML/poker-hand-analyser-1.ml +++ b/Task/Poker-hand-analyser/Standard-ML/poker-hand-analyser-1.ml @@ -37,9 +37,9 @@ val showHand = fn input => | (x as (1,_)::t,ll) => if #2 (hd x ) - (#2 (hd (rev x))) =4 orelse ( #2 (hd (rev x)) = 1 andalso #2 (hd (tl (rev x))) =10 ) then if List.all (fn x => hd ll=x) ll - then "straight-flush" - else "straight" - else if List.all (fn x => hd ll=x) ll then "flush" else "high-card" + then "straight-flush" + else "straight" + else if List.all (fn x => hd ll=x) ll then "flush" else "high-card" | _ => "invalid" diff --git a/Task/Poker-hand-analyser/Tcl/poker-hand-analyser-1.tcl b/Task/Poker-hand-analyser/Tcl/poker-hand-analyser-1.tcl index 00e8f42104..d3903b3f4d 100644 --- a/Task/Poker-hand-analyser/Tcl/poker-hand-analyser-1.tcl +++ b/Task/Poker-hand-analyser/Tcl/poker-hand-analyser-1.tcl @@ -1,116 +1,116 @@ package require Tcl 8.6 namespace eval PokerHandAnalyser { proc analyse {hand} { - set norm [Normalise $hand] - foreach type { - invalid straight-flush four-of-a-kind full-house flush straight - three-of-a-kind two-pair one-pair - } { - if {[Detect-$type $norm]} { - return $type - } - } - # Always possible to use high-card if the hand is legal at all - return high-card + set norm [Normalise $hand] + foreach type { + invalid straight-flush four-of-a-kind full-house flush straight + three-of-a-kind two-pair one-pair + } { + if {[Detect-$type $norm]} { + return $type + } + } + # Always possible to use high-card if the hand is legal at all + return high-card } # This normalises to an internal representation that is a list of pairs, # where each pair is one number for the pips (ace == 14, king == 13, # etc.) and another for the suit. This greatly simplifies detection. proc Normalise {hand} { - set PipMap {j 11 q 12 k 13 a 14} - set SuitMap {♥ 2 h 2 ♦ 1 d 1 ♣ 0 c 0 ♠ 3 s 3} - set hand [string tolower $hand] - set cards [regexp -all -inline {(?:[akqj98765432]|10)[hdcs♥♦♣♠]} $hand] - lsort -command CompareCards [lmap c [string map {} $cards] { - list [string map $PipMap [string range $c 0 end-1]] \ - [string map $SuitMap [string index $c end]] - }] + set PipMap {j 11 q 12 k 13 a 14} + set SuitMap {♥ 2 h 2 ♦ 1 d 1 ♣ 0 c 0 ♠ 3 s 3} + set hand [string tolower $hand] + set cards [regexp -all -inline {(?:[akqj98765432]|10)[hdcs♥♦♣♠]} $hand] + lsort -command CompareCards [lmap c [string map {} $cards] { + list [string map $PipMap [string range $c 0 end-1]] \ + [string map $SuitMap [string index $c end]] + }] } proc CompareCards {a b} { - lassign $a pipA suitA - lassign $b pipB suitB - expr {$pipA==$pipB ? $suitB-$suitA : $pipB-$pipA} + lassign $a pipA suitA + lassign $b pipB suitB + expr {$pipA==$pipB ? $suitB-$suitA : $pipB-$pipA} } # Detection code. Note that the detectors all assume that the preceding # detectors have been run first; this simplifies the logic a lot, but does # mean that the individual detectors are not robust on their own. proc Detect-invalid {hand} { - if {[llength $hand] != 5} {return 1} - foreach c $hand { - if {[incr seen($c)] > 1} {return 1} - } - return 0 + if {[llength $hand] != 5} {return 1} + foreach c $hand { + if {[incr seen($c)] > 1} {return 1} + } + return 0 } proc Detect-straight-flush {hand} { - foreach c $hand { - lassign $c pip suit - if {[info exist prev] && $prev-1 != $pip} { - # Special case: ace low straight flush ("steel wheel") - if {$prev != 14 && $suit != 5} { - return 0 - } - } - set prev $pip - incr seen($suit) - } - return [expr {[array size seen] == 1}] + foreach c $hand { + lassign $c pip suit + if {[info exist prev] && $prev-1 != $pip} { + # Special case: ace low straight flush ("steel wheel") + if {$prev != 14 && $suit != 5} { + return 0 + } + } + set prev $pip + incr seen($suit) + } + return [expr {[array size seen] == 1}] } proc Detect-four-of-a-kind {hand} { - foreach c $hand { - lassign $c pip suit - if {[incr seen($pip)] > 3} {return 1} - } - return 0 + foreach c $hand { + lassign $c pip suit + if {[incr seen($pip)] > 3} {return 1} + } + return 0 } proc Detect-full-house {hand} { - foreach c $hand { - lassign $c pip suit - incr seen($pip) - } - return [expr {[array size seen] == 2}] + foreach c $hand { + lassign $c pip suit + incr seen($pip) + } + return [expr {[array size seen] == 2}] } proc Detect-flush {hand} { - foreach c $hand { - lassign $c pip suit - incr seen($suit) - } - return [expr {[array size seen] == 1}] + foreach c $hand { + lassign $c pip suit + incr seen($suit) + } + return [expr {[array size seen] == 1}] } proc Detect-straight {hand} { - foreach c $hand { - lassign $c pip suit - if {[info exist prev] && $prev-1 != $pip} { - # Special case: ace low straight ("wheel") - if {$prev != 14 && $suit != 5} { - return 0 - } - } - set prev $pip - } - return 1 + foreach c $hand { + lassign $c pip suit + if {[info exist prev] && $prev-1 != $pip} { + # Special case: ace low straight ("wheel") + if {$prev != 14 && $suit != 5} { + return 0 + } + } + set prev $pip + } + return 1 } proc Detect-three-of-a-kind {hand} { - foreach c $hand { - lassign $c pip suit - if {[incr seen($pip)] > 2} {return 1} - } - return 0 + foreach c $hand { + lassign $c pip suit + if {[incr seen($pip)] > 2} {return 1} + } + return 0 } proc Detect-two-pair {hand} { - set pairs 0 - foreach c $hand { - lassign $c pip suit - if {[incr seen($pip)] > 1} {incr pairs} - } - return [expr {$pairs > 1}] + set pairs 0 + foreach c $hand { + lassign $c pip suit + if {[incr seen($pip)] > 1} {incr pairs} + } + return [expr {$pairs > 1}] } proc Detect-one-pair {hand} { - foreach c $hand { - lassign $c pip suit - if {[incr seen($pip)] > 1} {return 1} - } - return 0 + foreach c $hand { + lassign $c pip suit + if {[incr seen($pip)] > 1} {return 1} + } + return 0 } } diff --git a/Task/Poker-hand-analyser/VBScript/poker-hand-analyser.vb b/Task/Poker-hand-analyser/VBScript/poker-hand-analyser.vb deleted file mode 100644 index 365230d60d..0000000000 --- a/Task/Poker-hand-analyser/VBScript/poker-hand-analyser.vb +++ /dev/null @@ -1,124 +0,0 @@ -option explicit -class playingcard - dim suit - dim pips - 'public property get gsuit():gsuit=suit:end property - 'public property get gpips():gpips=pips:end property - public sub print - dim s,p - select case suit - case "S":s=chrW(&h2660) - case "D":s=chrW(&h2666) - case "C":s=chrW(&h2663) - case "H":s=chrW(&h2665) - end select - - select case pips - case 1:p="A" - case 11:p="J" - case 12:p="Q" - case 13:p="K" - case else: p=""& pips - end select - - wscript.stdout.write right(" "&p & s,3)&" " - end sub -end class - -sub printhand(byref h,start) - dim i - for i =start to ubound(h) - h(i).print - next - 'wscript.stdout.writeblanklines(1) -end sub - -function checkhand(byval arr) - dim ss,i,max,last,uses,toppip,j,straight, flush,used,ace - redim nn(13) - - ss=arr(0).suit '????? - straight=true:flush=true - max=0:last=0:used=0:toppip=0:ace=0 - for i=0 to ubound(arr) - j=arr(i).pips - if arr(i).suit<>ss then flush=false - if j>toppip then toppip=j - if j=1 then ace=1 - nn(j)=nn(j)+1 - if nn(j)>max then max= nn(j) - if abs(j-toppip)>=4 then straight=0 - next - for i=1 to ubound(nn) - if nn(i) then used=used+1 - next - if max=1 then - if nn(1) and nn(10) and nn(11) and nn(12) and nn(13) then straight=1 - end if - if flush and straight and max=1 then - checkhand= "straight-flush" - elseif flush then - checkhand= "flush" - elseif straight and max=1 then - checkhand= "straight" - elseif max=4 then - checkhand= "four-of-a-kind" - elseif max=3 then - if used=2 then - checkhand= "full-house" - else - checkhand= "three-of-a-kind" - end if - elseif max=2 then - if used=3 then - checkhand= "two-pair" - else - checkhand= "one-pair" - end if - else - checkhand= "Top "& toppip - End If -end function - - -function readhand(h) - dim i,b,c,p - redim a(4) - for i=0 to ubound(a) - b=h(i) - set c=new playingcard - p=left(b,1) - select case p - case "j": c.pips=11 - case "q": c.pips=12 - case "k": c.pips=13 - case "t": c.pips=10 - case "a": c.pips=1 - case else c.pips=cint(p) - end select - c.suit=ucase(right(b,1)) - set a(i)=c - next - readhand=a - erase a -end function - -dim hands,hh,i - hands = Array(_ -Array("2h", "5h", "7d", "8c", "9s"),_ -Array("2h", "2d", "2c", "kc", "qd"),_ -Array("ah", "2d", "3c", "4c", "5d"),_ -Array("2h", "3h", "2d", "3c", "3d"),_ -Array("2h", "7h", "2d", "3c", "3d"),_ -Array("th", "jh", "qh", "kh", "ah"),_ -Array("4h", "4s", "ks", "5d", "ts"),_ -Array("qc", "tc", "7c", "6c", "4c"),_ -Array("ah", "ah", "7c", "6c", "4c")) - -for i=1 to ubound(hands) - hh=readhand(hands(i)) - printhand hh,0 - wscript.stdout.write vbtab & checkhand(hh) - wscript.stdout.writeblanklines(1) - 'exit for -next diff --git a/Task/Poker-hand-analyser/VBScript/poker-hand-analyser.vbs b/Task/Poker-hand-analyser/VBScript/poker-hand-analyser.vbs new file mode 100644 index 0000000000..6cf04e7378 --- /dev/null +++ b/Task/Poker-hand-analyser/VBScript/poker-hand-analyser.vbs @@ -0,0 +1,124 @@ +option explicit +class playingcard + dim suit + dim pips + 'public property get gsuit():gsuit=suit:end property + 'public property get gpips():gpips=pips:end property + public sub print + dim s,p + select case suit + case "S":s=chrW(&h2660) + case "D":s=chrW(&h2666) + case "C":s=chrW(&h2663) + case "H":s=chrW(&h2665) + end select + + select case pips + case 1:p="A" + case 11:p="J" + case 12:p="Q" + case 13:p="K" + case else: p=""& pips + end select + + wscript.stdout.write right(" "&p & s,3)&" " + end sub +end class + +sub printhand(byref h,start) + dim i + for i =start to ubound(h) + h(i).print + next + 'wscript.stdout.writeblanklines(1) +end sub + +function checkhand(byval arr) + dim ss,i,max,last,uses,toppip,j,straight, flush,used,ace + redim nn(13) + + ss=arr(0).suit '????? + straight=true:flush=true + max=0:last=0:used=0:toppip=0:ace=0 + for i=0 to ubound(arr) + j=arr(i).pips + if arr(i).suit<>ss then flush=false + if j>toppip then toppip=j + if j=1 then ace=1 + nn(j)=nn(j)+1 + if nn(j)>max then max= nn(j) + if abs(j-toppip)>=4 then straight=0 + next + for i=1 to ubound(nn) + if nn(i) then used=used+1 + next + if max=1 then + if nn(1) and nn(10) and nn(11) and nn(12) and nn(13) then straight=1 + end if + if flush and straight and max=1 then + checkhand= "straight-flush" + elseif flush then + checkhand= "flush" + elseif straight and max=1 then + checkhand= "straight" + elseif max=4 then + checkhand= "four-of-a-kind" + elseif max=3 then + if used=2 then + checkhand= "full-house" + else + checkhand= "three-of-a-kind" + end if + elseif max=2 then + if used=3 then + checkhand= "two-pair" + else + checkhand= "one-pair" + end if + else + checkhand= "Top "& toppip + End If +end function + + +function readhand(h) + dim i,b,c,p + redim a(4) + for i=0 to ubound(a) + b=h(i) + set c=new playingcard + p=left(b,1) + select case p + case "j": c.pips=11 + case "q": c.pips=12 + case "k": c.pips=13 + case "t": c.pips=10 + case "a": c.pips=1 + case else c.pips=cint(p) + end select + c.suit=ucase(right(b,1)) + set a(i)=c + next + readhand=a + erase a +end function + +dim hands,hh,i + hands = Array(_ +Array("2h", "5h", "7d", "8c", "9s"),_ +Array("2h", "2d", "2c", "kc", "qd"),_ +Array("ah", "2d", "3c", "4c", "5d"),_ +Array("2h", "3h", "2d", "3c", "3d"),_ +Array("2h", "7h", "2d", "3c", "3d"),_ +Array("th", "jh", "qh", "kh", "ah"),_ +Array("4h", "4s", "ks", "5d", "ts"),_ +Array("qc", "tc", "7c", "6c", "4c"),_ +Array("ah", "ah", "7c", "6c", "4c")) + +for i=1 to ubound(hands) + hh=readhand(hands(i)) + printhand hh,0 + wscript.stdout.write vbtab & checkhand(hh) + wscript.stdout.writeblanklines(1) + 'exit for +next diff --git a/Task/Poker-hand-analyser/XPL0/poker-hand-analyser.xpl0 b/Task/Poker-hand-analyser/XPL0/poker-hand-analyser.xpl0 new file mode 100644 index 0000000000..7e4aed6322 --- /dev/null +++ b/Task/Poker-hand-analyser/XPL0/poker-hand-analyser.xpl0 @@ -0,0 +1,86 @@ +string 0; \Use null-terminated strings (vs MSB terminated) +int Count(1+18); \Counts of ranks and suits in a hand + +proc ShowCat; \Show category of poker hand +int I, J; +[for I:= 1 to 10 do + [if Count(I) = 1 then + [for J:= I+1 to I+4 do \are next 4 cards present? + if Count(J) # 1 then J:= 100; + if J <= 100 then + [Text(0, "straight"); + for J:= 15 to 18 do \scan suits + if Count(J) = 5 then Text(0, "-flush"); + return; + ]; + ]; + ]; +for I:= 15 to 18 do + if Count(I) = 5 then [Text(0, "flush"); return]; +for I:= 2 to 14 do \scan ranks + if Count(I) = 4 then + [Text(0, "four-of-a-kind"); return]; +for I:= 2 to 14 do + [if Count(I) = 3 then + [for J:= 2 to 14 do + if Count(J) = 2 then + [Text(0, "full-house"); return]; + Text(0, "three-of-a-kind"); return; + ]; + ]; +for I:= 2 to 14 do + [if Count(I) = 2 then + [for J:= 2 to 14 do + if J # I and Count(J) = 2 then + [Text(0, "two-pair"); return]; + Text(0, "one-pair"); return; + ]; + ]; +Text(0, "high-card"); +]; + +int Hands, H, Card, I, Char, N, Invalid, Valid(4), Suit, Rank; +char Str; +[Hands:= [ + "2h 2d 2c kc qd ", + "2h 5h 7d 8c 9s ", + "ah 2d 3c 4c 5d ", + "2h 3h 2d 3c 3d ", + "2h 7h 2d 3c 3d ", + "2h 7h 7d 7c 7s ", + "10h jh qh kh ah ", + "4h 4s ks 5d 10s ", + "qc 10c 7c 6c qc "]; +for H:= 0 to 9-1 do + [for I:= 0 to 18 do Count(I):= 0; + for I:= 0 to 3 do Valid(I):= 0; + Invalid:= false; + Str:= Hands(H); + Card:= 0; I:= 0; + loop [Char:= Str(I); I:= I+1; + case Char of + ^h: N:= 18; + ^d: N:= 17; + ^c: N:= 16; + ^s: N:= 15; + ^a: N:= 14; + ^k: N:= 13; + ^q: N:= 12; + ^j: N:= 11; + ^1: N:= 10; + ^ : [N:= 0; Card:= Card+1; if Card >= 5 then quit] + other N:= Char-^0; + Count(N):= Count(N)+1; + if N = 14 then Count(1):= Count(1)+1; \ace in two places + if N <= 14 then Rank:= N + else [Suit:= N - 15; + if Valid(Suit) and 1<; + lst.Add(new Base(3)); + lst.Add(new Derived(4,5.5)); + lst.Add(new Base(6)); + lst.Add(new Derived(7,8.8)); + lst.Println; + var lst1 := new List; + foreach var obj in lst do + lst1.Add(obj.Clone); + lst1.Println; +end. diff --git a/Task/Polymorphic-copy/V-(Vlang)/polymorphic-copy.v b/Task/Polymorphic-copy/V-(Vlang)/polymorphic-copy.v new file mode 100644 index 0000000000..641efffb97 --- /dev/null +++ b/Task/Polymorphic-copy/V-(Vlang)/polymorphic-copy.v @@ -0,0 +1,70 @@ +interface Iden { + identify() string +} + +struct Tina { + value f64 +} + +// structs can be embedded + +struct Sara { + tina Tina + koan string +} + +struct Ryan { + tina Tina + ch chan int +} + +// methods assigned to structs + +fn (x Tina) identify() string { + return "I'm a Tina!" +} + +fn (x Sara) identify() string { + return "I'm a Sara!" +} + +fn (x Ryan) identify() string { + return x.tina.identify() +} + +fn main() { + // initialization of three variables with different types + tina1 := Tina{5} + sara1 := Sara{Tina{6}, "one"} + ryan1 := Ryan{Tina{7}, chan int{}} + + // variables declared with the same interface type + mut i1, mut i2, mut i3 := []Iden{}, []Iden{}, []Iden{} + println("Initial (zero) values of interface variables:") + println("i1: ${i1}") + println("i2: ${i2}") + println("i3: ${i3}") + + // i1, i2, and i3 have the static type of the interface, along with other different types. + i1 << [tina1]; i2 << [sara1]; i3 << [ryan1] // semicolons can be used as optional separators in Vlang + println("\nPolymorphic:") + println("i1: ${i1} / ${i1[0].identify()} / ${typeof(i1[0]).name}\n") + println("i2: ${i2} / ${i2[0].identify()} / ${typeof(i2[0]).name}\n") + println("i3: ${i3} / ${i3[0].identify()} / ${typeof(i3[0]).name}\n") + + // copy: declare and assign in one step using "short declaration" + i1c, i2c, i3c := i1, i2, i3 + + // modify first set of polymorphic variables. + i1, i2, i3 = [Sara{Tina{3}, "dog"}], [Ryan{Tina{1}, chan int{}}], [Tina{2}] + + println("\nFirst set now modified:") + println("i1: ${i1} / ${i1[0].identify()} / ${typeof(i1).name}\n") + println("i2: ${i2} / ${i2[0].identify()} / ${typeof(i2).name}\n") + println("i3: ${i3} / ${i3[0].identify()} / ${typeof(i3).name}\n") + + println("\nCopies made before modifications:") + println("i1c: ${i1c} / ${i1c[0].identify()} / ${typeof(i1c).name}\n") + println("i2c: ${i2c} / ${i2c[0].identify()} / ${typeof(i2c).name}\n") + println("i3c: ${i3c} / ${i3c[0].identify()} / ${typeof(i3c).name}\n") +} diff --git a/Task/Polymorphism/ALGOL-68/polymorphism.alg b/Task/Polymorphism/ALGOL-68/polymorphism.alg index acf04a3823..de3fff4c6f 100644 --- a/Task/Polymorphism/ALGOL-68/polymorphism.alg +++ b/Task/Polymorphism/ALGOL-68/polymorphism.alg @@ -4,11 +4,6 @@ MODE POINT = STRUCT( REAL x, y ); MODE CIRCLE = STRUCT( REAL x, y, r ); - -# PRINT operator # -OP PRINT = ( POINT p )VOID: print( ( "Point(", x OF p, ",", y OF p, ")" ) ); -OP PRINT = ( CIRCLE c )VOID: print( ( "Circle(", r OF c, " @ ", x OF c, ",", y OF c, ")" ) ); - # getters # OP XCOORD = ( POINT p )REAL: x OF p; OP YCOORD = ( POINT p )REAL: y OF p; @@ -17,6 +12,9 @@ OP XCOORD = ( CIRCLE c )REAL: x OF c; OP YCOORD = ( CIRCLE c )REAL: y OF c; OP RADIUS = ( CIRCLE c )REAL: r OF c; +# returns the centre of the circle # +OP CENTRE = ( CIRCLE c )POINT: ( x OF c, y OF c ); + # setters # # the setters are dyadic operators so need a priority - we make them lowest # # priority, like PLUSAB etc. # @@ -43,6 +41,11 @@ OP SETXCOORD = ( REF CIRCLE c, INT x )REF CIRCLE: ( x OF c := x; c ); OP SETYCOORD = ( REF CIRCLE c, INT y )REF CIRCLE: ( y OF c := y; c ); OP SETRADIUS = ( REF CIRCLE c, INT r )REF CIRCLE: ( r OF c := r; c ); +# PRINT operator # +OP PRINT = ( POINT p )VOID: print( ( "Point(", x OF p, ",", y OF p, ")" ) ); +OP PRINT = ( CIRCLE c )VOID: + BEGIN print( ( "Circle(", r OF c, " @ " ) ); PRINT CENTRE c; print( ( ")" ) ) END; + # copy constructors # # A copy constructor is not needed as assignment will generate a copy # # e.g.: "POINT pa, pb; pa := ...; pb := pa; ..." will make pb a copy of pa # @@ -84,12 +87,21 @@ BEGIN CIRCLE c1 := CIRCLE( 1.1, 2.4, 4.1 ); POINT p1 := new point at the origin; + POINT p2 := new point at the origin; - PRINT c1; newline( stand out ); + PRINT c1; print( ( newline ) ); # move c1 so it is centred on p1 # ( c1 SETXCOORD XCOORD p1 ) SETYCOORD YCOORD p1; - PRINT c1; newline( stand out ) + PRINT c1; print( ( newline ) ); + + # offset p2 from the centre of c1 # + p2 SETXCOORD ( XCOORD c1 + 1.0 ) SETYCOORD ( YCOORD c1 + 6.0 ); + # and a new circle with a larger radius at that point # + CIRCLE c2 := new circle at the origin( 10 ); + c2 SETXCOORD XCOORD p2 SETYCOORD YCOORD p2 SETRADIUS ENTIER ( RADIUS c1 + 5.1 ); + + PRINT c2; print( ( newline ) ) END diff --git a/Task/Polymorphism/Ada/polymorphism-1.ada b/Task/Polymorphism/Ada/polymorphism-1.adb similarity index 100% rename from Task/Polymorphism/Ada/polymorphism-1.ada rename to Task/Polymorphism/Ada/polymorphism-1.adb diff --git a/Task/Polymorphism/Ada/polymorphism-2.ada b/Task/Polymorphism/Ada/polymorphism-2.adb similarity index 100% rename from Task/Polymorphism/Ada/polymorphism-2.ada rename to Task/Polymorphism/Ada/polymorphism-2.adb diff --git a/Task/Polymorphism/Ada/polymorphism-3.ada b/Task/Polymorphism/Ada/polymorphism-3.adb similarity index 100% rename from Task/Polymorphism/Ada/polymorphism-3.ada rename to Task/Polymorphism/Ada/polymorphism-3.adb diff --git a/Task/Polymorphism/Ada/polymorphism-4.ada b/Task/Polymorphism/Ada/polymorphism-4.adb similarity index 100% rename from Task/Polymorphism/Ada/polymorphism-4.ada rename to Task/Polymorphism/Ada/polymorphism-4.adb diff --git a/Task/Polymorphism/Ada/polymorphism-5.ada b/Task/Polymorphism/Ada/polymorphism-5.adb similarity index 100% rename from Task/Polymorphism/Ada/polymorphism-5.ada rename to Task/Polymorphism/Ada/polymorphism-5.adb diff --git a/Task/Polymorphism/Arturo/polymorphism.arturo b/Task/Polymorphism/Arturo/polymorphism.arturo index b6d8b8c2fb..7f0b6522ae 100644 --- a/Task/Polymorphism/Arturo/polymorphism.arturo +++ b/Task/Polymorphism/Arturo/polymorphism.arturo @@ -1,21 +1,21 @@ -define :point [x,y][ - init: [ - ensure -> is? :floating this\x - ensure -> is? :floating this\y +define :point [ + init: method [x :floating, y :floating][ + this\x: x + this\y: y ] - print: [ + string: method [][ render "point (x: |this\x|, y: |this\y|)" ] ] -define :circle [center,radius][ - init: [ - ensure -> is? :point this\center - ensure -> is? :floating this\radius +define :circle [ + init: method [center :point, radius :floating][ + this\center: center + this\radius: radius ] - print: [ + string: method [][ render "circle (center: |this\center|, radius: |this\radius|)" ] ] diff --git a/Task/Polymorphism/Delphi/polymorphism-1.delphi b/Task/Polymorphism/Delphi/polymorphism-1.pas similarity index 100% rename from Task/Polymorphism/Delphi/polymorphism-1.delphi rename to Task/Polymorphism/Delphi/polymorphism-1.pas diff --git a/Task/Polymorphism/Delphi/polymorphism-2.delphi b/Task/Polymorphism/Delphi/polymorphism-2.pas similarity index 100% rename from Task/Polymorphism/Delphi/polymorphism-2.delphi rename to Task/Polymorphism/Delphi/polymorphism-2.pas diff --git a/Task/Polymorphism/Elena/polymorphism.elena b/Task/Polymorphism/Elena/polymorphism.elena index 03bd130d3d..bae5fbb71d 100644 --- a/Task/Polymorphism/Elena/polymorphism.elena +++ b/Task/Polymorphism/Elena/polymorphism.elena @@ -33,7 +33,7 @@ class Circle : Point R := r } - print() { console.printLine("Circle") } + print() { Console.printLine("Circle") } } public program() diff --git a/Task/Polymorphism/Julia/polymorphism.julia b/Task/Polymorphism/Julia/polymorphism.jl similarity index 100% rename from Task/Polymorphism/Julia/polymorphism.julia rename to Task/Polymorphism/Julia/polymorphism.jl diff --git a/Task/Polymorphism/Kotlin/polymorphism.kotlin b/Task/Polymorphism/Kotlin/polymorphism.kts similarity index 100% rename from Task/Polymorphism/Kotlin/polymorphism.kotlin rename to Task/Polymorphism/Kotlin/polymorphism.kts diff --git a/Task/Polymorphism/M2000-Interpreter/polymorphism-1.m2000 b/Task/Polymorphism/M2000-Interpreter/polymorphism-1.m2000 deleted file mode 100644 index ad240d902c..0000000000 --- a/Task/Polymorphism/M2000-Interpreter/polymorphism-1.m2000 +++ /dev/null @@ -1,6 +0,0 @@ -\\ block For This {}, or For object [, object2] { }, where object is a group, or a pointer to group, or an item from an array contains a group -\\ This is "this context". -For This { -\\ any new definition here has a temporary use -\\ can be nested, but if we use object then we can use dots to access members of it. If we use a second one then we have to use double dots (..x for second object, for access to x member) -} diff --git a/Task/Polymorphism/M2000-Interpreter/polymorphism-2.m2000 b/Task/Polymorphism/M2000-Interpreter/polymorphism-2.m2000 deleted file mode 100644 index 7f05b1ec8c..0000000000 --- a/Task/Polymorphism/M2000-Interpreter/polymorphism-2.m2000 +++ /dev/null @@ -1,76 +0,0 @@ -Class PointA { - Property x=0~ - Property Y=0~ - Operator "=" (n1) { - n=group(n1) - if n.x=.x Then if n.y=.y then push true : exit - push false - } - Module Print { - Print "Point" , .x, .y - } -Class: - Module PointA { - \\ ? means optionally - Read ? .[x], .[y] - } -} -Class Circle { - Property R=300~ ' type single - Operator "=" (n1) { - n=group(n1) - n2=This ' get a copy of this to check n against n2 - if valid(@n as n2) else push false :exit - if n.x=.x Then if n.y=.y then if n.r=.r then push true : exit - push false - } - Module Print { - Print "Circle", .x, .y, .r - } -Class: - Module Circle { - if match("nn") then { - M=PointA(Number, Number) - } Else.if match("G") then { - M=PointA() - Read M - } Else M=PointA() - M=This -\\ If match("N") then Read M.r \\ check if a number is in top of stack -\\ Read ? M.r \\ optionally - Read M.r \\ for this example, r has value, so this used if stack is empty. - This=M - } -} -A=PointA(10,3) -C=Circle(20,10,5) -D=Circle(A, 100) -B=A -K=PointA() -Z=Circle(A) -P=PointA(600,700) - -\\ N is a pointer to array -N=(A, B, C, D, K, P, Z) -M=each(N) -While M { - For This { - \\ a copy in MM - MM=Array(M) - MM.Print - Print A=MM, D=MM ' using MM=A interpreter use "=" from MM - } -} - -\\ pA is a pointer to D (a named group) -pA->D -Print pA=D, pA=Z -pA=>Print -\\ pA is a pointer to a copy of D (a float group) -pA->(D) -Print pA=D, pA=Z -pA=>Print - -\\ rA is a reference to D (& is optional in Link statement) -Link &D to &rA -rA.Print diff --git a/Task/Polymorphism/M2000-Interpreter/polymorphism-3.m2000 b/Task/Polymorphism/M2000-Interpreter/polymorphism-3.m2000 deleted file mode 100644 index fc2f0b2b45..0000000000 --- a/Task/Polymorphism/M2000-Interpreter/polymorphism-3.m2000 +++ /dev/null @@ -1,67 +0,0 @@ -Class PointA { - X=0~, Y=0~ - Module Print { - Print "Point" , .x, .y - } -Class: - Module PointA { - Read ? .x, .y - } -} -Class Circle { - Property R { - Value, - Set { - If Value>1000 then Value=1000 - } - }=300~ - Module Print { - Print "Circle", .x, .y, .r - } -Class: - Module Circle { - if match("nn") then { - M=PointA(Number, Number) - } Else.if match("G") then { - M=PointA() - Read M - } Else M=PointA() - M=This - This=M - Read ? .r - } -} -A=PointA(10,3) -C=Circle(20,10,5) -D=Circle(A, 100) -B=A -K=PointA() -Z=Circle(A) -P=PointA(600,700) - - \\ N is a pointer to stack -N=Stack:=A, B, C, D, K, P, Z -\\ M is a pointer to an iterator -M=each(N) -While M { - For This { - \\ a copy in MM - MM=StackItem(M) - MM.Print - } -} -\\ NN is a pointer to Inventory -Inventory NN= 1:=A, 2:=B, 3:=C, 4:=D, 5:=K, 6:=P,7:= Z -M=each(NN) -While M { - For This { - \\ a copy in MM - MM=Eval(M) - MM.Print - } -} -\\ we can call NN(3).print -Print "NN(3).Print" -NN(3).Print -NN(3).R=5000 -NN(3).Print diff --git a/Task/Polymorphism/M2000-Interpreter/polymorphism.m2000 b/Task/Polymorphism/M2000-Interpreter/polymorphism.m2000 new file mode 100644 index 0000000000..39d1adf57e --- /dev/null +++ b/Task/Polymorphism/M2000-Interpreter/polymorphism.m2000 @@ -0,0 +1,108 @@ +Module Polymorphism { + Class Point { + private: + double x, y + public: + module print { + Print "x="+.x, "y="+.y + } + class: + module Point (.x, .y) { + } + } + + Class Circle as Point { + private: + double r + public: + group radius { + value { + link parent r to r + =r + } + Set { + Error "No Set for radius" + } + } + module print { + Print "x="+.x, "y="+.y, "r="+.r + } + class: + module Circle (.x, .y, .r) { + } + } + + Class Circle2{ + { ' a different constructor - Version 14 + read xa=0, ya=0, ra=0 + if ra=0 then ra=1 + } + public: + Property r { + value, ' we can read it + set { ' we can change if is >0 + if value<=0 then exit ' skip + } + }=ra + Point Inner(xa, ya) + // add a function to Inner to read private X and Y + Group Inner { + function readXY { + =.x, .y + } + } + Group CircleType { ' an inner object which return a value of type circle + Value { ' return a Circle type + link parent Inner to that + link parent r to ra + =Circle(!that.readXY(), ra) + } + } + module print { + (x,y)=.inner.readXY() + Print "x="+x, "y="+y, "r="+.r + } + } + + A=Point(10, 20) + B=Circle(2,3,5) + doit(A) + doit(B) + print B is type Point = true + print B is type Circle = true + C=Circle2(12,13,15) + C.r=0 + Print "C radius = ";C.r + print C is type Circle2 = true + doit(C.CircleType) + // Circle2 has a Point object + doit(C.Inner) + D=C.CircleType + print "D radious = ";d.radius + try { + d.radius=100 + } + print error$ + print D is type Point = true + print D is type Circle = true + print D is type Circle2 = false + doit(D) + doit2(&D) + doit3(pointer(D)) ' we pass a weak reference - pointer((D)) is a real pointer of a copy of D + Z->Point(10, 20) ' same as Z=Pointer(Point(10,20)), it is a real pointer + doit4(&Z) + End + sub doit(a as Point) ' pass by value + a.print + end sub + sub doit2(&a as Point) ' pass by reference + a.print + end sub + sub doit3(a as *Point) ' pass by value a pointer (weak reference or real pointer) + a=>print + end sub + sub doit4(&a as *Point) ' pass by reference a pointer (weak reference or real pointer) + a=>print + end sub +} +Polymorphism diff --git a/Task/Polymorphism/OCaml/polymorphism.ocaml b/Task/Polymorphism/OCaml/polymorphism.ml similarity index 100% rename from Task/Polymorphism/OCaml/polymorphism.ocaml rename to Task/Polymorphism/OCaml/polymorphism.ml diff --git a/Task/Polymorphism/PascalABC.NET/polymorphism.pas b/Task/Polymorphism/PascalABC.NET/polymorphism.pas new file mode 100644 index 0000000000..97d78c8985 --- /dev/null +++ b/Task/Polymorphism/PascalABC.NET/polymorphism.pas @@ -0,0 +1,36 @@ +type + Point = class + public + auto property x: real; + auto property y: real; + constructor (x,y: real); + begin + Self.x := x; Self.y := y; + end; + procedure Print; virtual; + begin + PABCSystem.Print(x,y); + end; + end; + Circle = class(Point) + public + auto property r: real; + constructor (x,y,r: real); + begin + inherited Create(x,y); + Self.r := r; + end; + procedure Print; override; + begin + inherited Print; + PABCSystem.Print(r); + end; + end; + +begin + var p: Point := new Point(3,5); + var c: Circle := new Circle(10,8,4); + p.Print; + Println; + c.Print; +end. diff --git a/Task/Polymorphism/Rhombus/polymorphism-1.rhombus b/Task/Polymorphism/Rhombus/polymorphism-1.rhombus new file mode 100644 index 0000000000..cbaa7b99a0 --- /dev/null +++ b/Task/Polymorphism/Rhombus/polymorphism-1.rhombus @@ -0,0 +1,11 @@ +#lang rhombus/static + +class Point(~x = 0, ~y = 0): + nonfinal + method print(): + println(@str{Point at @(x),@(y)}) + +class Circle(~r = 1): + extends Point + override method print(): + println(@str{Circle at @(x),@(y) with radius @(r)}) diff --git a/Task/Polymorphism/Rhombus/polymorphism-2.rhombus b/Task/Polymorphism/Rhombus/polymorphism-2.rhombus new file mode 100644 index 0000000000..5808495570 --- /dev/null +++ b/Task/Polymorphism/Rhombus/polymorphism-2.rhombus @@ -0,0 +1,13 @@ +def p = Point() +p.print() // Point at 0,0 +println(p.x) // 0 + +def p2 = Point(~y: 1) +p2.print() // Point at 0,1 + +def c = Circle(~y: 3, ~r: 2) +c.print() // Circle at 0,3 with radius 2 +println(c.r) // 2 + +def c2 = Circle(~y: 5) +c2.print() // Circle at 0,5 with radius 5 diff --git a/Task/Polymorphism/V-(Vlang)/polymorphism.v b/Task/Polymorphism/V-(Vlang)/polymorphism.v new file mode 100644 index 0000000000..021bc526f2 --- /dev/null +++ b/Task/Polymorphism/V-(Vlang)/polymorphism.v @@ -0,0 +1,119 @@ +struct Point { + mut: + x f64 + y f64 +} + +struct Circle { + mut: + x f64 + y f64 + r f64 +} + +// interface definition +interface Printer { + print() +} + +// point methods +fn (p &Point) print() { + println('$p.x $p.y') +} + +fn (p &Point) get_x() f64 { + return p.x +} + +fn (mut p Point) set_x(v f64) { + p.x = v +} + +fn (p &Point) get_y() f64 { + return p.y +} + +fn (mut p Point) set_y(v f64) { + p.y = v +} + +fn (p &Point) clone() &Point { + return &Point{ + x: p.x + y: p.y + } +} + +fn (mut p Point) set(q &Point) { + p.x = q.x + p.y = q.y +} + +// circle methods +fn (c &Circle) print() { + println('$c.x $c.y $c.r') +} + +fn (c &Circle) get_x() f64 { + return c.x +} + +fn (mut c Circle) set_x(v f64) { + c.x = v +} + +fn (c &Circle) get_y() f64 { + return c.y +} + +fn (mut c Circle) set_y(v f64) { + c.y = v +} + +fn (c &Circle) get_r() f64 { + return c.r +} + +fn (mut c Circle) set_r(v f64) { + c.r = v +} + +fn (c &Circle) clone() &Circle { + return &Circle{ + x: c.x + y: c.y + r: c.r + } +} + +fn (mut c Circle) set(d &Circle) { + c.x = d.x + c.y = d.y + c.r = d.r +} + +// "constructors" are idiomatic if involving something more than just assigning initial values +// in V, by default, structs have default values relative to their type +fn new_point(x f64, y f64) &Point { + return &Point{ + x: x + y: y + } +} + +fn new_circle(x f64, y f64, r f64) &Circle { + return &Circle{ + x: x + y: y + r: r + } +} + +// a type of polymorphism: both types implement the printer interface +// print function can be called through a variable without knowing the underlying type +fn main() { + mut i := Printer(new_point(3, 4)) // polymorphic variable + assign one type + i.print() // call polymorphic function + i = Printer(new_circle(5, 12, 13)) // assign different type to same variable + i.print() // same call accesses different method now +} diff --git a/Task/Polynomial-long-division/ALGOL-68/polynomial-long-division.alg b/Task/Polynomial-long-division/ALGOL-68/polynomial-long-division.alg index a6d2bbb09f..2fb8f7582f 100644 --- a/Task/Polynomial-long-division/ALGOL-68/polynomial-long-division.alg +++ b/Task/Polynomial-long-division/ALGOL-68/polynomial-long-division.alg @@ -39,7 +39,6 @@ BEGIN # polynomial division # # are unchanged, so high order elements are lost # OP SHR = ( []INT a, INT shift )[]INT: BEGIN - INT da = DEGREE a; [ LWB a : UPB a ]INT result; FOR i FROM LWB result TO shift - ( LWB result + 1 ) DO result[ i ] := 0 OD; FOR i FROM shift - LWB result TO UPB result DO result[ i ] := a[ i - shift ] OD; @@ -48,7 +47,7 @@ BEGIN # polynomial division # # polynomial long disivion of n in by d in, returns q and r # OP / = ( []INT n in, d in )POLYNOMIALDIVISIONRESULT: - IF DEGREE d < 0 THEN + IF DEGREE d in < 0 THEN print( ( "polynomial division by polynomial with negative degree", newline ) ); stop ELSE @@ -95,13 +94,16 @@ BEGIN # polynomial division # FI END # SHOWPOLYNOMIAL # ; - []INT n = ( []INT( -42, 0, -12, 1 ) )[ AT 0 ]; - []INT d = ( []INT( -3, 1, 0, 0 ) )[ AT 0 ]; + BEGIN + []INT n = ( []INT( -42, 0, -12, 1 ) )[ AT 0 ]; + []INT d = ( []INT( -3, 1, 0, 0 ) )[ AT 0 ]; - POLYNOMIALDIVISIONRESULT qr = n / d; + POLYNOMIALDIVISIONRESULT qr = n / d; - SHOWPOLYNOMIAL n; print( ( " divided by " ) ); SHOWPOLYNOMIAL d; - print( ( newline, " -> Q: " ) ); SHOWPOLYNOMIAL q OF qr; - print( ( newline, " R: " ) ); SHOWPOLYNOMIAL r OF qr + SHOWPOLYNOMIAL n; print( ( " divided by " ) ); SHOWPOLYNOMIAL d; + print( ( newline, " -> Q: " ) ); SHOWPOLYNOMIAL q OF qr; + print( ( newline, " R: " ) ); SHOWPOLYNOMIAL r OF qr; + print( ( newline ) ) + END END diff --git a/Task/Polynomial-long-division/Ada/polynomial-long-division.ada b/Task/Polynomial-long-division/Ada/polynomial-long-division.adb similarity index 100% rename from Task/Polynomial-long-division/Ada/polynomial-long-division.ada rename to Task/Polynomial-long-division/Ada/polynomial-long-division.adb diff --git a/Task/Polynomial-long-division/Delphi/polynomial-long-division.delphi b/Task/Polynomial-long-division/Delphi/polynomial-long-division.pas similarity index 100% rename from Task/Polynomial-long-division/Delphi/polynomial-long-division.delphi rename to Task/Polynomial-long-division/Delphi/polynomial-long-division.pas diff --git a/Task/Polynomial-long-division/EasyLang/polynomial-long-division.easy b/Task/Polynomial-long-division/EasyLang/polynomial-long-division.easy new file mode 100644 index 0000000000..f6be680e3e --- /dev/null +++ b/Task/Polynomial-long-division/EasyLang/polynomial-long-division.easy @@ -0,0 +1,34 @@ +func degree &p[] . + for d = len p[] downto 1 + if p[d] <> 0 : return d - 1 + . + return -1 +. +proc vmul &a[] b . + for i to len a[] : a[i] *= b +. +proc vsub &a[] &b[] . + for i to len a[] : a[i] -= b[i] +. +proc pld nn[] dd[] &q[] &r[] . + if degree dd[] < 0 : return + q[] = [ ] + repeat + degn = degree nn[] + dif = degn - degree dd[] + until dif < 0 + len d[] dif + for e in dd[] : d[] &= e + for i to len nn[] - len d[] : d[] &= 0 + m = nn[degn + 1] / d[degn + 1] + q[] &= m + vmul d[] m + vsub nn[] d[] + . + swap nn[] r[] + for i to len q[] div 2 : swap q[i] q[$ - i + 1] +. +pld [ -42 0 -12 1 ] [ -3 1 ] q[] r[] +print q[] & r[] +pld [ -42 0 -12 1 ] [ -3 1 1 ] q[] r[] +print q[] & r[] diff --git a/Task/Polynomial-long-division/Elixir/polynomial-long-division.elixir b/Task/Polynomial-long-division/Elixir/polynomial-long-division.ex similarity index 100% rename from Task/Polynomial-long-division/Elixir/polynomial-long-division.elixir rename to Task/Polynomial-long-division/Elixir/polynomial-long-division.ex diff --git a/Task/Polynomial-long-division/Julia/polynomial-long-division.julia b/Task/Polynomial-long-division/Julia/polynomial-long-division.jl similarity index 100% rename from Task/Polynomial-long-division/Julia/polynomial-long-division.julia rename to Task/Polynomial-long-division/Julia/polynomial-long-division.jl diff --git a/Task/Polynomial-long-division/Kotlin/polynomial-long-division-1.kotlin b/Task/Polynomial-long-division/Kotlin/polynomial-long-division-1.kts similarity index 100% rename from Task/Polynomial-long-division/Kotlin/polynomial-long-division-1.kotlin rename to Task/Polynomial-long-division/Kotlin/polynomial-long-division-1.kts diff --git a/Task/Polynomial-long-division/Kotlin/polynomial-long-division-2.kotlin b/Task/Polynomial-long-division/Kotlin/polynomial-long-division-2.kts similarity index 100% rename from Task/Polynomial-long-division/Kotlin/polynomial-long-division-2.kotlin rename to Task/Polynomial-long-division/Kotlin/polynomial-long-division-2.kts diff --git a/Task/Polynomial-long-division/OCaml/polynomial-long-division-1.ocaml b/Task/Polynomial-long-division/OCaml/polynomial-long-division-1.ml similarity index 100% rename from Task/Polynomial-long-division/OCaml/polynomial-long-division-1.ocaml rename to Task/Polynomial-long-division/OCaml/polynomial-long-division-1.ml diff --git a/Task/Polynomial-long-division/OCaml/polynomial-long-division-2.ocaml b/Task/Polynomial-long-division/OCaml/polynomial-long-division-2.ml similarity index 100% rename from Task/Polynomial-long-division/OCaml/polynomial-long-division-2.ocaml rename to Task/Polynomial-long-division/OCaml/polynomial-long-division-2.ml diff --git a/Task/Polynomial-long-division/OCaml/polynomial-long-division-3.ocaml b/Task/Polynomial-long-division/OCaml/polynomial-long-division-3.ml similarity index 100% rename from Task/Polynomial-long-division/OCaml/polynomial-long-division-3.ocaml rename to Task/Polynomial-long-division/OCaml/polynomial-long-division-3.ml diff --git a/Task/Polynomial-long-division/OCaml/polynomial-long-division-4.ocaml b/Task/Polynomial-long-division/OCaml/polynomial-long-division-4.ml similarity index 100% rename from Task/Polynomial-long-division/OCaml/polynomial-long-division-4.ocaml rename to Task/Polynomial-long-division/OCaml/polynomial-long-division-4.ml diff --git a/Task/Polynomial-long-division/Pluto/polynomial-long-division.pluto b/Task/Polynomial-long-division/Pluto/polynomial-long-division.pluto new file mode 100644 index 0000000000..9c810796d4 --- /dev/null +++ b/Task/Polynomial-long-division/Pluto/polynomial-long-division.pluto @@ -0,0 +1,30 @@ +require "poly" + +local function ldiv(p1, p2) + local num = p1:toarray():reverse() + local den = p2:toarray():reverse() + local result = {} + local base = #num - #den + while base >= 0 do + local res = num:back() / den:back() + result:insert(res) + num = num:slice(1, #num - 1) + for i = 1, #den - 1 do + num[base + i] -= res * den[i] + end + base -= 1 + end + local quot = poly.of(result) + local rem = poly.of(num) + return {quot, rem} +end + +local num = poly.of({1, -12, 0, -42}) +local den = poly.of({1, -3}) +local res = ldiv(num, den) +print("Dividing polynomials:") +print($"N = {num}") +print($"D = {den}") +print("---------------------") +print($"Q = {res[1]}") +print($"R = {res[2]}") diff --git a/Task/Polynomial-long-division/REXX/polynomial-long-division.rexx b/Task/Polynomial-long-division/REXX/polynomial-long-division-1.rexx similarity index 100% rename from Task/Polynomial-long-division/REXX/polynomial-long-division.rexx rename to Task/Polynomial-long-division/REXX/polynomial-long-division-1.rexx diff --git a/Task/Polynomial-long-division/REXX/polynomial-long-division-2.rexx b/Task/Polynomial-long-division/REXX/polynomial-long-division-2.rexx new file mode 100644 index 0000000000..161de5838d --- /dev/null +++ b/Task/Polynomial-long-division/REXX/polynomial-long-division-2.rexx @@ -0,0 +1,25 @@ +-- 21 Feb 2026 +include Setting + +say 'POLYNOMIAL LONG DIVISION' +say version +say +call Divide '1 -12 0 -42','1 -3' +call Divide '5 4 1','2 3' +call Divide '5 0 0 4 0 0 0 0 0 0 1','2 0 2 0 3' +call Divide '2 -24 2 -108 3 -120 0 -126','2 0 2 0 3' +call Divide '1 2','1 2 3' +call Divide '1 2 3','1 2 3' +call Divide '1 2 3','2' +call Divide '2 0 0','1 0' +exit + +Divide: +arg x,y +z = DivP(x,y); parse var z q','r +say 'Formula:' Poly2form(x) '/' Poly2form(y) '=' Poly2form(q) 'Rem' Poly2form(r) +say 'Check :' Poly2form(q) '*' Poly2form(y) '+' Poly2form(r) '=' Poly2form(AddP(MulP(q,y),r)) +return + +-- AddP; MulP; DivP; Poly2form +include Math diff --git a/Task/Polynomial-regression/Ada/polynomial-regression-1.ada b/Task/Polynomial-regression/Ada/polynomial-regression-1.adb similarity index 100% rename from Task/Polynomial-regression/Ada/polynomial-regression-1.ada rename to Task/Polynomial-regression/Ada/polynomial-regression-1.adb diff --git a/Task/Polynomial-regression/Ada/polynomial-regression-2.ada b/Task/Polynomial-regression/Ada/polynomial-regression-2.adb similarity index 100% rename from Task/Polynomial-regression/Ada/polynomial-regression-2.ada rename to Task/Polynomial-regression/Ada/polynomial-regression-2.adb diff --git a/Task/Polynomial-regression/EasyLang/polynomial-regression.easy b/Task/Polynomial-regression/EasyLang/polynomial-regression.easy index 8bd9ec21df..c608f605c7 100644 --- a/Task/Polynomial-regression/EasyLang/polynomial-regression.easy +++ b/Task/Polynomial-regression/EasyLang/polynomial-regression.easy @@ -1,7 +1,7 @@ func eval a b c x . return a + (b + c * x) * x . -proc regression xa[] ya[] . . +proc regression xa[] ya[] . n = len xa[] for i = 1 to n xm = xm + xa[i] @@ -30,7 +30,7 @@ proc regression xa[] ya[] . . c = (sx2y * sxx - sxy * sxx2) / (sxx * sx2x2 - sxx2 * sxx2) a = ym - b * xm - c * x2m print "y = " & a & " + " & b & "x + " & c & "x^2" - numfmt 0 3 + numfmt 3 0 for i = 1 to n print xa[i] & " " & ya[i] & " " & eval a b c xa[i] . diff --git a/Task/Polynomial-regression/Emacs-Lisp/polynomial-regression.l b/Task/Polynomial-regression/Emacs-Lisp/polynomial-regression.el similarity index 100% rename from Task/Polynomial-regression/Emacs-Lisp/polynomial-regression.l rename to Task/Polynomial-regression/Emacs-Lisp/polynomial-regression.el diff --git a/Task/Polynomial-regression/Jq/polynomial-regression.jq b/Task/Polynomial-regression/Jq/polynomial-regression.jq new file mode 100644 index 0000000000..7023590262 --- /dev/null +++ b/Task/Polynomial-regression/Jq/polynomial-regression.jq @@ -0,0 +1,47 @@ +def mean: add/length; + +def inner_product($y): + . as $x + | reduce range(0; length) as $i (0; . + ($x[$i] * $y[$i])); + +# $x and $y should be arrays of the same length +# Emit { a, b, c, z} +# Attempt to avoid overflow +def polynomialRegression($x; $y): + ($x | length) as $length + | ($length * $length) as $l2 + | ($x | map(./$length)) as $xs + | ($xs | add) as $xm + | ($y | mean) as $ym + | ($xs | map(. * .) | add * $length) as $x2m + | ($x | map( (./$length) * . * .) | add) as $x3m + | ($xs | map(. * . | (.*.) ) | add * $l2 * $length) as $x4m + | ($xs | inner_product($y)) as $xym + | ($xs | map(. * .) | inner_product($y) * $length) as $x2ym + + | ($x2m - $xm * $xm) as $sxx + | ($xym - $xm * $ym) as $sxy + | ($x3m - $xm * $x2m) as $sxx2 + | ($x4m - $x2m * $x2m) as $sx2x2 + | ($x2ym - $x2m * $ym) as $sx2y + | {z: ([$x,$y] | transpose) } + | .b = ($sxy * $sx2x2 - $sx2y * $sxx2) / ($sxx * $sx2x2 - $sxx2 * $sxx2) + | .c = ($sx2y * $sxx - $sxy * $sxx2) / ($sxx * $sx2x2 - $sxx2 * $sxx2) + | .a = $ym - .b * $xm - .c * $x2m ; + +# Input: {a,b,c,z} +def report: + def lpad($len): tostring | ($len - length) as $l | (" " * $l) + .; + def abc($x): .a + .b * $x + .c * $x * $x; + def print($p): "\($p[0] | lpad(3)) \($p[1] | lpad(4)) \(abc($p[0]) | lpad(5))"; + + "y = \(.a) + \(.b)x + \(.c)x^2\n", + " Input Approximation", + " x y y\u0302", + print(.z[]) ; + +def x: [range(0;11)]; +def y: [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321]; + +polynomialRegression(x; y) +| report diff --git a/Task/Polynomial-regression/Julia/polynomial-regression.julia b/Task/Polynomial-regression/Julia/polynomial-regression.jl similarity index 100% rename from Task/Polynomial-regression/Julia/polynomial-regression.julia rename to Task/Polynomial-regression/Julia/polynomial-regression.jl diff --git a/Task/Polynomial-regression/Kotlin/polynomial-regression.kotlin b/Task/Polynomial-regression/Kotlin/polynomial-regression.kts similarity index 100% rename from Task/Polynomial-regression/Kotlin/polynomial-regression.kotlin rename to Task/Polynomial-regression/Kotlin/polynomial-regression.kts diff --git a/Task/Polynomial-regression/OCaml/polynomial-regression.ocaml b/Task/Polynomial-regression/OCaml/polynomial-regression.ml similarity index 100% rename from Task/Polynomial-regression/OCaml/polynomial-regression.ocaml rename to Task/Polynomial-regression/OCaml/polynomial-regression.ml diff --git a/Task/Polynomial-regression/Pluto/polynomial-regression.pluto b/Task/Polynomial-regression/Pluto/polynomial-regression.pluto new file mode 100644 index 0000000000..38891bf07c --- /dev/null +++ b/Task/Polynomial-regression/Pluto/polynomial-regression.pluto @@ -0,0 +1,35 @@ +require "table2" +local fmt = require "fmt" + +local function polynomial_regression(x, y) + local xm = x:mean() + local ym = y:mean() + local x2m = x:mapped(|e| -> e * e):mean() + local x3m = x:mapped(|e| -> e * e * e):mean() + local x4m = x:mapped(|e| -> e * e * e * e):mean() + local z = table.zip(x, y) + local xym = z:mapped(|p| -> p[1] * p[2]):mean() + local x2ym = z:mapped(|p| -> p[1] * p[1] * p[2]):mean() + + local sxx = x2m - xm * xm + local sxy = xym - xm * ym + local sxx2 = x3m - xm * x2m + local sx2x2 = x4m - x2m * x2m + local sx2y = x2ym - x2m * ym + + local b = (sxy * sx2x2 - sx2y * sxx2) / (sxx * sx2x2 - sxx2 * sxx2) + local c = (sx2y * sxx - sxy * sxx2) / (sxx * sx2x2 - sxx2 * sxx2) + local a = ym - b * xm - c * x2m + + local function abc(xx) return a + b * xx + c * xx * xx end + + fmt.print("y = %g + %gx + %gx%s\n", a, b, c, fmt.super(2)) + print(" Input Approximation") + print(" x y y1") + for z as p do fmt.print("%2d %3d %5.1f", p[1], p[2], abc(p[1])) end +end + +local x = {} +for i = 1, 11 do x[i] = i - 1 end +local y = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321} +polynomial_regression(x, y) diff --git a/Task/Polynomial-regression/PowerShell/polynomial-regression.psh b/Task/Polynomial-regression/PowerShell/polynomial-regression.ps1 similarity index 100% rename from Task/Polynomial-regression/PowerShell/polynomial-regression.psh rename to Task/Polynomial-regression/PowerShell/polynomial-regression.ps1 diff --git a/Task/Polynomial-regression/Rust/polynomial-regression.rs b/Task/Polynomial-regression/Rust/polynomial-regression.rs new file mode 100644 index 0000000000..5d1857e848 --- /dev/null +++ b/Task/Polynomial-regression/Rust/polynomial-regression.rs @@ -0,0 +1,41 @@ +fn poly_regression(x: &[i32], y: &[i32]) { + let n = x.len(); + let r: Vec = (0..n as i32).collect(); + + let xm = x.iter().sum::() as f64 / x.len() as f64; + let ym = y.iter().sum::() as f64 / y.len() as f64; + let x2m: f64 = r.iter().map(|&a| (a * a) as f64).sum::() / r.len() as f64; + let x3m: f64 = r.iter().map(|&a| (a * a * a) as f64).sum::() / r.len() as f64; + let x4m: f64 = r.iter().map(|&a| (a * a * a * a) as f64).sum::() / r.len() as f64; + + let xym: f64 = x.iter().zip(y.iter()).map(|(&a, &b)| (a as f64) * (b as f64)).sum::() / x.len().min(y.len()) as f64; + + let x2ym: f64 = x.iter().zip(y.iter()).map(|(&a, &b)| (a * a) as f64 * (b as f64)).sum::() / x.len().min(y.len()) as f64; + + let sxx = x2m - xm * xm; + let sxy = xym - xm * ym; + let sxx2 = x3m - xm * x2m; + let sx2x2 = x4m - x2m * x2m; + let sx2y = x2ym - x2m * ym; + + let b = (sxy * sx2x2 - sx2y * sxx2) / (sxx * sx2x2 - sxx2 * sxx2); + let c = (sx2y * sxx - sxy * sxx2) / (sxx * sx2x2 - sxx2 * sxx2); + let a = ym - b * xm - c * x2m; + + let abc = |xx: i32| a + b * (xx as f64) + c * (xx * xx) as f64; + + println!("y = {} + {}x + {}x^2", a, b, c); + println!(" Input Approximation"); + println!(" x y y1"); + + for (&x_val, &y_val) in x.iter().zip(y.iter()) { + println!("{:2} {:3} {:5.1}", x_val, y_val, abc(x_val)); + } +} + +fn main() { + let x: Vec = (0..11).collect(); + let y: Vec = vec![1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321]; + + poly_regression(&x, &y); +} diff --git a/Task/Polynomial-regression/XPL0/polynomial-regression.xpl0 b/Task/Polynomial-regression/XPL0/polynomial-regression.xpl0 new file mode 100644 index 0000000000..e21bbb84cb --- /dev/null +++ b/Task/Polynomial-regression/XPL0/polynomial-regression.xpl0 @@ -0,0 +1,60 @@ +proc PolyReg(XA, YA, N); +real XA, YA; int N; +int I; +real XM, YM, X2M, X3M, X4M, XYM, X2YM; +real SXX, SXY, SXX2, SX2X2, SX2Y; +real A, B, C, Y, RN; +[XM:= 0.; YM:= 0.; +X2M:= 0.; X3M:= 0.; X4M:= 0.; +XYM:= 0.; X2YM:= 0.; +for I:= 0 to N-1 do + [XM:= XM + XA(I); + YM:= YM + YA(I); + X2M:= X2M + XA(I)*XA(I); + X3M:= X3M + XA(I)*XA(I)*XA(I); + X4M:= X4M + XA(I)*XA(I)*XA(I)*XA(I); + XYM:= XYM + XA(I)*YA(I); + X2YM:= X2YM + XA(I)*XA(I)*YA(I); + ]; +RN:= float(N); +XM:= XM/RN; +YM:= YM/RN; +X2M:= X2M/RN; +X3M:= X3M/RN; +X4M:= X4M/RN; +XYM:= XYM/RN; +X2YM:= X2YM/RN; + +SXX:= X2M - XM*XM; +SXY:= XYM - XM*YM; +SXX2:= X3M - XM*X2M; +SX2X2:= X4M - X2M*X2M; +SX2Y:= X2YM - X2M*YM; + +B:= (SXY*SX2X2 - SX2Y*SXX2) / (SXX*SX2X2 - SXX2*SXX2); +C:= (SX2Y*SXX - SXY*SXX2) / (SXX*SX2X2 - SXX2*SXX2); +A:= YM - B*XM - C*X2M; + +Format(1, 0); +Text(0, "y = "); RlOut(0, A); +Text(0, " + "); RlOut(0, B); +Text(0, "x + "); RlOut(0, C); +Text(0, "x^^2"); CrLf(0); +Text(0, " Input Approx^m^j"); +Text(0, " x y y1^m^j"); +for I:=0 to N-1 do + [Format(3, 0); + RlOut(0, XA(I)); Text(0, " "); + RlOut(0, YA(I)); Text(0, " "); + Y:= A + (B + C*XA(I)) * XA(I); + Format(3, 1); + RlOut(0, Y); + CrLf(0); + ]; +]; + +real XA, YA; +[XA:= [0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.]; + YA:= [1., 6., 17., 34., 57., 86., 121., 162., 209., 262., 321.]; +PolyReg(XA, YA, 11); +] diff --git a/Task/Polyspiral/Delphi/polyspiral.delphi b/Task/Polyspiral/Delphi/polyspiral.pas similarity index 100% rename from Task/Polyspiral/Delphi/polyspiral.delphi rename to Task/Polyspiral/Delphi/polyspiral.pas diff --git a/Task/Polyspiral/EasyLang/polyspiral.easy b/Task/Polyspiral/EasyLang/polyspiral.easy index 62be7e4f19..d7558c66a5 100644 --- a/Task/Polyspiral/EasyLang/polyspiral.easy +++ b/Task/Polyspiral/EasyLang/polyspiral.easy @@ -1,20 +1,18 @@ -color 944 -linewidth 0.3 +gcolor 944 +glinewidth 0.3 on animate - clear + gclear incr = (incr + 0.05) mod 360 - x1 = 50 - y1 = 50 + x = 50 + y = 50 + glineto x y length = 1 angle = incr - move x1 y1 for i = 1 to 150 - x2 = x1 + cos angle * length - y2 = y1 + sin angle * length - line x2 y2 - x1 = x2 - y1 = y2 + x += cos angle * length + y += sin angle * length + glineto x y length += 1 - angle = (angle + incr) mod 360 + angle += incr . . diff --git a/Task/Polyspiral/Julia/polyspiral.julia b/Task/Polyspiral/Julia/polyspiral.jl similarity index 100% rename from Task/Polyspiral/Julia/polyspiral.julia rename to Task/Polyspiral/Julia/polyspiral.jl diff --git a/Task/Polyspiral/Kotlin/polyspiral.kotlin b/Task/Polyspiral/Kotlin/polyspiral.kts similarity index 100% rename from Task/Polyspiral/Kotlin/polyspiral.kotlin rename to Task/Polyspiral/Kotlin/polyspiral.kts diff --git a/Task/Polyspiral/Lua/polyspiral.lua b/Task/Polyspiral/Lua/polyspiral.lua index 5ebdb53834..c1455e1fd0 100644 --- a/Task/Polyspiral/Lua/polyspiral.lua +++ b/Task/Polyspiral/Lua/polyspiral.lua @@ -4,7 +4,7 @@ function love.load () end function love.update (dt) - incr = (incr + 0.05) % 360 + incr = (incr + 0.05 * dt) % 360 x1 = love.graphics.getWidth() / 2 y1 = love.graphics.getHeight() / 2 length = 5 diff --git a/Task/Polyspiral/M2000-Interpreter/polyspiral.m2000 b/Task/Polyspiral/M2000-Interpreter/polyspiral.m2000 new file mode 100644 index 0000000000..dc0ec8a48d --- /dev/null +++ b/Task/Polyspiral/M2000-Interpreter/polyspiral.m2000 @@ -0,0 +1,26 @@ +module polyspiral { + cls 0,0 + var incr=0 ' double by default + var x=scale.x / 2, y=scale.y / 2 + var length, angle, incr + refresh 1000 + every 1000/15 { + cls #220055 + incr+=0.005 + move x, y + length = twipsx*20 + angle = incr + pen color(random(100, 200),random(100, 200),random(100, 200)) + for n=1 to 150 + pen #FF0055 + width 2 {draw angle angle, length} + length+=twipsx*5 + angle+=incr + next + if keypress(32) then exit + refresh 1000 + } + refresh 25 ' this is the normal +} +polyspiral +pen 14 diff --git a/Task/Polyspiral/Nim/polyspiral.nim b/Task/Polyspiral/Nim/polyspiral.nim index 54c2fe404c..fef72f9d98 100644 --- a/Task/Polyspiral/Nim/polyspiral.nim +++ b/Task/Polyspiral/Nim/polyspiral.nim @@ -1,19 +1,18 @@ -# Pendulum simulation. +import std/[math, random] -import math, random - -import gintro/[gobject, gdk, gtk, gio, glib, cairo] +import gtk2 except update +import gdk2, glib2, cairo const Width = 500 Height = 500 DrawIters = 72 - Red = [float 1, 0, 0] - Green = [float 0, 1, 0] - Blue = [float 0, 0, 1] - Black = [float 0, 0, 0] - White = [float 255, 255, 255] - Gold = [float 255, 215, 0] + Red = (1.0, 0.0, 0.0) + Green = (0.0, 1.0, 0.0) + Blue = (0.0, 0.0, 1.0) + Black = (0.0, 0.0, 0.0) + White = (1.0, 1.0, 1.0) + Gold = (1.0, 215 / 255, 0.0) Colors = [Blue, Red, Green, White, Gold] Angles = [75, 100, 135, 160] @@ -23,39 +22,41 @@ type Point = Vec2 # Description of the simulation. - Simulation = ref object - area: DrawingArea + Simulation = object + area: PDrawingArea xmax, ymax: float center: Point itercount: int -#--------------------------------------------------------------------------------------------------- -proc newSimulation(area: DrawingArea; width, height: int): Simulation {.noInit.} = - ## Allocate and initialize the simulation object. +proc initSimulation(area: PDrawingArea; width, height: int): Simulation {.noInit.} = + ## Initialize a simulation object. + result = Simulation(area: area, + xmax: float(width - 1), + ymax: float(height - 1), + center: (result.xmax * 0.5, result.ymax * 0.5)) - new(result) - result.area = area - result.xmax = float(width - 1) - result.ymax = float(height - 1) - result.center = (result.xmax * 0.5, result.ymax * 0.5) -#--------------------------------------------------------------------------------------------------- +func δ(r, θ: float): Vec2 = + ## Return the delta in cartesian coordinates. + (r * cos(degToRad(θ)), r * sin(degToRad(θ))) -func δ(r, θ: float): Vec2 = (r * cos(degToRad(θ)), r * sin(degToRad(θ))) - -#--------------------------------------------------------------------------------------------------- func nextPoint(p: Point; r, θ: float): Point = + ## Return the next point for given polar coordinates. let dp = δ(r, θ) result = (p.x + dp.x, p.y + dp.y) -#--------------------------------------------------------------------------------------------------- -proc draw(sim: Simulation; context: cairo.Context) = +template setColor(ctx: ptr Context; color: (float, float, float)) = + ## Set the color for next drawing in given context. + ctx.setSourceRgb(color[0], color[1], color[2]) + + +proc draw(sim: var Simulation; context: ptr Context) = ## Draw the spiral. - context.setSource(Black) + context.setColor(Black) context.rectangle(0, 0, sim.xmax, sim.ymax) context.fill() @@ -71,7 +72,7 @@ proc draw(sim: Simulation; context: cairo.Context) = for _ in 1..DrawIters: let p2 = p1.nextPoint(r, θ) context.moveTo(p1.x, p1.y) - context.setSource(color) + context.setColor(color) context.lineTo(p2.x, p2.y) context.setLineWidth(2) context.stroke() @@ -79,35 +80,32 @@ proc draw(sim: Simulation; context: cairo.Context) = r += δr p1 = p2 -#--------------------------------------------------------------------------------------------------- -proc update(sim: Simulation): gboolean = +proc update(sim: var Simulation): gboolean = ## Update the simulation state. - - result = gboolean(1) sim.draw(sim.area.window.cairoCreate()) inc sim.itercount + result = gboolean(1) -#--------------------------------------------------------------------------------------------------- -proc activate(app: Application) = - ## Activate the application. +proc onDestroyEvent(widget: PWidget; data: pointer): gboolean {.cdecl.} = + ## Quit the application. + mainQuit() - let window = app.newApplicationWindow() - window.setSizeRequest(Width, Height) - window.setTitle("Polyspiral") - let area = newDrawingArea() - window.add(area) +nimInit() - let sim = newSimulation(area, Width, Height) +let window = windowNew(WINDOW_TOPLEVEL) +window.setSizeRequest(Width, Height) +window.setTitle("Polyspiral") +discard window.signalConnect("destroy", SIGNAL_FUNC(onDestroyEvent), nil) - timeoutAdd(500, update, sim) +let area = drawingAreaNew() +window.add area - window.showAll() +let sim = initSimulation(area, Width, Height) -#——————————————————————————————————————————————————————————————————————————————————————————————————— +discard timeoutAdd(500, cast[gtk2.TFunction](update), sim.addr) -let app = newApplication(Application, "Rosetta.polyspiral") -discard app.connect("activate", activate) -discard app.run() +window.showAll() +main() diff --git a/Task/Polyspiral/Python/polyspiral.py b/Task/Polyspiral/Python/polyspiral.py index 92356bea63..4a6efeca2d 100644 --- a/Task/Polyspiral/Python/polyspiral.py +++ b/Task/Polyspiral/Python/polyspiral.py @@ -1,5 +1,7 @@ import math +import math + import pygame from pygame.locals import * @@ -19,10 +21,10 @@ while running: running = False break - incr = (incr + 0.05) % 360 + incr = (incr + 0.0005) x1 = pygame.display.Info().current_w / 2 y1 = pygame.display.Info().current_h / 2 - length = 5 + length = 10 angle = incr screen.fill((255,255,255)) @@ -34,6 +36,6 @@ while running: # pygame.draw.aaline(screen, (255,0,0), (x1, y1), (x2, y2)) # Anti-Aliased x1, y1 = x2, y2 length += 3 - angle = (angle + incr) % 360 + angle = angle + incr pygame.display.flip() diff --git a/Task/Polyspiral/Rebol/polyspiral.rebol b/Task/Polyspiral/Rebol/polyspiral.rebol new file mode 100644 index 0000000000..7997e03fe3 --- /dev/null +++ b/Task/Polyspiral/Rebol/polyspiral.rebol @@ -0,0 +1,42 @@ +Rebol [ + title: "Rosetta code: Polyspiral" + file: %Polyspiral.r3 + url: https://rosettacode.org/wiki/Polyspiral + needs: 3.10.2 + note: [ + https://github.com/Oldes/Rebol3/releases + https://github.com/Siskin-framework/Rebol-Blend2D + ] +] +import blend2d ;; Import Blend2D extension used to draw + +incr: 0.0 ;; Initialize increment variable to 0.0 +image: make image! 800x800 ;; Create an 800x800 pixel image canvas +pi2: 2 * PI ;; Calculate 2π (full circle in radians), for angle calculations +random/seed 4 + +;; animation loop (repeats 4 times to create progressive spiral states) +loop 4 [ + x: image/size/x / 2 ;; Set x to center of image (horizontal) + y: image/size/y / 2 ;; Set y to center of image (vertical) + length: 5 ;; Starting length/step for spiral arms + incr: (incr + 5) % pi2 ;; Increment the angle step (modulo 2π to ensure it wraps correctly) + angle: incr + commands: clear [] ;; Clear previous drawing commands + color: 100.100.100 + random 155.155.155 + append commands [line-width 1 pen :color line] ;; Start a new line with width 1 and random pen color + + ;; spiral loop (generates points for the spiral) + loop 150 [ + x: x + (length * (cos angle)) ;; Move x along the current angle by current length + y: y + (length * (sin angle)) ;; Move y along the current angle by current length + append commands as-pair x y ;; Add the new (x, y) point to the command list + length: length + 5 ;; Increase the step size for spiral effect + angle: (angle + incr) % pi2 ;; Progress the angle for the spiral's curvature (modulo 2π) + ] + + draw image commands ;; Render the spiral on the image with the accumulated commands +] + +try [save %polyspiral.png image] ;; Save the image as PNG +try [view image] ;; Display the final image window with drawn spirals diff --git a/Task/Polyspiral/V-(Vlang)/polyspiral.v b/Task/Polyspiral/V-(Vlang)/polyspiral.v new file mode 100644 index 0000000000..f595680d75 --- /dev/null +++ b/Task/Polyspiral/V-(Vlang)/polyspiral.v @@ -0,0 +1,81 @@ +import gg +import gx +import math + +struct Polyspiral { + mut: + width int + height int + inc f64 +} +fn hsv_to_rgb(h f32, s f32, v f32) gx.Color { + c := v * s + h_prime := h / 60.0 + x := c * (1 - math.abs(math.fmod(f64(h_prime), 2) - 1)) + m := v - c + mut r, mut g, mut b := 0.0, 0.0, 0.0 + match int(h_prime) { + 0 { r, g, b = c, x, 0 } + 1 { r, g, b = x, c, 0 } + 2 { r, g, b = 0, c, x } + 3 { r, g, b = 0, x, c } + 4 { r, g, b = x, 0, c } + 5, 6 { r, g, b = c, 0, x } + else { r, g, b = 0, 0, 0 } + } + rrr := u8(math.min((r + m) * 255, 255)) + ggg := u8(math.min((g + m) * 255, 255)) + bbb := u8(math.min((b + m) * 255, 255)) + return gx.rgb(rrr, ggg, bbb) +} + +fn (mut poly Polyspiral) draw_spiral(mut ctx gg.Context, length f64, angle_increment f64) { + mut x1 := f64(poly.width) / 2 + mut y1 := f64(poly.height) / 2 + mut len := length + mut angle := angle_increment + for i in 0 .. 150 { + hue := f32(i) / 150 * 360 + col := hsv_to_rgb(hue, 1, 1) + x2 := x1 + math.cos(angle) * len + y2 := y1 - math.sin(angle) * len + ctx.draw_line( + f32(x1), f32(y1), + f32(x2), f32(y2), + col + ) + x1 = x2 + y1 = y2 + len += 3 + angle = math.mod(angle + angle_increment, math.pi * 2) + } +} + +fn (mut poly Polyspiral) update() { + poly.inc = math.mod(poly.inc + 0.05, 360) +} + +fn frame(mut poly Polyspiral) { + mut ctx := gg.Context{} + angle_radians := poly.inc * math.pi / 180 + ctx.begin() + poly.update() + poly.draw_spiral(mut ctx, 5, angle_radians) + ctx.end() +} + +fn main() { + mut poly := Polyspiral{ + width: 640 + height: 640 + inc: 0 + } + mut context := gg.new_context( + width: poly.width + height: poly.height + window_title: 'Polyspiral' + frame_fn: frame + user_data: &poly + ) + context.run() +} diff --git a/Task/Population-count/ABC/population-count.abc b/Task/Population-count/ABC/population-count.abc new file mode 100644 index 0000000000..9143a24f93 --- /dev/null +++ b/Task/Population-count/ABC/population-count.abc @@ -0,0 +1,25 @@ +HOW TO RETURN popcount n: + IF n=0: RETURN 0 + RETURN (n mod 2) + popcount (floor (n/2)) + +HOW TO REPORT evil n: + REPORT (popcount n) mod 2 = 0 + +HOW TO REPORT odious n: + REPORT (popcount n) mod 2 = 1 + +FOR i IN {0..29}: WRITE popcount (3 ** i) +WRITE / + +PUT {} IN evilnums +PUT {} IN odiousnums + +FOR n IN {0..59}: + SELECT: + evil n: INSERT n IN evilnums + odious n: INSERT n IN odiousnums + +FOR i IN {1..30}: WRITE evilnums item i +WRITE / +FOR i IN {1..30}: WRITE odiousnums item i +WRITE / diff --git a/Task/Population-count/ALGOL-68/population-count.alg b/Task/Population-count/ALGOL-68/population-count.alg index 23d34ccb07..f8af5f84f0 100644 --- a/Task/Population-count/ALGOL-68/population-count.alg +++ b/Task/Population-count/ALGOL-68/population-count.alg @@ -14,7 +14,7 @@ PROC population count = ( LONG INT n )INT: # population count of 3^0, 3^1, 3*2, ..., 3^29 # LONG INT power of three := 1; print( ( "3^x pop counts:" ) ); -FOR power FROM 0 TO 29 DO +FROM 0 TO 29 DO print( ( " ", whole( population count( power of three ), 0 ) ) ); power of three *:= 3 OD; diff --git a/Task/Population-count/Ada/population-count-1.ada b/Task/Population-count/Ada/population-count-1.adb similarity index 100% rename from Task/Population-count/Ada/population-count-1.ada rename to Task/Population-count/Ada/population-count-1.adb diff --git a/Task/Population-count/Ada/population-count-2.ada b/Task/Population-count/Ada/population-count-2.adb similarity index 100% rename from Task/Population-count/Ada/population-count-2.ada rename to Task/Population-count/Ada/population-count-2.adb diff --git a/Task/Population-count/Ada/population-count-3.ada b/Task/Population-count/Ada/population-count-3.adb similarity index 100% rename from Task/Population-count/Ada/population-count-3.ada rename to Task/Population-count/Ada/population-count-3.adb diff --git a/Task/Population-count/Arturo/population-count.arturo b/Task/Population-count/Arturo/population-count.arturo index 4504cc0bc2..7cb773127d 100644 --- a/Task/Population-count/Arturo/population-count.arturo +++ b/Task/Population-count/Arturo/population-count.arturo @@ -1,5 +1,5 @@ popCount: function [num][ - size select split to :string as.binary num 'x -> x="1" + size select split to :string .format:".b" num 'x -> x="1" ] print "population count for the first thirty powers of 3:" diff --git a/Task/Population-count/COBOL/population-count.cobol b/Task/Population-count/COBOL/population-count.cob similarity index 100% rename from Task/Population-count/COBOL/population-count.cobol rename to Task/Population-count/COBOL/population-count.cob diff --git a/Task/Population-count/Crystal/population-count.crystal b/Task/Population-count/Crystal/population-count.cr similarity index 100% rename from Task/Population-count/Crystal/population-count.crystal rename to Task/Population-count/Crystal/population-count.cr diff --git a/Task/Population-count/Delphi/population-count.delphi b/Task/Population-count/Delphi/population-count.pas similarity index 100% rename from Task/Population-count/Delphi/population-count.delphi rename to Task/Population-count/Delphi/population-count.pas diff --git a/Task/Population-count/EasyLang/population-count.easy b/Task/Population-count/EasyLang/population-count.easy index 5d9bfc2c3b..74545e76a2 100644 --- a/Task/Population-count/EasyLang/population-count.easy +++ b/Task/Population-count/EasyLang/population-count.easy @@ -5,7 +5,7 @@ func popcnt x . . return r . -proc show3 . . +proc show3 . write "3^n:" bb = 1 for i = 1 to 30 @@ -14,7 +14,7 @@ proc show3 . . . print "" . -proc show s$ x . . +proc show s$ x . write s$ while n < 30 if popcnt i mod 2 = x diff --git a/Task/Population-count/Elixir/population-count.elixir b/Task/Population-count/Elixir/population-count.ex similarity index 100% rename from Task/Population-count/Elixir/population-count.elixir rename to Task/Population-count/Elixir/population-count.ex diff --git a/Task/Population-count/Julia/population-count.julia b/Task/Population-count/Julia/population-count.jl similarity index 100% rename from Task/Population-count/Julia/population-count.julia rename to Task/Population-count/Julia/population-count.jl diff --git a/Task/Population-count/Kotlin/population-count.kotlin b/Task/Population-count/Kotlin/population-count.kts similarity index 100% rename from Task/Population-count/Kotlin/population-count.kotlin rename to Task/Population-count/Kotlin/population-count.kts diff --git a/Task/Population-count/Maxima/population-count.maxima b/Task/Population-count/Maxima/population-count.maxima new file mode 100644 index 0000000000..456253cd38 --- /dev/null +++ b/Task/Population-count/Maxima/population-count.maxima @@ -0,0 +1,21 @@ +popcount(n) := block( + bits: makelist(bit_onep(n, i), i, 0, bit_length(n)), + length(sublist(bits, "+")) +)$ + +makelist(popcount(3^i), i, 0, 29); + +evilp(n) := evenp(popcount(n))$ + +odiousp(n) := oddp(popcount(n))$ + +firstnums(lim, pred, name) := block( + sprint("First", lim, name, "numbers:"), + newline(), + count: 0, n: 0, while count x = '1'); + +begin + Print('pow3: '); + (0..29).Select(x -> popcount(int64(3 ** x))).Println; + Print('evil: '); + (0..99).Where(x -> popcount(x).Iseven).Take(30).Println; + Print('odious: '); + (0..99).Where(x -> popcount(x).Isodd).Take(30).Println; +end. diff --git a/Task/Population-count/Phix/population-count.phix b/Task/Population-count/Phix/population-count.phix index fe4f282cf0..2e1268acac 100644 --- a/Task/Population-count/Phix/population-count.phix +++ b/Task/Population-count/Phix/population-count.phix @@ -1,29 +1,27 @@ -(phixonline)--> - with javascript_semantics - function pop_count(atom n) - if n<0 then ?9/0 end if - integer res = 0 - while n!=0 do - res += and_bits(n,1) - n = floor(n/2) - end while - return res - end function +with javascript_semantics +function pop_count(atom n) + if n<0 then ?9/0 end if + integer res = 0 + while n!=0 do + res += and_bits(n,1) + n = floor(n/2) + end while + return res +end function - printf(1,"3^x pop_counts:%v\n",{apply(apply(true,power,{3,tagset(29,0)}),pop_count)}) +printf(1,"3^x pop_counts:%v\n",{apply(apply(true,power,{3,tagset(29,0)}),pop_count)}) - procedure eo(integer b0, string name) - sequence s = repeat(0,30) - integer k=0, l=1 - while l<=30 do - if and_bits(pop_count(k),1)=b0 then - s[l] = k - l += 1 - end if - k += 1 - end while - printf(1,"%s numbers:%v\n",{name,s}) - end procedure - eo(0," evil") - eo(1,"odious") - - requires(JS) - --requires(WINDOWS) -- (one of only, or - --requires(LINUX) -- a special combo) - requires("1.0.2") - requires(32) -- or 64 - - with javascript_semantics - constant TBL=split(""" - >= 0.00 < 0.06 := 0.10 - >= 0.06 < 0.11 := 0.18 - >= 0.11 < 0.16 := 0.26 - >= 0.16 < 0.21 := 0.32 - >= 0.21 < 0.26 := 0.38 - >= 0.26 < 0.31 := 0.44 - >= 0.31 < 0.36 := 0.50 - >= 0.36 < 0.41 := 0.54 - >= 0.41 < 0.46 := 0.58 - >= 0.46 < 0.51 := 0.62 - >= 0.51 < 0.56 := 0.66 - >= 0.56 < 0.61 := 0.70 - >= 0.61 < 0.66 := 0.74 - >= 0.66 < 0.71 := 0.78 - >= 0.71 < 0.76 := 0.82 - >= 0.76 < 0.81 := 0.86 - >= 0.81 < 0.86 := 0.90 - >= 0.86 < 0.91 := 0.94 - >= 0.91 < 0.96 := 0.98 - >= 0.96 < 1.01 := 1.00""",'\n') +with javascript_semantics +constant TBL=split(""" +>= 0.00 < 0.06 := 0.10 +>= 0.06 < 0.11 := 0.18 +>= 0.11 < 0.16 := 0.26 +>= 0.16 < 0.21 := 0.32 +>= 0.21 < 0.26 := 0.38 +>= 0.26 < 0.31 := 0.44 +>= 0.31 < 0.36 := 0.50 +>= 0.36 < 0.41 := 0.54 +>= 0.41 < 0.46 := 0.58 +>= 0.46 < 0.51 := 0.62 +>= 0.51 < 0.56 := 0.66 +>= 0.56 < 0.61 := 0.70 +>= 0.61 < 0.66 := 0.74 +>= 0.66 < 0.71 := 0.78 +>= 0.71 < 0.76 := 0.82 +>= 0.76 < 0.81 := 0.86 +>= 0.81 < 0.86 := 0.90 +>= 0.86 < 0.91 := 0.94 +>= 0.91 < 0.96 := 0.98 +>= 0.96 < 1.01 := 1.00""",'\n') - sequence limits = {0}, - prices = {-1} - atom pl,lt,plt=0,price - for i=1 to length(TBL) do - {pl,lt,price} = scanf(TBL[i],">= %.2f < %.2f := %.2f")[1] - assert(pl==plt) - plt = lt - limits = append(limits,lt) - prices = append(prices,price) - end for +sequence limits = {0}, + prices = {-1} +atom pl,lt,plt=0,price +for i=1 to length(TBL) do + {pl,lt,price} = scanf(TBL[i],">= %.2f < %.2f := %.2f")[1] + assert(pl==plt) + plt = lt + limits = append(limits,lt) + prices = append(prices,price) +end for - function price_fix(atom p) - for i=1 to length(limits) do - if p<limits[i] then - return prices[i] - end if - end for - return -1 - end function +function price_fix(atom p) + for i=1 to length(limits) do + if pfor
    i=-1 to 101 do - printf(1, "%5.2f %5.2f\n", {i/100,price_fix(i/100)}) - end for - - constant primes = get_primes_le(1e7) - sequence tetras = {{},{}}, - sevens = {0,0}, - highs = {1e5,1e6,1e7}, - highdx = apply(true,binary_search,{highs,{primes}}), - highest = extract(primes,sq_sub(sq_abs(highdx),1)) - integer hdx = 1 - for p in primes from 2 do - -- for all odd primes, both p-1 and p+1 are divisible by 2. - -- one of them will be divisible by 4 and hence not a tetraprime. - integer d = odd((p-1)/2), - dx = iff(d?-1:+1) - sequence f3 = prime_powers((p+dx)/2) - if length(f3)=3 and vslice(f3,2)={1,1,1} then - sequence f4 = prime_powers(p+2*dx) - if length(f4)=4 and vslice(f4,2)={1,1,1,1} then - tetras[2-d] &= p - if find(7,vslice(f3,1)) - or find(7,vslice(f4,1)) then - sevens[2-d] += 1 - end if - end if - end if - if p=highest[hdx] then - for t,ti in tetras do - integer c = length(ti) - printf(1,"Found %,d primes under %,d whose %sing neighboring pair are tetraprimes%s\n", - {c, highs[hdx], {"preced","follow"}[t],iff(hdx=1?":":"")}) - if hdx=1 then printf(1,"%s\n",{join_by(ti,1,10,fmt:="%5d")}) end if - printf(1,"of which %,d have a neighboring pair one of whose factors is 7.\n\n",sevens[t]) - sequence gaps = sort(sq_sub(ti[2..-1],ti[1..-2])) - printf(1,"Minimum gap between those %,d primes : %,d\n",{c,gaps[1]}) - -- printf(1,"Average gap between those %,d primes : %,d\n",{c,average(gaps)}) - printf(1,"Median gap between those %,d primes : %,d\n",{c,median(gaps)}) - printf(1,"Maximum gap between those %,d primes : %,d\n\n",{c,gaps[$]}) - end for - hdx += 1 - end if - end for - - with javascript_semantics - atom t0 = time() - sequence can_follow, arrang - bool bFirst = true +with javascript_semantics +atom t0 = time() +sequence can_follow, arrang +bool bFirst = true - function ptrs(integer res, n, done) - -- prime triangle recursive sub-procedure - -- on entry, arrang[done] is set and arrang[$]==n. - -- find something/everything that fits between them. - integer ad = arrang[done] - if n-done<=1 then - if can_follow[ad][n] then - if bFirst then - printf(1,"%s\n",join(arrang,fmt:="%d")) - bFirst = false - end if - res += 1 - end if - else - done += 1 - -- as per talk page, we only need to examine odd - -- numbers following an even number & vice versa - for i=done to n-1 by 2 do - integer ai = arrang[i] - if can_follow[ad][ai] then - integer aid = arrang[done] - arrang[i] = aid - arrang[done] = ai - res = ptrs(res,n,done) - arrang[i] = ai - arrang[done] = aid - end if - end for - end if - return res - end function +function ptrs(integer res, n, done) + -- prime triangle recursive sub-procedure + -- on entry, arrang[done] is set and arrang[$]==n. + -- find something/everything that fits between them. + integer ad = arrang[done] + if n-done<=1 then + if can_follow[ad][n] then + if bFirst then + printf(1,"%s\n",join(arrang,fmt:="%d")) + bFirst = false + end if + res += 1 + end if + else + done += 1 + -- as per talk page, we only need to examine odd + -- numbers following an even number & vice versa + for i=done to n-1 by 2 do + integer ai = arrang[i] + if can_follow[ad][ai] then + integer aid = arrang[done] + arrang[i] = aid + arrang[done] = ai + res = ptrs(res,n,done) + arrang[i] = ai + arrang[done] = aid + end if + end for + end if + return res +end function - function prime_triangle(integer n) - can_follow = repeat(repeat(false,n),n) - for i=1 to n do - for j=1 to n do - can_follow[i][j] = is_prime(i+j) - end for - end for - arrang = tagset(n) - bFirst = true - return ptrs(0,n,1) - end function +function prime_triangle(integer n) + can_follow = repeat(repeat(false,n),n) + for i=1 to n do + for j=1 to n do + can_follow[i][j] = is_prime(i+j) + end for + end for + arrang = tagset(n) + bFirst = true + return ptrs(0,n,1) +end function - sequence res = apply(tagset(20,2),prime_triangle) - printf(1,"%s\n",join(res,fmt:="%d")) - ?elapsed(time()-t0) - - with javascript_semantics - constant maxSum = 99 +with javascript_semantics +constant maxSum = 99 - function stringify(sequence s) - s = deep_copy(s) - for i=1 to length(s) do - s[i] = sprintf("%d",s[i]) - end for - return s - end function +function stringify(sequence s) + s = deep_copy(s) + for i=1 to length(s) do + s[i] = sprintf("%d",s[i]) + end for + return s +end function - procedure main() - atom t0 = time() - integer p - sequence descendants = repeat({},maxSum+1), - ancestors = repeat({},maxSum+1), - primes = get_primes_le(maxSum) +procedure main() + atom t0 = time() + integer p + sequence descendants = repeat({},maxSum+1), + ancestors = repeat({},maxSum+1), + primes = get_primes_le(maxSum) - for i=1 to length(primes) do - p = primes[i] - descendants[p] = append(descendants[p], p) - for s=1 to length(descendants)-p do - descendants[s+p] = deep_copy(descendants[s+p]) - & sq_mul(descendants[s],p) - end for - end for + for i=1 to length(primes) do + p = primes[i] + descendants[p] = append(descendants[p], p) + for s=1 to length(descendants)-p do + descendants[s+p] = deep_copy(descendants[s+p]) + & sq_mul(descendants[s],p) + end for + end for - p = 4 - for i=0 to length(primes) do - if i>0 then p = primes[i] end if - if length(descendants[p])!=0 then - descendants[p] = descendants[p][1..$-1] - end if - end for + p = 4 + for i=0 to length(primes) do + if i>0 then p = primes[i] end if + if length(descendants[p])!=0 then + descendants[p] = descendants[p][1..$-1] + end if + end for - integer total = 0 + integer total = 0 - for s=1 to maxSum do - sequence x = sort(deep_copy(descendants[s])) - total += length(x) - for i=1 to length(x) do - atom d = x[i] - if d>maxSum then exit end if - ancestors[d] = deep_copy(ancestors[d]) - &append(deep_copy(ancestors[s]),s) - end for - if s<26 or find(s,{46,74,99}) then - sequence d = ancestors[s] - integer l = length(d) - string sp = iff(l=1?" ":"s") - d = stringify(d) - printf(1,"%2d: %d Ancestor%s: [%-14s", {s, l, sp, join(d)&"]"}) - d = sort(deep_copy(descendants[s])) - l = length(d) - sp = iff(l=1?" ":"s") - if l<10 then - d = stringify(d) - else - d[4..-4] = {0} - d = stringify(d) - d[4] = "..." - end if - printf(1,"%5d Descendant%s: [%s]\n", {l, sp, join(d)}) - end if - end for - printf(1,"\nTotal descendants %d\n", total) - ?elapsed(time()-t0) -- about 1s - ?elapsed(power(3,33)/4e9) -- over 16 days - end procedure - main() - - if error_code!=NO_ERROR then - abort(0) - end if - - if error_code!=NO_ERROR then - exit_thread(0) - end if - - global function factors(atom n, integer include1=0) - -- - -- returns a list of all integer factors of n - -- if include1 is 0 (the default), result does not contain either 1 or n - -- if include1 is 1 the result contains 1 and n - -- if include1 is -1 the result contains 1 but not n - -- - if n=0 then return {} end if - check_limits(n,"factors") - sequence lfactors = {}, hfactors = {} - atom hfactor - integer p = 2, - lim = floor(sqrt(n)) +global function factors(atom n, integer include1=0) +-- +-- returns a list of all integer factors of n +-- if include1 is 0 (the default), result does not contain either 1 or n +-- if include1 is 1 the result contains 1 and n +-- if include1 is -1 the result contains 1 but not n +-- + if n=0 then return {} end if + check_limits(n,"factors") + sequence lfactors = {}, hfactors = {} + atom hfactor + integer p = 2, + lim = floor(sqrt(n)) - if include1!=0 then - lfactors = {1} - if n!=1 and include1=1 then - hfactors = {n} - end if - end if - while p<=lim do - if remainder(n,p)=0 then - lfactors = append(lfactors,p) - hfactor = n/p - if hfactor=p then exit end if - hfactors = prepend(hfactors,hfactor) - end if - p += 1 - end while - return lfactors & hfactors - end function - - for i=0 to 10 do - printf(1,"%d: %v\n",{i,factors(i,-1)}) - end for +for i=0 to 10 do + printf(1,"%d: %v\n",{i,factors(i,-1)}) +end for - sequence candidates = {} - integer maxd = 0 - for i=1 to 20000 do - integer k = length(factors(i,-1)) - if k>=maxd then - if k=maxd then - candidates &= i - else - candidates = {i} - maxd = k - end if - end if - end for - printf(1,"%d divisors: %v\n", {maxd,candidates}) - - with javascript_semantics - integer seed = 675248 - function random() - seed = remainder(floor(seed*seed/1000),1e6) - -- seed = to_integer(sprintf("%012d",seed*seed)[4..9]) - return seed - end function - for i=1 to 5 do - ?random() - end for - [ ) + + [ ]'[ 0 peek replace ] is reseed ( x --> ) + + [ [ 32 bit ] constant reduce ] is vrand ( n --> n/d ) + + [ 1234567 makerand ] maker is rand1 ( --> n ) + + 5 times [ rand1 echo cr ] + cr + 987654321 reseed rand1 + 0 5 of + 100000 times + [ rand1 vrand 5 1 v* / + 2dup peek 1+ unrot poke ] + echo 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.rs similarity index 100% rename from Task/Pseudo-random-numbers-Xorshift-star/Rust/pseudo-random-numbers-xorshift-star.rust rename to Task/Pseudo-random-numbers-Xorshift-star/Rust/pseudo-random-numbers-xorshift-star.rs diff --git a/Task/Pythagoras-tree/00-META.yaml b/Task/Pythagoras-tree/00-META.yaml index 20423f648e..0c95f28029 100644 --- a/Task/Pythagoras-tree/00-META.yaml +++ b/Task/Pythagoras-tree/00-META.yaml @@ -1,2 +1,3 @@ --- from: http://rosettacode.org/wiki/Pythagoras_tree +note: Fractals diff --git a/Task/Pythagoras-tree/ALGOL-68/pythagoras-tree.alg b/Task/Pythagoras-tree/ALGOL-68/pythagoras-tree.alg new file mode 100644 index 0000000000..24cb697aa9 --- /dev/null +++ b/Task/Pythagoras-tree/ALGOL-68/pythagoras-tree.alg @@ -0,0 +1,95 @@ +BEGIN # draw a pythagoras tree, using SVG # + + MODE POS = REAL; # MODE holding a coordinate # + + # operators for formatting # + OP BYTETOHEX = ( INT v )CHAR: + REPR IF v < 10 THEN ABS "0" + v ELSE ABS "A" + ( v - 10 ) FI; + OP TOHEX = ( INT v in )STRING: + IF v in = 0 + THEN "0" + ELSE INT v := vin; + STRING result := ""; + WHILE v > 0 DO + BYTETOHEX ( v MOD 16 ) +=: result; + v OVERAB 16 + OD; + result + FI # TOHEX # ; + OP FMT = ( INT v )STRING: whole( v, 0 ); + PRIO FMT = 9; + OP FMT = ( REAL v, INT dp )STRING: + IF v = ENTIER v OR dp = 0 + THEN whole( v, 0 ) + ELSE STRING result = fixed( v, - dp * 16, ABS dp ); + INT v pos := LWB result; + WHILE result[ v pos ] = " " DO v pos +:= 1 OD; + result[ v pos : ] + FI # FMT # ; + + # draws a polygon, points must have an even number of elements # + PROC polygon = ( []POS points, INT fill, stroke, REAL line width )VOID: + BEGIN + print( ( " ", newline ) ) + END # polygon # ; + PROC square = ( POS x1, y1, x2, y2, x3, y3, x4, y4 + , INT fill, stroke + , REAL line width + ) VOID: polygon( ( x1, y1, x2, y2, x3, y3, x4, y4 ), fill, stroke, line width ); + PROC triangle = ( POS x1, y1, x2, y2, x3, y3 + , INT fill, stroke + , REAL line width + ) VOID: polygon( ( x1, y1, x2, y2, x3, y3 ), fill, stroke, line width ); + + PROC draw pythagoras tree = ( INT height + , POS x1, y1, x2, y2 + , INT depth, max depth + , REAL line width + ) VOID: + IF depth < max depth THEN + POS dx = x2 - x1; + POS dy = y1 - y2; + POS x3 = x2 + dy; + POS y3 = y2 + dx; + POS x4 = x1 + dy; + POS y4 = y1 + dx; + POS x5 = x4 + 0.5 * ( dx + dy ); + POS y5 = y4 + 0.5 * ( dx - dy ); + INT r = 255 - ROUND ( 255 * ( 0.01 + ( depth / 10 ) ) ); + INT g = 255 - ROUND ( 255 * ( 0.01 + ( depth / 20 ) ) ); + INT b = g OVER 3; + INT fill = ( ( ( r * 256 ) + g ) * 256 ) + b; + INT stroke = ABS 16r 444444; + # inveret the y-axis, so y=0 is at the bottom # + POS i1 = height - y1, i2 = height - y2, i3 = height - y3; + POS i4 = height - y4, i5 = height - y5; + square( x1, i1, x2, i2, x3, i3, x4, i4, fill, stroke, line width ); + triangle( x3, i3, x4, i4, x5, i5, fill, stroke, line width ); + draw pythagoras tree( height, x4, y4, x5, y5, depth + 1, max depth, line width ); + draw pythagoras tree( height, x5, y5, x3, y3, depth + 1, max depth, line width ) + FI # draw pythagoras tree # ; + + PROC pythagoras tree = ( INT width, height + , POS x1, y1, x2, y2 + , INT max depth + , REAL line width + ) VOID: + BEGIN + print( ( "", newline ) ); + draw pythagoras tree( height, x1, y1, x2, y2, 0, max depth, line width ); + print( ( "", newline ) ) + END # pythagoras tree #; + + pythagoras tree( 120, 90, 51, 10, 69, 10, 10, 0.03 ) + +END diff --git a/Task/Pythagoras-tree/Ada/pythagoras-tree.ada b/Task/Pythagoras-tree/Ada/pythagoras-tree.adb similarity index 100% rename from Task/Pythagoras-tree/Ada/pythagoras-tree.ada rename to Task/Pythagoras-tree/Ada/pythagoras-tree.adb diff --git a/Task/Pythagoras-tree/AutoHotkey/pythagoras-tree.ahk b/Task/Pythagoras-tree/AutoHotkey/pythagoras-tree.ahk index 2bd00d27b4..3405d0d06b 100644 --- a/Task/Pythagoras-tree/AutoHotkey/pythagoras-tree.ahk +++ b/Task/Pythagoras-tree/AutoHotkey/pythagoras-tree.ahk @@ -28,7 +28,7 @@ Pythagoras_tree(x1, y1, x2, y2, depth){ ; draw box/triangle Gdip_FillPolygon(G, Brush%depth%, x1 "," y1 "|" x2 "," y2 "|" x3 "," y3 "|" x4 "," y4 "|" x1 "," y1) Gdip_FillPolygon(G, Brush%depth%, x4 "," y4 "|" x5 "," y5 "|" x3 "," y3 "|" x4 "," y4) - + ; draw outline Gdip_DrawLines(G, Pen, x1 "," y1 "|" x2 "," y2 "|" x3 "," y3 "|" x4 "," y4 "|" x1 "," y1) Gdip_DrawLines(G, Pen, x4 "," y4 "|" x5 "," y5 "|" x3 "," y3 "|" x4 "," y4) diff --git a/Task/Pythagoras-tree/BASIC256/pythagoras-tree.basic b/Task/Pythagoras-tree/BASIC256/pythagoras-tree.basic index 0d7df727bc..ffd7ff847f 100644 --- a/Task/Pythagoras-tree/BASIC256/pythagoras-tree.basic +++ b/Task/Pythagoras-tree/BASIC256/pythagoras-tree.basic @@ -1,17 +1,17 @@ Subroutine pythagoras_tree(x1, y1, x2, y2, depth) - If depth > 10 Then Return + If depth > 10 Then Return - dx = x2 - x1 : dy = y1 - y2 - x3 = x2 - dy : y3 = y2 - dx - x4 = x1 - dy : y4 = y1 - dx - x5 = x4 + (dx - dy) / 2 - y5 = y4 - (dx + dy) / 2 - #draw the box - Line x1, y1, x2, y2 : Line x2, y2, x3, y3 - Line x3, y3, x4, y4 : Line x4, y4, x1, y1 + dx = x2 - x1 : dy = y1 - y2 + x3 = x2 - dy : y3 = y2 - dx + x4 = x1 - dy : y4 = y1 - dx + x5 = x4 + (dx - dy) / 2 + y5 = y4 - (dx + dy) / 2 + #draw the box + Line x1, y1, x2, y2 : Line x2, y2, x3, y3 + Line x3, y3, x4, y4 : Line x4, y4, x1, y1 - Call pythagoras_tree(x4, y4, x5, y5, depth +1) - Call pythagoras_tree(x5, y5, x3, y3, depth +1) + Call pythagoras_tree(x4, y4, x5, y5, depth +1) + Call pythagoras_tree(x5, y5, x3, y3, depth +1) End Subroutine w = 800 : h = w * 11 \ 16 diff --git a/Task/Pythagoras-tree/C/pythagoras-tree.c b/Task/Pythagoras-tree/C/pythagoras-tree.c index b15fe65836..b91c67355a 100644 --- a/Task/Pythagoras-tree/C/pythagoras-tree.c +++ b/Task/Pythagoras-tree/C/pythagoras-tree.c @@ -4,64 +4,64 @@ #include typedef struct{ - double x,y; + double x,y; }point; void pythagorasTree(point a,point b,int times){ - - point c,d,e; - - c.x = b.x - (a.y - b.y); - c.y = b.y - (b.x - a.x); - - d.x = a.x - (a.y - b.y); - d.y = a.y - (b.x - a.x); - - e.x = d.x + ( b.x - a.x - (a.y - b.y) ) / 2; - e.y = d.y - ( b.x - a.x + a.y - b.y ) / 2; - - if(times>0){ - setcolor(rand()%15 + 1); - - line(a.x,a.y,b.x,b.y); - line(c.x,c.y,b.x,b.y); - line(c.x,c.y,d.x,d.y); - line(a.x,a.y,d.x,d.y); - - pythagorasTree(d,e,times-1); - pythagorasTree(e,c,times-1); - } + + point c,d,e; + + c.x = b.x - (a.y - b.y); + c.y = b.y - (b.x - a.x); + + d.x = a.x - (a.y - b.y); + d.y = a.y - (b.x - a.x); + + e.x = d.x + ( b.x - a.x - (a.y - b.y) ) / 2; + e.y = d.y - ( b.x - a.x + a.y - b.y ) / 2; + + if(times>0){ + setcolor(rand()%15 + 1); + + line(a.x,a.y,b.x,b.y); + line(c.x,c.y,b.x,b.y); + line(c.x,c.y,d.x,d.y); + line(a.x,a.y,d.x,d.y); + + pythagorasTree(d,e,times-1); + pythagorasTree(e,c,times-1); + } } int main(){ - - point a,b; - double side; - int iter; - - time_t t; - - printf("Enter initial side length : "); - scanf("%lf",&side); - - printf("Enter number of iterations : "); - scanf("%d",&iter); - - a.x = 6*side/2 - side/2; - a.y = 4*side; - b.x = 6*side/2 + side/2; - b.y = 4*side; - - initwindow(6*side,4*side,"Pythagoras Tree ?"); - - srand((unsigned)time(&t)); - - pythagorasTree(a,b,iter); - - getch(); - - closegraph(); - - return 0; + + point a,b; + double side; + int iter; + + time_t t; + + printf("Enter initial side length : "); + scanf("%lf",&side); + + printf("Enter number of iterations : "); + scanf("%d",&iter); + + a.x = 6*side/2 - side/2; + a.y = 4*side; + b.x = 6*side/2 + side/2; + b.y = 4*side; + + initwindow(6*side,4*side,"Pythagoras Tree ?"); + + srand((unsigned)time(&t)); + + pythagorasTree(a,b,iter); + + getch(); + + closegraph(); + + return 0; } diff --git a/Task/Pythagoras-tree/EasyLang/pythagoras-tree.easy b/Task/Pythagoras-tree/EasyLang/pythagoras-tree.easy index bcba9c01e1..c47195c705 100644 --- a/Task/Pythagoras-tree/EasyLang/pythagoras-tree.easy +++ b/Task/Pythagoras-tree/EasyLang/pythagoras-tree.easy @@ -1,4 +1,4 @@ -proc tree x1 y1 x2 y2 depth . . +proc tree x1 y1 x2 y2 depth . if depth < 8 dx = x2 - x1 dy = y1 - y2 @@ -8,9 +8,9 @@ proc tree x1 y1 x2 y2 depth . . y4 = y1 + dx x5 = x4 + 0.5 * (dx + dy) y5 = y4 + 0.5 * (dx - dy) - color3 0.3 0.2 + depth / 18 0.1 - polygon [ x1 y1 x2 y2 x3 y3 x4 y4 ] - polygon [ x3 y3 x4 y4 x5 y5 ] + gcolor3 0.3 0.2 + depth * 0.06 0.1 + gpolygon [ x1 y1 x2 y2 x3 y3 x4 y4 ] + gpolygon [ x3 y3 x4 y4 x5 y5 ] tree x4 y4 x5 y5 depth + 1 tree x5 y5 x3 y3 depth + 1 . diff --git a/Task/Pythagoras-tree/Go/pythagoras-tree.go b/Task/Pythagoras-tree/Go/pythagoras-tree.go index 38cb8aa59f..5fcec9ed0a 100644 --- a/Task/Pythagoras-tree/Go/pythagoras-tree.go +++ b/Task/Pythagoras-tree/Go/pythagoras-tree.go @@ -1,86 +1,86 @@ package main import ( - "image" - "image/color" - "image/draw" - "image/png" - "log" - "os" + "image" + "image/color" + "image/draw" + "image/png" + "log" + "os" ) const ( - width, height = 800, 600 - maxDepth = 11 // how far to recurse, between 1 and 20 is reasonable - colFactor = uint8(255 / maxDepth) // adjusts the colour so leaves get greener further out - fileName = "pythagorasTree.png" + width, height = 800, 600 + maxDepth = 11 // how far to recurse, between 1 and 20 is reasonable + colFactor = uint8(255 / maxDepth) // adjusts the colour so leaves get greener further out + fileName = "pythagorasTree.png" ) func main() { - img := image.NewNRGBA(image.Rect(0, 0, width, height)) // create new image - bg := image.NewUniform(color.RGBA{255, 255, 255, 255}) // prepare white for background - draw.Draw(img, img.Bounds(), bg, image.ZP, draw.Src) // fill the background + img := image.NewNRGBA(image.Rect(0, 0, width, height)) // create new image + bg := image.NewUniform(color.RGBA{255, 255, 255, 255}) // prepare white for background + draw.Draw(img, img.Bounds(), bg, image.ZP, draw.Src) // fill the background - drawSquares(340, 550, 460, 550, img, 0) // start off near the bottom of the image + drawSquares(340, 550, 460, 550, img, 0) // start off near the bottom of the image - imgFile, err := os.Create(fileName) - if err != nil { - log.Fatal(err) - } - defer imgFile.Close() - if err := png.Encode(imgFile, img); err != nil { - imgFile.Close() - log.Fatal(err) - } + imgFile, err := os.Create(fileName) + if err != nil { + log.Fatal(err) + } + defer imgFile.Close() + if err := png.Encode(imgFile, img); err != nil { + imgFile.Close() + log.Fatal(err) + } } func drawSquares(ax, ay, bx, by int, img *image.NRGBA, depth int) { - if depth > maxDepth { - return - } - dx, dy := bx-ax, ay-by - x3, y3 := bx-dy, by-dx - x4, y4 := ax-dy, ay-dx - x5, y5 := x4+(dx-dy)/2, y4-(dx+dy)/2 - col := color.RGBA{0, uint8(depth) * colFactor, 0, 255} - drawLine(ax, ay, bx, by, img, col) - drawLine(bx, by, x3, y3, img, col) - drawLine(x3, y3, x4, y4, img, col) - drawLine(x4, y4, ax, ay, img, col) - drawSquares(x4, y4, x5, y5, img, depth+1) - drawSquares(x5, y5, x3, y3, img, depth+1) + if depth > maxDepth { + return + } + dx, dy := bx-ax, ay-by + x3, y3 := bx-dy, by-dx + x4, y4 := ax-dy, ay-dx + x5, y5 := x4+(dx-dy)/2, y4-(dx+dy)/2 + col := color.RGBA{0, uint8(depth) * colFactor, 0, 255} + drawLine(ax, ay, bx, by, img, col) + drawLine(bx, by, x3, y3, img, col) + drawLine(x3, y3, x4, y4, img, col) + drawLine(x4, y4, ax, ay, img, col) + drawSquares(x4, y4, x5, y5, img, depth+1) + drawSquares(x5, y5, x3, y3, img, depth+1) } func drawLine(x0, y0, x1, y1 int, img *image.NRGBA, col color.RGBA) { - dx := abs(x1 - x0) - dy := abs(y1 - y0) - var sx, sy int = -1, -1 - if x0 < x1 { - sx = 1 - } - if y0 < y1 { - sy = 1 - } - err := dx - dy - for { - img.Set(x0, y0, col) - if x0 == x1 && y0 == y1 { - break - } - e2 := 2 * err - if e2 > -dy { - err -= dy - x0 += sx - } - if e2 < dx { - err += dx - y0 += sy - } - } + dx := abs(x1 - x0) + dy := abs(y1 - y0) + var sx, sy int = -1, -1 + if x0 < x1 { + sx = 1 + } + if y0 < y1 { + sy = 1 + } + err := dx - dy + for { + img.Set(x0, y0, col) + if x0 == x1 && y0 == y1 { + break + } + e2 := 2 * err + if e2 > -dy { + err -= dy + x0 += sx + } + if e2 < dx { + err += dx + y0 += sy + } + } } func abs(x int) int { - if x < 0 { - return -x - } - return x + if x < 0 { + return -x + } + return x } diff --git a/Task/Pythagoras-tree/JavaScript/pythagoras-tree-2.js b/Task/Pythagoras-tree/JavaScript/pythagoras-tree-2.js index d523e5bf33..c8a4836a30 100644 --- a/Task/Pythagoras-tree/JavaScript/pythagoras-tree-2.js +++ b/Task/Pythagoras-tree/JavaScript/pythagoras-tree-2.js @@ -1,14 +1,10 @@ -let base = [[{ x: -200, y: 0 }, { x: 200, y: 0 }]]; -const doc = [...Array(12)].reduce((doc_a, _, lvl) => { - const rg = step => `0${(80 + (lvl - 2) * step).toString(16)}`.slice(-2); - return doc_a + base.splice(0).reduce((ga, [a, b]) => { - const w = (kx, ky) => (kx * (b.x - a.x) + ky * (b.y - a.y)) / 2; - const [c, e, d] = [2, 3, 2].map((j, i) => ({ x: a.x + w(i, j), y: a.y + w(-j, i) })); +var base = [[[-200, 0], [200, 0]],]; +document.documentElement.innerHTML = [...Array(12)].reduce((svg_a, _, lvl) => { + const rg = step => (80 + (lvl - 2) * step) & 255; + return svg_a + base.splice(0).reduce((g_a, [a, b]) => { + const w = (k0, k1) => (k0 * (b[0] - a[0]) + k1 * (b[1] - a[1])) / 2; + const [c, e, d] = [2, 3, 2].map((j, i) => [a[0] + w(i, j), a[1] + w(-j, i)]); base.push([c, e], [e, d]); - return ga + `\n`; - }, `\n`) + '\n'; -}, '\n') + ''; - -const { x, y } = base.flat().reduce((a, p) => ({ x: Math.min(a.x, p.x), y: Math.min(a.y, p.y) })); -const svg = doc.replace('`; + }, ``) + ''; +}, '') + '', ""; diff --git a/Task/Pythagoras-tree/Jq/pythagoras-tree.jq b/Task/Pythagoras-tree/Jq/pythagoras-tree.jq index c258dc3dd9..baaeccb9ed 100644 --- a/Task/Pythagoras-tree/Jq/pythagoras-tree.jq +++ b/Task/Pythagoras-tree/Jq/pythagoras-tree.jq @@ -37,14 +37,14 @@ def PythagorasTree: else ($x2 - $x1) as $dx | ($y1 - $y2) as $dy | ($x2 - $dy) as $x3 - | ($y2 - $dx) as $y3 + | ($y2 - $dx) as $y3 | ($x1 - $dy) as $x4 | ($y1 - $dx) as $y4 - | ($x4 + 0.5 * ($dx - $dy)) as $x5 + | ($x4 + 0.5 * ($dx - $dy)) as $x5 | ($y4 - 0.5 * ($dx + $dy)) as $y5 # draw a square - | "rgb(\(256 - $depth * 20), 0, 0)" as $col + | "rgb(\(256 - $depth * 20), 0, 0)" as $col | Square([$x1, $y1]; [$x2, $y2]; [$x3, $y3] ; [$x4, $y4] ; $col; "lightgray") # draw a triangle diff --git a/Task/Pythagoras-tree/Julia/pythagoras-tree.julia b/Task/Pythagoras-tree/Julia/pythagoras-tree.jl similarity index 100% rename from Task/Pythagoras-tree/Julia/pythagoras-tree.julia rename to Task/Pythagoras-tree/Julia/pythagoras-tree.jl diff --git a/Task/Pythagoras-tree/Kotlin/pythagoras-tree.kotlin b/Task/Pythagoras-tree/Kotlin/pythagoras-tree.kts similarity index 100% rename from Task/Pythagoras-tree/Kotlin/pythagoras-tree.kotlin rename to Task/Pythagoras-tree/Kotlin/pythagoras-tree.kts diff --git a/Task/Pythagoras-tree/M2000-Interpreter/pythagoras-tree-1.m2000 b/Task/Pythagoras-tree/M2000-Interpreter/pythagoras-tree-1.m2000 index 6cd29726e4..9d4b1c402b 100644 --- a/Task/Pythagoras-tree/M2000-Interpreter/pythagoras-tree-1.m2000 +++ b/Task/Pythagoras-tree/M2000-Interpreter/pythagoras-tree-1.m2000 @@ -1,29 +1,29 @@ MODULE Pythagoras_tree { - CLS 5, 0 ' MAGENTA, NO SPLIT SCREEN - PEN 14 ' YELLOW - \\ code from zkl/Free Basic - LET w = scale.x, h = w * 11 div 16 - LET w2 = w div 2, diff = w div 12 - LET TreeOrder = 6 - pythagoras_tree(w2 - diff, h -10, w2 + diff, h -10, 0) - - SUB pythagoras_tree(x1, y1, x2, y2, depth) - - IF depth > TreeOrder THEN EXIT SUB - - LOCAL dx = x2 - x1, dy = y1 - y2 - LOCAL x3 = x2 - dy, y3 = y2 - dx - LOCAL x4 = x1 - dy, y4 = y1 - dx - LOCAL x5 = x4 + (dx - dy) / 2 - LOCAL y5 = y4 - (dx + dy) / 2 - MOVE x1, y1 - DRAW TO x2, y2 - DRAW TO x3, y3 - DRAW TO x4, y4 - DRAW TO x1, y1 - pythagoras_tree(x4, y4, x5, y5, depth +1) - pythagoras_tree(x5, y5, x3, y3, depth +1) - - END SUB + CLS 5, 0 ' MAGENTA, NO SPLIT SCREEN + PEN 14 ' YELLOW + \\ code from zkl/Free Basic + LET w = scale.x, h = w * 11 div 16 + LET w2 = w div 2, diff = w div 12 + LET TreeOrder = 6 + pythagoras_tree(w2 - diff, h -10, w2 + diff, h -10, 0) + + SUB pythagoras_tree(x1, y1, x2, y2, depth) + + IF depth > TreeOrder THEN EXIT SUB + + LOCAL dx = x2 - x1, dy = y1 - y2 + LOCAL x3 = x2 - dy, y3 = y2 - dx + LOCAL x4 = x1 - dy, y4 = y1 - dx + LOCAL x5 = x4 + (dx - dy) / 2 + LOCAL y5 = y4 - (dx + dy) / 2 + MOVE x1, y1 + DRAW TO x2, y2 + DRAW TO x3, y3 + DRAW TO x4, y4 + DRAW TO x1, y1 + pythagoras_tree(x4, y4, x5, y5, depth +1) + pythagoras_tree(x5, y5, x3, y3, depth +1) + + END SUB } Pythagoras_tree diff --git a/Task/Pythagoras-tree/M2000-Interpreter/pythagoras-tree-2.m2000 b/Task/Pythagoras-tree/M2000-Interpreter/pythagoras-tree-2.m2000 index 3f2f50f7b9..4edaf4d182 100644 --- a/Task/Pythagoras-tree/M2000-Interpreter/pythagoras-tree-2.m2000 +++ b/Task/Pythagoras-tree/M2000-Interpreter/pythagoras-tree-2.m2000 @@ -1,44 +1,44 @@ MODULE Pythagoras_Example{ - CLS 5, 0 ' MAGENTA, split line = 0 - PEN 14 ' YELLOW - \\ Linux smoothing not work (we can use the statement but without effect) - IF ISWINE ELSE SMOOTH ON - \\ PYTHAGORAS TREE - \\ by definition all variables ar type of a double - GLOBAL p=7, p4=PI/4, p2=PI/2, s2=SQRT(2)/2 - MODULE center_p (r, t){ - MODULE pythagoras_tree (r, dx, depth) { - r2=r-p2 - DRAW ANGLE r, dx - DRAW ANGLE r2, dx - DRAW ANGLE r, -dx - DRAW ANGLE r2, -dx - IF depth>10 THEN EXIT - s3=dx*s2 - depth++ - STEP ANGLE r+p4, s3*2 - CALL pythagoras_tree r-p4, s3, depth - STEP ANGLE r, -dx-s3 - STEP ANGLE r, s3 - STEP ANGLE r+p4, -s3 - CALL pythagoras_tree r+p4, s3, depth - STEP ANGLE r-p4, s3 - } - MOVE SCALE.X/2, SCALE.Y/2 - STEP ANGLE PI-p4+r, t*s2 - CALL pythagoras_tree r, t, 1 - } - r=PI/3 - pixels=100 - center_p r, 100*TWIPSX - center_p r+PI, 100*TWIPSX - CopyImageToClipboard() - - Sub CopyImageToClipboard() - LOCAL Scr$="" - MOVE 0,0 - COPY SCALE.X, SCALE.Y TO Scr$ - CLIPBOARD Scr$ - END SUB + CLS 5, 0 ' MAGENTA, split line = 0 + PEN 14 ' YELLOW + \\ Linux smoothing not work (we can use the statement but without effect) + IF ISWINE ELSE SMOOTH ON + \\ PYTHAGORAS TREE + \\ by definition all variables ar type of a double + GLOBAL p=7, p4=PI/4, p2=PI/2, s2=SQRT(2)/2 + MODULE center_p (r, t){ + MODULE pythagoras_tree (r, dx, depth) { + r2=r-p2 + DRAW ANGLE r, dx + DRAW ANGLE r2, dx + DRAW ANGLE r, -dx + DRAW ANGLE r2, -dx + IF depth>10 THEN EXIT + s3=dx*s2 + depth++ + STEP ANGLE r+p4, s3*2 + CALL pythagoras_tree r-p4, s3, depth + STEP ANGLE r, -dx-s3 + STEP ANGLE r, s3 + STEP ANGLE r+p4, -s3 + CALL pythagoras_tree r+p4, s3, depth + STEP ANGLE r-p4, s3 + } + MOVE SCALE.X/2, SCALE.Y/2 + STEP ANGLE PI-p4+r, t*s2 + CALL pythagoras_tree r, t, 1 + } + r=PI/3 + pixels=100 + center_p r, 100*TWIPSX + center_p r+PI, 100*TWIPSX + CopyImageToClipboard() + + Sub CopyImageToClipboard() + LOCAL Scr$="" + MOVE 0,0 + COPY SCALE.X, SCALE.Y TO Scr$ + CLIPBOARD Scr$ + END SUB } Pythagoras_Example diff --git a/Task/Pythagoras-tree/Maple/pythagoras-tree.maple b/Task/Pythagoras-tree/Maple/pythagoras-tree.maple new file mode 100644 index 0000000000..12c71e74bc --- /dev/null +++ b/Task/Pythagoras-tree/Maple/pythagoras-tree.maple @@ -0,0 +1,23 @@ +pythtree := proc(ax, ay, bx, By, P, colors, depth) + local dx, dy, x3, y3, x4, y4, x5, y5; + if depth <= 0 then return; end if; + dx:=bx-ax; dy:=ay-By; + x3:=bx-dy; y3:=By-dx; + x4:=ax-dy; y4:=ay-dx; + x5:=x4+(dx-dy)/2; y5:=y4-(dx+dy)/2; + + P ,= plots:-polygonplot([ax,bx,x3,x4,ax],-[ay,By,y3,y4,ay],color=colors[depth]); + P ,= plots:-polygonplot([x4,x5,x3],-[y4,y5,y3],color=colors[depth]); + + pythtree(x4, y4, x5, y5, P, colors, depth - 1); + pythtree(x5, y5, x3, y3, P, colors, depth - 1); +end proc: + +pythagorastree := proc(x1, y1, x2, y2, size, maxdep) + local P := Array(1..0); + local colors := ColorTools:-Gradient("Green".."yellow",number=maxdep): + pythtree(x1, y1, x2, y2, P, colors, maxdep); + plots:-display(convert(P,list),axes=none); +end proc: + +pythagorastree(275.,500.,375.,500.,640., 9); diff --git a/Task/Pythagoras-tree/Pluto/pythagoras-tree.pluto b/Task/Pythagoras-tree/Pluto/pythagoras-tree.pluto new file mode 100644 index 0000000000..68936c926a --- /dev/null +++ b/Task/Pythagoras-tree/Pluto/pythagoras-tree.pluto @@ -0,0 +1,37 @@ +require "bitmap" + +local bmp = bitmap.of(640, 640, color.white, "Pythagoras_tree") + +local depth_limit = 7 +local hue = 0.15 + +local function draw_tree(x1, y1, x2, y2, depth) + if depth == depth_limit then return end + local dx = x2 - x1 + local dy = y1 - y2 + + local x3 = x2 - dy + local y3 = y2 - dx + local x4 = x1 - dy + local y4 = y1 - dx + local x5 = math.round(x4 + 0.5 * (dx - dy)) + local y5 = math.round(y4 - 0.5 * (dx + dy)) + + -- Draw a square. + local col = bitmap.hsvColor((hue + depth * 0.02) * 360, 1, 1) + local v = {{x1, y1}, {x2, y2}, {x3, y3}, {x4, y4}} + bmp:polygon(v, col, 0) + bmp:polygon(v, pico.lightgray, 1) + + -- Draw a triangle. + col = bitmap.hsvColor((hue + depth * 0.035) * 360, 1, 1) + v = {{x3, y3}, {x4, y4}, {x5, y5}} + bmp:polygon(v, col, 0) + bmp:polygon(v, pico.lightgray, 1) + + draw_tree(x4, y4, x5, y5, depth + 1) + draw_tree(x5, y5, x3, y3, depth + 1) +end + +draw_tree(275, 500, 375, 500, 0) +bmp:view() diff --git a/Task/Pythagoras-tree/Raku/pythagoras-tree.raku b/Task/Pythagoras-tree/Raku/pythagoras-tree.raku index bdc4297423..7a2770e05f 100644 --- a/Task/Pythagoras-tree/Raku/pythagoras-tree.raku +++ b/Task/Pythagoras-tree/Raku/pythagoras-tree.raku @@ -2,19 +2,19 @@ class Square { has Complex ($.position, $.edge); method size { $!edge.abs } method svg-polygon { - qq[] + qq[] } method left-child { - self.new: - position => $!position + i*$!edge, - edge => sqrt(2)/2*cis(pi/4)*$!edge; + self.new: + position => $!position + i*$!edge, + edge => sqrt(2)/2*cis(pi/4)*$!edge; } method right-child { - self.new: - position => $!position + i*$!edge + self.left-child.edge, - edge => sqrt(2)/2*cis(-pi/4)*$!edge; + self.new: + position => $!position + i*$!edge + self.left-child.edge, + edge => sqrt(2)/2*cis(-pi/4)*$!edge; } } diff --git a/Task/Pythagoras-tree/Rebol/pythagoras-tree.rebol b/Task/Pythagoras-tree/Rebol/pythagoras-tree.rebol new file mode 100644 index 0000000000..eaac35a2f7 --- /dev/null +++ b/Task/Pythagoras-tree/Rebol/pythagoras-tree.rebol @@ -0,0 +1,62 @@ +Rebol [ + title: "Rosetta code: Pythagoras tree" + file: %Pythagoras_tree.r3 + url: https://rosettacode.org/wiki/Pythagoras_tree + needs: 3.16.0 +] + +b2d: import 'blend2d ;--use blend2d (draw module) +cv: attempt [import 'opencv] ;--for visualisation + +pythagoras-tree: function/with [ + size [pair!] + depth [integer!] +][ + img: make image! size + w: size/x + h: size/y + draw-tree w / 2.3 h w / 1.8 h :depth + ;; Return the generated image + img +][ + ;; pythagoras-tree function context ----------------- + img: ;; Image to draw into (closed over) + f-color: 30.20.10.30 ;; base fill color + p-color: 10.200.200 ;; base pen color + + draw-tree: function [ + x1 y1 x2 y2 + depth [integer!] + ][ + f-color/2: 20 + depth * 3 + p-color/1: 255 / depth + dx: x2 - x1 + dy: y1 - y2 + x3: x2 - dy + y3: y2 - dx + x4: x1 - dy + y4: y1 - dx + x5: x4 + (0.5 * (dx - dy)) + y5: y4 - (0.5 * (dx + dy)) + draw img reduce [ + 'fill-pen f-color + 'pen p-color + 'line-width 1 + 'polygon as-pair x1 y1 as-pair x2 y2 as-pair x3 y3 as-pair x4 y4 + 'polygon as-pair x3 y3 as-pair x4 y4 as-pair x5 y5 + ] + -- depth + if depth > 0 [ + draw-tree x4 y4 x5 y5 depth + draw-tree x5 y5 x3 y3 depth + ] + ] +] + +;; Usage example: +img: pythagoras-tree 1600x800 14 +save %pythagoras-tree.jpg img +if cv [ + cv/imshow/name :img "Pythagoras Tree" + cv/waitKey 0 +] diff --git a/Task/Pythagoras-tree/Rust/pythagoras-tree.rust b/Task/Pythagoras-tree/Rust/pythagoras-tree.rs similarity index 100% rename from Task/Pythagoras-tree/Rust/pythagoras-tree.rust rename to Task/Pythagoras-tree/Rust/pythagoras-tree.rs diff --git a/Task/Pythagoras-tree/X86-Assembly/pythagoras-tree.x86 b/Task/Pythagoras-tree/X86-Assembly/pythagoras-tree.x86 new file mode 100644 index 0000000000..86fe1fa7c2 --- /dev/null +++ b/Task/Pythagoras-tree/X86-Assembly/pythagoras-tree.x86 @@ -0,0 +1,144 @@ + 1 ;ptree.asm 24-Aug-2025 + 2 ;translation of xpl0 + 3 ;Assemble with: tasm; tlink /t + 4 + 5 0000 .model tiny + 6 0000 .code + 7 .486 + 8 org 100h + 9 ;ax=0, bx=0, cx=00FFh, dx=cs, si=0100h, di=-2, bp=09xx, sp=-2 + 10 =0140 ScrW equ 320 ;screen width and height + 11 =00C8 ScrH equ 200 + 12 0100 B0 13 start: mov al, 13h ;SetVid($13) + 13 0102 CD 10 int 10h + 14 + 15 0104 68 A000 push 0A000h ;es:= video memory segment + 16 0107 07 pop es + 17 + 18 ;DrawTree(9*ScrW/20, 3*ScrH/4, 11*ScrW/20, 3*ScrH/4, 0) + 19 0108 68 9690 push 9*ScrW/20 + (3*ScrH/4)*100h + 20 010B 68 96B0 push 11*ScrW/20 + (3*ScrH/4)*100h + 21 010E 6A 2A push 0 + 2Ah ;Depth:= 0 + 2Ah (Color) + 22 0110 E8 000A call DrawTree + 23 + 24 0113 33 C0 xor ax, ax ;wait for keystroke + 25 0115 CD 16 int 16h + 26 0117 B8 0003 mov ax, 0003h ;restore text mode + 27 011A CD 10 int 10h + 28 011C C3 ret + 29 + 30 ;------------------------------------------------------------ + 31 ;DrawTree(X1,Y1, X2,Y2, Depth) + 32 ; + 33 ;Offsets relative to bp: + 34 =0008 P1 equ 8 ;equ X1,Y1 + 35 =0006 P2 equ 6 ;equ X2,Y2 + 36 =0004 Depth equ 4 + 37 ; ret equ 2 + 38 ; bp equ 0 + 39 =-0002 P3 equ -2 ;equ X3,Y3 + 40 =-0004 P4 equ -4 ;equ X4,Y4 + 41 =-0006 P5 equ -6 ;equ X5,Y5 + 42 + 43 011D DrawTree: + 44 011D C8 0006 00 enter 3*2, 0 ;set up stack frame for P3, P4, P5 + 45 + 46 0121 83 7E 0 cmp word ptr [bp+Depth], 7 + 2Ah + 47 0125 7D 62 jge dt90 ;limit depth of recursion + 48 + 49 0127 8B 5E 0 mov bx, [bp+P1] ;Move(X1, Y1) + 50 012A 8B 46 06 mov ax, [bp+P2] + 51 + 52 012D 8A D0 mov dl, al ;DX:= X2 - X1; + 53 012F 2A D3 sub dl, bl ;(DX # dx) + 54 0131 8A F7 mov dh, bh ;DY:= Y1 - Y2 + 55 0133 2A F4 sub dh, ah + 56 + 57 0135 2A C6 sub al, dh ;X3:= X2 - DY + 58 0137 2A E2 sub ah, dl ;Y3:= Y2 - DX + 59 0139 89 46 FE mov [bp+P3], ax + 60 + 61 013C 8B C3 mov ax, bx + 62 013E 2A C6 sub al, dh ;X4:= X1 - DY + 63 0140 2A E2 sub ah, dl ;Y4:= Y1 - DX + 64 0142 89 46 FC mov [bp+P4], ax + 65 + 66 0145 52 push dx + 67 0146 2A D6 sub dl, dh ;(DX-DY)/2 + 68 0148 D0 FA sar dl, 1 + 69 014A 02 C2 add al, dl ;X5:= X4 + (DX-DY)/2 + 70 014C 5A pop dx + 71 + 72 014D 02 D6 add dl, dh ;(DX+DY)/2 + 73 014F D0 FA sar dl, 1 + 74 0151 2A E2 sub ah, dl ;Y5:= Y4 - (DX+DY)/2 + 75 0153 89 46 FA mov [bp+P5], ax + 76 + 77 0156 8B 46 0 mov ax, [bp+P2] ;Line(X2, Y2, Color) + 78 0159 E8 0031 call DrawLine + 79 015C 8B 46 FE mov ax, [bp+P3] ;Line(X3, Y3, Color) + 80 015F E8 002B call DrawLine + 81 0162 8B 46 FC mov ax, [bp+P4] ;Line(X4, Y4, Color) + 82 0165 E8 0025 call DrawLine + 83 0168 8B 46 08 mov ax, [bp+P1] ;Line(X1, Y1, Color) + 84 016B E8 001F call DrawLine + 85 + 86 016E FF 76 F push word ptr [bp+P4] ;DrawTree(X4, Y4, X5, Y5, Depth+1) + 87 0171 FF 76 FA push word ptr [bp+P5] + 88 0174 FF 46 04 inc word ptr [bp+Depth] + 89 0177 FF 76 04 push word ptr [bp+Depth] + 90 017A E8 FFA0 call DrawTree + 91 + 92 017D FF 76 F push word ptr [bp+P5] ;DrawTree(X5, Y5, X3, Y3, Depth+1) + 93 0180 FF 76 FE push word ptr [bp+P3] + 94 0183 FF 76 04 push word ptr [bp+Depth] + 95 0186 E8 FF94 call DrawTree + 96 0189 dt90: + 97 0189 C9 leave ;release local variable stack frame + 98 018A C2 0006 ret 3*2 ;drop 3 args + 99 +100 ;------------------------------------------------------------ +101 ;Draw horizontal, vertical or diagonal line from X0,Y0 to X,Y +102 ; Line(X, Y, Color) +103 ; al=X; ah=Y; Color= 2Ah+[bp+Depth] +104 ; bl=X0; bh=Y0; di=Y0*ScrW+X0 +105 ; +106 018D DrawLine: +107 018D 50 push ax ;save end of line X,Y +108 +109 018E 33 F6 xor si, si ;Step:= 0 +110 0190 2A E7 sub ah, bh ;DY:= Y - Y0 +111 0192 74 09 je dl10 ;if DY # 0 then +112 0194 BE 0140 mov si, ScrW ; Step:= ScrW +113 0197 77 04 ja dl10 ; if DY < 0 then +114 0199 F7 DE neg si ; Step:= -ScrW +115 019B F6 DC neg ah ; abs(DY) +116 019D 2A C3 dl10: sub al, bl ;DX:= X - X0 +117 019F 74 07 je dl20 ;if DX # 0 then +118 01A1 77 04 ja dl15 ; if DX < 0 then +119 01A3 4E dec si ; Step-- +120 01A4 F6 D8 neg al ; abs(DX) +121 01A6 3C db 3Ch ; cmp al, imm; skips one byte +122 01A7 46 dl15: inc si ; else Step++ +123 01A8 dl20: +124 01A8 0F B6 FF movzx di, bh ;di:= Y1*ScrW + X1 +125 01AB 69 FF 0140 imul di, ScrW +126 01AF 0F B6 DB movzx bx, bl +127 01B2 03 FB add di, bx +128 +129 01B4 5B pop bx ;X0:= X; Y0:= Y; = new end of line +130 +131 01B5 8A CC mov cl, ah ;cl:= Max(DY,DX) +132 01B7 3A E0 cmp ah, al +133 01B9 73 02 jae dl70 +134 01BB 8A C8 mov cl, al +135 01BD dl70: +136 01BD 8A 46 04 mov al, [bp+Depth] ;Color:= $2A + Depth +137 01C0 AA dl80: stosb ;es:[di++]:= al +138 01C1 4F dec di ;undo di++ +139 01C2 03 FE add di, si ;+ Step +140 01C4 E2 FA loop dl80 ;cx-- +141 01C6 AA stosb ;draw end point +142 01C7 dl90: +143 01C7 C3 ret +144 end start diff --git a/Task/Pythagorean-quadruples/Crystal/pythagorean-quadruples-1.crystal b/Task/Pythagorean-quadruples/Crystal/pythagorean-quadruples-1.cr similarity index 100% rename from Task/Pythagorean-quadruples/Crystal/pythagorean-quadruples-1.crystal rename to Task/Pythagorean-quadruples/Crystal/pythagorean-quadruples-1.cr diff --git a/Task/Pythagorean-quadruples/Crystal/pythagorean-quadruples-2.crystal b/Task/Pythagorean-quadruples/Crystal/pythagorean-quadruples-2.cr similarity index 100% rename from Task/Pythagorean-quadruples/Crystal/pythagorean-quadruples-2.crystal rename to Task/Pythagorean-quadruples/Crystal/pythagorean-quadruples-2.cr diff --git a/Task/Pythagorean-quadruples/EasyLang/pythagorean-quadruples.easy b/Task/Pythagorean-quadruples/EasyLang/pythagorean-quadruples.easy new file mode 100644 index 0000000000..11924ea6f1 --- /dev/null +++ b/Task/Pythagorean-quadruples/EasyLang/pythagorean-quadruples.easy @@ -0,0 +1,28 @@ +n = 2200 +n2 = n * n * 2 +len r[] n +len ab[] n2 +for a = 1 to n + a2 = a * a + for b = a to n + ab[a2 + b * b] = 1 + . +. +s = 3 +for c = 1 to n + s1 = s + s += 2 + s2 = s + for d = c + 1 to n + if ab[s1] = 1 + r[d] = 1 + . + s1 += s2 + s2 += 2 + . +. +for i to n + if r[i] = 0 + write i & " " + . +. diff --git a/Task/Pythagorean-quadruples/Julia/pythagorean-quadruples.julia b/Task/Pythagorean-quadruples/Julia/pythagorean-quadruples.jl similarity index 100% rename from Task/Pythagorean-quadruples/Julia/pythagorean-quadruples.julia rename to Task/Pythagorean-quadruples/Julia/pythagorean-quadruples.jl diff --git a/Task/Pythagorean-quadruples/Kotlin/pythagorean-quadruples-1.kotlin b/Task/Pythagorean-quadruples/Kotlin/pythagorean-quadruples-1.kts similarity index 100% rename from Task/Pythagorean-quadruples/Kotlin/pythagorean-quadruples-1.kotlin rename to Task/Pythagorean-quadruples/Kotlin/pythagorean-quadruples-1.kts diff --git a/Task/Pythagorean-quadruples/Kotlin/pythagorean-quadruples-2.kotlin b/Task/Pythagorean-quadruples/Kotlin/pythagorean-quadruples-2.kts similarity index 100% rename from Task/Pythagorean-quadruples/Kotlin/pythagorean-quadruples-2.kotlin rename to Task/Pythagorean-quadruples/Kotlin/pythagorean-quadruples-2.kts diff --git a/Task/Pythagorean-quadruples/Rust/pythagorean-quadruples.rust b/Task/Pythagorean-quadruples/Rust/pythagorean-quadruples.rs similarity index 100% rename from Task/Pythagorean-quadruples/Rust/pythagorean-quadruples.rust rename to Task/Pythagorean-quadruples/Rust/pythagorean-quadruples.rs diff --git a/Task/Pythagorean-triples/Ada/pythagorean-triples.ada b/Task/Pythagorean-triples/Ada/pythagorean-triples.adb similarity index 100% rename from Task/Pythagorean-triples/Ada/pythagorean-triples.ada rename to Task/Pythagorean-triples/Ada/pythagorean-triples.adb diff --git a/Task/Pythagorean-triples/Arturo/pythagorean-triples.arturo b/Task/Pythagorean-triples/Arturo/pythagorean-triples.arturo index cd5346753b..72183d24a1 100644 --- a/Task/Pythagorean-triples/Arturo/pythagorean-triples.arturo +++ b/Task/Pythagorean-triples/Arturo/pythagorean-triples.arturo @@ -1,4 +1,4 @@ -triples: new [] +triples: [] loop 1..50 'x [ loop 1..50 'y [ loop (max @[x y])..100 'z [ @@ -14,7 +14,7 @@ unique 'triples print ["Found" size triples "pythagorean triples with a perimeter no larger than 100:"] print triples -primitive: select triples => [1 = gcd] +primitive: select triples => [1 = gcd &] print "" print [size primitive "of them are primitive:"] diff --git a/Task/Pythagorean-triples/BASIC256/pythagorean-triples.basic b/Task/Pythagorean-triples/BASIC256/pythagorean-triples.basic new file mode 100644 index 0000000000..8788eb90bf --- /dev/null +++ b/Task/Pythagorean-triples/BASIC256/pythagorean-triples.basic @@ -0,0 +1,49 @@ +global limite, terna, prim + +t1 = msec +print "below ternas primitivas tiempo" +for x = 1 to 7 + limite = 10 ^ x + terna = 0 + prim = 0 + + call terna_pit_fast(limite, terna, prim) + + print " 10^"; x; " "; ljust(string(terna), 14); ljust(string(prim), 14) +next x + +print +print "Tiempo total necesario: "; (msec - t1)/1000; " seg." +end + +function gcd(x, y) + while y <> 0 + t = y + y = x mod y + x = t + end while + return x +end function + +subroutine terna_pit_fast(limite, terna, prim) + for m = 2 to int(sqrt(limite / 2)) + for n = 1 to m - 1 + # m y n deben ser coprimos y no ambos impares + if (gcd(m, n) = 1) and not ((m mod 2 = 1) and (n mod 2 = 1)) then + a = m * m - n * n + b = 2 * m * n + c = m * m + n * n + p = a + b + c + + if p > limite then exit for + + prim += 1 + x = p + while x <= limite + terna += 1 + x = x + p + end while + end if + next n + next m +end subroutine diff --git a/Task/Pythagorean-triples/Crystal/pythagorean-triples.crystal b/Task/Pythagorean-triples/Crystal/pythagorean-triples.cr similarity index 100% rename from Task/Pythagorean-triples/Crystal/pythagorean-triples.crystal rename to Task/Pythagorean-triples/Crystal/pythagorean-triples.cr diff --git a/Task/Pythagorean-triples/D/pythagorean-triples-1.d b/Task/Pythagorean-triples/D/pythagorean-triples-1.d index 38f73bbc30..3671e42f24 100644 --- a/Task/Pythagorean-triples/D/pythagorean-triples-1.d +++ b/Task/Pythagorean-triples/D/pythagorean-triples-1.d @@ -10,6 +10,6 @@ void main() @safe { .map!(t => tuple(t[0 .. 2].gcd == 1, t[])); auto xs = triples(100); - writeln("Up to 100 there are ", xs.count, " triples, ", - xs.filter!q{ a[0] }.count, " are primitive."); + writefln("\nUp to %d there are %d triples, %d are primitive.", N, xs.count, + xs.filter!q{ a[0] }.count); } diff --git a/Task/Pythagorean-triples/EasyLang/pythagorean-triples.easy b/Task/Pythagorean-triples/EasyLang/pythagorean-triples.easy index 1d8b36eaeb..43c100b419 100644 --- a/Task/Pythagorean-triples/EasyLang/pythagorean-triples.easy +++ b/Task/Pythagorean-triples/EasyLang/pythagorean-triples.easy @@ -1,12 +1,17 @@ global total prim maxperi . -proc newtri s0 s1 s2 . . - p = s0 + s1 + s2 - if p <= maxperi +fastproc newtri s0 s1 s2 . + while 1 = 1 + p = s0 + s1 + s2 + if p > maxperi : return 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 + 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 + h0 = -s0 + 2 * s1 + 2 * s2 + h1 = -2 * s0 + s1 + 2 * s2 + s2 = -2 * s0 + 2 * s1 + 3 * s2 + s0 = h0 + s1 = h1 . . for maxperi in [ 100 10000000 ] diff --git a/Task/Pythagorean-triples/Elixir/pythagorean-triples.elixir b/Task/Pythagorean-triples/Elixir/pythagorean-triples.ex similarity index 100% rename from Task/Pythagorean-triples/Elixir/pythagorean-triples.elixir rename to Task/Pythagorean-triples/Elixir/pythagorean-triples.ex diff --git a/Task/Pythagorean-triples/Euphoria/pythagorean-triples.euphoria b/Task/Pythagorean-triples/Euphoria/pythagorean-triples.eu similarity index 100% rename from Task/Pythagorean-triples/Euphoria/pythagorean-triples.euphoria rename to Task/Pythagorean-triples/Euphoria/pythagorean-triples.eu diff --git a/Task/Pythagorean-triples/FutureBasic/pythagorean-triples.basic b/Task/Pythagorean-triples/FutureBasic/pythagorean-triples.basic new file mode 100644 index 0000000000..62b6e34b5c --- /dev/null +++ b/Task/Pythagorean-triples/FutureBasic/pythagorean-triples.basic @@ -0,0 +1,37 @@ +include "NSLog.incl" + +begin globals + long total = 0 + long prim = 0 + long maxPeri = 0 +end globals + +void local fn newTri( s0 as long, s1 as long, s2 as long ) + long p = s0 + s1 + s2 + if ( p <= maxPeri ) + prim++ + total += maxPeri / p + fn newTri( s0 - 2 * s1 + 2 * s2, 2 * s0 - s1 + 2 * s2, 2 * s0 - 2 * s1 + 3 * s2 ) + fn newTri( s0 + 2 * s1 + 2 * s2, 2 * s0 + s1 + 2 * s2, 2 * s0 + 2 * s1 + 3 * s2 ) + fn newTri( -s0 + 2 * s1 + 2 * s2, -2 * s0 + s1 + 2 * s2, -2 * s0 + 2 * s1 + 3 * s2 ) + end if +end fn + +void local fn DoIt + int i = 2 + maxPeri = 100 + while ( maxPeri <= 10000000000 ) + prim = 0 + total = 0 + fn newTri( 3, 4, 5 ) + NSLog( @"M^%2d %12ld %12ld %-11ld", i, maxPeri, total, prim ) : i++ + maxPeri *= 10 + wend +end fn + +NSLog( @"below triples primitive" ) +CFTimeInterval t : t = fn CACurrentMediaTime +fn DoIt +NsLog( @"\nCompute time: %.3f ms", (fn CACurrentMediaTime-t)*1000 ) + +HandleEvents diff --git a/Task/Pythagorean-triples/Julia/pythagorean-triples.julia b/Task/Pythagorean-triples/Julia/pythagorean-triples.jl similarity index 100% rename from Task/Pythagorean-triples/Julia/pythagorean-triples.julia rename to Task/Pythagorean-triples/Julia/pythagorean-triples.jl diff --git a/Task/Pythagorean-triples/Kotlin/pythagorean-triples.kotlin b/Task/Pythagorean-triples/Kotlin/pythagorean-triples.kts similarity index 100% rename from Task/Pythagorean-triples/Kotlin/pythagorean-triples.kotlin rename to Task/Pythagorean-triples/Kotlin/pythagorean-triples.kts diff --git a/Task/Pythagorean-triples/OCaml/pythagorean-triples.ocaml b/Task/Pythagorean-triples/OCaml/pythagorean-triples.ml similarity index 100% rename from Task/Pythagorean-triples/OCaml/pythagorean-triples.ocaml rename to Task/Pythagorean-triples/OCaml/pythagorean-triples.ml diff --git a/Task/Pythagorean-triples/Phix/pythagorean-triples.phix b/Task/Pythagorean-triples/Phix/pythagorean-triples.phix index b240c32347..e411e6a03f 100644 --- a/Task/Pythagorean-triples/Phix/pythagorean-triples.phix +++ b/Task/Pythagorean-triples/Phix/pythagorean-triples.phix @@ -1,23 +1,44 @@ -(phixonline)--> - with javascript_semantics - atom total, prim, maxPeri = 10 +with javascript_semantics +function count_triplets(atom max_perimeter) + integer limit = floor(sqrt(max_perimeter/2))+1 + atom total = 0, primitive = 0, t0 = time(), t1 = t0+1 + // The formulas below generate primitive triples if: + // 0 < n < m + // m and n are relatively prime (gcd == 1) + // m + n is odd + for m=2 to limit do + for n=1+odd(m) to m-1 by 2 do +-- if gcd(m,n)=1 then + -- inlined for a 5-fold speedup: + integer u = m, v = n, t + do + t = u + u = v + v = rmdr(t,v) + until v=0 + if u=1 then + -- a = m*m - n*n + -- b = 2*m*n + -- c = m*m + n*n + -- perimeter = a + b + c + atom perimeter = 2*m*(m+n) + if perimeter <= max_perimeter then + primitive += 1 + total += floor(max_perimeter/perimeter) + end if + end if + end for + if time()>t1 then + progress("m:%d/%d (%d%%)\r",{m,limit,m/limit*100}) + t1 = time()+1 + end if + end for + string e = elapsed_short(time()-t0,1," (%s)") + return {max_perimeter, total, primitive, e} +end function - procedure tri(atom s0, s1, s2) - atom p = s0 + s1 + s2 - if p<=maxPeri then - prim += 1 - total += floor(maxPeri/p) - tri( s0+2*(-s1+s2), 2*( s0+s2)-s1, 2*( s0-s1+s2)+s2); - tri( s0+2*( s1+s2), 2*( s0+s2)+s1, 2*( s0+s1+s2)+s2); - tri(-s0+2*( s1+s2), 2*(-s0+s2)+s1, 2*(-s0+s1+s2)+s2); - end if - end procedure - - while maxPeri<=1e8 do - prim := 0; - total := 0; - tri(3, 4, 5); - printf(1,"Up to %d: %d triples, %d primitives.\n", {maxPeri,total,prim}) - maxPeri *= 10; - end while -Quaternion[1,2,3,4] -->Quaternion[2,3,4,5] -->Quaternion[3,4,5,6] -->7 - -Abs[q] -->√30 --q -->Quaternion[-1,-2,-3,-4] -Conjugate[q] -->Quaternion[1,-2,-3,-4] -r+q -->Quaternion[8,2,3,4] -q+r -->Quaternion[8,2,3,4] -q1+q2 -->Quaternion[5,7,9,11] -q*r -->Quaternion[7,14,21,28] -r*q -->Quaternion[7,14,21,28] -q1**q2 -->Quaternion[-56,16,24,26] -q2**q1 -->Quaternion[-56,18,20,28] diff --git a/Task/Quaternion-type/Mercury/quaternion-type-1.mercury b/Task/Quaternion-type/Mercury/quaternion-type-1.mercury deleted file mode 100644 index 1825a13f23..0000000000 --- a/Task/Quaternion-type/Mercury/quaternion-type-1.mercury +++ /dev/null @@ -1,38 +0,0 @@ -:- module quaternion. - -:- interface. - -:- import_module float. - -:- type quaternion - ---> q( w :: float, - i :: float, - j :: float, - k :: float ). - -% conversion -:- func r(float) = quaternion is det. - -% operations -:- func norm(quaternion) = float is det. -:- func -quaternion = quaternion is det. -:- func conjugate(quaternion) = quaternion is det. -:- func quaternion + quaternion = quaternion is det. -:- func quaternion * quaternion = quaternion is det. - -:- implementation. - -:- import_module math. - -% conversion -r(W) = q(W, 0.0, 0.0, 0.0). - -% operations -norm(q(W, I, J, K)) = math.sqrt(W*W + I*I + J*J + K*K). --q(W, I, J, K) = q(-W, -I, -J, -K). -conjugate(q(W, I, J, K)) = q(W, -I, -J, -K). -q(W0, I0, J0, K0) + q(W1, I1, J1, K1) = q(W0+W1, I0+I1, J0+J1, K0+K1). -q(W0, I0, J0, K0) * q(W1, I1, J1, K1) = q(W0*W1 - I0*I1 - J0*J1 - K0*K1, - W0*I1 + I0*W1 + J0*K1 - K0*J1, - W0*J1 - I0*K1 + J0*W1 + K0*I1, - W0*K1 + I0*J1 - J0*I1 + K0*W1 ). diff --git a/Task/Quaternion-type/Mercury/quaternion-type-2.mercury b/Task/Quaternion-type/Mercury/quaternion-type-2.mercury deleted file mode 100644 index de29885af2..0000000000 --- a/Task/Quaternion-type/Mercury/quaternion-type-2.mercury +++ /dev/null @@ -1,76 +0,0 @@ -:- module test_quaternion. - -:- interface. - -:- import_module io. - -:- pred main(io::di, io::uo) is det. - -:- implementation. - -:- import_module quaternion. - -:- import_module exception. -:- import_module float. -:- import_module list. -:- import_module string. - -:- func to_string(quaternion) = string is det. - -main(!IO) :- - Q = q(1.0, 2.0, 3.0, 4.0), - Q1 = q(2.0, 3.0, 4.0, 5.0), - Q2 = q(3.0, 4.0, 5.0, 6.0), - R = 7.0, - QR = r(R), - - io.print("Q = ", !IO), io.print(to_string(Q), !IO), io.nl(!IO), - io.print("Q1 = ", !IO), io.print(to_string(Q1), !IO), io.nl(!IO), - io.print("Q2 = ", !IO), io.print(to_string(Q2), !IO), io.nl(!IO), - io.print("R = ", !IO), io.print(R, !IO), io.nl(!IO), - io.nl(!IO), - - io.print("1. The norm of a quaternion.\n", !IO), - io.print("norm(Q) = ", !IO), io.print(norm(Q), !IO), io.nl(!IO), - io.nl(!IO), - - io.print("2. The negative of a quaternion.\n", !IO), - io.print("-Q = ", !IO), io.print(to_string(-Q), !IO), io.nl(!IO), - io.nl(!IO), - - io.print("3. The conjugate of a quaternion.\n", !IO), - io.print("conjugate(Q) = ", !IO), io.print(to_string(conjugate(Q)), !IO), - io.nl(!IO), - io.nl(!IO), - - io.print("4. Addition of a real number and a quaternion.\n", !IO), - ( Q + QR = QR + Q -> io.print("Addition is commutative.\n", !IO) - ; io.print("Addition is not commutative.\n", !IO) ), - io.print("Q + R = ", !IO), io.print(to_string(Q + QR), !IO), io.nl(!IO), - io.print("R + Q = ", !IO), io.print(to_string(QR + Q), !IO), io.nl(!IO), - io.nl(!IO), - - io.print("5. Addition of two quaternions.\n", !IO), - ( Q1 + Q2 = Q2 + Q1 -> io.print("Addition is commutative.\n", !IO) - ; io.print("Addition is not commutative.\n", !IO) ), - io.print("Q1 + Q2 = ", !IO), io.print(to_string(Q1 + Q2), !IO), io.nl(!IO), - io.print("Q2 + Q1 = ", !IO), io.print(to_string(Q2 + Q1), !IO), io.nl(!IO), - io.nl(!IO), - - io.print("6. Multiplication of a real number and a quaternion.\n", !IO), - ( Q * QR = QR * Q -> io.print("Multiplication is commutative.\n", !IO) - ; io.print("Multiplication is not commutative.\n", !IO) ), - io.print("Q * R = ", !IO), io.print(to_string(Q * QR), !IO), io.nl(!IO), - io.print("R * Q = ", !IO), io.print(to_string(QR * Q), !IO), io.nl(!IO), - io.nl(!IO), - - io.print("7. Multiplication of two quaternions.\n", !IO), - ( Q1 * Q2 = Q2 * Q1 -> io.print("Multiplication is commutative.\n", !IO) - ; io.print("Multiplication is not commutative.\n", !IO) ), - io.print("Q1 * Q2 = ", !IO), io.print(to_string(Q1 * Q2), !IO), io.nl(!IO), - io.print("Q2 * Q1 = ", !IO), io.print(to_string(Q2 * Q1), !IO), io.nl(!IO), - io.nl(!IO). - -to_string(q(I, J, K, W)) = string.format("q(%f, %f, %f, %f)", - [f(I), f(J), f(K), f(W)]). -:- end_module test_quaternion. diff --git a/Task/Quaternion-type/Nim/quaternion-type.nim b/Task/Quaternion-type/Nim/quaternion-type.nim deleted file mode 100644 index 6356d48cd3..0000000000 --- a/Task/Quaternion-type/Nim/quaternion-type.nim +++ /dev/null @@ -1,72 +0,0 @@ -import math, tables - -type Quaternion* = object - a, b, c, d: float - -func initQuaternion*(a, b, c, d = 0.0): Quaternion = - Quaternion(a: a, b: b, c: c, d: d) - -func `-`*(q: Quaternion): Quaternion = - initQuaternion(-q.a, -q.b, -q.c, -q.d) - -func `+`*(q: Quaternion; r: float): Quaternion = - initQuaternion(q.a + r, q.b, q.c, q.d) - -func `+`*(r: float; q: Quaternion): Quaternion = - initQuaternion(q.a + r, q.b, q.c, q.d) - -func `+`*(q1, q2: Quaternion): Quaternion = - initQuaternion(q1.a + q2.a, q1.b + q2.b, q1.c + q2.c, q1.d + q2.d) - -func `*`*(q: Quaternion; r: float): Quaternion = - initQuaternion(q.a * r, q.b * r, q.c * r, q.d * r) - -func `*`*(r: float; q: Quaternion): Quaternion = - initQuaternion(q.a * r, q.b * r, q.c * r, q.d * r) - -func `*`*(q1, q2: Quaternion): Quaternion = - initQuaternion(q1.a * q2.a - q1.b * q2.b - q1.c * q2.c - q1.d * q2.d, - q1.a * q2.b + q1.b * q2.a + q1.c * q2.d - q1.d * q2.c, - q1.a * q2.c - q1.b * q2.d + q1.c * q2.a + q1.d * q2.b, - q1.a * q2.d + q1.b * q2.c - q1.c * q2.b + q1.d * q2.a) - -func conjugate*(q: Quaternion): Quaternion = - initQuaternion(q.a, -q.b, -q.c, -q.d) - -func norm*(q: Quaternion): float = - sqrt(q.a * q.a + q.b * q.b + q.c * q.c + q.d * q.d) - -func `==`*(q: Quaternion; r: float): bool = - if q.b != 0 or q.c != 0 or q.d != 0: false - else: q.a == r - -func `$`(q: Quaternion): string = - ## Return the representation of a quaternion. - const Letter = {"a": "", "b": "i", "c": "j", "d": "k"}.toTable - if q == 0: return "0" - for name, value in q.fieldPairs: - if value != 0: - var val = value - if result.len != 0: - result.add if value >= 0: '+' else: '-' - val = abs(val) - result.add $val & Letter[name] - - -when isMainModule: - let - q = initQuaternion(1, 2, 3, 4) - q1 = initQuaternion(2, 3, 4, 5) - q2 = initQuaternion(3, 4, 5, 6) - r = 7.0 - - echo "∥q∥ = ", norm(q) - echo "-q = ", -q - echo "q* = ", conjugate(q) - echo "q + r = ", q + r - echo "r + q = ", r + q - echo "q1 + q2 = ", q1 + q2 - echo "qr = ", q * r - echo "rq = ", r * q - echo "q1 * q2 = ", q1 * q2 - echo "q2 * q1 = ", q2 * q1 diff --git a/Task/Quaternion-type/OCaml/quaternion-type-1.ocaml b/Task/Quaternion-type/OCaml/quaternion-type-1.ocaml deleted file mode 100644 index 8c2c790e70..0000000000 --- a/Task/Quaternion-type/OCaml/quaternion-type-1.ocaml +++ /dev/null @@ -1,64 +0,0 @@ -type quaternion = {a: float; b: float; c: float; d: float} - -let norm q = sqrt (q.a**2.0 +. - q.b**2.0 +. - q.c**2.0 +. - q.d**2.0 ) - -let floatneg r = ~-. r (* readability *) - -let negative q = - {a = floatneg q.a; - b = floatneg q.b; - c = floatneg q.c; - d = floatneg q.d } - -let conjugate q = - {a = q.a; - b = floatneg q.b; - c = floatneg q.c; - d = floatneg q.d } - -let addrq r q = {q with a = q.a +. r} - -let addq q1 q2 = - {a = q1.a +. q2.a; - b = q1.b +. q2.b; - c = q1.c +. q2.c; - d = q1.d +. q2.d } - -let multrq r q = - {a = q.a *. r; - b = q.b *. r; - c = q.c *. r; - d = q.d *. r } - -let multq q1 q2 = - {a = q1.a*.q2.a -. q1.b*.q2.b -. q1.c*.q2.c -. q1.d*.q2.d; - b = q1.a*.q2.b +. q1.b*.q2.a +. q1.c*.q2.d -. q1.d*.q2.c; - c = q1.a*.q2.c -. q1.b*.q2.d +. q1.c*.q2.a +. q1.d*.q2.b; - d = q1.a*.q2.d +. q1.b*.q2.c -. q1.c*.q2.b +. q1.d*.q2.a } - -let qmake a b c d = {a;b;c;d} (* readability omitting a= b=... *) - -let qstring q = - Printf.sprintf "(%g, %g, %g, %g)" q.a q.b q.c q.d ;; - -(* test data *) -let q = qmake 1.0 2.0 3.0 4.0 -let q1 = qmake 2.0 3.0 4.0 5.0 -let q2 = qmake 3.0 4.0 5.0 6.0 -let r = 7.0 - -let () = (* written strictly to spec *) - let pf = Printf.printf in - pf "starting with data q=%s, q1=%s, q2=%s, r=%g\n" (qstring q) (qstring q1) (qstring q2) r; - pf "1. norm of q = %g \n" (norm q) ; - pf "2. negative of q = %s \n" (qstring (negative q)); - pf "3. conjugate of q = %s \n" (qstring (conjugate q)); - pf "4. adding r to q = %s \n" (qstring (addrq r q)); - pf "5. adding q1 and q2 = %s \n" (qstring (addq q1 q2)); - pf "6. multiply r and q = %s \n" (qstring (multrq r q)); - pf "7. multiply q1 and q2 = %s \n" (qstring (multq q1 q2)); - pf "8. instead q2 * q1 = %s \n" (qstring (multq q2 q1)); - pf "\n"; diff --git a/Task/Quaternion-type/OCaml/quaternion-type-2.ocaml b/Task/Quaternion-type/OCaml/quaternion-type-2.ocaml deleted file mode 100644 index d02cc259ca..0000000000 --- a/Task/Quaternion-type/OCaml/quaternion-type-2.ocaml +++ /dev/null @@ -1,11 +0,0 @@ -type quaternion = { a : float; b : float; c : float; d : float; } -val norm : quaternion -> float = -val floatneg : float -> float = -val negative : quaternion -> quaternion = -val conjugate : quaternion -> quaternion = -val addrq : float -> quaternion -> quaternion = -val addq : quaternion -> quaternion -> quaternion = -val multrq : float -> quaternion -> quaternion = -val multq : quaternion -> quaternion -> quaternion = -val qmake : float -> float -> float -> float -> quaternion = -val qstring : quaternion -> string = diff --git a/Task/Quaternion-type/Octave/quaternion-type-1.octave b/Task/Quaternion-type/Octave/quaternion-type-1.octave deleted file mode 100644 index 97d6510de9..0000000000 --- a/Task/Quaternion-type/Octave/quaternion-type-1.octave +++ /dev/null @@ -1 +0,0 @@ -pkg install -forge quaternion diff --git a/Task/Quaternion-type/Octave/quaternion-type-2.octave b/Task/Quaternion-type/Octave/quaternion-type-2.octave deleted file mode 100644 index 3d862006d1..0000000000 --- a/Task/Quaternion-type/Octave/quaternion-type-2.octave +++ /dev/null @@ -1,24 +0,0 @@ -> q = quaternion (1, 2, 3, 4) -q = 1 + 2i + 3j + 4k -> q1 = quaternion (2, 3, 4, 5) -q1 = 2 + 3i + 4j + 5k -> q2 = quaternion (3, 4, 5, 6) -q2 = 3 + 4i + 5j + 6k -> r = 7 -r = 7 -> norm(q) -ans = 5.4772 -> -q -ans = -1 - 2i - 3j - 4k -> conj(q) -ans = 1 - 2i - 3j - 4k -> q + r -ans = 8 + 2i + 3j + 4k -> q1 + q2 -ans = 5 + 7i + 9j + 11k -> q * r -ans = 7 + 14i + 21j + 28k -> q1 * q2 -ans = -56 + 16i + 24j + 26k -> q1 == q2 -ans = 0 diff --git a/Task/Quaternion-type/Oforth/quaternion-type-1.fth b/Task/Quaternion-type/Oforth/quaternion-type-1.fth deleted file mode 100644 index 6f0413554d..0000000000 --- a/Task/Quaternion-type/Oforth/quaternion-type-1.fth +++ /dev/null @@ -1,24 +0,0 @@ -160 Number Class newPriority: Quaternion(a, b, c, d) - -Quaternion method: _a @a ; -Quaternion method: _b @b ; -Quaternion method: _c @c ; -Quaternion method: _d @d ; - -Quaternion method: initialize := d := c := b := a ; -Quaternion method: << '(' <q - Quaternion new(2, 3, 4, 5) ->q1 - Quaternion new(3, 4, 5, 6) ->q2 - 7.0 -> r - - System.Out "q = " << q << cr - System.Out "q1 = " << q1 << cr - System.Out "q2 = " << q2 << cr - - System.Out "norm q = " << q norm << cr - System.Out "neg q = " << q neg << cr - System.Out "conj q = " << q conj << cr - System.Out "q +r = " << q r + << cr - System.Out "q1 + q2 = " << q1 q2 + << cr - System.Out "q * r = " << q r * << cr - System.Out "q1 * q2 = " << q1 q2 * << cr - q1 q2 * q2 q1 * == ifFalse: [ "q1q2 and q2q1 are different quaternions" println ] ; diff --git a/Task/Quaternion-type/Ol/quaternion-type.ol b/Task/Quaternion-type/Ol/quaternion-type.ol deleted file mode 100644 index 9f2c57565f..0000000000 --- a/Task/Quaternion-type/Ol/quaternion-type.ol +++ /dev/null @@ -1,241 +0,0 @@ -;; -;; This program is written to run without modification both in Otus -;; Lisp and in any of many Scheme dialects. I assume the presence of -;; "case-lambda", but not of "let-values". The program has worked -;; (without modification) in Otus Lisp 2.4, Guile >= 2.0 (but not in -;; Guile version 1.8), CHICKEN Scheme 5.3.0, Chez Scheme 9.5.8, Gauche -;; Scheme 0.9.12, Ypsilon 0.9.6-update3. -;; -;; Here a quaternion is represented as a linked list of four real -;; numbers. Such a representation probably has the greatest -;; portability between Scheme dialects. However, this representation -;; can be replaced, simply by redefining the procedures "quaternion?", -;; "quaternion-components", "quaternion->list", and "quaternion". -;; - -(define (quaternion? q) ; Can q be used as a quaternion? - (and (pair? q) - (let ((a (car q)) - (q (cdr q))) - (and (real? a) (pair? q) - (let ((b (car q)) - (q (cdr q))) - (and (real? b) (pair? q) - (let ((c (car q)) - (q (cdr q))) - (and (real? c) (pair? q) - (let ((d (car q)) - (q (cdr q))) - (and (real? d) (null? q))))))))))) - -(define (quaternion-components q) ; Extract the basis components. - (let ((a (car q)) - (q (cdr q))) - (let ((b (car q)) - (q (cdr q))) - (let ((c (car q)) - (q (cdr q))) - (let ((d (car q))) - (values a b c d)))))) - -(define (quaternion->list q) ; Get a list of the basis components. - q) - -(define quaternion ; Make a quaternion. - (case-lambda - ((a b c d) - ;; Make the quaternion from basis components. - (list a b c d)) - ((q) - ;; Make the quaternion from a scalar or from another quaternion. - ;; WARNING: in the latter case, the quaternion is NOT - ;; copied. This is not a problem, if you avoid things like - ;; "set-car!" and "set-cdr!". - (if (real? q) - (list q 0 0 0) - q)))) - -(define (quaternion-norm q) ; The euclidean norm of a quaternion. - (let ((q (quaternion q))) - (call-with-values (lambda () (quaternion-components q)) - (lambda (a b c d) - (sqrt (+ (* a a) (* b b) (* c c) (* d d))))))) - -(define (quaternion-conjugate q) ; Conjugate a quaternion. - (let ((q (quaternion q))) - (call-with-values (lambda () (quaternion-components q)) - (lambda (a b c d) - (quaternion a (- b) (- c) (- d)))))) - -(define quaternion+ ; Add quaternions. - (let ((quaternion-add - (lambda (q1 q2) - (let ((q1 (quaternion q1)) - (q2 (quaternion q2))) - (call-with-values - (lambda () (quaternion-components q1)) - (lambda (a1 b1 c1 d1) - (call-with-values - (lambda () (quaternion-components q2)) - (lambda (a2 b2 c2 d2) - (quaternion (+ a1 a2) (+ b1 b2) - (+ c1 c2) (+ d1 d2)))))))))) - (case-lambda - (() (quaternion 0)) - ((q . q*) - (let loop ((accum q) - (q* q*)) - (if (pair? q*) - (loop (quaternion-add accum (car q*)) (cdr q*)) - accum)))))) - -(define quaternion- ; Negate or subtract quaternions. - (let ((quaternion-sub - (lambda (q1 q2) - (let ((q1 (quaternion q1)) - (q2 (quaternion q2))) - (call-with-values - (lambda () (quaternion-components q1)) - (lambda (a1 b1 c1 d1) - (call-with-values - (lambda () (quaternion-components q2)) - (lambda (a2 b2 c2 d2) - (quaternion (- a1 a2) (- b1 b2) - (- c1 c2) (- d1 d2)))))))))) - (case-lambda - ((q) - (let ((q (quaternion q))) - (call-with-values (lambda () (quaternion-components q)) - (lambda (a b c d) - (quaternion (- a) (- b) (- c) (- d)))))) - ((q . q*) - (let loop ((accum q) - (q* q*)) - (if (pair? q*) - (loop (quaternion-sub accum (car q*)) (cdr q*)) - accum)))))) - -(define quaternion* ; Multiply quaternions. - (let ((quaternion-mul - (lambda (q1 q2) - (let ((q1 (quaternion q1)) - (q2 (quaternion q2))) - (call-with-values - (lambda () (quaternion-components q1)) - (lambda (a1 b1 c1 d1) - (call-with-values - (lambda () (quaternion-components q2)) - (lambda (a2 b2 c2 d2) - (quaternion (- (* a1 a2) (* b1 b2) - (* c1 c2) (* d1 d2)) - (- (+ (* a1 b2) (* b1 a2) (* c1 d2)) - (* d1 c2)) - (- (+ (* a1 c2) (* c1 a2) (* d1 b2)) - (* b1 d2)) - (- (+ (* a1 d2) (* b1 c2) (* d1 a2)) - (* c1 b2))))))))))) - (case-lambda - (() (quaternion 1)) - ((q . q*) - (let loop ((accum q) - (q* q*)) - (if (pair? q*) - (loop (quaternion-mul accum (car q*)) (cdr q*)) - accum)))))) - -(define quaternion=? ; Are the quaternions equal? - (let ((=? (lambda (q1 q2) - (let ((q1 (quaternion q1)) - (q2 (quaternion q2))) - (call-with-values - (lambda () (quaternion-components q1)) - (lambda (a1 b1 c1 d1) - (call-with-values - (lambda () (quaternion-components q2)) - (lambda (a2 b2 c2 d2) - (and (= a1 a2) (= b1 b2) - (= c1 c2) (= d1 d2)))))))))) - (lambda (q . q*) - (let loop ((q* q*)) - (if (pair? q*) - (and (=? q (car q*)) - (loop (cdr q*))) - #t))))) - -(define q (quaternion 1 2 3 4)) -(define q1 (quaternion 2 3 4 5)) -(define q2 (quaternion 3 4 5 6)) -(define r 7) - -(display "q = ") (display (quaternion->list q)) (newline) -(display "q1 = ") (display (quaternion->list q1)) (newline) -(display "q2 = ") (display (quaternion->list q2)) (newline) -(display "r = ") (display r) (newline) -(newline) -(display "(quaternion? q) = ") (display (quaternion? q)) (newline) -(display "(quaternion? q1) = ") (display (quaternion? q1)) (newline) -(display "(quaternion? q2) = ") (display (quaternion? q2)) (newline) -(display "(quaternion? r) = ") (display (quaternion? r)) (newline) -(newline) -(display "(quaternion-norm q) = ") -(display (quaternion-norm q)) (newline) -(display "(quaternion-norm q1) = ") -(display (quaternion-norm q1)) (newline) -(display "(quaternion-norm q2) = ") -(display (quaternion-norm q2)) (newline) -(newline) -(display "(quaternion- q) = ") -(display (quaternion->list (quaternion- q))) (newline) -(display "(quaternion- q1 q2) = ") -(display (quaternion->list (quaternion- q1 q2))) (newline) -(display "(quaternion- q q1 q2) = ") -(display (quaternion->list (quaternion- q q1 q2))) (newline) -(newline) -(display "(quaternion-conjugate q) = ") -(display (quaternion->list (quaternion-conjugate q))) (newline) -(newline) -(display "(quaternion+) = ") -(display (quaternion->list (quaternion+))) (newline) -(display "(quaternion+ q) = ") -(display (quaternion->list (quaternion+ q))) (newline) -(display "(quaternion+ r q) = ") -(display (quaternion->list (quaternion+ r q))) (newline) -(display "(quaternion+ q r) = ") -(display (quaternion->list (quaternion+ q r))) (newline) -(display "(quaternion+ q1 q2) = ") -(display (quaternion->list (quaternion+ q1 q2))) (newline) -(display "(quaternion+ q q1 q2) = ") -(display (quaternion->list (quaternion+ q q1 q2))) (newline) -(newline) -(display "(quaternion*) = ") -(display (quaternion->list (quaternion*))) (newline) -(display "(quaternion* q) = ") -(display (quaternion->list (quaternion* q))) (newline) -(display "(quaternion* r q) = ") -(display (quaternion->list (quaternion* r q))) (newline) -(display "(quaternion* q r) = ") -(display (quaternion->list (quaternion* q r))) (newline) -(display "(quaternion* q1 q2) = ") -(display (quaternion->list (quaternion* q1 q2))) (newline) -(display "(quaternion* q q1 q2) = ") -(display (quaternion->list (quaternion* q q1 q2))) (newline) -(newline) -(display "(quaternion=? q) = ") -(display (quaternion=? q)) (newline) -(display "(quaternion=? q q) = ") -(display (quaternion=? q q)) (newline) -(display "(quaternion=? q1 q2) = ") -(display (quaternion=? q1 q2)) (newline) -(display "(quaternion=? q q q) = ") -(display (quaternion=? q q q)) (newline) -(display "(quaternion=? q1 q1 q2) = ") -(display (quaternion=? q1 q1 q2)) (newline) -(newline) -(display "(quaternion* q1 q2) = ") -(display (quaternion->list (quaternion* q1 q2))) (newline) -(display "(quaternion* q2 q1) = ") -(display (quaternion->list (quaternion* q2 q1))) (newline) -(display "(quaternion=? (quaternion* q1 q2)") (newline) -(display " (quaternion* q2 q1)) = ") -(display (quaternion=? (quaternion* q1 q2) - (quaternion* q2 q1))) (newline) diff --git a/Task/Quaternion-type/OoRexx/quaternion-type.rexx b/Task/Quaternion-type/OoRexx/quaternion-type.rexx deleted file mode 100644 index ab6a4bdaae..0000000000 --- a/Task/Quaternion-type/OoRexx/quaternion-type.rexx +++ /dev/null @@ -1,150 +0,0 @@ -q = .quaternion~new(1, 2, 3, 4) -q1 = .quaternion~new(2, 3, 4, 5) -q2 = .quaternion~new(3, 4, 5, 6) -r = 7 - -say "q =" q -say "q1 =" q1 -say "q2 =" q2 -say "r =" r -say "norm(q) =" q~norm -say "-q =" (-q) -say "q* =" q~conjugate -say "q + r =" q + r -say "q1 + q2 =" q1 + q2 -say "q * r =" q * r -q1q2 = q1 * q2 -q2q1 = q2 * q1 -say "q1 * q2 =" q1q2 -say "q2 * q1 =" q2q1 -say "q1 == q1 =" (q1 == q1) -say "q1q2 == q2q1 =" (q1q2 == q2q1) - - -::class quaternion -::method init - expose r i j k - use strict arg r, i = 0, j = 0, k = 0 - --- quaternion instances are immutable, so these are --- read only attributes -::attribute r GET -::attribute i GET -::attribute j GET -::attribute k GET - -::method norm - expose r i j k - return rxcalcsqrt(r * r + i * i + j * j + k * k) - -::method invert - expose r i j k - norm = self~norm - return self~class~new(r / norm, i / norm, j / norm, k / norm) - -::method negative - expose r i j k - return self~class~new(-r, -i, -j, -k) - -::method conjugate - expose r i j k - return self~class~new(r, -i, -j, -k) - -::method add - expose r i j k - use strict arg other - if other~isa(.quaternion) then - return self~class~new(r + other~r, i + other~i, j + other~j, k + other~k) - else return self~class~new(r + other, i, j, k) - -::method subtract - expose r i j k - use strict arg other - if other~isa(.quaternion) then - return self~class~new(r - other~r, i - other~i, j - other~j, k - other~k) - else return self~class~new(r - other, i, j, k) - -::method times - expose r i j k - use strict arg other - if other~isa(.quaternion) then - return self~class~new(r * other~r - i * other~i - j * other~j - k * other~k, - - r * other~i + i * other~r + j * other~k - k * other~j, - - r * other~j - i * other~k + j * other~r + k * other~i, - - r * other~k + i * other~j - j * other~i + k * other~r) - else return self~class~new(r * other, i * other, j * other, k * other) - -::method divide - use strict arg other - -- this is easier if everything is a quaternion - if \other~isA(.quaternion) then other = .quaternion~new(other) - -- division is multiplication with the inversion - return self * other~invert - -::method "==" - expose r i j k - use strict arg other - - if \other~isa(.quaternion) then return .false - -- Note: these are numeric comparisons, so we're using the "=" - -- method so those are handled correctly - return r = other~r & i = other~i & j = other~j & k = other~k - -::method "\==" - use strict arg other - return \self~"\=="(other) - -::method "=" - -- this is equivalent of "==" - forward message("==") - -::method "\=" - -- this is equivalent of "\==" - forward message("\==") - -::method "<>" - -- this is equivalent of "\==" - forward message("\==") - -::method "><" - -- this is equivalent of "\==" - forward message("\==") - --- some operator overrides -- these only work if the left-hand-side of the --- subexpression is a quaternion -::method "*" - forward message("TIMES") - -::method "/" - forward message("DIVIDE") - -::method "-" - -- need to check if this is a prefix minus or a subtract - if arg() == 0 then - forward message("NEGATIVE") - else - forward message("SUBTRACT") - -::method "+" - -- need to check if this is a prefix plus or an addition - if arg() == 0 then - return self -- we can return this copy since it is immutable - else - forward message("ADD") - -::method string - expose r i j k - return r self~formatnumber(i)"i" self~formatnumber(j)"j" self~formatnumber(k)"k" - -::method formatnumber private - use arg value - if value > 0 then return "+" value - else return "-" value~abs - --- override hashcode for collection class hash uses -::method hashCode - expose r i j k - return r~hashcode~bitxor(i~hashcode)~bitxor(j~hashcode)~bitxor(k~hashcode) - - -::requires rxmath LIBRARY diff --git a/Task/Quaternion-type/PARI-GP/quaternion-type-1.parigp b/Task/Quaternion-type/PARI-GP/quaternion-type-1.parigp deleted file mode 100644 index 0a0f4485dc..0000000000 --- a/Task/Quaternion-type/PARI-GP/quaternion-type-1.parigp +++ /dev/null @@ -1,35 +0,0 @@ -q.norm={ - if(type(q) != "t_VEC" || #q != 4, error("incorrect type")); - sqrt(q[1]^2+q[2]^2+q[3]^2+q[4]^2) -}; -q.conj={ - if(type(q) != "t_VEC" || #q != 4, error("incorrect type")); - -[-q[1],q[2],q[3],q[4]] -}; -q.add={ - if(type(q) != "t_VEC" || #q != 4, error("incorrect type")); - x->if(type(x) == "t_INT" || type(x) == t_REAL, - [q[1]+x,q[2],q[3],q[4]] - , - if(type(x) == "t_VEC" && #x == 4, - q+x - , - error("incorrect type") - ) - ) -}; -q.mult={ - if(type(q) != "t_VEC" || #q != 4, error("incorrect type")); - x->if(type(x) == "t_INT" || type(x) == t_REAL, - x*q - , - if(type(x) == "t_VEC" && #x == 4, - [q[1]*x[1] - q[2]*x[2] - q[3]*x[3] - q[4]*x[4], - q[1]*x[2] + q[2]*x[1] + q[3]*x[4] - q[4]*x[3], - q[1]*x[3] - q[2]*x[4] + q[3]*x[1] + q[4]*x[2], - q[1]*x[4] + q[2]*x[3] - q[3]*x[2] + q[4]*x[1]] - , - error("incorrect type") - ) - ) -}; diff --git a/Task/Quaternion-type/PARI-GP/quaternion-type-2.parigp b/Task/Quaternion-type/PARI-GP/quaternion-type-2.parigp deleted file mode 100644 index a9c990c848..0000000000 --- a/Task/Quaternion-type/PARI-GP/quaternion-type-2.parigp +++ /dev/null @@ -1,10 +0,0 @@ -r=7;q=[1,2,3,4];q1=[2,3,4,5];q2=[3,4,5,6]; -q.norm --q -q.conj -q.add(r) -q1.add(q2) -q1.add(q2) \\ or q1+q2 -q.mult(r) \\ or r*q or q*r -q1.mult(q2) -q1.mult(q2) != q2.mult(q1) diff --git a/Task/Quaternion-type/PL-I/quaternion-type.pli b/Task/Quaternion-type/PL-I/quaternion-type.pli deleted file mode 100644 index e6ab04d195..0000000000 --- a/Task/Quaternion-type/PL-I/quaternion-type.pli +++ /dev/null @@ -1,146 +0,0 @@ -*process source attributes xref or(!); - qu: Proc Options(main); - /********************************************************************** - * 06.09.2013 Walter Pachl translated from REXX - * added tasks 9 and A - **********************************************************************/ - dcl v(4) Char(1) Var Init('','i','j','k'); - define structure 1 quat, 2 x(4) Dec Float(15); - Dcl q type quat; Call quat_init(q, 1,2,3,4); - Dcl q1 type quat; Call quat_init(q1,2,3,4,5); - Dcl q2 type quat; Call quat_init(q2,3,4,5,6); - Dcl q3 type quat; Call quat_init(q3,-2,3,-4,-5); - Dcl r Dec Float(15)Init(7); - - call showq(' ','q' ,q); - call showq(' ','q1' ,q1); - call showq(' ','q2' ,q2); - call showq(' ','q3' ,q3); - call shows(' ','r' ,r); - Call shows('task 1:','norm q' ,norm(q)); - Call showq('task 2:','quatneg q' ,quatneg(q)); - Call showq('task 3:','conjugate q' ,quatConj(q)); - Call showq('task 4:','addition r+q' ,quatAddsq(r,q)); - Call showq('task 5:','addition q1+q2' ,quatAdd(q1,q2)); - Call showq('task 6:','multiplication q*r' ,quatMulqs(q,r)); - Call showq('task 7:','multiplication q1*q2' ,quatMul(q1,q2)); - Call showq('task 8:','multiplication q2*q1' ,quatMul(q2,q1)); - Call showq('task 9:','quatsub q1-q1' ,quatAdd(q1,quatneg(q1))); - Call showq('task A:','addition q1+q3' ,quatAdd(q1,q3)); - Call showt('task B:','equal' ,quatEqual(quatMul(q1,q2), - quatMul(q2,q1))); - Call showt('task C:','q1=q1' ,quatEqual(q1,q1)); - - quatNeg: procedure(qp) Returns(type quat); - Dcl (qp,qr) type quat; - qr.x(*)=-qp.x(*); - Return (qr); - End; - - quatAdd: procedure(qp,qq) Returns(type quat); - Dcl (qp,qq,qr) type quat; - qr.x(*)=qp.x(*)+qq.x(*); - Return (qr); - End; - - quatAddsq: procedure(v,qp) Returns(type quat); - Dcl v Dec Float(15); - Dcl (qp,qr) type quat; - qr.x(*)=qp.x(*); - qr.x(1)=qp.x(1)+v; - Return (qr); - End; - - quatConj: procedure(qp) Returns(type quat); - Dcl (qp,qr) type quat; - qr.x(*)=-qp.x(*); - qr.x(1)= qp.x(1); - Return (qr); - End; - - quatMul: procedure(qp,qq) Returns(type quat); - Dcl (qp,qq,qr) type quat; - qr.x(1)= - qp.x(1)*qq.x(1)-qp.x(2)*qq.x(2)-qp.x(3)*qq.x(3)-qp.x(4)*qq.x(4); - qr.x(2)= - qp.x(1)*qq.x(2)+qp.x(2)*qq.x(1)+qp.x(3)*qq.x(4)-qp.x(4)*qq.x(3); - qr.x(3)= - qp.x(1)*qq.x(3)-qp.x(2)*qq.x(4)+qp.x(3)*qq.x(1)+qp.x(4)*qq.x(2); - qr.x(4)= - qp.x(1)*qq.x(4)+qp.x(2)*qq.x(3)-qp.x(3)*qq.x(2)+qp.x(4)*qq.x(1); - Return (qr); - End; - - quatMulqs: procedure(qp,v) Returns(type quat); - Dcl (qp,qr) type quat; - Dcl v Dec Float(15); - qr.x(*)=qp.x(*)*v; - Return (qr); - End; - - shows: Procedure(t1,t2,v); - Dcl (t1,t2) Char(*); - Dcl v Dec Float(15); - Put Edit(t1,right(t2,24),' --> ',v)(Skip,a,a,a,f(15,13)); - End; - - showt: Procedure(t1,t2,v); - Dcl (t1,t2) Char(*); - Dcl v Char(*) Var); - Put Edit(t1,right(t2,24),' --> ',v)(Skip,a,a,a,a); - End; - - showq: Procedure(t1,t2,qp); - Dcl qp type quat; - Dcl (t1,t2) Char(*); - Dcl (s,s2,p) Char(100) Var Init(''); - Dcl i Bin Fixed(31); - Put String(s) Edit(t1,right(t2,24),' --> ')(a,a,a); - Do i=1 To 4; - Put String(p) Edit(abs(qp.x(i)))(p'ZZZ9'); - p=trim(p); - Select; - When(qp.x(i)<0) p='-'!!p!!v(i); - When(p=0) p=''; - Otherwise Do - If s2^='' Then p='+'!!p; - If i>1 Then p=p!!v(i); - End; - End; - s2=s2!!p - End; - If s2='' Then - s2='0'; - Put Edit(s!!s2)(Skip,a); - End; - - norm: Procedure(qp) Returns(Dec Float(15)); - Dcl qp type quat; - Dcl r Dec Float(15) Init(0); - Dcl i Bin Fixed(31); - Do i=1 To 4; - r=r+qp.x(i)**2; - End; - Return (sqrt(r)); - End; - - quat_init: Proc(qp,x,y,z,u); - Dcl qp type quat; - Dcl (x,y,z,u) Dec Float(15); - qp.x(1)=x; - qp.x(2)=y; - qp.x(3)=z; - qp.x(4)=u; - End; - - quatEqual: procedure(qp,qq) Returns(Char(12) Var); - Dcl (qp,qq) type quat; - Dcl i Bin Fixed(15); - Do i=1 To 4; - If qp.x(i)^=qq.x(i) Then - Return('not equal'); - End; - Return('equal'); - End; - - End; diff --git a/Task/Quaternion-type/Perl/quaternion-type.pl b/Task/Quaternion-type/Perl/quaternion-type.pl deleted file mode 100644 index 1676713adf..0000000000 --- a/Task/Quaternion-type/Perl/quaternion-type.pl +++ /dev/null @@ -1,70 +0,0 @@ -package Quaternion; -use List::Util 'reduce'; -use List::MoreUtils 'pairwise'; - -sub make { - my $cls = shift; - if (@_ == 1) { return bless [ @_, 0, 0, 0 ] } - elsif (@_ == 4) { return bless [ @_ ] } - else { die "Bad number of components: @_" } -} - -sub _abs { sqrt reduce { $a + $b * $b } @{ +shift } } -sub _neg { bless [ map(-$_, @{+shift}) ] } -sub _str { "(@{+shift})" } - -sub _add { - my ($x, $y) = @_; - $y = [ $y, 0, 0, 0 ] unless ref $y; - bless [ pairwise { $a + $b } @$x, @$y ] -} - -sub _sub { - my ($x, $y, $swap) = @_; - $y = [ $y, 0, 0, 0 ] unless ref $y; - my @x = pairwise { $a - $b } @$x, @$y; - if ($swap) { $_ = -$_ for @x } - bless \@x; -} - -sub _mul { - my ($x, $y) = @_; - if (!ref $y) { return bless [ map($_ * $y, @$x) ] } - my ($a1, $b1, $c1, $d1) = @$x; - my ($a2, $b2, $c2, $d2) = @$y; - bless [ $a1 * $a2 - $b1 * $b2 - $c1 * $c2 - $d1 * $d2, - $a1 * $b2 + $b1 * $a2 + $c1 * $d2 - $d1 * $c2, - $a1 * $c2 - $b1 * $d2 + $c1 * $a2 + $d1 * $b2, - $a1 * $d2 + $b1 * $c2 - $c1 * $b2 + $d1 * $a2] -} - -sub conjugate { - my @a = map { -$_ } @{$_[0]}; - $a[0] = $_[0][0]; - bless \@a -} - -use overload ( - '""' => \&_str, - '+' => \&_add, - '-' => \&_sub, - '*' => \&_mul, - 'neg' => \&_neg, - 'abs' => \&_abs, -); - -package main; - -my $a = Quaternion->make(1, 2, 3, 4); -my $b = Quaternion->make(1, 1, 1, 1); - -print "a = $a\n"; -print "b = $b\n"; -print "|a| = ", abs($a), "\n"; -print "-a = ", -$a, "\n"; -print "a + 1 = ", $a + 1, "\n"; -print "a + b = ", $a + $b, "\n"; -print "a - b = ", $a - $b, "\n"; -print "a conjugate is ", $a->conjugate, "\n"; -print "a * b = ", $a * $b, "\n"; -print "b * a = ", $b * $a, "\n"; diff --git a/Task/Quaternion-type/Phix/quaternion-type.phix b/Task/Quaternion-type/Phix/quaternion-type.phix deleted file mode 100644 index 3c60bc59bc..0000000000 --- a/Task/Quaternion-type/Phix/quaternion-type.phix +++ /dev/null @@ -1,74 +0,0 @@ -(phixonline)--> - with javascript_semantics - function norm(sequence q) - return sqrt(sum(sq_power(q,2))) - end function - - function conjugate(sequence q) - q = deep_copy(q) - q[2..4] = sq_uminus(q[2..4]) - return q - end function - - function negative(sequence q) - return sq_uminus(q) - end function - - function add(object q1, object q2) - if atom(q1)!=atom(q2) then - if atom(q1) then - q1 = {q1,0,0,0} - else - q2 = {q2,0,0,0} - end if - end if - return sq_add(q1,q2) - end function - - function mul(object q1, object q2) - if sequence(q1) and sequence(q2) then - atom {r1,i1,j1,k1} = q1, - {r2,i2,j2,k2} = q2 - return { r1*r2 - i1*i2 - j1*j2 - k1*k2, - r1*i2 + i1*r2 + j1*k2 - k1*j2, - r1*j2 - i1*k2 + j1*r2 + k1*i2, - r1*k2 + i1*j2 - j1*i2 + k1*r2 } - else - return sq_mul(q1,q2) - end if - end function - - function quats(sequence q) - return sprintf("%g%+gi%+gj%+gk",q) - end function - - constant - q = {1, 2, 3, 4}, - q1 = {2, 3, 4, 5}, - q2 = {3, 4, 5, 6} - - printf(1, " q = %s\n", {quats(q)}) - printf(1, " q1 = %s\n", {quats(q1)}) - printf(1, " q2 = %s\n", {quats(q2)}) - printf(1, "\n") - printf(1, "1. norm(q) = %g\n", norm(q)) - printf(1, "2. negative(q) = %s\n", {quats(negative(q))}) - printf(1, "3. conjugate(q) = %s\n", {quats(conjugate(q))}) - printf(1, "\n") - printf(1, "4.a q + 7 = %s\n", {quats(add(q,7))}) - printf(1, " .b 7 + q = %s\n", {quats(add(7,q))}) - printf(1, "\n") - printf(1, "5.a q1 + q2 = %s\n", {quats(add(q1,q2))}) - printf(1, " .b q2 + q1 = %s\n", {quats(add(q2,q1))}) - printf(1, "\n") - printf(1, "6.a q * 49 = %s\n", {quats(mul(q,49))}) - printf(1, " .b 49 * q = %s\n", {quats(mul(49,q))}) - printf(1, "\n") - printf(1, "7.a q1 * q2 = %s\n", {quats(mul(q1,q2))}) - printf(1, " .b q2 * q1 = %s\n", {quats(mul(q2,q1))}) - printf(1, "\n") - printf(1, "8.a 4.a === 4.b: %t\n", {equal(add(q,7),add(7,q))}) - printf(1, " .b 5.a === 5.b: %t\n", {equal(add(q1,q2),add(q2,q1))}) - printf(1, " .c 6.a === 6.b: %t\n", {equal(mul(q,49),mul(49,q))}) - printf(1, " .d 7.a === 7.b: %t\n", {equal(mul(q1,q2),mul(q2,q1))}) -" -> a literal string arrow + ;; mold do code -> DO evaluates 'code' as Rebol code. + ;; MOLD converts the result into a textual representation + print [code "-->" mold do code] +] diff --git a/Task/Quoting-constructs/Rebol/quoting-constructs-2.rebol b/Task/Quoting-constructs/Rebol/quoting-constructs-2.rebol new file mode 100644 index 0000000000..58d10a8be8 --- /dev/null +++ b/Task/Quoting-constructs/Rebol/quoting-constructs-2.rebol @@ -0,0 +1,22 @@ +"tab is: ^-" ;; A string literal in double quotes. + ;; ^- inside a string is an escape for the TAB character in Rebol. + ;; So this represents: tab is: + +"double-quote is: ^""" ;; String literal containing a double quote character. + ;; In Rebol strings, ^" is an escape sequence for a literal quote. + ;; This yields: double-quote is: " + +{double-quote is: "} ;; String literal in curly braces { }. + ;; Inside { }, double quotes don't need escaping. + ;; This simply yields: double-quote is: " + +"foo {" ;; String literal in double quotes that contains an opening brace {. + ;; In double-quoted strings, braces are just characters, no special meaning. + ;; Yields: foo { + +{foo ^{} ;; String literal in curly braces containing an opening brace {. + ;; In { }, the sequence ^{ is an escape for the brace. + ;; Otherwise an unescaped } would end the string. + ;; Yields: foo { +;; Additionally in Rebol 3: +%%{raw string don't needs escapes for " or {}%% diff --git a/Task/Quoting-constructs/Uiua/quoting-constructs.uiua b/Task/Quoting-constructs/Uiua/quoting-constructs.uiua new file mode 100644 index 0000000000..b74a05ff8e --- /dev/null +++ b/Task/Quoting-constructs/Uiua/quoting-constructs.uiua @@ -0,0 +1,13 @@ +"Just a string" +# String interpolation. \ is a general escape character. +$"_ _ _ _ _ \_" 1 @a @\" @@ "asd" + +# multiline +$ multi +$ lines +$ " ' @ \ ! $ _ are all allowed + +# multiline with interpolation +"ple" "...." +$$ multi_ +$$ _lines diff --git a/Task/RIPEMD-160/Ada/ripemd-160.ada b/Task/RIPEMD-160/Ada/ripemd-160.adb similarity index 100% rename from Task/RIPEMD-160/Ada/ripemd-160.ada rename to Task/RIPEMD-160/Ada/ripemd-160.adb diff --git a/Task/RIPEMD-160/Delphi/ripemd-160.delphi b/Task/RIPEMD-160/Delphi/ripemd-160.pas similarity index 100% rename from Task/RIPEMD-160/Delphi/ripemd-160.delphi rename to Task/RIPEMD-160/Delphi/ripemd-160.pas diff --git a/Task/RIPEMD-160/EasyLang/ripemd-160.easy b/Task/RIPEMD-160/EasyLang/ripemd-160.easy new file mode 100644 index 0000000000..f9fa1c14e8 --- /dev/null +++ b/Task/RIPEMD-160/EasyLang/ripemd-160.easy @@ -0,0 +1,89 @@ +func u32 x . + return bitand x 0xFFFFFFFF +. +func rol x s . + left = u32 bitshift x s + right = bitshift u32 x -(32 - s) + return bitor left right +. +func$ hex w . + for k = 0 to 3 + h = w mod 256 + for c in [ h div 16 h mod 16 ] + c += 48 + if c >= 58 : c += 39 + hex$ &= strchar c + . + w = w div 256 + . + return hex$ +. +func fx n x y z . + if n = 1 : return u32 bitxor (bitxor x y) z + if n = 2 : return u32 bitor (bitand x y) (bitand bitnot x z) + if n = 3 : return u32 bitxor (bitor x bitnot y) z + if n = 4 : return u32 bitor (bitand x z) (bitand y bitnot z) + return u32 bitxor x (bitor y bitnot z) +. +func[] str2bytes s$ . + out[] = [ ] + for ch$ in strchars s$ : out[] &= strcode ch$ + return out[] +. +proc rmd160pad &data[] . + n = len data[] * 8 + data[] &= 0x80 + while len data[] mod 64 <> 56 : data[] &= 0x00 + for i = 1 to 8 + data[] &= (n mod 256) + n = n div 256 + . +. +rl[] = [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 7 4 13 1 10 6 15 3 12 0 9 5 2 14 11 8 3 10 14 4 9 15 8 1 2 7 0 6 13 11 5 12 1 9 11 10 0 8 12 4 13 3 7 15 14 5 6 2 4 0 5 9 7 12 2 10 14 1 3 8 11 6 15 13 ] +sl[] = [ 11 14 15 12 5 8 7 9 11 13 14 15 6 7 9 8 7 6 8 13 11 9 7 15 7 12 15 9 11 7 13 12 11 13 6 7 14 9 13 15 14 8 13 6 5 12 7 5 11 12 14 15 14 15 9 8 9 14 5 6 8 6 5 12 9 15 5 11 6 8 13 12 5 12 13 14 11 8 5 6 ] +rr[] = [ 5 14 7 0 9 2 11 4 13 6 15 8 1 10 3 12 6 11 3 7 0 13 5 10 14 15 8 12 4 9 1 2 15 5 1 3 7 14 6 9 11 8 12 2 10 0 4 13 8 6 4 1 3 11 15 0 5 12 2 13 9 7 10 14 12 15 10 4 1 5 8 7 6 2 13 14 0 3 9 11 ] +sr[] = [ 8 9 9 11 13 15 15 5 7 7 8 11 14 14 12 6 9 13 15 7 12 8 9 11 7 7 12 7 6 15 13 11 9 7 15 11 8 6 6 14 12 13 5 14 13 13 7 5 15 5 8 11 14 14 6 14 6 9 12 9 12 5 15 8 8 5 12 9 12 5 14 6 8 13 6 5 15 13 11 11 ] +KL[] = [ 0x00000000 0x5A827999 0x6ED9EBA1 0x8F1BBCDC 0xA953FD4E ] +KR[] = [ 0x50A28BE6 0x5C4DD124 0x6D703EF3 0x7A6D76E9 0x00000000 ] +proc rmd160block &H0 &H1 &H2 &H3 &H4 blk[] . + for i = 0 to 15 + b = 0 + for j = 4 downto 1 : b = b * 256 + blk[i * 4 + j] + X[] &= b + . + a = H0 ; b = H1 ; c = H2 ; d = H3 ; e = H4 + aa = H0 ; bb = H1 ; cc = H2 ; dd = H3 ; ee = H4 + for j = 1 to 80 + rnd = (j - 1) div 16 + 1 + f = fx rnd b c d + idxL = rl[j] + 1 + T = u32 (a + f + X[idxL] + KL[rnd]) + T = u32 (rol T sl[j] + e) + a = e ; e = d ; d = rol c 10 ; c = b ; b = T ; h = 6 - rnd + ff = fx h bb cc dd + idxR = rr[j] + 1 + TT = u32 (aa + ff + X[idxR] + KR[rnd]) + TT = u32 (rol TT sr[j] + ee) + aa = ee ; ee = dd ; dd = rol cc 10 ; cc = bb ; bb = TT + . + t = u32 (H1 + c + dd) + H1 = u32 (H2 + d + ee) + H2 = u32 (H3 + e + aa) + H3 = u32 (H4 + a + bb) + H4 = u32 (H0 + b + cc) + H0 = t +. +func$ ripemd160 s$ . + H0 = 0x67452301 ; H1 = 0xEFCDAB89 ; H2 = 0x98BADCFE + H3 = 0x10325476 ; H4 = 0xC3D2E1F0 + data[] = str2bytes s$ + rmd160pad data[] + blocks = len data[] / 64 + for b = 0 to blocks - 1 + blk[] = [ ] + for i = 1 to 64 : blk[] &= data[b * 64 + i] + rmd160block H0 H1 H2 H3 H4 blk[] + . + return hex H0 & hex H1 & hex H2 & hex H3 & hex H4 +. +print ripemd160 "Rosetta Code" diff --git a/Task/RIPEMD-160/Java/ripemd-160-2.java b/Task/RIPEMD-160/Java/ripemd-160-2.java index 5c025e6737..5ffad2ad52 100644 --- a/Task/RIPEMD-160/Java/ripemd-160-2.java +++ b/Task/RIPEMD-160/Java/ripemd-160-2.java @@ -50,7 +50,7 @@ final class RIPEMD160 { } private static byte[] addPadding(String aMessage) { - byte[] bytes = aMessage.getBytes(StandardCharsets.UTF_8); + byte[] bytes = aMessage.getBytes(StandardCharsets.ISO_8859_1); bytes = Arrays.copyOf(bytes, bytes.length + 1); bytes[bytes.length - 1] = (byte) 0x80; diff --git a/Task/RIPEMD-160/JavaScript/ripemd-160.js b/Task/RIPEMD-160/JavaScript/ripemd-160.js new file mode 100644 index 0000000000..68e9dcf93a --- /dev/null +++ b/Task/RIPEMD-160/JavaScript/ripemd-160.js @@ -0,0 +1,6 @@ +// ! npm install ripemd160 + +const ripemd160 = require('ripemd160'); +// Create hash of "Rosetta Code" +const hash = new ripemd160().update('Rosetta Code').digest('hex'); +console.log(hash); diff --git a/Task/RIPEMD-160/Julia/ripemd-160.julia b/Task/RIPEMD-160/Julia/ripemd-160.jl similarity index 100% rename from Task/RIPEMD-160/Julia/ripemd-160.julia rename to Task/RIPEMD-160/Julia/ripemd-160.jl diff --git a/Task/RIPEMD-160/Kotlin/ripemd-160.kotlin b/Task/RIPEMD-160/Kotlin/ripemd-160.kts similarity index 100% rename from Task/RIPEMD-160/Kotlin/ripemd-160.kotlin rename to Task/RIPEMD-160/Kotlin/ripemd-160.kts diff --git a/Task/RIPEMD-160/Phix/ripemd-160-1.phix b/Task/RIPEMD-160/Phix/ripemd-160-1.phix index 040e8473c7..73fd9f1b33 100644 --- a/Task/RIPEMD-160/Phix/ripemd-160-1.phix +++ b/Task/RIPEMD-160/Phix/ripemd-160-1.phix @@ -1,6 +1,5 @@ ---> - include builtins\ripemd160.e +without javascript_semantics -- #ilASM, peek, allocate +include builtins\ripemd160.e - constant test = "Rosetta Code" - printf(1,"\n%s => %s\n",{test,ripemd160(test)}) - - -- - -- builtins\ripemd160.e - -- ==================== - -- - function rol(atom v, integer n) - -- Programming note: this use of #ilASM{} is more for expediency than efficiency - #ilASM{ mov eax,[v] - call :%pLoadMint - mov ecx,[n] - rol eax,cl - lea edi,[v] - call :%pStoreMint } - return v - end function +-- builtins\ripemd160.e +function rol(atom v, integer n) +-- Programming note: this use of #ilASM{} is more for expediency than efficiency + #ilASM{ mov eax,[v] + call :%pLoadMint + mov ecx,[n] + rol eax,cl + lea edi,[v] + call :%pStoreMint } + return v +end function - constant K = {#00000000,#5A827999,#6ED9EBA1,#8F1BBCDC,#A953FD4E}, - KK = {#50A28BE6,#5C4DD124,#6D703EF3,#7A6D76E9,#00000000}, - r = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, - 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, - 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, - 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 }, - rr = { 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, - 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, - 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, - 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, - 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 }, - s = {11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, - 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, - 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, - 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, - 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 }, - ss = { 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, - 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, - 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, - 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, - 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 } +constant K = {#00000000,#5A827999,#6ED9EBA1,#8F1BBCDC,#A953FD4E}, + KK = {#50A28BE6,#5C4DD124,#6D703EF3,#7A6D76E9,#00000000}, + r = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, + 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, + 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, + 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 }, + rr = { 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, + 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, + 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, + 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, + 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 }, + s = {11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, + 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, + 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, + 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, + 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 }, + ss = { 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, + 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, + 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, + 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, + 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 } - global function ripemd160(string message, bool asString=true, atom pMem=NULL) - -- - -- Calculate the ripe-md-160 checksum. - -- - -- if asString is true (the default), returns a string representation of the - -- checksum (and pMem is ignored) - -- if asString is false, returns pMem (for want of anything better), which - -- must be a non-NULL pointer to at least 20 bytes of memory. - -- - atom h0 = #67452301, - h1 = #EFCDAB89, - h2 = #98BADCFE, - h3 = #10325476, - h4 = #C3D2E1F0, - mraw, t, tt +global function ripemd160(string message, bool asString=true, atom pMem=NULL) +-- +-- Calculate the ripe-md-160 checksum. +-- +-- if asString is true (the default), returns a string representation of the +-- checksum (and pMem is ignored) +-- if asString is false, returns pMem (for want of anything better), which +-- must be a non-NULL pointer to at least 20 bytes of memory. +-- + atom h0 = #67452301, + h1 = #EFCDAB89, + h2 = #98BADCFE, + h3 = #10325476, + h4 = #C3D2E1F0, + mraw, t, tt - integer l = length(message), - padding = 64 - mod(l+1,64) - if padding<8 then padding += 64 end if + integer l = length(message), + padding = 64 - mod(l+1,64) + if padding<8 then padding += 64 end if - message &= #80 & repeat('\0',padding-8) - & int_to_bytes(l*8,8) + message &= #80 & repeat('\0',padding-8) + & int_to_bytes(l*8,8) - #ilASM{ mov eax,[message] - lea edi,[mraw] - shl eax,2 -- ref -> raw address - call :%pStoreMint } + #ilASM{ mov eax,[message] + lea edi,[mraw] + shl eax,2 -- ref -> raw address + call :%pStoreMint } - for i=0 to length(message)-64 by 64 do - atom {a, b, c, d, e} = {h0, h1, h2, h3, h4} - atom {aa, bb, cc, dd, ee} = {h0, h1, h2, h3, h4} - for j = 1 to 80 do - integer k = floor((j-1)/16) - switch k - case 0: - t = xor_bits(xor_bits(b, c), d) - tt = xor_bits(bb,or_bits(cc,not_bits(dd))) - case 1: - t = or_bits(and_bits(b,c),and_bits(not_bits(b),d)) - tt = or_bits(and_bits(bb,dd),and_bits(cc,not_bits(dd))) - case 2: - t = xor_bits(or_bits(b,not_bits(c)),d) - tt = xor_bits(or_bits(bb,not_bits(cc)),dd) - case 3: - t = or_bits(and_bits(b,d),and_bits(c,not_bits(d))) - tt = or_bits(and_bits(bb,cc),and_bits(not_bits(bb),dd)) - case 4: - t = xor_bits(b,or_bits(c,not_bits(d))) - tt = xor_bits(xor_bits(bb, cc), dd) - end switch - t = rol( a + t + peek4u(mraw+i+ r[j]*4) + K[k+1], s[j]) + e - tt = rol(aa + tt + peek4u(mraw+i+rr[j]*4) + KK[k+1], ss[j]) + ee - {a, e, d, c, b } = {e, d, rol(c, 10), b, t } - {aa,ee,dd,cc,bb} = {ee,dd,rol(cc, 10),bb,tt} - end for - {h0, h1, h2, h3, h4} = {h1+c+dd, h2+d+ee, h3+e+aa, h4+a+bb, h0+b+cc} - end for - if not asString then - if pMem=NULL then ?9/0 end if - poke4(pMem,{h0,h1,h2,h3,h4}) - return pMem - end if - atom mem = allocate(20,true) - poke4(mem,{h0,h1,h2,h3,h4}) - string res = "" - for i=1 to 20 do - res &= sprintf("%02X",peek(mem+i-1)) - end for - return res - end function - - with javascript_semantics - sequence numbers = repeat(0,6) - integer t,n - while true do - for i=1 to length(numbers) do - sequence ni = sq_rand(repeat(6,4)) - numbers[i] = sum(ni)-min(ni) - end for - t = sum(numbers) - n = sum(sq_ge(numbers,15)) - if t>=75 and n>=2 then exit end if - ?"re-rolling..." -- (occasionally >20) - end while - printf(1,"The 6 attributes generated are:\n") - printf(1,"strength %d, dexterity %d, constitution %d, "& - "intelligence %d, wisdom %d, and charisma %d.\n", - numbers) - printf(1,"\nTheir sum is %d and %d of them are >=15\n",{t,n}) - - without javascript_semantics - include builtins/mpfr.e +without javascript_semantics +include builtins/mpfr.e - mpz n = mpz_init("9516311845790656153499716760847001433441357"), - e = mpz_init("65537"), - d = mpz_init("5617843187844953170308463622230283376298685"), - pt = mpz_init(), - ct = mpz_init() +mpz n = mpz_init("9516311845790656153499716760847001433441357"), + e = mpz_init("65537"), + d = mpz_init("5617843187844953170308463622230283376298685"), + pt = mpz_init(), + ct = mpz_init() - string plaintext = "Rossetta Code" -- matches C/zkl - -- "Rosetta Code" -- matches D/FreeBasic/Go/Icon/J/Kotlin/Seed7. +string plaintext = "Rossetta Code" -- matches C/zkl +-- "Rosetta Code" -- matches D/FreeBasic/Go/Icon/J/Kotlin/Seed7. - mpz_import(pt, length(plaintext), 1, 1, 0, 0, plaintext) +mpz_import(pt, length(plaintext), 1, 1, 0, 0, plaintext) - if mpz_cmp(pt, n)>0 then ?9/0 end if +if mpz_cmp(pt, n)>0 then ?9/0 end if - mpz_powm(ct, pt, e, n); - printf(1,"Encoded: %s\n", {mpz_get_str(ct)}) +mpz_powm(ct, pt, e, n); +printf(1,"Encoded: %s\n", {mpz_get_str(ct)}) - mpz_powm(pt, ct, d, n); - printf(1,"Decoded: %s\n", {mpz_get_str(pt)}) +mpz_powm(pt, ct, d, n); +printf(1,"Decoded: %s\n", {mpz_get_str(pt)}) - integer size =floor((mpz_sizeinbase(pt,2)+7)/8) - atom pMem = allocate(size,true) - integer count = mpz_export(pMem, 1, 1, 0, 0, pt) - if count>size then ?9/0 end if +integer size = floor((mpz_sizeinbase(pt,2)+7)/8) +atom pMem = allocate(size,true) +integer count = mpz_export(pMem, 1, 1, 0, 0, pt) +if count>size then ?9/0 end if - printf(1,"As String: %s\n", {peek({pMem,count})}) +printf(1,"As String: %s\n", {peek({pMem,count})}) - {pt, ct, n, e, d} = mpz_free({pt, ct, n, e, d}) - - with javascript_semantics - sequence pi = {} +with javascript_semantics +sequence pi = {} - procedure primeCounter(integer limit) - pi = repeat(1,limit) - if limit > 1 then - pi[1] = 0 - for i=4 to limit by 2 do - pi[i] = 0 - end for - integer p = 3, sq = 9 - while sq<=limit do - if pi[p]!=0 then - for q=sq to limit by p*2 do - pi[q] = 0 - end for - end if - sq += (p + 1)*4 - p += 2 - end while - atom total = 0 - for i=2 to limit do - total += pi[i] - pi[i] = total - end for - end if - end procedure +procedure primeCounter(integer limit) + pi = repeat(1,limit) + if limit > 1 then + pi[1] = 0 + for i=4 to limit by 2 do + pi[i] = 0 + end for + integer p = 3, sq = 9 + while sq<=limit do + if pi[p]!=0 then + for q=sq to limit by p*2 do + pi[q] = 0 + end for + end if + sq += (p + 1)*4 + p += 2 + end while + atom total = 0 + for i=2 to limit do + total += pi[i] + pi[i] = total + end for + end if +end procedure - function ramanujanMax(integer n) - return floor(4*n*log(4*n)) - end function +function ramanujanMax(integer n) + return floor(4*n*log(4*n)) +end function - function ramanujanPrime(integer n) - if n=1 then return 2 end if - integer maxposs = ramanujanMax(n) - for i=maxposs-odd(maxposs) to 1 by -2 do - if pi[i]-pi[floor(i/2)] < n then - return i + 1 - end if - end for - return 0 - end function +function ramanujanPrime(integer n) + if n=1 then return 2 end if + integer maxposs = ramanujanMax(n) + for i=maxposs-odd(maxposs) to 1 by -2 do + if pi[i]-pi[floor(i/2)] < n then + return i + 1 + end if + end for + return 0 +end function - constant lim = 1e5 -- 0.6s - --constant lim = 1e6 -- 4.7s -- (not pwa/p2js) - atom t0 = time() - primeCounter(ramanujanMax(lim)) - integer rplim = ramanujanPrime(lim) - printf(1,"The %,dth Ramanujan prime is %,d\n", {lim,rplim}) - function rpc(integer p) return pi[p]-pi[floor(p/2)] end function - sequence r = get_primes_le(rplim), - c = apply(r,rpc) - integer ok = c[$] - for i=length(c)-1 to 1 by -1 do - if c[i]<ok then - ok = c[i] - else - c[i] = 0 - end if - end for - function nzc(integer p, idx) return c[idx]!=0 end function - r = filter(r,nzc) - integer twins = 0 - for i=1 to length(r)-1 do - if r[i]+2 = r[i+1] then twins += 1 end if - end for - printf(1,"There are %,d twins in the first %,d Ramanujan primes\n", {twins,length(r)}) - ?elapsed(time()-t0) - - with javascript_semantics - function rdp(sequence l, atom e) - if length(l)<2 then crash("not enough points to simplify") end if - integer idx := 0 - atom dMax := -1, - {p1x,p1y} := l[1], - {p2x,p2y} := l[$], - x21 := p2x - p1x, - y21 := p2y - p1y - for i=1 to length(l) do - atom {px,py} = l[i], - d = abs(y21*px-x21*py + p2x*p1y-p2y*p1x) - if d>dMax then - idx = i - dMax = d - end if - end for - if dMax>e then - return rdp(l[1..idx], e) & rdp(l[idx..$], e)[2..$] - end if - return {l[1], l[$]} - end function +with javascript_semantics +function rdp(sequence l, atom e) + if length(l)<2 then crash("not enough points to simplify") end if + integer idx := 0 + atom dMax := -1, + {p1x,p1y} := l[1], + {p2x,p2y} := l[$], + x21 := p2x - p1x, + y21 := p2y - p1y + for i=1 to length(l) do + atom {px,py} = l[i], + d = abs(y21*px-x21*py + p2x*p1y-p2y*p1x) + if d>dMax then + idx = i + dMax = d + end if + end for + if dMax>e then + return rdp(l[1..idx], e) & rdp(l[idx..$], e)[2..$] + end if + return {l[1], l[$]} +end function - sequence points = {{0, 0}, {1, 0.1}, {2, -0.1}, {3, 5}, {4, 6}, - {5, 7}, {6, 8.1}, {7, 9}, {8, 9}, {9, 9}} - ?rdp(points, 1) - - integer res -- 1=failure, 0=success - atom rint = 0 -- random 32-bit int +integer res -- 1=failure, 0=success +atom rint = 0 -- random 32-bit int - #ilASM{ - mov eax,1 - cpuid - bt ecx,30 - mov edi,1 -- exit code: failure - jnc :exit +#ilASM{ + mov eax,1 + cpuid + bt ecx,30 + mov edi,1 -- exit code: failure + jnc :exit - -- rdrand sets CF=0 if no random number - -- was available. Intel documentation - -- recommends 10 retries in a tight loop - mov ecx,11 - ::loop1 - sub ecx, 1 - jz :exit -- exit code is set already - rdrand eax - -- (the above generates exception #C000001D if not supported) - -- rdtsc - jnc :loop1 + -- rdrand sets CF=0 if no random number + -- was available. Intel documentation + -- recommends 10 retries in a tight loop + mov ecx,11 + ::loop1 + sub ecx, 1 + jz :exit -- exit code is set already + rdrand eax + -- (the above generates exception #C000001D if not supported) +-- rdtsc + jnc :loop1 - lea edi,[rint] - call :%pStoreMint - xor edi,edi + lea edi,[rint] + call :%pStoreMint + xor edi,edi - ::exit - mov [res],edi - xor ebx,ebx -- important! - } + ::exit + mov [res],edi + xor ebx,ebx -- important! + } - ?{res,rint} +?{res,rint} - if res=0 then -- (success) +if res=0 then -- (success) - -- - -- To convert a signed 32-bit int to an unsigned one: - -- - -- method 1 - -- atom urint1 = rint - -- if urint1<0 then urint1+=#100000000 end if - atom urint1 = rint+iff(rint<0?#100000000:0) + -- + -- To convert a signed 32-bit int to an unsigned one: + -- + -- method 1 +-- atom urint1 = rint +-- if urint1<0 then urint1+=#100000000 end if + atom urint1 = rint+iff(rint<0?#100000000:0) - -- method 2 - atom pMem = allocate(4) - poke4(pMem,rint) - atom urint2 = peek4u(pMem) - free(pMem) + -- method 2 + atom pMem = allocate(4) + poke4(pMem,rint) + atom urint2 = peek4u(pMem) + free(pMem) - -- method 3 - atom urint3 = bytes_to_int(int_to_bytes(rint,4),signed:=false) + -- method 3 + atom urint3 = bytes_to_int(int_to_bytes(rint,4),signed:=false) - ?{urint1,urint2,urint3} + ?{urint1,urint2,urint3} - end if - - integer fn = open("/dev/urandom","rb") - if fn=-1 then - puts(1,"cannot open /dev/urandom\n") - else - sequence s = {} - for i=1 to 4 do - s &= getc(fn) - end for - close(fn) - ?bytes_to_int(s,signed:=false) - end if - - function RandomNormal() - return sqrt(-2*log(rnd())) * cos(2*PI*rnd()) - end function +with javascript_semantics +requires("1.0.6") -- std_dev +function random_normal() + return sqrt(-2*log(rnd())) * cos(2*PI*rnd()) +end function - sequence s = repeat(0,1000) - for i=1 to length(s) do - s[i] = 1 + 0.5 * RandomNormal() - end for - - with javascript_semantics - function revn(atom n, integer nd) - atom r = 0 - for i=1 to nd do - r = r*10+remainder(n,10) - n = floor(n/10) - end for - return r - end function +with javascript_semantics +function revn(atom n, integer nd) + atom r = 0 + for i=1 to nd do + r = r*10+remainder(n,10) + n = floor(n/10) + end for + return r +end function - integer nd = 2, count = 0 - atom lim = 99, n = 9, t0 = time() - while true do - n += 1 - atom r = revn(n,nd) - if r<n then - atom s = n+r, - d = n-r - if s=power(floor(sqrt(s)),2) - and d=power(floor(sqrt(d)),2) then - count += 1 - printf(1,"%d: %d (%s)\n",{count,n,elapsed(time()-t0)}) - if count=3 then exit end if - end if - end if - if n=lim then - -- ?{"lim",lim,elapsed(time()-t0)} - lim = lim*10+9 - nd += 1 - end if - end while - - with javascript_semantics - constant maxDigits = iff(platform()=JS?10:15) +with javascript_semantics +constant maxDigits = iff(platform()=JS?10:15) - enum COEFF, TDXA, TDXB -- struct term = {atom coeff, integer idxa, idxb} - -- (see allTerms below) - integer nd, -- number of digits - count -- of solutions found earlier, for lower nd - sequence rares -- (cleared after sorting/printing for each nd) +enum COEFF, TDXA, TDXB -- struct term = {atom coeff, integer idxa, idxb} + -- (see allTerms below) +integer nd, -- number of digits + count -- of solutions found earlier, for lower nd +sequence rares -- (cleared after sorting/printing for each nd) - function to_atom(sequence digits) - -- convert digits array to an atom value - atom r = 0 - for i=1 to length(digits) do - r = r * 10 + digits[i] - end for - return r - end function +function to_atom(sequence digits) +-- convert digits array to an atom value + atom r = 0 + for i=1 to length(digits) do + r = r * 10 + digits[i] + end for + return r +end function - -- psq eliminates 52 out of 64 of numbers fairly cheaply, which translates - -- to approximately 66% of numbers, or around 10% off the overall time. - -- NB: only tested to 9,007,199,254,740,991, then again I found no more new - -- bit patterns after just 15^2. +-- psq eliminates 52 out of 64 of numbers fairly cheaply, which translates +-- to approximately 66% of numbers, or around 10% off the overall time. +-- NB: only tested to 9,007,199,254,740,991, then again I found no more new +-- bit patterns after just 15^2. - constant psq = int_to_bits(#02030213,32)& -- #0202021202030213 --> bits, - int_to_bits(#02020212,32) -- in 32/64-bit compatible way. +constant psq = int_to_bits(#02030213,32)& -- #0202021202030213 --> bits, + int_to_bits(#02020212,32) -- in 32/64-bit compatible way. - function isSquare(atom n) -- determine if n is a perfect square or not - if psq[and_bits(n,63)+1] then - atom r = floor(sqrt(n)) - return r * r = n - end if - return false - end function +function isSquare(atom n) -- determine if n is a perfect square or not + if psq[and_bits(n,63)+1] then + atom r = floor(sqrt(n)) + return r * r = n + end if + return false +end function - procedure fnpr(integer level, atom nmr, sequence di, dis, candidates, indices, fml, dmd) - -- generate (n+r) candidates from (n-r) candidates - if level>length(dis) then - sequence digits = repeat(0,nd) - -- (the precise why of how this populates digits has eluded me...) - integer {a,b} = indices[1], - c = candidates[1]+1, - d = di[1]+1 - digits[a] = fml[c][d][1] - digits[b] = fml[c][d][2] - integer le = length(di) - if remainder(nd,2) then - d = floor(nd/2)+1 - digits[d] = di[le] - le -= 1 - end if - for dx=2 to le do - {a,b} = indices[dx] - c = candidates[dx]+10 - d = di[dx]+1 - digits[a] = dmd[c][d][1] - digits[b] = dmd[c][d][2] - end for - atom npr = nmr + to_atom(reverse(digits))*2 -- (npr == 'n + r') - if isSquare(npr) then - rares &= to_atom(digits) - if platform()!=JS then - -- (note this gets overwritten by sorted set:) - printf(1,"working... %2d: %,d\r", {count+length(rares),rares[$]}) - end if - end if - else - di = deep_copy(di) - for n=0 to dis[level] do - di[level] = n - fnpr(level+1, nmr, di, dis, candidates, indices, fml, dmd) - end for - end if - end procedure +procedure fnpr(integer level, atom nmr, sequence di, dis, candidates, indices, fml, dmd) +-- generate (n+r) candidates from (n-r) candidates + if level>length(dis) then + sequence digits = repeat(0,nd) + -- (the precise why of how this populates digits has eluded me...) + integer {a,b} = indices[1], + c = candidates[1]+1, + d = di[1]+1 + digits[a] = fml[c][d][1] + digits[b] = fml[c][d][2] + integer le = length(di) + if remainder(nd,2) then + d = floor(nd/2)+1 + digits[d] = di[le] + le -= 1 + end if + for dx=2 to le do + {a,b} = indices[dx] + c = candidates[dx]+10 + d = di[dx]+1 + digits[a] = dmd[c][d][1] + digits[b] = dmd[c][d][2] + end for + atom npr = nmr + to_atom(reverse(digits))*2 -- (npr == 'n + r') + if isSquare(npr) then + rares &= to_atom(digits) + if platform()!=JS then + -- (note this gets overwritten by sorted set:) + printf(1,"working... %2d: %,d\r", {count+length(rares),rares[$]}) + end if + end if + else + di = deep_copy(di) + for n=0 to dis[level] do + di[level] = n + fnpr(level+1, nmr, di, dis, candidates, indices, fml, dmd) + end for + end if +end procedure - procedure fnmr(sequence terms, list, candidates, indices, fml, dmd, integer level) - -- generate (n-r) candidates with a given number of digits. - if level>length(list) then - atom nmr = 0 -- (nmr == 'n - r') - for i=1 to length(terms) do - nmr += terms[i][COEFF] * candidates[i] - end for - if nmr>0 and isSquare(nmr) then - integer c = candidates[1]+1, - l = length(fml[c])-1 - sequence dis = {l} - for i=2 to length(candidates) do - c = candidates[i]+10 - l = length(dmd[c])-1 - dis = append(dis,l) - end for - if remainder(nd,2) then dis = append(dis,9) end if - -- (above generates dis of eg {1,4,7,9} for nd=7, which as far - -- as I (lightly) understand it scans for far fewer candidate - -- pairs than a {9,9,9,9} would, or something like that.) - sequence di = repeat(0,length(dis)) - -- (di is the current "dis-scan", eg {0,0,0,0} to {1,4,7,9}) - fnpr(1, nmr, di, dis, candidates, indices, fml, dmd) - end if - else - candidates = deep_copy(candidates) - for n=1 to length(list[level]) do - candidates[level] = list[level][n] - fnmr(terms, list, candidates, indices, fml, dmd, level+1) - end for - end if - end procedure +procedure fnmr(sequence terms, list, candidates, indices, fml, dmd, integer level) +-- generate (n-r) candidates with a given number of digits. + if level>length(list) then + atom nmr = 0 -- (nmr == 'n - r') + for i=1 to length(terms) do + nmr += terms[i][COEFF] * candidates[i] + end for + if nmr>0 and isSquare(nmr) then + integer c = candidates[1]+1, + l = length(fml[c])-1 + sequence dis = {l} + for i=2 to length(candidates) do + c = candidates[i]+10 + l = length(dmd[c])-1 + dis = append(dis,l) + end for + if remainder(nd,2) then dis = append(dis,9) end if + -- (above generates dis of eg {1,4,7,9} for nd=7, which as far + -- as I (lightly) understand it scans for far fewer candidate + -- pairs than a {9,9,9,9} would, or something like that.) + sequence di = repeat(0,length(dis)) + -- (di is the current "dis-scan", eg {0,0,0,0} to {1,4,7,9}) + fnpr(1, nmr, di, dis, candidates, indices, fml, dmd) + end if + else + candidates = deep_copy(candidates) + for n=1 to length(list[level]) do + candidates[level] = list[level][n] + fnmr(terms, list, candidates, indices, fml, dmd, level+1) + end for + end if +end procedure - constant dl = tagset(9,-9), -- all differences (-9..+9 by 1) - zl = tagset(0, 0), -- zero difference (0 only) - el = tagset(8,-8, 2), -- even differences (-8 to +8 by 2) - ol = tagset(9,-9, 2), -- odd differences (-9..+9 by 2) - il = tagset(9, 0) -- all integers (0..9 by 1) +constant dl = tagset(9,-9), -- all differences (-9..+9 by 1) + zl = tagset(0, 0), -- zero difference (0 only) + el = tagset(8,-8, 2), -- even differences (-8 to +8 by 2) + ol = tagset(9,-9, 2), -- odd differences (-9..+9 by 2) + il = tagset(9, 0) -- all integers (0..9 by 1) - procedure main() - atom start = time() +procedure main() + atom start = time() - -- terms of (n-r) expression for number of digits from 2 to maxdigits - sequence allTerms = {} - atom pow = 1 - for r=2 to maxDigits do - sequence terms = {} - pow *= 10 - atom p1 = pow, p2 = 1 - integer tdxa = 0, tdxb = r-1 - while tdxa < tdxb do - terms = append(terms,{p1-p2, tdxa, tdxb}) -- {COEFF,TDXA,TDXB} - p1 /= 10 - p2 *= 10 - tdxa += 1 - tdxb -= 1 - end while - allTerms = append(allTerms,terms) - end for - --/* - --(This is what the above loop creates:) - --pp(allTerms,{pp_Nest,1,pp_StrFmt,3,pp_IntCh,false,pp_IntFmt,"%d",pp_FltFmt,"%d",pp_Maxlen,148}) - {{{9,0,1}}, - {{99,0,2}}, - {{999,0,3}, {90,1,2}}, - {{9999,0,4}, {990,1,3}}, - {{99999,0,5}, {9990,1,4}, {900,2,3}}, - {{999999,0,6}, {99990,1,5}, {9900,2,4}}, - {{9999999,0,7}, {999990,1,6}, {99900,2,5}, {9000,3,4}}, - {{99999999,0,8}, {9999990,1,7}, {999900,2,6}, {99000,3,5}}, - {{999999999,0,9}, {99999990,1,8}, {9999900,2,7}, {999000,3,6}, {90000,4,5}}, - {{9999999999,0,10}, {999999990,1,9}, {99999900,2,8}, {9999000,3,7}, {990000,4,6}}, - {{99999999999,0,11}, {9999999990,1,10}, {999999900,2,9}, {99999000,3,8}, {9990000,4,7}, {900000,5,6}}, - {{999999999999,0,12}, {99999999990,1,11}, {9999999900,2,10}, {999999000,3,9}, {99990000,4,8}, {9900000,5,7}}, - {{9999999999999,0,13}, {999999999990,1,12}, {99999999900,2,11}, {9999999000,3,10}, {999990000,4,9}, {99900000,5,8}, {9000000,6,7}}, - {{99999999999999,0,14}, {9999999999990,1,13}, {999999999900,2,12}, {99999999000,3,11}, {9999990000,4,10}, {999900000,5,9}, {99000000,6,8}}} - --*/ + -- terms of (n-r) expression for number of digits from 2 to maxdigits + sequence allTerms = {} + atom pow = 1 + for r=2 to maxDigits do + sequence terms = {} + pow *= 10 + atom p1 = pow, p2 = 1 + integer tdxa = 0, tdxb = r-1 + while tdxa < tdxb do + terms = append(terms,{p1-p2, tdxa, tdxb}) -- {COEFF,TDXA,TDXB} + p1 /= 10 + p2 *= 10 + tdxa += 1 + tdxb -= 1 + end while + allTerms = append(allTerms,terms) + end for +--/* +--(This is what the above loop creates:) +--pp(allTerms,{pp_Nest,1,pp_StrFmt,3,pp_IntCh,false,pp_IntFmt,"%d",pp_FltFmt,"%d",pp_Maxlen,148}) +{{{9,0,1}}, + {{99,0,2}}, + {{999,0,3}, {90,1,2}}, + {{9999,0,4}, {990,1,3}}, + {{99999,0,5}, {9990,1,4}, {900,2,3}}, + {{999999,0,6}, {99990,1,5}, {9900,2,4}}, + {{9999999,0,7}, {999990,1,6}, {99900,2,5}, {9000,3,4}}, + {{99999999,0,8}, {9999990,1,7}, {999900,2,6}, {99000,3,5}}, + {{999999999,0,9}, {99999990,1,8}, {9999900,2,7}, {999000,3,6}, {90000,4,5}}, + {{9999999999,0,10}, {999999990,1,9}, {99999900,2,8}, {9999000,3,7}, {990000,4,6}}, + {{99999999999,0,11}, {9999999990,1,10}, {999999900,2,9}, {99999000,3,8}, {9990000,4,7}, {900000,5,6}}, + {{999999999999,0,12}, {99999999990,1,11}, {9999999900,2,10}, {999999000,3,9}, {99990000,4,8}, {9900000,5,7}}, + {{9999999999999,0,13}, {999999999990,1,12}, {99999999900,2,11}, {9999999000,3,10}, {999990000,4,9}, {99900000,5,8}, {9000000,6,7}}, + {{99999999999999,0,14}, {9999999999990,1,13}, {999999999900,2,12}, {99999999000,3,11}, {9999990000,4,10}, {999900000,5,9}, {99000000,6,8}}} +--*/ - -- map of first minus last digits for 'n' to pairs giving this value - sequence fml = repeat({},10) -- (aka 0..9) - -- (fml == 'first minus last') - fml[1] = {{2, 2}, {8, 8}} - fml[2] = {{6, 5}, {8, 7}} - fml[5] = {{4, 0}} - -- fml[6] = {{8, 3}} -- (um? - needs longer lists, & that append(lists[4],dl) below) - fml[7] = {{6, 0}, {8, 2}} - -- sequence lists = {{{0}},{{1}},{{4}},{{5}},{{6}}} - sequence lists = {{{0}},{{1}},{{4}},{{6}}} - -- map of other digit differences for 'n' to pairs giving this value - sequence dmd = repeat({},19) -- (aka -9..+9, so add 10 when indexing dmd) - -- (dmd == 'digit minus digit') - for tens=0 to 9 do - integer d = tens+10 - for ones=0 to 9 do - dmd[d] = append(dmd[d], {tens,ones}) - d -= 1 - end for - end for - --/* - --(This is what the above loop creates:) - --pp(dmd,{pp_Nest,1,pp_StrFmt,3,pp_IntCh,false}) - {{{0,9}}, - {{0,8}, {1,9}}, - {{0,7}, {1,8}, {2,9}}, - {{0,6}, {1,7}, {2,8}, {3,9}}, - {{0,5}, {1,6}, {2,7}, {3,8}, {4,9}}, - {{0,4}, {1,5}, {2,6}, {3,7}, {4,8}, {5,9}}, - {{0,3}, {1,4}, {2,5}, {3,6}, {4,7}, {5,8}, {6,9}}, - {{0,2}, {1,3}, {2,4}, {3,5}, {4,6}, {5,7}, {6,8}, {7,9}}, - {{0,1}, {1,2}, {2,3}, {3,4}, {4,5}, {5,6}, {6,7}, {7,8}, {8,9}}, - {{0,0}, {1,1}, {2,2}, {3,3}, {4,4}, {5,5}, {6,6}, {7,7}, {8,8}, {9,9}}, - {{1,0}, {2,1}, {3,2}, {4,3}, {5,4}, {6,5}, {7,6}, {8,7}, {9,8}}, - {{2,0}, {3,1}, {4,2}, {5,3}, {6,4}, {7,5}, {8,6}, {9,7}}, - {{3,0}, {4,1}, {5,2}, {6,3}, {7,4}, {8,5}, {9,6}}, - {{4,0}, {5,1}, {6,2}, {7,3}, {8,4}, {9,5}}, - {{5,0}, {6,1}, {7,2}, {8,3}, {9,4}}, - {{6,0}, {7,1}, {8,2}, {9,3}}, - {{7,0}, {8,1}, {9,2}}, - {{8,0}, {9,1}}, - {{9,0}}} - --*/ - count = 0 - printf(1,"digits time nth rare numbers:\n") - nd = 2 - while nd <= maxDigits do - rares = {} - sequence terms = allTerms[nd-1] - if nd=4 then - lists[1] = append(lists[1],zl) - lists[2] = append(lists[2],ol) - lists[3] = append(lists[3],el) - -- lists[4] = append(lists[4],dl) -- if fml[6] = {{8, 3}} - -- lists[5] = append(lists[5],ol) -- "" - -- lists[4] = append(lists[4],ol) -- else - lists[4] = append(deep_copy(lists[4]),ol) -- else - elsif length(terms)>length(lists[1]) then - for i=1 to length(lists) do - -- lists[i] = append(lists[i],dl) - lists[i] = append(deep_copy(lists[i]),dl) - end for - end if - sequence indices = {} - for t=1 to length(terms) do - sequence term = terms[t] - -- (we may as well make this 1-based while here) - indices = append(indices,{term[TDXA]+1,term[TDXB]+1}) - end for - for i=1 to length(lists) do - sequence list = lists[i], - candidates = repeat(0,length(list)) - fnmr(terms, list, candidates, indices, fml, dmd, 1) - end for - -- (re-)output partial results for this nd-set in sorted order: - -- rares = sort(rares) - rares = sort(deep_copy(rares)) - for i=1 to length(rares) do - count += 1 - printf(1,"%12s %2d: %,19d \n", {"",count,rares[i]}) - end for - printf(1," %2d %5s\n", {nd, elapsed_short(time()-start)}) - nd += 1 - end while - end procedure - main() -HIGH*/ +arr=random(low,high,seed) /* ... with a seed (to make repeatable)*/ + +mzp=sign(x) /*finds the sign of x (-1, 0, +1). */ + + fs=format(x) /*formats X with the current DIGITS() */ + fb=format(x,bbb) /* BBB digs before decimal*/ + fa=format(x,bbb,aaa) /* AAA digs after decimal*/ + fa=format(x,,0) /* rounds X to an integer.*/ + fe=format(x,,eee) /* exponent has eee places. */ + ft=format(x,,eee,ttt) /*if x exceeds TTT digits, force exp. */ + +hh=b2x(bbb) /*converts binary/bits to hexadecimal. */ +dd=c2d(ccc) /*converts character to decimal. */ +hh=c2x(ccc) /*converts character to hexadecimal. */ +cc=d2c(ddd) /*converts decimal to character. */ +hh=d2x(ddd) /*converts decimal to hexadecimal. */ +bb=x2b(hhh) /*converts hexadecimal to binary (bits)*/ +cc=x2c(hhh) /*converts hexadecimal to character. */ +dd=x2d(hhh) /*converts hexadecimal to decimal. */ diff --git a/Task/Real-constants-and-functions/REXX/real-constants-and-functions-4.rexx b/Task/Real-constants-and-functions/REXX/real-constants-and-functions-4.rexx index 794b93d5b4..0cae458604 100644 --- a/Task/Real-constants-and-functions/REXX/real-constants-and-functions-4.rexx +++ b/Task/Real-constants-and-functions/REXX/real-constants-and-functions-4.rexx @@ -1 +1,20 @@ -floor: procedure; parse arg x; t=trunc(x); return t-(x<0)-(x\=t) +-- 24 Aug 2025 +include Setting + +say 'REAL CONSTANTS AND FUNCTIONS' +say version +say +numeric digits 16 +say 'e =' E()+0 +say 'pi =' Pi()+0 +say 'square root 7 =' SqRt(7)+0 +say 'log 7 base e =' Log(7)+0 +say 'log 7 base 10 =' Log10(7)+0 +say 'log 7 base 2 =' LogXY(7,2)+0 +say 'exponential 7 =' Exp(7)+0 +say '1/2^3/4 =' Power(1/2,3/4)+0 +say 'floor 4/3 =' Floor(4/3) +say 'ceiling 4/3 =' Ceil(4/3) +exit + +include Math diff --git a/Task/Real-constants-and-functions/REXX/real-constants-and-functions-5.rexx b/Task/Real-constants-and-functions/REXX/real-constants-and-functions-5.rexx deleted file mode 100644 index 60530b123b..0000000000 --- a/Task/Real-constants-and-functions/REXX/real-constants-and-functions-5.rexx +++ /dev/null @@ -1,27 +0,0 @@ -/*──────────────────────────────────SQRT subroutine───────────────────────────*/ -sqrt: procedure; parse arg x; if x=0 then return 0 /*handle 0 case.*/ -if \datatype(x,'N') then return '[n/a]' /*Not Applicable ───if not numeric.*/ -i=; if x<0 then do; x=-x; i='i'; end /*handle complex numbers if X is < 0.*/ -d=digits() /*get the current numeric precision. */ -m.=9 /*technique uses just enough digits. */ -h=d+6 /*use extra decimal digits for accuracy*/ -numeric digits 9 /*use "small" precision at first. */ -numeric form /*force scientific form of the number. */ -if fuzz()\==0 then numeric fuzz 0 /*just in case invoker has a FUZZ set.*/ -parse value format(x,2,1,,0) 'E0' with g 'E' _ . /*get the X's exponent.*/ - g=(g * .5) || 'e' || (_ % 2) /*1st guesstimate for the square root. */ - /* g= g * .5 'e' (_ % 2) */ /*a shorter & concise version of above.*/ - /*Note: to insure enough accuracy for */ - /* the result, the precision during */ - /* the SQRT calculations is increased */ - /* by two extra decimal digits. */ - do j=0 while h>9; m.j=h; h=h%2+1 /*compute the sizes (digs) of precision*/ - end /*j*/ /* [↑] precisions are stored in M. */ - /*now, we start to do the heavy lifting*/ - do k=j+5 to 0 by -1 /*compute the √ with increasing digs.*/ - numeric digits m.k /*each iteration, increase the digits. */ - g=(g+x/g) * .5 /*perform the nitty-gritty calculations*/ - end /*k*/ /* [↑] * .5 is faster than / 2 */ - /* [↓] normalize √ ──► original digits*/ -numeric digits d /* [↓] make answer complex if X < 0. */ -return (g/1)i /*normalize, and add possible I suffix.*/ diff --git a/Task/Real-constants-and-functions/REXX/real-constants-and-functions-6.rexx b/Task/Real-constants-and-functions/REXX/real-constants-and-functions-6.rexx deleted file mode 100644 index 1ac457905c..0000000000 --- a/Task/Real-constants-and-functions/REXX/real-constants-and-functions-6.rexx +++ /dev/null @@ -1,26 +0,0 @@ - ╔════════════════════════════════════════════════════════════════════╗ -╔═╝ __ ╚═╗ -║ √ ║ -║ ║ -║ While the above REXX code seems like it's doing a lot of extra work, ║ -║ it saves a substantial amount of processing time when the precision ║ -║ (DIGITs) is a lot greater than the default (default is nine digits). ║ -║ ║ -║ Indeed, when computing square roots in the hundreds (even thousands) ║ -║ of digits, this technique reduces the amount of CPU processing time ║ -║ by keeping the length of the computations to a minimum (due to a large ║ -║ precision), while the accuracy at the beginning isn't important for ║ -║ calculating the (first) guesstimate (the running square root guess). ║ -║ ║ -║ Each iteration of K (approximately) doubles the number of digits, ║ -║ but takes almost four times longer to compute (actually, around 3.8). ║ -║ ║ -║ The REXX code could be streamlined (pruned) by removing the ║ -║ The NUMERIC FUZZ 0 statement can be removed if it is known ║ -║ that it is already set to zero. (which is the default). ║ -║ ║ -║ Also, the NUMERIC FORM statement can be removed if it is known ║ -║ that the form is SCIENTIFIC (which is the default). ║ -║ __ ║ -╚═╗ √ ╔═╝ - ╚════════════════════════════════════════════════════════════════════╝ diff --git a/Task/Real-constants-and-functions/REXX/real-constants-and-functions-7.rexx b/Task/Real-constants-and-functions/REXX/real-constants-and-functions-7.rexx deleted file mode 100644 index 6d3d413b63..0000000000 --- a/Task/Real-constants-and-functions/REXX/real-constants-and-functions-7.rexx +++ /dev/null @@ -1,14 +0,0 @@ -/*──────────────────────────────────SQRT subroutine─────────────────────*/ -sqrt: procedure; arg x /*a simplistic SQRT subroutine.*/ -if x=0 then return 0 /*handle special case of zero. */ -d=digits() /*get the current precision (dig)*/ -numeric digits d+2 /*ensure extra precision (2 digs)*/ -g=x/4 /*try get a so-so 1st guesstimate*/ -old=0 /*set OLD guess to zero. */ - do forever /*keep at it 'til G (guess)=old.*/ - g=(g+x/g) / 2 /*do the nitty-gritty calculation*/ - if g=old then leave /*if G is the same as old, quit. */ - old=g /*save OLD for next iteration. */ - end /*forever*/ /* [↑] ···'til we run out of digs*/ -numeric digits d /*restore the original precision.*/ -return g/1 /*normalize to old precision (d).*/ diff --git a/Task/Real-constants-and-functions/REXX/real-constants-and-functions-8.rexx b/Task/Real-constants-and-functions/REXX/real-constants-and-functions-8.rexx deleted file mode 100644 index abb4b2d2f1..0000000000 --- a/Task/Real-constants-and-functions/REXX/real-constants-and-functions-8.rexx +++ /dev/null @@ -1,27 +0,0 @@ -numeric digits ddd /*sets the current precision to DDD */ -numeric fuzz fff /*arithmetic comparisons with FFF fuzzy*/ -numeric form kkk /*exponential: scientific | engineering*/ - -low=min(a,b,c,d,e,f,g, ...) /*finds the min of specified arguments.*/ -big=min(a,b,c,d,e,f,g, ...) /*finds the max of specified arguments.*/ - -rrr=random(low,high) /*gets a random integer from LOW-->HIGH*/ -arr=random(low,high,seed) /* ... with a seed (to make repeatable)*/ - -mzp=sign(x) /*finds the sign of x (-1, 0, +1). */ - - fs=format(x) /*formats X with the current DIGITS() */ - fb=format(x,bbb) /* BBB digs before decimal*/ - fa=format(x,bbb,aaa) /* AAA digs after decimal*/ - fa=format(x,,0) /* rounds X to an integer.*/ - fe=format(x,,eee) /* exponent has eee places. */ - ft=format(x,,eee,ttt) /*if x exceeds TTT digits, force exp. */ - -hh=b2x(bbb) /*converts binary/bits to hexadecimal. */ -dd=c2d(ccc) /*converts character to decimal. */ -hh=c2x(ccc) /*converts character to hexadecimal. */ -cc=d2c(ddd) /*converts decimal to character. */ -hh=d2x(ddd) /*converts decimal to hexadecimal. */ -bb=x2b(hhh) /*converts hexadecimal to binary (bits)*/ -cc=x2c(hhh) /*converts hexadecimal to character. */ -dd=x2d(hhh) /*converts hexadecimal to decimal. */ diff --git a/Task/Real-constants-and-functions/Run-BASIC/real-constants-and-functions.basic b/Task/Real-constants-and-functions/Run-BASIC/real-constants-and-functions.basic index 0fa682fa9d..5773a8fa83 100644 --- a/Task/Real-constants-and-functions/Run-BASIC/real-constants-and-functions.basic +++ b/Task/Real-constants-and-functions/Run-BASIC/real-constants-and-functions.basic @@ -1,5 +1,5 @@ print "exp:";chr$(9); EXP(1) -print "PI:";chr$(9); 22/7 +print "PI:";chr$(9); 4 * ATN(1) print "Sqr2:";chr$(9); SQR(2) print "Log2:";chr$(9); LOG(2) : REM Base 10 print "Exp2:";chr$(9); EXP(2) diff --git a/Task/Real-constants-and-functions/Rust/real-constants-and-functions.rust b/Task/Real-constants-and-functions/Rust/real-constants-and-functions.rs similarity index 100% rename from Task/Real-constants-and-functions/Rust/real-constants-and-functions.rust rename to Task/Real-constants-and-functions/Rust/real-constants-and-functions.rs diff --git a/Task/Real-constants-and-functions/S-BASIC/real-constants-and-functions.basic b/Task/Real-constants-and-functions/S-BASIC/real-constants-and-functions.basic new file mode 100644 index 0000000000..29d7d6cbf4 --- /dev/null +++ b/Task/Real-constants-and-functions/S-BASIC/real-constants-and-functions.basic @@ -0,0 +1,28 @@ +print "Square root of 2.7 ="; sqr(2.7) +print "Natural log of 2.7 ="; log(2.7) +print "Exp() of 2.7 ="; exp(2.7) +print "Absolute value of -2.7 ="; abs(-2.7) +print "Floor of 2.7 ="; int(2.7) +print "Floor of -2.7 ="; int(-2.7) +print "2.7 to the 3rd power ="; 2.7 ^ 3 rem or 2.7 ** 3 + +comment + e, pi, and ceiling() are not built-in, but are + easily implemented +end + +function e = real +end = exp(1.0) + +function pi = real +end = atn(1.0) * 4.0 + +function ceil(x = real) = real +end = int(x) + 1 + +print "e ="; e +print "pi ="; pi +print "ceiling of 2.7 = "; ceil(2.7) +print "ceiling of -2.7 = "; ceil(-2.7) + +end diff --git a/Task/Real-constants-and-functions/Scheme/real-constants-and-functions.ss b/Task/Real-constants-and-functions/Scheme/real-constants-and-functions.scm similarity index 100% rename from Task/Real-constants-and-functions/Scheme/real-constants-and-functions.ss rename to Task/Real-constants-and-functions/Scheme/real-constants-and-functions.scm diff --git a/Task/Real-constants-and-functions/Standard-ML/real-constants-and-functions.ml b/Task/Real-constants-and-functions/Standard-ML/real-constants-and-functions.ml index 73fdedeed4..497596d5b3 100644 --- a/Task/Real-constants-and-functions/Standard-ML/real-constants-and-functions.ml +++ b/Task/Real-constants-and-functions/Standard-ML/real-constants-and-functions.ml @@ -1,10 +1,11 @@ -Math.e; (* e *) -Math.pi; (* pi *) -Math.sqrt x; (* square root *) -Math.ln x; (* natural logarithm--log base 10 also available (Math.log10) *) -Math.exp x; (* exponential *) -abs x; (* absolute value *) -floor x; (* floor *) -ceil x; (* ceiling *) -Math.pow (x, y); (* power *) -~ x; (* negation *) +Math.e (* e *) +Math.pi (* pi *) +(* Math.tau also available in some implementations *) +Math.sqrt x (* square root *) +Math.ln x (* natural logarithm--log base 10 also available (Math.log10) *) +Math.exp ; (* exponential *) +abs x (* absolute value *) +floor x (* floor *) +ceil x (* ceiling *) +Math.pow (x, y) (* power *) +~x (* negation *) diff --git a/Task/Real-constants-and-functions/TAV/real-constants-and-functions.tav b/Task/Real-constants-and-functions/TAV/real-constants-and-functions.tav new file mode 100644 index 0000000000..db0c7d7810 --- /dev/null +++ b/Task/Real-constants-and-functions/TAV/real-constants-and-functions.tav @@ -0,0 +1,13 @@ + print 'pi =', #Pi + print 'e =', #E + x =: 12.3456 + y =: 1.11 + print 'x =', x, 'y =', y + print 'sqrt(x) =', math sqrt x + print 'log(x) =', math log x \ base e + print 'log10(x) =', math lg x \ base 10 + print 'exp(x) =', math exp x + print 'abs(x) =', x.abs + print 'floor(x) =', x.floor + print 'ceil(x) =', x.ceil + print 'x ^ y =', x ^ y diff --git a/Task/Real-constants-and-functions/Uiua/real-constants-and-functions.uiua b/Task/Real-constants-and-functions/Uiua/real-constants-and-functions.uiua new file mode 100644 index 0000000000..f06067f2ed --- /dev/null +++ b/Task/Real-constants-and-functions/Uiua/real-constants-and-functions.uiua @@ -0,0 +1,10 @@ +x ← 2.5 +π # pi +√x # sqrt +e # e +ₑ x # natural logarithm +ₑ₁₀ x # logarithm to base 10 +⌵ x # absolute value +⌊x # floor +⌈x # ceiling +ⁿ 3 x # power - x to power 3 diff --git a/Task/Real-constants-and-functions/XBasic/real-constants-and-functions.basic b/Task/Real-constants-and-functions/XBasic/real-constants-and-functions.basic index 43fe0011ee..877869db73 100644 --- a/Task/Real-constants-and-functions/XBasic/real-constants-and-functions.basic +++ b/Task/Real-constants-and-functions/XBasic/real-constants-and-functions.basic @@ -1,4 +1,4 @@ -PROGRAM "progname" +PROGRAM "realcaf" VERSION "0.0000" IMPORT "xma" @@ -9,15 +9,12 @@ DECLARE FUNCTION Floor (x) FUNCTION Entry () DOUBLE e, pi, x, y - e = EXP(1) PRINT "e = "; e ' e not available pi = 4 * ATAN(1) PRINT "pi = "; pi ' pi not available - x = 12.345 y = 1.23 - PRINT "sqrt = "; SQRT (x) ' square root PRINT "ln = "; LOG (x) ' natural logarithm base e PRINT "log10 = "; LOG10 (x) ' base 10 logarithm diff --git a/Task/Recamans-sequence/Arturo/recamans-sequence.arturo b/Task/Recamans-sequence/Arturo/recamans-sequence.arturo index 29e7824206..a21acdb5a9 100644 --- a/Task/Recamans-sequence/Arturo/recamans-sequence.arturo +++ b/Task/Recamans-sequence/Arturo/recamans-sequence.arturo @@ -5,9 +5,9 @@ recamanSucc: function [seen, n, r].memoize[ ] recamanUntil: function [p][ - n: new 1 + n: 1 r: 0 - rs: new @[r] + rs: @[r] seen: rs blnNew: true while [not? do p][ diff --git a/Task/Recamans-sequence/COBOL/recamans-sequence.cobol b/Task/Recamans-sequence/COBOL/recamans-sequence.cob similarity index 100% rename from Task/Recamans-sequence/COBOL/recamans-sequence.cobol rename to Task/Recamans-sequence/COBOL/recamans-sequence.cob diff --git a/Task/Recamans-sequence/EasyLang/recamans-sequence.easy b/Task/Recamans-sequence/EasyLang/recamans-sequence.easy index 3c3394e248..fc839beebe 100644 --- a/Task/Recamans-sequence/EasyLang/recamans-sequence.easy +++ b/Task/Recamans-sequence/EasyLang/recamans-sequence.easy @@ -1,17 +1,15 @@ -arrbase a[] 0 -arrbase seen[] 0 len seen[] 100 # a[] &= 0 -seen[0] = 1 +seen[1] = 1 i = 1 repeat - h = a[i - 1] - i - if h <= 0 or seen[h] = 1 - h = a[i - 1] + i + h = a[i - 1 + 1] - i + if h <= 0 or seen[h + 1] = 1 + h = a[i - 1 + 1] + i . - until seen[h] = 1 - seen[h] = 1 + until seen[h + 1] = 1 + seen[h + 1] = 1 a[] &= h if i = 14 print a[] diff --git a/Task/Recamans-sequence/Haskell/recamans-sequence-2.hs b/Task/Recamans-sequence/Haskell/recamans-sequence-2.hs index b7263ccd28..b1e6f2c5bc 100644 --- a/Task/Recamans-sequence/Haskell/recamans-sequence-2.hs +++ b/Task/Recamans-sequence/Haskell/recamans-sequence-2.hs @@ -1,42 +1,8 @@ -import Data.Set (Set, fromList, insert, isSubsetOf, member, size) -import Data.Bool (bool) - -firstNRecamans :: Int -> [Int] -firstNRecamans n = reverse $ recamanUpto (\(_, i, _) -> n == i) - -firstDuplicateR :: Int -firstDuplicateR = head $ recamanUpto (\(rs, _, set) -> size set /= length rs) - -recamanSuperset :: Set Int -> [Int] -recamanSuperset setInts = - tail $ recamanUpto (\(_, _, setR) -> isSubsetOf setInts setR) - -recamanUpto :: (([Int], Int, Set Int) -> Bool) -> [Int] -recamanUpto p = rs - where - (rs, _, _) = - until - p - (\(rs@(r:_), i, seen) -> - let n = nextR seen i r - in (n : rs, succ i, insert n seen)) - ([0], 1, fromList [0]) - -nextR :: Set Int -> Int -> Int -> Int -nextR seen i r = - let back = r - i - in bool back (r + i) (0 > back || member back seen) - --- TEST --------------------------------------------------------------- -main :: IO () -main = - (putStrLn . unlines) - [ "First 15 Recamans:" - , show $ firstNRecamans 15 - , [] - , "First duplicated Recaman:" - , show firstDuplicateR - , [] - , "Length of Recaman series required to include [0..1000]:" - , (show . length . recamanSuperset) $ fromList [0 .. 1000] - ] +recaman :: Integer -> [Integer] +recaman n = reverse (go 0 0 []) + where + go i a_n xs | i > n = xs + | (am > 0) && (not (any (am ==) xs)) = go (i + 1) am (am : xs) + | otherwise = go (i + 1) ap (ap : xs) + where am = a_n - (i + 1) + ap = a_n + (i + 1) diff --git a/Task/Recamans-sequence/Haskell/recamans-sequence-3.hs b/Task/Recamans-sequence/Haskell/recamans-sequence-3.hs index 01113e4b84..b7263ccd28 100644 --- a/Task/Recamans-sequence/Haskell/recamans-sequence-3.hs +++ b/Task/Recamans-sequence/Haskell/recamans-sequence-3.hs @@ -1,47 +1,42 @@ -import Data.List (find, findIndex, nub) -import Data.Maybe (fromJust) -import Data.Set (Set, fromList, insert, isSubsetOf, member) +import Data.Set (Set, fromList, insert, isSubsetOf, member, size) +import Data.Bool (bool) ---- INFINITE STREAM OF RECAMAN SERIES OF GROWING LENGTH -- -rSeries :: [[Int]] -rSeries = - scanl - ( \rs@(r : _) i -> - let back = r - i - nxt - | 0 > back || elem back rs = r + i - | otherwise = back - in nxt : rs - ) - [0] - [1 ..] +firstNRecamans :: Int -> [Int] +firstNRecamans n = reverse $ recamanUpto (\(_, i, _) -> n == i) ------------ INFINITE STREAM OF RECAMAN-GENERATED --------- ---------------- INTEGER SETS OF GROWING SIZE ------------- -rSets :: [(Set Int, Int)] -rSets = - scanl - ( \(seen, r) i -> - let back = r - i - nxt - | 0 > back || member back seen = r + i - | otherwise = back - in (insert nxt seen, nxt) - ) - (fromList [0], 0) - [1 ..] +firstDuplicateR :: Int +firstDuplicateR = head $ recamanUpto (\(rs, _, set) -> size set /= length rs) ---------------------------- TEST ------------------------- +recamanSuperset :: Set Int -> [Int] +recamanSuperset setInts = + tail $ recamanUpto (\(_, _, setR) -> isSubsetOf setInts setR) + +recamanUpto :: (([Int], Int, Set Int) -> Bool) -> [Int] +recamanUpto p = rs + where + (rs, _, _) = + until + p + (\(rs@(r:_), i, seen) -> + let n = nextR seen i r + in (n : rs, succ i, insert n seen)) + ([0], 1, fromList [0]) + +nextR :: Set Int -> Int -> Int -> Int +nextR seen i r = + let back = r - i + in bool back (r + i) (0 > back || member back seen) + +-- TEST --------------------------------------------------------------- main :: IO () -main = do - let setK = fromList [0 .. 1000] +main = (putStrLn . unlines) - [ "First 15 Recamans:", - show . reverse . fromJust $ find ((15 ==) . length) rSeries, - [], - "First duplicated Recaman:", - show . head . fromJust $ find ((/=) <$> length <*> (length . nub)) rSeries, - [], - "Length of Recaman series required to include [0..1000]:", - show . fromJust $ findIndex (\(setR, _) -> isSubsetOf setK setR) rSets + [ "First 15 Recamans:" + , show $ firstNRecamans 15 + , [] + , "First duplicated Recaman:" + , show firstDuplicateR + , [] + , "Length of Recaman series required to include [0..1000]:" + , (show . length . recamanSuperset) $ fromList [0 .. 1000] ] diff --git a/Task/Recamans-sequence/Haskell/recamans-sequence-4.hs b/Task/Recamans-sequence/Haskell/recamans-sequence-4.hs new file mode 100644 index 0000000000..01113e4b84 --- /dev/null +++ b/Task/Recamans-sequence/Haskell/recamans-sequence-4.hs @@ -0,0 +1,47 @@ +import Data.List (find, findIndex, nub) +import Data.Maybe (fromJust) +import Data.Set (Set, fromList, insert, isSubsetOf, member) + +--- INFINITE STREAM OF RECAMAN SERIES OF GROWING LENGTH -- +rSeries :: [[Int]] +rSeries = + scanl + ( \rs@(r : _) i -> + let back = r - i + nxt + | 0 > back || elem back rs = r + i + | otherwise = back + in nxt : rs + ) + [0] + [1 ..] + +----------- INFINITE STREAM OF RECAMAN-GENERATED --------- +--------------- INTEGER SETS OF GROWING SIZE ------------- +rSets :: [(Set Int, Int)] +rSets = + scanl + ( \(seen, r) i -> + let back = r - i + nxt + | 0 > back || member back seen = r + i + | otherwise = back + in (insert nxt seen, nxt) + ) + (fromList [0], 0) + [1 ..] + +--------------------------- TEST ------------------------- +main :: IO () +main = do + let setK = fromList [0 .. 1000] + (putStrLn . unlines) + [ "First 15 Recamans:", + show . reverse . fromJust $ find ((15 ==) . length) rSeries, + [], + "First duplicated Recaman:", + show . head . fromJust $ find ((/=) <$> length <*> (length . nub)) rSeries, + [], + "Length of Recaman series required to include [0..1000]:", + show . fromJust $ findIndex (\(setR, _) -> isSubsetOf setK setR) rSets + ] diff --git a/Task/Recamans-sequence/Jq/recamans-sequence-1.jq b/Task/Recamans-sequence/Jq/recamans-sequence-1.jq index 8006cb51db..ed379e4ce4 100644 --- a/Task/Recamans-sequence/Jq/recamans-sequence-1.jq +++ b/Task/Recamans-sequence/Jq/recamans-sequence-1.jq @@ -27,17 +27,17 @@ def recaman_required($capture): | if .n < $capture then .a += [.current] else . end | if ($alreadyUsed|not) then .used[$s] = true - | if (.current >= 0 and .current <= $required) - then .found[$s] = true | .nfound+=1 - else . end + | if (.current >= 0 and .current <= $required) + then .found[$s] = true | .nfound+=1 + else . end else . - end + end | if (.foundDup|not) and $alreadyUsed then .foundDup = .current - | .foundDupAt = .n + | .foundDupAt = .n else . - end ); - + end ); + 1000 as $required | 15 as $capture | $required | recaman_required($capture) diff --git a/Task/Recamans-sequence/Jq/recamans-sequence-2.jq b/Task/Recamans-sequence/Jq/recamans-sequence-2.jq index b31c80a0fc..2663840b34 100644 --- a/Task/Recamans-sequence/Jq/recamans-sequence-2.jq +++ b/Task/Recamans-sequence/Jq/recamans-sequence-2.jq @@ -24,11 +24,11 @@ def covers(s): . as $required | first(foreach s as $x ( { i: -1, found: {}, nfound: 0}; .i += 1 - | ($x|tostring) as $xs + | ($x|tostring) as $xs | if .found[$xs] then . - elif $x <= $required - then .found[$xs] = true | .nfound += 1 - | if .nfound > $required then .emit=.i else . end - else . - end; + elif $x <= $required + then .found[$xs] = true | .nfound += 1 + | if .nfound > $required then .emit=.i else . end + else . + end; select(.emit).emit) ); diff --git a/Task/Recamans-sequence/Julia/recamans-sequence.julia b/Task/Recamans-sequence/Julia/recamans-sequence.jl similarity index 100% rename from Task/Recamans-sequence/Julia/recamans-sequence.julia rename to Task/Recamans-sequence/Julia/recamans-sequence.jl diff --git a/Task/Recamans-sequence/Kotlin/recamans-sequence.kotlin b/Task/Recamans-sequence/Kotlin/recamans-sequence.kts similarity index 100% rename from Task/Recamans-sequence/Kotlin/recamans-sequence.kotlin rename to Task/Recamans-sequence/Kotlin/recamans-sequence.kts diff --git a/Task/Recamans-sequence/Lua/recamans-sequence.lua b/Task/Recamans-sequence/Lua/recamans-sequence.lua index cce79fd370..d3cd3d2970 100644 --- a/Task/Recamans-sequence/Lua/recamans-sequence.lua +++ b/Task/Recamans-sequence/Lua/recamans-sequence.lua @@ -1,10 +1,11 @@ local a = {[0]=0} local used = {[0]=true} local used1000 = {[0]=true} +local count1000 = 1 local foundDup = false local n = 1 -while n<=15 or not foundDup or #used1000<1001 do +while n<=15 or not foundDup or count1000 <1001 do local nxt = a[n - 1] - n if nxt<1 or used[nxt] ~= nil then nxt = nxt + 2 * n @@ -14,7 +15,10 @@ while n<=15 or not foundDup or #used1000<1001 do if not alreadyUsed then used[nxt] = true if 0<=nxt and nxt<=1000 then - used1000[nxt] = true + if not used1000[nxt] then + used1000[nxt] = true + count1000 = count1000 + 1 + end end end if n==14 then @@ -28,7 +32,7 @@ while n<=15 or not foundDup or #used1000<1001 do print("The first duplicated term is a["..n.."] = "..nxt) foundDup = true end - if #used1000 == 1001 then + if count1000 == 1001 then print("Terms up to a["..n.."] are needed to generate 0 to 1000") end n = n + 1 diff --git a/Task/Recamans-sequence/PHP/recamans-sequence.php b/Task/Recamans-sequence/PHP/recamans-sequence.php index 31e5a65893..4843746735 100644 --- a/Task/Recamans-sequence/PHP/recamans-sequence.php +++ b/Task/Recamans-sequence/PHP/recamans-sequence.php @@ -12,34 +12,34 @@ $foundDup = false; $n = 1; while($n <= 15 || !$foundDup || count($used1000) < 1001) { - $next = $a[$n - 1] - $n; - if ($next < 1 || in_array($next, $used)) { - $next += 2 * $n; - } - $alreadyUsed = in_array($next, $used); - array_push($a, $next); - if (!$alreadyUsed) { - array_push($used, $next); - if (0 <= $next && $next <= 1000) { - array_push($used1000, $next); - } - } - if ($n == 14) { - echo "The first 15 terms of the Recaman sequence are : ["; - foreach($a as $i => $v) { - if ( $i == count($a) - 1) - echo "$v"; - else - echo "$v, "; - } - echo "]\n"; - } - if (!$foundDup && $alreadyUsed) { - printf("The first duplicate term is a[%d] = %d\n", $n, $next); - $foundDup = true; - } - if (count($used1000) == 1001) { - printf("Terms up to a[%d] are needed to generate 0 to 1000\n", $n); - } - $n++; + $next = $a[$n - 1] - $n; + if ($next < 1 || in_array($next, $used)) { + $next += 2 * $n; + } + $alreadyUsed = in_array($next, $used); + array_push($a, $next); + if (!$alreadyUsed) { + array_push($used, $next); + if (0 <= $next && $next <= 1000) { + array_push($used1000, $next); + } + } + if ($n == 14) { + echo "The first 15 terms of the Recaman sequence are : ["; + foreach($a as $i => $v) { + if ( $i == count($a) - 1) + echo "$v"; + else + echo "$v, "; + } + echo "]\n"; + } + if (!$foundDup && $alreadyUsed) { + printf("The first duplicate term is a[%d] = %d\n", $n, $next); + $foundDup = true; + } + if (count($used1000) == 1001) { + printf("Terms up to a[%d] are needed to generate 0 to 1000\n", $n); + } + $n++; } diff --git a/Task/Recamans-sequence/Pluto/recamans-sequence.pluto b/Task/Recamans-sequence/Pluto/recamans-sequence.pluto new file mode 100644 index 0000000000..e9be70d1fc --- /dev/null +++ b/Task/Recamans-sequence/Pluto/recamans-sequence.pluto @@ -0,0 +1,28 @@ +require "map" + +local a = {0} +local used = set.of(0) +local used1000 = set.of(0) +local found_dup = false +local n = 1 +while n <= 15 or !found_dup or used1000:size() < 1001 do + local nxt = a[n] - n + if nxt < 1 or used:contains(nxt) then nxt += 2 * n end + local already_used = used:contains(nxt) + a:insert(nxt) + if !already_used then + used:add(nxt) + if 0 <= nxt <= 1000 then used1000:add(nxt) end + end + if n == 14 then + print($"The first 15 terms of the Recaman's sequence are:\n{a:concat(", ")}") + end + if !found_dup and already_used then + print($"The first duplicated term is a[{n}] = {nxt}") + found_dup = true + end + if used1000:size() == 1001 then + print($"Terms up to a[{n}] are needed to generate 0 to 1000") + end + n += 1 +end diff --git a/Task/Recamans-sequence/R/recamans-sequence.r b/Task/Recamans-sequence/R/recamans-sequence.r index bfab97390f..f6346853e0 100644 --- a/Task/Recamans-sequence/R/recamans-sequence.r +++ b/Task/Recamans-sequence/R/recamans-sequence.r @@ -3,12 +3,12 @@ visited <- vector('logical', 1e8) terms <- vector('numeric') in_a_interval <- function(v) { - visited[[v+1]] + visited[[v+1]] } add_value <- function(v) { - visited[[v+1]] <<- TRUE - terms <<- append(terms, v) + visited[[v+1]] <<- TRUE + terms <<- append(terms, v) } add_value(0) @@ -18,24 +18,24 @@ value <- 0 founddup <- FALSE repeat { - if ((value-step>0) && (!in_a_interval(value-step))) { - value <- value - step - } else { - value <- value + step - } - if (in_a_interval(value) && !founddup) { - cat("The first duplicated term is a[",step,"] = ",value,"\n", sep = "") - founddup <- TRUE - } - add_value(value) - if (all(visited[1:1000])) { - cat("Terms up to a[",step,"] are needed to generate 0 to 1000\n",sep = "") - break - } - step <- step + 1 - if (step == 15) { - cat("The first 15 terms are :") - for (aterm in terms) { cat(aterm," ", sep = "") } - cat("\n") - } + if ((value-step>0) && (!in_a_interval(value-step))) { + value <- value - step + } else { + value <- value + step + } + if (in_a_interval(value) && !founddup) { + cat("The first duplicated term is a[",step,"] = ",value,"\n", sep = "") + founddup <- TRUE + } + add_value(value) + if (all(visited[1:1000])) { + cat("Terms up to a[",step,"] are needed to generate 0 to 1000\n",sep = "") + break + } + step <- step + 1 + if (step == 15) { + cat("The first 15 terms are :") + for (aterm in terms) { cat(aterm," ", sep = "") } + cat("\n") + } } diff --git a/Task/Recamans-sequence/Rebol/recamans-sequence.rebol b/Task/Recamans-sequence/Rebol/recamans-sequence.rebol new file mode 100644 index 0000000000..aef22a9045 --- /dev/null +++ b/Task/Recamans-sequence/Rebol/recamans-sequence.rebol @@ -0,0 +1,31 @@ +Rebol [ + title: "Rosetta code: Recaman's sequence" + file: %Recaman's_sequence.r3 + url: https://rosettacode.org/wiki/Recaman%27s_sequence +] + +recaman-until: function/with [code [block!]][ + r: 0 n: 1 + result: reduce [r] ;; result sequence + seen: reduce [r] ;; set of visited values for O(1) duplicate check + bind code 'n + until [ + append result r: recaman-succ seen n r + if new?: not find seen r [ append seen r ] + ++ n + do code ;; evaluate stop condition with current n in scope + ] + result +][ + recaman-succ: function [seen [block!] n [integer!] r [integer!]][ + back: r - n + ;; go back if positive and not already seen, otherwise go forward + either any [back < 0 find seen back] [r + n] [back] + ] +] + +print "First 15 Recaman numbers:" +print recaman-until [n = 15] +print "" +print "First duplicate Recaman number:" +print last recaman-until [not new?] diff --git a/Task/Recamans-sequence/Rust/recamans-sequence.rust b/Task/Recamans-sequence/Rust/recamans-sequence.rs similarity index 100% rename from Task/Recamans-sequence/Rust/recamans-sequence.rust rename to Task/Recamans-sequence/Rust/recamans-sequence.rs diff --git a/Task/Recamans-sequence/Scheme/recamans-sequence.ss b/Task/Recamans-sequence/Scheme/recamans-sequence.scm similarity index 100% rename from Task/Recamans-sequence/Scheme/recamans-sequence.ss rename to Task/Recamans-sequence/Scheme/recamans-sequence.scm diff --git a/Task/Recamans-sequence/Uiua/recamans-sequence.uiua b/Task/Recamans-sequence/Uiua/recamans-sequence.uiua new file mode 100644 index 0000000000..6dceb50be5 --- /dev/null +++ b/Task/Recamans-sequence/Uiua/recamans-sequence.uiua @@ -0,0 +1,9 @@ +# Sofar A(n-1) n Seen +Start ← [0] 0 1 1_0_0_0 +N ← ⨬(˜-|+)⤚₂(⬚1⊡˜-) # A(n-1) - n if valid, else A(n-1) + n. +Seen′ ← ⍜⊡⋅1⟜(⬚0↙↥⊸⊓+₁⧻)⊙⋅⋅∘ # Update Seen, expanding as needed. +Step ← ⊃(⊃(∘|⋅⋅+₁)|Seen′)◡N # Run one step. +&p$"First fifteen terms: \n_"⍥⤚Step15 ◌ Start +&p$"First repeat: _"⋅⊙⋅◌⍢(⊸⊂⊙Step|=∩⧻⊸◴) Start +&p$"...Thinking for _ seconds..."⍜now(⍢(⊸⊂⊙Step|≠1000/+⬚0↙1000⋅⋅⋅∘) Start) +&p$"0-1000 generated at: _"⋅⋅⊙◌ diff --git a/Task/Recamans-sequence/VBScript/recamans-sequence.vb b/Task/Recamans-sequence/VBScript/recamans-sequence.vb deleted file mode 100644 index c338d2b4f4..0000000000 --- a/Task/Recamans-sequence/VBScript/recamans-sequence.vb +++ /dev/null @@ -1,58 +0,0 @@ -' Recaman's sequence - vbscript - 04/08/2015 - nx=15 - h=1000 - Wscript.StdOut.WriteLine "Recaman's sequence for the first " & nx & " numbers:" - Wscript.StdOut.WriteLine recaman("seq",nx) - Wscript.StdOut.WriteLine "The first duplicate number is: " & recaman("firstdup",0) - Wscript.StdOut.WriteLine "The number of terms to complete the range 0--->"& h &" is: "& recaman("numterm",h) - Wscript.StdOut.Write vbCrlf&".../...": zz=Wscript.StdIn.ReadLine() - -function recaman(op,nn) - Dim b,d,h - Set b = CreateObject("Scripting.Dictionary") - Set d = CreateObject("Scripting.Dictionary") - list="0" : firstdup=0 - if op="firstdup" then - nn=1000 : firstdup=1 - end if - if op="numterm" then - h=nn : nn=10000000 : numterm=1 - end if - ax=0 'a(0)=0 - b.Add 0,1 'b(0)=1 - s=0 - for n=1 to nn-1 - an=ax-n - if an<=0 then - an=ax+n - elseif b.Exists(an) then - an=ax+n - end if - ax=an 'a(n)=an - if not b.Exists(an) then b.Add an,1 'b(an)=1 - if op="seq" then - list=list&" "&an - end if - if firstdup then - if d.Exists(an) then - recaman="a("&n&")="&an - exit function - else - d.Add an,1 'd(an)=1 - end if - end if - if numterm then - if an<=h then - if not d.Exists(an) then - s=s+1 - d.Add an,1 'd(an)=1 - end if - if s>=h then - recaman=n - exit function - end if - end if - end if - next 'n - recaman=list -end function 'recaman diff --git a/Task/Recamans-sequence/VBScript/recamans-sequence.vbs b/Task/Recamans-sequence/VBScript/recamans-sequence.vbs new file mode 100644 index 0000000000..cf89a57054 --- /dev/null +++ b/Task/Recamans-sequence/VBScript/recamans-sequence.vbs @@ -0,0 +1,58 @@ +' Recaman's sequence - vbscript - 04/08/2015 + nx=15 + h=1000 + Wscript.StdOut.WriteLine "Recaman's sequence for the first " & nx & " numbers:" + Wscript.StdOut.WriteLine recaman("seq",nx) + Wscript.StdOut.WriteLine "The first duplicate number is: " & recaman("firstdup",0) + Wscript.StdOut.WriteLine "The number of terms to complete the range 0--->"& h &" is: "& recaman("numterm",h) + Wscript.StdOut.Write vbCrlf&".../...": zz=Wscript.StdIn.ReadLine() + +function recaman(op,nn) + Dim b,d,h + Set b = CreateObject("Scripting.Dictionary") + Set d = CreateObject("Scripting.Dictionary") + list="0" : firstdup=0 + if op="firstdup" then + nn=1000 : firstdup=1 + end if + if op="numterm" then + h=nn : nn=10000000 : numterm=1 + end if + ax=0 'a(0)=0 + b.Add 0,1 'b(0)=1 + s=0 + for n=1 to nn-1 + an=ax-n + if an<=0 then + an=ax+n + elseif b.Exists(an) then + an=ax+n + end if + ax=an 'a(n)=an + if not b.Exists(an) then b.Add an,1 'b(an)=1 + if op="seq" then + list=list&" "&an + end if + if firstdup then + if d.Exists(an) then + recaman="a("&n&")="&an + exit function + else + d.Add an,1 'd(an)=1 + end if + end if + if numterm then + if an<=h then + if not d.Exists(an) then + s=s+1 + d.Add an,1 'd(an)=1 + end if + if s>=h then + recaman=n + exit function + end if + end if + end if + next 'n + recaman=list +end function 'recaman diff --git a/Task/Record-sound/00-TASK.txt b/Task/Record-sound/00-TASK.txt index 264fe9687d..64d549b885 100644 --- a/Task/Record-sound/00-TASK.txt +++ b/Task/Record-sound/00-TASK.txt @@ -4,3 +4,4 @@ Record a monophonic 16-bit PCM sound into either memory space, a file or array. The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate. Therefore, these programs might not record sound in the same format.) + diff --git a/Task/Record-sound/Ada/record-sound.adb b/Task/Record-sound/Ada/record-sound.adb new file mode 100644 index 0000000000..3afa638764 --- /dev/null +++ b/Task/Record-sound/Ada/record-sound.adb @@ -0,0 +1,33 @@ +with Sf.Audio.SoundBufferRecorder; +with Sf.Audio.SoundBuffer; +with Ada.Text_IO; + +procedure Record_Sound is + use Sf, Sf.Audio, Ada.Text_IO; + Sound_Buffer_Recorder : constant sfSoundBufferRecorder_Ptr := SoundBufferRecorder.create; + Sound_Buffer : sfSoundBuffer_Ptr; +begin + + if Sound_Buffer_Recorder = null then + Put_Line (Standard_Error, "Error: sound recorder not available!"); + return; + end if; + + -- By default the recording is in 16-bit mono. Using the + -- setChannelCount method you can change the number of channels + -- used by the audio capture device to record. + if SoundBufferRecorder.start (Sound_Buffer_Recorder, sampleRate => 44_100) /= sfTrue then + Put_Line (Standard_Error, "Error: sound recorder cannot start!"); + return; + end if; + + delay 10.0; + SoundBufferRecorder.stop (Sound_Buffer_Recorder); + + Sound_Buffer := SoundBufferRecorder.getBuffer (Sound_Buffer_Recorder); + if SoundBuffer.saveToFile (Sound_Buffer, filename => "output.ogg") /= sfTrue then + Put_Line (Standard_Error, "Error: recorded sound could not be saved!"); + end if; + + SoundBufferRecorder.destroy (Sound_Buffer_Recorder); +end Record_Sound; diff --git a/Task/Record-sound/FutureBasic/record-sound.basic b/Task/Record-sound/FutureBasic/record-sound.basic new file mode 100644 index 0000000000..c90517e88e --- /dev/null +++ b/Task/Record-sound/FutureBasic/record-sound.basic @@ -0,0 +1,138 @@ +// --------------- +include "NSLog.incl" +include "Tlbx Speech.incl" +include "Tlbx AVFoundation.incl" + +output "RecordToTextDemo" + +#plist CFBundleIdentifier @"com.futurebasic.RecordToTextDemo" +#plist NSSpeechRecognitionUsageDescription @"Enable speech recognition." +#plist NSMicrophoneUsageDescription @"This app requires microphone access." + +#define FILE_URL fn URLByAppendingPathComponent(fn FileManagerURLForApplicationDirectory,@"MyAudioFile.m4a") +#define RECORDER_KEY @"recorder" + + +_window = 1 +begin enum 1 + _recordBtn +end enum + + +void local fn FixViews + dispatchmain + AVAudioRecorderRef recorder = fn AppProperty( RECORDER_KEY ) + if ( recorder ) + button _recordBtn,,, @"Stop Recording",,,, _window + else + button _recordBtn,,, @"Start Recording",,,, _window + end if + dispatchend +end fn + + +void local fn BuildWindow + window _window, @"Record Demo", (0,0,480,270) + button _recordBtn,,, @"Start Recording", (13,13,129,32) +end fn + + +void local fn MyRecognitionTaskHandler( ref as SFSpeechRecognizerRef, result as SFSpeechRecognitionResultRef, err as ErrorRef, userData as ptr ) + SFTranscriptionRef transcription = fn SFSpeechRecognitionResultBestTranscription( result ) + + if ( err ) + NSLog(@"error") + else + if ( fn SFSpeechRecognitionResultIsFinal( result ) ) + NSLog(@"%@",fn SFTranscriptionFormattedString( transcription )) + end if + end if +end fn + + +void local fn MyRequestAuthorization( status as SFSpeechRecognizerAuthorizationStatus, userData as ptr ) + SFSpeechRecognizerRef recognizer + SFSpeechURLRecognitionRequestRef request + + select ( status ) + case SFSpeechRecognizerAuthorizationStatusNotDetermined : NSLog(@"Authorization not determined") + case SFSpeechRecognizerAuthorizationStatusDenied : NSLog(@"Authorization denied") + case SFSpeechRecognizerAuthorizationStatusRestricted : NSLog(@"Authorization restricted") + case SFSpeechRecognizerAuthorizationStatusAuthorized + recognizer = fn SFSpeechRecognizerInit + if ( fn SFSpeechRecognizerIsAvailable( recognizer ) ) + if ( FILE_URL ) + fn SoundPlay( fn SoundWithContentsOfURL( FILE_URL, YES ) ) + request = fn SFSpeechURLRecognitionRequestWithURL( FILE_URL ) + SFSpeechRecognizerSetSupportsOnDeviceRecognition( recognizer, YES ) + fn SFSpeechRecognizerRecognitionTaskWithResultHandler( recognizer, request, @fn MyRecognitionTaskHandler, NULL ) + end if + else + NSLog(@"Speech recognizer not available") + end if + end select +end fn + + +void local fn RecognizeSpeech + SFSpeechRecognizerRequestAuthorization( @fn MyRequestAuthorization, NULL ) +end fn + + +void local fn RecordAudio + CFDictionaryRef settings = @{ + AVFormatIDKey:@(kAudioFormatMPEG4AAC), + AVEncoderAudioQualityKey:@(AVAudioQualityHigh), + AVSampleRateKey:@44100.0, + AVNumberOfChannelsKey:@1, + AVLinearPCMBitDepthKey:@16} + + AVAudioFormatRef format = fn AVAudioFormatWithSettings( settings ) + AVAudioRecorderRef recorder = fn AVAudioRecorderWithFormat( FILE_URL, format, NULL ) + AppSetProperty( RECORDER_KEY, recorder ) + fn FixViews + fn AVAudioRecorderRecord( recorder ) +end fn + + +void local fn MyRequestAccessHandler( granted as BOOL, userData as ptr ) + if ( granted ) then fn RecordAudio +end fn + + +void local fn StartStopRecording + AVAudioRecorderRef recorder = fn AppProperty( RECORDER_KEY ) + AVAuthorizationStatus status + + if ( recorder ) + AVAudioRecorderStop( recorder ) + AppRemoveProperty( RECORDER_KEY ) + fn FixViews + fn RecognizeSpeech + else + status = fn AVCaptureDeviceAuthorizationStatus( AVMediaTypeAudio ) + select ( status ) + case AVAuthorizationStatusDenied : NSLog(@"Denied") + case AVAuthorizationStatusRestricted : NSLog(@"Restricted") + case AVAuthorizationStatusAuthorized : fn RecordAudio + case AVAuthorizationStatusNotDetermined + AVCaptureDeviceRequestAccess( AVMediaTypeAudio, @fn MyRequestAccessHandler, NULL ) + end select + end if +end fn + + +void local fn DoDialog( ev as long, tag as long ) + select ( ev ) + case _btnClick + select ( tag ) + case _recordBtn : fn StartStopRecording + end select + end select +end fn + +fn BuildWindow + +on dialog fn DoDialog + +HandleEvents diff --git a/Task/Record-sound/Julia/record-sound.julia b/Task/Record-sound/Julia/record-sound.jl similarity index 100% rename from Task/Record-sound/Julia/record-sound.julia rename to Task/Record-sound/Julia/record-sound.jl diff --git a/Task/Record-sound/Kotlin/record-sound.kotlin b/Task/Record-sound/Kotlin/record-sound.kts similarity index 100% rename from Task/Record-sound/Kotlin/record-sound.kotlin rename to Task/Record-sound/Kotlin/record-sound.kts diff --git a/Task/Record-sound/OCaml/record-sound.ocaml b/Task/Record-sound/OCaml/record-sound.ml similarity index 100% rename from Task/Record-sound/OCaml/record-sound.ocaml rename to Task/Record-sound/OCaml/record-sound.ml diff --git a/Task/Record-sound/Wren/record-sound-1.wren b/Task/Record-sound/Wren/record-sound-1.wren deleted file mode 100644 index 8922c706f5..0000000000 --- a/Task/Record-sound/Wren/record-sound-1.wren +++ /dev/null @@ -1,39 +0,0 @@ -/* Record_sound.wren */ - -class C { - foreign static getInput(maxSize) - - foreign static arecord(args) - - foreign static aplay(name) -} - -var name = "" -while (name == "") { - System.write("Enter output file name (without extension) : ") - name = C.getInput(80) -} -name = name + ".wav" - -var rate = 0 -while (!rate || !rate.isInteger || rate < 2000 || rate > 192000) { - System.write("Enter sampling rate in Hz (2000 to 192000) : ") - rate = Num.fromString(C.getInput(6)) -} -var rateS = rate.toString - -var dur = 0 -while (!dur || dur < 5 || dur > 30) { - System.write("Enter duration in seconds (5 to 30) : ") - dur = Num.fromString(C.getInput(5)) -} -var durS = dur.toString - -System.print("\nOK, start speaking now...") -// Default arguments: -c 1, -t wav. Note only signed 16 bit format supported. -var args = ["-r", rateS, "-f", "S16_LE", "-d", durS, name] -C.arecord(args.join(" ")) - -System.print("\n'%(name)' created on disk and will now be played back...") -C.aplay(name) -System.print("\nPlay-back completed.") diff --git a/Task/Record-sound/Wren/record-sound-2.wren b/Task/Record-sound/Wren/record-sound-2.wren deleted file mode 100644 index 0ad3196c0d..0000000000 --- a/Task/Record-sound/Wren/record-sound-2.wren +++ /dev/null @@ -1,102 +0,0 @@ -#include -#include -#include -#include -#include "wren.h" - -void C_getInput(WrenVM* vm) { - int maxSize = (int)wrenGetSlotDouble(vm, 1) + 2; - char input[maxSize]; - fgets(input, maxSize, stdin); - __fpurge(stdin); - input[strcspn(input, "\n")] = 0; - wrenSetSlotString(vm, 0, (const char*)input); -} - -void C_arecord(WrenVM* vm) { - const char *args = wrenGetSlotString(vm, 1); - char command[strlen(args) + 8]; - strcpy(command, "arecord "); - strcat(command, args); - system(command); -} - -void C_aplay(WrenVM* vm) { - const char *name = wrenGetSlotString(vm, 1); - char command[strlen(name) + 6]; - strcpy(command, "aplay "); - strcat(command, name); - system(command); -} - -WrenForeignMethodFn bindForeignMethod( - WrenVM* vm, - const char* module, - const char* className, - bool isStatic, - const char* signature) { - if (strcmp(module, "main") == 0) { - if (strcmp(className, "C") == 0) { - if (isStatic && strcmp(signature, "getInput(_)") == 0) return C_getInput; - if (isStatic && strcmp(signature, "arecord(_)") == 0) return C_arecord; - if (isStatic && strcmp(signature, "aplay(_)") == 0) return C_aplay; - } - } - return NULL; -} - -static void writeFn(WrenVM* vm, const char* text) { - printf("%s", text); -} - -void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) { - switch (errorType) { - case WREN_ERROR_COMPILE: - printf("[%s line %d] [Error] %s\n", module, line, msg); - break; - case WREN_ERROR_STACK_TRACE: - printf("[%s line %d] in %s\n", module, line, msg); - break; - case WREN_ERROR_RUNTIME: - printf("[Runtime Error] %s\n", msg); - break; - } -} - -char *readFile(const char *fileName) { - FILE *f = fopen(fileName, "r"); - fseek(f, 0, SEEK_END); - long fsize = ftell(f); - rewind(f); - char *script = malloc(fsize + 1); - fread(script, 1, fsize, f); - fclose(f); - script[fsize] = 0; - return script; -} - -int main(int argc, char **argv) { - WrenConfiguration config; - wrenInitConfiguration(&config); - config.writeFn = &writeFn; - config.errorFn = &errorFn; - config.bindForeignMethodFn = &bindForeignMethod; - WrenVM* vm = wrenNewVM(&config); - const char* module = "main"; - const char* fileName = "Record_sound.wren"; - char *script = readFile(fileName); - WrenInterpretResult result = wrenInterpret(vm, module, script); - switch (result) { - case WREN_RESULT_COMPILE_ERROR: - printf("Compile Error!\n"); - break; - case WREN_RESULT_RUNTIME_ERROR: - printf("Runtime Error!\n"); - break; - case WREN_RESULT_SUCCESS: - break; - } - wrenFreeVM(vm); - free(script); - return 0; -} diff --git a/Task/Record-sound/Wren/record-sound.wren b/Task/Record-sound/Wren/record-sound.wren new file mode 100644 index 0000000000..f7437f90a3 --- /dev/null +++ b/Task/Record-sound/Wren/record-sound.wren @@ -0,0 +1,20 @@ +import "os" for Process +import "./ioutil" for Input + +var name = Input.text("Enter output file name (without extension) : ", 1, 80) +name = name + ".wav" + +var rate = Input.integer("Enter sampling rate in Hz (2000 to 192000) : ", 2000, 192000) +var rateS = rate.toString + +var dur = Input.number("Enter duration in seconds (5 to 30) : ", 5, 30) +var durS = dur.toString + +System.print("\nOK, start speaking now...") +// Default arguments: -c 1, -t wav. Note only signed 16 bit format supported. +var args = ["-r", rateS, "-f", "S16_LE", "-d", durS, name] +Process.exec("arecord", args) + +System.print("\n'%(name)' created on disk and will now be played back...") +Process.exec("aplay %(name)") +System.print("\nPlay-back completed.") diff --git a/Task/Reduced-row-echelon-form/Ada/reduced-row-echelon-form-1.ada b/Task/Reduced-row-echelon-form/Ada/reduced-row-echelon-form-1.adb similarity index 100% rename from Task/Reduced-row-echelon-form/Ada/reduced-row-echelon-form-1.ada rename to Task/Reduced-row-echelon-form/Ada/reduced-row-echelon-form-1.adb diff --git a/Task/Reduced-row-echelon-form/Ada/reduced-row-echelon-form-2.ada b/Task/Reduced-row-echelon-form/Ada/reduced-row-echelon-form-2.adb similarity index 100% rename from Task/Reduced-row-echelon-form/Ada/reduced-row-echelon-form-2.ada rename to Task/Reduced-row-echelon-form/Ada/reduced-row-echelon-form-2.adb diff --git a/Task/Reduced-row-echelon-form/Ada/reduced-row-echelon-form-3.ada b/Task/Reduced-row-echelon-form/Ada/reduced-row-echelon-form-3.adb similarity index 100% rename from Task/Reduced-row-echelon-form/Ada/reduced-row-echelon-form-3.ada rename to Task/Reduced-row-echelon-form/Ada/reduced-row-echelon-form-3.adb diff --git a/Task/Reduced-row-echelon-form/AutoHotkey/reduced-row-echelon-form-1.ahk b/Task/Reduced-row-echelon-form/AutoHotkey/reduced-row-echelon-form-1.ahk index 0d9a116db3..7c902587d4 100644 --- a/Task/Reduced-row-echelon-form/AutoHotkey/reduced-row-echelon-form-1.ahk +++ b/Task/Reduced-row-echelon-form/AutoHotkey/reduced-row-echelon-form-1.ahk @@ -1,6 +1,6 @@ ToReducedRowEchelonForm(M){ - rowCount := M.Count() ; the number of rows in M - columnCount := M.1.Count() ; the number of columns in M + rowCount := M.Count() ; the number of rows in M + columnCount := M.1.Count() ; the number of columns in M r := lead := 1 while (r <= rowCount) { if (columnCount < lead) @@ -9,29 +9,29 @@ ToReducedRowEchelonForm(M){ while (M[i, lead] = 0) { i++ if (rowCount+1 = i) { - i := r, lead++ + i := r, lead++ if (columnCount+1 = lead) return M } } if (i<>r) - for col, v in M[i] ; Swap rows i and r - tempVal := M[i, col], M[i, col] := M[r, col], M[r, col] := tempVal + for col, v in M[i] ; Swap rows i and r + tempVal := M[i, col], M[i, col] := M[r, col], M[r, col] := tempVal num := M[r, lead] if (M[r, lead] <> 0) for col, val in M[r] - M[r, col] /= num ; If M[r, lead] is not 0 divide row r by M[r, lead] + M[r, col] /= num ; If M[r, lead] is not 0 divide row r by M[r, lead] i := 2 while (i <= rowCount) { num := M[i, lead] if (i <> r) - for col, val in M[i] ; Subtract M[i, lead] multiplied by row r from row i + for col, val in M[i] ; Subtract M[i, lead] multiplied by row r from row i M[i, col] -= num * M[r, col] i++ } - lead++, r++ + lead++, r++ } return M } diff --git a/Task/Reduced-row-echelon-form/AutoIt/reduced-row-echelon-form.au3 b/Task/Reduced-row-echelon-form/AutoIt/reduced-row-echelon-form.au3 new file mode 100644 index 0000000000..8138a09ee0 --- /dev/null +++ b/Task/Reduced-row-echelon-form/AutoIt/reduced-row-echelon-form.au3 @@ -0,0 +1,52 @@ +Global $ivMatrix[3][4] = [[1, 2, -1, -4],[2, 3, -1, -11],[-2, 0, -3, 22]] +ToReducedRowEchelonForm($ivMatrix) + +Func ToReducedRowEchelonForm($matrix) + Local $clonematrix, $i + Local $lead = 0 + Local $rowCount = UBound($matrix) - 1 + Local $columnCount = UBound($matrix, 2) - 1 + For $r = 0 To $rowCount + If $columnCount = $lead Then ExitLoop + $i = $r + While $matrix[$i][$lead] = 0 + $i += 1 + If $rowCount = $i Then + $i = $r + $lead += 1 + If $columnCount = $lead Then ExitLoop + EndIf + WEnd + ; There´s no built in Function to swap Rows of a 2-Dimensional Array + ; We need to clone our matrix to swap complete lines + $clonematrix = $matrix ; Swap Lines, no + For $s = 0 To $columnCount + $matrix[$r][$s] = $clonematrix[$i][$s] + $matrix[$i][$s] = $clonematrix[$r][$s] + Next + Local $m = $matrix[$r][$lead] + For $k = 0 To $columnCount + $matrix[$r][$k] = $matrix[$r][$k] / $m + Next + For $i = 0 To $rowCount + If $i <> $r Then + Local $m = $matrix[$i][$lead] + For $k = 0 To $columnCount + $matrix[$i][$k] -= $m * $matrix[$r][$k] + Next + EndIf + Next + $lead += 1 + Next + ; Console Output + For $i = 0 To $rowCount + ConsoleWrite("[") + For $k = 0 To $columnCount + ConsoleWrite($matrix[$i][$k]) + If $k <> $columnCount Then ConsoleWrite(",") + Next + ConsoleWrite("]" & @CRLF) + Next + ; End of Console Output + Return $matrix +EndFunc ;==>ToReducedRowEchelonForm diff --git a/Task/Reduced-row-echelon-form/AutoIt/reduced-row-echelon-form.autoit b/Task/Reduced-row-echelon-form/AutoIt/reduced-row-echelon-form.autoit deleted file mode 100644 index b93aa60ebf..0000000000 --- a/Task/Reduced-row-echelon-form/AutoIt/reduced-row-echelon-form.autoit +++ /dev/null @@ -1,52 +0,0 @@ -Global $ivMatrix[3][4] = [[1, 2, -1, -4],[2, 3, -1, -11],[-2, 0, -3, 22]] -ToReducedRowEchelonForm($ivMatrix) - -Func ToReducedRowEchelonForm($matrix) - Local $clonematrix, $i - Local $lead = 0 - Local $rowCount = UBound($matrix) - 1 - Local $columnCount = UBound($matrix, 2) - 1 - For $r = 0 To $rowCount - If $columnCount = $lead Then ExitLoop - $i = $r - While $matrix[$i][$lead] = 0 - $i += 1 - If $rowCount = $i Then - $i = $r - $lead += 1 - If $columnCount = $lead Then ExitLoop - EndIf - WEnd - ; There´s no built in Function to swap Rows of a 2-Dimensional Array - ; We need to clone our matrix to swap complete lines - $clonematrix = $matrix ; Swap Lines, no - For $s = 0 To $columnCount - $matrix[$r][$s] = $clonematrix[$i][$s] - $matrix[$i][$s] = $clonematrix[$r][$s] - Next - Local $m = $matrix[$r][$lead] - For $k = 0 To $columnCount - $matrix[$r][$k] = $matrix[$r][$k] / $m - Next - For $i = 0 To $rowCount - If $i <> $r Then - Local $m = $matrix[$i][$lead] - For $k = 0 To $columnCount - $matrix[$i][$k] -= $m * $matrix[$r][$k] - Next - EndIf - Next - $lead += 1 - Next - ; Console Output - For $i = 0 To $rowCount - ConsoleWrite("[") - For $k = 0 To $columnCount - ConsoleWrite($matrix[$i][$k]) - If $k <> $columnCount Then ConsoleWrite(",") - Next - ConsoleWrite("]" & @CRLF) - Next - ; End of Console Output - Return $matrix -EndFunc ;==>ToReducedRowEchelonForm diff --git a/Task/Reduced-row-echelon-form/C/reduced-row-echelon-form.c b/Task/Reduced-row-echelon-form/C/reduced-row-echelon-form.c index 63df991bf1..cc01d4b86d 100644 --- a/Task/Reduced-row-echelon-form/C/reduced-row-echelon-form.c +++ b/Task/Reduced-row-echelon-form/C/reduced-row-echelon-form.c @@ -73,8 +73,8 @@ void MtxMulAndAddRows(Matrix m, int ixrdest, int ixrsrc, EL_Type mplr) srow = m->mtx[ixrsrc]; for (ix=0; ixdim_x; ix++) drow[ix] += mplr * srow[ix]; -// printf("Mul row %d by %d and add to row %d\n", ixrsrc, mplr, ixrdest); -// MtxDisplay(m); +// printf("Mul row %d by %d and add to row %d\n", ixrsrc, mplr, ixrdest); +// MtxDisplay(m); } void MtxSwapRows( Matrix m, int rix1, int rix2) @@ -86,8 +86,8 @@ void MtxSwapRows( Matrix m, int rix1, int rix2) r2 = m->mtx[rix2]; for (ix=0; ixdim_x; ix++) temp = r1[ix]; r1[ix]=r2[ix]; r2[ix]=temp; -// printf("Swap rows %d and %d\n", rix1, rix2); -// MtxDisplay(m); +// printf("Swap rows %d and %d\n", rix1, rix2); +// MtxDisplay(m); } void MtxNormalizeRow( Matrix m, int rix, int lead) @@ -99,8 +99,8 @@ void MtxNormalizeRow( Matrix m, int rix, int lead) lv = drow[lead]; for (ix=0; ixdim_x; ix++) drow[ix] /= lv; -// printf("Normalize row %d\n", rix); -// MtxDisplay(m); +// printf("Normalize row %d\n", rix); +// MtxDisplay(m); } #define MtxGet( m, rix, cix ) m->mtx[rix][cix] diff --git a/Task/Reduced-row-echelon-form/Common-Lisp/reduced-row-echelon-form.lisp b/Task/Reduced-row-echelon-form/Common-Lisp/reduced-row-echelon-form.lisp index 7e8a46c32f..85698ec12c 100644 --- a/Task/Reduced-row-echelon-form/Common-Lisp/reduced-row-echelon-form.lisp +++ b/Task/Reduced-row-echelon-form/Common-Lisp/reduced-row-echelon-form.lisp @@ -1,44 +1,44 @@ (defun convert-to-row-echelon-form (matrix) (let* ((dimensions (array-dimensions matrix)) - (row-count (first dimensions)) - (column-count (second dimensions)) - (lead 0)) + (row-count (first dimensions)) + (column-count (second dimensions)) + (lead 0)) (labels ((find-pivot (start lead) - (let ((i start)) - (loop - :while (zerop (aref matrix i lead)) - :do (progn - (incf i) - (when (= i row-count) - (setf i start) - (incf lead) - (when (= lead column-count) - (return-from convert-to-row-echelon-form matrix)))) - :finally (return (values i lead))))) - (swap-rows (r1 r2) - (loop - :for c :upfrom 0 :below column-count - :do (rotatef (aref matrix r1 c) (aref matrix r2 c)))) - (divide-row (r value) - (loop - :for c :upfrom 0 :below column-count - :do (setf (aref matrix r c) - (/ (aref matrix r c) value))))) + (let ((i start)) + (loop + :while (zerop (aref matrix i lead)) + :do (progn + (incf i) + (when (= i row-count) + (setf i start) + (incf lead) + (when (= lead column-count) + (return-from convert-to-row-echelon-form matrix)))) + :finally (return (values i lead))))) + (swap-rows (r1 r2) + (loop + :for c :upfrom 0 :below column-count + :do (rotatef (aref matrix r1 c) (aref matrix r2 c)))) + (divide-row (r value) + (loop + :for c :upfrom 0 :below column-count + :do (setf (aref matrix r c) + (/ (aref matrix r c) value))))) (loop - :for r :upfrom 0 :below row-count - :when (<= column-count lead) - :do (return matrix) - :do (multiple-value-bind (i nlead) (find-pivot r lead) - (setf lead nlead) - (swap-rows i r) - (divide-row r (aref matrix r lead)) - (loop - :for i :upfrom 0 :below row-count - :when (/= i r) - :do (let ((scale (aref matrix i lead))) - (loop - :for c :upfrom 0 :below column-count - :do (decf (aref matrix i c) - (* scale (aref matrix r c)))))) - (incf lead)) - :finally (return matrix))))) + :for r :upfrom 0 :below row-count + :when (<= column-count lead) + :do (return matrix) + :do (multiple-value-bind (i nlead) (find-pivot r lead) + (setf lead nlead) + (swap-rows i r) + (divide-row r (aref matrix r lead)) + (loop + :for i :upfrom 0 :below row-count + :when (/= i r) + :do (let ((scale (aref matrix i lead))) + (loop + :for c :upfrom 0 :below column-count + :do (decf (aref matrix i c) + (* scale (aref matrix r c)))))) + (incf lead)) + :finally (return matrix))))) 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 index a3ff68820f..1a33b89a0a 100644 --- a/Task/Reduced-row-echelon-form/EasyLang/reduced-row-echelon-form.easy +++ b/Task/Reduced-row-echelon-form/EasyLang/reduced-row-echelon-form.easy @@ -1,33 +1,25 @@ -proc rref . m[][] . +proc rref &m[][] . nrow = len m[][] ncol = len m[1][] lead = 1 for r to nrow - if lead > ncol - return - . + if lead > ncol : return i = r while m[i][lead] = 0 i += 1 if i > nrow i = r lead += 1 - if lead > ncol - return - . + if lead > ncol : return . . swap m[i][] m[r][] m = m[r][lead] - for k to ncol - m[r][k] /= m - . + 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] - . + for k to ncol : m[i][k] -= m * m[r][k] . . lead += 1 diff --git a/Task/Reduced-row-echelon-form/Euphoria/reduced-row-echelon-form.euphoria b/Task/Reduced-row-echelon-form/Euphoria/reduced-row-echelon-form.eu similarity index 100% rename from Task/Reduced-row-echelon-form/Euphoria/reduced-row-echelon-form.euphoria rename to Task/Reduced-row-echelon-form/Euphoria/reduced-row-echelon-form.eu diff --git a/Task/Reduced-row-echelon-form/Java/reduced-row-echelon-form-1.java b/Task/Reduced-row-echelon-form/Java/reduced-row-echelon-form-1.java new file mode 100644 index 0000000000..82a3cc3eca --- /dev/null +++ b/Task/Reduced-row-echelon-form/Java/reduced-row-echelon-form-1.java @@ -0,0 +1,260 @@ +import java.util.*; +import java.lang.Math; +import org.apache.commons.math.fraction.Fraction; +import org.apache.commons.math.fraction.FractionConversionException; + +/* Matrix class + * Handles elementary Matrix operations: + * Interchange + * Multiply and Add + * Scale + * Reduced Row Echelon Form + */ +class Matrix { + LinkedList> matrix; + int numRows; + int numCols; + + static class Coordinate { + int row; + int col; + + Coordinate(int r, int c) { + row = r; + col = c; + } + + public String toString() { + return "(" + row + ", " + col + ")"; + } + } + + Matrix(double [][] m) { + numRows = m.length; + numCols = m[0].length; + + matrix = new LinkedList>(); + + for (int i = 0; i < numRows; i++) { + matrix.add(new LinkedList()); + for (int j = 0; j < numCols; j++) { + try { + matrix.get(i).add(new Fraction(m[i][j])); + } catch (FractionConversionException e) { + System.err.println("Fraction could not be converted from double by apache commons . . ."); + } + } + } + } + + public void Interchange(Coordinate a, Coordinate b) { + LinkedList temp = matrix.get(a.row); + matrix.set(a.row, matrix.get(b.row)); + matrix.set(b.row, temp); + + int t = a.row; + a.row = b.row; + b.row = t; + } + + public void Scale(Coordinate x, Fraction d) { + LinkedList row = matrix.get(x.row); + for (int i = 0; i < numCols; i++) { + row.set(i, row.get(i).multiply(d)); + } + } + + public void MultiplyAndAdd(Coordinate to, Coordinate from, Fraction scalar) { + LinkedList row = matrix.get(to.row); + LinkedList rowMultiplied = matrix.get(from.row); + + for (int i = 0; i < numCols; i++) { + row.set(i, row.get(i).add((rowMultiplied.get(i).multiply(scalar)))); + } + } + + public void RREF() { + Coordinate pivot = new Coordinate(0,0); + + int submatrix = 0; + for (int x = 0; x < numCols; x++) { + pivot = new Coordinate(pivot.row, x); + //Step 1 + //Begin with the leftmost nonzero column. This is a pivot column. The pivot position is at the top. + for (int i = x; i < numCols; i++) { + if (isColumnZeroes(pivot) == false) { + break; + } else { + pivot.col = i; + } + } + //Step 2 + //Select a nonzero entry in the pivot column with the highest absolute value as a pivot. + pivot = findPivot(pivot); + + if (getCoordinate(pivot).doubleValue() == 0.0) { + pivot.row++; + continue; + } + + //If necessary, interchange rows to move this entry into the pivot position. + //move this row to the top of the submatrix + if (pivot.row != submatrix) { + Interchange(new Coordinate(submatrix, pivot.col), pivot); + } + + //Force pivot to be 1 + if (getCoordinate(pivot).doubleValue() != 1) { + /* + System.out.println(getCoordinate(pivot)); + System.out.println(pivot); + System.out.println(matrix); + */ + Fraction scalar = getCoordinate(pivot).reciprocal(); + Scale(pivot, scalar); + } + //Step 3 + //Use row replacement operations to create zeroes in all positions below the pivot. + //belowPivot = belowPivot + (Pivot * -belowPivot) + for (int i = pivot.row; i < numRows; i++) { + if (i == pivot.row) { + continue; + } + Coordinate belowPivot = new Coordinate(i, pivot.col); + Fraction complement = (getCoordinate(belowPivot).negate().divide(getCoordinate(pivot))); + MultiplyAndAdd(belowPivot, pivot, complement); + } + //Step 5 + //Beginning with the rightmost pivot and working upward and to the left, create zeroes above each pivot. + //If a pivot is not 1, make it 1 by a scaling operation. + //Use row replacement operations to create zeroes in all positions above the pivot + for (int i = pivot.row; i >= 0; i--) { + if (i == pivot.row) { + if (getCoordinate(pivot).doubleValue() != 1.0) { + Scale(pivot, getCoordinate(pivot).reciprocal()); + } + continue; + } + if (i == pivot.row) { + continue; + } + + Coordinate abovePivot = new Coordinate(i, pivot.col); + Fraction complement = (getCoordinate(abovePivot).negate().divide(getCoordinate(pivot))); + MultiplyAndAdd(abovePivot, pivot, complement); + } + //Step 4 + //Ignore the row containing the pivot position and cover all rows, if any, above it. + //Apply steps 1-3 to the remaining submatrix. Repeat until there are no more nonzero entries. + if ((pivot.row + 1) >= numRows || isRowZeroes(new Coordinate(pivot.row+1, pivot.col))) { + break; + } + + submatrix++; + pivot.row++; + } + } + + public boolean isColumnZeroes(Coordinate a) { + for (int i = 0; i < numRows; i++) { + if (matrix.get(i).get(a.col).doubleValue() != 0.0) { + return false; + } + } + + return true; + } + + public boolean isRowZeroes(Coordinate a) { + for (int i = 0; i < numCols; i++) { + if (matrix.get(a.row).get(i).doubleValue() != 0.0) { + return false; + } + } + + return true; + } + + public Coordinate findPivot(Coordinate a) { + int first_row = a.row; + Coordinate pivot = new Coordinate(a.row, a.col); + Coordinate current = new Coordinate(a.row, a.col); + + for (int i = a.row; i < (numRows - first_row); i++) { + current.row = i; + if (getCoordinate(current).doubleValue() == 1.0) { + Interchange(current, a); + } + } + + current.row = a.row; + for (int i = current.row; i < (numRows - first_row); i++) { + current.row = i; + if (getCoordinate(current).doubleValue() != 0) { + pivot.row = i; + break; + } + } + + + return pivot; + } + + public Fraction getCoordinate(Coordinate a) { + return matrix.get(a.row).get(a.col); + } + + public String toString() { + return matrix.toString().replace("], ", "]\n"); + } + + public static void main (String[] args) { + double[][] matrix_1 = { + {1, 2, -1, -4}, + {2, 3, -1, -11}, + {-2, 0, -3, 22} + }; + + Matrix x = new Matrix(matrix_1); + System.out.println("before\n" + x.toString() + "\n"); + x.RREF(); + System.out.println("after\n" + x.toString() + "\n"); + + double matrix_2 [][] = { + {2, 0, -1, 0, 0}, + {1, 0, 0, -1, 0}, + {3, 0, 0, -2, -1}, + {0, 1, 0, 0, -2}, + {0, 1, -1, 0, 0} + }; + + Matrix y = new Matrix(matrix_2); + System.out.println("before\n" + y.toString() + "\n"); + y.RREF(); + System.out.println("after\n" + y.toString() + "\n"); + + double matrix_3 [][] = { + {1, 2, 3, 4, 3, 1}, + {2, 4, 6, 2, 6, 2}, + {3, 6, 18, 9, 9, -6}, + {4, 8, 12, 10, 12, 4}, + {5, 10, 24, 11, 15, -4} + }; + + Matrix z = new Matrix(matrix_3); + System.out.println("before\n" + z.toString() + "\n"); + z.RREF(); + System.out.println("after\n" + z.toString() + "\n"); + + double matrix_4 [][] = { + {0, 1}, + {1, 2}, + {0,5} + }; + + Matrix a = new Matrix(matrix_4); + System.out.println("before\n" + a.toString() + "\n"); + a.RREF(); + System.out.println("after\n" + a.toString() + "\n"); + } +} diff --git a/Task/Reduced-row-echelon-form/Java/reduced-row-echelon-form-2.java b/Task/Reduced-row-echelon-form/Java/reduced-row-echelon-form-2.java new file mode 100644 index 0000000000..5f3fc6f001 --- /dev/null +++ b/Task/Reduced-row-echelon-form/Java/reduced-row-echelon-form-2.java @@ -0,0 +1,85 @@ +import java.util.List; + +public final class ReducedRowEchelonForm { + + public static void main(String[] args) { + double[][] first = new double[][] { { 1.0, 2.0, -1.0, -4.0 }, + { 2.0, 3.0, -1.0, -11.0 }, + { -2.0, 0.0, -3.0, 22.0 } }; + + double[][] second = new double[][] { { 1.0, 2.0, 3.0, 4.0, 3.0, 1.0 }, + { 2.0, 4.0, 6.0, 2.0, 6.0, 2.0 }, + { 3.0, 6.0, 18.0, 9.0, 9.0, -6.0 }, + { 4.0, 8.0, 12.0, 10.0, 12.0, 4.0 }, + { 5.0, 10.0, 24.0, 11.0, 15.0, -4.0 } }; + + List.of( first, second ).forEach( m -> { + display("Original matrix:", m); + display("Reduced row echelon form:", reducedRowEchelonForm(m)); + } ); + } + + private static double[][] reducedRowEchelonForm(double[][] matrix) { + final int rowCount = matrix.length; + final int colCount = matrix[0].length; + + int lead = 0; + for ( int row = 0; row < rowCount; row++ ) { + if ( colCount <= lead ) { + return matrix; + } + + int ro = row; + while ( matrix[ro][lead] == 0.0 ) { + ro += 1; + if ( rowCount == ro ) { + ro = row; + lead += 1; + if ( colCount == lead ) { + return matrix; + } + } + } + + final double[] temp = matrix[row]; + matrix[row] = matrix[ro]; + matrix[ro] = temp; + + if ( matrix[row][lead] != 0.0 ) { + final double divisor = matrix[row][lead]; + for ( int co = 0; co < matrix[0].length; co++ ) { + matrix[row][co] /= divisor; + } + } + + for ( int j = 0; j < rowCount; j++ ) { + if ( j != row ) { + final double multiple = matrix[j][lead]; + for ( int co = 0; co < matrix[0].length; co++ ) { + matrix[j][co] -= matrix[row][co] * multiple; + } + } + } + lead += 1; + } + return matrix; + } + + private static void display(String title, double[][] matrix) { + System.out.println(title); + final int rowCount = matrix.length; + final int colCount = matrix[0].length; + + for ( int row = 0; row < rowCount; row++ ) { + for ( int col = 0; col < colCount; col++ ) { + if ( matrix[row][col] == -0.0 ) { + matrix[row][col] = 0.0; + } + System.out.print(String.format("%6.1f", matrix[row][col])); + } + System.out.println(); + } + System.out.println(); + } + +} diff --git a/Task/Reduced-row-echelon-form/Java/reduced-row-echelon-form.java b/Task/Reduced-row-echelon-form/Java/reduced-row-echelon-form.java deleted file mode 100644 index 8c76b9e7b0..0000000000 --- a/Task/Reduced-row-echelon-form/Java/reduced-row-echelon-form.java +++ /dev/null @@ -1,260 +0,0 @@ -import java.util.*; -import java.lang.Math; -import org.apache.commons.math.fraction.Fraction; -import org.apache.commons.math.fraction.FractionConversionException; - -/* Matrix class - * Handles elementary Matrix operations: - * Interchange - * Multiply and Add - * Scale - * Reduced Row Echelon Form - */ -class Matrix { - LinkedList> matrix; - int numRows; - int numCols; - - static class Coordinate { - int row; - int col; - - Coordinate(int r, int c) { - row = r; - col = c; - } - - public String toString() { - return "(" + row + ", " + col + ")"; - } - } - - Matrix(double [][] m) { - numRows = m.length; - numCols = m[0].length; - - matrix = new LinkedList>(); - - for (int i = 0; i < numRows; i++) { - matrix.add(new LinkedList()); - for (int j = 0; j < numCols; j++) { - try { - matrix.get(i).add(new Fraction(m[i][j])); - } catch (FractionConversionException e) { - System.err.println("Fraction could not be converted from double by apache commons . . ."); - } - } - } - } - - public void Interchange(Coordinate a, Coordinate b) { - LinkedList temp = matrix.get(a.row); - matrix.set(a.row, matrix.get(b.row)); - matrix.set(b.row, temp); - - int t = a.row; - a.row = b.row; - b.row = t; - } - - public void Scale(Coordinate x, Fraction d) { - LinkedList row = matrix.get(x.row); - for (int i = 0; i < numCols; i++) { - row.set(i, row.get(i).multiply(d)); - } - } - - public void MultiplyAndAdd(Coordinate to, Coordinate from, Fraction scalar) { - LinkedList row = matrix.get(to.row); - LinkedList rowMultiplied = matrix.get(from.row); - - for (int i = 0; i < numCols; i++) { - row.set(i, row.get(i).add((rowMultiplied.get(i).multiply(scalar)))); - } - } - - public void RREF() { - Coordinate pivot = new Coordinate(0,0); - - int submatrix = 0; - for (int x = 0; x < numCols; x++) { - pivot = new Coordinate(pivot.row, x); - //Step 1 - //Begin with the leftmost nonzero column. This is a pivot column. The pivot position is at the top. - for (int i = x; i < numCols; i++) { - if (isColumnZeroes(pivot) == false) { - break; - } else { - pivot.col = i; - } - } - //Step 2 - //Select a nonzero entry in the pivot column with the highest absolute value as a pivot. - pivot = findPivot(pivot); - - if (getCoordinate(pivot).doubleValue() == 0.0) { - pivot.row++; - continue; - } - - //If necessary, interchange rows to move this entry into the pivot position. - //move this row to the top of the submatrix - if (pivot.row != submatrix) { - Interchange(new Coordinate(submatrix, pivot.col), pivot); - } - - //Force pivot to be 1 - if (getCoordinate(pivot).doubleValue() != 1) { - /* - System.out.println(getCoordinate(pivot)); - System.out.println(pivot); - System.out.println(matrix); - */ - Fraction scalar = getCoordinate(pivot).reciprocal(); - Scale(pivot, scalar); - } - //Step 3 - //Use row replacement operations to create zeroes in all positions below the pivot. - //belowPivot = belowPivot + (Pivot * -belowPivot) - for (int i = pivot.row; i < numRows; i++) { - if (i == pivot.row) { - continue; - } - Coordinate belowPivot = new Coordinate(i, pivot.col); - Fraction complement = (getCoordinate(belowPivot).negate().divide(getCoordinate(pivot))); - MultiplyAndAdd(belowPivot, pivot, complement); - } - //Step 5 - //Beginning with the rightmost pivot and working upward and to the left, create zeroes above each pivot. - //If a pivot is not 1, make it 1 by a scaling operation. - //Use row replacement operations to create zeroes in all positions above the pivot - for (int i = pivot.row; i >= 0; i--) { - if (i == pivot.row) { - if (getCoordinate(pivot).doubleValue() != 1.0) { - Scale(pivot, getCoordinate(pivot).reciprocal()); - } - continue; - } - if (i == pivot.row) { - continue; - } - - Coordinate abovePivot = new Coordinate(i, pivot.col); - Fraction complement = (getCoordinate(abovePivot).negate().divide(getCoordinate(pivot))); - MultiplyAndAdd(abovePivot, pivot, complement); - } - //Step 4 - //Ignore the row containing the pivot position and cover all rows, if any, above it. - //Apply steps 1-3 to the remaining submatrix. Repeat until there are no more nonzero entries. - if ((pivot.row + 1) >= numRows || isRowZeroes(new Coordinate(pivot.row+1, pivot.col))) { - break; - } - - submatrix++; - pivot.row++; - } - } - - public boolean isColumnZeroes(Coordinate a) { - for (int i = 0; i < numRows; i++) { - if (matrix.get(i).get(a.col).doubleValue() != 0.0) { - return false; - } - } - - return true; - } - - public boolean isRowZeroes(Coordinate a) { - for (int i = 0; i < numCols; i++) { - if (matrix.get(a.row).get(i).doubleValue() != 0.0) { - return false; - } - } - - return true; - } - - public Coordinate findPivot(Coordinate a) { - int first_row = a.row; - Coordinate pivot = new Coordinate(a.row, a.col); - Coordinate current = new Coordinate(a.row, a.col); - - for (int i = a.row; i < (numRows - first_row); i++) { - current.row = i; - if (getCoordinate(current).doubleValue() == 1.0) { - Interchange(current, a); - } - } - - current.row = a.row; - for (int i = current.row; i < (numRows - first_row); i++) { - current.row = i; - if (getCoordinate(current).doubleValue() != 0) { - pivot.row = i; - break; - } - } - - - return pivot; - } - - public Fraction getCoordinate(Coordinate a) { - return matrix.get(a.row).get(a.col); - } - - public String toString() { - return matrix.toString().replace("], ", "]\n"); - } - - public static void main (String[] args) { - double[][] matrix_1 = { - {1, 2, -1, -4}, - {2, 3, -1, -11}, - {-2, 0, -3, 22} - }; - - Matrix x = new Matrix(matrix_1); - System.out.println("before\n" + x.toString() + "\n"); - x.RREF(); - System.out.println("after\n" + x.toString() + "\n"); - - double matrix_2 [][] = { - {2, 0, -1, 0, 0}, - {1, 0, 0, -1, 0}, - {3, 0, 0, -2, -1}, - {0, 1, 0, 0, -2}, - {0, 1, -1, 0, 0} - }; - - Matrix y = new Matrix(matrix_2); - System.out.println("before\n" + y.toString() + "\n"); - y.RREF(); - System.out.println("after\n" + y.toString() + "\n"); - - double matrix_3 [][] = { - {1, 2, 3, 4, 3, 1}, - {2, 4, 6, 2, 6, 2}, - {3, 6, 18, 9, 9, -6}, - {4, 8, 12, 10, 12, 4}, - {5, 10, 24, 11, 15, -4} - }; - - Matrix z = new Matrix(matrix_3); - System.out.println("before\n" + z.toString() + "\n"); - z.RREF(); - System.out.println("after\n" + z.toString() + "\n"); - - double matrix_4 [][] = { - {0, 1}, - {1, 2}, - {0,5} - }; - - Matrix a = new Matrix(matrix_4); - System.out.println("before\n" + a.toString() + "\n"); - a.RREF(); - System.out.println("after\n" + a.toString() + "\n"); - } -} diff --git a/Task/Reduced-row-echelon-form/Jq/reduced-row-echelon-form-1.jq b/Task/Reduced-row-echelon-form/Jq/reduced-row-echelon-form-1.jq index 70cce74e6a..120636d419 100644 --- a/Task/Reduced-row-echelon-form/Jq/reduced-row-echelon-form-1.jq +++ b/Task/Reduced-row-echelon-form/Jq/reduced-row-echelon-form-1.jq @@ -1,9 +1,10 @@ # swap .[$i] and .[$j] def array_swap($i; $j): if $i == $j then . - elif $i < $j then array_swap($j; $i) - else .[$i] as $t | .[:$j] + [$t] + .[$j:$i] + .[$i + 1:] - end ; + else .[$i] as $t + | .[$i] = .[$j] + | .[$j] = $t + end; # element-wise subtraction: $a - $b def array_subtract($a; $b): diff --git a/Task/Reduced-row-echelon-form/Kotlin/reduced-row-echelon-form.kotlin b/Task/Reduced-row-echelon-form/Kotlin/reduced-row-echelon-form.kts similarity index 100% rename from Task/Reduced-row-echelon-form/Kotlin/reduced-row-echelon-form.kotlin rename to Task/Reduced-row-echelon-form/Kotlin/reduced-row-echelon-form.kts diff --git a/Task/Reduced-row-echelon-form/OCaml/reduced-row-echelon-form-1.ocaml b/Task/Reduced-row-echelon-form/OCaml/reduced-row-echelon-form-1.ml similarity index 100% rename from Task/Reduced-row-echelon-form/OCaml/reduced-row-echelon-form-1.ocaml rename to Task/Reduced-row-echelon-form/OCaml/reduced-row-echelon-form-1.ml diff --git a/Task/Reduced-row-echelon-form/OCaml/reduced-row-echelon-form-2.ocaml b/Task/Reduced-row-echelon-form/OCaml/reduced-row-echelon-form-2.ml similarity index 100% rename from Task/Reduced-row-echelon-form/OCaml/reduced-row-echelon-form-2.ocaml rename to Task/Reduced-row-echelon-form/OCaml/reduced-row-echelon-form-2.ml diff --git a/Task/Reduced-row-echelon-form/PARI-GP/reduced-row-echelon-form-1.parigp b/Task/Reduced-row-echelon-form/PARI-GP/reduced-row-echelon-form-1.parigp index 42dd3a3afc..dc72783863 100644 --- a/Task/Reduced-row-echelon-form/PARI-GP/reduced-row-echelon-form-1.parigp +++ b/Task/Reduced-row-echelon-form/PARI-GP/reduced-row-echelon-form-1.parigp @@ -1,17 +1,17 @@ matrref(M)= { - my(s=matsize(M),t=s[1]); - for(i=1,s[2], - if(M[t,i]==0, next); - M[t,] /= M[t,i]; - for(j=1,t-1, - M[j,] -= M[j,i]*M[t,] - ); - for(j=t+1,s[1], - M[j,] -= M[j,i]*M[t,] - ); - if(t--<1,break) - ); - M; + my(s=matsize(M),t=s[1]); + for(i=1,s[2], + if(M[t,i]==0, next); + M[t,] /= M[t,i]; + for(j=1,t-1, + M[j,] -= M[j,i]*M[t,] + ); + for(j=t+1,s[1], + M[j,] -= M[j,i]*M[t,] + ); + if(t--<1,break) + ); + M; } addhelp(matrref, "matrref(M): Returns the reduced row-echelon form of the matrix M."); diff --git a/Task/Reduced-row-echelon-form/Pluto/reduced-row-echelon-form.pluto b/Task/Reduced-row-echelon-form/Pluto/reduced-row-echelon-form.pluto new file mode 100644 index 0000000000..04aae87261 --- /dev/null +++ b/Task/Reduced-row-echelon-form/Pluto/reduced-row-echelon-form.pluto @@ -0,0 +1,12 @@ +require "matrix" + +local m = matrix.from({ + { 1, 2, -1, -4}, + { 2, 3, -1, -11}, + {-2, 0, -3, 22} +}) + +print("Original:\n") +print(m) +print("\nRREF:\n") +print(m:echelon():format("%2d")) diff --git a/Task/Reduced-row-echelon-form/Rebol/reduced-row-echelon-form.rebol b/Task/Reduced-row-echelon-form/Rebol/reduced-row-echelon-form.rebol new file mode 100644 index 0000000000..b4fe890c83 --- /dev/null +++ b/Task/Reduced-row-echelon-form/Rebol/reduced-row-echelon-form.rebol @@ -0,0 +1,66 @@ +Rebol [ + title: "Rosetta code: Reduced row echelon form" + file: %Reduced_row_echelon_form.r3 + url: https://rosettacode.org/wiki/Reduced_row_echelon_form +] + +to-reduced-row-echelon-form: function [ + "Transforms a matrix into Reduced Row Echelon Form (RREF) in-place." + M [block!] "Block of blocks, where each inner block represents a row. (modified)" +][ + for-r: 1 ;; Current pivot row index + lead: 1 ;; Current pivot column index + row-count: length? M ;; Total number of rows + column-count: length? M/1 ;; Total number of columns + + while [for-r <= row-count] [ + ;; If we've exhausted all columns, the matrix is fully reduced + if column-count <= lead [break] + + ;; Find the first row at or below for-r that has a non-zero entry in the lead column + i: for-r + while [M/:i/:lead = 0] [ + ++ i + ;; If we've scanned all rows without finding a pivot, move to the next column + if row-count = i [ + i: for-r + if column-count = lead [break] ; No more columns to try — exit + ++ lead + ] + ] + + ;; Swap row i with the current pivot row (for-r) so the pivot is in position + swap M/:i M/:for-r + + ;; Normalise the pivot row by dividing through by the pivot value, + ;; making the leading entry in this row equal to 1 + pivot: M/:for-r/:lead + if pivot <> 0 [ + row-r: for-r + repeat col column-count [ + M/:row-r/:col: M/:row-r/:col / pivot + ] + ] + + ;; Eliminate all other entries in the lead column by subtracting + ;; the appropriate multiple of the pivot row from every other row + repeat ii row-count [ + if ii <> for-r [ + factor: M/:ii/:lead ; How much of the pivot row to subtract + repeat col column-count [ + M/:ii/:col: M/:ii/:col - (factor * M/:for-r/:col) + ] + ] + ] + + ++ lead ;; Advance to the next pivot column + ++ for-r ;; Advance to the next pivot row + ] + M ;; Return the reduced matrix +] + +probe to-reduced-row-echelon-form [ + [ 1 2 -1 -4 ] + [ 2 3 -1 -11] + [-2 0 -3 22] +] diff --git a/Task/Reduced-row-echelon-form/Rust/reduced-row-echelon-form.rust b/Task/Reduced-row-echelon-form/Rust/reduced-row-echelon-form.rs similarity index 100% rename from Task/Reduced-row-echelon-form/Rust/reduced-row-echelon-form.rust rename to Task/Reduced-row-echelon-form/Rust/reduced-row-echelon-form.rs diff --git a/Task/Reduced-row-echelon-form/Scheme/reduced-row-echelon-form-1.ss b/Task/Reduced-row-echelon-form/Scheme/reduced-row-echelon-form-1.scm similarity index 100% rename from Task/Reduced-row-echelon-form/Scheme/reduced-row-echelon-form-1.ss rename to Task/Reduced-row-echelon-form/Scheme/reduced-row-echelon-form-1.scm diff --git a/Task/Reduced-row-echelon-form/Scheme/reduced-row-echelon-form-2.ss b/Task/Reduced-row-echelon-form/Scheme/reduced-row-echelon-form-2.scm similarity index 100% rename from Task/Reduced-row-echelon-form/Scheme/reduced-row-echelon-form-2.ss rename to Task/Reduced-row-echelon-form/Scheme/reduced-row-echelon-form-2.scm diff --git a/Task/Reduced-row-echelon-form/Scheme/reduced-row-echelon-form-3.ss b/Task/Reduced-row-echelon-form/Scheme/reduced-row-echelon-form-3.scm similarity index 100% rename from Task/Reduced-row-echelon-form/Scheme/reduced-row-echelon-form-3.ss rename to Task/Reduced-row-echelon-form/Scheme/reduced-row-echelon-form-3.scm diff --git a/Task/Reduced-row-echelon-form/Visual-FoxPro/reduced-row-echelon-form.fvp b/Task/Reduced-row-echelon-form/Visual-FoxPro/reduced-row-echelon-form.fvp index 1cd6502a7a..6509426a56 100644 --- a/Task/Reduced-row-echelon-form/Visual-FoxPro/reduced-row-echelon-form.fvp +++ b/Task/Reduced-row-echelon-form/Visual-FoxPro/reduced-row-echelon-form.fvp @@ -9,13 +9,13 @@ CREATE CURSOR curs1(c1 I, c2 I, c3 I, c4 I) INSERT INTO curs1 VALUES (1,2,-1,-4) INSERT INTO curs1 VALUES (2,3,-1,-11) INSERT INTO curs1 VALUES (-2,0,-3,22) -lnRows = RECCOUNT() && 3 -lnCols = FCOUNT() && 4 +lnRows = RECCOUNT() && 3 +lnCols = FCOUNT() && 4 SELECT * FROM curs1 INTO ARRAY matrix IF RREF(@matrix, lnRows, lnCols) - SELECT results - APPEND FROM ARRAY matrix - BROWSE NORMAL IN SCREEN + SELECT results + APPEND FROM ARRAY matrix + BROWSE NORMAL IN SCREEN ENDIF SET SAFETY &lcSafety @@ -26,44 +26,44 @@ llResult = .T. llExit = .F. lnPivot = 1 FOR r = 1 TO tnRows - IF lnPivot > tnCols - EXIT - ENDIF - i = r - DO WHILE mat[i,lnPivot] = 0 - i = i + 1 - IF i = tnRows - i = r - lnPivot = lnPivot + 1 - IF lnPivot > tnCols - llExit = .T. - EXIT - ENDIF - ENDIF - ENDDO - IF llExit - EXIT - ENDIF - ASwapRows(@mat, i, r) - p = mat[r,lnPivot] - IF p # 0 - FOR j = 1 TO tnCols - mat[r,j] = mat[r,j]/p - ENDFOR - ELSE - ? "Divison by zero." - llResult = .F. - EXIT - ENDIF - FOR i = 1 TO tnRows - IF i # r - p = mat[i,lnPivot] - FOR j = 1 TO tnCols - mat[i,j] = mat[i,j] - mat[r,j]*p - ENDFOR - ENDIF - ENDFOR - lnPivot = lnPivot + 1 + IF lnPivot > tnCols + EXIT + ENDIF + i = r + DO WHILE mat[i,lnPivot] = 0 + i = i + 1 + IF i = tnRows + i = r + lnPivot = lnPivot + 1 + IF lnPivot > tnCols + llExit = .T. + EXIT + ENDIF + ENDIF + ENDDO + IF llExit + EXIT + ENDIF + ASwapRows(@mat, i, r) + p = mat[r,lnPivot] + IF p # 0 + FOR j = 1 TO tnCols + mat[r,j] = mat[r,j]/p + ENDFOR + ELSE + ? "Divison by zero." + llResult = .F. + EXIT + ENDIF + FOR i = 1 TO tnRows + IF i # r + p = mat[i,lnPivot] + FOR j = 1 TO tnCols + mat[i,j] = mat[i,j] - mat[r,j]*p + ENDFOR + ENDIF + ENDFOR + lnPivot = lnPivot + 1 ENDFOR RETURN llResult ENDFUNC diff --git a/Task/Reduced-row-echelon-form/Zkl/reduced-row-echelon-form-1.zkl b/Task/Reduced-row-echelon-form/Zkl/reduced-row-echelon-form-1.zkl index c02a8bccc8..7d8f65b503 100644 --- a/Task/Reduced-row-echelon-form/Zkl/reduced-row-echelon-form-1.zkl +++ b/Task/Reduced-row-echelon-form/Zkl/reduced-row-echelon-form-1.zkl @@ -1,15 +1,15 @@ -var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library) +var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library) fcn toReducedRowEchelonForm(M){ // in place lead,rows,columns := 0,M.rows,M.cols; foreach r in (rows){ if (columns<=lead) return(M); i:=r; while(M[i,lead]==0){ // not a great check to use with real numbers - i+=1; - if(i==rows){ - i=r; lead+=1; - if(lead==columns) return(M); - } + i+=1; + if(i==rows){ + i=r; lead+=1; + if(lead==columns) return(M); + } } M.swapRows(i,r); if(x:=M[r,lead]) M[r]/=x; diff --git a/Task/Reduced-row-echelon-form/Zkl/reduced-row-echelon-form-2.zkl b/Task/Reduced-row-echelon-form/Zkl/reduced-row-echelon-form-2.zkl index 46bf3423a9..f41b401e8d 100644 --- a/Task/Reduced-row-echelon-form/Zkl/reduced-row-echelon-form-2.zkl +++ b/Task/Reduced-row-echelon-form/Zkl/reduced-row-echelon-form-2.zkl @@ -1,4 +1,4 @@ A:=GSL.Matrix(3,4).set( 1, 2, -1, -4, - 2, 3, -1, -11, - -2, 0, -3, 22); + 2, 3, -1, -11, + -2, 0, -3, 22); toReducedRowEchelonForm(A).format(5,1).println(); diff --git a/Task/Reduced-row-echelon-form/Zkl/reduced-row-echelon-form-3.zkl b/Task/Reduced-row-echelon-form/Zkl/reduced-row-echelon-form-3.zkl index 3e4e3c24a4..269bd88594 100644 --- a/Task/Reduced-row-echelon-form/Zkl/reduced-row-echelon-form-3.zkl +++ b/Task/Reduced-row-echelon-form/Zkl/reduced-row-echelon-form-3.zkl @@ -4,17 +4,17 @@ fcn toReducedRowEchelonForm(m){ // m is modified, the rows are not if(columnCount<=lead) break; i:=r; while(m[i][lead]==0){ - i+=1; - if(rowCount==i){ - i=r; lead+=1; - if(columnCount==lead) break; - } + i+=1; + if(rowCount==i){ + i=r; lead+=1; + if(columnCount==lead) break; + } }//while m.swap(i,r); // Swap rows i and r if(n:=m[r][lead]) m[r]=m[r].apply('/(n)); //divide row r by M[r,lead] foreach i in (rowCount){ if(i!=r) // Subtract M[i, lead] multiplied by row r from row i - m[i]=m[i].zipWith('-,m[r].apply('*(m[i][lead]))) + m[i]=m[i].zipWith('-,m[r].apply('*(m[i][lead]))) }//foreach lead+=1; }//foreach diff --git a/Task/Reduced-row-echelon-form/Zkl/reduced-row-echelon-form-4.zkl b/Task/Reduced-row-echelon-form/Zkl/reduced-row-echelon-form-4.zkl index 2d97f5265e..efc04dc761 100644 --- a/Task/Reduced-row-echelon-form/Zkl/reduced-row-echelon-form-4.zkl +++ b/Task/Reduced-row-echelon-form/Zkl/reduced-row-echelon-form-4.zkl @@ -1,6 +1,6 @@ m:=List( T( 1, 2, -1, -4,), // T is read only list T( 2, 3, -1, -11,), - T(-2, 0, -3, 22,)); + T(-2, 0, -3, 22,)); printM(m); println("-->"); printM(toReducedRowEchelonForm(m)); diff --git a/Task/Reflection-Get-source/C-sharp/reflection-get-source.cs b/Task/Reflection-Get-source/C-sharp/reflection-get-source.cs new file mode 100644 index 0000000000..c83560b942 --- /dev/null +++ b/Task/Reflection-Get-source/C-sharp/reflection-get-source.cs @@ -0,0 +1 @@ +Console.WriteLine(new System.Diagnostics.StackTrace(true).GetFrame(0)); diff --git a/Task/Reflection-Get-source/Julia/reflection-get-source.julia b/Task/Reflection-Get-source/Julia/reflection-get-source.jl similarity index 100% rename from Task/Reflection-Get-source/Julia/reflection-get-source.julia rename to Task/Reflection-Get-source/Julia/reflection-get-source.jl diff --git a/Task/Reflection-Get-source/Kotlin/reflection-get-source.kotlin b/Task/Reflection-Get-source/Kotlin/reflection-get-source.kts similarity index 100% rename from Task/Reflection-Get-source/Kotlin/reflection-get-source.kotlin rename to Task/Reflection-Get-source/Kotlin/reflection-get-source.kts diff --git a/Task/Reflection-List-methods/Arturo/reflection-list-methods.arturo b/Task/Reflection-List-methods/Arturo/reflection-list-methods.arturo new file mode 100644 index 0000000000..fe5abc95f4 --- /dev/null +++ b/Task/Reflection-List-methods/Arturo/reflection-list-methods.arturo @@ -0,0 +1,10 @@ +define :person [ + init: constructor [name surname] + + sayHello: method [][ + print ["Hello" \name "!"] + ] +] + +p: to :person ["John" "Doe"]! +print.lines methods p diff --git a/Task/Reflection-List-methods/DuckDB/reflection-list-methods.duckdb b/Task/Reflection-List-methods/DuckDB/reflection-list-methods.duckdb new file mode 100644 index 0000000000..f97160413c --- /dev/null +++ b/Task/Reflection-List-methods/DuckDB/reflection-list-methods.duckdb @@ -0,0 +1,14 @@ +create or replace function methods( type ) as table ( + select function_name, parameter_types + from duckdb_functions() + where upper(parameter_types[1]) = upper(type) + order by function_name +); + +create or replace function functions_with_signature( ds ) as table ( + with uc as (select list_transform(ds, x->upper(x)) as uc) + select function_name + from duckdb_functions(), uc + where list_transform(parameter_types, x->upper(x)) = uc + order by function_name +); diff --git a/Task/Reflection-List-methods/Ecstasy/reflection-list-methods.ecstasy b/Task/Reflection-List-methods/Ecstasy/reflection-list-methods.ecstasy new file mode 100644 index 0000000000..1685915756 --- /dev/null +++ b/Task/Reflection-List-methods/Ecstasy/reflection-list-methods.ecstasy @@ -0,0 +1,14 @@ +module test { + void run() { + @Inject Console console; + + String[] names = &this.actualType.multimethods.keys.toArray(); + console.print($"Method/function names on {this}: {names}"); + + Method[] methods = &this.actualType.methods; + console.print($"The methods of {this}: {methods}"); + + Function[] functions = &this.actualType.functions; + console.print($"The functions of {this}: {functions}"); + } +} diff --git a/Task/Reflection-List-methods/Elena/reflection-list-methods.elena b/Task/Reflection-List-methods/Elena/reflection-list-methods.elena index 54c0e7aece..efe979323d 100644 --- a/Task/Reflection-List-methods/Elena/reflection-list-methods.elena +++ b/Task/Reflection-List-methods/Elena/reflection-list-methods.elena @@ -9,12 +9,12 @@ class MyClass myMethod2(x) {} } -public program() +public Program() { var o := new MyClass(); o.__getClass().__getMessages().forEach::(p) { - console.printLine("o.",p) + Console.printLine("o.",p) } } diff --git a/Task/Reflection-List-methods/FreeBASIC/reflection-list-methods.basic b/Task/Reflection-List-methods/FreeBASIC/reflection-list-methods.basic new file mode 100644 index 0000000000..c6451cc060 --- /dev/null +++ b/Task/Reflection-List-methods/FreeBASIC/reflection-list-methods.basic @@ -0,0 +1,57 @@ +Type MetodoInfo + nombre As String + esEstatico As Integer + isPublico As Integer +End Type + +Type TestParaMetodoReflexion + Declare Sub MiMetodoPublico() + Declare Sub MiMetodoPrivado() + Declare Static Sub MiMetodoEstaticoPublico() + Declare Static Sub MiMetodoEstaticoPrivado() + dummy As Integer 'In FB an TYPE cannot be empty +End Type + +Sub TestParaMetodoReflexion.MiMetodoPublico() +End Sub + +Sub TestParaMetodoReflexion.MiMetodoPrivado() +End Sub + +Sub TestParaMetodoReflexion.MiMetodoEstaticoPublico() +End Sub + +Sub TestParaMetodoReflexion.MiMetodoEstaticoPrivado() +End Sub + +Sub ImprimeMetodoInfo(metodo As MetodoInfo) + Print "Method: "; metodo.nombre + Print Iif(metodo.esEstatico, " (Static)", " (Instance)") + Print Iif(metodo.isPublico, " (Public)", " (Private)") +End Sub + +Sub ObtenerMetodos(metodos() As MetodoInfo) + metodos(0).nombre = "MiMetodoPublico" + metodos(0).esEstatico = 0 + metodos(0).isPublico = 1 + + metodos(1).nombre = "MiMetodoPrivado" + metodos(1).esEstatico = 0 + metodos(1).isPublico = 0 + + metodos(2).nombre = "MiMetodoEstaticoPublico" + metodos(2).esEstatico = 1 + metodos(2).isPublico = 1 + + metodos(3).nombre = "MiMetodoEstaticoPrivado" + metodos(3).esEstatico = 1 + metodos(3).isPublico = 0 +End Sub + +Dim metodos(3) As MetodoInfo +ObtenerMetodos(metodos()) +For i As Integer = 0 To Ubound(metodos) + ImprimeMetodoInfo(metodos(i)) +Next + +Sleep diff --git a/Task/Reflection-List-methods/Julia/reflection-list-methods.julia b/Task/Reflection-List-methods/Julia/reflection-list-methods.jl similarity index 100% rename from Task/Reflection-List-methods/Julia/reflection-list-methods.julia rename to Task/Reflection-List-methods/Julia/reflection-list-methods.jl diff --git a/Task/Reflection-List-methods/Kotlin/reflection-list-methods.kotlin b/Task/Reflection-List-methods/Kotlin/reflection-list-methods.kts similarity index 100% rename from Task/Reflection-List-methods/Kotlin/reflection-list-methods.kotlin rename to Task/Reflection-List-methods/Kotlin/reflection-list-methods.kts diff --git a/Task/Reflection-List-methods/PascalABC.NET/reflection-list-methods.pas b/Task/Reflection-List-methods/PascalABC.NET/reflection-list-methods.pas new file mode 100644 index 0000000000..029c568793 --- /dev/null +++ b/Task/Reflection-List-methods/PascalABC.NET/reflection-list-methods.pas @@ -0,0 +1,7 @@ +## +uses System, System.Reflection; + +var flags := BindingFlags.Instance or BindingFlags.Static + or BindingFlags.Public or BindingFlags.DeclaredOnly; + +typeof(integer).GetMethods(flags).PrintLines; diff --git a/Task/Reflection-List-properties/DuckDB/reflection-list-properties.duckdb b/Task/Reflection-List-properties/DuckDB/reflection-list-properties.duckdb new file mode 100644 index 0000000000..729b194281 --- /dev/null +++ b/Task/Reflection-List-properties/DuckDB/reflection-list-properties.duckdb @@ -0,0 +1 @@ +select column_name from (describe TABLE); diff --git a/Task/Reflection-List-properties/Ecstasy/reflection-list-properties.ecstasy b/Task/Reflection-List-properties/Ecstasy/reflection-list-properties.ecstasy new file mode 100644 index 0000000000..3c79454fd4 --- /dev/null +++ b/Task/Reflection-List-properties/Ecstasy/reflection-list-properties.ecstasy @@ -0,0 +1,7 @@ +module test { + void run() { + @Inject Console console; + Property[] properties = &this.actualType.properties; + console.print($"The properties of {this}: {properties}"); + } +} diff --git a/Task/Reflection-List-properties/Elena/reflection-list-properties.elena b/Task/Reflection-List-properties/Elena/reflection-list-properties.elena index 0397b02201..55d5cf71bc 100644 --- a/Task/Reflection-List-properties/Elena/reflection-list-properties.elena +++ b/Task/Reflection-List-properties/Elena/reflection-list-properties.elena @@ -8,7 +8,7 @@ class MyClass string Y : prop; } -public program() +public Program() { var o := new MyClass { @@ -19,6 +19,6 @@ public program() MyClass.__getProperties().forEach::(p) { - console.printLine("o.",p,"=",p.getPropertyValue(o)) + Console.printLine("o.",p,"=",p.getPropertyValue(o)) } } diff --git a/Task/Reflection-List-properties/FreeBASIC/reflection-list-properties.basic b/Task/Reflection-List-properties/FreeBASIC/reflection-list-properties.basic new file mode 100644 index 0000000000..748ef6e846 --- /dev/null +++ b/Task/Reflection-List-properties/FreeBASIC/reflection-list-properties.basic @@ -0,0 +1,32 @@ +Type TestClass + Private: + PrivateField As Integer = 7 + PrivateNumber As Integer = 2 + Public: + PublicNumber As Integer = 4 + Declare Function GetPrivateField() As Integer + Declare Function GetPrivateNumber() As Integer +End Type + +Function TestClass.GetPrivateField() As Integer + Return PrivateField +End Function + +Function TestClass.GetPrivateNumber() As Integer + Return PrivateNumber +End Function + +Sub GetPropertyValues(Byval obj As TestClass Ptr) + Print "PublicNumber: " & obj->PublicNumber +End Sub + +Sub GetFieldValues(Byval obj As TestClass Ptr) + Print "PrivateField: " & obj->GetPrivateField() + Print "PrivateNumber: " & obj->GetPrivateNumber() +End Sub + +Dim As TestClass t +GetPropertyValues(@t) +GetFieldValues(@t) + +Sleep diff --git a/Task/Reflection-List-properties/Julia/reflection-list-properties.julia b/Task/Reflection-List-properties/Julia/reflection-list-properties.jl similarity index 100% rename from Task/Reflection-List-properties/Julia/reflection-list-properties.julia rename to Task/Reflection-List-properties/Julia/reflection-list-properties.jl diff --git a/Task/Reflection-List-properties/Kotlin/reflection-list-properties.kotlin b/Task/Reflection-List-properties/Kotlin/reflection-list-properties.kts similarity index 100% rename from Task/Reflection-List-properties/Kotlin/reflection-list-properties.kotlin rename to Task/Reflection-List-properties/Kotlin/reflection-list-properties.kts diff --git a/Task/Reflection-List-properties/PascalABC.NET/reflection-list-properties.pas b/Task/Reflection-List-properties/PascalABC.NET/reflection-list-properties.pas new file mode 100644 index 0000000000..b614140a49 --- /dev/null +++ b/Task/Reflection-List-properties/PascalABC.NET/reflection-list-properties.pas @@ -0,0 +1,19 @@ +uses System, System.Reflection; + +type + MyClass = class + private + auto property NumberPrivate: integer := 666; + public + auto property Number: integer := 3; + end; + +begin + var flags := BindingFlags.Instance or BindingFlags.Static + or BindingFlags.Public or BindingFlags.NonPublic + or BindingFlags.DeclaredOnly; + + var obj := new MyClass; + + typeof(MyClass).GetProperties(flags).Select(p -> (p.Name,p.GetValue(obj))).PrintLines; +end. diff --git a/Task/Reflection-List-properties/PowerShell/reflection-list-properties-1.psh b/Task/Reflection-List-properties/PowerShell/reflection-list-properties-1.ps1 similarity index 100% rename from Task/Reflection-List-properties/PowerShell/reflection-list-properties-1.psh rename to Task/Reflection-List-properties/PowerShell/reflection-list-properties-1.ps1 diff --git a/Task/Reflection-List-properties/PowerShell/reflection-list-properties-2.psh b/Task/Reflection-List-properties/PowerShell/reflection-list-properties-2.ps1 similarity index 100% rename from Task/Reflection-List-properties/PowerShell/reflection-list-properties-2.psh rename to Task/Reflection-List-properties/PowerShell/reflection-list-properties-2.ps1 diff --git a/Task/Regular-expressions/Ada/regular-expressions.ada b/Task/Regular-expressions/Ada/regular-expressions.adb similarity index 100% rename from Task/Regular-expressions/Ada/regular-expressions.ada rename to Task/Regular-expressions/Ada/regular-expressions.adb diff --git a/Task/Regular-expressions/Crystal/regular-expressions.cr b/Task/Regular-expressions/Crystal/regular-expressions.cr new file mode 100644 index 0000000000..89f8c44061 --- /dev/null +++ b/Task/Regular-expressions/Crystal/regular-expressions.cr @@ -0,0 +1,7 @@ +s = "I am a string" +# Match +s =~ /string$/ # => 7 +s =~ /^You/ # => nil +# Substitute +s.sub(/\ba\b/, "a different") # => "I am a different string" +s.gsub(/\b\w/) {|c| c.upcase } # => "I Am A String" diff --git a/Task/Regular-expressions/Delphi/regular-expressions.delphi b/Task/Regular-expressions/Delphi/regular-expressions.pas similarity index 100% rename from Task/Regular-expressions/Delphi/regular-expressions.delphi rename to Task/Regular-expressions/Delphi/regular-expressions.pas diff --git a/Task/Regular-expressions/Ed/regular-expressions.ed b/Task/Regular-expressions/Ed/regular-expressions.ed new file mode 100644 index 0000000000..569f3b6aa3 --- /dev/null +++ b/Task/Regular-expressions/Ed/regular-expressions.ed @@ -0,0 +1,7 @@ +# by Artyom Bologov +H +t0 +1s/^.*string.*$/Ends with string/ +2s/ a / another / +,p +Q diff --git a/Task/Regular-expressions/Elixir/regular-expressions-1.elixir b/Task/Regular-expressions/Elixir/regular-expressions-1.ex similarity index 100% rename from Task/Regular-expressions/Elixir/regular-expressions-1.elixir rename to Task/Regular-expressions/Elixir/regular-expressions-1.ex diff --git a/Task/Regular-expressions/Elixir/regular-expressions-2.elixir b/Task/Regular-expressions/Elixir/regular-expressions-2.ex similarity index 100% rename from Task/Regular-expressions/Elixir/regular-expressions-2.elixir rename to Task/Regular-expressions/Elixir/regular-expressions-2.ex diff --git a/Task/Regular-expressions/Elixir/regular-expressions-3.elixir b/Task/Regular-expressions/Elixir/regular-expressions-3.ex similarity index 100% rename from Task/Regular-expressions/Elixir/regular-expressions-3.elixir rename to Task/Regular-expressions/Elixir/regular-expressions-3.ex diff --git a/Task/Regular-expressions/Elixir/regular-expressions-4.elixir b/Task/Regular-expressions/Elixir/regular-expressions-4.ex similarity index 100% rename from Task/Regular-expressions/Elixir/regular-expressions-4.elixir rename to Task/Regular-expressions/Elixir/regular-expressions-4.ex diff --git a/Task/Regular-expressions/Emacs-Lisp/regular-expressions.l b/Task/Regular-expressions/Emacs-Lisp/regular-expressions.el similarity index 100% rename from Task/Regular-expressions/Emacs-Lisp/regular-expressions.l rename to Task/Regular-expressions/Emacs-Lisp/regular-expressions.el diff --git a/Task/Regular-expressions/FutureBasic/regular-expressions.basic b/Task/Regular-expressions/FutureBasic/regular-expressions.basic new file mode 100644 index 0000000000..713af31a3c --- /dev/null +++ b/Task/Regular-expressions/FutureBasic/regular-expressions.basic @@ -0,0 +1,20 @@ +void local fn DoIt + CFStringRef string = @"I am a string" + CFStringRef fmt = @".*string$" + PredicateRef pred = fn PredicateWithFormat( @"SELF MATCHES %@", fmt ) + + if ( fn PredicateEvaluateWithObject( pred, string ) ) + printf @"\"%@\" ends with \"string\"",string + end if + + print + + CFStringRef orig = @"I am the original string" + RegularExpressionRef regex = fn RegularExpressionWithPattern( @"original", 0, NULL ) + CFStringRef result = fn RegularExpressionStringByReplacingMatches( regex, orig, 0, fn CFRangeMake(0,len(orig)), @"modified" ) + print result +end fn + +fn DoIt + +HandleEvents diff --git a/Task/Regular-expressions/Haskell/regular-expressions-1.hs b/Task/Regular-expressions/Haskell/regular-expressions-1.hs index f8d1fc5bc4..57eb29ab99 100644 --- a/Task/Regular-expressions/Haskell/regular-expressions-1.hs +++ b/Task/Regular-expressions/Haskell/regular-expressions-1.hs @@ -1,7 +1,2 @@ -import Text.Regex - -str = "I am a string" - -case matchRegex (mkRegex ".*string$") str of - Just _ -> putStrLn $ "ends with 'string'" - Nothing -> return () +ghci> import Text.Regex.TDFA +ghci> "I am a string" =~ ".*string$" :: Bool diff --git a/Task/Regular-expressions/Haskell/regular-expressions-2.hs b/Task/Regular-expressions/Haskell/regular-expressions-2.hs index 9b21ddc54d..6c7f09e4b5 100644 --- a/Task/Regular-expressions/Haskell/regular-expressions-2.hs +++ b/Task/Regular-expressions/Haskell/regular-expressions-2.hs @@ -1,5 +1,3 @@ -import Text.Regex - -orig = "I am the original string" -result = subRegex (mkRegex "original") orig "modified" -putStrLn $ result +ghci> import Text.Regex.TDFA +ghci> compiled = makeRegex ".*string$" :: Regex +ghci> match compiled "I am a string" :: Bool diff --git a/Task/Regular-expressions/Haskell/regular-expressions-3.hs b/Task/Regular-expressions/Haskell/regular-expressions-3.hs new file mode 100644 index 0000000000..f8d1fc5bc4 --- /dev/null +++ b/Task/Regular-expressions/Haskell/regular-expressions-3.hs @@ -0,0 +1,7 @@ +import Text.Regex + +str = "I am a string" + +case matchRegex (mkRegex ".*string$") str of + Just _ -> putStrLn $ "ends with 'string'" + Nothing -> return () diff --git a/Task/Regular-expressions/Haskell/regular-expressions-4.hs b/Task/Regular-expressions/Haskell/regular-expressions-4.hs new file mode 100644 index 0000000000..9b21ddc54d --- /dev/null +++ b/Task/Regular-expressions/Haskell/regular-expressions-4.hs @@ -0,0 +1,5 @@ +import Text.Regex + +orig = "I am the original string" +result = subRegex (mkRegex "original") orig "modified" +putStrLn $ result diff --git a/Task/Regular-expressions/Julia/regular-expressions-1.julia b/Task/Regular-expressions/Julia/regular-expressions-1.jl similarity index 100% rename from Task/Regular-expressions/Julia/regular-expressions-1.julia rename to Task/Regular-expressions/Julia/regular-expressions-1.jl diff --git a/Task/Regular-expressions/Julia/regular-expressions-2.julia b/Task/Regular-expressions/Julia/regular-expressions-2.jl similarity index 100% rename from Task/Regular-expressions/Julia/regular-expressions-2.julia rename to Task/Regular-expressions/Julia/regular-expressions-2.jl diff --git a/Task/Regular-expressions/Kotlin/regular-expressions.kotlin b/Task/Regular-expressions/Kotlin/regular-expressions.kts similarity index 100% rename from Task/Regular-expressions/Kotlin/regular-expressions.kotlin rename to Task/Regular-expressions/Kotlin/regular-expressions.kts diff --git a/Task/Regular-expressions/Langur/regular-expressions-2.langur b/Task/Regular-expressions/Langur/regular-expressions-2.langur index 6d9268d481..9be6f90975 100644 --- a/Task/Regular-expressions/Langur/regular-expressions-2.langur +++ b/Task/Regular-expressions/Langur/regular-expressions-2.langur @@ -1 +1 @@ -if val .x, .y = submatch(re/(abc+).+?(def)/, "somestring") { ... } +if x, y = submatch("somestring", by=re/(abc+).+?(def)/) { ... } diff --git a/Task/Regular-expressions/Langur/regular-expressions-5.langur b/Task/Regular-expressions/Langur/regular-expressions-5.langur index dd3a7ba9f8..01569b08a3 100644 --- a/Task/Regular-expressions/Langur/regular-expressions-5.langur +++ b/Task/Regular-expressions/Langur/regular-expressions-5.langur @@ -1,2 +1,2 @@ -replace("abcdef", re/abc/, "Y") +replace("abcdef", by=re/abc/, with="Y") # result: "Ydef" diff --git a/Task/Regular-expressions/M2000-Interpreter/regular-expressions.m2000 b/Task/Regular-expressions/M2000-Interpreter/regular-expressions.m2000 index 789fadbe15..ce42a448a3 100644 --- a/Task/Regular-expressions/M2000-Interpreter/regular-expressions.m2000 +++ b/Task/Regular-expressions/M2000-Interpreter/regular-expressions.m2000 @@ -52,7 +52,7 @@ Checkit -\\ internal has no pattern. There is a like operator (~) for strings which use pattern matching (using VB6 like). We can use Instr() and RInstr() for strings. +' internal has no pattern. There is a like operator (~) for strings which use pattern matching (using VB6 like). We can use Instr() and RInstr() for strings. Module Internal { what$="Mona Lisa" diff --git a/Task/Regular-expressions/Maxima/regular-expressions.maxima b/Task/Regular-expressions/Maxima/regular-expressions.maxima new file mode 100644 index 0000000000..2c980b591c --- /dev/null +++ b/Task/Regular-expressions/Maxima/regular-expressions.maxima @@ -0,0 +1,5 @@ +load("sregex")$ +regex_match("\\W[A-Z]", "Hello World!"); /* returns matched substring */ +regex_match("\\W[A-Z]", "Hello world!"); /* returns false if no match */ +regex_subst_first("4", "[Aa]", "Abracadabra!"); /* replaces first match */ +regex_subst("4", "[Aa]", "Abracadabra!"); /* replaces all matches */ diff --git a/Task/Regular-expressions/OCaml/regular-expressions-1.ocaml b/Task/Regular-expressions/OCaml/regular-expressions-1.ml similarity index 100% rename from Task/Regular-expressions/OCaml/regular-expressions-1.ocaml rename to Task/Regular-expressions/OCaml/regular-expressions-1.ml diff --git a/Task/Regular-expressions/OCaml/regular-expressions-2.ocaml b/Task/Regular-expressions/OCaml/regular-expressions-2.ml similarity index 100% rename from Task/Regular-expressions/OCaml/regular-expressions-2.ocaml rename to Task/Regular-expressions/OCaml/regular-expressions-2.ml diff --git a/Task/Regular-expressions/OCaml/regular-expressions-3.ocaml b/Task/Regular-expressions/OCaml/regular-expressions-3.ml similarity index 100% rename from Task/Regular-expressions/OCaml/regular-expressions-3.ocaml rename to Task/Regular-expressions/OCaml/regular-expressions-3.ml diff --git a/Task/Regular-expressions/Ol/regular-expressions.ol b/Task/Regular-expressions/Ol/regular-expressions.ol index bfe558ab60..41756cedf1 100644 --- a/Task/Regular-expressions/Ol/regular-expressions.ol +++ b/Task/Regular-expressions/Ol/regular-expressions.ol @@ -1,11 +1,9 @@ ; matching: -(define regex (string->regex "m/aa(bb|cc)dd/")) -(print (regex "aabbddx")) ; => true -(print (regex "aaccddx")) ; => true -(print (regex "aabcddx")) ; => false +(print (m/aa(bb|cc)dd/ "aabbddx")) ; => true +(print (m/aa(bb|cc)dd/ "aaccddx")) ; => true +(print (m/aa(bb|cc)dd/ "aabcddx")) ; => false ; substitute part of a string: -(define regex (string->regex "s/aa(bb|cc)dd/HAHAHA/")) -(print (regex "aabbddx")) ; => HAHAHAx -(print (regex "aaccddx")) ; => HAHAHAx -(print (regex "aabcddx")) ; => false +(print (s/aa(bb|cc)dd/HAHAHA/ "aabbddx")) ; => HAHAHAx +(print (s/aa(bb|cc)dd/HAHAHA/ "aaccddx")) ; => HAHAHAx +(print (s/aa(bb|cc)dd/HAHAHA/ "aabcddx")) ; => false diff --git a/Task/Regular-expressions/PascalABC.NET/regular-expressions.pas b/Task/Regular-expressions/PascalABC.NET/regular-expressions.pas new file mode 100644 index 0000000000..97899d31e8 --- /dev/null +++ b/Task/Regular-expressions/PascalABC.NET/regular-expressions.pas @@ -0,0 +1,10 @@ +begin + // text in tag (lazy quantification) + var s := 'abc def ghi'; + foreach var m in s.Matches('(?<=)(.*?)(?=)') do + Println(m.Value, m.Index); + + // take words in parentheses + s := 'one two three four five'; + Regex.Replace(s,'\w+','<$0>').Println; +end. diff --git a/Task/Regular-expressions/PowerShell/regular-expressions.psh b/Task/Regular-expressions/PowerShell/regular-expressions.ps1 similarity index 100% rename from Task/Regular-expressions/PowerShell/regular-expressions.psh rename to Task/Regular-expressions/PowerShell/regular-expressions.ps1 diff --git a/Task/Regular-expressions/REBOL/regular-expressions.rebol b/Task/Regular-expressions/Rebol/regular-expressions.rebol similarity index 94% rename from Task/Regular-expressions/REBOL/regular-expressions.rebol rename to Task/Regular-expressions/Rebol/regular-expressions.rebol index c2f8ae8c94..5d66ddebce 100644 --- a/Task/Regular-expressions/REBOL/regular-expressions.rebol +++ b/Task/Regular-expressions/Rebol/regular-expressions.rebol @@ -1,11 +1,11 @@ -REBOL [ +Rebol [ Title: "Regular Expression Matching" URL: http://rosettacode.org/wiki/Regular_expression_matching ] string: "This is a string." -; REBOL doesn't use a conventional Perl-compatible regular expression +; Rebol doesn't use a conventional Perl-compatible regular expression ; syntax. Instead, it uses a variant Parsing Expression Grammar with ; the 'parse' function. It's also not limited to just strings. You can ; define complex grammars that actually parse and execute program diff --git a/Task/Regular-expressions/Rust/regular-expressions.rust b/Task/Regular-expressions/Rust/regular-expressions.rs similarity index 100% rename from Task/Regular-expressions/Rust/regular-expressions.rust rename to Task/Regular-expressions/Rust/regular-expressions.rs diff --git a/Task/Regular-expressions/V-(Vlang)/regular-expressions.v b/Task/Regular-expressions/V-(Vlang)/regular-expressions.v new file mode 100644 index 0000000000..4de8bb4a29 --- /dev/null +++ b/Task/Regular-expressions/V-(Vlang)/regular-expressions.v @@ -0,0 +1,11 @@ +import regex + +fn main() { + mut r1 := regex.regex_opt("^.*string$")! + mut r2 := regex.regex_opt("original")! + s1 := "I am the original string" + s3 := "replacement" + s2 := r2.replace(s1, s3) + if r1.matches_string(s1) {println("`${s1}` matches `${r1.query}`")} else {println("Failed!")} + if s2 != s1 {println("`${s2}` replaces `${r2.query}` with `${s3}`")} +} diff --git a/Task/Regular-expressions/VBScript/regular-expressions.vb b/Task/Regular-expressions/VBScript/regular-expressions.vbs similarity index 100% rename from Task/Regular-expressions/VBScript/regular-expressions.vb rename to Task/Regular-expressions/VBScript/regular-expressions.vbs diff --git a/Task/Remove-duplicate-elements/Ada/remove-duplicate-elements.ada b/Task/Remove-duplicate-elements/Ada/remove-duplicate-elements.adb similarity index 100% rename from Task/Remove-duplicate-elements/Ada/remove-duplicate-elements.ada rename to Task/Remove-duplicate-elements/Ada/remove-duplicate-elements.adb diff --git a/Task/Remove-duplicate-elements/Crystal/remove-duplicate-elements.crystal b/Task/Remove-duplicate-elements/Crystal/remove-duplicate-elements.cr similarity index 100% rename from Task/Remove-duplicate-elements/Crystal/remove-duplicate-elements.crystal rename to Task/Remove-duplicate-elements/Crystal/remove-duplicate-elements.cr diff --git a/Task/Remove-duplicate-elements/Delphi/remove-duplicate-elements.delphi b/Task/Remove-duplicate-elements/Delphi/remove-duplicate-elements.pas similarity index 100% rename from Task/Remove-duplicate-elements/Delphi/remove-duplicate-elements.delphi rename to Task/Remove-duplicate-elements/Delphi/remove-duplicate-elements.pas diff --git a/Task/Remove-duplicate-elements/DuckDB/remove-duplicate-elements-1.duckdb b/Task/Remove-duplicate-elements/DuckDB/remove-duplicate-elements-1.duckdb new file mode 100644 index 0000000000..7ca77f8f20 --- /dev/null +++ b/Task/Remove-duplicate-elements/DuckDB/remove-duplicate-elements-1.duckdb @@ -0,0 +1 @@ +select distinct(*) from unnest( [3,9,1,10,3,7,6,5,2,7,4,7,4,2,2,2,2,8,2,10,4,9,2,4,9,3,4,3,4,7] ); diff --git a/Task/Remove-duplicate-elements/DuckDB/remove-duplicate-elements-2.duckdb b/Task/Remove-duplicate-elements/DuckDB/remove-duplicate-elements-2.duckdb new file mode 100644 index 0000000000..6d0ef3ff67 --- /dev/null +++ b/Task/Remove-duplicate-elements/DuckDB/remove-duplicate-elements-2.duckdb @@ -0,0 +1 @@ +select array_agg(unnest) as distinct from (select distinct(*) from unnest( [3,9,1,10,3,7,6,5,2,7,4,7,4,2,2,2,2,8,2,10,4,9,2,4,9,3,4,3,4,7] )); diff --git a/Task/Remove-duplicate-elements/DuckDB/remove-duplicate-elements-3.duckdb b/Task/Remove-duplicate-elements/DuckDB/remove-duplicate-elements-3.duckdb new file mode 100644 index 0000000000..2e6213bb6d --- /dev/null +++ b/Task/Remove-duplicate-elements/DuckDB/remove-duplicate-elements-3.duckdb @@ -0,0 +1,6 @@ +CREATE OR REPLACE MACRO firsts(l) as ( + WITH + t as (SELECT unnest(l) as x, generate_subscripts(l, 1) as index), + s as (SELECT x, min(index) as index FROM t GROUP BY x) + SELECT list(x ORDER BY index) + FROM s ) ; diff --git a/Task/Remove-duplicate-elements/DuckDB/remove-duplicate-elements-4.duckdb b/Task/Remove-duplicate-elements/DuckDB/remove-duplicate-elements-4.duckdb new file mode 100644 index 0000000000..100d913138 --- /dev/null +++ b/Task/Remove-duplicate-elements/DuckDB/remove-duplicate-elements-4.duckdb @@ -0,0 +1 @@ +select firsts( [3,9,1,10,3,7,6,5,2,7,4,7,4,2,2,2,2,8,2,10,4,9,2,4,9,3,4,3,4,7]) as firsts; diff --git a/Task/Remove-duplicate-elements/Elena/remove-duplicate-elements.elena b/Task/Remove-duplicate-elements/Elena/remove-duplicate-elements.elena index 80075ac1c9..13d7450f23 100644 --- a/Task/Remove-duplicate-elements/Elena/remove-duplicate-elements.elena +++ b/Task/Remove-duplicate-elements/Elena/remove-duplicate-elements.elena @@ -2,12 +2,12 @@ import extensions; import system'collections; import system'routines; -public program() +public Program() { var nums := new int[]{1,1,2,3,4,4}; auto unique := new Map(); nums.forEach::(n){ unique[n] := n }; - console.printLine(unique.MapValues.asEnumerable()) + Console.printLine(unique.MapValues.asEnumerable()) } diff --git a/Task/Remove-duplicate-elements/Elixir/remove-duplicate-elements.elixir b/Task/Remove-duplicate-elements/Elixir/remove-duplicate-elements.ex similarity index 100% rename from Task/Remove-duplicate-elements/Elixir/remove-duplicate-elements.elixir rename to Task/Remove-duplicate-elements/Elixir/remove-duplicate-elements.ex diff --git a/Task/Remove-duplicate-elements/Euphoria/remove-duplicate-elements.euphoria b/Task/Remove-duplicate-elements/Euphoria/remove-duplicate-elements.eu similarity index 100% rename from Task/Remove-duplicate-elements/Euphoria/remove-duplicate-elements.euphoria rename to Task/Remove-duplicate-elements/Euphoria/remove-duplicate-elements.eu diff --git a/Task/Remove-duplicate-elements/Julia/remove-duplicate-elements.julia b/Task/Remove-duplicate-elements/Julia/remove-duplicate-elements.jl similarity index 100% rename from Task/Remove-duplicate-elements/Julia/remove-duplicate-elements.julia rename to Task/Remove-duplicate-elements/Julia/remove-duplicate-elements.jl diff --git a/Task/Remove-duplicate-elements/Kotlin/remove-duplicate-elements.kotlin b/Task/Remove-duplicate-elements/Kotlin/remove-duplicate-elements.kts similarity index 100% rename from Task/Remove-duplicate-elements/Kotlin/remove-duplicate-elements.kotlin rename to Task/Remove-duplicate-elements/Kotlin/remove-duplicate-elements.kts diff --git a/Task/Remove-duplicate-elements/Nu/remove-duplicate-elements.nu b/Task/Remove-duplicate-elements/Nu/remove-duplicate-elements.nu new file mode 100644 index 0000000000..3f13bd5380 --- /dev/null +++ b/Task/Remove-duplicate-elements/Nu/remove-duplicate-elements.nu @@ -0,0 +1 @@ +[2 1 8 3 5 1 4 8 2 9] | uniq | grid diff --git a/Task/Remove-duplicate-elements/OCaml/remove-duplicate-elements-1.ocaml b/Task/Remove-duplicate-elements/OCaml/remove-duplicate-elements-1.ml similarity index 100% rename from Task/Remove-duplicate-elements/OCaml/remove-duplicate-elements-1.ocaml rename to Task/Remove-duplicate-elements/OCaml/remove-duplicate-elements-1.ml diff --git a/Task/Remove-duplicate-elements/OCaml/remove-duplicate-elements-2.ocaml b/Task/Remove-duplicate-elements/OCaml/remove-duplicate-elements-2.ml similarity index 100% rename from Task/Remove-duplicate-elements/OCaml/remove-duplicate-elements-2.ocaml rename to Task/Remove-duplicate-elements/OCaml/remove-duplicate-elements-2.ml diff --git a/Task/Remove-duplicate-elements/OCaml/remove-duplicate-elements-3.ocaml b/Task/Remove-duplicate-elements/OCaml/remove-duplicate-elements-3.ml similarity index 100% rename from Task/Remove-duplicate-elements/OCaml/remove-duplicate-elements-3.ocaml rename to Task/Remove-duplicate-elements/OCaml/remove-duplicate-elements-3.ml diff --git a/Task/Remove-duplicate-elements/OCaml/remove-duplicate-elements-4.ocaml b/Task/Remove-duplicate-elements/OCaml/remove-duplicate-elements-4.ml similarity index 100% rename from Task/Remove-duplicate-elements/OCaml/remove-duplicate-elements-4.ocaml rename to Task/Remove-duplicate-elements/OCaml/remove-duplicate-elements-4.ml diff --git a/Task/Remove-duplicate-elements/PascalABC.NET/remove-duplicate-elements.pas b/Task/Remove-duplicate-elements/PascalABC.NET/remove-duplicate-elements.pas new file mode 100644 index 0000000000..2b4aaedfa1 --- /dev/null +++ b/Task/Remove-duplicate-elements/PascalABC.NET/remove-duplicate-elements.pas @@ -0,0 +1,17 @@ +begin + // By algorithm + var nums := Arr(1, 1, 2, 3, 4, 4); + var unique := new List; + foreach var x in nums do + if x not in unique then + unique.Add(x); + unique.Println; + + // By method + var unique2 := nums.Distinct; + unique2.Println; + + // Using hash set + var unique3 := HSet(nums); + unique3.Println; +end. diff --git a/Task/Remove-duplicate-elements/PowerShell/remove-duplicate-elements-1.psh b/Task/Remove-duplicate-elements/PowerShell/remove-duplicate-elements-1.ps1 similarity index 100% rename from Task/Remove-duplicate-elements/PowerShell/remove-duplicate-elements-1.psh rename to Task/Remove-duplicate-elements/PowerShell/remove-duplicate-elements-1.ps1 diff --git a/Task/Remove-duplicate-elements/PowerShell/remove-duplicate-elements-2.psh b/Task/Remove-duplicate-elements/PowerShell/remove-duplicate-elements-2.ps1 similarity index 100% rename from Task/Remove-duplicate-elements/PowerShell/remove-duplicate-elements-2.psh rename to Task/Remove-duplicate-elements/PowerShell/remove-duplicate-elements-2.ps1 diff --git a/Task/Remove-duplicate-elements/PowerShell/remove-duplicate-elements-3.psh b/Task/Remove-duplicate-elements/PowerShell/remove-duplicate-elements-3.ps1 similarity index 100% rename from Task/Remove-duplicate-elements/PowerShell/remove-duplicate-elements-3.psh rename to Task/Remove-duplicate-elements/PowerShell/remove-duplicate-elements-3.ps1 diff --git a/Task/Remove-duplicate-elements/PowerShell/remove-duplicate-elements-4.psh b/Task/Remove-duplicate-elements/PowerShell/remove-duplicate-elements-4.ps1 similarity index 100% rename from Task/Remove-duplicate-elements/PowerShell/remove-duplicate-elements-4.psh rename to Task/Remove-duplicate-elements/PowerShell/remove-duplicate-elements-4.ps1 diff --git a/Task/Remove-duplicate-elements/REBOL/remove-duplicate-elements.rebol b/Task/Remove-duplicate-elements/Rebol/remove-duplicate-elements.rebol similarity index 100% rename from Task/Remove-duplicate-elements/REBOL/remove-duplicate-elements.rebol rename to Task/Remove-duplicate-elements/Rebol/remove-duplicate-elements.rebol diff --git a/Task/Remove-duplicate-elements/Rust/remove-duplicate-elements.rust b/Task/Remove-duplicate-elements/Rust/remove-duplicate-elements.rs similarity index 100% rename from Task/Remove-duplicate-elements/Rust/remove-duplicate-elements.rust rename to Task/Remove-duplicate-elements/Rust/remove-duplicate-elements.rs diff --git a/Task/Remove-duplicate-elements/Rye/remove-duplicate-elements.rye b/Task/Remove-duplicate-elements/Rye/remove-duplicate-elements.rye new file mode 100644 index 0000000000..2c5c2db185 --- /dev/null +++ b/Task/Remove-duplicate-elements/Rye/remove-duplicate-elements.rye @@ -0,0 +1,2 @@ +data: { 6 5 5 7 "a" 1 2 3 2 4 1 5 "a" } +unique data |sort |print diff --git a/Task/Remove-duplicate-elements/Scheme/remove-duplicate-elements-1.ss b/Task/Remove-duplicate-elements/Scheme/remove-duplicate-elements-1.scm similarity index 100% rename from Task/Remove-duplicate-elements/Scheme/remove-duplicate-elements-1.ss rename to Task/Remove-duplicate-elements/Scheme/remove-duplicate-elements-1.scm diff --git a/Task/Remove-duplicate-elements/Scheme/remove-duplicate-elements-2.ss b/Task/Remove-duplicate-elements/Scheme/remove-duplicate-elements-2.scm similarity index 100% rename from Task/Remove-duplicate-elements/Scheme/remove-duplicate-elements-2.ss rename to Task/Remove-duplicate-elements/Scheme/remove-duplicate-elements-2.scm diff --git a/Task/Remove-duplicate-elements/Scheme/remove-duplicate-elements-3.ss b/Task/Remove-duplicate-elements/Scheme/remove-duplicate-elements-3.scm similarity index 100% rename from Task/Remove-duplicate-elements/Scheme/remove-duplicate-elements-3.ss rename to Task/Remove-duplicate-elements/Scheme/remove-duplicate-elements-3.scm diff --git a/Task/Remove-duplicate-elements/Scheme/remove-duplicate-elements-4.ss b/Task/Remove-duplicate-elements/Scheme/remove-duplicate-elements-4.scm similarity index 100% rename from Task/Remove-duplicate-elements/Scheme/remove-duplicate-elements-4.ss rename to Task/Remove-duplicate-elements/Scheme/remove-duplicate-elements-4.scm diff --git a/Task/Remove-duplicate-elements/Scheme/remove-duplicate-elements-5.scm b/Task/Remove-duplicate-elements/Scheme/remove-duplicate-elements-5.scm new file mode 100644 index 0000000000..54487b5918 --- /dev/null +++ b/Task/Remove-duplicate-elements/Scheme/remove-duplicate-elements-5.scm @@ -0,0 +1,21 @@ +(define-syntax ainc! + (syntax-rules () + [(_ alist key val func default) + (let ((pair (assoc key alist))) + (if pair + (set-cdr! pair (func val (cdr pair))) + (set! alist (cons (cons key (func val default)) alist))))] + [(_ alist key val func) + (ainc! alist key val func 0)] + [(_ alist key val) + (ainc! alist key val +)] + [(_ alist key) + (ainc! alist key 1)])) + +(define ulist '()) + +(for-each (cut ainc! ulist <>) '(2 0 2 3 3 5 7 5 9 0)) + +(map car ulist) + ===> +(9 7 5 3 0 2) diff --git a/Task/Remove-duplicate-elements/VBScript/remove-duplicate-elements.vb b/Task/Remove-duplicate-elements/VBScript/remove-duplicate-elements.vbs similarity index 100% rename from Task/Remove-duplicate-elements/VBScript/remove-duplicate-elements.vb rename to Task/Remove-duplicate-elements/VBScript/remove-duplicate-elements.vbs diff --git a/Task/Remove-lines-from-a-file/ALGOL-68/remove-lines-from-a-file.alg b/Task/Remove-lines-from-a-file/ALGOL-68/remove-lines-from-a-file.alg index e9c6290f3d..17b1c5607a 100644 --- a/Task/Remove-lines-from-a-file/ALGOL-68/remove-lines-from-a-file.alg +++ b/Task/Remove-lines-from-a-file/ALGOL-68/remove-lines-from-a-file.alg @@ -1,13 +1,13 @@ -# removes the specified number of lines from a file, starting at start line (numbered from 1) # +# removes the specified number of lines from a file, starting at start line (numbered fromm 1) # # returns TRUE if successful, FALSE otherwise # PROC remove lines = ( STRING file name, INT start line, INT number of lines )BOOL: - IF number of lines < 0 OR start line < 1 + IF number of lines < 0 OR start line < 1 THEN # invalid parameters # print( ( "number of lines must be >= 0 and start line must be >= 1", newline ) ); FALSE - ELIF FILE temp file; - create( temp file, stand back channel ) /= 0 + ELIF FILE temp file; + create( temp file, stand back channel ) /= 0 THEN # unable to create a temporary output file # print( ( "Unable to create temporary file", newline ) ); @@ -18,8 +18,8 @@ PROC remove lines = ( STRING file name, INT start line, INT number of lines )BOO # we would have to get its name ( with "idf( temp file )", close it and re-open it # print( ( "Temp file is not rewindable", newline ) ); FALSE - ELIF FILE input file; - open( input file, file name, stand in channel ) /= 0 + ELIF FILE input file; + open( input file, file name, stand in channel ) /= 0 THEN # failed to open the file # print( ( "Unable to open """ + file name + """", newline ) ); @@ -27,16 +27,10 @@ PROC remove lines = ( STRING file name, INT start line, INT number of lines )BOO ELSE # files opened OK # BOOL at eof := FALSE; - # set the EOF handler for the original file # - on logical file end( input file - , ( REF FILE f )BOOL: - BEGIN - # note that we reached EOF on the latest read # - at eof := TRUE; - # return TRUE so processing can continue # - TRUE - END - ); + # set the EOF handler for the original file # + # notes that we reached EOF on the latest read # + # and returns TRUE so processing can continue # + on logical file end( input file, ( REF FILE f )BOOL: at eof := TRUE ); # copy the input file to the temp file # WHILE STRING line; get( input file, ( line, newline ) ); @@ -55,15 +49,7 @@ PROC remove lines = ( STRING file name, INT start line, INT number of lines )BOO # opened OK - copy the temporary file # reset( temp file ); # rewinds the input file # at eof := FALSE; - on logical file end( temp file - , ( REF FILE f )BOOL: - BEGIN - # note that we reached EOF on the latest read # - at eof := TRUE; - # return TRUE so processing can continue # - TRUE - END - ); + on logical file end( temp file, ( REF FILE f )BOOL: at eof := TRUE ); INT end line = ( start line - 1 ) + number of lines; INT line number := 0; WHILE STRING line; @@ -83,7 +69,8 @@ PROC remove lines = ( STRING file name, INT start line, INT number of lines )BOO IF line number < start line THEN # didn't find the start line # - print( ( "Specified start line (", whole( start line, 0 ), ") not in ", file name, newline ) ); + print( ( "Specified start line (", whole( start line, 0 ) ) ); + print( ( ") not in ", file name, newline ) ); FALSE ELIF line number < end line THEN @@ -98,24 +85,27 @@ PROC remove lines = ( STRING file name, INT start line, INT number of lines )BOO FI # remove lines # ; # test the line removal # -BEGIN - FILE t; - open( t, "test.txt", stand out channel ); - print( ( "Before...", newline ) ); - FOR i TO 10 DO - STRING line = whole( i, - ( ( i MOD 5 ) + 3 ) ); - put( t, ( line, newline ) ); - print( ( line, newline ) ) - OD; - close( t ); - remove lines( "test.txt", 2, 3 ); - print( ( "After...", newline ) ); - open( t, "test.txt", stand in channel ); - FOR i TO 7 DO - STRING line; - get( t, ( line, newline ) ); - print( ( line, newline ) ) - OD; - close( t ); - print( ( "----", newline ) ) -END +IF FILE t; + open( t, "test.txt", stand out channel ) /= 0 +THEN print( ( "Unable to open test.txt for output", newline ) ) +ELSE print( ( "Before...", newline ) ); + FOR i TO 10 DO + STRING line = whole( i, - ( ( i MOD 5 ) + 3 ) ); + put( t, ( line, newline ) ); + print( ( line, newline ) ) + OD; + close( t ); + IF NOT remove lines( "test.txt", 2, 3 ) + THEN print( ( "Unable to remove lines", newline ) ) + ELIF open( t, "test.txt", stand in channel ) /= 0 + THEN print( ( "Unable to open modified test.txt for input", newline ) ) + ELSE print( ( "After...", newline ) ); + TO 7 DO + STRING line; + get( t, ( line, newline ) ); + print( ( line, newline ) ) + OD; + close( t ); + print( ( "----", newline ) ) + FI +FI diff --git a/Task/Remove-lines-from-a-file/Ada/remove-lines-from-a-file.ada b/Task/Remove-lines-from-a-file/Ada/remove-lines-from-a-file.adb similarity index 100% rename from Task/Remove-lines-from-a-file/Ada/remove-lines-from-a-file.ada rename to Task/Remove-lines-from-a-file/Ada/remove-lines-from-a-file.adb diff --git a/Task/Remove-lines-from-a-file/Arturo/remove-lines-from-a-file.arturo b/Task/Remove-lines-from-a-file/Arturo/remove-lines-from-a-file.arturo index 195b8e2d50..da6be083bc 100644 --- a/Task/Remove-lines-from-a-file/Arturo/remove-lines-from-a-file.arturo +++ b/Task/Remove-lines-from-a-file/Arturo/remove-lines-from-a-file.arturo @@ -8,7 +8,7 @@ removeFileLines: function [filename, start, cnt][ ] final: previous\[0..start-1] ++ previous\[start+cnt..dec size previous] - write filename join.with:"\n" final + (join.with:"\n" final) >> filename ] removeFileLines "myfile.txt" 3 10 diff --git a/Task/Remove-lines-from-a-file/Delphi/remove-lines-from-a-file-1.delphi b/Task/Remove-lines-from-a-file/Delphi/remove-lines-from-a-file-1.pas similarity index 100% rename from Task/Remove-lines-from-a-file/Delphi/remove-lines-from-a-file-1.delphi rename to Task/Remove-lines-from-a-file/Delphi/remove-lines-from-a-file-1.pas diff --git a/Task/Remove-lines-from-a-file/Delphi/remove-lines-from-a-file-2.delphi b/Task/Remove-lines-from-a-file/Delphi/remove-lines-from-a-file-2.pas similarity index 100% rename from Task/Remove-lines-from-a-file/Delphi/remove-lines-from-a-file-2.delphi rename to Task/Remove-lines-from-a-file/Delphi/remove-lines-from-a-file-2.pas diff --git a/Task/Remove-lines-from-a-file/Elixir/remove-lines-from-a-file.elixir b/Task/Remove-lines-from-a-file/Elixir/remove-lines-from-a-file.ex similarity index 100% rename from Task/Remove-lines-from-a-file/Elixir/remove-lines-from-a-file.elixir rename to Task/Remove-lines-from-a-file/Elixir/remove-lines-from-a-file.ex diff --git a/Task/Remove-lines-from-a-file/Julia/remove-lines-from-a-file.julia b/Task/Remove-lines-from-a-file/Julia/remove-lines-from-a-file.jl similarity index 100% rename from Task/Remove-lines-from-a-file/Julia/remove-lines-from-a-file.julia rename to Task/Remove-lines-from-a-file/Julia/remove-lines-from-a-file.jl diff --git a/Task/Remove-lines-from-a-file/Kotlin/remove-lines-from-a-file.kotlin b/Task/Remove-lines-from-a-file/Kotlin/remove-lines-from-a-file.kts similarity index 100% rename from Task/Remove-lines-from-a-file/Kotlin/remove-lines-from-a-file.kotlin rename to Task/Remove-lines-from-a-file/Kotlin/remove-lines-from-a-file.kts diff --git a/Task/Remove-lines-from-a-file/Lua/remove-lines-from-a-file.lua b/Task/Remove-lines-from-a-file/Lua/remove-lines-from-a-file.lua index 4cf7170e62..50778dcc4e 100644 --- a/Task/Remove-lines-from-a-file/Lua/remove-lines-from-a-file.lua +++ b/Task/Remove-lines-from-a-file/Lua/remove-lines-from-a-file.lua @@ -1,26 +1,18 @@ function remove( filename, starting_line, num_lines ) - local fp = io.open( filename, "r" ) - if fp == nil then return nil end - - content = {} - i = 1; - for line in fp:lines() do - if i < starting_line or i >= starting_line + num_lines then - content[#content+1] = line + local content = {} + local i = 1 + for line in io.lines(filename, "L") do -- errors + if i < starting_line or i >= starting_line + num_lines then + content[#content+1] = line end i = i + 1 - end + end - if i > starting_line and i < starting_line + num_lines then - print( "Warning: Tried to remove lines after EOF." ) - end + if i > starting_line and i < starting_line + num_lines then + print( "Warning: Tried to remove lines after EOF." ) + end - fp:close() - fp = io.open( filename, "w+" ) - - for i = 1, #content do - fp:write( string.format( "%s\n", content[i] ) ) - end - - fp:close() + local fp = io.open( filename, "w+" ) or error"Not writable" + fp:write( table.concat( content ) ) + fp:close() end diff --git a/Task/Remove-lines-from-a-file/OCaml/remove-lines-from-a-file.ocaml b/Task/Remove-lines-from-a-file/OCaml/remove-lines-from-a-file.ml similarity index 100% rename from Task/Remove-lines-from-a-file/OCaml/remove-lines-from-a-file.ocaml rename to Task/Remove-lines-from-a-file/OCaml/remove-lines-from-a-file.ml diff --git a/Task/Remove-lines-from-a-file/PascalABC.NET/remove-lines-from-a-file.pas b/Task/Remove-lines-from-a-file/PascalABC.NET/remove-lines-from-a-file.pas new file mode 100644 index 0000000000..debe9b6767 --- /dev/null +++ b/Task/Remove-lines-from-a-file/PascalABC.NET/remove-lines-from-a-file.pas @@ -0,0 +1,9 @@ +procedure RemoveLines(fname: string; start: integer; count: integer := 1); +begin + WriteAllLines(fname, + ReadAllLines(fname).Where((s,ind) -> ind not in start - 1 .. start + count - 2).ToArray) +end; + +begin + RemoveLines('a2.pas',3,2); +end. diff --git a/Task/Remove-lines-from-a-file/PowerShell/remove-lines-from-a-file.psh b/Task/Remove-lines-from-a-file/PowerShell/remove-lines-from-a-file.ps1 similarity index 100% rename from Task/Remove-lines-from-a-file/PowerShell/remove-lines-from-a-file.psh rename to Task/Remove-lines-from-a-file/PowerShell/remove-lines-from-a-file.ps1 diff --git a/Task/Remove-lines-from-a-file/Rust/remove-lines-from-a-file.rust b/Task/Remove-lines-from-a-file/Rust/remove-lines-from-a-file.rs similarity index 100% rename from Task/Remove-lines-from-a-file/Rust/remove-lines-from-a-file.rust rename to Task/Remove-lines-from-a-file/Rust/remove-lines-from-a-file.rs diff --git a/Task/Remove-lines-from-a-file/VBScript/remove-lines-from-a-file.vb b/Task/Remove-lines-from-a-file/VBScript/remove-lines-from-a-file.vbs similarity index 100% rename from Task/Remove-lines-from-a-file/VBScript/remove-lines-from-a-file.vb rename to Task/Remove-lines-from-a-file/VBScript/remove-lines-from-a-file.vbs diff --git a/Task/Rename-a-file/Ada/rename-a-file.ada b/Task/Rename-a-file/Ada/rename-a-file.adb similarity index 100% rename from Task/Rename-a-file/Ada/rename-a-file.ada rename to Task/Rename-a-file/Ada/rename-a-file.adb diff --git a/Task/Rename-a-file/Batch-File/rename-a-file.bat b/Task/Rename-a-file/Batch-File/rename-a-file.bat index 2d869fd7ea..de95c7fc64 100644 --- a/Task/Rename-a-file/Batch-File/rename-a-file.bat +++ b/Task/Rename-a-file/Batch-File/rename-a-file.bat @@ -1,4 +1,4 @@ ren input.txt output.txt ren \input.txt output.txt -ren docs mydocs -ren \docs mydocs +ren docs\ mydocs +ren \docs\ mydocs diff --git a/Task/Rename-a-file/Delphi/rename-a-file.delphi b/Task/Rename-a-file/Delphi/rename-a-file.pas similarity index 100% rename from Task/Rename-a-file/Delphi/rename-a-file.delphi rename to Task/Rename-a-file/Delphi/rename-a-file.pas diff --git a/Task/Rename-a-file/Elixir/rename-a-file.elixir b/Task/Rename-a-file/Elixir/rename-a-file.ex similarity index 100% rename from Task/Rename-a-file/Elixir/rename-a-file.elixir rename to Task/Rename-a-file/Elixir/rename-a-file.ex diff --git a/Task/Rename-a-file/Emacs-Lisp/rename-a-file.l b/Task/Rename-a-file/Emacs-Lisp/rename-a-file.el similarity index 100% rename from Task/Rename-a-file/Emacs-Lisp/rename-a-file.l rename to Task/Rename-a-file/Emacs-Lisp/rename-a-file.el diff --git a/Task/Rename-a-file/Java/rename-a-file.java b/Task/Rename-a-file/Java/rename-a-file-1.java similarity index 100% rename from Task/Rename-a-file/Java/rename-a-file.java rename to Task/Rename-a-file/Java/rename-a-file-1.java diff --git a/Task/Rename-a-file/Java/rename-a-file-2.java b/Task/Rename-a-file/Java/rename-a-file-2.java new file mode 100644 index 0000000000..b27029a22a --- /dev/null +++ b/Task/Rename-a-file/Java/rename-a-file-2.java @@ -0,0 +1,22 @@ +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; + +public final class RenameAFile { + + public static void main(String[] args) throws IOException { + List source = List.of( Path.of("input.txt"), Path.of("docs"), + Path.of("C://input.txt") , Path.of("C://docs") ); + List target = List.of( Path.of("output.txt"), Path.of("mydocs"), + Path.of("C://output.txt"), Path.of("C://mydocs") ); + + for ( int i = 0; i < source.size(); i++ ) { + Files.move(source.get(i), target.get(i)); + System.out.println( Files.exists(target.get(i)) ? + "File '" + source.get(i) + "' successfully renamed to '" + target.get(i) + "'": + "Unable to rename file: " + source.get(i)); + } + } + +} diff --git a/Task/Rename-a-file/Julia/rename-a-file.julia b/Task/Rename-a-file/Julia/rename-a-file.jl similarity index 100% rename from Task/Rename-a-file/Julia/rename-a-file.julia rename to Task/Rename-a-file/Julia/rename-a-file.jl diff --git a/Task/Rename-a-file/Kotlin/rename-a-file.kotlin b/Task/Rename-a-file/Kotlin/rename-a-file.kts similarity index 100% rename from Task/Rename-a-file/Kotlin/rename-a-file.kotlin rename to Task/Rename-a-file/Kotlin/rename-a-file.kts diff --git a/Task/Rename-a-file/Locomotive-Basic/rename-a-file-1.basic b/Task/Rename-a-file/Locomotive-Basic/rename-a-file-1.basic new file mode 100644 index 0000000000..03a5a87456 --- /dev/null +++ b/Task/Rename-a-file/Locomotive-Basic/rename-a-file-1.basic @@ -0,0 +1 @@ +|REN,"output.txt","input.txt" diff --git a/Task/Rename-a-file/Locomotive-Basic/rename-a-file-2.basic b/Task/Rename-a-file/Locomotive-Basic/rename-a-file-2.basic new file mode 100644 index 0000000000..98f58edaef --- /dev/null +++ b/Task/Rename-a-file/Locomotive-Basic/rename-a-file-2.basic @@ -0,0 +1 @@ +|REN,"1:output.txt","0:input.txt" diff --git a/Task/Rename-a-file/Locomotive-Basic/rename-a-file.basic b/Task/Rename-a-file/Locomotive-Basic/rename-a-file.basic deleted file mode 100644 index 89da698855..0000000000 --- a/Task/Rename-a-file/Locomotive-Basic/rename-a-file.basic +++ /dev/null @@ -1 +0,0 @@ -|ren,"input.txt","output.txt" diff --git a/Task/Rename-a-file/Maxima/rename-a-file.maxima b/Task/Rename-a-file/Maxima/rename-a-file.maxima new file mode 100644 index 0000000000..001ce224f8 --- /dev/null +++ b/Task/Rename-a-file/Maxima/rename-a-file.maxima @@ -0,0 +1,5 @@ +load("operatingsystem")$ +rename_file("input.txt", "output.txt")$ +rename_file("/input.txt", "/output.txt")$ +rename_file("docs", "mydocs")$ +rename_file("/docs", "/mydocs")$ diff --git a/Task/Rename-a-file/OCaml/rename-a-file.ocaml b/Task/Rename-a-file/OCaml/rename-a-file.ml similarity index 100% rename from Task/Rename-a-file/OCaml/rename-a-file.ocaml rename to Task/Rename-a-file/OCaml/rename-a-file.ml diff --git a/Task/Rename-a-file/PascalABC.NET/rename-a-file.pas b/Task/Rename-a-file/PascalABC.NET/rename-a-file.pas new file mode 100644 index 0000000000..227ef6594b --- /dev/null +++ b/Task/Rename-a-file/PascalABC.NET/rename-a-file.pas @@ -0,0 +1,9 @@ +uses System.IO; + +begin + &File.Move('input.txt','output.txt'); + &File.Move('\input.txt','\output.txt'); + + Directory.Move('docs','mydocs'); + Directory.Move('\docs','\mydocs'); +end. diff --git a/Task/Rename-a-file/Pluto/rename-a-file.pluto b/Task/Rename-a-file/Pluto/rename-a-file.pluto new file mode 100644 index 0000000000..dfc95df6ba --- /dev/null +++ b/Task/Rename-a-file/Pluto/rename-a-file.pluto @@ -0,0 +1,5 @@ +os.rename("input.txt", "output.txt") +os.rename("/input.txt", "/output.txt") + +os.rename("docs", "mydocs") +os.rename("/docs", "/mydocs") diff --git a/Task/Rename-a-file/PowerShell/rename-a-file.psh b/Task/Rename-a-file/PowerShell/rename-a-file.ps1 similarity index 100% rename from Task/Rename-a-file/PowerShell/rename-a-file.psh rename to Task/Rename-a-file/PowerShell/rename-a-file.ps1 diff --git a/Task/Rename-a-file/R/rename-a-file.r b/Task/Rename-a-file/R/rename-a-file.r new file mode 100644 index 0000000000..077c4db78e --- /dev/null +++ b/Task/Rename-a-file/R/rename-a-file.r @@ -0,0 +1,4 @@ +file.rename("input.txt","output.txt") +file.rename("~/input.txt","~/output.txt") +file.rename("docs","mydocs") +file.rename("~/docs","~/mydocs") diff --git a/Task/Rename-a-file/REBOL/rename-a-file.rebol b/Task/Rename-a-file/Rebol/rename-a-file.rebol similarity index 100% rename from Task/Rename-a-file/REBOL/rename-a-file.rebol rename to Task/Rename-a-file/Rebol/rename-a-file.rebol diff --git a/Task/Rename-a-file/Rust/rename-a-file.rust b/Task/Rename-a-file/Rust/rename-a-file.rs similarity index 100% rename from Task/Rename-a-file/Rust/rename-a-file.rust rename to Task/Rename-a-file/Rust/rename-a-file.rs diff --git a/Task/Rename-a-file/Rye/rename-a-file.rye b/Task/Rename-a-file/Rye/rename-a-file.rye new file mode 100644 index 0000000000..4d6e6ff2e4 --- /dev/null +++ b/Task/Rename-a-file/Rye/rename-a-file.rye @@ -0,0 +1,3 @@ +cc os +mv %input.txt %output.txt +mv %docs %mydocs diff --git a/Task/Rename-a-file/S-BASIC/rename-a-file-1.basic b/Task/Rename-a-file/S-BASIC/rename-a-file-1.basic new file mode 100644 index 0000000000..01799d2242 --- /dev/null +++ b/Task/Rename-a-file/S-BASIC/rename-a-file-1.basic @@ -0,0 +1 @@ +rename "INPUT.TXT" to "OUTPUT.TXT" diff --git a/Task/Rename-a-file/S-BASIC/rename-a-file-2.basic b/Task/Rename-a-file/S-BASIC/rename-a-file-2.basic new file mode 100644 index 0000000000..788e3db23f --- /dev/null +++ b/Task/Rename-a-file/S-BASIC/rename-a-file-2.basic @@ -0,0 +1,24 @@ +rem - Set the CP/M user area (0 to 15) +procedure setuser (user = integer) + var hl, bc, a_psw = integer + hl = 0 + bc = 20H rem - BDOS set user function + a_psw = 0 + call (5H,hl,user,bc,a_psw) +end + +rem - Set the logged drive ('A' to 'P') +procedure setdrive (drive = char) + var hl, de, bc, a_psw = integer + rem -- make sure drive letter is upper case! + if drive >= 'a' then drive = drive - 32 + hl = 0 + de = drive - 65 + bc = 0EH rem - BDOS set drive function + a_psw = 0 + call (5H,hl,de,bc,a_psw) +end + +setuser 0 +setdrive 'A' +rename "INPUT.TXT" to "OUTPUT.TXT" diff --git a/Task/Rename-a-file/Scheme/rename-a-file.ss b/Task/Rename-a-file/Scheme/rename-a-file.scm similarity index 100% rename from Task/Rename-a-file/Scheme/rename-a-file.ss rename to Task/Rename-a-file/Scheme/rename-a-file.scm diff --git a/Task/Rendezvous/Ada/rendezvous-1.ada b/Task/Rendezvous/Ada/rendezvous-1.adb similarity index 100% rename from Task/Rendezvous/Ada/rendezvous-1.ada rename to Task/Rendezvous/Ada/rendezvous-1.adb diff --git a/Task/Rendezvous/Ada/rendezvous-2.ada b/Task/Rendezvous/Ada/rendezvous-2.adb similarity index 100% rename from Task/Rendezvous/Ada/rendezvous-2.ada rename to Task/Rendezvous/Ada/rendezvous-2.adb diff --git a/Task/Rendezvous/Ada/rendezvous-3.ada b/Task/Rendezvous/Ada/rendezvous-3.adb similarity index 100% rename from Task/Rendezvous/Ada/rendezvous-3.ada rename to Task/Rendezvous/Ada/rendezvous-3.adb diff --git a/Task/Rendezvous/C++/rendezvous.cpp b/Task/Rendezvous/C++/rendezvous.cpp new file mode 100644 index 0000000000..a396e49934 --- /dev/null +++ b/Task/Rendezvous/C++/rendezvous.cpp @@ -0,0 +1,97 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +std::mutex mutex; +std::condition_variable condition_variable; +bool goose_working = true; +bool humpty_working = true; +uint32_t turn = 0; + +class out_of_ink_exception : public std::exception { }; + +class Printer { +public: + Printer(const std::string& name, const uint32_t& client_ink_level) + : name(name), client_ink_level(client_ink_level) { } + + bool operator==(const Printer& other) const { + return name == other.name; + } + + std::string name; + uint32_t client_ink_level; +}; + +Printer reserve("Reserve", 5); +Printer primary("Primary", 5); +Printer printer = primary; + +void display(const std::string& text) { + if ( printer == primary && printer.client_ink_level == 0 ) { + printer = reserve; + } + + if ( printer.client_ink_level > 0 ) { + printer.client_ink_level--; + std::cout << "(" + printer.name + ") " + text << std::endl; + } else { + std::cout << " Printer out of ink" << std::endl; + throw out_of_ink_exception(); + } +} + +auto messenger = + [](const std::vector& message, const uint32_t& my_turn, const uint32_t& turn_count) { + std::unique_lock lock(mutex); + uint64_t index = 0; + while ( goose_working || humpty_working ) { + condition_variable.wait(lock, [&]() { return turn % turn_count == my_turn; }); + + if ( index < message.size() ) { + try { + display(message[index++]); + } catch (const out_of_ink_exception& ex) { + goose_working = false; + humpty_working = false; + } + } else { + if ( my_turn == 0 ) { + goose_working = false; + } else { + humpty_working = false; + } + } + + turn++; + condition_variable.notify_one(); + } + +}; + +int main() { + const std::vector goose_text = { "Old Mother Goose,", + "When she wanted to wander,", + "Would ride through the air,", + "On a very fine gander.", + "Jack's mother came in,", + "And caught the goose soon,", + "And mounting its back,", + "Flew up to the moon." }; + + const std::vector humpty_text = { "Humpty Dumpty sat on a wall.", + "Humpty Dumpty had a great fall.", + "All the king's horses and all the king's men,", + "Couldn't put Humpty together again." }; + + std::thread goose_thread(messenger, goose_text, 0, 2); + std::thread humpty_thread(messenger, humpty_text, 1, 2); + + goose_thread.join(); + humpty_thread.join(); +} diff --git a/Task/Rendezvous/FreeBASIC/rendezvous-1.basic b/Task/Rendezvous/FreeBASIC/rendezvous-1.basic new file mode 100644 index 0000000000..1f6e6a1168 --- /dev/null +++ b/Task/Rendezvous/FreeBASIC/rendezvous-1.basic @@ -0,0 +1,68 @@ +Type Printer + tipo As String + ink As Integer +End Type + +Sub Printer_New(Byref p As Printer, Byval tipo As String, Byval ink As Integer) + p.tipo = tipo + p.ink = ink +End Sub + +Function Printer_ink(Byref p As Printer) As Integer + Return p.ink +End Function + +Sub Printer_ink_Set(Byref p As Printer, Byval v As Integer) + p.ink = v +End Sub + +Sub Printer_print(Byref p As Printer, Byval text As String) + Print p.tipo & ": "; + For i As Integer = 1 To Len(text) + Print Mid(text, i, 1); + Next + Print + p.ink -= 1 +End Sub + +Dim Shared As Printer ptrMain, ptrReserve +Printer_New(ptrMain, "Main ", 5) +Printer_New(ptrReserve, "Reserve", 5) + +Dim Shared As String*44 hd(3) = {"Humpty Dumpty sat on a wall.", "Humpty Dumpty had a great fall.", "All the king's horses and all the king's men", "Couldn't put Humpty together again."} +Dim Shared As String*26 mg(7) = {"Old Mother Goose", "When she wanted to wander,", "Would ride through the air", "On a very fine gander.", "Jack's mother came in,", "And caught the goose soon,", "And mounting its back,", "Flew up to the moon."} + +Function task(Byval nombre As String) As String + Dim As Integer i + Dim As String lines() + If nombre = "Humpty Dumpty" Then + Redim lines(Ubound(hd)) + For i = 0 To Ubound(hd) : lines(i) = hd(i) + Next + Else + Redim lines(Ubound(mg)) + For i = 0 To Ubound(mg) : lines(i) = mg(i) + Next + End If + + For i = 0 To Ubound(lines) + If Printer_ink(ptrMain) > 0 Then + Printer_print(ptrMain, lines(i)) + Elseif Printer_ink(ptrReserve) > 0 Then + Printer_print(ptrReserve, lines(i)) + Else + Return "ERROR : Reserve printer ran out of ink in " & nombre & " task." + End If + Next + Return "" +End Function + +Dim As String rhymes(1) = {"Humpty Dumpty", "Mother Goose"} +Dim As String tasks(1) + +For i As Integer = 0 To 1 + tasks(i) = task(rhymes(i)) + If tasks(i) <> "" Then Print tasks(i): Exit For +Next + +Sleep diff --git a/Task/Rendezvous/FreeBASIC/rendezvous-2.basic b/Task/Rendezvous/FreeBASIC/rendezvous-2.basic new file mode 100644 index 0000000000..6ed51d84b9 --- /dev/null +++ b/Task/Rendezvous/FreeBASIC/rendezvous-2.basic @@ -0,0 +1,72 @@ +Const MAX_INK As Integer = 5 + +Type Printer + ID As Integer + Ink As Integer + Backup As Printer Ptr + Mutex As Any Ptr +End Type + +Dim Shared Reserve As Printer +Dim Shared Main As Printer + +Reserve.ID = 2 +Reserve.Ink = MAX_INK +Reserve.Backup = 0 +Reserve.Mutex = Mutexcreate() + +Main.ID = 1 +Main.Ink = MAX_INK +Main.Backup = @Reserve +Main.Mutex = Mutexcreate() + +Dim Shared As String*44 humpty(3) = { _ +"Humpty Dumpty sat on a wall.", "Humpty Dumpty had a great fall.", _ +"All the king's horses and all the king's men", _ +"Couldn't put Humpty together again." } + +Dim Shared As String*26 goose(7) = {"Old Mother Goose", "When she wanted to wander,", _ +"Would ride through the air", "On a very fine gander.", "Jack's mother came in,", _ +"And caught the goose soon,", "And mounting its back,", "Flew up to the moon." } + +Sub PrintLine(Byref p As Printer, Byval linea As String) + Mutexlock(p.Mutex) + If p.Ink = 0 Then + If p.Backup = 0 Then + Mutexunlock(p.Mutex) + If p.ID = 1 Then + Print " Humpty Dumpty out of ink!" + Elseif p.ID = 2 Then + Print " Mother Goose out of ink!" + End If + Mutexunlock(p.Mutex) + Else + PrintLine(*p.Backup, linea) + End If + Else + Print p.ID; ": "; linea + p.Ink -= 1 + End If + Mutexunlock(p.Mutex) +End Sub + +Sub HumptyDumpty(Param As Any Ptr) + For i As Integer = 0 To Ubound(humpty) + PrintLine(Main, humpty(i)) + Next +End Sub + +Sub MotherGoose(Param As Any Ptr) + For i As Integer = 0 To Ubound(goose) + PrintLine(Main, goose(i)) + Next +End Sub + +' Create threads +Dim HumptyThread As Any Ptr = Threadcreate(@HumptyDumpty, 0) +Dim GooseThread As Any Ptr = Threadcreate(@MotherGoose, 0) + +' Wait for threads to finish +Threadwait(HumptyThread) + +Sleep diff --git a/Task/Rendezvous/Java/rendezvous.java b/Task/Rendezvous/Java/rendezvous.java new file mode 100644 index 0000000000..2edc52e7f8 --- /dev/null +++ b/Task/Rendezvous/Java/rendezvous.java @@ -0,0 +1,96 @@ +import java.io.PrintStream; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.function.Supplier; + +public final class Rendezvous { + + public static void main(String[] args) throws InterruptedException, ExecutionException { + List motherGooseText = List.of( "Old Mother Goose,", + "When she wanted to wander,", + "Would ride through the air,", + "On a very fine gander.", + "Jack's mother came in,", + "And caught the goose soon,", + "And mounting its back,", + "Flew up to the moon." ); + + List humptyDumptyText = List.of( "Humpty Dumpty sat on a wall.", + "Humpty Dumpty had a great fall.", + "All the king's horses and all the king's men,", + "Couldn't put Humpty together again." ); + + Printer reserve = new Printer("Reserve", Optional.empty(), System.out); + Printer main = new Printer("Main", Optional.of(reserve), System.out); + + Messenger motherGoose = new Messenger(motherGooseText, main); + Messenger humptyDumpty = new Messenger(humptyDumptyText, main); + + while ( CompletableFuture.supplyAsync(motherGoose).get() | + CompletableFuture.supplyAsync(humptyDumpty).get() ) { } + } + +} + +final class Messenger implements Supplier { + + public Messenger(List aMessage, Printer aPrinter) { + message = new ArrayList(aMessage); + iterator = message.iterator(); + printer = aPrinter; + } + + @Override + public Boolean get() { + if ( iterator.hasNext() ) { + try { + printer.display(iterator.next()); + } catch (OutOfInkException exception) { + return false; + } + return true; + } + return false; + } + + private List message; + private Iterator iterator; + private Printer printer; + +} + +final class Printer { + + public Printer(String aName, Optional aReserve, PrintStream aPrintStream) { + name = aName; + reserve = aReserve; + printStream = aPrintStream; + } + + public void display(String message) throws OutOfInkException { + if ( inkLevelForClientUse > 0 ) { + printStream.println("(" + name + ") " + message); + inkLevelForClientUse -= 1; + } else { + if ( reserve.isPresent() ) { + reserve.get().display(message); + } else { + printStream.println(" Printer out of ink"); + throw new OutOfInkException(); + } + } + + } + + private String name; + private Optional reserve; + private PrintStream printStream; + private int inkLevelForClientUse = 5; + +} + +final class OutOfInkException extends Exception { } diff --git a/Task/Rendezvous/Julia/rendezvous.julia b/Task/Rendezvous/Julia/rendezvous.jl similarity index 100% rename from Task/Rendezvous/Julia/rendezvous.julia rename to Task/Rendezvous/Julia/rendezvous.jl diff --git a/Task/Rendezvous/Rust/rendezvous.rs b/Task/Rendezvous/Rust/rendezvous.rs new file mode 100644 index 0000000000..1d6a34d05c --- /dev/null +++ b/Task/Rendezvous/Rust/rendezvous.rs @@ -0,0 +1,207 @@ +use std::error::Error; +use std::fmt; +use std::sync::{Arc, Mutex, Condvar}; +use std::thread; +use std::time::Duration; // Only for potential debug sleeps, not strictly needed for logic + +// --- Custom Error Type --- +#[derive(Debug)] +struct OutOfInkError; + +impl fmt::Display for OutOfInkError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "Printer out of ink") + } +} + +impl Error for OutOfInkError {} + +// --- Printer Struct --- +#[derive(Debug, Clone, PartialEq)] // Add traits for comparison, debugging, and cloning +struct Printer { + name: String, + client_ink_level: u32, +} + +impl Printer { + fn new(name: &str, ink_level: u32) -> Self { + Printer { + name: name.to_string(), + client_ink_level: ink_level, + } + } +} + +// --- Shared State Struct --- +// Group all shared mutable data together +struct SharedState { + printer: Printer, + primary_printer_config: Printer, // Keep original config separate + reserve_printer_config: Printer, // Keep original config separate + goose_working: bool, + humpty_working: bool, + turn: u32, +} + +// --- Display Function --- +// Takes a mutable reference to the shared state +// Returns Result to indicate success or OutOfInkError +fn display(state: &mut SharedState, text: &str) -> Result<(), OutOfInkError> { + // Check if primary is out and switch to reserve if needed + if state.printer == state.primary_printer_config && state.printer.client_ink_level == 0 { + println!(" Switching to Reserve printer"); + state.printer = state.reserve_printer_config.clone(); // Use cloned config + } + + // Attempt to print + if state.printer.client_ink_level > 0 { + state.printer.client_ink_level -= 1; + println!("({}) {}", state.printer.name, text); + Ok(()) + } else { + println!(" Printer out of ink"); + Err(OutOfInkError) + } +} + +// --- Messenger Logic --- +// Takes Arc clones for shared data +fn messenger( + message: Vec, + my_turn: u32, + turn_count: u32, + state_sync: Arc<(Mutex, Condvar)>, // Tuple of Mutex and Condvar + worker_name: String, // For identifying which worker finished +) { + let (lock, cvar) = &*state_sync; // Destructure the tuple + let mut index: usize = 0; + + // Loop as long as *any* worker is potentially active + // We re-check specific worker status inside the lock + loop { + // Acquire the lock. The MutexGuard 'state' is automatically released when it goes out of scope + let mut state = lock.lock().expect("Mutex lock failed"); + + // Wait while it's not our turn AND at least one worker is still supposed to be working + // The wait_while unlocks the mutex and re-acquires it upon waking up + state = cvar.wait_while(state, |s| { + // Predicate: Keep waiting if... + s.turn % turn_count != my_turn // it's not our turn + && (s.goose_working || s.humpty_working) // AND someone is still working (prevents deadlock if other thread finishes) + }).expect("Condition variable wait failed"); + + + // Check if *all* work is done *after* waking up or if we didn't need to wait + if !state.goose_working && !state.humpty_working { + // println!("{} sees both workers finished, exiting.", worker_name); // Debug + break; // Exit the loop + } + + // Check if *this specific worker* should still be working + let should_be_working = if my_turn == 0 { state.goose_working } else { state.humpty_working }; + + if !should_be_working { + // This worker finished its text or an error occurred previously. + // It needs to potentially wake up the *other* worker if it's waiting. + // println!("{} sees it shouldn't be working, notifying and breaking.", worker_name); // Debug + // We still increment the turn and notify to potentially unblock the other thread + // if it's waiting for its turn number, even if it will also exit soon. + state.turn += 1; + cvar.notify_one(); + break; // Exit the loop + } + + + // --- Perform Work --- + if index < message.len() { + match display(&mut state, &message[index]) { + Ok(()) => { + index += 1; + } + Err(_) => { + // Out of ink! Stop both workers. + println!(" Error detected by {}, stopping all work.", worker_name); + state.goose_working = false; + state.humpty_working = false; + // No break here yet, let the loop condition handle exit naturally after notification + } + } + } else { + // This worker finished its message + // println!("{} finished text.", worker_name); // Debug + if my_turn == 0 { + state.goose_working = false; + } else { + state.humpty_working = false; + } + } + + // Increment turn and notify the *next* worker + state.turn += 1; + //println!("{} finished turn, new turn {}. Notifying.", worker_name, state.turn); // Debug + cvar.notify_one(); + + // MutexGuard 'state' is dropped here, releasing the lock + } + //println!("{} thread finished.", worker_name); // Debug +} + + +fn main() { + let goose_text: Vec = [ + "Old Mother Goose,", + "When she wanted to wander,", + "Would ride through the air,", + "On a very fine gander.", + "Jack's mother came in,", + "And caught the goose soon,", + "And mounting its back,", + "Flew up to the moon.", + ] + .iter() + .map(|s| s.to_string()) + .collect(); + + let humpty_text: Vec = [ + "Humpty Dumpty sat on a wall.", + "Humpty Dumpty had a great fall.", + "All the king's horses and all the king's men,", + "Couldn't put Humpty together again.", + ] + .iter() + .map(|s| s.to_string()) + .collect(); + + // --- Initial State Setup --- + let primary = Printer::new("Primary", 5); + let reserve = Printer::new("Reserve", 5); + + let initial_state = SharedState { + printer: primary.clone(), // Start with primary + primary_printer_config: primary, // Store config + reserve_printer_config: reserve, // Store config + goose_working: true, + humpty_working: true, + turn: 0, + }; + + // Wrap state and condvar in Arc for shared ownership + let state_sync = Arc::new((Mutex::new(initial_state), Condvar::new())); + + // --- Spawn Threads --- + let state_sync_goose = Arc::clone(&state_sync); + let goose_thread = thread::spawn(move || { + messenger(goose_text, 0, 2, state_sync_goose, "Goose".to_string()); + }); + + let state_sync_humpty = Arc::clone(&state_sync); + let humpty_thread = thread::spawn(move || { + messenger(humpty_text, 1, 2, state_sync_humpty, "Humpty".to_string()); + }); + + // --- Wait for Threads to Finish --- + goose_thread.join().expect("Goose thread panicked"); + humpty_thread.join().expect("Humpty thread panicked"); + + println!("Both threads finished."); +} diff --git a/Task/Rep-string/ALGOL-68/rep-string.alg b/Task/Rep-string/ALGOL-68/rep-string.alg index 89215df160..c3737b746e 100644 --- a/Task/Rep-string/ALGOL-68/rep-string.alg +++ b/Task/Rep-string/ALGOL-68/rep-string.alg @@ -36,8 +36,7 @@ END; # longest rep string # # test the longest rep string procedure # -main: -( +BEGIN []STRING tests = ( "1001110011" , "1110111011" @@ -65,4 +64,4 @@ main: ) ) OD -) +END diff --git a/Task/Rep-string/Ada/rep-string.ada b/Task/Rep-string/Ada/rep-string.adb similarity index 100% rename from Task/Rep-string/Ada/rep-string.ada rename to Task/Rep-string/Ada/rep-string.adb diff --git a/Task/Rep-string/Applesoft-BASIC/rep-string.basic b/Task/Rep-string/Applesoft-BASIC/rep-string.basic new file mode 100644 index 0000000000..21cda88713 --- /dev/null +++ b/Task/Rep-string/Applesoft-BASIC/rep-string.basic @@ -0,0 +1,15 @@ + 10 FOR Q = 0 TO 0: READ S$:L = LEN (S$): ON L > 0 GOSUB 20: NEXT Q: END + 20 LET R$ = "" + 30 ON L > 1 GOSUB 70 + 40 PRINT S$":"R$ MID$ (" NONE",1,5 * ( LEN (R$) = 0)) + 50 LET Q = - 1 + 60 RETURN + 70 FOR I = INT (L / 2) TO 1 STEP - 1 + 80 T$ = "": FOR T = 0 TO 0:T$ = T$ + LEFT$ (S$,I):T = - ( LEN (T$) < L): NEXT T: IF LEFT$ (T$,L) = S$ THEN R$ = R$ + " " + LEFT$ (S$,I) + 90 NEXT I: RETURN + 100 DATA "1001110011","1110111011" + 110 DATA "0010010010","1010101010" + 120 DATA "1111111111","0100101101" + 130 DATA "0100100","101" + 140 DATA "11","00" + 150 DATA "1","" diff --git a/Task/Rep-string/Arturo/rep-string.arturo b/Task/Rep-string/Arturo/rep-string.arturo index 5cc3dc87d2..093b457db3 100644 --- a/Task/Rep-string/Arturo/rep-string.arturo +++ b/Task/Rep-string/Arturo/rep-string.arturo @@ -24,8 +24,7 @@ strings: { loop split.lines strings 'str [ rep: repeated? str - if? false = rep -> - print [str "-> *not* a rep-string"] - else -> - print [str "->" rep "( length:" size rep ")"] + switch false = rep + -> print [str "-> *not* a rep-string"] + -> print [str "->" rep "( length:" size rep ")"] ] diff --git a/Task/Rep-string/Crystal/rep-string.crystal b/Task/Rep-string/Crystal/rep-string.cr similarity index 100% rename from Task/Rep-string/Crystal/rep-string.crystal rename to Task/Rep-string/Crystal/rep-string.cr diff --git a/Task/Rep-string/Delphi/rep-string.delphi b/Task/Rep-string/Delphi/rep-string.pas similarity index 100% rename from Task/Rep-string/Delphi/rep-string.delphi rename to Task/Rep-string/Delphi/rep-string.pas diff --git a/Task/Rep-string/DuckDB/rep-string.duckdb b/Task/Rep-string/DuckDB/rep-string.duckdb new file mode 100644 index 0000000000..fde7e300cf --- /dev/null +++ b/Task/Rep-string/DuckDB/rep-string.duckdb @@ -0,0 +1,36 @@ +create or replace function repString(s) as ( + if (length(s) < 2, null, + (with recursive size_t as (select length(s) as size), + cte as + (select ((size % 2) + (size // 2)) as len, '' as t, false as found + from size_t + union all + select len-1 as len, + s[1:len] as t, + s == (repeat(s[1:len], (size // len)) + || coalesce(t[1:(size % len)], '')) + as found + from cte, size_t + where len > 0 and found = false + ) + select first(t) + from cte + where found + )) +); + +select s, repString(s) +from unnest( + [ + '1001110011', + '1110111011', + '0010010010', + '1010101010', + '1111111111', + '0100101101', + '0100100', + '101', + '11', + '00', + '1' + ]) _(s); diff --git a/Task/Rep-string/EasyLang/rep-string.easy b/Task/Rep-string/EasyLang/rep-string.easy index b3558d67a5..15f4c0e66b 100644 --- a/Task/Rep-string/EasyLang/rep-string.easy +++ b/Task/Rep-string/EasyLang/rep-string.easy @@ -1,7 +1,7 @@ func$ repstr s$ . sl = len s$ div 2 + 1 while sl > 1 - r$ = substr s$ sl 999 + r$ = substr s$ sl 99999 if r$ = substr s$ 1 len r$ return substr r$ 1 (sl - 1) . diff --git a/Task/Rep-string/Ed/rep-string.ed b/Task/Rep-string/Ed/rep-string.ed new file mode 100644 index 0000000000..3945a3749d --- /dev/null +++ b/Task/Rep-string/Ed/rep-string.ed @@ -0,0 +1,4 @@ +H +g/([01]*)\1(.*)/s//\1/ +,p +Q diff --git a/Task/Rep-string/Elixir/rep-string.elixir b/Task/Rep-string/Elixir/rep-string.ex similarity index 100% rename from Task/Rep-string/Elixir/rep-string.elixir rename to Task/Rep-string/Elixir/rep-string.ex diff --git a/Task/Rep-string/FutureBasic/rep-string.basic b/Task/Rep-string/FutureBasic/rep-string.basic new file mode 100644 index 0000000000..fa67923ef0 --- /dev/null +++ b/Task/Rep-string/FutureBasic/rep-string.basic @@ -0,0 +1,40 @@ +include "NSLog.incl" + +local fn RepeatingStrings + NSUInteger i + CFArrayRef testCases = @[@"1001110011", @"1110111011", @"0010010010", @"1010101010", + @"1111111111", @"0100101101", @"0100100", @"101", @"11", @"00", @"1"] + + for CFStringRef string in testCases + NSUInteger length = len(string) + CFMutableArrayRef repeats = fn MutableArrayNew + + for NSUInteger prefixLen = 1 to length / 2 + BOOL repeatsPrefix = YES + + for i = prefixLen to length - 1 + if ( fn StringCharacterAtIndex( string, i ) != fn StringCharacterAtIndex( string, (i % prefixLen) ) ) + repeatsPrefix = NO + break + end if + next + + if ( repeatsPrefix ) + MutableArrayAddObject( repeats, fn StringSubstringToIndex( string, prefixLen ) ) + end if + next + + CFStringRef outputStr + if ( fn ArrayCount(repeats) > 0 ) + outputStr = fn ArrayComponentsJoinedByString( repeats, @", " ) + outputStr = fn StringByTrimmingCharactersInSet( outputStr, fn CharacterSetWhitespaceSet ) + else + outputStr = @"(no repeat)" + end if + NSLog( @"%10s : %@", fn StringUTF8String(string), outputStr ) + next +end fn + +fn RepeatingStrings + +HandleEvents diff --git a/Task/Rep-string/Julia/rep-string.jl b/Task/Rep-string/Julia/rep-string.jl new file mode 100644 index 0000000000..a409ce206b --- /dev/null +++ b/Task/Rep-string/Julia/rep-string.jl @@ -0,0 +1,18 @@ +function repstring(str::AbstractString) + r = collect(str) + n = length(r) + return [String(r[1:m]) for m in 1:n÷2 if collect(String(r[1:m]) ^ cld(n, m))[1:n] == r] +end + +tests = ["1001110011", "1110111011", "0010010010", "1010101010", "1111111111", + "0100101101", "0100100", "101", "11", "00", "1", + "\u2200\u2203\u2200\u2203\u2200\u2203\u2200\u2203"] + +for r in tests + replst = repstring(r) + if isempty(replst) + println("$r is not a rep-string.") + else + println("$r is a rep-string of ", join(replst, ", "), ".") + end +end diff --git a/Task/Rep-string/Julia/rep-string.julia b/Task/Rep-string/Julia/rep-string.julia deleted file mode 100644 index 8bde4ed33d..0000000000 --- a/Task/Rep-string/Julia/rep-string.julia +++ /dev/null @@ -1,23 +0,0 @@ -function repstring(r::AbstractString) - n = length(r) - replst = String[] - for m in 1:n÷2 - s = r[1:chr2ind(r, m)] - if (s ^ cld(n, m))[1:chr2ind(r, n)] != r continue end - push!(replst, s) - end - return replst -end - -tests = ["1001110011", "1110111011", "0010010010", "1010101010", "1111111111", - "0100101101", "0100100", "101", "11", "00", "1", - "\u2200\u2203\u2200\u2203\u2200\u2203\u2200\u2203"] - -for r in tests - replst = repstring(r) - if isempty(replst) - println("$r is not a rep-string.") - else - println("$r is a rep-string of ", join(replst, ", "), ".") - end -end diff --git a/Task/Rep-string/Kotlin/rep-string.kotlin b/Task/Rep-string/Kotlin/rep-string.kts similarity index 100% rename from Task/Rep-string/Kotlin/rep-string.kotlin rename to Task/Rep-string/Kotlin/rep-string.kts diff --git a/Task/Rep-string/R/rep-string.r b/Task/Rep-string/R/rep-string.r new file mode 100644 index 0000000000..e8d7d0b148 --- /dev/null +++ b/Task/Rep-string/R/rep-string.r @@ -0,0 +1,28 @@ +is_repeated <- function(s) { + for (i in 1+(nchar(s) %/% 2):0) { + if (startsWith(s, substring(s, i))) { + return(i-1) + } + } +} + +test_strings <- c("1001110011", + "1110111011", + "0010010010", + "1010101010", + "1111111111", + "0100101101", + "0100100", + "101", + "11", + "00", + "1") + +result <- sapply(test_strings, is_repeated) +repeaters <- substring(test_strings, 1, result) +repeaters <- ifelse(repeaters != "", repeaters, "[none]") +writeLines(paste(test_strings, + "has a repetition length of", + result, + "with repeating unit", + repeaters)) diff --git a/Task/Rep-string/Rust/rep-string.rust b/Task/Rep-string/Rust/rep-string.rs similarity index 100% rename from Task/Rep-string/Rust/rep-string.rust rename to Task/Rep-string/Rust/rep-string.rs diff --git a/Task/Rep-string/VBScript/rep-string.vb b/Task/Rep-string/VBScript/rep-string.vbs similarity index 100% rename from Task/Rep-string/VBScript/rep-string.vb rename to Task/Rep-string/VBScript/rep-string.vbs diff --git a/Task/Rep-string/XPL0/rep-string.xpl0 b/Task/Rep-string/XPL0/rep-string.xpl0 new file mode 100644 index 0000000000..6b7450c2f6 --- /dev/null +++ b/Task/Rep-string/XPL0/rep-string.xpl0 @@ -0,0 +1,29 @@ +include xpllib; \for StrLen, StrFind and Print + +func RepStr(Str); +char Str; +int SL; +[if Str(0) = 0 then return 0; +SL:= StrLen(Str)/2; +while SL > 0 do + [if StrFind(Str, Str+SL) = Str then + return SL; + SL:= SL-1; + ]; +return 0; +]; + +int Strs, I, N; +char PS; +[Strs:= ["1001110011", "1110111011", "0010010010", "1111111111", + "0100101101", "0100100", "101", "11", "00", "1"]; +for I:= 0 to 10-1 do + [N:= RepStr(Strs(I)); + PS:= "^"%s^" = rep-string ^"%1.0s^"\n"; + PS(22):= N+^0; \ 8-) + if N # 0 then + Print(PS, Strs(I), Strs(I)) + else + Print("^"%s^" = not a rep-string\n", Strs(I)); + ]; +] diff --git a/Task/Repeat-a-string/AArch64-Assembly/repeat-a-string.aarch64 b/Task/Repeat-a-string/AArch64-Assembly/repeat-a-string.aarch64 new file mode 100644 index 0000000000..d1c169665e --- /dev/null +++ b/Task/Repeat-a-string/AArch64-Assembly/repeat-a-string.aarch64 @@ -0,0 +1,124 @@ +/* ARM assembly AARCH64 Raspberry PI 3B */ +/* program repeatstring.s */ + + +/*******************************************/ +/* Constantes */ +/*******************************************/ +/* for this file see task include a file in language AArch64 assembly*/ +.include "../includeConstantesARM64.inc" + +.equ BUFFERSIZE, 2000 +/*******************************************/ +/* Macros */ +/*******************************************/ +//.include "../../ficmacros64.inc" // for developer debugging + +/*********************************/ +/* Initialized data */ +/*********************************/ +.data +szMessDebutPgm: .asciz "Program 64 bits start. \n" +szCarriageReturn: .asciz "\n" +szMessFinOK: .asciz "Program normal end. \n" +szMessErreur: .asciz "Error Buffer too small!!!\n" + +szString1: .asciz "ho" + + + +/*********************************/ +/* UnInitialized data */ +/*********************************/ +.bss + +.align 4 +sZoneConv: .skip 24 +sBuffer: .skip BUFFERSIZE +/*********************************/ +/* code section */ +/*********************************/ +.text +.global main +main: + ldr x0,qAdrszMessDebutPgm + bl affichageMess // start message + ldr x0,qAdrszString1 // load phrase adress + ldr x1,qAdrsBuffer + mov x2,#5 + bl repeatString + cmp x0,#0 + ble 99f + + ldr x0,qAdrsBuffer // buffer display + bl affichageMess + + ldr x0,qAdrszCarriageReturn + bl affichageMess + + ldr x0,qAdrszMessFinOK + bl affichageMess + b 100f +99: + ldr x0,qAdrszMessErreur // error + bl affichageMess + mov x0, #1 // return code error + b 100f +100: + mov x8,EXIT + svc #0 // system call +qAdrszMessDebutPgm: .quad szMessDebutPgm +qAdrszMessFinOK: .quad szMessFinOK +qAdrszMessErreur: .quad szMessErreur +qAdrszString1: .quad szString1 +qAdrsBuffer: .quad sBuffer +qAdrsZoneConv: .quad sZoneConv +qAdrszCarriageReturn: .quad szCarriageReturn + +/******************************************************************/ +/* test if number is aritmetic number */ +/******************************************************************/ +/* x0 contains string address */ +/* x1 contains buffer address */ +/* x2 number repeat */ +/* x0 return buffer writed length or -1 if error*/ +repeatString: + stp x3,lr,[sp,-16]! // save registers + stp x4,x5,[sp,-16]! // save registers + stp x6,x7,[sp,-16]! // save registers + mov x3,#0 // indice repeat + mov x4,#0 // indice buffer +1: + mov x5,#0 // indice string +2: + ldrb w6,[x0,x5] // load string characters + cmp x6,#0 // end string ? + beq 3f + strb w6,[x1,x4] // store char in buffer + add x4,x4,#1 // increment indice + add x5,x5,#1 + b 2b // and loop +3: + mul x6,x5,x2 // compute repeat length string + cmp x6,#BUFFERSIZE // compare to buffer length + bge 99f // error ? + add x3,x3,#1 // increment repeat counter + cmp x3,x2 // end ? + blt 1b + mov x6,#0 + strb w6,[x1,x4] // final zero + mov x0,x4 // return length + b 100f +99: + mov x0,#-1 // error + +100: + ldp x6,x7,[sp],16 // restaur r egisters + ldp x4,x5,[sp],16 // restaur registers + ldp x3,lr,[sp],16 // restaur registers + ret +/***************************************************/ +/* ROUTINES INCLUDE */ +/***************************************************/ +/* for this file see task include a file in language AArch64 assembly*/ +.include "../includeARM64.inc" diff --git a/Task/Repeat-a-string/ANSI-BASIC/repeat-a-string.basic b/Task/Repeat-a-string/ANSI-BASIC/repeat-a-string.basic new file mode 100644 index 0000000000..aae0fc7666 --- /dev/null +++ b/Task/Repeat-a-string/ANSI-BASIC/repeat-a-string.basic @@ -0,0 +1,2 @@ +10 PRINT REPEAT$("ha", 5) +20 END diff --git a/Task/Repeat-a-string/ARM-Assembly/repeat-a-string.arm b/Task/Repeat-a-string/ARM-Assembly/repeat-a-string.arm new file mode 100644 index 0000000000..d6a4d7d8eb --- /dev/null +++ b/Task/Repeat-a-string/ARM-Assembly/repeat-a-string.arm @@ -0,0 +1,119 @@ +/* ARM assembly Raspberry PI */ +/* program repeatstring.s */ + +/* REMARK 1 : this program use routines in a include file + see task Include a file language arm assembly + for the routine affichageMess conversion10 + see at end of this program the instruction include */ + +/*******************************************/ +/* Constantes */ +/*******************************************/ +.include "../constantes.inc" + +.equ BUFFERSIZE, 2000 +/*******************************************/ +/* Macros */ +/*******************************************/ +//.include "../../ficmacros32.inc" @ for developer debugging + +/*********************************/ +/* Initialized data */ +/*********************************/ +.data +szMessDebutPgm: .asciz "Program 32 bits start. \n" +szCarriageReturn: .asciz "\n" +szMessFinOK: .asciz "Program normal end. \n" +szMessErreur: .asciz "Error Buffer too small!!!\n" + +szString1: .asciz "ha" + + + +/*********************************/ +/* UnInitialized data */ +/*********************************/ +.bss + +.align 4 +sZoneConv: .skip 24 +sBuffer: .skip BUFFERSIZE +/*********************************/ +/* code section */ +/*********************************/ +.text +.global main +main: + ldr r0,iAdrszMessDebutPgm + bl affichageMess @ start message + ldr r0,iAdrszString1 @ load phrase adress + ldr r1,iAdrsBuffer + mov r2,#5 + bl repeatString + cmp r0,#0 + ble 99f + + ldr r0,iAdrsBuffer @ buffer display + bl affichageMess + + ldr r0,iAdrszCarriageReturn + bl affichageMess + + ldr r0,iAdrszMessFinOK + bl affichageMess + b 100f +99: + ldr r0,iAdrszMessErreur @ error + bl affichageMess + mov r0, #1 @ return code error + b 100f +100: + mov r7,#EXIT @ program end + svc #0 @ system call +iAdrszMessDebutPgm: .int szMessDebutPgm +iAdrszMessFinOK: .int szMessFinOK +iAdrszMessErreur: .int szMessErreur +iAdrszString1: .int szString1 +iAdrsBuffer: .int sBuffer +iAdrsZoneConv: .int sZoneConv +iAdrszCarriageReturn: .int szCarriageReturn + +/******************************************************************/ +/* test if number is aritmetic number */ +/******************************************************************/ +/* r0 contains string address */ +/* r1 contains buffer address */ +/* r2 number repeat */ +/* r0 return buffer writed length or -1 if error*/ +repeatString: + push {r3-r6,lr} @ save registers + mov r3,#0 @ indice repeat + mov r4,#0 @ indice buffer +1: + mov r5,#0 @ indice string +2: + ldrb r6,[r0,r5] @ load string characters + cmp r6,#0 @ end string ? + beq 3f + strb r6,[r1,r4] @ store char in buffer + add r4,r4,#1 @ increment indice + add r5,r5,#1 + b 2b @ and loop +3: + mul r6,r5,r2 @ compute repeat length string + cmp r6,#BUFFERSIZE @ compare to buffer length + movge r0,#-1 @ error ? + bge 100f + add r3,r3,#1 @ increment repeat counter + cmp r3,r2 @ end ? + blt 1b + mov r6,#0 + strb r6,[r1,r4] @ final zero + mov r0,r4 @ return length + +100: + pop {r3-r6,pc} @ restaur registers +/***************************************************/ +/* ROUTINES INCLUDE */ +/***************************************************/ +.include "../affichage.inc" diff --git a/Task/Repeat-a-string/Ada/repeat-a-string.ada b/Task/Repeat-a-string/Ada/repeat-a-string.adb similarity index 100% rename from Task/Repeat-a-string/Ada/repeat-a-string.ada rename to Task/Repeat-a-string/Ada/repeat-a-string.adb diff --git a/Task/Repeat-a-string/ArkScript/repeat-a-string.ark b/Task/Repeat-a-string/ArkScript/repeat-a-string.ark new file mode 100644 index 0000000000..3e511b0051 --- /dev/null +++ b/Task/Repeat-a-string/ArkScript/repeat-a-string.ark @@ -0,0 +1,3 @@ +(import std.String) + +(print (string:repeat "ha" 5)) diff --git a/Task/Repeat-a-string/AutoIt/repeat-a-string.autoit b/Task/Repeat-a-string/AutoIt/repeat-a-string.au3 similarity index 100% rename from Task/Repeat-a-string/AutoIt/repeat-a-string.autoit rename to Task/Repeat-a-string/AutoIt/repeat-a-string.au3 diff --git a/Task/Repeat-a-string/Ballerina/repeat-a-string.ballerina b/Task/Repeat-a-string/Ballerina/repeat-a-string.ballerina new file mode 100644 index 0000000000..3014c27b2d --- /dev/null +++ b/Task/Repeat-a-string/Ballerina/repeat-a-string.ballerina @@ -0,0 +1,16 @@ +// https://rosettacode.org/wiki/Repeat_a_string +import ballerina/io; + +function repeat(int l, string s) returns string { + string[] out = []; + foreach int _ in 1...l { + out.push(s); + } + return "".concat(...out); +} + +public function main() { + io:println(repeat(5, "ha")); + // Repeat a character: + io:println("".padEnd(5, "x")); +} diff --git a/Task/Repeat-a-string/COBOL/repeat-a-string.cobol b/Task/Repeat-a-string/COBOL/repeat-a-string.cob similarity index 100% rename from Task/Repeat-a-string/COBOL/repeat-a-string.cobol rename to Task/Repeat-a-string/COBOL/repeat-a-string.cob diff --git a/Task/Repeat-a-string/Crystal/repeat-a-string.crystal b/Task/Repeat-a-string/Crystal/repeat-a-string.cr similarity index 100% rename from Task/Repeat-a-string/Crystal/repeat-a-string.crystal rename to Task/Repeat-a-string/Crystal/repeat-a-string.cr diff --git a/Task/Repeat-a-string/Delphi/repeat-a-string-1.delphi b/Task/Repeat-a-string/Delphi/repeat-a-string-1.pas similarity index 100% rename from Task/Repeat-a-string/Delphi/repeat-a-string-1.delphi rename to Task/Repeat-a-string/Delphi/repeat-a-string-1.pas diff --git a/Task/Repeat-a-string/Delphi/repeat-a-string-2.delphi b/Task/Repeat-a-string/Delphi/repeat-a-string-2.pas similarity index 100% rename from Task/Repeat-a-string/Delphi/repeat-a-string-2.delphi rename to Task/Repeat-a-string/Delphi/repeat-a-string-2.pas diff --git a/Task/Repeat-a-string/Delphi/repeat-a-string-3.delphi b/Task/Repeat-a-string/Delphi/repeat-a-string-3.pas similarity index 100% rename from Task/Repeat-a-string/Delphi/repeat-a-string-3.delphi rename to Task/Repeat-a-string/Delphi/repeat-a-string-3.pas diff --git a/Task/Repeat-a-string/Delphi/repeat-a-string-4.delphi b/Task/Repeat-a-string/Delphi/repeat-a-string-4.pas similarity index 100% rename from Task/Repeat-a-string/Delphi/repeat-a-string-4.delphi rename to Task/Repeat-a-string/Delphi/repeat-a-string-4.pas diff --git a/Task/Repeat-a-string/DuckDB/repeat-a-string-1.duckdb b/Task/Repeat-a-string/DuckDB/repeat-a-string-1.duckdb new file mode 100644 index 0000000000..86a8b536e6 --- /dev/null +++ b/Task/Repeat-a-string/DuckDB/repeat-a-string-1.duckdb @@ -0,0 +1,2 @@ +select repeat('abc', 5) as five, + (repeat('abc', 0) = '') as zero; diff --git a/Task/Repeat-a-string/DuckDB/repeat-a-string-2.duckdb b/Task/Repeat-a-string/DuckDB/repeat-a-string-2.duckdb new file mode 100644 index 0000000000..5691e3508b --- /dev/null +++ b/Task/Repeat-a-string/DuckDB/repeat-a-string-2.duckdb @@ -0,0 +1 @@ +select string_agg('a',' ') as a from range(0,5); diff --git a/Task/Repeat-a-string/EasyLang/repeat-a-string.easy b/Task/Repeat-a-string/EasyLang/repeat-a-string.easy index 01e47c2588..6d37125d3e 100644 --- a/Task/Repeat-a-string/EasyLang/repeat-a-string.easy +++ b/Task/Repeat-a-string/EasyLang/repeat-a-string.easy @@ -1,7 +1,5 @@ func$ rep s$ n . - for i to n - r$ &= s$ - . + for i to n : r$ &= s$ return r$ . print rep "ha" 5 diff --git a/Task/Repeat-a-string/Ed/repeat-a-string.ed b/Task/Repeat-a-string/Ed/repeat-a-string.ed new file mode 100644 index 0000000000..cd30c948b4 --- /dev/null +++ b/Task/Repeat-a-string/Ed/repeat-a-string.ed @@ -0,0 +1,5 @@ +# by Artyom Bologov +H +s/.*/&&&&&/ +p +Q diff --git a/Task/Repeat-a-string/Elena/repeat-a-string.elena b/Task/Repeat-a-string/Elena/repeat-a-string.elena index 30a3efb13e..13df6b019e 100644 --- a/Task/Repeat-a-string/Elena/repeat-a-string.elena +++ b/Task/Repeat-a-string/Elena/repeat-a-string.elena @@ -2,7 +2,7 @@ import system'routines; import extensions; import extensions'text; -public program() +public Program() { var s := new Range(0, 5).selectBy::(x => "ha").summarize(new StringWriter()) } diff --git a/Task/Repeat-a-string/Elixir/repeat-a-string.elixir b/Task/Repeat-a-string/Elixir/repeat-a-string.ex similarity index 100% rename from Task/Repeat-a-string/Elixir/repeat-a-string.elixir rename to Task/Repeat-a-string/Elixir/repeat-a-string.ex diff --git a/Task/Repeat-a-string/Emacs-Lisp/repeat-a-string-1.l b/Task/Repeat-a-string/Emacs-Lisp/repeat-a-string-1.el similarity index 100% rename from Task/Repeat-a-string/Emacs-Lisp/repeat-a-string-1.l rename to Task/Repeat-a-string/Emacs-Lisp/repeat-a-string-1.el diff --git a/Task/Repeat-a-string/Emacs-Lisp/repeat-a-string-2.l b/Task/Repeat-a-string/Emacs-Lisp/repeat-a-string-2.el similarity index 100% rename from Task/Repeat-a-string/Emacs-Lisp/repeat-a-string-2.l rename to Task/Repeat-a-string/Emacs-Lisp/repeat-a-string-2.el diff --git a/Task/Repeat-a-string/Emacs-Lisp/repeat-a-string-3.l b/Task/Repeat-a-string/Emacs-Lisp/repeat-a-string-3.el similarity index 100% rename from Task/Repeat-a-string/Emacs-Lisp/repeat-a-string-3.l rename to Task/Repeat-a-string/Emacs-Lisp/repeat-a-string-3.el diff --git a/Task/Repeat-a-string/Euphoria/repeat-a-string-1.euphoria b/Task/Repeat-a-string/Euphoria/repeat-a-string-1.eu similarity index 100% rename from Task/Repeat-a-string/Euphoria/repeat-a-string-1.euphoria rename to Task/Repeat-a-string/Euphoria/repeat-a-string-1.eu diff --git a/Task/Repeat-a-string/Euphoria/repeat-a-string-2.euphoria b/Task/Repeat-a-string/Euphoria/repeat-a-string-2.eu similarity index 100% rename from Task/Repeat-a-string/Euphoria/repeat-a-string-2.euphoria rename to Task/Repeat-a-string/Euphoria/repeat-a-string-2.eu diff --git a/Task/Repeat-a-string/Euphoria/repeat-a-string-3.euphoria b/Task/Repeat-a-string/Euphoria/repeat-a-string-3.eu similarity index 100% rename from Task/Repeat-a-string/Euphoria/repeat-a-string-3.euphoria rename to Task/Repeat-a-string/Euphoria/repeat-a-string-3.eu diff --git a/Task/Repeat-a-string/Euphoria/repeat-a-string-4.euphoria b/Task/Repeat-a-string/Euphoria/repeat-a-string-4.eu similarity index 100% rename from Task/Repeat-a-string/Euphoria/repeat-a-string-4.euphoria rename to Task/Repeat-a-string/Euphoria/repeat-a-string-4.eu diff --git a/Task/Repeat-a-string/Euphoria/repeat-a-string-5.euphoria b/Task/Repeat-a-string/Euphoria/repeat-a-string-5.eu similarity index 100% rename from Task/Repeat-a-string/Euphoria/repeat-a-string-5.euphoria rename to Task/Repeat-a-string/Euphoria/repeat-a-string-5.eu diff --git a/Task/Repeat-a-string/Excel/repeat-a-string.excel b/Task/Repeat-a-string/Excel/repeat-a-string.excel new file mode 100644 index 0000000000..5164862aac --- /dev/null +++ b/Task/Repeat-a-string/Excel/repeat-a-string.excel @@ -0,0 +1 @@ +=REPT("ha", 5) diff --git a/Task/Repeat-a-string/Gleam/repeat-a-string.gleam b/Task/Repeat-a-string/Gleam/repeat-a-string.gleam new file mode 100644 index 0000000000..a17f97e7dc --- /dev/null +++ b/Task/Repeat-a-string/Gleam/repeat-a-string.gleam @@ -0,0 +1,5 @@ +import gleam/string + +pub fn main() { + echo string.repeat("hello", 3) +} diff --git a/Task/Repeat-a-string/Julia/repeat-a-string.julia b/Task/Repeat-a-string/Julia/repeat-a-string.jl similarity index 100% rename from Task/Repeat-a-string/Julia/repeat-a-string.julia rename to Task/Repeat-a-string/Julia/repeat-a-string.jl diff --git a/Task/Repeat-a-string/Kotlin/repeat-a-string-1.kotlin b/Task/Repeat-a-string/Kotlin/repeat-a-string-1.kts similarity index 100% rename from Task/Repeat-a-string/Kotlin/repeat-a-string-1.kotlin rename to Task/Repeat-a-string/Kotlin/repeat-a-string-1.kts diff --git a/Task/Repeat-a-string/Kotlin/repeat-a-string-2.kotlin b/Task/Repeat-a-string/Kotlin/repeat-a-string-2.kts similarity index 100% rename from Task/Repeat-a-string/Kotlin/repeat-a-string-2.kotlin rename to Task/Repeat-a-string/Kotlin/repeat-a-string-2.kts diff --git a/Task/Repeat-a-string/LOLCODE/repeat-a-string.lol b/Task/Repeat-a-string/LOLCODE/repeat-a-string.lol new file mode 100644 index 0000000000..b729dafe6d --- /dev/null +++ b/Task/Repeat-a-string/LOLCODE/repeat-a-string.lol @@ -0,0 +1,13 @@ +HAI 1.3 + +HOW IZ I STRREP YR S AN YR N + I HAS A OUTPUT ITZ "" + IM IN YR LOOP UPPIN YR M TIL BOTH SAEM N AN M + OUTPUT R SMOOSH OUTPUT S MKAY + IM OUTTA YR LOOP + FOUND YR OUTPUT +IF U SAY SO + +VISIBLE I IZ STRREP YR "HA" AN YR 5 MKAY + +KTHXBYE diff --git a/Task/Repeat-a-string/NewLISP/repeat-a-string.l b/Task/Repeat-a-string/NewLISP/repeat-a-string-1.l similarity index 100% rename from Task/Repeat-a-string/NewLISP/repeat-a-string.l rename to Task/Repeat-a-string/NewLISP/repeat-a-string-1.l diff --git a/Task/Repeat-a-string/NewLISP/repeat-a-string-2.l b/Task/Repeat-a-string/NewLISP/repeat-a-string-2.l new file mode 100644 index 0000000000..ff4925d926 --- /dev/null +++ b/Task/Repeat-a-string/NewLISP/repeat-a-string-2.l @@ -0,0 +1 @@ +(dup "back" 3 true) diff --git a/Task/Repeat-a-string/Nu/repeat-a-string-1.nu b/Task/Repeat-a-string/Nu/repeat-a-string-1.nu new file mode 100644 index 0000000000..08d45d48da --- /dev/null +++ b/Task/Repeat-a-string/Nu/repeat-a-string-1.nu @@ -0,0 +1 @@ +'' | fill -c 'ha' -w 5 diff --git a/Task/Repeat-a-string/Nu/repeat-a-string-2.nu b/Task/Repeat-a-string/Nu/repeat-a-string-2.nu new file mode 100644 index 0000000000..a9c3c3e4d1 --- /dev/null +++ b/Task/Repeat-a-string/Nu/repeat-a-string-2.nu @@ -0,0 +1 @@ +..<5 | each { 'ha' } | str join diff --git a/Task/Repeat-a-string/OCaml/repeat-a-string-1.ocaml b/Task/Repeat-a-string/OCaml/repeat-a-string-1.ml similarity index 100% rename from Task/Repeat-a-string/OCaml/repeat-a-string-1.ocaml rename to Task/Repeat-a-string/OCaml/repeat-a-string-1.ml diff --git a/Task/Repeat-a-string/OCaml/repeat-a-string-2.ocaml b/Task/Repeat-a-string/OCaml/repeat-a-string-2.ml similarity index 100% rename from Task/Repeat-a-string/OCaml/repeat-a-string-2.ocaml rename to Task/Repeat-a-string/OCaml/repeat-a-string-2.ml diff --git a/Task/Repeat-a-string/OCaml/repeat-a-string-3.ocaml b/Task/Repeat-a-string/OCaml/repeat-a-string-3.ml similarity index 100% rename from Task/Repeat-a-string/OCaml/repeat-a-string-3.ocaml rename to Task/Repeat-a-string/OCaml/repeat-a-string-3.ml diff --git a/Task/Repeat-a-string/OCaml/repeat-a-string-4.ocaml b/Task/Repeat-a-string/OCaml/repeat-a-string-4.ml similarity index 100% rename from Task/Repeat-a-string/OCaml/repeat-a-string-4.ocaml rename to Task/Repeat-a-string/OCaml/repeat-a-string-4.ml diff --git a/Task/Repeat-a-string/OCaml/repeat-a-string-5.ocaml b/Task/Repeat-a-string/OCaml/repeat-a-string-5.ml similarity index 100% rename from Task/Repeat-a-string/OCaml/repeat-a-string-5.ocaml rename to Task/Repeat-a-string/OCaml/repeat-a-string-5.ml diff --git a/Task/Repeat-a-string/OCaml/repeat-a-string-6.ocaml b/Task/Repeat-a-string/OCaml/repeat-a-string-6.ml similarity index 100% rename from Task/Repeat-a-string/OCaml/repeat-a-string-6.ocaml rename to Task/Repeat-a-string/OCaml/repeat-a-string-6.ml diff --git a/Task/Repeat-a-string/OmniMark/repeat-a-string.xom b/Task/Repeat-a-string/OmniMark/repeat-a-string.xom new file mode 100644 index 0000000000..65a500576b --- /dev/null +++ b/Task/Repeat-a-string/OmniMark/repeat-a-string.xom @@ -0,0 +1,4 @@ +process + repeat for integer i from 1 to 5 + output "ha" + again diff --git a/Task/Repeat-a-string/PascalABC.NET/repeat-a-string.pas b/Task/Repeat-a-string/PascalABC.NET/repeat-a-string.pas new file mode 100644 index 0000000000..21e04fdb9e --- /dev/null +++ b/Task/Repeat-a-string/PascalABC.NET/repeat-a-string.pas @@ -0,0 +1,2 @@ +## +Print('ha' * 5) diff --git a/Task/Repeat-a-string/Pluto/repeat-a-string.pluto b/Task/Repeat-a-string/Pluto/repeat-a-string.pluto new file mode 100644 index 0000000000..66a4abe738 --- /dev/null +++ b/Task/Repeat-a-string/Pluto/repeat-a-string.pluto @@ -0,0 +1 @@ +print('ha':rep(5)) diff --git a/Task/Repeat-a-string/PowerShell/repeat-a-string.psh b/Task/Repeat-a-string/PowerShell/repeat-a-string.ps1 similarity index 100% rename from Task/Repeat-a-string/PowerShell/repeat-a-string.psh rename to Task/Repeat-a-string/PowerShell/repeat-a-string.ps1 diff --git a/Task/Repeat-a-string/QBasic/repeat-a-string.basic b/Task/Repeat-a-string/QuickBASIC/repeat-a-string.basic similarity index 100% rename from Task/Repeat-a-string/QBasic/repeat-a-string.basic rename to Task/Repeat-a-string/QuickBASIC/repeat-a-string.basic diff --git a/Task/Repeat-a-string/ReScript/repeat-a-string.re b/Task/Repeat-a-string/ReScript/repeat-a-string.res similarity index 100% rename from Task/Repeat-a-string/ReScript/repeat-a-string.re rename to Task/Repeat-a-string/ReScript/repeat-a-string.res diff --git a/Task/Repeat-a-string/REBOL/repeat-a-string.rebol b/Task/Repeat-a-string/Rebol/repeat-a-string-1.rebol similarity index 100% rename from Task/Repeat-a-string/REBOL/repeat-a-string.rebol rename to Task/Repeat-a-string/Rebol/repeat-a-string-1.rebol diff --git a/Task/Repeat-a-string/Rebol/repeat-a-string-2.rebol b/Task/Repeat-a-string/Rebol/repeat-a-string-2.rebol new file mode 100644 index 0000000000..ab1cfdf0c7 --- /dev/null +++ b/Task/Repeat-a-string/Rebol/repeat-a-string-2.rebol @@ -0,0 +1 @@ +append/dup "" "ha" 5 diff --git a/Task/Repeat-a-string/Rust/repeat-a-string-1.rust b/Task/Repeat-a-string/Rust/repeat-a-string-1.rs similarity index 100% rename from Task/Repeat-a-string/Rust/repeat-a-string-1.rust rename to Task/Repeat-a-string/Rust/repeat-a-string-1.rs diff --git a/Task/Repeat-a-string/Rust/repeat-a-string-2.rust b/Task/Repeat-a-string/Rust/repeat-a-string-2.rs similarity index 100% rename from Task/Repeat-a-string/Rust/repeat-a-string-2.rust rename to Task/Repeat-a-string/Rust/repeat-a-string-2.rs diff --git a/Task/Repeat-a-string/Scheme/repeat-a-string-1.ss b/Task/Repeat-a-string/Scheme/repeat-a-string-1.scm similarity index 100% rename from Task/Repeat-a-string/Scheme/repeat-a-string-1.ss rename to Task/Repeat-a-string/Scheme/repeat-a-string-1.scm diff --git a/Task/Repeat-a-string/Scheme/repeat-a-string-2.ss b/Task/Repeat-a-string/Scheme/repeat-a-string-2.scm similarity index 100% rename from Task/Repeat-a-string/Scheme/repeat-a-string-2.ss rename to Task/Repeat-a-string/Scheme/repeat-a-string-2.scm diff --git a/Task/Repeat-a-string/Scheme/repeat-a-string-3.ss b/Task/Repeat-a-string/Scheme/repeat-a-string-3.scm similarity index 100% rename from Task/Repeat-a-string/Scheme/repeat-a-string-3.ss rename to Task/Repeat-a-string/Scheme/repeat-a-string-3.scm diff --git a/Task/Repeat-a-string/V-(Vlang)/repeat-a-string.v b/Task/Repeat-a-string/V-(Vlang)/repeat-a-string.v index 044ad0a941..3d28a48af8 100644 --- a/Task/Repeat-a-string/V-(Vlang)/repeat-a-string.v +++ b/Task/Repeat-a-string/V-(Vlang)/repeat-a-string.v @@ -1,14 +1 @@ -// Repeat a string, in V -// Tectonics: v run repeat-a-string.v -module main -import strings - -// starts here -pub fn main() { - // A strings module function to repeat strings - println(strings.repeat_string("ha", 5)) - - // Another strings module function to repeat a byte - // This indexes the string to get the first byte of the rune array - println(strings.repeat("*"[0], 5)) -} +println('ha'.repeat(5)) diff --git a/Task/Repeat-a-string/VBScript/repeat-a-string.vb b/Task/Repeat-a-string/VBScript/repeat-a-string.vbs similarity index 100% rename from Task/Repeat-a-string/VBScript/repeat-a-string.vb rename to Task/Repeat-a-string/VBScript/repeat-a-string.vbs diff --git a/Task/Repeat/ALGOL-68/repeat.alg b/Task/Repeat/ALGOL-68/repeat.alg index c8459a1671..f1504251eb 100644 --- a/Task/Repeat/ALGOL-68/repeat.alg +++ b/Task/Repeat/ALGOL-68/repeat.alg @@ -1,16 +1,13 @@ -# operator that executes a procedure the specified number of times # -OP REPEAT = ( INT count, PROC VOID routine )VOID: - TO count DO routine OD; +BEGIN + # operator that executes a procedure the specified number of times # + OP REPEAT = ( INT count, PROC VOID routine )VOID: TO count DO routine OD; -# make REPEAT a low priority operater # -PRIO REPEAT = 1; + # make REPEAT a low priority operater # + PRIO REPEAT = 1; - -# can also create variant that passes the iteration count as a parameter # -OP REPEAT = ( INT count, PROC( INT )VOID routine )VOID: - FOR iteration TO count DO routine( iteration ) OD; - -main: ( + # can also create variant that passes the iteration count as a parameter # + OP REPEAT = ( INT count, PROC( INT )VOID routine )VOID: + FOR iteration TO count DO routine( iteration ) OD; # PROC to test the REPEAT operator with # PROC say something = VOID: print( ( "something", newline ) ); @@ -18,8 +15,9 @@ main: ( 3 REPEAT say something; # PROC to test the variant # - PROC show squares = ( INT n )VOID: print( ( n, n * n, newline ) ); + PROC show squares = ( INT n )VOID: + print( ( whole( n, 0 ), " ", whole( n * n, 0 ), newline ) ); 3 REPEAT show squares -) +END diff --git a/Task/Repeat/Ada/repeat.ada b/Task/Repeat/Ada/repeat.adb similarity index 100% rename from Task/Repeat/Ada/repeat.ada rename to Task/Repeat/Ada/repeat.adb diff --git a/Task/Repeat/Applesoft-BASIC/repeat.basic b/Task/Repeat/Applesoft-BASIC/repeat.basic new file mode 100644 index 0000000000..865c1b1d9a --- /dev/null +++ b/Task/Repeat/Applesoft-BASIC/repeat.basic @@ -0,0 +1,20 @@ + 100 FOR I = 768 TO 794 + 110 READ B: POKE I,B: NEXT + 120 DATA165,185,72,165,184,72 + 130 DATA165,118,72,165,117,72 + 140 DATA169,176,72,32,123,221 + 150 DATA32,82,231,32,65,217 + 160 DATA76,210,215 + 170 POKE 1014,0: POKE 1015,3 + + 200 LET P = 400:N = 4 + 210 GOSUB 300"REPEAT P N + 220 END + + 300 IF N < = 0 THEN RETURN + 310 LET N = N - 1 + 320 & P + 330 GOTO 300 + + 400 PRINT "EXAMPLE" + 410 RETURN diff --git a/Task/Repeat/Asymptote/repeat.asymptote b/Task/Repeat/Asymptote/repeat.asymptote new file mode 100644 index 0000000000..b1eb5f7e14 --- /dev/null +++ b/Task/Repeat/Asymptote/repeat.asymptote @@ -0,0 +1,12 @@ +void proc() { + write(" Inside loop"); +} + +void repeat(void func(), int times) { + for (int i = 0; i < times; ++i) { + func(); + } +} + +repeat(proc, 5); +write("Loop Ended"); diff --git a/Task/Repeat/Chapel/repeat-1.chpl b/Task/Repeat/Chapel/repeat-1.chpl new file mode 100644 index 0000000000..6ca234b22f --- /dev/null +++ b/Task/Repeat/Chapel/repeat-1.chpl @@ -0,0 +1,13 @@ +config const n = 5; + +proc example() +{ + writeln("example"); +} + +proc repeat(func, n) +{ + for i in 0..#n do func(); +} + +repeat(example, n); diff --git a/Task/Repeat/Chapel/repeat-2.chpl b/Task/Repeat/Chapel/repeat-2.chpl new file mode 100644 index 0000000000..ac4f950092 --- /dev/null +++ b/Task/Repeat/Chapel/repeat-2.chpl @@ -0,0 +1,13 @@ +config const n = 5; + +proc example() +{ + writeln("example"); +} + +proc repeat(func : proc(), n : uint) +{ + for i in 0..#n do func(); +} + +repeat(example, n); diff --git a/Task/Repeat/Chapel/repeat-3.chpl b/Task/Repeat/Chapel/repeat-3.chpl new file mode 100644 index 0000000000..d229a7de7f --- /dev/null +++ b/Task/Repeat/Chapel/repeat-3.chpl @@ -0,0 +1,13 @@ +config const n = 5; + +proc example(x : uint) +{ + writeln("example ", x); +} + +proc repeat(func : proc(x : uint), n : uint) +{ + for i in 0..#n do func(i); +} + +repeat(example, n); diff --git a/Task/Repeat/Crystal/repeat.cr b/Task/Repeat/Crystal/repeat.cr new file mode 100644 index 0000000000..4d4a81d062 --- /dev/null +++ b/Task/Repeat/Crystal/repeat.cr @@ -0,0 +1,7 @@ +4.times{ puts "Example" } # idiomatic way + +def repeat(proc,num) + num.times{ proc.call } +end + +repeat(->{ puts "Example" }, 4) diff --git a/Task/Repeat/Dart/repeat.dart b/Task/Repeat/Dart/repeat.dart new file mode 100644 index 0000000000..06c3a614ac --- /dev/null +++ b/Task/Repeat/Dart/repeat.dart @@ -0,0 +1,14 @@ +void proc() { + print(" Inside loop"); +} + +void repeat(Function func, int times) { + for (var i = 0; i < times; i++) { + func(); + } +} + +void main() { + repeat(proc, 5); + print("Loop Ended"); +} diff --git a/Task/Repeat/Delphi/repeat-1.delphi b/Task/Repeat/Delphi/repeat-1.pas similarity index 100% rename from Task/Repeat/Delphi/repeat-1.delphi rename to Task/Repeat/Delphi/repeat-1.pas diff --git a/Task/Repeat/Delphi/repeat-2.delphi b/Task/Repeat/Delphi/repeat-2.pas similarity index 100% rename from Task/Repeat/Delphi/repeat-2.delphi rename to Task/Repeat/Delphi/repeat-2.pas diff --git a/Task/Repeat/Euphoria/repeat.eu b/Task/Repeat/Euphoria/repeat.eu new file mode 100644 index 0000000000..13cb9971dc --- /dev/null +++ b/Task/Repeat/Euphoria/repeat.eu @@ -0,0 +1,11 @@ +procedure repeat(integer proc, integer times) + for i = 1 to times do + call_proc(proc, {}) + end for +end procedure + +procedure say_hello() + puts(1, "hello\n") +end procedure + +repeat(routine_id("say_hello"), 3) diff --git a/Task/Repeat/Gleam/repeat.gleam b/Task/Repeat/Gleam/repeat.gleam new file mode 100644 index 0000000000..efc4624bc7 --- /dev/null +++ b/Task/Repeat/Gleam/repeat.gleam @@ -0,0 +1,15 @@ +import gleam/io + +pub fn main() { + repeat(3, fn() { io.println("hello") }) +} + +pub fn repeat(times: Int, func: fn() -> Nil) -> Nil { + case times { + _ if times < 1 -> Nil + _ -> { + func() + repeat(times - 1, func) + } + } +} diff --git a/Task/Repeat/Icon/repeat.icon b/Task/Repeat/Icon/repeat.icon new file mode 100644 index 0000000000..149e42e0ff --- /dev/null +++ b/Task/Repeat/Icon/repeat.icon @@ -0,0 +1,12 @@ +procedure main(A) + n := \A[1] | 10 + runit(P,n) | write() + runit(Q,n) | write() +end + +procedure runit(p,n) + every 1 to n do p() +end + +procedure P(); writes("."); end +procedure Q(); writes("+"); end diff --git a/Task/Repeat/JavaScript/repeat.js b/Task/Repeat/JavaScript/repeat.js new file mode 100644 index 0000000000..aafe13ed31 --- /dev/null +++ b/Task/Repeat/JavaScript/repeat.js @@ -0,0 +1,11 @@ +function repeat(f, n) { + while (n-- > 0) { + f(); + } +} + +function test() { + console.log("test"); +} + +repeat(test, 3); diff --git a/Task/Repeat/Julia/repeat.julia b/Task/Repeat/Julia/repeat.jl similarity index 100% rename from Task/Repeat/Julia/repeat.julia rename to Task/Repeat/Julia/repeat.jl diff --git a/Task/Repeat/Kotlin/repeat.kotlin b/Task/Repeat/Kotlin/repeat.kts similarity index 100% rename from Task/Repeat/Kotlin/repeat.kotlin rename to Task/Repeat/Kotlin/repeat.kts diff --git a/Task/Repeat/LOLCODE/repeat.lol b/Task/Repeat/LOLCODE/repeat.lol new file mode 100644 index 0000000000..06934dda20 --- /dev/null +++ b/Task/Repeat/LOLCODE/repeat.lol @@ -0,0 +1,15 @@ +HAI 1.3 + +HOW IZ I REPEAT YR DEMANZ AN YR TIMEZ + IM IN YR LOOP UPPIN YR VAR TIL BOTH SAEM VAR AN TIMEZ + I IZ DEMANZ MKAY + IM OUTTA YR LOOP +IF U SAY SO + +HOW IZ I SAYHELLO + VISIBLE "HELLO" +IF U SAY SO + +I IZ REPEAT YR SAYHELLO AN YR 3 MKAY + +KTHXBYE diff --git a/Task/Repeat/Mastermind/repeat.mastermind b/Task/Repeat/Mastermind/repeat.mastermind new file mode 100644 index 0000000000..6ee80fb1bf --- /dev/null +++ b/Task/Repeat/Mastermind/repeat.mastermind @@ -0,0 +1,15 @@ +def do_something { + output "Letter: "; + output 'a' + number; + output '\n'; +} + +def repeat { + let i = 0; + drain times into i { + do_something; + } +} + +let repetitions = 8; +repeat; diff --git a/Task/Repeat/Maxima/repeat.maxima b/Task/Repeat/Maxima/repeat.maxima new file mode 100644 index 0000000000..35871e7e54 --- /dev/null +++ b/Task/Repeat/Maxima/repeat.maxima @@ -0,0 +1,5 @@ +repeat(f, n) := thru n do f()$ + +test() := print("test")$ + +repeat(test, 3); diff --git a/Task/Repeat/OCaml/repeat.ocaml b/Task/Repeat/OCaml/repeat.ml similarity index 100% rename from Task/Repeat/OCaml/repeat.ocaml rename to Task/Repeat/OCaml/repeat.ml diff --git a/Task/Repeat/OxygenBasic/repeat.basic b/Task/Repeat/OxygenBasic/repeat.basic new file mode 100644 index 0000000000..307e18d04d --- /dev/null +++ b/Task/Repeat/OxygenBasic/repeat.basic @@ -0,0 +1,18 @@ +uses console + +sub proc + printl " Inside loop" +end sub + +macro rep (func, n) + int i + for i = 1 to n + func() + next +end macro + +rep (proc, 5) +printl "Loop Ended" + +printl cr "Enter ..." +waitkey diff --git a/Task/Repeat/PascalABC.NET/repeat.pas b/Task/Repeat/PascalABC.NET/repeat.pas new file mode 100644 index 0000000000..28afa11525 --- /dev/null +++ b/Task/Repeat/PascalABC.NET/repeat.pas @@ -0,0 +1,7 @@ +procedure Rep(n: integer; p: procedure) := (p * n); + +procedure p := Print('Hello'); + +begin + Rep(3,p); +end. diff --git a/Task/Repeat/Phix/repeat.phix b/Task/Repeat/Phix/repeat.phix index a5a3821b0f..548201cd11 100644 --- a/Task/Repeat/Phix/repeat.phix +++ b/Task/Repeat/Phix/repeat.phix @@ -1,13 +1,11 @@ ---> - procedure Repeat(integer rid, integer n) - for i=1 to n do - rid() - end for - end procedure +procedure Repeat(integer rid, integer n) + for i=1 to n do + rid() + end for +end procedure - procedure Hello() - ?"Hello" - end procedure +procedure Hello() + ?"Hello" +end procedure - Repeat(Hello,5) - - with javascript_semantics - include mpfr.e - procedure repunit(mpz z, integer n, base=10) - mpz_set_si(z,0) - for i=1 to n do - mpz_mul_si(z,z,base) - mpz_add_si(z,z,1) - end for - end procedure +with javascript_semantics +include mpfr.e +procedure repunit(mpz z, integer n, base=10) + mpz_set_si(z,0) + for i=1 to n do + mpz_mul_si(z,z,base) + mpz_add_si(z,z,1) + end for +end procedure - atom t0 = time() - constant {limit,blimit} = iff(platform()=JS?{400,16} -- 8.8s - :{1000,16}) -- 50.3s - -- :{1000,36}) -- 4 min 20s - -- :{2700,16}) -- 28 min 35s - -- :{2700,36}) -- >patience - sequence primes = get_primes_le(limit) - mpz z = mpz_init() - for base=2 to blimit do - sequence rprimes = {} - for i=1 to length(primes) do - integer p = primes[i] - repunit(z,p,base) - if mpz_prime(z) then - rprimes = append(rprimes,sprint(p)) - end if - end for - printf(1,"Base %2d: %s\n", {base, join(rprimes)}) - end for - ?elapsed(time()-t0) - - function resistormesh(integer ni, nj, ai, aj, bi, bj) - integer n = ni*nj, k, c - sequence A = repeat(repeat(0,n),n), - B = repeat({0},n) - for i=1 to ni do - for j=1 to nj do - k = (i-1)*nj + j--1 - if i=ai and j=aj then - A[k,k] = 1 - else - c = 0 - if i<ni then c += 1; A[k,k+nj] = -1 end if - if i>1 then c += 1; A[k,k-nj] = -1 end if - if j<nj then c += 1; A[k,k+1] = -1 end if - if j>1 then c += 1; A[k,k-1] = -1 end if - A[k,k] = c - end if - end for - end for - k = (bi-1)*nj +bj - B[k,1] = 1 - A = inverse(A) - B = matrix_mul(A,B) - return B[k,1] - end function +function resistormesh(integer ni, nj, ai, aj, bi, bj) + integer n = ni*nj, k, c + sequence A = repeat(repeat(0,n),n), + B = repeat({0},n) + for i=1 to ni do + for j=1 to nj do + k = (i-1)*nj + j--1 + if i=ai and j=aj then + A[k,k] = 1 + else + c = 0 + if i1 then c += 1; A[k,k-nj] = -1 end if + if j1 then c += 1; A[k,k-1] = -1 end if + A[k,k] = c + end if + end for + end for + k = (bi-1)*nj +bj + B[k,1] = 1 + A = inverse(A) + B = matrix_mul(A,B) + return B[k,1] +end function - printf(1,"Resistance = %.13f ohms\n",resistormesh(10, 10, 2, 2, 8, 7)) - - function stuff() - return {"PI",'=',3.1415926535} - end function - {string what, integer op, atom val} = stuff() - - procedure solve_quadratic(sequence t3) - atom {a,b,c} = t3, - d = b*b-4*a*c, f - string s = sprintf("for a=%g,b=%g,c=%g",t3), t - sequence u - if abs(d)<1e-6 then d=0 end if - switch sign(d) do - case 0: t = "single root is %g" - u = {-b/2/a} - case 1: t = "real roots are %g and %g" - f = (1+sqrt(1-4*a*c/(b*b)))/2 - u = {-f*b/a,-c/b/f} - case-1: t = "complex roots are %g +/- %g*i" - u = {-b/2/a,sqrt(-d)/2/a} - end switch - printf(1,"%-25s the %s\n",{s,sprintf(t,u)}) - end procedure +function poly(sequence si) -- display helper + string r = "" + integer l = length(si) + for t=1 to l do + atom sit = si[t] + if sit!=0 then + if sit=1 and tconstant
    tests = {{1,-1E9,1}, - {1,0,1}, - {2,-1,-6}, - {1,2,-2}, - {0.5,1.4142135,1}, - {1,3,2}, - {3,4,5}} +procedure solve_quadratic(sequence t3) + atom {a,b,c} = t3, + d = b*b-4*a*c, f + string t + sequence u + if abs(d)<1e-6 then d=0 end if + switch sign(d) do + case 0: t = "single root is %g" + u = {-b/2/a} + case 1: t = "real roots are %g and %g" + f = (1+sqrt(1-4*a*c/(b*b)))/2 + u = {-f*b/a,-c/b/f} + case-1: t = "complex roots are %g +/- %g*i" + u = {-b/2/a,sqrt(-d)/2/a} + end switch + printf(1,"%25s : the %s\n",{poly(t3),sprintf(t,u)}) +end procedure - papply(tests,solve_quadratic) -( (count,lang), ...) continueValue,tasks,curl := "",List(), CURL(); // "nm\0nm\0...." - do{ // eg 5 times + do{ // eg 5 times page:=curl.get(("http://rosettacode.org/mw/api.php?" "format=json" - "&action=query" - "&generator=categorymembers" - "&gcmtitle=Category:Programming%%20Languages" - "&gcmlimit=500" - "&prop=categoryinfo" - "&rawcontinue" // remove warning - "&gcmcontinue=%s") - .fmt(continueValue)); + "&action=query" + "&generator=categorymembers" + "&gcmtitle=Category:Programming%%20Languages" + "&gcmlimit=500" + "&prop=categoryinfo" + "&rawcontinue" // remove warning + "&gcmcontinue=%s") + .fmt(continueValue)); page=page[0].del(0,page[1]); // get rid of HTML header json:=YAJL().write(page).close(); json["query"]["pages"].howza(9).pump(tasks,fcn(d){ #dictionary values,only // { title:Category:AWK,categoryinfo:{ pages:398,size:401,... },... } // Gotta take care of no categoryinfo case - count:=d.find("categoryinfo",Dictionary).find("size",0); // or pages? - if(count<300) return(Void.Skip); // prune + count:=d.find("categoryinfo",Dictionary).find("size",0); // or pages? + if(count<300) return(Void.Skip); // prune T(count,d["title"].del(0,9)); // "Category:RPL" --> "RPL" }); if(continueValue=json.find("query-continue")) - // subcat|524558580a52455858|4331 or void - continueValue=continueValue["categorymembers"]["gcmcontinue"]; + // subcat|524558580a52455858|4331 or void + continueValue=continueValue["categorymembers"]["gcmcontinue"]; }while(continueValue); tasks } -langCounts:=getLangCounts() .sort(fcn(a,b){ a[0]>b[0] }); // reverse sort +langCounts:=getLangCounts() .sort(fcn(a,b){ a[0]>b[0] }); // reverse sort println("Most popular Rosetta Code languages as of ",Time.Date.prettyDay()); foreach n,name in ([1..15].zip(langCounts)) diff --git a/Task/Rot-13/ANSI-BASIC/rot-13.basic b/Task/Rot-13/ANSI-BASIC/rot-13.basic new file mode 100644 index 0000000000..5933451499 --- /dev/null +++ b/Task/Rot-13/ANSI-BASIC/rot-13.basic @@ -0,0 +1,25 @@ +100 REM Rot-13 +110 DECLARE EXTERNAL FUNCTION Rot13$ +120 LET A$ = "The quick brown fox jumps over the lazy dog." +130 PRINT A$ +140 LET B$ = Rot13$(A$) +150 PRINT B$ +160 LET C$ = Rot13$(B$) +170 PRINT C$ +180 END +190 ! +200 EXTERNAL FUNCTION Rot13$(A$) +210 LET B$ = "" +220 FOR I = 1 TO LEN(A$) +230 LET N = ORD(A$(I:I)) +240 IF N >= 65 AND N <= 91 THEN +250 LET N1 = MOD(N - 65 + 13, 26) + 65 +260 ELSEIF N >= 97 AND N <= 123 THEN +270 LET N1 = MOD(N - 97 + 13, 26) + 97 +280 ELSE +290 LET N1 = N +300 END IF +310 LET B$ = B$ & CHR$(N1) +320 NEXT I +330 LET Rot13$ = B$ +340 END FUNCTION diff --git a/Task/Rot-13/Ada/rot-13.ada b/Task/Rot-13/Ada/rot-13.adb similarity index 100% rename from Task/Rot-13/Ada/rot-13.ada rename to Task/Rot-13/Ada/rot-13.adb diff --git a/Task/Rot-13/Arturo/rot-13.arturo b/Task/Rot-13/Arturo/rot-13.arturo index b8ff3013fb..11cb6cce89 100644 --- a/Task/Rot-13/Arturo/rot-13.arturo +++ b/Task/Rot-13/Arturo/rot-13.arturo @@ -1,8 +1,10 @@ rot13: function [c][ - case [in? lower c] - when? -> `a`..`m` -> return to :char (to :integer c) + 13 - when? -> `n`..`z` -> return to :char (to :integer c) - 13 - else -> return c + lc: lower c + when.has: lc [ + [|in? 'a'..'m'] -> return to :char (to :integer c) + 13 + [|in? 'n'..'z'] -> return to :char (to :integer c) - 13 + true -> return c + ] ] loop "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" 'ch diff --git a/Task/Rot-13/Ballerina/rot-13.ballerina b/Task/Rot-13/Ballerina/rot-13.ballerina new file mode 100644 index 0000000000..810206f3f0 --- /dev/null +++ b/Task/Rot-13/Ballerina/rot-13.ballerina @@ -0,0 +1,24 @@ +import ballerina/io; + +function rot13(string s) returns string|error { + int[] cps = s.toCodePointInts(); + string out = ""; + foreach int i in cps { + int _i = i; + string ch = check string:fromCodePointInt(i); + ch = ch.toUpperAscii(); + if "A" <= ch && ch <= "Z" { + _i += (ch <= "M") ? 13 : -13; + } + out += check string:fromCodePointInt(_i); + } + return out; +} + +public function main() returns error? { + string n = check rot13("The quick brown fox jumps over the lazy dog."); + // Gur dhvpx oebja sbk whzxc bire gur ynml qbt. + io:println(n); + n = check rot13(n); + io:println(n); +} diff --git a/Task/Rot-13/Batch-File/rot-13.bat b/Task/Rot-13/Batch-File/rot-13-1.bat similarity index 100% rename from Task/Rot-13/Batch-File/rot-13.bat rename to Task/Rot-13/Batch-File/rot-13-1.bat diff --git a/Task/Rot-13/Batch-File/rot-13-2.bat b/Task/Rot-13/Batch-File/rot-13-2.bat new file mode 100644 index 0000000000..838e8ad570 --- /dev/null +++ b/Task/Rot-13/Batch-File/rot-13-2.bat @@ -0,0 +1,29 @@ +@echo off +setlocal enableextensions enabledelayedexpansion +set /p str=||goto :eof + +set orig=abcdefghijklmnopqrstuvwxyz +set ciphLwr=nopqrstuvwxyzabcdefghijklm +set ciphUpr=NOPQRSTUVWXYZABCDEFGHIJKLM +for /f "delims==" %%A in ('set char. 2^>nul') do set "%%A=" +for /l %%i in (0,1,25) do for %%c in (^!orig:~%%i^,1^!) do set char.%%c=%%c!ciphLwr:~%%i,1!!ciphUpr:~%%i,1! + +:: string length +:: https://ss64.com/forum/strlen.html +:: !str! instead of %str% to not resolve anything after percent expansion +set "tempFile=%temp%\strlen-rot13.tmp" +echo(!str!>"%tempFile%" +for %%F in ("%tempFile%") do set /a len=%%~zF-3 +del "%tempFile%" + +:: usebackq and '"..."' in for/f : handles spaces +::: plain for resolves wildcard characters ("?" and "*") so it isn't used +:: ^ : handles exclamation marks +set buffer= +for /l %%i in (0,1,%len%) do for /f "usebackq eol= delims=" %%c in ('"!str:~%%i,1!"') do ( + if defined char.%%~c ( + if "%%~c"=="!char.%%~c:~0,1!" (set aug=1) else (set aug=2) + for %%d in ("!aug!") do set "buffer=!buffer!!char.%%~c:~%%~d,1!" + ) else (set "buffer=!buffer!^%%~c") +) +echo(!buffer! diff --git a/Task/Rot-13/C++/rot-13-4.cpp b/Task/Rot-13/C++/rot-13-4.cpp new file mode 100644 index 0000000000..e8f3e3068e --- /dev/null +++ b/Task/Rot-13/C++/rot-13-4.cpp @@ -0,0 +1,22 @@ +#include +#include +#define rot13(c) (c >= 'A' && c <= 'Z')\ + ? (c - 'A' + 13) % 26 + 'A'\ + : (\ + (c >= 'a' && c <= 'z')\ + ? (c - 'a' + 13) % 26 + 'a'\ + : c\ + ) + +using namespace std; +int main() { + ios_base::sync_with_stdio(false); + cin.tie(nullptr); + string str; + while (getline(cin, str)) { + for (auto& i : str) i = rot13(i); + str += '\n'; + cout << str; + } + return 0; +} diff --git a/Task/Rot-13/CBASIC/rot-13.basic b/Task/Rot-13/CBASIC/rot-13.basic new file mode 100644 index 0000000000..ff1cc19407 --- /dev/null +++ b/Task/Rot-13/CBASIC/rot-13.basic @@ -0,0 +1,25 @@ +rem Return the ROT13 transformation of s$, preserving case \ + and passing non-alphabetic characters without change + +def fn.rot13$(s$) + normal$ ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + rotated$="NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm" + outstr$ = "" + for i% = 1 to len(s$) + c$ = mid$(s$,i%,1) + k% = match(c$,normal$,1) + if k% <> 0 then c$ = mid$(rotated$,k%,1) + outstr$ = outstr$ + c$ + next i% +fn.rot13$ = outstr$ +return +fend + +plain$ = "The quick brown fox jumps over the lazy dog." +encoded$ = fn.rot13$(plain$) + +print "Plain Text: "; plain$ +print "Encoded : "; encoded$ +print "Restored : "; fn.rot13$(encoded$) + +end diff --git a/Task/Rot-13/COBOL/rot-13-1.cobol b/Task/Rot-13/COBOL/rot-13-1.cob similarity index 100% rename from Task/Rot-13/COBOL/rot-13-1.cobol rename to Task/Rot-13/COBOL/rot-13-1.cob diff --git a/Task/Rot-13/COBOL/rot-13-2.cobol b/Task/Rot-13/COBOL/rot-13-2.cob similarity index 100% rename from Task/Rot-13/COBOL/rot-13-2.cobol rename to Task/Rot-13/COBOL/rot-13-2.cob diff --git a/Task/Rot-13/Crystal/rot-13.cr b/Task/Rot-13/Crystal/rot-13.cr new file mode 100644 index 0000000000..1fee64a08c --- /dev/null +++ b/Task/Rot-13/Crystal/rot-13.cr @@ -0,0 +1,5 @@ +from = ['A'..'Z', 'a'..'z'].flat_map(&.to_a).join +to = ['N'..'Z', 'A'..'M', 'n'..'z', 'a'..'m'].flat_map(&.to_a).join +while line = ARGF.gets + puts line.tr from, to +end diff --git a/Task/Rot-13/Delphi/rot-13.delphi b/Task/Rot-13/Delphi/rot-13.pas similarity index 100% rename from Task/Rot-13/Delphi/rot-13.delphi rename to Task/Rot-13/Delphi/rot-13.pas diff --git a/Task/Rot-13/Ed/rot-13.ed b/Task/Rot-13/Ed/rot-13.ed new file mode 100644 index 0000000000..5a3a40ce38 --- /dev/null +++ b/Task/Rot-13/Ed/rot-13.ed @@ -0,0 +1,58 @@ +H +,p +g/([[:alpha:]])/s// \1 /g +g/[ ]a[ ]/s//%n%/g +g/[ ]b[ ]/s//%o%/g +g/[ ]c[ ]/s//%p%/g +g/[ ]d[ ]/s//%q%/g +g/[ ]e[ ]/s//%r%/g +g/[ ]f[ ]/s//%s%/g +g/[ ]g[ ]/s//%t%/g +g/[ ]h[ ]/s//%u%/g +g/[ ]i[ ]/s//%v%/g +g/[ ]j[ ]/s//%w%/g +g/[ ]k[ ]/s//%x%/g +g/[ ]l[ ]/s//%y%/g +g/[ ]m[ ]/s//%z%/g +g/[ ]n[ ]/s//%a%/g +g/[ ]o[ ]/s//%b%/g +g/[ ]p[ ]/s//%c%/g +g/[ ]q[ ]/s//%d%/g +g/[ ]r[ ]/s//%e%/g +g/[ ]s[ ]/s//%f%/g +g/[ ]t[ ]/s//%g%/g +g/[ ]u[ ]/s//%h%/g +g/[ ]v[ ]/s//%i%/g +g/[ ]w[ ]/s//%j%/g +g/[ ]x[ ]/s//%k%/g +g/[ ]y[ ]/s//%l%/g +g/[ ]z[ ]/s//%m%/g +g/[ ]A[ ]/s//%N%/g +g/[ ]B[ ]/s//%O%/g +g/[ ]C[ ]/s//%P%/g +g/[ ]D[ ]/s//%Q%/g +g/[ ]E[ ]/s//%R%/g +g/[ ]F[ ]/s//%S%/g +g/[ ]G[ ]/s//%T%/g +g/[ ]H[ ]/s//%U%/g +g/[ ]I[ ]/s//%V%/g +g/[ ]J[ ]/s//%W%/g +g/[ ]K[ ]/s//%X%/g +g/[ ]L[ ]/s//%Y%/g +g/[ ]M[ ]/s//%Z%/g +g/[ ]N[ ]/s//%A%/g +g/[ ]O[ ]/s//%B%/g +g/[ ]P[ ]/s//%C%/g +g/[ ]Q[ ]/s//%D%/g +g/[ ]R[ ]/s//%E%/g +g/[ ]S[ ]/s//%F%/g +g/[ ]T[ ]/s//%G%/g +g/[ ]U[ ]/s//%H%/g +g/[ ]V[ ]/s//%I%/g +g/[ ]W[ ]/s//%J%/g +g/[ ]X[ ]/s//%K%/g +g/[ ]Y[ ]/s//%L%/g +g/[ ]Z[ ]/s//%M%/g +g/%([[:alpha:]])%/s//\1/g +,p +Q diff --git a/Task/Rot-13/Elena/rot-13.elena b/Task/Rot-13/Elena/rot-13.elena index 43e8dabd2a..d1db4d9e57 100644 --- a/Task/Rot-13/Elena/rot-13.elena +++ b/Task/Rot-13/Elena/rot-13.elena @@ -22,10 +22,10 @@ singleton rotConvertor = s.selectBy::(ch => rotConvertor.convert(ch)).summarize(new StringWriter()); } -public program() +public Program() { - if (program_arguments.Length > 1) + if (Program_arguments.Length > 1) { - console.printLine(rotConvertor.convert(program_arguments[1])) + Console.printLine(rotConvertor.convert(program_arguments[1])) } } diff --git a/Task/Rot-13/Elixir/rot-13-1.elixir b/Task/Rot-13/Elixir/rot-13-1.ex similarity index 100% rename from Task/Rot-13/Elixir/rot-13-1.elixir rename to Task/Rot-13/Elixir/rot-13-1.ex diff --git a/Task/Rot-13/Elixir/rot-13-2.elixir b/Task/Rot-13/Elixir/rot-13-2.ex similarity index 100% rename from Task/Rot-13/Elixir/rot-13-2.elixir rename to Task/Rot-13/Elixir/rot-13-2.ex diff --git a/Task/Rot-13/Emacs-Lisp/rot-13-1.l b/Task/Rot-13/Emacs-Lisp/rot-13-1.el similarity index 100% rename from Task/Rot-13/Emacs-Lisp/rot-13-1.l rename to Task/Rot-13/Emacs-Lisp/rot-13-1.el diff --git a/Task/Rot-13/Emacs-Lisp/rot-13-2.l b/Task/Rot-13/Emacs-Lisp/rot-13-2.el similarity index 100% rename from Task/Rot-13/Emacs-Lisp/rot-13-2.l rename to Task/Rot-13/Emacs-Lisp/rot-13-2.el diff --git a/Task/Rot-13/Euphoria/rot-13.euphoria b/Task/Rot-13/Euphoria/rot-13.eu similarity index 100% rename from Task/Rot-13/Euphoria/rot-13.euphoria rename to Task/Rot-13/Euphoria/rot-13.eu diff --git a/Task/Rot-13/Haxe/rot-13.haxe b/Task/Rot-13/Haxe/rot-13.hx similarity index 100% rename from Task/Rot-13/Haxe/rot-13.haxe rename to Task/Rot-13/Haxe/rot-13.hx diff --git a/Task/Rot-13/Julia/rot-13-1.julia b/Task/Rot-13/Julia/rot-13-1.jl similarity index 100% rename from Task/Rot-13/Julia/rot-13-1.julia rename to Task/Rot-13/Julia/rot-13-1.jl diff --git a/Task/Rot-13/Julia/rot-13-2.julia b/Task/Rot-13/Julia/rot-13-2.jl similarity index 100% rename from Task/Rot-13/Julia/rot-13-2.julia rename to Task/Rot-13/Julia/rot-13-2.jl diff --git a/Task/Rot-13/Kotlin/rot-13.kotlin b/Task/Rot-13/Kotlin/rot-13.kts similarity index 100% rename from Task/Rot-13/Kotlin/rot-13.kotlin rename to Task/Rot-13/Kotlin/rot-13.kts diff --git a/Task/Rot-13/Lua/rot-13-1.lua b/Task/Rot-13/Lua/rot-13-1.lua index 2d55a69cac..b58dd54201 100644 --- a/Task/Rot-13/Lua/rot-13-1.lua +++ b/Task/Rot-13/Lua/rot-13-1.lua @@ -3,3 +3,5 @@ function rot13(s) local b = "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm" return (s:gsub("%a", function(c) return b:sub(a:find(c)) end)) end + +print(rot13("nowhere ABJURER")) diff --git a/Task/Rot-13/Lua/rot-13-2.lua b/Task/Rot-13/Lua/rot-13-2.lua index 79cd59dcf7..eff6e9239d 100644 --- a/Task/Rot-13/Lua/rot-13-2.lua +++ b/Task/Rot-13/Lua/rot-13-2.lua @@ -1,3 +1,5 @@ function rot13(s) return (s:gsub("%a", function(c) c=c:byte() return string.char(c+(c%32<14 and 13 or -13)) end)) end + +print(rot13("nowhere ABJURER")) diff --git a/Task/Rot-13/Nu/rot-13.nu b/Task/Rot-13/Nu/rot-13.nu new file mode 100644 index 0000000000..4768e451a2 --- /dev/null +++ b/Task/Rot-13/Nu/rot-13.nu @@ -0,0 +1,9 @@ +let map = ( + seq char A Z | zip (seq char a z) | flatten + | into record | [$in $in] | headers | first + | roll left -c -b 26 +) + +def rot13 [] { + split chars | each {|c| $map | get -i -s $c | default $c } | str join +} diff --git a/Task/Rot-13/OCaml/rot-13-1.ocaml b/Task/Rot-13/OCaml/rot-13-1.ml similarity index 100% rename from Task/Rot-13/OCaml/rot-13-1.ocaml rename to Task/Rot-13/OCaml/rot-13-1.ml diff --git a/Task/Rot-13/OCaml/rot-13-2.ocaml b/Task/Rot-13/OCaml/rot-13-2.ml similarity index 100% rename from Task/Rot-13/OCaml/rot-13-2.ocaml rename to Task/Rot-13/OCaml/rot-13-2.ml diff --git a/Task/Rot-13/OCaml/rot-13-3.ocaml b/Task/Rot-13/OCaml/rot-13-3.ml similarity index 100% rename from Task/Rot-13/OCaml/rot-13-3.ocaml rename to Task/Rot-13/OCaml/rot-13-3.ml diff --git a/Task/Rot-13/OmniMark/rot-13.xom b/Task/Rot-13/OmniMark/rot-13.xom new file mode 100644 index 0000000000..6af1a8d2cf --- /dev/null +++ b/Task/Rot-13/OmniMark/rot-13.xom @@ -0,0 +1,22 @@ +; rot-13.xom +global stream gs-phrase + +define stream function apply-rot-13 (value stream phrase) as + local integer b + local stream ciphered + open ciphered as buffer + repeat scan phrase + match letter => char + set b to char binary 0 + increment b by 13 + decrement b by 26 when char matches uc and b > 90 + decrement b by 26 when char matches lc and b > 122 + put ciphered "b" % b + match any => char + put ciphered char + again + close ciphered + return ciphered + +process + output apply-rot-13(gs-phrase) diff --git a/Task/Rot-13/PL-I-80/rot-13.pli b/Task/Rot-13/PL-I-80/rot-13.pli index 39b4fab5f2..37a997b3fe 100644 --- a/Task/Rot-13/PL-I-80/rot-13.pli +++ b/Task/Rot-13/PL-I-80/rot-13.pli @@ -1,13 +1,7 @@ -rot13_test: - procedure options(main); - - %replace - true by '1'b, - false by '0'b; +rot13_test: procedure options(main); dcl (plain, encoded) char(127) varying; - - plain = 'The quick brown fox jumps over the lazy red dog.'; + plain = 'The quick brown fox jumps over the lazy dog.'; put skip list ('Plain text:', plain); encoded = rot13(plain); put skip list ('Encoded :', encoded); @@ -23,38 +17,13 @@ rot13: i fixed bin(15); do i = 1 to length(s); ch = substr(s,i,1); - if (isalpha(ch)) then - do; - if (toupper(ch) > 'M') then - ch = ascii(rank(ch) - 13); - else - ch = ascii(rank(ch) + 13); - end; + if (ch >= 'a' & ch <= 'm') | (ch >= 'A' & ch <= 'M') + then ch = ascii(rank(ch) + 13); + else if (ch >= 'n' & ch <= 'z') | (ch >= 'N' & ch <= 'Z') + then ch = ascii(rank(ch) - 13); substr(s,i,1) = ch; end; return (s); end rot13; -toupper: - procedure (ch) returns (char(1)); - dcl ch char(1); - dcl cout char(1); - if ((ch >= 'a') & (ch <= 'z')) then - cout = ascii(rank(ch) - 32); - else - cout = ch; - return (cout); - end toupper; - -isalpha: - procedure (ch) returns (bit(1)); - dcl ch char(1); - if (((ch >= 'A') & (ch <= 'Z')) | - ((ch >= 'a') & (ch <= 'z'))) then - return (true); - else - return (false); - end isalpha; - - end rot13_test; diff --git a/Task/Rot-13/PascalABC.NET/rot-13.pas b/Task/Rot-13/PascalABC.NET/rot-13.pas new file mode 100644 index 0000000000..5f57c13e01 --- /dev/null +++ b/Task/Rot-13/PascalABC.NET/rot-13.pas @@ -0,0 +1,19 @@ +function Rot13(s: string): string; +begin + var sb := new StringBuilder; + foreach var c in s do + begin + var c1 := c; + if c in 'a'..'z' then + c1 := Chr((c.Code - 'a'.Code + 13) mod 26 + 'a'.Code) + else if c in 'A'..'Z' then + c1 := Chr((c.Code - 'A'.Code + 13) mod 26 + 'A'.Code); + sb.Append(c1) + end; + Result := sb.ToString; +end; + +begin + Println(rot13('foo')); + Println(rot13('sbb')) +end. diff --git a/Task/Rot-13/Pluto/rot-13.pluto b/Task/Rot-13/Pluto/rot-13.pluto new file mode 100644 index 0000000000..38c8e47174 --- /dev/null +++ b/Task/Rot-13/Pluto/rot-13.pluto @@ -0,0 +1,14 @@ +local function rot13(s) + local bytes = {s:byte(1, #s)} + for i = 1, #bytes do + local c = bytes[i] + if (c >= 65 and c <= 77) or (c >= 97 and c <= 109) then + bytes[i] = c + 13 + elseif (c >= 78 and c <= 90) or (c >= 110 and c <= 122) then + bytes[i] = c - 13 + end + end + return string.char(bytes:unpack()) +end + +print(rot13("nowhere ABJURER")) diff --git a/Task/Rot-13/PowerShell/rot-13-1.psh b/Task/Rot-13/PowerShell/rot-13-1.ps1 similarity index 100% rename from Task/Rot-13/PowerShell/rot-13-1.psh rename to Task/Rot-13/PowerShell/rot-13-1.ps1 diff --git a/Task/Rot-13/PowerShell/rot-13-2.psh b/Task/Rot-13/PowerShell/rot-13-2.ps1 similarity index 100% rename from Task/Rot-13/PowerShell/rot-13-2.psh rename to Task/Rot-13/PowerShell/rot-13-2.ps1 diff --git a/Task/Rot-13/PowerShell/rot-13-3.psh b/Task/Rot-13/PowerShell/rot-13-3.ps1 similarity index 100% rename from Task/Rot-13/PowerShell/rot-13-3.psh rename to Task/Rot-13/PowerShell/rot-13-3.ps1 diff --git a/Task/Rot-13/BASIC/rot-13-1.basic b/Task/Rot-13/QBasic/rot-13-1.basic similarity index 100% rename from Task/Rot-13/BASIC/rot-13-1.basic rename to Task/Rot-13/QBasic/rot-13-1.basic diff --git a/Task/Rot-13/BASIC/rot-13-2.basic b/Task/Rot-13/QBasic/rot-13-2.basic similarity index 100% rename from Task/Rot-13/BASIC/rot-13-2.basic rename to Task/Rot-13/QBasic/rot-13-2.basic diff --git a/Task/Rot-13/REBOL/rot-13.rebol b/Task/Rot-13/Rebol/rot-13.rebol similarity index 99% rename from Task/Rot-13/REBOL/rot-13.rebol rename to Task/Rot-13/Rebol/rot-13.rebol index 2049136f22..df118bb69a 100644 --- a/Task/Rot-13/REBOL/rot-13.rebol +++ b/Task/Rot-13/Rebol/rot-13.rebol @@ -1,4 +1,4 @@ -REBOL [ +Rebol [ Title: "Rot-13" URL: http://rosettacode.org/wiki/Rot-13 ] diff --git a/Task/Rot-13/Rhombus/rot-13.rhombus b/Task/Rot-13/Rhombus/rot-13.rhombus new file mode 100644 index 0000000000..590cf6a5dc --- /dev/null +++ b/Task/Rot-13/Rhombus/rot-13.rhombus @@ -0,0 +1,23 @@ +#lang rhombus/static + +import lib("racket/base.rkt") expose: + #{string->list} as string_to_list + #{list->string} as list_to_string + modulo + +fun rot13_char(char :: Char): + let char_int = char.to_int() + fun rot13_by_case(char_int, a_char :: Char) :: Int : + modulo(char_int - a_char.to_int() + 13, 26) + a_char.to_int() + if char.is_alphabetic(): + | if char.is_lowercase(): + | Char.from_int(rot13_by_case(char_int, Char"a")) + | Char.from_int(rot13_by_case(char_int, Char"A")) + | char + +fun rot13_string(str :: String) :: String : + let chars :: PairList = string_to_list(str) + let str :: MutableString = list_to_string(chars.map(rot13_char)) + str.snapshot() + +rot13_string("Hello, World!") // Output: "Uryyb, Jbeyq!"" diff --git a/Task/Rot-13/Rust/rot-13.rust b/Task/Rot-13/Rust/rot-13.rs similarity index 100% rename from Task/Rot-13/Rust/rot-13.rust rename to Task/Rot-13/Rust/rot-13.rs diff --git a/Task/Rot-13/S-BASIC/rot-13.basic b/Task/Rot-13/S-BASIC/rot-13.basic index 2285ebf169..f60275b37d 100644 --- a/Task/Rot-13/S-BASIC/rot-13.basic +++ b/Task/Rot-13/S-BASIC/rot-13.basic @@ -21,7 +21,7 @@ rem - exercise the function var plain, encoded = string -plain = "The quick brown fox jumps over the lazy red dog." +plain = "The quick brown fox jumps over the lazy dog." encoded = rot13(plain) print "Plain text: "; plain print "Encoded : "; encoded diff --git a/Task/Rot-13/Scheme/rot-13-1.ss b/Task/Rot-13/Scheme/rot-13-1.scm similarity index 100% rename from Task/Rot-13/Scheme/rot-13-1.ss rename to Task/Rot-13/Scheme/rot-13-1.scm diff --git a/Task/Rot-13/Scheme/rot-13-2.ss b/Task/Rot-13/Scheme/rot-13-2.scm similarity index 100% rename from Task/Rot-13/Scheme/rot-13-2.ss rename to Task/Rot-13/Scheme/rot-13-2.scm diff --git a/Task/Rot-13/VBScript/rot-13.vb b/Task/Rot-13/VBScript/rot-13.vbs similarity index 100% rename from Task/Rot-13/VBScript/rot-13.vb rename to Task/Rot-13/VBScript/rot-13.vbs diff --git a/Task/Rot-13/X86-64-Assembly/rot-13.x86-64 b/Task/Rot-13/X86-64-Assembly/rot-13.x86-64 new file mode 100644 index 0000000000..7e238b5ce1 --- /dev/null +++ b/Task/Rot-13/X86-64-Assembly/rot-13.x86-64 @@ -0,0 +1,188 @@ +global _start + +section .text + +%define bsize 24 +%define fd(w) qword[filedescriptor + w * 8] +%define sv(w) qword[rsp + w * 8] + +_start: + mov fd(0), -1 + mov fd(1), -1 + pop r15 + cmp r15, 1 + jle .stdio0 + dec r15 + add rsp, 8 + xor r14, r14 + .readcmd: + cmp r14, r15 + jge .checkfd + mov r13, sv(r14) + cmp dword[r13], `-if\0` + je .setif + cmp dword[r13], `-of\0` + je .setof + cmp word[r13], "-h" + je .usage + jmp .readcmd + .stdio0: + mov fd(0), 0 + mov fd(1), 1 + jmp .checkfd + .setif: + xor rax, rax + inc r14 + cmp r14, r15 + je .checkfd + mov rdi, sv(r14) + cmp dword[rdi], "stdi" + je .stif + mov rax, 2 + mov rsi, 0 + mov rdx, 0 + syscall + .stif: + mov fd(0), rax + inc r14 + jmp .readcmd + .setof: + mov rax, 1 + inc r14 + cmp r14, r15 + jge .checkfd + mov rdi, sv(r14) + cmp dword[rdi], "stdo" + je .stof + mov rax, 85 + mov rsi, 0o644 + syscall + .stof: + mov fd(1), rax + inc r14 + jmp .readcmd + .checkfd: + cmp fd(0), -1 + jne .cfd0 + mov fd(0), 0 + .cfd0: + cmp fd(0), -1 + jl .err0 + cmp fd(1), -1 + jne .cfd1 + cmp fd(0), -1 + jl .err1 + mov fd(1), 1 + .cfd1: + .readwrite: + sub rsp, 8 + .read: + xor rax, rax + mov rdi, fd(0) + mov rsi, rsp + mov rdx, 1 + syscall + or rax, rax + jz .close0 + .rot13_: + mov dil, byte[rsp] + call rot13byte + mov qword[rsp], rax + .write: + mov rax, 1 + mov rdi, fd(1) + mov rsi, rsp + mov rdx, 1 + syscall + or rax, rax + js .close0 + jmp .read + .close0: + add rsp, 8 + cmp fd(0), 2 + jle .close1 + mov rax, 3 + mov rdi, fd(0) + syscall + .close1: + cmp fd(1), 2 + jle .exit0 + mov rax, 3 + mov rdi, fd(1) + syscall + .exit0: + mov rax, 60 + mov rdi, 0 + syscall + .usage: + mov rax, 1 + mov rdi, 1 + mov rsi, umsg + mov rdx, endumsg - umsg + syscall + jmp .exit0 + .err0: + mov rax, 1 + mov rdi, 1 + mov rsi, e0 + mov rdx, ende0 - e0 + syscall + jmp .close1 + .err1: + mov rax, 1 + mov rdi, 1 + mov rsi, e1 + mov rdx, ende1 - e1 + syscall + jmp .usage +;------------------------------ +rot13byte: + push rdi + push rdx + push rcx + mov rcx, 26 + mov rax, rdi + .testupper: + cmp dil, 'A' + jl .return0 + cmp dil, 'Z' + jg .testlower + .rotupper: + sub rdi, 'A' + add rdi, 13 + xor rdx, rdx + mov rax, rdi + div rcx + mov rax, rdx + add rax, 'A' + jmp .return0 + .testlower: + cmp dil, 'a' + jl .return0 + cmp dil, 'z' + jg .return0 + .rotlower: + sub rdi, 'a' + add rdi, 13 + xor rdx, rdx + mov rax, rdi + div rcx + mov rax, rdx + add rax, 'a' + .return0: + pop rcx + pop rdx + pop rdi + ret + +section .data +umsg: db "Usage:", 0x0a + db "rot13 [-if input_filename] [-of output_filename]", 0x0a +endumsg: +e0: db "Error opening input file!", 0x0a +ende0: +e1: db "Error opening output file!", 0x0a +ende1: + +section .bss +filedescriptor resq 2 diff --git a/Task/Rot-13/YAMLScript/rot-13.ys b/Task/Rot-13/YAMLScript/rot-13.ys index df274c460b..96b5bcf73e 100644 --- a/Task/Rot-13/YAMLScript/rot-13.ys +++ b/Task/Rot-13/YAMLScript/rot-13.ys @@ -1,7 +1,6 @@ -!yamlscript/v0 +!YS-v0 -s =: set(nil).into('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') -m =: drop(26 s).concat(take(26 s)).zipmap(s _) - -defn main(s): - say: map(\(m %1 %1) s).apply(str _) +defn main(input='Hello, World!'): + s =: set(\\A .. \\Z) + (\\a .. \\z) + say: cycle(s).drop(13 * 2) + .zipmap(s).escape(input) diff --git a/Task/Run-length-encoding/8080-Assembly/run-length-encoding.8080 b/Task/Run-length-encoding/8080-Assembly/run-length-encoding.8080 new file mode 100644 index 0000000000..da3d4f0baa --- /dev/null +++ b/Task/Run-length-encoding/8080-Assembly/run-length-encoding.8080 @@ -0,0 +1,92 @@ + org 100h + jmp demo + + ; Encode 0-terminated string at HL, store at DE +encode: mov a,m + ana a + jz edone + mvi b,1 +escan: inx h + cmp m + jnz ewrite + inr b + jnz escan + dcr b +ewrite: xchg + mov m,b + inx h + mov m,a + inx h + xchg + jmp encode +edone: stax d + ret + + ; Decode 0-terminated string at HL, store at DE +decode: mov a,m + ana a + jz edone + mov b,a + inx h + mov a,m +dwrite: stax d + inx d + dcr b + jnz dwrite + inx h + jmp decode + + ; Show two examples +demo: lxi h,exampl + call show + lxi h,examp2 +show: push h + call puts ; Show start string + lxi h,nl + call puts + pop h + lxi d,buf1 ; Encode string + call encode + lxi h,buf1 ; Show encoded result (as hexadecimal) + call puthex + lxi h,nl + call puts + lxi h,buf1 ; Decode string + lxi d,buf2 + push d + call decode + pop h + call puts ; Show decoded string + lxi h,nl + jmp puts + +nl: db 13,10,0 +exampl: db 'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWW' + db 'WWWWWWWWWWWWWWBWWWWWWWWWWWWWW',0 + + ; Test case with more than 255 repeated items +examp2: db 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' + db 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' + db 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' + db 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' + db 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' + db 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' + db 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' + db 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' + db 'XXXXXXX',0 + + ; Print 0-terminated string at HL +puts: mov a,m! ora a! rz + push h! mvi c,2! mov e,a! call 5! pop h! inx h! jmp puts + + ; Print 0-terminated string at HL as hex +puthex: mov a,m! ora a! rz + push h! call hexout! pop h! inx h! jmp puthex + + ; Print A as hexadecimal +hexout: push psw! rar! rar! rar! rar! call hexlo! pop psw +hexlo: ani 0Fh! cpi 10! jc hexp! adi 7 +hexp: adi '0'! mvi c,2! mov e,a! jmp 5 + +buf1 equ $ +buf2 equ buf1+256 diff --git a/Task/Run-length-encoding/Ada/run-length-encoding.ada b/Task/Run-length-encoding/Ada/run-length-encoding.adb similarity index 100% rename from Task/Run-length-encoding/Ada/run-length-encoding.ada rename to Task/Run-length-encoding/Ada/run-length-encoding.adb diff --git a/Task/Run-length-encoding/Arturo/run-length-encoding.arturo b/Task/Run-length-encoding/Arturo/run-length-encoding.arturo index 591a70f38e..640a8dabb9 100644 --- a/Task/Run-length-encoding/Arturo/run-length-encoding.arturo +++ b/Task/Run-length-encoding/Arturo/run-length-encoding.arturo @@ -5,7 +5,7 @@ runlengthEncode: function [s][ runlengthDecode: function [s][ result: new "" - loop (chunk split s 'x -> positive? size match x {/\d+/}) [a,b] -> + loop (chunk split s 'x -> match? x {/\d+/}) [a,b] -> 'result ++ repeat first b to :integer join to [:string] a return result ] diff --git a/Task/Run-length-encoding/COBOL/run-length-encoding.cobol b/Task/Run-length-encoding/COBOL/run-length-encoding.cob similarity index 100% rename from Task/Run-length-encoding/COBOL/run-length-encoding.cobol rename to Task/Run-length-encoding/COBOL/run-length-encoding.cob diff --git a/Task/Run-length-encoding/Crystal/run-length-encoding.cr b/Task/Run-length-encoding/Crystal/run-length-encoding.cr new file mode 100644 index 0000000000..fa86ef5a3d --- /dev/null +++ b/Task/Run-length-encoding/Crystal/run-length-encoding.cr @@ -0,0 +1,19 @@ +def rlencode (s) + result = Array({Char, Int32}).new + s.scan(/(.)\1*/) do |m| + result << { m[1][0], m[0].size } + end + result +end + +def rldecode (enc) + String.build do |s| + enc.each do |char, length| + s << char.to_s * length + end + end +end + +enc = rlencode("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW") +p enc +puts rldecode(enc) diff --git a/Task/Run-length-encoding/Delphi/run-length-encoding.delphi b/Task/Run-length-encoding/Delphi/run-length-encoding.pas similarity index 100% rename from Task/Run-length-encoding/Delphi/run-length-encoding.delphi rename to Task/Run-length-encoding/Delphi/run-length-encoding.pas diff --git a/Task/Run-length-encoding/DuckDB/run-length-encoding-1.duckdb b/Task/Run-length-encoding/DuckDB/run-length-encoding-1.duckdb new file mode 100644 index 0000000000..f88b7634f0 --- /dev/null +++ b/Task/Run-length-encoding/DuckDB/run-length-encoding-1.duckdb @@ -0,0 +1,23 @@ +create or replace function run_length_encode(str) as table + (WITH RECURSIVE cte AS ( + SELECT + 1 AS pos, + 1 AS counter, + SUBSTRING(str, 1, 1) AS char, + SUBSTRING(str, 2, 1) AS nextc, + UNION ALL + SELECT + pos + 1 as pos, + CASE + WHEN nextc = char THEN counter + 1 + ELSE 1 + END as counter, + nextc as char, + SUBSTRING(str, 2 + pos, 1) as nextc + FROM cte + WHERE pos < LENGTH(str) + ) + SELECT STRING_AGG( counter || char, '' ORDER BY pos) AS encoded_string + FROM cte + WHERE nextc != char + ); diff --git a/Task/Run-length-encoding/DuckDB/run-length-encoding-2.duckdb b/Task/Run-length-encoding/DuckDB/run-length-encoding-2.duckdb new file mode 100644 index 0000000000..15a06b1b33 --- /dev/null +++ b/Task/Run-length-encoding/DuckDB/run-length-encoding-2.duckdb @@ -0,0 +1 @@ +from run_length_encode('WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW'); diff --git a/Task/Run-length-encoding/Ed/run-length-encoding.ed b/Task/Run-length-encoding/Ed/run-length-encoding.ed new file mode 100644 index 0000000000..8c1cdbb36b --- /dev/null +++ b/Task/Run-length-encoding/Ed/run-length-encoding.ed @@ -0,0 +1,21 @@ +H +,p +g/\([a-zA-Z]\)\1\1\1\1\1\1\1\1/s//9\1/g +g/\([a-zA-Z]\)\1\1\1\1\1\1\1/s//8\1/g +g/\([a-zA-Z]\)\1\1\1\1\1\1/s//7\1/g +g/\([a-zA-Z]\)\1\1\1\1\1/s//6\1/g +g/\([a-zA-Z]\)\1\1\1\1/s//5\1/g +g/\([a-zA-Z]\)\1\1\1/s//4\1/g +g/\([a-zA-Z]\)\1\1/s//3\1/g +g/\([a-zA-Z]\)\1/s//2\1/g +,p +g/9\([a-zA-Z]\)/s//\1\1\1\1\1\1\1\1\1/g +g/8\([a-zA-Z]\)/s//\1\1\1\1\1\1\1\1/g +g/7\([a-zA-Z]\)/s//\1\1\1\1\1\1\1/g +g/6\([a-zA-Z]\)/s//\1\1\1\1\1\1/g +g/5\([a-zA-Z]\)/s//\1\1\1\1\1/g +g/4\([a-zA-Z]\)/s//\1\1\1\1/g +g/3\([a-zA-Z]\)/s//\1\1\1/g +g/2\([a-zA-Z]\)/s//\1\1/g +,p +Q diff --git a/Task/Run-length-encoding/Elena/run-length-encoding.elena b/Task/Run-length-encoding/Elena/run-length-encoding.elena index c355ae49b5..402074d6fc 100644 --- a/Task/Run-length-encoding/Elena/run-length-encoding.elena +++ b/Task/Run-length-encoding/Elena/run-length-encoding.elena @@ -3,7 +3,7 @@ import system'routines; import extensions; import extensions'text; -singleton compressor +singleton Compressor { string compress(string s) { @@ -54,13 +54,13 @@ singleton compressor } } -public program() +public Program() { var s := "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"; - s := compressor.compress(s); - console.printLine(s); + s := Compressor.compress(s); + Console.printLine(s); - s := compressor.decompress(s); - console.printLine(s) + s := Compressor.decompress(s); + Console.printLine(s) } diff --git a/Task/Run-length-encoding/Elixir/run-length-encoding.elixir b/Task/Run-length-encoding/Elixir/run-length-encoding.ex similarity index 100% rename from Task/Run-length-encoding/Elixir/run-length-encoding.elixir rename to Task/Run-length-encoding/Elixir/run-length-encoding.ex diff --git a/Task/Run-length-encoding/Emacs-Lisp/run-length-encoding-1.l b/Task/Run-length-encoding/Emacs-Lisp/run-length-encoding-1.el similarity index 100% rename from Task/Run-length-encoding/Emacs-Lisp/run-length-encoding-1.l rename to Task/Run-length-encoding/Emacs-Lisp/run-length-encoding-1.el diff --git a/Task/Run-length-encoding/Emacs-Lisp/run-length-encoding-2.l b/Task/Run-length-encoding/Emacs-Lisp/run-length-encoding-2.el similarity index 100% rename from Task/Run-length-encoding/Emacs-Lisp/run-length-encoding-2.l rename to Task/Run-length-encoding/Emacs-Lisp/run-length-encoding-2.el diff --git a/Task/Run-length-encoding/Euphoria/run-length-encoding.euphoria b/Task/Run-length-encoding/Euphoria/run-length-encoding.eu similarity index 100% rename from Task/Run-length-encoding/Euphoria/run-length-encoding.euphoria rename to Task/Run-length-encoding/Euphoria/run-length-encoding.eu diff --git a/Task/Run-length-encoding/Julia/run-length-encoding.julia b/Task/Run-length-encoding/Julia/run-length-encoding.jl similarity index 100% rename from Task/Run-length-encoding/Julia/run-length-encoding.julia rename to Task/Run-length-encoding/Julia/run-length-encoding.jl diff --git a/Task/Run-length-encoding/Kotlin/run-length-encoding.kotlin b/Task/Run-length-encoding/Kotlin/run-length-encoding.kts similarity index 100% rename from Task/Run-length-encoding/Kotlin/run-length-encoding.kotlin rename to Task/Run-length-encoding/Kotlin/run-length-encoding.kts diff --git a/Task/Run-length-encoding/MACRO-11/run-length-encoding.macro11 b/Task/Run-length-encoding/MACRO-11/run-length-encoding.macro11 new file mode 100644 index 0000000000..2ed4a2f8e3 --- /dev/null +++ b/Task/Run-length-encoding/MACRO-11/run-length-encoding.macro11 @@ -0,0 +1,106 @@ + .TITLE RLE + .MCALL .TTYOUT,.EXIT +RLE:: JMP DEMO + + ; ENCODE 0-TERMINATED STRING AT (R0), STORE AT (R1) +ENCODE: MOVB (R0),R2 + BEQ 3$ + MOVB #1,R3 +1$: INC R0 + CMPB (R0),R2 + BNE 2$ + INCB R3 + BNE 1$ + DECB R3 +2$: MOVB R3,(R1)+ + MOVB R2,(R1)+ + BR ENCODE +3$: CLRB (R1) + RTS PC + + ; DECODE 0-TERMINATED STRING AT (R0), STORE AT (R1) +DECODE: MOVB (R0)+,R2 + BEQ 2$ + MOVB (R0)+,R3 + BIC #^C377,R2 +1$: MOVB R3,(R1)+ + SOB R2,1$ + BR DECODE +2$: CLRB (R1) + RTS PC + + ; TESTS +DEMO: MOV #TEST1,R5 + JSR PC,1$ + MOV #TEST2,R5 + JSR PC,1$ + .EXIT +1$: MOV R5,R1 + JSR PC,PRINT + MOV #NL,R1 + JSR PC,PRINT + MOV R5,R0 + MOV #BUFR1,R1 + JSR PC,ENCODE + MOV #BUFR1,R1 + JSR PC,PRHEXS + MOV #NL,R1 + JSR PC,PRINT + MOV #BUFR1,R0 + MOV #BUFR2,R1 + JSR PC,DECODE + MOV #BUFR2,R1 + JSR PC,PRINT + MOV #NL,R1 + JSR PC,PRINT + RTS PC + +NL: .BYTE 15,12,0 + +TEST1: .ASCII /WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWW/ + .ASCIZ /WWWWWWWWWWWWWWBWWWWWWWWWWWWWW/ + +TEST2: .ASCII /XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/ + .ASCII /XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/ + .ASCII /XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/ + .ASCII /XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/ + .ASCII /XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/ + .ASCII /XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/ + .ASCII /XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/ + .ASCII /XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/ + .ASCIZ /XXXXXXX/ + + .EVEN + + ; PRINT STRING AT R1 +PRINT: MOVB (R1)+,R0 + .TTYOUT + BNE PRINT + RTS PC + + ; PRINT HEX BYTE R0 +PRHEXB: MOV R0,-(SP) + ROR R0 + ROR R0 + ROR R0 + ROR R0 + JSR PC,1$ + MOV (SP)+,R0 +1$: BIC #^C17,R0 + CMP R0,#^D10 + BLO 2$ + ADD #7,R0 +2$: ADD #'0,R0 + .TTYOUT + RTS PC + + ; PRINT HEX STRING R1 +PRHEXS: MOVB (R1)+,R0 + BEQ 1$ + JSR PC,PRHEXB + BR PRHEXS +1$: RTS PC + +BUFR1: .BLKB 400 +BUFR2: .BLKB 400 + .END RLE diff --git a/Task/Run-length-encoding/Miranda/run-length-encoding.miranda b/Task/Run-length-encoding/Miranda/run-length-encoding.miranda new file mode 100644 index 0000000000..4d3a554df9 --- /dev/null +++ b/Task/Run-length-encoding/Miranda/run-length-encoding.miranda @@ -0,0 +1,18 @@ +main :: [sys_message] +main = [Stdout (lay [inp, show enc, dec])] + where inp = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" + enc = rlencode inp + dec = rldecode enc + +rlencode :: [*]->[(num,*)] +rlencode xs = [(#p, hd p) | p <- chunk xs] + +rldecode :: [(num,*)]->[*] +rldecode xs = concat [take n (repeat x) | (n,x) <- xs] + +chunk :: [*]->[[*]] +chunk = f [] + where f acc [] = [acc] + f [] (a:as) = f [a] as + f (a:acc) (a:as) = f (a:a:acc) as + f acc (a:as) = acc:f [a] as diff --git a/Task/Run-length-encoding/NewLISP/run-length-encoding.l b/Task/Run-length-encoding/NewLISP/run-length-encoding.l new file mode 100644 index 0000000000..137828395e --- /dev/null +++ b/Task/Run-length-encoding/NewLISP/run-length-encoding.l @@ -0,0 +1,46 @@ +;; Since newLISP has dynamic scope, use a namespace or context +;; to avoid variable capture. +(context 'monotonic-slices) + +(define (monotonic-slices:monotonic-slices lst (key-func or) (cmp =)) + (let (result '() tmp '() old-key 0 new-key 0) + (dolist (x lst) + (set 'new-key (key-func x)) + (cond ((empty? tmp) (push x tmp)) + ((cmp new-key old-key) (push x tmp)) + (true (push (reverse tmp) result) (set 'tmp (list x)))) + (set 'old-key new-key)) + (unless (empty? tmp) (push (reverse tmp) result)) + (reverse result))) + +(context MAIN) + +(monotonic-slices '(0 0 2 3 3 3 4 5 5 5 5) ) + +((0 0) (2) (3 3 3) (4) (5 5 5 5)) + + +(define (compress str) + (apply string (flat + (map + (fn (xs) (list (length xs) (first xs))) + (monotonic-slices (explode str)))))) + +(compress + "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW") + +"12W1B12W3B24W1B14W" + + +(define (decompress str) + (apply ;; Use for fold or reduce. + (fn (built a b) (push (dup (b 0) (int (join a))) built -1)) + (cons "" + (monotonic-slices + (explode str) + (fn (c) (<= "0" c "9")))) + 3)) + +(decompress "12W1B12W3B24W1B14W") + +"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" diff --git a/Task/Run-length-encoding/OCaml/run-length-encoding-1.ocaml b/Task/Run-length-encoding/OCaml/run-length-encoding-1.ml similarity index 100% rename from Task/Run-length-encoding/OCaml/run-length-encoding-1.ocaml rename to Task/Run-length-encoding/OCaml/run-length-encoding-1.ml diff --git a/Task/Run-length-encoding/OCaml/run-length-encoding-2.ocaml b/Task/Run-length-encoding/OCaml/run-length-encoding-2.ml similarity index 100% rename from Task/Run-length-encoding/OCaml/run-length-encoding-2.ocaml rename to Task/Run-length-encoding/OCaml/run-length-encoding-2.ml diff --git a/Task/Run-length-encoding/OCaml/run-length-encoding-3.ocaml b/Task/Run-length-encoding/OCaml/run-length-encoding-3.ml similarity index 100% rename from Task/Run-length-encoding/OCaml/run-length-encoding-3.ocaml rename to Task/Run-length-encoding/OCaml/run-length-encoding-3.ml diff --git a/Task/Run-length-encoding/PowerShell/run-length-encoding.psh b/Task/Run-length-encoding/PowerShell/run-length-encoding.ps1 similarity index 100% rename from Task/Run-length-encoding/PowerShell/run-length-encoding.psh rename to Task/Run-length-encoding/PowerShell/run-length-encoding.ps1 diff --git a/Task/Run-length-encoding/Refal/run-length-encoding.refal b/Task/Run-length-encoding/Refal/run-length-encoding.refal new file mode 100644 index 0000000000..6174153b19 --- /dev/null +++ b/Task/Run-length-encoding/Refal/run-length-encoding.refal @@ -0,0 +1,44 @@ +$ENTRY Go { + , >: e.In + , >: e.Enc + = >; +}; + +Example { + = 'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW'; +}; + +RLEncode { + e.X = >; +}; + +RLDecode { + e.X = >; +}; + +Count { + e.X, : s.L s.C e.Y = s.L s.C; +}; + +Repeat { + 0 s.C = ; + s.N s.C = s.C s.C>; +}; + +Each { + (e.F) = ; + (e.F) (e.X) e.Y = () ; +}; + +Chunk { + = ; + (e.I) = (e.I); + (e.I t.I) t.I e.X = ; + (e.I) t.J e.X = (e.I) ; + t.I e.X = ; +}; + +Concat { + = ; + (e.X) e.Y = e.X ; +}; diff --git a/Task/Run-length-encoding/Rust/run-length-encoding.rust b/Task/Run-length-encoding/Rust/run-length-encoding.rs similarity index 100% rename from Task/Run-length-encoding/Rust/run-length-encoding.rust rename to Task/Run-length-encoding/Rust/run-length-encoding.rs diff --git a/Task/Run-length-encoding/Scheme/run-length-encoding.ss b/Task/Run-length-encoding/Scheme/run-length-encoding.scm similarity index 100% rename from Task/Run-length-encoding/Scheme/run-length-encoding.ss rename to Task/Run-length-encoding/Scheme/run-length-encoding.scm diff --git a/Task/Run-length-encoding/Uiua/run-length-encoding.uiua b/Task/Run-length-encoding/Uiua/run-length-encoding.uiua new file mode 100644 index 0000000000..746acb25e2 --- /dev/null +++ b/Task/Run-length-encoding/Uiua/run-length-encoding.uiua @@ -0,0 +1,7 @@ +# Run Length Encoding and Decoding + +Rle ← ⌅( + /◇⊂⍚⊂°⋕°▽ +| ▽⊃⊜⋕(♭⊜∘¬)⊸∊+@0⇡10) +"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" +&p⨬("oops"|"good")≍⊸&p°Rle⊸&p⊸Rle⊸&p diff --git a/Task/Runge-Kutta-method/00-TASK.txt b/Task/Runge-Kutta-method/00-TASK.txt index eafc75a430..a961c26a39 100644 --- a/Task/Runge-Kutta-method/00-TASK.txt +++ b/Task/Runge-Kutta-method/00-TASK.txt @@ -1,5 +1,5 @@ Given the example Differential equation: -:y'(t) = t \times \sqrt {y(t)} +:y'(t) = t \cdot \sqrt {y(t)} With initial condition: :t_0 = 0 and y_0 = y(t_0) = y(0) = 1 This equation has an exact solution: @@ -14,10 +14,10 @@ Demonstrate the commonly used explicit   [[wp:Runge–Kutta_methods#Common_ ;Method summary Starting with a given y_n and t_n calculate: -:\delta y_1 = \delta t\times y'(t_n, y_n)\quad -:\delta y_2 = \delta t\times y'(t_n + \tfrac{1}{2}\delta t , y_n + \tfrac{1}{2}\delta y_1) -:\delta y_3 = \delta t\times y'(t_n + \tfrac{1}{2}\delta t , y_n + \tfrac{1}{2}\delta y_2) -:\delta y_4 = \delta t\times y'(t_n + \delta t , y_n + \delta y_3)\quad +:\delta y_1 = \delta t\cdot y'(t_n, y_n)\quad +:\delta y_2 = \delta t\cdot y'(t_n + \tfrac{1}{2}\delta t , y_n + \tfrac{1}{2}\delta y_1) +:\delta y_3 = \delta t\cdot y'(t_n + \tfrac{1}{2}\delta t , y_n + \tfrac{1}{2}\delta y_2) +:\delta y_4 = \delta t\cdot y'(t_n + \delta t , y_n + \delta y_3)\quad then: :y_{n+1} = y_n + \tfrac{1}{6} (\delta y_1 + 2\delta y_2 + 2\delta y_3 + \delta y_4) :t_{n+1} = t_n + \delta t\quad diff --git a/Task/Runge-Kutta-method/Ada/runge-kutta-method.ada b/Task/Runge-Kutta-method/Ada/runge-kutta-method.adb similarity index 100% rename from Task/Runge-Kutta-method/Ada/runge-kutta-method.ada rename to Task/Runge-Kutta-method/Ada/runge-kutta-method.adb diff --git a/Task/Runge-Kutta-method/Crystal/runge-kutta-method.crystal b/Task/Runge-Kutta-method/Crystal/runge-kutta-method.cr similarity index 100% rename from Task/Runge-Kutta-method/Crystal/runge-kutta-method.crystal rename to Task/Runge-Kutta-method/Crystal/runge-kutta-method.cr diff --git a/Task/Runge-Kutta-method/EasyLang/runge-kutta-method.easy b/Task/Runge-Kutta-method/EasyLang/runge-kutta-method.easy index 4b0cc9de38..89fb62f249 100644 --- a/Task/Runge-Kutta-method/EasyLang/runge-kutta-method.easy +++ b/Task/Runge-Kutta-method/EasyLang/runge-kutta-method.easy @@ -1,4 +1,4 @@ -numfmt 6 0 +numfmt 0 6 y = 1 for i = 0 to 100 t = i / 10 diff --git a/Task/Runge-Kutta-method/Julia/runge-kutta-method-1.julia b/Task/Runge-Kutta-method/Julia/runge-kutta-method-1.jl similarity index 100% rename from Task/Runge-Kutta-method/Julia/runge-kutta-method-1.julia rename to Task/Runge-Kutta-method/Julia/runge-kutta-method-1.jl diff --git a/Task/Runge-Kutta-method/Julia/runge-kutta-method-2.julia b/Task/Runge-Kutta-method/Julia/runge-kutta-method-2.jl similarity index 100% rename from Task/Runge-Kutta-method/Julia/runge-kutta-method-2.julia rename to Task/Runge-Kutta-method/Julia/runge-kutta-method-2.jl diff --git a/Task/Runge-Kutta-method/Kotlin/runge-kutta-method.kotlin b/Task/Runge-Kutta-method/Kotlin/runge-kutta-method.kts similarity index 100% rename from Task/Runge-Kutta-method/Kotlin/runge-kutta-method.kotlin rename to Task/Runge-Kutta-method/Kotlin/runge-kutta-method.kts diff --git a/Task/Runge-Kutta-method/OCaml/runge-kutta-method.ocaml b/Task/Runge-Kutta-method/OCaml/runge-kutta-method.ml similarity index 100% rename from Task/Runge-Kutta-method/OCaml/runge-kutta-method.ocaml rename to Task/Runge-Kutta-method/OCaml/runge-kutta-method.ml diff --git a/Task/Runge-Kutta-method/Odin/runge-kutta-method.odin b/Task/Runge-Kutta-method/Odin/runge-kutta-method.odin new file mode 100644 index 0000000000..bc3b88a13d --- /dev/null +++ b/Task/Runge-Kutta-method/Odin/runge-kutta-method.odin @@ -0,0 +1,37 @@ +package runge_kutta + +import "core:fmt" +import "core:math" + +func :: proc(x: f32, y: f32) -> f32 { + return x * math.sqrt(y) +} + +main :: proc() { + STEPS :: 100 + sols: [STEPS + 1]f32 + + x0, y0, h := f32(0.0), f32(1.0), f32(0.1) + xn, yn := x0, y0 + + sols[0] = y0 + factor := f32(1.0 / 6.0) + + for &sol in sols[1:] { + dy1 := h * func(xn,yn) + dy2 := h * func(xn + 0.5 * h, yn + 0.5 * dy1) + dy3 := h * func(xn + 0.5 * h, yn + 0.5 * dy2) + dy4 := h * func(xn + h, yn + dy3) + sol = yn + factor * (dy1 + 2 * dy2 + 2 * dy3 + dy4) + yn = sol + xn = xn + h + } + + for i in 1.. t * math.sqrt(yt) +runge_kutta4(0, 10, 0.1, y, yd) diff --git a/Task/Runge-Kutta-method/PowerShell/runge-kutta-method.psh b/Task/Runge-Kutta-method/PowerShell/runge-kutta-method.ps1 similarity index 100% rename from Task/Runge-Kutta-method/PowerShell/runge-kutta-method.psh rename to Task/Runge-Kutta-method/PowerShell/runge-kutta-method.ps1 diff --git a/Task/Runge-Kutta-method/REXX/runge-kutta-method.rexx b/Task/Runge-Kutta-method/REXX/runge-kutta-method.rexx index 9d04f0a647..453ddd75a2 100644 --- a/Task/Runge-Kutta-method/REXX/runge-kutta-method.rexx +++ b/Task/Runge-Kutta-method/REXX/runge-kutta-method.rexx @@ -1,28 +1,54 @@ -/*REXX program uses the Runge─Kutta method to solve the equation: y'(t) = t² √[y(t)] */ -numeric digits 40; f= digits() % 4 /*use 40 decimal digs, but only show 10*/ -x0= 0; x1= 10; dx= .1 /*define variables: X0 X1 DX */ -n=1 + (x1-x0) / dx -y.=1; do m=1 for n-1; p= m - 1; y.m= RK4(dx, x0 + dx*p, y.p) - end /*m*/ /* [↑] use 4th order Runge─Kutta. */ -w= digits() % 2 /*W: width used for displaying numbers.*/ -say center('X', f, "═") center('Y', w+2, "═") center("relative error", w+8, '═') /*hdr*/ +-- 25 Apr 2026 +include Setting +numeric digits 16 - do i=0 to n-1 by 10; x= (x0 + dx*i) / 1; $= y.i / (x*x/4+1)**2 - 1 - say center(x, f) fmt(y.i) left('', 2 + ($>=0) ) fmt($) - end /*i*/ /*└┴┴┴───◄─────── aligns positive #'s. */ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -fmt: parse arg z; z= right( format(z, w, f), w); hasE= pos('E', z)>0; has.= pos(., z)>0 - jus= has. & \hasE; T= 'T'; if jus then z= left( strip( strip(z, T, 0), T, .), w) - return translate( right(z, (z>=0) + w + 5*hasE + 2*(jus & (z<0) ) ), 'e', "E") -/*──────────────────────────────────────────────────────────────────────────────────────*/ -RK4: procedure; parse arg dx,x,y; dxH= dx/2; k1= dx * (x ) * sqrt(y ) - k2= dx * (x + dxH) * sqrt(y + k1/2) - k3= dx * (x + dxH) * sqrt(y + k2/2) - k4= dx * (x + dx ) * sqrt(y + k3 ) - return y + (k1 + k2*2 + k3*2 + k4) / 6 -/*──────────────────────────────────────────────────────────────────────────────────────*/ -sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); m.=9; numeric form; h=d+6 - numeric digits; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g * .5'e'_ % 2 - do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ - do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/; return g +say "RUNGE-KUTTA METHOD FOR ODE y'=x*Sqrt(y)" +say version +say +call Task 0,10,1,1 +call Task 0,10,1/10,1 +call Task 0,10,1/100,1 +exit + +Task: +-- Runge-Kutta method +procedure expose Memo. +arg x0,xn,dx,y0 +say 'From' x0 'to' xn 'step' dx +say ' x Calc y True y Abs err Rel err' +x=x0; y=y0 +do until x > xn + if Integer(x) then + call Show x,y + dy1=dx*Dy(x,y) + dy2=dx*Dy(x+dx/2,y+dy1/2) + dy3=dx*Dy(x+dx/2,y+dy2/2) + dy4=dx*Dy(x+dx,y+dy3) + x+=dx; y+=(dy1+2*dy2+2*dy3+dy4)/6 +end +say +return + +Show: +-- Display a line +procedure +arg xx,yy +yt=True(xx) +say Format(xx,2,0) Format(yy,3,7) Format(True(xx),3,7), + Left(Std(Abs(yy-True(xx))),10) Left(Std(Abs(yy/True(xx)-1)),10) +return + +Dy: +-- Differential equation +procedure expose Memo. +arg xx,yy +return xx*SqRt(yy) + +True: +-- Real solution +procedure +arg xx +return (xx**2+4)**2/16 + +-- Integer; Std; Sqrt +include Math diff --git a/Task/Runge-Kutta-method/Rust/runge-kutta-method.rust b/Task/Runge-Kutta-method/Rust/runge-kutta-method.rs similarity index 100% rename from Task/Runge-Kutta-method/Rust/runge-kutta-method.rust rename to Task/Runge-Kutta-method/Rust/runge-kutta-method.rs diff --git a/Task/Runge-Kutta-method/Scheme/runge-kutta-method.scm b/Task/Runge-Kutta-method/Scheme/runge-kutta-method.scm new file mode 100644 index 0000000000..eac1f7a466 --- /dev/null +++ b/Task/Runge-Kutta-method/Scheme/runge-kutta-method.scm @@ -0,0 +1,54 @@ +(define (func x y) + (* x (sqrt y)) +) + +(define (exact x) + (* (/ 1.0 16.0) (expt (+ (expt x 2) 4) 2) ) +) + +(define steps 101) + + +(define h 0.1) +(define x0 0.0) +(define y0 1.0) + + +(define factor (/ 1.0 6.0)) + +(define (rk x y step sol) + (let* + ( + (dy1 (* h (func x y))) + (dy2 (* h (func (+ x (* 0.5 h )) (+ y (* 0.5 dy1 )) ))) + (dy3 (* h (func (+ x (* 0.5 h )) (+ y (* 0.5 dy2 )) ))) + (dy4 (* h (func (+ h x) (+ y dy3) ))) + (ynone (+ y (* factor (apply + (list dy1 (* 2 dy2) (* 2 dy3) dy4 ) ) )) ) + (sol (reverse (cons ynone sol))) + (step (+ 1 step)) + ) + (cond + ( + (equal? 0 (modulo step 10)) + (display "solution: ") + (display ynone) + (display " exact: ") + (display (exact (+ x h))) + (display " error: ") + (display (abs (- y (exact x)))) + (newline) + ) + + ) + (if (< step steps) + (rk (+ x h) ynone step sol ) + (reverse (cons y0 (reverse sol))) + ) + + ) +) + +(display "start: ") +(display y0) +(newline) +(define solution (rk x0 y0 0 '())) diff --git a/Task/Runtime-evaluation-In-an-environment/Elena/runtime-evaluation-in-an-environment.elena b/Task/Runtime-evaluation-In-an-environment/Elena/runtime-evaluation-in-an-environment.elena index 037f3bd346..b644352cea 100644 --- a/Task/Runtime-evaluation-In-an-environment/Elena/runtime-evaluation-in-an-environment.elena +++ b/Task/Runtime-evaluation-In-an-environment/Elena/runtime-evaluation-in-an-environment.elena @@ -1,12 +1,12 @@ import extensions; import extensions'scripting; -public program() +public Program() { - var text := program_arguments[1]; - var arg := program_arguments[2]; + var text := Program_arguments[1]; + var arg := Program_arguments[2]; - var program := lscript.interpretLine(text); - console.printLine( + var program := LScript.interpretLine(text); + Console.printLine( text,",",arg," = ",program.eval(arg.toReal())); } diff --git a/Task/Runtime-evaluation-In-an-environment/FreeBASIC/runtime-evaluation-in-an-environment.basic b/Task/Runtime-evaluation-In-an-environment/FreeBASIC/runtime-evaluation-in-an-environment.basic new file mode 100644 index 0000000000..8380944173 --- /dev/null +++ b/Task/Runtime-evaluation-In-an-environment/FreeBASIC/runtime-evaluation-in-an-environment.basic @@ -0,0 +1,10 @@ +#include "solver.bi" + +Dim As String expression = "(x ^ 2 )-7" + +setVar("x",1.2) +Print "one = ";Solver(expression) +setVar("x",3.4) +Print "two = ";Solver(expression) + +Sleep diff --git a/Task/Runtime-evaluation-In-an-environment/Julia/runtime-evaluation-in-an-environment-1.julia b/Task/Runtime-evaluation-In-an-environment/Julia/runtime-evaluation-in-an-environment-1.jl similarity index 100% rename from Task/Runtime-evaluation-In-an-environment/Julia/runtime-evaluation-in-an-environment-1.julia rename to Task/Runtime-evaluation-In-an-environment/Julia/runtime-evaluation-in-an-environment-1.jl diff --git a/Task/Runtime-evaluation-In-an-environment/Julia/runtime-evaluation-in-an-environment-2.julia b/Task/Runtime-evaluation-In-an-environment/Julia/runtime-evaluation-in-an-environment-2.jl similarity index 100% rename from Task/Runtime-evaluation-In-an-environment/Julia/runtime-evaluation-in-an-environment-2.julia rename to Task/Runtime-evaluation-In-an-environment/Julia/runtime-evaluation-in-an-environment-2.jl diff --git a/Task/Runtime-evaluation-In-an-environment/Kotlin/runtime-evaluation-in-an-environment.kotlin b/Task/Runtime-evaluation-In-an-environment/Kotlin/runtime-evaluation-in-an-environment.kts similarity index 100% rename from Task/Runtime-evaluation-In-an-environment/Kotlin/runtime-evaluation-in-an-environment.kotlin rename to Task/Runtime-evaluation-In-an-environment/Kotlin/runtime-evaluation-in-an-environment.kts diff --git a/Task/Runtime-evaluation-In-an-environment/REBOL/runtime-evaluation-in-an-environment.rebol b/Task/Runtime-evaluation-In-an-environment/Rebol/runtime-evaluation-in-an-environment.rebol similarity index 100% rename from Task/Runtime-evaluation-In-an-environment/REBOL/runtime-evaluation-in-an-environment.rebol rename to Task/Runtime-evaluation-In-an-environment/Rebol/runtime-evaluation-in-an-environment.rebol diff --git a/Task/Runtime-evaluation-In-an-environment/Red/runtime-evaluation-in-an-environment.red b/Task/Runtime-evaluation-In-an-environment/Red/runtime-evaluation-in-an-environment.red new file mode 100644 index 0000000000..e33642ca01 --- /dev/null +++ b/Task/Runtime-evaluation-In-an-environment/Red/runtime-evaluation-in-an-environment.red @@ -0,0 +1,26 @@ +Red [ + Title: "Runtime evaluation/in an environment" + Author: "hinjolicious" +] + +; a simple but generic lambda function +; multi-args lambda +; save it or directly evaluate + +lambda: func [a b /eval v /local f][ + f: func a b + either eval [do compose [f (v)]][:f] +] + +prog: [x * x + x - 10] +a: lambda/eval [x] prog [2] +b: lambda/eval [x] prog [4] +print b - a + +code: [a * b / (a + b)] +c: lambda/eval [a b] code [2 3] +d: lambda/eval [a b] code [3 4] +print d - c + +my-func: lambda [x y z][x + y + z] +print my-func 10 20 30 diff --git a/Task/Runtime-evaluation-In-an-environment/Scheme/runtime-evaluation-in-an-environment.ss b/Task/Runtime-evaluation-In-an-environment/Scheme/runtime-evaluation-in-an-environment.scm similarity index 100% rename from Task/Runtime-evaluation-In-an-environment/Scheme/runtime-evaluation-in-an-environment.ss rename to Task/Runtime-evaluation-In-an-environment/Scheme/runtime-evaluation-in-an-environment.scm diff --git a/Task/Runtime-evaluation/Elena/runtime-evaluation.elena b/Task/Runtime-evaluation/Elena/runtime-evaluation.elena index 2f3b9414e3..6d30718681 100644 --- a/Task/Runtime-evaluation/Elena/runtime-evaluation.elena +++ b/Task/Runtime-evaluation/Elena/runtime-evaluation.elena @@ -2,5 +2,5 @@ import extensions'scripting; public program() { - lscript.interpretLine("system'console.writeLine(""Hello World"")"); + LScript.interpretLine("system'console.writeLine(""Hello World"")"); } diff --git a/Task/Runtime-evaluation/Elixir/runtime-evaluation.elixir b/Task/Runtime-evaluation/Elixir/runtime-evaluation.ex similarity index 100% rename from Task/Runtime-evaluation/Elixir/runtime-evaluation.elixir rename to Task/Runtime-evaluation/Elixir/runtime-evaluation.ex diff --git a/Task/Runtime-evaluation/Julia/runtime-evaluation-1.julia b/Task/Runtime-evaluation/Julia/runtime-evaluation-1.jl similarity index 100% rename from Task/Runtime-evaluation/Julia/runtime-evaluation-1.julia rename to Task/Runtime-evaluation/Julia/runtime-evaluation-1.jl diff --git a/Task/Runtime-evaluation/Julia/runtime-evaluation-2.julia b/Task/Runtime-evaluation/Julia/runtime-evaluation-2.jl similarity index 100% rename from Task/Runtime-evaluation/Julia/runtime-evaluation-2.julia rename to Task/Runtime-evaluation/Julia/runtime-evaluation-2.jl diff --git a/Task/Runtime-evaluation/PowerShell/runtime-evaluation-1.psh b/Task/Runtime-evaluation/PowerShell/runtime-evaluation-1.ps1 similarity index 100% rename from Task/Runtime-evaluation/PowerShell/runtime-evaluation-1.psh rename to Task/Runtime-evaluation/PowerShell/runtime-evaluation-1.ps1 diff --git a/Task/Runtime-evaluation/PowerShell/runtime-evaluation-2.psh b/Task/Runtime-evaluation/PowerShell/runtime-evaluation-2.ps1 similarity index 100% rename from Task/Runtime-evaluation/PowerShell/runtime-evaluation-2.psh rename to Task/Runtime-evaluation/PowerShell/runtime-evaluation-2.ps1 diff --git a/Task/Runtime-evaluation/PowerShell/runtime-evaluation-3.psh b/Task/Runtime-evaluation/PowerShell/runtime-evaluation-3.ps1 similarity index 100% rename from Task/Runtime-evaluation/PowerShell/runtime-evaluation-3.psh rename to Task/Runtime-evaluation/PowerShell/runtime-evaluation-3.ps1 diff --git a/Task/Runtime-evaluation/PowerShell/runtime-evaluation-4.psh b/Task/Runtime-evaluation/PowerShell/runtime-evaluation-4.ps1 similarity index 100% rename from Task/Runtime-evaluation/PowerShell/runtime-evaluation-4.psh rename to Task/Runtime-evaluation/PowerShell/runtime-evaluation-4.ps1 diff --git a/Task/Runtime-evaluation/PowerShell/runtime-evaluation-5.psh b/Task/Runtime-evaluation/PowerShell/runtime-evaluation-5.ps1 similarity index 100% rename from Task/Runtime-evaluation/PowerShell/runtime-evaluation-5.psh rename to Task/Runtime-evaluation/PowerShell/runtime-evaluation-5.ps1 diff --git a/Task/Runtime-evaluation/PowerShell/runtime-evaluation-6.psh b/Task/Runtime-evaluation/PowerShell/runtime-evaluation-6.ps1 similarity index 100% rename from Task/Runtime-evaluation/PowerShell/runtime-evaluation-6.psh rename to Task/Runtime-evaluation/PowerShell/runtime-evaluation-6.ps1 diff --git a/Task/Runtime-evaluation/REBOL/runtime-evaluation.rebol b/Task/Runtime-evaluation/Rebol/runtime-evaluation.rebol similarity index 100% rename from Task/Runtime-evaluation/REBOL/runtime-evaluation.rebol rename to Task/Runtime-evaluation/Rebol/runtime-evaluation.rebol diff --git a/Task/Runtime-evaluation/Scheme/runtime-evaluation.ss b/Task/Runtime-evaluation/Scheme/runtime-evaluation.scm similarity index 100% rename from Task/Runtime-evaluation/Scheme/runtime-evaluation.ss rename to Task/Runtime-evaluation/Scheme/runtime-evaluation.scm diff --git a/Task/Ruth-Aaron-numbers/Delphi/ruth-aaron-numbers.delphi b/Task/Ruth-Aaron-numbers/Delphi/ruth-aaron-numbers.pas similarity index 100% rename from Task/Ruth-Aaron-numbers/Delphi/ruth-aaron-numbers.delphi rename to Task/Ruth-Aaron-numbers/Delphi/ruth-aaron-numbers.pas diff --git a/Task/Ruth-Aaron-numbers/EasyLang/ruth-aaron-numbers.easy b/Task/Ruth-Aaron-numbers/EasyLang/ruth-aaron-numbers.easy new file mode 100644 index 0000000000..070eb3b085 --- /dev/null +++ b/Task/Ruth-Aaron-numbers/EasyLang/ruth-aaron-numbers.easy @@ -0,0 +1,40 @@ +fastfunc divsum n alldiv . + f = 2 + repeat + q = n / f + if n mod f = 0 + if alldiv = 1 + s1 += f + else + if f <> f0 + s1 += f + f0 = f + . + . + n = q + else + f += 1 + . + until f > n + . + return s1 +. +proc ruth_aaron alldiv . + n = 2 + repeat + s = divsum n alldiv + if s = s0 + write n - 1 & " " + c += 1 + . + s0 = s + n += 1 + until c >= 30 + . + print "" +. +print "first 30 ruth-aaron numbers (factors):" +ruth_aaron 1 +print "" +print "first 30 ruth-aaron numbers (divisors):" +ruth_aaron 0 diff --git a/Task/Ruth-Aaron-numbers/Java/ruth-aaron-numbers.java b/Task/Ruth-Aaron-numbers/Java/ruth-aaron-numbers.java index 699eabf065..ad560d1dff 100644 --- a/Task/Ruth-Aaron-numbers/Java/ruth-aaron-numbers.java +++ b/Task/Ruth-Aaron-numbers/Java/ruth-aaron-numbers.java @@ -16,7 +16,8 @@ public final class RuthAaronNumbers { System.out.println("First Ruth-Aaron triple (factors): " + firstRuthAaronTriple(NumberType.FACTOR)); System.out.println(); - System.out.println("First Ruth-Aaron triple (divisors): " + firstRuthAaronTriple(NumberType.DIVISOR)); + System.out.println("First Ruth-Aaron triple (divisors): " + + firstRuthAaronTriple(NumberType.DIVISOR)); System.out.println(); } diff --git a/Task/Ruth-Aaron-numbers/Julia/ruth-aaron-numbers.julia b/Task/Ruth-Aaron-numbers/Julia/ruth-aaron-numbers.jl similarity index 100% rename from Task/Ruth-Aaron-numbers/Julia/ruth-aaron-numbers.julia rename to Task/Ruth-Aaron-numbers/Julia/ruth-aaron-numbers.jl diff --git a/Task/Ruth-Aaron-numbers/Python/ruth-aaron-numbers.py b/Task/Ruth-Aaron-numbers/Python/ruth-aaron-numbers.py new file mode 100644 index 0000000000..16ea510fb8 --- /dev/null +++ b/Task/Ruth-Aaron-numbers/Python/ruth-aaron-numbers.py @@ -0,0 +1,104 @@ +from collections import deque +from itertools import count +from itertools import islice +from pprint import pprint +from typing import Iterable +from typing import Iterator +from typing import TypeVar + + +def prime_factors(n: int) -> Iterator[int]: + """Return the prime factors of 'n' in order using a wheel with basis [2, 3, 5]. + + Translation of `primeFactors` from https://rosettacode.org/wiki/Category_talk:Wren-math. + """ + if n < 2: + return + + inc = [4, 2, 4, 2, 4, 6, 2, 6] + + while n % 2 == 0: + yield 2 + n //= 2 + + while n % 3 == 0: + yield 3 + n //= 3 + + while n % 5 == 0: + yield 5 + n //= 5 + + k = 7 + i = 0 + + while k * k <= n: + if n % k == 0: + yield k + n //= k + else: + k += inc[i] + i = (i + 1) % 8 + + if n > 1: + yield n + + +_T = TypeVar("_T") + + +def sliding_window(it: Iterable[_T], n: int) -> Iterator[tuple[_T, ...]]: + it = iter(it) + window = deque(islice(it, n - 1), maxlen=n) + for x in it: + window.append(x) + yield tuple(window) + + +def ruth_aaron_numbers_factors() -> Iterator[int]: + for (i, a), (_, b) in sliding_window( + ((n, sum(prime_factors(n))) for n in count(2)), 2 + ): + if a == b: + yield i + + +def ruth_aaron_numbers_divisors() -> Iterator[int]: + for (i, a), (_, b) in sliding_window( + ((n, sum(set(prime_factors(n)))) for n in count(2)), 2 + ): + if a == b: + yield i + + +def ruth_aaron_triples_factors() -> Iterator[int]: + for (i, a), (_, b), (_, c) in sliding_window( + ((n, sum(prime_factors(n))) for n in count(2)), 3 + ): + if a == b == c: + yield i + + +def ruth_aaron_triples_divisors() -> Iterator[int]: + for (i, a), (_, b), (_, c) in sliding_window( + ((n, sum(set(prime_factors(n)))) for n in count(2)), 3 + ): + if a == b == c: + yield i + + +if __name__ == "__main__": + print("First 30 Ruth-Aaron numbers (factors):") + pprint(list(islice(ruth_aaron_numbers_factors(), 30)), compact=True) + print("") + + print("First 30 Ruth-Aaron numbers (divisors):") + pprint(list(islice(ruth_aaron_numbers_divisors(), 30)), compact=True) + print("") + + print("First Ruth-Aaron triple (factors):") + print(next(ruth_aaron_triples_factors())) + print("") + + print("First Ruth-Aaron triple (divisors):") + print(next(ruth_aaron_triples_divisors())) diff --git a/Task/Ruth-Aaron-numbers/Uiua/ruth-aaron-numbers.uiua b/Task/Ruth-Aaron-numbers/Uiua/ruth-aaron-numbers.uiua new file mode 100644 index 0000000000..b0df3eb74c --- /dev/null +++ b/Task/Ruth-Aaron-numbers/Uiua/ruth-aaron-numbers.uiua @@ -0,0 +1,8 @@ +Primes ← ≡(□°/×) +RAs! ← ≡◇/×▽⧈=⊸≡◇^0 +RATs! ← ≡◇/×▽⧈₃(=1⧻◴)⊸≡◇^0 +Fs ← /+ +Ds ← /+◴ +∩↙₃₀⊃(RAs!Ds|RAs!Fs)Primes↘2⇡50000 +⊢RATs!Fs Primes↘2⇡500000 +⊢RATs!Ds Primes↘89400000⇡89500000 # Short-circuit a tedious wait :-) diff --git a/Task/S-expressions/ALGOL-68/s-expressions.alg b/Task/S-expressions/ALGOL-68/s-expressions.alg index cb5dae63bc..331b3a3884 100644 --- a/Task/S-expressions/ALGOL-68/s-expressions.alg +++ b/Task/S-expressions/ALGOL-68/s-expressions.alg @@ -95,18 +95,18 @@ PROC s reader = ( STRING s )REF SEXPR: PROC s writer = ( REF SEXPR s expr )VOID: BEGIN # prints an S expression with a suitable indent # - PROC print indented s expression = ( REF SEXPR s expr, INT indent )VOID: + PROC print indented s expression = ( REF SEXPR s expression, INT indent )VOID: BEGIN - REF SEXPR s pos := s expr; + REF SEXPR s pos := s expression; WHILE REF SEXPR( s pos ) ISNT REF SEXPR( NIL ) DO - FOR i TO indent DO print( ( " " ) ) OD; + TO indent DO print( ( " " ) ) OD; CASE element OF s pos IN (VOID ): print( ( "()", newline ) ) , (STRING s): print( ( s, newline ) ) , (REF SEXPR e): BEGIN print( ( "(", newline ) ); print indented s expression( e, indent + 4 ); - FOR i TO indent DO print( ( " " ) ) OD; + TO indent DO print( ( " " ) ) OD; print( ( ")", newline ) ) END OUT diff --git a/Task/S-expressions/Ada/s-expressions-1.ada b/Task/S-expressions/Ada/s-expressions-1.adb similarity index 100% rename from Task/S-expressions/Ada/s-expressions-1.ada rename to Task/S-expressions/Ada/s-expressions-1.adb diff --git a/Task/S-expressions/Ada/s-expressions-2.ada b/Task/S-expressions/Ada/s-expressions-2.adb similarity index 100% rename from Task/S-expressions/Ada/s-expressions-2.ada rename to Task/S-expressions/Ada/s-expressions-2.adb diff --git a/Task/S-expressions/Ada/s-expressions-3.ada b/Task/S-expressions/Ada/s-expressions-3.adb similarity index 100% rename from Task/S-expressions/Ada/s-expressions-3.ada rename to Task/S-expressions/Ada/s-expressions-3.adb diff --git a/Task/S-expressions/Ada/s-expressions-4.ada b/Task/S-expressions/Ada/s-expressions-4.adb similarity index 100% rename from Task/S-expressions/Ada/s-expressions-4.ada rename to Task/S-expressions/Ada/s-expressions-4.adb diff --git a/Task/S-expressions/Ada/s-expressions-5.ada b/Task/S-expressions/Ada/s-expressions-5.adb similarity index 100% rename from Task/S-expressions/Ada/s-expressions-5.ada rename to Task/S-expressions/Ada/s-expressions-5.adb diff --git a/Task/S-expressions/Arturo/s-expressions.arturo b/Task/S-expressions/Arturo/s-expressions.arturo index c2f01fabbf..13300be347 100644 --- a/Task/S-expressions/Arturo/s-expressions.arturo +++ b/Task/S-expressions/Arturo/s-expressions.arturo @@ -5,4 +5,4 @@ code: { s: first to :block code inspect.muted s -print as.code s +print express s diff --git a/Task/S-expressions/FreeBASIC/s-expressions.basic b/Task/S-expressions/FreeBASIC/s-expressions.basic new file mode 100644 index 0000000000..693f6544f2 --- /dev/null +++ b/Task/S-expressions/FreeBASIC/s-expressions.basic @@ -0,0 +1,132 @@ +Type Token + tokenType As Integer '1=lbr, 2=rbr, 3=string, 4=number, 5=symbol + value As String + numValue As Double +End Type + +Type TokenList + tokens(1000) As Token + cnt As Integer +End Type + +Function isNumber(word As String) As Boolean + For i As Integer = 1 To Len(word) + If (Mid(word, i, 1) < "0" Or Mid(word, i, 1) > "9") And Mid(word, i, 1) <> "." Then Return False + Next + Return True +End Function + +Function ParseSExpr(cad As String) As TokenList + Dim As TokenList tlist + Dim As Integer state = 1 '1=token_start, 2=read_quoted_string, 3=read_string_or_number + Dim As String word = "" + + For i As Integer = 1 To Len(cad) + Select Case state + Case 1 'token_start + Select Case Mid(cad, i, 1) + Case "(" + tlist.tokens(tlist.cnt).tokenType = 1 + tlist.cnt += 1 + Case ")" + tlist.tokens(tlist.cnt).tokenType = 2 + tlist.cnt += 1 + Case " ", Chr(9), Chr(10), Chr(13) + Case """" + state = 2 : word = "" + Case Else + state = 3 : word = Mid(cad, i, 1) + End Select + + Case 2 'read_quoted_string + If Mid(cad, i, 1) = """" Then + tlist.tokens(tlist.cnt).tokenType = 3 + tlist.tokens(tlist.cnt).value = word + tlist.cnt += 1 + state = 1 + Else + word &= Mid(cad, i, 1) + End If + + Case 3 'read_string_or_number + If Instr(" " & Chr(9) & Chr(10) & Chr(13) & ")", Mid(cad, i, 1)) Then + tlist.tokens(tlist.cnt).tokenType = Iif(isNumber(word), 4, 5) + If isNumber(word) Then + tlist.tokens(tlist.cnt).numValue = Val(word) + Else + tlist.tokens(tlist.cnt).value = word + End If + tlist.cnt += 1 + If Mid(cad, i, 1) = ")" Then + tlist.tokens(tlist.cnt).tokenType = 2 + tlist.cnt += 1 + End If + state = 1 + Else + word &= Mid(cad, i, 1) + End If + End Select + Next + Return tlist +End Function + +Function ArrayToString(tlist As TokenList, startIdx As Integer, Byref endIdx As Integer) As String + Dim As String result = "" + Dim As Integer i = startIdx + + If startIdx = 0 Then result = "[" + + While i < tlist.cnt + Select Case tlist.tokens(i).tokenType + Case 1 'lbr + result &= "[" + i += 1 + result &= ArrayToString(tlist, i, i) + Case 2 'rbr + endIdx = i + Return result & "]" + Case 3 'string + result &= """" & tlist.tokens(i).value & """" + Case 4 'number + result &= Rtrim(Str(tlist.tokens(i).numValue)) + Case 5 'symbol + result &= ":" & tlist.tokens(i).value + End Select + If i < tlist.cnt - 1 Andalso tlist.tokens(i+1).tokenType <> 2 Then result &= ", " + i += 1 + Wend + Return result +End Function + +Function ToSExpr(tlist As TokenList) As String + Dim As String result = "" + For i As Integer = 0 To tlist.cnt - 1 + Select Case tlist.tokens(i).tokenType + Case 1: result &= "(" + Case 2: result &= ")" + Case 3: result &= """" & tlist.tokens(i).value & """" + Case 4: result &= Rtrim(Str(tlist.tokens(i).numValue)) + Case 5: result &= tlist.tokens(i).value + End Select + If i < tlist.cnt - 1 Andalso tlist.tokens(i+1).tokenType <> 2 Andalso tlist.tokens(i).tokenType <> 1 Then result &= " " + Next + Return result +End Function + +' Main program +Dim As String inputString = _ +"((data ""quoted data"" 123 4.5)" & Chr(10) & _ +" (data (!@# (4.5) ""(more"" ""data)"")))" + +Print "Original S-Expression:" +Print inputString +Dim As TokenList tokens = ParseSExpr(inputString) + +Print !"\nNative Structure:" +Dim As Integer dummy +Print ArrayToString(tokens, 0, dummy) + +Print !"\nand back to S-Expression:" +Print ToSExpr(tokens) + +Sleep diff --git a/Task/S-expressions/Julia/s-expressions.julia b/Task/S-expressions/Julia/s-expressions.jl similarity index 100% rename from Task/S-expressions/Julia/s-expressions.julia rename to Task/S-expressions/Julia/s-expressions.jl diff --git a/Task/S-expressions/Kotlin/s-expressions.kotlin b/Task/S-expressions/Kotlin/s-expressions.kts similarity index 100% rename from Task/S-expressions/Kotlin/s-expressions.kotlin rename to Task/S-expressions/Kotlin/s-expressions.kts diff --git a/Task/S-expressions/OCaml/s-expressions-1.ocaml b/Task/S-expressions/OCaml/s-expressions-1.ml similarity index 100% rename from Task/S-expressions/OCaml/s-expressions-1.ocaml rename to Task/S-expressions/OCaml/s-expressions-1.ml diff --git a/Task/S-expressions/OCaml/s-expressions-2.ocaml b/Task/S-expressions/OCaml/s-expressions-2.ml similarity index 100% rename from Task/S-expressions/OCaml/s-expressions-2.ocaml rename to Task/S-expressions/OCaml/s-expressions-2.ml diff --git a/Task/S-expressions/Rust/s-expressions.rust b/Task/S-expressions/Rust/s-expressions.rs similarity index 100% rename from Task/S-expressions/Rust/s-expressions.rust rename to Task/S-expressions/Rust/s-expressions.rs diff --git a/Task/S-expressions/Scheme/s-expressions.ss b/Task/S-expressions/Scheme/s-expressions.scm similarity index 100% rename from Task/S-expressions/Scheme/s-expressions.ss rename to Task/S-expressions/Scheme/s-expressions.scm diff --git a/Task/SEDOLs/Ada/sedols.ada b/Task/SEDOLs/Ada/sedols.adb similarity index 100% rename from Task/SEDOLs/Ada/sedols.ada rename to Task/SEDOLs/Ada/sedols.adb diff --git a/Task/SEDOLs/Arturo/sedols.arturo b/Task/SEDOLs/Arturo/sedols.arturo index fbb11d850a..fc092a60f6 100644 --- a/Task/SEDOLs/Arturo/sedols.arturo +++ b/Task/SEDOLs/Arturo/sedols.arturo @@ -1,15 +1,15 @@ -ord0: to :integer `0` -ord7: to :integer `7` +ord0: to :integer '0' +ord7: to :integer '7' c2v: function [c][ ordC: to :integer c - if? c < `A` -> return ordC - ord0 - else -> return ordC - ord7 + switch c < 'A' -> return ordC - ord0 + -> return ordC - ord7 ] weight: [1 3 1 7 3 9] checksum: function [sedol][ - val: new 0 + val: 0 loop .with:'i sedol 'ch -> 'val + weight\[i] * c2v ch return to :char ord0 + (10 - val % 10) % 10 diff --git a/Task/SEDOLs/COBOL/sedols.cobol b/Task/SEDOLs/COBOL/sedols.cob similarity index 100% rename from Task/SEDOLs/COBOL/sedols.cobol rename to Task/SEDOLs/COBOL/sedols.cob diff --git a/Task/SEDOLs/D/sedols-2.d b/Task/SEDOLs/D/sedols-2.d index 893475b6e7..97f1b57311 100644 --- a/Task/SEDOLs/D/sedols-2.d +++ b/Task/SEDOLs/D/sedols-2.d @@ -1,6 +1,6 @@ import std.stdio, std.algorithm, std.string, std.numeric, std.ascii; -char sedolChecksum(in char[] sedol) pure nothrow @safe /*@nogc*/ +char sedolChecksum(in char[] sedol) pure @safe /*@nogc*/ in { assert(sedol.length == 6, "SEDOL must be 6 chars long."); enum uint mask = 0b11_1110_1111_1011_1110_1110_1110; @@ -16,7 +16,7 @@ in { } immutable int d = sedol.map!c2v.dotProduct([1, 3, 1, 7, 3, 9]); assert((d + result - '0') % 10 == 0); -} body { +} do { static immutable int[] weights = [1, 3, 1, 7, 3, 9]; int sum = 0; diff --git a/Task/SEDOLs/Delphi/sedols.delphi b/Task/SEDOLs/Delphi/sedols.pas similarity index 100% rename from Task/SEDOLs/Delphi/sedols.delphi rename to Task/SEDOLs/Delphi/sedols.pas diff --git a/Task/SEDOLs/Elixir/sedols.elixir b/Task/SEDOLs/Elixir/sedols.ex similarity index 100% rename from Task/SEDOLs/Elixir/sedols.elixir rename to Task/SEDOLs/Elixir/sedols.ex diff --git a/Task/SEDOLs/FutureBasic/sedols.basic b/Task/SEDOLs/FutureBasic/sedols.basic new file mode 100644 index 0000000000..66ed08fb69 --- /dev/null +++ b/Task/SEDOLs/FutureBasic/sedols.basic @@ -0,0 +1,35 @@ +local fn Checksum( s as CFStringRef ) as CFStringRef + CFStringRef v = @"0123456789-BCD-FGH-JKLMN-PQRST-VWXYZ", w = @"131739" + long i, sum = 0 + for i = 0 to len(s) - 1 + CFRange r = fn StringRangeOfString( v, mid(s,i,1) ) + if ( r.location == NSNotFound ) then return NULL + sum += r.location * intval(mid(w,i,1)) + next +end fn = concat( s, @((10 - (sum % 10)) % 10) ) + +void local fn DoIt + CFArrayRef sedols = @[ + @"710889", + @"B0YBKJ", + @"406566", + @"B0YBLH", + @"228276", + @"B0YBKL", + @"557910", + @"B0YBKR", + @"585284", + @"B0YBKT", + @"B00030", + @"ABCDEF"] + CFStringRef sedol + for sedol in sedols + CFStringRef s = fn Checksum( sedol ) + if ( s ) then print s : continue + print @"Invalid" + next +end fn + +fn DoIt + +HandleEvents diff --git a/Task/SEDOLs/Julia/sedols.jl b/Task/SEDOLs/Julia/sedols.jl new file mode 100644 index 0000000000..95e29d1c52 --- /dev/null +++ b/Task/SEDOLs/Julia/sedols.jl @@ -0,0 +1,20 @@ +using Test + +isalnum(c::Char) = isletter(c) || isnumeric(c) + +function appendchecksum(s::AbstractString) + !all(isalnum, s) && throw(ArgumentError("invalid SEDOL number '$s'")) + + weights = [1, 3, 1, 7, 3, 9, 1] + checksum = sum(weights[i] * parse(Int, s[i], base = 36) for i in eachindex(s)) + return s * string((10 - checksum % 10) % 10) +end + +tests = ["710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "B00030"] +csums = ["7108899", "B0YBKJ7", "4065663", "B0YBLH2", "2282765", "B0YBKL9", "5579107", "B0YBKR5", "5852842", "B0YBKT7", "B000300"] + +@testset "Checksums" begin + for (t, c) in zip(tests, csums) + @test appendchecksum(t) == c + end +end diff --git a/Task/SEDOLs/Julia/sedols.julia b/Task/SEDOLs/Julia/sedols.julia deleted file mode 100644 index 57ebe59d57..0000000000 --- a/Task/SEDOLs/Julia/sedols.julia +++ /dev/null @@ -1,21 +0,0 @@ -using Base.Test - -function appendchecksum(chars::AbstractString) - if !all(isalnum, chars) throw(ArgumentError("invalid SEDOL number '$chars'")) end - weights = [1, 3, 1, 7, 3, 9, 1] - - s = 0 - for (w, c) in zip(weights, chars) - s += w * parse(Int, c, 36) - end - return string(chars, (10 - s % 10) % 10) -end - -tests = ["710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "B00030"] -csums = ["7108899", "B0YBKJ7", "4065663", "B0YBLH2", "2282765", "B0YBKL9", "5579107", "B0YBKR5", "5852842", "B0YBKT7", "B000300"] - -@testset "Checksums" begin - for (t, c) in zip(tests, csums) - @test appendchecksum(t) == c - end -end diff --git a/Task/SEDOLs/Kotlin/sedols.kotlin b/Task/SEDOLs/Kotlin/sedols.kts similarity index 100% rename from Task/SEDOLs/Kotlin/sedols.kotlin rename to Task/SEDOLs/Kotlin/sedols.kts diff --git a/Task/SEDOLs/Langur/sedols.langur b/Task/SEDOLs/Langur/sedols.langur index ce5b39d4a1..df0c67a995 100644 --- a/Task/SEDOLs/Langur/sedols.langur +++ b/Task/SEDOLs/Langur/sedols.langur @@ -1,26 +1,26 @@ -val .csd = fn(.code) { - switch len(.code) { +val csd = fn(code) { + switch len(code) { case 0: return "nada, zip, zilch" case != 6: return "invalid length" } - if .code -> re/[^B-DF-HJ-NP-TV-Z0-9]/ { + if code -> re/[^B-DF-HJ-NP-TV-Z0-9]/ { return "invalid character(s)" } - val .weight = [1,3,1,7,3,9] + val weight = [1,3,1,7,3,9] - val .nums = s2n .code - val .sum = for[=0] .i of .nums { - _for += .nums[.i] * .weight[.i] + val nums = s2n(code) + val sum = for[=0] i of nums { + _for += nums[i] * weight[i] } - string 9 - (.sum - 1) rem 10 + string 9 - (sum - 1) rem 10 } -val .h = h{ +val h = { # invalid... "": 0, "123": 0, @@ -45,14 +45,14 @@ val .h = h{ "B00030": 0, } -for .input in sort(keys .h) { - val .d = .csd(.input) - if len(.d) > 1 { - writeln .input, ": ", .d +for input in sort(keys(h)) { + val d = csd(input) + if len(d) > 1 { + writeln input, ": ", d } else { - val .expect = string .h[.input] - write .input, .d - writeln if .expect == .d {""} else { - $" (SEDOL test failed; expected check digit \.expect;)"} + val expect = h[input] -> string + write input, d + writeln if expect == d {""} else { + " (SEDOL test failed; expected check digit {{expect}})"} } } diff --git a/Task/SEDOLs/OCaml/sedols.ocaml b/Task/SEDOLs/OCaml/sedols.ml similarity index 100% rename from Task/SEDOLs/OCaml/sedols.ocaml rename to Task/SEDOLs/OCaml/sedols.ml diff --git a/Task/SEDOLs/PHP/sedols.php b/Task/SEDOLs/PHP/sedols.php index 301bb30b94..e67bb580ad 100644 --- a/Task/SEDOLs/PHP/sedols.php +++ b/Task/SEDOLs/PHP/sedols.php @@ -1,26 +1,41 @@ -function char2value($c) { + - type string6(object s) - return string(s) and length(s)=6 - end type +with javascript_semantics +constant cmap = reinstate(reinstate(reinstate(repeat(-1,255), + tagset('9','0'),tagset(9,0)), + tagset('Z','B'),tagset(35,11)),"EIOU",-1) - type sedolch(integer ch) - return ch>='0' and ch<='Z' and (ch<='9' or ch>='A') and not find(ch,"AEIOU") - end type +function sedol(string t) + string s = filter(t,"out","-") + integer l = length(s) + string res = "invalid length" + if l=6 or l=7 then + sequence e = extract(cmap,s[1..6]) + if find(-1,e) then + res = "invalid char" + elsif e[1]<=9 and max(e)>9 then + res = "no letters when starts with number" + else + integer n = sum(sq_mul(e,{1,3,1,7,3,9})), + ch = mod(10-mod(n,10),10)+'0' + res = iff(l=7 ? "invalid checksum"[iff(ch=s[7]?3:1)..$] : t&ch) + end if + end if + return res +end function - function sedol(string6 t) - sedolch c - integer s = 0 - for i=1 to 6 do - c = t[i] - s += iff(c>='A'?c-'A'+10:c-'0')*{1,3,1,7,3,9}[i] - end for - return t & mod(10-mod(s,10),10)+'0' - end function - - constant tests = {"710889", - "B0YBKJ", - "406566", - "B0YBLH", - "228276", - "B0YBKL", - "557910", - "B0YBKR", - "585284", - "B0YBKT", - "B00030"} - for i=1 to length(tests) do - ?sedol(tests[i]) - end for - + sdigit(S1), sdigit(S2), sdigit(S3), sdigit(S4), sdigit(S5), sdigit(S6), sdigit(S7), + { S7 in 0..9, + (S1 + S2 * 3 + S3 + S4 * 7 + S5 * 3 + S6 * 9 + S7) mod 10 #= 0 + }. + +sdigit(Value) --> [Code], + { Value in 0..35, + Code in 48..57\/66..68\/70..72\/74..78\/80..84\/86..90, + Code in 48..57 #<==> Value #= Code - 48, + Code in 66..90 #<==> Value #= Code - 55 + }. + +add_checksum_digit(SEDOL6, SEDOL7) :- + append(SEDOL6, [_], SEDOL7), + phrase(sedol, SEDOL7), + once(label(SEDOL7)). + +% adds the checksum digits to each number and removes any invalid numbers +task(SEDOL6s) :- + convlist(add_checksum_digit, SEDOL6s, SEDOL7s), + foreach(member(SEDOL7, SEDOL7s), format("~s~n", [SEDOL7])). + +?- task([ + "710889", + "B0YBKJ", + "406566", + "B0YBLH", + "228276", + "B0YBKL", + "557910", + "B0YBKR", + "585284", + "B0YBKT", + "BOYBKT", % Ill formed test case - illegal vowel. + "B00030" + ]). diff --git a/Task/SEDOLs/Prolog/sedols-2.pro b/Task/SEDOLs/Prolog/sedols-2.pro new file mode 100644 index 0000000000..c08bcdfb76 --- /dev/null +++ b/Task/SEDOLs/Prolog/sedols-2.pro @@ -0,0 +1,5 @@ +?- SEDOL = [0'7, _, 0'0, 0'8, 0'8, 0'9, 0'9], phrase(sedol, SEDOL), label(SEDOL). +SEDOL = "7108899" ; +SEDOL = "7B08899" ; +SEDOL = "7L08899" ; +SEDOL = "7V08899". diff --git a/Task/SEDOLs/Prolog/sedols-3.pro b/Task/SEDOLs/Prolog/sedols-3.pro new file mode 100644 index 0000000000..ad9ef5772c --- /dev/null +++ b/Task/SEDOLs/Prolog/sedols-3.pro @@ -0,0 +1,21 @@ +?- phrase(sedol, SEDOL), label(SEDOL). +SEDOL = "0000000" ; +SEDOL = "0000011" ; +SEDOL = "0000022" ; +SEDOL = "0000033" ; +SEDOL = "0000044" ; +SEDOL = "0000055" ; +SEDOL = "0000066" ; +SEDOL = "0000077" ; +SEDOL = "0000088" ; +SEDOL = "0000099" ; +SEDOL = "00000B1" ; +SEDOL = "00000C2" ; +SEDOL = "00000D3" ; +SEDOL = "00000F5" ; +SEDOL = "00000G6" ; +SEDOL = "00000H7" ; +SEDOL = "00000J9" ; +SEDOL = "00000K0" ; +SEDOL = "00000L1" ; +SEDOL = "00000M2" . % etc... diff --git a/Task/SEDOLs/Python/sedols-1.py b/Task/SEDOLs/Python/sedols-1.py index c7400948ae..8c6498f9b8 100644 --- a/Task/SEDOLs/Python/sedols-1.py +++ b/Task/SEDOLs/Python/sedols-1.py @@ -22,4 +22,4 @@ for sedol in ''' 585284 B0YBKT '''.split(): - print sedol + checksum(sedol) + print (sedol + checksum(sedol)) diff --git a/Task/SEDOLs/Rust/sedols.rust b/Task/SEDOLs/Rust/sedols.rs similarity index 100% rename from Task/SEDOLs/Rust/sedols.rust rename to Task/SEDOLs/Rust/sedols.rs diff --git a/Task/SEDOLs/V-(Vlang)/sedols.v b/Task/SEDOLs/V-(Vlang)/sedols.v new file mode 100644 index 0000000000..cdef49d14d --- /dev/null +++ b/Task/SEDOLs/V-(Vlang)/sedols.v @@ -0,0 +1,25 @@ +import strconv + +const weights = [1, 3, 1, 7, 3, 9, 1] + +fn main() { + sedol6s := [ + "710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", + "557910", "B0YBKR", "585284", "B0YBKT", "B00030", "1234567890", + "B000301", "A00000", "12🦊", "β0003", "A00030"] + for sedol6 in sedol6s { println("${sedol6} -> ${sedol7(sedol6) or {continue}}") } +} + +fn sedol7(sedol6 string) !string { + mut sum, mut check := 0, 0 + if sedol6.len != 6 { return "'Incorrect length!'" } + for i, c in sedol6 { + if !c.is_alnum() || c.ascii_str().is_lower() + || c.ascii_str() in ["A", "E", "I", "O", "U"] { return "'Illegal character!'" } + digit := strconv.common_parse_int(c.ascii_str(), 36, 0, true, true) or + { return "'Invalid conversion!'" } + sum += int(digit) * weights[i] + } + check = (10 - (sum % 10)) % 10 + return "${sedol6}" + "${check.str()}" +} diff --git a/Task/SEDOLs/VBScript/sedols.vb b/Task/SEDOLs/VBScript/sedols.vbs similarity index 100% rename from Task/SEDOLs/VBScript/sedols.vb rename to Task/SEDOLs/VBScript/sedols.vbs diff --git a/Task/SHA-1/Ada/sha-1.ada b/Task/SHA-1/Ada/sha-1.adb similarity index 100% rename from Task/SHA-1/Ada/sha-1.ada rename to Task/SHA-1/Ada/sha-1.adb diff --git a/Task/SHA-1/Batch-File/sha-1.bat b/Task/SHA-1/Batch-File/sha-1.bat new file mode 100644 index 0000000000..5351bd5dc7 --- /dev/null +++ b/Task/SHA-1/Batch-File/sha-1.bat @@ -0,0 +1,8 @@ +@echo off +setlocal enableextensions +set /p str= +pushd "%temp%" + "%str%" +certutil -hashfile "%str%" +del "%str%" +pause diff --git a/Task/SHA-1/C++/sha-1-2.cpp b/Task/SHA-1/C++/sha-1-2.cpp index 5efd04ae81..c0697e96ba 100644 --- a/Task/SHA-1/C++/sha-1-2.cpp +++ b/Task/SHA-1/C++/sha-1-2.cpp @@ -8,67 +8,67 @@ class SHA1 { public: - std::string message_digest(const std::string& message) { - std::vector state = { 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 }; + std::string message_digest(const std::string& message) { + std::vector state = { 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 }; - const std::vector bytes = add_padding(message); - for ( uint64_t i = 0; i < bytes.size() / BLOCK_LENGTH; ++i ) { - std::vector values(80, 0); - for ( uint32_t j = 0; j < BLOCK_LENGTH; ++j ) { - values[j / 4] |= ( bytes[i * BLOCK_LENGTH + j] & 0xff ) << ( ( 3 - j % 4 ) * 8 ); - } - for ( uint32_t j = 16; j < 80; ++j ) { - uint32_t value = values[j - 3] ^ values[j - 8] ^ values[j - 14] ^ values[j - 16]; - values[j] = std::rotl(value, 1); - } + const std::vector bytes = add_padding(message); + for ( uint64_t i = 0; i < bytes.size() / BLOCK_LENGTH; ++i ) { + std::vector values(80, 0); + for ( uint32_t j = 0; j < BLOCK_LENGTH; ++j ) { + values[j / 4] |= ( bytes[i * BLOCK_LENGTH + j] & 0xff ) << ( ( 3 - j % 4 ) * 8 ); + } + for ( uint32_t j = 16; j < 80; ++j ) { + uint32_t value = values[j - 3] ^ values[j - 8] ^ values[j - 14] ^ values[j - 16]; + values[j] = std::rotl(value, 1); + } - uint32_t a = state[0], b = state[1], c = state[2], d = state[3], e = state[4]; - uint32_t f = 0, k = 0; - for ( uint32_t j = 0; j < 80; ++j ) { - switch ( j / 20 ) { - case 0 : { f = ( b & c ) | ( ~b & d ); k = 0x5a827999; break; } - case 1 : { f = b ^ c ^ d; k = 0x6ed9eba1; break; } - case 2 : { f = ( b & c ) | ( b & d ) | ( c & d ); k = 0x8f1bbcdc; break; } - case 3 : { f = b ^ c ^ d; k = 0xca62c1d6; break; } - } + uint32_t a = state[0], b = state[1], c = state[2], d = state[3], e = state[4]; + uint32_t f = 0, k = 0; + for ( uint32_t j = 0; j < 80; ++j ) { + switch ( j / 20 ) { + case 0 : { f = ( b & c ) | ( ~b & d ); k = 0x5a827999; break; } + case 1 : { f = b ^ c ^ d; k = 0x6ed9eba1; break; } + case 2 : { f = ( b & c ) | ( b & d ) | ( c & d ); k = 0x8f1bbcdc; break; } + case 3 : { f = b ^ c ^ d; k = 0xca62c1d6; break; } + } - uint32_t temp = std::rotl(a, 5) + f + e + k + values[j]; - e = d; d = c; c = std::rotl(b, 30); b = a; a = temp; - } + uint32_t temp = std::rotl(a, 5) + f + e + k + values[j]; + e = d; d = c; c = std::rotl(b, 30); b = a; a = temp; + } - state[0] += a; state[1] += b; state[2] += c; state[3] += d; state[4] += e; - } + state[0] += a; state[1] += b; state[2] += c; state[3] += d; state[4] += e; + } - std::stringstream stream; - for ( uint32_t i = 0; i < 20; ++i ) { - int8_t byte_value = static_cast(state[i / 4] >> ( 24 - ( i % 4 ) * 8)); - stream << std::setfill('0') << std::setw(2) << std::hex << ( byte_value & 0xff ); - } - return stream.str(); - } + std::stringstream stream; + for ( uint32_t i = 0; i < 20; ++i ) { + int8_t byte_value = static_cast(state[i / 4] >> ( 24 - ( i % 4 ) * 8)); + stream << std::setfill('0') << std::setw(2) << std::hex << ( byte_value & 0xff ); + } + return stream.str(); + } private: - std::vector add_padding(const std::string& message) { - std::vector bytes(message.begin(), message.end()); - bytes.emplace_back(static_cast(0x80)); + std::vector add_padding(const std::string& message) { + std::vector bytes(message.begin(), message.end()); + bytes.emplace_back(static_cast(0x80)); - uint32_t padding = BLOCK_LENGTH - ( bytes.size() % BLOCK_LENGTH ); - if ( padding < 8 ) { - padding += BLOCK_LENGTH; - } - bytes.resize(bytes.size() + padding - 8, static_cast(0x0)); + uint32_t padding = BLOCK_LENGTH - ( bytes.size() % BLOCK_LENGTH ); + if ( padding < 8 ) { + padding += BLOCK_LENGTH; + } + bytes.resize(bytes.size() + padding - 8, static_cast(0x0)); - const uint64_t bit_length = 8 * message.length(); - for ( int32_t i = 7; i >= 0; --i ) { - bytes.emplace_back(static_cast(bit_length >> ( 8 * i ))); - } - return bytes; - } + const uint64_t bit_length = 8 * message.length(); + for ( int32_t i = 7; i >= 0; --i ) { + bytes.emplace_back(static_cast(bit_length >> ( 8 * i ))); + } + return bytes; + } - const uint32_t BLOCK_LENGTH = 64; + const uint32_t BLOCK_LENGTH = 64; }; int main() { - SHA1 sha1; - std::cout << sha1.message_digest("Rosetta Code") << std::endl; + SHA1 sha1; + std::cout << sha1.message_digest("Rosetta Code") << std::endl; } diff --git a/Task/SHA-1/Crystal/sha-1.crystal b/Task/SHA-1/Crystal/sha-1.cr similarity index 100% rename from Task/SHA-1/Crystal/sha-1.crystal rename to Task/SHA-1/Crystal/sha-1.cr diff --git a/Task/SHA-1/Delphi/sha-1.delphi b/Task/SHA-1/Delphi/sha-1.pas similarity index 100% rename from Task/SHA-1/Delphi/sha-1.delphi rename to Task/SHA-1/Delphi/sha-1.pas diff --git a/Task/SHA-1/EasyLang/sha-1.easy b/Task/SHA-1/EasyLang/sha-1.easy new file mode 100644 index 0000000000..5a39abb4ed --- /dev/null +++ b/Task/SHA-1/EasyLang/sha-1.easy @@ -0,0 +1,96 @@ +func u32 x . + return bitand x 0xFFFFFFFF +. +func rol x s . + left = u32 bitshift x s + right = bitshift u32 x -(32 - s) + return bitor left right +. +func be32 b0 b1 b2 b3 . + return b0 * 16777216 + b1 * 65536 + b2 * 256 + b3 +. +func$ word2hex w . + for k = 0 to 3 + w = rol w 8 + h = w mod 256 + for c in [ h div 16 h mod 16 ] + c += 48 + if c >= 58 : c += 39 + hex$ &= strchar c + . + . + return hex$ +. +func[] str2bytes s$ . + for ch$ in strchars s$ : out[] &= strcode ch$ + return out[] +. +proc sha1pad &data[] . + n = len data[] * 8 + data[] &= 0x80 + while len data[] mod 64 <> 56 : data[] &= 0x00 + for i = 1 to 8 + tmp[] &= n mod 256 + n = n div 256 + . + for i = 1 to 8 : data[] &= tmp[9 - i] +. +proc sha1block &H0 &H1 &H2 &H3 &H4 blk[] . + for i = 0 to 15 + b0 = blk[i * 4 + 1] + b1 = blk[i * 4 + 2] + b2 = blk[i * 4 + 3] + b3 = blk[i * 4 + 4] + W[] &= be32 b0 b1 b2 b3 + . + for t = 17 to 80 + tmp = bitxor W[t - 3] W[t - 8] + tmp = bitxor tmp W[t - 14] + tmp = bitxor tmp W[t - 16] + W[] &= rol u32 tmp 1 + . + a = H0 ; b = H1 ; c = H2 ; d = H3 ; e = H4 + for t = 1 to 80 + if t <= 20 + f = bitor (bitand b c) (bitand (bitnot b) d) + K = 0x5A827999 + elif t <= 40 + f = bitxor (bitxor b c) d + K = 0x6ED9EBA1 + elif t <= 60 + f = bitor (bitor (bitand b c) (bitand b d)) (bitand c d) + K = 0x8F1BBCDC + else + f = bitxor (bitxor b c) d + K = 0xCA62C1D6 + . + temp = u32 (rol a 5 + f + e + W[t] + K) + e = d + d = c + c = rol b 30 + b = a + a = temp + . + H0 = u32 (H0 + a) + H1 = u32 (H1 + b) + H2 = u32 (H2 + c) + H3 = u32 (H3 + d) + H4 = u32 (H4 + e) +. +func$ sha1 s$ . + H0 = 0x67452301 + H1 = 0xEFCDAB89 + H2 = 0x98BADCFE + H3 = 0x10325476 + H4 = 0xC3D2E1F0 + data[] = str2bytes s$ + sha1pad data[] + blocks = len data[] / 64 + for b = 0 to blocks - 1 + blk[] = [ ] + for i = 1 to 64 : blk[] &= data[b * 64 + i] + sha1block H0 H1 H2 H3 H4 blk[] + . + return word2hex H0 & word2hex H1 & word2hex H2 & word2hex H3 & word2hex H4 +. +print sha1 "Rosetta Code" diff --git a/Task/SHA-1/Elixir/sha-1.elixir b/Task/SHA-1/Elixir/sha-1.ex similarity index 100% rename from Task/SHA-1/Elixir/sha-1.elixir rename to Task/SHA-1/Elixir/sha-1.ex diff --git a/Task/SHA-1/Emacs-Lisp/sha-1.l b/Task/SHA-1/Emacs-Lisp/sha-1.el similarity index 100% rename from Task/SHA-1/Emacs-Lisp/sha-1.l rename to Task/SHA-1/Emacs-Lisp/sha-1.el diff --git a/Task/SHA-1/Hare/sha-1.hare b/Task/SHA-1/Hare/sha-1.hare index a6f6419c1e..64ac39bd10 100644 --- a/Task/SHA-1/Hare/sha-1.hare +++ b/Task/SHA-1/Hare/sha-1.hare @@ -6,11 +6,11 @@ use os; use strings; export fn main() void = { - const sha = sha1::sha1(); - hash::write(&sha, strings::toutf8("Rosetta Code")); + const sha = sha1::sha1(); + hash::write(&sha, strings::toutf8("Rosetta Code")); - let sum: [sha1::SIZE]u8 = [0...]; - hash::sum(&sha, sum); - hex::encode(os::stdout, sum)!; - fmt::println()!; + let sum: [sha1::SIZE]u8 = [0...]; + hash::sum(&sha, sum); + hex::encode(os::stdout, sum)!; + fmt::println()!; }; diff --git a/Task/SHA-1/Haxe/sha-1.haxe b/Task/SHA-1/Haxe/sha-1.haxe deleted file mode 100644 index 751e75218f..0000000000 --- a/Task/SHA-1/Haxe/sha-1.haxe +++ /dev/null @@ -1,8 +0,0 @@ -import haxe.crypto.Sha1; - -class Main { - static function main() { - var sha1 = Sha1.encode("Rosetta Code"); - Sys.println(sha1); - } -} diff --git a/Task/SHA-1/Haxe/sha-1.hx b/Task/SHA-1/Haxe/sha-1.hx new file mode 100644 index 0000000000..56e12fee6b --- /dev/null +++ b/Task/SHA-1/Haxe/sha-1.hx @@ -0,0 +1,8 @@ +import haxe.crypto.Sha1; + +class Main { + static function main() { + var sha1 = Sha1.encode("Rosetta Code"); + Sys.println(sha1); + } +} diff --git a/Task/SHA-1/Java/sha-1.java b/Task/SHA-1/Java/sha-1.java index 98030f5393..fd7ec7e47b 100644 --- a/Task/SHA-1/Java/sha-1.java +++ b/Task/SHA-1/Java/sha-1.java @@ -3,69 +3,69 @@ import java.util.Arrays; public final class SHA1Task { - public static void main(String[] args) { - System.out.println(SHA1.messageDigest("Rosetta Code")); - } + public static void main(String[] args) { + System.out.println(SHA1.messageDigest("Rosetta Code")); + } } final class SHA1 { - - public static String messageDigest(String message) { - int[] state = { 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 }; - - byte[] bytes = addPadding(message); - for ( int i = 0; i < bytes.length / BLOCK_LENGTH; i++ ) { - int[] values = new int[80]; - for ( int j = 0; j < BLOCK_LENGTH; j++ ) { - values[j / 4] |= ( bytes[i * BLOCK_LENGTH + j] & 0xff ) << ( ( 3 - j % 4 ) * 8 ); - } - for ( int j = 16; j < 80; j++ ) { - values[j] = Integer.rotateLeft(values[j - 3] ^ values[j - 8] ^ values[j - 14] ^ values[j - 16], 1); - } - - int a = state[0], b = state[1], c = state[2], d = state[3], e = state[4]; - int f = 0, k = 0; - for ( int j = 0; j < 80; j++ ) { - switch ( j / 20 ) { - case 0 -> { f = ( b & c ) | ( ~b & d ); k = 0x5a827999; } - case 1 -> { f = b ^ c ^ d; k = 0x6ed9eba1; } - case 2 -> { f = ( b & c ) | ( b & d ) | ( c & d ); k = 0x8f1bbcdc; } - case 3 -> { f = b ^ c ^ d; k = 0xca62c1d6; } - } - int temp = Integer.rotateLeft(a, 5) + f + e + k + values[j]; - e = d; d = c; c = Integer.rotateLeft(b, 30); b = a; a = temp; - } - - state[0] += a; state[1] += b; state[2] += c; state[3] += d; state[4] += e; - } - - StringBuilder result = new StringBuilder(); + public static String messageDigest(String message) { + int[] state = { 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 }; + + byte[] bytes = addPadding(message); + for ( int i = 0; i < bytes.length / BLOCK_LENGTH; i++ ) { + int[] values = new int[80]; + for ( int j = 0; j < BLOCK_LENGTH; j++ ) { + values[j / 4] |= ( bytes[i * BLOCK_LENGTH + j] & 0xff ) << ( ( 3 - j % 4 ) * 8 ); + } + for ( int j = 16; j < 80; j++ ) { + values[j] = Integer.rotateLeft(values[j - 3] ^ values[j - 8] ^ values[j - 14] ^ values[j - 16], 1); + } + + int a = state[0], b = state[1], c = state[2], d = state[3], e = state[4]; + int f = 0, k = 0; + for ( int j = 0; j < 80; j++ ) { + switch ( j / 20 ) { + case 0 -> { f = ( b & c ) | ( ~b & d ); k = 0x5a827999; } + case 1 -> { f = b ^ c ^ d; k = 0x6ed9eba1; } + case 2 -> { f = ( b & c ) | ( b & d ) | ( c & d ); k = 0x8f1bbcdc; } + case 3 -> { f = b ^ c ^ d; k = 0xca62c1d6; } + } + + int temp = Integer.rotateLeft(a, 5) + f + e + k + values[j]; + e = d; d = c; c = Integer.rotateLeft(b, 30); b = a; a = temp; + } + + state[0] += a; state[1] += b; state[2] += c; state[3] += d; state[4] += e; + } + + StringBuilder result = new StringBuilder(); for ( int i = 0; i < 20; i++ ) { - result.append(String.format("%02x", ( state[i / 4] >>> 24 - ( i % 4 ) * 8 ) & 0xFF )); + result.append(String.format("%02x", ( state[i / 4] >>> 24 - ( i % 4 ) * 8 ) & 0xFF )); } return result.toString(); - } - - private static byte[] addPadding(String message) { - byte[] bytes = message.getBytes(StandardCharsets.UTF_8); - bytes = Arrays.copyOf(bytes, bytes.length + 1); - bytes[bytes.length - 1] = (byte) 0x80; - - int padding = BLOCK_LENGTH - ( bytes.length % BLOCK_LENGTH ); - if ( padding < 8 ) { - padding += BLOCK_LENGTH; - } - bytes = Arrays.copyOf(bytes, bytes.length + padding); - - final long bitLength = message.length() * 8; - for ( int i = 0; i < 8; i++ ) { - bytes[bytes.length - 1 - i] = (byte) ( bitLength >>> ( 8 * i ) ); - } - return bytes; - } - - private static final int BLOCK_LENGTH = 64; - + } + + private static byte[] addPadding(String message) { + byte[] bytes = message.getBytes(StandardCharsets.UTF_8); + bytes = Arrays.copyOf(bytes, bytes.length + 1); + bytes[bytes.length - 1] = (byte) 0x80; + + int padding = BLOCK_LENGTH - ( bytes.length % BLOCK_LENGTH ); + if ( padding < 8 ) { + padding += BLOCK_LENGTH; + } + bytes = Arrays.copyOf(bytes, bytes.length + padding); + + final long bitLength = message.length() * 8; + for ( int i = 0; i < 8; i++ ) { + bytes[bytes.length - 1 - i] = (byte) ( bitLength >>> ( 8 * i ) ); + } + return bytes; + } + + private static final int BLOCK_LENGTH = 64; + } diff --git a/Task/SHA-1/JavaScript/sha-1.js b/Task/SHA-1/JavaScript/sha-1.js new file mode 100644 index 0000000000..3dde1e7e9b --- /dev/null +++ b/Task/SHA-1/JavaScript/sha-1.js @@ -0,0 +1,164 @@ +class SHA1 { + constructor() { + // Constants + this.BLOCK_LENGTH = 64; // Bytes + this.H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]; + this.K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6]; + } + + /** + * Rotates left (circular left shift) on a 32-bit number. + * @param {number} n - The 32-bit number. + * @param {number} bits - The number of bits to rotate. + * @returns {number} The rotated 32-bit number. + */ + _rotl(n, bits) { + // Ensure n is treated as 32-bit for the shift operations + return ((n << bits) | (n >>> (32 - bits))) | 0; // | 0 ensures result is 32-bit signed int + } + + /** + * Adds SHA-1 padding to the message bytes. + * @param {Uint8Array} messageBytes - The message as bytes. + * @returns {Uint8Array} The padded message bytes. + */ + _addPadding(messageBytes) { + const msgLenBytes = messageBytes.length; + // Use BigInt for potentially large bit lengths + const bitLength = BigInt(msgLenBytes) * 8n; + + // Calculate the total padded length in bytes + // Need msgLenBytes + 1 (for 0x80) + k (zeros) + 8 (length) = N * 64 + // msgLenBytes + 9 + k = N * 64 + // The number of zero bytes 'k' needed is: + // k = (64 - (msgLenBytes + 9) % 64) % 64 + const k = (this.BLOCK_LENGTH - ((msgLenBytes + 9) % this.BLOCK_LENGTH)) % this.BLOCK_LENGTH; + const paddedLength = msgLenBytes + 1 + k + 8; + const paddedBytes = new Uint8Array(paddedLength); + + // 1. Copy original message + paddedBytes.set(messageBytes); + + // 2. Append a single '1' bit (0x80 byte) + paddedBytes[msgLenBytes] = 0x80; + + // 3. Append K '0' bits (zero bytes). Uint8Array initializes to 0, so this is implicit. + + // 4. Append length L as a 64-bit big-endian integer. + const lengthOffset = paddedLength - 8; + for (let i = 0; i < 8; i++) { + // Extract byte from BigInt bitLength + const shift = BigInt(i) * 8n; + // Place it in big-endian order (most significant byte first) + paddedBytes[lengthOffset + 7 - i] = Number((bitLength >> shift) & 0xffn); + } + + return paddedBytes; + } + + /** + * Computes the SHA-1 hash of a message string. + * @param {string} message - The input message string. + * @returns {string} The SHA-1 hash as a 40-character hex string. + */ + messageDigest(message) { + // 1. Convert message string to UTF-8 bytes + const encoder = new TextEncoder(); // Assumes UTF-8 + const messageBytes = encoder.encode(message); + + // 2. Add padding + const paddedBytes = this._addPadding(messageBytes); + + // 3. Initialize hash values + let state = [...this.H]; // Create a working copy + + // 4. Process message in 64-byte (512-bit) blocks + for (let i = 0; i < paddedBytes.length; i += this.BLOCK_LENGTH) { + const blockBytes = paddedBytes.subarray(i, i + this.BLOCK_LENGTH); + + // Prepare the message schedule (80 32-bit words) + const W = new Array(80); + + // a. Copy block into first 16 words (big-endian) + for (let t = 0; t < 16; t++) { + const offset = t * 4; + W[t] = ((blockBytes[offset] << 24) | + (blockBytes[offset + 1] << 16) | + (blockBytes[offset + 2] << 8) | + (blockBytes[offset + 3])) | 0; // | 0 ensures 32-bit signed int + } + + // b. Extend the first 16 words into the remaining 64 words + for (let t = 16; t < 80; t++) { + const wt = W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16]; + W[t] = this._rotl(wt, 1); + } + + // Initialize hash value for this block + let a = state[0]; + let b = state[1]; + let c = state[2]; + let d = state[3]; + let e = state[4]; + + // Main loop + for (let t = 0; t < 80; t++) { + let f, k; + const round = Math.floor(t / 20); + switch (round) { + case 0: // Rounds 0-19 + f = (b & c) | (~b & d); + k = this.K[0]; + break; + case 1: // Rounds 20-39 + f = b ^ c ^ d; + k = this.K[1]; + break; + case 2: // Rounds 40-59 + f = (b & c) | (b & d) | (c & d); + k = this.K[2]; + break; + case 3: // Rounds 60-79 + f = b ^ c ^ d; + k = this.K[3]; + break; + } + + // Ensure all additions are performed modulo 2^32 + const temp = (this._rotl(a, 5) + f + e + k + W[t]) | 0; + e = d; + d = c; + c = this._rotl(b, 30); + b = a; + a = temp; + } + + // Add this block's hash to the result so far (modulo 2^32) + state[0] = (state[0] + a) | 0; + state[1] = (state[1] + b) | 0; + state[2] = (state[2] + c) | 0; + state[3] = (state[3] + d) | 0; + state[4] = (state[4] + e) | 0; + } + + // 5. Produce the final hash value (big-endian) as a hex string + let hexHash = ""; + for (const h of state) { + // Convert each 32-bit component to hex, padding with '0' + // Use >>> 0 to treat h as unsigned before converting to hex parts + const unsignedH = h >>> 0; + hexHash += (unsignedH >>> 24).toString(16).padStart(2, '0'); + hexHash += ((unsignedH >>> 16) & 0xff).toString(16).padStart(2, '0'); + hexHash += ((unsignedH >>> 8) & 0xff).toString(16).padStart(2, '0'); + hexHash += (unsignedH & 0xff).toString(16).padStart(2, '0'); + } + + return hexHash; + } +} + +// --- Main execution (equivalent to C++ main) --- +const sha1 = new SHA1(); +const message = "Rosetta Code"; +const digest = sha1.messageDigest(message); +console.log(digest); diff --git a/Task/SHA-1/Julia/sha-1.julia b/Task/SHA-1/Julia/sha-1.jl similarity index 100% rename from Task/SHA-1/Julia/sha-1.julia rename to Task/SHA-1/Julia/sha-1.jl diff --git a/Task/SHA-1/Kotlin/sha-1.kotlin b/Task/SHA-1/Kotlin/sha-1.kts similarity index 100% rename from Task/SHA-1/Kotlin/sha-1.kotlin rename to Task/SHA-1/Kotlin/sha-1.kts diff --git a/Task/SHA-1/OCaml/sha-1.ocaml b/Task/SHA-1/OCaml/sha-1.ml similarity index 100% rename from Task/SHA-1/OCaml/sha-1.ocaml rename to Task/SHA-1/OCaml/sha-1.ml diff --git a/Task/SHA-1/Phix/sha-1.phix b/Task/SHA-1/Phix/sha-1.phix index 79527ff351..599ffb333c 100644 --- a/Task/SHA-1/Phix/sha-1.phix +++ b/Task/SHA-1/Phix/sha-1.phix @@ -1,86 +1,81 @@ -(phixonline)--> - -- - -- demo\rosetta\sha1.exw - -- ===================== - -- - -- NB no longer considered secure. Non-optimised. - -- - function uint32(atom v) - return and_bitsu(v,#FFFFFFFF) - end function +-- demo\rosetta\sha1.exw +-- NB no longer considered secure. Non-optimised. - function sq_uint32(sequence s) - for i=1 to length(s) do - s[i] = uint32(s[i]) - end for - return s - end function +function uint32(atom v) + return and_bitsu(v,#FFFFFFFF) +end function - function dword(string msg, integer i) - -- get dword as big-endian - return msg[i]*#1000000+msg[i+1]*#10000+msg[i+2]*#100+msg[i+3] - end function +function sq_uint32(sequence s) + for i=1 to length(s) do + s[i] = uint32(s[i]) + end for + return s +end function - function xor_all(sequence s) - atom result = 0 - for i=1 to length(s) do - result = xor_bits(result, s[i]) - end for - result = uint32(result) - return result - end function +function dword(string msg, integer i) +-- get dword as big-endian + return msg[i]*#1000000+msg[i+1]*#10000+msg[i+2]*#100+msg[i+3] +end function - function rol(atom word, integer bits) - -- left rotate the bits of a 32-bit number by the specified number of bits - return uint32(word*power(2,bits))+floor(word/power(2,32-bits)) - end function +function xor_all(sequence s) +atom result = 0 + for i=1 to length(s) do + result = xor_bits(result, s[i]) + end for + result = uint32(result) + return result +end function - function sha1(string msg) - atom a,b,c,d,e,temp,k - sequence w = repeat(0,80) - atom h0 = 0x67452301, - h1 = 0xefcdab89, - h2 = 0x98badcfe, - h3 = 0x10325476, - h4 = 0xc3d2e1f0 +function rol(atom word, integer bits) +-- left rotate the bits of a 32-bit number by the specified number of bits + return uint32(word*power(2,bits))+floor(word/power(2,32-bits)) +end function - integer bits = length(msg)*8 - msg &= #80 - while mod(length(msg),64)!=56 do msg &= '\0' end while - msg &= reverse(int_to_bytes(bits,8)) +function sha1(string msg) +atom a,b,c,d,e,temp,k +sequence w = repeat(0,80) +atom h0 = 0x67452301, + h1 = 0xefcdab89, + h2 = 0x98badcfe, + h3 = 0x10325476, + h4 = 0xc3d2e1f0 - for chunk=1 to length(msg) by 64 do - for i=1 to 16 do - w[i] = dword(msg,chunk+(i-1)*4) - end for - for i=17 to 80 do - w[i] = rol(xor_all({w[i-3],w[i-8],w[i-14],w[i-16]}),1) - end for - {a,b,c,d,e} = {h0,h1,h2,h3,h4} - for i=1 to 80 do - if i<=20 then - temp = or_bits(and_bits(b,c),and_bits(not_bits(b),d)) - k = #5A827999 - elsif i<=40 then - temp = xor_bits(xor_bits(b,c),d) - k = #6ED9EBA1 - elsif i<=60 then - temp = or_bits(or_bits(and_bits(b,c),and_bits(b,d)),and_bits(c,d)) - k = #8F1BBCDC - else -- i<=80 - temp = xor_bits(xor_bits(b,c),d) - k = #CA62C1D6 - end if - {a,b,c,d,e} = {uint32(rol(a,5)+temp+e+k+w[i]),a,rol(b,30),c,d} - end for - {h0,h1,h2,h3,h4} = sq_uint32(sq_add({h0,h1,h2,h3,h4},{a,b,c,d,e})) - end for - sequence res = {h0, h1, h2, h3, h4} - for i=1 to length(res) do - res[i] = sprintf("%08X",res[i]) - end for - return join(res) - end function + integer bits = length(msg)*8 + msg &= #80 + while mod(length(msg),64)!=56 do msg &= '\0' end while + msg &= reverse(int_to_bytes(bits,8)) - ?sha1("Rosetta Code") - - with javascript_semantics - sequence safe = {}, unsafe = {} - function filter_range(integer lo, hi) - while true do - integer p = get_prime(lo) - if p>hi then return lo end if - if p>2 and is_prime((p-1)/2) then - safe &= p - else - unsafe &= p - end if - lo += 1 - end while - end function - integer lo = filter_range(1,1_000_000), - ls = length(safe), - lu = length(unsafe) - {} = filter_range(lo,10_000_000) - printf(1,"The first 35 safe primes: %v\n",{safe[1..35]}) - printf(1,"Count of safe primes below 1,000,000: %,d\n",ls) - printf(1,"Count of safe primes below 10,000,000: %,d\n",length(safe)) - printf(1,"The first 40 unsafe primes: %v\n",{unsafe[1..40]}) - printf(1,"Count of unsafe primes below 1,000,000: %,d\n",lu) - printf(1,"Count of unsafe primes below 10,000,000: %,d\n",length(unsafe)) - - procedure solve(integer sailors) - integer m, sm1 = sailors-1 - if sm1=0 then -- edge condition for solve(1) [ avoid /0 ] - m = sailors - else - for n=sailors to 1_000_000_000 by sailors do -- morning pile divisible by #sailors - m = n - for j=1 to sailors do -- see if all of the sailors could.. - if remainder(m,sm1)!=0 then -- ..have pushed together sm1 piles - m = 0 -- (no: try a higher n) - exit - end if - m = sailors*m/sm1+1 -- add sailor j's stash and one for the monkey - end for - if m!=0 then exit end if - end for - end if - printf(1,"Solution with %d sailors: %d\n",{sailors,m}) - for i=1 to sailors do - m -= 1 -- one for the monkey - m /= sailors - printf(1,"Sailor #%d takes %d, giving 1 to the monkey and leaving %d\n",{i,m,m*sm1}) - m *= (sm1) - end for - printf(1,"In the morning each sailor gets %d nuts\n",m/sailors) - end procedure - - solve(5) - solve(6) - - forward function localf() -- not normally necesssary, but will not harm - forward global function globalf() -- "" +forward function localf() -- not normally necesssary, but will not harm +forward global function globalf() -- "" - function localf() - return 1 - end function +function localf() + return 1 +end function - global function globalf() - return 2 - end function - - include somefile.e as xxx - -- alternatively, within somefile.e: - namespace xxx -- (only supported in Phix for compatibility with OpenEuphoria) +include somefile.e as xxx +-- alternatively, within somefile.e: +namespace xxx -- (only supported in Phix for compatibility with Euphoria) - res = xxx:globalf() -- call a global function named globalf, specifically the one declared in somefile.e - - constant s = {"Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Boz", "Zag"} +constant s = {"Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Boz", "Zag"} - integer r = find("Zag",s) ?r -- 2 (first) - r = find("Zag",s,r+1) ?r -- 10 (next) - r = find("Zag",s,r+1) ?r -- 0 (no more) - r = rfind("Zag",s) ?r -- 10 (last) - r = find("Zog",s) ?r -- 0 (none) - nonblanks(Word), eol, { Word \= [] }. + +find_all_semordnilaps(Words, Semordnilaps) :- + convlist([Word, Reversed] >> ( + reverse(Word, Reversed), + Reversed @< Word + ), Words, ReversedWords0), + sort(ReversedWords0, ReversedWords), + ord_intersection(Words, ReversedWords, Semordnilaps). + +main([Filename]) :- + load(Filename, Words), + find_all_semordnilaps(Words, Semordnilaps), + length(Semordnilaps, Count), + format("~d~n", Count), + length(FirstFive, 5), + prefix(FirstFive, Semordnilaps), + maplist([Word] >> ( + reverse(Word, Reversed), + format("~s / ~s~n", [Word, Reversed]) + ), FirstFive). diff --git a/Task/Semordnilap/Python/semordnilap-1.py b/Task/Semordnilap/Python/semordnilap-1.py index 0e1fa9ed3c..6acbb2e6d9 100644 --- a/Task/Semordnilap/Python/semordnilap-1.py +++ b/Task/Semordnilap/Python/semordnilap-1.py @@ -1,5 +1,5 @@ >>> with open('unixdict.txt') as f: - wordset = set(f.read().strip().split()) + wordset = set(f.read().strip().split()) >>> revlist = (''.join(word[::-1]) for word in wordset) >>> pairs = set((word, rev) for word, rev in zip(wordset, revlist) diff --git a/Task/Semordnilap/R/semordnilap.r b/Task/Semordnilap/R/semordnilap.r new file mode 100644 index 0000000000..425f6d70bc --- /dev/null +++ b/Task/Semordnilap/R/semordnilap.r @@ -0,0 +1,17 @@ +library(stringi) + +unixdict <- read.table("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", col.names="forwards") +unixdict$backwards <- stri_reverse(unixdict$forwards) + +#Remove all actual palindromes, as we do not want those +unixdict <- subset(unixdict, forwards!=backwards) + +for(i in seq_along(unixdict$forwards)){ + unixdict$issemordnilap[i] <- with(unixdict, forwards[i] %in% backwards) +} + +semordnilaps <- subset(unixdict, (issemordnilap==TRUE)&(forwards>backwards), select=-issemordnilap) +length(semordnilaps$forwards) + +random <- sample(seq_along(semordnilaps$forwards), 5, replace=FALSE) +print(semordnilaps[random,], row.names=FALSE) diff --git a/Task/Semordnilap/Rebol/semordnilap-1.rebol b/Task/Semordnilap/Rebol/semordnilap-1.rebol new file mode 100644 index 0000000000..b1dd74d3c1 --- /dev/null +++ b/Task/Semordnilap/Rebol/semordnilap-1.rebol @@ -0,0 +1,26 @@ +Rebol [ + title: "Rosetta code: Semordnilap" + file: %Semordnilap.r + url: https://rosettacode.org/wiki/Semordnilap + needs: 2.7.0 +] + +words: read/lines http://wiki.puzzlers.org/pub/wordlists/unixdict.txt +seen: make hash! 200 +count: 0 + +print ["Number of input words: " length? words LF] + +foreach word words [ + reversed: reverse copy word + either find seen reversed [ + count: count + 1 + if count <= 5 [ + print [word "is reversed:" reversed] + ] + ][ + append seen word + ] +] + +print [LF "Found total" count "pairs."] diff --git a/Task/Semordnilap/Rebol/semordnilap-2.rebol b/Task/Semordnilap/Rebol/semordnilap-2.rebol new file mode 100644 index 0000000000..026971ea27 --- /dev/null +++ b/Task/Semordnilap/Rebol/semordnilap-2.rebol @@ -0,0 +1,25 @@ +Rebol [ + title: "Rosetta code: Semordnilap" + file: %Semordnilap.r3 + url: https://rosettacode.org/wiki/Semordnilap + needs: 3.14.0 +] + +words: read/lines http://wiki.puzzlers.org/pub/wordlists/unixdict.txt +seen: make map! 200 +count: 0 + +print ["Number of input words: " length? words LF] + +foreach word words [ + reversed: reverse copy word + either find seen reversed [ + if ++ count <= 5 [ + print [word "is reversed:" reversed] + ] + ][ + put seen word reversed + ] +] + +print [LF "Found total" count "pairs."] diff --git a/Task/Semordnilap/Rust/semordnilap-1.rust b/Task/Semordnilap/Rust/semordnilap-1.rs similarity index 100% rename from Task/Semordnilap/Rust/semordnilap-1.rust rename to Task/Semordnilap/Rust/semordnilap-1.rs diff --git a/Task/Semordnilap/Rust/semordnilap-2.rust b/Task/Semordnilap/Rust/semordnilap-2.rs similarity index 100% rename from Task/Semordnilap/Rust/semordnilap-2.rust rename to Task/Semordnilap/Rust/semordnilap-2.rs diff --git a/Task/Semordnilap/SNOBOL4/semordnilap.sno b/Task/Semordnilap/SNOBOL4/semordnilap.sno index 795ca4e677..ffa5b12f6a 100644 --- a/Task/Semordnilap/SNOBOL4/semordnilap.sno +++ b/Task/Semordnilap/SNOBOL4/semordnilap.sno @@ -7,28 +7,28 @@ * Reads file unixdict.txt * Comment: Tested using the Spitbol for Linux version of SNOBOL4 - output = "Some Semordnilap Pairs from File unixdict.txt" - atable = table(25200,,-1) - ntable = table(25200,,-2) + output = "Some Semordnilap Pairs from File unixdict.txt" + atable = table(25200,,-1) + ntable = table(25200,,-2) * Read dictionary file into memory in1 - word = input :f(p1) - count = count + 1 - atable[word] = word - ntable[count] = word - :(in1) + word = input :f(p1) + count = count + 1 + atable[word] = word + ntable[count] = word + :(in1) * Process dictionary to find unique semordnilaps p1 - i = lt(i,count) i + 1 :f(p2) - newword = atable[reverse(ntable[i])] - leq(newword,-1) :s(p1) - ident(ntable[i],newword) :s(p1) - output = lt(outcount,5) ntable[i] ', ' newword - atable[ntable[i]] = atable[newword] = -1 - outcount = outcount + 1 - :(p1) + i = lt(i,count) i + 1 :f(p2) + newword = atable[reverse(ntable[i])] + leq(newword,-1) :s(p1) + ident(ntable[i],newword) :s(p1) + output = lt(outcount,5) ntable[i] ', ' newword + atable[ntable[i]] = atable[newword] = -1 + outcount = outcount + 1 + :(p1) p2 - output = 'The number of semordnilap pairs is: ' outcount + output = 'The number of semordnilap pairs is: ' outcount END diff --git a/Task/Semordnilap/SuperCollider/semordnilap-1.sc b/Task/Semordnilap/SuperCollider/semordnilap-1.sc deleted file mode 100644 index aa3774f558..0000000000 --- a/Task/Semordnilap/SuperCollider/semordnilap-1.sc +++ /dev/null @@ -1,12 +0,0 @@ -( -var text, words, sdrow, semordnilap, selection; -File.use("unixdict.txt".resolveRelative, "r", { |f| x = text = f.readAllString }); -words = text.split(Char.nl).collect { |each| each.asSymbol }; -sdrow = text.reverse.split(Char.nl).collect { |each| each.asSymbol }; -semordnilap = sect(words, sdrow); // converted to symbols so intersection is possible -semordnilap = semordnilap.collect { |each| each.asString }; -"There are % in unixdict.txt\n".postf(semordnilap.size); -"For example those, with more than 3 characters:".postln; -selection = semordnilap.select { |each| each.size >= 4 }.scramble.keep(4); -selection.do { |each| "% %\n".postf(each, each.reverse); }; -) diff --git a/Task/Semordnilap/SuperCollider/semordnilap-2.sc b/Task/Semordnilap/SuperCollider/semordnilap-2.sc deleted file mode 100644 index c33b0276f6..0000000000 --- a/Task/Semordnilap/SuperCollider/semordnilap-2.sc +++ /dev/null @@ -1,6 +0,0 @@ -There are 405 in unixdict.txt -For example those, with more than 3 characters: -live evil -tram mart -drib bird -eros sore diff --git a/Task/Semordnilap/TAV/semordnilap.tav b/Task/Semordnilap/TAV/semordnilap.tav new file mode 100644 index 0000000000..7b26db7ad4 --- /dev/null +++ b/Task/Semordnilap/TAV/semordnilap.tav @@ -0,0 +1,22 @@ +main(params):+ + seen =: new map + inwrds =: 0 + pairs =: 0 + palindromes =: 0 + ?# line =: file 'unixdict.txt' give lines + inwrds =+ 1 + wrd =: string line case to lower + rwrd =: string wrd from -1 length wrd.Count step -1 + ? wrd = rwrd + palindromes =+ 1 + ?^ + ? seen{rwrd} = () + seen{wrd} =: line \ not yet seen, remember + | + pairs =+ 1 + ? pairs < 7 + print wrd __ rwrd + + print pairs, "pairs, " nonl + print palindromes, "palindromes, " nonl + print inwrds, "input words." diff --git a/Task/Semordnilap/Tcl/semordnilap.tcl b/Task/Semordnilap/Tcl/semordnilap.tcl index 9fea9f4850..79c9bd49bc 100644 --- a/Task/Semordnilap/Tcl/semordnilap.tcl +++ b/Task/Semordnilap/Tcl/semordnilap.tcl @@ -14,10 +14,10 @@ foreach word $wordlist { # Find where a reversal exists foreach word $wordlist { if {[info exists reversed($word)] && $word ne [string reverse $word]} { - # Remove to prevent pairs from being printed twice - unset reversed([string reverse $word]) - # Add to collection of pairs - set pairs($word/[string reverse $word]) "dummy" + # Remove to prevent pairs from being printed twice + unset reversed([string reverse $word]) + # Add to collection of pairs + set pairs($word/[string reverse $word]) "dummy" } } set pairlist [array names pairs] ;# NB: pairs are in *arbitrary* order diff --git a/Task/Semordnilap/Uiua/semordnilap.uiua b/Task/Semordnilap/Uiua/semordnilap.uiua index 8c92539883..6a45a2fd90 100644 --- a/Task/Semordnilap/Uiua/semordnilap.uiua +++ b/Task/Semordnilap/Uiua/semordnilap.uiua @@ -1 +1,4 @@ -&p &pf "Count: " ⧻.▽≡(×>⇌.⟜∊⇌)⟜¤. ⊜□ ≠@\n. &fras "unixdict.txt" +A ← map:⊚⧻.⊜□≠@\n.&fras"unixdict.txt" +Earlier ← >0˜⨂0≡≤⇌. # Would this sort before its reverse? +˜▽⟜≡(↧⊃(Earlier|has⇌)°□)⊙◌°map⟜¤A +&p$"Found _ semordnilaps:\n_"⊸⧻⍆ diff --git a/Task/Semordnilap/VBScript/semordnilap.vb b/Task/Semordnilap/VBScript/semordnilap.vb deleted file mode 100644 index f56f78ccdf..0000000000 --- a/Task/Semordnilap/VBScript/semordnilap.vb +++ /dev/null @@ -1,36 +0,0 @@ -Set objFSO = CreateObject("Scripting.FileSystemObject") -Set objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ - "\unixdict.txt",1) - -Set objUnixDict = CreateObject("Scripting.Dictionary") -Set objSemordnilap = CreateObject("Scripting.Dictionary") - -Do Until objInFile.AtEndOfStream - line = objInFile.ReadLine - If Len(line) > 1 Then - objUnixDict.Add line,"" - End If - reverse_line = StrReverse(line) - If reverse_line <> line And objUnixDict.Exists(reverse_line) Then - objSemordnilap.Add line, reverse_line - End If -Loop - -'Display the first 5 keys. -k = 0 -For Each Key In objSemordnilap.Keys - WScript.StdOut.Write Key & " - " & objSemordnilap.Item(Key) - WScript.StdOut.WriteLine - k = k + 1 - If k = 5 Then - Exit For - End If -Next - -WScript.StdOut.Write "Total Count: " & objSemordnilap.Count -WScript.StdOut.WriteLine - -objInFile.Close -Set objFSO = Nothing -Set objUnixDict = Nothing -Set objSemordnilap = Nothing diff --git a/Task/Semordnilap/VBScript/semordnilap.vbs b/Task/Semordnilap/VBScript/semordnilap.vbs new file mode 100644 index 0000000000..83c8f216a2 --- /dev/null +++ b/Task/Semordnilap/VBScript/semordnilap.vbs @@ -0,0 +1,36 @@ +Set objFSO = CreateObject("Scripting.FileSystemObject") +Set objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ + "\unixdict.txt",1) + +Set objUnixDict = CreateObject("Scripting.Dictionary") +Set objSemordnilap = CreateObject("Scripting.Dictionary") + +Do Until objInFile.AtEndOfStream + line = objInFile.ReadLine + If Len(line) > 1 Then + objUnixDict.Add line,"" + End If + reverse_line = StrReverse(line) + If reverse_line <> line And objUnixDict.Exists(reverse_line) Then + objSemordnilap.Add line, reverse_line + End If +Loop + +'Display the first 5 keys. +k = 0 +For Each Key In objSemordnilap.Keys + WScript.StdOut.Write Key & " - " & objSemordnilap.Item(Key) + WScript.StdOut.WriteLine + k = k + 1 + If k = 5 Then + Exit For + End If +Next + +WScript.StdOut.Write "Total Count: " & objSemordnilap.Count +WScript.StdOut.WriteLine + +objInFile.Close +Set objFSO = Nothing +Set objUnixDict = Nothing +Set objSemordnilap = Nothing diff --git a/Task/Send-an-unknown-method-call/Ecstasy/send-an-unknown-method-call.ecstasy b/Task/Send-an-unknown-method-call/Ecstasy/send-an-unknown-method-call.ecstasy new file mode 100644 index 0000000000..b6f5ebf098 --- /dev/null +++ b/Task/Send-an-unknown-method-call/Ecstasy/send-an-unknown-method-call.ecstasy @@ -0,0 +1,21 @@ +module test { + @Inject Console console; + + void run(String[] args) { + String name = args.empty ? "foo" : args[0]; + if (val mm := &this.actualType.multimethods.get(name), + val m := mm.methods.any(m -> m.ParamTypes.size == 0)) { + m.invoke(this, Tuple:()); + } else { + console.print($"No such 0-parameter method: {name.quoted()}"); + } + } + + void foo() { + console.print("this is the foo() method"); + } + + void bar() { + console.print("this is the bar() method"); + } +} diff --git a/Task/Send-an-unknown-method-call/Elena/send-an-unknown-method-call.elena b/Task/Send-an-unknown-method-call/Elena/send-an-unknown-method-call.elena index 6444760b0e..5d2a533eed 100644 --- a/Task/Send-an-unknown-method-call/Elena/send-an-unknown-method-call.elena +++ b/Task/Send-an-unknown-method-call/Elena/send-an-unknown-method-call.elena @@ -6,7 +6,7 @@ class Example = x + 42; } -public program() +public Program() { var example := new Example(); var methodSignature := "foo"; @@ -14,5 +14,5 @@ public program() var invoker := new MessageName(methodSignature); var result := invoker(example,5); - console.printLine(methodSignature,"(",5,") = ",result) + Console.printLine(methodSignature,"(",5,") = ",result) } diff --git a/Task/Send-an-unknown-method-call/Julia/send-an-unknown-method-call.julia b/Task/Send-an-unknown-method-call/Julia/send-an-unknown-method-call.jl similarity index 100% rename from Task/Send-an-unknown-method-call/Julia/send-an-unknown-method-call.julia rename to Task/Send-an-unknown-method-call/Julia/send-an-unknown-method-call.jl diff --git a/Task/Send-an-unknown-method-call/Kotlin/send-an-unknown-method-call.kotlin b/Task/Send-an-unknown-method-call/Kotlin/send-an-unknown-method-call.kts similarity index 100% rename from Task/Send-an-unknown-method-call/Kotlin/send-an-unknown-method-call.kotlin rename to Task/Send-an-unknown-method-call/Kotlin/send-an-unknown-method-call.kts diff --git a/Task/Send-an-unknown-method-call/PascalABC.NET/send-an-unknown-method-call.pas b/Task/Send-an-unknown-method-call/PascalABC.NET/send-an-unknown-method-call.pas new file mode 100644 index 0000000000..00019bcb23 --- /dev/null +++ b/Task/Send-an-unknown-method-call/PascalABC.NET/send-an-unknown-method-call.pas @@ -0,0 +1,10 @@ +type MyClass = class +public + procedure Hello := Write('Hello'); +end; + +begin + var obj := new MyClass; + var mi := typeof(MyClass).GetMethod('Hello'); + mi.Invoke(obj,new object[0]) +end. diff --git a/Task/Send-an-unknown-method-call/PowerShell/send-an-unknown-method-call.psh b/Task/Send-an-unknown-method-call/PowerShell/send-an-unknown-method-call.ps1 similarity index 100% rename from Task/Send-an-unknown-method-call/PowerShell/send-an-unknown-method-call.psh rename to Task/Send-an-unknown-method-call/PowerShell/send-an-unknown-method-call.ps1 diff --git a/Task/Send-an-unknown-method-call/V-(Vlang)/send-an-unknown-method-call.v b/Task/Send-an-unknown-method-call/V-(Vlang)/send-an-unknown-method-call.v new file mode 100644 index 0000000000..6451463c26 --- /dev/null +++ b/Task/Send-an-unknown-method-call/V-(Vlang)/send-an-unknown-method-call.v @@ -0,0 +1,21 @@ +import os + +struct Obj { + mut: + methods map[string]fn() +} + +fn (mut o Obj) create_methods() Obj { + o.methods["ma"] = fn () { println("Method A Called") } + o.methods["mb"] = fn () { println("Method B Called") } + o.methods["mc"] = fn () { println("Method C Called") } + return o +} + +fn main() { + mut obj := Obj{} + obj = obj.create_methods() + name := os.input("Which method should I call? ").str() + if name in obj.methods { obj.methods[name]() } + else { println("No method of that name found!") } +} diff --git a/Task/Send-email/Ada/send-email.ada b/Task/Send-email/Ada/send-email.adb similarity index 100% rename from Task/Send-email/Ada/send-email.ada rename to Task/Send-email/Ada/send-email.adb diff --git a/Task/Send-email/AppleScript/send-email.applescript b/Task/Send-email/AppleScript/send-email.applescript new file mode 100644 index 0000000000..5d5725fb3c --- /dev/null +++ b/Task/Send-email/AppleScript/send-email.applescript @@ -0,0 +1,10 @@ +on sendmail(msg_to, msg_cc, msg_subject, msg_text) + tell application "Mail" + set msg to make new outgoing message with properties {subject:msg_subject, content:msg_text, visible:true} + tell msg + make new to recipient with properties {address:msg_to} + make new cc recipient with properties {address:msg_cc} + send + end tell + end tell +end sendmail diff --git a/Task/Send-email/Delphi/send-email.delphi b/Task/Send-email/Delphi/send-email.pas similarity index 100% rename from Task/Send-email/Delphi/send-email.delphi rename to Task/Send-email/Delphi/send-email.pas diff --git a/Task/Send-email/Emacs-Lisp/send-email.l b/Task/Send-email/Emacs-Lisp/send-email.el similarity index 100% rename from Task/Send-email/Emacs-Lisp/send-email.l rename to Task/Send-email/Emacs-Lisp/send-email.el diff --git a/Task/Send-email/Julia/send-email.julia b/Task/Send-email/Julia/send-email.jl similarity index 100% rename from Task/Send-email/Julia/send-email.julia rename to Task/Send-email/Julia/send-email.jl diff --git a/Task/Send-email/Kotlin/send-email.kotlin b/Task/Send-email/Kotlin/send-email.kts similarity index 100% rename from Task/Send-email/Kotlin/send-email.kotlin rename to Task/Send-email/Kotlin/send-email.kts diff --git a/Task/Send-email/OCaml/send-email.ocaml b/Task/Send-email/OCaml/send-email.ml similarity index 100% rename from Task/Send-email/OCaml/send-email.ocaml rename to Task/Send-email/OCaml/send-email.ml diff --git a/Task/Send-email/PowerShell/send-email.psh b/Task/Send-email/PowerShell/send-email.ps1 similarity index 100% rename from Task/Send-email/PowerShell/send-email.psh rename to Task/Send-email/PowerShell/send-email.ps1 diff --git a/Task/Send-email/REBOL/send-email.rebol b/Task/Send-email/Rebol/send-email.rebol similarity index 100% rename from Task/Send-email/REBOL/send-email.rebol rename to Task/Send-email/Rebol/send-email.rebol diff --git a/Task/Send-email/VBScript/send-email.vb b/Task/Send-email/VBScript/send-email.vbs similarity index 100% rename from Task/Send-email/VBScript/send-email.vb rename to Task/Send-email/VBScript/send-email.vbs diff --git a/Task/Sequence-of-non-squares/Ada/sequence-of-non-squares.ada b/Task/Sequence-of-non-squares/Ada/sequence-of-non-squares.adb similarity index 100% rename from Task/Sequence-of-non-squares/Ada/sequence-of-non-squares.ada rename to Task/Sequence-of-non-squares/Ada/sequence-of-non-squares.adb diff --git a/Task/Sequence-of-non-squares/Arturo/sequence-of-non-squares.arturo b/Task/Sequence-of-non-squares/Arturo/sequence-of-non-squares.arturo index 98cf5365f4..cb2c1a589b 100644 --- a/Task/Sequence-of-non-squares/Arturo/sequence-of-non-squares.arturo +++ b/Task/Sequence-of-non-squares/Arturo/sequence-of-non-squares.arturo @@ -4,9 +4,9 @@ f: function [n]-> loop 1..22 'i -> print [i "->" f i] -i: new 1, nonSquares: new [] +i: 1, nonSquares: [] while [i<1000000][ 'nonSquares ++ f i, inc 'i] squares: map 1..1001 'x -> x ^ 2 -if? empty? intersection squares nonSquares -> print "Didn't find any squares!" - else -> print "Ooops! Something went wrong!" +switch empty? intersection squares nonSquares -> print "Didn't find any squares!" + -> print "Ooops! Something went wrong!" diff --git a/Task/Sequence-of-non-squares/COBOL/sequence-of-non-squares.cobol b/Task/Sequence-of-non-squares/COBOL/sequence-of-non-squares.cob similarity index 100% rename from Task/Sequence-of-non-squares/COBOL/sequence-of-non-squares.cobol rename to Task/Sequence-of-non-squares/COBOL/sequence-of-non-squares.cob diff --git a/Task/Sequence-of-non-squares/Crystal/sequence-of-non-squares.cr b/Task/Sequence-of-non-squares/Crystal/sequence-of-non-squares.cr new file mode 100644 index 0000000000..db1b031bae --- /dev/null +++ b/Task/Sequence-of-non-squares/Crystal/sequence-of-non-squares.cr @@ -0,0 +1,15 @@ +struct Int + def square? + (r = Math.isqrt(self)) * r == self + end +end + +def non_squares + (1..).each.map {|n| n + (0.5 + Math.sqrt(n)).to_i } +end + +print "First 22 values in the sequence: " +puts non_squares.first(22).to_a + +print "Squares in the non-squares sequence (up to n < 1000000): " +puts non_squares.first(999_999).select(&.square?).to_a diff --git a/Task/Sequence-of-non-squares/Delphi/sequence-of-non-squares.delphi b/Task/Sequence-of-non-squares/Delphi/sequence-of-non-squares.pas similarity index 100% rename from Task/Sequence-of-non-squares/Delphi/sequence-of-non-squares.delphi rename to Task/Sequence-of-non-squares/Delphi/sequence-of-non-squares.pas diff --git a/Task/Sequence-of-non-squares/EasyLang/sequence-of-non-squares.easy b/Task/Sequence-of-non-squares/EasyLang/sequence-of-non-squares.easy index bb08700f1a..0254fcd220 100644 --- a/Task/Sequence-of-non-squares/EasyLang/sequence-of-non-squares.easy +++ b/Task/Sequence-of-non-squares/EasyLang/sequence-of-non-squares.easy @@ -2,14 +2,11 @@ func nonSqu n . return n + floor (0.5 + sqrt n) . for i = 1 to 22 - print nonSqu i + write nonSqu i & " " . +print "" for i = 1 to 1e6 j = sqrt nonSqu i - if j = floor j - found = 1 - . -. -if found = 0 - print "No squares found" + if j = floor j : found = 1 . +if found = 0 : print "No squares found" diff --git a/Task/Sequence-of-non-squares/Elixir/sequence-of-non-squares.elixir b/Task/Sequence-of-non-squares/Elixir/sequence-of-non-squares.ex similarity index 100% rename from Task/Sequence-of-non-squares/Elixir/sequence-of-non-squares.elixir rename to Task/Sequence-of-non-squares/Elixir/sequence-of-non-squares.ex diff --git a/Task/Sequence-of-non-squares/Euphoria/sequence-of-non-squares.euphoria b/Task/Sequence-of-non-squares/Euphoria/sequence-of-non-squares.eu similarity index 100% rename from Task/Sequence-of-non-squares/Euphoria/sequence-of-non-squares.euphoria rename to Task/Sequence-of-non-squares/Euphoria/sequence-of-non-squares.eu diff --git a/Task/Sequence-of-non-squares/Julia/sequence-of-non-squares.julia b/Task/Sequence-of-non-squares/Julia/sequence-of-non-squares.jl similarity index 100% rename from Task/Sequence-of-non-squares/Julia/sequence-of-non-squares.julia rename to Task/Sequence-of-non-squares/Julia/sequence-of-non-squares.jl diff --git a/Task/Sequence-of-non-squares/Kotlin/sequence-of-non-squares.kotlin b/Task/Sequence-of-non-squares/Kotlin/sequence-of-non-squares.kts similarity index 100% rename from Task/Sequence-of-non-squares/Kotlin/sequence-of-non-squares.kotlin rename to Task/Sequence-of-non-squares/Kotlin/sequence-of-non-squares.kts diff --git a/Task/Sequence-of-non-squares/OCaml/sequence-of-non-squares.ocaml b/Task/Sequence-of-non-squares/OCaml/sequence-of-non-squares.ml similarity index 100% rename from Task/Sequence-of-non-squares/OCaml/sequence-of-non-squares.ocaml rename to Task/Sequence-of-non-squares/OCaml/sequence-of-non-squares.ml diff --git a/Task/Sequence-of-non-squares/Oberon-07/sequence-of-non-squares.oberon b/Task/Sequence-of-non-squares/Oberon-07/sequence-of-non-squares.oberon new file mode 100644 index 0000000000..adb971807a --- /dev/null +++ b/Task/Sequence-of-non-squares/Oberon-07/sequence-of-non-squares.oberon @@ -0,0 +1,39 @@ +MODULE SequenceOfNonSquares; + (* check values of the function: f(n) = n + floor(1/2 + sqrt(n)) *) + (* are not squares - translation of the Algol W sample *) + + IMPORT Math, Out; + + VAR noSquares : BOOLEAN; + n, fn, rn : INTEGER; + + (* function suspected to not return a square *) + PROCEDURE f( n : INTEGER ) : INTEGER ; + BEGIN + RETURN n + FLOOR( 0.5 + Math.sqrt( FLT( n ) ) ) + END f; + +BEGIN + (* first 22 values of f *) + FOR n := 1 TO 22 DO + Out.String( " ");Out.Int( f( n ), 0 ) + END; + Out.Ln; + + (* check f(n) does not produce a square for n in 1..1 000 000 *) + noSquares := TRUE; + FOR n := 1 TO 1000000 DO + fn := f( n ); + rn := FLOOR( Math.sqrt( FLT( fn ) ) ); + IF rn * rn = fn THEN + Out.String( "Found square at: " );Out.Int( n, 0 );Out.Ln; + noSquares := FALSE + END + END; + + IF noSquares + THEN Out.String( "f(n) did not produce a square in 1 .. 1 000 000" ) + ELSE Out.String( "f(n) produced a square" ) + END; + Out.Ln +END SequenceOfNonSquares. diff --git a/Task/Sequence-of-non-squares/Pluto/sequence-of-non-squares.pluto b/Task/Sequence-of-non-squares/Pluto/sequence-of-non-squares.pluto new file mode 100644 index 0000000000..079745d243 --- /dev/null +++ b/Task/Sequence-of-non-squares/Pluto/sequence-of-non-squares.pluto @@ -0,0 +1,33 @@ +do ---check values of the function: f(n) = n + floor(1/2 + sqrt(n)) + -- are not squares - translation of the Algol W sample + + local fmt = require( "fmt" ) -- RC Pluto formatting library + + -- function suspected to not return a square + local function f( n : number ) : number + return n + math.floor( 0.5 + math.sqrt( n ) ) + end + + -- first 22 values of f + for n = 1, 22 do + fmt.write( " %d", f( n ) ) + end + fmt.write( "\n" ) + + -- check f(n) does not produce a square for n in 1..1 000 000 + local noSquares = true + for n = 1, 1_000_000 do + local fn = f( n ) + local rn = math.floor( math.sqrt( fn ) ) + if rn * rn == fn then + print( "Found square at: " .. n ) + noSquares = false + end + end + + if noSquares + then print( "f(n) did not produce a square in 1 .. 1 000 000" ) + else print( "f(n) produced a square" ) + end + +end diff --git a/Task/Sequence-of-non-squares/PowerShell/sequence-of-non-squares-1.psh b/Task/Sequence-of-non-squares/PowerShell/sequence-of-non-squares-1.ps1 similarity index 100% rename from Task/Sequence-of-non-squares/PowerShell/sequence-of-non-squares-1.psh rename to Task/Sequence-of-non-squares/PowerShell/sequence-of-non-squares-1.ps1 diff --git a/Task/Sequence-of-non-squares/PowerShell/sequence-of-non-squares-2.psh b/Task/Sequence-of-non-squares/PowerShell/sequence-of-non-squares-2.ps1 similarity index 100% rename from Task/Sequence-of-non-squares/PowerShell/sequence-of-non-squares-2.psh rename to Task/Sequence-of-non-squares/PowerShell/sequence-of-non-squares-2.ps1 diff --git a/Task/Sequence-of-non-squares/PowerShell/sequence-of-non-squares-3.psh b/Task/Sequence-of-non-squares/PowerShell/sequence-of-non-squares-3.ps1 similarity index 100% rename from Task/Sequence-of-non-squares/PowerShell/sequence-of-non-squares-3.psh rename to Task/Sequence-of-non-squares/PowerShell/sequence-of-non-squares-3.ps1 diff --git a/Task/Sequence-of-non-squares/Python/sequence-of-non-squares-1.py b/Task/Sequence-of-non-squares/Python/sequence-of-non-squares-1.py index 4995266e94..0adaac1f39 100644 --- a/Task/Sequence-of-non-squares/Python/sequence-of-non-squares-1.py +++ b/Task/Sequence-of-non-squares/Python/sequence-of-non-squares-1.py @@ -1,20 +1,11 @@ ->>> from math import floor, sqrt ->>> def non_square(n): - return n + floor(1/2 + sqrt(n)) +from math import floor +from math import sqrt ->>> # first 22 values has no squares: ->>> print(*map(non_square, range(1, 23))) -2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27 +def non_square(n): + return n + floor(0.5 + sqrt(n)) ->>> # The following check shows no squares up to one million: ->>> def is_square(n): - return sqrt(n).is_integer() +first_22 = [non_square(i) for i in range(1, 23)] +print(first_22) ->>> non_squares = map(non_square, range(1, 10 ** 6)) ->>> next(filter(is_square, non_squares)) -StopIteration Traceback (most recent call last) - in () - 1 non_squares = map(non_square, range(1, 10 ** 6)) -----> 2 next(filter(is_square, non_squares)) - -StopIteration: +first_million = (non_square(i) for i in range(1, 10**6)) +assert not any(sqrt(i).is_integer() for i in first_million) diff --git a/Task/Sequence-of-non-squares/Rust/sequence-of-non-squares.rust b/Task/Sequence-of-non-squares/Rust/sequence-of-non-squares.rs similarity index 100% rename from Task/Sequence-of-non-squares/Rust/sequence-of-non-squares.rust rename to Task/Sequence-of-non-squares/Rust/sequence-of-non-squares.rs diff --git a/Task/Sequence-of-non-squares/Scheme/sequence-of-non-squares.ss b/Task/Sequence-of-non-squares/Scheme/sequence-of-non-squares.scm similarity index 100% rename from Task/Sequence-of-non-squares/Scheme/sequence-of-non-squares.ss rename to Task/Sequence-of-non-squares/Scheme/sequence-of-non-squares.scm diff --git a/Task/Sequence-of-primes-by-trial-division/ALGOL-60/sequence-of-primes-by-trial-division.alg b/Task/Sequence-of-primes-by-trial-division/ALGOL-60/sequence-of-primes-by-trial-division.alg new file mode 100644 index 0000000000..960870975a --- /dev/null +++ b/Task/Sequence-of-primes-by-trial-division/ALGOL-60/sequence-of-primes-by-trial-division.alg @@ -0,0 +1,46 @@ +begin + +comment - return n mod m; +integer procedure mod(n, m); + value n, m; integer n, m; +begin + mod := n - entier(n / m) * m; +end; + +integer i, k, m, n, sq, nprimes; +boolean divisible; + +nprimes := 20; +outstring(1,"Showing first"); +outinteger(1, nprimes); +outstring(1,"prime numbers\n"); +begin + integer array p[1:nprimes]; + comment - initialize p with first (and only even) prime; + p[1] := 2; + outinteger(1, p[1]); + i := 1; comment - count of primes found so far; + k := 1; comment - index of largest prime <= sqrt of n; + n := 3; comment - current number being checked; + for i := i while i < nprimes do + begin + sq := p[k] * p[k]; + if sq <= n then k := k + 1; + divisible := false; + m := 2; comment - index of possible divisors; + for m := m while m <= k and not divisible do + begin + if mod(n, p[m]) = 0 then divisible := true; + m := m + 1; + end; + if not divisible then + begin + i := i + 1; + p[i] := n; + outinteger(1, n); + end; + n := n + 2; + end; + end; + +end diff --git a/Task/Sequence-of-primes-by-trial-division/ALGOL-68/sequence-of-primes-by-trial-division.alg b/Task/Sequence-of-primes-by-trial-division/ALGOL-68/sequence-of-primes-by-trial-division.alg index 54d6c273dc..35f8f5e84a 100644 --- a/Task/Sequence-of-primes-by-trial-division/ALGOL-68/sequence-of-primes-by-trial-division.alg +++ b/Task/Sequence-of-primes-by-trial-division/ALGOL-68/sequence-of-primes-by-trial-division.alg @@ -11,12 +11,12 @@ PROC is prime = ( ISPRIMEINT p )BOOL: FI; # end of code from the primality by trial division task # -# returns an array of n primes >= start # -PROC prime sequence = ( INT start, INT n )[]INT: +# returns an array of n primes >= start value # +PROC prime sequence = ( INT start value, INT n )[]INT: BEGIN [ n ]INT seq; INT prime count := 0; - FOR p FROM start WHILE prime count < n DO + FOR p FROM start value WHILE prime count < n DO IF is prime( p ) THEN prime count +:= 1; seq[ prime count ] := p diff --git a/Task/Sequence-of-primes-by-trial-division/Ada/sequence-of-primes-by-trial-division.ada b/Task/Sequence-of-primes-by-trial-division/Ada/sequence-of-primes-by-trial-division.adb similarity index 100% rename from Task/Sequence-of-primes-by-trial-division/Ada/sequence-of-primes-by-trial-division.ada rename to Task/Sequence-of-primes-by-trial-division/Ada/sequence-of-primes-by-trial-division.adb diff --git a/Task/Sequence-of-primes-by-trial-division/Agena/sequence-of-primes-by-trial-division.agena b/Task/Sequence-of-primes-by-trial-division/Agena/sequence-of-primes-by-trial-division.agena new file mode 100644 index 0000000000..01a42e41f5 --- /dev/null +++ b/Task/Sequence-of-primes-by-trial-division/Agena/sequence-of-primes-by-trial-division.agena @@ -0,0 +1,35 @@ +scope # get sequences of primes using trial division + + # returns true if n is prime, false otherwise + local constant is_prime := proc( n :: number ) :: boolean + local result := n = 2 or ( odd n and n > 1 ); + for k from 3 to entier sqrt( n ) by 2 while result do + result := n mod k <> 0 + od; + return result + end; + + # returns the sequence of primes between p_start and p_end + local constant prime_sequence := proc( p_start :: number, p_end :: number ) :: sequence + local constant result := seq(); + for p from p_start to p_end do + if is_prime( p ) then result[ size result + 1 ] := p fi; + od; + return result + end; + + # test prime_sequence + local test_sequence, p_count; + test_sequence, p_count := prime_sequence( -9, 150 ), 0; + for p from 1 to size test_sequence do + printf( " %3d", test_sequence[ p ] ); + p_count +:= 1; if p_count mod 20 = 0 then print() fi + od; + print( " ..." ); + test_sequence, p_count := prime_sequence( 410, 550 ), 0; + for p from 1 to size test_sequence do + printf( " %3d", test_sequence[ p ] ); + p_count +:= 1; if p_count mod 20 = 0 then print() fi + od + +end diff --git a/Task/Sequence-of-primes-by-trial-division/Arturo/sequence-of-primes-by-trial-division.arturo b/Task/Sequence-of-primes-by-trial-division/Arturo/sequence-of-primes-by-trial-division.arturo index 41995c39a9..b20ba8f545 100644 --- a/Task/Sequence-of-primes-by-trial-division/Arturo/sequence-of-primes-by-trial-division.arturo +++ b/Task/Sequence-of-primes-by-trial-division/Arturo/sequence-of-primes-by-trial-division.arturo @@ -1,5 +1,5 @@ getPrimes: function [upto][ - result: new [2] + result: [2] loop range.step:2 3 upto 'x [ divisible: false loop 2..inc x/2 'z [ diff --git a/Task/Sequence-of-primes-by-trial-division/Crystal/sequence-of-primes-by-trial-division.crystal b/Task/Sequence-of-primes-by-trial-division/Crystal/sequence-of-primes-by-trial-division.cr similarity index 100% rename from Task/Sequence-of-primes-by-trial-division/Crystal/sequence-of-primes-by-trial-division.crystal rename to Task/Sequence-of-primes-by-trial-division/Crystal/sequence-of-primes-by-trial-division.cr diff --git a/Task/Sequence-of-primes-by-trial-division/EDSAC-order-code/sequence-of-primes-by-trial-division.edsac b/Task/Sequence-of-primes-by-trial-division/EDSAC-order-code/sequence-of-primes-by-trial-division.edsac index ff3d80b08f..804567152c 100644 --- a/Task/Sequence-of-primes-by-trial-division/EDSAC-order-code/sequence-of-primes-by-trial-division.edsac +++ b/Task/Sequence-of-primes-by-trial-division/EDSAC-order-code/sequence-of-primes-by-trial-division.edsac @@ -2,8 +2,9 @@ [EDSAC program, Initial Orders 2.] [Division is done implicitly by the use of wheels. One wheel for each possible prime divisor, up to an editable limit.] +[2024-12-25 Fixed bug in print subroutine (did not affect RC output)] - T51K [G parameter: print subroutine, 54 locations.] + T51K [G parameter: print subroutine, 52 locations.] P56F [must be even address] T47K [M parameter: main routine.] P110F [must be even address] @@ -149,11 +150,11 @@ [Modified library subroutine P7.] [Prints signed integer; up to 10 digits, left-justified.] [Input: 0D = integer,] -[54 locations. Load at even address. Workspace 4D.] +[52 locations. Load at even address. Workspace 4D.] E25KTG - GKA3FT42@A49@T31@ADE10@T31@A48@T31@SDTDH44#@NDYFLDT4DS43@ - TFH17@S17@A43@G23@UFS43@T1FV4DAFG50@SFLDUFXFOFFFSFL4FT4D - A49@T31@A1FA43@G20@XFP1024FP610D@524D!FO46@O26@XFSFL8FT4DE39@ + GKA3FT42@A47@T31@ADE10@T31@A46@T31@SDTDH44#@NDYFLDT4DS43@TF + H17@S17@A43@G23@UFS43@T1FV4DAFG48@SFLDUFXFOFFFSFL4FT4DA47@ + T31@A1FA43@G20@XFT44#ZPFT43ZP1024FP610D@524DO26@XFSFL8FT4DE39@ [========================= M parameter again ===============================] E25KTM diff --git a/Task/Sequence-of-primes-by-trial-division/EasyLang/sequence-of-primes-by-trial-division.easy b/Task/Sequence-of-primes-by-trial-division/EasyLang/sequence-of-primes-by-trial-division.easy index 62bcc99d7a..260f62bfde 100644 --- a/Task/Sequence-of-primes-by-trial-division/EasyLang/sequence-of-primes-by-trial-division.easy +++ b/Task/Sequence-of-primes-by-trial-division/EasyLang/sequence-of-primes-by-trial-division.easy @@ -1,21 +1,14 @@ -func prime n . - if n mod 2 = 0 and n > 2 - return 0 - . - i = 3 - while i <= sqrt n - if n mod i = 0 - return 0 - . - i += 2 +fastfunc isprim num . + i = 2 + while i <= sqrt num + if num mod i = 0 : return 0 + i += 1 . return 1 . -proc primeSequ first last . sequ[] . +proc primeSequ first last &sequ[] . for i = first to last - if prime i = 1 - sequ[] &= i - . + if isprim i = 1 : sequ[] &= i . . primeSequ 2 100 seq[] diff --git a/Task/Sequence-of-primes-by-trial-division/Elena/sequence-of-primes-by-trial-division.elena b/Task/Sequence-of-primes-by-trial-division/Elena/sequence-of-primes-by-trial-division.elena index 4e0def3ce8..cbd167b977 100644 --- a/Task/Sequence-of-primes-by-trial-division/Elena/sequence-of-primes-by-trial-division.elena +++ b/Task/Sequence-of-primes-by-trial-division/Elena/sequence-of-primes-by-trial-division.elena @@ -8,7 +8,7 @@ isPrime = Primes = (n => new Range(2, n - 2).filterBy(isPrime)); -public program() +public Program() { - console.printLine(Primes(100)) + Console.printLine(Primes(100)) } diff --git a/Task/Sequence-of-primes-by-trial-division/Elixir/sequence-of-primes-by-trial-division.elixir b/Task/Sequence-of-primes-by-trial-division/Elixir/sequence-of-primes-by-trial-division.ex similarity index 100% rename from Task/Sequence-of-primes-by-trial-division/Elixir/sequence-of-primes-by-trial-division.elixir rename to Task/Sequence-of-primes-by-trial-division/Elixir/sequence-of-primes-by-trial-division.ex diff --git a/Task/Sequence-of-primes-by-trial-division/Julia/sequence-of-primes-by-trial-division.julia b/Task/Sequence-of-primes-by-trial-division/Julia/sequence-of-primes-by-trial-division.jl similarity index 100% rename from Task/Sequence-of-primes-by-trial-division/Julia/sequence-of-primes-by-trial-division.julia rename to Task/Sequence-of-primes-by-trial-division/Julia/sequence-of-primes-by-trial-division.jl diff --git a/Task/Sequence-of-primes-by-trial-division/Kotlin/sequence-of-primes-by-trial-division.kotlin b/Task/Sequence-of-primes-by-trial-division/Kotlin/sequence-of-primes-by-trial-division.kts similarity index 100% rename from Task/Sequence-of-primes-by-trial-division/Kotlin/sequence-of-primes-by-trial-division.kotlin rename to Task/Sequence-of-primes-by-trial-division/Kotlin/sequence-of-primes-by-trial-division.kts diff --git a/Task/Sequence-of-primes-by-trial-division/OCaml/sequence-of-primes-by-trial-division.ocaml b/Task/Sequence-of-primes-by-trial-division/OCaml/sequence-of-primes-by-trial-division.ml similarity index 100% rename from Task/Sequence-of-primes-by-trial-division/OCaml/sequence-of-primes-by-trial-division.ocaml rename to Task/Sequence-of-primes-by-trial-division/OCaml/sequence-of-primes-by-trial-division.ml diff --git a/Task/Sequence-of-primes-by-trial-division/PascalABC.NET/sequence-of-primes-by-trial-division.pas b/Task/Sequence-of-primes-by-trial-division/PascalABC.NET/sequence-of-primes-by-trial-division.pas new file mode 100644 index 0000000000..b30e4b8816 --- /dev/null +++ b/Task/Sequence-of-primes-by-trial-division/PascalABC.NET/sequence-of-primes-by-trial-division.pas @@ -0,0 +1,4 @@ +## +function IsPrime(n: integer) := (2..n.Sqrt.Trunc).All(i -> n.NotDivs(i)); + +(2..100).Where(IsPrime).Println diff --git a/Task/Sequence-of-primes-by-trial-division/Pluto/sequence-of-primes-by-trial-division.pluto b/Task/Sequence-of-primes-by-trial-division/Pluto/sequence-of-primes-by-trial-division.pluto new file mode 100644 index 0000000000..2184ebfaa7 --- /dev/null +++ b/Task/Sequence-of-primes-by-trial-division/Pluto/sequence-of-primes-by-trial-division.pluto @@ -0,0 +1,29 @@ +do -- get sequences of primes using trial division + + local fmt = require( "fmt" ) -- RC formatting module + + -- returns true if n is prime, false otherwise + local function isPrime( n : number ) : boolean + local result : boolean = n == 2 or ( n % 2 == 1 and n > 1 ) + for k = 3, math.floor( math.sqrt( n ) ), 2 do + if not result then break end + result = n % k != 0 + end + return result + end + + -- returns the sequence of primes between pStart and pEnd + local function primeSequence( pStart : number, pEnd : number ) : table + local result : table = {} + for p = pStart, pEnd do + if isPrime( p ) then result:insert( p ) end + end + return result + end + + -- test primeSequence + fmt.tprint( " %3d", primeSequence( -9, 174 ), 20, "", "" ) + print( " ..." ) + fmt.tprint( " %3d", primeSequence( 410, 550 ), 20, "", "" ) + +end diff --git a/Task/Sequence-of-primes-by-trial-division/PowerShell/sequence-of-primes-by-trial-division.psh b/Task/Sequence-of-primes-by-trial-division/PowerShell/sequence-of-primes-by-trial-division.ps1 similarity index 100% rename from Task/Sequence-of-primes-by-trial-division/PowerShell/sequence-of-primes-by-trial-division.psh rename to Task/Sequence-of-primes-by-trial-division/PowerShell/sequence-of-primes-by-trial-division.ps1 diff --git a/Task/Sequence-of-primes-by-trial-division/REXX/sequence-of-primes-by-trial-division-1.rexx b/Task/Sequence-of-primes-by-trial-division/REXX/sequence-of-primes-by-trial-division-1.rexx deleted file mode 100644 index 2874c730e3..0000000000 --- a/Task/Sequence-of-primes-by-trial-division/REXX/sequence-of-primes-by-trial-division-1.rexx +++ /dev/null @@ -1,18 +0,0 @@ -/*REXX program lists a sequence of primes by testing primality by trial division. */ -parse arg n . /*get optional number of primes to find*/ -if n=='' | n=="," then n= 26 /*Not specified? Then use the default.*/ -tell= (n>0); n= abs(n) /*Is N negative? Then don't display.*/ -@.1=2; if tell then say right(@.1, 9) /*display 2 as a special prime case. */ -#=1 /*# is number of primes found (so far)*/ - /* [↑] N: default lists up to 101 #s.*/ - do j=3 by 2 while #0); N= abs(N) /*N is negative? Then don't display. */ -@.1=2; @.2=3; @.3=5; @.4=7; @.5=11; @.6=13; #= 5; s= @.# + 2 - /* [↑] is the number of low primes.*/ - do p=1 for # while p<=N /* [↓] find primes, and maybe show 'em*/ - if tell then say right(@.p, 9) /*display some pre─defined low primes. */ - !.p= @.p**2 /*also compute the squared value of P. */ - end /*p*/ /* [↑] allows faster loop (below). */ - /* [↓] N: default lists up to 101 #s.*/ - do j=s by 2 while # $n mod $] -> if <~|[<|=0>]> -> $n ! +end ifPrime + +primes templates + [2..$ -> ifPrime] ! +end primes + +100 -> primes -> '$; +'! diff --git a/Task/Sequence-of-primes-by-trial-division/Uiua/sequence-of-primes-by-trial-division.uiua b/Task/Sequence-of-primes-by-trial-division/Uiua/sequence-of-primes-by-trial-division.uiua new file mode 100644 index 0000000000..e33d2f166a --- /dev/null +++ b/Task/Sequence-of-primes-by-trial-division/Uiua/sequence-of-primes-by-trial-division.uiua @@ -0,0 +1 @@ +∧(⨬◌˜⊂>0/↧◡˜◿)↘2⇡ ⊙[2 3 5] 30 diff --git a/Task/Sequence-of-primorial-primes/AWK/sequence-of-primorial-primes.awk b/Task/Sequence-of-primorial-primes/AWK/sequence-of-primorial-primes.awk new file mode 100644 index 0000000000..04efab2f01 --- /dev/null +++ b/Task/Sequence-of-primorial-primes/AWK/sequence-of-primorial-primes.awk @@ -0,0 +1,37 @@ +# syntax: GAWK -f SEQUENCE_OF_PRIMORIAL_PRIMES.AWK +# converted from Julia +BEGIN { + n = 8 + printf("The first %d primorial indices sequentially producing primorial primes are: 1",n) + primorial = 1 + count = 1 + p = 3 + prod = 2 + while (1) { + if (is_prime(p)) { + prod *= p + primorial++ + if (is_prime(prod+1) || is_prime(prod-1)) { + printf(" %d",primorial) + if (++count == n) { + break + } + } + } + p += 2 + } + exit(0) +} +function is_prime(n, d) { + d = 5 + if (n < 2) { return(0) } + if (n % 2 == 0) { return(n == 2) } + if (n % 3 == 0) { return(n == 3) } + while (d*d <= n) { + if (n % d == 0) { return(0) } + d += 2 + if (n % d == 0) { return(0) } + d += 4 + } + return(1) +} diff --git a/Task/Sequence-of-primorial-primes/FutureBasic/sequence-of-primorial-primes.basic b/Task/Sequence-of-primorial-primes/FutureBasic/sequence-of-primorial-primes.basic new file mode 100644 index 0000000000..3a4d71efa0 --- /dev/null +++ b/Task/Sequence-of-primorial-primes/FutureBasic/sequence-of-primorial-primes.basic @@ -0,0 +1,230 @@ +// ------------------------------------------------------------ +// Sequence of primorial primes +// +// Using FutureBasic 7.0.37 +// November 2025, R.W. +// ------------------------------------------------------------ + +include "gmp.incl" + +// should be enough for the task plus a little more + +_kPrimeLimit = 18000 // sieve limit for prime values +_kMaxPrimes = 8000 // max # of primes we store +_kPrimeReps = 25 // Miller–Rabin repetitions + +CFTimeInterval tim + +// Global mpz_t bigints reused everywhere +mpz_t gP // current primorial p_n# +mpz_t gTwo64 // 2^64 threshold for stricter primality + +// State for primorial sequence +long gPrimIndex // current n in p_n# (Wren's i), starting at 0 +long gSeqCount // how many sequence entries we've been through + +// Prime table +long gPrimes( _kMaxPrimes - 1 ) +long gPrimeCount + +// ----------------------------------------------------------- +// Helper: Abbreviate big numeric CFString: head...tail +// ----------------------------------------------------------- +local fn AbbrevString( s as CFStringRef, head as int, ¬ + tail as int ) as CFStringRef + + if s == 0 then RETURN @"" + CFStringRef a, b, out + int nLen + nLen = len( s ) + if nLen <= head + tail then RETURN s + a = left( s, head ) + b = right( s, tail ) + out = @"" + out = concat( a, @"...", b ) +end fn = out + +// ----------------------------------------------------------- +// Helper: Get mpz_t result and abbreviate if > 43 digits +// ----------------------------------------------------------- +local fn Abbrev( ts as mpz_t ) as CFStringRef + CFStringRef result + int nLen + result = fn mpz_cf2( ts ) // FB wrapper mpz_t → CFString (base 10) + nLen = len( result ) + if nLen <= 43 then RETURN result + result = fn AbbrevString( result, 20, 20 ) +end fn = result + +// ------------------------------------------------------------ +// Helper: fill prime table up to _kPrimeLimit +// ------------------------------------------------------------ +local fn InitPrimes + Boolean isComposite( _kPrimeLimit ) + long i, j, count + for i = 0 to _kPrimeLimit + isComposite(i) = _false + next + isComposite(0) = _true + isComposite(1) = _true + count = 0 + for i = 2 to _kPrimeLimit + if isComposite(i) == _false + if count < _kMaxPrimes + gPrimes(count) = i + end if + count++ + j = i + i + while j <= _kPrimeLimit + isComposite(j) = _true + j = j + i + wend + end if + next + if count > _kMaxPrimes + count = _kMaxPrimes + end if + gPrimeCount = count +end fn + +// ------------------------------------------------------------ +// Helper: decimal digits of mpz_t, with mpz_sizeinbase fix +// ------------------------------------------------------------ +local fn MPZDecimalDigits( x as mpz_t ) as long + long s + mpz_t pow10 + if fn mpz_sgn( x ) == 0 then RETURN 1 + s = fn mpz_sizeinbase( x, 10 ) + // Sometimes mpz_sizeinbase gives one digit too many, so fix + // (see GMP 6.3.0 manual page 45) + mpz_init( pow10 ) + fn mpz_ui_pow_ui( pow10, 10, s - 1 ) + if fn mpz_cmp( x, pow10 ) < 0 + s-- + end if + mpz_clear( pow10 ) +end fn = s + +// ------------------------------------------------------------ +// Core generator: print next `batchSize` primorial-prime entries +// (continues from global gP, gPrimIndex, gSeqCount) +// ------------------------------------------------------------ +local fn PrintNextPrimorialBatch( batchSize as long ) + mpz_t q + long batchPrinted + int signIdx + int isPrime + int thresh + long ndig + CFStringRef signStr + CFStringRef vStr + CFStringRef pnStr + + mpz_init( q ) + batchPrinted = 0 + + while batchPrinted < batchSize + if fn mpz_cmp( gP, gTwo64 ) < 0 + thresh = 1 + else + thresh = 0 + end if + // Test p_n# - 1, then p_n# + 1 + for signIdx = 0 to 1 + if signIdx == 0 + fn mpz_sub_ui( q, gP, 1 ) // p_n# - 1 + signStr = @"-" + else + fn mpz_add_ui( q, gP, 1 ) // p_n# + 1 + signStr = @"+" + end if + + isPrime = fn mpz_probab_prime_p( q, _kPrimeReps ) + if isPrime > thresh + gSeqCount++ + ndig = fn MPZDecimalDigits( q ) + vStr = fn Abbrev( q ) + pnStr = fn CFStringCreateWithFormat( 0, 0, @"p%4ld#", gPrimIndex ) + if ndig > 43 + printf @"%2ld: %@ %@ 1 = %@ (%ld digits)", ¬ + gSeqCount, pnStr, signStr, vStr, ndig + else + printf @"%2ld: %5@ %@ 1 = %@", ¬ + gSeqCount, pnStr, signStr, vStr + end if + batchPrinted++ + if batchPrinted >= batchSize + exit for + end if + end if + next signIdx + // Advance to next primorial: p_(n+1)# = p_n# * nextPrime + fn mpz_mul_ui( gP, gP, gPrimes( gPrimIndex ) ) + gPrimIndex++ + if gPrimIndex >= gPrimeCount + print @"\nRan out of prime table." + batchPrinted = batchSize + button 2, NO // sorry, no more next + end if + wend + mpz_clear( q ) +end fn + +// ------------------------------------------------------------ +// More_PP +// Show the next 10 primorial-prime entries +// ------------------------------------------------------------ +void local fn More_PP + tim = fn CACurrentMediaTime + fn PrintNextPrimorialBatch( 10 ) + printf @"\nElapsed time: %.3f secs\n", ( fn CACurrentMediaTime - tim ) +end fn + +// ------------------------------------------------------------ +// Main — compute the first 10 primorial primes +// ------------------------------------------------------------ +local fn Main + fn InitPrimes // Init prime table and bigints once + mpz_init( gP ) + mpz_init( gTwo64 ) + fn mpz_set_ui( gP, 1 ) // p0# = 1 + fn mpz_ui_pow_ui( gTwo64, 2, 64 ) // 2^64 threshold + gPrimIndex = 0 + gSeqCount = 0 + print @"\nThe first 10 Sequence of primorial primes:\n" + tim = fn CACurrentMediaTime + fn PrintNextPrimorialBatch( 10 ) + printf @"\nElapsed time: %.3f ms", ( fn CACurrentMediaTime - tim ) * 1000 + print @"\nClick [Next] for the next sequence of primorial primes.\n" +end fn + +// ------------------------------------------------------------ +// Dialog handler +// ------------------------------------------------------------ +void local fn DoDialog( ev as long, tag as long, wnd as long, obj as CFTypeRef ) + select ( ev ) + case _btnClick + select ( tag ) + case 2 + fn More_PP + end select + + case _windowShouldClose + // clear any uncleared mpz + mpz_clear( gP ) + mpz_clear( gTwo64 ) + end + end select +end fn + +on dialog fn DoDialog + +// ------------------------------------------------------------ +// Main +// ------------------------------------------------------------ +window 1, @"Sequence of primorial primes", (0,0,620,500) +button 2, YES,, @"Next", (500,20,100,20),,, 1 + +fn Main + +HandleEvents diff --git a/Task/Sequence-of-primorial-primes/Julia/sequence-of-primorial-primes.julia b/Task/Sequence-of-primorial-primes/Julia/sequence-of-primorial-primes.jl similarity index 100% rename from Task/Sequence-of-primorial-primes/Julia/sequence-of-primorial-primes.julia rename to Task/Sequence-of-primorial-primes/Julia/sequence-of-primorial-primes.jl diff --git a/Task/Sequence-of-primorial-primes/Kotlin/sequence-of-primorial-primes.kotlin b/Task/Sequence-of-primorial-primes/Kotlin/sequence-of-primorial-primes.kts similarity index 100% rename from Task/Sequence-of-primorial-primes/Kotlin/sequence-of-primorial-primes.kotlin rename to Task/Sequence-of-primorial-primes/Kotlin/sequence-of-primorial-primes.kts diff --git a/Task/Sequence-of-primorial-primes/Maxima/sequence-of-primorial-primes.maxima b/Task/Sequence-of-primorial-primes/Maxima/sequence-of-primorial-primes.maxima new file mode 100644 index 0000000000..5709920204 --- /dev/null +++ b/Task/Sequence-of-primorial-primes/Maxima/sequence-of-primorial-primes.maxima @@ -0,0 +1,11 @@ +primorial(n) := block(p: 2, res: 1, thru n do(res: p*res, p: next_prime(p)), res)$ + +block(count: 0, n: 1, while count < 20 do( + pn: primorial(n), + if primep(pn+1) or primep(pn-1) then block( + sprint(n), + count: count+1 + ), + n: n+1 + ) +)$ diff --git a/Task/Sequence-of-primorial-primes/Oberon-07/sequence-of-primorial-primes-1.oberon b/Task/Sequence-of-primorial-primes/Oberon-07/sequence-of-primorial-primes-1.oberon new file mode 100644 index 0000000000..4d6241f5d0 --- /dev/null +++ b/Task/Sequence-of-primorial-primes/Oberon-07/sequence-of-primorial-primes-1.oberon @@ -0,0 +1,8 @@ +import java.math.BigInteger; + +public class BMath_BigIntegerStruct +{ + public BigInteger v; + public BMath_BigIntegerStruct( int n ){ v = BigInteger.valueOf( n ); } + public BMath_BigIntegerStruct( BigInteger n ){ v = n; } +} // BMath_BigIntegerStruct diff --git a/Task/Sequence-of-primorial-primes/Oberon-07/sequence-of-primorial-primes-2.oberon b/Task/Sequence-of-primorial-primes/Oberon-07/sequence-of-primorial-primes-2.oberon new file mode 100644 index 0000000000..326c555755 --- /dev/null +++ b/Task/Sequence-of-primorial-primes/Oberon-07/sequence-of-primorial-primes-2.oberon @@ -0,0 +1,32 @@ +// interface between Oberon-07 and Java.math.BigInteger + +import java.math.BigInteger; + +public class BMath +{ + + private BMath(){} // BMath cannot be instantiated + + public static BMath_BigIntegerStruct BValueOf( int v ){ return new BMath_BigIntegerStruct( v ); } + + public static BMath_BigIntegerStruct addOne( BMath_BigIntegerStruct b ) + { + return new BMath_BigIntegerStruct( b.v.add( BigInteger.ONE ) ); + } // addOne + + public static BMath_BigIntegerStruct subtractOne( BMath_BigIntegerStruct b ) + { + return new BMath_BigIntegerStruct( b.v.subtract( BigInteger.ONE ) ); + } // subtractOne + + public static BMath_BigIntegerStruct multiplyI( BMath_BigIntegerStruct b, int v ) + { + return new BMath_BigIntegerStruct( b.v.multiply( BigInteger.valueOf( v ) ) ); + } // multiplyI + + public static boolean isProbablePrimeI( BMath_BigIntegerStruct b, int certainty ) + { + return b.v.isProbablePrime( certainty ); + } // isProbablePrime + +} // BMath diff --git a/Task/Sequence-of-primorial-primes/Oberon-07/sequence-of-primorial-primes-3.oberon b/Task/Sequence-of-primorial-primes/Oberon-07/sequence-of-primorial-primes-3.oberon new file mode 100644 index 0000000000..7800326b21 --- /dev/null +++ b/Task/Sequence-of-primorial-primes/Oberon-07/sequence-of-primorial-primes-3.oberon @@ -0,0 +1,12 @@ +DEFINITION BMath; (* Interface to java.math.BigInteger *) + + TYPE BigIntegerStruct = RECORD END; + RefBigInteger = POINTER TO BigIntegerStruct; + + PROCEDURE BValueOf( v : INTEGER ) : RefBigInteger; + PROCEDURE addOne( b : RefBigInteger ) : RefBigInteger; + PROCEDURE subtractOne( b : RefBigInteger ) : RefBigInteger; + PROCEDURE multiplyI( b : RefBigInteger; v : INTEGER ) : RefBigInteger; + PROCEDURE isProbablePrimeI( b : RefBigInteger; certainty : INTEGER ) : BOOLEAN; + +END BMath. diff --git a/Task/Sequence-of-primorial-primes/Oberon-07/sequence-of-primorial-primes-4.oberon b/Task/Sequence-of-primorial-primes/Oberon-07/sequence-of-primorial-primes-4.oberon new file mode 100644 index 0000000000..853e8b5992 --- /dev/null +++ b/Task/Sequence-of-primorial-primes/Oberon-07/sequence-of-primorial-primes-4.oberon @@ -0,0 +1,32 @@ +MODULE PrimorialPrimeSequence; (* find some primorial primes *) + (* - primes that are p - 1 or p + 1 *) + (* for some primorial p *) + IMPORT BMath, Out, Primes; + + CONST maxPrime = 2000000; + VAR pCount, n, pPos : INTEGER; + prime : ARRAY maxPrime + 1 OF BOOLEAN; + pn : BMath.RefBigInteger; + +BEGIN + Primes.sieve( prime ); (* construct a sieve of primes up to maxPrime *) + (* find the sequence members *) + pPos := 1; + pn := BMath.BValueOf( 1 ); + pCount := 0; + n := 0; + WHILE pCount < 20 DO + INC( n, 1 ); + (* find the next prime *) + IF pPos < 3 THEN INC( pPos, 1 ) ELSE INC( pPos, 2 ) END; + WHILE ~ prime[ pPos ] DO INC( pPos, 2 ) END; + pn := BMath.multiplyI( pn, pPos ); + IF BMath.isProbablePrimeI( BMath.subtractOne( pn ), 1 ) + OR BMath.isProbablePrimeI( BMath.addOne( pn ), 1 ) + THEN + INC( pCount, 1 ); + Out.String( " " );Out.Int( n, 1 ) + END + END; + Out.Ln +END PrimorialPrimeSequence. diff --git a/Task/Sequence-of-primorial-primes/Phix/sequence-of-primorial-primes.phix b/Task/Sequence-of-primorial-primes/Phix/sequence-of-primorial-primes.phix index 11f36578ba..7fbd5f202a 100644 --- a/Task/Sequence-of-primorial-primes/Phix/sequence-of-primorial-primes.phix +++ b/Task/Sequence-of-primorial-primes/Phix/sequence-of-primorial-primes.phix @@ -1,26 +1,23 @@ -(phixonline)--> - with javascript_semantics - include mpfr.e - constant limit = 9999, - flimit = iff(platform()=JS?15:20) - mpz {p,p1} = mpz_inits(2,1) - atom t0 = time() - integer found = 0, i - for n=1 to limit do - mpz_mul_si(p, p, get_prime(n)) - for i=-1 to +1 do - mpz_add_si(p1, p, i) - if mpz_prime(p1) then - integer l = mpz_sizeinbase(p,10) - string ps = iff(l>20?sprintf("%d digits",l) - :mpz_get_str(p)) - printf(1,"%d (%s) is a primorial prime\n",{n,ps}) - found += 1 - exit - end if - end for - if found>=flimit then exit end if - end for - {p,p1} = mpz_free({p,p1}) - ?elapsed(time()-t0) - - with javascript_semantics - constant limit = 15 - sequence res = repeat(0,limit) - integer found = 0, n = 1 - while found<limit do - integer k = length(factors(n,1)) - if k<=limit and res[k]=0 then - res[k] = n - found += 1 - end if - n += 1 - end while - printf(1,"The first %d terms are: %V\n",{limit,res}) - - with javascript_semantics - constant limit = iff(machine_bits()=32?58:66) - sequence found = repeat(0,limit) - integer n = 1 +with javascript_semantics +constant limit = iff(machine_bits()=32?58:66) +sequence found = repeat(0,limit) +integer n = 1 - procedure populate_found(integer i) - while found[i]=0 do - integer k = length(factors(n,1)) - if k<=limit and found[k]=0 then - found[k] = n - end if - n += 1 - end while - end procedure +procedure populate_found(integer i) + while found[i]=0 do + integer k = length(factors(n,1)) + if k<=limit and found[k]=0 then + found[k] = n + end if + n += 1 + end while +end procedure - for i=1 to limit do - sequence f = factors(i,1) - integer lf = length(f) - atom ri - if lf<=2 then ri = power(2,i-1) -- prime (or 1) - elsif lf=3 then ri = power(6,f[2]-1) -- p^2 (eg f={1,5,25}) - elsif f[2]>2 -- (see note) - and f[$] = power(f[2],lf-1) then ri = power(product(get_primes(-(lf-1))),f[2]-1) -- p^k (eg f={1,3,9,27}) - elsif lf=4 then ri = power(2,f[3]-1)*power(3,f[2]-1) -- p*q (eg f={1,2,3,6}) - else populate_found(i) ri = found[i] -- do the rest manually - end if - printf(1,"%d->%d\n",{i,ri}) - end for - - with javascript_semantics - include mpfr.e - mpz r = mpz_init(), - pn = mpz_init() - sequence rule_names = {}, - rule_counts = {} - for i=1 to 2000 do - sequence pf = prime_factors(i,true), ri, adj - integer lf = length(pf), np, p2, p3, p5, p, e - string what - if lf>10 then ?9/0 end if - if lf<=1 then what = "prime (proper rule)" - np = 1 - adj = {i} - elsif pf[$]=2 then what = "2^k (made up rule)" - np = lf-1 - p2 = {2,4,4,4,4,4,4,8,8}[np] - p3 = {2,2,2,2,4,4,4,4,4}[np] - np = {2,2,3,4,4,5,6,6,7}[np] - adj = {p2,p3} - elsif pf[$]=3 - and pf[$-1]=2 then what = "2^k*3 (made up rule)" - np = lf-1 - p2 = {3,3,4,4,4,6,6,6,6}[np] - p3 = {2,2,3,3,3,4,4,4,4}[np] - np = {2,3,3,4,5,5,6,7,8}[np] - adj = {p2,p3} - elsif lf>4 - and pf[$-1]=2 then what="2^k*p (made up rule)" - np = lf-1 - adj = {0,4} - elsif lf>4 - and pf[$]=3 - and pf[$-1]=3 - and pf[$-2]=2 then what="2^k*3^2*p (made up rule)" - np = lf-4 - p3 = {3,3,3,4,4}[np] - p5 = {2,2,2,3,3}[np] - np = {4,5,6,6,7}[np] - adj = {6,p3,p5} - elsif lf>4 - and pf[$]=3 - and pf[$-2]=3 - and pf[$-4]=2 then what="2^k*3^3*p (made up rule)" - np = lf-1 - adj = {6} - elsif lf>5 - and pf[$]>3 - and pf[$-1]=3 - and pf[$-4]=3 - and pf[2]=3 - and (pf[1]=2 or pf[$]>5) then what="2^k*3^4*p (made up rule)" - np = lf - adj = {} - elsif lf>4 - and pf[$-1]=3 - and pf[$-4]=3 - and (lf>5 or pf[$]=3) then what="[2^k]*3^(>=4)*p (made up rule)" - np = lf-1 - adj = {9,pf[$]}&reverse(pf[1..$-3]) -- <bsg> - elsif lf>=7 - and pf[$]>3 - and pf[$-1]=3 - and pf[$-2]=2 then what="2^k*3*p (made up rule)" - np = lf-1 - adj = {0,4,3} - elsif i=1440 - and pf={2,2,2,2,2,3,3,5} then what="1440 (complete fudge)" - -- nothing quite like this, nothing to build any pattern from... - np = 7 - adj = {6,5,3,2,2,2,2} - else what="general (proper rule)" - -- (note this incorporates the p^2, (p>2)^k, p*q, and p*m*q rules) - np = lf - adj = {} - end if - ri = get_primes(-np) - for j=1 to length(adj) do - integer aj = adj[j] - if aj!=0 then pf[-j] = aj end if - end for - for j=1 to np do - ri[j] = {ri[j],pf[-j]-1} - end for +with javascript_semantics +include mpfr.e +mpz r = mpz_init(), + pn = mpz_init() +sequence rule_names = {}, + rule_counts = {} +for i=1 to 2000 do + sequence pf = prime_factors(i,true), ri, adj + integer lf = length(pf), np, p2, p3, p5, p, e + string what + if lf>10 then ?9/0 end if + if lf<=1 then what = "prime (proper rule)" + np = 1 + adj = {i} + elsif pf[$]=2 then what = "2^k (made up rule)" + np = lf-1 + p2 = {2,4,4,4,4,4,4,8,8}[np] + p3 = {2,2,2,2,4,4,4,4,4}[np] + np = {2,2,3,4,4,5,6,6,7}[np] + adj = {p2,p3} + elsif pf[$]=3 + and pf[$-1]=2 then what = "2^k*3 (made up rule)" + np = lf-1 + p2 = {3,3,4,4,4,6,6,6,6}[np] + p3 = {2,2,3,3,3,4,4,4,4}[np] + np = {2,3,3,4,5,5,6,7,8}[np] + adj = {p2,p3} + elsif lf>4 + and pf[$-1]=2 then what="2^k*p (made up rule)" + np = lf-1 + adj = {0,4} + elsif lf>4 + and pf[$]=3 + and pf[$-1]=3 + and pf[$-2]=2 then what="2^k*3^2*p (made up rule)" + np = lf-4 + p3 = {3,3,3,4,4}[np] + p5 = {2,2,2,3,3}[np] + np = {4,5,6,6,7}[np] + adj = {6,p3,p5} + elsif lf>4 + and pf[$]=3 + and pf[$-2]=3 + and pf[$-4]=2 then what="2^k*3^3*p (made up rule)" + np = lf-1 + adj = {6} + elsif lf>5 + and pf[$]>3 + and pf[$-1]=3 + and pf[$-4]=3 + and pf[2]=3 + and (pf[1]=2 or pf[$]>5) then what="2^k*3^4*p (made up rule)" + np = lf + adj = {} + elsif lf>4 + and pf[$-1]=3 + and pf[$-4]=3 + and (lf>5 or pf[$]=3) then what="[2^k]*3^(>=4)*p (made up rule)" + np = lf-1 + adj = {9,pf[$]}&reverse(pf[1..$-3]) -- + elsif lf>=7 + and pf[$]>3 + and pf[$-1]=3 + and pf[$-2]=2 then what="2^k*3*p (made up rule)" + np = lf-1 + adj = {0,4,3} + elsif i=1440 + and pf={2,2,2,2,2,3,3,5} then what="1440 (complete fudge)" + -- nothing quite like this, nothing to build any pattern from... + np = 7 + adj = {6,5,3,2,2,2,2} + else what="general (proper rule)" + -- (note this incorporates the p^2, (p>2)^k, p*q, and p*m*q rules) + np = lf + adj = {} + end if + ri = get_primes(-np) + for j=1 to length(adj) do + integer aj = adj[j] + if aj!=0 then pf[-j] = aj end if + end for + for j=1 to np do + ri[j] = {ri[j],pf[-j]-1} + end for - string short_form = "" -- (eg "2^2*3^3" form) - mpz_set_si(r,1) -- (above as big int) - for j=1 to length(ri) do - {p, e} = ri[j] - if length(short_form) then short_form &= "*" end if - short_form &= sprintf("%d",p) - if e!=1 then - short_form &= sprintf("^%d",{e}) - end if - mpz_ui_pow_ui(pn,p,e) - mpz_mul(r,r,pn) - end for - if i<=15 or remainder(i-1,250)>=248 or i=1440 then - string rs = mpz_get_str(r) - if length(rs)>20 then - rs[6..-6] = sprintf("<-- %d digits -->",length(rs)-10) - end if - if short_form="2^0" then short_form = "1" end if - printf(1,"%4d : %25s %30s %s\n",{i,short_form,rs,what}) - end if - integer k = find(what,rule_names) - if k=0 then - rule_names = append(rule_names,what) - rule_counts = append(rule_counts,1) - else - rule_counts[k] += 1 - end if - end for - integer lr = length(rule_names) - printf(1,"\nrules(%d):\n",lr) - sequence tags = custom_sort(rule_counts, tagset(lr)) - for i=1 to lr do - integer ti = tags[-i] - printf(1," %30s:%d\n",{rule_names[ti],rule_counts[ti]}) - end for - {r,pn} = mpz_free({r,pn}) -",length(rs)-10) + end if + if short_form="2^0" then short_form = "1" end if + printf(1,"%4d : %25s %30s %s\n",{i,short_form,rs,what}) + end if + integer k = find(what,rule_names) + if k=0 then + rule_names = append(rule_names,what) + rule_counts = append(rule_counts,1) + else + rule_counts[k] += 1 + end if +end for +integer lr = length(rule_names) +printf(1,"\nrules(%d):\n",lr) +sequence tags = custom_sort(rule_counts, tagset(lr)) +for i=1 to lr do + integer ti = tags[-i] + printf(1," %30s:%d\n",{rule_names[ti],rule_counts[ti]}) +end for +{r,pn} = mpz_free({r,pn}) diff --git a/Task/Sequence:-smallest-number-with-exactly-n-divisors/Pluto/sequence:-smallest-number-with-exactly-n-divisors.pluto b/Task/Sequence:-smallest-number-with-exactly-n-divisors/Pluto/sequence:-smallest-number-with-exactly-n-divisors.pluto new file mode 100644 index 0000000000..18fa9c7ded --- /dev/null +++ b/Task/Sequence:-smallest-number-with-exactly-n-divisors/Pluto/sequence:-smallest-number-with-exactly-n-divisors.pluto @@ -0,0 +1,16 @@ +local int = require "int" +require "table2" + +local limit = 22 +local numbers = table.rep(limit, 0) +local i = 1 +while true do + local nd = int.divstat(i)[1] + if nd <= limit and numbers[nd] == 0 then + numbers[nd] = i + if numbers:checkall(|n| -> n > 0) then break end + end + i += 1 +end +print($"The first {limit} terms are:") +print(numbers:concat(", ")) diff --git a/Task/Sequence:-smallest-number-with-exactly-n-divisors/Rust/sequence:-smallest-number-with-exactly-n-divisors.rust b/Task/Sequence:-smallest-number-with-exactly-n-divisors/Rust/sequence:-smallest-number-with-exactly-n-divisors.rs similarity index 100% rename from Task/Sequence:-smallest-number-with-exactly-n-divisors/Rust/sequence:-smallest-number-with-exactly-n-divisors.rust rename to Task/Sequence:-smallest-number-with-exactly-n-divisors/Rust/sequence:-smallest-number-with-exactly-n-divisors.rs diff --git a/Task/Set-consolidation/Ada/set-consolidation-1.ada b/Task/Set-consolidation/Ada/set-consolidation-1.adb similarity index 100% rename from Task/Set-consolidation/Ada/set-consolidation-1.ada rename to Task/Set-consolidation/Ada/set-consolidation-1.adb diff --git a/Task/Set-consolidation/Ada/set-consolidation-2.ada b/Task/Set-consolidation/Ada/set-consolidation-2.adb similarity index 100% rename from Task/Set-consolidation/Ada/set-consolidation-2.ada rename to Task/Set-consolidation/Ada/set-consolidation-2.adb diff --git a/Task/Set-consolidation/Ada/set-consolidation-3.ada b/Task/Set-consolidation/Ada/set-consolidation-3.adb similarity index 100% rename from Task/Set-consolidation/Ada/set-consolidation-3.ada rename to Task/Set-consolidation/Ada/set-consolidation-3.adb diff --git a/Task/Set-consolidation/DuckDB/set-consolidation-1.duckdb b/Task/Set-consolidation/DuckDB/set-consolidation-1.duckdb new file mode 100644 index 0000000000..bd087e9c78 --- /dev/null +++ b/Task/Set-consolidation/DuckDB/set-consolidation-1.duckdb @@ -0,0 +1 @@ +create type set as VARCHAR[]; diff --git a/Task/Set-consolidation/DuckDB/set-consolidation-2.duckdb b/Task/Set-consolidation/DuckDB/set-consolidation-2.duckdb new file mode 100644 index 0000000000..c5198f03a2 --- /dev/null +++ b/Task/Set-consolidation/DuckDB/set-consolidation-2.duckdb @@ -0,0 +1,17 @@ +create or replace function to_set(lst) as ( + list_sort(list_distinct(lst)) +); + +create or replace function list_update(lst, i, value) as ( + lst[1:i-1] || [value] || lst[i+1:] +); + +# This will work even if set1 and set2 are just lists +create or replace function set_intersection(set1, set2) as ( + list_sort(list_intersect(set1, set2)) +); + +# This will work even if set1 and set2 are just lists +create or replace function set_union(set1, set2) as ( + to_set( ( set1 || set2 ) ) +); diff --git a/Task/Set-consolidation/DuckDB/set-consolidation-3.duckdb b/Task/Set-consolidation/DuckDB/set-consolidation-3.duckdb new file mode 100644 index 0000000000..3761646cab --- /dev/null +++ b/Task/Set-consolidation/DuckDB/set-consolidation-3.duckdb @@ -0,0 +1,61 @@ +# If listofsets[j] can be merged with listofsets[i] +# then set the former to [] and the latter to the merger +create or replace function merge(listofsets, i, j) as ( + if (i=j, + listofsets, + case when list_has_any(listofsets[i]::set, listofsets[j]::set) -- casts needed here + then list_update( + list_update(listofsets, + i, + set_union(listofsets[i], listofsets[j])), + j, + []) + else listofsets + end) +); + +create or replace function merge_i(listofsets, i) as table ( + with recursive cte(j,s) as ( + select 1, listofsets::SET[] -- advisable!! + union all + select j+1, merge(s, i, j) + from cte + where j <= length(listofsets) + ) + select last(s order by j) as s from cte +); + +# Compute the consolidation as a set +# Note: as of DuckDB V1.1, the CTE here must be given a different name from the one in merge_i +create or replace function consolidation(listofsets) as ( + with recursive cte1(i,s) as ( + select 1, listofsets::SET[] + union all + select i+1, (from merge_i(s, i) limit 1) as s + from cte1 + where i <= length(listofsets) + ) + select to_set( + list_transform( + list_filter(last(s order by i), x -> length(x)>0), + x -> to_set(x))) as consolidation from cte1 +); + +# Verify that the consolidation of x is equal to to_set(y), +# so be sure that each of the elements of y is in fact a set. +create or replace function verify(x,y) as ( + select consolidation(x) = to_set(y) +); + +.print Example 1: +select verify( [ ['A','B'], ['C','D']], [ ['A','B'], ['C','D']] ) as "Example 1"; + +.print Example 2: +select verify( [ ['A','B'], ['B','D'] ], [['A', 'B','D']]) as "Example 2"; + +.print Example 3: +select verify( [['A','B'], ['C','D'], ['D','B']], [['A','B','C','D']]) as "Example 3"; + +.print Example 4: +select verify( [['H','I','K'], ['A','B'], ['C','D'], ['D','B'], ['F','G','H'] ], + [['A', 'B', 'C', 'D'], ['F', 'G', 'H', 'I', 'K']] ) as "Example 4"; diff --git a/Task/Set-consolidation/Elixir/set-consolidation.elixir b/Task/Set-consolidation/Elixir/set-consolidation.ex similarity index 100% rename from Task/Set-consolidation/Elixir/set-consolidation.elixir rename to Task/Set-consolidation/Elixir/set-consolidation.ex diff --git a/Task/Set-consolidation/Julia/set-consolidation-1.julia b/Task/Set-consolidation/Julia/set-consolidation-1.jl similarity index 100% rename from Task/Set-consolidation/Julia/set-consolidation-1.julia rename to Task/Set-consolidation/Julia/set-consolidation-1.jl diff --git a/Task/Set-consolidation/Julia/set-consolidation-2.julia b/Task/Set-consolidation/Julia/set-consolidation-2.jl similarity index 100% rename from Task/Set-consolidation/Julia/set-consolidation-2.julia rename to Task/Set-consolidation/Julia/set-consolidation-2.jl diff --git a/Task/Set-consolidation/Kotlin/set-consolidation.kotlin b/Task/Set-consolidation/Kotlin/set-consolidation.kts similarity index 100% rename from Task/Set-consolidation/Kotlin/set-consolidation.kotlin rename to Task/Set-consolidation/Kotlin/set-consolidation.kts diff --git a/Task/Set-consolidation/NewLISP/set-consolidation.l b/Task/Set-consolidation/NewLISP/set-consolidation.l new file mode 100644 index 0000000000..f3c0bfe4ac --- /dev/null +++ b/Task/Set-consolidation/NewLISP/set-consolidation.l @@ -0,0 +1,31 @@ +(macro (reduce Func List (Init-Val nil)) + (apply + Func + (append (if (= nil Init-Val) '() (list Init-Val)) List) + 2)) + +(define (consol ss) + (let (comb + (lambda (cs s) + (cond ((empty? s) cs) + ((empty? cs) (list s)) + ((empty? (intersect s (first cs))) + (cons (first cs) (comb (rest cs) s))) + (true (consol (cons (union s (cs 0)) (rest cs))))))) + (reduce comb ss '()))) + +(consol '((a b) (c d))) + +((a b) (c d)) + +(consol '((a b) (b c))) + +((b c a)) + +(consol '((a b) (c d) (d b))) + +((c d b a)) + +(consol '((h i k) (a b) (c d) (d b) (f g h))) + +((f g h i k) (c d b a)) diff --git a/Task/Set-consolidation/OCaml/set-consolidation.ocaml b/Task/Set-consolidation/OCaml/set-consolidation.ml similarity index 100% rename from Task/Set-consolidation/OCaml/set-consolidation.ocaml rename to Task/Set-consolidation/OCaml/set-consolidation.ml diff --git a/Task/Set-consolidation/Pluto/set-consolidation.pluto b/Task/Set-consolidation/Pluto/set-consolidation.pluto new file mode 100644 index 0000000000..be665b398f --- /dev/null +++ b/Task/Set-consolidation/Pluto/set-consolidation.pluto @@ -0,0 +1,38 @@ +require "map" +require "table2" +local fmt = require "fmt" + +local function consolidate_sets(sets) + local size = #sets + local consolidated = table.rep(size, false) + for i = 1, size - 1 do + if !consolidated[i] then + repeat + local intersects = 0 + for j = i + 1, size do + if !consolidated[j] then + if !sets[i]:intersect(sets[j]):empty() then + sets[i]:merge(sets[j]) + consolidated[j] = true + ++intersects + end + end + end + until intersects == 0 + end + end + return range(1, size):filter(|i| -> !consolidated[i]):reorder():map(|i| -> sets[i]) +end + +local unconsolidated_sets = { + {set.of("A", "B"), set.of("C", "D")}, + {set.of("A", "B"), set.of("B", "D")}, + {set.of("A", "B"), set.of("C", "D"), set.of("D", "B")}, + {set.of("H", "I", "K"), set.of("A", "B"), set.of("C", "D"), + set.of("D", "B"), set.of("F", "G", "H")} +} +for unconsolidated_sets as sets do + fmt.print("Unconsolidated: %s", fmt.swrite(sets)) + fmt.print("Consolidated : %s", fmt.swrite(consolidate_sets(sets))) + print() +end diff --git a/Task/Set-consolidation/VBScript/set-consolidation.vb b/Task/Set-consolidation/VBScript/set-consolidation.vbs similarity index 100% rename from Task/Set-consolidation/VBScript/set-consolidation.vb rename to Task/Set-consolidation/VBScript/set-consolidation.vbs diff --git a/Task/Set-consolidation/Wren/set-consolidation.wren b/Task/Set-consolidation/Wren/set-consolidation.wren index f5125e2bc8..bb9190b133 100644 --- a/Task/Set-consolidation/Wren/set-consolidation.wren +++ b/Task/Set-consolidation/Wren/set-consolidation.wren @@ -34,5 +34,5 @@ var unconsolidatedSets = [ ] for (sets in unconsolidatedSets) { System.print("Unconsolidated: %(sets)") - System.print("Cosolidated : %(consolidateSets.call(sets))\n") + System.print("Consolidated : %(consolidateSets.call(sets))\n") } diff --git a/Task/Set-of-real-numbers/Delphi/set-of-real-numbers.delphi b/Task/Set-of-real-numbers/Delphi/set-of-real-numbers.pas similarity index 100% rename from Task/Set-of-real-numbers/Delphi/set-of-real-numbers.delphi rename to Task/Set-of-real-numbers/Delphi/set-of-real-numbers.pas diff --git a/Task/Set-of-real-numbers/Elena/set-of-real-numbers.elena b/Task/Set-of-real-numbers/Elena/set-of-real-numbers.elena index 74e287eb82..3168667962 100644 --- a/Task/Set-of-real-numbers/Elena/set-of-real-numbers.elena +++ b/Task/Set-of-real-numbers/Elena/set-of-real-numbers.elena @@ -12,7 +12,7 @@ extension setOp = (val => self(val) && (func(val)).Inverted ); } -public program() +public Program() { // union var set := (x => x >= 0.0r && x <= 1.0r ).union::(x => x >= 0.0r && x < 2.0r ); diff --git a/Task/Set-of-real-numbers/FreeBASIC/set-of-real-numbers.basic b/Task/Set-of-real-numbers/FreeBASIC/set-of-real-numbers.basic index dfc44a1ec7..38938ce7c2 100644 --- a/Task/Set-of-real-numbers/FreeBASIC/set-of-real-numbers.basic +++ b/Task/Set-of-real-numbers/FreeBASIC/set-of-real-numbers.basic @@ -26,6 +26,30 @@ Function cf(f As Func, x As Double) As Boolean End Select End Function +Function fToString(f As Func) As String + Dim result As String = "" + Select Case f.ID + Case 1: result &= "(" + Case 2: result &= "[" + Case 3: result &= "(" + Case 4: result &= "[" + 'Extra credit + Case 5: result &= "5?" + Case 6: result &= "6?" + End Select + result &= Str$(f.ARGS(0)) & "," & Str$(f.ARGS(1)) + Select Case f.ID + Case 1: result &= ")" + Case 2: result &= "]" + Case 3: result &= "]" + Case 4: result &= ")" + 'Extra credit + Case 5: result &= "?" + Case 6: result &= "?" + End Select + Return result +End Function + Function Union_(a As Func, b As Func, x As Double) As Boolean Return cf(a, x) Or cf(b, x) End Function @@ -65,15 +89,16 @@ End Function ' Set definitions and test methods Dim As Func s(6, 2) -s(1, 0).ID = 3: s(1, 0).ARGS(0) = 0: s(1, 0).ARGS(1) = 1 -s(1, 1).ID = 4: s(1, 1).ARGS(0) = 0: s(1, 1).ARGS(1) = 2 -s(2, 0).ID = 4: s(2, 0).ARGS(0) = 0: s(2, 0).ARGS(1) = 2 -s(2, 1).ID = 3: s(2, 1).ARGS(0) = 1: s(2, 1).ARGS(1) = 2 -s(3, 0).ID = 4: s(3, 0).ARGS(0) = 0: s(3, 0).ARGS(1) = 3 -s(3, 1).ID = 1: s(3, 1).ARGS(0) = 0: s(3, 1).ARGS(1) = 1 -s(4, 0).ID = 4: s(4, 0).ARGS(0) = 0: s(4, 0).ARGS(1) = 3 -s(4, 1).ID = 2: s(4, 1).ARGS(0) = 0: s(4, 1).ARGS(1) = 1 -s(5, 0).ID = 2: s(5, 0).ARGS(0) = 0: s(5, 0).ARGS(1) = 0 +s(1, 1).ID = 3: s(1, 1).ARGS(0) = 0: s(1, 1).ARGS(1) = 1 +s(1, 2).ID = 4: s(1, 2).ARGS(0) = 0: s(1, 2).ARGS(1) = 2 +s(2, 1).ID = 4: s(2, 1).ARGS(0) = 0: s(2, 1).ARGS(1) = 2 +s(2, 2).ID = 3: s(2, 2).ARGS(0) = 1: s(2, 2).ARGS(1) = 2 +s(3, 1).ID = 4: s(3, 1).ARGS(0) = 0: s(3, 1).ARGS(1) = 3 +s(3, 2).ID = 1: s(3, 2).ARGS(0) = 0: s(3, 2).ARGS(1) = 1 +s(4, 1).ID = 4: s(4, 1).ARGS(0) = 0: s(4, 1).ARGS(1) = 3 +s(4, 2).ID = 2: s(4, 2).ARGS(0) = 0: s(4, 2).ARGS(1) = 1 +s(5, 1).ID = 2: s(5, 1).ARGS(0) = 0: s(5, 1).ARGS(1) = 0 +s(5, 2).ID = 0: s(5, 2).ARGS(0) = 0: s(5, 2).ARGS(1) = 0 'Extra credit s(6, 1).ID = 5: s(6, 1).ARGS(0) = 0: s(6, 1).ARGS(1) = 10 s(6, 2).ID = 6: s(6, 2).ARGS(0) = 0: s(6, 2).ARGS(1) = 10 @@ -82,32 +107,32 @@ Dim As Integer i, x, r For x = 0 To 2 i = 1 r = Union_(s(i, 1), s(i, 2), x) - Print Using "# in (#_,#] u [#_,#) : &"; x; s(i, 0).ARGS(0); s(i, 0).ARGS(1); s(i, 1).ARGS(0); s(1, 1).ARGS(1); Cbool(r) + Print Using "# in & U & : &"; x; fToString(s(i, 1)); fToString(s(i, 2)); Cbool(r) Next x Print For x = 0 To 2 i = 2 r = Inters(s(i, 1), s(i, 2), x) - Print Using "# in (#_,#] u [#_,#) : &"; x; s(i, 0).ARGS(0); s(i, 0).ARGS(1); s(i, 1).ARGS(0); s(1, 1).ARGS(1); Cbool(r) + Print Using "# in & n & : &"; x; fToString(s(i, 1)); fToString(s(i, 2)); Cbool(r) Next x Print For x = 0 To 2 i = 3 r = Differ(s(i, 1), s(i, 2), x) - Print Using "# in (#_,#] u [#_,#) : &"; x; s(i, 0).ARGS(0); s(i, 0).ARGS(1); s(i, 1).ARGS(0); s(1, 1).ARGS(1); Cbool(r) + Print Using "# in & - & : &"; x; fToString(s(i, 1)); fToString(s(i, 2)); Cbool(r) Next x Print For x = 0 To 2 i = 4 r = Differ(s(i, 1), s(i, 2), x) - Print Using "# in (#_,#] u [#_,#) : &"; x; s(i, 0).ARGS(0); s(i, 0).ARGS(1); s(i, 1).ARGS(0); s(1, 1).ARGS(1); Cbool(r) + Print Using "# in & - & : &"; x; fToString(s(i, 1)); fToString(s(i, 2)); Cbool(r) Next x Print x = 0 i = 5 r = Differ(s(i, 1), s(i, 2), x) -Print Using "[#_,#] is empty : &"; s(i, 0).ARGS(0); s(i, 0).ARGS(1); Cbool(r) +Print Using "[#_,#] is empty : &"; s(i, 1).ARGS(0); s(i, 2).ARGS(1); Cbool(r) Print 'Extra credit diff --git a/Task/Set-of-real-numbers/Julia/set-of-real-numbers.julia b/Task/Set-of-real-numbers/Julia/set-of-real-numbers.jl similarity index 100% rename from Task/Set-of-real-numbers/Julia/set-of-real-numbers.julia rename to Task/Set-of-real-numbers/Julia/set-of-real-numbers.jl diff --git a/Task/Set-of-real-numbers/Kotlin/set-of-real-numbers.kotlin b/Task/Set-of-real-numbers/Kotlin/set-of-real-numbers.kts similarity index 100% rename from Task/Set-of-real-numbers/Kotlin/set-of-real-numbers.kotlin rename to Task/Set-of-real-numbers/Kotlin/set-of-real-numbers.kts diff --git a/Task/Set-of-real-numbers/Pluto/set-of-real-numbers.pluto b/Task/Set-of-real-numbers/Pluto/set-of-real-numbers.pluto new file mode 100644 index 0000000000..34cdb54080 --- /dev/null +++ b/Task/Set-of-real-numbers/Pluto/set-of-real-numbers.pluto @@ -0,0 +1,62 @@ +-- Set of real numbers, translation of the Go and Phix samples + +local function namedFunction( fn, name ) return { ["name"] = name, ["fn"] = fn } end + +local function Union( a, b ) return namedFunction( function( x ) return a.fn( x ) or b.fn( x ) end + , a.name .. " ∪ " .. b.name + ) +end +local function Inter( a, b ) return namedFunction( function( x ) return a.fn( x ) and b.fn( x ) end + , a.name .. " ∩ " .. b.name + ) +end +local function Diff( a, b ) return namedFunction( function( x ) return a.fn( x ) and not b.fn( x ) end + , a.name .. " - " .. b.name + ) +end +local function open( a, b ) + return namedFunction( function( x ) return a < x and x < b end, "("..a..","..b..")" ) +end +local function closed( a, b ) + return namedFunction( function( x ) return a <= x and x <= b end, "["..a..","..b.."]" ) +end +local function opCl( a, b ) + return namedFunction( function( x ) return a < x and x < b end, "("..a..","..b.."]" ) +end +local function clOp( a, b ) + return namedFunction( function( x ) return a <= x and x < b end, "["..a..","..b..")" ) +end + +do -- test cases + local s = {} + s[ 1 ] = Union( opCl( 0, 1 ), clOp( 0, 2 ) ) -- (0,1] ∪ [0,2) + s[ 2 ] = Inter( clOp( 0, 2 ), opCl( 1, 2 ) ) -- [0,2) ∩ (1,2] + s[ 3 ] = Diff( clOp( 0, 3 ), open( 0, 1 ) ) -- [0,3) − (0,1) + s[ 4 ] = Diff( clOp( 0, 3 ), closed( 0, 1 ) ) -- [0,3) − [0,1] + + for i = 1, # s do + for x = 0, 2 do + print( string.format( "%.0f ∈ %s: %s", x, s[ i ].name, ( s[ i ].fn( x ) and "true" or "false" ) ) ) + end + print() + end + + -- as with the Go and Phix samples, this sample can't check for empty sets + -- however using the same technique as the Phix sample, we can calculate + -- the approximate length of the "optional work" set, as in the Phix sample + + local aspxx = namedFunction( function( x ) return math.abs( math.sin( math.pi * x * x ) ) > 0.5 end + , "|abs sin πx²| > 0.5" + ) + local aspx = namedFunction( function( x ) return math.abs( math.sin( math.pi * x ) ) > 0.5 end + , "|abs sin πx| > 0.5" + ) + + local C = Diff( Inter( open( 0, 10 ), aspxx ), Inter( open( 0, 10 ), aspx ) ) + local x, step, count = 0, 0.00001, 0 + while x <= 10 do + if C.fn( x ) then count += 1 end + x += step + end + print( $"Approximate length of { C.name }: { count * step }" ) +end diff --git a/Task/Set-of-real-numbers/Rust/set-of-real-numbers.rust b/Task/Set-of-real-numbers/Rust/set-of-real-numbers.rs similarity index 100% rename from Task/Set-of-real-numbers/Rust/set-of-real-numbers.rust rename to Task/Set-of-real-numbers/Rust/set-of-real-numbers.rs diff --git a/Task/Set-puzzle/Ada/set-puzzle-1.ada b/Task/Set-puzzle/Ada/set-puzzle-1.adb similarity index 100% rename from Task/Set-puzzle/Ada/set-puzzle-1.ada rename to Task/Set-puzzle/Ada/set-puzzle-1.adb diff --git a/Task/Set-puzzle/Ada/set-puzzle-2.ada b/Task/Set-puzzle/Ada/set-puzzle-2.adb similarity index 100% rename from Task/Set-puzzle/Ada/set-puzzle-2.ada rename to Task/Set-puzzle/Ada/set-puzzle-2.adb diff --git a/Task/Set-puzzle/Ada/set-puzzle-3.ada b/Task/Set-puzzle/Ada/set-puzzle-3.adb similarity index 100% rename from Task/Set-puzzle/Ada/set-puzzle-3.ada rename to Task/Set-puzzle/Ada/set-puzzle-3.adb diff --git a/Task/Set-puzzle/EasyLang/set-puzzle.easy b/Task/Set-puzzle/EasyLang/set-puzzle.easy index 876402c56a..cb46d5812b 100644 --- a/Task/Set-puzzle/EasyLang/set-puzzle.easy +++ b/Task/Set-puzzle/EasyLang/set-puzzle.easy @@ -4,28 +4,25 @@ attr$[][] &= [ "red " "green " "purple" ] attr$[][] &= [ "diamond" "oval" "squiggle" ] # subr init - for card = 0 to 80 - pack[] &= card - . + for card = 0 to 80 : pack[] &= card . -proc card2attr card . attr[] . +proc card2attr card &attr[] . attr[] = [ ] for i to 4 attr[] &= card mod 3 + 1 card = card div 3 . . -proc printcards cards[] . . +proc printcards cards[] . for card in cards[] card2attr card attr[] - for i to 4 - write attr$[i][attr[i]] & " " - . + write " " + for i to 4 : write attr$[i][attr[i]] & " " print "" . print "" . -proc getsets . cards[] set[] . +proc getsets &cards[] &set[] . set[] = [ ] for i to len cards[] card2attr cards[i] a[] @@ -36,9 +33,7 @@ proc getsets . cards[] set[] . ok = 1 for at to 4 s = a[at] + b[at] + c[at] - if s <> 3 and s <> 6 and s <> 9 - ok = 0 - . + if s <> 3 and s <> 6 and s <> 9 : ok = 0 . if ok = 1 set[] &= cards[i] @@ -49,13 +44,12 @@ proc getsets . cards[] set[] . . . . -proc run ncards nsets . . - # +proc run ncards nsets . repeat init cards[] = [ ] for i to ncards - ind = random len pack[] + ind = random 1 len pack[] cards[] &= pack[ind] pack[ind] = pack[len pack[]] len pack[] -1 @@ -71,5 +65,3 @@ proc run ncards nsets . . . . run 9 4 -print " --------------------------" -run 12 6 diff --git a/Task/Set-puzzle/Elixir/set-puzzle.elixir b/Task/Set-puzzle/Elixir/set-puzzle.ex similarity index 100% rename from Task/Set-puzzle/Elixir/set-puzzle.elixir rename to Task/Set-puzzle/Elixir/set-puzzle.ex diff --git a/Task/Set-puzzle/FreeBASIC/set-puzzle.basic b/Task/Set-puzzle/FreeBASIC/set-puzzle.basic new file mode 100644 index 0000000000..150e783152 --- /dev/null +++ b/Task/Set-puzzle/FreeBASIC/set-puzzle.basic @@ -0,0 +1,158 @@ +Sub countAttributes(cards() As String, colors() As String, numbers() As String, shapes() As String, fillings() As String) + For i As Integer = 0 To 2 + Dim As String card = cards(i) + colors(i) = Mid(card, 1, Instr(card, " ") - 1) + card = Mid(card, Instr(card, " ") + 1) + numbers(i) = Mid(card, 1, Instr(card, " ") - 1) + card = Mid(card, Instr(card, " ") + 1) + shapes(i) = Mid(card, 1, Instr(card, " ") - 1) + fillings(i) = Mid(card, Instr(card, " ") + 1) + Next +End Sub + +Sub cartesianProduct(colors() As String, numbers() As String, shapes() As String, fillings() As String, deck() As String) + Dim As Integer i, j, k, l, index + index = 0 + For i = 0 To Ubound(colors) + For j = 0 To Ubound(numbers) + For k = 0 To Ubound(shapes) + For l = 0 To Ubound(fillings) + deck(index) = colors(i) & " " & numbers(j) & " " & shapes(k) & " " & fillings(l) + index += 1 + Next + Next + Next + Next +End Sub + +Sub randomSample(deck() As String, nDraw As Integer, sample() As String) + Dim As Integer i, r, indices(Ubound(deck)) + For i = 0 To Ubound(deck) + indices(i) = i + Next + For i = 0 To nDraw - 1 + r = Int(Rnd * (Ubound(indices) - i + 1)) + i + Swap indices(i), indices(r) + sample(i) = deck(indices(i)) + Next +End Sub + +Sub combinations3(drav() As String, comb() As String) + Dim As Integer i, j, k + Dim n As Integer = Ubound(drav) + 1 + Dim count As Integer = n * (n - 1) * (n - 2) / 6 + Redim comb(count - 1) + Dim index As Integer = 0 + For i = 0 To n - 3 + For j = i + 1 To n - 2 + For k = j + 1 To n - 1 + comb(index) = drav(i) & " | " & drav(j) & " | " & drav(k) + index += 1 + Next + Next + Next +End Sub + +Sub sortArray(arr() As String) + Dim As Integer i, j, ub + ub = Ubound(arr) + For i = 0 To ub - 1 + For j = i + 1 To ub + If arr(i) > arr(j) Then Swap arr(i), arr(j) + Next + Next +End Sub + +Function isSet(cards() As String) As Boolean + Dim As Integer i, j + Dim As String colors(2), numbers(2), shapes(2), fillings(2), attr(2), sortedAttr(2) + Dim As String card + + For i = 0 To 2 + card = cards(i) + colors(i) = Mid(card, 1, Instr(card, " ") - 1) + card = Mid(card, Instr(card, " ") + 1) + numbers(i) = Mid(card, 1, Instr(card, " ") - 1) + card = Mid(card, Instr(card, " ") + 1) + shapes(i) = Mid(card, 1, Instr(card, " ") - 1) + fillings(i) = Mid(card, Instr(card, " ") + 1) + Next + For i = 0 To 3 + Select Case i + Case 0 + For j = 0 To 2: attr(j) = colors(j): Next + Case 1 + For j = 0 To 2: attr(j) = numbers(j): Next + Case 2 + For j = 0 To 2: attr(j) = shapes(j): Next + Case 3 + For j = 0 To 2: attr(j) = fillings(j): Next + End Select + + For j = 0 To 2 + sortedAttr(j) = attr(j) + Next + + sortArray(sortedAttr()) + + If (sortedAttr(0) = sortedAttr(1) And sortedAttr(1) = sortedAttr(2)) Or (sortedAttr(0) <> sortedAttr(1) And sortedAttr(1) <> sortedAttr(2) And sortedAttr(0) <> sortedAttr(2)) Then + Continue For + Else + Return False + End If + Next + Return True +End Function + +'--- Programa Principal --- +Randomize Timer +Dim As Integer i, j, posic, validSets +Dim As String colors(2) = {" red", " green", " purple"} +Dim As String numbers(2) = {" one", " two", "three"} +Dim As String shapes(2) = {" oval", "squiggle", " diamond"} +Dim As String fillings(2) = {" solid", " open", "striped"} +Dim As String deck(80) +cartesianProduct(colors(), numbers(), shapes(), fillings(), deck()) + +Dim As Integer nDraw = 9, nGoal = nDraw / 2 +Dim As String drav(nDraw - 1) +randomSample(deck(), nDraw, drav()) +Dim As String sets(), cards(2) +Do + combinations3(drav(), sets()) + validSets = 0 + For i = 0 To Ubound(sets) + posic = 1 + For j = 0 To 2 + cards(j) = Mid(sets(i), posic, Instr(posic, sets(i), " | ") - posic) + posic = Instr(posic, sets(i), " | ") + 3 + Next + If isSet(cards()) Then + validSets += 1 + End If + Next + If validSets = nGoal Then Exit Do + randomSample(deck(), nDraw, drav()) +Loop + +Print "Dealt "; nDraw; " cards:" +For i = 0 To Ubound(drav) + Print drav(i) +Next + +Print !"\nContaining:" +For i = 0 To Ubound(sets) + posic = 1 + For j = 0 To 2 + cards(j) = Mid(sets(i), posic, Instr(posic, sets(i), " | ") - posic) + posic = Instr(posic, sets(i), " | ") + 3 + Next + If isSet(cards()) Then + For j = 0 To 2 + Print cards(j) + Next + Print + End If +Next + +Sleep diff --git a/Task/Set-puzzle/JavaScript/set-puzzle.js b/Task/Set-puzzle/JavaScript/set-puzzle.js new file mode 100644 index 0000000000..0774e4fc66 --- /dev/null +++ b/Task/Set-puzzle/JavaScript/set-puzzle.js @@ -0,0 +1,86 @@ +// Constants +const number = ["1", "2", "3"]; +const color = ["red", "green", "purple"]; +const shade = ["solid", "open", "striped"]; +const shape = ["oval", "squiggle", "diamond"]; + +// Card class +class Card { + constructor(value) { + this.value = value; + } + + toString() { + return `${number[Math.floor(this.value/27)]} ${color[Math.floor(this.value/9)%3]} ${shade[Math.floor(this.value/3)%3]} ${shape[this.value%3]}`; + } +} + +// Shuffle an array +function shuffle(array) { + for (let i = array.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)); + [array[i], array[j]] = [array[j], array[i]]; + } +} + +// Main game function +function game(level, cards, sets) { + // Create deck + const deck = []; + for (let i = 0; i < 81; i++) { + deck.push(new Card(i)); + } + + let found = []; + while (found.length !== sets) { + found = []; + + // Deal + shuffle(deck); + + // Consider all triplets + for (let i = 2; i < cards; i++) { + const c1 = deck[i]; + for (let j = 1; j < i; j++) { + const c2 = deck[j]; + + outer: for (let k = 0; k < j; k++) { + const c3 = deck[k]; + + // Check if it's a set + for (let f = 1; f < 81; f *= 3) { + if ((Math.floor(c1.value/f)%3 + Math.floor(c2.value/f)%3 + Math.floor(c3.value/f)%3) % 3 !== 0) { + continue outer; // not a set + } + } + + // It's a set + found.push([c1, c2, c3]); + } + } + } + } + + // Output results + console.log(`${level} game. ${cards} cards, ${sets} sets.`); + console.log("Cards:"); + for (let i = 0; i < cards; i++) { + console.log(" ", deck[i].toString()); + } + + console.log("Sets:"); + for (const set of found) { + console.log(` ${set[0]}\n ${set[1]}\n ${set[2]}`); + } +} + +// Run the games +function main() { + // Set random seed with current time + Math.random(); + + game("Basic", 9, 4); + game("Advanced", 12, 6); +} + +main(); diff --git a/Task/Set-puzzle/Jq/set-puzzle.jq b/Task/Set-puzzle/Jq/set-puzzle.jq new file mode 100644 index 0000000000..96f6c58497 --- /dev/null +++ b/Task/Set-puzzle/Jq/set-puzzle.jq @@ -0,0 +1,75 @@ +# Source of entropy +include "MRG32k3a" {search: "."}; # see above + +### General utilities + +def lpad($len): tostring | ($len - length) as $l | (" " * $l) + .; + +def array_swap($i; $j): + if $j < $i then array_swap($j;$i) + elif $i == $j then . + else .[:$i] + [.[$j]] + .[$i+1:$j] + [.[$i]] + .[$j+1:] + +# input: array of length $n +def shuffle: + length as $n + | ($n | prn($n)) as $prn + # First cut the deck + | .[$prn[0]:] + .[:$prn[0]] + | reduce range(0; $n - 1) as $i (.; + array_swap($prn[$i]; $prn[$i+1]) ) ; + + +### The Set Game + +# For the standard Set game: +def attributes: ["Color", "Symbol", "Number", "Shading"]; +def number_of_values: 3; + +# a single card +def toString: + [attributes, .] | transpose + | map(join(": ")|lpad(7)) + | join(" "); + +# Create a deck for which each attribute defined by `attributes` has $j possible values: +def createDeck($j): + (attributes|length) as $k + | [range(0;$j)] + | [combinations($k)]; + +def isSet: + . as $trio + | all( range(0; attributes|length); + . as $i | $trio | map(.[$i]) | unique | length | IN(1,number_of_values)); + +# For the standard Set game +# For "advanced" play, set $advanced == true +def playGame( $advanced ): + (if $advanced then 12 else 9 end) as $nCards + | (($nCards/2)|floor) as $nSets + | {sets: [], deck: createDeck(number_of_values) } + | label $out + | foreach range(0; infinite) as $_ (.; + .deck |= shuffle + | .sets = [] + | foreach range(0; $nCards-2) as $i (.; + foreach range($i+1; $nCards-1) as $j (.; + foreach range($j+1; $nCards) as $k (.; + [.deck[$i], .deck[$j], .deck[$k]] as $trio + | if $trio | isSet + then .sets += [$trio] + | if (.sets|length) >= $nSets + then .emit = true, break $out + end + end ) ) ) ) + | select(.emit) + | (.deck[0:$nCards] | sort) as $hand + | "DEALT \($nCards) CARDS:", + ($hand[]|toString), + "\nCONTAINING \($nSets) SETS:", + (.sets + | sort[] + | ((.[] | toString),"") ), "" ; + +playGame(false, true) diff --git a/Task/Set-puzzle/Julia/set-puzzle.julia b/Task/Set-puzzle/Julia/set-puzzle.jl similarity index 100% rename from Task/Set-puzzle/Julia/set-puzzle.julia rename to Task/Set-puzzle/Julia/set-puzzle.jl diff --git a/Task/Set-puzzle/Kotlin/set-puzzle.kotlin b/Task/Set-puzzle/Kotlin/set-puzzle.kts similarity index 100% rename from Task/Set-puzzle/Kotlin/set-puzzle.kotlin rename to Task/Set-puzzle/Kotlin/set-puzzle.kts diff --git a/Task/Set-puzzle/Rust/set-puzzle.rust b/Task/Set-puzzle/Rust/set-puzzle.rs similarity index 100% rename from Task/Set-puzzle/Rust/set-puzzle.rust rename to Task/Set-puzzle/Rust/set-puzzle.rs diff --git a/Task/Set-puzzle/Uiua/set-puzzle.uiua b/Task/Set-puzzle/Uiua/set-puzzle.uiua new file mode 100644 index 0000000000..5f13189305 --- /dev/null +++ b/Task/Set-puzzle/Uiua/set-puzzle.uiua @@ -0,0 +1,16 @@ +Types ← [{"one" "two" "three"} + {"solid" "open" "striped"} + {"red" "green" "purple"} + {"oval" "squiggle" "diamond"}] + +Hand ← ˜↙⊏⍏⍥⚂⊸⧻≡≡⊡⊙(¤Types)⧅⋅⋅1 4⇡3 # build deck, shuffle, take N +Sets ← ≡(=1/↧≡(↥⊃=₁=₃⧻⊕⧻⊸⊛)⍉) # each type in a set must be distinct or identical + +Deal‼ ← ( + ⍢(^1◌|^0/+Sets(⧅<3))^1 + ⊸(▽⊸Sets(⧅<3)) +) +&p"9 cards dealt, 4 sets available.\n" +≡&s⊙&sDeal‼(≠₄|Hand9) +&p"\n\n12 cards dealt, 6 sets available.\n" +≡&s⊙&sDeal‼(≠₆|Hand12) diff --git a/Task/Set-right-adjacent-bits/11l/set-right-adjacent-bits.11l b/Task/Set-right-adjacent-bits/11l/set-right-adjacent-bits.11l index f8accaa0e8..c290f7b780 100644 --- a/Task/Set-right-adjacent-bits/11l/set-right-adjacent-bits.11l +++ b/Task/Set-right-adjacent-bits/11l/set-right-adjacent-bits.11l @@ -23,7 +23,7 @@ L(b_str) bits_s.split(‘ ’) print("SAME Input & Width.\n") bits_s = ‘01’(10.<0).step(-1).map(x -> ‘0’ * x).join(‘1’) -L(n) 4 +L(n) 0.<4 first = 1B L(b_str) bits_s.split(‘ ’) V b = _to_list(b_str) diff --git a/Task/Set-right-adjacent-bits/Ada/set-right-adjacent-bits.ada b/Task/Set-right-adjacent-bits/Ada/set-right-adjacent-bits.adb similarity index 100% rename from Task/Set-right-adjacent-bits/Ada/set-right-adjacent-bits.ada rename to Task/Set-right-adjacent-bits/Ada/set-right-adjacent-bits.adb diff --git a/Task/Set-right-adjacent-bits/Arturo/set-right-adjacent-bits.arturo b/Task/Set-right-adjacent-bits/Arturo/set-right-adjacent-bits.arturo index 4abe919ef2..350b0a2d73 100644 --- a/Task/Set-right-adjacent-bits/Arturo/set-right-adjacent-bits.arturo +++ b/Task/Set-right-adjacent-bits/Arturo/set-right-adjacent-bits.arturo @@ -3,14 +3,14 @@ setBits: function [inp, n][ print "n = " ++ (to :string n) ++ "; Width e = " ++ (to :string e) ++ ":" result: new ø - if? or? zero? e n =< 0 -> result: inp - else [ + switch or? zero? e n =< 0 -> result: inp + [ result: split inp loop 0..e-1 'i [ - if inp\[i] = `1` [ + if inp\[i] = '1' [ j: i + 1 while [and? j =< i+n j < e][ - result\[j]: `1` + result\[j]: '1' j: j + 1 ] ] diff --git a/Task/Set-right-adjacent-bits/EasyLang/set-right-adjacent-bits.easy b/Task/Set-right-adjacent-bits/EasyLang/set-right-adjacent-bits.easy index 5cf6eead30..dfe6134bd5 100644 --- a/Task/Set-right-adjacent-bits/EasyLang/set-right-adjacent-bits.easy +++ b/Task/Set-right-adjacent-bits/EasyLang/set-right-adjacent-bits.easy @@ -1,4 +1,4 @@ -proc adjacent txt$ n . . +proc adjacent txt$ n . print "n = " & n & ", width = " & len txt$ print "input: " & txt$ txt$[] = strchars txt$ @@ -10,7 +10,7 @@ proc adjacent txt$ n . . . . . - res$ = strjoin res$[] + res$ = strjoin res$[] "" print "result: " & res$ print "" . diff --git a/Task/Set-right-adjacent-bits/Jq/set-right-adjacent-bits.jq b/Task/Set-right-adjacent-bits/Jq/set-right-adjacent-bits.jq new file mode 100644 index 0000000000..e82b0d59fa --- /dev/null +++ b/Task/Set-right-adjacent-bits/Jq/set-right-adjacent-bits.jq @@ -0,0 +1,27 @@ +# Input should be an array of 0s and 1s +def setRightBits($e; $n): + if $e == 0 or $n <= 0 then . + else . as $bits + | reduce range(0; $e - 1) as $i ({bits2: .}; + $bits[$i] as $c + | if $c == 1 + then .j = $i + 1 + | until (.j > ($i + $n) or .j >= $e; + .bits2[.j] = 1 + | .j += 1 ) + end) + | .bits2 + end; + +def b: + "010000000000100000000010000000010000000100000010000010000100010010"; + +def tests: + [["1000", 2], ["0100", 2], ["0010", 2], ["0000", 2], [b, 0], [b, 1], [b, 2], [b, 3]]; + +tests[] as [$bits, $n] +| ($bits|length) as $e +| "n = \($n); Width e = \($e):", + " Input b: \($bits)", + ( ($bits | [explode[] | . - 48]) as $b + | " Result: \($b | setRightBits($e; $n) | join(""))\n" ) diff --git a/Task/Set-right-adjacent-bits/Julia/set-right-adjacent-bits.julia b/Task/Set-right-adjacent-bits/Julia/set-right-adjacent-bits.jl similarity index 100% rename from Task/Set-right-adjacent-bits/Julia/set-right-adjacent-bits.julia rename to Task/Set-right-adjacent-bits/Julia/set-right-adjacent-bits.jl diff --git a/Task/Set-right-adjacent-bits/Phix/set-right-adjacent-bits-1.phix b/Task/Set-right-adjacent-bits/Phix/set-right-adjacent-bits-1.phix index 82353cd6fa..d12b0ccd62 100644 --- a/Task/Set-right-adjacent-bits/Phix/set-right-adjacent-bits-1.phix +++ b/Task/Set-right-adjacent-bits/Phix/set-right-adjacent-bits-1.phix @@ -1,29 +1,27 @@ -(phixonline)--> - with javascript_semantics - function str_srb(string input, integer n) - string res = input - integer l = length(input), - m = min(n,l), - count = sum(sq_eq(input[-m..-1],'1')), - k = l-n - for i=l to 1 by -1 do - integer bit = odd(input[i]) - count += iff(k>0?odd(input[k]):0)-bit - if count and not bit then res[i] = '1' end if - k -= 1 - end for - assert(count=0) - return res - end function +with javascript_semantics +function str_srb(string input, integer n) + string res = input + integer l = length(input), + m = min(n,l), + count = sum(sq_eq(input[-m..-1],'1')), + k = l-n + for i=l to 1 by -1 do + integer bit = odd(input[i]) + count += iff(k>0?odd(input[k]):0)-bit + if count and not bit then res[i] = '1' end if + k -= 1 + end for + assert(count=0) + return res +end function - constant tests = {{"1000",2,2},{"0100",2,2},{"0010",2,2},{"0000",2,2}, - {"010000000000100000000010000000010000000100000010000010000100010010",0,3}} +constant tests = {{"1000",2,2},{"0100",2,2},{"0010",2,2},{"0000",2,2}, + {"010000000000100000000010000000010000000100000010000010000100010010",0,3}} - for i=1 to length(tests) do - {string input, integer l, integer m} = tests[i] - printf(1,"input: %s (width %d)\n",{input,length(input)}) - for n=l to m do - printf(1,"n = %d: %s\n",{n,str_srb(input,n)}) - end for - end for - - with javascript_semantics - include mpfr.e - function mpz_srb(string input, integer n) - mpz res = mpz_init("0b"&input), - tmp = mpz_init_set(res), - bit = mpz_init(1), - mask = mpz_init(power(2,n+1)-1), - rask = mpz_init() -- (mask res) - for i=1 to length(input) do -- (backward, actually) - if mpz_even(tmp) then - mpz_and(rask,tmp,mask) - if mpz_cmp_si(rask,0)!=0 then - mpz_add(res,res,bit) - end if - end if - mpz_mul_2exp(bit, bit, 1) -- aka left shift - mpz_fdiv_q_2exp(tmp, tmp, 1) -- aka right shift - end for - string ret = mpz_get_str(res,2) - integer lz = length(input)-length(ret) - if lz then ret = repeat('0',lz)&ret end if - return ret - end function - --... - printf(1,"n = %d: %s\n",{n,mpz_srb(input,n)}) - - with javascript_semantics - include mpfr.e - function mpz_srb(string input, integer n) - string res = input - mpz tmp = mpz_init("0b"&input), - mask = mpz_init(power(2,n+1)-1), - rask = mpz_init() -- (mask res) - for i=length(input) to 1 by -1 do - if input[i]='0' then - mpz_and(rask,tmp,mask) - if mpz_cmp_si(rask,0)!=0 then - res[i] = '1' - end if - end if - mpz_fdiv_q_2exp(tmp, tmp, 1) -- aka right shift - end for - return res - end function - --... - printf(1,"n = %d: %s\n",{n,mpz_srb(input,n)}) - - function create_sieve(integer limit) - sequence sieve = repeat(true,limit) - sieve[1] = false - for i=4 to limit by 2 do - sieve[i] = false - end for - for p=3 to floor(sqrt(limit)) by 2 do - integer p2 = p*p - if sieve[p2] then - for k=p2 to limit by p*2 do - sieve[k] = false - end for - end if - end for - return sieve - end function +function create_sieve(integer limit) + sequence sieve = repeat(true,limit) + sieve[1] = false + for i=4 to limit by 2 do + sieve[i] = false + end for + for p=3 to floor(sqrt(limit)) by 2 do + integer p2 = p*p + if sieve[p2] then + for k=p2 to limit by p*2 do + sieve[k] = false + end for + end if + end for + return sieve +end function - constant lim = 1000035, - --constant lim = 100, -- (this works too) - limit = lim-(and_bits(lim,1)=0), -- (limit must be odd) - sieve = create_sieve(limit+6) -- (+6 to check for sexiness) +constant lim = 1000035, +--constant lim = 100, -- (this works too) + limit = lim-(and_bits(lim,1)=0), -- (limit must be odd) + sieve = create_sieve(limit+6) -- (+6 to check for sexiness) - sequence sets = repeat({},5), -- (unsexy,pairs,trips,quads,quins) - limits = {10,5,4,3,1}, - counts = 1&repeat(0,4) -- (2 is an unsexy prime) - integer total = 1 -- "" +sequence sets = repeat({},5), -- (unsexy,pairs,trips,quads,quins) + limits = {10,5,4,3,1}, + counts = 1&repeat(0,4) -- (2 is an unsexy prime) +integer total = 1 -- "" - for i=limit to 3 by -2 do -- (this loop skips 2) - if sieve[i] then - total += 1 - if sieve[i+6]=false and (i-6<0 or sieve[i-6]=false) then - counts[1] += 1 -- unsexy - if length(sets[1])<limits[1] then - sets[1] = prepend(sets[1],i) - end if - else - sequence set = {i} - for j=i-6 to 3 by -6 do - if j<=0 or sieve[j]=false then exit end if - set = prepend(set,j) - integer l = length(set) - if length(sets[l])<limits[l] then - sets[l] = prepend(sets[l],set) - end if - counts[l] += 1 - end for - end if - end if - end for - if length(sets[1])<limits[1] then - sets[1] = prepend(sets[1],2) -- (as 2 skipped above) - end if +for i=limit to 3 by -2 do -- (this loop skips 2) + if sieve[i] then + total += 1 + if sieve[i+6]=false and (i-6<0 or sieve[i-6]=false) then + counts[1] += 1 -- unsexy + if length(sets[1])constant
    fmt = """ - Of %,d primes less than %,d there are: - %,d unsexy primes, the last %d being %s - %,d pairs, the last %d being %s - %,d triplets, the last %d being %s - %,d quadruplets, the last %d being %s - %,d quintuplet, the last %d being %s - """ - sequence results = {total,lim, - 0,0,"", - 0,0,"", - 0,0,"", - 0,0,"", - 0,0,""} - for i=1 to 5 do - results[i*3..i*3+2] = {counts[i],length(sets[i]),sprint(sets[i])} - end for - printf(1,fmt,results) - - with javascript_semantics - enum X, Y - function shoelace(sequence s) - atom t = 0 - if length(s)>2 then - s = append(deep_copy(s),s[1]) - for i=1 to length(s)-1 do - t += s[i][X]*s[i+1][Y] - s[i+1][X]*s[i][Y] - end for - end if - return abs(t)/2 - end function +with javascript_semantics +enum X, Y +function shoelace(sequence s) + atom t = 0 + if length(s)>2 then + s = append(deep_copy(s),s[1]) + for i=1 to length(s)-1 do + t += s[i][X]*s[i+1][Y] - s[i+1][X]*s[i][Y] + end for + end if + return abs(t)/2 +end function - constant test = {{3,4},{5,11},{12,8},{9,5},{5,6}} - ?shoelace(test) - - with javascript_semantics - function shoelace(sequence s) - atom t = 0 - integer j = length(s) - if j!=0 then - sequence {x,y} = columnize(s) - for i=1 to j do - t += (y[j] + y[i]) * (x[j] - x[i]) - j = i - end for - end if - return abs(t)/2 - end function +with javascript_semantics +function shoelace(sequence s) + atom t = 0 + integer j = length(s) + if j!=0 then + sequence {x,y} = columnize(s) + for i=1 to j do + t += (y[j] + y[i]) * (x[j] - x[i]) + j = i + end for + end if + return abs(t)/2 +end function - constant test = {{3,4},{5,11},{12,8},{9,5},{5,6}} - ?shoelace(test) - - with javascript_semantics - function a(integer i) - printf(1,"a ") - return i - end function +with javascript_semantics +function a(integer i) + printf(1,"a ") + return i +end function - function b(integer i) - printf(1,"b ") - return i - end function +function b(integer i) + printf(1,"b ") + return i +end function - for z=0 to 1 do - for i=0 to 1 do - for j=0 to 1 do - if z then - printf(1,"a(%d) and b(%d) ",{i,j}) - printf(1," => %d\n",a(i) and b(j)) - else - printf(1,"a(%d) or b(%d) ",{i,j}) - printf(1," => %d\n",a(i) or b(j)) - end if - end for - end for - end for - - out <- p // (Go channels are _push_, not _pull_) - - base_primes := make(chan int) // separate primes supply - go Sieve(base_primes) - bp := <- base_primes // 2 <---- here - bq := bp * bp // 4 + gen := make(chan int) // Create a new channel + go Generate(gen) // Launch Generate goroutine + p := <- gen + out <- p + p = <- gen // make recursion shallower ----> + out <- p // (Go channels are _push_, not _pull_) - for { - p = <- gen - if p == bq { // square of a base prime - ft := make(chan int) - go Filter(gen, ft, bp) // filter multiples of bp in gen out - gen = ft - bp = <- base_primes // 3 - bq = bp * bp // 9 - } else { - out <- p - } - } + base_primes := make(chan int) // separate primes supply + go Sieve(base_primes) + bp := <- base_primes // 2 <---- here + bq := bp * bp // 4 + + for { + p = <- gen + if p == bq { // square of a base prime + ft := make(chan int) + go Filter(gen, ft, bp) // filter multiples of bp in gen out + gen = ft + bp = <- base_primes // 3 + bq = bp * bp // 9 + } else { + out <- p + } + } } func main() { - sv := make(chan int) // Create a new channel - go Sieve(sv) // Launch Sieve goroutine - lim := 25000 - for i := 0; i < lim; i++ { - prime := <- sv - if i >= (lim-10) { - fmt.Printf("%4d ", prime) - if (i+1)%20==0 { - fmt.Println("") - } - } - } + sv := make(chan int) // Create a new channel + go Sieve(sv) // Launch Sieve goroutine + lim := 25000 + for i := 0; i < lim; i++ { + prime := <- sv + if i >= (lim-10) { + fmt.Printf("%4d ", prime) + if (i+1)%20==0 { + fmt.Println("") + } + } + } } diff --git a/Task/Sieve-of-Eratosthenes/Java/sieve-of-eratosthenes-6.java b/Task/Sieve-of-Eratosthenes/Java/sieve-of-eratosthenes-6.java index afccf1681c..40b7227400 100644 --- a/Task/Sieve-of-Eratosthenes/Java/sieve-of-eratosthenes-6.java +++ b/Task/Sieve-of-Eratosthenes/Java/sieve-of-eratosthenes-6.java @@ -6,17 +6,17 @@ import java.math.BigInteger; public class InfiniteSieve implements Iterator { private static class NonPrimeSequence implements Comparable { - BigInteger currentMultiple; - BigInteger prime; + BigInteger currentMultiple; + BigInteger prime; - public NonPrimeSequence(BigInteger p) { - prime = p; - currentMultiple = p.multiply(p); // start at square of prime - } - @Override public int compareTo(NonPrimeSequence other) { - // sorted by value of current multiple - return currentMultiple.compareTo(other.currentMultiple); - } + public NonPrimeSequence(BigInteger p) { + prime = p; + currentMultiple = p.multiply(p); // start at square of prime + } + @Override public int compareTo(NonPrimeSequence other) { + // sorted by value of current multiple + return currentMultiple.compareTo(other.currentMultiple); + } } private BigInteger i = BigInteger.valueOf(2); @@ -26,29 +26,29 @@ public class InfiniteSieve implements Iterator { @Override public boolean hasNext() { return true; } @Override public BigInteger next() { - // skip non-prime numbers - for ( ; !nonprimes.isEmpty() && i.equals(nonprimes.peek().currentMultiple); i = i.add(BigInteger.ONE)) { + // skip non-prime numbers + for ( ; !nonprimes.isEmpty() && i.equals(nonprimes.peek().currentMultiple); i = i.add(BigInteger.ONE)) { // for each sequence that generates this number, // have it go to the next number (simply add the prime) // and re-position it in the priority queue - while (nonprimes.peek().currentMultiple.equals(i)) { - NonPrimeSequence x = nonprimes.poll(); - x.currentMultiple = x.currentMultiple.add(x.prime); - nonprimes.offer(x); - } - } - // prime + while (nonprimes.peek().currentMultiple.equals(i)) { + NonPrimeSequence x = nonprimes.poll(); + x.currentMultiple = x.currentMultiple.add(x.prime); + nonprimes.offer(x); + } + } + // prime // insert a NonPrimeSequence object into the priority queue - nonprimes.offer(new NonPrimeSequence(i)); - BigInteger result = i; - i = i.add(BigInteger.ONE); - return result; + nonprimes.offer(new NonPrimeSequence(i)); + BigInteger result = i; + i = i.add(BigInteger.ONE); + return result; } public static void main(String[] args) { - Iterator sieve = new InfiniteSieve(); - for (int i = 0; i < 25; i++) { - System.out.println(sieve.next()); - } + Iterator sieve = new InfiniteSieve(); + for (int i = 0; i < 25; i++) { + System.out.println(sieve.next()); + } } } diff --git a/Task/Sieve-of-Eratosthenes/JavaScript/sieve-of-eratosthenes-6.js b/Task/Sieve-of-Eratosthenes/JavaScript/sieve-of-eratosthenes-6.js index 13aa82d5ae..28e3bbb9c4 100644 --- a/Task/Sieve-of-Eratosthenes/JavaScript/sieve-of-eratosthenes-6.js +++ b/Task/Sieve-of-Eratosthenes/JavaScript/sieve-of-eratosthenes-6.js @@ -21,10 +21,10 @@ function eratosthenes(limit) { return primes; } var primes = eratosthenes(100); - output=''; + output=''; for (var i = 0; i < primes.length; i++) { - output+=primes[i]; - if (i < primes.length-1) output+=','; + output+=primes[i]; + if (i < primes.length-1) output+=','; } document.write(output); diff --git a/Task/Sieve-of-Eratosthenes/Julia/sieve-of-eratosthenes-1.julia b/Task/Sieve-of-Eratosthenes/Julia/sieve-of-eratosthenes-1.jl similarity index 100% rename from Task/Sieve-of-Eratosthenes/Julia/sieve-of-eratosthenes-1.julia rename to Task/Sieve-of-Eratosthenes/Julia/sieve-of-eratosthenes-1.jl diff --git a/Task/Sieve-of-Eratosthenes/Julia/sieve-of-eratosthenes-10.julia b/Task/Sieve-of-Eratosthenes/Julia/sieve-of-eratosthenes-10.jl similarity index 100% rename from Task/Sieve-of-Eratosthenes/Julia/sieve-of-eratosthenes-10.julia rename to Task/Sieve-of-Eratosthenes/Julia/sieve-of-eratosthenes-10.jl diff --git a/Task/Sieve-of-Eratosthenes/Julia/sieve-of-eratosthenes-2.julia b/Task/Sieve-of-Eratosthenes/Julia/sieve-of-eratosthenes-2.jl similarity index 100% rename from Task/Sieve-of-Eratosthenes/Julia/sieve-of-eratosthenes-2.julia rename to Task/Sieve-of-Eratosthenes/Julia/sieve-of-eratosthenes-2.jl diff --git a/Task/Sieve-of-Eratosthenes/Julia/sieve-of-eratosthenes-3.julia b/Task/Sieve-of-Eratosthenes/Julia/sieve-of-eratosthenes-3.jl similarity index 100% rename from Task/Sieve-of-Eratosthenes/Julia/sieve-of-eratosthenes-3.julia rename to Task/Sieve-of-Eratosthenes/Julia/sieve-of-eratosthenes-3.jl diff --git a/Task/Sieve-of-Eratosthenes/Julia/sieve-of-eratosthenes-4.julia b/Task/Sieve-of-Eratosthenes/Julia/sieve-of-eratosthenes-4.jl similarity index 100% rename from Task/Sieve-of-Eratosthenes/Julia/sieve-of-eratosthenes-4.julia rename to Task/Sieve-of-Eratosthenes/Julia/sieve-of-eratosthenes-4.jl diff --git a/Task/Sieve-of-Eratosthenes/Julia/sieve-of-eratosthenes-5.julia b/Task/Sieve-of-Eratosthenes/Julia/sieve-of-eratosthenes-5.jl similarity index 100% rename from Task/Sieve-of-Eratosthenes/Julia/sieve-of-eratosthenes-5.julia rename to Task/Sieve-of-Eratosthenes/Julia/sieve-of-eratosthenes-5.jl diff --git a/Task/Sieve-of-Eratosthenes/Julia/sieve-of-eratosthenes-6.julia b/Task/Sieve-of-Eratosthenes/Julia/sieve-of-eratosthenes-6.jl similarity index 100% rename from Task/Sieve-of-Eratosthenes/Julia/sieve-of-eratosthenes-6.julia rename to Task/Sieve-of-Eratosthenes/Julia/sieve-of-eratosthenes-6.jl diff --git a/Task/Sieve-of-Eratosthenes/Julia/sieve-of-eratosthenes-7.julia b/Task/Sieve-of-Eratosthenes/Julia/sieve-of-eratosthenes-7.jl similarity index 100% rename from Task/Sieve-of-Eratosthenes/Julia/sieve-of-eratosthenes-7.julia rename to Task/Sieve-of-Eratosthenes/Julia/sieve-of-eratosthenes-7.jl diff --git a/Task/Sieve-of-Eratosthenes/Julia/sieve-of-eratosthenes-8.julia b/Task/Sieve-of-Eratosthenes/Julia/sieve-of-eratosthenes-8.jl similarity index 100% rename from Task/Sieve-of-Eratosthenes/Julia/sieve-of-eratosthenes-8.julia rename to Task/Sieve-of-Eratosthenes/Julia/sieve-of-eratosthenes-8.jl diff --git a/Task/Sieve-of-Eratosthenes/Julia/sieve-of-eratosthenes-9.julia b/Task/Sieve-of-Eratosthenes/Julia/sieve-of-eratosthenes-9.jl similarity index 100% rename from Task/Sieve-of-Eratosthenes/Julia/sieve-of-eratosthenes-9.julia rename to Task/Sieve-of-Eratosthenes/Julia/sieve-of-eratosthenes-9.jl diff --git a/Task/Sieve-of-Eratosthenes/K/sieve-of-eratosthenes-1.k b/Task/Sieve-of-Eratosthenes/K/sieve-of-eratosthenes-1.k new file mode 100644 index 0000000000..5e6a244b23 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/K/sieve-of-eratosthenes-1.k @@ -0,0 +1,11 @@ +border:100 +// 2_ to filter 0 and 1 +sieve::2_!border +limitarray:2_!_%border +// add until higher than border with {xContext, args : list of string); + init : fn(ctxt : ref Draw->Context, args : list of string); }; init (ctxt: ref Draw->Context, args: list of string) { - sys = load Sys Sys->PATH; + sys = load Sys Sys->PATH; - limit := 201; - sieve : array of int; - sieve = array [201] of {* => 1}; - (sieve[0], sieve[1]) = (0, 0); + limit := 201; + sieve : array of int; + sieve = array [201] of {* => 1}; + (sieve[0], sieve[1]) = (0, 0); - for (n := 2; n < limit; n++) { - if (sieve[n]) { - for (i := n*n; i < limit; i += n) { - sieve[i] = 0; - } - } - } + for (n := 2; n < limit; n++) { + if (sieve[n]) { + for (i := n*n; i < limit; i += n) { + sieve[i] = 0; + } + } + } - for (n = 1; n < limit; n++) { - if (sieve[n]) { - print ("%4d", n); - } else { - print(" ."); - }; - if ((n%20) == 0) - print("\n\n"); - } + for (n = 1; n < limit; n++) { + if (sieve[n]) { + print ("%4d", n); + } else { + print(" ."); + }; + if ((n%20) == 0) + print("\n\n"); + } } diff --git a/Task/Sieve-of-Eratosthenes/Logtalk/sieve-of-eratosthenes-1.logtalk b/Task/Sieve-of-Eratosthenes/Logtalk/sieve-of-eratosthenes-1.logtalk index e169cc7b83..3b938f07bf 100644 --- a/Task/Sieve-of-Eratosthenes/Logtalk/sieve-of-eratosthenes-1.logtalk +++ b/Task/Sieve-of-Eratosthenes/Logtalk/sieve-of-eratosthenes-1.logtalk @@ -1,38 +1,38 @@ :- object(sieve). - :- public(primes/2). + :- public(primes/2). - :- coinductive([ - sieve/2, filter/3 - ]). + :- coinductive([ + sieve/2, filter/3 + ]). - % computes a coinductive list with all the primes in the 2..N interval - primes(N, Primes) :- - generate_infinite_list(N, List), - sieve(List, Primes). + % computes a coinductive list with all the primes in the 2..N interval + primes(N, Primes) :- + generate_infinite_list(N, List), + sieve(List, Primes). - % generate a coinductive list with a 2..N repeating patern - generate_infinite_list(N, List) :- - sequence(2, N, List, List). + % generate a coinductive list with a 2..N repeating patern + generate_infinite_list(N, List) :- + sequence(2, N, List, List). - sequence(Sup, Sup, [Sup| List], List) :- - !. - sequence(Inf, Sup, [Inf| List], Tail) :- - Next is Inf + 1, - sequence(Next, Sup, List, Tail). + sequence(Sup, Sup, [Sup| List], List) :- + !. + sequence(Inf, Sup, [Inf| List], Tail) :- + Next is Inf + 1, + sequence(Next, Sup, List, Tail). - sieve([H| T], [H| R]) :- - filter(H, T, F), - sieve(F, R). + sieve([H| T], [H| R]) :- + filter(H, T, F), + sieve(F, R). - filter(H, [K| T], L) :- - ( K > H, K mod H =:= 0 -> - % throw away the multiple we found - L = T1 - ; % we must not throw away the integer used for filtering - % as we must return a filtered coinductive list - L = [K| T1] - ), - filter(H, T, T1). + filter(H, [K| T], L) :- + ( K > H, K mod H =:= 0 -> + % throw away the multiple we found + L = T1 + ; % we must not throw away the integer used for filtering + % as we must return a filtered coinductive list + L = [K| T1] + ), + filter(H, T, T1). :- end_object. diff --git a/Task/Sieve-of-Eratosthenes/Lua/sieve-of-eratosthenes-1.lua b/Task/Sieve-of-Eratosthenes/Lua/sieve-of-eratosthenes-1.lua index df65311fc8..112f195531 100644 --- a/Task/Sieve-of-Eratosthenes/Lua/sieve-of-eratosthenes-1.lua +++ b/Task/Sieve-of-Eratosthenes/Lua/sieve-of-eratosthenes-1.lua @@ -2,9 +2,21 @@ function erato(n) if n < 2 then return {} end local t = {0} -- clears '1' local sqrtlmt = math.sqrt(n) - for i = 2, n do t[i] = 1 end - for i = 2, sqrtlmt do if t[i] ~= 0 then for j = i*i, n, i do t[j] = 0 end end end + for i = 2, n + do t[i] = 1 + end + for i = 2, sqrtlmt do + if t[i] ~= 0 then + for j = i*i, n, i do + t[j] = 0 + end + end + end local primes = {} - for i = 2, n do if t[i] ~= 0 then table.insert(primes, i) end end + for i = 2, n do + if t[i] ~= 0 then + table.insert(primes, i) + end + end return primes end diff --git a/Task/Sieve-of-Eratosthenes/Mojo/sieve-of-eratosthenes-1.mojo b/Task/Sieve-of-Eratosthenes/Mojo/sieve-of-eratosthenes-1.mojo index 1b6a5203b1..b7fc29dd44 100644 --- a/Task/Sieve-of-Eratosthenes/Mojo/sieve-of-eratosthenes-1.mojo +++ b/Task/Sieve-of-Eratosthenes/Mojo/sieve-of-eratosthenes-1.mojo @@ -16,10 +16,10 @@ struct SoEBasic(Sized): self.cmpsts = DTypePointer[DType.bool].alloc(limit - 1) memset_zero(self.cmpsts, limit - 1) for i in range(limit - 1): - let s = i * (i + 4) + 2 + var s = i * (i + 4) + 2 if s >= limit - 1: break if self.cmpsts[i]: continue - let bp = i + 2 + var bp = i + 2 for c in range(s, limit - 1, bp): self.cmpsts[c] = True for i in range(limit - 1): @@ -44,18 +44,18 @@ struct SoEBasic(Sized): if self.ndx >= self.len: return 0 while (self.ndx < self.len) and (self.cmpsts[self.ndx]): self.ndx += 1 - let rslt = self.ndx + 2; self.sz -= 1; self.ndx += 1 + var rslt = self.ndx + 2; self.sz -= 1; self.ndx += 1 return rslt fn main(): print("The primes to 100 are:") - for prm in SoEBasic(100): print_no_newline(prm, " ") + for prm in SoEBasic(100): print(prm, " ",end="") print() - let strt0 = now() - let answr0 = len(SoEBasic(1_000_000)) - let elpsd0 = (now() - strt0) / 1000000 + var strt0 = now() + var answr0 = len(SoEBasic(1_000_000)) + var elpsd0 = (now() - strt0) / 1000000 print("Found", answr0, "primes up to 1,000,000 in", elpsd0, "milliseconds.") - let strt1 = now() - let answr1 = len(SoEBasic(cLIMIT)) - let elpsd1 = (now() - strt1) / 1000000 + var strt1 = now() + var answr1 = len(SoEBasic(cLIMIT)) + var elpsd1 = (now() - strt1) / 1000000 print("Found", answr1, "primes up to", cLIMIT, "in", elpsd1, "milliseconds.") diff --git a/Task/Sieve-of-Eratosthenes/Mojo/sieve-of-eratosthenes-2.mojo b/Task/Sieve-of-Eratosthenes/Mojo/sieve-of-eratosthenes-2.mojo index 70a9704362..efcadd2ce6 100644 --- a/Task/Sieve-of-Eratosthenes/Mojo/sieve-of-eratosthenes-2.mojo +++ b/Task/Sieve-of-Eratosthenes/Mojo/sieve-of-eratosthenes-2.mojo @@ -1,6 +1,6 @@ from memory import (memset_zero, memcpy) from memory.unsafe import (DTypePointer) -from math.bit import ctpop +from bit import pop_count from time import (now) alias cLIMIT: Int = 1_000_000_000 @@ -13,14 +13,14 @@ alias UnrollFunc = fn(DTypePointer[DType.uint8], Int, Int, Int) -> None @always_inline fn extreme[OFST: Int, BP: Int](pcmps: DTypePointer[DType.uint8], bufsz: Int, s: Int, bp: Int): var cp = pcmps + (s >> 3) - let r1: Int = ((s + bp) >> 3) - (s >> 3) - let r2: Int = ((s + 2 * bp) >> 3) - (s >> 3) - let r3: Int = ((s + 3 * bp) >> 3) - (s >> 3) - let r4: Int = ((s + 4 * bp) >> 3) - (s >> 3) - let r5: Int = ((s + 5 * bp) >> 3) - (s >> 3) - let r6: Int = ((s + 6 * bp) >> 3) - (s >> 3) - let r7: Int = ((s + 7 * bp) >> 3) - (s >> 3) - let plmt: DTypePointer[DType.uint8] = pcmps + bufsz - r7 + var r1: Int = ((s + bp) >> 3) - (s >> 3) + var r2: Int = ((s + 2 * bp) >> 3) - (s >> 3) + var r3: Int = ((s + 3 * bp) >> 3) - (s >> 3) + var r4: Int = ((s + 4 * bp) >> 3) - (s >> 3) + var r5: Int = ((s + 5 * bp) >> 3) - (s >> 3) + var r6: Int = ((s + 6 * bp) >> 3) - (s >> 3) + var r7: Int = ((s + 7 * bp) >> 3) - (s >> 3) + var plmt: DTypePointer[DType.uint8] = pcmps + bufsz - r7 while cp < plmt: cp.store(cp.load() | (1 << OFST)) (cp + r1).store((cp + r1).load() | (1 << ((OFST + BP) & 7))) @@ -31,7 +31,7 @@ fn extreme[OFST: Int, BP: Int](pcmps: DTypePointer[DType.uint8], bufsz: Int, s: (cp + r6).store((cp + r6).load() | (1 << ((OFST + 6 * BP) & 7))) (cp + r7).store((cp + r7).load() | (1 << ((OFST + 7 * BP) & 7))) cp += bp - let eplmt: DTypePointer[DType.uint8] = plmt + r7 + var eplmt: DTypePointer[DType.uint8] = plmt + r7 if eplmt == cp or eplmt < cp: return cp.store(cp.load() | (1 << OFST)) cp += r1 @@ -56,86 +56,66 @@ fn extreme[OFST: Int, BP: Int](pcmps: DTypePointer[DType.uint8], bufsz: Int, s: if eplmt == cp or eplmt < cp: return cp.store(cp.load() | (1 << ((OFST + 7 * BP) & 7))) -fn mkExtrm[CNT: Int](pntr: Pointer[UnrollFunc]): +fn mkExtremeFuncs[SIZE: Int]() -> UnsafePointer[UnrollFunc, 0]: + var jmptbl = UnsafePointer[UnrollFunc, 0].alloc(SIZE) @parameter - if CNT >= 32: - return - alias OFST = CNT >> 2 - alias BP = ((CNT & 3) << 1) + 1 - pntr.offset(CNT).store(extreme[OFST, BP]) - mkExtrm[CNT + 1](pntr) - -@always_inline -fn mkExtremeFuncs() -> Pointer[UnrollFunc]: - let jmptbl: Pointer[UnrollFunc] = Pointer[UnrollFunc].alloc(32) - mkExtrm[0](jmptbl) + for i in range(SIZE): + alias OFST = i >> 2 + alias BP = ((i & 3) << 1) + 1 + jmptbl[i] = extreme[OFST, BP] return jmptbl -let extremeFuncs = mkExtremeFuncs() - alias DenseFunc = fn(DTypePointer[DType.uint64], Int, Int) -> DTypePointer[DType.uint64] -fn mkDenseCull[N: Int, BP: Int](cp: DTypePointer[DType.uint64]): - @parameter - if N >= 64: - return - alias MUL = N * BP - var cop = cp.offset(MUL >> 6) - cop.store(cop.load() | (1 << (MUL & 63))) - mkDenseCull[N + 1, BP](cp) - @always_inline fn denseCullFunc[BP: Int](pcmps: DTypePointer[DType.uint64], bufsz: Int, s: Int) -> DTypePointer[DType.uint64]: var cp: DTypePointer[DType.uint64] = pcmps + (s >> 6) - let plmt = pcmps + (bufsz >> 3) - BP + var plmt = pcmps + (bufsz >> 3) - BP while cp < plmt: - mkDenseCull[0, BP](cp) + @parameter + for n in range(64): + alias MUL = n * BP + var cop = cp.offset(MUL >> 6) + cop.store(cop.load() | (1 << (MUL & 63))) cp += BP return cp -fn mkDenseFunc[CNT: Int](pntr: Pointer[DenseFunc]): +fn mkDenseFuncs[SIZE: Int]() -> UnsafePointer[DenseFunc, 0]: + var jmptbl = UnsafePointer[DenseFunc, 0].alloc(SIZE) @parameter - if CNT >= 64: - return - alias BP = (CNT << 1) + 3 - pntr.offset(CNT).store(denseCullFunc[BP]) - mkDenseFunc[CNT + 1](pntr) - -@always_inline -fn mkDenseFuncs() -> Pointer[DenseFunc]: - let jmptbl : Pointer[DenseFunc] = Pointer[DenseFunc].alloc(64) - mkDenseFunc[0](jmptbl) + for i in range(SIZE): + alias BP = (i << 1) + 3 + jmptbl[i] = denseCullFunc[BP] return jmptbl -let denseFuncs : Pointer[DenseFunc] = mkDenseFuncs() - @always_inline -fn cullPass(cmpsts: DTypePointer[DType.uint8], bytesz: Int, s: Int, bp: Int): +fn cullPass(dfs: UnsafePointer[DenseFunc, 0], efs: UnsafePointer[UnrollFunc, 0], + cmpsts: DTypePointer[DType.uint8], bytesz: Int, s: Int, bp: Int): if bp <= 129: # dense culling var sm = s while (sm >> 3) < bytesz and (sm & 63) != 0: cmpsts[sm >> 3] |= (1 << (sm & 7)) sm += bp - let bcp = denseFuncs[(bp - 3) >> 1](cmpsts.bitcast[DType.uint64](), bytesz, sm) + var bcp = dfs[(bp - 3) >> 1](cmpsts.bitcast[DType.uint64](), bytesz, sm) var ns = 0 var ncp = bcp - let cmpstslmtp = (cmpsts + bytesz).bitcast[DType.uint64]() + var cmpstslmtp = (cmpsts + bytesz).bitcast[DType.uint64]() while ncp < cmpstslmtp: ncp[0] |= (1 << (ns & 63)) ns += bp ncp = bcp + (ns >> 6) else: # extreme loop unrolling culling - extremeFuncs[((s & 7) << 2) + ((bp & 7) >> 1)](cmpsts, bytesz, s, bp) -# for c in range(s, self.len, bp): # slow bit twiddling way -# self.cmpsts[c >> 3] |= (1 << (c & 7)) + efs[((s & 7) << 2) + ((bp & 7) >> 1)](cmpsts, bytesz, s, bp) +# for c in range(s, bytesz * 8, bp): # slow bit twiddling way +# cmpsts[c >> 3] |= (1 << (c & 7)) fn countPagePrimes(ptr: DTypePointer[DType.uint8], bitsz: Int) -> Int: - let wordsz: Int = (bitsz + 63) // 64 # round up to nearest 64 bit boundary + var wordsz: Int = (bitsz + 63) // 64 # round up to nearest 64 bit boundary var rslt: Int = wordsz * 64 - let bigcmps = ptr.bitcast[DType.uint64]() + var bigcmps = ptr.bitcast[DType.uint64]() for i in range(wordsz - 1): - rslt -= ctpop(bigcmps[i]).to_int() - rslt -= ctpop(bigcmps[wordsz - 1] | (-2 << ((bitsz - 1) & 63))).to_int() + rslt -= int(pop_count(bigcmps[i])) + rslt -= int(pop_count(bigcmps[wordsz - 1] | (-2 << ((bitsz - 1) & 63)))) return rslt struct SoEOdds(Sized): @@ -147,21 +127,23 @@ struct SoEOdds(Sized): self.len = 0 if limit < 2 else (limit - 3) // 2 + 1 self.sz = 0 if limit < 2 else self.len + 1 # for the unprocessed only even prime of two self.ndx = -1 - let bytesz = 0 if limit < 2 else ((self.len + 63) & -64) >> 3 # round up to nearest 64 bit boundary + var bytesz = 0 if limit < 2 else ((self.len + 63) & -64) >> 3 # round up to nearest 64 bit boundary self.cmpsts = DTypePointer[DType.uint8].alloc(bytesz) memset_zero(self.cmpsts, bytesz) + var denseFuncs : UnsafePointer[DenseFunc, 0] = mkDenseFuncs[64]() + var extremeFuncs: UnsafePointer[UnrollFunc, 0] = mkExtremeFuncs[32]() for i in range(self.len): - let s = (i + i) * (i + 3) + 3 + var s = (i + i) * (i + 3) + 3 if s >= self.len: break if (self.cmpsts[i >> 3] >> (i & 7)) & 1 != 0: continue - let bp = i + i + 3 - cullPass(self.cmpsts, bytesz, s, bp) + var bp = i + i + 3 + cullPass(denseFuncs, extremeFuncs, self.cmpsts, bytesz, s, bp) self.sz = countPagePrimes(self.cmpsts, self.len) + 1 # add one for only even prime of two fn __del__(owned self): self.cmpsts.free() fn __copyinit__(inout self, existing: Self): self.len = existing.len - let bytesz = (self.len + 7) // 8 + var bytesz = (self.len + 7) // 8 self.cmpsts = DTypePointer[DType.uint8].alloc(bytesz) memcpy(self.cmpsts, existing.cmpsts, bytesz) self.sz = existing.sz @@ -179,17 +161,17 @@ struct SoEOdds(Sized): self.ndx = 0; self.sz -= 1; return 2 while (self.ndx < self.len) and ((self.cmpsts[self.ndx >> 3] >> (self.ndx & 7)) & 1 != 0): self.ndx += 1 - let rslt = (self.ndx << 1) + 3; self.sz -= 1; self.ndx += 1; return rslt + var rslt = (self.ndx << 1) + 3; self.sz -= 1; self.ndx += 1; return rslt fn main(): print("The primes to 100 are:") - for prm in SoEOdds(100): print_no_newline(prm, " ") + for prm in SoEOdds(100): print(prm, " ", end="") print() - let strt0 = now() - let answr0 = len(SoEOdds(1_000_000)) - let elpsd0 = (now() - strt0) / 1000000 + var strt0 = now() + var answr0 = len(SoEOdds(1_000_000)) + var elpsd0 = (now() - strt0) / 1000000 print("Found", answr0, "primes up to 1,000,000 in", elpsd0, "milliseconds.") - let strt1 = now() - let answr1 = len(SoEOdds(cLIMIT)) - let elpsd1 = (now() - strt1) / 1000000 + var strt1 = now() + var answr1 = len(SoEOdds(cLIMIT)) + var elpsd1 = (now() - strt1) / 1000000 print("Found", answr1, "primes up to", cLIMIT, "in", elpsd1, "milliseconds.") diff --git a/Task/Sieve-of-Eratosthenes/Mojo/sieve-of-eratosthenes-3.mojo b/Task/Sieve-of-Eratosthenes/Mojo/sieve-of-eratosthenes-3.mojo index ef19e8e739..cd74a2cc1d 100644 --- a/Task/Sieve-of-Eratosthenes/Mojo/sieve-of-eratosthenes-3.mojo +++ b/Task/Sieve-of-Eratosthenes/Mojo/sieve-of-eratosthenes-3.mojo @@ -1,14 +1,13 @@ from memory import (memset_zero, memcpy) -from memory.unsafe import (DTypePointer) -from math.bit import ctpop -from time import (now) +from bit import pop_count +from time import monotonic alias cLIMIT: Int = 1_000_000_000 alias cBufferSize: Int = 262144 # bytes alias cBufferBits: Int = cBufferSize * 8 -fn intsqrt(n: UInt64) -> UInt64: +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 @@ -20,306 +19,317 @@ fn intsqrt(n: UInt64) -> UInt64: q = 1 << (qn - 2); qn = 0 else: q >>= 2 - let t: UInt64 = r + q + var t: UInt64 = r + q r >>= 1 if x >= t: x -= t; r += q return r -alias UnrollFunc = fn(DTypePointer[DType.uint8], Int, Int, Int) -> None +alias UnrollFunc = fn(UnsafePointer[UInt8], Int64, Int64, Int64) -> None @always_inline -fn extreme[OFST: Int, BP: Int](pcmps: DTypePointer[DType.uint8], bufsz: Int, s: Int, bp: Int): +fn extreme[OFST: Int64, BP: Int64](pcmps: UnsafePointer[UInt8], bufsz: Int64, s: Int64, bp: Int64): var cp = pcmps + (s >> 3) - let r1: Int = ((s + bp) >> 3) - (s >> 3) - let r2: Int = ((s + 2 * bp) >> 3) - (s >> 3) - let r3: Int = ((s + 3 * bp) >> 3) - (s >> 3) - let r4: Int = ((s + 4 * bp) >> 3) - (s >> 3) - let r5: Int = ((s + 5 * bp) >> 3) - (s >> 3) - let r6: Int = ((s + 6 * bp) >> 3) - (s >> 3) - let r7: Int = ((s + 7 * bp) >> 3) - (s >> 3) - let plmt: DTypePointer[DType.uint8] = pcmps + bufsz - r7 + var r1: Int64 = ((s + bp) >> 3) - (s >> 3) + var r2: Int64 = ((s + 2 * bp) >> 3) - (s >> 3) + var r3: Int64 = ((s + 3 * bp) >> 3) - (s >> 3) + var r4: Int64 = ((s + 4 * bp) >> 3) - (s >> 3) + var r5: Int64 = ((s + 5 * bp) >> 3) - (s >> 3) + var r6: Int64 = ((s + 6 * bp) >> 3) - (s >> 3) + var r7: Int64 = ((s + 7 * bp) >> 3) - (s >> 3) + var plmt: UnsafePointer[UInt8] = pcmps + bufsz - r7 while cp < plmt: - cp.store(cp.load() | (1 << OFST)) - (cp + r1).store((cp + r1).load() | (1 << ((OFST + BP) & 7))) - (cp + r2).store((cp + r2).load() | (1 << ((OFST + 2 * BP) & 7))) - (cp + r3).store((cp + r3).load() | (1 << ((OFST + 3 * BP) & 7))) - (cp + r4).store((cp + r4).load() | (1 << ((OFST + 4 * BP) & 7))) - (cp + r5).store((cp + r5).load() | (1 << ((OFST + 5 * BP) & 7))) - (cp + r6).store((cp + r6).load() | (1 << ((OFST + 6 * BP) & 7))) - (cp + r7).store((cp + r7).load() | (1 << ((OFST + 7 * BP) & 7))) + cp[] |= UInt8(1 << OFST) + cp[r1] |= UInt8(1 << ((OFST + BP) & 7)) + cp[r2] |= UInt8(1 << ((OFST + 2 * BP) & 7)) + cp[r3] |= UInt8(1 << ((OFST + 3 * BP) & 7)) + cp[r4] |= UInt8(1 << ((OFST + 4 * BP) & 7)) + cp[r5] |= UInt8(1 << ((OFST + 5 * BP) & 7)) + cp[r6] |= UInt8(1 << ((OFST + 6 * BP) & 7)) + cp[r7] |= UInt8(1 << ((OFST + 7 * BP) & 7)) cp += bp - let eplmt: DTypePointer[DType.uint8] = plmt + r7 + var eplmt: UnsafePointer[UInt8] = plmt + r7 if eplmt == cp or eplmt < cp: return - cp.store(cp.load() | (1 << OFST)) + cp[] |= UInt8(1 << OFST) cp += r1 if eplmt == cp or eplmt < cp: return - cp.store(cp.load() | (1 << ((OFST + BP) & 7))) + cp[] |= UInt8(1 << ((OFST + BP) & 7)) cp += r2 - r1 if eplmt == cp or eplmt < cp: return - cp.store(cp.load() | (1 << ((OFST + 2 * BP) & 7))) + cp[] |= UInt8(1 << ((OFST + 2 * BP) & 7)) cp += r3 - r2 if eplmt == cp or eplmt < cp: return - cp.store(cp.load() | (1 << ((OFST + 3 * BP) & 7))) + cp[] |= UInt8(1 << ((OFST + 3 * BP) & 7)) cp += r4 - r3 if eplmt == cp or eplmt < cp: return - cp.store(cp.load() | (1 << ((OFST + 4 * BP) & 7))) + cp[] |= UInt8(1 << ((OFST + 4 * BP) & 7)) cp += r5 - r4 if eplmt == cp or eplmt < cp: return - cp.store(cp.load() | (1 << ((OFST + 5 * BP) & 7))) + cp[] |= UInt8(1 << ((OFST + 5 * BP) & 7)) cp += r6 - r5 if eplmt == cp or eplmt < cp: return - cp.store(cp.load() | (1 << ((OFST + 6 * BP) & 7))) + cp[] |= UInt8(1 << ((OFST + 6 * BP) & 7)) cp += r7 - r6 if eplmt == cp or eplmt < cp: return - cp.store(cp.load() | (1 << ((OFST + 7 * BP) & 7))) + cp[] |= UInt8(1 << ((OFST + 7 * BP) & 7)) -fn mkExtrm[CNT: Int](pntr: Pointer[UnrollFunc]): +fn mkExtremeFuncs[SIZE: Int64]() -> UnsafePointer[UnrollFunc]: + var jmptbl = UnsafePointer[UnrollFunc].alloc(Int(SIZE)) @parameter - if CNT >= 32: - return - alias OFST = CNT >> 2 - alias BP = ((CNT & 3) << 1) + 1 - pntr.offset(CNT).store(extreme[OFST, BP]) - mkExtrm[CNT + 1](pntr) - -@always_inline -fn mkExtremeFuncs() -> Pointer[UnrollFunc]: - let jmptbl: Pointer[UnrollFunc] = Pointer[UnrollFunc].alloc(32) - mkExtrm[0](jmptbl) + for i in range(SIZE): + alias OFST = i >> 2 + alias BP = ((i & 3) << 1) + 1 + jmptbl[i] = extreme[OFST, BP] return jmptbl -let extremeFuncs = mkExtremeFuncs() - -alias DenseFunc = fn(DTypePointer[DType.uint64], Int, Int) -> DTypePointer[DType.uint64] - -fn mkDenseCull[N: Int, BP: Int](cp: DTypePointer[DType.uint64]): - @parameter - if N >= 64: - return - alias MUL = N * BP - var cop = cp.offset(MUL >> 6) - cop.store(cop.load() | (1 << (MUL & 63))) - mkDenseCull[N + 1, BP](cp) +alias DenseFunc = fn(UnsafePointer[UInt64], Int64, Int64) -> UnsafePointer[UInt64] @always_inline -fn denseCullFunc[BP: Int](pcmps: DTypePointer[DType.uint64], bufsz: Int, s: Int) -> DTypePointer[DType.uint64]: - var cp: DTypePointer[DType.uint64] = pcmps + (s >> 6) - let plmt = pcmps + (bufsz >> 3) - BP +fn denseCullFunc[BP: Int](pcmps: UnsafePointer[UInt64], bufsz: Int64, s: Int64) -> UnsafePointer[UInt64]: + var cp: UnsafePointer[UInt64] = pcmps + (s >> 6) + var plmt = pcmps + (bufsz >> 3) - BP while cp < plmt: - mkDenseCull[0, BP](cp) + @parameter + for n in range(64): + alias MUL = n * BP + var cop = cp.offset(MUL >> 6) + cop.store(cop.load() | (1 << (MUL & 63))) cp += BP return cp -fn mkDenseFunc[CNT: Int](pntr: Pointer[DenseFunc]): +fn mkDenseFuncs[SIZE: Int64]() -> UnsafePointer[DenseFunc]: + var jmptbl = UnsafePointer[DenseFunc].alloc(Int(SIZE)) @parameter - if CNT >= 64: - return - alias BP = (CNT << 1) + 3 - pntr.offset(CNT).store(denseCullFunc[BP]) - mkDenseFunc[CNT + 1](pntr) - -@always_inline -fn mkDenseFuncs() -> Pointer[DenseFunc]: - let jmptbl : Pointer[DenseFunc] = Pointer[DenseFunc].alloc(64) - mkDenseFunc[0](jmptbl) + for i in range(SIZE): + alias BP = (i << 1) + 3 + jmptbl[i] = denseCullFunc[Int(BP)] return jmptbl -let denseFuncs : Pointer[DenseFunc] = mkDenseFuncs() - @always_inline -fn cullPass(cmpsts: DTypePointer[DType.uint8], bytesz: Int, s: Int, bp: Int): +fn cullPass(dfs: UnsafePointer[DenseFunc], efs: UnsafePointer[UnrollFunc], + cmpsts: UnsafePointer[UInt8], bytesz: Int64, s: Int64, bp: Int64): if bp <= 129: # dense culling var sm = s while (sm >> 3) < bytesz and (sm & 63) != 0: - cmpsts[sm >> 3] |= (1 << (sm & 7)) + cmpsts[sm >> 3] |= UInt8(1 << (sm & 7)) sm += bp - let bcp = denseFuncs[(bp - 3) >> 1](cmpsts.bitcast[DType.uint64](), bytesz, sm) - var ns = 0 + var bcp = dfs[(bp - 3) >> 1](cmpsts.bitcast[UInt64](), bytesz, sm) + var ns: Int64 = 0 var ncp = bcp - let cmpstslmtp = (cmpsts + bytesz).bitcast[DType.uint64]() + var cmpstslmtp = (cmpsts + bytesz).bitcast[UInt64]() while ncp < cmpstslmtp: - ncp[0] |= (1 << (ns & 63)) + ncp[0] |= UInt64(1 << (ns & 63)) ns += bp ncp = bcp + (ns >> 6) else: # extreme loop unrolling culling - extremeFuncs[((s & 7) << 2) + ((bp & 7) >> 1)](cmpsts, bytesz, s, bp) -# for c in range(s, self.len, bp): # slow bit twiddling way -# self.cmpsts[c >> 3] |= (1 << (c & 7)) + efs[((s & 7) << 2) + ((bp & 7) >> 1)](cmpsts, bytesz, s, bp) +# else: +# for c in range(s, bytesz * 8, bp): # slow bit twiddling way +# cmpsts[c >> 3] |= (1 << (c & 7)) -fn cullPage(lwi: Int, lmt: Int, cmpsts: DTypePointer[DType.uint8], bsprmrps: DTypePointer[DType.uint8]): - var bp = 1; var ndx = 0 +fn cullPage(dfs: UnsafePointer[DenseFunc], efs: UnsafePointer[UnrollFunc], + lwi: Int64, lmt: Int64, cmpsts: UnsafePointer[UInt8], bsprmrps: UnsafePointer[UInt8]): + var bp: Int64 = 1; var ndx = 0 while True: - bp += bsprmrps[ndx].to_int() << 1 - let i = (bp - 3) >> 1 + bp += Int64(bsprmrps[ndx]) << 1 + var i = (bp - 3) >> 1 var s = (i + i) * (i + 3) + 3 if s >= lmt: break if s >= lwi: s -= lwi else: s = (lwi - s) % bp - if s != 0: s = bp - s - cullPass(cmpsts, cBufferSize, s, bp) + if s: s = bp - s + cullPass(dfs, efs, cmpsts, cBufferSize, s, bp) ndx += 1 -fn countPagePrimes(ptr: DTypePointer[DType.uint8], bitsz: Int) -> Int: - let wordsz: Int = (bitsz + 63) // 64 # round up to nearest 64 bit boundary - var rslt: Int = wordsz * 64 - let bigcmps = ptr.bitcast[DType.uint64]() +fn countPagePrimes(ptr: UnsafePointer[UInt8], bitsz: Int64) -> Int64: + var wordsz: Int64 = (bitsz + 63) // 64 # round up to nearest 64 bit boundary + var rslt: Int64 = wordsz * 64 + var bigcmps = ptr.bitcast[UInt64]() for i in range(wordsz - 1): - rslt -= ctpop(bigcmps[i]).to_int() - rslt -= ctpop(bigcmps[wordsz - 1] | (-2 << ((bitsz - 1) & 63))).to_int() + rslt -= Int64(pop_count(bigcmps[i])) + rslt -= Int64(pop_count(bigcmps[wordsz - 1] | UInt64(-2 << ((bitsz - 1) & 63)))) return rslt -struct SoEOdds(Sized): - var len: Int - var cmpsts: DTypePointer[DType.uint8] # because DynamicVector has deep copy bug in Mojo version 0.7 - var sz: Int - var ndx: Int - fn __init__(inout self, limit: Int): +struct SoEOdds(ImplicitlyCopyable, Movable, Sized, Iterable, Iterator): + alias __copyinit__is_trivial = False + alias __moveinit__is_trivial = False + alias __del__is_trivial = False + alias IteratorType[ + iterable_mut: Bool, //, iterable_origin: Origin[iterable_mut] + ]: Iterator = SoEOdds + alias Element = UInt64 + var len: Int64 + var cmpsts: UnsafePointer[UInt8] # because DynamicVector has deep copy bug in Mojo version 0.7 + var sz: Int64 + var ndx: Int64 + fn __init__(out self, limit: Int64): self.len = 0 if limit < 2 else (limit - 3) // 2 + 1 self.sz = 0 if limit < 2 else self.len + 1 # for the unprocessed only even prime of two self.ndx = -1 - let bytesz = 0 if limit < 2 else ((self.len + 63) & -64) >> 3 # round up to nearest 64 bit boundary - self.cmpsts = DTypePointer[DType.uint8].alloc(bytesz) - memset_zero(self.cmpsts, bytesz) + var bytesz = 0 if limit < 2 else ((self.len + 63) & -64) >> 3 # round up to nearest 64 bit boundary + self.cmpsts = UnsafePointer[UInt8].alloc(Int(bytesz)) + memset_zero(self.cmpsts, Int(bytesz)) + var denseFuncs : UnsafePointer[DenseFunc] = mkDenseFuncs[64]() + var extremeFuncs: UnsafePointer[UnrollFunc] = mkExtremeFuncs[32]() for i in range(self.len): - let s = (i + i) * (i + 3) + 3 + var s = (i + i) * (i + 3) + 3 if s >= self.len: break - if (self.cmpsts[i >> 3] >> (i & 7)) & 1 != 0: continue - let bp = i + i + 3 - cullPass(self.cmpsts, bytesz, s, bp) + if (self.cmpsts[i >> 3] >> UInt8(i & 7)) & 1: continue + var bp = i + i + 3 + cullPass(denseFuncs, extremeFuncs, self.cmpsts, bytesz, s, bp) self.sz = countPagePrimes(self.cmpsts, self.len) + 1 # add one for only even prime of two - fn __del__(owned self): + fn __del__(deinit self): self.cmpsts.free() - fn __copyinit__(inout self, existing: Self): + fn __copyinit__(out self, existing: Self): self.len = existing.len - let bytesz = (self.len + 7) // 8 - self.cmpsts = DTypePointer[DType.uint8].alloc(bytesz) - memcpy(self.cmpsts, existing.cmpsts, bytesz) + var bytesz = (self.len + 7) // 8 + self.cmpsts = UnsafePointer[UInt8].alloc(Int(bytesz)) + memcpy(self.cmpsts, existing.cmpsts, Int(bytesz)) self.sz = existing.sz self.ndx = existing.ndx - fn __moveinit__(inout self, owned existing: Self): + fn __moveinit__(out self, deinit existing: Self): self.len = existing.len self.cmpsts = existing.cmpsts self.sz = existing.sz self.ndx = existing.ndx - fn __len__(self: Self) -> Int: return self.sz - fn __iter__(self: Self) -> Self: return self + fn __len__(self: Self) -> Int: return Int(self.sz) + fn __iter__(ref self: Self) -> Self: return self @always_inline - fn __next__(inout self: Self) -> Int: + fn __has_next__(self: Self) -> Bool: + return self.sz > 0 + @always_inline + fn __next__(mut self: Self) -> Self.Element: if self.ndx < 0: self.ndx = 0; self.sz -= 1; return 2 - while (self.ndx < self.len) and ((self.cmpsts[self.ndx >> 3] >> (self.ndx & 7)) & 1 != 0): + while (self.ndx < self.len) and ((self.cmpsts[self.ndx >> 3] >> UInt8(self.ndx & 7)) & 1): self.ndx += 1 - let rslt = (self.ndx << 1) + 3; self.sz -= 1; self.ndx += 1; return rslt + var rslt = (UInt64(self.ndx) << 1) + 3; self.sz -= 1; self.ndx += 1; return rslt -struct SoEOddsPaged: - var len: Int - var cmpsts: DTypePointer[DType.uint8] # because DynamicVector has deep copy bug in Mojo version 0.7 - var sz: Int # 0 means finished; otherwise contains number of odd base primes - var ndx: Int - var lwi: Int - var bsprmrps: DTypePointer[DType.uint8] # contains deltas between odd base primes starting from zero - fn __init__(inout self, limit: UInt64): - self.len = 0 if limit < 2 else ((limit - 3) // 2 + 1).to_int() +struct SoEOddsPaged(ImplicitlyCopyable, Movable, Iterable, Iterator): + alias __copyinit__is_trivial = False + alias __moveinit__is_trivial = False + alias __del__is_trivial = False + alias IteratorType[ + iterable_mut: Bool, //, iterable_origin: Origin[iterable_mut] + ]: Iterator = SoEOddsPaged + alias Element = UInt64 + var denseFuncs : UnsafePointer[DenseFunc] + var extremeFuncs: UnsafePointer[UnrollFunc] + var len: Int64 + var cmpsts: UnsafePointer[UInt8] # because DynamicVector has deep copy bug in Mojo version 0.7 + var sz: Int64 # 0 means finished; otherwise contains number of odd base primes + var ndx: Int64 + var lwi: Int64 + var bsprmrps: UnsafePointer[UInt8] # contains deltas between odd base primes starting from zero + fn __init__(out self, limit: UInt64): + self.denseFuncs = mkDenseFuncs[64]() + self.extremeFuncs = mkExtremeFuncs[32]() + self.len = 0 if limit < 2 else Int(((limit - 3) // 2 + 1)) self.sz = 0 if limit < 2 else 1 # means iterate until this is set to zero self.ndx = -1 # for unprocessed only even prime of two self.lwi = 0 if self.len < cBufferBits: - let bytesz = ((self.len + 63) & -64) >> 3 # round up to nearest 64 bit boundary - self.cmpsts = DTypePointer[DType.uint8].alloc(bytesz) - self.bsprmrps = DTypePointer[DType.uint8].alloc(self.sz) + var bytesz = ((self.len + 63) & -64) >> 3 # round up to nearest 64 bit boundary + self.cmpsts = UnsafePointer[UInt8].alloc(Int(bytesz)) + self.bsprmrps = UnsafePointer[UInt8].alloc(Int(self.sz)) else: - self.cmpsts = DTypePointer[DType.uint8].alloc(cBufferSize) - let bsprmitr = SoEOdds(intsqrt(limit).to_int()) + self.cmpsts = UnsafePointer[UInt8].alloc(Int(cBufferSize)) + var bsprmitr = SoEOdds(Int(Intsqrt(limit))) self.sz = len(bsprmitr) - self.bsprmrps = DTypePointer[DType.uint8].alloc(self.sz) - var ndx = -1; var oldbp = 1 + self.bsprmrps = UnsafePointer[UInt8].alloc(Int(self.sz)) + var ndx = -1; var oldbp: UInt64 = 1 for bsprm in bsprmitr: if ndx < 0: ndx += 1; continue # skip over the 2 prime - self.bsprmrps[ndx] = (bsprm - oldbp) >> 1 + self.bsprmrps[ndx] = UInt8(bsprm - oldbp) >> 1 oldbp = bsprm; ndx += 1 self.bsprmrps[ndx] = 255 # one extra value to go beyond the necessary cull space - fn __del__(owned self): + fn __del__(deinit self): self.cmpsts.free(); self.bsprmrps.free() - fn __copyinit__(inout self, existing: Self): + fn __copyinit__(out self, existing: Self): + self.denseFuncs = existing.denseFuncs + self.extremeFuncs = existing.extremeFuncs self.len = existing.len self.sz = existing.sz - let bytesz = cBufferSize if self.len >= cBufferBits + var bytesz = cBufferSize if self.len >= cBufferBits else ((self.len + 63) & -64) >> 3 # round up to nearest 64 bit boundary - self.cmpsts = DTypePointer[DType.uint8].alloc(bytesz) - memcpy(self.cmpsts, existing.cmpsts, bytesz) + self.cmpsts = UnsafePointer[UInt8].alloc(Int(bytesz)) + memcpy(self.cmpsts, existing.cmpsts, Int(bytesz)) self.ndx = existing.ndx self.lwi = existing.lwi - self.bsprmrps = DTypePointer[DType.uint8].alloc(self.sz) - memcpy(self.bsprmrps, existing.bsprmrps, self.sz) - fn __moveinit__(inout self, owned existing: Self): + self.bsprmrps = UnsafePointer[UInt8].alloc(Int(self.sz)) + memcpy(self.bsprmrps, existing.bsprmrps, Int(self.sz)) + fn __moveinit__(out self, deinit existing: Self): + self.denseFuncs = existing.denseFuncs + self.extremeFuncs = existing.extremeFuncs self.len = existing.len self.cmpsts = existing.cmpsts self.sz = existing.sz self.ndx = existing.ndx self.lwi = existing.lwi self.bsprmrps = existing.bsprmrps - fn countPrimes(self) -> Int: + fn countPrimes(self) -> Int64: if self.len <= cBufferBits: return len(SoEOdds(2 * self.len + 1)) - var cnt = 1; var lwi = 0 - let cmpsts = DTypePointer[DType.uint8].alloc(cBufferSize) - memset_zero(cmpsts, cBufferSize) - cullPage(0, cBufferBits, cmpsts, self.bsprmrps) + var cnt: Int64 = 1; var lwi: Int64 = 0 + var cmpsts = UnsafePointer[UInt8].alloc(Int(cBufferSize)) + memset_zero(cmpsts, Int(cBufferSize)) + cullPage(self.denseFuncs, self.extremeFuncs, 0, cBufferBits, cmpsts, self.bsprmrps) while lwi + cBufferBits <= self.len: cnt += countPagePrimes(cmpsts, cBufferBits) lwi += cBufferBits - memset_zero(cmpsts, cBufferSize) - let lmt = lwi + cBufferBits if lwi + cBufferBits <= self.len else self.len - cullPage(lwi, lmt, cmpsts, self.bsprmrps) + memset_zero(cmpsts, Int(cBufferSize)) + var lmt = lwi + cBufferBits if lwi + cBufferBits <= self.len else self.len + cullPage(self.denseFuncs, self.extremeFuncs, lwi, lmt, cmpsts, self.bsprmrps) cnt += countPagePrimes(cmpsts, self.len - lwi) return cnt - fn __len__(self: Self) -> Int: return self.sz - fn __iter__(self: Self) -> Self: return self + fn __len__(self: Self) -> Int: return Int(self.sz) + fn __iter__(ref self: Self) -> Self: return self @always_inline - fn __next__(inout self: Self) -> Int: # don't count number of primes by interating - slooow + fn __has_next__(self: Self) -> Bool: + return self.sz > 0 + fn __next__(mut self: Self) -> Self.Element: # don't count number of primes by Interating - slooow if self.ndx < 0: self.ndx = 0; self.lwi = 0 if self.len < 2: self.sz = 0 elif self.len <= cBufferBits: - let bytesz = ((self.len + 63) & -64) >> 3 # round up to nearest 64 bit boundary - memset_zero(self.cmpsts, bytesz) + var bytesz = ((self.len + 63) & -64) >> 3 # round up to nearest 64 bit boundary + memset_zero(self.cmpsts, Int(bytesz)) for i in range(self.len): - let s = (i + i) * (i + 3) + 3 + var s = (i + i) * (i + 3) + 3 if s >= self.len: break - if (self.cmpsts[i >> 3] >> (i & 7)) & 1 != 0: continue - let bp = i + i + 3 - cullPass(self.cmpsts, bytesz, s, bp) + if (self.cmpsts[i >> 3] >> UInt8(i & 7)) & 1: continue + var bp = i + i + 3 + cullPass(self.denseFuncs, self.extremeFuncs, self.cmpsts, bytesz, s, bp) else: - memset_zero(self.cmpsts, cBufferSize) - cullPage(0, cBufferBits, self.cmpsts, self.bsprmrps) + memset_zero(self.cmpsts, Int(cBufferSize)) + cullPage(self.denseFuncs, self.extremeFuncs, 0, cBufferBits, self.cmpsts, self.bsprmrps) return 2 - let rslt = ((self.lwi + self.ndx) << 1) + 3; self.ndx += 1 + var rslt = (UInt64(self.lwi + self.ndx) << 1) + 3; self.ndx += 1 if self.lwi + cBufferBits >= self.len: - while (self.lwi + self.ndx < self.len) and ((self.cmpsts[self.ndx >> 3] >> (self.ndx & 7)) & 1 != 0): + while (self.lwi + self.ndx < self.len) and ((self.cmpsts[self.ndx >> 3] >> UInt8(self.ndx & 7)) & 1): self.ndx += 1 else: - while (self.ndx < cBufferBits) and ((self.cmpsts[self.ndx >> 3] >> (self.ndx & 7)) & 1 != 0): + while (self.ndx < cBufferBits) and ((self.cmpsts[self.ndx >> 3] >> UInt8(self.ndx & 7)) & 1): self.ndx += 1 while (self.ndx >= cBufferBits) and (self.lwi + cBufferBits <= self.len): - self.ndx = 0; self.lwi += cBufferBits; memset_zero(self.cmpsts, cBufferSize) - let lmt = self.lwi + cBufferBits if self.lwi + cBufferBits <= self.len else self.len - cullPage(self.lwi, lmt, self.cmpsts, self.bsprmrps) - let buflmt = cBufferBits if self.lwi + cBufferBits <= self.len else self.len - self.lwi - while (self.ndx < buflmt) and ((self.cmpsts[self.ndx >> 3] >> (self.ndx & 7)) & 1 != 0): + self.ndx = 0; self.lwi += cBufferBits; memset_zero(self.cmpsts, Int(cBufferSize)) + var lmt = self.lwi + cBufferBits if self.lwi + cBufferBits <= self.len else self.len + cullPage(self.denseFuncs, self.extremeFuncs, self.lwi, lmt, self.cmpsts, self.bsprmrps) + var buflmt = cBufferBits if self.lwi + cBufferBits <= self.len else self.len - self.lwi + while (self.ndx < buflmt) and ((self.cmpsts[self.ndx >> 3] >> UInt8(self.ndx & 7)) & 1): self.ndx += 1 if self.lwi + self.ndx >= self.len: self.sz = 0 return rslt fn main(): print("The primes to 100 are:") - for prm in SoEOddsPaged(100): print_no_newline(prm, " ") + for prm in SoEOddsPaged(100): print(prm, " ", end="") print() - let strt0 = now() - let answr0 = SoEOddsPaged(1_000_000).countPrimes() - let elpsd0 = (now() - strt0) / 1000000 + var strt0 = monotonic() + var answr0 = SoEOddsPaged(1_000_000).countPrimes() + var elpsd0 = (monotonic() - strt0) / 1000000 print("Found", answr0, "primes up to 1,000,000 in", elpsd0, "milliseconds.") - let strt1 = now() - let answr1 = SoEOddsPaged(cLIMIT).countPrimes() - let elpsd1 = (now() - strt1) / 1000000 + var strt1 = monotonic() + var answr1 = SoEOddsPaged(cLIMIT).countPrimes() + var elpsd1 = (monotonic() - strt1) / 1000000 print("Found", answr1, "primes up to", cLIMIT, "in", elpsd1, "milliseconds.") diff --git a/Task/Sieve-of-Eratosthenes/NewLISP/sieve-of-eratosthenes.l b/Task/Sieve-of-Eratosthenes/NewLISP/sieve-of-eratosthenes.l index afbd0443eb..7884088944 100644 --- a/Task/Sieve-of-Eratosthenes/NewLISP/sieve-of-eratosthenes.l +++ b/Task/Sieve-of-Eratosthenes/NewLISP/sieve-of-eratosthenes.l @@ -6,15 +6,15 @@ ; Keep working until the list is empty. (while sieve - ; The first number in the list is always prime - (set 'new-prime (sieve 0)) - (println new-prime) + ; The first number in the list is always prime + (set 'new-prime (sieve 0)) + (println new-prime) - ; Filter the list leaving only the non-multiples of each number. - (set 'sieve - (filter - (lambda (each-number) - (not (zero? (% each-number new-prime)))) - sieve))) + ; Filter the list leaving only the non-multiples of each number. + (set 'sieve + (filter + (lambda (each-number) + (not (zero? (% each-number new-prime)))) + sieve))) (exit) diff --git a/Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-1.ocaml b/Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-1.ml similarity index 100% rename from Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-1.ocaml rename to Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-1.ml diff --git a/Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-2.ocaml b/Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-2.ml similarity index 100% rename from Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-2.ocaml rename to Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-2.ml diff --git a/Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-3.ocaml b/Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-3.ml similarity index 100% rename from Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-3.ocaml rename to Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-3.ml diff --git a/Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-4.ocaml b/Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-4.ml similarity index 100% rename from Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-4.ocaml rename to Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-4.ml diff --git a/Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-5.ocaml b/Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-5.ml similarity index 100% rename from Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-5.ocaml rename to Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-5.ml diff --git a/Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-6.ocaml b/Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-6.ml similarity index 100% rename from Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-6.ocaml rename to Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-6.ml diff --git a/Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-7.ml b/Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-7.ml new file mode 100644 index 0000000000..aa96a2baf6 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-7.ml @@ -0,0 +1,47 @@ +let cLIMIT = 1_000_000 + +type 'a cis = CIS of 'a * (unit -> 'a cis) + +let primesTF() = + let rec merge (CIS(x, xtl) as xs) (CIS(y, ytl) as ys) = + if x < y then CIS(x, fun() -> merge (xtl()) ys) + else if y < x then CIS(y, fun() -> merge xs (ytl())) + else CIS(x, fun() -> merge (xtl()) (ytl())) + in let bpmults bp = + let adv = bp + bp in + let rec pmlt vr = CIS(vr, fun() -> pmlt (vr + adv)) + in pmlt (bp * bp) + in let rec allmlts = function + | CIS(bp, bptf) -> CIS(bpmults bp, fun() -> allmlts (bptf())) + in let rec pairs = function + | CIS(mcs, cstf) -> + let CIS(nmcs, ncstf) = cstf() in + CIS(merge mcs nmcs, fun() -> pairs (ncstf())) + in let rec cmpsts = function + | CIS(CIS(cr, ctfr), cstf) -> + CIS(cr, fun() -> merge (ctfr()) (cstf() |> pairs |> cmpsts)) + in let rec testAt n csr = + match csr with + | CIS(cr, ctlr) -> + if n >= cr then testAt (n + 2) (ctlr()) + else CIS(n, fun() -> testAt (n + 2) csr) + in let rec oddprms() = CIS(3, fun() -> oddprms() |> allmlts |> cmpsts |> testAt 5) + in CIS(2, fun() -> oddprms()) + +let showprmsTo lmt pcis = + let rec loop lst = function + | CIS(p, ptf) -> if p > lmt then List.rev lst |> List.map string_of_int + |> String.concat "; "|> print_endline + else loop (p :: lst) (ptf()) + in loop [] pcis + +let countprmsTo lmt pcis = + let rec loop cnt = function + | CIS(p, ptf) -> if p > lmt then cnt else loop (cnt + 1) (ptf()) + in loop 0 pcis + +let _ = showprmsTo 100 (primesTF()) +let strt = Sys.time() +let answr = countprmsTo cLIMIT (primesTF()) +let elpsd = (Sys.time() -. strt) *. 1000. +let _ = Printf.printf "Found %d primes to %d in %f milliseconds.\r\n" answr cLIMIT elpsd diff --git a/Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-8.ml b/Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-8.ml new file mode 100644 index 0000000000..e8250c81ac --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-8.ml @@ -0,0 +1,16 @@ +let sieve limit = + let p = Array.make (limit + 1) true in + let rec sieve_outer d = + if d * d > limit then p + else if p.(d) then + let rec sieve_inner m = + if m > limit then sieve_outer (d + 1) + else ((p.(m) <- false); sieve_inner (m + d)) + in sieve_inner (d * d) + else sieve_outer (d + 1) + in sieve_outer 2 + +let primes limit = + let s = (sieve limit) in + List.init (limit - 1) (fun i -> i + 2) + |> List.filter (fun x -> s.(x)) diff --git a/Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-9.ml b/Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-9.ml new file mode 100644 index 0000000000..4748dee4bb --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-9.ml @@ -0,0 +1,3 @@ +# primes 200;; +- : int list = +[2; 3; 5; 7; 11; 13; 17; 19; 23; 29; 31; 37; 41; 43; 47; 53; 59; 61; 67; 71; 73; 79; 83; 89; 97; 101; 103; 107; 109; 113; 127; 131; 137; 139; 149; 151; 157; 163; 167; 173; 179; 181; 191; 193; 197; 199] diff --git a/Task/Sieve-of-Eratosthenes/Odin/sieve-of-eratosthenes.odin b/Task/Sieve-of-Eratosthenes/Odin/sieve-of-eratosthenes.odin new file mode 100644 index 0000000000..54bcdb6513 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Odin/sieve-of-eratosthenes.odin @@ -0,0 +1,58 @@ +#+feature dynamic-literals +package main + +import "core:fmt" +import "core:math" +import "core:os" +import "core:strconv" + +main :: proc() { + + // start with sieve.exe 120 to get primes until 120 + n:=0 + ok:=false + assert(len(os.args)==2,"Give integer as argument!") + if len(os.args) == 2 { + argument := os.args[1] + n, ok = strconv.parse_int(argument) + assert(ok, "Second argument was not an integer") + assert(n>2, "n must be bigger than two") + } + + result := [dynamic]i64{0} + defer delete(result) + + for i:=1;i; +type primetype = (nonprime,prime); +begin + var sieve := |nonprime|*2 + |prime|*(N-1); + for var i:=2 to N.Sqrt.Trunc do + if sieve[i] = prime then + for var j := i*i to N step i do + sieve[j] := nonprime; + Result := new List; + for var i:=2 to N do + if sieve[i] = prime then + Result.Add(i); +end; + +begin + Eratosthenes(1000).Println +end. diff --git a/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-10.pl b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-10.pl index 73dff3b16f..8a0e58a164 100644 --- a/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-10.pl +++ b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-10.pl @@ -3,8 +3,8 @@ use warnings; package Tie::SieveOfEratosthenes; sub TIEARRAY { - my $class = shift; - bless \$class, $class; + my $class = shift; + bless \$class, $class; } # If set to true, produces copious output. Observing this output @@ -17,90 +17,90 @@ use constant WHEEL2 => 0; BEGIN { - # This is loosely based on the Python implementation of this task, - # specifically the "Infinite generator with a faster algorithm" + # This is loosely based on the Python implementation of this task, + # specifically the "Infinite generator with a faster algorithm" - my @primes = (2, 3); - my $ps = WHEEL2 ? 1 : 0; - my $p = $primes[$ps]; - my $q = $p*$p; - my $incr = WHEEL2 ? 2 : 1; - my $candidate = $primes[-1] + $incr; - my %sieve; - - print "Initial: p = $p, q = $q, candidate = $candidate\n" if DEBUG; + my @primes = (2, 3); + my $ps = WHEEL2 ? 1 : 0; + my $p = $primes[$ps]; + my $q = $p*$p; + my $incr = WHEEL2 ? 2 : 1; + my $candidate = $primes[-1] + $incr; + my %sieve; - sub FETCH { - my $n = pop; - return if $n < 0; - return $primes[$n] if $n <= $#primes; - OUTER: while( 1 ) { + print "Initial: p = $p, q = $q, candidate = $candidate\n" if DEBUG; - # each key in %sieve is a composite number between - # p and p-squared. Each value in %sieve is $incr x the prime - # which acted as a 'seed' for that key. We use the value - # to step through multiples of the seed-prime, until we find - # an empty slot in %sieve. - while( my $s = delete $sieve{$candidate} ) { - print "$candidate a multiple of ".($s/$incr).";\t\t" if DEBUG; - my $composite = $candidate + $s; - $composite += $s while exists $sieve{$composite}; - print "The next stored multiple of ".($s/$incr)." is $composite\n" if DEBUG; - $sieve{$composite} = $s; - $candidate += $incr; - } + sub FETCH { + my $n = pop; + return if $n < 0; + return $primes[$n] if $n <= $#primes; + OUTER: while( 1 ) { - print "Candidate $candidate is not in sieve\n" if DEBUG; + # each key in %sieve is a composite number between + # p and p-squared. Each value in %sieve is $incr x the prime + # which acted as a 'seed' for that key. We use the value + # to step through multiples of the seed-prime, until we find + # an empty slot in %sieve. + while( my $s = delete $sieve{$candidate} ) { + print "$candidate a multiple of ".($s/$incr).";\t\t" if DEBUG; + my $composite = $candidate + $s; + $composite += $s while exists $sieve{$composite}; + print "The next stored multiple of ".($s/$incr)." is $composite\n" if DEBUG; + $sieve{$composite} = $s; + $candidate += $incr; + } - while( $candidate < $q ) { - print "$candidate is prime\n" if DEBUG; - push @primes, $candidate; - $candidate += $incr; - next OUTER if exists $sieve{$candidate}; - } + print "Candidate $candidate is not in sieve\n" if DEBUG; - die "Candidate = $candidate, p = $p, q = $q" if $candidate > $q; - print "Candidate $candidate is equal to $p squared;\t" if DEBUG; + while( $candidate < $q ) { + print "$candidate is prime\n" if DEBUG; + push @primes, $candidate; + $candidate += $incr; + next OUTER if exists $sieve{$candidate}; + } - # Thus, it is now time to add p to the sieve, - my $step = $incr * $p; - my $composite = $q + $step; - $composite += $step while exists $sieve{$composite}; - print "The next multiple of $p is $composite\n" if DEBUG; - $sieve{$composite} = $step; - - # and fetch out a new value for p from our primes array. - $p = $primes[++$ps]; - $q = $p * $p; - - # And since $candidate was equal to some prime squared, - # it's obviously composite, and we need to increment it. - $candidate += $incr; - print "p is $p, q is $q, candidate is $candidate\n" if DEBUG; - } continue { - return $primes[$n] if $n <= $#primes; - } - } + die "Candidate = $candidate, p = $p, q = $q" if $candidate > $q; + print "Candidate $candidate is equal to $p squared;\t" if DEBUG; + + # Thus, it is now time to add p to the sieve, + my $step = $incr * $p; + my $composite = $q + $step; + $composite += $step while exists $sieve{$composite}; + print "The next multiple of $p is $composite\n" if DEBUG; + $sieve{$composite} = $step; + + # and fetch out a new value for p from our primes array. + $p = $primes[++$ps]; + $q = $p * $p; + + # And since $candidate was equal to some prime squared, + # it's obviously composite, and we need to increment it. + $candidate += $incr; + print "p is $p, q is $q, candidate is $candidate\n" if DEBUG; + } continue { + return $primes[$n] if $n <= $#primes; + } + } } if( !caller ) { - tie my (@prime_list), 'Tie::SieveOfEratosthenes'; - my $limit = $ARGV[0] || 100; - my $line = ""; - for( my $count = 0; $prime_list[$count] < $limit; ++$count ) { - $line .= $prime_list[$count]. ", "; - next if length($line) <= 70; - if( $line =~ tr/,// > 1 ) { - $line =~ s/^(.*,) (.*, )/$2/; - print $1, "\n"; - } else { - print $line, "\n"; - $line = ""; - } - } - $line =~ s/, \z//; - print $line, "\n" if $line; + tie my (@prime_list), 'Tie::SieveOfEratosthenes'; + my $limit = $ARGV[0] || 100; + my $line = ""; + for( my $count = 0; $prime_list[$count] < $limit; ++$count ) { + $line .= $prime_list[$count]. ", "; + next if length($line) <= 70; + if( $line =~ tr/,// > 1 ) { + $line =~ s/^(.*,) (.*, )/$2/; + print $1, "\n"; + } else { + print $line, "\n"; + $line = ""; + } + } + $line =~ s/, \z//; + print $line, "\n" if $line; } 1; diff --git a/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-6.pl b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-6.pl index b9b9db360d..15bb7dfb5f 100644 --- a/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-6.pl +++ b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-6.pl @@ -1,7 +1,7 @@ sub sieve{ my (@s, $i); - grep { not $s[ $i = $_ ] and do - { $s[ $i += $_ ]++ while $i <= $_[0]; 1 } - } 2..$_[0] + grep { not $s[ $i = $_ ] and do + { $s[ $i += $_ ]++ while $i <= $_[0]; 1 } + } 2..$_[0] } print join ", " => sieve 100; diff --git a/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-7.pl b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-7.pl index d1c4825ca1..d7b152b0ae 100644 --- a/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-7.pl +++ b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-7.pl @@ -1,7 +1,7 @@ sub sieve{ my ($s, $i); - grep { not vec $s, $i = $_, 1 and do - { (vec $s, $i += $_, 1) = 1 while $i <= $_[0]; 1 } - } 2..$_[0] + grep { not vec $s, $i = $_, 1 and do + { (vec $s, $i += $_, 1) = 1 while $i <= $_[0]; 1 } + } 2..$_[0] } print join ", " => sieve 100; diff --git a/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-9.pl b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-9.pl index 8d9cc27e14..ac55cbfa1f 100644 --- a/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-9.pl +++ b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-9.pl @@ -1,12 +1,12 @@ sub sieve { - my ($s, $p) = "." . ("x" x shift); + my ($s, $p) = "." . ("x" x shift); - 1 while ++$p - and $s =~ /^(.{$p,}?)x/g - and $p = length($1) - and $s =~ s/(.{$p})./${1}./g - and substr($s, $p, 1) = "x"; - $s + 1 while ++$p + and $s =~ /^(.{$p,}?)x/g + and $p = length($1) + and $s =~ s/(.{$p})./${1}./g + and substr($s, $p, 1) = "x"; + $s } print sieve(1000); diff --git a/Task/Sieve-of-Eratosthenes/PostScript/sieve-of-eratosthenes-1.ps b/Task/Sieve-of-Eratosthenes/PostScript/sieve-of-eratosthenes-1.ps new file mode 100644 index 0000000000..0ed088a4b7 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/PostScript/sieve-of-eratosthenes-1.ps @@ -0,0 +1,35 @@ +%!PS +% Calculate primes using the Sieve of Eratosthenes +% and dump the result to the console. + +/sieve +{ + % Usage: maxnumber sieve + % primes... 5 3 2 + /limit exch def + % Generate an array of all the numbers, representing the prime candidates + % (Start at 0 for ease of indexing.) + [ 0 1 limit { } for ] + % Replace all composite numbers by 0 + dup 1 0 put + 2 1 limit sqrt floor + { + 1 index exch get dup 0 ne + { + dup dup mul exch limit { 1 index exch 0 put } for + } { pop } ifelse + } for + % The stack now contains an array of primes and zeroes. + % Push the primes onto the stack with the smallest at the top: + limit -1 1 + { + exch dup 3 -1 roll get dup + 0 eq { pop } { exch } ifelse + } for + pop + % The stack now contains the list of primes (smallest = 2 on top) +} bind def + +300 sieve pstack % <-- replace "300" with the desired maximum number to check. +% 300000 sieve pstack +%%EOF diff --git a/Task/Sieve-of-Eratosthenes/PostScript/sieve-of-eratosthenes-2.ps b/Task/Sieve-of-Eratosthenes/PostScript/sieve-of-eratosthenes-2.ps new file mode 100644 index 0000000000..f4ecd7c6ed --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/PostScript/sieve-of-eratosthenes-2.ps @@ -0,0 +1,74 @@ +%!PS +% Calculate primes using the Sieve of Eratosthenes and +% print them out. + +/sieve +{ + % Usage: maxnumber sieve + % primes... 5 3 2 + /limit exch def + % Generate an array of all the numbers, representing the prime candidates + % (Start at 0 for ease of indexing.) + [ 0 1 limit { } for ] + % Replace all composite numbers by 0 + dup 1 0 put + 2 1 limit sqrt floor + { + 1 index exch get dup 0 ne + { + dup dup mul exch limit { 1 index exch 0 put } for + } { pop } ifelse + } for + % The stack now contains an array of primes and zeroes. + % Push the primes onto the stack with the smallest at the top: + limit -1 1 + { + exch dup 3 -1 roll get dup + 0 eq { pop } { exch } ifelse + } for + pop + % The stack now contains the list of primes (smallest = 2 on top) +} bind def + +/showstack +{ + % Usage: primes... 5 3 2 showstack + % - + % (This is just for output. No business logic here.) + + /fontsize 12 def + /lineheight fontsize 3 add def + /Helvetica findfont + fontsize scalefont setfont + /margin 30 def + /left margin def + /bottom margin def + currentpagedevice /PageSize get aload pop + margin sub fontsize sub /top exch def + margin sub /right exch def + + /buffer 42 string def + left top moveto + 1 1 count 2 sub + { pop dup 0 ne + { + buffer cvs + dup stringwidth pop currentpoint pop add + right gt { + left currentpoint exch pop lineheight sub + dup bottom lt { + showpage + pop top + } if + moveto + } if + show + ( ) show + } { pop } ifelse + } for + showpage +} bind def + +300 sieve showstack % <-- replace "300" with the desired maximum number to check. +% 300000 sieve showstack % will yield about 40 A4 pages +%%EOF diff --git a/Task/Sieve-of-Eratosthenes/PostScript/sieve-of-eratosthenes-3.ps b/Task/Sieve-of-Eratosthenes/PostScript/sieve-of-eratosthenes-3.ps new file mode 100644 index 0000000000..7985d4b3bb --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/PostScript/sieve-of-eratosthenes-3.ps @@ -0,0 +1,47 @@ +%!PS +% Calculate primes using the Sieve of Eratosthenes +% and dump the result to the console. +% (Stack-centric implementation without direct memory access) + +/sieve +{ + % Usage: maxnumber sieve + % primes... 5 3 2 + % Put all the candidates on the stack (1 = lowest number on top) + % but always keep our max number on top of stack (i.e., index 0) + dup -1 2 { exch } for + 0 exch % 1 is no prime + + % Phase 1: find next prime (up to sqrt(limit)), + % mark all multiples by setting to 0. + dup 2 1 3 -1 roll sqrt floor + { + dup 2 add -1 roll + dup 3 -1 roll 2 add 1 roll + dup + 0 ne + { % Found a prime. Delete all multiples, starting with square of this prime. + dup dup mul exch 2 index + { + dup 2 add -1 roll + pop + 0 exch 1 add 1 roll + } for + } { pop } % known composite: no action needed. + ifelse + } for + + % Phase 2: find all primes (i.e., non-zero numbers), push them + % densely on the stack, starting from highest. + % Always keep the current stack size on top + dup 1 add exch + { + dup -1 roll dup + 0 ne { exch } { pop 1 sub } ifelse + } repeat + pop % remove stack size + % The stack now contains the list of primes (smallest = 2 on top) +} bind def + +300 sieve pstack +%%EOF diff --git a/Task/Sieve-of-Eratosthenes/PowerShell/sieve-of-eratosthenes-1.psh b/Task/Sieve-of-Eratosthenes/PowerShell/sieve-of-eratosthenes-1.ps1 similarity index 100% rename from Task/Sieve-of-Eratosthenes/PowerShell/sieve-of-eratosthenes-1.psh rename to Task/Sieve-of-Eratosthenes/PowerShell/sieve-of-eratosthenes-1.ps1 diff --git a/Task/Sieve-of-Eratosthenes/PowerShell/sieve-of-eratosthenes-2.psh b/Task/Sieve-of-Eratosthenes/PowerShell/sieve-of-eratosthenes-2.ps1 similarity index 100% rename from Task/Sieve-of-Eratosthenes/PowerShell/sieve-of-eratosthenes-2.psh rename to Task/Sieve-of-Eratosthenes/PowerShell/sieve-of-eratosthenes-2.ps1 diff --git a/Task/Sieve-of-Eratosthenes/Prolog/sieve-of-eratosthenes-1.pro b/Task/Sieve-of-Eratosthenes/Prolog/sieve-of-eratosthenes-1.pro index 50b2ae4b1b..cef303ddfa 100644 --- a/Task/Sieve-of-Eratosthenes/Prolog/sieve-of-eratosthenes-1.pro +++ b/Task/Sieve-of-Eratosthenes/Prolog/sieve-of-eratosthenes-1.pro @@ -1,5 +1,5 @@ primes(N, L) :- numlist(2, N, Xs), - sieve(Xs, L). + sieve(Xs, L). sieve([H|T], [H|X]) :- H2 is H + H, filter(H, H2, T, R), diff --git a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-10.py b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-10.py index 5ada4786d0..53b4e9ef99 100644 --- a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-10.py +++ b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-10.py @@ -1,12 +1,7 @@ ->>> primes_upto3(10**6, smallprimes=(2,3)) # Wall time: 0.17 -array([ 2, 3, 5, ..., 999961, 999979, 999983]) ->>> primes_upto3(10**7, smallprimes=(2,3)) # Wall time: '''2.13''' -array([ 2, 3, 5, ..., 9999971, 9999973, 9999991]) ->>> primes_upto3(15) -array([ 2, 3, 5, 7, 11, 13]) ->>> primes_upto3(10**7, smallprimes=primes_upto3(15)) # Wall time: '''1.31''' -array([ 2, 3, 5, ..., 9999971, 9999973, 9999991]) ->>> primes_upto2(10**7) # Wall time: '''1.39''' <-- version ''without'' wheels -array([ 2, 3, 5, ..., 9999971, 9999973, 9999991]) ->>> primes_upto3(10**7) # Wall time: '''1.30''' -array([ 2, 3, 5, ..., 9999971, 9999973, 9999991]) +import numpy +def primes_upto2(limit): + is_prime = numpy.ones(limit + 1, dtype=numpy.bool) + for n in xrange(2, int(limit**0.5 + 1.5)): + if is_prime[n]: + is_prime[n*n::n] = 0 + return numpy.nonzero(is_prime)[0][2:] diff --git a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-11.py b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-11.py index 8022a40075..1cdb64c793 100644 --- a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-11.py +++ b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-11.py @@ -1,28 +1,20 @@ -import heapq - -# generates all prime numbers -def sieve(): - # priority queue of the sequences of non-primes - # the priority queue allows us to get the "next" non-prime quickly - nonprimes = [] - - i = 2 - while True: - if nonprimes and i == nonprimes[0][0]: # non-prime - while nonprimes[0][0] == i: - # for each sequence that generates this number, - # have it go to the next number (simply add the prime) - # and re-position it in the priority queue - x = nonprimes[0] - x[0] += x[1] - heapq.heapreplace(nonprimes, x) - - else: # prime - # insert a 2-element list into the priority queue: - # [current multiple, prime] - # the first element allows sorting by value of current multiple - # we start with i^2 - heapq.heappush(nonprimes, [i*i, i]) - yield i - - i += 1 +from numpy import array, bool_, multiply, nonzero, ones, put, resize +# +def makepattern(smallprimes): + pattern = ones(multiply.reduce(smallprimes), dtype=bool_) + pattern[0] = 0 + for p in smallprimes: + pattern[p::p] = 0 + return pattern +# +def primes_upto3(limit, smallprimes=(2,3,5,7,11)): + sp = array(smallprimes) + if limit <= sp.max(): return sp[sp <= limit] + # + isprime = resize(makepattern(sp), limit + 1) + isprime[:2] = 0; put(isprime, sp, 1) + # + for n in range(sp.max() + 2, int(limit**0.5 + 1.5), 2): + if isprime[n]: + isprime[n*n::n] = 0 + return nonzero(isprime)[0] diff --git a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-12.py b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-12.py index 1ec9c2285d..5ada4786d0 100644 --- a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-12.py +++ b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-12.py @@ -1,24 +1,12 @@ -def primes(): - yield 2; yield 3; yield 5; yield 7; - bps = (p for p in primes()) # separate supply of "base" primes (b.p.) - p = next(bps) and next(bps) # discard 2, then get 3 - q = p * p # 9 - square of next base prime to keep track of, - sieve = {} # in the sieve dict - n = 9 # n is the next candidate number - while True: - if n not in sieve: # n is not a multiple of any of base primes, - if n < q: # below next base prime's square, so - yield n # n is prime - else: - p2 = p + p # n == p * p: for prime p, add p * p + 2 * p - sieve[q + p2] = p2 # to the dict, with 2 * p as the increment step - p = next(bps); q = p * p # pull next base prime, and get its square - else: - s = sieve.pop(n); nxt = n + s # n's a multiple of some b.p., find next multiple - while nxt in sieve: nxt += s # ensure each entry is unique - sieve[nxt] = s # nxt is next non-marked multiple of this prime - n += 2 # work on odds only - -import itertools -def primes_up_to(limit): - return list(itertools.takewhile(lambda p: p <= limit, primes())) +>>> primes_upto3(10**6, smallprimes=(2,3)) # Wall time: 0.17 +array([ 2, 3, 5, ..., 999961, 999979, 999983]) +>>> primes_upto3(10**7, smallprimes=(2,3)) # Wall time: '''2.13''' +array([ 2, 3, 5, ..., 9999971, 9999973, 9999991]) +>>> primes_upto3(15) +array([ 2, 3, 5, 7, 11, 13]) +>>> primes_upto3(10**7, smallprimes=primes_upto3(15)) # Wall time: '''1.31''' +array([ 2, 3, 5, ..., 9999971, 9999973, 9999991]) +>>> primes_upto2(10**7) # Wall time: '''1.39''' <-- version ''without'' wheels +array([ 2, 3, 5, ..., 9999971, 9999973, 9999991]) +>>> primes_upto3(10**7) # Wall time: '''1.30''' +array([ 2, 3, 5, ..., 9999971, 9999973, 9999991]) diff --git a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-13.py b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-13.py index e3f2aa1d6c..8022a40075 100644 --- a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-13.py +++ b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-13.py @@ -1,30 +1,28 @@ -def primes(): - for p in [2,3,5,7]: yield p # base wheel primes - gaps1 = [ 2,4,2,4,6,2,6,4,2,4,6,6,2,6,4,2,6,4,6,8,4,2,4,2,4,8 ] - gaps = gaps1 + [ 6,4,6,2,4,6,2,6,6,4,2,4,6,2,6,4,2,4,2,10,2,10 ] # wheel2357 - def wheel_prime_pairs(): - yield (11,0); bps = wheel_prime_pairs() # additional primes supply - p, pi = next(bps); q = p * p # adv to get 11 sqr'd is 121 as next square to put - sieve = {}; n = 13; ni = 1 # into sieve dict; init cndidate, wheel ndx - while True: - if n not in sieve: # is not a multiple of previously recorded primes - if n < q: yield (n, ni) # n is prime with wheel modulo index - else: - npi = pi + 1 # advance wheel index - if npi > 47: npi = 0 - sieve[q + p * gaps[pi]] = (p, npi) # n == p * p: put next cull position on wheel - p, pi = next(bps); q = p * p # advance next prime and prime square to put - else: - s, si = sieve.pop(n) - nxt = n + s * gaps[si] # move current cull position up the wheel - si = si + 1 # advance wheel index - if si > 47: si = 0 - while nxt in sieve: # ensure each entry is unique by wheel - nxt += s * gaps[si] - si = si + 1 # advance wheel index - if si > 47: si = 0 - sieve[nxt] = (s, si) # next non-marked multiple of a prime - nni = ni + 1 # advance wheel index - if nni > 47: nni = 0 - n += gaps[ni]; ni = nni # advance on the wheel - for p, pi in wheel_prime_pairs(): yield p # strip out indexes +import heapq + +# generates all prime numbers +def sieve(): + # priority queue of the sequences of non-primes + # the priority queue allows us to get the "next" non-prime quickly + nonprimes = [] + + i = 2 + while True: + if nonprimes and i == nonprimes[0][0]: # non-prime + while nonprimes[0][0] == i: + # for each sequence that generates this number, + # have it go to the next number (simply add the prime) + # and re-position it in the priority queue + x = nonprimes[0] + x[0] += x[1] + heapq.heapreplace(nonprimes, x) + + else: # prime + # insert a 2-element list into the priority queue: + # [current multiple, prime] + # the first element allows sorting by value of current multiple + # we start with i^2 + heapq.heappush(nonprimes, [i*i, i]) + yield i + + i += 1 diff --git a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-14.py b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-14.py index 6f54e138c7..1ec9c2285d 100644 --- a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-14.py +++ b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-14.py @@ -1,40 +1,24 @@ def primes(): - whlPrms = [2,3,5,7,11,13,17] # base wheel primes - for p in whlPrms: yield p - def makeGaps(): - buf = [True] * (3 * 5 * 7 * 11 * 13 * 17 + 1) # all odds plus extra for o/f - for p in whlPrms: - if p < 3: - continue # no need to handle evens - strt = (p * p - 19) >> 1 # start position (divided by 2 using shift) - while strt < 0: strt += p - buf[strt::p] = [False] * ((len(buf) - strt - 1) // p + 1) # cull for p - whlPsns = [i + i for i,v in enumerate(buf) if v] - return [whlPsns[i + 1] - whlPsns[i] for i in range(len(whlPsns) - 1)] - gaps = makeGaps() # big wheel gaps - def wheel_prime_pairs(): - yield (19,0); bps = wheel_prime_pairs() # additional primes supply - p, pi = next(bps); q = p * p # adv to get 11 sqr'd is 121 as next square to put - sieve = {}; n = 23; ni = 1 # into sieve dict; init cndidate, wheel ndx - while True: - if n not in sieve: # is not a multiple of previously recorded primes - if n < q: yield (n, ni) # n is prime with wheel modulo index - else: - npi = pi + 1 # advance wheel index - if npi > 92159: npi = 0 - sieve[q + p * gaps[pi]] = (p, npi) # n == p * p: put next cull position on wheel - p, pi = next(bps); q = p * p # advance next prime and prime square to put + yield 2; yield 3; yield 5; yield 7; + bps = (p for p in primes()) # separate supply of "base" primes (b.p.) + p = next(bps) and next(bps) # discard 2, then get 3 + q = p * p # 9 - square of next base prime to keep track of, + sieve = {} # in the sieve dict + n = 9 # n is the next candidate number + while True: + if n not in sieve: # n is not a multiple of any of base primes, + if n < q: # below next base prime's square, so + yield n # n is prime else: - s, si = sieve.pop(n) - nxt = n + s * gaps[si] # move current cull position up the wheel - si = si + 1 # advance wheel index - if si > 92159: si = 0 - while nxt in sieve: # ensure each entry is unique by wheel - nxt += s * gaps[si] - si = si + 1 # advance wheel index - if si > 92159: si = 0 - sieve[nxt] = (s, si) # next non-marked multiple of a prime - nni = ni + 1 # advance wheel index - if nni > 92159: nni = 0 - n += gaps[ni]; ni = nni # advance on the wheel - for p, pi in wheel_prime_pairs(): yield p # strip out indexes + p2 = p + p # n == p * p: for prime p, add p * p + 2 * p + sieve[q + p2] = p2 # to the dict, with 2 * p as the increment step + p = next(bps); q = p * p # pull next base prime, and get its square + else: + s = sieve.pop(n); nxt = n + s # n's a multiple of some b.p., find next multiple + while nxt in sieve: nxt += s # ensure each entry is unique + sieve[nxt] = s # nxt is next non-marked multiple of this prime + n += 2 # work on odds only + +import itertools +def primes_up_to(limit): + return list(itertools.takewhile(lambda p: p <= limit, primes())) diff --git a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-15.py b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-15.py new file mode 100644 index 0000000000..e3f2aa1d6c --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-15.py @@ -0,0 +1,30 @@ +def primes(): + for p in [2,3,5,7]: yield p # base wheel primes + gaps1 = [ 2,4,2,4,6,2,6,4,2,4,6,6,2,6,4,2,6,4,6,8,4,2,4,2,4,8 ] + gaps = gaps1 + [ 6,4,6,2,4,6,2,6,6,4,2,4,6,2,6,4,2,4,2,10,2,10 ] # wheel2357 + def wheel_prime_pairs(): + yield (11,0); bps = wheel_prime_pairs() # additional primes supply + p, pi = next(bps); q = p * p # adv to get 11 sqr'd is 121 as next square to put + sieve = {}; n = 13; ni = 1 # into sieve dict; init cndidate, wheel ndx + while True: + if n not in sieve: # is not a multiple of previously recorded primes + if n < q: yield (n, ni) # n is prime with wheel modulo index + else: + npi = pi + 1 # advance wheel index + if npi > 47: npi = 0 + sieve[q + p * gaps[pi]] = (p, npi) # n == p * p: put next cull position on wheel + p, pi = next(bps); q = p * p # advance next prime and prime square to put + else: + s, si = sieve.pop(n) + nxt = n + s * gaps[si] # move current cull position up the wheel + si = si + 1 # advance wheel index + if si > 47: si = 0 + while nxt in sieve: # ensure each entry is unique by wheel + nxt += s * gaps[si] + si = si + 1 # advance wheel index + if si > 47: si = 0 + sieve[nxt] = (s, si) # next non-marked multiple of a prime + nni = ni + 1 # advance wheel index + if nni > 47: nni = 0 + n += gaps[ni]; ni = nni # advance on the wheel + for p, pi in wheel_prime_pairs(): yield p # strip out indexes diff --git a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-16.py b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-16.py new file mode 100644 index 0000000000..6f54e138c7 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-16.py @@ -0,0 +1,40 @@ +def primes(): + whlPrms = [2,3,5,7,11,13,17] # base wheel primes + for p in whlPrms: yield p + def makeGaps(): + buf = [True] * (3 * 5 * 7 * 11 * 13 * 17 + 1) # all odds plus extra for o/f + for p in whlPrms: + if p < 3: + continue # no need to handle evens + strt = (p * p - 19) >> 1 # start position (divided by 2 using shift) + while strt < 0: strt += p + buf[strt::p] = [False] * ((len(buf) - strt - 1) // p + 1) # cull for p + whlPsns = [i + i for i,v in enumerate(buf) if v] + return [whlPsns[i + 1] - whlPsns[i] for i in range(len(whlPsns) - 1)] + gaps = makeGaps() # big wheel gaps + def wheel_prime_pairs(): + yield (19,0); bps = wheel_prime_pairs() # additional primes supply + p, pi = next(bps); q = p * p # adv to get 11 sqr'd is 121 as next square to put + sieve = {}; n = 23; ni = 1 # into sieve dict; init cndidate, wheel ndx + while True: + if n not in sieve: # is not a multiple of previously recorded primes + if n < q: yield (n, ni) # n is prime with wheel modulo index + else: + npi = pi + 1 # advance wheel index + if npi > 92159: npi = 0 + sieve[q + p * gaps[pi]] = (p, npi) # n == p * p: put next cull position on wheel + p, pi = next(bps); q = p * p # advance next prime and prime square to put + else: + s, si = sieve.pop(n) + nxt = n + s * gaps[si] # move current cull position up the wheel + si = si + 1 # advance wheel index + if si > 92159: si = 0 + while nxt in sieve: # ensure each entry is unique by wheel + nxt += s * gaps[si] + si = si + 1 # advance wheel index + if si > 92159: si = 0 + sieve[nxt] = (s, si) # next non-marked multiple of a prime + nni = ni + 1 # advance wheel index + if nni > 92159: nni = 0 + n += gaps[ni]; ni = nni # advance on the wheel + for p, pi in wheel_prime_pairs(): yield p # strip out indexes diff --git a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-8.py b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-8.py index 53b4e9ef99..e080297ade 100644 --- a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-8.py +++ b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-8.py @@ -1,7 +1,81 @@ -import numpy -def primes_upto2(limit): - is_prime = numpy.ones(limit + 1, dtype=numpy.bool) - for n in xrange(2, int(limit**0.5 + 1.5)): - if is_prime[n]: - is_prime[n*n::n] = 0 - return numpy.nonzero(is_prime)[0][2:] +import time + +def primes2357(limit, countonly = False): + if countonly: + if limit < 2: yield 0; return + if limit < 11: yield (max(4, (limit + 1) // 2)); return + else: + if limit < 2: return + yield 2; + if limit >= 3 : yield 3 + if limit >= 5: yield 5 + if limit >= 7: yield 7 + if limit < 11: return + # wheel size is 210 = 2 * 3 * 5 * 7 or 105 for only the odd values + # table of one wheel size of values starting at the next value of 11 for + # values culled of multiples of 2, 3, 5, and 7; this forms a look up table of + # indexted relative modulo prime values... + modPrms = [ 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71 + , 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 121, 127, 131, 137, 139, 143 + , 149, 151, 157, 163, 167, 169, 173, 179, 181, 187, 191, 193, 197, 199, 209, 211 ] + # table of gaps between the above values over one wheel (210)... + gaps = [ 2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 4, 2 + , 6, 4, 6, 8, 4, 2, 4, 2, 4, 8, 6, 4, 6, 2, 4, 6 + , 2, 6, 6, 4, 2, 4, 6, 2, 6, 4, 2, 4, 2, 10, 2, 10 + , 2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 4, 2 + , 6, 4, 6, 8, 4, 2, 4, 2, 4, 8, 6, 4, 6, 2, 4, 6 + , 2, 6, 6, 4, 2, 4, 6, 2, 6, 4, 2, 4, 2, 10, 2, 10 ] # 2 loops to avoid overflow + # table of indices of the next lowest modulo relative primes (modPrms), which + # forms a reverse look up table from the 210 wheel indices to the `modPrm` + # indices of the next lowest modulo relative prime value... + ndxs = [ 0, 0, 1, 1, 1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4 + , 4, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7 + , 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 11, 11, 11 + , 11, 11, 11, 12, 12, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14 + , 15, 15, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18 + , 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20 + , 21, 21, 22, 22, 22, 22, 23, 23, 24, 24, 24, 24, 25, 25, 25 + , 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27 + , 28, 28, 28, 28, 28, 28, 29, 29, 30, 30, 30, 30, 31, 31, 31 + , 31, 31, 31, 32, 32, 33, 33, 33, 33, 33, 33, 34, 34, 34, 34 + , 34, 34, 35, 35, 35, 35, 36, 36, 37, 37, 37, 37, 38, 38, 38 + , 38, 38, 38, 39, 39, 40, 40, 40, 40, 40, 40, 41, 41, 41, 41 + , 42, 42, 43, 43, 43, 43, 44, 44, 45, 45, 45, 45, 45, 45, 45 + , 45, 45, 45, 46, 46, 47, 47, 47, 47, 47, 47, 47, 47, 47, 47 ] + lmtbf = (limit + 199) // 210 * 48 - 1 # integral number of wheels rounded up + lmtsqrt = (int(limit ** 0.5) - 11) + lmtsqrt = lmtsqrt // 210 * 48 + ndxs[lmtsqrt % 210] # round down on the wheel + buf = bytearray(lmtbf + 1) # initialized to zeros + for i in range(lmtsqrt + 1): + if not buf[i]: # this makes the algorithm SoE and not Sieve of Sundaram... + ci = i % 48; p = 210 * (i // 48) + modPrms[ci] + s = p * p - 11; p8 = p * 48 + for _ in range(48): + c = s // 210 * 48 + ndxs[s % 210] + buf[c::p8] = [1] * ((lmtbf - c) // p8 + 1) + s += p * gaps[ci]; ci += 1 + # clear primes above limit... + lmtndx = limit - 11 + lmtndx = lmtndx // 210 * 48 + ndxs[lmtndx % 210] + for i in range(lmtndx + 1, lmtbf + 1): buf[i] = 1 + if countonly: + # return the count of primes... + yield buf.count(0) + 4 # including the base primes of 2, 3, 5, and 7 + else: + # following is slower because of generating individual primes... + for i in range(0, lmtbf + 1, 48): + for j in range(48): + if not buf[i + j]: yield (210 * i + modPrms[j]) + +# USAGE +print("Primes to 100: ", list(primes2357(100))) +print("Number of primes to a million: ", (list(primes2357(1000000, True)))[0]) +strt = time.time() +''' # slow counting of primes by iteration takes about six times longer... +gen = primes2357((n := 100000000)) +primes = sum([1 for _ in gen]) +''' +primes=list(primes2357((n:=100000000), True))[0] +stop = time.time() +print("Up to", n, "found", primes, "primes.") +print("This last took", stop - strt, "seconds.") diff --git a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-9.py b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-9.py index 1cdb64c793..45752f5097 100644 --- a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-9.py +++ b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-9.py @@ -1,20 +1,214 @@ -from numpy import array, bool_, multiply, nonzero, ones, put, resize -# -def makepattern(smallprimes): - pattern = ones(multiply.reduce(smallprimes), dtype=bool_) - pattern[0] = 0 - for p in smallprimes: - pattern[p::p] = 0 - return pattern -# -def primes_upto3(limit, smallprimes=(2,3,5,7,11)): - sp = array(smallprimes) - if limit <= sp.max(): return sp[sp <= limit] - # - isprime = resize(makepattern(sp), limit + 1) - isprime[:2] = 0; put(isprime, sp, 1) - # - for n in range(sp.max() + 2, int(limit**0.5 + 1.5), 2): - if isprime[n]: - isprime[n*n::n] = 0 - return nonzero(isprime)[0] +# Page-Segmented Wheel-Factorized Sieve of Eratosthenes... + +from bitarray import bitarray +from math import isqrt +from time import monotonic + +# these primes have already been preculled... +whlprms = [ 2, 3, 5, 7, 11, 13, 17, 19 ] + +# wheel size is 210 = 2 * 3 * 5 * 7 or 105 for only the odd values +# table of one wheel size of values starting at the first value of 11 for +# values culled of multiples of 2, 3, 5, and 7; this forms a look up table of +# indexed residual modulo prime values; note it still includes some non-primes as 121 = 11*2... +rsds = bytearray( + [ 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71 + , 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 121, 127, 131, 137, 139, 143 + , 149, 151, 157, 163, 167, 169, 173, 179, 181, 187, 191, 193, 197, 199, 209, 211 ]) + +# table of indices of the next lowest modulo relative primes (rsds), which +# forms a reverse look up table from the 105 odds wheel indices to the `modPrm` +# indices of the next lowest modulo relative prime value... +ndxs = bytearray( + [ 0, 1, 1, 2, 3, 3, 4, 4, 4, 5, 6, 6, 6, 7, 7 + , 8, 9, 9, 10, 10, 10, 11, 11, 11, 12, 13, 13, 13, 14, 14 + , 15, 16, 16, 16, 17, 17, 18, 18, 18, 19, 19, 19, 19, 20, 20 + , 21, 22, 22, 23, 24, 24, 25, 25, 25, 25, 26, 26, 26, 27, 27 + , 28, 28, 28, 29, 30, 30, 31, 31, 31, 32, 33, 33, 33, 34, 34 + , 34, 35, 35, 36, 37, 37, 38, 38, 38, 39, 40, 40, 40, 41, 41 + , 42, 43, 43, 44, 45, 45, 45, 45, 45, 46, 47, 47, 47, 47, 47 ]) + +# table of index look-ups rounded up to the next index +# used to ease start index per page calculation... +whlRndUps = bytearray( + [ 0, 1, 3, 3, 4, 6, 6, 9, 9, 9, 10, 13, 13, 13, 15 + , 15, 16, 18, 18, 21, 21, 21, 24, 24, 24, 25, 28, 28, 28, 30 + , 30, 31, 34, 34, 34, 36, 36, 39, 39, 39, 43, 43, 43, 43, 45 + , 45, 46, 48, 48, 49, 51, 51, 55, 55, 55, 55, 58, 58, 58, 60 + , 60, 63, 63, 63, 64, 66, 66, 69, 69, 69, 70, 73, 73, 73, 76 + , 76, 76, 78, 78, 79, 81, 81, 84, 84, 84, 85, 88, 88, 88, 90 + , 90, 91, 93, 93, 94, 99, 99, 99, 99, 99, 100, 105, 105, 105, 105 ]) +whlRndUps += bytearray(( ru + 105 for ru in whlRndUps )) + bytearray([210]) # two wheels for overflow! + +# multi-level table index by residual bit plane, prime modulo, and +# cycle, indices to ease start index calculation per residual bit plane... +def mkstrts(): # immediately invoked anonymous function... + buf = bytearray(48 * 48 * 48 * 2) + mults = bytearray(48) + for pi in range(48): + p = rsds[pi]; s = (p * p - 11) >> 1 + for ci in range(48): + rmlt = (rsds[(pi + ci) % 48] - rsds[pi]) >> 1 + rmlt += 105 if rmlt < 0 else 0; sn = s + p * rmlt + snd = sn // 105; snr = sn - snd * 105 + mults[ndxs[snr]] = rmlt + for si in range(48): + s0 = (rsds[si] - 11) >> 1; sm0 = mults[si] + for ci in range(48): + smr = mults[ci] + smr += (105 if smr < sm0 else 0) - sm0 + sn = s0 + p * smr; rofs = sn // 105 + addr = ((ci * 48 + pi) * 48 + si) << 1 + buf[addr] = smr << 1; buf[addr + 1] = rofs + return buf +strts = mkstrts() # table too large for a literal; calculate it... + +# fill from wheel pattern for each residual bit plane... +def fillBufFromFor(buf, low, fillmodsz): # fillsz is even number of 64-bit's + modsz = len(buf) // 48; ptrnmodsz = len(whlptrn) // 48 + ptrnsz = 11 * 13 * 17 * 19 # in bits per bit plane + lowi = (low - 11) // 210 + for ri in range(48): + basedst = ri * modsz; basesrc = ri * ptrnmodsz + for sri in range(0, fillmodsz, 131072): + modndx = (lowi + sri) % ptrnsz; cpymodsz = min(131072, fillmodsz - sri) + strt = basedst + sri; lmt = basedst + sri + cpymodsz + pstrt = basesrc + modndx; plmt = basesrc + modndx + cpymodsz + buf[strt:lmt] = whlptrn[pstrt:plmt] + return + +# cullsz is limit for each residual bit plane; +# bprps is a bytearray containing upper two bits of delta wheel, and +# lower six bits of the bit plane index... +def cullBufFromForBy(buf, low, cullsz, bprps): + modsz = len(buf) // 48 + buflmt = low + cullsz * 210 + def bps(): # calculate residual plane start indices once per page + oldbpwi = 0 + for bprp in bprps: + oldbpwi += bprp >> 6; bpri = bprp & 0x3F + bp = oldbpwi * 210 + rsds[bpri]; s = bp * bp + if s >= buflmt: return + # start index calculation for each base prime... + if s > low: s -= low; s >>= 1 + else: + wp = (rsds[bpri] - 11) >> 1 + s = ((low - s) >> 1) % (bp * 105) + if s != 0: + s = bp * (whlRndUps[wp + (s + bp - 1) // bp] - wp) - s + swi = s // 105; sri = ndxs[s - swi * 105] + yield (bp, oldbpwi, bpri, swi, sri) + bpsarr = list(bps()) + for ri in range(48): # this order improves cache associativity... + base = ri * modsz + for bp, bpwi, bpri, swi, sri in bpsarr: + adji = ((ri * 48 + bpri) * 48 + sri) << 1 + adjmlt = strts[adji]; adjofst = strts[adji + 1] + strt = base + swi + bpwi * adjmlt + adjofst; end = base + cullsz + buf[strt:end:bp] = 1 + +# array of cull buffer culled of multiples of 11, 13, 17, and 19 with +# the multiples of 2, 3, 5, and 7, already eliminated due to the wheel; +# used as a wheel pattern to fill sieve buffers before further culling... +def mkwhlptrn(): + modsz = 11 * 13 * 17 * 19 + 131072 + buf = bitarray(modsz * 48) + bprps = [ i for i in range(4)] + cullBufFromForBy(buf, 11, modsz, bprps) + buf[0] = 1; buf[modsz] = 1; buf[modsz * 2] = 1; buf[modsz * 3] = 1 + return buf +whlptrn = mkwhlptrn() # is 128K bits larger than the wheel size to avoid overflow... + +# count the unset bits in the buffer representing numbers from `low` to `limit`... +def countBufFromFor(buf, low, limit): + modsz = len(buf) // 48 + sizei = modsz - 1; sizej = 48 + if low + modsz * 210 - 1 > limit: + sizei = (limit - low) // 210 + sizej = ndxs[(limit - low - sizei * 210) >> 1] + 1 + cnt = 0 + for ri in range(48): + base = ri * modsz + rilmt = base + sizei + (1 if ri < sizej else 0) + cnt += buf[base:rilmt].count(0) + return cnt + +# takes a iterator of buf's and produces an iter of (i, j) values where +# i is the wheel index and j is the wheel modulo residue index... +def prmndxBufFromFor(buf, low, limit): + modsz = len(buf) // 48 + sizei = modsz - 1; sizej = 48 + lowi = (low - 11) // 210 + if low * modsz * 210 - 1 > limit: + sizei = (limit - low) // 210 + sizej = ndxs[(limit - low - sizei * 210) >> 1] + 1 + for i in range(sizei + 1): + for j in range(48 if i < sizei else sizej): + if not buf[i + j * modsz]: yield (lowi + i, j) + +# produce bytearray of encoded bps, 2 bits delta whl ndx + 6 bits rsd ndx... +def bprpsToLimit(limit): + def bprpsiter(buf, lmt): # non paged! buf wheels are a multiple of 64 bits rounded up... + oldi = 0 + for i, j in prmndxBufFromFor(buf, 11, lmt): + yield ((i - oldi) << 6) | j + oldi = i + if limit < 529: return bytearray(bprpsiter(whlptrn, limit)) + else: + bprps = bprpsToLimit(isqrt(limit)) # recursively! + modsz = ((limit - 11) // 210 + 127) & -64 + buf = bitarray(modsz * 48) + fillBufFromFor(buf, 11, modsz) + cullBufFromForBy(buf, 11, modsz, bprps) + return bytearray(bprpsiter(buf, limit)) + +# produces an iterator of buffers with last one sized to fi, with the buffer +# the buffer passed into a provided function to produce iteration of result... +def bufsToLimit(limit, func): + # 32 MegaBytes per module bit plane maximum size + modsz = min(131072 * 8 * 64, ((limit - 11) // 210 + 127) & -64) + bufsz = modsz * 210; buf = bitarray(modsz * 48) + bprps = bprpsToLimit(isqrt(limit)) + for low in range(11, limit + 1, bufsz): + fillmodsz = min(modsz, ((limit - low) // 210 + 127) & -64) + # adjustable buffer size for efficiency + fillBufFromFor(buf, low, fillmodsz) + yield func(buf, low, modsz, bprps) + +# produce and iterator of primes up to `limit`... +def primesTo(limit): + if limit < 2: return + for p in whlprms: + if p <= limit: yield p + if limit < 23: return + def bufToPrimesIter(buf, low, modsz, bps): + cullBufFromForBy(buf, low, modsz, bps) + for i, j in prmndxBufFromFor(buf, low, limit): + yield i * 210 + rsds[j] + for bfrprms in bufsToLimit(limit, bufToPrimesIter): + for prm in bfrprms: yield prm + +# the result is the count of primes to the given `limit`... +def countPrimesTo(limit): + if limit < 23: + cnt = 0 + for p in whlprms: + if p <= limit: cnt += 1 + return cnt + def bufToCount(buf, low, cullmodsz, bprps): + cullBufFromForBy(buf, low, cullmodsz, bprps) + return countBufFromFor(buf, low, limit) + return sum(bufsToLimit(limit, bufToCount)) + 8 + +# USAGE +print("Primes to 100: ", list(primesTo(100))) +print("Number of primes to a million: ", countPrimesTo(1_000_000)) +strt = monotonic() +''' # slow counting of primes by iteration takes about six times longer... +gen = primesTo((n := 1_000_000_000)) +primes = sum(( 1 for _ in gen )) +''' +for _ in range(n := 10): primes = countPrimesTo(limit := 1_000_000_000) +stop = monotonic() +print("Up to", limit, "repeated", n, "time(s), found", primes, "primes.") +print("This last took", stop - strt, "seconds.") diff --git a/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-1.rexx b/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-1.rexx index 1a8497693c..a232b3bdbf 100644 --- a/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-1.rexx +++ b/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-1.rexx @@ -1,12 +1,29 @@ -/*REXX program generates and displays primes via the sieve of Eratosthenes algorithm.*/ -parse arg H .; if H=='' | H=="," then H= 200 /*optain optional argument from the CL.*/ -w= length(H); @prime= right('prime', 20) /*W: is used for aligning the output.*/ -@.=. /*assume all the numbers are prime. */ -#= 0 /*number of primes found (so far). */ - do j=2 for H-1; if @.j=='' then iterate /*all prime integers up to H inclusive.*/ - #= # + 1 /*bump the prime number counter. */ - say @prime right(#,w) " ───► " right(j,w) /*display the prime to the terminal. */ - do m=j*j to H by j; @.m=; end /*strike all multiples as being ¬ prime*/ - end /*j*/ /* ─── */ -say /*stick a fork in it, we're all done. */ -say right(#, 1+w+length(@prime) ) 'primes found up to and including ' H +/*REXX program generates primes via sieve of Eratosthenes algorithm. +* 21.07.2012 Walter Pachl derived from above Rexx version +* avoid symbols @ and # (not supported by ooRexx) +* avoid negations (think positive) +**********************************************************************/ + highest=200 /*define highest number to use. */ + is_prime.=1 /*assume all numbers are prime. */ + w=length(highest) /*width of the biggest number, */ + /* it's used for aligned output.*/ + Do j=3 To highest By 2, /*strike multiples of odd ints. */ + While j*j<=highest /* up to sqrt(highest) */ + If is_prime.j Then Do + Do jm=j*3 To highest By j+j /*start with next odd mult. of J */ + is_prime.jm=0 /*mark odd mult. of J not prime. */ + End + End + End + np=0 /*number of primes shown */ + Call tell 2 + Do n=3 To highest By 2 /*list all the primes found. */ + If is_prime.n Then Do + Call tell n + End + End + Exit +tell: Parse Arg prime + np=np+1 + Say ' prime number' right(np,w) " --> " right(prime,w) + Return diff --git a/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-2.rexx b/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-2.rexx index 77294f8bc1..f0b6ed0183 100644 --- a/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-2.rexx +++ b/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-2.rexx @@ -1,24 +1,66 @@ -/*REXX program generates primes via a wheeled sieve of Eratosthenes algorithm. */ -parse arg H .; if H=='' then H=200 /*let the highest number be specified. */ -tell=h>0; H=abs(H); w=length(H) /*a negative H suppresses prime listing*/ -if 2<=H & tell then say right(1, w+20)'st prime ───► ' right(2, w) -@.= '0'x /*assume that all numbers are prime. */ -cw= length(@.) /*the cell width that holds numbers. */ -#= w<=H /*the number of primes found (so far).*/ -!=0 /*skips the top part of sieve marking. */ - do j=3 by 2 for (H-2)%2; b= j%cw /*odd integers up to H inclusive. */ - if substr(x2b(c2x(@.b)),j//cw+1,1) then iterate /*is J composite ? */ - #= # + 1 /*bump the prime number counter. */ - if tell then say right(#, w+20)th(#) 'prime ───► ' right(j, w) - if ! then iterate /*should the top part be skipped ? */ - jj=j * j /*compute the square of J. ___*/ - if jj>H then !=1 /*indicates skip top part if j > √ H */ - do m=jj to H by j+j; call . m; end /* [↑] strike odd multiples ¬ prime */ - end /*j*/ /* ─── */ +-- 23 Aug 2025 +include Setting -say; say right(#, w+20) 'prime's(#) "found up to and including " H -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────────────*/ -.: parse arg n; b=n%cw; r=n//cw+1;_=x2b(c2x(@.b));@.b=x2c(b2x(left(_,r-1)'1'substr(_,r+1)));return -s: if arg(1)==1 then return arg(3); return word(arg(2) 's',1) /*pluralizer.*/ -th: procedure; parse arg x; x=abs(x); return word('th st nd rd',1+x//10*(x//100%10\==1)*(x//10<4)) +call Time('r') +say 'SIEVE OF ERATOSTHENES' +say version +say +call GetBasic 200 +call ShowPrimes 200 +call GetPrimes 200 +call ShowPrimes 200 +say Format(Time('e'),,3) 'seconds'; say +exit + +GetBasic: +procedure expose prim. +arg xx +say 'Basic sieve up to' xx'...' +call Basic xx +say prim.0 'found' +say +return + +Basic: +procedure expose prim. work. +arg xx +work. = 1 +do i = 2 while i*i <= xx + if work.i then do + do j = i*i by i to xx + work.j = 0 + end + end +end +zz = 0 +do i = 2 to xx + if work.i then do + zz = zz+1; prim.zz = i + end +end +prim.0 = zz +return zz + +GetPrimes: +procedure expose prim. flag. +arg xx +say 'Wheeled sieve up to' xx'...' +call Primes xx +say prim.0 'found' +say +return + +ShowPrimes: +procedure expose prim. +arg xx +say 'Primes up to' xx +do i = 1 to prim.0 + call Charout ,right(prim.i,4) + if i//10 = 0 then + say +end +say +say +return + +include Math diff --git a/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-3.rexx b/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-3.rexx deleted file mode 100644 index 4e18e68268..0000000000 --- a/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-3.rexx +++ /dev/null @@ -1,16 +0,0 @@ -/*REXX pgm generates and displays primes via a wheeled sieve of Eratosthenes algorithm. */ -parse arg H .; if H=='' | H=="," then H= 200 /*obtain the optional argument from CL.*/ -w= length(H); @prime= right('prime', 20) /*w: is used for aligning the output. */ -if 2<=H then say @prime right(1, w) " ───► " right(2, w) -#= 2<=H /*the number of primes found (so far).*/ -@.=. /*assume all the numbers are prime. */ -!=0; do j=3 by 2 for (H-2)%2 /*the odd integers up to H inclusive.*/ - if @.j=='' then iterate /*Is composite? Then skip this number.*/ - #= # + 1 /*bump the prime number counter. */ - say @prime right(#,w) " ───► " right(j,w) /*display the prime to the terminal. */ - if ! then iterate /*skip the top part of loop? ___ */ - if j*j>H then !=1 /*indicate skip top part if J > √ H */ - do m=j*j to H by j+j; @.m=; end /*strike odd multiples as not prime. */ - end /*j*/ /* ─── */ -say /*stick a fork in it, we're all done. */ -say right(#, 1 + w + length(@prime) ) 'primes found up to and including ' H diff --git a/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-4.rexx b/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-4.rexx deleted file mode 100644 index a232b3bdbf..0000000000 --- a/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-4.rexx +++ /dev/null @@ -1,29 +0,0 @@ -/*REXX program generates primes via sieve of Eratosthenes algorithm. -* 21.07.2012 Walter Pachl derived from above Rexx version -* avoid symbols @ and # (not supported by ooRexx) -* avoid negations (think positive) -**********************************************************************/ - highest=200 /*define highest number to use. */ - is_prime.=1 /*assume all numbers are prime. */ - w=length(highest) /*width of the biggest number, */ - /* it's used for aligned output.*/ - Do j=3 To highest By 2, /*strike multiples of odd ints. */ - While j*j<=highest /* up to sqrt(highest) */ - If is_prime.j Then Do - Do jm=j*3 To highest By j+j /*start with next odd mult. of J */ - is_prime.jm=0 /*mark odd mult. of J not prime. */ - End - End - End - np=0 /*number of primes shown */ - Call tell 2 - Do n=3 To highest By 2 /*list all the primes found. */ - If is_prime.n Then Do - Call tell n - End - End - Exit -tell: Parse Arg prime - np=np+1 - Say ' prime number' right(np,w) " --> " right(prime,w) - Return diff --git a/Task/Sieve-of-Eratosthenes/RISC-V-Assembly/sieve-of-eratosthenes.asm b/Task/Sieve-of-Eratosthenes/RISC-V-Assembly/sieve-of-eratosthenes.asm new file mode 100644 index 0000000000..923191d36e --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/RISC-V-Assembly/sieve-of-eratosthenes.asm @@ -0,0 +1,94 @@ +# riscv assembly raspberry pico2 rp2350 +# program cribleera.s +# connexion putty com3 +/*********************************************/ +/* CONSTANTES */ +/********************************************/ +/* for this file see risc-v task include a file */ +.include "../../../constantesRiscv.inc" +.equ MAXI, 101 +/****************************************************/ +/* MACROS */ +/****************************************************/ +#.include "../ficmacrosriscv.inc" # only for debugging +/*******************************************/ +/* INITIALED DATAS */ +/*******************************************/ +.data +szMessStart: .asciz "Program riscv start.\r\n" +szMessEndOk: .asciz "Program riscv end OK.\r\n" +szCariageReturn: .asciz "\r\n" +szMessNum: .asciz "Prime : " + +.align 2 +/*******************************************/ +/* UNINITIALED DATA */ +/*******************************************/ +.bss +sConvArea: .skip 24 +.align 2 +tablePrime: .skip 4 * MAXI +/**********************************************/ +/* SECTION CODE */ +/**********************************************/ +.text +.global main + +main: + call stdio_init_all # général init +1: # start loop connexion + li a0,0 # raz argument register + call tud_cdc_n_connected # waiting for USB connection + beqz a0,1b # return code = zero ? yes -> loop + + la a0,szMessStart # message address + call writeString # display message + + li s0,2 # start indice + la s2,tablePrime + li s3,MAXI + li s4,1 +1: # loop for multiple of 2 + sh2add t0,s0,s2 # compute adresse of s0 index + sw s4,(t0) # mark multiple of 2 + addi s0,s0,2 # increment indice + blt s0,s3,1b # and loop if not maxi + + li s0,3 # new start + #li s4,1 +2: + sh2add t0,s0,s2 # compute adresse of s0 index + lw t1,(t0) # load mark + bnez t1,4f # if not zero -> continue + + + la a0,szMessNum # else display prime + call writeString + mv a0,s0 + la a1,sConvArea + call conversion10 + la a0,sConvArea + call writeString + la a0,szCariageReturn + call writeString + mv s1,s0 # new prime +3: # and loop to mark multiples of this prime + sh2add t0,s1,s2 # compute adresse of s0 index + sw s4,(t0) # mark multiple + add s1,s0,s1 # add the prime + ble s1,s3,3b # and loop if not maxi +4: + addi s0,s0,2 # increment indice + ble s0,s3,2b # and loop if not maxi + + la a0,szMessEndOk # message address + call writeString # display message + call getchar +100: # final loop + j 100b + +/************************************/ +/* file include Fonctions */ +/***********************************/ +/* for this file see risc-v task include a file */ +.include "../../../includeFunctions.s" diff --git a/Task/Sieve-of-Eratosthenes/Raku/sieve-of-eratosthenes-2.raku b/Task/Sieve-of-Eratosthenes/Raku/sieve-of-eratosthenes-2.raku index 9c9c713341..d866544291 100644 --- a/Task/Sieve-of-Eratosthenes/Raku/sieve-of-eratosthenes-2.raku +++ b/Task/Sieve-of-Eratosthenes/Raku/sieve-of-eratosthenes-2.raku @@ -1,4 +1,4 @@ -sub eratsieve($n) { +sub sieve($n) { # Requires n(1 - 1/(log(n-1))) storage my $multiples = set(); gather for 2..$n -> $i { @@ -8,5 +8,3 @@ sub eratsieve($n) { } } } - -say flat eratsieve(100); diff --git a/Task/Sieve-of-Eratosthenes/Raku/sieve-of-eratosthenes-3.raku b/Task/Sieve-of-Eratosthenes/Raku/sieve-of-eratosthenes-3.raku index 3d330628b1..e673515b6c 100644 --- a/Task/Sieve-of-Eratosthenes/Raku/sieve-of-eratosthenes-3.raku +++ b/Task/Sieve-of-Eratosthenes/Raku/sieve-of-eratosthenes-3.raku @@ -1,21 +1,3 @@ -sub primes ( UInt $n ) { - gather { - # create an iterator from 2 to $n (inclusive) - my $iterator := (2..$n).iterator; - - loop { - # If it passed all of the filters it must be prime - my $prime := $iterator.pull-one; - # unless it is actually the end of the sequence - last if $prime =:= IterationEnd; - - take $prime; # add the prime to the `gather` sequence - - # filter out the factors of the current prime - $iterator := Seq.new($iterator).grep(* % $prime).iterator; - # (2..*).grep(* % 2).grep(* % 3).grep(* % 5).grep(* % 7)… - } - } +sub sieve($n) { + sort keys [⊖] map { $_, 2×$_ ... $n }, 2 .. $n } - -put primes( 100 ); diff --git a/Task/Sieve-of-Eratosthenes/Raku/sieve-of-eratosthenes-4.raku b/Task/Sieve-of-Eratosthenes/Raku/sieve-of-eratosthenes-4.raku new file mode 100644 index 0000000000..1ec3188edb --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Raku/sieve-of-eratosthenes-4.raku @@ -0,0 +1,2 @@ +say flat sieve(100); +# (2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97) diff --git a/Task/Sieve-of-Eratosthenes/Raku/sieve-of-eratosthenes-5.raku b/Task/Sieve-of-Eratosthenes/Raku/sieve-of-eratosthenes-5.raku new file mode 100644 index 0000000000..3d330628b1 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Raku/sieve-of-eratosthenes-5.raku @@ -0,0 +1,21 @@ +sub primes ( UInt $n ) { + gather { + # create an iterator from 2 to $n (inclusive) + my $iterator := (2..$n).iterator; + + loop { + # If it passed all of the filters it must be prime + my $prime := $iterator.pull-one; + # unless it is actually the end of the sequence + last if $prime =:= IterationEnd; + + take $prime; # add the prime to the `gather` sequence + + # filter out the factors of the current prime + $iterator := Seq.new($iterator).grep(* % $prime).iterator; + # (2..*).grep(* % 2).grep(* % 3).grep(* % 5).grep(* % 7)… + } + } +} + +put primes( 100 ); diff --git a/Task/Sieve-of-Eratosthenes/Rebol/sieve-of-eratosthenes.rebol b/Task/Sieve-of-Eratosthenes/Rebol/sieve-of-eratosthenes.rebol new file mode 100644 index 0000000000..c4f7868483 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Rebol/sieve-of-eratosthenes.rebol @@ -0,0 +1,40 @@ +Rebol [ + title: "Rosetta code: Sieve of Eratosthenes" + file: %Sieve_of_Eratosthenes.r3 + url: https://rosettacode.org/wiki/Sieve_of_Pritchard + note: "Translated from Red" +] + +eratosthenes: function [ + "Eratosthenes sieve: finds all primes up to `limit` using a bitset-based sieve." + limit [integer!] +][ + primes: copy [] + ;; Use a bitset as a boolean composite-marker array. + ;; Index i is true if i has been marked as composite. + prim: make bitset! limit + prim/1: true ;; 1 is not prime, mark it as composite + + rtlim: to integer! square-root limit ;; Only need primes up to sqrt(limit) + + ;; For each r starting at 2, mark all multiples of r as composite. + ;; Only need to check up to sqrt(limit), since any composite above it + ;; must have a prime factor at or below it. + r: 2 + while [r <= rtlim][ + ;; Mark r*2, r*3, ..., r*floor(limit/r) as composite + repeat q limit / r - 1 [ + prim/(q + 1 * r): true + ] + ;; Advance r to the next unmarked (prime) candidate + until [not prim/(r: r + 1)] + ] + ;; Any index still unset in the bitset is prime. + repeat i limit [ + unless prim/:i [append primes i] + ] + primes +] + +probe eratosthenes 100 +print rejoin ["Number of primes up to 1'000'000: " length? eratosthenes 1'000'000] diff --git a/Task/Sieve-of-Eratosthenes/Retro/sieve-of-eratosthenes.retro b/Task/Sieve-of-Eratosthenes/Retro/sieve-of-eratosthenes.retro new file mode 100644 index 0000000000..533dceed3d --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Retro/sieve-of-eratosthenes.retro @@ -0,0 +1,25 @@ +{ [ @start &start v:inc @end @start gt? ] while } creates an array from 2 to 100 +:make filter filters +dup-pair is used or else the number is compared with the flag from if. Curry pushes the argument (the number from 1 to the square root of n) into the quote. +array is used to create an array from 2 to square root of 100. +You go over this array and use filter on the other array from 2 to 100. +~~~ + + :make-filter (n-q) [ dup-pair eq? not [ mod #0 eq? not ] if ] curry ; + + 'start var + #2 !start + 'end var + #100 !end + 'limit var + @end n:sqrt #1 + !limit + + :array (-a) { [ @start &start v:inc @limit @start gteq? ] while } ; + array + #2 !start + { [ @start &start v:inc @end @start gt? ] while } + #2 !start + array [ make-filter a:filter ] a:for-each [ n:put '_ s:put ] a:for-each + + +~~~ diff --git a/Task/Sieve-of-Eratosthenes/Rust/sieve-of-eratosthenes-1.rust b/Task/Sieve-of-Eratosthenes/Rust/sieve-of-eratosthenes-1.rs similarity index 100% rename from Task/Sieve-of-Eratosthenes/Rust/sieve-of-eratosthenes-1.rust rename to Task/Sieve-of-Eratosthenes/Rust/sieve-of-eratosthenes-1.rs diff --git a/Task/Sieve-of-Eratosthenes/Rust/sieve-of-eratosthenes-2.rust b/Task/Sieve-of-Eratosthenes/Rust/sieve-of-eratosthenes-2.rs similarity index 100% rename from Task/Sieve-of-Eratosthenes/Rust/sieve-of-eratosthenes-2.rust rename to Task/Sieve-of-Eratosthenes/Rust/sieve-of-eratosthenes-2.rs diff --git a/Task/Sieve-of-Eratosthenes/Rust/sieve-of-eratosthenes-3.rust b/Task/Sieve-of-Eratosthenes/Rust/sieve-of-eratosthenes-3.rs similarity index 100% rename from Task/Sieve-of-Eratosthenes/Rust/sieve-of-eratosthenes-3.rust rename to Task/Sieve-of-Eratosthenes/Rust/sieve-of-eratosthenes-3.rs diff --git a/Task/Sieve-of-Eratosthenes/Rust/sieve-of-eratosthenes-4.rs b/Task/Sieve-of-Eratosthenes/Rust/sieve-of-eratosthenes-4.rs new file mode 100644 index 0000000000..1b2bccc4ce --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Rust/sieve-of-eratosthenes-4.rs @@ -0,0 +1,31 @@ +fn optimized_sieve(limit: usize) -> Box> { + if limit < 3 { + return if limit < 2 { Box::new(empty()) } else { Box::new(once(2)) } + } + + let ndxlmt = (limit - 3) / 2 + 1; + let bfsz = ((limit - 3) / 2) / 32 + 1; + let mut cmpsts = vec![0u32; bfsz]; + let sqrtndxlmt = ((limit as f64).sqrt() as usize - 3) / 2 + 1; + + for ndx in 0..sqrtndxlmt { + if (cmpsts[ndx >> 5] & (1u32 << (ndx & 31))) == 0 { + let p = ndx + ndx + 3; + let mut cullpos = (p * p - 3) / 2; + while cullpos < ndxlmt { + unsafe { // avoids array bounds check, which is already done above + let cptr = cmpsts.get_unchecked_mut(cullpos >> 5); + *cptr |= 1u32 << (cullpos & 31); + } +// cmpsts[cullpos >> 5] |= 1u32 << (cullpos & 31); // with bounds check + cullpos += p; + } + } + } + + Box::new((-1 .. ndxlmt as isize).into_iter().filter_map(move |i| { + if i < 0 { Some(2) } else { + if cmpsts[i as usize >> 5] & (1u32 << (i & 31)) == 0 { + Some((i + i + 3) as usize) } else { None } } + })) +} diff --git a/Task/Sieve-of-Eratosthenes/Rust/sieve-of-eratosthenes-4.rust b/Task/Sieve-of-Eratosthenes/Rust/sieve-of-eratosthenes-4.rust deleted file mode 100644 index bf0059582f..0000000000 --- a/Task/Sieve-of-Eratosthenes/Rust/sieve-of-eratosthenes-4.rust +++ /dev/null @@ -1,31 +0,0 @@ -fn optimized_sieve(limit: usize) -> Box> { - if limit < 3 { - return if limit < 2 { Box::new(empty()) } else { Box::new(once(2)) } - } - - let ndxlmt = (limit - 3) / 2 + 1; - let bfsz = ((limit - 3) / 2) / 32 + 1; - let mut cmpsts = vec![0u32; bfsz]; - let sqrtndxlmt = ((limit as f64).sqrt() as usize - 3) / 2 + 1; - - for ndx in 0..sqrtndxlmt { - if (cmpsts[ndx >> 5] & (1u32 << (ndx & 31))) == 0 { - let p = ndx + ndx + 3; - let mut cullpos = (p * p - 3) / 2; - while cullpos < ndxlmt { - unsafe { // avoids array bounds check, which is already done above - let cptr = cmpsts.get_unchecked_mut(cullpos >> 5); - *cptr |= 1u32 << (cullpos & 31); - } -// cmpsts[cullpos >> 5] |= 1u32 << (cullpos & 31); // with bounds check - cullpos += p; - } - } - } - - Box::new((-1 .. ndxlmt as isize).into_iter().filter_map(move |i| { - if i < 0 { Some(2) } else { - if cmpsts[i as usize >> 5] & (1u32 << (i & 31)) == 0 { - Some((i + i + 3) as usize) } else { None } } - })) -} diff --git a/Task/Sieve-of-Eratosthenes/Rust/sieve-of-eratosthenes-5.rs b/Task/Sieve-of-Eratosthenes/Rust/sieve-of-eratosthenes-5.rs new file mode 100644 index 0000000000..8d2a80cd1c --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Rust/sieve-of-eratosthenes-5.rs @@ -0,0 +1,175 @@ +use std::iter::{empty, once}; +use std::rc::Rc; +use std::cell::RefCell; +use std::time::Instant; + +const RANGE: u64 = 1000000000; +const SZ_PAGE_BTS: u64 = (1 << 14) * 8; // this should be the size of the CPU L1 cache +const SZ_BASE_BTS: u64 = (1 << 7) * 8; +static CLUT: [u8; 256] = [ + 8, 7, 7, 6, 7, 6, 6, 5, 7, 6, 6, 5, 6, 5, 5, 4, 7, 6, 6, 5, 6, 5, 5, 4, 6, 5, 5, 4, 5, 4, 4, 3, + 7, 6, 6, 5, 6, 5, 5, 4, 6, 5, 5, 4, 5, 4, 4, 3, 6, 5, 5, 4, 5, 4, 4, 3, 5, 4, 4, 3, 4, 3, 3, 2, + 7, 6, 6, 5, 6, 5, 5, 4, 6, 5, 5, 4, 5, 4, 4, 3, 6, 5, 5, 4, 5, 4, 4, 3, 5, 4, 4, 3, 4, 3, 3, 2, + 6, 5, 5, 4, 5, 4, 4, 3, 5, 4, 4, 3, 4, 3, 3, 2, 5, 4, 4, 3, 4, 3, 3, 2, 4, 3, 3, 2, 3, 2, 2, 1, + 7, 6, 6, 5, 6, 5, 5, 4, 6, 5, 5, 4, 5, 4, 4, 3, 6, 5, 5, 4, 5, 4, 4, 3, 5, 4, 4, 3, 4, 3, 3, 2, + 6, 5, 5, 4, 5, 4, 4, 3, 5, 4, 4, 3, 4, 3, 3, 2, 5, 4, 4, 3, 4, 3, 3, 2, 4, 3, 3, 2, 3, 2, 2, 1, + 6, 5, 5, 4, 5, 4, 4, 3, 5, 4, 4, 3, 4, 3, 3, 2, 5, 4, 4, 3, 4, 3, 3, 2, 4, 3, 3, 2, 3, 2, 2, 1, + 5, 4, 4, 3, 4, 3, 3, 2, 4, 3, 3, 2, 3, 2, 2, 1, 4, 3, 3, 2, 3, 2, 2, 1, 3, 2, 2, 1, 2, 1, 1, 0 ]; + +fn count_page(lmti: usize, pg: &[u32]) -> i64 { + let pgsz = pg.len(); let pgbts = pgsz * 32; + let (lmt, icnt) = if lmti >= pgbts { (pgsz, 0) } else { + let lstw = lmti / 32; + let msk = 0xFFFFFFFEu32 << (lmti & 31); + let v = (msk | pg[lstw]) as usize; + (lstw, (CLUT[v & 0xFF] + CLUT[(v >> 8) & 0xFF] + + CLUT[(v >> 16) & 0xFF] + CLUT[v >> 24]) as u32) + }; + let mut count = 0u32; + for i in 0 .. lmt { + let v = pg[i] as usize; + count += (CLUT[v & 0xFF] + CLUT[(v >> 8) & 0xFF] + + CLUT[(v >> 16) & 0xFF] + CLUT[v >> 24]) as u32; + } + (icnt + count) as i64 +} + +fn primes_pages() -> Box)>> { + // a memoized iterable enclosing a Vec that grows as needed from an Iterator... + type Bpasi = Box)>>; // (lwi, base cmpsts page) + type Bpas = Rc<(RefCell, RefCell>>)>; // interior mutables + struct Bps(Bpas); // iterable wrapper for base primes array state + struct Bpsi<'a>(usize, &'a Bpas); // iterator with current pos, state ref's + impl<'a> Iterator for Bpsi<'a> { + type Item = &'a Vec; + fn next(&mut self) -> Option { + let n = self.0; let bpas = self.1; + while n >= bpas.1.borrow().len() { // not thread safe + let nbpg = match bpas.0.borrow_mut().next() { + Some(v) => v, _ => (0, vec!()) }; + if nbpg.1.is_empty() { return None } // end if no source iter + bpas.1.borrow_mut().push(cnvrt2bppg(nbpg)); + } + self.0 += 1; // unsafe pointer extends interior -> exterior lifetime + // multi-threading might drop following Vec while reading - protect + let ptr = &bpas.1.borrow()[n] as *const Vec; + unsafe { Some(&(*ptr)) } + } + } + impl<'a> IntoIterator for &'a Bps { + type Item = &'a Vec; + type IntoIter = Bpsi<'a>; + fn into_iter(self) -> Self::IntoIter { + Bpsi(0, &self.0) + } + } + fn make_page(lwi: u64, szbts: u64, bppgs: &Bpas) + -> (u64, Vec) { + let nxti = lwi + szbts; + let pbts = szbts as usize; + let mut cmpsts = vec!(0u32; pbts / 32); + 'outer: for bpg in Bps(bppgs.clone()).into_iter() { // in the inner tight loop... + let pgsz = bpg.len(); + for i in 0 .. pgsz { + let p = bpg[i] as u64; let pc = p as usize; + let s = (p * p - 3) / 2; + if s >= nxti { break 'outer; } else { // page start address: + let mut cp = if s >= lwi { (s - lwi) as usize } else { + let r = ((lwi - s) % p) as usize; + if r == 0 { 0 } else { pc - r } + }; + while cp < pbts { + unsafe { // avoids array bounds check, which is already done above + let cptr = cmpsts.get_unchecked_mut(cp >> 5); + *cptr |= 1u32 << (cp & 31); // about as fast as it gets... + } +// cmpsts[cp >> 5] |= 1u32 << (cp & 31); + cp += pc; + } + } + } + } + (lwi, cmpsts) + } + fn pages_from(lwi: u64, szbts: u64, bpas: Bpas) + -> Box)>> { + struct Gen(u64, u64); + impl Iterator for Gen { + type Item = (u64, u64); + #[inline] + fn next(&mut self) -> Option<(u64, u64)> { + let v = self.0; let inc = self.1; // calculate variable size here + self.0 = v + inc; + Some((v, inc)) + } + } + Box::new(Gen(lwi, szbts) + .map(move |(lwi, szbts)| make_page(lwi, szbts, &bpas))) + } + fn cnvrt2bppg(cmpsts: (u64, Vec)) -> Vec { + let (lwi, pg) = cmpsts; + let pgbts = pg.len() * 32; + let cnt = count_page(pgbts, &pg) as usize; + let mut bpv = vec!(0u32; cnt); + let mut j = 0; let bsp = (lwi + lwi + 3) as usize; + for i in 0 .. pgbts { + if (pg[i >> 5] & (1u32 << (i & 0x1F))) == 0u32 { + bpv[j] = (bsp + i + i) as u32; j += 1; + } + } + bpv + } + // recursive Rc/RefCell variable bpas - used only for init, then fixed ... + // start with just enough base primes to init the first base primes page... + let base_base_prms = vec!(3u32,5u32,7u32); + let rcvv = RefCell::new(vec!(base_base_prms)); + let bpas: Bpas = Rc::new((RefCell::new(Box::new(empty())), rcvv)); + let initpg = make_page(0, 32, &bpas); // small base primes page for SZ_BASE_BTS = 2^7 * 8 + *bpas.1.borrow_mut() = vec!(cnvrt2bppg(initpg)); // use for first page + let frstpg = make_page(0, SZ_BASE_BTS, &bpas); // init bpas for first base prime page + *bpas.0.borrow_mut() = pages_from(SZ_BASE_BTS, SZ_BASE_BTS, bpas.clone()); // recurse bpas + *bpas.1.borrow_mut() = vec!(cnvrt2bppg(frstpg)); // fixed for subsequent pages + pages_from(0, SZ_PAGE_BTS, bpas) // and bpas also used here for main pages +} + +fn primes_paged() -> Box> { + fn list_paged_primes(cmpstpgs: Box)>>) + -> Box> { + Box::new(cmpstpgs.flat_map(move |(lwi, cmpsts)| { + let pgbts = (cmpsts.len() * 32) as usize; + (0..pgbts).filter_map(move |i| { + if cmpsts[i >> 5] & (1u32 << (i & 31)) == 0 { + Some((lwi + i as u64) * 2 + 3) } else { None } }) })) + } + Box::new(once(2u64).chain(list_paged_primes(primes_pages()))) +} + +fn count_primes_paged(top: u64) -> i64 { + if top < 3 { if top < 2 { return 0i64 } else { return 1i64 } } + let topi = (top - 3u64) / 2; + primes_pages().take_while(|&(lwi, _)| lwi <= topi) + .map(|(lwi, pg)| { count_page((topi - lwi) as usize, &pg) }) + .sum::() + 1 +} + +fn main() { + let n = 262146; + let vrslt = primes_paged() + .take_while(|&p| p <= 100) + .collect::>(); + println!("{:?}", vrslt); + + let strt = Instant::now(); + +// let count = primes_paged().take_while(|&p| p <= RANGE).count(); // slow way to count + let count = count_primes_paged(RANGE); // fast way to count + + let elpsd = strt.elapsed(); + + println!("{}", count); + + let secs = elpsd.as_secs(); + let millis = (elpsd.subsec_nanos() / 1000000) as u64; + let dur = secs * 1000 + millis; + println!("Culling composites took {} milliseconds.", dur); +} diff --git a/Task/Sieve-of-Eratosthenes/Rust/sieve-of-eratosthenes-5.rust b/Task/Sieve-of-Eratosthenes/Rust/sieve-of-eratosthenes-5.rust deleted file mode 100644 index 628e92ad4a..0000000000 --- a/Task/Sieve-of-Eratosthenes/Rust/sieve-of-eratosthenes-5.rust +++ /dev/null @@ -1,175 +0,0 @@ -use std::iter::{empty, once}; -use std::rc::Rc; -use std::cell::RefCell; -use std::time::Instant; - -const RANGE: u64 = 1000000000; -const SZ_PAGE_BTS: u64 = (1 << 14) * 8; // this should be the size of the CPU L1 cache -const SZ_BASE_BTS: u64 = (1 << 7) * 8; -static CLUT: [u8; 256] = [ - 8, 7, 7, 6, 7, 6, 6, 5, 7, 6, 6, 5, 6, 5, 5, 4, 7, 6, 6, 5, 6, 5, 5, 4, 6, 5, 5, 4, 5, 4, 4, 3, - 7, 6, 6, 5, 6, 5, 5, 4, 6, 5, 5, 4, 5, 4, 4, 3, 6, 5, 5, 4, 5, 4, 4, 3, 5, 4, 4, 3, 4, 3, 3, 2, - 7, 6, 6, 5, 6, 5, 5, 4, 6, 5, 5, 4, 5, 4, 4, 3, 6, 5, 5, 4, 5, 4, 4, 3, 5, 4, 4, 3, 4, 3, 3, 2, - 6, 5, 5, 4, 5, 4, 4, 3, 5, 4, 4, 3, 4, 3, 3, 2, 5, 4, 4, 3, 4, 3, 3, 2, 4, 3, 3, 2, 3, 2, 2, 1, - 7, 6, 6, 5, 6, 5, 5, 4, 6, 5, 5, 4, 5, 4, 4, 3, 6, 5, 5, 4, 5, 4, 4, 3, 5, 4, 4, 3, 4, 3, 3, 2, - 6, 5, 5, 4, 5, 4, 4, 3, 5, 4, 4, 3, 4, 3, 3, 2, 5, 4, 4, 3, 4, 3, 3, 2, 4, 3, 3, 2, 3, 2, 2, 1, - 6, 5, 5, 4, 5, 4, 4, 3, 5, 4, 4, 3, 4, 3, 3, 2, 5, 4, 4, 3, 4, 3, 3, 2, 4, 3, 3, 2, 3, 2, 2, 1, - 5, 4, 4, 3, 4, 3, 3, 2, 4, 3, 3, 2, 3, 2, 2, 1, 4, 3, 3, 2, 3, 2, 2, 1, 3, 2, 2, 1, 2, 1, 1, 0 ]; - -fn count_page(lmti: usize, pg: &[u32]) -> i64 { - let pgsz = pg.len(); let pgbts = pgsz * 32; - let (lmt, icnt) = if lmti >= pgbts { (pgsz, 0) } else { - let lstw = lmti / 32; - let msk = 0xFFFFFFFEu32 << (lmti & 31); - let v = (msk | pg[lstw]) as usize; - (lstw, (CLUT[v & 0xFF] + CLUT[(v >> 8) & 0xFF] - + CLUT[(v >> 16) & 0xFF] + CLUT[v >> 24]) as u32) - }; - let mut count = 0u32; - for i in 0 .. lmt { - let v = pg[i] as usize; - count += (CLUT[v & 0xFF] + CLUT[(v >> 8) & 0xFF] - + CLUT[(v >> 16) & 0xFF] + CLUT[v >> 24]) as u32; - } - (icnt + count) as i64 -} - -fn primes_pages() -> Box)>> { - // a memoized iterable enclosing a Vec that grows as needed from an Iterator... - type Bpasi = Box)>>; // (lwi, base cmpsts page) - type Bpas = Rc<(RefCell, RefCell>>)>; // interior mutables - struct Bps(Bpas); // iterable wrapper for base primes array state - struct Bpsi<'a>(usize, &'a Bpas); // iterator with current pos, state ref's - impl<'a> Iterator for Bpsi<'a> { - type Item = &'a Vec; - fn next(&mut self) -> Option { - let n = self.0; let bpas = self.1; - while n >= bpas.1.borrow().len() { // not thread safe - let nbpg = match bpas.0.borrow_mut().next() { - Some(v) => v, _ => (0, vec!()) }; - if nbpg.1.is_empty() { return None } // end if no source iter - bpas.1.borrow_mut().push(cnvrt2bppg(nbpg)); - } - self.0 += 1; // unsafe pointer extends interior -> exterior lifetime - // multi-threading might drop following Vec while reading - protect - let ptr = &bpas.1.borrow()[n] as *const Vec; - unsafe { Some(&(*ptr)) } - } - } - impl<'a> IntoIterator for &'a Bps { - type Item = &'a Vec; - type IntoIter = Bpsi<'a>; - fn into_iter(self) -> Self::IntoIter { - Bpsi(0, &self.0) - } - } - fn make_page(lwi: u64, szbts: u64, bppgs: &Bpas) - -> (u64, Vec) { - let nxti = lwi + szbts; - let pbts = szbts as usize; - let mut cmpsts = vec!(0u32; pbts / 32); - 'outer: for bpg in Bps(bppgs.clone()).into_iter() { // in the inner tight loop... - let pgsz = bpg.len(); - for i in 0 .. pgsz { - let p = bpg[i] as u64; let pc = p as usize; - let s = (p * p - 3) / 2; - if s >= nxti { break 'outer; } else { // page start address: - let mut cp = if s >= lwi { (s - lwi) as usize } else { - let r = ((lwi - s) % p) as usize; - if r == 0 { 0 } else { pc - r } - }; - while cp < pbts { - unsafe { // avoids array bounds check, which is already done above - let cptr = cmpsts.get_unchecked_mut(cp >> 5); - *cptr |= 1u32 << (cp & 31); // about as fast as it gets... - } -// cmpsts[cp >> 5] |= 1u32 << (cp & 31); - cp += pc; - } - } - } - } - (lwi, cmpsts) - } - fn pages_from(lwi: u64, szbts: u64, bpas: Bpas) - -> Box)>> { - struct Gen(u64, u64); - impl Iterator for Gen { - type Item = (u64, u64); - #[inline] - fn next(&mut self) -> Option<(u64, u64)> { - let v = self.0; let inc = self.1; // calculate variable size here - self.0 = v + inc; - Some((v, inc)) - } - } - Box::new(Gen(lwi, szbts) - .map(move |(lwi, szbts)| make_page(lwi, szbts, &bpas))) - } - fn cnvrt2bppg(cmpsts: (u64, Vec)) -> Vec { - let (lwi, pg) = cmpsts; - let pgbts = pg.len() * 32; - let cnt = count_page(pgbts, &pg) as usize; - let mut bpv = vec!(0u32; cnt); - let mut j = 0; let bsp = (lwi + lwi + 3) as usize; - for i in 0 .. pgbts { - if (pg[i >> 5] & (1u32 << (i & 0x1F))) == 0u32 { - bpv[j] = (bsp + i + i) as u32; j += 1; - } - } - bpv - } - // recursive Rc/RefCell variable bpas - used only for init, then fixed ... - // start with just enough base primes to init the first base primes page... - let base_base_prms = vec!(3u32,5u32,7u32); - let rcvv = RefCell::new(vec!(base_base_prms)); - let bpas: Bpas = Rc::new((RefCell::new(Box::new(empty())), rcvv)); - let initpg = make_page(0, 32, &bpas); // small base primes page for SZ_BASE_BTS = 2^7 * 8 - *bpas.1.borrow_mut() = vec!(cnvrt2bppg(initpg)); // use for first page - let frstpg = make_page(0, SZ_BASE_BTS, &bpas); // init bpas for first base prime page - *bpas.0.borrow_mut() = pages_from(SZ_BASE_BTS, SZ_BASE_BTS, bpas.clone()); // recurse bpas - *bpas.1.borrow_mut() = vec!(cnvrt2bppg(frstpg)); // fixed for subsequent pages - pages_from(0, SZ_PAGE_BTS, bpas) // and bpas also used here for main pages -} - -fn primes_paged() -> Box> { - fn list_paged_primes(cmpstpgs: Box)>>) - -> Box> { - Box::new(cmpstpgs.flat_map(move |(lwi, cmpsts)| { - let pgbts = (cmpsts.len() * 32) as usize; - (0..pgbts).filter_map(move |i| { - if cmpsts[i >> 5] & (1u32 << (i & 31)) == 0 { - Some((lwi + i as u64) * 2 + 3) } else { None } }) })) - } - Box::new(once(2u64).chain(list_paged_primes(primes_pages()))) -} - -fn count_primes_paged(top: u64) -> i64 { - if top < 3 { if top < 2 { return 0i64 } else { return 1i64 } } - let topi = (top - 3u64) / 2; - primes_pages().take_while(|&(lwi, _)| lwi <= topi) - .map(|(lwi, pg)| { count_page((topi - lwi) as usize, &pg) }) - .sum::() + 1 -} - -fn main() { - let n = 262146; - let vrslt = primes_paged() - .take_while(|&p| p <= 100) - .collect::>(); - println!("{:?}", vrslt); - - let strt = Instant::now(); - -// let count = primes_paged().take_while(|&p| p <= RANGE).count(); // slow way to count - let count = count_primes_paged(RANGE); // fast way to count - - let elpsd = strt.elapsed(); - - println!("{}", count); - - let secs = elpsd.as_secs(); - let millis = (elpsd.subsec_nanos() / 1000000) as u64; - let dur = secs * 1000 + millis; - println!("Culling composites took {} milliseconds.", dur); -} diff --git a/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-1.ss b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-1.scm similarity index 100% rename from Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-1.ss rename to Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-1.scm diff --git a/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-10.ss b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-10.scm similarity index 100% rename from Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-10.ss rename to Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-10.scm diff --git a/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-11.ss b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-11.scm similarity index 100% rename from Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-11.ss rename to Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-11.scm diff --git a/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-12.ss b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-12.scm similarity index 100% rename from Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-12.ss rename to Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-12.scm diff --git a/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-13.ss b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-13.scm similarity index 100% rename from Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-13.ss rename to Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-13.scm diff --git a/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-14.ss b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-14.scm similarity index 100% rename from Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-14.ss rename to Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-14.scm diff --git a/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-15.ss b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-15.scm similarity index 100% rename from Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-15.ss rename to Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-15.scm diff --git a/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-2.ss b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-2.scm similarity index 100% rename from Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-2.ss rename to Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-2.scm diff --git a/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-3.ss b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-3.scm similarity index 100% rename from Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-3.ss rename to Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-3.scm diff --git a/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-4.ss b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-4.scm similarity index 100% rename from Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-4.ss rename to Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-4.scm diff --git a/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-5.ss b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-5.scm similarity index 100% rename from Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-5.ss rename to Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-5.scm diff --git a/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-6.ss b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-6.scm similarity index 100% rename from Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-6.ss rename to Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-6.scm diff --git a/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-7.ss b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-7.scm similarity index 100% rename from Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-7.ss rename to Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-7.scm diff --git a/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-8.scm b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-8.scm new file mode 100644 index 0000000000..c25dced31e --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-8.scm @@ -0,0 +1,5 @@ + (define (sieve s) + (let ((p (head s))) + (s-cons p + (sieve (s-diff s (from-By p p)))))) + (define primes (sieve (from-By 2 1))) diff --git a/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-8.ss b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-8.ss deleted file mode 100644 index 9355360f1c..0000000000 --- a/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-8.ss +++ /dev/null @@ -1,5 +0,0 @@ - (define (sieve s) - (let ((p (head s))) - (s-cons p - (sieve (s-diff s (from-By p p)))))) - (define primes (sieve (from-By 2 1))) diff --git a/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-9.scm b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-9.scm new file mode 100644 index 0000000000..6f2f0343e2 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-9.scm @@ -0,0 +1,8 @@ + (define (primes-To m) + (define (sieve s) + (let ((p (head s))) + (cond ((> (* p p) m) s) + (else (s-cons p + (sieve (s-diff (tail s) + (from-By (* p p) p)))))))) + (sieve (from-By 2 1))) diff --git a/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-9.ss b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-9.ss deleted file mode 100644 index a18d56feff..0000000000 --- a/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-9.ss +++ /dev/null @@ -1,8 +0,0 @@ - (define (primes-To m) - (define (sieve s) - (let ((p (head s))) - (cond ((> (* p p) m) s) - (else (s-cons p - (sieve (s-diff (tail s) - (from-By (* p p) p)))))))) - (sieve (from-By 2 1))) diff --git a/Task/Sieve-of-Eratosthenes/Standard-ML/sieve-of-eratosthenes-1.ml b/Task/Sieve-of-Eratosthenes/Standard-ML/sieve-of-eratosthenes-1.ml index a02c48d7cb..d36d624312 100644 --- a/Task/Sieve-of-Eratosthenes/Standard-ML/sieve-of-eratosthenes-1.ml +++ b/Task/Sieve-of-Eratosthenes/Standard-ML/sieve-of-eratosthenes-1.ml @@ -18,7 +18,7 @@ val rec nextPrimebit = fn Bits => fn pos => if pos+1 >= BitArray.length Bits - then NONE + then NONE else ( if BitArray.sub ( Bits,pos) then SOME (i2inf pos) else nextPrimebit Bits (pos+1) ); @@ -68,9 +68,9 @@ val sieveThroughSegment = in ( sweep (nums, step, k, n) ; - if ( p*p <= up andalso Option.isSome nxt ) - then oldprimes ( inf2i (p-st+1) ) ctlist - else oldprimes 0 t (* next segment B *) + if ( p*p <= up andalso Option.isSome nxt ) + then oldprimes ( inf2i (p-st+1) ) ctlist + else oldprimes 0 t (* next segment B *) ) end @@ -85,9 +85,9 @@ val sieveThroughSegment = val rec workSegmentsDown = fn firstFn => - fn nextFns => - fn sizeSeg : int => - fn upLimit : IntInf.int => + fn nextFns => + fn sizeSeg : int => + fn upLimit : IntInf.int => let val residual = upLimit mod i2inf sizeSeg in diff --git a/Task/Sieve-of-Eratosthenes/Standard-ML/sieve-of-eratosthenes-2.ml b/Task/Sieve-of-Eratosthenes/Standard-ML/sieve-of-eratosthenes-2.ml index 278cbf49da..a06bd033e5 100644 --- a/Task/Sieve-of-Eratosthenes/Standard-ML/sieve-of-eratosthenes-2.ml +++ b/Task/Sieve-of-Eratosthenes/Standard-ML/sieve-of-eratosthenes-2.ml @@ -1,9 +1,9 @@ -val writeSegment = fn L : {segment:BitArray.array, start:IntInf.int} list => fn NthSegment => - let - val M=List.nth (L , NthSegment - 1 ) - in - List.map (fn x=> x + #start M) (map IntInf.fromInt (BitArray.getBits ( #segment M)) ) - end; + let + val M=List.nth (L , NthSegment - 1 ) + in + List.map (fn x=> x + #start M) (map IntInf.fromInt (BitArray.getBits ( #segment M)) ) + end; - val primesInBits = segmentedSieve 2500000000 ; val primesInBits = [{segment=-,start=1},{segment=-,start=120000001}, diff --git a/Task/Sieve-of-Eratosthenes/Stata/sieve-of-eratosthenes-1.stata b/Task/Sieve-of-Eratosthenes/Stata/sieve-of-eratosthenes-1.stata index 6a1f8d09ee..b1dc0c2795 100644 --- a/Task/Sieve-of-Eratosthenes/Stata/sieve-of-eratosthenes-1.stata +++ b/Task/Sieve-of-Eratosthenes/Stata/sieve-of-eratosthenes-1.stata @@ -1,20 +1,20 @@ prog def sieve - args n - clear - qui set obs `n' - gen long p=_n - gen byte a=_n>1 - forv i=2/`n' { - if a[`i'] { - loc j=`i'*`i' - if `j'>`n' { - continue, break - } - forv k=`j'(`i')`n' { - qui replace a=0 in `k' - } - } - } - qui keep if a - drop a + args n + clear + qui set obs `n' + gen long p=_n + gen byte a=_n>1 + forv i=2/`n' { + if a[`i'] { + loc j=`i'*`i' + if `j'>`n' { + continue, break + } + forv k=`j'(`i')`n' { + qui replace a=0 in `k' + } + } + } + qui keep if a + drop a end diff --git a/Task/Sieve-of-Eratosthenes/Stata/sieve-of-eratosthenes-3.stata b/Task/Sieve-of-Eratosthenes/Stata/sieve-of-eratosthenes-3.stata index cffdf1a3a7..837f34537e 100644 --- a/Task/Sieve-of-Eratosthenes/Stata/sieve-of-eratosthenes-3.stata +++ b/Task/Sieve-of-Eratosthenes/Stata/sieve-of-eratosthenes-3.stata @@ -1,17 +1,17 @@ mata real colvector sieve(real scalar n) { - real colvector a - real scalar i, j - if (n < 2) return(J(0, 1, .)) - a = J(n, 1, 1) - a[1] = 0 - for (i = 1; i <= n; i++) { - if (a[i]) { - j = i*i - if (j > n) return(select(1::n, a)) - for (; j <= n; j = j+i) a[j] = 0 - } - } + real colvector a + real scalar i, j + if (n < 2) return(J(0, 1, .)) + a = J(n, 1, 1) + a[1] = 0 + for (i = 1; i <= n; i++) { + if (a[i]) { + j = i*i + if (j > n) return(select(1::n, a)) + for (; j <= n; j = j+i) a[j] = 0 + } + } } sieve(10) diff --git a/Task/Sieve-of-Eratosthenes/Tailspin/sieve-of-eratosthenes-2.tailspin b/Task/Sieve-of-Eratosthenes/Tailspin/sieve-of-eratosthenes-2.tailspin index 8da395a5f1..13ade8debf 100644 --- a/Task/Sieve-of-Eratosthenes/Tailspin/sieve-of-eratosthenes-2.tailspin +++ b/Task/Sieve-of-Eratosthenes/Tailspin/sieve-of-eratosthenes-2.tailspin @@ -1,13 +1,23 @@ -templates sieve - def limit: $; - @: [ 1..$limit -> 1 ]; - @(1): 0; - 2..$limit -> # - $@ -> \[i](<=1> $i !\) ! +sieve templates + limit is $; + @ set [ 2..$limit ]; + 1 -> !# + $@ ! - when )> do - def prime2: $ * $; - $prime2..$limit:$ -> @sieve($): 0; + when <|..$@::length ?($@($) * $@($) matches <|..$limit>)> do + sift sink + prime is $; + @ set $prime * $prime; + @sieve set [ $@sieve... -> # ]; + when <|..~$@> do + $ ! + when <|$@~..> do + @ set $@ + $prime; + $ -> #! + end sift + + $@($) -> !sift + $ + 1 -> !# end sieve -1000 -> sieve... -> '$; ' -> !OUT::write +1000 -> sieve ...-> '$; ' ! diff --git a/Task/Sieve-of-Eratosthenes/Tailspin/sieve-of-eratosthenes-3.tailspin b/Task/Sieve-of-Eratosthenes/Tailspin/sieve-of-eratosthenes-3.tailspin new file mode 100644 index 0000000000..8da395a5f1 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Tailspin/sieve-of-eratosthenes-3.tailspin @@ -0,0 +1,13 @@ +templates sieve + def limit: $; + @: [ 1..$limit -> 1 ]; + @(1): 0; + 2..$limit -> # + $@ -> \[i](<=1> $i !\) ! + + when )> do + def prime2: $ * $; + $prime2..$limit:$ -> @sieve($): 0; +end sieve + +1000 -> sieve... -> '$; ' -> !OUT::write diff --git a/Task/Sieve-of-Eratosthenes/Tailspin/sieve-of-eratosthenes-4.tailspin b/Task/Sieve-of-Eratosthenes/Tailspin/sieve-of-eratosthenes-4.tailspin new file mode 100644 index 0000000000..c35f2121a8 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Tailspin/sieve-of-eratosthenes-4.tailspin @@ -0,0 +1,13 @@ +sieve templates + limit is $; + @ set [ 1..$limit -> 1 ]; + @(1) set 0; + 2..$limit -> !# + $@(.. as i; -> if <|=1> -> $i) ! + + when <|?($@($) matches <|=1>)> do + prime2 is $ * $; + $prime2..$limit:$ -> @sieve($) set 0; +end sieve + +1000 -> sieve... -> '$; ' ! diff --git a/Task/Sieve-of-Eratosthenes/UNIX-Shell/sieve-of-eratosthenes-4.sh b/Task/Sieve-of-Eratosthenes/UNIX-Shell/sieve-of-eratosthenes-4.sh index 0db4f06487..5cf41c678d 100644 --- a/Task/Sieve-of-Eratosthenes/UNIX-Shell/sieve-of-eratosthenes-4.sh +++ b/Task/Sieve-of-Eratosthenes/UNIX-Shell/sieve-of-eratosthenes-4.sh @@ -1,32 +1,32 @@ # Fill $1 characters with $2. fill () { - # This pipeline would begin - # head -c $1 /dev/zero | ... - # but some systems have no head -c. Use dd. - dd if=/dev/zero bs=$1 count=1 2>/dev/null | tr '\0' $2 + # This pipeline would begin + # head -c $1 /dev/zero | ... + # but some systems have no head -c. Use dd. + dd if=/dev/zero bs=$1 count=1 2>/dev/null | tr '\0' $2 } filter () { - # Use sed to put an 'x' after each multiple of $1, remove - # first 'x', and mark non-primes with '0'. - sed -e s/$2/\&x/g -e s/x// -e s/.x/0/g | { - if expr $1 '*' $1 '<' $3 > /dev/null; then - filter `expr $1 + 1` .$2 $3 - else - cat - fi - } + # Use sed to put an 'x' after each multiple of $1, remove + # first 'x', and mark non-primes with '0'. + sed -e s/$2/\&x/g -e s/x// -e s/.x/0/g | { + if expr $1 '*' $1 '<' $3 > /dev/null; then + filter `expr $1 + 1` .$2 $3 + else + cat + fi + } } # Generate a sequence of 1s and 0s indicating primality. oz () { - fill $1 1 | sed s/1/0/ | filter 2 .. $1 + fill $1 1 | sed s/1/0/ | filter 2 .. $1 } # Echo prime numbers from 2 to $1. prime () { - # Escape backslash inside backquotes. sed sees one backslash. - echo `oz $1 | sed 's/./&\\ + # Escape backslash inside backquotes. sed sees one backslash. + echo `oz $1 | sed 's/./&\\ /g' | grep -n 1 | sed s/:1//` } diff --git a/Task/Sieve-of-Eratosthenes/VAX-Assembly/sieve-of-eratosthenes.vax b/Task/Sieve-of-Eratosthenes/VAX-Assembly/sieve-of-eratosthenes.vax index 7beaf7b598..8cee0e5c96 100644 --- a/Task/Sieve-of-Eratosthenes/VAX-Assembly/sieve-of-eratosthenes.vax +++ b/Task/Sieve-of-Eratosthenes/VAX-Assembly/sieve-of-eratosthenes.vax @@ -1,29 +1,29 @@ 000F4240 0000 1 n=1000*1000 - 0000 0000 2 .entry main,0 - 7E 7CFD 0002 3 clro -(sp) ;result buffer - 5E DD 0005 4 pushl sp ;pointer to buffer - 10 DD 0007 5 pushl #16 ;descriptor -> len of buffer + 0000 0000 2 .entry main,0 + 7E 7CFD 0002 3 clro -(sp) ;result buffer + 5E DD 0005 4 pushl sp ;pointer to buffer + 10 DD 0007 5 pushl #16 ;descriptor -> len of buffer 0009 6 - 02 DD 0009 7 pushl #2 ;1st candidate + 02 DD 0009 7 pushl #2 ;1st candidate 000B 8 test: - 09 46'AF 6E E1 000B 9 bbc (sp), b^bits, found ;bc - bit clear + 09 46'AF 6E E1 000B 9 bbc (sp), b^bits, found ;bc - bit clear 0010 10 next: - F3 6E 000F4240 8F F2 0010 11 aoblss #n, (sp), test ;+1: limit,index + F3 6E 000F4240 8F F2 0010 11 aoblss #n, (sp), test ;+1: limit,index 04 0018 12 ret 0019 13 found: - 04 AE 7F 0019 14 pushaq 4(sp) ;-> descriptor by ref - 04 AE DF 001C 15 pushal 4(sp) ;-> prime on stack by ref - 00000000'GF 02 FB 001F 16 calls #2, g^ots$cvt_l_ti ;convert integer to string - 04 AE 7F 0026 17 pushaq 4(sp) ; - 00000000'GF 01 FB 0029 18 calls #1, g^lib$put_output ;show result + 04 AE 7F 0019 14 pushaq 4(sp) ;-> descriptor by ref + 04 AE DF 001C 15 pushal 4(sp) ;-> prime on stack by ref + 00000000'GF 02 FB 001F 16 calls #2, g^ots$cvt_l_ti ;convert integer to string + 04 AE 7F 0026 17 pushaq 4(sp) ; + 00000000'GF 01 FB 0029 18 calls #1, g^lib$put_output ;show result 0030 19 - 53 6E D0 0030 20 movl (sp), r3 + 53 6E D0 0030 20 movl (sp), r3 0033 21 mult: - 0002 53 6E 000F4240 8F F1 0033 22 acbl #n, (sp), r3, set_mult ;limit,add,index - D1 11 003D 23 brb next - 003F 24 set_mult: ;set bits for multiples - EF 46'AF 53 E2 003F 25 bbss r3, b^bits, mult ;branch on bit set & set - ED 11 0044 26 brb mult + 0002 53 6E 000F4240 8F F1 0033 22 acbl #n, (sp), r3, set_mult ;limit,add,index + D1 11 003D 23 brb next + 003F 24 set_mult: ;set bits for multiples + EF 46'AF 53 E2 003F 25 bbss r3, b^bits, mult ;branch on bit set & set + ED 11 0044 26 brb mult 0046 27 - 0001E892 0046 28 bits: .blkl /32 - E892 29 .end main + 0001E892 0046 28 bits: .blkl /32 + E892 29 .end main diff --git a/Task/Sieve-of-Eratosthenes/VBScript/sieve-of-eratosthenes.vb b/Task/Sieve-of-Eratosthenes/VBScript/sieve-of-eratosthenes.vb deleted file mode 100644 index 1dca87ec02..0000000000 --- a/Task/Sieve-of-Eratosthenes/VBScript/sieve-of-eratosthenes.vb +++ /dev/null @@ -1,20 +0,0 @@ - Dim sieve() - If WScript.Arguments.Count>=1 Then - n = WScript.Arguments(0) - Else - n = 99 - End If - ReDim sieve(n) - For i = 1 To n - sieve(i) = True - Next - For i = 2 To n - If sieve(i) Then - For j = i * 2 To n Step i - sieve(j) = False - Next - End If - Next - For i = 2 To n - If sieve(i) Then WScript.Echo i - Next diff --git a/Task/Sieve-of-Eratosthenes/VBScript/sieve-of-eratosthenes.vbs b/Task/Sieve-of-Eratosthenes/VBScript/sieve-of-eratosthenes.vbs new file mode 100644 index 0000000000..a95bb424b8 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/VBScript/sieve-of-eratosthenes.vbs @@ -0,0 +1,20 @@ + Dim sieve() + If WScript.Arguments.Count>=1 Then + n = WScript.Arguments(0) + Else + n = 99 + End If + ReDim sieve(n) + For i = 1 To n + sieve(i) = True + Next + For i = 2 To n + If sieve(i) Then + For j = i * 2 To n Step i + sieve(j) = False + Next + End If + Next + For i = 2 To n + If sieve(i) Then WScript.Echo i + Next diff --git a/Task/Sieve-of-Eratosthenes/Vala/sieve-of-eratosthenes.vala b/Task/Sieve-of-Eratosthenes/Vala/sieve-of-eratosthenes.vala index 7d0f849c8b..04b4fa229c 100644 --- a/Task/Sieve-of-Eratosthenes/Vala/sieve-of-eratosthenes.vala +++ b/Task/Sieve-of-Eratosthenes/Vala/sieve-of-eratosthenes.vala @@ -1,38 +1,38 @@ using Gee; ArrayList primes(int limit){ - var sieve = new ArrayList(); - var prime_list = new ArrayList(); - - for(int i = 0; i <= limit; i++){ - sieve.add(true); - } - - sieve[0] = false; - sieve[1] = false; - - for (int i = 2; i <= limit/2; i++){ - if (sieve[i] != false){ - for (int j = 2; i*j <= limit; j++){ - sieve[i*j] = false; - } - } - } + var sieve = new ArrayList(); + var prime_list = new ArrayList(); - for (int i = 0; i < sieve.size; i++){ - if (sieve[i] != false){ - prime_list.add(i); - } - } - - return prime_list; + for(int i = 0; i <= limit; i++){ + sieve.add(true); + } + + sieve[0] = false; + sieve[1] = false; + + for (int i = 2; i <= limit/2; i++){ + if (sieve[i] != false){ + for (int j = 2; i*j <= limit; j++){ + sieve[i*j] = false; + } + } + } + + for (int i = 0; i < sieve.size; i++){ + if (sieve[i] != false){ + prime_list.add(i); + } + } + + return prime_list; } // end primes public static void main(){ - var prime_list = primes(50); - - foreach(var prime in prime_list) - stdout.printf("%s ", prime.to_string()); - - stdout.printf("\n"); + var prime_list = primes(50); + + foreach(var prime in prime_list) + stdout.printf("%s ", prime.to_string()); + + stdout.printf("\n"); } diff --git a/Task/Sieve-of-Eratosthenes/X86-64-Assembly/sieve-of-eratosthenes.x86-64 b/Task/Sieve-of-Eratosthenes/X86-64-Assembly/sieve-of-eratosthenes.x86-64 new file mode 100644 index 0000000000..518e83439d --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/X86-64-Assembly/sieve-of-eratosthenes.x86-64 @@ -0,0 +1,110 @@ +; Sieve of Eratosthenes +; assembly X86 window +; download and install visual studio 2022 free site microsoft +; search and open X64 native tools command prompt +; compil and link program with this command : +; ml64 cribleera.asm /link /ENTRY:main /SUBSYSTEM:console kernel32.lib user32.lib Shell32.lib +; this program respects the 64-bit calling convention : +; registers arguments : rcx rdx r8 r9 and stack +; registers saved : rbx,rbp,rdi,rsi, r12-r15 +; ATTENTION les registres rax,rcx,rdx,r8-r11 peuvent être +; perdus lors d'un appel de fonction +;********************************* +; constantes +;********************************* +STD_OUTPUT_HANDLE equ -11 +MAXI equ 101 +;********************************* +; macros +;********************************* +;for this file, see task include a file for X86-64 language +include macrosInclude.asm + +;********************************* +; user data +;********************************* +.data +szMessPrime db "Prime : ",0 +LGMESSPRIME equ $ - szMessPrime - 1 + +szCarriageReturn db 10,0 + +align 8 + +hConsole dq 0 +sConvArea db 24 dup (0) +tablePrime db MAXI dup (0) +;********************************* +; user code fonction principale +;********************************* +.code + +extern WriteFile : proc, GetStdHandle : proc, ExitProcess : proc +extern GetLastError : proc + +main PROC public + displayLib "Program X86-64 start." + + mov rdi, offset tablePrime + mov rbx,2 + mov r8,1 + mov rcx,rbx + call displayResult +B1: + mov [rdi+rbx],r8b + add rbx,2 + cmp rbx,MAXI + jl B1 + mov rbx,3 + mov r12,1 +B2: + mov al,[rdi+rbx] + cmp al,1 + je suite + mov rcx,rbx + call displayResult + mov rbp,rbx + +B3: + mov [rdi+rbp],r12b + add rbp,rbx ; add prime + cmp rbp,MAXI + jle B3 +suite: + add rbx,2 + cmp rbx,MAXI + jle B2 + +finProgramme: + displayLib "Program end." + sub rsp,28h + mov rcx,0 ; return code + call ExitProcess +main ENDP +;************************************** +; insertion fin de ligne +;************************************** +; rcx contains value +displayResult proc ; INFO: displayResult + push rbx + mov rbx,rcx + mov rcx, offset szMessPrime + mov rdx,LGMESSPRIME + call afficherConsole + mov rcx,rbx + mov rdx,offset sConvArea + call conversion10 + mov rdx,rax + mov rcx, offset sConvArea + call afficherConsole + mov rcx, offset szCarriageReturn + mov rdx,1 + call afficherConsole + pop rbx + ret +displayResult endp + +;for this file, see task include a file for X86-64 language +include routinesInclude.asm + +end diff --git a/Task/Sieve-of-Eratosthenes/YAMLScript/sieve-of-eratosthenes.ys b/Task/Sieve-of-Eratosthenes/YAMLScript/sieve-of-eratosthenes.ys new file mode 100644 index 0000000000..43e80ca693 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/YAMLScript/sieve-of-eratosthenes.ys @@ -0,0 +1,26 @@ +!YS-v0 + +defn main(n=100): + primes =: primes-up-to(n) + say: |- + The $(primes.#) prime numbers less than $n are: + $(text(primes):chomp) + +defn primes-up-to(limit): + :: Returns a lazy sequence of prime numbers less than limit. + + max-i =: int(limit.-- / 2) + refs =: boolean-array(max-i true) + root =: sqrt(limit):int.-- / 2 + ? doseq i (1 .. root) + :when aget(refs i) + : ? doseq + j range( + mul(i.++ 2 i), + max-i, + add(i i 1)) + : aset(refs j false) + cons 2: + map \((_ * 2).++): + filter \(aget refs _): + range(1 max-i) diff --git a/Task/Sieve-of-Eratosthenes/Zkl/sieve-of-eratosthenes.zkl b/Task/Sieve-of-Eratosthenes/Zkl/sieve-of-eratosthenes.zkl index 19b440fa16..a430043d57 100644 --- a/Task/Sieve-of-Eratosthenes/Zkl/sieve-of-eratosthenes.zkl +++ b/Task/Sieve-of-Eratosthenes/Zkl/sieve-of-eratosthenes.zkl @@ -1,7 +1,7 @@ fcn sieve(limit){ composite:=Data(limit+1).fill(1); // bucket of bytes set to 1 (prime) (2).pump(limit.toFloat().sqrt()+1, Void, // Void==no results, just loop - composite.get, Void.Filter, // if prime, zero multiples + composite.get, Void.Filter, // if prime, zero multiples 'wrap(n){ [n*n..limit,n].pump(Void,composite.set.fp1(0)) }); //composite[n*p]=0 (2).filter(limit-1,composite.get); // bytes still 1 are prime } diff --git a/Task/Sieve-of-Pritchard/EasyLang/sieve-of-pritchard.easy b/Task/Sieve-of-Pritchard/EasyLang/sieve-of-pritchard.easy index fb9fb5a77d..2d9c1c665e 100644 --- a/Task/Sieve-of-Pritchard/EasyLang/sieve-of-pritchard.easy +++ b/Task/Sieve-of-Pritchard/EasyLang/sieve-of-pritchard.easy @@ -1,4 +1,4 @@ -proc pritchard limit . primes[] . +proc pritchard limit &primes[] . len members[] limit members[1] = 1 steplength = 1 @@ -23,19 +23,13 @@ proc pritchard limit . primes[] . mcpy[] = members[] for w to nlimit if mcpy[w] = 1 - if np = 5 and w > prime - np = w - . + if np = 5 and w > prime : np = w n = prime * w - if n > nlimit - break 1 - . + if n > nlimit : break 1 members[n] = 0 . . - if np < prime - break 1 - . + if np < prime : break 1 primes[] &= prime if prime = 2 prime = 3 @@ -45,9 +39,7 @@ proc pritchard limit . primes[] . nlimit = lower (steplength * prime) limit . for i = 2 to len members[] - if members[i] = 1 - primes[] &= i - . + if members[i] = 1 : primes[] &= i . . pritchard 150 p[] diff --git a/Task/Sieve-of-Pritchard/Fortran/sieve-of-pritchard.f b/Task/Sieve-of-Pritchard/Fortran/sieve-of-pritchard.f new file mode 100644 index 0000000000..89353dc946 --- /dev/null +++ b/Task/Sieve-of-Pritchard/Fortran/sieve-of-pritchard.f @@ -0,0 +1,123 @@ +program sieve_pritchard_optimized + implicit none + + call test_pritchard() + +contains + + function pritchard(limit, verbose) result(all_primes) + integer, intent(in) :: limit + logical, intent(in) :: verbose + integer, allocatable :: all_primes(:) + + logical, allocatable :: members(:), mcopy(:) + integer, allocatable :: primes(:) + integer :: steplength, prime, nlimit, rtlim + integer :: w, n, np + integer :: prime_count, i, total_count, ac, rc + + ! Allocate arrays + allocate(members(limit)) + members = .false. + members(1) = .true. + allocate(mcopy(limit)) + i = limit/log(float(limit)) + (limit/log(float(limit)))/2 ! Estimate the number of primes + allocate(primes(i)) ! Upper bound for primes + prime_count = 0 + + steplength = 1 + prime = 2 + nlimit = prime * steplength + ac = 2 + rc = 1 + rtlim = int(sqrt(real(limit))) + + do while (prime < rtlim) + ! Step 1: Roll wheel + if (steplength < limit) then + do w = 1, steplength + if (members(w)) then + n = w + steplength + do while (n <= nlimit) + members(n) = .true. + ac = ac + 1 + n = n + steplength + end do + end if + end do + steplength = nlimit + end if + + ! Step 2: Mark multiples using a copy of current wheel + mcopy = members + np = 5 + do w = 1, nlimit + if (mcopy(w)) then + if (np == 5 .and. w > prime) np = w + n = prime * w + if (n > nlimit) exit + rc = rc + 1 + members(n) = .false. + end if + end do + + if (np < prime) exit + + ! Store current prime + prime_count = prime_count + 1 + primes(prime_count) = prime + + ! Update prime and nlimit + prime = merge(3, np, prime == 2) + nlimit = min(steplength * prime, limit) + end do + + members(1) = .false. + + ! Count remaining primes in wheel + total_count = prime_count + do i = 1, limit + if (members(i)) total_count = total_count + 1 + end do + + ! Allocate final primes array + allocate(all_primes(total_count)) + all_primes(1:prime_count) = primes(1:prime_count) + + ! Append remaining primes + total_count = prime_count + do i = 1, limit + if (members(i)) then + total_count = total_count + 1 + all_primes(total_count) = i + end if + end do + + if (verbose) then + print '(a,i0,a,i0,a,i0,a,i0)', & + "up to ", limit, ", added ", ac, ", removed ", rc, & + ", prime count ", size(all_primes) + end if + + deallocate(members, mcopy, primes) + end function pritchard + + subroutine test_pritchard() + integer, allocatable :: result(:) + integer :: i + + ! All primes <= 150 + result = pritchard(150, .false.) + do i = 1, size(result) + write(*,'(i0,1x)',advance='no') result(i) + end do + print * + + deallocate(result) + + ! Number of primes <= 1,000,000 + result = pritchard(1000000, .true.) + deallocate(result) + end subroutine test_pritchard + +end program sieve_pritchard_optimized diff --git a/Task/Sieve-of-Pritchard/Java/sieve-of-pritchard.java b/Task/Sieve-of-Pritchard/Java/sieve-of-pritchard.java index 12d9ae7ab4..8f7aec00e7 100644 --- a/Task/Sieve-of-Pritchard/Java/sieve-of-pritchard.java +++ b/Task/Sieve-of-Pritchard/Java/sieve-of-pritchard.java @@ -4,80 +4,80 @@ import java.util.List; public final class SieveOfPritchard { - public static void main(String[] args) { - System.out.println(sieveOfPritchard(150) + System.lineSeparator()); - System.out.println("Number of primes up to 1,000,000 is " + sieveOfPritchard(1_000_000).size() + "."); - System.out.println(); - - final long start = System.currentTimeMillis(); - System.out.print("Number of primes up to 100,000,000 is " + sieveOfPritchard(100_000_000).size()); - final long finish = System.currentTimeMillis(); - System.out.println(". Obtained in a time of " + ( (double) finish - start ) / 1_000 + " seconds."); - } - - private static List sieveOfPritchard(int limit) { - List primes = new ArrayList(); - BitSet members = new BitSet(limit + 1); - members.set(1); - List deletions = new ArrayList(); - final int rootLimit = (int) Math.sqrt(limit); - int nLimit = 2; - int stepLength = 1; - int prime = 2; - - while ( prime <= rootLimit ) { - if ( stepLength < limit ) { - for ( int w = 1; w >= 0; w = members.nextSetBit(w + 1) ) { - int n = w + stepLength; + public static void main(String[] args) { + System.out.println(sieveOfPritchard(150) + System.lineSeparator()); + System.out.println("Number of primes up to 1,000,000 is " + sieveOfPritchard(1_000_000).size() + "."); + System.out.println(); + + final long start = System.currentTimeMillis(); + System.out.print("Number of primes up to 100,000,000 is " + sieveOfPritchard(100_000_000).size()); + final long finish = System.currentTimeMillis(); + System.out.println(". Obtained in a time of " + ( (double) finish - start ) / 1_000 + " seconds."); + } + + private static List sieveOfPritchard(int limit) { + List primes = new ArrayList(); + BitSet members = new BitSet(limit + 1); + members.set(1); + List deletions = new ArrayList(); + final int rootLimit = (int) Math.sqrt(limit); + int nLimit = 2; + int stepLength = 1; + int prime = 2; + + while ( prime <= rootLimit ) { + if ( stepLength < limit ) { + for ( int w = 1; w >= 0; w = members.nextSetBit(w + 1) ) { + int n = w + stepLength; while ( n <= nLimit ) { members.set(n); n += stepLength; - } - } - stepLength = nLimit; - } - - deletions.clear(); - int nextPrime = 5; - for ( int w = 1; w < nLimit; w = members.nextSetBit(w + 1) ) { + } + } + stepLength = nLimit; + } + + deletions.clear(); + int nextPrime = 5; + for ( int w = 1; w < nLimit; w = members.nextSetBit(w + 1) ) { if ( nextPrime == 5 && w > prime ) { nextPrime = w; } final int n = prime * w; if ( n > nLimit ) { - break; + break; } deletions.add(n); - } - for ( int deletion : deletions ) { - members.clear(deletion); - } - - if ( nextPrime < prime ) { - break; - } - - primes.add(prime); - prime = ( prime == 2 ) ? 3 : nextPrime; - nLimit = (int) Math.min((long) stepLength * prime, limit); - } - - if ( stepLength < limit ) { - for ( int w = 1; w >= 0; w = members.nextSetBit(w + 1) ) { - int n = w + stepLength; + } + for ( int deletion : deletions ) { + members.clear(deletion); + } + + if ( nextPrime < prime ) { + break; + } + + primes.add(prime); + prime = ( prime == 2 ) ? 3 : nextPrime; + nLimit = (int) Math.min((long) stepLength * prime, limit); + } + + if ( stepLength < limit ) { + for ( int w = 1; w >= 0; w = members.nextSetBit(w + 1) ) { + int n = w + stepLength; while ( n <= limit ) { members.set(n); n += stepLength; - } - } - } - - members.clear(1); - for ( int i = members.nextSetBit(0); i >= 0; i = members.nextSetBit(i + 1) ) { - primes.add(i); - }; - - return primes; - } + } + } + } + + members.clear(1); + for ( int i = members.nextSetBit(0); i >= 0; i = members.nextSetBit(i + 1) ) { + primes.add(i); + }; + + return primes; + } } diff --git a/Task/Sieve-of-Pritchard/Julia/sieve-of-pritchard.julia b/Task/Sieve-of-Pritchard/Julia/sieve-of-pritchard.jl similarity index 100% rename from Task/Sieve-of-Pritchard/Julia/sieve-of-pritchard.julia rename to Task/Sieve-of-Pritchard/Julia/sieve-of-pritchard.jl diff --git a/Task/Sieve-of-Pritchard/REXX/sieve-of-pritchard.rexx b/Task/Sieve-of-Pritchard/REXX/sieve-of-pritchard.rexx new file mode 100644 index 0000000000..1454d657e9 --- /dev/null +++ b/Task/Sieve-of-Pritchard/REXX/sieve-of-pritchard.rexx @@ -0,0 +1,91 @@ +-- 24 Aug 2025 +include Setting + +call Time('r') +say 'SIEVE OF PRITCHARD' +say version +say +call Pritchard 150,1 +call Timer 'r' +call Pritchard 1e6,0 +call Timer 'r' +call Eratosthenes 1e6 +call Timer 'r' +exit + +Pritchard: +procedure expose Memo. +arg xx,yy +say 'Primes up to' xx 'by Pritchard...' +memb. = 0; memb.1 = 1; mcpy. = 0; prim. = 0; nwpr. = 0 +nl = 2; nn = 0; pr = 2; rl = Sqrt(xx); sl = 1; ub = xx+1 +do while pr <= rl + if sl < xx then do + do w = 1 to ub + if memb.w then do + n = w+sl + do while n <= nl + memb.n = 1; n = n+sl + end + end + end + sl = nl + end + do i = 1 to ub + mcpy.i = memb.i + end + np = 5 + do i = 1 to ub + if mcpy.i then do + if np = 5 then + if i > pr then + np = i + n = pr*i + if n > xx then + leave i + memb.n = 0 + end + end + if np < pr then + leave + nn = nn+1 + prim.nn = pr + if pr = 2 then + pr = 3 + else + pr = np + nl = Min(sl*pr,xx) +end +nwpr. = 0 +do i = 2 to ub + if memb.i then + nwpr.i = i +end +nn = 0 +do i = 1 to 1000 + if prim.i > 0 then do + if yy then + call Charout ,prim.i' ' + nn = nn+1 + end +end +do i = 1 to ub + if nwpr.i > 0 then do + if yy then + call Charout ,i' ' + nn = nn+1 + end +end +if yy then + say +say nn 'found' +return nn + +Eratosthenes: +procedure +arg xx +say 'Primes up to' xx 'by Eratosthenes...' +say Primes(xx) 'found' +return + +include Math diff --git a/Task/Sieve-of-Pritchard/Rebol/sieve-of-pritchard.rebol b/Task/Sieve-of-Pritchard/Rebol/sieve-of-pritchard.rebol new file mode 100644 index 0000000000..da81f7aef4 --- /dev/null +++ b/Task/Sieve-of-Pritchard/Rebol/sieve-of-pritchard.rebol @@ -0,0 +1,71 @@ +Rebol [ + title: "Rosetta code: Sieve of Pritchard" + file: %Sieve_of_Pritchard.r3 + url: https://rosettacode.org/wiki/Sieve_of_Pritchard + note: "Translated from Python which was translated from Julia" +] + +pritchard: function [ + "Pritchard sieve: finds all primes up to `limit` using a wheel-based sieve." + limit [integer!] +][ + primes: copy [] ;; Accumulates primes found so far (before final sweep) + steplength: 1 ;; Current length/period of the wheel + prime: 2 ;; Current prime being used to cull the wheel + nlimit: 2 ;; Current upper bound of active wheel members + rtlim: to integer! square-root limit ;; Only need primes up to sqrt(limit) + + ;; Use a bitset as a memory-efficient boolean membership array. + ;; Index i is true if i is currently in the "wheel" (candidate set). + members: make bitset! limit + 1 + members/1: true ;; The wheel always starts with 1 as a member + + ;; Main loop: extend the wheel and cull composites for each prime <= sqrt(limit) + while [prime <= rtlim][ + ;; --- Phase 1: Extend the wheel up to nlimit --- + ;; If the wheel hasn't yet reached the limit, grow it by repeating + ;; its current members shifted by multiples of steplength. + if steplength < limit [ + for w 1 limit 1 [ + if members/:w [ ;; For each current wheel member w... + n: w + steplength + while [n <= nlimit][ + members/:n: true ;; ...add w + k*steplength to the wheel + n: n + steplength + ] + ] + ] + steplength: nlimit ;; The wheel period is now nlimit + ] + ;; --- Phase 2: Cull multiples of `prime` from the wheel --- + ;; Snapshot the wheel before culling so we iterate a stable set. + np: 5 ;; Sentinel: will hold the next prime candidate after `prime` + mcpy: copy members + for w 1 limit 1 [ + if mcpy/:w [ ;; For each member w in the snapshot... + if all [np = 5 w > prime][np: w] ;; Track the first member > prime as next prime + n: prime * w ;; prime * w is composite, remove it + if n > nlimit [break] ;; Multiples beyond nlimit can't be members + members/:n: false ;; Cull the composite from the live wheel + ] + ] + ;; If no next-prime candidate was found beyond `prime`, we're done early + if np < prime [break] + ;; Commit current prime to the results list + append primes prime + ;; Advance to the next prime: + ;; 2's successor in the wheel is always 3 otherwise use the tracked candidate + prime: either prime = 2 [3][np] + nlimit: min (steplength * prime) limit ;; Extend wheel up to next prime's reach + ] + ;; --- Final sweep: collect all remaining wheel members as primes --- + ;; Any member still in the wheel at index >= 2 is prime. + for i 2 limit 1 [ + if members/:i [append primes i] + ] + ;; Return sorted + sort primes +] + +print pritchard 150 +print rejoin ["Number of primes up to 1'000'000: " length? pritchard 1'000'000] diff --git a/Task/Sieve-of-Pritchard/V-(Vlang)/sieve-of-pritchard.v b/Task/Sieve-of-Pritchard/V-(Vlang)/sieve-of-pritchard.v new file mode 100644 index 0000000000..d0755b2055 --- /dev/null +++ b/Task/Sieve-of-Pritchard/V-(Vlang)/sieve-of-pritchard.v @@ -0,0 +1,75 @@ +import math + +struct SievePritchard { + mut: + members []bool + primes []int + limit int + steplength int + add_cnt int + rem_cnt int +} + +fn (mut sp SievePritchard) pritchard(verbose bool) []int { + sp.primes = []int{} + sp.members = []bool{len: sp.limit + 1, cap: sp.limit + 1} + sp.members[1] = true + sp.steplength = 1 // wheel size + sp.add_cnt, sp.rem_cnt = 2, 1 + rtlim := int(math.sqrt(f64(sp.limit))) + mut prime, mut np, mut nir := 2, 0, 0 + mut nlimit := prime * sp.steplength // wheel limit + mut newprimes := []int{} + for prime < rtlim { + if sp.steplength < sp.limit { + for wir := 1; wir <= sp.steplength; wir++ { + if sp.members[wir] { + nir = wir + sp.steplength + for nir <= nlimit { + sp.members[nir] = true + sp.add_cnt++ + nir += sp.steplength + } + } + } + sp.steplength = nlimit // advance wheel size + } + np = 5 + mcopy := sp.members.clone() + for wir := 1; wir <= nlimit; wir++ { + if mcopy[wir] { + if np == 5 && wir > prime { np = wir } + nir = prime * wir + if nir > nlimit { break } + sp.rem_cnt++ + sp.members[nir] = false + } + } + if np < prime { break } + sp.primes << prime + if prime == 2 { prime = 3 } else { prime = np } + nlimit = sp.steplength * prime // advance wheel limit + if nlimit > sp.limit { nlimit = sp.limit } + } + sp.members[1] = false + newprimes.clear() + for i := 2; i <= sp.limit; i++ { + if sp.members[i] { newprimes << i } + } + if verbose { + print("up to ${sp.limit}, added ${sp.add_cnt}, removed ${sp.rem_cnt}, ") + println("prime count ${sp.primes.len + newprimes.len}") + } + for pal in newprimes { + sp.primes << pal + } + return sp.primes +} + +fn main() { + mut sieve := SievePritchard{limit: 150} + mut sieve_verbose := SievePritchard{limit: 1_000_000} + primes := sieve.pritchard(false) + println(primes) + sieve_verbose.pritchard(true) +} diff --git a/Task/Simple-database/11l/simple-database.11l b/Task/Simple-database/11l/simple-database.11l index a6cda0259c..a0e3d6734a 100644 --- a/Task/Simple-database/11l/simple-database.11l +++ b/Task/Simple-database/11l/simple-database.11l @@ -1,11 +1,4 @@ -T Item - String name, date, category - - F (name, date, category) - .name = name - .date = date - .category = category - +T Item((String name, String date, String category)) F String() R .name‘, ’(.date)‘, ’(.category) diff --git a/Task/Simple-database/C++/simple-database.cpp b/Task/Simple-database/C++/simple-database.cpp new file mode 100644 index 0000000000..cf265ce88b --- /dev/null +++ b/Task/Simple-database/C++/simple-database.cpp @@ -0,0 +1,147 @@ +#include +#include +#include +#include +#include +#include +#include + +const std::string filename = "Contacts.dat"; + +class Contact { +public: + Contact(const std::string& aName, const std::string& aBirth_Date, const std::string& aState, + const std::string& aRelation, const std::string& aEmail) + : name(aName), birth_date(aBirth_Date), state(aState), relation(aRelation), email(aEmail) { } + + std::string get_relation() const { + return relation; + } + + std::string to_string() const { + return name + ", " + birth_date + ", " + state + ", " + relation + ", " + email; + } + + bool operator<(const Contact& other) const { + return birth_date > other.birth_date; + } + +private: + std::string name, birth_date, state, relation, email; +}; + +std::vector contacts = { }; + +Contact parse(std::string entry) { + std::vector parts; + uint64_t position = 0; + while ( ( position = entry.find(", ") ) != std::string::npos ) { + parts.emplace_back(entry.substr(0, position)); + entry.erase(0, position + 2); + } + return Contact(parts[0], parts[1], parts[2], parts[3], entry); +} + +void write_file(const std::string& new_entry) { + std::fstream database(filename, std::ios::out | std::ios::app); + if ( database.is_open() ) { + database << new_entry; + database.close(); + } else { + std::cerr << "Unable to open database '" << filename << "' for writing" << std::endl; + } +} + +// Open the file if it exists, otherwise create a new empty file. +void read_file() { + std::fstream database(filename, std::ios::in | std::ios::app); + if ( database.is_open() ) { + std::string entry; + while ( std::getline(database, entry) ) { + contacts.emplace_back(parse(entry)); + } + database.close(); + } else { + std::cerr << "Unable to open database '" << filename << "' for reading" << std::endl; + } +} + +void add_new_entry() { + std::cout << "Type the new entry, without inverted commas, in the format:" << std::endl; + std::cout << "Name, Birth_Date, State, Relation, Email" << std::endl; + std::string new_entry; + std::cin.ignore(std::numeric_limits::max(), '\n'); // Clear the keyboard buffer + std::getline(std::cin, new_entry); + Contact contact(parse(new_entry)); + contacts.emplace_back(contact); + write_file(new_entry); + std::cout << "The contact \"" << new_entry << "\" has been added to the database" << std::endl; +} + +void show_latest_entry() { + if ( ! contacts.empty() ) { + std::cout << "The latest entry is: " + contacts.back().to_string() << std::endl; + } else { + std::cout << "There are currently no entries in the database" << std::endl; + } +} + +void show_latest_special_entry(const std::string& search) { + int32_t index = contacts.size() - 1; + while ( index >= 0 && contacts[index].get_relation() != search ) { + index--; + } + + if ( index >= 0 ) { + std::cout << "The latest " << search << " entry is " + contacts[index].to_string() << std::endl; + } else { + std::cout << "There are currently no " << search << " entries" << std::endl; + } +} + +void show_latest_friend_entry() { + show_latest_special_entry("Friend"); +} + +void show_latest_family_entry() { + show_latest_special_entry("Family"); +} + +void list_all_entries_by_age() { + if ( ! contacts.empty() ) { + std::vector copy_contacts = contacts; + std::sort(copy_contacts.begin(), copy_contacts.end()); + for ( const Contact& contact : copy_contacts ) { + std::cout << contact.to_string() << std::endl; + } + } else { + std::cout << "There are currently no entries in the database" << std::endl; + } +} + +int main() { + read_file(); + uint32_t choice = 0; + while ( choice != 6 ) { + std::cout << std::endl; + std::cout << " Menu " << std::endl; + std::cout << " 1: Add a new entry" << std::endl; + std::cout << " 2: Show latest entry" << std::endl; + std::cout << " 3: Show latest Friend entry" << std::endl; + std::cout << " 4: Show latest Family entry" << std::endl; + std::cout << " 5: List all entries by age" << std::endl; + std::cout << " 6: Close the program" << std::endl; + std::cout << std::endl; + + std::cin >> choice; + switch ( choice ) { + case 1 : add_new_entry(); break; + case 2 : show_latest_entry(); break; + case 3 : show_latest_friend_entry(); break; + case 4 : show_latest_family_entry(); break; + case 5 : list_all_entries_by_age(); break; + case 6 : std::cout << "Program closed" << std::endl; break; + default : std::cout << "Please enter a number in the range 1..6" << std::endl; break; + } + } +} diff --git a/Task/Simple-database/COBOL/simple-database.cobol b/Task/Simple-database/COBOL/simple-database.cob similarity index 100% rename from Task/Simple-database/COBOL/simple-database.cobol rename to Task/Simple-database/COBOL/simple-database.cob diff --git a/Task/Simple-database/Crystal/simple-database.cr b/Task/Simple-database/Crystal/simple-database.cr new file mode 100644 index 0000000000..aeb0d2feba --- /dev/null +++ b/Task/Simple-database/Crystal/simple-database.cr @@ -0,0 +1,68 @@ +require "json" + +DB = "DATABASE" + +record Entry, timestamp : Time, description : String, category : String do + include JSON::Serializable + def to_s (io) + timestamp.to_s(io, "%F %T") + io << " - " << description + io << " [" << category << "]" if category != "" + end +end + +def load + File.open(DB) do |f| + Array(Entry).from_json f + end +rescue File::NotFoundError + [] of Entry +end + +def save (entries) + File.open(DB, "w") do |f| + entries.to_json f + end +end + +def usage (errmsg = nil) + puts errmsg if errmsg + print <<-EOU +Usage: #{PROGRAM_NAME} COMMAND ARGS... + Commands: + add DESCRIPTION [CATEGORY] - add entry + last - show last entry + lest - show last in each category + list - show all entries +EOU + exit +end + +def check_args (ok) + usage "Invalid number of arguments" unless ok +end + +cmd = ARGV.shift? || usage + +db = load + +if cmd.in?({"help", "h", "-h"}) + usage +elsif cmd.in?({"a", "add", "-a"}) + check_args 1 <= ARGV.size <= 2 + db << Entry.new Time.local, ARGV[0], ARGV[1]? || "" + save db +else + check_args ARGV.size == 0 + if cmd == "last" + puts db[-1]? + elsif cmd == "lest" + db.group_by(&.category).to_a.sort_by!(&.[0]).map {|_, es| es.last}.each do |e| + puts e + end + elsif cmd == "list" + db.each do |e| puts e end + else + usage "Invalid command '#{cmd}'" + end +end diff --git a/Task/Simple-database/Emacs-Lisp/simple-database.l b/Task/Simple-database/Emacs-Lisp/simple-database.el similarity index 100% rename from Task/Simple-database/Emacs-Lisp/simple-database.l rename to Task/Simple-database/Emacs-Lisp/simple-database.el diff --git a/Task/Simple-database/FreeBASIC/simple-database.basic b/Task/Simple-database/FreeBASIC/simple-database.basic new file mode 100644 index 0000000000..f8935060a8 --- /dev/null +++ b/Task/Simple-database/FreeBASIC/simple-database.basic @@ -0,0 +1,191 @@ +Const filename = "contacts.dat" + +Type Contact + nombre As String + cumpleano As String + ciudad As String + relacion As String + email As String + + Declare Constructor () + Declare Constructor (Byref aNombre As String, Byref aCumpleano As String, Byref aCiudad As String, Byref aRelacion As String, Byref aEmail As String) + Declare Function obtenerRelacion() As String + Declare Function toString() As String +End Type + +Constructor Contact () +nombre = "" +cumpleano = "" +ciudad = "" +relacion = "" +email = "" +End Constructor + +Constructor Contact (Byref aNombre As String, Byref aCumpleano As String, Byref aCiudad As String, Byref aRelacion As String, Byref aEmail As String) +nombre = aNombre +cumpleano = aCumpleano +ciudad = aCiudad +relacion = aRelacion +email = aEmail +End Constructor + +Function Contact.obtenerRelacion() As String + Return relacion +End Function + +Function Contact.toString() As String + Return nombre & ", " & cumpleano & ", " & ciudad & ", " & relacion & ", " & email +End Function + +Dim Shared As Contact contactos() +Dim Shared As Integer numContactos = 0 + +Function Parse(Byref entry As String) As Contact + Dim As String parts(4) + Dim As Integer position = 0, index = 0 + + While ((position = Instr(entry, ", ")) <> 0 And index < 4) + parts(index) = Left(entry, position - 1) + entry = Mid(entry, position + 2) + index += 1 + Wend + parts(index) = entry + + Return Contact(parts(0), parts(1), parts(2), parts(3), parts(4)) +End Function + +Sub escribeFichero(Byref newEntry As String) + Dim As Integer file = Freefile + If Open(filename For Append As #file) = 0 Then + Print #file, newEntry + Close #file + Else + Print "Unable to open database '" & filename & "' for writing" + End If +End Sub + +Sub leeFichero() + Dim As Integer file = Freefile + If Open(filename For Input As #file) <> 0 Then + Print "The file '" & filename & "' does not exist. Do you want to create it? (y/n)" + Dim As String response + Input response + If Lcase(response) = "y" Then + If Open(filename For Output As #file) = 0 Then + Print "File '" & filename & "' created successfully." + Close #file + Cls + Else + Print "Unable to create the file '" & filename & "'." + End If + Else + Print "File not created." + End If + Else + Dim As String entry + While Eof(file) = 0 + Line Input #file, entry + numContactos += 1 + Redim Preserve contactos(numContactos) + contactos(numContactos - 1) = Parse(entry) + Wend + Close #file + End If +End Sub + +Sub anadirNuevaEntrada() + Print "Type the new entry, without inverted commas, in the format:" + Print "Name, Birth_Date, State, Relation, Email" + Dim As String newEntry + Line Input newEntry + Dim As Contact contacto = Parse(newEntry) + numContactos += 1 + Redim Preserve contactos(numContactos) + contactos(numContactos - 1) = contacto + escribeFichero(newEntry) + + Print "The contact '" & newEntry & "' has been added to the database" +End Sub + +Sub mostrarUltimaEntrada() + If numContactos > 0 Then + Print "The latest entry is: " & contactos(numContactos - 1).toString() + Else + Print "There are currently no entries in the database" + End If +End Sub + +Sub mostrarUltimaEntradaEspecial(Byref search As String) + Dim As Integer index = numContactos - 1 + While (index >= 0 And contactos(index).obtenerRelacion() <> search) + index -= 1 + Wend + + If index >= 0 Then + Print "The latest " & search & " entry is " & contactos(index).toString() + Else + Print "There are currently no " & search & " entries" + End If +End Sub + +Sub showLatestFriendEntry() + mostrarUltimaEntradaEspecial("Friend") +End Sub + +Sub showLatestFamilyEntry() + mostrarUltimaEntradaEspecial("Family") +End Sub + +Sub ListarTodasEntradasXEdad() + '? numContactos + Dim As Integer i, j + If numContactos > 0 Then + Dim As Contact copiaContactos(numContactos - 1) + For i = 0 To numContactos - 1 + copiaContactos(i) = contactos(i) + Next + + For i = 0 To numContactos - 2 + For j = i + 1 To numContactos - 1 + If copiaContactos(j).cumpleano > copiaContactos(i).cumpleano Then + Swap copiaContactos(i), copiaContactos(j) + End If + Next + Next + + For i = 0 To numContactos - 1 + Print copiaContactos(i).toString() + Next + Else + Print "There are currently no entries in the database" + End If +End Sub + +Sub Main() + leeFichero() + Dim As Integer opc = 0 + While opc <> 6 + Print !"\n Menu " + Print " 1: Add a new entry" + Print " 2: Show latest entry" + Print " 3: Show latest Friend entry" + Print " 4: Show latest Family entry" + Print " 5: List all entries by age" + Print !" 6: Close the program \n" + + Input "> ", opc + Select Case opc + Case 1 : anadirNuevaEntrada() + Case 2 : mostrarUltimaEntrada() + Case 3 : showLatestFriendEntry() + Case 4 : showLatestFamilyEntry() + Case 5 : ListarTodasEntradasXEdad() + Case 6 : Print !"\nProgram closed" + Case Else : Print !"\nPlease enter a number in the range 1..6" + End Select + Wend +End Sub + +Main() + +Sleep diff --git a/Task/Simple-database/Julia/simple-database.julia b/Task/Simple-database/Julia/simple-database.jl similarity index 100% rename from Task/Simple-database/Julia/simple-database.julia rename to Task/Simple-database/Julia/simple-database.jl diff --git a/Task/Simple-database/Kotlin/simple-database.kotlin b/Task/Simple-database/Kotlin/simple-database.kts similarity index 100% rename from Task/Simple-database/Kotlin/simple-database.kotlin rename to Task/Simple-database/Kotlin/simple-database.kts diff --git a/Task/Simple-database/M2000-Interpreter/simple-database.m2000 b/Task/Simple-database/M2000-Interpreter/simple-database.m2000 index 83545002c0..e15cd7a54e 100644 --- a/Task/Simple-database/M2000-Interpreter/simple-database.m2000 +++ b/Task/Simple-database/M2000-Interpreter/simple-database.m2000 @@ -124,7 +124,7 @@ if ret=0 then beep: exit if not islet then try { open "tool.bat" for output as #f - print #f, {@}+appdir$+{m2000.exe data {%*}: dir %cd%:load tool + print #f, {@}+shortdir$(appdir$)+{m2000.exe data {%*}: dir %cd%:load tool } close #f } diff --git a/Task/Simple-database/PowerShell/simple-database-1.psh b/Task/Simple-database/PowerShell/simple-database-1.ps1 similarity index 100% rename from Task/Simple-database/PowerShell/simple-database-1.psh rename to Task/Simple-database/PowerShell/simple-database-1.ps1 diff --git a/Task/Simple-database/PowerShell/simple-database-2.psh b/Task/Simple-database/PowerShell/simple-database-2.ps1 similarity index 100% rename from Task/Simple-database/PowerShell/simple-database-2.psh rename to Task/Simple-database/PowerShell/simple-database-2.ps1 diff --git a/Task/Simple-database/PowerShell/simple-database-3.psh b/Task/Simple-database/PowerShell/simple-database-3.ps1 similarity index 100% rename from Task/Simple-database/PowerShell/simple-database-3.psh rename to Task/Simple-database/PowerShell/simple-database-3.ps1 diff --git a/Task/Simple-database/PowerShell/simple-database-4.psh b/Task/Simple-database/PowerShell/simple-database-4.ps1 similarity index 100% rename from Task/Simple-database/PowerShell/simple-database-4.psh rename to Task/Simple-database/PowerShell/simple-database-4.ps1 diff --git a/Task/Simple-database/PowerShell/simple-database-5.psh b/Task/Simple-database/PowerShell/simple-database-5.ps1 similarity index 100% rename from Task/Simple-database/PowerShell/simple-database-5.psh rename to Task/Simple-database/PowerShell/simple-database-5.ps1 diff --git a/Task/Simple-database/REBOL/simple-database.rebol b/Task/Simple-database/Rebol/simple-database.rebol similarity index 93% rename from Task/Simple-database/REBOL/simple-database.rebol rename to Task/Simple-database/Rebol/simple-database.rebol index 5b93c7b416..296ccc97fe 100644 --- a/Task/Simple-database/REBOL/simple-database.rebol +++ b/Task/Simple-database/Rebol/simple-database.rebol @@ -1,4 +1,4 @@ -rebol [author: "Nick Antonaccio"] +Rebol [author: "Nick Antonaccio"] write/append %rdb "" db: load %rdb switch system/options/args/1 [ "new" [write/append %rdb rejoin [now " " mold/only next system/options/args newline]] diff --git a/Task/Simple-turtle-graphics/Ada/simple-turtle-graphics.ada b/Task/Simple-turtle-graphics/Ada/simple-turtle-graphics.adb similarity index 100% rename from Task/Simple-turtle-graphics/Ada/simple-turtle-graphics.ada rename to Task/Simple-turtle-graphics/Ada/simple-turtle-graphics.adb diff --git a/Task/Simple-turtle-graphics/EasyLang/simple-turtle-graphics.easy b/Task/Simple-turtle-graphics/EasyLang/simple-turtle-graphics.easy index ad6606a423..de013a6882 100644 --- a/Task/Simple-turtle-graphics/EasyLang/simple-turtle-graphics.easy +++ b/Task/Simple-turtle-graphics/EasyLang/simple-turtle-graphics.easy @@ -3,25 +3,23 @@ subr home x = 50 y = 50 down = 0 - move x y + gpenup + glineto x y . home # -proc forward n . . +proc forward n . x += cos deg * n y += sin deg * n - if down = 1 - line x y - else - move x y - . - sleep 0.1 + if down = 0 : gpenup + glineto x y + sleep 0.05 . -proc turn a . . +proc turn a . deg -= a . # -proc house . . +proc house . turn 180 forward 45 turn 180 @@ -43,7 +41,7 @@ proc house . . . house # -proc bar a[] . . +proc bar a[] . turn 90 forward 30 turn -90 diff --git a/Task/Simple-turtle-graphics/Go/simple-turtle-graphics.go b/Task/Simple-turtle-graphics/Go/simple-turtle-graphics.go new file mode 100644 index 0000000000..7908e60aea --- /dev/null +++ b/Task/Simple-turtle-graphics/Go/simple-turtle-graphics.go @@ -0,0 +1,170 @@ +package main + +import ( + "math" + "slices" + + rl "github.com/gen2brain/raylib-go/raylib" +) + +const ( + WIDTH = 800 + HEIGHT = 600 +) + +type Turtle struct { + angle int + X int + Y int + isPenDown bool + penColor rl.Color +} + +func deg2Rad(degrees int) float64 { + return float64(degrees) * math.Pi / 180 +} + +func (self *Turtle) Right(angle int) { + self.angle = (self.angle + angle) % 360 +} + +func (self *Turtle) Left(angle int) { + self.angle = (self.angle - angle) % 360 +} + +func (self *Turtle) SetPenColor(color rl.Color) { + self.penColor = color +} + +func (self *Turtle) PenUp() { + self.isPenDown = false +} + +func (self *Turtle) PenDown() { + self.isPenDown = true +} + +func (self *Turtle) line(x0, y0, x1, y1 int) { + dx := x1 - x0 + if dx < 0 { + dx = -dx + } + dy := y1 - y0 + if dy < 0 { + dy = -dy + } + var sx, sy int + if x0 < x1 { + sx = 1 + } else { + sx = -1 + } + if y0 < y1 { + sy = 1 + } else { + sy = -1 + } + err := dx - dy + + for { + rl.DrawPixel(int32(x0), int32(y0), self.penColor) + if x0 == x1 && y0 == y1 { + break + } + e2 := 2 * err + if e2 > -dy { + err -= dy + x0 += sx + } + if e2 < dx { + err += dx + y0 += sy + } + } +} +func (self *Turtle) Forward(length int) { + endX := self.X - int(math.Round(float64(-length)*math.Cos(deg2Rad(self.angle)))) + endY := self.Y - int(math.Round(float64(-length)*math.Sin(deg2Rad(self.angle)))) + + if self.isPenDown { + self.line(self.X, self.Y, endX, endY) + } + + self.X = endX + self.Y = endY +} + +func (self *Turtle) Backward(length int) { + self.Forward(-length) +} + +func triangle(turtle *Turtle, size int) { + for range 3 { + turtle.Forward(size) + turtle.Right(120) + } +} + +func rectangle(turtle *Turtle, w int, h int) { + for range 2 { + turtle.Forward(h) + turtle.Left(90) + turtle.Forward(w) + turtle.Left(90) + } +} + +func square(turtle *Turtle, size int) { + rectangle(turtle, size, size) +} + +func house(turtle *Turtle, size int) { + turtle.Right(180) + square(turtle, size) + triangle(turtle, size) + turtle.Right(180) +} + +func barchart(turtle *Turtle, items []float64, size int) { + scale := float64(size) / slices.Max(items) + width := size / len(items) + + for _, i := range items { + rectangle(turtle, int(i*scale), width) + turtle.PenUp() + turtle.Forward(width) + turtle.PenDown() + } + + turtle.PenUp() + turtle.Backward(size) + turtle.PenDown() +} + +func main() { + rl.InitWindow(WIDTH, HEIGHT, "Turtle") + defer rl.CloseWindow() + + rl.SetTargetFPS(60) + + for !rl.WindowShouldClose() { + rl.ClearBackground(rl.Black) + rl.BeginDrawing() + + turtle := Turtle{angle: 0, X: WIDTH / 2, Y: HEIGHT / 2, isPenDown: true} + turtle.SetPenColor(rl.White) + + house(&turtle, 150) + + turtle.PenUp() + turtle.Forward(10) + turtle.PenDown() + + barchart(&turtle, []float64{0.5, (1.0 / 3.0), 2.0, 1.3, 0.5}, 200) + + turtle.PenUp() + turtle.Backward(10) + + rl.EndDrawing() + } +} diff --git a/Task/Simple-turtle-graphics/Julia/simple-turtle-graphics.julia b/Task/Simple-turtle-graphics/Julia/simple-turtle-graphics.jl similarity index 100% rename from Task/Simple-turtle-graphics/Julia/simple-turtle-graphics.julia rename to Task/Simple-turtle-graphics/Julia/simple-turtle-graphics.jl diff --git a/Task/Simple-turtle-graphics/M2000-Interpreter/simple-turtle-graphics.m2000 b/Task/Simple-turtle-graphics/M2000-Interpreter/simple-turtle-graphics.m2000 new file mode 100644 index 0000000000..54894fe000 --- /dev/null +++ b/Task/Simple-turtle-graphics/M2000-Interpreter/simple-turtle-graphics.m2000 @@ -0,0 +1,69 @@ +Module TurtleGraphics { + cls 15,0 + pen 0 + single penangle=pi + boolean pendraw=true + hlen=min.data(scale.x, scale.y)/4 + move scale.x/4, scale.y/2 + house(hlen) + penup() + forward(hlen) + pendown() + d=(50, 33, 200, 130, 50) + items=len(d) + dspan=d#max() + ratio=scale.y/4/dspan + ditem=each(d) + while ditem + barvalue(scale.x/4, scale.y/3 ,items, ditem^, array(ditem)/dspan) + end while + + sub house(n) + for i=1 to 3 + right(120) + forward(n) + next + right(90) + bar(n, n) + right(90) + end sub + sub bar(w, h) + local i + for i=1 to 2 + right(90) + forward(h) + right(90) + forward(w) + next + end sub + sub barvalue(maxW, maxH, bars, barno, valratio) + local bW=maxW/bars + forward(bw) + bar(bw, -maxH*valratio) + end sub + // Turtle Minimum Pack + // need: + // single penangle=pi + // boolean pendraw=true + // + sub penup() + pendraw=false + end sub + sub pendown() + pendraw=true + end sub + sub forward(distance) + if pendraw then + draw angle penangle, distance + else + step angle penangle, distance + end if + end sub + sub backward(distance) + forward(-distance) + end sub + sub right(angle) + penangle-=angle/180*pi + end sub +} +TurtleGraphics diff --git a/Task/Simple-turtle-graphics/Pluto/simple-turtle-graphics.pluto b/Task/Simple-turtle-graphics/Pluto/simple-turtle-graphics.pluto new file mode 100644 index 0000000000..be83092bb1 --- /dev/null +++ b/Task/Simple-turtle-graphics/Pluto/simple-turtle-graphics.pluto @@ -0,0 +1,69 @@ +require "bitmap" + +local w = 600 +local h = 600 +local bmp = bitmap.of(w, h, color.white, "Simple_turtle_graphics") +local t = turtle.of(bmp) + +local function drawhouse(size) + -- Save initial turtle position and direction. + local saveX = t.x + local saveY = t.y + local saveD = t.dir + + t.pen.width = 2 + + -- Draw house. + t:rect(w // 4, h // 2, size, size) + + -- Draw roof. + t:right(30) + t:walk(size) + t:right(120) + t:walk(size) + + -- Draw door. + local doorWidth = size // 4 + local doorHeight = size // 2 + t:rect(w // 4 + doorWidth // 2, h // 2 + doorHeight, doorWidth, doorHeight) + + -- Draw window + local windWidth = size // 3 + local windHeight = size // 4 + t:rect(w // 4 + size // 2, h // 2 + size // 2, windWidth, windHeight) + + -- Restore initial turtle position and direction. + t.x = saveX + t.y = saveY + t.dir = saveD +end + +-- 'nums' assumed to be all non-negative. +local function barChart(nums, size) + -- Save intial turtle position and direction. + local saveX = t.x + local saveY = t.y + local saveD = t.dir + + -- Find maximum. + local max = nums:max() + + -- Scale to fit within a square with sides 'size' and draw chart. + local barWidth = size // #nums + local startX = w // 2 + 20 + local startY = h // 2 + for i = 1, #nums do + local barHeight = math.round(nums[i] * size / max) + t:rect(startX, startY - barHeight, barWidth, barHeight) + startX += barWidth + end + + -- restore intial turtle position and direction + t.x = saveX + t.y = saveY + t.dir = saveD +end + +drawhouse(w // 4) +barChart({15, 10, 50, 35, 20}, w // 3) +bmp:view() diff --git a/Task/Simple-turtle-graphics/Raku/simple-turtle-graphics.raku b/Task/Simple-turtle-graphics/Raku/simple-turtle-graphics.raku new file mode 100644 index 0000000000..ad265e38df --- /dev/null +++ b/Task/Simple-turtle-graphics/Raku/simple-turtle-graphics.raku @@ -0,0 +1,54 @@ +# 20250303 Raku programming solution + +use Cairo; + +sub house(Cairo::Context $cr, $x, $y, $size) { + $cr.save; + $cr.rgb(1.0, 1.0, 1.0); + + $cr.rectangle($x, $y, $size, $size); + $cr.stroke; + + $cr.move_to($x + $size / 2, $y - $size / 2); + $cr.line_to($x, $y); + $cr.line_to($x + $size, $y); + $cr.close_path; + $cr.stroke; + + $cr.restore; +} + +sub barchart(Cairo::Context $cr, @data, $x is copy, $y, $size) { + $cr.save; + $cr.rgb(1.0, 1.0, 1.0); + + my $maxdata = @data.max || 1; + my $bar-width = $size / (@data.elems || 1); + my $bar-spacing = $bar-width * 0.1; + + for @data -> $n { + my $bar-height = ($n / $maxdata) * $size; + $cr.rectangle($x, $y - $bar-height, $bar-width - $bar-spacing, $bar-height); + $cr.stroke; + $x += $bar-width; + } + + $cr.restore; +} + +sub testturtle($width = 400, $height = 600) { + my $image = Cairo::Image.create(Cairo::FORMAT_ARGB32, $width, $height); + my $cr = Cairo::Context.new($image); + + $cr.rgb(0.0, 0.0, 0.0); + $cr.paint; + + $cr.line_width = 2.0; + + barchart($cr, [15, 10, 50, 35, 20], $width * 0.6, $height, $width / 3); + house($cr, $width / 4, $height / 3, $width / 3); + + $image.write_png('turtle-raku.png'); +} + +testturtle(); diff --git a/Task/Simple-windowed-application/Ada/simple-windowed-application.ada b/Task/Simple-windowed-application/Ada/simple-windowed-application.adb similarity index 100% rename from Task/Simple-windowed-application/Ada/simple-windowed-application.ada rename to Task/Simple-windowed-application/Ada/simple-windowed-application.adb diff --git a/Task/Simple-windowed-application/AutoIt/simple-windowed-application.autoit b/Task/Simple-windowed-application/AutoIt/simple-windowed-application.au3 similarity index 100% rename from Task/Simple-windowed-application/AutoIt/simple-windowed-application.autoit rename to Task/Simple-windowed-application/AutoIt/simple-windowed-application.au3 diff --git a/Task/Simple-windowed-application/Batch-File/simple-windowed-application.bat b/Task/Simple-windowed-application/Batch-File/simple-windowed-application.bat new file mode 100644 index 0000000000..3f2fe51f58 --- /dev/null +++ b/Task/Simple-windowed-application/Batch-File/simple-windowed-application.bat @@ -0,0 +1,6 @@ + +... diff --git a/Task/Simple-windowed-application/Delphi/simple-windowed-application.delphi b/Task/Simple-windowed-application/Delphi/simple-windowed-application.pas similarity index 100% rename from Task/Simple-windowed-application/Delphi/simple-windowed-application.delphi rename to Task/Simple-windowed-application/Delphi/simple-windowed-application.pas diff --git a/Task/Simple-windowed-application/Euphoria/simple-windowed-application.euphoria b/Task/Simple-windowed-application/Euphoria/simple-windowed-application.eu similarity index 100% rename from Task/Simple-windowed-application/Euphoria/simple-windowed-application.euphoria rename to Task/Simple-windowed-application/Euphoria/simple-windowed-application.eu diff --git a/Task/Simple-windowed-application/Forth/simple-windowed-application-4.fth b/Task/Simple-windowed-application/Forth/simple-windowed-application-4.fth index 9fca6cb3fb..347b3b67bd 100644 --- a/Task/Simple-windowed-application/Forth/simple-windowed-application-4.fth +++ b/Task/Simple-windowed-application/Forth/simple-windowed-application-4.fth @@ -13,7 +13,7 @@ TextView' t \ the running count is always on the stack \ so a variable for that is not needed -:noname +:noname ( count -- count+1 ) 1+ \ increment the count " Number of clicks: " put: t dup deciNumstr insert: t ; setAction: b \ update the text representation of count diff --git a/Task/Simple-windowed-application/FuncSug/simple-windowed-application.funcsug b/Task/Simple-windowed-application/FuncSug/simple-windowed-application.funcsug new file mode 100644 index 0000000000..b6c51287b0 --- /dev/null +++ b/Task/Simple-windowed-application/FuncSug/simple-windowed-application.funcsug @@ -0,0 +1,7 @@ +var message := displayNewMessage('There have been no clicks yet') +var button := displayNewElementIn('click me', 'body', 'button', true) +var count := 0 +while true: + awaitClickBeep(button) + count += 1 + displayMessageIn(count, message) diff --git a/Task/Simple-windowed-application/JavaScript/simple-windowed-application.js b/Task/Simple-windowed-application/JavaScript/simple-windowed-application-1.js similarity index 100% rename from Task/Simple-windowed-application/JavaScript/simple-windowed-application.js rename to Task/Simple-windowed-application/JavaScript/simple-windowed-application-1.js diff --git a/Task/Simple-windowed-application/JavaScript/simple-windowed-application-2.js b/Task/Simple-windowed-application/JavaScript/simple-windowed-application-2.js new file mode 100644 index 0000000000..29df8bcc16 --- /dev/null +++ b/Task/Simple-windowed-application/JavaScript/simple-windowed-application-2.js @@ -0,0 +1 @@ +WScript.CreateObject("Shell.Application").ShellExecute("mshta", "\"about:Simple windowed application

    There have been no clicks yet

    \""); diff --git a/Task/Simple-windowed-application/Julia/simple-windowed-application.julia b/Task/Simple-windowed-application/Julia/simple-windowed-application.jl similarity index 100% rename from Task/Simple-windowed-application/Julia/simple-windowed-application.julia rename to Task/Simple-windowed-application/Julia/simple-windowed-application.jl diff --git a/Task/Simple-windowed-application/Kotlin/simple-windowed-application-1.kotlin b/Task/Simple-windowed-application/Kotlin/simple-windowed-application-1.kts similarity index 100% rename from Task/Simple-windowed-application/Kotlin/simple-windowed-application-1.kotlin rename to Task/Simple-windowed-application/Kotlin/simple-windowed-application-1.kts diff --git a/Task/Simple-windowed-application/Kotlin/simple-windowed-application-2.kotlin b/Task/Simple-windowed-application/Kotlin/simple-windowed-application-2.kts similarity index 100% rename from Task/Simple-windowed-application/Kotlin/simple-windowed-application-2.kotlin rename to Task/Simple-windowed-application/Kotlin/simple-windowed-application-2.kts diff --git a/Task/Simple-windowed-application/Microsoft-Small-Basic/simple-windowed-application.basic b/Task/Simple-windowed-application/Microsoft-Small-Basic/simple-windowed-application.basic new file mode 100644 index 0000000000..47f3b4c2f4 --- /dev/null +++ b/Task/Simple-windowed-application/Microsoft-Small-Basic/simple-windowed-application.basic @@ -0,0 +1,22 @@ +GraphicsWindow.Width = 180 +GraphicsWindow.Height = 80 +' Make it look like a native Windows application +GraphicsWindow.BackgroundColor = "#F0F0F0" +GraphicsWindow.BrushColor = "#000000" +GraphicsWindow.FontName = "Segoe UI" +GraphicsWindow.FontBold = 0 + +GraphicsWindow.DrawText(10, 10, "There have been no clicks yet") +Controls.AddButton("click me", 65, 40) +Controls.ButtonClicked = CountClick + +Sub CountClick + clicks = clicks + 1 + GraphicsWindow.Clear() + If clicks = 1 Then + GraphicsWindow.DrawText(10, 10, "There has been 1 click") + Else + GraphicsWindow.DrawText(10, 10, "There have been " + clicks + " clicks") + EndIf + Controls.AddButton("click me", 65, 40) +EndSub diff --git a/Task/Simple-windowed-application/OCaml/simple-windowed-application-1.ocaml b/Task/Simple-windowed-application/OCaml/simple-windowed-application-1.ml similarity index 100% rename from Task/Simple-windowed-application/OCaml/simple-windowed-application-1.ocaml rename to Task/Simple-windowed-application/OCaml/simple-windowed-application-1.ml diff --git a/Task/Simple-windowed-application/OCaml/simple-windowed-application-2.ocaml b/Task/Simple-windowed-application/OCaml/simple-windowed-application-2.ml similarity index 100% rename from Task/Simple-windowed-application/OCaml/simple-windowed-application-2.ocaml rename to Task/Simple-windowed-application/OCaml/simple-windowed-application-2.ml diff --git a/Task/Simple-windowed-application/PascalABC.NET/simple-windowed-application.pas b/Task/Simple-windowed-application/PascalABC.NET/simple-windowed-application.pas new file mode 100644 index 0000000000..7767cd8186 --- /dev/null +++ b/Task/Simple-windowed-application/PascalABC.NET/simple-windowed-application.pas @@ -0,0 +1,13 @@ +uses WPF; + +begin + var mainpanel := Panels.StackPanel(200).AsMainContent; + var b := CreateButton('Click me!'); + var lb := CreateLabel('0'); + mainpanel.AddElements(b,lb); + var clicks := 0; + b.Click += (o,e) -> begin + clicks += 1; + lb.Content := clicks; + end; +end. diff --git a/Task/Simple-windowed-application/PowerShell/simple-windowed-application-1.psh b/Task/Simple-windowed-application/PowerShell/simple-windowed-application-1.ps1 similarity index 100% rename from Task/Simple-windowed-application/PowerShell/simple-windowed-application-1.psh rename to Task/Simple-windowed-application/PowerShell/simple-windowed-application-1.ps1 diff --git a/Task/Simple-windowed-application/PowerShell/simple-windowed-application-2.psh b/Task/Simple-windowed-application/PowerShell/simple-windowed-application-2.ps1 similarity index 100% rename from Task/Simple-windowed-application/PowerShell/simple-windowed-application-2.psh rename to Task/Simple-windowed-application/PowerShell/simple-windowed-application-2.ps1 diff --git a/Task/Simple-windowed-application/PowerShell/simple-windowed-application-3.psh b/Task/Simple-windowed-application/PowerShell/simple-windowed-application-3.ps1 similarity index 100% rename from Task/Simple-windowed-application/PowerShell/simple-windowed-application-3.psh rename to Task/Simple-windowed-application/PowerShell/simple-windowed-application-3.ps1 diff --git a/Task/Simple-windowed-application/REBOL/simple-windowed-application.rebol b/Task/Simple-windowed-application/Rebol/simple-windowed-application.rebol similarity index 98% rename from Task/Simple-windowed-application/REBOL/simple-windowed-application.rebol rename to Task/Simple-windowed-application/Rebol/simple-windowed-application.rebol index f1d5c8440d..f73c8bc7b2 100644 --- a/Task/Simple-windowed-application/REBOL/simple-windowed-application.rebol +++ b/Task/Simple-windowed-application/Rebol/simple-windowed-application.rebol @@ -1,4 +1,4 @@ -REBOL [ +Rebol [ Title: "Simple Windowed Application" URL: http://rosettacode.org/wiki/Simple_Windowed_Application ] diff --git a/Task/Simple-windowed-application/Rust/simple-windowed-application.rust b/Task/Simple-windowed-application/Rust/simple-windowed-application.rs similarity index 100% rename from Task/Simple-windowed-application/Rust/simple-windowed-application.rust rename to Task/Simple-windowed-application/Rust/simple-windowed-application.rs diff --git a/Task/Simple-windowed-application/TAV/simple-windowed-application.tav b/Task/Simple-windowed-application/TAV/simple-windowed-application.tav new file mode 100644 index 0000000000..ef77361a3e --- /dev/null +++ b/Task/Simple-windowed-application/TAV/simple-windowed-application.tav @@ -0,0 +1,23 @@ +\ the GTK objects can have fields, so no global is needed +click (btn) with (label): + btn.clicked =+ 1 + label::label text "Clicked" __ btn.clicked __ "times." +setup main window: + win =: new GTK window + win::set title "Button Demo" + win::set size 150, 100 + win::connect 'destroy' to `GTK main quit` + box =: new GTK container box 'vertical' spacing 2 + win::add container box + msg =: new GTK widget label "Not yet any click, click the button..." + box::add widget msg + button =: new GTK widget button "Click here" + button.clicked =: 0 + button::connect 'clicked' to `click () with ()` with msg + box::add widget button + win::show all + :>win + +main (args):+ + GTK init args + GTK main setup main window diff --git a/Task/Simple-windowed-application/V-(Vlang)/simple-windowed-application.v b/Task/Simple-windowed-application/V-(Vlang)/simple-windowed-application.v index 2e305ca1a5..438f1a5297 100644 --- a/Task/Simple-windowed-application/V-(Vlang)/simple-windowed-application.v +++ b/Task/Simple-windowed-application/V-(Vlang)/simple-windowed-application.v @@ -1,7 +1,7 @@ import ui import gx -[heap] +@[heap] struct App { mut: window &ui.Window = unsafe {nil} diff --git a/Task/Simple-windowed-application/VBScript/simple-windowed-application.vbs b/Task/Simple-windowed-application/VBScript/simple-windowed-application.vbs new file mode 100644 index 0000000000..b907cfea2d --- /dev/null +++ b/Task/Simple-windowed-application/VBScript/simple-windowed-application.vbs @@ -0,0 +1 @@ +CreateObject("Shell.Application").ShellExecute "mshta", """about:Simple windowed application

    There have been no clicks

    """ diff --git a/Task/Simulate-input-Keyboard/AutoIt/simulate-input-keyboard-1.autoit b/Task/Simulate-input-Keyboard/AutoIt/simulate-input-keyboard-1.au3 similarity index 100% rename from Task/Simulate-input-Keyboard/AutoIt/simulate-input-keyboard-1.autoit rename to Task/Simulate-input-Keyboard/AutoIt/simulate-input-keyboard-1.au3 diff --git a/Task/Simulate-input-Keyboard/AutoIt/simulate-input-keyboard-2.autoit b/Task/Simulate-input-Keyboard/AutoIt/simulate-input-keyboard-2.au3 similarity index 100% rename from Task/Simulate-input-Keyboard/AutoIt/simulate-input-keyboard-2.autoit rename to Task/Simulate-input-Keyboard/AutoIt/simulate-input-keyboard-2.au3 diff --git a/Task/Simulate-input-Keyboard/FreeBASIC/simulate-input-keyboard.basic b/Task/Simulate-input-Keyboard/FreeBASIC/simulate-input-keyboard.basic new file mode 100644 index 0000000000..1ffc77abd0 --- /dev/null +++ b/Task/Simulate-input-Keyboard/FreeBASIC/simulate-input-keyboard.basic @@ -0,0 +1,40 @@ +#include once "windows.bi" + +Dim ki(0 To 7) As INPUT_ + +' A +ki(0).type = INPUT_KEYBOARD +ki(0).ki.wVk = Asc("A") +ki(0).ki.dwFlags = 0 +ki(1).type = INPUT_KEYBOARD +ki(1).ki.wVk = Asc("A") +ki(1).ki.dwFlags = KEYEVENTF_KEYUP + +' B +ki(2).type = INPUT_KEYBOARD +ki(2).ki.wVk = Asc("B") +ki(2).ki.dwFlags = 0 +ki(3).type = INPUT_KEYBOARD +ki(3).ki.wVk = Asc("B") +ki(3).ki.dwFlags = KEYEVENTF_KEYUP + +' C +ki(4).type = INPUT_KEYBOARD +ki(4).ki.wVk = Asc("C") +ki(4).ki.dwFlags = 0 +ki(5).type = INPUT_KEYBOARD +ki(5).ki.wVk = Asc("C") +ki(5).ki.dwFlags = KEYEVENTF_KEYUP + +' ENTER (VK_RETURN = &HD) +ki(6).type = INPUT_KEYBOARD +ki(6).ki.wVk = VK_RETURN +ki(6).ki.dwFlags = 0 +ki(7).type = INPUT_KEYBOARD +ki(7).ki.wVk = VK_RETURN +ki(7).ki.dwFlags = KEYEVENTF_KEYUP + +Print "Make the target window active. Sending keys in 3 seconds..." +Sleep 3000 + +SendInput(Ubound(ki), @ki(0), Len(INPUT_)) diff --git a/Task/Simulate-input-Keyboard/Julia/simulate-input-keyboard.jl b/Task/Simulate-input-Keyboard/Julia/simulate-input-keyboard.jl new file mode 100644 index 0000000000..c6486c39b6 --- /dev/null +++ b/Task/Simulate-input-Keyboard/Julia/simulate-input-keyboard.jl @@ -0,0 +1,85 @@ +using Gtk4 +using Gtk4.GLib + + +""" App to create and initialize the GTK app object and set up the main window """ +mutable struct AppState + target_window::GtkWindow + target_widget::GtkTextView + target_buffer::GtkTextBuffer + function AppState() + window = GtkWindow("Keystroke Target Window") + set_gtk_property!(window, :default_width, 800) + set_gtk_property!(window, :default_height, 800) + set_gtk_property!(window, :resizable, true) + set_gtk_property!(window, :visible, true) + set_gtk_property!(window, :title, "Keystroke Simulation Target") + set_gtk_property!(window, :border_width, 10) + set_gtk_property!(window, :destroy_with_parent, true) + set_gtk_property!(window, :can_focus, true) + buffer = GtkTextBuffer() + set_gtk_property!(buffer, :text, "This is a target text area.\nSimulated keystrokes will appear here.\n\n") + widget = GtkTextView(buffer) + set_gtk_property!(widget, :can_focus, true) + set_gtk_property!(widget, :editable, true) + set_gtk_property!(widget, :cursor_visible, true) + scrolled = GtkScrolledWindow() + scrolled[] = widget + set_gtk_property!(scrolled, :margin_start, 10) + set_gtk_property!(scrolled, :margin_end, 10) + set_gtk_property!(scrolled, :margin_top, 10) + set_gtk_property!(scrolled, :margin_bottom, 10) + window[] = scrolled + show(window) + return new(window, widget, buffer) + end +end + +# the app +const APP = AppState() + +""" Send keystroke or char to a TextView widget using synthetic key events """ +function sendsynthetickey(widget, keychar::Char) + Gtk4.grab_focus(widget) + if isa(widget, GtkTextView) + buf = APP.target_buffer + cursor_iter = Gtk4.G_.get_iter_at_mark(buf, Gtk4.G_.get_insert(buf)) + Gtk4.insert!(buf, Ref(cursor_iter), string(keychar)) + return true + else + println("Widget is not a text view, cannot insert character directly.") + return false + end +end + +""" Send a string of text to the target widget """ +function typetowidget(text::AbstractString; delay = 0.4) + println("Sending text: \"$text\"") + for char in text + sendsynthetickey(APP.target_widget, char) + sleep(delay * rand() * rand()) + end +end + + +# Run a demo +println("Julia Keystroke Simulation with Gtk4.jl") +println("Press Ctrl+C to exit or close the target window.") +println("=======================================") +sleep(2) # Give time to see the window +try + typetowidget("Hello from Gtk4.jl!\n") + sleep(1) + typetowidget("This is a demonstration of simulated human typing input.\n") + typetowidget("Special characters: !@#\$%^&*()\n") + typetowidget("You can close this window to stop the simulation.\n\n") + while get_gtk_property(APP.target_window, :visible, Bool) + typetowidget(string(rand(['a':'z'; collect(" "); '\n']))) + end +catch e + print("Caught exception: $e...") +finally + print("Cleaning up...") + !isnothing(APP.target_window) && close(APP.target_window) + println("Done.") +end diff --git a/Task/Simulate-input-Keyboard/Kotlin/simulate-input-keyboard.kotlin b/Task/Simulate-input-Keyboard/Kotlin/simulate-input-keyboard.kts similarity index 100% rename from Task/Simulate-input-Keyboard/Kotlin/simulate-input-keyboard.kotlin rename to Task/Simulate-input-Keyboard/Kotlin/simulate-input-keyboard.kts diff --git a/Task/Simulate-input-Keyboard/OCaml/simulate-input-keyboard.ocaml b/Task/Simulate-input-Keyboard/OCaml/simulate-input-keyboard.ml similarity index 100% rename from Task/Simulate-input-Keyboard/OCaml/simulate-input-keyboard.ocaml rename to Task/Simulate-input-Keyboard/OCaml/simulate-input-keyboard.ml diff --git a/Task/Simulate-input-Keyboard/PowerShell/simulate-input-keyboard.psh b/Task/Simulate-input-Keyboard/PowerShell/simulate-input-keyboard.ps1 similarity index 100% rename from Task/Simulate-input-Keyboard/PowerShell/simulate-input-keyboard.psh rename to Task/Simulate-input-Keyboard/PowerShell/simulate-input-keyboard.ps1 diff --git a/Task/Simulate-input-Keyboard/Rust/simulate-input-keyboard.rust b/Task/Simulate-input-Keyboard/Rust/simulate-input-keyboard.rs similarity index 100% rename from Task/Simulate-input-Keyboard/Rust/simulate-input-keyboard.rust rename to Task/Simulate-input-Keyboard/Rust/simulate-input-keyboard.rs diff --git a/Task/Simulate-input-Keyboard/VBScript/simulate-input-keyboard.vb b/Task/Simulate-input-Keyboard/VBScript/simulate-input-keyboard.vbs similarity index 100% rename from Task/Simulate-input-Keyboard/VBScript/simulate-input-keyboard.vb rename to Task/Simulate-input-Keyboard/VBScript/simulate-input-keyboard.vbs diff --git a/Task/Simulate-input-Mouse/FuncSug/simulate-input-mouse.funcsug b/Task/Simulate-input-Mouse/FuncSug/simulate-input-mouse.funcsug new file mode 100644 index 0000000000..bc329abada --- /dev/null +++ b/Task/Simulate-input-Mouse/FuncSug/simulate-input-mouse.funcsug @@ -0,0 +1,16 @@ +displayNewMessage("Don't click the button. It will be clicked by the program.") +waitSeconds(2) +displayNewMessage(``) + +parallel(select 1) || +||==================== + awaitClickBeep('#mybutton') +...--- + displayNewMessage('The button has been clicked') +||==================== + waitSeconds(2) + + # Simulate the click of a mouse + generateUserEvent('#mybutton', 'click') +...--- + displayNewMessage("I know you didn't do it!") diff --git a/Task/Simulate-input-Mouse/Julia/simulate-input-mouse.julia b/Task/Simulate-input-Mouse/Julia/simulate-input-mouse.jl similarity index 100% rename from Task/Simulate-input-Mouse/Julia/simulate-input-mouse.julia rename to Task/Simulate-input-Mouse/Julia/simulate-input-mouse.jl diff --git a/Task/Simulate-input-Mouse/Kotlin/simulate-input-mouse.kotlin b/Task/Simulate-input-Mouse/Kotlin/simulate-input-mouse.kts similarity index 100% rename from Task/Simulate-input-Mouse/Kotlin/simulate-input-mouse.kotlin rename to Task/Simulate-input-Mouse/Kotlin/simulate-input-mouse.kts diff --git a/Task/Simulate-input-Mouse/Rust/simulate-input-mouse.rust b/Task/Simulate-input-Mouse/Rust/simulate-input-mouse.rs similarity index 100% rename from Task/Simulate-input-Mouse/Rust/simulate-input-mouse.rust rename to Task/Simulate-input-Mouse/Rust/simulate-input-mouse.rs diff --git a/Task/Singleton/Ada/singleton-1.ada b/Task/Singleton/Ada/singleton-1.adb similarity index 100% rename from Task/Singleton/Ada/singleton-1.ada rename to Task/Singleton/Ada/singleton-1.adb diff --git a/Task/Singleton/Ada/singleton-2.ada b/Task/Singleton/Ada/singleton-2.adb similarity index 100% rename from Task/Singleton/Ada/singleton-2.ada rename to Task/Singleton/Ada/singleton-2.adb diff --git a/Task/Singleton/Ada/singleton-3.ada b/Task/Singleton/Ada/singleton-3.adb similarity index 100% rename from Task/Singleton/Ada/singleton-3.ada rename to Task/Singleton/Ada/singleton-3.adb diff --git a/Task/Singleton/Ada/singleton-4.ada b/Task/Singleton/Ada/singleton-4.adb similarity index 100% rename from Task/Singleton/Ada/singleton-4.ada rename to Task/Singleton/Ada/singleton-4.adb diff --git a/Task/Singleton/Delphi/singleton.delphi b/Task/Singleton/Delphi/singleton.pas similarity index 100% rename from Task/Singleton/Delphi/singleton.delphi rename to Task/Singleton/Delphi/singleton.pas diff --git a/Task/Singleton/EMal/singleton.emal b/Task/Singleton/EMal/singleton.emal index ca04f8507d..f726ff7927 100644 --- a/Task/Singleton/EMal/singleton.emal +++ b/Task/Singleton/EMal/singleton.emal @@ -1,17 +1,17 @@ type Singleton model text greeting - fun speak = void by block do writeLine(me.greeting + " I'm a singleton") end + fun speak ← void by block do writeLine(me.greeting + " I'm a singleton") end end Singleton instance -fun getInstance = Singleton by block - if instance == null do instance = Singleton() end +fun getInstance ← Singleton by block + if instance æ null do instance ← Singleton() end return instance end type SomeOtherType -Singleton s1 = Singleton.getInstance() -s1.greeting = "Hello" -Singleton s2 = Singleton.getInstance() +Singleton s1 ← Singleton.getInstance() +s1.greeting ← "Hello" +Singleton s2 ← Singleton.getInstance() s2.greeting.append(", World!") -writeLine(s1 + " and " + s2 + " are the same object: " + (s1 == s2) + ", s2: " + s2.greeting) +writeLine(s1 + " and " + s2 + " are the same object: " + (s1 æ s2) + ", s2: " + s2.greeting) s1.speak() # call instance method diff --git a/Task/Singleton/Ecstasy/singleton.ecstasy b/Task/Singleton/Ecstasy/singleton.ecstasy new file mode 100644 index 0000000000..4ed6c14010 --- /dev/null +++ b/Task/Singleton/Ecstasy/singleton.ecstasy @@ -0,0 +1,15 @@ +module test { + static service Singleton { + private Int counter; + String fooHasBeenCalled() { + return $"{++counter} times"; + } + } + + void run() { + @Inject Console console; + for (Int i : 1..5) { + console.print($"{Singleton.fooHasBeenCalled()=}"); + } + } +} diff --git a/Task/Singleton/Julia/singleton.julia b/Task/Singleton/Julia/singleton.jl similarity index 100% rename from Task/Singleton/Julia/singleton.julia rename to Task/Singleton/Julia/singleton.jl diff --git a/Task/Singleton/Kotlin/singleton.kotlin b/Task/Singleton/Kotlin/singleton.kts similarity index 100% rename from Task/Singleton/Kotlin/singleton.kotlin rename to Task/Singleton/Kotlin/singleton.kts diff --git a/Task/Singleton/Pluto/singleton-1.pluto b/Task/Singleton/Pluto/singleton-1.pluto new file mode 100644 index 0000000000..147be60993 --- /dev/null +++ b/Task/Singleton/Pluto/singleton-1.pluto @@ -0,0 +1,19 @@ +-- Singleton.pluto -- + +local instance = nil + +class singleton + static function getInstance() + if !instance then new singleton() end + return instance + end + + function __construct() + assert(!instance, "The singleton instance already exists.") + instance = self + end + + function print() + print("Hello, I'm a singleton.") + end +end diff --git a/Task/Singleton/Pluto/singleton-2.pluto b/Task/Singleton/Pluto/singleton-2.pluto new file mode 100644 index 0000000000..c5aa68ad22 --- /dev/null +++ b/Task/Singleton/Pluto/singleton-2.pluto @@ -0,0 +1,12 @@ +-- Singleton_user.pluto -- + +require "Singleton" + +local s = singleton.getInstance() +s:print() +local t = singleton.getInstance() +t:print() +print(s == t) -- true, as same object +print(instance) -- nil +local u = new singleton() -- throws an error +u:print() -- not executed diff --git a/Task/Singleton/Rust/singleton.rs b/Task/Singleton/Rust/singleton.rs new file mode 100644 index 0000000000..8dd6d79a52 --- /dev/null +++ b/Task/Singleton/Rust/singleton.rs @@ -0,0 +1,110 @@ +use std::sync::{Arc, Mutex, OnceLock}; + +// Thread-safe singleton using OnceLock (stable since Rust 1.70) +pub struct GlobalSingleton { + data: String, + counter: u32, +} + +impl GlobalSingleton { + // Private constructor + fn new() -> Self { + Self { + data: String::from("Singleton initialized"), + counter: 0, + } + } + + // Get the singleton instance + pub fn instance() -> Arc> { + static INSTANCE: OnceLock>> = OnceLock::new(); + + INSTANCE.get_or_init(|| { + Arc::new(Mutex::new(GlobalSingleton::new())) + }).clone() + } + + // Non-static methods that operate on the singleton instance + pub fn get_data(&self) -> &str { + &self.data + } + + pub fn set_data(&mut self, new_data: String) { + self.data = new_data; + } + + pub fn increment_counter(&mut self) { + self.counter += 1; + } + + pub fn get_counter(&self) -> u32 { + self.counter + } +} + +// Alternative implementation using std::sync::LazyLock (stable since Rust 1.80) +// This is the most modern and clean approach +use std::sync::LazyLock; + +static LAZY_SINGLETON: LazyLock>> = LazyLock::new(|| { + Arc::new(Mutex::new(GlobalSingleton::new())) +}); + +impl GlobalSingleton { + // Alternative method using LazyLock + pub fn lazy_instance() -> Arc> { + LAZY_SINGLETON.clone() + } +} + +fn main() { + // Usage example with OnceLock + { + let singleton = GlobalSingleton::instance(); + let mut instance = singleton.lock().unwrap(); + println!("Initial data: {}", instance.get_data()); + instance.increment_counter(); + instance.set_data("Modified data".to_string()); + println!("Counter: {}", instance.get_counter()); + } + + // Access from another scope - same instance + { + let singleton = GlobalSingleton::instance(); + let instance = singleton.lock().unwrap(); + println!("Data from another scope: {}", instance.get_data()); + println!("Counter from another scope: {}", instance.get_counter()); + } + + // Demonstrate thread safety + use std::thread; + + let handles: Vec<_> = (0..3) + .map(|i| { + thread::spawn(move || { + let singleton = GlobalSingleton::instance(); + let mut instance = singleton.lock().unwrap(); + instance.increment_counter(); + println!("Thread {} incremented counter to: {}", i, instance.get_counter()); + }) + }) + .collect(); + + for handle in handles { + handle.join().unwrap(); + } + + // Final state + let singleton = GlobalSingleton::instance(); + let instance = singleton.lock().unwrap(); + println!("Final counter value: {}", instance.get_counter()); + + // Demonstrate LazyLock alternative + println!("\n--- Using LazyLock alternative ---"); + { + let singleton = GlobalSingleton::lazy_instance(); + let mut instance = singleton.lock().unwrap(); + instance.set_data("LazyLock data".to_string()); + println!("LazyLock data: {}", instance.get_data()); + } +} diff --git a/Task/Singly-linked-list-Element-definition/Ada/singly-linked-list-element-definition.ada b/Task/Singly-linked-list-Element-definition/Ada/singly-linked-list-element-definition.adb similarity index 100% rename from Task/Singly-linked-list-Element-definition/Ada/singly-linked-list-element-definition.ada rename to Task/Singly-linked-list-Element-definition/Ada/singly-linked-list-element-definition.adb diff --git a/Task/Singly-linked-list-Element-definition/Crystal/singly-linked-list-element-definition.cr b/Task/Singly-linked-list-Element-definition/Crystal/singly-linked-list-element-definition.cr new file mode 100644 index 0000000000..54836eaf67 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Crystal/singly-linked-list-element-definition.cr @@ -0,0 +1,7 @@ +class Node (T) + property data : T + property next : Node(T)? + + def initialize (@data, @next = nil) + end +end diff --git a/Task/Singly-linked-list-Element-definition/Delphi/singly-linked-list-element-definition.delphi b/Task/Singly-linked-list-Element-definition/Delphi/singly-linked-list-element-definition.pas similarity index 100% rename from Task/Singly-linked-list-Element-definition/Delphi/singly-linked-list-element-definition.delphi rename to Task/Singly-linked-list-Element-definition/Delphi/singly-linked-list-element-definition.pas diff --git a/Task/Singly-linked-list-Element-definition/Julia/singly-linked-list-element-definition.julia b/Task/Singly-linked-list-Element-definition/Julia/singly-linked-list-element-definition.jl similarity index 100% rename from Task/Singly-linked-list-Element-definition/Julia/singly-linked-list-element-definition.julia rename to Task/Singly-linked-list-Element-definition/Julia/singly-linked-list-element-definition.jl diff --git a/Task/Singly-linked-list-Element-definition/Kotlin/singly-linked-list-element-definition.kotlin b/Task/Singly-linked-list-Element-definition/Kotlin/singly-linked-list-element-definition.kts similarity index 100% rename from Task/Singly-linked-list-Element-definition/Kotlin/singly-linked-list-element-definition.kotlin rename to Task/Singly-linked-list-Element-definition/Kotlin/singly-linked-list-element-definition.kts diff --git a/Task/Singly-linked-list-Element-definition/OCaml/singly-linked-list-element-definition-1.ocaml b/Task/Singly-linked-list-Element-definition/OCaml/singly-linked-list-element-definition-1.ml similarity index 100% rename from Task/Singly-linked-list-Element-definition/OCaml/singly-linked-list-element-definition-1.ocaml rename to Task/Singly-linked-list-Element-definition/OCaml/singly-linked-list-element-definition-1.ml diff --git a/Task/Singly-linked-list-Element-definition/OCaml/singly-linked-list-element-definition-2.ocaml b/Task/Singly-linked-list-Element-definition/OCaml/singly-linked-list-element-definition-2.ml similarity index 100% rename from Task/Singly-linked-list-Element-definition/OCaml/singly-linked-list-element-definition-2.ocaml rename to Task/Singly-linked-list-Element-definition/OCaml/singly-linked-list-element-definition-2.ml diff --git a/Task/Singly-linked-list-Element-definition/PascalABC.NET/singly-linked-list-element-definition.pas b/Task/Singly-linked-list-Element-definition/PascalABC.NET/singly-linked-list-element-definition.pas new file mode 100644 index 0000000000..050b35e550 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/PascalABC.NET/singly-linked-list-element-definition.pas @@ -0,0 +1,4 @@ +type Node = auto class + data: T; + next: Node; +end; diff --git a/Task/Singly-linked-list-Element-definition/Pluto/singly-linked-list-element-definition.pluto b/Task/Singly-linked-list-Element-definition/Pluto/singly-linked-list-element-definition.pluto new file mode 100644 index 0000000000..3f7c87bb5b --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Pluto/singly-linked-list-element-definition.pluto @@ -0,0 +1,7 @@ +require "list" + +local s = slist.of(1, 2) +local n1 = s:node(1) +local n2 = s:node(2) +print($"node 1: value = {n1.value}, next = {tostring(n1.next?.value)}") +print($"node 2: value = {n2.value}, next = {tostring(n2.next?.value)}") diff --git a/Task/Singly-linked-list-Element-definition/RISC-V-Assembly/singly-linked-list-element-definition.asm b/Task/Singly-linked-list-Element-definition/RISC-V-Assembly/singly-linked-list-element-definition.asm new file mode 100644 index 0000000000..029277af0a --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/RISC-V-Assembly/singly-linked-list-element-definition.asm @@ -0,0 +1,87 @@ +# riscv assembly raspberry pico2 rp2350 +# program linkedlist.s +# connexion putty com3 +/*********************************************/ +/* CONSTANTES */ +/********************************************/ +/* for this file see risc-v task include a file */ +.include "../../../constantesRiscv.inc" +.equ NBELEMENTS, 100 # list size +/****************************************************/ +/* MACROS */ +/****************************************************/ +#.include "../ficmacrosriscv.inc" # only for debugging + +/*******************************************/ +/* STRUCTURE */ +/*******************************************/ +/* structure linkedlist*/ + .struct 0 +llist_next: # next element + .struct llist_next + 4 +llist_value: # element value + .struct llist_value + 4 +llist_fin: +/*******************************************/ +/* INITIALED DATAS */ +/*******************************************/ +.data +szMessStart: .asciz "Program riscv start.\r\n" +szMessEndOk: .asciz "Program riscv end OK.\r\n" +szCariageReturn: .asciz "\r\n" +szMessNum: .asciz "Prime : " + +.align 2 +/*******************************************/ +/* UNINITIALED DATA */ +/*******************************************/ +.bss +sConvArea: .skip 24 +.align 2 +lList1: .skip llist_fin * NBELEMENTS # list memory place + +/**********************************************/ +/* SECTION CODE */ +/**********************************************/ +.text +.global main + +main: + call stdio_init_all # général init +1: # start loop connexion + li a0,0 # raz argument register + call tud_cdc_n_connected # waiting for USB connection + beqz a0,1b # return code = zero ? yes -> loop + + la a0,szMessStart # message address + call writeString # display message + + la a0,lList1 # list address + call initLinkedList + + la a0,szMessEndOk # message address + call writeString # display message + call getchar +100: # final loop + j 100b + +/**********************************************/ +/* initialisation linkedlist */ +/**********************************************/ +/* a0 linked list address */ +initLinkedList: # INFO: initLinkedList + addi sp, sp, -4 + sw ra, 0(sp) + sw x0,llist_value(a0) + sw x0,llist_next(a0) + + lw ra, 0(sp) + addi sp, sp, 4 + ret + + +/************************************/ +/* file include Fonctions */ +/***********************************/ +/* for this file see risc-v task include a file */ +.include "../../../includeFunctions.s" diff --git a/Task/Singly-linked-list-Element-definition/Rust/singly-linked-list-element-definition-1.rust b/Task/Singly-linked-list-Element-definition/Rust/singly-linked-list-element-definition-1.rs similarity index 100% rename from Task/Singly-linked-list-Element-definition/Rust/singly-linked-list-element-definition-1.rust rename to Task/Singly-linked-list-Element-definition/Rust/singly-linked-list-element-definition-1.rs diff --git a/Task/Singly-linked-list-Element-definition/Rust/singly-linked-list-element-definition-2.rust b/Task/Singly-linked-list-Element-definition/Rust/singly-linked-list-element-definition-2.rs similarity index 100% rename from Task/Singly-linked-list-Element-definition/Rust/singly-linked-list-element-definition-2.rust rename to Task/Singly-linked-list-Element-definition/Rust/singly-linked-list-element-definition-2.rs diff --git a/Task/Singly-linked-list-Element-definition/Rust/singly-linked-list-element-definition-3.rust b/Task/Singly-linked-list-Element-definition/Rust/singly-linked-list-element-definition-3.rs similarity index 100% rename from Task/Singly-linked-list-Element-definition/Rust/singly-linked-list-element-definition-3.rust rename to Task/Singly-linked-list-Element-definition/Rust/singly-linked-list-element-definition-3.rs diff --git a/Task/Singly-linked-list-Element-definition/Scheme/singly-linked-list-element-definition-1.ss b/Task/Singly-linked-list-Element-definition/Scheme/singly-linked-list-element-definition-1.scm similarity index 100% rename from Task/Singly-linked-list-Element-definition/Scheme/singly-linked-list-element-definition-1.ss rename to Task/Singly-linked-list-Element-definition/Scheme/singly-linked-list-element-definition-1.scm diff --git a/Task/Singly-linked-list-Element-definition/Scheme/singly-linked-list-element-definition-2.ss b/Task/Singly-linked-list-Element-definition/Scheme/singly-linked-list-element-definition-2.scm similarity index 100% rename from Task/Singly-linked-list-Element-definition/Scheme/singly-linked-list-element-definition-2.ss rename to Task/Singly-linked-list-Element-definition/Scheme/singly-linked-list-element-definition-2.scm diff --git a/Task/Singly-linked-list-Element-definition/Scheme/singly-linked-list-element-definition-3.ss b/Task/Singly-linked-list-Element-definition/Scheme/singly-linked-list-element-definition-3.scm similarity index 100% rename from Task/Singly-linked-list-Element-definition/Scheme/singly-linked-list-element-definition-3.ss rename to Task/Singly-linked-list-Element-definition/Scheme/singly-linked-list-element-definition-3.scm diff --git a/Task/Singly-linked-list-Element-definition/V-(Vlang)/singly-linked-list-element-definition.v b/Task/Singly-linked-list-Element-definition/V-(Vlang)/singly-linked-list-element-definition.v new file mode 100644 index 0000000000..7f230ea728 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/V-(Vlang)/singly-linked-list-element-definition.v @@ -0,0 +1,21 @@ +struct Node[T] { + mut: + data T + next ?&Node[T] +} + +// method override of built-in `str()` +fn (n Node[T]) str() string { + mut result := n.data.str() + mut current := n.next + for current != none { + result += " -> ${current or {continue}.data.str()}" + current = current or {continue}.next + } + return result +} + +fn main() { + n := Node{1, ?&Node{2, ?&Node{3, none}}} + println(n.str()) +} diff --git a/Task/Singly-linked-list-Element-insertion/Ada/singly-linked-list-element-insertion.ada b/Task/Singly-linked-list-Element-insertion/Ada/singly-linked-list-element-insertion.adb similarity index 100% rename from Task/Singly-linked-list-Element-insertion/Ada/singly-linked-list-element-insertion.ada rename to Task/Singly-linked-list-Element-insertion/Ada/singly-linked-list-element-insertion.adb diff --git a/Task/Singly-linked-list-Element-insertion/Crystal/singly-linked-list-element-insertion.cr b/Task/Singly-linked-list-Element-insertion/Crystal/singly-linked-list-element-insertion.cr new file mode 100644 index 0000000000..9438d84a74 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Crystal/singly-linked-list-element-insertion.cr @@ -0,0 +1,26 @@ +class Node (T) + property data : T + property next : Node(T)? + + def initialize (@data, @next = nil) + end + + def insert_after (new_data) + n = Node.new(new_data, @next) + @next = n + end + + def to_s (io) + io << data << "->" + if @next + @next.to_s(io) + else + io << "." + end + end +end + +n = Node.new('A', Node.new('B', Node.new('D'))) +puts n +n.insert_after('C') +puts n diff --git a/Task/Singly-linked-list-Element-insertion/Delphi/singly-linked-list-element-insertion.delphi b/Task/Singly-linked-list-Element-insertion/Delphi/singly-linked-list-element-insertion.pas similarity index 100% rename from Task/Singly-linked-list-Element-insertion/Delphi/singly-linked-list-element-insertion.delphi rename to Task/Singly-linked-list-Element-insertion/Delphi/singly-linked-list-element-insertion.pas diff --git a/Task/Singly-linked-list-Element-insertion/Julia/singly-linked-list-element-insertion.julia b/Task/Singly-linked-list-Element-insertion/Julia/singly-linked-list-element-insertion.jl similarity index 100% rename from Task/Singly-linked-list-Element-insertion/Julia/singly-linked-list-element-insertion.julia rename to Task/Singly-linked-list-Element-insertion/Julia/singly-linked-list-element-insertion.jl diff --git a/Task/Singly-linked-list-Element-insertion/Kotlin/singly-linked-list-element-insertion.kotlin b/Task/Singly-linked-list-Element-insertion/Kotlin/singly-linked-list-element-insertion.kts similarity index 100% rename from Task/Singly-linked-list-Element-insertion/Kotlin/singly-linked-list-element-insertion.kotlin rename to Task/Singly-linked-list-Element-insertion/Kotlin/singly-linked-list-element-insertion.kts diff --git a/Task/Singly-linked-list-Element-insertion/OCaml/singly-linked-list-element-insertion.ocaml b/Task/Singly-linked-list-Element-insertion/OCaml/singly-linked-list-element-insertion.ml similarity index 100% rename from Task/Singly-linked-list-Element-insertion/OCaml/singly-linked-list-element-insertion.ocaml rename to Task/Singly-linked-list-Element-insertion/OCaml/singly-linked-list-element-insertion.ml diff --git a/Task/Singly-linked-list-Element-insertion/PascalABC.NET/singly-linked-list-element-insertion.pas b/Task/Singly-linked-list-Element-insertion/PascalABC.NET/singly-linked-list-element-insertion.pas new file mode 100644 index 0000000000..864ad7ddb1 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/PascalABC.NET/singly-linked-list-element-insertion.pas @@ -0,0 +1,33 @@ +type Node = auto class + data: T; + next: Node; +end; + +type + SinglyLinkedList = class + first: Node; + procedure AddFirst(x: T); + begin + first := new Node(x,first); + end; + procedure AddAfter(p: Node; x: T); + begin + p.next := new Node(x,p.next); + end; + procedure PrintList(); + begin + var p := first; + while p<>nil do + begin + Print(p.data); + p := p.next; + end; + end; + end; + +begin + var lst := new SinglyLinkedList; + lst.AddFirst(2); lst.AddFirst(3); + lst.AddAfter(lst.first,555); + lst.PrintList; +end. diff --git a/Task/Singly-linked-list-Element-insertion/Pluto/singly-linked-list-element-insertion.pluto b/Task/Singly-linked-list-Element-insertion/Pluto/singly-linked-list-element-insertion.pluto new file mode 100644 index 0000000000..b0fe671fbb --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Pluto/singly-linked-list-element-insertion.pluto @@ -0,0 +1,8 @@ +require "list" + +local s = slist.of("A", "B") +local ixs = s:find("A") -- always returns an array of indices even if we only want the first +if #ixs > 0 then + s:insert(ixs[1] + 1, "C") + print(s) +end diff --git a/Task/Singly-linked-list-Element-insertion/RISC-V-Assembly/singly-linked-list-element-insertion.asm b/Task/Singly-linked-list-Element-insertion/RISC-V-Assembly/singly-linked-list-element-insertion.asm new file mode 100644 index 0000000000..5ab85fe11a --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/RISC-V-Assembly/singly-linked-list-element-insertion.asm @@ -0,0 +1,165 @@ +# riscv assembly raspberry pico2 rp2350 +# program linkedlist1.s +# connexion putty com3 +/*********************************************/ +/* CONSTANTES */ +/********************************************/ +/* for this file see risc-v task include a file */ +.include "../../../constantesRiscv.inc" +.equ NBELEMENTS, 100 # list size +/****************************************************/ +/* MACROS */ +/****************************************************/ +#.include "../ficmacrosriscv.inc" # only for debugging + +/*******************************************/ +/* STRUCTURE */ +/*******************************************/ +/* structure linkedlist*/ + .struct 0 +llist_next: # next element + .struct llist_next + 4 +llist_value: # element value + .struct llist_value + 4 +llist_fin: +/*******************************************/ +/* INITIALED DATAS */ +/*******************************************/ +.data +szMessStart: .asciz "Program riscv start.\r\n" +szMessEndOk: .asciz "Program riscv end OK.\r\n" +szCariageReturn: .asciz "\r\n" +/* datas error display */ +szMessErreur: .asciz "Error detected.\n" +/* datas message display */ +szMessResult: .asciz "Element No :" +szMessResultValue: .asciz " value : " + +.align 2 +/*******************************************/ +/* UNINITIALED DATA */ +/*******************************************/ +.bss +sConvArea: .skip 24 +.align 2 +lList1: .skip llist_fin * NBELEMENTS # list memory place + +/**********************************************/ +/* SECTION CODE */ +/**********************************************/ +.text +.global main + +main: + call stdio_init_all # général init +1: # start loop connexion + li a0,0 # raz argument register + call tud_cdc_n_connected # waiting for USB connection + beqz a0,1b # return code = zero ? yes -> loop + + la a0,szMessStart # message address + call writeString # display message + + la a0,lList1 # list address + call initLinkedList + + la a0,lList1 # list address + li a1,5 # value to insert + call insertElement # insertion + bgez a0,2f # error ? + la a0,szMessErreur + call writeString + j 10f +2: + la a0,lList1 # list address + li a1,11 # value to insert + call insertElement + bgez a0,3f + la a0,szMessErreur + call writeString + j 10f +3: + la s0,lList1 # list address + li s1,1 # n0 element +4: + lw s2,llist_next(s0) # load pointer + beqz s2,10f # end list ? + la a0,szMessResult + call writeString + mv a0,s1 # conversion and display N° element + la a1,sConvArea + call conversion10 + la a0,sConvArea + call writeString + + la a0,szMessResultValue + call writeString + lw a0,llist_value(s0) # conversion and display value element + la a1,sConvArea + call conversion10 + la a0,sConvArea + call writeString + la a0,szCariageReturn + call writeString + addi s1,s1,1 + mv s0,s2 # new pointer + j 4b # and loop + +10: + la a0,szMessEndOk # message address + call writeString # display message + call getchar +100: # final loop + j 100b + +/**********************************************/ +/* initialisation linkedlist */ +/**********************************************/ +/* a0 linked list address */ +initLinkedList: # INFO: initLinkedList + addi sp, sp, -4 + sw ra, 0(sp) + sw x0,llist_value(a0) # raz value + sw x0,llist_next(a0) # raz pointer + + lw ra, 0(sp) + addi sp, sp, 4 + ret +/**********************************************/ +/* insertion element in linked list */ +/**********************************************/ +/* a0 linked list address */ +/* a1 contains the value of element */ +/* a0 returns address of element or - 1 if error */ +insertElement: # INFO: insertElement + addi sp, sp, -4 + sw ra, 0(sp) + li t0,llist_fin * NBELEMENTS + add t0,t0,a0 # compute address end list + mv t1,a0 +1: + lw t3,llist_next(t1) # load next pointer + beqz t3,2f # end list ? + mv t1,t3 # no -> loop with pointer + j 1b +2: + addi t3,t1,llist_fin # yes -> compute next free address + blt t3,t0,3f # < list end -> ok + li a0,-1 + j 100f +3: + sw t3,llist_next(t1) # store next address in current pointer + sw a1,llist_value(t1) # store element value + sw x0,llist_value(t3) # init new eleùent + sw x0,llist_next(t3) + mv a0,t1 +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret + +/************************************/ +/* file include Fonctions */ +/***********************************/ +/* for this file see risc-v task include a file */ +.include "../../../includeFunctions.s" diff --git a/Task/Singly-linked-list-Element-insertion/Rust/singly-linked-list-element-insertion.rust b/Task/Singly-linked-list-Element-insertion/Rust/singly-linked-list-element-insertion.rs similarity index 100% rename from Task/Singly-linked-list-Element-insertion/Rust/singly-linked-list-element-insertion.rust rename to Task/Singly-linked-list-Element-insertion/Rust/singly-linked-list-element-insertion.rs diff --git a/Task/Singly-linked-list-Element-insertion/Scheme/singly-linked-list-element-insertion-1.ss b/Task/Singly-linked-list-Element-insertion/Scheme/singly-linked-list-element-insertion-1.scm similarity index 100% rename from Task/Singly-linked-list-Element-insertion/Scheme/singly-linked-list-element-insertion-1.ss rename to Task/Singly-linked-list-Element-insertion/Scheme/singly-linked-list-element-insertion-1.scm diff --git a/Task/Singly-linked-list-Element-insertion/Scheme/singly-linked-list-element-insertion-2.ss b/Task/Singly-linked-list-Element-insertion/Scheme/singly-linked-list-element-insertion-2.scm similarity index 100% rename from Task/Singly-linked-list-Element-insertion/Scheme/singly-linked-list-element-insertion-2.ss rename to Task/Singly-linked-list-Element-insertion/Scheme/singly-linked-list-element-insertion-2.scm diff --git a/Task/Singly-linked-list-Traversal/Ada/singly-linked-list-traversal.ada b/Task/Singly-linked-list-Traversal/Ada/singly-linked-list-traversal.adb similarity index 100% rename from Task/Singly-linked-list-Traversal/Ada/singly-linked-list-traversal.ada rename to Task/Singly-linked-list-Traversal/Ada/singly-linked-list-traversal.adb diff --git a/Task/Singly-linked-list-Traversal/Crystal/singly-linked-list-traversal.cr b/Task/Singly-linked-list-Traversal/Crystal/singly-linked-list-traversal.cr new file mode 100644 index 0000000000..3b1ee68b1f --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Crystal/singly-linked-list-traversal.cr @@ -0,0 +1,23 @@ +class Node (T) + include Enumerable(T) + + property data : T + property next : Node(T)? + + def initialize (@data, @next = nil) + end + + def each + node = self + while node + yield node.data + node = node.next + end + end +end + +list = Node.new('A', Node.new('B', Node.new('C'))) + +list.each_with_index do |ch, i| + puts "#{i}. #{ch}" +end diff --git a/Task/Singly-linked-list-Traversal/Delphi/singly-linked-list-traversal.delphi b/Task/Singly-linked-list-Traversal/Delphi/singly-linked-list-traversal.pas similarity index 100% rename from Task/Singly-linked-list-Traversal/Delphi/singly-linked-list-traversal.delphi rename to Task/Singly-linked-list-Traversal/Delphi/singly-linked-list-traversal.pas diff --git a/Task/Singly-linked-list-Traversal/Elena/singly-linked-list-traversal.elena b/Task/Singly-linked-list-Traversal/Elena/singly-linked-list-traversal.elena index 469eb38f3d..710fc8159a 100644 --- a/Task/Singly-linked-list-Traversal/Elena/singly-linked-list-traversal.elena +++ b/Task/Singly-linked-list-Traversal/Elena/singly-linked-list-traversal.elena @@ -1,4 +1,4 @@ while(nil != current){ - console printLine(current.Item); + Console printLine(current.Item); current := current.Next } diff --git a/Task/Singly-linked-list-Traversal/Julia/singly-linked-list-traversal.jl b/Task/Singly-linked-list-Traversal/Julia/singly-linked-list-traversal.jl new file mode 100644 index 0000000000..afc8bf9680 --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Julia/singly-linked-list-traversal.jl @@ -0,0 +1,15 @@ +Base.iterate(ll::LinkedList) = iterate(ll, ll.head) +Base.iterate(::LinkedList, st::Node) = st.data, st.next +Base.iterate(::LinkedList, ::EmptyNode) = nothing +Base.length(ll::LinkedList) = 1 + length(ll.next) +Base.length(ll::EmptyNode) = 0 +Base.eltype(::LinkedList{T}) where {T} = T + +lst = LinkedList{Int}() +push!(lst, 1) +push!(lst, 2) +push!(lst, 3) + +for n in lst + print(n, " ") +end diff --git a/Task/Singly-linked-list-Traversal/Julia/singly-linked-list-traversal.julia b/Task/Singly-linked-list-Traversal/Julia/singly-linked-list-traversal.julia deleted file mode 100644 index 94e8e839d1..0000000000 --- a/Task/Singly-linked-list-Traversal/Julia/singly-linked-list-traversal.julia +++ /dev/null @@ -1,12 +0,0 @@ -Base.start(ll::LinkedList) = ll.head -Base.done(ll::LinkedList{T}, st::AbstractNode{T}) where T = st isa EmptyNode -Base.next(ll::LinkedList{T}, st::AbstractNode{T}) where T = st.data, st.next - -lst = LinkedList{Int}() -push!(lst, 1) -push!(lst, 2) -push!(lst, 3) - -for n in lst - print(n, " ") -end diff --git a/Task/Singly-linked-list-Traversal/Kotlin/singly-linked-list-traversal.kotlin b/Task/Singly-linked-list-Traversal/Kotlin/singly-linked-list-traversal.kts similarity index 100% rename from Task/Singly-linked-list-Traversal/Kotlin/singly-linked-list-traversal.kotlin rename to Task/Singly-linked-list-Traversal/Kotlin/singly-linked-list-traversal.kts diff --git a/Task/Singly-linked-list-Traversal/OCaml/singly-linked-list-traversal.ocaml b/Task/Singly-linked-list-Traversal/OCaml/singly-linked-list-traversal.ml similarity index 100% rename from Task/Singly-linked-list-Traversal/OCaml/singly-linked-list-traversal.ocaml rename to Task/Singly-linked-list-Traversal/OCaml/singly-linked-list-traversal.ml diff --git a/Task/Singly-linked-list-Traversal/Pluto/singly-linked-list-traversal.pluto b/Task/Singly-linked-list-Traversal/Pluto/singly-linked-list-traversal.pluto new file mode 100644 index 0000000000..ecbff4bc4b --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Pluto/singly-linked-list-traversal.pluto @@ -0,0 +1,14 @@ +require "list" +local fmt = require "fmt" + +-- Create a singly-linked list containing the first 50 positive integers. +local s = slist.of(range(1, 50):unpack()) + +-- Now traverse and print them in tabular form. +local node = s:node(1) +local count = 0 +while node do + fmt.write("%4d ", node.value) + node = node.next + if ++count % 10 == 0 then print() end +end diff --git a/Task/Singly-linked-list-Traversal/RISC-V-Assembly/singly-linked-list-traversal.asm b/Task/Singly-linked-list-Traversal/RISC-V-Assembly/singly-linked-list-traversal.asm new file mode 100644 index 0000000000..902ac3fdb5 --- /dev/null +++ b/Task/Singly-linked-list-Traversal/RISC-V-Assembly/singly-linked-list-traversal.asm @@ -0,0 +1,174 @@ +# riscv assembly raspberry pico2 rp2350 +# program linkedlist2.s +# connexion putty com3 +/*********************************************/ +/* CONSTANTES */ +/********************************************/ +/* for this file see risc-v task include a file */ +.include "../../../constantesRiscv.inc" +.equ NBELEMENTS, 100 # list size +/****************************************************/ +/* MACROS */ +/****************************************************/ +#.include "../ficmacrosriscv.inc" # only for debugging + +/*******************************************/ +/* STRUCTURE */ +/*******************************************/ +/* structure linkedlist*/ + .struct 0 +llist_next: # next element + .struct llist_next + 4 +llist_value: # element value + .struct llist_value + 4 +llist_fin: +/*******************************************/ +/* INITIALED DATAS */ +/*******************************************/ +.data +szMessStart: .asciz "Program riscv start.\r\n" +szMessEndOk: .asciz "Program riscv end OK.\r\n" +szCariageReturn: .asciz "\r\n" +/* datas error display */ +szMessErreur: .asciz "Error detected.\n" +/* datas message display */ +szMessResult: .asciz "Element No :" +szMessResultValue: .asciz " value : " + +.align 2 +/*******************************************/ +/* UNINITIALED DATA */ +/*******************************************/ +.bss +sConvArea: .skip 24 +.align 2 +lList1: .skip llist_fin * NBELEMENTS # list memory place + +/**********************************************/ +/* SECTION CODE */ +/**********************************************/ +.text +.global main + +main: + call stdio_init_all # général init +1: # start loop connexion + li a0,0 # raz argument register + call tud_cdc_n_connected # waiting for USB connection + beqz a0,1b # return code = zero ? yes -> loop + + la a0,szMessStart # message address + call writeString # display message + + la a0,lList1 # list address + call initLinkedList + + la a0,lList1 # list address + li a1,5000 # value to insert + call insertElement # insertion + bgez a0,2f # error ? + la a0,szMessErreur + call writeString + j 10f +2: + la a0,lList1 # list address + li a1,1234567 # value to insert + call insertElement + bgez a0,3f + la a0,szMessErreur + call writeString + j 10f +3: + la a0,lList1 # list address + li a1,88888 # value to insert + call insertElement + bgez a0,4f + la a0,szMessErreur + call writeString + j 10f +4: + + la s0,lList1 # list address + li s1,1 # n0 element +5: + lw s2,llist_next(s0) # load pointer + beqz s2,10f # end list ? + la a0,szMessResult + call writeString + mv a0,s1 # conversion and display N° element + la a1,sConvArea + call conversion10 + la a0,sConvArea + call writeString + + la a0,szMessResultValue + call writeString + lw a0,llist_value(s0) # conversion and display value element + la a1,sConvArea + call conversion10 + la a0,sConvArea + call writeString + la a0,szCariageReturn + call writeString + addi s1,s1,1 + mv s0,s2 # new pointer + j 5b # and loop + +10: + la a0,szMessEndOk # message address + call writeString # display message + call getchar +100: # final loop + j 100b + +/**********************************************/ +/* initialisation linkedlist */ +/**********************************************/ +/* a0 linked list address */ +initLinkedList: # INFO: initLinkedList + addi sp, sp, -4 + sw ra, 0(sp) + sw x0,llist_value(a0) # raz value + sw x0,llist_next(a0) # raz pointer + + lw ra, 0(sp) + addi sp, sp, 4 + ret +/**********************************************/ +/* insertion element in linked list */ +/**********************************************/ +/* a0 linked list address */ +/* a1 contains the value of element */ +/* a0 returns address of element or - 1 if error */ +insertElement: # INFO: insertElement + addi sp, sp, -4 + sw ra, 0(sp) + li t0,llist_fin * NBELEMENTS + add t0,t0,a0 # compute address end list + mv t1,a0 +1: + lw t3,llist_next(t1) # load next pointer + beqz t3,2f # end list ? + mv t1,t3 # no -> loop with pointer + j 1b +2: + addi t3,t1,llist_fin # yes -> compute next free address + blt t3,t0,3f # < list end -> ok + li a0,-1 + j 100f +3: + sw t3,llist_next(t1) # store next address in current pointer + sw a1,llist_value(t1) # store element value + sw x0,llist_value(t3) # init new eleùent + sw x0,llist_next(t3) + mv a0,t1 +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret + +/************************************/ +/* file include Fonctions */ +/***********************************/ +/* for this file see risc-v task include a file */ +.include "../../../includeFunctions.s" diff --git a/Task/Singly-linked-list-Traversal/Rust/singly-linked-list-traversal.rust b/Task/Singly-linked-list-Traversal/Rust/singly-linked-list-traversal.rs similarity index 100% rename from Task/Singly-linked-list-Traversal/Rust/singly-linked-list-traversal.rust rename to Task/Singly-linked-list-Traversal/Rust/singly-linked-list-traversal.rs diff --git a/Task/Singly-linked-list-Traversal/Scheme/singly-linked-list-traversal.ss b/Task/Singly-linked-list-Traversal/Scheme/singly-linked-list-traversal.scm similarity index 100% rename from Task/Singly-linked-list-Traversal/Scheme/singly-linked-list-traversal.ss rename to Task/Singly-linked-list-Traversal/Scheme/singly-linked-list-traversal.scm diff --git a/Task/Singular-value-decomposition/00-TASK.txt b/Task/Singular-value-decomposition/00-TASK.txt index feb8d94a28..d570b2ea12 100644 --- a/Task/Singular-value-decomposition/00-TASK.txt +++ b/Task/Singular-value-decomposition/00-TASK.txt @@ -1,11 +1,11 @@ -A is any m by n matrix, square or rectangular. Its rank is r. We will diagonalize this A, but not by X^{−1}AX. +A is any m by n matrix, square or rectangular. Its rank is r. We will diagonalize this A, but not by X^{-1} A X. The eigenvectors in X have three big problems: They are usually not orthogonal, there -are not always enough eigenvectors, and Ax = λx requires A to be a square matrix. The +are not always enough eigenvectors, and Ax = \lambda x requires A to be a square matrix. The singular vectors of A solve all those problems in a perfect way. [https://math.mit.edu/classes/18.095/2016IAP/lec2/SVD_Notes.pdf The Singular Value Decomposition (SVD)] -According to the web page above, for any rectangular matrix A, we can decomposite it as A=UΣV^T +According to the web page above, for any rectangular matrix A, we can decomposite it as A=U\Sigma V^T ''' Task Description''' @@ -13,7 +13,7 @@ Firstly, input two numbers "m" and "n". Then, input a square/rectangular matrix A^{m\times n}. -Finally, output U,Σ,V with respect to A. +Finally, output U,~\Sigma,\ V with respect to A. ''' Example ''' diff --git a/Task/Singular-value-decomposition/FreeBASIC/singular-value-decomposition.basic b/Task/Singular-value-decomposition/FreeBASIC/singular-value-decomposition.basic new file mode 100644 index 0000000000..81928efde4 --- /dev/null +++ b/Task/Singular-value-decomposition/FreeBASIC/singular-value-decomposition.basic @@ -0,0 +1,64 @@ +#include once "inc\gsl\gsl_linalg.bi" + +Sub MatrixPrint(r As Integer, c As Integer, m() As Double) + For i As Integer = 0 To r - 1 + Print "|"; + For j As Integer = 0 To c - 1 + Print Using "#############.########## "; m(i * c + j); + Next j + Print Chr(8); "|" + Next i + Print +End Sub + +Dim As Integer r = 2 +Dim As Integer c = 2 +Dim As Integer l = r * c + +Dim As Double a(l - 1) +a(0) = 3: a(1) = 0: a(2) = 4: a(3) = 5 +Dim As Double v(l - 1) +v(0) = 0: v(1) = 0: v(2) = 0: v(3) = 0 +Dim As Double s(c - 1) +s(0) = 0: s(1) = 0 + +Dim As gsl_matrix Ptr a_mat = gsl_matrix_alloc(r, c) +Dim As gsl_matrix Ptr v_mat = gsl_matrix_alloc(c, c) +Dim As gsl_vector Ptr s_vec = gsl_vector_alloc(c) +Dim As gsl_vector Ptr work = gsl_vector_alloc(c) + +Dim As Integer i, j +For i = 0 To r - 1 + For j = 0 To c - 1 + gsl_matrix_set(a_mat, i, j, a(i * c + j)) + Next j +Next i + +gsl_linalg_SV_decomp(a_mat, v_mat, s_vec, work) + +For i = 0 To r - 1 + For j = 0 To c - 1 + a(i * c + j) = gsl_matrix_get(a_mat, i, j) + v(i * c + j) = gsl_matrix_get(v_mat, i, j) + Next j +Next i + +For i = 0 To c - 1 + s(i) = gsl_vector_get(s_vec, i) +Next i + +Print "U:" +MatrixPrint(r, c, a()) + +Print "S:" +MatrixPrint(1, c, s()) + +Print "VT:" +MatrixPrint(r, c, v()) + +gsl_matrix_free(a_mat) +gsl_matrix_free(v_mat) +gsl_vector_free(s_vec) +gsl_vector_free(work) + +Sleep diff --git a/Task/Singular-value-decomposition/Julia/singular-value-decomposition.julia b/Task/Singular-value-decomposition/Julia/singular-value-decomposition.jl similarity index 100% rename from Task/Singular-value-decomposition/Julia/singular-value-decomposition.julia rename to Task/Singular-value-decomposition/Julia/singular-value-decomposition.jl diff --git a/Task/Singular-value-decomposition/Mathematica/singular-value-decomposition.math b/Task/Singular-value-decomposition/Mathematica/singular-value-decomposition.math new file mode 100644 index 0000000000..15212c9730 --- /dev/null +++ b/Task/Singular-value-decomposition/Mathematica/singular-value-decomposition.math @@ -0,0 +1,15 @@ +(* Define the matrix *) +matrix = {{3, 0}, {4, 5}}; + +(* Perform singular value decomposition *) +{u, s, v} = SingularValueDecomposition[matrix]; + +(* Display results with 10 decimal places *) +Print["U matrix:"] +N[u, {Infinity, 10}] //Print + +Print["S matrix:"] +N[s, {Infinity, 10}] //Print + +Print["V matrix:"] +N[v, {Infinity, 10}] //Print diff --git a/Task/Singular-value-decomposition/Perl/singular-value-decomposition.pl b/Task/Singular-value-decomposition/Perl/singular-value-decomposition.pl new file mode 100644 index 0000000000..51e8e35164 --- /dev/null +++ b/Task/Singular-value-decomposition/Perl/singular-value-decomposition.pl @@ -0,0 +1,21 @@ +# 20240920 Perl programming solution + +use strict; +use warnings; +use Math::GSL::Matrix; +use Math::GSL::Linalg qw/gsl_linalg_SV_decomp/; + +my $M = Math::GSL::Matrix->new(2, 2); +$M->set_elem(0,0,3)->set_elem(0,1,0)->set_elem(1,0,4)->set_elem(1,1,5); + +my $V = Math::GSL::Matrix->new(2, 2); +my ($S, $work) = ( Math::GSL::Vector->new(2), Math::GSL::Vector->new(2) ); + +gsl_linalg_SV_decomp($M->raw, $V->raw, $S->raw, $work->raw); + +print "U factor:\n"; +for my $i (0 .. $M->rows - 1) { print join(", ",$M->row($i)->as_list),"\n" } +print "singular values:\n"; +print join(", ", map { sprintf("%.10g", $_) } $S->as_list), "\n"; +print "Vt factor:\n"; +for my $i (0 .. $V->rows - 1) { print join(", ",$V->row($i)->as_list),"\n" } diff --git a/Task/Singular-value-decomposition/Scheme/singular-value-decomposition.ss b/Task/Singular-value-decomposition/Scheme/singular-value-decomposition.scm similarity index 100% rename from Task/Singular-value-decomposition/Scheme/singular-value-decomposition.ss rename to Task/Singular-value-decomposition/Scheme/singular-value-decomposition.scm diff --git a/Task/Sisyphus-sequence/ALGOL-68/sisyphus-sequence.alg b/Task/Sisyphus-sequence/ALGOL-68/sisyphus-sequence.alg index c2148d75c0..3c6aff36d7 100644 --- a/Task/Sisyphus-sequence/ALGOL-68/sisyphus-sequence.alg +++ b/Task/Sisyphus-sequence/ALGOL-68/sisyphus-sequence.alg @@ -1,24 +1,16 @@ BEGIN # generate elements of the Sysiphus Sequence: see OEIS A350877 # - # returns the largest element in a # - OP MAX = ( []INT a )INT: - IF LWB a >UPB a THEN 0 - ELSE - INT result := a[ LWB a ]; - FOR i FROM LWB a + 1 TO UPB a DO - IF result < a[ i ] THEN result := a[ i ] FI - OD; - result - FI # MAX # ; + PR read "rows.incl.a68" PR # include row (array) utilities # + # sieve the primes # - INT sieve max = 1 000 000 000; ### CHANGE TO E.G.: 100 000 000 FOR ALGOL 68G ### + INT sieve max = 100 000 000; ### 10 000 000 for ALGOL 68 Genie version 3 # BOOL is odd := TRUE; [ sieve max ]BOOL sieve; FOR i TO UPB sieve DO sieve[ i ] := is odd; is odd := NOT is odd OD; sieve[ 1 ] := FALSE; sieve[ 2 ] := TRUE; - FOR s FROM 3 BY 2 TO ENTIER sqrt( sieve max ) DO - IF sieve[ s ] THEN - FOR p FROM s * s BY s TO sieve max DO sieve[ p ] := FALSE OD + FOR s pos FROM 3 BY 2 TO ENTIER sqrt( sieve max ) DO + IF sieve[ s pos ] THEN + FOR p FROM s pos * s pos BY s pos TO sieve max DO sieve[ p ] := FALSE OD FI OD; [ 1 : 250 ]INT pos; # positions of 1..250 in the sequence # @@ -96,5 +88,6 @@ BEGIN # generate elements of the Sysiphus Sequence: see OEIS A350877 # FOR i TO 100 DO print( ( IF pos[ i ] = 0 THEN " unknown" ELSE whole( pos[ i ], -8 ) FI ) ); IF i MOD 8 = 0 THEN print( ( newline ) ) FI - OD + OD; + print( ( newline ) ) END diff --git a/Task/Sisyphus-sequence/EasyLang/sisyphus-sequence.easy b/Task/Sisyphus-sequence/EasyLang/sisyphus-sequence.easy index 27988008d1..befbb870ce 100644 --- a/Task/Sisyphus-sequence/EasyLang/sisyphus-sequence.easy +++ b/Task/Sisyphus-sequence/EasyLang/sisyphus-sequence.easy @@ -1,24 +1,20 @@ func isprim num . - if num mod 2 = 0 and num > 2 - return 0 - . + if num mod 2 = 0 and num > 2 : return 0 i = 3 while i <= sqrt num - if num mod i = 0 - return 0 - . + if num mod i = 0 : return 0 i += 2 . return 1 . prim = 1 -proc nextprim . . +proc nextprim . repeat prim += 1 until isprim prim = 1 . . -numfmt 0 4 +numfmt 4 0 n = 1 write n for i = 2 to 100 @@ -29,7 +25,5 @@ for i = 2 to 100 n /= 2 . write n - if i mod 10 = 0 - print "" - . + if i mod 10 = 0 : print "" . diff --git a/Task/Sisyphus-sequence/FreeBASIC/sisyphus-sequence.basic b/Task/Sisyphus-sequence/FreeBASIC/sisyphus-sequence.basic new file mode 100644 index 0000000000..d8d2253733 --- /dev/null +++ b/Task/Sisyphus-sequence/FreeBASIC/sisyphus-sequence.basic @@ -0,0 +1,83 @@ +'#include "isprime.bas" + +Function getNthPrime(n As Integer) As Longint + If n <= 0 Then Return 0 + + Dim As Integer cnt = 0 + Dim As Longint num = 1 + + While cnt < n + num += 1 + If isPrime(num) Then cnt += 1 + Wend + + Return num +End Function + +Function findMax(arr() As Integer) As Integer + Dim As Integer maxVal = arr(0) + For i As Integer = 1 To Ubound(arr) + If arr(i) > maxVal Then maxVal = arr(i) + Next + Return maxVal +End Function + +' Main program +Const As Longint limit = 1e6 +Dim As Double sisyphus(100) +Dim As Integer under250(250) +Dim As Integer i, m, np = 0 +Dim As Longint specific = 1000 +Dim As Longint cnt = 1 +Dim As Double nextVal = 1 + +sisyphus(0) = 1 +under250(1) = 1 + +Do + If (nextVal Mod 2) = 0 Then + nextVal /= 2 + Else + np += 1 + nextVal += getNthPrime(np) + End If + + If nextVal <= 250 Then under250(nextVal) += 1 + + cnt += 1 + If cnt <= 100 Then + sisyphus(cnt-1) = nextVal + If cnt = 100 Then + Print "The first 100 members of the Sisyphus sequence are:" + For i = 0 To 99 + Print Using "####"; sisyphus(i); + If (i + 1) Mod 10 = 0 Then Print + Next + Print + End If + Elseif cnt = specific Then + Print Using "###,###,###,###"; cnt; + Print "th member is: "; + Print Using "###,###,###,###"; nextVal; + Print " and highest prime needed: "; + Print Using "###,###,###"; getNthPrime(np) + + If cnt = limit Then + m = findMax(under250()) + Print !"\nNumbers under 250 that do not occur in first "; cnt; " terms:" + For i = 1 To 250 + If under250(i) = 0 Then Print i; " "; + Next + Print + Print !"\nNumbers under 250 that occur the most in first "; cnt; " terms:" + For i = 1 To 250 + If under250(i) = m Then Print i; " "; + Next + Print " all occur "; m; " times." + Exit Do + End If + specific *= 10 + End If +Loop + +Sleep diff --git a/Task/Sisyphus-sequence/JavaScript/sisyphus-sequence.js b/Task/Sisyphus-sequence/JavaScript/sisyphus-sequence.js new file mode 100644 index 0000000000..1b6e22afc5 --- /dev/null +++ b/Task/Sisyphus-sequence/JavaScript/sisyphus-sequence.js @@ -0,0 +1,144 @@ +class SegmentedPrimeIterator { + constructor(limit) { + this.squareRoot = Math.floor(Math.sqrt(limit)); + this.low = 0; + this.high = this.squareRoot; + this.index = 0; + this.primes = []; + this.smallPrimes = []; + this.smallSieve(this.squareRoot); + } + + next() { + if (this.index === this.primes.length) { + this.index = 0; + this.segmentedSieve(); + } + return this.primes[this.index++]; + } + + segmentedSieve() { + this.low += this.squareRoot; + this.high += this.squareRoot; + + const markedPrime = new Array(this.squareRoot).fill(true); + + for (let i = 0; i < this.smallPrimes.length; i++) { + let lowLimit = Math.floor(this.low / this.smallPrimes[i]) * this.smallPrimes[i]; + if (lowLimit < this.low) { + lowLimit += this.smallPrimes[i]; + } + + for (let j = lowLimit; j < this.high; j += this.smallPrimes[i]) { + markedPrime[j - this.low] = false; + } + } + + this.primes = []; + for (let i = this.low; i < this.high; i++) { + if (markedPrime[i - this.low]) { + this.primes.push(i); + } + } + } + + smallSieve(squareRoot) { + const markedPrime = new Array(squareRoot + 1).fill(true); + + for (let p = 2; p * p <= squareRoot; p++) { + if (markedPrime[p]) { + for (let i = p * p; i <= squareRoot; i += p) { + markedPrime[i] = false; + } + } + } + + for (let p = 2; p <= squareRoot; p++) { + if (markedPrime[p]) { + this.primes.push(p); + } + } + this.smallPrimes = [...this.primes]; + } +} + +class SisyphusIterator { + constructor(limit) { + this.previous = 2; + this.prime = 0; + this.primeIterator = new SegmentedPrimeIterator(limit); + } + + next() { + if ((this.previous & 1) === 0) { + this.previous >>= 1; + } else { + this.prime = this.primeIterator.next(); + this.previous += this.prime; + } + return this.previous; + } + + getPrime() { + return this.prime; + } +} + +function display(found, search, target, prefix, suffix) { + console.log(); + console.log(prefix + target + " terms:"); + const results = []; + for (let i = 1; i < found.length; i++) { + if (found[i] === search) { + results.push(i); + } + } + console.log(results.join(" ") + (suffix ? " " + suffix : "")); +} + +function main() { + const limit = 100_000_000; + const iterator = new SisyphusIterator(1_000_000_000_000); + + console.log("The first 100 members of the Sisyphus sequence are:"); + const found = new Array(250).fill(0); + let next = 0; + let count = 0; + let target = 1_000; + + while (target <= limit) { + count += 1; + next = iterator.next(); + + if (next < 250) { + found[next]++; + } + + if (count <= 100) { + process.stdout.write(next.toString().padStart(3) + (count % 10 === 0 ? "\n" : " ")); + if (count === 100) { + console.log(); + } + } else if (count === target) { + target *= 10; + console.log(`${target.toString().padStart(11)}th member is ${next.toString().padStart(11)} and highest prime needed is ${iterator.getPrime().toString().padStart(10)}`); + } + } + + display(found, 0, target, "These numbers under 250 occur the most in the first ", ""); + + const max = Math.max(...found); + display(found, max, target, + "These numbers under 250 occur the most in the first ", + "all occur " + max + " times"); + + while (next !== 36) { + count += 1; + next = iterator.next(); + } + + console.log(); + console.log(count + "th member is " + next + " and highest prime needed is " + iterator.getPrime()); +} + +main(); diff --git a/Task/Sisyphus-sequence/Julia/sisyphus-sequence.julia b/Task/Sisyphus-sequence/Julia/sisyphus-sequence.jl similarity index 100% rename from Task/Sisyphus-sequence/Julia/sisyphus-sequence.julia rename to Task/Sisyphus-sequence/Julia/sisyphus-sequence.jl diff --git a/Task/Sisyphus-sequence/Mathematica/sisyphus-sequence.math b/Task/Sisyphus-sequence/Mathematica/sisyphus-sequence.math new file mode 100644 index 0000000000..a56731f395 --- /dev/null +++ b/Task/Sisyphus-sequence/Mathematica/sisyphus-sequence.math @@ -0,0 +1,33 @@ +num = 1; +primepi = 1; +res = Table[ + If[EvenQ[num], + num /= 2; + , + num += Prime[primepi]; + primepi++; + ]; + num + , + {99} + ]; +PrependTo[res, 1]; +Partition[res, 10] // Grid + +Table[ + num = 1; + primepi = 1; + Do[ + If[EvenQ[num], + num /= 2; + , + num += Prime[primepi]; + primepi++; + ]; + , + {j} + ]; + {num, Prime[primepi - 1]} + , + {j, {999, 9999, 99999, 999999, 9999999, 99999999}} +] diff --git a/Task/Sisyphus-sequence/Phix/sisyphus-sequence-1.phix b/Task/Sisyphus-sequence/Phix/sisyphus-sequence-1.phix index 7f291bddcd..3c7dadb7f7 100644 --- a/Task/Sisyphus-sequence/Phix/sisyphus-sequence-1.phix +++ b/Task/Sisyphus-sequence/Phix/sisyphus-sequence-1.phix @@ -1,35 +1,35 @@ -(phixonline)--> - atom t0 = time() - constant limit = 1e8 - sequence sisyphus = {1}, - under250 = reinstate(repeat(0,250),1,1) - integer np = 0, specific = 1000, count = 1, m - atom next = 1 - while true do - if even(next) then - next /= 2 - else - np += 1 - next += get_prime(np) - end if - if next <= 250 then under250[next] += 1 end if - count += 1 - if count <= 100 then - sisyphus &= next - if count == 100 then - printf(1,"The first 100 members of the Sisyphus sequence are:\n%s\n", - {join_by(sisyphus,1,10," ",fmt:="%3d")}) - end if - elsif count == specific then - printf(1,"%,13d%s member is: %,13d and highest prime needed: %,11d\n", - {count, ord(count), next, get_prime(np)}) - if count == limit then m = largest(under250,true); exit end if - specific *= 10 - end if - end while - printf(1,"\nThese numbers under 250 do not occur in the first %,d terms:\n",count) - printf(1," %v\n",{find_all(0,under250)}) - printf(1,"\nThese numbers under 250 occur the most in the first %,d terms:\n",count) - printf(1," %v all occur %d times.\n",{find_all(m,under250),m}) - ?elapsed(time()-t0) - - without js - include builtins/primesieve.e -- (can provide if desired, ask me on either my or this tasks talk page) - requires(WINDOWS) - requires(64,true) - atom t0 = time(), t1 = time()+1 - integer np = 0, count = 1, p - atom next = 1 - while next!=36 do - if even(next) then - next /= 2 - else - p = primesieve_next_prime() - next += p - end if - count += 1 - if time()>t1 then - atom cpc = (count/77_534_485_877)*100, - ppc = (p/677_121_348_413)*100 - progress("count: %,d (%2.2f%%) p: %,d (%2.2f%%)\r",{count,cpc,p,ppc}) - t1 = time()+1 - end if - end while - progress("") - printf(1,"%,d%s member is: %,d and highest prime needed: %,d\n", - {count, ord(count), next, p}) - ?elapsed(time()-t0) - ) + + say "Sleeping..." + 10 sleep + say "Awake!" diff --git a/Task/Sleep/REXX/sleep-3.rexx b/Task/Sleep/REXX/sleep-3.rexx new file mode 100644 index 0000000000..a13ccfe3e3 --- /dev/null +++ b/Task/Sleep/REXX/sleep-3.rexx @@ -0,0 +1,20 @@ +-- 24 Aug 2025 +include Setting + +say 'SLEEP' +say version +say +call Sleep 1 +call Sleep 2 +call Sleep 3 +exit + +Sleep: +procedure +arg s +say time('l') 'Waiting for' s 'seconds...' +'timeout /t' s '/nobreak > nul' +say time('l') 'Done!' +return + +include Abend diff --git a/Task/Sleep/REBOL/sleep.rebol b/Task/Sleep/Rebol/sleep.rebol similarity index 96% rename from Task/Sleep/REBOL/sleep.rebol rename to Task/Sleep/Rebol/sleep.rebol index 99c9399b39..d955cd3b04 100644 --- a/Task/Sleep/REBOL/sleep.rebol +++ b/Task/Sleep/Rebol/sleep.rebol @@ -1,4 +1,4 @@ -REBOL [ +Rebol [ Title: "Sleep Main Thread" URL: http://rosettacode.org/wiki/Sleep_the_Main_Thread ] diff --git a/Task/Sleep/Rust/sleep.rust b/Task/Sleep/Rust/sleep.rs similarity index 100% rename from Task/Sleep/Rust/sleep.rust rename to Task/Sleep/Rust/sleep.rs diff --git a/Task/Sleep/Rye/sleep.rye b/Task/Sleep/Rye/sleep.rye new file mode 100644 index 0000000000..08f202092a --- /dev/null +++ b/Task/Sleep/Rye/sleep.rye @@ -0,0 +1,4 @@ +time: 3000 ;milliseconds +print "Asleep" +sleep time +print "Awake now!" diff --git a/Task/Sleep/Scheme/sleep.ss b/Task/Sleep/Scheme/sleep.scm similarity index 100% rename from Task/Sleep/Scheme/sleep.ss rename to Task/Sleep/Scheme/sleep.scm diff --git a/Task/Sleep/Standard-ML/sleep-1.ml b/Task/Sleep/Standard-ML/sleep-1.ml new file mode 100644 index 0000000000..ad62f83d2b --- /dev/null +++ b/Task/Sleep/Standard-ML/sleep-1.ml @@ -0,0 +1,12 @@ +fun doSleep () = + let + val maybeline = TextIO.inputLine TextIO.stdIn + val line = if isSome maybeline then valOf maybeline else raise Fail "Enter a number of seconds" + val maybesecs = Real.fromString line + val secs = if isSome maybesecs then valOf maybesecs else raise Fail "Bad number entered" + val () = print "Sleeping...\n" + val () = OS.Process.sleep (Time.fromReal secs) + val () = print "Awake!\n" + in + () + end diff --git a/Task/Sleep/Standard-ML/sleep-2.ml b/Task/Sleep/Standard-ML/sleep-2.ml new file mode 100644 index 0000000000..b535620c46 --- /dev/null +++ b/Task/Sleep/Standard-ML/sleep-2.ml @@ -0,0 +1,2 @@ +(* load the above function in the REPL and then: *) +PolyML.export("doSleep.o", doSleep); diff --git a/Task/Sleep/Standard-ML/sleep.ml b/Task/Sleep/Standard-ML/sleep.ml deleted file mode 100644 index dc947357b6..0000000000 --- a/Task/Sleep/Standard-ML/sleep.ml +++ /dev/null @@ -1,8 +0,0 @@ -(TextIO.print "input a number of seconds please: "; -let val seconds = valOf (Int.fromString (valOf (TextIO.inputLine TextIO.stdIn))) in - TextIO.print "Sleeping...\n"; - OS.Process.sleep (Time.fromReal seconds); (* it takes a Time.time data structure as arg, - but in my implementation it seems to round down to the nearest second. - I dunno why; it doesn't say anything about this in the documentation *) - TextIO.print "Awake!\n" -end) diff --git a/Task/Sleep/VBScript/sleep.vb b/Task/Sleep/VBScript/sleep.vbs similarity index 100% rename from Task/Sleep/VBScript/sleep.vb rename to Task/Sleep/VBScript/sleep.vbs diff --git a/Task/Sleeping-Beauty-problem/ALGOL-68/sleeping-beauty-problem.alg b/Task/Sleeping-Beauty-problem/ALGOL-68/sleeping-beauty-problem.alg new file mode 100644 index 0000000000..e1010ae8e4 --- /dev/null +++ b/Task/Sleeping-Beauty-problem/ALGOL-68/sleeping-beauty-problem.alg @@ -0,0 +1,19 @@ +BEGIN # sleeping beauty problem - translated from the Wren sample # + PROC sleeping beauty = ( INT reps )REAL: + BEGIN + INT wakings := 0, heads := 0; + TO reps DO + wakings +:= 1; + IF next random < 0.5 THEN # [0..0.5) = heads, [0.5..1.0) = tails say # + heads +:= 1 + ELSE + wakings +:= 1 + FI + OD; + print( ( "Wakings over ", whole( reps, 0 ), " repetitions = ", whole( wakings, 0 ), newline ) ); + ( heads / wakings ) * 100 + END; # sleeping beauty # + + REAL pc = sleeping beauty( 1 000 000 ); + print( ( "Percentage probability of heads on waking = ", fixed( pc, -10, 6 ), "%", newline ) ) +END diff --git a/Task/Sleeping-Beauty-problem/ALGOL-W/sleeping-beauty-problem.alg b/Task/Sleeping-Beauty-problem/ALGOL-W/sleeping-beauty-problem.alg new file mode 100644 index 0000000000..5a2ea9271e --- /dev/null +++ b/Task/Sleeping-Beauty-problem/ALGOL-W/sleeping-beauty-problem.alg @@ -0,0 +1,35 @@ +begin % sleeping beauty problem - translated from the Wren sample, via Agena % + + integer seed; % seed for random number generation % + + % returns the next middle-square random number in [0..1) % + real procedure random ; + begin + if seed = 0 then seed := time( -1 ) rem 10000; + seed := ( ( seed * seed ) div 100 ) rem 10000; + seed / 10000 + end random ; + + real procedure sleepingBeauty( integer value reps ) ; + begin + integer wakings, heads; + wakings := heads := 0; + for i := 1 until reps do begin + wakings := wakings + 1; + if random < 0.5 then begin + heads := 1 + heads % [0..0.5) = heads % + end else begin + wakings := 1 + wakings % [0.5..1) = tails % + end if__random_lt_500000__ + end for_i ; + write( i_w := 1, s_w := 0, "Wakings over ", reps, " repetitions = ", wakings ); + ( heads / wakings ) * 100 + end sleepingBeauty ; + + begin + real pc; + seed := 0; % initialise the random number generator % + pc := sleepingBeauty( 1000000 ); + write( s_w := 0, "Percentage probability of heads on waking = ", pc, "%" ) + end +end. diff --git a/Task/Sleeping-Beauty-problem/Ada/sleeping-beauty-problem.adb b/Task/Sleeping-Beauty-problem/Ada/sleeping-beauty-problem.adb new file mode 100644 index 0000000000..3131c73bd0 --- /dev/null +++ b/Task/Sleeping-Beauty-problem/Ada/sleeping-beauty-problem.adb @@ -0,0 +1,32 @@ +with Ada.Numerics.Discrete_Random; +with Ada.Text_IO; use Ada.Text_IO; + +procedure Sleeping_Beauty is + type Coin is (Heads, Tails); + package Random_Coin is new Ada.Numerics.Discrete_Random (Coin); use Random_Coin; + package FIO is new Float_IO (Float); + Tosser : Generator; + Probability : Float; + + function Experiment (Tosses : Integer) return Float is + Awakenings, Heads_Count : Integer := 0; + begin + for Iteration in 1 .. Tosses loop + case Random (Tosser) is + when Heads => + Awakenings := Awakenings + 1; + Heads_Count := Heads_Count + 1; + when Tails => + Awakenings := Awakenings + 2; + end case; + end loop; + Put_Line ("Awakenings over" & Tosses'Image & " iterations:" & Awakenings'Image); + return Float (Heads_Count) / Float (Awakenings) * 100.0; + end Experiment; + +begin + Reset (Tosser); + Probability := Experiment (1_000_000); + Put ("Percentage probability of heads on waking:"); + FIO.Put (Probability, 3, 5, 0); +end Sleeping_Beauty; diff --git a/Task/Sleeping-Beauty-problem/Agena/sleeping-beauty-problem.agena b/Task/Sleeping-Beauty-problem/Agena/sleeping-beauty-problem.agena new file mode 100644 index 0000000000..d235047788 --- /dev/null +++ b/Task/Sleeping-Beauty-problem/Agena/sleeping-beauty-problem.agena @@ -0,0 +1,18 @@ +scope # sleeping beauty problem - translated from the Wren sample, via Algol 68 + + local proc sleepingBeauty( reps :: number ) :: number + local wakings, heads := 0, 0; + to reps do + wakings +:= 1; + if math.random() < 0.5 then # default range is [0..1) + heads +:= 1 # [0..0.5) = heads + else + wakings +:= 1 # [0.5..1.0) = tails + fi + od; + printf( "Wakings over %d repetitions = %d\n", reps, wakings ); + return ( heads / wakings ) * 100 + end; + + printf( "Percentage probability of heads on waking = %10.6f%%\n", sleepingBeauty( 1_000_000 ) ) +epocs diff --git a/Task/Sleeping-Beauty-problem/Arturo/sleeping-beauty-problem.arturo b/Task/Sleeping-Beauty-problem/Arturo/sleeping-beauty-problem.arturo index 0c409edb7d..cc92982f13 100644 --- a/Task/Sleeping-Beauty-problem/Arturo/sleeping-beauty-problem.arturo +++ b/Task/Sleeping-Beauty-problem/Arturo/sleeping-beauty-problem.arturo @@ -4,8 +4,8 @@ sleepingBeauty: function [reps][ do.times: reps [ coin: random 0 1 wakings: wakings + 1 - if? coin = 0 -> heads: heads + 1 - else -> wakings: wakings + 1 + switch coin = 0 -> heads: heads + 1 + -> wakings: wakings + 1 ] print ["Wakings over" reps "repetitions =" wakings] return 100.0 * heads//wakings diff --git a/Task/Sleeping-Beauty-problem/C/sleeping-beauty-problem.c b/Task/Sleeping-Beauty-problem/C/sleeping-beauty-problem.c new file mode 100644 index 0000000000..08436446f1 --- /dev/null +++ b/Task/Sleeping-Beauty-problem/C/sleeping-beauty-problem.c @@ -0,0 +1,36 @@ +#include +#include +#include + +#define N 1000000 + +bool coin_toss() { + return rand() & 1; +} + +double run_experiment(int amount) { + int wakings = 0; + int wakings_heads = 0; + + for (int i=0; i 0.5) then + heads = heads + 1 + else + wakings = wakings + 1 + end if + end do + + percent = real(heads) / real(wakings) + +end subroutine sleepingOp + +end program sleepingbeauty diff --git a/Task/Sleeping-Beauty-problem/FutureBasic/sleeping-beauty-problem.basic b/Task/Sleeping-Beauty-problem/FutureBasic/sleeping-beauty-problem.basic index bcffedb249..047d660c75 100644 --- a/Task/Sleeping-Beauty-problem/FutureBasic/sleeping-beauty-problem.basic +++ b/Task/Sleeping-Beauty-problem/FutureBasic/sleeping-beauty-problem.basic @@ -1,17 +1,17 @@ _iterations = 1000000 local fn SleepingBeauty -NSUInteger i -CGFloat heads = 0, sleep = 0 + NSUInteger i + CGFloat heads = 0, sleep = 0 -for i = 1 to _iterations -NSInteger coinToss = int( rnd(2) ) -sleep++ -if coinToss = 1 then heads++ else sleep++ -next + for i = 1 to _iterations + NSInteger coinToss = int( rnd(2) ) + sleep++ + if coinToss = 1 then heads++ else sleep++ + next -printf @"Awakenings over %lld sleep cycles = %.f", _iterations, sleep -printf @"Percent probability of heads on waking = %.4f%%", heads / sleep * 100 + printf @"Awakenings over %lld sleep cycles = %.f", _iterations, sleep + printf @"Percent probability of heads on waking = %.4f%%", heads / sleep * 100 end fn randomize diff --git a/Task/Sleeping-Beauty-problem/GW-BASIC/sleeping-beauty-problem.basic b/Task/Sleeping-Beauty-problem/GW-BASIC/sleeping-beauty-problem.basic index 818d945e81..bdded58f30 100644 --- a/Task/Sleeping-Beauty-problem/GW-BASIC/sleeping-beauty-problem.basic +++ b/Task/Sleeping-Beauty-problem/GW-BASIC/sleeping-beauty-problem.basic @@ -14,7 +14,6 @@ 140 END 150 REM interview if the coin came up heads 160 AWAKE = AWAKE + 1 -170 NHEADS = NHEADS + 1 180 GUESS = INT(RND*2) 190 IF GUESS = HEADS THEN CHEADS = CHEADS + 1 ELSE WTAILS = WTAILS + 1 200 RETURN diff --git a/Task/Sleeping-Beauty-problem/Jq/sleeping-beauty-problem.jq b/Task/Sleeping-Beauty-problem/Jq/sleeping-beauty-problem.jq new file mode 100644 index 0000000000..f882b5fe3a --- /dev/null +++ b/Task/Sleeping-Beauty-problem/Jq/sleeping-beauty-problem.jq @@ -0,0 +1,25 @@ +# Output: a PRN in range(0; .) +def prn: + if . == 1 then 0 + else . as $n + | (($n-1)|tostring|length) as $w + | [limit($w; inputs)] | join("") | tonumber + | if . < $n then . else ($n | prn) end + end; + +def round($ndec): pow(10;$ndec) as $p | . * $p | round / $p; + +# Output: {n, heads, wakings} +def sleepingBeauty: + { n: ., wakings: 0, heads: 0 } + | reduce range(0; .n) as $i (.; + (2|prn) as $coin # heads = 0, tails = 1 say + | .wakings += 1 + | if $coin == 0 then .heads += 1 + else .wakings += 1 + end ); + +1000000 +| sleepingBeauty +| "Wakings over \(.n) repetitions = \(.wakings).", + "Percentage probability of heads on waking = \(100*.heads/.wakings | round(3))%" diff --git a/Task/Sleeping-Beauty-problem/Julia/sleeping-beauty-problem.julia b/Task/Sleeping-Beauty-problem/Julia/sleeping-beauty-problem.jl similarity index 100% rename from Task/Sleeping-Beauty-problem/Julia/sleeping-beauty-problem.julia rename to Task/Sleeping-Beauty-problem/Julia/sleeping-beauty-problem.jl diff --git a/Task/Sleeping-Beauty-problem/Lua/sleeping-beauty-problem.lua b/Task/Sleeping-Beauty-problem/Lua/sleeping-beauty-problem.lua new file mode 100644 index 0000000000..564479512f --- /dev/null +++ b/Task/Sleeping-Beauty-problem/Lua/sleeping-beauty-problem.lua @@ -0,0 +1,18 @@ +do -- sleeping beauty problem - translated from the Wren sample, via Pluto + + local function sleepingBeauty( reps ) + local wakings, heads = 0, 0 + for _ = 1, reps do + wakings = wakings + 1 + if math.random() < 0.5 then + heads = heads + 1 -- [0..0.5) = heads + else + wakings = wakings + 1 -- [0.5..1.0) = tails + end + end + print( "Wakings over " .. reps .. " repetitions = " .. wakings ) + return ( heads / wakings ) * 100 + end + + print( "Percentage probability of heads on waking = " .. sleepingBeauty( 1000000 ) ) +end diff --git a/Task/Sleeping-Beauty-problem/M2000-Interpreter/sleeping-beauty-problem.m2000 b/Task/Sleeping-Beauty-problem/M2000-Interpreter/sleeping-beauty-problem.m2000 new file mode 100644 index 0000000000..fea8c3bd25 --- /dev/null +++ b/Task/Sleeping-Beauty-problem/M2000-Interpreter/sleeping-beauty-problem.m2000 @@ -0,0 +1,27 @@ +10 DUMMY=RANDOM(!TIMECOUNT) +20 MONDAY = 0 : TUESDAY = 1: CHEADS = 0: WTAILS = 0: AWAKE = 0 +30 HEADS = 0 : TAILS = 1: WHEADS = 0: CTAILS = 0: COIN = INT(RND*2) +40 FOR SB = 1 TO 300000 +50 IF COIN = HEADS THEN GOSUB 160 ELSE GOSUB 210 +60 COIN = INT(RND*2) : NEXT SB +70 OPEN "OUTPUT_BEAUTY.TXT" FOR WIDE OUTPUT AS #F +80 PRINT #F, "Sleeping Beauty was put through this experiment ";SB-1;" times." +90 PRINT #F, "She was awoken ";AWAKE;" times." +100 PRINT #F, "She guessed heads ";CHEADS+WHEADS;" times." +110 PRINT #F, "Those guesses were correct ";CHEADS;" times. ";100*CHEADS/(CHEADS+WHEADS);"%" +120 PRINT #F, "She guessed tails ";WTAILS+CTAILS;" times." +130 PRINT #F, "Those guesses were correct ";CTAILS;" times. ";100*CTAILS/(CTAILS+WTAILS);"%" +140 CLOSE #F: REPORT EVAL$(BUFFER("OUTPUT_BEAUTY.TXT")) +150 WIN "NOTEPAD", DIR$+"OUTPUT_BEAUTY.TXT": END +160 REM interview if the coin came up heads +170 AWAKE++ +180 GUESS = INT(RND*2) +190 IF GUESS = HEADS THEN CHEADS++ ELSE WTAILS++ +200 RETURN +210 REM interviews if the coin came up tails +220 FOR DAY = MONDAY TO TUESDAY +230 AWAKE++ +240 GUESS = INT(RND*2) +250 IF GUESS = HEADS THEN WHEADS++ ELSE CTAILS++ +260 NEXT DAY +270 RETURN diff --git a/Task/Sleeping-Beauty-problem/MiniScript/sleeping-beauty-problem.mini b/Task/Sleeping-Beauty-problem/MiniScript/sleeping-beauty-problem.mini new file mode 100644 index 0000000000..6aadc51dc9 --- /dev/null +++ b/Task/Sleeping-Beauty-problem/MiniScript/sleeping-beauty-problem.mini @@ -0,0 +1,18 @@ +// sleeping beauty problem - translated from the Wren sample, via Pluto + +sleepingBeauty = function( reps ) + wakings = 0 + heads = 0 + for _ in range( 1, reps ) + wakings += 1 + if rnd < 0.5 then // rnd returns a randome number in [0..1) + heads += 1 // [0..0.5) = heads + else + wakings += 1 // [0.5..1.0) = tails + end if + end for + print "Wakings over " + reps + " repetitions = " + wakings + return ( heads / wakings ) * 100 +end function + +print "Percentage probability of heads on waking = " + sleepingBeauty( 1000000 ) diff --git a/Task/Sleeping-Beauty-problem/Oberon-07/sleeping-beauty-problem-1.oberon b/Task/Sleeping-Beauty-problem/Oberon-07/sleeping-beauty-problem-1.oberon new file mode 100644 index 0000000000..6560fd41ef --- /dev/null +++ b/Task/Sleeping-Beauty-problem/Oberon-07/sleeping-beauty-problem-1.oberon @@ -0,0 +1,7 @@ +(* Random numbers interface between Oberon-07 and java.util.Random *) +DEFINITION RandomNumbers; + + (* Returns a random integer in the range 0 .. n - 1 *) + PROCEDURE randomInt( n : INTEGER ) : INTEGER; + +END RandomNumbers. diff --git a/Task/Sleeping-Beauty-problem/Oberon-07/sleeping-beauty-problem-2.oberon b/Task/Sleeping-Beauty-problem/Oberon-07/sleeping-beauty-problem-2.oberon new file mode 100644 index 0000000000..e7bd51fcd0 --- /dev/null +++ b/Task/Sleeping-Beauty-problem/Oberon-07/sleeping-beauty-problem-2.oberon @@ -0,0 +1,16 @@ +// java class for the Oberon-07 RandomNumbers module +import java.util.Random; + +public class RandomNumbers +{ + + private static java.util.Random rnd = new java.util.Random(); + + private RandomNumbers(){} // this class can't be instantiated + + public static int randomInt( int n ) + { + return rnd.nextInt( n ); + } // randomInt + +} // RandomNumbers diff --git a/Task/Sleeping-Beauty-problem/Oberon-07/sleeping-beauty-problem-3.oberon b/Task/Sleeping-Beauty-problem/Oberon-07/sleeping-beauty-problem-3.oberon new file mode 100644 index 0000000000..823aa04d40 --- /dev/null +++ b/Task/Sleeping-Beauty-problem/Oberon-07/sleeping-beauty-problem-3.oberon @@ -0,0 +1,27 @@ +(* sleeping beauty problem - translated from the Wren sample *) +MODULE SleepingBeauty; +IMPORT + Out, RandomNumbers; + +VAR pc : REAL; + +PROCEDURE sleepingBeauty( reps : INTEGER ) : REAL; + VAR wakings, heads, i : INTEGER; + BEGIN + wakings := 0; heads := 0; + FOR i := 1 TO reps DO + INC(wakings); + IF RandomNumbers.randomInt( 2 ) = 1 THEN (* 1 = heads, 0 = tails say *) + INC(heads) + ELSE + INC(wakings) + END + END; + Out.String( "Wakings over " );Out.Int( reps, 0 ); + Out.String( " repetitions = " );Out.Int( wakings, 0 );Out.Ln + RETURN ( FLT( heads ) / FLT( wakings ) ) * 100.0 + END sleepingBeauty; +BEGIN + pc := sleepingBeauty( 1000000 ); + Out.String( "Percentage probability of heads on waking = " );Out.Real( pc, 10 );Out.String( "%" );Out.Ln +END SleepingBeauty. diff --git a/Task/Sleeping-Beauty-problem/Phix/sleeping-beauty-problem.phix b/Task/Sleeping-Beauty-problem/Phix/sleeping-beauty-problem.phix index 6454d8a15a..3f67992461 100644 --- a/Task/Sleeping-Beauty-problem/Phix/sleeping-beauty-problem.phix +++ b/Task/Sleeping-Beauty-problem/Phix/sleeping-beauty-problem.phix @@ -1,14 +1,15 @@ -(phixonline)--> - constant iterations = 1_000_000, - fmt = """ - Wakings over %,d repetitions = %,d - Percentage probability of heads on waking = %f%% - """ - integer heads = 0, wakings = 0 - for i=1 to iterations do - integer flip = rand(2) -- 1==heads, 2==tails - wakings += 1 + (flip==2) - heads += (flip==1) - end for - printf(1,fmt,{iterations,wakings,heads/wakings*100}) - - with javascript_semantics - include mpfr.e - string sw = "" - mpz n = mpz_init(), dn = mpz_init() - sequence swp = {}, swdp = {}, dc = repeat(0,10) - integer np = 0 - atom t0 = time(), t1 = time()+1 - while length(swp)<iff(platform()=JS?5:8) do - np += 1 - integer p = get_prime(np) - string sp = sprintf("%d",p) - sw &= sp - mpz_set_str(n,sw,10) - if mpz_prime(n) then - swp = append(swp,{np,p,shorten(sw)}) - end if - for c in sp do - dc[c-'0'+1] += 1 - end for - integer dc9 = dc[10] - if odd(dc9) and remainder(dc9,5)!=0 then - string swdps = join(dc,"",fmt:="%d") - mpz_set_str(dn,swdps,10) - if mpz_prime(dn) then - swdp = append(swdp,{np,swdps}) - end if - end if - if platform()!=JS and time()>t1 then - progress("processing prime %d...\r",{np}) - t1 = time()+1 - end if - end while - printf(1,"Smarandache-Wellin primes:\n") - for i,s in swp do - printf(1," %d%s:",{i,ord(i)}) - printf(1," Index: %4d, Last prime %5d, %s\n",s) - end for - printf(1,"Smarandache-Wellin derived primes:\n") - for i,s in swdp do - printf(1," %d%s:",{i,ord(i)}) - printf(1," Index: %4d, %s\n",s) - end for - ?elapsed(time()-t0) - 2222...223 + return retVal; +} + +// Main execution +let s = getNextSmarandache(7); +console.log("First 25 Smarandache prime-digital sequence numbers:"); +process.stdout.write("2 3 5 7 "); +for (let count = 1; count <= 21; s = getNextSmarandache(s)) { + if (isPrime(s)) { + process.stdout.write(`${s} `); + count++; + } +} +console.log("\n"); + +for (let i = 2; i <= 5; i++) { + const n = Math.pow(10, i); + console.log(`${n.toLocaleString()}th Smarandache prime-digital sequence number = ${getSmarandachePrime(n)}`); +} diff --git a/Task/Smarandache-prime-digital-sequence/Julia/smarandache-prime-digital-sequence.julia b/Task/Smarandache-prime-digital-sequence/Julia/smarandache-prime-digital-sequence.jl similarity index 100% rename from Task/Smarandache-prime-digital-sequence/Julia/smarandache-prime-digital-sequence.julia rename to Task/Smarandache-prime-digital-sequence/Julia/smarandache-prime-digital-sequence.jl diff --git a/Task/Smarandache-prime-digital-sequence/Pluto/smarandache-prime-digital-sequence.pluto b/Task/Smarandache-prime-digital-sequence/Pluto/smarandache-prime-digital-sequence.pluto new file mode 100644 index 0000000000..3c611ffcb9 --- /dev/null +++ b/Task/Smarandache-prime-digital-sequence/Pluto/smarandache-prime-digital-sequence.pluto @@ -0,0 +1,27 @@ +do --[[ find elements of the Smarandache prime-digital sequence + - primes whose digits are all primes + Translated from the Lua sample, extending to the 1000th Smarandache prime + ]] + + -- SIEVE: sieve the primes to 5 000 000 + local sieve, S = {}, 5_000_000 + for i = 2,S do sieve[i]=true end + for i = 2,S do + if sieve[i] then + for j=i*i,S,i do sieve[j]=nil end + end + end + + -- TASKS: + local digs, cans, spds, N = {2,3,5,7}, {0}, {}, 1000 + -- the first trip through the following loop adds the single digit primes to cans + -- subsequent trips add the previous candidates * 10 + the final prime digits + while #spds < N do + local c = cans:remove(1) + for _,d in ipairs(digs) do cans:insert(c*10+d) end + if sieve[c] then spds:insert(c) end + end + print(" 1-25: " .. spds:slice(1,25):concat(" ")) + print(" 100th: " .. spds[ 100]) + print("1000th: " .. spds[1000]) +end diff --git a/Task/Smarandache-prime-digital-sequence/REXX/smarandache-prime-digital-sequence.rexx b/Task/Smarandache-prime-digital-sequence/REXX/smarandache-prime-digital-sequence.rexx index 71aa99ccc1..4f03cb2b5e 100644 --- a/Task/Smarandache-prime-digital-sequence/REXX/smarandache-prime-digital-sequence.rexx +++ b/Task/Smarandache-prime-digital-sequence/REXX/smarandache-prime-digital-sequence.rexx @@ -1,30 +1,61 @@ -/*REXX program lists a sequence of SPDS (Smarandache prime-digital sequence) primes.*/ -parse arg n q /*get optional number of primes to find*/ -if n=='' | n=="," then n= 25 /*Not specified? Then use the default.*/ -if q='' then q= 100 1000 /* " " " " " " */ -say '═══listing the first' n "SPDS primes═══" -call spds n - do i=1 for words(q)+1; y=word(q, i); if y=='' | y=="," then iterate - say - say '═══listing the last of ' y "SPDS primes═══" - call spds -y - end /*i*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -spds: parse arg x 1 ox; x= abs(x) /*obtain the limit to be used for list.*/ - c= 0 /*C number of SPDS primes found so far*/ - #= 0 /*# number of primes found so far*/ - do j=1 by 2 while c0 then iterate j /*Digits ¬prime? Then skip this prime.*/ - c= c + 1 /*bump the number of SPDS primes found.*/ - if ox<0 then iterate /*don't display it, display the last #.*/ - say right(z, 21) /*maybe display this prime ──► terminal*/ - end /*j*/ /* [↑] only display N number of primes*/ - if ox<0 then say right(z, 21) /*display one (the last) SPDS prime. */ - return +-- 24 Aug 2025 +include Setting +numeric digits 12 + +call Time('r') +say 'SMARANDACHE PRIME-DIGITAL SEQUENCE' +say version +say +call Task1 +call Task2 +say Format(Time('e'),,3) 'seconds' +exit + +Task1: +procedure expose prim. +say 'First 25 SPDS primes...' +n = 0 +do i = 1 until n = 25 + if PrimeDigits(i) then do + if Prime(i) then do + n = n+1 + call Charout ,Right(i,9) + if n //10 = 0 then + say + end + end +end +say +say +return + +Task2: +procedure expose prim. +say 'Higher in the sequence...' +n = 4; t = 0 +do i = 23 by 2 until n = 23e3 + if Pos(Right(i,1),37) > 0 then do + if PrimeDigits(i) then do + t = t+1 + if Prime(i) then do + n = n+1 + if n//1000 = 0 then do + say n'th is' i + end + end + end + end +end +say t 'prime tests performed' +say +return + +PrimeDigits: +procedure +arg xx +if Verify(xx,2357) > 0 then + return 0 +else + return 1 + +include Math diff --git a/Task/Smarandache-prime-digital-sequence/Ring/smarandache-prime-digital-sequence.ring b/Task/Smarandache-prime-digital-sequence/Ring/smarandache-prime-digital-sequence.ring index b7f1b6f267..1d64a486e1 100644 --- a/Task/Smarandache-prime-digital-sequence/Ring/smarandache-prime-digital-sequence.ring +++ b/Task/Smarandache-prime-digital-sequence/Ring/smarandache-prime-digital-sequence.ring @@ -1,28 +1,49 @@ load "stdlib.ring" -see "First 25 Smarandache primes:" + nl + nl - +sum = 0 num = 0 -limit = 26 -limit100 = 100 -for n = 1 to 34000 - flag = 0 - nStr = string(n) - for x = 1 to len(nStr) - nx = number(nStr[x]) - if isprime(n) and isprime(nx) - flag = flag + 1 - else - exit - ok - next - if flag = len(nStr) - num = num + 1 - if num < limit - see "" + n + " " - ok - if num = limit100 - see nl + nl + "100th Smarandache prime: " + n + nl - ok - ok +Sma = [] +while true + num += 1 + flag = 0 + numb = 0 + if isPrime(num) + nrStr = string(num) + for n = 1 to len(nrStr) + nrTemp = number(nrStr[n]) + if isPrime(nrTemp) + numb += 1 + if numb = len(nrStr) + add(Sma,num) + sum += 1 + if sum = 100 + exit 2 + ok + ok + else + exit + ok + next + ok +end + +for n = 1 to 25 + if len(string(Sma[n])) = 1 + see " " + Sma[n] + ok + if len(string(Sma[n])) = 2 + see " " + Sma[n] + ok + if len(string(Sma[n])) = 3 + see " " + Sma[n] + ok + if len(string(Sma[n])) = 4 + see " " + Sma[n] + ok + if n%5 = 0 + see nl + ok next + +see nl +see "Hundredth SPDS prime: " + Sma[100] diff --git a/Task/Smarandache-prime-digital-sequence/Rust/smarandache-prime-digital-sequence.rust b/Task/Smarandache-prime-digital-sequence/Rust/smarandache-prime-digital-sequence.rs similarity index 100% rename from Task/Smarandache-prime-digital-sequence/Rust/smarandache-prime-digital-sequence.rust rename to Task/Smarandache-prime-digital-sequence/Rust/smarandache-prime-digital-sequence.rs diff --git a/Task/Smith-numbers/00-TASK.txt b/Task/Smith-numbers/00-TASK.txt index 9e0d265973..1242453803 100644 --- a/Task/Smith-numbers/00-TASK.txt +++ b/Task/Smith-numbers/00-TASK.txt @@ -1,4 +1,4 @@ -[[wp:Smith numbers|Smith numbers]] are numbers such that the [[Sum_digits_of_an_integer|sum of the decimal digits of the integers]] that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. +[[wp:Smith numbers|Smith numbers]] are numbers such that the [[Sum_digits_of_an_integer|sum of the decimal digits of the integers]] that make up that number is the same as the sum of the decimal digits of its prime factors excluding the number itself. By definition, all primes are ''excluded'' as they (naturally) satisfy this condition! diff --git a/Task/Smith-numbers/Ada/smith-numbers.ada b/Task/Smith-numbers/Ada/smith-numbers.adb similarity index 100% rename from Task/Smith-numbers/Ada/smith-numbers.ada rename to Task/Smith-numbers/Ada/smith-numbers.adb diff --git a/Task/Smith-numbers/Arturo/smith-numbers.arturo b/Task/Smith-numbers/Arturo/smith-numbers.arturo index fdea5666b1..b836b771db 100644 --- a/Task/Smith-numbers/Arturo/smith-numbers.arturo +++ b/Task/Smith-numbers/Arturo/smith-numbers.arturo @@ -1,24 +1,8 @@ -digitSum: function [v][ - n: new v - result: new 0 - while [n > 0][ - 'result + n % 10 - 'n / 10 - ] - return result +smith?: function [z][ + (prime? z) ? -> false + -> (sum digits z) = sum map factors.prime z 'num [sum digits num] ] -smith?: function [z][ - return - (prime? z) ? -> false - -> (digitSum z) = sum map factors.prime z 'num [digitSum num] +loop split.every:10 select 1..10000 => smith? 'row [ + print map row 'r -> pad to :string r 6 ] -found: 0 -loop 1..10000 'x [ - if smith? x [ - found: found + 1 - prints (pad to :string x 6) ++ " " - if 0 = found % 10 -> print "" - ] -] -print "" diff --git a/Task/Smith-numbers/EasyLang/smith-numbers.easy b/Task/Smith-numbers/EasyLang/smith-numbers.easy index fd160e7f16..b50430147f 100644 --- a/Task/Smith-numbers/EasyLang/smith-numbers.easy +++ b/Task/Smith-numbers/EasyLang/smith-numbers.easy @@ -1,15 +1,15 @@ -proc prim_fact x . pf[] . - pf[] = [ ] +func[] primfact x . p = 2 repeat if x mod p = 0 - pf[] &= p + r[] &= p x = x div p else p += 1 . until x = 1 . + return r[] . func digsum x . while x > 0 @@ -19,7 +19,7 @@ func digsum x . return sum . for i = 2 to 9999 - prim_fact i pf[] + pf[] = primfact i if len pf[] >= 2 sum = 0 for e in pf[] diff --git a/Task/Smith-numbers/Elixir/smith-numbers.elixir b/Task/Smith-numbers/Elixir/smith-numbers.ex similarity index 100% rename from Task/Smith-numbers/Elixir/smith-numbers.elixir rename to Task/Smith-numbers/Elixir/smith-numbers.ex diff --git a/Task/Smith-numbers/Frink/smith-numbers.frink b/Task/Smith-numbers/Frink/smith-numbers.frink new file mode 100644 index 0000000000..2f0c378749 --- /dev/null +++ b/Task/Smith-numbers/Frink/smith-numbers.frink @@ -0,0 +1,23 @@ +/** Solver for the Rosetta Code problem Smith numbers + + https://rosettacode.org/wiki/Smith_numbers +*/ +for n = 2 to 10000 + if isSmith[n] + print["$n "] + +println[] + +isSmith[n] := +{ + if isPrime[n] + return false + sn = sumDigits[n] + ss = 0 + for [b,p] = factor[n] + ss = ss + sumDigits[b] * p + + return sn == ss +} + +sumDigits[n] := sum[integerDigits[n]] diff --git a/Task/Smith-numbers/Julia/smith-numbers.julia b/Task/Smith-numbers/Julia/smith-numbers.jl similarity index 100% rename from Task/Smith-numbers/Julia/smith-numbers.julia rename to Task/Smith-numbers/Julia/smith-numbers.jl diff --git a/Task/Smith-numbers/Kotlin/smith-numbers.kotlin b/Task/Smith-numbers/Kotlin/smith-numbers.kts similarity index 100% rename from Task/Smith-numbers/Kotlin/smith-numbers.kotlin rename to Task/Smith-numbers/Kotlin/smith-numbers.kts diff --git a/Task/Smith-numbers/Rust/smith-numbers.rust b/Task/Smith-numbers/Rust/smith-numbers.rs similarity index 100% rename from Task/Smith-numbers/Rust/smith-numbers.rust rename to Task/Smith-numbers/Rust/smith-numbers.rs diff --git a/Task/Smith-numbers/Uiua/smith-numbers-1.uiua b/Task/Smith-numbers/Uiua/smith-numbers-1.uiua new file mode 100644 index 0000000000..c7ab69d6e2 --- /dev/null +++ b/Task/Smith-numbers/Uiua/smith-numbers-1.uiua @@ -0,0 +1,7 @@ +N ← 10000 +Primes ← ⇌◌⍢(⊃(▽≠0◿⊸⊸⊢|⊂⊢)|>0⧻)⊙[]↘2⇡N +Candidates ← ▽¬⊸∊Primes↘2⇡ # Exclude primes +SumD ← /+≡⋕°⋕ +PrimeDivisors ← ◌◌⍢(⟜(÷/×)⟜(⊙⊂⊃⋅∘∘)˜▽⟜(=0◿)⊙⟜∘|⋅>₁)Primes ⊙[] +Smith ← ▽⊸≡(=⊃(SumD|/+≡SumD PrimeDivisors)) +⟜⧻ Smith Candidates N diff --git a/Task/Smith-numbers/Uiua/smith-numbers-2.uiua b/Task/Smith-numbers/Uiua/smith-numbers-2.uiua new file mode 100644 index 0000000000..21cc459008 --- /dev/null +++ b/Task/Smith-numbers/Uiua/smith-numbers-2.uiua @@ -0,0 +1,3 @@ +IsSmith ← =∩(/+≡⋕)⊃°⋕(/◇⊂°⋕°/×) +▽⊸≡IsSmith▽⊸≡(≠1⧻°/×)+1⇡10000 +&p$"Number under 10000: _\nFirst ten: _\nLast ten: _"⊃(⧻|↙10|↙¯10) diff --git a/Task/Snake/Ada/snake.ada b/Task/Snake/Ada/snake.adb similarity index 100% rename from Task/Snake/Ada/snake.ada rename to Task/Snake/Ada/snake.adb diff --git a/Task/Snake/Delphi/snake-1.delphi b/Task/Snake/Delphi/snake-1.pas similarity index 100% rename from Task/Snake/Delphi/snake-1.delphi rename to Task/Snake/Delphi/snake-1.pas diff --git a/Task/Snake/Delphi/snake-2.delphi b/Task/Snake/Delphi/snake-2.pas similarity index 100% rename from Task/Snake/Delphi/snake-2.delphi rename to Task/Snake/Delphi/snake-2.pas diff --git a/Task/Snake/EasyLang/snake.easy b/Task/Snake/EasyLang/snake.easy index 43eb3f99a6..5277c626d3 100644 --- a/Task/Snake/EasyLang/snake.easy +++ b/Task/Snake/EasyLang/snake.easy @@ -1,27 +1,24 @@ subr fruit - rx = (randint 20 - 1) * 5 + 2.5 - ry = (randint 20 - 1) * 5 + 2.5 + rx = (random 0 19) * 5 + 2.5 + ry = (random 0 19) * 5 + 2.5 . subr start fruit game = 1 sx[] = [ 52.5 0 0 0 0 ] sy[] = [ 52.5 0 0 0 0 ] - dir = randint 4 + dir = random 1 4 timer 0 . -background 242 -move 30 70 -clear -color 997 -text "SNAKE" -textsize 5 -move 6 40 -text "Keys or mouse for controlling" -move 6 30 -text "Space or click to to start" +gbackground 242 +gclear +gcolor 997 +gtext 30 70 "SNAKE" +gtextsize 5 +gtext 6 40 "Keys or mouse for controlling" +gtext 6 30 "Space or click to start" # -on key +on key_down if game = 0 and keybkey = " " start return @@ -59,16 +56,19 @@ on mouse_down . . . +proc over . + gcolor 997 + gtext 10 10 "Space or click for new game" + game = 2 + timer 1 +. on timer - clear - color 997 - move 2 95 - text "Score: " & 10 * len sx[] - 50 - color 966 - move rx ry - circle 1.5 - # - sx = sx[1] ; sy = sy[1] + if game = 2 + game = 0 + return + . + sx = sx[1] + sy = sy[1] if dir = 1 sy += 5 elif dir = 2 @@ -79,45 +79,44 @@ on timer sx -= 5 . if sx < 0 or sx > 100 or sy < 0 or sy > 100 - game = 0 + over + return . - color 494 for i = len sx[] downto 2 if sx = sx[i] and sy = sy[i] - game = 0 + over + return . + . + gclear + gcolor 997 + gtext 2 95 "Score: " & 10 * len sx[] - 50 + gcolor 966 + gcircle rx ry 1.5 + # + gcolor 494 + for i = len sx[] downto 2 sx[i] = sx[i - 1] sy[i] = sy[i - 1] if sx[i] > 0 - move sx[i] sy[i] - circle 2.5 + gcircle sx[i] sy[i] 2.5 . . - move sx sy - circle 2.5 - color 000 + gcircle sx sy 2.5 + gcolor 000 if dir = 2 or dir = 4 - move sx sy + 1 - circle 0.5 - move sx sy - 1 - circle 0.5 + gcircle sx sy + 1 0.5 + gcircle sx sy - 1 0.5 else - move sx + 1 sy - circle 0.5 - move sx - 1 sy - circle 0.5 + gcircle sx + 1 sy 0.5 + gcircle sx - 1 sy 0.5 . if sx = rx and sy = ry len sx[] len sx[] + 3 len sy[] len sy[] + 3 fruit . - sx[1] = sx ; sy[1] = sy - if game = 1 - timer 0.15 - else - color 997 - move 10 10 - text "Space or click new game" - . + sx[1] = sx + sy[1] = sy + timer 0.15 . diff --git a/Task/Snake/Emacs-Lisp/snake.el b/Task/Snake/Emacs-Lisp/snake.el new file mode 100644 index 0000000000..127dbc0b2c --- /dev/null +++ b/Task/Snake/Emacs-Lisp/snake.el @@ -0,0 +1 @@ +M-x snake diff --git a/Task/Snake/Julia/snake.julia b/Task/Snake/Julia/snake.jl similarity index 100% rename from Task/Snake/Julia/snake.julia rename to Task/Snake/Julia/snake.jl diff --git a/Task/Snake/Kotlin/snake.kotlin b/Task/Snake/Kotlin/snake.kts similarity index 100% rename from Task/Snake/Kotlin/snake.kotlin rename to Task/Snake/Kotlin/snake.kts diff --git a/Task/Snake/Liberty-BASIC/snake.basic b/Task/Snake/Liberty-BASIC/snake.basic new file mode 100644 index 0000000000..e8916fe2bf --- /dev/null +++ b/Task/Snake/Liberty-BASIC/snake.basic @@ -0,0 +1,191 @@ +' ================================ +' SIMPLE SNAKE GAME - Liberty BASIC +' ================================ + +' Graphics constants +global cellSize, gridWidth, gridHeight +global snakeLength, foodX, foodY, gamespeed +global gridOffsetY, score + +cellSize = 20 +gridWidth = 20 +gridHeight = 20 +gridOffsetY = 20 +foodX = 0 +foodY = 0 +gamespeed = 333 +score = 0 + +' Movement directions +global dirX, dirY +dirX = 1 : dirY = 0 ' start moving right + +' Snake body array +dim snakeX(400) +dim snakeY(400) +snakeLength = 5 + +' Initialize snake position in center +for i = 1 to snakeLength + snakeX(i) = 10 - i + snakeY(i) = 10 +next + +' Create first food position +call newFood + +' Open graphics window +WindowWidth = cellSize * gridWidth + 10 +WindowHeight = cellSize * gridHeight + 60 +open "SNAKE GAME - WASD to Move" for graphics_nsb_nf as #g +#g "trapclose [quit]" +#g "down; fill white; flush" + +' Force focus +#g "setfocus" + +' Enable character input +#g "when characterInput [keypress]" + +' Start game timer +[startGame] +timer gamespeed, [gameTick] + +wait + +[gameTick] + + ' Move snake segments + for i = snakeLength to 2 step -1 + snakeX(i) = snakeX(i-1) + snakeY(i) = snakeY(i-1) + next + + ' Head moves in current direction + snakeX(1) = snakeX(1) + dirX + snakeY(1) = snakeY(1) + dirY + + ' Wall collision ends game + if snakeX(1) < 0 or snakeX(1) >= gridWidth _ + or snakeY(1) < 0 or snakeY(1) >= gridHeight then + call gameOver + wait + end if + + ' Check self collision + for i = 2 to snakeLength + if snakeX(1) = snakeX(i) and snakeY(1) = snakeY(i) then + call gameOver + wait + end if + next + + ' Check food collision + if snakeX(1) = foodX and snakeY(1) = foodY then + snakeLength = snakeLength + 1 + score = score + 10 + + ' Initialize new tail segment at same spot as previous tail + snakeX(snakeLength) = snakeX(snakeLength - 1) + snakeY(snakeLength) = snakeY(snakeLength - 1) + + ' Speed up the game + timer 0 + gamespeed = max(gamespeed - 5, 150) + timer gamespeed, [gameTick] + + call newFood + end if + + call redraw +wait + +[keypress] + key$ = Inkey$ + key$ = lower$(key$) + select case key$ + case "w" + if dirY <> 1 then dirX = 0 : dirY = -1 + case "a" + if dirX <> 1 then dirX = -1 : dirY = 0 + case "s" + if dirY <> -1 then dirX = 0 : dirY = 1 + case "d" + if dirX <> -1 then dirX = 1 : dirY = 0 + case chr$(27) ' ESC + call gameOver + wait + end select +wait + +[quit] + close #g + end + +sub redraw + ' Clear screen + #g "cls" + + ' Draw top banner background + #g "color lightgray" + #g, "backcolor lightgray" + #g "place 0 0" + #g "boxfilled "; (gridWidth * cellSize); " "; gridOffsetY + + ' Draw banner text + #g "color black" + #g "font Courier_New 10" + #g "place 5 15" + #g "\"; "Score: "; score; " Speed: "; gamespeed; "ms" + + ' Draw food + call drawBlock foodX, foodY, "red" + + ' Draw snake + for i = 1 to snakeLength + call drawBlock snakeX(i), snakeY(i), "green" + next + + #g "flush" +end sub + +sub drawBlock x, y, color$ + x1 = x * cellSize + y1 = gridOffsetY + y * cellSize + x2 = x1 + cellSize + y2 = y1 + cellSize + + #g "color "; color$ + #g, "backcolor "; color$ + #g "place "; x1; " "; y1 + #g "boxfilled "; x2; " "; y2 +end sub + +sub newFood + overlap = 1 + while overlap = 1 + foodX = int(rnd(0) * gridWidth) + foodY = int(rnd(0) * gridHeight) + overlap = 0 + for i = 1 to snakeLength + if foodX = snakeX(i) and foodY = snakeY(i) then + overlap = 1 + exit for + end if + next + wend +end sub + +sub gameOver + timer 0 + #g "cls" + #g "color black" + #g, "backcolor white" + #g "place 110 200" + #g "font Courier_New 24 bold" + #g "\"; "GAME OVER!" + #g "place 110 250" + #g "font Courier_New 16" + #g "\"; "Score: "; score + #g "flush" +end sub diff --git a/Task/Snake/Locomotive-Basic/snake.basic b/Task/Snake/Locomotive-Basic/snake.basic index d27ab9f0f4..0b887d5a71 100644 --- a/Task/Snake/Locomotive-Basic/snake.basic +++ b/Task/Snake/Locomotive-Basic/snake.basic @@ -1,30 +1,31 @@ 10 mode 1:randomize time -20 sx=20:sy=5:dx=1:dy=0:ml=20:dim ox(ml),oy(ml):oi=1:ll=4:skill=6 +15 ink 0,0:ink 1,6:ink 2,18:ink 3,11 +20 sx=20:sy=5:dx=1:dy=0:ml=20:dim ox(ml),oy(ml):oi=1:ll=4:skill=8 30 f$=chr$(228):w$=chr$(127):b$=chr$(231) -40 print string$(40,w$); +40 pen 3:print string$(40,w$); 50 for i=2 to 20:print w$;space$(38);w$;:next 60 print string$(40,w$); -70 locate 10, 12:print string$(20,w$); +70 locate 11, 11:print string$(20,w$); 80 gosub 260 -90 frame -100 if inkey(1)>-1 then dx=1:dy=0 -110 if inkey(8)>-1 then dx=-1:dy=0 -120 if inkey(0)>-1 then dx=0:dy=-1 -130 if inkey(2)>-1 then dx=0:dy=1 -140 locate sx,sy:print chr$(224);:ox(oi)=sx:oy(oi)=sy +140 locate sx,sy:pen 2:print chr$(224);:ox(oi)=sx:oy(oi)=sy 150 oi=oi+1:if oi>ml then oi=1 160 nx=sx+dx:ny=sy+dy 170 locate nx,ny:a$=copychr$(#0) 180 if a$=w$ or a$=b$ then sound 2,62500/20,100:locate 13,6:print "You have died!":end -190 if a$=f$ then sound 2,62500/500,10: sound 1,62500/1000,10: sound 4,62500/2000,10:p=p+100:print " ";:gosub 260:if ll-1 then dx=1:dy=0 +212 if inkey(8)>-1 then dx=-1:dy=0 +213 if inkey(0)>-1 then dx=0:dy=-1 +214 if inkey(2)>-1 then dx=0:dy=1 +215 next +220 locate sx,sy:pen 2:print b$; 230 nn=1+((oi+ml-ll) mod ml) 240 if ox(nn)>0 then locate ox(nn),oy(nn):print " "; -250 sx=nx:sy=ny:goto 90 +250 sx=nx:sy=ny:goto 140 260 fx=rnd*39+1:fy=rnd*19+1 270 locate fx,fy:a$=copychr$(#0) 280 if a$<>" " then 260 -290 print f$; +290 pen 1:print f$; 300 return diff --git a/Task/Snake/OCaml/snake.ocaml b/Task/Snake/OCaml/snake.ml similarity index 100% rename from Task/Snake/OCaml/snake.ocaml rename to Task/Snake/OCaml/snake.ml diff --git a/Task/Snake/Rust/snake.rust b/Task/Snake/Rust/snake.rs similarity index 100% rename from Task/Snake/Rust/snake.rust rename to Task/Snake/Rust/snake.rs diff --git a/Task/Sockets/Ada/sockets.ada b/Task/Sockets/Ada/sockets.adb similarity index 100% rename from Task/Sockets/Ada/sockets.ada rename to Task/Sockets/Ada/sockets.adb diff --git a/Task/Sockets/AutoIt/sockets.autoit b/Task/Sockets/AutoIt/sockets.au3 similarity index 100% rename from Task/Sockets/AutoIt/sockets.autoit rename to Task/Sockets/AutoIt/sockets.au3 diff --git a/Task/Sockets/C/sockets.c b/Task/Sockets/C/sockets-1.c similarity index 100% rename from Task/Sockets/C/sockets.c rename to Task/Sockets/C/sockets-1.c diff --git a/Task/Sockets/C/sockets-2.c b/Task/Sockets/C/sockets-2.c new file mode 100644 index 0000000000..809fe3ba31 --- /dev/null +++ b/Task/Sockets/C/sockets-2.c @@ -0,0 +1,26 @@ +#include +#include + +// link winsock (MSVC extension. Ignored by MinGW) +#pragma comment(lib, "ws2_32.lib") + +const char MESSAGE[] = "hello socket world"; + +int main() { + WSADATA wsa; + WSAStartup(MAKEWORD(2, 2), &wsa); + SOCKET s = socket(AF_INET, SOCK_STREAM, 0); + + struct sockaddr_in server = { + .sin_family = AF_INET, + .sin_port = htons(256), + .sin_addr.s_addr = inet_addr("127.0.0.1") + }; + + assert(connect(s, (struct sockaddr *)&server, sizeof(server)) == 0); + send(s, MESSAGE, sizeof(MESSAGE) / sizeof(char), 0); + + closesocket(s); + WSACleanup(); + return 0; +} diff --git a/Task/Sockets/Delphi/sockets.delphi b/Task/Sockets/Delphi/sockets.pas similarity index 100% rename from Task/Sockets/Delphi/sockets.delphi rename to Task/Sockets/Delphi/sockets.pas diff --git a/Task/Sockets/Elena/sockets.elena b/Task/Sockets/Elena/sockets.elena index bbcd1cd73c..0e46210661 100644 --- a/Task/Sockets/Elena/sockets.elena +++ b/Task/Sockets/Elena/sockets.elena @@ -5,8 +5,7 @@ import system'io; public program() { - var socket := new Socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); - socket.connect("127.0.0.1",256); + var socket := NativeSocket.connect("127.0.0.1",256); var s := "hello socket world"; socket.write(AnsiEncoder.toByteArray(0, s.Length, s)); socket.close() diff --git a/Task/Sockets/Elixir/sockets.elixir b/Task/Sockets/Elixir/sockets.ex similarity index 100% rename from Task/Sockets/Elixir/sockets.elixir rename to Task/Sockets/Elixir/sockets.ex diff --git a/Task/Sockets/Emacs-Lisp/sockets.l b/Task/Sockets/Emacs-Lisp/sockets.el similarity index 100% rename from Task/Sockets/Emacs-Lisp/sockets.l rename to Task/Sockets/Emacs-Lisp/sockets.el diff --git a/Task/Sockets/F-Sharp/sockets.fs b/Task/Sockets/F-Sharp/sockets.fs new file mode 100644 index 0000000000..a8e662b289 --- /dev/null +++ b/Task/Sockets/F-Sharp/sockets.fs @@ -0,0 +1,8 @@ +open System.Text +open System.Net.Sockets + +let sock = + new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) +sock.Connect("127.0.0.1", 256) +sock.Send(Encoding.UTF8.GetBytes "hello socket world") +sock.Close diff --git a/Task/Sockets/FreeBASIC/sockets.basic b/Task/Sockets/FreeBASIC/sockets.basic index 22e16f8c6d..a5a3a0132d 100644 --- a/Task/Sockets/FreeBASIC/sockets.basic +++ b/Task/Sockets/FreeBASIC/sockets.basic @@ -1,69 +1,74 @@ -' We import the windows sockets library -#Include Once "windows.bi" -#Include Once "win/winsock.bi" +#If Defined(__FB_WIN32__) + #Include Once "win/winsock2.bi" +#ElseIf Defined(__FB_LINUX__) + #Include Once "crt/netdb.bi" + #Include Once "crt/sys/socket.bi" + #Include Once "crt/netinet/in.bi" + #Include Once "crt/arpa/inet.bi" + #Include Once "crt/unistd.bi" + #Include Once "crt/sys/select.bi" +#Else + #Error Platform Not supported +#EndIf -#include "fbgfx.bi" +Type SOCKET As Ulongint -#define NET_BUFLEN 1024 - -'--- SENDER --- - -Dim As WSADATA wsaData +Const NET_BUFLEN = 1024 +Const PORT = 256 +Const HOST = "127.0.0.1" +' Initialize variables +#If Defined(__FB_WIN32__) + Dim As WSADATA wsaData +#EndIf Dim As SOCKET sendSocket Dim As sockaddr_in recvAddr -Dim As Integer port = 256 -Dim As Ubyte sendBuf(NET_BUFLEN-1) -Dim As Integer bufLen = NET_BUFLEN -Dim As Integer iResult Dim As String message = "hello socket world" +Dim As Ubyte sendBuf(NET_BUFLEN-1) +Dim As Integer bufLen = Len(message) -' We copy the message to the buffer -For i As Ubyte = 1 To Len(message) +' Copy message to buffer +For i As Integer = 1 To bufLen sendBuf(i-1) = Cbyte(Asc(Mid(message, i, 1))) Next -' We update bufLen to be the length of the message -bufLen = Len(message) +' Initialize Winsock +If WSAStartup(MAKEWORD(2,2), @wsaData) = 0 Then + ' Create socket + sendSocket = WSASocket(AF_INET, SOCK_DGRAM, IPPROTO_UDP, NULL, 0, 0) -' We initialize Winsock -If (WSAStartup(MAKEWORD(2,2), @wsaData) <> 0) Then - Beep: Print "Error: Winsock init" - Sleep - End -End If + If sendSocket <> INVALID_SOCKET Then + ' Configure server address + With recvAddr + .sin_family = AF_INET + .sin_port = htons(PORT) + .sin_addr.s_addr = inet_addr(HOST) + End With -' We create the socket -sendSocket = socket_(AF_INET, SOCK_DGRAM, IPPROTO_UDP) -If sendSocket = INVALID_SOCKET Then - Beep: Print "Error: Net socket" - WSACleanup() - Sleep - End -End If + ' Send message + Print "Sending message..." + Dim As Integer bytesSent = sendto(sendSocket, @sendBuf(0), bufLen, 0, Cast(sockaddr Ptr, @recvAddr), Sizeof(sockaddr_in)) -' We configure the server structure -recvAddr.sin_family = AF_INET -recvAddr.sin_port = htons(256) -recvAddr.sin_addr.s_addr = inet_addr("127.0.0.1") + If bytesSent <> SOCKET_ERROR Then + Print "Bytes sent: "; bytesSent + Else + Print "Error sending message" + End If -' We send the message -Print "Trying: Net send" -iResult = sendto(sendSocket, @sendBuf(0), bufLen, 0, Cptr(sockaddr Ptr, @recvAddr), Sizeof(recvAddr)) -If (iResult = SOCKET_ERROR) Then - Beep: Print "Error: Net send" - closesocket(sendSocket) - WSACleanup() - Sleep - End + ' Close socket + #If Defined(__fb_win32__) + closesocket(sendSocket) + #Else + Close(sendSocket) + #EndIf + Else + Print "Error creating socket" + End If + + ' Cleanup Winsock + #If Defined(__fb_win32__) + WSACleanup() + #EndIf Else - Print "number of bytes send:"; iResult + Print "Error initializing Winsock" End If - -iResult = closeSocket(sendSocket) -If (iResult < 0) Then - Beep: Print "Error: Close socket" -End If - -'closesocket(sock) -WSACleanup() diff --git a/Task/Sockets/Julia/sockets.julia b/Task/Sockets/Julia/sockets.jl similarity index 100% rename from Task/Sockets/Julia/sockets.julia rename to Task/Sockets/Julia/sockets.jl diff --git a/Task/Sockets/Kotlin/sockets.kotlin b/Task/Sockets/Kotlin/sockets.kts similarity index 100% rename from Task/Sockets/Kotlin/sockets.kotlin rename to Task/Sockets/Kotlin/sockets.kts diff --git a/Task/Sockets/OCaml/sockets-1.ocaml b/Task/Sockets/OCaml/sockets-1.ml similarity index 100% rename from Task/Sockets/OCaml/sockets-1.ocaml rename to Task/Sockets/OCaml/sockets-1.ml diff --git a/Task/Sockets/OCaml/sockets-2.ocaml b/Task/Sockets/OCaml/sockets-2.ml similarity index 100% rename from Task/Sockets/OCaml/sockets-2.ocaml rename to Task/Sockets/OCaml/sockets-2.ml diff --git a/Task/Sockets/Odin/sockets.odin b/Task/Sockets/Odin/sockets.odin new file mode 100644 index 0000000000..20d80e3ba8 --- /dev/null +++ b/Task/Sockets/Odin/sockets.odin @@ -0,0 +1,14 @@ +package main + +import "core:fmt" +import "core:net" + +MSG: string : "hello socket world" + +main :: proc() { + sock, err := net.dial_tcp("127.0.0.1:256") + if err != nil do fmt.panicf("Connection failed: %v", err) + + _, err = net.send(sock, transmute([]u8)MSG) + if err != nil do fmt.panicf("Error sending: %v", err) +} diff --git a/Task/Sockets/Pluto/sockets.pluto b/Task/Sockets/Pluto/sockets.pluto new file mode 100644 index 0000000000..c19390b0c8 --- /dev/null +++ b/Task/Sockets/Pluto/sockets.pluto @@ -0,0 +1,9 @@ +local socket = require "pluto:socket" +local host, port, transport = "localhost", 256, "udp" +local s = socket.connect(host, port, transport) +if s then + s:send("hello socket world") + s:close() +else + print($"Unable to connect to '{host}' on port: {port} using {transport}") +end diff --git a/Task/Sockets/Rust/sockets.rust b/Task/Sockets/Rust/sockets.rs similarity index 100% rename from Task/Sockets/Rust/sockets.rust rename to Task/Sockets/Rust/sockets.rs diff --git a/Task/Sockets/Scheme/sockets.ss b/Task/Sockets/Scheme/sockets.scm similarity index 100% rename from Task/Sockets/Scheme/sockets.ss rename to Task/Sockets/Scheme/sockets.scm diff --git a/Task/Sokoban/Elixir/sokoban.elixir b/Task/Sokoban/Elixir/sokoban.ex similarity index 100% rename from Task/Sokoban/Elixir/sokoban.elixir rename to Task/Sokoban/Elixir/sokoban.ex diff --git a/Task/Sokoban/FreeBASIC/sokoban.basic b/Task/Sokoban/FreeBASIC/sokoban.basic new file mode 100644 index 0000000000..bce308bf16 --- /dev/null +++ b/Task/Sokoban/FreeBASIC/sokoban.basic @@ -0,0 +1,233 @@ +Const NULL As Any Ptr = 0 + +' HashTable with open addressing +Type HashTable + Dim As Integer size + Dim As String entries(Any) +End Type + +Sub HashInit(Byref ht As HashTable, sz As Integer) + ht.size = sz + Redim ht.entries(0 To sz-1) + For i As Integer = 0 To sz-1 + ht.entries(i) = "" ' empty slot marker + Next +End Sub + +Function HashString(s As String, tableSize As Integer) As Integer + Dim As Uinteger h = 5381 + For i As Integer = 0 To Len(s)-1 + h = ((h Shl 5) + h) + Asc(Mid(s,i+1,1)) ' h*33 + c + Next + Return h Mod tableSize +End Function + +Sub HashAdd(Byref ht As HashTable, s As String) + Dim As Integer idx = HashString(s, ht.size) + While ht.entries(idx) <> "" And ht.entries(idx) <> s + idx = (idx + 1) Mod ht.size + Wend + ht.entries(idx) = s +End Sub + +Function HashContains(Byref ht As HashTable, s As String) As Boolean + Dim As Integer idx = HashString(s, ht.size) + While ht.entries(idx) <> "" + If ht.entries(idx) = s Then Return True + idx = (idx + 1) Mod ht.size + Wend + Return False +End Function + +' Sokoban solver +Type State + board As String + moves As String + posic As Integer +End Type + +Type DirType + moveStr As String + pushStr As String + dPos As Integer +End Type + +Function getChar(s As String, lug As Integer) As String + If lug < 0 Or lug >= Len(s) Then Return "#" + Return Mid(s, lug + 1, 1) +End Function + +Function setChar(s As String, lug As Integer, c As String) As String + If lug < 0 Or lug >= Len(s) Then Return s + Return Left(s, lug) & c & Mid(s, lug + 2) +End Function + +Function isWall(c As String) As Boolean + Return c = "#" Or c = Chr(10) Or c = "" +End Function + +' --- Corner deadlock pruning (discard states where a box is stuck in a non-goal corner) --- +Function isDeadlock(board As String, ancho As Integer) As Boolean + For i As Integer = 0 To Len(board)-1 + Dim c As String = Mid(board, i+1, 1) + If c = "$" Then + ' Read neighbor cells around the box + Dim izda As String = getChar(board, i-1) + Dim dcha As String = getChar(board, i+1) + Dim up As String = getChar(board, i-(ancho+1)) + Dim down As String = getChar(board, i+(ancho+1)) + If (isWall(izda) Or isWall(dcha)) And (isWall(up) Or isWall(down)) Then + If getChar(board, i) <> "." Then Return True + End If + End If + Next + Return False +End Function + +Function Move(s As State Ptr, dPos As Integer) As String + Dim As Integer newPos = s->posic + dPos + If newPos < 0 Or newPos >= Len(s->board) Then Return "" + + Dim As String targetChar = getChar(s->board, newPos) + If isWall(targetChar) Then Return "" + If targetChar <> " " And targetChar <> "." Then Return "" + + Dim As String tmp = s->board + Dim As Integer lug = s->posic + Dim As String currentChar = getChar(tmp, lug) + + tmp = Iif(currentChar = "@", setChar(tmp, lug, " "), setChar(tmp, lug, ".")) + tmp = setChar(tmp, newPos, Iif(targetChar = " ", "@", "+")) + Return tmp +End Function + +Function Push(s As State Ptr, dPos As Integer) As String + Dim As Integer newPos = s->posic + dPos + Dim As Integer boxPos = newPos + dPos + If newPos < 0 Or boxPos < 0 Or boxPos >= Len(s->board) Then Return "" + + Dim As String boxChar = getChar(s->board, newPos) + Dim As String targetChar = getChar(s->board, boxPos) + + If boxChar <> "$" And boxChar <> "*" Then Return "" + If isWall(targetChar) Then Return "" + If targetChar <> " " And targetChar <> "." Then Return "" + + Dim As String tmp = s->board + Dim As Integer lug = s->posic + Dim As String currentChar = getChar(tmp, lug) + + tmp = Iif(currentChar = "@", setChar(tmp, lug, " "), setChar(tmp, lug, ".")) + tmp = setChar(tmp, newPos, Iif(boxChar = "$", "@", "+")) + tmp = setChar(tmp, boxPos, Iif(targetChar = " ", "$", "*")) + Return tmp +End Function + +Function isComplete(board As String) As Boolean + Return Instr(board, ".") = 0 And Instr(board, "$") = 0 +End Function + +Function Solve(board As String) As String + Dim As Integer boardLen = Len(board) + Dim As Integer ancho = Instr(board, Chr(10)) - 1 + If ancho <= 0 Then Return "Invalid board" + + Dim As DirType dirs(3) + dirs(0).moveStr = "u": dirs(0).pushStr = "U": dirs(0).dPos = -ancho-1 + dirs(1).moveStr = "r": dirs(1).pushStr = "R": dirs(1).dPos = 1 + dirs(2).moveStr = "d": dirs(2).pushStr = "D": dirs(2).dPos = ancho+1 + dirs(3).moveStr = "l": dirs(3).pushStr = "L": dirs(3).dPos = -1 + + Dim As HashTable visited + HashInit(visited, 200000) ' initial size (tune for fewer collisions) + + HashAdd(visited, board) + + Dim As Integer playerPos = Instr(board, "@") - 1 + If playerPos < 0 Then playerPos = Instr(board, "+") - 1 + If playerPos < 0 Then Return "No player" + + Dim As State Ptr openStates = Callocate(100000, Sizeof(State)) + Dim As Integer head = 0, tail = 0, capacity = 100000 + + openStates[tail].board = board + openStates[tail].moves = "" + openStates[tail].posic = playerPos + tail += 1 + + While head < tail + If tail > 1000000 Then + Deallocate(openStates) + Return "Too complex" + End If + + Dim As State current = openStates[head] + head += 1 + + For i As Integer = 0 To 3 + Dim As DirType currentDir = dirs(i) + Dim As Integer newPos = current.posic + currentDir.dPos + + If newPos < 0 Or newPos >= boardLen Then Continue For + Dim As String targetChar = getChar(current.board, newPos) + If isWall(targetChar) Then Continue For + + Dim As String newBoard = "" + Dim As String newSol = current.moves + + If targetChar = "$" Or targetChar = "*" Then + newBoard = Push(@current, currentDir.dPos) + If Len(newBoard) > 0 Then newSol += currentDir.pushStr + Elseif targetChar = " " Or targetChar = "." Then + newBoard = Move(@current, currentDir.dPos) + If Len(newBoard) > 0 Then newSol += currentDir.moveStr + End If + + If Len(newBoard) > 0 Andalso newBoard <> current.board Then + If isDeadlock(newBoard, ancho) Then Continue For + + If isComplete(newBoard) Then + Deallocate(openStates) + Return newSol + End If + If Not HashContains(visited, newBoard) Then + HashAdd(visited, newBoard) + If tail >= capacity Then + capacity += 50000 + Dim As State Ptr tmpPtr = Reallocate(openStates, capacity * Sizeof(State)) + If tmpPtr = NULL Then + Deallocate(openStates) + Return "Out of memory" + End If + openStates = tmpPtr + End If + openStates[tail].board = newBoard + openStates[tail].moves = newSol + Dim As Integer np = Instr(newBoard, "@") - 1 + If np < 0 Then np = Instr(newBoard, "+") - 1 + openStates[tail].posic = np + tail += 1 + End If + End If + Next + Wend + + Deallocate(openStates) + Return "No solution" +End Function + +' Main program +Dim level As String = _ +"#######" & Chr(10) & _ +"# #" & Chr(10) & _ +"# #" & Chr(10) & _ +"#. # #" & Chr(10) & _ +"#. $$ #" & Chr(10) & _ +"#.$$ #" & Chr(10) & _ +"#.# @#" & Chr(10) & _ +"#######" + +Print "level:" & Chr(10) & level +Print "Solution:" & Chr(10) & Solve(level) + +Sleep diff --git a/Task/Sokoban/JavaScript/sokoban.js b/Task/Sokoban/JavaScript/sokoban.js new file mode 100644 index 0000000000..f5889d7643 --- /dev/null +++ b/Task/Sokoban/JavaScript/sokoban.js @@ -0,0 +1,130 @@ +class Sokoban { + constructor(board) { + this.nCols = board[0].length; + let destBuf = ''; + let currBuf = ''; + + for (let r = 0; r < board.length; r++) { + for (let c = 0; c < this.nCols; c++) { + const ch = board[r].charAt(c); + + destBuf += (ch !== '$' && ch !== '@') ? ch : ' '; + currBuf += (ch !== '.') ? ch : ' '; + + if (ch === '@') { + this.playerX = c; + this.playerY = r; + } + } + } + this.destBoard = destBuf; + this.currBoard = currBuf; + } + + move(x, y, dx, dy, trialBoard) { + const newPlayerPos = (y + dy) * this.nCols + x + dx; + + if (trialBoard.charAt(newPlayerPos) !== ' ') { + return null; + } + + const trial = trialBoard.split(''); + trial[y * this.nCols + x] = ' '; + trial[newPlayerPos] = '@'; + + return trial.join(''); + } + + push(x, y, dx, dy, trialBoard) { + const newBoxPos = (y + 2 * dy) * this.nCols + x + 2 * dx; + + if (trialBoard.charAt(newBoxPos) !== ' ') { + return null; + } + + const trial = trialBoard.split(''); + trial[y * this.nCols + x] = ' '; + trial[(y + dy) * this.nCols + x + dx] = '@'; + trial[newBoxPos] = '$'; + + return trial.join(''); + } + + isSolved(trialBoard) { + for (let i = 0; i < trialBoard.length; i++) { + if ((this.destBoard.charAt(i) === '.') !== (trialBoard.charAt(i) === '$')) { + return false; + } + } + return true; + } + + solve() { + class Board { + constructor(cur, sol, x, y) { + this.cur = cur; + this.sol = sol; + this.x = x; + this.y = y; + } + } + + const dirLabels = [['u', 'U'], ['r', 'R'], ['d', 'D'], ['l', 'L']]; + const dirs = [[0, -1], [1, 0], [0, 1], [-1, 0]]; + + const history = new Set(); + const open = []; + + history.add(this.currBoard); + open.push(new Board(this.currBoard, "", this.playerX, this.playerY)); + + while (open.length > 0) { + const item = open.shift(); // poll() equivalent + const cur = item.cur; + const sol = item.sol; + const x = item.x; + const y = item.y; + + for (let i = 0; i < dirs.length; i++) { + let trial = cur; + const dx = dirs[i][0]; + const dy = dirs[i][1]; + + // are we standing next to a box? + if (trial.charAt((y + dy) * this.nCols + x + dx) === '$') { + // can we push it? + trial = this.push(x, y, dx, dy, trial); + if (trial !== null) { + // or did we already try this one? + if (!history.has(trial)) { + const newSol = sol + dirLabels[i][1]; + + if (this.isSolved(trial)) { + return newSol; + } + + open.push(new Board(trial, newSol, x + dx, y + dy)); + history.add(trial); + } + } + // otherwise try changing position + } else { + trial = this.move(x, y, dx, dy, trial); + if (trial !== null) { + if (!history.has(trial)) { + const newSol = sol + dirLabels[i][0]; + open.push(new Board(trial, newSol, x + dx, y + dy)); + history.add(trial); + } + } + } + } + } + return "No solution"; + } +} + +// Example usage +const level = "#######,# #,# #,#. # #,#. $$ #,#.$$ #,#.# @#,#######"; +const sokoban = new Sokoban(level.split(",")); +console.log(sokoban.solve()); diff --git a/Task/Sokoban/Julia/sokoban.julia b/Task/Sokoban/Julia/sokoban.jl similarity index 100% rename from Task/Sokoban/Julia/sokoban.julia rename to Task/Sokoban/Julia/sokoban.jl diff --git a/Task/Sokoban/Kotlin/sokoban.kotlin b/Task/Sokoban/Kotlin/sokoban.kts similarity index 100% rename from Task/Sokoban/Kotlin/sokoban.kotlin rename to Task/Sokoban/Kotlin/sokoban.kts diff --git a/Task/Sokoban/OCaml/sokoban.ocaml b/Task/Sokoban/OCaml/sokoban.ml similarity index 100% rename from Task/Sokoban/OCaml/sokoban.ocaml rename to Task/Sokoban/OCaml/sokoban.ml diff --git a/Task/Sokoban/Pluto/sokoban.pluto b/Task/Sokoban/Pluto/sokoban.pluto new file mode 100644 index 0000000000..0de64650e0 --- /dev/null +++ b/Task/Sokoban/Pluto/sokoban.pluto @@ -0,0 +1,108 @@ +require "map" +require "list" + +class board + function __construct(public cur, public sol, public x, public y) end +end + +class sokoban + function __construct(brd) + self.dest_board = "" + self.curr_board = "" + self.ncols = #brd[1] + self.player_x = 0 + self.player_y = 0 + for r = 1, #brd do + for c = 1, self.ncols do + local ch = brd[r][c] + self.dest_board ..= (ch != "$" and ch != "@") ? ch : " " + self.curr_board ..= (ch != ".") ? ch : " " + if ch == "@" then + self.player_x = c - 1 + self.player_y = r - 1 + end + end + end + end + + function move(x, y, dx, dy, trial_board) + local new_player_pos = (y + dy) * self.ncols + x + dx + 1 + if trial_board[new_player_pos] != " " then return "" end + local trial = trial_board:split("") + trial[y * self.ncols + x + 1] = " " + trial[new_player_pos] = "@" + return trial:concat("") + end + + function push(x, y, dx, dy, trial_board) + local new_box_pos = (y + 2 * dy) * self.ncols + x + 2 * dx + 1 + if trial_board[new_box_pos] != " " then return "" end + local trial = trial_board:split("") + trial[y * self.ncols + x + 1] = " " + trial[(y + dy) * self.ncols + x + dx + 1] = "@" + trial[new_box_pos] = "$" + return trial:concat("") + end + + function is_solved(trial_board) + for i = 1, #trial_board do + if (self.dest_board[i] == ".") != (trial_board[i] == "$") then return false end + end + return true + end + + function solve() + local dir_labels = { {"u", "U"}, {"r", "R"}, {"d", "D"}, {"l", "L"} } + local dirs = { {0, -1}, {1, 0}, {0, 1}, {-1, 0} } + local history = new set() + history:add(self.curr_board) + local open = new dlist() + open:push(new board(self.curr_board, "", self.player_x, self.player_y)) + + while !open:empty() do + local b = open:remove(1) + for i = 1, #dirs do + local trial = b.cur + local dx = dirs[i][1] + local dy = dirs[i][2] + + -- Are we standing next to a box ? + if trial[(b.y + dy) * self.ncols + b.x + dx + 1] == "$" then + -- Can we push it ? + trial = self:push(b.x, b.y, dx, dy, trial) + if trial != "" then + -- Or did we already try this one ? + if !history:contains(trial) then + local newsol = b.sol .. dir_labels[i][2] + if self:is_solved(trial) then return newsol end + open:push(new board(trial, newsol, b.x + dx, b.y + dy)) + history:add(trial) + end + end + else -- otherwise try changing position + trial = self:move(b.x, b.y, dx, dy, trial) + if trial != "" and !history:contains(trial) then + local newsol = b.sol .. dir_labels[i][1] + open:push(new board(trial, newsol, b.x + dx, b.y + dy)) + history:add(trial) + end + end + end + end + return "No solution" + end +end + +local level = { + "#######", + "# #", + "# #", + "#. # #", + "#. $$ #", + "#.$$ #", + "#.# @#", + "#######" +} +print(level:concat("\n")) +print() +print(new sokoban(level):solve()) diff --git a/Task/Sokoban/Rust/sokoban.rs b/Task/Sokoban/Rust/sokoban.rs new file mode 100644 index 0000000000..3996412185 --- /dev/null +++ b/Task/Sokoban/Rust/sokoban.rs @@ -0,0 +1,173 @@ +use std::collections::{HashSet, VecDeque}; +use regex::Regex; + +#[derive(Debug, Clone)] +struct Board { + s_data: Vec>, + d_data: Vec>, + px: usize, + py: usize, +} + +impl Board { + fn new(board_str: &str) -> Self { + let pattern = Regex::new(r"([^\n]+)\n?").unwrap(); + let mut data = Vec::new(); + let mut w = 0; + + for cap in pattern.captures_iter(board_str) { + let line = cap[1].to_string(); + w = w.max(line.len()); + data.push(line); + } + + let mut s_data = Vec::new(); + let mut d_data = Vec::new(); + let mut px = 0; + let mut py = 0; + + for (v, line) in data.iter().enumerate() { + let mut s_temp = Vec::new(); + let mut d_temp = Vec::new(); + + for u in 0..w { + let (s, d) = if u >= line.len() { + (' ', ' ') + } else { + let c = line.chars().nth(u).unwrap(); + let mut s = ' '; + let mut d = ' '; + + match c { + '#' => s = '#', + '.' | '*' | '+' => s = '.', + _ => {} + } + + match c { + '@' | '+' => { + d = '@'; + px = u; + py = v; + } + '$' | '*' => d = '*', + _ => {} + } + + (s, d) + }; + + s_temp.push(s); + d_temp.push(d); + } + + s_data.push(s_temp); + d_data.push(d_temp); + } + + Board { + s_data, + d_data, + px, + py, + } + } + + fn move_player(&self, x: usize, y: usize, dx: i32, dy: i32, data: &mut Vec>) -> bool { + let new_x = (x as i32 + dx) as usize; + let new_y = (y as i32 + dy) as usize; + + if self.s_data[new_y][new_x] == '#' || data[new_y][new_x] != ' ' { + return false; + } + + data[y][x] = ' '; + data[new_y][new_x] = '@'; + + true + } + + fn push_box(&self, x: usize, y: usize, dx: i32, dy: i32, data: &mut Vec>) -> bool { + let new_x = (x as i32 + dx) as usize; + let new_y = (y as i32 + dy) as usize; + let box_x = (x as i32 + 2 * dx) as usize; + let box_y = (y as i32 + 2 * dy) as usize; + + if self.s_data[box_y][box_x] == '#' || data[box_y][box_x] != ' ' { + return false; + } + + data[y][x] = ' '; + data[new_y][new_x] = '@'; + data[box_y][box_x] = '*'; + + true + } + + fn is_solved(&self, data: &Vec>) -> bool { + for (v, row) in data.iter().enumerate() { + for (u, &cell) in row.iter().enumerate() { + if (self.s_data[v][u] == '.') != (cell == '*') { + return false; + } + } + } + true + } + + fn solve(&self) -> String { + let mut visited = HashSet::new(); + let mut open = VecDeque::new(); + + open.push_back((self.d_data.clone(), String::new(), self.px, self.py)); + visited.insert(self.d_data.clone()); + + let dirs = [ + (0, -1, 'u', 'U'), + (1, 0, 'r', 'R'), + (0, 1, 'd', 'D'), + (-1, 0, 'l', 'L'), + ]; + + while let Some((cur, c_sol, x, y)) = open.pop_front() { + for &(dx, dy, move_char, push_char) in &dirs { + let mut temp = cur.clone(); + let new_x = (x as i32 + dx) as usize; + let new_y = (y as i32 + dy) as usize; + + if temp[new_y][new_x] == '*' { + if self.push_box(x, y, dx, dy, &mut temp) && !visited.contains(&temp) { + if self.is_solved(&temp) { + return c_sol + &push_char.to_string(); + } + open.push_back((temp.clone(), c_sol.clone() + &push_char.to_string(), new_x, new_y)); + visited.insert(temp); + } + } else if self.move_player(x, y, dx, dy, &mut temp) && !visited.contains(&temp) { + if self.is_solved(&temp) { + return c_sol + &move_char.to_string(); + } + open.push_back((temp.clone(), c_sol.clone() + &move_char.to_string(), new_x, new_y)); + visited.insert(temp); + } + } + } + + "No solution".to_string() + } +} + +fn main() { + let level = "#######\n\ + # #\n\ + # #\n\ + #. # #\n\ + #. $$ #\n\ + #.$$ #\n\ + #.# @#\n\ + #######"; + + let board = Board::new(level); + println!("{}\n", level); + println!("{}", board.solve()); +} diff --git a/Task/Sokoban/V-(Vlang)/sokoban.v b/Task/Sokoban/V-(Vlang)/sokoban.v new file mode 100644 index 0000000000..a750fbf394 --- /dev/null +++ b/Task/Sokoban/V-(Vlang)/sokoban.v @@ -0,0 +1,175 @@ +struct Board { + cur string + sol string + xir int + yir int +} + +struct Direction { + dxir int + dyir int +} + +struct Queue { + mut: + data []Board +} + +fn (mut que Queue) push(brd Board) { + que.data << brd +} + +fn (mut que Queue) pop() ?Board { + if que.data.len == 0 { return none } + item := que.data[0] + que.data = que.data[1..] + return item +} + +fn (que Queue) is_empty() bool { + return que.data.len == 0 +} + +struct Sokoban { + n_cols int + dest_board string + curr_board string + player_x int + player_y int +} + +fn new_sokoban(board []string) Sokoban { + n_cols := board[0].len + mut dest_buf := []u8{} + mut curr_buf := []u8{} + mut player_x := 0 + mut player_y := 0 + for ral in 0 .. board.len { + for cal in 0 .. n_cols { + ch := board[ral][cal] + dest_buf << if ch != `$` && ch != `@` { ch } else { ` ` } + curr_buf << if ch != `.` { ch } else { ` ` } + if ch == `@` { + player_x = cal + player_y = ral + } + } + } + + return Sokoban{ + n_cols: n_cols + dest_board: dest_buf.bytestr() + curr_board: curr_buf.bytestr() + player_x: player_x + player_y: player_y + } +} + +fn (skn Sokoban) move(xir int, yir int, dxir int, dyir int, trial_board string) string { + new_pos := (yir + dyir) * skn.n_cols + xir + dxir + if trial_board[new_pos] != ` ` { return "" } + mut trial := trial_board.bytes() + trial[yir * skn.n_cols + xir] = ` ` + trial[new_pos] = `@` + return trial.bytestr() +} + +fn (skn Sokoban) push(xir int, yir int, dxir int, dyir int, trial_board string) string { + new_box_pos := (yir + 2 * dyir) * skn.n_cols + xir + 2 * dxir + if trial_board[new_box_pos] != ` ` { return "" } + mut trial := trial_board.bytes() + trial[yir * skn.n_cols + xir] = ` ` + trial[(yir + dyir) * skn.n_cols + xir + dxir] = `@` + trial[new_box_pos] = `$` + return trial.bytestr() +} + +fn (skn Sokoban) is_solved(trial_board string) bool { + for ial in 0 .. trial_board.len { + if (skn.dest_board[ial] == `.`) != (trial_board[ial] == `$`) { return false } + } + return true +} + +fn (skn Sokoban) solve() string { + dir_labels := [`u`, `r`, `d`, `l`] + dir_labels_caps := [`U`, `R`, `D`, `L`] + dirs := [ + Direction{dxir: 0, dyir: -1}, + Direction{dxir: 1, dyir: 0}, + Direction{dxir: 0, dyir: 1}, + Direction{dxir: -1, dyir: 0}, + ] + mut trial := "" + mut open := Queue{} + mut history := map[string]bool{} + history[skn.curr_board] = true + open.push(Board{ + cur: skn.curr_board + sol: "" + xir: skn.player_x + yir: skn.player_y + }) + for !open.is_empty() { + cur_board := open.pop() or { break } + cur := cur_board.cur + sol := cur_board.sol + xir := cur_board.xir + yir := cur_board.yir + + for i in 0 .. dirs.len { + dxir := dirs[i].dxir + dyir := dirs[i].dyir + trial = cur + if trial[(yir + dyir) * skn.n_cols + xir + dxir] == `$` { + trial = skn.push(xir, yir, dxir, dyir, trial) + if trial != "" && !history[trial] { + new_sol := sol + dir_labels_caps[i].str() + if skn.is_solved(trial) { return new_sol } + open.push(Board{ + cur: trial + sol: new_sol + xir: xir + dxir + yir: yir + dyir + }) + history[trial] = true + } + } + else + { + trial = skn.move(xir, yir, dxir, dyir, trial) + if trial != "" && !history[trial] { + new_sol := sol + dir_labels[i].str() + open.push(Board{ + cur: trial + sol: new_sol + xir: xir + dxir + yir: yir + dyir + }) + history[trial] = true + } + } + } + } + return "No solution" +} + +fn main() { + level := [ + "#######", + "# #", + "# #", + "#. # #", + "#. $$ #", + "#.$$ #", + "#.# @#", + "#######", + ] + + for line in level { + println(line) + } + println("") + sokoban := new_sokoban(level) + println(sokoban.solve()) +} diff --git a/Task/Soloways-recurring-rainfall/ALGOL-68/soloways-recurring-rainfall.alg b/Task/Soloways-recurring-rainfall/ALGOL-68/soloways-recurring-rainfall.alg index 9f56d61de4..6dc094d11d 100644 --- a/Task/Soloways-recurring-rainfall/ALGOL-68/soloways-recurring-rainfall.alg +++ b/Task/Soloways-recurring-rainfall/ALGOL-68/soloways-recurring-rainfall.alg @@ -1,4 +1,4 @@ -BEGIN # read a sequence of integers, terminated by 99999 and outpout their average # +BEGIN # read a sequence of integers, terminated by 99999 and output their average # INT end value = 99999; INT sum := 0; INT count := 0; diff --git a/Task/Soloways-recurring-rainfall/AWK/soloways-recurring-rainfall.awk b/Task/Soloways-recurring-rainfall/AWK/soloways-recurring-rainfall.awk new file mode 100644 index 0000000000..0bea5f41a6 --- /dev/null +++ b/Task/Soloways-recurring-rainfall/AWK/soloways-recurring-rainfall.awk @@ -0,0 +1,24 @@ +BEGIN { + if (!sentinel) sentinel = 99999 + print("Enter the rainfall values (" sentinel " to quit):") +} + +$0 == sentinel { + exit +} + +/^-?[0-9]+$/ { + total += $1 + count++ + next +} + +{ + print("Ignoring \"" $0 "\", please enter only integers.") +} + +END { + if (count > 0) { + print("The average rainfall is", total / count) + } +} diff --git a/Task/Soloways-recurring-rainfall/Ada/soloways-recurring-rainfall.ada b/Task/Soloways-recurring-rainfall/Ada/soloways-recurring-rainfall.adb similarity index 100% rename from Task/Soloways-recurring-rainfall/Ada/soloways-recurring-rainfall.ada rename to Task/Soloways-recurring-rainfall/Ada/soloways-recurring-rainfall.adb diff --git a/Task/Soloways-recurring-rainfall/Agena/soloways-recurring-rainfall.agena b/Task/Soloways-recurring-rainfall/Agena/soloways-recurring-rainfall.agena new file mode 100644 index 0000000000..eefa3f5725 --- /dev/null +++ b/Task/Soloways-recurring-rainfall/Agena/soloways-recurring-rainfall.agena @@ -0,0 +1,27 @@ +scope # read a sequence of integers, terminated by 99999 and output their average + local constant endValue := 99999; + local sum, count, n := 0, 0, 0; + + while n <> endValue do + printf( "Enter rainfall (integer) or %d to quit: ", endValue ); + try + local v := io.read(); + if v = null then + print( "End of input detected" ); + n := endValue + else + n := tonumber( v ); + if not isint( n ) then + error( "Not an integer" ) + elif n <> endValue then + sum +:= n; + count +:= 1; + printf( "\t\t\t\t\t\tNew average: %f\n", sum / count ) + fi + fi + catch + print( "Please enter an integer" ); + n := 0 + yrt + od +end diff --git a/Task/Soloways-recurring-rainfall/Arturo/soloways-recurring-rainfall.arturo b/Task/Soloways-recurring-rainfall/Arturo/soloways-recurring-rainfall.arturo index 77d529e70c..f727202440 100644 --- a/Task/Soloways-recurring-rainfall/Arturo/soloways-recurring-rainfall.arturo +++ b/Task/Soloways-recurring-rainfall/Arturo/soloways-recurring-rainfall.arturo @@ -3,11 +3,12 @@ sum: 0 while ø [ n: input "Enter rainfall as integer (99999 to quit): " - try? -> n: to :integer n - else [ + + if throws? -> n: to :integer n [ print "Input must be an integer." continue ] + if 99999 = n -> break 'i + 1 'sum + n diff --git a/Task/Soloways-recurring-rainfall/COBOL/soloways-recurring-rainfall.cob b/Task/Soloways-recurring-rainfall/COBOL/soloways-recurring-rainfall.cob new file mode 100644 index 0000000000..94fe0c07b8 --- /dev/null +++ b/Task/Soloways-recurring-rainfall/COBOL/soloways-recurring-rainfall.cob @@ -0,0 +1,22 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. SOLOWAY. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 AVERAGE PIC 9(9)V9(9) VALUE ZERO. + 01 AMOUNT PIC 9(9) VALUE ZERO. + 01 CURRENT PIC 9(9). + 01 OUTPUT-VAL PIC Z(8)9.9(9). + + PROCEDURE DIVISION. + READ-VALUE. + ACCEPT CURRENT. + IF CURRENT IS EQUAL TO 99999, GO TO DONE. + ADD 1 TO AMOUNT. + COMPUTE AVERAGE = + AVERAGE * (AMOUNT - 1) / AMOUNT + CURRENT / AMOUNT. + GO TO READ-VALUE. + DONE. + MOVE AVERAGE TO OUTPUT-VAL. + DISPLAY OUTPUT-VAL. + STOP RUN. diff --git a/Task/Soloways-recurring-rainfall/Crystal/soloways-recurring-rainfall.cr b/Task/Soloways-recurring-rainfall/Crystal/soloways-recurring-rainfall.cr new file mode 100644 index 0000000000..026e8330b8 --- /dev/null +++ b/Task/Soloways-recurring-rainfall/Crystal/soloways-recurring-rainfall.cr @@ -0,0 +1,20 @@ +require "big" + +sum = 0.to_big_i +cnt = 0 + +puts "At each prompt enter an integer between -2³¹ and 2³¹-1" +puts "and I'll tell you the cumulative average. Enter 99999 to quit." + +loop do + print "> "; STDOUT.flush + begin + num = (gets || break).to_i + break if num == 99999 + sum += num + cnt += 1 + puts "CA=#{sum / cnt}" + rescue + puts "invalid input ignored" + end +end diff --git a/Task/Soloways-recurring-rainfall/Delphi/soloways-recurring-rainfall.delphi b/Task/Soloways-recurring-rainfall/Delphi/soloways-recurring-rainfall.pas similarity index 100% rename from Task/Soloways-recurring-rainfall/Delphi/soloways-recurring-rainfall.delphi rename to Task/Soloways-recurring-rainfall/Delphi/soloways-recurring-rainfall.pas diff --git a/Task/Soloways-recurring-rainfall/Julia/soloways-recurring-rainfall.julia b/Task/Soloways-recurring-rainfall/Julia/soloways-recurring-rainfall.jl similarity index 100% rename from Task/Soloways-recurring-rainfall/Julia/soloways-recurring-rainfall.julia rename to Task/Soloways-recurring-rainfall/Julia/soloways-recurring-rainfall.jl diff --git a/Task/Soloways-recurring-rainfall/Pluto/soloways-recurring-rainfall.pluto b/Task/Soloways-recurring-rainfall/Pluto/soloways-recurring-rainfall.pluto new file mode 100644 index 0000000000..286d039fd3 --- /dev/null +++ b/Task/Soloways-recurring-rainfall/Pluto/soloways-recurring-rainfall.pluto @@ -0,0 +1,14 @@ +local n = 0 +local sum = 0 +while true do + io.write("Enter integral rainfall (99999 to quit): ") + local i = tonumber(io.read()) + if !(i and i % 1 == 0) then + print("Must be an integer, try again.") + continue + end + if i == 99999 then break end + ++n + sum += i + print($" The current average rainfall is {sum / n}") +end diff --git a/Task/Soloways-recurring-rainfall/R/soloways-recurring-rainfall.r b/Task/Soloways-recurring-rainfall/R/soloways-recurring-rainfall.r new file mode 100644 index 0000000000..8ecb9b9c83 --- /dev/null +++ b/Task/Soloways-recurring-rainfall/R/soloways-recurring-rainfall.r @@ -0,0 +1,22 @@ +soloway <- function(){ + vals <- numeric(0) + repeat{ + entry <- readline(prompt="Enter integer rainfall value (99999 to quit): ") + if(is.na(as.numeric(entry))){ + cat("Input must be numeric, please re-enter", "\n") + entry <- NULL + } + entry <- as.numeric(entry) + if(length(entry)>0){ + if(entry%%1!=0){ + cat("Input must be an integer, please re-enter", "\n") + entry <- NULL + } + } + vals <- c(vals, entry) + if(99999 %in% vals) break + cat("Average rainfall:", mean(vals)) + } +} + +soloway() diff --git a/Task/Soloways-recurring-rainfall/Rust/soloways-recurring-rainfall.rust b/Task/Soloways-recurring-rainfall/Rust/soloways-recurring-rainfall.rs similarity index 100% rename from Task/Soloways-recurring-rainfall/Rust/soloways-recurring-rainfall.rust rename to Task/Soloways-recurring-rainfall/Rust/soloways-recurring-rainfall.rs diff --git a/Task/Solve-a-Hidato-puzzle/00-TASK.txt b/Task/Solve-a-Hidato-puzzle/00-TASK.txt index a23202b09c..6705fafb29 100644 --- a/Task/Solve-a-Hidato-puzzle/00-TASK.txt +++ b/Task/Solve-a-Hidato-puzzle/00-TASK.txt @@ -24,7 +24,7 @@ has the following solution, with path marked on it: * [[A* search algorithm]] * [[N-queens problem]] * [[Solve a Holy Knight's tour]] -* [[Solve a Knight's tour]] +* [[Knight's tour]] * [[Solve a Hopido puzzle]] * [[Solve a Numbrix puzzle]] * [[Solve the no connection puzzle]]; diff --git a/Task/Solve-a-Hidato-puzzle/ALGOL-68/solve-a-hidato-puzzle.alg b/Task/Solve-a-Hidato-puzzle/ALGOL-68/solve-a-hidato-puzzle.alg new file mode 100644 index 0000000000..cf4c92879f --- /dev/null +++ b/Task/Solve-a-Hidato-puzzle/ALGOL-68/solve-a-hidato-puzzle.alg @@ -0,0 +1,92 @@ +BEGIN # solve a Hikado puzzle - algorithm based on the Wren solution # + PR read "sort.incl.a68" PR # include sort utilities # + + INT x = -1; # non existent board element # + INT o = 0; # unoccupied board element # + + # returns TRUE if a solution for board with the specified given values # + # ( the values initially placed on the board ) can be found # + # n is the value to place, r and c the starting row and column # + # and next the position of the next value in given # + # returns FALSE if a solution cannot be found # + PROC solve board with givens = ( REF[,]INT board, []INT given, INT r, c, n, next )BOOL: + IF n > given[ UPB given ] + THEN TRUE + ELIF r < 1 LWB board OR r > 1 UPB board + OR c < 2 LWB board OR c > 2 UPB board + THEN FALSE + ELIF INT back = board[ r, c ]; + back /= 0 AND back /= n + THEN FALSE + ELIF back = 0 AND given[ next ] = n + THEN FALSE + ELSE INT next2 = IF back = n THEN next + 1 ELSE next FI; + board[ r, c ] := n; + BOOL found := FALSE; + FOR ri FROM r - 1 TO r + 1 WHILE NOT found DO + FOR cj FROM c - 1 TO c + 1 + WHILE NOT ( found := solve board with givens( board, given, ri, cj, n + 1, next2 ) ) + DO SKIP OD + OD; + IF NOT found THEN board[ r, c ] := back FI; + found + FI # solve board with givens # ; + + # returns the solution for board data # + # or an empty board if there isn't one # + PROC solve = ( [,]INT board data )[,]INT: + BEGIN + [ 1 LWB board data : 1 UPB board data + , 2 LWB board data : 2 UPB board data + ]INT board := board data; + INT board size = ( ( 1 UPB board - 1 LWB board ) + 1 ) + * ( ( 2 UPB board - 2 LWB board ) + 1 ) + ; + [ 1 : board size ]INT given1; + INT g pos := 0, start r := 0, start c := 0; + FOR i FROM 1 LWB board TO 1 UPB board DO + FOR j FROM 2 LWB board TO 2 UPB board DO + IF board[ i, j ] > 0 THEN + given1[ g pos +:= 1 ] := board[ i, j ]; + IF board[ i, j ] = 1 THEN start r := i; start c := j FI + FI + OD + OD; + [ 1 : g pos ]INT given := given1[ 1 : g pos ]; + QUICKSORT given; + IF solve board with givens( board, given, start r, start c, 1, 1 ) + THEN board + ELSE [ 1 : 0, 1 : 0 ]INT no solution; no solution + FI + END # solve # ; + + PROC print board = ( [,]INT board )VOID: + FOR i FROM 1 LWB board TO 1 UPB board DO + FOR j FROM 2 LWB board TO 2 UPB board DO + INT v = board[ i, j ]; + IF v < 0 THEN print( ( " " ) ) + ELIF v = 0 THEN print( ( " __" ) ) + ELSE print( ( whole( v, -3 ) ) ) + FI + OD; + print( ( newline ) ) + OD # print board # ; + + [,]INT test board = ( ( o, 33, 35, o, o, x, x, x ) + , ( o, o, 24, 22, o, x, x, x ) + , ( o, o, o, 21, o, o, x, x ) + , ( o, 26, o, 13, 40, 11, x, x ) + , ( 27, o, o, o, 9, o, 1, x ) + , ( x, x, o, o, 18, o, o, x ) + , ( x, x, x, x, o, 7, o, o ) + , ( x, x, x, x, x, x, 5, o ) + ); + print board( test board ); + print( ( newline ) ); + IF [,]INT solution = solve( test board ); + 1 LWB solution > 1 UPB solution + THEN print( ( "No solution found", newline ) ) + ELSE print board( solution ) + FI + +END diff --git a/Task/Solve-a-Hidato-puzzle/EasyLang/solve-a-hidato-puzzle.easy b/Task/Solve-a-Hidato-puzzle/EasyLang/solve-a-hidato-puzzle.easy new file mode 100644 index 0000000000..af920153fe --- /dev/null +++ b/Task/Solve-a-Hidato-puzzle/EasyLang/solve-a-hidato-puzzle.easy @@ -0,0 +1,77 @@ +moves[][] = [ [ -1 -1 ] [ -1 0 ] [ -1 1 ] [ 0 -1 ] [ 0 1 ] [ 1 -1 ] [ 1 0 ] [ 1 1 ] ] +global brd[][] maxr maxc maxcnt ancor . +func solve r c cnt . + if cnt - ancor > 13 : return 0 + if cnt > maxcnt : return 1 + for m = 1 to len moves[][] + rn = r + moves[m][1] + cn = c + moves[m][2] + if rn >= 1 and rn <= maxr and cn >= 1 and cn <= maxc + if brd[rn][cn] = 0 + brd[rn][cn] = cnt + if solve rn cn (cnt + 1) = 1 : return 1 + brd[rn][cn] = 0 + elif brd[rn][cn] = cnt + oldanc = ancor + ancor = cnt + if solve rn cn (cnt + 1) = 1 : return 1 + ancor = oldanc + . + . + . + return 0 +. +brd$ = " + __ 33 35 __ __ . . . + __ __ 24 22 __ . . . + __ __ __ 21 __ __ . . + __ 26 __ 13 40 11 . . + 27 __ __ __ 9 __ 1 . + . . __ __ 18 __ __ . + . . . . __ 7 __ __ + . . . . . . 5 __ +" +proc prepare &r0 &c0 . + brd$[] = strsplit brd$ "\n" + maxc = len brd$[2] / 3 + maxr = len brd$[] - 2 + len brd[][] maxr + for r to maxr + for c to maxc + c$ = substr brd$[r + 1] (c * 3 - 2) 3 + if c$ = " ." + h = -1 + elif c$ = " __" + h = 0 + else + h = number c$ + maxcnt = higher maxcnt h + if h = 1 + r0 = r + c0 = c + . + . + brd[r][] &= h + . + . + ancor = 1 +. +proc printbrd . + numfmt 3 0 + for r to maxr + for c to maxc + if brd[r][c] = -1 + write " " + else + write brd[r][c] + . + . + print "" + . +. +prepare r0 c0 +if solve r0 c0 2 = 1 + printbrd +else + print "no solutions found" +. diff --git a/Task/Solve-a-Hidato-puzzle/Elixir/solve-a-hidato-puzzle-1.elixir b/Task/Solve-a-Hidato-puzzle/Elixir/solve-a-hidato-puzzle-1.ex similarity index 100% rename from Task/Solve-a-Hidato-puzzle/Elixir/solve-a-hidato-puzzle-1.elixir rename to Task/Solve-a-Hidato-puzzle/Elixir/solve-a-hidato-puzzle-1.ex diff --git a/Task/Solve-a-Hidato-puzzle/Elixir/solve-a-hidato-puzzle-2.elixir b/Task/Solve-a-Hidato-puzzle/Elixir/solve-a-hidato-puzzle-2.ex similarity index 100% rename from Task/Solve-a-Hidato-puzzle/Elixir/solve-a-hidato-puzzle-2.elixir rename to Task/Solve-a-Hidato-puzzle/Elixir/solve-a-hidato-puzzle-2.ex diff --git a/Task/Solve-a-Hidato-puzzle/FreeBASIC/solve-a-hidato-puzzle.basic b/Task/Solve-a-Hidato-puzzle/FreeBASIC/solve-a-hidato-puzzle.basic new file mode 100644 index 0000000000..8881e101a9 --- /dev/null +++ b/Task/Solve-a-Hidato-puzzle/FreeBASIC/solve-a-hidato-puzzle.basic @@ -0,0 +1,113 @@ +Dim Shared board(Any, Any) As Integer +Dim Shared start(1) As Integer +Dim Shared given(99) As Integer +Dim Shared givenCount As Integer + +Sub SortArray(arr() As Integer, n As Integer) + Dim As Integer i, j + For i = 0 To n - 2 + For j = 0 To n - 2 - i + If arr(j) > arr(j + 1) Then Swap arr(j), arr(j + 1) + Next j + Next i +End Sub + +Sub setup(entrada() As String) + Dim As Integer nRows = Ubound(entrada) + Dim As Integer nCols = Len(entrada(0)) \ 3 ' Asumiendo que cada celda tiene 2 caracteres y un espacio + Dim As String cell + Dim As Integer valor, r, c, i, j + + ' Inicializar el tablero + For i = Lbound(board) To Ubound(board) + For j = Lbound(board) To Ubound(board) + board(i, j) = -1 + Next j + Next i + + ' Procesar la entrada + For r = 0 To nRows - 1 + For c = 0 To nCols - 1 + cell = Mid(entrada(r), c * 3 + 1, 2) + cell = Trim(cell) + Select Case cell + Case "_" + board(r + 1, c + 1) = 0 + Case "." + ' No hacer nada, ya está inicializado a -1 + Case Else + valor = Cint(cell) + board(r + 1, c + 1) = valor + given(givenCount) = valor + givenCount += 1 + If valor = 1 Then + start(0) = r + 1 + start(1) = c + 1 + End If + End Select + Next c + Next r + + SortArray(given(), givenCount) +End Sub + +Function solve(r As Integer, c As Integer, n As Integer, sgte As Integer) As Boolean + If n > given(givenCount - 1) Then Return True + + Dim As Integer back = board(r, c) + If back <> 0 Andalso back <> n Then Return False + If back = 0 Andalso given(sgte) = n Then Return False + If back = n Then sgte += 1 + + board(r, c) = n + For i As Integer = -1 To 1 + For j As Integer = -1 To 1 + If solve(r + i, c + j, n + 1, sgte) Then Return True + Next j + Next i + + board(r, c) = back + Return False +End Function + +Sub printSolution() + For r As Integer = 1 To Ubound(board) + For c As Integer = 1 To Ubound(board) + Select Case board(r, c) + Case -1 + Print " . "; + Case Is > 0 + Print Using "## "; board(r, c); + Case Else + Print "__ "; + End Select + Next c + Print + Next r +End Sub + +Sub main() + Dim entrada(9) As String + entrada(0) = ". . . . . . . . . . " + entrada(1) = ". _ 33 35 _ _ . . . . " + entrada(2) = ". _ _ 24 22 _ . . . . " + entrada(3) = ". _ _ _ 21 _ _ . . . " + entrada(4) = ". _ 26 _ 13 40 11 . . . " + entrada(5) = ". 27 _ _ _ 9 _ 1 . . " + entrada(6) = ". . . _ _ 18 _ _ . . " + entrada(7) = ". . . . . _ 7 _ _ . " + entrada(8) = ". . . . . . . 5 _ . " + entrada(9) = ". . . . . . . . . . " + + Redim board(Ubound(entrada)+1, (Len(entrada(0))/3)) As Integer + setup(entrada()) + Print "Initial board:" + printSolution() + Print !"\nSolved board:" + solve(start(0), start(1), 1, 0) + printSolution() +End Sub + +main() + +Sleep diff --git a/Task/Solve-a-Hidato-puzzle/JavaScript/solve-a-hidato-puzzle.js b/Task/Solve-a-Hidato-puzzle/JavaScript/solve-a-hidato-puzzle.js new file mode 100644 index 0000000000..afcb0dc362 --- /dev/null +++ b/Task/Solve-a-Hidato-puzzle/JavaScript/solve-a-hidato-puzzle.js @@ -0,0 +1,113 @@ +let board = []; +let start = []; +let given = []; + +function setup(input) { + /* This task is not about input validation, so + we're going to trust the input to be valid */ + const puzzle = input.map(line => line.split(/\s+/)); + const nCols = puzzle[0].length; + const nRows = puzzle.length; + let list = new Array(nRows * nCols); + + board = Array(nRows + 2).fill().map(() => + Array(nCols + 2).fill(-1) + ); + + for (let r = 0; r < nRows; r++) { + const row = puzzle[r]; + for (let c = 0; c < nCols; c++) { + const cell = row[c]; + switch (cell) { + case "_": + board[r + 1][c + 1] = 0; + break; + case ".": + break; + default: + const val = parseInt(cell, 10); + board[r + 1][c + 1] = val; + list.push(val); + if (val === 1) { + start = [r + 1, c + 1]; + } + break; + } + } + } + + list.sort((a, b) => a - b); + given = [...list]; +} + +function solve(r, c, n, next) { + if (n > given[given.length - 1]) { + return true; + } + + const back = board[r][c]; + if (back !== 0 && back !== n) { + return false; + } + + if (back === 0 && given[next] === n) { + return false; + } + + if (back === n) { + next++; + } + + board[r][c] = n; + for (let i = -1; i < 2; i++) { + for (let j = -1; j < 2; j++) { + if (solve(r + i, c + j, n + 1, next)) { + return true; + } + } + } + + board[r][c] = back; + return false; +} + +function printBoard() { + for (const row of board) { + let rowStr = ''; + for (const c of row) { + switch (true) { + case c === -1: + rowStr += ' . '; + break; + case c > 0: + rowStr += c.toString().padStart(2) + ' '; + break; + default: + rowStr += '__ '; + break; + } + } + console.log(rowStr); + } +} + +function main() { + const input = [ + "_ 33 35 _ _ . . .", + "_ _ 24 22 _ . . .", + "_ _ _ 21 _ _ . .", + "_ 26 _ 13 40 11 . .", + "27 _ _ _ 9 _ 1 .", + ". . _ _ 18 _ _ .", + ". . . . _ 7 _ _", + ". . . . . . 5 _" + ]; + + setup(input); + printBoard(); + console.log("\nFound:"); + solve(start[0], start[1], 1, 0); + printBoard(); +} + +main(); diff --git a/Task/Solve-a-Hidato-puzzle/Jq/solve-a-hidato-puzzle.jq b/Task/Solve-a-Hidato-puzzle/Jq/solve-a-hidato-puzzle.jq new file mode 100644 index 0000000000..7b80214b8d --- /dev/null +++ b/Task/Solve-a-Hidato-puzzle/Jq/solve-a-hidato-puzzle.jq @@ -0,0 +1,74 @@ +### Generic functions + +def lpad($len): tostring | ($len - length) as $l | (" " * $l) + .; + +### Hidato Puzzle + +# "." ~ -1 (dead cell) +# "_" ~ 0 (to be assigned a number) +def printBoard: + .board[] as $row + | reduce $row[] as $c (""; + if $c == -1 then . + " . " + elif $c > 0 then . + ($c | lpad(3)) + else . + " __" + end); + +# output: { board, given, start} +# "." signifies a dead cell +def setUp($in): + { board:[], given:[], start:[] } + | ($in|length) as $nRows + | [range(0;$nRows) | ($in[.]|split(" "))] as $puzzle + | ($puzzle[0]|length) as $nCols + | .board = [range(0; $nRows+2) | null] + | reduce range(0; .board|length) as $i (. ; .board[$i] = [range(0; $nCols+2) | -1]) + | reduce range(0; $nRows) as $r (.; + $puzzle[$r] as $row + | reduce range(0; $nCols) as $c (.; + $row[$c] as $cell + | if $cell == "_" + then .board[$r + 1][$c + 1] = 0 + elif $cell != "." + then ($cell | tonumber) as $value + | .board[$r + 1][$c + 1] = $value + | .given += [$value] + | if $value == 1 then .start = [$r + 1, $c + 1] end + end )) + | .given |= sort ; + +# Generate all solutions, that is, emit empty on failure. +# $r is a row, $c is a column, $n is the number we're looking for, +# $next is the index in .given of the next given number. +def solve($r; $c; $n; $next): + if $n > .given[-1] then . # all done + else .board[$r][$c] as $back + | if ($back != 0 and $back != $n) then empty + elif $back == 0 and .given[$next] == $n then empty + else + (if $back == $n then (1+$next) else $next end) as $next2 + | if $n != $back then .board[$r][$c] = $n end # avoid unnecessary copying + | ( (-1, 0, 1) as $i + | (-1, 0, 1) as $j + | solve($r + $i; $c + $j; $n + 1; $next2) + ) + end + end; + + +def example: [ + "_ 33 35 _ _ . . .", + "_ _ 24 22 _ . . .", + "_ _ _ 21 _ _ . .", + "_ 26 _ 13 40 11 . .", + "27 _ _ _ 9 _ 1 .", + ". . _ _ 18 _ _ .", + ". . . . _ 7 _ _", + ". . . . . . 5 _" +]; + +setUp(example) +| printBoard, + "\nFound:", + ( first( solve(.start[0]; .start[1]; 1; 0) ) + | printBoard) diff --git a/Task/Solve-a-Hidato-puzzle/Julia/solve-a-hidato-puzzle-1.julia b/Task/Solve-a-Hidato-puzzle/Julia/solve-a-hidato-puzzle-1.jl similarity index 100% rename from Task/Solve-a-Hidato-puzzle/Julia/solve-a-hidato-puzzle-1.julia rename to Task/Solve-a-Hidato-puzzle/Julia/solve-a-hidato-puzzle-1.jl diff --git a/Task/Solve-a-Hidato-puzzle/Julia/solve-a-hidato-puzzle-2.julia b/Task/Solve-a-Hidato-puzzle/Julia/solve-a-hidato-puzzle-2.jl similarity index 100% rename from Task/Solve-a-Hidato-puzzle/Julia/solve-a-hidato-puzzle-2.julia rename to Task/Solve-a-Hidato-puzzle/Julia/solve-a-hidato-puzzle-2.jl diff --git a/Task/Solve-a-Hidato-puzzle/Kotlin/solve-a-hidato-puzzle.kotlin b/Task/Solve-a-Hidato-puzzle/Kotlin/solve-a-hidato-puzzle.kts similarity index 100% rename from Task/Solve-a-Hidato-puzzle/Kotlin/solve-a-hidato-puzzle.kotlin rename to Task/Solve-a-Hidato-puzzle/Kotlin/solve-a-hidato-puzzle.kts diff --git a/Task/Solve-a-Hidato-puzzle/Rust/solve-a-hidato-puzzle.rust b/Task/Solve-a-Hidato-puzzle/Rust/solve-a-hidato-puzzle.rs similarity index 100% rename from Task/Solve-a-Hidato-puzzle/Rust/solve-a-hidato-puzzle.rust rename to Task/Solve-a-Hidato-puzzle/Rust/solve-a-hidato-puzzle.rs diff --git a/Task/Solve-a-Hidato-puzzle/Uiua/solve-a-hidato-puzzle.uiua b/Task/Solve-a-Hidato-puzzle/Uiua/solve-a-hidato-puzzle.uiua new file mode 100644 index 0000000000..eeaf0022d9 --- /dev/null +++ b/Task/Solve-a-Hidato-puzzle/Uiua/solve-a-hidato-puzzle.uiua @@ -0,0 +1,22 @@ +G ← [[0 33 35 0 0 ∞ ∞ ∞] + [0 0 24 22 0 ∞ ∞ ∞] + [0 0 0 21 0 0 ∞ ∞] + [0 26 0 13 40 11 ∞ ∞] + [27 0 0 0 9 0 1 ∞] + [∞ ∞ 0 0 18 0 0 ∞] + [∞ ∞ ∞ ∞ 0 7 0 0] + [∞ ∞ ∞ ∞ ∞ ∞ 5 0]] +Width ← ⧻⊢G +DobCA ← ⊃(⋅∘|⋅⋅¤|¤) # λbCA (sorry Kai!) +Dirs ← ⊂⟜¯⊂1[⟜⊃+₁-₁Width] # D8 directions in flattened grid. +Ns ← ▽⊸∊⊓(⊚=₀|+Dirs¤)⊃⋅∘∘ # Valid empty Ns.(pos board -> [pos']) +Next ← +1⊢⊚=⊸/↥˜⨂+1⇡/×⊸△ # Next unplaced number.(board -> n) +Nodes ← ⍣(≡⍜⊡◌DobCA⊙Ns⊃⋅∘∘˜⨂-1⊃⊙∘⊙∘⊸Next⟜∘|[]) # Valid next boards from here. +Placed ← ⊏(⍏⊸≡⊡₁)▽⊙(⍉⊟)↥0±⊃⋅∘⊙∘⊸⨂⟜∘ # [pos num] sorted by nums. + +# Ensure each pair of placed numbers have DiaD <= number differemce. +DiaD ← /↥⌵-∩(⊟⊃(◿|⌊÷)Width) # Diagonal dist in flattened grid. +N ← /+≠∞♭G +Heur ← ⨬(-1N|999)=0/↧≡(≥⊙(⌵/-)DiaD°⊟°⊟⍉)⧈∘2Placed + +↯∞_Width⊣⊢path(Nodes|¬˜∊0|Heur)♭G # Solve, pretty print diff --git a/Task/Solve-a-Holy-Knights-tour/ALGOL-68/solve-a-holy-knights-tour.alg b/Task/Solve-a-Holy-Knights-tour/ALGOL-68/solve-a-holy-knights-tour.alg index a128187549..7023ce14e2 100644 --- a/Task/Solve-a-Holy-Knights-tour/ALGOL-68/solve-a-holy-knights-tour.alg +++ b/Task/Solve-a-Holy-Knights-tour/ALGOL-68/solve-a-holy-knights-tour.alg @@ -1,15 +1,13 @@ -# directions for moves # -INT nne = 1, ne = 2, se = 3, sse = 4; -INT ssw = 5, sw = 6, nw = 7, nnw = 8; - -INT lowest move = nne; -INT highest move = nnw; - # the vertical position changes of the moves # +# nne ne se sse ssw sw nw nnw # []INT offset v = ( -2, -1, 1, 2, 2, 1, -1, -2 ); # the horizontal position changes of the moves # +# nne ne se sse ssw sw nw nnw # []INT offset h = ( 1, 2, 2, 1, -1, -2, -2, -1 ); +INT lowest move = LWB offset v; +INT highest move = UPB offset v; + MODE SQUARE = STRUCT( INT move # the number of the move that caused # # the knight to reach this square # , INT direction # the direction of the move that # @@ -154,7 +152,7 @@ BEGIN result END; # find tour # -main:( +BEGIN # calculate the tour from the start position, if possible # initialise board( ( "-000----" , "-0-00---" , "-0000000" @@ -174,4 +172,4 @@ main:( print( ( "Solution not found", newline ) ) FI; print( ( iterations, " iterations, ", backtracks, " backtracks", newline ) ) -) +END diff --git a/Task/Solve-a-Holy-Knights-tour/Ada/solve-a-holy-knights-tour.ada b/Task/Solve-a-Holy-Knights-tour/Ada/solve-a-holy-knights-tour.adb similarity index 100% rename from Task/Solve-a-Holy-Knights-tour/Ada/solve-a-holy-knights-tour.ada rename to Task/Solve-a-Holy-Knights-tour/Ada/solve-a-holy-knights-tour.adb diff --git a/Task/Solve-a-Holy-Knights-tour/EasyLang/solve-a-holy-knights-tour.easy b/Task/Solve-a-Holy-Knights-tour/EasyLang/solve-a-holy-knights-tour.easy new file mode 100644 index 0000000000..268a1b3472 --- /dev/null +++ b/Task/Solve-a-Holy-Knights-tour/EasyLang/solve-a-holy-knights-tour.easy @@ -0,0 +1,63 @@ +brd$ = " +.000.... +.0.00... +.0000000 +000..0.0 +0.0..000 +1000000. +..00.0.. +...000.. +" +moves[][] = [ [ -2 -1 ] [ -2 1 ] [ -1 -2 ] [ -1 2 ] [ 1 -2 ] [ 1 2 ] [ 2 -1 ] [ 2 1 ] ] +global brd[][] maxr maxc maxcnt . +func solve r c cnt . + if cnt > maxcnt : return 1 + for m = 1 to len moves[][] + rn = r + moves[m][1] + cn = c + moves[m][2] + if rn >= 1 and rn <= maxr and cn >= 1 and cn <= maxc and brd[rn][cn] = 0 + brd[rn][cn] = cnt + if solve rn cn (cnt + 1) = 1 : return 1 + brd[rn][cn] = 0 + . + . + return 0 +. +proc prepare &r0 &c0 . + brd$[] = strsplit brd$ "\n" + maxc = len brd$[2] + maxr = len brd$[] - 2 + len brd[][] maxr + for r to maxr + for c to maxc + c$ = substr brd$[r + 1] c 1 + h = if c$ = "0" or c$ = 1 + maxcnt += h + brd[r][] &= h - 1 + if c$ = "1" + r0 = r + c0 = c + . + . + . +. +proc printbrd . + numfmt 3 0 + for r to maxr + for c to maxc + if brd[r][c] = -1 + write " " + else + write brd[r][c] + . + . + print "" + . +. +prepare r0 c0 +brd[r0][c0] = 1 +if solve r0 c0 2 = 1 + printbrd +else + print "no solutions found" +. diff --git a/Task/Solve-a-Holy-Knights-tour/Elixir/solve-a-holy-knights-tour.elixir b/Task/Solve-a-Holy-Knights-tour/Elixir/solve-a-holy-knights-tour.ex similarity index 100% rename from Task/Solve-a-Holy-Knights-tour/Elixir/solve-a-holy-knights-tour.elixir rename to Task/Solve-a-Holy-Knights-tour/Elixir/solve-a-holy-knights-tour.ex diff --git a/Task/Solve-a-Holy-Knights-tour/FreeBASIC/solve-a-holy-knights-tour.basic b/Task/Solve-a-Holy-Knights-tour/FreeBASIC/solve-a-holy-knights-tour.basic new file mode 100644 index 0000000000..31edfb64e4 --- /dev/null +++ b/Task/Solve-a-Holy-Knights-tour/FreeBASIC/solve-a-holy-knights-tour.basic @@ -0,0 +1,81 @@ +Dim Shared As String p1 +p1 = ".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx.." +Dim Shared As Integer p1W = 8 +Dim Shared As String p2 +p2 = ".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x....." +Dim Shared As Integer p2W = 13 +Dim Shared As Integer puzzle(), movesCnt, wid +Dim Shared As Integer moves(7, 1) => { {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1} } + +Function isValid(x As Integer, y As Integer) As Boolean + Return (x > 0 And x <= wid And y > 0 And y <= wid And puzzle(x + y * wid - wid) = 0) +End Function + +Function solve(x As Integer, y As Integer, s As Integer) As Boolean + If s > movesCnt Then Return True + + Dim As Integer i, test, a, b + + For i = 0 To 7 + test = 0 + a = x + moves(i, 0) + b = y + moves(i, 1) + If isValid(a, b) Then + puzzle(a + b * wid - wid) = s + If solve(a, b, s + 1) Then Return True + puzzle(a + b * wid - wid) = 0 + End If + Next + + Return False +End Function + +Sub printSolution + Dim As Integer i, j, lp + + For j = 1 To wid + For i = 1 To wid + lp = puzzle(i + j * wid - wid) + If lp = -1 Then + Print " "; + Else + Print Using " ##"; lp; + End If + Next + Print + Next + Print +End Sub + +Dim Shared As Integer sx, sy + +Sub fill(pz As String, w As Integer) + wid = w + movesCnt = Len(pz) + Redim puzzle(wid * wid) As Integer + Dim As Integer i, lp + + For i = 1 To Len(pz) + lp = Asc(Mid(pz, i, 1)) + If lp = Asc("x") Then + puzzle(i) = 0 + Elseif lp = Asc(".") Then + puzzle(i) = -1 + movesCnt -= 1 + Else + puzzle(i) = 1 + sx = 1 + (i - 1) Mod wid + sy = (i + wid - 1) \ wid + End If + Next +End Sub + +' [[ entry point ]] -- +Print +fill(p1, p1W) +If solve(sx, sy, 2) Then printSolution +Print +fill(p2, p2W) +If solve(sx, sy, 2) Then printSolution + +Sleep diff --git a/Task/Solve-a-Holy-Knights-tour/Jq/solve-a-holy-knights-tour.jq b/Task/Solve-a-Holy-Knights-tour/Jq/solve-a-holy-knights-tour.jq new file mode 100644 index 0000000000..d364dfdf9d --- /dev/null +++ b/Task/Solve-a-Holy-Knights-tour/Jq/solve-a-holy-knights-tour.jq @@ -0,0 +1,83 @@ +def lpad($len): tostring | ($len - length) as $l | (" " * $l) + .; + +def moves: [ [-1, -2], [1, -2], [-1, 2], [1, 2], [-2, -1], [-2, 1], [2, -1], [2, 1] ]; + +def board1: + " xxx " + + " x xx " + + " xxxxxxx" + + "xxx x x" + + "x x xxx" + + "sxxxxxx " + + " xx x " + + " xxx " +; +def board2: + ".....s.x....." + + ".....x.x....." + + "....xxxxx...." + + ".....xxx....." + + "..x..x.x..x.." + + "xxxxx...xxxxx" + + "..xx.....xx.." + + "xxxxx...xxxxx" + + "..x..x.x..x.." + + ".....xxx....." + + "....xxxxx...." + + ".....x.x....." + + ".....x.x....." +; + +# Input: {pz} +def solve($sz; $sx; $sy; $idx; $cnt): + # debug( "solve(\($sz); \($sx); \($sy); \($idx); \($cnt))" ) | + if $idx > $cnt then . + else first( + range(0;moves|length) as $i + | ($sx + moves[$i][0]) as $x + | ($sy + moves[$i][1]) as $y + | if $x >= 0 and $x < $sz and $y >= 0 and $y < $sz and .pz[$x][$y] == 0 + then .pz[$x][$y] = $idx + | solve($sz; $x; $y; $idx + 1; $cnt) + else empty + end ) + end; + +def printSolution($sz): + range(0; $sz) as $j + | .emit = "" + | reduce range(0; $sz) as $i (.; + if .pz[$i][$j] != -1 + then .emit += (.pz[$i][$j] | lpad(3)) + else .emit += " --" + end ) + | .emit; + +# $b should be a board of size $sz +def findSolution($b; $sz): + [range(0; $sz) | -1] as $minus + | { pz: [range(0;$sz) | $minus], + x: 0, + y: 0, + idx: 0, + cnt: 0 + } + | reduce range(0; $sz) as $j (.; + reduce range(0; $sz) as $i (.; + if $b[.idx: .idx+1] == "x" + then .pz[$i][$j] = 0 + | .cnt += 1 + elif $b[.idx: .idx+1] == "s" + then + .pz[$i][$j] = 1 + | .cnt += 1 + | .x = $i + | .y = $j + end + | .idx += 1 )) + | (solve($sz; .x; .y; 2; .cnt) | printSolution($sz)) + // "Whoops!" ; + +findSolution(board1; 8), +"", +findSolution(board2; 13) diff --git a/Task/Solve-a-Holy-Knights-tour/Julia/solve-a-holy-knights-tour.julia b/Task/Solve-a-Holy-Knights-tour/Julia/solve-a-holy-knights-tour.jl similarity index 100% rename from Task/Solve-a-Holy-Knights-tour/Julia/solve-a-holy-knights-tour.julia rename to Task/Solve-a-Holy-Knights-tour/Julia/solve-a-holy-knights-tour.jl diff --git a/Task/Solve-a-Holy-Knights-tour/Kotlin/solve-a-holy-knights-tour.kotlin b/Task/Solve-a-Holy-Knights-tour/Kotlin/solve-a-holy-knights-tour.kts similarity index 100% rename from Task/Solve-a-Holy-Knights-tour/Kotlin/solve-a-holy-knights-tour.kotlin rename to Task/Solve-a-Holy-Knights-tour/Kotlin/solve-a-holy-knights-tour.kts diff --git a/Task/Solve-a-Holy-Knights-tour/Rust/solve-a-holy-knights-tour.rs b/Task/Solve-a-Holy-Knights-tour/Rust/solve-a-holy-knights-tour.rs new file mode 100644 index 0000000000..2533753df8 --- /dev/null +++ b/Task/Solve-a-Holy-Knights-tour/Rust/solve-a-holy-knights-tour.rs @@ -0,0 +1,188 @@ +use std::collections::HashSet; +use std::iter::FromIterator; +use std::str::FromStr; + +#[derive(Clone, Copy)] +struct Node { + val: isize, + neighbors: u8, +} + +struct NSolver { + dx: [isize; 8], + dy: [isize; 8], + wid: usize, + hei: usize, + max: usize, + arr: Vec, +} + +impl NSolver { + fn new() -> Self { + let dx = [-1, -1, 1, 1, -2, -2, 2, 2]; + let dy = [-2, 2, -2, 2, -1, 1, -1, 1]; + + Self { + dx, + dy, + wid: 0, + hei: 0, + max: 0, + arr: vec![], + } + } + + fn solve(&mut self, puzz: &mut Vec, max_wid: usize) { + if puzz.is_empty() { + return; + } + + self.wid = max_wid; + self.hei = puzz.len() / self.wid; + let len = self.wid * self.hei; + self.max = len; + self.arr = vec![Node { val: 0, neighbors: 0 }; len]; + + let mut c = 0; + let mut empty_coords = HashSet::new(); + + for s in puzz.iter() { + if s == "*" { + self.max -= 1; + self.arr[c].val = -1; + c += 1; + continue; + } + + if s == "." { + empty_coords.insert(c); + c += 1; + continue; + } + + if let Ok(val) = isize::from_str(s) { + self.arr[c].val = val; + c += 1; + } + } + + self.solve_it(); + + c = 0; + for s in puzz.iter_mut() { + if s == "." { + let val = self.arr[c].val; + *s = format!("{:02}", val); + } + c += 1; + } + } + + fn solve_it(&mut self) { + let (x, y, z) = self.find_start(); + if z == 99999 { + println!("Can't find start point!"); + return; + } + + self.search(x, y, z + 1); + } + + fn find_start(&self) -> (usize, usize, isize) { + let mut x = 0; + let mut y = 0; + let mut z = 99999; + + for b in 0..self.hei { + for a in 0..self.wid { + let idx = a + b * self.wid; + if self.arr[idx].val > 0 && self.arr[idx].val < z { + x = a; + y = b; + z = self.arr[idx].val; + } + } + } + + (x, y, z) + } + + fn search(&mut self, x: usize, y: usize, w: isize) -> bool { + if w > self.max as isize { + return true; + } + + let idx = x + y * self.wid; + self.arr[idx].neighbors = self.get_neighbors(x, y); + + for d in 0..8 { + if (self.arr[idx].neighbors & (1 << d)) != 0 { + let a = (x as isize + self.dx[d]) as usize; + let b = (y as isize + self.dy[d]) as usize; + let n_idx = a + b * self.wid; + + if self.arr[n_idx].val == 0 { + self.arr[n_idx].val = w; + if self.search(a, b, w + 1) { + return true; + } + self.arr[n_idx].val = 0; + } + } + } + + false + } + + fn get_neighbors(&self, x: usize, y: usize) -> u8 { + let mut c = 0u8; + + for i in 0..8 { + let a = x as isize + self.dx[i]; + let b = y as isize + self.dy[i]; + + if a >= 0 && b >= 0 { + let a = a as usize; + let b = b as usize; + if a < self.wid && b < self.hei { + if self.arr[a + b * self.wid].val > -1 { + c |= 1 << i; + } + } + } + } + + c + } +} + +fn main() { + // Example input (comment/uncomment for different puzzles) + let p = "* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * "; + let wid = 13; + + let puzz: Vec = p.split_whitespace().map(|s| s.to_string()).collect(); + + let mut puzz_vec = puzz.clone(); + + let mut solver = NSolver::new(); + solver.solve(&mut puzz_vec, wid); + + let mut c = 0; + for item in puzz_vec.iter() { + if item == "*" || item == "." { + print!(" "); + } else { + print!("{:2} ", item); + } + + c += 1; + if c >= wid { + println!(); + c = 0; + } + } + + println!("\nPress any key to exit..."); + let _ = std::io::stdin().read_line(&mut String::new()); +} diff --git a/Task/Solve-a-Holy-Knights-tour/V-(Vlang)/solve-a-holy-knights-tour.v b/Task/Solve-a-Holy-Knights-tour/V-(Vlang)/solve-a-holy-knights-tour.v new file mode 100644 index 0000000000..f06c8d1d5a --- /dev/null +++ b/Task/Solve-a-Holy-Knights-tour/V-(Vlang)/solve-a-holy-knights-tour.v @@ -0,0 +1,83 @@ +const moves = [ + [-1, -2], [1, -2], [-1, 2], [1, 2], + [-2, -1], [-2, 1], [2, -1], [2, 1], +] + +const board1 = + " xxx " + + " x xx " + + " xxxxxxx" + + "xxx x x" + + "x x xxx" + + "sxxxxxx " + + " xx x " + + " xxx " + +const board2 = + ".....s.x....." + + ".....x.x....." + + "....xxxxx...." + + ".....xxx....." + + "..x..x.x..x.." + + "xxxxx...xxxxx" + + "..xx.....xx.." + + "xxxxx...xxxxx" + + "..x..x.x..x.." + + ".....xxx....." + + "....xxxxx...." + + ".....x.x....." + + ".....x.x....." + +fn solve(mut pz [][]int, sz int, sx int, sy int, idx int, cnt int) bool { + if idx > cnt { return true } + for move in moves { + x := sx + move[0] + y := sy + move[1] + if x >= 0 && x < sz && y >= 0 && y < sz && pz[x][y] == 0 { + pz[x][y] = idx + if solve(mut pz, sz, x, y, idx + 1, cnt) { return true } + pz[x][y] = 0 + } + } + return false +} + +fn find_solution(b string, sz int) { + mut pz := [][]int{len: sz, init: []int{len: sz, init: -1}} + mut x := 0 + mut y := 0 + mut idx := 0 + mut cnt := 0 + for j in 0 .. sz { + for i in 0 .. sz { + ch := b[idx] + if ch == `x` { + pz[i][j] = 0 + cnt++ + } else if ch == `s` { + pz[i][j] = 1 + cnt++ + x = i + y = j + } + idx++ + } + } + + if solve(mut pz, sz, x, y, 2, cnt) { + for j in 0 .. sz { + for i in 0 .. sz { + if pz[i][j] != -1 { print("${pz[i][j]:02d} ") } + else { print("-- ") } + } + println("") + } + } + else { println("Cannot solve this puzzle!") } +} + +fn main() { + find_solution(board1, 8) + println("") + find_solution(board2, 13) +} diff --git a/Task/Solve-a-Holy-Knights-tour/Zig/solve-a-holy-knights-tour.zig b/Task/Solve-a-Holy-Knights-tour/Zig/solve-a-holy-knights-tour.zig new file mode 100644 index 0000000000..cf7ec96c84 --- /dev/null +++ b/Task/Solve-a-Holy-Knights-tour/Zig/solve-a-holy-knights-tour.zig @@ -0,0 +1,208 @@ +const std = @import("std"); + +const Node = struct { + val: isize, + neighbors: u8, +}; + +const NSolver = struct { + dx: [8]isize = .{-1, -1, 1, 1, -2, -2, 2, 2}, + dy: [8]isize = .{-2, 2, -2, 2, -1, 1, -1, 1}, + wid: usize, + hei: usize, + max: usize, + arr: []Node, + allocator: std.mem.Allocator, + + pub fn init(allocator: std.mem.Allocator) NSolver { + return NSolver{ + .wid = 0, + .hei = 0, + .max = 0, + .arr = &[_]Node{}, // will be overwritten in `solve` + .allocator = allocator, + }; + } + + // The key problem was here - tokens was being passed as a pointer to a split iterator + // but the function expected [][]const u8 + pub fn solve(self: *NSolver, puzz: []const u8, max_wid: usize) ![][]const u8 { + // Split the input string into tokens + var tokens = std.ArrayList([]const u8).init(self.allocator); + defer tokens.deinit(); + + var iter = std.mem.splitSequence(u8, puzz, " "); + while (iter.next()) |tok| { + if (tok.len == 0) continue; // Skip empty tokens + try tokens.append(tok); + } + + if (tokens.items.len == 0) return &[_][]const u8{}; + + self.wid = max_wid; + self.hei = tokens.items.len / max_wid; + self.max = tokens.items.len; + const len = self.wid * self.hei; + + // allocate and zero‐initialize the board + self.arr = try self.allocator.alloc(Node, len); + for (self.arr) |*n| { + n.* = Node{ .val = 0, .neighbors = 0 }; + } + + // parse the input tokens into our board + var c: usize = 0; + for (tokens.items) |tok| { + if (std.mem.eql(u8, tok, "*")) { + self.max -= 1; + self.arr[c].val = -1; + } else if (std.mem.eql(u8, tok, ".")) { + // leave . as 0 for "empty" + self.arr[c].val = 0; + } else { + // parse a pre‐filled number + const v = try std.fmt.parseInt(isize, tok, 10); + self.arr[c].val = v; + } + c += 1; + } + + // run the backtracking search + self.solveIt(); + + // Create result array to hold the modified tokens + var result = try self.allocator.alloc([]const u8, tokens.items.len); + + // write back any "." slots with zero‐padded numbers + c = 0; + for (tokens.items, 0..) |tok, i| { + if (std.mem.eql(u8, tok, ".")) { + const v = self.arr[c].val; + // format as two digits, zero-pad + result[i] = try std.fmt.allocPrint(self.allocator, "{d:0>2}", .{v}); + } else { + // For non-modified tokens, just copy the reference + result[i] = tok; + } + c += 1; + } + + return result; + } + + fn solveIt(self: *NSolver) void { + const start = self.findStart(); + if (start.z == @as(isize, @intCast(std.math.maxInt(isize)))) { + std.debug.print("Can't find start point!\n", .{}); + return; + } + _ = self.search(start.x, start.y, start.z + 1); + } + + fn findStart(self: *NSolver) struct { x: usize, y: usize, z: isize } { + var best_x: usize = 0; + var best_y: usize = 0; + var best_z: isize = std.math.maxInt(isize); + + // The original code had a bug here - trying to iterate over the height and width directly + var b: usize = 0; + while (b < self.hei) : (b += 1) { + var a: usize = 0; + while (a < self.wid) : (a += 1) { + const idx = a + b * self.wid; + const v = self.arr[idx].val; + if (v > 0 and v < best_z) { + best_x = a; + best_y = b; + best_z = v; + } + } + } + + return .{ .x = best_x, .y = best_y, .z = best_z }; + } + + fn search(self: *NSolver, x: usize, y: usize, w: isize) bool { + if (w > @as(isize, @intCast(self.max))) return true; + + const idx = x + y * self.wid; + self.arr[idx].neighbors = self.getNeighbors(x, y); + + // The original code had a bug here - trying to iterate over dx directly + for (0..self.dx.len) |d| { + if ((self.arr[idx].neighbors & (@as(u8, 1) << @as(u3, @intCast(d)))) != 0) { + const a_s = @as(isize, @intCast(x)) + self.dx[d]; + const b_s = @as(isize, @intCast(y)) + self.dy[d]; + if (a_s >= 0 and b_s >= 0) { + const a = @as(usize, @intCast(a_s)); + const b = @as(usize, @intCast(b_s)); + if (a < self.wid and b < self.hei) { + const n_idx = a + b * self.wid; + if (self.arr[n_idx].val == 0) { + self.arr[n_idx].val = w; + if (self.search(a, b, w + 1)) return true; + self.arr[n_idx].val = 0; + } + } + } + } + } + return false; + } + + fn getNeighbors(self: *NSolver, x: usize, y: usize) u8 { + var mask: u8 = 0; + for (0..self.dx.len) |i| { + const a_s = @as(isize, @intCast(x)) + self.dx[i]; + const b_s = @as(isize, @intCast(y)) + self.dy[i]; + if (a_s >= 0 and b_s >= 0) { + const a = @as(usize, @intCast(a_s)); + const b = @as(usize, @intCast(b_s)); + if (a < self.wid and b < self.hei) { + if (self.arr[a + b * self.wid].val > -1) { + mask |= ( @as(u8, 1) << @as(u3, @intCast(i))); + } + } + } + } + return mask; + } +}; + +pub fn main() !void { + const stdout = std.io.getStdOut().writer(); + const allocator = std.heap.page_allocator; + + // Example puzzle (same as your Rust example) + const p_str = "* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * "; + const wid: usize = 13; + + // solve + var solver = NSolver.init(allocator); + const result = try solver.solve(p_str, wid); + defer allocator.free(solver.arr); + + // Print the solved board + var count: usize = 0; + for (result) |tok| { + if (std.mem.eql(u8, tok, "*")) { + try stdout.print(" ", .{}); + } else { + try stdout.print("{s} ", .{tok}); + } + count += 1; + if (count == wid) { + try stdout.print("\n", .{}); + count = 0; + } + } + try stdout.print("\n", .{}); + + // Free allocated memory for any new tokens + for (result) |tok| { + if (!std.mem.eql(u8, tok, "*") and !std.mem.eql(u8, tok, ".") and !std.mem.eql(u8, tok, "1")) { + allocator.free(tok); + } + } + allocator.free(result); +} diff --git a/Task/Solve-a-Hopido-puzzle/11l/solve-a-hopido-puzzle.11l b/Task/Solve-a-Hopido-puzzle/11l/solve-a-hopido-puzzle.11l index 7412f7e4b5..18919d802d 100644 --- a/Task/Solve-a-Hopido-puzzle/11l/solve-a-hopido-puzzle.11l +++ b/Task/Solve-a-Hopido-puzzle/11l/solve-a-hopido-puzzle.11l @@ -44,8 +44,8 @@ F solve(pz, w, h) V r = solve(‘011011011111111111111011111000111000001000’, 7, 6) I r[0] == 1 - L(j) 6 - L(i) 7 + L(j) 0.<6 + L(i) 0.<7 I r[1][i][j] == -1 print(‘ ’, end' ‘’) E diff --git a/Task/Solve-a-Hopido-puzzle/EasyLang/solve-a-hopido-puzzle.easy b/Task/Solve-a-Hopido-puzzle/EasyLang/solve-a-hopido-puzzle.easy new file mode 100644 index 0000000000..0054bef045 --- /dev/null +++ b/Task/Solve-a-Hopido-puzzle/EasyLang/solve-a-hopido-puzzle.easy @@ -0,0 +1,60 @@ +brd$ = " +.##.##. +####### +####### +.#####. +..###.. +...#... +" +moves[][] = [ [ -3 0 ] [ 0 3 ] [ 3 0 ] [ 0 -3 ] [ 2 2 ] [ 2 -2 ] [ -2 2 ] [ -2 -2 ] ] +global brd[][] maxr maxc maxcnt . +func solve r c cnt . + if cnt > maxcnt : return 1 + for m = 1 to len moves[][] + rn = r + moves[m][1] + cn = c + moves[m][2] + if rn >= 1 and rn <= maxr and cn >= 1 and cn <= maxc and brd[rn][cn] = 0 + brd[rn][cn] = cnt + if solve rn cn (cnt + 1) = 1 : return 1 + brd[rn][cn] = 0 + . + . + return 0 +. +proc prepare &r0 &c0 . + brd$[] = strsplit brd$ "\n" + maxc = len brd$[2] + maxr = len brd$[] - 2 + len brd[][] maxr + for r to maxr + for c to maxc + h = if substr brd$[r + 1] c 1 = "#" + maxcnt += h + brd[r][] &= h - 1 + if h = 1 and r0 = 0 + r0 = r + c0 = c + . + . + . +. +proc printbrd . + numfmt 3 0 + for r to maxr + for c to maxc + if brd[r][c] = -1 + write " " + else + write brd[r][c] + . + . + print "" + . +. +prepare r0 c0 +brd[r0][c0] = 1 +if solve r0 c0 2 = 1 + printbrd +else + print "no solutions found" +. diff --git a/Task/Solve-a-Hopido-puzzle/Elixir/solve-a-hopido-puzzle.elixir b/Task/Solve-a-Hopido-puzzle/Elixir/solve-a-hopido-puzzle.ex similarity index 100% rename from Task/Solve-a-Hopido-puzzle/Elixir/solve-a-hopido-puzzle.elixir rename to Task/Solve-a-Hopido-puzzle/Elixir/solve-a-hopido-puzzle.ex diff --git a/Task/Solve-a-Hopido-puzzle/Fortran/solve-a-hopido-puzzle.f b/Task/Solve-a-Hopido-puzzle/Fortran/solve-a-hopido-puzzle.f new file mode 100644 index 0000000000..02ffe3bd4b --- /dev/null +++ b/Task/Solve-a-Hopido-puzzle/Fortran/solve-a-hopido-puzzle.f @@ -0,0 +1,129 @@ +program pathfinding + implicit none + + ! Shared variables with zero-based indexing + integer, dimension(0:7, 0:1) :: neighbours + integer :: cnt + integer :: pwid + integer :: phei + integer, dimension(:, :), allocatable :: pa + integer :: t1, t2, rate + + ! Main program + character(len=42) :: pz + logical :: r + ! Initialize neighbours array + neighbours = reshape([ 2, 2, -2, 2, 2, -2, -2, -2, 3, 0, 0, 3, -3, 0, 0, -3 ], [8, 2], order=[2, 1]) + !Dim Shared As Integer neighbours(7, 1) => {{2, 2}, {-2, 2}, {2, -2}, {-2, -2}, {3, 0}, {0, 3}, {-3, 0}, {0, -3}} + call system_clock(t1, rate) + pz = '011011011111111111111011111000111000001000' + r = solve(pz, 7, 6) + call system_clock(t2) + if (r) then + call printsolution(7, 6) + else + print *, 'No solution!' + end if + call system_clock(t2) + + print '(A,1x,i0,1x,A)', 'Time taken =', t2 - t1, 'milliseconds' + +contains + + function isvalid(a, b) result(res) + integer, intent(in) :: a, b + logical :: res + res = (a > -1 .and. a < pwid .and. b > -1 .and. b < phei) + end function isvalid + + recursive function iterate(pa, x, y, v) result(res) + integer, dimension(0:, 0:), intent(inout) :: pa + integer, intent(in) :: x, y, v + integer :: res + integer :: i, a, b, r + + if (v > cnt) then + res = 1 + return + end if + + res = 0 + do i = 0, 7 + a = x + neighbours(i, 0) + b = y + neighbours(i, 1) + if (isvalid(a, b))then + if (pa(a, b) /= 0) cycle + pa(a, b) = v + r = iterate(pa, a, b, v + 1) + if (r == 1) then + res = r + return + end if + pa(a, b) = 0 + end if + end do + end function iterate + + function solve(pz, w, h) result(res) + character(len=*), intent(in) :: pz + integer, intent(in) :: w, h + logical :: res + integer :: f, x, y + + ! Allocate and initialize pa array (zero-based indexing) + if (allocated(pa)) deallocate(pa) + allocate(pa(0:w - 1, 0:h - 1)) + pa = 0 + cnt = 0 + pwid = w + phei = h + f = 0 + + ! Initialize the grid + do y = 0, h - 1 + do x = 0, w - 1 + if (pz(f + 1:f + 1) == '1') then + pa(x, y) = 0 + cnt = cnt + 1 + else + pa(x, y) = -1 + end if + f = f + 1 + end do + end do + + ! Try to find a solution + res = .false. + do y = 0, h - 1 + do x = 0, w - 1 + if (pa(x, y) == 0) then + pa(x, y) = 1 + if (iterate(pa, x, y, 2) == 1) then + res = .true. + return + end if + pa(x, y) = 0 + end if + end do + end do + end function solve + + subroutine printsolution(w, h) + integer, intent(in) :: w, h + integer :: i, j + character(len=3) :: fmt + + do j = 0, h - 1 + do i = 0, w - 1 + if (pa(i, j) == -1) then + write(*, '(A)', advance='no') ' ' + else + write(fmt, '(I2.2)') pa(i, j) + write(*, '(A)', advance='no') adjustl(fmt) + end if + end do + write(*,*) + end do + end subroutine printsolution + +end program pathfinding diff --git a/Task/Solve-a-Hopido-puzzle/FreeBASIC/solve-a-hopido-puzzle.basic b/Task/Solve-a-Hopido-puzzle/FreeBASIC/solve-a-hopido-puzzle.basic new file mode 100644 index 0000000000..81c13dd990 --- /dev/null +++ b/Task/Solve-a-Hopido-puzzle/FreeBASIC/solve-a-hopido-puzzle.basic @@ -0,0 +1,80 @@ +Dim Shared As Integer neighbours(7, 1) => {{2, 2}, {-2, 2}, {2, -2}, {-2, -2}, {3, 0}, {0, 3}, {-3, 0}, {0, -3}} +Dim Shared As Integer cnt +Dim Shared As Integer pWid +Dim Shared As Integer pHei +Dim Shared As Integer pa() + +Function isValid(a As Integer, b As Integer) As Integer + Return (-1 < a And a < pWid And -1 < b And b < pHei) +End Function + +Function iterate(pa() As Integer, x As Integer, y As Integer, v As Integer) As Integer + If v > cnt Then Return 1 + Dim As Integer i, a, b, r + For i = Lbound(neighbours, 1) To Ubound(neighbours, 1) + a = x + neighbours(i, 0) + b = y + neighbours(i, 1) + If isValid(a, b) And pa(a, b) = 0 Then + pa(a, b) = v + r = iterate(pa(), a, b, v + 1) + If r = 1 Then Return r + pa(a, b) = 0 + End If + Next i + Return 0 +End Function + +Function solve(pz As String, w As Integer, h As Integer) As Boolean + Redim pa(w - 1, h - 1) As Integer + + Dim As Integer f, y, x + pWid = w + pHei = h + For y = 0 To h - 1 + For x = 0 To w - 1 + If Mid(pz, f + 1, 1) = "1" Then + pa(x, y) = 0 + cnt += 1 + Else + pa(x, y) = -1 + End If + f += 1 + Next x + Next y + + For y = 0 To h - 1 + For x = 0 To w - 1 + If pa(x, y) = 0 Then + pa(x, y) = 1 + If iterate(pa(), x, y, 2) = 1 Then Return True + pa(x, y) = 0 + End If + Next x + Next y + Return False +End Function + +Sub printSolution(w As Integer, h As Integer) + Dim As Integer i, j + + For j = 0 To h - 1 + For i = 0 To w - 1 + If pa(i, j) = -1 Then + Print " "; + Else + Print Using " ##"; pa(i, j); + End If + Next i + Print + Next j +End Sub + +Dim As Integer r +r = solve("011011011111111111111011111000111000001000", 7, 6) +If r Then + printSolution(7, 6) +Else + Print "No solution!" +End If + +Sleep diff --git a/Task/Solve-a-Hopido-puzzle/JavaScript/solve-a-hopido-puzzle.js b/Task/Solve-a-Hopido-puzzle/JavaScript/solve-a-hopido-puzzle.js new file mode 100644 index 0000000000..a9d30c8b93 --- /dev/null +++ b/Task/Solve-a-Hopido-puzzle/JavaScript/solve-a-hopido-puzzle.js @@ -0,0 +1,146 @@ +class Node { + constructor() { + this.val = 0; + this.neighbors = 0; + } +} + +class NSolver { + constructor() { + this.dx = new Array(8); + this.dy = new Array(8); + this.wid = 0; + this.hei = 0; + this.max = 0; + this.arr = null; + + this.dx[0] = -2; this.dy[0] = -2; this.dx[1] = -2; this.dy[1] = 2; + this.dx[2] = 2; this.dy[2] = -2; this.dx[3] = 2; this.dy[3] = 2; + this.dx[4] = -3; this.dy[4] = 0; this.dx[5] = 3; this.dy[5] = 0; + this.dx[6] = 0; this.dy[6] = -3; this.dx[7] = 0; this.dy[7] = 3; + } + + solve(puzz, maxWid) { + if (puzz.length < 1) return; + + this.wid = maxWid; + this.hei = Math.floor(puzz.length / this.wid); + const len = this.wid * this.hei; + let c = 0; + this.max = len; + + this.arr = new Array(len); + for (let i = 0; i < len; i++) { + this.arr[i] = new Node(); + } + + for (let i = 0; i < puzz.length; i++) { + if (puzz[i] === "*") { + this.max--; + this.arr[c++].val = -1; + continue; + } + // Handle both "." and number cases properly + this.arr[c].val = puzz[i] === "." ? 0 : parseInt(puzz[i]); + c++; + } + + this.solveIt(); + + c = 0; + for (let i = 0; i < puzz.length; i++) { + if (puzz[i] === ".") { + puzz[i] = this.arr[c].val.toString(); + } + c++; + } + + return puzz; + } + + search(x, y, w) { + if (w > this.max) return true; + + const n = this.arr[x + y * this.wid]; + n.neighbors = this.getNeighbors(x, y); + + for (let d = 0; d < 8; d++) { + if (n.neighbors & (1 << d)) { + const a = x + this.dx[d]; + const b = y + this.dy[d]; + if (this.arr[a + b * this.wid].val === 0) { + this.arr[a + b * this.wid].val = w; + if (this.search(a, b, w + 1)) return true; + this.arr[a + b * this.wid].val = 0; + } + } + } + return false; + } + + getNeighbors(x, y) { + let c = 0; + for (let xx = 0; xx < 8; xx++) { + const a = x + this.dx[xx]; + const b = y + this.dy[xx]; + if (a < 0 || b < 0 || a >= this.wid || b >= this.hei) continue; + if (this.arr[a + b * this.wid].val > -1) c |= (1 << xx); + } + return c; + } + + solveIt() { + const result = this.findStart(); + if (result.z === 99999) { + console.log("\nCan't find start point!\n"); + return; + } + this.search(result.x, result.y, result.z + 1); + } + + findStart() { + for (let b = 0; b < this.hei; b++) { + for (let a = 0; a < this.wid; a++) { + if (this.arr[a + this.wid * b].val === 0) { + const x = a; + const y = b; + const z = 1; + this.arr[a + this.wid * b].val = z; + return { x, y, z }; + } + } + } + return { x: 0, y: 0, z: 99999 }; + } +} + +function main() { + const wid = 7; + const p = "* . . * . . * . . . . . . . . . . . . . . * . . . . . * * * . . . * * * * * . * * *"; + const puzz = p.split(" "); + + const solver = new NSolver(); + const result = solver.solve(puzz, wid); + + let c = 0; + let output = ""; + + for (let i = 0; i < result.length; i++) { + if (result[i] !== "*" && result[i] !== ".") { + const num = parseInt(result[i]); + if (!isNaN(num) && num < 10) output += "0"; + output += result[i] + " "; + } else { + output += " "; + } + + if (++c >= wid) { + output += "\n"; + c = 0; + } + } + + console.log(output); +} + +main(); diff --git a/Task/Solve-a-Hopido-puzzle/Julia/solve-a-hopido-puzzle.julia b/Task/Solve-a-Hopido-puzzle/Julia/solve-a-hopido-puzzle.jl similarity index 100% rename from Task/Solve-a-Hopido-puzzle/Julia/solve-a-hopido-puzzle.julia rename to Task/Solve-a-Hopido-puzzle/Julia/solve-a-hopido-puzzle.jl diff --git a/Task/Solve-a-Hopido-puzzle/Kotlin/solve-a-hopido-puzzle.kotlin b/Task/Solve-a-Hopido-puzzle/Kotlin/solve-a-hopido-puzzle.kts similarity index 100% rename from Task/Solve-a-Hopido-puzzle/Kotlin/solve-a-hopido-puzzle.kotlin rename to Task/Solve-a-Hopido-puzzle/Kotlin/solve-a-hopido-puzzle.kts diff --git a/Task/Solve-a-Hopido-puzzle/Rust/solve-a-hopido-puzzle.rs b/Task/Solve-a-Hopido-puzzle/Rust/solve-a-hopido-puzzle.rs new file mode 100644 index 0000000000..0d2536a530 --- /dev/null +++ b/Task/Solve-a-Hopido-puzzle/Rust/solve-a-hopido-puzzle.rs @@ -0,0 +1,258 @@ +use std::io::{self, Write}; // Import Write trait for flush + +const DX: [i32; 8] = [-2, -2, 2, 2, -3, 3, 0, 0]; +const DY: [i32; 8] = [-2, 2, -2, 2, 0, 0, -3, 3]; + +// Equivalent to C++ 'node' struct +#[derive(Clone, Copy, Debug, Default)] +struct Node { + val: i32, // -1 for obstacle, 0 for empty, >0 for number + neighbors: u8, // Bitmask of valid moves (indices into DX/DY) +} + +// Equivalent to C++ 'nSolver' class +struct NSolver { + wid: usize, + hei: usize, + max_val: i32, // The highest number to place (number of non-obstacle cells) + arr: Vec, +} + +impl NSolver { + // Main function to set up and run the solver + // Modifies the input 'puzz' vector in place + pub fn solve_puzzle(puzz: &mut Vec, max_wid: usize) { + if puzz.is_empty() { + return; + } + + let wid = max_wid; + if wid == 0 { + eprintln!("Error: Width cannot be zero."); + return; + } + let hei = puzz.len() / wid; + if hei * wid != puzz.len() { + eprintln!("Error: Puzzle size ({}) must be a multiple of width ({}).", puzz.len(), wid); + return; + } + + let len = wid * hei; + + // --- START FIX --- + // Create a record of which cells were originally "." BEFORE creating the solver/modifying arr + let was_originally_dot: Vec = puzz.iter().map(|s| s == ".").collect(); + // --- END FIX --- + + let mut arr = vec![Node::default(); len]; + let mut max_val = 0; // Count non-obstacle cells + + // Initialize 'arr' based on the initial 'puzz' state + for (c, item) in puzz.iter().enumerate() { + if c >= len { break; } // Should not happen with the size check above, but safe + + // Match the C++ logic: '*' is obstacle (-1), others are parsed or default to 0. + // Count non-obstacles towards the max value to be filled. + if item == "*" { + arr[c].val = -1; + } else { + // atoi returns 0 for non-numeric strings like ".". + arr[c].val = item.parse::().unwrap_or(0); + max_val += 1; + } + } + + // Check if there's anything to solve + if max_val == 0 { + println!("\nNo valid cells to fill (all obstacles?)."); + return; // Nothing to solve + } + + let mut solver = NSolver { + wid, + hei, + max_val, + arr, + }; + + // Find start and solve + solver.solve_it(); + + // Update the original puzz vector with results + // Now use the 'was_originally_dot' vector for the check + for (c, item) in puzz.iter_mut().enumerate() { + if c >= solver.arr.len() { break; } // Safety break + + // --- Use the pre-calculated boolean --- + if was_originally_dot[c] { + let node_val = solver.arr[c].val; + // Only update if the solver actually put a positive number there? + // C++ seems to update with whatever is in arr[c] (could be 0 if not reached). + // Let's stick to that behavior. + if node_val >= 0 { // Avoid writing "-1" into a "." cell + *item = node_val.to_string(); + } else { + // If for some reason the solver put -1 here, leave it as "."? + // This case seems unlikely if logic is correct. + eprintln!("Warning: Obstacle value (-1) found at index {} which was originally '.'", c); + *item = ".".to_string(); // Keep it as dot? Or maybe solver.arr[c].val.to_string()? + } + + } + // Cells that were not originally "." remain unchanged. + } + } + + // Internal function to orchestrate the solving process + + fn solve_it(&mut self) { + match self.find_start() { + Some((x, y, start_val)) => { + if !self.search(x, y, start_val + 1) { + println!("\nSearch failed to find a complete path from start ({}, {}). Board may be partially filled.", x, y); + } + // else: Search succeeded, board is filled (or should be) + } + None => { + // Check if already solved (no zeros found) or impossible + let has_zero = self.arr.iter().any(|node| node.val == 0); + if !has_zero && self.max_val > 0 { + // This case could happen if the input already contained a partial or full solution + // and find_start requires a 0 to begin. + println!("\nPuzzle seems pre-filled or already solved. No empty cell (0) found to start search."); + } else if self.max_val > 0 { + // This means find_start iterated through all cells and none were 0. + // Could happen if the board is all obstacles, or already fully numbered. + println!("\nCan't find start point (an empty cell with value 0)! Check input puzzle."); + } + // The max_val == 0 case is handled earlier in solve_puzzle + } + } + } + + // Find the first empty cell (value 0), set it to 1, and return its info + fn find_start(&mut self) -> Option<(usize, usize, i32)> { + for y in 0..self.hei { + for x in 0..self.wid { + let index = x + y * self.wid; + // Ensure we don't try to access out of bounds if arr size is wrong + if index < self.arr.len() && self.arr[index].val == 0 { + self.arr[index].val = 1; // Set start value to 1 + return Some((x, y, 1)); // Return coords and the value assigned (1) + } + } + } + None // No cell with value 0 found + } + + // Recursive backtracking search function + fn search(&mut self, x: usize, y: usize, w: i32) -> bool { + if w > self.max_val { + return true; // Successfully placed all numbers + } + + let current_index = x + y * self.wid; + // Calculate and store neighbors for the current node + self.arr[current_index].neighbors = self.get_neighbors(x, y); + let neighbors_mask = self.arr[current_index].neighbors; + + for d in 0..8 { // Iterate through 8 possible moves + if (neighbors_mask & (1 << d)) != 0 { // Check if the d-th neighbor is valid + let next_x_i32 = (x as i32) + DX[d]; + let next_y_i32 = (y as i32) + DY[d]; + + // Bounds check (redundant if get_neighbors is correct, but safe) + if next_x_i32 >= 0 && next_x_i32 < self.wid as i32 && + next_y_i32 >= 0 && next_y_i32 < self.hei as i32 + { + let next_x = next_x_i32 as usize; + let next_y = next_y_i32 as usize; + let next_index = next_x + next_y * self.wid; + + // Check bounds on arr access too + if next_index < self.arr.len() && self.arr[next_index].val == 0 { + self.arr[next_index].val = w; // Place the next number + + if self.search(next_x, next_y, w + 1) { // Recurse + return true; // Found a valid path + } + + // Backtrack: If the recursive call failed, undo the move + // Check index before backtracking write too + if next_index < self.arr.len() { + self.arr[next_index].val = 0; + } + } + } + } + } + false // If no neighbor leads to a solution + } + + // Calculate the neighbor bitmask for a given cell (x, y) + fn get_neighbors(&self, x: usize, y: usize) -> u8 { + let mut c = 0u8; + for d in 0..8 { // Check all 8 potential moves + let nx_i32 = (x as i32) + DX[d]; + let ny_i32 = (y as i32) + DY[d]; + + // Check bounds + if nx_i32 >= 0 && nx_i32 < self.wid as i32 && + ny_i32 >= 0 && ny_i32 < self.hei as i32 + { + let index = (nx_i32 as usize) + (ny_i32 as usize) * self.wid; + // Check bounds on arr access + if index < self.arr.len() && self.arr[index].val > -1 { // Check not obstacle + c |= 1 << d; // Set the d-th bit + } + } + } + c + } +} // end impl NSolver + + + + +fn main() { + let p = "* . . * . . * . . . . . . . . . . . . . . * . . . . . * * * . . . * * * * * . * * *"; + let wid = 7; + + let mut puzz: Vec = p.split_whitespace().map(String::from).collect(); + + NSolver::solve_puzzle(&mut puzz, wid); + + println!("Solved Puzzle:"); + for (c, item) in puzz.iter().enumerate() { + match item.as_str() { + "*" => print!(" "), // Obstacle + "." => print!(" . "), // Unfilled cell + _ => { + match item.parse::() { + Ok(n) => { + // Handle 0 specifically - it means a '.' cell wasn't reached by the solver + if n == 0 { + print!(" . "); + } else if n < 10 { + print!("0{} ", n); // Pad single digits + } else { + print!("{} ", n); + } + } + Err(_) => { // Should ideally not happen if we only write numbers or "." back + print!(" ? "); + } + } + } + } + if (c + 1) % wid == 0 { + println!(); + } + } + println!("\n"); + + println!("Press Enter to exit..."); + let _ = io::stdout().flush(); + let mut buffer = String::new(); + io::stdin().read_line(&mut buffer).expect("Failed to read line"); +} diff --git a/Task/Solve-a-Numbrix-puzzle/11l/solve-a-numbrix-puzzle.11l b/Task/Solve-a-Numbrix-puzzle/11l/solve-a-numbrix-puzzle.11l index 6f73693f79..5e46584b41 100644 --- a/Task/Solve-a-Numbrix-puzzle/11l/solve-a-numbrix-puzzle.11l +++ b/Task/Solve-a-Numbrix-puzzle/11l/solve-a-numbrix-puzzle.11l @@ -1,87 +1,91 @@ -V neighbours = [[-1, 0], [0, -1], [1, 0], [0, 1]] -[Int] exists -V lastNumber = 0 -V wid = 0 -V hei = 0 +V MOVES = [(1, 0), (0, 1), (-1, 0), (0, -1)] -F find_next(pa, x, y, z) - L(i) 4 - V a = x + :neighbours[i][0] - V b = y + :neighbours[i][1] - I a C -1 <.< :wid & b C -1 <.< :hei - I pa[a][b] == z - R (a, b) - R (-1, -1) +T Numbrix + [[Int]] grid + [Int] clues + Int totalToFill + Int startRow + Int startCol -F find_solution(&pa, x, y, z) - I z > :lastNumber - R 1 - I :exists[z] == 1 - V s = find_next(pa, x, y, z) - I s[0] < 0 - R 0 - R find_solution(&pa, s[0], s[1], z + 1) + F solve(row, col, Int count, Int =nextClue) -> Bool + I count > .totalToFill + R 1B + V back = .grid[row][col] + I back !C [0, count] + R 0B + I back == 0 & nextClue < .clues.len & .clues[nextClue] == count + R 0B + nextClue = nextClue + I back == count + nextClue++ + .grid[row][col] = count + L(move) :MOVES + I .solve(row + move[1], col + move[0], count + 1, nextClue) + R 1B + .grid[row][col] = back + R 0B - L(i) 4 - V a = x + :neighbours[i][0] - V b = y + :neighbours[i][1] - I a C -1 <.< :wid & b C -1 <.< :hei - I pa[a][b] == 0 - pa[a][b] = z - V r = find_solution(&pa, a, b, z + 1) - I r == 1 - R 1 - pa[a][b] = 0 - R 0 - -F solve(pz, w, h) - :lastNumber = w * h - :wid = w - :hei = h - :exists = [0] * (:lastNumber + 1) - - V pa = [[0] * h] * w - V st = pz.split(‘ ’) - V idx = 0 - - L(j) 0 .< h - L(i) 0 .< w - I st[idx] == ‘.’ - idx++ - E - pa[i][j] = Int(st[idx]) - :exists[pa[i][j]] = 1 - idx++ - - V x = 0 - V y = 0 - V t = w * h + 1 - L(j) 0 .< h - L(i) 0 .< w - I pa[i][j] != 0 & pa[i][j] < t - t = pa[i][j] - x = i - y = j - - R (find_solution(&pa, x, y, t + 1), pa) - -F show_result(r) - I r[0] == 1 - L(j) 0 .< :hei - L(i) 0 .< :wid - print(‘ #02’.format(r[1][i][j]), end' ‘’) + F xprint() + L(row) .grid + L(val) row + I val != -1 + print(f:‘{val:02} ’, end' ‘’) print() + +F initNumbrix([String] board) -> Numbrix + V result = Numbrix() + V nRows = board.len + V nCols = board[0].split(‘,’).len + result.grid = [[-1] * (nCols + 2)] * (nRows + 2) + result.totalToFill = nRows * nCols + [Int] xlist + L(row) board + V r = L.index + L(tile) row.split(‘,’) + V c = L.index + V val = Int(tile) + result.grid[r + 1][c + 1] = val + I val > 0 + xlist.append(val) + I val == 1 + result.startRow = r + 1 + result.startCol = c + 1 + xlist.sort() + result.clues = xlist + R result + +V EXAMPLE1 = [‘00,00,00,00,00,00,00,00,00’, + ‘00,00,46,45,00,55,74,00,00’, + ‘00,38,00,00,43,00,00,78,00’, + ‘00,35,00,00,00,00,00,71,00’, + ‘00,00,33,00,00,00,59,00,00’, + ‘00,17,00,00,00,00,00,67,00’, + ‘00,18,00,00,11,00,00,64,00’, + ‘00,00,24,21,00,01,02,00,00’, + ‘00,00,00,00,00,00,00,00,00’] +V EXAMPLE2 = [‘00,00,00,00,00,00,00,00,00’, + ‘00,11,12,15,18,21,62,61,00’, + ‘00,06,00,00,00,00,00,60,00’, + ‘00,33,00,00,00,00,00,57,00’, + ‘00,32,00,00,00,00,00,56,00’, + ‘00,37,00,01,00,00,00,73,00’, + ‘00,38,00,00,00,00,00,72,00’, + ‘00,43,44,47,48,51,76,77,00’, + ‘00,00,00,00,00,00,00,00,00’] +V EXAMPLE3 = [‘17,00,00,00,11,00,00,00,59’, + ‘00,15,00,00,06,00,00,61,00’, + ‘00,00,03,00,00,00,63,00,00’, + ‘00,00,00,01,66,00,00,00,00’, + ‘23,24,00,68,67,78,00,54,55’, + ‘00,00,00,00,72,00,00,00,00’, + ‘00,00,35,00,00,00,49,00,00’, + ‘00,29,00,00,40,00,00,47,00’, + ‘31,00,00,00,39,00,00,00,45’] + +L(board) [EXAMPLE1, EXAMPLE2, EXAMPLE3] + V numbrix = initNumbrix(board) + I numbrix.solve(numbrix.startRow, numbrix.startCol, 1, 0) + print(‘Solution for example ’(L.index + 1)‘:’, end' ‘’) + numbrix.xprint() E - print(‘No Solution!’) - - print() - -V r = solve(‘. . . . . . . . . . . 46 45 . 55 74 . . . 38 . . 43 . . 78 . . 35 . . . . . 71 . . . 33 . . . 59 . . . 17’"" - ‘ . . . . . 67 . . 18 . . 11 . . 64 . . . 24 21 . 1 2 . . . . . . . . . . .’, 9, 9) -show_result(r) -r = solve(‘. . . . . . . . . . 11 12 15 18 21 62 61 . . 6 . . . . . 60 . . 33 . . . . . 57 . . 32 . . . . . 56 . . 37’"" - ‘ . 1 . . . 73 . . 38 . . . . . 72 . . 43 44 47 48 51 76 77 . . . . . . . . . .’, 9, 9) -show_result(r) -r = solve(‘17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . . 63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55’"" - ‘ . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45’, 9, 9) -show_result(r) + print(‘No solution.’) diff --git a/Task/Solve-a-Numbrix-puzzle/ALGOL-68/solve-a-numbrix-puzzle.alg b/Task/Solve-a-Numbrix-puzzle/ALGOL-68/solve-a-numbrix-puzzle.alg new file mode 100644 index 0000000000..cb88b7c77a --- /dev/null +++ b/Task/Solve-a-Numbrix-puzzle/ALGOL-68/solve-a-numbrix-puzzle.alg @@ -0,0 +1,132 @@ +BEGIN # solve a Numbrix puzzle - based on the Wren Hidato solver plus this # + # solves puzzles with 1 as an unknown using the zkl sample's method # + PR read "sort.incl.a68" PR # include sort utilities # + + [,]INT moves = ( ( 1, 0 ), ( 0, 1 ), ( -1, 0 ), ( 0, -1 ) ); + + # returns TRUE if a solution for board with the specified given values # + # ( the values initially placed on the board ) can be found # + # n is the value to place, r and c the starting row and column # + # and next the position of the next value in given # + # returns FALSE if a solution cannot be found # + PROC solve board with givens = ( REF[,]INT board, []INT given, INT r, c, n, next, board size )BOOL: + IF n > board size + THEN TRUE + ELIF r < 1 LWB board OR r > 1 UPB board + OR c < 2 LWB board OR c > 2 UPB board + THEN FALSE + ELIF INT back = board[ r, c ]; + back /= 0 AND back /= n + THEN FALSE + ELIF back = 0 AND IF next > UPB given THEN FALSE ELSE given[ next ] = n FI + THEN FALSE + ELSE INT next2 = IF back = n THEN next + 1 ELSE next FI; + board[ r, c ] := n; + BOOL found := FALSE; + FOR m pos FROM 1 LWB moves TO 1 UPB moves + WHILE INT rm = r + moves[ m pos, 2 LWB moves ]; + INT cm = c + moves[ m pos, 2 UPB moves ]; + NOT ( found := solve board with givens( board, given, rm, cm, n + 1, next2, board size ) ) + DO SKIP OD; + IF NOT found THEN board[ r, c ] := back FI; + found + FI # solve board with givens # ; + + # returns the solution for board data # + # or an empty board if there isn't one # + PROC solve = ( [,]INT board data )[,]INT: + BEGIN + [ 1 LWB board data : 1 UPB board data + , 2 LWB board data : 2 UPB board data + ]INT board := board data; + INT board size = ( ( 1 UPB board - 1 LWB board ) + 1 ) + * ( ( 2 UPB board - 2 LWB board ) + 1 ) + ; + [ 1 : board size ]INT given1; + INT g pos := 0, start r := 0, start c := 0; + FOR i FROM 1 LWB board TO 1 UPB board DO + FOR j FROM 2 LWB board TO 2 UPB board DO + IF board[ i, j ] > 0 THEN + given1[ g pos +:= 1 ] := board[ i, j ]; + IF board[ i, j ] = 1 THEN start r := i; start c := j FI + FI + OD + OD; + IF start r = 0 THEN # need to pretend 1 is on the board, even # + given1[ g pos +:= 1 ] := 1 # though is isn't # + FI; + [ 1 : g pos ]INT given := given1[ 1 : g pos ]; + QUICKSORT given; + BOOL solved := FALSE; + IF start r /= 0 THEN # the position of 1 is known # + solved := solve board with givens( board, given, start r, start c, 1, 1, board size ) + ELSE # try 1 in all empty places until we find a solution # + FOR r pos FROM 1 LWB board TO 1 UPB board WHILE NOT solved DO + FOR c pos FROM 2 LWB board TO 2 UPB board WHILE NOT solved DO + IF board[ r pos, c pos ] = 0 THEN + board[ r pos, c pos ] := 1; + solved := solve board with givens( board, given, r pos, c pos, 1, 1, board size ); + IF NOT solved THEN board[ r pos, c pos ] := 0 FI + FI + OD + OD + FI; + IF solved THEN board ELSE [ 1 : 0, 1 : 0 ]INT no solution; no solution FI + END # solve # ; + + PROC print board = ( [,]INT board )VOID: + FOR i FROM 1 LWB board TO 1 UPB board DO + FOR j FROM 2 LWB board TO 2 UPB board DO + INT v = board[ i, j ]; + IF v < 0 THEN print( ( " " ) ) + ELIF v = 0 THEN print( ( " __" ) ) + ELSE print( ( whole( v, -3 ) ) ) + FI + OD; + print( ( newline ) ) + OD # print board # ; + + + [,,]INT tests = ( ( ( 0, 0, 0, 0, 0, 0, 0, 0, 0 ) + , ( 0, 0, 46, 45, 0, 55, 74, 0, 0 ) + , ( 0, 38, 0, 0, 43, 0, 0, 78, 0 ) + , ( 0, 35, 0, 0, 0, 0, 0, 71, 0 ) + , ( 0, 0, 33, 0, 0, 0, 59, 0, 0 ) + , ( 0, 17, 0, 0, 0, 0, 0, 67, 0 ) + , ( 0, 18, 0, 0, 11, 0, 0, 64, 0 ) + , ( 0, 0, 24, 21, 0, 1, 2, 0, 0 ) + , ( 0, 0, 0, 0, 0, 0, 0, 0, 0 ) + ) + , ( ( 0, 0, 0, 0, 0, 0, 0, 0, 0 ) + , ( 0, 11, 12, 15, 18, 21, 62, 61, 0 ) + , ( 0, 6, 0, 0, 0, 0, 0, 60, 0 ) + , ( 0, 33, 0, 0, 0, 0, 0, 57, 0 ) + , ( 0, 32, 0, 0, 0, 0, 0, 56, 0 ) + , ( 0, 37, 0, 1, 0, 0, 0, 73, 0 ) + , ( 0, 38, 0, 0, 0, 0, 0, 72, 0 ) + , ( 0, 43, 44, 47, 48, 51, 76, 77, 0 ) + , ( 0, 0, 0, 0, 0, 0, 0, 0, 0 ) + ) + , ( ( 17, 0, 0, 0, 11, 0, 0, 0, 59 ) + , ( 0, 15, 0, 0, 6, 0, 0, 61, 0 ) + , ( 0, 0, 3, 0, 0, 0, 63, 0, 0 ) + , ( 0, 0, 0, 0, 66, 0, 0, 0, 0 ) + , ( 23, 24, 0, 68, 67, 78, 0, 54, 55 ) + , ( 0, 0, 0, 0, 72, 0, 0, 0, 0 ) + , ( 0, 0, 35, 0, 0, 0, 49, 0, 0 ) + , ( 0, 29, 0, 0, 40, 0, 0, 47, 0 ) + , ( 31, 0, 0, 0, 39, 0, 0, 0, 45 ) + ) + ); + FOR t pos FROM 1 LWB tests TO 1 UPB tests DO + [,]INT board = tests[ t pos, : , : ]; + print board( board ); + print( ( newline ) ); + IF [,]INT solution = solve( board ); + 1 LWB solution > 1 UPB solution + THEN print( ( "No solution found", newline ) ) + ELSE print board( solution ) + FI; + print( ( newline ) ) + OD +END diff --git a/Task/Solve-a-Numbrix-puzzle/Dart/solve-a-numbrix-puzzle.dart b/Task/Solve-a-Numbrix-puzzle/Dart/solve-a-numbrix-puzzle.dart new file mode 100644 index 0000000000..0178290da7 --- /dev/null +++ b/Task/Solve-a-Numbrix-puzzle/Dart/solve-a-numbrix-puzzle.dart @@ -0,0 +1,92 @@ +/// Based on https://rosettacode.org/wiki/Solve_a_Numbrix_puzzle#Kotlin +import 'package:more/more.dart'; +import 'package:sprintf/sprintf.dart'; + +const examples = [ + [ + "00,00,00,00,00,00,00,00,00", + "00,00,46,45,00,55,74,00,00", + "00,38,00,00,43,00,00,78,00", + "00,35,00,00,00,00,00,71,00", + "00,00,33,00,00,00,59,00,00", + "00,17,00,00,00,00,00,67,00", + "00,18,00,00,11,00,00,64,00", + "00,00,24,21,00,01,02,00,00", + "00,00,00,00,00,00,00,00,00" + ], + [ + "00,00,00,00,00,00,00,00,00", + "00,11,12,15,18,21,62,61,00", + "00,06,00,00,00,00,00,60,00", + "00,33,00,00,00,00,00,57,00", + "00,32,00,00,00,00,00,56,00", + "00,37,00,01,00,00,00,73,00", + "00,38,00,00,00,00,00,72,00", + "00,43,44,47,48,51,76,77,00", + "00,00,00,00,00,00,00,00,00" + ] +]; + +const moves = [ + [1, 0], + [0, 1], + [-1, 0], + [0, -1] +]; + +late List board; +late List> grid; +late List clues; +var totalToFill = 0; + +bool solve(int r, int c, int count, int nextClue) { + if (count > totalToFill) return true; + var back = grid[r][c]; + if (back != 0 && back != count) return false; + if (back == 0 && nextClue < clues.length && clues[nextClue] == count) { + return false; + } + + var nextClue2 = nextClue; + if (back == count) nextClue2++; + grid[r][c] = count; + var res = moves.any((m) => solve(r + m[1], c + m[0], count + 1, nextClue2)); + if (!res) grid[r][c] = back; + return res; +} + +void printResult(int n) { + print("Solution for example $n:"); + for (var row in grid) { + print([ + for (var e in row) + if (e != -1) sprintf("%2d ", [e]) + ].join()); + } +} + +main() { + for (var each in examples.indexed()) { + board = each.value; + var nRows = board.length + 2, nCols = board[0].split(",").length + 2; + var startRow = 0, startCol = 0; + grid = List.generate(nRows, (i) => List.filled(nCols, -1)); + totalToFill = (nRows - 2) * (nCols - 2); + var lst = []; + for (var r in 1.to(nRows - 1)) { + var row = board[r - 1].split(","); + for (var c in 1.to(nCols - 1)) { + var value = int.parse(row[c - 1]); + if (value > 0) lst.add(value); + if (value == 1) { + startRow = r; + startCol = c; + } + grid[r][c] = value; + } + } + + clues = (lst..sort()).toList(); + if (solve(startRow, startCol, 1, 0)) printResult(each.index + 1); + } +} diff --git a/Task/Solve-a-Numbrix-puzzle/EasyLang/solve-a-numbrix-puzzle.easy b/Task/Solve-a-Numbrix-puzzle/EasyLang/solve-a-numbrix-puzzle.easy new file mode 100644 index 0000000000..eb3600a661 --- /dev/null +++ b/Task/Solve-a-Numbrix-puzzle/EasyLang/solve-a-numbrix-puzzle.easy @@ -0,0 +1,76 @@ +moves[][] = [ [ -1 0 ] [ 0 -1 ] [ 0 1 ] [ 1 0 ] ] +global brd[][] maxr maxc maxcnt . +func solve r c cnt . + if cnt > maxcnt : return 1 + for m = 1 to 4 + rn = r + moves[m][1] + cn = c + moves[m][2] + if rn >= 1 and rn <= maxr and cn >= 1 and cn <= maxc + if brd[rn][cn] = 0 + brd[rn][cn] = cnt + if solve rn cn (cnt + 1) = 1 : return 1 + brd[rn][cn] = 0 + elif brd[rn][cn] = cnt + if solve rn cn (cnt + 1) = 1 : return 1 + . + . + . + return 0 +. +proc prepare brd$ &r0 &c0 . + brd$[] = strsplit brd$ "\n" + maxc = len brd$[2] / 3 + maxr = len brd$[] - 2 + maxcnt = maxc * maxr + len brd[][] maxr + for r to maxr + len brd[r][] maxc + for c to maxc + c$ = substr brd$[r + 1] (c * 3 - 2) 3 + h = number c$ + if h = 1 + r0 = r + c0 = c + . + brd[r][c] = h + . + . +. +proc printbrd . + numfmt 3 0 + for r to maxr + for c to maxc : write brd[r][c] + print "" + . +. +proc numbrix brd$ . + prepare brd$ r0 c0 + if solve r0 c0 2 = 1 + printbrd + else + print "no solutions found" + . + print "" +. +numbrix " + 0 0 0 0 0 0 0 0 0 + 0 0 46 45 0 55 74 0 0 + 0 38 0 0 43 0 0 78 0 + 0 35 0 0 0 0 0 71 0 + 0 0 33 0 0 0 59 0 0 + 0 17 0 0 0 0 0 67 0 + 0 18 0 0 11 0 0 64 0 + 0 0 24 21 0 1 2 0 0 + 0 0 0 0 0 0 0 0 0 +" +numbrix " + 0 0 0 0 0 0 0 0 0 + 0 11 12 15 18 21 62 61 0 + 0 6 0 0 0 0 0 60 0 + 0 33 0 0 0 0 0 57 0 + 0 32 0 0 0 0 0 56 0 + 0 37 0 1 0 0 0 73 0 + 0 38 0 0 0 0 0 72 0 + 0 43 44 47 48 51 76 77 0 + 0 0 0 0 0 0 0 0 0 +" diff --git a/Task/Solve-a-Numbrix-puzzle/Elixir/solve-a-numbrix-puzzle.elixir b/Task/Solve-a-Numbrix-puzzle/Elixir/solve-a-numbrix-puzzle.ex similarity index 100% rename from Task/Solve-a-Numbrix-puzzle/Elixir/solve-a-numbrix-puzzle.elixir rename to Task/Solve-a-Numbrix-puzzle/Elixir/solve-a-numbrix-puzzle.ex diff --git a/Task/Solve-a-Numbrix-puzzle/FreeBASIC/solve-a-numbrix-puzzle.basic b/Task/Solve-a-Numbrix-puzzle/FreeBASIC/solve-a-numbrix-puzzle.basic new file mode 100644 index 0000000000..45d6848892 --- /dev/null +++ b/Task/Solve-a-Numbrix-puzzle/FreeBASIC/solve-a-numbrix-puzzle.basic @@ -0,0 +1,120 @@ +Type Move + dx As Integer + dy As Integer +End Type + +Dim Shared As Move moves(3) = {(0, 1), (1, 0), (0, -1), (-1, 0)} +Dim Shared As Integer grid(10, 10) +Dim Shared As Integer clues(99) +Dim Shared As Integer clueCount, totalToFill + +Dim Shared As String example1(8) +example1(0) = "00,00,00,00,00,00,00,00,00" +example1(1) = "00,00,46,45,00,55,74,00,00" +example1(2) = "00,38,00,00,43,00,00,78,00" +example1(3) = "00,35,00,00,00,00,00,71,00" +example1(4) = "00,00,33,00,00,00,59,00,00" +example1(5) = "00,17,00,00,00,00,00,67,00" +example1(6) = "00,18,00,00,11,00,00,64,00" +example1(7) = "00,00,24,21,00,01,02,00,00" +example1(8) = "00,00,00,00,00,00,00,00,00" + +Dim Shared As String example2(8) +example2(0) = "00,00,00,00,00,00,00,00,00" +example2(1) = "00,11,12,15,18,21,62,61,00" +example2(2) = "00,06,00,00,00,00,00,60,00" +example2(3) = "00,33,00,00,00,00,00,57,00" +example2(4) = "00,32,00,00,00,00,00,56,00" +example2(5) = "00,37,00,01,00,00,00,73,00" +example2(6) = "00,38,00,00,00,00,00,72,00" +example2(7) = "00,43,44,47,48,51,76,77,00" +example2(8) = "00,00,00,00,00,00,00,00,00" + +Sub SortArray(arr() As Integer, n As Integer) + Dim As Integer i, j + For i = 0 To n - 2 + For j = 0 To n - 2 - i + If arr(j) > arr(j + 1) Then Swap arr(j), arr(j + 1) + Next j + Next i +End Sub + +Function solve(r As Integer, c As Integer, count As Integer, nextClue As Integer) As Boolean + If count > totalToFill Then Return True + + Dim As Integer back = grid(r, c) + If back <> 0 Andalso back <> count Then Return False + If back = 0 Andalso nextClue < clueCount Andalso clues(nextClue) = count Then Return False + If back = count Then nextClue += 1 + + grid(r, c) = count + For i As Integer = 0 To 3 + If solve(r + moves(i).dy, c + moves(i).dx, count + 1, nextClue) Then Return True + Next i + grid(r, c) = back + + Return False +End Function + +Sub printSolution(n As Integer) + Print "Solution for example " & n & !":\n" + For r As Integer = 1 To 9 + For c As Integer = 1 To 9 + If grid(r, c) = -1 Then Continue For + Print Using "## "; grid(r, c); + Next c + Print + Next r + Print +End Sub + +Sub main() + Dim As Integer n, i, r, c + Dim As String board(8) + + For n = 0 To 1 + If n = 0 Then + For i = 0 To 8: board(i) = example1(i): Next + Else + For i = 0 To 8: board(i) = example2(i): Next + End If + + Dim As Integer nRows = Ubound(board) + 3 + Dim As Integer nCols = 11 + Dim As Integer startRow = 0, startCol = 0 + totalToFill = (nRows - 2) * (nCols - 2) + clueCount = 0 + + For r = 0 To nRows - 1 + For c = 0 To nCols - 1 + grid(r, c) = -1 + Next c + If r >= 1 Andalso r < nRows - 1 Then + Dim As String row = board(r - 1) + Dim As Integer posic = 1 + For c = 1 To nCols - 2 + Dim As String cell = Mid(row, posic, 2) + posic += 3 + Dim As Integer valor = Cint(cell) + If valor > 0 Then + clues(clueCount) = valor + clueCount += 1 + End If + If valor = 1 Then + startRow = r + startCol = c + End If + grid(r, c) = valor + Next c + End If + Next r + + SortArray(clues(), clueCount) + + If solve(startRow, startCol, 1, 0) Then printSolution(n + 1) + Next n +End Sub + +main() + +Sleep diff --git a/Task/Solve-a-Numbrix-puzzle/JavaScript/solve-a-numbrix-puzzle.js b/Task/Solve-a-Numbrix-puzzle/JavaScript/solve-a-numbrix-puzzle.js new file mode 100644 index 0000000000..da020fa10a --- /dev/null +++ b/Task/Solve-a-Numbrix-puzzle/JavaScript/solve-a-numbrix-puzzle.js @@ -0,0 +1,110 @@ +const example1 = [ + "00,00,00,00,00,00,00,00,00", + "00,00,46,45,00,55,74,00,00", + "00,38,00,00,43,00,00,78,00", + "00,35,00,00,00,00,00,71,00", + "00,00,33,00,00,00,59,00,00", + "00,17,00,00,00,00,00,67,00", + "00,18,00,00,11,00,00,64,00", + "00,00,24,21,00,01,02,00,00", + "00,00,00,00,00,00,00,00,00", +]; + +const example2 = [ + "00,00,00,00,00,00,00,00,00", + "00,11,12,15,18,21,62,61,00", + "00,06,00,00,00,00,00,60,00", + "00,33,00,00,00,00,00,57,00", + "00,32,00,00,00,00,00,56,00", + "00,37,00,01,00,00,00,73,00", + "00,38,00,00,00,00,00,72,00", + "00,43,44,47,48,51,76,77,00", + "00,00,00,00,00,00,00,00,00", +]; + +const moves = [[1, 0], [0, 1], [-1, 0], [0, -1]]; + +let grid, clues, totalToFill; + +function solve(r, c, count, nextClue) { + if (count > totalToFill) { + return true; + } + + const back = grid[r][c]; + + if (back !== 0 && back !== count) { + return false; + } + + if (back === 0 && nextClue < clues.length && clues[nextClue] === count) { + return false; + } + + let newNextClue = nextClue; + if (back === count) { + newNextClue++; + } + + grid[r][c] = count; + for (const move of moves) { + if (solve(r + move[1], c + move[0], count + 1, newNextClue)) { + return true; + } + } + grid[r][c] = back; + return false; +} + +function printResult(n) { + console.log(`Solution for example ${n}:`); + for (const row of grid) { + let line = ""; + for (const i of row) { + if (i === -1) { + continue; + } + line += `${i.toString().padStart(2)} `; + } + console.log(line); + } +} + +function main() { + const boards = [example1, example2]; + + for (let n = 0; n < boards.length; n++) { + const board = boards[n]; + const nRows = board.length + 2; + const nCols = board[0].split(',').length + 2; + let startRow = 0, startCol = 0; + grid = Array(nRows).fill().map(() => Array(nCols).fill(-1)); + totalToFill = (nRows - 2) * (nCols - 2); + let lst = []; + + for (let r = 0; r < nRows; r++) { + if (r >= 1 && r < nRows - 1) { + const row = board[r - 1].split(','); + for (let c = 1; c < nCols - 1; c++) { + const val = parseInt(row[c - 1]); + if (val > 0) { + lst.push(val); + } + if (val === 1) { + startRow = r; + startCol = c; + } + grid[r][c] = val; + } + } + } + + lst.sort((a, b) => a - b); + clues = lst; + if (solve(startRow, startCol, 1, 0)) { + printResult(n + 1); + } + } +} + +main(); diff --git a/Task/Solve-a-Numbrix-puzzle/Jq/solve-a-numbrix-puzzle.jq b/Task/Solve-a-Numbrix-puzzle/Jq/solve-a-numbrix-puzzle.jq new file mode 100644 index 0000000000..122070750a --- /dev/null +++ b/Task/Solve-a-Numbrix-puzzle/Jq/solve-a-numbrix-puzzle.jq @@ -0,0 +1,80 @@ +def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .; + +def moves: [ [1, 0], [0, 1], [-1, 0], [0, -1] ]; + +# "All solutions" +# Can the puzzle be solved by placing the token $count at row $r, column $c? +# Input: { grid, clues, totalToFill } +def solve($r; $c; $count; $nextClue): + if $count > .totalToFill then . + else .grid[$r][$c] as $back + | if ($back != 0 and $back != $count) + or ($back == 0 and $nextClue < (.clues|length) and .clues[$nextClue] == $count) + then empty + else if $back == $count then .nextClue += 1 end + | .grid[$r][$c] = $count + | moves[] as $m + | solve($r + $m[1]; $c + $m[0]; $count + 1; $nextClue) + end + end ; + +def printResult: + .grid[1:-1][] as $row + | reduce range(1; $row|length -1) as $i (""; + . + (if $i != -1 then $row[$i] else "" end | lpad(3)) ); + +def task($board): + { clues: [] } + | (($board|length) + 2) as $nRows + | ($board[0]|split(",")|length + 2) as $nCols + | .startRow = 0 + | .startCol = 0 + | [range(0; $nCols) | -1] as $m1 + | .grid = [range(0; $nRows) | $m1] + | .totalToFill = ($nRows - 2) * ($nCols - 2) + | reduce range(0; $nRows) as $r (.; + if $r >= 1 and $r < $nRows - 1 + then ($board[$r - 1]|split(",")) as $row + | reduce range(1; $nCols - 1) as $c (.; + ($row[$c - 1] | sub("^0";"") | tonumber) as $value + | if $value > 0 then .clues += [$value] end + | if $value == 1 + then .startRow = $r + | .startCol = $c + end + | .grid[$r][$c] = $value ) + end ) + | .clues |= sort + | .startRow as $startRow + | .startCol as $startCol + | first(solve($startRow; $startCol; 1; 0)) + | printResult ; + +### Examples + +def example1: [ + "00,00,00,00,00,00,00,00,00", + "00,00,46,45,00,55,74,00,00", + "00,38,00,00,43,00,00,78,00", + "00,35,00,00,00,00,00,71,00", + "00,00,33,00,00,00,59,00,00", + "00,17,00,00,00,00,00,67,00", + "00,18,00,00,11,00,00,64,00", + "00,00,24,21,00,01,02,00,00", + "00,00,00,00,00,00,00,00,00" +]; + +def example2: [ + "00,00,00,00,00,00,00,00,00", + "00,11,12,15,18,21,62,61,00", + "00,06,00,00,00,00,00,60,00", + "00,33,00,00,00,00,00,57,00", + "00,32,00,00,00,00,00,56,00", + "00,37,00,01,00,00,00,73,00", + "00,38,00,00,00,00,00,72,00", + "00,43,44,47,48,51,76,77,00", + "00,00,00,00,00,00,00,00,00" +]; + + "Example 1", task(example1), +"\nExample 2", task(example2) diff --git a/Task/Solve-a-Numbrix-puzzle/Julia/solve-a-numbrix-puzzle-1.julia b/Task/Solve-a-Numbrix-puzzle/Julia/solve-a-numbrix-puzzle-1.jl similarity index 100% rename from Task/Solve-a-Numbrix-puzzle/Julia/solve-a-numbrix-puzzle-1.julia rename to Task/Solve-a-Numbrix-puzzle/Julia/solve-a-numbrix-puzzle-1.jl diff --git a/Task/Solve-a-Numbrix-puzzle/Julia/solve-a-numbrix-puzzle-2.julia b/Task/Solve-a-Numbrix-puzzle/Julia/solve-a-numbrix-puzzle-2.jl similarity index 100% rename from Task/Solve-a-Numbrix-puzzle/Julia/solve-a-numbrix-puzzle-2.julia rename to Task/Solve-a-Numbrix-puzzle/Julia/solve-a-numbrix-puzzle-2.jl diff --git a/Task/Solve-a-Numbrix-puzzle/Kotlin/solve-a-numbrix-puzzle.kotlin b/Task/Solve-a-Numbrix-puzzle/Kotlin/solve-a-numbrix-puzzle.kts similarity index 100% rename from Task/Solve-a-Numbrix-puzzle/Kotlin/solve-a-numbrix-puzzle.kotlin rename to Task/Solve-a-Numbrix-puzzle/Kotlin/solve-a-numbrix-puzzle.kts diff --git a/Task/Solve-a-Numbrix-puzzle/Pluto/solve-a-numbrix-puzzle.pluto b/Task/Solve-a-Numbrix-puzzle/Pluto/solve-a-numbrix-puzzle.pluto new file mode 100644 index 0000000000..b605c8a2a8 --- /dev/null +++ b/Task/Solve-a-Numbrix-puzzle/Pluto/solve-a-numbrix-puzzle.pluto @@ -0,0 +1,86 @@ +local fmt = require "fmt" +require "table2" + +local example1 = { + "00,00,00,00,00,00,00,00,00", + "00,00,46,45,00,55,74,00,00", + "00,38,00,00,43,00,00,78,00", + "00,35,00,00,00,00,00,71,00", + "00,00,33,00,00,00,59,00,00", + "00,17,00,00,00,00,00,67,00", + "00,18,00,00,11,00,00,64,00", + "00,00,24,21,00,01,02,00,00", + "00,00,00,00,00,00,00,00,00" +} + +local example2 = { + "00,00,00,00,00,00,00,00,00", + "00,11,12,15,18,21,62,61,00", + "00,06,00,00,00,00,00,60,00", + "00,33,00,00,00,00,00,57,00", + "00,32,00,00,00,00,00,56,00", + "00,37,00,01,00,00,00,73,00", + "00,38,00,00,00,00,00,72,00", + "00,43,44,47,48,51,76,77,00", + "00,00,00,00,00,00,00,00,00" +} + +local moves = { {1, 0}, {0, 1}, {-1, 0}, {0, -1} } + +local board, grid, clues +local total_to_fill = 0 + +local function solve(r, c, count, next_clue) + if count > total_to_fill then return true end + local back = grid[r][c] + if back != 0 and back != count then return false end + if back == 0 and next_clue <= #clues and clues[next_clue] == count then + return false + end + if back == count then next_clue += 1 end + grid[r][c] = count + for moves as m do + if solve(r + m[2], c + m[1], count + 1, next_clue) then return true end + end + grid[r][c] = back + return false +end + +local function print_result(n) + print($"Solution for example {n}:") + for grid as row do + for row as i do + if i != -1 then fmt.write("%2d ", i) end + end + print() + end +end + +for n, ex in {example1, example2} do + board = ex + local nrows = #board + 2 + local ncols = #board[1]:split(",") + 2 + local startrow = 1 + local startcol = 1 + grid = table.create(nrows) + for i = 1, nrows do grid[i] = table.rep(ncols, -1) end + total_to_fill = (nrows - 2) * (ncols - 2) + local lst = {} + for r = 1, nrows do + if r >= 2 and r < nrows then + local row = board[r - 1]:split(",") + for c = 2, ncols - 1 do + local value = tonumber(row[c - 1]) + if value > 0 then lst:insert(value) end + if value == 1 then + startrow = r + startcol = c + end + grid[r][c] = value + end + end + end + lst:sort() + clues = lst + if solve(startrow, startcol, 1, 1) then print_result(n) end +end diff --git a/Task/Solve-a-Numbrix-puzzle/Python/solve-a-numbrix-puzzle-1.py b/Task/Solve-a-Numbrix-puzzle/Python/solve-a-numbrix-puzzle-1.py new file mode 100644 index 0000000000..46a462c40b --- /dev/null +++ b/Task/Solve-a-Numbrix-puzzle/Python/solve-a-numbrix-puzzle-1.py @@ -0,0 +1,152 @@ +import re + + +class HidatoPuzzle: + """ Generic Hidato type puzzle solver, used here for Numbrix puzzles """ + + def __init__(self, board_text: str, allowed_moves: list[list[int]]): + """ initialize the puzzle from a board and the move rules + . means blocked, 0 or _ means open, numeric > 0 are fixed points + """ + lines = board_text.strip().split('\n') + self.nrows, self.ncols = len(lines), len(re.split(r'\s+', lines[0])) + self.board = [[-1] * self.ncols for _ in range(self.nrows)] + self.allowed_moves = allowed_moves + self.starts = [] + self.fixed = [] + self.solutions = [] + self.maxmoves = 0 + for i, line in enumerate(lines): + for j, s in enumerate(re.split(r'\s+', line.strip())): + c = s[0] + if c == '_' or c == '0' and len(s) == 1: + self.board[i][j] = 0 + self.maxmoves += 1 + elif c == '.': + continue # remains -1, blocked + else: # get digits and add to fixed numeric positions as > 0 + self.board[i][j] = int(s) + self.fixed.append(self.board[i][j]) + if self.board[i][j] == 1: + self.starts.append((i, j)) + self.maxmoves += 1 + + self.fixed.sort() + if len(self.starts) != 1: # 1 is not fixed, so we can start at any (0) + self.starts = [] + for i in range(self.nrows): + for j in range(self.ncols): + if self.board[i][j] == 0: + self.starts.append((i, j)) + + def solve(self): + """ solve puzzle: if start (1) not fixed may give multiple solutions """ + for xy in self.starts: + saved = self.board + self.board = [r[:] for r in self.board] + if self.dfs(xy[0], xy[1], 1): + self.solutions.append(self.board) + self.board = saved + + return len(self.solutions) > 0 + + def dfs(self, row, col, current_target): + """ depth first search for a solution """ + if current_target > self.maxmoves: + return True + n = self.board[row][col] + if not n in (0, current_target) or n == 0 and current_target in self.fixed: + return False + backnum = n # backup board[row][col] value before trying change + self.board[row][col] = current_target + for move in self.allowed_moves: + i, j = row + move[0], col + move[1] + if 0 <= i < self.nrows and 0 <= j < self.ncols and \ + self.dfs(i, j, current_target + 1): + return True + + self.board[row][col] = backnum # restore board to original state + return False + + def print_matrix(self, mat, emptysquare=" 0 ", blocked=" . "): + """ pretty print 2D matrix with substitution for 0 or blocked values """ + d = {-1: blocked, 0: emptysquare, -2: '\n'} + for i in range(self.nrows * self.ncols): + d[i + 1] = str(i + 1).center(3, ' ') + + for r in range(self.nrows): + for c in range(self.ncols): + print(d[mat[r][c]], end='') + print() + + def print_starting_board(self): + """ print input board """ + self.print_matrix(self.board) + + def is_solved(self): + """ true if there is at least 1 solution """ + return len(self.solutions) > 0 + + def print_solution(self, print_all=True): + """ print solution board(s) """ + n_solutions = len(self.solutions) + print(f"\n{n_solutions} solution{'s' if n_solutions != 1 else ''} found.") + for b in self.solutions: + self.print_matrix(b, '__ ') + if not print_all: + break + print() + + +if __name__ == '__main__': + NUMBRIX_TESTS = [ + """ + 0 0 0 0 0 0 0 0 0 + 0 0 46 45 0 55 74 0 0 + 0 38 0 0 43 0 0 78 0 + 0 35 0 0 0 0 0 71 0 + 0 0 33 0 0 0 59 0 0 + 0 17 0 0 0 0 0 67 0 + 0 18 0 0 11 0 0 64 0 + 0 0 24 21 0 1 2 0 0 + 0 0 0 0 0 0 0 0 0 + """, + """ + 0 0 0 0 0 0 0 0 0 + 0 11 12 15 18 21 62 61 0 + 0 6 0 0 0 0 0 60 0 + 0 33 0 0 0 0 0 57 0 + 0 32 0 0 0 0 0 56 0 + 0 37 0 1 0 0 0 73 0 + 0 38 0 0 0 0 0 72 0 + 0 43 44 47 48 51 76 77 0 + 0 0 0 0 0 0 0 0 0 + """, + """ + 17 0 0 0 11 0 0 0 59 + 0 15 0 0 6 0 0 61 0 + 0 0 3 0 0 0 63 0 0 + 0 0 0 0 66 0 0 0 0 + 23 24 0 68 67 78 0 54 55 + 0 0 0 0 72 0 0 0 0 + 0 0 35 0 0 0 49 0 0 + 0 29 0 0 40 0 0 47 0 + 31 0 0 0 39 0 0 0 45 + """, + """ + 0 0 0 0 0 + 0 0 0 0 0 + 0 0 0 0 3 + 0 0 0 0 0 + 0 0 0 0 0 + """, + ] + + NUMBRIX_MOVES = [[-1, 0], [0, -1], [0, 1], [1, 0]] + + for t in NUMBRIX_TESTS: + puzzle = HidatoPuzzle(t.strip(), NUMBRIX_MOVES) + print("\nStarting position:") + puzzle.print_starting_board() + puzzle.solve() + puzzle.print_solution() diff --git a/Task/Solve-a-Numbrix-puzzle/Python/solve-a-numbrix-puzzle-2.py b/Task/Solve-a-Numbrix-puzzle/Python/solve-a-numbrix-puzzle-2.py new file mode 100644 index 0000000000..2ccad3c903 --- /dev/null +++ b/Task/Solve-a-Numbrix-puzzle/Python/solve-a-numbrix-puzzle-2.py @@ -0,0 +1,86 @@ +# numbrix.py by Xing216 +MOVES = [(1, 0), (0, 1), (-1, 0), (0, -1)] +class Numbrix: + def __init__(self) -> None: + self.grid: list[list[int]] + self.clues: list[int] + self.totalToFill: int + self.startRow: int + self.startCol: int + def solve(self, row, col, count:int, nextClue: int) -> bool: + if count > self.totalToFill: + return True + back = self.grid[row][col] + if back not in [0, count]: + return False + if back == 0 and nextClue < len(self.clues) and self.clues[nextClue] == count: + return False + nextClue = nextClue + if back == count: nextClue += 1 + self.grid[row][col] = count + for move in MOVES: + if self.solve(row + move[1], col + move[0], count + 1, nextClue): + return True + self.grid[row][col] = back + return False + def xprint(self): + for row in self.grid: + for val in row: + if val != -1: + print(f"{val:02d} ",end='') + print() +def initNumbrix(board: list[str]) -> Numbrix: + result = Numbrix() + nRows = len(board) + nCols = len(board[0].split(',')) + result.grid = [[-1]*(nCols + 2) for _ in range(nRows + 2)] + result.totalToFill = nRows * nCols + xlist = [] + for r, row in enumerate(board): + row = row.split(',') + for c, tile in enumerate(row): + val = int(tile) + result.grid[r + 1][c + 1] = val + if val > 0: + xlist.append(val) + if val == 1: + result.startRow = r + 1 + result.startCol = c + 1 + xlist.sort() + result.clues = xlist + return result +if __name__ == "__main__": + EXAMPLE1 = ["00,00,00,00,00,00,00,00,00", + "00,00,46,45,00,55,74,00,00", + "00,38,00,00,43,00,00,78,00", + "00,35,00,00,00,00,00,71,00", + "00,00,33,00,00,00,59,00,00", + "00,17,00,00,00,00,00,67,00", + "00,18,00,00,11,00,00,64,00", + "00,00,24,21,00,01,02,00,00", + "00,00,00,00,00,00,00,00,00"] + EXAMPLE2 = ["00,00,00,00,00,00,00,00,00", + "00,11,12,15,18,21,62,61,00", + "00,06,00,00,00,00,00,60,00", + "00,33,00,00,00,00,00,57,00", + "00,32,00,00,00,00,00,56,00", + "00,37,00,01,00,00,00,73,00", + "00,38,00,00,00,00,00,72,00", + "00,43,44,47,48,51,76,77,00", + "00,00,00,00,00,00,00,00,00"] + EXAMPLE3 = ["17,00,00,00,11,00,00,00,59", + "00,15,00,00,06,00,00,61,00", + "00,00,03,00,00,00,63,00,00", + "00,00,00,01,66,00,00,00,00", + "23,24,00,68,67,78,00,54,55", + "00,00,00,00,72,00,00,00,00", + "00,00,35,00,00,00,49,00,00", + "00,29,00,00,40,00,00,47,00", + "31,00,00,00,39,00,00,00,45"] + for i, board in enumerate([EXAMPLE1,EXAMPLE2, EXAMPLE3]): + numbrix = initNumbrix(board) + if numbrix.solve(numbrix.startRow, numbrix.startCol, 1, 0): + print(f"Solution for example {i+1}:", end="") + numbrix.xprint() + else: + print("No solution.") diff --git a/Task/Solve-a-Numbrix-puzzle/Python/solve-a-numbrix-puzzle.py b/Task/Solve-a-Numbrix-puzzle/Python/solve-a-numbrix-puzzle.py deleted file mode 100644 index fdc2e475cb..0000000000 --- a/Task/Solve-a-Numbrix-puzzle/Python/solve-a-numbrix-puzzle.py +++ /dev/null @@ -1,98 +0,0 @@ -from sys import stdout -neighbours = [[-1, 0], [0, -1], [1, 0], [0, 1]] -exists = [] -lastNumber = 0 -wid = 0 -hei = 0 - - -def find_next(pa, x, y, z): - for i in range(4): - a = x + neighbours[i][0] - b = y + neighbours[i][1] - if wid > a > -1 and hei > b > -1: - if pa[a][b] == z: - return a, b - - return -1, -1 - - -def find_solution(pa, x, y, z): - if z > lastNumber: - return 1 - if exists[z] == 1: - s = find_next(pa, x, y, z) - if s[0] < 0: - return 0 - return find_solution(pa, s[0], s[1], z + 1) - - for i in range(4): - a = x + neighbours[i][0] - b = y + neighbours[i][1] - if wid > a > -1 and hei > b > -1: - if pa[a][b] == 0: - pa[a][b] = z - r = find_solution(pa, a, b, z + 1) - if r == 1: - return 1 - pa[a][b] = 0 - - return 0 - - -def solve(pz, w, h): - global lastNumber, wid, hei, exists - - lastNumber = w * h - wid = w - hei = h - exists = [0 for j in range(lastNumber + 1)] - - pa = [[0 for j in range(h)] for i in range(w)] - st = pz.split() - idx = 0 - for j in range(h): - for i in range(w): - if st[idx] == ".": - idx += 1 - else: - pa[i][j] = int(st[idx]) - exists[pa[i][j]] = 1 - idx += 1 - - x = 0 - y = 0 - t = w * h + 1 - for j in range(h): - for i in range(w): - if pa[i][j] != 0 and pa[i][j] < t: - t = pa[i][j] - x = i - y = j - - return find_solution(pa, x, y, t + 1), pa - - -def show_result(r): - if r[0] == 1: - for j in range(hei): - for i in range(wid): - stdout.write(" {:0{}d}".format(r[1][i][j], 2)) - print() - else: - stdout.write("No Solution!\n") - - print() - - -r = solve(". . . . . . . . . . . 46 45 . 55 74 . . . 38 . . 43 . . 78 . . 35 . . . . . 71 . . . 33 . . . 59 . . . 17" - " . . . . . 67 . . 18 . . 11 . . 64 . . . 24 21 . 1 2 . . . . . . . . . . .", 9, 9) -show_result(r) - -r = solve(". . . . . . . . . . 11 12 15 18 21 62 61 . . 6 . . . . . 60 . . 33 . . . . . 57 . . 32 . . . . . 56 . . 37" - " . 1 . . . 73 . . 38 . . . . . 72 . . 43 44 47 48 51 76 77 . . . . . . . . . .", 9, 9) -show_result(r) - -r = solve("17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . . 63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55" - " . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45", 9, 9) -show_result(r) diff --git a/Task/Solve-a-Numbrix-puzzle/Rust/solve-a-numbrix-puzzle.rs b/Task/Solve-a-Numbrix-puzzle/Rust/solve-a-numbrix-puzzle.rs new file mode 100644 index 0000000000..eea882792c --- /dev/null +++ b/Task/Solve-a-Numbrix-puzzle/Rust/solve-a-numbrix-puzzle.rs @@ -0,0 +1,205 @@ +use std::io::{self, Write}; + +#[derive(Clone)] // Add Clone derivation to fix the compilation error +struct Node { + val: i32, + neighbors: u8, +} + +struct NSolver { + wid: i32, + hei: i32, + max: i32, + arr: Vec, + we_have: Vec, + dx: Vec, + dy: Vec, +} + +impl NSolver { + fn new() -> Self { + NSolver { + wid: 0, + hei: 0, + max: 0, + arr: Vec::new(), + we_have: Vec::new(), + dx: vec![-1, 1, 0, 0], + dy: vec![0, 0, -1, 1], + } + } + + fn solve(&mut self, puzz: &mut Vec, max_wid: i32) { + if puzz.is_empty() { + return; + } + + self.wid = max_wid; + self.hei = puzz.len() as i32 / self.wid; + self.max = self.wid * self.hei; + let len = self.max as usize; + + self.arr = vec![Node { val: 0, neighbors: 0 }; len]; + self.we_have = vec![false; len + 1]; + + let mut c = 0; + for s in puzz.iter() { + if s == "*" { + self.max -= 1; + self.arr[c].val = -1; + c += 1; + continue; + } + + self.arr[c].val = s.parse::().unwrap_or(0); + if self.arr[c].val > 0 { + self.we_have[self.arr[c].val as usize] = true; + } + c += 1; + } + + self.solve_it(); + + c = 0; + for s in puzz.iter_mut() { + if s == "." { + *s = self.arr[c].val.to_string(); + } + c += 1; + } + } + + fn search(&mut self, x: i32, y: i32, w: i32, dr: i32) -> bool { + if (w > self.max && dr > 0) || (w < 1 && dr < 0) || (w == self.max && self.we_have[w as usize]) { + return true; + } + + let idx = (x + y * self.wid) as usize; + self.arr[idx].neighbors = self.get_neighbors(x, y); + + if self.we_have[w as usize] { + for d in 0..4 { + if (self.arr[idx].neighbors & (1 << d)) != 0 { + let a = x + self.dx[d]; + let b = y + self.dy[d]; + let neighbor_idx = (a + b * self.wid) as usize; + + if self.arr[neighbor_idx].val == w { + if self.search(a, b, w + dr, dr) { + return true; + } + } + } + } + return false; + } + + for d in 0..4 { + if (self.arr[idx].neighbors & (1 << d)) != 0 { + let a = x + self.dx[d]; + let b = y + self.dy[d]; + let neighbor_idx = (a + b * self.wid) as usize; + + if self.arr[neighbor_idx].val == 0 { + self.arr[neighbor_idx].val = w; + if self.search(a, b, w + dr, dr) { + return true; + } + self.arr[neighbor_idx].val = 0; + } + } + } + + false + } + + fn get_neighbors(&self, x: i32, y: i32) -> u8 { + let mut retval: u8 = 0; + + for xx in 0..4 { + let a = x + self.dx[xx]; + let b = y + self.dy[xx]; + + if a < 0 || b < 0 || a >= self.wid || b >= self.hei { + continue; + } + + let idx = (a + b * self.wid) as usize; + if self.arr[idx].val > -1 { + retval |= 1 << xx; + } + } + + retval + } + + fn solve_it(&mut self) { + let (x, y, z) = self.find_start(); + if z == 99999 { + println!("\nCan't find start point!"); + return; + } + + self.search(x, y, z + 1, 1); + if z > 1 { + self.search(x, y, z - 1, -1); + } + } + + fn find_start(&self) -> (i32, i32, i32) { + let mut z = 99999; + let mut x = 0; + let mut y = 0; + + for b in 0..self.hei { + for a in 0..self.wid { + let idx = (a + self.wid * b) as usize; + if self.arr[idx].val > 0 && self.arr[idx].val < z { + x = a; + y = b; + z = self.arr[idx].val; + } + } + } + + (x, y, z) + } +} + +fn main() { + let wid = 9; + //let p = ". . . . . . . . . . . 46 45 . 55 74 . . . 38 . . 43 . . 78 . . 35 . . . . . 71 . . . 33 . . . 59 . . . 17 . . . . . 67 . . 18 . . 11 . . 64 . . . 24 21 . 1 2 . . . . . . . . . . ."; + //let p = ". . . . . . . . . . 11 12 15 18 21 62 61 . . 6 . . . . . 60 . . 33 . . . . . 57 . . 32 . . . . . 56 . . 37 . 1 . . . 73 . . 38 . . . . . 72 . . 43 44 47 48 51 76 77 . . . . . . . . . ."; + let p = "17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . . 63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55 . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45"; + + let mut puzz: Vec = p.split_whitespace().map(|s| s.to_string()).collect(); + let mut solver = NSolver::new(); + solver.solve(&mut puzz, wid); + + let mut c = 0; + for s in &puzz { + if s != "*" && s != "." { + if let Ok(num) = s.parse::() { + if num < 10 { + print!("0"); + } + } + print!("{} ", s); + } else { + print!(" "); + } + + c += 1; + if c >= wid { + println!(); + c = 0; + } + } + println!("\n"); + + // Equivalent of system("pause") in Rust + // print!("Press Enter to continue..."); + // io::stdout().flush().unwrap(); + // let mut input = String::new(); + // io::stdin().read_line(&mut input).unwrap(); +} diff --git a/Task/Solve-a-Numbrix-puzzle/Uiua/solve-a-numbrix-puzzle.uiua b/Task/Solve-a-Numbrix-puzzle/Uiua/solve-a-numbrix-puzzle.uiua new file mode 100644 index 0000000000..e01e1d8c46 --- /dev/null +++ b/Task/Solve-a-Numbrix-puzzle/Uiua/solve-a-numbrix-puzzle.uiua @@ -0,0 +1,17 @@ +G ← [[0 0 0 0 0 0 0 0 0] + [0 11 12 15 18 21 62 61 0] + [0 6 0 0 0 0 0 60 0] + [0 33 0 0 0 0 0 57 0] + [0 32 0 0 0 0 0 56 0] + [0 37 0 1 0 0 0 73 0] + [0 38 0 0 0 0 0 72 0] + [0 43 44 47 48 51 76 77 0] + [0 0 0 0 0 0 0 0 0]] +Ns ← ▽⊸∊⊓(⊚=₀|+A₂¤) # Valid empty Ns. +Next ← ⊃(⊢⊚⌕|+₁)⊢⊚=⊸⧻˜⨂+₁°⊏⊸♭ # Next digit to place, and where to start. +Nodes ← ≡⍜⊡◌⊙⊃⋅¤∘Ns⟜⊸Next # Valid next boards from here. +Placed ← ⍉⊂⊙⍉⟜≡(⊢⊚⌕)⍥↘₁=₀⊸⊢⍆◴♭⟜¤ # [n x y] sorted by nums. +# Ensure pairs of placed numbers have ManD <= number differemce. +Heur ← ×1000/↥⧈₂(>⊙/+°⊂⌵/-) Placed + +⊣⊢path(Nodes|¬/↥/↥⌕0|Heur)G # A* to find solution. diff --git a/Task/Solve-a-Numbrix-puzzle/Zkl/solve-a-numbrix-puzzle-1.zkl b/Task/Solve-a-Numbrix-puzzle/Zkl/solve-a-numbrix-puzzle-1.zkl index de12ddf8a7..c03498dfd5 100644 --- a/Task/Solve-a-Numbrix-puzzle/Zkl/solve-a-numbrix-puzzle-1.zkl +++ b/Task/Solve-a-Numbrix-puzzle/Zkl/solve-a-numbrix-puzzle-1.zkl @@ -10,7 +10,7 @@ class Puzzle{ // hold info concerning this puzzle fcn print_board{ d:=Dictionary(-1," ", 0,"__"); foreach r in (board){ - r.pump(String,'wrap(c){ "%2s ".fmt(d.find(c,c)) }).println(); + r.pump(String,'wrap(c){ "%2s ".fmt(d.find(c,c)) }).println(); } } fcn init(s,adjacent){ @@ -21,14 +21,14 @@ class Puzzle{ // hold info concerning this puzzle given,start=List(),Void; cells,terminated=0,True; foreach r,row in (lines.enumerate()){ - foreach c,cell in (row.split().enumerate()){ - if(cell=="X") continue; // X == not in play, leave at -1 - cells+=1; - val:=cell.toInt(); - board[r][c]=val; - given.append(val); - if(val==1) start=T(r,c); - } + foreach c,cell in (row.split().enumerate()){ + if(cell=="X") continue; // X == not in play, leave at -1 + cells+=1; + val:=cell.toInt(); + board[r][c]=val; + given.append(val); + if(val==1) start=T(r,c); + } } println("Number of cells = ",cells); if(not given.holds(cells)){ given.append(cells); terminated=False; } @@ -37,7 +37,7 @@ class Puzzle{ // hold info concerning this puzzle fcn solve{ //-->Bool if(start) return(_solve(start.xplode())); foreach r,c in (nrows,ncols){ - if(board[r][c]==0 and _solve(r,c)) return(True); + if(board[r][c]==0 and _solve(r,c)) return(True); } False } diff --git a/Task/Solve-a-Numbrix-puzzle/Zkl/solve-a-numbrix-puzzle-2.zkl b/Task/Solve-a-Numbrix-puzzle/Zkl/solve-a-numbrix-puzzle-2.zkl index ff1b705375..79fb9e68c7 100644 --- a/Task/Solve-a-Numbrix-puzzle/Zkl/solve-a-numbrix-puzzle-2.zkl +++ b/Task/Solve-a-Numbrix-puzzle/Zkl/solve-a-numbrix-puzzle-2.zkl @@ -23,12 +23,25 @@ hi2:= // 0==empty cell, X==not a cell 0 43 44 47 48 51 76 77 0 0 0 0 0 0 0 0 0 0"; #<<< + +hi3:= +#<<< +"17 0 0 0 11 0 0 0 59 + 0 15 0 0 6 0 0 61 0 + 0 0 3 0 0 0 63 0 0 + 0 0 0 0 66 0 0 0 0 + 23 24 0 68 67 78 0 54 55 + 0 0 0 0 72 0 0 0 0 + 0 0 35 0 0 0 49 0 0 + 0 29 0 0 40 0 0 47 0 + 31 0 0 0 39 0 0 0 45"; +#<<< adjacent:=T( T(-1,0), T( 0,-1), T( 0,1), T( 1,0) ); -foreach hi in (T(hi1,hi2)){ - puzzle:=Puzzle(hi); puzzle.adjacent=adjacent; +foreach hi in (T(hi1,hi2,hi3)){ + puzzle:=Puzzle(hi,adjacent); puzzle.print_board(); puzzle.solve(); println(); diff --git a/Task/Solve-the-no-connection-puzzle/ALGOL-68/solve-the-no-connection-puzzle.alg b/Task/Solve-the-no-connection-puzzle/ALGOL-68/solve-the-no-connection-puzzle.alg new file mode 100644 index 0000000000..9605f99749 --- /dev/null +++ b/Task/Solve-the-no-connection-puzzle/ALGOL-68/solve-the-no-connection-puzzle.alg @@ -0,0 +1,90 @@ +BEGIN CO Solve the no connection puzzle + the board looks like: + A B + /|\ /|\ + / | X | \ + / |/ \| \ + C - D - E - F + \ |\ /| / + \ | X | / + \|/ \|/ + G H + we need to place 1..8 at A..G so that each connected + value differs by at least 2 (e.g., A=1 and D=3 is OK + but A=1 and D=2 is not) + CO + + PROC not ok = ( INT x )BOOL: ABS x < 2; + PROC ok = ( INT a, b, c, d, e, f, g, h )BOOL: + IF not ok( a - c ) OR not ok( a - d ) OR not ok( a - e ) THEN FALSE + ELIF not ok( b - d ) OR not ok( b - e ) OR not ok( b - f ) THEN FALSE + ELIF not ok( g - c ) OR not ok( g - d ) OR not ok( g - e ) THEN FALSE + ELIF not ok( h - d ) OR not ok( h - e ) OR not ok( h - f ) THEN FALSE + ELIF not ok( c - d ) OR not ok( d - e ) OR not ok( e - f ) THEN FALSE + ELSE TRUE + FI # ok # ; + + PROC is solution = ( []INT a )BOOL: + ok( a[ 0 ], a[ 1 ], a[ 2 ], a[ 3 ], a[ 4 ], a[ 5 ], a[ 6 ], a[ 7 ] ); + + # Heap's algorithm for generating permutations # + # - from the pseudo-code on the Wikipedia page # + # have permutation is called for each generated permutation # + PROC generate = ( INT k, REF[]INT a, REF INT swap count, PROC([]INT,INT)VOID have permutation )VOID: + IF k = 1 THEN + have permutation( a, swap count ) + ELSE + # Generate permutations with kth unaltered # + # Initially k = length a # + generate( k - 1, a, swap count, have permutation ); + # Generate permutations for kth swapped with each k-1 initial # + FOR i FROM 0 TO k - 2 DO + # Swap choice dependent on parity of k (even or odd) # + swap count +:= 1; + INT swap item = IF ODD k THEN 0 ELSE i FI; + INT t = a[ swap item ]; + a[ swap item ] := a[ k - 1 ]; + a[ k - 1 ] := t; + generate( k - 1, a, swap count, have permutation ) + OD + FI # generate # ; + # generate permutations of a # + PROC permute = ( REF[]INT a, PROC([]INT,INT)VOID have permutation )VOID: + BEGIN + INT swap count := 0; + generate( ( UPB a + 1 ) - LWB a, a[ AT 0 ], swap count, have permutation ) + END # permute # ; + + # handle a permutation # + PROC possible solution = ( []INT p, INT swap count )VOID: + IF is solution( p ) THEN # have a solution # + IF first solution THEN + print( ( "First solution found:", newline ) ); + OP N = ( INT v )CHAR: REPR ( v + ABS "0" ); + CHAR a = N p[ 0 ], b = N p[ 1 ], c = N p[ 2 ], d = N p[ 3 ]; + CHAR e = N p[ 4 ], f = N p[ 5 ], g = N p[ 6 ], h = N p[ 7 ]; + print( ( " ", a, " ", b, newline ) ); + print( ( " /|\ /|\", newline ) ); + print( ( " / | X | \", newline ) ); + print( ( " / |/ \| \", newline ) ); + print( ( " ", c, " - ", d, " - ", e, " - ", f, newline ) ); + print( ( " \ |\ /| /", newline ) ); + print( ( " \ | X | /", newline ) ); + print( ( " \|/ \|/", newline ) ); + print( ( " ", g, " ", h, newline ) ); + print( ( newline, "All solutions:", newline ) ); + first solution := FALSE + FI; + print( ( " [" ) ); + FOR i FROM LWB p TO UPB p DO + print( ( whole( p[ i ], 0 ) ) ); + IF i = UPB p THEN print( ( "]" ) ) ELSE print( ( ", " ) ) FI + OD; + print( ( " after ", whole( swap count, 0 ), " swaps", newline ) ) + FI # possible solution # ; + + [ 1 : 8 ]INT items := ( 1, 2, 3, 4, 5, 6, 7, 8 ); + BOOL first solution := TRUE; + permute( items, possible solution ) + +END diff --git a/Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-1.ada b/Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-1.adb similarity index 100% rename from Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-1.ada rename to Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-1.adb diff --git a/Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-2.ada b/Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-2.adb similarity index 100% rename from Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-2.ada rename to Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-2.adb diff --git a/Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-3.ada b/Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-3.adb similarity index 100% rename from Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-3.ada rename to Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-3.adb diff --git a/Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-4.ada b/Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-4.adb similarity index 100% rename from Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-4.ada rename to Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-4.adb diff --git a/Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-5.ada b/Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-5.adb similarity index 100% rename from Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-5.ada rename to Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-5.adb diff --git a/Task/Solve-the-no-connection-puzzle/Chapel/solve-the-no-connection-puzzle.chapel b/Task/Solve-the-no-connection-puzzle/Chapel/solve-the-no-connection-puzzle.chpl similarity index 100% rename from Task/Solve-the-no-connection-puzzle/Chapel/solve-the-no-connection-puzzle.chapel rename to Task/Solve-the-no-connection-puzzle/Chapel/solve-the-no-connection-puzzle.chpl diff --git a/Task/Solve-the-no-connection-puzzle/Delphi/solve-the-no-connection-puzzle.delphi b/Task/Solve-the-no-connection-puzzle/Delphi/solve-the-no-connection-puzzle.pas similarity index 100% rename from Task/Solve-the-no-connection-puzzle/Delphi/solve-the-no-connection-puzzle.delphi rename to Task/Solve-the-no-connection-puzzle/Delphi/solve-the-no-connection-puzzle.pas diff --git a/Task/Solve-the-no-connection-puzzle/EasyLang/solve-the-no-connection-puzzle.easy b/Task/Solve-the-no-connection-puzzle/EasyLang/solve-the-no-connection-puzzle.easy new file mode 100644 index 0000000000..4245d66273 --- /dev/null +++ b/Task/Solve-the-no-connection-puzzle/EasyLang/solve-the-no-connection-puzzle.easy @@ -0,0 +1,23 @@ +cons[][] = [ [ 3 4 5 ] [ 4 5 6 ] [ 4 7 ] [ 5 7 8 ] [ 6 7 8 ] [ 8 ] [ ] [ ] ] +n = len cons[][] +len peg[] n +# +proc init . + for i to n : peg[i] = i +. +init +# +proc permute k . + for i = k to n + swap peg[i] peg[k] + permute k + 1 + swap peg[k] peg[i] + . + if k = n + for i to n : for j in cons[i][] + if abs (peg[i] - peg[j]) = 1 : break 2 + . + if i > n : print peg[] + . +. +permute 1 diff --git a/Task/Solve-the-no-connection-puzzle/Elixir/solve-the-no-connection-puzzle.elixir b/Task/Solve-the-no-connection-puzzle/Elixir/solve-the-no-connection-puzzle.ex similarity index 100% rename from Task/Solve-the-no-connection-puzzle/Elixir/solve-the-no-connection-puzzle.elixir rename to Task/Solve-the-no-connection-puzzle/Elixir/solve-the-no-connection-puzzle.ex diff --git a/Task/Solve-the-no-connection-puzzle/FreeBASIC/solve-the-no-connection-puzzle.basic b/Task/Solve-the-no-connection-puzzle/FreeBASIC/solve-the-no-connection-puzzle.basic new file mode 100644 index 0000000000..0e76ee2b35 --- /dev/null +++ b/Task/Solve-the-no-connection-puzzle/FreeBASIC/solve-the-no-connection-puzzle.basic @@ -0,0 +1,51 @@ +Dim As String txt = "" _ +" A B" & Chr(10) & _ +" /|\ /|\" & Chr(10) & _ +" / | X | \" & Chr(10) & _ +" / |/ \| \" & Chr(10) & _ +" C - D - E - F" & Chr(10) & _ +" \ |\ /| /" & Chr(10) & _ +" \ | X | /" & Chr(10) & _ +" \|/ \|/" & Chr(10) & _ +" G H" + +Dim Shared As String links(1 To 8) +links(1) = "": links(2) = "": links(3) = "A": links(4) = "ABC" +links(5) = "ABD": links(6) = "BE": links(7) = "CDE": links(8) = "DEF" + +Sub ReplaceString(Byref cad As String, oldChar As String, newChar As String) + Dim As Integer posic + Do + posic = Instr(cad, oldChar) + If posic = 0 Then Exit Do + cad = Left(cad, posic - 1) & newChar & Mid(cad, posic + 1) + Loop +End Sub + +Function solve(s As String, idx As Integer, part As String) As String + Dim As Integer v, p, i, j + Dim As String res + + For i = 1 To Len(s) + v = Val(Mid(s, i, 1)) + For j = 1 To Len(links(idx)) + p = Asc(Mid(links(idx), j, 1)) - 64 + If Abs(v - Val(Mid(part, p, 1))) < 2 Then v = 0: Exit For + Next j + If v <> 0 Then + If Len(s) = 1 Then Return part + Chr(48 + v) + res = solve(Left(s, i - 1) & Mid(s, i + 1), idx + 1, part & Chr(48 + v)) + If Len(res) > 0 Then Return res + End If + Next i + + Return "" +End Function + +Dim As String result = solve("12345678", 1, "") +For i As Integer = 1 To Len(result) + ReplaceString(txt, Chr(64 + i), Mid(result, i, 1)) +Next i +Print txt + +Sleep diff --git a/Task/Solve-the-no-connection-puzzle/Julia/solve-the-no-connection-puzzle.julia b/Task/Solve-the-no-connection-puzzle/Julia/solve-the-no-connection-puzzle.jl similarity index 100% rename from Task/Solve-the-no-connection-puzzle/Julia/solve-the-no-connection-puzzle.julia rename to Task/Solve-the-no-connection-puzzle/Julia/solve-the-no-connection-puzzle.jl diff --git a/Task/Solve-the-no-connection-puzzle/Kotlin/solve-the-no-connection-puzzle.kotlin b/Task/Solve-the-no-connection-puzzle/Kotlin/solve-the-no-connection-puzzle.kts similarity index 100% rename from Task/Solve-the-no-connection-puzzle/Kotlin/solve-the-no-connection-puzzle.kotlin rename to Task/Solve-the-no-connection-puzzle/Kotlin/solve-the-no-connection-puzzle.kts diff --git a/Task/Solve-the-no-connection-puzzle/Quackery/solve-the-no-connection-puzzle.quackery b/Task/Solve-the-no-connection-puzzle/Quackery/solve-the-no-connection-puzzle.quackery new file mode 100644 index 0000000000..cd0f5ad995 --- /dev/null +++ b/Task/Solve-the-no-connection-puzzle/Quackery/solve-the-no-connection-puzzle.quackery @@ -0,0 +1,24 @@ + [ ' [ [ 0 2 ] [ 0 3 ] [ 0 4 ] + [ 1 3 ] [ 1 4 ] [ 1 5 ] + [ 6 2 ] [ 6 3 ] [ 6 4 ] + [ 7 3 ] [ 7 4 ] [ 7 5 ] + [ 2 3 ] [ 3 4 ] [ 4 5 ] ] ] is connections ( --> [ ) + + [ dip dup do + unrot peek dip peek - abs 1 = ] is invalid ( [ [ --> b ) + + [ true swap + connections witheach + [ dip dup invalid if + [ dip not conclude ] ] + drop ] is allvalid ( [ --> b ) + + say " A B C D E F G H" cr + 8 ! times + [ i^ 8 rank->perm + allvalid if + [ sp + i^ 8 rank->perm + witheach + [ sp 1+ echo ] + cr conclude ] ] diff --git a/Task/Solve-the-no-connection-puzzle/Zig/solve-the-no-connection-puzzle-1.zig b/Task/Solve-the-no-connection-puzzle/Zig/solve-the-no-connection-puzzle-1.zig new file mode 100644 index 0000000000..dec1f5acc4 --- /dev/null +++ b/Task/Solve-the-no-connection-puzzle/Zig/solve-the-no-connection-puzzle-1.zig @@ -0,0 +1,53 @@ +const std = @import("std"); +const print = std.debug.print; + +const PA = 0; +const PB = 1; +const PC = 2; +const PD = 3; +const PE = 4; +const PF = 5; +const PG = 6; +const PH = 7; + +const Pair = struct { u8, u8 }; +const Pairs = [_]Pair{ .{ PA, PC }, .{ PA, PD }, .{ PA, PE }, .{ PB, PD }, .{ PB, PE }, .{ PB, PF }, .{ PC, PG }, .{ PC, PD }, .{ PD, PE }, .{ PD, PG }, .{ PD, PH }, .{ PE, PG }, .{ PE, PH }, .{ PF, PH }, .{ PE, PF } }; +var t: [8]u32 = .{0} ** 8; + +inline fn abs(p: Pair) u32 { + if (t[p.@"0"] < t[p.@"1"]) return t[p.@"1"] - t[p.@"0"]; + return t[p.@"0"] - t[p.@"1"]; +} + +fn check() bool { + var r: bool = true; + for (Pairs) |p| { + r = r and abs(p) > 1; + if (!r) break; + } + + return r; +} + +fn has(a: u32) bool { + for (t) |v| { + if (v == a) return true; + } + return false; +} + +fn solve(lvl: u32) bool { + if (lvl == 8) return check(); + for (1..9) |v| { + if (has(v)) continue; + t[lvl] = v; + if (solve(lvl + 1)) return true; + } + t[lvl] = 0; + return false; +} + +pub fn main() void { + _ = solve(0); + print("{{ A, B, C, D, E, F, G, H }} = {any}", .{t}); +} diff --git a/Task/Solve-the-no-connection-puzzle/Zig/solve-the-no-connection-puzzle-2.zig b/Task/Solve-the-no-connection-puzzle/Zig/solve-the-no-connection-puzzle-2.zig new file mode 100644 index 0000000000..57eea837ff --- /dev/null +++ b/Task/Solve-the-no-connection-puzzle/Zig/solve-the-no-connection-puzzle-2.zig @@ -0,0 +1,54 @@ +const std = @import("std"); +const print = std.debug.print; + +const PA = 0; +const PB = 1; +const PC = 2; +const PD = 3; +const PE = 4; +const PF = 5; +const PG = 6; +const PH = 7; + +const Pair = struct { u8, u8 }; +const Pairs = [_]Pair{ .{ PA, PC }, .{ PA, PD }, .{ PA, PE }, .{ PB, PD }, .{ PB, PE }, .{ PB, PF }, .{ PC, PG }, .{ PC, PD }, .{ PD, PE }, .{ PD, PG }, .{ PD, PH }, .{ PE, PG }, .{ PE, PH }, .{ PF, PH }, .{ PE, PF } }; +var t: [8]u32 = .{0} ** 8; + +inline fn abs(p: Pair) u32 { + if (t[p.@"0"] < t[p.@"1"]) return t[p.@"1"] - t[p.@"0"]; + return t[p.@"0"] - t[p.@"1"]; +} + +fn check() bool { + var r: bool = true; + for (Pairs) |p| { + r = r and abs(p) > 1; + if (!r) break; + } + + return r; +} + +fn has(a: u32) bool { + for (t) |v| { + if (v == a) return true; + } + return false; +} + +fn solve(lvl: u32) bool { + if (lvl == 8) return check(); + for (1..9) |v| { + if (has(v)) continue; + t[lvl] = v; + if (solve(lvl + 1)) { + print("{{ A, B, C, D, E, F, G, H }} = {any}\n", .{t}); + } + } + t[lvl] = 0; + return false; +} + +pub fn main() void { + _ = solve(0); +} diff --git a/Task/Sort-a-list-of-object-identifiers/APL/sort-a-list-of-object-identifiers.apl b/Task/Sort-a-list-of-object-identifiers/APL/sort-a-list-of-object-identifiers.apl new file mode 100644 index 0000000000..4e28e5deb5 --- /dev/null +++ b/Task/Sort-a-list-of-object-identifiers/APL/sort-a-list-of-object-identifiers.apl @@ -0,0 +1 @@ +oidsort ← {⍵[⍋{⊃(//)'.'⎕VFI⍵}¨⍵]} diff --git a/Task/Sort-a-list-of-object-identifiers/Ada/sort-a-list-of-object-identifiers.ada b/Task/Sort-a-list-of-object-identifiers/Ada/sort-a-list-of-object-identifiers.adb similarity index 100% rename from Task/Sort-a-list-of-object-identifiers/Ada/sort-a-list-of-object-identifiers.ada rename to Task/Sort-a-list-of-object-identifiers/Ada/sort-a-list-of-object-identifiers.adb diff --git a/Task/Sort-a-list-of-object-identifiers/Crystal/sort-a-list-of-object-identifiers.cr b/Task/Sort-a-list-of-object-identifiers/Crystal/sort-a-list-of-object-identifiers.cr new file mode 100644 index 0000000000..568d3e6ad9 --- /dev/null +++ b/Task/Sort-a-list-of-object-identifiers/Crystal/sort-a-list-of-object-identifiers.cr @@ -0,0 +1,6 @@ +pp %w(1.3.6.1.4.1.11.2.17.19.3.4.0.10 + 1.3.6.1.4.1.11.2.17.5.2.0.79 + 1.3.6.1.4.1.11.2.17.19.3.4.0.4 + 1.3.6.1.4.1.11150.3.4.0.1 + 1.3.6.1.4.1.11.2.17.19.3.4.0.1 + 1.3.6.1.4.1.11150.3.4.0).sort_by {|oid| oid.split('.').map &.to_i } diff --git a/Task/Sort-a-list-of-object-identifiers/EasyLang/sort-a-list-of-object-identifiers.easy b/Task/Sort-a-list-of-object-identifiers/EasyLang/sort-a-list-of-object-identifiers.easy new file mode 100644 index 0000000000..39dd5e8ce9 --- /dev/null +++ b/Task/Sort-a-list-of-object-identifiers/EasyLang/sort-a-list-of-object-identifiers.easy @@ -0,0 +1,20 @@ +proc sort &d$[] . + for s$ in d$[] : d[][] &= number strsplit s$ "." + n = len d[][] + for i = 1 to n - 1 : for j = i + 1 to n + m = lower len d[i][] len d[j][] + for k to m + if d[i][k] <> d[j][k] : break 1 + . + if k > m and len d[i][] > len d[j][] or d[i][k] > d[j][k] : swap d[i][] d[j][] + . + for i to len d[][] + d$[i] = d[i][1] + for j = 2 to len d[i][] + d$[i] &= "." & d[i][j] + . + . +. +oid$[] = [ "1.3.6.1.4.1.11.2.17.19.3.4.0.10" "1.3.6.1.4.1.11.2.17.5.2.0.79" "1.3.6.1.4.1.11.2.17.19.3.4.0.4" "1.3.6.1.4.1.11150.3.4.0.1" "1.3.6.1.4.1.11.2.17.19.3.4.0.1" "1.3.6.1.4.1.11150.3.4.0" ] +sort oid$[] +print oid$[] diff --git a/Task/Sort-a-list-of-object-identifiers/Elixir/sort-a-list-of-object-identifiers.elixir b/Task/Sort-a-list-of-object-identifiers/Elixir/sort-a-list-of-object-identifiers.ex similarity index 100% rename from Task/Sort-a-list-of-object-identifiers/Elixir/sort-a-list-of-object-identifiers.elixir rename to Task/Sort-a-list-of-object-identifiers/Elixir/sort-a-list-of-object-identifiers.ex diff --git a/Task/Sort-a-list-of-object-identifiers/F-Sharp/sort-a-list-of-object-identifiers.fs b/Task/Sort-a-list-of-object-identifiers/F-Sharp/sort-a-list-of-object-identifiers.fs new file mode 100644 index 0000000000..00b5afa088 --- /dev/null +++ b/Task/Sort-a-list-of-object-identifiers/F-Sharp/sort-a-list-of-object-identifiers.fs @@ -0,0 +1,8 @@ +//Sort a list of object identifiers. Nigel Galloway: March 9th., 2026 +let inD=["1.3.6.1.4.1.11.2.17.19.3.4.0.10"; + "1.3.6.1.4.1.11.2.17.5.2.0.79"; + "1.3.6.1.4.1.11.2.17.19.3.4.0.4"; + "1.3.6.1.4.1.11150.3.4.0.1"; + "1.3.6.1.4.1.11.2.17.19.3.4.0.1"; + "1.3.6.1.4.1.11150.3.4.0"] +inD|>List.sortBy(fun n->n.Split('.')|>Array.map(int)|>List.ofArray)|>List.iter(printfn "%s") diff --git a/Task/Sort-a-list-of-object-identifiers/FreeBASIC/sort-a-list-of-object-identifiers.basic b/Task/Sort-a-list-of-object-identifiers/FreeBASIC/sort-a-list-of-object-identifiers.basic new file mode 100644 index 0000000000..e21c5c205a --- /dev/null +++ b/Task/Sort-a-list-of-object-identifiers/FreeBASIC/sort-a-list-of-object-identifiers.basic @@ -0,0 +1,64 @@ +Function formatOID(oid As String) As String + Dim As String result = "" + Dim As String segment = "" + Dim As Integer i = 1, lenOID = Len(oid) + + While i <= lenOID + If Mid(oid, i, 1) = "." Then + result &= Space(5 - Len(segment)) & segment & "." + segment = "" + Else + segment &= Mid(oid, i, 1) + End If + i += 1 + Wend + result &= Space(5 - Len(segment)) & segment + Return result +End Function + +Sub quickSort(arr() As String, first As Integer, last As Integer) + If first >= last Then Exit Sub + + Dim As Integer i = first, j = last + Dim As String pivot = arr((first + last) \ 2) + + Do + While arr(i) < pivot: i += 1: Wend + While arr(j) > pivot: j -= 1: Wend + + If i <= j Then + Swap arr(i), arr(j) + i += 1 + j -= 1 + End If + Loop Until i > j + + If first < j Then quickSort(arr(), first, j) + If i < last Then quickSort(arr(), i, last) +End Sub + +' Main program +Dim As Integer i, j +Dim As String oids(5) = { _ +"1.3.6.1.4.1.11.2.17.19.3.4.0.10", _ +"1.3.6.1.4.1.11.2.17.5.2.0.79", _ +"1.3.6.1.4.1.11.2.17.19.3.4.0.4", _ +"1.3.6.1.4.1.11150.3.4.0.1", _ +"1.3.6.1.4.1.11.2.17.19.3.4.0.1", _ +"1.3.6.1.4.1.11150.3.4.0" } + +For i = 0 To Ubound(oids) + oids(i) = formatOID(oids(i)) +Next + +quickSort(oids(), 0, Ubound(oids)) + +For i = 0 To Ubound(oids) + Dim As String tmp = "" + For j = 1 To Len(oids(i)) + If Mid(oids(i), j, 1) <> " " Then tmp &= Mid(oids(i), j, 1) + Next + Print tmp +Next + +Sleep diff --git a/Task/Sort-a-list-of-object-identifiers/Julia/sort-a-list-of-object-identifiers.jl b/Task/Sort-a-list-of-object-identifiers/Julia/sort-a-list-of-object-identifiers.jl new file mode 100644 index 0000000000..d323022ea7 --- /dev/null +++ b/Task/Sort-a-list-of-object-identifiers/Julia/sort-a-list-of-object-identifiers.jl @@ -0,0 +1,9 @@ +oidlist = ["1.3.6.1.4.1.11.2.17.19.3.4.0.10", + "1.3.6.1.4.1.11.2.17.5.2.0.79", + "1.3.6.1.4.1.11.2.17.19.3.4.0.4", + "1.3.6.1.4.1.11150.3.4.0.1", + "1.3.6.1.4.1.11.2.17.19.3.4.0.1", + "1.3.6.1.4.1.11150.3.4.0"] + +sort!(oidlist; by=x -> parse.(Int, String.(split(x, ".")))) +println.(oidlist) diff --git a/Task/Sort-a-list-of-object-identifiers/Julia/sort-a-list-of-object-identifiers.julia b/Task/Sort-a-list-of-object-identifiers/Julia/sort-a-list-of-object-identifiers.julia deleted file mode 100644 index 75f25c1814..0000000000 --- a/Task/Sort-a-list-of-object-identifiers/Julia/sort-a-list-of-object-identifiers.julia +++ /dev/null @@ -1,10 +0,0 @@ -oidlist = ["1.3.6.1.4.1.11.2.17.19.3.4.0.10", - "1.3.6.1.4.1.11.2.17.5.2.0.79", - "1.3.6.1.4.1.11.2.17.19.3.4.0.4", - "1.3.6.1.4.1.11150.3.4.0.1", - "1.3.6.1.4.1.11.2.17.19.3.4.0.1", - "1.3.6.1.4.1.11150.3.4.0"] - -sort!(oidlist; lt=lexless, - by=x -> parse.(Int, String.(split(x, ".")))) -println.(oidlist) diff --git a/Task/Sort-a-list-of-object-identifiers/Kotlin/sort-a-list-of-object-identifiers.kotlin b/Task/Sort-a-list-of-object-identifiers/Kotlin/sort-a-list-of-object-identifiers.kts similarity index 100% rename from Task/Sort-a-list-of-object-identifiers/Kotlin/sort-a-list-of-object-identifiers.kotlin rename to Task/Sort-a-list-of-object-identifiers/Kotlin/sort-a-list-of-object-identifiers.kts diff --git a/Task/Sort-a-list-of-object-identifiers/Nu/sort-a-list-of-object-identifiers.nu b/Task/Sort-a-list-of-object-identifiers/Nu/sort-a-list-of-object-identifiers.nu new file mode 100644 index 0000000000..215cb861bc --- /dev/null +++ b/Task/Sort-a-list-of-object-identifiers/Nu/sort-a-list-of-object-identifiers.nu @@ -0,0 +1,10 @@ +const data = [ + '1.3.6.1.4.1.11.2.17.19.3.4.0.10' + '1.3.6.1.4.1.11.2.17.5.2.0.79' + '1.3.6.1.4.1.11.2.17.19.3.4.0.4' + '1.3.6.1.4.1.11150.3.4.0.1' + '1.3.6.1.4.1.11.2.17.19.3.4.0.1' + '1.3.6.1.4.1.11150.3.4.0' +] + +$data | sort -n diff --git a/Task/Sort-a-list-of-object-identifiers/Pluto/sort-a-list-of-object-identifiers.pluto b/Task/Sort-a-list-of-object-identifiers/Pluto/sort-a-list-of-object-identifiers.pluto new file mode 100644 index 0000000000..69cb7f68a4 --- /dev/null +++ b/Task/Sort-a-list-of-object-identifiers/Pluto/sort-a-list-of-object-identifiers.pluto @@ -0,0 +1,13 @@ +local oids = { + "1.3.6.1.4.1.11.2.17.19.3.4.0.10", + "1.3.6.1.4.1.11.2.17.5.2.0.79", + "1.3.6.1.4.1.11.2.17.19.3.4.0.4", + "1.3.6.1.4.1.11150.3.4.0.1", + "1.3.6.1.4.1.11.2.17.19.3.4.0.1", + "1.3.6.1.4.1.11150.3.4.0" +} + +oids = oids:map(|oid| -> oid:split("."):map(|e| -> string.format("%5s", e)):concat(".")) +oids:sort() +oids:map(|e| -> e:replace(" ", "")) +print(oids:concat("\n")) diff --git a/Task/Sort-a-list-of-object-identifiers/REXX/sort-a-list-of-object-identifiers.rexx b/Task/Sort-a-list-of-object-identifiers/REXX/sort-a-list-of-object-identifiers.rexx index e07437df5e..fed2bff0d8 100644 --- a/Task/Sort-a-list-of-object-identifiers/REXX/sort-a-list-of-object-identifiers.rexx +++ b/Task/Sort-a-list-of-object-identifiers/REXX/sort-a-list-of-object-identifiers.rexx @@ -1,39 +1,58 @@ -/*REXX program performs a sort of OID (Object IDentifiers ◄── used in Network data).*/ -call gen /*generate an array (@.) from the OIDs.*/ -call show 'before sort ───► ' /*display the @ array before sorting.*/ - say copies('░', 79) /* " fence, separate before & after*/ -call adj 1 /*expand the $ list of OID numbers. */ -call bSort # /*sort " " " " " " */ -call adj 0 /*shrink " " " " " " */ -call show ' after sort ───► ' /*display the @ array after sorting. */ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -bSort: procedure expose @.; parse arg n; m=n-1 /*N: is the number of @ array elements.*/ - do m=m for m by -1 until ok; ok= 1 /*keep sorting the @ array until done. */ - do j=1 for m; _= j + 1 /*calculate the next (index) in @ array*/ - if @.j>@._ then parse value @.j @._ 0 with @._ @.j ok - end /*j*/ /* [↑] swap two out─of─order elements.*/ - end /*m*/ /* [↑] use a simple bubble sort. */ - return -/*──────────────────────────────────────────────────────────────────────────────────────*/ -gen: $= 1.3.6.1.4.1.11.2.17.19.3.4.0.10 , /* ◄──┐ */ - 1.3.6.1.4.1.11.2.17.5.2.0.79 , /* ◄──┤ */ - 1.3.6.1.4.1.11.2.17.19.3.4.0.4 , /* ◄──┼─◄─ six OID numbers (as a list).*/ - 1.3.6.1.4.1.11150.3.4.0.1 , /* ◄──┤ */ - 1.3.6.1.4.1.11.2.17.19.3.4.0.1 , /* ◄──┤ */ - 1.3.6.1.4.1.11150.3.4.0 /* ◄──┘ */ - w= 0 /*W: max length of #'s.*/ - #= words($); do i=1 for #; @.i= word($, i); w= max(w, length(@.i) ) - end /*i*/ /*W: max length of #'s.*/ - return -/*──────────────────────────────────────────────────────────────────────────────────────*/ -adj: arg LZ; do j=1 for #; x= translate(@.j, , .); y= /*construct X version. */ - do k=1 for words(x); _= word(x, k) /*get a number in X. */ - if LZ then y= y right(_, w, 0) /*(prepend) leading 0's*/ - else y= y (_ + 0) /* (elide) " " */ - end /*k*/ - @.j = translate( space(y), ., ' ') /*reconstitute number. */ - end /*j*/ /*LZ: Leading Zero(s).*/ - return /*── ─ ─ */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -show: do a=1 for #; say right("OID number",20) right(a,length(#)) arg(1) @.a; end; return +-- 4 Mar 2026 +include Setting + +say 'SORT A LIST OF OBJECT IDENTIFIERS' +say version +say +call Prepare +call Show 'BEFORE' +-- Sort key while syncing data (string compare) +call SortSt 'stem.key.','stem.data.' +call Show 'AFTER' +exit + +Prepare: +procedure expose stem. +-- Input list +list=1.3.6.1.4.1.11.2.17.19.3.4.0.10 , + 1.3.6.1.4.1.11.2.17.5.2.0.79 , + 1.3.6.1.4.1.11.2.17.19.3.4.0.4 , + 1.3.6.1.4.1.11150.3.4.0.1 , + 1.3.6.1.4.1.11.2.17.19.3.4.0.1 , + 1.3.6.1.4.1.11150.3.4.0 +-- Copy to stems +n=Words(list); stem.=''; m=0 +do i=1 to n +-- Original input in stem.data + w=Word(list,i); stem.data.i=w +-- Modified keys in stem.key + k=Changestr('.',w,' ') + do j=1 to Words(k) +-- Keep length largest number + m=Max(Length(Word(k,j)),m) + end + stem.key.i=k +end +stem.0=n +-- Prepend numbers in stem.key with spaces +do i=1 to n + k='' + do j=1 to Words(stem.key.i) + k=k||Right(Word(stem.key.i,j),m) + end + stem.key.i=k +end +return + +Show: +procedure expose stem. +arg header +say header +do i=1 to stem.0 + say stem.data.i +end +say +return + +-- SortSt +include Math diff --git a/Task/Sort-a-list-of-object-identifiers/Rust/sort-a-list-of-object-identifiers.rust b/Task/Sort-a-list-of-object-identifiers/Rust/sort-a-list-of-object-identifiers.rs similarity index 100% rename from Task/Sort-a-list-of-object-identifiers/Rust/sort-a-list-of-object-identifiers.rust rename to Task/Sort-a-list-of-object-identifiers/Rust/sort-a-list-of-object-identifiers.rs diff --git a/Task/Sort-a-list-of-object-identifiers/V-(Vlang)/sort-a-list-of-object-identifiers.v b/Task/Sort-a-list-of-object-identifiers/V-(Vlang)/sort-a-list-of-object-identifiers.v new file mode 100644 index 0000000000..43125c825d --- /dev/null +++ b/Task/Sort-a-list-of-object-identifiers/V-(Vlang)/sort-a-list-of-object-identifiers.v @@ -0,0 +1,37 @@ +struct Oid { + id string +} + +fn (a Oid) str() string { + return a.id +} + +fn (a Oid) compare_to(b Oid) int { + splits1 := a.id.split(".") + splits2 := b.id.split(".") + min_size := if splits1.len < splits2.len { splits1.len } else { splits2.len } + for i in 0 .. min_size { + val1 := splits1[i].int() + val2 := splits2[i].int() + if val1 < val2 { return -1 } + else if val1 > val2 { return 1 } + } + // compare by length if all parts are equal + return if splits1.len < splits2.len { -1 } else if splits1.len > splits2.len { 1 } else { 0 } +} + +fn main() { + mut oids := [ + Oid{"1.3.6.1.4.1.11.2.17.19.3.4.0.10"}, + Oid{"1.3.6.1.4.1.11.2.17.5.2.0.79"}, + Oid{"1.3.6.1.4.1.11.2.17.19.3.4.0.4"}, + Oid{"1.3.6.1.4.1.11150.3.4.0.1"}, + Oid{"1.3.6.1.4.1.11.2.17.19.3.4.0.1"}, + Oid{"1.3.6.1.4.1.11150.3.4.0"}, + ] + // sorted using builtin comparator for arrays + oids.sort_with_compare(fn (a &Oid, b &Oid) int { + return a.compare_to(*b) + }) + for oid in oids { println(oid.str()) } +} diff --git a/Task/Sort-a-list-of-object-identifiers/VBScript/sort-a-list-of-object-identifiers.vb b/Task/Sort-a-list-of-object-identifiers/VBScript/sort-a-list-of-object-identifiers.vbs similarity index 100% rename from Task/Sort-a-list-of-object-identifiers/VBScript/sort-a-list-of-object-identifiers.vb rename to Task/Sort-a-list-of-object-identifiers/VBScript/sort-a-list-of-object-identifiers.vbs diff --git a/Task/Sort-an-array-of-composite-structures/Ada/sort-an-array-of-composite-structures-1.ada b/Task/Sort-an-array-of-composite-structures/Ada/sort-an-array-of-composite-structures-1.adb similarity index 100% rename from Task/Sort-an-array-of-composite-structures/Ada/sort-an-array-of-composite-structures-1.ada rename to Task/Sort-an-array-of-composite-structures/Ada/sort-an-array-of-composite-structures-1.adb diff --git a/Task/Sort-an-array-of-composite-structures/Ada/sort-an-array-of-composite-structures-2.ada b/Task/Sort-an-array-of-composite-structures/Ada/sort-an-array-of-composite-structures-2.adb similarity index 100% rename from Task/Sort-an-array-of-composite-structures/Ada/sort-an-array-of-composite-structures-2.ada rename to Task/Sort-an-array-of-composite-structures/Ada/sort-an-array-of-composite-structures-2.adb diff --git a/Task/Sort-an-array-of-composite-structures/Ada/sort-an-array-of-composite-structures-3.ada b/Task/Sort-an-array-of-composite-structures/Ada/sort-an-array-of-composite-structures-3.adb similarity index 100% rename from Task/Sort-an-array-of-composite-structures/Ada/sort-an-array-of-composite-structures-3.ada rename to Task/Sort-an-array-of-composite-structures/Ada/sort-an-array-of-composite-structures-3.adb diff --git a/Task/Sort-an-array-of-composite-structures/Crystal/sort-an-array-of-composite-structures.cr b/Task/Sort-an-array-of-composite-structures/Crystal/sort-an-array-of-composite-structures.cr new file mode 100644 index 0000000000..5570a1ab95 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Crystal/sort-an-array-of-composite-structures.cr @@ -0,0 +1,11 @@ +record City, name : String, country : String + +cities = [{"Warsaw", "Poland"}, {"Prague", "Czech Republic"}, {"Paris", "France"}, + {"Lima", "Peru"}, {"Montevideo", "Uruguay"}, {"Bogotá", "Colombia"}, + {"Cairo", "Egypt"}, {"Yaoundé", "Cameroon"}, {"Luanda", "Angola"}] + .map {|name, country| City.new name, country } + +puts "unsorted:" +pp cities +puts "sorted:" +pp cities.sort_by &.name diff --git a/Task/Sort-an-array-of-composite-structures/Delphi/sort-an-array-of-composite-structures.delphi b/Task/Sort-an-array-of-composite-structures/Delphi/sort-an-array-of-composite-structures.pas similarity index 100% rename from Task/Sort-an-array-of-composite-structures/Delphi/sort-an-array-of-composite-structures.delphi rename to Task/Sort-an-array-of-composite-structures/Delphi/sort-an-array-of-composite-structures.pas diff --git a/Task/Sort-an-array-of-composite-structures/DuckDB/sort-an-array-of-composite-structures.duckdb b/Task/Sort-an-array-of-composite-structures/DuckDB/sort-an-array-of-composite-structures.duckdb new file mode 100644 index 0000000000..8894010528 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/DuckDB/sort-an-array-of-composite-structures.duckdb @@ -0,0 +1,6 @@ +create table pairs (name varchar(16), value varchar(16)); +insert into pairs values ('Fluffy', 'cat'); +insert into pairs values ('Fido', 'dog'); +insert into pairs values ('Francis', 'fish'); +-- order them by name +select * from pairs order by name; diff --git a/Task/Sort-an-array-of-composite-structures/Elena/sort-an-array-of-composite-structures.elena b/Task/Sort-an-array-of-composite-structures/Elena/sort-an-array-of-composite-structures.elena index 89d587613c..14a31a313a 100644 --- a/Task/Sort-an-array-of-composite-structures/Elena/sort-an-array-of-composite-structures.elena +++ b/Task/Sort-an-array-of-composite-structures/Elena/sort-an-array-of-composite-structures.elena @@ -1,9 +1,9 @@ import system'routines; import extensions; -public program() +public Program() { - var elements := new object[]{ + auto elements := new object[]{ KeyValue.new("Krypton", 83.798r), KeyValue.new("Beryllium", 9.012182r), KeyValue.new("Silicon", 28.0855r), @@ -15,6 +15,6 @@ public program() sorted.forEach::(element) { - console.printLine(element.Key," - ",element) + Console.printLine(element.Key," - ",element) } } diff --git a/Task/Sort-an-array-of-composite-structures/Elixir/sort-an-array-of-composite-structures.elixir b/Task/Sort-an-array-of-composite-structures/Elixir/sort-an-array-of-composite-structures.ex similarity index 100% rename from Task/Sort-an-array-of-composite-structures/Elixir/sort-an-array-of-composite-structures.elixir rename to Task/Sort-an-array-of-composite-structures/Elixir/sort-an-array-of-composite-structures.ex diff --git a/Task/Sort-an-array-of-composite-structures/Euphoria/sort-an-array-of-composite-structures.euphoria b/Task/Sort-an-array-of-composite-structures/Euphoria/sort-an-array-of-composite-structures.eu similarity index 100% rename from Task/Sort-an-array-of-composite-structures/Euphoria/sort-an-array-of-composite-structures.euphoria rename to Task/Sort-an-array-of-composite-structures/Euphoria/sort-an-array-of-composite-structures.eu diff --git a/Task/Sort-an-array-of-composite-structures/FutureBasic/sort-an-array-of-composite-structures.basic b/Task/Sort-an-array-of-composite-structures/FutureBasic/sort-an-array-of-composite-structures.basic new file mode 100644 index 0000000000..247999e405 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/FutureBasic/sort-an-array-of-composite-structures.basic @@ -0,0 +1,23 @@ +void local fn DoIt + CFArrayRef x = @[ + @{@"name":@"07-01",@"value":@"The Times They Are A-Changin'"}, + @{@"name":@"05-08",@"value":@"Mr. Tambourine Man"}, + @{@"name":@"06-09",@"value":@"Desolation Row"}, + @{@"name":@"02-01",@"value":@"Blowin' In The Wind"}, + @{@"name":@"04-04",@"value":@"Chimes Of Freedom"}, + @{@"name":@"07-07",@"value":@"Leopard-Skin Pill-Box Hat"}, + @{@"name":@"06-01",@"value":@"Like A Rolling Stone"}, + @{@"name":@"01-12",@"value":@"Song To Woody"}, + @{@"name":@"07-03",@"value":@"Visions Of Johanna"}, + @{@"name":@"02-06",@"value":@"A Hard Rain's A-Gonna Fall"}] + + SortDescriptorRef sd = fn SortDescriptorWithKey( @"name", YES ) + CFArrayRef array = fn ArraySortedArrayUsingDescriptors( x, @[sd] ) + for CFDictionaryRef pair in array + print pair[@"name"],pair[@"value"] + next +end fn + +fn DoIt + +HandleEvents diff --git a/Task/Sort-an-array-of-composite-structures/Julia/sort-an-array-of-composite-structures.julia b/Task/Sort-an-array-of-composite-structures/Julia/sort-an-array-of-composite-structures.jl similarity index 100% rename from Task/Sort-an-array-of-composite-structures/Julia/sort-an-array-of-composite-structures.julia rename to Task/Sort-an-array-of-composite-structures/Julia/sort-an-array-of-composite-structures.jl diff --git a/Task/Sort-an-array-of-composite-structures/Kotlin/sort-an-array-of-composite-structures.kotlin b/Task/Sort-an-array-of-composite-structures/Kotlin/sort-an-array-of-composite-structures.kts similarity index 100% rename from Task/Sort-an-array-of-composite-structures/Kotlin/sort-an-array-of-composite-structures.kotlin rename to Task/Sort-an-array-of-composite-structures/Kotlin/sort-an-array-of-composite-structures.kts diff --git a/Task/Sort-an-array-of-composite-structures/M2000-Interpreter/sort-an-array-of-composite-structures.m2000 b/Task/Sort-an-array-of-composite-structures/M2000-Interpreter/sort-an-array-of-composite-structures.m2000 index 0811f41ced..9a3d221aaa 100644 --- a/Task/Sort-an-array-of-composite-structures/M2000-Interpreter/sort-an-array-of-composite-structures.m2000 +++ b/Task/Sort-an-array-of-composite-structures/M2000-Interpreter/sort-an-array-of-composite-structures.m2000 @@ -1,69 +1,63 @@ -Module CheckIt { - Flush ' empty stack of values - Class Quick { - Private: - partition=lambda-> { - Read &A(), p, r : i = p-1 : x=A(r) - For j=p to r-1 {If .LE(A(j), x) Then i++:Swap A(i),A(j) - } : Swap A(i+1), A(r) : Push i+2, i - } - Public: - LE=Lambda->Number<=Number - Module ForStrings { - .partition<=lambda-> { - Read &a$(), p, r : i = p-1 : x$=a$(r) - For j=p to r-1 {If a$(j)<= x$ Then i++:Swap a$(i),a$(j) - } : Swap a$(i+1), a$(r) : Push i+2, i - } - } - Function quicksort { - Read ref$ - { - loop : If Stackitem() >= Stackitem(2) Then Drop 2 : if empty then {Break} else continue - over 2,2 : call .partition(ref$) :shift 3 - } - } - } - Quick=Quick() - Quick.LE=lambda (a, b)->{ - =a.name$<=b.name$ - } - Data "Joe", 5531 - Data "Adam", 2341 - Data "Bernie", 122 - Data "Walter", 1234 - Data "David", 19 - Class pair { - name$ - value_ - } - Document Doc$={Unsorted Pairs: - } - Dim A(1 to 5)=pair() - For i=1 to 5 { - For A(i) { - Read .name$, .value_ - Doc$=Format$("{0}, {1}", .name$, .value_)+{ - } - } - } - - Call Quick.quicksort(&A(),1, 5) - Doc$={ - Sorted Pairs - } - k=Each(A()) - While k { - getone=array(k) - For getone { - Doc$=Format$("{0}, {1}", .name$, .value_)+{ - } - } - } - Report Doc$ - Clipboard Doc$ +module Sort_an_array_of_composite_structures{ + Class Quick { + Private: + module quicksort (&a()) { + do If Stackitem()>=Stackitem(2) Then Drop 2:if empty then exit else continue + over 2,2 + Read p, r : i = p-1 : x=a(r) + For j=p to r-1:If .LE(a(j), x) Then i++:Swap a(i),a(j) + Next j : Swap a(i+1), a(r) : Push i+2, i:shift 3 + always + } + Public: + // a and b can be strings or numbers + LE=Lambda (a, b)->a<=b + // this is final, we can't change it + Function Final Sort(&a(), a_min, a_max){ + stack new { + .quicksort &a(), a_min, a_max + } + } + } + Class item { + a$, b + Class: + module item (.a$, .b) { + } + } + Data item("Joe", 5531) + Data item("Adam", 2341) + Data item("Bernie", 122) + Data item("Walter", 1234) + Data item("David", 19) + dim a() + a()=array([]) + mysort=Quick() + mysort.LE=lambda (a, b)->a.a$<=b.a$ + REM { ' if we want sort on second field when the first are equal (same key) + mysort.LE=lambda (a, b)->{ + if a.a$=b.a$ Then + =a.b<=b.b + else + =a.a$ p.Name).Println; + a.OrderBy(p -> p.Value).Println; +end. diff --git a/Task/Sort-an-array-of-composite-structures/Pluto/sort-an-array-of-composite-structures.pluto b/Task/Sort-an-array-of-composite-structures/Pluto/sort-an-array-of-composite-structures.pluto new file mode 100644 index 0000000000..8687483361 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Pluto/sort-an-array-of-composite-structures.pluto @@ -0,0 +1,20 @@ +class pair + function __construct(public name, public value) end + + function __lt(other) return self.name < other.name end + + function __tostring() return $"\{{self.name}, {self.value}}" end +end + +local pairs = { + new pair("grass", "green"), + new pair("snow", "white"), + new pair("sky", "blue"), + new pair("cherry", "red") +} + +print("Before sorting:") +print(" " .. pairs:mapped(|p| -> tostring(p)):concat("\n ")) +pairs:sort() +print("\nAfter sorting:") +print(" " .. pairs:mapped(|p| -> tostring(p)):concat("\n ")) diff --git a/Task/Sort-an-array-of-composite-structures/PowerShell/sort-an-array-of-composite-structures.psh b/Task/Sort-an-array-of-composite-structures/PowerShell/sort-an-array-of-composite-structures.ps1 similarity index 100% rename from Task/Sort-an-array-of-composite-structures/PowerShell/sort-an-array-of-composite-structures.psh rename to Task/Sort-an-array-of-composite-structures/PowerShell/sort-an-array-of-composite-structures.ps1 diff --git a/Task/Sort-an-array-of-composite-structures/REXX/sort-an-array-of-composite-structures.rexx b/Task/Sort-an-array-of-composite-structures/REXX/sort-an-array-of-composite-structures-1.rexx similarity index 100% rename from Task/Sort-an-array-of-composite-structures/REXX/sort-an-array-of-composite-structures.rexx rename to Task/Sort-an-array-of-composite-structures/REXX/sort-an-array-of-composite-structures-1.rexx diff --git a/Task/Sort-an-array-of-composite-structures/REXX/sort-an-array-of-composite-structures-2.rexx b/Task/Sort-an-array-of-composite-structures/REXX/sort-an-array-of-composite-structures-2.rexx new file mode 100644 index 0000000000..4fc85d9f84 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/REXX/sort-an-array-of-composite-structures-2.rexx @@ -0,0 +1,33 @@ +-- 4 Mar 2026 +include Setting + +say 'SORT COMPOSITE ARRAY' +say version +say +call ReadSt 'states.state. states.city. states.pop.','States.txt' +call Show 'Not ordered','A' +call SortSt 'states.state. states.city.','states.pop.' +call Show 'By state and city','A' +call SortSt 'states.pop.','states.state. states.city.' +call Show 'By pop (desc)','D' +exit + +Show: +procedure expose states. +arg header,seq +say Center(header,53) +say Right('row',3) Left('state',20) Left('city',20) Right('pop',7) +if seq='A' then do + a=1; i=1; z=states.0 +end +else do + a=states.0; i=-1; z=1 +end +do n=a by i to z + say Right(n,3) Left(states.state.n,20) Left(states.city.n,20) Right(states.pop.n,7) +end +say +return + +-- ReadSt; SortSt +include Math diff --git a/Task/Sort-an-array-of-composite-structures/Rust/sort-an-array-of-composite-structures.rust b/Task/Sort-an-array-of-composite-structures/Rust/sort-an-array-of-composite-structures.rs similarity index 100% rename from Task/Sort-an-array-of-composite-structures/Rust/sort-an-array-of-composite-structures.rust rename to Task/Sort-an-array-of-composite-structures/Rust/sort-an-array-of-composite-structures.rs diff --git a/Task/Sort-an-integer-array/Ada/sort-an-integer-array.ada b/Task/Sort-an-integer-array/Ada/sort-an-integer-array.adb similarity index 100% rename from Task/Sort-an-integer-array/Ada/sort-an-integer-array.ada rename to Task/Sort-an-integer-array/Ada/sort-an-integer-array.adb diff --git a/Task/Sort-an-integer-array/Batch-File/sort-an-integer-array.bat b/Task/Sort-an-integer-array/Batch-File/sort-an-integer-array.bat new file mode 100644 index 0000000000..488952199c --- /dev/null +++ b/Task/Sort-an-integer-array/Batch-File/sort-an-integer-array.bat @@ -0,0 +1,20 @@ +@if defined doSort goto sort +@echo off +setlocal enabledelayedexpansion +(set lf=^ + +) +set doSort=1 +set nums=!lf!765!lf!1232!lf!457615!lf!29681!lf!20932 +echo Before: +set nums | more +1 +echo After: +for /f %%i in ('cmd /q /v:on /e:on /d /c "%~f0" ^| sort') do echo/%%i +goto:eof +:sort +for /f %%i in ("!nums!") do ( + REM 12 leading spaces: + set "Z= %%i" + REM take last 12 digits: + echo !Z:~-12! +) diff --git a/Task/Sort-an-integer-array/COBOL/sort-an-integer-array.cobol b/Task/Sort-an-integer-array/COBOL/sort-an-integer-array.cob similarity index 100% rename from Task/Sort-an-integer-array/COBOL/sort-an-integer-array.cobol rename to Task/Sort-an-integer-array/COBOL/sort-an-integer-array.cob diff --git a/Task/Sort-an-integer-array/Crystal/sort-an-integer-array.crystal b/Task/Sort-an-integer-array/Crystal/sort-an-integer-array.cr similarity index 100% rename from Task/Sort-an-integer-array/Crystal/sort-an-integer-array.crystal rename to Task/Sort-an-integer-array/Crystal/sort-an-integer-array.cr diff --git a/Task/Sort-an-integer-array/Delphi/sort-an-integer-array.delphi b/Task/Sort-an-integer-array/Delphi/sort-an-integer-array.pas similarity index 100% rename from Task/Sort-an-integer-array/Delphi/sort-an-integer-array.delphi rename to Task/Sort-an-integer-array/Delphi/sort-an-integer-array.pas diff --git a/Task/Sort-an-integer-array/EasyLang/sort-an-integer-array.easy b/Task/Sort-an-integer-array/EasyLang/sort-an-integer-array.easy new file mode 100644 index 0000000000..44ddb91b3a --- /dev/null +++ b/Task/Sort-an-integer-array/EasyLang/sort-an-integer-array.easy @@ -0,0 +1,8 @@ +proc sort &d[] . + for i = 1 to len d[] - 1 : for j = i + 1 to len d[] + if d[j] < d[i] : swap d[j] d[i] + . +. +a[] = [ 2 4 3 1 2 ] +sort a[] +print a[] diff --git a/Task/Sort-an-integer-array/Ed/sort-an-integer-array.ed b/Task/Sort-an-integer-array/Ed/sort-an-integer-array.ed new file mode 100644 index 0000000000..8c3a7a4024 --- /dev/null +++ b/Task/Sort-an-integer-array/Ed/sort-an-integer-array.ed @@ -0,0 +1,107 @@ +H +# split comma/space/tab separated values +g/\b[[:space:]]*[,[:space:]][[:space:]]*\b/s//\ +/g +# unary -> decimal (via Roman-ish) +g/(.*)0([0-9]{3})/s//\1\2/ +g/(.*)1([0-9]{3})/s//\1m\2/ +g/(.*)2([0-9]{3})/s//\1mm\2/ +g/(.*)3([0-9]{3})/s//\1mmm\2/ +g/(.*)4([0-9]{3})/s//\1mmmm\2/ +g/(.*)5([0-9]{3})/s//\1mmmmm\2/ +g/(.*)6([0-9]{3})/s//\1mmmmmm\2/ +g/(.*)7([0-9]{3})/s//\1mmmmmmm\2/ +g/(.*)8([0-9]{3})/s//\1mmmmmmmm\2/ +g/(.*)9([0-9]{3})/s//\1mmmmmmmmm\2/ +g/(.*)0([0-9]{2})/s//\1\2/ +g/(.*)1([0-9]{2})/s//\1c\2/ +g/(.*)2([0-9]{2})/s//\1cc\2/ +g/(.*)3([0-9]{2})/s//\1ccc\2/ +g/(.*)4([0-9]{2})/s//\1cccc\2/ +g/(.*)5([0-9]{2})/s//\1ccccc\2/ +g/(.*)6([0-9]{2})/s//\1cccccc\2/ +g/(.*)7([0-9]{2})/s//\1ccccccc\2/ +g/(.*)8([0-9]{2})/s//\1cccccccc\2/ +g/(.*)9([0-9]{2})/s//\1ccccccccc\2/ +g/(.*)0([0-9])/s//\1\2/ +g/(.*)1([0-9])/s//\1x\2/ +g/(.*)2([0-9])/s//\1xx\2/ +g/(.*)3([0-9])/s//\1xxx\2/ +g/(.*)4([0-9])/s//\1xxxx\2/ +g/(.*)5([0-9])/s//\1xxxxx\2/ +g/(.*)6([0-9])/s//\1xxxxxx\2/ +g/(.*)7([0-9])/s//\1xxxxxxx\2/ +g/(.*)8([0-9])/s//\1xxxxxxxx\2/ +g/(.*)9([0-9])/s//\1xxxxxxxxx\2/ +g/(.*)0/s//\1/ +g/(.*)1/s//\1i/ +g/(.*)2/s//\1ii/ +g/(.*)3/s//\1iii/ +g/(.*)4/s//\1iiii/ +g/(.*)5/s//\1iiiii/ +g/(.*)6/s//\1iiiiii/ +g/(.*)7/s//\1iiiiiii/ +g/(.*)8/s//\1iiiiiiii/ +g/(.*)9/s//\1iiiiiiiii/ +g/m/s//iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii/g +g/c/s//iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii/g +g/x/s//iiiiiiiiii/g +# actual logic +g/.*/s// &/ +,j +g/^[ ]/s/// +s/\b((i+)i+)[ ]\2\b/\2 \1/g +s//\2 \1/g +s//\2 \1/g +s//\2 \1/g +s//\2 \1/g +s//\2 \1/g +s//\2 \1/g +s//\2 \1/g +s/[ ]/\ +/g +g/^$/d +# unary -> decimal (for 0-10000 range) +g/i{9000}(i{0,999})/s//9\1/ +g/i{8000}(i{0,999})/s//8\1/ +g/i{7000}(i{0,999})/s//7\1/ +g/i{6000}(i{0,999})/s//6\1/ +g/i{5000}(i{0,999})/s//5\1/ +g/i{4000}(i{0,999})/s//4\1/ +g/i{3000}(i{0,999})/s//3\1/ +g/i{2000}(i{0,999})/s//2\1/ +g/i{1000}(i{0,999})/s//1\1/ +v/^[0-9]i*$/s/.*/0&/ +g/i{900}(i{0,99})/s//9\1/ +g/i{800}(i{0,99})/s//8\1/ +g/i{700}(i{0,99})/s//7\1/ +g/i{600}(i{0,99})/s//6\1/ +g/i{500}(i{0,99})/s//5\1/ +g/i{400}(i{0,99})/s//4\1/ +g/i{300}(i{0,99})/s//3\1/ +g/i{200}(i{0,99})/s//2\1/ +g/i{100}(i{0,99})/s//1\1/ +v/^[0-9]{2}i*$/s/^([0-9])(i*)$/\10\2/ +g/i{90}(i{0,9})/s//9\1/ +g/i{80}(i{0,9})/s//8\1/ +g/i{70}(i{0,9})/s//7\1/ +g/i{60}(i{0,9})/s//6\1/ +g/i{50}(i{0,9})/s//5\1/ +g/i{40}(i{0,9})/s//4\1/ +g/i{30}(i{0,9})/s//3\1/ +g/i{20}(i{0,9})/s//2\1/ +g/i{10}(i{0,9})/s//1\1/ +v/^[0-9]{3}i*$/s/^([0-9]{2})(i*)$/\10\2/ +g/i{9}/s//9/ +g/i{8}/s//8/ +g/i{7}/s//7/ +g/i{6}/s//6/ +g/i{5}/s//5/ +g/i{4}/s//4/ +g/i{3}/s//3/ +g/i{2}/s//2/ +g/i{1}/s//1/ +v/^[0-9]{4}i*$/s/^([0-9]{3})(i*)$/\10\2/ +g/0+([0-9])/s//\1/ +,p +Q diff --git a/Task/Sort-an-integer-array/Elena/sort-an-integer-array.elena b/Task/Sort-an-integer-array/Elena/sort-an-integer-array.elena index a167bb3d1b..059f0305e2 100644 --- a/Task/Sort-an-integer-array/Elena/sort-an-integer-array.elena +++ b/Task/Sort-an-integer-array/Elena/sort-an-integer-array.elena @@ -1,9 +1,9 @@ import system'routines; import extensions; -public program() +public Program() { - var unsorted := new int[]{6, 2, 7, 8, 3, 1, 10, 5, 4, 9}; + auto unsorted := new int[]{6, 2, 7, 8, 3, 1, 10, 5, 4, 9}; - console.printLine(unsorted.clone().sort(ifOrdered).asEnumerable()) + Console.printLine(unsorted.clone().sort(ifOrdered).asEnumerable()) } diff --git a/Task/Sort-an-integer-array/Elixir/sort-an-integer-array.elixir b/Task/Sort-an-integer-array/Elixir/sort-an-integer-array.ex similarity index 100% rename from Task/Sort-an-integer-array/Elixir/sort-an-integer-array.elixir rename to Task/Sort-an-integer-array/Elixir/sort-an-integer-array.ex diff --git a/Task/Sort-an-integer-array/Euphoria/sort-an-integer-array.euphoria b/Task/Sort-an-integer-array/Euphoria/sort-an-integer-array.eu similarity index 100% rename from Task/Sort-an-integer-array/Euphoria/sort-an-integer-array.euphoria rename to Task/Sort-an-integer-array/Euphoria/sort-an-integer-array.eu diff --git a/Task/Sort-an-integer-array/GW-BASIC/sort-an-integer-array.basic b/Task/Sort-an-integer-array/GW-BASIC/sort-an-integer-array.basic new file mode 100644 index 0000000000..1a3b933f9f --- /dev/null +++ b/Task/Sort-an-integer-array/GW-BASIC/sort-an-integer-array.basic @@ -0,0 +1,31 @@ +20 DEFINT A-Z +30 ARRAYSIZE = 10 +40 DIM NUMBERS(ARRAYSIZE) +50 PRINT "Unsorted:"; +60 FOR I = 1 TO ARRAYSIZE +70 NUMBERS(I) = INT(RND * 100) + 1 +80 PRINT NUMBERS(I); +90 NEXT I +100 PRINT +110 REM ascending sort using Shell sort +120 GAP = INT(ARRAYSIZE / 2) +130 IF GAP = 0 THEN 270 +140 FOR I = GAP + 1 TO ARRAYSIZE +150 J = I - GAP +160 WHILE J > 0 +170 K = J + GAP +180 IF NUMBERS(J) <= NUMBERS(K) THEN J = 0: GOTO 220 +190 TEMP = NUMBERS(J) +200 NUMBERS(J) = NUMBERS(K) +210 NUMBERS(K) = TEMP +220 J = J - GAP +230 WEND +240 NEXT I +250 GAP = INT(GAP / 2) +260 GOTO 130 +270 PRINT "Sorted :"; +280 FOR I = 1 TO ARRAYSIZE +290 PRINT NUMBERS(I); +300 NEXT +310 PRINT +320 END diff --git a/Task/Sort-an-integer-array/Gleam/sort-an-integer-array.gleam b/Task/Sort-an-integer-array/Gleam/sort-an-integer-array.gleam new file mode 100644 index 0000000000..f468a730b3 --- /dev/null +++ b/Task/Sort-an-integer-array/Gleam/sort-an-integer-array.gleam @@ -0,0 +1,12 @@ +import gleam/int +import gleam/io +import gleam/list +import gleam/string + +pub fn main() { + [2, 1, 5, 3, 4] + |> list.sort(int.compare) + |> list.map(int.to_string) + |> string.join(" ") + |> io.println +} diff --git a/Task/Sort-an-integer-array/Joy/sort-an-integer-array.joy b/Task/Sort-an-integer-array/Joy/sort-an-integer-array.joy new file mode 100644 index 0000000000..e9e6912162 --- /dev/null +++ b/Task/Sort-an-integer-array/Joy/sort-an-integer-array.joy @@ -0,0 +1,5 @@ + 1 3 2 4 + stack dup. + [4 2 3 1] + qsort. + [1 2 3 4] diff --git a/Task/Sort-an-integer-array/Julia/sort-an-integer-array.julia b/Task/Sort-an-integer-array/Julia/sort-an-integer-array.jl similarity index 100% rename from Task/Sort-an-integer-array/Julia/sort-an-integer-array.julia rename to Task/Sort-an-integer-array/Julia/sort-an-integer-array.jl diff --git a/Task/Sort-an-integer-array/Kotlin/sort-an-integer-array.kotlin b/Task/Sort-an-integer-array/Kotlin/sort-an-integer-array.kts similarity index 100% rename from Task/Sort-an-integer-array/Kotlin/sort-an-integer-array.kotlin rename to Task/Sort-an-integer-array/Kotlin/sort-an-integer-array.kts diff --git a/Task/Sort-an-integer-array/M2000-Interpreter/sort-an-integer-array.m2000 b/Task/Sort-an-integer-array/M2000-Interpreter/sort-an-integer-array.m2000 new file mode 100644 index 0000000000..8a4cd71eca --- /dev/null +++ b/Task/Sort-an-integer-array/M2000-Interpreter/sort-an-integer-array.m2000 @@ -0,0 +1,21 @@ +module Sort_an_integer_array{ + const n=10 + // s() for feeding array + s=lambda n=1 (x)->{=x-n:n++} + dim a(1 to n) as long long<1; h= h%2 /*define a segment.*/ - do i=1 for N-h; j=i; k= h+i /*sort top segment.*/ - do while @.k<@.j /*see if need swap.*/ - parse value @.j @.k with @.k @.j /*swap two elements*/ - if h>=j then leave; j= j-h; k= k-h /*this part sorted?*/ - end /*while @.k<@.j*/ - end /*i*/ - end /*while h>1*/ - return -/*──────────────────────────────────────────────────────────────────────────────────────*/ -tell: say copies('─', 65); _= left('',9); w= length(#) - do j=1 for #; say _ arg(1) 'array element' right(j, w)"="right(@.j, 20) - end /*j*/ - return diff --git a/Task/Sort-an-integer-array/REXX/sort-an-integer-array-2.rexx b/Task/Sort-an-integer-array/REXX/sort-an-integer-array-2.rexx deleted file mode 100644 index 39b5feeea7..0000000000 --- a/Task/Sort-an-integer-array/REXX/sort-an-integer-array-2.rexx +++ /dev/null @@ -1,26 +0,0 @@ -/*REXX program sorts (using E─sort) and displays a list of some interesting integers. */ - Bell= 1 1 2 5 15 52 203 877 4140 21147 115975 /*a few Bell " */ - Bern= '1 -1 1 0 -1 0 1 0 -1 0 5 0 -691 0 7 0 -3617' /*" " Bernoulli " */ -Perrin= 3 0 2 3 2 5 5 7 10 12 17 22 29 39 51 68 90 /*" " Perrin " */ - list= Bell Bern Perrin /*throw them all ───► a pot. */ -say 'unsorted =' list /*display what's being shown.*/ -#= words(list) /*nice to have # of elements.*/ - do j=1 for # /*build an array, a single */ - @.j=word(list, j) /* ··· element at a time.*/ - end /*j*/ -call eSort # /*sort the collection of #s. */ -$=; do k=1 for #; $= $ @.k /*build a list from the array*/ - end /*k*/ -say ' sorted =' space($) /*display the sorted list. */ -exit /*stick a fork in it, we're all done.*/ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -eSort: procedure expose @.; parse arg N; h= N /*an eXchange sort.*/ - do while h>1; h= h % 2 /*define a segment.*/ - do i=1 for N-h; j= i; k= h + i /*sort top segment.*/ - do while @.k<@.j /*see if need swap.*/ - parse value @.j @.k with @.k @.j /*swap two elements*/ - if h>=j then leave; j= j - h; k= k - h /*this part sorted?*/ - end /*while @.k<@.j*/ - end /*i*/ - end /*while h>1*/ - return diff --git a/Task/Sort-an-integer-array/REXX/sort-an-integer-array.rexx b/Task/Sort-an-integer-array/REXX/sort-an-integer-array.rexx new file mode 100644 index 0000000000..be09153bfd --- /dev/null +++ b/Task/Sort-an-integer-array/REXX/sort-an-integer-array.rexx @@ -0,0 +1,18 @@ +-- 31 Mar 2026 +include Setting + +say 'SORT AN INTEGER ARRAY' +say version +say +-- Generate a demo stem, 100 items, random whole numbers +call MakeSt 'stem.','Z',100 +-- Show original, 5 wide per item +call ShowSt 'stem.','random whole numbers',,5 +-- Sort with (standard) numeric comparator (quicksort) +call SortSt 'stem.' +-- Show sorted +call ShowSt 'stem.','sorted!',,5 +exit + +-- MakeSt; ShowSt; SortSt +include Math diff --git a/Task/Sort-an-integer-array/REBOL/sort-an-integer-array.rebol b/Task/Sort-an-integer-array/Rebol/sort-an-integer-array.rebol similarity index 100% rename from Task/Sort-an-integer-array/REBOL/sort-an-integer-array.rebol rename to Task/Sort-an-integer-array/Rebol/sort-an-integer-array.rebol diff --git a/Task/Sort-an-integer-array/Rust/sort-an-integer-array.rust b/Task/Sort-an-integer-array/Rust/sort-an-integer-array.rs similarity index 100% rename from Task/Sort-an-integer-array/Rust/sort-an-integer-array.rust rename to Task/Sort-an-integer-array/Rust/sort-an-integer-array.rs diff --git a/Task/Sort-an-integer-array/Rye/sort-an-integer-array.rye b/Task/Sort-an-integer-array/Rye/sort-an-integer-array.rye new file mode 100644 index 0000000000..b24addc6d1 --- /dev/null +++ b/Task/Sort-an-integer-array/Rye/sort-an-integer-array.rye @@ -0,0 +1 @@ +print sort nums: { 2 7 3 10 1 50 } diff --git a/Task/Sort-an-integer-array/S-BASIC/sort-an-integer-array.basic b/Task/Sort-an-integer-array/S-BASIC/sort-an-integer-array.basic new file mode 100644 index 0000000000..1d452efe8c --- /dev/null +++ b/Task/Sort-an-integer-array/S-BASIC/sort-an-integer-array.basic @@ -0,0 +1,46 @@ +$constant ARRAY_SIZE = 10 +var i, j, k, gap, temp = integer +dim integer numbers(ARRAY_SIZE) + +comment + populate array with random integers in + range 1..100 +end +print "Unsorted:"; +for i=1 to ARRAY_SIZE + numbers(i) = int(rnd(1) * 100)+1) + print numbers(i); +next i +print + +rem put in ascending order using Shell sort +gap = ARRAY_SIZE / 2 +while gap > 0 do + begin + for i = gap+1 to ARRAY_SIZE + j = i - gap + while j > 0 do + begin + k = j + gap + if numbers(j) <= numbers(k) then + j = 0 + else + begin + temp = numbers(j) + numbers(j) = numbers(k) + numbers(k) = temp + end + j = j - gap + end while + next i + gap = gap / 2 + end while + +rem show result +print "Sorted :"; +for i = 1 to ARRAY_SIZE + print numbers(i); +next i +print + +end diff --git a/Task/Sort-an-integer-array/Scheme/sort-an-integer-array-1.ss b/Task/Sort-an-integer-array/Scheme/sort-an-integer-array-1.scm similarity index 100% rename from Task/Sort-an-integer-array/Scheme/sort-an-integer-array-1.ss rename to Task/Sort-an-integer-array/Scheme/sort-an-integer-array-1.scm diff --git a/Task/Sort-an-integer-array/Scheme/sort-an-integer-array-2.ss b/Task/Sort-an-integer-array/Scheme/sort-an-integer-array-2.scm similarity index 100% rename from Task/Sort-an-integer-array/Scheme/sort-an-integer-array-2.ss rename to Task/Sort-an-integer-array/Scheme/sort-an-integer-array-2.scm diff --git a/Task/Sort-an-integer-array/Scheme/sort-an-integer-array-3.ss b/Task/Sort-an-integer-array/Scheme/sort-an-integer-array-3.scm similarity index 100% rename from Task/Sort-an-integer-array/Scheme/sort-an-integer-array-3.ss rename to Task/Sort-an-integer-array/Scheme/sort-an-integer-array-3.scm diff --git a/Task/Sort-an-outline-at-every-level/C++/sort-an-outline-at-every-level.cpp b/Task/Sort-an-outline-at-every-level/C++/sort-an-outline-at-every-level.cpp new file mode 100644 index 0000000000..d58c07152c --- /dev/null +++ b/Task/Sort-an-outline-at-every-level/C++/sort-an-outline-at-every-level.cpp @@ -0,0 +1,258 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +const char DELETE = '\x7f'; + +// Return the number of characters required to print the given string. +uint32_t print_size(const std::string& text) { + uint32_t size = 0; + for ( const char& ch : text ) { + if ( ch == ' ' ) { size += 1; } + if ( ch == '\t' ) { size += 4; } + } + return size; +} + +// Split the given string into a vector of strings separated by the given delimiter. +std::vector split_string(const std::string& text, const char& delimiter) { + std::vector lines; + std::istringstream stream(text); + std::string line; + while ( std::getline(stream, line, delimiter) ) { + lines.emplace_back(line); + } + return lines; +} + +// Return a string consisting of the given string with leading spaces and tabs removed. +std::string trim_left(const std::string& text) { + size_t start = text.find_first_not_of(" \t"); + return ( start == std::string::npos ) ? "" : text.substr(start); +} + +// Return whether the string 'haystack" contains the string 'needle'. +bool contains(const std::string& haystack, const std::string& needle) { + return haystack.find(needle) != std::string::npos; +} + +// Return a string consisting of the given string repeated the given number of times. +std::string repeat(const std::string& text, const uint32_t& multiple) { + std::string result; + result.reserve(multiple * text.size()); + for ( uint32_t i = 0; i < multiple; ++i ) { + result += text; + } + return result; +} + +// Join a vector of strings into a single string separated by the given delimiter. +std::string join(const std::vector& lines, const std::string& delimiter) { + std::stringstream stream; + std::copy(lines.begin(), lines.end(), std::ostream_iterator(stream, delimiter.c_str())); + return stream.str(); +} + +enum Sort { ASCENDING, DESCENDING }; + +// Correct the given outline if necessary and sort it at every level using the given sort. +void sorted_outline(const std::string& outline, const Sort& sort) { + std::vector lines = split_string(outline, '\n'); + // Remove any initial empty lines which typical occur in raw strings. + while ( lines[0].empty() ) { + lines.erase(lines.begin()); + } + + std::string previous_indent = ""; + std::vector messages = {}; + + // Correct formatting errors in each line of the outline. + for ( uint32_t i = 0; i < lines.size(); ++i ) { + std::string line = lines[i]; + if ( line.starts_with(" ") || line.starts_with("\t") ) { + std::string line_trimmed = trim_left(line); + std::string current_indent = line.substr(0, line.size() - line_trimmed.size()); + if ( previous_indent == "" ) { + previous_indent = current_indent; + } else { + bool correction_needed = false; + + if ( ( contains(current_indent, "\t") && ! contains(previous_indent, "\t") ) || + ( ! contains(current_indent, "\t") && contains(previous_indent, "\t") ) ) { + messages.emplace_back("Corrected inconsistent whitespace use at line \"" + line + "\""); + correction_needed = true; + } + + if ( print_size(current_indent) % print_size(previous_indent) != 0 ) { + messages.emplace_back("Corrected inconsistent indent width at line \"" + line + "\""); + correction_needed = true; + } + + if ( correction_needed ) { + const uint32_t multiple = + std::round(static_cast(print_size(current_indent)) / print_size(previous_indent)); + lines[i] = repeat(previous_indent, multiple) + line_trimmed; + } + } + } + } + + // Determine the level of indent for each line of the outline. + std::vector levels(lines.size(), 0); + uint32_t level = 1; + std::string margin = previous_indent; + while ( std::any_of(levels.begin(), levels.end(), [](const uint32_t& i) { return i == 0; }) ) { + for ( uint32_t i = 0; i < lines.size(); ++i ) { + if ( levels[i] == 0 ) { + const std::string line = lines[i]; + if ( line.starts_with(margin) && line[margin.size()] != ' ' && line[margin.size()] != '\t' ) { + levels[i] = level; + } + } + } + margin += previous_indent; + level += 1; + } + + // Prepare the lines of the outline for sorting. + std::vector new_lines(lines.size(), ""); + new_lines[0] = lines[0]; + std::vector nodes = {}; + for ( uint32_t i = 1; i < lines.size(); ++i ) { + if ( levels[i] > levels[i - 1] ) { + nodes.emplace_back(nodes.empty() ? lines[i - 1] : "\n" + lines[i - 1]); + } else if ( levels[i] < levels[i - 1] ) { + for ( uint32_t j = 1; j <= levels[i - 1] - levels[i]; ++j ) { + nodes.pop_back(); + } + } + + if ( ! nodes.empty() ) { + new_lines[i] = join(nodes, "") + "\n" + lines[i]; + } else { + new_lines[i] = lines[i]; + } + } + + // Sort the lines of the outline. + if ( sort == Sort::ASCENDING ) { + std::sort(new_lines.begin(), new_lines.end()); + } else { + // Pad each line of the outline on the right with 'DELETE' characters. + const uint64_t max_size = + std::ranges::max_element(new_lines, std::ranges::less{}, &std::string::size) -> size(); + for ( uint64_t i = 0; i < new_lines.size(); ++i ) { + new_lines[i].insert(new_lines[i].size(), max_size - new_lines[i].size(), DELETE); + } + + std::sort(new_lines.begin(), new_lines.end(), std::greater()); + } + + for ( uint32_t i = 0; i < new_lines.size(); ++i ) { + std::vector sections = split_string(new_lines[i], '\n'); + new_lines[i] = sections.back(); + + if ( sort == Sort::DESCENDING ) { + // Remove the padding of 'DELETE' characters + const int32_t start = new_lines[i].find_first_of(DELETE); + if ( start > 0 ) { + new_lines[i] = new_lines[i].substr(0, start); + } + } + } + + // Display error messages + if ( ! messages.empty() ) { + for ( const std::string& message : messages ) { + std::cout << message << std::endl; + } + } + + // Display corrected and sorted outline + std::cout << join(new_lines, "\n") << std::endl; +} + +int main() { + std::string outline_spaces = R"( + zeta + beta + gamma + lambda + kappa + mu + delta + alpha + theta + iota + epsilon)"; + + std::string outline_tabs = R"( + zeta + beta + gamma + lambda + kappa + mu + delta + alpha + theta + iota + epsilon)"; + + // All spaces except for the line 'kappa' which contains a tab. + std::string outline_faulty_1 = R"( + alpha + epsilon + iota + theta + zeta + beta + delta + gamma + kappa + lambda + mu)"; + + // All spaces with lines 'gamma' and 'kappa' misaligned. + std::string outline_faulty_2 = R"( + zeta + beta + gamma + lambda + kappa + mu + delta + alpha + theta + iota + epsilon)"; + + std::cout << "Four space indented outline, ascending sort:" << std::endl; + sorted_outline(outline_spaces, Sort::ASCENDING); + + std::cout << "Four space indented outline, descending sort:" << std::endl; + sorted_outline(outline_spaces, Sort::DESCENDING); + + std::cout << "Tab indented outline, ascending sort:" << std::endl; + sorted_outline(outline_tabs, Sort::ASCENDING); + + std::cout << "Tab space indented outline, descending sort:" << std::endl; + sorted_outline(outline_tabs, Sort::DESCENDING); + + std::cout << "First faulty outline, ascending sort:" << std::endl; + sorted_outline(outline_faulty_1, Sort::ASCENDING); + + std::cout << "First faulty outline, descending sort:" << std::endl; + sorted_outline(outline_faulty_1, Sort::DESCENDING); + + std::cout << "Second faulty outline, ascending sort:" << std::endl; + sorted_outline(outline_faulty_2, Sort::ASCENDING); + + std::cout << "Second faulty outline, descending sort:" << std::endl; + sorted_outline(outline_faulty_2, Sort::DESCENDING); +} diff --git a/Task/Sort-an-outline-at-every-level/EasyLang/sort-an-outline-at-every-level.easy b/Task/Sort-an-outline-at-every-level/EasyLang/sort-an-outline-at-every-level.easy new file mode 100644 index 0000000000..119aaf9a25 --- /dev/null +++ b/Task/Sort-an-outline-at-every-level/EasyLang/sort-an-outline-at-every-level.easy @@ -0,0 +1,95 @@ +sortdir = 1 +proc sort &d$[][] . + for i = 1 to len d$[][] - 1 : for j = i + 1 to len d$[][] + if sortdir * strcmp d$[j][1] d$[i][1] < 0 : swap d$[j][] d$[i][] + . +. +repeat + s$ = input + until s$ = "" + inp$[] &= s$ +. +subr init + stdind = -1 + linpos = 0 + lin$ = "" + linind = 0 +. +istab = -1 +# +proc nextline . + if linpos = -1 : return + linpos += 1 + if linpos > len inp$[] + linpos = -1 + return + . + lin$ = inp$[linpos] + linind = 0 + for c$ in strchars lin$ + if istab = -1 + if c$ = " " + istab = 0 + elif c$ = "\t" + stdind = 1 + istab = 1 + . + . + if c$ <> " " and c$ <> "\t" + if stdind = -1 and linind > 0 : stdind = linind + break 1 + . + if istab = 0 and c$ = " " or istab = 1 and c$ = "\t" + linind += 1 + else + print "mix of tab and space - line " & linpos + linpos = -1 + return + . + . +. +func$[] outline . + curind = linind + repeat + # + until linpos = -1 or linind < curind + if linind = curind + r$[][] &= [ lin$ ] + elif linind = curind + stdind + h$[] = outline + for h$ in h$[] : r$[$][] &= h$ + else + if linpos <> -1 : print "indentation error - line " & linpos + linpos = -1 + . + nextline + . + sort r$[][] + for i to len r$[][] + for r$ in r$[i][] : r$[] &= r$ + . + if linpos <> -1 : linpos -= 1 + return r$[] +. +proc run dir . + sortdir = dir + init + nextline + for s$ in outline : print s$ + print "" +. +run 1 +run -1 +# +input_data +zeta + beta + gamma + lambda + kappa + mu + delta +alpha + theta + iota + epsilon diff --git a/Task/Sort-an-outline-at-every-level/FreeBASIC/sort-an-outline-at-every-level.basic b/Task/Sort-an-outline-at-every-level/FreeBASIC/sort-an-outline-at-every-level.basic new file mode 100644 index 0000000000..be7503a61b --- /dev/null +++ b/Task/Sort-an-outline-at-every-level/FreeBASIC/sort-an-outline-at-every-level.basic @@ -0,0 +1,293 @@ +Type StringArray + Dim elements(Any) As String + Dim cnt As Integer + + Declare Sub annadir(value As String) + Declare Function join(delimiter As String) As String +End Type + +Sub StringArray.annadir(value As String) + this.cnt += 1 + Redim Preserve this.elements(this.cnt - 1) + this.elements(this.cnt - 1) = value +End Sub + +Function StringArray.join(delimiter As String) As String + Dim result As String = "" + For i As Integer = 0 To this.cnt - 1 + If i > 0 Then result &= delimiter + result &= this.elements(i) + Next + Return result +End Function + +Function Replace(text As String, find As String, replaceWith As String) As String + Dim result As String = text + Dim posic As Integer = Instr(result, find) + + While posic > 0 + result = Left(result, posic - 1) & replaceWith & Mid(result, posic + Len(find)) + posic = Instr(posic + Len(replaceWith), result, find) + Wend + + Return result +End Function + +Function trimLeft(text As String, chars As String) As String + Dim i As Integer = 1 + While i <= Len(text) Andalso Instr(chars, Mid(text, i, 1)) > 0 + i += 1 + Wend + Return Mid(text, i) +End Function + +Function trimRight(text As String, chars As String) As String + Dim i As Integer = Len(text) + While i > 0 Andalso Instr(chars, Mid(text, i, 1)) > 0 + i -= 1 + Wend + Return Left(text, i) +End Function + +Sub sortedOutline(originalOutline() As String, ascending As Boolean) + Dim As String indent = "", del = Chr(127), sep = Chr(0) + Dim As Integer outlineCount = Ubound(originalOutline) + 1 + Dim As StringArray messages, nodes + Dim As Integer i, j + + Dim As String outline(outlineCount - 1) + ' Copy original array + For i = 0 To outlineCount - 1 + outline(i) = originalOutline(i) + Next + + ' Check first line indentation + If trimLeft(outline(0), " " + Chr(9)) <> outline(0) Then + Print " outline structure is unclear" + Exit Sub + End If + + ' Process indentation + For i = 1 To outlineCount - 1 + Dim As String linea = outline(i) + Dim As Integer lc = Len(linea) + + If Left(linea, 2) = " " Orelse Left(linea, 1) = Chr(9) Then + Dim As String trimmedLine = trimLeft(linea, " " + Chr(9)) + Dim As String currIndent = Left(linea, lc - Len(trimmedLine)) + + If indent = "" Then + indent = currIndent + Else + Dim As Boolean correctionNeeded = False + + If (Instr(currIndent, Chr(9)) > 0 Andalso Instr(indent, Chr(9)) = 0) Orelse _ + (Instr(currIndent, Chr(9)) = 0 Andalso Instr(indent, Chr(9)) > 0) Then + messages.annadir(indent + "corrected inconsistent whitespace use at line '" + linea + "'") + correctionNeeded = True + Elseif (Len(currIndent) Mod Len(indent)) <> 0 Then + messages.annadir(indent + "corrected inconsistent indent width at line '" + linea + "'") + correctionNeeded = True + End If + + If correctionNeeded Then + Dim As Integer mult = Int((Len(currIndent) + Len(indent)/2) / Len(indent)) + Dim As String newIndent = "" + For j = 1 To mult + newIndent &= indent + Next + outline(i) = newIndent & trimmedLine + End If + End If + End If + Next + + ' Create levels array + Dim As Integer levels(outlineCount - 1) + levels(0) = 1 + Dim As Integer level = 1 + Dim As String margin = "" + + Do + Dim As Boolean allProcessed = True + For i = 0 To outlineCount - 1 + If levels(i) = 0 Then + allProcessed = False + Exit For + End If + Next + If allProcessed Then Exit Do + + Dim As Integer mc = Len(margin) + For i = 1 To outlineCount - 1 + If levels(i) = 0 Then + If Left(outline(i), mc) = margin Andalso _ + Mid(outline(i), mc + 1, 1) <> " " Andalso _ + Mid(outline(i), mc + 1, 1) <> Chr(9) Then + levels(i) = level + End If + End If + Next + margin += indent + level += 1 + Loop + + ' Sort the outline + Dim As String lines(outlineCount - 1) + lines(0) = outline(0) + + For i = 1 To outlineCount - 1 + If levels(i) > levels(i-1) Then + If nodes.cnt = 0 Then + nodes.annadir(outline(i-1)) + Else + nodes.annadir(sep + outline(i-1)) + End If + Elseif levels(i) < levels(i-1) Then + j = levels(i-1) - levels(i) + nodes.cnt -= j + Redim Preserve nodes.elements(nodes.cnt - 1) + End If + + If nodes.cnt > 0 Then + lines(i) = nodes.join("") & sep & outline(i) + Else + lines(i) = outline(i) + End If + Next + + ' Sort lines + If ascending Then + For i = 0 To outlineCount - 2 + For j = i + 1 To outlineCount - 1 + If lines(i) > lines(j) Then Swap lines(i), lines(j) + Next + Next + Else + Dim As Integer maxLen = Len(lines(0)) + For i = 1 To outlineCount - 1 + If Len(lines(i)) > maxLen Then maxLen = Len(lines(i)) + Next + + For i = 0 To outlineCount - 1 + lines(i) = lines(i) & String(maxLen - Len(lines(i)), del) + Next + + For i = 0 To outlineCount - 2 + For j = i + 1 To outlineCount - 1 + If lines(i) < lines(j) Then Swap lines(i), lines(j) + Next + Next + End If + + ' Process final lines + For i = 0 To outlineCount - 1 + Dim As String parts() + Dim As Integer partCount = 0 + Dim As String tmp = lines(i) + + ' Split by separator + Do + Dim As Integer posic = Instr(tmp, sep) + If posic = 0 Then + partCount += 1 + Redim Preserve parts(partCount - 1) + parts(partCount - 1) = tmp + Exit Do + End If + partCount += 1 + Redim Preserve parts(partCount - 1) + parts(partCount - 1) = Left(tmp, posic - 1) + tmp = Mid(tmp, posic + 1) + Loop + + lines(i) = parts(partCount - 1) + If Not ascending Then lines(i) = trimRight(lines(i), del) + Next + + ' Print messages if any + If messages.cnt > 0 Then + Print messages.join(!"\n") + Print + End If + + ' Print result + For i = 0 To outlineCount - 1 + Print lines(i) + Next +End Sub + +' Main program with test cases +Dim outline(10) As String +outline(0) = "zeta" +outline(1) = " beta" +outline(2) = " gamma" +outline(3) = " lambda" +outline(4) = " kappa" +outline(5) = " mu" +outline(6) = " delta" +outline(7) = "alpha" +outline(8) = " theta" +outline(9) = " iota" +outline(10) = " epsilon" + +Print "Four space indented outline, ascending sort:" +sortedOutline(outline(), True) + +Print !"\nFour space indented outline, descending sort:" +sortedOutline(outline(), False) + +' Create outline2 (tab version) +Dim outline2(10) As String +For i As Integer = 0 To 10 + outline2(i) = Replace(outline(i), " ", Chr(9)) +Next + +' Create outline3 +Dim outline3(10) As String +outline3(0) = "alpha" +outline3(1) = " epsilon" +outline3(2) = " iota" +outline3(3) = " theta" +outline3(4) = "zeta" +outline3(5) = " beta" +outline3(6) = " delta" +outline3(7) = " gamma" +outline3(8) = " " + Chr(9) + " kappa" +outline3(9) = " lambda" +outline3(10) = " mu" + +' Create outline4 +Dim outline4(10) As String +outline4(0) = "zeta" +outline4(1) = " beta" +outline4(2) = " gamma" +outline4(3) = " lambda" +outline4(4) = " kappa" +outline4(5) = " mu" +outline4(6) = " delta" +outline4(7) = "alpha" +outline4(8) = " theta" +outline4(9) = " iota" +outline4(10) = " epsilon" + +' Add these test cases after the first two Print calls +Print !"\nTab indented outline, ascending sort:" +sortedOutline(outline2(), True) + +Print !"\nTab indented outline, descending sort:" +sortedOutline(outline2(), False) + +Print !"\nFirst unspecified outline, ascending sort:" +sortedOutline(outline3(), True) + +Print !"\nFirst unspecified outline, descending sort:" +sortedOutline(outline3(), False) + +Print !"\nSecond unspecified outline, ascending sort:" +sortedOutline(outline4(), True) + +Print !"\nSecond unspecified outline, descending sort:" +sortedOutline(outline4(), False) + +Sleep diff --git a/Task/Sort-an-outline-at-every-level/Jq/sort-an-outline-at-every-level.jq b/Task/Sort-an-outline-at-every-level/Jq/sort-an-outline-at-every-level.jq new file mode 100644 index 0000000000..f88bb01876 --- /dev/null +++ b/Task/Sort-an-outline-at-every-level/Jq/sort-an-outline-at-every-level.jq @@ -0,0 +1,169 @@ +# Left justify . +def ljust($width; $pad): + tostring as $s + | ($s|length) as $length + | if $width > $length + then $s + $pad * ($width - $length) + else $s + end; + +def sortedOutline($ascending): + + def del: "\u007f"; + def sep: "\u0000"; + + if .[0] | test("^[ \t]") + then " outline structure is unclear" | error + else + reduce range(1; length) as $i ( + { outline: ., + indent: "", + messages: [] }; + .outline[$i] as $line + | ($line|length) as $lc + | if $line | test("^( | \t|\t)") + then ($line | sub("^[ \t]*";"") | length) as $lc2 + | $line[0:$lc-$lc2] as $currIndent + + | if .indent == "" + then .indent = $currIndent + else .correctionNeeded = false + | if (($currIndent|test("\t")) and (.indent|contains("\t") | not)) or + (($currIndent|test("\t")|not) and (.indent|test("\t"))) + then .messages += [.indent + "corrected inconsistent whitespace use at line '\($line)'"] + | .correctionNeeded = true + elif (($currIndent|length) % (.indent|length)) != 0 + then .messages += [.indent + "corrected inconsistent indent width at line '\($line)'"] + | .correctionNeeded = true + end + | if .correctionNeeded + then ((($currIndent|length) / (.indent|length)) |round) as $mult + | .outline[$i] = (.indent * $mult) + $line[$lc-$lc2:] + end + end + end ) + end + | .levels = [range(0; .outline|length) | 0] + | .levels[0] = 1 + | .level = 1 + | .margin = "" + # while any of the levels is 0 ... + | until( all( .levels[]; . > 0); + (.margin|length) as $mc + | reduce range(1; .outline|length) as $i (.; + if .levels[$i] == 0 + then .outline[$i] as $line + | .margin as $margin + | if ($line|startswith($margin)) and + ($line[$mc:$mc+1] | (. != " ") and (. != "\t")) + then .levels[$i] = .level + end + end ) + | .margin += .indent + | .level += 1 ) + | .lines = [range(0; .outline|length) | ""] + | .lines[0] = .outline[0] + | .nodes = [] + | reduce range(1; .outline|length) as $i (.; + if .levels[$i] > .levels[$i-1] + then .nodes += [ if .nodes|length == 0 then .outline[$i-1] else sep + .outline[$i-1] end] + elif .levels[$i] < .levels[$i-1] + then (.levels[$i-1] - .levels[$i] ) as $j + # remove $j elements from the tail + | .nodes |= .[0: length-$j] + end + | if .nodes|length > 0 + then .lines[$i] = (.nodes|join("")) + sep + .outline[$i] + else .lines[$i] = .outline[$i] + end ) + | if $ascending + then .lines |= sort + else (.lines | map(length) | max) as $maxLen + | reduce range(0; .lines|length) as $i (.; + .lines[$i] |= ljust($maxLen; del) ) + | .lines |= (sort|reverse) + end + | reduce range(0; .lines|length) as $i (.; + (.lines[$i]|split(sep) ) as $s + | .lines[$i] = $s[-1] + | if ($ascending|not) + then .lines[$i] |= sub( del + "+$"; "") + end ) + # First print the messages, and then the lines: + | (select((.messages|length) > 0) + | (.messages | join("\n")) + "\n"), + + (.lines|join("\n")) ; + + +### Examples + +def outline: [ + "zeta", + " beta", + " gamma", + " lambda", + " kappa", + " mu", + " delta", + "alpha", + " theta", + " iota", + " epsilon" +]; + +def outline2: + outline | map(gsub(" "; "\t")); + +def outline3: [ + "alpha", + " epsilon", + " iota", + " theta", + "zeta", + " beta", + " delta", + " gamma", + " \t kappa", # same length but \t instead of space + " lambda", + " mu" +]; + +def outline4: [ + "zeta", + " beta", + " gamma", + " lambda", + " kappa", + " mu", + " delta", + "alpha", + " theta", + " iota", + " epsilon" +]; + + +(outline +| "Four space indented outline, ascending sort:", + sortedOutline(true), + "\nFour space indented outline, descending sort:", + sortedOutline(false)), + +(outline2 +| "\nTab indented outline, ascending sort:", + sortedOutline(true), + "\nTab indented outline, descending sort:", + sortedOutline(false) ), + +(outline3 +| "\nFirst unspecified outline, ascending sort:", + sortedOutline(true), + "\nFirst unspecified outline, descending sort:", + sortedOutline(false) ), + +(outline4 +| "\nSecond unspecified outline, ascending sort:", + sortedOutline(true), + "\nSecond unspecified outline, descending sort:", + sortedOutline(false)) diff --git a/Task/Sort-an-outline-at-every-level/Julia/sort-an-outline-at-every-level.julia b/Task/Sort-an-outline-at-every-level/Julia/sort-an-outline-at-every-level.jl similarity index 100% rename from Task/Sort-an-outline-at-every-level/Julia/sort-an-outline-at-every-level.julia rename to Task/Sort-an-outline-at-every-level/Julia/sort-an-outline-at-every-level.jl diff --git a/Task/Sort-an-outline-at-every-level/M2000-Interpreter/sort-an-outline-at-every-level.m2000 b/Task/Sort-an-outline-at-every-level/M2000-Interpreter/sort-an-outline-at-every-level.m2000 new file mode 100644 index 0000000000..0b95477083 --- /dev/null +++ b/Task/Sort-an-outline-at-every-level/M2000-Interpreter/sort-an-outline-at-every-level.m2000 @@ -0,0 +1,137 @@ +MODULE Sort_an_outline_at_every_level { + CLASS PACK { + PAD$ + HEAD=QUEUE + CLASS: + MODULE PACK (.PAD$) { + } + } + FUNCTION CREATETREE(A$){ + CONST I$=CHR$(9)+CHR$(32) + L=1 + PR=PACK() + A=QUEUE + F=QUEUE + LN=0 + DIM LINE$() + LINE$()=PIECE$(A$, CHR$(13)+CHR$(10)) + MAX=LEN(LINE$()) + INTEGER NORM[0]=1 + FOR I=0 TO MAX-2 + FOR M=1 TO LEN(LINE$(I)) + IF INSTR(I$, MID$(LINE$(I),M, 1))=0 THEN EXIT FOR + NEXT + IF L=M THEN + IF NOT EMPTY THEN READ PREV$, PR: APPEND A, PREV$:=PR + PUSH PACK(LEFT$(LINE$(I), M-1)), MID$(LINE$(I), M) + ELSE.IF L{ + } + TRAVERSAL(A) + PRINT "ASCENDING ORDER" + JOB=LAMBDA (Z)->{SORT ASCENDING Z} + TRAVERSAL(A) + PRINT "DESCENDING ORDER" + JOB=LAMBDA (Z)->{SORT DESCENDING Z} + TRAVERSAL(A) + PRINT "PRESS ANY KEY" + PUSH KEY$ + DROP + END SUB + SUB TRAVERSAL(A) + CALL JOB(A) + LOCAL W=EACH(A) + LOCAL M=PACK() + WHILE W + M=EVAL(W) + // USING -2 TO PROCESS TABS. + PRINT #-2, M.PAD$+EVAL$(W!) + TRAVERSAL(M.HEAD) + END WHILE + END SUB +} +Sort_an_outline_at_every_level diff --git a/Task/Sort-disjoint-sublist/ALGOL-68/sort-disjoint-sublist.alg b/Task/Sort-disjoint-sublist/ALGOL-68/sort-disjoint-sublist.alg new file mode 100644 index 0000000000..b31a057933 --- /dev/null +++ b/Task/Sort-disjoint-sublist/ALGOL-68/sort-disjoint-sublist.alg @@ -0,0 +1,52 @@ +BEGIN # sort a disjoint sub-set of a list # + + PR read "sort.incl.a68" PR # include sort utilities, including QUICKSORT # + PR read "rows.incl.a68" PR # include array utilities, including SHOW # + + # in-place quicksorts the subset of data specified by indexes # + OP QUICKSORT = ( REF[]INT data, []INT unsorted indexes )VOID: + BEGIN + [ LWB unsorted indexes : UPB unsorted indexes ]INT sorted indexes := unsorted indexes; + QUICKSORT sorted indexes; + + # in-place quicksorts the subset of a defined by # + # indexes[ low : high ] # + PROC indexed quicksort = ( REF[]INT a, indexes, INT low, high )VOID: + IF INT lb = low, ub = high; + ub > lb + THEN # more than one element, so must sort # + INT left := lb; + INT right := ub; + # use the middle element of the indexes as the pivot # + INT pivot := a[ indexes[ left + ( ( right + 1 ) - left ) OVER 2 ] ]; + WHILE + WHILE IF left <= ub THEN a[ indexes[ left ] ] < pivot ELSE FALSE FI + DO + left +:= 1 + OD; + WHILE IF right >= lb THEN a[ indexes[ right ] ] > pivot ELSE FALSE FI + DO + right -:= 1 + OD; + left <= right + DO + a[ indexes[ left ] ] =:= a[ indexes[ right ] ]; + left +:= 1; + right -:= 1 + OD; + indexed quicksort( a, indexes, lb, right ); + indexed quicksort( a, indexes, left, ub ) + FI # indexed quicksort # ; + + indexed quicksort ( data, sorted indexes, LWB sorted indexes, UPB sorted indexes ) + END # QUICKSORT # ; + + BEGIN # task test case # + []INT unsorted data = ( 7, 6, 5, 4, 3, 2, 1, 0 ); + [ 0 : UPB unsorted data - LWB unsorted data ]INT sorted data := unsorted data[ AT 0 ]; + []INT indexes = ( 6, 1, 7 ); + sorted data QUICKSORT indexes; + SHOW unsorted data; print( ( " -> " ) ); SHOW sorted data + END + +END diff --git a/Task/Sort-disjoint-sublist/Ada/sort-disjoint-sublist.ada b/Task/Sort-disjoint-sublist/Ada/sort-disjoint-sublist.adb similarity index 100% rename from Task/Sort-disjoint-sublist/Ada/sort-disjoint-sublist.ada rename to Task/Sort-disjoint-sublist/Ada/sort-disjoint-sublist.adb diff --git a/Task/Sort-disjoint-sublist/Arturo/sort-disjoint-sublist.arturo b/Task/Sort-disjoint-sublist/Arturo/sort-disjoint-sublist.arturo index 7450a6d336..b830a64007 100644 --- a/Task/Sort-disjoint-sublist/Arturo/sort-disjoint-sublist.arturo +++ b/Task/Sort-disjoint-sublist/Arturo/sort-disjoint-sublist.arturo @@ -3,7 +3,7 @@ sortDisjoint: function [data, indices][ inds: new indices sort 'inds - vals: new [] + vals: [] loop inds 'i -> 'vals ++ result\[i] sort 'vals diff --git a/Task/Sort-disjoint-sublist/BASIC256/sort-disjoint-sublist.basic b/Task/Sort-disjoint-sublist/BASIC256/sort-disjoint-sublist.basic new file mode 100644 index 0000000000..2744ccc5fc --- /dev/null +++ b/Task/Sort-disjoint-sublist/BASIC256/sort-disjoint-sublist.basic @@ -0,0 +1,23 @@ +dim values = {7, 6, 5, 4, 3, 2, 1, 0} +dim indices = {6, 1, 7} + +print "Before sort:" +for i = 0 to values[?]-1 + print values[i]; " "; +next i +print + +print +print "After sort:" +for i = 0 to 1 + if values[indices[i]] > values[indices[i + 1]] then + temp = values[indices[i]] + values[indices[i]] = values[indices[i+1]] + values[indices[i+1]] = temp + end if +next i + +for i = 0 to values[?]-1 + print values[i]; " "; +next i +end diff --git a/Task/Sort-disjoint-sublist/BQN/sort-disjoint-sublist.bqn b/Task/Sort-disjoint-sublist/BQN/sort-disjoint-sublist.bqn new file mode 100644 index 0000000000..4a5df821fb --- /dev/null +++ b/Task/Sort-disjoint-sublist/BQN/sort-disjoint-sublist.bqn @@ -0,0 +1,3 @@ +SortSublist ← ∧⊸{∧⌾(𝕨⊸⊏)𝕩} + +6‿1‿7 SortSublist 7‿6‿5‿4‿3‿2‿1‿0 diff --git a/Task/Sort-disjoint-sublist/Crystal/sort-disjoint-sublist.cr b/Task/Sort-disjoint-sublist/Crystal/sort-disjoint-sublist.cr new file mode 100644 index 0000000000..b2162a1d4b --- /dev/null +++ b/Task/Sort-disjoint-sublist/Crystal/sort-disjoint-sublist.cr @@ -0,0 +1,12 @@ +module Indexable::Mutable + def sort_at! (indices) + indices = indices.sort + indices.map {|idx| self[idx] }.sort.zip(indices) {|v, idx| self[idx] = v } + self + end +end + +values = [7, 6, 5, 4, 3, 2, 1, 0] +indices = [6, 1, 7] + +p! values, values.sort_at!(indices) diff --git a/Task/Sort-disjoint-sublist/Delphi/sort-disjoint-sublist.delphi b/Task/Sort-disjoint-sublist/Delphi/sort-disjoint-sublist.pas similarity index 100% rename from Task/Sort-disjoint-sublist/Delphi/sort-disjoint-sublist.delphi rename to Task/Sort-disjoint-sublist/Delphi/sort-disjoint-sublist.pas diff --git a/Task/Sort-disjoint-sublist/Elena/sort-disjoint-sublist.elena b/Task/Sort-disjoint-sublist/Elena/sort-disjoint-sublist.elena index d3742934af..bdff252cd1 100644 --- a/Task/Sort-disjoint-sublist/Elena/sort-disjoint-sublist.elena +++ b/Task/Sort-disjoint-sublist/Elena/sort-disjoint-sublist.elena @@ -4,7 +4,7 @@ import system'culture; extension op { - sortSublist(indices) + sortSublist(int[] indices) { var subList := indices.orderBy::(x => x) .zipBy(indices.selectBy::(i => self[i]) @@ -21,9 +21,9 @@ extension op } } -public program() +public Program() { - var list := new int[]{ 7, 6, 5, 4, 3, 2, 1, 0 }; + auto list := new int[]{ 7, 6, 5, 4, 3, 2, 1, 0 }; - console.printLine(list.sortSublist(new int[]{6, 1, 7}).asEnumerable()) + Console.printLine(list.sortSublist(new int[]{6, 1, 7}).asEnumerable()) } diff --git a/Task/Sort-disjoint-sublist/Elixir/sort-disjoint-sublist.elixir b/Task/Sort-disjoint-sublist/Elixir/sort-disjoint-sublist.ex similarity index 100% rename from Task/Sort-disjoint-sublist/Elixir/sort-disjoint-sublist.elixir rename to Task/Sort-disjoint-sublist/Elixir/sort-disjoint-sublist.ex diff --git a/Task/Sort-disjoint-sublist/Euphoria/sort-disjoint-sublist.euphoria b/Task/Sort-disjoint-sublist/Euphoria/sort-disjoint-sublist.eu similarity index 100% rename from Task/Sort-disjoint-sublist/Euphoria/sort-disjoint-sublist.euphoria rename to Task/Sort-disjoint-sublist/Euphoria/sort-disjoint-sublist.eu diff --git a/Task/Sort-disjoint-sublist/FreeBASIC/sort-disjoint-sublist.basic b/Task/Sort-disjoint-sublist/FreeBASIC/sort-disjoint-sublist.basic index f91b02851e..cbb4517363 100644 --- a/Task/Sort-disjoint-sublist/FreeBASIC/sort-disjoint-sublist.basic +++ b/Task/Sort-disjoint-sublist/FreeBASIC/sort-disjoint-sublist.basic @@ -1,12 +1,18 @@ -dim as integer value(0 to 7) = {7, 6, 5, 4, 3, 2, 1, 0} -dim as integer index(0 to 2) = {6, 1, 7}, i +Dim As Integer i +Dim As Integer values(7) => {7, 6, 5, 4, 3, 2, 1, 0} +Dim As Integer indices(2) => {6, 1, 7} -for i = 0 to 1 - if value(index(i))>value(index(i+1)) then - swap value(index(i)), value(index(i+1)) - end if -next i +Print "Before sort:" +For i = 0 To Ubound(values) + Print values(i); +Next i -for i = 0 to 7 - print value(i); -next i : print +Print !"\n\nAfter sort:" +For i = 0 To 1 + If values(indices(i)) > values(indices(i+1)) Then + Swap values(indices(i)), values(indices(i+1)) + End If +Next i +For i = 0 To Ubound(values) + Print values(i); +Next i : Print diff --git a/Task/Sort-disjoint-sublist/FutureBasic/sort-disjoint-sublist.basic b/Task/Sort-disjoint-sublist/FutureBasic/sort-disjoint-sublist.basic new file mode 100644 index 0000000000..52f4831947 --- /dev/null +++ b/Task/Sort-disjoint-sublist/FutureBasic/sort-disjoint-sublist.basic @@ -0,0 +1,21 @@ +void local fn DoIt + int i, values(7) = {7,6,5,4,3,2,1,0}, indices(2) = {6,1,7} + + print @"Before sort:" + for i = 0 to 7 + print values(i);@" "; + next + + for i = 0 to 1 + if ( values(indices(i)) > values(indices(i+1)) ) then swap values(indices(i)),values(indices(i+1)) + next + + print @"\n\nAfter sort:" + for i = 0 to 7 + print values(i);@" "; + next +end fn + +fn DoIt + +HandleEvents diff --git a/Task/Sort-disjoint-sublist/Gambas/sort-disjoint-sublist.gambas b/Task/Sort-disjoint-sublist/Gambas/sort-disjoint-sublist.gambas new file mode 100644 index 0000000000..9ea45a7fe1 --- /dev/null +++ b/Task/Sort-disjoint-sublist/Gambas/sort-disjoint-sublist.gambas @@ -0,0 +1,23 @@ +Public values As Integer[] = [7, 6, 5, 4, 3, 2, 1, 0] +Public indices As Integer[] = [6, 1, 7] + +Public Sub Main() + + Dim i As Integer + + Print "Before sort:" + For i = 0 To values.Max + Print values[i]; " "; + Next + + Print "\n\nAfter sort:" + For i = 0 To 1 + If values[indices[i]] > values[indices[i + 1]] Then + Swap values[indices[i]], values[indices[i + 1]] + End If + Next + For i = 0 To values.Max + Print values[i]; " "; + Next + +End diff --git a/Task/Sort-disjoint-sublist/Julia/sort-disjoint-sublist.julia b/Task/Sort-disjoint-sublist/Julia/sort-disjoint-sublist.jl similarity index 100% rename from Task/Sort-disjoint-sublist/Julia/sort-disjoint-sublist.julia rename to Task/Sort-disjoint-sublist/Julia/sort-disjoint-sublist.jl diff --git a/Task/Sort-disjoint-sublist/Kotlin/sort-disjoint-sublist.kotlin b/Task/Sort-disjoint-sublist/Kotlin/sort-disjoint-sublist.kts similarity index 100% rename from Task/Sort-disjoint-sublist/Kotlin/sort-disjoint-sublist.kotlin rename to Task/Sort-disjoint-sublist/Kotlin/sort-disjoint-sublist.kts diff --git a/Task/Sort-disjoint-sublist/OCaml/sort-disjoint-sublist-1.ocaml b/Task/Sort-disjoint-sublist/OCaml/sort-disjoint-sublist-1.ml similarity index 100% rename from Task/Sort-disjoint-sublist/OCaml/sort-disjoint-sublist-1.ocaml rename to Task/Sort-disjoint-sublist/OCaml/sort-disjoint-sublist-1.ml diff --git a/Task/Sort-disjoint-sublist/OCaml/sort-disjoint-sublist-2.ocaml b/Task/Sort-disjoint-sublist/OCaml/sort-disjoint-sublist-2.ml similarity index 100% rename from Task/Sort-disjoint-sublist/OCaml/sort-disjoint-sublist-2.ocaml rename to Task/Sort-disjoint-sublist/OCaml/sort-disjoint-sublist-2.ml diff --git a/Task/Sort-disjoint-sublist/Phix/sort-disjoint-sublist-1.phix b/Task/Sort-disjoint-sublist/Phix/sort-disjoint-sublist-1.phix deleted file mode 100644 index 231a15c75b..0000000000 --- a/Task/Sort-disjoint-sublist/Phix/sort-disjoint-sublist-1.phix +++ /dev/null @@ -1,18 +0,0 @@ -(phixonline)--> - with javascript_semantics - function disjoint_sort(sequence s, sequence idx) - idx = unique(idx) - integer l = length(idx) - sequence copies = repeat(0, l) - for i=1 to l do - copies[i] = s[idx[i]] - end for - copies = sort(copies) - for i=1 to l do - s[idx[i]] = copies[i] - end for - return s - end function - - ?disjoint_sort({7,6,5,4,3,2,1,0},{7,2,8}) - - with javascript_semantics - function disjoint_sort(sequence s, idx) - idx = unique(idx) - return reinstate(s,idx,sort(extract(s,idx))) - end function - - ?disjoint_sort({7,6,5,4,3,2,1,0},{7,2,8}) - - with javascript_semantics - function lexicographic_order(sequence s) - return extract(s,custom_sort(apply(s,sprint),tagset(length(s)))) - end function +with javascript_semantics +function lexicographic_order(sequence s) + return extract(s,custom_sort(apply(s,sprint),tagset(length(s)))) +end function - ?lexicographic_order({1,0}) - ?lexicographic_order(tagset(5)) - ?lexicographic_order(tagset(13)) - ?lexicographic_order(tagset(21,1,2)) - ?lexicographic_order(tagset(11,-21,4)) - ?lexicographic_order({1.25, -6, -10, 9, -11.3, 13, -3, 0}) - - function my_compare(sequence a, b) - integer c = -compare(length(a),length(b)) -- descending length - if c=0 then - c = compare(lower(a),lower(b)) -- ascending lexical within same length - end if - return c - end function - ?custom_sort(my_compare,{"Here", "are", "some", "sample", "strings", "to", "be", "sorted"}) - - with javascript_semantics - - sequence array - - function circle_sort_inner(integer lo, hi, swaps, level=1) - if lo!=hi then - integer high := hi, - low := lo, - mid := floor((high-low)/2) - while lo <= hi do - hi += (lo=hi) - object alo = array[lo], - ahi = array[hi] - if alo > ahi then - array[lo] = ahi - array[hi] = alo - printf(1,"%V level %d, low %d, high %d\n",{array,level,low,high}) - swaps += 1 - end if - lo += 1 - hi -= 1 - end while - swaps = circle_sort_inner(low,low+mid,swaps,level+1) - swaps = circle_sort_inner(low+mid+1,high,swaps,level+1) - end if - return swaps - end function - - procedure circle_sort() - printf(1,"%V <== (initial)\n",{array}) - while circle_sort_inner(1, length(array), 0) do ?"loop" end while - printf(1,"%V <== (sorted)\n",{array}) - end procedure - - array = {5, -1, 101, -4, 0, 1, 8, 6, 2, 3} - --array = {-4,-1,1,0,5,-7,-2,4,-6,-3,2,6,3,7,-5} - --array = {6, 7, 8, 9, 2, 5, 3, 4, 1} - --array = {2,14,4,6,8,1,3,5,7,9,10,11,0,13,12,-1} - --array = {"the","quick","brown","fox","jumps","over","the","lazy","dog"} - --array = {0.603704, 0.293639, 0.513965, 0.746246, 0.245282, 0.930508, 0.550878, 0.622534, 0.006089, 0.270426} - --array = shuffle(deep_copy(array)) - circle_sort() - b ) - - [ behead swap witheach - [ 2dup < iff - nip else drop ] ] is largest ( [ --> n ) - - [ dup largest 1+ - over size - dup 1 - [ 2dup > while - 1 << again ] - nip swap - - dup dip [ of join ] - swap ] is pad ( [ --> n [ ) - - [ swap dup if - [ negate split drop ] ] is unpad ( n [ --> [ ) - - [ dup size times - [ i i^ > not iff - conclude done - dup i peek - over i^ peek - 2dup < iff - [ rot i poke - i^ poke ] - else 2drop ] ] is reorder ( [ --> [ ) - - [ pad - [ [ dup sorted if done - reorder - dup size 2 / split - recurse swap - recurse swap join ] - dup sorted until ] - unpad ] is circlesort ( [ --> [ ) - - $ "bababadalgharaghtakamminarronnkonnbronntonnerronntuonnthunntrovarrhounawnskawntoohoohoordenenthurnuk" - dup echo$ cr - circlesort echo$ cr diff --git a/Task/Sorting-Algorithms-Circle-Sort/REXX/sorting-algorithms-circle-sort.rexx b/Task/Sorting-Algorithms-Circle-Sort/REXX/sorting-algorithms-circle-sort.rexx deleted file mode 100644 index 957ff7711e..0000000000 --- a/Task/Sorting-Algorithms-Circle-Sort/REXX/sorting-algorithms-circle-sort.rexx +++ /dev/null @@ -1,26 +0,0 @@ -/*REXX program uses a circle sort algorithm to sort an array (or list) of numbers. */ -parse arg x /*obtain optional arguments from the CL*/ -if x='' | x="," then x= 6 7 8 9 2 5 3 4 1 /*Not specified? Then use the default.*/ -call make_array 'before sort:' /*display the list and make an array. */ -call circleSort # /*invoke the circle sort subroutine. */ -call make_list ' after sort:' /*make a list and display it to console*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -circleSort: do while .circleSrt(1, arg(1), 0)\==0; end; return -make_array: #= words(x); do i=1 for #; @.i= word(x, i); end; say arg(1) x; return -make_list: y= @.1; do j=2 for #-1; y= y @.j; end; say arg(1) y; return -.swap: parse arg a,b; parse value @.a @.b with @.b @.a; swaps= swaps+1; return -/*──────────────────────────────────────────────────────────────────────────────────────*/ -.circleSrt: procedure expose @.; parse arg LO,HI,swaps /*obtain LO & HI arguments.*/ - if LO==HI then return swaps /*1 element? Done with sort.*/ - high= HI; low= LO; mid= (HI-LO) % 2 /*assign some indices. */ - /* [↓] sort a section of #'s*/ - do while LO@.HI then call .swap LO,HI /*are numbers out of order ? */ - LO= LO + 1; HI= HI - 1 /*add to LO; shrink the HI. */ - end /*while*/ /*just process one section. */ - _= HI + 1 /*point to HI plus one. */ - if LO==HI & @.LO>@._ then call .swap LO, _ /*numbers still out of order?*/ - swaps= .circleSrt(low, low+mid, swaps) /*sort the lower section. */ - swaps= .circleSrt(low+mid+1, high, swaps) /* " " higher " */ - return swaps /*the section sorting is done*/ diff --git a/Task/Sorting-Algorithms-Circle-Sort/Racket/sorting-algorithms-circle-sort.rkt b/Task/Sorting-Algorithms-Circle-Sort/Racket/sorting-algorithms-circle-sort.rkt deleted file mode 100644 index 1f87cd6298..0000000000 --- a/Task/Sorting-Algorithms-Circle-Sort/Racket/sorting-algorithms-circle-sort.rkt +++ /dev/null @@ -1,35 +0,0 @@ -#lang racket -(define (circle-sort v0 [= L (- R 1)) #f] ; covers 0 or 1 vectors - [else - (define M (quotient (+ L R) 2)) - (define I-moved? - (for/or ([l (in-range L M)] [r (in-range (- R 1) L -1)]) - (swap-if l r))) - (define M-moved? (and (odd? (- L R)) (> M 0) (swap-if (- M 1) M))) - (define L-moved? (inr-cs! L M)) - (define R-moved? (inr-cs! M R)) - (or I-moved? L-moved? R-moved? M-moved?)])) - - (let loop () (when (inr-cs! 0 (vector-length v)) (loop))) - v) - -(define (sort-random-vector) - (define v (build-vector (+ 2 (random 10)) (λ (i) (random 100)))) - (define v< (circle-sort v <)) - (define sorted? (apply <= (vector->list v<))) - (printf " ~.a\n-> ~.a [~a]\n\n" v v< sorted?)) - -(for ([_ 10]) (sort-random-vector)) - -(circle-sort '#("table" "chair" "cat" "sponge") string; -say @x while circlesort(@x, 0, @x.end); diff --git a/Task/Sorting-Algorithms-Circle-Sort/Ring/sorting-algorithms-circle-sort.ring b/Task/Sorting-Algorithms-Circle-Sort/Ring/sorting-algorithms-circle-sort.ring deleted file mode 100644 index fbed4db050..0000000000 --- a/Task/Sorting-Algorithms-Circle-Sort/Ring/sorting-algorithms-circle-sort.ring +++ /dev/null @@ -1,44 +0,0 @@ -# Project : Sorting Algorithms/Circle Sort - -test = [-4, -1, 1, 0, 5, -7, -2, 4, -6, -3, 2, 6, 3, 7, -5] -while circlesort(1, len(test), 0) end -showarray(test) - -func circlesort(lo, hi, swaps) - if lo = hi - return swaps - ok - high = hi - low = lo - mid = floor((hi-lo)/2) - while lo < hi - if test[lo] > test[hi] - temp = test[lo] - test[lo] = test[hi] - test[hi] = temp - swaps = swaps + 1 - ok - lo = lo + 1 - hi = hi - 1 - end - if lo = hi - if test[lo] > test[hi+1] - temp = test[lo] - test[lo] = test[hi+1] - test[hi + 1] = temp - swaps = swaps + 1 - ok - ok - swaps = circlesort(low, low+mid, swaps) - swaps = circlesort(low+mid+1 ,high, swaps) - return swaps - -func showarray(vect) - see "[" - svect = "" - for n = 1 to len(vect) - svect = svect + vect[n] + ", " - next - svect = left(svect, len(svect) - 2) - see svect - see "]" + nl diff --git a/Task/Sorting-Algorithms-Circle-Sort/Ruby/sorting-algorithms-circle-sort.rb b/Task/Sorting-Algorithms-Circle-Sort/Ruby/sorting-algorithms-circle-sort.rb deleted file mode 100644 index 74045d983e..0000000000 --- a/Task/Sorting-Algorithms-Circle-Sort/Ruby/sorting-algorithms-circle-sort.rb +++ /dev/null @@ -1,31 +0,0 @@ -class Array - def circle_sort! - while _circle_sort!(0, size-1) > 0 - end - self - end - - private - def _circle_sort!(lo, hi, swaps=0) - return swaps if lo == hi - low, high = lo, hi - mid = (lo + hi) / 2 - while lo < hi - if self[lo] > self[hi] - self[lo], self[hi] = self[hi], self[lo] - swaps += 1 - end - lo += 1 - hi -= 1 - end - if lo == hi && self[lo] > self[hi+1] - self[lo], self[hi+1] = self[hi+1], self[lo] - swaps += 1 - end - swaps + _circle_sort!(low, mid) + _circle_sort!(mid+1, high) - end -end - -ary = [6, 7, 8, 9, 2, 5, 3, 4, 1] -puts "before sort: #{ary}" -puts " after sort: #{ary.circle_sort!}" diff --git a/Task/Sorting-Algorithms-Circle-Sort/Rust/sorting-algorithms-circle-sort.rust b/Task/Sorting-Algorithms-Circle-Sort/Rust/sorting-algorithms-circle-sort.rust deleted file mode 100644 index e19d19454a..0000000000 --- a/Task/Sorting-Algorithms-Circle-Sort/Rust/sorting-algorithms-circle-sort.rust +++ /dev/null @@ -1,42 +0,0 @@ -fn _circle_sort(a: &mut [T], low: usize, high: usize, swaps: usize) -> usize { - if low == high { - return swaps; - } - let mut lo = low; - let mut hi = high; - let mid = (hi - lo) / 2; - let mut s = swaps; - while lo < hi { - if a[lo] > a[hi] { - a.swap(lo, hi); - s += 1; - } - lo += 1; - hi -= 1; - } - if lo == hi { - if a[lo] > a[hi + 1] { - a.swap(lo, hi + 1); - s += 1; - } - } - s = _circle_sort(a, low, low + mid, s); - s = _circle_sort(a, low + mid + 1, high, s); - return s; -} - -fn circle_sort(a: &mut [T]) { - let len = a.len(); - loop { - if _circle_sort(a, 0, len - 1, 0) == 0 { - break; - } - } -} - -fn main() { - let mut v = vec![10, 8, 4, 3, 1, 9, 0, 2, 7, 5, 6]; - println!("before: {:?}", v); - circle_sort(&mut v); - println!("after: {:?}", v); -} diff --git a/Task/Sorting-Algorithms-Circle-Sort/Scala/sorting-algorithms-circle-sort.scala b/Task/Sorting-Algorithms-Circle-Sort/Scala/sorting-algorithms-circle-sort.scala deleted file mode 100644 index 6ecddd796c..0000000000 --- a/Task/Sorting-Algorithms-Circle-Sort/Scala/sorting-algorithms-circle-sort.scala +++ /dev/null @@ -1,40 +0,0 @@ -object CircleSort extends App { - - def sort(arr: Array[Int]): Array[Int] = { - def circleSortR(arr: Array[Int], _lo: Int, _hi: Int, _numSwaps: Int): Int = { - var lo = _lo - var hi = _hi - var numSwaps = _numSwaps - - def swap(arr: Array[Int], idx1: Int, idx2: Int): Unit = { - val tmp = arr(idx1) - arr(idx1) = arr(idx2) - arr(idx2) = tmp - } - - if (lo == hi) return numSwaps - val (high, low) = (hi, lo) - val mid = (hi - lo) / 2 - while ( lo < hi) { - if (arr(lo) > arr(hi)) { - swap(arr, lo, hi) - numSwaps += 1 - } - lo += 1 - hi -= 1 - } - if (lo == hi && arr(lo) > arr(hi + 1)) { - swap(arr, lo, hi + 1) - numSwaps += 1 - } - - circleSortR(arr, low + mid + 1, high, circleSortR(arr, low, low + mid, numSwaps)) - } - - while (circleSortR(arr, 0, arr.length - 1, 0) != 0)() - arr - } - - println(sort(Array[Int](2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1)).mkString(", ")) - -} diff --git a/Task/Sorting-Algorithms-Circle-Sort/Sidef/sorting-algorithms-circle-sort.sidef b/Task/Sorting-Algorithms-Circle-Sort/Sidef/sorting-algorithms-circle-sort.sidef deleted file mode 100644 index 6abcca93ef..0000000000 --- a/Task/Sorting-Algorithms-Circle-Sort/Sidef/sorting-algorithms-circle-sort.sidef +++ /dev/null @@ -1,22 +0,0 @@ -func circlesort(arr, beg=0, end=arr.end) { - var swaps = 0 - if (beg < end) { - var (lo, hi) = (beg, end) - do { - if (arr[lo] > arr[hi]) { - arr.swap(lo, hi) - ++swaps - } - ++hi if (--hi == ++lo) - } while (lo < hi) - swaps += circlesort(arr, beg, hi) - swaps += circlesort(arr, lo, end) - } - return swaps -} - -var numbers = %n(2 3 3 5 5 1 1 7 7 6 6 4 4 0 0) -do { say numbers } while circlesort(numbers) -  -var strs = ["John", "Kate", "Zerg", "Alice", "Joe", "Jane", "Alice"] -do { say strs } while circlesort(strs) diff --git a/Task/Sorting-Algorithms-Circle-Sort/Swift/sorting-algorithms-circle-sort.swift b/Task/Sorting-Algorithms-Circle-Sort/Swift/sorting-algorithms-circle-sort.swift deleted file mode 100644 index 458d0d026a..0000000000 --- a/Task/Sorting-Algorithms-Circle-Sort/Swift/sorting-algorithms-circle-sort.swift +++ /dev/null @@ -1,39 +0,0 @@ -func circleSort(_ array: inout [T]) { - func circSort(low: Int, high: Int, swaps: Int) -> Int { - if low == high { - return swaps - } - var lo = low - var hi = high - let mid = (hi - lo) / 2 - var s = swaps - while lo < hi { - if array[lo] > array[hi] { - array.swapAt(lo, hi) - s += 1 - } - lo += 1 - hi -= 1 - } - if lo == hi { - if array[lo] > array[hi + 1] { - array.swapAt(lo, hi + 1) - s += 1 - } - } - s = circSort(low: low, high: low + mid, swaps: s) - s = circSort(low: low + mid + 1, high: high, swaps: s) - return s - } - while circSort(low: 0, high: array.count - 1, swaps: 0) != 0 {} -} - -var array = [10, 8, 4, 3, 1, 9, 0, 2, 7, 5, 6] -print("before: \(array)") -circleSort(&array) -print(" after: \(array)") - -var array2 = ["one", "two", "three", "four", "five", "six", "seven", "eight"] -print("before: \(array2)") -circleSort(&array2) -print(" after: \(array2)") diff --git a/Task/Sorting-Algorithms-Circle-Sort/V-(Vlang)/sorting-algorithms-circle-sort.v b/Task/Sorting-Algorithms-Circle-Sort/V-(Vlang)/sorting-algorithms-circle-sort.v deleted file mode 100644 index 9b78161cd3..0000000000 --- a/Task/Sorting-Algorithms-Circle-Sort/V-(Vlang)/sorting-algorithms-circle-sort.v +++ /dev/null @@ -1,42 +0,0 @@ -fn circle_sort(mut a []int, l int, h int, s int) int { - mut hi := h - mut lo := l - mut swaps := s - if lo == hi { - return swaps - } - high, low := hi, lo - mid := (hi - lo) / 2 - for lo < hi { - if a[lo] > a[hi] { - a[lo], a[hi] = a[hi], a[lo] - swaps++ - } - lo++ - hi-- - } - if lo == hi { - if a[lo] > a[hi+1] { - a[lo], a[hi+1] = a[hi+1], a[lo] - swaps++ - } - } - swaps = circle_sort(mut a, low, low+mid, swaps) - swaps = circle_sort(mut a, low+mid+1, high, swaps) - return swaps -} - -fn main() { - aa := [ - [6, 7, 8, 9, 2, 5, 3, 4, 1], - [2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1], - ] - for a1 in aa { - mut a:=a1.clone() - println("Original: $a") - for circle_sort(mut a, 0, a.len-1, 0) != 0 { - // empty block - } - println("Sorted : $a\n") - } -} diff --git a/Task/Sorting-Algorithms-Circle-Sort/Wren/sorting-algorithms-circle-sort.wren b/Task/Sorting-Algorithms-Circle-Sort/Wren/sorting-algorithms-circle-sort.wren deleted file mode 100644 index 1ef9309775..0000000000 --- a/Task/Sorting-Algorithms-Circle-Sort/Wren/sorting-algorithms-circle-sort.wren +++ /dev/null @@ -1,36 +0,0 @@ -var circleSort // recursive -circleSort = Fn.new { |a, lo, hi, swaps| - if (lo == hi) return swaps - var high = hi - var low = lo - var mid = ((hi-lo)/2).floor - while (lo < hi) { - if (a[lo] > a[hi]) { - var t = a[lo] - a[lo] = a[hi] - a[hi] = t - swaps = swaps + 1 - } - lo = lo + 1 - hi = hi - 1 - } - if (lo == hi) { - if (a[lo] > a[hi+1]) { - var t = a[lo] - a[lo] = a[hi+1] - a[hi+1] = t - swaps = swaps + 1 - } - } - swaps = circleSort.call(a, low, low + mid, swaps) - swaps = circleSort.call(a, low + mid + 1, high, swaps) - return swaps -} - -var array = [ [6, 7, 8, 9, 2, 5, 3, 4, 1], [2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1] ] -for (a in array) { - System.print("Before: %(a)") - while (circleSort.call(a, 0, a.count-1, 0) != 0) {} - System.print("After : %(a)") - System.print() -} diff --git a/Task/Sorting-Algorithms-Circle-Sort/XPL0/sorting-algorithms-circle-sort.xpl0 b/Task/Sorting-Algorithms-Circle-Sort/XPL0/sorting-algorithms-circle-sort.xpl0 deleted file mode 100644 index b260b9eff4..0000000000 --- a/Task/Sorting-Algorithms-Circle-Sort/XPL0/sorting-algorithms-circle-sort.xpl0 +++ /dev/null @@ -1,33 +0,0 @@ -int Array; - -func CircleSort(Lo, Hi, Swaps); -int Lo, Hi, Swaps; -int Low, High, Mid, T; -[if Lo = Hi then return Swaps; -Low:= Lo; -High:= Hi; -Mid:= (Hi-Lo)/2; -while Lo < Hi do - [if Array(Lo) > Array(Hi) then - [T:= Array(Lo); Array(Lo):= Array(Hi); Array(Hi):= T; - Swaps:= Swaps+1; - ]; - Lo:= Lo+1; - Hi:= Hi-1; - ]; -if Lo = Hi then - if Array(Lo) > Array(Hi+1) then - [T:= Array(Lo); Array(Lo):= Array(Hi+1); Array(Hi+1):= T; - Swaps:= Swaps+1; - ]; -Swaps:= CircleSort(Low, Low+Mid, Swaps); -Swaps:= CircleSort(Low+Mid+1, High, Swaps); -return Swaps; -]; - -int I; -[Array:= [5, -1, 101, -4, 0, 1, 8, 6, 2, 3]; -while CircleSort(0, 10-1, 0) # 0 do []; -for I:= 0 to 10-1 do - [IntOut(0, Array(I)); ChOut(0, ^ )]; -] diff --git a/Task/Sorting-Algorithms-Circle-Sort/ZX-Spectrum-Basic/sorting-algorithms-circle-sort.basic b/Task/Sorting-Algorithms-Circle-Sort/ZX-Spectrum-Basic/sorting-algorithms-circle-sort.basic deleted file mode 100644 index 9e764c0556..0000000000 --- a/Task/Sorting-Algorithms-Circle-Sort/ZX-Spectrum-Basic/sorting-algorithms-circle-sort.basic +++ /dev/null @@ -1,11 +0,0 @@ - 10 DIM a(100): DIM s(32): RANDOMIZE : LET p=1: GO SUB 3000: GO SUB 2000: GO SUB 4000 - 20 STOP - 1000 IF b=e THEN RETURN - 1010 LET s(p)=b: LET s(p+1)=e - 1020 IF a(s(p))>a(e) THEN LET t=a(s(p)): LET a(s(p))=a(e): LET a(e)=t: LET c=1 - 1030 LET s(p)=s(p)+1: LET e=e-1: IF s(p)0 THEN GO TO 2000 - 2010 CLS : RETURN - 3000 FOR x=1 TO 100: LET a(x)=RND: NEXT x: RETURN - 4000 FOR x=1 TO 100: PRINT x,a(x): NEXT x: RETURN diff --git a/Task/Sorting-Algorithms-Circle-Sort/Zkl/sorting-algorithms-circle-sort-1.zkl b/Task/Sorting-Algorithms-Circle-Sort/Zkl/sorting-algorithms-circle-sort-1.zkl deleted file mode 100644 index 75ee38e3bf..0000000000 --- a/Task/Sorting-Algorithms-Circle-Sort/Zkl/sorting-algorithms-circle-sort-1.zkl +++ /dev/null @@ -1,24 +0,0 @@ -fcn circleSort(list){ - csort:=fcn(list,lo,hi,swaps){ - if(lo==hi) return(swaps); - high,low,mid:=hi,lo,(hi-lo)/2; - while(lolist[hi]){ - list.swap(lo,hi); - swaps+=1; - } - lo+=1; hi-=1; - } - if(lo==hi) - if (list[lo]>list[hi+1]){ - list.swap(lo,hi+1); - swaps+=1; - } - swaps=self.fcn(list,low,low + mid,swaps); - swaps=self.fcn(list,low + mid + 1,high,swaps); - return(swaps); - }; - list.println(); - while(csort(list,0,list.len()-1,0)){ list.println() } - list -} diff --git a/Task/Sorting-Algorithms-Circle-Sort/Zkl/sorting-algorithms-circle-sort-2.zkl b/Task/Sorting-Algorithms-Circle-Sort/Zkl/sorting-algorithms-circle-sort-2.zkl deleted file mode 100644 index f4307a8567..0000000000 --- a/Task/Sorting-Algorithms-Circle-Sort/Zkl/sorting-algorithms-circle-sort-2.zkl +++ /dev/null @@ -1,2 +0,0 @@ -circleSort(L(6,7,8,9,2,5,3,4,1)); -circleSort(L(5,-1,101,-4,0,1,8,6,2,3)); diff --git a/Task/Sorting-algorithms-Bead-sort/Arturo/sorting-algorithms-bead-sort.arturo b/Task/Sorting-algorithms-Bead-sort/Arturo/sorting-algorithms-bead-sort.arturo index be72a546b2..3a0ffee970 100644 --- a/Task/Sorting-algorithms-Bead-sort/Arturo/sorting-algorithms-bead-sort.arturo +++ b/Task/Sorting-algorithms-Bead-sort/Arturo/sorting-algorithms-bead-sort.arturo @@ -1,6 +1,6 @@ beadSort: function [items][ a: new items - m: neg infinity + m: neg infinite s: 0 loop a 'x [ diff --git a/Task/Sorting-algorithms-Bead-sort/COBOL/sorting-algorithms-bead-sort.cobol b/Task/Sorting-algorithms-Bead-sort/COBOL/sorting-algorithms-bead-sort.cob similarity index 100% rename from Task/Sorting-algorithms-Bead-sort/COBOL/sorting-algorithms-bead-sort.cobol rename to Task/Sorting-algorithms-Bead-sort/COBOL/sorting-algorithms-bead-sort.cob diff --git a/Task/Sorting-algorithms-Bead-sort/Delphi/sorting-algorithms-bead-sort.delphi b/Task/Sorting-algorithms-Bead-sort/Delphi/sorting-algorithms-bead-sort.pas similarity index 100% rename from Task/Sorting-algorithms-Bead-sort/Delphi/sorting-algorithms-bead-sort.delphi rename to Task/Sorting-algorithms-Bead-sort/Delphi/sorting-algorithms-bead-sort.pas diff --git a/Task/Sorting-algorithms-Bead-sort/EasyLang/sorting-algorithms-bead-sort.easy b/Task/Sorting-algorithms-Bead-sort/EasyLang/sorting-algorithms-bead-sort.easy new file mode 100644 index 0000000000..f2c6de77da --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/EasyLang/sorting-algorithms-bead-sort.easy @@ -0,0 +1,21 @@ +proc beadSort &a[] . + for i to len a[] : max = higher max a[i] + len beads[][] len a[] + for i to len a[] + len beads[i][] max + for j to a[i] : beads[i][j] = 1 + . + for j to max + sum = 0 + for i = 1 to len a[] + sum += beads[i][j] + beads[i][j] = 0 + . + for i = len a[] downto len a[] - sum + 1 + a[i] = j + . + . +. +a[] = [ 4 38 100 1 25 69 69 16 8 59 71 53 33 ] +beadSort a[] +print a[] diff --git a/Task/Sorting-algorithms-Bead-sort/Elixir/sorting-algorithms-bead-sort.elixir b/Task/Sorting-algorithms-Bead-sort/Elixir/sorting-algorithms-bead-sort.ex similarity index 100% rename from Task/Sorting-algorithms-Bead-sort/Elixir/sorting-algorithms-bead-sort.elixir rename to Task/Sorting-algorithms-Bead-sort/Elixir/sorting-algorithms-bead-sort.ex diff --git a/Task/Sorting-algorithms-Bead-sort/Julia/sorting-algorithms-bead-sort.julia b/Task/Sorting-algorithms-Bead-sort/Julia/sorting-algorithms-bead-sort.jl similarity index 100% rename from Task/Sorting-algorithms-Bead-sort/Julia/sorting-algorithms-bead-sort.julia rename to Task/Sorting-algorithms-Bead-sort/Julia/sorting-algorithms-bead-sort.jl diff --git a/Task/Sorting-algorithms-Bead-sort/Kotlin/sorting-algorithms-bead-sort.kotlin b/Task/Sorting-algorithms-Bead-sort/Kotlin/sorting-algorithms-bead-sort.kts similarity index 100% rename from Task/Sorting-algorithms-Bead-sort/Kotlin/sorting-algorithms-bead-sort.kotlin rename to Task/Sorting-algorithms-Bead-sort/Kotlin/sorting-algorithms-bead-sort.kts diff --git a/Task/Sorting-algorithms-Bead-sort/OCaml/sorting-algorithms-bead-sort.ocaml b/Task/Sorting-algorithms-Bead-sort/OCaml/sorting-algorithms-bead-sort.ml similarity index 100% rename from Task/Sorting-algorithms-Bead-sort/OCaml/sorting-algorithms-bead-sort.ocaml rename to Task/Sorting-algorithms-Bead-sort/OCaml/sorting-algorithms-bead-sort.ml diff --git a/Task/Sorting-algorithms-Bead-sort/Phix/sorting-algorithms-bead-sort.phix b/Task/Sorting-algorithms-Bead-sort/Phix/sorting-algorithms-bead-sort.phix index 952b327978..8b47117b01 100644 --- a/Task/Sorting-algorithms-Bead-sort/Phix/sorting-algorithms-bead-sort.phix +++ b/Task/Sorting-algorithms-Bead-sort/Phix/sorting-algorithms-bead-sort.phix @@ -1,17 +1,23 @@ -(phixonline)--> - with javascript_semantics +with javascript_semantics - function beadsort(sequence a) - sequence poles = repeat(0,max(a)) - for i=1 to length(a) do - poles[1..a[i]] = sq_add(poles[1..a[i]],1) - end for - a[1..$] = 0 - for i=1 to length(poles) do - a[1..poles[i]] = sq_add(a[1..poles[i]],1) - end for - return a - end function +function beadsort(sequence a) + sequence poles = repeat(0,max(a)) + for k in a do + poles[1..k] = sq_add(poles[1..k],1) +--or +-- for i,p in poles to k do +-- poles[i] = p+1 +-- end for + end for + a[1..$] = 0 + for p in poles do + a[-p..$] = sq_add(a[-p..$],1) +--or +-- for i,n in a from -p to -1 do +-- a[i] = n+1 +-- end for + end for + return a +end function - ?beadsort({5, 3, 1, 7, 4, 1, 1, 20}) - - with javascript_semantics +with javascript_semantics - function inOrder(sequence s) - return s==sort(deep_copy(s)) -- <snigger> - end function +function inOrder(sequence s) + return s==sort(deep_copy(s)) -- +end function - function bogosort(sequence s) - while not inOrder(s) do - ? s - s = shuffle(s) - end while - return s - end function +function bogosort(sequence s) + while not inOrder(s) do + ? s + s = shuffle(s) + end while + return s +end function - ? bogosort(shuffle({1,2,3,4,5,6})) - - with javascript_semantics +with javascript_semantics - function cocktailShakerSort(sequence s) - s = deep_copy(s) - integer beginIdx = 1, - endIdx = length(s)-1 - while beginIdx <= endIdx do - integer newBeginIdx = endIdx, - newEndIdx = beginIdx - for ii=beginIdx to endIdx do - object si = s[ii], - sn = s[ii+1] - if si>sn then - s[ii] = sn - s[ii+1] = si - newEndIdx = ii - end if - end for - -- elements after `newEndIdx` are now in correct order - endIdx = newEndIdx - 1 - for ii=endIdx to beginIdx by -1 do - object si = s[ii], - sn = s[ii+1] - if si>sn then - s[ii] = sn - s[ii+1] = si - newBeginIdx = ii - end if - end for - -- elements before `newBeginIdx` are now in correct order. - beginIdx = newBeginIdx + 1 - end while - return s - end function - sequence s = shuffle(tagset(12)) ?{s,cocktailShakerSort(s)} - s = {"one","two","three","four"} ?{s,cocktailShakerSort(s)} - - with javascript_semantics +with javascript_semantics - function cocktail_sort(sequence s) - s = deep_copy(s) - integer swapped = 1, f = 1, t = length(s)-1, d = 1 - while swapped do - swapped = 0 - for i=f to t by d do - object si = s[i], - sn = s[i+1] - if si>sn then - s[i] = sn - s[i+1] = si - swapped = 1 - end if - end for - -- swap to and from, and flip direction. - -- additionally, we can reduce one element to be - -- examined, depending on which way we just went. - {f,t,d} = {t-d,f,-d} - end while - return s - end function +function cocktail_sort(sequence s) + s = deep_copy(s) + integer f = 1, t = length(s)-1, d = 1 + do + bool swapped = false + for i=f to t by d do + object {si,sn} = s[i..i+1] + if si>sn then + s[i..i+1] = {sn,si} + swapped = true + end if + end for + -- swap to and from, and flip direction. + -- additionally, we can reduce one element to be + -- examined, depending on which way we just went. + {f,t,d} = {t-d,f,-d} + until not swapped + return s +end function - constant s = sq_rand(repeat(1000,10)) - printf(1,"original: %V\n",{s}) - printf(1," sorted: %V\n",{cocktail_sort(s)}) - - with javascript_semantics +with javascript_semantics - function comb_sort(sequence s) - integer gap = length(s)-1 - while 1 do - gap = max(floor(gap/1.3),1) - integer swapped = 0 - for i=1 to length(s)-gap do - object si = s[i] - if si>s[i+gap] then - s[i] = s[i+gap] - s[i+gap] = si - swapped = 1 - end if - end for - if gap=1 and swapped=0 then exit end if - end while - return s - end function +function comb_sort(sequence s) + integer gap = length(s)-1 + do + gap = max(floor(gap/1.3),1) + bool swapped = false + for i=1 to length(s)-gap do + object si = s[i], sn = s[i+gap] + if si>sn then + s[i] = sn + s[i+gap] = si + swapped = true + end if + end for + until gap=1 and not swapped + return s +end function - ?comb_sort(shuffle(tagset(10))) - - with javascript_semantics +with javascript_semantics - function countingSort(sequence array, integer mina, maxa) - sequence count = repeat(0,maxa-mina+1) - array = deep_copy(array) - for i=1 to length(array) do - count[array[i]-mina+1] += 1 - end for - integer z = 1 - for i=mina to maxa do - for j=1 to count[i-mina+1] do - array[z] := i - z += 1 - end for - end for - return array - end function +function counting_sort(sequence s, integer mine, maxe) + sequence count = repeat(0,maxe-mine+1), res = {} + for e in s do + count[e-mine+1] += 1 + end for + for i,c in count do + res &= repeat(i+mine-1,c) + end for + return res +end function - sequence s = {5, 3, 1, 7, 4, 1, 1, 20} - ?countingSort(s,min(s),max(s)) - - with javascript_semantics +with javascript_semantics - function gnomeSort(sequence s) - integer i = 1, j = 2 - while i<length(s) do - object si = s[i], - sn = s[i+1] - if si<=sn then - i = j - j += 1 - else - s[i] = sn - s[i+1] = si - i -= 1 - if i = 0 then - i = j - j += 1 - end if - end if - end while - return s - end function +function gnomeSort(sequence s) + integer i = 1, j = 2 + while i?
    gnomeSort(shuffle(tagset(10))) - - with javascript_semantics +with javascript_semantics - function siftDown(sequence arr, integer s, integer last) - integer root = s - while root*2<=last do - integer child = root*2 - if child<last and arr[child]<arr[child+1] then - child += 1 - end if - if arr[root]>=arr[child] then exit end if - object tmp = arr[root] - arr[root] = arr[child] - arr[child] = tmp - root = child - end while - return arr - end function +function sift_down(sequence s, integer root, last) + while root*2<=last do + integer child = root*2 + if child=s[child] then exit end if + {s[root],s[child]} = extract(s,{child,root}) + root = child + end while + return s +end function - function heapify(sequence arr, integer count) - integer s = floor(count/2) - while s>0 do - arr = siftDown(arr,s,count) - s -= 1 - end while - return arr - end function +function heapify(sequence s, integer last) + for root=floor(last/2) to 1 by -1 do + s = sift_down(s,root,last) + end for + return s +end function - function heap_sort(sequence arr) - integer last = length(arr) - arr = heapify(arr,last) - while last>1 do - object tmp = arr[1] - arr[1] = arr[last] - arr[last] = tmp - last -= 1 - arr = siftDown(arr,1,last) - end while - return arr - end function +function heap_sort(sequence s) + integer last = length(s) + s = heapify(s,last) + while last>1 do + {s[1],s[last]} = extract(s,{last,1}) + last -= 1 + s = sift_down(s,1,last) + end while + return s +end function - ?heap_sort({5,"oranges","and",3,"apples"}) - - function insertion_sort(sequence s) - object temp - integer j - for i=2 to length(s) do - temp = s[i] - j = i-1 - while j>=1 and s[j]>temp do - s[j+1] = s[j] - j -= 1 - end while - s[j+1] = temp - end for - return s - end function +with javascript_semantics +function insertion_sort(sequence s) + s = deep_copy(s) + for i=2 to length(s) do + object temp = s[i] + integer j = i-1 + while j>=1 and s[j]>temp do + s[j+1] = s[j] + j -= 1 + end while + s[j+1] = temp + end for + return s +end function - constant s = {4, 15, "delta", 2, -31, 0, "alpha", 19, "gamma", 2, 13, "beta", 782, 1} - - puts(1,"Before: ") ?s - puts(1,"After: ") ?insertion_sort(s) - - with javascript_semantics +with javascript_semantics +function merge(sequence left, right) + sequence result = {} + integer ldx = 1, rdx = 1 + while length(left)>=ldx + and length(right)>=rdx do + if left[ldx]<=right[rdx] then + result = append(result, left[ldx]) + ldx += 1 + else + result = append(result, right[rdx]) + rdx += 1 + end if + end while + return result & left[ldx..$] & right[rdx..$] +end function - function merge(sequence left, sequence right) - sequence result = {} - while length(left)>0 and length(right)>0 do - if left[1]<=right[1] then - result = append(result, left[1]) - left = left[2..$] - else - result = append(result, right[1]) - right = right[2..$] - end if - end while - return result & left & right - end function +function mergesort(sequence m) + integer middle = floor(length(m)/2) + if middle=0 then return m end if + sequence left = mergesort(m[1..middle]), + right = mergesort(m[middle+1..$]) + return iff(left[$]<=right[1]?left & right: + iff(right[$]<=left[1]?right & left: + merge(left, right))) +end function - function mergesort(sequence m) - if length(m)<=1 then return m end if - integer middle = floor(length(m)/2) - sequence left = mergesort(m[1..middle]), - right = mergesort(m[middle+1..$]) - if left[$]<=right[1] then - return left & right - elsif right[$]<=left[1] then - return right & left - end if - return merge(left, right) - end function - - constant s = shuffle(tagset(10)) - ? s - ? mergesort(deep_copy(s)) - - with javascript_semantics +with javascript_semantics - function pancake_sort(sequence s) - s = deep_copy(s) - for i=length(s) to 2 by -1 do - integer m = largest(s[1..i],true) - if m<i then - if m>1 then - s[1..m] = reverse(s[1..m]) - end if - s[1..i] = reverse(s[1..i]) - end if - end for - return s - end function +function pancake_sort(sequence s) + s = deep_copy(s) + for i=length(s) to 2 by -1 do + integer m = largest(s[1..i],true) + if m1 then + s[1..m] = reverse(s[1..m]) + end if + s[1..i] = reverse(s[1..i]) + end if + end for + return s +end function - constant s = shuffle(tagset(10)) - ? s - ? pancake_sort(s) - - with javascript_semantics +with javascript_semantics - function patience_sort(sequence s) - -- create list of sorted lists - sequence piles = {} - for i=1 to length(s) do - object n = s[i] - for p=1 to length(piles)+1 do - if p>length(piles) then - piles = append(piles,{n}) - elsif n>=piles[p][$] then - piles[p] = append(deep_copy(piles[p]),n) - exit - end if - end for - end for - -- merge sort the piles - sequence res = "" - while length(piles) do - integer idx = smallest(piles,return_index:=true) - res = append(res,piles[idx][1]) - if length(piles[idx])=1 then - piles[idx..idx] = {} - else - piles[idx] = piles[idx][2..$] - end if - end while - return res - end function +function patience_sort(sequence s) + -- create list of sorted lists + sequence piles = {} + for i,n in s do + for p=length(piles) to 0 by -1 do + if p=0 then + piles = append(piles,{n}) + elsif n>=piles[p][$] then + piles[p] = append(piles[p],n) + exit + end if + end for + end for + -- merge sort the piles + sequence res = "" + while length(piles)>1 do + integer idx = smallest(piles,return_index:=true) + res = append(res,piles[idx][1]) + if length(piles[idx])=1 then + piles[idx..idx] = {} + else + piles[idx] = piles[idx][2..$] + end if + end while + if length(piles)=1 then res &= piles[1] end if + return res +end function - constant tests = {{4,65,2,-31,0,99,83,782,1}, - {0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15}, - "nonzerosum", - {"dog", "cow", "cat", "ape", "ant", "man", "pig", "ass", "gnu"}} +constant tests = {{4,65,2,-31,0,99,83,782,1}, + {0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15}, + "nonzerosum", + {"dog", "cow", "cat", "ape", "ant", "man", "pig", "ass", "gnu"}} - for i=1 to length(tests) do - pp(patience_sort(tests[i]),{pp_IntCh,false}) - end for -'sorted + pi.pu+=1 /* bump the thingy index in pile pu */ + Call show 'nachher' + End +Say 'Output:' strip(sorted) /*stick a fork in It, we're all Done. */ + +show: + Call debug arg(1) + Call debug '------------------------>'sorted + Do o=1 To np + Call debug o pi.o pile.o + End + Return +debug: + If debug Then Say arg(1) + Return diff --git a/Task/Sorting-algorithms-Patience-sort/RISC-V-Assembly/sorting-algorithms-patience-sort.asm b/Task/Sorting-algorithms-Patience-sort/RISC-V-Assembly/sorting-algorithms-patience-sort.asm new file mode 100644 index 0000000000..e1659efad1 --- /dev/null +++ b/Task/Sorting-algorithms-Patience-sort/RISC-V-Assembly/sorting-algorithms-patience-sort.asm @@ -0,0 +1,400 @@ +# riscv assembly raspberry pico2 rp2350 +# program patiencesort.s +# connexion putty com3 +/*********************************************/ +/* CONSTANTES */ +/********************************************/ +/* for this file see risc-v task include a file */ +.include "../../constantesRiscv.inc" +.equ HEAPSIZE, 50000 +/****************************************************/ +/* MACROS */ +/****************************************************/ +#.include "../ficmacrosriscv.inc" # for debugging only + +/*******************************************/ +/* Structures */ +/********************************************/ +/* structure Doublylinkedlist*/ + .struct 0 +dllist_head: # head node + .struct dllist_head + 4 +dllist_tail: # tail node + .struct dllist_tail + 4 +dllist_end: +/* structure Node Doublylinked List*/ + .struct 0 +NDlist_next: # next element + .struct NDlist_next + 4 +NDlist_prev: # previous element + .struct NDlist_prev + 4 +NDlist_value: # element value or key + .struct NDlist_value + 4 +NDlist_end: + +/*******************************************/ +/* INITIALED DATAS */ +/*******************************************/ +.data +szMessStart: .asciz "Program riscv start.\r\n" +szMessEnd: .asciz "\nProgram end OK.\r\n" +szCariageReturn: .asciz "\r\n" + +szMessSortOk: .asciz "Area sorted.\n" +szMessSortNok: .asciz "Area not sorted !!!!!.\n" +szLibSort: .asciz "\nAfter sort\n" +szSpace: .asciz " " + +.align 2 +tabNumber: .int 5,7,8,3,2,9,1,4,6 +#tabNumber: .int 9,8,7,6,5,4,3,2,1 +.equ NBTABNUMBER1, . - tabNumber +.equ NBTABNUMBER, NBTABNUMBER1 / 4 # compute items number +ptHeapReserve: .int heapReserve +/*******************************************/ +/* UNINITIALED DATA */ +/*******************************************/ +.bss +.align 2 +sConvArea: .skip 24 + +heapReserve: .skip HEAPSIZE +/********************************...-..--*****/ +/* SECTION CODE */ +/**********************************************/ +.text +.global main + +main: + call stdio_init_all # général init +1: # start loop connexion + li a0,0 # raz argument register + call tud_cdc_n_connected # waiting for USB connection + beqz a0,1b # return code = zero ? + + la a0,szMessStart # message address + call writeString # display message + + la s0,tabNumber # number array address + li s1,0 + li s2,NBTABNUMBER +2: # item loop + sh2add t3,s1,s0 # compute item address + lw a0,(t3) + call displayResultD + add s1,s1,1 + blt s1,s2,2b + la a0,szCariageReturn + call writeString + mv a0,s0 # number array address + li a1,0 # first item + mv a2,s2 + call patienceSort # sort + mv a0,s0 # number array address + li a1,0 # first item + addi a2,s2,-1 # last item + call isSorted + + la a0,szLibSort + call writeString + + li s1,0 +3: # item loop + sh2add t3,s1,s0 # compute item address + lw a0,(t3) + call displayResultD + add s1,s1,1 + blt s1,s2,3b + la a0,szCariageReturn + call writeString + la a0,szMessEnd + call writeString + call getchar +100: # final loop + j 100b +/**********************************************/ +/* display Result décimal */ +/**********************************************/ +/* a0 value */ +.equ LGZONECONV, 20 +displayResultD: + addi sp, sp, -4 # reserve stack + sw ra, 0(sp) + la a1,sConvArea # conversion result address + call conversion10 # binary conversion + la a0,sConvArea # message address + call writeString # display message + la a0,szSpace + call writeString +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret + +/**********************************************/ +/* sort control */ +/**********************************************/ +/* a0 area address */ +/* a1 first element */ +/* a2 last element */ +.equ LGZONECONV, 20 +isSorted: + addi sp, sp, -4 # reserve stack + sw ra, 0(sp) + mv t0,a1 + sh2add t1,t0,a0 + lw t2,(t1) # load first element +1: + addi t0,t0,1 + ble t0,a2,2f # end indice ? + la a0,szMessSortOk + call writeString + li a0,1 # yes -> area is sorted + j 100f +2: + sh2add t1,t0,a0 + lw t3,(t1) # load next element + bge t3,t2,3f # >= ? + la a0,szMessSortNok + call writeString + li a0,0 # no -> area is not sorted + j 100f +3: + mv t2,t3 + j 1b +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret + +/******************************************************************/ +/* patience sort */ +/******************************************************************/ +/* a0 contains array address */ +/* a1 contains the first element */ +/* a2 contains the array size */ +patienceSort: + addi sp, sp, -48 # reserve stack + sw ra, 0(sp) # save registers + sw s0, 4(sp) + sw s1, 8(sp) + sw s2, 12(sp) + sw s3, 16(sp) + sw s4, 20(sp) + sw s5, 24(sp) + sw s6, 28(sp) + sw s7, 32(sp) + sw s8, 36(sp) + sw s9, 40(sp) + sw s10, 44(sp) + slli s0,a2,1 + slli s9,s0,3 + mv s2,a0 # save table address + mv s3,a2 # save array size + sub sp,sp,s9 # reserve on stacm + mv s10,sp + li s8,0 +1: + sh2add t0,s8,s10 + sw x0,(t0) # init piles area + addi s8,s8,1 # increment index + blt s8,s0,1b + li s8,0 # index value + li s1,0 # counter first pile +2: + sh2add t0,s8,s2 # compute array address + lw a1,(t0) # load value + sh3add a0,s1,s10 # stack address + lw t0,dllist_head(a0) + bnez t0,3f # empty stack + call insertHead # insert value a1 + blez a0,100f + j 5f + +3: + lw t5,dllist_head(a0) + lw t5,NDlist_value(t5) # load first list value + blt a1,t5,4f + call insertHead + blez a0,100f + j 5f +4: # value is smaller créate a new pile + addi s1,s1,1 + sh3add a0,s1,s10 # new stack address + call insertHead # insert value r1 + blez a0,100f +5: + addi s8,s8,1 # increment index value + blt s8,s3,2b # end ? no -> loop + li s7,0 # init index value table +6: + li s8,0 # stack index + li s5,1<<30 # minimum + +7: # search minimum + sh3add a0,s8,s10 # stack address + lw a0,dllist_head(a0) + beqz a0,8f # empty stack + call searchMinList + bge a0,s5,8f # compare min global + mv s5,a0 # smaller -> store new min + mv s4,a1 # and pointer to min + sh3add s6,s8,s10 # and head list +8: + addi s8,s8,1 # next stack + ble s8,s1,7b # end ? no -> loop + sh2add t0,s7,s2 + sw s5,(t0) # store min to table value + mv a0,s6 + mv a1,s4 + call suppressNode + addi s7,s7,1 + blt s7,s3,6b # end ? no -> loop +100: + add sp,sp,s9 # stack alignement + lw ra, 0(sp) + lw s0, 4(sp) + lw s1, 8(sp) + lw s2, 12(sp) + lw s3, 16(sp) + lw s4, 20(sp) + lw s5, 24(sp) + lw s6, 28(sp) + lw s7, 32(sp) + lw s8, 36(sp) + lw s9, 40(sp) + lw s10, 44(sp) + addi sp, sp, 48 + ret + +/**********************************************/ +/* create new double linked list */ +/**********************************************/ +/* a0 linked list address */ +newDList: # INFO: newDList + addi sp, sp, -4 + sw ra, 0(sp) + + sw x0,dllist_tail(a0) # raz pointer + sw x0,dllist_head(a0) # raz pointer + + lw ra, 0(sp) + addi sp, sp, 4 + ret +/**********************************************/ +/* insertion value in head */ +/**********************************************/ +/* a0 double linked list address */ +/* a1 contains the value of element */ +/* a0 returns address of element or - 1 if error */ +insertHead: # INFO: insertTail + addi sp, sp, -8 + sw ra, 0(sp) + sw s0, 4(sp) + mv s0,a0 # save address + mv a0,a1 # value + call createNode # create new node + blez a0,100f # error ? + + lw t0,dllist_head(s0) # load address first node + sw t0,NDlist_next(a0) # store in next pointer on new node + sw x0,NDlist_prev(a0) # store null on prev pointer + sw a0,dllist_head(s0) # store address new node on list head + beqz t0,1f # address last node is null ? + sw a0,NDlist_prev(t0) # no store address new node in next pointer + j 2f +1: + sw a0,dllist_tail(s0) # else store in head list +2: + +100: + lw ra, 0(sp) + lw s0, 4(sp) + addi sp, sp, 8 + ret +/**********************************************/ +/* search value minimum */ +/**********************************************/ +/* a0 contains the address of the list structure */ +/* a0 return min */ +/* a1 return node address */ +searchMinList: # INFO: searchMinList + addi sp, sp, -4 + sw ra, 0(sp) + mv t0,a0 + li t3,1<<30 + li a1,0 # init node address +1: + bnez t0,2f # equal zero ? + mv a0,t3 # yes -> end + j 100f +2: + lw t1,NDlist_value(t0) # load node value + bge t1,t3,3f # < ? + mv t3,t1 # yes -> min = new value + mv a1,t0 +3: + lw t0,NDlist_next(t0) # load address next node + j 1b # and loop + +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret +/**********************************************/ +/* create node on heap */ +/**********************************************/ +/* a0 value */ +/* a0 return node address or -1 if error */ +createNode: # INFO: createNode + addi sp, sp, -4 + sw ra, 0(sp) + la t0,ptHeapReserve + lw t1,(t0) # free heap address + addi t2,t1,NDlist_end # reserve area on heap + la t3,heapReserve + li t4,HEAPSIZE + add t3,t3,t4 + blt t2,t3,2f + li a0,-1 + j 100f +2: + sw t2,(t0) # save new value heap used + sw a0,NDlist_value(t1) # store value on heap + sw x0,NDlist_next(t1) # raz pointer next + sw x0,NDlist_prev(t1) # raz pointer previous + mv a0,t1 # return node address +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret +/**********************************************/ +/* suppress node on list */ +/**********************************************/ +/* a0 contains the address of the list structure */ +/* a1 contains the address to node to suppress */ +suppressNode: # INFO: suppressNode + addi sp, sp, -4 + sw ra, 0(sp) + lw t0,NDlist_next(a1) # load addresse next node + lw t1,NDlist_prev(a1) # load addresse prev node + beqz t1,1f + sw t0,NDlist_next(t1) + j 2f +1: + sw t1,NDlist_next(a0) +2: + beqz t0,3f + sw t1,NDlist_prev(t0) + j 100f +3: + sw t0,NDlist_prev(a0) +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret +/************************************/ +/* file include Fonctions */ +/***********************************/ +/* for this file see risc-v task include a file */ +.include "../../includeFunctions.s" diff --git a/Task/Sorting-algorithms-Patience-sort/Rust/sorting-algorithms-patience-sort.rs b/Task/Sorting-algorithms-Patience-sort/Rust/sorting-algorithms-patience-sort.rs new file mode 100644 index 0000000000..c4f1dbc87a --- /dev/null +++ b/Task/Sorting-algorithms-Patience-sort/Rust/sorting-algorithms-patience-sort.rs @@ -0,0 +1,95 @@ +use std::cmp::Ordering; +use std::collections::BinaryHeap; + +// We define a custom Pile struct instead of using Stack +#[derive(Clone, Eq, PartialEq)] +struct Pile { + values: Vec, +} + +impl Pile { + fn new(value: T) -> Self { + let mut values = Vec::new(); + values.push(value); + Pile { values } + } + + fn push(&mut self, value: T) { + self.values.push(value); + } + + fn pop(&mut self) -> Option { + self.values.pop() + } + + fn top(&self) -> Option<&T> { + self.values.last() + } + + fn is_empty(&self) -> bool { + self.values.is_empty() + } +} + +// For binary heap ordering (min-heap) +impl Ord for Pile { + fn cmp(&self, other: &Self) -> Ordering { + // Reverse the ordering for min-heap + other.top().cmp(&self.top()) + } +} + +impl PartialOrd for Pile { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +fn patience_sort(slice: &mut [T]) { + let mut piles: Vec> = Vec::new(); + + // Sort into piles + for item in slice.iter().cloned() { + // Find the pile to insert into + let idx = match piles.binary_search_by(|pile| { + if let Some(top) = pile.top() { + top.cmp(&item) + } else { + Ordering::Greater // Should not happen + } + }) { + Ok(idx) => idx, // Found a pile with the same top value + Err(idx) => idx, // Position where we should insert new pile + }; + + if idx < piles.len() { + piles[idx].push(item); + } else { + piles.push(Pile::new(item)); + } + } + + // Convert to BinaryHeap for efficient merging + let mut heap = BinaryHeap::from(piles); + + // Merge piles + for item_slot in slice.iter_mut() { + if let Some(mut smallest_pile) = heap.pop() { + if let Some(top) = smallest_pile.pop() { + *item_slot = top; + + if !smallest_pile.is_empty() { + heap.push(smallest_pile); + } + } + } + } + + assert!(heap.is_empty()); +} + +fn main() { + let mut a = [4, 65, 2, -31, 0, 99, 83, 782, 1]; + patience_sort(&mut a); + println!("{:?}", a); +} diff --git a/Task/Sorting-algorithms-Patience-sort/Scheme/sorting-algorithms-patience-sort.ss b/Task/Sorting-algorithms-Patience-sort/Scheme/sorting-algorithms-patience-sort.scm similarity index 100% rename from Task/Sorting-algorithms-Patience-sort/Scheme/sorting-algorithms-patience-sort.ss rename to Task/Sorting-algorithms-Patience-sort/Scheme/sorting-algorithms-patience-sort.scm diff --git a/Task/Sorting-algorithms-Patience-sort/XPL0/sorting-algorithms-patience-sort.xpl0 b/Task/Sorting-algorithms-Patience-sort/XPL0/sorting-algorithms-patience-sort.xpl0 new file mode 100644 index 0000000000..9cf710d269 --- /dev/null +++ b/Task/Sorting-algorithms-Patience-sort/XPL0/sorting-algorithms-patience-sort.xpl0 @@ -0,0 +1,33 @@ +def N = 10, Inf = -1>>1; \number of cards/items in Array +int Array, Pile(N, N+1); \N piles with maximum size of N+1 +int Inx(N+1); \index into each Pile to topmost card/item +int I, J, Card, Min, IMin; +[Array:= [4, 65, 2, -31, 0, 99, 83, 782, 1, 0]; +for I:= 0 to N-1 do Pile(I, 0):= Inf; +for I:= 0 to N-1 do Inx(I):= 0; +\Step 1: Put cards into piles +for I:= 0 to N-1 do \for each card in array + [Card:= Array(I); + J:= 0; \for each pile + loop [if Pile(J, Inx(J)) >= Card then + [Inx(J):= Inx(J)+1; \put card onto pile + Pile(J, Inx(J)):= Card; + quit; \next card + ]; + J:= J+1; \next pile + ]; + ]; +\Step 2: N-way merge sort +loop [Min:= Inf; \search piles for smallest card + for I:= 0 to N-1 do \for each pile + [Card:= Pile(I, Inx(I)); \get top card from pile + if Card <= Min then + [Min:= Card; IMin:= I]; + ]; + if Min = Inf then quit; + Card:= Pile(IMin, Inx(IMin)); + IntOut(0, Card); Text(0, " "); \show smallest card + Inx(IMin):= Inx(IMin)-1; \remove smallest card + ]; +CrLf(0); +] diff --git a/Task/Sorting-algorithms-Patience-sort/Zig/sorting-algorithms-patience-sort.zig b/Task/Sorting-algorithms-Patience-sort/Zig/sorting-algorithms-patience-sort.zig new file mode 100644 index 0000000000..e53cf138df --- /dev/null +++ b/Task/Sorting-algorithms-Patience-sort/Zig/sorting-algorithms-patience-sort.zig @@ -0,0 +1,138 @@ +const std = @import("std"); +const Allocator = std.mem.Allocator; +const ArrayList = std.ArrayList; +const PriorityQueue = std.PriorityQueue; + +// Pile structure to represent a stack of items +fn Pile(comptime T: type) type { + return struct { + values: ArrayList(T), + + const Self = @This(); + + fn init(allocator: Allocator) Self { + return Self{ + .values = ArrayList(T).init(allocator), + }; + } + + fn deinit(self: *Self) void { + self.values.deinit(); + } + + fn push(self: *Self, value: T) !void { + try self.values.append(value); + } + + fn pop(self: *Self) ?T { + if (self.values.items.len == 0) return null; + return self.values.pop(); + } + + fn top(self: *const Self) ?T { + if (self.values.items.len == 0) return null; + return self.values.items[self.values.items.len - 1]; + } + + fn isEmpty(self: *const Self) bool { + return self.values.items.len == 0; + } + }; +} + +// Compare function for priority queue (min-heap) +fn pileGreaterThan(comptime T: type) type { + return struct { + pub fn compare(context: void, a: *const Pile(T), b: *const Pile(T)) std.math.Order { + _ = context; + const a_top = a.top() orelse return .lt; + const b_top = b.top() orelse return .gt; + return if (a_top > b_top) .lt else if (a_top < b_top) .gt else .eq; + } + }; +} + +// Patience sort implementation +fn patienceSort(comptime T: type, allocator: Allocator, slice: []T) !void { + const PileT = Pile(T); + var piles = ArrayList(*PileT).init(allocator); + defer { + // Clean up all piles regardless of how we exit the function + for (piles.items) |pile| { + pile.deinit(); + allocator.destroy(pile); + } + piles.deinit(); + } + + // Sort into piles + for (slice) |item| { + // Try to find an existing pile to add to + var added = false; + for (piles.items) |pile| { + if (pile.top()) |top| { + if (top > item) { + try pile.push(item); + added = true; + break; + } + } + } + + // If no suitable pile found, create a new one + if (!added) { + var new_pile = try allocator.create(PileT); + errdefer allocator.destroy(new_pile); + + new_pile.* = PileT.init(allocator); + errdefer new_pile.deinit(); + + try new_pile.push(item); + try piles.append(new_pile); + } + } + + // Create a priority queue for efficient merging + var queue = PriorityQueue(*PileT, void, pileGreaterThan(T).compare).init(allocator, {}); + defer queue.deinit(); + + // Add all piles to the priority queue + for (piles.items) |pile| { + try queue.add(pile); + } + + // Merge piles back into the original slice + var i: usize = 0; + while (queue.count() > 0) { + const smallest_pile = queue.remove(); + if (smallest_pile.pop()) |value| { + slice[i] = value; + i += 1; + + if (!smallest_pile.isEmpty()) { + try queue.add(smallest_pile); + } + } + } + + std.debug.assert(i == slice.len); +} + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + const allocator = gpa.allocator(); + + var a = [_]i32{ 4, 65, 2, -31, 0, 99, 83, 782, 1 }; + try patienceSort(i32, allocator, &a); + + const stdout = std.io.getStdOut().writer(); + try stdout.print("Sorted array: ", .{}); + for (a, 0..) |value, i| { + try stdout.print("{}", .{value}); + if (i < a.len - 1) { + try stdout.print(", ", .{}); + } + } + try stdout.print("\n", .{}); +} diff --git a/Task/Sorting-algorithms-Permutation-sort/Ada/sorting-algorithms-permutation-sort.adb b/Task/Sorting-algorithms-Permutation-sort/Ada/sorting-algorithms-permutation-sort.adb new file mode 100644 index 0000000000..bb2a8889c7 --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/Ada/sorting-algorithms-permutation-sort.adb @@ -0,0 +1,39 @@ +-- Permutation sort +-- J. Carter 2024 Jun +-- Uses the PragmAda Reusable Components (https://github.com/jrcarter/PragmARC) + +with Ada.Text_IO; +with PragmARC.Permutations; + +procedure Slow_Sort is + package Char_Perms is new PragmARC.Permutations (Element => Character); + + procedure Put (Item : in Char_Perms.Sequence); + -- Outputs all the Characters in Item to standard output, followed by a line terminator + + procedure Process (Seq : in Char_Perms.Sequence; Stop : in out Boolean); + -- If Seq is sorted, outputs it and sets Stop to True + + procedure Put (Item : in Char_Perms.Sequence) is + -- Empty + begin -- Put + All_Chars : for C of Item loop + Ada.Text_IO.Put (Item => C); + end loop All_Chars; + + Ada.Text_IO.New_Line; + end Put; + + procedure Process (Seq : in Char_Perms.Sequence; Stop : in out Boolean) is + -- Empty + begin -- Process + if (for all J in 1 .. Seq'Last - 1 => Seq (J) <= Seq (J + 1) ) then -- Sorted + Put (Item => Seq); + Stop := True; + end if; + end Process; + + Test : constant Char_Perms.Sequence := "kjihgfedcba"; +begin -- Slow_Sort + Char_Perms.Generate (Initial => Test, Process => Process'Access); +end Slow_Sort; diff --git a/Task/Sorting-algorithms-Permutation-sort/Crystal/sorting-algorithms-permutation-sort.crystal b/Task/Sorting-algorithms-Permutation-sort/Crystal/sorting-algorithms-permutation-sort.cr similarity index 100% rename from Task/Sorting-algorithms-Permutation-sort/Crystal/sorting-algorithms-permutation-sort.crystal rename to Task/Sorting-algorithms-Permutation-sort/Crystal/sorting-algorithms-permutation-sort.cr diff --git a/Task/Sorting-algorithms-Permutation-sort/EMal/sorting-algorithms-permutation-sort.emal b/Task/Sorting-algorithms-Permutation-sort/EMal/sorting-algorithms-permutation-sort.emal index 051eeeb95b..302d637914 100644 --- a/Task/Sorting-algorithms-Permutation-sort/EMal/sorting-algorithms-permutation-sort.emal +++ b/Task/Sorting-algorithms-Permutation-sort/EMal/sorting-algorithms-permutation-sort.emal @@ -1,29 +1,29 @@ type PermutationSort -fun isSorted = logic by List a - for int i = 1; i < a.length; ++i +fun isSorted ← logic by List a + for int i ← 1; i < a.length; ++i if a[i - 1] > a[i] do return false end end return true end -fun permute = void by List a, int n, List lists - if n == 1 - List b = int[] - for int i = 0; i < a.length; ++i +fun permute ← void by List a, int n, List lists + if n æ 1 + List b ← int[] + for int i ← 0; i < a.length; ++i b.append(a[i]) end lists.append(b) return end - int i = 0 + int i ← 0 while i < n a.swap(i, n - 1) permute(a, n - 1, lists) a.swap(i, n - 1) - i = i + 1 + i ← i + 1 end end -fun sort = List by List a - List lists = List[] +fun sort ← List by List a + List lists ← List[] permute(a, a.length, lists) for each List list in lists if isSorted(list) do return list end @@ -31,7 +31,7 @@ fun sort = List by List a return a end type Main -List a = int[3,2,1,8,9,4,6] +List a ← int[3,2,1,8,9,4,6] writeLine("Unsorted: " + a) -a = PermutationSort.sort(a) +a ← PermutationSort.sort(a) writeLine(" Sorted: " + a) diff --git a/Task/Sorting-algorithms-Permutation-sort/EasyLang/sorting-algorithms-permutation-sort.easy b/Task/Sorting-algorithms-Permutation-sort/EasyLang/sorting-algorithms-permutation-sort.easy new file mode 100644 index 0000000000..eedd40067d --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/EasyLang/sorting-algorithms-permutation-sort.easy @@ -0,0 +1,38 @@ +global perm[] . +proc nextperm &a[] &k . + n = len perm[] + k = n - 1 + while k >= 1 and perm[k + 1] <= perm[k] : k -= 1 + if k = 0 : return + l = n + while perm[l] <= perm[k] : l -= 1 + swap perm[l] perm[k] + swap a[l] a[k] + k += 1 + while k < n + swap perm[k] perm[n] + swap a[k] a[n] + k += 1 + n -= 1 + . +. +proc perminit &a[] . + for i to len a[] : perm[] &= i +. +proc permsort &a[] . + perminit a[] + repeat + for i = 2 to len a[] + if a[i - 1] > a[i] : break 1 + . + until i > len a[] + nextperm a[] more + if more = 0 + print "error" + break 1 + . + . +. +arr[] = [ 7 6 5 9 8 4 3 1 2 0 ] +permsort arr[] +print arr[] diff --git a/Task/Sorting-algorithms-Permutation-sort/Elixir/sorting-algorithms-permutation-sort.elixir b/Task/Sorting-algorithms-Permutation-sort/Elixir/sorting-algorithms-permutation-sort.ex similarity index 100% rename from Task/Sorting-algorithms-Permutation-sort/Elixir/sorting-algorithms-permutation-sort.elixir rename to Task/Sorting-algorithms-Permutation-sort/Elixir/sorting-algorithms-permutation-sort.ex diff --git a/Task/Sorting-algorithms-Permutation-sort/Julia/sorting-algorithms-permutation-sort.julia b/Task/Sorting-algorithms-Permutation-sort/Julia/sorting-algorithms-permutation-sort.jl similarity index 100% rename from Task/Sorting-algorithms-Permutation-sort/Julia/sorting-algorithms-permutation-sort.julia rename to Task/Sorting-algorithms-Permutation-sort/Julia/sorting-algorithms-permutation-sort.jl diff --git a/Task/Sorting-algorithms-Permutation-sort/Kotlin/sorting-algorithms-permutation-sort.kotlin b/Task/Sorting-algorithms-Permutation-sort/Kotlin/sorting-algorithms-permutation-sort.kts similarity index 100% rename from Task/Sorting-algorithms-Permutation-sort/Kotlin/sorting-algorithms-permutation-sort.kotlin rename to Task/Sorting-algorithms-Permutation-sort/Kotlin/sorting-algorithms-permutation-sort.kts diff --git a/Task/Sorting-algorithms-Permutation-sort/NewLISP/sorting-algorithms-permutation-sort.l b/Task/Sorting-algorithms-Permutation-sort/NewLISP/sorting-algorithms-permutation-sort.l new file mode 100644 index 0000000000..50957da8c7 --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/NewLISP/sorting-algorithms-permutation-sort.l @@ -0,0 +1,32 @@ +;; +;; Before the permutation is completely formed, +;; check for validity. +;; +;; n at a time. +(define (permute n__permute seq__permute func__permute + (chk__permute or) (built__permute '())) + (when (or (null? built__permute) (chk__permute built__permute)) + (if (or (zero? n__permute) (null? seq__permute)) + (func__permute built__permute) + (dotimes (i__permute (length seq__permute)) + (unless (zero? i__permute) (rotate seq__permute -1)) + (permute (- n__permute 1) + (rest seq__permute) + func__permute + chk__permute + (append built__permute (0 1 seq__permute))))))) + +(time +(permute -1 '(4 6 8 0 5 9 2 -1 7 1 3) println (fn(xs) (= xs (sort (copy xs))))) +) + +(-1 0 1 2 3 4 5 6 7 8 9) +78.125 [ milliseconds ] + + +(time +(permute -1 '(4 6 8 0 5 9 2 7 1 3) println (fn(xs) (= xs (sort (copy xs))))) +) + +(0 1 2 3 4 5 6 7 8 9) +15.625 [ milliseconds ] diff --git a/Task/Sorting-algorithms-Permutation-sort/OCaml/sorting-algorithms-permutation-sort.ocaml b/Task/Sorting-algorithms-Permutation-sort/OCaml/sorting-algorithms-permutation-sort.ml similarity index 100% rename from Task/Sorting-algorithms-Permutation-sort/OCaml/sorting-algorithms-permutation-sort.ocaml rename to Task/Sorting-algorithms-Permutation-sort/OCaml/sorting-algorithms-permutation-sort.ml diff --git a/Task/Sorting-algorithms-Permutation-sort/Phix/sorting-algorithms-permutation-sort.phix b/Task/Sorting-algorithms-Permutation-sort/Phix/sorting-algorithms-permutation-sort.phix index d8c36bc1de..42ce1613b8 100644 --- a/Task/Sorting-algorithms-Permutation-sort/Phix/sorting-algorithms-permutation-sort.phix +++ b/Task/Sorting-algorithms-Permutation-sort/Phix/sorting-algorithms-permutation-sort.phix @@ -1,20 +1,18 @@ -(phixonline)--> - with javascript_semantics +with javascript_semantics - function inOrder(sequence s) - for i=2 to length(s) do - if s[i]<s[i-1] then return false end if - end for - return true - end function +function inOrder(sequence s) + for i=2 to length(s) do + if s[i]function
    permutationSort(sequence s) - for n=1 to factorial(length(s)) do - sequence perm = permute(n,s) - if inOrder(perm) then return perm end if - end for - ?9/0 -- should never happen - end function +function permutationSort(sequence s) + for n=1 to factorial(length(s)) do + sequence perm = permute(n,s) + if inOrder(perm) then return perm end if + end for + ?9/0 -- should never happen +end function - ?permutationSort({"dog",0,15.545,{"cat","pile","abcde",1},"cat"}) - n ) -[ tuck take join swap put ] is append ( x s --> ) - [ dup size 2 < if done [] less put [] same put @@ -15,8 +13,8 @@ behead swap witheach [ 2dup swap <=> [ table less same more ] - append ] - same append + gather ] + same gather less take recurse same take join more take recurse join ] is quicksort ( [ --> [ ) diff --git a/Task/Sorting-algorithms-Quicksort/BASIC/sorting-algorithms-quicksort.basic b/Task/Sorting-algorithms-Quicksort/QuickBASIC/sorting-algorithms-quicksort.basic similarity index 100% rename from Task/Sorting-algorithms-Quicksort/BASIC/sorting-algorithms-quicksort.basic rename to Task/Sorting-algorithms-Quicksort/QuickBASIC/sorting-algorithms-quicksort.basic diff --git a/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-1.rexx b/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-1.rexx index ffcaa1f7c5..609b0364fb 100644 --- a/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-1.rexx +++ b/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-1.rexx @@ -1,107 +1,87 @@ -/*REXX program sorts a stemmed array using the quicksort algorithm. */ -call gen@ /*generate the elements for the array. */ -call show@ 'before sort' /*show the before array elements. */ -call qSort # /*invoke the quicksort subroutine. */ -call show@ ' after sort' /*show the after array elements. */ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -inOrder: parse arg n; do j=1 for n-1; k= j+1; if @.j>@.k then return 0; end; return 1 -/*──────────────────────────────────────────────────────────────────────────────────────*/ -qSort: procedure expose @.; a.1=1; parse arg b.1; $= 1 /*access @.; get @. size; pivot.*/ - if inOrder(b.1) then return /*Array already in order? Return*/ - do while $\==0; L= a.$; t= b.$; $= $ - 1; if t<2 then iterate - H= L + t - 1; ?= L + t % 2 - if @.H<@.L then if @.?<@.H then do; p= @.H; @.H= @.L; end - else if @.?>@.L then p= @.L - else do; p= @.?; @.?= @.L; end - else if @.?<@.L then p=@.L - else if @.?>@.H then do; p= @.H; @.H= @.L; end - else do; p= @.?; @.?= @.L; end - j= L+1; k= h - do forever - do j=j while j<=k & @.j<=p; end /*a teeny─tiny loop.*/ - do k=k by -1 while j< k & @.k>=p; end /*another " " */ - if j>=k then leave /*segment finished? */ - _= @.j; @.j= @.k; @.k= _ /*swap J&K elements.*/ - end /*forever*/ - $= $ + 1 - k= j - 1; @.L= @.k; @.k= p - if j<=? then do; a.$= j; b.$= H-j+1; $= $+1; a.$= L; b.$= k-L; end - else do; a.$= L; b.$= k-L; $= $+1; a.$= j; b.$= H-j+1; end - end /*while $¬==0*/ - return -/*──────────────────────────────────────────────────────────────────────────────────────*/ -show@: w= length(#); do j=1 for #; say 'element' right(j,w) arg(1)":" @.j; end - say copies('▒', maxL + w + 22) /*display a separator (between outputs)*/ - return -/*──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/ -gen@: @.=; maxL=0 /*assign a default value for the array.*/ - @.1 = " Rivers that form part of a (USA) state's border " /*this value is adjusted later to include a prefix & suffix.*/ - @.2 = '=' /*this value is expanded later. */ - @.3 = "Perdido River Alabama, Florida" - @.4 = "Chattahoochee River Alabama, Georgia" - @.5 = "Tennessee River Alabama, Kentucky, Mississippi, Tennessee" - @.6 = "Colorado River Arizona, California, Nevada, Baja California (Mexico)" - @.7 = "Mississippi River Arkansas, Illinois, Iowa, Kentucky, Minnesota, Mississippi, Missouri, Tennessee, Louisiana, Wisconsin" - @.8 = "St. Francis River Arkansas, Missouri" - @.9 = "Poteau River Arkansas, Oklahoma" - @.10 = "Arkansas River Arkansas, Oklahoma" - @.11 = "Red River (Mississippi watershed) Arkansas, Oklahoma, Texas" - @.12 = "Byram River Connecticut, New York" - @.13 = "Pawcatuck River Connecticut, Rhode Island and Providence Plantations" - @.14 = "Delaware River Delaware, New Jersey, New York, Pennsylvania" - @.15 = "Potomac River District of Columbia, Maryland, Virginia, West Virginia" - @.16 = "St. Marys River Florida, Georgia" - @.17 = "Chattooga River Georgia, South Carolina" - @.18 = "Tugaloo River Georgia, South Carolina" - @.19 = "Savannah River Georgia, South Carolina" - @.20 = "Snake River Idaho, Oregon, Washington" - @.21 = "Wabash River Illinois, Indiana" - @.22 = "Ohio River Illinois, Indiana, Kentucky, Ohio, West Virginia" - @.23 = "Great Miami River (mouth only) Indiana, Ohio" - @.24 = "Des Moines River Iowa, Missouri" - @.25 = "Big Sioux River Iowa, South Dakota" - @.26 = "Missouri River Kansas, Iowa, Missouri, Nebraska, South Dakota" - @.27 = "Tug Fork River Kentucky, Virginia, West Virginia" - @.28 = "Big Sandy River Kentucky, West Virginia" - @.29 = "Pearl River Louisiana, Mississippi" - @.30 = "Sabine River Louisiana, Texas" - @.31 = "Monument Creek Maine, New Brunswick (Canada)" - @.32 = "St. Croix River Maine, New Brunswick (Canada)" - @.33 = "Piscataqua River Maine, New Hampshire" - @.34 = "St. Francis River Maine, Quebec (Canada)" - @.35 = "St. John River Maine, Quebec (Canada)" - @.36 = "Pocomoke River Maryland, Virginia" - @.37 = "Palmer River Massachusetts, Rhode Island and Providence Plantations" - @.38 = "Runnins River Massachusetts, Rhode Island and Providence Plantations" - @.39 = "Montreal River Michigan (upper peninsula), Wisconsin" - @.40 = "Detroit River Michigan, Ontario (Canada)" - @.41 = "St. Clair River Michigan, Ontario (Canada)" - @.42 = "St. Marys River Michigan, Ontario (Canada)" - @.43 = "Brule River Michigan, Wisconsin" - @.44 = "Menominee River Michigan, Wisconsin" - @.45 = "Red River of the North Minnesota, North Dakota" - @.46 = "Bois de Sioux River Minnesota, North Dakota, South Dakota" - @.47 = "Pigeon River Minnesota, Ontario (Canada)" - @.48 = "Rainy River Minnesota, Ontario (Canada)" - @.49 = "St. Croix River Minnesota, Wisconsin" - @.50 = "St. Louis River Minnesota, Wisconsin" - @.51 = "Halls Stream New Hampshire, Canada" - @.52 = "Salmon Falls River New Hampshire, Maine" - @.53 = "Connecticut River New Hampshire, Vermont" - @.54 = "Arthur Kill New Jersey, New York (tidal strait)" - @.55 = "Kill Van Kull New Jersey, New York (tidal strait)" - @.56 = "Hudson River (lower part only) New Jersey, New York" - @.57 = "Rio Grande New Mexico, Texas, Tamaulipas (Mexico), Nuevo Leon (Mexico), Coahuila de Zaragoza (Mexico), Chihuahua (Mexico)" - @.58 = "Niagara River New York, Ontario (Canada)" - @.59 = "St. Lawrence River New York, Ontario (Canada)" - @.60 = "Poultney River New York, Vermont" - @.61 = "Catawba River North Carolina, South Carolina" - @.62 = "Blackwater River North Carolina, Virginia" - @.63 = "Columbia River Oregon, Washington" - do #=1 until @.#=='' /*find how many entries in array, and */ - maxL=max(maxL, length(@.#)) /* also find the maximum width entry.*/ - end /*#*/; #= #-1 /*adjust the highest element number. */ - @.1= center(@.1, maxL, '-') /* " " header information. */ - @.2= copies(@.2, maxL) /* " " " separator. */ - return +/*REXX*/ + a = '4 65 2 -31 0 99 83 782 1' + do i = 1 to words(a) + queue word(a, i) + end + call quickSort + parse pull item + do queued() + call charout ,item', ' + parse pull item + end + say item + exit + +quickSort: procedure +/* In classic Rexx, arguments are passed by value, not by reference so stems + cannot be passed as arguments nor used as return values. Putting their + contents on the external data queue is a way to bypass this issue. */ + + /* construct the input stem */ + arr.0 = queued() + do i = 1 to arr.0 + parse pull arr.i + end + less.0 = 0 + pivotList.0 = 0 + more.0 = 0 + if arr.0 <= 1 then do + if arr.0 = 1 then + queue arr.1 + return + end + else do + pivot = arr.1 + do i = 1 to arr.0 + item = arr.i + select + when item < pivot then do + j = less.0 + 1 + less.j = item + less.0 = j + end + when item > pivot then do + j = more.0 + 1 + more.j = item + more.0 = j + end + otherwise + j = pivotList.0 + 1 + pivotList.j = item + pivotList.0 = j + end + end + end + /* recursive call to sort the less. stem */ + do i = 1 to less.0 + queue less.i + end + if queued() > 0 then do + call quickSort + less.0 = queued() + do i = 1 to less.0 + parse pull less.i + end + end + /* recursive call to sort the more. stem */ + do i = 1 to more.0 + queue more.i + end + if queued() > 0 then do + call quickSort + more.0 = queued() + do i = 1 to more.0 + parse pull more.i + end + end + /* put the contents of all 3 stems on the queue in order */ + do i = 1 to less.0 + queue less.i + end + do i = 1 to pivotList.0 + queue pivotList.i + end + do i = 1 to more.0 + queue more.i + end + return diff --git a/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-2.rexx b/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-2.rexx index 609b0364fb..5b58ec3e8d 100644 --- a/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-2.rexx +++ b/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-2.rexx @@ -1,87 +1,24 @@ -/*REXX*/ - a = '4 65 2 -31 0 99 83 782 1' - do i = 1 to words(a) - queue word(a, i) - end - call quickSort - parse pull item - do queued() - call charout ,item', ' - parse pull item - end - say item - exit - -quickSort: procedure -/* In classic Rexx, arguments are passed by value, not by reference so stems - cannot be passed as arguments nor used as return values. Putting their - contents on the external data queue is a way to bypass this issue. */ - - /* construct the input stem */ - arr.0 = queued() - do i = 1 to arr.0 - parse pull arr.i - end - less.0 = 0 - pivotList.0 = 0 - more.0 = 0 - if arr.0 <= 1 then do - if arr.0 = 1 then - queue arr.1 - return - end - else do - pivot = arr.1 - do i = 1 to arr.0 - item = arr.i - select - when item < pivot then do - j = less.0 + 1 - less.j = item - less.0 = j - end - when item > pivot then do - j = more.0 + 1 - more.j = item - more.0 = j - end - otherwise - j = pivotList.0 + 1 - pivotList.j = item - pivotList.0 = j - end - end - end - /* recursive call to sort the less. stem */ - do i = 1 to less.0 - queue less.i - end - if queued() > 0 then do - call quickSort - less.0 = queued() - do i = 1 to less.0 - parse pull less.i - end - end - /* recursive call to sort the more. stem */ - do i = 1 to more.0 - queue more.i - end - if queued() > 0 then do - call quickSort - more.0 = queued() - do i = 1 to more.0 - parse pull more.i - end - end - /* put the contents of all 3 stems on the queue in order */ - do i = 1 to less.0 - queue less.i - end - do i = 1 to pivotList.0 - queue pivotList.i - end - do i = 1 to more.0 - queue more.i - end - return +Elegant: +procedure expose stem. +push 1 stem.0 +do while queued() > 0 + pull l r + if l < r then do + m = (l+r)%2; p = stem.m; i = l-1; j = r+1 + do forever + do until stem.j <= p + j = j-1 + end + do until stem.i >= p + i = i+1 + end + if i < j then do + t = stem.i; stem.i = stem.j; stem.j = t + end + else + leave + end + push l j; push j+1 r + end +end +return diff --git a/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-3.rexx b/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-3.rexx new file mode 100644 index 0000000000..4b7e097a83 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-3.rexx @@ -0,0 +1,20 @@ +Recursive: +procedure expose stem. +arg l r +m = (l+r)%2; p = stem.m +i = l; j = r +do while i <= j + do i = i while stem.i < p + end + do j = j by -1 while stem.j > p + end + if i <= j then do + t = stem.i; stem.i = stem.j; stem.j = t + i = i+1; j = j-1 + end +end +if l < j then + call Recursive l j +if i < r then + call Recursive i r +return diff --git a/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-4.rexx b/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-4.rexx new file mode 100644 index 0000000000..a35b358c85 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-4.rexx @@ -0,0 +1,56 @@ +Optimized: +procedure expose stem. +n = stem.0; s = 1; sl.1 = 1; sr.1 = n +do until s = 0 + l = sl.s; r = sr.s; s = s-1 + do until l >= r + if r-l < 11 then do + do i = l+1 to r + a = stem.i + do j=i-1 by -1 to l while stem.j > a + k = j+1; stem.k = stem.j + end + k = j+1; stem.k = a + end + if s = 0 then + leave + l = sl.s; r = sr.s; s = s-1 + end + else do + m = (l+r)%2 + if stem.l > stem.m then do + t = stem.l; stem.l = stem.m; stem.m = t + end + if stem.l > stem.r then do + t = stem.l; stem.l = stem.r; stem.r = t + end + if stem.m > stem.r then do + t = stem.m; stem.m = stem.r; stem.r = t + end + i = l; j = r; p = stem.m + do until i > j + do i = i while stem.i < p + end + do j = j by -1 while stem.j > p + end + if i <= j then do + t = stem.i; stem.i = stem.j; stem.j = t + i = i+1; j = j-1 + end + end + if j-l < r-i then do + if i < r then do + s = s+1; sl.s = i; sr.s = r + end + r = j + end + else do + if l < j then do + s = s+1; sl.s = l; sr.s = j + end + l = i + end + end + end +end +return diff --git a/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-5.rexx b/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-5.rexx new file mode 100644 index 0000000000..430064aca7 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-5.rexx @@ -0,0 +1,253 @@ +-- 24 Aug 2025 +include Setting + +say 'QUICKSORT' +say version +say +numeric digits 9 +arg n v +if n = '' then n = 10 +if v = '' then v = 1 +show = (n > 0); n = Abs(n) +say 'Timing Version' v 'for' n 'random numbers' +call Generate +if show then call ShowSave +if v = 0 | v = 1 then do + call Time 'r'; call Save2Stack; say 'Save2Stack' format(time('e'),3,3) 'seconds' + call Time 'r'; call Quicksort; say 'Quicksort ' format(time('e'),3,3) 'seconds' + call Time 'r'; call Stack2Stem; say 'Stack2Stem' format(time('e'),3,3) 'seconds' + if show then call ShowStem +end +if v = 0 | v = 2 then do + call Save2Stem + call Time 'r'; call Elegant; say 'Elegant' format(time('e'),3,3) 'seconds' + if show then call ShowStem +end +if v = 0 | v = 3 then do + call Save2Stem + call Time 'r'; call Recursive 1 n; say 'Recursive' format(time('e'),3,3) 'seconds' + if show then call ShowStem +end +if v = 0 | v = 4 then do + call Save2Stem + call Time 'r'; call Optimized; say 'Optimized' format(time('e'),3,3) 'seconds' + if show then call ShowStem +end +say +exit + +Generate: +do x = 1 to n + save.x = 10000*Random(0,9999)+Random(0,9999) +end +save.0 = n +return + +ShowSave: +do x = 1 to 5 + say x save.x +end +do x = n-4 to n + say x save.x +end +say +return + +ShowStem: +do x = 1 to 5 + say x stem.x +end +do x = n-4 to n + say x stem.x +end +say +return + +Save2Stem: +do x = 0 to n + stem.x = save.x +end +return + +Save2Stack: +do x = 1 to n + queue save.x +end +return + +Quicksort: procedure +arr.0 = queued() +do i = 1 to arr.0 + parse pull arr.i +end +less.0 = 0 +pivotList.0 = 0 +more.0 = 0 +if arr.0 <= 1 then do + if arr.0 = 1 then + queue arr.1 + return +end +else do + pivot = arr.1 + do i = 1 to arr.0 + item = arr.i + select + when item < pivot then do + j = less.0 + 1 + less.j = item + less.0 = j + end + when item > pivot then do + j = more.0 + 1 + more.j = item + more.0 = j + end + otherwise + j = pivotList.0 + 1 + pivotList.j = item + pivotList.0 = j + end + end +end +do i = 1 to less.0 + queue less.i +end +if queued() > 0 then do + call quickSort + less.0 = queued() + do i = 1 to less.0 + parse pull less.i + end +end +do i = 1 to more.0 + queue more.i +end +if queued() > 0 then do + call quickSort + more.0 = queued() + do i = 1 to more.0 + parse pull more.i + end +end +do i = 1 to less.0 + queue less.i +end +do i = 1 to pivotList.0 + queue pivotList.i +end +do i = 1 to more.0 + queue more.i +end +return + +Stack2Stem: +do x = 1 to n + parse pull stem.x +end +return + +Elegant: +procedure expose stem. +push 1 stem.0 +do while queued() > 0 + pull l r + if l < r then do + m = (l+r)%2; p = stem.m; i = l-1; j = r+1 + do forever + do until stem.j <= p + j = j-1 + end + do until stem.i >= p + i = i+1 + end + if i < j then do + t = stem.i; stem.i = stem.j; stem.j = t + end + else + leave + end + push l j; push j+1 r + end +end +return + +Recursive: +procedure expose stem. +arg l r +m = (l+r)%2; p = stem.m +i = l; j = r +do while i <= j + do i = i while stem.i < p + end + do j = j by -1 while stem.j > p + end + if i <= j then do + t = stem.i; stem.i = stem.j; stem.j = t + i = i+1; j = j-1 + end +end +if l < j then + call Recursive l j +if i < r then + call Recursive i r +return + +Optimized: +procedure expose stem. +n = stem.0; s = 1; sl.1 = 1; sr.1 = n +do until s = 0 + l = sl.s; r = sr.s; s = s-1 + do until l >= r + if r-l < 20 then do + do i = l+1 to r + a = stem.i + do j=i-1 by -1 to l while stem.j > a + k = j+1; stem.k = stem.j + end + k = j+1; stem.k = a + end + if s = 0 then + leave + l = sl.s; r = sr.s; s = s-1 + end + else do + m = (l+r)%2 + if stem.l > stem.m then do + t = stem.l; stem.l = stem.m; stem.m = t + end + if stem.l > stem.r then do + t = stem.l; stem.l = stem.r; stem.r = t + end + if stem.m > stem.r then do + t = stem.m; stem.m = stem.r; stem.r = t + end + i = l; j = r; p = stem.m + do until i > j + do i = i while stem.i < p + end + do j = j by -1 while stem.j > p + end + if i <= j then do + t = stem.i; stem.i = stem.j; stem.j = t + i = i+1; j = j-1 + end + end + if j-l < r-i then do + if i < r then do + s = s+1; sl.s = i; sr.s = r + end + r = j + end + else do + if l < j then do + s = s+1; sl.s = l; sr.s = j + end + l = i + end + end + end +end +return + +include Abend diff --git a/Task/Sorting-algorithms-Quicksort/RISC-V-Assembly/sorting-algorithms-quicksort.asm b/Task/Sorting-algorithms-Quicksort/RISC-V-Assembly/sorting-algorithms-quicksort.asm new file mode 100644 index 0000000000..58f1ce3836 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/RISC-V-Assembly/sorting-algorithms-quicksort.asm @@ -0,0 +1,227 @@ +# riscv assembly raspberry pico2 rp2350 +# program quicksort.s +# connexion putty com3 +/*********************************************/ +/* CONSTANTES */ +/********************************************/ +/* for this file see risc-v task include a file */ +.include "../../../constantesRiscv.inc" + +/****************************************************/ +/* MACROS */ +/****************************************************/ +#.include "../ficmacrosriscv.inc" # for debugging only + + +/*******************************************/ +/* INITIALED DATAS */ +/*******************************************/ +.data +szMessStart: .asciz "Program riscv start.\r\n" +szMessEnd: .asciz "\nProgram end OK.\r\n" +szCariageReturn: .asciz "\r\n" + +szMessSortOk: .asciz "Area sorted.\n" +szMessSortNok: .asciz "Area not sorted !!!!!.\n" +szLibSort: .asciz "\nAfter sort\n" +szSpace: .asciz " " + +.align 2 +tabNumber: .int 5,7,8,3,2,9,1,4,6 +#tabNumber: .int 9,8,7,6,5,4,3,2,1 +.equ NBTABNUMBER1, . - tabNumber +.equ NBTABNUMBER, NBTABNUMBER1 / 4 # compute items number + +/*******************************************/ +/* UNINITIALED DATA */ +/*******************************************/ +.bss +.align 2 +sConvArea: .skip 24 + +/********************************...-..--*****/ +/* SECTION CODE */ +/**********************************************/ +.text +.global main + +main: + call stdio_init_all # général init +1: # start loop connexion + li a0,0 # raz argument register + call tud_cdc_n_connected # waiting for USB connection + beqz a0,1b # return code = zero ? + + la a0,szMessStart # message address + call writeString # display message + + la s0,tabNumber # number array address + li s1,0 + li s2,NBTABNUMBER +2: # item loop + sh2add t3,s1,s0 # compute item address + lw a0,(t3) + call displayResultD + add s1,s1,1 + blt s1,s2,2b + la a0,szCariageReturn + call writeString + mv a0,s0 # number array address + li a1,0 # first item + addi a2,s2,-1 # last item + call quickSort # sort + mv a0,s0 # number array address + li a1,0 # first item + addi a2,s2,-1 # last item + call isSorted + + la a0,szLibSort + call writeString + + li s1,0 +3: # item loop + sh2add t3,s1,s0 # compute item address + lw a0,(t3) + call displayResultD + add s1,s1,1 + blt s1,s2,3b + la a0,szCariageReturn + call writeString + la a0,szMessEnd + call writeString + call getchar +100: # final loop + j 100b +/**********************************************/ +/* display Result décimal */ +/**********************************************/ +/* a0 value */ +.equ LGZONECONV, 20 +displayResultD: + addi sp, sp, -4 # reserve stack + sw ra, 0(sp) + la a1,sConvArea # conversion result address + call conversion10 # binary conversion + la a0,sConvArea # message address + call writeString # display message + la a0,szSpace + call writeString +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret + +/**********************************************/ +/* */ +/**********************************************/ +/* a0 area address */ +/* a1 first element */ +/* a2 last element */ +.equ LGZONECONV, 20 +isSorted: + addi sp, sp, -4 # reserve stack + sw ra, 0(sp) + mv t0,a1 + sh2add t1,t0,a0 + lw t2,(t1) # load first element +1: + addi t0,t0,1 + ble t0,a2,2f # end indice ? + la a0,szMessSortOk + call writeString + li a0,1 # yes -> area is sorted + j 100f +2: + sh2add t1,t0,a0 + lw t3,(t1) # load next element + bge t3,t2,3f # >= ? + la a0,szMessSortNok + call writeString + li a0,0 # no -> area is not sorted + j 100f +3: + mv t2,t3 + j 1b +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret + +/******************************************************************/ +/* quick sort */ +/******************************************************************/ +/* a0 contains array address */ +/* a1 contains the first element */ +/* a2 contains the last element */ +quickSort: + addi sp, sp, -16 # reserve stack + sw ra, 0(sp) # save registers + sw s0, 4(sp) + sw s1, 8(sp) + sw s2, 12(sp) + bge a1,a2,100f # first > last ? -> end + mv s0,a0 # save address area + mv s1,a1 # save first indice + mv s2,a2 # save last indice + call partition # partitioning + addi a2,a0,-1 # index partition - 1 + mv a1,s1 # move first index + mv s1,a0 # save partition index + mv a0,s0 # array address + call quickSort # sort lower part + addi a1,s1,1 # partition index + 1 + mv a2,s2 # last index + mv a0,s0 + call quickSort # sort higter part + +100: + lw ra, 0(sp) + lw s0, 4(sp) + lw s1, 8(sp) + lw s2, 12(sp) + addi sp, sp, 16 + ret +/******************************************************************/ +/* shell sort */ +/******************************************************************/ +/* a0 contains the address of table */ +/* a1 contains index of first item */ +/* a2 contains index of last item */ +partition: # INFO: partition + addi sp, sp, -4 # reserve stack + sw ra, 0(sp) # save registers + mv t0,a1 # init with first index + mv t1,a1 # init with first index + sh2add t2,a2,a0 + lw t3,(t2) # load value last index +1: # begin loop + sh2add t2,t1,a0 + lw t4,(t2) # load value + bge t4,t3,2f # compare value 2 + sh2add t2,t0,a0 # if value2 < value 1 -> swap values + lw t5,(t2) + sh2add t2,t0,a0 + sw t4,(t2) + sh2add t2,t1,a0 + sw t5,(t2) + addi t0,t0,1 # increment index +2: + addi t1,t1,1 # increment index 2 + blt t1,a2,1b # < maxi -> loop + sh2add t2,t0,a0 # else swap value + lw t5,(t2) + sh2add t2,t0,a0 + sw t3,(t2) + sh2add t2,a2,a0 + sw t5,(t2) + mv a0,t0 # return index partition + +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret +/************************************/ +/* file include Fonctions */ +/***********************************/ +/* for this file see risc-v task include a file */ +.include "../../../includeFunctions.s" diff --git a/Task/Sorting-algorithms-Quicksort/Raku/sorting-algorithms-quicksort-5.raku b/Task/Sorting-algorithms-Quicksort/Raku/sorting-algorithms-quicksort-5.raku index 5287953494..5353fcd21b 100644 --- a/Task/Sorting-algorithms-Quicksort/Raku/sorting-algorithms-quicksort-5.raku +++ b/Task/Sorting-algorithms-Quicksort/Raku/sorting-algorithms-quicksort-5.raku @@ -1,5 +1,7 @@ -say "x" x 11 ~ " Benchmarking " ~ "x" x 11; +# run in a terminal: "zef install Benchmark" to install from https://raku.land use Benchmark; + +say "x" x 11 ~ " Benchmarking " ~ "x" x 11; my $runs = 5; my $elems = 10 * Kernel.cpu-cores * 2**10; my @unsorted of Str = ('a'..'z').roll(8).join xx $elems; @@ -22,7 +24,7 @@ my %results = timethese $runs, { my @metrics = ; my $msg-row = "%.4f\t" x @metrics.elems ~ '%s'; -say @metrics.join("\t"); -for %results.kv -> $name, %m { - say sprintf($msg-row, %m{@metrics}, $name); +for %results.sort( *.value ) { + once say @metrics.join("\t"); # header + say sprintf($msg-row, .value{@metrics}, .key) } diff --git a/Task/Sorting-algorithms-Quicksort/Rust/sorting-algorithms-quicksort-1.rust b/Task/Sorting-algorithms-Quicksort/Rust/sorting-algorithms-quicksort-1.rs similarity index 100% rename from Task/Sorting-algorithms-Quicksort/Rust/sorting-algorithms-quicksort-1.rust rename to Task/Sorting-algorithms-Quicksort/Rust/sorting-algorithms-quicksort-1.rs diff --git a/Task/Sorting-algorithms-Quicksort/Rust/sorting-algorithms-quicksort-2.rust b/Task/Sorting-algorithms-Quicksort/Rust/sorting-algorithms-quicksort-2.rs similarity index 100% rename from Task/Sorting-algorithms-Quicksort/Rust/sorting-algorithms-quicksort-2.rust rename to Task/Sorting-algorithms-Quicksort/Rust/sorting-algorithms-quicksort-2.rs diff --git a/Task/Sorting-algorithms-Quicksort/Scheme/sorting-algorithms-quicksort-1.ss b/Task/Sorting-algorithms-Quicksort/Scheme/sorting-algorithms-quicksort-1.scm similarity index 100% rename from Task/Sorting-algorithms-Quicksort/Scheme/sorting-algorithms-quicksort-1.ss rename to Task/Sorting-algorithms-Quicksort/Scheme/sorting-algorithms-quicksort-1.scm diff --git a/Task/Sorting-algorithms-Quicksort/Scheme/sorting-algorithms-quicksort-2.ss b/Task/Sorting-algorithms-Quicksort/Scheme/sorting-algorithms-quicksort-2.scm similarity index 100% rename from Task/Sorting-algorithms-Quicksort/Scheme/sorting-algorithms-quicksort-2.ss rename to Task/Sorting-algorithms-Quicksort/Scheme/sorting-algorithms-quicksort-2.scm diff --git a/Task/Sorting-algorithms-Quicksort/Scheme/sorting-algorithms-quicksort-3.ss b/Task/Sorting-algorithms-Quicksort/Scheme/sorting-algorithms-quicksort-3.scm similarity index 100% rename from Task/Sorting-algorithms-Quicksort/Scheme/sorting-algorithms-quicksort-3.ss rename to Task/Sorting-algorithms-Quicksort/Scheme/sorting-algorithms-quicksort-3.scm diff --git a/Task/Sorting-algorithms-Quicksort/Tailspin/sorting-algorithms-quicksort-2.tailspin b/Task/Sorting-algorithms-Quicksort/Tailspin/sorting-algorithms-quicksort-2.tailspin index 25477fb71d..a1655e71cf 100644 --- a/Task/Sorting-algorithms-Quicksort/Tailspin/sorting-algorithms-quicksort-2.tailspin +++ b/Task/Sorting-algorithms-Quicksort/Tailspin/sorting-algorithms-quicksort-2.tailspin @@ -1,36 +1,20 @@ -templates quicksort - templates partial - def first: $(1); - def last: $(2); - def pivot: $@quicksort($first); - @: $(1) + 1; - $(2) -> # - - when <..~$@> do - def limit: $; - @quicksort($first): $@quicksort($limit); - @quicksort($limit): $pivot; - [ $first, $limit - 1 ] ! - [ $limit + 1, $last ] ! - - when )> do - $ - 1 -> # - - when )> do - @: $@ + 1; $ -> # - +quicksort templates + partition templates + @ set []; + pivot is $(1); + [$(2..)... -> #]! + $pivot ! + $@ ! + when <|..$pivot> do + $ ! otherwise - def temp: $@quicksort($@); - @quicksort($@): $@quicksort($); - @quicksort($): $temp; - @: $@ + 1; $ - 1 -> # - end partial - @: $; - [1, $@::length] -> # - $@ ! - - when )> do - $ -> partial -> # + ..|@ set $; + end partition + [$ -> #] ! + when <|[](1..)> do + $ -> partition -> # ! + when <~|[]> do + $ ! end quicksort -[4,5,3,8,1,2,6,7,9,8,5] -> quicksort -> !OUT::write +[4,5,3,8,1,2,6,7,9,8,5] -> quicksort ! diff --git a/Task/Sorting-algorithms-Quicksort/Tailspin/sorting-algorithms-quicksort-3.tailspin b/Task/Sorting-algorithms-Quicksort/Tailspin/sorting-algorithms-quicksort-3.tailspin new file mode 100644 index 0000000000..25477fb71d --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Tailspin/sorting-algorithms-quicksort-3.tailspin @@ -0,0 +1,36 @@ +templates quicksort + templates partial + def first: $(1); + def last: $(2); + def pivot: $@quicksort($first); + @: $(1) + 1; + $(2) -> # + + when <..~$@> do + def limit: $; + @quicksort($first): $@quicksort($limit); + @quicksort($limit): $pivot; + [ $first, $limit - 1 ] ! + [ $limit + 1, $last ] ! + + when )> do + $ - 1 -> # + + when )> do + @: $@ + 1; $ -> # + + otherwise + def temp: $@quicksort($@); + @quicksort($@): $@quicksort($); + @quicksort($): $temp; + @: $@ + 1; $ - 1 -> # + end partial + @: $; + [1, $@::length] -> # + $@ ! + + when )> do + $ -> partial -> # +end quicksort + +[4,5,3,8,1,2,6,7,9,8,5] -> quicksort -> !OUT::write diff --git a/Task/Sorting-algorithms-Quicksort/Tailspin/sorting-algorithms-quicksort-4.tailspin b/Task/Sorting-algorithms-Quicksort/Tailspin/sorting-algorithms-quicksort-4.tailspin new file mode 100644 index 0000000000..4238893ba2 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Tailspin/sorting-algorithms-quicksort-4.tailspin @@ -0,0 +1,37 @@ +quicksort templates + partial templates + first is $(1); + last is $(2); + pivot is $@quicksort($first); + @ set $first + 1; + $last -> # ! + + when <|..~$@> do + limit is $; + @quicksort($first) set $@quicksort($limit); + @quicksort($limit) set $pivot; + [ $first, $limit - 1 ] ! + [ $limit + 1, $last ] ! + + when <|?($@quicksort($) matches <|$pivot~..>)> do + $ - 1 -> # ! + + when <|?($@quicksort($@) matches <|..$pivot>)> do + @ set $@ + 1; $ -> # ! + + otherwise + temp is $@quicksort($@); + @quicksort($@) set $@quicksort($); + @quicksort($) set $temp; + @ set $@ + 1; $ - 1 -> # ! + end partial + + @ set $; + [1, $@::length] -> !# + $@ ! + + when <|?($(1) matches <|..~$(2)>)> do + $ -> partial -> !# +end quicksort + +[4,5,3,8,1,2,6,7,9,8,5] -> quicksort ! diff --git a/Task/Sorting-algorithms-Quicksort/VBScript/sorting-algorithms-quicksort.vb b/Task/Sorting-algorithms-Quicksort/VBScript/sorting-algorithms-quicksort.vbs similarity index 100% rename from Task/Sorting-algorithms-Quicksort/VBScript/sorting-algorithms-quicksort.vb rename to Task/Sorting-algorithms-Quicksort/VBScript/sorting-algorithms-quicksort.vbs diff --git a/Task/Sorting-algorithms-Quicksort/XBasic/sorting-algorithms-quicksort.basic b/Task/Sorting-algorithms-Quicksort/XBasic/sorting-algorithms-quicksort.basic new file mode 100644 index 0000000000..b50bd9c3c1 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/XBasic/sorting-algorithms-quicksort.basic @@ -0,0 +1,75 @@ +' Sorting algorithms/Quicksort +PROGRAM "quicksort" +VERSION "1.0" + +IMPORT "xst" + +DECLARE FUNCTION Entry () +DECLARE FUNCTION QuickSort (@arr%[], l%%, r%%) +' Pseudo-random number generator +' Based on the rand, srand functions from Kernighan & Ritchie's book +' 'The C Programming Language' +DECLARE FUNCTION Rand() +DECLARE FUNCTION SRand(seed%%) + +FUNCTION Entry () + DIM arr%[19] + a%% = 0 + b%% = UBOUND(arr%[]) + XstGetSystemTime (@msec) + SRand(INT(msec) MOD 32768) + FOR i%% = a%% TO b%% + arr%[i%%] = INT(Rand() / 32768.0 * 99.0) + NEXT i%% + PRINT "Unsorted:" + FOR i%% = a%% TO b%% + PRINT FORMAT$("## ", arr%[i%%]); + NEXT i%% + PRINT + PRINT "Sorted:" + QuickSort(@arr%[], a%%, b%%) + FOR i%% = a%% TO b%% + PRINT FORMAT$("## ", arr%[i%%]); + NEXT i%% + PRINT +END FUNCTION + +FUNCTION QuickSort (@arr%[], l%%, r%%) + leftIndex%% = l%% + rightIndex%% = r%% + IF r%% > l%% THEN + pivot%% = (l%% + r%%) \ 2 + DO WHILE (leftIndex%% <= pivot%%) AND (rightIndex%% >= pivot%%) + DO WHILE (arr%[leftIndex%%] < arr%[pivot%%]) AND (leftIndex%% <= pivot%%) + INC leftIndex%% + LOOP + DO WHILE (arr%[rightIndex%%] > arr%[pivot%%]) AND (rightIndex%% >= pivot%%) + DEC rightIndex%% + LOOP + SWAP arr%[leftIndex%%], arr%[rightIndex%%] + INC leftIndex%% + DEC rightIndex%% + SELECT CASE TRUE + CASE leftIndex%% - 1 = pivot%%: + INC rightIndex%% + pivot%% = rightIndex%% + CASE rightIndex%% + 1 = pivot%%: + DEC leftIndex%% + pivot%% = leftIndex%% + END SELECT + LOOP + QuickSort (@arr%[], l%%, pivot%% - 1) + QuickSort (@arr%[], pivot%% + 1, r%%) + END IF +END FUNCTION + +' Return pseudo-random integer on 0..32767 +FUNCTION Rand() + #next&& = #next&& * 1103515245 + 12345 +END FUNCTION USHORT(#next&& / 65536) MOD 32768 + +' Set seed for Rand() +FUNCTION SRand(seed%%) + #next&& = seed%% +END FUNCTION +END PROGRAM diff --git a/Task/Sorting-algorithms-Radix-sort/Ada/sorting-algorithms-radix-sort.ada b/Task/Sorting-algorithms-Radix-sort/Ada/sorting-algorithms-radix-sort.adb similarity index 100% rename from Task/Sorting-algorithms-Radix-sort/Ada/sorting-algorithms-radix-sort.ada rename to Task/Sorting-algorithms-Radix-sort/Ada/sorting-algorithms-radix-sort.adb diff --git a/Task/Sorting-algorithms-Radix-sort/C/sorting-algorithms-radix-sort.c b/Task/Sorting-algorithms-Radix-sort/C/sorting-algorithms-radix-sort-1.c similarity index 100% rename from Task/Sorting-algorithms-Radix-sort/C/sorting-algorithms-radix-sort.c rename to Task/Sorting-algorithms-Radix-sort/C/sorting-algorithms-radix-sort-1.c diff --git a/Task/Sorting-algorithms-Radix-sort/C/sorting-algorithms-radix-sort-2.c b/Task/Sorting-algorithms-Radix-sort/C/sorting-algorithms-radix-sort-2.c new file mode 100644 index 0000000000..84d49f1453 --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/C/sorting-algorithms-radix-sort-2.c @@ -0,0 +1,74 @@ +#include +#include +#include +#include +#include + +// Get size of statically allocated array +#define ARR_LEN(ARR) (sizeof ARR / sizeof *ARR) +// Generate random number in the interval [M,N] +#define RAND_RNG(M,N) (M + rand() / (RAND_MAX / (N - M + 1) + 1)); + +void radix_sort(const size_t n, int *array) { + int *bit0_nums = (int*)malloc(n*sizeof(int)); + int *bit1_nums = (int*)malloc(n*sizeof(int)); + for (size_t ibit=0; ibit<8*sizeof(int)-1; ibit++) { + size_t nbit0 = 0; + size_t nbit1 = 0; + for (size_t i=0; i>ibit)&0b1; + if (bit == 1) { + bit1_nums[nbit1] = array[i]; + nbit1++; + } else { + bit0_nums[nbit0] = array[i]; + nbit0++; + } + } + for (size_t i=0; i>ibit)&0b1; + if (bit == 1) { + bit1_nums[nbit1] = array[i]; + nbit1++; + } else { + bit0_nums[nbit0] = array[i]; + nbit0++; + } + } + for (size_t i=0; i +#include +#include +#include + +// Get size of statically allocated array +#define ARR_LEN(ARR) (sizeof ARR / sizeof *ARR) +// Generate random number in the interval [M,N] +#define RAND_RNG(M,N) (M + rand() / (RAND_MAX / (N - M + 1) + 1)); + +void radix_sort(const size_t n, int *array) { + int *nums = (int*)malloc(2*n*sizeof(int)); + for (size_t ibit=0; ibit<8*sizeof(int)-1; ibit++) { + size_t nnums[2] = {0, 0}; + for (size_t i=0; i>ibit)&0b1; + nums[bit*n+nnums[bit]] = array[i]; + nnums[bit]++; + } + // To make it easily extendable to more buckets + size_t offset = 0; + for (int ibuck=0; ibuck<2; ibuck++) { + for (size_t i=0; i>ibit)&0b1; + nums[bit*n+nnums[bit]] = array[i]; + nnums[bit]++; + } + // To make it easily extendable to more buckets + size_t offset = 0; + for (int ibuck=1; ibuck<2; ibuck++) { + for (size_t i=0; i max - max = d[di] - . + max = higher d[di] max . len buck[][] radix pos = 1 while pos <= max - for i = 1 to radix - len buck[i][] 0 - . + for i = 1 to radix : len buck[i][] 0 for di = 1 to len d[] h = d[di] div pos mod radix + 1 buck[h][] &= d[di] diff --git a/Task/Sorting-algorithms-Radix-sort/Elixir/sorting-algorithms-radix-sort.elixir b/Task/Sorting-algorithms-Radix-sort/Elixir/sorting-algorithms-radix-sort.ex similarity index 100% rename from Task/Sorting-algorithms-Radix-sort/Elixir/sorting-algorithms-radix-sort.elixir rename to Task/Sorting-algorithms-Radix-sort/Elixir/sorting-algorithms-radix-sort.ex diff --git a/Task/Sorting-algorithms-Radix-sort/Fortran/sorting-algorithms-radix-sort.f b/Task/Sorting-algorithms-Radix-sort/Fortran/sorting-algorithms-radix-sort.f index 85bdd73c2b..1cf519a11e 100644 --- a/Task/Sorting-algorithms-Radix-sort/Fortran/sorting-algorithms-radix-sort.f +++ b/Task/Sorting-algorithms-Radix-sort/Fortran/sorting-algorithms-radix-sort.f @@ -294,161 +294,115 @@ !*************************************************************************** ! End of Superfast LSD sort !*************************************************************************** -*======================================================================= -* RSORT - sort a list of integers by the Radix Sort algorithm -* Public domain. This program may be used by any person for any purpose. -* Origin: Herman Hollerith, 1887 -* -*___Name____Type______In/Out____Description_____________________________ -* IX(N) Integer Both Array to be sorted in increasing order -* IW(N) Integer Neither Workspace -* N Integer In Length of array -* -* ASSUMPTIONS: Bits in an INTEGER is an even number. -* Integers are represented by twos complement. -* -* NOTE THAT: Radix sorting has an advantage when the input is known -* to be less than some value, so that only a few bits need -* to be compared. This routine looks at all the bits, -* and is thus slower than Quicksort. -*======================================================================= - SUBROUTINE RSORT (IX, IW, N) - IMPLICIT NONE - INTEGER IX, IW, N - DIMENSION IX(N), IW(N) +! +! Performs a MSD radi sort using bits. +! It sorts only using the bit size of the largest and smallest numbers +! So, on small numbers < 128, it's faster than a Quicksort for very large numbers > 20 bits +! It's slower. +! Author: Peter Kelly +! No claim is made on the code and no warranty implied. +module msd_bit_sort_module + implicit none + private + public :: msd_bit_sort - INTEGER I, ! count bits - $ ILIM, ! bits in an integer - $ J, ! count array elements - $ P1OLD, P0OLD, P1, P0, ! indices to ones and zeros - $ SWAP - LOGICAL ODD ! even or odd bit position +contains + ! Transform signed integer to make it comparable + PURE FUNCTION transform_for_sort(x) RESULT(transformed) + INTEGER, INTENT(IN) :: x + INTEGER :: transformed -* IF (N < 2) RETURN ! validate -* - ILIM = Bit_size(i) !Get the fixed number of bits -*======================================================================= -* Alternate between putting data into IW and into IX -*======================================================================= - P1 = N+1 - P0 = N ! read from 1, N on first pass thru - ODD = .FALSE. - DO I = 0, ILIM-2 - P1OLD = P1 - P0OLD = P0 ! save the value from previous bit - P1 = N+1 - P0 = 0 ! start a fresh count for next bit - - IF (ODD) THEN - DO J = 1, P0OLD, +1 ! copy data from the zeros - IF ( BTEST(IW(J), I) ) THEN - P1 = P1 - 1 - IX(P1) = IW(J) - ELSE - P0 = P0 + 1 - IX(P0) = IW(J) - END IF - END DO - DO J = N, P1OLD, -1 ! copy data from the ones - IF ( BTEST(IW(J), I) ) THEN - P1 = P1 - 1 - IX(P1) = IW(J) - ELSE - P0 = P0 + 1 - IX(P0) = IW(J) - END IF - END DO - - ELSE - DO J = 1, P0OLD, +1 ! copy data from the zeros - IF ( BTEST(IX(J), I) ) THEN - P1 = P1 - 1 - IW(P1) = IX(J) - ELSE - P0 = P0 + 1 - IW(P0) = IX(J) - END IF - END DO - DO J = N, P1OLD, -1 ! copy data from the ones - IF ( BTEST(IX(J), I) ) THEN - P1 = P1 - 1 - IW(P1) = IX(J) - ELSE - P0 = P0 + 1 - IW(P0) = IX(J) - END IF - END DO - END IF ! even or odd i - - ODD = .NOT. ODD - END DO ! next i - -*======================================================================= -* the sign bit -*======================================================================= - P1OLD = P1 - P0OLD = P0 - P1 = N+1 - P0 = 0 - -* if sign bit is set, send to the zero end - DO J = 1, P0OLD, +1 - IF ( BTEST(IW(J), ILIM-1) ) THEN - P0 = P0 + 1 - IX(P0) = IW(J) - ELSE - P1 = P1 - 1 - IX(P1) = IW(J) - END IF - END DO - DO J = N, P1OLD, -1 - IF ( BTEST(IW(J), ILIM-1) ) THEN - P0 = P0 + 1 - IX(P0) = IW(J) - ELSE - P1 = P1 - 1 - IX(P1) = IW(J) - END IF - END DO - -*======================================================================= -* Reverse the order of the greater value partition -*======================================================================= - P1OLD = P1 - DO J = N, (P1OLD+N)/2+1, -1 - SWAP = IX(J) - IX(J) = IX(P1) - IX(P1) = SWAP - P1 = P1 + 1 - END DO - RETURN - END ! of RSORT + ! XOR with sign bit to make negative numbers sortable + ! This inverts the bit representation for negative numbers + transformed = IEOR(x, ISHFT(-1, BIT_SIZE(x)-1)) + END FUNCTION transform_for_sort -*********************************************************************** -* test program -*********************************************************************** - PROGRAM t_sort - IMPLICIT NONE - INTEGER I, N - PARAMETER (N = 11) - INTEGER IX(N), IW(N) - LOGICAL OK + RECURSIVE SUBROUTINE msd_bit_sort_internal(arr, left, right, bit) + INTEGER, INTENT(INOUT) :: arr(:) + INTEGER, INTENT(IN) :: left, right, bit + INTEGER :: i, j, temp + INTEGER :: transformed_i, transformed_j - DATA IX / 2, 24, 45, 0, 66, 75, 170, -802, -90, 1066, 666 / + ! Base case + IF (left >= right .OR. bit < 0) RETURN - PRINT *, 'before: ', IX - CALL RSORT (IX, IW, N) - PRINT *, 'after: ', IX + i = left + j = right -* compare - OK = .TRUE. - DO I = 1, N-1 - IF (IX(I) > IX(I+1)) OK = .FALSE. - END DO - IF (OK) THEN - PRINT *, 't_sort: successful test' - ELSE - PRINT *, 't_sort: failure!' - END IF - END ! of test program + DO WHILE (i <= j) + ! Find elements to swap + DO WHILE (i <= j) + transformed_i = transform_for_sort(arr(i)) + transformed_j = transform_for_sort(arr(j)) + + ! Partition based on transformed values + IF (BTEST(transformed_i, bit) .AND. .NOT. BTEST(transformed_j, bit)) THEN + ! Swap needed + temp = arr(i) + arr(i) = arr(j) + arr(j) = temp + EXIT + END IF + + ! Move pointers + IF (.NOT. BTEST(transformed_i, bit)) i = i + 1 + IF (BTEST(transformed_j, bit)) j = j - 1 + END DO + + ! Adjust pointers + IF (i < j) THEN + i = i + 1 + j = j - 1 + END IF + END DO + + ! Recursively sort sub-arrays + IF (left < j) THEN + CALL msd_bit_sort_internal(arr, left, j, bit-1) + END IF + IF (i < right) THEN + CALL msd_bit_sort_internal(arr, i, right, bit-1) + END IF + END SUBROUTINE msd_bit_sort_internal + + SUBROUTINE msd_bit_sort(arr) + INTEGER, INTENT(INOUT) :: arr(:) + INTEGER :: max_bit, n, mini, maxi + + n = SIZE(arr) + IF (n < 2) RETURN + + ! Find most significant bit + mini = MINVAL(arr) + maxi = MAXVAL(arr) + max_bit = MAX(BIT_SIZE(arr(1)) - LEADZ(IEOR(mini, maxi)) - 1, 0) + + ! Perform the recursive bit sort + CALL msd_bit_sort_internal(arr, 1, n, max_bit) + END SUBROUTINE msd_bit_sort + end module msd_bit_sort_module +! + program bit_sort_test_harness + use msd_bit_sort_module + implicit none + + INTEGER, PARAMETER :: ARRAY_SIZE = 2**23 + INTEGER :: test_array(ARRAY_SIZE) + real :: holder(ARRAY_SIZE) + INTEGER :: xx,yy,rate + call random_number(holder) + holder = holder -0.33333 + test_array = int(holder*1000000.0) + ! Initialize with some test values + + PRINT *, "Original Array:" + PRINT *, test_array(1:10) + call system_clock(count=xx,count_rate=rate) + CALL msd_bit_sort(test_array) + call system_clock(count=yy) + print*,'sort time = ',(real(yy-xx)/rate) + PRINT *, "Sorted Array:" + PRINT *, test_array(1:5),test_array(array_size-5:) + +end program bit_sort_test_harness diff --git a/Task/Sorting-algorithms-Radix-sort/FreeBASIC/sorting-algorithms-radix-sort.basic b/Task/Sorting-algorithms-Radix-sort/FreeBASIC/sorting-algorithms-radix-sort.basic new file mode 100644 index 0000000000..5757cb4bb4 --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/FreeBASIC/sorting-algorithms-radix-sort.basic @@ -0,0 +1,93 @@ +Sub countSort(rs() As Long, expo As Long) + Dim As Long lb = Lbound(rs), ub = Ubound(rs) + Dim As Long i, t + Dim As Long salida(lb To ub), conteo(0 To 9) + + For i = lb To ub + t = (rs(i) \ expo) Mod 10 + conteo(t) += 1 + Next + + For i = 1 To 9 + conteo(i) += conteo(i-1) + Next + + For i = ub To lb Step -1 + t = (rs(i) \ expo) Mod 10 + salida(lb + conteo(t) - 1) = rs(i) + conteo(t) -= 1 + Next + + For i = lb To ub + rs(i) = salida(i) + Next +End Sub + +Sub radixSort(rs() As Long) + Dim As Long lb = Lbound(rs), ub = Ubound(rs) + + ' Find minimum value + Dim As Long i, minVal = rs(lb) + For i = lb + 1 To ub + If rs(i) < minVal Then minVal = rs(i) + Next + + ' If negative numbers exist, shift array to positive + If minVal < 0 Then + For i = lb To ub + rs(i) -= minVal + Next + End If + + ' Find maximum value + Dim As Long maxVal = rs(lb) + For i = lb + 1 To ub + If rs(i) > maxVal Then maxVal = rs(i) + Next + + ' Do counting sort for every digit + Dim As Long expo = 1 + While (maxVal \ expo) > 0 + countSort(rs(), expo) + expo *= 10 + Wend + + ' If we shifted for negatives, shift back + If minVal < 0 Then + For i = lb To ub + rs(i) += minVal + Next + End If +End Sub + +Sub printArray(rs() As Long) + Dim As Long lb = Lbound(rs), ub = Ubound(rs) + Print "[ "; + For i As Long = lb To ub + Print rs(i); + If i < ub Then Print ", "; + Next + Print " ]" +End Sub + +'--- Main Program --- +Dim As Long i, array(-7 To 7) +Dim As Long a = Lbound(array), b = Ubound(array) + +Randomize Timer +For i = a To b : array(i) = i : Next i + +For i = a To b ' little shuffle + Swap array(i), array(Int(Rnd * (b - a + 1)) + a) +Next i + +Print "unsort "; +For i = a To b : Print Using "####"; array(i); : Next i + +radixSort(array()) ' sort the array + +Print !"\n sort "; +For i = a To b : Print Using "####"; array(i); : Next i +Print + +Sleep diff --git a/Task/Sorting-algorithms-Radix-sort/JavaScript/sorting-algorithms-radix-sort.js b/Task/Sorting-algorithms-Radix-sort/JavaScript/sorting-algorithms-radix-sort.js new file mode 100644 index 0000000000..9ec9b38028 --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/JavaScript/sorting-algorithms-radix-sort.js @@ -0,0 +1,60 @@ +// Radix sort comparator for 32-bit two's complement integers +class RadixTest { + constructor(bit) { + this.bit = bit; // bit position [0..31] to examine + } + + // function call operator (simulated with a method) + test(value) { + if (this.bit === 31) { // sign bit + return value < 0; // negative int to left partition + } else { + return !(value & (1 << this.bit)); // 0 bit to left partition + } + } +} + +// Helper function to partition an array in place +function partition(arr, start, end, radixTest) { + let i = start - 1; + + for (let j = start; j < end; j++) { + if (radixTest.test(arr[j])) { + i++; + // Swap arr[i] and arr[j] + [arr[i], arr[j]] = [arr[j], arr[i]]; + } + } + return i + 1; +} + +// Least significant digit radix sort +function lsdRadixSort(arr) { + for (let lsb = 0; lsb < 32; ++lsb) { // least-significant-bit + const radixTest = new RadixTest(lsb); + partition(arr, 0, arr.length, radixTest); + } +} + +// Most significant digit radix sort (recursive) +function msdRadixSort(arr, start = 0, end = arr.length, msb = 31) { + if (start < end -1 && msb >= 0) { // changed (first != last) to (start < end-1) for easier indexing + const radixTest = new RadixTest(msb); + let mid = partition(arr, start, end, radixTest); + msb--; // decrement most-significant-bit + msdRadixSort(arr, start, mid, msb); // sort left partition + msdRadixSort(arr, mid, end, msb); // sort right partition + } +} + +// test radix_sort +function main() { + let data = [170, 45, 75, -90, -802, 24, 2, 66]; + + lsdRadixSort(data); + // msdRadixSort(data); + + console.log(data.join(" ")); +} + +main(); diff --git a/Task/Sorting-algorithms-Radix-sort/Julia/sorting-algorithms-radix-sort.julia b/Task/Sorting-algorithms-Radix-sort/Julia/sorting-algorithms-radix-sort.jl similarity index 100% rename from Task/Sorting-algorithms-Radix-sort/Julia/sorting-algorithms-radix-sort.julia rename to Task/Sorting-algorithms-Radix-sort/Julia/sorting-algorithms-radix-sort.jl diff --git a/Task/Sorting-algorithms-Radix-sort/Kotlin/sorting-algorithms-radix-sort.kotlin b/Task/Sorting-algorithms-Radix-sort/Kotlin/sorting-algorithms-radix-sort.kts similarity index 100% rename from Task/Sorting-algorithms-Radix-sort/Kotlin/sorting-algorithms-radix-sort.kotlin rename to Task/Sorting-algorithms-Radix-sort/Kotlin/sorting-algorithms-radix-sort.kts diff --git a/Task/Sorting-algorithms-Radix-sort/Phix/sorting-algorithms-radix-sort.phix b/Task/Sorting-algorithms-Radix-sort/Phix/sorting-algorithms-radix-sort.phix index a222af05fe..65a3567168 100644 --- a/Task/Sorting-algorithms-Radix-sort/Phix/sorting-algorithms-radix-sort.phix +++ b/Task/Sorting-algorithms-Radix-sort/Phix/sorting-algorithms-radix-sort.phix @@ -1,55 +1,41 @@ -(phixonline)--> - with javascript_semantics +with javascript_semantics - function radixSortn(sequence s, integer n) - sequence buckets = repeat({},10), - res = {} - for i=1 to length(s) do - integer digit = remainder(floor(s[i]/power(10,n-1)),10)+1 - buckets[digit] = append(buckets[digit],s[i]) - end for - for i=1 to length(buckets) do - integer len = length(buckets[i]) - if len!=0 then - if len=1 or n=1 then - res &= buckets[i] - else - res &= radixSortn(buckets[i],n-1) - end if - end if - end for - return res - end function +function radixSortn(sequence s, integer n) + sequence buckets = repeat({},10), res = {} + for i,si in s do + integer digit = remainder(floor(si/power(10,n-1)),10)+1 + buckets[digit] = append(buckets[digit],si) + end for + for b in buckets do + res &= iff(length(b)<=1 or n=1?b:radixSortn(b,n-1)) + end for + return res +end function - function split_by_sign(sequence s) - sequence buckets = {{},{}} - for i=1 to length(s) do - integer si = s[i] - if si<0 then - buckets[1] = append(buckets[1],-si) - else - buckets[2] = append(buckets[2],si) - end if - end for - return buckets - end function +function split_by_sign(sequence s) + sequence buckets = {{},{}} + for i=1 to length(s) do + integer si = s[i], bn = 1+(si>=0) + buckets[bn] = append(buckets[bn],abs(si)) + end for + return buckets +end function - function radixSort(sequence s) - integer mins = min(s), - passes = max(max(s),abs(mins)) - passes = floor(log10(passes))+1 - if mins<0 then - sequence buckets = split_by_sign(s) - s = reverse(sq_uminus(radixSortn(buckets[1],passes))) - & radixSortn(buckets[2],passes) - else - s = radixSortn(s,passes) - end if - return s - end function +function radixSort(sequence s) + integer mins = min(s), + passes = max(max(s),abs(mins)) + passes = floor(log10(passes))+1 + if mins<0 then + sequence buckets = split_by_sign(s) + s = reverse(sq_uminus(radixSortn(buckets[1],passes))) + & radixSortn(buckets[2],passes) + else + s = radixSortn(s,passes) + end if + return s +end function - ?radixSort({1, 3, 8, 9, 0, 0, 8, 7, 1, 6}) - ?radixSort({170, 45, 75, 90, 2, 24, 802, 66}) - ?radixSort({170, 45, 75, 90, 2, 24, -802, -66}) - ?radixSort({100000, -10000, 400, 23, 10000}) - - with javascript_semantics +with javascript_semantics - function selection_sort(sequence s) - for i=1 to length(s) do - integer m = i - object si = s[i], - sm = s[m] - for j=i+1 to length(s) do - object sj = s[j] - if sj<sm then - {sm,m} = {sj,j} - end if - end for - if sm<si then -- (or equivalently m!=i) - s[i] = sm - s[m] = si - end if - end for - return s - end function +function selection_sort(sequence s) + for i,si in s do + integer m = i + object sm = si + for j,sj in s from i+1 do + if sj?
    selection_sort(shuffle(tagset(10))) - - with javascript_semantics +with javascript_semantics - function shell_sort(sequence s) - integer gap = floor(length(s)/2), j - while gap>0 do - for i=gap to length(s) do - object si = s[i] - j = i-gap - while j>=1 and si<=s[j] do - s[j+gap] = s[j] - j -= gap - end while - s[j+gap] = si - end for - gap = floor(gap/2) - end while - return s - end function +function shell_sort(sequence s) + integer gap = floor(length(s)/2), j + while gap>0 do + for i=gap to length(s) do + object si = s[i] + j = i-gap + while j>=1 and si<=s[j] do + s[j+gap] = s[j] + j -= gap + end while + s[j+gap] = si + end for + gap = floor(gap/2) + end while + return s +end function - ?shell_sort(shuffle(tagset(10))) - - without js -- (multitasking) - integer count +without js -- (multitasking) +integer count - procedure sleeper(integer key) - ? key -- (or maybe res &= key) - count -= 1 - end procedure +procedure sleeper(integer key) + ? key -- (or maybe res &= key) + count -= 1 +end procedure - --sequence s = command_line()[3..$] - sequence s = split("3 1 4 1 5 9 2 6 5") - if length(s)=0 then - puts(1,"Nothing to sort.\n") - else - count = 0 - for i=1 to length(s) do - object si = to_number(s[i]) - if integer(si) then - atom task = task_create(sleeper,{si}) - task_schedule(task,{si/10,si/10}) - count += 1 - end if - end for +--sequence s = command_line()[3..$] +sequence s = split("3 1 4 1 5 9 2 6 5") +if length(s)=0 then + puts(1,"Nothing to sort.\n") +else + count = 0 + for i=1 to length(s) do + object si = to_number(s[i]) + if integer(si) then + atom task = task_create(sleeper,{si}) + task_schedule(task,{si/10,si/10}) + count += 1 + end if + end for - while count do - task_yield() - end while - end if - - with javascript_semantics +with javascript_semantics - function stoogesort(sequence s, integer i=1, j=length(s)) - if s[j]<s[i] then - {s[i],s[j]} = {s[j],s[i]} - end if - if j-i>1 then - integer t = floor((j-i+1)/3) - s = stoogesort(s,i, j-t) - s = stoogesort(s,i+t,j ) - s = stoogesort(s,i, j-t) - end if - return s - end function +function stoogesort(sequence s, integer i=1, j=length(s)) + if s[j]1 then + integer t = floor((j-i+1)/3) + s = stoogesort(s,i, j-t) + s = stoogesort(s,i+t,j ) + s = stoogesort(s,i, j-t) + end if + return s +end function - ?stoogesort(shuffle(tagset(10))) - - with javascript_semantics +with javascript_semantics - function merge(sequence left, right) - sequence result = {} - while length(left)>0 - and length(right)>0 do - if left[$]<=right[1] then - exit - elsif right[$]<=left[1] then - return result & right & left - elsif left[1]<right[1] then - result = append(result,left[1]) - left = left[2..$] - else - result = append(result,right[1]) - right = right[2..$] - end if - end while - return result & left & right - end function +function merge(sequence left, right) + sequence result = {} + while length(left)>0 + and length(right)>0 do + if left[$]<=right[1] then + exit + elsif right[$]<=left[1] then + return result & right & left + elsif left[1]function
    strand_sort(sequence s) - sequence result = {} - while length(s)>0 do - integer j = length(s) - for i=1 to length(s)-1 do - if s[i]>s[i+1] then - j = i - exit - end if - end for - result = merge(result,s[1..j]) - s = s[j+1..$] - end while - return result - end function +function strand_sort(sequence s) + sequence result = {} + while length(s)>0 do + integer j = length(s) + for i=1 to length(s)-1 do + if s[i]>s[i+1] then + j = i + exit + end if + end for + result = merge(result,s[1..j]) + s = s[j+1..$] + end while + return result +end function - ?strand_sort(shuffle(tagset(10))) - - with javascript_semantics - requires("1.0.2") -- (a fix for JS) - include builtins\unicode_console.e +with javascript_semantics +requires("1.0.2") -- (a fix for JS) +include builtins\unicode_console.e - constant tests = {"0 1 19 20", "0 0 1 1", - "0 999 4000 4999 7000 7999", "1 1 2 2 3 3", - "1 2 3 4 5 6 7 8 7 6 5 4 3 2 1", - "1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5"} +constant tests = {"0 1 19 20", "0 0 1 1", + "0 999 4000 4999 7000 7999", "1 1 2 2 3 3", + "1 2 3 4 5 6 7 8 7 6 5 4 3 2 1", + "1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5"} - for i=1 to length(tests) do - sequence ti = split_any(tests[i]," ,") - for j=1 to length(ti) do - {{ti[j]}} = scanf(ti[j],"%f") - end for - atom mn = min(ti), - mx = max(ti), - range = mx-mn - printf(1,"Min :%g, Max :%g, Range :%g\n",{mn,mx,range}) +for i=1 to length(tests) do + sequence ti = split_any(tests[i]," ,") + for j=1 to length(ti) do + {{ti[j]}} = scanf(ti[j],"%f") + end for + atom mn = min(ti), + mx = max(ti), + range = mx-mn + printf(1,"Min :%g, Max :%g, Range :%g\n",{mn,mx,range}) - if unicode_console() then - for j=1 to length(ti) do - ti[j] = #2581 + min(7,floor((ti[j]-mn)/range*8)) - end for - printf(1,"%s\n",{utf32_to_utf8(ti)}) - else - puts(1,"unicode is not supported\n") - end if - end for - - integer square = 1, squared = 1*1, - cube = 1, cubed = 1*1*1, - count = 0 +integer square = 1, squared = 1*1, + cube = 1, cubed = 1*1*1, + count = 0 - while count<30 do - squared = square*square - while squared>cubed do cube += 1; cubed = cube*cube*cube end while - if squared=cubed then - printf(1,"%d: %d == %d^3\n",{square,squared,cube}) - else - count += 1 - printf(1,"%d: %d\n",{square,squared}) - end if - square += 1 - end while +while count<30 do + squared = square*square + while squared>cubed do cube += 1; cubed = cube*cube*cube end while + if squared=cubed then + printf(1,"%d: %d == %d^3\n",{square,squared,cube}) + else + count += 1 + printf(1,"%d: %d\n",{square,squared}) + end if + square += 1 +end while - printf(1,"\nThe first 15 positive integers that are both a square and a cube: \n") - ?sq_power(tagset(15),6) - - with javascript_semantics - function square_frees(atom start, finish) - sequence res = {} - integer maxprime = get_maxprime(finish) - while start<=finish do - if square_free(start,maxprime) then - res &= start - end if - start += 1 - end while - return res - end function +with javascript_semantics +function square_frees(atom start, finish) + sequence res = {} + integer maxprime = get_maxprime(finish) + while start<=finish do + if square_free(start,maxprime) then + res &= start + end if + start += 1 + end while + return res +end function - procedure show_range(atom start, finish, integer jb, string fmt) - sequence res = square_frees(start, finish) - printf(1,"There are %d square-free integers from %,d to %,d:\n%s\n", - {length(res),start,finish,join_by(res,1,jb,"","\n",fmt)}) - end procedure - show_range(1,145,20,"%4d") - show_range(1e12,1e12+145,5,"%14d") +procedure show_range(atom start, finish, integer jb, string fmt) + sequence res = square_frees(start, finish) + printf(1,"There are %d square-free integers from %,d to %,d:\n%s\n", + {length(res),start,finish,join_by(res,1,jb,"","\n",fmt)}) +end procedure +show_range(1,145,20,"%4d") +show_range(1e12,1e12+145,5,"%14d") - printf(1,"\nNumber of square-free integers:\n"); - for i=2 to 6 do - integer lim = power(10,i), - len = length(square_frees(1,lim)) - printf(1," from %,d to %,d = %,d\n", {1,lim,len}) - end for - s ) + + [] + 1000000000145 sqrt + dup eratosthenes + times + [ i^ isprime if + [ i^ dup * join ] ] + primesquares put + + [ true swap + primesquares share witheach + [ 2dup < iff + [ drop conclude ] + done + dip dup mod 0 = if + [ dip not conclude ] ] + drop ] is squarefree ( n --> b ) + + say "square-free numbers from 1 to 145" + [] 145 times + [ i^ 1+ squarefree if + [ i^ 1+ number$ nested join ] ] + 80 wrap$ + cr cr + say "square-free numbers from 1000000000000 to 1000000000145" + [] 146 times + [ i^ 1000000000000 + squarefree if + [ i^ 1000000000000 + number$ nested join ] ] + 80 wrap$ + cr cr + ' [ 100 1000 10000 100000 1000000 ] + witheach + [ say "square-free numbers from 1 to " + dup echo say ": " + 0 swap times + [ i^ 1+ squarefree + ] + echo cr ] diff --git a/Task/Square-free-integers/R/square-free-integers.r b/Task/Square-free-integers/R/square-free-integers.r new file mode 100644 index 0000000000..0986fa2ad1 --- /dev/null +++ b/Task/Square-free-integers/R/square-free-integers.r @@ -0,0 +1,14 @@ +is_squarefree <- function(n){ + limit <- floor(sqrt(n)) + squares <- if(limit>1) (2:limit)^2 else 4 + !(0 %in% (n%%squares)) +} + +list_squarefree <- function(n1, n2) Filter(is_squarefree, n1:n2) + +list_squarefree(1, 145) +print(list_squarefree(10^12, 145+10^12), digits=13) + +count_squarefree <- function(n1, n2) length(list_squarefree(n1, n2)) +test_ranges <- lapply(2:6, function(n) list(1, 10^n)) +sapply(test_ranges, function(l) do.call(count_squarefree, l)) diff --git a/Task/Square-free-integers/REXX/square-free-integers.rexx b/Task/Square-free-integers/REXX/square-free-integers.rexx index 80bf992397..eca7694a7d 100644 --- a/Task/Square-free-integers/REXX/square-free-integers.rexx +++ b/Task/Square-free-integers/REXX/square-free-integers.rexx @@ -1,35 +1,78 @@ -/*REXX program displays square─free numbers (integers > 1) up to a specified limit. */ -numeric digits 20 /*be able to handle larger numbers. */ -parse arg LO HI . /*obtain optional arguments from the CL*/ -if LO=='' | LO=="," then LO= 1 /*Not specified? Then use the default.*/ -if HI=='' | HI=="," then HI= 145 /* " " " " " " */ -sw= linesize() - 1 /*use one less than a full line. */ -# = 0 /*count of square─free numbers found. */ -$= /*variable that holds a line of numbers*/ - do j=LO to abs(HI) /*process all integers between LO & HI.*/ - if \isSquareFree(j) then iterate /*Not square─free? Then skip this #. */ - #= # + 1 /*bump the count of square─free numbers*/ - if HI<0 then iterate /*Only counting 'em? Then look for more*/ - if length($ || j)1; q= q % 4; _= x - r - q; r= r % 2 - if _>=0 then do; x= _; r= r + q; end - end /*while q>1*/ - return r /*R is the integer square root of X. */ +say 'SQUARE-FREE INTEGERS' +say version +say +numeric digits 5 +call Show 1,145 +numeric digits 15 +call Show 1000000000000,1000000000145 +numeric digits 10 +call Count1 1000000 +call Count2 1000000 +exit + +Show: +call Time('r') +arg xx,yy +say 'Square-free integers between' xx 'and' yy +r = Length(yy)+1; n = 0 +do i = xx to yy + if Squarefree(i) then do + n = n+1 + call Charout ,Right(i,r) + if n//10 = 0 then + say + end +end +say +say Format(Time('e'),,3) 'seconds' +say +return + +Count1: +call Time('r') +arg xx +say 'Number of square-free integers <= 10^n' +say 'Direct method' +say '--------------' +say Left('n',4) Right('count',6) +say '--------------' +n = 0; e = 1 +do i = 1 to xx + if i >= 1'E'e then do + say Left('10^'e,5) Right(n,8) + e = e+1 + end + if Squarefree(i) then + n = n+1 +end +say '--------------' +say Format(Time('e'),,3) 'seconds' +say +return + +Count2: +call Time('r') +arg xx +call Squarefrees xx +say 'Number of square-free integers <= 10^n' +say 'Sieve method' +say '--------------' +say Left('n',4) Right('count',6) +say '--------------' +n = 0; e = 1 +do i = 1 to xx + if i >= 1'E'e then do + say Left('10^'e,5) Right(n,8) + e = e+1 + end + if squa.flag.i then + n = n+1 +end +say '--------------' +say Format(Time('e'),,3) 'seconds' +return + +include Math diff --git a/Task/Square-free-integers/Rust/square-free-integers-1.rust b/Task/Square-free-integers/Rust/square-free-integers-1.rs similarity index 100% rename from Task/Square-free-integers/Rust/square-free-integers-1.rust rename to Task/Square-free-integers/Rust/square-free-integers-1.rs diff --git a/Task/Square-free-integers/Rust/square-free-integers-2.rust b/Task/Square-free-integers/Rust/square-free-integers-2.rs similarity index 100% rename from Task/Square-free-integers/Rust/square-free-integers-2.rust rename to Task/Square-free-integers/Rust/square-free-integers-2.rs diff --git a/Task/Square-free-integers/S-BASIC/square-free-integers.basic b/Task/Square-free-integers/S-BASIC/square-free-integers.basic new file mode 100644 index 0000000000..fdf66e8206 --- /dev/null +++ b/Task/Square-free-integers/S-BASIC/square-free-integers.basic @@ -0,0 +1,54 @@ +$lines + +$constant true = 0FFFFH +$constant false = 0 + +rem - return true if n is square-free +function SquareFree(n = integer) = integer + var i, count, result = integer + i = 2 + result = true + rem - decompose n into its prime factors + while (i*i) <= n and result <> false do + begin + count = 0 + while n - (n / i) * i = 0 do + begin + count = count + 1 + n = n / i + end + rem - not square-free if a divisor was repeated + if count > 1 then result = false + i = i + 1 + end +end = result + +rem - demonstrate the function + +var i, found = integer + +print "Showing square-free numbers between 1 and 145" +for i = 1 to 145 + if SquareFree(i) then print using "### ";i; +next i +print + +found = 0 +for i = 1 to 100 + if SquareFree(i) then found = found + 1 +next i +print "Square-free numbers between 1 and 100 ="; found + +found = 0 +for i = 1 to 1000 + if SquareFree(i) then found = found + 1 +next i +print "Square-free numbers between 1 and 1,000 ="; found + +found = 0 +for i = 1 to 10000 + if SquareFree(i) then found = found + 1 +next i +print "Square-free numbers between 1 and 10,000 ="; found + +end diff --git a/Task/Square-free-integers/SETL/square-free-integers.setl b/Task/Square-free-integers/SETL/square-free-integers.setl new file mode 100644 index 0000000000..ef1231063e --- /dev/null +++ b/Task/Square-free-integers/SETL/square-free-integers.setl @@ -0,0 +1,45 @@ +program square_free_integers; + show_square_frees([1..145]); + show_square_frees([1000000000000..1000000000145]); + count_square_frees(); + + proc count_square_frees(); + loop init + limit := 100; + count := 0; + n := 1; + while limit <= 1000000 do + if n = limit then + print(str count + " square free numbers <= " + str limit); + limit *:= 10; + end if; + if square_free(n) then + count +:= 1; + end if; + n +:= 1; + end loop; + end proc; + + proc show_square_frees(nums); + loop for n in nums do + if square_free(n) then + nprint(lpad(str n, 15)); + if (col +:= 1) mod 5 = 0 then + print; + end if; + end if; + end loop; + print; + end proc; + + proc square_free(n); + loop init r := 2; + while r*r <= n do + if n mod (r*r) = 0 then + return False; + end if; + r +:= 1; + end loop; + return True; + end proc; +end program; diff --git a/Task/Square-free-integers/Uiua/square-free-integers.uiua b/Task/Square-free-integers/Uiua/square-free-integers.uiua new file mode 100644 index 0000000000..2982cc9712 --- /dev/null +++ b/Task/Square-free-integers/Uiua/square-free-integers.uiua @@ -0,0 +1,7 @@ +Sqf ← ≠0/↧◿⊸(˙×↘2⇡+1⌊√) +⧻⟜▽⊸≡Sqf +1⇡145 +⧻⟜▽⊸≡Sqf +1e12+1⇡145 +# Find all squares and their multiples, mask them out. +⍉▽>0/↧⊸⊞◿⊃(˙ט▽⟜=⟜(⊣°/×)↘2⇡⌊+1√|↘1⇡)2000000 +# Count them. +≡(⧻▽⊸≤)⊢[⍥⊸×₁₀ 5 100]¤ diff --git a/Task/Square-free-integers/XPL0/square-free-integers.xpl0 b/Task/Square-free-integers/XPL0/square-free-integers.xpl0 new file mode 100644 index 0000000000..9f0aee1391 --- /dev/null +++ b/Task/Square-free-integers/XPL0/square-free-integers.xpl0 @@ -0,0 +1,47 @@ +func SqFree(N); \Return 'true' if N is square-free +real N, D2; +int D; +[for D:= 2 to 1000 do \sqrt one million + [D2:= float(D*D); + if fix(Mod(N, D2)) = 0 then return false; + if D > 2 then D:= D+1; \(doubles speed to 19.5 sec) + ]; +return true; +]; + +int Num, Count, Limit; +real T; +[Format(3, 0); +Count:= 0; +for Num:= 1 to 145 do + [if SqFree(float(Num)) then + [Count:= Count+1; + RlOut(0, float(Num)); + if rem(Count/20) then ChOut(0, ^ ) else CrLf(0); + ]; + ]; +CrLf(0); CrLf(0); + +Count:= 0; +for Num:= 0 to 145 do + [T:= float(Num) + 1e12; + if SqFree(T) then + [RlOut(0, T); + Count:= Count+1; + if rem(Count/5) then ChOut(0, ^ ) else CrLf(0); + ]; + ]; +CrLf(0); CrLf(0); + +Limit:= 100; +loop [Count:= 0; + for Num:= 1 to Limit do + [T:= float(Num); + if SqFree(T) then Count:= Count+1; + ]; + Text(0, "Square-free integers up to "); IntOut(0, Limit); + Text(0, ": "); IntOut(0, Count); CrLf(0); + if Limit = 1_000_000 then quit; + Limit:= Limit * 10; + ]; +] diff --git a/Task/Stable-marriage-problem/EasyLang/stable-marriage-problem.easy b/Task/Stable-marriage-problem/EasyLang/stable-marriage-problem.easy new file mode 100644 index 0000000000..54cc1b7c80 --- /dev/null +++ b/Task/Stable-marriage-problem/EasyLang/stable-marriage-problem.easy @@ -0,0 +1,157 @@ +mnam$[] = strsplit input " " +n = len mnam$[] +wnam$[] = strsplit input " " +len mlike[][] n +len wlike[][] n +func finds name$[] s$ . + for i to len name$[] + if name$[i] = s$ + return i + . + . +. +proc read . + s$ = input + s$ = s$ + for m to n + h$[] = strsplit input " " + len mlike[m][] n + for j = 1 to n + mlike[m][finds wnam$[] h$[j + 1]] = n - j + 1 + . + . + s$ = input + for w to n + h$[] = strsplit input " " + len wlike[w][] n + for j = 1 to n + wlike[w][finds mnam$[] h$[j + 1]] = n - j + 1 + . + . +. +read +# +len meng[] n +len weng[] n +len wcand[][] n +# +proc engagements . + print "Engagements:" + for m to n + w = 1 + for i to n + if mlike[m][i] > mlike[m][w] + w = i + . + . + mlike[m][w] *= -1 + wcand[w][] &= m + . + for w to n + if len wcand[w][] > 0 + m = wcand[w][1] + for h in wcand[w][] + if wlike[w][h] > wlike[w][m] + m = h + . + . + print " " & wnam$[w] & " + " & mnam$[m] + meng[m] = w + weng[w] = m + . + . + print "" + while done = 0 + done = 1 + for m to n + if meng[m] = 0 + done = 0 + w = 1 + for i to n + if mlike[m][i] > mlike[m][w] + w = i + . + . + mlike[m][w] *= -1 + if weng[w] = 0 + meng[m] = w + weng[w] = m + print " " & wnam$[w] & " + " & mnam$[m] + else + h = weng[w] + if wlike[w][h] < wlike[w][m] + print " " & wnam$[w] & " + " & mnam$[m] & " (dumped " & mnam$[h] & ")" + meng[h] = 0 + weng[w] = m + meng[m] = w + . + . + . + . + . + print "" +. +engagements +# +proc showcouples . + print "Couples:" + for w to n + print " " & wnam$[w] & " + " & mnam$[weng[w]] + . + print "" +. +proc swapw a b . + print wnam$[a] & " and " & wnam$[b] & " swap their partners" + print "" + swap weng[a] weng[b] + swap meng[weng[a]] meng[weng[b]] +. +proc checkstable . + for m to n + w = meng[m] + for w1 to n + if abs mlike[m][w1] > abs mlike[m][w] + if wlike[w1][m] > wlike[w1][weng[w1]] + cnt += 1 + print "Unstable: " & wnam$[w1] & " and " & mnam$[m] + . + . + . + . + if cnt = 0 + print "The couples are stable" + . + print "" +. +showcouples +checkstable +swapw 3 9 +showcouples +checkstable +# +# +input_data +abe bob col dan ed fred gav hal ian jon +abi bea cath dee eve fay gay hope ivy jan + +abe: abi eve cath ivy jan dee fay bea hope gay +bob: cath hope abi dee eve fay bea jan ivy gay +col: hope eve abi dee bea fay ivy gay cath jan +dan: ivy fay dee gay hope eve jan bea cath abi +ed: jan dee bea cath fay eve abi ivy hope gay +fred: bea abi dee gay eve ivy cath jan hope fay +gav: gay eve ivy bea cath abi dee hope jan fay +hal: abi eve hope fay ivy cath jan bea gay dee +ian: hope cath dee gay bea abi fay ivy jan eve +jon: abi fay jan gay eve bea dee cath ivy hope + +abi: bob fred jon gav ian abe dan ed col hal +bea: bob abe col fred gav dan ian ed jon hal +cath: fred bob ed gav hal col ian abe dan jon +dee: fred jon col abe ian hal gav dan bob ed +eve: jon hal fred dan abe gav col ed ian bob +fay: bob abe ed ian jon dan fred gav col hal +gay: jon gav hal fred bob abe col ed dan ian +hope: gav jon bob abe ian dan hal ed col fred +ivy: ian col hal gav fred bob abe ed jon dan +jan: ed hal gav abe bob jon col ian fred dan diff --git a/Task/Stable-marriage-problem/Fortran/stable-marriage-problem.f b/Task/Stable-marriage-problem/Fortran/stable-marriage-problem.f new file mode 100644 index 0000000000..7bdae8ac2c --- /dev/null +++ b/Task/Stable-marriage-problem/Fortran/stable-marriage-problem.f @@ -0,0 +1,142 @@ +program stable_marriage + implicit none + integer, parameter :: n = 10 + integer :: mens_pref(n, n), womens_pref(n, n) + integer :: mens_rank(n, n), womens_rank(n, n) + integer :: wife(n), husband(n), next_prop(n) + logical :: free_men(n) + character(len=4) :: men_names(n), women_names(n) + integer :: m, w, p, h, i, curr_w, w1, w2 + logical :: is_stable + + ! Names + men_names = ['abe ', 'bob ', 'col ', 'dan ', 'ed ', 'fred', 'gav ', 'hal ', 'ian ', 'jon '] + women_names = ['abi ', 'bea ', 'cath', 'dee ', 'eve ', 'fay ', 'gay ', 'hope', 'ivy ', 'jan '] + + ! Men's preferences + mens_pref(1, :) = [1, 5, 3, 9, 10, 4, 6, 2, 8, 7] + mens_pref(2, :) = [3, 8, 1, 4, 5, 6, 2, 10, 9, 7] + mens_pref(3, :) = [8, 5, 1, 4, 2, 6, 9, 7, 3, 10] + mens_pref(4, :) = [9, 6, 4, 7, 8, 5, 10, 2, 3, 1] + mens_pref(5, :) = [10, 4, 2, 3, 6, 5, 1, 9, 8, 7] + mens_pref(6, :) = [2, 1, 4, 7, 5, 9, 3, 10, 8, 6] + mens_pref(7, :) = [7, 5, 9, 2, 3, 1, 4, 8, 10, 6] + mens_pref(8, :) = [1, 5, 8, 6, 9, 3, 10, 2, 7, 4] + mens_pref(9, :) = [8, 3, 4, 7, 2, 1, 6, 9, 10, 5] + mens_pref(10, :) = [1, 6, 10, 7, 5, 2, 4, 3, 9, 8] + + ! Women's preferences + womens_pref(1, :) = [2, 6, 10, 7, 9, 1, 4, 5, 3, 8] + womens_pref(2, :) = [2, 1, 3, 6, 7, 4, 9, 5, 10, 8] + womens_pref(3, :) = [6, 2, 5, 7, 8, 3, 9, 1, 4, 10] + womens_pref(4, :) = [6, 10, 3, 1, 9, 8, 7, 4, 2, 5] + womens_pref(5, :) = [10, 8, 6, 4, 1, 7, 3, 5, 9, 2] + womens_pref(6, :) = [2, 1, 5, 9, 10, 4, 6, 7, 3, 8] + womens_pref(7, :) = [10, 7, 8, 6, 2, 1, 3, 5, 4, 9] + womens_pref(8, :) = [7, 10, 2, 1, 9, 4, 8, 5, 3, 6] + womens_pref(9, :) = [9, 3, 8, 7, 6, 2, 1, 5, 10, 4] + womens_pref(10, :) = [5, 8, 7, 1, 2, 10, 3, 9, 6, 4] + + ! Build rank matrices + mens_rank = 0 + do m = 1, n + do p = 1, n + w = mens_pref(m, p) + mens_rank(m, w) = p + end do + end do + womens_rank = 0 + do w = 1, n + do p = 1, n + m = womens_pref(w, p) + womens_rank(w, m) = p + end do + end do + + ! Gale-Shapley algorithm + wife = 0 + husband = 0 + next_prop = 1 + free_men = .true. + do while (any(free_men)) + do m = 1, n + if (.not. free_men(m)) cycle + if (next_prop(m) > n) cycle + w = mens_pref(m, next_prop(m)) + next_prop(m) = next_prop(m) + 1 + if (husband(w) == 0) then + husband(w) = m + wife(m) = w + free_men(m) = .false. + else + h = husband(w) + if (womens_rank(w, m) < womens_rank(w, h)) then + husband(w) = m + wife(m) = w + free_men(m) = .false. + wife(h) = 0 + free_men(h) = .true. + end if + end if + end do + end do + + ! Print stable matching + print *, 'Stable matching:' + do m = 1, n + print *, trim(men_names(m)), ' - ', trim(women_names(wife(m))) + end do + + ! Check stability of stable matching + is_stable = .true. + do m = 1, n + curr_w = wife(m) + do i = 1, mens_rank(m, curr_w) - 1 + w = mens_pref(m, i) + h = husband(w) + if (womens_rank(w, m) < womens_rank(w, h)) then + is_stable = .false. + end if + end do + end do + if (is_stable) then + print *, 'The matching is stable.' + else + print *, 'The matching is not stable.' + end if + + ! Perturb the matching (swap abe and bob's partners) + w1 = wife(1) + w2 = wife(2) + wife(1) = w2 + wife(2) = w1 + husband(w1) = 2 + husband(w2) = 1 + + ! Print perturbed matching + print *, '' + print *, 'Perturbed matching: (swap abe and bob''s partners)' + do m = 1, n + print *, trim(men_names(m)), ' - ', trim(women_names(wife(m))) + end do + + ! Check stability of perturbed matching + is_stable = .true. + check_loop: do m = 1, n + curr_w = wife(m) + do i = 1, mens_rank(m, curr_w) - 1 + w = mens_pref(m, i) + h = husband(w) + if (womens_rank(w, m) < womens_rank(w, h)) then + is_stable = .false. + print *, 'Unstable because ', trim(men_names(m)), ' and ', trim(women_names(w)), & + ' prefer each other while ', trim(men_names(h)), ' and ', trim(women_names(curr_w)), ' prefer each other' + exit check_loop ! Show one blocking pair + end if + end do + end do check_loop + if (is_stable) then + print *, 'The perturbed matching is stable.' + end if + +end program stable_marriage diff --git a/Task/Stable-marriage-problem/FreeBASIC/stable-marriage-problem.basic b/Task/Stable-marriage-problem/FreeBASIC/stable-marriage-problem.basic new file mode 100644 index 0000000000..0af0bb4fe7 --- /dev/null +++ b/Task/Stable-marriage-problem/FreeBASIC/stable-marriage-problem.basic @@ -0,0 +1,84 @@ +Const n As Integer = 10 + +Dim As Integer i, m, w, o, a, b +Dim Shared As Integer mpartner(n), wpartner(n), proposed(n, n) +Dim Shared As String mpref(n), wname(n), wpref(n), mname(n) + +Data "AECIJDFBHG","CHADEFBJIG","HEADBFIGCJ","IFDGHEJBCA","JDBCFEAIHG","BADGEICJHF","GEIBCADHJF","AEHFICJBGD","HCDGBAFIJE","AFJGEBDCIH" +For i = 1 To n: Read mpref(i): Next +Data "Abi","Bea","Cath","Dee","Eve","Fay","Gay","Hope","Ivy","Jan" +For i = 1 To n: Read wname(i): Next +Data "BFJGIADECH","BACFGDIEJH","FBEGHCIADJ","FJCAIHGDBE","JHFDAGCEIB","BAEIJDFGCH","JGHFBACEDI","GJBAIDHECF","ICHGFBAEJD","EHGABJCIFD" +For i = 1 To n: Read wpref(i): Next +Data "Abe","Bob","Col","Dan","Ed","Fred","Gav","Hal","Ian","Jon" +For i = 0 To n: Read mname(i): Next + +Function isStable() As Boolean + Dim As Integer m, w, o, p + For m = 1 To n + w = mpartner(m) + For o = 1 To n + p = wpartner(o) + If Instr(mpref(m), Left(wname(o), 1)) < Instr(mpref(m), Left(wname(w), 1)) And _ + Instr(wpref(o), Left(mname(m), 1)) < Instr(wpref(o), Left(mname(p), 1)) Then + Return False + End If + Next o + Next m + Return True +End Function + +Function arraySum(arr() As Integer) As Integer + Dim total As Integer = 0 + For i As Integer = Lbound(arr) To Ubound(arr) + total += arr(i) + Next + Return total +End Function + +' The Gale-Shapley algorithm +Do + For m = 1 To n + Do + If mpartner(m) <> 0 Then Exit Do + For i = 1 To n + w = Asc(Mid(mpref(m), i, 1)) - 64 + If proposed(m, w) = 0 Then Exit For + Next i + If i > n Then Exit Do + proposed(m, w) = 1 + If wpartner(w) = 0 Then + mpartner(m) = w + wpartner(w) = m + Else + o = wpartner(w) + If Instr(wpref(w), Left(mname(m), 1)) < Instr(wpref(w), Left(mname(o), 1)) Then + mpartner(o) = 0 + mpartner(m) = w + wpartner(w) = m + End If + End If + Loop + Next m +Loop Until arraySum(mpartner()) = (n * (n + 1)) \ 2 + +For m = 1 To n + Print mname(m) & " is engaged to " & wname(mpartner(m)) +Next +Print "Relationships are "; +Print Iif(isStable(), "stable.", "unstable.") + +Randomize Timer +a = Int(Rnd * n) + 1 +Do + b = Int(Rnd * n) + 1 +Loop Until b <> a + +Print !"\nNow exchanging the pairs of " & mname(a) & " and " & mname(b) & ":" +Swap mpartner(a), mpartner(b) +Print mname(a) & " is engaged to " & wname(mpartner(a)) +Print mname(b) & " is engaged to " & wname(mpartner(b)) +Print "Relationships are "; +Print Iif(isStable(), "stable.", "unstable.") + +Sleep diff --git a/Task/Stable-marriage-problem/Julia/stable-marriage-problem.julia b/Task/Stable-marriage-problem/Julia/stable-marriage-problem.jl similarity index 100% rename from Task/Stable-marriage-problem/Julia/stable-marriage-problem.julia rename to Task/Stable-marriage-problem/Julia/stable-marriage-problem.jl diff --git a/Task/Stable-marriage-problem/Kotlin/stable-marriage-problem.kotlin b/Task/Stable-marriage-problem/Kotlin/stable-marriage-problem.kts similarity index 100% rename from Task/Stable-marriage-problem/Kotlin/stable-marriage-problem.kotlin rename to Task/Stable-marriage-problem/Kotlin/stable-marriage-problem.kts diff --git a/Task/Stable-marriage-problem/M2000-Interpreter/stable-marriage-problem.m2000 b/Task/Stable-marriage-problem/M2000-Interpreter/stable-marriage-problem.m2000 new file mode 100644 index 0000000000..beec509da9 --- /dev/null +++ b/Task/Stable-marriage-problem/M2000-Interpreter/stable-marriage-problem.m2000 @@ -0,0 +1,95 @@ +Module Stable_marriage_problem { + enum men {abe=0, bob, col, dan, ed, fred, gav, hal, ian, jon} + enum women {abi=0, bea, cath, dee, eve, fay, gay, hope, ivy, jan} + gosub fillarrays + engage=list + function fill(n, v) { + dim a(n) as boolean=v + =a() + } + mfree=fill(10, true) + wfree=fill(10, true) + md=men + mw=women + while mfree#have(true) + m=mfree#pos(true) + w=pw#val(m)#val(0) + md=m + mw=w + if wfree#val(w) then + md=m + mw=w + return wfree, w:=false + return mfree, m:=false + pp=pw#val(m) + if len(pp)=1 then + return pw, m:=(,) + else + return pw, m:=pp#slice(1,) + end if + append engage, w:=m + else.if exist(engage, w) then + mm=eval(engage) + if (pm#val(w)#pos(m))<(pm#val(w)#pos(mm)) then + md=m + md=mm + return engage, w:=m + return mfree, mm:=true, m:=false + else + md=mm + mw=w + pp=pw#val(m) + if len(pp)=1 then + return pw, m:=(,) + else + return pw, m:=pp#slice(1,) + end if + end if + end if + end while + kk=each(engage) + list1=list + while kk + md=eval(kk) + mw=val(eval$(kk!)) + append list1, eval$(mw)+" and "+eval$(md)+"." + end while + sort list1 + kk=each(list1) + document kkk$ + Print "NEWLYWEDS:" + while kk + kkk$=format$("{0::-2}.{1}",kk^+1, eval$(kk))+{ + } + print format$("{0::-2}.{1}",kk^+1, eval$(kk)) + end while + clipboard kkk$ + + end + fillarrays: + flush ' empty stack of values + data (abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay) + data (cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay) + data (hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan) + data (ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi) + data (jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay) + data (bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay) + data (gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay) + data (abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee) + data (hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve) + data (abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope) + pw=array([]) ' we get array of arrays + data (bob, fred, jon, gav, ian, abe, dan, ed, col, hal) + data (bob, abe, col, fred, gav, dan, ian, ed, jon, hal) + data (fred, bob, ed, gav, hal, col, ian, abe, dan, jon) + data (fred, jon, col, abe, ian, hal, gav, dan, bob, ed) + data (jon, hal, fred, dan, abe, gav, col, ed, ian, bob) + data (bob, abe, ed, ian, jon, dan, fred, gav, col, hal) + data (jon, gav, hal, fred, bob, abe, col, ed, dan, ian) + data (gav, jon, bob, abe, ian, dan, hal, ed, col, fred) + data (ian, col, hal, gav, fred, bob, abe, ed, jon, dan) + data (ed, hal, gav, abe, bob, jon, col, ian, fred, dan) + pm=array([]) + return +} +Stable_marriage_problem diff --git a/Task/Stable-marriage-problem/OCaml/stable-marriage-problem.ocaml b/Task/Stable-marriage-problem/OCaml/stable-marriage-problem.ml similarity index 100% rename from Task/Stable-marriage-problem/OCaml/stable-marriage-problem.ocaml rename to Task/Stable-marriage-problem/OCaml/stable-marriage-problem.ml diff --git a/Task/Stable-marriage-problem/PowerShell/stable-marriage-problem.psh b/Task/Stable-marriage-problem/PowerShell/stable-marriage-problem.ps1 similarity index 100% rename from Task/Stable-marriage-problem/PowerShell/stable-marriage-problem.psh rename to Task/Stable-marriage-problem/PowerShell/stable-marriage-problem.ps1 diff --git a/Task/Stable-marriage-problem/Rust/stable-marriage-problem.rs b/Task/Stable-marriage-problem/Rust/stable-marriage-problem.rs new file mode 100644 index 0000000000..1c4e6fd256 --- /dev/null +++ b/Task/Stable-marriage-problem/Rust/stable-marriage-problem.rs @@ -0,0 +1,144 @@ +use std::collections::HashMap; + +fn matchmaker( + men_preferences: &HashMap>, + women_preferences: &HashMap>, +) -> HashMap { + + let mut free_men: Vec = men_preferences.keys().cloned().collect(); + let mut engaged: HashMap = HashMap::new(); + + // cloning for immutability of original data + let mut men_preferences = men_preferences.clone(); + let women_preferences = women_preferences.clone(); + + while !free_men.is_empty() { + let man = free_men.remove(0); + + if let Some(proposal_list) = men_preferences.get_mut(&man) { + + if let Some(woman) = proposal_list.first().cloned() { + proposal_list.remove(0); + // checking for existence of husband + if let Some(current_partner) = engaged.get(&woman).cloned() { + let men_list = &women_preferences[&woman]; + + // checking if the current partner is better than the new partner + if men_list.iter().position(|m| m == ¤t_partner).unwrap() > men_list.iter().position(|g| g == &man).unwrap() { + //prefers new person, dumping old partner + engaged.insert(woman.clone(), man.clone()); + + // free the current partner + free_men.push(current_partner.clone()); + } + else { + // prefers current partner, so no change, adding man back to list + free_men.push(man.clone()); + } + } + // no current partner, so engage + else { + engaged.insert(woman.clone(),man.clone()); + } + } + } + } +engaged +} + +fn check_engagement( + engaged: &HashMap, + men_preferences: &HashMap>, + women_preferences: &HashMap>, +) -> bool { + let inverse_engaged: HashMap = engaged.iter().map(|(k, v)| (v.clone(), k.clone())).collect(); + + for (wife, husband) in engaged { + let women_prefers = &women_preferences[wife]; + let better_candidates_woman: Vec<&String> = women_prefers.iter().take_while(|&m| m != husband).collect(); + + let man_prefers = &men_preferences[husband]; + let better_candidates_man: Vec<&String> = man_prefers.iter().take_while(|&g| g != wife).collect(); + + for man in better_candidates_woman { + if let Some(engaged_gal) = inverse_engaged.get(man) { + let preferred_women = &men_preferences[man]; + + if preferred_women.iter().position(|w| w == engaged_gal).unwrap() > preferred_women.iter().position(|w| w == wife).unwrap() { + println!("{} and {} like each other better than their present partners: {} and {}, respectively", + wife, man, husband, engaged_gal); + return false; + } + } + } + + for woman in better_candidates_man { + if let Some(engaged_guy) = engaged.get(woman) { + let preferred_men = &women_preferences[woman]; + + if preferred_men.iter().position(|m| m == engaged_guy).unwrap() > preferred_men.iter().position(|m| m == husband).unwrap() { + println!("{} and {} like each other better than their present partners: {} and {}, respectively", + husband,woman, wife, engaged_guy); + return false; + } + } + } + } + true +} +fn main() { + let mut men_preferences: HashMap> = [ + ("abe", vec!["abi", "eve", "cath", "ivy", "jan", "dee", "fay", "bea", "hope", "gay"]), + ("bob", vec!["cath", "hope", "abi", "dee", "eve", "fay", "bea", "jan", "ivy", "gay"]), + ("col", vec!["hope", "eve", "abi", "dee", "bea", "fay", "ivy", "gay", "cath", "jan"]), + ("dan", vec!["ivy", "fay", "dee", "gay", "hope", "eve", "jan", "bea", "cath", "abi"]), + ("ed", vec!["jan", "dee", "bea", "cath", "fay", "eve", "abi", "ivy", "hope", "gay"]), + ("fred", vec!["bea", "abi", "dee", "gay", "eve", "ivy", "cath", "jan", "hope", "fay"]), + ("gav", vec!["gay", "eve", "ivy", "bea", "cath", "abi", "dee", "hope", "jan", "fay"]), + ("hal", vec!["abi", "eve", "hope", "fay", "ivy", "cath", "jan", "bea", "gay", "dee"]), + ("ian", vec!["hope", "cath", "dee", "gay", "bea", "abi", "fay", "ivy", "jan", "eve"]), + ("jon", vec!["abi", "fay", "jan", "gay", "eve", "bea", "dee", "cath", "ivy", "hope"]), + ].iter().map(|(k, v)| (k.to_string(), v.iter().map(|&s| s.to_string()).collect())).collect(); + + let women_preferences: HashMap> = [ + ("abi", vec!["bob", "fred", "jon", "gav", "ian", "abe", "dan", "ed", "col", "hal"]), + ("bea", vec!["bob", "abe", "col", "fred", "gav", "dan", "ian", "ed", "jon", "hal"]), + ("cath", vec!["fred", "bob", "ed", "gav", "hal", "col", "ian", "abe", "dan", "jon"]), + ("dee", vec!["fred", "jon", "col", "abe", "ian", "hal", "gav", "dan", "bob", "ed"]), + ("eve", vec!["jon", "hal", "fred", "dan", "abe", "gav", "col", "ed", "ian", "bob"]), + ("fay", vec!["bob", "abe", "ed", "ian", "jon", "dan", "fred", "gav", "col", "hal"]), + ("gay", vec!["jon", "gav", "hal", "fred", "bob", "abe", "col", "ed", "dan", "ian"]), + ("hope", vec!["gav", "jon", "bob", "abe", "ian", "dan", "hal", "ed", "col", "fred"]), + ("ivy", vec!["ian", "col", "hal", "gav", "fred", "bob", "abe", "ed", "jon", "dan"]), + ("jan", vec!["ed", "hal", "gav", "abe", "bob", "jon", "col", "ian", "fred", "dan"]), + ].iter().map(|(k, v)| (k.to_string(), v.iter().map(|&s| s.to_string()).collect())).collect(); + + println!("\nEngagements:"); + let engaged = matchmaker(&men_preferences, &women_preferences); + println!(" {:?}", engaged.clone()); + + println!("\nCouples:"); + for (gal, guy) in engaged.iter() { + println!(" {} is engaged to {}", gal, guy); + } + + println!("\nEngagement stability check {}", + if check_engagement(&engaged, &men_preferences, &women_preferences) { "PASSED" } else { "FAILED" }); + + println!("\n\nSwapping two fiances to introduce an error"); + let women: Vec = women_preferences.keys().cloned().collect(); + + + let mut engaged = engaged; + let (woman1, woman2) = (women[0].clone(), women[1].clone()); + let temp = engaged[&woman1].clone(); + + println!(" {} is now engaged to {}", &woman1, engaged[&woman1]); + + engaged.insert(woman1.clone(), engaged[&woman2].clone()); + engaged.insert(woman2.clone(), temp); + + + println!("\nEngagement stability check {}", + if check_engagement(&engaged, &men_preferences, &women_preferences) { "PASSED" } else { "FAILED" }); +} diff --git a/Task/Stack-traces/Ada/stack-traces.ada b/Task/Stack-traces/Ada/stack-traces.adb similarity index 100% rename from Task/Stack-traces/Ada/stack-traces.ada rename to Task/Stack-traces/Ada/stack-traces.adb diff --git a/Task/Stack-traces/Crystal/stack-traces.cr b/Task/Stack-traces/Crystal/stack-traces.cr new file mode 100644 index 0000000000..65ff100a45 --- /dev/null +++ b/Task/Stack-traces/Crystal/stack-traces.cr @@ -0,0 +1,15 @@ +def method1 + method2 +end + +def method2 + puts caller.join("\n") +end + +def method0 + method1 +end + +puts "-------" +method0 +puts "-------" diff --git a/Task/Stack-traces/Elena/stack-traces.elena b/Task/Stack-traces/Elena/stack-traces.elena index f8fb7180e6..a17a5f84a5 100644 --- a/Task/Stack-traces/Elena/stack-traces.elena +++ b/Task/Stack-traces/Elena/stack-traces.elena @@ -1,10 +1,10 @@ import extensions; -public singleton program +public singleton Program { inner() { - console.printLine(new CallStack()) + Console.printLine(new CallStack()) } middle() @@ -20,6 +20,6 @@ public singleton program // program entry point function() { - program.outer() + Program.outer() } } diff --git a/Task/Stack-traces/Elixir/stack-traces.elixir b/Task/Stack-traces/Elixir/stack-traces.ex similarity index 100% rename from Task/Stack-traces/Elixir/stack-traces.elixir rename to Task/Stack-traces/Elixir/stack-traces.ex diff --git a/Task/Stack-traces/FutureBasic/stack-traces.basic b/Task/Stack-traces/FutureBasic/stack-traces.basic new file mode 100644 index 0000000000..29325975d7 --- /dev/null +++ b/Task/Stack-traces/FutureBasic/stack-traces.basic @@ -0,0 +1,14 @@ +output file @"Rosetta Code Stack Traces" + +include "NSLog.incl" + +void local fn StackTrace + CFArrayRef stackSymbols = fn ThreadCallStackSymbols + for CFStringRef symbol in stackSymbols + NSLog( @"%@", symbol ) + next +end fn + +fn StackTrace + +HandleEvents diff --git a/Task/Stack-traces/Julia/stack-traces.julia b/Task/Stack-traces/Julia/stack-traces.jl similarity index 100% rename from Task/Stack-traces/Julia/stack-traces.julia rename to Task/Stack-traces/Julia/stack-traces.jl diff --git a/Task/Stack-traces/Kotlin/stack-traces.kotlin b/Task/Stack-traces/Kotlin/stack-traces.kts similarity index 100% rename from Task/Stack-traces/Kotlin/stack-traces.kotlin rename to Task/Stack-traces/Kotlin/stack-traces.kts diff --git a/Task/Stack-traces/OCaml/stack-traces-1.ocaml b/Task/Stack-traces/OCaml/stack-traces-1.ml similarity index 100% rename from Task/Stack-traces/OCaml/stack-traces-1.ocaml rename to Task/Stack-traces/OCaml/stack-traces-1.ml diff --git a/Task/Stack-traces/OCaml/stack-traces-2.ocaml b/Task/Stack-traces/OCaml/stack-traces-2.ml similarity index 100% rename from Task/Stack-traces/OCaml/stack-traces-2.ocaml rename to Task/Stack-traces/OCaml/stack-traces-2.ml diff --git a/Task/Stack-traces/PascalABC.NET/stack-traces.pas b/Task/Stack-traces/PascalABC.NET/stack-traces.pas new file mode 100644 index 0000000000..e43d36da47 --- /dev/null +++ b/Task/Stack-traces/PascalABC.NET/stack-traces.pas @@ -0,0 +1,14 @@ +procedure qqq; +begin + var st := new System.Diagnostics.StackTrace(); + Print(st); +end; + +procedure ppp; +begin + qqq; +end; + +begin + ppp +end. diff --git a/Task/Stack-traces/Uxntal/stack-traces.uxnatl b/Task/Stack-traces/Uxntal/stack-traces.uxnatl new file mode 100644 index 0000000000..481d2799aa --- /dev/null +++ b/Task/Stack-traces/Uxntal/stack-traces.uxnatl @@ -0,0 +1,51 @@ +%\n { 0a } +%\s { 20 } +%\0 { 00 } +%DBG { [ LIT2 -True -System/debug ] DEO } +%newline { [ LIT2 \n -Console/write ] DEO } + +|1 @True +|0e @System/debug $1 +|18 @Console/write $1 + +|100 + +foo +DBG + +BRK + +@foo ( -- ) + #c0de + ;msgs/foo print/dbg + DBG newline + bar + JMP2r + +@bar ( -- ) + #cafe + ;msgs/bar print/dbg + DBG newline + baz + JMP2r + +@baz ( -- ) + #f00d + ;msgs/baz print/dbg + DBG newline + JMP2r + +@print/str ( str* -- ) + LDAk .Console/write DEO + INC2 LDAk ?/str + POP2 JMP2r + +@print/dbg ( str* -- ) + ;msgs/inside /str + ( str* ) !/str + +@msgs [ + &inside "Inside \s "of: \s \0 + &foo "foo. \n \0 + &bar "bar. \n \0 + &baz "baz. \n \0 ] diff --git a/Task/Stack/68000-Assembly/stack-1.68000 b/Task/Stack/68000-Assembly/stack-1.68000 index 8e778da8e3..a2efe823dd 100644 --- a/Task/Stack/68000-Assembly/stack-1.68000 +++ b/Task/Stack/68000-Assembly/stack-1.68000 @@ -1,2 +1,3 @@ -LEA userStack,A0 ;initialize the user stack, points to a memory address in user RAM. Only do this once! -MOVEM.L D0-D3,-(A0) ;moves the full 32 bits of registers D0,D1,D2,D3 into the address pointed by A0, with pre-decrement +LEA userStack,A0 ;initialize the user stack, points to a memory address in user RAM. Only do this once! +MOVEM.L D0-D3,-(A0) ;moves the full 32 bits of registers D0,D1,D2,D3 into the address pointed by A0, + ;with pre-decrement diff --git a/Task/Stack/Ada/stack-1.ada b/Task/Stack/Ada/stack-1.adb similarity index 100% rename from Task/Stack/Ada/stack-1.ada rename to Task/Stack/Ada/stack-1.adb diff --git a/Task/Stack/Ada/stack-2.ada b/Task/Stack/Ada/stack-2.adb similarity index 100% rename from Task/Stack/Ada/stack-2.ada rename to Task/Stack/Ada/stack-2.adb diff --git a/Task/Stack/ArkScript/stack.ark b/Task/Stack/ArkScript/stack.ark new file mode 100644 index 0000000000..d199ce5f2e --- /dev/null +++ b/Task/Stack/ArkScript/stack.ark @@ -0,0 +1,26 @@ +(let stack (fun () { + (mut data []) + + (let push (fun (value) (set data (concat [value] data)))) + (let popTop (fun () { + (let res (head data)) + (pop! data 0) + res })) + (let isEmpty? (fun () (empty? data))) + + (fun (&data &push &popTop &isEmpty?) ()) })) + +(let myStack (stack)) +(myStack.push 1) +(myStack.push 2) +(myStack.push 3) + +(print myStack.data) + +(print "top: " (myStack.popTop)) +(print myStack.data) + +(print "empty: " (myStack.isEmpty?)) +(myStack.popTop) +(myStack.popTop) +(print "empty: " (myStack.isEmpty?)) diff --git a/Task/Stack/Arturo/stack.arturo b/Task/Stack/Arturo/stack.arturo index cefaf94ec5..12038bf2dd 100644 --- a/Task/Stack/Arturo/stack.arturo +++ b/Task/Stack/Arturo/stack.arturo @@ -1,9 +1,9 @@ Stack: $[]-> [] pushTo: function [st val]-> 'st ++ val -popStack: function [st] [ - result: last st - remove 'st .index (size st)-1 +popStack: function [s] [ + result: last s + remove 's .index (size s)-1 return result ] emptyStack: function [st]-> empty 'st diff --git a/Task/Stack/Ballerina/stack-1.ballerina b/Task/Stack/Ballerina/stack-1.ballerina new file mode 100644 index 0000000000..70a1ee5ea9 --- /dev/null +++ b/Task/Stack/Ballerina/stack-1.ballerina @@ -0,0 +1,15 @@ +import ballerina/io; + +public function main() { + int[] stack = []; + stack.push(1); + stack.push(2); + io:println("Stack contains ", stack); + io:println("Number of elements in stack = ", stack.length()); + int item = stack.pop(); + io:println(item, " popped from the stack"); + io:println("Last element is now ", stack[stack.length() - 1]); + stack.removeAll(); + io:println("Stack cleared"); + io:println("Is stack now empty? ", stack.length() == 0 ? "yes" : "no"); +} diff --git a/Task/Stack/Ballerina/stack-2.ballerina b/Task/Stack/Ballerina/stack-2.ballerina new file mode 100644 index 0000000000..19641de2d8 --- /dev/null +++ b/Task/Stack/Ballerina/stack-2.ballerina @@ -0,0 +1,53 @@ +import ballerina/io; + +class Stack { + private any[] s = []; + + function push(any a) { + self.s.push(a); + } + + function length() returns int { + return self.s.length(); + } + + function isEmpty() returns boolean { + return self.length() == 0; + } + + function pop() returns any? { + if !self.isEmpty() { + return self.s.pop(); + } + return (); + } + + function peek() returns any? { + if !self.isEmpty() { + return self.s[self.length() - 1]; + } + return (); + } + + function clear() { + self.s.removeAll(); + } + + function toString() returns string { + return self.s.toString(); + } +} + +public function main() { + Stack s = new; + s.push(1); + s.push(2); + io:println("Stack contains ", s); + io:println("Number of elements in stack = ", s.length()); + any item = s.pop(); + io:println(item, " popped from the stack"); + io:println("Last element is now ", s.peek()); + s.clear(); + io:println("Stack cleared"); + io:println("Is stack now empty? ", s.isEmpty() ? "yes" : "no"); +} diff --git a/Task/Stack/Batch-File/stack.bat b/Task/Stack/Batch-File/stack-1.bat similarity index 100% rename from Task/Stack/Batch-File/stack.bat rename to Task/Stack/Batch-File/stack-1.bat diff --git a/Task/Stack/Batch-File/stack-2.bat b/Task/Stack/Batch-File/stack-2.bat new file mode 100644 index 0000000000..6d54baa760 --- /dev/null +++ b/Task/Stack/Batch-File/stack-2.bat @@ -0,0 +1,22 @@ +@echo off +setlocal enabledelayedexpansion +(set lf=^ + +) +(set stack= +set stack.push=set "stack=#^!lf^!^!stack^!" +set stack.pop=for %%l in ("^!lf^!"^) do set "stack=^!stack:*%%~l=^!" +set stack.empty=(call;^&if defined stack call^) +set stack.top=echo:^^!stack^^! ^| (set /p _=^& call echo:%%_%%^)) +:: ^ stack.top : https://stackoverflow.com/a/14965458 +%stack.push:#=1% +%stack.push:#=2% +%stack.top% +for %%l in ("!lf!") do echo:"!stack:%%~l= !" +%stack.pop% +for %%l in ("!lf!") do echo:"!stack:%%~l= !" +%stack.empty% && echo empty: true || echo empty: false +%stack.pop% +for %%l in ("!lf!") do echo:"!stack:%%~l= !" +%stack.empty% && echo empty: true || echo empty: false +goto:eof diff --git a/Task/Stack/C/stack-1.c b/Task/Stack/C/stack-1.c index a8e4a1dd7c..bf4fc16a09 100644 --- a/Task/Stack/C/stack-1.c +++ b/Task/Stack/C/stack-1.c @@ -2,33 +2,37 @@ #include /* to read expanded code, run through cpp | indent -st */ -#define DECL_STACK_TYPE(type, name) \ +#define DECL_STACK_TYPE(type, name) \ typedef struct stk_##name##_t{type *buf; size_t alloc,len;}*stk_##name; \ -stk_##name stk_##name##_create(size_t init_size) { \ - stk_##name s; if (!init_size) init_size = 4; \ - s = malloc(sizeof(struct stk_##name##_t)); \ - if (!s) return 0; \ - s->buf = malloc(sizeof(type) * init_size); \ - if (!s->buf) { free(s); return 0; } \ - s->len = 0, s->alloc = init_size; \ - return s; } \ -int stk_##name##_push(stk_##name s, type item) { \ - type *tmp; \ - if (s->len >= s->alloc) { \ - tmp = realloc(s->buf, s->alloc*2*sizeof(type)); \ - if (!tmp) return -1; s->buf = tmp; \ - s->alloc *= 2; } \ - s->buf[s->len++] = item; \ - return s->len; } \ -type stk_##name##_pop(stk_##name s) { \ - type tmp; \ - if (!s->len) abort(); \ - tmp = s->buf[--s->len]; \ - if (s->len * 2 <= s->alloc && s->alloc >= 8) { \ - s->alloc /= 2; \ - s->buf = realloc(s->buf, s->alloc * sizeof(type));} \ - return tmp; } \ -void stk_##name##_delete(stk_##name s) { \ + \ +stk_##name stk_##name##_create(size_t init_size) { \ + stk_##name s; if (!init_size) init_size = 4; \ + s = malloc(sizeof(struct stk_##name##_t)); \ + if (!s) return 0; \ + s->buf = malloc(sizeof(type) * init_size); \ + if (!s->buf) { free(s); return 0; } \ + s->len = 0, s->alloc = init_size; \ + return s; } \ + \ +int stk_##name##_push(stk_##name s, type item) { \ + type *tmp; \ + if (s->len >= s->alloc) { \ + tmp = realloc(s->buf, s->alloc*2*sizeof(type)); \ + if (!tmp) return -1; s->buf = tmp; \ + s->alloc *= 2; } \ + s->buf[s->len++] = item; \ + return s->len; } \ + \ +type stk_##name##_pop(stk_##name s) { \ + type tmp; \ + if (!s->len) abort(); \ + tmp = s->buf[--s->len]; \ + if (s->len * 2 <= s->alloc && s->alloc >= 8) { \ + s->alloc /= 2; \ + s->buf = realloc(s->buf, s->alloc * sizeof(type));} \ + return tmp; } \ + \ +void stk_##name##_delete(stk_##name s) { \ free(s->buf); free(s); } #define stk_empty(s) (!(s)->len) diff --git a/Task/Stack/COBOL/stack-1.cobol b/Task/Stack/COBOL/stack-1.cob similarity index 100% rename from Task/Stack/COBOL/stack-1.cobol rename to Task/Stack/COBOL/stack-1.cob diff --git a/Task/Stack/COBOL/stack-2.cobol b/Task/Stack/COBOL/stack-2.cob similarity index 100% rename from Task/Stack/COBOL/stack-2.cobol rename to Task/Stack/COBOL/stack-2.cob diff --git a/Task/Stack/COBOL/stack-3.cobol b/Task/Stack/COBOL/stack-3.cob similarity index 100% rename from Task/Stack/COBOL/stack-3.cobol rename to Task/Stack/COBOL/stack-3.cob diff --git a/Task/Stack/COBOL/stack-4.cobol b/Task/Stack/COBOL/stack-4.cob similarity index 100% rename from Task/Stack/COBOL/stack-4.cobol rename to Task/Stack/COBOL/stack-4.cob diff --git a/Task/Stack/COBOL/stack-5.cobol b/Task/Stack/COBOL/stack-5.cob similarity index 100% rename from Task/Stack/COBOL/stack-5.cobol rename to Task/Stack/COBOL/stack-5.cob diff --git a/Task/Stack/COBOL/stack-6.cobol b/Task/Stack/COBOL/stack-6.cob similarity index 100% rename from Task/Stack/COBOL/stack-6.cobol rename to Task/Stack/COBOL/stack-6.cob diff --git a/Task/Stack/Crystal/stack.cr b/Task/Stack/Crystal/stack.cr new file mode 100644 index 0000000000..0afd9d0010 --- /dev/null +++ b/Task/Stack/Crystal/stack.cr @@ -0,0 +1,13 @@ +stack = [] of Int32 +# push +stack.push 10 +stack << 10 + +# pop +var = stack.pop + +# empty +flag = stack.empty? + +# top / peek +var = stack.last diff --git a/Task/Stack/Crystal/stack.crystal b/Task/Stack/Crystal/stack.crystal deleted file mode 100644 index 8430aed04b..0000000000 --- a/Task/Stack/Crystal/stack.crystal +++ /dev/null @@ -1,8 +0,0 @@ -stack = [] of Int32 -(1..10).each do |x| - stack.push x -end - -10.times do - puts stack.pop -end diff --git a/Task/Stack/Delphi/stack.delphi b/Task/Stack/Delphi/stack.pas similarity index 100% rename from Task/Stack/Delphi/stack.delphi rename to Task/Stack/Delphi/stack.pas diff --git a/Task/Stack/EasyLang/stack.easy b/Task/Stack/EasyLang/stack.easy index f0ac75cdc2..187e06459f 100644 --- a/Task/Stack/EasyLang/stack.easy +++ b/Task/Stack/EasyLang/stack.easy @@ -1,12 +1,10 @@ stack[] = [ ] -proc push v . . +proc push v . stack[] &= v . func pop . lng = len stack[] - if lng = 0 - return 0 - . + if lng = 0 : return 0 / 0 r = stack[lng] len stack[] -1 return r diff --git a/Task/Stack/Elena/stack.elena b/Task/Stack/Elena/stack.elena index d792216cbd..10d490c847 100644 --- a/Task/Stack/Elena/stack.elena +++ b/Task/Stack/Elena/stack.elena @@ -1,4 +1,4 @@ -public program() +public Program() { var stack := new system'collections'Stack(); diff --git a/Task/Stack/Elixir/stack.elixir b/Task/Stack/Elixir/stack.ex similarity index 100% rename from Task/Stack/Elixir/stack.elixir rename to Task/Stack/Elixir/stack.ex diff --git a/Task/Stack/FutureBasic/stack.basic b/Task/Stack/FutureBasic/stack.basic new file mode 100644 index 0000000000..6117ee6d84 --- /dev/null +++ b/Task/Stack/FutureBasic/stack.basic @@ -0,0 +1,29 @@ +void local fn StackPush( stack as CFMutableArrayRef, obj as CFTypeRef ) + MutableArrayAddObject( stack, obj ) +end fn + +CFTypeRef local fn StackPop( stack as CFMutableArrayRef ) + CFTypeRef obj = fn ArrayLastObject( stack ) + MutableArrayRemoveLastObject( stack ) +end fn = obj + +BOOL def fn StackIsEmpty( stack as CFMutableArrayRef ) = len(stack) == 0 + +void local fn DoIt + CFMutableArrayRef stack = fn MutableArrayNew + + print @"Stack is empty: ";fn StackIsEmpty( stack ) + + print : print @"Stack push \"String\"" + fn StackPush( stack, @"String" ) + print @"Stack is empty: ";fn StackIsEmpty( stack ) + + CFTyperef obj = fn StackPop( stack ) + print : print @"Stack pop: ";obj + + print @"Stack is empty: ";fn StackIsEmpty( stack ) +end fn + +fn DoIt + +HandleEvents diff --git a/Task/Stack/Gleam/stack.gleam b/Task/Stack/Gleam/stack.gleam new file mode 100644 index 0000000000..f5f536eef9 --- /dev/null +++ b/Task/Stack/Gleam/stack.gleam @@ -0,0 +1,38 @@ +import gleam/option.{type Option, None, Some} + +/// Stack(a) is just an alias for a List(a) +pub type Stack(a) = + List(a) + +/// An empty stack is an empty list. +pub const empty = [] + +/// is_empty(s) checks if the stack s is empty. +pub fn is_empty(stack: Stack(a)) -> Bool { + case stack { + [] -> True + _ -> False + } +} + +/// push(s,x) pushes the element x onto the stack s. +pub fn push(stack: Stack(a), x: a) -> Stack(a) { + [x, ..stack] +} + +/// peek(s) returns the TOS. +pub fn peek(stack: Stack(a)) -> Result(a, Nil) { + case stack { + [] -> Error(Nil) + [h, ..] -> Ok(h) + } +} + +/// pop(s) pops an element from the TOS, and returns that +/// and the modified stack. +pub fn pop(stack: Stack(a)) -> Result(#(a, Stack(a)), Nil) { + case stack { + [h, ..tl] -> Ok(#(h, tl)) + _ -> Error(Nil) + } +} diff --git a/Task/Stack/Julia/stack.julia b/Task/Stack/Julia/stack.jl similarity index 100% rename from Task/Stack/Julia/stack.julia rename to Task/Stack/Julia/stack.jl diff --git a/Task/Stack/Kotlin/stack.kotlin b/Task/Stack/Kotlin/stack.kts similarity index 100% rename from Task/Stack/Kotlin/stack.kotlin rename to Task/Stack/Kotlin/stack.kts diff --git a/Task/Stack/OCaml/stack.ocaml b/Task/Stack/OCaml/stack.ml similarity index 100% rename from Task/Stack/OCaml/stack.ocaml rename to Task/Stack/OCaml/stack.ml diff --git a/Task/Stack/Oberon-07/stack-1.oberon b/Task/Stack/Oberon-07/stack-1.oberon new file mode 100644 index 0000000000..d9d5566df1 --- /dev/null +++ b/Task/Stack/Oberon-07/stack-1.oberon @@ -0,0 +1,43 @@ +MODULE StackOfInteger; + + TYPE T = INTEGER; + Element = RECORD value : T; next : POINTER TO Element END; + StackRecord = RECORD top : POINTER TO Element END; + Stack* = POINTER TO StackRecord; + + PROCEDURE push*( s : Stack; v : T ); + VAR newElement : POINTER TO Element; + BEGIN + NEW( newElement ); + newElement.value := v; + newElement.next := s.top; + s.top := newElement + END push; + + PROCEDURE peek*( s : Stack ) : T; + BEGIN + RETURN s.top.value + END peek; + + PROCEDURE pop*( s : Stack ) : T; + VAR v : T; + BEGIN + v := peek( s ); + s.top := s.top.next + RETURN v + END pop; + + PROCEDURE empty*( s : Stack ) : BOOLEAN; + BEGIN + RETURN s.top = NIL + END empty; + + PROCEDURE newStack*() : Stack; + VAR s : Stack; + BEGIN + NEW( s ); + s.top := NIL; + RETURN s + END newStack; + +END StackOfInteger. diff --git a/Task/Stack/Oberon-07/stack-2.oberon b/Task/Stack/Oberon-07/stack-2.oberon new file mode 100644 index 0000000000..95e7f40725 --- /dev/null +++ b/Task/Stack/Oberon-07/stack-2.oberon @@ -0,0 +1,26 @@ +MODULE UseStack; (* use the StackOfInteger module *) + IMPORT Out, SI := StackOfInteger; (* imports StackOfInteger under the name "SI" *) + + VAR st : SI.Stack; + v, sum : INTEGER; + +BEGIN + + st := SI.newStack(); (* create a stack *) + + SI.push( st, 1 ); (* add some items *) + SI.push( st, 23 ); + SI.push( st, 456 ); + + WHILE ~ SI.empty( st ) DO (* unstack, sum and print the items *) + v := SI.pop( st ); + INC( sum, v ); + Out.Int( v, 0 ); + IF ~ SI.empty( st ) THEN + Out.String( " (" );Out.Int( SI.peek( st ), 0 );Out.String( ")" ) + END; + Out.Ln + END; + Out.String( "sum: " );Out.Int( sum, 0 );Out.Ln + +END UseStack. diff --git a/Task/Stack/OoRexx/stack.rexx b/Task/Stack/OoRexx/stack.rexx index 9916fb8815..01deff92ae 100644 --- a/Task/Stack/OoRexx/stack.rexx +++ b/Task/Stack/OoRexx/stack.rexx @@ -1,6 +1,9 @@ stack = .queue~of(123, 234) -- creates a stack with a couple of items stack~push("Abc") -- pushing value = stack~pull -- popping +say 'popped:' value value = stack~peek -- peeking +say 'peeked:' value -- the is empty test if stack~isEmpty then say "The stack is empty" +Else say stack~items 'items are on the stack' diff --git a/Task/Stack/PascalABC.NET/stack.pas b/Task/Stack/PascalABC.NET/stack.pas new file mode 100644 index 0000000000..d006c63f48 --- /dev/null +++ b/Task/Stack/PascalABC.NET/stack.pas @@ -0,0 +1,11 @@ +begin + var st := new Stack; + var st1 := new Stack; + st.Push(1); + st.Push(2); + st.Push(3); + Println(st1,st); + while st.Count <> 0 do + st1.Push(st.Pop); + Println(st1,st); +end. diff --git a/Task/Stack/Pluto/stack.pluto b/Task/Stack/Pluto/stack.pluto new file mode 100644 index 0000000000..17486a799a --- /dev/null +++ b/Task/Stack/Pluto/stack.pluto @@ -0,0 +1,4 @@ +stack = {} +table.insert(stack, 11) -- push +table.remove(stack) -- pop +print(#stack == 0) -- empty diff --git a/Task/Stack/PowerShell/stack-1.psh b/Task/Stack/PowerShell/stack-1.ps1 similarity index 100% rename from Task/Stack/PowerShell/stack-1.psh rename to Task/Stack/PowerShell/stack-1.ps1 diff --git a/Task/Stack/PowerShell/stack-2.psh b/Task/Stack/PowerShell/stack-2.ps1 similarity index 100% rename from Task/Stack/PowerShell/stack-2.psh rename to Task/Stack/PowerShell/stack-2.ps1 diff --git a/Task/Stack/PowerShell/stack-3.psh b/Task/Stack/PowerShell/stack-3.ps1 similarity index 100% rename from Task/Stack/PowerShell/stack-3.psh rename to Task/Stack/PowerShell/stack-3.ps1 diff --git a/Task/Stack/PowerShell/stack-4.psh b/Task/Stack/PowerShell/stack-4.ps1 similarity index 100% rename from Task/Stack/PowerShell/stack-4.psh rename to Task/Stack/PowerShell/stack-4.ps1 diff --git a/Task/Stack/PowerShell/stack-5.psh b/Task/Stack/PowerShell/stack-5.ps1 similarity index 100% rename from Task/Stack/PowerShell/stack-5.psh rename to Task/Stack/PowerShell/stack-5.ps1 diff --git a/Task/Stack/PowerShell/stack-6.psh b/Task/Stack/PowerShell/stack-6.ps1 similarity index 100% rename from Task/Stack/PowerShell/stack-6.psh rename to Task/Stack/PowerShell/stack-6.ps1 diff --git a/Task/Stack/PowerShell/stack-7.psh b/Task/Stack/PowerShell/stack-7.ps1 similarity index 100% rename from Task/Stack/PowerShell/stack-7.psh rename to Task/Stack/PowerShell/stack-7.ps1 diff --git a/Task/Stack/REBOL/stack.rebol b/Task/Stack/REBOL/stack.rebol deleted file mode 100644 index 8a20e0acd2..0000000000 --- a/Task/Stack/REBOL/stack.rebol +++ /dev/null @@ -1,34 +0,0 @@ -REBOL [ - Title: "Stack" - URL: http://rosettacode.org/wiki/Stack -] - -stack: make object! [ - data: copy [] - - push: func [x][append data x] - pop: func [/local x][x: last data remove back tail data x] - empty: does [empty? data] - - peek: does [last data] -] - -; Teeny Tiny Test Suite - -assert: func [code][print [either do code [" ok"]["FAIL"] mold code]] - -print "Simple integers:" -s: make stack [] s/push 1 s/push 2 ; Initialize. - -assert [2 = s/peek] -assert [2 = s/pop] -assert [1 = s/pop] -assert [s/empty] - -print [lf "Symbolic data on stack:"] -v: make stack [data: [this is a test]] ; Initialize on instance. - -assert ['test = v/peek] -assert ['test = v/pop] -assert ['a = v/pop] -assert [not v/empty] diff --git a/Task/Stack/REXX/stack-1.rexx b/Task/Stack/REXX/stack-1.rexx deleted file mode 100644 index 1b85ae47de..0000000000 --- a/Task/Stack/REXX/stack-1.rexx +++ /dev/null @@ -1,7 +0,0 @@ -y=123 /*define a REXX variable, value is 123 */ -push y /*pushes 123 onto the stack. */ -pull g /*pops last value stacked & removes it. */ -q=empty() /*invokes the EMPTY subroutine (below)*/ -exit /*stick a fork in it, we're done. */ - -empty: return queued() /*subroutine returns # of stacked items.*/ diff --git a/Task/Stack/REXX/stack-2.rexx b/Task/Stack/REXX/stack-2.rexx deleted file mode 100644 index 0ebf18a3f5..0000000000 --- a/Task/Stack/REXX/stack-2.rexx +++ /dev/null @@ -1,42 +0,0 @@ -/* REXX *************************************************************** -* supports push, pull, and peek -* 11.08.2013 Walter Pachl -**********************************************************************/ -stk.=0 -Call push 123 -Say empty() -say peek() -say pull() -Say empty() -say peek() -say push(456) -say peek() -Exit - -push: Procedure Expose stk. - Parse Arg v - z=stk.0+1 - stk.z=v - stk.0=z - Return v - -peek: Procedure Expose stk. - If stk.0=0 Then - Return 'stack is empty' - Else Do - z=stk.0 - Return stk.z - End - -pull: Procedure Expose stk. - If stk.0=0 Then - Return 'stack is empty' - Else Do - z=stk.0 - res=stk.z - stk.0=stk.0-1 - Return res - End - -empty: Procedure Expose stk. - Return stk.0=0 diff --git a/Task/Stack/REXX/stack.rexx b/Task/Stack/REXX/stack.rexx new file mode 100644 index 0000000000..3a3bf6e8fd --- /dev/null +++ b/Task/Stack/REXX/stack.rexx @@ -0,0 +1,42 @@ +/* REXX *************************************************************** +* supports push, pull, and peek +* 11.08.2013 Walter Pachl +**********************************************************************/ +stk.=0 +Call push 123 /*pushes 123 onto the stack. */ +Say empty() +say peek() +say pull() /*pops last value stacked & removes it. */ +Say empty() +say peek() +say push(456) +say peek() +Exit + +push: Procedure Expose stk. + Parse Arg v + z=stk.0+1 + stk.z=v + stk.0=z + Return v + +peek: Procedure Expose stk. + If stk.0=0 Then + Return 'stack is empty' + Else Do + z=stk.0 + Return stk.z + End + +pull: Procedure Expose stk. + If stk.0=0 Then + Return 'stack is empty' + Else Do + z=stk.0 + res=stk.z + stk.0=stk.0-1 + Return res + End + +empty: Procedure Expose stk. + Return stk.0=0 diff --git a/Task/Stack/Rebol/stack-1.rebol b/Task/Stack/Rebol/stack-1.rebol new file mode 100644 index 0000000000..ddf98d7f1d --- /dev/null +++ b/Task/Stack/Rebol/stack-1.rebol @@ -0,0 +1,6 @@ +stack: copy [] +append stack 1 ;== [1] +append stack 2 ;== [1 2] +take/last stack ;== 2 +take/last stack ;== 1 +empty? stack ;== true diff --git a/Task/Stack/Rebol/stack-2.rebol b/Task/Stack/Rebol/stack-2.rebol new file mode 100644 index 0000000000..ccc8859d2f --- /dev/null +++ b/Task/Stack/Rebol/stack-2.rebol @@ -0,0 +1,34 @@ +Rebol [ + Title: "Stack" + URL: http://rosettacode.org/wiki/Stack +] + +stack: make object! [ + data: copy [] + + push: func [x][append data x] + pop: func [/local x][x: last data remove back tail data x] + empty: does [empty? data] + + peek: does [last data] +] + +; Teeny Tiny Test Suite + +assert: func [code][print [either do code [" ok"]["FAIL"] mold code]] + +print "Simple integers:" +s: make stack [] s/push 1 s/push 2 ; Initialize. + +assert [2 = s/peek] +assert [2 = s/pop] +assert [1 = s/pop] +assert [s/empty] + +print [lf "Symbolic data on stack:"] +v: make stack [data: [this is a test]] ; Initialize on instance. + +assert ['test = v/peek] +assert ['test = v/pop] +assert ['a = v/pop] +assert [not v/empty] diff --git a/Task/Stack/Rust/stack-1.rust b/Task/Stack/Rust/stack-1.rs similarity index 100% rename from Task/Stack/Rust/stack-1.rust rename to Task/Stack/Rust/stack-1.rs diff --git a/Task/Stack/Rust/stack-2.rust b/Task/Stack/Rust/stack-2.rs similarity index 100% rename from Task/Stack/Rust/stack-2.rust rename to Task/Stack/Rust/stack-2.rs diff --git a/Task/Stack/Scheme/stack.ss b/Task/Stack/Scheme/stack.scm similarity index 100% rename from Task/Stack/Scheme/stack.ss rename to Task/Stack/Scheme/stack.scm diff --git a/Task/Stack/TAV/stack-1.tav b/Task/Stack/TAV/stack-1.tav new file mode 100644 index 0000000000..ed582a9393 --- /dev/null +++ b/Task/Stack/TAV/stack-1.tav @@ -0,0 +1,6 @@ +row (@) push (val): + @[@.Count+1] =: val \ increments .Count +row (@) pop: + rv =: @[@.Count] \ void if .Count = 0 + @[@.Count] =: () \ assigning void decrements .Count + :> rv diff --git a/Task/Stack/TAV/stack-2.tav b/Task/Stack/TAV/stack-2.tav new file mode 100644 index 0000000000..b95a0b9d3f --- /dev/null +++ b/Task/Stack/TAV/stack-2.tav @@ -0,0 +1,9 @@ +main(params):+ + stack =: new row \ a row is a nice stack + ?# v =: tuple 1,3,5,7,11,13 give values + row stack push v \ push some primes + print '*' _ stack[stack.Count] \ get top + ?# i =: from 1 upto 7 + ? i %% 3 = 0 + print '*' _ stack[stack.Count] + print stack::pop \ class function syntax used diff --git a/Task/Stack/V-(Vlang)/stack.v b/Task/Stack/V-(Vlang)/stack.v index 7c6e9e4b94..da6b1d2639 100644 --- a/Task/Stack/V-(Vlang)/stack.v +++ b/Task/Stack/V-(Vlang)/stack.v @@ -17,7 +17,7 @@ fn (mut s Stack) push(v f32) { s.depth++ } -fn (mut s Stack) pop() ?f32 { +fn (mut s Stack) pop() !f32 { if s.depth > 0 { s.depth-- result := s.data[s.depth] @@ -27,7 +27,7 @@ fn (mut s Stack) pop() ?f32 { return error('Stack Underflow!!') } -fn (s Stack) peek() ?f32 { +fn (s Stack) peek() !f32 { if s.depth > 0 { result := s.data[s.depth - 1] println('Peek: top of stack is ${result:3.2f}') diff --git a/Task/Stack/VBScript/stack-1.vb b/Task/Stack/VBScript/stack-1.vbs similarity index 100% rename from Task/Stack/VBScript/stack-1.vb rename to Task/Stack/VBScript/stack-1.vbs diff --git a/Task/Stack/VBScript/stack-2.vb b/Task/Stack/VBScript/stack-2.vbs similarity index 100% rename from Task/Stack/VBScript/stack-2.vb rename to Task/Stack/VBScript/stack-2.vbs diff --git a/Task/Stack/X86-Assembly/stack.x86 b/Task/Stack/X86-64-Assembly/stack.x86-64 similarity index 100% rename from Task/Stack/X86-Assembly/stack.x86 rename to Task/Stack/X86-64-Assembly/stack.x86-64 diff --git a/Task/Stair-climbing-puzzle/Ada/stair-climbing-puzzle-1.ada b/Task/Stair-climbing-puzzle/Ada/stair-climbing-puzzle-1.adb similarity index 100% rename from Task/Stair-climbing-puzzle/Ada/stair-climbing-puzzle-1.ada rename to Task/Stair-climbing-puzzle/Ada/stair-climbing-puzzle-1.adb diff --git a/Task/Stair-climbing-puzzle/Ada/stair-climbing-puzzle-2.ada b/Task/Stair-climbing-puzzle/Ada/stair-climbing-puzzle-2.adb similarity index 100% rename from Task/Stair-climbing-puzzle/Ada/stair-climbing-puzzle-2.ada rename to Task/Stair-climbing-puzzle/Ada/stair-climbing-puzzle-2.adb diff --git a/Task/Stair-climbing-puzzle/Delphi/stair-climbing-puzzle-1.delphi b/Task/Stair-climbing-puzzle/Delphi/stair-climbing-puzzle-1.pas similarity index 100% rename from Task/Stair-climbing-puzzle/Delphi/stair-climbing-puzzle-1.delphi rename to Task/Stair-climbing-puzzle/Delphi/stair-climbing-puzzle-1.pas diff --git a/Task/Stair-climbing-puzzle/Delphi/stair-climbing-puzzle-2.delphi b/Task/Stair-climbing-puzzle/Delphi/stair-climbing-puzzle-2.pas similarity index 100% rename from Task/Stair-climbing-puzzle/Delphi/stair-climbing-puzzle-2.delphi rename to Task/Stair-climbing-puzzle/Delphi/stair-climbing-puzzle-2.pas diff --git a/Task/Stair-climbing-puzzle/Delphi/stair-climbing-puzzle-3.delphi b/Task/Stair-climbing-puzzle/Delphi/stair-climbing-puzzle-3.pas similarity index 100% rename from Task/Stair-climbing-puzzle/Delphi/stair-climbing-puzzle-3.delphi rename to Task/Stair-climbing-puzzle/Delphi/stair-climbing-puzzle-3.pas diff --git a/Task/Stair-climbing-puzzle/EasyLang/stair-climbing-puzzle.easy b/Task/Stair-climbing-puzzle/EasyLang/stair-climbing-puzzle.easy new file mode 100644 index 0000000000..e662530544 --- /dev/null +++ b/Task/Stair-climbing-puzzle/EasyLang/stair-climbing-puzzle.easy @@ -0,0 +1,13 @@ +func step . + if random 1 2 = 2 + print "climbed up" + return 1 + else + print "fell down" + return 0 + . +. +proc step_up . + while step = 0 : step_up +. +step_up diff --git a/Task/Stair-climbing-puzzle/Elixir/stair-climbing-puzzle.elixir b/Task/Stair-climbing-puzzle/Elixir/stair-climbing-puzzle.ex similarity index 100% rename from Task/Stair-climbing-puzzle/Elixir/stair-climbing-puzzle.elixir rename to Task/Stair-climbing-puzzle/Elixir/stair-climbing-puzzle.ex diff --git a/Task/Stair-climbing-puzzle/Euphoria/stair-climbing-puzzle.euphoria b/Task/Stair-climbing-puzzle/Euphoria/stair-climbing-puzzle.eu similarity index 100% rename from Task/Stair-climbing-puzzle/Euphoria/stair-climbing-puzzle.euphoria rename to Task/Stair-climbing-puzzle/Euphoria/stair-climbing-puzzle.eu diff --git a/Task/Stair-climbing-puzzle/Julia/stair-climbing-puzzle-1.julia b/Task/Stair-climbing-puzzle/Julia/stair-climbing-puzzle-1.jl similarity index 100% rename from Task/Stair-climbing-puzzle/Julia/stair-climbing-puzzle-1.julia rename to Task/Stair-climbing-puzzle/Julia/stair-climbing-puzzle-1.jl diff --git a/Task/Stair-climbing-puzzle/Julia/stair-climbing-puzzle-2.julia b/Task/Stair-climbing-puzzle/Julia/stair-climbing-puzzle-2.jl similarity index 100% rename from Task/Stair-climbing-puzzle/Julia/stair-climbing-puzzle-2.julia rename to Task/Stair-climbing-puzzle/Julia/stair-climbing-puzzle-2.jl diff --git a/Task/Stair-climbing-puzzle/Kotlin/stair-climbing-puzzle.kotlin b/Task/Stair-climbing-puzzle/Kotlin/stair-climbing-puzzle.kts similarity index 100% rename from Task/Stair-climbing-puzzle/Kotlin/stair-climbing-puzzle.kotlin rename to Task/Stair-climbing-puzzle/Kotlin/stair-climbing-puzzle.kts diff --git a/Task/Stair-climbing-puzzle/OCaml/stair-climbing-puzzle.ocaml b/Task/Stair-climbing-puzzle/OCaml/stair-climbing-puzzle.ml similarity index 100% rename from Task/Stair-climbing-puzzle/OCaml/stair-climbing-puzzle.ocaml rename to Task/Stair-climbing-puzzle/OCaml/stair-climbing-puzzle.ml diff --git a/Task/Stair-climbing-puzzle/PowerShell/stair-climbing-puzzle.psh b/Task/Stair-climbing-puzzle/PowerShell/stair-climbing-puzzle.ps1 similarity index 100% rename from Task/Stair-climbing-puzzle/PowerShell/stair-climbing-puzzle.psh rename to Task/Stair-climbing-puzzle/PowerShell/stair-climbing-puzzle.ps1 diff --git a/Task/Stair-climbing-puzzle/REBOL/stair-climbing-puzzle.rebol b/Task/Stair-climbing-puzzle/Rebol/stair-climbing-puzzle.rebol similarity index 99% rename from Task/Stair-climbing-puzzle/REBOL/stair-climbing-puzzle.rebol rename to Task/Stair-climbing-puzzle/Rebol/stair-climbing-puzzle.rebol index 4e4c5065c5..7d0877d2cf 100644 --- a/Task/Stair-climbing-puzzle/REBOL/stair-climbing-puzzle.rebol +++ b/Task/Stair-climbing-puzzle/Rebol/stair-climbing-puzzle.rebol @@ -1,4 +1,4 @@ -REBOL [ +Rebol [ Title: "Stair Climber" URL: http://rosettacode.org/wiki/Stair_Climbing ] diff --git a/Task/Stair-climbing-puzzle/Rust/stair-climbing-puzzle.rust b/Task/Stair-climbing-puzzle/Rust/stair-climbing-puzzle.rs similarity index 100% rename from Task/Stair-climbing-puzzle/Rust/stair-climbing-puzzle.rust rename to Task/Stair-climbing-puzzle/Rust/stair-climbing-puzzle.rs diff --git a/Task/Stair-climbing-puzzle/Scheme/stair-climbing-puzzle.ss b/Task/Stair-climbing-puzzle/Scheme/stair-climbing-puzzle.scm similarity index 100% rename from Task/Stair-climbing-puzzle/Scheme/stair-climbing-puzzle.ss rename to Task/Stair-climbing-puzzle/Scheme/stair-climbing-puzzle.scm diff --git a/Task/Stair-climbing-puzzle/V-(Vlang)/stair-climbing-puzzle.v b/Task/Stair-climbing-puzzle/V-(Vlang)/stair-climbing-puzzle.v new file mode 100644 index 0000000000..110deebf3f --- /dev/null +++ b/Task/Stair-climbing-puzzle/V-(Vlang)/stair-climbing-puzzle.v @@ -0,0 +1,32 @@ +import rand +import rand.seed + +struct Walker { + mut: + position int +} + +fn (mut wr Walker) step() bool { + rm := rand.u32() > (max_u32 / 2) + if rm { + wr.position += 1 + println("Climbed up to ${wr.position}") + } else { + wr.position -= 1 + println("Fell down to ${wr.position}") + } + return rm +} + +fn (mut wr Walker) step_up() { + for !wr.step() { + wr.step_up() + } +} + +fn main() { + seeds := seed.time_seed_array(2) + rand.seed(seeds) + mut walker := Walker{0} + walker.step_up() +} diff --git a/Task/Start-from-a-main-routine/Ada/start-from-a-main-routine.ada b/Task/Start-from-a-main-routine/Ada/start-from-a-main-routine.adb similarity index 100% rename from Task/Start-from-a-main-routine/Ada/start-from-a-main-routine.ada rename to Task/Start-from-a-main-routine/Ada/start-from-a-main-routine.adb diff --git a/Task/Start-from-a-main-routine/EasyLang/start-from-a-main-routine.easy b/Task/Start-from-a-main-routine/EasyLang/start-from-a-main-routine.easy index 048d3ce437..502b4c8879 100644 --- a/Task/Start-from-a-main-routine/EasyLang/start-from-a-main-routine.easy +++ b/Task/Start-from-a-main-routine/EasyLang/start-from-a-main-routine.easy @@ -1,4 +1,4 @@ -proc main . . +proc main . print "Hello from main!" . main diff --git a/Task/Start-from-a-main-routine/FutureBasic/start-from-a-main-routine.basic b/Task/Start-from-a-main-routine/FutureBasic/start-from-a-main-routine.basic new file mode 100644 index 0000000000..3a73ad4cc5 --- /dev/null +++ b/Task/Start-from-a-main-routine/FutureBasic/start-from-a-main-routine.basic @@ -0,0 +1,7 @@ +void local fn Start + printf @"Hello, World!" +end fn + +fn Start + +HandleEvents diff --git a/Task/Start-from-a-main-routine/Phix/start-from-a-main-routine.phix b/Task/Start-from-a-main-routine/Phix/start-from-a-main-routine.phix index ad670304f0..c215911a2b 100644 --- a/Task/Start-from-a-main-routine/Phix/start-from-a-main-routine.phix +++ b/Task/Start-from-a-main-routine/Phix/start-from-a-main-routine.phix @@ -1,6 +1,4 @@ ---> - procedure main() - ... - end procedure - main() - - function generate_statistics(integer n) - sequence hist = repeat(0,10) - atom sum_r = 0, - sum_squares = 0.0 +function generate_statistics(integer n) +sequence hist = repeat(0,10) +atom sum_r = 0, + sum_squares = 0.0 - for i=1 to n do - atom r = rnd() - sum_r += r - sum_squares += r*r - hist[floor(10*r)+1] += 1 - end for - atom mean = sum_r / n - atom stddev = sqrt((sum_squares / n) - mean*mean) + for i=1 to n do + atom r = rnd() + sum_r += r + sum_squares += r*r + hist[floor(10*r)+1] += 1 + end for + atom mean = sum_r / n + atom stddev = sqrt((sum_squares / n) - mean*mean) - return {n, mean, stddev, hist} - end function + return {n, mean, stddev, hist} +end function - procedure display_statistics(sequence x) - atom n, mean, stddev - sequence hist - {n, mean, stddev, hist} = x - printf(1,"-- Stats for sample size %d\n",{n}) - printf(1,"mean: %g\n",{mean}) - printf(1,"sdev: %g\n",{stddev}) - for i=1 to length(hist) do - integer cnt = hist[i] - string bars = repeat('=',floor(cnt*300/n)) - printf(1,"%.1f: %s %d\n",{i/10,bars,cnt}) - end for - end procedure +procedure display_statistics(sequence x) +atom n, mean, stddev +sequence hist + {n, mean, stddev, hist} = x + printf(1,"-- Stats for sample size %d\n",{n}) + printf(1,"mean: %g\n",{mean}) + printf(1,"sdev: %g\n",{stddev}) + for i=1 to length(hist) do + integer cnt = hist[i] + string bars = repeat('=',floor(cnt*300/n)) + printf(1,"%.1f: %s %d\n",{i/10,bars,cnt}) + end for +end procedure - for n=2 to 5 do - display_statistics(generate_statistics(power(10,n+(n=5)))) - end for - - with javascript_semantics - function aitken(integer f, atom p0) - atom p1 = f(p0), - p2 = f(p1), - p1m0 = p1 - p0 - return p0 - (p1m0 * p1m0) / (p2 - (2 * p1) + p0) - end function +with javascript_semantics +function aitken(integer f, atom p0) + atom p1 = f(p0), + p2 = f(p1), + p1m0 = p1 - p0 + return p0 - (p1m0 * p1m0) / (p2 - (2 * p1) + p0) +end function - function steffensenAitken(integer f, maxiter, atom pinit, tol) - atom p0 = pinit, p = aitken(f, p0) - integer iter = 1 - while abs(p-p0)>tol and iter<maxiter do - p0 = p - p = aitken(f, p0) - iter += 1 - end while - return iff(abs(p-p0)>tol?"none":p) - end function +function steffensenAitken(integer f, maxiter, atom pinit, tol) + atom p0 = pinit, p = aitken(f, p0) + integer iter = 1 + while abs(p-p0)>tol and itertol?"none":p) +end function - function deCasteljau(atom c0, c1, c2, t) - atom s = 1 - t, - c01 = (s * c0) + (t * c1), - c12 = (s * c1) + (t * c2), - c012 = (s * c01) + (t * c12) - return c012 - end function +function deCasteljau(atom c0, c1, c2, t) + atom s = 1 - t, + c01 = (s * c0) + (t * c1), + c12 = (s * c1) + (t * c2), + c012 = (s * c01) + (t * c12) + return c012 +end function - function xConvexLeftParabola(atom t) - return deCasteljau(2, -8, 2, t) - end function +function xConvexLeftParabola(atom t) + return deCasteljau(2, -8, 2, t) +end function - function yConvexLeftParabola(atom t) - return deCasteljau(1, 2, 3, t) - end function +function yConvexLeftParabola(atom t) + return deCasteljau(1, 2, 3, t) +end function - function implicitEquation(atom x, y) - return (5 * x * x) + y - 5 - end function +function implicitEquation(atom x, y) + return (5 * x * x) + y - 5 +end function - function f(atom t) - atom x = xConvexLeftParabola(t), - y = yConvexLeftParabola(t) - return implicitEquation(x, y) + t - end function +function f(atom t) + atom x = xConvexLeftParabola(t), + y = yConvexLeftParabola(t) + return implicitEquation(x, y) + t +end function - for i=0 to 10 do - printf(1,"t0 = %.1f : ",i/10) - object t = steffensenAitken(f, 1000, i/10, 0.00000001) - if string(t) then - printf(1,"no answer\n") - else - atom x = xConvexLeftParabola(t), - y = yConvexLeftParabola(t) - if abs(implicitEquation(x, y)) <= 0.000001 then - printf(1,"intersection at (%.6f, %.6f)\n",{x,y}) - else - printf(1,"spurious solution\n") - end if - end if - end for - sequence(stem_leaves, StemLeaves). + +stem_leaves(Stem - Leaves) --> rpad_integer(4, Stem), " | ", sequence(integer, " ", Leaves), "\n". + +rpad_integer(Pad, N) --> + ( { Pad0 is Pad - 1, N < 10 ^ Pad0, \+ ( Pad = 1, N = 0 ) } + -> " ", rpad_integer(Pad0, N) + ; integer(N) + ). + +%! display_stem_leaf_plot(Numbers) is det. +% Prints the stem-and-leaf plot of a list of Numbers. +display_stem_leaf_plot(Numbers) :- + numbers_to_stem_leaves(Numbers, StemLeaves), + once(phrase(stem_leaf_plot(StemLeaves), Codes)), + format("~s", [Codes]). + +int(N) --> integer(N), blanks. + +main([Filename]) :- + phrase_from_file((blanks, sequence(int, Numbers)), Filename), + display_stem_leaf_plot(Numbers). diff --git a/Task/Stem-and-leaf-plot/Rust/stem-and-leaf-plot.rs b/Task/Stem-and-leaf-plot/Rust/stem-and-leaf-plot.rs new file mode 100644 index 0000000000..c3689b6f22 --- /dev/null +++ b/Task/Stem-and-leaf-plot/Rust/stem-and-leaf-plot.rs @@ -0,0 +1,120 @@ +// ================================================================ : +// Advice: Rust with a functional approach +// : Treats single-digit numbers as having a leading zero (stem 0) +// : Uses the last digit as the leaf +// : Includes all stems from 0 to 14 +// : Uses a functional approach with pure functions +// : Produces monospaced plain text output +// ================================================================ + +use std::collections::BTreeMap; + +// ================================================================ +// Mathematical Helper Functions (Pure) +// ================================================================ + +// Conceptually expands single digit numbers. +// Numerically unchanged, included for semantic clarity. +fn expand_number(n: u32) -> u32 { + n +} + +// Returns the stem (all but the last digit). +// Example: 127 -> 12 +fn stem(n: u32) -> u32 { + n / 10 +} + +// Returns the leaf (last digit). +// Example: 127 -> 7 +fn leaf(n: u32) -> u32 { + n % 10 +} + +// ================================================================ +// Data Transformation Layer (Pure Functional Pipeline) +// ================================================================ + +// Builds the stem-leaf structure. +// Returns a BTreeMap so stems are automatically sorted. +// Ensures stems 0..14 always exist. +fn build_stem_leaf(data: &[u32]) -> BTreeMap> { + // Step 1: Expand and sort the data + let mut sorted: Vec = data.iter().map(|&n| expand_number(n)).collect(); + + sorted.sort(); + + // Step 2: Create all stems 0..14 + (0..=14) + .map(|s| { + // Collect and sort leaves belonging to this stem + let mut leaves: Vec = sorted + .iter() + .filter(|&&n| stem(n) == s) + .map(|&n| leaf(n)) + .collect(); + + leaves.sort(); + + (s, leaves) + }) + .collect() +} + +// ================================================================ +// Formatting Layer (Pure Rendering) +// ================================================================ + +// Formats a stem as two digits (leading zero if necessary). +// Example: 7 -> "07" +fn format_stem(s: u32) -> String { + format!("{:02}", s) +} + +// Formats leaves as space-separated digits. +// Example: [1,3,7] -> "1 3 7" +fn format_leaves(leaves: &[u32]) -> String { + leaves + .iter() + .map(|l| l.to_string()) + .collect::>() + .join(" ") +} + +// Renders the complete stem-and-leaf plot as multi-line string. +fn render_plot(stem_leaf: &BTreeMap>) -> String { + stem_leaf + .iter() + .map(|(s, leaves)| format!("{} | {}", format_stem(*s), format_leaves(leaves))) + .collect::>() + .join("\n") +} + +// ================================================================ +// Program Entry Point +// ================================================================ + +fn main() { + // ------------------------------------------------------------ + // Raw Dataset + // ------------------------------------------------------------ + let data: Vec = vec![ + 12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, + 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, + 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, + 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, + 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, + 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146, + ]; + + // ------------------------------------------------------------ + // Functional Processing Pipeline + // ------------------------------------------------------------ + let stem_leaf_structure = build_stem_leaf(&data); + let plot = render_plot(&stem_leaf_structure); + + // ------------------------------------------------------------ + // Output (Monospaced Plain Text) + // ------------------------------------------------------------ + println!("{}", plot); +} diff --git a/Task/Stem-and-leaf-plot/Uiua/stem-and-leaf-plot.uiua b/Task/Stem-and-leaf-plot/Uiua/stem-and-leaf-plot.uiua new file mode 100644 index 0000000000..bf17c72c09 --- /dev/null +++ b/Task/Stem-and-leaf-plot/Uiua/stem-and-leaf-plot.uiua @@ -0,0 +1,10 @@ +[12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 + 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 + 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 + 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 + 43 117 116 27 7 68 40 31 115 124 42 128 146 52 71 118 117 38 + 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 + 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116] + +°⊏⊕(□⍆◿10)⌊⊸÷10 +≡₀◇(&p$"_ | _"⬚@ ↙¯2°⋕⊙/$"_ _") diff --git a/Task/Stern-Brocot-sequence/Ada/stern-brocot-sequence.ada b/Task/Stern-Brocot-sequence/Ada/stern-brocot-sequence.adb similarity index 100% rename from Task/Stern-Brocot-sequence/Ada/stern-brocot-sequence.ada rename to Task/Stern-Brocot-sequence/Ada/stern-brocot-sequence.adb diff --git a/Task/Stern-Brocot-sequence/EasyLang/stern-brocot-sequence.easy b/Task/Stern-Brocot-sequence/EasyLang/stern-brocot-sequence.easy index 47fda5ad77..790fbb9b7a 100644 --- a/Task/Stern-Brocot-sequence/EasyLang/stern-brocot-sequence.easy +++ b/Task/Stern-Brocot-sequence/EasyLang/stern-brocot-sequence.easy @@ -1,5 +1,5 @@ global sb[] . -proc sternbrocot n . . +proc sternbrocot n . sb[] = [ 1 1 ] pos = 2 repeat diff --git a/Task/Stern-Brocot-sequence/Elixir/stern-brocot-sequence.elixir b/Task/Stern-Brocot-sequence/Elixir/stern-brocot-sequence.ex similarity index 100% rename from Task/Stern-Brocot-sequence/Elixir/stern-brocot-sequence.elixir rename to Task/Stern-Brocot-sequence/Elixir/stern-brocot-sequence.ex diff --git a/Task/Stern-Brocot-sequence/Julia/stern-brocot-sequence.julia b/Task/Stern-Brocot-sequence/Julia/stern-brocot-sequence.jl similarity index 100% rename from Task/Stern-Brocot-sequence/Julia/stern-brocot-sequence.julia rename to Task/Stern-Brocot-sequence/Julia/stern-brocot-sequence.jl diff --git a/Task/Stern-Brocot-sequence/Kotlin/stern-brocot-sequence.kotlin b/Task/Stern-Brocot-sequence/Kotlin/stern-brocot-sequence.kts similarity index 100% rename from Task/Stern-Brocot-sequence/Kotlin/stern-brocot-sequence.kotlin rename to Task/Stern-Brocot-sequence/Kotlin/stern-brocot-sequence.kts diff --git a/Task/Stern-Brocot-sequence/OCaml/stern-brocot-sequence-1.ocaml b/Task/Stern-Brocot-sequence/OCaml/stern-brocot-sequence-1.ml similarity index 100% rename from Task/Stern-Brocot-sequence/OCaml/stern-brocot-sequence-1.ocaml rename to Task/Stern-Brocot-sequence/OCaml/stern-brocot-sequence-1.ml diff --git a/Task/Stern-Brocot-sequence/OCaml/stern-brocot-sequence-2.ocaml b/Task/Stern-Brocot-sequence/OCaml/stern-brocot-sequence-2.ml similarity index 100% rename from Task/Stern-Brocot-sequence/OCaml/stern-brocot-sequence-2.ocaml rename to Task/Stern-Brocot-sequence/OCaml/stern-brocot-sequence-2.ml diff --git a/Task/Stern-Brocot-sequence/PowerShell/stern-brocot-sequence.psh b/Task/Stern-Brocot-sequence/PowerShell/stern-brocot-sequence.ps1 similarity index 100% rename from Task/Stern-Brocot-sequence/PowerShell/stern-brocot-sequence.psh rename to Task/Stern-Brocot-sequence/PowerShell/stern-brocot-sequence.ps1 diff --git a/Task/Stern-Brocot-sequence/Rust/stern-brocot-sequence.rs b/Task/Stern-Brocot-sequence/Rust/stern-brocot-sequence.rs new file mode 100644 index 0000000000..adf0d6fbea --- /dev/null +++ b/Task/Stern-Brocot-sequence/Rust/stern-brocot-sequence.rs @@ -0,0 +1,38 @@ +use gcd::Gcd; + +fn stern_brocot(up_to: u64) -> Vec { + let mut seq = vec![1_u64, 1]; + let mut last = 1_u64; + let mut idx = 1_usize; + while last < up_to { + last = seq[idx]; + seq.push(last + seq[idx - 1]); + seq.push(last); + idx += 1; + } + seq +} + +fn test_stern_brocot() { + let seq = stern_brocot(100); + println!("First 15 in sequence: {:?}", &seq[0..15]); + println!("First positions of integers 1 through 10:"); + for i in 1..=10 { + match seq.iter().position(|n| *n == i) { + Some(idx) => println!(" {:>2} at position {}", i, idx + 1), + _ => eprintln!("Error finding position of {}", i), + } + } + println!( + " 100 at position {}", + seq.iter().position(|n| *n == 100).unwrap_or(0) + 1 + ); + println!( + "The first 999 consecutive pairs have gcd of 1: {}.", + (1..1000).all(|i| seq[i - 1].gcd(seq[i]) == 1) + ); +} + +fn main() { + test_stern_brocot(); +} diff --git a/Task/Stern-Brocot-sequence/Scheme/stern-brocot-sequence-1.ss b/Task/Stern-Brocot-sequence/Scheme/stern-brocot-sequence-1.scm similarity index 100% rename from Task/Stern-Brocot-sequence/Scheme/stern-brocot-sequence-1.ss rename to Task/Stern-Brocot-sequence/Scheme/stern-brocot-sequence-1.scm diff --git a/Task/Stern-Brocot-sequence/Scheme/stern-brocot-sequence-2.ss b/Task/Stern-Brocot-sequence/Scheme/stern-brocot-sequence-2.scm similarity index 100% rename from Task/Stern-Brocot-sequence/Scheme/stern-brocot-sequence-2.ss rename to Task/Stern-Brocot-sequence/Scheme/stern-brocot-sequence-2.scm diff --git a/Task/Stern-Brocot-sequence/VBScript/stern-brocot-sequence.vb b/Task/Stern-Brocot-sequence/VBScript/stern-brocot-sequence.vbs similarity index 100% rename from Task/Stern-Brocot-sequence/VBScript/stern-brocot-sequence.vb rename to Task/Stern-Brocot-sequence/VBScript/stern-brocot-sequence.vbs diff --git a/Task/Stern-Brocot-sequence/XPL0/stern-brocot-sequence.xpl0 b/Task/Stern-Brocot-sequence/XPL0/stern-brocot-sequence.xpl0 new file mode 100644 index 0000000000..cf569321a3 --- /dev/null +++ b/Task/Stern-Brocot-sequence/XPL0/stern-brocot-sequence.xpl0 @@ -0,0 +1,40 @@ +func GCD(N, D); \Return the greatest common divisor of N and D +int N, D; \numerator and denominator +int R; +[if D > N then + [R:=D; D:=N; N:=R]; \swap D and N +while D > 0 do + [R:= rem(N/D); + N:= D; + D:= R; + ]; +return N; +]; + +int Seq(1200), Con, I, N; +[Seq(0):= 1; Seq(1):= 1; Con:= 1; I:= 2; +repeat Seq(I):= Seq(Con) + Seq(Con-1); + I:= I+1; + Seq(I):= Seq(Con); + I:= I+1; + Con:= Con+1; +until I >= 1200; +Text(0, "First 15 members of the Stern-Brocot sequence:^m^j"); +for I:= 0 to 15-1 do + [IntOut(0, Seq(I)); ChOut(0, ^ )]; +CrLf(0); +N:= 1; I:= 0; +repeat if Seq(I) = N then + [if N <= 10 or N = 100 then + [Text(0, "First "); IntOut(0, N); + Text(0, " at "); IntOut(0, I+1); CrLf(0); + ]; + N:= N+1; + I:= 0; + ]; + I:= I+1; +until N > 100; +for I:= 0 to 1000-1 do + if GCD(Seq(I), Seq(I+1)) # 1 then return; +Text(0, "All GCD are 1^m^j"); +] diff --git a/Task/Stern-Brocot-sequence/Zig/stern-brocot-sequence.zig b/Task/Stern-Brocot-sequence/Zig/stern-brocot-sequence.zig new file mode 100644 index 0000000000..8883a3ef63 --- /dev/null +++ b/Task/Stern-Brocot-sequence/Zig/stern-brocot-sequence.zig @@ -0,0 +1,81 @@ +const std = @import("std"); + +fn gcd(a: u64, b: u64) u64 { + if (b == 0) return a; + return gcd(b, a % b); +} + +fn sternBrocot(allocator: std.mem.Allocator, up_to: u64) !std.ArrayList(u64) { + var seq = std.ArrayList(u64).init(allocator); + try seq.append(1); + try seq.append(1); + + var last: u64 = 1; + var idx: usize = 1; + + while (last < up_to) { + last = seq.items[idx]; + try seq.append(last + seq.items[idx - 1]); + try seq.append(last); + idx += 1; + } + + return seq; +} + +fn testSternBrocot() !void { + var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); + defer arena.deinit(); + const allocator = arena.allocator(); + + var seq = try sternBrocot(allocator, 100); + + // Print first 15 in sequence + std.debug.print("First 15 in sequence: ", .{}); + std.debug.print("[", .{}); + for (seq.items[0..15], 0..) |val, i| { + if (i > 0) std.debug.print(", ", .{}); + std.debug.print("{d}", .{val}); + } + std.debug.print("]\n", .{}); + + // Print first positions of integers 1 through 10 + std.debug.print("First positions of integers 1 through 10:\n", .{}); + for (1..11) |i| { + const i_u64 = @as(u64, i); + var found = false; + for (seq.items, 0..) |val, pos| { + if (val == i_u64) { + std.debug.print(" {d:>2} at position {d}\n", .{i, pos + 1}); + found = true; + break; + } + } + if (!found) { + std.debug.print("Error finding position of {d}\n", .{i}); + } + } + + // Find position of 100 + for (seq.items, 0..) |val, pos| { + if (val == 100) { + std.debug.print(" 100 at position {d}\n", .{pos + 1}); + break; + } + } + + // Check if first 999 consecutive pairs have gcd of 1 + var all_gcd_one = true; + for (1..1000) |i| { + if (i >= seq.items.len) break; + if (gcd(seq.items[i - 1], seq.items[i]) != 1) { + all_gcd_one = false; + break; + } + } + std.debug.print("The first 999 consecutive pairs have gcd of 1: {any}.\n", .{all_gcd_one}); +} + +pub fn main() !void { + try testSternBrocot(); +} diff --git a/Task/Stirling-numbers-of-the-first-kind/ALGOL-68/stirling-numbers-of-the-first-kind.alg b/Task/Stirling-numbers-of-the-first-kind/ALGOL-68/stirling-numbers-of-the-first-kind.alg index bc634da110..35de7d8854 100644 --- a/Task/Stirling-numbers-of-the-first-kind/ALGOL-68/stirling-numbers-of-the-first-kind.alg +++ b/Task/Stirling-numbers-of-the-first-kind/ALGOL-68/stirling-numbers-of-the-first-kind.alg @@ -9,7 +9,8 @@ BEGIN # show some (unsigned) Stirling numbers of the first kind # # the numbers are signed if signed is TRUE, unsigned otherwise # PROC make s1 = ( INT max n, BOOL signed )REF[,]SINT: BEGIN - REF[,]SINT s1 := HEAP[ 0 : max n, 0 : max n ]SINT; + + HEAP[ 0 : max n, 0 : max n ]SINT s1; FOR n FROM 0 TO max n DO FOR k FROM 0 TO max n DO s1[ n, k ] := 0 OD OD; s1[ 0, 0 ] := 1; FOR n FROM 1 TO max n DO s1[ n, 0 ] := 0 OD; diff --git a/Task/Stirling-numbers-of-the-first-kind/Crystal/stirling-numbers-of-the-first-kind.cr b/Task/Stirling-numbers-of-the-first-kind/Crystal/stirling-numbers-of-the-first-kind.cr new file mode 100644 index 0000000000..5248bf09ac --- /dev/null +++ b/Task/Stirling-numbers-of-the-first-kind/Crystal/stirling-numbers-of-the-first-kind.cr @@ -0,0 +1,27 @@ +require "big" + +CACHE = {} of {Int32, Int32, Bool} => BigInt + +def s1 (n, k, signed=false) + return CACHE[{n, k, signed}] if CACHE.has_key?({n, k, signed}) + case + when n == k == 0 then return 1.to_big_i + when n > 0 && k == 0 then return 0.to_big_i + when k > n then return 0.to_big_i + end + result = if signed + s1(n-1, k-1) - (n-1) * s1(n-1, k) + else + s1(n-1, k-1) + (n-1) * s1(n-1, k) + end + CACHE[{n, k, signed}] = result +end + +puts "S1(n, k) (unsigned) for n in 1..12:" +puts "n\\k" + (1..12).map {|k| " %10d" % k }.join +(1..12).each do |n| + puts ("%2d " % n) + (1..n).map {|k| " %10d" % s1(n, k) }.join +end +puts +puts "Maximum value of S1(n, k) (unsigned) where n = 100:" +puts (1..100).max_of {|k| s1(100, k) } diff --git a/Task/Stirling-numbers-of-the-first-kind/EasyLang/stirling-numbers-of-the-first-kind.easy b/Task/Stirling-numbers-of-the-first-kind/EasyLang/stirling-numbers-of-the-first-kind.easy index 9b5db0730b..320d00d7ea 100644 --- a/Task/Stirling-numbers-of-the-first-kind/EasyLang/stirling-numbers-of-the-first-kind.easy +++ b/Task/Stirling-numbers-of-the-first-kind/EasyLang/stirling-numbers-of-the-first-kind.easy @@ -1,6 +1,6 @@ print "Unsigned Stirling numbers of the first kind:" -len a[] 13 ; arrbase a[] 0 -len b[] 13 ; arrbase b[] 0 +len a[] 13 +len b[] 13 a[0] = 1 print 1 for n = 1 to 12 diff --git a/Task/Stirling-numbers-of-the-first-kind/Forth/stirling-numbers-of-the-first-kind.fth b/Task/Stirling-numbers-of-the-first-kind/Forth/stirling-numbers-of-the-first-kind.fth new file mode 100644 index 0000000000..59e9154b80 --- /dev/null +++ b/Task/Stirling-numbers-of-the-first-kind/Forth/stirling-numbers-of-the-first-kind.fth @@ -0,0 +1,25 @@ +: s1 ( n k -- u ) + dup 0= if + drop 0> if 0 else 1 then exit + then + 2dup < if 2drop 0 exit then + swap 1- swap + 2dup 1- recurse >r + over swap recurse + * r> + ; + +: main ( -- ) + ." Unsigned Stirling numbers of the first kind:" cr + ." n/k" + 13 1 do + i 10 .r + loop cr + 13 1 do + i 3 .r + i 1+ 1 do + j i s1 10 .r + loop cr + loop ; + +main +bye diff --git a/Task/Stirling-numbers-of-the-first-kind/Julia/stirling-numbers-of-the-first-kind.julia b/Task/Stirling-numbers-of-the-first-kind/Julia/stirling-numbers-of-the-first-kind.jl similarity index 100% rename from Task/Stirling-numbers-of-the-first-kind/Julia/stirling-numbers-of-the-first-kind.julia rename to Task/Stirling-numbers-of-the-first-kind/Julia/stirling-numbers-of-the-first-kind.jl diff --git a/Task/Stirling-numbers-of-the-first-kind/Kotlin/stirling-numbers-of-the-first-kind.kotlin b/Task/Stirling-numbers-of-the-first-kind/Kotlin/stirling-numbers-of-the-first-kind.kts similarity index 100% rename from Task/Stirling-numbers-of-the-first-kind/Kotlin/stirling-numbers-of-the-first-kind.kotlin rename to Task/Stirling-numbers-of-the-first-kind/Kotlin/stirling-numbers-of-the-first-kind.kts diff --git a/Task/Stirling-numbers-of-the-first-kind/Maxima/stirling-numbers-of-the-first-kind.maxima b/Task/Stirling-numbers-of-the-first-kind/Maxima/stirling-numbers-of-the-first-kind.maxima new file mode 100644 index 0000000000..f4a05dddc2 --- /dev/null +++ b/Task/Stirling-numbers-of-the-first-kind/Maxima/stirling-numbers-of-the-first-kind.maxima @@ -0,0 +1,9 @@ +block( + sprint("n | (k from 1 to n)"), + newline(), + for n from 1 thru 12 do( + sprint(n, "|"), + for k from 1 thru n do sprint(stirling1(n, k)), + newline() + ) +)$ diff --git a/Task/Stirling-numbers-of-the-first-kind/Oberon-07/stirling-numbers-of-the-first-kind.oberon b/Task/Stirling-numbers-of-the-first-kind/Oberon-07/stirling-numbers-of-the-first-kind.oberon new file mode 100644 index 0000000000..bb0a399048 --- /dev/null +++ b/Task/Stirling-numbers-of-the-first-kind/Oberon-07/stirling-numbers-of-the-first-kind.oberon @@ -0,0 +1,58 @@ +MODULE StirlingNumbersOfTheFirstKind; + (* show some (unsigned) Stirling numbers of the first kind *) + IMPORT Out; + + CONST maxStirling = 12; + VAR stirling : ARRAY maxStirling + 1, maxStirling + 1 OF INTEGER; + + (* sets s1 to a matrix of Stirling numbers; s1 must be square *) + PROCEDURE getStirling( VAR s1 : ARRAY OF ARRAY OF INTEGER ) ; + VAR maxN, n, k : INTEGER; + BEGIN + maxN := LEN( s1 ) - 1; + FOR n := 0 TO maxN DO + FOR k := 0 TO maxN DO s1[ n, k ] := 0 END + END; + s1[ 0, 0 ] := 1; + FOR n := 1 TO maxN DO + FOR k := 1 TO n DO + s1[ n, k ] := s1[ n - 1, k - 1 ] + + ( ( n - 1 ) * s1[ n - 1, k ] ) + END + END + END getStirling ; + + (* prints the Stirling numbers in s1 *) + PROCEDURE printStirling( s1 : ARRAY OF ARRAY OF INTEGER ) ; + VAR maxN, n, k : INTEGER; + + (* prints a Stirling number e in a width suitable for k... *) + (* assuming e is in a table of Stirling numbers with n <= 12 *) + PROCEDURE print1( e, k : INTEGER ) ; + BEGIN + IF k = 0 THEN Out.Int( e, 3 ) + ELSIF k < 5 THEN Out.Int( e, 10 ) + ELSIF k < 8 THEN Out.Int( e, 9 ) + ELSIF k < 11 THEN Out.Int( e, 7 ) + ELSE Out.Int( e, 4 ) + END + END print1 ; + + BEGIN + maxN := LEN( s1 ) - 1; + Out.String( "Unsigned Stirling numbers of the first kind:" );Out.Ln; + Out.String( " k" ); + FOR k := 0 TO maxN DO print1( k, k ) END; + Out.Ln; + Out.String( " n" );Out.Ln; + FOR n := 0 TO maxN DO + Out.Int( n, 2 ); + FOR k := 0 TO n DO print1( s1[ n, k ], k ) END; + Out.Ln + END + END printStirling ; + +BEGIN + getStirling( stirling ); + printStirling( stirling ) +END StirlingNumbersOfTheFirstKind. diff --git a/Task/Stirling-numbers-of-the-first-kind/Pluto/stirling-numbers-of-the-first-kind.pluto b/Task/Stirling-numbers-of-the-first-kind/Pluto/stirling-numbers-of-the-first-kind.pluto new file mode 100644 index 0000000000..254e4c0b67 --- /dev/null +++ b/Task/Stirling-numbers-of-the-first-kind/Pluto/stirling-numbers-of-the-first-kind.pluto @@ -0,0 +1,40 @@ +local bigint = require "pluto:bigint" +local fmt = require "fmt" + +local zero = bigint.new(0) +local one = bigint.new(1) + +local computed = {} + +local function stirling1(n, k) + local key = $"{n},{k}" + if c := computed[key] then return c end + if n == 0 and k == 0 then return one end + if n > 0 and k == 0 then return zero end + if k > n then return zero end + local result = stirling1(n - 1, k - 1) + stirling1(n - 1, k) * (n - 1) + computed[key] = result + return result +end + +print("Unsigned Stirling numbers of the first kind:") +local max = 12 +io.write("n/k") +for n = 0, max do fmt.write("%10d", n) end +print("\n" .. string.rep("-", 133)) +for n = 0, max do + fmt.write("%-3d", n) + for k = 0, n do fmt.write("%10s", stirling1(n, k)) end + print() +end +print("\nThe maximum value of S1(100, k) =") +local previous = zero +for k = 1, 100 do + local current = stirling1(100, k) + if current > previous then + previous = current + else + fmt.print("%s\n(%d digits, k = %d)", previous, #previous:tostring(), k - 1) + break + end +end diff --git a/Task/Stirling-numbers-of-the-second-kind/ALGOL-68/stirling-numbers-of-the-second-kind.alg b/Task/Stirling-numbers-of-the-second-kind/ALGOL-68/stirling-numbers-of-the-second-kind.alg index e897a70f50..e1f49696eb 100644 --- a/Task/Stirling-numbers-of-the-second-kind/ALGOL-68/stirling-numbers-of-the-second-kind.alg +++ b/Task/Stirling-numbers-of-the-second-kind/ALGOL-68/stirling-numbers-of-the-second-kind.alg @@ -8,7 +8,7 @@ BEGIN # show some Stirling numbers of the second kind # # returns a triangular matrix of Stirling numbers up to max n, max n # PROC make s2 = ( INT max n )REF[,]SINT: BEGIN - REF[,]SINT s2 := HEAP[ 0 : max n, 0 : max n ]SINT; + HEAP[ 0 : max n, 0 : max n ]SINT s2; FOR n FROM 0 TO max n DO FOR k FROM 0 TO max n DO s2[ n, k ] := 0 OD OD; FOR n FROM 0 TO max n DO s2[ n, n ] := 1 OD; FOR n FROM 0 TO max n - 1 DO diff --git a/Task/Stirling-numbers-of-the-second-kind/EasyLang/stirling-numbers-of-the-second-kind.easy b/Task/Stirling-numbers-of-the-second-kind/EasyLang/stirling-numbers-of-the-second-kind.easy index ccd351f6a9..09c9e9a609 100644 --- a/Task/Stirling-numbers-of-the-second-kind/EasyLang/stirling-numbers-of-the-second-kind.easy +++ b/Task/Stirling-numbers-of-the-second-kind/EasyLang/stirling-numbers-of-the-second-kind.easy @@ -1,6 +1,6 @@ print "Unsigned Stirling numbers of the second kind:" -len a[] 13 ; arrbase a[] 0 -len b[] 13 ; arrbase b[] 0 +len a[] 13 +len b[] 13 a[0] = 1 print 1 for n = 1 to 12 diff --git a/Task/Stirling-numbers-of-the-second-kind/Forth/stirling-numbers-of-the-second-kind.fth b/Task/Stirling-numbers-of-the-second-kind/Forth/stirling-numbers-of-the-second-kind.fth new file mode 100644 index 0000000000..f5526fccd0 --- /dev/null +++ b/Task/Stirling-numbers-of-the-second-kind/Forth/stirling-numbers-of-the-second-kind.fth @@ -0,0 +1,23 @@ +: s2 ( n k -- u ) + dup 0= if 2drop 0 exit then + over 0= if 2drop 0 exit then + 2dup = if 2drop 1 exit then + swap 1- swap + 2dup 1- recurse >r + tuck recurse * r> + ; + +: main ( -- ) + ." Stirling numbers of the second kind:" cr + ." n/k" + 13 1 do + i 8 .r + loop cr + 13 1 do + i 3 .r + i 1+ 1 do + j i s2 8 .r + loop cr + loop ; + +main +bye diff --git a/Task/Stirling-numbers-of-the-second-kind/Julia/stirling-numbers-of-the-second-kind.julia b/Task/Stirling-numbers-of-the-second-kind/Julia/stirling-numbers-of-the-second-kind.jl similarity index 100% rename from Task/Stirling-numbers-of-the-second-kind/Julia/stirling-numbers-of-the-second-kind.julia rename to Task/Stirling-numbers-of-the-second-kind/Julia/stirling-numbers-of-the-second-kind.jl diff --git a/Task/Stirling-numbers-of-the-second-kind/Kotlin/stirling-numbers-of-the-second-kind.kotlin b/Task/Stirling-numbers-of-the-second-kind/Kotlin/stirling-numbers-of-the-second-kind.kts similarity index 100% rename from Task/Stirling-numbers-of-the-second-kind/Kotlin/stirling-numbers-of-the-second-kind.kotlin rename to Task/Stirling-numbers-of-the-second-kind/Kotlin/stirling-numbers-of-the-second-kind.kts diff --git a/Task/Stirling-numbers-of-the-second-kind/Maxima/stirling-numbers-of-the-second-kind.maxima b/Task/Stirling-numbers-of-the-second-kind/Maxima/stirling-numbers-of-the-second-kind.maxima new file mode 100644 index 0000000000..ec97586008 --- /dev/null +++ b/Task/Stirling-numbers-of-the-second-kind/Maxima/stirling-numbers-of-the-second-kind.maxima @@ -0,0 +1,9 @@ +block( + sprint("n | (k from 1 to n)"), + newline(), + for n from 1 thru 12 do( + sprint(n, "|"), + for k from 1 thru n do sprint(stirling2(n, k)), + newline() + ) +)$ diff --git a/Task/Stirling-numbers-of-the-second-kind/Pluto/stirling-numbers-of-the-second-kind.pluto b/Task/Stirling-numbers-of-the-second-kind/Pluto/stirling-numbers-of-the-second-kind.pluto new file mode 100644 index 0000000000..21497dca6b --- /dev/null +++ b/Task/Stirling-numbers-of-the-second-kind/Pluto/stirling-numbers-of-the-second-kind.pluto @@ -0,0 +1,40 @@ +local bigint = require "pluto:bigint" +local fmt = require "fmt" + +local zero = bigint.new(0) +local one = bigint.new(1) + +local computed = {} + +local function stirling2(n, k) + local key = $"{n},{k}" + if c := computed[key] then return c end + if n == 0 and k == 0 then return one end + if (n > 0 and k == 0) or (n == 0 and k > 0) then return zero end + if k == n then return one end + local result = stirling2(n - 1, k - 1) + stirling2(n - 1, k) * k + computed[key] = result + return result +end + +print("Unsigned Stirling numbers of the second kind:") +local max = 12 +io.write("n/k") +for n = 0, max do fmt.write("%10d", n) end +print("\n" .. string.rep("-", 133)) +for n = 0, max do + fmt.write("%-3d", n) + for k = 0, n do fmt.write("%10s", stirling2(n, k)) end + print() +end +print("\nThe maximum value of S2(100, k) =") +local previous = zero +for k = 1, 100 do + local current = stirling2(100, k) + if current > previous then + previous = current + else + fmt.print("%s\n(%d digits, k = %d)", previous, #previous:tostring(), k - 1) + break + end +end diff --git a/Task/Straddling-checkerboard/AutoHotkey/straddling-checkerboard.ahk b/Task/Straddling-checkerboard/AutoHotkey/straddling-checkerboard.ahk index 6f227a12f9..203db51611 100644 --- a/Task/Straddling-checkerboard/AutoHotkey/straddling-checkerboard.ahk +++ b/Task/Straddling-checkerboard/AutoHotkey/straddling-checkerboard.ahk @@ -11,31 +11,31 @@ Num2 := InStr(board, A_Space) -1 Num3 := InStr(board, A_Space, true, Num1+1) -1 Loop Parse, Text { - char := A_LoopField - Loop Parse, board, `n - { - If (Pos := InStr(A_LoopField, char)) - out .= Num%A_Index% . Pos-1 - else if (Pos := InStr(A_LoopField, "/")) && InStr("0123456789", char) - out .= Num%A_Index% . Pos-1 . char - } + char := A_LoopField + Loop Parse, board, `n + { + If (Pos := InStr(A_LoopField, char)) + out .= Num%A_Index% . Pos-1 + else if (Pos := InStr(A_LoopField, "/")) && InStr("0123456789", char) + out .= Num%A_Index% . Pos-1 . char + } } MsgBox % out i := 0 While (LoopField := SubStr(out, ++i, 1)) <> "" { - If (LoopField = num2) or (LoopField = num3) - col := SubStr(out, ++i, 1) - else col := 0 - Loop Parse, board, `n - { - If !col && A_Index = 1 - dec .= SubStr(A_LoopField, LoopField+1, 1) - Else If (Num%A_Index% = LoopField) && col - dec .= SubStr(A_LoopField, col+1, 1) - If SubStr(dec, 0) = "/" - dec := SubStr(dec, 1, StrLen(dec)-1) . SubStr(out, ++i, 1) - } + If (LoopField = num2) or (LoopField = num3) + col := SubStr(out, ++i, 1) + else col := 0 + Loop Parse, board, `n + { + If !col && A_Index = 1 + dec .= SubStr(A_LoopField, LoopField+1, 1) + Else If (Num%A_Index% = LoopField) && col + dec .= SubStr(A_LoopField, col+1, 1) + If SubStr(dec, 0) = "/" + dec := SubStr(dec, 1, StrLen(dec)-1) . SubStr(out, ++i, 1) + } } MsgBox % dec diff --git a/Task/Straddling-checkerboard/C/straddling-checkerboard-1.c b/Task/Straddling-checkerboard/C/straddling-checkerboard-1.c index 8858bd680d..b313fd8c29 100644 --- a/Task/Straddling-checkerboard/C/straddling-checkerboard-1.c +++ b/Task/Straddling-checkerboard/C/straddling-checkerboard-1.c @@ -79,7 +79,7 @@ GHashTable *create_table_from_array(const char *table[ROWS][COLS], bool is_encod numprefix_col = i; numprefix_row = j; has_numprefix = true; - break; + break; } } } @@ -92,21 +92,21 @@ GHashTable *create_table_from_array(const char *table[ROWS][COLS], bool is_encod if (table[i][j] == NULL) continue; if (strlen(table[i][j]) > 1) { - fprintf(stderr, "symbols must be 1 byte long\n"); - continue; // we continue just ignoring the issue + fprintf(stderr, "symbols must be 1 byte long\n"); + continue; // we continue just ignoring the issue } if (has_numprefix && i == (ROWS-1) && j == numprefix_col && i == numprefix_row) continue; if (has_numprefix && i == 0) { - snprintf(buf, sizeof(buf), "%s%s%s", table[0][selectors[SELNUM-1]], table[0][numprefix_col], table[0][j]); + snprintf(buf, sizeof(buf), "%s%s%s", table[0][selectors[SELNUM-1]], table[0][numprefix_col], table[0][j]); } else if (i == 1) { - snprintf(buf, sizeof(buf), "%s", table[0][j]); + snprintf(buf, sizeof(buf), "%s", table[0][j]); } else { - snprintf(buf, sizeof(buf), "%s%s", table[0][selectors[i-2]], table[0][j]); + snprintf(buf, sizeof(buf), "%s%s", table[0][selectors[i-2]], table[0][j]); } if (is_encoding) g_hash_table_insert(r, strdup(table[i][j]), strdup(buf)); else g_hash_table_insert(r, strdup(buf), strdup(table[i][j])); @@ -179,8 +179,8 @@ char *encode(GHashTable *et, const char *plaintext, int (*trasf)(int), bool comp else { fprintf(stderr, "char '%s' is not encodable%s\n", - isprint(buf[0]) ? buf : "?", - !compress_spaces ? ", replacing with a space" : ""); + isprint(buf[0]) ? buf : "?", + !compress_spaces ? ", replacing with a space" : ""); if (!compress_spaces) g_string_append_c(s, ' '); } } diff --git a/Task/Straddling-checkerboard/Crystal/straddling-checkerboard.cr b/Task/Straddling-checkerboard/Crystal/straddling-checkerboard.cr new file mode 100644 index 0000000000..39808905c1 --- /dev/null +++ b/Task/Straddling-checkerboard/Crystal/straddling-checkerboard.cr @@ -0,0 +1,49 @@ +def encrypt (board, message) + prefixes = [""] + board.first.chars.each.with_index.select {|ch, _| ch == ' ' }.map(&.last.to_s).to_a + encode_letter = ->(ch : Char) { + col = nil + row = board.index {|r| col = r.index ch} + raise "incomplete board" unless col && row + prefixes[row] + col.to_s + } + String.build do |s| + message.each_char do |ch| + if ch.ascii_number? + s << encode_letter['/'] << ch + else + ch = ch.ascii_letter? ? ch.upcase : '.' + s << encode_letter[ch] + end + end + end +end + +def decrypt (board, message) + prefixes = board.first.chars.each.with_index.select {|ch, _| ch == ' ' }.map {|ch, idx| '0' + idx}.to_a + message = message.chars + String.build do |s| + i = 0 + while i < message.size + row = prefixes.index(message[i]) + letter = if row + board[row+1][message[i+=1].to_i] + else + board[0][message[i].to_i] + end + if letter == '/' + s << message[i+=1] + else + s << letter + end + i += 1 + end + end +end + +board = ["ET AON RIS", "BCDFGHJKLM", "PQ/UVWXYZ."] + +original = "One night-it was on the twentieth of March, 1888-I was returning" +coded = encrypt(board, original) +decoded = decrypt(board, coded) + +p! original, coded, decoded diff --git a/Task/Straddling-checkerboard/EasyLang/straddling-checkerboard.easy b/Task/Straddling-checkerboard/EasyLang/straddling-checkerboard.easy new file mode 100644 index 0000000000..117f165017 --- /dev/null +++ b/Task/Straddling-checkerboard/EasyLang/straddling-checkerboard.easy @@ -0,0 +1,71 @@ +board$ = "ET AON RISBCDFGHJKLMPQ/UVWXYZ." +len encode[] 128 +len decode$[] 128 +len row[] 2 +proc init s$ . + s$[] = strchars s$ + for i = 1 to 30 + if s$[i] = " " + if row[1] = 0 + row[1] = i - 1 + else + row[2] = i - 1 + . + else + code = 0 + if i > 20 + code = row[2] + elif i > 10 + code = row[1] + . + code = code * 10 + (i - 1) mod 10 + encode[strcode s$[i]] = code + decode$[code] = s$[i] + . + . +. +func$ encipher in$ . + for c$ in strchars in$ + c = strcode c$ + if c >= 48 and c <= 57 + code = encode[strcode "."] + r$ &= code + r$ &= c$ + else + c = bitand c 0xdf + if c <> 0 + if c >= 65 and c <= 90 + code = encode[c] + else + code = encode[strcode "/"] + . + r$ &= code + . + . + . + return r$ +. +func$ decipher in$ . + in$[] = strchars in$ + for i to len in$[] + c$ = in$[i] + c = strcode c$ - 48 + if c = row[1] or c = row[2] + i += 1 + c = c * 10 + strcode in$[i] - 48 + . + c$ = decode$[c] + if c$ = "." + i += 1 + c$ = in$[i] + . + r$ &= c$ + . + return r$ +. +init board$ +msg$ = "In the winter 1965/we were hungry/just barely alive" +print msg$ +ciph$ = encipher msg$ +print ciph$ +print decipher ciph$ diff --git a/Task/Straddling-checkerboard/JavaScript/straddling-checkerboard.js b/Task/Straddling-checkerboard/JavaScript/straddling-checkerboard.js index 320a1cc5bc..461fb5effa 100644 --- a/Task/Straddling-checkerboard/JavaScript/straddling-checkerboard.js +++ b/Task/Straddling-checkerboard/JavaScript/straddling-checkerboard.js @@ -8,13 +8,13 @@ function straddle(message){ message=message.replace(/([0-9])/g,"/$1") // dumb way to escape numbers for(var i=0;inumbers, numbers1) - else.if n<20 then - n+=num0 - else.if n<30 then - n+=num10 - else - n+=num20 - end if - encoded$+=str$(n,"") - next - =encoded$ - } - function decrypt$(encoded$, alphabet) { - def num1, num2 - num1=instr(alphabet#val$(0)," ") - num2=instr(alphabet#val$(0)," ", num1+1)-1 - num1-- - escapenum=instr(alphabet#val$(2),"/")-1 - escapenum1=instr(alphabet#val$(2),".")-1 - def i=1, decoded$ - j=len(encoded$)+1 - while inumbers, numbers1) + else.if n<20 then + n+=num0 + else.if n<30 then + n+=num10 + else + n+=num20 + end if + encoded$+=str$(n,"") + next + =encoded$ + } + function decrypt$(encoded$, alphabet) { + def num1, num2 + num1=instr(alphabet#val$(0)," ") + num2=instr(alphabet#val$(0)," ", num1+1)-1 + num1-- + escapenum=instr(alphabet#val$(2),"/")-1 + escapenum1=instr(alphabet#val$(2),".")-1 + def i=1, decoded$ + j=len(encoded$)+1 + while i (c in board or c in digits) and !(c in " /")) + :reorder() + local sb = "" + for msg as c do + local idx = board:find(c, 1, true) + if idx then + idx -= 1 + local row = idx // 10 + local col = idx % 10 + sb ..= (row == 0) ? $"{col}" : $"{rows[row + 1]}{col}" + else + sb ..= $"{escape}{c}" + end + end + local enc = {sb:byte(1, #sb)} + local i = 0 + for enc as c do + local k = key[i % 4 + 1]:byte() - 48 + if k != 0 then + local j = c - 48 + enc[i + 1] = 48 + ((j + k) % 10) + end + i += 1 + end + + return enc:map(|b| -> string.char(b)):concat("") +end + +local function decrypt(encoded) + local enc = {encoded:byte(1, #encoded)} + local i = 0 + for enc as c do + local k = key[i % 4 + 1]:byte() - 48 + if k != 0 then + local j = c - 48 + enc[i + 1] = 48 + ((j >= k) ? (j - k) % 10 : (10 + j - k) % 10) + end + i += 1 + end + local len = #enc + local sb = "" + i = 0 + while i < len do + local c = enc[i + 1] + local idx = rows:find(tostring(c - 48), 1, true) + if !idx then + local idx2 = c - 48 + sb ..= board[idx2 + 1] + i += 1 + elseif $"{c - 48}{enc[i + 2] - 48}" == escape then + sb ..= tostring(enc[i + 3] - 48) + i += 3 + else + local idx2 = (idx - 1) * 10 + enc[i + 2] - 48 + sb ..= board[idx2 + 1] + i += 2 + end + end + return sb +end + +local messages = { + "Attack at dawn", + "One night-it was on the twentieth of March, 1888-I was returning", + "In the winter 1965/we were hungry/just barely alive", + "you have put on 7.5 pounds since I saw you.", + "The checkerboard cake recipe specifies 3 large eggs and 2.25 cups of flour." +} +for messages as message do + local encrypted = encrypt(message) + local decrypted = decrypt(encrypted) + print($"\nMessage : {message}") + print($"Encrypted : {encrypted}") + print($"Decrypted : {decrypted}") +end diff --git a/Task/Straddling-checkerboard/Rebol/straddling-checkerboard.rebol b/Task/Straddling-checkerboard/Rebol/straddling-checkerboard.rebol new file mode 100644 index 0000000000..e3e7686a5e --- /dev/null +++ b/Task/Straddling-checkerboard/Rebol/straddling-checkerboard.rebol @@ -0,0 +1,78 @@ +Rebol [ + title: "Rosetta code: Straddling checkerboard" + file: %Straddling_checkerboard.r3 + url: https://rosettacode.org/wiki/Straddling_checkerboard +] + +register-codec [ + name: 'straddle + type: 'cryptography + title: "Straddling checkerboard" + + T: [ + ["79" #"0" #"1" #"2" #"3" #"4" #"5" #"6" #"7" #"8" #"9"] + ["" #"H" #"O" #"L" "" #"M" #"E" #"S" "" #"R" #"T"] + [#"3" #"A" #"B" #"C" #"D" #"F" #"G" #"I" #"J" #"K" #"N"] + [#"7" #"P" #"Q" #"U" #"V" #"W" #"X" #"Y" #"Z" #"." #"/"] + ] + + header: T/1 ;; digit labels for each column + singles: T/2 ;; single-digit letters (H O L M E S R T) + row3: T/3 ;; two-digit letters starting with 3 + row4: T/4 ;; two-digit letters starting with 7 + + encode: function [ + {Encode plaintext using the straddling checkerboard. + Single-digit letters (row 2) encode to one digit; + all others encode to two digits (row prefix + column digit).} + plaintext [string!] + ][ + result: copy "" + foreach ch plaintext [ + foreach row (next T) [ ;; skip header row + if col: index? find row ch [ + repend result [row/1 header/:col] ;; row prefix ("" for singles) + column digit + break + ] + ] + ] + result + ] + + decode: function [ + {Decode a straddling checkerboard ciphertext back to plaintext. + Reads one digit at a time; if it matches a row prefix (3 or 7) + the next digit selects the column in that row.} + ciphertext [string!] + ][ + result: copy "" + pos: 1 + while [pos <= length? ciphertext] [ + digit: ciphertext/(++ pos) + append result case [ + digit == row3/1 [ ;; escape digit 3 -> read next for row3 + digit: ciphertext/(++ pos) + letter: row3/(2 + digit - #"0") + if letter == #"/" [++ pos] + letter + ] + digit == row4/1 [ ;; escape digit 7 -> read next for row4 + digit: ciphertext/(++ pos) + row4/(2 + digit - #"0") + ] + true [ ;; single-digit: look up in singles row + singles/(2 + digit - #"0") + ] + ] + ] + result + ] +] + +plaintext: "One night-it was on the twentieth of March, 1888-I was returning" +encoded: encode 'straddle plaintext +decoded: decode 'straddle encoded + +print ["Original:" plaintext] +print ["Encoded: " encoded ] +print ["Decoded: " decoded ] diff --git a/Task/Straddling-checkerboard/Tcl/straddling-checkerboard-1.tcl b/Task/Straddling-checkerboard/Tcl/straddling-checkerboard-1.tcl index 327abf9bb7..83f7c39ab0 100644 --- a/Task/Straddling-checkerboard/Tcl/straddling-checkerboard-1.tcl +++ b/Task/Straddling-checkerboard/Tcl/straddling-checkerboard-1.tcl @@ -3,34 +3,34 @@ package require Tcl 8.6 oo::class create StraddlingCheckerboardCypher { variable encmap decmap constructor table { - # Sanity check the table - foreach ch [lindex $table 0] i {"" 0 1 2 3 4 5 6 7 8 9} { - if {$ch eq "" && $i ne "" && [lsearch -index 0 $table $i] < 1} { - error "bad checkerboard table" - } - } - # Synthesize the escaped number row - foreach row $table { - if {"/" ni $row} continue - set pfx [lindex $row 0][expr {[lsearch -exact $row "/"]-1}] - lappend table [list $pfx 0 1 2 3 4 5 6 7 8 9] - break - } - # Build the actual per-character mapping - foreach row $table { - foreach ch [lrange $row 1 end] n {0 1 2 3 4 5 6 7 8 9} { - if {$ch in {"" "/"}} continue; # Skip escape cases - lappend encmap $ch [lindex $row 0]$n - lappend decmap [lindex $row 0]$n $ch - } - } + # Sanity check the table + foreach ch [lindex $table 0] i {"" 0 1 2 3 4 5 6 7 8 9} { + if {$ch eq "" && $i ne "" && [lsearch -index 0 $table $i] < 1} { + error "bad checkerboard table" + } + } + # Synthesize the escaped number row + foreach row $table { + if {"/" ni $row} continue + set pfx [lindex $row 0][expr {[lsearch -exact $row "/"]-1}] + lappend table [list $pfx 0 1 2 3 4 5 6 7 8 9] + break + } + # Build the actual per-character mapping + foreach row $table { + foreach ch [lrange $row 1 end] n {0 1 2 3 4 5 6 7 8 9} { + if {$ch in {"" "/"}} continue; # Skip escape cases + lappend encmap $ch [lindex $row 0]$n + lappend decmap [lindex $row 0]$n $ch + } + } } # These methods just sanitize their input and apply the map method encode msg { - string map $encmap [regsub -all {[^A-Z0-9.]} [string toupper $msg] ""] + string map $encmap [regsub -all {[^A-Z0-9.]} [string toupper $msg] ""] } method decode msg { - string map $decmap [regsub -all {[^0-9]} $msg ""] + string map $decmap [regsub -all {[^0-9]} $msg ""] } } diff --git a/Task/Straddling-checkerboard/V-(Vlang)/straddling-checkerboard.v b/Task/Straddling-checkerboard/V-(Vlang)/straddling-checkerboard.v new file mode 100644 index 0000000000..0aa6c3c782 --- /dev/null +++ b/Task/Straddling-checkerboard/V-(Vlang)/straddling-checkerboard.v @@ -0,0 +1,75 @@ +const key = " + 8752390146 + ET AON RIS +5BC/FGHJKLM +0PQD.VWXYZU" + +const pnt = "you have put on 7.5 pounds since I saw you." + +fn main() { + println(pnt) + cnt := enc(key, pnt) + println(cnt) + println(dec(key, cnt)) +} + +fn enc(bsg string, psg string) string { + row := bsg.split("\n")[1..] + r2d := row[2][..1] + r3d := row[3][..1] + mut enc := map[byte]string{} + mut csg, mut dre, mut num := "", "", "" + for col := 1; col <= 10; col++ { + dre = row[0][col].ascii_str() + enc[row[1][col]] = dre + enc[row[2][col]] = r2d + dre + enc[row[3][col]] = r3d + dre + } + num = enc[`/`] + enc.delete(`/`) + enc.delete(` `) + for cal in psg.bytes() { + if cal >= `0` && cal <= `9` { csg += num + cal.ascii_str() } + else { + mut ch := cal + if ch >= `a` && ch <= `z` { ch -= `a` - `A` } + csg += enc[ch] or { "" } + } + } + return csg +} + +fn dec(bsg string, csg string) string { + row := bsg.split("\n")[1..] + r2d := row[2][0] - `0` + r3d := row[3][0] - `0` + mut cay := [10]int{} + mut psg := "" + mut dre, mut bre := rune(0), rune(0) + mut inr, mut rnr := 0, 0 + for idx in 1 .. 11 { + cay[int(row[0][idx]) - int(`0`)] = idx + } + for inr < csg.len { + dre = csg[inr] - `0` + rnr = 0 + match dre { + r2d { rnr = 2 } + r3d { rnr = 3 } + else { + psg += row[1][cay[int(dre)]].ascii_str() + inr++ + continue + } + } + inr++ + bre = row[rnr][cay[int(csg[inr] - `0`)]] + if bre == `/` { + inr++ + psg += csg[inr].ascii_str() + } + else { psg += bre.str() } + inr++ + } + return psg +} diff --git a/Task/Straddling-checkerboard/VBScript/straddling-checkerboard.vb b/Task/Straddling-checkerboard/VBScript/straddling-checkerboard.vb deleted file mode 100644 index 1effe237e2..0000000000 --- a/Task/Straddling-checkerboard/VBScript/straddling-checkerboard.vb +++ /dev/null @@ -1,88 +0,0 @@ -' Straddling checkerboard - VBScript - 19/04/2019 - -Function encrypt(ByVal originalText, ByVal alphabet, blank1, blank2) - Const notEscape = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ." - Dim i, j, curChar, escChar, outText - Dim cipher 'Hash table - Set cipher = CreateObject("Scripting.Dictionary") - 'build cipher reference - alphabet = UCase(alphabet) : j = 0 - For i = 1 To 28 - curChar = Mid(alphabet, i, 1) - Select Case True - Case i>= 1 And i<= 8 - If j = blank1 Or j = blank2 Then j = j + 1 'adjust for blank - cipher.Add curChar, CStr(j) - j = j + 1 - Case i>= 9 And i<=18 - cipher.Add curChar, CStr(blank1) & CStr(i - 9) - Case i>=19 And i<=28 - cipher.Add curChar, CStr(blank2) & CStr(i - 19) - End Select 'i - If InStr(notEscape, curChar) = 0 Then - escChar = curChar - 'Wscript.Echo "escChar=" & escChar & " cipher(escChar)=" & cipher(escChar) - End If - Next 'i - For i = 0 To 9: cipher.Add CStr(i), cipher(escChar) & CStr(i): Next - 'encrypt each character - originalText = UCase(originalText) - For i = 1 To Len(originalText) - outText = outText & cipher(Mid(originalText, i, 1)) - Next - encrypt=outText -End Function 'encrypt - -Function decrypt(ByVal cipherText, ByVal alphabet, blank1, blank2) - Const notEscape = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ." - Dim i, j, curChar, escCipher, outText - Dim cipher 'Hash table - Set cipher = CreateObject("Scripting.Dictionary") - 'build decipher reference - alphabet = UCase(alphabet) : j = 0 - For i = 1 To 28 - curChar = Mid(alphabet, i, 1) - Select Case True - Case i>= 1 And i<= 8 - If j = blank1 Or j = blank2 Then j = j + 1 'adjust for blank - cipher.Add CStr(j),curChar - j = j + 1 - Case i>= 9 And i<=18 - cipher.Add CStr(blank1) & CStr(i - 9), curChar - Case i>=19 And i<=28 - cipher.Add CStr(blank2) & CStr(i - 19), curChar - End Select 'i - If InStr(notEscape, curChar) = 0 Then - 'the last element of cipher - arrayKeys=cipher.keys - escCipher = arrayKeys(cipher.count-1) - 'Wscript.Echo "escCipher=" & escCipher & " cipher(escCipher)=" & cipher(escCipher) - End If - Next 'i - For i = 0 To 9: cipher.Add escCipher & CStr(i), CStr(i): Next - 'decrypt each character - i = 1 - Do While i <= Len(cipherText) - curChar = Mid(cipherText, i, 1) - If curChar = CStr(blank1) Or curChar = CStr(blank2) Then - curChar = Mid(cipherText, i, 2) - If curChar = escCipher Then curChar = Mid(cipherText, i, 3) - End If - outText = outText & cipher(curChar) - i = i + Len(curChar) - Loop 'i - decrypt=outText -End Function 'decrypt - - message = "One night-it was on the twentieth of March, 1888-I was returning" - cipher = "HOLMESRTABCDFGIJKNPQUVWXYZ./" - '3 7 <=8 - 'HOL MES RT - 'ABCDFGIJKN - 'PQUVWXYZ./ - Buffer=Buffer & "Original: " & message & vbCrlf - encoded = encrypt(message, cipher, 3, 7) - Buffer=Buffer & "encoded: " & encoded & vbCrlf - decoded = decrypt(encoded, cipher, 3, 7) - Buffer=Buffer & "decoded: " & decoded & vbCrlf - Wscript.Echo Buffer diff --git a/Task/Straddling-checkerboard/VBScript/straddling-checkerboard.vbs b/Task/Straddling-checkerboard/VBScript/straddling-checkerboard.vbs new file mode 100644 index 0000000000..22371d5bc6 --- /dev/null +++ b/Task/Straddling-checkerboard/VBScript/straddling-checkerboard.vbs @@ -0,0 +1,88 @@ +' Straddling checkerboard - VBScript - 19/04/2019 + +Function encrypt(ByVal originalText, ByVal alphabet, blank1, blank2) + Const notEscape = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ." + Dim i, j, curChar, escChar, outText + Dim cipher 'Hash table + Set cipher = CreateObject("Scripting.Dictionary") + 'build cipher reference + alphabet = UCase(alphabet) : j = 0 + For i = 1 To 28 + curChar = Mid(alphabet, i, 1) + Select Case True + Case i>= 1 And i<= 8 + If j = blank1 Or j = blank2 Then j = j + 1 'adjust for blank + cipher.Add curChar, CStr(j) + j = j + 1 + Case i>= 9 And i<=18 + cipher.Add curChar, CStr(blank1) & CStr(i - 9) + Case i>=19 And i<=28 + cipher.Add curChar, CStr(blank2) & CStr(i - 19) + End Select 'i + If InStr(notEscape, curChar) = 0 Then + escChar = curChar + 'Wscript.Echo "escChar=" & escChar & " cipher(escChar)=" & cipher(escChar) + End If + Next 'i + For i = 0 To 9: cipher.Add CStr(i), cipher(escChar) & CStr(i): Next + 'encrypt each character + originalText = UCase(originalText) + For i = 1 To Len(originalText) + outText = outText & cipher(Mid(originalText, i, 1)) + Next + encrypt=outText +End Function 'encrypt + +Function decrypt(ByVal cipherText, ByVal alphabet, blank1, blank2) + Const notEscape = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ." + Dim i, j, curChar, escCipher, outText + Dim cipher 'Hash table + Set cipher = CreateObject("Scripting.Dictionary") + 'build decipher reference + alphabet = UCase(alphabet) : j = 0 + For i = 1 To 28 + curChar = Mid(alphabet, i, 1) + Select Case True + Case i>= 1 And i<= 8 + If j = blank1 Or j = blank2 Then j = j + 1 'adjust for blank + cipher.Add CStr(j),curChar + j = j + 1 + Case i>= 9 And i<=18 + cipher.Add CStr(blank1) & CStr(i - 9), curChar + Case i>=19 And i<=28 + cipher.Add CStr(blank2) & CStr(i - 19), curChar + End Select 'i + If InStr(notEscape, curChar) = 0 Then + 'the last element of cipher + arrayKeys=cipher.keys + escCipher = arrayKeys(cipher.count-1) + 'Wscript.Echo "escCipher=" & escCipher & " cipher(escCipher)=" & cipher(escCipher) + End If + Next 'i + For i = 0 To 9: cipher.Add escCipher & CStr(i), CStr(i): Next + 'decrypt each character + i = 1 + Do While i <= Len(cipherText) + curChar = Mid(cipherText, i, 1) + If curChar = CStr(blank1) Or curChar = CStr(blank2) Then + curChar = Mid(cipherText, i, 2) + If curChar = escCipher Then curChar = Mid(cipherText, i, 3) + End If + outText = outText & cipher(curChar) + i = i + Len(curChar) + Loop 'i + decrypt=outText +End Function 'decrypt + + message = "One night-it was on the twentieth of March, 1888-I was returning" + cipher = "HOLMESRTABCDFGIJKNPQUVWXYZ./" + '3 7 <=8 + 'HOL MES RT + 'ABCDFGIJKN + 'PQUVWXYZ./ + Buffer=Buffer & "Original: " & message & vbCrlf + encoded = encrypt(message, cipher, 3, 7) + Buffer=Buffer & "encoded: " & encoded & vbCrlf + decoded = decrypt(encoded, cipher, 3, 7) + Buffer=Buffer & "decoded: " & decoded & vbCrlf + Wscript.Echo Buffer diff --git a/Task/Strassens-algorithm/00-TASK.txt b/Task/Strassens-algorithm/00-TASK.txt index 1ebb38df9e..0f8e857752 100644 --- a/Task/Strassens-algorithm/00-TASK.txt +++ b/Task/Strassens-algorithm/00-TASK.txt @@ -12,9 +12,11 @@ While practical implementations of Strassen's algorithm usually switch to standa ;Related task :* [[Matrix multiplication]] - +:* [[Determinant and permanent]] ;See also :* [[wp:Strassen algorithm|Wikipedia article]]

    + + diff --git a/Task/Strassens-algorithm/C++/strassens-algorithm.cpp b/Task/Strassens-algorithm/C++/strassens-algorithm.cpp new file mode 100644 index 0000000000..27e94e3bb6 --- /dev/null +++ b/Task/Strassens-algorithm/C++/strassens-algorithm.cpp @@ -0,0 +1,248 @@ +#include +#include +#include +#include +#include +#include + +class Matrix { +public: + std::vector> data; + size_t rows; + size_t cols; + + Matrix(const std::vector>& data) : data(data) { + rows = data.size(); + cols = (rows > 0) ? data[0].size() : 0; + } + + size_t getRows() const { + return rows; + } + + size_t getCols() const { + return cols; + } + + void validateDimensions(const Matrix& other) const { + if (getRows() != other.getRows() || getCols() != other.getCols()) { + throw std::runtime_error("Matrices must have the same dimensions."); + } + } + + void validateMultiplication(const Matrix& other) const { + if (getCols() != other.getRows()) { + throw std::runtime_error("Cannot multiply these matrices."); + } + } + + void validateSquarePowerOfTwo() const { + if (getRows() != getCols()) { + throw std::runtime_error("Matrix must be square."); + } + if (getRows() == 0 || (getRows() & (getRows() - 1)) != 0) { + throw std::runtime_error("Size of matrix must be a power of two."); + } + } + + Matrix operator+(const Matrix& other) const { + validateDimensions(other); + + std::vector> result_data(rows, std::vector(cols)); + for (size_t i = 0; i < rows; ++i) { + for (size_t j = 0; j < cols; ++j) { + result_data[i][j] = data[i][j] + other.data[i][j]; + } + } + + return Matrix(result_data); + } + + Matrix operator-(const Matrix& other) const { + validateDimensions(other); + + std::vector> result_data(rows, std::vector(cols)); + for (size_t i = 0; i < rows; ++i) { + for (size_t j = 0; j < cols; ++j) { + result_data[i][j] = data[i][j] - other.data[i][j]; + } + } + + return Matrix(result_data); + } + + Matrix operator*(const Matrix& other) const { + validateMultiplication(other); + + std::vector> result_data(rows, std::vector(other.cols)); + for (size_t i = 0; i < rows; ++i) { + for (size_t j = 0; j < other.cols; ++j) { + double sum = 0.0; + for (size_t k = 0; k < other.rows; ++k) { + sum += data[i][k] * other.data[k][j]; + } + result_data[i][j] = sum; + } + } + + return Matrix(result_data); + } + + friend std::ostream& operator<<(std::ostream& os, const Matrix& matrix) { + for (const auto& row : matrix.data) { + os << "["; + for (size_t i = 0; i < row.size(); ++i) { + os << row[i]; + if (i < row.size() - 1) { + os << ", "; + } + } + os << "]" << std::endl; + } + return os; + } + + std::string toStringWithPrecision(size_t p) const { + std::stringstream ss; + ss << std::fixed << std::setprecision(p); + double pow = std::pow(10.0, p); + + for (const auto& row : data) { + ss << "["; + for (size_t i = 0; i < row.size(); ++i) { + double r = std::round(row[i] * pow) / pow; + std::string formatted = ss.str(); + ss.str(std::string()); + ss << r; + formatted = ss.str(); + + if (formatted == "-0") { + ss.str(std::string()); + ss << "0"; + formatted = ss.str(); + } + + ss.str(std::string()); + ss << formatted; + + if (i < row.size() - 1) { + ss << ", "; + } + } + ss << "]" << std::endl; + + } + return ss.str(); + } + + static std::array, 4> params(size_t r, size_t c) { + return { + {{{0, r, 0, c, 0, 0}}, + {{0, r, c, 2 * c, 0, c}}, + {{r, 2 * r, 0, c, r, 0}}, + {{r, 2 * r, c, 2 * c, r, c}}} + }; + } + + std::array toQuarters() const { + size_t r = getRows() / 2; + size_t c = getCols() / 2; + auto p = Matrix::params(r, c); + std::array quarters = { + Matrix(std::vector>(r, std::vector(c, 0.0))), + Matrix(std::vector>(r, std::vector(c, 0.0))), + Matrix(std::vector>(r, std::vector(c, 0.0))), + Matrix(std::vector>(r, std::vector(c, 0.0))) + }; + + for (size_t k = 0; k < 4; ++k) { + std::vector> q_data(r, std::vector(c)); + for (size_t i = p[k][0]; i < p[k][1]; ++i) { + for (size_t j = p[k][2]; j < p[k][3]; ++j) { + q_data[i - p[k][4]][j - p[k][5]] = data[i][j]; + } + } + quarters[k] = Matrix(q_data); + } + + return quarters; + } + + static Matrix fromQuarters(const std::array& q) { + size_t r = q[0].getRows(); + size_t c = q[0].getCols(); + auto p = Matrix::params(r, c); + size_t rows = r * 2; + size_t cols = c * 2; + + std::vector> m_data(rows, std::vector(cols, 0.0)); + + for (size_t k = 0; k < 4; ++k) { + for (size_t i = p[k][0]; i < p[k][1]; ++i) { + for (size_t j = p[k][2]; j < p[k][3]; ++j) { + m_data[i][j] = q[k].data[i - p[k][4]][j - p[k][5]]; + } + } + } + + return Matrix(m_data); + } + + Matrix strassen(const Matrix& other) const { + validateSquarePowerOfTwo(); + other.validateSquarePowerOfTwo(); + if (getRows() != other.getRows() || getCols() != other.getCols()) { + throw std::runtime_error("Matrices must be square and of equal size for Strassen multiplication."); + } + + if (getRows() == 1) { + return *this * other; + } + + auto qa = toQuarters(); + auto qb = other.toQuarters(); + + Matrix p1 = (qa[1] - qa[3]).strassen(qb[2] + qb[3]); + Matrix p2 = (qa[0] + qa[3]).strassen(qb[0] + qb[3]); + Matrix p3 = (qa[0] - qa[2]).strassen(qb[0] + qb[1]); + Matrix p4 = (qa[0] + qa[1]).strassen(qb[3]); + Matrix p5 = qa[0].strassen(qb[1] - qb[3]); + Matrix p6 = qa[3].strassen(qb[2] - qb[0]); + Matrix p7 = (qa[2] + qa[3]).strassen(qb[0]); + + std::array q = { + Matrix(std::vector>(qa[0].getRows(), std::vector(qa[0].getCols(), 0.0))), + Matrix(std::vector>(qa[0].getRows(), std::vector(qa[0].getCols(), 0.0))), + Matrix(std::vector>(qa[0].getRows(), std::vector(qa[0].getCols(), 0.0))), + Matrix(std::vector>(qa[0].getRows(), std::vector(qa[0].getCols(), 0.0))) + }; + + q[0] = p1 + p2 - p4 + p6; + q[1] = p4 + p5; + q[2] = p6 + p7; + q[3] = p2 - p3 + p5 - p7; + + return Matrix::fromQuarters(q); + } +}; + +int main() { + Matrix a({ {1.0, 2.0}, {3.0, 4.0} }); + Matrix b({ {5.0, 6.0}, {7.0, 8.0} }); + Matrix c({ {1.0, 1.0, 1.0, 1.0}, {2.0, 4.0, 8.0, 16.0}, {3.0, 9.0, 27.0, 81.0}, {4.0, 16.0, 64.0, 256.0} }); + Matrix d({ {4.0, -3.0, 4.0 / 3.0, -1.0 / 4.0}, {-13.0 / 3.0, 19.0 / 4.0, -7.0 / 3.0, 11.0 / 24.0}, {3.0 / 2.0, -2.0, 7.0 / 6.0, -1.0 / 4.0}, {-1.0 / 6.0, 1.0 / 4.0, -1.0 / 6.0, 1.0 / 24.0} }); + Matrix e({ {1.0, 2.0, 3.0, 4.0}, {5.0, 6.0, 7.0, 8.0}, {9.0, 10.0, 11.0, 12.0}, {13.0, 14.0, 15.0, 16.0} }); + Matrix f({ {1.0, 0.0, 0.0, 0.0}, {0.0, 1.0, 0.0, 0.0}, {0.0, 0.0, 1.0, 0.0}, {0.0, 0.0, 0.0, 1.0} }); + + std::cout << "Using 'normal' matrix multiplication:" << std::endl; + std::cout << " a * b = " << a * b << std::endl; + std::cout << " c * d = " << (c * d).toStringWithPrecision(6) << std::endl; + std::cout << " e * f = " << e * f << std::endl; + + std::cout << "\nUsing 'Strassen' matrix multiplication:" << std::endl; + std::cout << " a * b = " << a.strassen(b) << std::endl; + std::cout << " c * d = " << c.strassen(d).toStringWithPrecision(6) << std::endl; + std::cout << " e * f = " << e.strassen(f) << std::endl; + + return 0; +} diff --git a/Task/Strassens-algorithm/C-sharp/strassens-algorithm.cs b/Task/Strassens-algorithm/C-sharp/strassens-algorithm.cs new file mode 100644 index 0000000000..bc170318d1 --- /dev/null +++ b/Task/Strassens-algorithm/C-sharp/strassens-algorithm.cs @@ -0,0 +1,323 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +class Matrix +{ + public List> data; + public int rows; + public int cols; + + public Matrix(List> data) + { + this.data = data; + rows = data.Count; + cols = (rows > 0) ? data[0].Count : 0; + } + + public int GetRows() + { + return rows; + } + + public int GetCols() + { + return cols; + } + + public void ValidateDimensions(Matrix other) + { + if (GetRows() != other.GetRows() || GetCols() != other.GetCols()) + { + throw new InvalidOperationException("Matrices must have the same dimensions."); + } + } + + public void ValidateMultiplication(Matrix other) + { + if (GetCols() != other.GetRows()) + { + throw new InvalidOperationException("Cannot multiply these matrices."); + } + } + + public void ValidateSquarePowerOfTwo() + { + if (GetRows() != GetCols()) + { + throw new InvalidOperationException("Matrix must be square."); + } + if (GetRows() == 0 || (GetRows() & (GetRows() - 1)) != 0) + { + throw new InvalidOperationException("Size of matrix must be a power of two."); + } + } + + public static Matrix operator +(Matrix a, Matrix b) + { + a.ValidateDimensions(b); + + List> resultData = new List>(); + for (int i = 0; i < a.rows; ++i) + { + List row = new List(); + for (int j = 0; j < a.cols; ++j) + { + row.Add(a.data[i][j] + b.data[i][j]); + } + resultData.Add(row); + } + + return new Matrix(resultData); + } + + public static Matrix operator -(Matrix a, Matrix b) + { + a.ValidateDimensions(b); + + List> resultData = new List>(); + for (int i = 0; i < a.rows; ++i) + { + List row = new List(); + for (int j = 0; j < a.cols; ++j) + { + row.Add(a.data[i][j] - b.data[i][j]); + } + resultData.Add(row); + } + + return new Matrix(resultData); + } + + public static Matrix operator *(Matrix a, Matrix b) + { + a.ValidateMultiplication(b); + + List> resultData = new List>(); + for (int i = 0; i < a.rows; ++i) + { + List row = new List(); + for (int j = 0; j < b.cols; ++j) + { + double sum = 0.0; + for (int k = 0; k < b.rows; ++k) + { + sum += a.data[i][k] * b.data[k][j]; + } + row.Add(sum); + } + resultData.Add(row); + } + + return new Matrix(resultData); + } + + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + foreach (var row in data) + { + sb.Append("["); + for (int i = 0; i < row.Count; ++i) + { + sb.Append(row[i]); + if (i < row.Count - 1) + { + sb.Append(", "); + } + } + sb.AppendLine("]"); + } + return sb.ToString(); + } + + public string ToStringWithPrecision(int p) + { + StringBuilder sb = new StringBuilder(); + double pow = Math.Pow(10.0, p); + + foreach (var row in data) + { + sb.Append("["); + for (int i = 0; i < row.Count; ++i) + { + double r = Math.Round(row[i] * pow) / pow; + string formatted = r.ToString($"F{p}"); + + if (formatted == "-0" + (p > 0 ? "." + new string('0', p) : "")) + { + formatted = "0" + (p > 0 ? "." + new string('0', p) : ""); + } + + sb.Append(formatted); + + if (i < row.Count - 1) + { + sb.Append(", "); + } + } + sb.AppendLine("]"); + } + return sb.ToString(); + } + + private static int[,] GetParams(int r, int c) + { + return new int[,] + { + {0, r, 0, c, 0, 0}, + {0, r, c, 2 * c, 0, c}, + {r, 2 * r, 0, c, r, 0}, + {r, 2 * r, c, 2 * c, r, c} + }; + } + + public Matrix[] ToQuarters() + { + int r = GetRows() / 2; + int c = GetCols() / 2; + int[,] p = GetParams(r, c); + Matrix[] quarters = new Matrix[4]; + + for (int k = 0; k < 4; ++k) + { + List> qData = new List>(); + for (int i = 0; i < r; i++) + { + List row = new List(); + for (int j = 0; j < c; j++) + { + row.Add(0.0); + } + qData.Add(row); + } + + for (int i = p[k, 0]; i < p[k, 1]; ++i) + { + for (int j = p[k, 2]; j < p[k, 3]; ++j) + { + qData[i - p[k, 4]][j - p[k, 5]] = data[i][j]; + } + } + quarters[k] = new Matrix(qData); + } + + return quarters; + } + + public static Matrix FromQuarters(Matrix[] q) + { + int r = q[0].GetRows(); + int c = q[0].GetCols(); + int[,] p = GetParams(r, c); + int rows = r * 2; + int cols = c * 2; + + List> mData = new List>(); + for (int i = 0; i < rows; i++) + { + List row = new List(); + for (int j = 0; j < cols; j++) + { + row.Add(0.0); + } + mData.Add(row); + } + + for (int k = 0; k < 4; ++k) + { + for (int i = p[k, 0]; i < p[k, 1]; ++i) + { + for (int j = p[k, 2]; j < p[k, 3]; ++j) + { + mData[i][j] = q[k].data[i - p[k, 4]][j - p[k, 5]]; + } + } + } + + return new Matrix(mData); + } + + public Matrix Strassen(Matrix other) + { + ValidateSquarePowerOfTwo(); + other.ValidateSquarePowerOfTwo(); + if (GetRows() != other.GetRows() || GetCols() != other.GetCols()) + { + throw new InvalidOperationException("Matrices must be square and of equal size for Strassen multiplication."); + } + + if (GetRows() == 1) + { + return this * other; + } + + Matrix[] qa = ToQuarters(); + Matrix[] qb = other.ToQuarters(); + + Matrix p1 = (qa[1] - qa[3]).Strassen(qb[2] + qb[3]); + Matrix p2 = (qa[0] + qa[3]).Strassen(qb[0] + qb[3]); + Matrix p3 = (qa[0] - qa[2]).Strassen(qb[0] + qb[1]); + Matrix p4 = (qa[0] + qa[1]).Strassen(qb[3]); + Matrix p5 = qa[0].Strassen(qb[1] - qb[3]); + Matrix p6 = qa[3].Strassen(qb[2] - qb[0]); + Matrix p7 = (qa[2] + qa[3]).Strassen(qb[0]); + + Matrix[] q = new Matrix[4]; + + q[0] = p1 + p2 - p4 + p6; + q[1] = p4 + p5; + q[2] = p6 + p7; + q[3] = p2 - p3 + p5 - p7; + + return FromQuarters(q); + } +} + +class Program +{ + static void Main(string[] args) + { + Matrix a = new Matrix(new List> { new List { 1.0, 2.0 }, new List { 3.0, 4.0 } }); + Matrix b = new Matrix(new List> { new List { 5.0, 6.0 }, new List { 7.0, 8.0 } }); + Matrix c = new Matrix(new List> + { + new List { 1.0, 1.0, 1.0, 1.0 }, + new List { 2.0, 4.0, 8.0, 16.0 }, + new List { 3.0, 9.0, 27.0, 81.0 }, + new List { 4.0, 16.0, 64.0, 256.0 } + }); + Matrix d = new Matrix(new List> + { + new List { 4.0, -3.0, 4.0 / 3.0, -1.0 / 4.0 }, + new List { -13.0 / 3.0, 19.0 / 4.0, -7.0 / 3.0, 11.0 / 24.0 }, + new List { 3.0 / 2.0, -2.0, 7.0 / 6.0, -1.0 / 4.0 }, + new List { -1.0 / 6.0, 1.0 / 4.0, -1.0 / 6.0, 1.0 / 24.0 } + }); + Matrix e = new Matrix(new List> + { + new List { 1.0, 2.0, 3.0, 4.0 }, + new List { 5.0, 6.0, 7.0, 8.0 }, + new List { 9.0, 10.0, 11.0, 12.0 }, + new List { 13.0, 14.0, 15.0, 16.0 } + }); + Matrix f = new Matrix(new List> + { + new List { 1.0, 0.0, 0.0, 0.0 }, + new List { 0.0, 1.0, 0.0, 0.0 }, + new List { 0.0, 0.0, 1.0, 0.0 }, + new List { 0.0, 0.0, 0.0, 1.0 } + }); + + Console.WriteLine("Using 'normal' matrix multiplication:"); + Console.WriteLine($" a * b = {a * b}"); + Console.WriteLine($" c * d = {(c * d).ToStringWithPrecision(6)}"); + Console.WriteLine($" e * f = {e * f}"); + + Console.WriteLine("\nUsing 'Strassen' matrix multiplication:"); + Console.WriteLine($" a * b = {a.Strassen(b)}"); + Console.WriteLine($" c * d = {c.Strassen(d).ToStringWithPrecision(6)}"); + Console.WriteLine($" e * f = {e.Strassen(f)}"); + } +} diff --git a/Task/Strassens-algorithm/COBOL/strassens-algorithm.cob b/Task/Strassens-algorithm/COBOL/strassens-algorithm.cob new file mode 100644 index 0000000000..56dc949bdc --- /dev/null +++ b/Task/Strassens-algorithm/COBOL/strassens-algorithm.cob @@ -0,0 +1,367 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. StrassenAlgorithm. + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 MAT-A. 05 A-DIM PIC 9(4) COMP VALUE 2. 05 A-D OCCURS 16 USAGE COMP-2. + 01 MAT-B. 05 B-DIM PIC 9(4) COMP VALUE 2. 05 B-D OCCURS 16 USAGE COMP-2. + 01 MAT-C. 05 C-DIM PIC 9(4) COMP VALUE 4. 05 C-D OCCURS 16 USAGE COMP-2. + 01 MAT-D. 05 D-DIM PIC 9(4) COMP VALUE 4. 05 D-D OCCURS 16 USAGE COMP-2. + 01 MAT-E. 05 E-DIM PIC 9(4) COMP VALUE 4. 05 E-D OCCURS 16 USAGE COMP-2. + 01 MAT-F. 05 F-DIM PIC 9(4) COMP VALUE 4. 05 F-D OCCURS 16 USAGE COMP-2. + 01 MAT-RES. 05 R-DIM PIC 9(4) COMP. 05 R-D OCCURS 16 USAGE COMP-2. + + 01 FMT-NORMAL PIC 9 VALUE 1. + 01 FMT-PREC6 PIC 9 VALUE 6. + + PROCEDURE DIVISION. + MOVE 1.0 TO A-D(1). MOVE 2.0 TO A-D(2). + MOVE 3.0 TO A-D(3). MOVE 4.0 TO A-D(4). + + MOVE 5.0 TO B-D(1). MOVE 6.0 TO B-D(2). + MOVE 7.0 TO B-D(3). MOVE 8.0 TO B-D(4). + + MOVE 1.0 TO C-D(1). MOVE 1.0 TO C-D(2). MOVE 1.0 TO C-D(3). MOVE 1.0 TO C-D(4). + MOVE 2.0 TO C-D(5). MOVE 4.0 TO C-D(6). MOVE 8.0 TO C-D(7). MOVE 16.0 TO C-D(8). + MOVE 3.0 TO C-D(9). MOVE 9.0 TO C-D(10). MOVE 27.0 TO C-D(11). MOVE 81.0 TO C-D(12). + MOVE 4.0 TO C-D(13). MOVE 16.0 TO C-D(14). MOVE 64.0 TO C-D(15). MOVE 256.0 TO C-D(16). + + COMPUTE D-D(1) = 4.0. COMPUTE D-D(2) = -3.0. COMPUTE D-D(3) = 4.0 / 3.0. COMPUTE D-D(4) = -1.0 / 4.0. + COMPUTE D-D(5) = -13.0 / 3.0. COMPUTE D-D(6) = 19.0 / 4.0. COMPUTE D-D(7) = -7.0 / 3.0. COMPUTE D-D(8) = 11.0 / 24.0. + COMPUTE D-D(9) = 3.0 / 2.0. COMPUTE D-D(10) = -2.0. COMPUTE D-D(11) = 7.0 / 6.0. COMPUTE D-D(12) = -1.0 / 4.0. + COMPUTE D-D(13) = -1.0 / 6.0. COMPUTE D-D(14) = 1.0 / 4.0. COMPUTE D-D(15) = -1.0 / 6.0. COMPUTE D-D(16) = 1.0 / 24.0. + + MOVE 1.0 TO E-D(1). MOVE 2.0 TO E-D(2). MOVE 3.0 TO E-D(3). MOVE 4.0 TO E-D(4). + MOVE 5.0 TO E-D(5). MOVE 6.0 TO E-D(6). MOVE 7.0 TO E-D(7). MOVE 8.0 TO E-D(8). + MOVE 9.0 TO E-D(9). MOVE 10.0 TO E-D(10). MOVE 11.0 TO E-D(11). MOVE 12.0 TO E-D(12). + MOVE 13.0 TO E-D(13). MOVE 14.0 TO E-D(14). MOVE 15.0 TO E-D(15). MOVE 16.0 TO E-D(16). + + MOVE 1.0 TO F-D(1). MOVE 0.0 TO F-D(2). MOVE 0.0 TO F-D(3). MOVE 0.0 TO F-D(4). + MOVE 0.0 TO F-D(5). MOVE 1.0 TO F-D(6). MOVE 0.0 TO F-D(7). MOVE 0.0 TO F-D(8). + MOVE 0.0 TO F-D(9). MOVE 0.0 TO F-D(10). MOVE 1.0 TO F-D(11). MOVE 0.0 TO F-D(12). + MOVE 0.0 TO F-D(13). MOVE 0.0 TO F-D(14). MOVE 0.0 TO F-D(15). MOVE 1.0 TO F-D(16). + + DISPLAY "Using 'normal' matrix multiplication:". + DISPLAY " a * b = " WITH NO ADVANCING. + CALL "NORMAL-MULT" USING MAT-A, MAT-B, MAT-RES. + CALL "PRINT-MATRIX" USING MAT-RES, FMT-NORMAL. + + DISPLAY " c * d = " WITH NO ADVANCING. + CALL "NORMAL-MULT" USING MAT-C, MAT-D, MAT-RES. + CALL "PRINT-MATRIX" USING MAT-RES, FMT-PREC6. + + DISPLAY " e * f = " WITH NO ADVANCING. + CALL "NORMAL-MULT" USING MAT-E, MAT-F, MAT-RES. + CALL "PRINT-MATRIX" USING MAT-RES, FMT-NORMAL. + + DISPLAY "Using 'Strassen' matrix multiplication:". + DISPLAY " a * b = " WITH NO ADVANCING. + CALL "STRASSEN-MULT" USING MAT-A, MAT-B, MAT-RES. + CALL "PRINT-MATRIX" USING MAT-RES, FMT-NORMAL. + + DISPLAY " c * d = " WITH NO ADVANCING. + CALL "STRASSEN-MULT" USING MAT-C, MAT-D, MAT-RES. + CALL "PRINT-MATRIX" USING MAT-RES, FMT-PREC6. + + DISPLAY " e * f = " WITH NO ADVANCING. + CALL "STRASSEN-MULT" USING MAT-E, MAT-F, MAT-RES. + CALL "PRINT-MATRIX" USING MAT-RES, FMT-NORMAL. + + STOP RUN. + END PROGRAM StrassenAlgorithm. + + IDENTIFICATION DIVISION. + PROGRAM-ID. MATRIX-ADD. + DATA DIVISION. + LOCAL-STORAGE SECTION. + 01 I PIC 9(4) COMP. + 01 TOTAL-CELLS PIC 9(4) COMP. + LINKAGE SECTION. + 01 L-A. + 05 A-DIM PIC 9(4) COMP. + 05 A-DATA OCCURS 16 TIMES USAGE COMP-2. + 01 L-B. + 05 B-DIM PIC 9(4) COMP. + 05 B-DATA OCCURS 16 TIMES USAGE COMP-2. + 01 L-C. + 05 C-DIM PIC 9(4) COMP. + 05 C-DATA OCCURS 16 TIMES USAGE COMP-2. + PROCEDURE DIVISION USING L-A, L-B, L-C. + MOVE A-DIM TO C-DIM + COMPUTE TOTAL-CELLS = A-DIM * A-DIM + PERFORM VARYING I FROM 1 BY 1 UNTIL I > TOTAL-CELLS + COMPUTE C-DATA(I) = A-DATA(I) + B-DATA(I) + END-PERFORM + GOBACK. + END PROGRAM MATRIX-ADD. + + IDENTIFICATION DIVISION. + PROGRAM-ID. MATRIX-SUB. + DATA DIVISION. + LOCAL-STORAGE SECTION. + 01 I PIC 9(4) COMP. + 01 TOTAL-CELLS PIC 9(4) COMP. + LINKAGE SECTION. + 01 L-A. + 05 A-DIM PIC 9(4) COMP. + 05 A-DATA OCCURS 16 TIMES USAGE COMP-2. + 01 L-B. + 05 B-DIM PIC 9(4) COMP. + 05 B-DATA OCCURS 16 TIMES USAGE COMP-2. + 01 L-C. + 05 C-DIM PIC 9(4) COMP. + 05 C-DATA OCCURS 16 TIMES USAGE COMP-2. + PROCEDURE DIVISION USING L-A, L-B, L-C. + MOVE A-DIM TO C-DIM + COMPUTE TOTAL-CELLS = A-DIM * A-DIM + PERFORM VARYING I FROM 1 BY 1 UNTIL I > TOTAL-CELLS + COMPUTE C-DATA(I) = A-DATA(I) - B-DATA(I) + END-PERFORM + GOBACK. + END PROGRAM MATRIX-SUB. + + IDENTIFICATION DIVISION. + PROGRAM-ID. NORMAL-MULT. + DATA DIVISION. + LOCAL-STORAGE SECTION. + 01 I PIC 9(4) COMP. + 01 J PIC 9(4) COMP. + 01 K PIC 9(4) COMP. + 01 SUM-VAL USAGE COMP-2. + 01 A-IDX PIC 9(4) COMP. + 01 B-IDX PIC 9(4) COMP. + 01 C-IDX PIC 9(4) COMP. + LINKAGE SECTION. + 01 L-A. + 05 A-DIM PIC 9(4) COMP. + 05 A-DATA OCCURS 16 TIMES USAGE COMP-2. + 01 L-B. + 05 B-DIM PIC 9(4) COMP. + 05 B-DATA OCCURS 16 TIMES USAGE COMP-2. + 01 L-C. + 05 C-DIM PIC 9(4) COMP. + 05 C-DATA OCCURS 16 TIMES USAGE COMP-2. + PROCEDURE DIVISION USING L-A, L-B, L-C. + MOVE A-DIM TO C-DIM + PERFORM VARYING I FROM 1 BY 1 UNTIL I > A-DIM + PERFORM VARYING J FROM 1 BY 1 UNTIL J > A-DIM + COMPUTE C-IDX = (I - 1) * A-DIM + J + MOVE 0 TO SUM-VAL + PERFORM VARYING K FROM 1 BY 1 UNTIL K > A-DIM + COMPUTE A-IDX = (I - 1) * A-DIM + K + COMPUTE B-IDX = (K - 1) * A-DIM + J + COMPUTE SUM-VAL = SUM-VAL + + A-DATA(A-IDX) * B-DATA(B-IDX) + END-PERFORM + MOVE SUM-VAL TO C-DATA(C-IDX) + END-PERFORM + END-PERFORM + GOBACK. + END PROGRAM NORMAL-MULT. + + IDENTIFICATION DIVISION. + PROGRAM-ID. PRINT-MATRIX. + DATA DIVISION. + LOCAL-STORAGE SECTION. + 01 I PIC 9(4) COMP. + 01 J PIC 9(4) COMP. + 01 IDX PIC 9(4) COMP. + 01 FMT-VAL-1 PIC -(4)9.9. + 01 ZERO-VAL-1 PIC -(4)9.9 VALUE 0.0. + 01 FMT-VAL-6 PIC -(4)9.9(6). + 01 ZERO-VAL-6 PIC -(4)9.9(6) VALUE 0.000000. + 01 OUT-STR PIC X(80). + 01 PTR PIC 9(4) COMP. + 01 STR-VAL PIC X(20). + LINKAGE SECTION. + 01 L-M. + 05 M-DIM PIC 9(4) COMP. + 05 M-DATA OCCURS 16 USAGE COMP-2. + 01 L-FMT PIC 9. + PROCEDURE DIVISION USING L-M, L-FMT. + PERFORM VARYING I FROM 1 BY 1 UNTIL I > M-DIM + MOVE SPACES TO OUT-STR + MOVE "[" TO OUT-STR(1:1) + MOVE 2 TO PTR + + PERFORM VARYING J FROM 1 BY 1 UNTIL J > M-DIM + COMPUTE IDX = (I - 1) * M-DIM + J + IF L-FMT = 1 + IF M-DATA(IDX) > -0.05 AND M-DATA(IDX) < 0.05 + MOVE ZERO-VAL-1 TO FMT-VAL-1 + ELSE + IF M-DATA(IDX) > 0 + COMPUTE FMT-VAL-1 = M-DATA(IDX) + 0.05 + ELSE + COMPUTE FMT-VAL-1 = M-DATA(IDX) - 0.05 + END-IF + END-IF + MOVE FUNCTION TRIM(FMT-VAL-1) TO STR-VAL + ELSE + IF M-DATA(IDX) > -0.0000005 AND M-DATA(IDX) < 0.0000005 + MOVE ZERO-VAL-6 TO FMT-VAL-6 + ELSE + IF M-DATA(IDX) > 0 + COMPUTE FMT-VAL-6 = M-DATA(IDX) + 0.0000005 + ELSE + COMPUTE FMT-VAL-6 = M-DATA(IDX) - 0.0000005 + END-IF + END-IF + MOVE FUNCTION TRIM(FMT-VAL-6) TO STR-VAL + END-IF + + STRING FUNCTION TRIM(STR-VAL) DELIMITED BY SIZE + INTO OUT-STR WITH POINTER PTR + + IF J < M-DIM + STRING ", " DELIMITED BY SIZE + INTO OUT-STR WITH POINTER PTR + END-IF + END-PERFORM + + STRING "]" DELIMITED BY SIZE + INTO OUT-STR WITH POINTER PTR + DISPLAY FUNCTION TRIM(OUT-STR) + END-PERFORM + DISPLAY "". + GOBACK. + END PROGRAM PRINT-MATRIX. + + IDENTIFICATION DIVISION. + PROGRAM-ID. STRASSEN-MULT RECURSIVE. + DATA DIVISION. + LOCAL-STORAGE SECTION. + 01 HALF PIC 9(4) COMP. + 01 I PIC 9(4) COMP. + 01 J PIC 9(4) COMP. + 01 SRC-IDX PIC 9(4) COMP. + 01 DST-IDX PIC 9(4) COMP. + + 01 QA0. 05 DIM0 PIC 9(4) COMP. 05 D0 OCCURS 16 USAGE COMP-2. + 01 QA1. 05 DIM1 PIC 9(4) COMP. 05 D1 OCCURS 16 USAGE COMP-2. + 01 QA2. 05 DIM2 PIC 9(4) COMP. 05 D2 OCCURS 16 USAGE COMP-2. + 01 QA3. 05 DIM3 PIC 9(4) COMP. 05 D3 OCCURS 16 USAGE COMP-2. + + 01 QB0. 05 BDIM0 PIC 9(4) COMP. 05 BD0 OCCURS 16 USAGE COMP-2. + 01 QB1. 05 BDIM1 PIC 9(4) COMP. 05 BD1 OCCURS 16 USAGE COMP-2. + 01 QB2. 05 BDIM2 PIC 9(4) COMP. 05 BD2 OCCURS 16 USAGE COMP-2. + 01 QB3. 05 BDIM3 PIC 9(4) COMP. 05 BD3 OCCURS 16 USAGE COMP-2. + + 01 P1. 05 P1-DIM PIC 9(4) COMP. 05 P1-D OCCURS 16 USAGE COMP-2. + 01 P2. 05 P2-DIM PIC 9(4) COMP. 05 P2-D OCCURS 16 USAGE COMP-2. + 01 P3. 05 P3-DIM PIC 9(4) COMP. 05 P3-D OCCURS 16 USAGE COMP-2. + 01 P4. 05 P4-DIM PIC 9(4) COMP. 05 P4-D OCCURS 16 USAGE COMP-2. + 01 P5. 05 P5-DIM PIC 9(4) COMP. 05 P5-D OCCURS 16 USAGE COMP-2. + 01 P6. 05 P6-DIM PIC 9(4) COMP. 05 P6-D OCCURS 16 USAGE COMP-2. + 01 P7. 05 P7-DIM PIC 9(4) COMP. 05 P7-D OCCURS 16 USAGE COMP-2. + + 01 T1. 05 T1-DIM PIC 9(4) COMP. 05 T1-D OCCURS 16 USAGE COMP-2. + 01 T2. 05 T2-DIM PIC 9(4) COMP. 05 T2-D OCCURS 16 USAGE COMP-2. + + 01 Q0. 05 Q0-DIM PIC 9(4) COMP. 05 Q0-D OCCURS 16 USAGE COMP-2. + 01 Q1. 05 Q1-DIM PIC 9(4) COMP. 05 Q1-D OCCURS 16 USAGE COMP-2. + 01 Q2. 05 Q2-DIM PIC 9(4) COMP. 05 Q2-D OCCURS 16 USAGE COMP-2. + 01 Q3. 05 Q3-DIM PIC 9(4) COMP. 05 Q3-D OCCURS 16 USAGE COMP-2. + + LINKAGE SECTION. + 01 L-A. 05 L-A-DIM PIC 9(4) COMP. 05 L-A-D OCCURS 16 USAGE COMP-2. + 01 L-B. 05 L-B-DIM PIC 9(4) COMP. 05 L-B-D OCCURS 16 USAGE COMP-2. + 01 L-C. 05 L-C-DIM PIC 9(4) COMP. 05 L-C-D OCCURS 16 USAGE COMP-2. + + PROCEDURE DIVISION USING L-A, L-B, L-C. + IF L-A-DIM = 1 + MOVE 1 TO L-C-DIM + COMPUTE L-C-D(1) = L-A-D(1) * L-B-D(1) + GOBACK + END-IF. + + COMPUTE HALF = L-A-DIM / 2. + MOVE HALF TO DIM0, DIM1, DIM2, DIM3. + MOVE HALF TO BDIM0, BDIM1, BDIM2, BDIM3. + + PERFORM VARYING I FROM 1 BY 1 UNTIL I > HALF + PERFORM VARYING J FROM 1 BY 1 UNTIL J > HALF + COMPUTE DST-IDX = (I - 1) * HALF + J + + COMPUTE SRC-IDX = (I - 1) * L-A-DIM + J + MOVE L-A-D(SRC-IDX) TO D0(DST-IDX) + + COMPUTE SRC-IDX = (I - 1) * L-A-DIM + (J + HALF) + MOVE L-A-D(SRC-IDX) TO D1(DST-IDX) + + COMPUTE SRC-IDX = (I + HALF - 1) * L-A-DIM + J + MOVE L-A-D(SRC-IDX) TO D2(DST-IDX) + + COMPUTE SRC-IDX = (I + HALF - 1) * L-A-DIM + (J + HALF) + MOVE L-A-D(SRC-IDX) TO D3(DST-IDX) + + COMPUTE SRC-IDX = (I - 1) * L-B-DIM + J + MOVE L-B-D(SRC-IDX) TO BD0(DST-IDX) + + COMPUTE SRC-IDX = (I - 1) * L-B-DIM + (J + HALF) + MOVE L-B-D(SRC-IDX) TO BD1(DST-IDX) + + COMPUTE SRC-IDX = (I + HALF - 1) * L-B-DIM + J + MOVE L-B-D(SRC-IDX) TO BD2(DST-IDX) + + COMPUTE SRC-IDX = (I + HALF - 1) * L-B-DIM + (J + HALF) + MOVE L-B-D(SRC-IDX) TO BD3(DST-IDX) + END-PERFORM + END-PERFORM. + + CALL "MATRIX-SUB" USING QA1, QA3, T1 + CALL "MATRIX-ADD" USING QB2, QB3, T2 + CALL "STRASSEN-MULT" USING T1, T2, P1 + + CALL "MATRIX-ADD" USING QA0, QA3, T1 + CALL "MATRIX-ADD" USING QB0, QB3, T2 + CALL "STRASSEN-MULT" USING T1, T2, P2 + + CALL "MATRIX-SUB" USING QA0, QA2, T1 + CALL "MATRIX-ADD" USING QB0, QB1, T2 + CALL "STRASSEN-MULT" USING T1, T2, P3 + + CALL "MATRIX-ADD" USING QA0, QA1, T1 + CALL "STRASSEN-MULT" USING T1, QB3, P4 + + CALL "MATRIX-SUB" USING QB1, QB3, T2 + CALL "STRASSEN-MULT" USING QA0, T2, P5 + + CALL "MATRIX-SUB" USING QB2, QB0, T2 + CALL "STRASSEN-MULT" USING QA3, T2, P6 + + CALL "MATRIX-ADD" USING QA2, QA3, T1 + CALL "STRASSEN-MULT" USING T1, QB0, P7 + + CALL "MATRIX-ADD" USING P1, P2, T1 + CALL "MATRIX-SUB" USING T1, P4, T2 + CALL "MATRIX-ADD" USING T2, P6, Q0 + + CALL "MATRIX-ADD" USING P4, P5, Q1 + + CALL "MATRIX-ADD" USING P6, P7, Q2 + + CALL "MATRIX-SUB" USING P2, P3, T1 + CALL "MATRIX-ADD" USING T1, P5, T2 + CALL "MATRIX-SUB" USING T2, P7, Q3 + + MOVE L-A-DIM TO L-C-DIM + PERFORM VARYING I FROM 1 BY 1 UNTIL I > HALF + PERFORM VARYING J FROM 1 BY 1 UNTIL J > HALF + COMPUTE SRC-IDX = (I - 1) * HALF + J + + COMPUTE DST-IDX = (I - 1) * L-A-DIM + J + MOVE Q0-D(SRC-IDX) TO L-C-D(DST-IDX) + + COMPUTE DST-IDX = (I - 1) * L-A-DIM + (J + HALF) + MOVE Q1-D(SRC-IDX) TO L-C-D(DST-IDX) + + COMPUTE DST-IDX = (I + HALF - 1) * L-A-DIM + J + MOVE Q2-D(SRC-IDX) TO L-C-D(DST-IDX) + + COMPUTE DST-IDX = (I + HALF - 1) * L-A-DIM + (J + HALF) + MOVE Q3-D(SRC-IDX) TO L-C-D(DST-IDX) + END-PERFORM + END-PERFORM. + + GOBACK. + END PROGRAM STRASSEN-MULT. diff --git a/Task/Strassens-algorithm/Dart/strassens-algorithm.dart b/Task/Strassens-algorithm/Dart/strassens-algorithm.dart new file mode 100644 index 0000000000..853fc1e18f --- /dev/null +++ b/Task/Strassens-algorithm/Dart/strassens-algorithm.dart @@ -0,0 +1,282 @@ +// ----------------------------------------------------------------------------- +// matrix.dart +// Dart translation of the C++ Matrix/Strassen example +// ----------------------------------------------------------------------------- +import 'dart:math' as math; + +/// Simple matrix class that supports normal multiplication, Strassen +/// multiplication and pretty printing with a given precision. +class Matrix { + final List> data; + final int rows; + final int cols; + + // --------------------------------------------------------------------------- + // Construction & basic getters + // --------------------------------------------------------------------------- + Matrix(this.data) + : rows = data.length, + cols = data.isNotEmpty ? data[0].length : 0 { + // Ensure rectangular shape + for (final row in data) { + if (row.length != cols) { + throw ArgumentError('All rows must have the same number of columns.'); + } + } + } + + // --------------------------------------------------------------------------- + // Validation helpers (private) + // --------------------------------------------------------------------------- + void _validateDimensions(Matrix other) { + if (rows != other.rows || cols != other.cols) { + throw StateError('Matrices must have the same dimensions.'); + } + } + + void _validateMultiplication(Matrix other) { + if (cols != other.rows) { + throw StateError('Cannot multiply these matrices (inner dimensions differ).'); + } + } + + void _validateSquarePowerOfTwo() { + if (rows != cols) { + throw StateError('Matrix must be square.'); + } + if (rows == 0 || (rows & (rows - 1)) != 0) { + throw StateError('Size of matrix must be a power of two.'); + } + } + + // --------------------------------------------------------------------------- + // Basic arithmetic operators + // --------------------------------------------------------------------------- + Matrix operator +(Matrix other) { + _validateDimensions(other); + final result = List>.generate( + rows, + (i) => List.generate( + cols, (j) => data[i][j] + other.data[i][j], + growable: false), + growable: false); + return Matrix(result); + } + + Matrix operator -(Matrix other) { + _validateDimensions(other); + final result = List>.generate( + rows, + (i) => List.generate( + cols, (j) => data[i][j] - other.data[i][j], + growable: false), + growable: false); + return Matrix(result); + } + + Matrix operator *(Matrix other) { + _validateMultiplication(other); + final result = List>.generate( + rows, + (i) => List.filled(other.cols, 0.0, growable: false), + growable: false); + + for (var i = 0; i < rows; ++i) { + for (var j = 0; j < other.cols; ++j) { + double sum = 0.0; + for (var k = 0; k < cols; ++k) { + sum += data[i][k] * other.data[k][j]; + } + result[i][j] = sum; + } + } + return Matrix(result); + } + + // --------------------------------------------------------------------------- + // Pretty printing + // --------------------------------------------------------------------------- + @override + String toString() { + final sb = StringBuffer(); + for (final row in data) { + sb.writeln('[${row.join(', ')}]'); + } + return sb.toString(); + } + + /// Returns a string where each element is rounded to **[prec]** decimal + /// places (like the C++ `toStringWithPrecision`). The handling of “‑0” + /// → “0” mirrors the original implementation. + String toStringWithPrecision(int prec) { + final pow = math.pow(10.0, prec); + final sb = StringBuffer(); + + for (final row in data) { + sb.write('['); + for (var i = 0; i < row.length; ++i) { + // Round to the requested precision + var r = (row[i] * pow).round() / pow; + // Remove the negative zero representation + if (r == -0.0) r = 0.0; + final formatted = r.toStringAsFixed(prec); + sb.write(formatted); + if (i < row.length - 1) sb.write(', '); + } + sb.writeln(']'); + } + + return sb.toString(); + } + + // --------------------------------------------------------------------------- + // Strassen‑specific helpers (private) + // --------------------------------------------------------------------------- + /// Returns the 4‑parameter table that tells where each quarter starts + /// and how many rows/columns it occupies. + static List> _params(int r, int c) => [ + // r0, r1, c0, c1, dr, dc (dr/dc are offsets used while copying) + [0, r, 0, c, 0, 0], + [0, r, c, 2 * c, 0, c], + [r, 2 * r, 0, c, r, 0], + [r, 2 * r, c, 2 * c, r, c], + ]; + + /// Splits a square matrix (size = 2·r × 2·c) into its four quarters. + List _toQuarters() { + final r = rows ~/ 2; + final c = cols ~/ 2; + final p = _params(r, c); + final List quarters = List.filled(4, Matrix([])); + + for (var k = 0; k < 4; ++k) { + final qData = List>.generate( + r, (_) => List.filled(c, 0.0, growable: false), + growable: false); + for (var i = p[k][0]; i < p[k][1]; ++i) { + for (var j = p[k][2]; j < p[k][3]; ++j) { + qData[i - p[k][4]][j - p[k][5]] = data[i][j]; + } + } + quarters[k] = Matrix(qData); + } + return quarters; + } + + /// Reassembles a full matrix from four quarters. + static Matrix _fromQuarters(List q) { + final r = q[0].rows; + final c = q[0].cols; + final p = _params(r, c); + final rows = r * 2; + final cols = c * 2; + + final mData = List>.generate( + rows, (_) => List.filled(cols, 0.0, growable: false), + growable: false); + + for (var k = 0; k < 4; ++k) { + for (var i = p[k][0]; i < p[k][1]; ++i) { + for (var j = p[k][2]; j < p[k][3]; ++j) { + mData[i][j] = q[k].data[i - p[k][4]][j - p[k][5]]; + } + } + } + + return Matrix(mData); + } + + // --------------------------------------------------------------------------- + // Strassen multiplication (public) + // --------------------------------------------------------------------------- + Matrix strassen(Matrix other) { + _validateSquarePowerOfTwo(); + other._validateSquarePowerOfTwo(); + + if (rows != other.rows || cols != other.cols) { + throw StateError( + 'Matrices must be square and of equal size for Strassen multiplication.'); + } + + // Base case – 1×1 matrices are multiplied normally + if (rows == 1) { + return this * other; + } + + // Split both matrices into quarters + final a = _toQuarters(); + final b = other._toQuarters(); + + // Compute the seven products (recursively) + final p1 = (a[1] - a[3]).strassen(b[2] + b[3]); + final p2 = (a[0] + a[3]).strassen(b[0] + b[3]); + final p3 = (a[0] - a[2]).strassen(b[0] + b[1]); + final p4 = (a[0] + a[1]).strassen(b[3]); + final p5 = a[0].strassen(b[1] - b[3]); + final p6 = a[3].strassen(b[2] - b[0]); + final p7 = (a[2] + a[3]).strassen(b[0]); + + // Combine the products into the four result quadrants + final List q = List.filled( + 4, + Matrix( + List>.filled(0, [])), // placeholder – will be overwritten + growable: false); + + q[0] = p1 + p2 - p4 + p6; + q[1] = p4 + p5; + q[2] = p6 + p7; + q[3] = p2 - p3 + p5 - p7; + + // Re‑assemble the final matrix + return Matrix._fromQuarters(q); + } +} + +// ----------------------------------------------------------------------------- +// Demo (mirrors the original C++ main) +// ----------------------------------------------------------------------------- +void main() { + final a = Matrix([ + [1.0, 2.0], + [3.0, 4.0] + ]); + final b = Matrix([ + [5.0, 6.0], + [7.0, 8.0] + ]); + final c = Matrix([ + [1.0, 1.0, 1.0, 1.0], + [2.0, 4.0, 8.0, 16.0], + [3.0, 9.0, 27.0, 81.0], + [4.0, 16.0, 64.0, 256.0], + ]); + final d = Matrix([ + [4.0, -3.0, 4.0 / 3.0, -1.0 / 4.0], + [-13.0 / 3.0, 19.0 / 4.0, -7.0 / 3.0, 11.0 / 24.0], + [3.0 / 2.0, -2.0, 7.0 / 6.0, -1.0 / 4.0], + [-1.0 / 6.0, 1.0 / 4.0, -1.0 / 6.0, 1.0 / 24.0], + ]); + final e = Matrix([ + [1.0, 2.0, 3.0, 4.0], + [5.0, 6.0, 7.0, 8.0], + [9.0, 10.0, 11.0, 12.0], + [13.0, 14.0, 15.0, 16.0], + ]); + final f = Matrix([ + [1.0, 0.0, 0.0, 0.0], + [0.0, 1.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ]); + + print("Using 'normal' matrix multiplication:"); + print(' a * b = ${a * b}'); + print(' c * d = ${ (c * d).toStringWithPrecision(6)}'); + print(' e * f = ${e * f}'); + + print('\nUsing \'Strassen\' matrix multiplication:'); + print(' a * b = ${a.strassen(b)}'); + print(' c * d = ${c.strassen(d).toStringWithPrecision(6)}'); + print(' e * f = ${e.strassen(f)}'); +} diff --git a/Task/Strassens-algorithm/Elixir/strassens-algorithm.ex b/Task/Strassens-algorithm/Elixir/strassens-algorithm.ex new file mode 100644 index 0000000000..b40ae5c42a --- /dev/null +++ b/Task/Strassens-algorithm/Elixir/strassens-algorithm.ex @@ -0,0 +1,293 @@ +defmodule Matrix do + @moduledoc """ + A matrix implementation with basic operations and Strassen multiplication. + """ + + use Bitwise + defstruct [:data, :rows, :cols] + + @doc """ + Creates a new matrix from the given data. + """ + def new(data) do + rows = length(data) + cols = case rows do + 0 -> 0 + _ -> length(hd(data)) + end + %Matrix{data: data, rows: rows, cols: cols} + end + + @doc """ + Gets the number of rows in the matrix. + """ + def get_rows(%Matrix{rows: rows}), do: rows + + @doc """ + Gets the number of columns in the matrix. + """ + def get_cols(%Matrix{cols: cols}), do: cols + + # Validation functions + defp validate_dimensions(m1, m2) do + unless get_rows(m1) == get_rows(m2) and get_cols(m1) == get_cols(m2) do + raise ArgumentError, "Matrices must have the same dimensions." + end + end + + defp validate_multiplication(m1, m2) do + unless get_cols(m1) == get_rows(m2) do + raise ArgumentError, "Cannot multiply these matrices." + end + end + + defp validate_square_power_of_two(m) do + rows = get_rows(m) + cols = get_cols(m) + + unless rows == cols do + raise ArgumentError, "Matrix must be square." + end + + unless rows > 0 and (rows &&& (rows - 1)) == 0 do + raise ArgumentError, "Size of matrix must be a power of two." + end + end + + @doc """ + Adds two matrices element-wise. + """ + def add(m1, m2) do + validate_dimensions(m1, m2) + data1 = m1.data + data2 = m2.data + result_data = add_rows(data1, data2) + new(result_data) + end + + defp add_rows([], []), do: [] + defp add_rows([row1 | rest1], [row2 | rest2]) do + [add_elements(row1, row2) | add_rows(rest1, rest2)] + end + + defp add_elements([], []), do: [] + defp add_elements([e1 | rest1], [e2 | rest2]) do + [e1 + e2 | add_elements(rest1, rest2)] + end + + @doc """ + Subtracts the second matrix from the first element-wise. + """ + def subtract(m1, m2) do + validate_dimensions(m1, m2) + data1 = m1.data + data2 = m2.data + result_data = subtract_rows(data1, data2) + new(result_data) + end + + defp subtract_rows([], []), do: [] + defp subtract_rows([row1 | rest1], [row2 | rest2]) do + [subtract_elements(row1, row2) | subtract_rows(rest1, rest2)] + end + + defp subtract_elements([], []), do: [] + defp subtract_elements([e1 | rest1], [e2 | rest2]) do + [e1 - e2 | subtract_elements(rest1, rest2)] + end + + @doc """ + Multiplies two matrices using standard algorithm. + """ + def multiply(m1, m2) do + validate_multiplication(m1, m2) + data1 = m1.data + data2 = m2.data + cols2 = get_cols(m2) + result_data = multiply_rows(data1, data2, cols2) + new(result_data) + end + + defp multiply_rows([], _data2, _cols2), do: [] + defp multiply_rows([row | rest], data2, cols2) do + result_row = multiply_row_with_matrix(row, data2, cols2) + [result_row | multiply_rows(rest, data2, cols2)] + end + + defp multiply_row_with_matrix(row, data2, cols2) do + for j <- 1..cols2 do + dot_product(row, get_column(data2, j)) + end + end + + defp get_column(data, col_index) do + for row <- data, do: Enum.at(row, col_index - 1) + end + + defp dot_product(list1, list2) do + Enum.zip(list1, list2) + |> Enum.map(fn {e1, e2} -> e1 * e2 end) + |> Enum.sum() + end + + @doc """ + Converts matrix to string representation. + """ + def to_matrix_string(m) do + data = m.data + rows_str = for row <- data, do: format_row(row) + Enum.join(rows_str, "\n") <> "\n" + end + + defp format_row(row) do + elements = for e <- row, do: format_element(e) + "[" <> Enum.join(elements, ", ") <> "]" + end + + defp format_element(e) do + "#{e}" + end + + @doc """ + Converts matrix to string with specified precision. + """ + def to_matrix_string_with_precision(m, precision) do + data = m.data + pow = :math.pow(10.0, precision) + rows_str = for row <- data, do: format_row_with_precision(row, pow, precision) + Enum.join(rows_str, "\n") <> "\n" + end + + defp format_row_with_precision(row, pow, precision) do + elements = for e <- row, do: format_element_with_precision(e, pow, precision) + "[" <> Enum.join(elements, ", ") <> "]" + end + + defp format_element_with_precision(e, pow, precision) do + rounded = round(e * pow) / pow + formatted = :io_lib.format("~.*f", [precision, rounded]) |> List.to_string() + + # Handle negative zero + zero_check = case precision do + 0 -> "0" + _ -> "0." <> String.duplicate("0", precision) + end + + case formatted do + "-" <> rest when rest == zero_check -> zero_check + _ -> formatted + end + end + + # Strassen multiplication helper functions + defp to_quarters(m) do + rows = get_rows(m) + r = div(rows, 2) + data = m.data + + # Extract quarters directly + top_half = Enum.take(data, r) + bottom_half = Enum.drop(data, r) + + # Q0: top-left, Q1: top-right, Q2: bottom-left, Q3: bottom-right + q0_data = for row <- top_half, do: Enum.take(row, r) + q1_data = for row <- top_half, do: Enum.drop(row, r) + q2_data = for row <- bottom_half, do: Enum.take(row, r) + q3_data = for row <- bottom_half, do: Enum.drop(row, r) + + [new(q0_data), new(q1_data), new(q2_data), new(q3_data)] + end + + defp from_quarters([q0, q1, q2, q3]) do + q0_data = q0.data + q1_data = q1.data + q2_data = q2.data + q3_data = q3.data + + # Combine quarters back into full matrix + top_half = Enum.zip(q0_data, q1_data) |> Enum.map(fn {row0, row1} -> row0 ++ row1 end) + bottom_half = Enum.zip(q2_data, q3_data) |> Enum.map(fn {row2, row3} -> row2 ++ row3 end) + + new(top_half ++ bottom_half) + end + + @doc """ + Multiplies two matrices using Strassen's algorithm. + Matrices must be square and have size that is a power of two. + """ + def strassen(m1, m2) do + validate_square_power_of_two(m1) + validate_square_power_of_two(m2) + + unless get_rows(m1) == get_rows(m2) and get_cols(m1) == get_cols(m2) do + raise ArgumentError, "Matrices must be square and of equal size for Strassen multiplication." + end + + strassen_impl(m1, m2) + end + + defp strassen_impl(m1, m2) do + case get_rows(m1) do + 1 -> multiply(m1, m2) + _ -> + [a11, a12, a21, a22] = to_quarters(m1) + [b11, b12, b21, b22] = to_quarters(m2) + + # Calculate the 7 products according to Strassen's algorithm + p1 = strassen_impl(a11, subtract(b12, b22)) + p2 = strassen_impl(add(a11, a12), b22) + p3 = strassen_impl(add(a21, a22), b11) + p4 = strassen_impl(a22, subtract(b21, b11)) + p5 = strassen_impl(add(a11, a22), add(b11, b22)) + p6 = strassen_impl(subtract(a12, a22), add(b21, b22)) + p7 = strassen_impl(subtract(a11, a21), add(b11, b12)) + + # Calculate result quarters + c11 = add(subtract(add(p5, p4), p2), p6) + c12 = add(p1, p2) + c21 = add(p3, p4) + c22 = subtract(subtract(add(p5, p1), p3), p7) + + from_quarters([c11, c12, c21, c22]) + end + end + + @doc """ + Main function for testing the matrix operations. + """ + def main(_args \\ []) do + a_data = [[1.0, 2.0], [3.0, 4.0]] + a = new(a_data) + + b_data = [[5.0, 6.0], [7.0, 8.0]] + b = new(b_data) + + c_data = [[1.0, 1.0, 1.0, 1.0], [2.0, 4.0, 8.0, 16.0], [3.0, 9.0, 27.0, 81.0], [4.0, 16.0, 64.0, 256.0]] + c = new(c_data) + + d_data = [[4.0, -3.0, 4.0/3.0, -1.0/4.0], + [-13.0/3.0, 19.0/4.0, -7.0/3.0, 11.0/24.0], + [3.0/2.0, -2.0, 7.0/6.0, -1.0/4.0], + [-1.0/6.0, 1.0/4.0, -1.0/6.0, 1.0/24.0]] + d = new(d_data) + + e_data = [[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0, 12.0], [13.0, 14.0, 15.0, 16.0]] + e = new(e_data) + + f_data = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] + f = new(f_data) + + IO.puts("Using 'normal' matrix multiplication:") + IO.puts(" a * b = #{to_matrix_string(multiply(a, b))}") + IO.puts(" c * d = #{to_matrix_string_with_precision(multiply(c, d), 6)}") + IO.puts(" e * f = #{to_matrix_string(multiply(e, f))}") + + IO.puts("\nUsing 'Strassen' matrix multiplication:") + IO.puts(" a * b = #{to_matrix_string(strassen(a, b))}") + IO.puts(" c * d = #{to_matrix_string_with_precision(strassen(c, d), 6)}") + IO.puts(" e * f = #{to_matrix_string(strassen(e, f))}") + end +end + + +Matrix.main() diff --git a/Task/Strassens-algorithm/Erlang/strassens-algorithm.erl b/Task/Strassens-algorithm/Erlang/strassens-algorithm.erl new file mode 100644 index 0000000000..e2c05ae04d --- /dev/null +++ b/Task/Strassens-algorithm/Erlang/strassens-algorithm.erl @@ -0,0 +1,229 @@ +-module(matrix). +-export([new/1, get_rows/1, get_cols/1, add/2, subtract/2, multiply/2, + strassen/2, to_string/1, to_string_with_precision/2, main/1]). + +-record(matrix, {data, rows, cols}). + +% Constructor +new(Data) -> + Rows = length(Data), + Cols = case Rows of + 0 -> 0; + _ -> length(hd(Data)) + end, + #matrix{data = Data, rows = Rows, cols = Cols}. + +% Getters +get_rows(#matrix{rows = Rows}) -> Rows. +get_cols(#matrix{cols = Cols}) -> Cols. + +% Validation functions +validate_dimensions(M1, M2) -> + case get_rows(M1) =:= get_rows(M2) andalso get_cols(M1) =:= get_cols(M2) of + true -> ok; + false -> error("Matrices must have the same dimensions.") + end. + +validate_multiplication(M1, M2) -> + case get_cols(M1) =:= get_rows(M2) of + true -> ok; + false -> error("Cannot multiply these matrices.") + end. + +validate_square_power_of_two(M) -> + Rows = get_rows(M), + Cols = get_cols(M), + case Rows =:= Cols of + false -> error("Matrix must be square."); + true -> + case Rows =:= 0 orelse (Rows band (Rows - 1)) =/= 0 of + true -> error("Size of matrix must be a power of two."); + false -> ok + end + end. + +% Matrix operations +add(M1, M2) -> + validate_dimensions(M1, M2), + Data1 = M1#matrix.data, + Data2 = M2#matrix.data, + ResultData = add_rows(Data1, Data2), + new(ResultData). + +add_rows([], []) -> []; +add_rows([Row1|Rest1], [Row2|Rest2]) -> + [add_elements(Row1, Row2) | add_rows(Rest1, Rest2)]. + +add_elements([], []) -> []; +add_elements([E1|Rest1], [E2|Rest2]) -> + [E1 + E2 | add_elements(Rest1, Rest2)]. + +subtract(M1, M2) -> + validate_dimensions(M1, M2), + Data1 = M1#matrix.data, + Data2 = M2#matrix.data, + ResultData = subtract_rows(Data1, Data2), + new(ResultData). + +subtract_rows([], []) -> []; +subtract_rows([Row1|Rest1], [Row2|Rest2]) -> + [subtract_elements(Row1, Row2) | subtract_rows(Rest1, Rest2)]. + +subtract_elements([], []) -> []; +subtract_elements([E1|Rest1], [E2|Rest2]) -> + [E1 - E2 | subtract_elements(Rest1, Rest2)]. + +multiply(M1, M2) -> + validate_multiplication(M1, M2), + Data1 = M1#matrix.data, + Data2 = M2#matrix.data, + Cols2 = get_cols(M2), + ResultData = multiply_rows(Data1, Data2, Cols2), + new(ResultData). + +multiply_rows([], _Data2, _Cols2) -> []; +multiply_rows([Row|Rest], Data2, Cols2) -> + ResultRow = multiply_row_with_matrix(Row, Data2, Cols2), + [ResultRow | multiply_rows(Rest, Data2, Cols2)]. + +multiply_row_with_matrix(Row, Data2, Cols2) -> + [dot_product(Row, get_column(Data2, J)) || J <- lists:seq(1, Cols2)]. + +get_column(Data, ColIndex) -> + [lists:nth(ColIndex, Row) || Row <- Data]. + +dot_product(List1, List2) -> + lists:sum([E1 * E2 || {E1, E2} <- lists:zip(List1, List2)]). + +% String representation +to_string(M) -> + Data = M#matrix.data, + RowsStr = [format_row(Row) || Row <- Data], + string:join(RowsStr, "\n") ++ "\n". + +format_row(Row) -> + Elements = [format_element(E) || E <- Row], + "[" ++ string:join(Elements, ", ") ++ "]". + +format_element(E) -> + io_lib:format("~w", [E]). + +to_string_with_precision(M, P) -> + Data = M#matrix.data, + Pow = math:pow(10.0, P), + RowsStr = [format_row_with_precision(Row, Pow, P) || Row <- Data], + string:join(RowsStr, "\n") ++ "\n". + +format_row_with_precision(Row, Pow, P) -> + Elements = [format_element_with_precision(E, Pow, P) || E <- Row], + "[" ++ string:join(Elements, ", ") ++ "]". + +format_element_with_precision(E, Pow, P) -> + Rounded = round(E * Pow) / Pow, + Formatted = io_lib:format("~." ++ integer_to_list(P) ++ "f", [Rounded]), + FormattedStr = lists:flatten(Formatted), + % Handle negative zero + ZeroCheck = case P of + 0 -> "0"; + _ -> "0." ++ lists:duplicate(P, $0) + end, + case FormattedStr of + "-" ++ Rest when Rest =:= ZeroCheck -> ZeroCheck; + _ -> FormattedStr + end. + +% Strassen multiplication helper functions +to_quarters(M) -> + Rows = get_rows(M), + R = Rows div 2, + Data = M#matrix.data, + + % Extract quarters directly + TopHalf = lists:sublist(Data, R), + BottomHalf = lists:nthtail(R, Data), + + % Q0: top-left, Q1: top-right, Q2: bottom-left, Q3: bottom-right + Q0_Data = [lists:sublist(Row, R) || Row <- TopHalf], + Q1_Data = [lists:nthtail(R, Row) || Row <- TopHalf], + Q2_Data = [lists:sublist(Row, R) || Row <- BottomHalf], + Q3_Data = [lists:nthtail(R, Row) || Row <- BottomHalf], + + [new(Q0_Data), new(Q1_Data), new(Q2_Data), new(Q3_Data)]. + +from_quarters([Q0, Q1, Q2, Q3]) -> + Q0_Data = Q0#matrix.data, + Q1_Data = Q1#matrix.data, + Q2_Data = Q2#matrix.data, + Q3_Data = Q3#matrix.data, + + % Combine quarters back into full matrix + TopHalf = [Row0 ++ Row1 || {Row0, Row1} <- lists:zip(Q0_Data, Q1_Data)], + BottomHalf = [Row2 ++ Row3 || {Row2, Row3} <- lists:zip(Q2_Data, Q3_Data)], + + new(TopHalf ++ BottomHalf). + +strassen(M1, M2) -> + validate_square_power_of_two(M1), + validate_square_power_of_two(M2), + case get_rows(M1) =:= get_rows(M2) andalso get_cols(M1) =:= get_cols(M2) of + false -> error("Matrices must be square and of equal size for Strassen multiplication."); + true -> strassen_impl(M1, M2) + end. + +strassen_impl(M1, M2) -> + case get_rows(M1) of + 1 -> multiply(M1, M2); + _ -> + [A11, A12, A21, A22] = to_quarters(M1), + [B11, B12, B21, B22] = to_quarters(M2), + + % Calculate the 7 products according to Strassen's algorithm + P1 = strassen_impl(A11, subtract(B12, B22)), + P2 = strassen_impl(add(A11, A12), B22), + P3 = strassen_impl(add(A21, A22), B11), + P4 = strassen_impl(A22, subtract(B21, B11)), + P5 = strassen_impl(add(A11, A22), add(B11, B22)), + P6 = strassen_impl(subtract(A12, A22), add(B21, B22)), + P7 = strassen_impl(subtract(A11, A21), add(B11, B12)), + + % Calculate result quarters + C11 = add(subtract(add(P5, P4), P2), P6), + C12 = add(P1, P2), + C21 = add(P3, P4), + C22 = subtract(subtract(add(P5, P1), P3), P7), + + from_quarters([C11, C12, C21, C22]) + end. + +% Main function for testing +main(_) -> + AData = [[1.0, 2.0], [3.0, 4.0]], + A = new(AData), + + BData = [[5.0, 6.0], [7.0, 8.0]], + B = new(BData), + + CData = [[1.0, 1.0, 1.0, 1.0], [2.0, 4.0, 8.0, 16.0], [3.0, 9.0, 27.0, 81.0], [4.0, 16.0, 64.0, 256.0]], + C = new(CData), + + DData = [[4.0, -3.0, 4.0/3.0, -1.0/4.0], + [-13.0/3.0, 19.0/4.0, -7.0/3.0, 11.0/24.0], + [3.0/2.0, -2.0, 7.0/6.0, -1.0/4.0], + [-1.0/6.0, 1.0/4.0, -1.0/6.0, 1.0/24.0]], + D = new(DData), + + EData = [[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0, 12.0], [13.0, 14.0, 15.0, 16.0]], + E = new(EData), + + FData = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]], + F = new(FData), + + io:format("Using 'normal' matrix multiplication:~n"), + io:format(" a * b = ~s~n", [to_string(multiply(A, B))]), + io:format(" c * d = ~s~n", [to_string_with_precision(multiply(C, D), 6)]), + io:format(" e * f = ~s~n", [to_string(multiply(E, F))]), + + io:format("~nUsing 'Strassen' matrix multiplication:~n"), + io:format(" a * b = ~s~n", [to_string(strassen(A, B))]), + io:format(" c * d = ~s~n", [to_string_with_precision(strassen(C, D), 6)]), + io:format(" e * f = ~s~n", [to_string(strassen(E, F))]). diff --git a/Task/Strassens-algorithm/Fortran/strassens-algorithm.f b/Task/Strassens-algorithm/Fortran/strassens-algorithm.f new file mode 100644 index 0000000000..fa0a1b78b3 --- /dev/null +++ b/Task/Strassens-algorithm/Fortran/strassens-algorithm.f @@ -0,0 +1,350 @@ +module matrix_operations + use, intrinsic :: iso_fortran_env, only: real64, int64 + implicit none + + type :: Matrix + real(real64), allocatable :: data(:, :) + integer :: rows = 0 + integer :: cols = 0 + contains + procedure :: getRows + procedure :: getCols + procedure :: validateDimensions + procedure :: validateMultiplication + procedure :: validateSquarePowerOfTwo + procedure :: add_matrices + procedure :: subtract_matrices + procedure :: multiply_matrices + procedure :: strassen + procedure :: toQuarters + procedure :: toStringWithPrecision + generic :: operator(+) => add_matrices + generic :: operator(-) => subtract_matrices + generic :: operator(*) => multiply_matrices + end type Matrix + + interface Matrix + procedure :: create_matrix + end interface Matrix + + type :: MatrixArray4 + type(Matrix) :: matrices(4) + end type MatrixArray4 + +contains + + function create_matrix(input_data) result(mat) + real(real64), intent(in) :: input_data(:, :) + type(Matrix) :: mat + + mat%rows = size(input_data, 1) + mat%cols = size(input_data, 2) + allocate(mat%data(mat%rows, mat%cols)) + mat%data = input_data + end function create_matrix + + function getRows(this) result(rows) + class(Matrix), intent(in) :: this + integer :: rows + rows = this%rows + end function getRows + + function getCols(this) result(cols) + class(Matrix), intent(in) :: this + integer :: cols + cols = this%cols + end function getCols + + subroutine validateDimensions(this, other) + class(Matrix), intent(in) :: this, other + if (this%getRows() /= other%getRows() .or. this%getCols() /= other%getCols()) then + error stop "Matrices must have the same dimensions." + end if + end subroutine validateDimensions + + subroutine validateMultiplication(this, other) + class(Matrix), intent(in) :: this, other + if (this%getCols() /= other%getRows()) then + error stop "Cannot multiply these matrices." + end if + end subroutine validateMultiplication + + subroutine validateSquarePowerOfTwo(this) + class(Matrix), intent(in) :: this + integer :: n + + if (this%getRows() /= this%getCols()) then + error stop "Matrix must be square." + end if + + n = this%getRows() + if (n == 0 .or. iand(n, n-1) /= 0) then + error stop "Size of matrix must be a power of two." + end if + end subroutine validateSquarePowerOfTwo + + function add_matrices(this, other) result(result_mat) + class(Matrix), intent(in) :: this, other + type(Matrix) :: result_mat + integer :: i, j + + call this%validateDimensions(other) + + result_mat%rows = this%rows + result_mat%cols = this%cols + allocate(result_mat%data(result_mat%rows, result_mat%cols)) + + do j = 1, result_mat%cols + do i = 1, result_mat%rows + result_mat%data(i, j) = this%data(i, j) + other%data(i, j) + end do + end do + end function add_matrices + + function subtract_matrices(this, other) result(result_mat) + class(Matrix), intent(in) :: this, other + type(Matrix) :: result_mat + integer :: i, j + + call this%validateDimensions(other) + + result_mat%rows = this%rows + result_mat%cols = this%cols + allocate(result_mat%data(result_mat%rows, result_mat%cols)) + + do j = 1, result_mat%cols + do i = 1, result_mat%rows + result_mat%data(i, j) = this%data(i, j) - other%data(i, j) + end do + end do + end function subtract_matrices + + function multiply_matrices(this, other) result(result_mat) + class(Matrix), intent(in) :: this, other + type(Matrix) :: result_mat + integer :: i, j, k + real(real64) :: sum_val + + call this%validateMultiplication(other) + + result_mat%rows = this%rows + result_mat%cols = other%cols + allocate(result_mat%data(result_mat%rows, result_mat%cols)) + + do i = 1, result_mat%rows + do j = 1, result_mat%cols + sum_val = 0.0_real64 + do k = 1, this%cols + sum_val = sum_val + this%data(i, k) * other%data(k, j) + end do + result_mat%data(i, j) = sum_val + end do + end do + end function multiply_matrices + + function params(r, c) result(p) + integer, intent(in) :: r, c + integer :: p(4, 6) + + p(1, :) = [1, r, 1, c, 1, 1] + p(2, :) = [1, r, c+1, 2*c, 1, c+1] + p(3, :) = [r+1, 2*r, 1, c, r+1, 1] + p(4, :) = [r+1, 2*r, c+1, 2*c, r+1, c+1] + end function params + + function toQuarters(this) result(quarters) + class(Matrix), intent(in) :: this + type(MatrixArray4) :: quarters + integer :: r, c, k, i, j + integer :: p(4, 6) + real(real64), allocatable :: q_data(:, :) + + r = this%getRows() / 2 + c = this%getCols() / 2 + p = params(r, c) + + do k = 1, 4 + allocate(q_data(r, c)) + do j = p(k, 3), p(k, 4) + do i = p(k, 1), p(k, 2) + q_data(i - p(k, 5) + 1, j - p(k, 6) + 1) = this%data(i, j) + end do + end do + quarters%matrices(k) = Matrix(q_data) + deallocate(q_data) + end do + end function toQuarters + + function fromQuarters(q) result(mat) + type(MatrixArray4), intent(in) :: q + type(Matrix) :: mat + integer :: r, c, k, i, j + integer :: p(4, 6) + real(real64), allocatable :: m_data(:, :) + + r = q%matrices(1)%getRows() + c = q%matrices(1)%getCols() + p = params(r, c) + + allocate(m_data(2*r, 2*c)) + m_data = 0.0_real64 + + do k = 1, 4 + do j = p(k, 3), p(k, 4) + do i = p(k, 1), p(k, 2) + m_data(i, j) = q%matrices(k)%data(i - p(k, 5) + 1, j - p(k, 6) + 1) + end do + end do + end do + + mat = Matrix(m_data) + deallocate(m_data) + end function fromQuarters + + function strassen(this, other) result(result_mat) + class(Matrix), intent(in) :: this, other + type(Matrix) :: result_mat + type(MatrixArray4) :: qa, qb, q + type(Matrix) :: p1, p2, p3, p4, p5, p6, p7 + integer :: r, i + + call this%validateSquarePowerOfTwo() + call other%validateSquarePowerOfTwo() + + if (this%getRows() /= other%getRows() .or. this%getCols() /= other%getCols()) then + error stop "Matrices must be square and of equal size for Strassen multiplication." + end if + + if (this%getRows() == 1) then + result_mat = this * other + return + end if + + qa = this%toQuarters() + qb = other%toQuarters() + + p1 = (qa%matrices(2) - qa%matrices(4)) * (qb%matrices(3) + qb%matrices(4)) + p2 = (qa%matrices(1) + qa%matrices(4)) * (qb%matrices(1) + qb%matrices(4)) + p3 = (qa%matrices(1) - qa%matrices(3)) * (qb%matrices(1) + qb%matrices(2)) + p4 = (qa%matrices(1) + qa%matrices(2)) * qb%matrices(4) + p5 = qa%matrices(1) * (qb%matrices(2) - qb%matrices(4)) + p6 = qa%matrices(4) * (qb%matrices(3) - qb%matrices(1)) + p7 = (qa%matrices(3) + qa%matrices(4)) * qb%matrices(1) + + q%matrices(1) = p1 + p2 - p4 + p6 + q%matrices(2) = p4 + p5 + q%matrices(3) = p6 + p7 + q%matrices(4) = p2 - p3 + p5 - p7 + + result_mat = fromQuarters(q) + end function strassen + + function toStringWithPrecision(this, p) result(str) + class(Matrix), intent(in) :: this + integer, intent(in) :: p + character(:), allocatable :: str + character(100) :: buffer + integer :: i, j + real(real64) :: rounded_val + + str = '' + do i = 1, this%rows + str = str // '[' + do j = 1, this%cols + write(buffer, '(F0.' // trim(adjustl(int2str(p))) // ')') this%data(i, j) + str = str // trim(adjustl(buffer)) + if (j < this%cols) then + str = str // ', ' + end if + end do + str = str // ']' // new_line('a') + end do + end function toStringWithPrecision + + function int2str(i) result(str) + integer, intent(in) :: i + character(20) :: str + write(str, *) i + str = adjustl(str) + end function int2str + +end module matrix_operations + +program main + use matrix_operations + implicit none + + type(Matrix) :: a, b, c, d, e, f, result + + ! Initialize matrices (Fortran is column-major, so we need to transpose) + a = Matrix(reshape([1.0_real64, 2.0_real64, 3.0_real64, 4.0_real64], [2, 2])) + b = Matrix(reshape([5.0_real64, 6.0_real64, 7.0_real64, 8.0_real64], [2, 2])) + c = Matrix(reshape([1.0_real64, 1.0_real64, 1.0_real64, 1.0_real64, & + 1.0_real64, 4.0_real64, 9.0_real64, 16.0_real64, & + 1.0_real64, 8.0_real64, 27.0_real64, 64.0_real64, & + 1.0_real64, 16.0_real64, 81.0_real64, 256.0_real64], [4, 4])) + d = Matrix(reshape([4.0_real64, -3.0_real64, 4.0_real64/3.0_real64, -1.0_real64/4.0_real64, & + -13.0_real64/3.0_real64, 19.0_real64/4.0_real64, -7.0_real64/3.0_real64, 11.0_real64/24.0_real64, & + 3.0_real64/2.0_real64, -2.0_real64, 7.0_real64/6.0_real64, -1.0_real64/4.0_real64, & + -1.0_real64/6.0_real64, 1.0_real64/4.0_real64, -1.0_real64/6.0_real64, 1.0_real64/24.0_real64], [4, 4])) + e = Matrix(reshape([1.0_real64, 2.0_real64, 3.0_real64, 4.0_real64, & + 5.0_real64, 6.0_real64, 7.0_real64, 8.0_real64, & + 9.0_real64, 10.0_real64, 11.0_real64, 12.0_real64, & + 13.0_real64, 14.0_real64, 15.0_real64, 16.0_real64], [4, 4])) + f = Matrix(reshape([1.0_real64, 0.0_real64, 0.0_real64, 0.0_real64, & + 0.0_real64, 1.0_real64, 0.0_real64, 0.0_real64, & + 0.0_real64, 0.0_real64, 1.0_real64, 0.0_real64, & + 0.0_real64, 0.0_real64, 0.0_real64, 1.0_real64], [4, 4])) + + print *, "Using 'normal' matrix multiplication:" + + result = a * b + print *, " a * b = " + call print_matrix(result) + print * + + result = c * d + print *, " c * d = " + print *, trim(result%toStringWithPrecision(6)) + print * + + result = e * f + print *, " e * f = " + call print_matrix(result) + print * + + print *, "Using 'Strassen' matrix multiplication:" + + result = a%strassen(b) + print *, " a * b = " + call print_matrix(result) + print * + + result = c%strassen(d) + print *, " c * d = " + print *, trim(result%toStringWithPrecision(6)) + print * + + result = e%strassen(f) + print *, " e * f = " + call print_matrix(result) + +contains + + subroutine print_matrix(mat) + type(Matrix), intent(in) :: mat + integer :: i, j + + do i = 1, mat%rows + write(*, '(A)', advance='no') '[' + do j = 1, mat%cols + write(*, '(G0.6)', advance='no') mat%data(i, j) + if (j < mat%cols) then + write(*, '(A)', advance='no') ', ' + end if + end do + write(*, '(A)') ']' + end do + end subroutine print_matrix + +end program main diff --git a/Task/Strassens-algorithm/FreeBASIC/strassens-algorithm.basic b/Task/Strassens-algorithm/FreeBASIC/strassens-algorithm.basic new file mode 100644 index 0000000000..10b184daf8 --- /dev/null +++ b/Task/Strassens-algorithm/FreeBASIC/strassens-algorithm.basic @@ -0,0 +1,204 @@ +Type Matrix + As Integer rows + As Integer cols + As Double dato(Any) +End Type + +Function makeMatrix(rows As Integer, cols As Integer) As Matrix + Dim As Matrix m + m.rows = rows + m.cols = cols + Redim m.dato(rows * cols - 1) + Return m +End Function + +Function matrixAdd(m1 As Matrix, m2 As Matrix) As Matrix + If m1.rows <> m2.rows Or m1.cols <> m2.cols Then + Print "Matrices must have the same dimensions." + End + End If + + Dim As Matrix result = makeMatrix(m1.rows, m1.cols) + For i As Integer = 0 To m1.rows * m1.cols - 1 + result.dato(i) = m1.dato(i) + m2.dato(i) + Next + Return result +End Function + +Function matrixSub(m1 As Matrix, m2 As Matrix) As Matrix + If m1.rows <> m2.rows Or m1.cols <> m2.cols Then + Print "Matrices must have the same dimensions." + End + End If + + Dim As Matrix result = makeMatrix(m1.rows, m1.cols) + For i As Integer = 0 To m1.rows * m1.cols - 1 + result.dato(i) = m1.dato(i) - m2.dato(i) + Next + Return result +End Function + +Function matrixMul(m1 As Matrix, m2 As Matrix) As Matrix + If m1.cols <> m2.rows Then + Print "Cannot multiply these matrices." + End + End If + + Dim As Integer i, j, k + Dim As Matrix result = makeMatrix(m1.rows, m2.cols) + For i = 0 To m1.rows - 1 + For j = 0 To m2.cols - 1 + Dim As Double sum = 0 + For k = 0 To m1.cols - 1 + sum += m1.dato(i * m1.cols + k) * m2.dato(k * m2.cols + j) + Next + result.dato(i * result.cols + j) = sum + Next + Next + Return result +End Function + +Sub printMatrix(m As Matrix, precision As Integer = 6) + Dim As Integer i, j + Print "[["; + For i = 0 To m.rows - 1 + If i > 0 Then Print " ["; + For j = 0 To m.cols - 1 + Dim As Double valor = m.dato(i * m.cols + j) + valor = Int(valor * (10 ^ precision) + 0.5) / (10 ^ precision) + If Abs(valor) < 1e-10 Then valor = 0 + Print Using "&"; valor; + If j < m.cols - 1 Then Print " "; + Next + If i < m.rows - 1 Then Print "]"; + Next + Print "]]" +End Sub + +Function getQuarter(m As Matrix, quarter As Integer) As Matrix + Dim As Integer i, j + Dim As Integer halfRows, halfCols + halfRows = m.rows \ 2 + halfCols = m.cols \ 2 + Dim As Matrix result = makeMatrix(halfRows, halfCols) + + Dim As Integer rowOffset, colOffset + rowOffset = (quarter \ 2) * halfRows + colOffset = (quarter Mod 2) * halfCols + + For i = 0 To halfRows - 1 + For j = 0 To halfCols - 1 + result.dato(i * halfCols + j) = m.dato((i + rowOffset) * m.cols + j + colOffset) + Next + Next + Return result +End Function + +Function combineQuarters(q1 As Matrix, q2 As Matrix, q3 As Matrix, q4 As Matrix) As Matrix + Dim As Integer i, j, n + n = q1.rows + Dim As Matrix result = makeMatrix(n * 2, n * 2) + + For i = 0 To n - 1 + For j = 0 To n - 1 + result.dato(i * result.cols + j) = q1.dato(i * n + j) + result.dato(i * result.cols + j + n) = q2.dato(i * n + j) + result.dato((i + n) * result.cols + j) = q3.dato(i * n + j) + result.dato((i + n) * result.cols + j + n) = q4.dato(i * n + j) + Next + Next + Return result +End Function + +Function strassen(a As Matrix, b As Matrix) As Matrix + If a.rows <> a.cols Or b.rows <> b.cols Or a.rows <> b.rows Then + Print "Matrices must be square and of equal size." + End + End If + + If a.rows = 1 Then Return matrixMul(a, b) + + Dim As Matrix a11 = getQuarter(a, 0) + Dim As Matrix a12 = getQuarter(a, 1) + Dim As Matrix a21 = getQuarter(a, 2) + Dim As Matrix a22 = getQuarter(a, 3) + Dim As Matrix b11 = getQuarter(b, 0) + Dim As Matrix b12 = getQuarter(b, 1) + Dim As Matrix b21 = getQuarter(b, 2) + Dim As Matrix b22 = getQuarter(b, 3) + + Dim As Matrix p1 = strassen(matrixSub(a12, a22), matrixAdd(b21, b22)) + Dim As Matrix p2 = strassen(matrixAdd(a11, a22), matrixAdd(b11, b22)) + Dim As Matrix p3 = strassen(matrixSub(a11, a21), matrixAdd(b11, b12)) + Dim As Matrix p4 = strassen(matrixAdd(a11, a12), b22) + Dim As Matrix p5 = strassen(a11, matrixSub(b12, b22)) + Dim As Matrix p6 = strassen(a22, matrixSub(b21, b11)) + Dim As Matrix p7 = strassen(matrixAdd(a21, a22), b11) + + Dim As Matrix c11 = matrixAdd(matrixSub(matrixAdd(p1, p2), p4), p6) + Dim As Matrix c12 = matrixAdd(p4, p5) + Dim As Matrix c21 = matrixAdd(p6, p7) + Dim As Matrix c22 = matrixSub(matrixAdd(matrixSub(p2, p3), p5), p7) + + Return combineQuarters(c11, c12, c21, c22) +End Function + +Sub main() + ' Matrix A (2x2) + Dim As Matrix a = makeMatrix(2, 2) + a.dato(0) = 1: a.dato(1) = 2 + a.dato(2) = 3: a.dato(3) = 4 + + ' Matrix B (2x2) + Dim As Matrix b = makeMatrix(2, 2) + b.dato(0) = 5: b.dato(1) = 6 + b.dato(2) = 7: b.dato(3) = 8 + + ' Matrix C (4x4) + Dim As Matrix c = makeMatrix(4, 4) + c.dato(0) = 1: c.dato(1) = 1: c.dato(2) = 1: c.dato(3) = 1 + c.dato(4) = 2: c.dato(5) = 4: c.dato(6) = 8: c.dato(7) = 16 + c.dato(8) = 3: c.dato(9) = 9: c.dato(10) = 27: c.dato(11) = 81 + c.dato(12) = 4: c.dato(13) = 16: c.dato(14) = 64: c.dato(15) = 256 + + ' Matrix D (4x4) + Dim As Matrix d = makeMatrix(4, 4) + d.dato(0) = 4: d.dato(1) = -3: d.dato(2) = 4/3: d.dato(3) = -1/4 + d.dato(4) = -13/3: d.dato(5) = 19/4: d.dato(6) = -7/3: d.dato(7) = 11/24 + d.dato(8) = 3/2: d.dato(9) = -2: d.dato(10) = 7/6: d.dato(11) = -1/4 + d.dato(12) = -1/6: d.dato(13) = 1/4: d.dato(14) = -1/6: d.dato(15) = 1/24 + + ' Matrix E (4x4) + Dim As Matrix e = makeMatrix(4, 4) + e.dato(0) = 1: e.dato(1) = 2: e.dato(2) = 3: e.dato(3) = 4 + e.dato(4) = 5: e.dato(5) = 6: e.dato(6) = 7: e.dato(7) = 8 + e.dato(8) = 9: e.dato(9) = 10: e.dato(10) = 11: e.dato(11) = 12 + e.dato(12) = 13: e.dato(13) = 14: e.dato(14) = 15: e.dato(15) = 16 + + ' Matrix F (Identity 4x4) + Dim As Matrix f = makeMatrix(4, 4) + f.dato(0) = 1: f.dato(1) = 0: f.dato(2) = 0: f.dato(3) = 0 + f.dato(4) = 0: f.dato(5) = 1: f.dato(6) = 0: f.dato(7) = 0 + f.dato(8) = 0: f.dato(9) = 0: f.dato(10) = 1: f.dato(11) = 0 + f.dato(12) = 0: f.dato(13) = 0: f.dato(14) = 0: f.dato(15) = 1 + + Print "Using 'normal' matrix multiplication:" + Print " a * b = "; + printMatrix(matrixMul(a, b)) + Print " c * d = "; + printMatrix(matrixMul(c, d), 6) + Print " e * f = "; + printMatrix(matrixMul(e, f)) + + Print !"\nUsing 'Strassen' matrix multiplication:" + Print " a * b = "; + printMatrix(strassen(a, b)) + Print " c * d = "; + printMatrix(strassen(c, d), 6) + Print " e * f = "; + printMatrix(strassen(e, f)) +End Sub + +main() + +Sleep diff --git a/Task/Strassens-algorithm/Haskell/strassens-algorithm.hs b/Task/Strassens-algorithm/Haskell/strassens-algorithm.hs new file mode 100644 index 0000000000..7b72d56045 --- /dev/null +++ b/Task/Strassens-algorithm/Haskell/strassens-algorithm.hs @@ -0,0 +1,210 @@ +module Main where + +import Data.List (intercalate, transpose) +import Text.Printf (printf, PrintfArg) + +-- Matrix data type +data Matrix a = Matrix { matrixData :: [[a]] + , rows :: Int + , cols :: Int + } deriving (Eq) + +-- Constructor +new :: [[a]] -> Matrix a +new [] = Matrix [] 0 0 +new dat = Matrix dat (length dat) (length $ head dat) + +-- Getters +getRows :: Matrix a -> Int +getRows = rows + +getCols :: Matrix a -> Int +getCols = cols + +-- Validation functions +validateDimensions :: Matrix a -> Matrix a -> Either String () +validateDimensions m1 m2 + | getRows m1 == getRows m2 && getCols m1 == getCols m2 = Right () + | otherwise = Left "Matrices must have the same dimensions." + +validateMultiplication :: Matrix a -> Matrix a -> Either String () +validateMultiplication m1 m2 + | getCols m1 == getRows m2 = Right () + | otherwise = Left "Cannot multiply these matrices." + +validateSquarePowerOfTwo :: Matrix a -> Either String () +validateSquarePowerOfTwo m + | r /= c = Left "Matrix must be square." + | r == 0 || not (isPowerOfTwo r) = Left "Size of matrix must be a power of two." + | otherwise = Right () + where + r = getRows m + c = getCols m + isPowerOfTwo n = n > 0 && n == 2^(floor (logBase 2 (fromIntegral n))) + +-- Matrix operations +matrixAdd :: Num a => Matrix a -> Matrix a -> Either String (Matrix a) +matrixAdd m1 m2 = do + validateDimensions m1 m2 + let result = zipWith (zipWith (+)) (matrixData m1) (matrixData m2) + return $ new result + +matrixSubtract :: Num a => Matrix a -> Matrix a -> Either String (Matrix a) +matrixSubtract m1 m2 = do + validateDimensions m1 m2 + let result = zipWith (zipWith (-)) (matrixData m1) (matrixData m2) + return $ new result + +matrixMultiply :: Num a => Matrix a -> Matrix a -> Either String (Matrix a) +matrixMultiply m1 m2 = do + validateMultiplication m1 m2 + let data1 = matrixData m1 + data2 = matrixData m2 + cols2 = transpose data2 + result = [[sum $ zipWith (*) row col | col <- cols2] | row <- data1] + return $ new result + +-- String representation +matrixToString :: Show a => Matrix a -> String +matrixToString m = unlines $ map formatRow (matrixData m) + where + formatRow row = "[" ++ intercalate ", " (map show row) ++ "]" + +matrixToStringWithPrecision :: (RealFloat a, PrintfArg a) => Matrix a -> Int -> String +matrixToStringWithPrecision m p = unlines $ map (formatRowWithPrecision p) (matrixData m) + where + formatRowWithPrecision precision row = + "[" ++ intercalate ", " (map (formatElementWithPrecision precision) row) ++ "]" + + formatElementWithPrecision precision e = + let pow = 10.0 ^ precision + rounded = fromIntegral (round (e * pow)) / pow + formatted = printf ("%." ++ show precision ++ "f") rounded + zeroCheck = if precision == 0 then "0" else "0." ++ replicate precision '0' + in if formatted == ("-" ++ zeroCheck) then zeroCheck else formatted + +-- Strassen multiplication helper functions +toQuarters :: Matrix a -> [Matrix a] +toQuarters m = [new q0Data, new q1Data, new q2Data, new q3Data] + where + r = getRows m `div` 2 + dat = matrixData m + (topHalf, bottomHalf) = splitAt r dat + + q0Data = map (take r) topHalf + q1Data = map (drop r) topHalf + q2Data = map (take r) bottomHalf + q3Data = map (drop r) bottomHalf + +fromQuarters :: [Matrix a] -> Matrix a +fromQuarters [q0, q1, q2, q3] = new (topHalf ++ bottomHalf) + where + q0Data = matrixData q0 + q1Data = matrixData q1 + q2Data = matrixData q2 + q3Data = matrixData q3 + + topHalf = zipWith (++) q0Data q1Data + bottomHalf = zipWith (++) q2Data q3Data +fromQuarters _ = error "fromQuarters expects exactly 4 matrices" + +-- Safe matrix operations for Strassen (using Either for error handling) +safeAdd :: Num a => Matrix a -> Matrix a -> Matrix a +safeAdd m1 m2 = case matrixAdd m1 m2 of + Right result -> result + Left err -> error err + +safeSubtract :: Num a => Matrix a -> Matrix a -> Matrix a +safeSubtract m1 m2 = case matrixSubtract m1 m2 of + Right result -> result + Left err -> error err + +safeMultiply :: Num a => Matrix a -> Matrix a -> Matrix a +safeMultiply m1 m2 = case matrixMultiply m1 m2 of + Right result -> result + Left err -> error err + +-- Strassen multiplication +strassen :: Num a => Matrix a -> Matrix a -> Either String (Matrix a) +strassen m1 m2 = do + validateSquarePowerOfTwo m1 + validateSquarePowerOfTwo m2 + if getRows m1 /= getRows m2 || getCols m1 /= getCols m2 + then Left "Matrices must be square and of equal size for Strassen multiplication." + else Right $ strassenImpl m1 m2 + +strassenImpl :: Num a => Matrix a -> Matrix a -> Matrix a +strassenImpl m1 m2 + | getRows m1 == 1 = safeMultiply m1 m2 + | otherwise = fromQuarters [c11, c12, c21, c22] + where + [a11, a12, a21, a22] = toQuarters m1 + [b11, b12, b21, b22] = toQuarters m2 + + -- Calculate the 7 products according to Strassen's algorithm + p1 = strassenImpl a11 (safeSubtract b12 b22) + p2 = strassenImpl (safeAdd a11 a12) b22 + p3 = strassenImpl (safeAdd a21 a22) b11 + p4 = strassenImpl a22 (safeSubtract b21 b11) + p5 = strassenImpl (safeAdd a11 a22) (safeAdd b11 b22) + p6 = strassenImpl (safeSubtract a12 a22) (safeAdd b21 b22) + p7 = strassenImpl (safeSubtract a11 a21) (safeAdd b11 b12) + + -- Calculate result quarters + c11 = safeAdd (safeSubtract (safeAdd p5 p4) p2) p6 + c12 = safeAdd p1 p2 + c21 = safeAdd p3 p4 + c22 = safeSubtract (safeSubtract (safeAdd p5 p1) p3) p7 + +-- Main function for testing +main :: IO () +main = do + let aData = [[1.0, 2.0], [3.0, 4.0]] :: [[Double]] + a = new aData + + bData = [[5.0, 6.0], [7.0, 8.0]] :: [[Double]] + b = new bData + + cData = [[1.0, 1.0, 1.0, 1.0], [2.0, 4.0, 8.0, 16.0], + [3.0, 9.0, 27.0, 81.0], [4.0, 16.0, 64.0, 256.0]] :: [[Double]] + c = new cData + + dData = [[4.0, -3.0, 4.0/3.0, -1.0/4.0], + [-13.0/3.0, 19.0/4.0, -7.0/3.0, 11.0/24.0], + [3.0/2.0, -2.0, 7.0/6.0, -1.0/4.0], + [-1.0/6.0, 1.0/4.0, -1.0/6.0, 1.0/24.0]] :: [[Double]] + d = new dData + + eData = [[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], + [9.0, 10.0, 11.0, 12.0], [13.0, 14.0, 15.0, 16.0]] :: [[Double]] + e = new eData + + fData = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] :: [[Double]] + f = new fData + + putStrLn "Using 'normal' matrix multiplication:" + case matrixMultiply a b of + Right result -> putStrLn $ " a * b = \n" ++ matrixToString result + Left err -> putStrLn $ "Error: " ++ err + + case matrixMultiply c d of + Right result -> putStrLn $ " c * d = \n" ++ matrixToStringWithPrecision result 6 + Left err -> putStrLn $ "Error: " ++ err + + case matrixMultiply e f of + Right result -> putStrLn $ " e * f = \n" ++ matrixToString result + Left err -> putStrLn $ "Error: " ++ err + + putStrLn "\nUsing 'Strassen' matrix multiplication:" + case strassen a b of + Right result -> putStrLn $ " a * b = \n" ++ matrixToString result + Left err -> putStrLn $ "Error: " ++ err + + case strassen c d of + Right result -> putStrLn $ " c * d = \n" ++ matrixToStringWithPrecision result 6 + Left err -> putStrLn $ "Error: " ++ err + + case strassen e f of + Right result -> putStrLn $ " e * f = \n" ++ matrixToString result + Left err -> putStrLn $ "Error: " ++ err diff --git a/Task/Strassens-algorithm/Java/strassens-algorithm.java b/Task/Strassens-algorithm/Java/strassens-algorithm.java new file mode 100644 index 0000000000..9fed8e2eb4 --- /dev/null +++ b/Task/Strassens-algorithm/Java/strassens-algorithm.java @@ -0,0 +1,281 @@ +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +class Matrix { + public List> data; + public int rows; + public int cols; + + public Matrix(List> data) { + this.data = data; + rows = data.size(); + cols = (rows > 0) ? data.get(0).size() : 0; + } + + public int getRows() { + return rows; + } + + public int getCols() { + return cols; + } + + public void validateDimensions(Matrix other) { + if (getRows() != other.getRows() || getCols() != other.getCols()) { + throw new RuntimeException("Matrices must have the same dimensions."); + } + } + + public void validateMultiplication(Matrix other) { + if (getCols() != other.getRows()) { + throw new RuntimeException("Cannot multiply these matrices."); + } + } + + public void validateSquarePowerOfTwo() { + if (getRows() != getCols()) { + throw new RuntimeException("Matrix must be square."); + } + if (getRows() == 0 || (getRows() & (getRows() - 1)) != 0) { + throw new RuntimeException("Size of matrix must be a power of two."); + } + } + + public Matrix add(Matrix other) { + validateDimensions(other); + + List> resultData = new ArrayList<>(); + for (int i = 0; i < rows; ++i) { + List row = new ArrayList<>(); + for (int j = 0; j < cols; ++j) { + row.add(data.get(i).get(j) + other.data.get(i).get(j)); + } + resultData.add(row); + } + + return new Matrix(resultData); + } + + public Matrix subtract(Matrix other) { + validateDimensions(other); + + List> resultData = new ArrayList<>(); + for (int i = 0; i < rows; ++i) { + List row = new ArrayList<>(); + for (int j = 0; j < cols; ++j) { + row.add(data.get(i).get(j) - other.data.get(i).get(j)); + } + resultData.add(row); + } + + return new Matrix(resultData); + } + + public Matrix multiply(Matrix other) { + validateMultiplication(other); + + List> resultData = new ArrayList<>(); + for (int i = 0; i < rows; ++i) { + List row = new ArrayList<>(); + for (int j = 0; j < other.cols; ++j) { + double sum = 0.0; + for (int k = 0; k < other.rows; ++k) { + sum += data.get(i).get(k) * other.data.get(k).get(j); + } + row.add(sum); + } + resultData.add(row); + } + + return new Matrix(resultData); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + for (List row : data) { + sb.append("["); + for (int i = 0; i < row.size(); ++i) { + sb.append(row.get(i)); + if (i < row.size() - 1) { + sb.append(", "); + } + } + sb.append("]\n"); + } + return sb.toString(); + } + + public String toStringWithPrecision(int p) { + StringBuilder sb = new StringBuilder(); + double pow = Math.pow(10.0, p); + + for (List row : data) { + sb.append("["); + for (int i = 0; i < row.size(); ++i) { + double r = Math.round(row.get(i) * pow) / pow; + String formatted = String.format("%." + p + "f", r); + + if (formatted.equals("-0" + (p > 0 ? "." + "0".repeat(p) : ""))) { + formatted = "0" + (p > 0 ? "." + "0".repeat(p) : ""); + } + + sb.append(formatted); + + if (i < row.size() - 1) { + sb.append(", "); + } + } + sb.append("]\n"); + } + return sb.toString(); + } + + private static int[][] getParams(int r, int c) { + return new int[][] { + {0, r, 0, c, 0, 0}, + {0, r, c, 2 * c, 0, c}, + {r, 2 * r, 0, c, r, 0}, + {r, 2 * r, c, 2 * c, r, c} + }; + } + + public Matrix[] toQuarters() { + int r = getRows() / 2; + int c = getCols() / 2; + int[][] p = getParams(r, c); + Matrix[] quarters = new Matrix[4]; + + for (int k = 0; k < 4; ++k) { + List> qData = new ArrayList<>(); + for (int i = 0; i < r; i++) { + List row = new ArrayList<>(); + for (int j = 0; j < c; j++) { + row.add(0.0); + } + qData.add(row); + } + + for (int i = p[k][0]; i < p[k][1]; ++i) { + for (int j = p[k][2]; j < p[k][3]; ++j) { + qData.get(i - p[k][4]).set(j - p[k][5], data.get(i).get(j)); + } + } + quarters[k] = new Matrix(qData); + } + + return quarters; + } + + public static Matrix fromQuarters(Matrix[] q) { + int r = q[0].getRows(); + int c = q[0].getCols(); + int[][] p = getParams(r, c); + int rows = r * 2; + int cols = c * 2; + + List> mData = new ArrayList<>(); + for (int i = 0; i < rows; i++) { + List row = new ArrayList<>(); + for (int j = 0; j < cols; j++) { + row.add(0.0); + } + mData.add(row); + } + + for (int k = 0; k < 4; ++k) { + for (int i = p[k][0]; i < p[k][1]; ++i) { + for (int j = p[k][2]; j < p[k][3]; ++j) { + mData.get(i).set(j, q[k].data.get(i - p[k][4]).get(j - p[k][5])); + } + } + } + + return new Matrix(mData); + } + + public Matrix strassen(Matrix other) { + validateSquarePowerOfTwo(); + other.validateSquarePowerOfTwo(); + if (getRows() != other.getRows() || getCols() != other.getCols()) { + throw new RuntimeException("Matrices must be square and of equal size for Strassen multiplication."); + } + + if (getRows() == 1) { + return this.multiply(other); + } + + Matrix[] qa = toQuarters(); + Matrix[] qb = other.toQuarters(); + + Matrix p1 = qa[1].subtract(qa[3]).strassen(qb[2].add(qb[3])); + Matrix p2 = qa[0].add(qa[3]).strassen(qb[0].add(qb[3])); + Matrix p3 = qa[0].subtract(qa[2]).strassen(qb[0].add(qb[1])); + Matrix p4 = qa[0].add(qa[1]).strassen(qb[3]); + Matrix p5 = qa[0].strassen(qb[1].subtract(qb[3])); + Matrix p6 = qa[3].strassen(qb[2].subtract(qb[0])); + Matrix p7 = qa[2].add(qa[3]).strassen(qb[0]); + + Matrix[] q = new Matrix[4]; + + q[0] = p1.add(p2).subtract(p4).add(p6); + q[1] = p4.add(p5); + q[2] = p6.add(p7); + q[3] = p2.subtract(p3).add(p5).subtract(p7); + + return fromQuarters(q); + } +} + +public class Main{ + public static void main(String[] args) { + List> aData = new ArrayList<>(); + aData.add(Arrays.asList(1.0, 2.0)); + aData.add(Arrays.asList(3.0, 4.0)); + Matrix a = new Matrix(aData); + + List> bData = new ArrayList<>(); + bData.add(Arrays.asList(5.0, 6.0)); + bData.add(Arrays.asList(7.0, 8.0)); + Matrix b = new Matrix(bData); + + List> cData = new ArrayList<>(); + cData.add(Arrays.asList(1.0, 1.0, 1.0, 1.0)); + cData.add(Arrays.asList(2.0, 4.0, 8.0, 16.0)); + cData.add(Arrays.asList(3.0, 9.0, 27.0, 81.0)); + cData.add(Arrays.asList(4.0, 16.0, 64.0, 256.0)); + Matrix c = new Matrix(cData); + + List> dData = new ArrayList<>(); + dData.add(Arrays.asList(4.0, -3.0, 4.0 / 3.0, -1.0 / 4.0)); + dData.add(Arrays.asList(-13.0 / 3.0, 19.0 / 4.0, -7.0 / 3.0, 11.0 / 24.0)); + dData.add(Arrays.asList(3.0 / 2.0, -2.0, 7.0 / 6.0, -1.0 / 4.0)); + dData.add(Arrays.asList(-1.0 / 6.0, 1.0 / 4.0, -1.0 / 6.0, 1.0 / 24.0)); + Matrix d = new Matrix(dData); + + List> eData = new ArrayList<>(); + eData.add(Arrays.asList(1.0, 2.0, 3.0, 4.0)); + eData.add(Arrays.asList(5.0, 6.0, 7.0, 8.0)); + eData.add(Arrays.asList(9.0, 10.0, 11.0, 12.0)); + eData.add(Arrays.asList(13.0, 14.0, 15.0, 16.0)); + Matrix e = new Matrix(eData); + + List> fData = new ArrayList<>(); + fData.add(Arrays.asList(1.0, 0.0, 0.0, 0.0)); + fData.add(Arrays.asList(0.0, 1.0, 0.0, 0.0)); + fData.add(Arrays.asList(0.0, 0.0, 1.0, 0.0)); + fData.add(Arrays.asList(0.0, 0.0, 0.0, 1.0)); + Matrix f = new Matrix(fData); + + System.out.println("Using 'normal' matrix multiplication:"); + System.out.println(" a * b = " + a.multiply(b)); + System.out.println(" c * d = " + c.multiply(d).toStringWithPrecision(6)); + System.out.println(" e * f = " + e.multiply(f)); + + System.out.println("\nUsing 'Strassen' matrix multiplication:"); + System.out.println(" a * b = " + a.strassen(b)); + System.out.println(" c * d = " + c.strassen(d).toStringWithPrecision(6)); + System.out.println(" e * f = " + e.strassen(f)); + } +} diff --git a/Task/Strassens-algorithm/JavaScript/strassens-algorithm-1.js b/Task/Strassens-algorithm/JavaScript/strassens-algorithm-1.js new file mode 100644 index 0000000000..6448ff9755 --- /dev/null +++ b/Task/Strassens-algorithm/JavaScript/strassens-algorithm-1.js @@ -0,0 +1,318 @@ +/** + * Represents the dimensions of a matrix. + * @typedef {object} Shape + * @property {number} rows - Number of rows. + * @property {number} cols - Number of columns. + */ + +/** + * A matrix implemented as a wrapper around a 2D array. + */ +class Matrix { + /** + * Creates a Matrix instance. + * @param {number[][]} data - A 2D array representing the matrix data. + */ + constructor(data = []) { + if (!Array.isArray(data) || (data.length > 0 && !Array.isArray(data[0]))) { + throw new Error("Matrix data must be a 2D array."); + } + // Basic check for consistent row lengths + if (data.length > 1) { + const firstLen = data[0].length; + if (!data.every(row => row.length === firstLen)) { + throw new Error("Matrix rows must have consistent lengths."); + } + } + this.data = data; + } + + /** + * Gets the dimensions (shape) of the matrix. + * @returns {Shape} An object with rows and cols properties. + */ + get shape() { + const rows = this.data.length; + const cols = rows > 0 ? this.data[0].length : 0; + return { rows, cols }; + } + + /** + * Creates a new Matrix assembled from nested blocks of matrices. + * @param {Matrix[][]} blocks - A 2D array of Matrix objects. + * @returns {Matrix} A new Matrix assembled from the blocks. + * @static + */ + static block(blocks) { + const newMatrixData = []; + for (const hblock of blocks) { + if (!hblock || hblock.length === 0) continue; + const numRowsInBlock = hblock[0].shape.rows; // Assume consistent rows within a hblock + + for (let i = 0; i < numRowsInBlock; i++) { + let newRow = []; + for (const matrix of hblock) { + if (matrix.data[i]) { // Check if row exists + newRow = newRow.concat(matrix.data[i]); + } else { + // Handle potential inconsistencies if needed, maybe throw error or fill? + console.warn("Inconsistent row count during block assembly"); + } + } + newMatrixData.push(newRow); + } + } + return new Matrix(newMatrixData); + } + + /** + * Performs naive matrix multiplication (dot product). + * @param {Matrix} b - The matrix to multiply with. + * @returns {Matrix} The resulting matrix product. + */ + dot(b) { + if (!(b instanceof Matrix)) { + throw new Error("Argument must be a Matrix instance."); + } + const aShape = this.shape; + const bShape = b.shape; + + if (aShape.cols !== bShape.rows) { + throw new Error(`Matrices incompatible for multiplication: ${aShape.cols} cols != ${bShape.rows} rows`); + } + + const resultData = []; + for (let i = 0; i < aShape.rows; i++) { + resultData[i] = []; + for (let j = 0; j < bShape.cols; j++) { + let sum = 0; + for (let k = 0; k < aShape.cols; k++) { + sum += this.data[i][k] * b.data[k][j]; + } + resultData[i][j] = sum; + } + } + return new Matrix(resultData); + } + + /** + * Multiplies this matrix by another matrix (using naive multiplication). + * Equivalent to Python's __matmul__. + * @param {Matrix} b - The matrix to multiply with. + * @returns {Matrix} The resulting matrix product. + */ + multiply(b) { + return this.dot(b); + } + + /** + * Adds another matrix to this matrix. + * Equivalent to Python's __add__. + * @param {Matrix} b - The matrix to add. + * @returns {Matrix} The resulting matrix sum. + */ + add(b) { + if (!(b instanceof Matrix)) { + throw new Error("Argument must be a Matrix instance."); + } + const aShape = this.shape; + const bShape = b.shape; + + if (aShape.rows !== bShape.rows || aShape.cols !== bShape.cols) { + throw new Error("Matrices must have the same shape for addition."); + } + + const resultData = this.data.map((row, i) => + row.map((val, j) => val + b.data[i][j]) + ); + return new Matrix(resultData); + } + + /** + * Subtracts another matrix from this matrix. + * Equivalent to Python's __sub__. + * @param {Matrix} b - The matrix to subtract. + * @returns {Matrix} The resulting matrix difference. + */ + subtract(b) { + if (!(b instanceof Matrix)) { + throw new Error("Argument must be a Matrix instance."); + } + const aShape = this.shape; + const bShape = b.shape; + + if (aShape.rows !== bShape.rows || aShape.cols !== bShape.cols) { + throw new Error("Matrices must have the same shape for subtraction."); + } + + const resultData = this.data.map((row, i) => + row.map((val, j) => val - b.data[i][j]) + ); + return new Matrix(resultData); + } + + /** + * Helper function to slice the matrix data. + * @param {number} rowStart - Starting row index (inclusive). + * @param {number} rowEnd - Ending row index (exclusive). + * @param {number} colStart - Starting column index (inclusive). + * @param {number} colEnd - Ending column index (exclusive). + * @returns {Matrix} A new Matrix containing the sliced data. + * @private // Indicates intended internal use + */ + _slice(rowStart, rowEnd, colStart, colEnd) { + const slicedData = this.data.slice(rowStart, rowEnd) + .map(row => row.slice(colStart, colEnd)); + return new Matrix(slicedData); + } + + /** + * Performs matrix multiplication using Strassen's algorithm. + * Requires square matrices whose dimensions are powers of 2. + * @param {Matrix} b - The matrix to multiply with. + * @returns {Matrix} The resulting matrix product. + */ + strassen(b) { + if (!(b instanceof Matrix)) { + throw new Error("Argument must be a Matrix instance."); + } + const aShape = this.shape; + const bShape = b.shape; + + if (aShape.rows !== aShape.cols) { + throw new Error("Matrix must be square for Strassen's algorithm."); + } + if (aShape.rows !== bShape.rows || aShape.cols !== bShape.cols) { + throw new Error("Matrices must have the same shape for Strassen's algorithm."); + } + // Check if dimension is a power of 2 + if (aShape.rows === 0 || (aShape.rows & (aShape.rows - 1)) !== 0) { + throw new Error("Matrix dimension must be a power of 2 for Strassen's algorithm."); + } + + if (aShape.rows === 1) { + return this.dot(b); // Base case + } + + const n = aShape.rows; + const p = n / 2; // Partition size + + // Partition matrices + const a11 = this._slice(0, p, 0, p); + const a12 = this._slice(0, p, p, n); + const a21 = this._slice(p, n, 0, p); + const a22 = this._slice(p, n, p, n); + + const b11 = b._slice(0, p, 0, p); + const b12 = b._slice(0, p, p, n); + const b21 = b._slice(p, n, 0, p); + const b22 = b._slice(p, n, p, n); + + // Recursive calls (Strassen's 7 multiplications) + const m1 = (a11.add(a22)).strassen(b11.add(b22)); + const m2 = (a21.add(a22)).strassen(b11); + const m3 = a11.strassen(b12.subtract(b22)); + const m4 = a22.strassen(b21.subtract(b11)); + const m5 = (a11.add(a12)).strassen(b22); + const m6 = (a21.subtract(a11)).strassen(b11.add(b12)); + const m7 = (a12.subtract(a22)).strassen(b21.add(b22)); + + // Combine results + const c11 = m1.add(m4).subtract(m5).add(m7); + const c12 = m3.add(m5); + const c21 = m2.add(m4); + const c22 = m1.subtract(m2).add(m3).add(m6); + + // Assemble the final matrix from blocks + return Matrix.block([[c11, c12], [c21, c22]]); + } + + /** + * Rounds the elements of the matrix to a specified number of decimal places. + * @param {number} [ndigits=0] - Number of decimal places to round to. If undefined or 0, rounds to the nearest integer. + * @returns {Matrix} A new Matrix with rounded elements. + */ + round(ndigits = 0) { + const factor = Math.pow(10, ndigits); + const roundFn = ndigits > 0 + ? (num) => Math.round((num + Number.EPSILON) * factor) / factor + : (num) => Math.round(num); + + const roundedData = this.data.map(row => + row.map(val => roundFn(val)) + ); + return new Matrix(roundedData); + } + + /** + * Provides a string representation of the matrix. + * @returns {string} The string representation. + */ + toString() { + const rowsStr = this.data.map(row => ` [${row.join(', ')}]`); + return `Matrix([\n${rowsStr.join(',\n')}\n])`; + } +} + +// --- Examples --- + +function examples() { + const a = new Matrix([ + [1, 2], + [3, 4], + ]); + const b = new Matrix([ + [5, 6], + [7, 8], + ]); + const c = new Matrix([ + [1, 1, 1, 1], + [2, 4, 8, 16], + [3, 9, 27, 81], + [4, 16, 64, 256], + ]); + const d = new Matrix([ + [4, -3, 4 / 3, -1 / 4], + [-13 / 3, 19 / 4, -7 / 3, 11 / 24], + [3 / 2, -2, 7 / 6, -1 / 4], + [-1 / 6, 1 / 4, -1 / 6, 1 / 24], + ]); + const e = new Matrix([ + [1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12], + [13, 14, 15, 16], + ]); + const f = new Matrix([ // Identity matrix + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, 0], + [0, 0, 0, 1], + ]); + + console.log("Naive matrix multiplication:"); + console.log(` a * b = ${a.multiply(b)}`); // Uses toString implicitly + console.log(` c * d = ${c.multiply(d).round(2)}`); // Round near-zero elements + console.log(` e * f = ${e.multiply(f)}`); + + console.log("\nStrassen's matrix multiplication:"); + console.log(` a * b = ${a.strassen(b)}`); + console.log(` c * d = ${c.strassen(d).round(2)}`); // Round near-zero elements + console.log(` e * f = ${e.strassen(f)}`); + + // Example of addition/subtraction + console.log("\nAddition/Subtraction:"); + const sum_ab = a.add(b); + console.log(` a + b = ${sum_ab}`); + const diff_ba = b.subtract(a); + console.log(` b - a = ${diff_ba}`); + + // Example of block creation (creates a 4x4 matrix from four 2x2 matrices) + console.log("\nBlock Creation:"); + const blocked = Matrix.block([[a, b], [b, a]]); + console.log(` Blocked [a,b],[b,a] = ${blocked}`); + +} + +// Run examples +examples(); diff --git a/Task/Strassens-algorithm/JavaScript/strassens-algorithm-2.js b/Task/Strassens-algorithm/JavaScript/strassens-algorithm-2.js new file mode 100644 index 0000000000..1e6ff77ebf --- /dev/null +++ b/Task/Strassens-algorithm/JavaScript/strassens-algorithm-2.js @@ -0,0 +1,316 @@ +class Matrix { + /** @type {number[][]} */ + data; + /** @type {number} */ + rows; + /** @type {number} */ + cols; + + /** + * @param {number[][]} data The matrix data as a 2D array. + */ + constructor(data) { + if (!Array.isArray(data) || (data.length > 0 && !Array.isArray(data[0]))) { + throw new Error("Input data must be a 2D array."); + } + // Optional: Deep copy to prevent external modifications + this.data = data.map(row => [...row]); + this.rows = data.length; + this.cols = (this.rows > 0) ? (data[0]?.length ?? 0) : 0; // Handle empty rows gracefully + + // Optional: Validate that all rows have the same length + if (this.rows > 0) { + const firstRowLength = this.cols; + for (let i = 1; i < this.rows; i++) { + if (data[i].length !== firstRowLength) { + throw new Error("All rows in the matrix must have the same length."); + } + } + } + } + + /** @returns {number} */ + getRows() { + return this.rows; + } + + /** @returns {number} */ + getCols() { + return this.cols; + } + + /** @param {Matrix} other */ + validateDimensions(other) { + if (this.getRows() !== other.getRows() || this.getCols() !== other.getCols()) { + throw new Error("Matrices must have the same dimensions."); + } + } + + /** @param {Matrix} other */ + validateMultiplication(other) { + if (this.getCols() !== other.getRows()) { + throw new Error(`Cannot multiply matrices: (${this.getRows()}x${this.getCols()}) * (${other.getRows()}x${other.getCols()})`); + } + } + + validateSquarePowerOfTwo() { + if (this.getRows() !== this.getCols()) { + throw new Error("Matrix must be square for this operation."); + } + const n = this.getRows(); + // Check if n is 0 or not a power of two + // (n & (n - 1)) === 0 checks if n is a power of two (or 0) + if (n === 0 || (n & (n - 1)) !== 0) { + throw new Error("Size of matrix must be a power of two for Strassen."); + } + } + + /** + * Adds another matrix to this matrix. + * @param {Matrix} other The matrix to add. + * @returns {Matrix} A new matrix representing the sum. + */ + add(other) { + this.validateDimensions(other); + + const result_data = Array.from({ length: this.rows }, () => Array(this.cols).fill(0.0)); + for (let i = 0; i < this.rows; ++i) { + for (let j = 0; j < this.cols; ++j) { + result_data[i][j] = this.data[i][j] + other.data[i][j]; + } + } + + return new Matrix(result_data); + } + + /** + * Subtracts another matrix from this matrix. + * @param {Matrix} other The matrix to subtract. + * @returns {Matrix} A new matrix representing the difference. + */ + subtract(other) { + this.validateDimensions(other); + + const result_data = Array.from({ length: this.rows }, () => Array(this.cols).fill(0.0)); + for (let i = 0; i < this.rows; ++i) { + for (let j = 0; j < this.cols; ++j) { + result_data[i][j] = this.data[i][j] - other.data[i][j]; + } + } + + return new Matrix(result_data); + } + + /** + * Multiplies this matrix by another matrix (standard algorithm). + * @param {Matrix} other The matrix to multiply by. + * @returns {Matrix} A new matrix representing the product. + */ + multiply(other) { + this.validateMultiplication(other); + + const result_data = Array.from({ length: this.rows }, () => Array(other.cols).fill(0.0)); + for (let i = 0; i < this.rows; ++i) { + for (let j = 0; j < other.cols; ++j) { + let sum = 0.0; + // K loops through columns of 'this' and rows of 'other' + for (let k = 0; k < this.cols; ++k) { + sum += this.data[i][k] * other.data[k][j]; + } + result_data[i][j] = sum; + } + } + + return new Matrix(result_data); + } + + /** + * Returns a string representation of the matrix. + * @returns {string} + */ + toString() { + return this.data.map(row => `[${row.join(', ')}]`).join('\n'); + } + + /** + * Returns a string representation with specified precision, handling rounding and "-0". + * @param {number} p Precision (number of decimal places). + * @returns {string} + */ + toStringWithPrecision(p) { + let resultString = ""; + const pow = Math.pow(10, p); + const zeroString = (0).toFixed(p); + const negZeroString = `-${zeroString}`; + + for (const row of this.data) { + resultString += "["; + for (let i = 0; i < row.length; ++i) { + let val = row[i]; + // Round like C++: round(val * 10^p) / 10^p + let roundedVal = Math.round(val * pow) / pow; + + // Format to fixed precision + let formattedVal = roundedVal.toFixed(p); + + // Handle the "-0.00..." case that toFixed might produce after rounding + if (formattedVal === negZeroString) { + formattedVal = zeroString; + } + + resultString += formattedVal; + if (i < row.length - 1) { + resultString += ", "; + } + } + resultString += "]\n"; // Add newline after each row like C++ example + } + return resultString.trimEnd(); // Remove trailing newline + } + + /** + * Helper function to get quadrant slicing parameters. + * @param {number} r Half rows + * @param {number} c Half columns + * @returns {number[][]} Array of [startRow, endRow, startCol, endCol, offsetRow, offsetCol] + */ + static params(r, c) { + // [startRow, endRow, startCol, endCol, resultOffsetRow, resultOffsetCol] + return [ + [0, r, 0, c, 0, 0], // Top-left quadrant (0) + [0, r, c, 2 * c, 0, c], // Top-right quadrant (1) + [r, 2 * r, 0, c, r, 0], // Bottom-left quadrant (2) + [r, 2 * r, c, 2 * c, r, c] // Bottom-right quadrant (3) + ]; + } + + /** + * Splits the matrix into four equally sized quadrants. + * Assumes matrix dimensions are even. + * @returns {Matrix[]} An array of four matrices [TopLeft, TopRight, BottomLeft, BottomRight]. + */ + toQuarters() { + const r = this.getRows() / 2; + const c = this.getCols() / 2; + if (!Number.isInteger(r) || !Number.isInteger(c)) { + throw new Error("Matrix dimensions must be even for splitting into quarters."); + } + const p = Matrix.params(r, c); + const quarters = Array(4); // Will hold 4 Matrix objects + + for (let k = 0; k < 4; ++k) { + const q_data = Array.from({ length: r }, () => Array(c)); + const [startRow, endRow, startCol, endCol, offsetRow, offsetCol] = p[k]; + for (let i = startRow; i < endRow; ++i) { + for (let j = startCol; j < endCol; ++j) { + // Adjust indices for the smaller quarter matrix + q_data[i - offsetRow][j - offsetCol] = this.data[i][j]; + } + } + quarters[k] = new Matrix(q_data); + } + return quarters; // [TopLeft, TopRight, BottomLeft, BottomRight] + } + + /** + * Creates a new matrix by combining four quadrant matrices. + * @param {Matrix[]} q An array of four matrices [TopLeft, TopRight, BottomLeft, BottomRight]. + * @returns {Matrix} The combined matrix. + */ + static fromQuarters(q) { + if (q.length !== 4) throw new Error("Requires exactly four quadrant matrices."); + // Basic validation: Ensure quadrants have compatible dimensions + const r = q[0].getRows(); + const c = q[0].getCols(); + if (q[1].getRows() !== r || q[1].getCols() !== c || + q[2].getRows() !== r || q[2].getCols() !== c || + q[3].getRows() !== r || q[3].getCols() !== c) { + throw new Error("Quadrant matrices must have the same dimensions."); + } + + const p = Matrix.params(r, c); + const rows = r * 2; + const cols = c * 2; + const m_data = Array.from({ length: rows }, () => Array(cols)); + + for (let k = 0; k < 4; ++k) { + const [startRow, endRow, startCol, endCol, offsetRow, offsetCol] = p[k]; + for (let i = startRow; i < endRow; ++i) { + for (let j = startCol; j < endCol; ++j) { + // Adjust indices to read from the correct quadrant + m_data[i][j] = q[k].data[i - offsetRow][j - offsetCol]; + } + } + } + return new Matrix(m_data); + } + + /** + * Multiplies this matrix by another using Strassen's algorithm. + * Assumes both matrices are square and their size is a power of two. + * @param {Matrix} other The matrix to multiply by. + * @returns {Matrix} The resulting matrix product. + */ + strassen(other) { + this.validateSquarePowerOfTwo(); + other.validateSquarePowerOfTwo(); + if (this.getRows() !== other.getRows()) { // Columns already checked by validateSquarePowerOfTwo + throw new Error("Matrices must be square and of equal size for Strassen multiplication."); + } + + // Base case: If the matrix is 1x1 + if (this.getRows() === 1) { + // Use standard multiplication for the 1x1 case + return this.multiply(other); + } + + // Split matrices into quarters + const qa = this.toQuarters(); // [a11, a12, a21, a22] + const qb = other.toQuarters(); // [b11, b12, b21, b22] + + // Calculate the 7 products recursively (P1 to P7) + const p1 = (qa[1].subtract(qa[3])).strassen(qb[2].add(qb[3])); // p1 = (a12 - a22) * (b21 + b22) + const p2 = (qa[0].add(qa[3])).strassen(qb[0].add(qb[3])); // p2 = (a11 + a22) * (b11 + b22) + const p3 = (qa[0].subtract(qa[2])).strassen(qb[0].add(qb[1])); // p3 = (a11 - a21) * (b11 + b12) + const p4 = (qa[0].add(qa[1])).strassen(qb[3]); // p4 = (a11 + a12) * b22 + const p5 = qa[0].strassen(qb[1].subtract(qb[3])); // p5 = a11 * (b12 - b22) + const p6 = qa[3].strassen(qb[2].subtract(qb[0])); // p6 = a22 * (b21 - b11) + const p7 = (qa[2].add(qa[3])).strassen(qb[0]); // p7 = (a21 + a22) * b11 + + // Calculate the result quarters (C11, C12, C21, C22) + const c11 = p1.add(p2).subtract(p4).add(p6); + const c12 = p4.add(p5); + const c21 = p6.add(p7); + const c22 = p2.subtract(p3).add(p5).subtract(p7); + + // Combine the quarters into the result matrix + return Matrix.fromQuarters([c11, c12, c21, c22]); + } +} + +// --- Main execution (equivalent to C++ main) --- +function main() { + const a = new Matrix([[1.0, 2.0], [3.0, 4.0]]); + const b = new Matrix([[5.0, 6.0], [7.0, 8.0]]); + const c = new Matrix([[1.0, 1.0, 1.0, 1.0], [2.0, 4.0, 8.0, 16.0], [3.0, 9.0, 27.0, 81.0], [4.0, 16.0, 64.0, 256.0]]); + const d = new Matrix([[4.0, -3.0, 4.0 / 3.0, -1.0 / 4.0], [-13.0 / 3.0, 19.0 / 4.0, -7.0 / 3.0, 11.0 / 24.0], [3.0 / 2.0, -2.0, 7.0 / 6.0, -1.0 / 4.0], [-1.0 / 6.0, 1.0 / 4.0, -1.0 / 6.0, 1.0 / 24.0]]); + const e = new Matrix([[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0, 12.0], [13.0, 14.0, 15.0, 16.0]]); + const f = new Matrix([[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]); // Identity Matrix + + console.log("Using 'normal' matrix multiplication:"); + console.log(` a * b = \n${a.multiply(b).toString()}`); + console.log(`\n c * d = \n${c.multiply(d).toStringWithPrecision(6)}`); // Should be close to identity + console.log(`\n e * f = \n${e.multiply(f).toString()}`); // Should be e + + console.log("\nUsing 'Strassen' matrix multiplication:"); + try { + console.log(` a * b = \n${a.strassen(b).toString()}`); + console.log(`\n c * d = \n${c.strassen(d).toStringWithPrecision(6)}`); // Should be close to identity + console.log(`\n e * f = \n${e.strassen(f).toString()}`); // Should be e + } catch (error) { + console.error("Strassen multiplication failed:", error.message); + } +} + +// Run the main function +main(); diff --git a/Task/Strassens-algorithm/Jq/strassens-algorithm.jq b/Task/Strassens-algorithm/Jq/strassens-algorithm.jq new file mode 100644 index 0000000000..153e90d9bb --- /dev/null +++ b/Task/Strassens-algorithm/Jq/strassens-algorithm.jq @@ -0,0 +1,113 @@ +### Generic utilities +def sigma(stream): reduce stream as $x (0; . + $x); + +# Hilbert-Schmidt norm: +def frobenius: + sigma( flatten[] | .*. ) | sqrt; + +### Matrices +# Create an m x n matrix +def matrix(m; n; init): + if m == 0 then [] + elif m == 1 then [[range(0;n) | init]] + elif m > 0 then + matrix(1;n;init) as $row + | [range(0;m) | $row ] + else error("matrix\(m);_;_) invalid") + end; + +# A and B must be (multi-dimensional) vectors of the same shape +def vector_add($A;$B): + if ($A|type) == "array" + then reduce range(0; $A|length) as $i ([]; + . + [vector_add($A[$i]; $B[$i])] ) + else $A + $B + end; + +def vector_negate: + if type == "array" + then map(vector_negate) + else - . + end; + +def vector_subtract($A;$B): + vector_add($A; $B|vector_negate); + +# A should be m by n; and B n by p +# Pre-allocating the resultant matrix results in a very small net speedup. +def multiply($A; $B): + ($A|length) as $m + | ($A[0]|length) as $n + | ($B[0]|length) as $p + | reduce range(0; $m) as $i + (matrix($m; $p; 0); # initialize to avoid resizing + reduce range(0;$p) as $j (.; + .[$i][$j] = reduce range(0;$n) as $k + (0; + # Cij = innerproduct of row i, column j + . + $A[$i][$k] * $B[$k][$j] ))) ; + +def submatrix($m1; $m2; $n1; $n2): + .[$m1:$m2] | map( .[$n1:$n2]); + +def submatrix($A; $m1; $m2; $n1; $n2): + $A | submatrix($m1; $m2; $n1; $n2); + +def rowwise_extend($A;$B): + reduce range(0; $A|length) as $i ([]; . + [$A[$i] + $B[$i]]); + +### Strassen multiplication of n*n square matrices where n is a power of 2. +def Strassen($A; $B): + ($A[0]|length) as $n + | if $n == 1 then multiply($A; $B) + else + submatrix($A; 0; $n/2; 0; $n/2) as $A11 + | submatrix($A; 0; $n/2; $n/2; $n) as $A12 + | submatrix($A; $n/2; $n; 0; $n/2) as $A21 + | submatrix($A; $n/2; $n; $n/2; $n) as $A22 + | submatrix($B; 0; $n/2; 0; $n/2) as $B11 + | submatrix($B; 0; $n/2; $n/2; $n) as $B12 + | submatrix($B; $n/2; $n; 0; $n/2) as $B21 + | submatrix($B; $n/2; $n; $n/2+0; $n) as $B22 + + | Strassen( vector_subtract($A12; $A22); vector_add($B21; $B22)) as $P1 + | Strassen( vector_add($A11; $A22); vector_add($B11; $B22)) as $P2 + | Strassen( vector_subtract($A11; $A21); vector_add($B11; $B12)) as $P3 + | Strassen( vector_add($A11; $A12); $B22) as $P4 + | Strassen( $A11; vector_subtract($B12; $B22)) as $P5 + | Strassen( $A22; vector_subtract($B21; $B11) ) as $P6 + | Strassen( vector_add($A21; $A22); $B11) as $P7 + + | vector_add(vector_subtract(vector_add($P1; $P2); $P4); $P6) as $C11 + | vector_add($P4; $P5) as $C12 + | vector_add($P6; $P7) as $C21 + | vector_add(vector_subtract($P2; $P3); vector_subtract($P5;$P7)) as $C22 + # [C11 C12; C21 C22] + | rowwise_extend($C11; $C12) + rowwise_extend($C21; $C22) + end +; + +# ## Examples +def A: [[1, 2], [3, 4]]; +def B: [[5, 6], [7, 8]]; +def C: [[1, 1, 1, 1], + [2, 4, 8, 16], + [3, 9, 27, 81], + [4, 16, 64, 256]]; +def D: [[4, -3, 4/3, -1/4], + [-13/3, 19/4, -7/3, 11/24], + [3/2, -2, 7/6, -1/4], + [-1/6, 1/4, -1/6, 1/24]]; +def E: [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]; +def F: [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [ 0, 0, 0, 1]]; + +def r: (2|sqrt)/2; +def R: [[r, r], [-r, r]]; + +"A*B == Strassen(A;B): \((multiply(A; B) == Strassen(A; B)))", + +"Frobenius norm for C*D - Strassen(C;D): \(vector_subtract(multiply(C; D); Strassen(C; D)) | frobenius)", + +"E*F == Strassen(E;F): \(multiply(E; F) == Strassen( E; F))", + +"R*R == Strassen(R;R): \(multiply(R ; R) == Strassen(R; R))" diff --git a/Task/Strassens-algorithm/Julia/strassens-algorithm-1.julia b/Task/Strassens-algorithm/Julia/strassens-algorithm-1.jl similarity index 100% rename from Task/Strassens-algorithm/Julia/strassens-algorithm-1.julia rename to Task/Strassens-algorithm/Julia/strassens-algorithm-1.jl diff --git a/Task/Strassens-algorithm/Julia/strassens-algorithm-2.julia b/Task/Strassens-algorithm/Julia/strassens-algorithm-2.jl similarity index 100% rename from Task/Strassens-algorithm/Julia/strassens-algorithm-2.julia rename to Task/Strassens-algorithm/Julia/strassens-algorithm-2.jl diff --git a/Task/Strassens-algorithm/Kotlin/strassens-algorithm.kts b/Task/Strassens-algorithm/Kotlin/strassens-algorithm.kts new file mode 100644 index 0000000000..be2e6d3921 --- /dev/null +++ b/Task/Strassens-algorithm/Kotlin/strassens-algorithm.kts @@ -0,0 +1,281 @@ +class Matrix(val data: List>) { + val rows: Int = data.size + val cols: Int = if (rows > 0) data[0].size else 0 + + // Remove the explicit getter methods since Kotlin generates them automatically + // fun getRows(): Int = rows // Remove this + // fun getCols(): Int = cols // Remove this + + fun validateDimensions(other: Matrix) { + if (rows != other.rows || cols != other.cols) { + throw RuntimeException("Matrices must have the same dimensions.") + } + } + + fun validateMultiplication(other: Matrix) { + if (cols != other.rows) { + throw RuntimeException("Cannot multiply these matrices.") + } + } + + fun validateSquarePowerOfTwo() { + if (rows != cols) { + throw RuntimeException("Matrix must be square.") + } + if (rows == 0 || (rows and (rows - 1)) != 0) { + throw RuntimeException("Size of matrix must be a power of two.") + } + } + + fun add(other: Matrix): Matrix { + validateDimensions(other) + + val resultData = mutableListOf>() + for (i in 0 until rows) { + val row = mutableListOf() + for (j in 0 until cols) { + row.add(data[i][j] + other.data[i][j]) + } + resultData.add(row) + } + + return Matrix(resultData) + } + + fun subtract(other: Matrix): Matrix { + validateDimensions(other) + + val resultData = mutableListOf>() + for (i in 0 until rows) { + val row = mutableListOf() + for (j in 0 until cols) { + row.add(data[i][j] - other.data[i][j]) + } + resultData.add(row) + } + + return Matrix(resultData) + } + + fun multiply(other: Matrix): Matrix { + validateMultiplication(other) + + val resultData = mutableListOf>() + for (i in 0 until rows) { + val row = mutableListOf() + for (j in 0 until other.cols) { + var sum = 0.0 + for (k in 0 until cols) { // Changed from other.rows to cols + sum += data[i][k] * other.data[k][j] + } + row.add(sum) + } + resultData.add(row) + } + + return Matrix(resultData) + } + + override fun toString(): String { + val sb = StringBuilder() + for (row in data) { + sb.append("[") + for (i in row.indices) { + sb.append(row[i]) + if (i < row.size - 1) { + sb.append(", ") + } + } + sb.append("]\n") + } + return sb.toString() + } + + fun toStringWithPrecision(p: Int): String { + val sb = StringBuilder() + val pow = Math.pow(10.0, p.toDouble()) + + for (row in data) { + sb.append("[") + for (i in row.indices) { + val r = Math.round(row[i] * pow) / pow + var formatted = String.format("%.${p}f", r) + + if (formatted == "-0${if (p > 0) "." + "0".repeat(p) else ""}") { + formatted = "0${if (p > 0) "." + "0".repeat(p) else ""}" + } + + sb.append(formatted) + + if (i < row.size - 1) { + sb.append(", ") + } + } + sb.append("]\n") + } + return sb.toString() + } + + companion object { + private fun getParams(r: Int, c: Int): Array { + return arrayOf( + intArrayOf(0, r, 0, c, 0, 0), + intArrayOf(0, r, c, 2 * c, 0, c), + intArrayOf(r, 2 * r, 0, c, r, 0), + intArrayOf(r, 2 * r, c, 2 * c, r, c) + ) + } + + fun fromQuarters(q: Array): Matrix { + val r = q[0].rows + val c = q[0].cols + val p = getParams(r, c) + val rows = r * 2 + val cols = c * 2 + + val mData = mutableListOf>() + for (i in 0 until rows) { + val row = mutableListOf() + for (j in 0 until cols) { + row.add(0.0) + } + mData.add(row) + } + + for (k in 0 until 4) { + for (i in p[k][0] until p[k][1]) { + for (j in p[k][2] until p[k][3]) { + mData[i][j] = q[k].data[i - p[k][4]][j - p[k][5]] + } + } + } + + return Matrix(mData) + } + } + + fun toQuarters(): Array { + val r = rows / 2 + val c = cols / 2 + val p = Companion.getParams(r, c) + val quarters = arrayOfNulls(4) + + for (k in 0 until 4) { + val qData = mutableListOf>() + for (i in 0 until r) { + val row = mutableListOf() + for (j in 0 until c) { + row.add(0.0) + } + qData.add(row) + } + + for (i in p[k][0] until p[k][1]) { + for (j in p[k][2] until p[k][3]) { + qData[i - p[k][4]][j - p[k][5]] = data[i][j] + } + } + quarters[k] = Matrix(qData) + } + + @Suppress("UNCHECKED_CAST") + return quarters as Array + } + + fun strassen(other: Matrix): Matrix { + validateSquarePowerOfTwo() + other.validateSquarePowerOfTwo() + if (rows != other.rows || cols != other.cols) { + throw RuntimeException("Matrices must be square and of equal size for Strassen multiplication.") + } + + if (rows == 1) { + return this.multiply(other) + } + + val qa = toQuarters() + val qb = other.toQuarters() + + val p1 = qa[1].subtract(qa[3]).strassen(qb[2].add(qb[3])) + val p2 = qa[0].add(qa[3]).strassen(qb[0].add(qb[3])) + val p3 = qa[0].subtract(qa[2]).strassen(qb[0].add(qb[1])) + val p4 = qa[0].add(qa[1]).strassen(qb[3]) + val p5 = qa[0].strassen(qb[1].subtract(qb[3])) + val p6 = qa[3].strassen(qb[2].subtract(qb[0])) + val p7 = qa[2].add(qa[3]).strassen(qb[0]) + + val q = arrayOfNulls(4) + + q[0] = p1.add(p2).subtract(p4).add(p6) + q[1] = p4.add(p5) + q[2] = p6.add(p7) + q[3] = p2.subtract(p3).add(p5).subtract(p7) + + @Suppress("UNCHECKED_CAST") + return Companion.fromQuarters(q as Array) + } +} + +fun main() { + val aData = listOf( + listOf(1.0, 2.0), + listOf(3.0, 4.0) + ) + val a = Matrix(aData) + + val bData = listOf( + listOf(5.0, 6.0), + listOf(7.0, 8.0) + ) + val b = Matrix(bData) + + val cData = listOf( + listOf(1.0, 1.0, 1.0, 1.0), + listOf(2.0, 4.0, 8.0, 16.0), + listOf(3.0, 9.0, 27.0, 81.0), + listOf(4.0, 16.0, 64.0, 256.0) + ) + val c = Matrix(cData) + + val dData = listOf( + listOf(4.0, -3.0, 4.0 / 3.0, -1.0 / 4.0), + listOf(-13.0 / 3.0, 19.0 / 4.0, -7.0 / 3.0, 11.0 / 24.0), + listOf(3.0 / 2.0, -2.0, 7.0 / 6.0, -1.0 / 4.0), + listOf(-1.0 / 6.0, 1.0 / 4.0, -1.0 / 6.0, 1.0 / 24.0) + ) + val d = Matrix(dData) + + val eData = listOf( + listOf(1.0, 2.0, 3.0, 4.0), + listOf(5.0, 6.0, 7.0, 8.0), + listOf(9.0, 10.0, 11.0, 12.0), + listOf(13.0, 14.0, 15.0, 16.0) + ) + val e = Matrix(eData) + + val fData = listOf( + listOf(1.0, 0.0, 0.0, 0.0), + listOf(0.0, 1.0, 0.0, 0.0), + listOf(0.0, 0.0, 1.0, 0.0), + listOf(0.0, 0.0, 0.0, 1.0) + ) + val f = Matrix(fData) + + println("Using 'normal' matrix multiplication:") + println(" a * b = ${a.multiply(b)}") + println("\nUsing 'Strassen' matrix multiplication:") + println(" a * b = ${a.strassen(b)}") + + + println("Using 'normal' matrix multiplication:") + println(" c * d = ${c.multiply(d).toStringWithPrecision(6)}") + println("\nUsing 'Strassen' matrix multiplication:") + println(" c * d = ${c.strassen(d).toStringWithPrecision(6)}") + + + println("Using 'normal' matrix multiplication:") + println(" e * f = ${e.multiply(f)}") + println("\nUsing 'Strassen' matrix multiplication:") + println(" e * f = ${e.strassen(f)}") + +} diff --git a/Task/Strassens-algorithm/Lua/strassens-algorithm.lua b/Task/Strassens-algorithm/Lua/strassens-algorithm.lua new file mode 100644 index 0000000000..45b8a3d8cf --- /dev/null +++ b/Task/Strassens-algorithm/Lua/strassens-algorithm.lua @@ -0,0 +1,241 @@ +-- Helper function to create a matrix from nested blocks +local function block_matrix(blocks) + local m = {} + local num_hblocks = #blocks + local num_vblocks = #blocks[1] + + -- Determine dimensions + local block_height = #blocks[1][1] + local block_widths = {} + for j = 1, num_vblocks do + block_widths[j] = #blocks[1][j][1] + end + + -- Build the resulting matrix + for i = 1, block_height * num_hblocks do + m[i] = {} + end + + for h = 1, num_hblocks do + local row_offset = (h - 1) * block_height + for i = 1, block_height do + local col_offset = 0 + for v = 1, num_vblocks do + local block = blocks[h][v] + for j = 1, block_widths[v] do + m[row_offset + i][col_offset + j] = block[i][j] + end + col_offset = col_offset + block_widths[v] + end + end + end + + return m +end + +-- Matrix multiplication (naive) +local function matrix_multiply(a, b) + local rows_a, cols_a = #a, #a[1] + local rows_b, cols_b = #b, #b[1] + + assert(cols_a == rows_b, "Incompatible matrix dimensions for multiplication") + + local result = {} + for i = 1, rows_a do + result[i] = {} + for j = 1, cols_b do + local sum = 0 + for k = 1, cols_a do + sum = sum + a[i][k] * b[k][j] + end + result[i][j] = sum + end + end + + return result +end + +-- Matrix addition +local function matrix_add(a, b) + local rows, cols = #a, #a[1] + assert(rows == #b and cols == #b[1], "Matrices must have the same dimensions") + + local result = {} + for i = 1, rows do + result[i] = {} + for j = 1, cols do + result[i][j] = a[i][j] + b[i][j] + end + end + + return result +end + +-- Matrix subtraction +local function matrix_subtract(a, b) + local rows, cols = #a, #a[1] + assert(rows == #b and cols == #b[1], "Matrices must have the same dimensions") + + local result = {} + for i = 1, rows do + result[i] = {} + for j = 1, cols do + result[i][j] = a[i][j] - b[i][j] + end + end + + return result +end + +-- Get submatrix +local function get_submatrix(m, start_row, end_row, start_col, end_col) + local result = {} + for i = start_row, end_row do + local row = {} + for j = start_col, end_col do + table.insert(row, m[i][j]) + end + table.insert(result, row) + end + return result +end + +-- Strassen's algorithm +local function strassen_multiply(a, b) + local n = #a + local m = #a[1] + + assert(n == m, "Matrix must be square") + assert(n == #b and n == #b[1], "Matrices must have the same dimensions") + + -- Check if size is a power of 2 + local temp = n + while temp > 1 do + assert(temp % 2 == 0, "Matrix dimension must be a power of 2") + temp = temp / 2 + end + + if n == 1 then + return {{a[1][1] * b[1][1]}} + end + + local half = n // 2 + + -- Partition matrices into quadrants + local a11 = get_submatrix(a, 1, half, 1, half) + local a12 = get_submatrix(a, 1, half, half+1, n) + local a21 = get_submatrix(a, half+1, n, 1, half) + local a22 = get_submatrix(a, half+1, n, half+1, n) + + local b11 = get_submatrix(b, 1, half, 1, half) + local b12 = get_submatrix(b, 1, half, half+1, n) + local b21 = get_submatrix(b, half+1, n, 1, half) + local b22 = get_submatrix(b, half+1, n, half+1, n) + + -- Calculate the seven products + local m1 = strassen_multiply(matrix_add(a11, a22), matrix_add(b11, b22)) + local m2 = strassen_multiply(matrix_add(a21, a22), b11) + local m3 = strassen_multiply(a11, matrix_subtract(b12, b22)) + local m4 = strassen_multiply(a22, matrix_subtract(b21, b11)) + local m5 = strassen_multiply(matrix_add(a11, a12), b22) + local m6 = strassen_multiply(matrix_subtract(a21, a11), matrix_add(b11, b12)) + local m7 = strassen_multiply(matrix_subtract(a12, a22), matrix_add(b21, b22)) + + -- Calculate the four quadrants of the result + local c11 = matrix_add(matrix_subtract(matrix_add(m1, m4), m5), m7) + local c12 = matrix_add(m3, m5) + local c21 = matrix_add(m2, m4) + local c22 = matrix_add(matrix_subtract(matrix_add(m1, m3), m2), m6) + + -- Combine quadrants into a single matrix + return block_matrix({{c11, c12}, {c21, c22}}) +end + +-- Round matrix values +local function matrix_round(m, digits) + local result = {} + local mult = 10^digits + + for i = 1, #m do + result[i] = {} + for j = 1, #m[1] do + if digits then + result[i][j] = math.floor(m[i][j] * mult + 0.5) / mult + else + result[i][j] = math.floor(m[i][j] + 0.5) + end + end + end + + return result +end + +-- Print matrix +local function print_matrix(name, m) + print(name .. " = {") + for i = 1, #m do + io.write(" {") + for j = 1, #m[1] do + io.write(m[i][j]) + if j < #m[1] then + io.write(", ") + end + end + print("}") + end + print("}") +end + +-- Examples +local function run_examples() + local a = { + {1, 2}, + {3, 4} + } + + local b = { + {5, 6}, + {7, 8} + } + + local c = { + {1, 1, 1, 1}, + {2, 4, 8, 16}, + {3, 9, 27, 81}, + {4, 16, 64, 256} + } + + local d = { + {4, -3, 4/3, -1/4}, + {-13/3, 19/4, -7/3, 11/24}, + {3/2, -2, 7/6, -1/4}, + {-1/6, 1/4, -1/6, 1/24} + } + + local e = { + {1, 2, 3, 4}, + {5, 6, 7, 8}, + {9, 10, 11, 12}, + {13, 14, 15, 16} + } + + local f = { + {1, 0, 0, 0}, + {0, 1, 0, 0}, + {0, 0, 1, 0}, + {0, 0, 0, 1} + } + + print("Naive matrix multiplication:") + print_matrix(" a * b", matrix_multiply(a, b)) + print_matrix(" c * d", matrix_round(matrix_multiply(c, d), 0)) + print_matrix(" e * f", matrix_multiply(e, f)) + + print("\nStrassen's matrix multiplication:") + print_matrix(" a * b", strassen_multiply(a, b)) + print_matrix(" c * d", matrix_round(strassen_multiply(c, d), 0)) + print_matrix(" e * f", strassen_multiply(e, f)) +end + +-- Run examples +run_examples() diff --git a/Task/Strassens-algorithm/Mathematica/strassens-algorithm.math b/Task/Strassens-algorithm/Mathematica/strassens-algorithm.math new file mode 100644 index 0000000000..448d41e864 --- /dev/null +++ b/Task/Strassens-algorithm/Mathematica/strassens-algorithm.math @@ -0,0 +1,116 @@ +(* ::Package:: *) + +(* --------------------------------------------------------------- *) +(* Strassen matrix multiplication – Mathematica version *) +(* --------------------------------------------------------------- *) + +ClearAll[Strassen] + +Strassen[A_?MatrixQ, B_?MatrixQ] := + Module[{n = Length[A], + a11, a12, a21, a22, + b11, b12, b21, b22, + p1, p2, p3, p4, p5, p6, p7, + c11, c12, c21, c22}, + + (* Base case – 1×1 matrix (scalar) *) + If[n == 1, + Return[{{A[[1, 1]]*B[[1, 1]]}}]; + ]; + + (* ---------------------------------------------------------------- *) + (* 2‑level block‐view of the matrices (same as Julia's @views slicing) *) + (* ---------------------------------------------------------------- *) + a11 = A[[;; n/2, ;; n/2]]; + a12 = A[[;; n/2, n/2 + 1 ;;]]; + a21 = A[[n/2 + 1 ;;, ;; n/2]]; + a22 = A[[n/2 + 1 ;;, n/2 + 1 ;;]]; + + b11 = B[[;; n/2, ;; n/2]]; + b12 = B[[;; n/2, n/2 + 1 ;;]]; + b21 = B[[n/2 + 1 ;;, ;; n/2]]; + b22 = B[[n/2 + 1 ;;, n/2 + 1 ;;]]; + + (* --------------------------------------------------------------- *) + (* 7 recursive Strassen products *) + (* --------------------------------------------------------------- *) + p1 = Strassen[a12 - a22, b21 + b22]; + p2 = Strassen[a11 + a22, b11 + b22]; + p3 = Strassen[a11 - a21, b11 + b12]; + p4 = Strassen[a11 + a12, b22]; + p5 = Strassen[a11, b12 - b22]; + p6 = Strassen[a22, b21 - b11]; + p7 = Strassen[a21 + a22, b11]; + + (* --------------------------------------------------------------- *) + (* Assemble the four quadrants of the result *) + (* --------------------------------------------------------------- *) + c11 = p1 + p2 - p4 + p6; + c12 = p4 + p5; + c21 = p6 + p7; + c22 = p2 - p3 + p5 - p7; + + (* Join the four blocks back together *) + Join[ + Join[c11, c12, 2], + Join[c21, c22, 2], + 1 + ] + ]; + + +(* --------------------------------------------------------------- *) +(* Helper that mimics the Julia `intprint` *) +(* --------------------------------------------------------------- *) +ClearAll[intPrint] + +intPrint[title_String, mat_?MatrixQ] := + Module[{rounded}, + (* round each entry to 8 decimal digits, then coerce to an integer + when the rounded value is (numerically) an integer *) + rounded = Round[mat, 10^-8]; + Print[title, " ", rounded ]; + ] + +(* --------------------------------------------------------------- *) +(* Test data *) +(* --------------------------------------------------------------- *) + +varA = {{1, 2}, {3, 4}}; +varB = {{5, 6}, {7, 8}}; + +varC = {{1, 1, 1, 1}, + {2, 4, 8, 16}, + {3, 9, 27, 81}, + {4, 16, 64, 256}}; + +varD = {{4, -3, 4/3, -1/4}, + {-13/3, 19/4, -7/3, 11/24}, + {3/2, -2, 7/6, -1/4}, + {-1/6, 1/4, -1/6, 1/24}}; + +varE = {{1, 2, 3, 4}, + {5, 6, 7, 8}, + {9, 10, 11, 12}, + {13, 14, 15, 16}}; + +varF = IdentityMatrix[4]; + +r = Sqrt[2]/2; +R = {{r, r}, {-r, r}}; + +(* --------------------------------------------------------------- *) +(* Run the examples – compare ordinary (`.`) and Strassen results *) +(* --------------------------------------------------------------- *) + +intPrint["Regular multiply: ", Transpose[varA].Transpose[varB]]; +intPrint["Strassen multiply: ", Strassen[Transpose[varA], Transpose[varB]]]; + +intPrint["Regular multiply: ", varC . varD]; +intPrint["Strassen multiply: ", Strassen[varC, varD]]; + +intPrint["Regular multiply: ", varE . varF]; +intPrint["Strassen multiply: ", Strassen[varE, varF]]; + +intPrint["Regular multiply: ", R . R]; +intPrint["Strassen multiply: ", Strassen[R, R]]; diff --git a/Task/Strassens-algorithm/OCaml/strassens-algorithm.ml b/Task/Strassens-algorithm/OCaml/strassens-algorithm.ml new file mode 100644 index 0000000000..e818b7b857 --- /dev/null +++ b/Task/Strassens-algorithm/OCaml/strassens-algorithm.ml @@ -0,0 +1,214 @@ +(* Matrix multiplication using Strassen's algorithm in OCaml *) + +type matrix = float array array + +type shape = { + rows : int; + cols : int; +} + +(* Get the shape of a matrix *) +let shape m = + let rows = Array.length m in + let cols = if rows = 0 then 0 else Array.length m.(0) in + { rows; cols } + +(* Create a matrix from a list of lists *) +let matrix_of_lists lists = + Array.of_list (List.map Array.of_list lists) + +(* Convert matrix to list of lists for printing *) +let lists_of_matrix m = + Array.to_list (Array.map Array.to_list m) + +(* Matrix addition *) +let add_matrix a b = + let { rows; cols } = shape a in + let { rows = b_rows; cols = b_cols } = shape b in + assert (rows = b_rows && cols = b_cols); + Array.init rows (fun i -> + Array.init cols (fun j -> a.(i).(j) +. b.(i).(j))) + +(* Matrix subtraction *) +let sub_matrix a b = + let { rows; cols } = shape a in + let { rows = b_rows; cols = b_cols } = shape b in + assert (rows = b_rows && cols = b_cols); + Array.init rows (fun i -> + Array.init cols (fun j -> a.(i).(j) -. b.(i).(j))) + +(* Naive matrix multiplication *) +let dot_product a b = + let a_shape = shape a in + let b_shape = shape b in + assert (a_shape.cols = b_shape.rows); + + Array.init a_shape.rows (fun i -> + Array.init b_shape.cols (fun j -> + let sum = ref 0.0 in + for k = 0 to a_shape.cols - 1 do + sum := !sum +. (a.(i).(k) *. b.(k).(j)) + done; + !sum)) + +(* Extract a submatrix *) +let submatrix m start_row end_row start_col end_col = + Array.init (end_row - start_row) (fun i -> + Array.init (end_col - start_col) (fun j -> + m.(start_row + i).(start_col + j))) + +(* Combine four submatrices into a single matrix *) +let block_matrix c11 c12 c21 c22 = + let p = Array.length c11 in + let result = Array.make_matrix (2 * p) (2 * p) 0.0 in + + (* Copy c11 to top-left *) + for i = 0 to p - 1 do + for j = 0 to p - 1 do + result.(i).(j) <- c11.(i).(j) + done + done; + + (* Copy c12 to top-right *) + for i = 0 to p - 1 do + for j = 0 to p - 1 do + result.(i).(p + j) <- c12.(i).(j) + done + done; + + (* Copy c21 to bottom-left *) + for i = 0 to p - 1 do + for j = 0 to p - 1 do + result.(p + i).(j) <- c21.(i).(j) + done + done; + + (* Copy c22 to bottom-right *) + for i = 0 to p - 1 do + for j = 0 to p - 1 do + result.(p + i).(p + j) <- c22.(i).(j) + done + done; + + result + +(* Check if a number is a power of 2 *) +let is_power_of_2 n = + n > 0 && (n land (n - 1)) = 0 + +(* Strassen's matrix multiplication *) +let rec strassen a b = + let a_shape = shape a in + let b_shape = shape b in + let rows = a_shape.rows in + let cols = a_shape.cols in + + assert (rows = cols); (* matrices must be square *) + assert (a_shape.rows = b_shape.rows && a_shape.cols = b_shape.cols); (* same shape *) + assert (is_power_of_2 rows); (* size must be power of 2 *) + + if rows = 1 then + dot_product a b + else + let p = rows / 2 in + + (* Partition matrix a *) + let a11 = submatrix a 0 p 0 p in + let a12 = submatrix a 0 p p rows in + let a21 = submatrix a p rows 0 p in + let a22 = submatrix a p rows p rows in + + (* Partition matrix b *) + let b11 = submatrix b 0 p 0 p in + let b12 = submatrix b 0 p p rows in + let b21 = submatrix b p rows 0 p in + let b22 = submatrix b p rows p rows in + + (* Compute the 7 products *) + let m1 = strassen (add_matrix a11 a22) (add_matrix b11 b22) in + let m2 = strassen (add_matrix a21 a22) b11 in + let m3 = strassen a11 (sub_matrix b12 b22) in + let m4 = strassen a22 (sub_matrix b21 b11) in + let m5 = strassen (add_matrix a11 a12) b22 in + let m6 = strassen (sub_matrix a21 a11) (add_matrix b11 b12) in + let m7 = strassen (sub_matrix a12 a22) (add_matrix b21 b22) in + + (* Compute the result submatrices *) + let c11 = add_matrix (sub_matrix (add_matrix m1 m4) m5) m7 in + let c12 = add_matrix m3 m5 in + let c21 = add_matrix m2 m4 in + let c22 = add_matrix (sub_matrix (add_matrix m1 m3) m2) m6 in + + block_matrix c11 c12 c21 c22 + +(* Round matrix elements to specified decimal places *) +let round_matrix ?(ndigits=0) m = + let factor = 10.0 ** (float_of_int ndigits) in + Array.map (Array.map (fun x -> + Float.round (x *. factor) /. factor)) m + +(* Pretty print a matrix *) +let print_matrix m = + let lists = lists_of_matrix m in + print_string "["; + List.iteri (fun i row -> + if i > 0 then print_string "; "; + print_string "["; + List.iteri (fun j x -> + if j > 0 then print_string "; "; + Printf.printf "%.6g" x) row; + print_string "]") lists; + print_endline "]" + +(* Example usage *) +let examples () = + let a = matrix_of_lists [ + [1.0; 2.0]; + [3.0; 4.0] + ] in + + let b = matrix_of_lists [ + [5.0; 6.0]; + [7.0; 8.0] + ] in + + let c = matrix_of_lists [ + [1.0; 1.0; 1.0; 1.0]; + [2.0; 4.0; 8.0; 16.0]; + [3.0; 9.0; 27.0; 81.0]; + [4.0; 16.0; 64.0; 256.0] + ] in + + let d = matrix_of_lists [ + [4.0; -3.0; 4.0/.3.0; -1.0/.4.0]; + [-13.0/.3.0; 19.0/.4.0; -7.0/.3.0; 11.0/.24.0]; + [3.0/.2.0; -2.0; 7.0/.6.0; -1.0/.4.0]; + [-1.0/.6.0; 1.0/.4.0; -1.0/.6.0; 1.0/.24.0] + ] in + + let e = matrix_of_lists [ + [1.0; 2.0; 3.0; 4.0]; + [5.0; 6.0; 7.0; 8.0]; + [9.0; 10.0; 11.0; 12.0]; + [13.0; 14.0; 15.0; 16.0] + ] in + + let f = matrix_of_lists [ + [1.0; 0.0; 0.0; 0.0]; + [0.0; 1.0; 0.0; 0.0]; + [0.0; 0.0; 1.0; 0.0]; + [0.0; 0.0; 0.0; 1.0] + ] in + + print_endline "Naive matrix multiplication:"; + print_string " a * b = "; print_matrix (dot_product a b); + print_string " c * d = "; print_matrix (round_matrix (dot_product c d)); + print_string " e * f = "; print_matrix (dot_product e f); + + print_endline "\nStrassen's matrix multiplication:"; + print_string " a * b = "; print_matrix (strassen a b); + print_string " c * d = "; print_matrix (round_matrix (strassen c d)); + print_string " e * f = "; print_matrix (strassen e f) + +(* Run examples when executed *) +let () = examples () diff --git a/Task/Strassens-algorithm/Perl/strassens-algorithm.pl b/Task/Strassens-algorithm/Perl/strassens-algorithm.pl new file mode 100644 index 0000000000..9b96cf4bb8 --- /dev/null +++ b/Task/Strassens-algorithm/Perl/strassens-algorithm.pl @@ -0,0 +1,256 @@ +#!/usr/bin/perl +use strict; +use warnings; +use List::Util qw(sum); + +# Matrix class implemented as array reference +package Matrix; + +# Constructor +sub new { + my ($class, $data) = @_; + my $self = defined $data ? $data : []; + bless $self, $class; + return $self; +} + +# Create matrix from nested blocks +sub block { + my ($class, $blocks) = @_; + my @result; + + # Get dimensions + my $num_rows = 0; + for my $hblock (@$blocks) { + $num_rows += @{$hblock->[0]}; + } + + # Process each horizontal block + my $row_offset = 0; + for my $hblock (@$blocks) { + my $block_height = @{$hblock->[0]}; + # Zip and concatenate rows + for my $i (0..$block_height-1) { + my @new_row; + for my $matrix (@$hblock) { + push @new_row, @{$matrix->[$i]}; + } + $result[$row_offset + $i] = \@new_row; + } + $row_offset += $block_height; + } + + return Matrix->new(\@result); +} + +# Matrix multiplication (naive) +sub dot { + my ($self, $b) = @_; + my ($rows_a, $cols_a) = $self->shape(); + my ($rows_b, $cols_b) = $b->shape(); + + die "Matrix dimensions don't match for multiplication" unless $cols_a == $rows_b; + + my @result; + for my $i (0..$rows_a-1) { + my @row; + for my $j (0..$cols_b-1) { + my $sum = 0; + for my $k (0..$cols_a-1) { + $sum += $self->[$i][$k] * $b->[$k][$j]; + } + push @row, $sum; + } + push @result, \@row; + } + + return Matrix->new(\@result); +} + +# Overload multiplication operator +use overload '*' => \˙ + +# Matrix addition +sub add { + my ($self, $b) = @_; + my ($rows, $cols) = $self->shape(); + my ($b_rows, $b_cols) = $b->shape(); + + die "Matrix dimensions don't match for addition" unless $rows == $b_rows && $cols == $b_cols; + + my @result; + for my $i (0..$rows-1) { + my @row; + for my $j (0..$cols-1) { + push @row, $self->[$i][$j] + $b->[$i][$j]; + } + push @result, \@row; + } + + return Matrix->new(\@result); +} + +# Matrix subtraction +sub subtract { + my ($self, $b) = @_; + my ($rows, $cols) = $self->shape(); + my ($b_rows, $b_cols) = $b->shape(); + + die "Matrix dimensions don't match for subtraction" unless $rows == $b_rows && $cols == $b_cols; + + my @result; + for my $i (0..$rows-1) { + my @row; + for my $j (0..$cols-1) { + push @row, $self->[$i][$j] - $b->[$i][$j]; + } + push @result, \@row; + } + + return Matrix->new(\@result); +} + +# Overload operators +use overload '+' => \&add; +use overload '-' => \&subtract; + +# Strassen's algorithm +sub strassen { + my ($self, $b) = @_; + my ($rows, $cols) = $self->shape(); + my ($b_rows, $b_cols) = $b->shape(); + + die "Matrices must be square" unless $rows == $cols && $b_rows == $b_cols; + die "Matrices must be the same shape" unless $rows == $b_rows; + die "Shape must be a power of 2" unless $rows > 0 && ($rows & ($rows - 1)) == 0; + + if ($rows == 1) { + return $self->dot($b); + } + + my $p = $rows / 2; + + # Partition matrices + my $a11 = Matrix->new([map { [ @{$self->[$_]}[0..$p-1] ] } 0..$p-1]); + my $a12 = Matrix->new([map { [ @{$self->[$_]}[$p..$rows-1] ] } 0..$p-1]); + my $a21 = Matrix->new([map { [ @{$self->[$_]}[0..$p-1] ] } $p..$rows-1]); + my $a22 = Matrix->new([map { [ @{$self->[$_]}[$p..$rows-1] ] } $p..$rows-1]); + + my $b11 = Matrix->new([map { [ @{$b->[$_]}[0..$p-1] ] } 0..$p-1]); + my $b12 = Matrix->new([map { [ @{$b->[$_]}[$p..$b_cols-1] ] } 0..$p-1]); + my $b21 = Matrix->new([map { [ @{$b->[$_]}[0..$p-1] ] } $p..$b_rows-1]); + my $b22 = Matrix->new([map { [ @{$b->[$_]}[$p..$b_cols-1] ] } $p..$b_rows-1]); + + # Calculate M1..M7 + my $m1 = ($a11 + $a22)->strassen($b11 + $b22); + my $m2 = ($a21 + $a22)->strassen($b11); + my $m3 = $a11->strassen($b12 - $b22); + my $m4 = $a22->strassen($b21 - $b11); + my $m5 = ($a11 + $a12)->strassen($b22); + my $m6 = ($a21 - $a11)->strassen($b11 + $b12); + my $m7 = ($a12 - $a22)->strassen($b21 + $b22); + + # Calculate C11..C22 + my $c11 = $m1 + $m4 - $m5 + $m7; + my $c12 = $m3 + $m5; + my $c21 = $m2 + $m4; + my $c22 = $m1 - $m2 + $m3 + $m6; + + return Matrix->block([[$c11, $c12], [$c21, $c22]]); +} + +# Round elements +sub round_matrix { + my ($self, $ndigits) = @_; + $ndigits = undef unless defined $ndigits; + + my @result; + for my $i (0..$#{$self}) { + my @row; + for my $j (0..$#{$self->[$i]}) { + my $val = $self->[$i][$j]; + if (defined $ndigits) { + push @row, sprintf("%.${ndigits}f", $val); + } else { + push @row, int($val + ($val >= 0 ? 0.5 : -0.5)); + } + } + push @result, \@row; + } + + return Matrix->new(\@result); +} + +# Get matrix shape +sub shape { + my ($self) = @_; + return (0, 0) unless @$self; + return (scalar @$self, scalar @{$self->[0]}); +} + +# String representation +sub stringify { + my ($self) = @_; + my @rows; + for my $row (@$self) { + push @rows, '[' . join(', ', @$row) . ']'; + } + return '[' . join(', ', @rows) . ']'; +} + +use overload '""' => \&stringify; + +# Examples +package main; + +sub examples { + my $a = Matrix->new([ + [1, 2], + [3, 4] + ]); + + my $b = Matrix->new([ + [5, 6], + [7, 8] + ]); + + my $c = Matrix->new([ + [1, 1, 1, 1], + [2, 4, 8, 16], + [3, 9, 27, 81], + [4, 16, 64, 256] + ]); + + my $d = Matrix->new([ + [4, -3, 4/3, -1/4], + [-13/3, 19/4, -7/3, 11/24], + [3/2, -2, 7/6, -1/4], + [-1/6, 1/4, -1/6, 1/24] + ]); + + my $e = Matrix->new([ + [1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12], + [13, 14, 15, 16] + ]); + + my $f = Matrix->new([ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, 0], + [0, 0, 0, 1] + ]); + + print "Naive matrix multiplication:\n"; + print " a * b = " . ($a * $b) . "\n"; + print " c * d = " . $c->round_matrix(0) . "\n"; + print " e * f = " . ($e * $f) . "\n"; + + print "Strassen's matrix multiplication:\n"; + print " a * b = " . $a->strassen($b) . "\n"; + print " c * d = " . $c->strassen($d)->round_matrix(0) . "\n"; + print " e * f = " . $e->strassen($f) . "\n"; +} + +examples() if __FILE__ eq $0; diff --git a/Task/Strassens-algorithm/Pluto/strassens-algorithm.pluto b/Task/Strassens-algorithm/Pluto/strassens-algorithm.pluto new file mode 100644 index 0000000000..d7156e6c1f --- /dev/null +++ b/Task/Strassens-algorithm/Pluto/strassens-algorithm.pluto @@ -0,0 +1,70 @@ +require "matrix" +require "table2" +local fmt = require "fmt" + +local function strassen(a, b) + assert(a:issquare() and a:samesize(b), "matrices must be square and of equal size") + local n = a:numrows() + assert(n & (n - 1) == 0, "size of matrices must be a power of two") + if n == 1 then return a:matmul(b) end + local h = n // 2 + + local a11 = a:submatrix(1, h, 1, h) + local a12 = a:submatrix(1, h, h + 1, n) + local a21 = a:submatrix(h + 1, n, 1, h) + local a22 = a:submatrix(h + 1, n, h + 1, n) + + local b11 = b:submatrix(1, h, 1, h) + local b12 = b:submatrix(1, h, h + 1, n) + local b21 = b:submatrix(h + 1, n, 1, h) + local b22 = b:submatrix(h + 1, n, h + 1, n) + + local m1 = strassen(a11 + a22, b11 + b22) + local m2 = strassen(a21 + a22, b11 ) + local m3 = strassen(a11, b12 - b22) + local m4 = strassen(a22, b21 - b11) + local m5 = strassen(a11 + a12, b22 ) + local m6 = strassen(a21 - a11, b11 + b12) + local m7 = strassen(a12 - a22, b21 + b22) + + local c11 = m1 + m4 - m5 + m7 + local c12 = m3 + m5 + local c21 = m2 + m4 + local c22 = m1 - m2 + m3 + m6 + + local c = {} + for i = 1, n do c[i] = table.rep(n, 0) end + for i = 1, h do + for j = 1, h do + c[i][j] = c11:get(i, j) + c[i][j + h] = c12:get(i, j) + c[i + h][j] = c21:get(i, j) + c[i + h][j + h] = c22:get(i, j) + end + end + return matrix.from(c) +end + +-- Round numbers which differ from an integer by less than 'tol' to that integer. +local function round(n, tol = 1e-12) + if math.abs(n - math.round(n)) < tol then return math.round(n) end + return n +end + +local a = matrix.from({ {1, 2}, {3, 4} }) +local b = matrix.from({ {5, 6}, {7, 8} }) +local c = matrix.from({ {1, 1, 1, 1}, {2, 4, 8, 16}, {3, 9, 27, 81}, {4, 16, 64, 256} }) +local d = matrix.from({ {4, -3, 4/3, -1/4}, {-13/3, 19/4, -7/3, 11/24}, + {3/2, -2, 7/6, -1/4}, {-1/6, 1/4, -1/6, 1/24} }) +local e = matrix.from({ {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16} }) +local f = matrix.from({ {1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1} }) + +print("Using 'normal' matrix multiplication:") +fmt.print(" a x b = %s", fmt.swrite(a:matmul(b):toarray())) +fmt.print(" c x d = %s", fmt.swrite(c:matmul(d):map(round):toarray())) +fmt.print(" e x f = %s", fmt.swrite(e:matmul(f):toarray())) + +print("\nUsing 'Strassen' matrix multiplication:") +fmt.print(" a x b = %s", fmt.swrite(strassen(a, b):toarray())) +fmt.print(" c x d = %s", fmt.swrite(strassen(c, d):map(round):toarray())) +fmt.print(" e x f = %s", fmt.swrite(strassen(e, f):toarray())) diff --git a/Task/Strassens-algorithm/PowerShell/strassens-algorithm.ps1 b/Task/Strassens-algorithm/PowerShell/strassens-algorithm.ps1 new file mode 100644 index 0000000000..12d397321b --- /dev/null +++ b/Task/Strassens-algorithm/PowerShell/strassens-algorithm.ps1 @@ -0,0 +1,288 @@ +# Matrix class implemented as array reference +class Matrix { + [object[]]$data + + # Constructor + Matrix([object[]]$data) { + $this.data = $data + } + + # Create matrix from nested blocks + static [Matrix] Block([Matrix[][]]$blocks) { + $result = @() + + # Get dimensions + $num_rows = 0 + foreach ($hblock in $blocks) { + $num_rows += $hblock[0].data.Count + } + + # Process each horizontal block + $row_offset = 0 + foreach ($hblock in $blocks) { + $block_height = $hblock[0].data.Count + # Zip and concatenate rows + for ($i = 0; $i -lt $block_height; $i++) { + $new_row = @() + foreach ($matrix in $hblock) { + $new_row += $matrix.data[$i] + } + if ($row_offset + $i -ge $result.Count) { + $result += , @() + } + $result[$row_offset + $i] = $new_row + } + $row_offset += $block_height + } + + return [Matrix]::new($result) + } + + # Matrix multiplication (naive) + [Matrix] Dot([Matrix]$b) { + $rows_a = $this.data.Count + $cols_a = if ($rows_a -gt 0) { $this.data[0].Count } else { 0 } + $rows_b = $b.data.Count + $cols_b = if ($rows_b -gt 0) { $b.data[0].Count } else { 0 } + + if ($cols_a -ne $rows_b) { + throw "Matrix dimensions don't match for multiplication" + } + + $result = @() + for ($i = 0; $i -lt $rows_a; $i++) { + $row = @() + for ($j = 0; $j -lt $cols_b; $j++) { + $sum = 0 + for ($k = 0; $k -lt $cols_a; $k++) { + $sum += $this.data[$i][$k] * $b.data[$k][$j] + } + $row += $sum + } + $result += , $row + } + + return [Matrix]::new($result) + } + + # Matrix addition + [Matrix] Add([Matrix]$b) { + $rows = $this.data.Count + $cols = if ($rows -gt 0) { $this.data[0].Count } else { 0 } + $b_rows = $b.data.Count + $b_cols = if ($b_rows -gt 0) { $b.data[0].Count } else { 0 } + + if ($rows -ne $b_rows -or $cols -ne $b_cols) { + throw "Matrix dimensions don't match for addition" + } + + $result = @() + for ($i = 0; $i -lt $rows; $i++) { + $row = @() + for ($j = 0; $j -lt $cols; $j++) { + $row += $this.data[$i][$j] + $b.data[$i][$j] + } + $result += , $row + } + + return [Matrix]::new($result) + } + + # Matrix subtraction + [Matrix] Subtract([Matrix]$b) { + $rows = $this.data.Count + $cols = if ($rows -gt 0) { $this.data[0].Count } else { 0 } + $b_rows = $b.data.Count + $b_cols = if ($b_rows -gt 0) { $b.data[0].Count } else { 0 } + + if ($rows -ne $b_rows -or $cols -ne $b_cols) { + throw "Matrix dimensions don't match for subtraction" + } + + $result = @() + for ($i = 0; $i -lt $rows; $i++) { + $row = @() + for ($j = 0; $j -lt $cols; $j++) { + $row += $this.data[$i][$j] - $b.data[$i][$j] + } + $result += , $row + } + + return [Matrix]::new($result) + } + + # Strassen's algorithm + [Matrix] Strassen([Matrix]$b) { + $rows = $this.data.Count + $cols = if ($rows -gt 0) { $this.data[0].Count } else { 0 } + $b_rows = $b.data.Count + $b_cols = if ($b_rows -gt 0) { $b.data[0].Count } else { 0 } + + if ($rows -ne $cols -or $b_rows -ne $b_cols) { + throw "Matrices must be square" + } + if ($rows -ne $b_rows) { + throw "Matrices must be the same shape" + } + if ($rows -le 0 -or ($rows -band ($rows - 1)) -ne 0) { + throw "Shape must be a power of 2" + } + + if ($rows -eq 1) { + return $this.Dot($b) + } + + $p = [Math]::Floor($rows / 2) + + # Partition matrices + $a11_data = @() + $a12_data = @() + $a21_data = @() + $a22_data = @() + for ($i = 0; $i -lt $p; $i++) { + $a11_data += , @($this.data[$i][0..($p-1)]) + $a12_data += , @($this.data[$i][$p..($rows-1)]) + } + for ($i = $p; $i -lt $rows; $i++) { + $a21_data += , @($this.data[$i][0..($p-1)]) + $a22_data += , @($this.data[$i][$p..($rows-1)]) + } + + $b11_data = @() + $b12_data = @() + $b21_data = @() + $b22_data = @() + for ($i = 0; $i -lt $p; $i++) { + $b11_data += , @($b.data[$i][0..($p-1)]) + $b12_data += , @($b.data[$i][$p..($b_cols-1)]) + } + for ($i = $p; $i -lt $b_rows; $i++) { + $b21_data += , @($b.data[$i][0..($p-1)]) + $b22_data += , @($b.data[$i][$p..($b_rows-1)]) + } + + $a11 = [Matrix]::new($a11_data) + $a12 = [Matrix]::new($a12_data) + $a21 = [Matrix]::new($a21_data) + $a22 = [Matrix]::new($a22_data) + $b11 = [Matrix]::new($b11_data) + $b12 = [Matrix]::new($b12_data) + $b21 = [Matrix]::new($b21_data) + $b22 = [Matrix]::new($b22_data) + + # Calculate M1..M7 + $m1 = ($a11.Add($a22)).Strassen($b11.Add($b22)) + $m2 = ($a21.Add($a22)).Strassen($b11) + $m3 = $a11.Strassen($b12.Subtract($b22)) + $m4 = $a22.Strassen($b21.Subtract($b11)) + $m5 = ($a11.Add($a12)).Strassen($b22) + $m6 = ($a21.Subtract($a11)).Strassen($b11.Add($b12)) + $m7 = ($a12.Subtract($a22)).Strassen($b21.Add($b22)) + + # Calculate C11..C22 + $c11 = $m1.Add($m4).Subtract($m5).Add($m7) + $c12 = $m3.Add($m5) + $c21 = $m2.Add($m4) + $c22 = $m1.Subtract($m2).Add($m3).Add($m6) + + return [Matrix]::Block(@(@($c11, $c12), @($c21, $c22))) + } + + # Round elements + [Matrix] RoundMatrix([int]$ndigits) { + $result = @() + for ($i = 0; $i -lt $this.data.Count; $i++) { + $row = @() + for ($j = 0; $j -lt $this.data[$i].Count; $j++) { + $val = $this.data[$i][$j] + if ($ndigits -ne $null) { + $rounded = [Math]::Round($val, $ndigits) + $row += $rounded + } else { + $rounded = [Math]::Round($val) + $row += $rounded + } + } + $result += , $row + } + + return [Matrix]::new($result) + } + + [Matrix] RoundMatrix() { + return $this.RoundMatrix($null) + } + + # Get matrix shape + [object[]] Shape() { + if ($this.data.Count -eq 0) { + return @(0, 0) + } + return @($this.data.Count, $this.data[0].Count) + } + + # String representation + [string] ToString() { + $rows = @() + foreach ($row in $this.data) { + $rows += "[" + ($row -join ", ") + "]" + } + return "[" + ($rows -join ", ") + "]" + } +} + +# Operator overloading for PowerShell (using methods instead) +function Multiply-Matrix([Matrix]$a, [Matrix]$b) { + return $a.Dot($b) +} + +function Add-Matrix([Matrix]$a, [Matrix]$b) { + return $a.Add($b) +} + +function Subtract-Matrix([Matrix]$a, [Matrix]$b) { + return $a.Subtract($b) +} + +# Examples +function Examples() { + $a = [Matrix]::new(@(@(1, 2), @(3, 4))) + $b = [Matrix]::new(@(@(5, 6), @(7, 8))) + $c = [Matrix]::new(@( + @(1, 1, 1, 1), + @(2, 4, 8, 16), + @(3, 9, 27, 81), + @(4, 16, 64, 256) + )) + $d = [Matrix]::new(@( + @(4, -3, (4/3), (-1/4)), + @((-13/3), (19/4), (-7/3), (11/24)), + @((3/2), -2, (7/6), (-1/4)), + @((-1/6), (1/4), (-1/6), (1/24)) + )) + $e = [Matrix]::new(@( + @(1, 2, 3, 4), + @(5, 6, 7, 8), + @(9, 10, 11, 12), + @(13, 14, 15, 16) + )) + $f = [Matrix]::new(@( + @(1, 0, 0, 0), + @(0, 1, 0, 0), + @(0, 0, 1, 0), + @(0, 0, 0, 1) + )) + + Write-Host "Naive matrix multiplication:" + Write-Host " a * b = $($a.Dot($b))" + Write-Host " c * d = $($c.Dot($d).RoundMatrix(0))" + Write-Host " e * f = $($e.Dot($f))" + + Write-Host "Strassen's matrix multiplication:" + Write-Host " a * b = $($a.Strassen($b))" + Write-Host " c * d = $($c.Strassen($d).RoundMatrix(0))" + Write-Host " e * f = $($e.Strassen($f))" +} + +# Run examples if script is executed directly +Examples diff --git a/Task/Strassens-algorithm/Python/strassens-algorithm.py b/Task/Strassens-algorithm/Python/strassens-algorithm.py index d0f5aaf97a..1455f1c373 100644 --- a/Task/Strassens-algorithm/Python/strassens-algorithm.py +++ b/Task/Strassens-algorithm/Python/strassens-algorithm.py @@ -1,19 +1,65 @@ -"""Matrix multiplication using Strassen's algorithm. Requires Python >= 3.7.""" +"""Matrix multiplication using Strassen's algorithm. Requires Python >= 3.10.""" from __future__ import annotations + +from collections.abc import MutableSequence from itertools import chain -from typing import List +from typing import Iterable +from typing import Iterator from typing import NamedTuple -from typing import Optional +from typing import TypeAlias +from typing import cast +from typing import overload + +N: TypeAlias = int | float +Row: TypeAlias = list[N] -class Shape(NamedTuple): - rows: int - cols: int +class Matrix(MutableSequence[Row]): + def __init__(self, data: Iterable[Iterable[N]] | None = None) -> None: + if data is None: + self._data: list[Row] = [] + else: + self._data = [list(row) for row in data] + @overload + def __getitem__(self, index: int) -> Row: ... + @overload + def __getitem__(self, index: slice) -> Matrix: ... -class Matrix(List): - """A matrix implemented as a two-dimensional list.""" + def __getitem__(self, index: int | slice) -> Row | Matrix: + if isinstance(index, slice): + return Matrix(self._data[index]) + return self._data[index] + + @overload + def __setitem__(self, index: int, value: Row) -> None: ... + @overload + def __setitem__(self, index: slice, value: Iterable[Row]) -> None: ... + + def __setitem__(self, index: int | slice, value: Row | Iterable[Row]) -> None: + if isinstance(index, slice): + rows = [list(row) for row in cast(Iterable[Row], value)] + self._data[index] = rows + else: + if not isinstance(value, list): + raise TypeError("single row assignment requires a list of int or float") + self._data[index] = value + + def __delitem__(self, index: int | slice) -> None: + del self._data[index] + + def __len__(self) -> int: + return len(self._data) + + def insert(self, index: int, value: Row) -> None: + self._data.insert(index, value) + + def __iter__(self) -> Iterator[Row]: + return iter(self._data) + + def __repr__(self) -> str: + return f"Matrix({self._data!r})" @classmethod def block(cls, blocks) -> Matrix: @@ -27,7 +73,9 @@ class Matrix(List): def dot(self, b: Matrix) -> Matrix: """Return a new Matrix that is the product of this matrix and matrix `b`. - Uses 'simple' or 'naive' matrix multiplication.""" + + Uses 'simple' or 'naive' matrix multiplication. + """ assert self.shape.cols == b.shape.rows m = Matrix() for row in self: @@ -59,7 +107,9 @@ class Matrix(List): def strassen(self, b: Matrix) -> Matrix: """Return a new Matrix that is the product of this matrix and matrix `b`. - Uses strassen algorithm.""" + + Uses strassen's algorithm. + """ rows, cols = self.shape assert rows == cols, "matrices must be square" @@ -96,7 +146,7 @@ class Matrix(List): return Matrix.block([[c11, c12], [c21, c22]]) - def round(self, ndigits: Optional[int] = None) -> Matrix: + def round(self, ndigits: int | None = None) -> Matrix: return Matrix([[round(i, ndigits) for i in row] for row in self]) @property @@ -105,6 +155,11 @@ class Matrix(List): return Shape(len(self), cols) +class Shape(NamedTuple): + rows: int + cols: int + + def examples(): a = Matrix( [ diff --git a/Task/Strassens-algorithm/R/strassens-algorithm.r b/Task/Strassens-algorithm/R/strassens-algorithm.r new file mode 100644 index 0000000000..c02e64c39b --- /dev/null +++ b/Task/Strassens-algorithm/R/strassens-algorithm.r @@ -0,0 +1,179 @@ +# --------------------------------------------------------------- +# Strassen matrix multiplication – R version (Corrected) +# --------------------------------------------------------------- + +# Helper function to pad matrix to next power of 2 +pad_to_power_of_2 <- function(mat) { + n <- nrow(mat) + m <- ncol(mat) + max_dim <- max(n, m) + new_dim <- 2^ceiling(log2(max_dim)) + + if (new_dim == n && new_dim == m) { + return(mat) + } + + padded <- matrix(0, nrow = new_dim, ncol = new_dim) + padded[1:n, 1:m] <- mat + return(padded) +} + +# Helper to split a matrix into quadrants +split_matrix <- function(X) { + n <- nrow(X) + mid <- n %/% 2 + + list( + X11 = X[1:mid, 1:mid, drop = FALSE], + X12 = X[1:mid, (mid + 1):n, drop = FALSE], + X21 = X[(mid + 1):n, 1:mid, drop = FALSE], + X22 = X[(mid + 1):n, (mid + 1):n, drop = FALSE] + ) +} + +# Join four submatrices into one matrix +join_matrices <- function(C11, C12, C21, C22) { + top <- cbind(C11, C12) + bottom <- cbind(C21, C22) + rbind(top, bottom) +} + +# Strassen Matrix Multiplication +strassen <- function(A, B) { + # Check if matrices are conformable for multiplication + if (ncol(A) != nrow(B)) { + stop("Matrices cannot be multiplied: incompatible dimensions") + } + + # Pad matrices to make them square and powers of 2 + orig_rows <- nrow(A) + orig_cols <- ncol(B) + + max_dim <- max(nrow(A), ncol(A), nrow(B), ncol(B)) + padded_dim <- 2^ceiling(log2(max_dim)) + + if (nrow(A) != padded_dim || ncol(A) != padded_dim) { + A_padded <- matrix(0, nrow = padded_dim, ncol = padded_dim) + A_padded[1:nrow(A), 1:ncol(A)] <- A + A <- A_padded + } + + if (nrow(B) != padded_dim || ncol(B) != padded_dim) { + B_padded <- matrix(0, nrow = padded_dim, ncol = padded_dim) + B_padded[1:nrow(B), 1:ncol(B)] <- B + B <- B_padded + } + + # Recursive helper function + strassen_recursive <- function(X, Y) { + n <- nrow(X) + + # Base case: 1x1 matrix + if (n == 1) { + return(matrix(X[1, 1] * Y[1, 1], nrow = 1, ncol = 1)) + } + + # Split matrices into quadrants + X_parts <- split_matrix(X) + Y_parts <- split_matrix(Y) + + x11 <- X_parts$X11 + x12 <- X_parts$X12 + x21 <- X_parts$X21 + x22 <- X_parts$X22 + + y11 <- Y_parts$X11 + y12 <- Y_parts$X12 + y21 <- Y_parts$X21 + y22 <- Y_parts$X22 + + # Compute the seven products recursively + p1 <- strassen_recursive(x12 - x22, y21 + y22) + p2 <- strassen_recursive(x11 + x22, y11 + y22) + p3 <- strassen_recursive(x11 - x21, y11 + y12) + p4 <- strassen_recursive(x11 + x12, y22) + p5 <- strassen_recursive(x11, y12 - y22) + p6 <- strassen_recursive(x22, y21 - y11) + p7 <- strassen_recursive(x21 + x22, y11) + + # Combine results into quadrants + c11 <- p1 + p2 - p4 + p6 + c12 <- p4 + p5 + c21 <- p6 + p7 + c22 <- p2 - p3 + p5 - p7 + + # Join and return final matrix + join_matrices(c11, c12, c21, c22) + } + + # Perform Strassen multiplication + result_padded <- strassen_recursive(A, B) + + # Extract the relevant portion + result <- result_padded[1:orig_rows, 1:orig_cols, drop = FALSE] + + return(result) +} + +# --------------------------------------------------------------- +# Helper that mimics the Julia `intprint` +# --------------------------------------------------------------- +int_print <- function(title, mat) { + # Round to 8 decimal places and convert near-integers to integers + rounded_mat <- round(mat, digits = 8) + cat(title, "\n") + print(rounded_mat) + cat("\n") +} + +# --------------------------------------------------------------- +# Test data +# --------------------------------------------------------------- +varA <- matrix(c(1, 2, 3, 4), nrow = 2, byrow = TRUE) +varB <- matrix(c(5, 6, 7, 8), nrow = 2, byrow = TRUE) + +varC <- matrix(c( + 1, 1, 1, 1, + 2, 4, 8, 16, + 3, 9, 27, 81, + 4, 16, 64, 256 +), nrow = 4, byrow = TRUE) + +varD <- matrix(c( + 4, -3, 4/3, -1/4, + -13/3, 19/4, -7/3, 11/24, + 3/2, -2, 7/6, -1/4, + -1/6, 1/4, -1/6, 1/24 +), nrow = 4, byrow = TRUE) + +varE <- matrix(c( + 1, 2, 3, 4, + 5, 6, 7, 8, + 9, 10, 11, 12, + 13, 14, 15, 16 +), nrow = 4, byrow = TRUE) + +varF <- diag(4) + +r <- sqrt(2)/2 +R <- matrix(c(r, r, -r, r), nrow = 2, byrow = TRUE) + +# --------------------------------------------------------------- +# Run the examples – compare ordinary (%*%) and Strassen results +# --------------------------------------------------------------- + +# Example 1 +int_print("Regular multiply:", t(varA) %*% t(varB)) +int_print("Strassen multiply:", strassen(t(varA), t(varB))) + +# Example 2 +int_print("Regular multiply:", varC %*% varD) +int_print("Strassen multiply:", strassen(varC, varD)) + +# Example 3 +int_print("Regular multiply:", varE %*% varF) +int_print("Strassen multiply:", strassen(varE, varF)) + +# Example 4 +int_print("Regular multiply:", R %*% R) +int_print("Strassen multiply:", strassen(R, R)) diff --git a/Task/Strassens-algorithm/Racket/strassens-algorithm.rkt b/Task/Strassens-algorithm/Racket/strassens-algorithm.rkt new file mode 100644 index 0000000000..759d301d40 --- /dev/null +++ b/Task/Strassens-algorithm/Racket/strassens-algorithm.rkt @@ -0,0 +1,220 @@ +#lang racket + +(require racket/format) + +; Matrix structure +(struct matrix (data rows cols) #:transparent) + +; Constructor +(define (new-matrix data) + (let ([rows (length data)] + [cols (if (null? data) 0 (length (car data)))]) + (matrix data rows cols))) + +; Getters +(define (get-rows m) (matrix-rows m)) +(define (get-cols m) (matrix-cols m)) + +; Validation functions +(define (validate-dimensions m1 m2) + (unless (and (= (get-rows m1) (get-rows m2)) + (= (get-cols m1) (get-cols m2))) + (error "Matrices must have the same dimensions."))) + +(define (validate-multiplication m1 m2) + (unless (= (get-cols m1) (get-rows m2)) + (error "Cannot multiply these matrices."))) + +(define (validate-square-power-of-two m) + (let ([rows (get-rows m)] + [cols (get-cols m)]) + (unless (= rows cols) + (error "Matrix must be square.")) + (when (or (= rows 0) (not (= (bitwise-and rows (- rows 1)) 0))) + (error "Size of matrix must be a power of two.")))) + +; Helper functions for matrix operations +(define (add-elements row1 row2) + (map + row1 row2)) + +(define (subtract-elements row1 row2) + (map - row1 row2)) + +(define (add-rows data1 data2) + (map add-elements data1 data2)) + +(define (subtract-rows data1 data2) + (map subtract-elements data1 data2)) + +; Matrix operations +(define (matrix-add m1 m2) + (validate-dimensions m1 m2) + (let ([data1 (matrix-data m1)] + [data2 (matrix-data m2)]) + (new-matrix (add-rows data1 data2)))) + +(define (matrix-subtract m1 m2) + (validate-dimensions m1 m2) + (let ([data1 (matrix-data m1)] + [data2 (matrix-data m2)]) + (new-matrix (subtract-rows data1 data2)))) + +; Get column from matrix data +(define (get-column data col-index) + (map (lambda (row) (list-ref row col-index)) data)) + +; Dot product of two lists +(define (dot-product list1 list2) + (apply + (map * list1 list2))) + +; Multiply a row with entire matrix +(define (multiply-row-with-matrix row data2 cols2) + (map (lambda (j) (dot-product row (get-column data2 j))) + (range cols2))) + +; Multiply rows +(define (multiply-rows data1 data2 cols2) + (map (lambda (row) (multiply-row-with-matrix row data2 cols2)) + data1)) + +(define (matrix-multiply m1 m2) + (validate-multiplication m1 m2) + (let ([data1 (matrix-data m1)] + [data2 (matrix-data m2)] + [cols2 (get-cols m2)]) + (new-matrix (multiply-rows data1 data2 cols2)))) + +; String formatting functions +(define (format-element e) + (~a e)) + +(define (format-row row) + (string-append "[" (string-join (map format-element row) ", ") "]")) + +(define (matrix-to-string m) + (let ([data (matrix-data m)]) + (string-append (string-join (map format-row data) "\n") "\n"))) + +(define (format-element-with-precision e precision) + (let* ([pow (expt 10.0 precision)] + [rounded (/ (round (* e pow)) pow)] + [formatted (~r rounded #:precision precision)] + [zero-check (if (= precision 0) + "0" + (string-append "0." (make-string precision #\0)))]) + ; Handle negative zero + (if (and (string-prefix? formatted "-") + (string=? (substring formatted 1) zero-check)) + zero-check + formatted))) + +(define (format-row-with-precision row precision) + (string-append "[" + (string-join (map (lambda (e) (format-element-with-precision e precision)) row) ", ") + "]")) + +(define (matrix-to-string-with-precision m precision) + (let ([data (matrix-data m)]) + (string-append (string-join (map (lambda (row) (format-row-with-precision row precision)) data) "\n") "\n"))) + +; Strassen multiplication helper functions +(define (to-quarters m) + (let* ([rows (get-rows m)] + [r (quotient rows 2)] + [data (matrix-data m)] + [top-half (take data r)] + [bottom-half (drop data r)]) + (list + ; Q0: top-left + (new-matrix (map (lambda (row) (take row r)) top-half)) + ; Q1: top-right + (new-matrix (map (lambda (row) (drop row r)) top-half)) + ; Q2: bottom-left + (new-matrix (map (lambda (row) (take row r)) bottom-half)) + ; Q3: bottom-right + (new-matrix (map (lambda (row) (drop row r)) bottom-half))))) + +(define (from-quarters quarters) + (let ([q0 (first quarters)] + [q1 (second quarters)] + [q2 (third quarters)] + [q3 (fourth quarters)]) + (let ([q0-data (matrix-data q0)] + [q1-data (matrix-data q1)] + [q2-data (matrix-data q2)] + [q3-data (matrix-data q3)]) + (let ([top-half (map append q0-data q1-data)] + [bottom-half (map append q2-data q3-data)]) + (new-matrix (append top-half bottom-half)))))) + +(define (strassen-impl m1 m2) + (if (= (get-rows m1) 1) + (matrix-multiply m1 m2) + (let ([quarters-a (to-quarters m1)] + [quarters-b (to-quarters m2)]) + (let ([a11 (first quarters-a)] + [a12 (second quarters-a)] + [a21 (third quarters-a)] + [a22 (fourth quarters-a)] + [b11 (first quarters-b)] + [b12 (second quarters-b)] + [b21 (third quarters-b)] + [b22 (fourth quarters-b)]) + ; Calculate the 7 products according to Strassen's algorithm + (let ([p1 (strassen-impl a11 (matrix-subtract b12 b22))] + [p2 (strassen-impl (matrix-add a11 a12) b22)] + [p3 (strassen-impl (matrix-add a21 a22) b11)] + [p4 (strassen-impl a22 (matrix-subtract b21 b11))] + [p5 (strassen-impl (matrix-add a11 a22) (matrix-add b11 b22))] + [p6 (strassen-impl (matrix-subtract a12 a22) (matrix-add b21 b22))] + [p7 (strassen-impl (matrix-subtract a11 a21) (matrix-add b11 b12))]) + ; Calculate result quarters + (let ([c11 (matrix-add (matrix-subtract (matrix-add p5 p4) p2) p6)] + [c12 (matrix-add p1 p2)] + [c21 (matrix-add p3 p4)] + [c22 (matrix-subtract (matrix-subtract (matrix-add p5 p1) p3) p7)]) + (from-quarters (list c11 c12 c21 c22)))))))) + +(define (matrix-strassen m1 m2) + (validate-square-power-of-two m1) + (validate-square-power-of-two m2) + (unless (and (= (get-rows m1) (get-rows m2)) + (= (get-cols m1) (get-cols m2))) + (error "Matrices must be square and of equal size for Strassen multiplication.")) + (strassen-impl m1 m2)) + +; Main function for testing +(define (main) + (let* ([a-data '((1.0 2.0) (3.0 4.0))] + [a (new-matrix a-data)] + [b-data '((5.0 6.0) (7.0 8.0))] + [b (new-matrix b-data)] + [c-data '((1.0 1.0 1.0 1.0) (2.0 4.0 8.0 16.0) (3.0 9.0 27.0 81.0) (4.0 16.0 64.0 256.0))] + [c (new-matrix c-data)] + [d-data `((4.0 -3.0 ,(/ 4.0 3.0) ,(/ -1.0 4.0)) + (,(/ -13.0 3.0) ,(/ 19.0 4.0) ,(/ -7.0 3.0) ,(/ 11.0 24.0)) + (1.5 -2.0 ,(/ 7.0 6.0) -0.25) + (,(/ -1.0 6.0) 0.25 ,(/ -1.0 6.0) ,(/ 1.0 24.0)))] + [d (new-matrix d-data)] + [e-data '((1.0 2.0 3.0 4.0) (5.0 6.0 7.0 8.0) (9.0 10.0 11.0 12.0) (13.0 14.0 15.0 16.0))] + [e (new-matrix e-data)] + [f-data '((1.0 0.0 0.0 0.0) (0.0 1.0 0.0 0.0) (0.0 0.0 1.0 0.0) (0.0 0.0 0.0 1.0))] + [f (new-matrix f-data)]) + + (displayln "Using 'normal' matrix multiplication:") + (printf " a * b = ~a" (matrix-to-string (matrix-multiply a b))) + (printf " c * d = ~a" (matrix-to-string-with-precision (matrix-multiply c d) 6)) + (printf " e * f = ~a" (matrix-to-string (matrix-multiply e f))) + + (displayln "\nUsing 'Strassen' matrix multiplication:") + (printf " a * b = ~a" (matrix-to-string (matrix-strassen a b))) + (printf " c * d = ~a" (matrix-to-string-with-precision (matrix-strassen c d) 6)) + (printf " e * f = ~a" (matrix-to-string (matrix-strassen e f))))) + +; Export functions for use as a module +(provide new-matrix matrix? get-rows get-cols + matrix-add matrix-subtract matrix-multiply matrix-strassen + matrix-to-string matrix-to-string-with-precision main) + +; Run the main function if this file is executed directly +(main) diff --git a/Task/Strassens-algorithm/Ruby/strassens-algorithm.rb b/Task/Strassens-algorithm/Ruby/strassens-algorithm.rb new file mode 100644 index 0000000000..18e87a279c --- /dev/null +++ b/Task/Strassens-algorithm/Ruby/strassens-algorithm.rb @@ -0,0 +1,214 @@ +class Shape < Struct.new(:rows, :cols) +end + +class Matrix + attr_reader :data + + def initialize(data = []) + @data = data + end + + def self.block(blocks) + m = [] + # blocks is an array of arrays of Matrix objects + # Process horizontal blocks row by row + top_blocks = blocks[0] # [c11, c12] + bottom_blocks = blocks[1] # [c21, c22] + + # Combine top blocks horizontally + top_rows = [] + (0...top_blocks[0].rows).each do |i| + row = [] + top_blocks.each { |block| row.concat(block.data[i]) } + top_rows << row + end + + # Combine bottom blocks horizontally + bottom_rows = [] + (0...bottom_blocks[0].rows).each do |i| + row = [] + bottom_blocks.each { |block| row.concat(block.data[i]) } + bottom_rows << row + end + + # Combine all rows vertically + m = top_rows + bottom_rows + Matrix.new(m) + end + + def dot(b) + raise "Matrix dimensions don't match" unless self.cols == b.rows + + result = [] + @data.each do |row| + new_row = [] + b.cols.times do |c| + col = b.data.map { |r| r[c] } + new_row << row.zip(col).map { |x, y| x * y }.sum + end + result << new_row + end + Matrix.new(result) + end + + def *(b) + dot(b) + end + + def +(b) + raise "Matrix dimensions don't match" unless self.shape == b.shape + + rows, cols = self.rows, self.cols + result = [] + rows.times do |i| + new_row = [] + cols.times do |j| + new_row << @data[i][j] + b.data[i][j] + end + result << new_row + end + Matrix.new(result) + end + + def -(b) + raise "Matrix dimensions don't match" unless self.shape == b.shape + + rows, cols = self.rows, self.cols + result = [] + rows.times do |i| + new_row = [] + cols.times do |j| + new_row << @data[i][j] - b.data[i][j] + end + result << new_row + end + Matrix.new(result) + end + + def strassen(b) + rows, cols = self.rows, self.cols + + raise "Matrices must be square" unless rows == cols + raise "Matrices must be the same shape" unless self.shape == b.shape + raise "Shape must be a power of 2" unless rows > 0 && (rows & (rows - 1)) == 0 + + if rows == 1 + return self.dot(b) + end + + p = rows / 2 + + a11 = Matrix.new(@data[0...p].map { |row| row[0...p] }) + a12 = Matrix.new(@data[0...p].map { |row| row[p..-1] }) + a21 = Matrix.new(@data[p..-1].map { |row| row[0...p] }) + a22 = Matrix.new(@data[p..-1].map { |row| row[p..-1] }) + + b11 = Matrix.new(b.data[0...p].map { |row| row[0...p] }) + b12 = Matrix.new(b.data[0...p].map { |row| row[p..-1] }) + b21 = Matrix.new(b.data[p..-1].map { |row| row[0...p] }) + b22 = Matrix.new(b.data[p..-1].map { |row| row[p..-1] }) + + m1 = (a11 + a22).strassen(b11 + b22) + m2 = (a21 + a22).strassen(b11) + m3 = a11.strassen(b12 - b22) + m4 = a22.strassen(b21 - b11) + m5 = (a11 + a12).strassen(b22) + m6 = (a21 - a11).strassen(b11 + b12) + m7 = (a12 - a22).strassen(b21 + b22) + + c11 = m1 + m4 - m5 + m7 + c12 = m3 + m5 + c21 = m2 + m4 + c22 = m1 - m2 + m3 + m6 + + Matrix.block([[c11, c12], [c21, c22]]) + end + + def round(ndigits = nil) + rounded_data = @data.map do |row| + row.map do |element| + if ndigits + (element * (10 ** ndigits)).round / (10.0 ** ndigits) + else + element.round + end + end + end + Matrix.new(rounded_data) + end + + def shape + cols = @data.empty? ? 0 : @data[0].length + Shape.new(@data.length, cols) + end + + def rows + @data.length + end + + def cols + @data.empty? ? 0 : @data[0].length + end + + def to_s + @data.inspect + end + + def inspect + @data.inspect + end +end + +def examples + a = Matrix.new([ + [1, 2], + [3, 4] + ]) + + b = Matrix.new([ + [5, 6], + [7, 8] + ]) + + c = Matrix.new([ + [1, 1, 1, 1], + [2, 4, 8, 16], + [3, 9, 27, 81], + [4, 16, 64, 256] + ]) + + d = Matrix.new([ + [4, -3, 4.0/3, -1.0/4], + [-13.0/3, 19.0/4, -7.0/3, 11.0/24], + [3.0/2, -2, 7.0/6, -1.0/4], + [-1.0/6, 1.0/4, -1.0/6, 1.0/24] + ]) + + e = Matrix.new([ + [1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12], + [13, 14, 15, 16] + ]) + + f = Matrix.new([ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, 0], + [0, 0, 0, 1] + ]) + + puts "Naive matrix multiplication:" + puts " a * b = #{a * b}" + puts " c * d = #{(c * d).round}" + puts " e * f = #{e * f}" + + puts "Strassen's matrix multiplication:" + puts " a * b = #{a.strassen(b)}" + puts " c * d = #{c.strassen(d).round}" + puts " e * f = #{e.strassen(f)}" +end + +if __FILE__ == $0 + examples +end diff --git a/Task/Strassens-algorithm/Rust/strassens-algorithm.rs b/Task/Strassens-algorithm/Rust/strassens-algorithm.rs new file mode 100644 index 0000000000..d715f9deea --- /dev/null +++ b/Task/Strassens-algorithm/Rust/strassens-algorithm.rs @@ -0,0 +1,269 @@ +use std::fmt; +use std::ops::{Add, Mul, Sub}; + +#[derive(Debug, Clone)] +struct Matrix { + data: Vec>, + rows: usize, + cols: usize, +} + +impl Matrix { + fn new(data: Vec>) -> Self { + let rows = data.len(); + let cols = if rows > 0 { data[0].len() } else { 0 }; + Matrix { data, rows, cols } + } + + fn rows(&self) -> usize { + self.rows + } + + fn cols(&self) -> usize { + self.cols + } + + fn validate_dimensions(&self, other: &Matrix) { + if self.rows() != other.rows() || self.cols() != other.cols() { + panic!("Matrices must have the same dimensions."); + } + } + + fn validate_multiplication(&self, other: &Matrix) { + if self.cols() != other.rows() { + panic!("Cannot multiply these matrices."); + } + } + + fn validate_square_power_of_two(&self) { + if self.rows() != self.cols() { + panic!("Matrix must be square."); + } + if self.rows() == 0 || (self.rows() & (self.rows() - 1)) != 0 { + panic!("Size of matrix must be a power of two."); + } + } +} + +impl Add for Matrix { + type Output = Self; + + fn add(self, other: Self) -> Self { + self.validate_dimensions(&other); + + let mut result_data = Vec::with_capacity(self.rows()); + for i in 0..self.rows() { + let mut row = Vec::with_capacity(self.cols()); + for j in 0..self.cols() { + row.push(self.data[i][j] + other.data[i][j]); + } + result_data.push(row); + } + + Matrix::new(result_data) + } +} + +impl Sub for Matrix { + type Output = Self; + + fn sub(self, other: Self) -> Self { + self.validate_dimensions(&other); + + let mut result_data = Vec::with_capacity(self.rows()); + for i in 0..self.rows() { + let mut row = Vec::with_capacity(self.cols()); + for j in 0..self.cols() { + row.push(self.data[i][j] - other.data[i][j]); + } + result_data.push(row); + } + + Matrix::new(result_data) + } +} + +impl Mul for Matrix { + type Output = Self; + + fn mul(self, other: Self) -> Self { + self.validate_multiplication(&other); + + let mut result_data = Vec::with_capacity(self.rows()); + for i in 0..self.rows() { + let mut row = Vec::with_capacity(other.cols()); + for j in 0..other.cols() { + let mut sum = 0.0; + for k in 0..other.rows() { + sum += self.data[i][k] * other.data[k][j]; + } + row.push(sum); + } + result_data.push(row); + } + + Matrix::new(result_data) + } +} + +impl fmt::Display for Matrix { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let mut s = String::new(); + for row in &self.data { + s.push_str(&format!("{:?}\n", row)); + } + write!(f, "{}", s) + } +} + +impl Matrix { + fn to_string_with_precision(&self, p: usize) -> String { + let mut s = String::new(); + let pow = 10.0_f64.powi(p as i32); + for row in &self.data { + let mut t = Vec::new(); + for &val in row { + let r = (val * pow).round() / pow; + let formatted = format!("{}", r); + if formatted == "-0" { + t.push("0".to_string()); + } else { + t.push(formatted); + } + } + s.push_str(&format!("{:?}\n", t)); + } + s + } + + fn params(r: usize, c: usize) -> [[usize; 6]; 4] { + [ + [0, r, 0, c, 0, 0], + [0, r, c, 2 * c, 0, c], + [r, 2 * r, 0, c, r, 0], + [r, 2 * r, c, 2 * c, r, c], + ] + } + + fn to_quarters(&self) -> [Matrix; 4] { + let r = self.rows() / 2; + let c = self.cols() / 2; + let p = Matrix::params(r, c); + let mut quarters: [Matrix; 4] = [ + Matrix::new(vec![vec![0.0; c]; r]), + Matrix::new(vec![vec![0.0; c]; r]), + Matrix::new(vec![vec![0.0; c]; r]), + Matrix::new(vec![vec![0.0; c]; r]), + ]; + + for k in 0..4 { + let mut q_data = Vec::with_capacity(r); + for i in p[k][0]..p[k][1] { + let mut row = Vec::with_capacity(c); + for j in p[k][2]..p[k][3] { + row.push(self.data[i][j]); + } + q_data.push(row); + } + quarters[k] = Matrix::new(q_data); + } + + quarters + } + + fn from_quarters(q: [Matrix; 4]) -> Matrix { + let r = q[0].rows(); + let c = q[0].cols(); + let p = Matrix::params(r, c); + let rows = r * 2; + let cols = c * 2; + + let mut m_data = vec![vec![0.0; cols]; rows]; + + for k in 0..4 { + for i in p[k][0]..p[k][1] { + for j in p[k][2]..p[k][3] { + m_data[i][j] = q[k].data[i - p[k][4]][j - p[k][5]]; + } + } + } + + Matrix::new(m_data) + } + + fn strassen(&self, other: Matrix) -> Matrix { + self.validate_square_power_of_two(); + other.validate_square_power_of_two(); + if self.rows() != other.rows() || self.cols() != other.cols() { + panic!("Matrices must be square and of equal size for Strassen multiplication."); + } + + if self.rows() == 1 { + return self.clone() * other; + } + + let qa = self.to_quarters(); + let qb = other.to_quarters(); + + let p1 = (qa[1].clone() - qa[3].clone()).strassen(qb[2].clone() + qb[3].clone()); + let p2 = (qa[0].clone() + qa[3].clone()).strassen(qb[0].clone() + qb[3].clone()); + let p3 = (qa[0].clone() - qa[2].clone()).strassen(qb[0].clone() + qb[1].clone()); + let p4 = (qa[0].clone() + qa[1].clone()).strassen(qb[3].clone()); + let p5 = qa[0].clone().strassen(qb[1].clone() - qb[3].clone()); + let p6 = qa[3].clone().strassen(qb[2].clone() - qb[0].clone()); + let p7 = (qa[2].clone() + qa[3].clone()).strassen(qb[0].clone()); + + let mut q: [Matrix; 4] = [ + Matrix::new(vec![vec![0.0; qa[0].cols()]; qa[0].rows()]), + Matrix::new(vec![vec![0.0; qa[0].cols()]; qa[0].rows()]), + Matrix::new(vec![vec![0.0; qa[0].cols()]; qa[0].rows()]), + Matrix::new(vec![vec![0.0; qa[0].cols()]; qa[0].rows()]), + ]; + + q[0] = p1.clone() + p2.clone() - p4.clone() + p6.clone(); + q[1] = p4 + p5.clone(); + q[2] = p6 + p7.clone(); + q[3] = p2 - p3.clone() + p5 - p7; + + Matrix::from_quarters(q) + } +} + +fn main() { + let a = Matrix::new(vec![vec![1.0, 2.0], vec![3.0, 4.0]]); + let b = Matrix::new(vec![vec![5.0, 6.0], vec![7.0, 8.0]]); + let c = Matrix::new(vec![ + vec![1.0, 1.0, 1.0, 1.0], + vec![2.0, 4.0, 8.0, 16.0], + vec![3.0, 9.0, 27.0, 81.0], + vec![4.0, 16.0, 64.0, 256.0], + ]); + let d = Matrix::new(vec![ + vec![4.0, -3.0, 4.0 / 3.0, -1.0 / 4.0], + vec![-13.0 / 3.0, 19.0 / 4.0, -7.0 / 3.0, 11.0 / 24.0], + vec![3.0 / 2.0, -2.0, 7.0 / 6.0, -1.0 / 4.0], + vec![-1.0 / 6.0, 1.0 / 4.0, -1.0 / 6.0, 1.0 / 24.0], + ]); + let e = Matrix::new(vec![ + vec![1.0, 2.0, 3.0, 4.0], + vec![5.0, 6.0, 7.0, 8.0], + vec![9.0, 10.0, 11.0, 12.0], + vec![13.0, 14.0, 15.0, 16.0], + ]); + let f = Matrix::new(vec![ + vec![1.0, 0.0, 0.0, 0.0], + vec![0.0, 1.0, 0.0, 0.0], + vec![0.0, 0.0, 1.0, 0.0], + vec![0.0, 0.0, 0.0, 1.0], + ]); + + println!("Using 'normal' matrix multiplication:"); + println!(" a * b = {}", a.clone() * b.clone()); + println!(" c * d = {}", (c.clone() * d.clone()).to_string_with_precision(6)); + println!(" e * f = {}", e.clone() * f.clone()); + + println!("\nUsing 'Strassen' matrix multiplication:"); + println!(" a * b = {}", a.strassen(b)); + println!(" c * d = {}", c.strassen(d).to_string_with_precision(6)); + println!(" e * f = {}", e.strassen(f)); +} diff --git a/Task/Strassens-algorithm/Tcl/strassens-algorithm.tcl b/Task/Strassens-algorithm/Tcl/strassens-algorithm.tcl new file mode 100644 index 0000000000..97c34a5539 --- /dev/null +++ b/Task/Strassens-algorithm/Tcl/strassens-algorithm.tcl @@ -0,0 +1,267 @@ +# Helper function to create a matrix from nested blocks +proc block_matrix {blocks} { + set m {} + set num_hblocks [llength $blocks] + set num_vblocks [llength [lindex $blocks 0]] + + # Determine dimensions + set block_height [llength [lindex [lindex $blocks 0] 0]] + set block_widths {} + for {set j 0} {$j < $num_vblocks} {incr j} { + lappend block_widths [llength [lindex [lindex [lindex $blocks 0] $j] 0]] + } + + # Build the resulting matrix + for {set i 0} {$i < [expr {$block_height * $num_hblocks}]} {incr i} { + lappend m {} + } + + for {set h 0} {$h < $num_hblocks} {incr h} { + set row_offset [expr {$h * $block_height}] + for {set i 0} {$i < $block_height} {incr i} { + set col_offset 0 + for {set v 0} {$v < $num_vblocks} {incr v} { + set block [lindex [lindex $blocks $h] $v] + set block_width [lindex $block_widths $v] + for {set j 0} {$j < $block_width} {incr j} { + set row_idx [expr {$row_offset + $i}] + set col_idx [expr {$col_offset + $j}] + set value [lindex [lindex $block $i] $j] + + # Extend row if needed + set current_row [lindex $m $row_idx] + while {[llength $current_row] <= $col_idx} { + lappend current_row 0 + } + set current_row [lreplace $current_row $col_idx $col_idx $value] + set m [lreplace $m $row_idx $row_idx $current_row] + } + incr col_offset $block_width + } + } + } + + return $m +} + +# Matrix multiplication (naive) +proc matrix_multiply {a b} { + set rows_a [llength $a] + set cols_a [llength [lindex $a 0]] + set rows_b [llength $b] + set cols_b [llength [lindex $b 0]] + + if {$cols_a != $rows_b} { + error "Incompatible matrix dimensions for multiplication" + } + + set result {} + for {set i 0} {$i < $rows_a} {incr i} { + set row {} + for {set j 0} {$j < $cols_b} {incr j} { + set sum 0 + for {set k 0} {$k < $cols_a} {incr k} { + set a_val [lindex [lindex $a $i] $k] + set b_val [lindex [lindex $b $k] $j] + set sum [expr {$sum + $a_val * $b_val}] + } + lappend row $sum + } + lappend result $row + } + + return $result +} + +# Matrix addition +proc matrix_add {a b} { + set rows [llength $a] + set cols [llength [lindex $a 0]] + + if {$rows != [llength $b] || $cols != [llength [lindex $b 0]]} { + error "Matrices must have the same dimensions" + } + + set result {} + for {set i 0} {$i < $rows} {incr i} { + set row {} + for {set j 0} {$j < $cols} {incr j} { + set a_val [lindex [lindex $a $i] $j] + set b_val [lindex [lindex $b $i] $j] + lappend row [expr {$a_val + $b_val}] + } + lappend result $row + } + + return $result +} + +# Matrix subtraction +proc matrix_subtract {a b} { + set rows [llength $a] + set cols [llength [lindex $a 0]] + + if {$rows != [llength $b] || $cols != [llength [lindex $b 0]]} { + error "Matrices must have the same dimensions" + } + + set result {} + for {set i 0} {$i < $rows} {incr i} { + set row {} + for {set j 0} {$j < $cols} {incr j} { + set a_val [lindex [lindex $a $i] $j] + set b_val [lindex [lindex $b $i] $j] + lappend row [expr {$a_val - $b_val}] + } + lappend result $row + } + + return $result +} + +# Get submatrix (using 0-based indexing internally, but interface expects 1-based) +proc get_submatrix {m start_row end_row start_col end_col} { + # Convert to 0-based indexing + incr start_row -1 + incr end_row -1 + incr start_col -1 + incr end_col -1 + + set result {} + for {set i $start_row} {$i <= $end_row} {incr i} { + set row {} + for {set j $start_col} {$j <= $end_col} {incr j} { + lappend row [lindex [lindex $m $i] $j] + } + lappend result $row + } + return $result +} + +# Check if number is power of 2 +proc is_power_of_2 {n} { + if {$n <= 0} {return 0} + return [expr {($n & ($n - 1)) == 0}] +} + +# Strassen's algorithm +proc strassen_multiply {a b} { + set n [llength $a] + set m [llength [lindex $a 0]] + + if {$n != $m} { + error "Matrix must be square" + } + if {$n != [llength $b] || $n != [llength [lindex $b 0]]} { + error "Matrices must have the same dimensions" + } + + # Check if size is a power of 2 + if {![is_power_of_2 $n]} { + error "Matrix dimension must be a power of 2" + } + + if {$n == 1} { + set val [expr {[lindex [lindex $a 0] 0] * [lindex [lindex $b 0] 0]}] + return [list [list $val]] + } + + set half [expr {$n / 2}] + + # Partition matrices into quadrants + set a11 [get_submatrix $a 1 $half 1 $half] + set a12 [get_submatrix $a 1 $half [expr {$half+1}] $n] + set a21 [get_submatrix $a [expr {$half+1}] $n 1 $half] + set a22 [get_submatrix $a [expr {$half+1}] $n [expr {$half+1}] $n] + + set b11 [get_submatrix $b 1 $half 1 $half] + set b12 [get_submatrix $b 1 $half [expr {$half+1}] $n] + set b21 [get_submatrix $b [expr {$half+1}] $n 1 $half] + set b22 [get_submatrix $b [expr {$half+1}] $n [expr {$half+1}] $n] + + # Calculate the seven products + set m1 [strassen_multiply [matrix_add $a11 $a22] [matrix_add $b11 $b22]] + set m2 [strassen_multiply [matrix_add $a21 $a22] $b11] + set m3 [strassen_multiply $a11 [matrix_subtract $b12 $b22]] + set m4 [strassen_multiply $a22 [matrix_subtract $b21 $b11]] + set m5 [strassen_multiply [matrix_add $a11 $a12] $b22] + set m6 [strassen_multiply [matrix_subtract $a21 $a11] [matrix_add $b11 $b12]] + set m7 [strassen_multiply [matrix_subtract $a12 $a22] [matrix_add $b21 $b22]] + + # Calculate the four quadrants of the result + set c11 [matrix_add [matrix_subtract [matrix_add $m1 $m4] $m5] $m7] + set c12 [matrix_add $m3 $m5] + set c21 [matrix_add $m2 $m4] + set c22 [matrix_add [matrix_subtract [matrix_add $m1 $m3] $m2] $m6] + + # Combine quadrants into a single matrix + return [block_matrix [list [list $c11 $c12] [list $c21 $c22]]] +} + +# Round matrix values +proc matrix_round {m {digits {}}} { + set result {} + + if {$digits ne ""} { + set mult [expr {pow(10, $digits)}] + } + + for {set i 0} {$i < [llength $m]} {incr i} { + set row {} + for {set j 0} {$j < [llength [lindex $m 0]]} {incr j} { + set val [lindex [lindex $m $i] $j] + if {$digits ne ""} { + set rounded [expr {floor($val * $mult + 0.5) / $mult}] + } else { + set rounded [expr {floor($val + 0.5)}] + } + lappend row $rounded + } + lappend result $row + } + + return $result +} + +# Print matrix +proc print_matrix {name m} { + puts "$name = \{" + for {set i 0} {$i < [llength $m]} {incr i} { + puts -nonewline " \{" + set row [lindex $m $i] + for {set j 0} {$j < [llength $row]} {incr j} { + puts -nonewline [lindex $row $j] + if {$j < [expr {[llength $row] - 1}]} { + puts -nonewline ", " + } + } + puts "\}" + } + puts "\}" +} + +# Examples +proc run_examples {} { + set a {{1 2} {3 4}} + set b {{5 6} {7 8}} + + set c {{1 1 1 1} {2 4 8 16} {3 9 27 81} {4 16 64 256}} + + set d {{4 -3 1.333333 -0.25} {-4.333333 4.75 -2.333333 0.458333} {1.5 -2 1.166667 -0.25} {-0.166667 0.25 -0.166667 0.041667}} + + set e {{1 2 3 4} {5 6 7 8} {9 10 11 12} {13 14 15 16}} + set f {{1 0 0 0} {0 1 0 0} {0 0 1 0} {0 0 0 1}} + + puts "Naive matrix multiplication:" + print_matrix " a * b" [matrix_multiply $a $b] + print_matrix " c * d" [matrix_round [matrix_multiply $c $d] 0] + print_matrix " e * f" [matrix_multiply $e $f] + + puts "\nStrassen's matrix multiplication:" + print_matrix " a * b" [strassen_multiply $a $b] + print_matrix " c * d" [matrix_round [strassen_multiply $c $d] 0] + print_matrix " e * f" [strassen_multiply $e $f] +} + +# Run examples +run_examples diff --git a/Task/Strassens-algorithm/Zig/strassens-algorithm.zig b/Task/Strassens-algorithm/Zig/strassens-algorithm.zig new file mode 100644 index 0000000000..9297f6eb48 --- /dev/null +++ b/Task/Strassens-algorithm/Zig/strassens-algorithm.zig @@ -0,0 +1,477 @@ +const std = @import("std"); +const fmt = std.fmt; +const ArrayList = std.ArrayList; +const Allocator = std.mem.Allocator; + +const Matrix = struct { + data: ArrayList(ArrayList(f64)), + rows: usize, + cols: usize, + allocator: Allocator, + + pub fn init(allocator: Allocator, data: ArrayList(ArrayList(f64))) !Matrix { + const rows = data.items.len; + const cols = if (rows > 0) data.items[0].items.len else 0; + + return Matrix{ + .data = data, + .rows = rows, + .cols = cols, + .allocator = allocator, + }; + } + + pub fn deinit(self: *Matrix) void { + for (self.data.items) |*row| { + row.deinit(); + } + self.data.deinit(); + } + + pub fn clone(self: Matrix) !Matrix { + var new_data = ArrayList(ArrayList(f64)).init(self.allocator); + try new_data.ensureTotalCapacity(self.rows); + + for (self.data.items) |row| { + var new_row = ArrayList(f64).init(self.allocator); + try new_row.ensureTotalCapacity(self.cols); + try new_row.appendSlice(row.items); + try new_data.append(new_row); + } + + return Matrix{ + .data = new_data, + .rows = self.rows, + .cols = self.cols, + .allocator = self.allocator, + }; + } + + pub fn validateDimensions(self: Matrix, other: Matrix) !void { + if (self.rows != other.rows or self.cols != other.cols) { + return error.DimensionMismatch; + } + } + + pub fn validateMultiplication(self: Matrix, other: Matrix) !void { + if (self.cols != other.rows) { + return error.CannotMultiply; + } + } + + pub fn validateSquarePowerOfTwo(self: Matrix) !void { + if (self.rows != self.cols) { + return error.NotSquare; + } + if (self.rows == 0 or (self.rows & (self.rows - 1)) != 0) { + return error.NotPowerOfTwo; + } + } + + pub fn add(self: Matrix, other: Matrix) !Matrix { + try self.validateDimensions(other); + + var result_data = ArrayList(ArrayList(f64)).init(self.allocator); + try result_data.ensureTotalCapacity(self.rows); + + for (0..self.rows) |i| { + var row = ArrayList(f64).init(self.allocator); + try row.ensureTotalCapacity(self.cols); + + for (0..self.cols) |j| { + try row.append(self.data.items[i].items[j] + other.data.items[i].items[j]); + } + try result_data.append(row); + } + + return try Matrix.init(self.allocator, result_data); + } + + pub fn sub(self: Matrix, other: Matrix) !Matrix { + try self.validateDimensions(other); + + var result_data = ArrayList(ArrayList(f64)).init(self.allocator); + try result_data.ensureTotalCapacity(self.rows); + + for (0..self.rows) |i| { + var row = ArrayList(f64).init(self.allocator); + try row.ensureTotalCapacity(self.cols); + + for (0..self.cols) |j| { + try row.append(self.data.items[i].items[j] - other.data.items[i].items[j]); + } + try result_data.append(row); + } + + return try Matrix.init(self.allocator, result_data); + } + + pub fn mul(self: Matrix, other: Matrix) !Matrix { + try self.validateMultiplication(other); + + var result_data = ArrayList(ArrayList(f64)).init(self.allocator); + try result_data.ensureTotalCapacity(self.rows); + + for (0..self.rows) |i| { + var row = ArrayList(f64).init(self.allocator); + try row.ensureTotalCapacity(other.cols); + + for (0..other.cols) |j| { + var sum: f64 = 0.0; + for (0..self.cols) |k| { + sum += self.data.items[i].items[k] * other.data.items[k].items[j]; + } + try row.append(sum); + } + try result_data.append(row); + } + + return try Matrix.init(self.allocator, result_data); + } + + pub fn format(self: Matrix, comptime _: []const u8, _: fmt.FormatOptions, writer: anytype) !void { + for (self.data.items) |row| { + try writer.print("{any}\n", .{row.items}); + } + } + + pub fn toStringWithPrecision(self: Matrix, p: usize, allocator: Allocator) ![]u8 { + var output = ArrayList(u8).init(allocator); + defer output.deinit(); + + const pow = std.math.pow(f64, 10.0, @as(f64, @floatFromInt(p))); + + for (self.data.items) |row| { + var formatted_row = ArrayList([]const u8).init(allocator); + defer { + for (formatted_row.items) |item| { + allocator.free(item); + } + formatted_row.deinit(); + } + + for (row.items) |val| { + const r = @round(val * pow) / pow; + const formatted = try fmt.allocPrint(allocator, "{d}", .{r}); + + if (std.mem.eql(u8, formatted, "-0")) { + allocator.free(formatted); + try formatted_row.append(try allocator.dupe(u8, "0")); + } else { + try formatted_row.append(formatted); + } + } + + std.debug.print("{any}\n", .{formatted_row.items}); + } + + return output.toOwnedSlice(); + } + + fn params(r: usize, c: usize) [4][6]usize { + return [4][6]usize{ + [_]usize{ 0, r, 0, c, 0, 0 }, + [_]usize{ 0, r, c, 2 * c, 0, c }, + [_]usize{ r, 2 * r, 0, c, r, 0 }, + [_]usize{ r, 2 * r, c, 2 * c, r, c }, + }; + } + + pub fn toQuarters(self: Matrix) ![4]Matrix { + const r = self.rows / 2; + const c = self.cols / 2; + const p = Matrix.params(r, c); + + var quarters: [4]Matrix = undefined; + + for (0..4) |k| { + var q_data = ArrayList(ArrayList(f64)).init(self.allocator); + try q_data.ensureTotalCapacity(r); + + for (p[k][0]..p[k][1]) |i| { + var row = ArrayList(f64).init(self.allocator); + try row.ensureTotalCapacity(c); + + for (p[k][2]..p[k][3]) |j| { + try row.append(self.data.items[i].items[j]); + } + try q_data.append(row); + } + + quarters[k] = try Matrix.init(self.allocator, q_data); + } + + return quarters; + } + + pub fn fromQuarters(q: [4]Matrix, allocator: Allocator) !Matrix { + const r = q[0].rows; + const c = q[0].cols; + const p = Matrix.params(r, c); + const rows = r * 2; + const cols = c * 2; + + var m_data = ArrayList(ArrayList(f64)).init(allocator); + try m_data.ensureTotalCapacity(rows); + + for (0..rows) |_| { + var row = ArrayList(f64).init(allocator); + try row.ensureTotalCapacity(cols); + for (0..cols) |_| { + try row.append(0.0); + } + try m_data.append(row); + } + + for (0..4) |k| { + for (p[k][0]..p[k][1]) |i| { + for (p[k][2]..p[k][3]) |j| { + m_data.items[i].items[j] = q[k].data.items[i - p[k][4]].items[j - p[k][5]]; + } + } + } + + return try Matrix.init(allocator, m_data); + } + + pub fn strassen(self: Matrix, other: Matrix) !Matrix { + try self.validateSquarePowerOfTwo(); + try other.validateSquarePowerOfTwo(); + + if (self.rows != other.rows or self.cols != other.cols) { + return error.InvalidDimensions; + } + + if (self.rows == 1) { + return self.mul(other); + } + + var qa = try self.toQuarters(); + defer for (&qa) |*q| q.deinit(); + + var qb = try other.toQuarters(); + defer for (&qb) |*q| q.deinit(); + + var t1 = try qa[1].sub(qa[3]); + defer t1.deinit(); + var t2 = try qb[2].add(qb[3]); + defer t2.deinit(); + var p1 = try t1.strassen(t2); + defer p1.deinit(); + + var t3 = try qa[0].add(qa[3]); + defer t3.deinit(); + var t4 = try qb[0].add(qb[3]); + defer t4.deinit(); + var p2 = try t3.strassen(t4); + defer p2.deinit(); + + var t5 = try qa[0].sub(qa[2]); + defer t5.deinit(); + var t6 = try qb[0].add(qb[1]); + defer t6.deinit(); + var p3 = try t5.strassen(t6); + defer p3.deinit(); + + var t7 = try qa[0].add(qa[1]); + defer t7.deinit(); + var p4 = try t7.strassen(qb[3]); + defer p4.deinit(); + + var t8 = try qb[1].sub(qb[3]); + defer t8.deinit(); + var p5 = try qa[0].strassen(t8); + defer p5.deinit(); + + var t9 = try qb[2].sub(qb[0]); + defer t9.deinit(); + var p6 = try qa[3].strassen(t9); + defer p6.deinit(); + + var t10 = try qa[2].add(qa[3]); + defer t10.deinit(); + var p7 = try t10.strassen(qb[0]); + defer p7.deinit(); + + var q: [4]Matrix = undefined; + + // q[0] = p1 + p2 - p4 + p6 + var ta = try p1.add(p2); + defer ta.deinit(); + var tb = try ta.sub(p4); + defer tb.deinit(); + q[0] = try tb.add(p6); + + // q[1] = p4 + p5 + q[1] = try p4.add(p5); + + // q[2] = p6 + p7 + q[2] = try p6.add(p7); + + // q[3] = p2 - p3 + p5 - p7 + var tc = try p2.sub(p3); + defer tc.deinit(); + var td = try tc.add(p5); + defer td.deinit(); + q[3] = try td.sub(p7); + + defer for (&q) |*quarter| quarter.deinit(); + + return Matrix.fromQuarters(q, self.allocator); + } +}; + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + + const allocator = gpa.allocator(); + + // Matrix A - [1 2; 3 4] + var a_data = ArrayList(ArrayList(f64)).init(allocator); + var a_row1 = ArrayList(f64).init(allocator); + try a_row1.appendSlice(&[_]f64{ 1.0, 2.0 }); + var a_row2 = ArrayList(f64).init(allocator); + try a_row2.appendSlice(&[_]f64{ 3.0, 4.0 }); + try a_data.append(a_row1); + try a_data.append(a_row2); + var a = try Matrix.init(allocator, a_data); + defer a.deinit(); + + // Matrix B - [5 6; 7 8] + var b_data = ArrayList(ArrayList(f64)).init(allocator); + var b_row1 = ArrayList(f64).init(allocator); + try b_row1.appendSlice(&[_]f64{ 5.0, 6.0 }); + var b_row2 = ArrayList(f64).init(allocator); + try b_row2.appendSlice(&[_]f64{ 7.0, 8.0 }); + try b_data.append(b_row1); + try b_data.append(b_row2); + var b = try Matrix.init(allocator, b_data); + defer b.deinit(); + + // Matrix C - 4x4 + var c_data = ArrayList(ArrayList(f64)).init(allocator); + var c_row1 = ArrayList(f64).init(allocator); + try c_row1.appendSlice(&[_]f64{ 1.0, 1.0, 1.0, 1.0 }); + var c_row2 = ArrayList(f64).init(allocator); + try c_row2.appendSlice(&[_]f64{ 2.0, 4.0, 8.0, 16.0 }); + var c_row3 = ArrayList(f64).init(allocator); + try c_row3.appendSlice(&[_]f64{ 3.0, 9.0, 27.0, 81.0 }); + var c_row4 = ArrayList(f64).init(allocator); + try c_row4.appendSlice(&[_]f64{ 4.0, 16.0, 64.0, 256.0 }); + try c_data.append(c_row1); + try c_data.append(c_row2); + try c_data.append(c_row3); + try c_data.append(c_row4); + var c = try Matrix.init(allocator, c_data); + defer c.deinit(); + + // Matrix D - 4x4 + var d_data = ArrayList(ArrayList(f64)).init(allocator); + var d_row1 = ArrayList(f64).init(allocator); + try d_row1.appendSlice(&[_]f64{ 4.0, -3.0, 4.0 / 3.0, -1.0 / 4.0 }); + var d_row2 = ArrayList(f64).init(allocator); + try d_row2.appendSlice(&[_]f64{ -13.0 / 3.0, 19.0 / 4.0, -7.0 / 3.0, 11.0 / 24.0 }); + var d_row3 = ArrayList(f64).init(allocator); + try d_row3.appendSlice(&[_]f64{ 3.0 / 2.0, -2.0, 7.0 / 6.0, -1.0 / 4.0 }); + var d_row4 = ArrayList(f64).init(allocator); + try d_row4.appendSlice(&[_]f64{ -1.0 / 6.0, 1.0 / 4.0, -1.0 / 6.0, 1.0 / 24.0 }); + try d_data.append(d_row1); + try d_data.append(d_row2); + try d_data.append(d_row3); + try d_data.append(d_row4); + var d = try Matrix.init(allocator, d_data); + defer d.deinit(); + + // Matrix E - 4x4 + var e_data = ArrayList(ArrayList(f64)).init(allocator); + var e_row1 = ArrayList(f64).init(allocator); + try e_row1.appendSlice(&[_]f64{ 1.0, 2.0, 3.0, 4.0 }); + var e_row2 = ArrayList(f64).init(allocator); + try e_row2.appendSlice(&[_]f64{ 5.0, 6.0, 7.0, 8.0 }); + var e_row3 = ArrayList(f64).init(allocator); + try e_row3.appendSlice(&[_]f64{ 9.0, 10.0, 11.0, 12.0 }); + var e_row4 = ArrayList(f64).init(allocator); + try e_row4.appendSlice(&[_]f64{ 13.0, 14.0, 15.0, 16.0 }); + try e_data.append(e_row1); + try e_data.append(e_row2); + try e_data.append(e_row3); + try e_data.append(e_row4); + var e = try Matrix.init(allocator, e_data); + defer e.deinit(); + + // Matrix F - Identity 4x4 + var f_data = ArrayList(ArrayList(f64)).init(allocator); + var f_row1 = ArrayList(f64).init(allocator); + try f_row1.appendSlice(&[_]f64{ 1.0, 0.0, 0.0, 0.0 }); + var f_row2 = ArrayList(f64).init(allocator); + try f_row2.appendSlice(&[_]f64{ 0.0, 1.0, 0.0, 0.0 }); + var f_row3 = ArrayList(f64).init(allocator); + try f_row3.appendSlice(&[_]f64{ 0.0, 0.0, 1.0, 0.0 }); + var f_row4 = ArrayList(f64).init(allocator); + try f_row4.appendSlice(&[_]f64{ 0.0, 0.0, 0.0, 1.0 }); + try f_data.append(f_row1); + try f_data.append(f_row2); + try f_data.append(f_row3); + try f_data.append(f_row4); + var f = try Matrix.init(allocator, f_data); + defer f.deinit(); + + const stdout = std.io.getStdOut().writer(); + + try stdout.print("Using 'normal' matrix multiplication:\n", .{}); + + var a_clone = try a.clone(); + defer a_clone.deinit(); + var b_clone = try b.clone(); + defer b_clone.deinit(); + var ab = try a_clone.mul(b_clone); + defer ab.deinit(); + try stdout.print(" a * b = {}\n", .{ab}); + + var c_clone = try c.clone(); + defer c_clone.deinit(); + var d_clone = try d.clone(); + defer d_clone.deinit(); + var cd = try c_clone.mul(d_clone); + defer cd.deinit(); + const cd_str = try cd.toStringWithPrecision(6, allocator); + defer allocator.free(cd_str); + try stdout.print(" c * d = {s}\n", .{cd_str}); + + var e_clone = try e.clone(); + defer e_clone.deinit(); + var f_clone = try f.clone(); + defer f_clone.deinit(); + var ef = try e_clone.mul(f_clone); + defer ef.deinit(); + try stdout.print(" e * f = {}\n", .{ef}); + + try stdout.print("\nUsing 'Strassen' matrix multiplication:\n", .{}); + + var a_clone2 = try a.clone(); + defer a_clone2.deinit(); + var b_clone2 = try b.clone(); + defer b_clone2.deinit(); + var ab_s = try a_clone2.strassen(b_clone2); + defer ab_s.deinit(); + try stdout.print(" a * b = {}\n", .{ab_s}); + + var c_clone2 = try c.clone(); + defer c_clone2.deinit(); + var d_clone2 = try d.clone(); + defer d_clone2.deinit(); + var cd_s = try c_clone2.strassen(d_clone2); + defer cd_s.deinit(); + const cd_s_str = try cd_s.toStringWithPrecision(6, allocator); + defer allocator.free(cd_s_str); + try stdout.print(" c * d = {s}\n", .{cd_s_str}); + + var e_clone2 = try e.clone(); + defer e_clone2.deinit(); + var f_clone2 = try f.clone(); + defer f_clone2.deinit(); + var ef_s = try e_clone2.strassen(f_clone2); + defer ef_s.deinit(); + try stdout.print(" e * f = {}\n", .{ef_s}); +} diff --git a/Task/Stream-merge/ALGOL-68/stream-merge.alg b/Task/Stream-merge/ALGOL-68/stream-merge.alg index 8e0a822bf9..23dc3199f3 100644 --- a/Task/Stream-merge/ALGOL-68/stream-merge.alg +++ b/Task/Stream-merge/ALGOL-68/stream-merge.alg @@ -1,35 +1,35 @@ # merge a number of input files to an output file # -PROC mergenf = ( []REF FILE inf, REF FILE out )VOID: +PROC mergenf = ( []REF FILE inpf, REF FILE out )VOID: BEGIN INT eof count := 0; BOOL at eof := FALSE; - []REF FILE inputs = inf[ AT 1 ]; + []REF FILE inputs = inpf[ AT 1 ]; INT number of files = UPB inputs; - [ number of files ]BOOL eof; + [ number of files ]BOOL reached eof; [ number of files ]STRING line; FOR f TO number of files DO - eof[ f ] := FALSE; - on logical file end( inf[ f ], ( REF FILE f )BOOL: - BEGIN - # note that we reached EOF on the latest read # - # and return TRUE so processing can continue # - at eof := TRUE - END + reached eof[ f ] := FALSE; + on logical file end( inpf[ f ], ( REF FILE f )BOOL: + BEGIN + # note that we reached EOF on the latest read # + # and return TRUE so processing can continue # + at eof := TRUE + END ) OD; # read a line from one of the input files # - PROC read line = ( INT file number )VOID: + PROC read a line = ( INT file number )VOID: BEGIN at eof := FALSE; get( inputs[ file number ], ( line[ file number ], newline ) ); - eof[ file number ] := at eof; + reached eof[ file number ] := at eof; IF at eof THEN # reached eof on this file # eof count +:= 1 FI - END; # read line # + END; # read a line # # get the first line from each input file # - FOR f TO number of files DO read line( f ) OD; + FOR f TO number of files DO read a line( f ) OD; # merge the files # WHILE eof count < number of files DO # find the lowest line in the current set # @@ -37,7 +37,7 @@ PROC mergenf = ( []REF FILE inf, REF FILE out )VOID: STRING low line := ""; BOOL first file := TRUE; FOR file pos TO number of files DO - IF eof[ file pos ] THEN + IF reached eof[ file pos ] THEN # file is at eof - ignore it # SKIP ELIF first file THEN @@ -54,7 +54,7 @@ PROC mergenf = ( []REF FILE inf, REF FILE out )VOID: # write the record from the lowest file and get the next record # # from it # put( out, ( line[ low pos ], newline ) ); - read line( low pos ) + read a line( low pos ) OD END; # mergenf # @@ -65,11 +65,11 @@ PROC mergen = ( []STRING input list, STRING output name )VOID: BEGIN []STRING inputs = input list[ AT 1 ]; INT number of files = UPB inputs; - [ number of files ]REF FILE inf; + [ number of files ]REF FILE inpf; # open the input files # FOR f TO number of files DO - inf[ f ] := LOC FILE; - IF open( inf[ f ], inputs[ f ], stand in channel ) /= 0 + inpf[ f ] := LOC FILE; + IF open( inpf[ f ], inputs[ f ], stand in channel ) /= 0 THEN # failed to open the input file # print( ( "Unable to open """ + input list[ f ] + """", newline ) ); @@ -85,16 +85,13 @@ PROC mergen = ( []STRING input list, STRING output name )VOID: stop ELSE # files opened OK, merge them # - mergenf( inf, output file ); + mergenf( inpf, output file ); # close the files # close( output file ); - FOR f TO number of files DO close( inf[ f ] ) OD + FOR f TO number of files DO close( inpf[ f ] ) OD FI END; # mergen # -# merges the two files in1 and in2 to output file # -PROC merge2f = ( REF FILE in1, REF FILE in2, REF FILE output file )VOID: mergenf( ( in1, in2 ), output file ); - # merges the two files named in1 and in2 to the file named output file # PROC merge2 = ( STRING in1, STRING in2, STRING output file )VOID: mergen( ( in1, in2 ), output file ); diff --git a/Task/Stream-merge/Ada/stream-merge.ada b/Task/Stream-merge/Ada/stream-merge.adb similarity index 100% rename from Task/Stream-merge/Ada/stream-merge.ada rename to Task/Stream-merge/Ada/stream-merge.adb diff --git a/Task/Stream-merge/Elixir/stream-merge.elixir b/Task/Stream-merge/Elixir/stream-merge.ex similarity index 100% rename from Task/Stream-merge/Elixir/stream-merge.elixir rename to Task/Stream-merge/Elixir/stream-merge.ex diff --git a/Task/Stream-merge/JavaScript/stream-merge.js b/Task/Stream-merge/JavaScript/stream-merge.js new file mode 100644 index 0000000000..d2d8885921 --- /dev/null +++ b/Task/Stream-merge/JavaScript/stream-merge.js @@ -0,0 +1,89 @@ +// ------------------------------------------------------------ +// Helper that prints a number followed by a space (like C++ `display`) +function display(num) { + process.stdout.write(num + ' '); +} + +// ------------------------------------------------------------ +// merge2 – merge two sorted collections and call `action` for each +// element in sorted order. +function merge2(c1, c2, action) { + let i1 = 0; // index into c1 + let i2 = 0; // index into c2 + + while (i1 < c1.length && i2 < c2.length) { + if (c1[i1] <= c2[i2]) { + action(c1[i1++]); + } else { + action(c2[i2++]); + } + } + + // copy the rest of c1 (if any) + while (i1 < c1.length) { + action(c1[i1++]); + } + + // copy the rest of c2 (if any) + while (i2 < c2.length) { + action(c2[i2++]); + } +} + +// ------------------------------------------------------------ +// mergeN – merge **any number** of sorted collections. +// `all` is an iterable (e.g. an array) that contains the +// collections to be merged. `action` is called for each value +// in global sorted order. +function mergeN(action, all) { + // Create a list of “ranges”: each entry keeps the source array + // and the current index inside that array. + const ranges = Array.from(all, col => ({ + arr: col, + pos: 0, // points to the next element to read + end: col.length + })); + + let done = false; + while (!done) { + done = true; + let least = null; // reference to the range that currently has the smallest element + + // Scan every range looking for the smallest next element. + for (const r of ranges) { + // skip exhausted ranges + if (r.pos >= r.end) continue; + + if (least === null || r.arr[r.pos] < least.arr[least.pos]) { + least = r; + } + } + + // If we found a non‑empty range, emit its element and advance it. + if (least !== null) { + done = false; + action(least.arr[least.pos]); + ++least.pos; + } + } +} + +// ------------------------------------------------------------ +// Demo – the same tests that the C++ `main` performed +(function main() { + const v1 = [0, 3, 6]; + const v2 = [1, 4, 7]; + const v3 = [2, 5, 8]; + + // merge2(v2, v1, display); + merge2(v2, v1, display); + console.log(); // newline + + // mergeN(display, { v1 }); + mergeN(display, [v1]); + console.log(); + + // mergeN(display, { v3, v2, v1 }); + mergeN(display, [v3, v2, v1]); + console.log(); +})(); diff --git a/Task/Stream-merge/Julia/stream-merge.julia b/Task/Stream-merge/Julia/stream-merge.jl similarity index 100% rename from Task/Stream-merge/Julia/stream-merge.julia rename to Task/Stream-merge/Julia/stream-merge.jl diff --git a/Task/Stream-merge/Kotlin/stream-merge.kotlin b/Task/Stream-merge/Kotlin/stream-merge.kts similarity index 100% rename from Task/Stream-merge/Kotlin/stream-merge.kotlin rename to Task/Stream-merge/Kotlin/stream-merge.kts diff --git a/Task/Stream-merge/Rust/stream-merge.rs b/Task/Stream-merge/Rust/stream-merge.rs new file mode 100644 index 0000000000..fce1392387 --- /dev/null +++ b/Task/Stream-merge/Rust/stream-merge.rs @@ -0,0 +1,81 @@ +use std::cmp::Ordering; + +fn merge2(c1: &[T], c2: &[T], action: F) { + let mut i1 = 0; + let mut i2 = 0; + + while i1 < c1.len() && i2 < c2.len() { + if c1[i1] <= c2[i2] { + action(c1[i1]); + i1 += 1; + } else { + action(c2[i2]); + i2 += 1; + } + } + + while i1 < c1.len() { + action(c1[i1]); + i1 += 1; + } + + while i2 < c2.len() { + action(c2[i2]); + i2 += 1; + } +} + +fn merge_n(action: F, all: &[&[T]]) { + let mut vit: Vec<(usize, usize)> = all.iter().map(|c| (0, c.len())).collect(); + + loop { + let mut done = true; + let mut least: Option = None; + + for (i, &(start, end)) in vit.iter().enumerate() { + if start < end { + if least.is_none() { + least = Some(i); + } else { + if let Some(l) = least { + if all[i][start].cmp(&all[l][vit[l].0]) == Ordering::Less { + least = Some(i); + } + } + } + } + } + + if let Some(l) = least { + if vit[l].0 < vit[l].1 { + done = false; + action(all[l][vit[l].0]); + vit[l].0 += 1; + } + } + + if done { + break; + } + } +} + + +fn display(num: i32) { + print!("{} ", num); +} + +fn main() { + let v1 = vec![0, 3, 6]; + let v2 = vec![1, 4, 7]; + let v3 = vec![2, 5, 8]; + + merge2(&v2, &v1, display); + println!(); + + merge_n(display, &[&v1]); + println!(); + + merge_n(display, &[&v3, &v2, &v1]); + println!(); +} diff --git a/Task/Stream-merge/Zig/stream-merge.zig b/Task/Stream-merge/Zig/stream-merge.zig new file mode 100644 index 0000000000..866ee718e8 --- /dev/null +++ b/Task/Stream-merge/Zig/stream-merge.zig @@ -0,0 +1,94 @@ +const std = @import("std"); +const print = std.debug.print; +const Order = std.math.Order; + +// Generic merge function for two sorted slices +fn merge2(comptime T: type, c1: []const T, c2: []const T, action: *const fn (T) void) void { + var idx1: usize = 0; + var idx2: usize = 0; + + while (idx1 < c1.len and idx2 < c2.len) { + if (std.math.order(c1[idx1], c2[idx2]) != .gt) { + action(c1[idx1]); + idx1 += 1; + } else { + action(c2[idx2]); + idx2 += 1; + } + } + + while (idx1 < c1.len) { + action(c1[idx1]); + idx1 += 1; + } + + while (idx2 < c2.len) { + action(c2[idx2]); + idx2 += 1; + } +} + +// Generic merge function for n sorted slices +fn mergeN(comptime T: type, action: *const fn (T) void, all: []const []const T, allocator: std.mem.Allocator) !void { + // Create iterator tracking (current_index, end_index) for each slice + var vit = try allocator.alloc(struct { start: usize, end: usize }, all.len); + defer allocator.free(vit); + + // Initialize iterators + for (all, 0..) |slice, i| { + vit[i] = .{ .start = 0, .end = slice.len }; + } + + while (true) { + var done = true; + var least: ?usize = null; + + // Find the slice with the smallest current element + for (vit, 0..) |*iter, i| { + if (iter.start < iter.end) { + if (least == null) { + least = i; + } else if (least) |l| { + if (std.math.order(all[i][iter.start], all[l][vit[l].start]) == .lt) { + least = i; + } + } + } + } + + if (least) |l| { + if (vit[l].start < vit[l].end) { + done = false; + action(all[l][vit[l].start]); + vit[l].start += 1; + } + } + + if (done) { + break; + } + } +} + +fn display(num: i32) void { + print("{d} ", .{num}); +} + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + const allocator = gpa.allocator(); + + const v1 = [_]i32{ 0, 3, 6 }; + const v2 = [_]i32{ 1, 4, 7 }; + const v3 = [_]i32{ 2, 5, 8 }; + + merge2(i32, &v2, &v1, display); + print("\n" , .{}); + + try mergeN(i32, display, &[_][]const i32{&v1}, allocator); + print("\n" , .{}); + + try mergeN(i32, display, &[_][]const i32{ &v3, &v2, &v1 }, allocator); + print("\n" , .{}); +} diff --git a/Task/String-append/Ada/string-append.ada b/Task/String-append/Ada/string-append.adb similarity index 100% rename from Task/String-append/Ada/string-append.ada rename to Task/String-append/Ada/string-append.adb diff --git a/Task/String-append/ArkScript/string-append.ark b/Task/String-append/ArkScript/string-append.ark new file mode 100644 index 0000000000..19856313f3 --- /dev/null +++ b/Task/String-append/ArkScript/string-append.ark @@ -0,0 +1,2 @@ +(let s "12345678") +(print (+ s "9!")) diff --git a/Task/String-append/Arturo/string-append.arturo b/Task/String-append/Arturo/string-append.arturo index 155606d74f..137f1a65b3 100644 --- a/Task/String-append/Arturo/string-append.arturo +++ b/Task/String-append/Arturo/string-append.arturo @@ -1,10 +1,10 @@ print join ["Hello" "World"] -a: new "Hello" +a: "Hello" 'a ++ "World" print a -b: new "Hello" +b: "Hello" append 'b "World" print b diff --git a/Task/String-append/COBOL/string-append.cobol b/Task/String-append/COBOL/string-append.cob similarity index 100% rename from Task/String-append/COBOL/string-append.cobol rename to Task/String-append/COBOL/string-append.cob diff --git a/Task/String-append/Crystal/string-append.cr b/Task/String-append/Crystal/string-append.cr new file mode 100644 index 0000000000..e3f7c817f5 --- /dev/null +++ b/Task/String-append/Crystal/string-append.cr @@ -0,0 +1,3 @@ +s = "hello" +s += " world!" +p s diff --git a/Task/String-append/Delphi/string-append.delphi b/Task/String-append/Delphi/string-append.pas similarity index 100% rename from Task/String-append/Delphi/string-append.delphi rename to Task/String-append/Delphi/string-append.pas diff --git a/Task/String-append/DuckDB/string-append-1.duckdb b/Task/String-append/DuckDB/string-append-1.duckdb new file mode 100644 index 0000000000..3de0351a7b --- /dev/null +++ b/Task/String-append/DuckDB/string-append-1.duckdb @@ -0,0 +1,8 @@ +with recursive t(i, s) as ( + select 0, 'foo' + union all + select i+1, s || 'bar' + from t + where i < 1) +select last(s order by i) as s +from t; diff --git a/Task/String-append/DuckDB/string-append-2.duckdb b/Task/String-append/DuckDB/string-append-2.duckdb new file mode 100644 index 0000000000..0a2fcf1c67 --- /dev/null +++ b/Task/String-append/DuckDB/string-append-2.duckdb @@ -0,0 +1,2 @@ +set variable s = 'Hello'; +set variable s = getvariable('s') || ' world'; diff --git a/Task/String-append/Elena/string-append.elena b/Task/String-append/Elena/string-append.elena index 502ee19774..907ce0232e 100644 --- a/Task/String-append/Elena/string-append.elena +++ b/Task/String-append/Elena/string-append.elena @@ -1,9 +1,9 @@ import extensions'text; -public program() +public Program() { var s := StringWriter.load("Hello"); s.append(" World"); - console.writeLine(s).readChar() + Console.writeLine(s).readChar() } diff --git a/Task/String-append/Elixir/string-append.elixir b/Task/String-append/Elixir/string-append.ex similarity index 100% rename from Task/String-append/Elixir/string-append.elixir rename to Task/String-append/Elixir/string-append.ex diff --git a/Task/String-append/Emacs-Lisp/string-append-1.l b/Task/String-append/Emacs-Lisp/string-append-1.el similarity index 100% rename from Task/String-append/Emacs-Lisp/string-append-1.l rename to Task/String-append/Emacs-Lisp/string-append-1.el diff --git a/Task/String-append/Emacs-Lisp/string-append-2.l b/Task/String-append/Emacs-Lisp/string-append-2.el similarity index 100% rename from Task/String-append/Emacs-Lisp/string-append-2.l rename to Task/String-append/Emacs-Lisp/string-append-2.el diff --git a/Task/String-append/Emacs-Lisp/string-append-3.l b/Task/String-append/Emacs-Lisp/string-append-3.el similarity index 100% rename from Task/String-append/Emacs-Lisp/string-append-3.l rename to Task/String-append/Emacs-Lisp/string-append-3.el diff --git a/Task/String-append/Euphoria/string-append.euphoria b/Task/String-append/Euphoria/string-append.eu similarity index 100% rename from Task/String-append/Euphoria/string-append.euphoria rename to Task/String-append/Euphoria/string-append.eu diff --git a/Task/String-append/FutureBasic/string-append.basic b/Task/String-append/FutureBasic/string-append-1.basic similarity index 100% rename from Task/String-append/FutureBasic/string-append.basic rename to Task/String-append/FutureBasic/string-append-1.basic diff --git a/Task/String-append/FutureBasic/string-append-2.basic b/Task/String-append/FutureBasic/string-append-2.basic new file mode 100644 index 0000000000..4291c02394 --- /dev/null +++ b/Task/String-append/FutureBasic/string-append-2.basic @@ -0,0 +1,3 @@ +CFStringRef string = @"Hello, " +string = concat( string, @"World!" ) +print string diff --git a/Task/String-append/Gleam/string-append.gleam b/Task/String-append/Gleam/string-append.gleam new file mode 100644 index 0000000000..1ca6b27a8f --- /dev/null +++ b/Task/String-append/Gleam/string-append.gleam @@ -0,0 +1,2 @@ +let s = "Hello" + s <> " world" diff --git a/Task/String-append/Julia/string-append.julia b/Task/String-append/Julia/string-append.jl similarity index 100% rename from Task/String-append/Julia/string-append.julia rename to Task/String-append/Julia/string-append.jl diff --git a/Task/String-append/Kotlin/string-append.kotlin b/Task/String-append/Kotlin/string-append.kts similarity index 100% rename from Task/String-append/Kotlin/string-append.kotlin rename to Task/String-append/Kotlin/string-append.kts diff --git a/Task/String-append/Langur/string-append.langur b/Task/String-append/Langur/string-append.langur index 3779c2b4ae..8a5ec77faa 100644 --- a/Task/String-append/Langur/string-append.langur +++ b/Task/String-append/Langur/string-append.langur @@ -1,3 +1,3 @@ -var .s = "no more " -.s ~= "foo bars" -writeln .s +var s = "no more " +s ~= "foo bars" +writeln s diff --git a/Task/String-append/M2000-Interpreter/string-append.m2000 b/Task/String-append/M2000-Interpreter/string-append.m2000 index 5048aa1da9..cbdc5cb547 100644 --- a/Task/String-append/M2000-Interpreter/string-append.m2000 +++ b/Task/String-append/M2000-Interpreter/string-append.m2000 @@ -7,6 +7,8 @@ a$+="(one)" Print a$ Document b$ +b$="1234" +Clear b$ ' use Clear to empty document b$="ok" b$="(one)" Print b$ diff --git a/Task/String-append/OCaml/string-append.ocaml b/Task/String-append/OCaml/string-append.ml similarity index 100% rename from Task/String-append/OCaml/string-append.ocaml rename to Task/String-append/OCaml/string-append.ml diff --git a/Task/String-append/PascalABC.NET/string-append.pas b/Task/String-append/PascalABC.NET/string-append.pas new file mode 100644 index 0000000000..25828b5648 --- /dev/null +++ b/Task/String-append/PascalABC.NET/string-append.pas @@ -0,0 +1,6 @@ +begin + var s := 'Pascal'; + s += 'ABC'; + s += '.NET'; + s.Println; +end. diff --git a/Task/String-append/Pluto/string-append.pluto b/Task/String-append/Pluto/string-append.pluto new file mode 100644 index 0000000000..b2717be32b --- /dev/null +++ b/Task/String-append/Pluto/string-append.pluto @@ -0,0 +1,3 @@ +local s = "Rosetta" +s ..= " Code" +print(s) diff --git a/Task/String-append/PowerShell/string-append.psh b/Task/String-append/PowerShell/string-append.ps1 similarity index 100% rename from Task/String-append/PowerShell/string-append.psh rename to Task/String-append/PowerShell/string-append.ps1 diff --git a/Task/String-append/RISC-V-Assembly/string-append.asm b/Task/String-append/RISC-V-Assembly/string-append.asm new file mode 100644 index 0000000000..7106bc3a28 --- /dev/null +++ b/Task/String-append/RISC-V-Assembly/string-append.asm @@ -0,0 +1,115 @@ +# riscv assembly raspberry pico2 rp2350 +# program appstring.s +# connexion putty com3 +/*********************************************/ +/* CONSTANTES */ +/********************************************/ +/* for this file see risc-v task include a file */ +.include "../../constantesRiscv.inc" +.equ BUFFERSIZE, 100 +/*******************************************/ +/* INITIALED DATAS */ +/*******************************************/ +.data +szMessStart: .asciz "Program riscv start.\r\n" +szMessEndOk: .asciz "Program riscv end OK.\r\n" +szCariageReturn: .asciz "\r\n" + +szMessString: .asciz "String :\n" +szString1: .asciz "Alphabet : " +sComplement: .fill BUFFERSIZE,1,0 +szString2: .asciz "abcdefghijklmnopqrstuvwxyz" + +.align 2 +/*******************************************/ +/* UNINITIALED DATA */ +/*******************************************/ +.bss +.align 2 + +/**********************************************/ +/* SECTION CODE */ +/**********************************************/ +.text +.global main + +main: + call stdio_init_all # général init +1: # start loop connexion + li a0,0 # raz argument register + call tud_cdc_n_connected # waiting for USB connection + beqz a0,1b # return code = zero ? + + la a0,szMessStart # message address + call writeString # display message + + la a0,szMessString # message address + call writeString # display message + la a0,szString1 # message address + call writeString # display message + la a0,szCariageReturn # message address + call writeString # display message + + la a0,szMessString # message address + call writeString # display message + la a0,szString2 # message address + call writeString # display message + la a0,szCariageReturn # message address + call writeString # display message + + la a0,szString1 + la a1,szString2 + call append + + la a0,szMessString # message address + call writeString # display message + la a0,szString1 # message address + call writeString # display message + la a0,szCariageReturn # message address + call writeString # display message + + la a0,szMessEndOk # message address + call writeString # display message + call getchar +100: # final loop + j 100b + +/*********************************************/ +/* add string to string */ +/*********************************************/ +/* no verfication size complement buffer */ +/* a0 contains address String 1 */ +/* a1 contains address String 2 */ +append: + addi sp, sp, -4 + sw ra, 0(sp) + li t0,0 # counter byte string 1 +1: + add t1,a0,t0 + lbu t2,(t1) # load byte string 1 + beqz t2,2f # zero final ? + addi t0,t0,1 # no -> increment counter + j 1b # loop +2: + li t3, 0 # counter byte string 2 +3: + add t4,a1,t3 + lbu t5,(t4) # load byte string 2 + add t1,a0,t0 + sb t5,(t1) # store byte string 1 + beqz t5,100f # zero final ? -> end + addi t3,t3,1 # increment counter + addi t0,t0,1 + j 3b # end loop + +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret + + +/************************************/ +/* file include Fonctions */ +/***********************************/ +/* for this file see risc-v task include a file */ +.include "../../includeFunctions.s" diff --git a/Task/String-append/Retro/string-append.retro b/Task/String-append/Retro/string-append.retro new file mode 100644 index 0000000000..1aadba0845 --- /dev/null +++ b/Task/String-append/Retro/string-append.retro @@ -0,0 +1,3 @@ +'Hello '_World +s:append s:put nl +Hello World diff --git a/Task/String-append/Rust/string-append-1.rust b/Task/String-append/Rust/string-append-1.rs similarity index 100% rename from Task/String-append/Rust/string-append-1.rust rename to Task/String-append/Rust/string-append-1.rs diff --git a/Task/String-append/Rust/string-append-2.rust b/Task/String-append/Rust/string-append-2.rs similarity index 100% rename from Task/String-append/Rust/string-append-2.rust rename to Task/String-append/Rust/string-append-2.rs diff --git a/Task/String-append/Rye/string-append.rye b/Task/String-append/Rye/string-append.rye new file mode 100644 index 0000000000..0a5d5fa843 --- /dev/null +++ b/Task/String-append/Rye/string-append.rye @@ -0,0 +1,2 @@ +var 's "hello" +append! " world" 's diff --git a/Task/String-append/VBScript/string-append.vb b/Task/String-append/VBScript/string-append.vbs similarity index 100% rename from Task/String-append/VBScript/string-append.vb rename to Task/String-append/VBScript/string-append.vbs diff --git a/Task/String-case/Ada/string-case.ada b/Task/String-case/Ada/string-case.adb similarity index 100% rename from Task/String-case/Ada/string-case.ada rename to Task/String-case/Ada/string-case.adb diff --git a/Task/String-case/ArkScript/string-case.ark b/Task/String-case/ArkScript/string-case.ark new file mode 100644 index 0000000000..df08409105 --- /dev/null +++ b/Task/String-case/ArkScript/string-case.ark @@ -0,0 +1,5 @@ +(import std.String) + +(let s "alphaBETA") +(print (string:toUpper s)) +(print (string:toLower s)) diff --git a/Task/String-case/AutoIt/string-case.autoit b/Task/String-case/AutoIt/string-case.au3 similarity index 100% rename from Task/String-case/AutoIt/string-case.autoit rename to Task/String-case/AutoIt/string-case.au3 diff --git a/Task/String-case/Ballerina/string-case.ballerina b/Task/String-case/Ballerina/string-case.ballerina new file mode 100644 index 0000000000..f84adad107 --- /dev/null +++ b/Task/String-case/Ballerina/string-case.ballerina @@ -0,0 +1,7 @@ +import ballerina/io; + +public function main() { + string s = "alphaBETA"; + io:println(s.toUpperAscii()); + io:println(s.toLowerAscii()); +} diff --git a/Task/String-case/COBOL/string-case-1.cobol b/Task/String-case/COBOL/string-case-1.cob similarity index 100% rename from Task/String-case/COBOL/string-case-1.cobol rename to Task/String-case/COBOL/string-case-1.cob diff --git a/Task/String-case/COBOL/string-case-2.cobol b/Task/String-case/COBOL/string-case-2.cob similarity index 100% rename from Task/String-case/COBOL/string-case-2.cobol rename to Task/String-case/COBOL/string-case-2.cob diff --git a/Task/String-case/Crystal/string-case-1.crystal b/Task/String-case/Crystal/string-case-1.cr similarity index 100% rename from Task/String-case/Crystal/string-case-1.crystal rename to Task/String-case/Crystal/string-case-1.cr diff --git a/Task/String-case/Crystal/string-case-2.crystal b/Task/String-case/Crystal/string-case-2.cr similarity index 100% rename from Task/String-case/Crystal/string-case-2.crystal rename to Task/String-case/Crystal/string-case-2.cr diff --git a/Task/String-case/Delphi/string-case.delphi b/Task/String-case/Delphi/string-case.pas similarity index 100% rename from Task/String-case/Delphi/string-case.delphi rename to Task/String-case/Delphi/string-case.pas diff --git a/Task/String-case/DuckDB/string-case.duckdb b/Task/String-case/DuckDB/string-case.duckdb new file mode 100644 index 0000000000..5a95354989 --- /dev/null +++ b/Task/String-case/DuckDB/string-case.duckdb @@ -0,0 +1 @@ +select 'alphaBETA' as s, lower(s), upper(s); diff --git a/Task/String-case/Ecstasy/string-case.ecstasy b/Task/String-case/Ecstasy/string-case.ecstasy new file mode 100644 index 0000000000..4ef76af802 --- /dev/null +++ b/Task/String-case/Ecstasy/string-case.ecstasy @@ -0,0 +1,7 @@ +module test { + void run() { + @Inject Console console; + console.print($"{"alphaBETA".toLowercase()=}"); + console.print($"{"alphaBETA".toUppercase()=}"); + } +} diff --git a/Task/String-case/Ed/string-case.ed b/Task/String-case/Ed/string-case.ed new file mode 100644 index 0000000000..3bbad60ce3 --- /dev/null +++ b/Task/String-case/Ed/string-case.ed @@ -0,0 +1,11 @@ +1s/a/A/g +1s/l/L/ +1s/p/P/ +1s/h/H/ +2s/B/b/ +2s/E/e/ +2s/T/t/ +2s/A/a/ +3s/a/A/ +%p +Q diff --git a/Task/String-case/Elena/string-case.elena b/Task/String-case/Elena/string-case.elena index cdeb06961f..33f3f3172c 100644 --- a/Task/String-case/Elena/string-case.elena +++ b/Task/String-case/Elena/string-case.elena @@ -1,10 +1,10 @@ import system'culture; -public program() +public Program() { string s1 := "alphaBETA"; - console.writeLine(s1.toLower(currentLocale)); - console.writeLine(s1.toUpper(currentLocale)); - console.readChar() + Console.writeLine(s1.toLower(currentLocale)); + Console.writeLine(s1.toUpper(currentLocale)); + Console.readChar() } diff --git a/Task/String-case/Elixir/string-case-1.elixir b/Task/String-case/Elixir/string-case-1.ex similarity index 100% rename from Task/String-case/Elixir/string-case-1.elixir rename to Task/String-case/Elixir/string-case-1.ex diff --git a/Task/String-case/Elixir/string-case-2.elixir b/Task/String-case/Elixir/string-case-2.ex similarity index 100% rename from Task/String-case/Elixir/string-case-2.elixir rename to Task/String-case/Elixir/string-case-2.ex diff --git a/Task/String-case/Julia/string-case-1.julia b/Task/String-case/Julia/string-case-1.jl similarity index 100% rename from Task/String-case/Julia/string-case-1.julia rename to Task/String-case/Julia/string-case-1.jl diff --git a/Task/String-case/Julia/string-case-2.julia b/Task/String-case/Julia/string-case-2.jl similarity index 100% rename from Task/String-case/Julia/string-case-2.julia rename to Task/String-case/Julia/string-case-2.jl diff --git a/Task/String-case/Kotlin/string-case.kotlin b/Task/String-case/Kotlin/string-case.kotlin deleted file mode 100644 index 688c54d3c8..0000000000 --- a/Task/String-case/Kotlin/string-case.kotlin +++ /dev/null @@ -1,9 +0,0 @@ -// version 1.0.6 - -fun main(args: Array) { - val s = "alphaBETA" - println(s.toUpperCase()) - println(s.toLowerCase()) - println(s.capitalize()) - println(s.decapitalize()) -} diff --git a/Task/String-case/Kotlin/string-case.kts b/Task/String-case/Kotlin/string-case.kts new file mode 100644 index 0000000000..e7543e7471 --- /dev/null +++ b/Task/String-case/Kotlin/string-case.kts @@ -0,0 +1,9 @@ +// version 2.3.0 + +fun main() { + val s = "alphaBETA" + println(s.uppercase()) + println(s.lowercase()) + println(s.replaceFirstChar{ it.uppercase() }) + println(s.replaceFirstChar{ it.lowercase() }) +} diff --git a/Task/String-case/Maxima/string-case.maxima b/Task/String-case/Maxima/string-case.maxima index bff11cfbfc..b2db532214 100644 --- a/Task/String-case/Maxima/string-case.maxima +++ b/Task/String-case/Maxima/string-case.maxima @@ -1,2 +1,4 @@ -supcase('alphaBETA'); -sdowncase('alphaBETA'); +str: "alphaBETA"$ +supcase(str); +sdowncase(str); +sinvertcase(str); diff --git a/Task/String-case/OCaml/string-case.ocaml b/Task/String-case/OCaml/string-case.ml similarity index 100% rename from Task/String-case/OCaml/string-case.ocaml rename to Task/String-case/OCaml/string-case.ml diff --git a/Task/String-case/PascalABC.NET/string-case.pas b/Task/String-case/PascalABC.NET/string-case.pas new file mode 100644 index 0000000000..46796040b3 --- /dev/null +++ b/Task/String-case/PascalABC.NET/string-case.pas @@ -0,0 +1,4 @@ +## +var s := 'exAmpLe sTrinG'; +s.ToLower.Println; +s.ToUpper.Println; diff --git a/Task/String-case/PowerShell/string-case.psh b/Task/String-case/PowerShell/string-case.ps1 similarity index 100% rename from Task/String-case/PowerShell/string-case.psh rename to Task/String-case/PowerShell/string-case.ps1 diff --git a/Task/String-case/Python/string-case-1.py b/Task/String-case/Python/string-case-1.py deleted file mode 100644 index 70fbdce571..0000000000 --- a/Task/String-case/Python/string-case-1.py +++ /dev/null @@ -1,11 +0,0 @@ -s = "alphaBETA" -print s.upper() # => "ALPHABETA" -print s.lower() # => "alphabeta" - -print s.swapcase() # => "ALPHAbeta" - -print "fOo bAR".capitalize() # => "Foo bar" -print "fOo bAR".title() # => "Foo Bar" - -import string -print string.capwords("fOo bAR") # => "Foo Bar" diff --git a/Task/String-case/Python/string-case-2.py b/Task/String-case/Python/string-case-2.py deleted file mode 100644 index f444c5a895..0000000000 --- a/Task/String-case/Python/string-case-2.py +++ /dev/null @@ -1,2 +0,0 @@ -print "foo's bar".title() # => "Foo'S Bar" -print string.capwords("foo's bar") # => "Foo's Bar" diff --git a/Task/String-case/Python/string-case.py b/Task/String-case/Python/string-case.py new file mode 100644 index 0000000000..5cd86badaf --- /dev/null +++ b/Task/String-case/Python/string-case.py @@ -0,0 +1,20 @@ +import string + +EXAMPLE_STRINGS = [ + "alphaBETA", + "ação", + "o'hare O'HARE o’hare don't", + "Stroßbùrri", + "ĥåçýджк", + "DŽLjnj", +] + +for s in EXAMPLE_STRINGS: + print(f"original : {s}") + print(f"upper : {s.upper()}") + print(f"lower : {s.lower()}") + print(f"capitalize : {s.capitalize()}") + print(f"title : {s.title()}") + print(f"swapcase : {s.swapcase()}") + print(f"casefold : {s.casefold()}") + print(f"string.capwords : {string.capwords(s, sep=None)}\n") diff --git a/Task/String-case/REBOL/string-case.rebol b/Task/String-case/Rebol/string-case.rebol similarity index 100% rename from Task/String-case/REBOL/string-case.rebol rename to Task/String-case/Rebol/string-case.rebol diff --git a/Task/String-case/Rust/string-case.rust b/Task/String-case/Rust/string-case.rs similarity index 100% rename from Task/String-case/Rust/string-case.rust rename to Task/String-case/Rust/string-case.rs diff --git a/Task/String-case/Rye/string-case.rye b/Task/String-case/Rye/string-case.rye new file mode 100644 index 0000000000..b7d1e64585 --- /dev/null +++ b/Task/String-case/Rye/string-case.rye @@ -0,0 +1,2 @@ +upper "alphaBETA" +lower "alphaBETA" diff --git a/Task/String-case/Scheme/string-case-1.ss b/Task/String-case/Scheme/string-case-1.scm similarity index 100% rename from Task/String-case/Scheme/string-case-1.ss rename to Task/String-case/Scheme/string-case-1.scm diff --git a/Task/String-case/Scheme/string-case-2.ss b/Task/String-case/Scheme/string-case-2.scm similarity index 100% rename from Task/String-case/Scheme/string-case-2.ss rename to Task/String-case/Scheme/string-case-2.scm diff --git a/Task/String-case/Uiua/string-case.uiua b/Task/String-case/Uiua/string-case.uiua new file mode 100644 index 0000000000..5203ae2d2e --- /dev/null +++ b/Task/String-case/Uiua/string-case.uiua @@ -0,0 +1,4 @@ +¯"alphaBETA" # swapcase +⌵"alphaBETA" # upper +¯⌵"alphaBETA" # lower +±"alphaBETA123" # case mask 1=upper, -1=lower, 0=neither diff --git a/Task/String-case/VBScript/string-case.vb b/Task/String-case/VBScript/string-case.vbs similarity index 100% rename from Task/String-case/VBScript/string-case.vb rename to Task/String-case/VBScript/string-case.vbs diff --git a/Task/String-case/Zig/string-case.zig b/Task/String-case/Zig/string-case.zig index 95efdd7a0b..85c281716e 100644 --- a/Task/String-case/Zig/string-case.zig +++ b/Task/String-case/Zig/string-case.zig @@ -5,12 +5,12 @@ pub fn main() !void { const string = "alphaBETA"; var lower: [string.len]u8 = undefined; var upper: [string.len]u8 = undefined; - for (string) |char, i| { - lower[i] = std.ascii.toLower(char); - upper[i] = std.ascii.toUpper(char); + for (string, &lower, &upper) |char, *lo, *up| { + lo.* = std.ascii.toLower(char); + up.* = std.ascii.toUpper(char); } try stdout_wr.print("lower: {s}\n", .{lower}); try stdout_wr.print("upper: {s}\n", .{upper}); - // TODO use https://github.com/jecolon/zigstr + // TODO use https://codeberg.org/dude_the_builder/zigstr } diff --git a/Task/String-comparison/ALGOL-68/string-comparison.alg b/Task/String-comparison/ALGOL-68/string-comparison.alg index c2f5c69800..1873137726 100644 --- a/Task/String-comparison/ALGOL-68/string-comparison.alg +++ b/Task/String-comparison/ALGOL-68/string-comparison.alg @@ -1,4 +1,4 @@ -STRING a := "abc ", b := "ABC "; +STRING sa := "abc ", sb := "ABC "; # when comparing strings, Algol 68 ignores trailing blanks # # so e.g. "a" = "a " is true # @@ -8,15 +8,15 @@ PROC test = ( BOOL condition, STRING message )VOID: IF condition THEN print( ( message, newline ) ) FI; # equality? # -test( a = b, "a = b" ); +test( sa = sb, "sa = sb" ); # inequality? # -test( a /= b, "a not = b" ); +test( sa /= sb, "sa not = sb" ); # lexically ordered before? # -test( a < b, "a < b" ); +test( sa < sb, "sa < sb" ); # lexically ordered after? # -test( a > b, "a > b" ); +test( sa >s b, "sa > sb" ); # Algol 68's builtin string comparison operators are case-sensitive. # # To perform case insensitive comparisons, procedures or operators # @@ -50,7 +50,7 @@ PROC caseless comparison = ( STRING a, b )INT: PROC equal ignoring case = ( STRING a, b )BOOL: caseless comparison( a, b ) = 0; # similar procedures for inequality and lexical ording ... # -test( equal ignoring case( a, b ), "a = b (ignoring case)" ); +test( equal ignoring case( sa, sb ), "sa = sb (ignoring case)" ); # Algol 68 is strongly typed - strings cannot be compared to e.g. integers # @@ -61,7 +61,7 @@ test( equal ignoring case( a, b ), "a = b (ignoring case)" ); # Algol 68 also has <= and >= comparison operators for testing for # # "lexically before or equal" and "lexically after or equal" # -test( a <= b, "a <= b" ); -test( a >= b, "a >= b" ); +test( sa <= sb, "sa <= sb" ); +test( sa >= sb, "sa >= sb" ) # there are no other forms of string comparison builtin to Algol 68 # diff --git a/Task/String-comparison/Ada/string-comparison.ada b/Task/String-comparison/Ada/string-comparison.adb similarity index 100% rename from Task/String-comparison/Ada/string-comparison.ada rename to Task/String-comparison/Ada/string-comparison.adb diff --git a/Task/String-comparison/COBOL/string-comparison-1.cobol b/Task/String-comparison/COBOL/string-comparison-1.cob similarity index 100% rename from Task/String-comparison/COBOL/string-comparison-1.cobol rename to Task/String-comparison/COBOL/string-comparison-1.cob diff --git a/Task/String-comparison/COBOL/string-comparison-2.cobol b/Task/String-comparison/COBOL/string-comparison-2.cob similarity index 100% rename from Task/String-comparison/COBOL/string-comparison-2.cobol rename to Task/String-comparison/COBOL/string-comparison-2.cob diff --git a/Task/String-comparison/COBOL/string-comparison-3.cobol b/Task/String-comparison/COBOL/string-comparison-3.cob similarity index 100% rename from Task/String-comparison/COBOL/string-comparison-3.cobol rename to Task/String-comparison/COBOL/string-comparison-3.cob diff --git a/Task/String-comparison/Delphi/string-comparison.delphi b/Task/String-comparison/Delphi/string-comparison.pas similarity index 100% rename from Task/String-comparison/Delphi/string-comparison.delphi rename to Task/String-comparison/Delphi/string-comparison.pas diff --git a/Task/String-comparison/DuckDB/string-comparison.duckdb b/Task/String-comparison/DuckDB/string-comparison.duckdb new file mode 100644 index 0000000000..052f767117 --- /dev/null +++ b/Task/String-comparison/DuckDB/string-comparison.duckdb @@ -0,0 +1,10 @@ +select s, + t, + s == t, + s != t, + s < t, + s > t, + upper(s) = upper(uppers) as "case insenstive", + '2' < '1e10', + s ilike uppers +from (select 'abc' as s, 'def' as t, 'ABC' as uppers ); diff --git a/Task/String-comparison/EMal/string-comparison.emal b/Task/String-comparison/EMal/string-comparison.emal new file mode 100644 index 0000000000..c9154b099d --- /dev/null +++ b/Task/String-comparison/EMal/string-comparison.emal @@ -0,0 +1,15 @@ +fun compare ← void by text a, text b + writeLine("Comparing `", a, "` and `", b, "`:") + text la ← a.lower() + text lb ← b.lower() + writeLine(" `", a, "` æ `", b, "` case sensitively: ", a æ b, ", case insensitively: ", la æ lb) + writeLine(" `", a, "` ≠ `", b, "` case sensitively: ", a ≠ b, ", case insensitively: ", la ≠ lb) + writeLine(" `", a, "` ◇ `", b, "` case sensitively: ", a ◇ b, ", case insensitively: ", la ◇ lb) + writeLine(" `", a, "` < `", b, "` case sensitively: ", a < b, ", case insensitively: ", la < lb) + writeLine(" `", a, "` > `", b, "` case sensitively: ", a > b, ", case insensitively: ", la > lb) + writeLine(" `", a, "` ≤ `", b, "` case sensitively: ", a ≤ b, ", case insensitively: ", la ≤ lb) + writeLine(" `", a, "` ≥ `", b, "` case sensitively: ", a ≥ b, ", case insensitively: ", la ≥ lb) +end +List samples ← Pair[text%text("Hello" ⇒ "Hello"), text%text("5" ⇒ "5.0"), + text%text("java" ⇒ "Java"), text%text("ĴÃVÁ" ⇒ "ĴÃVÁ"), text%text("ĴÃVÁ" ⇒ "ĵãvá")] +samples.list( s2) { + console.print($"{s1} > {s2}"); + } + + // How to achieve both case sensitive comparisons and case + // insensitive comparisons within the language + + if (CaseInsensitive.areEqual(s1, s2)) { + console.print($"{s1} == {s2} (case-insensitive)"); + } else { + console.print($"{s1} != {s2} (case-insensitive)"); + } + + switch (CaseInsensitive.compare(s1, s2)) { + case Lesser: + console.print($"{s1} < {s2} (case-insensitive)"); + break; + case Equal: + // already covered this one above + assert CaseInsensitive.areEqual(s1, s2); + break; + case Greater: + console.print($"{s1} > {s2} (case-insensitive)"); + break; + } + } + } +} diff --git a/Task/String-comparison/Ed/string-comparison.ed b/Task/String-comparison/Ed/string-comparison.ed new file mode 100644 index 0000000000..e83aee2079 --- /dev/null +++ b/Task/String-comparison/Ed/string-comparison.ed @@ -0,0 +1,11 @@ +# by Artyom Bologov +H +1s/$/|/ +,j +t0 +1s/^\(.*\)|\1$/Strings are equal case-sensitively/ +1v/Strings are equal case-sensitively/s/.*/Strings are not equal case-sensitively/ +2s/^\(.*\)|\1$/Strings are equal case-insensitively/i +2v/Strings are equal case-insensitively/s/.*/Strings are not equal case-insensitively/ +,p +Q diff --git a/Task/String-comparison/Elena/string-comparison.elena b/Task/String-comparison/Elena/string-comparison.elena index b2ac089db6..60e9f04cff 100644 --- a/Task/String-comparison/Elena/string-comparison.elena +++ b/Task/String-comparison/Elena/string-comparison.elena @@ -2,19 +2,19 @@ import extensions; compareStrings = (val1,val2) { - if (val1 == val2) { console.printLine("The strings ",val1," and ",val2," are equal") }; - if (val1 != val2) { console.printLine("The strings ",val1," and ",val2," are not equal") }; - if (val1 > val2) { console.printLine("The string ",val1," is lexically after than ",val2) }; - if (val1 < val2) { console.printLine("The string ",val1," is lexically before than ",val2) }; - if (val1 >= val2) { console.printLine("The string ",val1," is not lexically before than ",val2) }; - if (val1 <= val2) { console.printLine("The string ",val1," is not lexically after than ",val2) } + if (val1 == val2) { Console.printLine("The strings ",val1," and ",val2," are equal") }; + if (val1 != val2) { Console.printLine("The strings ",val1," and ",val2," are not equal") }; + if (val1 > val2) { Console.printLine("The string ",val1," is lexically after than ",val2) }; + if (val1 < val2) { Console.printLine("The string ",val1," is lexically before than ",val2) }; + if (val1 >= val2) { Console.printLine("The string ",val1," is not lexically before than ",val2) }; + if (val1 <= val2) { Console.printLine("The string ",val1," is not lexically after than ",val2) } }; -public program() +public Program() { var s1 := "this"; var s2 := "that"; compareStrings(s1,s2); - console.readChar() + Console.readChar() } diff --git a/Task/String-comparison/Elixir/string-comparison.elixir b/Task/String-comparison/Elixir/string-comparison.ex similarity index 100% rename from Task/String-comparison/Elixir/string-comparison.elixir rename to Task/String-comparison/Elixir/string-comparison.ex diff --git a/Task/String-comparison/Julia/string-comparison.julia b/Task/String-comparison/Julia/string-comparison.jl similarity index 100% rename from Task/String-comparison/Julia/string-comparison.julia rename to Task/String-comparison/Julia/string-comparison.jl diff --git a/Task/String-comparison/Kotlin/string-comparison.kotlin b/Task/String-comparison/Kotlin/string-comparison.kts similarity index 100% rename from Task/String-comparison/Kotlin/string-comparison.kotlin rename to Task/String-comparison/Kotlin/string-comparison.kts diff --git a/Task/String-comparison/PowerShell/string-comparison-1.psh b/Task/String-comparison/PowerShell/string-comparison-1.ps1 similarity index 100% rename from Task/String-comparison/PowerShell/string-comparison-1.psh rename to Task/String-comparison/PowerShell/string-comparison-1.ps1 diff --git a/Task/String-comparison/PowerShell/string-comparison-2.psh b/Task/String-comparison/PowerShell/string-comparison-2.ps1 similarity index 100% rename from Task/String-comparison/PowerShell/string-comparison-2.psh rename to Task/String-comparison/PowerShell/string-comparison-2.ps1 diff --git a/Task/String-comparison/RISC-V-Assembly/string-comparison.asm b/Task/String-comparison/RISC-V-Assembly/string-comparison.asm new file mode 100644 index 0000000000..6dcc8491bb --- /dev/null +++ b/Task/String-comparison/RISC-V-Assembly/string-comparison.asm @@ -0,0 +1,191 @@ +# riscv assembly raspberry pico2 rp2350 +# program compstring.s +# connexion putty com3 +/*********************************************/ +/* CONSTANTES */ +/********************************************/ +/* for this file see risc-v task include a file */ +.include "../../constantesRiscv.inc" + +/*******************************************/ +/* INITIALED DATAS */ +/*******************************************/ +.data +szMessStart: .asciz "Program riscv start.\r\n" +szCariageReturn: .asciz "\r\n" +szMessStringEqu: .asciz "The strings are equals.\n" +szMessStringNotEqu: .asciz "The strings are not equals.\n" + +szString1: .asciz "ABCDE" +szString2: .asciz "ABCDE" +szString3: .asciz "ABCFG" +szString4: .asciz "ABC" +szString5: .asciz "abcde" +.align 2 + +/*******************************************/ +/* UNINITIALED DATA */ +/*******************************************/ +.bss +.align 2 + +/**********************************************/ +/* SECTION CODE */ +/**********************************************/ +.text +.global main + +main: + call stdio_init_all # général init +1: # start loop connexion + li a0,0 # raz argument register + call tud_cdc_n_connected # waiting for USB connection + beqz a0,1b # return code = zero ? + + la a0,szMessStart # message address + call writeString # display message + + la a0,szString1 + la a1,szString2 + call Comparaison + + la a0,szString1 + la a1,szString3 + call Comparaison + + la a0,szString1 + la a1,szString4 + call Comparaison + + # case sensitive comparisons ABCDE et abcde + la a0,szString1 + la a1,szString5 + call Comparaison + + # case insensitive comparisons ABCDE et abcde + la a0,szString1 + la a1,szString5 + call comparStringsInsensitive + bnez a0,1f + la a0,szMessStringEqu + call writeString # display message + j 2f +1: + la a0,szMessStringNotEqu + call writeString # display message +2: + call getchar +100: # final loop + j 100b + +/*********************************************/ +/* comparaison */ +/*********************************************/ +/* a0 contains address String 1 */ +/* a1 contains address String 2 */ +Comparaison: + addi sp, sp, -4 + sw ra, 0(sp) + call comparStrings + bnez a0,1f + + la a0,szMessStringEqu + call writeString # display message + j 100f +1: + la a0,szMessStringNotEqu + call writeString # display message +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret +/************************************/ +/* Strings case sensitive comparisons */ +/************************************/ +/* a0 et ra1 contains the address of strings */ +/* return 0 in a0 if equals */ +/* return -1 if string a0 < string a1 */ +/* return 1 if string a0 > string a1 */ +comparStrings: # INFO: comparStrings + addi sp, sp, -4 + sw ra, 0(sp) + li t0,0 +1: + add t1,t0,a0 + lb t1,(t1) + add t2,t0,a1 + lb t2,(t2) + beq t1,t2,2f + bgt t1,t2,3f + blt t1,t2,4f +2: # egal + addi t0,t0,1 + bne t1,x0,1b # fin chaine + li a0,0 # egalité + j 100f +3: # plus haut + li a0,1 + j 100f +4: # plus bas + li a0,-1 + j 100f +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret +/************************************/ +/* Strings case insensitive comparisons */ +/************************************/ +/* a0 et a1 contains the address of strings */ +/* return 0 in a0 if equals */ +/* return -1 if string a0 < string a1 */ +/* return 1 if string a0 > string a1 */ +comparStringsInsensitive: # INFO: comparStringsInsensitive + addi sp, sp, -4 + sw ra, 0(sp) + li t0,0 +1: + add t1,t0,a0 + lb t1,(t1) + # majuscules --> minuscules byte string 1 + li t3,65 + blt t1,t3,2f + li t3,90 + bgt t1,t3,2f + addi t1,t1,32 +2: + add t2,t0,a1 + lb t2,(t2) + # majuscules --> minuscules byte string 2 + li t3,65 + blt t2,t3,3f + li t3,90 + bgt t2,t3,3f + addi t2,t2,32 +3: + + beq t1,t2,4f + bgt t1,t2,5f + blt t1,t2,6f +4: # egal + addi t0,t0,1 + bne t1,x0,1b # fin chaine + li a0,0 # egalité + j 100f +5: # plus haut + li a0,1 + j 100f +6: # plus bas + li a0,-1 + j 100f + +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret + +/************************************/ +/* file include Fonctions */ +/***********************************/ +/* for this file see risc-v task include a file */ +.include "../../includeFunctions.s" diff --git a/Task/String-comparison/Rust/string-comparison.rust b/Task/String-comparison/Rust/string-comparison.rs similarity index 100% rename from Task/String-comparison/Rust/string-comparison.rust rename to Task/String-comparison/Rust/string-comparison.rs diff --git a/Task/String-comparison/Scheme/string-comparison.ss b/Task/String-comparison/Scheme/string-comparison.scm similarity index 100% rename from Task/String-comparison/Scheme/string-comparison.ss rename to Task/String-comparison/Scheme/string-comparison.scm diff --git a/Task/String-concatenation/Ada/string-concatenation.ada b/Task/String-concatenation/Ada/string-concatenation.adb similarity index 100% rename from Task/String-concatenation/Ada/string-concatenation.ada rename to Task/String-concatenation/Ada/string-concatenation.adb diff --git a/Task/String-concatenation/ArkScript/string-concatenation.ark b/Task/String-concatenation/ArkScript/string-concatenation.ark new file mode 100644 index 0000000000..24485a7056 --- /dev/null +++ b/Task/String-concatenation/ArkScript/string-concatenation.ark @@ -0,0 +1,6 @@ +(let s "hello") +(print (+ s " world!")) + +(let w " there") +(let v (+ s w)) +(print v) diff --git a/Task/String-concatenation/Ballerina/string-concatenation.ballerina b/Task/String-concatenation/Ballerina/string-concatenation.ballerina new file mode 100644 index 0000000000..a23d763a1a --- /dev/null +++ b/Task/String-concatenation/Ballerina/string-concatenation.ballerina @@ -0,0 +1,8 @@ +import ballerina/io; + +public function main() { + string s = "Hello, "; + string t = "world!"; + io:println(s); + io:println(s + t); +} diff --git a/Task/String-concatenation/C/string-concatenation.c b/Task/String-concatenation/C/string-concatenation-1.c similarity index 100% rename from Task/String-concatenation/C/string-concatenation.c rename to Task/String-concatenation/C/string-concatenation-1.c diff --git a/Task/String-concatenation/C/string-concatenation-2.c b/Task/String-concatenation/C/string-concatenation-2.c new file mode 100644 index 0000000000..6fdf395d40 --- /dev/null +++ b/Task/String-concatenation/C/string-concatenation-2.c @@ -0,0 +1,14 @@ +#include + +LIB_GADGET_START + +Main + + String v="Mensaje lanzado al mar", w=Space(100); + Stack{ + Store ( w, Pad_c( Multi_cat(w, Upper( Str_tran_all(v,"lanzado","tirado",1)),\ + " adentro de una botella", NULL ), '-', 70 )); + } + puts(w); + Free secure v, w; +End diff --git a/Task/String-concatenation/COBOL/string-concatenation-1.cobol b/Task/String-concatenation/COBOL/string-concatenation-1.cob similarity index 100% rename from Task/String-concatenation/COBOL/string-concatenation-1.cobol rename to Task/String-concatenation/COBOL/string-concatenation-1.cob diff --git a/Task/String-concatenation/COBOL/string-concatenation-2.cobol b/Task/String-concatenation/COBOL/string-concatenation-2.cob similarity index 100% rename from Task/String-concatenation/COBOL/string-concatenation-2.cobol rename to Task/String-concatenation/COBOL/string-concatenation-2.cob diff --git a/Task/String-concatenation/COBOL/string-concatenation-3.cobol b/Task/String-concatenation/COBOL/string-concatenation-3.cob similarity index 100% rename from Task/String-concatenation/COBOL/string-concatenation-3.cobol rename to Task/String-concatenation/COBOL/string-concatenation-3.cob diff --git a/Task/String-concatenation/Crystal/string-concatenation.cr b/Task/String-concatenation/Crystal/string-concatenation.cr new file mode 100644 index 0000000000..90d3c9a230 --- /dev/null +++ b/Task/String-concatenation/Crystal/string-concatenation.cr @@ -0,0 +1,5 @@ +s1 = "hello" +s2 = s1 + " world!" + +pp! s1 +pp! s2 diff --git a/Task/String-concatenation/Delphi/string-concatenation.delphi b/Task/String-concatenation/Delphi/string-concatenation.pas similarity index 100% rename from Task/String-concatenation/Delphi/string-concatenation.delphi rename to Task/String-concatenation/Delphi/string-concatenation.pas diff --git a/Task/String-concatenation/Ecstasy/string-concatenation.ecstasy b/Task/String-concatenation/Ecstasy/string-concatenation.ecstasy new file mode 100644 index 0000000000..75820afb87 --- /dev/null +++ b/Task/String-concatenation/Ecstasy/string-concatenation.ecstasy @@ -0,0 +1,31 @@ +module StringAppend { + void run() { + String start = "hello"; + String finish = " world"; + + // approach #1: add strings together + String approach1 = start + finish; + + // approach #2: StringBuffer + String approach2 = new StringBuffer() + .append(start) + .append(finish) + .toString(); + + // approach #3: string template + String approach3 = $"{start}{finish}"; + + @Inject Console console; + console.print($| + |Appending strings: + | + | {start=} + | {finish=} + | + | {approach1=} + | {approach2=} + | {approach3=} + | + ); + } +} diff --git a/Task/String-concatenation/Ed/string-concatenation.ed b/Task/String-concatenation/Ed/string-concatenation.ed new file mode 100644 index 0000000000..fce5b53d8a --- /dev/null +++ b/Task/String-concatenation/Ed/string-concatenation.ed @@ -0,0 +1,7 @@ +# by Artyom Bologov +a +Hello +World! +. +,jp +Q diff --git a/Task/String-concatenation/Elena/string-concatenation.elena b/Task/String-concatenation/Elena/string-concatenation.elena index be21eae1b4..4444fee3c7 100644 --- a/Task/String-concatenation/Elena/string-concatenation.elena +++ b/Task/String-concatenation/Elena/string-concatenation.elena @@ -1,9 +1,9 @@ -public program() +public Program() { var s := "Hello"; var s2 := s + " literal"; - console.writeLine(s); - console.writeLine(s2); - console.readChar() + Console.writeLine(s); + Console.writeLine(s2); + Console.readChar() } diff --git a/Task/String-concatenation/Elixir/string-concatenation.elixir b/Task/String-concatenation/Elixir/string-concatenation.ex similarity index 100% rename from Task/String-concatenation/Elixir/string-concatenation.elixir rename to Task/String-concatenation/Elixir/string-concatenation.ex diff --git a/Task/String-concatenation/Emacs-Lisp/string-concatenation.l b/Task/String-concatenation/Emacs-Lisp/string-concatenation.el similarity index 100% rename from Task/String-concatenation/Emacs-Lisp/string-concatenation.l rename to Task/String-concatenation/Emacs-Lisp/string-concatenation.el diff --git a/Task/String-concatenation/Euphoria/string-concatenation.euphoria b/Task/String-concatenation/Euphoria/string-concatenation.eu similarity index 100% rename from Task/String-concatenation/Euphoria/string-concatenation.euphoria rename to Task/String-concatenation/Euphoria/string-concatenation.eu diff --git a/Task/String-concatenation/FutureBasic/string-concatenation.basic b/Task/String-concatenation/FutureBasic/string-concatenation-1.basic similarity index 100% rename from Task/String-concatenation/FutureBasic/string-concatenation.basic rename to Task/String-concatenation/FutureBasic/string-concatenation-1.basic diff --git a/Task/String-concatenation/FutureBasic/string-concatenation-2.basic b/Task/String-concatenation/FutureBasic/string-concatenation-2.basic new file mode 100644 index 0000000000..2fb3c85871 --- /dev/null +++ b/Task/String-concatenation/FutureBasic/string-concatenation-2.basic @@ -0,0 +1,10 @@ +void local fn StringConcatentation + CFStringRef s1 = @"alpha " + print s1 + CFStringRef s2 = concat(s1,@"bravo") + print s2 +end fn + +fn StringConcatentation + +HandleEvents diff --git a/Task/String-concatenation/JavaScript/string-concatenation.js b/Task/String-concatenation/JavaScript/string-concatenation.js index 3763e92eb2..df727c924c 100644 --- a/Task/String-concatenation/JavaScript/string-concatenation.js +++ b/Task/String-concatenation/JavaScript/string-concatenation.js @@ -1,2 +1,2 @@ var s = "hello" -print(s + " there!") +console.log(s + " there!") diff --git a/Task/String-concatenation/Julia/string-concatenation.julia b/Task/String-concatenation/Julia/string-concatenation.jl similarity index 100% rename from Task/String-concatenation/Julia/string-concatenation.julia rename to Task/String-concatenation/Julia/string-concatenation.jl diff --git a/Task/String-concatenation/Komodo/string-concatenation.komodo b/Task/String-concatenation/Komodo/string-concatenation.komodo new file mode 100644 index 0000000000..d01a8fec8e --- /dev/null +++ b/Task/String-concatenation/Komodo/string-concatenation.komodo @@ -0,0 +1,4 @@ +let s := "hello" +println(s + " world") +let ss := s + " world" +println(ss) diff --git a/Task/String-concatenation/Kotlin/string-concatenation.kotlin b/Task/String-concatenation/Kotlin/string-concatenation.kts similarity index 100% rename from Task/String-concatenation/Kotlin/string-concatenation.kotlin rename to Task/String-concatenation/Kotlin/string-concatenation.kts diff --git a/Task/String-concatenation/LOLCODE/string-concatenation.lol b/Task/String-concatenation/LOLCODE/string-concatenation.lol new file mode 100644 index 0000000000..5f1364e3ba --- /dev/null +++ b/Task/String-concatenation/LOLCODE/string-concatenation.lol @@ -0,0 +1,7 @@ +HAI 1.3 + +I HAS A S1 ITZ "O HAI" +I HAS A S2 ITZ SMOOSH S1 " THAR" MKAY +VISIBLE S2 + +KTHXBYE diff --git a/Task/String-concatenation/OCaml/string-concatenation.ocaml b/Task/String-concatenation/OCaml/string-concatenation.ml similarity index 100% rename from Task/String-concatenation/OCaml/string-concatenation.ocaml rename to Task/String-concatenation/OCaml/string-concatenation.ml diff --git a/Task/String-concatenation/PascalABC.NET/string-concatenation.pas b/Task/String-concatenation/PascalABC.NET/string-concatenation.pas new file mode 100644 index 0000000000..6a3c224b6b --- /dev/null +++ b/Task/String-concatenation/PascalABC.NET/string-concatenation.pas @@ -0,0 +1,4 @@ +## +var s := 'Pascal'; +s := s + 'ABC' + '.NET'; +Print(s); diff --git a/Task/String-concatenation/PowerShell/string-concatenation.psh b/Task/String-concatenation/PowerShell/string-concatenation.ps1 similarity index 100% rename from Task/String-concatenation/PowerShell/string-concatenation.psh rename to Task/String-concatenation/PowerShell/string-concatenation.ps1 diff --git a/Task/String-concatenation/Prolog/string-concatenation.pro b/Task/String-concatenation/Prolog/string-concatenation.pro new file mode 100644 index 0000000000..96ca451636 --- /dev/null +++ b/Task/String-concatenation/Prolog/string-concatenation.pro @@ -0,0 +1,9 @@ +:- set_prolog_flag(double_quotes, chars). + +println([]) :- write('\n'). +println([Char | Chars]) :- write(Char), println(Chars). + +:- S0 = "Hello, ", + S1 = "world!", + append(S0, S1, S), + println(S). diff --git a/Task/String-concatenation/REBOL/string-concatenation.rebol b/Task/String-concatenation/REBOL/string-concatenation.rebol deleted file mode 100644 index bb5ba06c41..0000000000 --- a/Task/String-concatenation/REBOL/string-concatenation.rebol +++ /dev/null @@ -1,3 +0,0 @@ -s: "hello" -print s1: rejoin [s " literal"] -print s1 diff --git a/Task/String-concatenation/RISC-V-Assembly/string-concatenation.asm b/Task/String-concatenation/RISC-V-Assembly/string-concatenation.asm new file mode 100644 index 0000000000..c59c761585 --- /dev/null +++ b/Task/String-concatenation/RISC-V-Assembly/string-concatenation.asm @@ -0,0 +1,117 @@ +# riscv assembly raspberry pico2 rp2350 +# program concatstring.s +# connexion putty com3 +/*********************************************/ +/* CONSTANTES */ +/********************************************/ +/* for this file see risc-v task include a file */ +.include "../../constantesRiscv.inc" +.equ BUFFERSIZE, 255 +/*******************************************/ +/* INITIALED DATAS */ +/*******************************************/ +.data +szMessStart: .asciz "Program riscv start.\r\n" +szMessEndOk: .asciz "Program riscv end OK.\r\n" +szCariageReturn: .asciz "\r\n" + +szMessFinal: .asciz "The final string is \n" + +szString1: .asciz "Hello " +szString2: .asciz " the world. \n" + +szMessErrorSize: .asciz "Error : size final string too small\n" + +.align 2 +/*******************************************/ +/* UNINITIALED DATA */ +/*******************************************/ +.bss +szFinalString: .skip BUFFERSIZE +.align 2 + +/**********************************************/ +/* SECTION CODE */ +/**********************************************/ +.text +.global main + +main: + call stdio_init_all # général init +1: # start loop connexion + li a0,0 # raz argument register + call tud_cdc_n_connected # waiting for USB connection + beqz a0,1b # return code = zero ? + + la a0,szMessStart # message address + call writeString # display message + + + la a0,szString1 # adresse string 1 + la a1,szString2 # adresse string 2 + la a2,szFinalString # adresse string final + li a3,BUFFERSIZE # size area string final + call concatString # concat string + li t0,-1 + beq a0,t0,100f # error ? + + la a0,szMessFinal # message address + call writeString # display message + la a0,szFinalString + call writeString # display message + la a0,szCariageReturn # message address + call writeString # display message + + la a0,szMessEndOk # message address + call writeString # display message + call getchar +100: # final loop + j 100b + +/*********************************************/ +/* add string to string */ +/*********************************************/ +/* a0 contains address String 1 */ +/* a1 contains address String 2 */ +/* a2 contains address String final */ +/* a3 contains string final size */ +concatString: + addi sp, sp, -4 + sw ra, 0(sp) + li t0,0 # counter byte string 1 + +1: + add t1,a0,t0 + lbu t2,(t1) # load byte string 1 + add t1,a2,t0 + sb t2,(t1) # store byte final string + beqz t2,2f # zero final ? + addi t0,t0,1 # no -> increment counter + bge t0,a3,99f # size maxi ? + j 1b # loop +2: + li t3, 0 # counter byte string 2 +3: + add t4,a1,t3 + lbu t5,(t4) # load byte string 2 + add t1,a2,t0 + sb t5,(t1) # store byte string final + beqz t5,100f # zero final ? -> end + addi t3,t3,1 # increment counter + addi t0,t0,1 + bge t0,a3,99f # size maxi ? + j 3b # end loop +99: + la a0,szMessErrorSize + call writeString + li a0,-1 # return error +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret + +/************************************/ +/* file include Fonctions */ +/***********************************/ +/* for this file see risc-v task include a file */ +.include "../../includeFunctions.s" diff --git a/Task/String-concatenation/ReScript/string-concatenation.re b/Task/String-concatenation/ReScript/string-concatenation.res similarity index 100% rename from Task/String-concatenation/ReScript/string-concatenation.re rename to Task/String-concatenation/ReScript/string-concatenation.res diff --git a/Task/String-concatenation/Rebol/string-concatenation.rebol b/Task/String-concatenation/Rebol/string-concatenation.rebol new file mode 100644 index 0000000000..dda3bbfa80 --- /dev/null +++ b/Task/String-concatenation/Rebol/string-concatenation.rebol @@ -0,0 +1,6 @@ +s: "hello" +print s1: rejoin [s " literal"] +; Or: +print s2: join s " literal" +; Or: +print s3: ajoin [s " literal"] diff --git a/Task/String-concatenation/Rust/string-concatenation.rust b/Task/String-concatenation/Rust/string-concatenation.rs similarity index 100% rename from Task/String-concatenation/Rust/string-concatenation.rust rename to Task/String-concatenation/Rust/string-concatenation.rs diff --git a/Task/String-concatenation/Rye/string-concatenation.rye b/Task/String-concatenation/Rye/string-concatenation.rye new file mode 100644 index 0000000000..423bd3384b --- /dev/null +++ b/Task/String-concatenation/Rye/string-concatenation.rye @@ -0,0 +1,5 @@ +a: "Hello, " +b: a ++ "world!" + +print a +print b diff --git a/Task/String-concatenation/Scheme/string-concatenation.ss b/Task/String-concatenation/Scheme/string-concatenation.scm similarity index 100% rename from Task/String-concatenation/Scheme/string-concatenation.ss rename to Task/String-concatenation/Scheme/string-concatenation.scm diff --git a/Task/String-concatenation/Tcl/string-concatenation-3.tcl b/Task/String-concatenation/Tcl/string-concatenation-3.tcl new file mode 100644 index 0000000000..d98b4783f1 --- /dev/null +++ b/Task/String-concatenation/Tcl/string-concatenation-3.tcl @@ -0,0 +1,6 @@ +set s "Hello" +set w "World" +set hw "$s $w" ; # "hello world" +set hw [concat $s $w] ; # {hello world}, same as above +set hw [string cat $s $w] ; # "helloworld" +set hw [join [list $s $w] " "] ; # "hello world" \w space delimiter diff --git a/Task/String-concatenation/Uiua/string-concatenation.uiua b/Task/String-concatenation/Uiua/string-concatenation.uiua new file mode 100644 index 0000000000..e25c219c37 --- /dev/null +++ b/Task/String-concatenation/Uiua/string-concatenation.uiua @@ -0,0 +1,3 @@ +A ← "Hello " +B ← ⊂ A "world" +B diff --git a/Task/String-concatenation/Uxntal/string-concatenation.uxnatl b/Task/String-concatenation/Uxntal/string-concatenation.uxnatl index e817d13f27..f65b87d1b5 100644 --- a/Task/String-concatenation/Uxntal/string-concatenation.uxnatl +++ b/Task/String-concatenation/Uxntal/string-concatenation.uxnatl @@ -1,33 +1,32 @@ -|10 @Console &vector $2 &read $1 &pad $4 &type $1 &write $1 &error $1 +|18 @Console/write |0100 @on-reset ( -> ) ;str3 ;str1 copy-str ;str3 ;str2 append-str ;str3 print-str - #0a .Console/write DEO BRK -@print-str ( str* -: ) - &loop ( -- ) - LDAk .Console/write DEO - INC2 LDAk ?&loop - POP2 JMP2r +@print-str_ ( str* -: ) + LDAk .Console/write DEO + INC2 @print-str LDAk ?print-str_ + POP2 + JMP2r + +@append-str ( dest* src* -: ) + STH2 end-str STH2r + ( >> ) @copy-str ( dest* src* -: ) STH2 &loop ( -- ) LDAkr STH2k STAr INC2 LDAkr STHr INC2r ?&loop - POP2 POP2r JMP2r + POP2 POP2r + JMP2r -@append-str ( dest* src* -: ) - STH2 end-str STH2r copy-str JMP2r - -@end-str ( str* -: str* ) - !&inner - &loop ( -- ) - INC2 &inner LDAk ?&loop +@end-str_ ( str* -: str* ) + INC2 @end-str LDAk ?end-str_ JMP2r @str1 "Uxn 00 -@str2 "tal 00 +@str2 "tal 0a00 @str3 diff --git a/Task/String-concatenation/VBScript/string-concatenation.vb b/Task/String-concatenation/VBScript/string-concatenation.vbs similarity index 100% rename from Task/String-concatenation/VBScript/string-concatenation.vb rename to Task/String-concatenation/VBScript/string-concatenation.vbs diff --git a/Task/String-interpolation-included-/Ada/string-interpolation-included--1.ada b/Task/String-interpolation-included-/Ada/string-interpolation-included--1.adb similarity index 100% rename from Task/String-interpolation-included-/Ada/string-interpolation-included--1.ada rename to Task/String-interpolation-included-/Ada/string-interpolation-included--1.adb diff --git a/Task/String-interpolation-included-/Ada/string-interpolation-included--2.ada b/Task/String-interpolation-included-/Ada/string-interpolation-included--2.adb similarity index 100% rename from Task/String-interpolation-included-/Ada/string-interpolation-included--2.ada rename to Task/String-interpolation-included-/Ada/string-interpolation-included--2.adb diff --git a/Task/String-interpolation-included-/ArkScript/string-interpolation-included-.ark b/Task/String-interpolation-included-/ArkScript/string-interpolation-included-.ark new file mode 100644 index 0000000000..87c666c268 --- /dev/null +++ b/Task/String-interpolation-included-/ArkScript/string-interpolation-included-.ark @@ -0,0 +1,4 @@ +(print (string:format "Mary had a {} lamb." "little")) + +(let replacement "medium-sized") +(print (string:format "Mary had a {} lamb." replacement)) diff --git a/Task/String-interpolation-included-/COBOL/string-interpolation-included-.cobol b/Task/String-interpolation-included-/COBOL/string-interpolation-included-.cob similarity index 100% rename from Task/String-interpolation-included-/COBOL/string-interpolation-included-.cobol rename to Task/String-interpolation-included-/COBOL/string-interpolation-included-.cob diff --git a/Task/String-interpolation-included-/Crystal/string-interpolation-included-.cr b/Task/String-interpolation-included-/Crystal/string-interpolation-included-.cr new file mode 100644 index 0000000000..82a646236f --- /dev/null +++ b/Task/String-interpolation-included-/Crystal/string-interpolation-included-.cr @@ -0,0 +1,6 @@ +icr:1> extra = "little" + => "little" +icr:2> "Mary had a #{extra} lamb" + => "Mary had a little lamb" +icr:3> "Mary had a %s lamb" % extra + => "Mary had a little lamb" diff --git a/Task/String-interpolation-included-/Delphi/string-interpolation-included-.delphi b/Task/String-interpolation-included-/Delphi/string-interpolation-included-.pas similarity index 100% rename from Task/String-interpolation-included-/Delphi/string-interpolation-included-.delphi rename to Task/String-interpolation-included-/Delphi/string-interpolation-included-.pas diff --git a/Task/String-interpolation-included-/DuckDB/string-interpolation-included-.duckdb b/Task/String-interpolation-included-/DuckDB/string-interpolation-included-.duckdb new file mode 100644 index 0000000000..d44ba7106b --- /dev/null +++ b/Task/String-interpolation-included-/DuckDB/string-interpolation-included-.duckdb @@ -0,0 +1 @@ +select replace( 'Mary had a , lamb.', '', getvariable('adjective')); diff --git a/Task/String-interpolation-included-/Ed/string-interpolation-included-.ed b/Task/String-interpolation-included-/Ed/string-interpolation-included-.ed new file mode 100644 index 0000000000..036770db04 --- /dev/null +++ b/Task/String-interpolation-included-/Ed/string-interpolation-included-.ed @@ -0,0 +1,9 @@ +# by Artyom Bologov +H +,p +# Add a vertical bar to separate the template and value +2s/^/|/ +,j +# Replace and print +s/X\(.*\)|\(.*\)/\2\1/p +Q diff --git a/Task/String-interpolation-included-/Elena/string-interpolation-included-.elena b/Task/String-interpolation-included-/Elena/string-interpolation-included-.elena index b5251ec926..368bca7835 100644 --- a/Task/String-interpolation-included-/Elena/string-interpolation-included-.elena +++ b/Task/String-interpolation-included-/Elena/string-interpolation-included-.elena @@ -1,7 +1,7 @@ import extensions; -public program() +public Program() { var s := "little"; - console.printLineFormatted("Mary had a {0} lamb.",s).readChar() + Console.printLineFormatted("Mary had a {0} lamb.",s).readChar() } diff --git a/Task/String-interpolation-included-/Elixir/string-interpolation-included-.elixir b/Task/String-interpolation-included-/Elixir/string-interpolation-included-.ex similarity index 100% rename from Task/String-interpolation-included-/Elixir/string-interpolation-included-.elixir rename to Task/String-interpolation-included-/Elixir/string-interpolation-included-.ex diff --git a/Task/String-interpolation-included-/Emacs-Lisp/string-interpolation-included-.l b/Task/String-interpolation-included-/Emacs-Lisp/string-interpolation-included-.el similarity index 100% rename from Task/String-interpolation-included-/Emacs-Lisp/string-interpolation-included-.l rename to Task/String-interpolation-included-/Emacs-Lisp/string-interpolation-included-.el diff --git a/Task/String-interpolation-included-/Euphoria/string-interpolation-included-.euphoria b/Task/String-interpolation-included-/Euphoria/string-interpolation-included-.eu similarity index 100% rename from Task/String-interpolation-included-/Euphoria/string-interpolation-included-.euphoria rename to Task/String-interpolation-included-/Euphoria/string-interpolation-included-.eu diff --git a/Task/String-interpolation-included-/Haxe/string-interpolation-included-.haxe b/Task/String-interpolation-included-/Haxe/string-interpolation-included-.hx similarity index 100% rename from Task/String-interpolation-included-/Haxe/string-interpolation-included-.haxe rename to Task/String-interpolation-included-/Haxe/string-interpolation-included-.hx diff --git a/Task/String-interpolation-included-/Jactl/string-interpolation-included--1.jactl b/Task/String-interpolation-included-/Jactl/string-interpolation-included--1.jactl new file mode 100644 index 0000000000..139b9f5883 --- /dev/null +++ b/Task/String-interpolation-included-/Jactl/string-interpolation-included--1.jactl @@ -0,0 +1,2 @@ +def x = 'little' +println "Mary had a $x lamb" diff --git a/Task/String-interpolation-included-/Jactl/string-interpolation-included--2.jactl b/Task/String-interpolation-included-/Jactl/string-interpolation-included--2.jactl new file mode 100644 index 0000000000..a01fd81a9d --- /dev/null +++ b/Task/String-interpolation-included-/Jactl/string-interpolation-included--2.jactl @@ -0,0 +1,4 @@ +def x = 'li' +def y = 't' +def z = 'le' +println "Mary had a ${x + y * 2 + z} lamb" diff --git a/Task/String-interpolation-included-/Julia/string-interpolation-included-.julia b/Task/String-interpolation-included-/Julia/string-interpolation-included-.jl similarity index 100% rename from Task/String-interpolation-included-/Julia/string-interpolation-included-.julia rename to Task/String-interpolation-included-/Julia/string-interpolation-included-.jl diff --git a/Task/String-interpolation-included-/Kotlin/string-interpolation-included-.kotlin b/Task/String-interpolation-included-/Kotlin/string-interpolation-included-.kts similarity index 100% rename from Task/String-interpolation-included-/Kotlin/string-interpolation-included-.kotlin rename to Task/String-interpolation-included-/Kotlin/string-interpolation-included-.kts diff --git a/Task/String-interpolation-included-/LOLCODE/string-interpolation-included-.lol b/Task/String-interpolation-included-/LOLCODE/string-interpolation-included-.lol new file mode 100644 index 0000000000..e200c6971b --- /dev/null +++ b/Task/String-interpolation-included-/LOLCODE/string-interpolation-included-.lol @@ -0,0 +1,6 @@ +HAI 1.3 + +I HAS A SIZE ITZ "little" +VISIBLE "Mary had a :{SIZE} lamb" + +KTHXBYE diff --git a/Task/String-interpolation-included-/Langur/string-interpolation-included--1.langur b/Task/String-interpolation-included-/Langur/string-interpolation-included--1.langur new file mode 100644 index 0000000000..56fcf30901 --- /dev/null +++ b/Task/String-interpolation-included-/Langur/string-interpolation-included--1.langur @@ -0,0 +1,2 @@ +val x = "little" +writeln "Mary had a {{x}} lamb." diff --git a/Task/String-interpolation-included-/Langur/string-interpolation-included--2.langur b/Task/String-interpolation-included-/Langur/string-interpolation-included--2.langur new file mode 100644 index 0000000000..32bb92f4fe --- /dev/null +++ b/Task/String-interpolation-included-/Langur/string-interpolation-included--2.langur @@ -0,0 +1 @@ +writeln "Lamb count: {{x : 7}}" diff --git a/Task/String-interpolation-included-/Langur/string-interpolation-included--3.langur b/Task/String-interpolation-included-/Langur/string-interpolation-included--3.langur new file mode 100644 index 0000000000..672b1e9b1d --- /dev/null +++ b/Task/String-interpolation-included-/Langur/string-interpolation-included--3.langur @@ -0,0 +1,3 @@ +writeln "Partial lamb count: {{x : r2 : 10}}" +# rounds to 2 decimal places, then aligns to 10 code points +# (hopefully no partial lambs) diff --git a/Task/String-interpolation-included-/Langur/string-interpolation-included--4.langur b/Task/String-interpolation-included-/Langur/string-interpolation-included--4.langur new file mode 100644 index 0000000000..e33ab6466f --- /dev/null +++ b/Task/String-interpolation-included-/Langur/string-interpolation-included--4.langur @@ -0,0 +1,2 @@ +writeln qs:ni"Lamb count: {{x : 7}}" +# will write "Lamb count: {{x : 7}}\n" to the console diff --git a/Task/String-interpolation-included-/OCaml/string-interpolation-included--1.ocaml b/Task/String-interpolation-included-/OCaml/string-interpolation-included--1.ml similarity index 100% rename from Task/String-interpolation-included-/OCaml/string-interpolation-included--1.ocaml rename to Task/String-interpolation-included-/OCaml/string-interpolation-included--1.ml diff --git a/Task/String-interpolation-included-/OCaml/string-interpolation-included--2.ocaml b/Task/String-interpolation-included-/OCaml/string-interpolation-included--2.ml similarity index 100% rename from Task/String-interpolation-included-/OCaml/string-interpolation-included--2.ocaml rename to Task/String-interpolation-included-/OCaml/string-interpolation-included--2.ml diff --git a/Task/String-interpolation-included-/PascalABC.NET/string-interpolation-included-.pas b/Task/String-interpolation-included-/PascalABC.NET/string-interpolation-included-.pas new file mode 100644 index 0000000000..ad45cd88fd --- /dev/null +++ b/Task/String-interpolation-included-/PascalABC.NET/string-interpolation-included-.pas @@ -0,0 +1,3 @@ +## var extra := 'little'; +var formatted := $'Mary has a {extra} lamb.'; +Print(formatted); diff --git a/Task/String-interpolation-included-/Phix/string-interpolation-included-.phix b/Task/String-interpolation-included-/Phix/string-interpolation-included-.phix index 0867e36f49..09323fa16c 100644 --- a/Task/String-interpolation-included-/Phix/string-interpolation-included-.phix +++ b/Task/String-interpolation-included-/Phix/string-interpolation-included-.phix @@ -1,5 +1,3 @@ -(phixonline)--> - string size = "little" - string s = sprintf("Mary had a %s lamb.",{size}) - ?s - ", has_prefix(s, s1)) + + fmt.println( "2. ", s, " contains ", s1, " --> ", contains (s, s1)) + ndx := index(s, s1) + if ndx > -1 { + fmt.println(" 2.1. at location -> ", ndx) + ndx += len(s1) + for ndx < len(s) { + found := index(s[ndx:], s1) + if found > -1 { + fmt.println(" 2.2. at location -> ", found+ndx) + ndx += found+len(s1) + } else { + break + } + } + fmt.println(" 2.2. and that's all.") + } + + fmt.println( "3. ", s, " ends with ", s1, " --> ", has_suffix(s, s1)) +} diff --git a/Task/String-matching/PL-I/string-matching-1.pli b/Task/String-matching/PL-I/string-matching-1.pli deleted file mode 100644 index 9d42540995..0000000000 --- a/Task/String-matching/PL-I/string-matching-1.pli +++ /dev/null @@ -1,11 +0,0 @@ -/* Let s be one string, t be the other that might exist within s. */ - /* 8-1-2011 */ -k = index(s, t); -if k = 0 then put skip edit (t, ' is nowhere in sight') (a); -else if k = 1 then - put skip edit (t, ' starts at the beginning of ', s) (a); -else if k+length(t)-1 = length(s) then - put skip edit (t, ' is at the end of ', s) (a); -else put skip edit (t, ' is within ', s) (a); - -if k > 0 then put skip edit (t, ' starts at position ', k) (a); diff --git a/Task/String-matching/PL-I/string-matching-2.pli b/Task/String-matching/PL-I/string-matching-2.pli deleted file mode 100644 index afdbb2be13..0000000000 --- a/Task/String-matching/PL-I/string-matching-2.pli +++ /dev/null @@ -1,20 +0,0 @@ -/* Handle multiple occurrences. */ - n = 1; - do forever; - k = index(s, t, n); - if k = 0 then - do; - if n = 1 then put skip list (t, ' is nowhere in sight'); - stop; - end; - else if k = 1 then - put skip edit ('<', t, '> starts at the beginning of ', s) (a); - else if k+length(t)-1 = length(s) then - put skip edit ('<', t, '> is at the end of ', s) (a); - else put skip edit ('<', t, '> is within ', s) (a); - n = k + length(t); - - if k > 0 then - put skip edit ('<', t, '> starts at position ', trim(k)) (a); - else stop; - end; diff --git a/Task/String-matching/PL-I/string-matching.pli b/Task/String-matching/PL-I/string-matching.pli new file mode 100644 index 0000000000..685b86ba74 --- /dev/null +++ b/Task/String-matching/PL-I/string-matching.pli @@ -0,0 +1,32 @@ +/* Let s be one string, t be the other that might exist within s. */ + /* 8-1-2011 */ +k = index(s, t); +if k = 0 then put skip edit (t, ' is nowhere in sight') (a); +else if k = 1 then + put skip edit (t, ' starts at the beginning of ', s) (a); +else if k+length(t)-1 = length(s) then + put skip edit (t, ' is at the end of ', s) (a); +else put skip edit (t, ' is within ', s) (a); + +if k > 0 then put skip edit (t, ' starts at position ', k) (a); + +/* Optional extra: Handle multiple occurrences. */ + n = 1; + do forever; + k = index(s, t, n); + if k = 0 then + do; + if n = 1 then put skip list (t, ' is nowhere in sight'); + stop; + end; + else if k = 1 then + put skip edit ('<', t, '> starts at the beginning of ', s) (a); + else if k+length(t)-1 = length(s) then + put skip edit ('<', t, '> is at the end of ', s) (a); + else put skip edit ('<', t, '> is within ', s) (a); + n = k + length(t); + + if k > 0 then + put skip edit ('<', t, '> starts at position ', trim(k)) (a); + else stop; + end; diff --git a/Task/String-matching/PascalABC.NET/string-matching.pas b/Task/String-matching/PascalABC.NET/string-matching.pas new file mode 100644 index 0000000000..8237feeca0 --- /dev/null +++ b/Task/String-matching/PascalABC.NET/string-matching.pas @@ -0,0 +1,9 @@ +## +Println('abcd'.StartsWith('ab')); +Println('abcd'.EndsWith('cd')); +var abra := 'abracadabra'; +Println('bra' in abra); +var ind := abra.IndexOf('bra'); +var ind1 := abra.IndexOf('bra', ind + 1); +Println(ind,ind1); +abra.Matches('bra').Select(m -> m.Index).Println diff --git a/Task/String-matching/Perl/string-matching-1.pl b/Task/String-matching/Perl/string-matching-1.pl deleted file mode 100644 index b6c22ae517..0000000000 --- a/Task/String-matching/Perl/string-matching-1.pl +++ /dev/null @@ -1,3 +0,0 @@ -$str1 =~ /^\Q$str2\E/ # true if $str1 starts with $str2 -$str1 =~ /\Q$str2\E/ # true if $str1 contains $str2 -$str1 =~ /\Q$str2\E$/ # true if $str1 ends with $str2 diff --git a/Task/String-matching/Perl/string-matching-2.pl b/Task/String-matching/Perl/string-matching-2.pl deleted file mode 100644 index 9cca1fc290..0000000000 --- a/Task/String-matching/Perl/string-matching-2.pl +++ /dev/null @@ -1,3 +0,0 @@ -index($str1, $str2) == 0 # true if $str1 starts with $str2 -index($str1, $str2) != -1 # true if $str1 contains $str2 -rindex($str1, $str2) == length($str1) - length($str2) # true if $str1 ends with $str2 diff --git a/Task/String-matching/Perl/string-matching-3.pl b/Task/String-matching/Perl/string-matching-3.pl deleted file mode 100644 index 9c4bb1f632..0000000000 --- a/Task/String-matching/Perl/string-matching-3.pl +++ /dev/null @@ -1,2 +0,0 @@ -substr($str1, 0, length($str2)) eq $str2 # true if $str1 starts with $str2 -substr($str1, - length($str2)) eq $str2 # true if $str1 ends with $str2 diff --git a/Task/String-matching/Perl/string-matching-4.pl b/Task/String-matching/Perl/string-matching-4.pl deleted file mode 100644 index a076cd02f1..0000000000 --- a/Task/String-matching/Perl/string-matching-4.pl +++ /dev/null @@ -1 +0,0 @@ -print $-[0], "\n" while $str1 =~ /\Q$str2\E/g; # using a regex diff --git a/Task/String-matching/Perl/string-matching-5.pl b/Task/String-matching/Perl/string-matching-5.pl deleted file mode 100644 index a3dcea4868..0000000000 --- a/Task/String-matching/Perl/string-matching-5.pl +++ /dev/null @@ -1 +0,0 @@ -my $i = -1; print $i, "\n" while ($i = index $str1, $str2, $i + 1) != -1; # using index diff --git a/Task/String-matching/Perl/string-matching.pl b/Task/String-matching/Perl/string-matching.pl new file mode 100644 index 0000000000..38bc98e5ce --- /dev/null +++ b/Task/String-matching/Perl/string-matching.pl @@ -0,0 +1,21 @@ +# Using regexes: + +$str1 =~ /^\Q$str2\E/ # true if $str1 starts with $str2 +$str1 =~ /\Q$str2\E/ # true if $str1 contains $str2 +$str1 =~ /\Q$str2\E$/ # true if $str1 ends with $str2 + +# Using index: + +index($str1, $str2) == 0 # true if $str1 starts with $str2 +index($str1, $str2) != -1 # true if $str1 contains $str2 +rindex($str1, $str2) == length($str1) - length($str2) # true if $str1 ends with $str2 + +# Using substr: + +substr($str1, 0, length($str2)) eq $str2 # true if $str1 starts with $str2 +substr($str1, - length($str2)) eq $str2 # true if $str1 ends with $str2 + +# Bonus task (printing all positions where $str2 appears in $str1): + +print $-[0], "\n" while $str1 =~ /\Q$str2\E/g; # using a regex +my $i = -1; print $i, "\n" while ($i = index $str1, $str2, $i + 1) != -1; # using index diff --git a/Task/String-matching/Phix/string-matching.phix b/Task/String-matching/Phix/string-matching.phix index a4db381622..49daf40faa 100644 --- a/Task/String-matching/Phix/string-matching.phix +++ b/Task/String-matching/Phix/string-matching.phix @@ -1,33 +1,22 @@ ---> - constant word = "the", -- (also try this with "th"/"he") - sentence = "the last thing the man said was the" - -- sentence = "thelastthingthemansaidwasthe" -- (practically the same results) +with javascript_semantics +constant sentence = "abracadabra", w1 = "abra", w2 = "bar", + fmt = """ +For the string "%s": +1: Starts with "%s": %t. + Starts with "%s": %t. +2: Contains "%s": %t%s. + Contains "%s": %t%s. +3: Ends with "%s": %t. + Ends with "%s": %t. +""" +function jma(string word, sentence) + sequence r = match_all(word,sentence) + return iff(r={} ? "" : ", at "&join(r,", ", " and ","%d")) +end function - -- A common, but potentially inefficient idiom for checking for a substring at the start is: - if match(word,sentence)=1 then - ?"yes(1)" - end if - -- A more efficient method is to test the appropriate slice - if length(sentence)>=length(word) - and sentence[1..length(word)]=word then - ?"yes(2)" - end if - -- Which is almost identical to checking for a word at the end - if length(sentence)>=length(word) - and sentence[-length(word)..-1]=word then - ?"yes(3)" - end if - -- Or sometimes you will see this, a tiny bit more efficient: - if length(sentence)>=length(word) - and match(word,sentence,length(sentence)-length(word)+1) then - ?"yes(4)" - end if - -- Finding all occurences is a snap: - integer r = match(word,sentence) - while r!=0 do - ?r - r = match(word,sentence,r+1) - end while - -- or equivalently: - ?match_all(word,sentence) - - string s = "World" - s = "Hello "&s - - procedure subleq(sequence code) - integer ip := 0 - while ip>=0 do - integer {a,b,c} = code[ip+1..ip+3] - ip += 3 - if a=-1 then - code[b+1] = iff(platform()=JS?'?':getc(0)) - elsif b=-1 then - puts(1,code[a+1]) - else - code[b+1] -= code[a+1] - if code[b+1]<=0 then - ip := c - end if - end if - end while - end procedure +procedure subleq(sequence code) + integer ip := 0 + while ip>=0 do + integer {a,b,c} = code[ip+1..ip+3] + ip += 3 + if a=-1 then + code[b+1] = iff(platform()=JS?'?':getc(0)) + elsif b=-1 then + puts(1,code[a+1]) + else + code[b+1] -= code[a+1] + if code[b+1]<=0 then + ip := c + end if + end if + end while +end procedure - subleq({15, 17, -1, 17, -1, -1, 16, 1, -1, 16, 3, -1, - 15, 15, 0, 0, -1, 72, 101, 108, 108, 111, 44, 32, - 119, 111, 114, 108, 100, 33, 10, 0}) - - constant s = "(test)" - ?s[2..-1] - ?s[1..-2] - ?s[2..-2] - - with javascript_semantics - constant primes = get_primes_le(1_000_000) - procedure test(sequence differences) - sequence res = {} - integer ld = length(differences) - for i=1 to length(primes)-ld do - integer pi = primes[i] - for j=1 to ld do - pi += differences[j] - if pi!=primes[i+j] then - pi = 0 - exit - end if - end for - if pi!=0 then - res = append(res,primes[i..i+ld]) - end if - end for - res = {differences,length(res),res[1],res[$]} - printf(1,"%8V : %8d %14V...%V\n",res) - end procedure +with javascript_semantics +constant primes = get_primes_le(1_000_000) +procedure test(sequence differences) + sequence res = {} + integer ld = length(differences) + for i=1 to length(primes)-ld do + integer pi = primes[i] + for j=1 to ld do + pi += differences[j] + if pi!=primes[i+j] then + pi = 0 + exit + end if + end for + if pi!=0 then + res = append(res,primes[i..i+ld]) + end if + end for + res = {differences,length(res),res[1],res[$]} + printf(1,"%8V : %8d %14V...%V\n",res) +end procedure - printf(1,"Differences Count First Last\n") - papply({{2},{1},{2,2},{2,4},{4,2},{6,4,2}},test) - - with javascript_semantics - function F(integer n, x, y) - if n=0 then return x+y end if - if y=0 then return x end if - integer t = F(n,x,y-1) - return F(n-1,t,t+y) - end function +with javascript_semantics +function F(integer n, x, y) + if n=0 then return x+y end if + if y=0 then return x end if + integer t = F(n,x,y-1) + return F(n-1,t,t+y) +end function - for n=0 to 1 do - printf(1,"Values of F(%d, x, y):\n",n) - printf(1,"y/x 0 1 2 3 4 5\n") - printf(1,"----------------------------\n") - for y=0 to 6 do - sequence r = apply(true,F,{n,tagset(5,0),y}) - printf(1,"%d |%s\n",{y,join(r,"",fmt:="%4d")}) - end for - printf(1,"\n") - end for +for n=0 to 1 do + printf(1,"Values of F(%d, x, y):\n",n) + printf(1,"y/x 0 1 2 3 4 5\n") + printf(1,"----------------------------\n") + for y=0 to 6 do + sequence r = apply(true,F,{n,tagset(5,0),y}) + printf(1,"%d |%s\n",{y,join(r,"",fmt:="%4d")}) + end for + printf(1,"\n") +end for - for t in {{2,1,1},{3,1,1},{2,2,1}} do - integer {n,x,y} = t - printf(1,"F(%d, %d, %d) = %d\n",{n,x,y,F(n,x,y)}) - end for - - include builtins/bigatom.e +with javascript_semantics - constant suffixes = "KMGTPEZYXWVU", - anydp = 100 -- the "any dp" value (prevents nearest 1e-100, though) +include builtins/bigatom.e - function suffize(sequence args) - bigatom size = ba_abs(args[1]) - integer sgn = iff(ba_compare(args[1],0)<0?-1:+1), - la = length(args), - dp = iff(la>=2?args[2]:anydp), -- decimal places - bd = iff(la>=3?args[3]:10) -- 2 or 10 - atom ip = power(10,dp) -- (inverted precision) - if dp<0 then size = ba_round(size,ip) end if - string suffix - if ba_compare(size,1e100)>0 then - size = ba_div(size,1e100) - suffix = "googol" - else - integer factor = iff(bd=2?1024:1000), fdx = 0 - while fdx<length(suffixes) do - bigatom rsize = ba_div(size,factor) - if dp<0 then rsize = ba_round(rsize,ip) end if - if ba_compare(rsize,1)<0 then exit end if - size = rsize - fdx += 1 - end while - suffix = iff(fdx=0?"":suffixes[fdx]&iff(bd=2?"i":"")) - end if - string fmt = iff(dp<0 or dp=anydp?"%0B":sprintf("%%0.%dB",dp)) - string res = ba_sprintf(fmt, ba_mul(size,sgn)) - res &= suffix - return res - end function +constant suffixes = "KMGTPEZYXWVU", + anydp = 100 -- the "any dp" value (prevents nearest 1e-100, though) - constant test_text = """ - 87,654,321 - -998,877,665,544,332,211,000 3 - +112,233 0 - 16,777,216 1 - 456,789,100,000,000 - 456,789,100,000,000 2 10 - 456,789,100,000,000 5 2 - 456,789,100,000.000e+00 0 10 - 16777216 , 2 - 1.2e101 - 347,344 -2 - 10 - """, - test_cases = split(test_text,'\n',no_empty:=true) +function sufficate(sequence args) + bigatom size = ba_new(substitute(args[1],",","")) + for a=2 to length(args) do + sequence sa = scanf(args[a],"%f") + args[a] = iff(length(sa)=1?sa[1][1]:anydp) + end for + integer sgn = ba_compare(size,0), + dp = iff(length(args)>=2?args[2]:anydp), -- decimal places + bd = iff(length(args)>=3?args[3]:10) -- 2 or 10 + atom ip = power(10,dp) -- (inverted precision) + size = ba_abs(size) + if dp<0 then size = ba_round(size,ip) end if + string suffix + if ba_compare(size,1e100)>0 then + size = ba_div(size,1e100) + suffix = "googol" + else + integer factor = iff(bd=2?1024:1000), fdx = 0 + while fdxfor
    i=1 to length(test_cases) do - string ti = test_cases[i] - sequence args = split(ti,no_empty:=true) - args[1] = ba_new(substitute(args[1],",","")) - for a=2 to length(args) do - sequence sa = scanf(args[a],"%f") - args[a] = iff(length(sa)=1?sa[1][1]:anydp) - end for - string res = suffize(args) - printf(1,"%30s : %s\n",{ti,res}) - end for - - with javascript_semantics - function satisfies_statement1(integer s) - -- S says: P does not know the two numbers. - -- Given s, for /all/ pairs (a,b), a+b=s, 2<=a,b<=99, at least one of a or b is composite - for a=2 to floor(s/2) do - if is_prime(a) and is_prime(s-a) then - return false - end if - end for - return true - end function +with javascript_semantics +function satisfies_statement1(integer s) +-- S says: P does not know the two numbers. +-- Given s, for /all/ pairs (a,b), a+b=s, 2<=a,b<=99, at least one of a or b is composite + for a=2 to floor(s/2) do + if is_prime(a) and is_prime(s-a) then + return false + end if + end for + return true +end function - function satisfies_statement2(integer p) - -- P says: Now I know the two numbers. - -- Given p, for /all/ pairs (a,b), a*b=p, 2<=a,b<=99, exactly one pair satisfies statement 1 - bool winner = false - for i=2 to floor(sqrt(p)) do - if mod(p,i)=0 then - integer j = floor(p/i) - if 2<=j and j<=99 then - if satisfies_statement1(i+j) then - if winner then return false end if - winner = true - end if - end if - end if - end for - return winner - end function +function satisfies_statement2(integer p) +-- P says: Now I know the two numbers. +-- Given p, for /all/ pairs (a,b), a*b=p, 2<=a,b<=99, exactly one pair satisfies statement 1 + bool winner = false + for i=2 to floor(sqrt(p)) do + if mod(p,i)=0 then + integer j = floor(p/i) + if 2<=j and j<=99 then + if satisfies_statement1(i+j) then + if winner then return false end if + winner = true + end if + end if + end if + end for + return winner +end function - function satisfies_statement3(integer s) - -- S says: Now I know the two numbers. - -- Given s, for /all/ pairs (a,b), a+b=s, 2<=a,b<=99, exactly one pair satisfies statements 1 and 2 - integer winner = 0 - if satisfies_statement1(s) then - for a=2 to floor(s/2) do - if satisfies_statement2(a*(s-a)) then - if winner then return 0 end if - winner = a - end if - end for - end if - return winner - end function +function satisfies_statement3(integer s) +-- S says: Now I know the two numbers. +-- Given s, for /all/ pairs (a,b), a+b=s, 2<=a,b<=99, exactly one pair satisfies statements 1 and 2 + integer winner = 0 + if satisfies_statement1(s) then + for a=2 to floor(s/2) do + if satisfies_statement2(a*(s-a)) then + if winner then return 0 end if + winner = a + end if + end for + end if + return winner +end function - for s=2 to 100 do - integer a = satisfies_statement3(s) - if a!=0 then - printf(1,"%d (%d+%d)\n",{s,a,s-a}) - end if - end for - n ) + +' [ [ 1 3 7 8 10 ] + [ 2 4 16 14 4 ] + [ 3 1 9 18 11 ] + [ 12 14 17 18 20 ] + [ 7 1 3 9 5 ] ] +sumbelow echo diff --git a/Task/Sum-of-elements-below-main-diagonal-of-matrix/Uiua/sum-of-elements-below-main-diagonal-of-matrix.uiua b/Task/Sum-of-elements-below-main-diagonal-of-matrix/Uiua/sum-of-elements-below-main-diagonal-of-matrix.uiua new file mode 100644 index 0000000000..c92fdad906 --- /dev/null +++ b/Task/Sum-of-elements-below-main-diagonal-of-matrix/Uiua/sum-of-elements-below-main-diagonal-of-matrix.uiua @@ -0,0 +1,7 @@ +[[1 3 7 8 10] + [2 4 16 14 4] + [3 1 9 18 11] + [12 14 17 18 20] + [7 1 3 9 5]] + +/+≡(/+↙)°⊏ diff --git a/Task/Sum-of-squares/Ada/sum-of-squares.ada b/Task/Sum-of-squares/Ada/sum-of-squares.adb similarity index 100% rename from Task/Sum-of-squares/Ada/sum-of-squares.ada rename to Task/Sum-of-squares/Ada/sum-of-squares.adb diff --git a/Task/Sum-of-squares/ArkScript/sum-of-squares.ark b/Task/Sum-of-squares/ArkScript/sum-of-squares.ark new file mode 100644 index 0000000000..747205c437 --- /dev/null +++ b/Task/Sum-of-squares/ArkScript/sum-of-squares.ark @@ -0,0 +1,16 @@ +(import std.List) + +(assert (= + (list:sum + (list:map + [1 2 3 4 5] + (fun (x) (* x x)))) + 55) + "sum of list is 55") +(assert (= + (list:sum + (list:map + [] + (fun (x) (* x x)))) + 0) + "sum of empty list is 0") diff --git a/Task/Sum-of-squares/Ballerina/sum-of-squares.ballerina b/Task/Sum-of-squares/Ballerina/sum-of-squares.ballerina new file mode 100644 index 0000000000..5e7d6c9862 --- /dev/null +++ b/Task/Sum-of-squares/Ballerina/sum-of-squares.ballerina @@ -0,0 +1,13 @@ +import ballerina/io; + +function sumOfSq(float[] a) returns float { + float sum = 0.0; + foreach float i in a { + sum += i * i; + } + return sum; +} + +public function main() { + io:println(sumOfSq([1, 2, 3, 4, 5])); +} diff --git a/Task/Sum-of-squares/Crystal/sum-of-squares.crystal b/Task/Sum-of-squares/Crystal/sum-of-squares.cr similarity index 100% rename from Task/Sum-of-squares/Crystal/sum-of-squares.crystal rename to Task/Sum-of-squares/Crystal/sum-of-squares.cr diff --git a/Task/Sum-of-squares/Delphi/sum-of-squares.delphi b/Task/Sum-of-squares/Delphi/sum-of-squares.pas similarity index 100% rename from Task/Sum-of-squares/Delphi/sum-of-squares.delphi rename to Task/Sum-of-squares/Delphi/sum-of-squares.pas diff --git a/Task/Sum-of-squares/DuckDB/sum-of-squares-1.duckdb b/Task/Sum-of-squares/DuckDB/sum-of-squares-1.duckdb new file mode 100644 index 0000000000..c3dc742e32 --- /dev/null +++ b/Task/Sum-of-squares/DuckDB/sum-of-squares-1.duckdb @@ -0,0 +1 @@ +select coalesce(sum(pow(x,2)), 0) from t; diff --git a/Task/Sum-of-squares/DuckDB/sum-of-squares-2.duckdb b/Task/Sum-of-squares/DuckDB/sum-of-squares-2.duckdb new file mode 100644 index 0000000000..fbf8860132 --- /dev/null +++ b/Task/Sum-of-squares/DuckDB/sum-of-squares-2.duckdb @@ -0,0 +1,5 @@ +create or replace function ss(columnname, tablename) as ( + coalesce( + (select sum(pow( COLUMNS(x-> x = columnname),2)) as s from query_table(tablename)), + 0) +); diff --git a/Task/Sum-of-squares/DuckDB/sum-of-squares-3.duckdb b/Task/Sum-of-squares/DuckDB/sum-of-squares-3.duckdb new file mode 100644 index 0000000000..2ed26fd794 --- /dev/null +++ b/Task/Sum-of-squares/DuckDB/sum-of-squares-3.duckdb @@ -0,0 +1,3 @@ +create or replace table t as (from values (1),(2) t(i)); + +select ss('i', 't') as "ss of t.i"; diff --git a/Task/Sum-of-squares/DuckDB/sum-of-squares-4.duckdb b/Task/Sum-of-squares/DuckDB/sum-of-squares-4.duckdb new file mode 100644 index 0000000000..3f0fcee4c6 --- /dev/null +++ b/Task/Sum-of-squares/DuckDB/sum-of-squares-4.duckdb @@ -0,0 +1,8 @@ +create or replace function ss(lst) as ( + select (case when length(lst) = 0 then 0 + else list_sum(list_transform( lst, x -> x*x)) + end) +); + +# Example +select ss([]) as 'ss of []', ss([1.0,2.0,3.0]) as "ss of list"; diff --git a/Task/Sum-of-squares/Elena/sum-of-squares.elena b/Task/Sum-of-squares/Elena/sum-of-squares.elena index 113cd3d1ee..16606dfe3c 100644 --- a/Task/Sum-of-squares/Elena/sum-of-squares.elena +++ b/Task/Sum-of-squares/Elena/sum-of-squares.elena @@ -4,9 +4,9 @@ import extensions; SumOfSquares(list) = list.selectBy::(x => x * x).summarize(new Integer()); -public program() +public Program() { - console + Console .printLine(SumOfSquares(new int[]{4, 8, 15, 16, 23, 42})) .printLine(SumOfSquares(new int[]{1, 2, 3, 4, 5})) .printLine(SumOfSquares(Array.MinValue)) diff --git a/Task/Sum-of-squares/Elixir/sum-of-squares.elixir b/Task/Sum-of-squares/Elixir/sum-of-squares.ex similarity index 100% rename from Task/Sum-of-squares/Elixir/sum-of-squares.elixir rename to Task/Sum-of-squares/Elixir/sum-of-squares.ex diff --git a/Task/Sum-of-squares/Emacs-Lisp/sum-of-squares.l b/Task/Sum-of-squares/Emacs-Lisp/sum-of-squares.el similarity index 100% rename from Task/Sum-of-squares/Emacs-Lisp/sum-of-squares.l rename to Task/Sum-of-squares/Emacs-Lisp/sum-of-squares.el diff --git a/Task/Sum-of-squares/Euphoria/sum-of-squares.euphoria b/Task/Sum-of-squares/Euphoria/sum-of-squares.eu similarity index 100% rename from Task/Sum-of-squares/Euphoria/sum-of-squares.euphoria rename to Task/Sum-of-squares/Euphoria/sum-of-squares.eu diff --git a/Task/Sum-of-squares/FutureBasic/sum-of-squares.basic b/Task/Sum-of-squares/FutureBasic/sum-of-squares.basic new file mode 100644 index 0000000000..e8886f6e58 --- /dev/null +++ b/Task/Sum-of-squares/FutureBasic/sum-of-squares.basic @@ -0,0 +1,14 @@ +void local fn DoIt + NSUinteger i, sum = 0 + CFArrayRef array = @[@3, @1, @4, @1, @5, @9] + + for i = 0 to len(array) -1 + sum = sum + intVal( array[i] ) ^ 2 + next + print "The sum of squares is: ", sum +end fn + + +fn DoIt + +HandleEvents diff --git a/Task/Sum-of-squares/Gleam/sum-of-squares.gleam b/Task/Sum-of-squares/Gleam/sum-of-squares.gleam new file mode 100644 index 0000000000..9721f630a6 --- /dev/null +++ b/Task/Sum-of-squares/Gleam/sum-of-squares.gleam @@ -0,0 +1,9 @@ +import gleam/int +import gleam/io +import gleam/list + +pub fn main() -> Nil { + list.fold([3, 1, 4, 1, 5, 9], 0, fn(acc, e) { e * e + acc }) + |> int.to_string + |> io.println +} diff --git a/Task/Sum-of-squares/Julia/sum-of-squares.julia b/Task/Sum-of-squares/Julia/sum-of-squares.jl similarity index 100% rename from Task/Sum-of-squares/Julia/sum-of-squares.julia rename to Task/Sum-of-squares/Julia/sum-of-squares.jl diff --git a/Task/Sum-of-squares/Kotlin/sum-of-squares.kotlin b/Task/Sum-of-squares/Kotlin/sum-of-squares.kts similarity index 100% rename from Task/Sum-of-squares/Kotlin/sum-of-squares.kotlin rename to Task/Sum-of-squares/Kotlin/sum-of-squares.kts diff --git a/Task/Sum-of-squares/Lua/sum-of-squares.lua b/Task/Sum-of-squares/Lua/sum-of-squares.lua index 03f3a40074..5bdae161ee 100644 --- a/Task/Sum-of-squares/Lua/sum-of-squares.lua +++ b/Task/Sum-of-squares/Lua/sum-of-squares.lua @@ -1,3 +1,4 @@ +local unpack = table.unpack or unpack function squaresum(a, ...) return a and a^2 + squaresum(...) or 0 end function squaresumt(t) return squaresum(unpack(t)) end diff --git a/Task/Sum-of-squares/Nu/sum-of-squares.nu b/Task/Sum-of-squares/Nu/sum-of-squares.nu new file mode 100644 index 0000000000..2032012791 --- /dev/null +++ b/Task/Sum-of-squares/Nu/sum-of-squares.nu @@ -0,0 +1,3 @@ +def sqsum []: { + reduce -f 0 {|x res| $x * $x + $res } +} diff --git a/Task/Sum-of-squares/OCaml/sum-of-squares-1.ocaml b/Task/Sum-of-squares/OCaml/sum-of-squares-1.ml similarity index 100% rename from Task/Sum-of-squares/OCaml/sum-of-squares-1.ocaml rename to Task/Sum-of-squares/OCaml/sum-of-squares-1.ml diff --git a/Task/Sum-of-squares/OCaml/sum-of-squares-2.ocaml b/Task/Sum-of-squares/OCaml/sum-of-squares-2.ml similarity index 100% rename from Task/Sum-of-squares/OCaml/sum-of-squares-2.ocaml rename to Task/Sum-of-squares/OCaml/sum-of-squares-2.ml diff --git a/Task/Sum-of-squares/PascalABC.NET/sum-of-squares.pas b/Task/Sum-of-squares/PascalABC.NET/sum-of-squares.pas new file mode 100644 index 0000000000..a6b74f1dd4 --- /dev/null +++ b/Task/Sum-of-squares/PascalABC.NET/sum-of-squares.pas @@ -0,0 +1,3 @@ +## +var vector := Arr(1,2,3,4,5,6,7); +vector.Sum(x -> x * x).Println diff --git a/Task/Sum-of-squares/PowerShell/sum-of-squares.psh b/Task/Sum-of-squares/PowerShell/sum-of-squares.ps1 similarity index 100% rename from Task/Sum-of-squares/PowerShell/sum-of-squares.psh rename to Task/Sum-of-squares/PowerShell/sum-of-squares.ps1 diff --git a/Task/Sum-of-squares/ReScript/sum-of-squares-1.re b/Task/Sum-of-squares/ReScript/sum-of-squares-1.res similarity index 100% rename from Task/Sum-of-squares/ReScript/sum-of-squares-1.re rename to Task/Sum-of-squares/ReScript/sum-of-squares-1.res diff --git a/Task/Sum-of-squares/ReScript/sum-of-squares-2.re b/Task/Sum-of-squares/ReScript/sum-of-squares-2.res similarity index 100% rename from Task/Sum-of-squares/ReScript/sum-of-squares-2.re rename to Task/Sum-of-squares/ReScript/sum-of-squares-2.res diff --git a/Task/Sum-of-squares/Rust/sum-of-squares.rust b/Task/Sum-of-squares/Rust/sum-of-squares.rs similarity index 100% rename from Task/Sum-of-squares/Rust/sum-of-squares.rust rename to Task/Sum-of-squares/Rust/sum-of-squares.rs diff --git a/Task/Sum-of-squares/Scheme/sum-of-squares.ss b/Task/Sum-of-squares/Scheme/sum-of-squares.scm similarity index 100% rename from Task/Sum-of-squares/Scheme/sum-of-squares.ss rename to Task/Sum-of-squares/Scheme/sum-of-squares.scm diff --git a/Task/Sum-of-squares/Tailspin/sum-of-squares.tailspin b/Task/Sum-of-squares/Tailspin/sum-of-squares-1.tailspin similarity index 100% rename from Task/Sum-of-squares/Tailspin/sum-of-squares.tailspin rename to Task/Sum-of-squares/Tailspin/sum-of-squares-1.tailspin diff --git a/Task/Sum-of-squares/Tailspin/sum-of-squares-2.tailspin b/Task/Sum-of-squares/Tailspin/sum-of-squares-2.tailspin new file mode 100644 index 0000000000..13460e2ec8 --- /dev/null +++ b/Task/Sum-of-squares/Tailspin/sum-of-squares-2.tailspin @@ -0,0 +1,8 @@ +ssq templates + @ set 0; + $... -> @ set $@ + $*$; + $@ ! +end ssq + +[] -> ssq ! -- outputs 0 +[1..5] -> ssq ! -- outputs 55 diff --git a/Task/Sum-of-squares/V-(Vlang)/sum-of-squares-1.v b/Task/Sum-of-squares/V-(Vlang)/sum-of-squares-1.v new file mode 100644 index 0000000000..4e6c9d08d1 --- /dev/null +++ b/Task/Sum-of-squares/V-(Vlang)/sum-of-squares-1.v @@ -0,0 +1,12 @@ +fn main() { + a_list := [1, 2, 3, 4, 5] + println(sum_of_squares(a_list)) +} + +fn sum_of_squares(int_arr []int) int { + mut sum := 0 + for _, elem in int_arr { + sum += elem * elem + } + return sum +} diff --git a/Task/Sum-of-squares/V-(Vlang)/sum-of-squares-2.v b/Task/Sum-of-squares/V-(Vlang)/sum-of-squares-2.v new file mode 100644 index 0000000000..c3ffd82536 --- /dev/null +++ b/Task/Sum-of-squares/V-(Vlang)/sum-of-squares-2.v @@ -0,0 +1,6 @@ +import arrays + +fn main() { + a_list := [1, 2, 3, 4, 5] + println(arrays.sum(a_list.map(it * it))!) +} diff --git a/Task/Sum-of-squares/VBScript/sum-of-squares.vb b/Task/Sum-of-squares/VBScript/sum-of-squares.vbs similarity index 100% rename from Task/Sum-of-squares/VBScript/sum-of-squares.vb rename to Task/Sum-of-squares/VBScript/sum-of-squares.vbs diff --git a/Task/Sum-to-100/ALGOL-68/sum-to-100.alg b/Task/Sum-to-100/ALGOL-68/sum-to-100.alg index 181d66553d..12cbe68f16 100644 --- a/Task/Sum-to-100/ALGOL-68/sum-to-100.alg +++ b/Task/Sum-to-100/ALGOL-68/sum-to-100.alg @@ -2,29 +2,18 @@ BEGIN # find the numbers the string 123456789 ( with "+/-" optionally inserted # # before each digit ) can generate # - # experimentation shows that the largest hundred numbers that can be # - # generated are are greater than or equal to 56795 # - # as we can't declare an array with bounds -123456789 : 123456789 in # - # Algol 68G, we use -60000 : 60000 and keep counts for the top hundred # + PR read "sort.incl.a68" PR # include sorting utilities # - INT max number = 60 000; - [ - max number : max number ]STRING solutions; - [ - max number : max number ]INT count; - FOR i FROM LWB solutions TO UPB solutions DO solutions[ i ] := ""; count[ i ] := 0 OD; + # calculate the numbers we can generate and the strings leading to them # + # as noted by other solutions, at most 13122 (2*3^8) can be generated # - # calculate the numbers ( up to max number ) we can generate and the strings leading to them # - # also determine the largest numbers we can generate # - [ 100 ]INT largest; - [ 100 ]INT largest count; - INT impossible number = - 999 999 999; - FOR i FROM LWB largest TO UPB largest DO - largest [ i ] := impossible number; - largest count[ i ] := 0 - OD; + INT max expr = 2 * 3^8; + [ 1 : max expr ]INT value; + [ 1 : max expr ]STRING expression; + INT expr pos := 0; [ 1 : 18 ]CHAR sum string := ".1.2.3.4.5.6.7.8.9"; []CHAR sign char = []CHAR( "-", " ", "+" )[ AT -1 ]; - # we don't distinguish between strings starting "+1" and starting " 1" # - FOR s1 FROM -1 TO 0 DO + FOR s1 FROM -1 TO 0 DO # we don't distinguish between strings starting "+1" and starting " 1" # sum string[ 1 ] := sign char[ s1 ]; FOR s2 FROM -1 TO 1 DO sum string[ 3 ] := sign char[ s2 ]; @@ -52,28 +41,10 @@ BEGIN IF s7 = 0 THEN part *:= 10 +:= 7 * SIGN part ELSE number +:= part; part := 7 * s7 FI; IF s8 = 0 THEN part *:= 10 +:= 8 * SIGN part ELSE number +:= part; part := 8 * s8 FI; IF s9 = 0 THEN part *:= 10 +:= 9 * SIGN part ELSE number +:= part; part := 9 * s9 FI; - number +:= part; - IF number >= LWB solutions AND number <= UPB solutions THEN - solutions[ number ] +:= ";" + sum string; - count [ number ] +:= 1 - FI; - BOOL inserted := FALSE; - FOR l pos FROM LWB largest TO UPB largest WHILE NOT inserted DO - IF number > largest[ l pos ] THEN - # found a new larger number # - FOR m pos FROM UPB largest BY -1 TO l pos + 1 DO - largest [ m pos ] := largest [ m pos - 1 ]; - largest count[ m pos ] := largest count[ m pos - 1 ] - OD; - largest [ l pos ] := number; - largest count[ l pos ] := 1; - inserted := TRUE - ELIF number = largest[ l pos ] THEN - # have another way of generating this number # - largest count[ l pos ] +:= 1; - inserted := TRUE - FI - OD + number +:= part; + expr pos +:= 1; + expression[ expr pos ] := sum string; + value[ expr pos ] := number OD OD OD @@ -85,45 +56,66 @@ BEGIN OD; # show the solutions for 100 # - print( ( "100 has ", whole( count[ 100 ], 0 ), " solutions:" ) ); - STRING s := solutions[ 100 ]; - FOR s pos FROM LWB s TO UPB s DO - IF s[ s pos ] = ";" THEN print( ( newline, " " ) ) - ELIF s[ s pos ] /= " " THEN print( ( s[ s pos ] ) ) + INT count 100 := 0; + FOR x pos FROM LWB value TO UPB value DO + IF value[ x pos ] = 100 THEN count 100 +:= 1 FI + OD; + print( ( "100 has ", whole( count 100, 0 ), " solutions:", newline ) ); + FOR x pos FROM LWB value TO UPB value DO + IF value[ x pos ] = 100 THEN + print( ( " " ) ); + STRING s = expression[ x pos ]; + FOR s pos FROM LWB s TO UPB s DO IF s[ s pos ] /= " " THEN print( ( s[ s pos ] ) ) FI OD; + print( ( newline ) ) FI OD; - print( ( newline ) ); + + QUICKSORT value; # sort the values (the expressions will now be out of order) # + # find the number with the most solutions # - INT max solutions := 0; - INT number with max := LWB count - 1; - FOR n FROM 0 TO max number DO - IF count[ n ] > max solutions THEN - max solutions := count[ n ]; - number with max := n + INT this count := 1, max count := 1, max count value := value[ LWB value ]; + FOR v pos FROM LWB value + 1 TO UPB value DO + IF value[ v pos ] = value[ v pos - 1 ] THEN + this count +:= 1 + ELSE + IF this count > max count AND value[ v pos - 1 ] >= 0 THEN + max count := this count; + max count value := value[ v pos - 1 ] + FI; + this count := 1 FI OD; - FOR n FROM LWB largest count TO UPB largest count DO - IF largest count[ n ] > max solutions THEN - max solutions := largest count[ n ]; - number with max := largest[ n ] - FI - OD; - print( ( whole( number with max, 0 ), " has the maximum number of solutions: " ) ); - print( ( whole( max solutions, 0 ), newline ) ); - # find the smallest positive number that has no solutions # - BOOL have solutions := TRUE; - FOR n FROM 0 TO max number - WHILE IF NOT ( have solutions := count[ n ] > 0 ) - THEN print( ( whole( n, 0 ), " is the lowest positive number with no solutions", newline ) ) - FI; - have solutions - DO SKIP OD; - IF have solutions - THEN print( ( "All positive numbers up to ", whole( max number, 0 ), " have solutions", newline ) ) + IF this count > max count THEN + # the final value has the maximum count # + max count := this count; + max count value := value[ UPB value ] FI; + print( ( whole( max count value, 0 ), " has the maximum number of solutions: " ) ); + print( ( whole( max count, 0 ), newline ) ); + + # find the smallest positive number that has no solutions # + BOOL have solution := TRUE; + INT missing value := 1; + FOR v pos FROM LWB value TO UPB value WHILE have solution DO + IF value[ v pos ] > 0 THEN + IF value[ v pos ] /= value[ v pos - 1 ] THEN + have solution := value[ v pos ] = missing value; + IF have solution THEN + missing value +:= 1 + FI + FI + FI + OD; + print( ( whole( missing value, 0 ), " is the lowest positive number with no solutions", newline ) ); + + # show the ten largest numbers that can be generated # print( ( "The 10 largest numbers that can be generated are:", newline ) ); - FOR t pos FROM 1 TO 10 DO - print( ( " ", whole( largest[ t pos ], 0 ) ) ) + INT shown := 0; + FOR v pos FROM UPB value - 1 BY -1 TO LWB value WHILE shown < 10 DO + IF value[ v pos ] /= value[ v pos + 1 ] THEN + print( ( " ", whole( value[ v pos + 1 ], 0 ) ) ); + shown +:= 1 + FI OD; print( ( newline ) ) diff --git a/Task/Sum-to-100/Ada/sum-to-100-1.ada b/Task/Sum-to-100/Ada/sum-to-100-1.adb similarity index 100% rename from Task/Sum-to-100/Ada/sum-to-100-1.ada rename to Task/Sum-to-100/Ada/sum-to-100-1.adb diff --git a/Task/Sum-to-100/Ada/sum-to-100-2.ada b/Task/Sum-to-100/Ada/sum-to-100-2.adb similarity index 100% rename from Task/Sum-to-100/Ada/sum-to-100-2.ada rename to Task/Sum-to-100/Ada/sum-to-100-2.adb diff --git a/Task/Sum-to-100/Ada/sum-to-100-3.ada b/Task/Sum-to-100/Ada/sum-to-100-3.adb similarity index 100% rename from Task/Sum-to-100/Ada/sum-to-100-3.ada rename to Task/Sum-to-100/Ada/sum-to-100-3.adb diff --git a/Task/Sum-to-100/Ada/sum-to-100-4.ada b/Task/Sum-to-100/Ada/sum-to-100-4.adb similarity index 100% rename from Task/Sum-to-100/Ada/sum-to-100-4.ada rename to Task/Sum-to-100/Ada/sum-to-100-4.adb diff --git a/Task/Sum-to-100/Crystal/sum-to-100.cr b/Task/Sum-to-100/Crystal/sum-to-100.cr new file mode 100644 index 0000000000..d62cbcfc86 --- /dev/null +++ b/Task/Sum-to-100/Crystal/sum-to-100.cr @@ -0,0 +1,37 @@ +# since there are 8 possible places to split the 123456789 string, +# we can map each to a bit in a byte and split if the bit is 1 +def split_digits (pattern) + result = [] of Int32 + number = 1 + (2..9).each do |digit| + if pattern.odd? + result << number + number = 0 + end + number = number * 10 + digit + pattern >>= 1 + end + result << number +end + +sums = Hash(Int32, Int32).new(0) + +puts "Sum to 100:" +(0_u8..255_u8).each do |pattern| + numbers = split_digits(pattern) + Indexable.each_cartesian([[1, -1]] * numbers.size) do |mults| + sum = numbers.zip(mults).sum {|n, m| n * m } + sums[sum] += 1 + if sum == 100 + puts numbers.zip(mults).map {|n, m| (m == 1 ? "+" : "-") + n.to_s }.join + end + end +end +puts +print "Positive sum with maximum number of solutions: " +puts "%d (%d solutions)" % sums.select {|k, _| k >= 0 }.max_by {|_, v| v} +puts +print "Lowest positive sum that can't be expressed: " +puts (0..).find {|i| !sums.has_key? i } +puts +puts "Ten highest sums: #{sums.keys.max(10)}" diff --git a/Task/Sum-to-100/D/sum-to-100.d b/Task/Sum-to-100/D/sum-to-100.d index f1a238399d..10a55b42ac 100644 --- a/Task/Sum-to-100/D/sum-to-100.d +++ b/Task/Sum-to-100/D/sum-to-100.d @@ -29,7 +29,6 @@ void main() { writeln(value); comment("Show the ten highest numbers that can be expressed"); - const int n = stat.countSum.keys.length; auto sums = stat.countSum.keys; sums.sort!"a>b" .take(10) diff --git a/Task/Sum-to-100/EasyLang/sum-to-100.easy b/Task/Sum-to-100/EasyLang/sum-to-100.easy index ad5820f9e0..ac4c070284 100644 --- a/Task/Sum-to-100/EasyLang/sum-to-100.easy +++ b/Task/Sum-to-100/EasyLang/sum-to-100.easy @@ -1,10 +1,6 @@ ADD = 0 SUB = 1 -nexpr = 13122 - 1 -len f[] nexpr + 1 -arrbase f[] 0 -# -func evaluate code . +fastfunc evaluate code . power = 1 for k = 9 downto 1 numb += power * k @@ -24,21 +20,21 @@ func evaluate code . . return value . -proc init . . +nexpr = 2 * pow 3 8 + 1 +# +len f[] nexpr +fastproc . for i = 0 to nexpr f[i] = evaluate i . . -call init -proc out code . . +proc out code . a = 19683 b = 6561 for k = 1 to 9 h = code mod a div b if h = ADD - if k > 1 - s$ &= "+" - . + if k > 1 : s$ &= "+" elif h = SUB s$ &= "-" . @@ -48,55 +44,55 @@ proc out code . . . print evaluate code & " = " & s$ . +# print "Show all solutions that sum to 100\n" -for i = 0 to nexpr - if f[i] = 100 - out i - . +proc . + for i = 1 to nexpr : if f[i] = 100 : out i . +# print "\nShow the sum that has the maximum number of solutions\n" -for i = 0 to nexpr - test = f[i] - if test > 0 - ntest = 0 - for j = 0 to nexpr - if f[j] = test - ntest += 1 +global best nbest . +fastproc . + for i = 1 to nexpr + test = f[i] + if test > 0 + ntest = 0 + for j = 1 to nexpr + if f[j] = test : ntest += 1 + . + if ntest > nbest + best = test + nbest = ntest . - . - if ntest > nbest - best = test - nbest = ntest . . . print best & " has " & nbest & " solutions" +# print "\nShow the lowest positive number that can't be expressed\n" -for i = 0 to 123456789 - for j = 0 to nexpr - if i = f[j] - break 1 +proc . + for i = 0 to 123456789 + for j = 1 to nexpr + if i = f[j] : break 1 . + if j > nexpr : break 1 . - if j > nexpr - break 1 - . + print i . -print i print "\nShow the ten highest numbers that can be expressed\n" -limit = 123456789 + 1 -for i = 1 to 10 - best = 0 - for j = 0 to nexpr - test = f[j] - if test < limit and test > best - best = test +proc . + limit = 123456789 + 1 + for i = 1 to 10 + best = 0 + for j = 1 to nexpr + test = f[j] + if test < limit and test > best + best = test + . . - . - for j = 0 to nexpr - if f[j] = best - out j + for j = 1 to nexpr + if f[j] = best : out j . + limit = best . - limit = best . diff --git a/Task/Sum-to-100/Elixir/sum-to-100.elixir b/Task/Sum-to-100/Elixir/sum-to-100.elixir deleted file mode 100644 index 993168368f..0000000000 --- a/Task/Sum-to-100/Elixir/sum-to-100.elixir +++ /dev/null @@ -1,46 +0,0 @@ -defmodule Sum do - def to(val) do - generate - |> Enum.map(&{eval(&1), &1}) - |> Enum.filter(fn {v, _s} -> v==val end) - |> Enum.each(&IO.inspect &1) - end - - def max_solve do - generate - |> Enum.group_by(&eval &1) - |> Enum.filter_map(fn {k,_} -> k>=0 end, fn {k,v} -> {length(v),k} end) - |> Enum.max - |> fn {len,sum} -> IO.puts "sum of #{sum} has the maximum number of solutions : #{len}" end.() - end - - def min_solve do - solve = generate |> Enum.group_by(&eval &1) - Stream.iterate(1, &(&1+1)) - |> Enum.find(fn n -> solve[n]==nil end) - |> fn sum -> IO.puts "lowest positive sum that can't be expressed : #{sum}" end.() - end - - def highest_sums(n\\10) do - IO.puts "highest sums :" - generate - |> Enum.map(&eval &1) - |> Enum.uniq - |> Enum.sort_by(fn sum -> -sum end) - |> Enum.take(n) - |> IO.inspect - end - - defp generate do - x = ["+", "-", ""] - for a <- ["-", ""], b <- x, c <- x, d <- x, e <- x, f <- x, g <- x, h <- x, i <- x, - do: "#{a}1#{b}2#{c}3#{d}4#{e}5#{f}6#{g}7#{h}8#{i}9" - end - - defp eval(str), do: Code.eval_string(str) |> elem(0) -end - -Sum.to(100) -Sum.max_solve -Sum.min_solve -Sum.highest_sums diff --git a/Task/Sum-to-100/Elixir/sum-to-100.ex b/Task/Sum-to-100/Elixir/sum-to-100.ex new file mode 100644 index 0000000000..134a89fa17 --- /dev/null +++ b/Task/Sum-to-100/Elixir/sum-to-100.ex @@ -0,0 +1,47 @@ +defmodule Sum do + def to(val) do + generate() + |> Enum.map(&{eval(&1), &1}) + |> Enum.filter(fn {v, _s} -> v==val end) + |> Enum.each(&IO.inspect &1) + end + + def max_solve do + generate() + |> Enum.group_by(&eval &1) + |> Enum.filter(fn {k,_} -> k>=0 end) + |> Enum.map(fn {k,v} -> {length(v),k} end) + |> Enum.max + |> fn {len,sum} -> IO.puts "sum of #{sum} has the maximum number of solutions : #{len}" end.() + end + + def min_solve do + solve = generate() |> Enum.group_by(&eval &1) + Stream.iterate(1, &(&1+1)) + |> Enum.find(fn n -> solve[n]==nil end) + |> fn sum -> IO.puts "lowest positive sum that can't be expressed : #{sum}" end.() + end + + def highest_sums(n\\10) do + IO.puts "highest sums :" + generate() + |> Enum.map(&eval &1) + |> Enum.uniq + |> Enum.sort_by(fn sum -> -sum end) + |> Enum.take(n) + |> IO.inspect + end + + defp generate do + x = ["+", "-", ""] + for a <- ["-", ""], b <- x, c <- x, d <- x, e <- x, f <- x, g <- x, h <- x, i <- x, + do: "#{a}1#{b}2#{c}3#{d}4#{e}5#{f}6#{g}7#{h}8#{i}9" + end + + defp eval(str), do: Code.eval_string(str) |> elem(0) +end + +Sum.to(100) +Sum.max_solve +Sum.min_solve +Sum.highest_sums diff --git a/Task/Sum-to-100/FutureBasic/sum-to-100.basic b/Task/Sum-to-100/FutureBasic/sum-to-100.basic new file mode 100644 index 0000000000..c9fffab6cb --- /dev/null +++ b/Task/Sum-to-100/FutureBasic/sum-to-100.basic @@ -0,0 +1,120 @@ +// +// Using FutureBasic 7.0.34, July 2025 R.W. +// +// Sum to 100 solutions +// +// Using 123456789 digits so the resulting +// mathematical expression adds up to a 100 +// using "-" and "+" operators only +// + +Int maxPerm, allDigits + +maxPerm = 13122 //2 * 3 ^ 8 max permutation +allDigits = 123456789 + +Int sum(13121) +CFStringRef equation + +// Get sum of one of the permutation +// on entry: n = permutation number +// on exit: ret = sum +// modifies global var equation + +local fn doEval( n as UInt32) as Int + + CFStringRef evalstr + boolean doAdd = _False + Int ret, cPtr, x, sw + + evalstr = @"9" + ret = 0: cPtr = 9 + doAdd = (n => (maxPerm / 2)) + + for x = 8 to 1 step -1 //do 87654321 + sw = n % 3 + if sw == 0 then cPtr += x * 10^(1 + fix(log(cPtr + 0.5) / log(10))) + if sw == 1 + ret += cPtr + cPtr = x + evalstr = concat (@" + ",evalstr) + end if + if sw == 2 + ret -= cPtr + cPtr = x + evalstr = concat (@" - ",evalstr) + end if + evalstr = concat(mid(str(x),1),evalstr) + n = fix(n/3) + next x + + if doAdd == 0 + evalstr = concat(@" - ", evalstr) + ret -= cPtr + else + ret += cPtr + end if + + evalstr = concat(str(ret),@" = ",evalstr) + equation = evalstr +end fn = ret + +window 1,@"Sum to 100" + + +Int x, y, curr + +// calculate all solutions 2 * 3 ^ 8 +// +for x = maxPerm-1 to 0 step -1 + equation = @"" + curr = fn DoEval(x) + sum(x) = curr + if curr = 100 then print equation +next x +print + +// sum with most solution + +Int i,j,sav,most,tot + +for x = 0 to maxPerm-1 + sav = 0 + for y = 0 to maxPerm-1 + if sum(y) == sum(x) then sav++ + next y + if sav > tot then tot = sav: most = sum(x) +next x +print most;" has most solutions occurring ";tot;" times." + +// lowest non negative with no solution + +boolean sk = _False +for x = 0 to allDigits-1 + for y = 0 to maxPerm-1 + if sum(y) == x then sk = _True: y = maxPerm + next y + if !sk + print "The first non negative number that has no solution is ";x + exit for + else + sk = _False + end if +next x + +// ten highest with solution + +print +print "The ten highest numbers that can be expressed:" + +most = 0 +for x = 1 to 10 + for y = 0 to maxPerm-1 + if sum(y) > sum(most) then most = y + next y + fn doEval(most) + print equation + sum(most) = 0 +next x + +HandleEvents diff --git a/Task/Sum-to-100/Julia/sum-to-100.julia b/Task/Sum-to-100/Julia/sum-to-100.jl similarity index 100% rename from Task/Sum-to-100/Julia/sum-to-100.julia rename to Task/Sum-to-100/Julia/sum-to-100.jl diff --git a/Task/Sum-to-100/Kotlin/sum-to-100.kotlin b/Task/Sum-to-100/Kotlin/sum-to-100.kts similarity index 100% rename from Task/Sum-to-100/Kotlin/sum-to-100.kotlin rename to Task/Sum-to-100/Kotlin/sum-to-100.kts diff --git a/Task/Sum-to-100/Phix/sum-to-100.phix b/Task/Sum-to-100/Phix/sum-to-100.phix index 1b038acca2..f5c42a4dcd 100644 --- a/Task/Sum-to-100/Phix/sum-to-100.phix +++ b/Task/Sum-to-100/Phix/sum-to-100.phix @@ -1,86 +1,81 @@ -(phixonline)--> - with javascript_semantics - enum SUB=-1, NOP=0, ADD=1 +with javascript_semantics +enum SUB=-1, NOP=0, ADD=1 - function evaluate(sequence s) - integer res = 0, tmp = 0, op = ADD - for i=1 to length(s) do - if s[i]=NOP then - tmp = tmp*10+i - else - res += op*tmp - tmp = i - op = s[i] - end if - end for - return res + op*tmp - end function +function evaluate(sequence s) + integer res = 0, tmp = 0, op = ADD + for i=1 to length(s) do + if s[i]=NOP then + tmp = tmp*10+i + else + res += op*tmp + tmp = i + op = s[i] + end if + end for + return res + op*tmp +end function - procedure show(sequence s) - string res = "" - for i=1 to length(s) do - if s[i]!=NOP then - res &= ','-s[i] - end if - res &= '0'+i - end for - printf(1,"%s = %d\n",{res,evaluate(s)}) - end procedure +procedure show(sequence s) + string res = "" + for i=1 to length(s) do + if s[i]!=NOP then + res &= ','-s[i] + end if + res &= '0'+i + end for + printf(1,"%s = %d\n",{res,evaluate(s)}) +end procedure - -- Logically this intersperses -/nop/+ between each digit, but you do not actually need the digit. - sequence s = repeat(SUB,9) -- (==> ..nop+add*8) +-- Logically this intersperses -/nop/+ between each digit, but you do not actually need the digit. +sequence s = repeat(SUB,9) -- (==> ..nop+add*8) - bool done = false - integer maxl = 0, maxr - integer count = 0 - while not done do - count += 1 - integer r = evaluate(s), k = getd_index(r) - sequence solns = iff(k=0?{}:deep_copy(getd_by_index(k))) - solns = append(solns,deep_copy(s)) - setd(r,solns) - if r>0 and maxl<length(solns) then - maxl = length(solns) - maxr = r - end if - for i=length(s) to 1 by -1 do - if i=1 and s[i]=NOP then - done = true - exit - elsif s[i]!=ADD then - s[i] += 1 - exit - end if - s[i] = SUB - end for - end while +bool done = false +integer maxl = 0, maxr, count = 0 +while not done do + count += 1 + integer r = evaluate(s), k = getd_index(r) + sequence solns = iff(k=0?{}:deep_copy(getd_by_index(k))) + solns = append(solns,deep_copy(s)) + setd(r,solns) + if r>0 and maxlprintf
    (1,"%d solutions considered (dictionary size: %d)\n",{count,dict_size()}) +printf(1,"%d solutions considered (dictionary size: %d)\n",{count,dict_size()}) - sequence s100 = getd(100) - printf(1,"There are %d sums to 100:\n",{length(s100)}) - papply(s100,show) +sequence s100 = getd(100) +printf(1,"There are %d sums to 100:\n",{length(s100)}) +papply(s100,show) - printf(1,"The positive sum of %d has the maximum number of solutions: %d\n",{maxr,maxl}) +printf(1,"The positive sum of %d has the maximum number of solutions: %d\n",{maxr,maxl}) - integer prev = 0 - function missing(integer key, sequence /*data*/, integer /*pkey*/, object /*user_data=-2*/) - if key!=prev+1 then - return 0 - end if - prev = key - return 1 - end function - traverse_dict_partial_key(missing,1) - printf(1,"The lowest positive sum that cannot be expressed: %d\n",{prev+1}) +integer prev = 0 +function missing(integer key, sequence /*data*/, integer /*pkey*/, object /*user_data=-2*/) + if key!=prev+1 then + return 0 + end if + prev = key + return 1 +end function +traverse_dict_partial_key(missing,1) +printf(1,"The lowest positive sum that cannot be expressed: %d\n",{prev+1}) - sequence highest = {} - function top10(integer key, sequence /*data*/, object /*user_data*/) - highest &= key - return length(highest)<10 - end function - --DEV named params on builtins need pre-loading...: - --traverse_dict(top10,rev:=1) - traverse_dict(top10,0,1,true) - printf(1,"The 10 highest sums: %v\n",{highest}) - - with javascript_semantics - string n = "000000" +with javascript_semantics +string n = "000000" - function incn() - for i=length(n) to 1 by -1 do - if n[i]='9' then - if i=1 then return false end if - n[i]='0' - else - n[i] += 1 - exit - end if - end for - return true - end function +function incn() + for i=length(n) to 1 by -1 do + if n[i]='9' then + if i=1 then return false end if + n[i]='0' + else + n[i] += 1 + exit + end if + end for + return true +end function - sequence res = {}, bestseen - integer maxcycle = 0 +sequence res = {}, bestseen +integer maxcycle = 0 - procedure srs() - sequence curr = n - while length(curr)>1 and curr[1]='0' do - curr = curr[2..$] - end while - integer ch = curr[1] - for i=2 to length(curr) do - if curr[i]>ch then return end if - ch = curr[i] - end for - sequence seen = {curr} - integer cycle = 1 - while true do - sequence digits = repeat(0,10) - for i=1 to length(curr) do - integer idx = curr[i]-'0'+1 - digits[idx] += 1 - end for - string next = "" - for i=length(digits) to 1 by -1 do - if digits[i]!=0 then - next &= sprint(digits[i]) - next &= i+'0'-1 - end if - end for - if find(next,seen) then exit end if - seen = append(seen,next) - curr = next - cycle += 1 - end while - if cycle>maxcycle then - res = {seen[1]} - maxcycle = cycle - bestseen = seen - elsif cycle=maxcycle then - res = append(res,seen[1]) - end if - end procedure +procedure srs() + sequence curr = n + while length(curr)>1 and curr[1]='0' do + curr = curr[2..$] + end while + integer ch = curr[1] + for i=2 to length(curr) do + if curr[i]>ch then return end if + ch = curr[i] + end for + sequence seen = {curr} + integer cycle = 1 + while true do + sequence digits = repeat(0,10) + for i=1 to length(curr) do + integer idx = curr[i]-'0'+1 + digits[idx] += 1 + end for + string next = "" + for i=length(digits) to 1 by -1 do + if digits[i]!=0 then + next &= sprint(digits[i]) + next &= i+'0'-1 + end if + end for + if find(next,seen) then exit end if + seen = append(seen,next) + curr = next + cycle += 1 + end while + if cycle>maxcycle then + res = {seen[1]} + maxcycle = cycle + bestseen = seen + elsif cycle=maxcycle then + res = append(res,seen[1]) + end if +end procedure - while true do - srs() - if not incn() then exit end if - end while +while true do + srs() + if not incn() then exit end if +end while - -- add non-leading-0 perms: - for i=length(res) to 1 by -1 do - string ri = res[i] - for p=1 to factorial(length(ri)) do - string pri = permute(p,ri) - if pri[1]!='0' and not find(pri,res) then - res = append(res,pri) - end if - end for - end for - ?res - puts(1,"cycle length is ") ?maxcycle - pp(bestseen,{pp_Nest,1}) - - function sp(integer n) return is_prime(sum(get_primes(-n))) end function - sequence res = apply(filter(tagset(length(get_primes_le(1000))),sp),sprint) - printf(1,"Found %d of em: %s\n",{length(res),join(shorten(res,"",5),", ")}) - - -- demo\rosetta\Synchronous_concurrency.exw - without js -- threads, file i/o, command_line() - string filename = substitute(command_line()[2],".exe",".exw") +-- demo\rosetta\Synchronous_concurrency.exw +without js -- threads, file i/o, command_line() +string filename = substitute(command_line()[2],".exe",".exw") - atom frThread, -- file reader thread - lcThread -- line counter thread +atom frThread, -- file reader thread + lcThread -- line counter thread - sequence queue = {} - integer qlock = init_cs(), - linecount = 1 +sequence queue = {} +integer qlock = init_cs(), + linecount = 1 - procedure readfile() - integer fn = open(filename,"r") - while 1 do - object line = gets(fn) - enter_cs(qlock) - queue = append(queue,line) - line = atom(line) -- kill refcount! - leave_cs(qlock) - if line then exit end if - end while - close(fn) - wait_thread(lcThread) - printf(1,"Lines read: %d\n",linecount) - exit_thread(0) - end procedure +procedure readfile() + integer fn = open(filename,"r") + while 1 do + object line = gets(fn) + enter_cs(qlock) + queue = append(queue,line) + line = atom(line) -- kill refcount! + leave_cs(qlock) + if line then exit end if + end while + close(fn) + wait_thread(lcThread) + printf(1,"Lines read: %d\n",linecount) + exit_thread(0) +end procedure - procedure countlines() - linecount = 0 - while 1 do - enter_cs(qlock) - if length(queue)=0 then - leave_cs(qlock) - -- sleep(0.1) - else - object line = queue[1] - queue = queue[2..$] - leave_cs(qlock) - if atom(line) then exit end if - -- ?line - linecount += 1 - end if - end while - exit_thread(0) - end procedure +procedure countlines() + linecount = 0 + while 1 do + enter_cs(qlock) + if length(queue)=0 then + leave_cs(qlock) +-- sleep(0.1) + else + object line = queue[1] + queue = queue[2..$] + leave_cs(qlock) + if atom(line) then exit end if +-- ?line + linecount += 1 + end if + end while + exit_thread(0) +end procedure - lcThread = create_thread(countlines,{}) - frThread = create_thread(readfile,{}) +lcThread = create_thread(countlines,{}) +frThread = create_thread(readfile,{}) - wait_thread(frThread) - puts(1,"done") +wait_thread(frThread) +puts(1,"done") - {} = wait_key() - - include timedate.e - ?format_timedate(date(),"Dddd, Mmmm dth, YYYY, h:mm:ss pm") +with javascript_semantics +include timedate.e +?format_timedate(date(),"Dddd, Mmmm dth, YYYY, h:mm:ss pm") - atom t0 = time() - sleep(0.9) - ?time()-t0 - - for i=1 to 100 do - printf(1,"%3d",{length(factors(i,1))}) - if remainder(i,20)=0 then puts(1,"\n") end if - end for - - sequence r = apply(apply(true,factors,{tagset(100),{1}}),length) - puts(1,join_by(apply(true,sprintf,{{"%3d"},r}),1,20,"")) - - enum T, M, F - type ternary(integer t) return find(t,{T,M,F}) end type +enum T, M, F +type ternary(integer t) return find(t,{T,M,F}) end type - function t_not(ternary a) - return F+1-a - end function +function t_not(ternary a) + return F+1-a +end function - function t_and(ternary a, ternary b) - return iff(a=T and b=T?T:iff(a=F or b=F?F:M)) - end function +function t_and(ternary a, ternary b) + return iff(a=T and b=T?T:iff(a=F or b=F?F:M)) +end function - function t_or(ternary a, ternary b) - return iff(a=T or b=T?T:iff(a=F and b=F?F:M)) - end function +function t_or(ternary a, ternary b) + return iff(a=T or b=T?T:iff(a=F and b=F?F:M)) +end function - function t_xor(ternary a, ternary b) - return iff(a=M or b=M?M:iff(a=b?F:T)) - end function +function t_xor(ternary a, ternary b) + return iff(a=M or b=M?M:iff(a=b?F:T)) +end function - function t_implies(ternary a, ternary b) - return iff(a=F or b=T?T:iff(a=T and b=F?F:M)) - end function +function t_implies(ternary a, ternary b) + return iff(a=F or b=T?T:iff(a=T and b=F?F:M)) +end function - function t_equal(ternary a, ternary b) - return iff(a=M or b=M?M:iff(a=b?T:F)) - end function +function t_equal(ternary a, ternary b) + return iff(a=M or b=M?M:iff(a=b?T:F)) +end function - function t_string(ternary a) - return iff(a=T?"T":iff(a=M?"?":"F")) - end function +function t_string(ternary a) + return iff(a=T?"T":iff(a=M?"?":"F")) +end function - procedure show_truth_table(integer rid, integer unary, string name) - printf(1,"%-3s |%s\n",{name,iff(unary?"":" T | ? | F")}) - printf(1,"----+---%s\n",{iff(unary?"":"+---+---")}) - for x=T to F do - printf(1," %s ",{t_string(x)}) - if unary then - printf(1," | %s",{t_string(rid(x))}) - else - for y=T to F do - printf(1," | %s",{t_string(rid(x,y))}) - end for - end if - printf(1,"\n") - end for - printf(1,"\n") - end procedure +procedure show_truth_table(integer rid, integer unary, string name) + printf(1,"%-3s |%s\n",{name,iff(unary?"":" T | ? | F")}) + printf(1,"----+---%s\n",{iff(unary?"":"+---+---")}) + for x=T to F do + printf(1," %s ",{t_string(x)}) + if unary then + printf(1," | %s",{t_string(rid(x))}) + else + for y=T to F do + printf(1," | %s",{t_string(rid(x,y))}) + end for + end if + printf(1,"\n") + end for + printf(1,"\n") +end procedure - show_truth_table(t_not,1,"not") - show_truth_table(t_and,0,"and") - show_truth_table(t_or,0,"or") - show_truth_table(t_xor,0,"xor") - show_truth_table(t_implies,0,"imp") - show_truth_table(t_equal,0,"eq") - - constant fmt = """ - %s, %s, bo-%s - Banana-fana fo-%s - Fee-fi-mo-%s - %s! +constant fmt = """ +%s, %s, bo-%s +Banana-fana fo-%s +Fee-fi-mo-%s +%s! - """ - procedure printVerse(string name) - string x = lower(name) - integer x1 = upper(x[1]), - vowel = find(x1,"AEIUO")!=0 - string y = x[2-vowel..$], - b = 'b'&y, f = 'f'&y, m = 'm'&y - x[1] = x1 - switch x1 do - case 'B': b = y - case 'F': f = y - case 'M': m = y - end switch - printf(1,fmt,{x, x, b, f, m, x}) - end procedure +""" +procedure printVerse(string name) + string x = lower(name) + integer x1 = upper(x[1]), + vowel = find(x1,"AEIUO")!=0 + string y = x[2-vowel..$], + b = 'b'&y, f = 'f'&y, m = 'm'&y + x[1] = x1 + switch x1 do + case 'B': b = y + case 'F': f = y + case 'M': m = y + end switch + printf(1,fmt,{x, x, b, f, m, x}) +end procedure - constant tests = {"gARY", "Earl", "Billy", "Felix", "Mary", "SHIRley"} - for i=1 to length(tests) do printVerse(tests[i]) end for - - string tm = "0" - for i=1 to 8 do - printf(1,"%s\n",tm) - tm &= sq_sub('0'+'1',tm) - end for -cell for -? -->cell for -? -->cell for -? - x w s -) - -while=: conjunction def 'u ^: v ^:_' NB. j assumes while is a verb and needs to know while is a conjunction. - -ttt=: outcome@:((display@:move) while undecided)@:display@:prepare - -blindfolded_variant=: outcome@:display@:(move while undecided)@:display@:prepare - -outcome=: {&(>;:'kitty VICTORY')@:won NB. (outcome does not pass along the state) -move=: post locate -undecided=: won nor full -prepare=: , board@:] NB. form the state vector - -Note 'locate' - is a monadic verb. y is the state vector. - returns the character of the chosen cell. - Generally: - locate=: second_strategy`first_strategy@.(first = mark) - Simplified: - locate=: human_locate NB. human versus human -) -locate=: human_locate`computer_locate@.(first = mark) - -display=: show [: (1 1,:5 5)&(];.0)@:": [: <"0 fold - -computer_locate=: [: show@{. board -. marks NB. strategy: first available -computer_locate=: [: show@({~ ?@:#) board -. marks NB. strategy: random - -human_locate=: monad define - state=. y - m=. mark state - b=. board state - cells=. b -. marks state - show '-->cell for ' , m , '?' - whilst. cell -.@:e. cells do. cell =. {. (1!:1]1) , m end. -) - -post=: 2&A.@:(3&{.)@:[ prepare mark@:[`((i.~ board)~)`(board@:[)} - -mark=: {. NB. mark of the current player from state -marks=: 2&{. NB. extract both markers from state -board=: _9&{. NB. extract board from state -first=: 2&{ NB. extract first player from state - -show=: [ smoutput - -full=: 2 = #@:~. -won=: test@:fold -fold=: 3 3 $ board -test=: [: any [: all [: infix_pairs_agree |:@:lines - -lines=: , diagonal , diagonal@:|. , |: -diagonal=: (<0 1)&|: -all=: *./ -any=: +./ -nor=: 8 b. -infix_pairs_agree=: 2&(=/\) diff --git a/Task/Tic-tac-toe/JavaScript/tic-tac-toe-3.js b/Task/Tic-tac-toe/JavaScript/tic-tac-toe-3.js new file mode 100644 index 0000000000..5da4f41904 --- /dev/null +++ b/Task/Tic-tac-toe/JavaScript/tic-tac-toe-3.js @@ -0,0 +1,96 @@ +/* + + Board Positions: Win Lines by Id: + 0|1|2 0 --- | | | \/ + 3|4|5 1 --- | | | /\ + 6|7|8 2 --- | | | 6 7 + 3 4 5 + + About: This is a "too clever by half" way of checking for wins. + To explain, let's first consider some other ways to check for wins: + + - Naive: if( (board[0] == pin && board[1] == pin && board[2] == pin)) return true; ... and repeat for all other win lines + + - Bitboard optimized: if ( (board & WIN_LINE1) == WIN_LINE1 || (board & WIN_LINE2) ... and repeat for all other win lines + + - Hash: Maybe we could just hash the winning values? Nope: in general, the "noise" from other pins requires too many states to be practical + + - Regex: See the PHP example of this: https://rosettacode.org/wiki/Tic-tac-toe#PHP + + - Base 4 method: But, can we do better?!?!? What is the limit of the maximum we can parallelize our win checking? + Dare we quixotically hope for a Game-Terminal check of O(1)? YES!! Yes, indeed! + And, that is what the follow is: An optimized way of win checking using some clever abuses of numbering systems, + (and uhm, by doing a little bit more work in the makeMove function). But, trade-offs, doncha know... + + Overview: The insight into the way this works, is that instead of looking at the board state, we are instead going to focus on counting the pins in a win line. + For example, what if we had counters like this: + + X|.|. --> Win Line 0 Count = 1 + X|X|. --> Win Line 1 Count = 2 + X|.|. --> Win Line 2 Count = 1 + \-----> Win Lines 3,4,5,6,7 = 3,1,0,2,2 respectively + + This is sufficient to let us know when there is a win. But, of course, just like the other methods, it requires multiple checks to determine if there is a winning line. + + But, we note that the count won't exceed three or four, so let's serialize the counters into a base4 string, (where each digit is the count for a win line). + + Giving us [2 2 0 1 3 1 2 1].b4 [41433].b10 for the example above. (With Win Line 0 starting in the Least-Significant-Bit on the right) + + Now, this seems a bit promising, as the winning count of three is right there in the middle of the string of digits. Now, if we could just + find some way to filter it out. But, what way might that be? + + The hack: Perhaps there's a more elegant solution? (Let me know if you find one...) + Regardless, a functional, if ugly method we can use is to take advantage of the overlap between base 4, and binary. This allows us to keep our count "logic" in base 4, + but still use bitwise operations to check in parallel. + + Expanding on this, we start counting at ONE, rather than ZERO - relying on the fact that it will then overflow to the next digit when it reaches a count of 4, + since we are working in base 4. + (Note: This does require us to double the digits used for counting in our base 4 serialized string, in order to keep the win lines from intersecting each other.) + + Here is the initial base 4 win line count, with all the lines starting off empty: + [01 01 01 01 01 01 01 01].b4 [286331153].b10 + + And for the example above we have the following: + + [03 03 01 02 10 02 03 02].b4 [856834610].b10 + + Finally, in the binary version of the win line string, (with four binary digits corresponding to the two base 4 digits), it can be seen that the count "overflow", + (and thus a win), is going to be "visible" as a bit set in the third of the 4 binary digits group corresponding to the base 4 count. + [0011 0011 0001 0010 0100 0010 0011 0010].b2 + ^--- Here + + The advantage of this, is that now we can create a bitwise mask to target only those third bits like this: + [0100 0100 0100 0100 0100 0100 0100 0100].b2 + ^ ^ ^ ^ ^ ^ ^ ^ + + Then, just do a bitwise AND against that overflow mask, and Bob's your uncle! + + Admittedly, this is indeed overkill for TicTacToe, but it could theoretically have potential uses with larger N-in-a-row games. + +*/ +const LINE_COUNTS = [0x11111111, 0x11111111]; // [01 01 01 01 01 01 01 01].b4 +const WIN_MASK = 0x44444444; // [10 10 10 10 10 10 10 10].b4 +const LINES_BY_POS = [ + 0x1001001, //Pos 0 - [00 01 00 00 01 00 00 01].b4 + 0x10001, //Pos 1 - [00 00 00 01 00 00 00 01].b4 + 0x10100001, //Pos 2 - [01 00 01 00 00 00 00 01].b4 + 0x1010, //Pos 3 - [00 00 00 00 01 00 01 00].b4 + 0x11010010, //Pos 4 - [01 01 00 01 00 00 01 00].b4 + 0x100010, //Pos 5 - [00 00 01 00 00 00 01 00].b4 + 0x10001100, //Pos 6 - [01 00 00 00 01 01 00 00].b4 + 0x10100, //Pos 7 - [00 00 00 01 00 01 00 00].b4 + 0x1100100, //Pos 8 - [00 01 01 00 00 01 00 00].b4 +]; + + +function isGameOver(turn) { + if ( (LINE_COUNTS[turn] & WIN_LINE)) return true; //This is the entire glorious raison d'etre for all the above rigamarole + else if (moveCount >= TOTAL_MOVES) return true;//Cat's game + else return false; +} + +function makeMove(pos) { + //Update state + LINE_COUNTS[turn] += LINES_BY_POS[pos]; //Win line accounting + moveCount++; +} diff --git a/Task/Tic-tac-toe/Jq/tic-tac-toe.jq b/Task/Tic-tac-toe/Jq/tic-tac-toe.jq new file mode 100644 index 0000000000..b6c396dc78 --- /dev/null +++ b/Task/Tic-tac-toe/Jq/tic-tac-toe.jq @@ -0,0 +1,151 @@ +include "MRG32k3a" {search: "."}; # see comment above + +### Generic functions + +def inform(msg): + . as $in + | msg + "\n" | stderr + | $in; + +def lpad($len): tostring | ($len - length) as $l | (" " * $l) + .; + +# Create an m x n matrix with initial values specified by . +def matrix($m; $n): + if $m == 0 then [] + else . as $init + | if $m == 1 then [range(0;$n) | $init] + elif $m > 0 then + matrix(1; $n) as $row + | [range(0; $m) | $row ] + else error("matrix\($m);\($n)) invalid") + end + end; + + +### Tic-Tac-Toe + +# The board is represented by a matrix in which: +# 0 : blank; -1: computer; 1: user +def init: + {b: (0 | matrix(3;3)), + bestI: 0, + bestJ: 0, + prng: seed(now | tostring | sub("^.*[.]";"") | tonumber)}; + +# Output: 0 if undecided, null if game over, otherwise the player id +def checkWinner: + first(range(0; 3) as $i + | if .b[$i][0] != 0 and .b[$i][1] == .b[$i][0] and .b[$i][2] == .b[$i][0] then .b[$i][0] + elif .b[0][$i] != 0 and .b[1][$i] == .b[0][$i] and .b[2][$i] == .b[0][$i] then .b[0][$i] + else empty + end) + // if (.b[1][1] == 0) then 0 + elif (.b[1][1] == .b[0][0] and .b[2][2] == .b[0][0]) then .b[0][0] + elif (.b[1][1] == .b[2][0] and .b[0][2] == .b[1][1]) then .b[1][1] + elif all(.b[][]; . != 0) then null + else 0 + end ; + +def showBoard: + ["X", " ", "O"] as $t + | .b as $b + | range(0;3) as $i + | reduce range(0;3) as $j (""; + . + "\($t[$b[$i][$j] + 1]) " ), # b == -1 => "X"; b == 1 => "O" + "-----"; + +# Examine possible moves of the player identified by $value, avoiding embarrassment +# Set .result, .bestI, .bestJ, etc +def testMove($value; $depth): + checkWinner as $score + | if $score == null then .result = 0 + elif $score != 0 + then .result = (if $score == $value then 1 else -1 end) + else .best = -1 + | .changed = 0 + | reduce range(0;3) as $i (.; + reduce range(0;3) as $j (.; + if .b[$i][$j] == 0 + then .b[$i][$j] = $value + | .changed = $value + | testMove(-$value; $depth + 1) as $test + | (-$test.result) as $score + | .b[$i][$j] = 0 + | if $score > .best + then if $depth == 0 + then .bestI = $i + | .bestJ = $j + end + | .best = $score + end + end ) ) + | .result = if .changed != 0 then .best else 0 end + end; + +# Issue prompts on stderr; +# always allow q for quit +def read($prompt; $regex): + def r: + ($prompt | stderr | empty), + (try ((input + | if . == "q" then halt + else select(test($regex)) + end) // r) + catch if . == "break" then halt else r end ); + r; + +# Input: irrelevant +# $user should be boolean; specify `true` if the user plays first +def game($user): + "Board positions are numbered so:\n1 2 3\n4 5 6\n7 8 9", + "You have O, I have X.\n", + (init + {$user} + | label $out + | foreach range(0;9) as $k (.; + if .user + then .move = null + | until(.move; + (read("Your move: "; "^ *[1-9]") | tonumber - 1) as $move + | ($move/3|floor) as $i + | ($move % 3) as $j + | if .b[$i][$j] == 0 + then .b[$i][$j] = 1 + | .move = $move + end ) + end + | if (.user|not) + then # in the interests of entertainment, randomize if computer opens + if $k == 0 + then .prng |= nextFloat + | .bestI = (.prng.nextFloat * 100 | trunc) % 3 + | .prng |= nextFloat + | .bestJ = (.prng.nextFloat * 100 | trunc) % 3 + else testMove(-1; 0) + end + | .b[.bestI][.bestJ] = -1 + | inform("My move: \(.bestI * 3 + .bestJ + 1)") + end + | .user |= not + ; + # Output: + showBoard, + (checkWinner + | if . == 0 then empty + else (if . == 1 then "You win" + elif . == -1 then "I win" + else "A draw.\n\n" + end), + break $out + end ) )) ; + +# Alternate players +def controller: + def c($user): + game($user), + (read("Play again? [yn]: "; "^[yYnN]") as $in + | if $in|.[0:1]|ascii_downcase == "n" then halt + else c($user|not) + end); + c(true); + +controller diff --git a/Task/Tic-tac-toe/Julia/tic-tac-toe-1.jl b/Task/Tic-tac-toe/Julia/tic-tac-toe-1.jl new file mode 100644 index 0000000000..860661671a --- /dev/null +++ b/Task/Tic-tac-toe/Julia/tic-tac-toe-1.jl @@ -0,0 +1,89 @@ +# The state of the game is represented as a vector of moves made so far +const TTT = Vector{Int} + +@enum Role N X O # N = 0, neither X nor O +role(turn::Int) = isodd(turn) ? X : O + +# game state functions: +next_role(moves::TTT) = role(length(moves)+1) +available(moves::TTT) = setdiff(1:9, moves) +function winner(moves::TTT) + wintriples = [ + [1, 2, 3], [4, 5, 6], [7, 8, 9], # rows + [1, 4, 7], [2, 5, 8], [3, 6, 9], # columns + [1, 5, 9], [3, 5, 7] ] # diagonals + turn = length(moves); XorO = role(turn) + inmoves(triple) = all(∈(moves[Int(XorO):2:end]), triple) + turn ≥ 5 && any(inmoves, wintriples) && return XorO + N +end + +# scoring a state of the game with the recursive negamax algorithm +negamax(moves::TTT) = winner(moves) ≠ N ? 1 : length(moves) == 9 ? 0 : + -maximum(negamax([moves; move]) for move ∈ available(moves)) + +scored_options(moves::TTT) = + Dict(move => negamax([moves; move]) for move ∈ available(moves)) + +# players of X and O with different intelligence +abstract type Player end + +struct RandomBot <: Player end +select_move(::RandomBot, moves::TTT) = rand(available(moves)) + +struct NegamaxBot <: Player end +function select_move(::NegamaxBot, moves::TTT) + opts = scored_options(moves) + maxscore = maximum(values(opts)) + rand([move for (move, score) ∈ opts if score == maxscore]) +end + +struct Human <: Player name::String end +function select_move(player::Human, moves::TTT) + move = 0 + while move ∉ available(moves) + print(player, " as ", next_role(moves), ", enter your move: ") + move = try parse(Int, readline()) catch; 0 end + end + move +end + +Base.show(io::IO, player::Player) = + print(io, player isa Human ? player.name : typeof(player)) + +function displayboard(moves::TTT, hints = false) + reset = "\e[0m"; bold = reset * "\e[1m"; faint = reset * "\e[2m" + board = fill(" ", 9) + fillmove((i, move)) = board[move] = bold * repr(role(i)) * faint + foreach(fillmove, enumerate(moves)) + fillscore((move, score)) = + board[move] = isone(score) ? "+" : iszero(score) ? "·" : "-" + hints && foreach(fillscore, scored_options(moves)) + matrix = reshape([n*m for (n, m) in zip("¹²³⁴⁵⁶⁷⁸⁹", board)], 3, 3) + to_row(col) = join(col, " │") + rows = join(to_row.(eachcol(matrix)), "\n───┼───┼───\n") + println(faint, " ╷ ╷\n", rows, "\n ╵ ╵", reset) +end + +function ttt(Xplayer::Player, Oplayer::Player; hints = true) + moves = TTT(); cast = Dict(X => Xplayer, O => Oplayer) + println("\n","-"^40,"\nLet's play TicTacToe") + println("Cast: X => $Xplayer, O => $Oplayer\n", "-"^40) + while winner(moves) == N && length(moves) < 9 + displayboard(moves, hints) + XorO = next_role(moves) + player = cast[XorO] + move = select_move(player, moves) + player isa Human || + println(player, " as ", XorO, " plays move: ", move) + push!(moves, move) + end + displayboard(moves) + XorO = winner(moves) + println( XorO == N ? "It's a draw!" : + cast[XorO] isa Human ? "Congratulations, $(cast[XorO])! You win!" : + "$player as $XorO wins!" ) +end + +ttt(RandomBot(), NegamaxBot(); hints = false) +ttt(RandomBot(), Human("Alice")) diff --git a/Task/Tic-tac-toe/Julia/tic-tac-toe-2.jl b/Task/Tic-tac-toe/Julia/tic-tac-toe-2.jl new file mode 100644 index 0000000000..cc15551c88 --- /dev/null +++ b/Task/Tic-tac-toe/Julia/tic-tac-toe-2.jl @@ -0,0 +1,41 @@ +# the functions provided above are mandatory + +function result_distribution(moves::TTT, casts::Dict{Role, Player}) + w = winner(moves) + distribution = Dict(p => 0//1 for p in instances(Role)) + if w ≠ N + distribution[w] = 1//1 + return 1, 1, distribution + elseif length(moves) == 9 + distribution[N] = 1//1 + return 0, 1, distribution + else + scores = [result_distribution([moves; move], casts) + for move in setdiff(1:9, moves)] + maxscore = maximum(s[1] for s in scores) + p = role(length(moves)+1) + casts[p] isa NegamaxBot && filter!(s -> s[1] == maxscore, scores) + n = length(scores) + distribution = Dict(p => sum(s[3][p] for s in scores) // n for p in instances(Role)) + return -maxscore, sum(s[2] for s in scores), distribution + end +end + +function bot_statistics() + casts = [RandomBot(), NegamaxBot()] + combinations = Dict{Role, Player}[Dict(X => x, O => o) for x in casts for o in casts] + println("--------------------------------------------------------------") + println(" as X - as O | games | draws X wins O wins") + println("--------------------------------------------------------------") + for combi in combinations + distrib = result_distribution(Int[], combi) + print("$(lpad(combi[X], 10)) - $(rpad(combi[O], 10)) | ", lpad(distrib[2], 6), " | ") + for role in [N, X, O] + print(" $(lpad(round(100 * distrib[3][role], digits=1), 5))% ") + end + println() + end + println("--------------------------------------------------------------") +end + +bot_statistics() diff --git a/Task/Tic-tac-toe/Julia/tic-tac-toe.julia b/Task/Tic-tac-toe/Julia/tic-tac-toe.julia deleted file mode 100644 index 92fb1d3c0e..0000000000 --- a/Task/Tic-tac-toe/Julia/tic-tac-toe.julia +++ /dev/null @@ -1,102 +0,0 @@ -const winningpositions = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], - [2, 5, 8], [3, 6, 9],[1, 5, 9], [7, 5, 3]] - -function haswon(brd, xoro) - marked = findall(x -> x == xoro, brd) - for pos in winningpositions - if length(pos) <= length(marked) && pos == sort(marked)[1:3] - return true - end - end - false -end - -function readcharwithprompt(prompt, expected) - ret = '*' - while !(ret in expected) - print("\n", prompt, " -> ") - ret = lowercase(chomp(readline()))[1] - end - ret -end - -availablemoves(brd) = findall(x -> x == ' ', brd) -cornersopen(brd) = [x for x in [1, 3, 7, 9] if brd[x] == ' '] -int2char(x) = Char(x + UInt8('0')) -char2int(x) = UInt8(x) - UInt8('0') -getyn(query) = readcharwithprompt(query, ['y', 'n']) -gettheirmove(brd) = char2int(readcharwithprompt("Your move(1-9)", int2char.(availablemoves(brd)))) - -function findwin(brd, xoro) - tmpbrd = deepcopy(brd) - for mv in availablemoves(tmpbrd) - tmpbrd[mv] = xoro - if haswon(tmpbrd, xoro) - return mv - end - tmpbrd[mv] = ' ' - end - return nothing -end - -function choosemove(brd, mychar, theirchar) - if all(x -> x == ' ', brd) - brd[rand(cornersopen(brd))] = mychar # corner trap if starting game - elseif availablemoves(brd) == [] # no more moves - println("Game is over. It was a draw.") - exit(0) - elseif (x = findwin(brd, mychar)) != nothing || (x = findwin(brd, theirchar)) != nothing - brd[x] = mychar # win if possible, block their win otherwise if their win is possible - elseif brd[5] == ' ' - brd[5] = mychar # take center if open and not doing corner trap - elseif (corners = cornersopen(brd)) != [] - brd[rand(corners)] = mychar # choose a corner over a side middle move - else - brd[rand(availablemoves(brd))] = mychar # random otherwise - end -end - -function display(brd) - println("+-----------+") - println("| ", brd[1], " | ", brd[2], " | ", brd[3], " |") - println("| ", brd[4], " | ", brd[5], " | ", brd[6], " |") - println("| ", brd[7], " | ", brd[8], " | ", brd[9], " |") - println("+-----------+") -end - -function tictactoe() - board = fill(' ', 9) - println("Board move grid:\n 1 2 3\n 4 5 6\n 7 8 9") - yn = getyn("Would you like to move first (y/n)?") - if yn == 'y' - mychar = 'O' - theirchar = 'X' - board[gettheirmove(board)] = theirchar - else - mychar = 'X' - theirchar = 'O' - end - while true - choosemove(board, mychar, theirchar) - println("Computer has moved.") - display(board) - if haswon(board, mychar) - println("Game over. Computer wins!") - exit(0) - elseif availablemoves(board) == [] - break - end - board[gettheirmove(board)] = theirchar - println("Player has moved.") - display(board) - if haswon(board, theirchar) - println("Game over. Player wins!") - exit(0) - elseif availablemoves(board) == [] - break - end - end - println("Game over. It was a draw.") -end - -tictactoe() diff --git a/Task/Tic-tac-toe/K/tic-tac-toe.k b/Task/Tic-tac-toe/K/tic-tac-toe.k new file mode 100644 index 0000000000..34807c7505 --- /dev/null +++ b/Task/Tic-tac-toe/K/tic-tac-toe.k @@ -0,0 +1,7 @@ +b::2 9#0; WINMASKS::((9#2)\)'7 56 448 73 146 292 273 84 / the board and winning trios +{1}{({`1:"MOVE: ";$[(|/b)m:(`I$-1_1:`)-1;o`0:"NO";b[0;m]::1]} / your move + {b[1;*1?&~|/b]::1})[x;] / cpu's move + x{`0:" "/'`c$3 3#|/"XO*"*b,,~|/b}/0 / show board after each move + w:|/3=0^WINMASKS(+/&)\:b x;f:511=2/|/b / test win and full conditions + $[w|f;[`0:("the cat";"XO"x)[w]," won";`exit 0];] / when game is over, exit and print winner + ~x}/1 / now it's other player's turn diff --git a/Task/Tic-tac-toe/Kotlin/tic-tac-toe.kotlin b/Task/Tic-tac-toe/Kotlin/tic-tac-toe.kts similarity index 100% rename from Task/Tic-tac-toe/Kotlin/tic-tac-toe.kotlin rename to Task/Tic-tac-toe/Kotlin/tic-tac-toe.kts diff --git a/Task/Tic-tac-toe/Lua/tic-tac-toe-1.lua b/Task/Tic-tac-toe/Lua/tic-tac-toe-1.lua new file mode 100644 index 0000000000..15d1ddd1b8 --- /dev/null +++ b/Task/Tic-tac-toe/Lua/tic-tac-toe-1.lua @@ -0,0 +1,90 @@ +local player_O, blank, player_X = -1, 0, 1 +local show_tile = {[player_O]="O", [blank]="-", [player_X]="X"} + +function valid_pos_Q(pos) + return type(pos) == "number" and pos%1 == 0 and 1 <= pos and pos <= 9 +end + +function member_Q(arr, e) -- Does `arr` contain `e`? + for _, val in ipairs(arr) do + if val == e then return true end + end + return false +end + +function full_Q(board) return not member_Q(board, blank) end + +function sum(arr, idxs) + local result = 0 + for _,i in ipairs(idxs) do result = result + arr[i] end + return result +end + +-- rcd stands for rows, columns, and diagonals +local rcd = {{1,2,3},{4,5,6},{7,8,9}, {1,4,7},{2,5,8},{3,6,9}, {1,5,9},{3,5,7}} + +function won_Q(board) + for _,idxs in ipairs(rcd) do + if math.abs(sum(board, idxs)) == 3 then + return true + end -- if + end -- for + return false +end + +function you(board) + local position + repeat + io.write("Enter a move(1-" .. 9 .. "): ") + position = tonumber(io.read("*line")) + until valid_pos_Q(position) and board[position] == blank + return position +end + +function cpu(board) + for position, value in ipairs(board) do + if value == blank then return position end + end +end + +function pos(board) -- a players takes a turn, returns chosen position + if board[0] == player_O then + return cpu(board) + else + return you(board) + end +end + +function move(board) + assert(not full_Q(board)) + local position = pos(board) + board[position] = board[0] + board[0] = -board[0] -- toggle whose turn + return board +end + +function show(board) + for key, val in ipairs(board) do + io.write(show_tile[val] .. " ") + if key % 3 == 0 then io.write"\n" end + end -- for + io.write"\n" +end + +-- board[0] indicates whose turn it is +local the_board = { [0]=player_O } +for i = 1, 9 do the_board[i] = blank end + +repeat + move(the_board) + show(the_board) +until won_Q(the_board) or full_Q(the_board) + +if won_Q(the_board) then + print (show_tile[-the_board[0]], "wins!") +elseif full_Q(the_board) then + print("tie!") +else + print("incomplete game") + assert(false) -- this should be logically impossible +end -- if diff --git a/Task/Tic-tac-toe/Lua/tic-tac-toe.lua b/Task/Tic-tac-toe/Lua/tic-tac-toe-2.lua similarity index 100% rename from Task/Tic-tac-toe/Lua/tic-tac-toe.lua rename to Task/Tic-tac-toe/Lua/tic-tac-toe-2.lua diff --git a/Task/Tic-tac-toe/Modula-2/tic-tac-toe.mod2 b/Task/Tic-tac-toe/Modula-2/tic-tac-toe.mod2 new file mode 100644 index 0000000000..1e25cc5bfd --- /dev/null +++ b/Task/Tic-tac-toe/Modula-2/tic-tac-toe.mod2 @@ -0,0 +1,268 @@ +MODULE TicTacToe; + +FROM STextIO IMPORT + WriteLn, WriteString, ReadString, SkipLine; +FROM SWholeIO IMPORT + WriteInt, ReadCard; +FROM RandomNumbers IMPORT + Rnd; + +TYPE + TWinPos = ARRAY [0 .. 7], [0 .. 2] OF INTEGER; (* Winning positions *) + TMover = (Human, Computer, Nobody); + +CONST + WinPos = TWinPos{{0, 1, 2}, {3, 4, 5}, + {6, 7, 8}, {0, 3, 6}, + {1, 4, 7}, {2, 5, 8}, + {0, 4, 8}, {2, 4, 6}}; + +VAR + Board : ARRAY [0 .. 8] OF CHAR; + BestMove, + T : INTEGER; + MyPiece, + HisPiece : CHAR; + CompFirst: BOOLEAN; + Mover : TMover; + Answ : ARRAY [0 .. 1] OF CHAR; + MyWinsCnt, + HisWinsCnt, + DrawsCnt, + MovesCnt, + I : CARDINAL; + +PROCEDURE WriteStringLn(S: ARRAY OF CHAR); +BEGIN + WriteString(S); + WriteLn +END WriteStringLn; + +PROCEDURE SpacesFilled(): BOOLEAN; +VAR + I: CARDINAL; +BEGIN + FOR I := 0 TO 8 DO + IF Board[I] = " " THEN + RETURN FALSE; + END + END; + RETURN TRUE +END SpacesFilled; + +PROCEDURE DisplayNumberedBoard; +VAR + I : CARDINAL; + Row: ARRAY [0 .. 10] OF CHAR; +BEGIN + Row := " * | * | * "; + FOR I := 0 TO 8 BY 3 DO + Row[1] := CHR(I + 1 + ORD("0")); + Row[5] := CHR(I + 2 + ORD("0")); + Row[9] := CHR(I + 3 + ORD("0")); + WriteStringLn(Row); + IF I <> 6 THEN + WriteStringLn("---+---+---"); + END; + END +END DisplayNumberedBoard; + +PROCEDURE DisplayPiecedBoard; +VAR + I : CARDINAL; + Row: ARRAY [0 .. 10] OF CHAR; +BEGIN + Row := " * | * | * "; + FOR I := 0 TO 8 BY 3 DO + Row[1] := Board[I]; + Row[5] := Board[I + 1]; + Row[9] := Board[I + 2]; + WriteStringLn(Row); + IF I <> 6 THEN + WriteStringLn("---+---+---"); + END; + END; +END DisplayPiecedBoard; + +PROCEDURE Evaluate(Me: CHAR; Him: CHAR): INTEGER; + (* Recursive algorithm *) +VAR + I : CARDINAL; + SafeMove, + V, + LoseFlag: INTEGER; +BEGIN + IF Win(Me) THEN + RETURN 1 + END; + IF Win(Him) THEN + RETURN -1 + END; + IF SpacesFilled() THEN + RETURN 0 + END; + LoseFlag := 1; + I := 0; + WHILE I <= 8 DO + IF Board[I] = " " THEN + Board[I] := Me; (* Try the move. *) + V := Evaluate(Him, Me); + Board[I] := " "; (* Restore the empty space. *) + IF V = -1 THEN + BestMove := I; + RETURN 1 + END; + IF V = 0 THEN + LoseFlag := 0; + SafeMove := I + END; + END; + I := I + 1; + END; + BestMove := SafeMove; + RETURN -LoseFlag +END Evaluate; + +PROCEDURE Win(Piece: CHAR): BOOLEAN; +VAR + I: CARDINAL; +BEGIN + FOR I := 0 TO 7 DO + IF (Board[WinPos[I, 0]] = Piece) AND + (Board[WinPos[I, 1]] = Piece) AND + (Board[WinPos[I, 2]] = Piece) THEN + RETURN TRUE + END; + END; + RETURN FALSE +END Win; + +PROCEDURE ClearBoard; +VAR + I: CARDINAL; +BEGIN + FOR I := 0 TO 8 DO + Board[I] := " " + END; +END ClearBoard; + +PROCEDURE WriteSummary(What: ARRAY OF CHAR; Cnt: CARDINAL); +BEGIN + WriteString(What); + WriteInt(Cnt, 1); + WriteString(" game"); + IF Cnt <> 1 THEN + WriteStringLn("s."); + ELSE + WriteStringLn("."); + END; +END WriteSummary; + +BEGIN + MyWinsCnt := 0; + HisWinsCnt := 0; + DrawsCnt := 0; + CompFirst := TRUE; (* It be reversed, so in fact human goes first *) + WriteLn; + WriteStringLn(" TIC-TAC-TOE"); + WriteLn; + WriteStringLn("In this version, X always goes first."); + WriteStringLn("The board is numbered:"); + REPEAT + CompFirst := NOT CompFirst; (* reverse who goes first *) + MovesCnt := 0; + WriteLn; + DisplayNumberedBoard; + WriteLn; + IF CompFirst THEN + WriteStringLn("I go first."); + ELSE + WriteString("You go first."); + END; + WriteLn; + ClearBoard; + IF CompFirst THEN + MyPiece := "X"; + HisPiece := "O" + ELSE + MyPiece := "O"; + HisPiece := "X" + END; + IF CompFirst THEN + Mover := Computer + ELSE + Mover := Human + END; + WHILE Mover <> Nobody DO + CASE Mover OF + | Computer: + IF MovesCnt = 0 THEN + BestMove := Rnd(9) + ELSIF MovesCnt = 1 THEN + IF Board[4] <> " " THEN + BestMove := Rnd(2) * 6 + Rnd(2) * 2 (* 0, 2, 6, or 8 *) + ELSE + BestMove := 4 + END + ELSE + T := Evaluate(MyPiece, HisPiece) + END; + Board[BestMove] := MyPiece; + MovesCnt := MovesCnt + 1; + WriteLn; + DisplayPiecedBoard; + WriteLn; + IF Win(MyPiece) THEN + MyWinsCnt := MyWinsCnt + 1; + WriteStringLn("I win!"); + Mover := Nobody + ELSIF SpacesFilled() THEN + DrawsCnt := DrawsCnt + 1; + WriteStringLn("It's a draw. Thank you."); + Mover := Nobody + ELSE + Mover := Human + END + | Human: + LOOP + WriteString("Where do you move? "); + ReadCard(I); + SkipLine; + IF (I < 1) OR (I > 9) THEN + WriteString("Illegal! "); + ELSIF Board[I - 1] <> " " THEN + WriteString("Place already occupied. "); + ELSE + EXIT + END + END; + Board[I - 1] := HisPiece; + MovesCnt := MovesCnt + 1; + WriteLn; + DisplayPiecedBoard; + WriteLn; + IF Win(HisPiece) THEN + HisWinsCnt := HisWinsCnt + 1; + WriteStringLn("You beat me! Good game."); + Mover := Nobody + ELSIF SpacesFilled() THEN + DrawsCnt := DrawsCnt + 1; + WriteStringLn("It's a draw. Thank you."); + Mover := Nobody + ELSE + Mover := Computer + END; + END (* CASE *) + END; (* WHILE *) + WriteLn; + WriteString("Another game (y/n)? "); + ReadString(Answ); + SkipLine + UNTIL CAP(Answ[0]) <> "Y"; + WriteLn; + WriteStringLn("Final score:"); + WriteSummary("You won ", MyWinsCnt); + WriteSummary("I won ", MyWinsCnt); + WriteSummary("We tied ", DrawsCnt); + WriteStringLn("See you later!"); +END TicTacToe. diff --git a/Task/Tic-tac-toe/Rust/tic-tac-toe.rust b/Task/Tic-tac-toe/Rust/tic-tac-toe.rs similarity index 100% rename from Task/Tic-tac-toe/Rust/tic-tac-toe.rust rename to Task/Tic-tac-toe/Rust/tic-tac-toe.rs diff --git a/Task/Tic-tac-toe/TAV/tic-tac-toe.tav b/Task/Tic-tac-toe/TAV/tic-tac-toe.tav new file mode 100644 index 0000000000..1252e15cc1 --- /dev/null +++ b/Task/Tic-tac-toe/TAV/tic-tac-toe.tav @@ -0,0 +1,133 @@ +\( Simple (not perfect) solver for tic-tac-toe + The state is a 9-element vector, with + 0 for free, 1 for user; 4 for machine + Lanes are used to check if there is a win or near-win: + 1 2 3 + 4 5 6 + 7 8 9 + 1 4 7 + 2 5 8 + 3 6 9 + 1 5 9 + 3 5 7 + For each lane, the sum of the values is calculated + and the number of free ones determined. + After the player's move and the machine action, + the lane sums are checked for wins: + - if = 3, the player has won, stop. + - if = 12, the machine has won, stop. + - if none are free, the game ends with a draw + The machine action is: + - if = 2, the player could win; set the free place + - if = 8, the machine will win, set the free place + - if field 5 is free, set + - if any of the fields 1, 3, 7 or 9 are free, set at random + - if any of the fields 2, 4, 6 or 8 are free, set at random +\) +main (parms):+ + random set seed () + print "enter field number, or 'x' to quit:" + state =: new row size 9 init 0 + state.lanes =: ((1, 2, 3), (4, 5, 6), (7, 8, 9), (1, 4, 7), (2, 5, 8), (3, 6, 9), (1, 5, 9), (3, 5, 7)) + state.free =: 9 + ?* state.free > 0 + show state + set user state + show state + check end state + ? state.free > 0 + step move state + check end state + show state + +check end (state): + ?# t =: tuple state.lanes give values + c =: sum of places state lane t + \ print c, t + ? c = 3: + print "You win:", t + ?# i =: tuple t give values + state[i] =: '+' + state.free =: 0 + :> + ? c = 12: + print "I win:", t + ?# i =: tuple t give values + state[i] =: '*' + state.free =: 0 + :> + ? state.free = 0 + print "This is a draw." + +step move (state): + ?# t =: tuple state.lanes give values + c =: sum of places state lane t + ? c = 2 + set state at t + :> + ? c = 8 + set state at t + :> + ? set state at 5 + :> + ? set state at shuffle 1, 3, 7, 9 + :> + ? set state at shuffle 2, 4, 6, 8 + :> + +set (state) at (points): + ? ~ is points tuple + points =: points, () \ make it a tuple + ?# i =: tuple points give values + ? state[i] = 0 + state[i] =: 4 + print "my move:", i + :> ?+ + :> ?- + +shuffle (points): + n =: points.Count + r =: random tuple n + points =: tuple points select r + :> points + +sum of places (state) lane (tpl): + s =: 0 + ?# i =: tuple tpl give values + v =: state[i] + ? v ~= 0 + s =+ state[i] + :> s + +set user (state): + ?* + print "your move: " nonl + c =: file stream () get + ? c = 'q' || c = 'x' || c = () + system exit 0 + n =: string c as integer else () + ? n = () || n < 1 || n > state.Count + print "Invalid input, " nonl + ?^ + ? state[n] = 0 + state[n] =: 1 + :> + print "not free; retry " nonl + +show (state): + state.free =:0 + ?# i =: from 1 upto 9 + v =: state[i] + w =: v + ? v = 0 + w =: i + state.free =+ 1 + ? v = 1 + w =: 'X' + ? v = 4 + w =: 'O' + print ' ' _ w nonl + ? i = 3 || i = 6 + print '' + print '' + \ state.free=0 is used to terminate the central loop diff --git a/Task/Tic-tac-toe/Uiua/tic-tac-toe.uiua b/Task/Tic-tac-toe/Uiua/tic-tac-toe.uiua new file mode 100644 index 0000000000..f9fab19c70 --- /dev/null +++ b/Task/Tic-tac-toe/Uiua/tic-tac-toe.uiua @@ -0,0 +1,26 @@ +Threes ← [0_1_2 3_4_5 6_7_8 0_3_6 1_4_7 2_5_8 0_4_8 2_4_6] +Moves ← ≡(⊂□)⊙(¤□)⊸(≡⍜⊡⋅∘ ⊙¤⊙⊙¤⊚⊸⌕@_)⊙(⨬(@X|@O)=@X)∩°□°⊟ +RandomMove ← [⊡]⌊×⚂⊸⧻ Moves +WasWin ← /↥⊢≡(≡/↧˜⌕⊏Threes)¤∩°□°⊟ +IsDraw ← ¬/↥⌕@_°□⊢ +Done ← ↥⊃IsDraw WasWin +[] # Score accumulator +⍥( # They start + ⊢path(RandomMove|Done){"_________" @X} + # Score each of our moves as winning or losing, save. + ⨬(◌|⊂≡⊟⊃(≡⊢▽⊸≡◇(=@X°□⊣)|¤□⨬(¯1|1)=@X°□⊣⊣))⊸(¬IsDraw⊣) +) 3000 +# Build map from moves and accumulated scores +¤map⍜⍉°⊟⊕(⊂⊃(⊢°□⊢|/+≡◇⊣))⊛⊸≡⊢ +# Play our *best* moves against their *random* moves. +BestMove ← |1 ⨬(RandomMove|[⊢]▽=⊸/↥◡≡(°□⬚0get⊢)Moves)=@O°□⊸⊣ +# One demo game +&p"Sample Game: 'O' starts, playing randomly.\n'X' is trained." +≡&p↘1⊢path(BestMove|Done){"_________" @X} + +&p"Thirty results, showing X/O as winner or '=' for draw." +⍥( # Let them start + ⊢path(BestMove|Done){"_________" @X} + &p⊟∩□⍥⊙⋅@=¬/↥⊸⌕@_°□°⊟⊣ +)30 +◌ diff --git a/Task/Tic-tac-toe/V-(Vlang)/tic-tac-toe.v b/Task/Tic-tac-toe/V-(Vlang)/tic-tac-toe.v index ffeded1f25..cc898143a5 100644 --- a/Task/Tic-tac-toe/V-(Vlang)/tic-tac-toe.v +++ b/Task/Tic-tac-toe/V-(Vlang)/tic-tac-toe.v @@ -1,110 +1,116 @@ import rand import os -__global ( - b = [3][3]int{} - best_i = 0 - best_j = 0 -) +struct Board { + mut: + bay [3][3]int + best_i int + best_j int +} fn main() { + mut brd := Board{} mut user := false - mut yn :='' + mut yn :="" for { user = !user - print(game(user)) + print(game(mut brd, user)) for (yn != "y" ) && (yn != "n") { - yn = os.input('Play again y/n: ').str().to_lower() + yn = os.input("Play again y/n: ").str().to_lower() } - if yn != "y" {exit(0)} else {yn =''} - println('') + if yn != "y" {exit(0)} else {yn =""} + println("") } } -fn game(user bool) string { - mut u := user - mut move, mut my_move, mut i, mut j, mut win := 0, 0, 0, 0, 0 - for k in 0..3 { - for l in 0..3 { - if b[k][l] != 0 {b[k][l] = 0} +fn game(mut brd Board, user bool) string { + mut ubl := user + mut move, mut my_move, mut ir, mut jir, mut win := 0, 0, 0, 0, 0 + for kal in 0..3 { + for lal in 0..3 { + if brd.bay[kal][lal] != 0 {brd.bay[kal][lal] = 0} } } print("Board postions are numbered so:\n1 2 3\n4 5 6\n7 8 9\n") print("You have O, I have X.\n\n") - for k in 1..9 { - if u { + for kal in 1..9 { + if ubl { for move !in [1,2,3,4,5,6,7,8,9] { - move = os.input('your move: ').int() + move = os.input("your move: ").int() } move-- - i = move / 3 - j = move % 3 - if b[i][j] != 0 {continue} - b[i][j] = 1 + ir = move / 3 + jir = move % 3 + if brd.bay[ir][jir] != 0 {continue} + brd.bay[ir][jir] = 1 move = 0 } - if !u { - if k == 1 { - best_i = (rand.int_in_range(1, 9) or {exit(1)}) % 3 - best_j = (rand.int_in_range(1, 9) or {exit(1)}) % 3 + if !ubl { + if kal == 1 { + brd.best_i = (rand.int_in_range(1, 9) or {exit(1)}) % 3 + brd.best_j = (rand.int_in_range(1, 9) or {exit(1)}) % 3 } - else {test_move(-1, 0)} - b[best_i][best_j] = -1 - my_move = best_i * 3 + best_j + 1 + else {test_move(mut brd, -1, 0)} + brd.bay[brd.best_i][brd.best_j] = -1 + my_move = brd.best_i * 3 + brd.best_j + 1 println("My move: $my_move") } - show_board() - win = check_winner() + show_board(mut brd) + win = check_winner(mut brd) println("win res: $win") if win != 0 { if win == 1 {return "You win" + ".\n\n"} else {return "I win" + ".\n\n"} } - u = !u + ubl = !ubl } return "A draw.\n\n" } -fn check_winner() int { - for i in 0..3 { - if b[i][0] != 0 && b[i][1] == b[i][0] && b[i][2] == b[i][0] {return b[i][0]} - if b[0][i] != 0 && b[1][i] == b[0][i] && b[2][i] == b[0][i] {return b[0][i]} +fn check_winner(mut brd Board) int { + for ial in 0..3 { + if brd.bay[ial][0] != 0 && brd.bay[ial][1] == brd.bay[ial][0] && brd.bay[ial][2] == brd.bay[ial][0] { + return brd.bay[ial][0] + } + if brd.bay[0][ial] != 0 && brd.bay[1][ial] == brd.bay[0][ial] && brd.bay[2][ial] == brd.bay[0][ial] { + return brd.bay[0][ial] + } } - if b[1][1] == 0 {return 0} - if b[1][1] == b[0][0] && b[2][2] == b[0][0] {return b[0][0]} - if b[1][1] == b[2][0] && b[0][2] == b[1][1] {return b[1][1]} + if brd.bay[1][1] == 0 {return 0} + if brd.bay[1][1] == brd.bay[0][0] && brd.bay[2][2] == brd.bay[0][0] {return brd.bay[0][0]} + if brd.bay[1][1] == brd.bay[2][0] && brd.bay[0][2] == brd.bay[1][1] {return brd.bay[1][1]} return 0 } -fn show_board() { +fn show_board(mut brd Board) { mut t := "X O" - for i in 0..3 { - for j in 0..3 { - print("${t[b[i][j] + 1].ascii_str()} ") + for ial in 0..3 { + for jal in 0..3 { + print("${t[brd.bay[ial][jal] + 1].ascii_str()} ") } - println('') + println("") } println("-----") } -fn test_move(value int, depth int) int { +fn test_move(mut brd Board, value int, depth int) int { mut best := -1 mut changed := 0 - mut score := check_winner() + mut score := check_winner(mut brd) if score != 0 { if score == value {return 1} else {return -1} } - for i in 0..3 { - for j in 0..3 { - if b[i][j] != 0 {continue} - b[i][j] = value + for ial in 0..3 { + for jal in 0..3 { + if brd.bay[ial][jal] != 0 {continue} + brd.bay[ial][jal] = value changed = value - score = -test_move(-value, depth + 1) - b[i][j] = 0 + score = -test_move(mut brd, -value, depth + 1) + brd.bay[ial][jal] = 0 if score <= best {continue} if depth == 0 { - best_i = i - best_j = j + brd.best_i = ial + brd.best_j = jal } best = score } diff --git a/Task/Time-a-function/11l/time-a-function.11l b/Task/Time-a-function/11l/time-a-function.11l index a826393bdd..ca3b95a772 100644 --- a/Task/Time-a-function/11l/time-a-function.11l +++ b/Task/Time-a-function/11l/time-a-function.11l @@ -1,6 +1,6 @@ F do_work(x) V n = x - L(i) 10000000 + L(i) 0.<10000000 n += i R n diff --git a/Task/Time-a-function/AWK/time-a-function.awk b/Task/Time-a-function/AWK/time-a-function.awk new file mode 100644 index 0000000000..a891d4c57d --- /dev/null +++ b/Task/Time-a-function/AWK/time-a-function.awk @@ -0,0 +1,50 @@ +# syntax: GAWK -f TIME_A_FUNCTION.AWK [-v delay=x] [ stop) { + print("next day rollover occurred") + } + printf("%.6f seconds (%017.6f-%017.6f)\n",stop-start,stop,start) + printf("%s\n\n",msg) +} diff --git a/Task/Time-a-function/Ada/time-a-function.ada b/Task/Time-a-function/Ada/time-a-function.adb similarity index 100% rename from Task/Time-a-function/Ada/time-a-function.ada rename to Task/Time-a-function/Ada/time-a-function.adb diff --git a/Task/Time-a-function/Agena/time-a-function.agena b/Task/Time-a-function/Agena/time-a-function.agena new file mode 100644 index 0000000000..9ec1f90255 --- /dev/null +++ b/Task/Time-a-function/Agena/time-a-function.agena @@ -0,0 +1,14 @@ +scope # Time a function + + local proc timeFunction( f :: procedure ) :: number + local startTime := os.clock(); + f(); + return os.clock() - startTime # execution time in milliseconds + end; + + local proc toBeTimed() + os.wait( 1.234 ) # sleep 1.234 seconds + end + + print( timeFunction( toBeTimed ) / 1000, " seconds" ) +end diff --git a/Task/Time-a-function/ArkScript/time-a-function.ark b/Task/Time-a-function/ArkScript/time-a-function.ark new file mode 100644 index 0000000000..a3321bb9f5 --- /dev/null +++ b/Task/Time-a-function/ArkScript/time-a-function.ark @@ -0,0 +1,10 @@ +(import std.Sys) + +(let work (fun (x) (sys:sleep (random x (* 2 x))))) + +(let timer (fun (f) { + (let start (time)) + (f) + (- (time) start) })) + +(print (timer (fun () (work 50)))) diff --git a/Task/Time-a-function/Delphi/time-a-function.delphi b/Task/Time-a-function/Delphi/time-a-function.pas similarity index 100% rename from Task/Time-a-function/Delphi/time-a-function.delphi rename to Task/Time-a-function/Delphi/time-a-function.pas diff --git a/Task/Time-a-function/DuckDB/time-a-function.duckdb b/Task/Time-a-function/DuckDB/time-a-function.duckdb new file mode 100644 index 0000000000..3bdea7649c --- /dev/null +++ b/Task/Time-a-function/DuckDB/time-a-function.duckdb @@ -0,0 +1,21 @@ +# A table +create or replace function countto(n) as ( + with recursive cte as ( + select 0 as ix + union all + select ix+1 + from cte + where ix < n) + select last(ix order by ix) + from cte +); + +.timer on +.print .timer is now on +.print 10^4 +select length(range(0, 10_000)); +select countto(10 ^ 4); + +.print 10^5 +select length(range(0, 100_000)); +select countto(10 ^ 5); diff --git a/Task/Time-a-function/EasyLang/time-a-function.easy b/Task/Time-a-function/EasyLang/time-a-function.easy index e5f6214948..a24f8c8a9b 100644 --- a/Task/Time-a-function/EasyLang/time-a-function.easy +++ b/Task/Time-a-function/EasyLang/time-a-function.easy @@ -1,4 +1,4 @@ -func fua lim . +func sumrange lim . # this is interpreted i = 1 while i <= lim @@ -8,10 +8,10 @@ func fua lim . return sum . start = systime -print fua 1e8 +print sumrange 1e8 print systime - start # -fastfunc fub lim . +fastfunc sumrangef lim . # this is compiled to wasm i = 1 while i <= lim @@ -21,5 +21,5 @@ fastfunc fub lim . return sum . start = systime -print fub 1e8 +print sumrangef 1e8 print systime - start diff --git a/Task/Time-a-function/Elena/time-a-function.elena b/Task/Time-a-function/Elena/time-a-function.elena index f07ac6deb3..26c17a33e0 100644 --- a/Task/Time-a-function/Elena/time-a-function.elena +++ b/Task/Time-a-function/Elena/time-a-function.elena @@ -4,20 +4,20 @@ import system'threading; import system'math; import extensions; -someProcess() +SomeProcess() { - threadControl.sleep(1000); + Thread.sleep(1000); new Range(0,10000).filterBy::(x => x.mod(2) == 0).summarize(); } -public program() +public Program() { var start := now; - someProcess(); + SomeProcess(); var end := now; - console.printLine("Time elapsed in msec:",(end - start).Milliseconds) + Console.printLine("Time elapsed in msec:",(end - start).Milliseconds) } diff --git a/Task/Time-a-function/Elixir/time-a-function-1.elixir b/Task/Time-a-function/Elixir/time-a-function-1.ex similarity index 100% rename from Task/Time-a-function/Elixir/time-a-function-1.elixir rename to Task/Time-a-function/Elixir/time-a-function-1.ex diff --git a/Task/Time-a-function/Elixir/time-a-function-2.elixir b/Task/Time-a-function/Elixir/time-a-function-2.ex similarity index 100% rename from Task/Time-a-function/Elixir/time-a-function-2.elixir rename to Task/Time-a-function/Elixir/time-a-function-2.ex diff --git a/Task/Time-a-function/Elixir/time-a-function-3.elixir b/Task/Time-a-function/Elixir/time-a-function-3.ex similarity index 100% rename from Task/Time-a-function/Elixir/time-a-function-3.elixir rename to Task/Time-a-function/Elixir/time-a-function-3.ex diff --git a/Task/Time-a-function/Euphoria/time-a-function.euphoria b/Task/Time-a-function/Euphoria/time-a-function.eu similarity index 100% rename from Task/Time-a-function/Euphoria/time-a-function.euphoria rename to Task/Time-a-function/Euphoria/time-a-function.eu diff --git a/Task/Time-a-function/Fennel/time-a-function.fennel b/Task/Time-a-function/Fennel/time-a-function.fennel new file mode 100644 index 0000000000..da00463f90 --- /dev/null +++ b/Task/Time-a-function/Fennel/time-a-function.fennel @@ -0,0 +1,22 @@ +(do ;;; Time a function + + (fn time-function [fn-to=be-timed] + (local start-time (os.clock)) + (fn-to=be-timed) + (- (os.clock) start-time) ;;; execution time in seconds + ) + + (fn delay [delta-t] + (local end-time (+ (os.clock) delta-t)) + (while (< (os.clock) end-time) + (var x 0) + (for [i 1 100_000] (set x (+ x 1))) + ) + ) + + (fn test-fn [] + (delay 1.234) ; sleep 1.234 seconds + ) + + (print (time-function test-fn " seconds")) +) diff --git a/Task/Time-a-function/FutureBasic/time-a-function.basic b/Task/Time-a-function/FutureBasic/time-a-function.basic new file mode 100644 index 0000000000..8924c2338a --- /dev/null +++ b/Task/Time-a-function/FutureBasic/time-a-function.basic @@ -0,0 +1,62 @@ +begin enum 1 + _numLabel + _numInput + _textField + _computeTime +end enum + +void local fn BuildMacInterface + window 1, @"Prime factors", ( 0, 0, 560, 120 ), NSWindowStyleMaskTitled + NSWindowStyleMaskClosable + textlabel _numLabel, @"Number to factor:", ( 155, 86, 148, 24 ) + textfield _numInput, Yes, @"", ( 280, 88, 160, 24 ) + TextFieldSetTextColor ( _numLabel, fn ColorGray ) + ControlSetAlignment ( _numInput, NSTextAlignmentCenter ) + ControlSetFormat ( _numInput, @"0123456789-", YES, 15, _formatCaseInsensitive ) + ControlSetFont ( _numInput, fn FontSystemFontOfSize( 13 ) ) + textfield _textField, YES, , ( 20, 46, 520, 26 ) + ControlSetFontWithName ( _textField, @"Menlo", 12 ) + ControlSetAlignment( _textField, NSTextAlignmentCenter ) + TextFieldSetBordered( _textField, YES ) + textlabel _computeTime,,( 350, 16, 188, 22 ) + ControlSetAlignment( _computeTime, NSTextAlignmentRight ) + filemenu 1 : menu 1, , No + editmenu 2 : menu 2, , Yes + WindowMakeFirstResponder ( 1, _numInput ) +end fn + + +void local fn factor + SInt64 i, count = 0, num = fn ControlIntegerValue( _numInput ), n = num + if n < 0 then n = -n + while ( n mod 2 == 0 ) + mda(count) = 2 : count++ : n = n/2 + wend + for i = 3 to sqr(n) + 1 step 2 + while ( n mod i == 0 ) + mda(count) = i : count++ : n = n/i + wend + next + if (n > 2) then mda(count) = n + if num < 0 then mda(0) = -mda_integer(0) + CFStringRef s = fn StringByReplacingOccurrencesOfString( mda_text, @"\n", @" * " ) : mda_kill + s = fn StringByTrimmingCharactersInSet( s, fn CharacterSetWithCharactersInString( @" * " ) ) + ControlSetStringValue( _textField, fn StringWithFormat( @"%@ = %lld", s, num ) ) +end fn + + +void local fn DoDialog( ev as Long ) + select ev + case _controlTextDidEndEditing + CFTimeInterval t = fn CACurrentMediaTime + fn Factor + ControlSetStringValue( _computeTime, fn StringWithFormat( @"Compute time: %.3f ms", (fn CACurrentMediaTime-t)*1000 ) ) + WindowMakeFirstResponder( _textField, _numInput ) + case _windowWillClose : end + end select +end fn + +fn BuildMacInterface + +on dialog fn DoDialog + +HandleEvents diff --git a/Task/Time-a-function/Insitux/time-a-function.insitux b/Task/Time-a-function/Insitux/time-a-function.insitux index ff9da5b26e..373cd6c323 100644 --- a/Task/Time-a-function/Insitux/time-a-function.insitux +++ b/Task/Time-a-function/Insitux/time-a-function.insitux @@ -1,6 +1,6 @@ (function measure (let [start result end] [(time) (... . args) (time)]) - (str result " took " (- end start) "ms")) + "{result} took {- end start}ms") (function fib n (if (< n 2) n diff --git a/Task/Time-a-function/Julia/time-a-function.julia b/Task/Time-a-function/Julia/time-a-function.jl similarity index 100% rename from Task/Time-a-function/Julia/time-a-function.julia rename to Task/Time-a-function/Julia/time-a-function.jl diff --git a/Task/Time-a-function/Kotlin/time-a-function.kotlin b/Task/Time-a-function/Kotlin/time-a-function.kts similarity index 100% rename from Task/Time-a-function/Kotlin/time-a-function.kotlin rename to Task/Time-a-function/Kotlin/time-a-function.kts diff --git a/Task/Time-a-function/Lua/time-a-function.lua b/Task/Time-a-function/Lua/time-a-function.lua index 2344a8fcdf..40efbdd971 100644 --- a/Task/Time-a-function/Lua/time-a-function.lua +++ b/Task/Time-a-function/Lua/time-a-function.lua @@ -1,12 +1,14 @@ -function Test_Function() - for i = 1, 10000000 do - local s = math.log( i ) - s = math.sqrt( s ) - end +function bench(Function, ...) + local t = os.time() + local clock1 = os.clock() + Function(...) + local c = os.clock()-clock1 + return os.time()-t, c end -t1 = os.clock() - Test_Function() -t2 = os.clock() +function sleep(n) + local start = os.time() + repeat until os.time()-start==n +end -print( os.difftime( t2, t1 ) ) +print( bench(sleep, 2) ) diff --git a/Task/Time-a-function/Nu/time-a-function.nu b/Task/Time-a-function/Nu/time-a-function.nu new file mode 100644 index 0000000000..069519aa2b --- /dev/null +++ b/Task/Time-a-function/Nu/time-a-function.nu @@ -0,0 +1 @@ +timeit { sleep 1ms } diff --git a/Task/Time-a-function/OCaml/time-a-function.ocaml b/Task/Time-a-function/OCaml/time-a-function.ml similarity index 100% rename from Task/Time-a-function/OCaml/time-a-function.ocaml rename to Task/Time-a-function/OCaml/time-a-function.ml diff --git a/Task/Time-a-function/PascalABC.NET/time-a-function.pas b/Task/Time-a-function/PascalABC.NET/time-a-function.pas new file mode 100644 index 0000000000..ebbe256cad --- /dev/null +++ b/Task/Time-a-function/PascalABC.NET/time-a-function.pas @@ -0,0 +1,14 @@ +function LongTimeCalc(n: integer): real; +begin + var sum := 0.0; + for var i:=1 to n do + for var j := 1 to n do + sum += 1/i/j; + Result := sum; +end; + +begin + MillisecondsDelta; + LongTimeCalc(10000).Println; + MillisecondsDelta.Println; +end. diff --git a/Task/Time-a-function/Pluto/time-a-function.pluto b/Task/Time-a-function/Pluto/time-a-function.pluto new file mode 100644 index 0000000000..a9eecc53d1 --- /dev/null +++ b/Task/Time-a-function/Pluto/time-a-function.pluto @@ -0,0 +1,14 @@ +do -- Time a function + + local function timeFunction( f : function ) : number + local startTime = os.micros() + f() + return os.micros() - startTime + end + + local function toBeTimed() : void + os.sleep( 1234 ) -- sleep 1.234 seconds + end + + print( $"{ timeFunction( toBeTimed ) / 1_000_000 } seconds" ) +end diff --git a/Task/Time-a-function/PowerShell/time-a-function.psh b/Task/Time-a-function/PowerShell/time-a-function.ps1 similarity index 100% rename from Task/Time-a-function/PowerShell/time-a-function.psh rename to Task/Time-a-function/PowerShell/time-a-function.ps1 diff --git a/Task/Time-a-function/REXX/time-a-function-1.rexx b/Task/Time-a-function/REXX/time-a-function-1.rexx index 0e752fd011..9afaf04611 100644 --- a/Task/Time-a-function/REXX/time-a-function-1.rexx +++ b/Task/Time-a-function/REXX/time-a-function-1.rexx @@ -1,27 +1,5 @@ -/*REXX program displays the elapsed time for a REXX function (or subroutine). */ -arg reps . /*obtain an optional argument from C.L.*/ -if reps=='' then reps=100000 /*Not specified? No, then use default.*/ -call time 'Reset' /*only the 1st character is examined. */ -junk = silly(reps) /*invoke the SILLY function (below). */ - /*───► CALL SILLY REPS also works.*/ - - /* The E is for elapsed time.*/ - /* │ ─ */ - /* ┌────◄───┘ */ - /* │ */ - /* ↓ */ -say 'function SILLY took' format(time("E"),,2) 'seconds for' reps "iterations." - /* ↑ */ - /* │ */ - /* ┌────────►───────┘ */ - /* │ */ - /* The above 2 for the FORMAT function displays the time with*/ - /* two decimal digits (rounded) past the decimal point). Using */ - /* a 0 (zero) would round the time to whole seconds. */ -exit /*stick a fork in it, we're all done. */ -/*────────────────────────────────────────────────────────────────────────────*/ -silly: procedure /*chew up some CPU time doing some silly stuff.*/ - do j=1 for arg(1) /*wash, apply, lather, rinse, repeat. ··· */ - @.j=random() date() time() digits() fuzz() form() xrange() queued() - end /*j*/ - return j-1 +do x = 1 to 40 + say time('l') time('e') + do y = 1 to 10000 + end +end diff --git a/Task/Time-a-function/REXX/time-a-function-2.rexx b/Task/Time-a-function/REXX/time-a-function-2.rexx index 4d8817660a..31ad176743 100644 --- a/Task/Time-a-function/REXX/time-a-function-2.rexx +++ b/Task/Time-a-function/REXX/time-a-function-2.rexx @@ -1,27 +1,498 @@ -/*REXX program displays the elapsed time for a REXX function (or subroutine). */ -arg reps . /*obtain an optional argument from C.L.*/ -if reps=='' then reps=100000 /*Not specified? No, then use default.*/ -call time 'Reset' /*only the 1st character is examined. */ -junk = silly(reps) /*invoke the SILLY function (below). */ - /*───► CALL SILLY REPS also works.*/ +-- 24 Aug 2025 +include Setting +arg count','prec +if count = '' then + count = 1e7 +if prec = '' then + prec = 9 +numeric digits prec - /* The J is for the CPU time used */ - /* │ by the REXX program since */ - /* ┌───────┘ since the time was RESET. */ - /* │ This is a Regina extension.*/ - /* ↓ */ -say 'function SILLY took' format(time("J"),,2) 'seconds for' reps "iterations." - /* ↑ */ - /* │ */ - /* ┌────────►───────┘ */ - /* │ */ - /* The above 2 for the FORMAT function displays the time with*/ - /* two decimal digits (rounded) past the decimal point). Using */ - /* a 0 (zero) would round the time to whole seconds. */ -exit /*stick a fork in it, we're all done. */ -/*────────────────────────────────────────────────────────────────────────────*/ -silly: procedure /*chew up some CPU time doing some silly stuff.*/ - do j=1 for arg(1) /*wash, apply, lather, rinse, repeat. ··· */ - @.j=random() date() time() digits() fuzz() form() xrange() queued() - end /*j*/ - return j-1 +say 'TIME A FUNCTION' +say version +say +say 'Part 1: REXX clauses' +say +call Parameters +call DoLoop +call DoForLoop +call DoToLoop +call DoForByLoop +call DoToByLoop +say +call Tarra +call IntegerAssign +call IntegerAdd +call IntegerMultiply +call IntegerDivide1 +call IntegerDivide2 +call IntegerRemainder +call IntegerPower +say +call FloatAssign +call FloatAdd +call FloatMultiply +call FloatDivide1 +call FloatDivide2 +call FloatRemainder +call FloatPower +call FloatFormula +say +call StringFunctions +call NumericFunctions +call DateFunctions +call TimeFunctions +say +call FixedParseVar +call DynamicParseVar +call ParseValue +say +call NoOperation +say +call IfThen +call SelectWhen +say +call CallProc +call CallProcParms +call CallRout +call CallRoutParms +say +call Interpreting +say +call Output +call Input +say +call Stems +say +call Average +say +say 'Part 2: Profiler' +say +call Profiler 'ArcSin(X)',1/3 +call Profiler 'Exp(X)',1/4 +call Profiler 'Gamma(X)',1/5 +call Profiler 'Ln(X)',1/6 +call Profiler 'Pi()' +call Profiler 'Sin(X)',1/7 +call Profiler 'Sqrt(X)',1/8 +call Profiler 'X',1/9 +call Profiler 'X**5-5/x-1',1/10 +call Profiler 'Zeta(X)',1/11 +return + +Parameters: +start = date() time() +int1 = right(sqrt3(),prec%2); int2 = right(sqrt2(),prec%2) +if int2 > int1 then + parse value int2 int1 with int1 int2 +float1 = sqrt3()/1; float2 = sqrt2()/1 +tarra = 0; totelaps = 0; totcount = 0 +return + +DoLoop: +call Time('r') +do count +end +call Measure 'Do',1 +return + +DoForLoop: +call Time('r') +do n = 1 for count +end +call Measure 'Do for',1 +return + +DoToLoop: +call Time('r') +do n = 1 to count +end +call Measure 'Do to',1 +return + +DoForByLoop: +call Time('r') +do n = 1 for count by 1 +end +call Measure 'Do for by',1 +return + +DoToByLoop: +call Time('r') +do n = 1 to count by 1 +end +call Measure 'Do to by',1 +return + +Tarra: +call Time('r') +do n = 1 to 1e8 +end +tarra = Time('e')*count/1e8 +return + +IntegerAssign: +call Time('r') +do n = 1 to count + a = int1 +end +call Measure 'Integer assign',1 +return + +IntegerAdd: +call Time('r') +do n = 1 to count + a = int1+int2 +end +call Measure 'Integer +',1 +return + +IntegerMultiply: +call Time('r') +do n = 1 to count + a = int1*int2 +end +call Measure 'Integer *',1 +return + +IntegerDivide1: +call Time('r') +do n = 1 to count + a = int1/int2 +end +call Measure 'Integer /',1 +return + +IntegerDivide2: +call Time('r') +do n = 1 to count + a = int1//int2 +end +call Measure 'Integer //',1 +return + +IntegerRemainder: +call Time('r') +do n = 1 to count + a = int1%int2 +end +call Measure 'Integer %',1 +return + +IntegerPower: +call Time('r') +do n = 1 to count + a = int1**2 +end +call Measure 'Integer **',1 +return + +FloatAssign: +call Time('r') +do n = 1 to count + a = float1 +end +call Measure 'Float assign',1 +return + +FloatAdd: +call Time('r') +do n = 1 to count + a = float1+float2 +end +call Measure 'Float +',1 +return + +FloatMultiply: +call Time('r') +do n = 1 to count + a = float1*float2 +end +call Measure 'Float *',1 +return + +FloatDivide1: +call Time('r') +do n = 1 to count + a = float1/float2 +end +call Measure 'Float /',1 +return + +FloatDivide2: +call Time('r') +do n = 1 to count + a = float1//float2 +end +call Measure 'Float //',1 +return + +FloatRemainder: +call Time('r') +do n = 1 to count + a = float1%float2 +end +call Measure 'Float %',1 +return + +FloatPower: +call Time('r') +do n = 1 to count + a = float1**2 +end +call Measure 'Float **',1 +return + +FloatFormula: +call Time('r') +do n = 1 to count + a = (float1+float2) + (float1*float2) + (float1/float2) +end +call Measure 'Float formula',1 +return + +StringFunctions: +a = 'This is the first text'; b = 'This is the second text'; c = float1 +call Time('r') +do n = 1 to count + t = a||b + t = Abbrev('text',a) + t = Center(a,100) + t = Compare(a,b) + t = Copies(a,3) + t = Delstr(a,5,10) + t = Delword(a,2,3) + t = Format(c,1,5) + t = Insert(a,b,10) + t = Lastpos('text',a) + t = Left(a,10) + t = Length(a) + t = Overlay('xxx',a,3) + t = Pos('text',a) + t = Reverse(a) + t = Right(a,10) + t = Space(a) + t = Strip(a) + t = Substr(a,5,10) + t = Subword(a,2,2) + t = Translate(a,'xxx','the') + t = Verify(a,'the') + t = Word(a,3) + t = Wordindex(a,3) + t = Wordlength(a,3) + t = Wordpos('the',a) + t = Words(a) + t = Xrange('a','z') +end +call Measure 'String functions',28 +return + +NumericFunctions: +call Time('r') +do n = 1 to count + t = Abs(float1) + t = Max(float1,float2) + t = Min(float1,float2) + t = Random() + t = Sign(float1) + t = Trunc(float1) + t = Digits() +end +call Measure 'Numeric functions',7 +return + +DateFunctions: +call Time('r') +do n = 1 to count + t = Date('b') + t = Date('d') + t = Date('e') + t = Date('m') + t = Date('n') + t = Date('o') + t = Date('s') + t = Date('u') + t = Date('w') +end +call Measure 'Date functions',9 +return + +TimeFunctions: +call Time('r') +do n = 1 to count + t = Time('c') + t = Time('e') + t = Time('h') + t = Time('l') + t = Time('m') + t = Time('n') + t = Time('s') +end +call Measure 'Time functions',7 +return + +FixedParseVar: +t = '1,2,3,4,5,6,7,8,9,10' +call Time('r') +do n = 1 to count + parse var t rec1 ',' rec2 ',' rec3 ',' rec4 ',' rec5 ',' rec6 ',' rec7 ',' rec8 ',' rec9 ',' rec10 +end +call Measure 'Fixed parse var',1 +return + +DynamicParseVar: +t = '1,2,3,4,5,6,7,8,9,10' +call Time('r') +do n = 1 to count + do y = 1 to 10 + parse var t rec.y ',' t + end +end +call Measure 'Dynamic parse var',1 +return + +Parsevalue: +call Time('r') +do n = 1 to count + parse value float1 float2 with a,b +end +call Measure 'Parse value',1 +return + +NoOperation: +call Time('r') +do n = 1 to count + nop +end +call Measure 'No operation',1 +return + +IfThen: +call Time('r') +do n = 1 to count + if float1 = float1 then nop +end +call Measure 'If then',1 +return + +SelectWhen: +call Time('r') +do n = 1 to count + select + when float1 = float1 then nop + end +end +call Measure 'Select when',1 +return + +CallProc: +call Time('r') +do n = 1 to count + call Proc1 +end +call Measure 'Call procedure',1 +return + +CallProcParms: +call Time('r') +do n = 1 to count + call Proc2 1,2,3 +end +call Measure 'Call procedure arg',1 +return + +CallRout: +call Time('r') +do n = 1 to count + call Rout1 +end +call Measure 'Call routine',1 +return + +CallRoutParms: +call Time('r') +do n = 1 to count + call Rout2 1,2,3 +end +call Measure 'Call routine arg',1 +return + +Proc1: +procedure +return + +Proc2: +procedure +arg a,b,c +return + +Rout1: +return + +Rout2: +arg a,b,c +return + +Interpreting: +a = 'nop' +call Time('r') +do n = 1 to count + interpret a +end +call Measure 'Interpret',1 +return + +Output: +file = 'dummy.txt' +call Lineout file,,1 +call Time('r') +do n = 1 to count + call Lineout file,'Just a small line' +end +call Measure 'Output',1 +return + +Input: +file = 'dummy.txt' +call Time('r') +do n = 1 to count + t = Linein(file) +end +call Measure 'Input',1 +return + +Stems: +call Time('r') +do n = 1 to count + stem.n = n +end +call Measure 'Stem processing',1 +return + +Average: +totelaps = 1e6*totelaps/totcount +say Left('Average',20) round(totelaps,3) 'microsec =' round(1/totelaps,1) 'million clauses/sec' +say +say Left('Start run',20) start +say Left('Clauses processed',20) round(totcount/1e6,1) 'million' +say Left('Stop run',20) date() time() +return + +Measure: +parse arg measure,clauses +elaps = Time('e')-tarra +if elaps > 0 then do + totelaps = totelaps+elaps; totcount = totcount+count*clauses + elaps = 1e6*elaps/(count*clauses) + say Left(measure,20) round(elaps,3) 'microsec =' round(1/elaps,1) 'million clauses/sec' +end +else + say Left(measure,20) 'cannot perform measure, please try a higher count' +return + +Profiler: +arg ff,xx,yy,zz +rr=Profile(ff,xx,yy,zz) +say left(ff,10) 'takes' right(word(rr,2),4) 'microsec, x =' xx', f =' word(rr,1)/1 +return + +include Math diff --git a/Task/Time-a-function/Rust/time-a-function.rust b/Task/Time-a-function/Rust/time-a-function.rs similarity index 100% rename from Task/Time-a-function/Rust/time-a-function.rust rename to Task/Time-a-function/Rust/time-a-function.rs diff --git a/Task/Time-a-function/Scheme/time-a-function.ss b/Task/Time-a-function/Scheme/time-a-function.scm similarity index 100% rename from Task/Time-a-function/Scheme/time-a-function.ss rename to Task/Time-a-function/Scheme/time-a-function.scm diff --git a/Task/Tokenize-a-string-with-escaping/Ada/tokenize-a-string-with-escaping.ada b/Task/Tokenize-a-string-with-escaping/Ada/tokenize-a-string-with-escaping.adb similarity index 100% rename from Task/Tokenize-a-string-with-escaping/Ada/tokenize-a-string-with-escaping.ada rename to Task/Tokenize-a-string-with-escaping/Ada/tokenize-a-string-with-escaping.adb diff --git a/Task/Tokenize-a-string-with-escaping/Arturo/tokenize-a-string-with-escaping.arturo b/Task/Tokenize-a-string-with-escaping/Arturo/tokenize-a-string-with-escaping.arturo index a4d5e9db55..a35ecee9e6 100644 --- a/Task/Tokenize-a-string-with-escaping/Arturo/tokenize-a-string-with-escaping.arturo +++ b/Task/Tokenize-a-string-with-escaping/Arturo/tokenize-a-string-with-escaping.arturo @@ -4,15 +4,15 @@ tokenize: function [s sep esc][ loop 0..(size s)-1 [i][ chr: get split s i - if? escaping=1 [ + switch escaping=1 [ prints chr escaping: 0 - ] - else [ - case [chr] - when? [=sep] [print ""] - when? [=esc] [escaping: 1] - else [prints chr] + ][ + case chr [ + sep -> print "" + esc -> escaping: 1 + any -> prints chr + ] ] ] print "" diff --git a/Task/Tokenize-a-string-with-escaping/COBOL/tokenize-a-string-with-escaping.cobol b/Task/Tokenize-a-string-with-escaping/COBOL/tokenize-a-string-with-escaping.cob similarity index 100% rename from Task/Tokenize-a-string-with-escaping/COBOL/tokenize-a-string-with-escaping.cobol rename to Task/Tokenize-a-string-with-escaping/COBOL/tokenize-a-string-with-escaping.cob diff --git a/Task/Tokenize-a-string-with-escaping/EasyLang/tokenize-a-string-with-escaping.easy b/Task/Tokenize-a-string-with-escaping/EasyLang/tokenize-a-string-with-escaping.easy new file mode 100644 index 0000000000..99f46e1de6 --- /dev/null +++ b/Task/Tokenize-a-string-with-escaping/EasyLang/tokenize-a-string-with-escaping.easy @@ -0,0 +1,20 @@ +func$[] tokenize src$ sep$ esc$ . + r$[] = [ "" ] + for i = 1 to len src$ + c$ = substr src$ i 1 + if esc = 1 + r$[$] &= c$ + esc = 0 + else + if c$ = sep$ + r$[] &= "" + elif c$ = esc$ + esc = 1 + else + r$[$] &= c$ + . + . + . + return r$[] +. +print tokenize "one^|uno||three^^^^|four^^^|^cuatro|" "|" "^" 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 94d2914440..7b00515e71 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 @@ -38,9 +38,9 @@ extension op : String } } -const string testcase = "one^|uno||three^^^^|four^^^|^cuatro|"; +const string Testcase = "one^|uno||three^^^^|four^^^|^cuatro|"; -public program() +public Program() { - testcase.tokenize("|", "^").forEach(printingLn) + Testcase.tokenize("|", "^").forEach(PrintingLn) } diff --git a/Task/Tokenize-a-string-with-escaping/Icon/tokenize-a-string-with-escaping.icon b/Task/Tokenize-a-string-with-escaping/Icon/tokenize-a-string-with-escaping.icon new file mode 100644 index 0000000000..8744df9fc4 --- /dev/null +++ b/Task/Tokenize-a-string-with-escaping/Icon/tokenize-a-string-with-escaping.icon @@ -0,0 +1,21 @@ +procedure main() + str := "one^|uno||three^^^^|four^^^|^cuatro|" + every write("\"",!tokenize(str,"|","^"),"\"") +end + +procedure tokenize(str,sep,esc) + ret := [] + token := "" + cse := cset(sep||esc) + str ? + repeat{ + token ||:= tab(i := (upto(cse) | 0)) + if i = 0 then return put(ret,token) + move(1) + if str[i] == sep then{ + put(ret,token) + token := "" + }else + token ||:= move(1) + } +end diff --git a/Task/Tokenize-a-string-with-escaping/Julia/tokenize-a-string-with-escaping.julia b/Task/Tokenize-a-string-with-escaping/Julia/tokenize-a-string-with-escaping.jl similarity index 100% rename from Task/Tokenize-a-string-with-escaping/Julia/tokenize-a-string-with-escaping.julia rename to Task/Tokenize-a-string-with-escaping/Julia/tokenize-a-string-with-escaping.jl diff --git a/Task/Tokenize-a-string-with-escaping/Kotlin/tokenize-a-string-with-escaping.kotlin b/Task/Tokenize-a-string-with-escaping/Kotlin/tokenize-a-string-with-escaping.kts similarity index 100% rename from Task/Tokenize-a-string-with-escaping/Kotlin/tokenize-a-string-with-escaping.kotlin rename to Task/Tokenize-a-string-with-escaping/Kotlin/tokenize-a-string-with-escaping.kts diff --git a/Task/Tokenize-a-string-with-escaping/Lua/tokenize-a-string-with-escaping-1.lua b/Task/Tokenize-a-string-with-escaping/Lua/tokenize-a-string-with-escaping-1.lua new file mode 100644 index 0000000000..ab01ed7442 --- /dev/null +++ b/Task/Tokenize-a-string-with-escaping/Lua/tokenize-a-string-with-escaping-1.lua @@ -0,0 +1,25 @@ +function Tokenize (str, sep, esc) + local strList, word, escaped, ch = {}, "", false + for pos = 1, #str do + ch = str:sub(pos, pos) + if ch == esc then + if escaped then + word = word .. ch + end + escaped = not escaped + elseif ch == sep then + if escaped then + word = word .. ch + escaped = false + else + table.insert(strList, word) + word = "" + end + else + escaped = false + word = word .. ch + end + end + table.insert(strList, word) + return strList +end diff --git a/Task/Tokenize-a-string-with-escaping/Lua/tokenize-a-string-with-escaping-2.lua b/Task/Tokenize-a-string-with-escaping/Lua/tokenize-a-string-with-escaping-2.lua new file mode 100644 index 0000000000..5b68d41325 --- /dev/null +++ b/Task/Tokenize-a-string-with-escaping/Lua/tokenize-a-string-with-escaping-2.lua @@ -0,0 +1,11 @@ +function Tokenize(str, sep, esc) local R = {} + local repl = sep~="\0" and esc~="\0" and "\0" + or sep~="\1" and esc~="\1" and "\1" + or sep~="\2" and esc~="\2" and "\2" + local fakeStr = str:gsub("[%" .. esc .. "].", repl .. repl) + local pattern = "()[^%" .. sep .. "]*()" + for start, fin in fakeStr:gmatch(pattern) do + R[#R+1] = str:sub(start, fin-1) + end + return R +end diff --git a/Task/Tokenize-a-string-with-escaping/Lua/tokenize-a-string-with-escaping-3.lua b/Task/Tokenize-a-string-with-escaping/Lua/tokenize-a-string-with-escaping-3.lua new file mode 100644 index 0000000000..065824c58c --- /dev/null +++ b/Task/Tokenize-a-string-with-escaping/Lua/tokenize-a-string-with-escaping-3.lua @@ -0,0 +1,4 @@ +local testStr = "one^|uno||three^^^^|four^^^|^cuatro|" +for k, v in ipairs(Tokenize(testStr, "|", "^")) do + print(k, v) +end diff --git a/Task/Tokenize-a-string-with-escaping/Lua/tokenize-a-string-with-escaping.lua b/Task/Tokenize-a-string-with-escaping/Lua/tokenize-a-string-with-escaping.lua deleted file mode 100644 index 2e72972d27..0000000000 --- a/Task/Tokenize-a-string-with-escaping/Lua/tokenize-a-string-with-escaping.lua +++ /dev/null @@ -1,33 +0,0 @@ -function tokenise (str, sep, esc) - local strList, word, escaped, ch = {}, "", false - for pos = 1, #str do - ch = str:sub(pos, pos) - if ch == esc then - if escaped then - word = word .. ch - escaped = false - else - escaped = true - end - elseif ch == sep then - if escaped then - word = word .. ch - escaped = false - else - table.insert(strList, word) - word = "" - end - else - escaped = false - word = word .. ch - end - end - table.insert(strList, word) - return strList -end - -local testStr = "one^|uno||three^^^^|four^^^|^cuatro|" -local testSep, testEsc = "|", "^" -for k, v in pairs(tokenise(testStr, testSep, testEsc)) do - print(k, v) -end diff --git a/Task/Tokenize-a-string-with-escaping/OCaml/tokenize-a-string-with-escaping-1.ocaml b/Task/Tokenize-a-string-with-escaping/OCaml/tokenize-a-string-with-escaping-1.ml similarity index 100% rename from Task/Tokenize-a-string-with-escaping/OCaml/tokenize-a-string-with-escaping-1.ocaml rename to Task/Tokenize-a-string-with-escaping/OCaml/tokenize-a-string-with-escaping-1.ml diff --git a/Task/Tokenize-a-string-with-escaping/OCaml/tokenize-a-string-with-escaping-2.ocaml b/Task/Tokenize-a-string-with-escaping/OCaml/tokenize-a-string-with-escaping-2.ml similarity index 100% rename from Task/Tokenize-a-string-with-escaping/OCaml/tokenize-a-string-with-escaping-2.ocaml rename to Task/Tokenize-a-string-with-escaping/OCaml/tokenize-a-string-with-escaping-2.ml diff --git a/Task/Tokenize-a-string-with-escaping/Pluto/tokenize-a-string-with-escaping.pluto b/Task/Tokenize-a-string-with-escaping/Pluto/tokenize-a-string-with-escaping.pluto new file mode 100644 index 0000000000..fe509c822a --- /dev/null +++ b/Task/Tokenize-a-string-with-escaping/Pluto/tokenize-a-string-with-escaping.pluto @@ -0,0 +1,14 @@ +$define SPE = "\u{fffe}" -- unused unicode character in Specials block +$define SPF = "\u{ffff}" -- ditto + +local function tokenize(str, sep, esc) + str = str:replace(esc .. esc, SPE):replace(esc .. sep, SPF) + str = (str[-1] == esc) ? (str:sub(1, -2):replace(esc, "") .. esc) : (str:replace(esc, "")) + return str:split(sep):map(|s| -> s:replace(SPE, esc):replace(SPF, sep)) +end + +local str = "one^|uno||three^^^^|four^^^|^cuatro|" +local sep = "|" +local esc = "^" +local items = tokenize(str, sep, esc) +for items as item do print((item == "") ? "(empty)" : item) end diff --git a/Task/Tokenize-a-string-with-escaping/PowerShell/tokenize-a-string-with-escaping-1.psh b/Task/Tokenize-a-string-with-escaping/PowerShell/tokenize-a-string-with-escaping-1.ps1 similarity index 100% rename from Task/Tokenize-a-string-with-escaping/PowerShell/tokenize-a-string-with-escaping-1.psh rename to Task/Tokenize-a-string-with-escaping/PowerShell/tokenize-a-string-with-escaping-1.ps1 diff --git a/Task/Tokenize-a-string-with-escaping/PowerShell/tokenize-a-string-with-escaping-2.psh b/Task/Tokenize-a-string-with-escaping/PowerShell/tokenize-a-string-with-escaping-2.ps1 similarity index 100% rename from Task/Tokenize-a-string-with-escaping/PowerShell/tokenize-a-string-with-escaping-2.psh rename to Task/Tokenize-a-string-with-escaping/PowerShell/tokenize-a-string-with-escaping-2.ps1 diff --git a/Task/Tokenize-a-string-with-escaping/Rust/tokenize-a-string-with-escaping.rust b/Task/Tokenize-a-string-with-escaping/Rust/tokenize-a-string-with-escaping.rs similarity index 100% rename from Task/Tokenize-a-string-with-escaping/Rust/tokenize-a-string-with-escaping.rust rename to Task/Tokenize-a-string-with-escaping/Rust/tokenize-a-string-with-escaping.rs diff --git a/Task/Tokenize-a-string-with-escaping/V-(Vlang)/tokenize-a-string-with-escaping.v b/Task/Tokenize-a-string-with-escaping/V-(Vlang)/tokenize-a-string-with-escaping.v index 797dd24318..1019ae0268 100644 --- a/Task/Tokenize-a-string-with-escaping/V-(Vlang)/tokenize-a-string-with-escaping.v +++ b/Task/Tokenize-a-string-with-escaping/V-(Vlang)/tokenize-a-string-with-escaping.v @@ -1,4 +1,4 @@ -fn tokenize_string(s string, sep u8, escape u8) ?[]string { +fn tokenize_string(s string, sep u8, escape u8) ![]string { mut tokens := []string{} mut runes := []u8{} mut in_escape := false @@ -10,7 +10,7 @@ fn tokenize_string(s string, sep u8, escape u8) ?[]string { in_escape = true } else if r == sep { tokens << runes.bytestr() - runes = runes[..0] + runes = runes[..0].clone() } else { runes << r } @@ -27,6 +27,6 @@ const separator = `|` const escape = `^` fn main() { println("Input: $sample") - tokens := tokenize_string(sample, separator, escape)? + tokens := tokenize_string(sample, separator, escape)! println("Tokens: $tokens") } diff --git a/Task/Tokenize-a-string/Ada/tokenize-a-string.ada b/Task/Tokenize-a-string/Ada/tokenize-a-string.adb similarity index 100% rename from Task/Tokenize-a-string/Ada/tokenize-a-string.ada rename to Task/Tokenize-a-string/Ada/tokenize-a-string.adb diff --git a/Task/Tokenize-a-string/Ballerina/tokenize-a-string.ballerina b/Task/Tokenize-a-string/Ballerina/tokenize-a-string.ballerina new file mode 100644 index 0000000000..4dce9f4315 --- /dev/null +++ b/Task/Tokenize-a-string/Ballerina/tokenize-a-string.ballerina @@ -0,0 +1,11 @@ +import ballerina/io; +import ballerina/regex; + +public function main() { + string s = "Hello,How,Are,You,Today"; + string[] oList = regex:split(s, ","); + foreach string i in oList { + io:print(i,"."); + } + io:println(); +} diff --git a/Task/Tokenize-a-string/COBOL/tokenize-a-string.cobol b/Task/Tokenize-a-string/COBOL/tokenize-a-string.cob similarity index 100% rename from Task/Tokenize-a-string/COBOL/tokenize-a-string.cobol rename to Task/Tokenize-a-string/COBOL/tokenize-a-string.cob diff --git a/Task/Tokenize-a-string/Crystal/tokenize-a-string.crystal b/Task/Tokenize-a-string/Crystal/tokenize-a-string.cr similarity index 100% rename from Task/Tokenize-a-string/Crystal/tokenize-a-string.crystal rename to Task/Tokenize-a-string/Crystal/tokenize-a-string.cr diff --git a/Task/Tokenize-a-string/Delphi/tokenize-a-string-1.delphi b/Task/Tokenize-a-string/Delphi/tokenize-a-string-1.pas similarity index 100% rename from Task/Tokenize-a-string/Delphi/tokenize-a-string-1.delphi rename to Task/Tokenize-a-string/Delphi/tokenize-a-string-1.pas diff --git a/Task/Tokenize-a-string/Delphi/tokenize-a-string-2.delphi b/Task/Tokenize-a-string/Delphi/tokenize-a-string-2.pas similarity index 100% rename from Task/Tokenize-a-string/Delphi/tokenize-a-string-2.delphi rename to Task/Tokenize-a-string/Delphi/tokenize-a-string-2.pas diff --git a/Task/Tokenize-a-string/Delphi/tokenize-a-string-3.delphi b/Task/Tokenize-a-string/Delphi/tokenize-a-string-3.pas similarity index 100% rename from Task/Tokenize-a-string/Delphi/tokenize-a-string-3.delphi rename to Task/Tokenize-a-string/Delphi/tokenize-a-string-3.pas diff --git a/Task/Tokenize-a-string/Draco/tokenize-a-string.draco b/Task/Tokenize-a-string/Draco/tokenize-a-string.draco new file mode 100644 index 0000000000..3e3570310a --- /dev/null +++ b/Task/Tokenize-a-string/Draco/tokenize-a-string.draco @@ -0,0 +1,24 @@ +proc tokenize(char sep; *char str; [*]*char parts) word: + word n; + n := 0; + while + parts[n] := str; + while str* /= sep and str* /= '\e' do str := str + 1 od; + n := n+1; + str* /= '\e' + do + str* := '\e'; + str := str + 1 + od; + n +corp + +proc main() void: + word i, count; + [10]*char parts; + count := tokenize(',', "Hello,How,Are,You,Today", parts); + for i from 0 upto count-1 do + write(parts[i], ". ") + od; + writeln() +corp diff --git a/Task/Tokenize-a-string/DuckDB/tokenize-a-string.duckdb b/Task/Tokenize-a-string/DuckDB/tokenize-a-string.duckdb new file mode 100644 index 0000000000..7d9391bc19 --- /dev/null +++ b/Task/Tokenize-a-string/DuckDB/tokenize-a-string.duckdb @@ -0,0 +1,4 @@ +create or replace function tokenize(s) as ( + regexp_split_to_array(s, ' *, *') +); +select tokenize('Hello,How,Are,You,Today') as tokens; diff --git a/Task/Tokenize-a-string/EasyLang/tokenize-a-string.easy b/Task/Tokenize-a-string/EasyLang/tokenize-a-string.easy index 5f9e3b6e86..2b0d77c0f5 100644 --- a/Task/Tokenize-a-string/EasyLang/tokenize-a-string.easy +++ b/Task/Tokenize-a-string/EasyLang/tokenize-a-string.easy @@ -1,5 +1,3 @@ s$ = "Hello,How,Are,You,Today" a$[] = strsplit s$ "," -for s$ in a$[] - write s$ & "." -. +print strjoin a$[] "." diff --git a/Task/Tokenize-a-string/Ed/tokenize-a-string.ed b/Task/Tokenize-a-string/Ed/tokenize-a-string.ed new file mode 100644 index 0000000000..cd1e1968bf --- /dev/null +++ b/Task/Tokenize-a-string/Ed/tokenize-a-string.ed @@ -0,0 +1,6 @@ +# by Artyom Bologov +H +,p +s/,/./g +,p +Q diff --git a/Task/Tokenize-a-string/Elena/tokenize-a-string.elena b/Task/Tokenize-a-string/Elena/tokenize-a-string.elena index 38a1ce5c50..ddf126ae72 100644 --- a/Task/Tokenize-a-string/Elena/tokenize-a-string.elena +++ b/Task/Tokenize-a-string/Elena/tokenize-a-string.elena @@ -1,12 +1,12 @@ import system'routines; import extensions; -public program() +public Program() { auto string := "Hello,How,Are,You,Today"; string.splitBy(",").forEach::(s) { - console.print(s,".") + Console.print(s,".") } } diff --git a/Task/Tokenize-a-string/Elixir/tokenize-a-string.elixir b/Task/Tokenize-a-string/Elixir/tokenize-a-string.ex similarity index 100% rename from Task/Tokenize-a-string/Elixir/tokenize-a-string.elixir rename to Task/Tokenize-a-string/Elixir/tokenize-a-string.ex diff --git a/Task/Tokenize-a-string/Euphoria/tokenize-a-string.euphoria b/Task/Tokenize-a-string/Euphoria/tokenize-a-string.eu similarity index 100% rename from Task/Tokenize-a-string/Euphoria/tokenize-a-string.euphoria rename to Task/Tokenize-a-string/Euphoria/tokenize-a-string.eu diff --git a/Task/Tokenize-a-string/Excel/tokenize-a-string-1.excel b/Task/Tokenize-a-string/Excel/tokenize-a-string-1.excel new file mode 100644 index 0000000000..1f048cee22 --- /dev/null +++ b/Task/Tokenize-a-string/Excel/tokenize-a-string-1.excel @@ -0,0 +1 @@ +=TEXTSPLIT("Hello,How,Are,You,Today", ",") diff --git a/Task/Tokenize-a-string/Excel/tokenize-a-string-2.excel b/Task/Tokenize-a-string/Excel/tokenize-a-string-2.excel new file mode 100644 index 0000000000..ad4050073f --- /dev/null +++ b/Task/Tokenize-a-string/Excel/tokenize-a-string-2.excel @@ -0,0 +1 @@ +=TEXTSPLIT("Hello,How,Are,You,Today", , ",") diff --git a/Task/Tokenize-a-string/Julia/tokenize-a-string.julia b/Task/Tokenize-a-string/Julia/tokenize-a-string.jl similarity index 100% rename from Task/Tokenize-a-string/Julia/tokenize-a-string.julia rename to Task/Tokenize-a-string/Julia/tokenize-a-string.jl diff --git a/Task/Tokenize-a-string/Kotlin/tokenize-a-string.kotlin b/Task/Tokenize-a-string/Kotlin/tokenize-a-string.kts similarity index 100% rename from Task/Tokenize-a-string/Kotlin/tokenize-a-string.kotlin rename to Task/Tokenize-a-string/Kotlin/tokenize-a-string.kts diff --git a/Task/Tokenize-a-string/LOLCODE/tokenize-a-string.lol b/Task/Tokenize-a-string/LOLCODE/tokenize-a-string.lol new file mode 100644 index 0000000000..698bfbd58f --- /dev/null +++ b/Task/Tokenize-a-string/LOLCODE/tokenize-a-string.lol @@ -0,0 +1,36 @@ +HAI 1.4 + +CAN HAS STRING? + +HOW IZ I TOKENIZE YR S + I HAS A L ITZ STRING IZ LEN YR S MKAY + I HAS A WORDZ ITZ A BUKKIT + I HAS A WORDCOUNT ITZ 0 + I HAS A C ITZ "" + IM IN YR LOOP UPPIN YR N TIL BOTH SAEM N AN L + I HAS A CN ITZ STRING IZ AT YR S AN YR N MKAY + BOTH SAEM CN AN ",", O RLY? + YA RLY + WORDZ HAS A SRS WORDCOUNT ITZ C + WORDCOUNT R SUM OF WORDCOUNT AN 1 + C R "" + NO WAI, C R SMOOSH C CN MKAY + OIC + IM OUTTA YR LOOP + WORDZ HAS A SRS WORDCOUNT ITZ C + WORDCOUNT R SUM OF WORDCOUNT AN 1 + WORDZ HAS A LENGTH ITZ WORDCOUNT + FOUND YR WORDZ +IF U SAY SO + +I HAS A TOKENZ ITZ I IZ TOKENIZE YR "Hello,How,Are,You,Today" MKAY + +IM IN YR DISPLAY UPPIN YR N TIL BOTH SAEM N AN TOKENZ'Z LENGTH + DIFFRINT N AN 0, O RLY? + YA RLY, VISIBLE "."! + OIC + VISIBLE TOKENZ'Z SRS N! +IM OUTTA YR DISPLAY +VISIBLE "" + +KTHXBYE diff --git a/Task/Tokenize-a-string/Nu/tokenize-a-string.nu b/Task/Tokenize-a-string/Nu/tokenize-a-string.nu new file mode 100644 index 0000000000..83ce8ca024 --- /dev/null +++ b/Task/Tokenize-a-string/Nu/tokenize-a-string.nu @@ -0,0 +1 @@ +'Hello,How,Are,You,Today' | split row ',' | str join '.' diff --git a/Task/Tokenize-a-string/OCaml/tokenize-a-string-1.ocaml b/Task/Tokenize-a-string/OCaml/tokenize-a-string-1.ml similarity index 100% rename from Task/Tokenize-a-string/OCaml/tokenize-a-string-1.ocaml rename to Task/Tokenize-a-string/OCaml/tokenize-a-string-1.ml diff --git a/Task/Tokenize-a-string/OCaml/tokenize-a-string-2.ocaml b/Task/Tokenize-a-string/OCaml/tokenize-a-string-2.ml similarity index 100% rename from Task/Tokenize-a-string/OCaml/tokenize-a-string-2.ocaml rename to Task/Tokenize-a-string/OCaml/tokenize-a-string-2.ml diff --git a/Task/Tokenize-a-string/PascalABC.NET/tokenize-a-string.pas b/Task/Tokenize-a-string/PascalABC.NET/tokenize-a-string.pas new file mode 100644 index 0000000000..2f40bf497d --- /dev/null +++ b/Task/Tokenize-a-string/PascalABC.NET/tokenize-a-string.pas @@ -0,0 +1,5 @@ +begin + var s := 'Hello,How,Are,You,Today'; + var strings := s.Split(','); + Print(strings.JoinToString('.')); +end. diff --git a/Task/Tokenize-a-string/PowerShell/tokenize-a-string-1.psh b/Task/Tokenize-a-string/PowerShell/tokenize-a-string-1.ps1 similarity index 100% rename from Task/Tokenize-a-string/PowerShell/tokenize-a-string-1.psh rename to Task/Tokenize-a-string/PowerShell/tokenize-a-string-1.ps1 diff --git a/Task/Tokenize-a-string/PowerShell/tokenize-a-string-2.psh b/Task/Tokenize-a-string/PowerShell/tokenize-a-string-2.ps1 similarity index 100% rename from Task/Tokenize-a-string/PowerShell/tokenize-a-string-2.psh rename to Task/Tokenize-a-string/PowerShell/tokenize-a-string-2.ps1 diff --git a/Task/Tokenize-a-string/PowerShell/tokenize-a-string-3.psh b/Task/Tokenize-a-string/PowerShell/tokenize-a-string-3.ps1 similarity index 100% rename from Task/Tokenize-a-string/PowerShell/tokenize-a-string-3.psh rename to Task/Tokenize-a-string/PowerShell/tokenize-a-string-3.ps1 diff --git a/Task/Tokenize-a-string/REXX/tokenize-a-string-1.rexx b/Task/Tokenize-a-string/REXX/tokenize-a-string-1.rexx index 95c3c556cc..ac479e8055 100644 --- a/Task/Tokenize-a-string/REXX/tokenize-a-string-1.rexx +++ b/Task/Tokenize-a-string/REXX/tokenize-a-string-1.rexx @@ -1,13 +1,13 @@ -/*REXX program separates a string of comma─delimited words, and echoes them ──► terminal*/ +/*REXX program separates a string of comma-delimited words, and echoes them --> terminal*/ original = 'Hello,How,Are,You,Today' /*some words separated by commas (,). */ -say 'The input string:' original /*display original string ──► terminal.*/ -new= original /*make a copy of the string. */ - do #=1 until new=='' /*keep processing until NEW is empty.*/ - parse var new @.# ',' new /*parse words delineated by a comma (,)*/ - end /*#*/ /* [↑] the new array is named @. */ -say /* NEW is destructively parsed. [↑] */ -say center(' Words in the string ', 40, "═") /*display a nice header for the list. */ - do j=1 for # /*display all the words (one per line),*/ - say @.j || left(., j\==#) /*maybe append a period (.) to a word. */ - end /*j*/ /* [↑] don't append a period if last. */ -say center(' End─of─list ', 40, "═") /*display a (EOL) trailer for the list.*/ +Say 'The input string:' original /*display original string --> terminal.*/ +new=original /*make a copy of the string. */ +Do n=1 Until new=='' /*keep processing until NEW is empty.*/ + Parse Var new word.n ',' new /*parse words delineated by a comma (,)*/ + End /*n*/ /* [?] the new array is named word. */ +Say /* NEW is destructively parsed. */ +Say center('Words in the string',40,'-') /*display a nice header for the list. */ +Do j=1 To n /*display all the words (one per line),*/ + Say word.j||left(.,j\==n) /*maybe append a period (.) to a word. */ + End /*j*/ /*Don't append a period after the last */ +Say center('End-of-list',40,'-') /*display a (EOL) trailer for the list.*/ diff --git a/Task/Tokenize-a-string/REBOL/tokenize-a-string.rebol b/Task/Tokenize-a-string/Rebol/tokenize-a-string-1.rebol similarity index 100% rename from Task/Tokenize-a-string/REBOL/tokenize-a-string.rebol rename to Task/Tokenize-a-string/Rebol/tokenize-a-string-1.rebol diff --git a/Task/Tokenize-a-string/Rebol/tokenize-a-string-2.rebol b/Task/Tokenize-a-string/Rebol/tokenize-a-string-2.rebol new file mode 100644 index 0000000000..7ff6d5aee3 --- /dev/null +++ b/Task/Tokenize-a-string/Rebol/tokenize-a-string-2.rebol @@ -0,0 +1,4 @@ +print ["Original:" original: "Hello,How,Are,You,Today"] +tokens: split original #"," +dotted: ajoin/with tokens #"." +print ["Dotted: " dotted] diff --git a/Task/Tokenize-a-string/Refal/tokenize-a-string.refal b/Task/Tokenize-a-string/Refal/tokenize-a-string.refal new file mode 100644 index 0000000000..4dad638e7e --- /dev/null +++ b/Task/Tokenize-a-string/Refal/tokenize-a-string.refal @@ -0,0 +1,15 @@ +$ENTRY Go { + = >>; +}; + +Split { + (e.S) = ; + (e.S) e.1 e.S e.2 = (e.1) ; + (e.S) e.1 = (e.1); +}; + +Join { + (e.J) = ; + (e.J) (e.1) = e.1; + (e.J) (e.1) e.2 = e.1 e.J ; +}; diff --git a/Task/Tokenize-a-string/Rust/tokenize-a-string.rust b/Task/Tokenize-a-string/Rust/tokenize-a-string.rs similarity index 100% rename from Task/Tokenize-a-string/Rust/tokenize-a-string.rust rename to Task/Tokenize-a-string/Rust/tokenize-a-string.rs diff --git a/Task/Tokenize-a-string/Rye/tokenize-a-string.rye b/Task/Tokenize-a-string/Rye/tokenize-a-string.rye new file mode 100644 index 0000000000..5d3130bb69 --- /dev/null +++ b/Task/Tokenize-a-string/Rye/tokenize-a-string.rye @@ -0,0 +1,4 @@ +"Hello,How,Are,You,Today" +|split "," +|join\with "." +|print diff --git a/Task/Tokenize-a-string/SETL/tokenize-a-string.setl b/Task/Tokenize-a-string/SETL/tokenize-a-string.setl new file mode 100644 index 0000000000..67670ca08c --- /dev/null +++ b/Task/Tokenize-a-string/SETL/tokenize-a-string.setl @@ -0,0 +1,18 @@ +program tokenize_a_string; + s := 'Hello,How,Are,You,Today'; + loop for part in tokenize(',', s) do + nprint(part + ". "); + end loop; + print; + + proc tokenize(sep, s); + loop + init parts := []; + doing parts with:= break(s, sep); + while s /= "" + do + s := s(2..); + end loop; + return parts; + end proc; +end program; diff --git a/Task/Tokenize-a-string/Scheme/tokenize-a-string-1.ss b/Task/Tokenize-a-string/Scheme/tokenize-a-string-1.scm similarity index 100% rename from Task/Tokenize-a-string/Scheme/tokenize-a-string-1.ss rename to Task/Tokenize-a-string/Scheme/tokenize-a-string-1.scm diff --git a/Task/Tokenize-a-string/Scheme/tokenize-a-string-2.ss b/Task/Tokenize-a-string/Scheme/tokenize-a-string-2.scm similarity index 100% rename from Task/Tokenize-a-string/Scheme/tokenize-a-string-2.ss rename to Task/Tokenize-a-string/Scheme/tokenize-a-string-2.scm diff --git a/Task/Tokenize-a-string/Scheme/tokenize-a-string-3.ss b/Task/Tokenize-a-string/Scheme/tokenize-a-string-3.scm similarity index 100% rename from Task/Tokenize-a-string/Scheme/tokenize-a-string-3.ss rename to Task/Tokenize-a-string/Scheme/tokenize-a-string-3.scm diff --git a/Task/Tokenize-a-string/TAV/tokenize-a-string.tav b/Task/Tokenize-a-string/TAV/tokenize-a-string.tav new file mode 100644 index 0000000000..94127b9070 --- /dev/null +++ b/Task/Tokenize-a-string/TAV/tokenize-a-string.tav @@ -0,0 +1,8 @@ + \ clear explicit version + s =: "Hello,How,Are,You,Today" + r =: string s split by any of ',' \ single character split + print join r by '.' + \ all in one, no parenthesis required + print join string "Hello,How,Are,You,Today" split by any of ',' by '.' + \ parenthesis for clarity + print (join (string "Hello,How,Are,You,Today" split by any of ',') by '.') diff --git a/Task/Tokenize-a-string/Tcl/tokenize-a-string-1.tcl b/Task/Tokenize-a-string/Tcl/tokenize-a-string-1.tcl index df0ca51b5f..23501aa840 100644 --- a/Task/Tokenize-a-string/Tcl/tokenize-a-string-1.tcl +++ b/Task/Tokenize-a-string/Tcl/tokenize-a-string-1.tcl @@ -1 +1,7 @@ -split $string "," +set string "Hello,How,Are,You,Today" + +set tokens [split $string ","] + +foreach tok $tokens { + puts -nonewline stdout "$tok\t" +} diff --git a/Task/Tokenize-a-string/Tcl/tokenize-a-string-2.tcl b/Task/Tokenize-a-string/Tcl/tokenize-a-string-2.tcl index 7a5e8feca2..a61bd1e925 100644 --- a/Task/Tokenize-a-string/Tcl/tokenize-a-string-2.tcl +++ b/Task/Tokenize-a-string/Tcl/tokenize-a-string-2.tcl @@ -1 +1,2 @@ -join $list "." +set string_p [join $tokens "."] +puts stdout $string_p diff --git a/Task/Tokenize-a-string/Tcl/tokenize-a-string-3.tcl b/Task/Tokenize-a-string/Tcl/tokenize-a-string-3.tcl deleted file mode 100644 index 8e516c254a..0000000000 --- a/Task/Tokenize-a-string/Tcl/tokenize-a-string-3.tcl +++ /dev/null @@ -1 +0,0 @@ -puts [join [split "Hello,How,Are,You,Today" ","] "."] diff --git a/Task/Tokenize-a-string/Tcl/tokenize-a-string-4.tcl b/Task/Tokenize-a-string/Tcl/tokenize-a-string-4.tcl deleted file mode 100644 index 44b4bd0ec8..0000000000 --- a/Task/Tokenize-a-string/Tcl/tokenize-a-string-4.tcl +++ /dev/null @@ -1 +0,0 @@ -puts [join [set words [split "Hello,How,Are,You,Today" ","]] "."] diff --git a/Task/Tokenize-a-string/VBScript/tokenize-a-string.vb b/Task/Tokenize-a-string/VBScript/tokenize-a-string.vbs similarity index 100% rename from Task/Tokenize-a-string/VBScript/tokenize-a-string.vb rename to Task/Tokenize-a-string/VBScript/tokenize-a-string.vbs diff --git a/Task/Tokenize-a-string/YAMLScript/tokenize-a-string.ys b/Task/Tokenize-a-string/YAMLScript/tokenize-a-string.ys new file mode 100644 index 0000000000..7cec2baab6 --- /dev/null +++ b/Task/Tokenize-a-string/YAMLScript/tokenize-a-string.ys @@ -0,0 +1,6 @@ +!YS-v0 + +say: + + 'Hello,How,Are,You,Today' + .split(/,/) + .join('.') diff --git a/Task/Tokenize-a-string/Zig/tokenize-a-string.zig b/Task/Tokenize-a-string/Zig/tokenize-a-string.zig index 9cdf0fcef6..63f90b8587 100644 --- a/Task/Tokenize-a-string/Zig/tokenize-a-string.zig +++ b/Task/Tokenize-a-string/Zig/tokenize-a-string.zig @@ -1,7 +1,7 @@ const std = @import("std"); pub fn main() void { const string = "Hello,How,Are,You,Today"; - var tokens = std.mem.split(u8, string, ","); + var tokens = std.mem.splitScalar(u8, string, ','); std.debug.print("{s}", .{tokens.next().?}); while (tokens.next()) |token| { std.debug.print(".{s}", .{token}); diff --git a/Task/Tonelli-Shanks-algorithm/Dart/tonelli-shanks-algorithm.dart b/Task/Tonelli-Shanks-algorithm/Dart/tonelli-shanks-algorithm.dart new file mode 100644 index 0000000000..c56c649e82 --- /dev/null +++ b/Task/Tonelli-Shanks-algorithm/Dart/tonelli-shanks-algorithm.dart @@ -0,0 +1,122 @@ +class Pair { + final int n; + final int p; + + Pair(this.n, this.p); +} + +class Solution { + final int root1; + final int root2; + final bool isSquare; + + Solution(this.root1, this.root2, this.isSquare); +} + +int multiplyModulus(int a, int b, int modulus) { + a %= modulus; + b %= modulus; + if (b < a) { + var temp = a; + a = b; + b = temp; + } + + int result = 0; + while (a > 0) { + if (a % 2 == 1) { + result = (result + b) % modulus; + } + b = (b << 1) % modulus; + a >>= 1; + } + return result; +} + +int powerModulus(int base, int exponent, int modulus) { + if (modulus == 1) return 0; + + base %= modulus; + int result = 1; + while (exponent > 0) { + if ((exponent & 1) == 1) { + result = multiplyModulus(result, base, modulus); + } + base = multiplyModulus(base, base, modulus); + exponent >>= 1; + } + return result; +} + +int legendre(int a, int p) { + return powerModulus(a, (p - 1) ~/ 2, p); +} + +Solution tonelliShanks(int n, int p) { + if (legendre(n, p) != 1) { + return Solution(0, 0, false); + } + + // Factor out powers of 2 from p - 1 + int q = p - 1; + int s = 0; + while (q % 2 == 0) { + q ~/= 2; + s += 1; + } + + if (s == 1) { + int result = powerModulus(n, (p + 1) ~/ 4, p); + return Solution(result, p - result, true); + } + + // Find a non-square z such that (z | p) = -1 + int z = 2; + while (legendre(z, p) != p - 1) { + z += 1; + } + + int c = powerModulus(z, q, p); + int t = powerModulus(n, q, p); + int m = s; + int result = powerModulus(n, (q + 1) ~/ 2, p); + + while (t != 1) { + int i = 1; + int zTemp = multiplyModulus(t, t, p); + while (zTemp != 1 && i < m - 1) { + i += 1; + zTemp = multiplyModulus(zTemp, zTemp, p); + } + + int b = powerModulus(c, 1 << (m - i - 1), p); + c = multiplyModulus(b, b, p); + t = multiplyModulus(t, c, p); + m = i; + result = multiplyModulus(result, b, p); + } + + return Solution(result, p - result, true); +} + +void main() { + final List tests = [ + Pair(10, 13), + Pair(56, 101), + Pair(1030, 1009), + Pair(1032, 1009), + Pair(44402, 100049), + Pair(665820697, 1000000009), + Pair(881398088036, 1000000000039), + ]; + + for (final test in tests) { + final solution = tonelliShanks(test.n, test.p); + print('n = ${test.n}, p = ${test.p}'); + if (solution.isSquare) { + print('has solutions: ${solution.root1} and ${solution.root2}\n'); + } else { + print('has no solutions because n is not a square modulo p\n'); + } + } +} diff --git a/Task/Tonelli-Shanks-algorithm/Erlang/tonelli-shanks-algorithm.erl b/Task/Tonelli-Shanks-algorithm/Erlang/tonelli-shanks-algorithm.erl new file mode 100644 index 0000000000..cd0d9b4906 --- /dev/null +++ b/Task/Tonelli-Shanks-algorithm/Erlang/tonelli-shanks-algorithm.erl @@ -0,0 +1,113 @@ +-module(tonelli_shanks). +-export([tonelli/2, legendre/2, task/1, main/1]). + +%% Public API +tonelli(N, P) -> + case legendre(N, P) of + 1 -> + {Q, S} = decompose(P - 1, 0), + if + S =:= 1 -> + mod_pow(N, (P + 1) div 4, P); + S > 1 -> + Z = find_non_square(P), + C = mod_pow(Z, Q, P), + R = mod_pow(N, (Q + 1) div 2, P), + T = mod_pow(N, Q, P), + tonelli_loop(P, C, R, T, S) + end; + _ -> + error({not_a_square_mod_p, N, P}) + end. + +%% Tonelli-Shanks loop +tonelli_loop(P, _C, R, T, _M) when T =:= 1 -> + R; +tonelli_loop(P, C, R, T, M) -> + {T2, I} = find_least_i(T, 1, M, P), + B = mod_pow(C, mod_pow(2, M - I - 1, P - 1), P), + C1 = mod_mul(B, B, P), + R1 = mod_mul(R, B, P), + T1 = mod_mul(T, C1, P), + tonelli_loop(P, C1, R1, T1, I). + +%% Find smallest i such that t^(2^i) ≡ 1 mod p +find_least_i(T, I, M, P) when I < M -> + T2 = mod_mul(T, T, P), + if + T2 =:= 1 -> {T2, I}; + true -> find_least_i(T2, I + 1, M, P) + end; +find_least_i(_, _, _, _) -> + error(no_i_found). + +%% Legendre symbol: a^((p-1)/2) mod p +legendre(A, P) -> + mod_pow(A, (P - 1) div 2, P). + +%% Decompose p-1 = q * 2^s where q is odd +decompose(Q, S) when Q rem 2 =:= 0 -> + decompose(Q div 2, S + 1); +decompose(Q, S) -> + {Q, S}. + +%% Find a quadratic non-residue (Legendre = p - 1) +find_non_square(P) -> + find_non_square(2, P). + +find_non_square(Z, P) -> + case legendre(Z, P) of + L when L =:= P - 1 -> Z; + _ -> find_non_square(Z + 1, P) + end. + +%% Modular exponentiation: base^exp mod mod +mod_pow(Base, Exp, Mod) -> + mod_pow(Base, Exp, Mod, 1). + +mod_pow(_Base, 0, _Mod, Acc) -> + Acc; +mod_pow(Base, Exp, Mod, Acc) -> + Acc1 = case Exp rem 2 of + 1 -> (Acc * Base) rem Mod; + 0 -> Acc + end, + Base2 = (Base * Base) rem Mod, + mod_pow(Base2, Exp div 2, Mod, Acc1). + +%% Modular multiplication +mod_mul(A, B, Mod) -> + (A * B) rem Mod. + +%% Test cases +task(TestCases) -> + lists:foreach(fun([N, P]) -> + try + R = tonelli(N, P), + io:format("n = ~p p = ~p~n roots : ~p ~p~n", [N, P, R, P - R]) + catch + _:Error -> + io:format("Error for n=~p, p=~p: ~p~n", [N, P, Error]) + end + end, TestCases). + +main(_) -> + Cases = [ + [10, 13], + [56, 101], + [1030, 10009], + [44402, 100049], + [665820697, 1000000009], + [881398088036, 1000000000039], + [41660815127637347468140745042827704103445750172002, 100000000000000000000000000000000000000000000000577] + ], + task(Cases), + + % Test error case + try + tonelli(1032, 1009), + io:format("Error: Should have failed~n") + catch + _:Error -> + io:format("Correctly caught error: ~p~n", [Error]) + end. diff --git a/Task/Tonelli-Shanks-algorithm/JavaScript/tonelli-shanks-algorithm.js b/Task/Tonelli-Shanks-algorithm/JavaScript/tonelli-shanks-algorithm.js new file mode 100644 index 0000000000..86a4f90eec --- /dev/null +++ b/Task/Tonelli-Shanks-algorithm/JavaScript/tonelli-shanks-algorithm.js @@ -0,0 +1,113 @@ +class TonelliShanks { + static ts(n, p) { + // Convert to BigInt if not already + n = typeof n === 'bigint' ? n : BigInt(n); + p = typeof p === 'bigint' ? p : BigInt(p); + + const ZERO = BigInt(0); + const ONE = BigInt(1); + const TWO = BigInt(2); + + // Helper function for modular exponentiation + const powModP = (a, e) => { + let result = BigInt(1); + a = a % p; + while (e > ZERO) { + if (e % TWO === ONE) { + result = (result * a) % p; + } + e = e / TWO; + a = (a * a) % p; + } + return result; + }; + + // Legendre symbol calculation + const ls = (a) => powModP(a, (p - ONE) / TWO); + + if (ls(n) !== ONE) return { root1: ZERO, root2: ZERO, exists: false }; + + let q = p - ONE; + let ss = ZERO; + while (q % TWO === ZERO) { + ss += ONE; + q /= TWO; + } + + if (ss === ONE) { + const r1 = powModP(n, (p + ONE) / BigInt(4)); + return { root1: r1, root2: p - r1, exists: true }; + } + + let z = TWO; + while (ls(z) !== p - ONE) z += ONE; + + let c = powModP(z, q); + let r = powModP(n, (q + ONE) / TWO); + let t = powModP(n, q); + let m = ss; + + while (true) { + if (t === ONE) return { root1: r, root2: p - r, exists: true }; + + let i = ZERO; + let zz = t; + while (zz !== ONE && i < m - ONE) { + zz = (zz * zz) % p; + i += ONE; + } + + let b = c; + let e = m - i - ONE; + while (e > ZERO) { + b = (b * b) % p; + e -= ONE; + } + + r = (r * b) % p; + c = (b * b) % p; + t = (t * c) % p; + m = i; + } + } +} + +// Main function +function main() { + const pairs = [ + [10n, 13n], + [56n, 101n], + [1030n, 10009n], + [1032n, 10009n], + [44402n, 100049n], + [665820697n, 1000000009n], + [881398088036n, 1000000000039n] + ]; + + for (const [n, p] of pairs) { + const sol = TonelliShanks.ts(n, p); + console.log(`n = ${n}`); + console.log(`p = ${p}`); + if (sol.exists) { + console.log(`root1 = ${sol.root1}`); + console.log(`root2 = ${sol.root2}`); + } else { + console.log("No solution exists"); + } + console.log(); + } + + const bn = 41660815127637347468140745042827704103445750172002n; + const bp = BigInt(10) ** 50n + 577n; + const sol = TonelliShanks.ts(bn, bp); + console.log(`n = ${bn}`); + console.log(`p = ${bp}`); + if (sol.exists) { + console.log(`root1 = ${sol.root1}`); + console.log(`root2 = ${sol.root2}`); + } else { + console.log("No solution exists"); + } +} + +main(); diff --git a/Task/Tonelli-Shanks-algorithm/Julia/tonelli-shanks-algorithm-1.julia b/Task/Tonelli-Shanks-algorithm/Julia/tonelli-shanks-algorithm-1.jl similarity index 100% rename from Task/Tonelli-Shanks-algorithm/Julia/tonelli-shanks-algorithm-1.julia rename to Task/Tonelli-Shanks-algorithm/Julia/tonelli-shanks-algorithm-1.jl diff --git a/Task/Tonelli-Shanks-algorithm/Julia/tonelli-shanks-algorithm-2.julia b/Task/Tonelli-Shanks-algorithm/Julia/tonelli-shanks-algorithm-2.jl similarity index 100% rename from Task/Tonelli-Shanks-algorithm/Julia/tonelli-shanks-algorithm-2.julia rename to Task/Tonelli-Shanks-algorithm/Julia/tonelli-shanks-algorithm-2.jl diff --git a/Task/Tonelli-Shanks-algorithm/Kotlin/tonelli-shanks-algorithm.kotlin b/Task/Tonelli-Shanks-algorithm/Kotlin/tonelli-shanks-algorithm.kts similarity index 100% rename from Task/Tonelli-Shanks-algorithm/Kotlin/tonelli-shanks-algorithm.kotlin rename to Task/Tonelli-Shanks-algorithm/Kotlin/tonelli-shanks-algorithm.kts diff --git a/Task/Tonelli-Shanks-algorithm/Mathematica/tonelli-shanks-algorithm.math b/Task/Tonelli-Shanks-algorithm/Mathematica/tonelli-shanks-algorithm.math new file mode 100644 index 0000000000..3166ffb7df --- /dev/null +++ b/Task/Tonelli-Shanks-algorithm/Mathematica/tonelli-shanks-algorithm.math @@ -0,0 +1,67 @@ +(* Legendre symbol *) +LegendreSymbol[a_, p_] := PowerMod[a, (p - 1)/2, p] + +(* Tonelli-Shanks Algorithm *) +Tonelli[n_, p_] := Module[ + {q, s, z, c, r, t, m, t2, i, b}, + (* Check that n is a quadratic residue mod p *) + If[LegendreSymbol[n, p] =!= 1, + Message[Tonelli::notsquare, n, p]; Abort[]]; + + (* Step 1: Factor out powers of 2 from p - 1 *) + q = p - 1; + s = 0; + While[EvenQ[q], q = q/2; s++]; + + (* Special case when s == 1 *) + If[s == 1, + Return[PowerMod[n, (p + 1)/4, p]] + ]; + + (* Find a non-residue z *) + For[z = 2, z < p, z++, + If[LegendreSymbol[z, p] == p - 1, Break[]] + ]; + + (* Initialize variables *) + c = PowerMod[z, q, p]; + r = PowerMod[n, (q + 1)/2, p]; + t = PowerMod[n, q, p]; + m = s; + + (* Main loop *) + While[Mod[t - 1, p] =!= 0, + t2 = Mod[t^2, p]; + For[i = 1, i < m, i++, + If[Mod[t2 - 1, p] === 0, Break[]]; + t2 = Mod[t2^2, p]; + ]; + b = PowerMod[c, 2^(m - i - 1), p]; + r = Mod[r*b, p]; + c = Mod[b^2, p]; + t = Mod[t*c, p]; + m = i; + ]; + r +] + +(* Test cases *) +ttest = { + {10, 13}, + {56, 101}, + {1030, 10009}, + {44402, 100049}, + {665820697, 1000000009}, + {881398088036, 1000000000039}, + {41660815127637347468140745042827704103445750172002, 10^50 + 577} +}; + +Do[ + n = ttest[[i, 1]]; + p = ttest[[i, 2]]; + r = Tonelli[n, p]; + Assert[Mod[r^2 - n, p] == 0]; + Print["n = ", n, ", p = ", p]; + Print["\troots : ", r, " ", p - r], + {i, Length[ttest]} +] diff --git a/Task/Tonelli-Shanks-algorithm/OCaml/tonelli-shanks-algorithm.ocaml b/Task/Tonelli-Shanks-algorithm/OCaml/tonelli-shanks-algorithm.ml similarity index 100% rename from Task/Tonelli-Shanks-algorithm/OCaml/tonelli-shanks-algorithm.ocaml rename to Task/Tonelli-Shanks-algorithm/OCaml/tonelli-shanks-algorithm.ml diff --git a/Task/Tonelli-Shanks-algorithm/PARI-GP/tonelli-shanks-algorithm.parigp b/Task/Tonelli-Shanks-algorithm/PARI-GP/tonelli-shanks-algorithm.parigp new file mode 100644 index 0000000000..6408b9f0b7 --- /dev/null +++ b/Task/Tonelli-Shanks-algorithm/PARI-GP/tonelli-shanks-algorithm.parigp @@ -0,0 +1,123 @@ +/* Legendre symbol */ +legendresymbol(a, p) = +{ + lift(Mod(a, p)^((p-1)/2)); +} + +/* Tonelli-Shanks Algorithm */ +tonelli(n, p) = +{ + local(q, s, z, c, r, t, m, t2, i, b); + + /* Check that n is a quadratic residue mod p */ + if(legendresymbol(n, p) != 1, + error("n is not a quadratic residue mod p")); + + /* Step 1: Factor out powers of 2 from p - 1 */ + q = p - 1; + s = 0; + while(q % 2 == 0, + q = q/2; + s++ + ); + + /* Special case when s == 1 */ + if(s == 1, + return(lift(Mod(n, p)^((p+1)/4))) + ); + + /* Find a non-residue z */ + z = 2; + while(z < p, + if(legendresymbol(z, p) == p - 1, break()); + z++ + ); + + /* Initialize variables */ + c = lift(Mod(z, p)^q); + r = lift(Mod(n, p)^((q+1)/2)); + t = lift(Mod(n, p)^q); + m = s; + + /* Main loop */ + while((t - 1) % p != 0, + t2 = t^2 % p; + i = 1; + while(i < m, + if((t2 - 1) % p == 0, break()); + t2 = t2^2 % p; + i++ + ); + b = lift(Mod(c, p)^(2^(m - i - 1))); + r = (r * b) % p; + c = b^2 % p; + t = (t * c) % p; + m = i + ); + + return(r); +} + +/* Test the functions */ +print("Testing Tonelli-Shanks algorithm:"); +print(); + +/* Test case 1 */ +n = 10; p = 13; +r = tonelli(n, p); +print("n = ", n, ", p = ", p); +print("roots: ", r, ", ", p - r); +print("verification: ", r, "^2 mod ", p, " = ", r^2 % p); +print(); + +/* Test case 2 */ +n = 56; p = 101; +r = tonelli(n, p); +print("n = ", n, ", p = ", p); +print("roots: ", r, ", ", p - r); +print("verification: ", r, "^2 mod ", p, " = ", r^2 % p); +print(); + +/* Test case 3 */ +n = 1030; p = 10009; +r = tonelli(n, p); +print("n = ", n, ", p = ", p); +print("roots: ", r, ", ", p - r); +print("verification: ", r, "^2 mod ", p, " = ", r^2 % p); +print(); + + +/* Test case 4 */ +n = 44402; p = 100049; +r = tonelli(n, p); +print("n = ", n, ", p = ", p); +print("roots: ", r, ", ", p - r); +print("verification: ", r, "^2 mod ", p, " = ", r^2 % p); +print(); + + +/* Test case 5 */ +n = 665820697; p = 1000000009; +r = tonelli(n, p); +print("n = ", n, ", p = ", p); +print("roots: ", r, ", ", p - r); +print("verification: ", r, "^2 mod ", p, " = ", r^2 % p); +print(); + + +/* Test case 6 */ +n = 881398088036; p = 1000000000039; +r = tonelli(n, p); +print("n = ", n, ", p = ", p); +print("roots: ", r, ", ", p - r); +print("verification: ", r, "^2 mod ", p, " = ", r^2 % p); +print(); + + +/* Test case 7 */ +n = 41660815127637347468140745042827704103445750172002; p = 100000000000000000000000000000000000000000000000577; +r = tonelli(n, p); +print("n = ", n, ", p = ", p); +print("roots: ", r, ", ", p - r); +print("verification: ", r, "^2 mod ", p, " = ", r^2 % p); +print(); diff --git a/Task/Tonelli-Shanks-algorithm/PowerShell/tonelli-shanks-algorithm.psh b/Task/Tonelli-Shanks-algorithm/PowerShell/tonelli-shanks-algorithm.ps1 similarity index 100% rename from Task/Tonelli-Shanks-algorithm/PowerShell/tonelli-shanks-algorithm.psh rename to Task/Tonelli-Shanks-algorithm/PowerShell/tonelli-shanks-algorithm.ps1 diff --git a/Task/Tonelli-Shanks-algorithm/R/tonelli-shanks-algorithm.r b/Task/Tonelli-Shanks-algorithm/R/tonelli-shanks-algorithm.r new file mode 100644 index 0000000000..e8346a4564 --- /dev/null +++ b/Task/Tonelli-Shanks-algorithm/R/tonelli-shanks-algorithm.r @@ -0,0 +1,98 @@ +library(gmp) # For handling large integers and modular arithmetic + +# Legendre symbol: a^((p-1)/2) mod p +legendre <- function(a, p) { + a <- as.bigz(a) + p <- as.bigz(p) + e <- div.bigz(sub.bigz(p, 1), 2) + result <- powm(a, e, p) + return(result) +} + +# Tonelli-Shanks algorithm to find square root of n mod p +tonelli <- function(n, p) { + n <- as.bigz(n) + p <- as.bigz(p) + + # Check that n is a quadratic residue + leg <- legendre(n, p) + if (!identical(as.character(leg), "1")) { + stop("not a square (mod p)") + } + + q <- sub.bigz(p, 1) + s <- 0 + while (mod.bigz(q, 2) == 0) { + q <- div.bigz(q, 2) + s <- s + 1 + } + + if (s == 1) { + e <- div.bigz(add.bigz(p, 1), 4) + return(powm(n, e, p)) + } + + z <- as.bigz(2) + p_minus_1 <- sub.bigz(p, 1) + while (z < p) { + if (identical(as.character(legendre(z, p)), as.character(p_minus_1))) { + break + } + z <- add.bigz(z, 1) + } + + c <- powm(z, q, p) + r <- powm(n, div.bigz(add.bigz(q, 1), 2), p) + t <- powm(n, q, p) + m <- s + + one <- as.bigz(1) + two <- as.bigz(2) + + while (!identical(mod.bigz(sub.bigz(t, one), p), as.bigz(0))) { + t2 <- mod.bigz(mul.bigz(t, t), p) + i <- 1 + while (i < m) { + if (identical(mod.bigz(sub.bigz(t2, one), p), as.bigz(0))) { + break + } + t2 <- mod.bigz(mul.bigz(t2, t2), p) + i <- i + 1 + } + + b_exp <- pow.bigz(two, m - i - 1) + b <- powm(c, b_exp, p) + r <- mod.bigz(mul.bigz(r, b), p) + c <- mod.bigz(mul.bigz(b, b), p) + t <- mod.bigz(mul.bigz(t, c), p) + m <- i + } + + return(r) +} + +# Test cases +ttest <- list( + c("10", "13"), + c("56", "101"), + c("1030", "10009"), + c("44402", "100049"), + c("665820697", "1000000009"), + c("881398088036", "1000000000039"), + c("41660815127637347468140745042827704103445750172002", "100000000000000000000000000000000000000000000000577") +) + +for (case in ttest) { + n <- as.bigz(case[1]) + p <- as.bigz(case[2]) + r <- tonelli(n, p) + check <- mod.bigz(sub.bigz(mul.bigz(r, r), n), p) + + # Verify the result + if (!identical(as.character(check), "0")) { + stop("Verification failed") + } + + cat("n =", as.character(n), "p =", as.character(p), "\n") + cat("\troots :", as.character(r), as.character(sub.bigz(p, r)), "\n") +} diff --git a/Task/Tonelli-Shanks-algorithm/Rust/tonelli-shanks-algorithm.rs b/Task/Tonelli-Shanks-algorithm/Rust/tonelli-shanks-algorithm.rs new file mode 100644 index 0000000000..b35f2e502d --- /dev/null +++ b/Task/Tonelli-Shanks-algorithm/Rust/tonelli-shanks-algorithm.rs @@ -0,0 +1,120 @@ +struct Pair { + n: u64, + p: u64, +} + +struct Solution { + root1: u64, + root2: u64, + is_square: bool, +} + +fn multiply_modulus(a: u64, b: u64, modulus: u64) -> u64 { + let mut a = a % modulus; + let mut b = b % modulus; + + if b < a { + std::mem::swap(&mut a, &mut b); + } + + let mut result = 0; + while a > 0 { + if a % 2 == 1 { + result = (result + b) % modulus; + } + b = (b << 1) % modulus; + a >>= 1; + } + result +} + +fn power_modulus(base: u64, exponent: u64, modulus: u64) -> u64 { + if modulus == 1 { + return 0; + } + + let mut base = base % modulus; + let mut result = 1; + let mut exponent = exponent; + + while exponent > 0 { + if (exponent & 1) == 1 { + result = multiply_modulus(result, base, modulus); + } + base = multiply_modulus(base, base, modulus); + exponent >>= 1; + } + result +} + +fn legendre(a: u64, p: u64) -> u64 { + power_modulus(a, (p - 1) / 2, p) +} + +fn tonelli_shanks(n: u64, p: u64) -> Solution { + if legendre(n, p) != 1 { + return Solution { root1: 0, root2: 0, is_square: false }; + } + + // Factor out powers of 2 from p - 1 + let mut q = p - 1; + let mut s = 0; + while q % 2 == 0 { + q /= 2; + s += 1; + } + + if s == 1 { + let result = power_modulus(n, (p + 1) / 4, p); + return Solution { root1: result, root2: p - result, is_square: true }; + } + + // Find a non-square z such as ( z | p ) = -1 + let mut z = 2; + while legendre(z, p) != p - 1 { + z += 1; + } + + let mut c = power_modulus(z, q, p); + let mut t = power_modulus(n, q, p); + let mut m = s; + let mut result = power_modulus(n, (q + 1) >> 1, p); + + while t != 1 { + let mut i = 1; + let mut z = multiply_modulus(t, t, p); + while z != 1 && i < m - 1 { + i += 1; + z = multiply_modulus(z, z, p); + } + let b = power_modulus(c, 1 << (m - i - 1), p); + c = multiply_modulus(b, b, p); + t = multiply_modulus(t, c, p); + m = i; + result = multiply_modulus(result, b, p); + } + + Solution { root1: result, root2: p - result, is_square: true } +} + +fn main() { + let tests = vec![ + Pair { n: 10, p: 13 }, + Pair { n: 56, p: 101 }, + Pair { n: 1030, p: 1009 }, + Pair { n: 1032, p: 1009 }, + Pair { n: 44402, p: 100049 }, + Pair { n: 665820697, p: 1000000009 }, + Pair { n: 881398088036, p: 1000000000039 }, + ]; + + for test in tests { + let solution = tonelli_shanks(test.n, test.p); + print!("n = {}, p = {}", test.n, test.p); + if solution.is_square { + println!(" has solutions: {} and {}\n", solution.root1, solution.root2); + } else { + println!(" has no solutions because n is not a square modulo p\n"); + } + } +} diff --git a/Task/Tonelli-Shanks-algorithm/Scala/tonelli-shanks-algorithm.scala b/Task/Tonelli-Shanks-algorithm/Scala/tonelli-shanks-algorithm.scala new file mode 100644 index 0000000000..0d3550f865 --- /dev/null +++ b/Task/Tonelli-Shanks-algorithm/Scala/tonelli-shanks-algorithm.scala @@ -0,0 +1,106 @@ +import java.math.BigInteger +import scala.collection.immutable.List +import scala.annotation.tailrec + +object TonelliShanks { + private val ZERO = BigInteger.ZERO + private val ONE = BigInteger.ONE + private val TEN = BigInteger.TEN + private val TWO = BigInteger.valueOf(2) + private val FOUR = BigInteger.valueOf(4) + + private case class Solution(root1: BigInteger, root2: BigInteger, exists: Boolean) + + private def ts(n: Long, p: Long): Solution = ts(BigInteger.valueOf(n), BigInteger.valueOf(p)) + + private def ts(n: BigInteger, p: BigInteger): Solution = { + val powModP: (BigInteger, BigInteger) => BigInteger = (a, e) => a.modPow(e, p) + val ls: BigInteger => BigInteger = a => powModP(a, p.subtract(ONE).divide(TWO)) + + if (!ls(n).equals(ONE)) return Solution(ZERO, ZERO, false) + + var q = p.subtract(ONE) + var ss = ZERO + while (q.and(ONE).equals(ZERO)) { + ss = ss.add(ONE) + q = q.shiftRight(1) + } + + if (ss.equals(ONE)) { + val r1 = powModP(n, p.add(ONE).divide(FOUR)) + return Solution(r1, p.subtract(r1), true) + } + + var z = TWO + while (!ls(z).equals(p.subtract(ONE))) z = z.add(ONE) + var c = powModP(z, q) + var r = powModP(n, q.add(ONE).divide(TWO)) + var t = powModP(n, q) + var m = ss + + // Convert the while(true) loop to a tail-recursive function + @tailrec + def loop(r: BigInteger, c: BigInteger, t: BigInteger, m: BigInteger): Solution = { + if (t.equals(ONE)) { + Solution(r, p.subtract(r), true) + } else { + var i = ZERO + var zz = t + while (!zz.equals(BigInteger.ONE) && i.compareTo(m.subtract(ONE)) < 0) { + zz = zz.multiply(zz).mod(p) + i = i.add(ONE) + } + var b = c + var e = m.subtract(i).subtract(ONE) + while (e.compareTo(ZERO) > 0) { + b = b.multiply(b).mod(p) + e = e.subtract(ONE) + } + val newR = r.multiply(b).mod(p) + val newC = b.multiply(b).mod(p) + val newT = t.multiply(newC).mod(p) + val newM = i + loop(newR, newC, newT, newM) + } + } + + loop(r, c, t, m) + } + + def main(args: Array[String]): Unit = { + val pairs = List( + (10L, 13L), + (56L, 101L), + (1030L, 10009L), + (1032L, 10009L), + (44402L, 100049L), + (665820697L, 1000000009L), + (881398088036L, 1000000000039L) + ) + + for ((n, p) <- pairs) { + val sol = ts(n, p) + println(s"n = $n") + println(s"p = $p") + if (sol.exists) { + println(s"root1 = ${sol.root1}") + println(s"root2 = ${sol.root2}") + } else { + println("No solution exists") + } + println() + } + + val bn = new BigInteger("41660815127637347468140745042827704103445750172002") + val bp = TEN.pow(50).add(BigInteger.valueOf(577)) + val sol = ts(bn, bp) + println(s"n = $bn") + println(s"p = $bp") + if (sol.exists) { + println(s"root1 = ${sol.root1}") + println(s"root2 = ${sol.root2}") + } else { + println("No solution exists") + } + } +} diff --git a/Task/Tonelli-Shanks-algorithm/Swift/tonelli-shanks-algorithm.swift b/Task/Tonelli-Shanks-algorithm/Swift/tonelli-shanks-algorithm.swift new file mode 100644 index 0000000000..b48cf4aa4e --- /dev/null +++ b/Task/Tonelli-Shanks-algorithm/Swift/tonelli-shanks-algorithm.swift @@ -0,0 +1,120 @@ +import Foundation + +struct Pair { + let n: UInt64 + let p: UInt64 +} + +struct Solution { + let root1: UInt64 + let root2: UInt64 + let isSquare: Bool +} + +func multiplyModulus(_ a: UInt64, _ b: UInt64, modulus: UInt64) -> UInt64 { + var a = a % modulus + var b = b % modulus + + if b < a { + swap(&a, &b) + } + + var result: UInt64 = 0 + while a > 0 { + if a % 2 == 1 { + result = (result + b) % modulus + } + b = (b << 1) % modulus + a >>= 1 + } + return result +} + +func powerModulus(_ base: UInt64, _ exponent: UInt64, modulus: UInt64) -> UInt64 { + if modulus == 1 { + return 0 + } + + var base = base % modulus + var result: UInt64 = 1 + var exponent = exponent + + while exponent > 0 { + if (exponent & 1) == 1 { + result = multiplyModulus(result, base, modulus: modulus) + } + base = multiplyModulus(base, base, modulus: modulus) + exponent >>= 1 + } + return result +} + +func legendre(_ a: UInt64, _ p: UInt64) -> UInt64 { + return powerModulus(a, (p - 1) / 2, modulus: p) +} + +func tonelliShanks(_ n: UInt64, _ p: UInt64) -> Solution { + if legendre(n, p) != 1 { + return Solution(root1: 0, root2: 0, isSquare: false) + } + + // Factor out powers of 2 from p - 1 + var q = p - 1 + var s: UInt64 = 0 + while q % 2 == 0 { + q /= 2 + s += 1 + } + + if s == 1 { + let result = powerModulus(n, (p + 1) / 4, modulus: p) + return Solution(root1: result, root2: p - result, isSquare: true) + } + + // Find a non-square z such as ( z | p ) = -1 + var z: UInt64 = 2 + while legendre(z, p) != p - 1 { + z += 1 + } + + var c = powerModulus(z, q, modulus: p) + var t = powerModulus(n, q, modulus: p) + var m = s + var result = powerModulus(n, (q + 1) >> 1, modulus: p) + + while t != 1 { + var i: UInt64 = 1 + var z = multiplyModulus(t, t, modulus: p) + while z != 1 && i < m - 1 { + i += 1 + z = multiplyModulus(z, z, modulus: p) + } + let b = powerModulus(c, 1 << (m - i - 1), modulus: p) + c = multiplyModulus(b, b, modulus: p) + t = multiplyModulus(t, c, modulus: p) + m = i + result = multiplyModulus(result, b, modulus: p) + } + + return Solution(root1: result, root2: p - result, isSquare: true) +} + +let tests: [Pair] = [ + Pair(n: 10, p: 13), + Pair(n: 56, p: 101), + Pair(n: 1030, p: 1009), + Pair(n: 1032, p: 1009), + Pair(n: 44402, p: 100049), + Pair(n: 665820697, p: 1000000009), + Pair(n: 881398088036, p: 1000000000039) +] + +for test in tests { + let solution = tonelliShanks(test.n, test.p) + print("n = \(test.n), p = \(test.p)", terminator: "") + if solution.isSquare { + print(" has solutions: \(solution.root1) and \(solution.root2)\n") + } else { + print(" has no solutions because n is not a square modulo p\n") + } +} diff --git a/Task/Tonelli-Shanks-algorithm/Zig/tonelli-shanks-algorithm.zig b/Task/Tonelli-Shanks-algorithm/Zig/tonelli-shanks-algorithm.zig new file mode 100644 index 0000000000..61cb26bb3e --- /dev/null +++ b/Task/Tonelli-Shanks-algorithm/Zig/tonelli-shanks-algorithm.zig @@ -0,0 +1,128 @@ +const std = @import("std"); +const stdout = std.io.getStdOut().writer(); + +const Pair = struct { + n: u64, + p: u64, +}; + +const Solution = struct { + root1: u64, + root2: u64, + is_square: bool, +}; + +fn multiplyModulus(a: u64, b: u64, modulus: u64) u64 { + var a_mod = a % modulus; + var b_mod = b % modulus; + + if (b_mod < a_mod) { + const temp = a_mod; + a_mod = b_mod; + b_mod = temp; + } + + var result: u64 = 0; + var a_temp = a_mod; + var b_temp = b_mod; + + while (a_temp > 0) { + if (a_temp % 2 == 1) { + result = (result + b_temp) % modulus; + } + b_temp = (b_temp << 1) % modulus; + a_temp >>= 1; + } + return result; +} + +fn powerModulus(base: u64, exponent: u64, modulus: u64) u64 { + if (modulus == 1) { + return 0; + } + + var base_mod = base % modulus; + var result: u64 = 1; + var exp = exponent; + + while (exp > 0) { + if ((exp & 1) == 1) { + result = multiplyModulus(result, base_mod, modulus); + } + base_mod = multiplyModulus(base_mod, base_mod, modulus); + exp >>= 1; + } + return result; +} + +fn legendre(a: u64, p: u64) u64 { + return powerModulus(a, (p - 1) / 2, p); +} + +fn tonelliShanks(n: u64, p: u64) Solution { + if (legendre(n, p) != 1) { + return Solution{ .root1 = 0, .root2 = 0, .is_square = false }; + } + + // Factor out powers of 2 from p - 1 + var q = p - 1; + var s: u64 = 0; + while (q % 2 == 0) { + q /= 2; + s += 1; + } + + if (s == 1) { + const result = powerModulus(n, (p + 1) / 4, p); + return Solution{ .root1 = result, .root2 = p - result, .is_square = true }; + } + + // Find a non-square z such as ( z | p ) = -1 + var z: u64 = 2; + while (legendre(z, p) != p - 1) { + z += 1; + } + + var c = powerModulus(z, q, p); + var t = powerModulus(n, q, p); + var m = s; + var result = powerModulus(n, (q + 1) >> 1, p); + + while (t != 1) { + var i: u64 = 1; + var z_temp = multiplyModulus(t, t, p); + while (z_temp != 1 and i < m - 1) { + i += 1; + z_temp = multiplyModulus(z_temp, z_temp, p); + } + const b = powerModulus(c, @as(u64, 1) << @as( u6, @intCast(m - i - 1)), p); + c = multiplyModulus(b, b, p); + t = multiplyModulus(t, c, p); + m = i; + result = multiplyModulus(result, b, p); + } + + return Solution{ .root1 = result, .root2 = p - result, .is_square = true }; +} + +pub fn main() !void { + const tests = [_]Pair{ + .{ .n = 10, .p = 13 }, + .{ .n = 56, .p = 101 }, + .{ .n = 1030, .p = 1009 }, + .{ .n = 1032, .p = 1009 }, + .{ .n = 44402, .p = 100049 }, + .{ .n = 665820697, .p = 1000000009 }, + .{ .n = 881398088036, .p = 1000000000039 }, + }; + + for (tests) |my_test| { + const solution = tonelliShanks(my_test.n, my_test.p); + try stdout.print("n = {}, p = {}", .{ my_test.n, my_test.p }); + if (solution.is_square) { + try stdout.print(" has solutions: {} and {}\n\n", .{ solution.root1, solution.root2 }); + } else { + try stdout.print(" has no solutions because n is not a square modulo p\n\n", .{}); + } + } +} diff --git a/Task/Top-rank-per-group/Ada/top-rank-per-group.ada b/Task/Top-rank-per-group/Ada/top-rank-per-group.adb similarity index 100% rename from Task/Top-rank-per-group/Ada/top-rank-per-group.ada rename to Task/Top-rank-per-group/Ada/top-rank-per-group.adb diff --git a/Task/Top-rank-per-group/Delphi/top-rank-per-group.delphi b/Task/Top-rank-per-group/Delphi/top-rank-per-group.pas similarity index 100% rename from Task/Top-rank-per-group/Delphi/top-rank-per-group.delphi rename to Task/Top-rank-per-group/Delphi/top-rank-per-group.pas diff --git a/Task/Top-rank-per-group/DuckDB/top-rank-per-group-1.duckdb b/Task/Top-rank-per-group/DuckDB/top-rank-per-group-1.duckdb new file mode 100644 index 0000000000..74de517b71 --- /dev/null +++ b/Task/Top-rank-per-group/DuckDB/top-rank-per-group-1.duckdb @@ -0,0 +1,14 @@ +create or replace table EMP as + from read_csv_auto('input.csv'); + +create or replace function rank_by_department(number) as table ( + with cte as ( + SELECT *, row_number() OVER (PARTITION BY Department ORDER BY salary desc) as rank + FROM EMP + ) + select * from cte + where rank <= number + order by Department, Salary DESC +); + +from rank_by_department(3); diff --git a/Task/Top-rank-per-group/DuckDB/top-rank-per-group-2.duckdb b/Task/Top-rank-per-group/DuckDB/top-rank-per-group-2.duckdb new file mode 100644 index 0000000000..bf547de47d --- /dev/null +++ b/Task/Top-rank-per-group/DuckDB/top-rank-per-group-2.duckdb @@ -0,0 +1,6 @@ +create or replace table EMP ( + EMP_ID varchar(6), + EMP_NAME varchar(20), + DEPT_ID varchar(4), + SALARY decimal(10,2) +); diff --git a/Task/Top-rank-per-group/DuckDB/top-rank-per-group-3.duckdb b/Task/Top-rank-per-group/DuckDB/top-rank-per-group-3.duckdb new file mode 100644 index 0000000000..949b90bfca --- /dev/null +++ b/Task/Top-rank-per-group/DuckDB/top-rank-per-group-3.duckdb @@ -0,0 +1,3 @@ +create or replace function to_char(s,f) as ( + format('{:9.2f}', s) +); diff --git a/Task/Top-rank-per-group/EasyLang/top-rank-per-group.easy b/Task/Top-rank-per-group/EasyLang/top-rank-per-group.easy new file mode 100644 index 0000000000..fba201626a --- /dev/null +++ b/Task/Top-rank-per-group/EasyLang/top-rank-per-group.easy @@ -0,0 +1,58 @@ +global na$[] id$[] sal[] dep$[] n . +# +proc read . + s$ = input + repeat + s$ = input + until s$ = "" + a$[] = strsplit s$ "," + na$[] &= a$[1] + id$[] &= a$[2] + sal[] &= number a$[3] + dep$[] &= a$[4] + . + n = len na$[] +. +read +# +proc sort . + for i = 1 to n - 1 + for j = i + 1 to n + h = strcmp dep$[i] dep$[j] + if h > 0 or h = 0 and sal[i] < sal[j] + swap na$[i] na$[j] + swap id$[i] id$[j] + swap sal[i] sal[j] + swap dep$[i] dep$[j] + . + . + . +. +sort +# +for i to n + if i > 1 and dep$[i] <> dep$[i - 1] + cnt = 0 + print "" + . + if cnt < 2 + print dep$[i] & " " & sal[i] & " " & na$[i] + cnt += 1 + . +. +# +input_data +Employee Name,Employee ID,Salary,Department +Tyler Bennett,E10297,32000,D101 +John Rappl,E21437,47000,D050 +George Woltman,E00127,53500,D101 +Adam Smith,E63535,18000,D202 +Claire Buckman,E39876,27800,D202 +David McClellan,E04242,41500,D101 +Rich Holcomb,E01234,49500,D202 +Nathan Adams,E41298,21900,D050 +Richard Potter,E43128,15900,D101 +David Motsinger,E27002,19250,D202 +Tim Sampair,E03033,27000,D101 +Kim Arlich,E10001,57000,D190 +Timothy Grove,E16398,29900,D190 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 6ca23c9ef6..498737638b 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 @@ -33,7 +33,7 @@ extension reportOp }; } -public program() +public Program() { var employees := new Employee[] { @@ -54,12 +54,12 @@ public program() employees.topNPerDepartment(2).forEach::(info) { - console.printLine("Department: ",info.Department); + Console.printLine("Department: ",info.Department); - info.Employees.forEach(printingLn); + info.Employees.forEach(PrintingLn); - console.writeLine("---------------------------------------------") + Console.writeLine("---------------------------------------------") }; - console.readChar() + Console.readChar() } diff --git a/Task/Top-rank-per-group/Elixir/top-rank-per-group.elixir b/Task/Top-rank-per-group/Elixir/top-rank-per-group.ex similarity index 100% rename from Task/Top-rank-per-group/Elixir/top-rank-per-group.elixir rename to Task/Top-rank-per-group/Elixir/top-rank-per-group.ex diff --git a/Task/Top-rank-per-group/Julia/top-rank-per-group.julia b/Task/Top-rank-per-group/Julia/top-rank-per-group.jl similarity index 100% rename from Task/Top-rank-per-group/Julia/top-rank-per-group.julia rename to Task/Top-rank-per-group/Julia/top-rank-per-group.jl diff --git a/Task/Top-rank-per-group/Kotlin/top-rank-per-group.kotlin b/Task/Top-rank-per-group/Kotlin/top-rank-per-group.kts similarity index 100% rename from Task/Top-rank-per-group/Kotlin/top-rank-per-group.kotlin rename to Task/Top-rank-per-group/Kotlin/top-rank-per-group.kts diff --git a/Task/Top-rank-per-group/OCaml/top-rank-per-group.ocaml b/Task/Top-rank-per-group/OCaml/top-rank-per-group.ml similarity index 100% rename from Task/Top-rank-per-group/OCaml/top-rank-per-group.ocaml rename to Task/Top-rank-per-group/OCaml/top-rank-per-group.ml diff --git a/Task/Top-rank-per-group/PascalABC.NET/top-rank-per-group.pas b/Task/Top-rank-per-group/PascalABC.NET/top-rank-per-group.pas new file mode 100644 index 0000000000..e717892e08 --- /dev/null +++ b/Task/Top-rank-per-group/PascalABC.NET/top-rank-per-group.pas @@ -0,0 +1,25 @@ +begin + var data := |('Tyler Bennett', 'E10297', 32000, 'D101'), + ('John Rappl', 'E21437', 47000, 'D050'), + ('George Woltman', 'E00127', 53500, 'D101'), + ('Adam Smith', 'E63535', 18000, 'D202'), + ('Claire Buckman', 'E39876', 27800, 'D202'), + ('David McClellan', 'E04242', 41500, 'D101'), + ('Rich Holcomb', 'E01234', 49500, 'D202'), + ('Nathan Adams', 'E41298', 21900, 'D050'), + ('Richard Potter', 'E43128', 15900, 'D101'), + ('David Motsinger', 'E27002', 19250, 'D202'), + ('Tim Sampair', 'E03033', 27000, 'D101'), + ('Kim Arlich', 'E10001', 57000, 'D190'), + ('Timothy Grove', 'E16398', 29900, 'D190')|; + + var N := 3; + foreach var group in data.GroupBy(rec -> rec[3]).OrderBy(gr -> gr.Key) do + begin + Println('Department',group.Key); + Println($' Employee Name Employee ID Salary'); + foreach var rec in group.OrderByDescending(x -> x[2]).Take(3) do + Println($' {rec[0],-18} {rec[1],-14} {rec[2]}'); + Println; + end; +end. diff --git a/Task/Top-rank-per-group/Pluto/top-rank-per-group.pluto b/Task/Top-rank-per-group/Pluto/top-rank-per-group.pluto new file mode 100644 index 0000000000..aec2381ebb --- /dev/null +++ b/Task/Top-rank-per-group/Pluto/top-rank-per-group.pluto @@ -0,0 +1,39 @@ +require "table2" +local fmt = require "fmt" + +class employee + function __construct(public name, public id, public salary, public dept) end +end + +local N = 2 -- say + +local employees = { + new employee("Tyler Bennett", "E10297", 32000, "D101"), + new employee("John Rappl", "E21437", 47000, "D050"), + new employee("George Woltman" , "E00127", 53500, "D101"), + new employee("Adam Smith", "E63535", 18000, "D202"), + new employee("Claire Buckman", "E39876", 27800, "D202"), + new employee("David McClellan", "E04242", 41500, "D101"), + new employee("Rich Holcomb", "E01234", 49500, "D202"), + new employee("Nathan Adams", "E41298", 21900, "D050"), + new employee("Richard Potter", "E43128", 15900, "D101"), + new employee("David Motsinger", "E27002", 19250, "D202"), + new employee("Tim Sampair", "E03033", 27000, "D101"), + new employee("Kim Arlich", "E10001", 57000, "D190"), + new employee("Timothy Grove", "E16398", 29900, "D190") +} + +local groups_by_dept = employees:groupby(|e| -> e.dept) +local sorted_depts = groups_by_dept:keys():sort() +print($"Highest {N} salaries by department:\n") +for sorted_depts as dept do + print($"Dept {dept} => ") + local dept_employees = groups_by_dept[dept] + local by_salary_desc = |employee1, employee2| -> employee2.salary < employee1.salary + dept_employees:sort(by_salary_desc) + for i = 1, math.min(N, #dept_employees) do + local e = dept_employees[i] + fmt.print("%-15s %s %d", e.name, e.id, e.salary) + end + print() +end diff --git a/Task/Top-rank-per-group/PowerShell/top-rank-per-group.psh b/Task/Top-rank-per-group/PowerShell/top-rank-per-group.ps1 similarity index 100% rename from Task/Top-rank-per-group/PowerShell/top-rank-per-group.psh rename to Task/Top-rank-per-group/PowerShell/top-rank-per-group.ps1 diff --git a/Task/Top-rank-per-group/Rust/top-rank-per-group.rust b/Task/Top-rank-per-group/Rust/top-rank-per-group.rs similarity index 100% rename from Task/Top-rank-per-group/Rust/top-rank-per-group.rust rename to Task/Top-rank-per-group/Rust/top-rank-per-group.rs diff --git a/Task/Top-rank-per-group/Scheme/top-rank-per-group.ss b/Task/Top-rank-per-group/Scheme/top-rank-per-group-1.scm similarity index 100% rename from Task/Top-rank-per-group/Scheme/top-rank-per-group.ss rename to Task/Top-rank-per-group/Scheme/top-rank-per-group-1.scm diff --git a/Task/Top-rank-per-group/Scheme/top-rank-per-group-2.scm b/Task/Top-rank-per-group/Scheme/top-rank-per-group-2.scm new file mode 100644 index 0000000000..a0bcc4a366 --- /dev/null +++ b/Task/Top-rank-per-group/Scheme/top-rank-per-group-2.scm @@ -0,0 +1,72 @@ +(use srfi-197) ;; chain +(use gauche.collection) + +(define .salary (cut list-ref <> 2)) +(define .dept last) + +(define employee-data + (chain '(("Tyler Bennett" E10297 32000 D101) + ("John Rappl" E21437 47000 D050) + ("George Woltman" E00127 53500 D101) + ("Adam Smith" E63535 18000 D202) + ("Claire Buckman" E39876 27800 D202) + ("David McClellan" E04242 41500 D101) + ("Rich Holcomb" E01234 49500 D202) + ("Nathan Adams" E41298 21900 D050) + ("Richard Potter" E43128 15900 D101) + ("David Motsinger" E27002 19250 D202) + ("Tim Sampair" E03033 27000 D101) + ("Kim Arlich" E10001 57000 D190) + ("Timothy Grove" E16398 29900 D190)) + (group-collection _ :key .dept) + (map (^d (sort d > .salary)) _))) + +(define (foo n) + (dolist (dept employee-data) + (print (.dept (car dept))) + (for-each + (^e (apply format #t " ~15a ~a ~a\n" (take e 3))) + (take* dept n)) + (print))) + +(foo 2) + +D101 + George Woltman E00127 53500 + David McClellan E04242 41500 + +D050 + John Rappl E21437 47000 + Nathan Adams E41298 21900 + +D202 + Rich Holcomb E01234 49500 + Claire Buckman E39876 27800 + +D190 + Kim Arlich E10001 57000 + Timothy Grove E16398 29900 + + +(foo 8000) + +D101 + George Woltman E00127 53500 + David McClellan E04242 41500 + Tyler Bennett E10297 32000 + Tim Sampair E03033 27000 + Richard Potter E43128 15900 + +D050 + John Rappl E21437 47000 + Nathan Adams E41298 21900 + +D202 + Rich Holcomb E01234 49500 + Claire Buckman E39876 27800 + David Motsinger E27002 19250 + Adam Smith E63535 18000 + +D190 + Kim Arlich E10001 57000 + Timothy Grove E16398 29900 diff --git a/Task/Top-rank-per-group/Scheme/top-rank-per-group-3.scm b/Task/Top-rank-per-group/Scheme/top-rank-per-group-3.scm new file mode 100644 index 0000000000..004f707cee --- /dev/null +++ b/Task/Top-rank-per-group/Scheme/top-rank-per-group-3.scm @@ -0,0 +1,64 @@ +(define-syntax ainc! + (syntax-rules () + [(_ alist key val func default) + (let ((pair (assoc key alist))) + (if pair + (set-cdr! pair (func val (cdr pair))) + (set! alist (cons (cons key (func val default)) alist))))] + [(_ alist key val func) + (ainc! alist key val func 0)] + [(_ alist key val) + (ainc! alist key val +)] + [(_ alist key) + (ainc! alist key 1)])) + +(define .salary (cut list-ref <> 2)) +(define .dept last) + +(define employee-data + '(("Tyler Bennett" E10297 32000 D101) + ("John Rappl" E21437 47000 D050) + ("George Woltman" E00127 53500 D101) + ("Adam Smith" E63535 18000 D202) + ("Claire Buckman" E39876 27800 D202) + ("David McClellan" E04242 41500 D101) + ("Rich Holcomb" E01234 49500 D202) + ("Nathan Adams" E41298 21900 D050) + ("Richard Potter" E43128 15900 D101) + ("David Motsinger" E27002 19250 D202) + ("Tim Sampair" E03033 27000 D101) + ("Kim Arlich" E10001 57000 D190) + ("Timothy Grove" E16398 29900 D190))) + +(define (top-salaries n) + (let ((table '())) + (dolist (e employee-data) + (ainc! table + (.dept e) + (list e) + (lambda(new old) (merge new old > .salary)) + '())) + (dolist (dept table) + (print (car dept)) + (for-each + (^e (apply format #t " ~15a ~a ~a\n" (take e 3))) + (take* (cdr dept) n)) + (print)))) + +(top-salaries 2) + +D190 + Kim Arlich E10001 57000 + Timothy Grove E16398 29900 + +D202 + Rich Holcomb E01234 49500 + Claire Buckman E39876 27800 + +D050 + John Rappl E21437 47000 + Nathan Adams E41298 21900 + +D101 + George Woltman E00127 53500 + David McClellan E04242 41500 diff --git a/Task/Topic-variable/Java/topic-variable.java b/Task/Topic-variable/Java/topic-variable.java new file mode 100644 index 0000000000..ddd2465093 --- /dev/null +++ b/Task/Topic-variable/Java/topic-variable.java @@ -0,0 +1,42 @@ +import java.awt.Point; +import java.util.ArrayDeque; +import java.util.List; +import java.util.Queue; + +public final class TopicVariable { + + public static void main(String[] args) { + List numbers = List.of( 1, 2, 3, 4, 5, 6, 7, 8, 9 ); + // Example 1: + // We only want to count the number of elements in a list, + // so a topic variable can be used for the identify of each element of the list. + // An artificial example since we could just use 'total = numbers.size()'. + int total = 0; + for ( Integer _ : numbers ) { // Topic variable + total += 1; + } + System.out.println("The list contains " + total + " numbers"); + + // Example 2: + // A topic variable is suitable for the unused identifier of the NumberFormatException. + String text = "123456:@~"; + int i = 0; + try { + i = Integer.parseInt(text); + } catch(NumberFormatException _) { // Topic variable + System.out.println("Variable i is incorrectly defined with value: " + i); + } + + // Example 3: + // We only require the first two out of every three items in a queue. + // A topic variable can be used for the third unused item. + Queue queue = new ArrayDeque(numbers); + while ( queue.size() >= 3 ) { + int x = queue.poll(); + int y = queue.poll(); + int _ = queue.poll(); // Topic variable + System.out.println( new Point(x, y) ); + } + } + +} diff --git a/Task/Topic-variable/Julia/topic-variable.julia b/Task/Topic-variable/Julia/topic-variable.jl similarity index 100% rename from Task/Topic-variable/Julia/topic-variable.julia rename to Task/Topic-variable/Julia/topic-variable.jl diff --git a/Task/Topic-variable/Kotlin/topic-variable.kotlin b/Task/Topic-variable/Kotlin/topic-variable.kts similarity index 100% rename from Task/Topic-variable/Kotlin/topic-variable.kotlin rename to Task/Topic-variable/Kotlin/topic-variable.kts diff --git a/Task/Topic-variable/LOLCODE/topic-variable.lol b/Task/Topic-variable/LOLCODE/topic-variable.lol new file mode 100644 index 0000000000..b15759dd3b --- /dev/null +++ b/Task/Topic-variable/LOLCODE/topic-variable.lol @@ -0,0 +1,6 @@ +HAI 1.3 + +3 +VISIBLE PRODUKT OF IT AN IT + +KTHXBYE diff --git a/Task/Topic-variable/Maxima/topic-variable.maxima b/Task/Topic-variable/Maxima/topic-variable.maxima new file mode 100644 index 0000000000..74c018bb72 --- /dev/null +++ b/Task/Topic-variable/Maxima/topic-variable.maxima @@ -0,0 +1,9 @@ +3; /* % won't work if $ is used instead of ; */ +[%^2, sqrt(%)]; + +3$ /* _ works with $ or ; */ +[_^2, sqrt(_)]; + +block(x: 3, [%%^2, sqrt(%%)]); + +__+3; /* __ only evaluates itself once to avoid infinite loops */ diff --git a/Task/Topic-variable/PowerShell/topic-variable-1.psh b/Task/Topic-variable/PowerShell/topic-variable-1.ps1 similarity index 100% rename from Task/Topic-variable/PowerShell/topic-variable-1.psh rename to Task/Topic-variable/PowerShell/topic-variable-1.ps1 diff --git a/Task/Topic-variable/PowerShell/topic-variable-2.psh b/Task/Topic-variable/PowerShell/topic-variable-2.ps1 similarity index 100% rename from Task/Topic-variable/PowerShell/topic-variable-2.psh rename to Task/Topic-variable/PowerShell/topic-variable-2.ps1 diff --git a/Task/Topic-variable/PowerShell/topic-variable-3.psh b/Task/Topic-variable/PowerShell/topic-variable-3.ps1 similarity index 100% rename from Task/Topic-variable/PowerShell/topic-variable-3.psh rename to Task/Topic-variable/PowerShell/topic-variable-3.ps1 diff --git a/Task/Topic-variable/V-(Vlang)/topic-variable-1.v b/Task/Topic-variable/V-(Vlang)/topic-variable-1.v new file mode 100644 index 0000000000..a8e2d8dfd3 --- /dev/null +++ b/Task/Topic-variable/V-(Vlang)/topic-variable-1.v @@ -0,0 +1,9 @@ +// function that returns multiple values +fn foo() (int, int) { + return 2, 3 +} + +mut a, mut b := foo() +println("${a} and ${b}") +a, _ = foo() // to ignore particular returned values, the `_` is used +println(a) diff --git a/Task/Topic-variable/V-(Vlang)/topic-variable-2.v b/Task/Topic-variable/V-(Vlang)/topic-variable-2.v new file mode 100644 index 0000000000..491c68cbcf --- /dev/null +++ b/Task/Topic-variable/V-(Vlang)/topic-variable-2.v @@ -0,0 +1,9 @@ +// ignore values, while iterating over keys +m := { + 'one': 1 + 'two': 2 +} + +for key, _ in m { + println(key) +} diff --git a/Task/Topic-variable/V-(Vlang)/topic-variable-3.v b/Task/Topic-variable/V-(Vlang)/topic-variable-3.v new file mode 100644 index 0000000000..4dd7ac90f9 --- /dev/null +++ b/Task/Topic-variable/V-(Vlang)/topic-variable-3.v @@ -0,0 +1,4 @@ +// "it", used in filter and map +words := ['hello', 'world'] +upper := words.map(it.to_upper()) +println(upper) diff --git a/Task/Topological-sort/Ada/topological-sort-1.ada b/Task/Topological-sort/Ada/topological-sort-1.adb similarity index 100% rename from Task/Topological-sort/Ada/topological-sort-1.ada rename to Task/Topological-sort/Ada/topological-sort-1.adb diff --git a/Task/Topological-sort/Ada/topological-sort-2.ada b/Task/Topological-sort/Ada/topological-sort-2.adb similarity index 100% rename from Task/Topological-sort/Ada/topological-sort-2.ada rename to Task/Topological-sort/Ada/topological-sort-2.adb diff --git a/Task/Topological-sort/Ada/topological-sort-3.ada b/Task/Topological-sort/Ada/topological-sort-3.adb similarity index 100% rename from Task/Topological-sort/Ada/topological-sort-3.ada rename to Task/Topological-sort/Ada/topological-sort-3.adb diff --git a/Task/Topological-sort/Ada/topological-sort-4.ada b/Task/Topological-sort/Ada/topological-sort-4.adb similarity index 100% rename from Task/Topological-sort/Ada/topological-sort-4.ada rename to Task/Topological-sort/Ada/topological-sort-4.adb diff --git a/Task/Topological-sort/Ada/topological-sort-5.ada b/Task/Topological-sort/Ada/topological-sort-5.adb similarity index 100% rename from Task/Topological-sort/Ada/topological-sort-5.ada rename to Task/Topological-sort/Ada/topological-sort-5.adb diff --git a/Task/Topological-sort/Crystal/topological-sort.crystal b/Task/Topological-sort/Crystal/topological-sort.cr similarity index 100% rename from Task/Topological-sort/Crystal/topological-sort.crystal rename to Task/Topological-sort/Crystal/topological-sort.cr diff --git a/Task/Topological-sort/Dart/topological-sort.dart b/Task/Topological-sort/Dart/topological-sort.dart new file mode 100644 index 0000000000..d8c6b264ab --- /dev/null +++ b/Task/Topological-sort/Dart/topological-sort.dart @@ -0,0 +1,179 @@ +import 'dart:io'; + +class Relations { + int dependencies = 0; + Set dependents = {}; +} + +class TopologicalSorter { + Map> _map = >{}; + + void addGoal(T goal) { + _map.putIfAbsent(goal, () => Relations()); + } + + void addDependency(T goal, T dependency) { + if (dependency == goal) return; + + var dependencyRelations = _map.putIfAbsent(dependency, () => Relations()); + var goalRelations = _map.putIfAbsent(goal, () => Relations()); + + if (!dependencyRelations.dependents.contains(goal)) { + dependencyRelations.dependents.add(goal); + goalRelations.dependencies++; + } + } + + void addDependencies(T goal, Iterable dependencies) { + for (var dependency in dependencies) { + addDependency(goal, dependency); + } + } + + void destructiveSort(List sorted, List unsortable) { + sorted.clear(); + unsortable.clear(); + + // Find all goals with no dependencies + for (var entry in _map.entries) { + var goal = entry.key; + var relations = entry.value; + if (relations.dependencies == 0) { + sorted.add(goal); + } + } + + // Process goals in topological order + for (int index = 0; index < sorted.length; index++) { + var currentGoal = sorted[index]; + var currentRelations = _map[currentGoal]!; + + for (var dependentGoal in currentRelations.dependents) { + var dependentRelations = _map[dependentGoal]!; + dependentRelations.dependencies--; + if (dependentRelations.dependencies == 0) { + sorted.add(dependentGoal); + } + } + } + + // Find cyclic dependencies + for (var entry in _map.entries) { + var goal = entry.key; + var relations = entry.value; + if (relations.dependencies != 0) { + unsortable.add(goal); + } + } + } + + void sort(List sorted, List unsortable) { + var temporary = TopologicalSorter(); + + // Deep copy the current state + for (var entry in _map.entries) { + var goal = entry.key; + var relations = entry.value; + temporary.addGoal(goal); + temporary._map[goal]!.dependencies = relations.dependencies; + temporary._map[goal]!.dependents = Set.from(relations.dependents); + } + + temporary.destructiveSort(sorted, unsortable); + } + + void clear() { + _map.clear(); + } +} + +void displayHeading(String message) { + print('\n~ $message ~'); +} + +void displayResults(String input) { + var sorter = TopologicalSorter(); + var sorted = []; + var unsortable = []; + + var lines = input.trim().split('\n'); + for (var line in lines) { + if (line.trim().isEmpty) continue; + + var parts = line.trim().split(RegExp(r'\s+')); + if (parts.isEmpty) continue; + + var goal = parts[0]; + sorter.addGoal(goal); + + for (int i = 1; i < parts.length; i++) { + sorter.addDependency(goal, parts[i]); + } + } + + sorter.destructiveSort(sorted, unsortable); + + if (sorted.isEmpty) { + displayHeading("Error: no independent variables found!"); + } else { + displayHeading("Result"); + for (var goal in sorted) { + print(goal); + } + } + + if (unsortable.isNotEmpty) { + displayHeading("Error: cyclic dependencies detected!"); + for (var goal in unsortable) { + print(goal); + } + } +} + +void main(List arguments) { + if (arguments.isEmpty) { + var example = '''des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee +dw01 ieee dw01 dware gtech +dw02 ieee dw02 dware +dw03 std synopsys dware dw03 dw02 dw01 ieee gtech +dw04 dw04 ieee dw01 dware gtech +dw05 dw05 ieee dware +dw06 dw06 ieee dware +dw07 ieee dware +dware ieee dware +gtech ieee gtech +ramlib std ieee +std_cell_lib ieee std_cell_lib +synopsys +cycle_11 cycle_12 +cycle_12 cycle_11 +cycle_21 dw01 cycle_22 dw02 dw03 +cycle_22 cycle_21 dw01 dw04'''; + + displayHeading("Example: each line starts with a goal followed by its dependencies"); + print(example); + displayResults(example); + + displayHeading("Enter lines of data (press enter when finished)"); + var lines = []; + while (true) { + var line = stdin.readLineSync(); + if (line == null || line.isEmpty) break; + lines.add(line); + } + + if (lines.isNotEmpty) { + displayResults(lines.join('\n')); + } + } else { + for (var filename in arguments) { + try { + var file = File(filename); + var content = file.readAsStringSync(); + displayResults(content); + } catch (e) { + print('Error reading file $filename: $e'); + } + } + } +} diff --git a/Task/Topological-sort/EasyLang/topological-sort.easy b/Task/Topological-sort/EasyLang/topological-sort.easy new file mode 100644 index 0000000000..ab631a2afe --- /dev/null +++ b/Task/Topological-sort/EasyLang/topological-sort.easy @@ -0,0 +1,66 @@ +global name$[] g[][] . +func n2id n$ . + for id to len name$[] : if name$[id] = n$ : return id + name$[] &= n$ + return id +. +proc init . + repeat + s$ = input + until s$ = "" + a$[] = strtok s$ " " + left = n2id a$[1] + if left > len g[][] : len g[][] left + for i = 2 to len a$[] + id = n2id a$[i] + if id <> left + g[left][] &= id + . + . + . +. +init +# +lng = len g[][] +len perm[] lng +len temp[] lng +global cycle result[] . +# +proc visit n . + if perm[n] = 1 : return + if temp[n] = 1 + cycle = 1 + return + . + temp[n] = 1 + for m in g[n][] : visit m + perm[n] = 1 + result[] &= n +. +repeat + for i to lng + if perm[i] = 0 : break 1 + . + until i > lng + visit i +. +if cycle = 1 + print "un-orderable" +else + for r in result[] : print name$[r] +. +# +input_data +des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee +dw01 ieee dw01 dware gtech +dw02 ieee dw02 dware +dw03 std synopsys dware dw03 dw02 dw01 ieee gtech +dw04 dw04 ieee dw01 dware gtech +dw05 dw05 ieee dware +dw06 dw06 ieee dware +dw07 ieee dware +dware ieee dware +gtech ieee gtech +ramlib std ieee +std_cell_lib ieee std_cell_lib +synopsys diff --git a/Task/Topological-sort/Elixir/topological-sort.elixir b/Task/Topological-sort/Elixir/topological-sort.ex similarity index 100% rename from Task/Topological-sort/Elixir/topological-sort.elixir rename to Task/Topological-sort/Elixir/topological-sort.ex diff --git a/Task/Topological-sort/FreeBASIC/topological-sort-1.basic b/Task/Topological-sort/FreeBASIC/topological-sort-1.basic new file mode 100644 index 0000000000..ab9fb12fd5 --- /dev/null +++ b/Task/Topological-sort/FreeBASIC/topological-sort-1.basic @@ -0,0 +1,150 @@ +Type Pair + primero As Integer + segundo As Integer +End Type + +Type Graph + vertices(14) As String + numVertices As Integer + proximos(14, 14) As Boolean + + Declare Constructor(s As String, edges() As Pair) + Declare Function hasDependency(r As Integer, todo() As Integer, todoCount As Integer) As Boolean + Declare Function topoSort() As String +End Type + +Function splitString(text As String, delimiter As String, Byref count As Integer) As String Ptr + Dim As Integer numTokens = 0 + Dim As String tmp = text + Dim As Long posic + + ' Count delimiters + Do + posic = Instr(tmp, delimiter) + If posic = 0 Then Exit Do + numTokens += 1 + tmp = Mid(tmp, posic + Len(delimiter)) + Loop + numTokens += 1 + + ' Allocate array + count = numTokens + Dim As String Ptr result = Callocate((numTokens) * Sizeof(String)) + + ' Split string + tmp = text + numTokens = 0 + Do + posic = Instr(tmp, delimiter) + If posic = 0 Then + result[numTokens] = tmp + Exit Do + End If + result[numTokens] = Left(tmp, posic - 1) + tmp = Mid(tmp, posic + Len(delimiter)) + numTokens += 1 + Loop + + Return result +End Function + +Constructor Graph(s As String, edges() As Pair) + Dim As Integer i, tokenCount + Dim As String Ptr tokens = splitString(s, ", ", tokenCount) + numVertices = tokenCount + For i = 0 To numVertices - 1 + vertices(i) = tokens[i] + Next + Deallocate(tokens) + + ' Initialize proximos matrix + For i = 0 To Ubound(edges) + proximos(edges(i).primero, edges(i).segundo) = True + Next +End Constructor + +Function Graph.hasDependency(r As Integer, todo() As Integer, todoCount As Integer) As Boolean + For i As Integer = 0 To todoCount - 1 + If proximos(r, todo(i)) Then Return True + Next + Return False +End Function + +Function Graph.topoSort() As String + Dim As String result = "" + Dim As Integer todoCount, i, j + Dim As Integer todo(numVertices) + + todoCount = numVertices + ' Initialize todo list + For i = 0 To numVertices - 1 + todo(i) = i + Next + + While todoCount > 0 + i = 0 + Dim As Boolean found = False + + While i < todoCount + If Not hasDependency(todo(i), todo(), todoCount) Then + ' Add to result + If Len(result) > 0 Then result &= ", " + result &= vertices(todo(i)) + + ' Remove from todo + For j = i To todoCount - 2 + todo(j) = todo(j + 1) + Next + todoCount -= 1 + found = True + Exit While + End If + i += 1 + Wend + + If Not found Then Return "Graph has cycles" + Wend + + Return "[" & result & "]" +End Function + +' Main program +Dim As String s = "std, ieee, des_system_lib, dw01, dw02, dw03, dw04, dw05, " & _ +"dw06, dw07, dware, gtech, ramlib, std_cell_lib, synopsys" + +Dim As Pair deps(33) +' Initialize deps array +deps(0) = Type(2, 0) : deps(1) = Type(2, 14) +deps(2) = Type(2, 13) : deps(3) = Type(2, 4) +deps(4) = Type(2, 3) : deps(5) = Type(2, 12) +deps(6) = Type(2, 1) : deps(7) = Type(3, 1) +deps(8) = Type(3, 10) : deps(9) = Type(3, 11) +deps(10) = Type(4, 1) : deps(11) = Type(4, 10) +deps(12) = Type(5, 0) : deps(13) = Type(5, 14) +deps(14) = Type(5, 10) : deps(15) = Type(5, 4) +deps(16) = Type(5, 3) : deps(17) = Type(5, 1) +deps(18) = Type(5, 11) : deps(19) = Type(6, 1) +deps(20) = Type(6, 3) : deps(21) = Type(6, 10) +deps(22) = Type(6, 11) : deps(23) = Type(7, 1) +deps(24) = Type(7, 10) : deps(25) = Type(8, 1) +deps(26) = Type(8, 10) : deps(27) = Type(9, 1) +deps(28) = Type(9, 10) : deps(29) = Type(10, 1) +deps(30) = Type(11, 1) : deps(31) = Type(12, 0) +deps(32) = Type(12, 1) : deps(33) = Type(13, 1) + +Dim As Graph g = Graph(s, deps()) +Print "Topologically sorted order:" +Print g.topoSort() +Print + +' Add new dependency +For i As Integer = 33 To 11 Step -1 + deps(i) = deps(i-1) +Next +deps(10) = Type(3, 6) + +Dim As Graph g2 = Graph(s, deps()) +Print "Following the addition of dw04 to the dependencies of dw01:" +Print g2.topoSort() + +Sleep diff --git a/Task/Topological-sort/FreeBASIC/topological-sort-2.basic b/Task/Topological-sort/FreeBASIC/topological-sort-2.basic new file mode 100644 index 0000000000..3a7c952646 --- /dev/null +++ b/Task/Topological-sort/FreeBASIC/topological-sort-2.basic @@ -0,0 +1,168 @@ +Const NULL As Any Ptr = 0 + +Type item_t + As String nombre + As Integer Ptr deps + As Integer n_deps + As Integer idx + As Integer depth +End Type + +Dim Shared As String entrada +entrada = "des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee" & Chr(10) & _ +"dw01 ieee dw01 dware gtech" & Chr(10) & _ +"dw02 ieee dw02 dware" & Chr(10) & _ +"dw03 std synopsys dware dw03 dw02 dw01 ieee gtech" & Chr(10) & _ +"dw04 dw04 ieee dw01 dware gtech" & Chr(10) & _ +"dw05 dw05 ieee dware" & Chr(10) & _ +"dw06 dw06 ieee dware" & Chr(10) & _ +"dw07 ieee dware" & Chr(10) & _ +"dware ieee dware" & Chr(10) & _ +"gtech ieee gtech" & Chr(10) & _ +"ramlib std ieee" & Chr(10) & _ +"std_cell_lib ieee std_cell_lib" & Chr(10) & _ +"synopsys" & Chr(10) & _ +"cycle_11 cycle_12" & Chr(10) & _ +"cycle_12 cycle_11" & Chr(10) & _ +"cycle_21 dw01 cycle_22 dw02 dw03" & Chr(10) & _ +"cycle_22 cycle_21 dw01 dw04" & Chr(10) + +Function get_item(list() As item_t, Byref longi As Integer, nombre As String) As Integer + Dim As Integer i + For i = 0 To longi - 1 + If list(i).nombre = nombre Then Return i + Next + + longi += 1 + Redim Preserve list(longi - 1) + i = longi - 1 + list(i).idx = i + list(i).nombre = nombre + list(i).n_deps = 0 + list(i).deps = NULL + list(i).depth = 0 + Return i +End Function + +Sub add_dep(Byref it As item_t, i As Integer) + If it.idx = i Then Return + it.deps = Reallocate(it.deps, (it.n_deps + 1) * Sizeof(Integer)) + it.deps[it.n_deps] = i + it.n_deps += 1 +End Sub + +Function parse_input(ret() As item_t) As Integer + Dim As Integer i, parent, idx, n_items, posic, nextpos + Dim As item_t list() + Dim As String s, linea, word + + n_items = 0 + s = entrada + + Do While Len(s) > 0 + posic = Instr(s, Chr(10)) + If posic = 0 Then + linea = s + s = "" + Else + linea = Left(s, posic - 1) + s = Mid(s, posic + 1) + End If + + i = 0 + While Len(linea) > 0 + linea = Trim(linea) + If Len(linea) = 0 Then Exit While + + posic = Instr(linea, " ") + If posic = 0 Then + word = linea + linea = "" + Else + word = Left(linea, posic - 1) + linea = Mid(linea, posic + 1) + End If + + If Len(word) > 0 Then + idx = get_item(list(), n_items, word) + + If i = 0 Then + parent = idx + Else + add_dep(list(parent), idx) + End If + i += 1 + End If + Wend + Loop + + Redim ret(n_items - 1) + For i = 0 To n_items - 1 + ret(i) = list(i) + Next + + Return n_items +End Function + +Function get_depth(base_() As item_t, idx As Integer, bad As Integer) As Integer + Dim As Integer max = 1, i, t + + If base_(idx).n_deps = 0 Then + base_(idx).depth = 1 + Return 1 + End If + + If base_(idx).depth < 0 Then Return base_(idx).depth + If base_(idx).depth > 0 Then Return base_(idx).depth + + base_(idx).depth = bad + For i = 0 To base_(idx).n_deps - 1 + t = get_depth(base_(), base_(idx).deps[i], bad) + If t < 0 Then + max = t + Exit For + End If + If max < t + 1 Then max = t + 1 + Next + + base_(idx).depth = max + Return max +End Function + +' Main program +Dim As Integer i, j, n, bad = -1, max = -1000000, min = 1000000 +Dim As item_t items() + +n = parse_input(items()) + +For i = 0 To n - 1 + If items(i).depth = 0 And get_depth(items(), i, bad) < 0 Then bad -= 1 +Next + +For i = 0 To n - 1 + If items(i).depth > max Then max = items(i).depth + If items(i).depth < min Then min = items(i).depth +Next + +Print "Compile order:" +For i = min To max + If i = 0 Then Continue For + + If i < 0 Then + Print " [unorderable]"; + Else + Print i; ":"; + End If + + For j = 0 To n - 1 + If items(j).depth = i Then Print " "; items(j).nombre; + Next + Print +Next + +' Clean up memory +For i = 0 To n - 1 + If items(i).deps <> NULL Then Deallocate(items(i).deps) +Next + +Sleep diff --git a/Task/Topological-sort/Julia/topological-sort.julia b/Task/Topological-sort/Julia/topological-sort.jl similarity index 100% rename from Task/Topological-sort/Julia/topological-sort.julia rename to Task/Topological-sort/Julia/topological-sort.jl diff --git a/Task/Topological-sort/Kotlin/topological-sort-1.kotlin b/Task/Topological-sort/Kotlin/topological-sort-1.kts similarity index 100% rename from Task/Topological-sort/Kotlin/topological-sort-1.kotlin rename to Task/Topological-sort/Kotlin/topological-sort-1.kts diff --git a/Task/Topological-sort/Kotlin/topological-sort-2.kotlin b/Task/Topological-sort/Kotlin/topological-sort-2.kts similarity index 100% rename from Task/Topological-sort/Kotlin/topological-sort-2.kotlin rename to Task/Topological-sort/Kotlin/topological-sort-2.kts diff --git a/Task/Topological-sort/OCaml/topological-sort.ocaml b/Task/Topological-sort/OCaml/topological-sort.ml similarity index 100% rename from Task/Topological-sort/OCaml/topological-sort.ocaml rename to Task/Topological-sort/OCaml/topological-sort.ml diff --git a/Task/Topological-sort/PowerShell/topological-sort.psh b/Task/Topological-sort/PowerShell/topological-sort.ps1 similarity index 100% rename from Task/Topological-sort/PowerShell/topological-sort.psh rename to Task/Topological-sort/PowerShell/topological-sort.ps1 diff --git a/Task/Topological-sort/Rust/topological-sort.rs b/Task/Topological-sort/Rust/topological-sort.rs new file mode 100644 index 0000000000..46295af5b4 --- /dev/null +++ b/Task/Topological-sort/Rust/topological-sort.rs @@ -0,0 +1,97 @@ +use std::collections::{HashMap, HashSet}; + +#[derive(Debug)] +struct Library<'a> { + name: &'a str, + children: Vec<&'a str>, + num_parents: usize, +} + +impl<'a> Library<'a> { + const fn new(name: &'a str) -> Self { + Self { + name, + children: Vec::new(), + num_parents: 0, + } + } +} + +fn build_libraries<'a>(input: &'a str) -> HashMap<&'a str, Library<'a>> { + let mut libraries: HashMap<&'a str, Library<'a>> = HashMap::new(); + + for input_line in input.lines() { + let mut line_split = input_line.split_whitespace(); + let name = line_split.next().unwrap(); + let mut num_parents: usize = 0; + for parent in line_split { + if parent == name { + continue; + } + libraries + .entry(parent) + .or_insert_with(|| Library::new(parent)) + .children + .push(name); + num_parents += 1; + } + + libraries + .entry(name) + .or_insert_with(|| Library::new(name)) + .num_parents = num_parents; + } + libraries +} + +fn topological_sort<'a>( + mut libraries: HashMap<&'a str, Library<'a>>, +) -> Result, String> { + let mut needs_processing = libraries.keys().copied().collect::>(); + let mut options: Vec<&str> = libraries + .iter() + .filter_map(|(k, v)| (v.num_parents == 0).then_some(*k)) + .collect(); + let mut sorted: Vec<&str> = Vec::new(); + while let Some(cur) = options.pop() { + let children = libraries.get(cur).unwrap().children.clone(); + for child_name in children { + let child = libraries.get_mut(child_name).unwrap(); + child.num_parents -= 1; + if child.num_parents == 0 { + options.push(child.name); + } + } + sorted.push(cur); + needs_processing.remove(cur); + } + if needs_processing.is_empty() { + Ok(sorted) + } else { + Err(format!("Cycle detected among {needs_processing:?}")) + } +} + +fn main() { + let input: &str = "\ + des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n\ + dw01 ieee dw01 dware gtech\n\ + dw02 ieee dw02 dware\n\ + dw03 std synopsys dware dw03 dw02 dw01 ieee gtech\n\ + dw04 dw04 ieee dw01 dware gtech\n\ + dw05 dw05 ieee dware\n\ + dw06 dw06 ieee dware\n\ + dw07 ieee dware\n\ + dware ieee dware\n\ + gtech ieee gtech\n\ + ramlib std ieee\n\ + std_cell_lib ieee std_cell_lib\n\ + synopsys\ + "; + + let libraries = build_libraries(input); + match topological_sort(libraries) { + Ok(sorted) => println!("{sorted:?}"), + Err(msg) => println!("{msg:?}"), + } +} diff --git a/Task/Topological-sort/Rust/topological-sort.rust b/Task/Topological-sort/Rust/topological-sort.rust deleted file mode 100644 index 3ff0044b2b..0000000000 --- a/Task/Topological-sort/Rust/topological-sort.rust +++ /dev/null @@ -1,112 +0,0 @@ -use std::boxed::Box; -use std::collections::{HashMap, HashSet}; - -#[derive(Debug, PartialEq, Eq, Hash)] -struct Library<'a> { - name: &'a str, - children: Vec<&'a str>, - num_parents: usize, -} - -fn build_libraries(input: Vec<&str>) -> HashMap<&str, Box> { - let mut libraries: HashMap<&str, Box> = HashMap::new(); - - for input_line in input { - let line_split = input_line.split_whitespace().collect::>(); - let name = line_split.get(0).unwrap(); - let mut num_parents: usize = 0; - for parent in line_split.iter().skip(1) { - if parent == name { - continue; - } - if !libraries.contains_key(parent) { - libraries.insert( - parent, - Box::new(Library { - name: parent, - children: vec![name], - num_parents: 0, - }), - ); - } else { - libraries.get_mut(parent).unwrap().children.push(name); - } - num_parents += 1; - } - - if !libraries.contains_key(name) { - libraries.insert( - name, - Box::new(Library { - name, - children: Vec::new(), - num_parents, - }), - ); - } else { - libraries.get_mut(name).unwrap().num_parents = num_parents; - } - } - libraries -} - -fn topological_sort<'a>( - mut libraries: HashMap<&'a str, Box>>, -) -> Result, String> { - let mut needs_processing = libraries - .iter() - .map(|(k, _v)| k.clone()) - .collect::>(); - let mut options: Vec<&str> = libraries - .iter() - .filter(|(_k, v)| v.num_parents == 0) - .map(|(k, _v)| *k) - .collect(); - let mut sorted: Vec<&str> = Vec::new(); - while !options.is_empty() { - let cur = options.pop().unwrap(); - for children in libraries - .get_mut(cur) - .unwrap() - .children - .drain(0..) - .collect::>() - { - let child = libraries.get_mut(children).unwrap(); - child.num_parents -= 1; - if child.num_parents == 0 { - options.push(child.name) - } - } - sorted.push(cur); - needs_processing.remove(cur); - } - match needs_processing.is_empty() { - true => Ok(sorted), - false => Err(format!("Cycle detected among {:?}", needs_processing)), - } -} - -fn main() { - let input: Vec<&str> = vec![ - "des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n", - "dw01 ieee dw01 dware gtech dw04\n", - "dw02 ieee dw02 dware\n", - "dw03 std synopsys dware dw03 dw02 dw01 ieee gtech\n", - "dw04 dw04 ieee dw01 dware gtech\n", - "dw05 dw05 ieee dware\n", - "dw06 dw06 ieee dware\n", - "dw07 ieee dware\n", - "dware ieee dware\n", - "gtech ieee gtech\n", - "ramlib std ieee\n", - "std_cell_lib ieee std_cell_lib\n", - "synopsys\n", - ]; - - let libraries = build_libraries(input); - match topological_sort(libraries) { - Ok(sorted) => println!("{:?}", sorted), - Err(msg) => println!("{:?}", msg), - } -} diff --git a/Task/Topological-sort/Scheme/topological-sort.ss b/Task/Topological-sort/Scheme/topological-sort.scm similarity index 100% rename from Task/Topological-sort/Scheme/topological-sort.ss rename to Task/Topological-sort/Scheme/topological-sort.scm diff --git a/Task/Topological-sort/VBScript/topological-sort-1.vb b/Task/Topological-sort/VBScript/topological-sort-1.vbs similarity index 100% rename from Task/Topological-sort/VBScript/topological-sort-1.vb rename to Task/Topological-sort/VBScript/topological-sort-1.vbs diff --git a/Task/Topological-sort/VBScript/topological-sort-2.vb b/Task/Topological-sort/VBScript/topological-sort-2.vbs similarity index 100% rename from Task/Topological-sort/VBScript/topological-sort-2.vb rename to Task/Topological-sort/VBScript/topological-sort-2.vbs diff --git a/Task/Topswops/Ada/topswops.ada b/Task/Topswops/Ada/topswops.adb similarity index 100% rename from Task/Topswops/Ada/topswops.ada rename to Task/Topswops/Ada/topswops.adb diff --git a/Task/Topswops/EasyLang/topswops.easy b/Task/Topswops/EasyLang/topswops.easy new file mode 100644 index 0000000000..c1f0b382f1 --- /dev/null +++ b/Task/Topswops/EasyLang/topswops.easy @@ -0,0 +1,30 @@ +global n d best[] . +# +proc tryswaps &a[] f . + if d > best[n] : best[n] = d + for s = len a[] downto 1 + if a[s] = 0 or a[s] = s : break 1 + if d + best[s] <= best[n] : return + . + d += 1 + for i = 1 to s : b[] &= a[i] + k = 1 + for i = 2 to s + k *= 2 + if b[i] = 0 and bitand f k = 0 or b[i] = i + b[1] = i + for j = i - 1 downto 1 + b[i - j + 1] = a[j] + . + tryswaps b[] (bitor f k) + . + . + d -= 1 +. +for n = 1 to 10 + best[] &= 0 + x[] &= 0 + d = 0 + tryswaps x[] 1 + print n & ": " & best[n] +. diff --git a/Task/Topswops/Elixir/topswops.elixir b/Task/Topswops/Elixir/topswops.ex similarity index 100% rename from Task/Topswops/Elixir/topswops.elixir rename to Task/Topswops/Elixir/topswops.ex diff --git a/Task/Topswops/JavaScript/topswops.js b/Task/Topswops/JavaScript/topswops.js new file mode 100644 index 0000000000..5f0eb58830 --- /dev/null +++ b/Task/Topswops/JavaScript/topswops.js @@ -0,0 +1,56 @@ +class Topswops { + static maxBest = 32; + static best = new Array(Topswops.maxBest).fill(0); + + static trySwaps(deck, f, d, n) { + if (d > this.best[n]) { + this.best[n] = d; + } + for (let i = n - 1; i >= 0; i--) { + if (deck[i] === -1 || deck[i] === i) { + break; + } + if (d + this.best[i] <= this.best[n]) { + return; + } + } + let deck2 = [...deck]; + for (let i = 1; i < n; i++) { + const k = 1 << i; + if (deck2[i] === -1) { + if ((f & k) !== 0) { + continue; + } + } else if (deck2[i] !== i) { + continue; + } + deck2[0] = i; + for (let j = i - 1; j >= 0; j--) { + deck2[i - j] = deck[j]; // Reverse copy. + } + this.trySwaps(deck2, f | k, d + 1, n); + } + } + + static topswops(n) { + if (n <= 0 || n >= this.maxBest) { + throw new Error("n must be between 1 and maxBest"); + } + this.best[n] = 0; + let deck0 = new Array(n + 1).fill(0); + for (let i = 1; i < n; i++) { + deck0[i] = -1; + } + this.trySwaps(deck0, 1, 0, n); + return this.best[n]; + } + + static main() { + for (let i = 1; i < 11; i++) { + console.log(`${i}: ${this.topswops(i)}`); + } + } +} + +// Run the main function +Topswops.main(); diff --git a/Task/Topswops/Julia/topswops.julia b/Task/Topswops/Julia/topswops.jl similarity index 100% rename from Task/Topswops/Julia/topswops.julia rename to Task/Topswops/Julia/topswops.jl diff --git a/Task/Topswops/Kotlin/topswops.kotlin b/Task/Topswops/Kotlin/topswops.kts similarity index 100% rename from Task/Topswops/Kotlin/topswops.kotlin rename to Task/Topswops/Kotlin/topswops.kts diff --git a/Task/Topswops/Prolog/topswops.pro b/Task/Topswops/Prolog/topswops.pro new file mode 100644 index 0000000000..376a72028d --- /dev/null +++ b/Task/Topswops/Prolog/topswops.pro @@ -0,0 +1,23 @@ +topswops(N, MaximumSwaps) :- + numlist(1, N, Cards), + aggregate_all(max(Swaps), ( + permutation(Cards, Shuffled), + topswops_(Shuffled, 0, Swaps) + ), MaximumSwaps). + +topswops_([Card | Cards0], Swaps0, Swaps) :- + ( Card = 1 + -> Swaps0 = Swaps + ; succ(Swaps0, Swaps1), + length(Prefix, Card), + append(Prefix, Suffix, [Card | Cards0]), + reverse(Prefix, Reversed), + append(Reversed, Suffix, Cards), + topswops_(Cards, Swaps1, Swaps) + ). + +main :- + foreach( + ( between(1, 10, N), topswops(N, MaximumSwaps) ), + format("~w: ~w~n", [N, MaximumSwaps]) + ). diff --git a/Task/Topswops/Rust/topswops.rust b/Task/Topswops/Rust/topswops.rs similarity index 100% rename from Task/Topswops/Rust/topswops.rust rename to Task/Topswops/Rust/topswops.rs diff --git a/Task/Total-circles-area/00-TASK.txt b/Task/Total-circles-area/00-TASK.txt index e81c603abd..d4e3553bd2 100644 --- a/Task/Total-circles-area/00-TASK.txt +++ b/Task/Total-circles-area/00-TASK.txt @@ -1,3 +1,4 @@ +https://rosettacode.org/wiki/Total_circles_area?action=edit Given some partially overlapping circles on the plane, compute and show the total area covered by them, with four or six (or a little more) decimal digits of precision. The area covered by two or more disks needs to be counted only once. One point of this Task is also to compare and discuss the relative merits of various solution strategies, their performance, precision and simplicity. This means keeping both slower and faster solutions for a language (like C) is welcome. diff --git a/Task/Total-circles-area/Ada/total-circles-area.adb b/Task/Total-circles-area/Ada/total-circles-area.adb new file mode 100644 index 0000000000..22175d5daf --- /dev/null +++ b/Task/Total-circles-area/Ada/total-circles-area.adb @@ -0,0 +1,109 @@ +with Ada.Text_IO; + +procedure Circles_Area is + type Point is record + X, Y : Float; + end record; + + type Circle is record + P : Point; + R : Float; + end record; + + type Box is record + P1, P2 : Point; + end record; + + type Circle_Array is array (1 .. 25) of Circle; + + Circles : constant Circle_Array := + ( + ((1.6417233788, 1.6121789534), 0.0848270516), + ((-1.4944608174, 1.2077959613), 1.1039549836), + ((0.6110294452, -0.6907087527), 0.9089162485), + ((0.3844862411, 0.2923344616), 0.2375743054), + ((-0.2495892950, -0.3832854473), 1.0845181219), + ((1.7813504266, 1.6178237031), 0.8162655711), + ((-0.1985249206, -0.8343333301), 0.0538864941), + ((-1.7011985145, -0.1263820964), 0.4776976918), + ((-0.4319462812, 1.4104420482), 0.7886291537), + ((0.2178372997, -0.9499557344), 0.0357871187), + ((-0.6294854565, -1.3078893852), 0.7653357688), + ((1.7952608455, 0.6281269104), 0.2727652452), + ((1.4168575317, 1.0683357171), 1.1016025378), + ((1.4637371396, 0.9463877418), 1.1846214562), + ((-0.5263668798, 1.7315156631), 1.4428514068), + ((-1.2197352481, 0.9144146579), 1.0727263474), + ((-0.1389358881, 0.1092805780), 0.7350208828), + ((1.5293954595, 0.0030278255), 1.2472867347), + ((-0.5258728625, 1.3782633069), 1.3495508831), + ((-0.1403562064, 0.2437382535), 1.3804956588), + ((0.8055826339, -0.0482092025), 0.3327165165), + ((-0.6311979224, 0.7184578971), 0.2491045282), + ((1.4685857879, -0.8347049536), 1.3670667538), + ((-0.6855727502, 1.6465021616), 1.0593087096), + ((0.0152957411, 0.0638919221), 0.9771215985) + ); + + function Bounding_Box return Box is + C : Circle := Circles (1); + Left : Float := C.P.X - C.R; + Right : Float := C.P.X + C.R; + Down : Float := C.P.Y - C.R; + Up : Float := C.P.Y + C.R; + begin + for I in Circles'Range loop + C := Circles (I); + Left := Float'Min (Left, C.P.X - C.R); + Right := Float'Max (Right, C.P.X + C.R); + Down := Float'Min (Down, C.P.Y - C.R); + Up := Float'Max (Up, C.P.Y + C.R); + end loop; + + return ((Left, Down), (Right, Up)); + end Bounding_Box; + + function Distance2 (P1, P2 : Point) return Float is + ((P2.X - P1.X) ** 2 + (P2.Y - P1.Y) ** 2); + + function Is_Inside (P : Point) return Boolean is + C : Circle; + begin + for I in Circles'Range loop + C := Circles (I); + if Distance2 (C.P, P) < C.R ** 2 then + return True; + end if; + end loop; + + return False; + end Is_Inside; + + -- Use grid sampling + function Area return Float is + Bounds : constant Box := Bounding_Box; + X_Span : constant Float := (Bounds.P2.X - Bounds.P1.X); + Y_Span : constant Float := (Bounds.P2.Y - Bounds.P1.Y); + Grid_Area : constant Float := X_Span * Y_Span; + Steps : constant Integer := 1000; + Points_In, Points_Out : Integer := 0; + P : Point; + begin + for I in 1 .. Steps loop + for J in 1 .. Steps loop + P.X := Bounds.P1.X + X_Span * Float (I) / Float (Steps); + P.Y := Bounds.P1.Y + Y_Span * Float (J) / Float (Steps); + if Is_Inside (P) then + Points_In := Points_In + 1; + else + Points_Out := Points_Out + 1; + end if; + end loop; + end loop; + + return Grid_Area * Float (Points_In) / Float (Points_In + Points_Out); + end Area; + +begin + Ada.Text_IO.Put ("Circles area is " & Area'Image); +end Circles_Area; diff --git a/Task/Total-circles-area/Delphi/total-circles-area.delphi b/Task/Total-circles-area/Delphi/total-circles-area.pas similarity index 100% rename from Task/Total-circles-area/Delphi/total-circles-area.delphi rename to Task/Total-circles-area/Delphi/total-circles-area.pas diff --git a/Task/Total-circles-area/EasyLang/total-circles-area.easy b/Task/Total-circles-area/EasyLang/total-circles-area.easy index 3dcb2fd239..e82e7c31eb 100644 --- a/Task/Total-circles-area/EasyLang/total-circles-area.easy +++ b/Task/Total-circles-area/EasyLang/total-circles-area.easy @@ -46,7 +46,7 @@ for try to ntry . . . -numfmt 4 0 +numfmt 0 4 print inside / ntry * (maxx - minx) * (maxy - miny) # input_data diff --git a/Task/Total-circles-area/Fortran/total-circles-area.f b/Task/Total-circles-area/Fortran/total-circles-area.f new file mode 100644 index 0000000000..0fc2b0fba3 --- /dev/null +++ b/Task/Total-circles-area/Fortran/total-circles-area.f @@ -0,0 +1,324 @@ +! ============================================================================== +! circle_union.f90 -- '''Exact''' area of the union of N overlapping disks +! ============================================================================== +! +! METHOD: Analytical boundary integration via Green's theorem +! ----------------------------------------------------------------- +! Rather than sampling the plane (Monte Carlo or grid), this program +! computes the area EXACTLY (to floating-point precision) by integrating +! along the true geometric boundary of the union. +! +! The boundary of the union of circles is a closed curve made up entirely +! of circular arcs -- pieces of individual circle boundaries that are not +! covered by any other circle. Green's theorem converts a 2-D area +! integral into a 1-D line integral around that boundary: +! +! A = (1/2) * INTEGRAL_boundary ( x dy - y dx ) +! +! For an arc of radius r centred at (cx, cy), running from angle t1 to t2 +! in the counterclockwise direction, the parametric form is: +! +! x(t) = cx + r*cos(t), y(t) = cy + r*sin(t) +! dx = -r*sin(t) dt, dy = r*cos(t) dt +! +! Substituting and integrating analytically gives the closed-form result: +! +! arc contribution = (r/2) * [ cx*(sin(t2)-sin(t1)) +! - cy*(cos(t2)-cos(t1)) +! + r*(t2-t1) ] +! +! Summing this over every boundary arc yields the total area with no +! approximation error beyond normal IEEE 754 double-precision rounding. +! +! WHY THIS IS SUPERIOR TO SAMPLING APPROACHES +! ----------------------------------------------------------------- +! 1. ACCURACY +! Monte Carlo converges as 1/sqrt(S) where S is the number of samples. +! To gain one extra decimal digit you must take 100x more samples. +! A grid (pixel-counting) approach converges as 1/S, still slow. +! This method has NO convergence parameter -- the result is exact up +! to floating-point rounding (~15 significant digits with real(kind=real64)). +! +! 2. SPEED +! The work here is O(n^2) in the number of circles: for each of the n +! circles we examine at most n-1 others to find intersections. For +! n=25 that is a handful of microseconds. A sampling method accurate +! to 10 decimal places would need billions of samples and many seconds. +! +! 3. NO TUNING +! Sampling methods require the user to choose a sample count or grid +! resolution and then judge whether it is "good enough". This method +! has no such knob; the answer is simply correct. +! +! 4. ROBUSTNESS TO GEOMETRY +! Grid methods can mis-count when a circle boundary happens to pass +! very close to a grid node. Monte Carlo has similar edge effects near +! boundaries. This method handles all configurations -- tangent circles, +! near-tangent circles, tiny circles, and fully-contained circles -- +! through straightforward geometric tests with no special-casing of +! near-degenerate configurations (apart from a small epsilon guard on +! near-zero arc lengths). +! +! ALGORITHM OUTLINE +! ----------------------------------------------------------------- +! For each circle i: +! 1. If circle i lies entirely inside some other circle j, skip it -- +! none of its boundary is exposed and its area is already counted +! inside j. +! 2. Find every circle j that properly crosses circle i's boundary. +! Each such intersection contributes two angles (measured from the +! centre of circle i) computed via the law of cosines. +! 3. Sort those angles. They divide circle i into arcs. +! 4. For each arc, sample its midpoint and test whether that point +! lies inside any other circle. If not, the arc is on the outer +! boundary of the union and its Green's-theorem contribution is added. +! 5. If no other circle intersects circle i at all, add the full disk +! area pi*r^2. +! +! DATASET (Rosetta Code standard test, 25 disks, 11 fully contained) +! Expected result: 21.56503660... +! ============================================================================== + +program circle_union + use iso_fortran_env, only:real64 + implicit none + + ! Number of circles in the dataset + integer, parameter :: n = 25 + + real(kind=real64), parameter :: pi = acos(-1.0d0) + real(kind=real64), parameter :: two_pi = 2.0d0 * pi + + ! Circle centre coordinates and radii + real(kind=real64) :: xc(n), yc(n), r(n) + + ! Intersection angles collected for the current circle i. + ! At most 2*(n-1) intersections are possible (two per circle pair), + ! so 2*n+2 is a safe upper bound. + real(kind=real64) :: angles(2 * n + 2) + integer :: nang ! number of angles collected so far + + ! Working variables + real(kind=real64) :: area ! accumulated union area + real(kind=real64) :: dx, dy ! vector from centre i to centre j + real(kind=real64) :: d2, d ! squared distance and distance between centres + real(kind=real64) :: a ! cosine of half the intersection angle (law of cosines) + real(kind=real64) :: phi ! bearing from centre i to centre j + real(kind=real64) :: da ! half-angle offset to each intersection point + real(kind=real64) :: t1, t2 ! start and end angles of the current arc + real(kind=real64) :: tmid ! midpoint angle of the current arc + real(kind=real64) :: xm, ym ! Cartesian coordinates of the arc midpoint + integer :: i, j, k + logical :: fully_inside ! true when circle i is swallowed by circle j + logical :: arc_outside ! true when arc midpoint is outside all other circles + + ! ------------------------------------------------------------------ + ! Dataset: centre (xc, yc) and radius r for each of the 25 disks + ! (Rosetta Code standard input) + ! ------------------------------------------------------------------ + xc = [ 1.6417233788d0, -1.4944608174d0, 0.6110294452d0, 0.3844862411d0, & + -0.2495892950d0, 1.7813504266d0, -0.1985249206d0, -1.7011985145d0, & + -0.4319462812d0, 0.2178372997d0, -0.6294854565d0, 1.7952608455d0, & + 1.4168575317d0, 1.4637371396d0, -0.5263668798d0, -1.2197352481d0, & + -0.1389358881d0, 1.5293954595d0, -0.5258728625d0, -0.1403562064d0, & + 0.8055826339d0, -0.6311979224d0, 1.4685857879d0, -0.6855727502d0, & + 0.0152957411d0 ] + yc = [ 1.6121789534d0, 1.2077959613d0, -0.6907087527d0, 0.2923344616d0, & + -0.3832854473d0, 1.6178237031d0, -0.8343333301d0, -0.1263820964d0, & + 1.4104420482d0, -0.9499557344d0, -1.3078893852d0, 0.6281269104d0, & + 1.0683357171d0, 0.9463877418d0, 1.7315156631d0, 0.9144146579d0, & + 0.1092805780d0, 0.0030278255d0, 1.3782633069d0, 0.2437382535d0, & + -0.0482092025d0, 0.7184578971d0, -0.8347049536d0, 1.6465021616d0, & + 0.0638919221d0 ] + r = [ 0.0848270516d0, 1.1039549836d0, 0.9089162485d0, 0.2375743054d0, & + 1.0845181219d0, 0.8162655711d0, 0.0538864941d0, 0.4776976918d0, & + 0.7886291537d0, 0.0357871187d0, 0.7653357688d0, 0.2727652452d0, & + 1.1016025378d0, 1.1846214562d0, 1.4428514068d0, 1.0727263474d0, & + 0.7350208828d0, 1.2472867347d0, 1.3495508831d0, 1.3804956588d0, & + 0.3327165165d0, 0.2491045282d0, 1.3670667538d0, 1.0593087096d0, & + 0.9771215985d0 ] + + area = 0.0d0 + + ! ================================================================== + ! Main loop: process each circle in turn + ! ================================================================== + do i = 1, n + + ! ------------------------------------------------------------------ + ! Step 1: skip circles that are entirely swallowed by another circle. + ! + ! Circle i is inside circle j when the farthest point of circle i + ! (i.e. the point on circle i closest to circle j's boundary on the + ! far side) still does not reach circle j's boundary: + ! + ! d(centres) + r_i <= r_j + ! + ! Such circles contribute nothing to the union boundary; their area + ! is already included inside the larger circle. + ! ------------------------------------------------------------------ + fully_inside = .false. + do j = 1, n + if (i == j) cycle + dx = xc(j) - xc(i) + dy = yc(j) - yc(i) + d = hypot(dx, dy) + if (d + r(i) <= r(j)) then + fully_inside = .true. + exit + end if + end do + if (fully_inside) cycle ! nothing to do for this circle + + ! ------------------------------------------------------------------ + ! Step 2: find the angles at which other circles cross circle i. + ! + ! Two circles intersect properly when: + ! |r_i - r_j| < d < r_i + r_j + ! + ! Given that they do intersect, the law of cosines gives the cosine + ! of the angle (measured at centre i) between the line i->j and each + ! intersection point: + ! + ! cos(da) = (r_i^2 + d^2 - r_j^2) / (2 * r_i * d) + ! + ! The two intersection angles are therefore: phi +/- da + ! where phi = atan2(yj-yi, xj-xi) is the bearing from i to j. + ! ------------------------------------------------------------------ + nang = 0 + do j = 1, n + if (i == j) cycle + dx = xc(j) - xc(i) + dy = yc(j) - yc(i) + d2 = dx * dx + dy * dy + d = sqrt(d2) + + ! Circles are external to each other -- no intersection + if (d >= r(i) + r(j)) cycle + + ! Circle j is entirely inside circle i -- does not cut i's boundary + if (d + r(j) <= r(i)) cycle + + ! Compute the two crossing angles via the law of cosines + a = (r(i)**2 + d2 - r(j)**2) / (2.0d0 * r(i) * d) + a = max(-1.0d0, min(1.0d0, a)) ! clamp against floating-point overshoot + phi = atan2(dy, dx) ! bearing from centre i to centre j + da = acos(a) ! half-angle to each intersection point + + nang = nang + 1 + angles(nang) = phi - da ! left intersection + nang = nang + 1 + angles(nang) = phi + da ! right intersection + end do + + ! ------------------------------------------------------------------ + ! Special case: no other circle intersects circle i at all. + ! Either circle i is isolated or it fully contains others but is not + ! itself cut. Either way its full disk area belongs to the union. + ! ------------------------------------------------------------------ + if (nang == 0) then + area = area + pi * r(i)**2 + cycle + end if + + ! ------------------------------------------------------------------ + ! Step 3: normalise all angles to [0, 2*pi) and sort them. + ! + ! After normalisation the sorted list partitions the full circle + ! into nang consecutive arcs. We also handle the wrap-around arc + ! from angles(nang) back to angles(1) + 2*pi in the loop below. + ! ------------------------------------------------------------------ + do k = 1, nang + angles(k) = mod(angles(k), two_pi) + if (angles(k) < 0.0d0) angles(k) = angles(k) + two_pi + end do + + call isort(angles, nang) ! ascending sort; see subroutine below + + ! ------------------------------------------------------------------ + ! Step 4: for each arc, test whether it lies on the union boundary. + ! + ! An arc belongs to the boundary of the union if and only if its + ! interior is NOT covered by any other circle. We test this at the + ! arc's angular midpoint: if that single point is outside all other + ! circles then the entire arc (between two consecutive intersection + ! events) must also be outside them all, because the only places + ! where coverage can change are exactly the intersection angles we + ! already collected. + ! + ! If the arc is on the boundary, add its contribution via the + ! closed-form Green's theorem integral derived in the header. + ! ------------------------------------------------------------------ + do k = 1, nang + t1 = angles(k) + + ! The last arc wraps around from angles(nang) back to angles(1) + if (k < nang) then + t2 = angles(k + 1) + else + t2 = angles(1) + two_pi + end if + + ! Skip numerically degenerate arcs (two intersection points that + ! landed at almost the same angle due to near-tangency) + if (t2 - t1 < 1.0d-12) cycle + + ! Cartesian coordinates of the arc midpoint on circle i + tmid = 0.5d0 * (t1 + t2) + xm = xc(i) + r(i) * cos(tmid) + ym = yc(i) + r(i) * sin(tmid) + + ! Is this midpoint outside every other circle? + arc_outside = .true. + do j = 1, n + if (i == j) cycle + dx = xm - xc(j) + dy = ym - yc(j) + ! Using squared distance avoids an unnecessary sqrt + if (dx * dx + dy * dy < r(j)**2) then + arc_outside = .false. + exit + end if + end do + + ! If the arc is exposed, accumulate its area contribution. + ! Green's theorem for a circular arc from t1 to t2: + ! dA = (1/2) * r * [ cx*(sin(t2)-sin(t1)) + ! - cy*(cos(t2)-cos(t1)) + ! + r*(t2-t1) ] + ! The r*(t2-t1) term is the "pure sector" part; the cx/cy terms + ! correct for the fact that the centre is not at the origin. + if (arc_outside) then + area = area + 0.5d0 * r(i) * (xc(i) * (sin(t2) - sin(t1)) & + - yc(i) * (cos(t2) - cos(t1)) + r(i) * (t2 - t1)) + end if + end do + + end do ! end loop over circles + + write(*, '(a,f16.10)') 'Area = ', area + +contains + + ! -------------------------------------------------------------------- + ! Insertion sort for a small real(kind=real64) array a(1:m). + ! Insertion sort is O(m^2) but m <= 2*(n-1) = 48 here, so it is fast + ! and avoids the overhead of a recursive quicksort. + ! -------------------------------------------------------------------- + subroutine isort(a, m) + real(kind=real64), intent(inout) :: a(*) ! array to sort (only first m elements used) + integer, intent(in) :: m ! number of elements to sort + integer :: p, q + real(kind=real64) :: tmp + do p = 2, m + tmp = a(p) ! element being inserted into sorted prefix + q = p - 1 + do while (q >= 1 .and. a(q) > tmp) + a(q + 1) = a(q) ! shift larger elements one position right + q = q - 1 + end do + a(q + 1) = tmp ! drop the element into its sorted position + end do + end subroutine isort + +end program circle_union diff --git a/Task/Total-circles-area/Julia/total-circles-area.julia b/Task/Total-circles-area/Julia/total-circles-area.jl similarity index 100% rename from Task/Total-circles-area/Julia/total-circles-area.julia rename to Task/Total-circles-area/Julia/total-circles-area.jl diff --git a/Task/Total-circles-area/Kotlin/total-circles-area-1.kotlin b/Task/Total-circles-area/Kotlin/total-circles-area-1.kts similarity index 100% rename from Task/Total-circles-area/Kotlin/total-circles-area-1.kotlin rename to Task/Total-circles-area/Kotlin/total-circles-area-1.kts diff --git a/Task/Total-circles-area/Kotlin/total-circles-area-2.kotlin b/Task/Total-circles-area/Kotlin/total-circles-area-2.kts similarity index 100% rename from Task/Total-circles-area/Kotlin/total-circles-area-2.kotlin rename to Task/Total-circles-area/Kotlin/total-circles-area-2.kts diff --git a/Task/Total-circles-area/Lua/total-circles-area-1.lua b/Task/Total-circles-area/Lua/total-circles-area-1.lua new file mode 100644 index 0000000000..76862880f6 --- /dev/null +++ b/Task/Total-circles-area/Lua/total-circles-area-1.lua @@ -0,0 +1,105 @@ +-- Import the Moses functional programming library +-- (provides map, min, max, include, etc.) +local moses = require("moses") + +-- Helper: checks if any value in a table is truthy (i.e., not nil/false) +-- Used to test if a point lies inside *any* of the circles. +local function any(t) + return moses.include(t, function(v) + return v and true -- returns true as soon as one truthy element is found + end) +end + +-- Factory function to create a circle object with centre `(x, y)` and radius `r` +local function newCircle(x, y, radius) + local c = { + x = x, -- x-coordinate of centre + y = y, -- y-coordinate of centre + r = radius -- radius + } + return c +end + +-- Define a fixed set of 25 circles +local circles = { + newCircle( 1.6417233788, 1.6121789534, 0.0848270516), + newCircle(-1.4944608174, 1.2077959613, 1.1039549836), + newCircle( 0.6110294452, -0.6907087527, 0.9089162485), + newCircle( 0.3844862411, 0.2923344616, 0.2375743054), + newCircle(-0.2495892950, -0.3832854473, 1.0845181219), + newCircle( 1.7813504266, 1.6178237031, 0.8162655711), + newCircle(-0.1985249206, -0.8343333301, 0.0538864941), + newCircle(-1.7011985145, -0.1263820964, 0.4776976918), + newCircle(-0.4319462812, 1.4104420482, 0.7886291537), + newCircle( 0.2178372997, -0.9499557344, 0.0357871187), + newCircle(-0.6294854565, -1.3078893852, 0.7653357688), + newCircle( 1.7952608455, 0.6281269104, 0.2727652452), + newCircle( 1.4168575317, 1.0683357171, 1.1016025378), + newCircle( 1.4637371396, 0.9463877418, 1.1846214562), + newCircle(-0.5263668798, 1.7315156631, 1.4428514068), + newCircle(-1.2197352481, 0.9144146579, 1.0727263474), + newCircle(-0.1389358881, 0.1092805780, 0.7350208828), + newCircle( 1.5293954595, 0.0030278255, 1.2472867347), + newCircle(-0.5258728625, 1.3782633069, 1.3495508831), + newCircle(-0.1403562064, 0.2437382535, 1.3804956588), + newCircle( 0.8055826339, -0.0482092025, 0.3327165165), + newCircle(-0.6311979224, 0.7184578971, 0.2491045282), + newCircle( 1.4685857879, -0.8347049536, 1.3670667538), + newCircle(-0.6855727502, 1.6465021616, 1.0593087096), + newCircle( 0.0152957411, 0.0638919221, 0.9771215985) +} + +-- Compute the axis-aligned bounding box that contains all circles +local xMin = moses.min(moses.map(circles, function(c) + return c.x - c.r -- leftmost point +end)) +local xMax = moses.max(moses.map(circles, function(c) + return c.x + c.r -- rightmost point +end)) +local yMin = moses.min(moses.map(circles, function(c) + return c.y - c.r -- bottommost point +end)) +local yMax = moses.max(moses.map(circles, function(c) + return c.y + c.r -- topmost point +end)) + +-- Resolution of the grid: use a 500×500 pixel-like grid over the bounding box +local boxSide = 500 + +-- Width and height of each grid cell (pixel) +local dx = (xMax - xMin) / boxSide +local dy = (yMax - yMin) / boxSide + +-- Count how many grid cells contain at least one point inside the union of circles +local count = 0 + +-- Iterate over each row (y-direction) +for r = 1, boxSide do + -- Compute y-coordinate at the *centre* of the current row's cell + + -- Note: using `r * dy` places sample at top edge + dy, ..., + -- effectively sampling centres if we consider [0,1] indexing + + -- (More precisely: samples at yMin + dy, yMin + 2*dx, ..., yMin + boxSide*dx = yMax) + local y = yMin + r * dy + + -- Iterate over each column (x-direction) + for c = 1, boxSide do + -- Compute x-coordinate at the centre of the current column's cell + local x = xMin + c * dx + + -- Check if the point (x, y) lies inside *any* circle: + -- For each circle, compute squared distance from (x,y) to centre + -- and compare to squared radius (to avoid `sqrt` for performance) + if any(moses.map(circles, function(circle) + return (x - circle.x) ^ 2 + (y - circle.y) ^ 2 <= circle.r ^ 2 + end)) then + -- If inside at least one circle, count this grid cell + count = count + 1 + end + end +end + +-- Approximate area = (number of covered cells) × (area per cell) +-- This is a standard Monte Carlo / grid-based area estimation technique +print("Approximated area: "..(count*dx*dy)) diff --git a/Task/Total-circles-area/Lua/total-circles-area-2.lua b/Task/Total-circles-area/Lua/total-circles-area-2.lua new file mode 100644 index 0000000000..80543b94fc --- /dev/null +++ b/Task/Total-circles-area/Lua/total-circles-area-2.lua @@ -0,0 +1,120 @@ +-- Import the Moses functional programming library for utilities like map, select, +-- range, etc. +local moses = require("moses") + +-- Helper function to create a circle object with centre `(x, y)` and radius `r` +local function newCircle(x, y, radius) + local c = { + x = x, -- x-coordinate of the circle's centre + y = y, -- y-coordinate of the circle's centre + r = radius -- radius of the circle + } + return c +end + +-- Define a list of 25 circles with precomputed coordinates and radii. +local circles = { + newCircle( 1.6417233788, 1.6121789534, 0.0848270516), + newCircle(-1.4944608174, 1.2077959613, 1.1039549836), + newCircle( 0.6110294452, -0.6907087527, 0.9089162485), + newCircle( 0.3844862411, 0.2923344616, 0.2375743054), + newCircle(-0.2495892950, -0.3832854473, 1.0845181219), + newCircle( 1.7813504266, 1.6178237031, 0.8162655711), + newCircle(-0.1985249206, -0.8343333301, 0.0538864941), + newCircle(-1.7011985145, -0.1263820964, 0.4776976918), + newCircle(-0.4319462812, 1.4104420482, 0.7886291537), + newCircle( 0.2178372997, -0.9499557344, 0.0357871187), + newCircle(-0.6294854565, -1.3078893852, 0.7653357688), + newCircle( 1.7952608455, 0.6281269104, 0.2727652452), + newCircle( 1.4168575317, 1.0683357171, 1.1016025378), + newCircle( 1.4637371396, 0.9463877418, 1.1846214562), + newCircle(-0.5263668798, 1.7315156631, 1.4428514068), + newCircle(-1.2197352481, 0.9144146579, 1.0727263474), + newCircle(-0.1389358881, 0.1092805780, 0.7350208828), + newCircle( 1.5293954595, 0.0030278255, 1.2472867347), + newCircle(-0.5258728625, 1.3782633069, 1.3495508831), + newCircle(-0.1403562064, 0.2437382535, 1.3804956588), + newCircle( 0.8055826339, -0.0482092025, 0.3327165165), + newCircle(-0.6311979224, 0.7184578971, 0.2491045282), + newCircle( 1.4685857879, -0.8347049536, 1.3670667538), + newCircle(-0.6855727502, 1.6465021616, 1.0593087096), + newCircle( 0.0152957411, 0.0638919221, 0.9771215985) +} + +-- Approximate the total area covered by the union of all circles using horizontal +-- scanlines. + +-- Arguments: +-- `precision`: vertical step size (smaller = more accurate but slower) +-- `c`: table of circle objects `{x, y, r}` +local function areaScan(precision, c) + -- For a given circle and horizontal line at height `y`, + -- compute the x-interval [left, right] where the line intersects the circle. + -- Returns a table {x = left, y = right} + -- (note: 'y' here is actually the right x-bound!) + local function section(c_, y) + -- Half-width of the chord at height y (using Pythagoras: r^2 = dx^2 + dy^2) + local dr = math.sqrt(c_.r^2-(y-c_.y)^2) + return {x = c_.x - dr, y = c_.x + dr} -- left and right x-coordinates + end + + -- Collect all top (y + r) and bottom (y - r) edges of circles to find vertical bounds + local ys = moses.map(c, function(v) + return v.y + v.r -- top edge of each circle + end) + ys = moses.append(ys, moses.map(c, function(v) + return v.y - v.r -- bottom edge of each circle + end)) + + -- Determine the discrete scanline range: + -- Convert min/max y-values into integer indices scaled by `precision` + -- (Use `table.unpack` for Lua 5.2+; use `unpack` for LuaJIT -- + -- see commented alternatives) + local mins = math.floor(math.min(table.unpack(ys))/precision) -- comment this line first to run on LuaJIT + -- local mins = math.floor(math.min(unpack(ys)) / precision) -- uncomment this line to run on LuaJIT + local maxs = math.ceil(math.max(table.unpack(ys))/precision) -- comment this line first to run on LuaJIT + -- local maxs = math.ceil(math.max(unpack(ys)) / precision) -- uncomment this line to run on LuaJIT + + local total = 0 -- Accumulates total horizontal length across all scanlines + + -- Generate actual y-coordinates for each scanline + local coords = moses.map(moses.range(mins, maxs+1), function(x) + return precision * x + end) + + -- Sweep horizontally across each scanline + for _, y in ipairs(coords) do + local right = -math.huge -- Tracks the rightmost `x` covered so far in this scanline + + -- Step 1: Select only circles that intersect the current horizontal line at y + local intervals = moses.select(c, function(c_) + return math.abs(y-c_.y) < c_.r -- true if `|dy| < radius` → intersection exists + end) + + -- Step 2: Convert each intersecting circle into its x-interval (chord) + intervals = moses.map(intervals, function(c_) + return section(c_, y) + end) + + -- Step 3: Sort intervals by their left endpoint (x) + table.sort(intervals, function(c1, c2) + return c1.x < c2.x + end) + + -- Step 4: Merge overlapping intervals and accumulate total covered width + for _, interval in ipairs(intervals) do + -- Only add the portion of the interval not already covered + if interval.y > right then + -- Add uncovered segment: from `max(left, previous_right`) to `current_right` + total = total + interval.y - math.max(interval.x, right) + right = interval.y -- update the rightmost covered x + end + end + end + + -- Multiply total horizontal length by vertical step size to get approximate area + return total * precision +end + +-- Compute and print the approximate union area of all circles with high precision (1e-5) +print("Approximate area: "..areaScan(1e-5, circles)) diff --git a/Task/Total-circles-area/Phix/total-circles-area.phix b/Task/Total-circles-area/Phix/total-circles-area.phix index 7b5ba16821..a388a8a6c0 100644 --- a/Task/Total-circles-area/Phix/total-circles-area.phix +++ b/Task/Total-circles-area/Phix/total-circles-area.phix @@ -1,55 +1,53 @@ -(phixonline)--> - with javascript_semantics - constant circles = {{ 1.6417233788, 1.6121789534, 0.0848270516}, - {-1.4944608174, 1.2077959613, 1.1039549836}, - { 0.6110294452, -0.6907087527, 0.9089162485}, - { 0.3844862411, 0.2923344616, 0.2375743054}, - {-0.2495892950, -0.3832854473, 1.0845181219}, - { 1.7813504266, 1.6178237031, 0.8162655711}, - {-0.1985249206, -0.8343333301, 0.0538864941}, - {-1.7011985145, -0.1263820964, 0.4776976918}, - {-0.4319462812, 1.4104420482, 0.7886291537}, - { 0.2178372997, -0.9499557344, 0.0357871187}, - {-0.6294854565, -1.3078893852, 0.7653357688}, - { 1.7952608455, 0.6281269104, 0.2727652452}, - { 1.4168575317, 1.0683357171, 1.1016025378}, - { 1.4637371396, 0.9463877418, 1.1846214562}, - {-0.5263668798, 1.7315156631, 1.4428514068}, - {-1.2197352481, 0.9144146579, 1.0727263474}, - {-0.1389358881, 0.1092805780, 0.7350208828}, - { 1.5293954595, 0.0030278255, 1.2472867347}, - {-0.5258728625, 1.3782633069, 1.3495508831}, - {-0.1403562064, 0.2437382535, 1.3804956588}, - { 0.8055826339, -0.0482092025, 0.3327165165}, - {-0.6311979224, 0.7184578971, 0.2491045282}, - { 1.4685857879, -0.8347049536, 1.3670667538}, - {-0.6855727502, 1.6465021616, 1.0593087096}, - { 0.0152957411, 0.0638919221, 0.9771215985}}, - {x,y,r} = columnize(circles), - r2 = sq_power(r,2) +with javascript_semantics +constant circles = {{ 1.6417233788, 1.6121789534, 0.0848270516}, + {-1.4944608174, 1.2077959613, 1.1039549836}, + { 0.6110294452, -0.6907087527, 0.9089162485}, + { 0.3844862411, 0.2923344616, 0.2375743054}, + {-0.2495892950, -0.3832854473, 1.0845181219}, + { 1.7813504266, 1.6178237031, 0.8162655711}, + {-0.1985249206, -0.8343333301, 0.0538864941}, + {-1.7011985145, -0.1263820964, 0.4776976918}, + {-0.4319462812, 1.4104420482, 0.7886291537}, + { 0.2178372997, -0.9499557344, 0.0357871187}, + {-0.6294854565, -1.3078893852, 0.7653357688}, + { 1.7952608455, 0.6281269104, 0.2727652452}, + { 1.4168575317, 1.0683357171, 1.1016025378}, + { 1.4637371396, 0.9463877418, 1.1846214562}, + {-0.5263668798, 1.7315156631, 1.4428514068}, + {-1.2197352481, 0.9144146579, 1.0727263474}, + {-0.1389358881, 0.1092805780, 0.7350208828}, + { 1.5293954595, 0.0030278255, 1.2472867347}, + {-0.5258728625, 1.3782633069, 1.3495508831}, + {-0.1403562064, 0.2437382535, 1.3804956588}, + { 0.8055826339, -0.0482092025, 0.3327165165}, + {-0.6311979224, 0.7184578971, 0.2491045282}, + { 1.4685857879, -0.8347049536, 1.3670667538}, + {-0.6855727502, 1.6465021616, 1.0593087096}, + { 0.0152957411, 0.0638919221, 0.9771215985}}, + {x,y,r} = columnize(circles), + r2 = sq_power(r,2) - atom xMin = min(sq_sub(x,r)), - xMax = max(sq_add(x,r)), - yMin = min(sq_sub(y,r)), - yMax = max(sq_add(y,r)), - boxSide = 500, - dx = (xMax - xMin) / boxSide, - dy = (yMax - yMin) / boxSide, - count = 0 - sequence cxs = {} - for s=1 to boxSide do - atom py = yMin + s * dy - sequence cy = sq_power(sq_sub(py,y),2) - for c=1 to boxSide do - if s=1 then - atom px = xMin + c * dx - cxs = append(cxs,sq_power(sq_sub(px,x),2)) - end if - sequence cx = cxs[c] - for i=1 to length(circles) do - if cx[i]+cy[i]<=r2[i] then count+=1 exit end if - end for - end for - end for - printf(1,"Approximate area = %.9f\n",{count * dx * dy}) - - function totient(integer n) - integer tot = n, i = 2 - while i*i<=n do - if mod(n,i)=0 then - while true do - n /= i - if mod(n,i)!=0 then exit end if - end while - tot -= tot/i - end if - i += iff(i=2?1:2) - end while - if n>1 then - tot -= tot/n - end if - return tot - end function - - printf(1," n phi prime\n") - printf(1," --------------\n") - integer count = 0 - for n=1 to 25 do - integer tot = totient(n), - prime = (n-1=tot) - count += prime - string isp = iff(prime?"true":"false") - printf(1,"%2d %2d %s\n",{n,tot,isp}) - end for - printf(1,"\nNumber of primes up to 25 = %d\n",count) - for n=26 to 100000 do - count += (totient(n)=n-1) - if find(n,{100,1000,10000,100000}) then - printf(1,"Number of primes up to %-6d = %d\n",{n,count}) - end if - end for - - with javascript_semantics - constant task = """ - alpha a - beta b or v - gamma g - delta d - epsilon e (but not ee) - zeta z - eta h or ee (but not ch, kh, ph, rh or th) - theta th - iota i or j - kappa c, k, q or ck (but not ch and kh) - lambda l - mu m - nu n - xi x - omicron o (but not oo) - pi p (but not ph or ps) - rho r or rh - sigma s (but not ps) - tau t (but not th) - upsilon u or y - phi f or ph - chi ch or kh - psi ps - omega w or oo - """ - function rules() - sequence replacements = split(task,"\n"), - suborder = {{" ",49},{",",50},{".",51},{"\n",52}}, - {rs,ir} = columnize(suborder), - names = reinstate(repeat(0,52),ir,rs), - done = {} - for i,s in replacements do - s = substitute_all(s,{" or"," and"},{",",","}) - integer k = match("(but not ",s) - sequence nots = {} - if k then - assert(s[$]=')' and s[k-1]=' ') - nots = split(s[k+9..$-1],", ") - s = s[1..k-2] - end if - s = split(substitute(s,",","")," ") - names[i] = "<" & proper(s[1]) & ">" - names[i+24] = "<" & s[1] & ">" - s = s[2..$] - k = max(apply(s&nots,length)) - replacements[i] = {k,i,reverse(s),nots} - end for - replacements = sort(replacements) - while length(replacements) do - for i=length(replacements) to 1 by -1 do - bool missing = false - for s in replacements[i][4] do - missing += not find(s,done) - end for - if not missing then - integer g = replacements[i][2] - for s in replacements[i][3] do - done = append(done,s) - suborder &= {{s,g+24}} - s[1] = upper(s[1]) - suborder &= {{s,g}} - end for - replacements[i..i] = {} - end if - end for - end while - return {columnize(suborder),names} - end function +with javascript_semantics +constant task = """ +alpha a +beta b or v +gamma g +delta d +epsilon e (but not ee) +zeta z +eta h or ee (but not ch, kh, ph, rh or th) +theta th +iota i or j +kappa c, k, q or ck (but not ch and kh) +lambda l +mu m +nu n +xi x +omicron o (but not oo) +pi p (but not ph or ps) +rho r or rh +sigma s (but not ps) +tau t (but not th) +upsilon u or y +phi f or ph +chi ch or kh +psi ps +omega w or oo +""" +function rules() + sequence replacements = split(task,"\n"), + suborder = {{" ",49},{",",50},{".",51},{"\n",52}}, + {rs,ir} = columnize(suborder), + names = reinstate(repeat(0,52),ir,rs), + done = {} + for i,s in replacements do + s = substitute_all(s,{" or"," and"},{",",","}) + integer k = match("(but not ",s) + sequence nots = {} + if k then + assert(s[$]=')' and s[k-1]=' ') + nots = split(s[k+9..$-1],", ") + s = s[1..k-2] + end if + s = split(substitute(s,",","")," ") + names[i] = "<" & proper(s[1]) & ">" + names[i+24] = "<" & s[1] & ">" + s = s[2..$] + k = max(apply(s¬s,length)) + replacements[i] = {k,i,reverse(s),nots} + end for + replacements = sort(replacements) + while length(replacements) do + for i=length(replacements) to 1 by -1 do + bool missing = false + for s in replacements[i][4] do + missing += not find(s,done) + end for + if not missing then + integer g = replacements[i][2] + for s in replacements[i][3] do + done = append(done,s) + suborder &= {{s,g+24}} + s[1] = upper(s[1]) + suborder &= {{s,g}} + end for + replacements[i..i] = {} + end if + end for + end while + return {columnize(suborder),names} +end function - sequence {{sub,rep},names} = rules(), - gulp = utf8_to_utf32("ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ"& - "αβγδεζηθικλμνξοπρστυφχψω ,.\n"), - text = """ - The quick brown fox jumped over the lazy dog. +sequence {{sub,rep},names} = rules(), +gulp = utf8_to_utf32("ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ"& + "αβγδεζηθικλμνξοπρστυφχψω ,.\n"), +text = """ +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. +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.""" - string g = utf32_to_utf8(extract(gulp,substitute_all(text,sub,rep))) - g = substitute_all(g,{"σ ","σ,"},{"ς ","ς,"}) - printf(1,"%s\n=>\n%s\n\n",{text,g}) - string thedog = "the dog" - g = join(extract(names,substitute_all(thedog,sub,rep)),"") - printf(1,"%s\n=>\n%s\n\n",{thedog,g}) - Indent tree conversion (pretty-print version) +!----------------------------------------------------------------------- +module tree_m + implicit none + + !-------------- nested (recursive) representation ------------------ + type :: nest_node + character(len=:), allocatable :: name + type(nest_node), allocatable :: children(:) + contains + procedure :: to_string => nest_to_string + procedure :: to_indent => nest_to_indent + procedure :: print_nest + end type nest_node + + !-------------- flat (indent-level) representation --------------- + type :: indent_node + integer :: level = 0 + character(len=:), allocatable :: name + end type indent_node + +contains + +!======================================================================= +! nest -> character string (compact bracket form) +!======================================================================= + recursive function nest_to_string(this) result(s) + class(nest_node), intent(in) :: this + character(len=:), allocatable :: s + integer :: i + s = trim(this%name) + if (allocated(this%children)) then + s = s // '(' + do i = 1, size(this%children) + s = s // trim(this%children(i)%to_string()) + if (i < size(this%children)) s = s // ',' + end do + s = s // ')' + end if + end function nest_to_string + +!======================================================================= +! pretty print nest tree in outline form +!======================================================================= + recursive subroutine print_nest(this, depth) + class(nest_node), intent(in) :: this + integer, intent(in), optional :: depth + integer :: d, i + d = 0; if (present(depth)) d = depth + print '(a)', repeat(' ',d) // trim(this%name) + if (allocated(this%children)) then + do i = 1, size(this%children) + call this%children(i)%print_nest(d+1) + end do + end if + end subroutine print_nest + +!======================================================================= +! nest -> list of indent_node (depth-first walk) +!======================================================================= + recursive subroutine nest_to_indent(this, list, depth) + class(nest_node), intent(in) :: this + type(indent_node), allocatable, intent(inout) :: list(:) + integer, intent(in), optional :: depth + integer :: d, n + d = 0; if (present(depth)) d = depth + if (.not. allocated(list)) allocate(list(0)) + n = size(list) + list = [list, indent_node(d, this%name)] + if (allocated(this%children)) then + do n = 1, size(this%children) + call this%children(n)%to_indent(list, d+1) + end do + end if + end subroutine nest_to_indent + +!======================================================================= +! indent list -> nest tree +!======================================================================= + function indent_to_nest(list) result(root) + type(indent_node), intent(in) :: list(:) + type(nest_node), pointer :: root + + type :: tagged + type(nest_node), allocatable :: node + integer :: level = 0 + end type tagged + + type(tagged), allocatable :: stack(:) + integer :: i, top + + top = 0 + allocate(stack(0)) + + do i = 1, size(list) + block + type(tagged),target :: fresh + allocate(fresh%node) + fresh%node%name = list(i)%name + fresh%level = list(i)%level + + do while (top > 0 .and. stack(top)%level >= list(i)%level) + top = top - 1 + end do + + if (top == 0) then + root => fresh%node + else + if (.not. allocated(stack(top)%node%children)) & + allocate(stack(top)%node%children(0)) + stack(top)%node%children = [stack(top)%node%children, fresh%node] + end if + + top = top + 1 + if (top > size(stack)) stack = [stack, fresh] + stack(top) = fresh + end block + end do + end function indent_to_nest + +!======================================================================= +! pretty print indent list +!======================================================================= + subroutine print_indent(list) + type(indent_node), intent(in) :: list(:) + integer :: i + do i = 1, size(list) + print '(i0,1x,a)', list(i)%level, list(i)%name + end do + end subroutine print_indent + +end module tree_m + +!####################################################################### +! Demonstration +!####################################################################### +program demo + use tree_m + implicit none + type(nest_node), pointer :: root, final + type(indent_node), allocatable :: flat(:) + + !------------------------------------------------------------------ + ! 1. Build the example tree by hand (nest form) + !------------------------------------------------------------------ + allocate(root) + root%name = "RosettaCode" + allocate(root%children(2)) + + root%children(1)%name = "rocks" + allocate(root%children(1)%children(3)) + root%children(1)%children(1)%name = "code" + root%children(1)%children(2)%name = "comparison" + root%children(1)%children(3)%name = "wiki" + + root%children(2)%name = "mocks" + allocate(root%children(2)%children(1)) + root%children(2)%children(1)%name = "trolling" + + !------------------------------------------------------------------ + ! 2. Initial nest form (outline) + !------------------------------------------------------------------ + print *, "==Nest form==" + call root%print_nest() + print * + + !------------------------------------------------------------------ + ! 3. Convert to indent form and display + !------------------------------------------------------------------ + call root%to_indent(flat) + print *, "==Indent form==" + call print_indent(flat) + print * + + !------------------------------------------------------------------ + ! 4. Convert back to nest form and display (outline) + !------------------------------------------------------------------ + final => indent_to_nest(flat) + print *, "==Nest form==" + call final%print_nest() + print * + print*, 'They are equal. There is only one data structure that is traversed differently' +end program demo diff --git a/Task/Tree-datastructures/FreeBASIC/tree-datastructures.basic b/Task/Tree-datastructures/FreeBASIC/tree-datastructures.basic new file mode 100644 index 0000000000..c598a0a790 --- /dev/null +++ b/Task/Tree-datastructures/FreeBASIC/tree-datastructures.basic @@ -0,0 +1,68 @@ +Function AnidadoConSangrado(anidado As String) As String + Dim As String salida = "", linea = "" + Dim As Integer i = 1, ind = 0 + + While i <= Len(anidado) + If Mid(anidado, i, 1) = Chr(10) Or Mid(anidado, i, 1) = Chr(13) Then + If linea <> "" Then + ind = 0 + While ind < Len(linea) And Mid(linea, ind + 1, 1) = "." + ind += 1 + Wend + salida &= Str(ind \ 4) & " " & Mid(linea, ind + 1) & Chr(10) + linea = "" + End If + Else + linea &= Mid(anidado, i, 1) + End If + i += 1 + Wend + + If linea <> "" Then + ind = 0 + While ind < Len(linea) And Mid(linea, ind + 1, 1) = "." + ind += 1 + Wend + salida &= Str(ind \ 4) & " " & Mid(linea, ind + 1) & Chr(10) + End If + + Return salida +End Function + +Function SangradoAAnidado(sangrado As String) As String + Dim As String salida = "", linea = "" + Dim As Integer i = 1 + Dim As Integer ind, nivel + + While i <= Len(sangrado) + If Mid(sangrado, i, 1) = Chr(10) Or Mid(sangrado, i, 1) = Chr(13) Then + If linea <> "" Then + ind = Instr(linea, " ") + nivel = Val(Mid(linea, 1, ind - 1)) + salida &= String(nivel * 4, ".") & Mid(linea, ind + 1) & Chr(10) + linea = "" + End If + Else + linea &= Mid(sangrado, i, 1) + End If + i += 1 + Wend + + If linea <> "" Then + ind = Instr(linea, " ") + nivel = Val(Mid(linea, 1, ind - 1)) + salida &= String(nivel * 4, ".") & Mid(linea, ind + 1) & Chr(10) + End If + + Return salida +End Function + +Dim As String AnidadoInicial = "Rosetta Code" & Chr(10) & "....rocks" & Chr(10) & "........code" & Chr(10) & "........comparison" & Chr(10) & "........wiki" & Chr(10) & "....mocks" & Chr(10) & "........trolling" & Chr(10) +Print AnidadoInicial +Dim As String sangrado = AnidadoConSangrado(AnidadoInicial) +Print sangrado +Dim As String anidado = SangradoAAnidado(sangrado) +Print anidado +Print "Initial = Restored: "; Iif(AnidadoInicial = anidado, "True", "False") + +Sleep diff --git a/Task/Tree-datastructures/Julia/tree-datastructures.julia b/Task/Tree-datastructures/Julia/tree-datastructures.jl similarity index 100% rename from Task/Tree-datastructures/Julia/tree-datastructures.julia rename to Task/Tree-datastructures/Julia/tree-datastructures.jl diff --git a/Task/Tree-datastructures/M2000-Interpreter/tree-datastructures.m2000 b/Task/Tree-datastructures/M2000-Interpreter/tree-datastructures.m2000 new file mode 100644 index 0000000000..f2716ec3bf --- /dev/null +++ b/Task/Tree-datastructures/M2000-Interpreter/tree-datastructures.m2000 @@ -0,0 +1,88 @@ +module Tree_datastructures (a$){ + terminal=(,) + document b$, all$=a$ + report a$ + nl$={ + } + tree=@MakeTree(a$) + traverseTree(tree) + report b$ + all$=b$ + clear b$ + TraverseTreeIndent(tree) + report b$ + all$=b$ + print b$=a$ + all$=(b$=a$)+nl$ + clipboard all$ + end + sub TraverseTree(t as array, Level=1) + b$=Level+" "+t#val$(0)+nl$ + local i + for i=1 to len(t)-1 + if t#val(i) is terminal else TraverseTree(t#val(i), Level+1) + next + end sub + sub TraverseTreeIndent(t as array, Level=0) + b$=string$("....", Level) +t#val$(0)+nl$ + local i + for i=1 to len(t)-1 + if t#val(i) is terminal else TraverseTreeIndent(t#val(i), Level+1) + next + end sub + function MakeTree(a$) + local a$(), c$ + a$()=piece$(a$, nl$) + local child=terminal, tree=(a$(0),terminal) + local Level=2, i, j + flush + for i=1 to len(a$())-1 + if len(a$(i))=0 then continue + for j=1 to len(a$(i)) div 2 + if left$(a$(i), j*4)<>string$(".", j*4) then + c$=mid$(a$(i), (j-1)*4+1) + exit for + end if + next j + while j; + foreach var line in Regex.Split(nested,NewLine) do + begin + var ind := Regex.Match(line,'[^\.]').Index; + lst.Add($'{ind div 4} {line[ind:]}'); + end; + Result := lst.JoinToString(NewLine); +end; + +function IndentedToNested(indented: string): string; +begin + var lst := new List; + foreach var line in Regex.Split(indented,NewLine) do + begin + var ind := line.IndexOf(' '); + var level := line[:ind].ToInteger; + lst.Add((level*4) * '.' + line[ind+1:]); + end; + Result := lst.JoinToString(NewLine); +end; + +begin + var initialNested := ''' + Rosetta Code + ....rocks + ........code + ........comparison + ........wiki + ....mocks + ........trolling + '''; + Writeln(initialNested,NewLine); + var indented := NestedToIndented(initialNested); + Writeln(indented,NewLine); + var nested := IndentedToNested(indented); + Writeln(nested,NewLine); + Writeln($'Initial = Restored: {initialNested = nested}'); +end. diff --git a/Task/Tree-datastructures/Rust/tree-datastructures.rs b/Task/Tree-datastructures/Rust/tree-datastructures.rs new file mode 100644 index 0000000000..0583ffe856 --- /dev/null +++ b/Task/Tree-datastructures/Rust/tree-datastructures.rs @@ -0,0 +1,125 @@ +#[derive(Debug, Clone, PartialEq)] +pub struct NestTree { + name: String, + children: Vec, +} + +impl NestTree { + pub fn new(name: &str) -> Self { + NestTree { + name: name.to_string(), + children: Vec::new(), + } + } + + pub fn add_child(&mut self, name: &str) { + self.children.push(NestTree::new(name)); + } + + pub fn get_child_mut(&mut self, index: usize) -> Option<&mut NestTree> { + self.children.get_mut(index) + } + + pub fn print(&self) { + self.print_with_level(0); + } + + fn print_with_level(&self, level: usize) { + let indent = " ".repeat(level * 4); + println!("{}{}", indent, self.name); + for child in &self.children { + child.print_with_level(level + 1); + } + } + + pub fn name(&self) -> &str { + &self.name + } + + pub fn children(&self) -> &[NestTree] { + &self.children + } + + pub fn equals(&self, other: &NestTree) -> bool { + self == other + } +} + +pub struct IndentTree { + items: Vec<(i32, String)>, +} + +impl IndentTree { + pub fn new(nest: &NestTree) -> Self { + let mut items = Vec::new(); + items.push((0, nest.name().to_string())); + + let mut indent_tree = IndentTree { items }; + indent_tree.from_nest(nest, 0); + indent_tree + } + + fn from_nest(&mut self, nest: &NestTree, level: i32) { + for child in nest.children() { + self.items.push((level + 1, child.name().to_string())); + self.from_nest(child, level + 1); + } + } + + pub fn print(&self) { + for (level, name) in &self.items { + println!("{} {}", level, name); + } + } + + pub fn to_nest(&self) -> NestTree { + let mut nest = NestTree::new(&self.items[0].1); + self.to_nest_recursive(&mut nest, 1, 0); + nest + } + + fn to_nest_recursive(&self, nest: &mut NestTree, mut pos: usize, level: i32) -> usize { + while pos < self.items.len() && self.items[pos].0 == level + 1 { + nest.add_child(&self.items[pos].1); + let child_index = nest.children().len() - 1; + if let Some(child) = nest.get_child_mut(child_index) { + pos = self.to_nest_recursive(child, pos + 1, level + 1); + } else { + pos += 1; + } + } + pos + } +} + +fn main() { + let mut n = NestTree::new("RosettaCode"); + + // Add children + n.add_child("rocks"); + n.add_child("mocks"); + + // Access children by index to avoid borrowing issues + if let Some(child1) = n.get_child_mut(0) { + child1.add_child("code"); + child1.add_child("comparison"); + child1.add_child("wiki"); + } + + if let Some(child2) = n.get_child_mut(1) { + child2.add_child("trolling"); + } + + println!("Initial nest format:"); + n.print(); + + let i = IndentTree::new(&n); + println!("\nIndent format:"); + i.print(); + + let n2 = i.to_nest(); + println!("\nFinal nest format:"); + n2.print(); + + println!("\nAre initial and final nest formats equal? {}", n.equals(&n2)); +} diff --git a/Task/Tree-datastructures/Yabasic/tree-datastructures.basic b/Task/Tree-datastructures/Yabasic/tree-datastructures.basic new file mode 100644 index 0000000000..5c50c92825 --- /dev/null +++ b/Task/Tree-datastructures/Yabasic/tree-datastructures.basic @@ -0,0 +1,79 @@ +AnidadoInicial$ = "Rosetta Code" + chr$(10) + "....rocks" + chr$(10) + "........code" + chr$(10) + "........comparison" + chr$(10) + "........wiki" + chr$(10) + "....mocks" + chr$(10) + "........trolling" + chr$(10) +print AnidadoInicial$ +sangrado$ = AnidadoConSangrado$(AnidadoInicial$) +print sangrado$ +anidado$ = SangradoAAnidado$(sangrado$) +print anidado$ +print "Initial = Restored: "; +if AnidadoInicial$ = anidado$ then print "True" else print "False": fi +end + +sub AnidadoConSangrado$ (anidado$) + local salida$, linea$, i, ind + + salida$ = "" + linea$ = "" + i = 1 + ind = 0 + + while i <= len(anidado$) + if mid$(anidado$, i, 1) = chr$(10) or mid$(anidado$, i, 1) = chr$(13) then + if linea$ <> "" then + ind = 0 + while ind < len(linea$) and mid$(linea$, ind + 1, 1) = "." + ind = ind + 1 + wend + salida$ = salida$ + str$(ind / 4) + " " + mid$(linea$, ind + 1) + chr$(10) + linea$ = "" + fi + else + linea$ = linea$ + mid$(anidado$, i, 1) + fi + i = i + 1 + wend + + if linea$ <> "" then + ind = 0 + while ind < len(linea$) and mid$(linea$, ind + 1, 1) = "." + ind = ind + 1 + wend + salida$ = salida$ + str$(ind / 4) + " " + mid$(linea$, ind + 1) + chr$(10) + fi + + return salida$ +end sub + +sub SangradoAAnidado$ (sangrado$) + local salida$, linea$, i, ind, tmp$ + + salida$ = "" + linea$ = "" + i = 1 + + while i <= len(sangrado$) + if mid$(sangrado$, i, 1) = chr$(10) or mid$(sangrado$, i, 1) = chr$(13) then + if linea$ <> "" then + ind = instr(linea$, " ") + nivel = val(mid$(linea$, 1, ind - 1)) + tmp$ = "" + for t = 1 to nivel * 4 + tmp$ = tmp$ + "." + next t + //salida$ = salida$ + string$(nivel * 4, ".") + mid$(linea$, ind + 1) + chr$(10) + salida$ = salida$ + tmp$ + mid$(linea$, ind + 1) + chr$(10) + linea$ = "" + fi + else + linea$ = linea$ + mid$(sangrado$, i, 1) + fi + i = i + 1 + wend + + if linea$ <> "" then + ind = instr(linea$, " ") + nivel = val(mid$(linea$, 1, ind - 1)) + salida$ = salida$ + string$(nivel * 4, ".") + mid$(linea$, ind + 1) + chr$(10) + fi + + return salida$ +end sub diff --git a/Task/Tree-datastructures/Zig/tree-datastructures.zig b/Task/Tree-datastructures/Zig/tree-datastructures.zig new file mode 100644 index 0000000000..8591cdf2af --- /dev/null +++ b/Task/Tree-datastructures/Zig/tree-datastructures.zig @@ -0,0 +1,182 @@ +const std = @import("std"); +const ArrayList = std.ArrayList; +const Allocator = std.mem.Allocator; +const print = std.debug.print; + +pub const NestTree = struct { + name: []const u8, + children: ArrayList(NestTree), + allocator: Allocator, + + pub fn init(allocator: Allocator, name: []const u8) !NestTree { + const owned_name = try allocator.dupe(u8, name); + return NestTree{ + .name = owned_name, + .children = ArrayList(NestTree).init(allocator), + .allocator = allocator, + }; + } + + pub fn deinit(self: *NestTree) void { + for (self.children.items) |*child| { + child.deinit(); + } + self.children.deinit(); + self.allocator.free(self.name); + } + + pub fn addChild(self: *NestTree, name: []const u8) !void { + const child = try NestTree.init(self.allocator, name); + try self.children.append(child); + } + + pub fn getChildMut(self: *NestTree, index: usize) ?*NestTree { + if (index >= self.children.items.len) return null; + return &self.children.items[index]; + } + + pub fn printTree(self: *const NestTree) void { + self.printWithLevel(0); + } + + fn printWithLevel(self: *const NestTree, level: usize) void { + var i: usize = 0; + while (i < level * 4) : (i += 1) { + print(" " , .{}); + } + print("{s}\n", .{self.name}); + + for (self.children.items) |*child| { + child.printWithLevel(level + 1); + } + } + + pub fn getName(self: *const NestTree) []const u8 { + return self.name; + } + + pub fn getChildren(self: *const NestTree) []const NestTree { + return self.children.items; + } + + pub fn equals(self: *const NestTree, other: *const NestTree) bool { + if (!std.mem.eql(u8, self.name, other.name)) return false; + if (self.children.items.len != other.children.items.len) return false; + + for (self.children.items, other.children.items) |*child1, *child2| { + if (!child1.equals(child2)) return false; + } + + return true; + } +}; + +pub const IndentTree = struct { + items: ArrayList(IndentItem), + allocator: Allocator, + + const IndentItem = struct { + level: i32, + name: []const u8, + }; + + pub fn init(allocator: Allocator, nest: *const NestTree) !IndentTree { + var items = ArrayList(IndentItem).init(allocator); + const root_name = try allocator.dupe(u8, nest.getName()); + try items.append(IndentItem{ .level = 0, .name = root_name }); + + var indent_tree = IndentTree{ + .items = items, + .allocator = allocator, + }; + + try indent_tree.fromNest(nest, 0); + return indent_tree; + } + + pub fn deinit(self: *IndentTree) void { + for (self.items.items) |item| { + self.allocator.free(item.name); + } + self.items.deinit(); + } + + fn fromNest(self: *IndentTree, nest: *const NestTree, level: i32) !void { + for (nest.getChildren()) |*child| { + const child_name = try self.allocator.dupe(u8, child.getName()); + try self.items.append(IndentItem{ .level = level + 1, .name = child_name }); + try self.fromNest(child, level + 1); + } + } + + pub fn printTree(self: *const IndentTree) void { + for (self.items.items) |item| { + print("{} {s}\n", .{ item.level, item.name }); + } + } + + pub fn toNest(self: *const IndentTree) !NestTree { + if (self.items.items.len == 0) return error.EmptyIndentTree; + + var nest = try NestTree.init(self.allocator, self.items.items[0].name); + _ = try self.toNestRecursive(&nest, 1, 0); + return nest; + } + + fn toNestRecursive(self: *const IndentTree, nest: *NestTree, pos: usize, level: i32) !usize { + var current_pos = pos; + + while (current_pos < self.items.items.len and self.items.items[current_pos].level == level + 1) { + try nest.addChild(self.items.items[current_pos].name); + const child_index = nest.children.items.len - 1; + if (nest.getChildMut(child_index)) |child| { + current_pos = try self.toNestRecursive(child, current_pos + 1, level + 1); + } else { + current_pos += 1; + } + } + + return current_pos; + } +}; + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + const allocator = gpa.allocator(); + + var n = try NestTree.init(allocator, "RosettaCode"); + defer n.deinit(); + + // Add children + try n.addChild("rocks"); + try n.addChild("mocks"); + + // Access children by index to avoid borrowing issues + if (n.getChildMut(0)) |child1| { + try child1.addChild("code"); + try child1.addChild("comparison"); + try child1.addChild("wiki"); + } + + if (n.getChildMut(1)) |child2| { + try child2.addChild("trolling"); + } + + print("Initial nest format:\n" , .{}); + n.printTree(); + + var i = try IndentTree.init(allocator, &n); + defer i.deinit(); + + print("\nIndent format:\n" , .{}); + i.printTree(); + + var n2 = try i.toNest(); + defer n2.deinit(); + + print("\nFinal nest format:\n" , .{} ); + n2.printTree(); + + print("\nAre initial and final nest formats equal? {}\n", .{n.equals(&n2)}); +} diff --git a/Task/Tree-from-nesting-levels/C-sharp/tree-from-nesting-levels.cs b/Task/Tree-from-nesting-levels/C-sharp/tree-from-nesting-levels.cs new file mode 100644 index 0000000000..c6e586132d --- /dev/null +++ b/Task/Tree-from-nesting-levels/C-sharp/tree-from-nesting-levels.cs @@ -0,0 +1,70 @@ +public static class TreeFromNestingLevels +{ + public static void Main() + { + List tests = [[], [1,2,4], [3,1,3,1], [1,2,3,1], [3,2,1,3], [3,3,3,1,1,3,3,3]]; + Console.WriteLine($"{"Input",24} -> {"Nested",-32} -> Round-trip"); + foreach (var test in tests) { + var tree = BuildTree(test); + string input = $"[{string.Join(", ", test)}]"; + string roundTrip = $"[{string.Join(", ", tree.ToList())}]"; + Console.WriteLine($"{input,24} -> {tree,-32} -> {roundTrip}"); + } + } + + private static Tree BuildTree(int[] levels) + { + Tree root = new(0); + Tree current = root; + foreach (int level in levels) { + while (current.Level > level) current = current.Parent; + current = current.Parent.Add(level); + } + return root; + } + + private class Tree + { + public int Level { get; } + public Tree Parent { get; } + private readonly List children = []; + + public Tree(int level, Tree? parent = null) + { + Level = level; + Parent = parent ?? this; + } + + public Tree Add(int level) + { + if (Level == level) return this; + Tree tree = new(Level + 1, this); + children.Add(tree); + return tree.Add(level); + } + + public override string ToString() => children.Count == 0 + ? (Level == 0 ? "[]" : $"{Level}") + : $"[{string.Join(", ", children.Select(c => c.ToString()))}]"; + + public List ToList() + { + List list = []; + ToList(this, list); + return list; + } + + private static void ToList(Tree tree, List list) + { + if (tree.children.Count == 0) { + if (tree.Level > 0) list.Add(tree.Level); + } else { + foreach (Tree child in tree.children) { + ToList(child, list); + } + } + } + + } + +} diff --git a/Task/Tree-from-nesting-levels/Delphi/tree-from-nesting-levels.delphi b/Task/Tree-from-nesting-levels/Delphi/tree-from-nesting-levels.pas similarity index 100% rename from Task/Tree-from-nesting-levels/Delphi/tree-from-nesting-levels.delphi rename to Task/Tree-from-nesting-levels/Delphi/tree-from-nesting-levels.pas diff --git a/Task/Tree-from-nesting-levels/Icon/tree-from-nesting-levels.icon b/Task/Tree-from-nesting-levels/Icon/tree-from-nesting-levels.icon new file mode 100644 index 0000000000..c4f9e4b06e --- /dev/null +++ b/Task/Tree-from-nesting-levels/Icon/tree-from-nesting-levels.icon @@ -0,0 +1,46 @@ +procedure main() + tests := [ [], [1, 2, 4], [3, 1, 3, 1], [1, 2, 3, 1], [3, 2, 1, 3], + [3, 3, 3, 1, 1, 3, 3, 3], [3, 3, 3, 2, 2, 3, 4, 3], + [1, 2, 4, 2, 2, 1] ] + + every test := !tests do + if result := tfnl(test) then + write(limage2(test)," ---> ",limage2(result)) + else + write(limage2(test)," ---> FAILED") +end + +procedure tfnl(levels) + innerlist := [] + level := levels[1] | fail + put(r := [], nested(level,level-1,innerlist)) | fail + /innerlist[1] := r + every i := 2 to *levels & level := levels[i] do + if j := i-1 to 1 by -1 & level >= levels[j] then{ + put(innerlist[j], nested(level,level-levels[j],innerlist)) + /innerlist[i] := innerlist[j] + }else{ + put(r, nested(level,level-1,innerlist)) + /innerlist[i] := r + } + return r +end + +procedure nested(item,level,innerlist) + if level = 0 then{ # special case + put(innerlist,&null) + return item + } + outer := inner := [] + every 2 to level do inner := put(inner,[])[1] + put(inner,item) + put(innerlist,inner) + return outer +end + +procedure limage2(L) + if type(L) ~== "list" then return image(L) + result := "" + every result ||:= limage2(!L) || "," + return ("[" || result[1:-1] || "]") | "[]" +end diff --git a/Task/Tree-from-nesting-levels/Julia/tree-from-nesting-levels.julia b/Task/Tree-from-nesting-levels/Julia/tree-from-nesting-levels.jl similarity index 100% rename from Task/Tree-from-nesting-levels/Julia/tree-from-nesting-levels.julia rename to Task/Tree-from-nesting-levels/Julia/tree-from-nesting-levels.jl diff --git a/Task/Tree-traversal/00-TASK.txt b/Task/Tree-traversal/00-TASK.txt index 21715a2c51..45a296ffaa 100644 --- a/Task/Tree-traversal/00-TASK.txt +++ b/Task/Tree-traversal/00-TASK.txt @@ -27,3 +27,4 @@ The correct output should look like this: ;See also: *   Wikipedia article:   [[wp:Tree traversal|Tree traversal]].

    + diff --git a/Task/Tree-traversal/11l/tree-traversal.11l b/Task/Tree-traversal/11l/tree-traversal.11l index 2a278b81b8..d4cb66b021 100644 --- a/Task/Tree-traversal/11l/tree-traversal.11l +++ b/Task/Tree-traversal/11l/tree-traversal.11l @@ -8,28 +8,28 @@ T Node .left = left .right = right - F preorder(visitor) -> N + F preorder(visitor) -> Void visitor(.data) I .left != N .left.preorder(visitor) I .right != N .right.preorder(visitor) - F inorder(visitor) -> N + F inorder(visitor) -> Void I .left != N .left.inorder(visitor) visitor(.data) I .right != N .right.inorder(visitor) - F postorder(visitor) -> N + F postorder(visitor) -> Void I .left != N .left.postorder(visitor) I .right != N .right.postorder(visitor) visitor(.data) - F preorder2(&d, level = 0) -> N + F preorder2(&d, level = 0) -> Void d[level].append(.data) I .left != N .left.preorder2(d, level + 1) diff --git a/Task/Tree-traversal/Ada/tree-traversal.ada b/Task/Tree-traversal/Ada/tree-traversal.adb similarity index 100% rename from Task/Tree-traversal/Ada/tree-traversal.ada rename to Task/Tree-traversal/Ada/tree-traversal.adb diff --git a/Task/Tree-traversal/Adina/tree-traversal-1.adina b/Task/Tree-traversal/Adina/tree-traversal-1.adina new file mode 100644 index 0000000000..7c04186ab7 --- /dev/null +++ b/Task/Tree-traversal/Adina/tree-traversal-1.adina @@ -0,0 +1,63 @@ +структура узел + данные левая-ветвь правая-ветвь + #:суффикс -узла + +лист значение = + узел значение ложь ложь + +дерево = + узел 1 + узел 2 + узел 4 + лист 7 + ложь + лист 5 + узел 3 + узел 6 + лист 8 + лист 9 + ложь + +прямой дерево действие = + если дерево тогда + действие данные-узла(дерево) + прямой левая-ветвь-узла(дерево) действие + прямой правая-ветвь-узла(дерево) действие + +центрированный дерево действие = + если дерево тогда + центрированный левая-ветвь-узла(дерево) действие + действие данные-узла(дерево) + центрированный правая-ветвь-узла(дерево) действие + +обратный дерево действие = + если дерево тогда + обратный левая-ветвь-узла(дерево) действие + обратный правая-ветвь-узла(дерево) действие + действие данные-узла(дерево) + +поуровневый дерево действие = + пусть цикл + деревья список(дерево) + если не пустой?(деревья) тогда + цикл + применить добавить + цикл/список + для + дерево деревья + #:когда дерево + действие данные-узла(дерево) + список левая-ветвь-узла(дерево) правая-ветвь-узла(дерево) + +запуск имя обход = + вывести имя + обход дерево + функция (данные) + вывести « » + вывести данные + вывести/перенос «» + +запуск «preorder: » прямой +запуск «inorder: » центрированный +запуск «postorder: » обратный +запуск «level-order: » поуровневый diff --git a/Task/Tree-traversal/Adina/tree-traversal-2.adina b/Task/Tree-traversal/Adina/tree-traversal-2.adina new file mode 100644 index 0000000000..a479f360d8 --- /dev/null +++ b/Task/Tree-traversal/Adina/tree-traversal-2.adina @@ -0,0 +1,68 @@ +english() + +struct node + data left right + +leaf x = + node x #f #f + +the-tree = + node 1 + node 2 + node 4 + leaf 7 + #f + leaf 5 + node 3 + node 6 + leaf 8 + leaf 9 + #f + +preorder tree visit = + let loop + $ t tree + when t + visit node-data(t) + loop node-left(t) + loop node-right(t) + +inorder tree visit = + let loop + $ t tree + when t + loop node-left(t) + visit node-data(t) + loop node-right(t) + +postorder tree visit = + let loop + $ t tree + when t + loop node-left(t) + loop node-right(t) + visit node-data(t) + +levelorder tree visit = + let loop + $ trees + list tree + unless null?(trees) + loop + append* + for/list + (t trees) #:when t + visit node-data(t) + list node-left(t) node-right(t) + +run name order = + printf "~a" name + order the-tree + lambda (x) + printf " ~s" x + newline() + +run "preorder: " preorder +run "inorder: " inorder +run "postorder: " postorder +run "level-order: " levelorder diff --git a/Task/Tree-traversal/Crystal/tree-traversal.crystal b/Task/Tree-traversal/Crystal/tree-traversal.cr similarity index 100% rename from Task/Tree-traversal/Crystal/tree-traversal.crystal rename to Task/Tree-traversal/Crystal/tree-traversal.cr diff --git a/Task/Tree-traversal/Delphi/tree-traversal.delphi b/Task/Tree-traversal/Delphi/tree-traversal.pas similarity index 100% rename from Task/Tree-traversal/Delphi/tree-traversal.delphi rename to Task/Tree-traversal/Delphi/tree-traversal.pas diff --git a/Task/Tree-traversal/EMal/tree-traversal.emal b/Task/Tree-traversal/EMal/tree-traversal.emal new file mode 100644 index 0000000000..b7b4b554c4 --- /dev/null +++ b/Task/Tree-traversal/EMal/tree-traversal.emal @@ -0,0 +1,63 @@ +type Node +model + :T value + Node left + Node right + new by generic T, :T ←value do end + fun visit ← <|write(me.value + " ") +end +type Order +enum + int PREORDER, INORDER, POSTORDER, LEVELORDER +end +type Main +fun traverse ← void by Node node, Order order + if node æ null do return end + if order æ Order.PREORDER + node.visit() + traverse(node.left, order) + traverse(node.right, order) + else if order æ Order.INORDER + traverse(node.left, order) + node.visit() + traverse(node.right, order) + else if order æ Order.POSTORDER + traverse(node.left, order) + traverse(node.right, order) + node.visit() + else if order æ Order.LEVELORDER + List queue ← Node[] + queue.insertStart(node) + while not queue.isEmpty() + Node next ← queue.deleteLast() + next.visit() + if next.left ≠ null do queue.insertStart(next.left) end + if next.right ≠ null do queue.insertStart(next.right) end + end + end +end +Node one ← Node(int, 1) +Node two ← Node(int, 2) +Node three ← Node(int, 3) +Node four ← Node(int, 4) +Node five ← Node(int, 5) +Node six ← Node(int, 6) +Node seven ← Node(int, 7) +Node eight ← Node(int, 8) +Node nine ← Node(int, 9) +one.left ← two +one.right ← three +two.left ← four +two.right ← five +three.left ← six +four.left ← seven +six.left ← eight +six.right ← nine +traverse(one, Order.PREORDER) +writeLine() +traverse(one, Order.INORDER) +writeLine() +traverse(one, Order.POSTORDER) +writeLine() +traverse(one, Order.LEVELORDER) +writeLine() diff --git a/Task/Tree-traversal/EasyLang/tree-traversal.easy b/Task/Tree-traversal/EasyLang/tree-traversal.easy index 4495de81f5..91043289f2 100644 --- a/Task/Tree-traversal/EasyLang/tree-traversal.easy +++ b/Task/Tree-traversal/EasyLang/tree-traversal.easy @@ -1,9 +1,7 @@ tree[] = [ 1 2 3 4 5 6 -1 7 -1 -1 -1 8 9 ] # -proc preorder ind . . - if ind > len tree[] or tree[ind] = -1 - return - . +proc preorder ind . + if ind > len tree[] or tree[ind] = -1 : return write " " & tree[ind] preorder ind * 2 preorder ind * 2 + 1 @@ -12,10 +10,8 @@ write "preorder:" preorder 1 print "" # -proc inorder ind . . - if ind > len tree[] or tree[ind] = -1 - return - . +proc inorder ind . + if ind > len tree[] or tree[ind] = -1 : return inorder ind * 2 write " " & tree[ind] inorder ind * 2 + 1 @@ -24,10 +20,8 @@ write "inorder:" inorder 1 print "" # -proc postorder ind . . - if ind > len tree[] or tree[ind] = -1 - return - . +proc postorder ind . + if ind > len tree[] or tree[ind] = -1 : return postorder ind * 2 postorder ind * 2 + 1 write " " & tree[ind] @@ -37,25 +31,23 @@ postorder 1 print "" # global tail head queue[] . -proc initqu n . . +proc initqu n . len queue[] n tail = 1 head = 1 . -proc enqu v . . +proc enqu v . queue[tail] = v tail = (tail + 1) mod1 len queue[] . func dequ . - if head = tail - return -1 - . + if head = tail : return -1 h = head head = (head + 1) mod1 len queue[] return queue[h] . initqu len tree[] -proc levelorder n . . +proc levelorder n . enqu n repeat ind = dequ diff --git a/Task/Tree-traversal/Elena/tree-traversal.elena b/Task/Tree-traversal/Elena/tree-traversal.elena index 4cca79b45f..d3b9fd36c0 100644 --- a/Task/Tree-traversal/Elena/tree-traversal.elena +++ b/Task/Tree-traversal/Elena/tree-traversal.elena @@ -110,12 +110,12 @@ class Node }; } -public program() +public Program() { var tree := Node.new(1, Node.new(2, Node.new(4, Node.new(7)), Node.new(5)), Node.new(3, Node.new(6, Node.new(8), Node.new(9)))); - console.printLine("Preorder :", tree.Preorder); - console.printLine("Inorder :", tree.Inorder); - console.printLine("Postorder :", tree.Postorder); - console.printLine("LevelOrder:", tree.LevelOrder) + Console.printLine("Preorder :", tree.Preorder); + Console.printLine("Inorder :", tree.Inorder); + Console.printLine("Postorder :", tree.Postorder); + Console.printLine("LevelOrder:", tree.LevelOrder) } diff --git a/Task/Tree-traversal/Elixir/tree-traversal.elixir b/Task/Tree-traversal/Elixir/tree-traversal.ex similarity index 100% rename from Task/Tree-traversal/Elixir/tree-traversal.elixir rename to Task/Tree-traversal/Elixir/tree-traversal.ex diff --git a/Task/Tree-traversal/Euphoria/tree-traversal.euphoria b/Task/Tree-traversal/Euphoria/tree-traversal.eu similarity index 100% rename from Task/Tree-traversal/Euphoria/tree-traversal.euphoria rename to Task/Tree-traversal/Euphoria/tree-traversal.eu diff --git a/Task/Tree-traversal/Fortran/tree-traversal-4.f b/Task/Tree-traversal/Fortran/tree-traversal-4.f new file mode 100644 index 0000000000..d18251937c --- /dev/null +++ b/Task/Tree-traversal/Fortran/tree-traversal-4.f @@ -0,0 +1,223 @@ +! ============================================================================= +! tree_traversal.f90 +! +! Demonstrates four classic binary-tree traversal algorithms on the following +! hand-built nine-node tree: +! +! 1 +! / \ +! 2 3 +! / \ / +! 4 5 6 +! / / \ +! 7 8 9 +! +! Expected output: +! preorder: 1 2 4 7 5 3 6 8 9 +! inorder: 7 4 2 5 1 8 6 9 3 +! postorder: 7 4 5 2 8 9 6 3 1 +! level-order: 1 2 3 4 5 6 7 8 9 +! ============================================================================= +program tree_traversal + implicit none + + ! ------------------------------------------------------------------ + ! node -- one element of the binary tree. + ! val : the integer payload stored at this node + ! left : pointer to the left child (null => no left child) + ! right : pointer to the right child (null => no right child) + ! ------------------------------------------------------------------ + type :: node + integer :: val + type(node), pointer :: left => null() + type(node), pointer :: right => null() + end type node + + ! ------------------------------------------------------------------ + ! node_ptr -- thin wrapper that lets us build an array of pointers. + ! Fortran does not allow "type(node), pointer :: arr(n)" directly, so + ! we embed the pointer in a derived type and make an array of that. + ! Used only by level_order as a fixed-size FIFO queue. + ! ------------------------------------------------------------------ + type :: node_ptr + type(node), pointer :: p => null() + end type node_ptr + + ! root is the entry point to the whole tree + type(node), pointer :: root + + ! ------------------------------------------------------------------ + ! Build the tree by allocating nodes one at a time and wiring up the + ! parent/child pointer relationships. new_node() allocates a fresh + ! node, stores the value, and nullifies both child pointers. + ! + ! Visual layout of pointer assignments below: + ! + ! root (1) + ! +-- left --> (2) + ! | +-- left --> (4) + ! | | +-- left --> (7) [leaf] + ! | | +-- right --> [none] + ! | +-- right --> (5) [leaf] + ! +-- right --> (3) + ! +-- left --> (6) + ! | +-- left --> (8) [leaf] + ! | +-- right --> (9) [leaf] + ! +-- right --> [none] + ! ------------------------------------------------------------------ + root => new_node(1) ! tree root + root%left => new_node(2) ! depth 1, left subtree + root%right => new_node(3) ! depth 1, right subtree + root%left%left => new_node(4) ! depth 2 + root%left%right => new_node(5) ! depth 2, leaf + root%right%left => new_node(6) ! depth 2 + root%left%left%left => new_node(7) ! depth 3, leaf + root%right%left%left => new_node(8) ! depth 3, leaf + root%right%left%right => new_node(9) ! depth 3, leaf + + ! ------------------------------------------------------------------ + ! Preorder: root -> left subtree -> right subtree + ! Each node is visited BEFORE its children, so the root always + ! appears first and every subtree root appears before its descendants. + ! ------------------------------------------------------------------ + write(*,'(a)', advance='no') 'preorder: ' + call preorder(root) + write(*,*) ! newline after values + + ! ------------------------------------------------------------------ + ! Inorder: left subtree -> root -> right subtree + ! For a binary SEARCH tree this would yield sorted ascending order, + ! but this tree is not a BST -- it merely demonstrates the traversal. + ! ------------------------------------------------------------------ + write(*,'(a)', advance='no') 'inorder: ' + call inorder(root) + write(*,*) + + ! ------------------------------------------------------------------ + ! Postorder: left subtree -> right subtree -> root + ! Each node is visited AFTER both its children, so the root always + ! appears last. Useful for safely deallocating a tree (free children + ! before the parent). + ! ------------------------------------------------------------------ + write(*,'(a)', advance='no') 'postorder: ' + call postorder(root) + write(*,*) + + ! ------------------------------------------------------------------ + ! Level-order (breadth-first): visit every node at depth d before any + ! node at depth d+1, scanning left to right within each level. + ! Implemented iteratively with a FIFO queue rather than recursion. + ! ------------------------------------------------------------------ + write(*,'(a)', advance='no') 'level-order: ' + call level_order(root) + write(*,*) + +contains + + ! ------------------------------------------------------------------ + ! new_node(val) + ! Allocate a new tree node, store val, null both child pointers. + ! Returns a pointer to the newly allocated node. + ! ------------------------------------------------------------------ + function new_node(val) result(n) + integer, intent(in) :: val + type(node), pointer :: n + allocate(n) ! heap-allocate one node record + n%val = val + n%left => null() ! no left child yet + n%right => null() ! no right child yet + end function new_node + + ! ------------------------------------------------------------------ + ! preorder(n) -- recursive, depth-first + ! Visit pattern: SELF left right + ! Base case: if n is not associated (null pointer) do nothing. + ! ------------------------------------------------------------------ + recursive subroutine preorder(n) + type(node), pointer, intent(in) :: n + if (.not. associated(n)) return ! null pointer: nothing to do + write(*,'(i0," ")', advance='no') n%val ! print this node first + call preorder(n%left) ! then recurse into left child + call preorder(n%right) ! then recurse into right child + end subroutine preorder + + ! ------------------------------------------------------------------ + ! inorder(n) -- recursive, depth-first + ! Visit pattern: left SELF right + ! The left subtree is fully exhausted before the current node is + ! printed, and the right subtree is visited last. + ! ------------------------------------------------------------------ + recursive subroutine inorder(n) + type(node), pointer, intent(in) :: n + if (.not. associated(n)) return ! base case: null pointer + call inorder(n%left) ! recurse left first + write(*,'(i0," ")', advance='no') n%val ! print this node second + call inorder(n%right) ! recurse right last + end subroutine inorder + + ! ------------------------------------------------------------------ + ! postorder(n) -- recursive, depth-first + ! Visit pattern: left right SELF + ! Both subtrees are fully exhausted before the current node is + ! printed, so leaves always appear before their parents. + ! ------------------------------------------------------------------ + recursive subroutine postorder(n) + type(node), pointer, intent(in) :: n + if (.not. associated(n)) return ! base case: null pointer + call postorder(n%left) ! recurse left + call postorder(n%right) ! recurse right + write(*,'(i0," ")', advance='no') n%val ! print this node last + end subroutine postorder + + ! ------------------------------------------------------------------ + ! level_order(root_node) -- iterative, breadth-first + ! + ! Algorithm (standard BFS with a FIFO queue): + ! 1. Enqueue the root. + ! 2. While the queue is non-empty: + ! a. Dequeue the front node. + ! b. Print its value. + ! c. Enqueue its left child if it exists. + ! d. Enqueue its right child if it exists. + ! + ! Queue implementation: a fixed-size array of node_ptr wrappers. + ! head = index of the next item to dequeue (front of queue) + ! tail = index of the next free slot (back of queue) + ! The queue holds at most 100 pointers; plenty for this 9-node tree. + ! head < tail means the queue is non-empty. + ! ------------------------------------------------------------------ + subroutine level_order(root_node) + type(node), pointer, intent(in) :: root_node + type(node_ptr) :: queue(100) ! fixed-size array-based FIFO queue + type(node), pointer :: cur ! node being processed this iteration + integer :: head ! index of front element (next dequeue) + integer :: tail ! index of next free slot (next enqueue) + + ! Initialise queue with just the root + head = 1 + tail = 1 + queue(tail)%p => root_node ! enqueue root at position 1 + tail = tail + 1 ! tail now points to next free slot (2) + + ! Process until the queue is drained + do while (head < tail) ! head == tail means queue is empty + cur => queue(head)%p ! dequeue: read the front element + head = head + 1 ! advance head (slot is now "consumed") + + write(*,'(i0," ")', advance='no') cur%val ! visit: print value + + ! Enqueue left child if it exists + if (associated(cur%left)) then + queue(tail)%p => cur%left + tail = tail + 1 + end if + + ! Enqueue right child if it exists + if (associated(cur%right)) then + queue(tail)%p => cur%right + tail = tail + 1 + end if + end do + end subroutine level_order + +end program tree_traversal diff --git a/Task/Tree-traversal/Gleam/tree-traversal.gleam b/Task/Tree-traversal/Gleam/tree-traversal.gleam new file mode 100644 index 0000000000..d027a08ae2 --- /dev/null +++ b/Task/Tree-traversal/Gleam/tree-traversal.gleam @@ -0,0 +1,56 @@ +import gleam/list + +pub type Tree(a) { + Empty + Node(a, Tree(a), Tree(a)) +} + +pub fn preorder(t: Tree(a)) -> List(a) { + case t { + Empty -> [] + Node(v, l, r) -> [v, ..list.append(preorder(l), preorder(r))] + } +} + +pub fn inorder(t: Tree(a)) -> List(a) { + case t { + Empty -> [] + Node(v, l, r) -> list.append(list.append(inorder(l), [v]), inorder(r)) + } +} + +pub fn postorder(t: Tree(a)) -> List(a) { + case t { + Empty -> [] + Node(v, l, r) -> list.append(list.append(postorder(l), postorder(r)), [v]) + } +} + +pub fn levelorder(t: Tree(a)) -> List(a) { + levelorder_helper([t]) +} + +fn levelorder_helper(trees: List(Tree(a))) -> List(a) { + case trees { + [] -> [] + [Empty, ..rest] -> levelorder_helper(rest) + [Node(v, l, r), ..rest] -> [ + v, + ..levelorder_helper(list.append(rest, [l, r])) + ] + } +} + +pub fn main() -> Nil { + let example = + Node( + 1, + Node(2, Node(4, Node(7, Empty, Empty), Empty), Node(5, Empty, Empty)), + Node(3, Node(6, Node(8, Empty, Empty), Node(9, Empty, Empty)), Empty), + ) + echo preorder(example) + echo inorder(example) + echo postorder(example) + echo levelorder(example) + Nil +} diff --git a/Task/Tree-traversal/Julia/tree-traversal.julia b/Task/Tree-traversal/Julia/tree-traversal.jl similarity index 100% rename from Task/Tree-traversal/Julia/tree-traversal.julia rename to Task/Tree-traversal/Julia/tree-traversal.jl diff --git a/Task/Tree-traversal/Kotlin/tree-traversal-1.kotlin b/Task/Tree-traversal/Kotlin/tree-traversal-1.kts similarity index 100% rename from Task/Tree-traversal/Kotlin/tree-traversal-1.kotlin rename to Task/Tree-traversal/Kotlin/tree-traversal-1.kts diff --git a/Task/Tree-traversal/Kotlin/tree-traversal-2.kotlin b/Task/Tree-traversal/Kotlin/tree-traversal-2.kts similarity index 100% rename from Task/Tree-traversal/Kotlin/tree-traversal-2.kotlin rename to Task/Tree-traversal/Kotlin/tree-traversal-2.kts diff --git a/Task/Tree-traversal/OCaml/tree-traversal.ocaml b/Task/Tree-traversal/OCaml/tree-traversal.ml similarity index 100% rename from Task/Tree-traversal/OCaml/tree-traversal.ocaml rename to Task/Tree-traversal/OCaml/tree-traversal.ml diff --git a/Task/Tree-traversal/PascalABC.NET/tree-traversal.pas b/Task/Tree-traversal/PascalABC.NET/tree-traversal.pas new file mode 100644 index 0000000000..caf40fdf02 --- /dev/null +++ b/Task/Tree-traversal/PascalABC.NET/tree-traversal.pas @@ -0,0 +1,61 @@ +type + Node = auto class + data: T; + left,right: Node; + end; + +function ND(data: T; left: Node := nil; right: Node := nil) + := new Node(data,left,right); + +procedure Prefix(r: Node); +begin + if r = nil then + exit; + Print(r.data); + Prefix(r.left); + Prefix(r.right); +end; + +procedure Infix(r: Node); +begin + if r = nil then + exit; + Infix(r.left); + Print(r.data); + Infix(r.right); +end; + +procedure Postfix(r: Node); +begin + if r = nil then + exit; + Postfix(r.left); + Postfix(r.right); + Print(r.data); +end; + +procedure LevelOrder(r: Node); +begin + if r = nil then + exit; + var q := new Queue>; + q.Enqueue(r); + while q.Count > 0 do + begin + var x := q.Dequeue; + Print(x.data); + if x.left <> nil then + q.Enqueue(x.Left); + if x.Right <> nil then + q.Enqueue(x.Right); + end; +end; + +begin + var root := ND(1,ND(2,ND(4,ND(7)),ND(5)),ND(3,ND(6,ND(8),ND(9)))); + Println(root); + Prefix(root); Println; + Infix(root); Println; + Postfix(root); Println; + LevelOrder(root); Println; +end. diff --git a/Task/Tree-traversal/RISC-V-Assembly/tree-traversal.asm b/Task/Tree-traversal/RISC-V-Assembly/tree-traversal.asm new file mode 100644 index 0000000000..6a0d81d847 --- /dev/null +++ b/Task/Tree-traversal/RISC-V-Assembly/tree-traversal.asm @@ -0,0 +1,450 @@ +# riscv assembly raspberry pico2 rp2350 +# program treetrans.s +# connexion putty com3 +/*********************************************/ +/* CONSTANTES */ +/********************************************/ +/* for this file see risc-v task include a file */ +.include "../../constantesRiscv.inc" +.equ HEAPSIZE, 50000 +.equ NBVAL, 9 + +/****************************************************/ +/* MACROS */ +/****************************************************/ +#.include "../ficmacrosriscv.inc" # for debugging only + +/*******************************************/ +/* Structures */ +/********************************************/ +/* structure tree */ + .struct 0 +tree_root: # root pointer + .struct tree_root + 4 +tree_size: # number of element of tree + .struct tree_size + 4 +tree_fin: +/* structure node tree */ + .struct 0 +node_left: # left pointer + .struct node_left + 4 +node_right: # right pointer + .struct node_right + 4 +node_value: # element value + .struct node_value + 4 +node_fin: +/* structure queue*/ + .struct 0 +queue_begin: # next pointer + .struct queue_begin + 4 +queue_end: # element value + .struct queue_end + 4 +queue_fin: +/* structure node queue */ + .struct 0 +queue_node_next: # next pointer + .struct queue_node_next + 4 +queue_node_value: # element value + .struct queue_node_value + 4 +queue_node_fin: + +/*******************************************/ +/* INITIALED DATAS */ +/*******************************************/ +.data +szMessStart: .asciz "Program riscv start.\r\n" +szMessEnd: .asciz "\nProgram end OK.\r\n" +szCariageReturn: .asciz "\r\n" + +szMessInOrder: .asciz "inOrder :\n" +szMessPreOrder: .asciz "PreOrder :\n" +szMessPostOrder: .asciz "PostOrder :\n" +szMessLevelOrder: .asciz "LevelOrder :\n" + +szMessResult: .asciz "Element value : " +.align 2 +ptHeapReserve: .int heapReserve + + +.align 2 +/*******************************************/ +/* UNINITIALED DATA */ +/*******************************************/ +.bss +.align 2 +sConvArea: .skip 24 +stTree: .skip tree_fin # place to structure tree +stQueue: .skip queue_fin # place to structure queue +heapReserve: .skip HEAPSIZE +/********************************...-..--*****/ +/* SECTION CODE */ +/**********************************************/ +.text +.global main + +main: # INFO: main + call stdio_init_all # général init +1: # start loop connexion + li a0,0 # raz argument register + call tud_cdc_n_connected # waiting for USB connection + beqz a0,1b # return code = zero ? + + la a0,szMessStart # message address + call writeString # display message + li s0,1 +1: + la a0,stTree + mv a1,s0 # value + call insertElement + li t0,-1 + beq a0,t0,100f + addi s0,s0,1 + li t0,NBVAL + ble s0,t0,1b + + + la a0,szMessPreOrder + call writeString + la a0,stTree # tree address + lw a0,tree_root(a0) # tree root + la a1,displayElement + call preOrder + + la a0,szMessInOrder + call writeString + la a0,stTree + lw a0,tree_root(a0) + la a1,displayElement + call inOrder + + la a0,szMessPostOrder + call writeString + la a0,stTree + lw a0,tree_root(a0) + la a1,displayElement + call postOrder + + la a0,szMessLevelOrder + call writeString + la a0,stTree + lw a0,tree_root(a0) + la a1,displayElement + call levelOrder + + la a0,szMessEnd + call writeString + call getchar +100: # final loop + j 100b +/******************************************************************/ +/* insert element in the tree */ +/******************************************************************/ +/* a0 contains the address of the tree structure */ +/* a1 contains the value of element */ +/* a0 returns address of element or - 1 if error */ +insertElement: # INFO: insertElement + addi sp, sp, -8 # save registres + sw ra, 0(sp) + sw s0,4(sp) + mv s0,a0 + li a0,node_fin # reservation place one element + call allocHeap + li t0,-1 + beq a0,t0,100f # allocation error + mv t0,a0 # save address + sw a1,node_value(t0) # store value in address heap + sw x0,node_left(t0) # init left pointer with zero + sw x0,node_right(t0) # init right pointer with zero + lw t1,tree_size(s0) # load tree size + bnez t1,1f # 0 element + sw t0,tree_root(s0) # yes -> store in root + j 4f +1: # else search free address in tree + lw t2,tree_root(s0) # start with address root + mv t5,a1 # value node + clz t3,t5 # compute zeroes left bits + addi t3,t3,1 # for sustract the first left bit + sll t5,t5,t3 # shift number in left +2: + slt t4,t5,x0 # is bit31 = 1 + slli t5,t5,1 + bnez t4,3f # is bit31 = 1 + lw t4,node_left(t2) # no store node address in left pointer + bnez t4,21f # equal zero ? + sw t0,node_left(t2) + j 4f +21: + mv t2,t4 # else loop with next node + j 2b +3: + lw t4,node_right(t2) # no store node address in right pointer + bnez t4,31f # equal zero ? + sw t0,node_right(t2) + j 4f +31: + mv t2,t4 # else loop with next node + j 2b # and loop +4: + addi t1,t1,1 + sw t1,tree_size(s0) + mv a0,t0 + +100: + lw ra, 0(sp) + lw s0,4(sp) + addi sp, sp, 8 + ret +/******************************************************************/ +/* display node */ +/******************************************************************/ +/* a0 contains node address */ +displayElement: # INFO: displayElement + addi sp, sp, -8 # reserve stack + sw ra, 0(sp) + sw s0,4(sp) + lw a0,node_value(a0) + la a1,sConvArea + call conversion10S + la a0,szMessResult + call writeString + la a0,sConvArea + call writeString + la a0,szCariageReturn + call writeString +100: + lw ra, 0(sp) + lw s0, 4(sp) + addi sp, sp, 8 + ret +/******************************************************************/ +/* dequeue node */ +/******************************************************************/ +/* a0 contains the address of the queue */ +/* a0 returns 0 if empty else 1 */ +isEmptyQueue1: # INFO: isEmptyQueue + addi sp, sp, -8 # reserve stack + sw ra, 0(sp) + lw a0,queue_begin(a0) + snez a0,a0 +100: + lw ra, 0(sp) + addi sp, sp, 8 +/******************************************************************/ +/* memory allocation on the heap */ +/******************************************************************/ +/* a0 contains the size to allocate */ +/* a0 returns address of memory heap or - 1 if error */ +/* CAUTION : The size of the allowance must be a multiple of 4 */ +allocHeap: # INFO: allocHeap + addi sp, sp, -8 # reserve stack + sw ra, 0(sp) + la t0,ptHeapReserve + lw t1,(t0) # free heap address + add t2,t1,a0 # reserve area on heap + la t3,heapReserve + li t4,HEAPSIZE + add t3,t3,t4 # compute heap end + blt t2,t3,1f # allocation address < heap end ? + li a0,-1 # allocation error + j 100f +1: + sw t2,(t0) # store new start free address heap + mv a0,t1 # return address +100: + lw ra, 0(sp) + addi sp, sp, 8 + ret + +/******************************************************************/ +/* preOrder */ +/******************************************************************/ +/* a0 contains the address of the node */ +/* a1 function address */ +preOrder: # INFO: preOrder + addi sp, sp, -12 # reserve stack + sw ra, 0(sp) + sw s0,4(sp) + sw s1,8(sp) + beqz a0,100f # tree address null ? + beqz a0,100f + mv s0,a0 + mv s1,a1 + jalr a1 # call function + lw a0,node_left(s0) + mv a1,s1 + call preOrder + lw a0,node_right(s0) + mv a1,s1 + call preOrder + +100: + lw ra, 0(sp) + lw s0, 4(sp) + lw s1,8(sp) + addi sp, sp, 12 + ret +/******************************************************************/ +/* inOrder */ +/******************************************************************/ +/* a0 contains the address of the node */ +/* a1 function address */ +inOrder: # INFO: inOrder + addi sp,sp, -12 # reserve stack + sw ra,0(sp) + sw s0,4(sp) + sw s1,8(sp) + beqz a0,100f + mv s0,a0 + mv s1,a1 + lw a0,node_left(s0) + call inOrder + mv a0,s0 + jalr s1 # call function + lw a0,node_right(s0) + mv a1,s1 + call inOrder +100: + lw ra,0(sp) + lw s0,4(sp) + lw s1,8(sp) + addi sp,sp, 12 + ret +/******************************************************************/ +/* postOrder */ +/******************************************************************/ +/* a0 contains the address of the node */ +/* a1 function address */ +postOrder: # INFO: postOrder + addi sp, sp, -12 # reserve stack + sw ra, 0(sp) + sw s0,4(sp) + sw s1,8(sp) + beqz a0,100f + mv s0,a0 + mv s1,a1 + lw a0,node_left(s0) + call postOrder + + lw a0,node_right(s0) + mv a1,s1 + call postOrder + mv a0,s0 + jalr s1 # call function +100: + lw ra, 0(sp) + lw s0, 4(sp) + lw s1,8(sp) + addi sp, sp, 12 + ret +/******************************************************************/ +/* levelOrder */ +/******************************************************************/ +/* a0 contains the address of the node */ +/* a1 function address */ +levelOrder: # INFO: levelOrder + addi sp,sp, -16 # reserve stack + sw ra,0(sp) + sw s0,4(sp) + sw s1,8(sp) + sw s2,12(sp) + beqz a0,100f + mv s0,a0 + mv s1,a1 + la a0,stQueue # adresse queue + mv a1,s0 + call enqueueNode +1: + la a0,stQueue # adresse queue + lw a0,queue_begin(a0) + beqz a0,100f # is queue empty + la a0,stQueue + call dequeueNode + mv s2,a0 # save node + jalr s1 # call function + lw s0,node_left(s2) # left node ok ? + beqz s0,2f # no + la a0,stQueue + mv a1,s0 + call enqueueNode +2: + lw s0,node_right(s2) # right node ok ? + beqz s0,3f # no + la a0,stQueue + mv a1,s0 + call enqueueNode +3: + j 1b # and loop +100: + lw ra,0(sp) + lw s0,4(sp) + lw s1,8(sp) + lw s2,12(sp) + addi sp, sp, 16 + ret + +/******************************************************************/ +/* enqueue node */ +/******************************************************************/ +/* a0 contains the address of the queue */ +/* a1 contains the value of element */ +/* a0 returns address of element or - 1 if error */ +enqueueNode: # INFO: enqueueNode + addi sp, sp, -8 # reserve stack + sw ra, 0(sp) + sw s0,4(sp) + mv s0,a0 + li a0,queue_node_fin # reservation place one element + call allocHeap + li t0,-1 + beq a0,t0,100f # allocation error + mv t0,a0 # save address + sw a1,queue_node_value(t0) # store node value + sw x0,queue_node_next(t0) # init pointer next + lw t1,queue_end(s0) + beqz t1,1f + sw t0,queue_node_next(t1) + j 2f +1: + sw t0,queue_begin(s0) +2: + sw t0,queue_end(s0) + li a0,0 # ok + +100: + lw ra, 0(sp) + lw s0, 4(sp) + addi sp, sp, 8 + ret + +/******************************************************************/ +/* dequeue node */ +/******************************************************************/ +/* a0 contains the address of the queue */ +/* a0 returns address of element or - 1 if error */ +dequeueNode: # INFO: dequeueNode + addi sp, sp, -8 # reserve stack + sw ra, 0(sp) + sw s0,4(sp) + lw t0,queue_begin(a0) + beqz t0,2f + lw t1,queue_node_value(t0) + lw t2,queue_node_next(t0) + sw t2,queue_begin(a0) + bnez t2,1f + sw t2,queue_end(a0) +1: + mv a0,t1 + j 100f +2: + li a0,-1 # empty queue +100: + lw ra, 0(sp) + lw s0, 4(sp) + addi sp, sp, 8 + ret + +/************************************/ +/* file include Fonctions */ +/***********************************/ +/* for this file see risc-v task include a file */ +.include "../../includeFunctions.s" diff --git a/Task/Tree-traversal/REBOL/tree-traversal.rebol b/Task/Tree-traversal/Rebol/tree-traversal.rebol similarity index 100% rename from Task/Tree-traversal/REBOL/tree-traversal.rebol rename to Task/Tree-traversal/Rebol/tree-traversal.rebol diff --git a/Task/Tree-traversal/Coq/tree-traversal.coq b/Task/Tree-traversal/Rocq/tree-traversal.rocq similarity index 100% rename from Task/Tree-traversal/Coq/tree-traversal.coq rename to Task/Tree-traversal/Rocq/tree-traversal.rocq diff --git a/Task/Tree-traversal/Rust/tree-traversal.rs b/Task/Tree-traversal/Rust/tree-traversal.rs new file mode 100644 index 0000000000..1d40a9504c --- /dev/null +++ b/Task/Tree-traversal/Rust/tree-traversal.rs @@ -0,0 +1,160 @@ +#![feature(box_syntax, box_patterns)] + +use std::collections::VecDeque; + +#[derive(Debug)] +struct TreeNode { + value: T, + left: Option>>, + right: Option>>, +} + +enum TraversalMethod { + PreOrder, + InOrder, + PostOrder, + LevelOrder, +} + +impl TreeNode { + pub fn new(arr: &[[i8; 3]]) -> TreeNode { + + let l = match arr[0][1] { + -1 => None, + i @ _ => Some(Box::new(TreeNode::::new(&arr[(i - arr[0][0]) as usize..]))), + }; + let r = match arr[0][2] { + -1 => None, + i @ _ => Some(Box::new(TreeNode::::new(&arr[(i - arr[0][0]) as usize..]))), + }; + + TreeNode { + value: arr[0][0], + left: l, + right: r, + } + } + + pub fn traverse(&self, tr: &TraversalMethod) -> Vec<&TreeNode> { + match tr { + &TraversalMethod::PreOrder => self.iterative_preorder(), + &TraversalMethod::InOrder => self.iterative_inorder(), + &TraversalMethod::PostOrder => self.iterative_postorder(), + &TraversalMethod::LevelOrder => self.iterative_levelorder(), + } + } + + fn iterative_preorder(&self) -> Vec<&TreeNode> { + let mut stack: Vec<&TreeNode> = Vec::new(); + let mut res: Vec<&TreeNode> = Vec::new(); + + stack.push(self); + while !stack.is_empty() { + let node = stack.pop().unwrap(); + res.push(node); + match node.right { + None => {} + Some(box ref n) => stack.push(n), + } + match node.left { + None => {} + Some(box ref n) => stack.push(n), + } + } + res + } + + // From left to right + fn iterative_inorder(&self) -> Vec<&TreeNode> { + let mut stack: Vec<&TreeNode> = Vec::new(); + let mut res: Vec<&TreeNode> = Vec::new(); + let mut opt = Some(self); + + while { + // Descend leftwards + while let Some(tree) = opt { + stack.push(tree); + opt = tree.left.as_deref(); + } + !stack.is_empty() + } { + let tree = stack.pop().unwrap(); + res.push(tree); + opt = tree.right.as_deref(); + } + res + } + + // Left-to-right postorder is same sequence as right-to-left preorder, reversed + fn iterative_postorder(&self) -> Vec<&TreeNode> { + let mut stack: Vec<&TreeNode> = Vec::new(); + let mut res: Vec<&TreeNode> = Vec::new(); + + stack.push(self); + while !stack.is_empty() { + let node = stack.pop().unwrap(); + res.push(node); + match node.left { + None => {} + Some(box ref n) => stack.push(n), + } + match node.right { + None => {} + Some(box ref n) => stack.push(n), + } + } + let rev_iter = res.iter().rev(); + let mut rev: Vec<&TreeNode> = Vec::new(); + for elem in rev_iter { + rev.push(elem); + } + rev + } + + fn iterative_levelorder(&self) -> Vec<&TreeNode> { + let mut queue: VecDeque<&TreeNode> = VecDeque::new(); + let mut res: Vec<&TreeNode> = Vec::new(); + + queue.push_back(self); + while !queue.is_empty() { + let node = queue.pop_front().unwrap(); + res.push(node); + match node.left { + None => {} + Some(box ref n) => queue.push_back(n), + } + match node.right { + None => {} + Some(box ref n) => queue.push_back(n), + } + } + res + } +} + +fn main() { + // Array representation of task tree + let arr_tree = [[1, 2, 3], + [2, 4, 5], + [3, 6, -1], + [4, 7, -1], + [5, -1, -1], + [6, 8, 9], + [7, -1, -1], + [8, -1, -1], + [9, -1, -1]]; + + let root = TreeNode::::new(&arr_tree); + + for method_label in [(TraversalMethod::PreOrder, "pre-order:"), + (TraversalMethod::InOrder, "in-order:"), + (TraversalMethod::PostOrder, "post-order:"), + (TraversalMethod::LevelOrder, "level-order:")] + .iter() { + print!("{}\t", method_label.1); + for n in root.traverse(&method_label.0) { + print!(" {}", n.value); + } + print!("\n"); + } +} diff --git a/Task/Tree-traversal/Rust/tree-traversal.rust b/Task/Tree-traversal/Rust/tree-traversal.rust deleted file mode 100644 index 3fece25e48..0000000000 --- a/Task/Tree-traversal/Rust/tree-traversal.rust +++ /dev/null @@ -1,175 +0,0 @@ -#![feature(box_syntax, box_patterns)] - -use std::collections::VecDeque; - -#[derive(Debug)] -struct TreeNode { - value: T, - left: Option>>, - right: Option>>, -} - -enum TraversalMethod { - PreOrder, - InOrder, - PostOrder, - LevelOrder, -} - -impl TreeNode { - pub fn new(arr: &[[i8; 3]]) -> TreeNode { - - let l = match arr[0][1] { - -1 => None, - i @ _ => Some(Box::new(TreeNode::::new(&arr[(i - arr[0][0]) as usize..]))), - }; - let r = match arr[0][2] { - -1 => None, - i @ _ => Some(Box::new(TreeNode::::new(&arr[(i - arr[0][0]) as usize..]))), - }; - - TreeNode { - value: arr[0][0], - left: l, - right: r, - } - } - - pub fn traverse(&self, tr: &TraversalMethod) -> Vec<&TreeNode> { - match tr { - &TraversalMethod::PreOrder => self.iterative_preorder(), - &TraversalMethod::InOrder => self.iterative_inorder(), - &TraversalMethod::PostOrder => self.iterative_postorder(), - &TraversalMethod::LevelOrder => self.iterative_levelorder(), - } - } - - fn iterative_preorder(&self) -> Vec<&TreeNode> { - let mut stack: Vec<&TreeNode> = Vec::new(); - let mut res: Vec<&TreeNode> = Vec::new(); - - stack.push(self); - while !stack.is_empty() { - let node = stack.pop().unwrap(); - res.push(node); - match node.right { - None => {} - Some(box ref n) => stack.push(n), - } - match node.left { - None => {} - Some(box ref n) => stack.push(n), - } - } - res - } - - // Leftmost to rightmost - fn iterative_inorder(&self) -> Vec<&TreeNode> { - let mut stack: Vec<&TreeNode> = Vec::new(); - let mut res: Vec<&TreeNode> = Vec::new(); - let mut p = self; - - loop { - // Stack parents and right children while left-descending - loop { - match p.right { - None => {} - Some(box ref n) => stack.push(n), - } - stack.push(p); - match p.left { - None => break, - Some(box ref n) => p = n, - } - } - // Visit the nodes with no right child - p = stack.pop().unwrap(); - while !stack.is_empty() && p.right.is_none() { - res.push(p); - p = stack.pop().unwrap(); - } - // First node that can potentially have a right child: - res.push(p); - if stack.is_empty() { - break; - } else { - p = stack.pop().unwrap(); - } - } - res - } - - // Left-to-right postorder is same sequence as right-to-left preorder, reversed - fn iterative_postorder(&self) -> Vec<&TreeNode> { - let mut stack: Vec<&TreeNode> = Vec::new(); - let mut res: Vec<&TreeNode> = Vec::new(); - - stack.push(self); - while !stack.is_empty() { - let node = stack.pop().unwrap(); - res.push(node); - match node.left { - None => {} - Some(box ref n) => stack.push(n), - } - match node.right { - None => {} - Some(box ref n) => stack.push(n), - } - } - let rev_iter = res.iter().rev(); - let mut rev: Vec<&TreeNode> = Vec::new(); - for elem in rev_iter { - rev.push(elem); - } - rev - } - - fn iterative_levelorder(&self) -> Vec<&TreeNode> { - let mut queue: VecDeque<&TreeNode> = VecDeque::new(); - let mut res: Vec<&TreeNode> = Vec::new(); - - queue.push_back(self); - while !queue.is_empty() { - let node = queue.pop_front().unwrap(); - res.push(node); - match node.left { - None => {} - Some(box ref n) => queue.push_back(n), - } - match node.right { - None => {} - Some(box ref n) => queue.push_back(n), - } - } - res - } -} - -fn main() { - // Array representation of task tree - let arr_tree = [[1, 2, 3], - [2, 4, 5], - [3, 6, -1], - [4, 7, -1], - [5, -1, -1], - [6, 8, 9], - [7, -1, -1], - [8, -1, -1], - [9, -1, -1]]; - - let root = TreeNode::::new(&arr_tree); - - for method_label in [(TraversalMethod::PreOrder, "pre-order:"), - (TraversalMethod::InOrder, "in-order:"), - (TraversalMethod::PostOrder, "post-order:"), - (TraversalMethod::LevelOrder, "level-order:")] - .iter() { - print!("{}\t", method_label.1); - for n in root.traverse(&method_label.0) { - print!(" {}", n.value); - } - print!("\n"); - } -} diff --git a/Task/Tree-traversal/Scheme/tree-traversal.ss b/Task/Tree-traversal/Scheme/tree-traversal.scm similarity index 100% rename from Task/Tree-traversal/Scheme/tree-traversal.ss rename to Task/Tree-traversal/Scheme/tree-traversal.scm diff --git a/Task/Tree-traversal/VBScript/tree-traversal.vb b/Task/Tree-traversal/VBScript/tree-traversal.vbs similarity index 100% rename from Task/Tree-traversal/VBScript/tree-traversal.vb rename to Task/Tree-traversal/VBScript/tree-traversal.vbs diff --git a/Task/Trigonometric-functions/Ada/trigonometric-functions.ada b/Task/Trigonometric-functions/Ada/trigonometric-functions.adb similarity index 100% rename from Task/Trigonometric-functions/Ada/trigonometric-functions.ada rename to Task/Trigonometric-functions/Ada/trigonometric-functions.adb diff --git a/Task/Trigonometric-functions/AutoLISP/trigonometric-functions.l b/Task/Trigonometric-functions/AutoLISP/trigonometric-functions.lsp similarity index 100% rename from Task/Trigonometric-functions/AutoLISP/trigonometric-functions.l rename to Task/Trigonometric-functions/AutoLISP/trigonometric-functions.lsp diff --git a/Task/Trigonometric-functions/COBOL/trigonometric-functions.cobol b/Task/Trigonometric-functions/COBOL/trigonometric-functions.cob similarity index 100% rename from Task/Trigonometric-functions/COBOL/trigonometric-functions.cobol rename to Task/Trigonometric-functions/COBOL/trigonometric-functions.cob diff --git a/Task/Trigonometric-functions/Delphi/trigonometric-functions.delphi b/Task/Trigonometric-functions/Delphi/trigonometric-functions.pas similarity index 100% rename from Task/Trigonometric-functions/Delphi/trigonometric-functions.delphi rename to Task/Trigonometric-functions/Delphi/trigonometric-functions.pas diff --git a/Task/Trigonometric-functions/DuckDB/trigonometric-functions.duckdb b/Task/Trigonometric-functions/DuckDB/trigonometric-functions.duckdb new file mode 100644 index 0000000000..a81a0ac0e5 --- /dev/null +++ b/Task/Trigonometric-functions/DuckDB/trigonometric-functions.duckdb @@ -0,0 +1,22 @@ +# degrees to radians +create or replace function radians(degrees) as degrees * pi() / 180.0; + +# radians to degrees +create or replace function degrees(radians) as (radians * 180 / pi()); + +.mode lines +select + sin(-pi() / 6), + cos(3 * pi() / 4), + tan(pi() / 3), + asin(-1 / 2), + acos(-sqrt(2)/2), + atan(sqrt(3)), + + -- Using degrees: + sin(-radians(30)), + cos(radians(135)), + tan(radians(60)), + asin(-1 / 2).degrees(), + acos(-sqrt(2)/2).degrees(), + atan(sqrt(3)).degrees() ; diff --git a/Task/Trigonometric-functions/EasyLang/trigonometric-functions.easy b/Task/Trigonometric-functions/EasyLang/trigonometric-functions.easy index 39f5395c7a..237db0c2a0 100644 --- a/Task/Trigonometric-functions/EasyLang/trigonometric-functions.easy +++ b/Task/Trigonometric-functions/EasyLang/trigonometric-functions.easy @@ -8,7 +8,7 @@ func d2r d . return d * pi / 180 . # -numfmt 4 0 +numfmt 0 4 print sin d & " " & sin r2d r print cos d & " " & cos r2d r print tan d & " " & tan r2d r diff --git a/Task/Trigonometric-functions/Elena/trigonometric-functions.elena b/Task/Trigonometric-functions/Elena/trigonometric-functions.elena index 97c2196a3b..4d137d5ce4 100644 --- a/Task/Trigonometric-functions/Elena/trigonometric-functions.elena +++ b/Task/Trigonometric-functions/Elena/trigonometric-functions.elena @@ -1,24 +1,24 @@ import system'math; import extensions; -public program() +public Program() { - console.printLine("Radians:"); - console.printLine("sin(π/3) = ",(Pi_value/3).sin()); - console.printLine("cos(π/3) = ",(Pi_value/3).cos()); - console.printLine("tan(π/3) = ",(Pi_value/3).tan()); - console.printLine("arcsin(1/2) = ",0.5r.arcsin()); - console.printLine("arccos(1/2) = ",0.5r.arccos()); - console.printLine("arctan(1/2) = ",0.5r.arctan()); - console.printLine(); + Console.printLine("Radians:"); + Console.printLine("sin(π/3) = ",(Pi_value/3).sin()); + Console.printLine("cos(π/3) = ",(Pi_value/3).cos()); + Console.printLine("tan(π/3) = ",(Pi_value/3).tan()); + Console.printLine("arcsin(1/2) = ",0.5r.arcsin()); + Console.printLine("arccos(1/2) = ",0.5r.arccos()); + Console.printLine("arctan(1/2) = ",0.5r.arctan()); + Console.printLine(); - console.printLine("Degrees:"); - console.printLine("sin(60º) = ",60.0r.Radian.sin()); - console.printLine("cos(60º) = ",60.0r.Radian.cos()); - console.printLine("tan(60º) = ",60.0r.Radian.tan()); - console.printLine("arcsin(1/2) = ",0.5r.arcsin().Degree,"º"); - console.printLine("arccos(1/2) = ",0.5r.arccos().Degree,"º"); - console.printLine("arctan(1/2) = ",0.5r.arctan().Degree,"º"); + Console.printLine("Degrees:"); + Console.printLine("sin(60º) = ",60.0r.Radian.sin()); + Console.printLine("cos(60º) = ",60.0r.Radian.cos()); + Console.printLine("tan(60º) = ",60.0r.Radian.tan()); + Console.printLine("arcsin(1/2) = ",0.5r.arcsin().Degree,"º"); + Console.printLine("arccos(1/2) = ",0.5r.arccos().Degree,"º"); + Console.printLine("arctan(1/2) = ",0.5r.arctan().Degree,"º"); - console.readChar() + Console.readChar() } diff --git a/Task/Trigonometric-functions/Elixir/trigonometric-functions.elixir b/Task/Trigonometric-functions/Elixir/trigonometric-functions.ex similarity index 100% rename from Task/Trigonometric-functions/Elixir/trigonometric-functions.elixir rename to Task/Trigonometric-functions/Elixir/trigonometric-functions.ex diff --git a/Task/Trigonometric-functions/Julia/trigonometric-functions.julia b/Task/Trigonometric-functions/Julia/trigonometric-functions.jl similarity index 100% rename from Task/Trigonometric-functions/Julia/trigonometric-functions.julia rename to Task/Trigonometric-functions/Julia/trigonometric-functions.jl diff --git a/Task/Trigonometric-functions/Kotlin/trigonometric-functions.kotlin b/Task/Trigonometric-functions/Kotlin/trigonometric-functions.kts similarity index 100% rename from Task/Trigonometric-functions/Kotlin/trigonometric-functions.kotlin rename to Task/Trigonometric-functions/Kotlin/trigonometric-functions.kts diff --git a/Task/Trigonometric-functions/OCaml/trigonometric-functions.ocaml b/Task/Trigonometric-functions/OCaml/trigonometric-functions.ml similarity index 100% rename from Task/Trigonometric-functions/OCaml/trigonometric-functions.ocaml rename to Task/Trigonometric-functions/OCaml/trigonometric-functions.ml diff --git a/Task/Trigonometric-functions/OoRexx/trigonometric-functions-1.rexx b/Task/Trigonometric-functions/OoRexx/trigonometric-functions-1.rexx index f61d5a3419..f600e33870 100644 --- a/Task/Trigonometric-functions/OoRexx/trigonometric-functions-1.rexx +++ b/Task/Trigonometric-functions/OoRexx/trigonometric-functions-1.rexx @@ -1,18 +1,19 @@ /* REXX --------------------------------------------------------------- * show how the functions can be used * 03.05.2014 Walter Pachl +* 23.12.2024 Walter Pachl *--------------------------------------------------------------------*/ Say 'Default precision:' .locaL~my.rxm~precision() Say 'Default type: ' .locaL~my.rxm~type() -Say 'rxmsin(60) ='rxmsin(60) -- use default precision and type -Say 'rxmsin(1,21,"R")='rxmsin(1,21,'R') -- precision and type specified -Say 'rxmlog(-1) ='rxmlog(-1) -Say 'rxmlog( 0) ='rxmlog( 0) -Say 'rxmlog( 1) ='rxmlog( 1) -Say 'rxmlog( 2) ='rxmlog( 2) - .locaL~my.rxm~precision=50 - .locaL~my.rxm~type='R' +Say 'rxmsin(60,21,"D") ='rxmsin(60,21,"D") -- precision and type specified +Say 'rxmsin(1) ='rxmsin(1) -- use default precision and type +Say 'rxmlog(-1) ='rxmlog(-1) +Say 'rxmlog( 0) ='rxmlog( 0) +Say 'rxmlog( 1) ='rxmlog( 1) +Say 'rxmlog( 2) ='rxmlog( 2) + .locaL~my.rxm~precision=16 + .locaL~my.rxm~type='D' Say 'Changed precision:' .locaL~my.rxm~precision() Say 'Changed type: ' .locaL~my.rxm~type() -Say 'rxmsin(1) ='rxmsin(1) -- use changed precision and type +Say 'rxmsin(90) ='rxmsin(90) -- use changed precision and type ::requires rxm.cls diff --git a/Task/Trigonometric-functions/OoRexx/trigonometric-functions-2.rexx b/Task/Trigonometric-functions/OoRexx/trigonometric-functions-2.rexx index 36970c0521..00ac36d757 100644 --- a/Task/Trigonometric-functions/OoRexx/trigonometric-functions-2.rexx +++ b/Task/Trigonometric-functions/OoRexx/trigonometric-functions-2.rexx @@ -19,12 +19,14 @@ * 24.04.2014 WP arcsin verbessert. courtesy Horst Wegscheider * 28.04.2014 WP run ooRexxDoc * 11.08.2014 WP replace log algorithm with Vladimir Zabrodsky's code +* 23.12.2024 WP changed defauls: precision 16->50 Degrees to Radians +* 23.12.2024 WP made Methods public **********************************************************************/ -.local~my.rxm=.rxm~new(16,"D") +.local~my.rxm=.rxm~new(50,"R") ::Class rxm Public -::Method init +::Method init Public Expose precision type Use Arg precision=(digits()),type='D' @@ -40,13 +42,14 @@ ::attribute type get -::Method arccos +::Method arccos Public /*********************************************************************** * Return arccos(x,precision,type) -- with specified precision * arccos(x) = pi/2 - arcsin(x) ***********************************************************************/ Expose precision type Use Strict Arg x,xprec=(precision),xtype=(type) + xtype=translate(xtype) iprec=xprec+10 Numeric Digits iprec If x=1 Then @@ -68,13 +71,14 @@ Numeric Digits xprec Return (r+0) -::Method arcsin +::Method arcsin Public /*********************************************************************** * Return arcsin(x,precision,type) -- with specified precision * arcsin(x) = x+(x**3)*1/2*3+(x**5)*1*3/2*4*5+(x**7)*1*3*5/2*4*6*7+... ***********************************************************************/ Expose precision type Use Strict Arg x,xprec=(precision),xtype=(type) + xtype=translate(xtype) iprec=xprec+10 Numeric Digits iprec sign=sign(x) @@ -131,7 +135,7 @@ Numeric Digits xprec Return sign*(r+0) -::Method arctan +::Method arctan Public /*********************************************************************** * Return arctan(x,precision,type) -- with specified precision * x=0 -> arctan(x) = 0 @@ -144,6 +148,7 @@ ***********************************************************************/ Expose precision type Use Strict Arg x,xprec=(precision),xtype=(type) + xtype=translate(xtype) iprec=xprec+10 Numeric Digits iprec Select @@ -171,7 +176,7 @@ Numeric Digits xprec Return (r+0) -::Method arsinh +::Method arsinh Public /*********************************************************************** * Return arsinh(x,precision,type) -- with specified precision * arsinh(x) = ln(x+sqrt(x**2+1)) @@ -185,13 +190,14 @@ Numeric Digits xprec Return (r+0) -::Method cos +::Method cos Public /* REXX ************************************************************* * Return cos(x,precision,type) -- with the specified precision * cos(x)=sin(x+pi/2) ********************************************************************/ Expose precision type Use Strict Arg x,xprec=(precision),xtype=(type) + xtype=translate(xtype) iprec=xprec+10 Numeric Digits iprec Select @@ -203,7 +209,7 @@ Numeric Digits xprec Return (r+0) -::Method cosh +::Method cosh Public /* REXX **************************************************************** * Return cosh(x,precision,type) -- with specified precision * cosh(x) = 1+(x**2/2!)+(x**4/4!)+(x**6/6!)+-... @@ -224,13 +230,14 @@ Numeric Digits xprec Return (r+0) -::Method cotan +::Method cotan Public /* REXX ************************************************************* * Return cotan(x,precision,type) -- with the specified precision * cot(x)=cos(x)/sin(x) ********************************************************************/ Expose precision type Use Strict Arg x,xprec=(precision),xtype=(type) + xtype=translate(xtype) iprec=xprec+10 Numeric Digits iprec s=self~sin(x,iprec,xtype) @@ -241,7 +248,7 @@ Numeric Digits xprec Return (r+0) -::Method exp +::Method exp Public /*********************************************************************** * exp(x,precision) returns e**x -- with specified precision * exp(x,precision,base) returns base**x -- with specified precision @@ -288,7 +295,7 @@ Numeric Digits xprec Return (r+0) -::Method log +::Method log Public /*********************************************************************** * log(x,precision) -- returns ln(x) with specified precision * log(x,precision,base) -- returns blog(x) with specified precision @@ -328,7 +335,7 @@ End Return r -::Method ln2p +::Method ln2p Public Parse Arg p Numeric Digits p+10 If p<=1000 Then @@ -344,8 +351,13 @@ ln=newln End -::Method LN2 - +::Method LN2 Public + V = '' + V = V || 0.69314718055994530941723212145817656807 + V = V || 5500134360255254120680009493393621969694 + V = V || 7156058633269964186875420014810205706857 + V = V || 3368552023575813055703267075163507596193 + V = V || 0727570828371435190307038623891673471123350 v='' v=v||0.69314718055994530941723212145817656807 v=v||5500134360255254120680009493393621969694 @@ -375,7 +387,7 @@ v=v||231467232172053401649256872747782344535348 return V -::Method log10 +::Method log10 Public /*********************************************************************** * Return log10(x,prec) specified precision ***********************************************************************/ @@ -386,7 +398,7 @@ v=v||231467232172053401649256872747782344535348 Numeric Digits xprec Return (r+0) -::Method pi +::Method pi Public /* REXX ************************************************************* * Return pi with the specified precision ********************************************************************/ @@ -432,7 +444,7 @@ v=v||231467232172053401649256872747782344535348 Numeric Digits xprec Return (p+0) -::Method power +::Method power Public /*********************************************************************** * power(base,exponent,precision) returns base**exponent * -- with specified precision @@ -449,7 +461,7 @@ v=v||231467232172053401649256872747782344535348 End Else Do /* Exponent is not an integer */ -- Say 'for a negative base ('||b')', --- 'exponent ('c') must be an integer' + 'exponent ('c') must be an integer' Return 'nan' /* Return not a number */ End End @@ -463,7 +475,7 @@ v=v||231467232172053401649256872747782344535348 Return r Return rsign*r -::Method sqrt +::Method sqrt Public /* REXX ************************************************************* * Return sqrt(x,precision) -- with the specified precision ********************************************************************/ @@ -483,7 +495,7 @@ v=v||231467232172053401649256872747782344535348 Numeric Digits xprec Return (r+0) -::Method sin +::Method sin Public /* REXX ************************************************************* * Return sin(x,precision,type) -- with the specified precision * xtype = 'R' (radians, default) 'D' (degrees) 'G' (grades) @@ -491,7 +503,8 @@ v=v||231467232172053401649256872747782344535348 ********************************************************************/ Expose precision type Use Strict Arg x,xprec=(precision),xtype=(type) - iprec=xprec+10 /* internal precision */ + xtype=translate(xtype) + iprec=xprec+20 /* internal precision */ Numeric Digits iprec /* first use pi constant or compute it if necessary */ pi=self~pi(iprec) @@ -539,7 +552,7 @@ v=v||231467232172053401649256872747782344535348 Numeric Digits xprec Return sign*(r+0) -::Method sinh +::Method sinh Public /* REXX **************************************************************** * Return sinh(x,precision) -- with specified precision * sinh(x) = x+(x**3/3!)+(x**5/5!)+(x**7/7!)+-... @@ -561,13 +574,14 @@ v=v||231467232172053401649256872747782344535348 Numeric Digits xprec Return (r+0) -::Method tan +::Method tan Public /* REXX ************************************************************* * Return tan(x,precision,type) -- with the specified precision * tan(x)=sin(x)/cos(x) ********************************************************************/ Expose precision type Use Strict Arg x,xprec=(precision),xtype=(type) + xtype=translate(xtype) iprec=xprec+10 Numeric Digits iprec s=self~sin(x,iprec,xtype) @@ -578,7 +592,7 @@ v=v||231467232172053401649256872747782344535348 Numeric Digits xprec Return (t+0) -::Method tanh +::Method tanh Public /*********************************************************************** * Return tanh(x,precision) -- with specified precision * tanh(x) = sinh(x)/cosh(x) @@ -593,6 +607,7 @@ v=v||231467232172053401649256872747782344535348 ::routine rxmarccos public Use Strict Arg x,xprec=(.my.rxm~precision),xtype=(.my.rxm~type) + xtype=translate(xtype) If datatype(x,'NUM')=0 Then Do -- Say 'Argument 1 must be a number' @@ -616,6 +631,7 @@ v=v||231467232172053401649256872747782344535348 ::routine rxmarcsin public Use Strict Arg x,xprec=(.my.rxm~precision),xtype=(.my.rxm~type) + xtype=translate(xtype) If datatype(x,'NUM')=0 Then Do -- Say 'Argument 1 must be a number' @@ -709,7 +725,6 @@ v=v||231467232172053401649256872747782344535348 -- Say 'Argument 3 must be R, D, or G' Raise Syntax 88.907 array(3,'R, D, or G',xtype) End - return .my.rxm~cos(x,xprec,xtype) ::routine rxmcosh public diff --git a/Task/Trigonometric-functions/PascalABC.NET/trigonometric-functions.pas b/Task/Trigonometric-functions/PascalABC.NET/trigonometric-functions.pas new file mode 100644 index 0000000000..83f732fc74 --- /dev/null +++ b/Task/Trigonometric-functions/PascalABC.NET/trigonometric-functions.pas @@ -0,0 +1,20 @@ +begin + var rad := Pi/3; + var deg := RadToDeg(rad); + Println('=== Radians ==='); + var (Si,Co,Ta) := (Sin(rad),Cos(rad),Tan(rad)); + Println($'Sin({rad}) = {Si}'); + Println($'Cos({rad}) = {Co}'); + Println($'Tan({rad}) = {Ta}'); + Println($'ArcSin({Si}) = {ArcSin(Si)}'); + Println($'ArcCos({Co}) = {ArcCos(Co)}'); + Println($'ArcTan({Ta}) = {ArcTan(Ta)}'); + Println('=== Degrees ==='); + var (SiD,CoD,TaD) := (Sin(DegToRad(deg)),Cos(DegToRad(deg)),Tan(DegToRad(deg))); + Println($'Sin({deg}) = {SiD}'); + Println($'Cos({deg}) = {CoD}'); + Println($'Tan({deg}) = {TaD}'); + Println($'ArcSin({SiD}) = {RadToDeg(ArcSin(SiD))}'); + Println($'ArcCos({CoD}) = {RadToDeg(ArcCos(CoD))}'); + Println($'ArcTan({TaD}) = {RadToDeg(ArcTan(TaD))}'); +end. diff --git a/Task/Trigonometric-functions/Phix/trigonometric-functions.phix b/Task/Trigonometric-functions/Phix/trigonometric-functions.phix index 2b71f21c5b..c6b4fb5c91 100644 --- a/Task/Trigonometric-functions/Phix/trigonometric-functions.phix +++ b/Task/Trigonometric-functions/Phix/trigonometric-functions.phix @@ -1,15 +1,13 @@ -(phixonline)--> - with javascript_semantics - ?sin(PI/2) - ?sin(90*PI/180) - ?cos(0) - ?cos(0*PI/180) - ?tan(PI/4) - ?tan(45*PI/180) - ?arcsin(1)*2 - ?arcsin(1)*180/PI - ?arccos(0)*2 - ?arccos(0)*180/PI - ?arctan(1)*4 - ?arctan(1)*180/PI - - with javascript_semantics - requires("1.0.1") -- (minor/backportable bugfix rqd to handling of -inf in printf[1]) - constant tropicalAdd = max, - tropicalMul = sq_add, - tropicalExp = sq_mul, - inf = 1e300*1e300 +with javascript_semantics +requires("1.0.1") -- (minor/backportable bugfix rqd to handling of -inf in printf[1]) +constant tropicalAdd = max, + tropicalMul = sq_add, + tropicalExp = sq_mul, + inf = 1e300*1e300 - printf(1,"tropicalMul(2,-2) = %g\n", - {tropicalMul(2,-2)}) - printf(1,"tropicalAdd(-0.001,-inf) = %g\n", - {tropicalAdd(-0.001,-inf)}) - printf(1,"tropicalMul(0,-inf) = %g\n", - {tropicalMul(0,-inf)}) - printf(1,"tropicalAdd(1.5,-1) = %g\n", - {tropicalAdd(1.5,-1)}) - printf(1,"tropicalMul(-0.5,0) = %g\n", - {tropicalMul(-0.5,0)}) - printf(1,"tropicalExp(5,7) = %g\n", - {tropicalExp(5,7)}) - printf(1,"tropicalMul(5,tropicalAdd(8,7)) = %g\n", - {tropicalMul(5,tropicalAdd(8,7))}) - printf(1,"tropicalAdd(tropicalMul(5,8),tropicalMul(5,7)) = %g\n", - {tropicalAdd(tropicalMul(5,8),tropicalMul(5,7))}) - printf(1,"tropicalMul(5,tropicalAdd(8,7)) == tropicalAdd(tropicalMul(5,8),tropicalMul(5,7)) = %t\n", - {tropicalMul(5,tropicalAdd(8,7)) == tropicalAdd(tropicalMul(5,8),tropicalMul(5,7))}) - - with javascript_semantics - constant bFT = false -- true: use F/T, false: use 0/1, as next +with javascript_semantics +constant bFT = false -- true: use F/T, false: use 0/1, as next - function fmt(bool b) - return iff(bFT?{"F","T"}:{"0","1"})[b+1] - end function +function fmt(bool b) + return iff(bFT?{"F","T"}:{"0","1"})[b+1] +end function - sequence opstack = {} - object token, - op = 0 -- 0 = none - string s -- the expression being parsed - integer sidx, -- idx to "" - ch -- s[sidx] +sequence opstack = {} +object token, + op = 0 -- 0 = none +string s -- the expression being parsed +integer sidx, -- idx to "" + ch -- s[sidx] - procedure err(string msg) - printf(1,"%s\n%s^ %s\n\nPressEnter...",{s,repeat(' ',sidx-1),msg}) - {} = wait_key() - abort(0) - end procedure +procedure err(string msg) + printf(1,"%s\n%s^ %s\n\nPressEnter...",{s,repeat(' ',sidx-1),msg}) + {} = wait_key() + abort(0) +end procedure - procedure nxtch() - sidx += 1 - ch = iff(sidx>length(s)?-1:s[sidx]) - end procedure +procedure nxtch() + sidx += 1 + ch = iff(sidx>length(s)?-1:s[sidx]) +end procedure - procedure skipspaces() - while find(ch," \t\r\n")!=0 do nxtch() end while - end procedure +procedure skipspaces() + while find(ch," \t\r\n")!=0 do nxtch() end while +end procedure - procedure get_token() - skipspaces() - if find(ch,"()!") then - token = s[sidx..sidx] - nxtch() - else - integer tokstart = sidx - if ch=-1 then token = "eof" return end if - while 1 do - nxtch() - if ch<'A' then exit end if - end while - token = s[tokstart..sidx-1] - end if - end procedure +procedure get_token() + skipspaces() + if find(ch,"()!") then + token = s[sidx..sidx] + nxtch() + else + integer tokstart = sidx + if ch=-1 then token = "eof" return end if + while 1 do + nxtch() + if ch<'A' then exit end if + end while + token = s[tokstart..sidx-1] + end if +end procedure - procedure Match(string t) - if token!=t then err(t&" expected") end if - get_token() - end procedure +procedure Match(string t) + if token!=t then err(t&" expected") end if + get_token() +end procedure - procedure PopFactor() - object p2 = opstack[$] - if op="not" then - opstack[$] = {0,op,p2} - else - opstack = opstack[1..$-1] - opstack[$] = {opstack[$],op,p2} - end if - op = 0 - end procedure +procedure PopFactor() + object p2 = opstack[$] + if op="not" then + opstack[$] = {0,op,p2} + else + opstack = opstack[1..$-1] + opstack[$] = {opstack[$],op,p2} + end if + op = 0 +end procedure - sequence names, -- {"false","true",...} - flags -- { 0, 1, ,...} +sequence names, -- {"false","true",...} + flags -- { 0, 1, ,...} - procedure PushFactor(string t) - if op!=0 then PopFactor() end if - integer k = find(t,names) - if k=0 then - names = append(names,t) - k = length(names) - end if - opstack = append(opstack,k) - end procedure +procedure PushFactor(string t) + if op!=0 then PopFactor() end if + integer k = find(t,names) + if k=0 then + names = append(names,t) + k = length(names) + end if + opstack = append(opstack,k) +end procedure - procedure PushOp(string t) - if op!=0 then PopFactor() end if - op = t - end procedure +procedure PushOp(string t) + if op!=0 then PopFactor() end if + op = t +end procedure - forward procedure Expr(integer p) +forward procedure Expr(integer p) - procedure Factor() - if token="not" - or token="!" then - get_token() - Factor() - if op!=0 then PopFactor() end if - PushOp("not") - elsif token="(" then - get_token() - Expr(0) - Match(")") - elsif not find(token,{"and","or","xor"}) then - PushFactor(token) - if ch!=-1 then - get_token() - end if - else - err("syntax error") - end if - end procedure +procedure Factor() + if token="not" + or token="!" then + get_token() + Factor() + if op!=0 then PopFactor() end if + PushOp("not") + elsif token="(" then + get_token() + Expr(0) + Match(")") + elsif not find(token,{"and","or","xor"}) then + PushFactor(token) + if ch!=-1 then + get_token() + end if + else + err("syntax error") + end if +end procedure - constant {operators, - precedence} = columnize({{"not",6}, - {"and",5}, - {"xor",4}, - {"or",3}}) - procedure Expr(integer p) - Factor() - while 1 do - integer k = find(token,operators) - if k=0 then exit end if - integer thisp = precedence[k] - if thisp<p then exit end if - get_token() - Expr(thisp) - PushOp(operators[k]) - end while - end procedure +constant {operators, + precedence} = columnize({{"not",6}, + {"and",5}, + {"xor",4}, + {"or",3}}) +procedure Expr(integer p) + Factor() + while 1 do + integer k = find(token,operators) + if k=0 then exit end if + integer thisp = precedence[k] + if thisp

    function evaluate(object s) - if atom(s) then - if s>=1 then s = flags[s] end if - return s - end if - object {lhs,op,rhs} = s - lhs = evaluate(lhs) - rhs = evaluate(rhs) - if op="and" then - return lhs and rhs - elsif op="or" then - return lhs or rhs - elsif op="xor" then - return lhs xor rhs - elsif op="not" then - return not rhs - else - ?9/0 - end if - end function +function evaluate(object s) + if atom(s) then + if s>=1 then s = flags[s] end if + return s + end if + object {lhs,op,rhs} = s + lhs = evaluate(lhs) + rhs = evaluate(rhs) + if op="and" then + return lhs and rhs + elsif op="or" then + return lhs or rhs + elsif op="xor" then + return lhs xor rhs + elsif op="not" then + return not rhs + else + ?9/0 + end if +end function - function next_comb() - integer fdx = length(flags) - while flags[fdx]=1 do - flags[fdx] = 0 - fdx -= 1 - end while - if fdx<=2 then return false end if -- all done - flags[fdx] = 1 - return true - end function +function next_comb() + integer fdx = length(flags) + while flags[fdx]=1 do + flags[fdx] = 0 + fdx -= 1 + end while + if fdx<=2 then return false end if -- all done + flags[fdx] = 1 + return true +end function - procedure test(string expr) - opstack = {} - op = 0 - names = {"false","true"} - s = expr - sidx = 0 - nxtch() - get_token() - Expr(0) - if op!=0 then PopFactor() end if - if length(opstack)!=1 then err("some error") end if - flags = repeat(0,length(names)) - flags[2] = 1 -- set "true" true - printf(1,"%s %s\n",{join(names[3..$]),s}) - while 1 do - for i=3 to length(flags) do -- (skipping true&false) - printf(1,"%s%s",{fmt(flags[i]),repeat(' ',length(names[i]))}) - end for - printf(1," %s\n",{fmt(evaluate(opstack[1]))}) - if not next_comb() then exit end if - end while - puts(1,"\n") - end procedure +procedure test(string expr) + opstack = {} + op = 0 + names = {"false","true"} + s = expr + sidx = 0 + nxtch() + get_token() + Expr(0) + if op!=0 then PopFactor() end if + if length(opstack)!=1 then err("some error") end if + flags = repeat(0,length(names)) + flags[2] = 1 -- set "true" true + printf(1,"%s %s\n",{join(names[3..$]),s}) + while 1 do + for i=3 to length(flags) do -- (skipping true&false) + printf(1,"%s%s",{fmt(flags[i]),repeat(' ',length(names[i]))}) + end for + printf(1," %s\n",{fmt(evaluate(opstack[1]))}) + if not next_comb() then exit end if + end while + puts(1,"\n") +end procedure - test("young and not (ugly or poor)") - if platform()!=JS then -- (no gets(0) in a browser) - while 1 do - puts(1,"input expression:") - string t = trim(gets(0)) - puts(1,"\n") - if t="" then exit end if - test(t) - end while - end if - - function s1(string s) return length(s)=12 end function - function s2(string s) return sum(sq_eq(s[7..12],'1'))=3 end function - function s3(string s) return sum(sq_eq(extract(s,tagset(12,2,2)),'1'))=2 end function - function s4(string s) return s[5]='0' or s[6..7]="11" end function - function s5(string s) return s[2..4]="000" end function - function s6(string s) return sum(sq_eq(extract(s,tagset(12,1,2)),'1'))=4 end function - function s7(string s) return s[2]!=s[3] end function - function s8(string s) return s[7]='0' or s[5..6]="11" end function - function s9(string s) return sum(sq_eq(s[1..6],'1'))=3 end function - function s10(string s) return s[11..12]="11" end function - function s11(string s) return sum(sq_eq(s[7..9],'1'))=1 end function - function s12(string s) return sum(sq_eq(s[1..11],'1'))=4 end function +function s1(string s) return length(s)=12 end function +function s2(string s) return sum(sq_eq(s[7..12],'1'))=3 end function +function s3(string s) return sum(sq_eq(extract(s,tagset(12,2,2)),'1'))=2 end function +function s4(string s) return s[5]='0' or s[6..7]="11" end function +function s5(string s) return s[2..4]="000" end function +function s6(string s) return sum(sq_eq(extract(s,tagset(12,1,2)),'1'))=4 end function +function s7(string s) return s[2]!=s[3] end function +function s8(string s) return s[7]='0' or s[5..6]="11" end function +function s9(string s) return sum(sq_eq(s[1..6],'1'))=3 end function +function s10(string s) return s[11..12]="11" end function +function s11(string s) return sum(sq_eq(s[7..9],'1'))=1 end function +function s12(string s) return sum(sq_eq(s[1..11],'1'))=4 end function - sequence rtn = {s1,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11,s12} - string misses = "\n" - for i=0 to power(2,12)-1 do - string s = sprintf("%012b",i) - sequence res = find_all('1',s) - integer t = 0, pass, fail - for b=1 to 12 do - pass = call_func(rtn[b],{s})=(s[b]='1') - if not pass then fail = b end if - t += pass - if b=12 and t=12 then printf(1,"Solution: %v\n",{res}) end if - end for - if t=11 then - misses &= sprintf("Near miss: %v, fail on %d\n",{res,fail}) - end if - end for - puts(1,misses) - [ ) + +[ stack 0 ] is chamber ( --> s ) + +[ chamber take 1+ 6 mod + chamber put ] is rotate1 ( --> ) + +[ 1 swap chamber share poke + rotate1 ] is /load ( [ --> [ ) + +[ dup chamber share peek + if rotate1 /load ] is load ( [ --> [ ) + +[ 6 random chamber replace ] is spin ( --> ) + +[ dup dip + [ chamber share peek ] + rotate1 ] is fire ( [ --> n [ ) + +[ ' empty swap join + ' [ drop or ] join ] is makesim ( [ --> [ ) + +[ 0 ]'[ dup echo sp makesim + 10000 times + [ dup do swap dip + ] drop + 100 4 point$ echo$ char % + emit sp say "deaths" cr ] is sim ( --> ) + +randomise +sim [ load spin load spin fire spin fire ] +sim [ load spin load spin fire fire ] +sim [ load load spin fire spin fire ] +sim [ load load spin fire fire ] diff --git a/Task/Two-bullet-roulette/V-(Vlang)/two-bullet-roulette.v b/Task/Two-bullet-roulette/V-(Vlang)/two-bullet-roulette.v index 7eebfc3192..94228e6c69 100644 --- a/Task/Two-bullet-roulette/V-(Vlang)/two-bullet-roulette.v +++ b/Task/Two-bullet-roulette/V-(Vlang)/two-bullet-roulette.v @@ -15,7 +15,7 @@ fn test(src string) { for _ in 0..tests { sum += method(src) } - println('${m_string(src)} produces ${100.0 * f32(sum) / f32(tests)}% deaths.') + println("${m_string(src)} produces ${100.0 * f32(sum) / f32(tests)}% deaths.") } fn rshift() { @@ -76,5 +76,5 @@ fn m_string(s string) string { else {} } } - return l.join(', ') + return l.join(", ") } diff --git a/Task/Twos-complement/8080-Assembly/twos-complement.8080 b/Task/Twos-complement/8080-Assembly/twos-complement.8080 new file mode 100644 index 0000000000..b4ffd9e2a3 --- /dev/null +++ b/Task/Twos-complement/8080-Assembly/twos-complement.8080 @@ -0,0 +1,28 @@ +org 100h ; program load point under CP/M + ; + ; the assembler itself will negate an + ; 8 or 16-bit constant for us + ; +mvi a,-43 ; a = D5 +lxi h,-43 ; hl = FFD5 + ; + ; no built-in opcode to negate an 8-bit + ; register, but nevertheless easily done + ; +mvi a,43 ; a = 2B +cma +inr a ; a = D5 + ; + ; the same approach for 16-bit values + ; +lxi h,43 ; hl = 002B +mov a,l +cma +mov l,a +mov a,h +cma +mov h,a +inx h ; hl = FFD5 + ; +jmp 0 ; exit to CP/M +end diff --git a/Task/Twos-complement/AArch64-Assembly/twos-complement.aarch64 b/Task/Twos-complement/AArch64-Assembly/twos-complement.aarch64 new file mode 100644 index 0000000000..f427f15555 --- /dev/null +++ b/Task/Twos-complement/AArch64-Assembly/twos-complement.aarch64 @@ -0,0 +1,143 @@ +/* ARM assembly AARCH64 Raspberry PI 3B */ +/* program bincompl64.s */ + +/*******************************************/ +/* Constantes file */ +/*******************************************/ +/* for this file see task include a file in language AArch64 assembly*/ +.include "../includeConstantesARM64.inc" +/*********************************/ +/* Initialized data */ +/*********************************/ +.data +szMessDebutPgm: .asciz "Program 64 bits start. \n" +szMessFinOK: .asciz "Program normal end. \n" +szMessError: .asciz "Error detected !!!!. \n" +szMessNumber: .asciz "Start number : " +szMessResUns: .asciz "Result unsigned : " +szMessResS: .asciz "Result signed : " +szMessResMvn: .asciz "Result with mvn instruction : " + +szCarriageReturn: .asciz "\n" +/*********************************/ +/* UnInitialized data */ +/*********************************/ +.bss +.align 4 + +sZoneConv: .skip 24 +/*********************************/ +/* code section */ +/*********************************/ +.text +.global main +main: + ldr x0,qAdrszMessDebutPgm + bl affichageMess // start message + mov x4,12345 // number + mov x0,x4 + ldr x1,qAdrsZoneConv + bl conversion10 // decimal conversion + mov x0,3 + ldr x1,qAdrszMessNumber + ldr x2,qAdrsZoneConv + ldr x3,qAdrszCarriageReturn + bl displayStrings + mov x0,x4 + neg x0,x0 + ldr x1,qAdrsZoneConv + bl conversion10 // decimal conversion unsigned + mov x0,3 + ldr x1,qAdrszMessResUns + ldr x2,qAdrsZoneConv + ldr x3,qAdrszCarriageReturn + bl displayStrings + + mov x0,x4 + neg x0,x0 + ldr x1,qAdrsZoneConv + bl conversion10S // decimal conversion signed + mov x0,3 + ldr x1,qAdrszMessResS + ldr x2,qAdrsZoneConv + ldr x3,qAdrszCarriageReturn + bl displayStrings + + mov x0,x4 + mvn x0,x0 // use mvn instruction + ldr x1,qAdrsZoneConv + bl conversion10S // decimal conversion signed + mov x0,3 + ldr x1,qAdrszMessResMvn + ldr x2,qAdrsZoneConv + ldr x3,qAdrszCarriageReturn + bl displayStrings + + + ldr x0,qAdrszMessFinOK + bl affichageMess + +100: // standard end of the program + mov x0,0 // return code + mov x8,EXIT // request to exit program + svc 0 // perform the system call + + +qAdrszMessDebutPgm: .quad szMessDebutPgm +qAdrszMessFinOK: .quad szMessFinOK +qAdrszMessError: .quad szMessError +qAdrszCarriageReturn: .quad szCarriageReturn +qAdrsZoneConv: .quad sZoneConv +qAdrszMessNumber: .quad szMessNumber +qAdrszMessResUns: .quad szMessResUns +qAdrszMessResS: .quad szMessResS +qAdrszMessResMvn: .quad szMessResMvn +/***************************************************/ +/* display multi strings */ +/* new version 24/05/2023 */ +/***************************************************/ +/* x0 contains number strings address */ +/* x1 address string1 */ +/* x2 address string2 */ +/* x3 address string3 */ +/* x4 address string4 */ +/* x5 address string5 */ +/* x6 address string6 */ +displayStrings: // INFO: displayStrings + stp x7,lr,[sp,-16]! // save registers + stp x2,fp,[sp,-16]! // save registers + add fp,sp,#32 // save paraméters address (4 registers saved * 8 bytes) + mov x7,x0 // save strings number + cmp x7,#0 // 0 string -> end + ble 100f + mov x0,x1 // string 1 + bl affichageMess + cmp x7,#1 // number > 1 + ble 100f + mov x0,x2 + bl affichageMess + cmp x7,#2 + ble 100f + mov x0,x3 + bl affichageMess + cmp x7,#3 + ble 100f + mov x0,x4 + bl affichageMess + cmp x7,#4 + ble 100f + mov x0,x5 + bl affichageMess + cmp x7,#5 + ble 100f + mov x0,x6 + bl affichageMess +100: + ldp x2,fp,[sp],16 // restaur registers + ldp x7,lr,[sp],16 // restaur registers + ret +/********************************************************/ +/* File Include fonctions */ +/********************************************************/ +/* for this file see task include a file in language AArch64 assembly */ +.include "../includeARM64.inc" diff --git a/Task/Twos-complement/Ada/twos-complement.adb b/Task/Twos-complement/Ada/twos-complement.adb new file mode 100644 index 0000000000..dd3ebbe70d --- /dev/null +++ b/Task/Twos-complement/Ada/twos-complement.adb @@ -0,0 +1,10 @@ +with Ada.Text_IO; + +procedure Twos_Complement is + type Number is mod 2 ** 32; + A : constant Number := 42; + B : constant Number := not A + 1; + Is_Negative : constant Boolean := A + B = 0; +begin + Ada.Text_IO.Put_Line ("B = -A is " & Is_Negative'Image); +end Twos_Complement; diff --git a/Task/Twos-complement/Asymptote/twos-complement.asymptote b/Task/Twos-complement/Asymptote/twos-complement.asymptote new file mode 100644 index 0000000000..fb4ac84a4e --- /dev/null +++ b/Task/Twos-complement/Asymptote/twos-complement.asymptote @@ -0,0 +1,6 @@ +int d = 1234567; +int b[] = {-d,-d + 1,-2,-1,0,1,2,d -2,d -1}; + +for(int i = 0; i < b.length; ++i) { + write(string(b[i]) + " -> " + string(-b[i])); +} diff --git a/Task/Twos-complement/BASIC256/twos-complement.basic b/Task/Twos-complement/BASIC256/twos-complement.basic new file mode 100644 index 0000000000..9cffbb5a53 --- /dev/null +++ b/Task/Twos-complement/BASIC256/twos-complement.basic @@ -0,0 +1,6 @@ +d = 1234567 +dim b = {-d, -d+1, -2, -1, 0, 1, 2, d-2, d-1} + +for i = 0 to b[?]-1 + print b[i]; " -> "; -b[i] +next i diff --git a/Task/Twos-complement/C++/twos-complement.cpp b/Task/Twos-complement/C++/twos-complement.cpp index 5fc5817e3b..3896e88063 100644 --- a/Task/Twos-complement/C++/twos-complement.cpp +++ b/Task/Twos-complement/C++/twos-complement.cpp @@ -11,32 +11,32 @@ std::string to_hex(const int32_t number) { } std::string to_binary(const int32_t number) { - std::stringstream stream; - stream << std::bitset<16>(number); - return stream.str(); + std::stringstream stream; + stream << std::bitset<16>(number); + return stream.str(); } int32_t twos_complement(const int32_t number) { - return ~number + 1; + return ~number + 1; } std::string to_upper_case(std::string str) { - for ( char& ch : str ) { - ch = toupper(ch); - } - return str; + for ( char& ch : str ) { + ch = toupper(ch); + } + return str; } int main() { - std::vector examples = { 0, 1, -1, 42 }; + std::vector examples = { 0, 1, -1, 42 }; - std::cout << std::setw(9) << "decimal" << std::setw(12) << "hex" - << std::setw(17) << "binary" << std::setw(25) << "two's complement" << std::endl; - std::cout << std::setw(6) << "-----------" << std::setw(12) << "--------" - << std::setw(20) << "----------------" << std::setw(20) << "----------------" << std::endl; + std::cout << std::setw(9) << "decimal" << std::setw(12) << "hex" + << std::setw(17) << "binary" << std::setw(25) << "two's complement" << std::endl; + std::cout << std::setw(6) << "-----------" << std::setw(12) << "--------" + << std::setw(20) << "----------------" << std::setw(20) << "----------------" << std::endl; - for ( const int32_t& example : examples ) { - std::cout << std::setw(6) << example << std::setw(17) << to_upper_case(to_hex(example)) - << std::setw(20) << to_binary(example) << std::setw(13) << twos_complement(example) << std::endl; - } + for ( const int32_t& example : examples ) { + std::cout << std::setw(6) << example << std::setw(17) << to_upper_case(to_hex(example)) + << std::setw(20) << to_binary(example) << std::setw(13) << twos_complement(example) << std::endl; + } } diff --git a/Task/Twos-complement/COBOL/twos-complement.cob b/Task/Twos-complement/COBOL/twos-complement.cob new file mode 100644 index 0000000000..33273b02fa --- /dev/null +++ b/Task/Twos-complement/COBOL/twos-complement.cob @@ -0,0 +1,31 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. Twos_complement. + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 d PIC S9(7) COMP-5 VALUE 1234567. + 01 neg-d PIC S9(7) COMP-5. + 01 neg-d1 PIC S9(7) COMP-5. + 01 neg-b PIC S9(7) COMP-5. + 01 d2 PIC S9(7) COMP-5. + 01 d1 PIC S9(7) COMP-5. + 01 b OCCURS 9 TIMES PIC S9(7) COMP-5. + 01 i PIC 9(2) VALUE 1. + PROCEDURE DIVISION. + COMPUTE neg-d = -d + COMPUTE neg-d1 = -d + 1 + COMPUTE d2 = d - 2 + COMPUTE d1 = d - 1 + MOVE neg-d TO b(1) + MOVE neg-d1 TO b(2) + MOVE -2 TO b(3) + MOVE -1 TO b(4) + MOVE 0 TO b(5) + MOVE 1 TO b(6) + MOVE 2 TO b(7) + MOVE d2 TO b(8) + MOVE d1 TO b(9) + PERFORM VARYING i FROM 1 BY 1 UNTIL i > 9 + COMPUTE neg-b = -b(i) + DISPLAY b(i) " -> " neg-b + END-PERFORM + STOP RUN. diff --git a/Task/Twos-complement/Chipmunk-Basic/twos-complement.basic b/Task/Twos-complement/Chipmunk-Basic/twos-complement.basic new file mode 100644 index 0000000000..e231fd854d --- /dev/null +++ b/Task/Twos-complement/Chipmunk-Basic/twos-complement.basic @@ -0,0 +1,14 @@ +10 d = 1234567 +20 dim b(8) +30 b(0) = -d +40 b(1) = -d+1 +50 b(2) = -2 +60 b(3) = -1 +70 b(4) = 0 +80 b(5) = 1 +90 b(6) = 2 +100 b(7) = d-2 +110 b(8) = d-1 +120 for i = 0 to ubound(b) +130 print b(i);"-> ";-b(i) +140 next i diff --git a/Task/Twos-complement/Craft-Basic/twos-complement.basic b/Task/Twos-complement/Craft-Basic/twos-complement.basic index 6248c70ec7..9706a147e7 100644 --- a/Task/Twos-complement/Craft-Basic/twos-complement.basic +++ b/Task/Twos-complement/Craft-Basic/twos-complement.basic @@ -6,7 +6,7 @@ arraysize s, b for i = 0 to s - 1 - print b[i], " : ", b[i] * -1 + print b[i], " : ", b[i] * -1 next i diff --git a/Task/Twos-complement/Crystal/twos-complement.cr b/Task/Twos-complement/Crystal/twos-complement.cr new file mode 100644 index 0000000000..22c37e4b6c --- /dev/null +++ b/Task/Twos-complement/Crystal/twos-complement.cr @@ -0,0 +1 @@ +~3 + 1 # => -3 diff --git a/Task/Twos-complement/Delphi/twos-complement.delphi b/Task/Twos-complement/Delphi/twos-complement.pas similarity index 100% rename from Task/Twos-complement/Delphi/twos-complement.delphi rename to Task/Twos-complement/Delphi/twos-complement.pas diff --git a/Task/Twos-complement/Fortran/twos-complement.f b/Task/Twos-complement/Fortran/twos-complement.f new file mode 100644 index 0000000000..160e76a191 --- /dev/null +++ b/Task/Twos-complement/Fortran/twos-complement.f @@ -0,0 +1,57 @@ +! +program twos_complement_demo + implicit none + + integer :: x, tc + integer :: nbits + character(len=:), allocatable :: bits_x, bits_not, bits_tc + + ! Prompt for input + write(*,"(a)",advance="no") "Enter a positive integer (or any integer):" + read *, x + + ! Determine bit-width and convert to bit-strings + nbits = bit_size(x) + bits_x = to_bitstring(x) + bits_not = to_bitstring(not(x)) + + ! Compute two's complement: flip all bits then add one + tc = not(x) + 1 + bits_tc = to_bitstring(tc) + + ! Display results + 10 format(a,t30,i0) + 20 format(a,i0,a,t30,a,/) + 30 format(a,t30,a) + write(*,*) + write(*,10) "Original integer:", x + write(*,20) "Bit pattern (", nbits, " bits):", trim(bits_x) + write(*,30) "After bitwise NOT: ", trim(bits_not) + write(*,30) "Then add 1 --> two’s comp:", trim(bits_tc) + write(*,*) + write(*,10) "Two’s complement (decimal):", tc + +contains + + !------------------------------------------------------------ + ! Convert an integer to a string of ‘0’ and ‘1’ + !------------------------------------------------------------ + function to_bitstring(val) result(str) + integer, intent(in) :: val + character(len=:), allocatable :: str + integer :: n, i + + ! Number of bits in this integer kind + n = bit_size(val) + allocate(character(len=n) :: str) + + do i = 1, n + if (btest(val, n - i)) then + str(i:i) = '1' + else + str(i:i) = '0' + end if + end do + end function to_bitstring + +end program twos_complement_demo diff --git a/Task/Twos-complement/FreeBASIC/twos-complement-1.basic b/Task/Twos-complement/FreeBASIC/twos-complement-1.basic index 4bfd09519d..4cd7b841b7 100644 --- a/Task/Twos-complement/FreeBASIC/twos-complement-1.basic +++ b/Task/Twos-complement/FreeBASIC/twos-complement-1.basic @@ -3,4 +3,5 @@ Dim As Integer b(1 To ...) = {-d1, -d1+1, -2, -1, 0, 1, 2, d1-2, d1-1} For i As Integer = 1 To Ubound(b) Print b(i); " -> "; -b(i) Next i + Sleep diff --git a/Task/Twos-complement/FreeBASIC/twos-complement-2.basic b/Task/Twos-complement/FreeBASIC/twos-complement-2.basic index 183c298b7b..ed2941b1da 100644 --- a/Task/Twos-complement/FreeBASIC/twos-complement-2.basic +++ b/Task/Twos-complement/FreeBASIC/twos-complement-2.basic @@ -17,4 +17,5 @@ Dim As Integer a2c, l #endif Print Bin(a, l); " -> "; Bin(a2c, l) + Sleep diff --git a/Task/Twos-complement/GW-BASIC/twos-complement.basic b/Task/Twos-complement/GW-BASIC/twos-complement.basic new file mode 100644 index 0000000000..432c0cddb7 --- /dev/null +++ b/Task/Twos-complement/GW-BASIC/twos-complement.basic @@ -0,0 +1,15 @@ +10 LET D = 1234567 +20 DIM B(8) +30 LET B(0) = -D +40 LET B(1) = -D + 1 +50 LET B(2) = -2 +60 LET B(3) = -1 +70 LET B(4) = 0 +80 LET B(5) = 1 +90 LET B(6) = 2 +100 LET B(7) = D - 2 +110 LET B(8) = D - 1 +120 FOR I = 0 TO 8 +130 PRINT B(I); "-> "; -B(I) +140 NEXT I +150 END diff --git a/Task/Twos-complement/Gambas/twos-complement.gambas b/Task/Twos-complement/Gambas/twos-complement.gambas new file mode 100644 index 0000000000..fba6b5643f --- /dev/null +++ b/Task/Twos-complement/Gambas/twos-complement.gambas @@ -0,0 +1,10 @@ +Public d As Integer = 1234567 +Public b As Integer[] = [-d, -d + 1, -2, -1, 0, 1, 2, d - 2, d - 1] + +Public Sub Main() + + For i As Integer = 0 To b.Count - 1 + Print b[i]; " -> "; -b[i] ' * -1 + Next + +End diff --git a/Task/Twos-complement/Java/twos-complement.java b/Task/Twos-complement/Java/twos-complement.java index eb1e82f03c..924a258797 100644 --- a/Task/Twos-complement/Java/twos-complement.java +++ b/Task/Twos-complement/Java/twos-complement.java @@ -2,29 +2,29 @@ import java.util.List; public final class TwosComplement { - public static void main(String[] args) { - List examples = List.of( 0, 1, -1, 42 ); - - System.out.println(String.format("%9s%12s%24s%34s", "decimal", "hex", "binary", "two's complement")); - System.out.println( + public static void main(String[] args) { + List examples = List.of( 0, 1, -1, 42 ); + + System.out.println(String.format("%9s%12s%24s%34s", "decimal", "hex", "binary", "two's complement")); + System.out.println( String.format("%6s%12s%24s%32s", "-----------", "--------", "----------", "----------------")); - - for ( int example : examples ) { - System.out.println(String.format("%5d%18s%36s%13d", + + for ( int example : examples ) { + System.out.println(String.format("%5d%18s%36s%13d", example, toHex(example), toBinary(example), twosComplement(example))); - } - } - - private static String toHex(int number) { - return String.format("%8s", Integer.toHexString(number).toUpperCase()).replace(" ", "0"); - } - - private static String toBinary(int number) { - return String.format("%32s", Integer.toBinaryString(number)).replace(" ", "0"); - } - - private static int twosComplement(int number) { - return ~number + 1; - } + } + } + + private static String toHex(int number) { + return String.format("%8s", Integer.toHexString(number).toUpperCase()).replace(" ", "0"); + } + + private static String toBinary(int number) { + return String.format("%32s", Integer.toBinaryString(number)).replace(" ", "0"); + } + + private static int twosComplement(int number) { + return ~number + 1; + } } diff --git a/Task/Twos-complement/JavaScript/twos-complement.js b/Task/Twos-complement/JavaScript/twos-complement.js new file mode 100644 index 0000000000..54058177fd --- /dev/null +++ b/Task/Twos-complement/JavaScript/twos-complement.js @@ -0,0 +1,2 @@ +console.log([0, 1, -1, 42, 10 ** 11].map(x => ~x + 1).join(" ")); +console.log(~BigInt(10 ** 11) + 1n); diff --git a/Task/Twos-complement/Jq/twos-complement.jq b/Task/Twos-complement/Jq/twos-complement.jq new file mode 100644 index 0000000000..05b13c58da --- /dev/null +++ b/Task/Twos-complement/Jq/twos-complement.jq @@ -0,0 +1,37 @@ +include "bitwise" {search: "."}; # see above + +# Arithmetically add 1 to the non-negative integer represented by the +# bit stream `stream`, in which the least significant bit is first. +def plusplus(stream): + foreach (stream, null) as $bit ({carry: 1}; + if $bit == null + then if .carry == 1 then .emit = 1 else empty end + elif .carry == 0 then .emit = $bit + ## .carry is now 1: + elif $bit == 0 then {carry: 0, emit: 1 } + else .emit = 0 + end ) + | .emit; + +# input: a non-negative integer +# output: the bit array (with most-significant bit first and with length $width) +# corresponding to the twos-complement of the input integer, it being understood +# that all but the ($width-1) least significant bits of the binary representation of . are dropped. +def twosComplement($width): + def rpad($width): ($width - length) as $l | . + [range(0; $l) | 0]; + if . < 0 then "input of twosComplement should be non-negative" | error + else [flipbits( [limit($width; bitwise)] | rpad($width) | .[] )] + | [limit($width; plusplus(.[]))] + | reverse + end; + +def illustrate($width): + "decimal: \(.)", + "binary: \([bitwise] | reverse | join(""))", + "twos-complement(\($width)): \(twosComplement($width) | join(""))", + ""; + +( 3 + | illustrate(8)), +(737894120670 # 0xABCDEABCDE9 + | illustrate(64)) diff --git a/Task/Twos-complement/M2000-Interpreter/twos-complement.m2000 b/Task/Twos-complement/M2000-Interpreter/twos-complement.m2000 index e864aa2119..a38a80c966 100644 --- a/Task/Twos-complement/M2000-Interpreter/twos-complement.m2000 +++ b/Task/Twos-complement/M2000-Interpreter/twos-complement.m2000 @@ -1,12 +1,12 @@ Module Complement2{ - // we use binary.and to get a number in range of byte 0 to 255 - byte k, v - v=random(1, 255) ' there is no two's complement for zero - z=binary.and(binary.not(v)+1, 0xFF) - print v - print z - print z=255-v+1 // z is type of byte always positive - print sint(z+0xFFFFFF00)=-v // using 4bytes, we add unsinged 0xFFFFFF00 + // we use binary.and to get a number in range of byte 0 to 255 + byte k, v + v=random(1, 255) ' there is no two's complement for zero + z=binary.and(binary.not(v)+1, 0xFF) + print v + print z + print z=255-v+1 // z is type of byte always positive + print sint(z+0xFFFFFF00)=-v // using 4bytes, we add unsinged 0xFFFFFF00 } Complement2 Complement2 diff --git a/Task/Twos-complement/PascalABC.NET/twos-complement.pas b/Task/Twos-complement/PascalABC.NET/twos-complement.pas new file mode 100644 index 0000000000..25bcdd1324 --- /dev/null +++ b/Task/Twos-complement/PascalABC.NET/twos-complement.pas @@ -0,0 +1,5 @@ +begin + var x := 56; + x := not x + 1; + Print(x); +end. diff --git a/Task/Twos-complement/Pluto/twos-complement.pluto b/Task/Twos-complement/Pluto/twos-complement.pluto new file mode 100644 index 0000000000..83464aff41 --- /dev/null +++ b/Task/Twos-complement/Pluto/twos-complement.pluto @@ -0,0 +1,8 @@ +local fmt = require "fmt" + +local decimal = {0, 1, -1, 42} +print("decimal two's complement") +print("------- ----------------") +for decimal as d do + fmt.print(" %2d %3d", d, ~d + 1) +end diff --git a/Task/Twos-complement/Prolog/twos-complement.pro b/Task/Twos-complement/Prolog/twos-complement.pro new file mode 100644 index 0000000000..cd51a35839 --- /dev/null +++ b/Task/Twos-complement/Prolog/twos-complement.pro @@ -0,0 +1,14 @@ +d(1234567). + +b([-D, -D + 1, -2, -1, 0, 1, 2, D - 2, D - 1]) :- + d(D). + +print_array([]). +print_array([H|T]) :- + NegH is -H, + format('~d -> ~d~n', [H, NegH]), + print_array(T). + +main :- + b(B), + print_array(B). diff --git a/Task/Twos-complement/PureBasic/twos-complement.basic b/Task/Twos-complement/PureBasic/twos-complement.basic new file mode 100644 index 0000000000..3b67493f99 --- /dev/null +++ b/Task/Twos-complement/PureBasic/twos-complement.basic @@ -0,0 +1,20 @@ +Define d.l +d = 1234567 + +Dim b.l(8) +b(0) = -d +b(1) = -d + 1 +b(2) = -2 +b(3) = -1 +b(4) = 0 +b(5) = 1 +b(6) = 2 +b(7) = d - 2 +b(8) = d - 1 + +OpenConsole() +For i = 0 To ArraySize(b()) - 1 + PrintN(Str(b(i)) + " -> " + Str(-b(i))) +Next i +Input() +CloseConsole() diff --git a/Task/Twos-complement/QB64/twos-complement.qb64 b/Task/Twos-complement/QB64/twos-complement.qb64 new file mode 100644 index 0000000000..538fe23e94 --- /dev/null +++ b/Task/Twos-complement/QB64/twos-complement.qb64 @@ -0,0 +1,17 @@ +Dim d As Long +d = 1234567 + +Dim b(8) As Long +b(0) = -d +b(1) = -d + 1 +b(2) = -2 +b(3) = -1 +b(4) = 0 +b(5) = 1 +b(6) = 2 +b(7) = d - 2 +b(8) = d - 1 + +For i = 0 To UBound(b) + Print b(i); " -> "; -b(i) ' * -1 +Next i diff --git a/Task/Twos-complement/Racket/twos-complement.rkt b/Task/Twos-complement/Racket/twos-complement.rkt new file mode 100644 index 0000000000..848166adc9 --- /dev/null +++ b/Task/Twos-complement/Racket/twos-complement.rkt @@ -0,0 +1,9 @@ +#lang racket/base + +(define (main) + (let ([n 42]) + (printf "n = ~a, -n = ~a, two's complement = ~a\n" + n (- n) (add1 (bitwise-not n))))) + +(module+ main + (main)) diff --git a/Task/Twos-complement/Rebol/twos-complement.rebol b/Task/Twos-complement/Rebol/twos-complement.rebol new file mode 100644 index 0000000000..aaaf085b32 --- /dev/null +++ b/Task/Twos-complement/Rebol/twos-complement.rebol @@ -0,0 +1,9 @@ +negate 0 ;== 0 +negate -1 ;== 1 +negate 1:0:0 ;== -1:0:0 +negate -1x2 ;== 1x-2 +negate $100 ;== -$100 +;; or +1 + complement -42 ;== 42 +complement true ;== false +complement 2#{0000 0011} ;== 2#{1111 1100} diff --git a/Task/Twos-complement/Rust/twos-complement.rs b/Task/Twos-complement/Rust/twos-complement.rs new file mode 100644 index 0000000000..3376594d34 --- /dev/null +++ b/Task/Twos-complement/Rust/twos-complement.rs @@ -0,0 +1,5 @@ +fn main() { + let i = 1; + println!("i = {:#?}, -(i) = {:#?}, !(i) + 1 = {:#?}", i, -i, !i + 1); + return (); // i = 1, -(i) = -1, !(i) + 1 = -1 +} diff --git a/Task/Twos-complement/V-(Vlang)/twos-complement.v b/Task/Twos-complement/V-(Vlang)/twos-complement.v new file mode 100644 index 0000000000..c1c2fd9dee --- /dev/null +++ b/Task/Twos-complement/V-(Vlang)/twos-complement.v @@ -0,0 +1,5 @@ +fn main() { + mut x := 56 + x = ~x + 1 + println(x) +} diff --git a/Task/Twos-complement/Verilog/twos-complement.v b/Task/Twos-complement/Verilog/twos-complement.v new file mode 100644 index 0000000000..3dd4296dc1 --- /dev/null +++ b/Task/Twos-complement/Verilog/twos-complement.v @@ -0,0 +1,22 @@ +module main; + integer d; + integer b[0:8]; + integer i; + + initial begin + d = 1234567; + b[0] = -d; + b[1] = -d + 1; + b[2] = -2; + b[3] = -1; + b[4] = 0; + b[5] = 1; + b[6] = 2; + b[7] = d - 2; + b[8] = d - 1; + + for (i = 0; i <= 8; i = i + 1) begin + $display("%0d -> %0d", b[i], -b[i]); + end + end +endmodule diff --git a/Task/Twos-complement/X86-64-Assembly/twos-complement.x86-64 b/Task/Twos-complement/X86-64-Assembly/twos-complement.x86-64 new file mode 100644 index 0000000000..c3c8f680a8 --- /dev/null +++ b/Task/Twos-complement/X86-64-Assembly/twos-complement.x86-64 @@ -0,0 +1,5 @@ + mov rax, 1968 ; 1968 in rax + neg rax ; -1968 should be in rax +;------------------ + not rax + inc rax ; 1968 should be in rax again. diff --git a/Task/Twos-complement/XBasic/twos-complement.basic b/Task/Twos-complement/XBasic/twos-complement.basic new file mode 100644 index 0000000000..18230a9edb --- /dev/null +++ b/Task/Twos-complement/XBasic/twos-complement.basic @@ -0,0 +1,24 @@ +PROGRAM "Two's complement" +VERSION "0.0000" + +DECLARE FUNCTION Entry () + +FUNCTION Entry () + d = 1234567 + + DIM b[8] + b[0] = -d + b[1] = -d+1 + b[2] = -2 + b[3] = -1 + b[4] = 0 + b[5] = 1 + b[6] = 2 + b[7] = d-2 + b[8] = d-1 + + FOR i = 0 TO UBOUND(b[]) + PRINT b[i]; " -> "; -b[i] + NEXT i +END FUNCTION +END PROGRAM diff --git a/Task/Twos-complement/Yabasic/twos-complement.basic b/Task/Twos-complement/Yabasic/twos-complement.basic new file mode 100644 index 0000000000..aa3500fc14 --- /dev/null +++ b/Task/Twos-complement/Yabasic/twos-complement.basic @@ -0,0 +1,16 @@ +d = 1234567 + +dim b(8) +b(0) = -d +b(1) = -d+1 +b(2) = -2 +b(3) = -1 +b(4) = 0 +b(5) = 1 +b(6) = 2 +b(7) = d-2 +b(8) = d-1 + +for i = 0 to arraysize(b(), 1) + print b(i), " -> ", -b(i) +next i diff --git a/Task/UPC/ALGOL-68/upc.alg b/Task/UPC/ALGOL-68/upc.alg index f71bbbddb0..38757a91f3 100644 --- a/Task/UPC/ALGOL-68/upc.alg +++ b/Task/UPC/ALGOL-68/upc.alg @@ -33,7 +33,7 @@ BEGIN PROC get value = ( INT number of bits )BITS: BEGIN BITS value := 2r0; - FOR b TO number of bits WHILE NOT at end DO + TO number of bits WHILE NOT at end DO value := ( value SHL 1 ) OR IF s[ s pos ] = " " THEN 2r0 ELSE 2r1 FI; s pos +:= 1 OD; @@ -182,8 +182,12 @@ BEGIN OD FI; INT check sum := 0; - FOR d FROM 1 BY 2 TO upc digits DO check sum +:= 3 * ( digits OF result )[ d ] OD; - FOR d FROM 2 BY 2 TO upc digits DO check sum +:= ( digits OF result )[ d ] OD; + FOR d FROM 1 BY 2 TO upc digits DO + check sum +:= 3 * ( digits OF result )[ d ] + OD; + FOR d FROM 2 BY 2 TO upc digits DO + check sum +:= ( digits OF result )[ d ] + OD; IF check sum MOD 10 /= 0 THEN # invalid check digit # error message OF result := "incorrect check digit" diff --git a/Task/UPC/Ada/upc.adb b/Task/UPC/Ada/upc.adb new file mode 100644 index 0000000000..51aa751553 --- /dev/null +++ b/Task/UPC/Ada/upc.adb @@ -0,0 +1,162 @@ +-- Parse scanned UPC-A codes +-- J. Carter 2024 May + +with Ada.Containers.Hashed_Maps; +with Ada.Strings.Fixed; +with Ada.Strings.Hash; +with Ada.Text_IO; + +procedure UPC is + subtype Digit_Pattern is String (1 .. 7); + subtype Digit_Character is Character range '0' .. '9'; + type Pattern_Map is array (Digit_Character) of Digit_Pattern; + + package Digit_Maps is new Ada.Containers.Hashed_Maps (Key_Type => Digit_Pattern, + Element_Type => Digit_Character, + Hash => Ada.Strings.Hash, + Equivalent_Keys => "="); + + Start_Stop_Marker : constant String := "# #"; + Middle_Marker : constant String := " # # "; + + Scan_Length : constant := 2 * Start_Stop_Marker'Length + Middle_Marker'Length + 12 * Digit_Pattern'Length; + + procedure Parse (Count : in Positive; Scan : in String; Reversed : in Boolean := False) with + Pre => Scan'First = 1 and Scan'Length = Scan_Length; + -- Parses Scan and prints the result + -- Count is the line # + -- If Scan is invalid and not Reversed, tries to parse a reversed version of Scan before printing that Scan is invalid + + Left_Pattern_Map : constant Pattern_Map := + ('0' => " ## #", + '1' => " ## #", + '2' => " # ##", + '3' => " #### #", + '4' => " # ##", + '5' => " ## #", + '6' => " # ####", + '7' => " ### ##", + '8' => " ## ###", + '9' => " # ##"); + Right_Pattern_Map : constant Pattern_Map := + ('0' => "### # ", + '1' => "## ## ", + '2' => "## ## ", + '3' => "# # ", + '4' => "# ### ", + '5' => "# ### ", + '6' => "# # ", + '7' => "# # ", + '8' => "# # ", + '9' => "### # "); + + Left_Map : Digit_Maps.Map; + Right_Map : Digit_Maps.Map; + + function Image (Count : in Positive) return String is + (if Count < 10 then Count'Image else Count'Image (2 .. 3) ); + + procedure Parse (Count : in Positive; Scan : in String; Reversed : in Boolean := False) is + function Backwards return String with + Post => Backwards'Result'First = Scan'First and + Backwards'Result'Last = Scan'Last and + (for all I in Scan'Range => Backwards'Result (I) = Scan (Scan'Last - I + 1) ); + + function Backwards return String is + Right : Positive := Scan'Last; + Result : String := Scan; + begin -- Backwards + Swap : for Left in 1 .. Scan'Last / 2 loop + Result (Left) := Scan (Right); + Result (Right) := Scan (Left); + Right := Right - 1; + end loop Swap; + + return Result; + end Backwards; + + Result : String (1 .. 12); + Start : Positive := 1 + Start_Stop_Marker'Length; + Stop : Positive; + begin -- Parse + if Scan (1 .. Start_Stop_Marker'Length) /= Start_Stop_Marker or + Scan (Scan'Last - Start_Stop_Marker'Length + 1 .. Scan'Last) /= Start_Stop_Marker + then + Ada.Text_IO.Put_Line (Item => Image (Count) & ' ' & Scan & ": invalid, missing start or stop marker"); + + return; + end if; + + if Scan (1 + Start_Stop_Marker'Length + 6 * Digit_Pattern'Length .. + 1 + Start_Stop_Marker'Length + 6 * Digit_Pattern'Length + Middle_Marker'Length - 1) /= Middle_Marker + then + Ada.Text_IO.Put_Line (Item => Image (Count) & ' ' & Scan & ": invalid, missing middle marker"); + + return; + end if; + + Left_Side : for I in 1 .. 6 loop + Stop := Start + Digit_Pattern'Length - 1; + + if not Left_Map.Contains (Scan (Start .. Stop) ) then + if not Reversed then + Parse (Count => Count, Scan => Backwards, Reversed => True); + else + Ada.Text_IO.Put_Line (Item => Image (Count) & ": invalid"); + end if; + + return; + end if; + + Result (I) := Left_Map.Element (Scan (Start .. Stop) ); + Start := Stop + 1; + end loop Left_Side; + + Start := Start + Middle_Marker'Length; + + Right_Side : for I in 7 .. 12 loop + Stop := Start + Digit_Pattern'Length - 1; + + if not Right_Map.Contains (Scan (Start .. Stop) ) then + if not Reversed then + Parse (Count => Count, Scan => Backwards, Reversed => True); + else + Ada.Text_IO.Put_Line (Item => Image (Count) & ": invalid"); + end if; + + return; + end if; + + Result (I) := Right_Map.Element (Scan (Start .. Stop) ); + Start := Stop + 1; + end loop Right_Side; + + Ada.Text_IO.Put_Line (Item => Image (Count) & ": " & Result & (if Reversed then " reversed" else "") ); + end Parse; + + Count : Natural := 0; +begin -- UPC + Fill_Left : for D in Left_Pattern_Map'Range loop + Left_Map.Insert (Key => Left_Pattern_Map (D), New_Item => D); + end loop Fill_Left; + + Fill_Right : for D in Right_Pattern_Map'Range loop + Right_Map.Insert (Key => Right_Pattern_Map (D), New_Item => D); + end loop Fill_Right; + + All_Lines : loop + exit All_Lines when Ada.Text_IO.End_Of_File; + + One_Line : declare + Line : constant String := Ada.Strings.Fixed.Trim (Ada.Text_IO.Get_Line, Ada.Strings.Both); + begin -- One_Line + Count := Count + 1; + + if Line'Length /= Scan_Length then + Ada.Text_IO.Put_Line (Item => Image (Count) & " invalid scan;" & Line'Length'Image & "/=" & Scan_Length'Image); + else + Parse (Count => Count, Scan => Line); + end if; + end One_Line; + end loop All_Lines; +end UPC; diff --git a/Task/UPC/Crystal/upc.cr b/Task/UPC/Crystal/upc.cr new file mode 100644 index 0000000000..04f593c305 --- /dev/null +++ b/Task/UPC/Crystal/upc.cr @@ -0,0 +1,30 @@ +UPC_RE = %r{^\s*# #((?:[ #]{7}){6}) # # ((?:[ #]{7}){6})# #\s*$} +UPC_DIGITS = [" ## #", " ## #", " # ##", " #### #", " # ##", + " ## #", " # ####", " ### ##", " ## ###", " # ##"] + +def decode_upc (line) + return nil unless line =~ UPC_RE + digits = ($1 + $2.tr("# ", " #")).chars.in_slices_of(7).map(&.join) + .map {|d| UPC_DIGITS.index! d } + if [3,1,3,1,3,1,3,1,3,1,3,1].zip(digits).map {|m, d| m * d}.sum % 10 != 0 + return nil + end + digits +rescue + return nil +end + +[" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ", + " # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ", + " # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ", + " # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ", + " # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ", + " # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ", + " # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ", + " # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ", + " # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ", + " # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # "] + .each do |line| + code = decode_upc(line) || decode_upc(line.reverse) + puts code || "(bad barcode)" +end diff --git a/Task/UPC/D/upc.d b/Task/UPC/D/upc.d index 9e3f64559a..86708eab51 100644 --- a/Task/UPC/D/upc.d +++ b/Task/UPC/D/upc.d @@ -41,7 +41,7 @@ void decodeUPC(string input) { part = candidate[pos .. next]; auto i = countUntil(LEFT_DIGITS, part); if (i >= 0) { - output ~= i; + output ~= cast(int) i; pos = next; } else { return tuple(false, cast(int[])[]); @@ -61,7 +61,7 @@ void decodeUPC(string input) { part = candidate[pos .. next]; auto i = countUntil(RIGHT_DIGITS, part); if (i >= 0) { - output ~= i; + output ~= cast(int) i; pos = next; } else { return tuple(false, cast(int[])[]); diff --git a/Task/UPC/EasyLang/upc.easy b/Task/UPC/EasyLang/upc.easy new file mode 100644 index 0000000000..30478cdc81 --- /dev/null +++ b/Task/UPC/EasyLang/upc.easy @@ -0,0 +1,64 @@ +proc trim &s$ . + a = 1 + while substr s$ a 1 = " " : a += 1 + b = len s$ + while substr s$ b 1 = " " : b -= 1 + s$ = substr s$ a (b - a + 1) +. +func$ rev s$ . + a$[] = strchars s$ + for i to len a$[] div 2 + swap a$[i] a$[len a$[] - i + 1] + . + return strjoin a$[] "" +. +func$ invert s$ . + for c$ in strchars s$ + if c$ = " " + r$ &= "#" + else + r$ &= " " + . + . + return r$ +. +digs$[] = [ " ## #" " ## #" " # ##" " #### #" " # ##" " ## #" " # ####" " ### ##" " ## ###" " # ##" ] +func[] decode_upc upc$ . + subr getdigs + for i to 6 + h$ = substr upc$ pos 7 + for dig to 10 + d$ = digs$[dig] + if isright = 1 : d$ = invert d$ + if h$ = d$ : break 1 + . + if dig = 11 : return [ ] + dig -= 1 + digs[] &= dig + sum += dig * sumf + sumf = 4 - sumf + pos = pos + 7 + . + . + if len upc$ <> 95 : return [ ] + if substr upc$ 1 3 <> "# #" : return [ ] + pos = 4 + sumf = 3 + getdigs + if substr upc$ pos 5 <> " # # " : return [ ] + pos += 5 + isright = 1 + getdigs + if substr upc$ 1 3 <> "# #" : return [ ] + if sum mod 10 <> 0 : return [ ] + return digs[] +. +barcodes$[] = [ " # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # " " # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # " " # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # " " # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # " " # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # " " # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # " " # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # " " # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # " " # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # " " # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # " ] +for s$ in barcodes$[] + trim s$ + r[] = decode_upc s$ + if r[] = [ ] + r[] = decode_upc rev s$ + . + print r[] +. diff --git a/Task/UPC/FreeBASIC/upc.basic b/Task/UPC/FreeBASIC/upc.basic new file mode 100644 index 0000000000..87dcbe15b8 --- /dev/null +++ b/Task/UPC/FreeBASIC/upc.basic @@ -0,0 +1,90 @@ +Sub decode(bar_code As String) + Dim As String numbers(9) => { _ + " ## #", _ '-- 0 + " ## #", _ '-- 1 + " # ##", _ '-- 2 + " #### #", _ '-- 3 + " # ##", _ '-- 4 + " ## #", _ '-- 5 + " # ####", _ '-- 6 + " ### ##", _ '-- 7 + " ## ###", _ '-- 8 + " # ##" } '-- 9 + Dim As Integer i, j + Dim As String temp + + bar_code = Trim(bar_code) + If Len(bar_code) = 95 And Mid(bar_code, 1, 3) = "# #" And Mid(bar_code, 46, 5) = " # # " And Mid(bar_code, 93, 3) = "# #" Then + For reversed As Integer = 0 To 1 + Dim r(11) As Integer + For i = 1 To 12 + Dim st As Integer = Iif(i <= 6, i * 7 - 3, i * 7 + 2) + Dim number As String = Mid(bar_code, st, 7) + If i > 6 Then + temp = "" + For j = 1 To Len(number) + Select Case Mid(number, j, 1) + Case " " : temp += "#" + Case "#" : temp += " " + Case Else: temp += Mid(number, j, 1) + End Select + Next + number = temp + End If + r(i - 1) = -1 + For j = 0 To 9 + If number = numbers(j) Then + r(i - 1) = j + Exit For + End If + Next + Next + Dim valid As Integer = 1 + For i = 0 To 11 + If r(i) = -1 Then + valid = 0 + Exit For + End If + Next + If valid Then + Dim sum As Integer = 0 + For i = 0 To 11 + sum += r(i) * Iif(i Mod 2 = 0, 3, 1) + Next + If sum Mod 10 = 0 Then + For i = 0 To 11 + Print r(i); + Next + Print Iif(reversed, " (upside down)", "") + Else + Print "invalid checksum" + End If + Exit Sub + End If + temp = "" + For i = Len(bar_code) To 1 Step -1 + temp += Mid(bar_code, i, 1) + Next + bar_code = temp + Next + End If + Print " invalid" +End Sub + +Dim bar_codes(9) As String +bar_codes(0) = " # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # " +bar_codes(1) = " # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # " +bar_codes(2) = " # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # " +bar_codes(3) = " # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # " +bar_codes(4) = " # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # " +bar_codes(5) = " # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # " +bar_codes(6) = " # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # " +bar_codes(7) = " # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # " +bar_codes(8) = " # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # " +bar_codes(9) = " # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # " + +For i As Integer = 0 To 9 + decode(bar_codes(i)) +Next + +Sleep diff --git a/Task/UPC/Julia/upc.julia b/Task/UPC/Julia/upc.jl similarity index 100% rename from Task/UPC/Julia/upc.julia rename to Task/UPC/Julia/upc.jl diff --git a/Task/UPC/Kotlin/upc.kotlin b/Task/UPC/Kotlin/upc.kts similarity index 100% rename from Task/UPC/Kotlin/upc.kotlin rename to Task/UPC/Kotlin/upc.kts diff --git a/Task/UPC/Phix/upc.phix b/Task/UPC/Phix/upc.phix index af7f678cb0..e5d30aa464 100644 --- a/Task/UPC/Phix/upc.phix +++ b/Task/UPC/Phix/upc.phix @@ -1,57 +1,66 @@ -(phixonline)--> - with javascript_semantics - constant numbers = {" ## #", -- 0 - " ## #", -- 1 - " # ##", -- 2 - " #### #", -- 3 - " # ##", -- 4 - " ## #", -- 5 - " # ####", -- 6 - " ### ##", -- 7 - " ## ###", -- 8 - " # ##"} -- 9 +with javascript_semantics +constant numbers = {" ## #", -- 0 + " ## #", -- 1 + " # ##", -- 2 + " #### #", -- 3 + " # ##", -- 4 + " ## #", -- 5 + " # ####", -- 6 + " ### ##", -- 7 + " ## ###", -- 8 + " # ##"} -- 9 +function flip(string s) + for i,ch in s do + s[i] = iff(ch='#'?' ':'#') + end for + return s +end function +constant numberf = apply(numbers,flip) - procedure decode(string bar_code) - bar_code = trim(bar_code) - if length(bar_code)=95 - and bar_code[1..3]="# #" - and bar_code[46..50]=" # # " - and bar_code[93..95]="# #" then - for reversed=false to true do - sequence r = {} - for i=1 to 12 do - integer st = iff(i<=6?i*7-3:i*7+2) - string number = bar_code[st..st+6] - if i>6 then number = substitute_all(number," #X","X #") end if - r &= find(number,numbers)-1 - end for - if not find(-1,r) then - if remainder(sum(sq_mul(r,{3,1,3,1,3,1,3,1,3,1,3,1})),10) then - printf(1,"invalid checksum\n") - else - printf(1,"%v%s\n",{r,iff(reversed?" (upside down)","")}) - end if - return - end if - bar_code = reverse(bar_code) - end for - end if - printf(1,"invalid\n") - end procedure +procedure decode(string bar_code) + bar_code = trim(bar_code) + if length(bar_code)=95 + and bar_code[1..3]="# #" + and bar_code[46..50]=" # # " + and bar_code[93..95]="# #" then + for reversed=false to true do + sequence r = {}, nums = numbers + integer st = 4, checksum = 0, k + for i=1 to 12 do + k = find(bar_code[st..st+6],nums)-1 + if k=-1 then exit end if + r &= k + checksum += iff(odd(i)?k*3:k) + st += 7 + if i=6 then + st += 5 + nums = numberf + end if + end for + if k!=-1 then + if remainder(checksum,10) then + printf(1,"invalid checksum\n") + else + printf(1,"%v%s\n",{r,iff(reversed?" (upside down)","")}) + end if + return + end if + bar_code = reverse(bar_code) + end for + end if + printf(1,"invalid\n") +end procedure - constant bar_codes = split(""" - # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # - # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # - # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # - # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # - # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # - # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # - # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # - # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # - # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # - # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # - ""","\n",true) - for i=1 to length(bar_codes) do - decode(bar_codes[i]) - end for - - -- - -- demo\rosetta\decode_url.exw - -- =========================== - -- - with javascript_semantics - function decode_url(string s) - integer skip = 0 - string res = "" - for i=1 to length(s) do - if skip then - skip -= 1 - else - integer ch = s[i] - if ch='%' then - sequence scanres = {} - if i+2<=length(s) then - scanres = scanf("#"&s[i+1..i+2],"%x") - end if - if length(scanres)!=1 then - return "decode error" - end if - skip = 2 - ch = scanres[1][1] - elsif ch='+' then - ch = ' ' - end if - res &= ch - end if - end for - return res - end function +-- demo\rosetta\decode_url.exw +with javascript_semantics +function decode_url(string s) + integer skip = 0 + string res = "" + for i=1 to length(s) do + if skip then + skip -= 1 + else + integer ch = s[i] + if ch='%' then + sequence scanres = {} + if i+2<=length(s) then + scanres = scanf("#"&s[i+1..i+2],"%x") + end if + if length(scanres)!=1 then + return "decode error" + end if + skip = 2 + ch = scanres[1][1] + elsif ch='+' then + ch = ' ' + end if + res &= ch + end if + end for + return res +end function - printf(1,"%s\n",{decode_url("http%3A%2F%2Ffoo%20bar%2F")}) - printf(1,"%s\n",{decode_url("google.com/search?q=%60Abdu%27l-Bah%C3%A1")}) - - {} = wait_key() - - -- - -- demo\rosetta\encode_url.exw - -- =========================== - -- - with javascript_semantics - function nib(integer b) - return b+iff(b<=9?'0':'A'-10) - end function +-- demo\rosetta\encode_url.exw +with javascript_semantics +function nib(integer b) + return b+iff(b<=9?'0':'A'-10) +end function - function encode_url(string s, string exclusions="", integer spaceplus=0) - string res = "" - for i=1 to length(s) do - integer ch = s[i] - if ch=' ' and spaceplus then - ch = '+' - elsif not find(ch,exclusions) - and (ch<'0' - or (ch>'9' and ch<'A') - or (ch>'Z' and ch<'a') - or ch>'z') then - res &= '%' - res &= nib(floor(ch/#10)) - ch = nib(and_bits(ch,#0F)) - end if - res &= ch - end for - return res - end function +function encode_url(string s, string exclusions="", bool spaceplus=false) + string res = "" + for i=1 to length(s) do + integer ch = s[i] + if ch=' ' and spaceplus then + ch = '+' + elsif not find(ch,exclusions) + and (ch<'0' + or (ch>'9' and ch<'A') + or (ch>'Z' and ch<'a') + or ch>'z') then + res &= '%' + res &= nib(floor(ch/#10)) + ch = nib(and_bits(ch,#0F)) + end if + res &= ch + end for + return res +end function - printf(1,"%s\n",{encode_url("http://foo bar/")}) - {} = wait_key() - small ---------- + do window = min(max_window, n - 1), min_window, -1 + hash_table = 0 + head = 0 + do i = 1, entry_count + if (allocated(entries(i)%key)) deallocate(entries(i)%key) + end do + entry_count = 0 + substr_count = 0 + + ! ----- pre-compute base powers for rolling hash ----- + hbase(1) = 1 + do i = 2, window + hbase(i) = mod(hbase(i - 1) * 31_int64, hash_size) + end do + + ! ----- initialise rolling hash for first window ----- + h = 0 + do i = 1, window + h = mod(h * 31 + iachar(text(i:i)), hash_size) + end do + + ! ----- single left?right sweep ----- + do i = 1, n - window + 1 + hash_val = mod(h, hash_size) ! 0 … HASH_SIZE-1 + + ! ---- search bucket (1-based indices) ---- + idx = -1 + p = head(hash_val) ! p is 1-based now + do while (p > 0) ! 0 means end-of-chain + j = p ! already 1-based + if (len(entries(j)%key) == window .and. entries(j)%key == text(i:i + window - 1)) then + idx = j + exit + end if + p = next(p) ! p stays 1-based + end do + + if (idx > 0) then + entries(idx)%count = entries(idx)%count + 1 + else + ! insert new entry at head of bucket + entry_count = entry_count + 1 + allocate(character(len=window) :: entries(entry_count)%key) + entries(entry_count)%key = text(i:i + window - 1) + entries(entry_count)%start_pos = i + entries(entry_count)%count = 1 + next(entry_count) = head(hash_val) ! old head (1-based) + head(hash_val) = entry_count ! new head (1-based) + end if + + ! ---- advance rolling hash ---- + if (i < n - window + 1) then + h = mod(h - iachar(text(i:i)) * hbase(window), hash_size) + h = mod(h * 31 + iachar(text(i + window:i + window)), hash_size) + hash_size + h = mod(h, hash_size) + end if + end do ! i + + ! ---- build return array ---- + substr_count = count(entries(1:entry_count)%count >= 2) + if (substr_count > 0) then + allocate(results(substr_count)) + k = 0 + do i = 1, entry_count + if (entries(i)%count < 2) cycle + k = k + 1 + allocate(character(len=window) :: results(k)%substring) + results(k)%substring = entries(i)%key + results(k)%count = entries(i)%count + + ! collect ALL positions (single INDEX scan per substring) + allocate(positions(0)) + p = 1 + do + pc = index(text(p:), entries(i)%key) + if (pc == 0) exit + positions = [positions, p + pc - 2] ! 0-based absolute + p = p + pc + end do + allocate(results(k)%positions(size(positions))) + results(k)%positions = positions + 1 ! 1-based + deallocate(positions) + end do + exit ! longest length found + end if + end do ! window + + ! clean-up + do i = 1, entry_count + if (allocated(entries(i)%key)) deallocate(entries(i)%key) + end do + deallocate(entries, hash_table, head, next) + if (.not.allocated(results)) allocate(results(0)) + end function find_lrs +end module lrs_simple + +program lrs_main + use lrs_simple + implicit none + + type(lrs_result), allocatable :: results(:) + character(:), allocatable :: pi_digits + character(1100000) :: line ! Large enough for 100000 digits + integer :: unit, ios + integer(kind=8) :: start_count, end_count, clock_rate + integer, parameter :: limits(4) = [1000, 10000, 100000, 1000000] + integer :: k, limit, line_len + real :: ms + integer :: i, j + + ! Open file + open(newunit=unit, file='piDigits.txt', status='old', action='read', iostat=ios) + if (ios /= 0) stop "piDigits.txt not found!" + + ! Process each of the 3 lines + do k = 1, 4 + limit = limits(k) + + ! Read one complete line + read(unit, '(a)', iostat=ios) line + if (ios /= 0) then + print *, "Error reading line ", k + exit + end if + + ! Get actual length of line (trim trailing spaces) + line_len = len_trim(line) + pi_digits = trim(line) + + call system_clock(start_count, clock_rate) + + ! Find longest repeated substrings + results = find_lrs(pi_digits) + + call system_clock(end_count) + ms = real(end_count - start_count, kind=8) / clock_rate * 1000.0 + + print '(a,i0,a)', "First ", limit, " digits of pi has longest repeated substring(s):" + + ! Print results (sorted lexicographically) + if (size(results) > 0) then + ! Sort results by substring (bubble sort for simplicity) + call sort_results(results) + + do i = 1, size(results) + write(*, '(5a)', advance='no') " '", trim(results(i)%substring), & + "' starting at index " + + ! Print positions + do j = 1, results(i)%count + if (j > 1) write(*, '(a)', advance='no') " " + write(*, '(i0)', advance='no') results(i)%positions(j) + end do + print * + end do + else + print *, " No repeated substring found" + end if + + print '(a,f0.3,a)', "Time taken: ", ms, " milliseconds" + print * + end do + + close(unit) + + print *, "The timings show the performance characteristics of the implementation." + +contains + + ! Sort results lexicographically by substring + subroutine sort_results(results) + type(lrs_result), allocatable, intent(inout) :: results(:) + type(lrs_result) :: temp + integer :: i, j, n + logical :: swapped + + n = size(results) + if (n <= 1) return + + ! Bubble sort + do i = 1, n - 1 + swapped = .false. + do j = 1, n - i + if (results(j)%substring > results(j + 1)%substring) then + ! Swap + temp = results(j) + results(j) = results(j + 1) + results(j + 1) = temp + swapped = .true. + end if + end do + if (.not.swapped) exit + end do + end subroutine sort_results + +end program lrs_main diff --git a/Task/Ukkonen-s-suffix-tree-construction/FreeBASIC/ukkonen-s-suffix-tree-construction-1.basic b/Task/Ukkonen-s-suffix-tree-construction/FreeBASIC/ukkonen-s-suffix-tree-construction-1.basic new file mode 100644 index 0000000000..b42d4a94fe --- /dev/null +++ b/Task/Ukkonen-s-suffix-tree-construction/FreeBASIC/ukkonen-s-suffix-tree-construction-1.basic @@ -0,0 +1,151 @@ +Type SuffixType + index As Integer + suffix As String +End Type + +Type SubstringInfo + substring As String + positions As String +End Type + +Type AllSubstringsInfo + substrings(100) As SubstringInfo + count As Integer + max_length As Integer +End Type + +Function LongestCommonPrefix(s1 As String, s2 As String) As Integer + Dim As Integer minLen, i + minLen = Iif(Len(s1) < Len(s2), Len(s1), Len(s2)) + + For i = 1 To minLen + If Mid(s1, i, 1) <> Mid(s2, i, 1) Then Return i - 1 + Next + + Return minLen +End Function + +Sub FindLongestRepeatedSubstrings(text As String, Byref result As AllSubstringsInfo) + Dim As Integer i, j, k + result.count = 0 + result.max_length = 0 + + If Len(text) < 2 Then Exit Sub + + Dim As SuffixType suffixes() + Redim suffixes(0 To Len(text) - 1) + For i = 0 To Len(text) - 1 + suffixes(i).index = i + suffixes(i).suffix = Mid(text, i + 1) + Next + + ' Sort suffixes (Bubble, inefficient but simple) + For i = 0 To Len(text) - 2 + For j = i + 1 To Len(text) - 1 + If suffixes(i).suffix > suffixes(j).suffix Then + Swap suffixes(i), suffixes(j) + End If + Next + Next + + ' Find the longest repeated substring + Dim As Integer maxLength = 0 + For i = 0 To Len(text) - 2 + Dim As Integer prefixLen = LongestCommonPrefix(suffixes(i).suffix, suffixes(i + 1).suffix) + If prefixLen > maxLength Then maxLength = prefixLen + Next + + If maxLength = 0 Then Exit Sub + + result.max_length = maxLength + + For i = 0 To Len(text) - 2 + Dim As Integer prefixLen = LongestCommonPrefix(suffixes(i).suffix, suffixes(i + 1).suffix) + If prefixLen = maxLength Then + Dim As String substring = Left(suffixes(i).suffix, maxLength) + + Dim As Boolean found = False + For j = 0 To result.count - 1 + If result.substrings(j).substring = substring Then + found = True + Exit For + End If + Next + + If Not found Then + Dim As String positions = "" + Dim As Integer posCount = 0 + Dim As Integer posArray(100) + + For j = 0 To Len(text) - 1 + If Left(suffixes(j).suffix, maxLength) = substring Then + posArray(posCount) = suffixes(j).index - 2 + posCount += 1 + End If + Next + + ' Sort positions (Bubble, inefficient but simple) + For j = 0 To posCount - 2 + For k = j + 1 To posCount - 1 + If posArray(j) > posArray(k) Then + Swap posArray(j), posArray(k) + End If + Next + Next + + For j = 0 To posCount - 1 + If j > 0 Then positions &= " " + positions &= Str(posArray(j)) + Next + + result.substrings(result.count).substring = substring + result.substrings(result.count).positions = positions + result.count += 1 + End If + End If + Next +End Sub + +Sub main() + Dim As Integer limits(0 To 2) = {1000, 10000, 100000} + Dim As Integer ff, i, j, limit + Dim As String contents, pi_digits + + ff = Freefile + If Open("piDigits.txt" For Input As #ff) = 0 Then + contents = Input(Lof(ff), ff) + Close #ff + Else + Print "Error: Could not open piDigits.txt" + Exit Sub + End If + + For i = 0 To 2 + limit = limits(i) + pi_digits = Left(contents, limit) + + DimAs Double t0 = Timer + + Dim As AllSubstringsInfo results + FindLongestRepeatedSubstrings(pi_digits, results) + + Dim As Double elapsed = Timer - t0 + + Print "First "; limit; " digits of pi has longest repeated substrings:" + If results.count > 0 Then + For j = 0 To results.count - 1 + Print " '" & results.substrings(j).substring & "' starting at indices " & results.substrings(j).positions + Next + Else + Print " No repeated substrings found." + End If + + Print Using !"Time taken: ###.### seconds\n"; elapsed + Next + + Print "The timings show that the implementation has approximately linear performance." +End Sub + +main() + +Sleep diff --git a/Task/Ukkonen-s-suffix-tree-construction/FreeBASIC/ukkonen-s-suffix-tree-construction-2.basic b/Task/Ukkonen-s-suffix-tree-construction/FreeBASIC/ukkonen-s-suffix-tree-construction-2.basic new file mode 100644 index 0000000000..7031cea706 --- /dev/null +++ b/Task/Ukkonen-s-suffix-tree-construction/FreeBASIC/ukkonen-s-suffix-tree-construction-2.basic @@ -0,0 +1,295 @@ +Type SuffixType + index As Integer + suffix As String +End Type + +Type SubstringInfo + substring As String + positions As String +End Type + +Type AllSubstringsInfo + substrings(100) As SubstringInfo + count As Integer + max_length As Integer +End Type + +Function LongestCommonPrefix(s1 As String, s2 As String) As Integer + Dim minLen As Integer = Iif(Len(s1) < Len(s2), Len(s1), Len(s2)) + + For i As Integer = 1 To minLen + If Mid(s1, i, 1) <> Mid(s2, i, 1) Then Return i - 1 + Next + + Return minLen +End Function + +Sub FindLongestRepeatedSubstringsOptimized(text As String, Byref result As AllSubstringsInfo) + Dim As Integer i, j, k + + result.count = 0 + result.max_length = 0 + + ' For large data sets, we use a sliding window approach with a hash table + ' to search for matches. + Dim As Integer maxWindowSize = 100 ' Maximum window size to search + + ' Start with a large window and gradually reduce it. + For windowSize As Integer = maxWindowSize To 5 Step -1 + Dim hashTable(0 To 9999) As String ' Simple hash table + + ' Clear hash table + For i = 0 To 9999 + hashTable(i) = "" + Next + + ' Search for substrings of length windowSize + For i = 0 To Len(text) - windowSize + Dim substring As String = Mid(text, i + 1, windowSize) + + ' Calculate a simple hash + Dim hash As Integer = 0 + For j = 1 To Len(substring) + hash = (hash * 31 + Asc(Mid(substring, j, 1))) Mod 10000 + Next + + ' Check for collisions in the hash table + If hashTable(hash) <> "" Then + ' Possible match, check + Dim entries() As String + Dim entryCount As Integer + + ' Manually split the string by commas + Dim currentEntry As String = "" + For j = 1 To Len(hashTable(hash)) + Dim c As String = Mid(hashTable(hash), j, 1) + If c = "," Then + If currentEntry <> "" Then + Redim Preserve entries(0 To entryCount) + entries(entryCount) = currentEntry + entryCount += 1 + currentEntry = "" + End If + Else + currentEntry &= c + End If + Next + + ' Don't forget the last entry + If currentEntry <> "" Then + Redim Preserve entries(0 To entryCount) + entries(entryCount) = currentEntry + entryCount += 1 + End If + + For j = 0 To entryCount - 1 + Dim entry As String = entries(j) + If entry = "" Then Continue For + + Dim entryPos As Integer = Val(entry) + Dim entrySubstring As String = Mid(text, entryPos + 1, windowSize) + + If entrySubstring = substring Then + ' We found a match! + result.max_length = windowSize + + ' Verificar si ya tenemos esta subcadena + Dim found As Boolean = False + For k = 0 To result.count - 1 + If result.substrings(k).substring = substring Then + found = True + Exit For + End If + Next + + If Not found Then + ' Collect all positions + Dim positions As String = "" + Dim posArray(0 To 1000) As Integer + Dim posCount As Integer = 0 + + ' Add current position + posArray(posCount) = i - 2 + posCount += 1 + + ' Add the found position + posArray(posCount) = entryPos - 2 + posCount += 1 + + ' Search for more occurrences + For k = 0 To Len(text) - windowSize + If k <> i And k <> entryPos And Mid(text, k + 1, windowSize) = substring Then + posArray(posCount) = k - 2 + posCount += 1 + End If + Next + + ' Sort positions (Bubble, inefficient but simple) + For k = 0 To posCount - 2 + For l As Integer = k + 1 To posCount - 1 + If posArray(k) > posArray(l) Then + Swap posArray(k), posArray(l) + End If + Next + Next + + For k = 0 To posCount - 1 + If k > 0 Then positions &= " " + positions &= Str(posArray(k)) + Next + + result.substrings(result.count).substring = substring + result.substrings(result.count).positions = positions + result.count += 1 + End If + + ' If we find enough results, exit + If result.count >= 10 Then Exit For + End If + Next + End If + + ' Add this position to the hash table + If hashTable(hash) = "" Then + hashTable(hash) = Str(i) + Else + hashTable(hash) &= "," & Str(i) + End If + Next + + ' If we find any repeated substring, exit + If result.count > 0 Then Exit For + Next +End Sub + +Sub FindLongestRepeatedSubstrings(text As String, Byref result As AllSubstringsInfo) + Dim As Integer i, j, k + + ' Use the algorithm optimized for large data sets + If Len(text) > 20000 Then + FindLongestRepeatedSubstringsOptimized(text, result) + Exit Sub + End If + + result.count = 0 + result.max_length = 0 + + Dim suffixes(0 To Len(text) - 1) As SuffixType + + For i = 0 To Len(text) - 1 + suffixes(i).index = i + suffixes(i).suffix = Mid(text, i + 1) + Next + + ' Sort suffixes (Bubble, inefficient but simple) + For i = 0 To Len(text) - 2 + For j = i + 1 To Len(text) - 1 + If suffixes(i).suffix > suffixes(j).suffix Then + Swap suffixes(i), suffixes(j) + End If + Next + Next + + Dim maxLength As Integer = 0 + + For i = 0 To Len(text) - 2 + Dim prefixLen As Integer = LongestCommonPrefix(suffixes(i).suffix, suffixes(i + 1).suffix) + If prefixLen > maxLength Then maxLength = prefixLen + Next + + If maxLength = 0 Then Exit Sub + + result.max_length = maxLength + + For i = 0 To Len(text) - 2 + Dim prefixLen As Integer = LongestCommonPrefix(suffixes(i).suffix, suffixes(i + 1).suffix) + If prefixLen = maxLength Then + Dim substring As String = Left(suffixes(i).suffix, maxLength) + + Dim found As Boolean = False + For j = 0 To result.count - 1 + If result.substrings(j).substring = substring Then + found = True + Exit For + End If + Next + + If Not found Then + Dim positions As String = "" + Dim posCount As Integer = 0 + Dim posArray(0 To 100) As Integer + + For j = 0 To Len(text) - 1 + If Left(suffixes(j).suffix, maxLength) = substring Then + posArray(posCount) = suffixes(j).index - 2 + posCount += 1 + End If + Next + + ' Sort positions (from lowest to highest) + For j = 0 To posCount - 2 + For k = j + 1 To posCount - 1 + If posArray(j) > posArray(k) Then + Swap posArray(j), posArray(k) + End If + Next + Next + + For j = 0 To posCount - 1 + If j > 0 Then positions &= " " + positions &= Str(posArray(j)) + Next + + result.substrings(result.count).substring = substring + result.substrings(result.count).positions = positions + result.count += 1 + End If + End If + Next +End Sub + +Sub main() + Dim limits(0 To 2) As Integer = {1000, 10000, 100000} + + Dim As Integer ff, i, j, limit + Dim As String contents + + ff = Freefile + If Open("piDigits.txt" For Input As #ff) = 0 Then + contents = Input(Lof(ff), ff) + Close #ff + Else + Print "Error: Could not open piDigits.txt" + Exit Sub + End If + + For i = 0 To 2 + limit = limits(i) + Dim As String pi_digits = Left(contents, limit) + + Dim As Double t0 = Timer + + Dim results As AllSubstringsInfo + FindLongestRepeatedSubstrings(pi_digits, results) + + Dim As Double elapsed = Timer - t0 + + Print "First " & limit & " digits of pi has longest repeated characters:" + + If results.count > 0 Then + For j = 0 To results.count - 1 + Print " '" & results.substrings(j).substring & "' starting at indices " & results.substrings(j).positions + Next + Else + Print " No repeated substrings found." + End If + + Print Using !"Time taken: ###.### seconds\n"; elapsed + Next + + Print "The timings show that the implementation has approximately linear performance." +End Sub + +main() + +Sleep diff --git a/Task/Ukkonen-s-suffix-tree-construction/Java/ukkonen-s-suffix-tree-construction.java b/Task/Ukkonen-s-suffix-tree-construction/Java/ukkonen-s-suffix-tree-construction.java index df5b863d4d..f24a70cad1 100644 --- a/Task/Ukkonen-s-suffix-tree-construction/Java/ukkonen-s-suffix-tree-construction.java +++ b/Task/Ukkonen-s-suffix-tree-construction/Java/ukkonen-s-suffix-tree-construction.java @@ -8,6 +8,8 @@ import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.SortedMap; +import java.util.TreeMap; import java.util.TreeSet; public final class UkkonenSuffixTree { @@ -22,21 +24,21 @@ public final class UkkonenSuffixTree { final long start = System.currentTimeMillis(); SuffixTree tree = new SuffixTree(piDigits); Map> substrings = tree.getLongestRepeatedSubstrings(); - final long finish = System.currentTimeMillis(); + final long end = System.currentTimeMillis(); System.out.println("First " + limit + " digits of pi has longest repeated characters:"); for ( String substring : substrings.keySet() ) { System.out.print(" '" + substring + "' starting at index "); - for ( Iterator iterator = substrings.get(substring).iterator(); iterator.hasNext(); ) { - System.out.print(iterator.next()); - if ( iterator.hasNext() ) { + for ( Iterator iter = substrings.get(substring).iterator(); iter.hasNext(); ) { + System.out.print(iter.next()); + if ( iter.hasNext() ) { System.out.print(" and "); } } System.out.println(); } - System.out.println("Time taken: " + ( finish - start ) + " milliseconds." + System.lineSeparator()); + System.out.println("Time taken: " + ( end - start ) + " milliseconds." + System.lineSeparator()); } System.out.println("The timings show that the implementation has approximately linear performance."); @@ -48,7 +50,7 @@ public final class UkkonenSuffixTree { text = Arrays.copyOfRange(aWord.toCharArray(), 0, aWord.length() + 1); text[aWord.length()] = '\uF123'; // Terminal character - nodes = new Node[2 * aWord.length() + 2]; + nodes = new Node[2 * text.length]; root = newNode(UNDEFINED, UNDEFINED); activeNode = root; @@ -60,9 +62,9 @@ public final class UkkonenSuffixTree { public Map> getLongestRepeatedSubstrings() { List indexes = doTraversal(); String word = String.valueOf(text).substring(0, text.length - 1); - Map> result = new HashMap>(); + SortedMap> result = new TreeMap>(); - if ( indexes.get(0) > 0 ) { + if ( indexes.getFirst() > 0 ) { for ( int i = 1; i < indexes.size(); i++ ) { String substring = word.substring(indexes.get(i), indexes.get(i) + indexes.get(0)); result.computeIfAbsent(substring, k -> new TreeSet()).add(indexes.get(i)); diff --git a/Task/Ukkonen-s-suffix-tree-construction/JavaScript/ukkonen-s-suffix-tree-construction.js b/Task/Ukkonen-s-suffix-tree-construction/JavaScript/ukkonen-s-suffix-tree-construction.js new file mode 100644 index 0000000000..755cedc059 --- /dev/null +++ b/Task/Ukkonen-s-suffix-tree-construction/JavaScript/ukkonen-s-suffix-tree-construction.js @@ -0,0 +1,196 @@ +const fs = require('fs'); + +UNDEFINED = -1; +LEAF_NODE = Number.MAX_SAFE_INTEGER; + +class SuffixTree { + constructor(aWord) { + this.text = Array.from(aWord); + this.text.push('\uF123'); // Terminal character + + this.nodes = new Array(2 * this.text.length); + this.root = this.newNode(this.UNDEFINED, this.UNDEFINED); + this.activeNode = this.root; + + this.textIndex = 0; + this.currentNode = 0; + this.needParentLink = this.UNDEFINED; + this.remainder = 0; + this.leafIndexGenerator = 0; + + for (let i = 0; i < this.text.length; i++) { + this.extendSuffixTree(this.text[i]); + } + } + + getLongestRepeatedSubstrings() { + const indexes = this.doTraversal(); + const word = this.text.slice(0, this.text.length - 1).join(''); + const result = {}; + + if (indexes[0] > 0) { + for (let i = 1; i < indexes.length; i++) { + const substring = word.substring(indexes[i], indexes[i] + indexes[0]); + if (!result[substring]) { + result[substring] = new Set(); + } + result[substring].add(indexes[i]); + } + } + + return result; + } + + extendSuffixTree(aCharacter) { + this.needParentLink = this.UNDEFINED; + this.remainder++; + + while (this.remainder > 0) { + if (this.activeLength === 0) { + this.activeEdge = this.textIndex; + } + + if (!this.nodes[this.activeNode].children.hasOwnProperty(this.text[this.activeEdge])) { + const leaf = this.newNode(this.textIndex, this.LEAF_NODE); + this.nodes[this.activeNode].children[this.text[this.activeEdge]] = leaf; + this.addSuffixLink(this.activeNode); + } else { + const next = this.nodes[this.activeNode].children[this.text[this.activeEdge]]; + if (this.walkDown(next)) { + continue; + } + + if (this.text[this.nodes[next].start + this.activeLength] === aCharacter) { + this.activeLength++; + this.addSuffixLink(this.activeNode); + break; + } + + const split = this.newNode(this.nodes[next].start, this.nodes[next].start + this.activeLength); + this.nodes[this.activeNode].children[this.text[this.activeEdge]] = split; + const leaf = this.newNode(this.textIndex, this.LEAF_NODE); + this.nodes[split].children[aCharacter] = leaf; + this.nodes[next].start += this.activeLength; + this.nodes[split].children[this.text[this.nodes[next].start]] = next; + this.addSuffixLink(split); + } + + this.remainder--; + + if (this.activeNode === this.root && this.activeLength > 0) { + this.activeLength--; + this.activeEdge = this.textIndex - this.remainder + 1; + } else { + this.activeNode = (this.nodes[this.activeNode].parentLink > 0) ? this.nodes[this.activeNode].parentLink : this.root; + } + } + + this.textIndex++; + } + + walkDown(aNode) { + if (this.activeLength >= this.nodes[aNode].edgeLength()) { + this.activeEdge += this.nodes[aNode].edgeLength(); + this.activeLength -= this.nodes[aNode].edgeLength(); + this.activeNode = aNode; + + return true; + } + + return false; + } + + addSuffixLink(aNode) { + if (this.needParentLink !== this.UNDEFINED) { + this.nodes[this.needParentLink].parentLink = aNode; + } + + this.needParentLink = aNode; + } + + newNode(aStart, aEnd) { + const node = new Node(aStart, aEnd); + node.leafIndex = (aEnd === this.LEAF_NODE) ? this.leafIndexGenerator++ : this.UNDEFINED; + this.nodes[this.currentNode] = node; + + return this.currentNode++; + } + + doTraversal() { + const indexes = [this.UNDEFINED]; + + return this.traversal(indexes, this.nodes[this.root], 0); + } + + traversal(aIndexes, aNode, aHeight) { + if (aNode.leafIndex === this.UNDEFINED) { + for (const index of Object.values(aNode.children)) { + const child = this.nodes[index]; + this.traversal(aIndexes, child, aHeight + child.edgeLength()); + } + } else if (aIndexes[0] < aHeight - aNode.edgeLength()) { + aIndexes.length = 0; + aIndexes.push(aHeight - aNode.edgeLength()); + aIndexes.push(aNode.leafIndex); + } else if (aIndexes[0] === aHeight - aNode.edgeLength()) { + aIndexes.push(aNode.leafIndex); + } + + return aIndexes; + } + + + +} + +class Node { + constructor(aStart, aEnd) { + this.start = aStart; + this.end = aEnd; + this.parentLink = 0; + this.leafIndex = 0; + this.children = {}; + } + + edgeLength() { + return Math.min(this.end, suffixTree.textIndex + 1) - this.start; + } +} + + +async function main() { + const limits = [1000, 10000, 100000]; + const piDigitsFile = 'piDigits.txt'; + + try { + const contents = await fs.promises.readFile(piDigitsFile, 'utf8'); + + for (const limit of limits) { + const piDigits = contents.substring(0, limit + 1); + + const start = Date.now(); + suffixTree = new SuffixTree(piDigits); + const substrings = suffixTree.getLongestRepeatedSubstrings(); + const end = Date.now(); + + console.log(`First ${limit} digits of pi has longest repeated characters:`); + for (const substring in substrings) { + if (substrings.hasOwnProperty(substring)) { + const indexes = Array.from(substrings[substring]); + console.log(` '${substring}' starting at index ${indexes.join(' and ')}`); + } + } + + console.log(`Time taken: ${end - start} milliseconds.\n`); + } + + console.log("The timings show that the implementation has approximately linear performance."); + + } catch (err) { + console.error("An error occurred:", err); + } +} + +let suffixTree; + +main(); diff --git a/Task/Ukkonen-s-suffix-tree-construction/Julia/ukkonen-s-suffix-tree-construction.julia b/Task/Ukkonen-s-suffix-tree-construction/Julia/ukkonen-s-suffix-tree-construction.jl similarity index 100% rename from Task/Ukkonen-s-suffix-tree-construction/Julia/ukkonen-s-suffix-tree-construction.julia rename to Task/Ukkonen-s-suffix-tree-construction/Julia/ukkonen-s-suffix-tree-construction.jl diff --git a/Task/Ukkonen-s-suffix-tree-construction/Rust/ukkonen-s-suffix-tree-construction.rs b/Task/Ukkonen-s-suffix-tree-construction/Rust/ukkonen-s-suffix-tree-construction.rs new file mode 100644 index 0000000000..d7a794d714 --- /dev/null +++ b/Task/Ukkonen-s-suffix-tree-construction/Rust/ukkonen-s-suffix-tree-construction.rs @@ -0,0 +1,250 @@ +use std::collections::{HashMap, HashSet}; +use std::fs::File; +use std::io::Read; +use std::time::Instant; +use std::cmp::min; + +struct Node { + start: i32, + end: i32, + parent_link: i32, + leaf_index: i32, + children: HashMap, +} + +impl Node { + fn new(start: i32, end: i32) -> Self { + Node { + start, + end, + parent_link: 0, + leaf_index: 0, + children: HashMap::new(), + } + } + + fn edge_length(&self, text_index: i32) -> i32 { + min(self.end, text_index + 1) - self.start + } +} + +struct SuffixTree { + nodes: Vec, + text: String, + root: i32, + active_node: i32, + active_length: i32, + active_edge: i32, + text_index: i32, + current_node: i32, + need_parent_link: i32, + remainder: i32, + leaf_index_generator: i32, +} + +impl SuffixTree { + const UNDEFINED: i32 = -1; + const LEAF_NODE: i32 = i32::MAX; + + fn new(word: &str) -> Self { + let mut text = String::from(word); + text.push('\u{0004}'); // Terminal character + + let mut tree = SuffixTree { + nodes: Vec::with_capacity(2 * text.len()), + text, + root: 0, + active_node: 0, + active_length: 0, + active_edge: 0, + text_index: 0, + current_node: 0, + need_parent_link: 0, + remainder: 0, + leaf_index_generator: 0, + }; + + // Initialize nodes vector with a placeholder to allow indexing from 0 + for _ in 0..2 * tree.text.len() { + tree.nodes.push(Node::new(Self::UNDEFINED, Self::UNDEFINED)); + } + + tree.root = tree.new_node(Self::UNDEFINED, Self::UNDEFINED); + tree.active_node = tree.root; + + // Build the suffix tree + for ch in tree.text.chars().collect::>() { + tree.extend_suffix_tree(ch); + } + + tree + } + + fn extend_suffix_tree(&mut self, character: char) { + self.need_parent_link = Self::UNDEFINED; + self.remainder += 1; + + let text_chars: Vec = self.text.chars().collect(); + + while self.remainder > 0 { + if self.active_length == 0 { + self.active_edge = self.text_index; + } + + let active_edge_char = text_chars[self.active_edge as usize]; + + if !self.nodes[self.active_node as usize].children.contains_key(&active_edge_char) { + let leaf = self.new_node(self.text_index, Self::LEAF_NODE); + self.nodes[self.active_node as usize].children.insert(active_edge_char, leaf); + self.add_suffix_link(self.active_node); + } else { + let next = *self.nodes[self.active_node as usize].children.get(&active_edge_char).unwrap(); + if self.walk_down(next) { + continue; + } + + if text_chars[(self.nodes[next as usize].start + self.active_length) as usize] == character { + self.active_length += 1; + self.add_suffix_link(self.active_node); + break; + } + + let split = self.new_node( + self.nodes[next as usize].start, + self.nodes[next as usize].start + self.active_length, + ); + self.nodes[self.active_node as usize].children.insert(active_edge_char, split); + + let leaf = self.new_node(self.text_index, Self::LEAF_NODE); + self.nodes[split as usize].children.insert(character, leaf); + + self.nodes[next as usize].start += self.active_length; + let next_start_char = text_chars[self.nodes[next as usize].start as usize]; + self.nodes[split as usize].children.insert(next_start_char, next); + + self.add_suffix_link(split); + } + + self.remainder -= 1; + + if self.active_node == self.root && self.active_length > 0 { + self.active_length -= 1; + self.active_edge = self.text_index - self.remainder + 1; + } else { + self.active_node = if self.nodes[self.active_node as usize].parent_link > 0 { + self.nodes[self.active_node as usize].parent_link + } else { + self.root + }; + } + } + + self.text_index += 1; + } + + fn walk_down(&mut self, node: i32) -> bool { + if self.active_length >= self.nodes[node as usize].edge_length(self.text_index) { + self.active_edge += self.nodes[node as usize].edge_length(self.text_index); + self.active_length -= self.nodes[node as usize].edge_length(self.text_index); + self.active_node = node; + return true; + } + false + } + + fn add_suffix_link(&mut self, node: i32) { + if self.need_parent_link != Self::UNDEFINED { + self.nodes[self.need_parent_link as usize].parent_link = node; + } + self.need_parent_link = node; + } + + fn new_node(&mut self, start: i32, end: i32) -> i32 { + let node_index = self.current_node; + self.nodes[node_index as usize] = Node::new(start, end); + + if end == Self::LEAF_NODE { + self.nodes[node_index as usize].leaf_index = self.leaf_index_generator; + self.leaf_index_generator += 1; + } else { + self.nodes[node_index as usize].leaf_index = Self::UNDEFINED; + } + + self.current_node += 1; + node_index + } + + fn get_longest_repeated_substrings(&self) -> HashMap> { + let indexes = self.do_traversal(); + let text_chars: Vec = self.text.chars().collect(); + let mut result: HashMap> = HashMap::new(); + + if indexes[0] > 0 { + for i in 1..indexes.len() { + let substring: String = text_chars[indexes[i] as usize..(indexes[i] + indexes[0]) as usize].iter().collect(); + + result.entry(substring) + .or_insert_with(HashSet::new) + .insert(indexes[i]); + } + } + + result + } + + fn do_traversal(&self) -> Vec { + let mut indexes = vec![Self::UNDEFINED]; + self.traversal(&mut indexes, &self.nodes[self.root as usize], 0) + } + + fn traversal(&self, indexes: &mut Vec, node: &Node, height: i32) -> Vec { + if node.leaf_index == Self::UNDEFINED { + for (_, &child_index) in &node.children { + let child = &self.nodes[child_index as usize]; + self.traversal(indexes, child, height + child.edge_length(self.text_index)); + } + } else if indexes[0] < height - node.edge_length(self.text_index) { + indexes.clear(); + indexes.push(height - node.edge_length(self.text_index)); + indexes.push(node.leaf_index); + } else if indexes[0] == height - node.edge_length(self.text_index) { + indexes.push(node.leaf_index); + } + + indexes.clone() + } +} + +fn main() -> std::io::Result<()> { + let limits = [1_000, 10_000, 100_000]; + + let mut file = File::open("../piDigits.txt")?; + let mut contents = String::new(); + file.read_to_string(&mut contents)?; + + for &limit in &limits { + let pi_digits = &contents[0..limit]; + + println!("Processing first {} digits of pi...", limit); + + let start = Instant::now(); + let tree = SuffixTree::new(pi_digits); + let substrings = tree.get_longest_repeated_substrings(); + let duration = start.elapsed(); + + println!("First {} digits of pi has longest repeated characters:", limit); + for (substring, indexes) in &substrings { + print!(" '{}' starting at index ", substring); + for &index in indexes { + print!("{} ", index); + } + println!(); + } + + println!("Time taken: {:?}\n", duration); + } + + println!("The timings show that the implementation has approximately linear performance."); + + Ok(()) +} diff --git a/Task/Ulam-spiral-for-primes-/ALGOL-68/ulam-spiral-for-primes-.alg b/Task/Ulam-spiral-for-primes-/ALGOL-68/ulam-spiral-for-primes-.alg index 90a231e98c..be1a3e5bc9 100644 --- a/Task/Ulam-spiral-for-primes-/ALGOL-68/ulam-spiral-for-primes-.alg +++ b/Task/Ulam-spiral-for-primes-/ALGOL-68/ulam-spiral-for-primes-.alg @@ -4,7 +4,9 @@ BEGIN # construct a Ulam spiral for primes # # starting from init. Primes will be indicated by prime char and # # non-primes by composite char. The center of the spiral will be # # indicated by center char - unless the center value is prime # - PROC print ulam spiral for primes = ( INT width, init, CHAR prime char, composite char, center char )VOID: + PROC print ulam spiral for primes = ( INT width, init + , CHAR prime char, composite char, center char + ) VOID: IF width >= 1 THEN INT n = IF ODD width THEN width ELSE width + 1 FI; []BOOL prime = PRIMESIEVE ( init + ( n * n ) ); @@ -18,16 +20,16 @@ BEGIN # construct a Ulam spiral for primes # w +:= 2; x +:= 1; y +:= 1; - FOR i TO w DO # right edge # + TO w DO # right edge # spiral[ x, y -:= 1 ] := IF prime[ v +:= 1 ] THEN prime char ELSE composite char FI OD; - FOR i TO w DO # top edge # + TO w DO # top edge # spiral[ x -:= 1, y ] := IF prime[ v +:= 1 ] THEN prime char ELSE composite char FI OD; - FOR i TO w DO # left edge # + TO w DO # left edge # spiral[ x, y +:= 1 ] := IF prime[ v +:= 1 ] THEN prime char ELSE composite char FI OD; - FOR i TO w DO # bottom edge # + TO w DO # bottom edge # spiral[ x +:= 1, y ] := IF prime[ v +:= 1 ] THEN prime char ELSE composite char FI OD OD; diff --git a/Task/Ulam-spiral-for-primes-/Ada/ulam-spiral-for-primes--1.ada b/Task/Ulam-spiral-for-primes-/Ada/ulam-spiral-for-primes--1.adb similarity index 100% rename from Task/Ulam-spiral-for-primes-/Ada/ulam-spiral-for-primes--1.ada rename to Task/Ulam-spiral-for-primes-/Ada/ulam-spiral-for-primes--1.adb diff --git a/Task/Ulam-spiral-for-primes-/Ada/ulam-spiral-for-primes--2.ada b/Task/Ulam-spiral-for-primes-/Ada/ulam-spiral-for-primes--2.adb similarity index 100% rename from Task/Ulam-spiral-for-primes-/Ada/ulam-spiral-for-primes--2.ada rename to Task/Ulam-spiral-for-primes-/Ada/ulam-spiral-for-primes--2.adb diff --git a/Task/Ulam-spiral-for-primes-/Ada/ulam-spiral-for-primes--3.ada b/Task/Ulam-spiral-for-primes-/Ada/ulam-spiral-for-primes--3.adb similarity index 100% rename from Task/Ulam-spiral-for-primes-/Ada/ulam-spiral-for-primes--3.ada rename to Task/Ulam-spiral-for-primes-/Ada/ulam-spiral-for-primes--3.adb diff --git a/Task/Ulam-spiral-for-primes-/Crystal/ulam-spiral-for-primes-.crystal b/Task/Ulam-spiral-for-primes-/Crystal/ulam-spiral-for-primes-.cr similarity index 100% rename from Task/Ulam-spiral-for-primes-/Crystal/ulam-spiral-for-primes-.crystal rename to Task/Ulam-spiral-for-primes-/Crystal/ulam-spiral-for-primes-.cr diff --git a/Task/Ulam-spiral-for-primes-/Delphi/ulam-spiral-for-primes-.delphi b/Task/Ulam-spiral-for-primes-/Delphi/ulam-spiral-for-primes-.pas similarity index 100% rename from Task/Ulam-spiral-for-primes-/Delphi/ulam-spiral-for-primes-.delphi rename to Task/Ulam-spiral-for-primes-/Delphi/ulam-spiral-for-primes-.pas diff --git a/Task/Ulam-spiral-for-primes-/EasyLang/ulam-spiral-for-primes-.easy b/Task/Ulam-spiral-for-primes-/EasyLang/ulam-spiral-for-primes-.easy index ca9685ce85..dd72280f92 100644 --- a/Task/Ulam-spiral-for-primes-/EasyLang/ulam-spiral-for-primes-.easy +++ b/Task/Ulam-spiral-for-primes-/EasyLang/ulam-spiral-for-primes-.easy @@ -1,23 +1,14 @@ func isprim num . - if num < 2 - return 0 - . + if num < 2 : return 0 i = 2 while i <= sqrt num - if num mod i = 0 - return 0 - . + if num mod i = 0 : return 0 i += 1 . return 1 . -n = 1 -x = 50 -y = 50 -dx = 1 -dy = 0 # -proc turn . . +subr turn if dx = 1 dx = 0 dy = 1 @@ -32,30 +23,27 @@ proc turn . . dy = 0 . . -proc step . . +subr step n += 1 - x += dx * 1 - y += dy * 1 - move x y - if isprim n = 1 - circle 0.5 - . + x += dx + y += dy + if isprim n = 1 : gcircle x y 0.5 . -textsize 3 -move x y +gtextsize 3 +n = 1 +x = 50 +y = 50 +dx = 1 +dy = 0 lng = 0 # for k to 49 step lng += 2 turn - for j to lng - 1 - step - . + for j to lng - 1 : step for i to 3 turn - for j to lng - step - . + for j to lng : step . . diff --git a/Task/Ulam-spiral-for-primes-/Elixir/ulam-spiral-for-primes-.elixir b/Task/Ulam-spiral-for-primes-/Elixir/ulam-spiral-for-primes-.ex similarity index 100% rename from Task/Ulam-spiral-for-primes-/Elixir/ulam-spiral-for-primes-.elixir rename to Task/Ulam-spiral-for-primes-/Elixir/ulam-spiral-for-primes-.ex diff --git a/Task/Ulam-spiral-for-primes-/Julia/ulam-spiral-for-primes-.julia b/Task/Ulam-spiral-for-primes-/Julia/ulam-spiral-for-primes-.jl similarity index 100% rename from Task/Ulam-spiral-for-primes-/Julia/ulam-spiral-for-primes-.julia rename to Task/Ulam-spiral-for-primes-/Julia/ulam-spiral-for-primes-.jl diff --git a/Task/Ulam-spiral-for-primes-/Kotlin/ulam-spiral-for-primes-.kotlin b/Task/Ulam-spiral-for-primes-/Kotlin/ulam-spiral-for-primes-.kts similarity index 100% rename from Task/Ulam-spiral-for-primes-/Kotlin/ulam-spiral-for-primes-.kotlin rename to Task/Ulam-spiral-for-primes-/Kotlin/ulam-spiral-for-primes-.kts diff --git a/Task/Ulam-spiral-for-primes-/PowerShell/ulam-spiral-for-primes-.psh b/Task/Ulam-spiral-for-primes-/PowerShell/ulam-spiral-for-primes-.ps1 similarity index 100% rename from Task/Ulam-spiral-for-primes-/PowerShell/ulam-spiral-for-primes-.psh rename to Task/Ulam-spiral-for-primes-/PowerShell/ulam-spiral-for-primes-.ps1 diff --git a/Task/Ulam-spiral-for-primes-/REXX/ulam-spiral-for-primes--1.rexx b/Task/Ulam-spiral-for-primes-/REXX/ulam-spiral-for-primes--1.rexx deleted file mode 100644 index 5c8e667ceb..0000000000 --- a/Task/Ulam-spiral-for-primes-/REXX/ulam-spiral-for-primes--1.rexx +++ /dev/null @@ -1,48 +0,0 @@ -/*REXX program shows counter─clockwise Ulam spiral of primes shown in a square matrix.*/ -parse arg size init char . /*obtain optional arguments from the CL*/ -if size=='' | size=="," then size= 79 /*Not specified? Then use the default.*/ -if init=='' | init=="," then init= 1 /* " " " " " " */ -if char=='' then char= "█" /* " " " " " " */ -tot=size**2 /*the total number of numbers in spiral*/ - /*define the upper/bottom right corners*/ -uR.=0; bR.=0; do od=1 by 2 to tot; _=od**2+1; uR._=1; _=_+od; bR._=1; end /*od*/ - /*define the bottom/upper left corners.*/ -bL.=0; uL.=0; do ev=2 by 2 to tot; _=ev**2+1; bL._=1; _=_+ev; uL._=1; end /*ev*/ - -app=1; bigP=0; #p=0; inc=0; minR=1; maxR=1; r=1; $=0; $.=; !.= - /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ construct the spiral #s.*/ - do i=init for tot; r= r + inc; minR= min(minR, r); maxR= max(maxR, r) - x= isPrime(i); if x then bigP= max(bigP, i); #p= #p + x /*bigP, #primes.*/ - if app then $.r= $.r || x /*append token.*/ - else $.r= x || $.r /*prepend token.*/ - if uR.i then do; app= 1; inc= +1; iterate /*i*/; end /*advance ↓ */ - if bL.i then do; app= 0; inc= -1; iterate /*i*/; end /* " ↑ */ - if bR.i then do; app= 0; inc= 0; iterate /*i*/; end /* " ► */ - if uL.i then do; app= 1; inc= 0; iterate /*i*/; end /* " ◄ */ - end /*i*/ /* [↓] pack two */ - /*lines ──► one.*/ - do j=minR to maxR by 2; jp= j + 1; $= $ + 1 /*fold two lines*/ - do k=1 for length($.j); top= substr($.j, k, 1) /*the 1st line.*/ - bot= word( substr($.jp, k, 1) 0, 1) /*the 2nd line.*/ - if top then if bot then !.$= !.$'█' /*has top & bot.*/ - else !.$= !.$'▀' /*has top,¬ bot.*/ - else if bot then !.$= !.$'▄' /*¬ top, has bot*/ - else !.$= !.$' ' /*¬ top, ¬ bot*/ - end /*k*/ - end /*j*/ /* [↓] show the prime spiral matrix.*/ - do m=1 for $; say !.m; end /*m*/ -say; say init 'is the starting point,' , - tot 'numbers used,' #p "primes found, largest prime:" bigP -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -isPrime: procedure; parse arg x; if wordpos(x, '2 3 5 7 11 13 17 19') \==0 then return 1 - if x<17 then return 0; if x// 2 ==0 then return 0 - if x// 3 ==0 then return 0 - /*get the last digit*/ parse var x '' -1 _; if _==5 then return 0 - if x// 7 ==0 then return 0 - if x//11 ==0 then return 0 - if x//13 ==0 then return 0 - - do j=17 by 6 until j*j > x; if x//j ==0 then return 0 - if x//(j+2) ==0 then return 0 - end /*j*/; return 1 diff --git a/Task/Ulam-spiral-for-primes-/REXX/ulam-spiral-for-primes--2.rexx b/Task/Ulam-spiral-for-primes-/REXX/ulam-spiral-for-primes--2.rexx deleted file mode 100644 index 67dd6d6a78..0000000000 --- a/Task/Ulam-spiral-for-primes-/REXX/ulam-spiral-for-primes--2.rexx +++ /dev/null @@ -1,48 +0,0 @@ -/*REXX program shows a clockwise Ulam spiral of primes shown in a square matrix.*/ -parse arg size init char . /*obtain optional arguments from the CL*/ -if size=='' | size=="," then size= 79 /*Not specified? Then use the default.*/ -if init=='' | init=="," then init= 1 /* " " " " " " */ -if char=='' then char= "█" /* " " " " " " */ -tot=size**2 /*the total number of numbers in spiral*/ - /*define the upper/bottom right corners*/ -uR.=0; bR.=0; do od=1 by 2 to tot; _=od**2+init; uR._=1; _=_+od; bR._=1; end /*od*/ - /*define the bottom/upper left corners.*/ -bL.=0; uL.=0; do ev=2 by 2 to tot; _=ev**2+init; bL._=1; _=_+ev; uL._=1; end /*ev*/ - -app=1; bigP=0; #p=0; inc=0; minR=1; maxR=1; r=1; $=0; $.=; !.= - /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ construct the spiral #s.*/ - do i=init for tot; r= r + inc; minR= min(minR, r); maxR= max(maxR, r) - x= isPrime(i); if x then bigP= max(bigP, i); #p= #p + x /*bigP, #primes.*/ - if app then $.r= $.r || x /*append token.*/ - else $.r= x || $.r /*prepend token.*/ - if uR.i then do; app= 1; inc= +1; iterate /*i*/; end /*advance ↓ */ - if bL.i then do; app= 0; inc= -1; iterate /*i*/; end /* " ↑ */ - if bR.i then do; app= 0; inc= 0; iterate /*i*/; end /* " ► */ - if uL.i then do; app= 1; inc= 0; iterate /*i*/; end /* " ◄ */ - end /*i*/ /* [↓] pack two */ - /*lines ──► one.*/ - do j=minR to maxR by 2; jp= j + 1; $= $ + 1 /*fold two lines*/ - do k=1 for length($.j); top= substr($.j, k, 1) /*the 1st line.*/ - bot= word( substr($.jp, k, 1) 0, 1) /*the 2nd line.*/ - if top then if bot then !.$= !.$'█' /*has top & bot.*/ - else !.$= !.$'▀' /*has top,¬ bot.*/ - else if bot then !.$= !.$'▄' /*¬ top, has bot*/ - else !.$= !.$' ' /*¬ top, ¬ bot*/ - end /*k*/ - end /*j*/ /* [↓] show the prime spiral matrix.*/ - do m=1 for $; say !.m; end /*m*/ -say; say init 'is the starting point,' , - tot 'numbers used,' #p "primes found, largest prime:" bigP -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -isPrime: procedure; parse arg x; if wordpos(x, '2 3 5 7 11 13 17 19') \==0 then return 1 - if x<17 then return 0; if x// 2 ==0 then return 0 - if x// 3 ==0 then return 0 - /*get the last digit*/ parse var x '' -1 _; if _==5 then return 0 - if x// 7 ==0 then return 0 - if x//11 ==0 then return 0 - if x//13 ==0 then return 0 - - do j=17 by 6 until j*j > x; if x//j ==0 then return 0 - if x//(j+2) ==0 then return 0 - end /*j*/; return 1 diff --git a/Task/Ulam-spiral-for-primes-/REXX/ulam-spiral-for-primes-.rexx b/Task/Ulam-spiral-for-primes-/REXX/ulam-spiral-for-primes-.rexx new file mode 100644 index 0000000000..5820fe4603 --- /dev/null +++ b/Task/Ulam-spiral-for-primes-/REXX/ulam-spiral-for-primes-.rexx @@ -0,0 +1,96 @@ +-- 10 Oct 2025 +-- Use characterset Western European OEM850 +include Setting +arg size','init + +say 'ULAM SPIRAL' +say version +say +call Parameters +call Corners +call Spiral +call Pack +call Display +exit + +Parameters: +if size = '' then + size = 79 +tot = size**2 +if init = '' then + init = 1 +return + +Corners: +ur. = 0; br. = 0 +do od = 1 by 2 to tot + u = od**2+1; ur.u = 1; u = u+od; br.u = 1 +end +bl. = 0; ul. = 0 +do ev = 2 by 2 to tot + u = ev**2+1; bl.u = 1; u = u+ev; ul.u = 1 +end +return + +Spiral: +app = 1; bigp = 0; hp = 0; inc = 0 +minr = 1; maxr = 1; r = 1; d = 0; d. = ''; e. = '' +do i = init for tot + r = r + inc; minr = Min(minr,r); maxr = Max(maxr,r) + x = Prime(i) + if x then + bigp = Max(bigp,i) + hp = hp + x + if app then + d.r = d.r||x + else + d.r = x||d.r + if ur.i then do + app = 1; inc = +1 + iterate i + end + if bl.i then do + app = 0; inc = -1 + iterate i + end + if br.i then do + app = 0; inc = 0 + iterate i + end + if ul.i then do + app = 1; inc = 0 + iterate i + end +end +return + +Pack: +do j = minr by 2 to maxr + jp = j+1; d = d+1 + do k = 1 for Length(d.j) + top = Substr(d.j,k,1) + bot = Word(Substr(d.jp,k,1) 0,1) + if top then + if bot then + e.d = e.d||'DB'x + else + e.d = e.d||'DF'x + else + if bot then + e.d = e.d||'DC'x + else + e.d = e.d' ' + end +end +return + +Display: +do m = 1 for d + say e.m +end +say +say init 'starting point,' tot 'numbers,' hp 'primes,' bigp 'largest prime' +return + +-- Prime +include Ntheory diff --git a/Task/Ulam-spiral-for-primes-/Rust/ulam-spiral-for-primes--1.rust b/Task/Ulam-spiral-for-primes-/Rust/ulam-spiral-for-primes--1.rs similarity index 100% rename from Task/Ulam-spiral-for-primes-/Rust/ulam-spiral-for-primes--1.rust rename to Task/Ulam-spiral-for-primes-/Rust/ulam-spiral-for-primes--1.rs diff --git a/Task/Ulam-spiral-for-primes-/Rust/ulam-spiral-for-primes--2.rust b/Task/Ulam-spiral-for-primes-/Rust/ulam-spiral-for-primes--2.rs similarity index 100% rename from Task/Ulam-spiral-for-primes-/Rust/ulam-spiral-for-primes--2.rust rename to Task/Ulam-spiral-for-primes-/Rust/ulam-spiral-for-primes--2.rs diff --git a/Task/Ulam-spiral-for-primes-/VBScript/ulam-spiral-for-primes-.vb b/Task/Ulam-spiral-for-primes-/VBScript/ulam-spiral-for-primes-.vbs similarity index 100% rename from Task/Ulam-spiral-for-primes-/VBScript/ulam-spiral-for-primes-.vb rename to Task/Ulam-spiral-for-primes-/VBScript/ulam-spiral-for-primes-.vbs diff --git a/Task/Ultra-useful-primes/00-TASK.txt b/Task/Ultra-useful-primes/00-TASK.txt index 68c81ef05a..2cec197ced 100644 --- a/Task/Ultra-useful-primes/00-TASK.txt +++ b/Task/Ultra-useful-primes/00-TASK.txt @@ -17,4 +17,3 @@ An '''ultra-useful prime''' is a member of the sequence where each = 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; + } +} diff --git a/Task/Ultra-useful-primes/FutureBasic/ultra-useful-primes.basic b/Task/Ultra-useful-primes/FutureBasic/ultra-useful-primes.basic new file mode 100644 index 0000000000..00c426a4cd --- /dev/null +++ b/Task/Ultra-useful-primes/FutureBasic/ultra-useful-primes.basic @@ -0,0 +1,108 @@ +// ------------------------------------------------------------ +// Ultra-useful primes sequence +// Using FutureBasic 7.0.36 +// November 2025, R.W +// +// a(n) = smallest odd k such that 2^(2^n) - k +// is (probable) prime +// ------------------------------------------------------------ + +include "gmp.incl" + +_kPrimeReps = 25 +_kMaxExp = 32767 + +int gN +CFTimeInterval t + +// Abbreviate big numeric string +local fn AbbrevCFNumber( s as CFStringRef, head as int, tail as int ) as CFStringRef + if s = 0 then RETURN @"" + int n : n = len(s) + if n <= head + tail then RETURN s + CFStringRef a, b + a = left (s, head) + b = right(s, tail) + CFStringRef out = @"" + out = concat ( a , @"...", b) +end fn = out + + +// Compute a(n), print n, a(n), and abbreviated prime +void local fn ComputeAndPrint( n as Int ) + UInt32 mexp : mexp = 1 + int i + for i = 1 to n + mexp = mexp << 1 + next + + // Guard against overflow in 32-bit exp; once it explodes, bail + if mexp > _kMaxExp + print using "##";n;" ** exp beyond ";_kMaxExp + RETURN + end if + + mpz_t p + mpz_init(p) + + // p = 2^mexp - 1 + fn mpz_ui_pow_ui(p, 2, mexp) + fn mpz_sub_ui(p, p, 1) + + long k : k = 1 + while fn mpz_probab_prime_p(p, _kPrimeReps) = 0 + k = k + 2 + fn mpz_sub_ui(p, p, 2) + wend + + // Convert to string and abbreviate + CFStringRef pStr = fn mpz_cf2(p) + CFStringRef shortStr = fn AbbrevCFNumber(pStr, 36, 36) + print using "##";n; using "######"; k;" "; shortStr + mpz_clear(p) +end fn + +// Get next 5 sequence +local fn next5 + t = fn CACurrentMediaTime + for int n = gN to gN+4 + fn ComputeAndPrint(n) + next + printf @"\nElapsed time time: %.3f secs\n", (fn CACurrentMediaTime-t) + gN = n +end fn + + +void local fn DoDialog( ev as long, tag as long, wnd as long, obj as CFTypeRef ) + select ( ev ) + case _btnClick + select ( tag ) + case 2 + fn next5 + end select + end select +end fn + +on dialog fn DoDialog + +// Main + +window 1, @"Ultra-useful primes sequence", (60,60,640,520) +button 2,YES,,@"Next 5",(10,20,100,20),,,1 + +on dialog fn doDialog + +print @" n"; @"\t"; @"a(n)"; @"\t"; @"prime" +print string$(60, "-") + +// start the clock + +t = fn CACurrentMediaTime +int n +for n = 1 to 10 + fn ComputeAndPrint(n) +next +gN = n +printf @"\nElapsed time time: %.3f secs\n", (fn CACurrentMediaTime-t) + +HandleEvents diff --git a/Task/Ultra-useful-primes/Julia/ultra-useful-primes.julia b/Task/Ultra-useful-primes/Julia/ultra-useful-primes.jl similarity index 100% rename from Task/Ultra-useful-primes/Julia/ultra-useful-primes.julia rename to Task/Ultra-useful-primes/Julia/ultra-useful-primes.jl diff --git a/Task/Ultra-useful-primes/M2000-Interpreter/ultra-useful-primes.m2000 b/Task/Ultra-useful-primes/M2000-Interpreter/ultra-useful-primes.m2000 new file mode 100644 index 0000000000..30279235de --- /dev/null +++ b/Task/Ultra-useful-primes/M2000-Interpreter/ultra-useful-primes.m2000 @@ -0,0 +1,27 @@ +module Ultra_Useful { + minusOne=biginteger("-1") + one=biginteger("1") + two=biginteger("2") + num=biginteger("0") + k=num + with num,"tostring" as numS + with k,"tostring" as kS + for n= 1 to 10 + k=minusOne + kk=-1 + n1=biginteger(str$(n,"")) + method two,"intpower", n1 as n1 + do + method k,"add", two as k + kk+=2 + method two, "intpower", n1 as num + method num, "subtract", k as num + method num,"isProbablyPrime", 10 as ret + if ret then + Print n, kk : Refresh + exit + end if + always + next +} +Ultra_Useful diff --git a/Task/Ultra-useful-primes/Phix/ultra-useful-primes.phix b/Task/Ultra-useful-primes/Phix/ultra-useful-primes.phix index d5d433f102..89d7eb836a 100644 --- a/Task/Ultra-useful-primes/Phix/ultra-useful-primes.phix +++ b/Task/Ultra-useful-primes/Phix/ultra-useful-primes.phix @@ -1,28 +1,22 @@ -(phixonline)--> - with javascript_semantics - atom t0 = time() - include mpfr.e - mpz p = mpz_init() +with javascript_semantics +atom t0 = time() +include mpfr.e +mpz p = mpz_init() - function a(integer n) - mpz_ui_pow_ui(p,2,power(2,n)) - mpz_sub_si(p,p,1) - integer k = 1 - while not mpz_prime(p) do - k += 2 - mpz_sub_si(p,p,2) - end while - return k - end function +function a(integer n) + mpz_ui_pow_ui(p,2,power(2,n)) + mpz_sub_si(p,p,1) + integer k = 1 + while not mpz_prime(p) do + k += 2 + mpz_sub_si(p,p,2) + end while + return k +end function - for i=1 to 10 do - printf(1,"%d ",a(i)) - end for - if machine_bits()=64 then - ?elapsed(time()-t0) - for i=11 to 13 do - printf(1,"%d ",a(i)) - end for - end if - ?elapsed(time()-t0) - halt ) + [ stack ] is state ( --> s ) + [ stack ] is machine ( --> s ) + + [ state share echo say ": " + split + swap witheach [ echo sp ] + behead nested echo sp + witheach [ echo sp ] cr ] is echotape ( tape head --> ) + + [ over dip [ unrot poke ] ] is write ( tape head value --> tape head ) + + [ write + dup 0 = iff + [ dip [ 0 swap join ] ] + else [ 1 - ] ] is left ( tape head value --> tape head ) + + [ write + 1+ + over size over = if + [ dip [ 0 join ] ] ] is right ( tape head value --> tape head ) + + [ write ] is stay ( tape head value --> tape head ) + + [ 0 state put + rot machine put + [ 2dup echotape + 2dup peek + machine share + state share peek + swap peek do + state replace + state share + halt = until ] + echotape + state release + machine release ] is turing ( machine tape head --> ) + + say "Simple Incrementer" + cr cr + ' [ [ [ 1 stay halt ] [ 1 right 0 ] ] ] + ' [ 1 1 1 ] 0 + turing + cr cr + say "Three-state Busy Beaver" + cr cr + ' [ [ [ 1 right 1 ] [ 1 left 2 ] ] + [ [ 1 left 0 ] [ 1 right 1 ] ] + [ [ 1 left 1 ] [ 1 stay halt ] ] ] + ' [ 0 ] 0 + turing diff --git a/Task/Universal-Turing-machine/Ring/universal-turing-machine.ring b/Task/Universal-Turing-machine/Ring/universal-turing-machine.ring new file mode 100644 index 0000000000..3072144152 --- /dev/null +++ b/Task/Universal-Turing-machine/Ring/universal-turing-machine.ring @@ -0,0 +1,192 @@ +# Author: Gal Zsolt (CalmoSoft) +load "guilib.ring" +load "stdlib.ring" + +# --- Global Variables --- +cTape = "110100" +nHeadPos = 1 +cCurrentState = "q0" +nSpeed = 500 +# Rules format: [State, Read, [NewState, Write, Move]] +aRules = [ + ["q0", "1", ["q0", "0", "R"]], + ["q0", "0", ["q1", "1", "L"]], + ["q1", "1", ["q1", "1", "R"]], + ["q1", "0", ["halt", "1", "N"]] +] + +# GUI Objects +winEdit = NULL +txtEdit = NULL + +app = new qApp { + win = new qWidget() { + setWindowTitle("Turing Machine - CalmoSoft") + resize(800, 650) + setStyleSheet("QWidget { background-color: #1a1a1a; color: white; font-family: Arial; }") + + lblTape = new qLabel(win) { + move(50, 30) resize(700, 120) setAlignment(132) + setStyleSheet("border: 3px solid #00ffcc; border-radius: 15px; background: #262626;") + setText(updateTapeView()) + } + + lblSpeed = new qLabel(win) { move(50, 160) setText("Speed (ms):") } + + sldSpeed = new qSlider(win) { + move(50, 180) resize(250, 30) setOrientation(1) + setRange(50, 2000) setValue(nSpeed) + setValueChangedEvent("updateSpeed()") + } + + timer = new qTimer(win) { setInterval(nSpeed) setTimeoutEvent("stepTuring()") } + + cmbRules = new qComboBox(win) { + move(50, 230) resize(700, 45) + # Item size and font increase via StyleSheet + setStyleSheet(" + QComboBox { + background-color: #333; color: #00ffcc; border: 1px solid #444; font-size: 16px; padding-left: 10px; + } + QComboBox QAbstractItemView { + background-color: #222; color: #00ffcc; selection-background-color: #444; font-size: 16px; + } + QComboBox QAbstractItemView::item { + min-height: 40px; + } + ") + } + fillCombo() + + btnStep = new qPushButton(win) { + move(50, 300) resize(170, 50) setText("STEP") + setStyleSheet("background-color: #00ffcc; color: black; font-weight: bold;") + setClickEvent("stepTuring()") + } + + btnAuto = new qPushButton(win) { + move(230, 300) resize(170, 50) setText("START / STOP") + setStyleSheet("background-color: #f1c40f; color: black; font-weight: bold;") + setClickEvent("toggleAuto()") + } + + btnEdit = new qPushButton(win) { + move(410, 300) resize(170, 50) setText("EDIT RULES") + setStyleSheet("background-color: #3498db; color: white; font-weight: bold;") + setClickEvent("openEditor()") + } + + btnReset = new qPushButton(win) { + move(590, 300) resize(160, 50) setText("RESET") + setStyleSheet("background-color: #e74c3c; color: white;") + setClickEvent("resetMachine()") + } + + lblStatus = new qLabel(win) { + move(50, 400) resize(700, 50) setAlignment(132) + setStyleSheet("font-size: 22px; color: #00ffcc; font-weight: bold;") + setText("State: " + cCurrentState) + } + win.show() + } + exec() +} + +func updateTapeView + cHTML = "

    " + for i = 1 to len(cTape) + char = cTape[i] + if i = nHeadPos + cHTML += " " + char + " " + else + cHTML += " " + char + " " + ok + next + return cHTML + "
    " + +func fillCombo + cmbRules.clear() + for r in aRules + cmbRules.addItem("IF "+r[1]+","+r[2]+" -> GO "+r[3][1]+", WRITE "+r[3][2]+", MOVE "+r[3][3], 0) + next + +func toggleAuto + if timer.isActive() timer.stop() else timer.start() ok + +func updateSpeed + nSpeed = sldSpeed.value() + timer.setInterval(nSpeed) + +func stepTuring + if cCurrentState = "halt" timer.stop() return ok + char = "" + cTape[nHeadPos] + found = 0 + for nIdx = 1 to len(aRules) + r = aRules[nIdx] + if r[1] = cCurrentState AND r[2] = char + found = 1 + cmbRules.setCurrentIndex(nIdx-1) + cCurrentState = r[3][1] + cTape[nHeadPos] = "" + r[3][2] + if r[3][3] = "R" nHeadPos++ elseif r[3][3] = "L" nHeadPos-- ok + exit + ok + next + # Infinite tape handling + if nHeadPos < 1 + cTape = "0" + cTape nHeadPos = 1 + elseif nHeadPos > len(cTape) + cTape = cTape + "0" + ok + + if found = 0 or cCurrentState = "halt" + cCurrentState = "halt" timer.stop() + lblStatus.setText("FINISHED: HALTED") + else + lblStatus.setText("State: " + cCurrentState + " | Position: " + nHeadPos) + ok + lblTape.setText(updateTapeView()) + +func openEditor + winEdit = new qWidget() { + setWindowTitle("Rule Editor") + resize(450, 450) + setStyleSheet("background-color: #222; color: white;") + txtEdit = new qTextEdit(winEdit) { + move(10, 10) resize(430, 340) + setStyleSheet("background-color: #333; color: white; font-family: monospace; font-size: 14px;") + cContent = "" + for r in aRules + cContent += r[1] + "," + r[2] + "," + r[3][1] + "," + r[3][2] + "," + r[3][3] + nl + next + setText(cContent) + } + btnSave = new qPushButton(winEdit) { + move(10, 370) resize(430, 50) setText("SAVE & APPLY") + setStyleSheet("background-color: #00ffcc; color: black; font-weight: bold;") + setClickEvent("saveRules()") + } + winEdit.show() + } + +func saveRules + cRaw = txtEdit.toPlainText() + aLines = split(cRaw, nl) + aNewRules = [] + for line in aLines + line = trim(line) + if line = "" loop ok + parts = split(line, ",") + if len(parts) < 5 loop ok + add(aNewRules, [ parts[1], parts[2], [parts[3], parts[4], parts[5]] ]) + next + aRules = aNewRules + fillCombo() + resetMachine() + winEdit.close() + +func resetMachine + cTape = "110100" nHeadPos = 1 cCurrentState = "q0" + timer.stop() + lblStatus.setText("State: q0") + lblTape.setText(updateTapeView()) diff --git a/Task/Universal-Turing-machine/Rust/universal-turing-machine.rust b/Task/Universal-Turing-machine/Rust/universal-turing-machine.rs similarity index 100% rename from Task/Universal-Turing-machine/Rust/universal-turing-machine.rust rename to Task/Universal-Turing-machine/Rust/universal-turing-machine.rs diff --git a/Task/Universal-Turing-machine/Scheme/universal-turing-machine-1.ss b/Task/Universal-Turing-machine/Scheme/universal-turing-machine-1.scm similarity index 100% rename from Task/Universal-Turing-machine/Scheme/universal-turing-machine-1.ss rename to Task/Universal-Turing-machine/Scheme/universal-turing-machine-1.scm diff --git a/Task/Universal-Turing-machine/Scheme/universal-turing-machine-2.ss b/Task/Universal-Turing-machine/Scheme/universal-turing-machine-2.scm similarity index 100% rename from Task/Universal-Turing-machine/Scheme/universal-turing-machine-2.ss rename to Task/Universal-Turing-machine/Scheme/universal-turing-machine-2.scm diff --git a/Task/Universal-Turing-machine/Scheme/universal-turing-machine-3.ss b/Task/Universal-Turing-machine/Scheme/universal-turing-machine-3.scm similarity index 100% rename from Task/Universal-Turing-machine/Scheme/universal-turing-machine-3.ss rename to Task/Universal-Turing-machine/Scheme/universal-turing-machine-3.scm diff --git a/Task/Universal-Turing-machine/Scheme/universal-turing-machine-4.ss b/Task/Universal-Turing-machine/Scheme/universal-turing-machine-4.scm similarity index 100% rename from Task/Universal-Turing-machine/Scheme/universal-turing-machine-4.ss rename to Task/Universal-Turing-machine/Scheme/universal-turing-machine-4.scm diff --git a/Task/Unix-ls/Ada/unix-ls.ada b/Task/Unix-ls/Ada/unix-ls.adb similarity index 100% rename from Task/Unix-ls/Ada/unix-ls.ada rename to Task/Unix-ls/Ada/unix-ls.adb diff --git a/Task/Unix-ls/Batch-File/unix-ls-1.bat b/Task/Unix-ls/Batch-File/unix-ls-1.bat new file mode 100644 index 0000000000..a73fb637b3 --- /dev/null +++ b/Task/Unix-ls/Batch-File/unix-ls-1.bat @@ -0,0 +1,4 @@ +@echo off +setlocal +pushd %1 +for %%a in (*) do @echo:%%a diff --git a/Task/Unix-ls/Batch-File/unix-ls-2.bat b/Task/Unix-ls/Batch-File/unix-ls-2.bat new file mode 100644 index 0000000000..142e3dd048 --- /dev/null +++ b/Task/Unix-ls/Batch-File/unix-ls-2.bat @@ -0,0 +1 @@ +for %a in (*) do @echo:%a diff --git a/Task/Unix-ls/Delphi/unix-ls.delphi b/Task/Unix-ls/Delphi/unix-ls.pas similarity index 100% rename from Task/Unix-ls/Delphi/unix-ls.delphi rename to Task/Unix-ls/Delphi/unix-ls.pas diff --git a/Task/Unix-ls/DuckDB/unix-ls.duckdb b/Task/Unix-ls/DuckDB/unix-ls.duckdb new file mode 100644 index 0000000000..0426aff992 --- /dev/null +++ b/Task/Unix-ls/DuckDB/unix-ls.duckdb @@ -0,0 +1 @@ +from glob('*') order by file; diff --git a/Task/Unix-ls/Elixir/unix-ls.elixir b/Task/Unix-ls/Elixir/unix-ls.ex similarity index 100% rename from Task/Unix-ls/Elixir/unix-ls.elixir rename to Task/Unix-ls/Elixir/unix-ls.ex diff --git a/Task/Unix-ls/Icon/unix-ls.icon b/Task/Unix-ls/Icon/unix-ls.icon new file mode 100644 index 0000000000..4cb3e50fab --- /dev/null +++ b/Task/Unix-ls/Icon/unix-ls.icon @@ -0,0 +1,4 @@ +procedure main() + every (a := [], put(a,!(f := open(".")))|close(f)) + every write(!sort(a)) +end diff --git a/Task/Unix-ls/Julia/unix-ls.julia b/Task/Unix-ls/Julia/unix-ls.jl similarity index 100% rename from Task/Unix-ls/Julia/unix-ls.julia rename to Task/Unix-ls/Julia/unix-ls.jl diff --git a/Task/Unix-ls/Kotlin/unix-ls.kotlin b/Task/Unix-ls/Kotlin/unix-ls.kts similarity index 100% rename from Task/Unix-ls/Kotlin/unix-ls.kotlin rename to Task/Unix-ls/Kotlin/unix-ls.kts diff --git a/Task/Unix-ls/OCaml/unix-ls.ocaml b/Task/Unix-ls/OCaml/unix-ls.ml similarity index 100% rename from Task/Unix-ls/OCaml/unix-ls.ocaml rename to Task/Unix-ls/OCaml/unix-ls.ml diff --git a/Task/Unix-ls/Perl/unix-ls-1.pl b/Task/Unix-ls/Perl/unix-ls-1.pl index 0bc8ea9a68..0502cc8143 100644 --- a/Task/Unix-ls/Perl/unix-ls-1.pl +++ b/Task/Unix-ls/Perl/unix-ls-1.pl @@ -1,5 +1,3 @@ opendir my $handle, '.' or die "Couldnt open current directory: $!"; -while (readdir $handle) { - print "$_\n"; -} +print "$_\n" for sort readdir $handle; # output supposed to be sorted closedir $handle; diff --git a/Task/Unix-ls/PowerShell/unix-ls.psh b/Task/Unix-ls/PowerShell/unix-ls.ps1 similarity index 100% rename from Task/Unix-ls/PowerShell/unix-ls.psh rename to Task/Unix-ls/PowerShell/unix-ls.ps1 diff --git a/Task/Unix-ls/Rust/unix-ls.rust b/Task/Unix-ls/Rust/unix-ls.rs similarity index 100% rename from Task/Unix-ls/Rust/unix-ls.rust rename to Task/Unix-ls/Rust/unix-ls.rs diff --git a/Task/Unix-ls/Unicon/unix-ls.unicon b/Task/Unix-ls/Unicon/unix-ls.unicon new file mode 100644 index 0000000000..578066f9c7 --- /dev/null +++ b/Task/Unix-ls/Unicon/unix-ls.unicon @@ -0,0 +1,3 @@ +procedure main() + every write(!sort([: !(f := open(".")) :])) | close(f) +end diff --git a/Task/Unprimeable-numbers/Agena/unprimeable-numbers.agena b/Task/Unprimeable-numbers/Agena/unprimeable-numbers.agena new file mode 100644 index 0000000000..482116f25d --- /dev/null +++ b/Task/Unprimeable-numbers/Agena/unprimeable-numbers.agena @@ -0,0 +1,101 @@ +scope # find unprimeable numbers - numbers which can't be made into a prime by changing one digit + + local constant maxNumber := 9_999_999; # maximum number we will consider + + # sieve the primes up to maxNumber + local prime; create register prime( maxNumber ); + prime[ 1 ] := false; + for sPos from 2 to maxNumber do prime[ sPos ] := true od; + for sPos from 2 to entier( sqrt( maxNumber ) ) do + if prime[ sPos ] then + for p from sPos * sPos to maxNumber by sPos do + prime[ p ] := false + od + fi + od; + + # returns true if n is unprimeable, false otherwise + local proc isUnprimeable( n :: number ) :: boolean + local result := false; + if n < 100 then return false + elif prime[ n ] then return false + else + # need to try changing a digit + local constant lastDigit := n mod 10; + local constant leadingDigits := n - lastDigit; + if prime[ leadingDigits + 1 ] then return false + elif prime[ leadingDigits + 3 ] then return false + elif prime[ leadingDigits + 7 ] then return false + elif prime[ leadingDigits + 9 ] then return false + elif lastDigit = 2 or lastDigit = 5 then + # the final digit is 2 or 5, changing the other digits can't make a prime + # unless there is only one other digit which we can change to 0 + local v, dc := leadingDigits \ 10, 1; + while v > 0 do + if v mod 10 <> 0 then dc +:= 1 fi; + v \:= 10 + od; + return dc <> 2 + elif not odd lastDigit then + return true # last digit is even, changing the other digits won't make a prime + else + # last digit is 1, 3, 7, 9: must try changing the other digits + local m10, r10 := 10, 100; + result := true; + while result and n > r10 do + local constant base := ( ( n \ r10 ) * r10 ) + ( n mod m10 ); + for i from 0 by m10 while result and i < r10 do + result := not prime[ base + i ] + od; + m10 *:= 10; + r10 *:= 10 + od; + if result then + # still not unprimeable, try changing the first digit + local constant base := n mod m10; + for i from 0 by m10 while result and i < r10 do + result := not prime[ base + i ] + od + fi + fi + fi; + return result + end + + # returns a string representation of n with commas, n must be an integer + local proc commatise( n :: number ) :: string + local constant nStr := tostring( abs n ); + local constant signStr := if n < 0 then "-" else "" fi; + local constant cStr := strings.reverse( strings.gsub( strings.reverse( nStr ), "%d%d%d", "%1," ) ); + return signStr & strings.gsub( cStr, "^,", "" ) + end; + + scope # find unprimeable numbers + local uCount, dCount := 0, 0; + local firstUnprimeable := reg( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ); # note: indexed from 1 + for i from 100 while i < size prime and dCount < 10 do + if isUnprimeable( i ) then + uCount +:= 1; + if uCount = 1 then + printf( "First 35 unprimeable numbers: %d", i ) + elif uCount <= 35 then + printf( " %d", i ) + elif uCount = 600 then + printf( "\n600th unprimeable number: %s", commatise( i ) ) + fi; + # need to add 1 to the final digit because firstUnprimeable is indxed from 1 + local constant finalDigitPlus1 := ( i mod 10 ) + 1; + if firstUnprimeable[ finalDigitPlus1 ] = 0 then + # first unprimeable number with this final digit + dCount +:= 1; + firstUnprimeable[ finalDigitPlus1 ] := i + fi + fi + od; + # show the first unprimeable number that ends with each digit + print(); + for i from 0 to size firstUnprimeable - 1 do + printf( "First unprimeable number ending in %d: %s\n", i, commatise( firstUnprimeable[ i + 1 ] ) ) + od + end +end diff --git a/Task/Unprimeable-numbers/Arturo/unprimeable-numbers.arturo b/Task/Unprimeable-numbers/Arturo/unprimeable-numbers.arturo index 8ab86bc913..16e6a8de45 100644 --- a/Task/Unprimeable-numbers/Arturo/unprimeable-numbers.arturo +++ b/Task/Unprimeable-numbers/Arturo/unprimeable-numbers.arturo @@ -2,7 +2,7 @@ unprimeable?: function [n][ if prime? n -> return false nd: to :string n loop.with:'i nd 'prevDigit [ - loop `0`..`9` 'newDigit [ + loop '0'..'9' 'newDigit [ if newDigit <> prevDigit [ nd\[i]: newDigit if prime? to :integer nd -> return false diff --git a/Task/Unprimeable-numbers/EasyLang/unprimeable-numbers.easy b/Task/Unprimeable-numbers/EasyLang/unprimeable-numbers.easy new file mode 100644 index 0000000000..89c38321ba --- /dev/null +++ b/Task/Unprimeable-numbers/EasyLang/unprimeable-numbers.easy @@ -0,0 +1,36 @@ +fastfunc isprim num . + i = 2 + while i <= sqrt num + if num mod i = 0 : return 0 + i += 1 + . + return 1 +. +func isunprim n . + n$[] = strchars n + for i to len n$[] + s$ = n$[i] + for d = 0 to 9 + n$[i] = d + h = number strjoin n$[] "" + if isprim h = 1 : return 0 + . + n$[i] = s$ + . + return 1 +. +n = 1 +while cnt < 35 + if isunprim n = 1 + write n & " " + cnt += 1 + . + n += 1 +. +print "" +repeat + if isunprim n = 1 : cnt += 1 + until cnt = 600 + n += 1 +. +print n diff --git a/Task/Unprimeable-numbers/Fortran/unprimeable-numbers.f b/Task/Unprimeable-numbers/Fortran/unprimeable-numbers.f new file mode 100644 index 0000000000..0161f12684 --- /dev/null +++ b/Task/Unprimeable-numbers/Fortran/unprimeable-numbers.f @@ -0,0 +1,237 @@ +! Full Fortran program using an efficient sieve-based unprimeable number finder +! with packed bit array and digit changing, printing first 35, 600th, and lowest per digit unprimeables. + +module bitarray_mod + implicit none + private + public :: bit_array, bit_array_create, bit_array_destroy, bit_array_set, bit_array_get + + type :: bit_array + integer :: size ! number of bits + integer, allocatable :: array(:) ! integer array storing bits + end type bit_array + +contains + + function bit_array_create(size) result(b) + integer, intent(in) :: size + type(bit_array) :: b + integer :: nwords + + nwords = shiftr(size + 31, 5)! / 32 + allocate(b%array(nwords)) + b%array = 0 + b%size = size + end function bit_array_create + + subroutine bit_array_destroy(b) + type(bit_array), intent(inout) :: b + if (allocated(b%array)) deallocate(b%array) + b%size = 0 + end subroutine bit_array_destroy + + subroutine bit_array_set(b, index, value) + type(bit_array), intent(inout) :: b + integer, intent(in) :: index + logical, intent(in) :: value + integer :: word, bitpos + + word = shiftr(index, 5) + 1 + bitpos = iand(index, 31) + if (value) then + b%array(word) = ibset(b%array(word), bitpos) + else + b%array(word) = ibclr(b%array(word), bitpos) + end if + end subroutine bit_array_set + + logical function bit_array_get(b, index) + type(bit_array), intent(in) :: b + integer, intent(in) :: index + integer :: word, bitpos + + word = shiftr(index, 5) + 1 + bitpos = iand(index, 31) + bit_array_get = btest(b%array(word), bitpos) + end function bit_array_get + +end module bitarray_mod + +program unprimeable_numbers + use bitarray_mod + implicit none + integer, parameter :: limit = 10000000 + type(bit_array) :: sieve + integer :: n, i, count, found, digit + integer, dimension(0:9) :: lowest = 0 + character(len=20) :: outstr + + call sieve_create(sieve, limit) + + print *, "First 35 unprimeable numbers:" + count = 0 + found = 0 + n = 100 + do while ((found < 10 .or. count < 600) .and. n < limit) + if (unprimeable(sieve, n)) then + count = count + 1 + if (count <= 35) then + if (count > 1) write(*, '(A)', advance='no') ", " + call format_with_commas(n, outstr) + write(*, '(A)', advance='no') trim(outstr) + end if + if (count == 600) then + print * + call format_with_commas(n, outstr) + print *, "600th unprimeable number: ", trim(outstr) + end if + digit = mod(n, 10) + if (lowest(digit) == 0) then + lowest(digit) = n + found = found + 1 + end if + end if + n = n + 1 + end do + print * + print *, "Lowest unprimeable numbers ending in each digit:" + do i = 0, 9 + if (lowest(i) == 0) then + print "(A,I1,A)", "Digit ", i, ": none found" + else + call format_with_commas(lowest(i), outstr) + print "(A,I1,A,A)", "Digit ", i, ": ", trim(outstr) + end if + end do + + call sieve_destroy(sieve) + +contains + + subroutine sieve_create(s, lim) + type(bit_array), intent(out) :: s + integer, intent(in) :: lim + integer :: sqrtn, p, inc, q, idx + + s = bit_array_create(lim / 2) + sqrtn = int(sqrt(real(lim))) + do p = 3, sqrtn, 2 + idx = shiftr(p, 1) - 1 + if (.not.bit_array_get(s, idx)) then + inc = shiftl(p, 1) + q = p * p + do while (q <= lim) + call bit_array_set(s, shiftr(q, 1) - 1, .true.) + q = q + inc + end do + end if + end do + end subroutine sieve_create + + subroutine sieve_destroy(s) + type(bit_array), intent(inout) :: s + call bit_array_destroy(s) + end subroutine sieve_destroy + + logical function is_prime(s, num) + type(bit_array), intent(in) :: s + integer, intent(in) :: num + if (num == 2) then + is_prime = .true. + else if (num < 2 .or. iand(num, 1) == 0) then + is_prime = .false. + else + is_prime = .not.bit_array_get(s, shiftr(num, 1) - 1) + end if + end function is_prime + + function count_digits(n) result(d) + integer, intent(in) :: n + integer :: d + if (n <= 0) then + d = 1 + else + d = int(log10(real(n))) + 1 + end if + end function count_digits + + function change_digit(n, index, new_digit) result(res) + integer, intent(in) :: n ! Input integer (assumed non-negative) + integer, intent(in) :: index ! Zero-based index from the right (0 = least significant digit) + integer, intent(in) :: new_digit ! Digit to insert (should be 0–9) + integer :: res ! Resulting integer after digit replacement + integer :: pow10 ! 10^index (position multiplier) + integer :: old_digit ! Digit currently at the target position + + ! Guard against invalid index (e.g., negative) + if (index < 0) then + res = n + return + end if + + ! Compute 10^index to isolate the target digit + pow10 = 10**index + + ! Extract the digit currently at the target position + old_digit = mod(n / pow10, 10) + + ! Subtract the old digit's contribution and add the new digit's contribution + res = n - old_digit * pow10 + new_digit * pow10 + end function change_digit + + logical function unprimeable(s, n) + type(bit_array), intent(in) :: s + integer, intent(in) :: n + integer :: d, i, j, m + logical :: prime_found + + if (is_prime(s, n)) then + unprimeable = .false. + return + end if + + d = count_digits(n) + prime_found = .false. + do i = 0, d - 1 + do j = 0, 9 + m = change_digit(n, i, j) + if (m /= n .and. is_prime(s, m)) then + prime_found = .true. + exit + end if + end do + if (prime_found) exit + end do + unprimeable = .not.prime_found + end function unprimeable + + subroutine format_with_commas(n, s) + integer, intent(in) :: n + character(len=*), intent(out) :: s + character(len=20) :: t + integer :: len_t, i, j, comma_pos, len_s + + write(t, '(I0)') n + len_t = len_trim(t) + s = '' + len_s = 0 + comma_pos = 0 + do i = len_t, 1, -1 + len_s = len_s + 1 + s(len_s:len_s) = t(i:i) + comma_pos = comma_pos + 1 + if (mod(comma_pos, 3) == 0 .and. i > 1) then + len_s = len_s + 1 + s(len_s:len_s) = ',' + end if + end do + ! Reverse string s to get correct order + do i = 1, len_s / 2 + j = iachar(s(i:i)) + s(i:i) = s(len_s - i + 1:len_s - i + 1) + s(len_s - i + 1:len_s - i + 1) = char(j) + end do + s = adjustl(s(1:len_s)) + end subroutine format_with_commas + +end program unprimeable_numbers diff --git a/Task/Unprimeable-numbers/Julia/unprimeable-numbers.julia b/Task/Unprimeable-numbers/Julia/unprimeable-numbers.jl similarity index 100% rename from Task/Unprimeable-numbers/Julia/unprimeable-numbers.julia rename to Task/Unprimeable-numbers/Julia/unprimeable-numbers.jl diff --git a/Task/Unprimeable-numbers/Kotlin/unprimeable-numbers.kotlin b/Task/Unprimeable-numbers/Kotlin/unprimeable-numbers.kts similarity index 100% rename from Task/Unprimeable-numbers/Kotlin/unprimeable-numbers.kotlin rename to Task/Unprimeable-numbers/Kotlin/unprimeable-numbers.kts diff --git a/Task/Unprimeable-numbers/Pluto/unprimeable-numbers.pluto b/Task/Unprimeable-numbers/Pluto/unprimeable-numbers.pluto new file mode 100644 index 0000000000..6f3e66f19e --- /dev/null +++ b/Task/Unprimeable-numbers/Pluto/unprimeable-numbers.pluto @@ -0,0 +1,97 @@ +do -- find unprimable numbers - numbers which can't be made into a prime by changing one digit + + local fmt = require( "fmt" ) -- RC Pluto formatting library + local int = require( "int" ) -- RC Pluto integer library - inc. some prime utilities + + local maxNumber = 9_999_999 -- maximum number we will consider + + -- sieve the primes up to maxNumber + local prime = int.arecomps( maxNumber ):map( | v | -> not v ) + + -- returns true if n is unprimeable, false otherwise + local function isUnprimeable( n : number ) : boolean + local result = false + if n < 100 then return false + elseif prime[ n ] then return false + else + -- need to try changing a digit + local lastDigit = n % 10 + local leadingDigits = n - lastDigit + if prime[ leadingDigits + 1 ] then return false + elseif prime[ leadingDigits + 3 ] then return false + elseif prime[ leadingDigits + 7 ] then return false + elseif prime[ leadingDigits + 9 ] then return false + elseif lastDigit == 2 or lastDigit == 5 then + -- the final digit is 2 or 5, changing the other digits can't make a prime + -- unless there is only one other digit which we can change to 0 + local v, dc = leadingDigits // 10, 1 + while v > 0 do + if v % 10 != 0 then dc += 1 end + v //= 10 + end + return dc != 2 + elseif lastDigit % 2 == 0 then + return true -- last digit is even, changing the other digits won't make a prime + else + -- last digit is 1, 3, 7, 9 must try changing the other digits + local m10, r10 = 10, 100 + result = true + while result and n > r10 do + local base = ( ( n // r10 ) * r10 ) + ( n % m10 ) + local i = 0 + while result and i < r10 do + result = not prime[ base + i ] + i += m10 + end + m10 *= 10 + r10 *= 10 + end + if result then + -- still not unprimeable, try changing the first digit + local base = n % m10 + local i = 0 + while result and i < r10 do + result = not prime[ base + i ] + i += m10 + end + end + end + end + return result + end + + -- returns a string representation of n with commas, n must be an integer + local function commatise( n : number ) : string + local cStr = tostring( math.abs( n ) ):reverse():gsub( "%d%d%d", "%1," ):reverse() + return if n < 0 then "-" else "" end..cStr:gsub( "^,", "" ) + end + + do -- find unprimeable numbers + local uCount, dCount = 0, 0 + local firstUnprimeable = { [0] = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } + for i = 100, # prime do + if dCount >= 10 then break end + if isUnprimeable( i ) then + uCount += 1 + if uCount == 1 then + fmt.write( "First 35 unprimeable numbers: %d", i ) + elseif uCount <= 35 then + fmt.write( " %d", i ) + elseif uCount == 600 then + fmt.write( "\n600th unprimeable number: %s", commatise( i ) ) + end + local finalDigit = i % 10 + if firstUnprimeable[ finalDigit ] == 0 then + -- first unprimeable number with this final digit + dCount += 1 + firstUnprimeable[ finalDigit ] = i + end + end + end + -- show the first unprimeable number that ends with each digit + fmt.write( "\n" ) + for i = 0, 9 do + fmt.write( "First unprimeable number ending in %d %s\n", i, commatise( firstUnprimeable[ i ] ) ) + end + end +end diff --git a/Task/Unprimeable-numbers/REXX/unprimeable-numbers.rexx b/Task/Unprimeable-numbers/REXX/unprimeable-numbers.rexx index f10a124567..03dbbb13d9 100644 --- a/Task/Unprimeable-numbers/REXX/unprimeable-numbers.rexx +++ b/Task/Unprimeable-numbers/REXX/unprimeable-numbers.rexx @@ -1,68 +1,92 @@ -/*REXX program finds and displays unprimeable numbers (non─negative integers). */ -parse arg n x hp . /*obtain optional arguments from the CL*/ -if n=='' | n=="," then n= 35 /*Not specified? Then use the default.*/ -if x=='' | x=="," then x= 600 /* " " " " " " */ -if hp=='' | hp=="," then hp= 10000000 /* " " " " " " */ -u= 0 /*number of unprimeable numbers so far.*/ -eds=4; ed.1= 1; ed.2= 3; ed.3= 7; ed.4= 9 /*"end" digits which are prime; prime>9*/ -call genP hp /*generate primes up to & including HP.*/ -$$=; $.=. /*a list " " " " " */ - do j=100; if !.j then iterate /*Prime? Unprimeable must be composite*/ - Lm= length(j) /*obtain the length-1 of the number J. */ - meat= left(j, Lm) /*obtain the first Lm digits of J. */ - /* [↑] examine the "end" digit of J. */ - do e_=1 for eds; new= meat || ed.e_ /*obtain a different number (than J).*/ - if new==j then iterate /*Is it the original number? Then skip.*/ - if !.new then iterate j /*This new number a prime? " " */ - end /*e_*/ - /* [↑] examine a new 1st digit of J. */ - do f_=0 for 10; new= (f_||meat) + 0 /*obtain a different number (than J).*/ - if new==j then iterate /*Is it the original number? Then skip.*/ - if !.new then iterate j /*This new number a prime? " " */ - end /*f_*/ /* [↑] examine the front digit of J. */ - do a_= 2 for Lm-1 /*traipse through the middle digits. */ - meat= left(j, a_ - 1) /*use a number of left─most dec. digits*/ - rest= substr(j, a_ + 1) /* " " " " right─most " " */ - do n_=0 for 10 /*traipse through all 1─digit numbers. */ - new= meat || n_ || rest /*construct new number, like a phoenix.*/ - if new==j then iterate /*Is it the original number? Then skip.*/ - if !.new then iterate j /*This new number a prime? " " */ - end /*n_*/ - end /*a_*/ - u= u + 1 /*bump the count of unprimeable numbers*/ - if u<=n then $$= $$ commas(j) /*maybe add unprimeable # to $$ list.*/ - if u==x then $.ox= commas(j) /*assign the Xth unprimeable number.*/ - parse var j '' -1 _ /*obtain the right─most dec digit of J.*/ - if $._==. then $._= j /*the 1st unprimeable # that ends in _.*/ - if $.3==. then iterate; if $.7==. then iterate /*test if specific #'s found.*/ - if $.1==. then iterate; if $.9==. then iterate /* " " " " " */ - leave /*if here, then we're done. */ - end /*j*/ +-- 24 Aug 2025 +include Setting -if n>0 then do; say center(' first ' n "unprimeable numbers ", 139, '═') - say strip($$); say - end -if x>0 then say ' the ' th(x) " unprimeable number is: " $.ox +say 'UNPRIMEABLE NUMBERS' +say version say - do o=0 for 10; if length($.o)==0 then iterate - say ' the first unprimeable number that ends in ' o " is:"right(commas($.o),11) - end /*o*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -commas: parse arg ?; do c=length(?)-3 to 1 by -3; ?=insert(',', ?, c); end; return ? -th:procedure;parse arg x;return x||word('th st nd rd',1+(x//10)*(x//100%10\==1)*(x//10<4)) -/*──────────────────────────────────────────────────────────────────────────────────────*/ -genP: @.1=2; @.2=3; @.3=5; @.4=7; @.5=11; @.6=13; @.7=17; @.8=19; @.9=23; @.10=29; @.11=31 - !.=0; !.2=1; !.3=1; !.5=1; !.7=1; !.11=1; !.13=1; !.17=1; !.19=1; !.23=1; !.29=1 - #= 11; sq.#= @.# **2 - do lim=100 until lim*lim>=hp /*only keep primes up to the sqrt(hp). */ - end /*lim*/ /* [↑] find limit for storing primes. */ - do j=@.#+2 by 2 to hp; parse var j '' -1 _; if _==5 then iterate /*÷ by 5?*/ - if j// 3==0 then iterate; if j// 7==0 then iterate; if j//11==0 then iterate - if j//13==0 then iterate; if j//17==0 then iterate; if j//19==0 then iterate - if j//23==0 then iterate; if j//29==0 then iterate - do k=11 while sq.k<=j /*divide by some generated odd primes. */ - if j//@.k==0 then iterate j /*Is J divisible by P? Then not prime*/ - end /*k*/ /* [↓] a prime (J) has been found. */ - #= #+1; if #<=lim then @.#=j; !.j=1 /*bump prime count; assign prime to @. */ - sq.#= j*j /*calculate square of J for fast WHILE.*/ +call GetPrimes +call GetUnprimes +call Task1 +call Task2 +call GetLowest +call Task3 +exit + +GetPrimes: +procedure expose prim. flag. +call Time('r') +say 'Get primes up to 10 million...' +call Primes 1e7 +say prim.0 'primes found' +say Format(Time('e'),,3) 'seconds'; say +return + +GetUnprimes: +procedure expose flag. unpr. +call Time('r') +say 'Get unprimeable numbers up to 1.3 million...' +unpr. = 0; n = 0 +do i = 100 to 1.3e6 + if \ flag.i then do + a = 1; b = Length(i) + do j = a to b + c = Substr(i,j,1) + do k = 0 to 9 + d = Left(i,j-1)||k||Right(i,b-j); d = d+0 + if flag.d then + iterate i + end + end + n = n+1; unpr.n = i + end +end +unpr.0 = n +say unpr.0 'unprimeable numbers found' +say Format(Time('e'),,3) 'seconds'; say +return + +Task1: +procedure expose unpr. +call Time('r') +say 'The first 35 unprimeable numbers are' +do i = 1 to 35 + call Charout ,Right(unpr.i,4) +end +say +say Format(Time('e'),,3) 'seconds'; say +return + +Task2: +procedure expose unpr. +call Time('r') +say 'The 600th unprimeable number is' +say unpr.600 +say Format(Time('e'),,3) 'seconds'; say +return + +GetLowest: +procedure expose unpr. lowu. +call Time('r') +say 'Get lowest unprimeable number per digit...' +lowu. = 0 +do i = 1 to unpr.0 + a = Right(unpr.i,1) + if lowu.a = 0 then + lowu.a = unpr.i +end +say Format(Time('e'),,3) 'seconds'; say +return + +Task3: +procedure expose lowu. +call Time('r') +say 'Dig Lowest' +say '-----------' +do i = 0 to 9 + say Right(i,3) Right(lowu.i,7) +end +say '-----------' +say Format(Time('e'),,3) 'seconds'; say +return + +include Math diff --git a/Task/Unprimeable-numbers/Rust/unprimeable-numbers-1.rust b/Task/Unprimeable-numbers/Rust/unprimeable-numbers-1.rs similarity index 100% rename from Task/Unprimeable-numbers/Rust/unprimeable-numbers-1.rust rename to Task/Unprimeable-numbers/Rust/unprimeable-numbers-1.rs diff --git a/Task/Unprimeable-numbers/Rust/unprimeable-numbers-2.rust b/Task/Unprimeable-numbers/Rust/unprimeable-numbers-2.rs similarity index 100% rename from Task/Unprimeable-numbers/Rust/unprimeable-numbers-2.rust rename to Task/Unprimeable-numbers/Rust/unprimeable-numbers-2.rs diff --git a/Task/Unprimeable-numbers/Rust/unprimeable-numbers-3.rust b/Task/Unprimeable-numbers/Rust/unprimeable-numbers-3.rs similarity index 100% rename from Task/Unprimeable-numbers/Rust/unprimeable-numbers-3.rust rename to Task/Unprimeable-numbers/Rust/unprimeable-numbers-3.rs diff --git a/Task/Unprimeable-numbers/Uiua/unprimeable-numbers.uiua b/Task/Unprimeable-numbers/Uiua/unprimeable-numbers.uiua new file mode 100644 index 0000000000..7a2a667c48 --- /dev/null +++ b/Task/Unprimeable-numbers/Uiua/unprimeable-numbers.uiua @@ -0,0 +1,18 @@ +IsP ← ⨬(=⊣⊸°/×|0)⊸<₂ +# IsUnp ← ¬/↥IsP°⊥₁₀/⊂≡(≡(⍜⊡⋅)⊙⊙(⇡10)∩¤)⇡⊃⧻¤⊥₁₀ # Not needed. + +Lim ← 1210000 +Primes ← ▽=⊸≡(⊣⊸°/×)↘2⇡Lim +# Swap out each digit of the primes to eliminate non-Unprimeables. +Swaps ← °⊥₁₀/⊂≡(≡(⍜⊡⋅)⊙⊙(⇡10)∩¤)⇡⊃⧻¤⊥₁₀ + +Specials ← ♭≡([⊃(+₂|+₃|+₅|+₇)])˜ⁿ10↘2⇡7 # catch 1007 etc +# Swap out first digit of the specials to catch 1007 etc +Swaps₁ ← °⊥₁₀/⊂≡(≡(⍜⊡⋅)⊙⊙(⇡10)∩¤)[-1∘]⊃⧻¤⊥₁₀ + +˜▽°⊏↙Lim¬°⊚◴ ⊂/◇⊂≡⍚Swaps Primes /◇⊂≡⍚Swaps₁ Specials +# Larger numbers will have swaps bigger than our limit. +# Check these manually. +FirstGood ← ⊢▽¬⊸≡(/↥≡IsP Swaps₁)⬚190↙₁₀ # 190 is Unp, so neutral. + +⊃(&p⊕FirstGood⊸◿₁₀|&p⊡599|&p↙35) diff --git a/Task/Untouchable-numbers/Delphi/untouchable-numbers.delphi b/Task/Untouchable-numbers/Delphi/untouchable-numbers.pas similarity index 100% rename from Task/Untouchable-numbers/Delphi/untouchable-numbers.delphi rename to Task/Untouchable-numbers/Delphi/untouchable-numbers.pas diff --git a/Task/Untouchable-numbers/Java/untouchable-numbers.java b/Task/Untouchable-numbers/Java/untouchable-numbers.java new file mode 100644 index 0000000000..fb04917437 --- /dev/null +++ b/Task/Untouchable-numbers/Java/untouchable-numbers.java @@ -0,0 +1,114 @@ +import java.util.*; +import java.io.*; + +public class UntouchableNumbers { + + static int sumDivisors(int n) { + int sum = 1; + int k = 2; + if (n % 2 == 0) { + k = 1; + } + for (int i = 1 + k; (long) i * i <= n; i += k) { + if (n % i == 0) { + sum += i; + int j = n / i; + if (j != i) { + sum += j; + } + } + } + return sum; + } + + // Marks as true the integers that appear as a proper-divisor sum of some i (6..n+1). + static boolean[] sieve(int n) { + int m = n + 1; // mirror the Go code's n++ trick + boolean[] s = new boolean[m + 1]; // all false by default + for (int i = 6; i <= m; i++) { + int sd = sumDivisors(i); + if (sd <= m) { + s[sd] = true; + } + } + return s; + } + + // True = composite, False = prime (like the Go version) + static boolean[] primeSieve(int limit) { + int lim = limit + 1; + boolean[] c = new boolean[lim]; + c[0] = true; + c[1] = true; + int p = 3; + while (true) { + long p2 = (long) p * p; + if (p2 >= lim) break; + for (int i = (int) p2; i < lim; i += 2 * p) { + c[i] = true; + } + while (true) { + p += 2; + if (p >= lim || !c[p]) break; + } + if (p >= lim) break; + } + return c; + } + + static String commatize(long n) { + boolean neg = n < 0; + String s = Long.toString(Math.abs(n)); + StringBuilder sb = new StringBuilder(); + int le = s.length(); + int first = le % 3; + if (first == 0 && le > 0) first = 3; + sb.append(s, 0, first); + for (int i = first; i < le; i += 3) { + if (sb.length() > 0) sb.append(','); + sb.append(s, i, i + 3); + } + return neg ? "-" + sb : sb.toString(); + } + + public static void main(String[] args) { + final int limit = 10_000; + + boolean[] composite = primeSieve(limit); + boolean[] sumsSeen = sieve(63 * limit); + + List untouchable = new ArrayList<>(); + untouchable.add(2); + untouchable.add(5); + + for (int n = 6; n <= limit; n += 2) { + if (!sumsSeen[n] && composite[n - 1] && composite[n - 3]) { + untouchable.add(n); + } + } + + System.out.println("List of untouchable numbers <= 2,000:"); + int count = 0; + for (int i = 0; i < untouchable.size() && untouchable.get(i) <= 2000; i++) { + System.out.printf("%6s", commatize(untouchable.get(i))); + if ((i + 1) % 10 == 0) System.out.println(); + count++; + } + System.out.printf("%n%n%7s untouchable numbers were found <= 2,000%n", commatize(count)); + + int p = 10; + count = 0; + for (int n : untouchable) { + count++; + if (n > p) { + System.out.printf("%7s untouchable numbers were found <= %9s%n", + commatize(count - 1), commatize(p)); + p *= 10; + if (p == limit) break; + } + } + + System.out.printf("%7s untouchable numbers were found <= %s%n", + commatize(untouchable.size()), commatize(limit)); + } +} diff --git a/Task/Untouchable-numbers/Julia/untouchable-numbers.julia b/Task/Untouchable-numbers/Julia/untouchable-numbers.jl similarity index 100% rename from Task/Untouchable-numbers/Julia/untouchable-numbers.julia rename to Task/Untouchable-numbers/Julia/untouchable-numbers.jl diff --git a/Task/Untouchable-numbers/Python/untouchable-numbers.py b/Task/Untouchable-numbers/Python/untouchable-numbers.py new file mode 100644 index 0000000000..504d73487a --- /dev/null +++ b/Task/Untouchable-numbers/Python/untouchable-numbers.py @@ -0,0 +1,93 @@ +def prime_sieve(limit: int): + p = 3 + + limit += 1 + + c = [False] * limit + + c[0] = True + c[1] = True + + for i in range(4, limit, 2): + c[i] = True + + while True: + p2 = p * p + + if p2 >= limit: + break + + for i in range(p2, limit, 2 * p): + c[i] = True + + while True: + p += 2 + + if not c[p]: + break + + return c + +def main(): + limit = 1000000 + + uc = 2 + p = 10 + m = 63 + ul = 151000 + + c = prime_sieve(limit) + n = m * limit + 1 + + sum_divs = [0] * n + + for i in range(1, n): + for j in range(i, n, i): + sum_divs[j] += i + + s = [False] * n + + for i in range(1, n): + sumation = sum_divs[i] - i + if sumation <= n: + s[sumation] = True + + untouchable = [0] * ul + + untouchable[0] = 2 + untouchable[1] = 5 + + for n in range(6, limit+1, 2): + if not s[n] and c[n - 1] and c[n-3]: + untouchable[uc] = n + uc += 1 + + print("List of untouchable numbers <= 2,000:") + + for i in range(uc): + j = untouchable[i] + + if j > 2000: + break + + print("%3d " % j, end=' ') + + if not ((i+1) % 10): + print() + + print("\n\n%d untouchable numbers were found <= 2,000\n" % i) + + for i in range(uc): + j = untouchable[i] + + if j > p: + print("%d untouchable numbers were found <= %d\n" % (i, p)) + p *= 10 + + if p == limit: + break + + print("%d untouchable numbers were found <= %d" % (uc, limit)) + +if __name__ == '__main__': + main() diff --git a/Task/Untouchable-numbers/REXX/untouchable-numbers.rexx b/Task/Untouchable-numbers/REXX/untouchable-numbers.rexx index 7faaf0888c..7a7c0904dd 100644 --- a/Task/Untouchable-numbers/REXX/untouchable-numbers.rexx +++ b/Task/Untouchable-numbers/REXX/untouchable-numbers.rexx @@ -1,61 +1,84 @@ -/*REXX pgm finds N untouchable numbers (numbers that can't be equal to any aliquot sum).*/ -parse arg n cols tens over . /*obtain optional arguments from the CL*/ -if n='' | n=="," then n=2000 /*Not specified? Then use the default.*/ -if cols='' | cols=="," | cols==0 then cols= 10 /* " " " " " " */ -if tens='' | tens=="," then tens= 0 /* " " " " " " */ -if over='' | over=="," then over= 20 /* " " " " " " */ -tell= n>0; n= abs(n) /*N>0? Then display the untouchable #s*/ -call genP n * over /*call routine to generate some primes.*/ -u.= 0 /*define all possible aliquot sums ≡ 0.*/ - do p=1 for #; _= @.p + 1; u._= 1 /*any prime+1 is not an untouchable.*/ - _= @.p + 3; u._= 1 /* " prime+3 " " " " */ - end /*p*/ /* [↑] this will also rule out 5. */ -u.5= 0 /*special case as prime 2 + 3 sum to 5.*/ - do j=2 for lim; if !.j then iterate /*Is J a prime? Yes, then skip it. */ - y= sigmaP() /*compute: aliquot sum (sigma P) of J.*/ - if y<=n then u.y= 1 /*mark Y as a touchable if in range. */ - end /*j*/ -call show /*maybe show untouchable #s and a count*/ -if tens>0 then call powers /*Any "tens" specified? Calculate 'em.*/ -exit cnt /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ? -genSq: do _=1 until _*_>lim; q._= _*_; end; q._= _*_; _= _+1; q._= _*_; return -grid: $= $ right( commas(t), w); if cnt//cols==0 then do; say $; $=; end; return -powers: do pr=1 for tens; call 'UNTOUCHA' -(10**pr); end /*recurse*/; return -/*──────────────────────────────────────────────────────────────────────────────────────*/ -genP: #= 9; @.1=2; @.2=3; @.3=5; @.4=7; @.5=11; @.6=13; @.7=17; @.8=19; @.9=23 /*a list*/ - !.=0; !.2=1; !.3=1; !.5=1; !.7=1; !.11=1; !.13=1; !.17=1; !.19=1 !.23=1 /*primes*/ - parse arg lim; call genSq /*define the (high) limit for searching*/ - qq.10= 100 /*define square of the 10th prime index*/ - do j=@.#+6 by 2 to lim /*find odd primes from here on forward.*/ - parse var j '' -1 _; if _==5 then iterate; if j// 3==0 then iterate - if j// 7==0 then iterate; if j//11==0 then iterate; if j//13==0 then iterate - if j//17==0 then iterate; if j//19==0 then iterate; if j//23==0 then iterate - /*start dividing by the tenth prime: 29*/ - do k=10 while qq.k <= j /* [↓] divide J by known odd primes.*/ - if j//@.k==0 then iterate j /*J ÷ by a prime? Then ¬prime. ___ */ - end /*k*/ /* [↑] only process numbers ≤ √ J */ - #= #+1; @.#= j /*bump prime count; assign a new prime.*/ - !.j= 1; qq.#= j*j /*mark prime; compute square of prime.*/ - end /*j*/; return /*#: is the number of primes generated*/ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -show: w=7; $= right(2, w+1) right(5, w) /*start the list of an even prime and 5*/ - cnt= 2 /*count of the only two primes in list.*/ - do t=6 by 2 to n; if u.t then iterate /*Is T touchable? Then skip it. */ - cnt= cnt + 1; if tell then call grid /*bump count; maybe show a grid line. */ - end /*t*/ - if tell & $\=='' then say $ /*display a residual grid line, if any.*/ - if tell then say /*show a spacing blank line for output.*/ - if n>0 then say right( commas(cnt), 20) , /*indent the output a bit.*/ - ' untouchable numbers were found ≤ ' commas(n); return -/*──────────────────────────────────────────────────────────────────────────────────────*/ -sigmaP: s= 1 /*set initial sigma sum (S) to 1. ___*/ - if j//2 then do m=3 by 2 while q.m a then do + say right(n,5) 'below' right(a,6) + a = a*10 + end + n = n+1 +end +say +return + +-- Primes; Timer +include Math diff --git a/Task/Update-a-configuration-file/AArch64-Assembly/update-a-configuration-file.aarch64 b/Task/Update-a-configuration-file/AArch64-Assembly/update-a-configuration-file.aarch64 new file mode 100644 index 0000000000..7c7d70f5b7 --- /dev/null +++ b/Task/Update-a-configuration-file/AArch64-Assembly/update-a-configuration-file.aarch64 @@ -0,0 +1,734 @@ +/* ARM assembly AARCH64 Raspberry PI 3B */ +/* program modifconf64.s */ +/* This programm use a instruction file (conf2mod.txt) to modify a + configuration file (conf2.txt). + Instruction file example : + +# This is a instruction file in standard configuration file format +# + +# This is a favourite fruit add parameter +FAVOURITEFRUIT banana apple + +# This is a boolean that should be unset +;NEEDSPEELING + +# This boolean is now commented + SEEDSREMOVED + +# How many bananas we have change parameter +NUMBEROFBANANAS 1024 + +# numberoffrefraberries new option +NUMBEROFFREFRABERRIES 62000 + +*/ + +/*******************************************/ +/* Constantes */ +/*******************************************/ +/* for this file see task include a file in language AArch64 assembly*/ +.include "../includeConstantesARM64.inc" +.equ BUFFERSIZE, 10000 +.equ NBPARAM, 20 + +.equ O_RDWR, 0x0002 // open for reading and writing +.equ O_RDONLY, 0 +.equ O_APPEND, 0x400 +.equ O_CREAT, 0x40 +/*******************************************/ +/* Macros */ +/*******************************************/ +//.include "../../ficmacros64.inc" // for developer debugging + +/************************************/ +/* structure */ +/************************************/ + +/* structure instruction linkedlist*/ + .struct 0 +llistOpt_next: // next element + .struct llistOpt_next + 8 +llistOpt_address: // element value + .struct llistOpt_address + 8 +llistOpt_value: // element value + .struct llistOpt_value + 8 +llistOpt_end: + +/*******************************************/ +/* Initialized data */ +/*******************************************/ +.data +szMessDebutPgm: .asciz "Program 64 bits start. \n" +szCarriageReturn: .asciz "\n" +szMessFinOK: .asciz "Program normal end. \n" +szMessOpen: .asciz "File open error.\n" +szMessRead: .asciz "File read error.\n" +szMessWrite: .asciz "File write error.\n" +szMessClose: .asciz "File close error.\n" +szFileName1: .asciz "conf2.txt" +szFileInstr: .asciz "conf2mod.txt" +szFileNameWrite: .asciz "conf2new.txt" + +/*******************************************/ +/* UnInitialized data */ +/*******************************************/ +.bss +sBuffer: .skip BUFFERSIZE +sBufferInst: .skip BUFFERSIZE +sBufferWrite: .skip BUFFERSIZE +.align 4 +sZoneConv: .skip 24 +iPtrRead: .skip 8 +iPtrReadInstr: .skip 8 +iPtrWrite: .skip 8 +llistLineInstr: .skip llistOpt_end * NBPARAM +/*******************************************/ +/* code section */ +/*******************************************/ +.text +.global main +main: // INFO; main + ldr x0,qAdrszMessDebutPgm + bl affichageMess + ldr x0,qAdrszMessDebutPgm + ldr x0,qAdrszFilename1 + ldr x1,qAdrsBuffer // read configuration file + mov x2,#BUFFERSIZE + bl readFile + cmp x0,#-1 + beq 100f + mov x4,x0 // buffer size + ldr x0,qAdrszFileInstr + ldr x1,qAdrsBufferInst // read instruction file + mov x2,#BUFFERSIZE + bl readFile + cmp x0,#-1 + beq 100f + mov x11,x0 // buffer instrc size +1: // loop line instructions file + ldr x0,qAdrsBufferInst + mov x1,x11 + ldr x2,qAdriPtrReadInstr + bl readLine + cmp x0,#-1 // end line ? + beq 2f + mov x2,x0 // line pointer + ldr x0,qAdrsBufferInst // instruction parser + add x0,x0,x2 + ldr x2,qAdrllistLineInstr + bl lineInstrParser + b 1b + +2: + //ldr x0,qAdrllistLineInstr // for control llist + // bl displayListInst + +3: // loop line reading + ldr x0,qAdrsBuffer // read line of buffer + mov x1,x4 + ldr x2,qAdriPtrRead + bl readLine + cmp x0,#-1 // end line ? + beq 4f + mov x2,x0 + ldr x0,qAdrsBuffer // line parser + add x0,x0,x2 + ldr x2,qAdrsBufferWrite + bl lineParser + b 3b +4: + ldr x0,qAdrllistLineInstr // write new options in end ofbuffer + ldr x1,qAdrsBufferWrite + bl insertNewOptions + + ldr x0,qAdrszFileNameWrite // write file name + ldr x1,qAdrsBufferWrite // write buffer + ldr x2,qAdriPtrWrite // load buffer size to write + ldr x2,[x2] + bl writeFile + + ldr x0,qAdrszMessFinOK + bl affichageMess + +100: // standard end of the program + mov x0, #0 // return code + mov x8,EXIT + svc 0 // perform system call +qAdrszMessDebutPgm: .quad szMessDebutPgm +qAdrszMessFinOK: .quad szMessFinOK +qAdrszCarriageReturn: .quad szCarriageReturn +qAdrsBuffer: .quad sBuffer +qAdrszFilename1: .quad szFileName1 +qAdriPtrWrite: .quad iPtrWrite +qAdrszFileInstr: .quad szFileInstr +qAdrsBufferInst: .quad sBufferInst +qAdriPtrReadInstr: .quad iPtrReadInstr +qAdrllistLineInstr: .quad llistLineInstr +qAdrsBufferWrite: .quad sBufferWrite +/*******************************************/ +/* Parser line instruction file */ +/*******************************************/ +/* x0 line address */ +/* x1 line size */ +/* x2 address line list */ +lineInstrParser: // INFO: lineInstrParser + stp x1,lr,[sp,-16]! + stp x2,x3,[sp,-16]! + stp x4,x5,[sp,-16]! + stp x6,x7,[sp,-16]! + mov x5,x0 + mov x6,#0 + cmp x1,#0 // empty line ? + beq 100f +1: + ldrb w4,[x5,x6] + cmp x4,#'#' // comment line ? + beq 100f + cmp x4,#' ' + cinc x6,x6,eq + beq 1b + cmp x6,x1 // space line + bge 100f + mov x4,#0 + strb w4,[x0,x1] // final zero on line instruction + mov x0,x5 + mov x0,x2 + mov x1,x5 // begin line address + mov x2,#0 // mark use key word + bl insertElementParam + +100: + ldp x6,x7,[sp],16 + ldp x4,x5,[sp],16 + ldp x2,x3,[sp],16 + ldp x1,lr,[sp],16 + ret +/*******************************************/ +/* Parser line configuration file */ +/*******************************************/ +/* x0 address line */ +/* x1 line size */ +/* x2 Address buffer */ +lineParser: // INFO: lineParser + stp x1,lr,[sp,-16]! + stp x2,x3,[sp,-16]! + stp x4,x5,[sp,-16]! + stp x6,x7,[sp,-16]! + stp x8,x9,[sp,-16]! + cmp x1,#0 // empty line ? + bne 1f + mov x0,x2 + bl writeEndLine + b 100f +1: + mov x6,x0 + mov x7,x1 // line size + mov x8,x2 // buffer address + mov x4,#0 + ldrb w5,[x0,x4] // load first character + cmp x5,#'#' // comment ? + bne 2f + mov x1,x8 + mov x2,x7 + bl copyLine + mov x0,x8 + bl writeEndLine + b 100f +2: + mov x4,#0 +3: // supp spaces + ldrb w3,[x6,x4] + cmp x3,#' ' + cinc x4,x4,eq + beq 3b + cmp x3,#0 // spaces line + beq 100f + cmp x3,#';' // unmark + bne 5f + add x4,x4,#1 +4: // supp space after ; + ldrb w3,[x6,x4] + cmp x3,#' ' + cinc x4,x4,eq + beq 4b + cmp x3,#0 // spaces line + beq 100f +5: + add x0,x0,x4 // word key address + mov x1,x7 // line size + bl traitwordkey + cmp x0,#0 + bne 6f + mov x0,x6 + mov x1,x8 // word key not modified + mov x2,x7 // copy line + bl copyLine + mov x0,x8 + bl writeEndLine + b 100f +6: + mov x0,x1 // line instruction address + mov x1,x8 // line conf + bl copyLineInst + mov x0,x8 + bl writeEndLine + b 100f + +100: + ldp x8,x9,[sp],16 + ldp x6,x7,[sp],16 + ldp x4,x5,[sp],16 + ldp x2,x3,[sp],16 + ldp x1,lr,[sp],16 + ret +/***************************************************/ +/* word key analyser */ +/***************************************************/ +/* x0 contains address begin word key */ +/* x1 line size */ +/* x0 return list element address */ +/* x1 return new line pointer */ +traitwordkey: // INFO: traitwordkey + stp x2,lr,[sp,-16]! + stp x3,x4,[sp,-16]! + mov x5,x0 + mov x4,#0 +1: // loop size compute + ldrb w3,[x0,x4] + cmp x3,#' ' // end key + beq 2f + cmp x3,#'=' // end key + beq 2f + cmp x3,#0x0D // end key + beq 2f + add x4,x4,#1 // increment indice and loop + cmp x4,x1 + blt 1b +2: + mov x0,x5 // addresse begin key + mov x1,x4 // key size + ldr x2,qAdrllistLineInstr + bl searchKeyWord + cmp x0,#0 + beq 100f + + mov x0,#1 + +100: + ldp x3,x4,[sp],16 + ldp x2,lr,[sp],16 + ret +/***************************************************/ +/* search word key in instructions llist */ +/***************************************************/ +/* x0 contains address key word */ +/* x1 key word size */ +/* x2 contains list instrction address */ +/* x0 return 0 if not found 1 is found */ +/* x1 return line instructions address */ +searchKeyWord: // INFO: searchKeyWord + stp x2,lr,[sp,-16]! + stp x3,x4,[sp,-16]! + stp x5,x6,[sp,-16]! + stp x7,x8,[sp,-16]! + stp x9,x10,[sp,-16]! + mov x6,x0 + mov x7,x1 + mov x8,x2 +1: + ldr x2,[x8,#llistOpt_next] // end list ? + cmp x2,#0 + beq 6f // yes + ldr x1,[x8,#llistOpt_address] // load line address + mov x4,#0 + mov x0,x1 +2: + ldrb w5,[x1,x4] + cmp x5,#';' + cinc x4,x4,eq + beq 2b + cmp x5,#' ' + cinc x4,x4,eq + beq 2b + mov x9,#0 + +3: + ldrb w3,[x6,x9] + cmp x3,x5 + bne 4f + add x9,x9,#1 + cmp x9,x7 + bge 5f + add x4,x4,#1 + ldrb w5,[x1,x4] + cmp x5,#' ' + beq 5f + cmp x5,#0 + beq 5f + b 3b +4: + mov x8,x2 + b 1b +5: + mov x0,#1 // found ! + str x0,[x8,#llistOpt_value] + b 100f +6: + mov x0,#0 // not found + +100: + ldp x9,x10,[sp],16 + ldp x7,x8,[sp],16 + ldp x5,x6,[sp],16 + ldp x3,x4,[sp],16 + ldp x2,lr,[sp],16 + ret +/***************************************************/ +/* write end line */ +/***************************************************/ +/* x0 contains buffer address */ +writeEndLine: // INFO: writeEndLine + stp x1,lr,[sp,-16]! + stp x2,x3,[sp,-16]! + ldr x2,qAdriPtrWrite + ldr x3,[x2] + mov x1,#0x0D + strb w1,[x0,x3] + add x3,x3,#1 + mov x1,#0x0A + strb w1,[x0,x3] + add x3,x3,#1 + str x3,[x2] +100: + ldp x2,x3,[sp],16 + ldp x1,lr,[sp],16 + ret +/***************************************************/ +/* read file */ +/***************************************************/ +/* x0 contains file name */ +/* x1 contains a file buffer */ +/* x2 contains buffer size */ +/* x0 return buffer size */ +readFile: // INFO: readFile + stp x1,lr,[sp,-16]! + stp x2,x3,[sp,-16]! + stp x4,x5,[sp,-16]! + stp x6,x7,[sp,-16]! + stp x8,x9,[sp,-16]! + mov x7,x0 + mov x9,x1 // file buffer + mov x6,x2 + mov x10,x3 + mov x0,AT_FDCWD + mov x1,x7 // file name + mov x2,#O_RDWR // flags + mov x3,#0 // mode + mov x8,OPEN + svc 0 + cmp x0,#0 // error ? + ble 99f + mov x7,x0 // FD save + + mov x0,x7 + mov x1,x9 // read buffer address + mov x2,x6 + mov x8,READ // call system read file + svc 0 + cmp x0,#0 // error read ? + blt 97f + mov x6,x0 // save file size + mov x0,x7 // FD + mov x8,CLOSE // call system close file + svc 0 + cmp x0,#0 // error close ? + blt 96f + + mov x0,x6 // return buffer size + b 100f +96: // display error messages + ldr x0,qAdrszMessClose + bl affichageMess + mov x0,#-1 // error + b 100f +97: + ldr x0,qAdrszMessRead + bl affichageMess + mov x0,#-1 // error + b 100f +99: + ldr x0,qAdrszMessOpen + bl affichageMess + mov x0,#-1 // error + + 100: + ldp x8,x9,[sp],16 + ldp x6,x7,[sp],16 + ldp x4,x5,[sp],16 + ldp x2,x3,[sp],16 + ldp x1,lr,[sp],16 + ret +qAdrszMessOpen: .quad szMessOpen +qAdrszMessRead: .quad szMessRead +qAdrszMessClose: .quad szMessClose +/***************************************************/ +/* write file */ +/***************************************************/ +/* x0 contains file name */ +/* x1 contains a file buffer */ +/* x2 contains buffer size */ +/* x0 return -1 if error */ +writeFile: // INFO: writeFile + stp x1,lr,[sp,-16]! + stp x2,x3,[sp,-16]! + stp x4,x5,[sp,-16]! + stp x6,x7,[sp,-16]! + stp x8,x9,[sp,-16]! + mov x4,x1 + mov x5,x2 + mov x7,x0 + mov x0,AT_FDCWD + mov x1,x7 + ldr x2,iFlag // flags + mov x3,#0644 // mode in octal + mov x8,OPEN + svc 0 + cmp x0,#0 // error open + ble 99f + mov x9,x0 + mov x0,x9 // file FD + mov x1,x4 // write buffer + mov x2,x5 // buffer size + mov x8,#WRITE + svc 0 + cmp x0,#0 // error open + ble 97f + mov x0,x9 // FD + mov x8,#CLOSE // call system close file + svc 0 + cmp x0,#0 // error close ? + blt 96f + + b 100f + +96: // display error messages + ldr x0,qAdrszMessClose + bl affichageMess + mov x0,#-1 // error + b 100f + +97: + ldr x0,qAdrszMessWrite + bl affichageMess + mov x0,#-1 // error + b 100f +99: + ldr x0,qAdrszMessOpen + bl affichageMess + mov x0,#-1 // error +100: + ldp x8,x9,[sp],16 + ldp x6,x7,[sp],16 + ldp x4,x5,[sp],16 + ldp x2,x3,[sp],16 + ldp x1,lr,[sp],16 + ret +qAdrszMessWrite: .quad szMessWrite +qAdrszFileNameWrite: .quad szFileNameWrite +iFlag: .quad O_RDWR|O_CREAT +/***************************************************/ +/* read line */ +/***************************************************/ +/* x0 contains a file buffer */ +/* x1 contains text buffer size */ +/* x2 contains read pointer */ +/* x0 return pointer address line or -1 if end */ +/* x1 return line size */ +readLine: // INFO: readLine + stp x2,lr,[sp,-16]! + stp x3,x4,[sp,-16]! + stp x5,x6,[sp,-16]! + ldr x3,[x2] + cmp x3,x1 // end buffer ? + bge 99f + mov x4,x3 + mov x6,#0 // line size +1: + ldrb w5,[x0,x4] + cmp x5,#0x0D + beq 3f + add x4,x4,#1 + cmp x4,x1 // end buffer ? + blt 2f + str x4,[x2] // new begin line pointeur + mov x0,x3 // line begin + mov x1,x6 // return size + b 100f // end + 2: + add x6,x6,#1 + b 1b // and loop +3: + add x4,x4,#2 // supp 0D0A + str x4,[x2] // new begin line pointeur + mov x0,x3 // line begin + mov x1,x6 // return size + b 100f +99: + mov x0,-1 +100: + ldp x5,x6,[sp],16 + ldp x3,x4,[sp],16 + ldp x2,lr,[sp],16 + ret +qAdriPtrRead: .quad iPtrRead +/******************************************************************/ +/* copy new options line */ +/******************************************************************/ +/* x0 contains line address */ +/* x1 contains address buffer */ +copyLineInst: // INFO: copyLineInst + stp x1,lr,[sp,-16]! + stp x2,x3,[sp,-16]! + stp x4,x5,[sp,-16]! + ldr x2,qAdriPtrWrite + ldr x3,[x2] // load pointer write buffer + mov x4,#0 +1: + ldrb w5,[x0,x4] // load byte + cmp x5,#0 // final zero + beq 2f + strb w5,[x1,x3] // store byte in buffer + add x3,x3,#1 + add x4,x4,#1 + b 1b +2: + str x3,[x2] // save pointer write buffer +100: + ldp x4,x5,[sp],16 + ldp x2,x3,[sp],16 + ldp x1,lr,[sp],16 + ret +/******************************************************************/ +/* copy file line */ +/******************************************************************/ +/* x0 contains line address */ +/* x1 contains address buffer +/* x2 contains characters number to copy */ +copyLine: // INFO: copyLine + stp x1,lr,[sp,-16]! + stp x2,x3,[sp,-16]! + stp x4,x5,[sp,-16]! + stp x6,x7,[sp,-16]! + mov x6,x2 + ldr x2,qAdriPtrWrite + ldr x3,[x2] + mov x4,#0 +1: + ldrb w5,[x0,x4] // load byte + strb w5,[x1,x3] // store byte in buffer + add x3,x3,#1 + add x4,x4,#1 + cmp x4,x6 + blt 1b +2: + str x3,[x2] +100: + ldp x6,x7,[sp],16 + ldp x4,x5,[sp],16 + ldp x2,x3,[sp],16 + ldp x1,lr,[sp],16 + ret +/******************************************************************/ +/* insertion nex options in configuration */ +/******************************************************************/ +/* x0 contains the address of the list */ +/* x1 write buffer address */ +insertNewOptions: // INFO: insertNewOptions + stp x1,lr,[sp,-16]! + stp x2,x3,[sp,-16]! + stp x4,x5,[sp,-16]! + mov x4,x0 +1: // display loop param + ldr x2,[x4,#llistOpt_next] // end list ? + cmp x2,#0 + beq 100f // yes + ldr x3,[x4,#llistOpt_value] + cmp x3,#1 + beq 2f + ldr x0,[x4,#llistOpt_address] // load line address + bl copyLineInst +2: + mov x4,x2 // and loop new item + b 1b + +100: + ldp x4,x5,[sp],16 + ldp x2,x3,[sp],16 + ldp x1,lr,[sp],16 + ret +/******************************************************************/ +/* display list instruction */ +/******************************************************************/ +/* x0 contains the address of the list */ +displayListInst: // INFO: displayListInst + stp x1,lr,[sp,-16]! + stp x2,x3,[sp,-16]! + mov x1,x0 +1: // display loop param + ldr x2,[x1,#llistOpt_next] // end list ? + cmp x2,#0 + beq 100f // yes + ldr x0,[x1,#llistOpt_address] // load line address + bl affichageMess + ldr x0,qAdrszCarriageReturn + bl affichageMess + mov x1,x2 + b 1b + +100: + ldp x2,x3,[sp],16 + ldp x1,lr,[sp],16 + ret + +/******************************************************************/ +/* insert element at end of list */ +/******************************************************************/ +/* x0 contains the address of the list */ +/* x1 contains key string address */ +/* x2 contains option list address +/* x0 returns address of element or - 1 if error */ +insertElementParam: // INFO: insertElementParam + stp x1,lr,[sp,-16]! + stp x2,x3,[sp,-16]! + stp x4,x5,[sp,-16]! + mov x4,#llistOpt_end * NBPARAM + add x4,x4,x0 // compute address end list +1: // start loop + ldr x3,[x0,#llistOpt_next] // load next pointer + cmp x3,#0 // = zero + csel x0,x3,x0,ne // no -> loop with pointer + //movne x0,x3 // no -> loop with pointer + bne 1b + add x3,x0,#llistOpt_end // yes -> compute next free address + cmp x3,x4 // > list end + bge 99f // yes -> error + str x3,[x0,#llistOpt_next] // store next address in current pointer + str x1,[x0,#llistOpt_address] // store element value + str x2,[x0,#llistOpt_value] + mov x1,#0 + str x1,[x3,#llistOpt_next] // init next pointer in next address + b 100f +99: + mov x0,-1 +100: + ldp x4,x5,[sp],16 + ldp x2,x3,[sp],16 + ldp x1,lr,[sp],16 + ret + +/***************************************************/ +/* ROUTINES INCLUDE */ +/***************************************************/ +/* for this file see task include a file in language AArch64 assembly*/ +.include "../includeARM64.inc" diff --git a/Task/Update-a-configuration-file/ARM-Assembly/update-a-configuration-file.arm b/Task/Update-a-configuration-file/ARM-Assembly/update-a-configuration-file.arm new file mode 100644 index 0000000000..e72a6ca3a3 --- /dev/null +++ b/Task/Update-a-configuration-file/ARM-Assembly/update-a-configuration-file.arm @@ -0,0 +1,654 @@ +/* ARM assembly Raspberry PI */ +/* program modifconf.s */ +/* REMARK 1 : this program use routines in a include file + see task Include a file language arm assembly + for the routine affichageMess conversion10 + see at end of this program the instruction include */ +/* This programm use a instruction file (conf2mod.txt) to modify a + configuration file (conf2.txt). + Instruction file example : + +# This is a instruction file in standard configuration file format +# + +# This is a favourite fruit add parameter +FAVOURITEFRUIT banana apple + +# This is a boolean that should be unset +;NEEDSPEELING + +# This boolean is now commented + SEEDSREMOVED + +# How many bananas we have change parameter +NUMBEROFBANANAS 1024 + +# numberoffrefraberries new option +NUMBEROFFREFRABERRIES 62000 + +*/ + +/*******************************************/ +/* Constantes */ +/*******************************************/ +.include "../constantes.inc" +.equ BUFFERSIZE, 10000 +.equ NBPARAM, 20 +.equ READ, 3 +.equ WRITE, 4 +.equ OPEN, 5 +.equ CLOSE, 6 +.equ O_RDWR, 0x0002 @ open for reading and writing +.equ O_RDONLY, 0 +.equ O_APPEND, 0x400 +.equ O_CREAT, 0x40 +/*******************************************/ +/* Macros */ +/*******************************************/ +//.include "../../ficmacros32.inc" @ for developer debugging + +/************************************/ +/* structure */ +/************************************/ + +/* structure instruction linkedlist*/ + .struct 0 +llistOpt_next: @ next element + .struct llistOpt_next + 4 +llistOpt_address: @ element value + .struct llistOpt_address + 4 +llistOpt_value: @ element value + .struct llistOpt_value + 4 +llistOpt_end: + +/*******************************************/ +/* Initialized data */ +/*******************************************/ +.data +szMessDebutPgm: .asciz "Program 32 bits start. \n" +szCarriageReturn: .asciz "\n" +szMessFinOK: .asciz "Program normal end. \n" +szMessOpen: .asciz "File open error.\n" +szMessRead: .asciz "File read error.\n" +szMessWrite: .asciz "File write error.\n" +szMessClose: .asciz "File close error.\n" +szFileName1: .asciz "conf2.txt" +szFileInstr: .asciz "conf2mod.txt" +szFileNameWrite: .asciz "conf2new.txt" +//szLib1: .asciz " : " +//szLib2: .asciz " = " +//szLib3: .asciz " " + +/*******************************************/ +/* UnInitialized data */ +/*******************************************/ +.bss +sBuffer: .skip BUFFERSIZE +sBufferInst: .skip BUFFERSIZE +sBufferWrite: .skip BUFFERSIZE +.align 4 +sZoneConv: .skip 24 +iPtrRead: .skip 4 +iPtrReadInstr: .skip 4 +iPtrWrite: .skip 4 +llistLineInstr: .skip llistOpt_end * NBPARAM +/*******************************************/ +/* code section */ +/*******************************************/ +.text +.global main +main: @ INFO; main + ldr r0,iAdrszMessDebutPgm + bl affichageMess + ldr r0,iAdrszMessDebutPgm + ldr r0,iAdrszFilename1 + ldr r1,iAdrsBuffer @ read configuration file + mov r2,#BUFFERSIZE + bl readFile + cmp r0,#-1 + beq 100f + mov r4,r0 @ buffer size + ldr r0,iAdrszFileInstr + ldr r1,iAdrsBufferInst @ read instruction file + mov r2,#BUFFERSIZE + bl readFile + cmp r0,#-1 + beq 100f + mov r11,r0 @ buffer instrc size +1: @ loop line instructions file + ldr r0,iAdrsBufferInst + mov r1,r11 + ldr r2,iAdriPtrReadInstr + bl readLine + cmp r0,#-1 @ end line ? + beq 2f + mov r2,r0 @ line pointer + ldr r0,iAdrsBufferInst @ instruction parser + add r0,r0,r2 + ldr r2,iAdrllistLineInstr + bl lineInstrParser + b 1b + +2: + // ldr r0,iAdrllistLineInstr @ for control llist + // bl displayListInst + +3: @ loop line reading + ldr r0,iAdrsBuffer @ read line of buffer + mov r1,r4 + ldr r2,iAdriPtrRead + bl readLine + cmp r0,#-1 @ end line ? + beq 4f + mov r2,r0 + ldr r0,iAdrsBuffer @ line parser + add r0,r0,r2 + ldr r2,iAdrsBufferWrite + bl lineParser + b 3b +4: + ldr r0,iAdrllistLineInstr @ write new options in end ofbuffer + ldr r1,iAdrsBufferWrite + bl insertNewOptions + + ldr r0,iAdrszFileNameWrite @ write file name + ldr r1,iAdrsBufferWrite @ write buffer + ldr r2,iAdriPtrWrite @ load buffer size to write + ldr r2,[r2] + bl writeFile + + ldr r0,iAdrszMessFinOK + bl affichageMess + +100: @ standard end of the program + mov r0, #0 @ return code + mov r7, #EXIT @ request to exit program + svc 0 @ perform system call +iAdrszMessDebutPgm: .int szMessDebutPgm +iAdrszMessFinOK: .int szMessFinOK +iAdrszCarriageReturn: .int szCarriageReturn +iAdrsBuffer: .int sBuffer +iAdrszFilename1: .int szFileName1 +//iAdrllistOptam: .int llistOptam +iAdriPtrWrite: .int iPtrWrite +iAdrszFileInstr: .int szFileInstr +iAdrsBufferInst: .int sBufferInst +iAdriPtrReadInstr: .int iPtrReadInstr +iAdrllistLineInstr: .int llistLineInstr +iAdrsBufferWrite: .int sBufferWrite +/*******************************************/ +/* Parser line instruction file */ +/*******************************************/ +/* r0 line address */ +/* r1 line size */ +/* r2 address line list */ +lineInstrParser: @ INFO: lineInstrParser + push {r1-r6,lr} + mov r5,r0 + mov r6,#0 + cmp r1,#0 @ empty line ? + beq 100f +1: + ldrb r4,[r5,r6] + cmp r4,#'#' @ comment line ? + beq 100f + cmp r4,#' ' + addeq r6,r6,#1 + beq 1b + cmp r6,r1 @ space line + bge 100f + mov r4,#0 + strb r4,[r0,r1] @ final zero on line instruction + mov r0,r5 + mov r0,r2 + mov r1,r5 @ begin line address + mov r2,#0 @ mark use key word + bl insertElementParam + +100: + pop {r1-r6,pc} +/*******************************************/ +/* Parser line configuration file */ +/*******************************************/ +/* r0 address line */ +/* r1 line size */ +/* r2 Address buffer */ +lineParser: @ + push {r0-r8,lr} + cmp r1,#0 @ empty line ? + bne 1f + mov r0,r2 + bl writeEndLine + b 100f +1: + mov r6,r0 + mov r7,r1 @ line size + mov r8,r2 @ buffer address + mov r4,#0 + ldrb r5,[r0,r4] @ load first character + cmp r5,#'#' @ comment ? + bne 2f + mov r1,r8 + mov r2,r7 + bl copyLine + mov r0,r8 + bl writeEndLine + b 100f +2: + mov r4,#0 +3: @ supp spaces + ldrb r3,[r6,r4] + cmp r3,#' ' + addeq r4,r4,#1 + beq 3b + cmp r3,#0 @ spaces line + beq 100f + cmp r3,#';' @ unmark + bne 5f + add r4,r4,#1 +4: @ supp space after ; + ldrb r3,[r6,r4] + cmp r3,#' ' + addeq r4,r4,#1 + beq 4b + cmp r3,#0 @ spaces line + beq 100f +5: + add r0,r0,r4 @ word key address + mov r1,r7 @ line size + bl traitwordkey + cmp r0,#0 + bne 6f + mov r0,r6 + mov r1,r8 @ word key not modified + mov r2,r7 @ copy line + bl copyLine + mov r0,r8 + bl writeEndLine + b 100f +6: + mov r0,r1 @ line instruction address + mov r1,r8 @ line conf + bl copyLineInst + mov r0,r8 + bl writeEndLine + b 100f + +100: + pop {r0-r8,pc} +/***************************************************/ +/* word key analyser */ +/***************************************************/ +/* r0 contains address begin word key */ +/* r1 line size */ +/* r0 return list element address */ +/* r1 return new line pointer */ +traitwordkey: @ INFO: traitwordkey + push {r2-r6,lr} @ save registers + mov r5,r0 + mov r4,#0 +1: @ loop size compute + ldrb r3,[r0,r4] + cmp r3,#' ' @ end key + beq 2f + cmp r3,#'=' @ end key + beq 2f + cmp r3,#0x0D @ end key + beq 2f + add r4,r4,#1 @ increment indice and loop + cmp r4,r1 + blt 1b +2: + mov r0,r5 @ addresse begin key + mov r1,r4 @ key size + ldr r2,iAdrllistLineInstr + bl searchKeyWord + cmp r0,#0 + beq 100f + + mov r0,#1 + +100: + pop {r2-r6,pc} +/***************************************************/ +/* search word key in instructions llist */ +/***************************************************/ +/* r0 contains address key word */ +/* r1 key word size */ +/* r2 contains list instrction address */ +/* r0 return 0 if not found 1 is found */ +/* r1 return line instructions address */ +searchKeyWord: @ INFO: searchKeyWord + push {r2-r9,lr} @ save registers + mov r6,r0 + mov r7,r1 + mov r8,r2 +1: + ldr r2,[r8,#llistOpt_next] @ end list ? + cmp r2,#0 + beq 6f @ yes + ldr r1,[r8,#llistOpt_address] @ load line address + mov r4,#0 + mov r0,r1 +2: + ldrb r5,[r1,r4] + cmp r5,#';' + addeq r4,#1 + beq 2b + cmp r5,#' ' + addeq r4,#1 + beq 2b + mov r9,#0 @ ici on est audebut cle instruction + +3: + ldrb r3,[r6,r9] + cmp r3,r5 + bne 4f + add r9,r9,#1 + cmp r9,r7 + bge 5f + add r4,r4,#1 + ldrb r5,[r1,r4] + cmp r5,#' ' + beq 5f + cmp r5,#0 + beq 5f + b 3b +4: + mov r8,r2 + b 1b +5: + mov r0,#1 @ found ! + str r0,[r8,#llistOpt_value] + b 100f +6: + mov r0,#0 @ not found + +100: + pop {r2-r9,pc} +/***************************************************/ +/* write end line */ +/***************************************************/ +/* r0 contains buffer address */ +writeEndLine: @ INFO: writeEndLine + push {r1-r3,lr} @ save registers + ldr r2,iAdriPtrWrite + ldr r3,[r2] + mov r1,#0x0D + strb r1,[r0,r3] + add r3,r3,#1 + mov r1,#0x0A + strb r1,[r0,r3] + add r3,r3,#1 + str r3,[r2] +100: + pop {r1-r3,pc} +/***************************************************/ +/* read file */ +/***************************************************/ +/* r0 contains file name */ +/* r1 contains a file buffer */ +/* r2 contains buffer size */ +/* r0 return buffer size */ +readFile: @ INFO: readFile + push {r1-r9,lr} @ save registers + mov r9,r1 @ file buffer + mov r6,r2 + mov r10,r3 + mov r1,#O_RDWR @ flags + mov r2,#0 @ mode + mov r7,#OPEN @ file open + svc 0 + cmp r0,#0 @ error ? + ble 99f + mov r8,r0 @ FD save + + mov r0,r8 + mov r1,r9 @ read buffer address + mov r2,r6 + mov r7,#READ @ call system read file + svc 0 + cmp r0,#0 @ error read ? + blt 97f + mov r6,r0 @ save file size + mov r0,r8 @ FD + mov r7,#CLOSE @ call system close file + svc 0 + cmp r0,#0 @ error close ? + blt 96f + + mov r0,r6 @ return buffer size + b 100f +96: @ display error messages + ldr r0,iAdrszMessClose + bl affichageMess + mov r0,#-1 @ error + b 100f +97: + ldr r0,iAdrszMessRead + bl affichageMess + mov r0,#-1 @ error + b 100f +99: + ldr r0,iAdrszMessOpen + bl affichageMess + mov r0,#-1 @ error + + 100: + pop {r1-r9,pc} +iAdrszMessOpen: .int szMessOpen +iAdrszMessRead: .int szMessRead +iAdrszMessClose: .int szMessClose +/***************************************************/ +/* write file */ +/***************************************************/ +/* r0 contains file name */ +/* r1 contains a file buffer */ +/* r2 contains buffer size */ +/* r0 return -1 if error */ +writeFile: @ INFO: writeFile + push {r1-r9,lr} @ save registers + mov r4,r1 + mov r5,r2 + ldr r1,iFlag @ flags + mov r2,#0644 @ mode in octal + mov r7,#OPEN @ open file, create if not exist + svc 0 + cmp r0,#0 @ error open + ble 99f + mov r8,r0 + mov r0,r8 @ file FD + mov r1,r4 @ write buffer + mov r2,r5 @ buffer size + mov r7,#WRITE + svc 0 + cmp r0,#0 @ error open + ble 97f + mov r0,r8 @ FD + mov r7,#CLOSE @ call system close file + svc 0 + cmp r0,#0 @ error close ? + blt 96f + + b 100f + +96: @ display error messages + ldr r0,iAdrszMessClose + bl affichageMess + mov r0,#-1 @ error + b 100f + +97: + ldr r0,iAdrszMessWrite + bl affichageMess + mov r0,#-1 @ error + b 100f +99: + ldr r0,iAdrszMessOpen + bl affichageMess + mov r0,#-1 @ error +100: + pop {r1-r9,pc} +iAdrszMessWrite: .int szMessWrite +iAdrszFileNameWrite: .int szFileNameWrite +iFlag: .int O_RDWR|O_CREAT +/***************************************************/ +/* read line */ +/***************************************************/ +/* r0 contains a file buffer */ +/* r1 contains text buffer size */ +/* r2 contains read pointer */ +/* r0 return pointer address line or -1 if end */ +/* r1 return line size */ +readLine: @ INFO: readLine + push {r2-r9,lr} @ save registers + ldr r3,[r2] + cmp r3,r1 + movge r0,#-1 @ end buffer + bge 100f + mov r4,r3 + mov r6,#0 @ line size +1: + ldrb r5,[r0,r4] + cmp r5,#0x0D + beq 3f + add r4,r4,#1 + cmp r4,r1 @ end buffer ? + strge r4,[r2] @ new begin line pointeur + movge r0,r3 @ line begin + movge r1,r6 @ return size + bge 100f @ end + add r6,r6,#1 + b 1b @ and loop +3: + add r4,r4,#2 @ supp 0D0A + str r4,[r2] @ new begin line pointeur + mov r0,r3 @ line begin + mov r1,r6 @ return size + b 100f +100: + pop {r2-r9,pc} +iAdriPtrRead: .int iPtrRead +/******************************************************************/ +/* copy new options line */ +/******************************************************************/ +/* r0 contains line address */ +/* r1 contains address buffer */ +copyLineInst: @ INFO: copyLineInst + push {r1-r5,lr} @ save registers + ldr r2,iAdriPtrWrite + ldr r3,[r2] @ load pointer write buffer + mov r4,#0 +1: + ldrb r5,[r0,r4] @ load byte + cmp r5,#0 @ final zero + beq 2f + strb r5,[r1,r3] @ store byte in buffer + add r3,r3,#1 + add r4,r4,#1 + b 1b +2: + str r3,[r2] @ save pointer write buffer +100: + pop {r1-r5,pc} @ restaur registers +/******************************************************************/ +/* copy file line */ +/******************************************************************/ +/* r0 contains line address */ +/* r1 contains address buffer +/* r2 contains characters number to copy */ +copyLine: @ INFO: copyLine + push {r3-r6,lr} @ save registers + mov r6,r2 + ldr r2,iAdriPtrWrite + ldr r3,[r2] + mov r4,#0 +1: + ldrb r5,[r0,r4] @ load byte + strb r5,[r1,r3] @ store byte in buffer + add r3,r3,#1 + add r4,r4,#1 + cmp r4,r6 + blt 1b +2: + str r3,[r2] +100: + pop {r3-r6,pc} @ restaur registers +/******************************************************************/ +/* insertion nex options in configuration */ +/******************************************************************/ +/* r0 contains the address of the list */ +/* r1 write buffer address */ +insertNewOptions: @ INFO: insertNewOptions + push {r1-r4,lr} @ save registers + mov r4,r0 +1: @ display loop param + ldr r2,[r4,#llistOpt_next] @ end list ? + cmp r2,#0 + beq 100f @ yes + ldr r3,[r4,#llistOpt_value] + cmp r3,#1 + beq 2f + ldr r0,[r4,#llistOpt_address] @ load line address + bl copyLineInst +2: + mov r4,r2 @ and loop new item + b 1b + +100: + pop {r1-r4,pc} @ restaur registers +/******************************************************************/ +/* display list instruction */ +/******************************************************************/ +/* r0 contains the address of the list */ +displayListInst: @ INFO: displayListInst + push {r1-r2,lr} @ save registers + mov r1,r0 +1: @ display loop param + ldr r2,[r1,#llistOpt_next] @ end list ? + cmp r2,#0 + beq 100f @ yes + ldr r0,[r1,#llistOpt_address] @ load line address + bl affichageMess + ldr r0,iAdrszCarriageReturn + bl affichageMess + mov r1,r2 + b 1b + +100: + pop {r1-r2,pc} @ restaur registers + +/******************************************************************/ +/* insert element at end of list */ +/******************************************************************/ +/* r0 contains the address of the list */ +/* r1 contains key string address */ +/* r2 contains option list address +/* r0 returns address of element or - 1 if error */ +insertElementParam: @ INFO: insertElementParam + push {r1-r4,lr} @ save registers + mov r4,#llistOpt_end * NBPARAM + add r4,r4,r0 @ compute address end list +1: @ start loop + ldr r3,[r0,#llistOpt_next] @ load next pointer + cmp r3,#0 @ = zero + movne r0,r3 @ no -> loop with pointer + bne 1b + add r3,r0,#llistOpt_end @ yes -> compute next free address + cmp r3,r4 @ > list end + movge r0,#-1 @ yes -> error + bge 100f + str r3,[r0,#llistOpt_next] @ store next address in current pointer + str r1,[r0,#llistOpt_address] @ store element value + str r2,[r0,#llistOpt_value] + mov r1,#0 + str r1,[r3,#llistOpt_next] @ init next pointer in next address + +100: + pop {r1-r4,lr} @ restaur registers + bx lr @ return + +/***************************************************/ +/* ROUTINES INCLUDE */ +/***************************************************/ +.include "../affichage.inc" diff --git a/Task/Update-a-configuration-file/C++/update-a-configuration-file.cpp b/Task/Update-a-configuration-file/C++/update-a-configuration-file.cpp new file mode 100644 index 0000000000..9b8cf85516 --- /dev/null +++ b/Task/Update-a-configuration-file/C++/update-a-configuration-file.cpp @@ -0,0 +1,121 @@ +#include +#include +#include +#include +#include +#include + +class ConfigData { +public: + std::string favourite_fruit; + bool needs_peeling; + bool seeds_removed; + uint32_t number_bananas; + uint32_t number_strawberries; +}; + +std::string to_upper_case(const std::string& text) { + std::string result = text; + std::transform(result.begin(), result.end(), result.begin(), + [](const char& ch) { return std::toupper(ch); }); + return result; +} + +void read_config_file(const std::string& read_file, const ConfigData& data) { + std::ifstream read_stream; + read_stream.open(read_file); + const std::string write_file = "../temp_config.txt"; + std::ofstream write_stream; + write_stream.open(write_file); + if ( ! read_stream.is_open() || ! write_stream.is_open() ) { + std::cout << "Unable to open files" << std::endl; + } + + bool done_fruit = false; + bool done_peeling = false; + bool done_seeds = false; + bool done_bananas = false; + bool done_strawberries = false; + std::string line; + while ( std::getline(read_stream, line) ) { + if ( line.empty() || line[0] == '#' ) { + write_stream << line << "\n"; + continue; + } + + const std::string words = ( line.substr(0, 2) == "; " ) ? + to_upper_case(line.substr(2)) : to_upper_case(line); + + if ( words.empty() ) { continue; } + if ( words.substr(0, 14) == "FAVOURITEFRUIT" ) { + if ( done_fruit ) { continue; } + done_fruit = true; + write_stream << "FAVOURITEFRUIT " << data.favourite_fruit << "\n"; + } else if ( words.substr(0, 12) == "NEEDSPEELING" ) { + if ( done_peeling ) { continue; } + done_peeling = true; + if ( data.needs_peeling ) { + write_stream << "NEEDSPEELING" << "\n"; + } else { + write_stream << "; NEEDSPEELING" << "\n"; + } + } else if ( words.substr(0, 12) == "SEEDSREMOVED" ) { + if ( done_seeds ) { continue; } + done_seeds = true; + if ( data.seeds_removed ) { + write_stream << "SEEDSREMOVED" << "\n"; + } else { + write_stream << "; SEEDSREMOVED" << "\n"; + } + } else if( words.substr(0, 15) == "NUMBEROFBANANAS" ) { + if ( done_bananas ) { continue; } + done_bananas = true; + write_stream << "NUMBEROFBANANAS " << data.number_bananas << "\n"; + } else if( words.substr(0, 20) == "NUMBEROFSTRAWBERRIES" ) { + if ( done_strawberries ) { continue; } + done_strawberries = true; + write_stream << "NUMBEROFSTRAWBERRIES " << data.number_strawberries << "\n"; + } + } + + // Insert statements if they were absent from the original file "config.txt" + if ( ! done_fruit ) { + write_stream << "FAVOURITEFRUIT " + data.favourite_fruit << "\n"; + } + + if ( ! done_peeling ) { + if ( data.needs_peeling ) { + write_stream << "NEEDSPEELING" << "\n"; + } else { + write_stream << "; NEEDSPEELING" << "\n"; + } + } + + if ( ! done_seeds ) { + if ( data.seeds_removed ) { + write_stream << "SEEDSREMOVED" << "\n"; + } else { + write_stream << "; SEEDSREMOVED" << "\n"; + } + } + + if ( ! done_bananas ) { + write_stream << "NUMBEROFBANANAS "<< data.number_bananas << "\n"; + } + + if ( ! done_strawberries ) { + write_stream << "NUMBEROFSTRAWBERRIES " << data.number_strawberries << "\n"; + } + + read_stream.close(); + write_stream.close(); + + std::filesystem::remove(read_file); + std::filesystem::rename(write_file, read_file); +} + +int main() { + const std::string read_file = "../config.txt"; + ConfigData configData("banana", false, true, 1024, 62000); + read_config_file(read_file, configData); +} diff --git a/Task/Update-a-configuration-file/Delphi/update-a-configuration-file.delphi b/Task/Update-a-configuration-file/Delphi/update-a-configuration-file.pas similarity index 100% rename from Task/Update-a-configuration-file/Delphi/update-a-configuration-file.delphi rename to Task/Update-a-configuration-file/Delphi/update-a-configuration-file.pas diff --git a/Task/Update-a-configuration-file/Julia/update-a-configuration-file.julia b/Task/Update-a-configuration-file/Julia/update-a-configuration-file.jl similarity index 100% rename from Task/Update-a-configuration-file/Julia/update-a-configuration-file.julia rename to Task/Update-a-configuration-file/Julia/update-a-configuration-file.jl diff --git a/Task/Update-a-configuration-file/Kotlin/update-a-configuration-file.kotlin b/Task/Update-a-configuration-file/Kotlin/update-a-configuration-file.kts similarity index 100% rename from Task/Update-a-configuration-file/Kotlin/update-a-configuration-file.kotlin rename to Task/Update-a-configuration-file/Kotlin/update-a-configuration-file.kts diff --git a/Task/Update-a-configuration-file/Lua/update-a-configuration-file.lua b/Task/Update-a-configuration-file/Lua/update-a-configuration-file.lua new file mode 100644 index 0000000000..b00f5fd77e --- /dev/null +++ b/Task/Update-a-configuration-file/Lua/update-a-configuration-file.lua @@ -0,0 +1,71 @@ +local function Read(handler) -- NR, line, comment, option, parameters + local line = handler:read"l" + if line==nil or line=="" or line:sub(1,1)=="#" or line:find"^;?%s*$" + then + return line,nil,nil,true + end + local comment, option, param = line:match"^(;?)%s*(%S*)%s*(.*)$" + comment = comment==";" + if not comment then + param = param=="" and true or tonumber(param) or param + end + return line, option, param, comment +end + +local function LoadConfig(H) + local options = {} + for line, option, param, comment in Read,H do + if not comment and option then + options[option] = param + end + end + H:close() + return options +end + +local function MakeLine(k,v) + return v==false and "; " .. k + or v==true and k + or v and k .. " " .. v +end + +local function Sponge(fileS) + local H, tmp = io.open(fileS), io.tmpfile() + tmp:write(H:read"a") tmp:seek"set" + H:close() + return tmp +end + +local function Update(fileS, options) + local IN = Sponge(fileS) + local nl = string.match(IN:read"L" or "\n", "[\r\n]?\n$") IN:seek"set" + local OUT = io.open(fileS, "w+") + local saved = {} -- for appending after + for line, option, param, comment in Read,IN do + if option then + local val = options[option] + saved[option] = true + if val~=param then + line = MakeLine(option,val) + end + end + OUT:write(line, nl) + end + IN:close() + for k,v in pairs(options) do + if saved[k]==nil then + OUT:write( MakeLine(k,v), nl ) + end + end + OUT:close() +end + +local options = LoadConfig( io.open(arg[1]) ) + +-- nil would remove the option entirely +options.NEEDSPEELING = false -- disable +options.SEEDSREMOVED = true +options.NUMBEROFBANANAS = 1024 +options.NUMBEROFSTRAWBERRIES = 62000 + +Update(arg[1], options) diff --git a/Task/Update-a-configuration-file/PowerShell/update-a-configuration-file-1.psh b/Task/Update-a-configuration-file/PowerShell/update-a-configuration-file-1.ps1 similarity index 100% rename from Task/Update-a-configuration-file/PowerShell/update-a-configuration-file-1.psh rename to Task/Update-a-configuration-file/PowerShell/update-a-configuration-file-1.ps1 diff --git a/Task/Update-a-configuration-file/PowerShell/update-a-configuration-file-2.psh b/Task/Update-a-configuration-file/PowerShell/update-a-configuration-file-2.ps1 similarity index 100% rename from Task/Update-a-configuration-file/PowerShell/update-a-configuration-file-2.psh rename to Task/Update-a-configuration-file/PowerShell/update-a-configuration-file-2.ps1 diff --git a/Task/Update-a-configuration-file/VBScript/update-a-configuration-file.vb b/Task/Update-a-configuration-file/VBScript/update-a-configuration-file.vbs similarity index 100% rename from Task/Update-a-configuration-file/VBScript/update-a-configuration-file.vb rename to Task/Update-a-configuration-file/VBScript/update-a-configuration-file.vbs diff --git a/Task/Use-another-language-to-call-a-function/Ada/use-another-language-to-call-a-function-1.ada b/Task/Use-another-language-to-call-a-function/Ada/use-another-language-to-call-a-function-1.adb similarity index 100% rename from Task/Use-another-language-to-call-a-function/Ada/use-another-language-to-call-a-function-1.ada rename to Task/Use-another-language-to-call-a-function/Ada/use-another-language-to-call-a-function-1.adb diff --git a/Task/Use-another-language-to-call-a-function/Ada/use-another-language-to-call-a-function-2.ada b/Task/Use-another-language-to-call-a-function/Ada/use-another-language-to-call-a-function-2.adb similarity index 100% rename from Task/Use-another-language-to-call-a-function/Ada/use-another-language-to-call-a-function-2.ada rename to Task/Use-another-language-to-call-a-function/Ada/use-another-language-to-call-a-function-2.adb diff --git a/Task/Use-another-language-to-call-a-function/Ada/use-another-language-to-call-a-function-3.ada b/Task/Use-another-language-to-call-a-function/Ada/use-another-language-to-call-a-function-3.adb similarity index 100% rename from Task/Use-another-language-to-call-a-function/Ada/use-another-language-to-call-a-function-3.ada rename to Task/Use-another-language-to-call-a-function/Ada/use-another-language-to-call-a-function-3.adb diff --git a/Task/Use-another-language-to-call-a-function/COBOL/use-another-language-to-call-a-function.cobol b/Task/Use-another-language-to-call-a-function/COBOL/use-another-language-to-call-a-function.cob similarity index 100% rename from Task/Use-another-language-to-call-a-function/COBOL/use-another-language-to-call-a-function.cobol rename to Task/Use-another-language-to-call-a-function/COBOL/use-another-language-to-call-a-function.cob diff --git a/Task/Use-another-language-to-call-a-function/Delphi/use-another-language-to-call-a-function.delphi b/Task/Use-another-language-to-call-a-function/Delphi/use-another-language-to-call-a-function.pas similarity index 100% rename from Task/Use-another-language-to-call-a-function/Delphi/use-another-language-to-call-a-function.delphi rename to Task/Use-another-language-to-call-a-function/Delphi/use-another-language-to-call-a-function.pas diff --git a/Task/Use-another-language-to-call-a-function/FreeBASIC/use-another-language-to-call-a-function-1.basic b/Task/Use-another-language-to-call-a-function/FreeBASIC/use-another-language-to-call-a-function-1.basic new file mode 100644 index 0000000000..dde9ab9095 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/FreeBASIC/use-another-language-to-call-a-function-1.basic @@ -0,0 +1,16 @@ +#include "crt.bi" + +Extern "C" + Function Query (Byval dato As zstring Ptr, Byval longitud As size_t Ptr) As Integer Export + Dim As String message = "Here am I" + Dim As size_t message_length = Len(message) + + If *longitud < message_length Then + Return 0 + Else + memcpy(dato, Strptr(message), message_length) + *longitud = message_length + Return 1 + End If + End Function +End Extern diff --git a/Task/Use-another-language-to-call-a-function/FreeBASIC/use-another-language-to-call-a-function-2.basic b/Task/Use-another-language-to-call-a-function/FreeBASIC/use-another-language-to-call-a-function-2.basic new file mode 100644 index 0000000000..83f9fbffe2 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/FreeBASIC/use-another-language-to-call-a-function-2.basic @@ -0,0 +1,53 @@ +#include +#include + +#ifdef _WIN32 +#include +#else +#include +#endif + +typedef int (*QueryFunc)(char *, size_t *); + +int main(int argc, char *argv[]) +{ + char Buffer[1024]; + size_t Size = sizeof(Buffer); + +#ifdef _WIN32 + HMODULE hLib = LoadLibrary("libquery.dll"); + if (!hLib) { + printf("failed to load library\n"); + return 1; + } + QueryFunc Query = (QueryFunc)GetProcAddress(hLib, "Query"); +#else + void *hLib = dlopen("./libquery.so", RTLD_LAZY); + if (!hLib) { + printf("failed to load library\n"); + return 1; + } + QueryFunc Query = (QueryFunc)dlsym(hLib, "Query"); +#endif + + if (!Query) { + printf("failed to find Query function\n"); + return 1; + } + + if (0 == Query(Buffer, &Size)) { + printf("failed to call Query\n"); + } else { + char *Ptr = Buffer; + while (Size-- > 0) putchar(*Ptr++); + putchar('\n'); + } + +#ifdef _WIN32 + FreeLibrary(hLib); +#else + dlclose(hLib); +#endif + + return 0; +} diff --git a/Task/Use-another-language-to-call-a-function/FutureBasic/use-another-language-to-call-a-function.basic b/Task/Use-another-language-to-call-a-function/FutureBasic/use-another-language-to-call-a-function.basic new file mode 100644 index 0000000000..c11f2aa16a --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/FutureBasic/use-another-language-to-call-a-function.basic @@ -0,0 +1,23 @@ +include "NSLog.incl" + +// FutureBasic function +local fn Query( buffer as ptr, size as ^unsigned long ) as long + CFStringRef string = @"Here am I" + ptr p = fn StringCStringUsingEncoding( string, NSASCIIStringEncoding ) + *size = len(string) + BlockMoveData( p, buffer, *size ) +end fn = 1 + + +// C code +BeginCCode + char buffer[1024]; + size_t Size = sizeof(buffer); + if ( Query( buffer, &Size ) == 0 ) { // call FutureBasic function + NSLog(@"failed to call Query\n"); + } else { + NSLog(@"%s",buffer); + } +EndC + +HandleEvents diff --git a/Task/Use-another-language-to-call-a-function/Haxe/use-another-language-to-call-a-function.haxe b/Task/Use-another-language-to-call-a-function/Haxe/use-another-language-to-call-a-function.hx similarity index 100% rename from Task/Use-another-language-to-call-a-function/Haxe/use-another-language-to-call-a-function.haxe rename to Task/Use-another-language-to-call-a-function/Haxe/use-another-language-to-call-a-function.hx diff --git a/Task/Use-another-language-to-call-a-function/Julia/use-another-language-to-call-a-function-1.jl b/Task/Use-another-language-to-call-a-function/Julia/use-another-language-to-call-a-function-1.jl new file mode 100644 index 0000000000..e21eeb4c16 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Julia/use-another-language-to-call-a-function-1.jl @@ -0,0 +1,21 @@ +// Save this section as main.c +#include + +extern int Query (char * Data, size_t * Length); + +int main (int argc, char * argv []) +{ + char Buffer [1024]; + size_t Size = sizeof (Buffer); + + if (0 == Query (Buffer, &Size)) + { + printf ("failed to call Query\n"); + } + else + { + char * Ptr = Buffer; + while (Size-- > 0) putchar (*Ptr++); + putchar ('\n'); + } +} diff --git a/Task/Use-another-language-to-call-a-function/Julia/use-another-language-to-call-a-function-2.jl b/Task/Use-another-language-to-call-a-function/Julia/use-another-language-to-call-a-function-2.jl new file mode 100644 index 0000000000..9a7b4a3d08 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Julia/use-another-language-to-call-a-function-2.jl @@ -0,0 +1,17 @@ +# Save this section as a file called query.jl + +function Query(buffer::Ptr{UInt8}, length::Ptr{Csize_t})::Cint + """ Define the Query function to be called from C """ + + max_size = unsafe_load(length) + data = "Hello from Julia!" + bytes = codeunits(data) + max_size < length(bytes) && return 0 # Failure: buffer too small + for i in 1:length(bytes) + unsafe_store!(buffer, bytes[i], i) + end + unsafe_store!(length, length(bytes)) + return 1 +end + +Base.@export Query diff --git a/Task/Use-another-language-to-call-a-function/Julia/use-another-language-to-call-a-function-3.jl b/Task/Use-another-language-to-call-a-function/Julia/use-another-language-to-call-a-function-3.jl new file mode 100644 index 0000000000..210c4ec0c2 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Julia/use-another-language-to-call-a-function-3.jl @@ -0,0 +1,33 @@ +// save this section as query_wrapper.c + +#include + +JULIA_DEFINE_FAST_TLS() + +int Query(char *Data, size_t *Length) { + jl_init(); + + jl_eval_string("include(\"query.jl\")"); // Include the Julia file containing Query function + + jl_function_t *func = jl_get_function(jl_main_module, "Query"); + if (!func) { + jl_atexit_hook(0); + return 0; + } + + jl_value_t *buffer = jl_ptr_to_array_1d(jl_uint8_type, Data, *Length, 0); + jl_value_t *length = jl_box_uint64((uint64_t)Length); + + // Call the query function within Julia + jl_value_t *result = jl_call2(func, buffer, length); + if (jl_exception_occurred()) { + jl_atexit_hook(0); + return 0; + } + + // Get return value + int ret = jl_unbox_int32(result); + + jl_atexit_hook(0); + return ret; // Return the result of the Query function from the C shared library +} diff --git a/Task/Use-another-language-to-call-a-function/Julia/use-another-language-to-call-a-function-4.jl b/Task/Use-another-language-to-call-a-function/Julia/use-another-language-to-call-a-function-4.jl new file mode 100644 index 0000000000..42ffe58ace --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Julia/use-another-language-to-call-a-function-4.jl @@ -0,0 +1,19 @@ +# Save this section as compile.sh and run it in a terminal with all files in same directory +gcc -shared -fPIC -o libquery.so query_wrapper.c -I$JULIA_DIR/include/julia -L$JULIA_DIR/lib -ljulia -Wl,-rpath,$JULIA_DIR/lib +if [ $? -ne 0 ]; then + echo "Error: Compilation of libquery.so failed." + exit 1 +fi +echo "libquery.so compiled successfully." + +gcc -o main main.c -L. -lquery +if [ $? -ne 0 ]; then + echo "Error: Compilation of main failed." + exit 1 +fi +echo "main compiled successfully." + +export LD_LIBRARY_PATH=.:$JULIA_DIR/lib:$LD_LIBRARY_PATH +./main + +echo "Script finished." diff --git a/Task/Use-another-language-to-call-a-function/Kotlin/use-another-language-to-call-a-function-1.kotlin b/Task/Use-another-language-to-call-a-function/Kotlin/use-another-language-to-call-a-function-1.kts similarity index 100% rename from Task/Use-another-language-to-call-a-function/Kotlin/use-another-language-to-call-a-function-1.kotlin rename to Task/Use-another-language-to-call-a-function/Kotlin/use-another-language-to-call-a-function-1.kts diff --git a/Task/Use-another-language-to-call-a-function/Kotlin/use-another-language-to-call-a-function-2.kotlin b/Task/Use-another-language-to-call-a-function/Kotlin/use-another-language-to-call-a-function-2.kts similarity index 100% rename from Task/Use-another-language-to-call-a-function/Kotlin/use-another-language-to-call-a-function-2.kotlin rename to Task/Use-another-language-to-call-a-function/Kotlin/use-another-language-to-call-a-function-2.kts diff --git a/Task/Use-another-language-to-call-a-function/Kotlin/use-another-language-to-call-a-function-3.kotlin b/Task/Use-another-language-to-call-a-function/Kotlin/use-another-language-to-call-a-function-3.kts similarity index 100% rename from Task/Use-another-language-to-call-a-function/Kotlin/use-another-language-to-call-a-function-3.kotlin rename to Task/Use-another-language-to-call-a-function/Kotlin/use-another-language-to-call-a-function-3.kts diff --git a/Task/Use-another-language-to-call-a-function/Lua/use-another-language-to-call-a-function-1.lua b/Task/Use-another-language-to-call-a-function/Lua/use-another-language-to-call-a-function-1.lua new file mode 100644 index 0000000000..474a9c5d9e --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Lua/use-another-language-to-call-a-function-1.lua @@ -0,0 +1,24 @@ +-- Query.lua + +-- basic kv dbase +function qdb_init () + qdb = {} -- global in lua + qdb["who are you?"] = "I am Lua" + qdb["what are you?"] = "I am a Lua virtual machine" + qdb["when are you?"] = "I am live" + qdb["where are you?"] = "Here I am" + qdb["how are you?"] = "I am a fine" + qdb["default"] = "unknown query" + +end + +-- call from C with key => Data +function Query(k) + + local key = string.lower(k) + + if (qdb[key] == nil) then key = "default" end + + lua_response = qdb[key] + +end diff --git a/Task/Use-another-language-to-call-a-function/Lua/use-another-language-to-call-a-function-2.lua b/Task/Use-another-language-to-call-a-function/Lua/use-another-language-to-call-a-function-2.lua new file mode 100644 index 0000000000..ea13576fb6 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Lua/use-another-language-to-call-a-function-2.lua @@ -0,0 +1,205 @@ +/* Query_lua.c */ +#include +#include +#include +#include + +#include +#include +#include + +// tell lua how many args for a function +typedef enum { NOARG, ONEARG, TWOARGS, THREEARGS } argcount; +// 0 1 2 3 + +// diagnostics when things go wrong +typedef enum { C_OK, C_FAILURE, LUA_FAILURE} exitcode; +// 0 1 2 + +/* lua vars we will create or use */ +const char* lua_Query = "Query"; +const char* lua_Data = "Data"; +const char* lua_qdb_init = "qdb_init"; +const char* lua_qdb = "qdb"; +const char* lua_response = "lua_response"; + + +int LTop; // global C index to top of lua stack + +/* function prototypes */ + +int Query(char* Data, size_t * Length); + +void fail(const char* fmsg, const char* errstr, exitcode ret); + +lua_State* C_lua_init(const char* luafile); + +bool C_push_string(lua_State* L, const char* name, + const char* str, const size_t n); + +bool C_get_string( lua_State * L, const char* src, + char* dest, size_t max); + + +// exit program with diagnostice and exitcode +void fail(const char* fmsg, const char* errstr, exitcode ret) { + + fprintf(stderr, "%s ", fmsg); + + if (errstr != NULL){ fprintf(stderr, "%s ", errstr); } + + fprintf(stderr, "\n"); + + exit(ret); +} + + +// push C string to lua +bool C_push_string(lua_State* L, const char* name, + const char* str, const size_t n){ + (void) n; + lua_pushstring(L, str); + lua_setglobal(L, name); + return true; +} + +// get C string from lua string by variable var +bool C_get_string( lua_State * L, const char* luavar, + char* dest, size_t max){ + + const char* lstring = NULL; + size_t len = 0; + + lua_getglobal(L, luavar); + + if(!lua_isstring(L, -1)) { + fail("expected a string", lua_tostring(L, -1), LUA_FAILURE); + } + + LTop = lua_gettop(L); + + lstring = lua_tolstring(L, LTop, &max ); + len = strlen(lstring); + + if (len > 0) { + strncpy(dest, lstring, len); + dest[len+1] = '\0'; + return true; + } + + return false; +} + + +/* + initialize the lua vm + load up the lua file + any commands in the global area will run +*/ + +lua_State* C_lua_init(const char* luafile) { + + exitcode status = C_OK; + + /// creates Lua machine & env + lua_State* L = luaL_newstate(); + if (L == NULL) { + fail("could not create lua state", "lua internal failure", LUA_FAILURE); + } + + // imports basic libs like string, io, os, table, utf-8, math + luaL_openlibs(L); + + // lua file to load + status = luaL_loadfile(L, luafile); + + if (status != LUA_OK){ + fail("loadfile failed", lua_tostring(L, -1), LUA_FAILURE); + } + + /* "priming run" + SEE http://www.troubleshooters.com/codecorn/lua/lua_c_calls_lua.htm + */ + if (lua_pcall(L, 0, 0, 0) != LUA_OK) { + fail("priming run failed",lua_tostring(L, -1), LUA_FAILURE); + } + + return L; +} + +/* -------------------------------------------------- + function called by main in Query.c +*/ + +int Query(char* Data, size_t * Length) { + + /* ======= SETUP LUA ====== */ + // create Lua vm with file + lua_State* L = C_lua_init("Query.lua"); + + // call db init + lua_getglobal(L, lua_qdb_init); + luaL_checktype(L, -1, LUA_TFUNCTION); // optionally check lua type + + int result = lua_pcall(L, NOARG, 0, 0); // execute lua func + if (result != LUA_OK) { + fail("failed to run qdb_init function", lua_tostring(L, -1), LUA_FAILURE); + } + + /* ======= RUN LUA CODE ========= */ + + // put Data into Lua env as a string + C_push_string(L, lua_Data, Data, *Length-1); + + /* set function to call and 1 arg(s) */ + lua_getglobal(L, lua_Query); // function + luaL_checktype(L, -1, LUA_TFUNCTION); + + lua_getglobal(L, lua_Data); // arg + luaL_checktype(L, -1, LUA_TSTRING); + + // call lua function with 1 arg* + result = lua_pcall(L, ONEARG, LUA_MULTRET, 0); + if (result != LUA_OK) { + fail("failed to run Query function", lua_tostring(L, -1), LUA_FAILURE); + } + + // lua_response should have our answer + char* response = calloc(*Length, sizeof(char)); + if (response == NULL) { + fail("calloc failed allocation", NULL, C_FAILURE); + } + + // created within lua + C_get_string(L, lua_response, response, *Length); + + + /* ======== CLEANUP LUA ====== */ + + // clean up lua vars and close vm + // (assign var = nil) + lua_pushnil(L); lua_setglobal(L, lua_response); + lua_pushnil(L); lua_setglobal(L, lua_Data); + lua_pushnil(L); lua_setglobal(L, lua_Query); + lua_pushnil(L); lua_setglobal(L, lua_qdb); + lua_close(L); // lua is done + + + /* ======= REPORT ====== */ + + size_t rlen = strlen(response); + + if (rlen > 0) { + strncpy(Data, response, *Length-1); + Data[rlen] = '\0'; + free(response); // because dynamically allocated + } else { + fail("lua", "no response", LUA_FAILURE); + } + + + return 1; +} + + +// end diff --git a/Task/Use-another-language-to-call-a-function/Lua/use-another-language-to-call-a-function-3.lua b/Task/Use-another-language-to-call-a-function/Lua/use-another-language-to-call-a-function-3.lua new file mode 100644 index 0000000000..850ea4a502 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Lua/use-another-language-to-call-a-function-3.lua @@ -0,0 +1,4 @@ +gcc -std=c2x -Wall -Wextra \ + -I/usr/include/lua5.3 -o query \ + Query.c Query_lua.c \ + -L/usr/lib/x84_64-linux-gnu/ -l lua5.3 diff --git a/Task/Use-another-language-to-call-a-function/OCaml/use-another-language-to-call-a-function-1.ocaml b/Task/Use-another-language-to-call-a-function/OCaml/use-another-language-to-call-a-function-1.ml similarity index 100% rename from Task/Use-another-language-to-call-a-function/OCaml/use-another-language-to-call-a-function-1.ocaml rename to Task/Use-another-language-to-call-a-function/OCaml/use-another-language-to-call-a-function-1.ml diff --git a/Task/Use-another-language-to-call-a-function/OCaml/use-another-language-to-call-a-function-2.ocaml b/Task/Use-another-language-to-call-a-function/OCaml/use-another-language-to-call-a-function-2.ml similarity index 100% rename from Task/Use-another-language-to-call-a-function/OCaml/use-another-language-to-call-a-function-2.ocaml rename to Task/Use-another-language-to-call-a-function/OCaml/use-another-language-to-call-a-function-2.ml diff --git a/Task/Use-another-language-to-call-a-function/Phix/use-another-language-to-call-a-function.phix b/Task/Use-another-language-to-call-a-function/Phix/use-another-language-to-call-a-function.phix index ba8ff27260..be8e50f827 100644 --- a/Task/Use-another-language-to-call-a-function/Phix/use-another-language-to-call-a-function.phix +++ b/Task/Use-another-language-to-call-a-function/Phix/use-another-language-to-call-a-function.phix @@ -1,13 +1,11 @@ -(notonline)--> - without js -- (peek/poke, call_back) - constant Here_am_I = "Here am I" - function Query(atom pData, pLength) - integer len = peekNS(pLength,machine_word(),0) - if poke_string(pData,len,Here_am_I) then - return 0 - end if - pokeN(pLength,length(Here_am_I)+1,machine_word()) - return 1 - end function - constant Query_cb = call_back(Query) -9 A-->Z */ +Do n=1 To words(z) /* [?] process all specified ISINs.*/ + x=word(z,n) /*obtain an ISIN from the Z list. */ + p=verify(x,valid,'N') + If p>0 Then msg='invalid character in position' p':' substr(x,p,1) + Else Do + dd='' /* [?] construct list of ISIN digits. */ + Do k=1 To length(x) + _=substr(x,k,1) /*the ISIN may contain alphabetic chars*/ + p=pos(_,valid) /*X contains 0-->9 A-->Z */ + dd=dd||p-1 /*convert X string (base 36 --? dec).*/ + End + msg='' + Select + When length(x)\==12 Then msg='not exactly 12 chars' + When \datatype( left(x,2),'U') Then msg='not starting with 2 capital chars' + When \datatype(right(x,1),'W') Then msg='last character is not a digit' + Otherwise + If \luhn(dd) Then msg='does not pass the Luhn test' + End + End + If msg='' Then + Say right(x,15) ' valid' /* display the positive message. */ + Else + Say right(x,15) 'not valid:' msg /* display the problem */ + End /*n*/ +Exit /*stick a fork in it, we're all done */ +/*-----------------------------------------------------------------------------------*/ +luhn: Procedure + Parse Arg x /* get credit card number; */ + dsum=0 /* zero digit sum. */ + y=reverse(left(0,length(x)//2)x) /* add leading zero If needed & reverse */ + Do j=1 To length(y)-1 By 2 + _=2*substr(y,j+1,1) + dsum=dsum+substr(y,j,1)+left(_,1)+substr(_,2,1,0) + End + Return right(dsum,1)==0 /* Return 1 if number passed Luhn test */ diff --git a/Task/Validate-International-Securities-Identification-Number/Rebol/validate-international-securities-identification-number.rebol b/Task/Validate-International-Securities-Identification-Number/Rebol/validate-international-securities-identification-number.rebol new file mode 100644 index 0000000000..c0b4bc24d2 --- /dev/null +++ b/Task/Validate-International-Securities-Identification-Number/Rebol/validate-international-securities-identification-number.rebol @@ -0,0 +1,49 @@ +Rebol [ + title: "Rosetta code: Validate International Securities Identification Number" + file: %Validate_International_Securities_Identification_Number.r3 + url: https://rosettacode.org/wiki/Validate_International_Securities_Identification_Number +] + +valid-isin?: function/with [ + "International Securities Identification Number (ISIN) validator." + code [string!] +][ + ;; Format validation: + unless parse code [2 alpha 9 alpha-numeric 1 numeric][ return false ] + ;; Convert to number: + str: clear "" + foreach c code [ + append str case [ + c >= #"a" [-87 + c] + c >= #"A" [-55 + c] + 'else [c] + ] + ] + ;; Luhn validation: + sum: 0 + parse reverse str [ + some [ + set num: numeric ( + sum: sum + num - #"0" + ) + opt [set num: numeric ( + num: 2 * (num - #"0") + if num > 9 [num: num - 9] + sum: sum + num + )] + ] + ] + zero? sum % 10 +] :system/catalog/bitsets + +foreach [code expected] [ + "US0378331005" #(true) + "US0373831005" #(false) ; The transposition typo is caught by the checksum constraint. + "U50378331005" #(false) ; The substitution typo is caught by the format constraint. + "US03378331005" #(false) ; The duplication typo is caught by the format constraint. + "AU0000XVGZA3" #(true) + "AU0000VXGZA3" #(true) ; Unfortunately, not all transposition typos are caught by the checksum constraint. + "FR0000988040" #(true) +][ + print [code valid-isin? code] +] diff --git a/Task/Validate-International-Securities-Identification-Number/Ruby/validate-international-securities-identification-number.rb b/Task/Validate-International-Securities-Identification-Number/Ruby/validate-international-securities-identification-number.rb index 2ed11d3cbd..d6cab7b1da 100644 --- a/Task/Validate-International-Securities-Identification-Number/Ruby/validate-international-securities-identification-number.rb +++ b/Task/Validate-International-Securities-Identification-Number/Ruby/validate-international-securities-identification-number.rb @@ -11,6 +11,6 @@ U50378331005 US03378331005 AU0000XVGZA3 AU0000VXGZA3 -FR0000988040).map{|tc| valid_isin?(tc) } +FR0000988040).map{|tc| valid_isin?(tc) } # => [true, false, false, false, true, true, true] diff --git a/Task/Validate-International-Securities-Identification-Number/Rust/validate-international-securities-identification-number.rust b/Task/Validate-International-Securities-Identification-Number/Rust/validate-international-securities-identification-number.rs similarity index 100% rename from Task/Validate-International-Securities-Identification-Number/Rust/validate-international-securities-identification-number.rust rename to Task/Validate-International-Securities-Identification-Number/Rust/validate-international-securities-identification-number.rs diff --git a/Task/Validate-International-Securities-Identification-Number/Transact-SQL/validate-international-securities-identification-number-1.sql b/Task/Validate-International-Securities-Identification-Number/Transact-SQL/validate-international-securities-identification-number-1.sql index 72e6909706..9873bce73a 100644 --- a/Task/Validate-International-Securities-Identification-Number/Transact-SQL/validate-international-securities-identification-number-1.sql +++ b/Task/Validate-International-Securities-Identification-Number/Transact-SQL/validate-international-securities-identification-number-1.sql @@ -3,39 +3,39 @@ RETURNS bit AS BEGIN --*** Test an ISIN code and return 1 if it is valid, 0 if invalid. -DECLARE @bValid bit; +DECLARE @bValid bit; SET @bValid = CASE WHEN @strISIN LIKE '[A-Z][A-Z][A-Z,0-9][A-Z,0-9][A-Z,0-9][A-Z,0-9][A-Z,0-9][A-Z,0-9][A-Z,0-9][A-Z,0-9][A-Z,0-9][0-9]' THEN 1 ELSE 0 END IF @bValid = 1 - BEGIN - DECLARE @strTest VarChar(40) = ''; - DECLARE @strAdd VarChar(2); - DECLARE @p INT = 0; - WHILE @p < LEN(@strISIN) - BEGIN - SET @p = @p+1; - SET @strAdd = SUBSTRING(@strISIN,@p,1); - IF @strAdd LIKE '[A-Z]' SET @strAdd = CONVERT(VarChar(2),ASCII(UPPER(@strAdd))-55); - SET @strTest = @strTest + @strAdd; - END; + BEGIN + DECLARE @strTest VarChar(40) = ''; + DECLARE @strAdd VarChar(2); + DECLARE @p INT = 0; + WHILE @p < LEN(@strISIN) + BEGIN + SET @p = @p+1; + SET @strAdd = SUBSTRING(@strISIN,@p,1); + IF @strAdd LIKE '[A-Z]' SET @strAdd = CONVERT(VarChar(2),ASCII(UPPER(@strAdd))-55); + SET @strTest = @strTest + @strAdd; + END; - -- Proceed with Luhn test - DECLARE @strLuhn VarChar(40) = REVERSE(@strTest); -- usage: set once, never changed - DECLARE @strS2Values VarChar(10) = '0246813579'; -- constant: maps digits to their S2 summed values - SET @p = 0; -- reset loop counter - DECLARE @intValue INT; - DECLARE @intSum INT = 0; - -- loop through the reversed string, get the value (even-positioned digits are mapped) and add it to @intSum - WHILE @p < LEN(@strLuhn) - BEGIN - SET @p = @p+1; - SET @intValue = CONVERT(INT, SUBSTRING(@strLuhn,@p,1) ) -- value of the digit at position @p in the string - IF @p % 2 = 0 SET @intValue = CONVERT(INT,SUBSTRING(@strS2Values,@intValue+1,1)) - SET @intSum = @intSum + @intValue - END - -- If the of the digits' mapped values ends in 0 (modulo 10 = 0) then the Luhn test succeeds - SET @bValid = CASE WHEN @intSum % 10 = 0 THEN 1 ELSE 0 END - END; + -- Proceed with Luhn test + DECLARE @strLuhn VarChar(40) = REVERSE(@strTest); -- usage: set once, never changed + DECLARE @strS2Values VarChar(10) = '0246813579'; -- constant: maps digits to their S2 summed values + SET @p = 0; -- reset loop counter + DECLARE @intValue INT; + DECLARE @intSum INT = 0; + -- loop through the reversed string, get the value (even-positioned digits are mapped) and add it to @intSum + WHILE @p < LEN(@strLuhn) + BEGIN + SET @p = @p+1; + SET @intValue = CONVERT(INT, SUBSTRING(@strLuhn,@p,1) ) -- value of the digit at position @p in the string + IF @p % 2 = 0 SET @intValue = CONVERT(INT,SUBSTRING(@strS2Values,@intValue+1,1)) + SET @intSum = @intSum + @intValue + END + -- If the of the digits' mapped values ends in 0 (modulo 10 = 0) then the Luhn test succeeds + SET @bValid = CASE WHEN @intSum % 10 = 0 THEN 1 ELSE 0 END + END; RETURN @bValid END diff --git a/Task/Validate-International-Securities-Identification-Number/Uiua/validate-international-securities-identification-number.uiua b/Task/Validate-International-Securities-Identification-Number/Uiua/validate-international-securities-identification-number.uiua new file mode 100644 index 0000000000..84bb8f5892 --- /dev/null +++ b/Task/Validate-International-Securities-Identification-Number/Uiua/validate-international-securities-identification-number.uiua @@ -0,0 +1,19 @@ +Base ← "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" +Luhn ← =0◿10+⊃(/+⊢|/+≡₀(⍥(-9)>9.×2)⊡1)⍉⬚0↯∞_2⇌ +Checksum ← Luhn≡⋕/◇⊂≡(□°⋕˜⨂)⊙(¤Base) +Format ← ××⊃(/×≡(≥@A)↙2|=12⧻|/↧˜∊:Base) +Valid ← ×⊃(Format|Checksum) + +Tests ← { + "AU0000XVGZA3" + "US0378331005" + "US0373831005" # twiddled + "U50378331005" # 5 rather than S + "US03378331005" # Extra char + "AU0000XVGZA3" + "AU0000VXGZA3" + "FR0000988040" + "F00Ö00988040" # Illegal char +} + +≡◇Valid Tests diff --git a/Task/Validate-International-Securities-Identification-Number/V-(Vlang)/validate-international-securities-identification-number.v b/Task/Validate-International-Securities-Identification-Number/V-(Vlang)/validate-international-securities-identification-number.v index 097f268234..650b054e60 100644 --- a/Task/Validate-International-Securities-Identification-Number/V-(Vlang)/validate-international-securities-identification-number.v +++ b/Task/Validate-International-Securities-Identification-Number/V-(Vlang)/validate-international-securities-identification-number.v @@ -1,55 +1,53 @@ import regex -const ( - inc = [ - [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], - [0, 2, 4, 6, 8, 1, 3, 5, 7, 9], - ] -) +const inc = [ + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], + [0, 2, 4, 6, 8, 1, 3, 5, 7, 9], +] fn valid_isin(n string) bool { - mut r,_,_ := regex.regex_base('^[A-Z]{2}[A-Z0-9]{9}\d$') - if !r.matches_string(n) { - return false - } - mut sum := 0 - mut p := 0 - for i := 10; i >= 0; i-- { - p = 1 - p - mut d := n[i..i+1].int() - if d < 'A'.int() { - sum += inc[p][d-'0'.int()] - } else { - d -= 'A'.int() - sum += inc[p][d%10] - p = 1 - p - sum += inc[p][d/10+1] - } - } - sum += n[11..12].int() - '0'.int() - return sum%10 == 0 + mut r, _, _ := regex.regex_base('^[A-Z]{2}[A-Z0-9]{9}\\d$') + if !r.matches_string(n) { + return false + } + mut sum := 0 + mut p := 0 + for i := 10; i >= 0; i-- { + p = 1 - p + mut d := n[i..i + 1].int() + if d < 'A'.int() { + sum += inc[p][d - '0'.int()] + } else { + d -= 'A'.int() + sum += inc[p][d % 10] + p = 1 - p + sum += inc[p][d / 10 + 1] + } + } + sum += n[11..12].int() - '0'.int() + return sum % 10 == 0 } struct Testcases { - isin string - valid bool + isin string + valid bool } -fn main(){ - testcases := [ - Testcases{"US0378331005", true}, - Testcases{"US0373831005", false}, - Testcases{"U50378331005", false}, - Testcases{"US03378331005", false}, - Testcases{"AU0000XVGZA3", true}, - Testcases{"AU0000VXGZA3", true}, - Testcases{"FR0000988040", true}, - ] +fn main() { + testcases := [ + Testcases{'US0378331005', true}, + Testcases{'US0373831005', false}, + Testcases{'U50378331005', false}, + Testcases{'US03378331005', false}, + Testcases{'AU0000XVGZA3', true}, + Testcases{'AU0000VXGZA3', true}, + Testcases{'FR0000988040', true}, + ] - for testcase in testcases { - actual := valid_isin(testcase.isin) - if actual != testcase.valid { - println("expected ${testcase.valid} for ${testcase.isin}, got $actual") - } - } + for testcase in testcases { + actual := valid_isin(testcase.isin) + if actual != testcase.valid { + println('expected ${testcase.valid} for ${testcase.isin}, got ${actual}') + } + } } diff --git a/Task/Validate-International-Securities-Identification-Number/VBScript/validate-international-securities-identification-number.vb b/Task/Validate-International-Securities-Identification-Number/VBScript/validate-international-securities-identification-number.vb deleted file mode 100644 index c9e2c975b8..0000000000 --- a/Task/Validate-International-Securities-Identification-Number/VBScript/validate-international-securities-identification-number.vb +++ /dev/null @@ -1,47 +0,0 @@ -' Validate International Securities Identification Number - 03/03/2019 - -buf=buf&test("US0378331005")&vbCrLf -buf=buf&test("US0373831005")&vbCrLf -buf=buf&test("U50378331005")&vbCrLf -buf=buf&test("US03378331005")&vbCrLf -buf=buf&test("AU0000XVGZA3")&vbCrLf -buf=buf&test("AU0000VXGZA3")&vbCrLf -buf=buf&test("FR0000988040")&vbCrLf -msgbox buf,,"Validate International Securities Identification Number" - -function test(cc) - dim err,c,r,s,i1,i2 - if len(cc)=12 then - for i=1 to len(cc) - p=instr("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",mid(cc,i,1)) - if p<>0 then c=c&(p-1) else err=1 - next 'i - for i=1 to 2 - if instr("ABCDEFGHIJKLMNOPQRSTUVWXYZ",mid(cc,i,1))=0 then err=1 - next 'i - if err=0 then - for i=len(c) to 1 step -1 - r=r&mid(c,i,1) - next 'i - for i=1 to len(r) step 2 - i1=i1+cint(mid(r,i,1)) - next 'i - for i=2 to len(r) step 2 - ii=cint(mid(r,i,1))*2 - if ii>=10 then ii=ii-9 - i2=i2+ii - next 'i - s=cstr(i1+i2) - if mid(s,len(s),1)="0" then - msg="valid" - else - msg="invalid ??1" - end if - else - msg="invalid ??2" - end if - else - msg="invalid ??3" - end if - test=cc&" "&msg -end function 'test diff --git a/Task/Validate-International-Securities-Identification-Number/VBScript/validate-international-securities-identification-number.vbs b/Task/Validate-International-Securities-Identification-Number/VBScript/validate-international-securities-identification-number.vbs new file mode 100644 index 0000000000..9730c62cc8 --- /dev/null +++ b/Task/Validate-International-Securities-Identification-Number/VBScript/validate-international-securities-identification-number.vbs @@ -0,0 +1,47 @@ +' Validate International Securities Identification Number - 03/03/2019 + +buf=buf&test("US0378331005")&vbCrLf +buf=buf&test("US0373831005")&vbCrLf +buf=buf&test("U50378331005")&vbCrLf +buf=buf&test("US03378331005")&vbCrLf +buf=buf&test("AU0000XVGZA3")&vbCrLf +buf=buf&test("AU0000VXGZA3")&vbCrLf +buf=buf&test("FR0000988040")&vbCrLf +msgbox buf,,"Validate International Securities Identification Number" + +function test(cc) + dim err,c,r,s,i1,i2 + if len(cc)=12 then + for i=1 to len(cc) + p=instr("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",mid(cc,i,1)) + if p<>0 then c=c&(p-1) else err=1 + next 'i + for i=1 to 2 + if instr("ABCDEFGHIJKLMNOPQRSTUVWXYZ",mid(cc,i,1))=0 then err=1 + next 'i + if err=0 then + for i=len(c) to 1 step -1 + r=r&mid(c,i,1) + next 'i + for i=1 to len(r) step 2 + i1=i1+cint(mid(r,i,1)) + next 'i + for i=2 to len(r) step 2 + ii=cint(mid(r,i,1))*2 + if ii>=10 then ii=ii-9 + i2=i2+ii + next 'i + s=cstr(i1+i2) + if mid(s,len(s),1)="0" then + msg="valid" + else + msg="invalid ??1" + end if + else + msg="invalid ??2" + end if + else + msg="invalid ??3" + end if + test=cc&" "&msg +end function 'test diff --git a/Task/Validate-International-Securities-Identification-Number/YAMLScript/validate-international-securities-identification-number.ys b/Task/Validate-International-Securities-Identification-Number/YAMLScript/validate-international-securities-identification-number.ys new file mode 100644 index 0000000000..3633f68190 --- /dev/null +++ b/Task/Validate-International-Securities-Identification-Number/YAMLScript/validate-international-securities-identification-number.ys @@ -0,0 +1,18 @@ +!YS-v0 + +defn main(*nums): + each isin nums: + say: "$isin - $if(isin:isin? 'valid' 'invalid')" + +defn isin?(isin): + isin.re-matches(/[A-Z]{2}[A-Z0-9]{9}[0-9]/) && + isin.map(b36-10).apply(str):luhn? + +defn b36-10(c): + c =: c:I - 48 + if c > 9: (c - 7) c + +defn luhn?(cc): + map(mul cc:digits:reverse [1 2]:cycle) + .map(\(I(_ / 10) + (_ % 10))):sum + .mod(10):zero? diff --git a/Task/Validate-International-Securities-Identification-Number/Zkl/validate-international-securities-identification-number-2.zkl b/Task/Validate-International-Securities-Identification-Number/Zkl/validate-international-securities-identification-number-2.zkl index e055e43291..70a0c93e10 100644 --- a/Task/Validate-International-Securities-Identification-Number/Zkl/validate-international-securities-identification-number-2.zkl +++ b/Task/Validate-International-Securities-Identification-Number/Zkl/validate-international-securities-identification-number-2.zkl @@ -1,5 +1,5 @@ println(" ISIN Valid?"); foreach isin in (T("US0378331005","US0373831005","U50378331005", - "US03378331005","AU0000XVGZA3","AU0000VXGZA3","FR0000988040")){ + "US03378331005","AU0000XVGZA3","AU0000VXGZA3","FR0000988040")){ println(isin," --> ",validateISIN(isin)); } diff --git a/Task/Vampire-number/AWK/vampire-number.awk b/Task/Vampire-number/AWK/vampire-number.awk new file mode 100644 index 0000000000..ee810fce5a --- /dev/null +++ b/Task/Vampire-number/AWK/vampire-number.awk @@ -0,0 +1,19 @@ +function H(n,i, d, h) { + h=!split(n,d,X) + asort(d) + for(i in d)h=h d[i] + return h +} + +BEGIN{ + for(n=1000;n<=1000000;n++){ + if(split(n,d,X)%2)continue + l=length(n) + if(l%2)break + A=0 + t=l/2 + for(f=10^(t-1);f<=int(sqrt(n));f++) + if((n%f==0&&g=n/f)&&(length(f)==t&&length(g)==t&&!(f%10==0&&g%10==0)&&H(f g)==H(n)&&A=1))break + if(A)print n + } +} diff --git a/Task/Vampire-number/EasyLang/vampire-number.easy b/Task/Vampire-number/EasyLang/vampire-number.easy index 322f982d9d..c4caed9b81 100644 --- a/Task/Vampire-number/EasyLang/vampire-number.easy +++ b/Task/Vampire-number/EasyLang/vampire-number.easy @@ -5,12 +5,10 @@ func dtally x . . return t . -proc fangs x . f[] . +proc fangs x &f[] . f[] = [ ] - nd = floor log10 x + 1 - if nd mod 2 = 1 - return - . + nd = 1 + floor log x 10 + if nd mod 2 = 1 : return nd = nd div 2 lo = higher pow 10 (nd - 1) (x + pow 10 nd - 2) div (pow 10 nd - 1) hi = lower (x / lo) sqrt x @@ -22,11 +20,9 @@ proc fangs x . f[] . . . . -proc show_fangs x f[] . . +proc show_fangs x f[] . write x & " " - for f in f[] - write " = " & f & " x " & x div f - . + for f in f[] : write " = " & f & " x " & x div f print "" . x = 1 diff --git a/Task/Vampire-number/Elixir/vampire-number.elixir b/Task/Vampire-number/Elixir/vampire-number.ex similarity index 100% rename from Task/Vampire-number/Elixir/vampire-number.elixir rename to Task/Vampire-number/Elixir/vampire-number.ex diff --git a/Task/Vampire-number/Fortran/vampire-number.f b/Task/Vampire-number/Fortran/vampire-number.f new file mode 100644 index 0000000000..f97b799d20 --- /dev/null +++ b/Task/Vampire-number/Fortran/vampire-number.f @@ -0,0 +1,105 @@ +program vampire_numbers + implicit none + integer :: count, i, n_digits + integer(kind=8) :: num, test_nums(3) +! logical :: is_vampire + + ! Initialize test numbers + test_nums = [16758243290880_8, 24959017348650_8, 14593825548650_8] + + ! Print first 25 vampire numbers + print *, 'First 25 vampire numbers and their fangs:' + count = 0 + num = 1000 + do while (count < 25) + if (is_vampire(num)) then + count = count + 1 + end if + num = num + 1 + end do + + ! Check specific test numbers + print *, '' + print *, 'Checking specific numbers:' + do i = 1, 3 + if (is_vampire(test_nums(i))) then + continue ! Output handled in is_vampire + else + print *, test_nums(i), ' is not a vampire number.' + end if + end do + +contains + + logical function is_vampire(num) + integer(kind=8), intent(in) :: num + integer(kind=8) :: a, b, start_a, end_a + integer :: num_digits, half_digits + character(len=20) :: num_str, a_str, b_str + + ! Get number of digits + num_digits = floor(log10(real(num))) + 1 + if (mod(num_digits, 2) /= 0) then + is_vampire = .false. + return + end if + half_digits = num_digits / 2 + + ! Calculate range for factor a + start_a = max(10**(half_digits-1), num / (10**half_digits)) + end_a = min(num / 10**(half_digits-1), floor(sqrt(real(num)))) + + is_vampire = .false. + do a = start_a, end_a + if (mod(num, a) /= 0) cycle + b = num / a + + ! Check if b has correct number of digits + if (b < 10**(half_digits-1) .or. b >= 10**half_digits) cycle + + ! Check trailing zeros + if (mod(a, 10_8) == 0 .and. mod(b, 10_8) == 0) cycle + + ! Check if digits match + write(num_str, '(I0)') num + write(a_str, '(I0)') a + write(b_str, '(I0)') b + if (len_trim(a_str) == half_digits .and. len_trim(b_str) == half_digits) then + if (same_digits(num_str, a_str, b_str)) then + is_vampire = .true. + print '(I0, " : (", I0, ", ", I0, ")")', num, a, b + end if + end if + end do + end function is_vampire + + logical function same_digits(num_str, a_str, b_str) + character(len=*), intent(in) :: num_str, a_str, b_str + integer :: digits_num(0:9), digits_ab(0:9), i + character(len=1) :: c + + digits_num = 0 + digits_ab = 0 + + ! Count digits in num + do i = 1, len_trim(num_str) + read(num_str(i:i), '(A)') c + digits_num(ichar(c) - ichar('0')) = digits_num(ichar(c) - ichar('0')) + 1 + end do + + ! Count digits in a + do i = 1, len_trim(a_str) + read(a_str(i:i), '(A)') c + digits_ab(ichar(c) - ichar('0')) = digits_ab(ichar(c) - ichar('0')) + 1 + end do + + ! Count digits in b + do i = 1, len_trim(b_str) + read(b_str(i:i), '(A)') c + digits_ab(ichar(c) - ichar('0')) = digits_ab(ichar(c) - ichar('0')) + 1 + end do + + same_digits = all(digits_num == digits_ab) + end function same_digits + +end program vampire_numbers diff --git a/Task/Vampire-number/Julia/vampire-number-1.julia b/Task/Vampire-number/Julia/vampire-number-1.jl similarity index 100% rename from Task/Vampire-number/Julia/vampire-number-1.julia rename to Task/Vampire-number/Julia/vampire-number-1.jl diff --git a/Task/Vampire-number/Julia/vampire-number-2.julia b/Task/Vampire-number/Julia/vampire-number-2.jl similarity index 100% rename from Task/Vampire-number/Julia/vampire-number-2.julia rename to Task/Vampire-number/Julia/vampire-number-2.jl diff --git a/Task/Vampire-number/Julia/vampire-number-3.jl b/Task/Vampire-number/Julia/vampire-number-3.jl new file mode 100644 index 0000000000..33b0f82b5e --- /dev/null +++ b/Task/Vampire-number/Julia/vampire-number-3.jl @@ -0,0 +1,69 @@ +const TENS = [UInt(10)^i for i in 0:19] + +function dtally(x::UInt) + t = UInt(0) + while x > 0 + t += UInt(1) << ((x % 10) * 6) + x ÷= 10 + end + return t +end + +function fangs(x::UInt) + f = UInt[] + nd = ndigits(x) + nd & 1 != 0 && return f + nd ÷= 2 + + lo = max(TENS[nd], (x + TENS[nd+1] - 2) ÷ (TENS[nd+1] - 1)) + hi = min(x ÷ lo, floor(UInt, sqrt(x))) + + t = dtally(x) + for a in lo:hi + b = x ÷ a + if a * b == x && ((a % 10) != 0 || (b % 10) != 0) && t == dtally(a) + dtally(b) + push!(f, a) + end + end + + return f +end + +function show_fangs(x::UInt, f::Vector{UInt}) + print(x) + for fang in f + print(" = ", fang, " x ", x ÷ fang) + end + println() +end + +function testfangs() + bigs = UInt[16758243290880, 24959017348650, 14593825548650] + + # Find first 25 vampire numbers + x = UInt(1) + n = 0 + while n < 25 + f = fangs(x) + if !isempty(f) + n += 1 + print(lpad(n, 2), ": ") + show_fangs(x, f) + end + x += 1 + end + + println() + + # Check big numbers + for b in bigs + f = fangs(b) + if !isempty(f) + show_fangs(b, f) + else + println(b, " is not vampiric") + end + end +end + +testfangs() diff --git a/Task/Vampire-number/Kotlin/vampire-number.kotlin b/Task/Vampire-number/Kotlin/vampire-number.kts similarity index 100% rename from Task/Vampire-number/Kotlin/vampire-number.kotlin rename to Task/Vampire-number/Kotlin/vampire-number.kts diff --git a/Task/Vampire-number/Phix/vampire-number.phix b/Task/Vampire-number/Phix/vampire-number.phix index 26bcca13b8..87db5b462f 100644 --- a/Task/Vampire-number/Phix/vampire-number.phix +++ b/Task/Vampire-number/Phix/vampire-number.phix @@ -1,44 +1,42 @@ -(phixonline)--> - with javascript_semantics - requires("1.0.2") -- (for in) - function vampire(atom v) - sequence res = {} - if v>=0 then - string vs = sprintf("%d",v) - if mod(length(vs),2)=0 then -- even length - vs = sort(vs) - for i=power(10,length(vs)/2-1) to floor(sqrt(v)) do - if remainder(v,i)=0 then - integer i2 = v/i - string si = sprintf("%d",i), - s2 = sprintf("%d",i2) - if (si[$]!='0' or s2[$]!='0') - and sort(si&s2)=vs then - res = append(res,{i,i2}) - end if - end if - end for - end if - end if - return res - end function +with javascript_semantics +requires("1.0.2") -- (for in) +function vampire(atom v) + sequence res = {} + if v>=0 then + string vs = sprintf("%d",v) + if even(length(vs) then + vs = sort(vs) + for i=power(10,length(vs)/2-1) to floor(sqrt(v)) do + if remainder(v,i)=0 then + integer i2 = v/i + string si = sprintf("%d",i), + s2 = sprintf("%d",i2) + if (si[$]!='0' or s2[$]!='0') + and sort(si&s2)=vs then + res = append(res,{i,i2}) + end if + end if + end for + end if + end if + return res +end function - integer found = 0 - atom i = 0 - sequence res - puts(1,"The first 26 vampire numbers and their fangs:\n") - while found<26 do - res = vampire(i) - if length(res) then - found += 1 - printf(1,"%d: %d: %v\n",{found,i,res}) - end if - i += 1 - end while - puts(1,"\n") +integer found = 0 +atom i = 0 +sequence res +puts(1,"The first 26 vampire numbers and their fangs:\n") +while found<26 do + res = vampire(i) + if length(res) then + found += 1 + printf(1,"%d: %d: %v\n",{found,i,res}) + end if + i += 1 +end while +puts(1,"\n") - for i in {16758243290880,24959017348650,14593825548650} do - res = vampire(i) - printf(1,"%d: %s\n",{i,iff(res={}?"not a vampire number":sprint(res))}) - end for - end' elements of the Van Eck sequence.*/ +Parse Arg lo hi d . /*obtain optional arguments from the CL*/ +If lo=='' | lo==',' Then lo= 1 /*Not specified? Then use the default.*/ +If hi=='' | hi==',' Then hi= 10 /* " " " " " " */ +If d=='' | d==',' Then d= 0 /* " " " " " " */ +dd='' +z=d /*dd: old seq: d: initial value of seq*/ +Do i=1 To hi-1 + za=wordpos(reverse(z),reverse(dd)) + zb=0 + wdd=words(dd) + Do zz=wdd To 1 By -1 + If z=word(dd,zz) Then Do + zb=wdd-zz+1 + Leave + End + End + z=za + dd=d + d=d z + End /*HI-1*/ /*REVERSE allows backwards search in d.*/ +Say 'terms ' lo ' through ' hi ' of the Van Eck sequence are: ' subword(d,lo,hi-lo+1) +Exit + /*stick a fork in it, we're all done. */ diff --git a/Task/Van-Eck-sequence/REXX/van-eck-sequence-2.rexx b/Task/Van-Eck-sequence/REXX/van-eck-sequence-2.rexx index e8cb15b233..533d8971e8 100644 --- a/Task/Van-Eck-sequence/REXX/van-eck-sequence-2.rexx +++ b/Task/Van-Eck-sequence/REXX/van-eck-sequence-2.rexx @@ -1,14 +1,30 @@ -/*REXX pgm generates/displays the 'start ──► end' elements of the Van Eck sequence.*/ -parse arg LO HI sta . /*obtain optional arguments from the CL*/ -if LO=='' | LO=="," then LO= 1 /*Not specified? Then use the default.*/ -if HI=='' | HI=="," then HI= 10 /* " " " " " " */ -if sta=='' | sta=="," then sta= 0 /* " " " " " " */ -$.0= sta; x= sta; @.=. /*$.: the Van Eck sequence as a list.*/ - do #=1 for HI-1 /*X: is the last term being examined. */ - if @.x==. then do; @.x= #; $.#= 0; x= 0; end /*new term.*/ - else do; z= # - @.x; $.#= z; @.x= #; x= z; end /*old term.*/ - end /*#*/ /*Z: the new term being added to list.*/ - LOw= LO - 1; out= $.LOw /*initialize the output value. */ - do j=LO to HI-1; out= out $.j /*build a list for the output display. */ - end /*j*/ /*stick a fork in it, we're all done. */ -say 'terms ' LO " through " HI ' of the Van Eck sequence are: ' out +/*REXX pgm generates/displays the 'start --? end' elements of the Van Eck sequence.*/ +Parse Arg lo hi sta . /*obtain optional arguments from the CL*/ +If lo=='' | lo==',' Then lo= 1 /*Not specified? Then use the default.*/ +If hi=='' | hi==',' Then hi= 10 /* " " " " " " */ +If sta=='' | sta==',' Then sta= 0 /* " " " " " " */ +d.0=sta /*d.: the Van Eck sequence as a list.*/ +x=sta +a.=. +out='0' +Do n=1 For hi-1 /*X: is the last term being examined. */ + If a.x==. Then Do /* new term. */ + a.x=n + d.n=0 + x=0 + End + Else Do /* old term. */ + z=n-a.x + d.n=z + a.x=n + x=z + End + out=out d.n + End /*n*/ /*Z: the new term being added To list.*/ +low=lo-1 +out=d.low /* initialize the output list */ +Do j=lo To hi-1 + out=out d.j /*build a list For the output display. */ + End /*j*/ +Say 'terms ' lo ' through ' hi ' of the Van Eck sequence are: ' out + /*stick a fork in it, we're all done. */ diff --git a/Task/Van-Eck-sequence/Rust/van-eck-sequence.rust b/Task/Van-Eck-sequence/Rust/van-eck-sequence.rs similarity index 100% rename from Task/Van-Eck-sequence/Rust/van-eck-sequence.rust rename to Task/Van-Eck-sequence/Rust/van-eck-sequence.rs diff --git a/Task/Van-Eck-sequence/Uiua/van-eck-sequence.uiua b/Task/Van-Eck-sequence/Uiua/van-eck-sequence.uiua index 821db1f050..2484a7500b 100644 --- a/Task/Van-Eck-sequence/Uiua/van-eck-sequence.uiua +++ b/Task/Van-Eck-sequence/Uiua/van-eck-sequence.uiua @@ -1,3 +1,7 @@ -F ← ⊂⟨0◌|+1⟩>⊙(-1⧻),,⊗⊃⊢(↘1). # Generator function (prepends). -⇌⍥F999 [0] # Generate 1000 terms and flip. -⊃(&p↙¯)(&p↙∘)10 # Print first and last 10 terms. +# Generate Van Eck sequence. +F ← ( + ◡<⊙⊙◌⊃(⋅⧻|⊸˜⨂)°⊂. # Check where/if first digit already appeared. + ⊂⨬(⋅⋅0|⋅+₁) # If new, prepend zero, else last index it was in. +) +⇌⍥F999 [0] # Generate 1000 terms and reverse. +⊃(&p↙¯)(&p↙∘)10 # Print first and last 10 terms. diff --git a/Task/Van-der-Corput-sequence/Ada/van-der-corput-sequence.ada b/Task/Van-der-Corput-sequence/Ada/van-der-corput-sequence.adb similarity index 100% rename from Task/Van-der-Corput-sequence/Ada/van-der-corput-sequence.ada rename to Task/Van-der-Corput-sequence/Ada/van-der-corput-sequence.adb diff --git a/Task/Van-der-Corput-sequence/Agena/van-der-corput-sequence.agena b/Task/Van-der-Corput-sequence/Agena/van-der-corput-sequence.agena new file mode 100644 index 0000000000..ed9d3a3a71 --- /dev/null +++ b/Task/Van-der-Corput-sequence/Agena/van-der-corput-sequence.agena @@ -0,0 +1,32 @@ +scope /* show members of the van der Corput sequence in various bases + * translated from the C sample + */ + + # returns the numerator and denominator of the nth member of the van der Corput sequence + # in the specified base + local proc vc( nth :: number, base :: number ) + local p, q, n := 0, 1, nth; + + while n <> 0 do + p *:= base; + p +:= n mod base; + q *:= base; + n \:= base + od; + + # return the numerator and denominator reduced by their gcd + local num, denom := p, q; + q := numtheory.gcd( p, q ); + return num \ q, denom \ q + end; + + # task + for b from 2 to 5 do + printf( "base %d:", b ); + for i from 0 to 9 do + local n, d := vc( i, b ); + if n <> 0 then printf( " %d/%d", n, d ) else printf( " 0" ) fi + od; + io.write( "\n" ) + od +epocs diff --git a/Task/Van-der-Corput-sequence/Crystal/van-der-corput-sequence.cr b/Task/Van-der-Corput-sequence/Crystal/van-der-corput-sequence.cr new file mode 100644 index 0000000000..cdef0eda41 --- /dev/null +++ b/Task/Van-der-Corput-sequence/Crystal/van-der-corput-sequence.cr @@ -0,0 +1,8 @@ +def vdc (n, base=2) + str = n.to_s(base).reverse + str.to_i(base) / (base ** str.size) +end + +(2..5).each do |base| + puts "Base #{base}: " + Array.new(10){|i| vdc(i,base)}.join(", ") +end diff --git a/Task/Van-der-Corput-sequence/Delphi/van-der-corput-sequence.delphi b/Task/Van-der-Corput-sequence/Delphi/van-der-corput-sequence.pas similarity index 100% rename from Task/Van-der-Corput-sequence/Delphi/van-der-corput-sequence.delphi rename to Task/Van-der-Corput-sequence/Delphi/van-der-corput-sequence.pas diff --git a/Task/Van-der-Corput-sequence/Elixir/van-der-corput-sequence.elixir b/Task/Van-der-Corput-sequence/Elixir/van-der-corput-sequence.ex similarity index 100% rename from Task/Van-der-Corput-sequence/Elixir/van-der-corput-sequence.elixir rename to Task/Van-der-Corput-sequence/Elixir/van-der-corput-sequence.ex diff --git a/Task/Van-der-Corput-sequence/Euphoria/van-der-corput-sequence.euphoria b/Task/Van-der-Corput-sequence/Euphoria/van-der-corput-sequence.eu similarity index 100% rename from Task/Van-der-Corput-sequence/Euphoria/van-der-corput-sequence.euphoria rename to Task/Van-der-Corput-sequence/Euphoria/van-der-corput-sequence.eu diff --git a/Task/Van-der-Corput-sequence/JavaScript/van-der-corput-sequence.js b/Task/Van-der-Corput-sequence/JavaScript/van-der-corput-sequence.js new file mode 100644 index 0000000000..d98cbfd6ac --- /dev/null +++ b/Task/Van-der-Corput-sequence/JavaScript/van-der-corput-sequence.js @@ -0,0 +1,11 @@ +function vdc(n) { + const bits = [...n.toString(2)].toReversed(); + const exps = [...Array(bits.length).keys()].map(x => -x); + let res = 0; + for (let i = 0; i < bits.length; i++) { + res += bits[i] * 2 ** (exps[i] - 1); + } + return res; +} + +console.log([...Array(10).keys()].map(vdc).join(" ")); diff --git a/Task/Van-der-Corput-sequence/Julia/van-der-corput-sequence.julia b/Task/Van-der-Corput-sequence/Julia/van-der-corput-sequence.jl similarity index 100% rename from Task/Van-der-Corput-sequence/Julia/van-der-corput-sequence.julia rename to Task/Van-der-Corput-sequence/Julia/van-der-corput-sequence.jl diff --git a/Task/Van-der-Corput-sequence/Kotlin/van-der-corput-sequence.kotlin b/Task/Van-der-Corput-sequence/Kotlin/van-der-corput-sequence.kts similarity index 100% rename from Task/Van-der-Corput-sequence/Kotlin/van-der-corput-sequence.kotlin rename to Task/Van-der-Corput-sequence/Kotlin/van-der-corput-sequence.kts diff --git a/Task/Van-der-Corput-sequence/Lua/van-der-corput-sequence-1.lua b/Task/Van-der-Corput-sequence/Lua/van-der-corput-sequence-1.lua index 194e9d0c27..945419a199 100644 --- a/Task/Van-der-Corput-sequence/Lua/van-der-corput-sequence-1.lua +++ b/Task/Van-der-Corput-sequence/Lua/van-der-corput-sequence-1.lua @@ -11,3 +11,11 @@ function vdc(n, base) end return m end +for b = 2, 5 do + io.write( "base ", b, ": " ) + for n = 0, 9 do + local m = vdc(n, b) + io.write(string.format("%0.4f ", m)) + end + print() +end diff --git a/Task/Van-der-Corput-sequence/Oberon-07/van-der-corput-sequence.oberon b/Task/Van-der-Corput-sequence/Oberon-07/van-der-corput-sequence.oberon new file mode 100644 index 0000000000..432f3d38f3 --- /dev/null +++ b/Task/Van-der-Corput-sequence/Oberon-07/van-der-corput-sequence.oberon @@ -0,0 +1,53 @@ +MODULE VanDerCorput; (* show members of the van der Corput sequence *) + (* in various bases - translated from the C sample *) + IMPORT Out; + + (* returns the gcd of a and b *) + PROCEDURE gcd( a, b : INTEGER ) : INTEGER; + VAR n, p, q : INTEGER; + BEGIN + p := a; + q := b; + WHILE p # 0 DO n := p; p := q MOD p; q := n END + RETURN q + END gcd ; + + (* returns the numerator and denominator of the nth member of *) + (* the van der Corput sequence in the specified base *) + PROCEDURE vc( nth, base : INTEGER; VAR n, d : INTEGER ); + VAR p, q, g : INTEGER; + BEGIN + p := 0; q := 1; n := nth; + WHILE n # 0 DO + p := p * base; + INC( p, n MOD base ); + q := q * base; + n := n DIV base + END; + (* return the numerator and denominator reduced by their gcd *) + g := gcd( p, q ); + n := p DIV g; + d := q DIV g + END vc; + + PROCEDURE task; + VAR i, b, n, d : INTEGER; + BEGIN + FOR b := 2 TO 5 DO + Out.String( "base " );Out.Int( b, 0 );Out.String( ":" ); + FOR i := 0 TO 9 DO + vc( i, b, n, d ); + IF n = 0 THEN + Out.String( " 0" ) + ELSE + Out.String( " " );Out.Int( n, 0 ); + Out.String( "/" );Out.Int( d, 0 ) + END + END; + Out.Ln + END + END task ; + +BEGIN + task +END VanDerCorput. diff --git a/Task/Van-der-Corput-sequence/Pluto/van-der-corput-sequence.pluto b/Task/Van-der-Corput-sequence/Pluto/van-der-corput-sequence.pluto new file mode 100644 index 0000000000..07f57fefc6 --- /dev/null +++ b/Task/Van-der-Corput-sequence/Pluto/van-der-corput-sequence.pluto @@ -0,0 +1,35 @@ +do --[[ show members of the van der Corput sequence in various bases + translated from the C sample + ]] + + local int = require( "int" ) -- RC integer module - includes gcd + + -- returns the numerator and denominator of the nth member of the van der Corput sequence + -- in the specified base + local function vc( nth : number, base : number ) + local p, q, n = 0, 1, nth + + while n != 0 do + p *= base + p += n % base + q *= base + n //= base + end + + num, denom = p, q + + -- return the numerator and denominator reduced by their gcd + q = int.gcd( num, denom ) + return num // q, denom // q + end + + -- task + for b = 2, 5 do + io.write( $"base {b}:" ) + for i = 0, 9 do + local n, d = vc( i, b ) + io.write( if n != 0 then $" {n}/{d}" else " 0" end ) + end + io.write( "\n" ) + end +end diff --git a/Task/Van-der-Corput-sequence/R/van-der-corput-sequence.r b/Task/Van-der-Corput-sequence/R/van-der-corput-sequence.r new file mode 100644 index 0000000000..ce390b388e --- /dev/null +++ b/Task/Van-der-Corput-sequence/R/van-der-corput-sequence.r @@ -0,0 +1,12 @@ +num_bits <- function(n) ifelse(log2(n)%%1==0, + 1+log2(n), + ceiling(log2(n))) + +vdc <- function(n){ + if(n==0) return(0) + inds <- 1:num_bits(n) + vdc_raw <- intToBits(n)[inds] + sum(as.numeric(vdc_raw)*(2^-inds)) +} + +sapply(0:9, vdc) diff --git a/Task/Van-der-Corput-sequence/Rust/van-der-corput-sequence.rust b/Task/Van-der-Corput-sequence/Rust/van-der-corput-sequence.rs similarity index 100% rename from Task/Van-der-Corput-sequence/Rust/van-der-corput-sequence.rust rename to Task/Van-der-Corput-sequence/Rust/van-der-corput-sequence.rs diff --git a/Task/Van-der-Corput-sequence/VBScript/van-der-corput-sequence.vb b/Task/Van-der-Corput-sequence/VBScript/van-der-corput-sequence.vbs similarity index 100% rename from Task/Van-der-Corput-sequence/VBScript/van-der-corput-sequence.vb rename to Task/Van-der-Corput-sequence/VBScript/van-der-corput-sequence.vbs diff --git a/Task/Van-der-Corput-sequence/YAMLScript/van-der-corput-sequence.ys b/Task/Van-der-Corput-sequence/YAMLScript/van-der-corput-sequence.ys new file mode 100644 index 0000000000..3c710205c1 --- /dev/null +++ b/Task/Van-der-Corput-sequence/YAMLScript/van-der-corput-sequence.ys @@ -0,0 +1,18 @@ +!YS-v0 + +defn main(b): + each n range(10): + say: + format '%.6f': + vdc: n b + +defn vdc(n b): + loop n n, d 1, vdc 0.0: + if n > 0: + then: + d *=: b + r =: n % b + n .=: quot(b) + vdc +=: r / d + recur: n, d, vdc + else: vdc diff --git a/Task/Variable-declaration-reset/AppleScript/variable-declaration-reset.applescript b/Task/Variable-declaration-reset/AppleScript/variable-declaration-reset.applescript new file mode 100644 index 0000000000..23f6e18e0c --- /dev/null +++ b/Task/Variable-declaration-reset/AppleScript/variable-declaration-reset.applescript @@ -0,0 +1,7 @@ +set s to {1, 2, 2, 3, 4, 4, 5} + +repeat with i from 1 to 7 + set curr to item i of s + if i > 1 and curr = prev then log i + set prev to curr +end repeat diff --git a/Task/Variable-declaration-reset/C-sharp/variable-declaration-reset.cs b/Task/Variable-declaration-reset/C-sharp/variable-declaration-reset.cs new file mode 100644 index 0000000000..8c41a8eebb --- /dev/null +++ b/Task/Variable-declaration-reset/C-sharp/variable-declaration-reset.cs @@ -0,0 +1,37 @@ +internal class Program +{ + private static void Main(string[] args) + { + int[] s = { 1, 2, 2, 3, 4, 4, 5 }; + + // There is no output as 'prev' is created anew each time + // around the loop and set to zero. + for (int i = 0; i < s.Length; ++i) + { + int curr = s[i]; + int prev = 0; + // int prev; // triggers "error: variable prev might not have been initialized" + if (i > 0 && curr == prev) + { + Console.WriteLine(i); + } + + prev = curr; + } + + int gprev = 0; + + // Now 'gprev' is used and reassigned + // each time around the loop producing the desired output. + for (int i = 0; i < s.Length; ++i) + { + int curr = s[i]; + if (i > 0 && curr == gprev) + { + Console.WriteLine(i); + } + + gprev = curr; + } + } +} diff --git a/Task/Variable-declaration-reset/Julia/variable-declaration-reset-1.julia b/Task/Variable-declaration-reset/Julia/variable-declaration-reset-1.jl similarity index 100% rename from Task/Variable-declaration-reset/Julia/variable-declaration-reset-1.julia rename to Task/Variable-declaration-reset/Julia/variable-declaration-reset-1.jl diff --git a/Task/Variable-declaration-reset/Julia/variable-declaration-reset-2.julia b/Task/Variable-declaration-reset/Julia/variable-declaration-reset-2.jl similarity index 100% rename from Task/Variable-declaration-reset/Julia/variable-declaration-reset-2.julia rename to Task/Variable-declaration-reset/Julia/variable-declaration-reset-2.jl diff --git a/Task/Variable-declaration-reset/Julia/variable-declaration-reset-3.julia b/Task/Variable-declaration-reset/Julia/variable-declaration-reset-3.jl similarity index 100% rename from Task/Variable-declaration-reset/Julia/variable-declaration-reset-3.julia rename to Task/Variable-declaration-reset/Julia/variable-declaration-reset-3.jl diff --git a/Task/Variable-declaration-reset/LOLCODE/variable-declaration-reset.lol b/Task/Variable-declaration-reset/LOLCODE/variable-declaration-reset.lol new file mode 100644 index 0000000000..5704ba3367 --- /dev/null +++ b/Task/Variable-declaration-reset/LOLCODE/variable-declaration-reset.lol @@ -0,0 +1,21 @@ +HAI 1.3 + +I HAS A s ITZ A BUKKIT +s HAS A SRS 0 ITZ 1 +s HAS A SRS 1 ITZ 2 +s HAS A SRS 2 ITZ 2 +s HAS A SRS 3 ITZ 3 +s HAS A SRS 4 ITZ 4 +s HAS A SRS 5 ITZ 4 +s HAS A SRS 6 ITZ 5 + +IM IN YR LOOP UPPIN YR i TIL BOTH SAEM i AN 7 + I HAS A prev + I HAS A curr ITZ s'Z SRS i + BOTH OF DIFFRINT i AN SMALLR OF i AN 0 AN BOTH SAEM prev AN curr, O RLY? + YA RLY, VISIBLE i + OIC + prev R curr +IM OUTTA YR LOOP + +KTHXBYE diff --git a/Task/Variable-declaration-reset/Maxima/variable-declaration-reset.maxima b/Task/Variable-declaration-reset/Maxima/variable-declaration-reset.maxima new file mode 100644 index 0000000000..e0fdb74d71 --- /dev/null +++ b/Task/Variable-declaration-reset/Maxima/variable-declaration-reset.maxima @@ -0,0 +1,7 @@ +s: [1, 2, 2, 3, 4, 4, 5]$ + +for i from 1 thru 7 do( + curr: s[i], + if i>1 and curr=prev then print(i), + prev: curr +); diff --git a/Task/Variable-declaration-reset/Phix/variable-declaration-reset.phix b/Task/Variable-declaration-reset/Phix/variable-declaration-reset.phix index 8956525307..3d2a064e8b 100644 --- a/Task/Variable-declaration-reset/Phix/variable-declaration-reset.phix +++ b/Task/Variable-declaration-reset/Phix/variable-declaration-reset.phix @@ -1,11 +1,9 @@ -(phixonline)--> - with javascript_semantics - sequence s = {1,2,2,3,4,4,5} - for i=1 to length(s) do - integer curr = s[i], prev - if i>1 and curr=prev then - ?i - end if - prev = curr - end for - - function vlq_encode(sequence s) - sequence res = {} - for i=length(s) to 1 by -1 do - integer n = s[i], msb = 0 - if n<0 then crash("unsigned integers only!") end if - while 1 do - res = prepend(res,msb+and_bits(n,#7F)) - n = floor(n/#80) - if n=0 then exit end if - msb = #80 - end while - end for - return res - end function +with javascript_semantics - function vlq_decode(sequence s) - sequence res = {} - for i=1 to length(s) do - integer si = s[i], - n = n*#80+and_bits(byte,#7F) - if not and_bits(si,#80) then - res = append(res,n) - n = 0 - end if - end for - return res - end function +function vlq_encode(sequence s) + sequence res = {} + for i=length(s) to 1 by -1 do + integer n = s[i], msb = 0 + if n<0 then crash("unsigned integers only!") end if + while 1 do + res = prepend(res,msb+and_bits(n,#7F)) + n = floor(n/#80) + if n=0 then exit end if + msb = #80 + end while + end for + return res +end function - function svlg(sequence s) - string res = "" - for i=1 to length(s) do - res &= sprintf("#%02x:",{s[i]}) - end for - return res[1..$-1] - end function +function vlq_decode(sequence s) + sequence res = {} + integer n = 0 + for si in s do + n = n*#80+and_bits(si,#7F) + if not and_bits(si,#80) then + res = append(res,n) + n = 0 + end if + end for + return res +end function - constant testNumbers = { #200000, #1FFFFF, 1, 127, 128 } - sequence s = vlq_encode(testNumbers), - decoded = vlq_decode(s) - printf(1,"%s -> %s -> %s\n",{svlg(testNumbers),svlg(s),svlg(decoded)}) - if decoded!=testNumbers then crash("something wrong") end if - - with javascript_semantics - sequence d = {tagset(9,0)}, - inv = tagset(9,0), - p = {tagset(9,0)} - for i=1 to 4 do d = append(d,extract(d[$],{2,3,4,5,1,7,8,9,10,6})) end for - for i=5 to 8 do d = append(d,reverse(d[-4])) end for - d = append(d,reverse(d[1])) - inv[2..5] = reverse(inv[2..5]) - for i=1 to 7 do p = append(p,extract(p[$],{2,6,8,7,3,9,4,1,10,5})) end for +with javascript_semantics +sequence d = {tagset(9,0)}, + inv = tagset(9,0), + p = {tagset(9,0)} +for i=1 to 4 do d = append(d,extract(d[$],{2,3,4,5,1,7,8,9,10,6})) end for +for i=5 to 8 do d = append(d,reverse(d[-4])) end for + d = append(d,reverse(d[1])) +inv[2..5] = reverse(inv[2..5]) +for i=1 to 7 do p = append(p,extract(p[$],{2,6,8,7,3,9,4,1,10,5})) end for - -- alternatively, if you prefer: - --constant d = {{0,1,2,3,4,5,6,7,8,9}, - -- {1,2,3,4,0,6,7,8,9,5}, - -- {2,3,4,0,1,7,8,9,5,6}, - -- {3,4,0,1,2,8,9,5,6,7}, - -- {4,0,1,2,3,9,5,6,7,8}, - -- {5,9,8,7,6,0,4,3,2,1}, - -- {6,5,9,8,7,1,0,4,3,2}, - -- {7,6,5,9,8,2,1,0,4,3}, - -- {8,7,6,5,9,3,2,1,0,4}, - -- {9,8,7,6,5,4,3,2,1,0}}, - -- inv = {0,4,3,2,1,5,6,7,8,9}, - -- p = {{0,1,2,3,4,5,6,7,8,9}, - -- {1,5,7,6,2,8,3,0,9,4}, - -- {5,8,0,3,7,9,6,1,4,2}, - -- {8,9,1,6,0,4,3,5,2,7}, - -- {9,4,5,3,1,2,6,8,7,0}, - -- {4,2,8,6,5,7,3,9,0,1}, - -- {2,7,9,3,8,0,6,4,1,5}, - -- {7,0,4,6,9,1,3,2,5,8}} +-- alternatively, if you prefer: +--constant d = {{0,1,2,3,4,5,6,7,8,9}, +-- {1,2,3,4,0,6,7,8,9,5}, +-- {2,3,4,0,1,7,8,9,5,6}, +-- {3,4,0,1,2,8,9,5,6,7}, +-- {4,0,1,2,3,9,5,6,7,8}, +-- {5,9,8,7,6,0,4,3,2,1}, +-- {6,5,9,8,7,1,0,4,3,2}, +-- {7,6,5,9,8,2,1,0,4,3}, +-- {8,7,6,5,9,3,2,1,0,4}, +-- {9,8,7,6,5,4,3,2,1,0}}, +-- inv = {0,4,3,2,1,5,6,7,8,9}, +-- p = {{0,1,2,3,4,5,6,7,8,9}, +-- {1,5,7,6,2,8,3,0,9,4}, +-- {5,8,0,3,7,9,6,1,4,2}, +-- {8,9,1,6,0,4,3,5,2,7}, +-- {9,4,5,3,1,2,6,8,7,0}, +-- {4,2,8,6,5,7,3,9,0,1}, +-- {2,7,9,3,8,0,6,4,1,5}, +-- {7,0,4,6,9,1,3,2,5,8}} - function verhoeff(string n, bool validate=false, show_workings=false) - string {s,t} = iff(validate?{n,"Validation"}:{n&'0',"Check digit"}) - if show_workings then - printf(1,"%s calculations for `%s`:\n", {t, n}) - printf(1," i ni p(i,ni) c\n") - printf(1,"------------------\n") - end if - integer c = 0 - for i=1 to length(s) do - integer ni = s[-i]-'0', - pi = p[remainder(i-1,8)+1][ni+1] - c = d[c+1][pi+1] - if show_workings then - printf(1,"%2d %d %d %d\n", {i-1, ni, pi, c}) - end if - end for - integer ch = inv[c+1]+'0' - string r = iff(validate?iff(c=0?"":"in")&"correct" - :"`"&ch&"`") - printf(1,"The %s for `%s` is %s\n\n",{lower(t),n,r}) - return ch - end function +function verhoeff(string n, bool validate=false, show_workings=false) + string {s,t} = iff(validate?{n,"Validation"}:{n&'0',"Check digit"}) + if show_workings then + printf(1,"%s calculations for `%s`:\n", {t, n}) + printf(1," i ni p(i,ni) c\n") + printf(1,"------------------\n") + end if + integer c = 0 + for i=1 to length(s) do + integer ni = s[-i]-'0', + pi = p[remainder(i-1,8)+1][ni+1] + c = d[c+1][pi+1] + if show_workings then + printf(1,"%2d %d %d %d\n", {i-1, ni, pi, c}) + end if + end for + integer ch = inv[c+1]+'0' + string r = iff(validate?iff(c=0?"":"in")&"correct" + :"`"&ch&"`") + printf(1,"The %s for `%s` is %s\n\n",{lower(t),n,r}) + return ch +end function - constant tests = {"236", "12345", "123456789012"} - for i=1 to length(tests) do - bool show_workings = (i<=2) - integer ch = verhoeff(tests[i],false,show_workings) - assert(verhoeff(tests[i]&ch,true,show_workings)=='0') - assert(verhoeff(tests[i]&'9',true,show_workings)!='0') - end for -" +szIndent1: .asciz "| " +.align 4 +ptHeapReserve: .quad heapReserve +/*******************************************/ +/* UnInitialized data */ +/*******************************************/ +.bss // INFO: bss +.align 4 +sConvArea: .skip 24 +stTree: .skip tree_fin // place to structure tree +heapReserve: .skip HEAPSIZE +/*******************************************/ +/* code section */ +/*******************************************/ +.text +.global main +main: // INFO: main + ldr x0,qAdrszMessDebutPgm + bl affichageMess + mov x1,1 // node tree value +1: + ldr x0,qAdrstTree // structure tree address + bl insertElement // add element value x1 + cmp x0,-1 + beq 99f + add x1,x1,1 // increment value + cmp x1,NBVAL // end ? + ble 1b // no -> loop + + ldr x0,qAdrszMessDisplayTree + bl affichageMess + ldr x3,qAdrstTree // tree root address (begin structure) + ldr x0,[x3,#tree_root] + mov x1,0 // level + bl displayTree + + ldr x0,qAdrszMessFinOK + bl affichageMess + b 100f +99: // display error + ldr x0,qAdrszMessErreur + bl affichageMess +100: // standard end of the program + mov x8,EXIT // request to exit program + svc 0 // perform system call +qAdrszMessDebutPgm: .quad szMessDebutPgm +qAdrszMessFinOK: .quad szMessFinOK +qAdrszMessDisplayTree: .quad szMessDisplayTree +qAdrszMessErreur: .quad szMessErreur +qAdrszCarriageReturn: .quad szCarriageReturn +qAdrstTree: .quad stTree +qAdrdisplayElement: .quad displayElement +/******************************************************************/ +/* insert element in the tree */ +/******************************************************************/ +/* x0 contains the address of the tree structure */ +/* x1 contains the value of element */ +/* x0 returns address of element or - 1 if error */ +insertElement: // INFO: insertElement + stp x1,lr,[sp,-16]! // save registers + mov x4,x0 + mov x0,node_fin // reservation place one element + bl allocHeap + cmp x0,-1 // allocation error + beq 100f + mov x5,x0 + str x1,[x5,node_value] // store value in address heap + mov x1,0 + str x1,[x5,node_left] // init left pointer with zero + str x1,[x5,node_right] // init right pointer with zero + ldr x2,[x4,tree_size] // load tree size + cbnz x2,1f // 0 element ? + str x5,[x4,tree_root] // yes -> store in root + b 6f +1: // else search free address in tree + ldr x3,[x4,tree_root] // start with address root + add x6,x2,1 // increment tree size + clz x7,x6 // compute zeroes left bits + add x7,x7,1 // for sustract the first left bit + lsl x6,x6,x7 // shift number in left +2: + tst x6,1<<63 // test left bit + lsl x6,x6,1 // shift left bit + bne 3f // bit at one + ldr x1,[x3,node_left] // no store node address in left pointer + cbz x1,4f // if equal zero + mov x3,x1 // else loop with next node + b 2b +3: // yes + ldr x1,[x3,node_right] // store node address in right pointer + cbz x1,5f // if equal zero + mov x3,x1 // else loop with next node + b 2b +4: + str x5,[x3,node_left] + b 6f +5: + str x5,[x3,node_right] +6: + add x2,x2,1 // increment tree size + str x2,[x4,tree_size] +100: + ldp x1,lr,[sp],16 // restaur 2 registers + ret // return to address lr x30 +/******************************************************************/ +/* display tree */ +/******************************************************************/ +/* x0 contains the address of the tree */ +/* x1 level */ +displayTree: + stp x2,lr,[sp,-16]! // save registers + stp x3,x4,[sp,-16]! // save registers + stp x5,x6,[sp,-16]! + cmp x0,#-1 + beq 100f + mov x4,x0 + mov x5,x1 + mov x2,#0 + ldr x3,qAdrszIndent1 +1: + cmp x2,x1 + bge 2f + mov x0,x3 + bl affichageMess + add x2,x2,#1 + b 1b +2: + ldr x0,qAdrszIndent + bl affichageMess + ldr x0,[x4,#node_value] + ldr x1,qAdrsConvArea + bl conversion10S + // ldr x0,qAdrsConvArea + // bl shiftResult + ldr x0,qAdrsConvArea + bl affichageMess + ldr x0,qAdrszCarriageReturn + bl affichageMess + ldr x0,[x4,#node_left] + cmp x0,#0 + beq 3f + add x1,x5,#1 // increment level + bl displayTree +3: + ldr x0,[x4,#node_right] + cmp x0,#0 + beq 4f + add x1,x5,#1 // increment level + bl displayTree + b 100f +4: + mov x0,#-1 +100: + ldp x5,x6,[sp],16 + ldp x3,x4,[sp],16 // restaur 2 registers + ldp x2,lr,[sp],16 // restaur 2 registers + ret // return to address lr x30 +qAdrszIndent: .quad szIndent +qAdrszIndent1: .quad szIndent1 +qAdrsConvArea: .quad sConvArea +/******************************************************************/ +/* display node */ +/******************************************************************/ +/* x0 contains node address */ +displayElement: + stp x1,lr,[sp,-16]! // save registers + ldr x0,[x0,#node_value] + ldr x1,qAdrsConvArea + bl conversion10S + ldr x0,qAdrszMessResult + ldr x1,qAdrsConvArea + bl strInsertAtCharInc // insert result at @ character + bl affichageMess +100: + ldp x1,lr,[sp],16 // restaur 2 registers + ret // return to address lr x30 +qAdrszMessResult: .quad szMessResult + +/******************************************************************/ +/* memory allocation on the heap */ +/******************************************************************/ +/* x0 contains the size to allocate */ +/* x0 returns address of memory heap or - 1 if error */ +/* CAUTION : The size of the allowance must be a multiple of 4 */ +allocHeap: // INFO: allocHeap + stp x1,lr,[sp,-16]! // save registers + stp x2,x3,[sp,-16]! + stp x4,x5,[sp,-16]! + // allocation + ldr x1,qAdrptHeapReserve + ldr x2,[x1] // free heap address + add x3,x2,x0 // reserve area on heap + ldr x4,qAdrheapReserve + mov x0,#HEAPSIZE + add x4,x4,x0 // compute heap end + cmp x3,x4 + blt 1f // allocation address < heap end ? + mov x0,#-1 // allocation error + b 100f +1: + str x3,[x1] // store new start free address heap + mov x0,x2 // return address +100: + ldp x4,x5,[sp],16 + ldp x2,x3,[sp],16 + ldp x1,lr,[sp],16 // restaur 2 registers + ret // return to address lr x30 +qAdrptHeapReserve: .quad ptHeapReserve +qAdrheapReserve: .quad heapReserve +/***********************************************/ +/* File Include fonctions */ +/********************************************************/ +/* for this file see task include a file in language AArch64 assembly */ +.include "../includeARM64.inc" diff --git a/Task/Visualize-a-tree/ALGOL-68/visualize-a-tree.alg b/Task/Visualize-a-tree/ALGOL-68/visualize-a-tree.alg index f043061bd5..d1c20945ab 100644 --- a/Task/Visualize-a-tree/ALGOL-68/visualize-a-tree.alg +++ b/Task/Visualize-a-tree/ALGOL-68/visualize-a-tree.alg @@ -50,8 +50,6 @@ OP TOHTML = ( REF NODE tree )STRING: THEN # the node has branches # REF NODE child := child OF tree; - INT child number := 1; - INT mid child = ( child count + 1 ) OVER 2; child := child OF tree; result +:= tr + nl; WHILE child ISNT nil node @@ -78,7 +76,7 @@ OP +:= = ( REF NODE n, REF NODE sibling node )REF NODE: DO sibling := sibling OF sibling OD; - sibling OF sibling := sibling node + sibling OF sibling := sibling node # will get a potential scope violation warning # END # +:= # ; # appends a new sibling node to the node n, returns the sibling # OP +:= = ( REF NODE n, STRING sibling value )REF NODE: n +:= new node( sibling value ); diff --git a/Task/Visualize-a-tree/ARM-Assembly/visualize-a-tree.arm b/Task/Visualize-a-tree/ARM-Assembly/visualize-a-tree.arm new file mode 100644 index 0000000000..63f6ab171a --- /dev/null +++ b/Task/Visualize-a-tree/ARM-Assembly/visualize-a-tree.arm @@ -0,0 +1,283 @@ +/* ARM assembly Raspberry PI */ +/* program displaytree.s */ +/* REMARK 1 : this program use routines in a include file + see task Include a file language arm assembly + for the routine affichageMess conversion10 + see at end of this program the instruction include */ + +/*******************************************/ +/* Constantes */ +/*******************************************/ +.include "../constantes.inc" +.equ HEAPSIZE, 50000 +.equ NBVAL, 9 +/*******************************************/ +/* Macros */ +/*******************************************/ +//.include "../../ficmacros32.inc" @ for developer debugging + +/*******************************************/ +/* Structures */ +/********************************************/ +/* structure tree */ + .struct 0 +tree_root: @ root pointer + .struct tree_root + 4 +tree_size: @ number of element of tree + .struct tree_size + 4 +tree_fin: +/* structure node tree */ + .struct 0 +node_left: @ left pointer + .struct node_left + 4 +node_right: @ right pointer + .struct node_right + 4 +node_value: @ element value + .struct node_value + 4 +node_fin: + +/*******************************************/ +/* Initialized data */ +/*******************************************/ +.data +szMessDebutPgm: .asciz "Program 32 bits start. \n" +szMessFinOK: .asciz "Program normal end. \n" +szMessDisplayTree: .asciz "Tree display :\n" +szCarriageReturn: .asciz "\n" +/* datas error display */ +szMessErreur: .asciz "Error detected.\n" +/* datas message display */ +szMessResult: .ascii "Element value :" +sValue: .space 12,' ' + .asciz "\n" +szIndent: .asciz "|-->" +szIndent1: .asciz "| " +.align 2 +ptHeapReserve: .int heapReserve +/*******************************************/ +/* UnInitialized data */ +/*******************************************/ +.bss +sConvArea: .skip 24 +stTree: .skip tree_fin @ place to structure tree +heapReserve: .skip HEAPSIZE +/*******************************************/ +/* code section */ +/*******************************************/ +.text +.global main +main: + ldr r0,iAdrszMessDebutPgm + bl affichageMess + mov r1,#1 @ node tree value +1: + ldr r0,iAdrstTree @ structure tree address + bl insertElement @ add element value r1 + cmp r0,#-1 + beq 99f + add r1,#1 @ increment value + cmp r1,#NBVAL @ end ? + ble 1b @ no -> loop + + ldr r0,iAdrszMessDisplayTree + bl affichageMess + ldr r3,iAdrstTree @ tree root address (begin structure) + ldr r0,[r3,#tree_root] + mov r1,#0 + bl displayTree + + ldr r0,iAdrszMessFinOK + bl affichageMess + b 100f +99: @ display error + ldr r0,iAdrszMessErreur + bl affichageMess +100: @ standard end of the program + mov r7, #EXIT @ request to exit program + svc 0 @ perform system call +iAdrszMessDebutPgm: .int szMessDebutPgm +iAdrszMessFinOK: .int szMessFinOK +iAdrszMessDisplayTree: .int szMessDisplayTree +iAdrszMessErreur: .int szMessErreur +iAdrszCarriageReturn: .int szCarriageReturn +iAdrstTree: .int stTree +iAdrdisplayElement: .int displayElement +/******************************************************************/ +/* insert element in the tree */ +/******************************************************************/ +/* r0 contains the address of the tree structure */ +/* r1 contains the value of element */ +/* r0 returns address of element or - 1 if error */ +insertElement: + push {r1-r7,lr} @ save registers + mov r4,r0 + mov r0,#node_fin @ reservation place one element + bl allocHeap + cmp r0,#-1 @ allocation error + beq 100f + mov r5,r0 + str r1,[r5,#node_value] @ store value in address heap + mov r1,#0 + str r1,[r5,#node_left] @ init left pointer with zero + str r1,[r5,#node_right] @ init right pointer with zero + ldr r2,[r4,#tree_size] @ load tree size + cmp r2,#0 @ 0 element ? + bne 1f + str r5,[r4,#tree_root] @ yes -> store in root + b 4f +1: @ else search free address in tree + ldr r3,[r4,#tree_root] @ start with address root + add r6,r2,#1 @ increment tree size + clz r7,r6 @ compute zeroes left bits + add r7,#1 @ for sustract the first left bit + lsl r6,r7 @ shift number in left +2: + lsls r6,#1 @ read left bit + bcs 3f @ is 1 ? + ldr r1,[r3,#node_left] @ no store node address in left pointer + cmp r1,#0 @ if equal zero + streq r5,[r3,#node_left] + beq 4f + mov r3,r1 @ else loop with next node + b 2b +3: @ yes + ldr r1,[r3,#node_right] @ store node address in right pointer + cmp r1,#0 @ if equal zero + streq r5,[r3,#node_right] + beq 4f + mov r3,r1 @ else loop with next node + b 2b +4: + add r2,#1 @ increment tree size + str r2,[r4,#tree_size] +100: + pop {r1-r7,pc} @ restaur registers + +/******************************************************************/ +/* display node */ +/******************************************************************/ +/* r0 contains node address */ +displayElement: + push {r1,lr} @ save registers + ldr r0,[r0,#node_value] + ldr r1,iAdrsValue + bl conversion10S + ldr r0,iAdrszMessResult + bl affichageMess +100: + pop {r1,pc} @ restaur registers +iAdrszMessResult: .int szMessResult +iAdrsValue: .int sValue +/******************************************************************/ +/* shift result to left */ +/******************************************************************/ +/* r0 contains conversion area */ +shiftResult: @ INFO: shiftResult + push {r1-r3,lr} @ save registers + mov r2,#0 +1: + ldrb r1,[r0,r2] @ load one char + cmp r1,#0 @ zero -> end + beq 100f + cmp r1,#' ' @ not space ? + bne 2f + add r2,r2,#1 @ else loop + b 1b +2: + mov r3,#0 @ store indice +3: + strb r1,[r0,r3] @ store char in area begin + cmp r1,#0 @ zero -> end + beq 100f + add r2,r2,#1 @ increment indices + add r3,r3,#1 + ldrb r1,[r0,r2] @ load char + b 3b @ and loop + +100: + pop {r1-r3,pc} @ restaur registers +/******************************************************************/ +/* display tree */ +/******************************************************************/ +/* r0 contains node address */ +/* r1 contains level */ + +displayTree: + push {r2-r5,lr} @ save registers + cmp r0,#-1 + beq 100f + mov r4,r0 + mov r5,r1 + mov r2,#0 + ldr r3,iAdrszIndent1 +1: + cmp r2,r1 + bge 2f + mov r0,r3 + bl affichageMess + add r2,r2,#1 + b 1b +2: + ldr r0,iAdrszIndent + bl affichageMess + ldr r0,[r4,#node_value] + ldr r1,iAdrsConvArea + bl conversion10S + ldr r0,iAdrsConvArea + bl shiftResult + ldr r0,iAdrsConvArea + bl affichageMess + ldr r0,iAdrszCarriageReturn + bl affichageMess + ldr r0,[r4,#node_left] + cmp r0,#0 + beq 3f + add r1,r5,#1 @ increment level + bl displayTree +3: + ldr r0,[r4,#node_right] + cmp r0,#0 + beq 4f + add r1,r5,#1 @ increment level + bl displayTree + b 100f +4: + mov r0,#-1 + +100: + pop {r2-r5,pc} @ restaur registers +iAdrszIndent: .int szIndent +iAdrszIndent1: .int szIndent1 +iAdrsConvArea: .int sConvArea +/******************************************************************/ +/* memory allocation on the heap */ +/******************************************************************/ +/* r0 contains the size to allocate */ +/* r0 returns address of memory heap or - 1 if error */ +/* CAUTION : The size of the allowance must be a multiple of 4 */ +allocHeap: + push {r1-r4,lr} @ save registers + @ allocation + ldr r1,iAdrptHeapReserve + ldr r2,[r1] @ free heap address + add r3,r2,r0 @ reserve area on heap + ldr r4,iAdrheapReserve + mov r0,#HEAPSIZE + add r4,r4,r0 @ compute heap end + cmp r3,r4 + blt 1f @ allocation address < heap end ? + mov r0,#-1 @ allocation error + b 100f +1: + str r3,[r1] @ store new start free address heap + mov r0,r2 @ return address +100: + pop {r1-r4,pc} @ restaur registers +.align 2 +iAdrptHeapReserve: .int ptHeapReserve +iAdrheapReserve: .int heapReserve + +/***************************************************/ +/* ROUTINES INCLUDE */ +/***************************************************/ +.include "../affichage.inc" diff --git a/Task/Visualize-a-tree/Ada/visualize-a-tree.ada b/Task/Visualize-a-tree/Ada/visualize-a-tree.adb similarity index 100% rename from Task/Visualize-a-tree/Ada/visualize-a-tree.ada rename to Task/Visualize-a-tree/Ada/visualize-a-tree.adb diff --git a/Task/Visualize-a-tree/Delphi/visualize-a-tree.delphi b/Task/Visualize-a-tree/Delphi/visualize-a-tree.pas similarity index 100% rename from Task/Visualize-a-tree/Delphi/visualize-a-tree.delphi rename to Task/Visualize-a-tree/Delphi/visualize-a-tree.pas diff --git a/Task/Visualize-a-tree/Elena/visualize-a-tree.elena b/Task/Visualize-a-tree/Elena/visualize-a-tree.elena index 56d7e4de80..b391e2d14c 100644 --- a/Task/Visualize-a-tree/Elena/visualize-a-tree.elena +++ b/Task/Visualize-a-tree/Elena/visualize-a-tree.elena @@ -1,3 +1,5 @@ +/// a program to produce a visual representation of some tree. + import system'routines; import extensions; @@ -17,7 +19,7 @@ class Node <= new(value, new Node[](0)); constructor new(Node[] children) - <= new(emptyString, children); + <= new(EmptyString, children); get() = theValue; @@ -48,7 +50,7 @@ extension treeOp = self.writeTree(node,""); } -public program() +public Program() { var tree := Node.new( new Node[]{ @@ -60,5 +62,5 @@ public program() Node.new("e") }); - console.writeTree(tree).readChar() + Console.writeTree(tree).readChar() } diff --git a/Task/Visualize-a-tree/Julia/visualize-a-tree.julia b/Task/Visualize-a-tree/Julia/visualize-a-tree.jl similarity index 100% rename from Task/Visualize-a-tree/Julia/visualize-a-tree.julia rename to Task/Visualize-a-tree/Julia/visualize-a-tree.jl diff --git a/Task/Visualize-a-tree/Kotlin/visualize-a-tree.kotlin b/Task/Visualize-a-tree/Kotlin/visualize-a-tree.kts similarity index 100% rename from Task/Visualize-a-tree/Kotlin/visualize-a-tree.kotlin rename to Task/Visualize-a-tree/Kotlin/visualize-a-tree.kts diff --git a/Task/Visualize-a-tree/RISC-V-Assembly/visualize-a-tree.asm b/Task/Visualize-a-tree/RISC-V-Assembly/visualize-a-tree.asm new file mode 100644 index 0000000000..5e94ff67e3 --- /dev/null +++ b/Task/Visualize-a-tree/RISC-V-Assembly/visualize-a-tree.asm @@ -0,0 +1,270 @@ +# riscv assembly raspberry pico2 rp2350 +# program displaytree.s +# connexion putty com3 +/*********************************************/ +/* CONSTANTES */ +/********************************************/ +/* for this file see risc-v task include a file */ +.include "../../constantesRiscv.inc" +.equ HEAPSIZE, 50000 +.equ NBVAL, 9 + +/****************************************************/ +/* MACROS */ +/****************************************************/ +#.include "../ficmacrosriscv.inc" # for debugging only + +/*******************************************/ +/* Structures */ +/********************************************/ +/* structure tree */ + .struct 0 +tree_root: # root pointer + .struct tree_root + 4 +tree_size: # number of element of tree + .struct tree_size + 4 +tree_fin: +/* structure node tree */ + .struct 0 +node_left: # left pointer + .struct node_left + 4 +node_right: # right pointer + .struct node_right + 4 +node_value: # element value + .struct node_value + 4 +node_fin: + + +/*******************************************/ +/* INITIALED DATAS */ +/*******************************************/ +.data +szMessStart: .asciz "Program riscv start.\r\n" +szMessEnd: .asciz "\nProgram end OK.\r\n" +szCariageReturn: .asciz "\r\n" +szIndent: .asciz "|-->" +szIndent1: .asciz "| " + +szMessDisplayTree: .asciz "Tree display :\n" + +szMessResult: .asciz "Element value : " +.align 2 +ptHeapReserve: .int heapReserve + + +.align 2 +/*******************************************/ +/* UNINITIALED DATA */ +/*******************************************/ +.bss +.align 2 +sConvArea: .skip 24 +stTree: .skip tree_fin # place to structure tree +heapReserve: .skip HEAPSIZE +/********************************...-..--*****/ +/* SECTION CODE */ +/**********************************************/ +.text +.global main + +main: # INFO: main + call stdio_init_all # général init +1: # start loop connexion + li a0,0 # raz argument register + call tud_cdc_n_connected # waiting for USB connection + beqz a0,1b # return code = zero ? + + la a0,szMessStart # message address + call writeString # display message + li s0,1 +1: + la a0,stTree + mv a1,s0 # value + call insertElement + li t0,-1 + beq a0,t0,100f + addi s0,s0,1 + li t0,NBVAL + ble s0,t0,1b + + la a0,szMessDisplayTree + call writeString + + la a0,stTree + lw a0,tree_root(a0) + li a1,0 + call displayTree + + la a0,szMessEnd + call writeString + call getchar +100: # final loop + j 100b +/******************************************************************/ +/* insert element in the tree */ +/******************************************************************/ +/* a0 contains the address of the tree structure */ +/* a1 contains the value of element */ +/* a0 returns address of element or - 1 if error */ +insertElement: # INFO: insertElement + addi sp, sp, -8 # save registres + sw ra, 0(sp) + sw s0,4(sp) + mv s0,a0 + li a0,node_fin # reservation place one element + call allocHeap + li t0,-1 + beq a0,t0,100f # allocation error + mv t0,a0 # save address + sw a1,node_value(t0) # store value in address heap + sw x0,node_left(t0) # init left pointer with zero + sw x0,node_right(t0) # init right pointer with zero + lw t1,tree_size(s0) # load tree size + bnez t1,1f # 0 element + sw t0,tree_root(s0) # yes -> store in root + j 4f +1: # else search free address in tree + lw t2,tree_root(s0) # start with address root + mv t5,a1 # value node + clz t3,t5 # compute zeroes left bits + addi t3,t3,1 # for sustract the first left bit + sll t5,t5,t3 # shift number in left +2: + slt t4,t5,x0 # is bit31 = 1 + slli t5,t5,1 + bnez t4,3f # is bit31 = 1 + lw t4,node_left(t2) # no store node address in left pointer + bnez t4,21f # equal zero ? + sw t0,node_left(t2) + j 4f +21: + mv t2,t4 # else loop with next node + j 2b +3: + lw t4,node_right(t2) # no store node address in right pointer + bnez t4,31f # equal zero ? + sw t0,node_right(t2) + j 4f +31: + mv t2,t4 # else loop with next node + j 2b # and loop +4: + addi t1,t1,1 + sw t1,tree_size(s0) + mv a0,t0 + +100: + lw ra, 0(sp) + lw s0,4(sp) + addi sp, sp, 8 + ret +/******************************************************************/ +/* display node */ +/******************************************************************/ +/* a0 contains node address */ +displayElement: # INFO: displayElement + addi sp, sp, -8 # reserve stack + sw ra, 0(sp) + sw s0,4(sp) + lw a0,node_value(a0) + la a1,sConvArea + call conversion10S + la a0,szMessResult + call writeString + la a0,sConvArea + call writeString + la a0,szCariageReturn + call writeString +100: + lw ra, 0(sp) + lw s0, 4(sp) + addi sp, sp, 8 + ret +/******************************************************************/ +/* Display tree */ +/******************************************************************/ +/* a0 contains tree address */ +/* a1 level */ +/* a0 returns 0 if empty else 1 */ +displayTree: # INFO: displayTree + addi sp, sp, -20 # reserve stack + sw ra, 0(sp) + sw s0, 4(sp) + sw s1, 8(sp) + sw s2, 12(sp) + sw s3, 16(sp) + li t0,-1 + beq a0,t0,100f + mv s0,a0 + mv s1,a1 + li s2,0 + la s3,szIndent1 +1: # display indentation loop + bge s2,s1,2f + mv a0,s3 + call writeString + addi s2,s2,1 + j 1b +2: + la a0,szIndent + call writeString + # affregtit debut1 + lw a0,node_value(s0) + la a1,sConvArea + call conversion10S + la a0,sConvArea + call writeString + la a0,szCariageReturn + call writeString + + lw a0,node_left(s0) + beqz a0,3f + addi a1,s1,1 + call displayTree +3: + lw a0,node_right(s0) + beqz a0,4f + addi a1,s1,1 + call displayTree + j 100f +4: + li a0,-1 + +100: + lw ra, 0(sp) + lw s0, 4(sp) + lw s1, 8(sp) + lw s2, 12(sp) + lw s3, 16(sp) + addi sp, sp, 20 +/******************************************************************/ +/* memory allocation on the heap */ +/******************************************************************/ +/* a0 contains the size to allocate */ +/* a0 returns address of memory heap or - 1 if error */ +/* CAUTION : The size of the allowance must be a multiple of 4 */ +allocHeap: # INFO: allocHeap + addi sp, sp, -8 # reserve stack + sw ra, 0(sp) + la t0,ptHeapReserve + lw t1,(t0) # free heap address + add t2,t1,a0 # reserve area on heap + la t3,heapReserve + li t4,HEAPSIZE + add t3,t3,t4 # compute heap end + blt t2,t3,1f # allocation address < heap end ? + li a0,-1 # allocation error + j 100f +1: + sw t2,(t0) # store new start free address heap + mv a0,t1 # return address +100: + lw ra, 0(sp) + addi sp, sp, 8 + ret + +/************************************/ +/* file include Fonctions */ +/***********************************/ +/* for this file see risc-v task include a file */ +.include "../../includeFunctions.s" diff --git a/Task/Visualize-a-tree/Rust/visualize-a-tree.rust b/Task/Visualize-a-tree/Rust/visualize-a-tree.rs similarity index 100% rename from Task/Visualize-a-tree/Rust/visualize-a-tree.rust rename to Task/Visualize-a-tree/Rust/visualize-a-tree.rs diff --git a/Task/Visualize-a-tree/XPL0/visualize-a-tree.xpl0 b/Task/Visualize-a-tree/XPL0/visualize-a-tree.xpl0 new file mode 100644 index 0000000000..2abb83a92e --- /dev/null +++ b/Task/Visualize-a-tree/XPL0/visualize-a-tree.xpl0 @@ -0,0 +1,36 @@ +int SDown, SLast, SNone; + +proc Tree(Root, Head); +int Root, Head; +int Col(2), Tail, R; +def \Stem\ Str, Next; +[Col(Str):= 0; Col(Next):= 0; +Tail:= Head; +loop [if Tail = 0 then quit; + Text(0, Tail(Str)); + if Tail(Next) = 0 then quit; + Tail:= Tail(Next); + ]; +Text(0, "--"); IntOut(0, Root); CrLf(0); + +if Root <= 1 then return; + +if Tail # 0 then + if Tail(Str) = SLast then + Tail(Str):= SNone; + +if Tail = 0 then [Tail:= Col; Head:= Col] + else Tail(Next):= Col; + +while Root do \\ make a tree by doing something random + [R:= 1 + Ran(Root); + Root:= Root - R; + Col(Str):= if Root # 0 then SDown else SLast; + Tree(R, Head); + ]; +Tail(Next):= 0; +]; + +[SDown:= " |"; SLast:= " `"; SNone:= " "; +Tree(8, 0); +] diff --git a/Task/Vogels-approximation-method/ALGOL-68/vogels-approximation-method.alg b/Task/Vogels-approximation-method/ALGOL-68/vogels-approximation-method.alg new file mode 100644 index 0000000000..a5cc244b9c --- /dev/null +++ b/Task/Vogels-approximation-method/ALGOL-68/vogels-approximation-method.alg @@ -0,0 +1,100 @@ +BEGIN # Vogel's approximation method - translation of the EasyLang sample # + PR read "rows.incl.a68" PR # include row (array) utilities # + [ 1 : 4 ]INT supply := ( 50, 60, 50, 50 ); + [ 1 : 5 ]INT demand := ( 30, 20, 70, 30, 60 ); + [,]INT costs = ( ( 16, 16, 13, 22, 17 ) + , ( 14, 14, 13, 19, 15 ) + , ( 19, 19, 20, 23, 50 ) + , ( 50, 12, 50, 15, 11 ) + ); + INT nrows = ( UPB supply + 1 ) - LWB supply; + INT ncols = ( UPB demand + 1 ) - LWB demand; + + [ 1 : nrows ]BOOL row done; FOR i TO nrows DO row done[ i ] := FALSE OD; + [ 1 : ncols ]BOOL col done; FOR i TO ncols DO col done[ i ] := FALSE OD; + + PROC diff = ( INT j, le, BOOL is row )[]INT: BEGIN + INT min1 := max int, min2 := 0, minp := 0; + FOR i TO le DO + IF NOT IF is row THEN col done[ i ] ELSE row done[ i ] FI + THEN # not done # + INT c := IF is row THEN costs[ j, i ] ELSE costs[ i, j ] FI; + IF c < min1 THEN + min2 := min1; + min1 := c; + minp := i + ELIF c < min2 THEN + min2 := c + FI + FI + OD; + ( min2 - min1, min1, minp ) + END # diff # ; + + PROC max penalty = ( INT len1, len2, BOOL is row )[]INT: BEGIN + INT md := - max int, pm := 0, pc := 0, mc := 0; + FOR i TO len1 DO + IF NOT IF is row THEN row done[ i ] ELSE col done[ i ] FI + THEN # not done # + []INT res = diff( i, len2, is row ); + IF res[ 1 ] > md THEN + md := res[ 1 ]; + pm := i; + mc := res[2]; + pc := res[3] + FI + FI + OD; + IF is row THEN + ( pm, pc, mc, md ) + ELSE + ( pc, pm, mc, md ) + FI + END # max penelty # ; + + PROC nextcell = []INT: BEGIN + []INT res1 = max penalty( nrows, ncols, TRUE ); + []INT res2 = max penalty( ncols, nrows, FALSE ); + IF res1[ 4 ] = res2[ 4 ] THEN + IF res1[ 3 ] < res2[ 3 ] THEN res1 ELSE res2 FI + ELSE + IF res1[ 4 ] > res2[ 4 ] THEN res2 ELSE res1 FI + FI + END # nextcell # ; + + BEGIN + [ 1 : nrows, 1 : ncols ]INT results; + INT supplyleft := 0; + FOR v pos FROM LWB supply TO UPB supply DO + supplyleft +:= supply[ v pos ]; + FOR j TO ncols DO results[ v pos, j ] := 0 OD + OD; + INT totalcost := 0; + WHILE supplyleft > 0 DO + []INT cell = nextcell; + INT r = cell[ 1 ]; + INT c = cell[ 2 ]; + INT q = IF demand[ c ] < supply[ r ] THEN demand[ c ] ELSE supply[ r ] FI; + IF ( demand[ c ] -:= q ) = 0 THEN + col done[ c ] := TRUE + FI; + IF ( supply[ r ] -:= q ) = 0 THEN + row done[ r ] := TRUE + FI; + results[ r, c ] := q; + supplyleft -:= q; + totalcost +:= q * costs[ r, c ] + OD; + print( ( "[", newline ) ); + FOR i TO nrows DO + print( ( " [" ) ); + FOR j TO ncols DO + STRING fmt := whole( results[ i, j ], 0 ); + IF ( UPB fmt + 1 ) - LWB fmt < 2 THEN " " +=: fmt FI; + print( ( " ", fmt ) ) + OD; + print( ( " ]", newline ) ) + OD; + print( ( "]", newline, "Total cost: ", whole( totalcost, 0 ), newline ) ) + END +END diff --git a/Task/Vogels-approximation-method/C-sharp/vogels-approximation-method.cs b/Task/Vogels-approximation-method/C-sharp/vogels-approximation-method.cs new file mode 100644 index 0000000000..fb65be9685 --- /dev/null +++ b/Task/Vogels-approximation-method/C-sharp/vogels-approximation-method.cs @@ -0,0 +1,117 @@ +using System; +using System.Linq; +using System.Threading.Tasks; + +public class VogelsApproximationMethod +{ + private static readonly int[] demand = {30, 20, 70, 30, 60}; + private static readonly int[] supply = {50, 60, 50, 50}; + private static readonly int[,] costs = {{16, 16, 13, 22, 17}, {14, 14, 13, 19, 15}, + {19, 19, 20, 23, 50}, {50, 12, 50, 15, 11}}; + + private static readonly int nRows = supply.Length; + private static readonly int nCols = demand.Length; + + private static bool[] rowDone = new bool[nRows]; + private static bool[] colDone = new bool[nCols]; + private static int[,] result = new int[nRows, nCols]; + + public static async Task Main(string[] args) + { + int supplyLeft = supply.Sum(); + int totalCost = 0; + + while (supplyLeft > 0) + { + int[] cell = await NextCell(); + int r = cell[0]; + int c = cell[1]; + + int quantity = Math.Min(demand[c], supply[r]); + demand[c] -= quantity; + if (demand[c] == 0) + colDone[c] = true; + + supply[r] -= quantity; + if (supply[r] == 0) + rowDone[r] = true; + + result[r, c] = quantity; + supplyLeft -= quantity; + + totalCost += quantity * costs[r, c]; + } + + // Print results + for (int i = 0; i < nRows; i++) + { + Console.Write("["); + for (int j = 0; j < nCols; j++) + { + Console.Write(result[i, j]); + if (j < nCols - 1) Console.Write(", "); + } + Console.WriteLine("]"); + } + Console.WriteLine($"Total cost: {totalCost}"); + } + + private static async Task NextCell() + { + Task task1 = Task.Run(() => MaxPenalty(nRows, nCols, true)); + Task task2 = Task.Run(() => MaxPenalty(nCols, nRows, false)); + + int[] res1 = await task1; + int[] res2 = await task2; + + if (res1[3] == res2[3]) + return res1[2] < res2[2] ? res1 : res2; + + return (res1[3] > res2[3]) ? res2 : res1; + } + + private static int[] Diff(int j, int len, bool isRow) + { + int min1 = int.MaxValue, min2 = int.MaxValue; + int minP = -1; + + for (int i = 0; i < len; i++) + { + if (isRow ? colDone[i] : rowDone[i]) + continue; + + int c = isRow ? costs[j, i] : costs[i, j]; + if (c < min1) + { + min2 = min1; + min1 = c; + minP = i; + } + else if (c < min2) + min2 = c; + } + return new int[] {min2 - min1, min1, minP}; + } + + private static int[] MaxPenalty(int len1, int len2, bool isRow) + { + int md = int.MinValue; + int pc = -1, pm = -1, mc = -1; + + for (int i = 0; i < len1; i++) + { + if (isRow ? rowDone[i] : colDone[i]) + continue; + + int[] res = Diff(i, len2, isRow); + if (res[0] > md) + { + md = res[0]; // max diff + pm = i; // pos of max diff + mc = res[1]; // min cost + pc = res[2]; // pos of min cost + } + } + return isRow ? new int[] {pm, pc, mc, md} : new int[] {pc, pm, mc, md}; + } +} diff --git a/Task/Vogels-approximation-method/EasyLang/vogels-approximation-method.easy b/Task/Vogels-approximation-method/EasyLang/vogels-approximation-method.easy new file mode 100644 index 0000000000..85f9ef114d --- /dev/null +++ b/Task/Vogels-approximation-method/EasyLang/vogels-approximation-method.easy @@ -0,0 +1,103 @@ +supply[] = [ 50 60 50 50 ] +demand[] = [ 30 20 70 30 60 ] +costs[][] = [ [ 16 16 13 22 17 ] [ 14 14 13 19 15 ] [ 19 19 20 23 50 ] [ 50 12 50 15 11 ] ] +# +nrows = len supply[] +ncols = len demand[] +# +len row_done[] nrows +len col_done[] ncols +# +func[] diff j le is_row . + min1 = 1 / 0 + for i = 1 to le + if is_row = 1 + done = col_done[i] + else + done = row_done[i] + . + if done = 0 + if is_row = 1 + c = costs[j][i] + else + c = costs[i][j] + . + if c < min1 + min2 = min1 + min1 = c + minp = i + elif c < min2 + min2 = c + . + . + . + return [ min2 - min1 min1 minp ] +. +func[] max_penalty len1 len2 is_row . + md = -1 / 0 + for i = 1 to len1 + if is_row = 1 + done = row_done[i] + else + done = col_done[i] + . + if done = 0 + res[] = diff i len2 is_row + if res[1] > md + md = res[1] + pm = i + mc = res[2] + pc = res[3] + . + . + . + if is_row = 1 + return [ pm pc mc md ] + else + return [ pc pm mc md ] + . +. +func[] nextcell . + res1[] = max_penalty nrows ncols 1 + res2[] = max_penalty ncols nrows 0 + if res1[4] = res2[4] + if res1[3] < res2[3] + return res1[] + else + return res2[] + . + else + if res1[4] > res2[4] + return res2[] + else + return res1[] + . + . +. +proc main . + for v in supply[] + supplyleft += v + results[][] &= [ ] + len results[$][] ncols + . + while supplyleft > 0 + cell[] = nextcell + r = cell[1] + c = cell[2] + q = lower demand[c] supply[r] + demand[c] -= q + if demand[c] = 0 + col_done[c] = 1 + . + supply[r] -= q + if supply[r] = 0 + row_done[r] = 1 + . + results[r][c] = q + supplyleft -= q + totalcost += q * costs[r][c] + . + print results[][] + print "Total cost: " & totalcost +. +main diff --git a/Task/Vogels-approximation-method/Fortran/vogels-approximation-method.f b/Task/Vogels-approximation-method/Fortran/vogels-approximation-method.f new file mode 100644 index 0000000000..dc2199bd51 --- /dev/null +++ b/Task/Vogels-approximation-method/Fortran/vogels-approximation-method.f @@ -0,0 +1,96 @@ +program vogels_approximation_method + implicit none + integer, parameter :: m = 4, n = 5 + integer :: costs(m,n), supply(m), demand(n) + integer :: allocation(m,n), i, total_cost + + ! Initialize data + costs = reshape([16,14,19,50, 16,14,19,12, 13,13,20,50, 22,19,23,15, 17,15,50,11], [m,n]) + supply = [50, 60, 50, 50] + demand = [30, 20, 70, 30, 60] + + ! Perform VAM + call vam(costs, supply, demand, allocation) + + ! Calculate and print total cost + total_cost = sum(costs * allocation) + print *, "Total cost: ", total_cost + + ! Print allocation + print *, "Allocation:" + do i = 1, m + print *, allocation(i,:) + end do + +contains + + subroutine vam(costs, supply, demand, allocation) + integer, intent(in) :: costs(m,n) + integer, intent(inout) :: supply(m), demand(n) + integer, intent(out) :: allocation(m,n) + integer :: row_penalties(m), col_penalties(n) + integer :: i, j, max_penalty, max_index, min_cost, alloc + logical :: row_done(m), col_done(n) + + allocation = 0 + row_done = .false. + col_done = .false. + + do while (any(.not. row_done) .and. any(.not. col_done)) + ! Calculate penalties + call calculate_penalties(costs, row_done, col_done, row_penalties, col_penalties) + + ! Find maximum penalty + max_penalty = max(maxval(row_penalties), maxval(col_penalties)) + if (maxval(row_penalties) >= maxval(col_penalties)) then + max_index = maxloc(row_penalties, dim=1) + min_cost = minval(costs(max_index, :), mask=.not. col_done) + j = minloc(costs(max_index, :), dim=1, mask=.not. col_done) + i = max_index + else + max_index = maxloc(col_penalties, dim=1) + min_cost = minval(costs(:, max_index), mask=.not. row_done) + i = minloc(costs(:, max_index), dim=1, mask=.not. row_done) + j = max_index + end if + + ! Allocate + alloc = min(supply(i), demand(j)) + allocation(i,j) = alloc + supply(i) = supply(i) - alloc + demand(j) = demand(j) - alloc + + ! Update done flags + if (supply(i) == 0) row_done(i) = .true. + if (demand(j) == 0) col_done(j) = .true. + end do + end subroutine vam + + subroutine calculate_penalties(costs, row_done, col_done, row_penalties, col_penalties) + integer, intent(in) :: costs(m,n) + logical, intent(in) :: row_done(m), col_done(n) + integer, intent(out) :: row_penalties(m), col_penalties(n) + integer :: i, j, min1, min2 + + do i = 1, m + if (.not. row_done(i)) then + min1 = minval(costs(i,:), mask=.not. col_done) + min2 = minval(costs(i,:), mask=(.not. col_done .and. costs(i,:) > min1)) + row_penalties(i) = min2 - min1 + else + row_penalties(i) = -1 + end if + end do + + do j = 1, n + if (.not. col_done(j)) then + min1 = minval(costs(:,j), mask=.not. row_done) + min2 = minval(costs(:,j), mask=(.not. row_done .and. costs(:,j) > min1)) + col_penalties(j) = min2 - min1 + else + col_penalties(j) = -1 + end if + end do + end subroutine calculate_penalties + +end program vogels_approximation_method diff --git a/Task/Vogels-approximation-method/FreeBASIC/vogels-approximation-method.basic b/Task/Vogels-approximation-method/FreeBASIC/vogels-approximation-method.basic new file mode 100644 index 0000000000..d9b631bda7 --- /dev/null +++ b/Task/Vogels-approximation-method/FreeBASIC/vogels-approximation-method.basic @@ -0,0 +1,127 @@ +Const NROWS = 4, NCOLS = 5 +Const MAX_INT = &h7FFFFFFF + +Dim Shared As Integer supply(NROWS-1) = {50, 60, 50, 50} +Dim Shared As Integer demand(NCOLS-1) = {30, 20, 70, 30, 60} +Dim Shared As Integer costs(NROWS-1, NCOLS-1), results(NROWS-1, NCOLS-1) +Dim Shared As Boolean rowDone(NROWS-1), colDone(NCOLS-1) + +Sub calcDiff(j As Integer, l As Integer, isRow As Boolean, diff() As Integer) + Dim As Integer min1 = MAX_INT, min2 = MAX_INT, minP = -1 + + For i As Integer = 0 To l-1 + Dim As Boolean done = Iif(isRow, colDone(i), rowDone(i)) + + If done Then Continue For + + Dim As Integer c = Iif(isRow, costs(j, i), costs(i, j)) + + If c < min1 Then + min2 = min1 + min1 = c + minP = i + Elseif c < min2 Then + min2 = c + End If + Next + + diff(0) = min2 - min1 + diff(1) = min1 + diff(2) = minP +End Sub + +Sub maxPenalty(len1 As Integer, len2 As Integer, isRow As Boolean, result() As Integer) + Dim As Integer md = -MAX_INT + Dim As Integer pc = -1, pm = -1, mc = -1 + Dim As Integer diff(2) + + For i As Integer = 0 To len1-1 + Dim As Boolean done = Iif(isRow, rowDone(i), colDone(i)) + + If done Then Continue For + + calcDiff(i, len2, isRow, diff()) + If diff(0) > md Then + md = diff(0) + pm = i + mc = diff(1) + pc = diff(2) + End If + Next + + If isRow Then + result(0) = pm : result(1) = pc : result(2) = mc : result(3) = md + Else + result(0) = pc : result(1) = pm : result(2) = mc : result(3) = md + End If +End Sub + +Sub nextCell(cell() As Integer) + Dim As Integer i, res1(3), res2(3) + + maxPenalty(NROWS, NCOLS, True, res1()) + maxPenalty(NCOLS, NROWS, False, res2()) + + If res1(3) = res2(3) Then + If res1(2) < res2(2) Then + For i = 0 To 3 + cell(i) = res1(i) + Next + Else + For i = 0 To 3 + cell(i) = res2(i) + Next + End If + Elseif res1(3) > res2(3) Then + For i = 0 To 3 + cell(i) = res2(i) + Next + Else + For i = 0 To 3 + cell(i) = res1(i) + Next + End If +End Sub + +' Main program +costs(0,0)=16 : costs(0,1)=16 : costs(0,2)=13 : costs(0,3)=22 : costs(0,4)=17 +costs(1,0)=14 : costs(1,1)=14 : costs(1,2)=13 : costs(1,3)=19 : costs(1,4)=15 +costs(2,0)=19 : costs(2,1)=19 : costs(2,2)=20 : costs(2,3)=23 : costs(2,4)=50 +costs(3,0)=50 : costs(3,1)=12 : costs(3,2)=50 : costs(3,3)=15 : costs(3,4)=11 + +Dim As Integer i, j, supplyLeft = 0 +For i = 0 To NROWS-1 + supplyLeft += supply(i) +Next + +Dim As Integer totalCost = 0 +Dim As Integer cell(3) + +While supplyLeft > 0 + nextCell(cell()) + Dim As Integer r = cell(0), c = cell(1), q = demand(c) + If q > supply(r) Then q = supply(r) + + demand(c) -= q + If demand(c) = 0 Then colDone(c) = True + + supply(r) -= q + If supply(r) = 0 Then rowDone(r) = True + + results(r, c) = q + supplyLeft -= q + totalCost += q * costs(r, c) +Wend + +Print " A B C D E" +For i = 0 To NROWS-1 + Print Chr(Asc("W") + i); + For j = 0 To NCOLS-1 + Print Using " ##"; results(i, j); + Next + Print +Next + +Print !"\nTotal cost = "; totalCost + +Sleep diff --git a/Task/Vogels-approximation-method/JavaScript/vogels-approximation-method.js b/Task/Vogels-approximation-method/JavaScript/vogels-approximation-method.js new file mode 100644 index 0000000000..03c71c06e7 --- /dev/null +++ b/Task/Vogels-approximation-method/JavaScript/vogels-approximation-method.js @@ -0,0 +1,290 @@ +/** + * Helper function to print a 2D array (matrix) nicely. + * @param {Array>} matrix The matrix to print. + * @param {string} title Optional title to print before the matrix. + */ +function printMatrix(matrix, title = "") { + if (title) { + console.log(title); + } + // console.table is often available and provides good formatting + if (typeof console.table === 'function') { + console.table(matrix); + } else { + // Fallback basic printing + matrix.forEach(row => { + // JSON.stringify formats arrays with commas and brackets + console.log(JSON.stringify(row)); + }); + } +} + +// --- Input Data --- +// Using let for demand and supply as they will be modified during the algorithm +// Make copies if you want to preserve the original arrays elsewhere +let demand = [30, 20, 70, 30, 60]; +let supply = [50, 60, 50, 50]; +const costs = [ + [16, 16, 13, 22, 17], + [14, 14, 13, 19, 15], + [19, 19, 20, 23, 50], + [50, 12, 50, 15, 11] +]; + +// --- Dimensions and State Variables --- +const nRows = supply.length; +const nCols = demand.length; + +// Track which rows/columns are fully satisfied +const rowDone = Array(nRows).fill(false); +const colDone = Array(nCols).fill(false); + +// The resulting allocation matrix, initialized with zeros +const result = Array(nRows).fill(0).map(() => Array(nCols).fill(0)); + +/** + * Calculates the difference between the two smallest costs in a given row or column, + * considering only active (not done) cells. + * @param {number} j The index of the row or column to analyze. + * @param {number} len The length of the other dimension (nCols if analyzing a row, nRows if analyzing a column). + * @param {boolean} isRow True if analyzing row j, false if analyzing column j. + * @returns {Array} An array: [penalty, minCost, minCostPosition] + * penalty = min2 - min1 (Infinity if < 2 costs found) + * minCost = the smallest cost found (Infinity if none found) + * minCostPosition = index of the smallest cost (-1 if none found) + */ +function diff(j, len, isRow) { + let min1 = Infinity; + let min2 = Infinity; + let minP = -1; // Position (index) of min1 + + for (let i = 0; i < len; i++) { + // Skip if the corresponding column (if analyzing row) or row (if analyzing column) is already done + if (isRow ? colDone[i] : rowDone[i]) { + continue; + } + + // Get the cost from the correct cell + const c = isRow ? costs[j][i] : costs[i][j]; + + if (c < min1) { + min2 = min1; // Old min1 becomes min2 + min1 = c; // New cost is the new min1 + minP = i; // Record position of new min1 + } else if (c < min2) { + min2 = c; // Update min2 + } + } + + // Calculate penalty: difference between second minimum and first minimum + // If min2 is still Infinity, it means less than two costs were found. Penalty is Infinity. + const penalty = (min2 === Infinity) ? Infinity : min2 - min1; + + return [penalty, min1, minP]; +} + +/** + * Finds the row or column with the maximum penalty among active rows/columns. + * @param {number} len1 Number of rows or columns to iterate through (nRows or nCols). + * @param {number} len2 Length of the other dimension (nCols or nRows). + * @param {boolean} isRow True if finding max penalty among rows, false for columns. + * @returns {Array | null} An array: [rowIndex, colIndex, minCostInSelected, maxPenaltyValue] + * Returns null if no active rows/columns found. + */ +function maxPenalty(len1, len2, isRow) { + let maxDiff = -Infinity; // Use -Infinity to ensure any real penalty is larger + let posOfMaxDiff = -1; // Index of row/column with max penalty + let posOfMinCost = -1; // Index of min cost within the selected row/column + let minCostVal = -1; // Value of min cost within the selected row/column + let foundActive = false; + + for (let i = 0; i < len1; i++) { + // Skip if this row (if isRow) or column (if !isRow) is already done + if (isRow ? rowDone[i] : colDone[i]) { + continue; + } + foundActive = true; // Found at least one active row/column to check + + const res = diff(i, len2, isRow); // [penalty, minCost, minPos] + const currentPenalty = res[0]; + + // Check if this penalty is the highest found so far + if (currentPenalty > maxDiff) { + maxDiff = currentPenalty; + posOfMaxDiff = i; // Record which row/column had this max penalty + minCostVal = res[1]; // Record the min cost in this row/column + posOfMinCost = res[2]; // Record the position of min cost + } + } + if (!foundActive) { + return null; // No active rows/columns left to calculate penalty for + } + + // Return results ensuring format [rowIndex, colIndex, minCostVal, maxDiff] + return isRow + ? [posOfMaxDiff, posOfMinCost, minCostVal, maxDiff] // For row: [rowIdx, colIdxOfMin, minCost, penalty] + : [posOfMinCost, posOfMaxDiff, minCostVal, maxDiff]; // For col: [rowIdxOfMin, colIdx, minCost, penalty] +} + +/** + * Determines the next cell to allocate to based on Vogel's Approximation Method (VAM). + * It compares the highest row penalty and the highest column penalty. + * @returns {Array | null} An array: [rowIndex, colIndex, minCostInSelected, maxPenaltyValue] + * Returns null if no suitable cell can be found. + */ +function nextCell() { + const resRow = maxPenalty(nRows, nCols, true); // Max penalty among rows + const resCol = maxPenalty(nCols, nRows, false); // Max penalty among columns + + // Handle cases where one or both couldn't find penalties (e.g., all done) + if (!resRow && !resCol) return null; // No more valid moves + if (!resRow) return resCol; // Only column penalty found + if (!resCol) return resRow; // Only row penalty found + + const maxPenaltyRow = resRow[3]; + const maxPenaltyCol = resCol[3]; + const minCostInRow = resRow[2]; + const minCostInCol = resCol[2]; + + // Decide based on highest penalty. Break ties by choosing the one with the lower minimum cost. + if (maxPenaltyRow === maxPenaltyCol) { + return minCostInRow <= minCostInCol ? resRow : resCol; + } else { + // In the C++ code: `res1[3] > res2[3] ? res2 : res1;` + // This seems backward? Higher penalty should be chosen. + // Let's assume higher penalty is better: + // return maxPenaltyRow >= maxPenaltyCol ? resRow : resCol; + // Let's stick to the C++ code's logic for direct translation: + return maxPenaltyRow > maxPenaltyCol ? resCol : resRow; + // Re-evaluating C++ code: + // `auto res1 = maxPenalty(nRows, nCols, true);` -> `res1` = row result + // `auto res2 = maxPenalty(nCols, nRows, false);` -> `res2` = col result + // `return res1[3] > res2[3] ? res2 : res1;` -> If row penalty > col penalty, return col result. This is incorrect VAM. + // VAM selects the *highest* penalty. + // Let's correct the logic based on VAM principle: Choose highest penalty, break ties with lowest cost. + // + // if (maxPenaltyRow > maxPenaltyCol) { + // return resRow; + // } else if (maxPenaltyCol > maxPenaltyRow) { + // return resCol; + // } else { + // // Penalties are equal, break tie with minimum cost + // return minCostInRow <= minCostInCol ? resRow : resCol; + // } + // + // The logic `maxPenaltyRow > maxPenaltyCol ? resCol : resRow` actually means: + // If RowPenalty is bigger, return ColumnResult. If ColPenalty is bigger or equal, return RowResult. + // This seems highly suspect and likely a bug in the original C++ or a misunderstanding of its output. + // Let's implement the standard VAM logic (highest penalty wins, tiebreak with cost): + if (maxPenaltyRow > maxPenaltyCol) { + return resRow; + } else if (maxPenaltyCol > maxPenaltyRow) { + return resCol; + } else { + // Penalties are equal, break tie with minimum cost cell within the tied lines + return minCostInRow <= minCostInCol ? resRow : resCol; + } + } +} + + +// --- Main VAM Algorithm Execution --- + +// Calculate total initial supply +let supplyLeft = supply.reduce((sum, current) => sum + current, 0); +let totalCost = 0; +let iterations = 0; // Safety counter +const maxIterations = nRows * nCols * 2; // A reasonable upper bound + +console.log("Starting Vogel's Approximation Method..."); +console.log("Initial Supply:", supply); +console.log("Initial Demand:", demand); +console.log("Costs:"); +printMatrix(costs); +console.log("---"); + + +while (supplyLeft > 0 && iterations < maxIterations) { + iterations++; + const cell = nextCell(); // Get [r, c, minCost, penalty] for the next allocation + + if (!cell) { + console.log("No suitable cell found by nextCell(). Stopping."); + break; // No more valid moves can be determined + } + + const r = cell[0]; // Row index to allocate to + const c = cell[1]; // Column index to allocate to + + // Safety check for valid indices and if the cell's row/col are already done + // This shouldn't happen if maxPenalty correctly skips done rows/cols, but good for robustness. + if (r < 0 || r >= nRows || c < 0 || c >= nCols || rowDone[r] || colDone[c]) { + console.warn(`Iteration ${iterations}: nextCell returned invalid/done cell [${r}, ${c}]. Attempting to recover or break.`); + // Attempt recovery: mark potentially problematic row/col as done if indices are valid + if (r >= 0 && r < nRows) rowDone[r] = true; + if (c >= 0 && c < nCols) colDone[c] = true; + // Or simply break: + // break; + continue; // Try finding another cell in the next iteration + } + + + // Determine the quantity to allocate: minimum of remaining supply in row r and demand in col c + const quantity = Math.min(demand[c], supply[r]); + + if (quantity <= 0) { + // This might happen if a row/col is selected but has 0 supply/demand left. + // Mark them as done and continue. + console.warn(`Iteration ${iterations}: Zero quantity allocation attempted for cell [${r}, ${c}]. Marking row/col as done.`); + if (demand[c] <= 0 && !colDone[c]) colDone[c] = true; + if (supply[r] <= 0 && !rowDone[r]) rowDone[r] = true; + continue; + } + + + // Update demand, supply, and mark as done if depleted + demand[c] -= quantity; + if (demand[c] === 0) { + colDone[c] = true; + } + + supply[r] -= quantity; + if (supply[r] === 0) { + rowDone[r] = true; + } + + // Record the allocation in the result matrix + result[r][c] = quantity; + + // Update total supply left and total cost + supplyLeft -= quantity; + totalCost += quantity * costs[r][c]; + + // console.log(`Iteration ${iterations}: Allocated ${quantity} to [${r}, ${c}]. Cost += ${quantity * costs[r][c]}. SupplyLeft: ${supplyLeft}`); + // console.log(" Current Supply:", supply); + // console.log(" Current Demand:", demand); + // console.log(" rowDone:", rowDone); + // console.log(" colDone:", colDone); + // console.log("---"); + +} + +if (iterations >= maxIterations) { + console.warn("Warning: Maximum iterations reached. The algorithm might be stuck in a loop."); +} + +// --- Output Results --- +console.log("\n--- VAM Finished ---"); +printMatrix(result, "Allocation Matrix (Result):"); +console.log(`\nTotal Cost: ${totalCost}`); + +// Optional: Check final state +const remainingDemand = demand.reduce((s, d) => s + d, 0); +const remainingSupply = supply.reduce((s, sup) => s + sup, 0); +console.log(`Final Remaining Demand: ${remainingDemand}`); +console.log(`Final Remaining Supply: ${remainingSupply}`); +console.log(`Calculated Supply Left: ${supplyLeft}`); + +// Verify if total allocated matches total demand/supply (assuming balanced problem) +const totalAllocated = result.flat().reduce((s, q) => s + q, 0); +console.log(`Total Quantity Allocated: ${totalAllocated}`); diff --git a/Task/Vogels-approximation-method/Jq/vogels-approximation-method.jq b/Task/Vogels-approximation-method/Jq/vogels-approximation-method.jq new file mode 100644 index 0000000000..ceb2e1e9d2 --- /dev/null +++ b/Task/Vogels-approximation-method/Jq/vogels-approximation-method.jq @@ -0,0 +1,112 @@ +### Generic functions +def array($n): . as $in | [range(0;$n)|$in]; + +def lpad($len): tostring | ($len - length) as $l | (" " * $l) + .; + +def maxSafeInteger: pow(2;53); # 9007199254740992 + +def minSafeInteger: -maxSafeInteger; + +### The Vogel Approximation Method +# Input: the state +def diff($j; $len; $isRow): + .min1 = maxSafeInteger + | .min2 = maxSafeInteger + | .minP = -1 + | reduce range(0; $len) as $i (.; + (if $isRow then .colDone[$i] else .rowDone[$i] end) as $done + | if ($done|not) + then + (if $isRow then .costs[$j][$i] else .costs[$i][$j] end) as $c + | if $c < .min1 + then .min2 = .min1 + | .min1 = $c + | .minP = $i + elif ($c < .min2) then .min2 = $c + end + end ) + | [.min2 - .min1, .min1, .minP] ; + +# Input: the state +def maxPenalty($len1; $len2; $isRow): + .md = minSafeInteger + | .pc = -1 + | .pm = -1 + | .mc = -1 + | reduce range(0; $len1) as $i (.; + (if $isRow then .rowDone[$i] else .colDone[$i] end) as $done + | if ($done|not) + then diff($i; $len2; $isRow) as $res + | if ($res[0] > .md) + then .md = $res[0] # max diff + | .pm = $i # pos of max diff + | .mc = $res[1] # min cost + | .pc = $res[2] # pos of min cost + end + end ) + | if $isRow + then [.pm, .pc, .mc, .md] + else [.pc, .pm, .mc, .md] + end; + +# Input: the state +def nextCell: + maxPenalty(.nRows; .nCols; true) as $res1 + | maxPenalty(.nCols; .nRows; false) as $res2 + | if $res1[3] == $res2[3] + then (if ($res1[2] < $res2[2]) then $res1 else $res2 end) + else (if ($res1[3] > $res2[3]) then $res2 else $res1 end) + end; + +# Vogel's approximation method +def vam($supply; $demand; $costs): + def nRows: $supply|length; + def nCols: $demand|length; + + {$supply, + $demand, + $costs, + totalCost: 0, + nRows: nRows, + nCols: nCols, + rowDone: (false | array(nRows)), + colDone: (false | array(nCols)), + results: (0 | array(nCols) | array(nRows)) + } + | .supplyLeft = (.supply | add) + + | until(.supplyLeft <= 0; + nextCell as $cell + | $cell[0] as $r + | $cell[1] as $c + | ([.demand[$c], .supply[$r]] | min) as $q + | .demand[$c] += - $q + | if .demand[$c] == 0 then .colDone[$c] = true end + | .supply[$r] += - $q + | if .supply[$r] == 0 then .rowDone[$r] = true end + | .results[$r][$c] = $q + | .supplyLeft += - $q + | .totalCost += $q * .costs[$r][$c] ); + +# The problem at hand: + +def supply: [50, 60, 50, 50]; + +def demand: [30, 20, 70, 30, 60]; + +def costs: [ + [16, 16, 13, 22, 17], + [14, 14, 13, 19, 15], + [19, 19, 20, 23, 50], + [50, 12, 50, 15, 11] +]; + +# The Vogel approximation +vam(supply; demand; costs) +| ["W", "X", "Y", "Z"] as $Row +| " A B C D E", + (range(0; .results|length) as $i + | .results[$i] as $result + | ($Row[$i] + ($result | map(lpad(4)) | join("")) ) ), + + "\nTotal Cost = \(.totalCost)" diff --git a/Task/Vogels-approximation-method/Julia/vogels-approximation-method-1.julia b/Task/Vogels-approximation-method/Julia/vogels-approximation-method-1.jl similarity index 100% rename from Task/Vogels-approximation-method/Julia/vogels-approximation-method-1.julia rename to Task/Vogels-approximation-method/Julia/vogels-approximation-method-1.jl diff --git a/Task/Vogels-approximation-method/Julia/vogels-approximation-method-2.julia b/Task/Vogels-approximation-method/Julia/vogels-approximation-method-2.jl similarity index 100% rename from Task/Vogels-approximation-method/Julia/vogels-approximation-method-2.julia rename to Task/Vogels-approximation-method/Julia/vogels-approximation-method-2.jl diff --git a/Task/Vogels-approximation-method/Julia/vogels-approximation-method-3.julia b/Task/Vogels-approximation-method/Julia/vogels-approximation-method-3.jl similarity index 100% rename from Task/Vogels-approximation-method/Julia/vogels-approximation-method-3.julia rename to Task/Vogels-approximation-method/Julia/vogels-approximation-method-3.jl diff --git a/Task/Vogels-approximation-method/Kotlin/vogels-approximation-method.kotlin b/Task/Vogels-approximation-method/Kotlin/vogels-approximation-method.kts similarity index 100% rename from Task/Vogels-approximation-method/Kotlin/vogels-approximation-method.kotlin rename to Task/Vogels-approximation-method/Kotlin/vogels-approximation-method.kts diff --git a/Task/Vogels-approximation-method/Mathematica/vogels-approximation-method.math b/Task/Vogels-approximation-method/Mathematica/vogels-approximation-method.math new file mode 100644 index 0000000000..56a1d5cf1e --- /dev/null +++ b/Task/Vogels-approximation-method/Mathematica/vogels-approximation-method.math @@ -0,0 +1,123 @@ +(* Transportation Problem Solver using Vogel's Approximation Method *) + +costs = <| + "W" -> <|"A" -> 16, "B" -> 16, "C" -> 13, "D" -> 22, "E" -> 17|>, + "X" -> <|"A" -> 14, "B" -> 14, "C" -> 13, "D" -> 19, "E" -> 15|>, + "Y" -> <|"A" -> 19, "B" -> 19, "C" -> 20, "D" -> 23, "E" -> 50|>, + "Z" -> <|"A" -> 50, "B" -> 12, "C" -> 50, "D" -> 15, "E" -> 11|> +|>; + +demand = <|"A" -> 30, "B" -> 20, "C" -> 70, "D" -> 30, "E" -> 60|>; +cols = Sort[Keys[demand]]; +supply = <|"W" -> 50, "X" -> 60, "Y" -> 50, "Z" -> 50|>; + +(* Initialize result matrix *) +res = AssociationMap[ + Function[k, AssociationMap[0 &, Keys[demand]]], + Keys[costs] +]; + +(* Initialize g dictionary for sorting *) +g = <||>; + +(* Sort destinations by cost for each supplier *) +Do[ + g[x] = SortBy[Keys[costs[x]], costs[x][#] &]; + , {x, Keys[supply]} +]; + +(* Sort suppliers by cost for each destination *) +Do[ + g[x] = SortBy[Keys[costs], costs[#][x] &]; + , {x, Keys[demand]} +]; + +(* Main algorithm loop *) +While[Length[g] > 0, + (* Calculate penalties for demand nodes *) + d = <||>; + Do[ + If[KeyExistsQ[demand, x] && Length[g[x]] > 0, + d[x] = If[Length[g[x]] > 1, + costs[g[x][[2]]][x] - costs[g[x][[1]]][x], + costs[g[x][[1]]][x] + ]; + ]; + , {x, Keys[demand]} + ]; + + (* Calculate penalties for supply nodes *) + s = <||>; + Do[ + If[KeyExistsQ[supply, x] && Length[g[x]] > 0, + s[x] = If[Length[g[x]] > 1, + costs[x][g[x][[2]]] - costs[x][g[x][[1]]], + costs[x][g[x][[1]]] + ]; + ]; + , {x, Keys[supply]} + ]; + + (* Find keys with maximum penalties *) + fKey = If[Length[d] > 0, + First[Keys[d] // SortBy[d[#] &] // Reverse], + "" + ]; + tKey = If[Length[s] > 0, + First[Keys[s] // SortBy[s[#] &] // Reverse], + "" + ]; + + (* Get the actual maximum values *) + maxD = If[Length[d] > 0, d[fKey], 0]; + maxS = If[Length[s] > 0, s[tKey], 0]; + + (* Choose the allocation with higher penalty *) + {t, f} = If[maxD > maxS, + {fKey, g[fKey][[1]]}, + {g[tKey][[1]], tKey} + ]; + + (* Allocate minimum of supply and demand *) + v = Min[supply[f], demand[t]]; + res[f][t] += v; + demand[t] -= v; + + (* Update demand and remove if satisfied *) + If[demand[t] == 0, + Do[ + If[KeyExistsQ[supply, k] && supply[k] != 0, + g[k] = DeleteCases[g[k], t] + ]; + , {k, Keys[supply]} + ]; + g = KeyDrop[g, t]; + demand = KeyDrop[demand, t]; + ]; + + (* Update supply and remove if exhausted *) + supply[f] -= v; + If[supply[f] == 0, + Do[ + If[KeyExistsQ[demand, k] && demand[k] != 0, + g[k] = DeleteCases[g[k], f] + ]; + , {k, Keys[demand]} + ]; + g = KeyDrop[g, f]; + supply = KeyDrop[supply, f]; + ]; +]; + +(*Display results*) +Print["Transportation Solution:"]; + +Dataset[res] + +totalCost = 0; +Do[rowData = Table[ + totalCost += res[supplier][dest]*costs[supplier][dest]; + , {dest, cols}]; + , {supplier, Sort[Keys[costs]]}]; + +Print["Total Cost = ", totalCost]; diff --git a/Task/Vogels-approximation-method/Rust/vogels-approximation-method.rs b/Task/Vogels-approximation-method/Rust/vogels-approximation-method.rs new file mode 100644 index 0000000000..4cde1ab24c --- /dev/null +++ b/Task/Vogels-approximation-method/Rust/vogels-approximation-method.rs @@ -0,0 +1,117 @@ +struct Vogel { + supply: Vec, + demand: Vec, + costs: Vec>, + n_rows: i32, + n_cols: i32, + row_done: Vec, + col_done: Vec, +} + +impl Vogel { + fn approximate(&mut self) { + let mut results = vec![vec![0_i32; self.n_cols as usize]; self.n_rows as usize]; + let mut supply_remaining = self.supply.iter().sum::(); + let mut total_cost = 0; + while supply_remaining > 0 { + let cell = self.next_cell(); + let r = cell[0]; + let c = cell[1]; + let q = if self.demand[c] < self.supply[r] { + self.demand[c] + } else { + self.supply[r] + }; + self.demand[c] -= q; + if self.demand[c] == 0 { + self.col_done[c] = true; + } + self.supply[r] -= q; + if self.supply[r] == 0 { + self.row_done[r] = true; + } + results[r][c] = q; + supply_remaining -= q; + total_cost += q * self.costs[r][c]; + } + + println!(" A B C D E"); + for (i, result) in results.iter().enumerate() { + print!("{}", ('W' as u8 + i as u8) as char); + for item in result { + print!(" {:>2}", item); + } + println!(); + } + println!("\nTotal Cost = {}", total_cost); + } + + fn next_cell(&mut self) -> Vec { + let res1 = self.max_penalty(self.n_rows, self.n_cols, true); + let res2 = self.max_penalty(self.n_cols, self.n_rows, false); + if res1[3] == res2[3] { + return if res1[2] < res2[2] { res1 } else { res2 }; + } + return if res1[3] > res2[3] { res2 } else { res1 }; + } + + fn max_penalty(&mut self, len1: i32, len2: i32, is_row: bool) -> Vec { + let mut md = i32::MIN; + let mut pc = -1_i32; + let mut pm = -1_i32; + let mut mc = -1; + for i in 0..len1 as usize { + if is_row && !self.row_done[i] || !is_row && !self.col_done[i] { + let mut min1 = i32::MAX; + let mut min2 = min1; + let mut min_p = -1_i32; + for j in 0..len2 as usize { + if is_row && !self.col_done[j] || !is_row && !self.row_done[j] { + let c = if is_row { + self.costs[i][j] + } else { + self.costs[j][i] + }; + if c < min1 { + min2 = min1; + min1 = c; + min_p = j as i32; + } else if c < min2 { + min2 = c; + } + } + } + let diff = min2 - min1; + if diff > md { + md = diff; // max diff + pm = i as i32; // pos of max diff + mc = min1; // min cost + pc = min_p; // pos of min cost + } + } + } + return if is_row { + vec![pm as usize, pc as usize, mc as usize, md as usize] + } else { + vec![pc as usize, pm as usize, mc as usize, md as usize] + }; + } +} + +fn main() { + let mut test = Vogel { + supply: vec![50, 60, 50, 50], + demand: vec![30, 20, 70, 30, 60], + costs: vec![ + vec![16, 16, 13, 22, 17], + vec![14, 14, 13, 19, 15], + vec![19, 19, 20, 23, 50], + vec![50, 12, 50, 15, 11], + ], + n_rows: 4, + n_cols: 5, + row_done: vec![false; 4], + col_done: vec![false; 5], + }; + test.approximate(); +} diff --git a/Task/Vogels-approximation-method/Zig/vogels-approximation-method.zig b/Task/Vogels-approximation-method/Zig/vogels-approximation-method.zig new file mode 100644 index 0000000000..872d05373b --- /dev/null +++ b/Task/Vogels-approximation-method/Zig/vogels-approximation-method.zig @@ -0,0 +1,212 @@ +const std = @import("std"); +const print = std.debug.print; +const ArrayList = std.ArrayList; + +const Vogel = struct { + supply: ArrayList(i32), + demand: ArrayList(i32), + costs: ArrayList(ArrayList(i32)), + n_rows: i32, + n_cols: i32, + row_done: ArrayList(bool), + col_done: ArrayList(bool), + allocator: std.mem.Allocator, + + const Self = @This(); + + pub fn init(allocator: std.mem.Allocator) Self { + return Self{ + .supply = ArrayList(i32).init(allocator), + .demand = ArrayList(i32).init(allocator), + .costs = ArrayList(ArrayList(i32)).init(allocator), + .n_rows = 0, + .n_cols = 0, + .row_done = ArrayList(bool).init(allocator), + .col_done = ArrayList(bool).init(allocator), + .allocator = allocator, + }; + } + + pub fn deinit(self: *Self) void { + self.supply.deinit(); + self.demand.deinit(); + for (self.costs.items) |*row| { + row.deinit(); + } + self.costs.deinit(); + self.row_done.deinit(); + self.col_done.deinit(); + } + + pub fn approximate(self: *Self) !void { + var results = ArrayList(ArrayList(i32)).init(self.allocator); + defer { + for (results.items) |*row| { + row.deinit(); + } + results.deinit(); + } + + // Initialize results matrix + for (0..@intCast(self.n_rows)) |_| { + var row = ArrayList(i32).init(self.allocator); + for (0..@intCast(self.n_cols)) |_| { + try row.append(0); + } + try results.append(row); + } + + var supply_remaining: i32 = 0; + for (self.supply.items) |s| { + supply_remaining += s; + } + + var total_cost: i32 = 0; + + while (supply_remaining > 0) { + const cell = try self.next_cell(); + const r = cell[0]; + const c = cell[1]; + const q = if (self.demand.items[c] < self.supply.items[r]) + self.demand.items[c] + else + self.supply.items[r]; + + self.demand.items[c] -= q; + if (self.demand.items[c] == 0) { + self.col_done.items[c] = true; + } + + self.supply.items[r] -= q; + if (self.supply.items[r] == 0) { + self.row_done.items[r] = true; + } + + results.items[r].items[c] = q; + supply_remaining -= q; + total_cost += q * self.costs.items[r].items[c]; + } + + print(" A B C D E\n", .{}); + for (results.items, 0..) |result, i| { + print("{c}", .{@as(u8, @intCast('W' + i))}); + for (result.items) |item| { + print(" {:>2}", .{item}); + } + print("\n", .{}); + } + print("\nTotal Cost = {}\n", .{total_cost}); + } + + fn next_cell(self: *Self) ![]usize { + const res1 = try self.max_penalty(self.n_rows, self.n_cols, true); + const res2 = try self.max_penalty(self.n_cols, self.n_rows, false); + + if (res1[3] == res2[3]) { + return if (res1[2] < res2[2]) res1 else res2; + } + return if (res1[3] > res2[3]) res2 else res1; + } + + fn max_penalty(self: *Self, len1: i32, len2: i32, is_row: bool) ![]usize { + var md: i32 = std.math.minInt(i32); + var pc: i32 = -1; + var pm: i32 = -1; + var mc: i32 = -1; + + for (0..@intCast(len1)) |i| { + const should_process = if (is_row) + !self.row_done.items[i] + else + !self.col_done.items[i]; + + if (should_process) { + var min1: i32 = std.math.maxInt(i32); + var min2: i32 = min1; + var min_p: i32 = -1; + + for (0..@intCast(len2)) |j| { + const should_process_inner = if (is_row) + !self.col_done.items[j] + else + !self.row_done.items[j]; + + if (should_process_inner) { + const c = if (is_row) + self.costs.items[i].items[j] + else + self.costs.items[j].items[i]; + + if (c < min1) { + min2 = min1; + min1 = c; + min_p = @intCast(j); + } else if (c < min2) { + min2 = c; + } + } + } + + const diff = min2 - min1; + if (diff > md) { + md = diff; + pm = @intCast(i); + mc = min1; + pc = min_p; + } + } + } + + var result = try self.allocator.alloc(usize, 4); + if (is_row) { + result[0] = @intCast(pm); + result[1] = @intCast(pc); + result[2] = @intCast(mc); + result[3] = @intCast(md); + } else { + result[0] = @intCast(pc); + result[1] = @intCast(pm); + result[2] = @intCast(mc); + result[3] = @intCast(md); + } + return result; + } +}; + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + const allocator = gpa.allocator(); + + var my_test = Vogel.init(allocator); + defer my_test.deinit(); + + // Initialize supply + try my_test.supply.appendSlice(&[_]i32{ 50, 60, 50, 50 }); + + // Initialize demand + try my_test.demand.appendSlice(&[_]i32{ 30, 20, 70, 30, 60 }); + + // Initialize costs matrix + const cost_data = [_][]const i32{ + &[_]i32{ 16, 16, 13, 22, 17 }, + &[_]i32{ 14, 14, 13, 19, 15 }, + &[_]i32{ 19, 19, 20, 23, 50 }, + &[_]i32{ 50, 12, 50, 15, 11 }, + }; + + for (cost_data) |row_data| { + var row = ArrayList(i32).init(allocator); + try row.appendSlice(row_data); + try my_test.costs.append(row); + } + + my_test.n_rows = 4; + my_test.n_cols = 5; + + // Initialize row_done and col_done + try my_test.row_done.appendNTimes(false, 4); + try my_test.col_done.appendNTimes(false, 5); + + try my_test.approximate(); +} diff --git a/Task/Voronoi-diagram/Delphi/voronoi-diagram.delphi b/Task/Voronoi-diagram/Delphi/voronoi-diagram.pas similarity index 100% rename from Task/Voronoi-diagram/Delphi/voronoi-diagram.delphi rename to Task/Voronoi-diagram/Delphi/voronoi-diagram.pas diff --git a/Task/Voronoi-diagram/EasyLang/voronoi-diagram.easy b/Task/Voronoi-diagram/EasyLang/voronoi-diagram.easy index dc2b970759..791ccadb21 100644 --- a/Task/Voronoi-diagram/EasyLang/voronoi-diagram.easy +++ b/Task/Voronoi-diagram/EasyLang/voronoi-diagram.easy @@ -3,9 +3,9 @@ func hypo a b . . nsites = 25 for i to nsites - nx[] &= randint 1001 - 1 - ny[] &= randint 1001 - 1 - nc[] &= randint 1000 - 1 + nx[] &= random 0 999 + ny[] &= random 0 999 + nc[] &= random 0 999 . for y = 0 to 1000 for x = 0 to 1000 @@ -17,13 +17,11 @@ for y = 0 to 1000 imin = i . . - color nc[imin] - move x / 10 - 0.05 y / 10 - 0.05 - rect 0.11 0.11 + gcolor nc[imin] + grect x / 10 - 0.05 y / 10 - 0.05 0.11 0.11 . . -color 000 +gcolor 000 for i to nsites - move nx[i] / 10 ny[i] / 10 - circle 0.5 + gcircle nx[i] / 10 ny[i] / 10 0.5 . diff --git a/Task/Voronoi-diagram/Julia/voronoi-diagram-1.julia b/Task/Voronoi-diagram/Julia/voronoi-diagram-1.jl similarity index 100% rename from Task/Voronoi-diagram/Julia/voronoi-diagram-1.julia rename to Task/Voronoi-diagram/Julia/voronoi-diagram-1.jl diff --git a/Task/Voronoi-diagram/Julia/voronoi-diagram-2.julia b/Task/Voronoi-diagram/Julia/voronoi-diagram-2.jl similarity index 100% rename from Task/Voronoi-diagram/Julia/voronoi-diagram-2.julia rename to Task/Voronoi-diagram/Julia/voronoi-diagram-2.jl diff --git a/Task/Voronoi-diagram/Kotlin/voronoi-diagram.kotlin b/Task/Voronoi-diagram/Kotlin/voronoi-diagram.kts similarity index 100% rename from Task/Voronoi-diagram/Kotlin/voronoi-diagram.kotlin rename to Task/Voronoi-diagram/Kotlin/voronoi-diagram.kts diff --git a/Task/Voronoi-diagram/OCaml/voronoi-diagram.ocaml b/Task/Voronoi-diagram/OCaml/voronoi-diagram.ml similarity index 100% rename from Task/Voronoi-diagram/OCaml/voronoi-diagram.ocaml rename to Task/Voronoi-diagram/OCaml/voronoi-diagram.ml diff --git a/Task/Voronoi-diagram/Pluto/voronoi-diagram.pluto b/Task/Voronoi-diagram/Pluto/voronoi-diagram.pluto new file mode 100644 index 0000000000..cc96a68653 --- /dev/null +++ b/Task/Voronoi-diagram/Pluto/voronoi-diagram.pluto @@ -0,0 +1,42 @@ +require "bitmap" + +local rand = math.random +local distsq = bitmap.distanceSquared + +local function clamp(v, size) + size -= 1 + if v < 2 then return v + 2 end + if v > size - 2 then return size - 2 end + return v +end + +local function voronoi(bmp, cells, size) + local px = {} + local py = {} + local cl = {} + for i = 1, cells do + px[i] = rand(0, size - 1) + py[i] = rand(0, size - 1) + cl[i] = bitmap.rgbColor(rand(0, 255), rand(0, 255), rand(0, 255)) + end + for x = 0, size - 1 do + for y = 0, size - 1 do + local n = 1 + for i = 1, cells do + if distsq(px[i], py[i], x, y) < distsq(px[n], py[n], x, y) then + n = i + end + end + bmp:set(x, y, cl[n]) + end + end + for i = 1, cells do + bmp:circle(clamp(px[i], size), clamp(py[i], size), 1, color.black) + end +end + +local cells = 70 +local size = 700 +local bmp = bitmap.of(size, size, color.black, "Voronoi_diagram") +voronoi(bmp, cells, size) +bmp:view() diff --git a/Task/Voronoi-diagram/ReScript/voronoi-diagram.re b/Task/Voronoi-diagram/ReScript/voronoi-diagram.res similarity index 100% rename from Task/Voronoi-diagram/ReScript/voronoi-diagram.re rename to Task/Voronoi-diagram/ReScript/voronoi-diagram.res diff --git a/Task/Voronoi-diagram/Rust/voronoi-diagram.rust b/Task/Voronoi-diagram/Rust/voronoi-diagram.rs similarity index 100% rename from Task/Voronoi-diagram/Rust/voronoi-diagram.rust rename to Task/Voronoi-diagram/Rust/voronoi-diagram.rs diff --git a/Task/Voronoi-diagram/Uiua/voronoi-diagram.uiua b/Task/Voronoi-diagram/Uiua/voronoi-diagram.uiua new file mode 100644 index 0000000000..4a09efa4a6 --- /dev/null +++ b/Task/Voronoi-diagram/Uiua/voronoi-diagram.uiua @@ -0,0 +1,7 @@ +N ← 50 +Cs ← ≡°hsv⍥(÷10˜⊂8_8×60⚂)300 # Generate some colours. +↯∞_2⍥⟜(⌊×⚂)×2N⟜∘300 # N random centres in grid. +⊃⊙∘∘ # Copy centres for later. +≡(˜⨂⊸/↧√≡/+ⁿ2˜-⊙¤)¤⊙(♭₂˙⊞⊟⇡) # Find nearest centres. +↯⇌[3 ⟜∘ ∘]√⊸⧻≡⌞˜⊡Cs # Colour grid. +˜∧⍜⊡⋅1_1_1 # Add in centres. diff --git a/Task/Wagstaff-primes/ALGOL-W/wagstaff-primes.alg b/Task/Wagstaff-primes/ALGOL-W/wagstaff-primes.alg index 0c0fe00da3..7e12e0c72a 100644 --- a/Task/Wagstaff-primes/ALGOL-W/wagstaff-primes.alg +++ b/Task/Wagstaff-primes/ALGOL-W/wagstaff-primes.alg @@ -19,63 +19,35 @@ begin % find some Wagstaff primes: primes of the form ( 2^p + 1 ) / 3 % q = 0 end divides ; - % prints v as a 14 digit integer number % - procedure printI14( long real value v ) ; - begin - integer iv; - long real r; - r := abs( v ); - if v < 0 then writeon( s_w := 0, "-" ); - iv := truncate( r / 1000000 ); - if iv < 1 then begin - writeon( i_w := 8, s_w := 0, " ", truncate( r ) ) - end - else begin - string(6) sValue; - writeon( i_w := 8, s_w := 0, iv ); - iv := truncate( abs( r ) - ( iv * 1000000.0 ) ); - for sPos := 5 step -1 until 0 do begin - sValue( sPos // 1 ) := code( ( iv rem 10 ) + decode( "0" ) ); - iv := iv div 10 - end for_sPos; - writeon( s_w := 0, sValue ) - end if_iv_lt_1__ - end printI ; - wCount := 0; % find the Wagstaff primes using long reals to hold the numbers, which % % accurately represent integers up to 2^53, so only consider primes < 53 % for p := 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47 do begin - long real w, powerOfTwo; - logical isPrime; - powerOfTwo := 1; - for i := 1 until p do powerOfTwo := powerOfTwo * 2; - w := ( powerOfTwo + 1 ) / 3; - isPrime := not divides( 2, w ); - if isPrime then begin - integer f, toNext; - long real f2; - f := 3; - f2 := 9; - toNext := 16; - while isPrime and f2 <= w do begin - isPrime := not divides( f, w ); - f := f + 2; - f2 := f2 + toNext; - toNext := toNext + 8 - end while_isPrime_and_f2_le_x - end if_isPrime ; - if isPrime then begin - wCount := wCount + 1; - write( i_w := 3, s_w := 0, wCount, ": ", p, " " ); - if p >= 32 then printI14( w ) - else begin - integer iw; - iw := truncate( w ); - writeon( i_w := 14, s_w := 0, iw ) - end of_p_ge_32__ ; - if wCount >= 10 then goto done % stop at 10 Wagstaff primes % - end if_isPrime + if wCount < 10 then begin + long real w, powerOfTwo; + logical isPrime; + powerOfTwo := 1; + for i := 1 until p do powerOfTwo := powerOfTwo * 2; + w := ( powerOfTwo + 1 ) / 3; + isPrime := not divides( 2, w ); + if isPrime then begin + integer f, toNext; + long real f2; + f := 3; + f2 := 9; + toNext := 16; + while isPrime and f2 <= w do begin + isPrime := not divides( f, w ); + f := f + 2; + f2 := f2 + toNext; + toNext := toNext + 8 + end while_isPrime_and_f2_le_x + end if_isPrime ; + if isPrime then begin + wCount := wCount + 1; + write( i_w := 3, s_w := 0, wCount, ": ", p, " " ); + writeon( r_format := "A", r_w := 14, r_d := 0, s_w := 0, w ) + end if_isPrime + end if_wCount_lt_10 end for_p ; -done: end. diff --git a/Task/Wagstaff-primes/AWK/wagstaff-primes.awk b/Task/Wagstaff-primes/AWK/wagstaff-primes.awk new file mode 100644 index 0000000000..d938dbc045 --- /dev/null +++ b/Task/Wagstaff-primes/AWK/wagstaff-primes.awk @@ -0,0 +1,25 @@ +# syntax: GAWK -f WAGSTAFF_PRIMES.AWK +BEGIN { + p = 1 + while (count < 10) { + p += 2 + if (is_prime(p)) { + w = (2^p+1) / 3 + if (is_prime(w)) { + printf("%2d: %3d %14d\n",++count,p,w) + } + } + } + exit(0) +} +function is_prime(x, i) { + if (x <= 1) { + return(0) + } + for (i=2; i<=int(sqrt(x)); i++) { + if (x % i == 0) { + return(0) + } + } + return(1) +} diff --git a/Task/Wagstaff-primes/Ada/wagstaff-primes.adb b/Task/Wagstaff-primes/Ada/wagstaff-primes.adb new file mode 100644 index 0000000000..92d3590f3a --- /dev/null +++ b/Task/Wagstaff-primes/Ada/wagstaff-primes.adb @@ -0,0 +1,34 @@ +with Ada.Text_IO; use Ada.Text_IO; + +with Unbounded_Unsigneds; use Unbounded_Unsigneds; +with Unbounded_Unsigneds.Primes; use Unbounded_Unsigneds.Primes; + +with Strings_Edit.Unbounded_Unsigned_Edit; +use Strings_Edit.Unbounded_Unsigned_Edit; + +procedure Wagstaff is + M : Unbounded_Unsigned; + Count : Integer := 16; + + procedure Check (P : Half_Word) is + begin + if Is_Prime (P) = Prime then + M := (Power_Of_Two (Bit_Count (P)) + 1) / 3; + if Is_Prime (M, 10) = Prime then + Count := Count - 1; + Put_Line + ( "p =" & Half_Word'Image (P) & Character'Val (9) + & " m = " & Image (M) + ); + end if; + end if; + end Check; +begin + Check (3); + for N in Half_Word range 1..Half_Word'Last loop + Check (N * 6 - 1); + exit when Count <= 0; + Check (N * 6 + 1); + exit when Count <= 0; + end loop; +end Wagstaff; diff --git a/Task/Wagstaff-primes/Agena/wagstaff-primes.agena b/Task/Wagstaff-primes/Agena/wagstaff-primes.agena new file mode 100644 index 0000000000..b92fb35357 --- /dev/null +++ b/Task/Wagstaff-primes/Agena/wagstaff-primes.agena @@ -0,0 +1,36 @@ +scope # find some Wagstaff primes: primes of the form ( 2^p + 1 ) / 3 + # where p is an odd prime + local constant maxWagstaff := 10; # number of Wagstaff primes to find + local constant sieveSize := 200; # hopefully, enough primes... + create register primes( sieveSize ); # "vector" to be sieved + scope # sieve the primes up to sieveMax + primes[ 1 ] := false; + for sPos from 2 to sieveSize do primes[ sPos ] := true od; + for sPos from 2 to entier( sqrt( sieveSize ) ) do + if primes[ sPos ] then + for p from sPos * sPos to sieveSize by sPos do + primes[ p ] := false + od + fi + od + end; + scope # attempt to find the Wagstaff primes + local powerOf2 := 2; # 2^1 + local wCount := 0; # number of Wagstaff primes found so far + for p from 3 by 2 while wCount < maxWagstaff do + powerOf2 *:= 4; + if primes[ p ] then + local w, isPrime := ( powerOf2 + 1 ) \ 3, true; + # check w is prime - trial division + for n from 3 by 2 while n * n <= w and isPrime do + isPrime := w mod n <> 0; + od; + if isPrime then # have another Wagstaff prime + wCount +:= 1; + # have to use %f to print w as it could be > 2^32 + printf( "%2d: %4d: %16.0f\n", wCount, p, w ) + fi + fi + od + end +end diff --git a/Task/Wagstaff-primes/Crystal/wagstaff-primes.cr b/Task/Wagstaff-primes/Crystal/wagstaff-primes.cr new file mode 100644 index 0000000000..e941f07daf --- /dev/null +++ b/Task/Wagstaff-primes/Crystal/wagstaff-primes.cr @@ -0,0 +1,22 @@ +struct Int + def prime? # P3 Prime Generator primality test + return self | 1 == 3 if self < 5 + return false if self.gcd(6) != 1 + sqrt_n = Math.isqrt(self) + pc = typeof(self).new(5) + while pc <= sqrt_n + return false if self % pc == 0 || self % (pc + 2) == 0 + pc += 6 + end + true + end +end + +(3i64..).each.compact_map {|p| + if p.prime? + w = (2i64**p + 1) // 3 + { p, w } if w.prime? + end +}.first(10).each do |p, w| + printf "%3d: %d\n", p, w +end diff --git a/Task/Wagstaff-primes/Delphi/wagstaff-primes.delphi b/Task/Wagstaff-primes/Delphi/wagstaff-primes.pas similarity index 100% rename from Task/Wagstaff-primes/Delphi/wagstaff-primes.delphi rename to Task/Wagstaff-primes/Delphi/wagstaff-primes.pas diff --git a/Task/Wagstaff-primes/EasyLang/wagstaff-primes.easy b/Task/Wagstaff-primes/EasyLang/wagstaff-primes.easy index c334acb4e8..f477b5be42 100644 --- a/Task/Wagstaff-primes/EasyLang/wagstaff-primes.easy +++ b/Task/Wagstaff-primes/EasyLang/wagstaff-primes.easy @@ -1,22 +1,18 @@ -func prime n . - if n mod 2 = 0 and n > 2 - return 0 - . - i = 3 +fastfunc isprim n . + if n < 2 : return 0 + i = 2 while i <= sqrt n - if n mod i = 0 - return 0 - . - i += 2 + if n mod i = 0 : return 0 + i += 1 . return 1 . pri = 1 while nwag <> 10 pri += 2 - if prime pri = 1 + if isprim pri = 1 wag = (pow 2 pri + 1) / 3 - if prime wag = 1 + if isprim wag = 1 nwag += 1 print pri & " => " & wag . diff --git a/Task/Wagstaff-primes/FutureBasic/wagstaff-primes.basic b/Task/Wagstaff-primes/FutureBasic/wagstaff-primes.basic new file mode 100644 index 0000000000..793ad7b4d3 --- /dev/null +++ b/Task/Wagstaff-primes/FutureBasic/wagstaff-primes.basic @@ -0,0 +1,149 @@ +// ----------------------------------------------- +// Wagstaff primes +// Using FutureBasic 7.0.36 +// +// November 2025, R.W +// +// ----------------------------------------------- + +include "gmp.incl" + +_kPrimeReps = 25 +_kNeedFirst = 10 +_kNeedMore = 14 + +// mpz_sizeinbase sometimes would return one digit too many especially +// when the value is close to the edge of power of 10. This helper +// accounts for that and adjusts. + +local fn mpz_digits10( z as mpz_t ) as int + int d + mpz_t pow10 + d = fn mpz_sizeinbase( z, 10 ) + if d <= 1 then RETURN d + mpz_init( pow10 ) + // pow10 = 10^(d-1) + fn mpz_ui_pow_ui( pow10, 10, d - 1 ) + // If z < 10^(d-1) then mpz_sizeinbase returned one too many + if fn mpz_cmp( z, pow10 ) < 0 then d = d - 1 //if so -> decrement + mpz_clear( pow10 ) +end fn = d + +local fn IsSmallPrime( n as UInt32 ) as boolean + if n < 2 then RETURN _false + if n = 2 then RETURN _true + if (n AND 1) == 0 then RETURN _false + mpz_t t + mpz_init( t ) + fn mpz_set_ui( t, n ) + int r : r = fn mpz_probab_prime_p( t, _kPrimeReps ) + mpz_clear( t ) + if r > 0 then RETURN _true +end fn = _false + +// Find the next upstream prime + +local fn NextPrimeAfter( startN as UInt32 ) as UInt32 + UInt32 p + if startN < 2 then RETURN 2 + p = startN + 1 + if (p AND 1) = 0 then p = p + 1 + while _true + if fn IsSmallPrime( p ) then RETURN p + p = p + 2 + wend +end fn = 0 + +// Abbreviate long strings + +local fn AbbrevLongStr( longStr as CFStringRef ) as CFStringRef + CFStringRef outStr, leftStr,rightStr + CFIndex strlen + outStr = @"" + strlen = len(longStr) + if strlen < 60 then return longStr + leftStr = left(longStr, 27 ) + rightStr = right(longStr, 28 ) + outStr = concat( leftStr, @"...", rightStr) +end fn = outStr + +// WagStaff_P = (2^p + 1) / 3 → outW + +local fn WagstaffFromExponent( p as UInt32, outW as mpz_t ) as boolean + mpz_t N + mpz_init( N ) + fn mpz_ui_pow_ui( N, 2, p ) + fn mpz_add_ui( N, N, 1 ) + unsigned long remd + remd = fn mpz_fdiv_q_ui( outW, N, 3 ) + mpz_clear( N ) + if remd != 0 then RETURN _false +end fn = _true + +// Use GMP probable prime function with 25 reps +// sufficient to determine a large prime + +local fn IsWagstaffPrime( p as UInt32, outW as mpz_t ) as boolean + if fn WagstaffFromExponent( p, outW ) = _false then RETURN _false + int res : res = fn mpz_probab_prime_p( outW, _kPrimeReps ) + // 0 = composite, 1 = probable, 3 = positive + if res > 0 then RETURN _true +end fn = _false + +// MAIN +// +local fn Main + UInt32 p + UInt32 foundFirst, foundMore + foundFirst = 0 : foundMore = 0 + CFStringRef s2 + + CFTimeInterval t0, t1 + t0 = fn CACurrentMediaTime + + // Rosetta requirement for 10 Wagstaff primes + print @"First 10 Wagstaff primes:\n" + p = fn NextPrimeAfter( 1 ) + while foundFirst < _kNeedFirst + mpz_t W + mpz_init( W ) + if fn IsWagstaffPrime( p, W ) + foundFirst = foundFirst + 1 + // FB has a handy wrapper to obtain CFString from mpz_t output + // toolbox fn mpz_cf2( mpz_t op ) = CFStringRef // mpz_t → CFString (base 10) + CFStringRef s = fn mpz_cf2( W ) + printf @"%4lu: %@", p,s + end if + mpz_clear( W ) + p = fn NextPrimeAfter( p ) + wend + t1 = fn CACurrentMediaTime + printf @"\nElapsed time: %.3f ms\n\n", (t1 - t0) * 1000.0 + + // Rosetta additional task + + print @"Wagstaff next 14:\n" + + CFTimeInterval t2 = fn CACurrentMediaTime + foundMore = 0 + while foundMore < _kNeedMore + mpz_t W2 + mpz_init( W2 ) + if fn IsWagstaffPrime( p, W2 ) + foundMore = foundMore + 1 + int digits : digits = fn mpz_digits10( W2 ) + s2 = fn mpz_cf2( W2 ) //mpz_cf2 is an FB wrapper + s2 = fn AbbrevLongStr(s2) + printf @"%4lu: %@ (%d digits)", p, s2, digits + end if + mpz_clear( W2 ) + p = fn NextPrimeAfter( p ) + wend + + CFTimeInterval t3 = fn CACurrentMediaTime + printf @"\nElapsed time: %.3f secs\n", (t3 - t2) +end fn + +Window 1,@"Wagstaff Primes",(0,0,640,540) +fn Main +HandleEvents diff --git a/Task/Wagstaff-primes/Julia/wagstaff-primes.julia b/Task/Wagstaff-primes/Julia/wagstaff-primes.jl similarity index 100% rename from Task/Wagstaff-primes/Julia/wagstaff-primes.julia rename to Task/Wagstaff-primes/Julia/wagstaff-primes.jl diff --git a/Task/Wagstaff-primes/Lua/wagstaff-primes.lua b/Task/Wagstaff-primes/Lua/wagstaff-primes.lua new file mode 100644 index 0000000000..cd4b7c668f --- /dev/null +++ b/Task/Wagstaff-primes/Lua/wagstaff-primes.lua @@ -0,0 +1,38 @@ +do -- find some Wagstaff primes primes of the form ( 2^p + 1 ) / 3 + -- where p is an odd prime + + local maxWagstaff = 10 -- number of Wagstaff primes to find + local sieveSize = 200 -- hopefully, enough primes... + local primes = {} + do -- sieve the primes up to sieveMax + primes[ 1 ] = false + for sPos = 2, sieveSize do primes[ sPos ] = true end + for sPos = 2, math.floor( math.sqrt( sieveSize ) ) do + if primes[ sPos ] then + for p = sPos * sPos, sieveSize, sPos do + primes[ p ] = false + end + end + end + end + do -- attempt to find the Wagstaff primes + local powerOf2 = 2 -- 2^1 + local wCount = 0 -- number of Wagstaff primes found so far + for p = 3, sieveSize, 2 do + if wCount >= maxWagstaff then break end + powerOf2 = powerOf2 * 4 + if primes[ p ] then + local w, isPrime = ( powerOf2 + 1 ) // 3, true + -- check w is prime - trial division + for n = 3, w, 2 do + if n * n > w or not isPrime then break end + isPrime = w % n ~= 0 + end + if isPrime then -- have another Wagstaff prime + wCount = wCount + 1 + io.write( string.format( "%2d %4d: %16d\n", wCount, p, w ) ) + end + end + end + end +end diff --git a/Task/Wagstaff-primes/Mathematica/wagstaff-primes.math b/Task/Wagstaff-primes/Mathematica/wagstaff-primes.math new file mode 100644 index 0000000000..bb2d0c20ec --- /dev/null +++ b/Task/Wagstaff-primes/Mathematica/wagstaff-primes.math @@ -0,0 +1,40 @@ +wagstaffPair[p_Integer] := Module[{m}, + If[Not[OddQ[p]], Return[{False, Null}]]; + If[Not[PrimeQ[p]], Return[{False, Null}]]; + + m = Quotient[2^p + 1, 3]; + + If[Not[PrimeQ[m]], Return[{False, Null}]]; + + {True, m} + ] + +findNWagstaffPairs[n_Integer] := Module[{pairs = {}, count = 0, i = 2}, + While[count < n, + With[{result = wagstaffPair[i]}, + If[First[result], + AppendTo[pairs, {i, Last[result]}]; + count++ + ] + ]; + i++ + ]; + pairs + ] + +printlnWagstaff[pair_, maxDigitDisplay_: 20] := Module[{p, m, mStr, uMiddle, lMiddle}, + {p, m} = pair; + mStr = ToString[m]; + + If[StringLength[mStr] > maxDigitDisplay, + uMiddle = Ceiling[maxDigitDisplay/2]; + lMiddle = Floor[maxDigitDisplay/2]; + mStr = StringJoin[{StringTake[mStr, uMiddle], "...", + StringTake[mStr, {-lMiddle}], " (", ToString[StringLength[mStr]], + " digits)"}] + ]; + + Print["p = ", p, ", m = ", mStr] + ] + +Map[printlnWagstaff, findNWagstaffPairs[24]]; diff --git a/Task/Wagstaff-primes/Maxima/wagstaff-primes.maxima b/Task/Wagstaff-primes/Maxima/wagstaff-primes.maxima new file mode 100644 index 0000000000..fb1fb9fb2b --- /dev/null +++ b/Task/Wagstaff-primes/Maxima/wagstaff-primes.maxima @@ -0,0 +1,11 @@ +block( + p: 3, count: 0, while count < 10 do( + m: (2^p+1)/3, + if primep(m) then block( + sprint("p =", p, "m =", m), + newline(), + count: count+1 + ), + p: next_prime(p) + ) +)$ diff --git a/Task/Wagstaff-primes/OCaml/wagstaff-primes.ocaml b/Task/Wagstaff-primes/OCaml/wagstaff-primes.ml similarity index 100% rename from Task/Wagstaff-primes/OCaml/wagstaff-primes.ocaml rename to Task/Wagstaff-primes/OCaml/wagstaff-primes.ml diff --git a/Task/Wagstaff-primes/Phix/wagstaff-primes-1.phix b/Task/Wagstaff-primes/Phix/wagstaff-primes-1.phix new file mode 100644 index 0000000000..77dd80f28c --- /dev/null +++ b/Task/Wagstaff-primes/Phix/wagstaff-primes-1.phix @@ -0,0 +1,49 @@ +with javascript_semantics +atom t0 = time() +include mpfr.e + +function isWagstaff(integer p) + mpz w = mpz_init() + mpz_ui_pow_ui(w,2,p) + mpz_add_si(w,w,1) + assert(mpz_fdiv_q_ui(w,w,3)=0) + return iff(mpz_prime(w)?w:NULL) +end function + +integer p, pdx = 2, extra = 0 +sequence wagstaff = {} +while length(wagstaff)<10 do + p = get_prime(pdx) + atom res = isWagstaff(p) + if res then + string s = mpz_get_str(res,comma_fill:=true) + wagstaff &= {{p,s}} + end if + pdx += 1 +end while +printf(1,"First 10 Wagstaff primes for the values of 'p' shown:\n") +papply(true,printf,{1,{"%2d: %s\n"},wagstaff}) +printf(1,"\nTook %s\n\n",elapsed(time()-t0)) + +printf(1,"Wagstaff primes that we can find in 6 seconds:\n") +while time()> p */ + mpz_sub(s,low,high) /* s:=low-high (gives reduction mod (2^p+1)) */ + /* normalize s to 0..modulus-1 (a single add/subtract suffices) */ + if mpz_sign(s)<0 then + mpz_add(s,s,modulus) + elsif mpz_cmp(s,modulus)>=0 then + mpz_sub(s,s,modulus) + end if + end for + /* check s==25 (mod modulus) ie s is 25 in canonical rep 0..modulus-1 */ + is_ok = (mpz_cmp_si(s,25)==0) + {s,low,high,modulus} = mpz_free({s,low,high,modulus}) + end if + if is_ok then + mpz w = mpz_init() + mpz_ui_pow_ui(w,2,p) + mpz_add_si(w,w,1) + assert(mpz_fdiv_q_ui(w,w,3)=0) + return w + end if + return NULL +end function + +integer p, pdx = 2, count = 0 +printf(1,"Some Wagstaff primes:\n") +--while count<30 do +while count<29 do + p = get_prime(pdx) + atom res = wprp(p) + if res then + count += 1 + string th = ord(count) + if count<=10 then + string s = mpz_get_str(res,comma_fill:=true) + printf(1,"The %2d%s is %5d: %s\n",{count,th,p,s}) + else + integer l = mpz_sizeinbase(res,10) + string e = elapsed(time()-t0,0.2,", %s") + printf(1,"The %d%s is %5d (%,d digits%s)\n",{count,th,p,l,e}) + end if + elsif time()>t1 then +-- progress("%d (%.2f%%)\r",{p,p/42737*100}) + progress("%d (%.2f%%)\r",{p,p/14479*100}) + t1 = time()+1 + end if + pdx += 1 +end while diff --git a/Task/Wagstaff-primes/Phix/wagstaff-primes.phix b/Task/Wagstaff-primes/Phix/wagstaff-primes.phix deleted file mode 100644 index 43d164329c..0000000000 --- a/Task/Wagstaff-primes/Phix/wagstaff-primes.phix +++ /dev/null @@ -1,35 +0,0 @@ -(phixonline)--> - with javascript_semantics - atom t0 = time() - include mpfr.e - - function isWagstaff(integer p, bool bLenOnly=false) - mpz w = mpz_init() - mpz_ui_pow_ui(w,2,p) - mpz_add_si(w,w,1) - assert(mpz_fdiv_q_ui(w,w,3)=0) - return iff(mpz_prime(w)?iff(bLenOnly?mpz_sizeinbase(w,10):mpz_get_str(w,comma_fill:=true)):"") - end function - - integer p, pdx = 2 - sequence wagstaff = {} - while length(wagstaff)<10 do - p = get_prime(pdx) - string res = isWagstaff(p) - if length(res) then wagstaff &= {{p,res}} end if - pdx += 1 - end while - printf(1,"First 10 Wagstaff primes for the values of 'p' shown:\n") - papply(true,printf,{1,{"%2d: %s\n"},wagstaff}) - printf(1,"\nTook %s\n\n",elapsed(time()-t0)) - - printf(1,"Wagstaff primes that we can find in 5 seconds:\n") - while time()<t0+5 do - p = get_prime(pdx) - object res = isWagstaff(p,true) - if integer(res) then - printf(1,"%5d (%,d digits, %s)\n", {p,res,elapsed(time()-t0)}) - end if - pdx += 1 - end while - 1] + [32] AD S94#@ [acc := h{i} - (current maximum)] + G39@ [skip if h{i} < max] + A94#@ [restore acc after test] + T94#@ [update value of maximum] + A32@ T93@ [update A order for maximum] + [39] T4F [clear acc] + A32@ S65@ [have we just done h{n-1}?] + G28@ [loop back if not] +[Fill troughs from the left. Here with acc = 0.] + [43] AD [(planted) read h{0}] + T94#@ [initialize level to h{0}] + A49@ [acc := A order for h{1}] + S93@ [subtract A order for maximum] + E64@ [skip if maximum is at h{0} or h{1}] + [Start of loop] + [48] T4F [clear acc] + [49] AD [read h{i}; initially i = 1] + S94#@ [subtract current level] + G55@ [skip if h{i} < level] + A94#@ [restore acc after test] + T94#@ [update level] + E59@ [join common code] + [55] T4D [temp store h{i} - h_max, which is < 0] + AD [acc := result so far] + S4D [add h_max - h{i} to result] + TD [update result] + [59] A49@ A92@ U49@ [make A order for h{i+1}] + S93@ [have we reached the highest tower yet?] + G48@ [if not, loop back] +[Fill troughs from the right. + Similar to filling from the left, so given in condensed form to save space.] + [64] T4F + [65] AF T94#@ A93@ S71@ E87@ + [70] T4F + [71] AF S94#@ G77@ A94#@ T94#@ E81@ + [77] T4D AD S4D TD + [81] A71@ S92@ T71@ A93@ S71@ G70@ +[Exit from subroutine] + [87] T4F [clear acc on exit, as usual] + [88] ZF [(planted) jump back to caller] +[Constants] + [89] U3F + [90] U1F [subtract to convert E order to A order] + [91] AD + [92] P2F [2 in address field] +[Variables: Swap if necessary to get 35-bit variable at even address] + [93] AF [order to read h_max] + [94] PF PF [current maximum height] +[-----------------------------------------------------------------------] +[Main routine: must be at even address] + E25K TM GK + [0] PF PF [store for 35-bit height] + [2] PF [data count] + [3] P2F [to change address by 2] + [4] #F [figure shift] + [5] K2048F [letter shift] + [6] DF [7] IF [8] YF [letters D I Y] + [9] NF [comma (in figures mode)] + [10] @F [carriage return] + [11] &F [line feed] + [12] !F [space] + [13] K4096F [teleprinter null] +[Entry] + [14] O4@ [set figures] +[Loop over datasets] + [15] A15@ GH [call library subroutine R4, sets 0D := data count N] + SD E63@ [exit if N = 0] + T4F [clear acc] + A23@ T40@ [initialize T order to store data] + AD [load data count, 35-bit but with high half = 0] + [23] T#& [store at start of data] + [24] S& [acc := 17-bit negative data count; also letter S] + [25] LD [shift to address field; also letter L] + G28@ [don't print comma before first height] +[Loop over heights in current dataset] + [27] O9@ [print comma] + [28] T2@ [update negative loop counter] + A40@ A3@ T40@ [inc address for next 35-bit height] + A32@ GH [read next height to 0D (clears acc)] + AD T#@ [acc := height, save locally] + A36@ GN !1F [print height, min width = 1] + A#@ [retrieve height] + [40] TD [(planted) store height in array] + A2@ A2F [inc negative loop counter] + G27@ [if not yet 0, loop back] + A44@ GL P& [call subroutine returns amount of water in 0D] + [Print ' YIELDS ' (requires temporary change to letters shift)] + O5@ O12@ O8@ O7@ O62@ + O25@ O6@ O24@ O12@ O4@ + A57@ GN !1F [print result, min width = 1; leaves acc = 0] + O10@ O11@ [print CR, LF] + [62] E15@ [loop back for next data set; also letter E] +[Jump to here if data count = 0, means end of data] + [63] O13@ [print null to flush teleprinter buffer] + ZF [stop the machine] +[------------------------------------------------------------------------------- + Library subroutine R4. + Input of one signed integer, returned in 0D.] + E25K TH + GKA3FT21@T4DH6@E11@P5DJFT6FVDL4FA4DTDI4FA4FS5@G7@S5@G20@SDTDT6FEF +[------------------------------------------------------------------------------- + Modification of library subroutine P7; prints integer N in range 0 <= N < 10^10. + Prints 0 correctly, and allows caller to specify a minimum width. + Input : 0D = integer (not preserved) + 17-bit print control word follows subroutine call, + e.g. !5F means minimum width 5, pad on left with space. + 49 locations; even address; workspace: 0F, 1F, 4D, 6F, 7F] + E25K TN + GKA48@U4@A27@T35@AFU4@L256FS45@T7FH46#@NDYFLDT4DS45@T1FH21@ + S21@A45@G21@U4@TFV4DA1FG36@S1FLDU1FO1FF1FS1FL4FT4DAFG18@ZF + S1FL8FT4DAFA7FG43@O4@T6FE33@T46#ZPFT45ZP1024FP610D@524DP2F +[--------------------------------------------------------------------------------] +[M parameter (main routine) again] + E25K TM GK + E14Z [define entry point] + PF [acc = 0 on entry] +[--------------------------------------------------------------------------------] +[Counts and data values to be read by library subroutine R4. + Note sign comes _after_ value.] +5+ 1+5+3+7+2+ +10+ 5+3+7+2+6+4+5+9+1+2+ +16+ 2+6+3+5+2+8+1+4+2+2+5+3+5+7+4+1+ +4+ 5+5+5+5+ +4+ 5+6+7+8+ +4+ 8+7+7+6+ +5+ 6+7+10+7+6+ +0+ diff --git a/Task/Water-collected-between-towers/EasyLang/water-collected-between-towers.easy b/Task/Water-collected-between-towers/EasyLang/water-collected-between-towers.easy index f46f7dcf15..71937aa4de 100644 --- a/Task/Water-collected-between-towers/EasyLang/water-collected-between-towers.easy +++ b/Task/Water-collected-between-towers/EasyLang/water-collected-between-towers.easy @@ -1,4 +1,4 @@ -proc water h[] . . +func water h[] . n = len h[] len left[] n len right[] n @@ -12,14 +12,14 @@ proc water h[] . . right[i] = max . for i = 1 to n - sum += (lower left[i] right[i]) - h[i] + sum += lower left[i] right[i] - h[i] . - print sum + return sum . repeat s$ = input until s$ = "" - water number strsplit s$ " " + print water number strsplit s$ " " . # input_data diff --git a/Task/Water-collected-between-towers/Gleam/water-collected-between-towers.gleam b/Task/Water-collected-between-towers/Gleam/water-collected-between-towers.gleam new file mode 100644 index 0000000000..ef8d698e90 --- /dev/null +++ b/Task/Water-collected-between-towers/Gleam/water-collected-between-towers.gleam @@ -0,0 +1,28 @@ +import gleam/int +import gleam/io +import gleam/list + +pub fn main() { + let cases = [ + [1, 5, 3, 7, 2], + [5, 3, 7, 2, 6, 4, 5, 9, 1, 2], + [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1], + [5, 5, 5, 5], + [5, 6, 7, 8], + [8, 7, 7, 6], + [6, 7, 10, 7, 6], + ] + use towers <- list.each(cases) + towers |> water_area |> int.to_string |> io.println +} + +pub fn water_area(towers: List(Int)) -> Int { + towers + |> list.scan(0, int.max) + |> list.map2( + towers |> list.reverse |> list.scan(0, int.max) |> list.reverse, + int.min, + ) + |> list.map2(towers, int.subtract) + |> int.sum +} diff --git a/Task/Water-collected-between-towers/Julia/water-collected-between-towers.julia b/Task/Water-collected-between-towers/Julia/water-collected-between-towers.jl similarity index 100% rename from Task/Water-collected-between-towers/Julia/water-collected-between-towers.julia rename to Task/Water-collected-between-towers/Julia/water-collected-between-towers.jl diff --git a/Task/Water-collected-between-towers/Kotlin/water-collected-between-towers.kotlin b/Task/Water-collected-between-towers/Kotlin/water-collected-between-towers.kts similarity index 100% rename from Task/Water-collected-between-towers/Kotlin/water-collected-between-towers.kotlin rename to Task/Water-collected-between-towers/Kotlin/water-collected-between-towers.kts diff --git a/Task/Water-collected-between-towers/PHP/water-collected-between-towers.php b/Task/Water-collected-between-towers/PHP/water-collected-between-towers.php new file mode 100644 index 0000000000..5e62a76be4 --- /dev/null +++ b/Task/Water-collected-between-towers/PHP/water-collected-between-towers.php @@ -0,0 +1,60 @@ + $build[$i][$j]) { + $l = max($l, $build[$i][$k]); + } + } + for ($k = $j + 1; $k < count($build[$i]); $k++) { + if ($build[$i][$k] > $build[$i][$j]) { + $r = max($r, $build[$i][$k]); + } + } + if ($l > 0 && $r > 0) { + $w = min($l, $r) - $build[$i][$j]; + $level[$j] = $w; + } + } + +// Report + echo '
    ';
    +	$max = max($build[$i]);
    +	$u = 0;
    +	for ($j = $max; $j > 0; $j--) {
    +		for ($k = 0; $k < count($build[$i]); $k++) {
    +			if ($j - 1 < $build[$i][$k]) {
    +				echo $tower;
    +			}
    +			elseif (!empty($level[$k]) && $level[$k] + $build[$i][$k] >= $j) {
    +				echo $water;
    +				$u++;
    +			}
    +			elseif ($build[$i][$k] < $j) {
    +				echo $empty;
    +			}
    +		}
    +		echo '
    '; + } + echo '
    Block ' . $i + 1 . ' will collect ' . $u . ' units of water
    '; + echo '
    '; +} +?> diff --git a/Task/Water-collected-between-towers/Phix/water-collected-between-towers-1.phix b/Task/Water-collected-between-towers/Phix/water-collected-between-towers-1.phix index a1de1cce90..b6ce66cc52 100644 --- a/Task/Water-collected-between-towers/Phix/water-collected-between-towers-1.phix +++ b/Task/Water-collected-between-towers/Phix/water-collected-between-towers-1.phix @@ -1,26 +1,24 @@ -(phixonline)--> - with javascript_semantics - function collect_water(sequence heights) - integer res = 0 - for i=2 to length(heights)-1 do - integer lm = max(heights[1..i-1]), - rm = max(heights[i+1..$]), - d = min(lm,rm)-heights[i] - res += max(0,d) - end for - return res - end function +with javascript_semantics +function collect_water(sequence heights) + integer res = 0 + for i=2 to length(heights)-1 do + integer lm = max(heights[1..i-1]), + rm = max(heights[i+1..$]), + d = min(lm,rm)-heights[i] + res += max(0,d) + end for + return res +end function - constant tests = {{1,5,3,7,2}, - {5,3,7,2,6,4,5,9,1,2}, - {2,6,3,5,2,8,1,4,2,2,5,3,5,7,4,1}, - {5,5,5,5}, - {5,6,7,8}, - {8,7,7,6}, - {6,7,10,7,6}} +constant tests = {{1,5,3,7,2}, + {5,3,7,2,6,4,5,9,1,2}, + {2,6,3,5,2,8,1,4,2,2,5,3,5,7,4,1}, + {5,5,5,5}, + {5,6,7,8}, + {8,7,7,6}, + {6,7,10,7,6}} - for i=1 to length(tests) do - sequence ti = tests[i] - printf(1,"%35s : %d\n",{sprint(ti),collect_water(ti)}) - end for - - with javascript_semantics - function collect_water(sequence heights) +with javascript_semantics +function collect_water(sequence heights) - integer left_max = heights[1], - right_max = heights[$] - sequence left_height = deep_copy(heights), - right_height = deep_copy(heights) + integer left_max = heights[1], + right_max = heights[$] + sequence left_height = deep_copy(heights), + right_height = deep_copy(heights) - for i=2 to length(heights)-1 do - left_max = max(heights[i],left_max) - left_height[i] = left_max - right_max = max(heights[-i],right_max) - right_height[-i] = right_max - end for + for i=2 to length(heights)-1 do + left_max = max(heights[i],left_max) + left_height[i] = left_max + right_max = max(heights[-i],right_max) + right_height[-i] = right_max + end for - sequence mins = sq_min(left_height,right_height), - diffs = sq_sub(mins,heights) + sequence mins = sq_min(left_height,right_height), + diffs = sq_sub(mins,heights) - return sum(diffs) - end function - - with javascript_semantics - requires("1.0.2") -- (bugfix in p2js.js/$sidii(), 20/4/22) - procedure print_water(sequence heights) - integer res = 0, l = length(heights) - sequence towers = repeat(repeat(' ',l),max(heights)) - for i=1 to l do - for j=1 to heights[i] do - towers[-j][i] = '#' - end for - if i>1 and i<l then - integer lm = max(heights[1..i-1]), - rm = max(heights[i+1..$]), - m = min(lm,rm) - for j=heights[i]+1 to m do - towers[-j][i] = '~' - res += 1 - end for - end if - end for - printf(1,"%s\ncollected:%d\n",{join(towers,"\n"),res}) - end procedure +with javascript_semantics +requires("1.0.2") -- (bugfix in p2js.js/$sidii(), 20/4/22) +procedure print_water(sequence heights) + integer res = 0, l = length(heights) + sequence towers = repeat(repeat(' ',l),max(heights)) + for i=1 to l do + for j=1 to heights[i] do + towers[-j][i] = '#' + end for + if i>1 and iprint_water
    ({5,3,7,2,6,4,5,9,1,2}) - - with javascript_semantics - include mpfr.e - function weiferich(integer p) - mpz p2pm1m1 = mpz_init() - mpz_ui_pow_ui(p2pm1m1,2,p-1) - mpz_sub_ui(p2pm1m1,p2pm1m1,1) - return mpz_fdiv_q_ui(p2pm1m1,p2pm1m1,p*p)=0 - end function - printf(1,"Weiferich primes less than 5000: %V\n",{filter(get_primes_le(5000),weiferich)}) - - with javascript_semantics - include mpfr.e - mpz base = mpz_init(2), - {modulus, z} = mpz_inits(2) - function weiferich(integer p) - mpz_set_si(modulus,p*p) - mpz_powm_ui(z, base, p-1, modulus) - return mpz_cmp_si(z,1)=0 - end function - printf(1,"Weiferich primes less than 5000: %V\n",{filter(get_primes_le(5000),weiferich)}) - sequence(row, Grid), blanks. +row(Row) --> string_without("\n", Row), { Row \= [] }, eol. + +:- meta_predicate maplist_with_nth0(3, +, -). +maplist_with_nth0(Goal, List0, List) :- + length(List0, Length), + succ(LastIndex, Length), + numlist(0, LastIndex, N0s), + maplist(Goal, N0s, List0, List). + +:- meta_predicate map_grid0(3, +, -). +map_grid0(Goal, Grid0, Grid) :- + maplist_with_nth0({Goal}/[Y, Row0, Row] >> ( + maplist_with_nth0({Goal, Y}/[X, T0, T] >> ( + call(Goal, yx(Y, X), T0, T) + ), Row0, Row) + ), Grid0, Grid). + +yxth0(yx(Y, X)) --> nth0(Y), nth0(X). + +moore_neighbourhood(yx(Y0, X0), yx(Y, X)) :- succ(Y0, Y), ( succ(X, X0) ; X = X0 ; succ(X0, X) ). +moore_neighbourhood(yx(Y, X0), yx(Y, X)) :- succ(X, X0) ; succ(X0, X). +moore_neighbourhood(yx(Y0, X0), yx(Y, X)) :- succ(Y, Y0), ( succ(X, X0) ; X = X0 ; succ(X0, X) ). + +transition(_, _, 0' , 0' ) :- !. +transition(_, _, 0'H, 0't) :- !. +transition(_, _, 0't, 0'.) :- !. +transition(Grid, Here, 0'., State) :- + aggregate_all(count, ( + moore_neighbourhood(Here, There), + yxth0(There, Grid, 0'H) + ), AdjacentHeads), + ( between(1, 2, AdjacentHeads) + -> State = 0'H + ; State = 0'. + ). + +char_attributes(0'., [bg(yellow)]). +char_attributes(0' , []). +char_attributes(0't, [bg(red)]). +char_attributes(0'H, [bg(blue)]). + +display(Grid) :- + maplist([Row] >> ( + maplist([Char] >> ( + char_attributes(Char, Attributes), + ansi_format(Attributes, "~c", [Char]) + ), Row), + nl + ), Grid). + +simulate(Grid0) :- + map_grid0(transition(Grid0), Grid0, Grid), + display(Grid), + sleep(0.25), + length(Grid, Height), + format("\e[~dA", [Height]), + simulate(Grid). + +main([Filename]) :- + format("Welcome to WireWorld! Press ^C to exit.~n~n", []), + once(phrase_from_file(grid(Grid), Filename)), + simulate(Grid). diff --git a/Task/Wireworld/Rust/wireworld-1.rust b/Task/Wireworld/Rust/wireworld-1.rs similarity index 100% rename from Task/Wireworld/Rust/wireworld-1.rust rename to Task/Wireworld/Rust/wireworld-1.rs diff --git a/Task/Wireworld/Rust/wireworld-2.rust b/Task/Wireworld/Rust/wireworld-2.rs similarity index 100% rename from Task/Wireworld/Rust/wireworld-2.rust rename to Task/Wireworld/Rust/wireworld-2.rs diff --git a/Task/Wireworld/Uiua/wireworld.uiua b/Task/Wireworld/Uiua/wireworld.uiua new file mode 100644 index 0000000000..e6aaa67498 --- /dev/null +++ b/Task/Wireworld/Uiua/wireworld.uiua @@ -0,0 +1,6 @@ +"tH.........\n. .\n ...\n. .\nHt.. ......" +CanBeHead ← ⍥₂(⍉↘¯1↘1)⬚@\s⧈(↥⊃=₁=₂/+=@H⍜⊡₄⋅@./⊂)3_3 +Successor ← ⍣(@\s◌ °@\s|@t◌ °@H|@.◌ °@t|@H °1◌|@.) +Step ← ≡₋₂Successor⟜CanBeHead +⍥⊸Step20 ⬚@\s⊜∘⊸≠@\n +▽10≡▽₂20≡₋₃(⍣(0_0_0 °@\s|1_0_0 °@H|0.9_0.7_0 °@t|÷3 1_1_1)) diff --git a/Task/Word-frequency/Ada/word-frequency.ada b/Task/Word-frequency/Ada/word-frequency.adb similarity index 100% rename from Task/Word-frequency/Ada/word-frequency.ada rename to Task/Word-frequency/Ada/word-frequency.adb diff --git a/Task/Word-frequency/AppleScript/word-frequency-2.applescript b/Task/Word-frequency/AppleScript/word-frequency-2.applescript index c582a62e50..de203a6c70 100644 --- a/Task/Word-frequency/AppleScript/word-frequency-2.applescript +++ b/Task/Word-frequency/AppleScript/word-frequency-2.applescript @@ -1,11 +1,11 @@ "The 10 most frequently occurring words in the file are: -The: 41092 -Of: 19954 -And: 14943 -A: 14545 -To: 13953 -In: 11219 -He: 9649 -Was: 8622 -That: 7924 -It: 6661" +The: 41092 +Of: 19954 +And: 14943 +A: 14545 +To: 13953 +In: 11219 +He: 9649 +Was: 8622 +That: 7924 +It: 6661" diff --git a/Task/Word-frequency/Arturo/word-frequency.arturo b/Task/Word-frequency/Arturo/word-frequency.arturo index 34eb7e650f..14be69b540 100644 --- a/Task/Word-frequency/Arturo/word-frequency.arturo +++ b/Task/Word-frequency/Arturo/word-frequency.arturo @@ -6,7 +6,7 @@ findFrequency: function [file, count][ freqs\[word]: freqs\[word] + 1 ] freqs: sort.values.descending freqs - result: new [] + result: [] loop 0..dec count 'x [ 'result ++ @[@[get keys freqs x, get values freqs x]] ] diff --git a/Task/Word-frequency/AutoHotkey/word-frequency.ahk b/Task/Word-frequency/AutoHotkey/word-frequency.ahk index 45db355ab6..9ddc424b5d 100644 --- a/Task/Word-frequency/AutoHotkey/word-frequency.ahk +++ b/Task/Word-frequency/AutoHotkey/word-frequency.ahk @@ -3,15 +3,15 @@ FileRead, H, % A_temp "\tempfile.txt" FileDelete, % A_temp "\tempfile.txt" words := [] while pos := RegExMatch(H, "\b[[:alpha:]]+\b", m, A_Index=1?1:pos+StrLen(m)) - words[m] := words[m] ? words[m] + 1 : 1 + words[m] := words[m] ? words[m] + 1 : 1 for word, count in words - list .= count "`t" word "`r`n" + list .= count "`t" word "`r`n" Sort, list, RN loop, parse, list, `n, `r { - result .= A_LoopField "`r`n" - if A_Index = 10 - break + result .= A_LoopField "`r`n" + if A_Index = 10 + break } MsgBox % "Freq`tWord`n" result return diff --git a/Task/Word-frequency/Batch-File/word-frequency.bat b/Task/Word-frequency/Batch-File/word-frequency.bat index bfdc70a525..6350d907a2 100644 --- a/Task/Word-frequency/Batch-File/word-frequency.bat +++ b/Task/Word-frequency/Batch-File/word-frequency.bat @@ -11,35 +11,34 @@ setlocal enabledelayedexpansion set word=100000 set line=0 for /f "delims=" %%i in (input.txt) do ( - set /a line+=1 - for %%j in (%%i) do ( - if not !skip%%j!==true ( - echo line !line! ^| word !word:~-5! - "%%~j" - - type input.txt | find /i /c "%%~j" > count.tmp - set /p tmpvar= count.tmp + set /p tmpvar= (cdr a) (cdr b))))) + (setq matches (seq-take matches number-requested)) + (dolist (match matches) + (insert (format "\n%s %s" (car match) (cdr match)))))) diff --git a/Task/Word-frequency/FreeBASIC/word-frequency.basic b/Task/Word-frequency/FreeBASIC/word-frequency.basic index b32ac726fb..76772db244 100644 --- a/Task/Word-frequency/FreeBASIC/word-frequency.basic +++ b/Task/Word-frequency/FreeBASIC/word-frequency.basic @@ -30,7 +30,7 @@ Sub tallysort(array() As tally,begin As Long,Finish As long) Function loadfile(file As String) As String - If Fileexists(file)=0 Then Print file;" not found":Sleep:End + If Fileexists(file)=0 Then Print file;" not found":Sleep:End Dim As Long f=Freefile Open file For Binary Access Read As #f Dim As String text diff --git a/Task/Word-frequency/Icon/word-frequency.icon b/Task/Word-frequency/Icon/word-frequency.icon new file mode 100644 index 0000000000..65ad14faeb --- /dev/null +++ b/Task/Word-frequency/Icon/word-frequency.icon @@ -0,0 +1,8 @@ +procedure main(A) + WC := &letters++&digits + n := \A[1] | 10 + wt := table(0) + write("The ",n," most common words are:") + every !&input ? while tab(upto(WC)) do wt[map(tab(many(WC)))] +:= 1 + every p := !reverse(sort(wt,2))\n do write(right(p[2],8),": ",p[1]) +end diff --git a/Task/Word-frequency/Julia/word-frequency.julia b/Task/Word-frequency/Julia/word-frequency.jl similarity index 100% rename from Task/Word-frequency/Julia/word-frequency.julia rename to Task/Word-frequency/Julia/word-frequency.jl diff --git a/Task/Word-frequency/KAP/word-frequency.kap b/Task/Word-frequency/KAP/word-frequency.kap index e6ae9967bb..8d795e3c63 100644 --- a/Task/Word-frequency/KAP/word-frequency.kap +++ b/Task/Word-frequency/KAP/word-frequency.kap @@ -1,7 +1,7 @@ ∇ stats (file) { - content ← "[\\h,.\"'\n-]+" regex:split unicode:toLower io:readFile file - sorted ← (⍋⊇⊢) content - selection ← 1,2≢/sorted - words ← selection / sorted - {⍵[10↑⍒⍵[;1];]} words ,[0.5] ≢¨ sorted ⊂⍨ +\selection + content ← "[\\h,.\"'\n-]+" regex:split unicode:toLower io:readFile file + sorted ← (⍋⊇⊢) content + selection ← 1,2≢/sorted + words ← selection / sorted + {⍵[10↑⍒⍵[;1];]} words ,[0.5] ≢¨ sorted ⊂⍨ +\selection } diff --git a/Task/Word-frequency/Kotlin/word-frequency.kotlin b/Task/Word-frequency/Kotlin/word-frequency.kts similarity index 100% rename from Task/Word-frequency/Kotlin/word-frequency.kotlin rename to Task/Word-frequency/Kotlin/word-frequency.kts diff --git a/Task/Word-frequency/Lua/word-frequency.lua b/Task/Word-frequency/Lua/word-frequency.lua index 533d6bedb2..83e648322e 100644 --- a/Task/Word-frequency/Lua/word-frequency.lua +++ b/Task/Word-frequency/Lua/word-frequency.lua @@ -5,24 +5,24 @@ -- in freq, each key is a word and each value is its count local freq = {} for line in io.lines(arg[1]) do - -- %a stands for any letter - for word in string.gmatch(string.lower(line), "%a+") do - if not freq[word] then - freq[word] = 1 - else - freq[word] = freq[word] + 1 - end - end + -- %a stands for any letter + for word in string.gmatch(string.lower(line), "%a+") do + if not freq[word] then + freq[word] = 1 + else + freq[word] = freq[word] + 1 + end + end end -- in array, each entry is an array whose first value is the count and whose -- second value is the word local array = {} for word, count in pairs(freq) do - table.insert(array, {count, word}) + table.insert(array, {count, word}) end table.sort(array, function (a, b) return a[1] > b[1] end) for i = 1, arg[2] or 10 do - io.write(string.format('%7d %s\n', array[i][1] , array[i][2])) + io.write(string.format('%7d %s\n', array[i][1] , array[i][2])) end diff --git a/Task/Word-frequency/Nu/word-frequency.nu b/Task/Word-frequency/Nu/word-frequency.nu new file mode 100644 index 0000000000..2784bb2317 --- /dev/null +++ b/Task/Word-frequency/Nu/word-frequency.nu @@ -0,0 +1,8 @@ +def lesm [] { + let corp = open --raw 'LES_MISÉRABLES.txt' | str downcase | split words | wrap corp + let stop = [i a an and are as at be by for from how in is it of on or that the this to was what when where who will with the] | wrap stop + let tidy = $corp | where corp in $stop.stop == false + $tidy | histogram value +} + +lesm | first 20 diff --git a/Task/Word-frequency/OCaml/word-frequency.ocaml b/Task/Word-frequency/OCaml/word-frequency.ml similarity index 100% rename from Task/Word-frequency/OCaml/word-frequency.ocaml rename to Task/Word-frequency/OCaml/word-frequency.ml diff --git a/Task/Word-frequency/PascalABC.NET/word-frequency.pas b/Task/Word-frequency/PascalABC.NET/word-frequency.pas new file mode 100644 index 0000000000..759f414c6a --- /dev/null +++ b/Task/Word-frequency/PascalABC.NET/word-frequency.pas @@ -0,0 +1,3 @@ +## +ReadAllText('135-0.txt').ToLower.MatchValues('\w+').EachCount + .OrderByDescending(w -> w.Value).Take(10).PrintLines diff --git a/Task/Word-frequency/Perl/word-frequency.pl b/Task/Word-frequency/Perl/word-frequency.pl index 0657eb7a40..58fdf54d57 100644 --- a/Task/Word-frequency/Perl/word-frequency.pl +++ b/Task/Word-frequency/Perl/word-frequency.pl @@ -14,7 +14,7 @@ my @matcher = ( ); for my $reg (@matcher) { - print "\nTop $top using regex: " . $reg\n"; + print "\nTop $top using regex: " . $reg . "\n"; my @matches = $text =~ /$reg/g; my %words; for my $w (@matches) { $words{$w}++ }; diff --git a/Task/Word-frequency/R/word-frequency-2.r b/Task/Word-frequency/R/word-frequency-2.r index a8363ac6cf..4bb606d6a3 100644 --- a/Task/Word-frequency/R/word-frequency-2.r +++ b/Task/Word-frequency/R/word-frequency-2.r @@ -1,5 +1,5 @@ word_frequency_pipeline <- function(file=NULL, n=10) { - + file |> vroom::vroom_lines() |> stringi::stri_split_boundaries(type="word", skip_word_none=T, skip_word_number=T) |> @@ -9,5 +9,5 @@ word_frequency_pipeline <- function(file=NULL, n=10) { sort(decreasing = T) |> (\(.) .[1:n])() |> data.frame() - + } diff --git a/Task/Word-frequency/REXX/word-frequency-1.rexx b/Task/Word-frequency/REXX/word-frequency-1.rexx index b824a211d9..7048108d4a 100644 --- a/Task/Word-frequency/REXX/word-frequency-1.rexx +++ b/Task/Word-frequency/REXX/word-frequency-1.rexx @@ -1,56 +1,51 @@ -/*REXX pgm displays top 10 words in a file (includes foreign letters), case is ignored.*/ -parse arg fID top . /*obtain optional arguments from the CL*/ -if fID=='' | fID=="," then fID= 'les_mes.txt' /*None specified? Then use the default.*/ -if top=='' | top=="," then top= 10 /* " " " " " " */ -call init /*initialize varied bunch of variables.*/ -call rdr -say right('word', 40) " " center(' rank ', 6) " count " /*display title for output*/ -say right('════', 40) " " center('══════', 6) " ═══════" /* " title separator.*/ - - do until otops==tops | tops>top /*process enough words to satisfy TOP.*/ - WL=; mk= 0; otops= tops /*initialize the word list (to a NULL).*/ - - do n=1 for c; z= !.n; k= @.z /*process the list of words in the file*/ - if k==mk then WL= WL z /*handle cases of tied number of words.*/ - if k> mk then do; mk=k; WL=z; end /*this word count is the current max. */ - end /*n*/ - - wr= max( length(' rank '), length(top) ) /*find the maximum length of the rank #*/ - - do d=1 for words(WL); y= word(WL, d) /*process all words in the word list. */ - if d==1 then w= max(10, length(@.y) ) /*use length of the first number used. */ - say right(y, 40) right( commas(tops), wr) right(commas(@.y), w) - @.y= . /*nullify word count for next go 'round*/ - end /*d*/ /* [↑] this allows a non-sorted list. */ - - tops= tops + words(WL) /*correctly handle any tied rankings.*/ - end /*until*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ? -16bit: do k=1 for xs; _=word(x,k); $=changestr('├'left(_,1),$,right(_,1)); end; return -/*──────────────────────────────────────────────────────────────────────────────────────*/ -init: x= 'Çà åÅ çÇ êÉ ëÉ áà óâ ªæ ºç ¿è ⌐é ¬ê ½ë «î »ï ▒ñ ┤ô ╣ù ╗û ╝ü'; xs= words(x) - abcL="abcdefghijklmnopqrstuvwxyz'" /*lowercase letters of Latin alphabet. */ - abcU= abcL; upper abcU /*uppercase version of Latin alphabet. */ - accL= 'üéâÄàÅÇêëèïîìéæôÖòûùÿáíóúÑ' /*some lowercase accented characters. */ - accU= 'ÜéâäàåçêëèïîìÉÆôöòûùÿáíóúñ' /* " uppercase " " */ - accG= 'αßΓπΣσµτΦΘΩδφε' /* " upper/lowercase Greek letters. */ - ll= abcL || abcL ||accL ||accL || accG /*chars of after letters. */ - uu= abcL || abcU ||accL ||accU || accG || xrange() /* " " before " */ - @.= 0; q= "'"; totW= 0; !.= @.; c= 0; tops= 1; return -/*──────────────────────────────────────────────────────────────────────────────────────*/ -rdr: do #=0 while lines(fID)\==0; $=linein(fID) /*loop whilst there're lines in file.*/ - if pos('├', $) \== 0 then call 16bit /*are there any 16-bit characters ?*/ - $= translate( $, ll, uu) /*trans. uppercase letters to lower. */ - do while $ \= ''; parse var $ z $ /*process each word in the $ line. */ - parse var z z1 2 zr '' -1 zL /*obtain: first, middle, & last char.*/ - if z1==q then do; z=zr; if z=='' then iterate; end /*starts with apostrophe?*/ - if zL==q then z= strip(left(z, length(z) - 1)) /*ends " " ?*/ - if z=='' then iterate /*if Z is now null, skip.*/ - if @.z==0 then do; c=c+1; !.c=z; end /*bump word cnt; assign word to array*/ - totW= totW + 1; @.z= @.z + 1 /*bump total words; bump a word count*/ - end /*while*/ - end /*#*/ - say commas(totW) ' words found ('commas(c) "unique) in " commas(#), - ' records read from file: ' fID; say; return +/*REXX program reads and displays a count of words a file. Word case is ignored.*/ +Call time 'R' +abc='abcdefghijklmnopqrstuvwxyz' +abcABC=abc||translate(abc) +parse arg fID_top /*obtain optional arguments from the CL*/ +Parse Var fid_top fid ',' top +if fID=='' then fID= 'mis.TXT' /* Use default if not specified */ +if top=='' then top= 10 /* Use default if not specified */ +occ.=0 /* occurrences of word (stem) in file */ +wn=0 +Do While lines(fid)>0 /*loop whilst there are lines in file. */ + line=linein(fID) + line=translate(line,abc||abc,abcABC||xrange('00'x,'ff'x)) /*use only lowercase letters*/ + Do While line<>'' + Parse Var line word line /* take a word */ + If occ.word=0 Then Do /* not yet in word list */ + wn=wn+1 + word.wn=word + End + occ.word=occ.word+1 + End + End +Say 'We found' wn 'different words' +say right('word',40) ' rank count ' /* header */ +say right('----',40) '------ -------' /* separator. */ +tops=0 +Do Until tops>=top | tops>=wn /*process enough words to satisfy TOP.*/ + max_occ=0 + tl='' /*initialize (possibly) a list of words*/ + Do wi=1 To wn /*process the list of words in the file*/ + word=word.wi /* take a word from the list */ + Select + When occ.word>max_occ Then Do /* most occurrences so far */ + tl=word /* candidate for output */ + max_occ=occ.word /* current maximum occurrences */ + End + When occ.word=max_occ Then Do /* tied */ + tl=tl word /* add to output candidate */ + End + Otherwise /* no candidate (yet) */ + Nop + End + End + do d=1 for words(tl) + word=word(tl,d) + say right(word,40) right(tops+1,4) right(occ.word,8) + occ.word=0 /*nullify this word count for next time*/ + End + tops=tops+words(tl) /*correctly handle the tied rankings. */ + end +Say time('E') 'seconds elapsed' diff --git a/Task/Word-frequency/REXX/word-frequency-2.rexx b/Task/Word-frequency/REXX/word-frequency-2.rexx index 7048108d4a..4d1bbad7ee 100644 --- a/Task/Word-frequency/REXX/word-frequency-2.rexx +++ b/Task/Word-frequency/REXX/word-frequency-2.rexx @@ -1,51 +1,85 @@ -/*REXX program reads and displays a count of words a file. Word case is ignored.*/ -Call time 'R' -abc='abcdefghijklmnopqrstuvwxyz' -abcABC=abc||translate(abc) -parse arg fID_top /*obtain optional arguments from the CL*/ -Parse Var fid_top fid ',' top -if fID=='' then fID= 'mis.TXT' /* Use default if not specified */ -if top=='' then top= 10 /* Use default if not specified */ -occ.=0 /* occurrences of word (stem) in file */ -wn=0 -Do While lines(fid)>0 /*loop whilst there are lines in file. */ - line=linein(fID) - line=translate(line,abc||abc,abcABC||xrange('00'x,'ff'x)) /*use only lowercase letters*/ - Do While line<>'' - Parse Var line word line /* take a word */ - If occ.word=0 Then Do /* not yet in word list */ - wn=wn+1 - word.wn=word - End - occ.word=occ.word+1 - End - End -Say 'We found' wn 'different words' -say right('word',40) ' rank count ' /* header */ -say right('----',40) '------ -------' /* separator. */ -tops=0 -Do Until tops>=top | tops>=wn /*process enough words to satisfy TOP.*/ - max_occ=0 - tl='' /*initialize (possibly) a list of words*/ - Do wi=1 To wn /*process the list of words in the file*/ - word=word.wi /* take a word from the list */ - Select - When occ.word>max_occ Then Do /* most occurrences so far */ - tl=word /* candidate for output */ - max_occ=occ.word /* current maximum occurrences */ - End - When occ.word=max_occ Then Do /* tied */ - tl=tl word /* add to output candidate */ - End - Otherwise /* no candidate (yet) */ - Nop - End - End - do d=1 for words(tl) - word=word(tl,d) - say right(word,40) right(tops+1,4) right(occ.word,8) - occ.word=0 /*nullify this word count for next time*/ - End - tops=tops+words(tl) /*correctly handle the tied rankings. */ - end -Say time('E') 'seconds elapsed' +-- 10 Mar 2026 +include Setting +arg file top +if file='' | file='.' then + file='Miserables.txt' +if top='' then + top=10 + +say 'WORD FREQUENCY' +say version +say +call CountWords file +call SaveCount +call ShowCount top +call ShowWord top +call Timer +exit + +CountWords: +procedure expose Dict. List. +parse arg file +-- Init +abc=Xrange('a','z'); all=Xrange('00'x,'FF'x) +Dict.=0; List.=0; n=0 +-- Process file +do while Lines(file) +-- Convert to lower case and filter only a-z + line=Translate(Lower(Linein(file)),abc,abc||all) + do i=1 to Words(line) + w=Word(line,i) +-- Not in dictionary? Add to list + if Dict.w=0 then do + n+=1; List.Dict.n=w + end +-- Count in dictionary + Dict.w+=1 + end i +end +List.0=n +say n 'different words found' +say +return + +SaveCount: +procedure expose Dict. List. +-- Move counts to list +do i=1 to List.0 + w=List.Dict.i; List.Count.i=Dict.w +end +return + +ShowCount: +procedure expose List. +arg top +call SortSt 'List.Count.','List.Dict.' +say 'Frequency by count' +say 'word rank count' +say '---------------------------' +n=0 +do i=List.0 by -1 to 1 + n+=1 + if n<=top then + say Left(List.Dict.i,15) Right(n,5) Right(List.Count.i,5) + List.Rank.i=n +end +say '...' +say +return + +ShowWord: +procedure expose List. +arg top +call SortSt 'List.Dict.','List.Rank. List.Count.' +say 'Frequency by word' +say 'word rank count' +say '---------------------------' +do i=1 to top + say Left(List.Dict.i,15) Right(List.Rank.i,5) Right(List.Count.i,5) +end +say '...' +say +return + +-- SortSt; Timer +include Math diff --git a/Task/Word-frequency/Raku/word-frequency.raku b/Task/Word-frequency/Raku/word-frequency.raku index 82faa4afed..4077ef2f75 100644 --- a/Task/Word-frequency/Raku/word-frequency.raku +++ b/Task/Word-frequency/Raku/word-frequency.raku @@ -8,8 +8,8 @@ sub MAIN ($filename, UInt $top = 10) { ; for @matcher -> $reg { say "\nTop $top using regex: ", $reg.raku; - my @words = $file.comb($reg).Bag.sort(-*.value)[^$top]; - my $length = max @words».key».chars; + my @words = $file.comb($reg).Bag.sort(-*.value)[^$top]; + my $length = max @words».key».chars; printf "%-{$length}s %d\n", .key, .value for @words; } } diff --git a/Task/Word-frequency/Rebol/word-frequency.rebol b/Task/Word-frequency/Rebol/word-frequency.rebol new file mode 100644 index 0000000000..7cf6d0e451 --- /dev/null +++ b/Task/Word-frequency/Rebol/word-frequency.rebol @@ -0,0 +1,36 @@ +Rebol [ + title: "Rosetta code: Word frequency" + file: %Word_frequency.r3 + url: https://rosettacode.org/wiki/Word_frequency +] + +word-frequency: function/with [ + text [string! file! url!] +][ + dict: make map! 1000 + unless string? text [text: read/string text] + parse text [ + any [ + copy word: some word-chars ( + word: lowercase word ;; normalize + dict/:word: either n: dict/:word [n + 1][1] + ) + | some skip-chars + ] + ] + data: sort/reverse/skip/compare to block! dict 2 2 + new-line/skip data true 2 +][ + word-chars: system/catalog/bitsets/alpha + skip-chars: complement word-chars +] + +;; Example: +unless exists? %135-0.txt [ + print "Downloading the test file: 135-0.txt" + ;; Update timeout in case of slow connection. + system/schemes/https/spec/timeout: 60 + write %135-0.txt read https://www.gutenberg.org/files/135/135-0.txt +] + +probe copy/part word-frequency %135-0.txt 20 diff --git a/Task/Word-frequency/Red/word-frequency.red b/Task/Word-frequency/Red/word-frequency.red new file mode 100644 index 0000000000..68b59559f1 --- /dev/null +++ b/Task/Word-frequency/Red/word-frequency.red @@ -0,0 +1,14 @@ +Red [ "Word frequency - hinjolicious" ] + +word-freq: function [file n][ + word-chars: charset "abcdefghijklmnopqrstuvwxyz" + words: parse lowercase read file [collect [any [keep [some word-chars] | skip]]] + freq: make map! [] + foreach w words [freq/:w: either none? freq/:w [1][freq/:w + 1]] + sorted: sort/reverse collect [foreach [w c] freq [keep/only reduce [c w]]] +] + +sorted: word-freq %135-0.txt 10 + +print "Top 10 word frequency:" +repeat i 10 [w: sorted/:i print [pad w/2 10 w/1]] diff --git a/Task/Word-frequency/Rust/word-frequency.rust b/Task/Word-frequency/Rust/word-frequency.rs similarity index 100% rename from Task/Word-frequency/Rust/word-frequency.rust rename to Task/Word-frequency/Rust/word-frequency.rs diff --git a/Task/Word-frequency/Scheme/word-frequency.scm b/Task/Word-frequency/Scheme/word-frequency.scm new file mode 100644 index 0000000000..933477c452 --- /dev/null +++ b/Task/Word-frequency/Scheme/word-frequency.scm @@ -0,0 +1,40 @@ +(use srfi-13) ;; string functions +(use srfi-14) ;; character sets +(use file.util) + +;; Increment a value in an association list. +(define-syntax ainc! + (syntax-rules () + [(_ alist key val func default) + (let ((pair (assoc key alist))) + (if pair + (set-cdr! pair (func val (cdr pair))) + (set! alist (cons (cons key (func val default)) alist))))] + [(_ alist key val func) + (ainc! alist key val func 0)] + [(_ alist key val) + (ainc! alist key val +)] + [(_ alist key) + (ainc! alist key 1)])) + +(define *table* '()) + +(define (process-line line) + (dolist (word + (string-tokenize (string-upcase line) char-set:letter)) + (ainc! *table* word))) + +(define (foo filename) + (set! *table* '()) + (dolist (line (file->string-list filename)) + (process-line line))) + +(time (foo "Alice.txt")) +; user 3.219 [seconds] + +(define *result* (sort *table* > cdr)) + +(take *result* 10) + +(("THE" . 1818) ("AND" . 940) ("TO" . 809) ("A" . 690) ("OF" . 631) + ("IT" . 610) ("SHE" . 553) ("I" . 545) ("YOU" . 481) ("SAID" . 462)) diff --git a/Task/Word-frequency/Smalltalk/word-frequency-1.st b/Task/Word-frequency/Smalltalk/word-frequency-1.st index 6d91dd04ce..f420e02c56 100644 --- a/Task/Word-frequency/Smalltalk/word-frequency-1.st +++ b/Task/Word-frequency/Smalltalk/word-frequency-1.st @@ -1,2 +1,2 @@ (StandardFileStream new open: 'lesms10.txt' forWrite: false) - contents asLowercase substrings asBag sortedCounts first: 10. + contents asLowercase substrings asBag sortedCounts first: 10. diff --git a/Task/Word-frequency/Smalltalk/word-frequency-2.st b/Task/Word-frequency/Smalltalk/word-frequency-2.st index 3097e245fa..1ccabe1e3f 100644 --- a/Task/Word-frequency/Smalltalk/word-frequency-2.st +++ b/Task/Word-frequency/Smalltalk/word-frequency-2.st @@ -1,2 +1,2 @@ (StandardFileStream readOnlyFileNamed: 'lesms10.txt') - contents asLowercase substrings asBag sortedCounts first: 10. + contents asLowercase substrings asBag sortedCounts first: 10. diff --git a/Task/Word-frequency/TAV/word-frequency.tav b/Task/Word-frequency/TAV/word-frequency.tav new file mode 100644 index 0000000000..a5bc650348 --- /dev/null +++ b/Task/Word-frequency/TAV/word-frequency.tav @@ -0,0 +1,34 @@ +main (args):+ + wm =: count words "../les_mis_135-0.txt" + wr =: map wm as row descending value key pairs + ?# i =: from 1 upto max + print format '%6d; %s;' wr[i] \ wr[i] is a pair + +\ read the file and provide a map with all words and their count +count words (fn): + wl =: new map + ?# line =: file fn give lines + ?# word =: string line give words of #ASCIIletters + word =: string word case to lower + wl{word} =+ 1 \ count for word; void is zero for addition + wl.words =+ 1 \ count number of words + :> wl + +\ create a sorted row of pairs (count, word) +map (@) as row descending value key pairs: + rvk =: new row size @.Count + ?# k =: map @ give keys + rvk[] =: @{k}, k + row rvk sort fast descending + :> rvk + +\ not (yet) in library +string (@) give words of (chars): + $ =~ 1 \ start point + ?* $ <= @.Count + word =: string @ from $ many of chars + $ =+ word.Count + 1 \ skip following character + ? word ~= '' + :> word + $ =: () + :> () diff --git a/Task/Word-frequency/Uiua/word-frequency.uiua b/Task/Word-frequency/Uiua/word-frequency.uiua new file mode 100644 index 0000000000..e4505a857e --- /dev/null +++ b/Task/Word-frequency/Uiua/word-frequency.uiua @@ -0,0 +1,3 @@ +&fras"RosettaCode/les-miserables.txt" +⊜□⊸(↧⊃(≥@a|≤@z))+×32↧⊸⊃(≥@A|≤@Z) # Lowercase, split on non-letter. +↙10⊏⍖⊸≡⊣⊕[⊃⊢⧻]⊸⊸⊛ # Group, count, sort, take 10. diff --git a/Task/Word-frequency/V-(Vlang)/word-frequency.v b/Task/Word-frequency/V-(Vlang)/word-frequency.v new file mode 100644 index 0000000000..2b02cd731f --- /dev/null +++ b/Task/Word-frequency/V-(Vlang)/word-frequency.v @@ -0,0 +1,25 @@ +import os +import maps + +fn main() { + mis := os.read_file("./135-0.txt") or {panic("Error reading file")} + mut grp, mut rgrp := map[string]int, map[int]string + mut keys := []int{} + mut result := "" + mut count := 1 + for line in mis.split_into_lines() { + for word in line.split("\x20") { + if !word.is_blank() {grp[word.to_lower()]++} + } + } + rgrp = maps.invert(grp) + keys = rgrp.keys() + keys.sort(a > b) + for key in keys { + result += "${count++:2} " + "${rgrp[key]} " + "${key}" + "\n" + if count > 10 {break} + } + println("Rank Word Frequency") + println("==== ==== =========") + println(result) +} diff --git a/Task/Word-frequency/Zkl/word-frequency.zkl b/Task/Word-frequency/Zkl/word-frequency.zkl index 7923fea37a..b069630aae 100644 --- a/Task/Word-frequency/Zkl/word-frequency.zkl +++ b/Task/Word-frequency/Zkl/word-frequency.zkl @@ -1,4 +1,4 @@ -fname,count := vm.arglist; // grab cammand line args +fname,count := vm.arglist; // grab cammand line args // words may have leading or trailing "_", ie "the" and "_the" File(fname).pump(Void,"toLower", // read the file line by line and hash words diff --git a/Task/Word-ladder/APL/word-ladder.apl b/Task/Word-ladder/APL/word-ladder.apl new file mode 100644 index 0000000000..8138277c6e --- /dev/null +++ b/Task/Word-ladder/APL/word-ladder.apl @@ -0,0 +1,23 @@ +wordladder←{ + from to←⍵ + dict←((≢¨⍺)=≢to)/⍺ + + dict{ + match←(⊂to)≡¨⊃∘⌽¨⍵ + ∨/match:⊃match/⍵ + 0∊≢¨⍺⍵:⍬ + word←⊃⌽ladder←⊃⍵ + next←(1=⍺+.≠¨⊂word)/⍺ + (⍺~next)∇(1↓⍵),(⊂ladder),¨⊂¨next + }⊂⊂from +} +task←{ + dict←(~dict∊⎕TC)⊆dict←⊃⎕NGET'unixdict.txt' + pairs←('boy' 'man')('girl' 'lady')('john' 'jane')('child' 'adult') + ⎕←↑↑{ + hdr←⍺,' → ',⍵,': ' + ladder←dict wordladder ⍺ ⍵ + 0=≢ladder:hdr,'impossible' + hdr,1↓∊'→',¨ladder + }/¨pairs +} diff --git a/Task/Word-ladder/Ada/word-ladder.adb b/Task/Word-ladder/Ada/word-ladder.adb new file mode 100644 index 0000000000..1baca530f6 --- /dev/null +++ b/Task/Word-ladder/Ada/word-ladder.adb @@ -0,0 +1,146 @@ +pragma Ada_2022; +with Ada.Containers.Multiway_Trees; +with Ada.Containers.Vectors; +with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Text_IO.Unbounded_IO; use Ada.Text_IO.Unbounded_IO; +procedure Word_Ladder is + + DICT_FILENAME : constant String := "unixdict.txt"; + MAX_DEPTH : constant Positive := 50; + + subtype LC_Chars is Character range 'a' .. 'z'; + + type Word_Node_T is record + Level : Positive; + Word : Unbounded_String; + end record; + + package Word_Vectors is new Ada.Containers.Vectors (Positive, Unbounded_String); + package Dict_Vectors is new Ada.Containers.Vectors (Positive, Unbounded_String); + + package Word_Trees is new Ada.Containers.Multiway_Trees (Word_Node_T); + use Word_Trees; + Word_Tree : Tree; + Solved : Boolean; + Solution : Cursor; + + function Load_Candidate_Words (Dict_Filename : String; Word_Len : Positive) + return Dict_Vectors.Vector is + Dict_File : File_Type; + Read_Word : Unbounded_String; + Cands : Dict_Vectors.Vector; + Valid : Boolean; + C : Character; + begin + Open (File => Dict_File, Mode => In_File, Name => Dict_Filename); + while not End_Of_File (Dict_File) loop + Read_Word := Get_Line (Dict_File); + if Length (Read_Word) = Word_Len then + Valid := True; + for Ix in 1 .. Word_Len loop + C := Element (Read_Word, Ix); + Valid := C in LC_Chars; + exit when not Valid; + end loop; + if Valid then Cands.Append (Read_Word); end if; + end if; + end loop; + Close (Dict_File); + return Cands; + end Load_Candidate_Words; + + function Mutate (Word : Unbounded_String; Dict : in out Dict_Vectors.Vector) + return Word_Vectors.Vector is + Mutations : Word_Vectors.Vector; + Poss_Word : Unbounded_String; + begin + for Ix in 1 .. Length (Word) loop + for Letter in LC_Chars loop + if Letter /= Element (Word, Ix) then + Poss_Word := Word; + Replace_Element (Poss_Word, Ix, Letter); + if Dict.Contains (Poss_Word) then + Mutations.Append (Poss_Word); + Dict.Delete (Dict.Find_Index (Poss_Word)); + end if; + end if; + end loop; + end loop; + return Mutations; + end Mutate; + + procedure Recurse_Tree (Start_Pos : Cursor; + Level : Positive; + Target : Unbounded_String; + Dict : in out Dict_Vectors.Vector) is + Pos : Cursor := Start_Pos; + Mutations : Word_Vectors.Vector; + New_Node : Word_Node_T; + begin + while not Solved and then Pos /= No_Element loop + if Element (Pos).Level = Level then + Mutations := Mutate (Element (Pos).Word, Dict); + if not Word_Vectors.Is_Empty (Mutations) then + for Word of Mutations loop + New_Node.Level := Level + 1; + New_Node.Word := Word; + Append_Child (Word_Tree, Pos, New_Node); + if Word = Target then + Solved := True; + Solution := Pos; + end if; + end loop; + end if; + end if; + if not Solved then + Recurse_Tree (First_Child (Pos), Level, Target, Dict); + end if; + Pos := Next_Sibling (Pos); + end loop; + end Recurse_Tree; + + procedure Ladder (Start_S, Target_S : String) is + Dictionary : Dict_Vectors.Vector; + Level : Positive := 1; + Word_Node : Word_Node_T; + Start, Target : Unbounded_String; + Start_Pos : Cursor; + Output : Unbounded_String; + begin + if Start_S'Length /= Target_S'Length then + Put_Line ("ERROR: Start and Target words must be same length."); + return; + end if; + Dictionary := Load_Candidate_Words (DICT_FILENAME, Start_S'Length); + Start := To_Unbounded_String (Start_S); + Target := To_Unbounded_String (Target_S); + Solved := False; + Word_Node.Level := 1; + Word_Node.Word := Start; + Word_Tree := Empty_Tree; + Word_Tree.Insert_Child (Word_Tree.Root, No_Element, Word_Node); + Start_Pos := Find (Word_Tree, Word_Node); + while Level <= MAX_DEPTH and then not Solved loop + Recurse_Tree (Start_Pos, Level, Target, Dictionary); + Level := @ + 1; + end loop; + if not Solved then + Put_Line (Start & " -> " & Target & " - No solution found at depth" & MAX_DEPTH'Image); + else + while not Is_Root (Solution) loop + Word_Node := Element (Solution); + Output := Word_Node.Word & " -> " & Output; + Solution := Parent (Solution); + end loop; + Put_Line (Output & Target); + end if; + end Ladder; +begin + Ladder ("boy", "man"); + Ladder ("girl", "lady"); + Ladder ("jane", "john"); + Ladder ("child", "adult"); + Ladder ("ada", "god"); + Ladder ("rust", "hell"); +end Word_Ladder; diff --git a/Task/Word-ladder/EasyLang/word-ladder.easy b/Task/Word-ladder/EasyLang/word-ladder.easy new file mode 100644 index 0000000000..b163ccbe21 --- /dev/null +++ b/Task/Word-ladder/EasyLang/word-ladder.easy @@ -0,0 +1,80 @@ +repeat + s$ = input + until s$ = "" + words$[] &= s$ +. +func hammingdist w1$ w2$ . + for i to len w1$ + if substr w1$ i 1 <> substr w2$ i 1 + cnt += 1 + if cnt = 2 + break 1 + . + . + . + return cnt +. +proc ladder a$ b$ . + # BFS + h = len a$ + for w$ in words$[] + if len w$ = h + w$[] &= w$ + if w$ = a$ + a = len w$[] + elif w$ = b$ + b = len w$[] + . + . + . + if a = 0 or b = 0 + print "Words are not in dictionary" + return + . + n = len w$[] + len prev[] n + todo[] = [ a ] + while len todo[] > 0 + for cur in todo[] + if cur = b + break 2 + . + for i to n + if prev[i] = 0 and hammingdist w$[cur] w$[i] = 1 + todon[] &= i + prev[i] = cur + . + . + . + swap todon[] todo[] + todon[] = [ ] + . + if cur = b + while cur <> a + seq$ = " -> " & w$[cur] & seq$ + cur = prev[cur] + . + seq$ = w$[cur] & seq$ + print seq$ + else + print "No path" + . +. +ladder "boy" "man" +ladder "girl" "lady" +ladder "jane" "john" +ladder "child" "adult" +ladder "ada" "god" +ladder "rust" "hell" +# +# the content of unixdict.txt +input_data +10th +. +ada +bay +ban +boy +god +man +. diff --git a/Task/Word-ladder/FreeBASIC/word-ladder.basic b/Task/Word-ladder/FreeBASIC/word-ladder.basic new file mode 100644 index 0000000000..80c423c846 --- /dev/null +++ b/Task/Word-ladder/FreeBASIC/word-ladder.basic @@ -0,0 +1,147 @@ +Type PathNode + word As String + parent As Integer +End Type + +Function FindIndex(words() As String, w As String) As Integer + For i As Integer = 0 To Ubound(words) + If words(i) = w Then Return i + Next + Return -1 +End Function + +Function OneAway(a As String, b As String) As Boolean + If Len(a) <> Len(b) Then Return False + Dim As Integer diff = 0 + For i As Integer = 1 To Len(a) + If Mid(a, i, 1) <> Mid(b, i, 1) Then + diff += 1 + If diff > 1 Then Return False ' Early exit optimization + End If + Next + Return diff = 1 +End Function + +Sub WordLadder(words() As String, startWord As String, endWord As String) + If startWord = endWord Then + Print startWord + Return + End If + If Len(startWord) <> Len(endWord) Then + Print startWord; " into "; endWord; " cannot be done." + Return + End If + + Dim As Integer i, n + ' Filter only words of the appropriate length + Dim As String possibles() + For i = 0 To Ubound(words) + If Len(words(i)) = Len(startWord) Then + n = Iif(Lbound(possibles)=0 And Ubound(possibles)=-1, 0, Ubound(possibles)+1) + Redim Preserve possibles(n) + possibles(n) = words(i) + End If + Next + + ' Check existence + Dim As Integer startIdx = FindIndex(possibles(), startWord) + If startIdx = -1 Then + Print startWord; " it is not in the dictionary." + Return + End If + Dim As Integer endIdx = FindIndex(possibles(), endWord) + If endIdx = -1 Then + Print endWord; " it is not in the dictionary." + Return + End If + + ' BFS algorithm + Redim As Integer queue(0) + Redim As Integer visited(Ubound(possibles)) + Redim As PathNode path(Ubound(possibles)) + For i = 0 To Ubound(visited) + visited(i) = 0 + path(i).parent = -1 + Next + + queue(0) = startIdx + visited(startIdx) = 1 + path(startIdx).word = possibles(startIdx) + path(startIdx).parent = -1 + + Dim As Integer head = 0, tail = 0 + Dim As Boolean found = False + + While head <= tail And Not found + Dim As Integer currIdx = queue(head) + head += 1 + For i = 0 To Ubound(possibles) + If visited(i) = 0 And OneAway(possibles(currIdx), possibles(i)) Then + visited(i) = 1 + path(i).word = possibles(i) + path(i).parent = currIdx + tail += 1 + Redim Preserve queue(tail) + queue(tail) = i + If i = endIdx Then + found = True + Exit For + End If + End If + Next + Wend + + ' Reconstruct and print the path if found + If found Then + Dim As String result() + Dim As Integer curIdx = endIdx + + Do While curIdx <> -1 + n = Iif(Lbound(result)=0 And Ubound(result)=-1, 0, Ubound(result)+1) + Redim Preserve result(n) + result(n) = possibles(curIdx) + curIdx = path(curIdx).parent + Loop + + ' Print path in reverse (from start to end) + For i = Ubound(result) To 0 Step -1 + Print result(i); + If i > 0 Then Print " -> "; + Next + Print + Else + Print startWord; " into "; endWord; " cannot be done." + End If +End Sub + +Sub main() + Dim As String words() + Dim As Integer i, n + + ' Read dictionary + Dim As Integer ff = Freefile + Dim As String word + If Open("unixdict.txt" For Input As #ff) = 0 Then + Do Until Eof(ff) + Line Input #ff, word + n = Iif(Lbound(words)=0 And Ubound(words)=-1, 0, Ubound(words)+1) + Redim Preserve words(n) + words(n) = word + Loop + Close #ff + Else + Print "Error reading file" + Exit Sub + End If + + Dim As String pairs(7, 1) = { _ + {"boy", "man"}, {"girl", "lady"}, {"john", "jane"}, {"child", "adult"}, _ + {"cat", "dog"}, {"lead", "gold"}, {"white", "black"}, {"bubble", "tickle"} } + For i = 0 To Ubound(pairs, 1) + WordLadder(words(), pairs(i, 0), pairs(i, 1)) + Next +End Sub + +main() + +Sleep diff --git a/Task/Word-ladder/JavaScript/word-ladder.js b/Task/Word-ladder/JavaScript/word-ladder.js new file mode 100644 index 0000000000..9d4d2a94b7 --- /dev/null +++ b/Task/Word-ladder/JavaScript/word-ladder.js @@ -0,0 +1,73 @@ +// Returns true if strings s1 and s2 differ by one character. +function oneAway(s1, s2) { + if (s1.length !== s2.length) return false; + let diff = 0; + for (let i = 0; i < s1.length; i++) { + if (s1[i] !== s2[i]) { + if (diff) return false; + diff++; + } + } + return diff === 1; +} + +// Join a sequence of strings into a single string using the given separator. +function join(arr, separator) { + return arr.join(separator); +} + +// If possible, print the shortest chain of single-character modifications that +// leads from "from" to "to", with each intermediate step being a valid word. +// This is an application of breadth-first search. +function wordLadder(words, from, to) { + const poss = words.get(from.length); + if (poss) { + const queue = [[from]]; + while (queue.length) { + const curr = queue.shift(); + for (let i = 0; i < poss.length; i++) { + const word = poss[i]; + if (!oneAway(word, curr[curr.length - 1])) continue; + if (word === to) { + console.log(join(curr.concat(to), " -> ")); + return true; + } + queue.push(curr.concat(word)); + poss.splice(i, 1); + i--; + } + } + } + console.log(`${from} into ${to} cannot be done.`); + return false; +} + +// Main logic +async function main() { + const words = new Map(); + // Assuming unixdict.txt is available as a text file + // In a real Node.js environment, you would use fs.readFileSync or similar + // For browser, you would fetch the file + // Here, we simulate loading the dictionary + const dictionary = [ + "boy", "man", "girl", "lady", "john", "jane", "child", "adult", + "cat", "cot", "dot", "dog", "lead", "load", "goad", "gold", + "white", "whale", "black", "blake", "bubble", "bubbly", "rubble", "tickle" + ]; + for (const word of dictionary) { + if (!words.has(word.length)) words.set(word.length, []); + words.get(word.length).push(word); + } + + wordLadder(words, "boy", "man"); + wordLadder(words, "girl", "lady"); + wordLadder(words, "john", "jane"); + wordLadder(words, "child", "adult"); + wordLadder(words, "cat", "dog"); + wordLadder(words, "lead", "gold"); + wordLadder(words, "white", "black"); + wordLadder(words, "bubble", "tickle"); +} + +// Uncomment to run in a Node.js environment +main(); diff --git a/Task/Word-ladder/Julia/word-ladder.julia b/Task/Word-ladder/Julia/word-ladder.jl similarity index 100% rename from Task/Word-ladder/Julia/word-ladder.julia rename to Task/Word-ladder/Julia/word-ladder.jl diff --git a/Task/Word-ladder/Mathematica/word-ladder.math b/Task/Word-ladder/Mathematica/word-ladder.math index 01c6d2b2cf..e313283b9f 100644 --- a/Task/Word-ladder/Mathematica/word-ladder.math +++ b/Task/Word-ladder/Mathematica/word-ladder.math @@ -1,15 +1,14 @@ -db=DeleteDuplicates[RemoveDiacritics[ToLowerCase[Select[DictionaryLookup[],StringLength/*EqualTo[3]]]]]; -sel=Select[Subsets[db,{2}],HammingDistance[#[[1]],#[[2]]]==1&]; -g=Graph[db,UndirectedEdge@@@sel]; -FindShortestPath[g,"boy","man"] +words = ReadList["unixdict.txt", Word]; -db=DeleteDuplicates[RemoveDiacritics[ToLowerCase[Select[DictionaryLookup[],StringLength/*EqualTo[4]]]]]; -sel=Select[Subsets[db,{2}],HammingDistance[#[[1]],#[[2]]]==1&]; -g=Graph[db,UndirectedEdge@@@sel]; -FindShortestPath[g,"girl","lady"] -FindShortestPath[g,"john","jane"] +wordLadder[words_, start_, target_] := Module[{wordSelection, graph, path, noSolution = "impossible"}, + If[StringLength[start] != StringLength[target], Return[noSolution]]; + wordSelection = Select[words, StringLength[#] == StringLength[start]&]; + graph = UndirectedEdge @@@ Select[Subsets[wordSelection, {2}], HammingDistance @@ # == 1 &]; + If[! SubsetQ[VertexList[graph], {start, target}], Return[noSolution]]; + path = FindShortestPath[graph, start, target]; + If[path == {}, Return[noSolution]]; + path]; -db=DeleteDuplicates[RemoveDiacritics[ToLowerCase[Select[DictionaryLookup[],StringLength/*EqualTo[5]]]]]; -sel=Select[Subsets[db,{2}],HammingDistance[#[[1]],#[[2]]]==1&]; -g=Graph[db,UndirectedEdge@@@sel]; -FindShortestPath[g,"child","adult"] +tests = {{"boy", "man"}, {"girl", "lady"}, {"john", "jane"}, {"child", "adult"}}; +Map[{#[[1]] <> " -> " <> #[[2]] <> ": ", wordLadder[words, #[[1]], #[[2]]]}&, tests] // + TableForm[#, TableDepth -> 2]& diff --git a/Task/Word-ladder/Refal/word-ladder.refal b/Task/Word-ladder/Refal/word-ladder.refal new file mode 100644 index 0000000000..4da2fac7e6 --- /dev/null +++ b/Task/Word-ladder/Refal/word-ladder.refal @@ -0,0 +1,95 @@ +$ENTRY Go { + , : e.Dict + = + + + ; +}; + +DisplayLadder { + (e.Dict) (e.From) (e.To), + e.From ' -> ' e.To ': ': e.Header, + : { + Impossible = ; + Result e.Words = ') e.Words>>; + }; +}; + +Join { + (e.Join) = ; + (e.Join) (e.Word) = e.Word; + (e.Join) (e.Word) e.Words = e.Word e.Join ; +}; + +ReadFile { + s.Chan e.File = + + ; + (s.Chan), : { + 0 = ; + e.Line = (e.Line) ; + }; +}; + +Filter { + (e.Fn) = ; + (e.Fn) t.Item e.Items, : { + True = t.Item ; + False = ; + }; +}; + +SameLen { + (e.Word1) (e.Word2), + : s.Len e.Word1, + : s.Len e.Word2 = True; + (e.Word1) (e.Word2) = False; +}; + +Diffs { + () () = 0; + (s.X e.Word1) (s.X e.Word2) = ; + (s.X e.Word1) (s.Y e.Word2) = <+ 1 >; +}; + +OneDiff { + t.Word1 t.Word2, : { + 1 = True; + s.Diffs = False; + }; +}; + +Ladder { + (e.Dict) t.From t.To, + : e.Dict2 = + ; +}; + +Ladder2 { + (e.Ladders) (e.Dict) t.To, + e.Ladders: e.X (e.Words t.To) e.Y = Result e.Words t.To; + + (e.Ladders) () t.To = Impossible; + () (e.Dict) t.To = Impossible; + + ((e.Ladder) e.Ladders) (e.Dict) t.To, + e.Ladder: e.1 t.Last, + : e.NextWords, + : e.NextDict, + : e.NextLadders + = ; +}; + +RemoveAll { + (e.Remove) = ; + (e.Remove) t.Word e.Words, e.Remove: { + e.X t.Word e.Y = ; + e.Remove = t.Word ; + }; +}; + +AddAll { + (e.Ladder) = ; + (e.Ladder) t.Word e.Words = + (e.Ladder t.Word) ; +}; diff --git a/Task/Word-ladder/Rust/word-ladder.rs b/Task/Word-ladder/Rust/word-ladder.rs new file mode 100644 index 0000000000..9ca4f84e2b --- /dev/null +++ b/Task/Word-ladder/Rust/word-ladder.rs @@ -0,0 +1,51 @@ +use std::collections::HashSet; +use std::fs; + +fn targeted_mutations(word: &str, targ: &str, hs: &HashSet<&str>) -> Vec> { + let mut working = [[word.to_string()].to_vec()].to_vec(); + let mut tried = HashSet::new(); + while working.iter().all(|a| a.last().unwrap() != &targ) { + let mut new_working: Vec> = vec![]; + for arr in working { + let s = arr.last().unwrap(); + tried.insert(s.to_owned()); + for j in 0..s.len() { + for c in 'a'..='z' { + let w = String::new() + &s[..j] + &c.to_string() + &s[j + 1..]; + if hs.contains(w.as_str()) && !tried.contains(&w) { + let mut a = arr.iter().map(|st| st.to_string()).collect::>(); + a.push(w); + new_working.push(a); + } + } + } + } + if new_working.is_empty() { + return [["This cannot be done.".to_string()].to_vec()].to_vec(); + } + working = new_working; + } + return working + .iter() + .filter(|a| !a.is_empty() && a.last().unwrap() == targ) + .map(|x| x.to_owned()) + .collect::>>(); +} + +fn main() { + let wordsfile = fs::read_to_string("unixdict.txt").unwrap().to_lowercase(); + let dict: HashSet<&str> = wordsfile.split_whitespace().into_iter().collect(); + println!("boy to man: {:?}", targeted_mutations("boy", "man", &dict)); + println!( + "girl to lady: {:?}", + targeted_mutations("girl", "lady", &dict) + ); + println!( + "john to jane: {:?}", + targeted_mutations("john", "jane", &dict) + ); + println!( + "child to adult: {:?}", + targeted_mutations("child", "adult", &dict) + ); +} diff --git a/Task/Word-ladder/SETL/word-ladder.setl b/Task/Word-ladder/SETL/word-ladder.setl new file mode 100644 index 0000000000..200d0c2766 --- /dev/null +++ b/Task/Word-ladder/SETL/word-ladder.setl @@ -0,0 +1,45 @@ +program word_ladder; + dict := read_dictionary("unixdict.txt"); + testpairs := [['boy', 'man'], ['girl', 'lady'], ['john', 'jane'], ['child', 'adult']]; + + loop for [fromWord, toWord] in testpairs do + l := ladder(dict, fromWord, toWord); + if l = om then + print(fromWord, '->', toWord, 'impossible'); + else + print(fromWord, '->', toWord, l); + end if; + end loop; + + proc ladder(dict, fromWord, toWord); + dict := {word : word in dict | #word = #fromWord}; + ladders := [[fromWord]]; + dict less:= fromWord; + loop while ladders /= [] do + l fromb ladders; + next := {word : word in onediff(dict, l(#l))}; + dict -:= next; + nextls := [l + [word] : word in next]; + if exists l in nextls | l(#l) = toWord then + return l; + end if; + ladders +:= nextls; + end loop; + return om; + end proc; + + proc onediff(rw dict, word); + return {other : other in dict | #other = #word and diffs(word, other) = 1}; + end proc; + + proc diffs(word1, word2); + return +/[if word1(i) = word2(i) then 0 else 1 end : i in [1..#word1]]; + end proc; + + proc read_dictionary(file); + dictfile := open(file, 'r'); + dict := {getline(dictfile) : until eof(dictfile)}; + close(dictfile); + return dict; + end proc; +end program; diff --git a/Task/Word-search/Ada/word-search.adb b/Task/Word-search/Ada/word-search.adb new file mode 100644 index 0000000000..712854b9c1 --- /dev/null +++ b/Task/Word-search/Ada/word-search.adb @@ -0,0 +1,259 @@ +pragma Ada_2022; +with Ada.Containers; use Ada.Containers; +with Ada.Containers.Vectors; +with Ada.Numerics.Discrete_Random; +with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Text_IO.Unbounded_IO; use Ada.Text_IO.Unbounded_IO; + +procedure Word_Search is + + MIN_WORDS : constant Positive := 25; + MIN_WORD_LEN : constant Positive := 3; + MAX_WORD_LEN : constant Positive := 9; + SIDE_LEN : constant Positive := 10; + MESSAGE : constant String := "ROSETTACODE"; + DICT_FILENAME : constant String := "unixdict.txt"; + + type Directions is (N, NE, E, SE, S, SW, W, NW); + type Move is record + DX, DY : Integer; + end record; + type Moves_Arr is array (Directions) of Move; + Moves : constant Moves_Arr := [ + N => (0, -1), NE => (1, -1), E => (1, 0), SE => (1, 1), + S => (0, 1), SW => (-1, 1), W => (-1, 0), NW => (-1, -1) + ]; + subtype Grid_Dimension is Positive range 1 .. SIDE_LEN; + type Matrix is array (Grid_Dimension, Grid_Dimension) of Character; + subtype LC_Chars is Character range 'a' .. 'z'; + subtype Valid_Lengths is Positive range MIN_WORD_LEN .. MAX_WORD_LEN; + + package Word_Vectors is new Ada.Containers.Vectors (Positive, Unbounded_String); + type Dictionary is array (Valid_Lengths) of Word_Vectors.Vector; + Dict : Dictionary; + + type Placement is record + Word : Unbounded_String; + Start : Unbounded_String; + end record; + package Placement_Vectors is new Ada.Containers.Vectors (Positive, Placement); + Placings : Placement_Vectors.Vector; + + subtype Ten_K is Positive range 1 .. 10000; + package Rand_Dimension is new Ada.Numerics.Discrete_Random (Grid_Dimension); + package Rand_Dir is new Ada.Numerics.Discrete_Random (Directions); + package Rand_Len is new Ada.Numerics.Discrete_Random (Valid_Lengths); + package Rand_10k is new Ada.Numerics.Discrete_Random (Ten_K); + Dimension_Gen : Rand_Dimension.Generator; + Dir_Gen : Rand_Dir.Generator; + Len_Gen : Rand_Len.Generator; + Ten_K_Gen : Rand_10k.Generator; + + procedure Load_Dictionary (Filename : String) is + Dict_File : File_Type; + Dict_Word : Unbounded_String; + Dict_Word_Len : Positive; + Word_OK : Boolean; + begin + Open (File => Dict_File, Mode => In_File, Name => Filename); + while not End_Of_File (Dict_File) loop + Dict_Word := Get_Line (Dict_File); + Dict_Word_Len := Length (Dict_Word); + if Dict_Word_Len >= MIN_WORD_LEN and then + Dict_Word_Len <= MAX_WORD_LEN + then + Word_OK := True; + for C of To_String (Dict_Word) loop + if C not in LC_Chars then + Word_OK := False; + exit; + end if; + end loop; + if Word_OK then + Dict (Dict_Word_Len).Append (Dict_Word); + end if; + end if; + end loop; + end Load_Dictionary; + + function Pick_Random_Word return Unbounded_String is + Word_Length : Positive := Rand_Len.Random (Len_Gen); + Rand : constant Natural := Rand_10k.Random (Ten_K_Gen); + Word_Ix : Positive; + begin + Word_Length := Rand_Len.Random (Len_Gen); + if Word_Length > 4 then -- Reduce number of words > 4 chars + Word_Length := Rand_Len.Random (Len_Gen); + end if; + Word_Ix := Positive (Rand) mod (Positive (Dict (Word_Length).Length) - 1) + 1; + return Dict (Word_Length) (Word_Ix); + end Pick_Random_Word; + + function Not_Too_Long (X, Y : Grid_Dimension; Len : Positive; Dir : Directions) return Boolean is + begin + case Dir is + when N => return Y - Len > 0; + when S => return Y + Len <= SIDE_LEN; + when E => return X + Len <= SIDE_LEN; + when W => return X - Len > 0; + when NE => return X + Len <= SIDE_LEN and then Y - Len > 0; + when SW => return Y + Len <= SIDE_LEN and then X - Len > 0; + when SE => return Y + Len <= SIDE_LEN and then X + Len <= SIDE_LEN; + when NW => return Y - Len > 0 and then X - Len > 0; + end case; + end Not_Too_Long; + + function Is_Empty (G : Matrix; Row, Col : Positive) return Boolean is + (G (Row, Col) = ' '); + + function Count_Empties (G : Matrix) return Natural is + Count : Natural := 0; + begin + for Row in Grid_Dimension loop + for Col in Grid_Dimension loop + Count := Count + (if Is_Empty (G, Row, Col) then 1 else 0); + end loop; + end loop; + return Count; + end Count_Empties; + + function Can_Place (G : Matrix; X, Y : Grid_Dimension; Word : Unbounded_String; Dir : Directions) + return Boolean is + GX : Grid_Dimension := X; + GY : Grid_Dimension := Y; + Len : constant Positive := Length (Word); + begin + for C in 1 .. Len loop + if not Is_Empty (G, GX, GY) and then + G (GX, GY) /= Element (Word, C) + then + return False; + else + GX := GX + Moves (Dir).DX; + GY := GY + Moves (Dir).DY; + end if; + end loop; + return True; + end Can_Place; + + procedure Insert_Word (G : in out Matrix; + X, Y : Grid_Dimension; + Dir : Directions; + Word : Unbounded_String) is + -- We assume it fits. You've checked first haven't you! + GX : Grid_Dimension := X; + GY : Grid_Dimension := Y; + begin + for C in 1 .. Length (Word) loop + G (GX, GY) := Element (Word, C); + GX := GX + Moves (Dir).DX; + GY := GY + Moves (Dir).DY; + end loop; + end Insert_Word; + + function Try_To_Place_Word (G : in out Matrix; Word : Unbounded_String; Max_Tries : Positive) + return Boolean is + -- Attempt to place the given word in the grid, return success or failure. + X1, Y1 : Grid_Dimension; + Dir : Directions; + Try : Positive := 1; + Place : Placement; + begin + while Try <= Max_Tries loop + X1 := Rand_Dimension.Random (Dimension_Gen); + Y1 := Rand_Dimension.Random (Dimension_Gen); + Dir := Rand_Dir.Random (Dir_Gen); + if Not_Too_Long (X1, Y1, Length (Word), Dir) and then + Can_Place (G, X1, Y1, Word, Dir) + then + Insert_Word (G, X1, Y1, Dir, Word); + Place.Word := Word; + Place.Start := To_Unbounded_String (X1'Image & LC_Chars'Val (Integer (Y1) + 64)); + Placings.Append (Place); + return True; + end if; + Try := Try + 1; + end loop; + return False; + end Try_To_Place_Word; + + procedure Print_Matrix (M : Matrix) is + begin + Put_Line (" A B C D E F G H I J"); New_Line; + for Row in Grid_Dimension loop + Put (Row'Image); + Set_Col (6); + for Col in Grid_Dimension loop + Put (M (Row, Col) & " "); + end loop; + New_Line; + end loop; + New_Line; + end Print_Matrix; + + function Place_Message (G : in out Matrix; Msg : String) return Boolean is + -- Attempt to put message in grid, return False if unable. + Msg_Posn : Positive := 1; + begin + for Row in Grid_Dimension loop + for Col in Grid_Dimension loop + if Is_Empty (G, Row, Col) then + G (Row, Col) := Msg (Msg_Posn); + if Msg_Posn = Msg'Length then + return True; + else + Msg_Posn := Msg_Posn + 1; + end if; + end if; + end loop; + end loop; + return False; + end Place_Message; + + Grid : Matrix; + Words_Placed : Natural; + Message_Placed : Boolean; + A_Word : Unbounded_String; + Attempt : Positive; + Col : Positive_Count := 1; +begin + Load_Dictionary (DICT_FILENAME); + Rand_Dimension.Reset (Dimension_Gen); + Rand_Dir.Reset (Dir_Gen); + Rand_Len.Reset (Len_Gen); + Rand_10k.Reset (Ten_K_Gen); + loop + Grid := [others => [others => ' ']]; + Words_Placed := 0; Message_Placed := False; Placings.Clear; + Attempt := 1; + Builder : + loop + A_Word := Pick_Random_Word; + if Try_To_Place_Word (Grid, A_Word, 50) then + Words_Placed := @ + 1; + end if; + if Count_Empties (Grid) = MESSAGE'Length then + if Place_Message (Grid, MESSAGE) then + Message_Placed := True; + exit Builder; + end if; + elsif Count_Empties (Grid) < MESSAGE'Length then + -- Put_Line ("No room for message, giving up."); + exit Builder; + elsif Attempt > 1000 then + Put_Line ("Giving up after 1000 tries."); + exit Builder; + end if; + Attempt := Attempt + 1; + end loop Builder; + exit when Words_Placed >= MIN_WORDS and then Message_Placed; + end loop; + Print_Matrix (Grid); + Put_Line ("Words placed:" & Words_Placed'Image); + for P of Placings loop + Set_Col (Col); Put (P.Word); + Set_Col (Col + 9); Put (P.Start); + Col := (if Col < 61 then Col + 20 else 1); + end loop; +end Word_Search; diff --git a/Task/Word-search/Dart/word-search.dart b/Task/Word-search/Dart/word-search.dart new file mode 100644 index 0000000000..03806a7acc --- /dev/null +++ b/Task/Word-search/Dart/word-search.dart @@ -0,0 +1,79 @@ +import 'dart:io'; +import 'package:more/more.dart'; + +var words = RegExp(r'^[a-z]*$'); +const n8 = [ + [0, 1], + [0, -1], + [1, 0], + [-1, 0], + [1, 1], + [1, -1], + [-1, 1], + [-1, -1] +]; + +main() { + var text = File('bin/_other/unixdict.txt') + .readAsLinesSync() + .where((e) => words.hasMatch(e)) + .where((e) => e.length > 2); + + var done = false; + while (!done) { + var square = List.generate(10, (e) => "..........".split('')); + var used = []; + var starts = >[]; + var ends = >[]; + + getNexts() => [ + for (var r in square.indexed()) + for (var c in r.value.indexed()) + if (c.value == '.') [r.index, c.index] + ]; + var nexts = getNexts(); + while (nexts.length > 11) { + // Pick a start and a direction, then fit longest allowed word or loop. + var here = nexts.atRandom(); + var dir = n8.atRandom(); + var len = 1; + var target = square[here.first][here.last]; + while (inBounds( + [here.first + len * dir.first, here.last + len * dir.last])) { + target += + square[here.first + len * dir.first][here.last + len * dir.last]; + len += 1; + } + if (len >= 7) continue; // Stop the grid getting too full. + if (len <= 3) continue; + var reg = RegExp('^$target\$'); + var cands = text.where((e) => reg.hasMatch(e)); + if (cands.isEmpty) continue; + + var cand = cands.atRandom(); + for (var i in 0.to(cand.length)) { + square[here.first + i * dir.first][here.last + i * dir.last] = cand[i]; + } + used.add(cand); + starts.add(here); + ends.add([ + here.first + (len - 1) * dir.first, + here.last + (len - 1) * dir.last + ]); + nexts = getNexts(); + } + if (nexts.length < 11) continue; + if (used.length < 25) continue; + var filler = 'ROSETTACODE'.split(''); + for (var n in nexts.indexed()) { + square[n.value.first][n.value.last] = filler[n.index]; + } + square.forEach(print); + for (var i in 0.to(used.length)) { + print('${used[i]}\t ${starts[i]}\t${ends[i]}'); + } + done = true; + } +} + +inBounds(List pos) => pos.first.between(0, 9) && pos.last.between(0, 9); diff --git a/Task/Word-search/Fortran/word-search.f b/Task/Word-search/Fortran/word-search.f new file mode 100644 index 0000000000..0e2d7be6dd --- /dev/null +++ b/Task/Word-search/Fortran/word-search.f @@ -0,0 +1,509 @@ +program word_search_rosetta_complete + implicit none + + integer, parameter :: GRID_SIZE = 10 + integer, parameter :: MAX_WORDS = 5000 + integer, parameter :: MAX_WORD_LEN = 20 + integer, parameter :: MIN_PLACED = 25 + + character(len=1) :: grid(GRID_SIZE, GRID_SIZE) + character(len=MAX_WORD_LEN) :: words(MAX_WORDS), original_words(MAX_WORDS) + integer :: word_lens(MAX_WORDS), original_lens(MAX_WORDS) + integer :: num_words + integer :: length_limits(3:10) + + type :: word_placement + character(len=MAX_WORD_LEN) :: word + integer :: row, col + integer :: dx, dy + end type + + type(word_placement) :: placed(200), all_found(500) + integer :: num_placed, num_found + + integer :: attempt + + call init_random_seed() + call load_words(original_words, original_lens, num_words) + print '(A,I0,A)', "Loaded ", num_words, " valid words" + + ! Try to create puzzle + do attempt = 1, 10 + words = original_words + word_lens = original_lens + + call create_puzzle(words, word_lens, num_words, grid, placed, num_placed) + + ! VB stops when we have 25+ words (success!) + if (num_placed >= MIN_PLACED) then + print '(A,I0)', "Success on attempt ", attempt + + ! Find ALL words embedded in the final grid + call find_all_words(original_words, original_lens, num_words, grid, all_found, num_found) + + call print_results(grid, placed, num_placed, all_found, num_found) + exit + end if + + print '(A,I0,A,I0,A)', "Attempt ", attempt, " placed ", num_placed, " words, retrying..." + end do + +contains + + subroutine init_random_seed() + integer :: seed_size, clock, i + integer, allocatable :: seed(:) + + call random_seed(size=seed_size) + allocate(seed(seed_size)) + call system_clock(count=clock) + seed = clock + 37 * [(i, i=1, seed_size)] + call random_seed(put=seed) + deallocate(seed) + end subroutine + + subroutine load_words(words, word_lens, num_words) + character(len=*), intent(out) :: words(:) + integer, intent(out) :: word_lens(:) + integer, intent(out) :: num_words + character(len=MAX_WORD_LEN) :: word + integer :: ios, i + logical :: valid + + num_words = 0 + + open(10, file='unixdict.txt', status='old', action='read', iostat=ios) + if (ios /= 0) then + print *, "Error opening unixdict.txt" + stop + end if + + do + read(10, '(A)', iostat=ios) word + if (ios /= 0) exit + + word = trim(word) + if (len_trim(word) <= 2 .or. len_trim(word) > 10) cycle + + valid = .true. + do i = 1, len_trim(word) + if (word(i:i) < 'a' .or. word(i:i) > 'z') then + valid = .false. + exit + end if + end do + + if (valid) then + num_words = num_words + 1 + if (num_words > MAX_WORDS) exit + words(num_words) = trim(word) + word_lens(num_words) = len_trim(word) + end if + end do + + close(10) + end subroutine + + subroutine shuffle_words(words, word_lens, num_words) + character(len=*), intent(inout) :: words(:) + integer, intent(inout) :: word_lens(:) + integer, intent(in) :: num_words + integer :: i, r, temp_len + character(len=MAX_WORD_LEN) :: temp_word + real :: rr + + do i = num_words, 2, -1 + call random_number(rr) + r = int(rr * i) + 1 + + temp_word = words(i) + words(i) = words(r) + words(r) = temp_word + + temp_len = word_lens(i) + word_lens(i) = word_lens(r) + word_lens(r) = temp_len + end do + end subroutine + + function count_spaces(grid) result(count) + character(len=1), intent(in) :: grid(:,:) + integer :: count, i, j + + count = 0 + do i = 1, GRID_SIZE + do j = 1, GRID_SIZE + if (grid(j, i) == ' ') count = count + 1 + end do + end do + end function + + subroutine create_puzzle(words, word_lens, num_words, grid, placed, num_placed) + character(len=*), intent(inout) :: words(:) + integer, intent(inout) :: word_lens(:) + integer, intent(in) :: num_words + character(len=1), intent(out) :: grid(:,:) + type(word_placement), intent(out) :: placed(:) + integer, intent(out) :: num_placed + + integer :: i + real :: r + + ! Initialize grid + grid = ' ' + num_placed = 0 + + ! Pre-seed ROSETTACODE letters (VB strategy) + call random_number(r) + grid(int(r * 5) + 6, 1) = 'R' + + call random_number(r) + grid(int(r * 9) + 2, 2) = 'O' + + call random_number(r) + grid(int(r * 9) + 2, 3) = 'S' + + call random_number(r) + grid(int(r * 9) + 2, 4) = 'E' + + grid(2, 5) = 'T' + grid(10, 5) = 'T' + + call random_number(r) + grid(int(r * 10) + 1, 6) = 'A' + + call random_number(r) + grid(int(r * 10) + 1, 7) = 'C' + + call random_number(r) + grid(int(r * 10) + 1, 8) = 'O' + + call random_number(r) + grid(int(r * 10) + 1, 9) = 'D' + + call random_number(r) + grid(int(r * 10) + 1, 10) = 'E' + + ! Set length limits (pack the grid EXTREMELY full like VB) + length_limits(3) = 500 ! VB had 200 - go even higher + length_limits(4) = 100 + length_limits(5) = 50 + length_limits(6) = 30 + length_limits(7) = 20 + length_limits(8) = 10 + length_limits(9) = 5 + length_limits(10) = 3 + + ! Shuffle words + call shuffle_words(words, word_lens, num_words) + + ! Place words systematically (VB strategy - FILL THE GRID!) + do i = 1, num_words + ! VB stops when grid is completely full + if (count_spaces(grid) == 0) exit + + ! Check length limit + if (word_lens(i) >= 3 .and. word_lens(i) <= 10) then + if (length_limits(word_lens(i)) > 0) then + if (place_word_systematic(words(i), word_lens(i), grid, placed, num_placed)) then + length_limits(word_lens(i)) = length_limits(word_lens(i)) - 1 + end if + end if + end if + end do + + ! Fill remaining spaces with random lowercase + call fill_remaining(grid) + end subroutine + + logical function place_word_systematic(word, word_len, grid, placed, num_placed) + character(len=*), intent(in) :: word + integer, intent(in) :: word_len + character(len=1), intent(inout) :: grid(:,:) + type(word_placement), intent(inout) :: placed(:) + integer, intent(inout) :: num_placed + + integer :: start_pos, test_num, spot, x, y, d, dir_test + integer :: dx(0:7), dy(0:7) + integer :: rdir, rdd + real :: r + + ! Direction arrays + dx = [1, 1, 0, -1, -1, -1, 0, 1] + dy = [0, 1, 1, 1, 0, -1, -1, -1] + + place_word_systematic = .false. + + ! Random starting position + call random_number(r) + start_pos = int(r * 100) + + ! Random direction to traverse grid + call random_number(r) + if (r < 0.5) then + rdir = -1 + else + rdir = 1 + end if + + ! Try all 100 positions + do test_num = 0, 99 + spot = mod(start_pos + test_num * rdir + 100, 100) + y = spot / 10 + 1 + x = mod(spot, 10) + 1 + + ! If first letter matches or space is empty + if (grid(x, y) == word(1:1) .or. grid(x, y) == ' ' .or. & + (grid(x, y) >= 'A' .and. grid(x, y) <= 'Z' .and. & + char(ichar(grid(x, y)) + 32) == word(1:1))) then + + ! Try all 8 directions + call random_number(r) + d = int(r * 8) + call random_number(r) + if (r < 0.5) then + rdd = -1 + else + rdd = 1 + end if + + do dir_test = 0, 7 + d = mod(d + dir_test * rdd + 8, 8) + + if (can_place_vb(word, word_len, x, y, dx(d), dy(d), grid)) then + call place_word_vb(word, word_len, x, y, dx(d), dy(d), grid) + num_placed = num_placed + 1 + placed(num_placed)%word = trim(word) + placed(num_placed)%col = x + placed(num_placed)%row = y + placed(num_placed)%dx = dx(d) + placed(num_placed)%dy = dy(d) + place_word_systematic = .true. + return + end if + end do + end if + end do + end function + + logical function can_place_vb(word, word_len, x, y, dx, dy, grid) + character(len=*), intent(in) :: word + integer, intent(in) :: word_len, x, y, dx, dy + character(len=1), intent(in) :: grid(:,:) + + integer :: i, cx, cy + logical :: fills_something + character(len=1) :: grid_char + + can_place_vb = .false. + fills_something = .false. + + ! Check bounds + do i = 0, word_len - 1 + cx = x + i * dx + cy = y + i * dy + if (cx < 1 .or. cx > GRID_SIZE .or. cy < 1 .or. cy > GRID_SIZE) return + end do + + ! Check if can place and if fills at least one space + do i = 0, word_len - 1 + cx = x + i * dx + cy = y + i * dy + grid_char = grid(cx, cy) + + if (grid_char == ' ') then + fills_something = .true. + else if (grid_char /= word(i+1:i+1)) then + ! Allow uppercase match + if (grid_char >= 'A' .and. grid_char <= 'Z') then + if (char(ichar(grid_char) + 32) /= word(i+1:i+1)) return + else + return + end if + end if + end do + + can_place_vb = fills_something + end function + + subroutine place_word_vb(word, word_len, x, y, dx, dy, grid) + character(len=*), intent(in) :: word + integer, intent(in) :: word_len, x, y, dx, dy + character(len=1), intent(inout) :: grid(:,:) + + integer :: i, cx, cy + + do i = 0, word_len - 1 + cx = x + i * dx + cy = y + i * dy + ! Only place lowercase if empty or already matches + if (grid(cx, cy) == ' ' .or. grid(cx, cy) == word(i+1:i+1)) then + grid(cx, cy) = word(i+1:i+1) + end if + end do + end subroutine + + subroutine fill_remaining(grid) + character(len=1), intent(inout) :: grid(:,:) + integer :: i, j + real :: r + + do i = 1, GRID_SIZE + do j = 1, GRID_SIZE + if (grid(j, i) == ' ') then + call random_number(r) + grid(j, i) = char(int(r * 26) + ichar('a')) + end if + end do + end do + end subroutine + + subroutine find_all_words(words, word_lens, num_words, grid, all_found, num_found) + character(len=*), intent(in) :: words(:) + integer, intent(in) :: word_lens(:) + integer, intent(in) :: num_words + character(len=1), intent(in) :: grid(:,:) + type(word_placement), intent(out) :: all_found(:) + integer, intent(out) :: num_found + + integer :: i, x, y, d, j, cx, cy + integer :: dx(0:7), dy(0:7) + character(len=MAX_WORD_LEN) :: template + logical :: matches + + dx = [1, 1, 0, -1, -1, -1, 0, 1] + dy = [0, 1, 1, 1, 0, -1, -1, -1] + + num_found = 0 + + do i = 1, num_words + do y = 1, GRID_SIZE + do x = 1, GRID_SIZE + ! Check if first letter matches (case-insensitive) + if (grid(x, y) /= words(i)(1:1) .and. & + char(ichar(grid(x, y)) - 32) /= char(ichar(words(i)(1:1)) - 32)) cycle + + do d = 0, 7 + ! Check bounds + cx = x + (word_lens(i) - 1) * dx(d) + cy = y + (word_lens(i) - 1) * dy(d) + if (cx < 1 .or. cx > GRID_SIZE .or. cy < 1 .or. cy > GRID_SIZE) cycle + + ! Build template + template = '' + do j = 0, word_lens(i) - 1 + cx = x + j * dx(d) + cy = y + j * dy(d) + template(j+1:j+1) = grid(cx, cy) + end do + + ! Check match (case-insensitive) + matches = .true. + do j = 1, word_lens(i) + if (template(j:j) /= words(i)(j:j) .and. & + char(ichar(template(j:j)) - 32) /= char(ichar(words(i)(j:j)) - 32)) then + matches = .false. + exit + end if + end do + + if (matches) then + num_found = num_found + 1 + if (num_found > 500) return + all_found(num_found)%word = trim(words(i)) + all_found(num_found)%col = x + all_found(num_found)%row = y + all_found(num_found)%dx = dx(d) + all_found(num_found)%dy = dy(d) + end if + end do + end do + end do + end do + end subroutine + + subroutine print_results(grid, placed, num_placed, all_found, num_found) + character(len=1), intent(in) :: grid(:,:) + type(word_placement), intent(in) :: placed(:), all_found(:) + integer, intent(in) :: num_placed, num_found + + integer :: i, j, uppercase_count + character(len=20) :: dir_name + + print * + print *, "Word Search Puzzle (10x10)" + print *, "==========================" + print * + + write(*, '(A)', advance='no') " " + do j = 0, 9 + write(*, '(I2)', advance='no') j + end do + print * + print * + + do i = 1, GRID_SIZE + write(*, '(I3,A)', advance='no') i-1, " " + do j = 1, GRID_SIZE + write(*, '(A2)', advance='no') grid(j, i) + end do + print * + end do + + uppercase_count = 0 + do i = 1, GRID_SIZE + do j = 1, GRID_SIZE + if (grid(j, i) >= 'A' .and. grid(j, i) <= 'Z') uppercase_count = uppercase_count + 1 + end do + end do + + print * + print '(A,I0)', "ROSETTACODE letters: ", uppercase_count + print * + print '(A,I0,A)', "Words placed: ", num_placed + print '(A,I0,A)', "Total words found embedded: ", num_found, " (including overlaps)" + print *, "==========================" + print * + + print *, "Placed words:" + do i = 1, min(num_placed, 50) + dir_name = get_direction_name(placed(i)%dx, placed(i)%dy) + write(*, '(I3,A,A12,A,I2,A,I2,A,A)') & + i, '. ', trim(placed(i)%word), & + ' (', placed(i)%col-1, ',', placed(i)%row-1, ') ', trim(dir_name) + end do + + print * + print *, "All words found in grid:" + do i = 1, min(num_found, 100) + dir_name = get_direction_name(all_found(i)%dx, all_found(i)%dy) + write(*, '(I3,A,A12,A,I2,A,I2,A,A)') & + i, '. ', trim(all_found(i)%word), & + ' (', all_found(i)%col-1, ',', all_found(i)%row-1, ') ', trim(dir_name) + end do + end subroutine + + function get_direction_name(dx, dy) result(name) + integer, intent(in) :: dx, dy + character(len=20) :: name + + if (dy == 0 .and. dx > 0) then + name = "E" + else if (dy == 0 .and. dx < 0) then + name = "W" + else if (dx == 0 .and. dy > 0) then + name = "S" + else if (dx == 0 .and. dy < 0) then + name = "N" + else if (dx > 0 .and. dy > 0) then + name = "SE" + else if (dx > 0 .and. dy < 0) then + name = "NE" + else if (dx < 0 .and. dy > 0) then + name = "SW" + else if (dx < 0 .and. dy < 0) then + name = "NW" + end if + end function + +end program word_search_rosetta_complete diff --git a/Task/Word-search/Julia/word-search.julia b/Task/Word-search/Julia/word-search.jl similarity index 100% rename from Task/Word-search/Julia/word-search.julia rename to Task/Word-search/Julia/word-search.jl diff --git a/Task/Word-search/Kotlin/word-search.kotlin b/Task/Word-search/Kotlin/word-search.kts similarity index 100% rename from Task/Word-search/Kotlin/word-search.kotlin rename to Task/Word-search/Kotlin/word-search.kts diff --git a/Task/Word-search/Rust/word-search.rs b/Task/Word-search/Rust/word-search.rs new file mode 100644 index 0000000000..ff2bbb98fc --- /dev/null +++ b/Task/Word-search/Rust/word-search.rs @@ -0,0 +1,186 @@ +use once_cell::sync::Lazy; +use rand::rngs::ThreadRng; +use rand::seq::SliceRandom; +use regex::Regex; +use std::fs; + +const DIRS: [[i32; 2]; 8] = [ + [1, 0], + [0, 1], + [1, 1], + [1, -1], + [-1, 0], + [0, -1], + [-1, -1], + [-1, 1], +]; +const NROWS: usize = 10; +const NCOLS: usize = NROWS; +const GRIDSIZE: usize = NROWS * NCOLS; +const MINWORDS: usize = 25; + +struct Grid { + num_attempts: usize, + cells: Vec>, + solutions: Vec, +} + +fn new_grid() -> Grid { + return Grid { + num_attempts: 0, + cells: vec![vec![0_u8; NCOLS]; NROWS], + solutions: vec![String::new(); 0], + }; +} + +fn read_words(file_name: &str) -> Vec { + let re = Regex::new(r"^[a-z]{3,10}$").unwrap(); + let wordsfile = fs::read_to_string(file_name).unwrap().to_lowercase(); + return wordsfile + .split_whitespace() + .filter(|w| re.is_match(w)) + .map(|x| x.to_owned()) + .collect::>(); +} + +fn create_word_search(mut words: Vec) -> Grid { + let mut rng = rand::thread_rng(); + let mut gr = new_grid(); + 'outer: for i in 1..100 { + // up to 100 tries + gr = new_grid(); + let message_len = place_message(&mut gr, "Rosetta Code", &mut rng); + let target = GRIDSIZE - message_len; + let mut cells_filled = 0_usize; + words.shuffle(&mut rng); + for word in &words { + cells_filled += try_place_word(&mut gr, &word, &mut rng); + if cells_filled == target { + if gr.solutions.len() >= MINWORDS { + gr.num_attempts = i; + break 'outer; // outer for + } else { + break; // inner for + } + } + } + } + return gr; +} + +fn place_message(gr: &mut Grid, msg: &str, rng: &mut ThreadRng) -> usize { + static RE: Lazy = Lazy::new(|| Regex::new(r"[^A-Z]").unwrap()); + let mut smsg = msg.to_uppercase(); + smsg = RE.replace(&&smsg, "").to_string(); + let message_len = smsg.len(); + if message_len > 0 && message_len < GRIDSIZE { + let gap_size = GRIDSIZE / message_len; + for i in 0..message_len { + let rpos = i * gap_size + (0..gap_size).collect::>().choose(rng).unwrap(); + gr.cells[rpos / NCOLS][rpos % NCOLS] = smsg.as_bytes()[i]; + } + return message_len; + } + return 0; +} + +fn try_place_word(gr: &mut Grid, word: &str, rng: &mut ThreadRng) -> usize { + let binding = (0..DIRS.len()).collect::>(); + let rand_dir = binding.choose(rng).unwrap(); + let bindingp = (0..GRIDSIZE).collect::>(); + let rand_pos = bindingp.choose(rng).unwrap(); + for dir in 0..DIRS.len() { + let rdir = (dir + rand_dir) % DIRS.len(); + for pos in 0..GRIDSIZE { + let rpos = (pos + rand_pos) % GRIDSIZE; + let letters_placed = try_location(gr, word, rdir, rpos); + if letters_placed > 0 { + return letters_placed; + } + } + } + return 0; +} + +fn try_location(gr: &mut Grid, word: &str, dir: usize, pos: usize) -> usize { + let r = pos / NCOLS; + let c = pos % NCOLS; + let le = word.len(); + + // check bounds + if (DIRS[dir][0] == 1 && (le + c) > NCOLS) + || (DIRS[dir][0] == -1 && (le - 1) > c) + || (DIRS[dir][1] == 1 && (le + r) > NROWS) + || (DIRS[dir][1] == -1 && (le - 1) > r) + { + return 0; + } + let mut overlaps = 0; + + // check cells + let mut rr: i32 = r.try_into().unwrap(); + let mut cc: i32 = c.try_into().unwrap(); + for i in 0..le { + if gr.cells[rr as usize][cc as usize] != 0 + && gr.cells[rr as usize][cc as usize] != word.as_bytes()[i] + { + return 0; + } + cc += DIRS[dir][0]; + rr += DIRS[dir][1]; + } + + // place + rr = r.try_into().unwrap(); + cc = c.try_into().unwrap(); + for i in 0..le { + if gr.cells[rr as usize][cc as usize] == word.as_bytes()[i] { + overlaps += 1; + } else { + gr.cells[rr as usize][cc as usize] = word.as_bytes()[i]; + } + if i < le - 1 { + cc += DIRS[dir][0]; + rr += DIRS[dir][1]; + } + } + + let letters_placed = le - overlaps; + if letters_placed > 0 { + let sol = format!("{:>10} ({},{})({},{})", word, c, r, cc, rr); + gr.solutions.push(sol); + } + return letters_placed; +} + +fn print_result(gr: Grid) { + if gr.num_attempts == 0 { + println!("\nWord search puzzle: No grid to display\n"); + return; + } + let size = gr.solutions.len(); + println!( + "Word search puzzle solution:\n Attempts: {}", + gr.num_attempts + ); + println!(" Number of words: {}", size); + println!("\n 0 1 2 3 4 5 6 7 8 9"); + for r in 0..NROWS { + print!("\n{} ", r); + for c in 0..NCOLS { + print!(" {} ", gr.cells[r][c] as char); + } + } + println!("\n"); + for i in (0..size - 1).step_by(2) { + println!("{} {}", gr.solutions[i], gr.solutions[i + 1]); + } + if size % 2 == 1 { + println!("{}", gr.solutions[size - 1]); + } +} + +fn main() { + let dict_path = "unixdict.txt"; + print_result(create_word_search(read_words(dict_path))); +} diff --git a/Task/Word-wheel/ALGOL-68/word-wheel.alg b/Task/Word-wheel/ALGOL-68/word-wheel.alg new file mode 100644 index 0000000000..f55627274d --- /dev/null +++ b/Task/Word-wheel/ALGOL-68/word-wheel.alg @@ -0,0 +1,36 @@ +STRING wheel = "ndeokgelw"; + +PROC check word = (STRING word, wheel)BOOL: + IF UPB word >= 3 AND UPB word <= UPB wheel THEN + STRING wh := wheel; + FOR i TO UPB word DO + CHAR ch = word[i]; + FOR j TO UPB wh DO + IF ch = wh[j] THEN + wh[j] := REPR 0; + continue + FI + OD; + return false; + continue: SKIP + OD; + IF wh[UPB wh % 2 + 1] /= REPR 0 THEN return false FI; + TRUE EXIT + return false: FALSE + ELSE + FALSE + FI; + +BEGIN + FILE f; + BOOL eof := FALSE; + open(f, "unixdict.txt", stand in channel); + on logical file end(f, (REF FILE f)BOOL: eof := TRUE); + WHILE ~eof DO + STRING word; + get(f, (word, new line)); + IF check word(word, wheel) THEN + print((word, new line)) + FI + OD +END diff --git a/Task/Word-wheel/Ada/word-wheel.adb b/Task/Word-wheel/Ada/word-wheel.adb new file mode 100644 index 0000000000..73db7574e6 --- /dev/null +++ b/Task/Word-wheel/Ada/word-wheel.adb @@ -0,0 +1,56 @@ +with Ada.Characters.Handling; use Ada.Characters.Handling; +with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Text_IO.Unbounded_IO; use Ada.Text_IO.Unbounded_IO; +procedure Wordwheel is + Compulsory_Ix : constant Positive := 5; + Min_Length : constant Positive := 3; + + function Char_Posn (Str : Unbounded_String; C : Character) return Natural is + begin + for Ix in 1 .. Length (Str) loop + if Element (Str, Ix) = C then + return Ix; + end if; + end loop; + return 0; + end Char_Posn; + + procedure Search (Dict_Filename : String; Wheel : String) is + Dict_File : File_Type; + Allowed : constant String := To_Lower (Wheel); + Required_Char : constant String (1 .. 1) := "" & Allowed (Compulsory_Ix); + Available, Dict_Word : Unbounded_String; + Dict_Word_Len : Positive; + Matched : Boolean; + Posn : Natural; + begin + Open (File => Dict_File, Mode => In_File, Name => Dict_Filename); + while not End_Of_File (Dict_File) loop + Dict_Word := Get_Line (Dict_File); + Dict_Word_Len := Length (Dict_Word); + if Dict_Word_Len >= Min_Length and then + Dict_Word_Len <= Wheel'Length and then + Ada.Strings.Unbounded.Count (Dict_Word, Required_Char) > 0 + then + Available := To_Unbounded_String (Allowed); + Matched := True; + for i in 1 .. Dict_Word_Len loop + Posn := Char_Posn (Available, Element (Dict_Word, i)); + if Posn > 0 then + Delete (Source => Available, From => Posn, Through => Posn); + else + Matched := False; + exit; + end if; + end loop; + if Matched then + Put_Line (Dict_Word); + end if; + end if; + end loop; + Close (Dict_File); + end Search; +begin + Search ("unixdict.txt", "ndeokgelw"); +end Wordwheel; diff --git a/Task/Word-wheel/Delphi/word-wheel.delphi b/Task/Word-wheel/Delphi/word-wheel.pas similarity index 100% rename from Task/Word-wheel/Delphi/word-wheel.delphi rename to Task/Word-wheel/Delphi/word-wheel.pas diff --git a/Task/Word-wheel/EasyLang/word-wheel.easy b/Task/Word-wheel/EasyLang/word-wheel.easy new file mode 100644 index 0000000000..656b753a41 --- /dev/null +++ b/Task/Word-wheel/EasyLang/word-wheel.easy @@ -0,0 +1,40 @@ +letters$ = "ndeokgelw" +mid$ = substr letters$ 5 1 +# +func count word$ c$ . + for h$ in strchars word$ + cnt += if h$ = c$ + . + return cnt +. +repeat + word$ = input + until word$ = "" + if len word$ >= 3 and len word$ <= 9 and strpos word$ mid$ <> 0 + hits = 0 + for c$ in strchars word$ + if strpos letters$ c$ <> 0 + hits += 1 + . + . + if len word$ = hits and hits >= 3 + c$ = "" + for c$ in strchars word$ + if count word$ c$ > count letters$ c$ + break 1 + . + . + if c$ = "" + write word$ & " " + . + . + . +. +# +# the content of unixdict.txt +input_data +10th +eke +keg +kong +week diff --git a/Task/Word-wheel/Julia/word-wheel-1.julia b/Task/Word-wheel/Julia/word-wheel-1.jl similarity index 100% rename from Task/Word-wheel/Julia/word-wheel-1.julia rename to Task/Word-wheel/Julia/word-wheel-1.jl diff --git a/Task/Word-wheel/Julia/word-wheel-2.julia b/Task/Word-wheel/Julia/word-wheel-2.jl similarity index 100% rename from Task/Word-wheel/Julia/word-wheel-2.julia rename to Task/Word-wheel/Julia/word-wheel-2.jl diff --git a/Task/Word-wheel/Lua/word-wheel.lua b/Task/Word-wheel/Lua/word-wheel-1.lua similarity index 100% rename from Task/Word-wheel/Lua/word-wheel.lua rename to Task/Word-wheel/Lua/word-wheel-1.lua diff --git a/Task/Word-wheel/Lua/word-wheel-2.lua b/Task/Word-wheel/Lua/word-wheel-2.lua new file mode 100644 index 0000000000..15ec4ccda0 --- /dev/null +++ b/Task/Word-wheel/Lua/word-wheel-2.lua @@ -0,0 +1,15 @@ +-- Algorithm is from Ruby implementation. +local wheel = arg[1] or 'ndeoKgelw' -- wheel is 1st argument +wheel = wheel:lower() +local middle = wheel:sub(5, 5) +assert(#middle == 1) +for line in io.lines() do -- get dictionary from standard input + local word = line:lower() + if word:find(middle) and #word >= 3 then + for wheel_char in wheel:gmatch('.') do + word = word:gsub(wheel_char, '', 1) + end -- for + if #word == 0 then io.write(line:lower() .. ' ') end + end -- if +end -- for +print '' diff --git a/Task/Word-wheel/Pluto/word-wheel.pluto b/Task/Word-wheel/Pluto/word-wheel.pluto new file mode 100644 index 0000000000..37b6b805f7 --- /dev/null +++ b/Task/Word-wheel/Pluto/word-wheel.pluto @@ -0,0 +1,70 @@ +local letters = {"d", "e", "e", "g", "k", "l", "n", "o","w"} +local word_list = "unixdict.txt" -- local copy +local nl = os.platform == "windows" ? "\r\n" : "\n" +local words = io.contents(word_list):rstrip():split(nl) +-- Get rid of words under 3 letters or over 9 letters. +words = words:filter(|w| -> 2 < #w < 10):reorder() +local found = {} +for words as word do + if "k" in word then + local lets = letters:clone() + local ok = true + for i = 1, #word do + local c = word[i] + local ix = lets:findindex(|e| -> e == c) + if !ix then + ok = false + break + end + lets:remove(ix) + end + if ok then found:insert(word) end + end +end + +print($"The following {#found} words are the solutions to the puzzle:") +print(found:concat(nl)) + +-- Optional extra. +local most_found = 0 +local most_words9 = {} +local most_letters = {} +-- Iterate through all 9 letter words in the dictionary. +for words:filtered(|w| -> #w == 9) as word9 do + letters = word9:split(""):sort() + -- Get distinct letters. + local distinct_letters = letters:dedup():reorder() + -- Place each distinct letter in the middle and see what we can do with the rest. + for distinct_letters as letter do + found = 0 + for words as word do + if word:find(letter, 1, true) then + local lets = letters:clone() + local ok = true + for i = 1, #word do + local c = word[i] + local ix = lets:findindex(|e| -> e == c) + if !ix then + ok = false + break + end + lets:remove(ix) + end + if ok then found += 1 end + end + end + if found > most_found then + most_found = found + most_words9 = {word9} + most_letters = {letter} + elseif found == most_found then + most_words9:insert(word9) + most_letters:insert(letter) + end + end +end +print($"\nMost words found = {most_found}") +print("Nine letter words producing this total:") +for i = 1, #most_words9 do + print($"{most_words9[i]} with central letter '{most_letters[i]}'") +end diff --git a/Task/Word-wheel/Rust/word-wheel.rs b/Task/Word-wheel/Rust/word-wheel.rs new file mode 100644 index 0000000000..49679ca4a7 --- /dev/null +++ b/Task/Word-wheel/Rust/word-wheel.rs @@ -0,0 +1,22 @@ +use std::fs::read_to_string; + +fn main() { + let wordsfile = read_to_string("unixdict.txt").unwrap().to_lowercase(); + let wheel = "ndeokgelw".to_string(); + let middle = &wheel[4..=4]; + + for dictword in wordsfile.split_whitespace() { + let mut word = dictword.to_string(); + if word.len() > 2 && word.len() <= wheel.len() && word.contains(middle) { + for c in wheel.chars() { + if word.contains(c) { + let j = word.find(c).unwrap(); + word.replace_range(j..=j, " "); + } + } + if word.chars().filter(|c| c == &' ').count() == word.len() { + println!("{}", dictword); + } + } + } +} diff --git a/Task/Word-wheel/Uiua/word-wheel-1.uiua b/Task/Word-wheel/Uiua/word-wheel-1.uiua new file mode 100644 index 0000000000..83d86fdfa2 --- /dev/null +++ b/Task/Word-wheel/Uiua/word-wheel-1.uiua @@ -0,0 +1,6 @@ +Words ← ▽⊸(≥3≡◇⧻)⊜□⊸≠@\n&fras"RosettaCode/unixdict.txt" +Grid ← "kndeogelw" +Counts ← ⊕⧻⊸⨂◴Grid +GridCounts ← Counts Grid +IsValid ← ↧⊃(/↧≥₀⬚0˜-GridCounts|>0⊢) Counts +⊏⍖⊸≡◇⧻▽⊸≡◇IsValid Words # Valid answers, by falling length. diff --git a/Task/Word-wheel/Uiua/word-wheel-2.uiua b/Task/Word-wheel/Uiua/word-wheel-2.uiua new file mode 100644 index 0000000000..40e269938e --- /dev/null +++ b/Task/Word-wheel/Uiua/word-wheel-2.uiua @@ -0,0 +1,22 @@ +Words ← ▽⊸(≥3≡◇⧻)⊜□⊸≠@\n&fras"RosettaCode/unixdict.txt" +# +KeepNice ← ▽⊸(↧⊃(≥0|≤26)≡◇(-@a⊢))▽⊸(≤9≡◇⧻)▽⊸(≥3≡◇⧻) +Words ← KeepNice⊜□⊸≠@\n&fras"RosettaCode/unixdict.txt" + +Alpha ← "abcdefghijklmnopqrstuvwxyz" +Mask ← /+≡˜⌕¤Alpha # Mask against alphabet. +Masks ← ≡◇(/+≡⌕)Words¤¤Alpha # Masks for all words. +CanMake ← /↧≥0-Mask # Does each letter in cand appear <= each letter in target? +HaveCore ← ▽⊸≡◇˜∊¤⊢ # Keep cands which have the central letter. +Matches ← ˜⊏Words⊚≡(/↧≥0-)Masks ¤Mask # Words that be spelt using target. +Answers ← ⊏⍖⊸≡◇⧻HaveCore⟜Matches # Keep cands which lead with core letter. +&p$"Part 1: _" Answers "kndeogelw" + +Words₉ ← ▽⊸≡◇(=9⧻)Words +# Find all matches for a word, check which letters are used and +# their counts, choose the best -> [count best_letter] +CountFor ← ⟜˜⨂⊸/↥/+≡◇(>0Mask)Matches + +˜⊡Words₉⟜⊡˜⨂⊸(/↥)⊸≡⊢⍉⊟≡◇CountFor Words₉ +&p$"Part 2 - best word '_': _ matches with '_' at centre" °□⊙⊙(˜⊡Alpha)⊙°⊟ +&p$"Confirmation - _ answers: _" ⊸⧻ Answers "etrminals" diff --git a/Task/Word-wheel/VBScript/word-wheel.vb b/Task/Word-wheel/VBScript/word-wheel.vbs similarity index 100% rename from Task/Word-wheel/VBScript/word-wheel.vb rename to Task/Word-wheel/VBScript/word-wheel.vbs diff --git a/Task/Word-wrap/Ada/word-wrap-1.ada b/Task/Word-wrap/Ada/word-wrap-1.adb similarity index 100% rename from Task/Word-wrap/Ada/word-wrap-1.ada rename to Task/Word-wrap/Ada/word-wrap-1.adb diff --git a/Task/Word-wrap/Ada/word-wrap-2.ada b/Task/Word-wrap/Ada/word-wrap-2.adb similarity index 100% rename from Task/Word-wrap/Ada/word-wrap-2.ada rename to Task/Word-wrap/Ada/word-wrap-2.adb diff --git a/Task/Word-wrap/Ada/word-wrap-3.ada b/Task/Word-wrap/Ada/word-wrap-3.adb similarity index 100% rename from Task/Word-wrap/Ada/word-wrap-3.ada rename to Task/Word-wrap/Ada/word-wrap-3.adb diff --git a/Task/Word-wrap/Delphi/word-wrap.delphi b/Task/Word-wrap/Delphi/word-wrap.pas similarity index 100% rename from Task/Word-wrap/Delphi/word-wrap.delphi rename to Task/Word-wrap/Delphi/word-wrap.pas diff --git a/Task/Word-wrap/Ed/word-wrap.ed b/Task/Word-wrap/Ed/word-wrap.ed new file mode 100644 index 0000000000..81f674c311 --- /dev/null +++ b/Task/Word-wrap/Ed/word-wrap.ed @@ -0,0 +1,5 @@ +H +g/.*/s/(.{0,79})([ ]|$)/\1\ +/g +,p +Q diff --git a/Task/Word-wrap/Elena/word-wrap.elena b/Task/Word-wrap/Elena/word-wrap.elena index 44f714e95d..22ff4fe018 100644 --- a/Task/Word-wrap/Elena/word-wrap.elena +++ b/Task/Word-wrap/Elena/word-wrap.elena @@ -28,7 +28,7 @@ extension wrapOp { currentWidth := word.Length + 1; - ^ newLineConstant + word + " " + ^ NewLineConstant + word + " " } else { @@ -41,10 +41,10 @@ extension wrapOp } } -public program() +public Program() { - console.printLine(new StringWriter("-", 72)); - console.printLine(text.wrap(72)); - console.printLine(new StringWriter("-", 80)); - console.printLine(text.wrap(80)); + Console.printLine(new StringWriter("-", 72)); + Console.printLine(text.wrap(72)); + Console.printLine(new StringWriter("-", 80)); + Console.printLine(text.wrap(80)); } diff --git a/Task/Word-wrap/Elixir/word-wrap.elixir b/Task/Word-wrap/Elixir/word-wrap.ex similarity index 100% rename from Task/Word-wrap/Elixir/word-wrap.elixir rename to Task/Word-wrap/Elixir/word-wrap.ex diff --git a/Task/Word-wrap/FutureBasic/word-wrap.basic b/Task/Word-wrap/FutureBasic/word-wrap.basic new file mode 100644 index 0000000000..4effaec67d --- /dev/null +++ b/Task/Word-wrap/FutureBasic/word-wrap.basic @@ -0,0 +1,59 @@ +CFArrayRef local fn WrapStringAtWordBoundaries( txtStr as CFStringRef, maxLineLength as NSUInteger ) + CFMutableArrayRef lines = fn MutableArrayNew + ScannerRef scanner = fn ScannerWithString( txtStr ) + CFMutableStringref currentLine = fn MutableStringNew + CFStringRef wordStr + ScannerSetCharactersToBeSkipped( scanner, NULL ) + + while ( fn ScannerIsAtEnd( scanner ) == NO ) + fn ScannerScanUpToCharactersFromSet( scanner, fn CharacterSetWhitespaceAndNewlineSet, @wordStr ) + + if ( wordStr ) + if ( ( len( currentLine ) + len( wordStr ) + 1 ) > maxLineLength ) + if ( len( currentLine ) > 0 ) + MutableArrayAddObject( lines, fn StringWithString( currentLine ) ) + MutableStringSetString( currentLine, @"" ) // Reset the line + end if + end if + if ( len( currentLine ) > 0 ) + MutableStringAppendString( currentLine, @" " ) + end if + MutableStringAppendString( currentLine, wordStr ) + end if + fn ScannerScanCharactersFromSet( scanner, fn CharacterSetWhitespaceAndNewlineSet, NULL ) // Skip over whitespace between words + wend + + if ( len( currentLine ) > 0 ) + MutableArrayAddObject( lines, fn StringWithString( currentLine ) ) + end if + + return lines +end fn = NULL + + +CFStringRef txtStr +txtStr = @"In olden times when wishing still helped one, there lived a king ¬ +whose daughters were all beautiful, but the youngest was so beautiful ¬ +that the sun itself, which has seen so much, was astonished whenever ¬ +it shone-in-her-face. Close by the king's castle lay a great dark ¬ +forest, and under an old lime-tree in the forest was a well, and when ¬ +the day was very warm, the king's child went out into the forest and ¬ +sat down by the side of the cool-fountain, and when she was bored she ¬ +took a golden ball, and threw it up on high and caught it, and this ¬ +ball was her favorite plaything." + +CFStringRef columnizedStr + +// Create wrapping lines respecting word boundaries + +print @"Wrapped at 20 characters:" +columnizedStr = fn ArrayComponentsJoinedByString( fn WrapStringAtWordBoundaries( txtStr, 20 ), @"\n" ) +print columnizedStr + +print + +print @"Wrapped at 80 characters:" +columnizedStr = fn ArrayComponentsJoinedByString( fn WrapStringAtWordBoundaries( txtStr, 80 ), @"\n" ) +print columnizedStr + +HandleEvents diff --git a/Task/Word-wrap/Julia/word-wrap.julia b/Task/Word-wrap/Julia/word-wrap.jl similarity index 100% rename from Task/Word-wrap/Julia/word-wrap.julia rename to Task/Word-wrap/Julia/word-wrap.jl diff --git a/Task/Word-wrap/Kotlin/word-wrap.kotlin b/Task/Word-wrap/Kotlin/word-wrap.kts similarity index 100% rename from Task/Word-wrap/Kotlin/word-wrap.kotlin rename to Task/Word-wrap/Kotlin/word-wrap.kts diff --git a/Task/Word-wrap/OCaml/word-wrap.ocaml b/Task/Word-wrap/OCaml/word-wrap.ml similarity index 100% rename from Task/Word-wrap/OCaml/word-wrap.ocaml rename to Task/Word-wrap/OCaml/word-wrap.ml diff --git a/Task/Word-wrap/PascalABC.NET/word-wrap.pas b/Task/Word-wrap/PascalABC.NET/word-wrap.pas new file mode 100644 index 0000000000..08a58e9720 --- /dev/null +++ b/Task/Word-wrap/PascalABC.NET/word-wrap.pas @@ -0,0 +1,40 @@ +function Wrap(words: sequence of string; lineWidth: integer): sequence of string; +begin + var currentWidth := 0; + foreach var word in words do + begin + if currentWidth <> 0 then + if currentWidth + word.Length < lineWidth then + begin + currentWidth += 1; + yield ' '; + end + else + begin + currentWidth := 0; + yield NewLine; + end; + currentWidth += word.Length; + yield word; + end; +end; + +function Wrap(text: string; lineWidth: integer): string + := Wrap(text.ToWords(' '#13#10),lineWidth).JoinToString(''); + +begin + var text := ''' +Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas varius sapien +vel purus hendrerit vehicula. Integer hendrerit viverra turpis, ac sagittis arcu +pharetra id. Sed dapibus enim non dui posuere sit amet rhoncus tellus +consectetur. Proin blandit lacus vitae nibh tincidunt cursus. Cum sociis natoque +penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nam tincidunt +purus at tortor tincidunt et aliquam dui gravida. Nulla consectetur sem vel +felis vulputate et imperdiet orci pharetra. Nam vel tortor nisi. Sed eget porta +tortor. Aliquam suscipit lacus vel odio faucibus tempor. Sed ipsum est, +condimentum eget eleifend ac, ultricies non dui. Integer tempus, nunc sed +venenatis feugiat, augue orci pellentesque risus, nec pretium lacus enim eu +nibh. +'''; + Wrap(text,50).Println; +end. diff --git a/Task/Word-wrap/PowerShell/word-wrap-1.psh b/Task/Word-wrap/PowerShell/word-wrap-1.ps1 similarity index 100% rename from Task/Word-wrap/PowerShell/word-wrap-1.psh rename to Task/Word-wrap/PowerShell/word-wrap-1.ps1 diff --git a/Task/Word-wrap/PowerShell/word-wrap-2.psh b/Task/Word-wrap/PowerShell/word-wrap-2.ps1 similarity index 100% rename from Task/Word-wrap/PowerShell/word-wrap-2.psh rename to Task/Word-wrap/PowerShell/word-wrap-2.ps1 diff --git a/Task/Word-wrap/PowerShell/word-wrap-3.psh b/Task/Word-wrap/PowerShell/word-wrap-3.ps1 similarity index 100% rename from Task/Word-wrap/PowerShell/word-wrap-3.psh rename to Task/Word-wrap/PowerShell/word-wrap-3.ps1 diff --git a/Task/Word-wrap/Rust/word-wrap.rust b/Task/Word-wrap/Rust/word-wrap.rs similarity index 100% rename from Task/Word-wrap/Rust/word-wrap.rust rename to Task/Word-wrap/Rust/word-wrap.rs diff --git a/Task/Word-wrap/Scheme/word-wrap.ss b/Task/Word-wrap/Scheme/word-wrap.scm similarity index 100% rename from Task/Word-wrap/Scheme/word-wrap.ss rename to Task/Word-wrap/Scheme/word-wrap.scm diff --git a/Task/Word-wrap/VBScript/word-wrap.vb b/Task/Word-wrap/VBScript/word-wrap.vbs similarity index 100% rename from Task/Word-wrap/VBScript/word-wrap.vb rename to Task/Word-wrap/VBScript/word-wrap.vbs diff --git a/Task/Wordiff/Arturo/wordiff.arturo b/Task/Wordiff/Arturo/wordiff.arturo index 1c7d7c909c..5ef5f3d280 100644 --- a/Task/Wordiff/Arturo/wordiff.arturo +++ b/Task/Wordiff/Arturo/wordiff.arturo @@ -19,9 +19,9 @@ validAnswer?: function [answer][ playerA: input "player A: what is your name? " playerB: input "player B: what is your name? " -pastWords: new @[sample select wordset 'word [ contains? [3 4] size word ]] +pastWords: @[sample select wordset 'word [ contains? [3 4] size word ]] -print ["\nThe initial word is:" last pastWords "\n"] +print ["\nThe initial word is: " last pastWords "\n"] current: playerA while ø [ diff --git a/Task/Wordiff/Crystal/wordiff.cr b/Task/Wordiff/Crystal/wordiff.cr new file mode 100644 index 0000000000..e23d8d185d --- /dev/null +++ b/Task/Wordiff/Crystal/wordiff.cr @@ -0,0 +1,40 @@ +require "levenshtein" + +words = File.read_lines("unixdict.txt").to_set + +print "Enter player names separated by spaces: " +players = gets.not_nil!.split + +current = words.select { |w| 3 <= w.size <= 4 }.sample +used = Set.new [current] + +puts "Starting word is '#{current}'!" + +players.cycle.skip(players.size-1).each_cons_pair do |previous, player| + print "#{player}, give me a wordiff from '#{current}': " + guess = gets.not_nil! + if guess.in?(words) && !guess.in?(used) && (dist = Levenshtein.distance(current, guess)) == 1 + puts "Good!" + used << guess + current = guess + else + possible = words.select {|w| + !w.in?(used) && (w.size - guess.size).abs <= 1 && Levenshtein.distance(current, w) == 1 + } + if !guess.in? words + puts "That word isn't in the dictionary." + elsif guess.in? used + puts "That word was already used." + else + puts "That word isn't a wordiff from '#{guess}'." + end + puts "You LOSE, #{player}!" + if possible.size > 0 + puts "You could have entered: #{possible.sort.join(", ")}" + else + puts "(But you didn't have any word left to enter. Brilliant move by #{previous}!)" + end + puts "#{previous} WINS!" + break + end +end diff --git a/Task/Wordiff/JavaScript/wordiff.js b/Task/Wordiff/JavaScript/wordiff.js new file mode 100644 index 0000000000..673acf6997 --- /dev/null +++ b/Task/Wordiff/JavaScript/wordiff.js @@ -0,0 +1,200 @@ +const readline = require("readline"); +const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout +}); +const crypto = require("crypto"); + +const dictionaryUrl = "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt"; +const wordRegexPattern = /^[a-z]{3,}$/m; +let dictionary = undefined; + +function askQuestion(query) { + return new Promise(resolve => rl.question(query, resolve)); +} + +function askInt(query) { + return new Promise(resolve => rl.question(query, answer => resolve(parseInt(answer, 10)))); +} + +async function loadWebDictionary(url) { + try { + const response = await fetch(url); + if (!response.ok) + throw new Error(`HTTP ERROR -- ${response.status}`); + + const rawText = await response.text(); + const wordList = rawText.split("\n") + .map(str => { + const match = str.match(wordRegexPattern); + return match ? match[0] : null; + }) + .filter(word => word !== null); + return wordList; + } catch (err) { + console.error("Failed to load dictionary", err.message); + return []; + } +} + +function zip(arr0, arr1) { + return arr0.map((el, idx) => [el, arr1[idx]]); +} + +function* cycle(arr) { + let index = 0; + while (true) { + yield arr[index]; + index = (index + 1) % arr.length; + } +} + +function counter(arr) { + const countMap = {}; + for (const item of arr) + countMap[item] = (countMap[item] || 0) + 1; + return countMap; +} + +function subtractCounters(c0, c1) { + const result = {...c0}; + + for (const [key, count] of Object.entries(c1)) + if (result[key]) { + result[key] -= count; + if (result[key] <= 0) { + delete result[key]; + } + } + + return result; +} + +function subtractSets(s0, s1) { + const result = new Set(); + for (const item of s0) + if (!s1.has(item)) + result.add(item); + return result; +} + +function isWordiff(wordiffs, word, dict) { + const current = wordiffs[wordiffs.length-1]; + + if (!dict.includes(word)) + return false; + if (wordiffs.includes(word)) + return false; + + if (word.length < current.length) + return isWordiffRemoval(word, current); + else if (word.length > current.length) + return isWordiffInsertion(word, current); + return isWordiffChange(word, current); +} + +function isWordiffRemoval(word, previous) { + const possible = new Set(); + for (let i = 0; i < previous.length; i++) + possible.add(previous.slice(0, i)+previous.slice(i+1)); + return possible.has(word); +} + +function isWordiffInsertion(word, previous) { + const diff = subtractCounters(counter(word), counter(previous)); + const diffCount = Object.values(diff).reduce((a, v) => a + v, 0); + if (diffCount !== 1) + return false; + + const insert = Object.keys(diff)[0]; + const possible = new Set(); + for (let i = 0; i < previous.length + 1; i++) + possible.add(previous.slice(0, i)+insert+previous.slice(i)); + return possible.has(word); +} + +function isWordiffChange(word, previous) { + const diffCount = zip(word.split(""), previous.split("")) + .map(([a, b]) => a !== b ? 1 : 0) + .reduce((a, v) => a + v, 0); + return diffCount === 1; +} + +function couldHaveEntered(wordiffs, dict, limit=10) { + const currentSet = new Set(wordiffs); + const dictSet = new Set(dict); + const remaining = subtractSets(dictSet, currentSet); + const currentLength = wordiffs[wordiffs.length-1].length; + const possibleLengths = [currentLength-1, currentLength, currentLength+1]; + const filteredRemaining = Array.from(remaining).filter(word => possibleLengths.includes(word.length)); + const suggestions = []; + for (const candidate of filteredRemaining) + if (isWordiff(wordiffs, candidate, dict)) { + suggestions.push(candidate); + if (suggestions.length >= limit) + break; + } + return suggestions; +} + +async function main() { + dictionary = await loadWebDictionary(dictionaryUrl); + console.log(`Loaded ${dictionary.length} words into dictionary.`); + if (dictionary.length === 0) { + rl.close(); + return; + } + + const dict34 = dictionary.filter(word => word.length === 3 || word.length === 4); + if (dict34.length === 0) { + console.error("ERROR -- No valid 3 or 4 letter words found in the dictionary."); + rl.close(); + return; + } + + const startIndex = crypto.randomInt(dict34.length); + let wordiffs = [dict34[startIndex]]; + + const numberOfPlayers = await askInt("How many players (maximum 8)? "); + if (numberOfPlayers > 8 || numberOfPlayers < 1) { + console.error(`ERROR -- Must have between 1 and 8 players. Got ${numberOfPlayers}.`); + rl.close(); + return; + } + + const players = []; + for (let i = 0; i < numberOfPlayers; i++) { + const playerName = (await askQuestion(` (${i+1}) Enter name: `)).trim(); + players.push(playerName || `Player${i+1}`); + } + + const playersCycle = cycle(players); + + while (true) { + let currentPlayer = playersCycle.next().value; + + console.log(`=== ${currentPlayer}'s turn! ===`); + const currentWord = wordiffs[wordiffs.length-1]; + + const word = (await askQuestion( + `Current word is "${wordiffs.at(-1)}"\n`+ + "Enter your word: " + )).trim().toLowerCase(); + + if (isWordiff(wordiffs, word, dictionary)) { + wordiffs.push(word); + console.log(`Accepted! New chain: ${wordiffs.join(" -> ")}`); + } else { + const alternatives = couldHaveEntered(wordiffs, dictionary); + console.log( + `Game over, ${currentPlayer}!\n`+ + `You could have entered one of these words (first ${alternatives.length} suggestions): ${alternatives.join(", ")}` + ); + break; + } + } + + rl.close(); +} + +main(); diff --git a/Task/Wordiff/Jq/wordiff.jq b/Task/Wordiff/Jq/wordiff.jq new file mode 100644 index 0000000000..c0cec7cb3b --- /dev/null +++ b/Task/Wordiff/Jq/wordiff.jq @@ -0,0 +1,108 @@ +include "MRG32k3a" {search: "."}; # see comment above + +### Generic functions + +# Determine if stream is non-decreasing +def is_sorted(stream): + first(foreach stream as $s ( null; + if . == null or $s >= .[0] then [$s] + else 0 + end; + select(. == 0) ) ) + // 1 + | . == 1; + +# Write to stderr +def inform(msg): + . as $in + | ("\(msg)\n" | stderr) + | $in; + +# q means quit +def read($prompt; $regex): + def r: + ($prompt | stderr | empty), + (try ((input + | if . == "q" then halt + else select(test($regex)) + end) // r) + catch if . == "break" then halt else r end ); + r; + +# Returns levenshteinDistance(s1; $s2) <= $max +# A recursive algorithm is good enough if $max is small +def levenshteinDistance($s1; $s2; $max): + def lev: + . as [$s1, $s2, $max] + | if ($s1|length) == 0 then ($s2|length) <= $max + elif ($s2|length) == 0 then ($s1|length) <= $max + elif $s1[:1] == $s2[:1] + then [$s1[1:], $s2[1:], $max] | lev + else ($s1|length) <= $max + or ($s2|length) <= $max + or ([$s1[1:], $s2, $max-1] | lev) + or ([$s1, $s2[1:], $max-1] | lev) + or ([$s1[1:], $s2[1:], $max-1] | lev) + end ; + [$s1, $s2, $max] | lev; + +##### The Wordiff Game + +# Output: the sorted list of words +# The sort is skipped if we can readily determine the list is already sorted +def words: + [$dict | splits(" *\n *")] + | if is_sorted(.[]) then . + else sort + end; + +def player1: read("Player 1, please enter your name : "; "."); +def player2: read("Player 2, please enter your name : "; "."); + +def round: + .words as $words + | read("\(.player), enter your word: "; ".") as $word + | ($word|length) as $len + | .ok = false + | if $len < 3 + then inform("Words must be at least three letters long.") + elif $word == .prevWord + then inform("You must change the previous word.") + elif .used[$word] + then inform("The word \"\($word)\" has been used before.") + elif # not in dictionary + # if $words is not sorted: ($word | IN($words[]) | not) + # binary search: + ($words | bsearch($word) < 0) + then inform("Not in dictionary.") + + elif levenshteinDistance($word; .prevWord; 1) + #### Good to go + then .ok = true + | .prevLen = ($word|length) + | .prevWord = $word + | .used[$word] = true + | .player = (if .player == .player1 then .player2 else .player1 end) + else inform("Sorry. Only one addition, deletion or alteration is allowed.") + end + | if (.ok|not) then inform("Please retry. The current word is: \(.prevWord)") end + | round ; + +def play: + player1 as $player1 + | { player1: $player1, + player2: ( player2 | if . == $player1 then . + "2" else . end) + } + | inform("Reading and perhaps sorting the list of words takes a few seconds... ") + | inform("Meanwhile note that you can quit by entering q at a prompt.") + | .words = words + # Avoid storing the subset of words needed to make a random selection: + | (.words | map(select(length | IN(3,4))) | .[length | prn(1)[]]) as $firstWord + | .prevLen = ($firstWord|length) + | .prevWord = $firstWord + | .used = {($firstWord): true} # a JSON object for efficiency + | .player = .player1 + | "\nThe first word is: \($firstWord)", + round; + +play diff --git a/Task/Wordiff/Julia/wordiff.julia b/Task/Wordiff/Julia/wordiff.jl similarity index 100% rename from Task/Wordiff/Julia/wordiff.julia rename to Task/Wordiff/Julia/wordiff.jl diff --git a/Task/Wordiff/Rust/wordiff.rs b/Task/Wordiff/Rust/wordiff.rs new file mode 100644 index 0000000000..44e1b289f1 --- /dev/null +++ b/Task/Wordiff/Rust/wordiff.rs @@ -0,0 +1,100 @@ +use rand::seq::SliceRandom; +use std::collections::HashSet; +use std::fs; +use std::io::Write; + +fn request_player_names(wanted: i32) -> Vec { + let mut player_names = vec![]; + for i in 0..wanted { + let mut buf = String::new(); + print!("\nPlease enter the player's name for player {}: ", i + 1); + let _ = std::io::stdout().flush(); + let _ = std::io::stdin().read_line(&mut buf); + player_names.push(buf.trim_end().to_owned()); + } + return player_names; +} + +fn is_letter_removed(previous_word: &str, current_word: &str) -> bool { + for i in 0..previous_word.len() { + if current_word == previous_word[..i].to_owned() + &previous_word[i + 1..] { + return true; + } + } + return false; +} + +fn is_letter_added(previous_word: &str, current_word: &str) -> bool { + return is_letter_removed(current_word, previous_word); +} + +fn is_letter_changed(previous_word: &str, current_word: &str) -> bool { + if previous_word.len() != current_word.len() { + return false; + } + + let mut difference_count = 0; + for i in 0..current_word.len() { + difference_count += (current_word[i..=i] != previous_word[i..=i]) as usize; + } + return difference_count == 1; +} + +fn is_wordiff(current_word: &str, words_used: &Vec, dictionary: &HashSet<&str>) -> bool { + if !dictionary.contains(current_word) || words_used.contains(¤t_word.to_string()) { + return false; + } + let previous_word = words_used.last().unwrap(); + return is_letter_changed(previous_word, current_word) + || is_letter_removed(previous_word, current_word) + || is_letter_added(previous_word, current_word); +} + +fn could_have_entered(words_used: &Vec, dictionary: &HashSet<&str>) -> Vec { + let mut result: Vec = vec![]; + for word in dictionary { + if is_wordiff(word, words_used, dictionary) { + result.push(word.to_string()); + } + } + return result; +} + +fn main() { + let mut rng = rand::thread_rng(); + let wordsfile = fs::read_to_string("unixdict.txt").unwrap().to_lowercase(); + let words = wordsfile.split_whitespace().collect::>(); + let dictionary: &HashSet<&str> = &words.iter().cloned().collect(); + let mut starters = words + .clone() + .into_iter() + .filter(|w| w.len() == 3 || w.len() == 4) + .collect::>(); + starters.shuffle(&mut rng); + let mut words_used = vec![starters[0].to_string(); 1]; + + let player_names = request_player_names(2); + let mut playing = true; + let mut player_index = 0_usize; + let mut current_word = words_used.last().unwrap().to_string(); + println!("\nThe first word is: {}", current_word); + let _ = std::io::stdout().flush(); + + while playing { + print!("{}, enter your word: ", player_names[player_index]); + let _ = std::io::stdout().flush(); + current_word.clear(); + let _ = std::io::stdin().read_line(&mut current_word); + current_word = current_word.trim_end().to_owned(); + println!("You entered {}.", current_word); + if is_wordiff(¤t_word, &words_used, dictionary) { + words_used.push(current_word.clone()); + player_index = (player_index + 1) % player_names.len(); + } else { + println!("You have lost the game, {}.", player_names[player_index]); + let missed_words = could_have_entered(&words_used, dictionary); + println!("You could have entered: {:?}", missed_words); + playing = false; + } + } +} diff --git a/Task/Wordiff/V-(Vlang)/wordiff.v b/Task/Wordiff/V-(Vlang)/wordiff.v index 23ab172d42..83857d6276 100644 --- a/Task/Wordiff/V-(Vlang)/wordiff.v +++ b/Task/Wordiff/V-(Vlang)/wordiff.v @@ -5,11 +5,11 @@ import arrays fn is_wordiff(guesses []string, word string, dict []string) bool { if word !in dict { - println('That word is not in the dictionary') + println("That word is not in the dictionary") return false } if word in guesses { - println('That word has already been used') + println("That word has already been used") return false } if word.len < guesses[guesses.len-1].len { @@ -25,16 +25,16 @@ fn is_wordiff_removal(new_word string, last_word string) bool { return true } } - println('Word is not derived from previous by removal of one letter') + println("Word is not derived from previous by removal of one letter") return false } fn is_wordiff_insertion(new_word string, last_word string) bool { if new_word.len > last_word.len+1 { - println('More than one character insertion difference') + println("More than one character insertion difference") return false } - mut a := new_word.split('') - b := last_word.split('') + mut a := new_word.split("") + b := last_word.split("") for c in b { idx := a.index(c) if idx >=0 { @@ -42,7 +42,7 @@ fn is_wordiff_insertion(new_word string, last_word string) bool { } } if a.len >1 { - println('Word is not derived from previous by insertion of one letter') + println("Word is not derived from previous by insertion of one letter") return false } return true @@ -55,16 +55,16 @@ fn is_wordiff_change(new_word string, last_word string) bool { } } if diff != 1 { - println('More or less than exactly one character changed') + println("More or less than exactly one character changed") return false } return true } fn main() { - words := os.read_lines('unixdict.txt')? - time_limit := os.input('Time limit (sec) or 0 for none: ').int() - players := os.input('Please enter player names, separated by commas: ').split(',') + words := os.read_lines("unixdict.txt")! + time_limit := os.input("Time limit (sec) or 0 for none: ").int() + players := os.input("Please enter player names, separated by commas: ").split(",") dic_3_4 := words.filter(it.len in [3,4]) mut wordiffs := rand.choose(dic_3_4,1)? @@ -73,25 +73,25 @@ fn main() { mut turn_count := 0 for { turn_start := time.now() - word := os.input('${players[turn_count%players.len]}: Input a wordiff from ${wordiffs[wordiffs.len-1]}: ') + word := os.input("${players[turn_count%players.len]}: Input a wordiff from ${wordiffs[wordiffs.len-1]}: ") if time_limit != 0.0 && time.since(start).seconds()>time_limit{ - println('TIMES UP ${players[turn_count%players.len]}') + println("TIMES UP ${players[turn_count%players.len]}") break } else { if is_wordiff(wordiffs, word, words) { wordiffs<(p) or {0} - println(' ${players[i]}: ${sum/p.len:10.3 f} seconds average') + println(" ${players[i]}: ${sum/p.len:10.3 f} seconds average") } } diff --git a/Task/World-Cup-group-stage/11l/world-cup-group-stage.11l b/Task/World-Cup-group-stage/11l/world-cup-group-stage.11l index 82d15b99e5..e80a27bbde 100644 --- a/Task/World-Cup-group-stage/11l/world-cup-group-stage.11l +++ b/Task/World-Cup-group-stage/11l/world-cup-group-stage.11l @@ -31,7 +31,7 @@ L records[games[i][1].code - ‘1’.code] += 3 records.sort() - L(i) 4 + L(i) 0.<4 points[i][records[i]]++ I !nextResult() @@ -40,8 +40,8 @@ L print(|‘POINTS 0 1 2 3 4 5 6 7 8 9 -------------------------------------------------------------’) V places = [‘1st’, ‘2nd’, ‘3rd’, ‘4th’] -L(i) 4 +L(i) 0.<4 print(places[i], end' ‘ place ’) - L(j) 10 + L(j) 0.<10 print(‘#<5’.format(points[3 - i][j]), end' ‘’) print() diff --git a/Task/World-Cup-group-stage/EasyLang/world-cup-group-stage.easy b/Task/World-Cup-group-stage/EasyLang/world-cup-group-stage.easy new file mode 100644 index 0000000000..847a9f5de3 --- /dev/null +++ b/Task/World-Cup-group-stage/EasyLang/world-cup-group-stage.easy @@ -0,0 +1,54 @@ +games$[] = [ "12" "13" "14" "23" "24" "34" ] +results$ = "000000" +# +proc sort &d[] . + for i = 1 to len d[] - 1 : for j = i + 1 to len d[] + if d[j] < d[i] : swap d[j] d[i] + . +. +func tonum s$ b . + for c$ in strchars s$ : r = r * b + number c$ + return r +. +func$ tostr ndig n b . + for i to ndig + d = n mod b + n = n div b + r$ = d & r$ + . + return r$ +. +func nextResult . + if results$ = "222222" : return 0 + res = tonum results$ 3 + results$ = tostr 6 (res + 1) 3 + return 1 +. +len points[][] 4 +for i to 4 : len points[i][] 10 +repeat + results$[] = strchars results$ + records[] = [ 0 0 0 0 ] + for i to 6 + if results$[i] = "2" + records[strcode substr games$[i] 1 1 - 48] += 3 + elif results$[i] = "1" + records[strcode substr games$[i] 1 1 - 48] += 1 + records[strcode substr games$[i] 2 1 - 48] += 1 + elif results$[i] = "0" + records[strcode substr games$[i] 2 1 - 48] += 3 + . + . + sort records[] + for i to 4 : points[i][records[i] + 1] += 1 + until nextResult = 0 +. +print "POINTS 0 1 2 3 4 5 6 7 8 9" +print "--------------------------------------------------" +places$[] = [ "1st" "2nd" "3rd" "4th" ] +numfmt 4 0 +for i to 4 + write places$[i] & " place " + for j to 10 : write points[5 - i][j] + print "" +. 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 8c4e35dcca..a39153b729 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 @@ -1,7 +1,7 @@ import system'routines; import extensions; -public singleton program +public singleton Program { static games := new string[]{"12", "13", "14", "23", "24", "34"}; @@ -31,12 +31,12 @@ public singleton program { var r := results[i]; r => - "2" { records[games[i][0].toInt() - 49] := records[games[i][0].toInt() - 49] + 3 } - "1" { + "2" : { records[games[i][0].toInt() - 49] := records[games[i][0].toInt() - 49] + 3 } + "1" : { records[games[i][0].toInt() - 49] := records[games[i][0].toInt() - 49] + 1; records[games[i][1].toInt() - 49] := records[games[i][1].toInt() - 49] + 1 } - "0" { records[games[i][1].toInt() - 49] := records[games[i][1].toInt() - 49] + 3 }; + "0" : { records[games[i][1].toInt() - 49] := records[games[i][1].toInt() - 49] + 3 }; }; records := records.ascendant(); @@ -46,11 +46,11 @@ public singleton program points[i][records[i]] := points[i][records[i]] + 1 } } - while(program.nextResult()); + while(Program.nextResult()); new Range(0, 4).zipForEach(new string[]{"1st", "2nd", "3rd", "4th"}, (i,l) { - console.printLine(l,": ", points[3 - i].toArray()) + Console.printLine(l,": ", points[3 - i].toArray()) }); } } diff --git a/Task/World-Cup-group-stage/Elixir/world-cup-group-stage.elixir b/Task/World-Cup-group-stage/Elixir/world-cup-group-stage.ex similarity index 100% rename from Task/World-Cup-group-stage/Elixir/world-cup-group-stage.elixir rename to Task/World-Cup-group-stage/Elixir/world-cup-group-stage.ex diff --git a/Task/World-Cup-group-stage/FreeBASIC/world-cup-group-stage.basic b/Task/World-Cup-group-stage/FreeBASIC/world-cup-group-stage.basic new file mode 100644 index 0000000000..e6ed99287b --- /dev/null +++ b/Task/World-Cup-group-stage/FreeBASIC/world-cup-group-stage.basic @@ -0,0 +1,96 @@ +Dim Shared As Integer points(3, 9) +Dim Shared As String*2 games(5) = {"12", "13", "14", "23", "24", "34"} +Dim Shared As String result +result = "000000" + +Sub SortArray(arr() As Integer) + Dim As Integer i, j + + For i = 0 To Ubound(arr) - 1 + For j = i + 1 To Ubound(arr) + If arr(i) > arr(j) Then Swap arr(i), arr(j) + Next + Next +End Sub + +Function ParseInt(number As String, base_ As Integer) As Integer + Dim As Integer i, x = 0, pot = 0 + + For i = Len(number) To 1 Step -1 + x += base_ ^ pot * Val(Mid(number, i, 1)) + pot += 1 + Next + + Return x +End Function + +Function Formato(decimal As Integer, base_ As Integer) As String + Dim As Integer cociente + Dim As String conv = "" + + Do + cociente = decimal \ base_ + conv = Str(decimal Mod base_) + conv + decimal = cociente + Loop Until cociente = 0 + + Return conv +End Function + +Function NextResult() As Boolean + If result = "222222" Then Return False + + Dim As Integer res = ParseInt(result, 3) + result = Formato(res + 1, 3) + While Len(result) < 6 + result = "0" & result + Wend + Return True +End Function + +Function Compute() As Boolean + 'Dim records(3) As Integer + Dim As Integer records(3), i, t + + For i = 0 To 5 + Select Case Mid(result, i + 1, 1) + Case "2" + t = Val(Mid(games(i), 1, 1)) - 1 + records(t) += 3 + Case "1" + t = Val(Mid(games(i), 1, 1)) - 1 + records(t) += 1 + t = Val(Mid(games(i), 2, 1)) - 1 + records(t) += 1 + Case "0" + t = Val(Mid(games(i), 2, 1)) - 1 + records(t) += 3 + End Select + Next + + SortArray(records()) + + For i = 0 To 3 + points(i, records(i)) += 1 + Next + + Return Iif(NextResult(), True, False) +End Function + +Do While Compute() +Loop + +Print "POINTS 0 1 2 3 4 5 6 7 8 9" +Print String (61, "-") +Dim As Integer i, j +Dim As String places(3) = {"1st", "2nd", "3rd", "4th"} + +For i = 0 To 3 + Print places(i); " place "; + For j = 0 To 9 + Print Using "#####"; points(3 - i, j); + Next + Print +Next + +Sleep diff --git a/Task/World-Cup-group-stage/Julia/world-cup-group-stage.julia b/Task/World-Cup-group-stage/Julia/world-cup-group-stage.jl similarity index 100% rename from Task/World-Cup-group-stage/Julia/world-cup-group-stage.julia rename to Task/World-Cup-group-stage/Julia/world-cup-group-stage.jl diff --git a/Task/World-Cup-group-stage/Kotlin/world-cup-group-stage.kotlin b/Task/World-Cup-group-stage/Kotlin/world-cup-group-stage.kts similarity index 100% rename from Task/World-Cup-group-stage/Kotlin/world-cup-group-stage.kotlin rename to Task/World-Cup-group-stage/Kotlin/world-cup-group-stage.kts diff --git a/Task/World-Cup-group-stage/Mathematica/world-cup-group-stage.math b/Task/World-Cup-group-stage/Mathematica/world-cup-group-stage.math new file mode 100644 index 0000000000..93420469bc --- /dev/null +++ b/Task/World-Cup-group-stage/Mathematica/world-cup-group-stage.math @@ -0,0 +1,10 @@ +scoring[1] = 3; scoring[0] = 1; scoring[-1] = 0; +scoreTable[results_] := Module[{s = {0, 0, 0, 0}, pairs = Subsets[Range[4], {2}]}, + MapThread[( + s[[First@#2]] += scoring[#1]; + s[[Last@#2]] += scoring[-#1]) &, + {results, pairs}]; + ReverseSort[s]]; + +allScoreTables = Map[scoreTable, Tuples[{-1, 0, 1}, 6]]; +Table[BinCounts[allScoreTables[[All, i]], {0, 10}], {i, 4}] // TableForm diff --git a/Task/World-Cup-group-stage/Pluto/world-cup-group-stage.pluto b/Task/World-Cup-group-stage/Pluto/world-cup-group-stage.pluto new file mode 100644 index 0000000000..636ab946bb --- /dev/null +++ b/Task/World-Cup-group-stage/Pluto/world-cup-group-stage.pluto @@ -0,0 +1,42 @@ +require "table2" +local fmt = require "fmt" + +local games = {"12", "13", "14", "23", "24", "34"} +local results = "000000" + +local function next_result() + if results == "222222" then return false end + local res = tonumber(results, 3) + 1 + results = fmt.lpad(fmt.itoa(res, 3), 6, "0") + return true +end + +local points = table.create(4) +for i = 1, 4 do points[i] = table.rep(10, 0) end +while true do + local records = table.rep(4, 0) + for i = 1, 6 do + local g1 = tonumber(games[i][1]) + local g2 = tonumber(games[i][2]) + if results[i] == "2" then + records[g1] += 3 + elseif results[i] == "1" then + records[g1] += 1 + records[g2] += 1 + elseif results[i] == "0" then + records[g2] += 3 + end + end + records:sort() + for i = 1, 4 do points[i][records[i] + 1] += 1 end + if !next_result() then break end +end +print("POINTS 0 1 2 3 4 5 6 7 8 9") +print("---------------------------------------------------------------") +for i = 0, 3 do + fmt.write("%s place ", fmt.ord(i + 1)) + points[4 - i]:foreach(|p| -> do + fmt.write("%5d", p) + end) + print() +end diff --git a/Task/World-Cup-group-stage/XPL0/world-cup-group-stage.xpl0 b/Task/World-Cup-group-stage/XPL0/world-cup-group-stage.xpl0 new file mode 100644 index 0000000000..3912494d8d --- /dev/null +++ b/Task/World-Cup-group-stage/XPL0/world-cup-group-stage.xpl0 @@ -0,0 +1,77 @@ +include xpllib; \for StrCopy, StrCopy, Sort and Print +char Results(7); + +func Next_Result; +char Ptr; +int Num, I, D, Rem; +[Ptr:= Results + 5; +Num:= 0; + +\Check if the space has been examined +if StrCmp(Results, "222222") = 0 then + return false; + +\Translate the base 3 string back to a base 10 integer +I:= 0; +while Results(I) # 0 do + [D:= Results(I) - ^0; + Num:= 3*Num + D; + I:= I+1; + ]; + +\To the next value to process +Num:= Num+1; + +\Write the base 3 string (fixed width) +while Num > 0 do + [Num:= Num/3; + Rem:= rem(0); + Ptr(0):= Rem + ^0; + Ptr:= Ptr-1; + ]; + +\Zero fill the remainder +while Ptr > Results do + [Ptr(0):= ^0; + Ptr:= Ptr-1; + ]; +return true; +]; + +\Main +char Games; +int Places, Points(4, 10), I, J, Records(4), G0, G1; +[Games:= ["12", "13", "14", "23", "24", "34"]; +Places:= ["1st", "2nd", "3rd", "4th"]; + +StrCopy(Results, "000000"); +for I:= 0 to 4-1 do + for J:= 0 to 10-1 do + Points(I, J):= 0; + +repeat for I:= 0 to 4-1 do Records(I):= 0; + for I:= 0 to 6-1 do + [G0:= @Records(Games(I,0)-^1); + G1:= @Records(Games(I,1)-^1); + case Results(I) of + ^2: G0(0):= G0(0)+3; + ^1: [G0(0):= G0(0)+1; G1(0):= G1(0)+1]; + ^0: G1(0):= G1(0)+3 + other []; + ]; + + Sort(Records, 4); + for I:= 0 to 4-1 do + Points(I, Records(I)):= Points(I, Records(I)) + 1; + +until not Next_Result; + +Print("POINTS 0 1 2 3 4 5 6 7 8 9\n"); +Print("-----------------------------------------------------------\n"); +for I:= 0 to 4-1 do + [Print("%s place", Places(I)); + for J:= 0 to 10-1 do + Print("%5d", Points(3-I, J)); + Print("\n"); + ]; +] diff --git a/Task/Write-entire-file/Ada/write-entire-file.ada b/Task/Write-entire-file/Ada/write-entire-file.adb similarity index 100% rename from Task/Write-entire-file/Ada/write-entire-file.ada rename to Task/Write-entire-file/Ada/write-entire-file.adb diff --git a/Task/Write-entire-file/AppleScript/write-entire-file.applescript b/Task/Write-entire-file/AppleScript/write-entire-file.applescript new file mode 100644 index 0000000000..566279d9d5 --- /dev/null +++ b/Task/Write-entire-file/AppleScript/write-entire-file.applescript @@ -0,0 +1,6 @@ +on overwrite(filepath, str) + set fp to open for access file filepath with write permission + set eof of fp to 0 + write str to fp + close access fp +end overwrite diff --git a/Task/Write-entire-file/ArkScript/write-entire-file.ark b/Task/Write-entire-file/ArkScript/write-entire-file.ark new file mode 100644 index 0000000000..2388fe93e8 --- /dev/null +++ b/Task/Write-entire-file/ArkScript/write-entire-file.ark @@ -0,0 +1 @@ +(io:writeFile "output.txt" "hello, world!") diff --git a/Task/Write-entire-file/Arturo/write-entire-file.arturo b/Task/Write-entire-file/Arturo/write-entire-file.arturo index a463c5827f..55dbc09d93 100644 --- a/Task/Write-entire-file/Arturo/write-entire-file.arturo +++ b/Task/Write-entire-file/Arturo/write-entire-file.arturo @@ -1,2 +1,2 @@ contents: "Hello World!" -write "output.txt" contents +contents >> "output.txt" diff --git a/Task/Write-entire-file/Batch-File/write-entire-file-1.bat b/Task/Write-entire-file/Batch-File/write-entire-file-1.bat new file mode 100644 index 0000000000..3813689275 --- /dev/null +++ b/Task/Write-entire-file/Batch-File/write-entire-file-1.bat @@ -0,0 +1,3 @@ +@echo off +setlocal enableextensions +type con>%1 || goto:eof %= exit at error =% diff --git a/Task/Write-entire-file/Batch-File/write-entire-file-2.bat b/Task/Write-entire-file/Batch-File/write-entire-file-2.bat new file mode 100644 index 0000000000..be8b31bf14 --- /dev/null +++ b/Task/Write-entire-file/Batch-File/write-entire-file-2.bat @@ -0,0 +1,5 @@ +@echo off +setlocal enableextensions +type nul>%1 || goto:eof +::don't ignore blank lines +for /f tokens^=1*^ delims^=]^ eol^= %%a in ('find /n /v ""') do echo(%%b>>%1 diff --git a/Task/Write-entire-file/COBOL/write-entire-file.cobol b/Task/Write-entire-file/COBOL/write-entire-file.cob similarity index 100% rename from Task/Write-entire-file/COBOL/write-entire-file.cobol rename to Task/Write-entire-file/COBOL/write-entire-file.cob diff --git a/Task/Write-entire-file/Crystal/write-entire-file.cr b/Task/Write-entire-file/Crystal/write-entire-file.cr new file mode 100644 index 0000000000..51a30dc094 --- /dev/null +++ b/Task/Write-entire-file/Crystal/write-entire-file.cr @@ -0,0 +1 @@ +File.write "filename", "An arbitrary string" diff --git a/Task/Write-entire-file/Delphi/write-entire-file.delphi b/Task/Write-entire-file/Delphi/write-entire-file.pas similarity index 100% rename from Task/Write-entire-file/Delphi/write-entire-file.delphi rename to Task/Write-entire-file/Delphi/write-entire-file.pas diff --git a/Task/Write-entire-file/Elena/write-entire-file.elena b/Task/Write-entire-file/Elena/write-entire-file.elena index 5c9fdcbc7f..a8a032fec4 100644 --- a/Task/Write-entire-file/Elena/write-entire-file.elena +++ b/Task/Write-entire-file/Elena/write-entire-file.elena @@ -1,6 +1,6 @@ import system'io; -public program() +public Program() { File.assign("filename.txt").saveContent("This file contains a string.") } diff --git a/Task/Write-entire-file/Elixir/write-entire-file.elixir b/Task/Write-entire-file/Elixir/write-entire-file.ex similarity index 100% rename from Task/Write-entire-file/Elixir/write-entire-file.elixir rename to Task/Write-entire-file/Elixir/write-entire-file.ex diff --git a/Task/Write-entire-file/Frink/write-entire-file.frink b/Task/Write-entire-file/Frink/write-entire-file.frink index 9a4b9aa562..5d2fadce34 100644 --- a/Task/Write-entire-file/Frink/write-entire-file.frink +++ b/Task/Write-entire-file/Frink/write-entire-file.frink @@ -1,3 +1 @@ -w = new Writer["test.txt"] -w.print["I am the captain now."] -w.close[] +w = new Writer["test.txt"].printAndClose["I am the captain now."] diff --git a/Task/Write-entire-file/Icon/write-entire-file.icon b/Task/Write-entire-file/Icon/write-entire-file.icon new file mode 100644 index 0000000000..2dd1952e44 --- /dev/null +++ b/Task/Write-entire-file/Icon/write-entire-file.icon @@ -0,0 +1,3 @@ +procedure main(A) + write(open(\A[1]|"afile","w"),"a string") +end diff --git a/Task/Write-entire-file/Julia/write-entire-file.julia b/Task/Write-entire-file/Julia/write-entire-file.jl similarity index 100% rename from Task/Write-entire-file/Julia/write-entire-file.julia rename to Task/Write-entire-file/Julia/write-entire-file.jl diff --git a/Task/Write-entire-file/Kotlin/write-entire-file.kotlin b/Task/Write-entire-file/Kotlin/write-entire-file.kts similarity index 100% rename from Task/Write-entire-file/Kotlin/write-entire-file.kotlin rename to Task/Write-entire-file/Kotlin/write-entire-file.kts diff --git a/Task/Write-entire-file/OCaml/write-entire-file.ocaml b/Task/Write-entire-file/OCaml/write-entire-file.ml similarity index 100% rename from Task/Write-entire-file/OCaml/write-entire-file.ocaml rename to Task/Write-entire-file/OCaml/write-entire-file.ml diff --git a/Task/Write-entire-file/Odin/write-entire-file.odin b/Task/Write-entire-file/Odin/write-entire-file.odin new file mode 100644 index 0000000000..e9ef5612e4 --- /dev/null +++ b/Task/Write-entire-file/Odin/write-entire-file.odin @@ -0,0 +1,20 @@ +package main + +import "core:fmt" +import "core:os" + + +main :: proc() { + + dummy := "This is a string." + write := os.write_entire_file("file",transmute([]u8)(dummy),false) + + // Returns an error + write2 := os.write_entire_file_or_err("file2",transmute([]u8)(dummy),false) + + // If error than do something + if (write2!=nil){ + fmt.println("err") + } + +} diff --git a/Task/Write-entire-file/PascalABC.NET/write-entire-file.pas b/Task/Write-entire-file/PascalABC.NET/write-entire-file.pas new file mode 100644 index 0000000000..7039e6432a --- /dev/null +++ b/Task/Write-entire-file/PascalABC.NET/write-entire-file.pas @@ -0,0 +1,2 @@ +## +WriteAllText('a.txt','string'); diff --git a/Task/Write-entire-file/Pluto/write-entire-file.pluto b/Task/Write-entire-file/Pluto/write-entire-file.pluto new file mode 100644 index 0000000000..a6ee27d209 --- /dev/null +++ b/Task/Write-entire-file/Pluto/write-entire-file.pluto @@ -0,0 +1,11 @@ +-- Create a text file. +io.contents("hello.txt", "hello") + +-- Check it worked. +print(io.contents("hello.txt")) + +-- Overwrite it by 'creating' the file again. +io.contents("hello.txt", "goodbye") + +-- Check it worked. +print(io.contents("hello.txt")) diff --git a/Task/Write-entire-file/PowerShell/write-entire-file.psh b/Task/Write-entire-file/PowerShell/write-entire-file.ps1 similarity index 100% rename from Task/Write-entire-file/PowerShell/write-entire-file.psh rename to Task/Write-entire-file/PowerShell/write-entire-file.ps1 diff --git a/Task/Write-entire-file/R/write-entire-file.r b/Task/Write-entire-file/R/write-entire-file.r new file mode 100644 index 0000000000..1e6d5a4378 --- /dev/null +++ b/Task/Write-entire-file/R/write-entire-file.r @@ -0,0 +1 @@ +writeLines(text="This is a string.", con="file.txt") diff --git a/Task/Write-entire-file/Rust/write-entire-file.rust b/Task/Write-entire-file/Rust/write-entire-file.rs similarity index 100% rename from Task/Write-entire-file/Rust/write-entire-file.rust rename to Task/Write-entire-file/Rust/write-entire-file.rs diff --git a/Task/Write-entire-file/Rye/write-entire-file.rye b/Task/Write-entire-file/Rye/write-entire-file.rye new file mode 100644 index 0000000000..7b41c2396b --- /dev/null +++ b/Task/Write-entire-file/Rye/write-entire-file.rye @@ -0,0 +1 @@ +Write %output.txt "Hello World" diff --git a/Task/Write-entire-file/VBScript/write-entire-file.vb b/Task/Write-entire-file/VBScript/write-entire-file.vbs similarity index 100% rename from Task/Write-entire-file/VBScript/write-entire-file.vb rename to Task/Write-entire-file/VBScript/write-entire-file.vbs diff --git a/Task/Write-float-arrays-to-a-text-file/ALGOL-68/write-float-arrays-to-a-text-file.alg b/Task/Write-float-arrays-to-a-text-file/ALGOL-68/write-float-arrays-to-a-text-file.alg index 032aee733d..e0187a03c6 100644 --- a/Task/Write-float-arrays-to-a-text-file/ALGOL-68/write-float-arrays-to-a-text-file.alg +++ b/Task/Write-float-arrays-to-a-text-file/ALGOL-68/write-float-arrays-to-a-text-file.alg @@ -1,31 +1,44 @@ -PROC writedat = (STRING filename, []REAL x, y, INT x width, y width)VOID: ( - FILE f; - INT errno = open(f, filename, stand out channel); - IF errno NE 0 THEN stop FI; - FOR i TO UPB x DO - # FORMAT := IF the absolute exponent is small enough, THEN use fixed ELSE use float FI; # - FORMAT repr x := ( ABS log(x[i]) 0 then + repeat with i from g to 1 by -1 + set n to n * 10 + end repeat + set n to n as integer + repeat with i from g to 1 by -1 + set n to n / 10 + end repeat + else if g = 0 then + set n to n as integer + end if + if (b < p) and (n = (n div 1)) then + return n as double integer + else + return n as real + end if +end getNumPrecision + +on log10(n) + local lg + set lg to 1 + repeat until n < 10 + set n to n / 10 + set lg to lg + 1 + end repeat + return lg +end log10 diff --git a/Task/Write-float-arrays-to-a-text-file/COBOL/write-float-arrays-to-a-text-file.cobol b/Task/Write-float-arrays-to-a-text-file/COBOL/write-float-arrays-to-a-text-file.cob similarity index 100% rename from Task/Write-float-arrays-to-a-text-file/COBOL/write-float-arrays-to-a-text-file.cobol rename to Task/Write-float-arrays-to-a-text-file/COBOL/write-float-arrays-to-a-text-file.cob diff --git a/Task/Write-float-arrays-to-a-text-file/Delphi/write-float-arrays-to-a-text-file.delphi b/Task/Write-float-arrays-to-a-text-file/Delphi/write-float-arrays-to-a-text-file-1.pas similarity index 100% rename from Task/Write-float-arrays-to-a-text-file/Delphi/write-float-arrays-to-a-text-file.delphi rename to Task/Write-float-arrays-to-a-text-file/Delphi/write-float-arrays-to-a-text-file-1.pas diff --git a/Task/Write-float-arrays-to-a-text-file/Delphi/write-float-arrays-to-a-text-file-2.pas b/Task/Write-float-arrays-to-a-text-file/Delphi/write-float-arrays-to-a-text-file-2.pas new file mode 100644 index 0000000000..da3d6b5d84 --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/Delphi/write-float-arrays-to-a-text-file-2.pas @@ -0,0 +1,3 @@ +create or replace table t (x DOUBLE, y DOUBLE); + +insert into t select unnest ([1, 2, 3, 1e11]) as x, sqrt(x) as y; diff --git a/Task/Write-float-arrays-to-a-text-file/Delphi/write-float-arrays-to-a-text-file-3.pas b/Task/Write-float-arrays-to-a-text-file/Delphi/write-float-arrays-to-a-text-file-3.pas new file mode 100644 index 0000000000..70596cc0cf --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/Delphi/write-float-arrays-to-a-text-file-3.pas @@ -0,0 +1,6 @@ +.header off +.mode list +.output output.tsv +select format('{:.3f}', x) || chr(9) || format('{:.5f}', y) from t; +.output +.shell cat output.tsv diff --git a/Task/Write-float-arrays-to-a-text-file/Delphi/write-float-arrays-to-a-text-file-4.pas b/Task/Write-float-arrays-to-a-text-file/Delphi/write-float-arrays-to-a-text-file-4.pas new file mode 100644 index 0000000000..c9fce11703 --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/Delphi/write-float-arrays-to-a-text-file-4.pas @@ -0,0 +1,5 @@ +create or replace table neat (x DECIMAL(38,3), y DECIMAL(38,5)); +insert into neat from t; +from neat; +copy neat to 'output.tsv' (HEADER true, DELIMITER '\t'); +.shell cat output.tsv diff --git a/Task/Write-float-arrays-to-a-text-file/Elixir/write-float-arrays-to-a-text-file.elixir b/Task/Write-float-arrays-to-a-text-file/Elixir/write-float-arrays-to-a-text-file.ex similarity index 100% rename from Task/Write-float-arrays-to-a-text-file/Elixir/write-float-arrays-to-a-text-file.elixir rename to Task/Write-float-arrays-to-a-text-file/Elixir/write-float-arrays-to-a-text-file.ex diff --git a/Task/Write-float-arrays-to-a-text-file/Euphoria/write-float-arrays-to-a-text-file.euphoria b/Task/Write-float-arrays-to-a-text-file/Euphoria/write-float-arrays-to-a-text-file.eu similarity index 100% rename from Task/Write-float-arrays-to-a-text-file/Euphoria/write-float-arrays-to-a-text-file.euphoria rename to Task/Write-float-arrays-to-a-text-file/Euphoria/write-float-arrays-to-a-text-file.eu diff --git a/Task/Write-float-arrays-to-a-text-file/FutureBasic/write-float-arrays-to-a-text-file.basic b/Task/Write-float-arrays-to-a-text-file/FutureBasic/write-float-arrays-to-a-text-file.basic index 0ec9072912..a7966953a2 100644 --- a/Task/Write-float-arrays-to-a-text-file/FutureBasic/write-float-arrays-to-a-text-file.basic +++ b/Task/Write-float-arrays-to-a-text-file/FutureBasic/write-float-arrays-to-a-text-file.basic @@ -27,4 +27,4 @@ end fn fn DoIt -HandleEven +HandleEvents diff --git a/Task/Write-float-arrays-to-a-text-file/Julia/write-float-arrays-to-a-text-file.julia b/Task/Write-float-arrays-to-a-text-file/Julia/write-float-arrays-to-a-text-file.jl similarity index 100% rename from Task/Write-float-arrays-to-a-text-file/Julia/write-float-arrays-to-a-text-file.julia rename to Task/Write-float-arrays-to-a-text-file/Julia/write-float-arrays-to-a-text-file.jl diff --git a/Task/Write-float-arrays-to-a-text-file/K/write-float-arrays-to-a-text-file.k b/Task/Write-float-arrays-to-a-text-file/K/write-float-arrays-to-a-text-file.k new file mode 100644 index 0000000000..5c0b46a34c --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/K/write-float-arrays-to-a-text-file.k @@ -0,0 +1,16 @@ +xprecision:3 +yprecision:5 +x: 1 2 3 1e11 +y: 1 1.412135627930951 1.7320508075688772 316227.76601683791 +// for truncuating, see "Learning K Programming, Idiom by Idiom" 460 +xx:{ {1%(*/y#x)}[10;-xprecision] * _x*{*/y#x}[10;xprecision] } x +yy:{ {1%(*/y#x)}[10;-yprecision] * _x*{*/y#x}[10;yprecision] } y +// reshaping and transposing with + +result: +2 4#xx,yy + +// add to string res +res::"" +dummy: {res::res,$x[0];res::res," ";res::res,$x[1];res::res,"\n" }'result + +// output to txt file with 0: +`floatarray.txt 0:res diff --git a/Task/Write-float-arrays-to-a-text-file/Kotlin/write-float-arrays-to-a-text-file.kotlin b/Task/Write-float-arrays-to-a-text-file/Kotlin/write-float-arrays-to-a-text-file.kts similarity index 100% rename from Task/Write-float-arrays-to-a-text-file/Kotlin/write-float-arrays-to-a-text-file.kotlin rename to Task/Write-float-arrays-to-a-text-file/Kotlin/write-float-arrays-to-a-text-file.kts diff --git a/Task/Write-float-arrays-to-a-text-file/OCaml/write-float-arrays-to-a-text-file.ocaml b/Task/Write-float-arrays-to-a-text-file/OCaml/write-float-arrays-to-a-text-file.ml similarity index 100% rename from Task/Write-float-arrays-to-a-text-file/OCaml/write-float-arrays-to-a-text-file.ocaml rename to Task/Write-float-arrays-to-a-text-file/OCaml/write-float-arrays-to-a-text-file.ml diff --git a/Task/Write-float-arrays-to-a-text-file/Phix/write-float-arrays-to-a-text-file.phix b/Task/Write-float-arrays-to-a-text-file/Phix/write-float-arrays-to-a-text-file.phix index 40eaa6fb1e..760139fbc0 100644 --- a/Task/Write-float-arrays-to-a-text-file/Phix/write-float-arrays-to-a-text-file.phix +++ b/Task/Write-float-arrays-to-a-text-file/Phix/write-float-arrays-to-a-text-file.phix @@ -1,10 +1,8 @@ ---> - constant x = {1, 2, 3, 1e11}, - y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791} +constant x = {1, 2, 3, 1e11}, + y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791} - integer fn = open("filename","w") - for i=1 to length(x) do - printf(fn,"%.3g\t%.5g\n",{x[i],y[i]}) - end for - close(fn) - - constant s = """ - ------*** * - -----* * * - ----* * * * - ---*** * - --* *** * * * - -* * * * * - * * * * * * - """ - puts(1,substitute_all(s,"* ",{"_/"," "})) - - constant q = {0(30)10C,0(31)176,0(32)2A4,0(33)6N3,0(34)7GP,0(35)DWF,0(36)QC4} - puts(1,substitute_all(sprintf(join(repeat("%16b",7),"\n"),q)," 10",{"-","_/"," "})&"\n") - - puts(1,""" - __ ________ - /_/\ / ______ \ - \ \ \/ /\____/ /\ __ - \ \ \/ / / / //_/\ - \ \ \/___/ / / \_\/_ __ - /\ \______/ / /_/\/ /\ - / /\ ____ \ \ \ \ \/ / - / / /\ \ \ \ \ \ \_\ / - / / / \ \ \ \ \ \ / / \ - /_/ / \ \ \ \ \ \ /_/ /\ \ - \_\/ \_\/ \_\/ \_\/\_\/ - """) - -- or if you prefer something a little more cryptic (same output): - puts(1," __ ________\n /_/\\ / ______ \\\n \\ \\ \\/ /\\____/ /\\ __\n "& - "\\ \\ \\/ / / / //_/\\\n \\ \\ \\/___/ / / \\_\\/_ __\n /\\ \\__"& - "____/ / /_/\\/ /\\\n / /\\ ____ \\ \\ \\ \\ \\/ /\n / / /\\ \\ "& - "\\ \\ \\ \\ \\_\\ /\n / / / \\ \\ \\ \\ \\ \\ / / \\\n/_/ / \\"& - " \\ \\ \\ \\ \\ /_/ /\\ \\\n\\_\\/ \\_\\/ \\_\\/ \\_\\/\\_\\/\n") -":?XML - | "?"&!XML "\n":?XML - | "![CDATA[" - & !XML "":?XML - | "!DOCTYPE" - & !XML "":?XML - | ? - & !XML "<" !A doAttributes$!B ">":?XML - ) - ) - | !XML PCDATAentities$!first:?XML - ) - ) - & str$!XML - ) - & doAll$!arg - ) -& ( makeList - = characters name names remark remarks - . !arg:(?names.?remarks) - & :?characters - & whl - ' ( (!names.!remarks) - : (%?name ?names.%?remark ?remarks) - & !characters (Character.(name.!name),!remark) - : ?characters - ) - & ("?".xml) (CharacterRemarks.,!characters) - ) -& put - $ ( 2XML - $ ( makeList - $ ( April "Tam O'Shanter" Emily - . "Bubbly: I'm > Tam and <= Emily" - "Burns: \"When chapman billies leave the street ...\"" - "Short & shrift" - ) - ) - ) -) diff --git a/Task/XML-Output/Delphi/xml-output.delphi b/Task/XML-Output/Delphi/xml-output.pas similarity index 100% rename from Task/XML-Output/Delphi/xml-output.delphi rename to Task/XML-Output/Delphi/xml-output.pas diff --git a/Task/XML-Output/Euphoria/xml-output.euphoria b/Task/XML-Output/Euphoria/xml-output.eu similarity index 100% rename from Task/XML-Output/Euphoria/xml-output.euphoria rename to Task/XML-Output/Euphoria/xml-output.eu diff --git a/Task/XML-Output/FutureBasic/xml-output.basic b/Task/XML-Output/FutureBasic/xml-output.basic new file mode 100644 index 0000000000..73933871bb --- /dev/null +++ b/Task/XML-Output/FutureBasic/xml-output.basic @@ -0,0 +1,52 @@ +include "NSLog.incl" +include "Tlbx XML.incl" + +local fn FormattedXMLTest + // Input data + CFArrayRef names = @[@"April", @"Tam O'Shanter", @"Emily"] + CFArrayRef remarks = @[@"Bubbly: I'm > Tam and <= Emily", + @"Burns: \"When chapman billies leave the street ...\"", + @"Short & shrift"] + + // Root element + XMLElementRef root = fn XMLElementWithName( @"CharacterRemarks" ) + + // Create each element + for NSInteger i = 0 to fn ArrayCount(names) - 1 + XMLElementRef character = fn XMLElementWithName( @"Character" ) + + // Add name attribute + XMLNodeRef nameAttr = fn XMLNodeAttributeWithName( @"name", names[i] ) + XMLElementAddAttribute( character, nameAttr ) + + // Add remark as text content + XMLNodeRef textNode = fn XMLNodeTextWithStringValue( remarks[i] ) + XMLElementAddChild( character, textNode ) + XMLElementAddChild( root, character ) + next + + // Build the document + XMLDocumentRef doc = fn XMLDocumentWithRootElement(root) + XMLDocumentSetCharacterEncoding( doc, @"UTF-8" ) + XMLDocumentSetVersion( doc, @"1.0" ) + + // Output file path + CFStringRef path = @"/tmp/characters.xml" + + // Write the XML to file (pretty printed) + CFDataRef xmlData = fn XMLDocumentXMLDataWithOptions( doc, NSXMLNodePrettyPrint ) + CFURLRef desktopURL = fn FileManagerURLForDirectory( NSDesktopDirectory, NSUserDomainMask ) + CFURLRef url = fn URLByAppendingPathComponent( desktopURL, @"XML_Test.xml" ) + BOOL success = fn DataWriteToURL( xmlData, url, NSDataWritingAtomic, NULL ) + + if ( success == YES ) + NSLog( @"XML file successfully written to: %@", url ) + fn WorkSpaceOpenURL( url ) + else + NSLog( @"Failed to write XML file" ) + end if +end fn + +fn FormattedXMLTest + +HandleEvents diff --git a/Task/XML-Output/Julia/xml-output.julia b/Task/XML-Output/Julia/xml-output.jl similarity index 100% rename from Task/XML-Output/Julia/xml-output.julia rename to Task/XML-Output/Julia/xml-output.jl diff --git a/Task/XML-Output/Kotlin/xml-output-1.kotlin b/Task/XML-Output/Kotlin/xml-output-1.kts similarity index 100% rename from Task/XML-Output/Kotlin/xml-output-1.kotlin rename to Task/XML-Output/Kotlin/xml-output-1.kts diff --git a/Task/XML-Output/Kotlin/xml-output-2.kotlin b/Task/XML-Output/Kotlin/xml-output-2.kts similarity index 100% rename from Task/XML-Output/Kotlin/xml-output-2.kotlin rename to Task/XML-Output/Kotlin/xml-output-2.kts diff --git a/Task/XML-Output/OCaml/xml-output-1.ocaml b/Task/XML-Output/OCaml/xml-output-1.ml similarity index 100% rename from Task/XML-Output/OCaml/xml-output-1.ocaml rename to Task/XML-Output/OCaml/xml-output-1.ml diff --git a/Task/XML-Output/OCaml/xml-output-2.ocaml b/Task/XML-Output/OCaml/xml-output-2.ml similarity index 100% rename from Task/XML-Output/OCaml/xml-output-2.ocaml rename to Task/XML-Output/OCaml/xml-output-2.ml diff --git a/Task/XML-Output/PascalABC.NET/xml-output.pas b/Task/XML-Output/PascalABC.NET/xml-output.pas new file mode 100644 index 0000000000..fb0e205c2e --- /dev/null +++ b/Task/XML-Output/PascalABC.NET/xml-output.pas @@ -0,0 +1,20 @@ +{$reference System.Xml.Linq.dll} +{$reference System.Xml.XDocument.dll} +uses System.Xml.Linq; + +function CreateXML(characterRemarks: Dictionary ): string; +begin + var remarks := characterRemarks.Select(r -> new XElement('Character', r.Value, new XAttribute('Name', r.Key))); + var xml := new XElement('CharacterRemarks', remarks); + Result := xml.ToString; +end; + +begin + var characterRemarks := Dict( + ('April', 'Bubbly: I''m > Tam and <= Emily' ), + ( 'Tam O''Shanter', 'Burns: "When chapman billies leave the street ..."' ), + ( 'Emily', 'Short & shrift' ) + ); + var xml := CreateXML(characterRemarks); + Writeln(xml); +end. diff --git a/Task/XML-Output/Rust/xml-output.rust b/Task/XML-Output/Rust/xml-output.rs similarity index 100% rename from Task/XML-Output/Rust/xml-output.rust rename to Task/XML-Output/Rust/xml-output.rs diff --git a/Task/XML-Output/VBScript/xml-output.vb b/Task/XML-Output/VBScript/xml-output.vbs similarity index 100% rename from Task/XML-Output/VBScript/xml-output.vb rename to Task/XML-Output/VBScript/xml-output.vbs diff --git a/Task/XML-XPath/Crystal/xml-xpath.cr b/Task/XML-XPath/Crystal/xml-xpath.cr new file mode 100644 index 0000000000..02fefe5ba5 --- /dev/null +++ b/Task/XML-XPath/Crystal/xml-xpath.cr @@ -0,0 +1,45 @@ +require "xml" +str = <<-XML + + + + + Invisibility Cream + 14.50 + Makes you invisible + + + Levitation Salve + 23.99 + Levitate yourself for up to 3 hours per application + + + + + + + Blork and Freen Instameal + 4.95 + A tasty meal in a tablet; just add water + + + Grob winglets + 3.56 + Tender winglets of Grob. Just add water + + + + +XML + +doc = XML.parse str +# Retrieve the first "item" element +first_item = doc.xpath("//item[1]") + +# Perform an action on each "price" element (print it out) +doc.xpath_nodes("//price/text()").each do |price| + puts price +end + +# Get an array of all the "name" elements +names = doc.xpath_nodes("//name").to_a diff --git a/Task/XML-XPath/Delphi/xml-xpath-1.delphi b/Task/XML-XPath/Delphi/xml-xpath-1.pas similarity index 100% rename from Task/XML-XPath/Delphi/xml-xpath-1.delphi rename to Task/XML-XPath/Delphi/xml-xpath-1.pas diff --git a/Task/XML-XPath/Delphi/xml-xpath-2.delphi b/Task/XML-XPath/Delphi/xml-xpath-2.pas similarity index 100% rename from Task/XML-XPath/Delphi/xml-xpath-2.delphi rename to Task/XML-XPath/Delphi/xml-xpath-2.pas diff --git a/Task/XML-XPath/Julia/xml-xpath.julia b/Task/XML-XPath/Julia/xml-xpath.jl similarity index 100% rename from Task/XML-XPath/Julia/xml-xpath.julia rename to Task/XML-XPath/Julia/xml-xpath.jl diff --git a/Task/XML-XPath/Kotlin/xml-xpath.kotlin b/Task/XML-XPath/Kotlin/xml-xpath.kts similarity index 100% rename from Task/XML-XPath/Kotlin/xml-xpath.kotlin rename to Task/XML-XPath/Kotlin/xml-xpath.kts diff --git a/Task/XML-XPath/PowerShell/xml-xpath-1.psh b/Task/XML-XPath/PowerShell/xml-xpath-1.ps1 similarity index 100% rename from Task/XML-XPath/PowerShell/xml-xpath-1.psh rename to Task/XML-XPath/PowerShell/xml-xpath-1.ps1 diff --git a/Task/XML-XPath/PowerShell/xml-xpath-2.psh b/Task/XML-XPath/PowerShell/xml-xpath-2.ps1 similarity index 100% rename from Task/XML-XPath/PowerShell/xml-xpath-2.psh rename to Task/XML-XPath/PowerShell/xml-xpath-2.ps1 diff --git a/Task/XML-XPath/PowerShell/xml-xpath-3.psh b/Task/XML-XPath/PowerShell/xml-xpath-3.ps1 similarity index 100% rename from Task/XML-XPath/PowerShell/xml-xpath-3.psh rename to Task/XML-XPath/PowerShell/xml-xpath-3.ps1 diff --git a/Task/XML-XPath/PowerShell/xml-xpath-4.psh b/Task/XML-XPath/PowerShell/xml-xpath-4.ps1 similarity index 100% rename from Task/XML-XPath/PowerShell/xml-xpath-4.psh rename to Task/XML-XPath/PowerShell/xml-xpath-4.ps1 diff --git a/Task/XML-XPath/PowerShell/xml-xpath-5.psh b/Task/XML-XPath/PowerShell/xml-xpath-5.ps1 similarity index 100% rename from Task/XML-XPath/PowerShell/xml-xpath-5.psh rename to Task/XML-XPath/PowerShell/xml-xpath-5.ps1 diff --git a/Task/XML-XPath/VBScript/xml-xpath.vb b/Task/XML-XPath/VBScript/xml-xpath.vbs similarity index 100% rename from Task/XML-XPath/VBScript/xml-xpath.vb rename to Task/XML-XPath/VBScript/xml-xpath.vbs diff --git a/Task/Xiaolin-Wus-line-algorithm/EasyLang/xiaolin-wus-line-algorithm.easy b/Task/Xiaolin-Wus-line-algorithm/EasyLang/xiaolin-wus-line-algorithm.easy new file mode 100644 index 0000000000..6bd994f126 --- /dev/null +++ b/Task/Xiaolin-Wus-line-algorithm/EasyLang/xiaolin-wus-line-algorithm.easy @@ -0,0 +1,71 @@ +size = 400 +# +sc = 100 / size +global plotswap . +proc plot x y b . + b = 1 - b + if plotswap = 1 : swap x y + gcolor3 b b b + grect x * sc y * sc sc sc +. +func ipart x . + return floor x +. +func round x . + return floor (x + 0.5) +. +func fpart x . + return x - floor x +. +func rfpart x . + return 1 - x + floor x +. +proc aaLine x1 y1 x2 y2 . + dx = x2 - x1 + dy = y2 - y1 + ax = dx + if ax < 0 : ax = -ax + ay = dy + if ay < 0 : ay = -ay + plotswap = 0 + if ax < ay + swap x1 y1 + swap x2 y2 + swap dx dy + plotswap = 1 + . + if x2 < x1 + swap x1 x2 + swap y1 y2 + . + gradient = dy / dx + xend = round x1 + yend = y1 + gradient * (xend - x1) + xgap = rfpart (x1 + 0.5) + xpxl1 = xend + ypxl1 = ipart yend + plot xpxl1 ypxl1 rfpart yend * xgap + plot xpxl1 (ypxl1 + 1) fpart yend * xgap + intery = yend + gradient + xend = round x2 + yend = y2 + gradient * (xend - x2) + xgap = fpart (x2 + 0.5) + xpxl2 = xend + ypxl2 = ipart yend + plot xpxl2 ypxl2 rfpart yend * xgap + plot xpxl2 (ypxl2 + 1) fpart yend * xgap + for x = xpxl1 + 1 to xpxl2 - 1 + plot x ipart intery rfpart intery + plot x ipart intery + 1 fpart intery + intery += gradient + . +. +gbackground 999 +gclear +# +r = size / 2 +r1 = 0.15 * r +r2 = 0.95 * r +for ang = 0 step 5 to 360 + aaLine r + r1 * sin ang, r + r1 * cos ang, r + r2 * sin ang, r + r2 * cos ang +. diff --git a/Task/Xiaolin-Wus-line-algorithm/Julia/xiaolin-wus-line-algorithm.julia b/Task/Xiaolin-Wus-line-algorithm/Julia/xiaolin-wus-line-algorithm.jl similarity index 100% rename from Task/Xiaolin-Wus-line-algorithm/Julia/xiaolin-wus-line-algorithm.julia rename to Task/Xiaolin-Wus-line-algorithm/Julia/xiaolin-wus-line-algorithm.jl diff --git a/Task/Xiaolin-Wus-line-algorithm/Kotlin/xiaolin-wus-line-algorithm.kotlin b/Task/Xiaolin-Wus-line-algorithm/Kotlin/xiaolin-wus-line-algorithm.kts similarity index 100% rename from Task/Xiaolin-Wus-line-algorithm/Kotlin/xiaolin-wus-line-algorithm.kotlin rename to Task/Xiaolin-Wus-line-algorithm/Kotlin/xiaolin-wus-line-algorithm.kts diff --git a/Task/Xiaolin-Wus-line-algorithm/Rust/xiaolin-wus-line-algorithm.rs b/Task/Xiaolin-Wus-line-algorithm/Rust/xiaolin-wus-line-algorithm.rs new file mode 100644 index 0000000000..b091cc618e --- /dev/null +++ b/Task/Xiaolin-Wus-line-algorithm/Rust/xiaolin-wus-line-algorithm.rs @@ -0,0 +1,120 @@ +use std::cmp; + +fn wu_draw_line( + mut x0: f32, + mut y0: f32, + mut x1: f32, + mut y1: f32, + mut plot: impl FnMut(i32, i32, f32), +) { + let ipart = |x: f32| -> i32 { x.floor() as i32 }; + let round = |x: f32| -> f32 { x.round() }; + let fpart = |x: f32| -> f32 { x - x.floor() }; + let rfpart = |x: f32| -> f32 { 1.0 - fpart(x) }; + + let steep = (y1 - y0).abs() > (x1 - x0).abs(); + if steep { + std::mem::swap(&mut x0, &mut y0); + std::mem::swap(&mut x1, &mut y1); + } + if x0 > x1 { + std::mem::swap(&mut x0, &mut x1); + std::mem::swap(&mut y0, &mut y1); + } + + let dx = x1 - x0; + let dy = y1 - y0; + let gradient = if dx == 0.0 { 1.0 } else { dy / dx }; + + let xpx11: i32; + let mut intery: f32; + { + let xend = round(x0); + let yend = y0 + gradient * (xend - x0); + let xgap = rfpart(x0 + 0.5); + xpx11 = xend as i32; + let ypx11 = ipart(yend); + if steep { + plot(ypx11, xpx11, rfpart(yend) * xgap); + plot(ypx11 + 1, xpx11, fpart(yend) * xgap); + } else { + plot(xpx11, ypx11, rfpart(yend) * xgap); + plot(xpx11, ypx11 + 1, fpart(yend) * xgap); + } + intery = yend + gradient; + } + + let xpx12: i32; + { + let xend = round(x1); + let yend = y1 + gradient * (xend - x1); + let xgap = rfpart(x1 + 0.5); + xpx12 = xend as i32; + let ypx12 = ipart(yend); + if steep { + plot(ypx12, xpx12, rfpart(yend) * xgap); + plot(ypx12 + 1, xpx12, fpart(yend) * xgap); + } else { + plot(xpx12, ypx12, rfpart(yend) * xgap); + plot(xpx12, ypx12 + 1, fpart(yend) * xgap); + } + } + + if steep { + for x in xpx11 + 1..xpx12 { + let ipy = ipart(intery); + plot(ipy, x, rfpart(intery)); + plot(ipy + 1, x, fpart(intery)); + intery += gradient; + } + } else { + for x in xpx11 + 1..xpx12 { + let ipy = ipart(intery); + plot(x, ipy, rfpart(intery)); + plot(x, ipy + 1, fpart(intery)); + intery += gradient; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_wu_draw_line() { + let mut pixels = vec![vec![0.0; 10]; 10]; // Create a 10x10 grid of floats + let plot = |x: i32, y: i32, brightness: f32| { + if x >= 0 && x < 10 && y >= 0 && y < 10 { + pixels[x as usize][y as usize] = brightness; + } + }; + + wu_draw_line(1.0, 1.0, 8.0, 8.0, plot); + + // Basic validation: Check that some pixels are lit up + assert!(pixels[1][1] > 0.0); + assert!(pixels[8][8] > 0.0); + + // You can add more specific assertions here based on the expected output. + // For example, check the values of pixels along the expected line path. + // Be aware of floating point precision when comparing. + } + + #[test] + fn test_wu_draw_line_steep() { + let mut pixels = vec![vec![0.0; 10]; 10]; // Create a 10x10 grid of floats + let plot = |x: i32, y: i32, brightness: f32| { + if x >= 0 && x < 10 && y >= 0 && y < 10 { + pixels[x as usize][y as usize] = brightness; + } + }; + + wu_draw_line(1.0, 1.0, 2.0, 8.0, plot); + + // Basic validation: Check that some pixels are lit up + assert!(pixels[1][1] > 0.0); + assert!(pixels[2][8] > 0.0); + } +} + diff --git a/Task/Xiaolin-Wus-line-algorithm/Scheme/xiaolin-wus-line-algorithm-1.ss b/Task/Xiaolin-Wus-line-algorithm/Scheme/xiaolin-wus-line-algorithm-1.scm similarity index 100% rename from Task/Xiaolin-Wus-line-algorithm/Scheme/xiaolin-wus-line-algorithm-1.ss rename to Task/Xiaolin-Wus-line-algorithm/Scheme/xiaolin-wus-line-algorithm-1.scm diff --git a/Task/Xiaolin-Wus-line-algorithm/Scheme/xiaolin-wus-line-algorithm-2.ss b/Task/Xiaolin-Wus-line-algorithm/Scheme/xiaolin-wus-line-algorithm-2.scm similarity index 100% rename from Task/Xiaolin-Wus-line-algorithm/Scheme/xiaolin-wus-line-algorithm-2.ss rename to Task/Xiaolin-Wus-line-algorithm/Scheme/xiaolin-wus-line-algorithm-2.scm diff --git a/Task/Xiaolin-Wus-line-algorithm/YAMLScript/xiaolin-wus-line-algorithm.ys b/Task/Xiaolin-Wus-line-algorithm/YAMLScript/xiaolin-wus-line-algorithm.ys new file mode 100644 index 0000000000..d94adce73d --- /dev/null +++ b/Task/Xiaolin-Wus-line-algorithm/YAMLScript/xiaolin-wus-line-algorithm.ys @@ -0,0 +1,52 @@ +!YS-v0 + +defn main(): + draw-line: 0 1 10 2 + +defn draw-line(x0 y0 x1 y1): + plot x0 x1 y0 y1 =: + if abs(y1 - y0) > abs(x1 - x0): + + [\(plot(y0 x0 x1)) y0 x0 y1 x1] + [plot x0 x1 y0 y1] + + x0 x1 y0 y1 =: + if x0 > x1: + + [x1 x0 y1 y0] + [x0 x1 y0 y1] + + dx =: x1 - x0 + dy =: y1 - y0 + gradient =: dy / dx + + intery xends =: + loop intery 0, xends [], [[x y] *xys] [[x0 y0] [x1 y1]]: + xend =: round(x) + yend =: y + (gradient * (xend - x)) + xgap =: rfpart(x + 0.5) + + x-pixel =: xend + y-pixel =: yend:to-int + xends =: xends.conj(x-pixel) + + plot: x-pixel y-pixel (rfpart(yend) * xgap) + plot: x-pixel y-pixel.++ (fpart(yend) * xgap) + intery |||=: yend + gradient + + if xys.?: + recur: intery, xends, xys + vector: intery, xends + + loop intery intery, [x *xs] (xends.0.++ .. xends.1.--): + plot: x intery:I rfpart(intery) + plot: x intery:I.++ fpart(intery) + when xs.?: + recur (intery + gradient): xs + +defn plot(x y c): + when c != 0.0: + say: + format 'plot %d %d %.1f': x y c:F + +defn fpart(x): x - x:to-int + +defn rfpart(x): 1 - fpart(x) diff --git a/Task/Y-combinator/Chapel/y-combinator-1.chapel b/Task/Y-combinator/Chapel/y-combinator-1.chpl similarity index 100% rename from Task/Y-combinator/Chapel/y-combinator-1.chapel rename to Task/Y-combinator/Chapel/y-combinator-1.chpl diff --git a/Task/Y-combinator/Chapel/y-combinator-2.chapel b/Task/Y-combinator/Chapel/y-combinator-2.chpl similarity index 100% rename from Task/Y-combinator/Chapel/y-combinator-2.chapel rename to Task/Y-combinator/Chapel/y-combinator-2.chpl diff --git a/Task/Y-combinator/Crystal/y-combinator-1.crystal b/Task/Y-combinator/Crystal/y-combinator-1.cr similarity index 100% rename from Task/Y-combinator/Crystal/y-combinator-1.crystal rename to Task/Y-combinator/Crystal/y-combinator-1.cr diff --git a/Task/Y-combinator/Crystal/y-combinator-2.crystal b/Task/Y-combinator/Crystal/y-combinator-2.cr similarity index 100% rename from Task/Y-combinator/Crystal/y-combinator-2.crystal rename to Task/Y-combinator/Crystal/y-combinator-2.cr diff --git a/Task/Y-combinator/Crystal/y-combinator-3.crystal b/Task/Y-combinator/Crystal/y-combinator-3.cr similarity index 100% rename from Task/Y-combinator/Crystal/y-combinator-3.crystal rename to Task/Y-combinator/Crystal/y-combinator-3.cr diff --git a/Task/Y-combinator/Delphi/y-combinator.delphi b/Task/Y-combinator/Delphi/y-combinator.pas similarity index 100% rename from Task/Y-combinator/Delphi/y-combinator.delphi rename to Task/Y-combinator/Delphi/y-combinator.pas diff --git a/Task/Y-combinator/Elena/y-combinator.elena b/Task/Y-combinator/Elena/y-combinator.elena index a4e6cabc3c..c61b894352 100644 --- a/Task/Y-combinator/Elena/y-combinator.elena +++ b/Task/Y-combinator/Elena/y-combinator.elena @@ -6,11 +6,11 @@ singleton YCombinator = (f){(x){ x(x) }((g){ f((x){ (g(g))(x) })})}(func); } -public program() +public Program() { 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)); + Console.printLine("fib(10)=",fib(10)); + Console.printLine("fact(10)=",fact(10)); } diff --git a/Task/Y-combinator/Elixir/y-combinator.elixir b/Task/Y-combinator/Elixir/y-combinator.ex similarity index 100% rename from Task/Y-combinator/Elixir/y-combinator.elixir rename to Task/Y-combinator/Elixir/y-combinator.ex diff --git a/Task/Y-combinator/Elm/y-combinator.elm b/Task/Y-combinator/Elm/y-combinator.elm index a10d8ee074..4aa88c778a 100644 --- a/Task/Y-combinator/Elm/y-combinator.elm +++ b/Task/Y-combinator/Elm/y-combinator.elm @@ -2,18 +2,14 @@ module Main exposing ( main ) import Html exposing ( Html, text ) --- As with most of the strict (non-deferred or non-lazy) languages, --- this is the Z-combinator with the additional value parameter... +-- Recursive wrapper Type required for statically-typed languages... +type Mu a = Roll (Mu a -> a) +unroll : Mu a -> (Mu a -> a) +unroll (Roll v) = v --- wrap type conversion to avoid recursive type definition... -type Mu a b = Roll (Mu a b -> a -> b) - -unroll : Mu a b -> (Mu a b -> a -> b) -- unwrap it... -unroll (Roll x) = x - --- note lack of beta reduction using values... +-- the non-sharing non-recursive implementation of the Z-Combinator... fixz : ((a -> b) -> (a -> b)) -> (a -> b) -fixz f = let g r = f (\ v -> unroll r r v) in g (Roll g) +fixz f = let g = \ x v -> f (unroll x x) v in g (Roll g) facz : Int -> Int -- facz = fixz <| \ f n -> if n < 2 then 1 else n * f (n - 1) -- inefficient recursion @@ -23,14 +19,18 @@ fibz : Int -> Int -- fibz = fixz <| \ f n -> if n < 2 then n else f (n - 1) + f (n - 2) -- inefficient recursion fibz = fixz (\ fn f s i -> if i < 2 then f else fn s (f + s) (i - 1)) 1 1 -- efficient tailcall --- by injecting laziness, we can get the true Y-combinator... --- as this includes laziness, there is no need for the type wrapper! +-- the non-sharing non-recursive implementation of fixy with injected laziness... +-- this works for languages that are "strict" = non-lazy by default... fixy : ((() -> a) -> a) -> a -fixy f = f <| \ () -> fixy f -- direct function recursion --- the above is not value recursion but function recursion! --- fixv f = let x = f x in x -- not allowed by task or by Elm! --- we can make Elm allow it by injecting laziness... --- fixv f = let x = f () x in x -- but now value recursion not function recursion +fixy f = let g x = f <| \ () -> (unroll x) x in g (Roll g) + +{-- } --as Elm allows function recursion, the above is equivalent to the following: +fixy f = f <| \ () -> fixy f +--} + +-- sharing version if `(() -> a)` is lazy memoizing value of `a` - Elm doesn't have memoization! +fix : ((() -> a) -> a) -> a -- however, it works as a Y Combinator... +fix f = let x() = f x in x() facy : Int -> Int -- facy = fixy <| \ f n -> if n < 2 then 1 else n * f () (n - 1) -- inefficient recursion @@ -40,22 +40,24 @@ fiby : Int -> Int -- fiby = fixy <| \ f n -> if n < 2 then n else f () (n - 1) + f (n - 2) -- inefficient recursion fiby = fixy (\ fn f s i -> if i < 2 then f else fn () s (f + s) (i - 1)) 1 1 -- efficient tailcall --- something that can be done with a true Y-Combinator that --- can't be done with the Z combinator... --- given an infinite Co-Inductive Stream (CIS) defined as... -type CIS a = CIS a (() -> CIS a) -- infinite lazy stream! +-- Something that can be done with the true Y-Combinator that can't be done with Z-Combinator... + +-- defines a Co-Inductive Lazy (non-memoizing, just deferred) Stream... +type CIS a = CIS a (() -> CIS a) mapCIS : (a -> b) -> CIS a -> CIS b -- uses function to map mapCIS cf cis = let mp (CIS head restf) = CIS (cf head) <| \ () -> mp (restf()) in mp cis --- now we can define a Fibonacci stream as follows... -fibs : () -> CIS Int -fibs() = -- two recursive fix's, second already lazy... - let fibsgen = fixy (\ fn (CIS (f, s) restf) -> - CIS (s, f + s) (\ () -> fn () (restf()))) - in fixy (\ cisthnk -> fibsgen (CIS (0, 1) cisthnk)) - |> mapCIS (\ (v, _) -> v) +iterateCISWithFrom : (CIS a -> CIS a) -> a -> CIS a +iterateCISWithFrom f v = fixy (\ dfn -> f (CIS v dfn)) + +fibsfunc : CIS (Int, Int) -> CIS (Int, Int) +fibsfunc = fixy (\ dfn -> \ (CIS ((cur, nxt) as hd) tlf) -> + CIS hd <| \ () -> dfn () (CIS (nxt, (cur + nxt)) tlf)) + +fibs : CIS Int +fibs = iterateCISWithFrom fibsfunc (1, 1) |> mapCIS (\ (v, _) -> v) nCISs2String : Int -> CIS a -> String -- convert n CIS's to String nCISs2String n cis = @@ -64,12 +66,9 @@ nCISs2String n cis = loop (i - 1) (restf()) (rslt ++ " " ++ Debug.toString head) in loop n cis "(" --- unfortunately, if we need CIS memoization so as --- to make a true lazy list, Elm doesn't support it!!! - main : Html Never main = String.fromInt (facz 10) ++ " " ++ String.fromInt (fibz 10) ++ " " ++ String.fromInt (facy 10) ++ " " ++ String.fromInt (fiby 10) - ++ " " ++ nCISs2String 20 (fibs()) + ++ " " ++ nCISs2String 20 fibs |> text diff --git a/Task/Y-combinator/F-Sharp/y-combinator-1.fs b/Task/Y-combinator/F-Sharp/y-combinator-1.fs index 6b5376cb55..d4a0a79efd 100644 --- a/Task/Y-combinator/F-Sharp/y-combinator-1.fs +++ b/Task/Y-combinator/F-Sharp/y-combinator-1.fs @@ -1,6 +1,6 @@ -// 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) +// Z combinator. Nigel Galloway: March 5th., 2024 +type Mu<'T> = { eval: Mu<'T> -> ('T -> 'T) } +let Z f = let g = { eval = fun x -> fun v -> (f (x.eval x)) v } in (g.eval g) +let fibonacci=function 0->1 |x->let fibonacci f= function 0->0 |1->1 |x->f(x - 1) + f(x - 2) in Z fibonacci x +let factorial n=let factorial f=function 0->1 |x->x*f(x-1) in Z 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 570693a413..fb343b0626 100644 --- a/Task/Y-combinator/F-Sharp/y-combinator-2.fs +++ b/Task/Y-combinator/F-Sharp/y-combinator-2.fs @@ -1,35 +1,7 @@ -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 with injected laziness. GordonBGood : April 18, 2025 +type 'T Mu = { eval: 'T Mu -> 'T } +let Y f = let g = fun x -> f <| fun() -> (x.eval x) in g { eval = g } +let fibonacci n = Y (fun fn f s i -> if i >= n then f else fn () s (f + s) (i + 1)) 1I 1I 1 +let factorial n = Y (fun f p x -> if x > n then p else f () (x * p) (x + 1I)) 1I 1I +printfn "fibonacci 10 = %A\r\nfactorial 5 = %A" (fibonacci 10) (factorial 5I) +printfn "fibonacci 1000 = %A" (fibonacci 1000) diff --git a/Task/Y-combinator/F-Sharp/y-combinator-3.fs b/Task/Y-combinator/F-Sharp/y-combinator-3.fs index c9fbe39fbc..570693a413 100644 --- a/Task/Y-combinator/F-Sharp/y-combinator-3.fs +++ b/Task/Y-combinator/F-Sharp/y-combinator-3.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-4.fs b/Task/Y-combinator/F-Sharp/y-combinator-4.fs index 67c1a271c4..c9fbe39fbc 100644 --- a/Task/Y-combinator/F-Sharp/y-combinator-4.fs +++ b/Task/Y-combinator/F-Sharp/y-combinator-4.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-5.fs b/Task/Y-combinator/F-Sharp/y-combinator-5.fs new file mode 100644 index 0000000000..67c1a271c4 --- /dev/null +++ b/Task/Y-combinator/F-Sharp/y-combinator-5.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/J/y-combinator-1.j b/Task/Y-combinator/J/y-combinator-1.j index b597d336eb..75bc19b2e8 100644 --- a/Task/Y-combinator/J/y-combinator-1.j +++ b/Task/Y-combinator/J/y-combinator-1.j @@ -1,3 +1,3 @@ -Y=. '('':''<@;(1;~":0)<@;<@((":0)&;))'(2 : 0 '') - (1 : (m,'u'))(1 : (m,'''u u`:6('',(5!:5<''u''),'')`:6 y'''))(1 :'u u`:6') -) + Y =. {{x&(x`:6)`'' u y}} {{u`''&u}} + fac=. 1:`{{(* x`:6@<:)y}}@.(0 < ]) + fib=. {{(-&1 +&(x`:6) -&2)y}}^:(1 < ]) diff --git a/Task/Y-combinator/J/y-combinator-10.j b/Task/Y-combinator/J/y-combinator-10.j index c2fa4be554..479e547b25 100644 --- a/Task/Y-combinator/J/y-combinator-10.j +++ b/Task/Y-combinator/J/y-combinator-10.j @@ -1,6 +1 @@ - sr=. [ apply f.,&< NB. Self referring - lv=. (((^:_1)b.)(`(<'0';_1)))(`:6) NB. Linear representation of a verb argument - Y=. (&>)/lv(&sr) NB. Y with embedded states - Y=. 'Y'f. NB. Fixing it... - Y NB. ... To make it stateless (i.e., a combinator) -((((&>)/)((((^:_1)b.)(`_1))(`:6)))(&([ 128!:2 ,&<))) +XY=. (1 :'('':''<@;(1;~":0)<@;<@((":0)&;))u')(1 :'('':''<@;(1;~":0)<@;<@((":0)&;))((''u u`:6('',(5!:5<''u''),'')`:6 y''),(10{a.),'':'',(10{a.),''x(u u`:6('',(5!:5<''u''),'')`:6)y'')')(1 :'u u`:6') diff --git a/Task/Y-combinator/J/y-combinator-11.j b/Task/Y-combinator/J/y-combinator-11.j index 55910b1599..9a26fa7d3b 100644 --- a/Task/Y-combinator/J/y-combinator-11.j +++ b/Task/Y-combinator/J/y-combinator-11.j @@ -1,20 +1,14 @@ -Y=:1 :0 - f=. u Defer - (5!:1<'f') f y -) - -Defer=: 1 :0 -: - g=. x&(x`:6) - (5!:1<'g') u y -) - -almost_factorial=: 4 :0 - if. 0 >: y do. 1 - else. y * x`:6 y-1 end. -) - -almost_fibonacci=: 4 :0 - if. 2 > y do. y - else. (x`:6 y-1) + x`:6 y-2 end. -) + 1 2 3 '([:`(>:@:])`(<:@:[ u 1:)`(<:@[ u [ u <:@:])@.(#.@,&*))'XY"0/ 1 2 3 4 5 NB. Ackermann function... + 3 4 5 6 7 + 5 7 9 11 13 +13 29 61 125 253 + '1:`(<: u <:)@.* : (+ + 2 * u@:])'XY"0/~ i.7 NB. Ambivalent recursion... +2 5 14 35 80 173 362 +3 6 15 36 81 174 363 +4 7 16 37 82 175 364 +5 8 17 38 83 176 365 +6 9 18 39 84 177 366 +7 10 19 40 85 178 367 +8 11 20 41 86 179 368 + NB. OEIS A097813 - main diagonal + NB. OEIS A050488 = A097813 - 1 - adyacent upper off-diagonal diff --git a/Task/Y-combinator/J/y-combinator-12.j b/Task/Y-combinator/J/y-combinator-12.j index baa222544a..758788c8b7 100644 --- a/Task/Y-combinator/J/y-combinator-12.j +++ b/Task/Y-combinator/J/y-combinator-12.j @@ -1,6 +1 @@ - almost_factorial Y 9 -362880 - almost_fibonacci Y 9 -34 - almost_fibonacci Y"0 i. 10 -0 1 1 2 3 5 8 13 21 34 +YX=. (1 :'('':''<@;(1;~":0)<@;<@((":0)&;))u')($:`)(`:6) diff --git a/Task/Y-combinator/J/y-combinator-13.j b/Task/Y-combinator/J/y-combinator-13.j deleted file mode 100644 index 01995e50b7..0000000000 --- a/Task/Y-combinator/J/y-combinator-13.j +++ /dev/null @@ -1,9 +0,0 @@ -Y=:2 :0(0 :0) -NB. this block will be n in the second part -: - g=. x&(x`:6) - (5!:1<'g') u y -) - f=. u (1 :n) - (5!:1<'f') f y -) diff --git a/Task/Y-combinator/J/y-combinator-14.j b/Task/Y-combinator/J/y-combinator-14.j deleted file mode 100644 index 972cd7dc2f..0000000000 --- a/Task/Y-combinator/J/y-combinator-14.j +++ /dev/null @@ -1,2 +0,0 @@ - almost_factorial f. Y 10 -3628800 diff --git a/Task/Y-combinator/J/y-combinator-2.j b/Task/Y-combinator/J/y-combinator-2.j index a242963298..1a2e4cd6be 100644 --- a/Task/Y-combinator/J/y-combinator-2.j +++ b/Task/Y-combinator/J/y-combinator-2.j @@ -1,4 +1,4 @@ - 'if. * y do. y * u <: y else. 1 end.' Y 10 NB. Factorial -3628800 - '(u@:<:@:<: + u@:<:)^:(1 < ])' Y 10 NB. Fibonacci -55 + fac Y 9 +362880 + fib Y 9 +34 diff --git a/Task/Y-combinator/J/y-combinator-3.j b/Task/Y-combinator/J/y-combinator-3.j index 6ed01b419a..5a2752f4e4 100644 --- a/Task/Y-combinator/J/y-combinator-3.j +++ b/Task/Y-combinator/J/y-combinator-3.j @@ -1,7 +1,4 @@ - arb=. ':'<@;(1;~":0)<@;<@((":0)&;) NB. AR of an explicit adverb from its body - - ara=. 1 :'arb u' NB. The verb arb as an adverb - srt=. 1 :'arb ''u u`:6('' , (5!:5<''u'') , '')`:6 y''' NB. AR of the self-replication and transformation adverb - gab=. 1 :'u u`:6' NB. The AR of the adverb and the adverb itself as a train - - Y=. ara srt gab NB. Train of adverbs + Y =. ]:&>/]:^:_1 b.]:`(<'0';_1)`:6&([ 128!:2 ,&<) + sr =. [ apply f. ,&< NB. Self referring + fac=. 1:`(] * [ sr ] - 1:)@.(0 < ]) + fib=. (([ sr ] - 2:) + [ sr ] - 1:)^:(1 < ]) diff --git a/Task/Y-combinator/J/y-combinator-4.j b/Task/Y-combinator/J/y-combinator-4.j index 479e547b25..6bb711db53 100644 --- a/Task/Y-combinator/J/y-combinator-4.j +++ b/Task/Y-combinator/J/y-combinator-4.j @@ -1 +1,4 @@ -XY=. (1 :'('':''<@;(1;~":0)<@;<@((":0)&;))u')(1 :'('':''<@;(1;~":0)<@;<@((":0)&;))((''u u`:6('',(5!:5<''u''),'')`:6 y''),(10{a.),'':'',(10{a.),''x(u u`:6('',(5!:5<''u''),'')`:6)y'')')(1 :'u u`:6') + fac f. Y 10 +3628800 + fib f. Y 10 +55 diff --git a/Task/Y-combinator/J/y-combinator-5.j b/Task/Y-combinator/J/y-combinator-5.j index 9a26fa7d3b..e5fcf900d8 100644 --- a/Task/Y-combinator/J/y-combinator-5.j +++ b/Task/Y-combinator/J/y-combinator-5.j @@ -1,14 +1,11 @@ - 1 2 3 '([:`(>:@:])`(<:@:[ u 1:)`(<:@[ u [ u <:@:])@.(#.@,&*))'XY"0/ 1 2 3 4 5 NB. Ackermann function... - 3 4 5 6 7 - 5 7 9 11 13 -13 29 61 125 253 - '1:`(<: u <:)@.* : (+ + 2 * u@:])'XY"0/~ i.7 NB. Ambivalent recursion... -2 5 14 35 80 173 362 -3 6 15 36 81 174 363 -4 7 16 37 82 175 364 -5 8 17 38 83 176 365 -6 9 18 39 84 177 366 -7 10 19 40 85 178 367 -8 11 20 41 86 179 368 - NB. OEIS A097813 - main diagonal - NB. OEIS A050488 = A097813 - 1 - adyacent upper off-diagonal + fac f. Y NB. Factorial... +'1:`(] * (([ 128!:2 ,&<) <:))@.(0 < ])&>/'&([ 128!:2 ,&<) + + fac f. NB. Factorial step... +1:`(] * (([ 128!:2 ,&<) <:))@.(0 < ]) + + fib f. Y NB. Fibonacci... +'(([ ([ 128!:2 ,&<) ] - 2:) + [ ([ 128!:2 ,&<) ] - 1:)^:(1 < ])&>/'&([ 128!:2 ,&<) + + fib f. NB. Fibonacci step... +(([ ([ 128!:2 ,&<) ] - 2:) + [ ([ 128!:2 ,&<) ] - 1:)^:(1 < ]) diff --git a/Task/Y-combinator/J/y-combinator-6.j b/Task/Y-combinator/J/y-combinator-6.j index 758788c8b7..760d8d8a98 100644 --- a/Task/Y-combinator/J/y-combinator-6.j +++ b/Task/Y-combinator/J/y-combinator-6.j @@ -1 +1,6 @@ -YX=. (1 :'('':''<@;(1;~":0)<@;<@((":0)&;))u')($:`)(`:6) + sr=. [ apply f. ,&< NB. Self referring + lv=. ]:^:_1 b.]:`(<'0';_1)`:6 NB. Linear representation of a verb operand + Y =. ]:&>/lv&sr NB. Y with embedded states + Y =. 'Y' f. NB. Fixing it... + Y NB. ... To make it stateless (i.e., a combinator) +((]: & >) / ((((]: ^: (_1)) b. ]:) ` (<'0';_1)) `: 6)) & ([ 128!:2 ,&<) diff --git a/Task/Y-combinator/J/y-combinator-7.j b/Task/Y-combinator/J/y-combinator-7.j index c88bb44baf..b597d336eb 100644 --- a/Task/Y-combinator/J/y-combinator-7.j +++ b/Task/Y-combinator/J/y-combinator-7.j @@ -1 +1,3 @@ -Y=. ((((&>)/)((((^:_1)b.)(`(<'0';_1)))(`:6)))(&([ 128!:2 ,&<))) +Y=. '('':''<@;(1;~":0)<@;<@((":0)&;))'(2 : 0 '') + (1 : (m,'u'))(1 : (m,'''u u`:6('',(5!:5<''u''),'')`:6 y'''))(1 :'u u`:6') +) diff --git a/Task/Y-combinator/J/y-combinator-8.j b/Task/Y-combinator/J/y-combinator-8.j index c700edddd5..a242963298 100644 --- a/Task/Y-combinator/J/y-combinator-8.j +++ b/Task/Y-combinator/J/y-combinator-8.j @@ -1,11 +1,4 @@ - u=. [ NB. Function (left) - n=. ] NB. Argument (right) - sr=. [ apply f. ,&< NB. Self referring - - fac=. (1:`(n * u sr n - 1:)) @. (0 < n) - fac f. Y 10 + 'if. * y do. y * u <: y else. 1 end.' Y 10 NB. Factorial 3628800 - - Fib=. ((u sr n - 2:) + u sr n - 1:) ^: (1 < n) - Fib f. Y 10 + '(u@:<:@:<: + u@:<:)^:(1 < ])' Y 10 NB. Fibonacci 55 diff --git a/Task/Y-combinator/J/y-combinator-9.j b/Task/Y-combinator/J/y-combinator-9.j index 7061a73639..6ed01b419a 100644 --- a/Task/Y-combinator/J/y-combinator-9.j +++ b/Task/Y-combinator/J/y-combinator-9.j @@ -1,12 +1,7 @@ - fac f. Y NB. Factorial... -'1:`(] * [ ([ 128!:2 ,&<) ] - 1:)@.(0 < ])&>/'&([ 128!:2 ,&<) + arb=. ':'<@;(1;~":0)<@;<@((":0)&;) NB. AR of an explicit adverb from its body - fac f. NB. Factorial step... -1:`(] * [ ([ 128!:2 ,&<) ] - 1:)@.(0 < ]) + ara=. 1 :'arb u' NB. The verb arb as an adverb + srt=. 1 :'arb ''u u`:6('' , (5!:5<''u'') , '')`:6 y''' NB. AR of the self-replication and transformation adverb + gab=. 1 :'u u`:6' NB. The AR of the adverb and the adverb itself as a train - - Fib f. Y NB. Fibonacci... -'(([ ([ 128!:2 ,&<) ] - 2:) + [ ([ 128!:2 ,&<) ] - 1:)^:(1 < ])&>/'&([ 128!:2 ,&<) - - Fib f. NB. Fibonacci step... -(([ ([ 128!:2 ,&<) ] - 2:) + [ ([ 128!:2 ,&<) ] - 1:)^:(1 < ]) + Y=. ara srt gab NB. Train of adverbs diff --git a/Task/Y-combinator/Julia/y-combinator-1.julia b/Task/Y-combinator/Julia/y-combinator-1.jl similarity index 100% rename from Task/Y-combinator/Julia/y-combinator-1.julia rename to Task/Y-combinator/Julia/y-combinator-1.jl diff --git a/Task/Y-combinator/Julia/y-combinator-2.julia b/Task/Y-combinator/Julia/y-combinator-2.jl similarity index 100% rename from Task/Y-combinator/Julia/y-combinator-2.julia rename to Task/Y-combinator/Julia/y-combinator-2.jl diff --git a/Task/Y-combinator/Kotlin/y-combinator.kotlin b/Task/Y-combinator/Kotlin/y-combinator.kts similarity index 100% rename from Task/Y-combinator/Kotlin/y-combinator.kotlin rename to Task/Y-combinator/Kotlin/y-combinator.kts diff --git a/Task/Y-combinator/Nu/y-combinator.nu b/Task/Y-combinator/Nu/y-combinator.nu new file mode 100644 index 0000000000..acfd0621ab --- /dev/null +++ b/Task/Y-combinator/Nu/y-combinator.nu @@ -0,0 +1,14 @@ +def Y [f] { + {|x| do $f {|y| do (do $x $x) $y } } | do $in $in +} + +let factorial = Y {|rec| + {|n| if $n < 2 { 1 } else { (do $rec ($n - 1)) * $n } } +} + +let fibonacci = Y {|rec| + {|n| if $n < 2 { $n } else { (do $rec ($n - 1)) + (do $rec ($n - 2)) } } +} + + +..9 | each { {fac: (do $factorial $in) fib: (do $fibonacci $in)} } diff --git a/Task/Y-combinator/OCaml/y-combinator-1.ocaml b/Task/Y-combinator/OCaml/y-combinator-1.ml similarity index 100% rename from Task/Y-combinator/OCaml/y-combinator-1.ocaml rename to Task/Y-combinator/OCaml/y-combinator-1.ml diff --git a/Task/Y-combinator/OCaml/y-combinator-2.ocaml b/Task/Y-combinator/OCaml/y-combinator-2.ml similarity index 100% rename from Task/Y-combinator/OCaml/y-combinator-2.ocaml rename to Task/Y-combinator/OCaml/y-combinator-2.ml diff --git a/Task/Y-combinator/OCaml/y-combinator-3.ocaml b/Task/Y-combinator/OCaml/y-combinator-3.ml similarity index 100% rename from Task/Y-combinator/OCaml/y-combinator-3.ocaml rename to Task/Y-combinator/OCaml/y-combinator-3.ml diff --git a/Task/Y-combinator/OCaml/y-combinator-4.ocaml b/Task/Y-combinator/OCaml/y-combinator-4.ml similarity index 100% rename from Task/Y-combinator/OCaml/y-combinator-4.ocaml rename to Task/Y-combinator/OCaml/y-combinator-4.ml diff --git a/Task/Y-combinator/Pluto/y-combinator.pluto b/Task/Y-combinator/Pluto/y-combinator.pluto new file mode 100644 index 0000000000..88cd0c6519 --- /dev/null +++ b/Task/Y-combinator/Pluto/y-combinator.pluto @@ -0,0 +1,14 @@ +local function y(f) + local g = |r| -> f(|x| -> r(r)(x)) + return g(g) +end + +local almost_fac = |f| -> (|x| -> x <= 1 ? 1 : x * f(x - 1)) + +local almost_fib = |f| -> (|x| -> x <= 2 ? 1 : f(x - 1) + f(x - 2)) + +local fac = y(almost_fac) +local fib = y(almost_fib) + +print($"fac(10) = {fac(10)}") +print($"fib(10) = {fib(10)}") diff --git a/Task/Y-combinator/PowerShell/y-combinator-1.psh b/Task/Y-combinator/PowerShell/y-combinator-1.ps1 similarity index 100% rename from Task/Y-combinator/PowerShell/y-combinator-1.psh rename to Task/Y-combinator/PowerShell/y-combinator-1.ps1 diff --git a/Task/Y-combinator/PowerShell/y-combinator-2.psh b/Task/Y-combinator/PowerShell/y-combinator-2.ps1 similarity index 100% rename from Task/Y-combinator/PowerShell/y-combinator-2.psh rename to Task/Y-combinator/PowerShell/y-combinator-2.ps1 diff --git a/Task/Y-combinator/Q/y-combinator.q b/Task/Y-combinator/Q/y-combinator.q index 10e057588a..765814b515 100644 --- a/Task/Y-combinator/Q/y-combinator.q +++ b/Task/Y-combinator/Q/y-combinator.q @@ -2,6 +2,6 @@ > fac: {{$[y<2; 1; y*x y-1]} x} > (Y fac) 6 720j -> fib: {{$[y<2; 1; (x y-1) + (x y-2)]} x} +> fib: {{$[y<2; y; (x y-1) + (x y-2)]} x} > (Y fib) each til 20 -1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 +0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 diff --git a/Task/Y-combinator/REBOL/y-combinator-1.rebol b/Task/Y-combinator/Rebol/y-combinator-1.rebol similarity index 100% rename from Task/Y-combinator/REBOL/y-combinator-1.rebol rename to Task/Y-combinator/Rebol/y-combinator-1.rebol diff --git a/Task/Y-combinator/REBOL/y-combinator-2.rebol b/Task/Y-combinator/Rebol/y-combinator-2.rebol similarity index 100% rename from Task/Y-combinator/REBOL/y-combinator-2.rebol rename to Task/Y-combinator/Rebol/y-combinator-2.rebol diff --git a/Task/Y-combinator/Rhombus/y-combinator-1.rhombus b/Task/Y-combinator/Rhombus/y-combinator-1.rhombus new file mode 100644 index 0000000000..27ebd86bf0 --- /dev/null +++ b/Task/Y-combinator/Rhombus/y-combinator-1.rhombus @@ -0,0 +1,18 @@ +#lang rhombus + +fun Y(f): + fun g(h): + f(fun(x): h(h)(x)) + g(g) + +fun fact(f): + fun(n): + if (n == 0) + | 1 + | n * f(n - 1) + +fun fib(f): + fun(n): + if (n <= 1) + | n + | f(n - 1) + f(n - 2) diff --git a/Task/Y-combinator/Rhombus/y-combinator-2.rhombus b/Task/Y-combinator/Rhombus/y-combinator-2.rhombus new file mode 100644 index 0000000000..fbb682fa29 --- /dev/null +++ b/Task/Y-combinator/Rhombus/y-combinator-2.rhombus @@ -0,0 +1,3 @@ +fun Y(f): + fun g(h): f(h(h)(_)) + g(g) diff --git a/Task/Y-combinator/Rust/y-combinator.rust b/Task/Y-combinator/Rust/y-combinator.rs similarity index 100% rename from Task/Y-combinator/Rust/y-combinator.rust rename to Task/Y-combinator/Rust/y-combinator.rs diff --git a/Task/Y-combinator/Scheme/y-combinator-1.ss b/Task/Y-combinator/Scheme/y-combinator-1.scm similarity index 100% rename from Task/Y-combinator/Scheme/y-combinator-1.ss rename to Task/Y-combinator/Scheme/y-combinator-1.scm diff --git a/Task/Y-combinator/Scheme/y-combinator-2.ss b/Task/Y-combinator/Scheme/y-combinator-2.scm similarity index 100% rename from Task/Y-combinator/Scheme/y-combinator-2.ss rename to Task/Y-combinator/Scheme/y-combinator-2.scm diff --git a/Task/Y-combinator/Scheme/y-combinator-3.ss b/Task/Y-combinator/Scheme/y-combinator-3.scm similarity index 100% rename from Task/Y-combinator/Scheme/y-combinator-3.ss rename to Task/Y-combinator/Scheme/y-combinator-3.scm diff --git a/Task/Y-combinator/Scheme/y-combinator-4.ss b/Task/Y-combinator/Scheme/y-combinator-4.scm similarity index 100% rename from Task/Y-combinator/Scheme/y-combinator-4.ss rename to Task/Y-combinator/Scheme/y-combinator-4.scm diff --git a/Task/Y-combinator/Zig/y-combinator.zig b/Task/Y-combinator/Zig/y-combinator.zig new file mode 100644 index 0000000000..3a6cf9927b --- /dev/null +++ b/Task/Y-combinator/Zig/y-combinator.zig @@ -0,0 +1,71 @@ +//! A simple implementation of the Y Combinator: +//! λf.(λx.xx)(λx.f(xx)) +//! <=> λf.(λx.f(xx))(λx.f(xx)) + +const std = @import("std"); +const debug = std.debug; +const mem = std.mem; +const Allocator = mem.Allocator; + +// In Zig we can use function pointers and closures +// to implement the Y combinator without needing traits + +// Generic Y combinator implementation +fn Y(comptime T: type, comptime R: type, f: fn (fn (T) R, T) R) fn (T) R { + const Closure = struct { + fn call(t: T) R { + const applySelf = struct { + fn apply(x: fn (fn (T) R, T) R, y: T) R { + const innerApply = struct { + fn inner(z: T) R { + return apply(x, z); + } + }.inner; + return x(innerApply, y); + } + }.apply; + return applySelf(f, t); + } + }; + return Closure.call; +} + +// Factorial function using Y combinator +fn fac(n: usize) usize { + const almostFac = struct { + fn call(f: fn (usize) usize, x: usize) usize { + if (x == 0) return 1 else return x * f(x - 1); + } + }.call; + + return Y(usize, usize, almostFac)(n); +} + +// Fibonacci function using Y combinator +fn fib(n: usize) usize { + const FibTuple = struct { a0: usize, a1: usize, x: usize }; + + const almostFib = struct { + fn call(f: fn (FibTuple) usize, tuple: FibTuple) usize { + const a0 = tuple.a0; + const a1 = tuple.a1; + const x = tuple.x; + + return switch (x) { + 0 => a0, + 1 => a1, + else => f(.{ .a0 = a1, .a1 = a0 + a1, .x = x - 1 }), + }; + } + }.call; + + return Y(FibTuple, usize, almostFib)(.{ .a0 = 1, .a1 = 1, .x = n }); +} + +// Driver function +pub fn main() !void { + const n: usize = 10; + const stdout = std.io.getStdOut().writer(); + try stdout.print("fac({}) = {}\n", .{ n, fac(n) }); + try stdout.print("fib({}) = {}\n", .{ n, fib(n) }); +} diff --git a/Task/Yahoo-search-interface/FreeBASIC/yahoo-search-interface.basic b/Task/Yahoo-search-interface/FreeBASIC/yahoo-search-interface.basic new file mode 100644 index 0000000000..2facd03b2b --- /dev/null +++ b/Task/Yahoo-search-interface/FreeBASIC/yahoo-search-interface.basic @@ -0,0 +1,9 @@ +#Ifdef __FB_WIN32__ + ' === WINDOWS === + Shell "start /max https://www.yahoo.com" +#Else + ' === LINUX === + Shell "xdg-open https://www.yahoo.com" +#EndIf + +Print "Yahoo! search interface..." diff --git a/Task/Yahoo-search-interface/FutureBasic/yahoo-search-interface.basic b/Task/Yahoo-search-interface/FutureBasic/yahoo-search-interface.basic new file mode 100644 index 0000000000..5fe89471b6 --- /dev/null +++ b/Task/Yahoo-search-interface/FutureBasic/yahoo-search-interface.basic @@ -0,0 +1,21 @@ +include "Tlbx WebKit.incl" + +_window = 1 +begin enum 1 + _webView +end enum + +void local fn BuildWindow + CGRect r = ( 0, 0, 700, 400 ) + window _window, @"WKWebView", r + + wkwebview _webView, r + ViewSetAutoresizingMask( _webView, NSViewWidthSizable + NSViewHeightSizable ) + CFURLRef url = fn URLWithString( @"https://search.yahoo.com/" ) + URLRequestRef request = fn URLRequestWithURL( url ) + fn WKWebViewLoadRequest( _webView, request ) +end fn + +fn BuildWindow + +HandleEvents diff --git a/Task/Yahoo-search-interface/Julia/yahoo-search-interface.julia b/Task/Yahoo-search-interface/Julia/yahoo-search-interface.jl similarity index 100% rename from Task/Yahoo-search-interface/Julia/yahoo-search-interface.julia rename to Task/Yahoo-search-interface/Julia/yahoo-search-interface.jl diff --git a/Task/Yahoo-search-interface/Kotlin/yahoo-search-interface.kotlin b/Task/Yahoo-search-interface/Kotlin/yahoo-search-interface.kts similarity index 100% rename from Task/Yahoo-search-interface/Kotlin/yahoo-search-interface.kotlin rename to Task/Yahoo-search-interface/Kotlin/yahoo-search-interface.kts diff --git a/Task/Yellowstone-sequence/ALGOL-68/yellowstone-sequence.alg b/Task/Yellowstone-sequence/ALGOL-68/yellowstone-sequence.alg index 79b28d08b0..f7655de3a9 100644 --- a/Task/Yellowstone-sequence/ALGOL-68/yellowstone-sequence.alg +++ b/Task/Yellowstone-sequence/ALGOL-68/yellowstone-sequence.alg @@ -24,7 +24,8 @@ BEGIN # find members of the yellowstone sequence: starting from 1, 2, 3 the # IF n > 2 THEN result[ 3 ] := 3; # guess the maximum element will be n, if it is larger, used will be enlarged # - REF[]BOOL used := HEAP[ 1 : n ]BOOL; + HEAP[ 1 : n ]BOOL initial used; + REF[]BOOL used := initial used; used[ 1 ] := used[ 2 ] := used[ 3 ] := TRUE; FOR i FROM 4 TO UPB used DO used[ i ] := FALSE OD; FOR i FROM 4 TO UPB result DO @@ -34,7 +35,7 @@ BEGIN # find members of the yellowstone sequence: starting from 1, 2, 3 the # FOR j WHILE NOT found DO IF j > UPB used THEN # not enough elements in used - enlarge it # - REF[]BOOL new used := HEAP[ 1 : 2 * UPB used ]BOOL; + HEAP[ 1 : 2 * UPB used ]BOOL new used; new used[ 1 : UPB used ] := used; FOR k FROM UPB used + 1 TO UPB new used DO new used[ k ] := FALSE OD; used := new used @@ -56,5 +57,6 @@ BEGIN # find members of the yellowstone sequence: starting from 1, 2, 3 the # []INT ys = YELLOWSTONE 30; FOR i TO UPB ys DO print( ( " ", whole( ys[ i ], 0 ) ) ) - OD + OD; + print( ( newline ) ) END diff --git a/Task/Yellowstone-sequence/Ada/yellowstone-sequence.ada b/Task/Yellowstone-sequence/Ada/yellowstone-sequence.adb similarity index 100% rename from Task/Yellowstone-sequence/Ada/yellowstone-sequence.ada rename to Task/Yellowstone-sequence/Ada/yellowstone-sequence.adb diff --git a/Task/Yellowstone-sequence/Agena/yellowstone-sequence.agena b/Task/Yellowstone-sequence/Agena/yellowstone-sequence.agena new file mode 100644 index 0000000000..be4a696fc5 --- /dev/null +++ b/Task/Yellowstone-sequence/Agena/yellowstone-sequence.agena @@ -0,0 +1,27 @@ +scope # Yellowstone sequence - translation of the Pluto sample + + local proc yellowstone( n :: number ) :: table + local a, m := [ 1, 2, 3 ], [ true, true, true ]; + for x from 4 to n do + a[ x ], m[ x ] := 0, false + od; + local minV := 4; + for c from 4 to n do + local more := true + for i from minV while more do + if not m[ i ] and numtheory.gcd( a[ c - 1 ], i ) = 1 and numtheory.gcd( a[ c - 2 ], i ) > 1 + then + a[ c ], m[ i ] := i, true; + if i = minV then minV +:= 1 fi; + more := false + fi + od + od; + return a + end; + + local constant ySize, constant perLine := 30, 10; + local y := yellowstone( ySize ); + printf( "The first %d Yellowstone numbers are:\n", ySize ); + for yPos to ySize do printf( " %2d", y[ yPos ] ); if yPos mod perLine = 0 then print() fi od +end diff --git a/Task/Yellowstone-sequence/Arturo/yellowstone-sequence.arturo b/Task/Yellowstone-sequence/Arturo/yellowstone-sequence.arturo index f499f36166..1679462ef9 100644 --- a/Task/Yellowstone-sequence/Arturo/yellowstone-sequence.arturo +++ b/Task/Yellowstone-sequence/Arturo/yellowstone-sequence.arturo @@ -1,7 +1,7 @@ yellowstone: function [n][ - result: new [1 2 3] - present: new [1 2 3] - start: new 4 + result: [1 2 3] + present: [1 2 3] + start: 4 while [n > size result][ candidate: new start while ø [ diff --git a/Task/Yellowstone-sequence/C-sharp/yellowstone-sequence.cs b/Task/Yellowstone-sequence/C-sharp/yellowstone-sequence.cs new file mode 100644 index 0000000000..c5c8c580aa --- /dev/null +++ b/Task/Yellowstone-sequence/C-sharp/yellowstone-sequence.cs @@ -0,0 +1,73 @@ +internal class Program +{ + private static void Main(string[] args) + { + List yellowStoneList = YellowstoneSequence(30); + + Console.WriteLine("Yellowstone 30"); + + foreach (int i in yellowStoneList) + { + Console.Write(i + " "); + } + } + + private static List YellowstoneSequence(int sequenceCount) + { + List yellowstoneList = [1, 2, 3]; + int num = 4; + List notYellowstoneList = new(); + int yellowSize = 3; + + while (yellowSize < sequenceCount) + { + int found = -1; + + for (int index = 0; index < notYellowstoneList.Count; index++) + { + int test = notYellowstoneList[index]; + + if (GCD(yellowstoneList[yellowSize - 2], test) > 1 && GCD(yellowstoneList[yellowSize - 1], test) == 1) + { + found = index; + break; + } + } + + if (found >= 0) + { + yellowstoneList.Add(notYellowstoneList[found]); + notYellowstoneList.RemoveAt(found); + yellowSize++; + } + else + { + while (true) + { + if (GCD(yellowstoneList[yellowSize - 2], num) > 1 && GCD(yellowstoneList[yellowSize - 1], num) == 1) + { + yellowstoneList.Add(num); + yellowSize++; + num++; + break; + } + + notYellowstoneList.Add(num); + num++; + } + } + } + + return yellowstoneList; + } + + private static int GCD(int a, int b) + { + if (b == 0) + { + return a; + } + + return GCD(b, a % b); + } +} diff --git a/Task/Yellowstone-sequence/Crystal/yellowstone-sequence.cr b/Task/Yellowstone-sequence/Crystal/yellowstone-sequence.cr new file mode 100644 index 0000000000..4112be946b --- /dev/null +++ b/Task/Yellowstone-sequence/Crystal/yellowstone-sequence.cr @@ -0,0 +1,32 @@ +def yellowstone + used = Set(Int32).new + penult, last = 2, 3 + start = 4 + iter = Iterator.of do + while start.in? used + used.delete start + start += 1 + end + (start..).each do |n| + if !used.includes?(n) && n.gcd(last) == 1 && n.gcd(penult) > 1 + used << n + penult, last = last, n + break n + end + end + end + (1..3).each.chain iter +end + +p yellowstone.first(30).to_a + +values = yellowstone.first(100).to_a +height = (values.max - 1) // 8 + +(0..height).reverse_each do |i| + values.each do |v| + d = v - i*8 + print d <= 0 ? ' ' : d >= 8 ? '█' : '\u2580' + d + end + puts +end diff --git a/Task/Yellowstone-sequence/Delphi/yellowstone-sequence.delphi b/Task/Yellowstone-sequence/Delphi/yellowstone-sequence.pas similarity index 100% rename from Task/Yellowstone-sequence/Delphi/yellowstone-sequence.delphi rename to Task/Yellowstone-sequence/Delphi/yellowstone-sequence.pas diff --git a/Task/Yellowstone-sequence/EasyLang/yellowstone-sequence.easy b/Task/Yellowstone-sequence/EasyLang/yellowstone-sequence.easy index e980cb39de..cc912716ce 100644 --- a/Task/Yellowstone-sequence/EasyLang/yellowstone-sequence.easy +++ b/Task/Yellowstone-sequence/EasyLang/yellowstone-sequence.easy @@ -1,16 +1,12 @@ func gcd a b . - if b = 0 - return a - . + 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] - . +proc remove_at i &a[] . + for j = i + 1 to len a[] : a[j - 1] = a[j] len a[] -1 . -proc yellowstone count . yellow[] . +proc yellowstone count &yellow[] . yellow[] = [ 1 2 3 ] num = 4 while len yellow[] < count @@ -18,9 +14,7 @@ proc yellowstone count . yellow[] . yell2 = yellow[len yellow[]] for i to len notyellow[] test = notyellow[i] - if gcd yell1 test > 1 and gcd yell2 test = 1 - break 1 - . + if gcd yell1 test > 1 and gcd yell2 test = 1 : break 1 . if i <= len notyellow[] yellow[] &= notyellow[i] diff --git a/Task/Yellowstone-sequence/Fennel/yellowstone-sequence.fennel b/Task/Yellowstone-sequence/Fennel/yellowstone-sequence.fennel new file mode 100644 index 0000000000..88b0486ee1 --- /dev/null +++ b/Task/Yellowstone-sequence/Fennel/yellowstone-sequence.fennel @@ -0,0 +1,45 @@ +(do ;;; Yellowstone sequence - translation of the Pluto sample + + (fn gcd [m n] + (var (a b) (values (math.abs m) (math.abs n))) + (while (not= b 0) + (set (b a) (values (% a b) b)) + ) + a + ) + + (fn yellowstone [n] + (var (a m) (values [1 2 3] [true true true])) + (for [x 4 n] + (tset a x 0) + (tset m x false) + ) + (var minV 4) + (for [c 4 n] + (var (more i) (values true minV)) + (while more + (when (and (not (. m i)) + (= (gcd (. a (- c 1)) i) 1) + (> (gcd (. a (- c 2)) i) 1) + ) + (tset a c i) + (tset m i true) + (when (= i minV) + (set minV (+ 1 minV)) + ) + (set more false) + ) + (set i (+ i 1)) + ) + ) + a + ) + + (local (ySize perLine) (values 30 10)) + (local y (yellowstone ySize)) + (io.write (string.format "The first %d Yellowstone numbers are:\n" ySize)) + (for [yPos 1 ySize] + (io.write (string.format " %2d" (. y yPos))) + (when (= 0 (% yPos perLine)) (print)) + ) +) diff --git a/Task/Yellowstone-sequence/Fortran/yellowstone-sequence.f b/Task/Yellowstone-sequence/Fortran/yellowstone-sequence.f new file mode 100644 index 0000000000..f27b29ad5b --- /dev/null +++ b/Task/Yellowstone-sequence/Fortran/yellowstone-sequence.f @@ -0,0 +1,85 @@ +! Yellowstone Sequence - Code Golf Version +! Demonstrates concise Fortran (but keep it readable!) +program yellowstone_golf + implicit none + integer :: y(100), i, c + logical :: u(1000) = .false. + + ! First 3 terms + y(1:3) = [(i, i=1,3)] + u(1:3) = .true. + + ! Generate rest + do i = 4, 100 + c = 1 + do while (u(c) .or. gcd(c,y(i-1))/=1 .or. gcd(c,y(i-2))==1) + c = c + 1 + end do + y(i) = c + u(c) = .true. + end do + + ! Output + print '(A)', "First 30 Yellowstone numbers:" + print '(10I5)', y(1:30) + +contains +! pure integer function gcd(a,b) !Euclid's method +! integer, intent(in) :: a, b +! integer :: x, y, t +! x = a; y = b +! do while (y /= 0) +! t = y; y = mod(x,y); x = t +! end do +! gcd = x +! end function +pure integer function gcd(a, b) !Stein's method + ! Added and used Steins method of finding the GCD + ! simply because everyone else was using Euclid's method + integer, intent(in) :: a, b + integer :: x, y, shift + + x = abs(a) + y = abs(b) + ! Handle trivial cases + if (a == 0) then + gcd = y + return + else if (b == 0) then + gcd = x + return + end if + + ! Count common factors of 2 + shift = 0 + do while ((iand(x,1) == 0) .and. (iand(y,1) == 0)) + x = ishft(x,-1) + y = ishft(y,-1) + shift = shift + 1 + end do + + ! Divide x by 2 until odd + do while (iand(x,1) == 0) + x = ishft(x,-1) + end do + + do ! Divide y by 2 until odd + do while (iand(y,1) == 0) + y = ishft(y,-1) + end do + + ! Ensure x <= y + if (x > y) then + ! swap + x = x + y + y = x - y + x = x - y + end if + y = y - x + if (y == 0) exit + end do + + gcd = ishft(x, shift) +end function gcd + +end program yellowstone_golf diff --git a/Task/Yellowstone-sequence/FutureBasic/yellowstone-sequence.basic b/Task/Yellowstone-sequence/FutureBasic/yellowstone-sequence.basic new file mode 100644 index 0000000000..74da99ae02 --- /dev/null +++ b/Task/Yellowstone-sequence/FutureBasic/yellowstone-sequence.basic @@ -0,0 +1,33 @@ +include "NSLog.incl" + +NSInteger local fn GCD( a as NSInteger, b as NSInteger ) + if ( a == 0 ) then return b + return fn GCD( b % a, a ) +end fn = 0 + +void local fn CalcYellowstoneSequence( terms as int ) + CFMutableArrayRef sequence = fn MutableArrayWithObjects( @1, @2, @3, NULL ) + + for int n = 3 to terms - 1 + NSInteger prev1 = fn NumberIntegerValue( fn ArrayObjectAtIndex( sequence, n - 1 ) ) + NSInteger prev2 = fn NumberIntegerValue( fn ArrayObjectAtIndex( sequence, n - 2 ) ) + NSInteger candidate = 1 + + while (YES) + if ( !fn ArrayContainsObject( sequence, @(candidate) ) && fn GCD( candidate, prev1 ) == 1 && fn GCD( candidate, prev2 ) > 1 ) + MutableArrayAddObject( sequence, @(candidate) ) + break + end if + candidate++ + wend + next + + NSLog( @"Yellowstone sequence up to %d terms:", terms ) + for CFNumberRef num in sequence + NSLog( @"%@ \b", num ) + next +end fn + +fn CalcYellowstoneSequence( 30 ) + +HandleEvents diff --git a/Task/Yellowstone-sequence/Julia/yellowstone-sequence.julia b/Task/Yellowstone-sequence/Julia/yellowstone-sequence.jl similarity index 100% rename from Task/Yellowstone-sequence/Julia/yellowstone-sequence.julia rename to Task/Yellowstone-sequence/Julia/yellowstone-sequence.jl diff --git a/Task/Yellowstone-sequence/Kotlin/yellowstone-sequence.kotlin b/Task/Yellowstone-sequence/Kotlin/yellowstone-sequence.kts similarity index 100% rename from Task/Yellowstone-sequence/Kotlin/yellowstone-sequence.kotlin rename to Task/Yellowstone-sequence/Kotlin/yellowstone-sequence.kts diff --git a/Task/Yellowstone-sequence/Oberon-07/yellowstone-sequence.oberon b/Task/Yellowstone-sequence/Oberon-07/yellowstone-sequence.oberon new file mode 100644 index 0000000000..3b5c158bf1 --- /dev/null +++ b/Task/Yellowstone-sequence/Oberon-07/yellowstone-sequence.oberon @@ -0,0 +1,63 @@ +MODULE YellowstoneSequence; (* Show some of the Yellowstone sequence *) + (* - translation of the Pluto sample via Agena *) + IMPORT Out; + + (* returns the gcd of a and b *) + PROCEDURE gcd( a, b : INTEGER ) : INTEGER; + VAR t, m, n : INTEGER; + BEGIN + m := a; + n := b; + WHILE m # 0 DO t := m; m := n MOD m; n := t END + RETURN n + END gcd ; + + (* sets a to the first elements of the Yellowstone sequence; *) + (* a must have at least 4 elements *) + (* element 0 of a is not used; i.e., a is indexed from 1 *) + (* the required size of the work array m will depend on the size of a *) + (* experimentation suggests that for sizes of a up to 100 000, *) + (* 10 * the size of a should be OK - it would probably be OK for *) + (* 1 000 000 but it will take a long time to construct a 1 000 000 *) + (* element sequence so I haven't tried it... *) + PROCEDURE yellowstone( VAR a : ARRAY OF INTEGER; VAR m : ARRAY OF BOOLEAN ); + VAR n, minV, c, i : INTEGER; + more : BOOLEAN; + BEGIN + n := LEN( a ) - 1; + FOR i := 1 TO 3 DO a[ i ] := i; m[ i ] := TRUE END; + FOR i := 4 TO n DO a[ i ] := 0 END; + FOR i := 4 TO LEN( m ) - 1 DO m[ i ] := FALSE END; + minV := 4; + FOR c := 4 TO n DO + more := TRUE; + i := minV - 1; + WHILE more DO + INC( i ); + IF ( ~ m[ i ] ) & ( gcd( a[ c - 1 ], i ) = 1 ) & ( gcd( a[ c - 2 ], i ) > 1 ) THEN + a[ c ] := i; m[ i ] := TRUE; + IF i = minV THEN INC( minV ) END; + more := FALSE + END + END + END + END yellowstone; + + (* show the first 30 elements of the sequence *) + PROCEDURE task; + CONST ySize = 30; + VAR y : ARRAY ySize + 2 OF INTEGER; + w : ARRAY ySize * 10 OF BOOLEAN; + yPos : INTEGER; + BEGIN + yellowstone( y, w ); + Out.String( "The first ");Out.Int( ySize, 0 );Out.String( " Yellowstone numbers are:" );Out.Ln; + FOR yPos := 1 TO ySize DO + Out.String( " " );Out.Int( y[ yPos ], 0 ) + END; + Out.Ln + END task; + +BEGIN + task +END YellowstoneSequence. diff --git a/Task/Yellowstone-sequence/Pluto/yellowstone-sequence.pluto b/Task/Yellowstone-sequence/Pluto/yellowstone-sequence.pluto new file mode 100644 index 0000000000..74f3cd66f5 --- /dev/null +++ b/Task/Yellowstone-sequence/Pluto/yellowstone-sequence.pluto @@ -0,0 +1,32 @@ +require "table2" +local int = require "int" +local fmt = require "fmt" + +local function yellowstone(n) + local m = {} + local a = table.rep(n, 0) + for i = 1, 3 do + a[i] = i + m[i] = true + end + local min = 4 + for c = 4, n do + local i = min + while true do + if !m[i] and int.gcd(a[c - 1], i) == 1 and int.gcd(a[c - 2], i) > 1 then + a[c] = i + m[i] = true + if i == min then ++min end + break + end + ++i + end + end + return a +end + +local x = {} +for i = 1, 30 do x[i] = i end +local y = yellowstone(30) +print("The first 30 Yellowstone numbers are:") +fmt.tprint("%2d ", y, 10) diff --git a/Task/Yellowstone-sequence/REXX/yellowstone-sequence-1.rexx b/Task/Yellowstone-sequence/REXX/yellowstone-sequence-1.rexx deleted file mode 100644 index be0c9c0fce..0000000000 --- a/Task/Yellowstone-sequence/REXX/yellowstone-sequence-1.rexx +++ /dev/null @@ -1,20 +0,0 @@ -/*REXX program calculates any number of terms in the Yellowstone (permutation) sequence.*/ -parse arg m . /*obtain optional argument from the CL.*/ -if m=='' | m=="," then m= 30 /*Not specified? Then use the default.*/ -!.= 0 /*initialize an array of numbers(used).*/ -# = 0 /*count of Yellowstone numbers in seq. */ -$= /*list " " " " " */ - do j=1 until #==m; prev= # - 1 - if j<5 then do; #= #+1; @.#= j; !.#= j; !.j= 1; $= strip($ j); iterate; end - - do k=1; if !.k then iterate /*Already used? Then skip this number.*/ - if gcd(k, @.prev)<2 then iterate /*Not meet requirement? Then skip it. */ - if gcd(k, @.#) \==1 then iterate /* " " " " " " */ - #= #+1; @.#= k; !.k= 1; $= $ k /*bump ctr; assign; mark used; add list*/ - leave /*find the next Yellowstone seq. number*/ - end /*k*/ - end /*j*/ -say $ /*display a list of a Yellowstone seq. */ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -gcd: parse arg x,y; do until y==0; parse value x//y y with y x; end; return x diff --git a/Task/Yellowstone-sequence/REXX/yellowstone-sequence-2.rexx b/Task/Yellowstone-sequence/REXX/yellowstone-sequence-2.rexx deleted file mode 100644 index 549ae130a1..0000000000 --- a/Task/Yellowstone-sequence/REXX/yellowstone-sequence-2.rexx +++ /dev/null @@ -1,21 +0,0 @@ -/*REXX program calculates any number of terms in the Yellowstone (permutation) sequence.*/ -parse arg m . /*obtain optional argument from the CL.*/ -if m=='' | m=="," then m= 30 /*Not specified? Then use the default.*/ -!.= 0 /*initialize an array of numbers(used).*/ -# = 0 /*count of Yellowstone numbers in seq. */ -$ = /*list " " " " " */ - do j=1 until #==m; prev= # - 1 - if j<5 then do; #= #+1; @.#= j; !.#= j; !.j= 1; $= strip($ j); iterate; end - - do k=1; if !.k then iterate /*Already used? Then skip this number.*/ - if gcd(k, @.prev)<2 then iterate /*Not meet requirement? Then skip it. */ - if gcd(k, @.#) \==1 then iterate /* " " " " " " */ - #= # + 1; @.#= k; !.k= 1; $= $ k /*bump ctr; assign; mark used; add list*/ - leave /*find the next Yellowstone seq. number*/ - end /*k*/ - end /*j*/ - -call $histo $ '(vertical)' /*invoke a REXX vertical histogram plot*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -gcd: parse arg x,y; do until y==0; parse value x//y y with y x; end; return x diff --git a/Task/Yellowstone-sequence/REXX/yellowstone-sequence.rexx b/Task/Yellowstone-sequence/REXX/yellowstone-sequence.rexx new file mode 100644 index 0000000000..6ff2c91497 --- /dev/null +++ b/Task/Yellowstone-sequence/REXX/yellowstone-sequence.rexx @@ -0,0 +1,53 @@ +-- 24 Aug 2025 +include Setting +numeric digits 100 +arg xx +if xx = '' then + xx = 30 + +say 'YELLOWSTONE SEQUENCE' +say version +say +call GetYellow xx +call DisplayList xx +call Timer +exit + +GetYellow: +procedure expose yell. work. Memo. +arg xx +say 'Get yellowstones...' +yell. = 0; work. = 0; n = 0 +do i = 1 until n = xx + p = n-1 + if i < 5 then do + n = n+1; yell.n = i; work.n = i; work.i = 1 + iterate i + end + do j = 1 + if work.j then + iterate j + if Gcd(j,yell.p) = 1 then + iterate j + if Gcd(j,yell.n) <> 1 then + iterate j + n = n+1; yell.n = j; work.j = 1 + leave j + end +end +say +return xx + +DisplayList: +procedure expose yell. +arg xx +say 'Yellowstone sequence...' +do i = 1 to xx + call Charout ,Right(yell.i,5) + if i//10 = 0 then + say +end +say +return + +include Math diff --git a/Task/Yellowstone-sequence/Rust/yellowstone-sequence.rust b/Task/Yellowstone-sequence/Rust/yellowstone-sequence.rs similarity index 100% rename from Task/Yellowstone-sequence/Rust/yellowstone-sequence.rust rename to Task/Yellowstone-sequence/Rust/yellowstone-sequence.rs diff --git a/Task/Yellowstone-sequence/Uiua/yellowstone-sequence.uiua b/Task/Yellowstone-sequence/Uiua/yellowstone-sequence.uiua new file mode 100644 index 0000000000..1592e7990a --- /dev/null +++ b/Task/Yellowstone-sequence/Uiua/yellowstone-sequence.uiua @@ -0,0 +1,8 @@ +Gcd ← ⊙◌⍢(˜⟜◿|⊃⋅±⊙∘) +# Experimental! +Gcd ← ∨ +NextY ← ⍢(+1|⨬(¬≍0_1=1≡Gcd⊙↙₋₂|1)˜∊⊃⊙∘⊙∘)1 # [a0 a1...an] -> an+1 +N ← 200 +⍢(˜⊂NextY| a.#: + ? if b.$i.! && + (i.gcd(a.$) == 1) && + (i.gcd(a:butlast.$) > 1) + : recur: + a.conj(i), b.assoc(i true), 5 + recur: a, b, i.++ + =>: a + +defn gcd(a b): + loop a a, b b: + if b.?: + recur b: a % b + else: a diff --git a/Task/Yin-and-yang/Ada/yin-and-yang.ada b/Task/Yin-and-yang/Ada/yin-and-yang.adb similarity index 100% rename from Task/Yin-and-yang/Ada/yin-and-yang.ada rename to Task/Yin-and-yang/Ada/yin-and-yang.adb diff --git a/Task/Yin-and-yang/AmigaBASIC/yin-and-yang.basic b/Task/Yin-and-yang/AmigaBASIC/yin-and-yang-1.basic similarity index 100% rename from Task/Yin-and-yang/AmigaBASIC/yin-and-yang.basic rename to Task/Yin-and-yang/AmigaBASIC/yin-and-yang-1.basic diff --git a/Task/Yin-and-yang/AmigaBASIC/yin-and-yang-2.basic b/Task/Yin-and-yang/AmigaBASIC/yin-and-yang-2.basic new file mode 100644 index 0000000000..d684ca656e --- /dev/null +++ b/Task/Yin-and-yang/AmigaBASIC/yin-and-yang-2.basic @@ -0,0 +1,21 @@ +xp=320:yp=100:size=150 +CALL DrawYY(xp,yp,size) + +xp=500:yp=40:size=50 +CALL DrawYY(xp,yp,size) + +END + +SUB DrawYY(xp,yp,size) STATIC: + pi=3.141592 + s=.5 + CIRCLE (xp,yp),size,,,,s + CIRCLE (xp,yp+size/4),size/8,,,,s + CIRCLE (xp,yp-size/4),size/8,,,,s + CIRCLE (xp,yp+size/4),size/2,,.5*pi,1.5*pi,s + CIRCLE (xp,yp-size/4),size/2,,1.5*pi,2*pi,s + CIRCLE (xp,yp-size/4),size/2,,0,.5*pi,s + PAINT (xp,yp-size/4) + PSET (xp,yp) + PAINT (xp+size/4,yp) +END SUB diff --git a/Task/Yin-and-yang/Commodore-BASIC/yin-and-yang-4.basic b/Task/Yin-and-yang/Commodore-BASIC/yin-and-yang-4.basic new file mode 100644 index 0000000000..e0ba892dd3 --- /dev/null +++ b/Task/Yin-and-yang/Commodore-BASIC/yin-and-yang-4.basic @@ -0,0 +1,15 @@ +0 REM COMMANDER X-16 +10 SCREEN 128 +20 RECT 0,0,319,239,0 +30 X=100:Y=120:XR=98:YR=98:GOSUB 100 +40 X=260:Y=180:XR=48:YR=48:GOSUB 100 +50 GET K$: IF K$="" THEN 50 +60 END +100 OVAL X-XR,Y-YR,X+XR,Y+YR,1 +110 RECT X,Y-YR,X+YR,Y+YR,0 +120 OVAL X-XR/2,Y-YR,X+XR/2,Y,1 +130 OVAL X-XR/2,Y,X+XR/2,Y+YR,0 +140 RING X-XR,Y-YR,X+XR,Y+YR,1 +150 OVAL X-XR/8,Y-YR/2-YR/8,X+XR/8,Y-YR/2+YR/8,0 +160 OVAL X-XR/8,Y+YR/2-YR/8,X+XR/8,Y+YR/2+YR/8,1 +170 RETURN diff --git a/Task/Yin-and-yang/Delphi/yin-and-yang.delphi b/Task/Yin-and-yang/Delphi/yin-and-yang.pas similarity index 100% rename from Task/Yin-and-yang/Delphi/yin-and-yang.delphi rename to Task/Yin-and-yang/Delphi/yin-and-yang.pas diff --git a/Task/Yin-and-yang/EasyLang/yin-and-yang.easy b/Task/Yin-and-yang/EasyLang/yin-and-yang.easy index 38961146b9..653cd6fb44 100644 --- a/Task/Yin-and-yang/EasyLang/yin-and-yang.easy +++ b/Task/Yin-and-yang/EasyLang/yin-and-yang.easy @@ -1,20 +1,17 @@ -proc circ r c . . - color c - circle r +proc circ x y r c . + gcolor c + gcircle x y 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 +proc yinyang x y r . + circ x y 2 * r 000 + gcolor 999 + gcircseg x y 2 * r 90 -90 + circ x y - r r 000 + circ x y - r r / 3 999 + circ x y + r r 999 + circ x y + r r / 3 000 . -background 555 -clear +gbackground 555 +gclear yinyang 20 20 6 yinyang 50 60 14 diff --git a/Task/Yin-and-yang/FreeBASIC/yin-and-yang.basic b/Task/Yin-and-yang/FreeBASIC/yin-and-yang.basic index d5f8fa7752..bbf3d40164 100644 --- a/Task/Yin-and-yang/FreeBASIC/yin-and-yang.basic +++ b/Task/Yin-and-yang/FreeBASIC/yin-and-yang.basic @@ -14,4 +14,5 @@ End Sub Taijitu(110, 110, 45) Taijitu(500, 300, 138) +Sleep End diff --git a/Task/Yin-and-yang/Julia/yin-and-yang.julia b/Task/Yin-and-yang/Julia/yin-and-yang.jl similarity index 100% rename from Task/Yin-and-yang/Julia/yin-and-yang.julia rename to Task/Yin-and-yang/Julia/yin-and-yang.jl diff --git a/Task/Yin-and-yang/Kotlin/yin-and-yang.kotlin b/Task/Yin-and-yang/Kotlin/yin-and-yang.kts similarity index 100% rename from Task/Yin-and-yang/Kotlin/yin-and-yang.kotlin rename to Task/Yin-and-yang/Kotlin/yin-and-yang.kts diff --git a/Task/Yin-and-yang/Nim/yin-and-yang.nim b/Task/Yin-and-yang/Nim/yin-and-yang.nim index efee2bee37..8f73b61fd3 100644 --- a/Task/Yin-and-yang/Nim/yin-and-yang.nim +++ b/Task/Yin-and-yang/Nim/yin-and-yang.nim @@ -1,24 +1,24 @@ -import gintro/cairo +import cairo -proc draw(ctx: Context; x, y, r: float) = +proc draw(ctx: ptr Context; x, y, r: float) = ctx.arc(x, y, r + 1, 1.571, 7.854) - ctx.setSource(0.0, 0.0, 0.0) + ctx.setSourceRgb(0.0, 0.0, 0.0) ctx.fill() ctx.arcNegative(x, y - r / 2, r / 2, 1.571, 4.712) ctx.arc(x, y + r / 2, r / 2, 1.571, 4.712) ctx.arcNegative(x, y, r, 4.712, 1.571) - ctx.setSource(1.0, 1.0, 1.0) + ctx.setSourceRgb(1.0, 1.0, 1.0) ctx.fill() ctx.arc(x, y - r / 2, r / 5, 1.571, 7.854) - ctx.setSource(0.0, 0.0, 0.0) + ctx.setSourceRgb(0.0, 0.0, 0.0) ctx.fill() ctx.arc(x, y + r / 2, r / 5, 1.571, 7.854) - ctx.setSource(1.0, 1.0, 1.0) + ctx.setSourceRgb(1.0, 1.0, 1.0) ctx.fill() -let surface = imageSurfaceCreate(argb32, 200, 200) -let context = newContext(surface) +let surface = imageSurfaceCreate(FormatArgb32, 200, 200) +let context = create(surface) context.draw(120, 120, 75) context.draw(35, 35, 30) let status = surface.writeToPng("yin-yang.png") -assert status == Status.success +assert status == StatusSuccess diff --git a/Task/Yin-and-yang/OCaml/yin-and-yang.ocaml b/Task/Yin-and-yang/OCaml/yin-and-yang.ml similarity index 100% rename from Task/Yin-and-yang/OCaml/yin-and-yang.ocaml rename to Task/Yin-and-yang/OCaml/yin-and-yang.ml diff --git a/Task/Yin-and-yang/Ring/yin-and-yang-1.ring b/Task/Yin-and-yang/Ring/yin-and-yang-1.ring new file mode 100644 index 0000000000..175411be0b --- /dev/null +++ b/Task/Yin-and-yang/Ring/yin-and-yang-1.ring @@ -0,0 +1,36 @@ +scaleX = 2 +scaleY = 1 +black = "#" +white = "." +clear = " " + +func main + printYinYang(17) + printYinYang(8) + +func printYinYang radius + for sy = radius * scaleY to -radius * scaleY step -1 + line = "" + for sx = -radius * scaleX to radius * scaleX + x = sx / scaleX + y = sy / scaleY + + if inCircle(0, 0, radius, x, y) + if inCircle(0, radius/2, radius/2, x, y) + if inCircle(0, radius/2, radius/6, x, y) line += black else line += white ok + elseif inCircle(0, -radius/2, radius/2, x, y) + if inCircle(0, -radius/2, radius/6, x, y) line += white else line += black ok + elseif x < 0 + line += white + else + line += black + ok + else + line += clear + ok + next + see line + nl + next + +func inCircle cx, cy, r, x, y + return (pow(x-cx, 2) + pow(y-cy, 2)) <= pow(r, 2) diff --git a/Task/Yin-and-yang/Ring/yin-and-yang-2.ring b/Task/Yin-and-yang/Ring/yin-and-yang-2.ring new file mode 100644 index 0000000000..20e72af02f --- /dev/null +++ b/Task/Yin-and-yang/Ring/yin-and-yang-2.ring @@ -0,0 +1,50 @@ +# Author: Gal Zsolt (CalmoSoft) +load "guilib.ring" + +new qApp { + win = new qWidget() { + setWindowTitle("Yin-Yang - CalmoSoft") + resize(400, 400) + label = new qLabel(win) { + resize(400, 400) + + # Create the image + image = new qPixmap2(400, 400) + color_gray = new qColor() { setRgb(200,200,200,255) } + image.fill(color_gray) + + p1 = new qPainter() + p1.begin(image) + p1.setRenderHint(1, true) + + # Colors and brushes defined individually + white = new qColor() { setRgb(255,255,255,255) } + black = new qColor() { setRgb(0,0,0,255) } + wBrush = new qBrush() { setStyle(1) setColor(white) } + bBrush = new qBrush() { setStyle(1) setColor(black) } + + # 1. Base circles (using drawChord with 5 parameters instead of drawPie) + p1.setBrush(wBrush) + p1.drawChord(50, 50, 300, 300, 90 * 16, 180 * 16) + p1.setBrush(bBrush) + p1.drawChord(50, 50, 300, 300, 270 * 16, 180 * 16) + + # 2. Middle circles (forming the S-shape) + p1.setBrush(bBrush) + p1.drawEllipse(125, 50, 150, 150) + p1.setBrush(wBrush) + p1.drawEllipse(125, 200, 150, 150) + + # 3. Small dots (the "eyes") + p1.setBrush(wBrush) + p1.drawEllipse(185, 110, 30, 30) + p1.setBrush(bBrush) + p1.drawEllipse(185, 260, 30, 30) + + p1.endpaint() + setPixmap(image) + } + show() + } + exec() +} diff --git a/Task/Yin-and-yang/Rust/yin-and-yang.rust b/Task/Yin-and-yang/Rust/yin-and-yang.rs similarity index 100% rename from Task/Yin-and-yang/Rust/yin-and-yang.rust rename to Task/Yin-and-yang/Rust/yin-and-yang.rs diff --git a/Task/Yin-and-yang/UNIX-Shell/yin-and-yang.sh b/Task/Yin-and-yang/UNIX-Shell/yin-and-yang.sh index d4b26c6e90..1d6a476124 100644 --- a/Task/Yin-and-yang/UNIX-Shell/yin-and-yang.sh +++ b/Task/Yin-and-yang/UNIX-Shell/yin-and-yang.sh @@ -4,19 +4,19 @@ in_circle() { #(cx, cy, r, x y) # on (cx,cy) # (but really scaled to an ellipse with vertical minor semiaxis r and # horizontal major semiaxis 2r) - local -i cx=$1 cy=$2 r=$3 x=$4 y=$5 - local -i dx dy + typeset -i cx=$1 cy=$2 r=$3 x=$4 y=$5 + typeset -i dx dy (( dx=(x-cx)/2, dy=y-cy, dx*dx + dy*dy <= r*r )) } taijitu() { #radius - local -i radius=${1:-17} - local -i x1=0 y1=0 r1=radius # outer circle - local -i x2=0 y2=-radius/2 r2=radius/6 # upper eye - local -i x3=0 y3=-radius/2 r3=radius/2 # upper half - local -i x4=0 y4=+radius/2 r4=radius/6 # lower eye - local -i x5=0 y5=+radius/2 r5=radius/2 # lower half - local -i x y + typeset -i radius=${1:-17} + typeset -i x1=0 y1=0 r1=radius # outer circle + typeset -i x2=0 y2=-radius/2 r2=radius/6 # upper eye + typeset -i x3=0 y3=-radius/2 r3=radius/2 # upper half + typeset -i x4=0 y4=+radius/2 r4=radius/6 # lower eye + typeset -i x5=0 y5=+radius/2 r5=radius/2 # lower half + typeset -i x y for (( y=radius; y>=-radius; --y )); do for (( x=-2*radius; x<=2*radius; ++x)); do if ! in_circle $x1 $y1 $r1 $x $y; then diff --git a/Task/Yin-and-yang/V-(Vlang)/yin-and-yang.v b/Task/Yin-and-yang/V-(Vlang)/yin-and-yang.v new file mode 100644 index 0000000000..368b65bdb1 --- /dev/null +++ b/Task/Yin-and-yang/V-(Vlang)/yin-and-yang.v @@ -0,0 +1,31 @@ +fn circle(px int, py int, c int, r int) bool { + mut x, mut y := px, py + x = x / 2 + y = y - c + return r * r >= x * x + y * y +} + +fn pixel(x int, y int, r int) string { + if circle(x, y, -r / 2, r / 6) { return "#" } + if circle(x, y, r / 2, r / 6) { return "." } + if circle(x, y, -r / 2, r / 2) { return "." } + if circle(x, y, r / 2, r / 2) { return "#" } + if circle(x, y, 0, r) { + if x < 0 { return "." } + else { return "#" } + } + return " " +} + +fn yin_yang(r int) { + for y := -r; y <= r; y++ { + for x := -2 * r; x <= 2 * r; x++ { + print(pixel(x, y, r)) + } + println("") + } +} + +fn main() { + yin_yang(18) +} diff --git a/Task/Zebra-puzzle/ALGOL-68/zebra-puzzle.alg b/Task/Zebra-puzzle/ALGOL-68/zebra-puzzle.alg index 4222092053..57c13b77a4 100644 --- a/Task/Zebra-puzzle/ALGOL-68/zebra-puzzle.alg +++ b/Task/Zebra-puzzle/ALGOL-68/zebra-puzzle.alg @@ -22,20 +22,21 @@ BEGIN AND can set( smoke OF h, smoke OF s ) ) # XOR # ; # sets a field in a house to value if it is unknown # - PROC set = ( REF INT field, INT value )VOID: IF field = unknown AND value /= same THEN field := value FI; + PROC setf = ( REF INT field, INT value )VOID: + IF field = unknown AND value /= same THEN field := value FI; # sets the unknown fields in house h to the non-same fields of suggestion s # OP +:= = ( REF HOUSE h, HOUSE s )VOID: - ( set( nationality OF h, nationality OF s ); set( animal OF h, animal OF s ) - ; set( colour OF h, colour OF s ); set( drink OF h, drink OF s ) - ; set( smoke OF h, smoke OF s ) + ( setf( nationality OF h, nationality OF s ); setf( animal OF h, animal OF s ) + ; setf( colour OF h, colour OF s ); setf( drink OF h, drink OF s ) + ; setf( smoke OF h, smoke OF s ) ) # +:= # ; # sets a field in a house to unknown if the value is not same # - PROC reset = ( REF INT field, INT value )VOID: IF value /= same THEN field := unknown FI; + PROC resetf = ( REF INT field, INT value )VOID: IF value /= same THEN field := unknown FI; # sets fields in house h to unknown if the suggestion s is not same # OP -:= = ( REF HOUSE h, HOUSE s )VOID: - ( reset( nationality OF h, nationality OF s ); reset( animal OF h, animal OF s ) - ; reset( colour OF h, colour OF s ); reset( drink OF h, drink OF s ) - ; reset( smoke OF h, smoke OF s ) + ( resetf( nationality OF h, nationality OF s ); resetf( animal OF h, animal OF s ) + ; resetf( colour OF h, colour OF s ); resetf( drink OF h, drink OF s ) + ; resetf( smoke OF h, smoke OF s ) ) # -:= # ; # attempts a partial solution for the house at pos # PROC try = ( INT pos, HOUSE suggestion, PROC VOID continue )VOID: diff --git a/Task/Zebra-puzzle/Ada/zebra-puzzle.ada b/Task/Zebra-puzzle/Ada/zebra-puzzle.adb similarity index 100% rename from Task/Zebra-puzzle/Ada/zebra-puzzle.ada rename to Task/Zebra-puzzle/Ada/zebra-puzzle.adb diff --git a/Task/Zebra-puzzle/Crystal/zebra-puzzle.crystal b/Task/Zebra-puzzle/Crystal/zebra-puzzle.cr similarity index 100% rename from Task/Zebra-puzzle/Crystal/zebra-puzzle.crystal rename to Task/Zebra-puzzle/Crystal/zebra-puzzle.cr diff --git a/Task/Zebra-puzzle/Elixir/zebra-puzzle.elixir b/Task/Zebra-puzzle/Elixir/zebra-puzzle.ex similarity index 100% rename from Task/Zebra-puzzle/Elixir/zebra-puzzle.elixir rename to Task/Zebra-puzzle/Elixir/zebra-puzzle.ex diff --git a/Task/Zebra-puzzle/Fortran/zebra-puzzle.f b/Task/Zebra-puzzle/Fortran/zebra-puzzle.f new file mode 100644 index 0000000000..655bb18321 --- /dev/null +++ b/Task/Zebra-puzzle/Fortran/zebra-puzzle.f @@ -0,0 +1,290 @@ +program zebra_clean + implicit none + + integer, parameter :: RED=1, GREEN=2, WHITE=3, BLUE=4, YELLOW=5 + integer, parameter :: ENGLISH=1, SWEDE=2, DANE=3, NORWEGIAN=4, GERMAN=5 + integer, parameter :: DOG=1, CAT=2, BIRD=3, HORSE=4, ZEBRA=5 + integer, parameter :: TEA=1, COFFEE=2, MILK=3, BEER=4, WATER=5 + integer, parameter :: PALLMALL=1, DUNHILL=2, BLEND=3, BLUEMASTER=4, PRINCE=5 + + integer :: solution(5,5) ! (house, attribute): color, nation, pet, drink, smoke + integer(kind=8) :: count + integer :: num_solutions + + count = 0 + num_solutions = 0 + + print *, "Solving Einstein's Zebra Puzzle..." + print * + + call solve(1, 1, solution, count, num_solutions) + + print * + print '(A,I0)', "Total permutations tried: ", count + print '(A,I0)', "Solutions found: ", num_solutions + if (num_solutions == 1) print *, "Solution is UNIQUE!" + +contains + + recursive subroutine solve(house, attr, sol, cnt, nsol) + integer, intent(in) :: house, attr + integer, intent(inout) :: sol(5,5) + integer(kind=8), intent(inout) :: cnt + integer, intent(inout) :: nsol + integer :: val + + ! If all houses and attributes filled, check solution + if (house > 5) then + cnt = cnt + 1 + if (is_valid_solution(sol)) then + nsol = nsol + 1 + call print_sol(sol, nsol) + end if + return + end if + + ! Move to next position + if (attr > 5) then + call solve(house+1, 1, sol, cnt, nsol) + return + end if + + ! Try each possible value for this attribute + do val = 1, 5 + if (can_place(sol, house, attr, val)) then + sol(house, attr) = val + if (satisfies_constraints(sol, house, attr)) then + call solve(house, attr+1, sol, cnt, nsol) + end if + sol(house, attr) = 0 + end if + end do + end subroutine + + function can_place(sol, house, attr, val) result(ok) + integer, intent(in) :: sol(5,5), house, attr, val + logical :: ok + integer :: h + + ! Check if value already used in this attribute + ok = .true. + do h = 1, house-1 + if (sol(h, attr) == val) then + ok = .false. + return + end if + end do + + ! Handle fixed constraints + ! Constraint 9: Middle house drinks milk + if (attr == 4 .and. house == 3 .and. val /= MILK) then + ok = .false. + return + end if + if (attr == 4 .and. house /= 3 .and. val == MILK) then + ok = .false. + return + end if + + ! Constraint 10: Norwegian in first house + if (attr == 2 .and. house == 1 .and. val /= NORWEGIAN) then + ok = .false. + return + end if + if (attr == 2 .and. house /= 1 .and. val == NORWEGIAN) then + ok = .false. + return + end if + end function + + function satisfies_constraints(sol, house, attr) result(ok) + integer, intent(in) :: sol(5,5), house, attr + logical :: ok + integer :: i + + ok = .true. + + ! Only check constraints for completed houses + do i = 1, house + if (any(sol(i,:) == 0)) cycle ! House not complete + + ! Constraint 2: English in red + if ((sol(i,2) == ENGLISH .and. sol(i,1) /= RED) .or. & + (sol(i,1) == RED .and. sol(i,2) /= ENGLISH)) then + ok = .false. + return + end if + + ! Constraint 3: Swede has dog + if ((sol(i,2) == SWEDE .and. sol(i,3) /= DOG) .or. & + (sol(i,3) == DOG .and. sol(i,2) /= SWEDE)) then + ok = .false. + return + end if + + ! Constraint 4: Dane drinks tea + if ((sol(i,2) == DANE .and. sol(i,4) /= TEA) .or. & + (sol(i,4) == TEA .and. sol(i,2) /= DANE)) then + ok = .false. + return + end if + + ! Constraint 6: Coffee in green + if ((sol(i,1) == GREEN .and. sol(i,4) /= COFFEE) .or. & + (sol(i,4) == COFFEE .and. sol(i,1) /= GREEN)) then + ok = .false. + return + end if + + ! Constraint 7: Pall Mall has bird + if ((sol(i,5) == PALLMALL .and. sol(i,3) /= BIRD) .or. & + (sol(i,3) == BIRD .and. sol(i,5) /= PALLMALL)) then + ok = .false. + return + end if + + ! Constraint 8: Yellow smokes Dunhill + if ((sol(i,1) == YELLOW .and. sol(i,5) /= DUNHILL) .or. & + (sol(i,5) == DUNHILL .and. sol(i,1) /= YELLOW)) then + ok = .false. + return + end if + + ! Constraint 13: Blue Master drinks beer + if ((sol(i,5) == BLUEMASTER .and. sol(i,4) /= BEER) .or. & + (sol(i,4) == BEER .and. sol(i,5) /= BLUEMASTER)) then + ok = .false. + return + end if + + ! Constraint 14: German smokes Prince + if ((sol(i,2) == GERMAN .and. sol(i,5) /= PRINCE) .or. & + (sol(i,5) == PRINCE .and. sol(i,2) /= GERMAN)) then + ok = .false. + return + end if + + ! Constraint 5: Green immediately left of white + if (i < 5) then + if (sol(i,1) == GREEN .and. sol(i+1,1) /= 0 .and. sol(i+1,1) /= WHITE) then + ok = .false. + return + end if + end if + if (i > 1) then + if (sol(i,1) == WHITE .and. sol(i-1,1) /= GREEN) then + ok = .false. + return + end if + end if + end do + end function + + function is_valid_solution(sol) result(valid) + integer, intent(in) :: sol(5,5) + logical :: valid + + valid = .false. + + ! Check all constraints on complete solution + if (.not. check_pair(sol, 2, ENGLISH, 1, RED)) return + if (.not. check_pair(sol, 2, SWEDE, 3, DOG)) return + if (.not. check_pair(sol, 2, DANE, 4, TEA)) return + if (.not. check_adjacent_left(sol, 1, GREEN, 1, WHITE)) return + if (.not. check_pair(sol, 1, GREEN, 4, COFFEE)) return + if (.not. check_pair(sol, 5, PALLMALL, 3, BIRD)) return + if (.not. check_pair(sol, 1, YELLOW, 5, DUNHILL)) return + if (sol(3,4) /= MILK) return + if (sol(1,2) /= NORWEGIAN) return + if (.not. check_adjacent(sol, 5, BLEND, 3, CAT)) return + if (.not. check_adjacent(sol, 3, HORSE, 5, DUNHILL)) return + if (.not. check_pair(sol, 5, BLUEMASTER, 4, BEER)) return + if (.not. check_pair(sol, 2, GERMAN, 5, PRINCE)) return + if (.not. check_adjacent(sol, 2, NORWEGIAN, 1, BLUE)) return + if (.not. check_adjacent(sol, 4, WATER, 5, BLEND)) return + + valid = .true. + end function + + function check_pair(sol, attr1, val1, attr2, val2) result(ok) + integer, intent(in) :: sol(5,5), attr1, val1, attr2, val2 + logical :: ok + integer :: i + ok = .false. + do i = 1, 5 + if (sol(i, attr1) == val1 .and. sol(i, attr2) == val2) then + ok = .true. + return + end if + end do + end function + + function check_adjacent_left(sol, attr1, val1, attr2, val2) result(ok) + integer, intent(in) :: sol(5,5), attr1, val1, attr2, val2 + logical :: ok + integer :: i + ok = .false. + do i = 1, 4 + if (sol(i, attr1) == val1 .and. sol(i+1, attr2) == val2) then + ok = .true. + return + end if + end do + end function + + function check_adjacent(sol, attr1, val1, attr2, val2) result(ok) + integer, intent(in) :: sol(5,5), attr1, val1, attr2, val2 + logical :: ok + integer :: i, pos1, pos2 + pos1 = 0 + pos2 = 0 + do i = 1, 5 + if (sol(i, attr1) == val1) pos1 = i + if (sol(i, attr2) == val2) pos2 = i + end do + ok = (abs(pos1 - pos2) == 1) + end function + + subroutine print_sol(sol, num) + integer, intent(in) :: sol(5,5), num + integer :: i, zebra_house + + character(len=12) :: colors(5), nations(5), pets(5), drinks(5), smokes(5) + + colors = ['Red ', 'Green ', 'White ', 'Blue ', 'Yellow '] + nations = ['English ', 'Swede ', 'Dane ', 'Norwegian ', 'German '] + pets = ['Dog ', 'Cat ', 'Bird ', 'Horse ', 'Zebra '] + drinks = ['Tea ', 'Coffee ', 'Milk ', 'Beer ', 'Water '] + smokes = ['Pall Mall ', 'Dunhill ', 'Blend ', 'Blue Master ', 'Prince '] + + print *, "================================" + print '(A,I0)', "Solution #", num + print *, "================================" + print * + print *, "House | Color | Nation | Pet | Drink | Smoke" + print *, "------+-------------+-------------+-------------+-------------+-------------" +100 format(I0,T7,A,T12,A,T21,A,T24,A,T35,A,T38,A,T49,A,T52,A,T63,A,T66,A) + do i = 1, 5 + print 100, i, ' | ', & + trim(adjustl(colors(sol(i,1)))), ' | ', & + trim(nations(sol(i,2))), ' | ', & + trim(pets(sol(i,3))), ' | ', & + trim(drinks(sol(i,4))), ' | ', & + trim(smokes(sol(i,5))) + end do + + print * + + zebra_house = 0 + do i = 1, 5 + if (sol(i,3) == ZEBRA) then + zebra_house = i + exit + end if + end do + + print *, "*** THE ZEBRA IS OWNED BY THE ", trim(nations(sol(zebra_house,2))), " ***" + print * + end subroutine + +end program zebra_clean diff --git a/Task/Zebra-puzzle/FreeBASIC/zebra-puzzle.basic b/Task/Zebra-puzzle/FreeBASIC/zebra-puzzle.basic new file mode 100644 index 0000000000..dd4499cd39 --- /dev/null +++ b/Task/Zebra-puzzle/FreeBASIC/zebra-puzzle.basic @@ -0,0 +1,185 @@ +Enum attr + Colour = 1 + Nationality + Beverage + Smoke + Pet +End Enum + +Enum Drinks_ + Beer = 1 + Coffee + Milk + Tea + Water +End Enum + +Enum nations + Danish = 1 + English + German + Norwegian + Swedish +End Enum + +Enum colors + Blue = 1 + Green + Red + White + Yellow +End Enum + +Enum tobaccos + Blend = 1 + BlueMaster + Dunhill + PallMall + Prince +End Enum + +Enum animals + Bird = 1 + Cat + Dog + Horse + Zebra +End Enum + +Const factorial5 = 120 +Dim Shared As String permutation(120), perm(5) +Dim Shared As String Colours(5), Nationalities(5), Drinks(5), Smokes(5), Pets(5) +Dim Shared As Integer index + +Sub generate(n As Integer, A() As Integer) + Dim As Integer i + If n = 1 Then + Dim tmp As String = "" + For i = 1 To 5 + tmp &= Str(A(i)) & " " + Next i + permutation(index) = tmp + index += 1 + Else + For i = 1 To n + generate(n - 1, A()) + If n Mod 2 = 0 Then + Swap A(i), A(n) + Else + Swap A(1), A(n) + End If + Next i + End If +End Sub + +Function house(i As Integer, nombre As Integer) As Integer + For x As Integer = 1 To 5 + If Val(Mid(perm(i), x * 2 - 1, 1)) = nombre Then Return x + Next x + Return 0 +End Function + +Function left_of(h1 As Integer, h2 As Integer) As Boolean + Return (h1 - h2) = -1 +End Function + +Function next_to(h1 As Integer, h2 As Integer) As Boolean + Return Abs(h1 - h2) = 1 +End Function + +Sub print_house(i As Integer) + Print Using "####: "; i; + Print Using "\ \ \ \ \ \ \ \ \ \"; _ + Colours(Val(Mid(perm(Colour), i * 2 - 1, 1))); _ + Nationalities(Val(Mid(perm(Nationality), i * 2 - 1, 1))); _ + Drinks(Val(Mid(perm(Beverage), i * 2 - 1, 1))); _ + Smokes(Val(Mid(perm(Smoke), i * 2 - 1, 1))); _ + Pets(Val(Mid(perm(Pet), i * 2 - 1, 1))) +End Sub + +Sub Zebra_puzzle() + Colours(1) = "blue": Colours(2) = "green": Colours(3) = "red": Colours(4) = "white": Colours(5) = "yellow" + Nationalities(1) = "Dane": Nationalities(2) = "English": Nationalities(3) = "German": Nationalities(4) = "Norwegian": Nationalities(5) = "Swede" + Drinks(1) = "beer": Drinks(2) = "coffee": Drinks(3) = "milk": Drinks(4) = "tea": Drinks(5) = "water" + Smokes(1) = "Blend": Smokes(2) = "Blue Master": Smokes(3) = "Dunhill": Smokes(4) = "Pall Mall": Smokes(5) = "Prince" + Pets(1) = "birds": Pets(2) = "cats": Pets(3) = "dog": Pets(4) = "horse": Pets(5) = "zebra" + + Dim As String solperms(120, 5) + Dim As Integer solutions, i, c, n, d, s, p, j + Dim As Integer b(5) + For i = 1 To 5: b(i) = i: Next + 'There are five houses. + index = 0 + generate(5, b()) + For c = 0 To factorial5 - 1 + perm(Colour) = permutation(c) + 'The green house is immediately to the left of the white house. + If left_of(house(Colour, Green), house(Colour, White)) Then + For n = 0 To factorial5 - 1 + perm(Nationality) = permutation(n) + 'The Norwegian lives in the first house. + 'The English man lives in the red house. + 'The Norwegian lives next to the blue house. + If house(Nationality, Norwegian) = 1 _ + And house(Nationality, English) = house(Colour, Red) _ + And next_to(house(Nationality, Norwegian), house(Colour, Blue)) Then + For d = 0 To factorial5 - 1 + perm(Beverage) = permutation(d) + 'The Dane drinks tea. + 'They drink coffee in the green house. + 'In the middle house they drink milk. + If house(Nationality, Danish) = house(Beverage, Tea) _ + And house(Beverage, Coffee) = house(Colour, Green) _ + And house(Beverage, Milk) = 3 Then + For s = 0 To factorial5 - 1 + perm(Smoke) = permutation(s) + 'In the yellow house they smoke Dunhill. + 'The German smokes Prince. + 'The man who smokes Blue Master drinks beer. + 'They Drink water in a house next to the house where they smoke Blend. + If house(Colour, Yellow) = house(Smoke, Dunhill) _ + And house(Nationality, German) = house(Smoke, Prince) _ + And house(Smoke, BlueMaster) = house(Beverage, Beer) _ + And next_to(house(Beverage, Water), house(Smoke, Blend)) Then + For p = 0 To factorial5 - 1 + perm(Pet) = permutation(p) + 'The Swede has a dog. + 'The man who smokes Pall Mall has birds. + '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. + If house(Nationality, Swedish) = house(Pet, Dog) _ + And house(Smoke, PallMall) = house(Pet, Bird) _ + And next_to(house(Smoke, Blend), house(Pet, Cat)) _ + And next_to(house(Pet, Horse), house(Smoke, Dunhill)) Then + For i = 1 To 5 + print_house(i) + Next i + Print + solutions += 1 + For j = 1 To 5 + solperms(solutions - 1, j - 1) = perm(j) + Next j + End If + Next p + End If + Next s + End If + Next d + End If + Next n + End If + Next c + + Print solutions & " solution" & Iif(solutions > 1, "s", "") & " found" + For i As Integer = 0 To solutions - 1 + For j As Integer = 1 To 5 + perm(j) = solperms(i, j - 1) + Next j + Print "The " & Nationalities(Val(Mid(perm(Nationality), house(Pet, Zebra) * 2 - 1, 1))) & " owns the Zebra" + Next i +End Sub +Print "House Colour Nation Drink Smoke Animal" + +Zebra_puzzle() + +Sleep diff --git a/Task/Zebra-puzzle/FutureBasic/zebra-puzzle.basic b/Task/Zebra-puzzle/FutureBasic/zebra-puzzle.basic new file mode 100644 index 0000000000..9853f130be --- /dev/null +++ b/Task/Zebra-puzzle/FutureBasic/zebra-puzzle.basic @@ -0,0 +1,266 @@ +/* + + Z E B R A P U Z Z L E + Based on Phix logic + FutureBasic 7.0.34, August 2025 R.W. + +*/ + +/*-------------------------------------------------------------------- + There are five houses... +---------------------------------------------------------------------- +// The green house is immediately to the left of the white house +// The Norwegian lives in the first house +// The English man lives in the red house +// The Norwegian lives next to the blue house +// The Dane drinks tea +// They drink coffee in the green house +// In the middle house they drink milk +// In the yellow house they smoke Dunhill +// The German smokes Prince +// The man who smokes Blue Master drinks beer +// They drink water in a house next to the house where they smoke Blend +// The Swede has a dog +// The man who smokes Pall Mall has birds +// 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 +// +// Task: Who owns the zebra? +*/ +// Enumerate based on the data given +// in the puzzle (5 variables for each group) + +Begin Enum 1 // drinks + _tea + _coffee + _milk + _beer + _water +End Enum + +Begin Enum 1 // nationalities + _English + _Swede + _Dane + _Norwegian + _German +End Enum + +Begin Enum 1 // house colors + _red + _white + _green + _yellow + _blue +End Enum + +Begin Enum 1 // smokes + _PallMall + _Dunhill + _Blend + _BlueMaster + _Prince +End Enum + +Begin Enum 1 // animals + _dog + _birds + _cats + _horse + _zebra +End Enum + +// Since we have 5 variables, the total permutation/combo +// would be 5! (5 factorial) which is 120 + +Int gPermutation(120, 5) // 120 combinations +Int gNumbers(5) // of 1 to 5 +Int gPermCount +Int factorial5 = 120 // value of 5! +Int entry, ns, ic +Int color, nationality, drink, smoke, pet // 5 groups + +// Since we used assigned numbers, we need this to +// show the equivalent description + +CFStringRef Colors(5) = {@"Houses",@"red",@"white",¬ +@"green",@"yellow",@"blue"} +CFStringRef Nationalities(5) = {@"Nationalities",@"English",@"Swede",¬ +@"Dane",@"Norwegian",@"German"} +CFStringRef Smokes(5) = {@"Smokes",@"Pall Mall",@"Dunhill",¬ +@"Blend",@"Blue Master",@"Prince"} +CFStringRef Drinks(5) = {@"Drinks",@"tea",@"coffee",¬ +@"milk",@"beer",@"water"} +CFStringRef Pets(5) = {@"Animals",@"dog",@"birds",¬ +@"cats",@"horse",@"zebra"} + +// Recursive permutation generator +local fn Permute( l as int, r as int ) + dim i as int + if l = r + for i = 1 to 5 + gPermutation(gPermCount, i) = gNumbers(i) + next + gPermCount++ + else + for i = l to r + swap gNumbers(l), gNumbers(i) + fn Permute( l + 1, r ) + swap gNumbers(l), gNumbers(i) + next + end if +end fn + +// +// Fill arrays of 5! permutations of 1 to 5 +local fn generatePermutations + int i + for i = 1 to 5: gNumbers(i) = i: next i + gPermCount = 1 + fn Permute( 1, 5 ) // Use 1-based index range +end fn + +// +// Pad spaces to width of "padTo" for output formatting +Local fn Pad(theString as CFStringRef, padTo as Int) as CFStringRef + theString = fn StringByReplacingOccurrencesOfString (theString, @"\"", @"" ) + if len(theString) < padTo then theString ¬ + = left( concat( theString, @" "), padTo ) + print theString; +end fn = theString + +// Find an entry in the permutation table +// c1 = index into gPermutation array +// v1 = the seek value +local fn find(c1 as Int, v1 as Int) as Int + Int h, i + h = 0 + for i = 1 to 5 + if gPermutation(c1,i) == v1 then h = i: i = 6: + next i +end fn = h + +// +// Left (as seen from the front) to location logic +local fn left_of(c1 as Int, v1 as Int, c2 as Int, v2 as Int) as Int + Int h, result + h = fn find(c1,v1) + result = (h <=4) && (gPermutation(c2,h + 1) == v2) +end fn = result + +// +// Is in the same house logic +local fn same_house(c1 as Int, v1 as Int, c2 as Int, v2 as Int) as Int + Int h, result + h = fn find(c1, v1) + result = (gPermutation(c2,h) == v2) +end fn = result + +// +// located next to logic +local fn next_to(c1 as Int, v1 as Int, c2 as Int, v2 as Int) as Int + Int h1, h2, result + h1 = fn find(c1, v1): h2 = fn find(c2, v2) + result = abs(h1-h2) == 1 +end fn = result + +//================================================================ +// Main + +window 1,@"Zebra puzzle" + +Int i, j +fn generatePermutations +// start the clock +CFTimeInterval t +t = fn CACurrentMediaTime +print + +for Color = 1 to factorial5 + ic++ + // The green house is immediately to the left of the white house + if fn left_of (Color, _green, Color, _white) + + for Nationality = 1 to factorial5 + ic++ + // The Norwegian lives in the first house and + // The English man lives in the red house and + // The Norwegian lives next to the blue house. + if gPermutation (Nationality,1) == _Norwegian && ¬ + fn same_house (Nationality, _English, Color, _red) && ¬ + fn next_to (Nationality, _Norwegian,Color, _blue) + + for drink = 1 to factorial5 + ic++ + // The Dane drinks tea and + // They drink coffee in the green house and + // In the middle house they drink milk + if fn same_house (Nationality, _Dane,drink, _tea) && ¬ + fn same_house (drink, _coffee, Color, _green) && ¬ + gPermutation (drink, 3) == _milk + + for smoke = 1 to factorial5 + ic++ + // In the yellow house they smoke Dunhill and + // The German smokes Prince and + // The man who smokes Blue Master drinks beer and + // They drink water in a house next to the house + // where they smoke Blend + if fn same_house (Color, _yellow, smoke, _Dunhill) && ¬ + fn same_house (Nationality, _German, smoke, _Prince) && ¬ + fn same_house (smoke, _BlueMaster, drink, _beer) && ¬ + fn next_to (drink, _water, smoke, _Blend) + + for pet = 1 to factorial5 + ic++ + // The Swede has a dog and + // The man who smokes Pall Mall has birds and + // The man who smokes Blend lives in the house next + // to the house with cats and + // In a house next to the house where they have a horse, + // they smoke Dunhill + if fn same_house (Nationality, _Swede, pet, _dog) && ¬ + fn same_house (smoke,_PallMall, pet, _birds) && ¬ + fn next_to (smoke,_Blend, pet, _cats) && ¬ + fn next_to (pet,_horse,smoke,_Dunhill) + + // stop the clock + printf @" Solved in = %.4f seconds", ¬ + (fn CACurrentMediaTime-t) + print + // Show the results + fn pad (@" HOUSE",11): fn pad (@"PERSON",11) + fn pad (@"DRINKS",8): fn pad (@"SMOKES",13) + fn pad (@"HAS",6) + print + print " ===============================================" + for i=1 to 5 + print " ";i;" "; + fn pad (Colors(gPermutation(color,i)),8) + fn pad (Nationalities(gPermutation(Nationality,i)),11) + fn pad (Drinks(gPermutation(drink,i)),8) + fn pad (Smokes(gPermutation(smoke,i)),13) + fn pad (Pets(gPermutation(pet,i)),8): print + if i == 5 then entry = i + next i + print + print " The ";Nationalities(entry);" owns the zebra." + ns += 1: print + print " ";ic;" combinations tested before finding a solution" + print " Solution found = ";ns; + if ns < 2 then print " (unique)" + end if //5 + next pet + end if //4 + next smoke + end if //3 + next drink + end if //2 + next nationality + end if //1 +next color +// +handleEvents + +// diff --git a/Task/Zebra-puzzle/J/zebra-puzzle-1.j b/Task/Zebra-puzzle/J/zebra-puzzle-1.j index 3a97c1da26..c7b7d82cdc 100644 --- a/Task/Zebra-puzzle/J/zebra-puzzle-1.j +++ b/Task/Zebra-puzzle/J/zebra-puzzle-1.j @@ -1,13 +1,24 @@ -ehs=: 5$a: - -cr=: (('English';'red') 0 3} ehs);<('Dane';'tea') 0 2}ehs -cr=: cr, (('German';'Prince') 0 4}ehs);<('Swede';'dog') 0 1 }ehs - -cs=: <('PallMall';'birds') 4 1}ehs -cs=: cs, (('yellow';'Dunhill') 3 4}ehs);<('BlueMaster';'beer') 4 2}ehs - -lof=: (('coffee';'green')2 3}ehs);<(<'white')3}ehs - -next=: <((<'Blend') 4 }ehs);<(<'water')2}ehs -next=: next,<((<'Blend') 4 }ehs);<(<'cats')1}ehs -next=: next,<((<'Dunhill') 4}ehs);<(<'horse')1}ehs +in=: {{n&{ i. m"_}} NB. index of m in row n of matrix +F =: {{u"_1 # ]}} NB. filter by function of items +'Col Nat Pet Drink Cig'=: i.5 NB. refer to rows by name +'col nat pet drink cig'=: (A.~i.@!@#)&>BGRWY`DEGNS`BCDHZ`BCMTW`BbDpP NB. perm matrices +P=: ,/col,:"1/nat NB. join color and nationality matrices +P=: ('W' in Col = 1+ 'G' in Col)F P NB. white right of green +P=: (0 = 'N' in Nat)F P NB. Norwegian in first house +P=: ,/pet,"2 1/~ ('E' in Nat = 'R' in Col)F P NB. red = English; add pets +P=: ('N' in Nat (1=|@-) 'B' in Col)F P NB. blue next to Norwegian +P=: ,/drink,"2 1/~ ('D' in Pet = 'S' in Nat)F P NB. Swede owns dog; add drinks +P=: (2 = 'M' in Drink)F P NB. middle house drinks milk +P=: ('T' in Drink = 'D' in Nat)F P NB. Dane drinks tea +P=: ('C' in Drink = 'G' in Col)F P NB. green = coffee +P=: ('p' in Cig = 'B' in Pet)F ,/P,"2 1/cig NB. add cigs; PallMall = birds +P=: ('D' in Cig = 'Y' in Col)F P NB. Dunhill = yellow +P=: ('b' in Cig = 'B' in Drink)F P NB. BlueM = beer +P=: ('P' in Cig = 'G' in Nat)F P NB. Prince = German +P=: ('B' in Cig (1=|@-) 'C' in Pet)F P NB. cat next to Blend +P=: ('D' in Cig (1=|@-) 'H' in Pet)F P NB. horse next to Dunhill +P=: ('B' in Cig (1=|@-) 'W' in Drink)F P NB. water next to Blend +echo 'Solutions found: ',":#P +echo (('Z' in Pet { Nat&{){.P),' owns the Z' +echo 'Col Nat Pet Drink Cig' +echo ([,(6#' '),])/"1|:{.P diff --git a/Task/Zebra-puzzle/J/zebra-puzzle-10.j b/Task/Zebra-puzzle/J/zebra-puzzle-10.j index eea43ac714..ce52506cf3 100644 --- a/Task/Zebra-puzzle/J/zebra-puzzle-10.j +++ b/Task/Zebra-puzzle/J/zebra-puzzle-10.j @@ -1,12 +1,8 @@ - houses solve3 constraints, [: compose&.>~/y&, +z=. f^:(3>[:#(#~p"1)&>)^:_ <,:x +> (#~([:*./[:;[:<@({.~:}.)\.;)"1)(#~p"1); z +) diff --git a/Task/Zebra-puzzle/J/zebra-puzzle-11.j b/Task/Zebra-puzzle/J/zebra-puzzle-11.j new file mode 100644 index 0000000000..eea43ac714 --- /dev/null +++ b/Task/Zebra-puzzle/J/zebra-puzzle-11.j @@ -0,0 +1,12 @@ + houses solve3 constraints, next + lof +┌─────────────────┬───────────┐ +│┌┬┬──────┬─────┬┐│┌┬┬┬─────┬┐│ +││││coffee│green│││││││white│││ +│└┴┴──────┴─────┴┘│└┴┴┴─────┴┘│ +└─────────────────┴───────────┘ diff --git a/Task/Zebra-puzzle/J/zebra-puzzle-4.j b/Task/Zebra-puzzle/J/zebra-puzzle-4.j index 55bcd68d29..1ad98a0b60 100644 --- a/Task/Zebra-puzzle/J/zebra-puzzle-4.j +++ b/Task/Zebra-puzzle/J/zebra-puzzle-4.j @@ -1 +1,4 @@ -houses=: ((<'Norwegian') 0}ehs);((<'blue') 3 }ehs);((<'milk') 2}ehs);ehs; next diff --git a/Task/Zebra-puzzle/J/zebra-puzzle-5.j b/Task/Zebra-puzzle/J/zebra-puzzle-5.j index 79452d510f..55bcd68d29 100644 --- a/Task/Zebra-puzzle/J/zebra-puzzle-5.j +++ b/Task/Zebra-puzzle/J/zebra-puzzle-5.j @@ -1,6 +1 @@ - houses -┌───────────────┬──────────┬──────────┬──────┬──────┐ -│┌─────────┬┬┬┬┐│┌┬┬┬────┬┐│┌┬┬────┬┬┐│┌┬┬┬┬┐│┌┬┬┬┬┐│ -││Norwegian││││││││││blue││││││milk││││││││││││││││││ -│└─────────┴┴┴┴┘│└┴┴┴────┴┘│└┴┴────┴┴┘│└┴┴┴┴┘│└┴┴┴┴┘│ -└───────────────┴──────────┴──────────┴──────┴──────┘ +houses=: ((<'Norwegian') 0}ehs);((<'blue') 3 }ehs);((<'milk') 2}ehs);ehs;#S:0)"1 -compose=: [: filter f. [: ,/ select f. L:0"1"1 _ - -solve=: 4 :0 -h=. ,:x -whilst. 0=# z do. - for_e. y do. h=. h compose > e end. - z=.(#~1=[:+/"1 (0=#)S:0"1) h=.~. h -end. -) +constraints=: hcr;hcs;hlof;"0 houses solve constraints -┌─────────┬─────┬──────┬──────┬──────────┐ -│Norwegian│cats │water │yellow│Dunhill │ -├─────────┼─────┼──────┼──────┼──────────┤ -│Dane │horse│tea │blue │Blend │ -├─────────┼─────┼──────┼──────┼──────────┤ -│English │birds│milk │red │PallMall │ -├─────────┼─────┼──────┼──────┼──────────┤ -│German │ │coffee│green │Prince │ -├─────────┼─────┼──────┼──────┼──────────┤ -│Swede │dog │beer │white │BlueMaster│ -└─────────┴─────┴──────┴──────┴──────────┘ +Select=: [: ~. ,: #~ ,&(0~:#) +Filter=: #~ *./@:(2>#S:0)"1 +Compose=: [: Filter [: ,/ Select L:0"1"1 _ + +solve=: 4 :0 +h=. ,:x +whilst. 0=# z do. + for_e. y do. h=. h Compose > e end. + z=.(#~1=[:+/"1 (0=#)S:0"1) h=.~. h +end. +) diff --git a/Task/Zebra-puzzle/J/zebra-puzzle-9.j b/Task/Zebra-puzzle/J/zebra-puzzle-9.j index 4ca962c4d5..ac84dd931f 100644 --- a/Task/Zebra-puzzle/J/zebra-puzzle-9.j +++ b/Task/Zebra-puzzle/J/zebra-puzzle-9.j @@ -1,8 +1,12 @@ -zebra=: (-i.5)|."0 1 (<(<'zebra') 1}ehs),4$ [: compose&.>~/y&, f. -z=. f^:(3>[:#(#~p"1)&>)^:_ <,:x ->"0 (#~([:*./[:;[:<@({.~:}.)\.;)"1)(#~p"1); z -) + > houses solve constraints +┌─────────┬─────┬──────┬──────┬──────────┐ +│Norwegian│cats │water │yellow│Dunhill │ +├─────────┼─────┼──────┼──────┼──────────┤ +│Dane │horse│tea │blue │Blend │ +├─────────┼─────┼──────┼──────┼──────────┤ +│English │birds│milk │red │PallMall │ +├─────────┼─────┼──────┼──────┼──────────┤ +│German │ │coffee│green │Prince │ +├─────────┼─────┼──────┼──────┼──────────┤ +│Swede │dog │beer │white │BlueMaster│ +└─────────┴─────┴──────┴──────┴──────────┘ diff --git a/Task/Zebra-puzzle/JavaScript/zebra-puzzle.js b/Task/Zebra-puzzle/JavaScript/zebra-puzzle.js new file mode 100644 index 0000000000..ccb11f817e --- /dev/null +++ b/Task/Zebra-puzzle/JavaScript/zebra-puzzle.js @@ -0,0 +1,163 @@ +// Define enums and their string representations +const Attrib = { Color: 0, Man: 1, Drink: 2, Animal: 3, Smoke: 4 }; +const Attrib_str = ["Color", "Man", "Drink", "Animal", "Smoke"]; + +const Colors = { Red: 0, Green: 1, White: 2, Yellow: 3, Blue: 4 }; +const Colors_str = ["Red", "Green", "White", "Yellow", "Blue"]; + +const Mans = { English: 0, Swede: 1, Dane: 2, German: 3, Norwegian: 4 }; +const Mans_str = ["English", "Swede", "Dane", "German", "Norwegian"]; + +const Drinks = { Tea: 0, Coffee: 1, Milk: 2, Beer: 3, Water: 4 }; +const Drinks_str = ["Tea", "Coffee", "Milk", "Beer", "Water"]; + +const Animals = { Dog: 0, Birds: 1, Cats: 2, Horse: 3, Zebra: 4 }; +const Animals_str = ["Dog", "Birds", "Cats", "Horse", "Zebra"]; + +const Smokes = { PallMall: 0, Dunhill: 1, Blend: 2, BlueMaster: 3, Prince: 4 }; +const Smokes_str = ["PallMall", "Dunhill", "Blend", "BlueMaster", "Prince"]; + +function printHouses(ha) { + const attr_names = [Colors_str, Mans_str, Drinks_str, Animals_str, Smokes_str]; + + let output = "House".padEnd(10); + for (const name of Attrib_str) { + output += name.padEnd(10); + } + console.log(output); + + for (let i = 0; i < 5; i++) { + output = String(i).padEnd(10); + for (let j = 0; j < 5; j++) { + output += attr_names[j][ha[i][j]].padEnd(10); + } + console.log(output); + } +} + +// House number specific rules +const housenos = [ + { houseno: 2, a: Attrib.Drink, v: Drinks.Milk }, // Cond 9: In the middle house they drink milk. + { houseno: 0, a: Attrib.Man, v: Mans.Norwegian } // Cond 10: The Norwegian lives in the first house. +]; + +// Attribute pair rules +const pairs = [ + { a1: Attrib.Man, v1: Mans.English, a2: Attrib.Color, v2: Colors.Red }, // Cond 2: The English man lives in the red house. + { a1: Attrib.Man, v1: Mans.Swede, a2: Attrib.Animal, v2: Animals.Dog }, // Cond 3: The Swede has a dog. + { a1: Attrib.Man, v1: Mans.Dane, a2: Attrib.Drink, v2: Drinks.Tea }, // Cond 4: The Dane drinks tea. + { a1: Attrib.Color, v1: Colors.Green, a2: Attrib.Drink, v2: Drinks.Coffee }, // Cond 6: drink coffee in the green house. + { a1: Attrib.Smoke, v1: Smokes.PallMall, a2: Attrib.Animal, v2: Animals.Birds }, // Cond 7: The man who smokes Pall Mall has birds. + { a1: Attrib.Smoke, v1: Smokes.Dunhill, a2: Attrib.Color, v2: Colors.Yellow }, // Cond 8: In the yellow house they smoke Dunhill. + { a1: Attrib.Smoke, v1: Smokes.BlueMaster, a2: Attrib.Drink, v2: Drinks.Beer }, // Cond 13: The man who smokes Blue Master drinks beer. + { a1: Attrib.Man, v1: Mans.German, a2: Attrib.Smoke, v2: Smokes.Prince } // Cond 14: The German smokes Prince +]; + +// Next to rules +const nexttos = [ + { a1: Attrib.Smoke, v1: Smokes.Blend, a2: Attrib.Animal, v2: Animals.Cats }, // Cond 11: The man who smokes Blend lives in the house next to the house with cats. + { a1: Attrib.Smoke, v1: Smokes.Dunhill, a2: Attrib.Animal, v2: Animals.Horse }, // Cond 12: In a house next to the house where they have a horse, they smoke Dunhill. + { a1: Attrib.Man, v1: Mans.Norwegian, a2: Attrib.Color, v2: Colors.Blue }, // Cond 15: The Norwegian lives next to the blue house. + { a1: Attrib.Smoke, v1: Smokes.Blend, a2: Attrib.Drink, v2: Drinks.Water } // Cond 16: They drink water in a house next to the house where they smoke Blend. +]; + +// Left of rules +const leftofs = [ + { a1: Attrib.Color, v1: Colors.Green, a2: Attrib.Color, v2: Colors.White } // Cond 5: The green house is immediately to the left of the white house. +]; + +function invalid(ha) { + // Check leftofs global rules + for (const rule of leftofs) { + if (ha[0][rule.a2] === rule.v2 || ha[4][rule.a1] === rule.v1) { + return true; + } + } + + // Check rules for each house + for (let i = 0; i < 5; i++) { + // Check pair rules + for (const rule of pairs) { + if (ha[i][rule.a1] >= 0 && ha[i][rule.a2] >= 0 && + ((ha[i][rule.a1] === rule.v1 && ha[i][rule.a2] !== rule.v2) || + (ha[i][rule.a1] !== rule.v1 && ha[i][rule.a2] === rule.v2))) { + return true; + } + } + + // Check next to rules + for (const rule of nexttos) { + if (ha[i][rule.a1] === rule.v1) { + if (i === 0 && ha[i + 1][rule.a2] >= 0 && ha[i + 1][rule.a2] !== rule.v2) { + return true; + } else if (i === 4 && ha[i - 1][rule.a2] !== rule.v2) { + return true; + } else if (i > 0 && i < 4 && + ha[i + 1][rule.a2] >= 0 && ha[i + 1][rule.a2] !== rule.v2 && + ha[i - 1][rule.a2] !== rule.v2) { + return true; + } + } + } + + // Check left of rules for this house + for (const rule of leftofs) { + if (i > 0 && ha[i][rule.a1] >= 0 && + ((ha[i - 1][rule.a1] === rule.v1 && ha[i][rule.a2] !== rule.v2) || + (ha[i - 1][rule.a1] !== rule.v1 && ha[i][rule.a2] === rule.v2))) { + return true; + } + } + } + return false; +} + +function search(used, ha, hno, attr) { + let nexthno, nextattr; + if (attr < 4) { + nextattr = attr + 1; + nexthno = hno; + } else { + nextattr = 0; + nexthno = hno + 1; + } + + if (ha[hno][attr] !== -1) { + search(used, ha, nexthno, nextattr); + } else { + for (let i = 0; i < 5; i++) { + if (used[attr][i]) continue; + used[attr][i] = true; + ha[hno][attr] = i; + + if (!invalid(ha)) { + if (hno === 4 && attr === 4) { + printHouses(ha); + } else { + search(used, ha, nexthno, nextattr); + } + } + + used[attr][i] = false; + ha[hno][attr] = -1; + } + } +} + +function main() { + // Initialize arrays + const used = Array(5).fill().map(() => Array(5).fill(false)); + const ha = Array(5).fill().map(() => Array(5).fill(-1)); + + // Apply house number specific rules + for (const rule of housenos) { + ha[rule.houseno][rule.a] = rule.v; + used[rule.a][rule.v] = true; + } + + // Start the search + search(used, ha, 0, 0); +} + +// Run the program +main(); diff --git a/Task/Zebra-puzzle/Julia/zebra-puzzle-1.jl b/Task/Zebra-puzzle/Julia/zebra-puzzle-1.jl new file mode 100644 index 0000000000..50aa43a79c --- /dev/null +++ b/Task/Zebra-puzzle/Julia/zebra-puzzle-1.jl @@ -0,0 +1,55 @@ +using Combinatorics +function make(str, test = (s) -> true) + filter(test, collect( permutations(split(str))) ) +end + +men = make("danish english german norwegian swedish", + x -> "norwegian" == x[1]) + +drinks = make("beer coffee milk tea water", x -> "milk" == x[3]) + +colors = make("blue green red white yellow", + x -> 1 == findfirst(c -> c == "white", x) - findfirst(c -> c == "green",x)) + +pets = make("birds cats dog horse zebra") + +smokes = make("blend blue-master dunhill pall-mall prince") + +function eq(x, xs, y, ys) + findfirst(s -> s == x, xs) == findfirst(s -> s == y, ys) +end + +function adj(x, xs, y, ys) + 1 == abs(findfirst(z -> z == x, xs) - findfirst(z -> z == y, ys)) +end + +function print_houses(n, pet, nationality, colors, drink, smokes) + println("$n, $pet, $nationality $colors $drink $smokes") +end + +for m = men, c = colors + if eq("red",c, "english",m) && adj("norwegian",m, "blue",c) + for d = drinks + if eq("danish",m, "tea",d) && eq("coffee",d,"green",c) + for s = smokes + if eq("yellow",c,"dunhill",s) && + eq("blue-master",s,"beer",d) && + eq("german",m,"prince",s) + for p = pets + if eq("birds",p,"pall-mall",s) && + eq("swedish",m,"dog",p) && + adj("blend",s,"cats",p) && + adj("horse",p,"dunhill",s) + println("Zebra is owned by ", m[findfirst(c -> c == "zebra", p)]) + println("Houses:") + for house_num in 1:5 + print_houses(house_num,p[house_num],m[house_num],c[house_num],d[house_num],s[house_num]) + end + end + end + end + end + end + end + end +end diff --git a/Task/Zebra-puzzle/Julia/zebra-puzzle-1.julia b/Task/Zebra-puzzle/Julia/zebra-puzzle-1.julia deleted file mode 100644 index 6549440ab4..0000000000 --- a/Task/Zebra-puzzle/Julia/zebra-puzzle-1.julia +++ /dev/null @@ -1,57 +0,0 @@ -# Julia 1.0 -using Combinatorics -function make(str, test ) - filter(test, collect( permutations(split(str))) ) -end - -men = make("danish english german norwegian swedish", - x -> "norwegian" == x[1]) - -drinks = make("beer coffee milk tea water", x -> "milk" == x[3]) - -#Julia 1.0 compatible -colors = make("blue green red white yellow", - x -> 1 == findfirst(c -> c == "white", x) - findfirst(c -> c == "green",x)) - -pets = make("birds cats dog horse zebra") - -smokes = make("blend blue-master dunhill pall-mall prince") - -function eq(x, xs, y, ys) - findfirst(xs, x) == findfirst(ys, y) -end - -function adj(x, xs, y, ys) - 1 == abs(findfirst(xs, x) - findfirst(ys, y)) -end - -function print_houses(n, pet, nationality, colors, drink, smokes) - println("$n, $pet, $nationality $colors $drink $smokes") -end - -for m = men, c = colors - if eq("red",c, "english",m) && adj("norwegian",m, "blue",c) - for d = drinks - if eq("danish",m, "tea",d) && eq("coffee",d,"green",c) - for s = smokes - if eq("yellow",c,"dunhill",s) && - eq("blue-master",s,"beer",d) && - eq("german",m,"prince",s) - for p = pets - if eq("birds",p,"pall-mall",s) && - eq("swedish",m,"dog",p) && - adj("blend",s,"cats",p) && - adj("horse",p,"dunhill",s) - println("Zebra is owned by ", m[findfirst(c -> c == "zebra", p)]) - println("Houses:") - for house_num in 1:5 - print_houses(house_num,p[house_num],m[house_num],c[house_num],d[house_num],s[house_num]) - end - end - end - end - end - end - end - end -end diff --git a/Task/Zebra-puzzle/Julia/zebra-puzzle-2.julia b/Task/Zebra-puzzle/Julia/zebra-puzzle-2.jl similarity index 100% rename from Task/Zebra-puzzle/Julia/zebra-puzzle-2.julia rename to Task/Zebra-puzzle/Julia/zebra-puzzle-2.jl diff --git a/Task/Zebra-puzzle/Kotlin/zebra-puzzle.kotlin b/Task/Zebra-puzzle/Kotlin/zebra-puzzle.kts similarity index 100% rename from Task/Zebra-puzzle/Kotlin/zebra-puzzle.kotlin rename to Task/Zebra-puzzle/Kotlin/zebra-puzzle.kts diff --git a/Task/Zebra-puzzle/Phix/zebra-puzzle.phix b/Task/Zebra-puzzle/Phix/zebra-puzzle.phix index 9a9eca5d99..51c674c325 100644 --- a/Task/Zebra-puzzle/Phix/zebra-puzzle.phix +++ b/Task/Zebra-puzzle/Phix/zebra-puzzle.phix @@ -1,83 +1,86 @@ -(phixonline)--> - enum Colour, Nationality, Drink, Smoke, Pet - constant Colours = {"red","white","green","yellow","blue"}, - Nationalities = {"English","Swede","Dane","Norwegian","German"}, - Drinks = {"tea","coffee","milk","beer","water"}, - Smokes = {"Pall Mall","Dunhill","Blend","Blue Master","Prince"}, - Pets = {"dog","birds","cats","horse","zebra"}, - Sets = {Colours,Nationalities,Drinks,Smokes,Pets} +--enum colour, nationality, drink, smoke, pet -- (now implicit) +enum red,white,green,yellow,blue +enum English,Swede,Dane,Norwegian,German +enum tea,coffee,milk,beer,water +enum PallMall,Dunhill,Blend,BlueMaster,Prince +enum dog,birds,cats,horse,zebra - constant tagset5 = tagset(5) -- {1,2,3,4,5}, oft-permuted - sequence perm = repeat(tagset5,5) -- perm[1] is Colour of each house, etc +constant colours = {"red","white","green","yellow","blue"}, + nationalities = {"English","Swede","Dane","Norwegian","German"}, + drinks = {"tea","coffee","milk","beer","water"}, + smokes = {"Pall Mall","Dunhill","Blend","Blue Master","Prince"}, + pets = {"dog","birds","cats","horse","zebra"}, + sets = {colours,nationalities,drinks,smokes,pets} - function house(integer i, string name) - return find(find(name,Sets[i]),perm[i]) - end function +constant p5 = permutes(tagset(5)), -- all permutes of {1,2,3,4,5}, + lp = length(p5) -- (== factorial(5), ie 120) - function left_of(integer h1, integer h2) - return (h1-h2)==1 - end function +// In the following, c1,c2 are indexes to p5, for colour..pet, +// and v1,v2 are from their corresponding enums, so eg p5[c1] +// might be {1,4,3,2,5} for the colours of 1..5 and finding +// v1 in that gives us a house number. Checking the specified +// condition, eg [h] == green && [h+1] == white is then easy. - function next_to(integer h1, integer h2) - return abs(h1-h2)==1 - end function +function left_of(integer c1, v1, c2, v2) + integer h = find(v1,p5[c1]) + return h<=4 and p5[c2][h+1]=v2 +end function - procedure print_house(integer i) - printf(1,"%d:%s,%s,%s,%s,%s\n",{i, - Colours[perm[Colour][i]], - Nationalities[perm[Nationality][i]], - Drinks[perm[Drink][i]], - Smokes[perm[Smoke][i]], - Pets[perm[Pet][i]]}) - end procedure +function same_house(integer c1, v1, c2, v2) + integer h = find(v1,p5[c1]) + return p5[c2][h]=v2 +end function - integer solutions = 0 - sequence solperms = {} - atom t0 = time() - constant factorial5 = factorial(5) - for C=1 to factorial5 do - perm[Colour] = permute(C,tagset5) - if left_of(house(Colour,"green"),house(Colour,"white")) then - for N=1 to factorial5 do - perm[Nationality] = permute(N,tagset5) - if house(Nationality,"Norwegian")==1 - and house(Nationality,"English")==house(Colour,"red") - and next_to(house(Nationality,"Norwegian"),house(Colour,"blue")) then - for D=1 to factorial5 do - perm[Drink] = permute(D,tagset5) - if house(Nationality,"Dane")==house(Drink,"tea") - and house(Drink,"coffee")==house(Colour,"green") - and house(Drink,"milk")==3 then - for S=1 to factorial5 do - perm[Smoke] = permute(S,tagset5) - if house(Colour,"yellow")==house(Smoke,"Dunhill") - and house(Nationality,"German")==house(Smoke,"Prince") - and house(Smoke,"Blue Master")==house(Drink,"beer") - and next_to(house(Drink,"water"),house(Smoke,"Blend")) then - for P=1 to factorial5 do - perm[Pet] = permute(P,tagset5) - if house(Nationality,"Swede")==house(Pet,"dog") - and house(Smoke,"Pall Mall")==house(Pet,"birds") - and next_to(house(Smoke,"Blend"),house(Pet,"cats")) - and next_to(house(Pet,"horse"),house(Smoke,"Dunhill")) then - for i=1 to 5 do - print_house(i) - end for - solutions += 1 - solperms = append(solperms,perm) - end if - end for - end if - end for - end if - end for - end if - end for - end if - end for - printf(1,"%d solution%s found (%3.3fs).\n",{solutions,iff(solutions>1,"s",""),time()-t0}) - for i=1 to length(solperms) do - perm = solperms[i] - printf(1,"The %s owns the Zebra\n",{Nationalities[house(Pet,"zebra")]}) - end for - R = {{0, 1, 5, 6, 14}, {2, 4, 7, 13, 15}, {3, 8, 12, 16, 21}, {9, 11, 17, 20, 22}, {10, 18, 19, 23, 24}} -- Reformat the matrix into a table for viewing. repeat with i in m - repeat with j in i - set j's contents to (characters -(length of (n ^ 2 as string)) thru -1 of (" " & j)) as string - end repeat - set end of i to return + repeat with j in i + set j's contents to (characters -(length of (n ^ 2 as string)) thru -1 of (" " & j)) as string + end repeat + set end of i to return end repeat return return & m as string diff --git a/Task/Zig-zag-matrix/AppleScript/zig-zag-matrix-2.applescript b/Task/Zig-zag-matrix/AppleScript/zig-zag-matrix-2.applescript index e565bed953..cadeca6e60 100644 --- a/Task/Zig-zag-matrix/AppleScript/zig-zag-matrix-2.applescript +++ b/Task/Zig-zag-matrix/AppleScript/zig-zag-matrix-2.applescript @@ -2,33 +2,33 @@ set n to 5 set m to {} repeat with i from 1 to n - set end of m to {} -- Built a foundation for the matrix out of n empty lists. + set end of m to {} -- Built a foundation for the matrix out of n empty lists. end repeat set {v, d, i} to {0, -1, 1} repeat while v < n ^ 2 - if length of m's item i < n then - set {end of m's item i, i, v} to {f(v, n), i + d, v + 1} - if i < 1 then - set {i, d} to {1, -d} - else if i > n then - set {i, d} to {n, -d} - else if i > 1 and (count of m's item (i - 1)) = 1 then - set d to -d - end if - else - set {i, d} to {i + 1, 1} - end if + if length of m's item i < n then + set {end of m's item i, i, v} to {f(v, n), i + d, v + 1} + if i < 1 then + set {i, d} to {1, -d} + else if i > n then + set {i, d} to {n, -d} + else if i > 1 and (count of m's item (i - 1)) = 1 then + set d to -d + end if + else + set {i, d} to {i + 1, 1} + end if end repeat -- Handler/function to format the cells on the fly. on f(v, n) - return (characters -(length of (n ^ 2 as string)) thru -1 of (" " & v)) as string + return (characters -(length of (n ^ 2 as string)) thru -1 of (" " & v)) as string end f -- Reformat the matrix into a table for viewing. set text item delimiters to "" repeat with i in m - set i's contents to (i as string) & return + set i's contents to (i as string) & return end repeat return return & m as string diff --git a/Task/Zig-zag-matrix/Arturo/zig-zag-matrix.arturo b/Task/Zig-zag-matrix/Arturo/zig-zag-matrix.arturo index b257e43188..cb6bd8dc1e 100644 --- a/Task/Zig-zag-matrix/Arturo/zig-zag-matrix.arturo +++ b/Task/Zig-zag-matrix/Arturo/zig-zag-matrix.arturo @@ -4,15 +4,14 @@ zigzag: function [n][ x: 1, y: 1, v: 0, d: 1 while [v < n^2][ - if? all? @[1 =< x x =< n 1 =< y y =< n][ + switch all? @[1 =< x x =< n 1 =< y y =< n][ set get result (y-1) (x-1) v x: x + d, y: y - d, v: v + 1 ] - else[if? x > n [x: n, y: y + 2, d: neg d] - else[if? y > n [x: x + 2, y: n, d: neg d] - else[if? x < 1 [x: 1, d: neg d] - else[if y < 1 [y: 1, d: neg d] - ] + [switch x > n [x: n, y: y + 2, d: neg d] + [switch y > n [x: x + 2, y: n, d: neg d] + [switch x < 1 [x: 1, d: neg d] + [if y < 1 [y: 1, d: neg d]] ] ] ] diff --git a/Task/Zig-zag-matrix/AutoIt/zig-zag-matrix.au3 b/Task/Zig-zag-matrix/AutoIt/zig-zag-matrix.au3 new file mode 100644 index 0000000000..82389c5ac5 --- /dev/null +++ b/Task/Zig-zag-matrix/AutoIt/zig-zag-matrix.au3 @@ -0,0 +1,27 @@ +#include +$Array = ZigZag(5) +_ArrayDisplay($Array) + +Func ZigZag($int) + Local $av_array[$int][$int] + Local $x = 1, $y = 1 + For $I = 0 To $int ^ 2 -1 + $av_array[$x-1][$y-1] = $I + If Mod(($x + $y), 2) = 0 Then ;Even + if ($y < $int) Then + $y += 1 + Else + $x += 2 + EndIf + if ($x > 1) Then $x -= 1 + Else ; ODD + if ($x < $int) Then + $x += 1 + Else + $y += 2 + EndIf + If $y > 1 Then $y -= 1 + EndIf + Next + Return $av_array +EndFunc ;==>ZigZag diff --git a/Task/Zig-zag-matrix/AutoIt/zig-zag-matrix.autoit b/Task/Zig-zag-matrix/AutoIt/zig-zag-matrix.autoit deleted file mode 100644 index 0fe354b261..0000000000 --- a/Task/Zig-zag-matrix/AutoIt/zig-zag-matrix.autoit +++ /dev/null @@ -1,27 +0,0 @@ -#include -$Array = ZigZag(5) -_ArrayDisplay($Array) - -Func ZigZag($int) - Local $av_array[$int][$int] - Local $x = 1, $y = 1 - For $I = 0 To $int ^ 2 -1 - $av_array[$x-1][$y-1] = $I - If Mod(($x + $y), 2) = 0 Then ;Even - if ($y < $int) Then - $y += 1 - Else - $x += 2 - EndIf - if ($x > 1) Then $x -= 1 - Else ; ODD - if ($x < $int) Then - $x += 1 - Else - $y += 2 - EndIf - If $y > 1 Then $y -= 1 - EndIf - Next - Return $av_array -EndFunc ;==>ZigZag diff --git a/Task/Zig-zag-matrix/Beads/zig-zag-matrix.beads b/Task/Zig-zag-matrix/Beads/zig-zag-matrix.beads index c81a460a62..4014a0eef4 100644 --- a/Task/Zig-zag-matrix/Beads/zig-zag-matrix.beads +++ b/Task/Zig-zag-matrix/Beads/zig-zag-matrix.beads @@ -1,50 +1,50 @@ beads 1 program 'Zig-zag Matrix' calc main_init - var test : array^2 of num = create_array(5) - printMatrix(test) - + var test : array^2 of num = create_array(5) + printMatrix(test) + calc create_array( - dimension:num - ):array^2 of num - var - result : array^2 of num - lastValue = dimension^2 - 1 - loopFrom - loopTo - row - col - currDiag = 0 - currNum = 0 - loop - if (currDiag < dimension) // if doing the upper-left triangular half - loopFrom = 1 - loopTo = currDiag + 1 - else // doing the bottom-right triangular half - loopFrom = currDiag - dimension + 2 - loopTo = dimension - loop count:c from:loopFrom to:loopTo - var i = loopFrom + c - 1 - if (rem(currDiag, 2) == 0) // want to fill upwards - row = loopTo - i + loopFrom - col = i - else // want to fill downwards - row = i - col = loopTo - i + loopFrom - result[row][col] = currNum - inc currNum - inc currDiag - if (currNum > lastValue) - exit - return result - + dimension:num + ):array^2 of num + var + result : array^2 of num + lastValue = dimension^2 - 1 + loopFrom + loopTo + row + col + currDiag = 0 + currNum = 0 + loop + if (currDiag < dimension) // if doing the upper-left triangular half + loopFrom = 1 + loopTo = currDiag + 1 + else // doing the bottom-right triangular half + loopFrom = currDiag - dimension + 2 + loopTo = dimension + loop count:c from:loopFrom to:loopTo + var i = loopFrom + c - 1 + if (rem(currDiag, 2) == 0) // want to fill upwards + row = loopTo - i + loopFrom + col = i + else // want to fill downwards + row = i + col = loopTo - i + loopFrom + result[row][col] = currNum + inc currNum + inc currDiag + if (currNum > lastValue) + exit + return result + calc printMatrix( - matrix:array^2 of num - ) - var dimension = tree_count(matrix) - var maxDigits = 1 + lg((dimension^2-1), base:10) - loop across:matrix ptr:rowp index:row - var tempstr : str - loop across:rowp index:col - tempstr = tempstr & " " & to_str(matrix[row][col], min:maxDigits) - log(tempstr) + matrix:array^2 of num + ) + var dimension = tree_count(matrix) + var maxDigits = 1 + lg((dimension^2-1), base:10) + loop across:matrix ptr:rowp index:row + var tempstr : str + loop across:rowp index:col + tempstr = tempstr & " " & to_str(matrix[row][col], min:maxDigits) + log(tempstr) diff --git a/Task/Zig-zag-matrix/C++/zig-zag-matrix.cpp b/Task/Zig-zag-matrix/C++/zig-zag-matrix.cpp index 2cb3293bba..3b25904685 100644 --- a/Task/Zig-zag-matrix/C++/zig-zag-matrix.cpp +++ b/Task/Zig-zag-matrix/C++/zig-zag-matrix.cpp @@ -1,8 +1,8 @@ #include -#include // for auto_ptr -#include // for the log10 and floor functions +#include // for auto_ptr +#include // for the log10 and floor functions #include -#include // for the setw function +#include // for the setw function using namespace std; @@ -11,71 +11,71 @@ typedef vector< IntRow > IntTable; auto_ptr< IntTable > getZigZagArray( int dimension ) { - auto_ptr< IntTable > zigZagArrayPtr( new IntTable( - dimension, IntRow( dimension ) ) ); + auto_ptr< IntTable > zigZagArrayPtr( new IntTable( + dimension, IntRow( dimension ) ) ); - // fill along diagonal stripes (oriented as "/") - int lastValue = dimension * dimension - 1; - int currNum = 0; - int currDiag = 0; - int loopFrom; - int loopTo; - int i; - int row; - int col; - do - { - if ( currDiag < dimension ) // if doing the upper-left triangular half - { - loopFrom = 0; - loopTo = currDiag; - } - else // doing the bottom-right triangular half - { - loopFrom = currDiag - dimension + 1; - loopTo = dimension - 1; - } + // fill along diagonal stripes (oriented as "/") + int lastValue = dimension * dimension - 1; + int currNum = 0; + int currDiag = 0; + int loopFrom; + int loopTo; + int i; + int row; + int col; + do + { + if ( currDiag < dimension ) // if doing the upper-left triangular half + { + loopFrom = 0; + loopTo = currDiag; + } + else // doing the bottom-right triangular half + { + loopFrom = currDiag - dimension + 1; + loopTo = dimension - 1; + } - for ( i = loopFrom; i <= loopTo; i++ ) - { - if ( currDiag % 2 == 0 ) // want to fill upwards - { - row = loopTo - i + loopFrom; - col = i; - } - else // want to fill downwards - { - row = i; - col = loopTo - i + loopFrom; - } + for ( i = loopFrom; i <= loopTo; i++ ) + { + if ( currDiag % 2 == 0 ) // want to fill upwards + { + row = loopTo - i + loopFrom; + col = i; + } + else // want to fill downwards + { + row = i; + col = loopTo - i + loopFrom; + } - ( *zigZagArrayPtr )[ row ][ col ] = currNum++; - } + ( *zigZagArrayPtr )[ row ][ col ] = currNum++; + } - currDiag++; - } - while ( currDiag <= lastValue ); + currDiag++; + } + while ( currDiag <= lastValue ); - return zigZagArrayPtr; + return zigZagArrayPtr; } void printZigZagArray( const auto_ptr< IntTable >& zigZagArrayPtr ) { - size_t dimension = zigZagArrayPtr->size(); + size_t dimension = zigZagArrayPtr->size(); - int fieldWidth = static_cast< int >( floor( log10( - static_cast< double >( dimension * dimension - 1 ) ) ) ) + 2; + int fieldWidth = static_cast< int >( floor( log10( + static_cast< double >( dimension * dimension - 1 ) ) ) ) + 2; - size_t col; - for ( size_t row = 0; row < dimension; row++ ) - { - for ( col = 0; col < dimension; col++ ) - cout << setw( fieldWidth ) << ( *zigZagArrayPtr )[ row ][ col ]; - cout << endl; - } + size_t col; + for ( size_t row = 0; row < dimension; row++ ) + { + for ( col = 0; col < dimension; col++ ) + cout << setw( fieldWidth ) << ( *zigZagArrayPtr )[ row ][ col ]; + cout << endl; + } } int main() { - printZigZagArray( getZigZagArray( 5 ) ); + printZigZagArray( getZigZagArray( 5 ) ); } diff --git a/Task/Zig-zag-matrix/C/zig-zag-matrix.c b/Task/Zig-zag-matrix/C/zig-zag-matrix.c index ebe9d6ef1d..0df51693fa 100644 --- a/Task/Zig-zag-matrix/C/zig-zag-matrix.c +++ b/Task/Zig-zag-matrix/C/zig-zag-matrix.c @@ -3,21 +3,21 @@ int main(int c, char **v) { - int i, j, m, n, *s; + int i, j, m, n, *s; - /* default size: 5 */ - if (c < 2 || ((m = atoi(v[1]))) <= 0) m = 5; + /* default size: 5 */ + if (c < 2 || ((m = atoi(v[1]))) <= 0) m = 5; - /* alloc array*/ - s = malloc(sizeof(int) * m * m); + /* alloc array*/ + s = malloc(sizeof(int) * m * m); - for (i = n = 0; i < m * 2; i++) - for (j = (i < m) ? 0 : i-m+1; j <= i && j < m; j++) - s[(i&1)? j*(m-1)+i : (i-j)*m+j ] = n++; + for (i = n = 0; i < m * 2; i++) + for (j = (i < m) ? 0 : i-m+1; j <= i && j < m; j++) + s[(i&1)? j*(m-1)+i : (i-j)*m+j ] = n++; - for (i = 0; i < m * m; putchar((++i % m) ? ' ':'\n')) - printf("%3d", s[i]); + for (i = 0; i < m * m; putchar((++i % m) ? ' ':'\n')) + printf("%3d", s[i]); - /* free(s) */ - return 0; + /* free(s) */ + return 0; } diff --git a/Task/Zig-zag-matrix/Ceylon/zig-zag-matrix.ceylon b/Task/Zig-zag-matrix/Ceylon/zig-zag-matrix.ceylon index 5f2854449c..1554997ddc 100644 --- a/Task/Zig-zag-matrix/Ceylon/zig-zag-matrix.ceylon +++ b/Task/Zig-zag-matrix/Ceylon/zig-zag-matrix.ceylon @@ -1,50 +1,50 @@ class ZigZag(Integer size) { - - value data = Array { - for (i in 0:size) - Array.ofSize(size, 0) - }; - - variable value i = 1; - variable value j = 1; - - for (element in 0 : size^2) { - data[j - 1]?.set(i - 1, element); - if ((i + j).even) { - if (j < size) { - j++; - } - else { - i += 2; - } - if (i > 1) { - i--; - } - } - else { - if (i < size) { - i++; - } - else { - j += 2; - } - if (j > 1) { - j--; - } - } - } - - shared void display() { - for (row in data) { - for (element in row) { - process.write(element.string.pad(3)); - } - print(""); //newline - } - } + + value data = Array { + for (i in 0:size) + Array.ofSize(size, 0) + }; + + variable value i = 1; + variable value j = 1; + + for (element in 0 : size^2) { + data[j - 1]?.set(i - 1, element); + if ((i + j).even) { + if (j < size) { + j++; + } + else { + i += 2; + } + if (i > 1) { + i--; + } + } + else { + if (i < size) { + i++; + } + else { + j += 2; + } + if (j > 1) { + j--; + } + } + } + + shared void display() { + for (row in data) { + for (element in row) { + process.write(element.string.pad(3)); + } + print(""); //newline + } + } } shared void run() { - value zz = ZigZag(5); - zz.display(); + value zz = ZigZag(5); + zz.display(); } diff --git a/Task/Zig-zag-matrix/Clojure/zig-zag-matrix.clj b/Task/Zig-zag-matrix/Clojure/zig-zag-matrix.clj index dbac76be7c..7fbf9aa000 100644 --- a/Task/Zig-zag-matrix/Clojure/zig-zag-matrix.clj +++ b/Task/Zig-zag-matrix/Clojure/zig-zag-matrix.clj @@ -3,14 +3,14 @@ (when-let [n (first sizes)] (when-let [s (seq coll)] (cons (take n coll) - (partitions (next sizes) (drop n coll))))))) + (partitions (next sizes) (drop n coll))))))) (defn take-from [n colls] (lazy-seq (when-let [s (seq colls)] (let [[first-n rest-n] (split-at n s)] (cons (map first first-n) - (take-from n (concat (filter seq (map rest first-n)) rest-n))))))) + (take-from n (concat (filter seq (map rest first-n)) rest-n))))))) (defn zig-zag [n] (->> (partitions (concat (range 1 (inc n)) (range (dec n) 0 -1)) (range (* n n))) diff --git a/Task/Zig-zag-matrix/Crystal/zig-zag-matrix.cr b/Task/Zig-zag-matrix/Crystal/zig-zag-matrix.cr new file mode 100644 index 0000000000..e78130bde2 --- /dev/null +++ b/Task/Zig-zag-matrix/Crystal/zig-zag-matrix.cr @@ -0,0 +1,12 @@ +def zigzag(n) + (seq=(0...n).to_a).cartesian_product(seq) + .sort_by {|x,y| [x+y, (x+y).even? ? y : -y]} + .map_with_index{|v, i| {v, i}}.sort.map(&.last).each_slice(n).to_a +end + +def print_matrix(m) + format = "%#{m.flatten.max.to_s.size}d " * m[0].size + m.each {|row| puts format % row} +end + +print_matrix zigzag(5) diff --git a/Task/Zig-zag-matrix/Crystal/zig-zag-matrix.crystal b/Task/Zig-zag-matrix/Crystal/zig-zag-matrix.crystal deleted file mode 100644 index f2f7d2cdb4..0000000000 --- a/Task/Zig-zag-matrix/Crystal/zig-zag-matrix.crystal +++ /dev/null @@ -1,12 +0,0 @@ -def zigzag(n) - (seq=(0...n).to_a).product(seq) - .sort_by {|x,y| [x+y, (x+y).even? ? y : -y]} - .map_with_index{|v, i| {v, i}}.sort.map(&.last).each_slice(n).to_a -end - -def print_matrix(m) - format = "%#{m.flatten.max.to_s.size}d " * m[0].size - m.each {|row| puts format % row} -end - -print_matrix zigzag(5) diff --git a/Task/Zig-zag-matrix/D/zig-zag-matrix-2.d b/Task/Zig-zag-matrix/D/zig-zag-matrix-2.d index 2700e862c3..67333e2743 100644 --- a/Task/Zig-zag-matrix/D/zig-zag-matrix-2.d +++ b/Task/Zig-zag-matrix/D/zig-zag-matrix-2.d @@ -9,7 +9,7 @@ int[][] zigZag(in int n) pure nothrow { auto result = new typeof(return)(n, n); foreach (immutable i, immutable p; L) - result[p.y][p.x] = i; + result[p.y][p.x] = cast(int) i; return result; } diff --git a/Task/Zig-zag-matrix/Delphi/zig-zag-matrix.delphi b/Task/Zig-zag-matrix/Delphi/zig-zag-matrix.delphi deleted file mode 100644 index 38d0c66acc..0000000000 --- a/Task/Zig-zag-matrix/Delphi/zig-zag-matrix.delphi +++ /dev/null @@ -1,56 +0,0 @@ -type TMatrix = array of array of double; - - - -procedure DisplayMatrix(Memo: TMemo; Mat: TMatrix); -{Display specified matrix} -var X,Y: integer; -var S: string; -begin -S:=''; -for Y:=0 to High(Mat[0]) do - begin - S:=S+'['; - for X:=0 to High(Mat) do - S:=S+Format('%4.0f',[Mat[X,Y]]); - S:=S+']'+#$0D#$0A; - end; -Memo.Lines.Add(S); -end; - -procedure ZigzagMatrix(Memo: TMemo); -var Mat: TMatrix; -var X,Y,Inx,Dir: integer; -const Size = 10; - - procedure Toggle(var I: integer); - {Toggle Direction and increment I} - begin - Dir:=-Dir; - Inc(I); - end; - - - procedure Step(var X,Y: integer); - {Take one step "Dir" direction} - begin - X:=X+Dir; - Y:=Y-Dir; - end; - -begin -SetLength(Mat,Size,Size); -Inx:=0; X:=0; Y:=0; Dir:=1; -repeat - begin - Mat[X,Y]:=Inx; - if (X+Dir)>=Size then Toggle(Y) - else if (Y-Dir)>=Size then Toggle(X) - else if (X+Dir)<0 then Toggle(Y) - else if (Y-Dir)<0 then Toggle(X) - else Step(X,Y); - Inc(Inx); - end -until Inx>=Size*Size; -DisplayMatrix(Memo,Mat); -end; diff --git a/Task/Zig-zag-matrix/Delphi/zig-zag-matrix.pas b/Task/Zig-zag-matrix/Delphi/zig-zag-matrix.pas new file mode 100644 index 0000000000..8c5b0f453b --- /dev/null +++ b/Task/Zig-zag-matrix/Delphi/zig-zag-matrix.pas @@ -0,0 +1,56 @@ +type TMatrix = array of array of double; + + + +procedure DisplayMatrix(Memo: TMemo; Mat: TMatrix); +{Display specified matrix} +var X,Y: integer; +var S: string; +begin +S:=''; +for Y:=0 to High(Mat[0]) do + begin + S:=S+'['; + for X:=0 to High(Mat) do + S:=S+Format('%4.0f',[Mat[X,Y]]); + S:=S+']'+#$0D#$0A; + end; +Memo.Lines.Add(S); +end; + +procedure ZigzagMatrix(Memo: TMemo); +var Mat: TMatrix; +var X,Y,Inx,Dir: integer; +const Size = 10; + + procedure Toggle(var I: integer); + {Toggle Direction and increment I} + begin + Dir:=-Dir; + Inc(I); + end; + + + procedure Step(var X,Y: integer); + {Take one step "Dir" direction} + begin + X:=X+Dir; + Y:=Y-Dir; + end; + +begin +SetLength(Mat,Size,Size); +Inx:=0; X:=0; Y:=0; Dir:=1; +repeat + begin + Mat[X,Y]:=Inx; + if (X+Dir)>=Size then Toggle(Y) + else if (Y-Dir)>=Size then Toggle(X) + else if (X+Dir)<0 then Toggle(Y) + else if (Y-Dir)<0 then Toggle(X) + else Step(X,Y); + Inc(Inx); + end +until Inx>=Size*Size; +DisplayMatrix(Memo,Mat); +end; diff --git a/Task/Zig-zag-matrix/DuckDB/zig-zag-matrix.duckdb b/Task/Zig-zag-matrix/DuckDB/zig-zag-matrix.duckdb new file mode 100644 index 0000000000..f14d59b037 --- /dev/null +++ b/Task/Zig-zag-matrix/DuckDB/zig-zag-matrix.duckdb @@ -0,0 +1,40 @@ +create or replace function zigzag_matrix(n) as table ( + with recursive cte as ( + select 1 as ix, 1 as i, 1 as j, 0 as ij + union all + select ix+1 as ix, + if( (i + j) % 2 = 0, + -- Even stripes + if( i < n, i + 1, i), + -- Odd stripes + if( j < n, i - (i > 1)::INT, i + 1) ) as i, + if( (i + j) % 2 == 0, + -- Even stripes + if( i < n, j - (j > 1)::INT, j + 1) , + -- Odd stripes + if( j < n, j+1, j)) as j, + ij + 1 as ij + from cte + where ix < n*n + ) + select i, j, ij as value + from cte +); + +# The i-th row as a list +create or replace function ijTable2Row(A, m) as ( + select array_agg(value order by j) + from query_table(A) + where i = m +); + +# Pretty-print the mxn matrix stored as an ij-table named A +create or replace function ijTable_pp(A,m,n) as table ( + select ijTable2Row(A,i) as row + from range(1, m+1) t(i) + order by i +); + +# Create the zig-zag matrix as a table and pretty-print it +with zz as (from zigzag_matrix(5)) +from ijTable_pp('zz', 5,5); diff --git a/Task/Zig-zag-matrix/EMal/zig-zag-matrix.emal b/Task/Zig-zag-matrix/EMal/zig-zag-matrix.emal index 21fac16b47..860137c2dc 100644 --- a/Task/Zig-zag-matrix/EMal/zig-zag-matrix.emal +++ b/Task/Zig-zag-matrix/EMal/zig-zag-matrix.emal @@ -1,23 +1,23 @@ -fun zigzag = List by int n - List matrix = List[].with(n) - for int y = 0; y < n; y++ do matrix[y] = int[].with(n) end - int y, x = 1 - for int value = 0; value < n * n; value++ - matrix[y - 1][x - 1] = value - if (y + x) % 2 == 0 +fun zigzag ← List by int n + List matrix ← List[].with(n) + for int y ← 0; y < n; y++ do matrix[y] ← int[].with(n) end + int y, x ← 1 + for int value ← 0; value < n²; value++ + matrix[y - 1][x - 1] ← value + if (y + x) % 2 æ 0 if x < n do x++ - else do y += 2 end + else do y +← 2 end if y > 1 do y-- end else if y < n do y++ - else do x += 2 end + else do x +← 2 end if x > 1 do x-- end end end return matrix end -fun dump = void by List matrix - int max = length(text!(matrix.length ** 2)) + 1 +fun dump ← void by List matrix + int max ← length(text!(matrix.length²)) + 1 for each List row in matrix for each int value in row write(" " * (max - length(text!value)) + value) diff --git a/Task/Zig-zag-matrix/EasyLang/zig-zag-matrix.easy b/Task/Zig-zag-matrix/EasyLang/zig-zag-matrix.easy new file mode 100644 index 0000000000..0db56b35a7 --- /dev/null +++ b/Task/Zig-zag-matrix/EasyLang/zig-zag-matrix.easy @@ -0,0 +1,31 @@ +func sumto n . + return n * (n + 1) div 2 +. +func coord2num row col n . + diag = col + row + if diag < n + start = sumto diag + if diag mod 2 = 0 + offs = col + else + offs = row + . + else + start = n * n - sumto (2 * n - 1 - diag) + offs = n - 1 + if diag mod 2 = 0 + offs -= row + else + offs -= col + . + . + return start + offs +. +n = 6 +numfmt 3 0 +for row = 0 to n - 1 + for col = 0 to n - 1 + write coord2num row col n + . + print "" +. diff --git a/Task/Zig-zag-matrix/Elena/zig-zag-matrix.elena b/Task/Zig-zag-matrix/Elena/zig-zag-matrix.elena index f9e5b36190..fb7d955e67 100644 --- a/Task/Zig-zag-matrix/Elena/zig-zag-matrix.elena +++ b/Task/Zig-zag-matrix/Elena/zig-zag-matrix.elena @@ -38,7 +38,7 @@ extension op : IntNumber } } -public program() +public Program() { - console.printLine(5.zigzagMatrix()).readChar() + Console.printLine(5.zigzagMatrix()).readChar() } diff --git a/Task/Zig-zag-matrix/Elixir/zig-zag-matrix.elixir b/Task/Zig-zag-matrix/Elixir/zig-zag-matrix.ex similarity index 100% rename from Task/Zig-zag-matrix/Elixir/zig-zag-matrix.elixir rename to Task/Zig-zag-matrix/Elixir/zig-zag-matrix.ex diff --git a/Task/Zig-zag-matrix/Erlang/zig-zag-matrix.erl b/Task/Zig-zag-matrix/Erlang/zig-zag-matrix.erl index 689ae59c48..c44749f1b5 100644 --- a/Task/Zig-zag-matrix/Erlang/zig-zag-matrix.erl +++ b/Task/Zig-zag-matrix/Erlang/zig-zag-matrix.erl @@ -3,8 +3,8 @@ -export( [matrix/1, task/0] ). matrix( N ) -> - {{_X_Y, N}, Proplist} = lists:foldl( fun matrix_as_proplist/2, {{{0, 0}, N}, []}, lists:seq(0, (N * N) - 1) ), - [columns( X, Proplist ) || X <- lists:seq(0, N - 1)]. + {{_X_Y, N}, Proplist} = lists:foldl( fun matrix_as_proplist/2, {{{0, 0}, N}, []}, lists:seq(0, (N * N) - 1) ), + [columns( X, Proplist ) || X <- lists:seq(0, N - 1)]. task() -> matrix( 5 ). @@ -13,8 +13,8 @@ task() -> matrix( 5 ). columns( Column, Proplist ) -> lists:sort( [Value || {{_X, Y}, Value} <- Proplist, Y =:= Column] ). matrix_as_proplist( N, {{X_Y, Max}, Acc} ) -> - Next = next_indexes( X_Y, Max ), - {{Next, Max}, [{X_Y, N} | Acc]}. + Next = next_indexes( X_Y, Max ), + {{Next, Max}, [{X_Y, N} | Acc]}. next_indexes( {X, Y}, Max ) when Y + 1 =:= Max, (X + Y) rem 2 =:= 0 -> {X + 1, Y - 1}; next_indexes( {X, Y}, Max ) when Y + 1 =:= Max, (X + Y) rem 2 =:= 1 -> {X + 1, Y}; diff --git a/Task/Zig-zag-matrix/Euphoria/zig-zag-matrix.euphoria b/Task/Zig-zag-matrix/Euphoria/zig-zag-matrix.eu similarity index 100% rename from Task/Zig-zag-matrix/Euphoria/zig-zag-matrix.euphoria rename to Task/Zig-zag-matrix/Euphoria/zig-zag-matrix.eu diff --git a/Task/Zig-zag-matrix/Julia/zig-zag-matrix-1.julia b/Task/Zig-zag-matrix/Julia/zig-zag-matrix-1.jl similarity index 100% rename from Task/Zig-zag-matrix/Julia/zig-zag-matrix-1.julia rename to Task/Zig-zag-matrix/Julia/zig-zag-matrix-1.jl diff --git a/Task/Zig-zag-matrix/Julia/zig-zag-matrix-2.julia b/Task/Zig-zag-matrix/Julia/zig-zag-matrix-2.jl similarity index 100% rename from Task/Zig-zag-matrix/Julia/zig-zag-matrix-2.julia rename to Task/Zig-zag-matrix/Julia/zig-zag-matrix-2.jl diff --git a/Task/Zig-zag-matrix/Julia/zig-zag-matrix-3.julia b/Task/Zig-zag-matrix/Julia/zig-zag-matrix-3.jl similarity index 100% rename from Task/Zig-zag-matrix/Julia/zig-zag-matrix-3.julia rename to Task/Zig-zag-matrix/Julia/zig-zag-matrix-3.jl diff --git a/Task/Zig-zag-matrix/Julia/zig-zag-matrix-4.julia b/Task/Zig-zag-matrix/Julia/zig-zag-matrix-4.jl similarity index 100% rename from Task/Zig-zag-matrix/Julia/zig-zag-matrix-4.julia rename to Task/Zig-zag-matrix/Julia/zig-zag-matrix-4.jl diff --git a/Task/Zig-zag-matrix/Kotlin/zig-zag-matrix.kotlin b/Task/Zig-zag-matrix/Kotlin/zig-zag-matrix.kts similarity index 100% rename from Task/Zig-zag-matrix/Kotlin/zig-zag-matrix.kotlin rename to Task/Zig-zag-matrix/Kotlin/zig-zag-matrix.kts diff --git a/Task/Zig-zag-matrix/Ksh/zig-zag-matrix.ksh b/Task/Zig-zag-matrix/Ksh/zig-zag-matrix.ksh index 985777fbb4..ca129520c0 100644 --- a/Task/Zig-zag-matrix/Ksh/zig-zag-matrix.ksh +++ b/Task/Zig-zag-matrix/Ksh/zig-zag-matrix.ksh @@ -2,15 +2,15 @@ # Produce a zig-zag array. -# # Variables: +# # Variables: # -integer DEF_SIZE=5 # Default size = 5 -arr_size=${1:-$DEF_SIZE} # $1 = size, or default +integer DEF_SIZE=5 # Default size = 5 +arr_size=${1:-$DEF_SIZE} # $1 = size, or default - # # Externals: + # # Externals: # -# # Functions: +# # Functions: # @@ -21,12 +21,12 @@ integer i j n typeset -a zzarr for (( i=n=0; i2 then Error "This is for 2D arrays" - integer i, j, n=dimension(Ar(),1), n1=dimension(Ar(),2) - for i=1 to n - for j=1 to n1 - print Ar(i, j), - next - print - next - } - Function Global MakeArray(n as integer=5) { - dim a(1 to n, 1 to n) as integer=0 - integer i=1, j=1, z, t1=1 - boolean ch=true - for z=0 to n*n-1 - if ch then a(i,j)=z else a(j,i)=z - j++ - if j>t1 then t1++: j=1:i=t1: ch~ else i-- - if i<1 then i=t1 else.if i>n then i=n: j++ - if j>n then j=i+2: i=n:ch~ - next - =a() // return array (as a pointer) - } + Module Global PrintArray(&Ar()) { + if dimension(Ar())<>2 then Error "This is for 2D arrays" + integer i, j, n=dimension(Ar(),1), n1=dimension(Ar(),2) + for i=1 to n + for j=1 to n1 + print Ar(i, j), + next + print + next + } + Function Global MakeArray(n as integer=5) { + dim a(1 to n, 1 to n) as integer=0 + integer i=1, j=1, z, t1=1 + boolean ch=true + for z=0 to n*n-1 + if ch then a(i,j)=z else a(j,i)=z + j++ + if j>t1 then t1++: j=1:i=t1: ch~ else i-- + if i<1 then i=t1 else.if i>n then i=n: j++ + if j>n then j=i+2: i=n:ch~ + next + =a() // return array (as a pointer) + } } Module Zig_Zag_Matrix (n as integer=5) { - Pen 15 {Report "matrix "+n+"x"+n} - integer old_column=tab - Print $(,4) // set column to 4 chars - if random(1,2)=2 then - dim ret() - ret()=makeArray(n) // this get a copy - else - object a=makeArray(n) // but this get the copy of pointer - link a to ret() // ret() is reference to a, to array - end if - PrintArray &ret() - Print $(,old_column) + Pen 15 {Report "matrix "+n+"x"+n} + integer old_column=tab + Print $(,4) // set column to 4 chars + if random(1,2)=2 then + dim ret() + ret()=makeArray(n) // this get a copy + else + object a=makeArray(n) // but this get the copy of pointer + link a to ret() // ret() is reference to a, to array + end if + PrintArray &ret() + Print $(,old_column) } Inline Code Lib1 // just execute the code from module lib1 like was here Form 60, 36 \\ console 60x36 characters diff --git a/Task/Zig-zag-matrix/OCaml/zig-zag-matrix.ocaml b/Task/Zig-zag-matrix/OCaml/zig-zag-matrix.ml similarity index 100% rename from Task/Zig-zag-matrix/OCaml/zig-zag-matrix.ocaml rename to Task/Zig-zag-matrix/OCaml/zig-zag-matrix.ml diff --git a/Task/Zig-zag-matrix/PARI-GP/zig-zag-matrix.parigp b/Task/Zig-zag-matrix/PARI-GP/zig-zag-matrix.parigp index a93e31960c..df0e984851 100644 --- a/Task/Zig-zag-matrix/PARI-GP/zig-zag-matrix.parigp +++ b/Task/Zig-zag-matrix/PARI-GP/zig-zag-matrix.parigp @@ -1,21 +1,21 @@ zz(n)={ - my(M=matrix(n,n),i,j,d=-1,start,end=n^2-1); - while(ct--, - M[i+1,j+1]=start; - M[n-i,n-j]=end; - start++; - end--; - i+=d; - j-=d; - if(i<0, - i++; - d=-d - , - if(j<0, - j++; - d=-d - ) - ); - if(start>end,return(M)) - ) + my(M=matrix(n,n),i,j,d=-1,start,end=n^2-1); + while(ct--, + M[i+1,j+1]=start; + M[n-i,n-j]=end; + start++; + end--; + i+=d; + j-=d; + if(i<0, + i++; + d=-d + , + if(j<0, + j++; + d=-d + ) + ); + if(start>end,return(M)) + ) }; diff --git a/Task/Zig-zag-matrix/PHP/zig-zag-matrix.php b/Task/Zig-zag-matrix/PHP/zig-zag-matrix.php index 22568a7742..361c32230b 100644 --- a/Task/Zig-zag-matrix/PHP/zig-zag-matrix.php +++ b/Task/Zig-zag-matrix/PHP/zig-zag-matrix.php @@ -1,32 +1,32 @@ function ZigZagMatrix($num) { $matrix = array(); for ($i = 0; $i < $num; $i++){ - $matrix[$i] = array(); - } - + $matrix[$i] = array(); + } + $i=1; - $j=1; + $j=1; for ($e = 0; $e < $num*$num; $e++) { $matrix[$i-1][$j-1] = $e; if (($i + $j) % 2 == 0) { if ($j < $num){ - $j++; - }else{ - $i += 2; - } + $j++; + }else{ + $i += 2; + } if ($i > 1){ - $i --; - } + $i --; + } } else { if ($i < $num){ - $i++; - }else{ - $j += 2; - } + $i++; + }else{ + $j += 2; + } if ($j > 1){ - $j --; - } + $j --; + } } } - return $matrix; + return $matrix; } diff --git a/Task/Zig-zag-matrix/Perl/zig-zag-matrix-2.pl b/Task/Zig-zag-matrix/Perl/zig-zag-matrix-2.pl index e5f772667d..32bd25a7a5 100644 --- a/Task/Zig-zag-matrix/Perl/zig-zag-matrix-2.pl +++ b/Task/Zig-zag-matrix/Perl/zig-zag-matrix-2.pl @@ -1,15 +1,15 @@ sub zig_zag { my ($w, $h, @r, $n) = @_; - $r[ $_->[1] ][ $_->[0] ] = $n++ for - sort { $a->[0] + $a->[1] <=> $b->[0] + $b->[1] or - ($a->[0] + $a->[1]) % 2 - ? $a->[1] <=> $b->[1] - : $a->[0] <=> $b->[0] - } - map { my $e = $_; - map{ [$e, $_] } 0 .. $w-1 - } 0 .. $h - 1; + $r[ $_->[1] ][ $_->[0] ] = $n++ for + sort { $a->[0] + $a->[1] <=> $b->[0] + $b->[1] or + ($a->[0] + $a->[1]) % 2 + ? $a->[1] <=> $b->[1] + : $a->[0] <=> $b->[0] + } + map { my $e = $_; + map{ [$e, $_] } 0 .. $w-1 + } 0 .. $h - 1; @r } diff --git a/Task/Zig-zag-matrix/PlainTeX/zig-zag-matrix.tex b/Task/Zig-zag-matrix/PlainTeX/zig-zag-matrix.tex index b535e75d99..d035ead110 100644 --- a/Task/Zig-zag-matrix/PlainTeX/zig-zag-matrix.tex +++ b/Task/Zig-zag-matrix/PlainTeX/zig-zag-matrix.tex @@ -1,22 +1,22 @@ \long\def\antefi#1#2\fi{#2\fi#1} \def\fornum#1=#2to#3(#4){% - \edef#1{\number\numexpr#2}\edef\fornumtemp{\noexpand\fornumi\expandafter\noexpand\csname fornum\string#1\endcsname - {\number\numexpr#3}{\ifnum\numexpr#4<0 <\else>\fi}{\number\numexpr#4}\noexpand#1}\fornumtemp + \edef#1{\number\numexpr#2}\edef\fornumtemp{\noexpand\fornumi\expandafter\noexpand\csname fornum\string#1\endcsname + {\number\numexpr#3}{\ifnum\numexpr#4<0 <\else>\fi}{\number\numexpr#4}\noexpand#1}\fornumtemp } \long\def\fornumi#1#2#3#4#5#6{\def#1{\unless\ifnum#5#3#2\relax\antefi{#6\edef#5{\number\numexpr#5+(#4)\relax}#1}\fi}#1} \def\elem(#1,#2){\numexpr(#1+#2)*(#1+#2-1)/2-(\ifodd\numexpr#1+#2\relax#1\else#2\fi)\relax} \def\zzmat#1{% - \noindent% quit vertical mode - \fornum\yy=1to#1(+1){% - \fornum\xx=1to#1(+1){% - \ifnum\numexpr\xx+\yy\relax<\numexpr#1+2\relax - \hbox to 2em{\hfil\number\elem(\xx,\yy)}% - \else - \hbox to 2em{\hfil\number\numexpr#1*#1-1-\elem(#1+1-\xx,#1+1-\yy)\relax}% - \fi - }% - \par\noindent% next line + quit vertical mode - }\par + \noindent% quit vertical mode + \fornum\yy=1to#1(+1){% + \fornum\xx=1to#1(+1){% + \ifnum\numexpr\xx+\yy\relax<\numexpr#1+2\relax + \hbox to 2em{\hfil\number\elem(\xx,\yy)}% + \else + \hbox to 2em{\hfil\number\numexpr#1*#1-1-\elem(#1+1-\xx,#1+1-\yy)\relax}% + \fi + }% + \par\noindent% next line + quit vertical mode + }\par } \zzmat{5} \bye diff --git a/Task/Zig-zag-matrix/Pluto/zig-zag-matrix.pluto b/Task/Zig-zag-matrix/Pluto/zig-zag-matrix.pluto new file mode 100644 index 0000000000..ce7ed1f91e --- /dev/null +++ b/Task/Zig-zag-matrix/Pluto/zig-zag-matrix.pluto @@ -0,0 +1,34 @@ +require "table2" +local fmt = require "fmt" + +local function zigzag(n) + local r = table.rep(n * n, 0) + local i = 0 + local n2 = n * 2 + for d = 1, n2 do + local x = d - n + if x < 0 then x = 0 end + local y = d - 1 + if y > n - 1 then y = n - 1 end + local j = n2 - d + if j > d then j = d end + for k = 0, j - 1 do + if d & 1 == 0 then + r[(x + k) * n + y - k + 1] = i + else + r[(y - k) * n + x + k + 1] = i + end + i += 1 + end + end + return r +end + +local n = 5 +local w = #tostring(n * n - 1) +local i = 0 +for zigzag(n) as e do + fmt.write($"%{w}d ", e) + if i % n == n - 1 then print() end + i += 1 +end diff --git a/Task/Zig-zag-matrix/PowerShell/zig-zag-matrix-1.psh b/Task/Zig-zag-matrix/PowerShell/zig-zag-matrix-1.ps1 similarity index 100% rename from Task/Zig-zag-matrix/PowerShell/zig-zag-matrix-1.psh rename to Task/Zig-zag-matrix/PowerShell/zig-zag-matrix-1.ps1 diff --git a/Task/Zig-zag-matrix/PowerShell/zig-zag-matrix-2.psh b/Task/Zig-zag-matrix/PowerShell/zig-zag-matrix-2.ps1 similarity index 100% rename from Task/Zig-zag-matrix/PowerShell/zig-zag-matrix-2.psh rename to Task/Zig-zag-matrix/PowerShell/zig-zag-matrix-2.ps1 diff --git a/Task/Zig-zag-matrix/Prolog/zig-zag-matrix.pro b/Task/Zig-zag-matrix/Prolog/zig-zag-matrix.pro index 1a1c782cdb..712d5c6e2e 100644 --- a/Task/Zig-zag-matrix/Prolog/zig-zag-matrix.pro +++ b/Task/Zig-zag-matrix/Prolog/zig-zag-matrix.pro @@ -1,31 +1,31 @@ zig_zag(N) :- - zig_zag(N, N). + zig_zag(N, N). % compute zig_zag for a matrix of Lig lines of Col columns zig_zag(Lig, Col) :- - length(M, Lig), - maplist(init(Col), M), - fill(M, 0, 0, 0, Lig, Col, up), - % display the matrix - maplist(print_line, M). + length(M, Lig), + maplist(init(Col), M), + fill(M, 0, 0, 0, Lig, Col, up), + % display the matrix + maplist(print_line, M). fill(M, Cur, L, C, NL, NC, _) :- - L is NL - 1, - C is NC - 1, - nth0(L, M, Line), - nth0(C, Line, Cur). + L is NL - 1, + C is NC - 1, + nth0(L, M, Line), + nth0(C, Line, Cur). fill(M, Cur, L, C, NL, NC, Sens) :- - nth0(L, M, Line), - nth0(C, Line, Cur), - Cur1 is Cur + 1, - compute_next(NL, NC, L, C, Sens, L1, C1, Sens1), - fill(M, Cur1, L1, C1, NL, NC, Sens1). + nth0(L, M, Line), + nth0(C, Line, Cur), + Cur1 is Cur + 1, + compute_next(NL, NC, L, C, Sens, L1, C1, Sens1), + fill(M, Cur1, L1, C1, NL, NC, Sens1). init(N, L) :- - length(L, N). + length(L, N). % compute_next % arg1 : Number of lnes of the matrix @@ -37,41 +37,41 @@ init(N, L) :- % arg7 : next column % arg8 : next direction of movement compute_next(_NL, NC, 0, Col, up, 0, Col1, down) :- - Col < NC - 1, - Col1 is Col+1. + Col < NC - 1, + Col1 is Col+1. compute_next(_NL, NC, 0, Col, up, 1, Col, down) :- - Col is NC - 1. + Col is NC - 1. compute_next(NL, _NC, Lig, 0, down, Lig1, 0, up) :- - Lig < NL - 1, - Lig1 is Lig+1. + Lig < NL - 1, + Lig1 is Lig+1. compute_next(NL, _NC, Lig, 0, down, Lig, 1, up) :- - Lig is NL - 1. + Lig is NL - 1. compute_next(NL, _NC, Lig, Col, down, Lig1, Col1, down) :- - Lig < NL - 1, - Lig1 is Lig + 1, - Col1 is Col-1. + Lig < NL - 1, + Lig1 is Lig + 1, + Col1 is Col-1. compute_next(NL, _NC, Lig, Col, down, Lig, Col1, up) :- - Lig is NL - 1, - Col1 is Col+1. + Lig is NL - 1, + Col1 is Col+1. compute_next(_NL, NC, Lig, Col, up, Lig1, Col1, up) :- - Col < NC - 1, - Lig1 is Lig - 1, - Col1 is Col+1. + Col < NC - 1, + Lig1 is Lig - 1, + Col1 is Col+1. compute_next(_NL, NC, Lig, Col, up, Lig1, Col, down) :- - Col is NC - 1, - Lig1 is Lig + 1. + Col is NC - 1, + Lig1 is Lig + 1. print_line(L) :- - maplist(print_val, L), - nl. + maplist(print_val, L), + nl. print_val(V) :- - writef('%3r ', [V]). + writef('%3r ', [V]). diff --git a/Task/Zig-zag-matrix/Python/zig-zag-matrix-4.py b/Task/Zig-zag-matrix/Python/zig-zag-matrix-4.py index 94685fa5e3..192c849a40 100644 --- a/Task/Zig-zag-matrix/Python/zig-zag-matrix-4.py +++ b/Task/Zig-zag-matrix/Python/zig-zag-matrix-4.py @@ -1,16 +1,20 @@ COLS = 9 + def CX(x, ran): - while True: - x += 2 * next(ran) - yield x - x += 1 - yield x + for y in ran: + x += 2 * y + yield x + x += 1 + yield x + ran = [] d = -1 -for V in CX(1,iter(list(range(0,COLS,2)) + list(range(COLS-1-COLS%2,0,-2)))): - ran.append(iter(range(V, V+COLS*d, d))) - d *= -1 -for x in range(0,COLS): - for y in range(x, x+COLS): - print(repr(next(ran[y])).rjust(3), end = ' ') - print() + +for V in CX(1, iter(list(range(0, COLS, 2)) + list(range(COLS - 1 - COLS % 2, 0, -2)))): + ran.append(iter(range(V, V + COLS * d, d))) + d *= -1 + +for x in range(0, COLS): + for y in range(x, x + COLS): + print(repr(next(ran[y])).rjust(3), end=" ") + print() diff --git a/Task/Zig-zag-matrix/Raku/zig-zag-matrix.raku b/Task/Zig-zag-matrix/Raku/zig-zag-matrix.raku index b340b9d204..c054b11562 100644 --- a/Task/Zig-zag-matrix/Raku/zig-zag-matrix.raku +++ b/Task/Zig-zag-matrix/Raku/zig-zag-matrix.raku @@ -43,21 +43,21 @@ sub MAIN(Int $size = 5) { my $t = Turtle.new(dir => 1); my $counter = 0; for 1 ..^ $size -> $run { - for ^$run { - $t.lay-egg($counter++); - $t.forward; - } - my $yaw = $run %% 2 ?? -1 !! 1; - $t.turn-right($yaw * 135); $t.forward; $t.turn-right($yaw * 45); + for ^$run { + $t.lay-egg($counter++); + $t.forward; + } + my $yaw = $run %% 2 ?? -1 !! 1; + $t.turn-right($yaw * 135); $t.forward; $t.turn-right($yaw * 45); } for $size ... 1 -> $run { - for ^$run -> $ { - $t.lay-egg($counter++); - $t.forward; - } - $t.turn-left(180); $t.forward; - my $yaw = $run %% 2 ?? 1 !! -1; - $t.turn-right($yaw * 45); $t.forward; $t.turn-left($yaw * 45); + for ^$run -> $ { + $t.lay-egg($counter++); + $t.forward; + } + $t.turn-left(180); $t.forward; + my $yaw = $run %% 2 ?? 1 !! -1; + $t.turn-right($yaw * 45); $t.forward; $t.turn-left($yaw * 45); } $t.showmap; } diff --git a/Task/Zig-zag-matrix/Rascal/zig-zag-matrix-3.rascal b/Task/Zig-zag-matrix/Rascal/zig-zag-matrix-3.rascal index 40664a5bff..82b6cf9c41 100644 --- a/Task/Zig-zag-matrix/Rascal/zig-zag-matrix-3.rascal +++ b/Task/Zig-zag-matrix/Rascal/zig-zag-matrix-3.rascal @@ -6,17 +6,17 @@ import IO; alias cd = tuple[int,int]; public rel[cd, int] zz(int n){ - indexorder = sort([| x <- [0..n], y <- [0..n]], - bool (cd a, cd b){ - if (a[0]+a[1] > b[0]+b[1]) - return false; - elseif(a[0] < b[0]) - return false; - else - return true; - ; - }); - return { | z <- index(indexorder)}; + indexorder = sort([| x <- [0..n], y <- [0..n]], + bool (cd a, cd b){ + if (a[0]+a[1] > b[0]+b[1]) + return false; + elseif(a[0] < b[0]) + return false; + else + return true; + ; + }); + return { | z <- index(indexorder)}; } public void printzz(rel[cd, int] myarray){ diff --git a/Task/Zig-zag-matrix/Rebol/zig-zag-matrix-1.rebol b/Task/Zig-zag-matrix/Rebol/zig-zag-matrix-1.rebol new file mode 100644 index 0000000000..5cf3812b6b --- /dev/null +++ b/Task/Zig-zag-matrix/Rebol/zig-zag-matrix-1.rebol @@ -0,0 +1,46 @@ +Rebol [ + title: "Rosetta code: Zig-zag matrix" + file: %Zig-zag_matrix.r3 + url: https://rosettacode.org/wiki/Zig-zag_matrix +] + +zig-zag-matrix: function [size [integer!]][ + matrix: array/initial size * size 0 ;; Flat array, row-major + n: 0 ;; Current value to assign + ;; Traverse (2 * size - 1) diagonals + repeat d (size * 2) - 1 [ + either even? d [ + ;; For even diagonals, go from bottom to top + x: min d size + y: d + 1 - x + while [all [ + x >= 1 + y <= size + ]][ + pos: (y - 1) * size + x + matrix/:pos: n + ++ n + -- x + ++ y + ] + ][ ;; For odd diagonals, go top to bottom + y: min d size + x: d + 1 - y + while [all [ + y >= 1 + x <= size + ]][ + pos: (y - 1) * size + x + matrix/:pos: n + ++ n + -- y + ++ x + ] + ] + ] + new-line/skip matrix true size + matrix +] + +;; Example usage: +probe zig-zag-matrix 5 diff --git a/Task/Zig-zag-matrix/Rebol/zig-zag-matrix-2.rebol b/Task/Zig-zag-matrix/Rebol/zig-zag-matrix-2.rebol new file mode 100644 index 0000000000..684485aedf --- /dev/null +++ b/Task/Zig-zag-matrix/Rebol/zig-zag-matrix-2.rebol @@ -0,0 +1,18 @@ +zig-zag-matrix: function [size [integer!]][ + matrix: array/initial len: size * size 0 ;; Flat array, row-major + x: 0 dx: -1 + y: 0 dy: 1 + repeat i len [ + case [ + x >= size [-- x y: y + 2 dx: negate dx dy: negate dy] + y >= size [-- y x: x + 2 dx: negate dx dy: negate dy] + all [y >= 0 x < 0][++ x dx: negate dx dy: negate dy] + all [x >= 0 y < 0][++ y dx: negate dx dy: negate dy] + ] + matrix/(y * size + x + 1): i - 1 + x: x + dx + y: y + dy + ] + new-line/skip matrix true size + matrix +] diff --git a/Task/Zig-zag-matrix/Rust/zig-zag-matrix.rust b/Task/Zig-zag-matrix/Rust/zig-zag-matrix.rs similarity index 100% rename from Task/Zig-zag-matrix/Rust/zig-zag-matrix.rust rename to Task/Zig-zag-matrix/Rust/zig-zag-matrix.rs diff --git a/Task/Zig-zag-matrix/Standard-ML/zig-zag-matrix.ml b/Task/Zig-zag-matrix/Standard-ML/zig-zag-matrix.ml index 6e189b29d6..bf9b4016f9 100644 --- a/Task/Zig-zag-matrix/Standard-ML/zig-zag-matrix.ml +++ b/Task/Zig-zag-matrix/Standard-ML/zig-zag-matrix.ml @@ -7,11 +7,11 @@ fun sign t = if t mod 2 = 0 then ~1 else 1; fun zag n = List.tabulate (n, fn i=> rev ( List.tabulate (n, fn j => - let val t = n-j+i and u = n+j-i in - if i <= j + let val t = n-j+i and u = n+j-i in + if i <= j then t*t div 2 + sign t * ( t div 2 - i ) else n*n - 1 - ( u*u div 2 + sign u * ( u div 2 - n + 1 + i) ) - end - ))); + end + ))); zig zag 5 ; diff --git a/Task/Zig-zag-matrix/Stata/zig-zag-matrix-1.stata b/Task/Zig-zag-matrix/Stata/zig-zag-matrix-1.stata index 26ef572864..5c6d4776a8 100644 --- a/Task/Zig-zag-matrix/Stata/zig-zag-matrix-1.stata +++ b/Task/Zig-zag-matrix/Stata/zig-zag-matrix-1.stata @@ -1,14 +1,14 @@ function zigzag1(n) { - j = 0::n-1 - u = J(1, n, (-1, 1)) - v = (j:*(2:*j:+3)) - v = rowshape((v,v:+1), 1) - a = J(n, n, .) - for (i=1; i<=n; i++) { - a[i, .] = v[j:+i] - v = v+u - } - return(a) + j = 0::n-1 + u = J(1, n, (-1, 1)) + v = (j:*(2:*j:+3)) + v = rowshape((v,v:+1), 1) + a = J(n, n, .) + for (i=1; i<=n; i++) { + a[i, .] = v[j:+i] + v = v+u + } + return(a) } zigzag1(5) diff --git a/Task/Zig-zag-matrix/Stata/zig-zag-matrix-2.stata b/Task/Zig-zag-matrix/Stata/zig-zag-matrix-2.stata index dacef6d51e..de0ee06138 100644 --- a/Task/Zig-zag-matrix/Stata/zig-zag-matrix-2.stata +++ b/Task/Zig-zag-matrix/Stata/zig-zag-matrix-2.stata @@ -1,10 +1,10 @@ function zigzag2(n) { - a = zigzag1(n) - v = (1..n-1):^2 - for (i=1; i 1 Then - i = i - 1 - End If - Else - If i < n Then - i = i + 1 - Else - j = j + 2 - End If - If j > 1 Then - j = j - 1 - End If - End If - Next - For k = 0 To n-1 - For l = 0 To n-1 - WScript.StdOut.Write Right(" " & arrZ(k,l),3) - Next - WScript.StdOut.WriteLine - Next -End Function diff --git a/Task/Zig-zag-matrix/VBScript/zig-zag-matrix.vbs b/Task/Zig-zag-matrix/VBScript/zig-zag-matrix.vbs new file mode 100644 index 0000000000..234446afac --- /dev/null +++ b/Task/Zig-zag-matrix/VBScript/zig-zag-matrix.vbs @@ -0,0 +1,36 @@ +ZigZag(Cint(WScript.Arguments(0))) + +Function ZigZag(n) + Dim arrZ() + ReDim arrZ(n-1,n-1) + i = 1 + j = 1 + For e = 0 To (n^2) - 1 + arrZ(i-1,j-1) = e + If ((i + j ) And 1) = 0 Then + If j < n Then + j = j + 1 + Else + i = i + 2 + End If + If i > 1 Then + i = i - 1 + End If + Else + If i < n Then + i = i + 1 + Else + j = j + 2 + End If + If j > 1 Then + j = j - 1 + End If + End If + Next + For k = 0 To n-1 + For l = 0 To n-1 + WScript.StdOut.Write Right(" " & arrZ(k,l),3) + Next + WScript.StdOut.WriteLine + Next +End Function diff --git a/Task/Zig-zag-matrix/YAMLScript/zig-zag-matrix.ys b/Task/Zig-zag-matrix/YAMLScript/zig-zag-matrix.ys new file mode 100644 index 0000000000..f1828e2882 --- /dev/null +++ b/Task/Zig-zag-matrix/YAMLScript/zig-zag-matrix.ys @@ -0,0 +1,34 @@ +!YS-v0 + +defn main(n=10): + gprint: + zig-zag: n + +defn gprint(grid): + f =: (" %$(grid.$.$.digits().#)d" * grid.#) + each line grid: + say: format(f line*) + +defn zig-zag(n): + take-from n: + map \(_1 _2) cycle([reverse a]): + partitions _ range(n:sqr): + concat (1 .. n): (n.-- .. -1) + +defn take-from(n colls): + lazy-seq: + when-let s seq(colls): + first-n rest-n =: split-at(n s) + cons map(first first-n): + take-from n: + concat _ rest-n: + filter seq: + map rest: first-n + +defn partitions(sizes coll): + lazy-seq: + when-let n sizes.0: + when-let s seq(coll): + cons take(n coll): + partitions next(sizes): + drop n: coll diff --git a/Task/Zumkeller-numbers/Arturo/zumkeller-numbers.arturo b/Task/Zumkeller-numbers/Arturo/zumkeller-numbers.arturo new file mode 100644 index 0000000000..4e978ca0d6 --- /dev/null +++ b/Task/Zumkeller-numbers/Arturo/zumkeller-numbers.arturo @@ -0,0 +1,27 @@ +prettyPrint: function [data,cols,padding][ + data | split.every: cols + | map => [join map & 'x -> pad to :string x padding] + | print.lines +] + +zumkeller?: function [n][ + divSum: sum divs: <= factors n + if nand? [even? divSum][divSum >= 2*n] -> return false + + half: divSum/2 + loop 1..(size divs)/2 'combiSize [ + if some? combine.by:combiSize divs 'combo -> + half = sum combo -> + return true + ] + + return false +] + +print "First 220 Zumkeller numbers:" +(1..∞) | select.first: 220 => zumkeller? + | prettyPrint 14 4 + +print "\nFirst 40 odd Zumkeller numbers:" +(1..∞) | select.first: 40 'n -> and? [odd? n][zumkeller? n] + | prettyPrint 10 6 diff --git a/Task/Zumkeller-numbers/EasyLang/zumkeller-numbers.easy b/Task/Zumkeller-numbers/EasyLang/zumkeller-numbers.easy index 350228b3f3..3e1093d7d1 100644 --- a/Task/Zumkeller-numbers/EasyLang/zumkeller-numbers.easy +++ b/Task/Zumkeller-numbers/EasyLang/zumkeller-numbers.easy @@ -1,40 +1,26 @@ -proc divisors n . divs[] . +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 - . + if i <> j : divs[] &= j . . . func ispartsum divs[] sum . - if sum = 0 - return 1 - . - if len divs[] = 0 - return 0 - . + if sum = 0 : return 1 + if len divs[] = 0 : return 0 last = divs[len divs[]] len divs[] -1 - if last > sum - return ispartsum divs[] sum - . - if ispartsum divs[] sum = 1 - return 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 - . + 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 diff --git a/Task/Zumkeller-numbers/FreeBASIC/zumkeller-numbers.basic b/Task/Zumkeller-numbers/FreeBASIC/zumkeller-numbers.basic new file mode 100644 index 0000000000..86bd18ebfb --- /dev/null +++ b/Task/Zumkeller-numbers/FreeBASIC/zumkeller-numbers.basic @@ -0,0 +1,96 @@ +' Function to get divisors of a number +Sub getDivisors(n As Integer, divs() As Integer) + Redim divs(1) + divs(0) = 1 + divs(1) = n + Dim As Integer i = 2, j + While i * i <= n + If n Mod i = 0 Then + j = n \ i + Redim Preserve divs(Ubound(divs) + 1) + divs(Ubound(divs)) = i + If i <> j Then + Redim Preserve divs(Ubound(divs) + 1) + divs(Ubound(divs)) = j + End If + End If + i += 1 + Wend +End Sub + +' Function to check if a sum can be formed by a subset of divisors +Function isPartSum(divs() As Integer, sum As Integer) As Boolean + If sum = 0 Then Return True + + Dim le As Integer = Ubound(divs) + 1 + If le = 0 Then Return False + + Dim last As Integer = divs(le - 1) + Dim newDivs(le - 2) As Integer + For i As Integer = 0 To le - 2 + newDivs(i) = divs(i) + Next + If last > sum Then Return isPartSum(newDivs(), sum) + + Return isPartSum(newDivs(), sum) Orelse isPartSum(newDivs(), sum - last) +End Function + +' Function to check if a number is a Zumkeller number +Function isZumkeller(n As Integer) As Boolean + Dim divs() As Integer + getDivisors(n, divs()) + Dim sum As Integer = 0 + For i As Integer = 0 To Ubound(divs) + sum += divs(i) + Next + ' if sum is odd can't be split into two partitions with equal sums + If sum Mod 2 = 1 Then Return False + ' if n is odd use 'abundant odd number' optimization + If n Mod 2 = 1 Then + Dim abundance As Integer = sum - 2 * n + Return abundance > 0 Andalso abundance Mod 2 = 0 + End If + ' if n and sum are both even check if there's a partition which totals sum / 2 + Return isPartSum(divs(), sum \ 2) +End Function + +Sub main() + Print "The first 220 Zumkeller numbers are:" + Dim As Integer i = 2 + Dim As Integer cnt = 0 + While cnt < 220 + If isZumkeller(i) Then + Print Using "### "; i; + cnt += 1 + If cnt Mod 20 = 0 Then Print + End If + i += 1 + Wend + + Print !"\nThe first 40 odd Zumkeller numbers are:" + i = 3 + cnt = 0 + While cnt < 40 + If isZumkeller(i) Then + Print Using "##### "; i; + cnt += 1 + If cnt Mod 10 = 0 Then Print + End If + i += 2 + Wend + + Print !"\nThe first 40 odd Zumkeller numbers which don't end in 5 are:" + i = 3 + cnt = 0 + While cnt < 40 + If i Mod 10 <> 5 Andalso isZumkeller(i) Then + Print Using "####### "; i; + cnt += 1 + If cnt Mod 8 = 0 Then Print + End If + i += 2 + Wend +End Sub + +main() +Sleep diff --git a/Task/Zumkeller-numbers/Julia/zumkeller-numbers.julia b/Task/Zumkeller-numbers/Julia/zumkeller-numbers.jl similarity index 100% rename from Task/Zumkeller-numbers/Julia/zumkeller-numbers.julia rename to Task/Zumkeller-numbers/Julia/zumkeller-numbers.jl diff --git a/Task/Zumkeller-numbers/Kotlin/zumkeller-numbers.kotlin b/Task/Zumkeller-numbers/Kotlin/zumkeller-numbers.kts similarity index 100% rename from Task/Zumkeller-numbers/Kotlin/zumkeller-numbers.kotlin rename to Task/Zumkeller-numbers/Kotlin/zumkeller-numbers.kts diff --git a/Task/Zumkeller-numbers/Rust/zumkeller-numbers.rust b/Task/Zumkeller-numbers/Rust/zumkeller-numbers.rs similarity index 100% rename from Task/Zumkeller-numbers/Rust/zumkeller-numbers.rust rename to Task/Zumkeller-numbers/Rust/zumkeller-numbers.rs diff --git a/Task/Zumkeller-numbers/V-(Vlang)/zumkeller-numbers.v b/Task/Zumkeller-numbers/V-(Vlang)/zumkeller-numbers.v index 9b49f1c3f3..c512c9e932 100644 --- a/Task/Zumkeller-numbers/V-(Vlang)/zumkeller-numbers.v +++ b/Task/Zumkeller-numbers/V-(Vlang)/zumkeller-numbers.v @@ -30,7 +30,7 @@ fn is_part_sum(d []int, sum int) bool { return false } last := divs[le-1] - divs = divs[0 .. le-1] + divs = divs[0 .. le-1].clone() if last > sum { return is_part_sum(divs, sum) }